@lunora/platform-node 1.0.0-alpha.223 → 1.0.0-alpha.225

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -55,7 +55,11 @@ declare const drainTogether: (parts: ReadonlyArray<Drainable>, options?: DrainOp
55
55
  interface NodeDispatchInvocation {
56
56
  args: Record<string, unknown>;
57
57
  functionPath: string;
58
- /** The scheduler record or delivery id, used as the shard's idempotency key. */
58
+ /**
59
+ * The shard's idempotency key: the scheduler's per-record `dedupKey` when the body carries one,
60
+ * else the record or delivery id. A scheduler id is free again once its job settles, so the bare
61
+ * id would answer a reused id's new job from the previous job's dedup row.
62
+ */
59
63
  id: string | undefined;
60
64
  /** Identity the trusted caller forwarded, if any. */
61
65
  identity: {
package/dist/index.d.ts CHANGED
@@ -55,7 +55,11 @@ declare const drainTogether: (parts: ReadonlyArray<Drainable>, options?: DrainOp
55
55
  interface NodeDispatchInvocation {
56
56
  args: Record<string, unknown>;
57
57
  functionPath: string;
58
- /** The scheduler record or delivery id, used as the shard's idempotency key. */
58
+ /**
59
+ * The shard's idempotency key: the scheduler's per-record `dedupKey` when the body carries one,
60
+ * else the record or delivery id. A scheduler id is free again once its job settles, so the bare
61
+ * id would answer a reused id's new job from the previous job's dedup row.
62
+ */
59
63
  id: string | undefined;
60
64
  /** Identity the trusted caller forwarded, if any. */
61
65
  identity: {
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{DEFAULT_DRAIN_TIMEOUT_MS as o,drainTogether as t}from"./packem_shared/DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{checkNodeAppHost as c,createNodeAppHost as d}from"./packem_shared/checkNodeAppHost-Cv5p7igg.mjs";import{N,c as f}from"./packem_shared/node-dispatch-route-B3GAZkHT.mjs";import{createNodeDurableObjectFactory as x}from"./packem_shared/createNodeDurableObjectFactory-hAwJt_pN.mjs";import{createNodeGlobalStore as s,createNodeSqlExec as H}from"./packem_shared/createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeHttpServer as h}from"./packem_shared/createNodeHttpServer-cUx4J9Z9.mjs";import{createNodeHyperdrive as D}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as u}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeMailHost as E}from"./packem_shared/createNodeMailHost-DrUo8de-.mjs";import{createNodePlatform as _}from"./packem_shared/createNodePlatform-De8dIBya.mjs";import{createNodeProfileHandler as R}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as P}from"./packem_shared/createNodeQueueHost-glQ8GNCA.mjs";import{createNodeR2Bucket as v}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as I}from"./packem_shared/createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeSecretBindings as O}from"./packem_shared/createNodeSecretBindings-C7wh0fOm.mjs";import{createNodeShardHost as w}from"./packem_shared/createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardNamespace as C}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as L}from"./packem_shared/createNodeShardRegistry-D1r6M8Rg.mjs";import{bindShardSockets as j,createNodeShardState as q}from"./packem_shared/bindShardSockets-DjLmRlIA.mjs";import{createNodeSocketHost as K}from"./packem_shared/createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as z}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as V}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{o as DEFAULT_DRAIN_TIMEOUT_MS,N as NODE_SCHEDULER_DISPATCH_PATH,j as bindShardSockets,c as checkNodeAppHost,d as createNodeAppHost,f as createNodeDispatchRoute,x as createNodeDurableObjectFactory,s as createNodeGlobalStore,h as createNodeHttpServer,D as createNodeHyperdrive,E as createNodeMailHost,_ as createNodePlatform,R as createNodeProfileHandler,P as createNodeQueueHost,v as createNodeR2Bucket,I as createNodeSchedulerHost,O as createNodeSecretBindings,w as createNodeShardHost,u as createNodeShardKvStore,C as createNodeShardNamespace,L as createNodeShardRegistry,q as createNodeShardState,K as createNodeSocketHost,H as createNodeSqlExec,z as createNodeWorkflowHost,V as createNodeWorkflowStore,t as drainTogether};
1
+ import{DEFAULT_DRAIN_TIMEOUT_MS as o,drainTogether as t}from"./packem_shared/DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{checkNodeAppHost as c,createNodeAppHost as d}from"./packem_shared/checkNodeAppHost-CdSUcgPi.mjs";import{N,c as f}from"./packem_shared/node-dispatch-route-qngKbRsA.mjs";import{createNodeDurableObjectFactory as x}from"./packem_shared/createNodeDurableObjectFactory-hAwJt_pN.mjs";import{createNodeGlobalStore as s,createNodeSqlExec as H}from"./packem_shared/createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeHttpServer as h}from"./packem_shared/createNodeHttpServer-cUx4J9Z9.mjs";import{createNodeHyperdrive as D}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as u}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeMailHost as E}from"./packem_shared/createNodeMailHost-DrUo8de-.mjs";import{createNodePlatform as _}from"./packem_shared/createNodePlatform-CGOXeyXQ.mjs";import{createNodeProfileHandler as R}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as P}from"./packem_shared/createNodeQueueHost-glQ8GNCA.mjs";import{createNodeR2Bucket as v}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as I}from"./packem_shared/createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeSecretBindings as O}from"./packem_shared/createNodeSecretBindings-C7wh0fOm.mjs";import{createNodeShardHost as w}from"./packem_shared/createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardNamespace as C}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as L}from"./packem_shared/createNodeShardRegistry-D1r6M8Rg.mjs";import{bindShardSockets as j,createNodeShardState as q}from"./packem_shared/bindShardSockets-DjLmRlIA.mjs";import{createNodeSocketHost as K}from"./packem_shared/createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as z}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as V}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{o as DEFAULT_DRAIN_TIMEOUT_MS,N as NODE_SCHEDULER_DISPATCH_PATH,j as bindShardSockets,c as checkNodeAppHost,d as createNodeAppHost,f as createNodeDispatchRoute,x as createNodeDurableObjectFactory,s as createNodeGlobalStore,h as createNodeHttpServer,D as createNodeHyperdrive,E as createNodeMailHost,_ as createNodePlatform,R as createNodeProfileHandler,P as createNodeQueueHost,v as createNodeR2Bucket,I as createNodeSchedulerHost,O as createNodeSecretBindings,w as createNodeShardHost,u as createNodeShardKvStore,C as createNodeShardNamespace,L as createNodeShardRegistry,q as createNodeShardState,K as createNodeSocketHost,H as createNodeSqlExec,z as createNodeWorkflowHost,V as createNodeWorkflowStore,t as drainTogether};
@@ -1 +1 @@
1
- import{N as o,c as r,a as t}from"./node-dispatch-route-B3GAZkHT.mjs";export{o as NODE_SCHEDULER_DISPATCH_PATH,r as createNodeDispatchRoute,t as createShardInvoke};
1
+ import{N as o,c as r,a as t}from"./node-dispatch-route-qngKbRsA.mjs";export{o as NODE_SCHEDULER_DISPATCH_PATH,r as createNodeDispatchRoute,t as createShardInvoke};
@@ -1 +1 @@
1
- import{mkdirSync as p,existsSync as m,realpathSync as h,lstatSync as g}from"node:fs";import{join as f,relative as y,isAbsolute as O}from"node:path";import{LunoraError as i}from"@lunora/errors";import{drainTimeoutMs as k,drainTogether as A,startDrainDeadline as R,settlesBefore as D}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeDurableObjectFactory as $}from"./createNodeDurableObjectFactory-hAwJt_pN.mjs";import{walkDeclaredCrons as N,createNodePlatform as v}from"./createNodePlatform-De8dIBya.mjs";import{createNodeShardNamespace as I}from"./createNodeShardNamespace-BgQjDv7V.mjs";const w=e=>{const r=new Set;let a=0;const t=()=>{const n=a===0?[]:[`${String(a)} ${e.label} failed`];return a=0,n},o=()=>r.size===0?[]:[`${String(r.size)} ${e.label}`];return{drain:async n=>{const c=R(n);try{for(;r.size>0;)if(!await D(Promise.all(r),c))return{failed:t(),pending:o(),timedOut:!0};return{failed:t(),pending:[],timedOut:!1}}finally{c.cancel()}},idle:()=>r.size===0,pending:o,track:n=>{const c=Promise.resolve(n).then(()=>{},d=>{e.reportFailures&&(a+=1,console.error("[@lunora/platform-node] work handed to waitUntil failed:",d))}).finally(()=>r.delete(c));r.add(c)}}},b=e=>{const r=[];for(const a of e)try{a.close({force:!0})}catch(t){r.push(t)}if(r.length>0)throw new AggregateError(r,`@lunora/platform-node: ${String(r.length)} platform(s) failed to close`)},S=e=>typeof e=="object"&&e!==null&&typeof e.fetch=="function",j=(e,r,a,t)=>{const o=$(r.worker[e.className],a);return v({crons:e.name===t?r.crons??{}:void 0,directory:r.dataDirectory===void 0?void 0:f(r.dataDirectory,e.name),onAlarm:async n=>{n!==void 0&&await(await o(n)).alarm?.()},onFetch:async(n,c)=>(await o(c)).fetch(n),path:r.dataDirectory===void 0?void 0:f(r.dataDirectory,`${e.name}.platform.sqlite3`)})},E=/^[A-Za-z_$][\w$]*$/u,L=(e,r)=>{const a=y(e,r);return a!==""&&!a.startsWith("..")&&!O(a)},T=(e,r)=>{if(!E.test(e))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${JSON.stringify(e)} is not a valid binding name (a JavaScript identifier such as SHARD), and its name becomes a directory under the data directory`);if(r===void 0||!m(r))return;const a=h(r);for(const t of[f(r,e),f(r,`${e}.platform.sqlite3`)]){let o;try{o=g(t)}catch{continue}if(o.isSymbolicLink()&&!m(t))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${e} would store data outside ${r}: ${t} is a link to nothing, which SQLite would follow`);if(!L(a,h(t)))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${e} would store data outside ${r}: ${t} links out of it`)}},_=e=>{const r=new Map;for(const{name:a}of e){const t=r.get(a.toLowerCase());if(t!==void 0)throw new i("VALIDATION_ERROR",t===a?`@lunora/platform-node: Durable Object binding ${a} is declared twice, and both would share one shard directory and platform database`:`@lunora/platform-node: Durable Object bindings ${t} and ${a} differ only in case, so on a case-insensitive volume they would share one shard directory and platform database — rename one`);r.set(a.toLowerCase(),a)}},P=e=>{if(typeof e!="function")return!1;try{return Reflect.construct(String,[],e),!0}catch{return!1}},x=e=>{if(!S(e.worker.default))throw new i("VALIDATION_ERROR","@lunora/platform-node: the worker module has no default export with a `fetch` handler");_(e.durableObjects);for(const t of e.durableObjects){T(t.name,e.dataDirectory);const o=Object.hasOwn(e.worker,t.className)?e.worker[t.className]:void 0;if(o===void 0)throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${t.name} names class ${t.className}, which the worker module does not export`);if(!P(o))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${t.name} names ${t.className}, which the worker module exports as something \`new\` cannot construct`)}const r=e.shardBinding??"SHARD";if(N(e.crons??{}).length>0&&!e.durableObjects.some(t=>t.name===r))throw new i("VALIDATION_ERROR",`@lunora/platform-node: the app declares crons, but no Durable Object binding is named ${r} to run them on`)},M=e=>{x(e);const r=e.worker.default,a={...e.env},t=[],o=w({label:"worker waitUntil task(s)",reportFailures:!0}),n=w({label:"worker request(s)",reportFailures:!1}),c=e.shardBinding??"SHARD";e.dataDirectory!==void 0&&p(e.dataDirectory,{recursive:!0});try{for(const s of e.durableObjects){const l=j(s,e,a,c);t.push(l),Object.defineProperty(a,s.name,{configurable:!0,enumerable:!0,value:I(l.directory),writable:!0})}}catch(s){try{b(t.splice(0))}catch(l){console.error("[@lunora/platform-node] closing the platforms of a host that failed to compose failed:",l)}throw s}const d={passThroughOnException:()=>{},waitUntil:o.track};let u;return{close:async s=>(k(s),u??=(async()=>{try{return await A([n,o,...t],s)}finally{b(t.splice(0))}})(),u),fetch:async s=>{const l=Promise.resolve(r.fetch(s,a,d));return n.track(l),l},rearmPersistedAlarms:()=>t.flatMap(s=>s.rearmPersistedAlarms())}};export{x as checkNodeAppHost,M as createNodeAppHost};
1
+ import{mkdirSync as p,existsSync as m,realpathSync as h,lstatSync as g}from"node:fs";import{join as f,relative as y,isAbsolute as O}from"node:path";import{LunoraError as i}from"@lunora/errors";import{drainTimeoutMs as k,drainTogether as A,startDrainDeadline as R,settlesBefore as D}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeDurableObjectFactory as $}from"./createNodeDurableObjectFactory-hAwJt_pN.mjs";import{walkDeclaredCrons as N,createNodePlatform as v}from"./createNodePlatform-CGOXeyXQ.mjs";import{createNodeShardNamespace as I}from"./createNodeShardNamespace-BgQjDv7V.mjs";const w=e=>{const r=new Set;let a=0;const t=()=>{const n=a===0?[]:[`${String(a)} ${e.label} failed`];return a=0,n},o=()=>r.size===0?[]:[`${String(r.size)} ${e.label}`];return{drain:async n=>{const c=R(n);try{for(;r.size>0;)if(!await D(Promise.all(r),c))return{failed:t(),pending:o(),timedOut:!0};return{failed:t(),pending:[],timedOut:!1}}finally{c.cancel()}},idle:()=>r.size===0,pending:o,track:n=>{const c=Promise.resolve(n).then(()=>{},d=>{e.reportFailures&&(a+=1,console.error("[@lunora/platform-node] work handed to waitUntil failed:",d))}).finally(()=>r.delete(c));r.add(c)}}},b=e=>{const r=[];for(const a of e)try{a.close({force:!0})}catch(t){r.push(t)}if(r.length>0)throw new AggregateError(r,`@lunora/platform-node: ${String(r.length)} platform(s) failed to close`)},S=e=>typeof e=="object"&&e!==null&&typeof e.fetch=="function",j=(e,r,a,t)=>{const o=$(r.worker[e.className],a);return v({crons:e.name===t?r.crons??{}:void 0,directory:r.dataDirectory===void 0?void 0:f(r.dataDirectory,e.name),onAlarm:async n=>{n!==void 0&&await(await o(n)).alarm?.()},onFetch:async(n,c)=>(await o(c)).fetch(n),path:r.dataDirectory===void 0?void 0:f(r.dataDirectory,`${e.name}.platform.sqlite3`)})},E=/^[A-Za-z_$][\w$]*$/u,L=(e,r)=>{const a=y(e,r);return a!==""&&!a.startsWith("..")&&!O(a)},T=(e,r)=>{if(!E.test(e))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${JSON.stringify(e)} is not a valid binding name (a JavaScript identifier such as SHARD), and its name becomes a directory under the data directory`);if(r===void 0||!m(r))return;const a=h(r);for(const t of[f(r,e),f(r,`${e}.platform.sqlite3`)]){let o;try{o=g(t)}catch{continue}if(o.isSymbolicLink()&&!m(t))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${e} would store data outside ${r}: ${t} is a link to nothing, which SQLite would follow`);if(!L(a,h(t)))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${e} would store data outside ${r}: ${t} links out of it`)}},_=e=>{const r=new Map;for(const{name:a}of e){const t=r.get(a.toLowerCase());if(t!==void 0)throw new i("VALIDATION_ERROR",t===a?`@lunora/platform-node: Durable Object binding ${a} is declared twice, and both would share one shard directory and platform database`:`@lunora/platform-node: Durable Object bindings ${t} and ${a} differ only in case, so on a case-insensitive volume they would share one shard directory and platform database — rename one`);r.set(a.toLowerCase(),a)}},P=e=>{if(typeof e!="function")return!1;try{return Reflect.construct(String,[],e),!0}catch{return!1}},x=e=>{if(!S(e.worker.default))throw new i("VALIDATION_ERROR","@lunora/platform-node: the worker module has no default export with a `fetch` handler");_(e.durableObjects);for(const t of e.durableObjects){T(t.name,e.dataDirectory);const o=Object.hasOwn(e.worker,t.className)?e.worker[t.className]:void 0;if(o===void 0)throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${t.name} names class ${t.className}, which the worker module does not export`);if(!P(o))throw new i("VALIDATION_ERROR",`@lunora/platform-node: Durable Object binding ${t.name} names ${t.className}, which the worker module exports as something \`new\` cannot construct`)}const r=e.shardBinding??"SHARD";if(N(e.crons??{}).length>0&&!e.durableObjects.some(t=>t.name===r))throw new i("VALIDATION_ERROR",`@lunora/platform-node: the app declares crons, but no Durable Object binding is named ${r} to run them on`)},M=e=>{x(e);const r=e.worker.default,a={...e.env},t=[],o=w({label:"worker waitUntil task(s)",reportFailures:!0}),n=w({label:"worker request(s)",reportFailures:!1}),c=e.shardBinding??"SHARD";e.dataDirectory!==void 0&&p(e.dataDirectory,{recursive:!0});try{for(const s of e.durableObjects){const l=j(s,e,a,c);t.push(l),Object.defineProperty(a,s.name,{configurable:!0,enumerable:!0,value:I(l.directory),writable:!0})}}catch(s){try{b(t.splice(0))}catch(l){console.error("[@lunora/platform-node] closing the platforms of a host that failed to compose failed:",l)}throw s}const d={passThroughOnException:()=>{},waitUntil:o.track};let u;return{close:async s=>(k(s),u??=(async()=>{try{return await A([n,o,...t],s)}finally{b(t.splice(0))}})(),u),fetch:async s=>{const l=Promise.resolve(r.fetch(s,a,d));return n.track(l),l},rearmPersistedAlarms:()=>t.flatMap(s=>s.rearmPersistedAlarms())}};export{x as checkNodeAppHost,M as createNodeAppHost};
@@ -1 +1 @@
1
- import{readdirSync as j,lstatSync as X,readlinkSync as Y,statSync as $,realpathSync as F}from"node:fs";import{join as m,dirname as p,basename as M,resolve as N}from"node:path";import{LunoraError as d}from"@lunora/errors";import{NODE_CAPABILITIES as z}from"@lunora/platform";import Z from"better-sqlite3";import{a as ee,c as te,i as re,A as oe}from"./node-dispatch-route-B3GAZkHT.mjs";import{startDrainDeadline as P,settlesBefore as D,drainTimeoutMs as ae,drainTogether as se}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeGlobalStore as ne}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as ie}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeMailHost as de}from"./createNodeMailHost-DrUo8de-.mjs";import{createNodeQueueHost as le}from"./createNodeQueueHost-glQ8GNCA.mjs";import{createNodeR2Bucket as ce}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as he}from"./createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as ue}from"./createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardRegistry as fe,SHARD_FILE_SUFFIX as k}from"./createNodeShardRegistry-D1r6M8Rg.mjs";import{createNodeSocketHost as me}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as pe}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as we}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const ge="__root__",ye=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>{if(o.functionPath===void 0)throw new d("VALIDATION_ERROR",o.workflow===void 0?`@lunora/platform-node: cron job "${o.name}" has neither a function target nor a workflow target`:`@lunora/platform-node: cron job "${o.name}" starts workflow "${o.workflow}", which this host cannot do from a cron tick — schedule a function that calls ctx.workflows.get(name).create() instead`);return{args:o.args??{},expression:t,functionPath:o.functionPath,name:o.name}})),ve=(e,t)=>{const r=ye(e);if(r.length>0&&!t)throw new d("VALIDATION_ERROR","@lunora/platform-node: `crons` declares jobs but nothing can deliver them — pass `onFetch` (to run them on the shard) or `onDispatch`");return r},w=(e,{databaseFile:t})=>{const r=N(t?e.trim():e);try{return F(r)}catch{try{return m(F(p(r)),M(r))}catch{return r}}},V=40,Re=e=>{let t=N(e.trim());const r=[t];for(let o=0;o<=V;o+=1){let i;try{i=X(t).isSymbolicLink()}catch(a){if(a.code==="ENOENT")return r;throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" could not be resolved — pass a path it can check`,{cause:a})}if(!i)return r;try{t=N(p(t),Y(t)),r.push(t)}catch(a){throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a symlink whose target could not be read`,{cause:a})}}throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a chain of more than ${String(V)} symlinks (a loop?) — pass the file itself`)},H=(e,t)=>{try{const r=$(e.trim(),{bigint:!0}),o=$(t.trim(),{bigint:!0});return r.dev===o.dev&&r.ino===o.ino}catch{return w(e,{databaseFile:!0}).toLowerCase()===w(t,{databaseFile:!0}).toLowerCase()}},Se=e=>{const t=e.trim();if(t===""||t===":memory:")throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path ${JSON.stringify(e)} is not durable — the mail queue and its sent ledger must survive a restart, so give mail a database file`);if(t.toLowerCase().startsWith("file:"))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path ${JSON.stringify(e)} is a file: URI — pass a plain filesystem path instead (better-sqlite3 does not read URIs, and would open a file by that literal name)`)},Ae=e=>({drain:async t=>{const r=P(t);try{return await D(e.drain(),r)?{failed:[],pending:[],timedOut:!1}:(console.error("[@lunora/platform-node] platform drain deadline passed with a mail poll still running"),{failed:[],pending:["a mail poll"],timedOut:!0})}finally{r.cancel()}},idle:()=>e.idle(),pending:()=>e.idle()?[]:["a mail poll"]}),be=(e,t)=>{const r=Re(e),o=r.at(-1)??e,i=[["the shard database (`path`)",t.path],["the .global() store (`globalTablesPath`)",t.globalTablesPath]];for(const[l,s]of i)if(s!==void 0&&s!==":memory:"&&s!==""&&H(s,o))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is ${l} "${s}" — give mail a database file of its own`);const{directory:a}=t;if(a===void 0)return;const u=w(a,{databaseFile:!1});if(r.some(l=>{const s=m(w(p(l),{databaseFile:!1}),M(l));return s.endsWith(k)&&p(s)===u}))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a ${k} file inside the shard registry's directory "${a}", which would open it as a shard — move it out of that directory`);let f;try{f=j(a).filter(l=>l.endsWith(k))}catch{return}const h=f.find(l=>H(m(a,l),o));if(h!==void 0)throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is the same file as the shard registry's shard "${m(a,h)}" — give mail a database file of its own`)},_e=(e,t)=>{if(e===void 0)return;const{path:r,...o}=e;Se(r),be(r,t);const i=new Z(r);try{return{close:()=>{i.close()},mail:de(i,o)}}catch(a){throw i.close(),a}},ke=(e,t)=>async(r,o,i)=>{if(re(r,t,ge))throw new d("BAD_REQUEST",oe);const a=await e({args:o,functionPath:r,id:i.id,identity:void 0,scheduledFor:i.scheduledFor,shardKey:t,traceparent:void 0});if(!a.ok)throw new d("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${r} was refused with status ${String(a.status)}`)},Ke=(e={})=>{const t=[],{database:r,dispose:o,drain:i,host:a,pendingAlarms:u,pendingBackground:g,suspendAlarms:f,takeFailures:h}=ue(e);t.push(o);try{const l=ie(r),s=fe(e);t.push(n=>{s.close(n)});const{directory:O}=s,I=ee(O,e.onFetch!==void 0),B=te({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:I,schedulerSecret:e.dispatch?.schedulerSecret}),C=e.onFetch===void 0?void 0:ke(I,e.shardKey??"__root__"),{declareCrons:U,dispose:q,pendingDispatches:y,scheduler:W,suspend:J}=he(r,{...e,onDispatch:e.onDispatch??C}),{socket:K}=me(r);t.push(q),e.crons!==void 0&&U(ve(e.crons,e.onDispatch!==void 0||e.onFetch!==void 0));const Q=e.queues===void 0?void 0:le(r,{onBatch:e.onQueueBatch??(()=>{throw new d("VALIDATION_ERROR","@lunora/platform-node: createNodePlatform was given `queues` without `onQueueBatch`, so a delivered batch has nowhere to go — pass the worker's queue export from createWorker")}),queues:e.queues}),v=_e(e.mail,e);v!==void 0&&t.push(v.close);const R=v?.mail,x=e.objectStorageDirectory===void 0?void 0:ce({directory:e.objectStorageDirectory}),S=e.globalTablesPath===void 0?void 0:ne({path:e.globalTablesPath});S!==void 0&&t.push(()=>{S.dispose()});const G=e.workflows===void 0?void 0:pe({store:we(r),workflows:e.workflows}),E=n=>{const c=[];for(const b of t.toReversed())try{b(n)}catch(_){c.push(_)}if(c.length>0)throw new AggregateError(c,`@lunora/platform-node: ${String(c.length)} resource(s) failed to close`)},T=()=>[...g()>0||u()>0?["waitUntil work on the platform host"]:[],...y().labels],A=[{drain:async n=>{const c=P(n);try{const[b,_]=await Promise.all([D(i(),c),D(Promise.allSettled(y().waits),c)]);if(b&&_)return{failed:h(),pending:[],timedOut:!1};const L=T();return console.error("[@lunora/platform-node] platform drain deadline passed with work still running: %s",L.join(", ")),{failed:h(),pending:L,timedOut:!0}}finally{c.cancel()}},idle:()=>g()===0&&u()===0&&y().waits.length===0,pending:T},s,...R===void 0?[]:[Ae(R)]];return{capabilities:z,close:E,directory:O,dispatch:n=>B(n),idle:()=>A.every(n=>n.idle()),pending:()=>A.flatMap(n=>n.pending()),drain:async n=>(ae(n),J(),f(),s.suspendAlarms(),se(A,n)),globalTables:S,kv:l,mail:R,objectStorage:x,rearmPersistedAlarms:()=>s.rearmPersistedAlarms(),queues:Q,scheduler:W,shard:a,sockets:K,workflows:G,[Symbol.dispose]:()=>{E()}}}catch(l){for(const s of t.toReversed())try{s()}catch{}throw l}};export{ke as createJobDelivery,Ke as createNodePlatform,ye as walkDeclaredCrons};
1
+ import{readdirSync as j,lstatSync as X,readlinkSync as Y,statSync as $,realpathSync as F}from"node:fs";import{join as m,dirname as p,basename as M,resolve as N}from"node:path";import{LunoraError as d}from"@lunora/errors";import{NODE_CAPABILITIES as z}from"@lunora/platform";import Z from"better-sqlite3";import{a as ee,c as te,i as re,A as oe}from"./node-dispatch-route-qngKbRsA.mjs";import{startDrainDeadline as P,settlesBefore as D,drainTimeoutMs as ae,drainTogether as se}from"./DEFAULT_DRAIN_TIMEOUT_MS-JyFyF0D9.mjs";import{createNodeGlobalStore as ne}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as ie}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeMailHost as de}from"./createNodeMailHost-DrUo8de-.mjs";import{createNodeQueueHost as le}from"./createNodeQueueHost-glQ8GNCA.mjs";import{createNodeR2Bucket as ce}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as he}from"./createNodeSchedulerHost-BQPmMWJ7.mjs";import{createNodeShardHost as ue}from"./createNodeShardHost-DZ2cwIKF.mjs";import{createNodeShardRegistry as fe,SHARD_FILE_SUFFIX as k}from"./createNodeShardRegistry-D1r6M8Rg.mjs";import{createNodeSocketHost as me}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as pe}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as we}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const ge="__root__",ye=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>{if(o.functionPath===void 0)throw new d("VALIDATION_ERROR",o.workflow===void 0?`@lunora/platform-node: cron job "${o.name}" has neither a function target nor a workflow target`:`@lunora/platform-node: cron job "${o.name}" starts workflow "${o.workflow}", which this host cannot do from a cron tick — schedule a function that calls ctx.workflows.get(name).create() instead`);return{args:o.args??{},expression:t,functionPath:o.functionPath,name:o.name}})),ve=(e,t)=>{const r=ye(e);if(r.length>0&&!t)throw new d("VALIDATION_ERROR","@lunora/platform-node: `crons` declares jobs but nothing can deliver them — pass `onFetch` (to run them on the shard) or `onDispatch`");return r},w=(e,{databaseFile:t})=>{const r=N(t?e.trim():e);try{return F(r)}catch{try{return m(F(p(r)),M(r))}catch{return r}}},V=40,Re=e=>{let t=N(e.trim());const r=[t];for(let o=0;o<=V;o+=1){let i;try{i=X(t).isSymbolicLink()}catch(a){if(a.code==="ENOENT")return r;throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" could not be resolved — pass a path it can check`,{cause:a})}if(!i)return r;try{t=N(p(t),Y(t)),r.push(t)}catch(a){throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a symlink whose target could not be read`,{cause:a})}}throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a chain of more than ${String(V)} symlinks (a loop?) — pass the file itself`)},H=(e,t)=>{try{const r=$(e.trim(),{bigint:!0}),o=$(t.trim(),{bigint:!0});return r.dev===o.dev&&r.ino===o.ino}catch{return w(e,{databaseFile:!0}).toLowerCase()===w(t,{databaseFile:!0}).toLowerCase()}},Se=e=>{const t=e.trim();if(t===""||t===":memory:")throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path ${JSON.stringify(e)} is not durable — the mail queue and its sent ledger must survive a restart, so give mail a database file`);if(t.toLowerCase().startsWith("file:"))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path ${JSON.stringify(e)} is a file: URI — pass a plain filesystem path instead (better-sqlite3 does not read URIs, and would open a file by that literal name)`)},Ae=e=>({drain:async t=>{const r=P(t);try{return await D(e.drain(),r)?{failed:[],pending:[],timedOut:!1}:(console.error("[@lunora/platform-node] platform drain deadline passed with a mail poll still running"),{failed:[],pending:["a mail poll"],timedOut:!0})}finally{r.cancel()}},idle:()=>e.idle(),pending:()=>e.idle()?[]:["a mail poll"]}),be=(e,t)=>{const r=Re(e),o=r.at(-1)??e,i=[["the shard database (`path`)",t.path],["the .global() store (`globalTablesPath`)",t.globalTablesPath]];for(const[l,s]of i)if(s!==void 0&&s!==":memory:"&&s!==""&&H(s,o))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is ${l} "${s}" — give mail a database file of its own`);const{directory:a}=t;if(a===void 0)return;const u=w(a,{databaseFile:!1});if(r.some(l=>{const s=m(w(p(l),{databaseFile:!1}),M(l));return s.endsWith(k)&&p(s)===u}))throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is a ${k} file inside the shard registry's directory "${a}", which would open it as a shard — move it out of that directory`);let f;try{f=j(a).filter(l=>l.endsWith(k))}catch{return}const h=f.find(l=>H(m(a,l),o));if(h!==void 0)throw new d("VALIDATION_ERROR",`@lunora/platform-node: mail.path "${e}" is the same file as the shard registry's shard "${m(a,h)}" — give mail a database file of its own`)},_e=(e,t)=>{if(e===void 0)return;const{path:r,...o}=e;Se(r),be(r,t);const i=new Z(r);try{return{close:()=>{i.close()},mail:de(i,o)}}catch(a){throw i.close(),a}},ke=(e,t)=>async(r,o,i)=>{if(re(r,t,ge))throw new d("BAD_REQUEST",oe);const a=await e({args:o,functionPath:r,id:i.id,identity:void 0,scheduledFor:i.scheduledFor,shardKey:t,traceparent:void 0});if(!a.ok)throw new d("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${r} was refused with status ${String(a.status)}`)},Ke=(e={})=>{const t=[],{database:r,dispose:o,drain:i,host:a,pendingAlarms:u,pendingBackground:g,suspendAlarms:f,takeFailures:h}=ue(e);t.push(o);try{const l=ie(r),s=fe(e);t.push(n=>{s.close(n)});const{directory:O}=s,I=ee(O,e.onFetch!==void 0),B=te({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:I,schedulerSecret:e.dispatch?.schedulerSecret}),C=e.onFetch===void 0?void 0:ke(I,e.shardKey??"__root__"),{declareCrons:U,dispose:q,pendingDispatches:y,scheduler:W,suspend:J}=he(r,{...e,onDispatch:e.onDispatch??C}),{socket:K}=me(r);t.push(q),e.crons!==void 0&&U(ve(e.crons,e.onDispatch!==void 0||e.onFetch!==void 0));const Q=e.queues===void 0?void 0:le(r,{onBatch:e.onQueueBatch??(()=>{throw new d("VALIDATION_ERROR","@lunora/platform-node: createNodePlatform was given `queues` without `onQueueBatch`, so a delivered batch has nowhere to go — pass the worker's queue export from createWorker")}),queues:e.queues}),v=_e(e.mail,e);v!==void 0&&t.push(v.close);const R=v?.mail,x=e.objectStorageDirectory===void 0?void 0:ce({directory:e.objectStorageDirectory}),S=e.globalTablesPath===void 0?void 0:ne({path:e.globalTablesPath});S!==void 0&&t.push(()=>{S.dispose()});const G=e.workflows===void 0?void 0:pe({store:we(r),workflows:e.workflows}),E=n=>{const c=[];for(const b of t.toReversed())try{b(n)}catch(_){c.push(_)}if(c.length>0)throw new AggregateError(c,`@lunora/platform-node: ${String(c.length)} resource(s) failed to close`)},T=()=>[...g()>0||u()>0?["waitUntil work on the platform host"]:[],...y().labels],A=[{drain:async n=>{const c=P(n);try{const[b,_]=await Promise.all([D(i(),c),D(Promise.allSettled(y().waits),c)]);if(b&&_)return{failed:h(),pending:[],timedOut:!1};const L=T();return console.error("[@lunora/platform-node] platform drain deadline passed with work still running: %s",L.join(", ")),{failed:h(),pending:L,timedOut:!0}}finally{c.cancel()}},idle:()=>g()===0&&u()===0&&y().waits.length===0,pending:T},s,...R===void 0?[]:[Ae(R)]];return{capabilities:z,close:E,directory:O,dispatch:n=>B(n),idle:()=>A.every(n=>n.idle()),pending:()=>A.flatMap(n=>n.pending()),drain:async n=>(ae(n),J(),f(),s.suspendAlarms(),se(A,n)),globalTables:S,kv:l,mail:R,objectStorage:x,rearmPersistedAlarms:()=>s.rearmPersistedAlarms(),queues:Q,scheduler:W,shard:a,sockets:K,workflows:G,[Symbol.dispose]:()=>{E()}}}catch(l){for(const s of t.toReversed())try{s()}catch{}throw l}};export{ke as createJobDelivery,Ke as createNodePlatform,ye as walkDeclaredCrons};
@@ -0,0 +1,2 @@
1
+ import{LunoraError as i}from"@lunora/errors";import{toErrorResponse as u,resolveShard as l}from"@lunora/runtime";import{assertDedupKey as f}from"@lunora/scheduler";import{s as E}from"./hmac-url-Bogwm7I6.mjs";const c=(e,t)=>{const n=Math.max(e.length,t.length);let a=e.length^t.length;for(let r=0;r<n;r+=1){const o=r<e.length?e.charCodeAt(r):0,s=r<t.length?t.charCodeAt(r):0;a|=o^s}return a===0},y="/_lunora/scheduler/dispatch",g="__lunora_relation__:",_=e=>e.startsWith(g),h="agents:agentRun",S=(e,t,n)=>e===h&&t!==n,A=`\`${h}\` runs on the default shard only, where agent threads live; to run an agent's tools on another shard, start it from a mutation on that shard with \`ctx.agents.<name>.run\``,p=(e,t)=>{if(!t||t.length===0)return!1;const n=e.headers.get("authorization");if(!n)return!1;const[a,...r]=n.split(" ");return a?.toLowerCase()!=="bearer"?!1:c(t,r.join(" ").trim())},w="x-lunora-scheduler-signature",m="x-lunora-scheduler-timestamp",D=5*6e4,T=e=>["v1",String(e.timestamp),e.userId??"",e.identity??"",e.body].join(`
2
+ `),R=(e,t)=>E(e,T(t)),N=async(e,t,n)=>{const a=e.headers.get(w),{schedulerSecret:r}=n;if(a!==null&&a.length>0&&r!==void 0&&r.length>0){const o=e.headers.get(m);if(o===null||!/^\d+$/u.test(o))return!1;const s=Number(o);if(!Number.isSafeInteger(s)||Math.abs((n.now??Date.now)()-s)>D)return!1;const d=await R(r,{body:t,identity:e.headers.get("x-lunora-identity")??void 0,timestamp:s,userId:e.headers.get("x-lunora-userid")??void 0});return c(d,a)}return p(e,n.adminToken)},I=async(e,t)=>{if(!e.body)return"";const n=e.body.getReader(),a=new TextDecoder;let r=0,o="";for(;;){const{done:s,value:d}=await n.read();if(s)break;if(d){if(r+=d.byteLength,r>t)return await n.cancel().catch(()=>{}),null;o+=a.decode(d,{stream:!0})}}return o+=a.decode(),o},P="x-lunora-paywall",v="1",L="x-lunora-scheduled-for",O=({forwardedIdentity:e,mutationId:t,scheduledFor:n,traceparent:a})=>{const r={"content-type":"application/json",[P]:v,"x-lunora-system":"1"};return e?.userId!==void 0&&e.userId.length>0&&(r["x-lunora-userid"]=e.userId),e?.identity!==void 0&&e.identity.length>0&&(r["x-lunora-identity"]=e.identity),t!==void 0&&t.length>0&&(r["x-lunora-mutation-id"]=t),a!==void 0&&a.length>0&&(r.traceparent=a),n!==void 0&&Number.isFinite(n)&&(r[L]=String(Math.trunc(n))),r},C=e=>{const t=e.headers.get("x-lunora-userid"),n=e.headers.get("x-lunora-identity");if(!(t===null&&n===null))return{...n===null?{}:{identity:n},...t===null?{}:{userId:t}}},H=1048576,U=async e=>{const t=await I(e,H);if(t===null)throw new i("PAYLOAD_TOO_LARGE","Scheduler dispatch body is too large");return t},x=e=>{const t=f(e.dedupKey);return t!==void 0?t:typeof e.id=="string"&&e.id.length>0?e.id:void 0},b=async(e,t)=>{if(e.method!=="POST")throw new i("METHOD_NOT_ALLOWED","Scheduler dispatch endpoint requires POST",{status:405});const n=await U(e);if(!await N(e,n,{adminToken:t.adminToken,now:t.now,schedulerSecret:t.schedulerSecret}))throw new i("DISPATCH_UNAUTHENTICATED","Scheduler dispatch requires a valid signature or admin bearer");let r;try{r=JSON.parse(n)}catch{throw new i("BAD_REQUEST","Scheduler dispatch body must be valid JSON")}const o=r??{};if(typeof o.workflow=="string"||o.pool!==void 0)throw new i("SERVICE_UNAVAILABLE","Scheduler dispatch for a workflow or pool target is not served by the Node dispatch route");if(typeof o.functionPath!="string"||o.functionPath.length===0)throw new i("BAD_REQUEST","Scheduler dispatch is missing `functionPath`");if(_(o.functionPath))throw new i("FORBIDDEN","`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard");const s=typeof o.shardKey=="string"&&o.shardKey.length>0?o.shardKey:t.defaultShardKey;if(S(o.functionPath,s,t.defaultShardKey))throw new i("BAD_REQUEST",A);return t.invoke({args:o.args??{},functionPath:o.functionPath,id:x(o),identity:C(e),scheduledFor:typeof o.scheduledFor=="number"?o.scheduledFor:void 0,shardKey:s,traceparent:e.headers.get("traceparent")??void 0})},M=(e,t)=>n=>{if(!t)throw new i("SERVICE_UNAVAILABLE","@lunora/platform-node: the dispatch route needs `onFetch` to run a function; without it a shard only echoes its key");const a=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:n.args,functionPath:n.functionPath}),headers:O({forwardedIdentity:n.identity,mutationId:n.id,scheduledFor:n.scheduledFor,traceparent:n.traceparent}),method:"POST"});return l(e,n.shardKey).fetch(a)},G=e=>async t=>{try{return await b(t,e)}catch(n){return u(n)}},Y=y;export{A,Y as N,M as a,G as c,S as i};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/platform-node",
3
- "version": "1.0.0-alpha.223",
3
+ "version": "1.0.0-alpha.225",
4
4
  "description": "Node implementation of the Lunora platform contracts: ShardHost, SocketHost, ShardDirectory, ShardKvStore, SchedulerHost over better-sqlite3 and an in-process socket registry (dev/test target)",
