@moinulmoin/eden-world-cloudflare 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and purpose be included on the same "printed
186
+ page" as the copyright notice for easier identification within
187
+ third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,19 @@
1
+ Eden
2
+ Copyright 2026 Eden contributors
3
+
4
+ Cloudflare Containers
5
+ @cloudflare/containers, version 0.3.7
6
+ https://github.com/cloudflare/containers
7
+
8
+ Eden's generated Worker host bundle includes software from
9
+ `@cloudflare/containers`, distributed under MIT OR Apache-2.0. Eden
10
+ redistributes that bundled software under the Apache-2.0 option included in
11
+ LICENSE.
12
+
13
+ Workflow SDK
14
+ @workflow/world-postgres, version 5.0.0-beta.47
15
+ https://github.com/vercel/workflow
16
+
17
+ Eden's Cloudflare World storage implementation
18
+ (`@moinulmoin/eden-world-cloudflare`) is adapted from the Workflow SDK
19
+ PostgreSQL World, distributed under the Apache License, Version 2.0.
@@ -0,0 +1,8 @@
1
+ import { type World } from "@workflow/world";
2
+ export interface CloudflareWorldOptions {
3
+ url?: string;
4
+ pollIntervalMs?: number;
5
+ }
6
+ /** A Node-side World whose durable state lives in Eden's SQLite Durable Object. */
7
+ export declare function createWorld(options?: CloudflareWorldOptions): World;
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,96 @@
1
+ import * as errors from "@workflow/errors";
2
+ import { SPEC_VERSION_CURRENT } from "@workflow/world";
3
+ import { createWorld as createLocalWorld } from "@workflow/world-local";
4
+ import { decode, encode } from "cbor-x";
5
+ /** A Node-side World whose durable state lives in Eden's SQLite Durable Object. */
6
+ export function createWorld(options = {}) {
7
+ const url = options.url ?? process.env.EDEN_WORLD_URL;
8
+ if (!url)
9
+ throw new Error("EDEN_WORLD_URL must be set to the Eden World RPC URL");
10
+ const endpoint = new URL(url).toString();
11
+ const pollIntervalMs = options.pollIntervalMs ?? 200;
12
+ const local = createLocalWorld({ recoverActiveRuns: false });
13
+ async function rpc(op, args) {
14
+ if (op === "events.create" && args[2] && typeof args[2] === "object") {
15
+ // Replay observers are process-local callbacks for streamed responses.
16
+ // This transport returns a complete CBOR result, not a streamed replay.
17
+ const params = { ...args[2] };
18
+ delete params.replayEventObserver;
19
+ args = [args[0], args[1], params];
20
+ }
21
+ const body = new Uint8Array(encode({ op, args }));
22
+ const response = await fetch(endpoint, {
23
+ method: "POST",
24
+ headers: { "content-type": "application/cbor" },
25
+ body,
26
+ });
27
+ if (!response.ok)
28
+ throw new Error(`Eden World RPC ${op} failed: HTTP ${response.status}`);
29
+ const result = decode(new Uint8Array(await response.arrayBuffer()));
30
+ if (!result.ok) {
31
+ const error = Object.assign(new Error(result.error.message), result.error);
32
+ const constructor = errors[result.error.name];
33
+ if (constructor?.prototype)
34
+ Object.setPrototypeOf(error, constructor.prototype);
35
+ throw error;
36
+ }
37
+ return result.result;
38
+ }
39
+ function methods(namespace, names) {
40
+ return Object.fromEntries(names.map((name) => [name, (...args) => rpc(`${namespace}.${name}`, args)]));
41
+ }
42
+ const streams = methods("streams", ["write", "writeMulti", "close", "list", "getChunks", "getInfo"]);
43
+ streams.get = async (runId, name, startIndex = 0) => {
44
+ let index = startIndex;
45
+ if (index < 0) {
46
+ const info = await streams.getInfo(runId, name);
47
+ index = Math.max(0, info.tailIndex + 1 + index);
48
+ }
49
+ let cancelled = false;
50
+ let wake;
51
+ return new ReadableStream({
52
+ async pull(controller) {
53
+ try {
54
+ while (!cancelled) {
55
+ const result = await rpc("streams.readChunks", [name, index, 100]);
56
+ if (cancelled)
57
+ return;
58
+ index = result.nextIndex;
59
+ for (const chunk of result.chunks)
60
+ controller.enqueue(chunk);
61
+ if (result.done) {
62
+ controller.close();
63
+ return;
64
+ }
65
+ if (result.chunks.length)
66
+ return;
67
+ await new Promise((resolve) => {
68
+ const timer = setTimeout(resolve, pollIntervalMs);
69
+ wake = () => { clearTimeout(timer); resolve(); };
70
+ });
71
+ wake = undefined;
72
+ }
73
+ }
74
+ catch (error) {
75
+ if (!cancelled)
76
+ controller.error(error);
77
+ }
78
+ },
79
+ cancel() { cancelled = true; wake?.(); },
80
+ });
81
+ };
82
+ return {
83
+ specVersion: SPEC_VERSION_CURRENT,
84
+ runs: methods("runs", ["get", "getMany", "list", "experimentalSetAttributes"]),
85
+ steps: methods("steps", ["get", "list"]),
86
+ events: methods("events", ["create", "get", "list", "listByCorrelationId"]),
87
+ hooks: methods("hooks", ["get", "getByToken", "list"]),
88
+ streams,
89
+ getDeploymentId: async () => "eden-cloudflare",
90
+ queue: (...args) => rpc("queue.enqueue", args),
91
+ createQueueHandler: local.createQueueHandler,
92
+ start: async () => { },
93
+ close: async () => { await local.close?.(); },
94
+ };
95
+ }
96
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,69 @@
1
+ export interface SqlExec {
2
+ exec(query: string, ...bindings: unknown[]): {
3
+ toArray(): Record<string, unknown>[];
4
+ };
5
+ transactionSync?<T>(callback: () => T): T;
6
+ }
7
+ export interface QueueDelivery {
8
+ deliver(msg: {
9
+ queueName: string;
10
+ messageId: string;
11
+ attempt: number;
12
+ body: Uint8Array;
13
+ path: 'flow' | 'step';
14
+ headers?: Record<string, string>;
15
+ }): Promise<{
16
+ ok: boolean;
17
+ retryAfterMs?: number;
18
+ }>;
19
+ }
20
+ export declare class WorldCore {
21
+ private readonly sql;
22
+ private readonly delivery;
23
+ private readonly now;
24
+ private readonly scheduleAlarm;
25
+ private alarmRunning;
26
+ constructor(opts: {
27
+ sql: SqlExec;
28
+ delivery: QueueDelivery;
29
+ now?: () => number;
30
+ scheduleAlarm: (atMs: number | null) => void | Promise<void>;
31
+ });
32
+ private rows;
33
+ private atomic;
34
+ migrate(): void;
35
+ private run;
36
+ private step;
37
+ private saveRun;
38
+ private saveStep;
39
+ private saveHook;
40
+ private hookAvailable;
41
+ private findHook;
42
+ private hook;
43
+ private event;
44
+ private prior;
45
+ private insertEvent;
46
+ private listEvents;
47
+ private attributes;
48
+ private forceRefusal;
49
+ private createRun;
50
+ private create;
51
+ private createSync;
52
+ private eventResult;
53
+ private purge;
54
+ private listRuns;
55
+ private listSteps;
56
+ private listHooks;
57
+ private writeStream;
58
+ private streamRows;
59
+ private streamCount;
60
+ private streamDone;
61
+ private readChunks;
62
+ private getChunks;
63
+ private enqueue;
64
+ private reschedule;
65
+ runAlarm(): Promise<void>;
66
+ handleRpc(body: Uint8Array): Promise<Uint8Array>;
67
+ private dispatch;
68
+ }
69
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,602 @@
1
+ // Storage semantics ported from @workflow/world-postgres (Apache-2.0).
2
+ import { decode, encode } from 'cbor-x';
3
+ import { monotonicFactory } from 'ulid';
4
+ import { EntityConflictError, HookForceClaimedError, HookNotFoundError, RunExpiredError, RunNotSupportedError, TooEarlyError, WorkflowRunNotFoundError, WorkflowWorldError } from '@workflow/errors';
5
+ import { EventSchema, HookSchema, StepSchema, WorkflowRunSchema, SPEC_VERSION_CURRENT, SPEC_VERSION_LEGACY, SPEC_VERSION_SUPPORTS_HOOK_FORCE_CLAIM, slotToEventId, eventIdToSlot, stripEventDataRefs, validateAttributeChanges, validateUlidTimestamp, isTerminalWorkflowRunStatus, isTerminalStepStatus, isChildEntityCreationEvent, isTerminalRunEventType, requiresNewerWorld, isLegacySpecVersion } from '@workflow/world';
6
+ const ulid = monotonicFactory();
7
+ // Same default as @workflow/world when WORKFLOW_MAX_EVENTS is unset.
8
+ const DEFAULT_MAX_EVENTS_PER_RUN = 25000;
9
+ const bytes = (v) => typeof v === 'string' ? new TextEncoder().encode(v) : v;
10
+ function sqlBytes(value) {
11
+ if (value instanceof Uint8Array)
12
+ return value;
13
+ if (value instanceof ArrayBuffer)
14
+ return new Uint8Array(value);
15
+ throw new TypeError('SQLite BLOB must be an ArrayBuffer or Uint8Array');
16
+ }
17
+ const unpack = (row) => row ? decode(sqlBytes(row.data)) : undefined;
18
+ const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined && v !== null));
19
+ function filterData(value, params) {
20
+ return params?.resolveData === 'none' ? { ...value, input: undefined, output: undefined } : value;
21
+ }
22
+ function filterHook(hook, params) { return params?.resolveData === 'none' ? { ...hook, metadata: undefined } : hook; }
23
+ export class WorldCore {
24
+ sql;
25
+ delivery;
26
+ now;
27
+ scheduleAlarm;
28
+ alarmRunning = false;
29
+ constructor(opts) {
30
+ this.sql = opts.sql;
31
+ this.delivery = opts.delivery;
32
+ this.now = opts.now ?? Date.now;
33
+ this.scheduleAlarm = opts.scheduleAlarm;
34
+ }
35
+ rows(query, ...args) { return this.sql.exec(query, ...args).toArray(); }
36
+ atomic(fn) { return this.sql.transactionSync ? this.sql.transactionSync(fn) : fn(); }
37
+ migrate() {
38
+ for (const statement of [
39
+ 'CREATE TABLE IF NOT EXISTS workflow_runs (id TEXT PRIMARY KEY, name TEXT NOT NULL, status TEXT NOT NULL, deployment_id TEXT NOT NULL, data BLOB NOT NULL)',
40
+ 'CREATE INDEX IF NOT EXISTS workflow_runs_name ON workflow_runs(name)',
41
+ 'CREATE INDEX IF NOT EXISTS workflow_runs_status ON workflow_runs(status)',
42
+ 'CREATE TABLE IF NOT EXISTS workflow_event_slots (run_id TEXT PRIMARY KEY)',
43
+ 'CREATE TABLE IF NOT EXISTS workflow_events (run_id TEXT NOT NULL, id TEXT NOT NULL, type TEXT NOT NULL, correlation_id TEXT, resume_id TEXT, resume_payload_digest TEXT, data BLOB NOT NULL, PRIMARY KEY(run_id,id))',
44
+ 'CREATE INDEX IF NOT EXISTS workflow_events_correlation ON workflow_events(correlation_id)',
45
+ "CREATE UNIQUE INDEX IF NOT EXISTS workflow_events_entity_creation_unique ON workflow_events(run_id,correlation_id,type) WHERE type IN ('step_created','hook_created','wait_created','attr_set')",
46
+ "CREATE UNIQUE INDEX IF NOT EXISTS workflow_events_hook_resume_unique ON workflow_events(run_id,resume_id) WHERE type = 'hook_received' AND resume_id IS NOT NULL",
47
+ 'CREATE TABLE IF NOT EXISTS workflow_steps (step_id TEXT PRIMARY KEY, run_id TEXT NOT NULL, status TEXT NOT NULL, data BLOB NOT NULL)',
48
+ 'CREATE INDEX IF NOT EXISTS workflow_steps_run ON workflow_steps(run_id)',
49
+ 'CREATE TABLE IF NOT EXISTS workflow_hooks (hook_id TEXT PRIMARY KEY, run_id TEXT NOT NULL, token TEXT NOT NULL, data BLOB NOT NULL)',
50
+ 'CREATE INDEX IF NOT EXISTS workflow_hooks_run ON workflow_hooks(run_id)',
51
+ 'CREATE INDEX IF NOT EXISTS workflow_hooks_token ON workflow_hooks(token)',
52
+ 'CREATE TABLE IF NOT EXISTS workflow_waits (wait_id TEXT PRIMARY KEY, run_id TEXT NOT NULL, data BLOB NOT NULL)',
53
+ 'CREATE TABLE IF NOT EXISTS workflow_stream_chunks (sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, stream_id TEXT NOT NULL, run_id TEXT NOT NULL, data BLOB NOT NULL, eof INTEGER NOT NULL, created_at INTEGER NOT NULL, UNIQUE(stream_id,id))',
54
+ 'CREATE INDEX IF NOT EXISTS workflow_stream_chunks_name ON workflow_stream_chunks(stream_id,sequence)',
55
+ 'CREATE INDEX IF NOT EXISTS workflow_stream_chunks_run ON workflow_stream_chunks(run_id)',
56
+ 'CREATE TABLE IF NOT EXISTS workflow_queue_messages (id TEXT PRIMARY KEY, queue_name TEXT NOT NULL, body BLOB NOT NULL, path TEXT NOT NULL, due_at INTEGER NOT NULL, attempt INTEGER NOT NULL DEFAULT 1, completed INTEGER NOT NULL DEFAULT 0, idempotency_key TEXT)',
57
+ 'CREATE UNIQUE INDEX IF NOT EXISTS workflow_queue_idempotency ON workflow_queue_messages(idempotency_key) WHERE idempotency_key IS NOT NULL',
58
+ 'CREATE INDEX IF NOT EXISTS workflow_queue_due ON workflow_queue_messages(completed,due_at)',
59
+ ])
60
+ this.sql.exec(statement);
61
+ if (!this.rows('PRAGMA table_info(workflow_queue_messages)').some(row => row.name === 'headers'))
62
+ this.sql.exec('ALTER TABLE workflow_queue_messages ADD COLUMN headers BLOB');
63
+ }
64
+ run(id) { const value = unpack(this.rows('SELECT data FROM workflow_runs WHERE id = ?', id)[0]); if (!value)
65
+ throw new WorkflowRunNotFoundError(id); return WorkflowRunSchema.parse(value); }
66
+ step(runId, id) { const value = unpack(this.rows('SELECT data FROM workflow_steps WHERE run_id = ? AND step_id = ?', runId, id)[0]); if (!value)
67
+ throw new WorkflowWorldError(`Step not found: ${id}`); return StepSchema.parse(value); }
68
+ saveRun(run) { this.sql.exec('INSERT INTO workflow_runs(id,name,status,deployment_id,data) VALUES(?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,status=excluded.status,deployment_id=excluded.deployment_id,data=excluded.data', run.runId, run.workflowName, run.status, run.deploymentId, encode(compact(run))); }
69
+ saveStep(step) { this.sql.exec('INSERT INTO workflow_steps(step_id,run_id,status,data) VALUES(?,?,?,?) ON CONFLICT(step_id) DO UPDATE SET status=excluded.status,data=excluded.data', step.stepId, step.runId, step.status, encode(compact(step))); }
70
+ saveHook(hook) { this.sql.exec('INSERT INTO workflow_hooks(hook_id,run_id,token,data) VALUES(?,?,?,?) ON CONFLICT(hook_id) DO UPDATE SET token=excluded.token,data=excluded.data', hook.hookId, hook.runId, hook.token, encode(compact(hook))); }
71
+ hookAvailable(hook) { let run; try {
72
+ run = this.run(hook.runId);
73
+ }
74
+ catch {
75
+ return true;
76
+ } return !isTerminalWorkflowRunStatus(run.status) || (hook.tokenRetentionUntil?.getTime() ?? 0) > this.now(); }
77
+ findHook(id, token = false) { const values = this.rows(`SELECT data FROM workflow_hooks WHERE ${token ? 'token' : 'hook_id'} = ?`, id); return values.map(row => HookSchema.parse(unpack(row))).find(h => this.hookAvailable(h)); }
78
+ hook(id, token = false, params) { const value = this.findHook(id, token); if (!value)
79
+ throw new HookNotFoundError(id); return filterHook(value, params); }
80
+ event(runId, id, resolveData = 'all') { const value = unpack(this.rows('SELECT data FROM workflow_events WHERE run_id=? AND id=?', runId, id)[0]); if (!value)
81
+ throw new WorkflowWorldError(`Event not found: ${id}`); return stripEventDataRefs(EventSchema.parse(value), resolveData); }
82
+ prior(runId, correlationId, type) { if (!correlationId)
83
+ return; return unpack(this.rows('SELECT data FROM workflow_events WHERE run_id=? AND correlation_id=? AND type=? LIMIT 1', runId, correlationId, type)[0]); }
84
+ insertEvent(runId, data, resumeId, digest) {
85
+ const slotted = this.rows('SELECT run_id FROM workflow_event_slots WHERE run_id=?', runId).length > 0;
86
+ const last = this.rows('SELECT id FROM workflow_events WHERE run_id=? ORDER BY id DESC LIMIT 1', runId)[0];
87
+ const eventId = slotted ? slotToEventId((last ? eventIdToSlot(String(last.id)) ?? 0 : 0) + 1) : `wevt_${ulid(this.now())}`;
88
+ const event = EventSchema.parse(compact({ ...data, specVersion: data.specVersion ?? SPEC_VERSION_CURRENT, eventId, runId, createdAt: new Date(this.now()), resumeId }));
89
+ try {
90
+ this.sql.exec('INSERT INTO workflow_events(run_id,id,type,correlation_id,resume_id,resume_payload_digest,data) VALUES(?,?,?,?,?,?,?)', runId, eventId, data.eventType, data.correlationId ?? null, resumeId ?? null, digest ?? null, encode(event));
91
+ }
92
+ catch (error) {
93
+ if (String(error).includes('UNIQUE'))
94
+ throw new EntityConflictError(`${data.eventType} for correlationId "${data.correlationId}" already exists in run "${runId}"`);
95
+ throw error;
96
+ }
97
+ return event;
98
+ }
99
+ listEvents(params, correlation = false, resolveData = 'all') {
100
+ const limit = params.pagination?.limit ?? (correlation ? 100 : DEFAULT_MAX_EVENTS_PER_RUN);
101
+ const args = [params.runId];
102
+ let where = 'run_id=?';
103
+ const desc = params.pagination?.sortOrder === 'desc';
104
+ if (correlation) {
105
+ where += ' AND correlation_id=?';
106
+ args.push(params.correlationId);
107
+ }
108
+ if (params.pagination?.cursor) {
109
+ where += ` AND id ${desc ? '<' : '>'} ?`;
110
+ args.push(params.pagination.cursor);
111
+ }
112
+ const rows = this.rows(`SELECT data FROM workflow_events WHERE ${where} ORDER BY id ${desc ? 'DESC' : 'ASC'} LIMIT ?`, ...args, limit + 1);
113
+ const data = rows.slice(0, limit).map(row => stripEventDataRefs(EventSchema.parse(unpack(row)), resolveData));
114
+ return { data, cursor: data.at(-1)?.eventId ?? null, hasMore: rows.length > limit };
115
+ }
116
+ attributes(runId, changes, options) {
117
+ const run = this.run(runId);
118
+ validateAttributeChanges(changes, { existingKeys: Object.keys(run.attributes ?? {}), allowReservedAttributes: options?.allowReservedAttributes === true });
119
+ const attributes = { ...run.attributes };
120
+ for (const { key, value } of changes) {
121
+ if (value === null)
122
+ delete attributes[key];
123
+ else
124
+ attributes[key] = value;
125
+ }
126
+ const updated = { ...run, attributes, updatedAt: new Date(this.now()) };
127
+ this.saveRun(updated);
128
+ return updated;
129
+ }
130
+ forceRefusal(runId, hookId, token) {
131
+ const disposal = this.prior(runId, hookId, 'hook_disposed');
132
+ const data = disposal?.eventType === 'hook_disposed' ? disposal.eventData : undefined;
133
+ if (data?.forceClaimedBy) {
134
+ const successor = this.findHook(token ?? data.token ?? '', true);
135
+ throw new HookForceClaimedError(token ?? data.token ?? '', successor?.runId ?? data.forceClaimedBy.runId, successor?.hookId ?? data.forceClaimedBy.hookId);
136
+ }
137
+ throw new HookNotFoundError(hookId);
138
+ }
139
+ createRun(runId, data) {
140
+ if (this.rows('SELECT id FROM workflow_runs WHERE id=?', runId).length)
141
+ throw new EntityConflictError(`Workflow run "${runId}" already exists`);
142
+ const d = data.eventData;
143
+ validateAttributeChanges(Object.entries(d.attributes ?? {}).map(([key, value]) => ({ key, value })), { allowReservedAttributes: d.allowReservedAttributes === true });
144
+ const now = new Date(this.now());
145
+ const run = WorkflowRunSchema.parse(compact({ runId, ...d, status: 'pending', attributes: d.attributes ?? {}, createdAt: now, updatedAt: now, specVersion: data.specVersion ?? SPEC_VERSION_CURRENT }));
146
+ this.saveRun(run);
147
+ this.sql.exec('INSERT INTO workflow_event_slots(run_id) VALUES(?)', runId);
148
+ const event = this.insertEvent(runId, data);
149
+ return { run, event };
150
+ }
151
+ async create(runId, request, params) {
152
+ const id = runId || (request.eventType === 'run_created' ? `wrun_${ulid(this.now())}` : '');
153
+ if (!id)
154
+ throw new Error('runId is required for non-run_created events');
155
+ if (request.eventType === 'run_created' && runId) {
156
+ const error = validateUlidTimestamp(id, 'wrun_');
157
+ if (error)
158
+ throw new WorkflowWorldError(error);
159
+ }
160
+ let digest;
161
+ if (request.eventType === 'hook_received' && params?.resumeId) {
162
+ const payload = request.eventData.payload;
163
+ const input = payload instanceof Uint8Array ? payload : encode(payload);
164
+ digest = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', new Uint8Array(input))), b => b.toString(16).padStart(2, '0')).join('');
165
+ if (params.resumePayloadDigest && params.resumePayloadDigest !== digest)
166
+ throw new WorkflowWorldError('Hook resume digest does not match its payload', { status: 422 });
167
+ }
168
+ return this.atomic(() => this.createSync(id, request, params, digest));
169
+ }
170
+ createSync(id, request, params, digest) {
171
+ const now = new Date(this.now());
172
+ const specVersion = request.specVersion ?? SPEC_VERSION_CURRENT;
173
+ let data = { ...request };
174
+ let run;
175
+ let step;
176
+ let hook;
177
+ let wait;
178
+ let event;
179
+ let stepCreated = false;
180
+ const type = data.eventType;
181
+ const correlationId = data.correlationId;
182
+ if (type === 'run_created') {
183
+ ({ run, event } = this.createRun(id, data));
184
+ }
185
+ else {
186
+ let current;
187
+ try {
188
+ current = this.run(id);
189
+ }
190
+ catch (error) {
191
+ if (!(error instanceof WorkflowRunNotFoundError))
192
+ throw error;
193
+ }
194
+ if (!current && type === 'run_started' && 'eventData' in data && data.eventData) {
195
+ const d = data.eventData;
196
+ if (d.deploymentId && d.workflowName && d.input !== undefined)
197
+ current = this.createRun(id, { eventType: 'run_created', eventData: d, specVersion }).run;
198
+ }
199
+ if (!current && ['run_started', 'attr_set', 'hook_received'].includes(type))
200
+ throw new WorkflowRunNotFoundError(id);
201
+ const validatesRunVersion = type !== 'step_completed' && type !== 'step_retrying';
202
+ if (current && validatesRunVersion && requiresNewerWorld(current.specVersion))
203
+ throw new RunNotSupportedError(current.specVersion, SPEC_VERSION_CURRENT);
204
+ if (current && validatesRunVersion && isLegacySpecVersion(current.specVersion)) {
205
+ if (type === 'run_cancelled') {
206
+ run = WorkflowRunSchema.parse({ ...current, status: 'cancelled', completedAt: now, updatedAt: now });
207
+ this.saveRun(run);
208
+ this.sql.exec('DELETE FROM workflow_hooks WHERE run_id=?', id);
209
+ this.sql.exec('DELETE FROM workflow_waits WHERE run_id=?', id);
210
+ return { run };
211
+ }
212
+ if (!['wait_completed', 'hook_received'].includes(type))
213
+ throw new Error(`Event type '${type}' not supported for legacy runs (specVersion: ${current.specVersion || 'undefined'}). Please upgrade @workflow packages.`);
214
+ if (type === 'hook_received' && isTerminalWorkflowRunStatus(current.status))
215
+ throw new RunExpiredError(`Workflow run "${id}" is already in terminal state "${current.status}"`);
216
+ return { event: stripEventDataRefs(this.insertEvent(id, data), params?.resolveData ?? 'all') };
217
+ }
218
+ if (type === 'hook_received' && params?.resumeId) {
219
+ if (current?.expiredAt || (current && isTerminalWorkflowRunStatus(current.status) && current.attributes['$retention'] === '0'))
220
+ throw new WorkflowWorldError('Invocation data has expired under the run retention policy', { status: 410, code: 'INVOCATION_DATA_EXPIRED' });
221
+ const prior = this.rows("SELECT data,resume_payload_digest,correlation_id FROM workflow_events WHERE run_id=? AND resume_id=? AND type='hook_received'", id, params.resumeId)[0];
222
+ if (prior) {
223
+ const existing = unpack(prior);
224
+ const incoming = data;
225
+ if (prior.correlation_id !== correlationId || prior.resume_payload_digest !== digest || existing.eventType !== 'hook_received' || existing.eventData?.token !== incoming.eventData.token)
226
+ throw new WorkflowWorldError('Hook resume identity reused with different contents', { status: 422 });
227
+ return this.eventResult(id, { event: existing }, params);
228
+ }
229
+ }
230
+ const lazy = isChildEntityCreationEvent(data) && type === 'step_started';
231
+ const terminal = current && isTerminalWorkflowRunStatus(current.status);
232
+ if (terminal && current) {
233
+ if (type === 'run_cancelled' && current.status === 'cancelled')
234
+ return { event: stripEventDataRefs(this.insertEvent(id, data), params?.resolveData ?? 'all'), run: current };
235
+ if (type === 'run_started' || type === 'hook_received')
236
+ throw new RunExpiredError(`Workflow run "${id}" is already in terminal state "${current.status}"`);
237
+ if (isTerminalRunEventType(type) && !(type === 'run_cancelled' && current.status === 'cancelled'))
238
+ throw new EntityConflictError(`Cannot transition run from terminal state "${current.status}"`);
239
+ if (isChildEntityCreationEvent(data))
240
+ throw new EntityConflictError(`Cannot create new entities on run in terminal state "${current.status}"`);
241
+ if (type === 'attr_set')
242
+ throw new EntityConflictError(`Cannot set attributes on run in terminal state "${current.status}"`);
243
+ }
244
+ if (['step_created', 'hook_created', 'wait_created'].includes(type) || (data.eventType === 'attr_set' && data.eventData.writer.type === 'workflow')) {
245
+ if (this.prior(id, correlationId, type))
246
+ throw new EntityConflictError(`${type} for correlationId "${correlationId}" already exists in run "${id}"`);
247
+ }
248
+ if (type.startsWith('run_')) {
249
+ if (!current)
250
+ throw new WorkflowRunNotFoundError(id);
251
+ if (type === 'run_started') {
252
+ if (current.status === 'running')
253
+ return { run: current };
254
+ run = WorkflowRunSchema.parse({ ...current, status: 'running', startedAt: now, updatedAt: now });
255
+ data = compact({ ...data, eventData: undefined });
256
+ }
257
+ else if (data.eventType === 'run_completed')
258
+ run = WorkflowRunSchema.parse({ ...current, status: 'completed', output: data.eventData.output, completedAt: now, updatedAt: now });
259
+ else if (data.eventType === 'run_failed') {
260
+ const d = data.eventData;
261
+ run = WorkflowRunSchema.parse({ ...current, status: 'failed', error: d.error, errorCode: d.errorCode, completedAt: now, updatedAt: now });
262
+ }
263
+ else if (type === 'run_cancelled')
264
+ run = WorkflowRunSchema.parse({ ...current, status: 'cancelled', completedAt: current.completedAt ?? now, updatedAt: now });
265
+ if (run)
266
+ this.saveRun(run);
267
+ if (isTerminalRunEventType(type)) {
268
+ for (const row of this.rows('SELECT data FROM workflow_hooks WHERE run_id=?', id)) {
269
+ const h = unpack(row);
270
+ if ((h.tokenRetentionUntil?.getTime() ?? 0) <= this.now())
271
+ this.sql.exec('DELETE FROM workflow_hooks WHERE hook_id=?', h.hookId);
272
+ }
273
+ this.sql.exec('DELETE FROM workflow_waits WHERE run_id=?', id);
274
+ }
275
+ }
276
+ if (data.eventType === 'attr_set') {
277
+ const d = data.eventData;
278
+ run = this.attributes(id, d.changes, { allowReservedAttributes: d.allowReservedAttributes === true });
279
+ }
280
+ if (type.startsWith('step_')) {
281
+ const d = ('eventData' in data ? data.eventData : {});
282
+ let existing;
283
+ try {
284
+ existing = this.step(id, correlationId);
285
+ }
286
+ catch (error) {
287
+ if (!(error instanceof WorkflowWorldError))
288
+ throw error;
289
+ }
290
+ if (type === 'step_created' || lazy) {
291
+ if (lazy && existing)
292
+ throw new EntityConflictError(`Step "${correlationId}" already created`);
293
+ step = existing ?? StepSchema.parse(compact({ runId: id, stepId: correlationId, stepName: d.stepName, input: d.input, status: 'pending', attempt: 0, createdAt: now, updatedAt: now, specVersion }));
294
+ if (lazy) {
295
+ this.insertEvent(id, { eventType: 'step_created', correlationId: correlationId, eventData: { stepName: d.stepName, input: d.input }, specVersion });
296
+ stepCreated = true;
297
+ }
298
+ }
299
+ else {
300
+ if (!existing)
301
+ throw new WorkflowWorldError(`Step "${correlationId}" not found`);
302
+ step = existing;
303
+ }
304
+ if (type !== 'step_created') {
305
+ if (isTerminalStepStatus(step.status))
306
+ throw new EntityConflictError(`Cannot modify step in terminal state "${step.status}"`);
307
+ if (terminal && type === 'step_started')
308
+ throw new RunExpiredError(`Cannot start step on run in terminal state "${current.status}"`);
309
+ if (type === 'step_started') {
310
+ if (step.retryAfter && step.retryAfter.getTime() > this.now())
311
+ throw new TooEarlyError(`Cannot start step "${correlationId}": retryAfter timestamp has not been reached yet`, { retryAfter: Math.ceil((step.retryAfter.getTime() - this.now()) / 1000) });
312
+ step = { ...step, status: 'running', attempt: step.attempt + 1, startedAt: step.startedAt ?? now, retryAfter: undefined, updatedAt: now };
313
+ if ('eventData' in data && data.eventData && 'input' in data.eventData) {
314
+ const rest = { ...data.eventData };
315
+ delete rest.input;
316
+ data = { ...data, eventData: rest };
317
+ }
318
+ }
319
+ else if (type === 'step_completed')
320
+ step = { ...step, status: 'completed', output: d.result, completedAt: now, updatedAt: now };
321
+ else if (type === 'step_failed')
322
+ step = { ...step, status: 'failed', error: d.error, completedAt: now, updatedAt: now };
323
+ else if (type === 'step_retrying')
324
+ step = { ...step, status: 'pending', error: d.error, retryAfter: d.retryAfter, updatedAt: now };
325
+ }
326
+ this.saveStep(step);
327
+ }
328
+ if (type === 'hook_created') {
329
+ const d = data.eventData;
330
+ if (d.tokenRetentionUntil && d.tokenRetentionUntil.getTime() > this.now() + 30 * 86400000)
331
+ throw new WorkflowWorldError('Hook minimum retention cannot exceed 30 days in the Cloudflare World.', { status: 400 });
332
+ const existing = this.findHook(d.token, true);
333
+ let claimedFrom;
334
+ if (existing && existing.runId === id && existing.hookId === correlationId)
335
+ hook = existing;
336
+ else if (existing) {
337
+ const victim = this.run(existing.runId);
338
+ const victimRunning = !isTerminalWorkflowRunStatus(victim.status);
339
+ const refused = d.force === true && victimRunning && (victim.specVersion ?? SPEC_VERSION_LEGACY) < SPEC_VERSION_SUPPORTS_HOOK_FORCE_CLAIM;
340
+ if (d.force !== true || refused) {
341
+ const conflict = { eventType: 'hook_conflict', correlationId: correlationId, eventData: { token: d.token, conflictingRunId: existing.runId, ...(refused ? { forceRefusedReason: 'victim-spec-version' } : {}) }, specVersion };
342
+ return { event: stripEventDataRefs(this.insertEvent(id, conflict), params?.resolveData ?? 'all') };
343
+ }
344
+ claimedFrom = { runId: existing.runId, hookId: existing.hookId, ...(victimRunning ? { workflowName: victim.workflowName, deploymentId: victim.deploymentId, runSpecVersion: victim.specVersion } : {}) };
345
+ if (victimRunning)
346
+ this.insertEvent(existing.runId, { eventType: 'hook_disposed', correlationId: existing.hookId, eventData: { token: d.token, forceClaimedBy: { runId: id, hookId: correlationId } }, specVersion: victim.specVersion ?? specVersion });
347
+ this.sql.exec('DELETE FROM workflow_hooks WHERE hook_id=?', existing.hookId);
348
+ data = { ...data, eventData: { ...d, forceClaimedFrom: claimedFrom } };
349
+ }
350
+ if (!hook)
351
+ hook = HookSchema.parse(compact({ runId: id, hookId: correlationId, token: d.token, metadata: d.metadata, ownerId: '', projectId: '', environment: '', createdAt: now, specVersion, isWebhook: d.isWebhook ?? true, isSystem: d.isSystem ?? false, tokenRetentionUntil: d.tokenRetentionUntil, claimedFrom }));
352
+ this.saveHook(hook);
353
+ }
354
+ if (type === 'hook_disposed' || type === 'hook_received') {
355
+ hook = this.findHook(correlationId);
356
+ if (!hook)
357
+ this.forceRefusal(id, correlationId, type === 'hook_received' ? data.eventData.token : undefined);
358
+ if (type === 'hook_received' && params?.resumeId) {
359
+ const token = data.eventData.token;
360
+ if (hook.runId !== id || (token !== undefined && token !== hook.token))
361
+ throw new HookNotFoundError(correlationId);
362
+ }
363
+ if (type === 'hook_disposed')
364
+ this.sql.exec('DELETE FROM workflow_hooks WHERE hook_id=?', correlationId);
365
+ hook = undefined;
366
+ }
367
+ if (type === 'wait_created' || type === 'wait_completed') {
368
+ const waitId = `${id}-${correlationId}`;
369
+ const existing = unpack(this.rows('SELECT data FROM workflow_waits WHERE wait_id=?', waitId)[0]);
370
+ if (type === 'wait_created') {
371
+ if (existing)
372
+ throw new EntityConflictError(`Wait "${correlationId}" already exists`);
373
+ wait = compact({ waitId, runId: id, status: 'waiting', resumeAt: data.eventData.resumeAt, createdAt: now, updatedAt: now, specVersion });
374
+ }
375
+ else {
376
+ if (!existing)
377
+ throw new WorkflowWorldError(`Wait "${correlationId}" not found`);
378
+ if (existing.status === 'completed')
379
+ throw new EntityConflictError(`Wait "${correlationId}" already completed`);
380
+ wait = { ...existing, status: 'completed', completedAt: now, updatedAt: now };
381
+ }
382
+ this.sql.exec('INSERT INTO workflow_waits(wait_id,run_id,data) VALUES(?,?,?) ON CONFLICT(wait_id) DO UPDATE SET data=excluded.data', waitId, id, encode(wait));
383
+ }
384
+ event = this.insertEvent(id, data, params?.resumeId, digest);
385
+ }
386
+ const result = this.eventResult(id, compact({ event, run, step, hook, wait, ...(stepCreated ? { stepCreated: true } : {}) }), params, request.eventType === 'run_started');
387
+ if (run && isTerminalWorkflowRunStatus(run.status) && run.attributes?.['$retention'] === '0')
388
+ this.purge(id, now);
389
+ return result;
390
+ }
391
+ eventResult(id, result, params, preload = false) {
392
+ const resolveData = params?.resolveData ?? 'all';
393
+ const original = result.event;
394
+ if (original)
395
+ result = { ...result, event: stripEventDataRefs(original, resolveData) };
396
+ if (typeof params?.sinceCursor === 'string') {
397
+ const page = this.listEvents({ runId: id, pagination: { cursor: params.sinceCursor, limit: 100 } }, false, resolveData);
398
+ return { ...result, events: page.data, cursor: page.cursor, hasMore: page.hasMore };
399
+ }
400
+ if (preload && !params?.skipPreload) {
401
+ const events = this.rows('SELECT data FROM workflow_events WHERE run_id=? ORDER BY id', id).map(row => stripEventDataRefs(EventSchema.parse(unpack(row)), resolveData));
402
+ return { ...result, events, cursor: events.at(-1)?.eventId ?? null, hasMore: false };
403
+ }
404
+ const slot = original ? eventIdToSlot(original.eventId) : null;
405
+ if (params?.eventCount !== undefined && params.eventCount >= 1 && slot !== null && slot > params.eventCount + 1) {
406
+ const events = this.rows('SELECT data FROM workflow_events WHERE run_id=? AND id>? AND id<? ORDER BY id', id, slotToEventId(params.eventCount), original.eventId).map(row => stripEventDataRefs(EventSchema.parse(unpack(row)), resolveData));
407
+ return { ...result, events, cursor: null, hasMore: events.length < slot - params.eventCount - 1 };
408
+ }
409
+ return result;
410
+ }
411
+ purge(id, at) {
412
+ const run = this.run(id);
413
+ this.saveRun({ ...run, input: undefined, output: undefined, error: undefined, expiredAt: at });
414
+ for (const row of this.rows('SELECT data FROM workflow_steps WHERE run_id=?', id)) {
415
+ const step = unpack(row);
416
+ this.saveStep({ ...step, input: undefined, output: undefined, error: undefined });
417
+ }
418
+ for (const row of this.rows('SELECT data FROM workflow_events WHERE run_id=?', id)) {
419
+ const event = unpack(row);
420
+ this.sql.exec('UPDATE workflow_events SET data=?,resume_payload_digest=NULL WHERE run_id=? AND id=?', encode({ ...event, eventData: undefined }), id, event.eventId);
421
+ }
422
+ for (const row of this.rows('SELECT data FROM workflow_hooks WHERE run_id=?', id)) {
423
+ const hook = unpack(row);
424
+ this.saveHook({ ...hook, metadata: undefined, resumeContext: undefined });
425
+ }
426
+ this.sql.exec('UPDATE workflow_stream_chunks SET data=? WHERE run_id=?', new Uint8Array(), id);
427
+ }
428
+ listRuns(params) {
429
+ const args = [];
430
+ const where = [];
431
+ if (params?.pagination?.cursor) {
432
+ where.push('id<?');
433
+ args.push(params.pagination.cursor);
434
+ }
435
+ if (params?.workflowName) {
436
+ where.push('name=?');
437
+ args.push(params.workflowName);
438
+ }
439
+ if (params?.status) {
440
+ const statuses = Array.isArray(params.status) ? params.status : [params.status];
441
+ where.push(`status IN (${statuses.map(() => '?').join(',') || 'NULL'})`);
442
+ args.push(...statuses);
443
+ }
444
+ const limit = params?.pagination?.limit ?? 20;
445
+ const rows = this.rows(`SELECT data FROM workflow_runs ${where.length ? `WHERE ${where.join(' AND ')}` : ''} ORDER BY id DESC LIMIT ?`, ...args, limit + 1);
446
+ const data = rows.slice(0, limit).map(row => filterData(WorkflowRunSchema.parse(unpack(row)), params));
447
+ return { data, cursor: data.at(-1)?.runId ?? null, hasMore: rows.length > limit };
448
+ }
449
+ listSteps(params) {
450
+ const limit = params.pagination?.limit ?? 20;
451
+ const rows = this.rows(`SELECT data FROM workflow_steps WHERE run_id=? ${params.pagination?.cursor ? 'AND step_id<?' : ''} ORDER BY step_id DESC LIMIT ?`, params.runId, ...(params.pagination?.cursor ? [params.pagination.cursor] : []), limit + 1);
452
+ const data = rows.slice(0, limit).map(row => filterData(StepSchema.parse(unpack(row)), params));
453
+ return { data, cursor: data.at(-1)?.stepId ?? null, hasMore: rows.length > limit };
454
+ }
455
+ listHooks(params) {
456
+ const desc = params.pagination?.sortOrder === 'desc';
457
+ const where = [];
458
+ const args = [];
459
+ if (params.runId) {
460
+ where.push('run_id=?');
461
+ args.push(params.runId);
462
+ }
463
+ if (params.pagination?.cursor) {
464
+ where.push(`hook_id${desc ? '<' : '>'}?`);
465
+ args.push(params.pagination.cursor);
466
+ }
467
+ const limit = params.pagination?.limit ?? 100;
468
+ const values = this.rows(`SELECT data FROM workflow_hooks ${where.length ? `WHERE ${where.join(' AND ')}` : ''} ORDER BY hook_id ${desc ? 'DESC' : 'ASC'}`, ...args).map(row => HookSchema.parse(unpack(row))).filter(h => this.hookAvailable(h));
469
+ const data = values.slice(0, limit).map(h => filterHook(h, params));
470
+ return { data, cursor: data.at(-1)?.hookId ?? null, hasMore: values.length > limit };
471
+ }
472
+ writeStream(runId, name, chunks, eof = false) { this.atomic(() => { for (const chunk of chunks)
473
+ this.sql.exec('INSERT INTO workflow_stream_chunks(id,stream_id,run_id,data,eof,created_at) VALUES(?,?,?,?,?,?)', `chnk_${ulid(this.now())}`, name, runId, bytes(chunk), eof ? 1 : 0, this.now()); }); }
474
+ streamRows(name, from = 0, limit = 100) { return this.rows('SELECT sequence,data FROM workflow_stream_chunks WHERE stream_id=? AND sequence < COALESCE((SELECT MIN(sequence) FROM workflow_stream_chunks WHERE stream_id=? AND eof=1),9223372036854775807) ORDER BY sequence LIMIT ? OFFSET ?', name, name, limit, from); }
475
+ streamCount(name) { return Number(this.rows('SELECT COUNT(*) AS count FROM workflow_stream_chunks WHERE stream_id=? AND sequence < COALESCE((SELECT MIN(sequence) FROM workflow_stream_chunks WHERE stream_id=? AND eof=1),9223372036854775807)', name, name)[0]?.count ?? 0); }
476
+ streamDone(name) { return this.rows('SELECT sequence FROM workflow_stream_chunks WHERE stream_id=? AND eof=1 LIMIT 1', name).length > 0; }
477
+ readChunks(name, fromIndex = 0, limit = 100) {
478
+ const count = this.streamCount(name);
479
+ const start = fromIndex < 0 ? Math.max(0, count + fromIndex) : fromIndex;
480
+ const chunks = this.streamRows(name, start, limit).map(row => sqlBytes(row.data));
481
+ return { chunks, nextIndex: start + chunks.length, done: this.streamDone(name) && start + chunks.length >= count };
482
+ }
483
+ getChunks(name, options) {
484
+ let from = 0;
485
+ try {
486
+ if (options?.cursor) {
487
+ const parsed = JSON.parse(atob(options.cursor));
488
+ from = parsed.i ?? 0;
489
+ }
490
+ }
491
+ catch { /* Invalid reference cursors start at the beginning. */ }
492
+ const limit = options?.limit ?? 100;
493
+ const rows = this.streamRows(name, from, limit + 1);
494
+ const page = rows.slice(0, limit);
495
+ const hasMore = rows.length > limit;
496
+ return { data: page.map((row, i) => ({ index: from + i, data: sqlBytes(row.data) })), cursor: hasMore ? btoa(JSON.stringify({ i: from + page.length })) : null, hasMore, done: this.streamDone(name) };
497
+ }
498
+ async enqueue(queueName, message, opts) {
499
+ if (opts?.idempotencyKey) {
500
+ const prior = this.rows('SELECT id FROM workflow_queue_messages WHERE idempotency_key=?', opts.idempotencyKey)[0];
501
+ if (prior)
502
+ return { messageId: String(prior.id) };
503
+ }
504
+ // World-local beta.48 uses the combined flow endpoint for steps and wakes.
505
+ const id = `msg_${ulid(this.now())}`;
506
+ const path = 'flow';
507
+ const json = JSON.stringify(message, (_key, value) => {
508
+ if (value instanceof Uint8Array) {
509
+ let binary = '';
510
+ for (const byte of value)
511
+ binary += String.fromCharCode(byte);
512
+ return { __type: 'Uint8Array', data: btoa(binary) };
513
+ }
514
+ return value;
515
+ });
516
+ this.sql.exec('INSERT INTO workflow_queue_messages(id,queue_name,body,path,due_at,idempotency_key,headers) VALUES(?,?,?,?,?,?,?)', id, queueName, new TextEncoder().encode(json), path, this.now() + Math.max(0, opts?.delaySeconds ?? 0) * 1000, opts?.idempotencyKey ?? null, opts?.headers ? encode(opts.headers) : null);
517
+ await this.reschedule();
518
+ return { messageId: id };
519
+ }
520
+ async reschedule() { const row = this.rows('SELECT MIN(due_at) AS due FROM workflow_queue_messages WHERE completed=0')[0]; await this.scheduleAlarm(row?.due === null || row?.due === undefined ? null : Number(row.due)); }
521
+ async runAlarm() {
522
+ if (this.alarmRunning)
523
+ return;
524
+ this.alarmRunning = true;
525
+ try {
526
+ const due = this.rows('SELECT * FROM workflow_queue_messages WHERE completed=0 AND due_at<=? ORDER BY due_at,id LIMIT 50', this.now());
527
+ await Promise.all(due.map(async (row) => {
528
+ const id = String(row.id);
529
+ const attempt = Number(row.attempt);
530
+ // Persist a lease before the external effect: a crashed delivery retries.
531
+ this.sql.exec('UPDATE workflow_queue_messages SET due_at=? WHERE id=?', this.now() + 60000, id);
532
+ let result;
533
+ try {
534
+ result = await this.delivery.deliver({ queueName: String(row.queue_name), messageId: id, attempt, body: sqlBytes(row.body), path: row.path, ...(row.headers ? { headers: decode(sqlBytes(row.headers)) } : {}) });
535
+ }
536
+ catch {
537
+ result = { ok: false };
538
+ }
539
+ // Like world-local, deduplicate outstanding deliveries, not future wakes.
540
+ if (result.ok && result.retryAfterMs === undefined)
541
+ this.sql.exec('UPDATE workflow_queue_messages SET completed=1,idempotency_key=NULL WHERE id=?', id);
542
+ else
543
+ this.sql.exec('UPDATE workflow_queue_messages SET attempt=?,due_at=? WHERE id=?', attempt + 1, this.now() + Math.max(1, result.retryAfterMs ?? Math.min(60000, 1000 * 2 ** Math.min(attempt - 1, 6))), id);
544
+ }));
545
+ }
546
+ finally {
547
+ this.alarmRunning = false;
548
+ await this.reschedule();
549
+ }
550
+ }
551
+ async handleRpc(body) {
552
+ try {
553
+ const { op, args } = decode(body);
554
+ const result = await this.dispatch(op, args);
555
+ return encode({ ok: true, result });
556
+ }
557
+ catch (error) {
558
+ const e = error instanceof Error ? error : new Error(String(error));
559
+ return encode({ ok: false, error: { ...Object.fromEntries(Object.entries(e)), name: e.name, message: e.message } });
560
+ }
561
+ }
562
+ async dispatch(op, args) {
563
+ switch (op) {
564
+ case 'runs.get': return filterData(this.run(args[0]), args[1]);
565
+ case 'runs.getMany': return args[0].map(id => { try {
566
+ return filterData(this.run(id), args[1]);
567
+ }
568
+ catch (e) {
569
+ if (e instanceof WorkflowRunNotFoundError)
570
+ return null;
571
+ throw e;
572
+ } });
573
+ case 'runs.list': return this.listRuns(args[0]);
574
+ case 'runs.experimentalSetAttributes': return this.atomic(() => ({ attributes: this.attributes(args[0], args[1], args[2]).attributes }));
575
+ case 'steps.get': return filterData(this.step(args[0], args[1]), args[2]);
576
+ case 'steps.list': return this.listSteps(args[0]);
577
+ case 'events.create': return this.create(args[0], args[1], args[2]);
578
+ case 'events.get': return this.event(args[0], args[1], args[2]?.resolveData);
579
+ case 'events.list': return this.listEvents(args[0], false, args[0]?.resolveData);
580
+ case 'events.listByCorrelationId': return this.listEvents(args[0], true, args[0]?.resolveData);
581
+ case 'hooks.get': return this.hook(args[0], false, args[1]);
582
+ case 'hooks.getByToken': return this.hook(args[0], true, args[1]);
583
+ case 'hooks.list': return this.listHooks(args[0]);
584
+ case 'streams.write': return this.writeStream(args[0], args[1], [args[2]]);
585
+ case 'streams.writeMulti': return this.writeStream(args[0], args[1], args[2]);
586
+ case 'streams.close': return this.writeStream(args[0], args[1], [new Uint8Array()], true);
587
+ case 'streams.list': return this.rows('SELECT DISTINCT stream_id FROM workflow_stream_chunks WHERE run_id=?', args[0]).map(row => String(row.stream_id));
588
+ case 'streams.readChunks': return this.readChunks(args[0], args[1], args[2]);
589
+ case 'streams.getChunks': return this.getChunks(args[1], args[2]);
590
+ case 'streams.getInfo': return { tailIndex: this.streamCount(args[1]) - 1, done: this.streamDone(args[1]) };
591
+ case 'queue.enqueue': return this.enqueue(args[0], args[1], args[2]);
592
+ case 'queue.enqueueBatch': return Promise.all(args[1].map(async (item) => { try {
593
+ return await this.enqueue(args[0], item.message, item.opts);
594
+ }
595
+ catch (e) {
596
+ return { messageId: null, error: String(e), retryable: true };
597
+ } }));
598
+ default: throw new WorkflowWorldError(`Unknown Eden World RPC operation: ${op}`, { status: 400 });
599
+ }
600
+ }
601
+ }
602
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,14 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import type { SqlExec } from './index.js';
3
+ /** Node 24 adapter for exercising the same SQL engine as Durable Objects. */
4
+ export declare class NodeSqliteAdapter implements SqlExec {
5
+ readonly database: DatabaseSync;
6
+ private transactionDepth;
7
+ constructor(filename?: string);
8
+ exec(query: string, ...bindings: unknown[]): {
9
+ toArray(): Record<string, unknown>[];
10
+ };
11
+ transactionSync<T>(callback: () => T): T;
12
+ close(): void;
13
+ }
14
+ //# sourceMappingURL=node-sqlite.d.ts.map
@@ -0,0 +1,32 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ /** Node 24 adapter for exercising the same SQL engine as Durable Objects. */
3
+ export class NodeSqliteAdapter {
4
+ database;
5
+ transactionDepth = 0;
6
+ constructor(filename = ':memory:') { this.database = new DatabaseSync(filename); }
7
+ exec(query, ...bindings) {
8
+ const statement = this.database.prepare(query);
9
+ const values = bindings;
10
+ const rows = statement.all(...values);
11
+ return { toArray: () => rows };
12
+ }
13
+ transactionSync(callback) {
14
+ const name = `world_${this.transactionDepth++}`;
15
+ this.database.exec(`SAVEPOINT ${name}`);
16
+ try {
17
+ const result = callback();
18
+ this.database.exec(`RELEASE SAVEPOINT ${name}`);
19
+ return result;
20
+ }
21
+ catch (error) {
22
+ this.database.exec(`ROLLBACK TO SAVEPOINT ${name}`);
23
+ this.database.exec(`RELEASE SAVEPOINT ${name}`);
24
+ throw error;
25
+ }
26
+ finally {
27
+ this.transactionDepth--;
28
+ }
29
+ }
30
+ close() { this.database.close(); }
31
+ }
32
+ //# sourceMappingURL=node-sqlite.js.map
@@ -0,0 +1,2 @@
1
+ export { createWorld, type CloudflareWorldOptions } from "./client/index.js";
2
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { createWorld } from "./client/index.js";
2
+ //# sourceMappingURL=index.js.map
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@moinulmoin/eden-world-cloudflare",
3
+ "version": "0.4.0",
4
+ "description": "Cloudflare Durable Object SQLite World for Eve workflows.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "types": "./dist/index.d.ts",
8
+ "module": "./dist/index.js",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ },
14
+ "./core": {
15
+ "types": "./dist/core/index.d.ts",
16
+ "import": "./dist/core/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist/**/*.js",
21
+ "dist/**/*.d.ts",
22
+ "LICENSE",
23
+ "NOTICE"
24
+ ],
25
+ "dependencies": {
26
+ "@workflow/errors": "5.0.0-beta.24",
27
+ "@workflow/world": "5.0.0-beta.39",
28
+ "@workflow/world-local": "5.0.0-beta.48",
29
+ "cbor-x": "1.6.4",
30
+ "ulid": "3.0.2"
31
+ },
32
+ "devDependencies": {
33
+ "@types/node": "24.0.0",
34
+ "@workflow/world-testing": "5.0.0-beta.57"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/moinulmoin/eden.git",
39
+ "directory": "packages/world-cloudflare"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "engines": {
45
+ "node": ">=24.17.0"
46
+ },
47
+ "scripts": {
48
+ "build": "tsc -b",
49
+ "typecheck": "tsc -b --pretty false",
50
+ "lint": "eslint src --max-warnings 0",
51
+ "test": "vitest run --config vitest.config.ts --passWithNoTests --maxWorkers=1",
52
+ "test:server": "node test/server.mjs"
53
+ }
54
+ }