@lunora/platform-node 1.0.0-alpha.217 → 1.0.0-alpha.219

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/LICENSE.md CHANGED
@@ -1,108 +1,205 @@
1
- # Functional Source License, Version 1.1, Apache 2.0 Future License
2
1
 
3
- ## Abbreviation
4
-
5
- FSL-1.1-Apache-2.0
6
-
7
- ## Notice
8
-
9
- Copyright 2026 anolilab and contributors
10
-
11
- ## Terms and Conditions
12
-
13
- ### Licensor ("We")
14
-
15
- The party offering the Software under these Terms and Conditions.
16
-
17
- ### The Software
18
-
19
- The "Software" is each version of the software that we make available under
20
- these Terms and Conditions, as indicated by our inclusion of these Terms and
21
- Conditions with the Software.
22
-
23
- ### License Grant
24
-
25
- Subject to your compliance with this License Grant and the Patents,
26
- Redistribution and Trademark clauses below, we hereby grant you the right to
27
- use, copy, modify, create derivative works, publicly perform, publicly display
28
- and redistribute the Software for any Permitted Purpose identified below.
29
-
30
- ### Permitted Purpose
31
-
32
- A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
- means making the Software available to others in a commercial product or service
34
- that:
35
-
36
- 1. substitutes for the Software;
37
-
38
- 2. substitutes for any other product or service we offer using the Software that
39
- exists as of the date we make the Software available; or
40
-
41
- 3. offers the same or substantially similar functionality as the Software.
42
-
43
- Permitted Purposes specifically include using the Software:
44
-
45
- 1. for your internal use and access;
46
-
47
- 2. for non-commercial education;
48
-
49
- 3. for non-commercial research; and
50
-
51
- 4. in connection with professional services that you provide to a licensee using
52
- the Software in accordance with these Terms and Conditions.
53
-
54
- ### Patents
55
-
56
- To the extent your use for a Permitted Purpose would necessarily infringe our
57
- patents, the license grant above includes a license under our patents. If you
58
- make a claim against any party that the Software infringes or contributes to the
59
- infringement of any patent, then your patent license to the Software ends
60
- immediately.
61
-
62
- ### Redistribution
63
-
64
- The Terms and Conditions apply to all copies, modifications and derivatives of
65
- the Software.
66
-
67
- If you redistribute any copies, modifications or derivatives of the Software,
68
- you must include a copy of or a link to these Terms and Conditions and not
69
- remove any copyright notices provided in or with the Software.
70
-
71
- ### Disclaimer
72
-
73
- THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
- IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
- PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
-
77
- IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
- SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, EVEN
79
- IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
-
81
- ### Trademarks
82
-
83
- Except for displaying the License Details and identifying us as the origin of
84
- the Software, you have no right under these Terms and Conditions to use our
85
- trademarks, trade names, service marks or product names.
86
-
87
- ## Grant of Future License
88
-
89
- We hereby irrevocably grant you an additional license to use the Software under
90
- the Apache License, Version 2.0 that is effective on the second anniversary of
91
- the date we make the Software available. On or after that date, you may use the
92
- Software under the Apache License, Version 2.0, in which case the following will
93
- apply:
94
-
95
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
- this file except in compliance with the License.
97
-
98
- You may obtain a copy of the License at
99
-
100
- http://www.apache.org/licenses/LICENSE-2.0
101
-
102
- Unless required by applicable law or agreed to in writing, software distributed
103
- under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
- CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
- specific language governing permissions and limitations under the License.
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
106
203
 
107
204
  <!-- DEPENDENCIES -->
108
205
  <!-- /DEPENDENCIES -->
@@ -1 +1 @@
1
- import{NODE_CAPABILITIES as g}from"@lunora/platform";import{createNodeShardKvStore as D}from"../packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeSchedulerHost as k}from"../packem_shared/createNodeSchedulerHost-CjgGhVoQ.mjs";import{createNodeShardHost as T}from"../packem_shared/createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardRegistry as H}from"../packem_shared/createNodeShardRegistry-BKl1QXiv.mjs";import{createNodeSocketHost as b}from"../packem_shared/createNodeSocketHost-ByOmEGFe.mjs";const P=()=>{const{database:o,dispose:m,host:p}=T(),h=D(o),i=H(),{directory:l}=i,{readFrames:w,restoreSocket:S,simulateRecycle:u,socket:f}=b(o),c=new Set,s=new Map,{dispose:y,scheduler:d,simulateDeadLetter:N}=k(o,{onDispatch:(e,a,t)=>{c.add(t.id),s.set(e,(s.get(e)??0)+1)}}),n=()=>{y(),m(),i.close()};return{capabilities:g,awaitAlarmFired:async e=>{await new Promise(a=>{setTimeout(a,Math.max(0,e-Date.now())+30)})},awaitJobDispatched:async e=>{const t=(await d.list?.())?.find(r=>r.id===e);return t!==void 0&&await new Promise(r=>{setTimeout(r,Math.max(0,t.scheduledFor-Date.now())+30)}),c.has(e)},cleanup:n,cronTicks:e=>s.get(e)??0,directory:l,disposeTerminally:n,kv:h,readFrames:w,restoreSocket:S,scheduler:d,shard:p,simulateDeadLetter:N,simulateRecycle:u,socket:f}};export{P as createNodeConformanceHost};
1
+ import{NODE_CAPABILITIES as g}from"@lunora/platform";import{createNodeShardKvStore as D}from"../packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeSchedulerHost as k}from"../packem_shared/createNodeSchedulerHost-DY6TOmXg.mjs";import{createNodeShardHost as T}from"../packem_shared/createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardRegistry as H}from"../packem_shared/createNodeShardRegistry-BKl1QXiv.mjs";import{createNodeSocketHost as b}from"../packem_shared/createNodeSocketHost-ByOmEGFe.mjs";const P=()=>{const{database:o,dispose:m,host:p}=T(),h=D(o),i=H(),{directory:l}=i,{readFrames:w,restoreSocket:S,simulateRecycle:u,socket:f}=b(o),c=new Set,s=new Map,{dispose:y,scheduler:d,simulateDeadLetter:N}=k(o,{onDispatch:(e,a,t)=>{c.add(t.id),s.set(e,(s.get(e)??0)+1)}}),n=()=>{y(),m(),i.close()};return{capabilities:g,awaitAlarmFired:async e=>{await new Promise(a=>{setTimeout(a,Math.max(0,e-Date.now())+30)})},awaitJobDispatched:async e=>{const t=(await d.list?.())?.find(r=>r.id===e);return t!==void 0&&await new Promise(r=>{setTimeout(r,Math.max(0,t.scheduledFor-Date.now())+30)}),c.has(e)},cleanup:n,cronTicks:e=>s.get(e)??0,directory:l,disposeTerminally:n,kv:h,readFrames:w,restoreSocket:S,scheduler:d,shard:p,simulateDeadLetter:N,simulateRecycle:u,socket:f}};export{P as createNodeConformanceHost};
package/dist/index.d.mts CHANGED
@@ -28,6 +28,8 @@ interface NodeDispatchRouteOptions {
28
28
  defaultShardKey: string;
29
29
  /** Runs the call in-process and returns the shard's response, unchanged. */
30
30
  invoke: (call: NodeDispatchInvocation) => Promise<Response>;
31
+ /** Epoch-ms clock for the signature window. Defaults to `Date.now`; tests inject one. */
32
+ now?: () => number;
31
33
  /** `LUNORA_SCHEDULER_SECRET`. When set, a signed request is verified against it. */
32
34
  schedulerSecret?: string;
33
35
  }
@@ -133,6 +135,42 @@ interface NodeHttpServer {
133
135
  /** The `http://host:port` origin the server answers on. */
134
136
  origin: string;
135
137
  }
138
+ /**
139
+ * The connection fields a Cloudflare `Hyperdrive` binding exposes, and the
140
+ * `HyperdriveLike` shape `@lunora/hyperdrive`'s `createHyperdrive` reads.
141
+ * Declared here structurally so this package does not depend on
142
+ * `@lunora/hyperdrive` for a type.
143
+ */
144
+ interface NodeHyperdriveBinding {
145
+ connectionString: string;
146
+ database: string;
147
+ host: string;
148
+ password: string;
149
+ port: number;
150
+ user: string;
151
+ }
152
+ /**
153
+ * Build the `HYPERDRIVE` binding for a Node host from a database URL, by
154
+ * default `process.env.DATABASE_URL`. Put it on the `env` the worker and shard
155
+ * are built over, under the binding name the app reads (`env.HYPERDRIVE`), and
156
+ * the app's own `.hyperdrive((env) => …)` wiring builds `ctx.sql` from it
157
+ * unchanged.
158
+ *
159
+ * There is no pool or query cache in front of the database here: the driver
160
+ * the app constructs from `connectionString` connects to it directly, so its own
161
+ * pool settings are the only ones that apply.
162
+ * A Postgres URL may name a Unix socket the libpq way: an empty host with the
163
+ * socket directory in a `host` query parameter (`postgres:///db?host=/var/run/postgresql`),
164
+ * which becomes the binding's `host`.
165
+ *
166
+ * A URL with any TLS option other than an explicit off (`sslmode=prefer` or
167
+ * `require`, `ssl=true`, `sslrootcert=…`) gets a binding whose discrete fields
168
+ * throw: they cannot carry it, so a pool built from them would silently connect
169
+ * without TLS. `sslmode=disable` and `ssl=false` keep them. Build the driver
170
+ * from `connectionString`, which keeps every query option.
171
+ * @param url A `postgres://`, `postgresql://`, `mysql://` or `mariadb://` URL; `DATABASE_URL` unless given.
172
+ */
173
+ declare const createNodeHyperdrive: (url?: string | undefined) => NodeHyperdriveBinding;
136
174
  /** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
137
175
  declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
138
176
  /** Options for {@link createNodeQueueHost}. */