5
5
  "keywords": [
6
6
  "better-sqlite3",
@@ -46,14 +46,14 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/d1": "^1.0.0-alpha.237",
49
+ "@lunora/d1": "^1.0.0-alpha.238",
50
50
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
51
51
  "@lunora/mail": "^1.0.0-alpha.140",
52
- "@lunora/platform": "^1.0.0-alpha.82",
53
- "@lunora/queue": "^1.0.0-alpha.144",
54
- "@lunora/runtime": "^1.0.0-alpha.292",
55
- "@lunora/scheduler": "^1.0.0-alpha.171",
56
- "@lunora/sql-store": "^1.0.0-alpha.234",
52
+ "@lunora/platform": "^1.0.0-alpha.83",
53
+ "@lunora/queue": "^1.0.0-alpha.146",
54
+ "@lunora/runtime": "^1.0.0-alpha.300",
55
+ "@lunora/scheduler": "^1.0.0-alpha.173",
56
+ "@lunora/sql-store": "^1.0.0-alpha.240",
57
57
  "@lunora/workflow": "^1.0.0-alpha.111",
58
58
  "@visulima/cron-parser": "2.0.0",
59
59
  "@visulima/workflow": "4.0.0",
@@ -1,2 +0,0 @@
1
- import{LunoraError as i}from"@lunora/errors";import{toErrorResponse as u,resolveShard as l}from"@lunora/runtime";import{s as f}from"./hmac-url-Bogwm7I6.mjs";const c=(t,e)=>{const n=Math.max(t.length,e.length);let o=t.length^e.length;for(let a=0;a<n;a+=1){const r=a<t.length?t.charCodeAt(a):0,s=a<e.length?e.charCodeAt(a):0;o|=r^s}return o===0},E="/_lunora/scheduler/dispatch",g="__lunora_relation__:",_=t=>t.startsWith(g),h="agents:agentRun",y=(t,e,n)=>t===h&&e!==n,S=`\`${h}\` runs on the default shard only, where agent threads live; to run an agent's tools on another shard, start it from a mutation on that shard with \`ctx.agents.<name>.run\``,A=(t,e)=>{if(!e||e.length===0)return!1;const n=t.headers.get("authorization");if(!n)return!1;const[o,...a]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:c(e,a.join(" ").trim())},w="x-lunora-scheduler-signature",m="x-lunora-scheduler-timestamp",p=5*6e4,D=t=>["v1",String(t.timestamp),t.userId??"",t.identity??"",t.body].join(`
2
- `),T=(t,e)=>f(t,D(e)),R=async(t,e,n)=>{const o=t.headers.get(w),{schedulerSecret:a}=n;if(o!==null&&o.length>0&&a!==void 0&&a.length>0){const r=t.headers.get(m);if(r===null||!/^\d+$/u.test(r))return!1;const s=Number(r);if(!Number.isSafeInteger(s)||Math.abs((n.now??Date.now)()-s)>p)return!1;const d=await T(a,{body:e,identity:t.headers.get("x-lunora-identity")??void 0,timestamp:s,userId:t.headers.get("x-lunora-userid")??void 0});return c(d,o)}return A(t,n.adminToken)},N=async(t,e)=>{if(!t.body)return"";const n=t.body.getReader(),o=new TextDecoder;let a=0,r="";for(;;){const{done:s,value:d}=await n.read();if(s)break;if(d){if(a+=d.byteLength,a>e)return await n.cancel().catch(()=>{}),null;r+=o.decode(d,{stream:!0})}}return r+=o.decode(),r},I="x-lunora-paywall",P="1",v="x-lunora-scheduled-for",L=({forwardedIdentity:t,mutationId:e,scheduledFor:n,traceparent:o})=>{const a={"content-type":"application/json",[I]:P,"x-lunora-system":"1"};return t?.userId!==void 0&&t.userId.length>0&&(a["x-lunora-userid"]=t.userId),t?.identity!==void 0&&t.identity.length>0&&(a["x-lunora-identity"]=t.identity),e!==void 0&&e.length>0&&(a["x-lunora-mutation-id"]=e),o!==void 0&&o.length>0&&(a.traceparent=o),n!==void 0&&Number.isFinite(n)&&(a[v]=String(Math.trunc(n))),a},O=t=>{const e=t.headers.get("x-lunora-userid"),n=t.headers.get("x-lunora-identity");if(!(e===null&&n===null))return{...n===null?{}:{identity:n},...e===null?{}:{userId:e}}},C=1048576,H=async t=>{const e=await N(t,C);if(e===null)throw new i("PAYLOAD_TOO_LARGE","Scheduler dispatch body is too large");return e},U=async(t,e)=>{if(t.method!=="POST")throw new i("METHOD_NOT_ALLOWED","Scheduler dispatch endpoint requires POST",{status:405});const n=await H(t);if(!await R(t,n,{adminToken:e.adminToken,now:e.now,schedulerSecret:e.schedulerSecret}))throw new i("DISPATCH_UNAUTHENTICATED","Scheduler dispatch requires a valid signature or admin bearer");let a;try{a=JSON.parse(n)}catch{throw new i("BAD_REQUEST","Scheduler dispatch body must be valid JSON")}const r=a??{};if(typeof r.workflow=="string"||r.pool!==void 0)throw new i("SERVICE_UNAVAILABLE","Scheduler dispatch for a workflow or pool target is not served by the Node dispatch route");if(typeof r.functionPath!="string"||r.functionPath.length===0)throw new i("BAD_REQUEST","Scheduler dispatch is missing `functionPath`");if(_(r.functionPath))throw new i("FORBIDDEN","`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard");const s=typeof r.shardKey=="string"&&r.shardKey.length>0?r.shardKey:e.defaultShardKey;if(y(r.functionPath,s,e.defaultShardKey))throw new i("BAD_REQUEST",S);return e.invoke({args:r.args??{},functionPath:r.functionPath,id:typeof r.id=="string"&&r.id.length>0?r.id:void 0,identity:O(t),scheduledFor:typeof r.scheduledFor=="number"?r.scheduledFor:void 0,shardKey:s,traceparent:t.headers.get("traceparent")??void 0})},B=(t,e)=>n=>{if(!e)throw new i("SERVICE_UNAVAILABLE","@lunora/platform-node: the dispatch route needs `onFetch` to run a function; without it a shard only echoes its key");const o=new Request("https://shard.internal/rpc",{body:JSON.stringify({args:n.args,functionPath:n.functionPath}),headers:L({forwardedIdentity:n.identity,mutationId:n.id,scheduledFor:n.scheduledFor,traceparent:n.traceparent}),method:"POST"});return l(t,n.shardKey).fetch(o)},k=t=>async e=>{try{return await U(e,t)}catch(n){return u(n)}},M=E;export{S as A,M as N,B as a,k as c,y as i};