@@ -207,6 +245,14 @@ interface NodeQueueHost<Queues extends Record<string, {
207
245
  declare const createNodeQueueHost: <Queues extends Record<string, {
208
246
  isLunoraQueue: true;
209
247
  }>>(database: Database.Database, options: NodeQueueHostOptions<Queues>) => NodeQueueHost<Queues>;
248
+ /** One declared cron job, as {@link NodeSchedulerHost.declareCrons} takes it. */
249
+ interface NodeDeclaredCron {
250
+ args: Record<string, unknown>;
251
+ expression: string;
252
+ functionPath: string;
253
+ /** The job's `cronJobs()` name, unique across the app. Keys its row. */
254
+ name: string;
255
+ }
210
256
  /** Options for {@link createNodeSchedulerHost}. */
211
257
  interface NodeSchedulerHostOptions {
212
258
  /**
@@ -239,6 +285,14 @@ interface NodeSchedulerHostOptions {
239
285
  * TCK's dead-letter legs need.
240
286
  */
241
287
  interface NodeSchedulerHost {
288
+ /**
289
+ * Make `crons` the app's declared cron set: upsert each one, arm it, and
290
+ * delete and disarm any declared row not in the list (a job the app removed
291
+ * or renamed). Every expression is parsed before anything is written, so an
292
+ * invalid one throws and leaves the previous set in place. Throws after
293
+ * `dispose()`.
294
+ */
295
+ declareCrons: (crons: ReadonlyArray<NodeDeclaredCron>) => void;
242
296
  /**
243
297
  * Clear every armed `setTimeout` (one-shot jobs and cron ticks alike) and
244
298
  * put the host into a terminal, closed state: afterwards `schedule()` and
@@ -506,6 +560,13 @@ interface NodeWorkflowHost<Workflows extends Record<string, {
506
560
  declare const createNodeWorkflowHost: <Workflows extends Record<string, {
507
561
  isLunoraWorkflow: true;
508
562
  }>>(options: NodeWorkflowHostOptions<Workflows>) => NodeWorkflowHost<Workflows>;
563
+ /** One entry of the generated `LUNORA_CRONS` map (`_generated/crons.ts`). */
564
+ interface NodeCronJob {
565
+ args?: Record<string, unknown>;
566
+ functionPath?: string;
567
+ name: string;
568
+ workflow?: string;
569
+ }
509
570
  /** Every contract this package provides, composed for one Node process. */
510
571
  interface NodePlatform<Queues extends Record<string, {
511
572
  isLunoraQueue: true;
@@ -641,6 +702,19 @@ type NodePlatformOptions<Queues extends Record<string, {
641
702
  }> = Record<string, never>, Workflows extends Record<string, {
642
703
  isLunoraWorkflow: true;
643
704
  }> = Record<string, never>> = {
705
+ /**
706
+ * The app's declared crons — pass the generated `LUNORA_CRONS` map
707
+ * (`_generated/crons.ts`). Each job is armed on the scheduler and delivered
708
+ * through the same `onDispatch` a scheduled job uses, so it needs `onFetch`
709
+ * (or your own `onDispatch`) to reach a shard; a non-empty map with neither
710
+ * throws. Job names must be unique, every schedule must have a next
711
+ * occurrence, and schedules are read as UTC. The map is the whole declared
712
+ * set: a job declared by an earlier run and absent here is deleted. Omit
713
+ * the option and this process neither fires nor deletes declared jobs, so
714
+ * a script opening the same file leaves a running server's crons alone.
715
+ * Crons registered through `scheduler.cron()` are re-armed either way.
716
+ */
717
+ crons?: Readonly<Record<string, ReadonlyArray<NodeCronJob>>>;
644
718
  /** Secrets for the dispatch route. Omit to leave the route refusing every request. */
645
719
  dispatch?: NodePlatformDispatchOptions;
646
720
  /**
@@ -695,6 +769,28 @@ interface NodeR2BucketOptions {
695
769
  * maps directly onto a file operation.
696
770
  */
697
771
  declare const createNodeR2Bucket: (options: NodeR2BucketOptions) => R2BucketLike;
772
+ /** The shape `ctx.secrets` reads off `env[name]`: a Cloudflare Secrets Store secret binding. */
773
+ interface NodeSecretBinding {
774
+ get: () => Promise<string>;
775
+ }
776
+ /**
777
+ * Build the `ctx.secrets` bindings for a Node host from environment variables:
778
+ * one binding per name, spread into the `env` the worker and shard are built
779
+ * over. `ctx.secrets.get(name)` then reads `source[name]`.
780
+ *
781
+ * Names are listed rather than every variable in `source` being bound, for the
782
+ * same reason a wrangler config lists `secrets_store_secrets[]`: `ctx.secrets`
783
+ * reaches only what was granted to it. It also keeps the bindings off names the
784
+ * env already carries as plain strings (`LUNORA_ADMIN_TOKEN` and the like),
785
+ * which the runtime reads as strings and a binding object would break; a
786
+ * `LUNORA_*` name is refused for that reason.
787
+ *
788
+ * The value is read when `get()` is called, so an unused secret never has to be
789
+ * set. An unset or empty variable rejects the call.
790
+ * @param names The secret names the app reads through `ctx.secrets`.
791
+ * @param source Where values come from; `process.env` unless given.
792
+ */
793
+ declare const createNodeSecretBindings: (names: ReadonlyArray<string>, source?: Readonly<Record<string, string | undefined>>) => Record<string, NodeSecretBinding>;
698
794
  /**
699
795
  * Present the node shard registry as the `ShardNamespaceLike` a worker is built
700
796
  * over (`createWorker({ shardDO })`).
@@ -774,7 +870,7 @@ declare const bindShardSockets: (shard: ShardSocketHooks, inbound: Pick<NodeShar
774
870
  * Pass the result as `createNodeWorkflowHost({ store })`.
775
871
  */
776
872
  declare const createNodeWorkflowStore: (database: Database.Database) => WorkflowStore;
777
- export { NODE_SCHEDULER_DISPATCH_PATH,
873
+ export { NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron,
778
874
  /**
779
875
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
780
876
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -811,7 +907,9 @@ export { NODE_SCHEDULER_DISPATCH_PATH,
811
907
  * registry as the `shardDO` namespace that worker routes to. Also absent are
812
908
  * the Cloudflare product bindings with no local
813
909
  * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
814
- * Engine, Pipelines, Secrets Store, Hyperdrive.
910
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
911
+ * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
912
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
815
913
  *
816
914
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
817
915
  * for `provision` — which reports, once, which declared features this target
@@ -857,7 +955,9 @@ type NodeDispatchInvocation,
857
955
  * registry as the `shardDO` namespace that worker routes to. Also absent are
858
956
  * the Cloudflare product bindings with no local
859
957
  * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
860
- * Engine, Pipelines, Secrets Store, Hyperdrive.
958
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
959
+ * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
960
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
861
961
  *
862
962
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
863
963
  * for `provision` — which reports, once, which declared features this target
@@ -866,4 +966,4 @@ type NodeDispatchInvocation,
866
966
  * server, which is why both statements above hold at once. See
867
967
  * `plans/234-node-host-findings.md`.
868
968
  */
869
- type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore };
969
+ type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeSecretBinding, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore };
package/dist/index.d.ts CHANGED
@@ -28,6 +28,8 @@ interface NodeDispatchRouteOptions {
28
28
  defaultShardKey: string;
29
29
  /** Runs the call in-process and returns the shard's response, unchanged. */
30
30
  invoke: (call: NodeDispatchInvocation) => Promise<Response>;
31
+ /** Epoch-ms clock for the signature window. Defaults to `Date.now`; tests inject one. */
32
+ now?: () => number;
31
33
  /** `LUNORA_SCHEDULER_SECRET`. When set, a signed request is verified against it. */
32
34
  schedulerSecret?: string;
33
35
  }
@@ -133,6 +135,42 @@ interface NodeHttpServer {
133
135
  /** The `http://host:port` origin the server answers on. */
134
136
  origin: string;
135
137
  }
138
+ /**
139
+ * The connection fields a Cloudflare `Hyperdrive` binding exposes, and the
140
+ * `HyperdriveLike` shape `@lunora/hyperdrive`'s `createHyperdrive` reads.
141
+ * Declared here structurally so this package does not depend on
142
+ * `@lunora/hyperdrive` for a type.
143
+ */
144
+ interface NodeHyperdriveBinding {
145
+ connectionString: string;
146
+ database: string;
147
+ host: string;
148
+ password: string;
149
+ port: number;
150
+ user: string;
151
+ }
152
+ /**
153
+ * Build the `HYPERDRIVE` binding for a Node host from a database URL, by
154
+ * default `process.env.DATABASE_URL`. Put it on the `env` the worker and shard
155
+ * are built over, under the binding name the app reads (`env.HYPERDRIVE`), and
156
+ * the app's own `.hyperdrive((env) => …)` wiring builds `ctx.sql` from it
157
+ * unchanged.
158
+ *
159
+ * There is no pool or query cache in front of the database here: the driver
160
+ * the app constructs from `connectionString` connects to it directly, so its own
161
+ * pool settings are the only ones that apply.
162
+ * A Postgres URL may name a Unix socket the libpq way: an empty host with the
163
+ * socket directory in a `host` query parameter (`postgres:///db?host=/var/run/postgresql`),
164
+ * which becomes the binding's `host`.
165
+ *
166
+ * A URL with any TLS option other than an explicit off (`sslmode=prefer` or
167
+ * `require`, `ssl=true`, `sslrootcert=…`) gets a binding whose discrete fields
168
+ * throw: they cannot carry it, so a pool built from them would silently connect
169
+ * without TLS. `sslmode=disable` and `ssl=false` keep them. Build the driver
170
+ * from `connectionString`, which keeps every query option.
171
+ * @param url A `postgres://`, `postgresql://`, `mysql://` or `mariadb://` URL; `DATABASE_URL` unless given.
172
+ */
173
+ declare const createNodeHyperdrive: (url?: string | undefined) => NodeHyperdriveBinding;
136
174
  /** Build a `ShardKvStore` over a `better-sqlite3` table in the shard's database. */
137
175
  declare const createNodeShardKvStore: (database: Database.Database) => ShardKvStore;
138
176
  /** Options for {@link createNodeQueueHost}. */
@@ -207,6 +245,14 @@ interface NodeQueueHost<Queues extends Record<string, {
207
245
  declare const createNodeQueueHost: <Queues extends Record<string, {
208
246
  isLunoraQueue: true;
209
247
  }>>(database: Database.Database, options: NodeQueueHostOptions<Queues>) => NodeQueueHost<Queues>;
248
+ /** One declared cron job, as {@link NodeSchedulerHost.declareCrons} takes it. */
249
+ interface NodeDeclaredCron {
250
+ args: Record<string, unknown>;
251
+ expression: string;
252
+ functionPath: string;
253
+ /** The job's `cronJobs()` name, unique across the app. Keys its row. */
254
+ name: string;
255
+ }
210
256
  /** Options for {@link createNodeSchedulerHost}. */
211
257
  interface NodeSchedulerHostOptions {
212
258
  /**
@@ -239,6 +285,14 @@ interface NodeSchedulerHostOptions {
239
285
  * TCK's dead-letter legs need.
240
286
  */
241
287
  interface NodeSchedulerHost {
288
+ /**
289
+ * Make `crons` the app's declared cron set: upsert each one, arm it, and
290
+ * delete and disarm any declared row not in the list (a job the app removed
291
+ * or renamed). Every expression is parsed before anything is written, so an
292
+ * invalid one throws and leaves the previous set in place. Throws after
293
+ * `dispose()`.
294
+ */
295
+ declareCrons: (crons: ReadonlyArray<NodeDeclaredCron>) => void;
242
296
  /**
243
297
  * Clear every armed `setTimeout` (one-shot jobs and cron ticks alike) and
244
298
  * put the host into a terminal, closed state: afterwards `schedule()` and
@@ -506,6 +560,13 @@ interface NodeWorkflowHost<Workflows extends Record<string, {
506
560
  declare const createNodeWorkflowHost: <Workflows extends Record<string, {
507
561
  isLunoraWorkflow: true;
508
562
  }>>(options: NodeWorkflowHostOptions<Workflows>) => NodeWorkflowHost<Workflows>;
563
+ /** One entry of the generated `LUNORA_CRONS` map (`_generated/crons.ts`). */
564
+ interface NodeCronJob {
565
+ args?: Record<string, unknown>;
566
+ functionPath?: string;
567
+ name: string;
568
+ workflow?: string;
569
+ }
509
570
  /** Every contract this package provides, composed for one Node process. */
510
571
  interface NodePlatform<Queues extends Record<string, {
511
572
  isLunoraQueue: true;
@@ -641,6 +702,19 @@ type NodePlatformOptions<Queues extends Record<string, {
641
702
  }> = Record<string, never>, Workflows extends Record<string, {
642
703
  isLunoraWorkflow: true;
643
704
  }> = Record<string, never>> = {
705
+ /**
706
+ * The app's declared crons — pass the generated `LUNORA_CRONS` map
707
+ * (`_generated/crons.ts`). Each job is armed on the scheduler and delivered
708
+ * through the same `onDispatch` a scheduled job uses, so it needs `onFetch`
709
+ * (or your own `onDispatch`) to reach a shard; a non-empty map with neither
710
+ * throws. Job names must be unique, every schedule must have a next
711
+ * occurrence, and schedules are read as UTC. The map is the whole declared
712
+ * set: a job declared by an earlier run and absent here is deleted. Omit
713
+ * the option and this process neither fires nor deletes declared jobs, so
714
+ * a script opening the same file leaves a running server's crons alone.
715
+ * Crons registered through `scheduler.cron()` are re-armed either way.
716
+ */
717
+ crons?: Readonly<Record<string, ReadonlyArray<NodeCronJob>>>;
644
718
  /** Secrets for the dispatch route. Omit to leave the route refusing every request. */
645
719
  dispatch?: NodePlatformDispatchOptions;
646
720
  /**
@@ -695,6 +769,28 @@ interface NodeR2BucketOptions {
695
769
  * maps directly onto a file operation.
696
770
  */
697
771
  declare const createNodeR2Bucket: (options: NodeR2BucketOptions) => R2BucketLike;
772
+ /** The shape `ctx.secrets` reads off `env[name]`: a Cloudflare Secrets Store secret binding. */
773
+ interface NodeSecretBinding {
774
+ get: () => Promise<string>;
775
+ }
776
+ /**
777
+ * Build the `ctx.secrets` bindings for a Node host from environment variables:
778
+ * one binding per name, spread into the `env` the worker and shard are built
779
+ * over. `ctx.secrets.get(name)` then reads `source[name]`.
780
+ *
781
+ * Names are listed rather than every variable in `source` being bound, for the
782
+ * same reason a wrangler config lists `secrets_store_secrets[]`: `ctx.secrets`
783
+ * reaches only what was granted to it. It also keeps the bindings off names the
784
+ * env already carries as plain strings (`LUNORA_ADMIN_TOKEN` and the like),
785
+ * which the runtime reads as strings and a binding object would break; a
786
+ * `LUNORA_*` name is refused for that reason.
787
+ *
788
+ * The value is read when `get()` is called, so an unused secret never has to be
789
+ * set. An unset or empty variable rejects the call.
790
+ * @param names The secret names the app reads through `ctx.secrets`.
791
+ * @param source Where values come from; `process.env` unless given.
792
+ */
793
+ declare const createNodeSecretBindings: (names: ReadonlyArray<string>, source?: Readonly<Record<string, string | undefined>>) => Record<string, NodeSecretBinding>;
698
794
  /**
699
795
  * Present the node shard registry as the `ShardNamespaceLike` a worker is built
700
796
  * over (`createWorker({ shardDO })`).
@@ -774,7 +870,7 @@ declare const bindShardSockets: (shard: ShardSocketHooks, inbound: Pick<NodeShar
774
870
  * Pass the result as `createNodeWorkflowHost({ store })`.
775
871
  */
776
872
  declare const createNodeWorkflowStore: (database: Database.Database) => WorkflowStore;
777
- export { NODE_SCHEDULER_DISPATCH_PATH,
873
+ export { NODE_SCHEDULER_DISPATCH_PATH, type NodeCronJob, type NodeDeclaredCron,
778
874
  /**
779
875
  * `@lunora/platform-node` — a Node implementation of the `@lunora/platform`
780
876
  * host contracts (`ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`,
@@ -811,7 +907,9 @@ export { NODE_SCHEDULER_DISPATCH_PATH,
811
907
  * registry as the `shardDO` namespace that worker routes to. Also absent are
812
908
  * the Cloudflare product bindings with no local
813
909
  * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
814
- * Engine, Pipelines, Secrets Store, Hyperdrive.
910
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
911
+ * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
912
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
815
913
  *
816
914
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
817
915
  * for `provision` — which reports, once, which declared features this target
@@ -857,7 +955,9 @@ type NodeDispatchInvocation,
857
955
  * registry as the `shardDO` namespace that worker routes to. Also absent are
858
956
  * the Cloudflare product bindings with no local
859
957
  * equivalent — Vectorize, Workers AI, Browser Rendering, Containers, Analytics
860
- * Engine, Pipelines, Secrets Store, Hyperdrive.
958
+ * Engine, Pipelines. `ctx.secrets` reads environment variables through
959
+ * `createNodeSecretBindings` (`./node-secrets`), and the Hyperdrive binding is
960
+ * built from `DATABASE_URL` by `createNodeHyperdrive` (`./node-hyperdrive`).
861
961
  *
862
962
  * `@lunora/config` ships a `node` **deploy** driver, so `--target node` resolves
863
963
  * for `provision` — which reports, once, which declared features this target
@@ -866,4 +966,4 @@ type NodeDispatchInvocation,
866
966
  * server, which is why both statements above hold at once. See
867
967
  * `plans/234-node-host-findings.md`.
868
968
  */
869
- type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore };
969
+ type NodeDispatchRouteOptions, type NodeGlobalContextDatabaseOptions, type NodeGlobalStore, type NodeGlobalStoreOptions, type NodeHttpServer, type NodeHttpServerOptions, type NodeHyperdriveBinding, type NodePlatform, type NodePlatformDispatchOptions, type NodePlatformOptions, type NodeProfileHandler, type NodeProfileHandlerOptions, type NodeQueueHost, type NodeQueueHostOptions, type NodeR2BucketOptions, type NodeSchedulerHost, type NodeSchedulerHostOptions, type NodeSecretBinding, type NodeShard, type NodeShardHostOptions, type NodeShardRegistry, type NodeShardRegistryOptions, type NodeShardState, type NodeSocketHost, type NodeWorkflowHost, type NodeWorkflowHostOptions, type ShardSocketHooks, bindShardSockets, createNodeDispatchRoute, createNodeGlobalStore, createNodeHttpServer, createNodeHyperdrive, createNodePlatform, createNodeProfileHandler, createNodeQueueHost, createNodeR2Bucket, createNodeSchedulerHost, createNodeSecretBindings, createNodeShardHost, createNodeShardKvStore, createNodeShardNamespace, createNodeShardRegistry, createNodeShardState, createNodeSocketHost, createNodeSqlExec, createNodeWorkflowHost, createNodeWorkflowStore };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{N as r,c as t}from"./packem_shared/node-dispatch-route-Dycdolqs.mjs";import{createNodeGlobalStore as d,createNodeSqlExec as c}from"./packem_shared/createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeHttpServer as N}from"./packem_shared/createNodeHttpServer-D4YVdhJn.mjs";import{createNodeShardKvStore as m}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodePlatform as S}from"./packem_shared/createNodePlatform-BndSFuJZ.mjs";import{createNodeProfileHandler as H}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as h}from"./packem_shared/createNodeQueueHost-CttDb5sY.mjs";import{createNodeR2Bucket as u}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as D}from"./packem_shared/createNodeSchedulerHost-CjgGhVoQ.mjs";import{createNodeShardHost as P}from"./packem_shared/createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardNamespace as _}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as n}from"./packem_shared/createNodeShardRegistry-BKl1QXiv.mjs";import{bindShardSockets as w,createNodeShardState as A}from"./packem_shared/bindShardSockets-9GvSocBW.mjs";import{createNodeSocketHost as T}from"./packem_shared/createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as g}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as y}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{r as NODE_SCHEDULER_DISPATCH_PATH,w as bindShardSockets,t as createNodeDispatchRoute,d as createNodeGlobalStore,N as createNodeHttpServer,S as createNodePlatform,H as createNodeProfileHandler,h as createNodeQueueHost,u as createNodeR2Bucket,D as createNodeSchedulerHost,P as createNodeShardHost,m as createNodeShardKvStore,_ as createNodeShardNamespace,n as createNodeShardRegistry,A as createNodeShardState,T as createNodeSocketHost,c as createNodeSqlExec,g as createNodeWorkflowHost,y as createNodeWorkflowStore};
1
+ import{N as o,c as t}from"./packem_shared/node-dispatch-route-ByuCR26s.mjs";import{createNodeGlobalStore as d,createNodeSqlExec as c}from"./packem_shared/createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeHttpServer as p}from"./packem_shared/createNodeHttpServer-D4YVdhJn.mjs";import{createNodeHyperdrive as m}from"./packem_shared/createNodeHyperdrive-C4Z_s0hY.mjs";import{createNodeShardKvStore as S}from"./packem_shared/createNodeShardKvStore-DVi1OsvH.mjs";import{createNodePlatform as H}from"./packem_shared/createNodePlatform-Cgr4hQvw.mjs";import{createNodeProfileHandler as h}from"./packem_shared/createNodeProfileHandler-MX5xKPg0.mjs";import{createNodeQueueHost as k}from"./packem_shared/createNodeQueueHost-szMV0PBN.mjs";import{createNodeR2Bucket as n}from"./packem_shared/createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as E}from"./packem_shared/createNodeSchedulerHost-DY6TOmXg.mjs";import{createNodeSecretBindings as R}from"./packem_shared/createNodeSecretBindings-C7wh0fOm.mjs";import{createNodeShardHost as _}from"./packem_shared/createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardNamespace as g}from"./packem_shared/createNodeShardNamespace-BgQjDv7V.mjs";import{createNodeShardRegistry as y}from"./packem_shared/createNodeShardRegistry-BKl1QXiv.mjs";import{bindShardSockets as B,createNodeShardState as C}from"./packem_shared/bindShardSockets-9GvSocBW.mjs";import{createNodeSocketHost as W}from"./packem_shared/createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as G}from"./packem_shared/createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as K}from"./packem_shared/createNodeWorkflowStore-CL7RYP6H.mjs";export{o as NODE_SCHEDULER_DISPATCH_PATH,B as bindShardSockets,t as createNodeDispatchRoute,d as createNodeGlobalStore,p as createNodeHttpServer,m as createNodeHyperdrive,H as createNodePlatform,h as createNodeProfileHandler,k as createNodeQueueHost,n as createNodeR2Bucket,E as createNodeSchedulerHost,R as createNodeSecretBindings,_ as createNodeShardHost,S as createNodeShardKvStore,g as createNodeShardNamespace,y as createNodeShardRegistry,C as createNodeShardState,W as createNodeSocketHost,c as createNodeSqlExec,G as createNodeWorkflowHost,K as createNodeWorkflowStore};
@@ -1 +1 @@
1
- import{N as o,c as r,a as t}from"./node-dispatch-route-Dycdolqs.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-ByuCR26s.mjs";export{o as NODE_SCHEDULER_DISPATCH_PATH,r as createNodeDispatchRoute,t as createShardInvoke};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";const m=/^\//u,R=/^\[(.*)\]$/u,h=new Set(["disable","disabled"]),b=new Set(["0","false"]),A=/[-_]/gu,L=o=>[...o.entries()].filter(([e,t])=>{const r=e.toLowerCase().replaceAll(A,""),a=t.toLowerCase();return r==="sslmode"?!h.has(a):r.startsWith("ssl")&&!(r==="ssl"&&b.has(a))}).map(([e])=>e),O=(o,e)=>{const t=()=>{throw new s("VALIDATION_ERROR",`@lunora/platform-node: the Hyperdrive database URL sets ${e.join(", ")}, which the discrete host/port/user/password/database fields cannot carry, so a driver built from them would connect without TLS — build the driver from connectionString instead`)};return Object.defineProperties({connectionString:o},{database:{enumerable:!0,get:t},host:{enumerable:!0,get:t},password:{enumerable:!0,get:t},port:{enumerable:!0,get:t},user:{enumerable:!0,get:t}})},l=new Set(["postgres:","postgresql:"]),w=/^\d+$/u,f=65535,S=(o,e)=>{if(o.port!=="")return Number(o.port);const t=l.has(o.protocol)?o.searchParams.get("port")??void 0:void 0;if(t===void 0)return e;const r=w.test(t)?Number(t):Number.NaN;if(!(r>=1&&r<=f))throw new s("VALIDATION_ERROR","@lunora/platform-node: the Hyperdrive database URL's port query parameter must be a whole number from 1 to 65535");return r},v={"mariadb:":3306,"mysql:":3306,"postgres:":5432,"postgresql:":5432},y=(o=process.env.DATABASE_URL)=>{if(o===void 0||o==="")throw new s("VALIDATION_ERROR","@lunora/platform-node: Hyperdrive needs a database URL — set DATABASE_URL or pass one to createNodeHyperdrive");let e,t,r,a,n;try{e=new URL(o),t=decodeURIComponent(e.pathname.replace(m,"")),r=decodeURIComponent(e.hostname),a=decodeURIComponent(e.password),n=decodeURIComponent(e.username)}catch{throw new s("VALIDATION_ERROR","@lunora/platform-node: the Hyperdrive database URL is not a valid URL")}const d=v[e.protocol];if(d===void 0)throw new s("VALIDATION_ERROR",`@lunora/platform-node: the Hyperdrive database URL uses "${e.protocol}", but Hyperdrive serves only postgres:, postgresql:, mysql: and mariadb:`);const p=l.has(e.protocol)?e.searchParams.get("host")??"":"",c=r===""?p:r.replace(R,"$1");if(c===""||t==="")throw new s("VALIDATION_ERROR","@lunora/platform-node: the Hyperdrive database URL needs both a host and a database name");const u=S(e,d),i=L(e.searchParams);return i.length>0?O(o,i):{connectionString:o,database:t,host:c,password:a,port:u,user:n}};export{y as createNodeHyperdrive};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{NODE_CAPABILITIES as R}from"@lunora/platform";import{a as g,c as D,i as E,A as b}from"./node-dispatch-route-ByuCR26s.mjs";import{createNodeGlobalStore as y}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as T}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeQueueHost as I}from"./createNodeQueueHost-szMV0PBN.mjs";import{createNodeR2Bucket as F}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as O}from"./createNodeSchedulerHost-DY6TOmXg.mjs";import{createNodeShardHost as L}from"./createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardRegistry as B}from"./createNodeShardRegistry-BKl1QXiv.mjs";import{createNodeSocketHost as H}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as q}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as P}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const C="__root__",U=e=>Object.entries(e).flatMap(([r,o])=>o.map(t=>{if(t.functionPath===void 0)throw new a("VALIDATION_ERROR",t.workflow===void 0?`@lunora/platform-node: cron job "${t.name}" has neither a function target nor a workflow target`:`@lunora/platform-node: cron job "${t.name}" starts workflow "${t.workflow}", which this host cannot do from a cron tick — schedule a function that calls ctx.workflows.get(name).create() instead`);return{args:t.args??{},expression:r,functionPath:t.functionPath,name:t.name}})),V=(e,r)=>{const o=U(e);if(o.length>0&&!r)throw new a("VALIDATION_ERROR","@lunora/platform-node: `crons` declares jobs but nothing can deliver them — pass `onFetch` (to run them on the shard) or `onDispatch`");return o},$=(e,r)=>async(o,t,c)=>{if(E(o,r,C))throw new a("BAD_REQUEST",b);const s=await e({args:t,functionPath:o,id:c.id,identity:void 0,scheduledFor:c.scheduledFor,shardKey:r,traceparent:void 0});if(!s.ok)throw new a("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${o} was refused with status ${String(s.status)}`)},oe=(e={})=>{const r=[],{database:o,dispose:t,drain:c,host:s}=L(e);r.push(t);try{const n=T(o),d=B(e);r.push(()=>{d.close()});const{directory:l}=d,u=g(l,e.onFetch!==void 0),m=D({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:u,schedulerSecret:e.dispatch?.schedulerSecret}),w=e.onFetch===void 0?void 0:$(u,e.shardKey??"__root__"),{declareCrons:v,dispose:S,scheduler:p}=O(o,{...e,onDispatch:e.onDispatch??w}),{socket:k}=H(o);r.push(S),e.crons!==void 0&&v(V(e.crons,e.onDispatch!==void 0||e.onFetch!==void 0));const _=e.queues===void 0?void 0:I(o,{onBatch:e.onQueueBatch??(()=>{throw new a("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}),A=e.objectStorageDirectory===void 0?void 0:F({directory:e.objectStorageDirectory}),i=e.globalTablesPath===void 0?void 0:y({path:e.globalTablesPath});i!==void 0&&r.push(()=>{i.dispose()});const N=e.workflows===void 0?void 0:q({store:P(o),workflows:e.workflows}),f=()=>{for(const h of r.toReversed())h()};return{capabilities:R,close:f,directory:l,dispatch:h=>m(h),drain:c,globalTables:i,kv:n,objectStorage:A,queues:_,scheduler:p,shard:s,sockets:k,workflows:N,[Symbol.dispose]:f}}catch(n){for(const d of r.toReversed())try{d()}catch{}throw n}};export{$ as createJobDelivery,oe as createNodePlatform};
@@ -1,4 +1,4 @@
1
- import{randomUUID as F}from"node:crypto";import{deserialize as H,serialize as W}from"node:v8";import{LunoraError as m}from"@lunora/errors";import{isQueueDefinition as X,queueDefaultName as $,queueBindingName as Q}from"@lunora/queue";const _={maxBatchSize:10,maxBatchTimeoutSeconds:5,maxRetries:3,retryDelaySeconds:0,visibilityTimeoutMs:3e4},V=43200,A=131072,S=262144,k=(e,i)=>{switch(i){case"bytes":{if(e instanceof ArrayBuffer)return Buffer.from(e);if(ArrayBuffer.isView(e))return Buffer.from(e.buffer,e.byteOffset,e.byteLength);throw new m("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "bytes" needs an ArrayBuffer or a typed array')}case"text":{if(typeof e!="string")throw new m("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "text" needs a string');return Buffer.from(e,"utf8")}case"v8":return W(e);default:return Buffer.from(JSON.stringify(e??null),"utf8")}},O=(e,i,R)=>{const E=k(e,i);if(E.byteLength>A)throw new m("VALIDATION_ERROR",`@lunora/platform-node: a message for queue "${R}" encodes to ${String(E.byteLength)} bytes, over the Cloudflare Queues ceiling of ${String(A)} (128 KiB) per message — store the payload and enqueue a reference to it`);return E},D=(e,i)=>{switch(i){case"bytes":return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);case"text":return e.toString("utf8");case"v8":return H(e);default:return JSON.parse(e.toString("utf8"))}},Y=e=>{try{return D(e.body,e.content_type)}catch{return}},y=e=>e===void 0||!Number.isFinite(e)?0:Math.min(Math.max(0,Math.floor(e)),V)*1e3,K=(e,i)=>{e.pragma("journal_mode = WAL"),e.exec(`CREATE TABLE IF NOT EXISTS _lunora_queue_messages (
1
+ import{randomUUID as F}from"node:crypto";import{deserialize as H,serialize as W}from"node:v8";import{LunoraError as m}from"@lunora/errors";import{isQueueDefinition as X,queueDefaultName as $,queueBindingName as Q}from"@lunora/queue";const _={maxBatchSize:10,maxBatchTimeoutSeconds:5,maxRetries:3,retryDelaySeconds:0,visibilityTimeoutMs:3e4},V=86400,A=131072,S=262144,k=(e,i)=>{switch(i){case"bytes":{if(e instanceof ArrayBuffer)return Buffer.from(e);if(ArrayBuffer.isView(e))return Buffer.from(e.buffer,e.byteOffset,e.byteLength);throw new m("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "bytes" needs an ArrayBuffer or a typed array')}case"text":{if(typeof e!="string")throw new m("VALIDATION_ERROR",'@lunora/platform-node: queue contentType "text" needs a string');return Buffer.from(e,"utf8")}case"v8":return W(e);default:return Buffer.from(JSON.stringify(e??null),"utf8")}},O=(e,i,R)=>{const E=k(e,i);if(E.byteLength>A)throw new m("VALIDATION_ERROR",`@lunora/platform-node: a message for queue "${R}" encodes to ${String(E.byteLength)} bytes, over the Cloudflare Queues ceiling of ${String(A)} (128 KiB) per message — store the payload and enqueue a reference to it`);return E},D=(e,i)=>{switch(i){case"bytes":return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);case"text":return e.toString("utf8");case"v8":return H(e);default:return JSON.parse(e.toString("utf8"))}},Y=e=>{try{return D(e.body,e.content_type)}catch{return}},y=e=>e===void 0||!Number.isFinite(e)?0:Math.min(Math.max(0,Math.ceil(e)),V)*1e3,K=(e,i)=>{e.pragma("journal_mode = WAL"),e.exec(`CREATE TABLE IF NOT EXISTS _lunora_queue_messages (
2
2
  id TEXT PRIMARY KEY,
3
3
  queue TEXT NOT NULL,
4
4
  body BLOB NOT NULL,
@@ -0,0 +1,15 @@
1
+ import{randomUUID as ie}from"node:crypto";import{serialize as N,deserialize as v}from"node:v8";import{LunoraError as F}from"@lunora/errors";import le from"@lunora/scheduler/validate";import{parse as de}from"@visulima/cron-parser/cloudflare";const ue={seconds:"optional",tz:"UTC"},T={backoffMultiplier:2,initialDelayMs:1e3,maxAttempts:5,maxDelayMs:6e4},R=2147483647,L=6e4,J=L/3,me=1e3,pe=5,_e=20,j=10,D=6048e5,X=(s,u)=>{if(!le(s))throw new F("VALIDATION_ERROR",`@lunora/platform-node: ${u} has cron expression "${s}", which is invalid or never occurs`)},E="declared:",$=s=>s.key.startsWith(E)?`job "${s.key.slice(E.length)}" (${s.function_path})`:`"${s.expression}" (${s.function_path})`,fe=(s,u)=>{const h=u?.initialDelayMs??T.initialDelayMs,g=u?.backoffMultiplier??T.backoffMultiplier,S=u?.maxDelayMs??T.maxDelayMs;return Math.min(S,h*g**Math.max(0,s-1))},Ne=(s,u={})=>{s.exec(`CREATE TABLE IF NOT EXISTS _lunora_scheduler_jobs (
2
+ id TEXT PRIMARY KEY,
3
+ function_path TEXT NOT NULL,
4
+ args BLOB NOT NULL,
5
+ scheduled_for INTEGER NOT NULL,
6
+ attempts INTEGER NOT NULL DEFAULT 0,
7
+ retry BLOB,
8
+ state TEXT NOT NULL DEFAULT 'pending'
9
+ )`);const h=e=>s.prepare("PRAGMA table_info(_lunora_scheduler_jobs)").all().some(t=>t.name===e),g=e=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},S=e=>{for(let t=0;;t+=1)try{s.exec(`ALTER TABLE _lunora_scheduler_jobs ADD COLUMN ${e} INTEGER`);return}catch(r){if(h(e))return;if(!(r instanceof Error&&"code"in r&&r.code==="SQLITE_BUSY")||t>=pe)throw r;g(_e*2**t)}};for(const e of["claimed_at","completed_at"])h(e)||S(e);s.exec("CREATE INDEX IF NOT EXISTS _lunora_scheduler_jobs_state_completed ON _lunora_scheduler_jobs (state, completed_at)"),s.exec(`CREATE TABLE IF NOT EXISTS _lunora_scheduler_crons (
10
+ key TEXT PRIMARY KEY,
11
+ expression TEXT NOT NULL,
12
+ function_path TEXT NOT NULL,
13
+ args BLOB NOT NULL
14
+ )`);const Y=s.prepare("INSERT INTO _lunora_scheduler_jobs (id, function_path, args, scheduled_for, retry) VALUES (?, ?, ?, ?, ?)"),I=s.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE id = ?"),w=s.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE state = ? ORDER BY scheduled_for"),G=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'canceled', completed_at = ? WHERE id = ? AND state = 'pending'"),V=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ?"),x=s.prepare("DELETE FROM _lunora_scheduler_jobs WHERE state IN ('succeeded', 'canceled') AND completed_at <= ?"),q=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'succeeded', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ?"),z=s.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND claimed_at = ? AND state = 'pending'"),K=s.prepare("UPDATE _lunora_scheduler_jobs SET attempts = ?, scheduled_for = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),Q=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),Z=s.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND state = 'pending' AND scheduled_for <= ? AND (claimed_at IS NULL OR claimed_at < ?) RETURNING *"),ee=s.prepare("UPDATE _lunora_scheduler_jobs SET state = 'pending', attempts = 0, completed_at = NULL, scheduled_for = ? WHERE id = ? AND state = 'dead'"),P=s.prepare(`INSERT INTO _lunora_scheduler_crons (key, expression, function_path, args) VALUES (?, ?, ?, ?)
15
+ ON CONFLICT (key) DO UPDATE SET expression = excluded.expression, function_path = excluded.function_path, args = excluded.args`),W=s.prepare("SELECT * FROM _lunora_scheduler_crons"),B=s.prepare("SELECT * FROM _lunora_scheduler_crons WHERE key = ?"),te=s.prepare("DELETE FROM _lunora_scheduler_crons WHERE key = ?"),l=()=>s.open,y=()=>s.inTransaction,H=e=>e===null?void 0:v(e);let c=!1;const k=async()=>{c||!l()||!y()||(await new Promise(e=>{setTimeout(e,j).unref()}),await k())},_=new Map,m=new Map,M=new Set;let O=new Set;const U=e=>({attempts:e.attempts,functionPath:e.function_path,id:e.id,scheduledFor:e.scheduled_for}),C=e=>{const t=_.get(e);t!==void 0&&(clearTimeout(t),_.delete(e))},p=(e,t)=>{C(e);const r=Math.max(0,t-Date.now());if(r>R){const n=setTimeout(()=>{p(e,t)},R);_.set(e,n);return}const o=setTimeout(()=>{se(e).catch(()=>{})},r);_.set(e,o)},re=e=>{const t=I.get(e);!c&&t?.state==="pending"&&p(e,t.claimed_at===null?t.scheduled_for:t.claimed_at+L)},ne=(e,t)=>{if(y()){c||p(e,t+j);return}try{const r=Z.get(t,e,t,t-L);return r===void 0&&re(e),r}catch{!c&&l()&&p(e,Date.now()+me);return}},oe=(e,t)=>{let r=t,o;const n=a=>{o=setTimeout(()=>{if(!l())return;if(y()){n(j);return}const i=Date.now();try{z.run(i,e,r).changes===1&&(r=i)}catch{}n(J)},a),o.unref()};return n(J),{release:()=>{clearTimeout(o)},stamp:()=>r}},se=async e=>{if(_.delete(e),!l())return;const t=Date.now(),r=ne(e,t);if(r===void 0)return;const o=r.attempts+1,n=H(r.retry),a=oe(e,t);try{if(await u.onDispatch?.(r.function_path,v(r.args),{attempts:o,id:e,scheduledFor:r.scheduled_for}),await k(),l()&&!y()){const i=Date.now();q.run(o,i,e,a.stamp()),x.run(i-D)}}catch{if(await k(),c||!l())return;const i=n?.maxAttempts??T.maxAttempts;if(o>=i){Q.run(o,Date.now(),e,a.stamp());return}const d=Date.now()+fe(o,n);K.run(o,d,e,a.stamp()).changes===1&&p(e,d)}finally{a.release()}};let b,A;const f=e=>{if(M.has(e.key))return;const t=m.get(e.key);t!==void 0&&clearTimeout(t);let r;try{r=de(e.expression,ue).next().getTime()}catch{return}const o=Math.max(0,r-Date.now());if(o>R)return m.set(e.key,setTimeout(()=>{f(e)},R)),r;const n=setTimeout(()=>{if(m.delete(e.key),c||!l())return;let a;try{a=B.get(e.key)}catch(d){A(e,`could not read its row before the tick due ${new Date(r).toISOString()}, so that tick was skipped`,d);return}if(a===void 0){b(e,r,void 0);return}if(a.expression!==e.expression){f(a);return}const i=a;M.add(e.key),(async()=>{let d;try{await u.onDispatch?.(i.function_path,v(i.args),{attempts:0,id:`${e.key}:${String(r)}`,scheduledFor:r})}catch(ce){d={error:ce}}finally{M.delete(e.key)}b(i,r,d)})().catch(d=>{A(i,"failed to settle its tick",d)})},o);return m.set(e.key,n),r};A=(e,t,r)=>{const o=c||!l()?void 0:f(e),n=o===void 0?"none scheduled, the scheduler is closed":new Date(o).toISOString();return console.error(`[@lunora/platform-node] cron ${$(e)} ${t}; re-armed from its last known definition, next run: ${n}`,r),o},b=(e,t,r)=>{let o;if(!c&&l()){let n,a=!1;try{n=B.get(e.key)}catch(i){a=!0,o=A(e,"could not read its row after its tick",i)}n!==void 0?o=f(n):!a&&O.has(e.key)&&(O.delete(e.key),console.warn(`[@lunora/platform-node] declared cron ${$(e)} was removed from the database by another process passing \`crons\`; it stops firing here`))}if(r!==void 0){const n=o===void 0?"none scheduled":new Date(o).toISOString();console.error(`[@lunora/platform-node] cron ${$(e)} tick due ${new Date(t).toISOString()} failed; next run: ${n}`,r.error)}};const ae={cancel:async e=>{if(c)return!1;C(e);const t=Date.now(),r=G.run(t,e).changes>0;return x.run(t-D),r},cron:async(e,t,r)=>{if(c)throw new Error("platform closed: cannot register a cron");X(e,`cron for ${t}`);const o={args:N(r??{}),expression:e,function_path:t,key:`${e} ${t}`};P.run(o.key,o.expression,o.function_path,o.args),f(o)},deadLetter:{list:async()=>c||!l()?[]:w.all("dead").map(e=>U(e)),requeue:async e=>{if(c||!l())return!1;const t=Date.now();return ee.run(t,e).changes===0?!1:(p(e,t),!0)}},get:async e=>{const t=c||!l()?void 0:I.get(e);if(t===void 0||t.completed_at!==null&&t.state!=="dead"&&t.completed_at<=Date.now()-D)return null;const r={canceled:"canceled",dead:"failed",pending:"pending",succeeded:"succeeded"},o=t.state==="pending"&&t.claimed_at!==null&&t.claimed_at>=Date.now()-L,n={...U(t),state:o?"running":r[t.state]};return t.completed_at!==null&&(n.completedAt=t.completed_at),n},list:async()=>c||!l()?[]:w.all("pending").map(e=>U(e)),schedule:async(e,t,r)=>{if(c)throw new Error("platform closed: cannot schedule a job");if(r?.retry?.forever===!0)throw new F("INVALID_INPUT","retry.forever is not supported by the Node scheduler host; set a finite retry.maxAttempts");const o=`node-job-${ie()}`;let n;return r?.at===void 0?n=Date.now()+(r?.delayMs??0):n=typeof r.at=="number"?r.at:r.at.getTime(),Y.run(o,e,N(t),n,r?.retry===void 0?null:N(r.retry)),p(o,n),{id:o,scheduledFor:n}}};x.run(Date.now()-D);for(const e of w.all("pending"))p(e.id,e.scheduled_for);for(const e of W.all())e.key.startsWith(E)||f(e);return{declareCrons:e=>{if(c)throw new Error("platform closed: cannot declare crons");const t=new Set;for(const n of e){if(t.has(n.name))throw new F("VALIDATION_ERROR",`@lunora/platform-node: two declared cron jobs are named "${n.name}"; cron job names must be unique`);t.add(n.name),X(n.expression,`cron job "${n.name}"`)}const r=e.map(n=>({args:N(n.args),expression:n.expression,function_path:n.functionPath,key:`${E}${n.name}`})),o=new Set(r.map(n=>n.key));s.transaction(()=>{for(const n of W.all())n.key.startsWith(E)&&!o.has(n.key)&&te.run(n.key);for(const n of r)P.run(n.key,n.expression,n.function_path,n.args)}).immediate();for(const[n,a]of m)n.startsWith(E)&&!o.has(n)&&(clearTimeout(a),m.delete(n));O=o;for(const n of r)f(n)},dispose:()=>{for(const e of _.values())clearTimeout(e);for(const e of m.values())clearTimeout(e);_.clear(),m.clear(),c=!0},scheduler:ae,simulateDeadLetter:async e=>{const t=I.get(e);if(t?.state!=="pending")return!1;C(e);const r=H(t.retry);return V.run((r?.maxAttempts??T.maxAttempts)+1,Date.now(),e),!0}}};export{Ne as createNodeSchedulerHost};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";const a="LUNORA_",c=(r,t=process.env)=>{const o=r.filter(e=>e.startsWith(a));if(o.length>0)throw new s("VALIDATION_ERROR",`@lunora/platform-node: ${o.join(", ")} cannot be a ctx.secrets binding — Lunora reads ${a}* env vars as plain strings, and a binding object spread over one would replace it (an admin token would stop working). Keep it a plain env value, or read your own secret under another name`);return Object.fromEntries(r.map(e=>[e,{get:async()=>{const n=Object.hasOwn(t,e)?t[e]:void 0;if(typeof n!="string"||n==="")throw new s("INTERNAL",`ctx.secrets: environment variable "${e}" is not set on this Node host`);return n}}]))};export{c as createNodeSecretBindings};
@@ -0,0 +1,2 @@
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 E=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},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},g="/_lunora/scheduler/dispatch",_="__lunora_relation__:",y=t=>t.startsWith(_),h="agents:agentRun",S=(t,e,n)=>t===h&&e!==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\``,w=(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())},m="x-lunora-scheduler-signature",p="x-lunora-scheduler-timestamp",D=5*6e4,T=t=>["v1",String(t.timestamp),t.userId??"",t.identity??"",t.body].join(`
2
+ `),R=(t,e)=>f(t,T(e)),N=async(t,e,n)=>{const o=t.headers.get(m),{schedulerSecret:a}=n;if(o!==null&&o.length>0&&a!==void 0&&a.length>0){const r=t.headers.get(p);if(r===null||!/^\d+$/u.test(r))return!1;const s=Number(r);if(!Number.isSafeInteger(s)||Math.abs((n.now??Date.now)()-s)>D)return!1;const d=await R(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 w(t,n.adminToken)},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 E(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 N(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(y(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(S(r.functionPath,s,e.defaultShardKey))throw new i("BAD_REQUEST",A);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=g;export{A,M as N,B as a,k 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.217",
3
+ "version": "1.0.0-alpha.219",
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",
@@ -11,7 +11,7 @@
11
11
  ],
12
12
  "homepage": "https://lunora.sh",
13
13
  "bugs": "https://github.com/anolilab/lunora/issues",
14
- "license": "FSL-1.1-Apache-2.0",
14
+ "license": "Apache-2.0",
15
15
  "author": {
16
16
  "name": "Daniel Bannert",
17
17
  "email": "d.bannert@anolilab.de"
@@ -50,14 +50,15 @@
50
50
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
51
51
  "@lunora/platform": "1.0.0-alpha.80",
52
52
  "@lunora/queue": "1.0.0-alpha.143",
53
- "@lunora/runtime": "^1.0.0-alpha.276",
53
+ "@lunora/runtime": "^1.0.0-alpha.287",
54
+ "@lunora/scheduler": "^1.0.0-alpha.170",
54
55
  "@lunora/sql-store": "^1.0.0-alpha.234",
55
56
  "@lunora/workflow": "^1.0.0-alpha.111",
56
57
  "@visulima/cron-parser": "2.0.0",
57
58
  "@visulima/workflow": "4.0.0",
58
59
  "better-sqlite3": "^13.0.3",
59
60
  "pprof-format": "2.3.1",
60
- "ws": "^8.21.0"
61
+ "ws": "^8.22.1"
61
62
  },
62
63
  "peerDependencies": {
63
64
  "@lunora/shard-engine": ">=1.0.0-alpha.45 <2.0.0-0"
@@ -1 +0,0 @@
1
- import{LunoraError as u}from"@lunora/errors";import{NODE_CAPABILITIES as b}from"@lunora/platform";import{a as A,c as E,i as D,A as R}from"./node-dispatch-route-Dycdolqs.mjs";import{createNodeGlobalStore as y}from"./createNodeGlobalStore-CD4DiqeS.mjs";import{createNodeShardKvStore as g}from"./createNodeShardKvStore-DVi1OsvH.mjs";import{createNodeQueueHost as T}from"./createNodeQueueHost-CttDb5sY.mjs";import{createNodeR2Bucket as F}from"./createNodeR2Bucket-D_jsnenX.mjs";import{createNodeSchedulerHost as I}from"./createNodeSchedulerHost-CjgGhVoQ.mjs";import{createNodeShardHost as B}from"./createNodeShardHost-Bhbm4txQ.mjs";import{createNodeShardRegistry as H}from"./createNodeShardRegistry-BKl1QXiv.mjs";import{createNodeSocketHost as L}from"./createNodeSocketHost-ByOmEGFe.mjs";import{createNodeWorkflowHost as q}from"./createNodeWorkflowHost-B76TKiw_.mjs";import{createNodeWorkflowStore as O}from"./createNodeWorkflowStore-CL7RYP6H.mjs";const U="__root__",Q=(e,o)=>async(r,c,t)=>{if(D(r,o,U))throw new u("BAD_REQUEST",R);const s=await e({args:c,functionPath:r,id:t.id,identity:void 0,scheduledFor:t.scheduledFor,shardKey:o,traceparent:void 0});if(!s.ok)throw new u("SERVICE_UNAVAILABLE",`@lunora/platform-node: scheduled job ${r} was refused with status ${String(s.status)}`)},X=(e={})=>{const o=[],{database:r,dispose:c,drain:t,host:s}=B(e);o.push(c);try{const d=g(r),a=H(e);o.push(()=>{a.close()});const{directory:l}=a,n=A(l,e.onFetch!==void 0),m=E({adminToken:e.dispatch?.adminToken,defaultShardKey:"__root__",invoke:n,schedulerSecret:e.dispatch?.schedulerSecret}),S=e.onFetch===void 0?void 0:Q(n,e.shardKey??"__root__"),{dispose:w,scheduler:v}=I(r,{...e,onDispatch:e.onDispatch??S}),{socket:_}=L(r);o.push(w);const p=e.queues===void 0?void 0:T(r,{onBatch:e.onQueueBatch??(()=>{throw new u("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}),k=e.objectStorageDirectory===void 0?void 0:F({directory:e.objectStorageDirectory}),i=e.globalTablesPath===void 0?void 0:y({path:e.globalTablesPath});i!==void 0&&o.push(()=>{i.dispose()});const N=e.workflows===void 0?void 0:q({store:O(r),workflows:e.workflows}),f=()=>{for(const h of o.toReversed())h()};return{capabilities:b,close:f,directory:l,dispatch:h=>m(h),drain:t,globalTables:i,kv:d,objectStorage:k,queues:p,scheduler:v,shard:s,sockets:_,workflows:N,[Symbol.dispose]:f}}catch(d){for(const a of o.toReversed())try{a()}catch{}throw d}};export{Q as createJobDelivery,X as createNodePlatform};
@@ -1,15 +0,0 @@
1
- import{randomUUID as Z}from"node:crypto";import{deserialize as U,serialize as w}from"node:v8";import{LunoraError as ee}from"@lunora/errors";import{parse as b}from"@visulima/cron-parser/cloudflare";const j={seconds:"optional"},p={backoffMultiplier:2,initialDelayMs:1e3,maxAttempts:5,maxDelayMs:6e4},A=2147483647,N=6e4,F=N/3,te=1e3,re=5,ne=20,O=10,h=6048e5,oe=(o,_)=>{const E=_?.initialDelayMs??p.initialDelayMs,D=_?.backoffMultiplier??p.backoffMultiplier,L=_?.maxDelayMs??p.maxDelayMs;return Math.min(L,E*D**Math.max(0,o-1))},ie=(o,_={})=>{o.exec(`CREATE TABLE IF NOT EXISTS _lunora_scheduler_jobs (
2
- id TEXT PRIMARY KEY,
3
- function_path TEXT NOT NULL,
4
- args BLOB NOT NULL,
5
- scheduled_for INTEGER NOT NULL,
6
- attempts INTEGER NOT NULL DEFAULT 0,
7
- retry BLOB,
8
- state TEXT NOT NULL DEFAULT 'pending'
9
- )`);const E=e=>o.prepare("PRAGMA table_info(_lunora_scheduler_jobs)").all().some(t=>t.name===e),D=e=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)},L=e=>{for(let t=0;;t+=1)try{o.exec(`ALTER TABLE _lunora_scheduler_jobs ADD COLUMN ${e} INTEGER`);return}catch(r){if(E(e))return;if(!(r instanceof Error&&"code"in r&&r.code==="SQLITE_BUSY")||t>=re)throw r;D(ne*2**t)}};for(const e of["claimed_at","completed_at"])E(e)||L(e);o.exec("CREATE INDEX IF NOT EXISTS _lunora_scheduler_jobs_state_completed ON _lunora_scheduler_jobs (state, completed_at)"),o.exec(`CREATE TABLE IF NOT EXISTS _lunora_scheduler_crons (
10
- key TEXT PRIMARY KEY,
11
- expression TEXT NOT NULL,
12
- function_path TEXT NOT NULL,
13
- args BLOB NOT NULL
14
- )`);const P=o.prepare("INSERT INTO _lunora_scheduler_jobs (id, function_path, args, scheduled_for, retry) VALUES (?, ?, ?, ?, ?)"),y=o.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE id = ?"),R=o.prepare("SELECT * FROM _lunora_scheduler_jobs WHERE state = ? ORDER BY scheduled_for"),k=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'canceled', completed_at = ? WHERE id = ? AND state = 'pending'"),v=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ?"),g=o.prepare("DELETE FROM _lunora_scheduler_jobs WHERE state IN ('succeeded', 'canceled') AND completed_at <= ?"),B=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'succeeded', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ?"),H=o.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND claimed_at = ? AND state = 'pending'"),J=o.prepare("UPDATE _lunora_scheduler_jobs SET attempts = ?, scheduled_for = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),W=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'dead', attempts = ?, completed_at = ?, claimed_at = NULL WHERE id = ? AND claimed_at = ? AND state = 'pending'"),X=o.prepare("UPDATE _lunora_scheduler_jobs SET claimed_at = ? WHERE id = ? AND state = 'pending' AND scheduled_for <= ? AND (claimed_at IS NULL OR claimed_at < ?) RETURNING *"),Y=o.prepare("UPDATE _lunora_scheduler_jobs SET state = 'pending', attempts = 0, completed_at = NULL, scheduled_for = ? WHERE id = ? AND state = 'dead'"),G=o.prepare(`INSERT INTO _lunora_scheduler_crons (key, expression, function_path, args) VALUES (?, ?, ?, ?)
15
- ON CONFLICT (key) DO UPDATE SET expression = excluded.expression, args = excluded.args`),$=o.prepare("SELECT * FROM _lunora_scheduler_crons"),a=()=>o.open,T=()=>o.inTransaction,x=e=>e===null?void 0:U(e);let s=!1;const S=async()=>{s||!a()||!T()||(await new Promise(e=>{setTimeout(e,O).unref()}),await S())},i=new Map,m=new Map,I=e=>({attempts:e.attempts,functionPath:e.function_path,id:e.id,scheduledFor:e.scheduled_for}),M=e=>{const t=i.get(e);t!==void 0&&(clearTimeout(t),i.delete(e))},l=(e,t)=>{M(e);const r=Math.max(0,t-Date.now());if(r>A){const c=setTimeout(()=>{l(e,t)},A);i.set(e,c);return}const n=setTimeout(()=>{K(e).catch(()=>{})},r);i.set(e,n)},V=e=>{const t=y.get(e);!s&&t?.state==="pending"&&l(e,t.claimed_at===null?t.scheduled_for:t.claimed_at+N)},q=(e,t)=>{if(T()){s||l(e,t+O);return}try{const r=X.get(t,e,t,t-N);return r===void 0&&V(e),r}catch{!s&&a()&&l(e,Date.now()+te);return}},z=(e,t)=>{let r=t,n;const c=u=>{n=setTimeout(()=>{if(!a())return;if(T()){c(O);return}const d=Date.now();try{H.run(d,e,r).changes===1&&(r=d)}catch{}c(F)},u),n.unref()};return c(F),{release:()=>{clearTimeout(n)},stamp:()=>r}},K=async e=>{if(i.delete(e),!a())return;const t=Date.now(),r=q(e,t);if(r===void 0)return;const n=r.attempts+1,c=x(r.retry),u=z(e,t);try{if(await _.onDispatch?.(r.function_path,U(r.args),{attempts:n,id:e,scheduledFor:r.scheduled_for}),await S(),a()&&!T()){const d=Date.now();B.run(n,d,e,u.stamp()),g.run(d-h)}}catch{if(await S(),s||!a())return;const d=c?.maxAttempts??p.maxAttempts;if(n>=d){W.run(n,Date.now(),e,u.stamp());return}const C=Date.now()+oe(n,c);J.run(n,C,e,u.stamp()).changes===1&&l(e,C)}finally{u.release()}},f=e=>{const t=m.get(e.key);t!==void 0&&clearTimeout(t);let r;try{r=b(e.expression,j).next().getTime()}catch{return}const n=Math.max(0,r-Date.now());if(n>A){m.set(e.key,setTimeout(()=>{f(e)},A));return}const c=setTimeout(()=>{m.delete(e.key),(async()=>{try{await _.onDispatch?.(e.function_path,U(e.args),{attempts:0,id:`${e.key}:${String(r)}`,scheduledFor:r})}catch{}!s&&a()&&f(e)})().catch(()=>{})},n);m.set(e.key,c)},Q={cancel:async e=>{if(s)return!1;M(e);const t=Date.now(),r=k.run(t,e).changes>0;return g.run(t-h),r},cron:async(e,t,r)=>{if(s)throw new Error("platform closed: cannot register a cron");b(e,j);const n={args:w(r??{}),expression:e,function_path:t,key:`${e} ${t}`};G.run(n.key,n.expression,n.function_path,n.args),f(n)},deadLetter:{list:async()=>s||!a()?[]:R.all("dead").map(e=>I(e)),requeue:async e=>{if(s||!a())return!1;const t=Date.now();return Y.run(t,e).changes===0?!1:(l(e,t),!0)}},get:async e=>{const t=s||!a()?void 0:y.get(e);if(t===void 0||t.completed_at!==null&&t.state!=="dead"&&t.completed_at<=Date.now()-h)return null;const r={canceled:"canceled",dead:"failed",pending:"pending",succeeded:"succeeded"},n=t.state==="pending"&&t.claimed_at!==null&&t.claimed_at>=Date.now()-N,c={...I(t),state:n?"running":r[t.state]};return t.completed_at!==null&&(c.completedAt=t.completed_at),c},list:async()=>s||!a()?[]:R.all("pending").map(e=>I(e)),schedule:async(e,t,r)=>{if(s)throw new Error("platform closed: cannot schedule a job");if(r?.retry?.forever===!0)throw new ee("INVALID_INPUT","retry.forever is not supported by the Node scheduler host; set a finite retry.maxAttempts");const n=`node-job-${Z()}`;let c;return r?.at===void 0?c=Date.now()+(r?.delayMs??0):c=typeof r.at=="number"?r.at:r.at.getTime(),P.run(n,e,w(t),c,r?.retry===void 0?null:w(r.retry)),l(n,c),{id:n,scheduledFor:c}}};g.run(Date.now()-h);for(const e of R.all("pending"))l(e.id,e.scheduled_for);for(const e of $.all())f(e);return{dispose:()=>{for(const e of i.values())clearTimeout(e);for(const e of m.values())clearTimeout(e);i.clear(),m.clear(),s=!0},scheduler:Q,simulateDeadLetter:async e=>{const t=y.get(e);if(t?.state!=="pending")return!1;M(e);const r=x(t.retry);return v.run((r?.maxAttempts??p.maxAttempts)+1,Date.now(),e),!0}}};export{ie as createNodeSchedulerHost};
@@ -1 +0,0 @@
1
- import{LunoraError as s}from"@lunora/errors";import{toErrorResponse as u,resolveShard as l}from"@lunora/runtime";import{s as f}from"./hmac-url-Bogwm7I6.mjs";const g=async(t,e)=>{if(!t.body)return"";const n=t.body.getReader(),o=new TextDecoder;let r=0,a="";for(;;){const{done:i,value:d}=await n.read();if(i)break;if(d){if(r+=d.byteLength,r>e)return await n.cancel().catch(()=>{}),null;a+=o.decode(d,{stream:!0})}}return a+=o.decode(),a},h=(t,e)=>{const n=Math.max(t.length,e.length);let o=t.length^e.length;for(let r=0;r<n;r+=1){const a=r<t.length?t.charCodeAt(r):0,i=r<e.length?e.charCodeAt(r):0;o|=a^i}return o===0},y="/_lunora/scheduler/dispatch",_="__lunora_relation__:",A=t=>t.startsWith(_),c="agents:agentRun",E=(t,e,n)=>t===c&&e!==n,S=`\`${c}\` 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\``,w=(t,e)=>{if(!e||e.length===0)return!1;const n=t.headers.get("authorization");if(!n)return!1;const[o,...r]=n.split(" ");return o?.toLowerCase()!=="bearer"?!1:h(e,r.join(" ").trim())},p=async(t,e,n)=>{const o=t.headers.get("x-lunora-scheduler-signature"),{schedulerSecret:r}=n;return o!==null&&o.length>0&&r!==void 0&&r.length>0?h(await f(r,e),o):w(t,n.adminToken)},T="x-lunora-paywall",D="1",R="x-lunora-scheduled-for",m=({forwardedIdentity:t,mutationId:e,scheduledFor:n,traceparent:o})=>{const r={"content-type":"application/json",[T]:D,"x-lunora-system":"1"};return t?.userId!==void 0&&t.userId.length>0&&(r["x-lunora-userid"]=t.userId),t?.identity!==void 0&&t.identity.length>0&&(r["x-lunora-identity"]=t.identity),e!==void 0&&e.length>0&&(r["x-lunora-mutation-id"]=e),o!==void 0&&o.length>0&&(r.traceparent=o),n!==void 0&&Number.isFinite(n)&&(r[R]=String(Math.trunc(n))),r},P=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}}},N=1048576,O=async t=>{const e=await g(t,N);if(e===null)throw new s("PAYLOAD_TOO_LARGE","Scheduler dispatch body is too large");return e},v=async(t,e)=>{if(t.method!=="POST")throw new s("METHOD_NOT_ALLOWED","Scheduler dispatch endpoint requires POST",{status:405});const n=await O(t);if(!await p(t,n,{adminToken:e.adminToken,schedulerSecret:e.schedulerSecret}))throw new s("DISPATCH_UNAUTHENTICATED","Scheduler dispatch requires a valid signature or admin bearer");let r;try{r=JSON.parse(n)}catch{throw new s("BAD_REQUEST","Scheduler dispatch body must be valid JSON")}const a=r??{};if(typeof a.workflow=="string"||a.pool!==void 0)throw new s("SERVICE_UNAVAILABLE","Scheduler dispatch for a workflow or pool target is not served by the Node dispatch route");if(typeof a.functionPath!="string"||a.functionPath.length===0)throw new s("BAD_REQUEST","Scheduler dispatch is missing `functionPath`");if(A(a.functionPath))throw new s("FORBIDDEN","`__lunora_relation__:*` is a fan-out-only reserved RPC and cannot be dispatched to a single shard");const i=typeof a.shardKey=="string"&&a.shardKey.length>0?a.shardKey:e.defaultShardKey;if(E(a.functionPath,i,e.defaultShardKey))throw new s("BAD_REQUEST",S);return e.invoke({args:a.args??{},functionPath:a.functionPath,id:typeof a.id=="string"&&a.id.length>0?a.id:void 0,identity:P(t),scheduledFor:typeof a.scheduledFor=="number"?a.scheduledFor:void 0,shardKey:i,traceparent:t.headers.get("traceparent")??void 0})},x=(t,e)=>n=>{if(!e)throw new s("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:m({forwardedIdentity:n.identity,mutationId:n.id,scheduledFor:n.scheduledFor,traceparent:n.traceparent}),method:"POST"});return l(t,n.shardKey).fetch(o)},H=t=>async e=>{try{return await v(e,t)}catch(n){return u(n)}},U=y;export{S as A,U as N,x as a,H as c,E as i};