@lunora/platform 0.0.0 → 1.0.0-alpha.2

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 ADDED
@@ -0,0 +1,111 @@
1
+ # Functional Source License, Version 1.1, Apache 2.0 Future License
2
+
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.
106
+
107
+ <!-- DEPENDENCIES -->
108
+ <!-- /DEPENDENCIES -->
109
+
110
+ <!-- TYPE_DEPENDENCIES -->
111
+ <!-- /TYPE_DEPENDENCIES -->
package/README.md CHANGED
@@ -1,45 +1,19 @@
1
1
  # @lunora/platform
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
3
+ Provider-neutral host contracts for Lunora.
4
4
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
5
+ This package defines the structural interfaces that separate the Lunora engine from any specific host (Cloudflare Workers, AWS, Rivet, Node, etc.). It contains **types and capability metadata only** — near-zero runtime code.
6
6
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
7
+ ## Contracts
8
8
 
9
- ## Purpose
9
+ - **`ShardHost`** — single-writer execution, transactions, local SQL, alarms, and background continuation per shard key.
10
+ - **`SocketHost`** — hibernated WebSocket subscriptions with durable attachments and tagged fan-out.
11
+ - **`ShardDirectory`** — deterministic placement and RPC dispatch from shard keys to stubs.
12
+ - **`SchedulerHost`** — durable delayed jobs, cron, and at-least-once dispatch.
13
+ - **`PlatformCapabilities`** — capability matrix consumed by codegen to tailor emitted types per target.
10
14
 
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@lunora/platform`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
15
+ Plus canonical binding projections (`KVNamespaceLike`, `R2BucketLike`, `QueueBindingLike`, `D1DatabaseLike`, `VectorizeIndexLike`, …) shared by all host adapters.
15
16
 
16
- ## What is OIDC Trusted Publishing?
17
+ ## Status
17
18
 
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
19
-
20
- ## Setup Instructions
21
-
22
- To properly configure OIDC trusted publishing for this package:
23
-
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
-
29
- ## DO NOT USE THIS PACKAGE
30
-
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
36
-
37
- ## More Information
38
-
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
42
-
43
- ---
44
-
45
- **Maintained for OIDC setup purposes only**
19
+ This package is part of plan 114 (multi-provider platform). It is the prerequisite for the AWS target in the same plan (§§6–9).
@@ -0,0 +1,2 @@
1
+ export { type C as ConformanceHost, type a as ConformanceHostFactory, type R as ReferenceHost, type VitestApi, c as createReferenceHost, defineHostContractSuite } from "./suite.mjs";
2
+ import "../packem_shared/socket-host.d-Cq5uVbiH.mjs";
@@ -0,0 +1,2 @@
1
+ export { type C as ConformanceHost, type a as ConformanceHostFactory, type R as ReferenceHost, type VitestApi, c as createReferenceHost, defineHostContractSuite } from "./suite.js";
2
+ import "../packem_shared/socket-host.d-Cq5uVbiH.js";
@@ -0,0 +1 @@
1
+ import{createReferenceHost as o}from"../packem_shared/createReferenceHost-GO8Hp4ft.mjs";import{defineHostContractSuite as f}from"./suite.mjs";export{o as createReferenceHost,f as defineHostContractSuite};
@@ -0,0 +1,132 @@
1
+ import { f as ShardDirectory, j as ShardKvStore, n as SocketHandle, c as SchedulerHost, g as ShardHost, o as SocketHost } from "../packem_shared/socket-host.d-Cq5uVbiH.mjs";
2
+ /**
3
+ * A conformance host bundles all four platform contracts so a single factory
4
+ * can stand up a complete, isolated test environment.
5
+ */
6
+ interface ConformanceHost {
7
+ /**
8
+ * Resolve once a pending alarm has actually fired. Optional: hosts whose
9
+ * alarm delivery is owned by the platform and can't be observed from inside
10
+ * a shard callback (Cloudflare wakes a separate `alarm()` invocation) omit
11
+ * it, and the suite then asserts only the set/read/delete half of the alarm
12
+ * contract — platform delivery is the platform's test, not the adapter's.
13
+ */
14
+ awaitAlarmFired?: (target: number) => Promise<void>;
15
+ /** Optional cleanup hook (close DBs, release timers). */
16
+ cleanup?: () => void;
17
+ /**
18
+ * Mint a raw socket for {@link SocketHost.accept}. Optional: what a socket
19
+ * actually _is_ differs per host (Cloudflare needs a live `WebSocketPair` end), and
20
+ * the provider-neutral suite can't know. Defaults to an opaque object for
21
+ * hosts that don't care.
22
+ */
23
+ createSocket?: () => unknown;
24
+ /** The shard directory under test. */
25
+ directory: ShardDirectory;
26
+ /**
27
+ * The durable key-value store under test. Optional: a host that implements
28
+ * only the reactive-engine half (`ShardHost`) has no KV surface to offer,
29
+ * and the suite reports the gap rather than asserting against a stub.
30
+ */
31
+ kv?: ShardKvStore;
32
+ /**
33
+ * Read back the frames a socket has been sent, oldest first.
34
+ *
35
+ * Optional, because not every host can observe its own outbound traffic —
36
+ * but a host that omits it cannot be asserted against for any *delivery*
37
+ * guarantee, only for "send did not throw". Since delivery is most of what
38
+ * the engine does (pokes, deltas, whispers), a host without this is only
39
+ * partially proven, and the suites say so rather than skipping quietly.
40
+ */
41
+ readFrames?: (socket: SocketHandle) => string[];
42
+ /**
43
+ * Re-create a runtime socket from its durable state. Optional: only hosts
44
+ * that can be driven through a recycle from inside a test implement it
45
+ * (see {@link ConformanceHost.simulateRecycle}).
46
+ */
47
+ restoreSocket?: (id: string, attachment: unknown) => SocketHandle;
48
+ /**
49
+ * The scheduler host under test. Optional: a package that implements only
50
+ * the shard/socket half of the platform (`@lunora/do`) has no scheduler to
51
+ * offer, and the suite reports the gap instead of asserting against a stub.
52
+ * A full composition root must supply one.
53
+ */
54
+ scheduler?: SchedulerHost;
55
+ /** The shard execution slot under test. */
56
+ shard: ShardHost;
57
+ /**
58
+ * Drive a pending job to its dead-letter state — however this host gets
59
+ * there — so the suite can assert what a parked job looks like without
60
+ * waiting out a real retry budget.
61
+ *
62
+ * Optional, and the same shape as {@link ConformanceHost.simulateRecycle}:
63
+ * a host that cannot force the transition from inside a test omits it and
64
+ * the suite reports the gap. It exists because the observable *invariants*
65
+ * of dead-lettering — disjoint listings, requeue semantics — are
66
+ * contract-level, while how many failures it takes to get there is host
67
+ * policy the contract deliberately does not fix.
68
+ * @returns `true` if the job was pending and is now parked.
69
+ */
70
+ simulateDeadLetter?: (id: string) => Promise<boolean>;
71
+ /**
72
+ * Drop runtime socket state while keeping durable state, so the suite can
73
+ * assert attachments survive. Optional: a host whose recycle is owned by
74
+ * the platform (Cloudflare hibernation) cannot trigger one on demand, and
75
+ * the suite skips the recycle leg rather than faking it.
76
+ */
77
+ simulateRecycle?: () => void;
78
+ /** The socket subscription host under test. */
79
+ socket: SocketHost;
80
+ }
81
+ /**
82
+ * Factory signature consumed by `defineHostContractSuite`. Must return a
83
+ * fresh, isolated host for each test run.
84
+ */
85
+ type ConformanceHostFactory = () => ConformanceHost | Promise<ConformanceHost>;
86
+ /**
87
+ * Create a reference in-memory conformance host built on `node:sqlite`.
88
+ *
89
+ * This is the cheapest possible host that satisfies the `@lunora/platform`
90
+ * contracts. It is intentionally not production-ready — it exists so the TCK
91
+ * can assert the contract shape without wrangler/miniflare overhead.
92
+ */
93
+ declare const createReferenceHost: () => ReferenceHost;
94
+ /**
95
+ * A reference host exposes the public `ConformanceHost` contracts plus
96
+ * reference-host-specific helpers for simulating recycle/rehydrate.
97
+ */
98
+ interface ReferenceHost extends ConformanceHost {
99
+ /** Re-create a runtime socket from its durable attachment and tags. */
100
+ restoreSocket: (id: string, attachment: unknown) => SocketHandle;
101
+ /** Drop runtime socket state while keeping durable attachments and tags. */
102
+ simulateRecycle: () => void;
103
+ }
104
+ /**
105
+ * Vitest API surface required by `defineHostContractSuite`. Passing the API in
106
+ * keeps the source file free of a runtime `vitest` import, so hosts that want
107
+ * to run the suite with a different test runner can do so.
108
+ */
109
+ type VitestApi = {
110
+ describe: typeof import("vitest").describe;
111
+ expect: typeof import("vitest").expect;
112
+ it: typeof import("vitest").it;
113
+ };
114
+ /**
115
+ * Define the host-contract conformance suite for the given factory.
116
+ *
117
+ * The suite asserts the provider-neutral behaviors that every Lunora host must
118
+ * provide: single-writer serialization, durable transactions, local SQL,
119
+ * durable alarms, socket accept/send/close, attachment round-trip across
120
+ * recycle, deterministic shard placement, and durable scheduling.
121
+ *
122
+ * Usage:
123
+ *
124
+ * ```ts
125
+ * import { describe, expect, it } from "vitest";
126
+ * import { createReferenceHost, defineHostContractSuite } from "@lunora/platform/conformance";
127
+ *
128
+ * defineHostContractSuite("reference", createReferenceHost, { describe, expect, it });
129
+ * ```
130
+ */
131
+ declare const defineHostContractSuite: (name: string, factory: ConformanceHostFactory, vitest: VitestApi) => void;
132
+ export { ConformanceHost as C, ReferenceHost as R, type VitestApi, ConformanceHostFactory as a, createReferenceHost as c, defineHostContractSuite };
@@ -0,0 +1,132 @@
1
+ import { f as ShardDirectory, j as ShardKvStore, n as SocketHandle, c as SchedulerHost, g as ShardHost, o as SocketHost } from "../packem_shared/socket-host.d-Cq5uVbiH.js";
2
+ /**
3
+ * A conformance host bundles all four platform contracts so a single factory
4
+ * can stand up a complete, isolated test environment.
5
+ */
6
+ interface ConformanceHost {
7
+ /**
8
+ * Resolve once a pending alarm has actually fired. Optional: hosts whose
9
+ * alarm delivery is owned by the platform and can't be observed from inside
10
+ * a shard callback (Cloudflare wakes a separate `alarm()` invocation) omit
11
+ * it, and the suite then asserts only the set/read/delete half of the alarm
12
+ * contract — platform delivery is the platform's test, not the adapter's.
13
+ */
14
+ awaitAlarmFired?: (target: number) => Promise<void>;
15
+ /** Optional cleanup hook (close DBs, release timers). */
16
+ cleanup?: () => void;
17
+ /**
18
+ * Mint a raw socket for {@link SocketHost.accept}. Optional: what a socket
19
+ * actually _is_ differs per host (Cloudflare needs a live `WebSocketPair` end), and
20
+ * the provider-neutral suite can't know. Defaults to an opaque object for
21
+ * hosts that don't care.
22
+ */
23
+ createSocket?: () => unknown;
24
+ /** The shard directory under test. */
25
+ directory: ShardDirectory;
26
+ /**
27
+ * The durable key-value store under test. Optional: a host that implements
28
+ * only the reactive-engine half (`ShardHost`) has no KV surface to offer,
29
+ * and the suite reports the gap rather than asserting against a stub.
30
+ */
31
+ kv?: ShardKvStore;
32
+ /**
33
+ * Read back the frames a socket has been sent, oldest first.
34
+ *
35
+ * Optional, because not every host can observe its own outbound traffic —
36
+ * but a host that omits it cannot be asserted against for any *delivery*
37
+ * guarantee, only for "send did not throw". Since delivery is most of what
38
+ * the engine does (pokes, deltas, whispers), a host without this is only
39
+ * partially proven, and the suites say so rather than skipping quietly.
40
+ */
41
+ readFrames?: (socket: SocketHandle) => string[];
42
+ /**
43
+ * Re-create a runtime socket from its durable state. Optional: only hosts
44
+ * that can be driven through a recycle from inside a test implement it
45
+ * (see {@link ConformanceHost.simulateRecycle}).
46
+ */
47
+ restoreSocket?: (id: string, attachment: unknown) => SocketHandle;
48
+ /**
49
+ * The scheduler host under test. Optional: a package that implements only
50
+ * the shard/socket half of the platform (`@lunora/do`) has no scheduler to
51
+ * offer, and the suite reports the gap instead of asserting against a stub.
52
+ * A full composition root must supply one.
53
+ */
54
+ scheduler?: SchedulerHost;
55
+ /** The shard execution slot under test. */
56
+ shard: ShardHost;
57
+ /**
58
+ * Drive a pending job to its dead-letter state — however this host gets
59
+ * there — so the suite can assert what a parked job looks like without
60
+ * waiting out a real retry budget.
61
+ *
62
+ * Optional, and the same shape as {@link ConformanceHost.simulateRecycle}:
63
+ * a host that cannot force the transition from inside a test omits it and
64
+ * the suite reports the gap. It exists because the observable *invariants*
65
+ * of dead-lettering — disjoint listings, requeue semantics — are
66
+ * contract-level, while how many failures it takes to get there is host
67
+ * policy the contract deliberately does not fix.
68
+ * @returns `true` if the job was pending and is now parked.
69
+ */
70
+ simulateDeadLetter?: (id: string) => Promise<boolean>;
71
+ /**
72
+ * Drop runtime socket state while keeping durable state, so the suite can
73
+ * assert attachments survive. Optional: a host whose recycle is owned by
74
+ * the platform (Cloudflare hibernation) cannot trigger one on demand, and
75
+ * the suite skips the recycle leg rather than faking it.
76
+ */
77
+ simulateRecycle?: () => void;
78
+ /** The socket subscription host under test. */
79
+ socket: SocketHost;
80
+ }
81
+ /**
82
+ * Factory signature consumed by `defineHostContractSuite`. Must return a
83
+ * fresh, isolated host for each test run.
84
+ */
85
+ type ConformanceHostFactory = () => ConformanceHost | Promise<ConformanceHost>;
86
+ /**
87
+ * Create a reference in-memory conformance host built on `node:sqlite`.
88
+ *
89
+ * This is the cheapest possible host that satisfies the `@lunora/platform`
90
+ * contracts. It is intentionally not production-ready — it exists so the TCK
91
+ * can assert the contract shape without wrangler/miniflare overhead.
92
+ */
93
+ declare const createReferenceHost: () => ReferenceHost;
94
+ /**
95
+ * A reference host exposes the public `ConformanceHost` contracts plus
96
+ * reference-host-specific helpers for simulating recycle/rehydrate.
97
+ */
98
+ interface ReferenceHost extends ConformanceHost {
99
+ /** Re-create a runtime socket from its durable attachment and tags. */
100
+ restoreSocket: (id: string, attachment: unknown) => SocketHandle;
101
+ /** Drop runtime socket state while keeping durable attachments and tags. */
102
+ simulateRecycle: () => void;
103
+ }
104
+ /**
105
+ * Vitest API surface required by `defineHostContractSuite`. Passing the API in
106
+ * keeps the source file free of a runtime `vitest` import, so hosts that want
107
+ * to run the suite with a different test runner can do so.
108
+ */
109
+ type VitestApi = {
110
+ describe: typeof import("vitest").describe;
111
+ expect: typeof import("vitest").expect;
112
+ it: typeof import("vitest").it;
113
+ };
114
+ /**
115
+ * Define the host-contract conformance suite for the given factory.
116
+ *
117
+ * The suite asserts the provider-neutral behaviors that every Lunora host must
118
+ * provide: single-writer serialization, durable transactions, local SQL,
119
+ * durable alarms, socket accept/send/close, attachment round-trip across
120
+ * recycle, deterministic shard placement, and durable scheduling.
121
+ *
122
+ * Usage:
123
+ *
124
+ * ```ts
125
+ * import { describe, expect, it } from "vitest";
126
+ * import { createReferenceHost, defineHostContractSuite } from "@lunora/platform/conformance";
127
+ *
128
+ * defineHostContractSuite("reference", createReferenceHost, { describe, expect, it });
129
+ * ```
130
+ */
131
+ declare const defineHostContractSuite: (name: string, factory: ConformanceHostFactory, vitest: VitestApi) => void;
132
+ export { ConformanceHost as C, ReferenceHost as R, type VitestApi, ConformanceHostFactory as a, createReferenceHost as c, defineHostContractSuite };
@@ -0,0 +1 @@
1
+ import{resolveShard as l}from"../packem_shared/resolveShard-uGhAKuTB.mjs";const m=(u,h,w)=>{const{describe:d,expect:t,it:o}=w;d(`host contract: ${u}`,()=>{const r=async()=>h(),n=e=>e.createSocket?.()??{};d("ShardHost",()=>{o("serializes mutations so no two closures interleave",async()=>{t.assertions(1);const e=await r(),a=[];await Promise.all([e.shard.runSerialized(async()=>{a.push("a-start"),await new Promise(c=>{setTimeout(c,10)}),a.push("a-end")}),e.shard.runSerialized(async()=>{a.push("b-start"),await new Promise(c=>{setTimeout(c,5)}),a.push("b-end")})]);const s=a.join("").includes("a-starta-end"),i=a.join("").includes("b-startb-end");t(s&&i).toBe(!0),e.cleanup?.()}),o("rolls back a transaction that throws",async()=>{t.assertions(2);const e=await r();await e.shard.transaction(async()=>{e.shard.sql.exec("CREATE TABLE IF NOT EXISTS rollback_test (id INTEGER PRIMARY KEY)"),e.shard.sql.exec("INSERT INTO rollback_test (id) VALUES (1)")}),await t(e.shard.transaction(async()=>{throw e.shard.sql.exec("INSERT INTO rollback_test (id) VALUES (2)"),new Error("boom")})).rejects.toThrow("boom");const a=e.shard.sql.exec("SELECT id FROM rollback_test WHERE id = 2").toArray();t(a).toHaveLength(0),e.cleanup?.()}),o("observes its own writes inside a transaction",async()=>{t.assertions(1);const e=await r(),a=await e.shard.transaction(async()=>(e.shard.sql.exec("CREATE TABLE IF NOT EXISTS ryw_test (id INTEGER PRIMARY KEY, value TEXT)"),e.shard.sql.exec("INSERT INTO ryw_test (id, value) VALUES (1, 'hello')"),e.shard.sql.exec("SELECT value FROM ryw_test WHERE id = 1").toArray()[0]?.value));t(a).toBe("hello"),e.cleanup?.()}),o("returns a cursor that buffers, yields one row, and iterates",async()=>{t.assertions(3);const e=await r();await e.shard.transaction(async()=>{e.shard.sql.exec("CREATE TABLE IF NOT EXISTS cursor_test (id INTEGER PRIMARY KEY)"),e.shard.sql.exec("INSERT INTO cursor_test (id) VALUES (1)"),e.shard.sql.exec("INSERT INTO cursor_test (id) VALUES (2)")}),t(e.shard.sql.exec("SELECT id FROM cursor_test ORDER BY id").toArray()).toHaveLength(2),t(e.shard.sql.exec("SELECT id FROM cursor_test WHERE id = 1").one()).toEqual({id:1}),t([...e.shard.sql.exec("SELECT id FROM cursor_test ORDER BY id")]).toHaveLength(2),e.cleanup?.()}),o("reports a pending alarm, and clears it once fired",async()=>{t.assertions(2);const e=await r(),a=Date.now()+50;if(await e.shard.alarms.set(a),t(await e.shard.alarms.get()).toBe(a),e.awaitAlarmFired===void 0){t(await e.shard.alarms.get()).toBe(a),e.cleanup?.();return}await e.awaitAlarmFired(a),t(await e.shard.alarms.get()).toBeNull(),e.cleanup?.()}),o("deletes a pending alarm",async()=>{t.assertions(1);const e=await r();await e.shard.alarms.set(Date.now()+1e4),await e.shard.alarms.delete(),t(await e.shard.alarms.get()).toBeNull(),e.cleanup?.()})}),d("SocketHost",()=>{o("accepts a socket and can send/close",async()=>{const e=await r(),a=e.socket.accept(n(e),{user:"ada"});t(e.socket.idFor(a)).toBeDefined(),a.send("hello"),t(e.socket.getSockets().map(s=>e.socket.idFor(s))).toContain(e.socket.idFor(a)),e.readFrames!==void 0&&t(e.readFrames(a)).toStrictEqual(["hello"]),t(()=>{a.close(1e3,"done")}).not.toThrow(),e.cleanup?.()}),o("round-trips an attachment on a live socket",async()=>{t.assertions(1);const e=await r(),a={roomId:"room-1",roles:["admin"]},s=e.socket.accept(n(e),a);t(s.deserializeAttachment()).toEqual(a),e.cleanup?.()}),o("round-trips attachments across a recycle",async()=>{t.assertions(1);const e=await r();if(e.simulateRecycle===void 0||e.restoreSocket===void 0){t(!0).toBe(!0),e.cleanup?.();return}const a={roomId:"room-1",roles:["admin"]},s=e.socket.accept(n(e),a);e.simulateRecycle();const i=e.restoreSocket(e.socket.idFor(s),a);t(i.deserializeAttachment()).toEqual(a),e.cleanup?.()}),o("keeps idFor stable across repeated calls within a wake",async()=>{t.assertions(1);const e=await r(),a=e.socket.accept(n(e),{}),s=e.socket.idFor(a),i=e.socket.idFor(a);t(i).toBe(s),e.cleanup?.()}),o("keeps idFor stable across a recycle",async()=>{t.assertions(1);const e=await r();if(e.simulateRecycle===void 0||e.restoreSocket===void 0){t(!0).toBe(!0),e.cleanup?.();return}const a={roomId:"room-1",roles:["admin"]},s=e.socket.accept(n(e),a),i=e.socket.idFor(s);e.simulateRecycle();const c=e.restoreSocket(i,a);t(e.socket.idFor(c)).toBe(i),e.cleanup?.()}),o("returns exactly the sockets carrying an accept-time tag",async()=>{t.assertions(4);const e=await r(),a=e.socket.accept(n(e),{},["room-a"]),s=e.socket.accept(n(e),{},["room-b"]),i=e.socket.accept(n(e),{}),c=p=>e.socket.idFor(p);t(e.socket.getSockets("room-a").map(c)).toStrictEqual([c(a)]),t(e.socket.getSockets("room-b").map(c)).toStrictEqual([c(s)]),t(e.socket.getSockets("room-c").map(c)).toStrictEqual([]),t(e.socket.getSockets().map(c)).toContain(c(i)),e.cleanup?.()}),o("resolves a raw socket back to its handle",async()=>{t.assertions(2);const e=await r(),a=n(e),s=e.socket.accept(a,{}),i=e.socket.handleFor(a);t(i!==void 0&&e.socket.idFor(i)).toBe(e.socket.idFor(s)),t(e.socket.handleFor(n(e))).toBeUndefined(),e.cleanup?.()}),o("reports a plausible outbound queue depth, if any",async()=>{t.assertions(1);const e=await r(),a=e.socket.accept(n(e),{}),{bufferedAmount:s}=a;t(s===void 0||typeof s=="number"&&s>=0).toBe(!0),e.cleanup?.()}),o("retags a live socket when the host declares mutable tags",async()=>{t.assertions(2);const e=await r();if(e.socket.setTag===void 0){t(e.socket.removeTag).toBeUndefined(),t(!0).toBe(!0),e.cleanup?.();return}const a=e.socket.accept(n(e),{});e.socket.setTag(a,"room-a"),t(e.socket.getSockets("room-a").map(s=>e.socket.idFor(s))).toStrictEqual([e.socket.idFor(a)]),e.socket.removeTag?.(a,"room-a"),t(e.socket.getSockets("room-a").map(s=>e.socket.idFor(s))).toStrictEqual([]),e.cleanup?.()})}),d("ShardDirectory",()=>{o("resolves shard keys deterministically",async()=>{t.assertions(1);const e=await r(),a=await l(e.directory,"tenant-42").fetch(new Request("http://localhost/")),s=await l(e.directory,"tenant-42").fetch(new Request("http://localhost/"));await t(a.text()).resolves.toBe(await s.text()),e.cleanup?.()}),o("dispatches fetch to a resolved stub",async()=>{t.assertions(1);const e=await r(),a=await l(e.directory,"tenant-42").fetch(new Request("http://localhost/"));t(a).toBeInstanceOf(Response),e.cleanup?.()})}),d("SchedulerHost",()=>{o("schedules a job for a future timestamp",async()=>{t.assertions(2);const e=await r();if(e.scheduler===void 0){t(e.scheduler).toBeUndefined(),t(!0).toBe(!0),e.cleanup?.();return}const a=Date.now(),s=await e.scheduler.schedule("tasks/remind",{user:"ada"},{delayMs:50});t(s.scheduledFor).toBeGreaterThanOrEqual(a+50),t(s.id).toBeDefined(),e.cleanup?.()}),o("cancels a scheduled job",async()=>{t.assertions(1);const e=await r();if(e.scheduler===void 0){t(e.scheduler).toBeUndefined(),e.cleanup?.();return}const a=await e.scheduler.schedule("tasks/remind",{},{delayMs:1e4}),s=await e.scheduler.cancel(a.id);t(s).toBe(!0),e.cleanup?.()}),o("reports a second cancel of the same job as false",async()=>{t.assertions(2);const e=await r();if(e.scheduler===void 0){t(e.scheduler).toBeUndefined(),t(!0).toBe(!0),e.cleanup?.();return}const a=await e.scheduler.schedule("tasks/remind",{},{delayMs:1e4});t(await e.scheduler.cancel(a.id)).toBe(!0),t(await e.scheduler.cancel(a.id)).toBe(!1),e.cleanup?.()}),o("gives two identical schedules independently cancellable ids",async()=>{t.assertions(3);const e=await r();if(e.scheduler===void 0){t(e.scheduler).toBeUndefined(),t(!0).toBe(!0),t(!0).toBe(!0),e.cleanup?.();return}const a=await e.scheduler.schedule("tasks/remind",{user:"ada"},{delayMs:1e4}),s=await e.scheduler.schedule("tasks/remind",{user:"ada"},{delayMs:1e4});t(s.id).not.toBe(a.id),t(await e.scheduler.cancel(a.id)).toBe(!0),t(await e.scheduler.cancel(s.id)).toBe(!0),e.cleanup?.()}),o("lists a pending job with a zero attempt count",async()=>{t.assertions(2);const e=await r();if(e.scheduler?.list===void 0){t(e.scheduler?.list).toBeUndefined(),t(!0).toBe(!0),e.cleanup?.();return}const a=await e.scheduler.schedule("tasks/remind",{user:"ada"},{delayMs:1e4}),s=(await e.scheduler.list()).find(i=>i.id===a.id);t(s?.functionPath).toBe("tasks/remind"),t(s?.attempts).toBe(0),e.cleanup?.()}),o("keeps the pending and dead-letter listings disjoint",async()=>{t.assertions(2);const e=await r();if(e.scheduler?.list===void 0||e.scheduler.deadLetter===void 0||e.simulateDeadLetter===void 0){t(e.simulateDeadLetter).toBeUndefined(),t(!0).toBe(!0),e.cleanup?.();return}const a=await e.scheduler.schedule("tasks/remind",{},{delayMs:1e4});await e.simulateDeadLetter(a.id);const s=await e.scheduler.list(),i=await e.scheduler.deadLetter.list();t(s.some(c=>c.id===a.id)).toBe(!1),t(i.some(c=>c.id===a.id)).toBe(!0),e.cleanup?.()}),o("returns a requeued job to the pending set with a fresh budget",async()=>{t.assertions(4);const e=await r();if(e.scheduler?.list===void 0||e.scheduler.deadLetter===void 0||e.simulateDeadLetter===void 0){t(e.simulateDeadLetter).toBeUndefined(),t(!0).toBe(!0),t(!0).toBe(!0),t(!0).toBe(!0),e.cleanup?.();return}const a=await e.scheduler.schedule("tasks/remind",{},{delayMs:1e4});await e.simulateDeadLetter(a.id),t(await e.scheduler.deadLetter.requeue(a.id)).toBe(!0);const s=(await e.scheduler.list()).find(c=>c.id===a.id);t(s).toBeDefined(),t(s?.attempts).toBe(0);const i=await e.scheduler.deadLetter.list();t(i.some(c=>c.id===a.id)).toBe(!1),e.cleanup?.()}),o("reports a requeue of an unparked job as false",async()=>{t.assertions(1);const e=await r();if(e.scheduler?.deadLetter===void 0){t(e.scheduler?.deadLetter).toBeUndefined(),e.cleanup?.();return}t(await e.scheduler.deadLetter.requeue("job-does-not-exist")).toBe(!1),e.cleanup?.()})}),d("ShardKvStore",()=>{o("reads back a written value",async()=>{t.assertions(2);const e=await r();if(e.kv===void 0){t(e.kv).toBeUndefined(),t(!0).toBe(!0),e.cleanup?.();return}await e.kv.put("s:token-1",{userId:"ada"}),t(await e.kv.get("s:token-1")).toEqual({userId:"ada"}),t(await e.kv.get("s:missing")).toBeUndefined(),e.cleanup?.()}),o("deletes a key idempotently",async()=>{t.assertions(3);const e=await r();if(e.kv===void 0){t(e.kv).toBeUndefined(),t(!0).toBe(!0),t(!0).toBe(!0),e.cleanup?.();return}await e.kv.put("k",1),t(await e.kv.delete("k")).toBe(!0),t(await e.kv.delete("k")).toBe(!1),t(await e.kv.get("k")).toBeUndefined(),e.cleanup?.()}),o("enumerates exactly the keys under a prefix",async()=>{t.assertions(2);const e=await r();if(e.kv===void 0){t(e.kv).toBeUndefined(),t(!0).toBe(!0),e.cleanup?.();return}await e.kv.put("s:a",1),await e.kv.put("s:b",2),await e.kv.put("other",3);const a=await e.kv.list({prefix:"s:"}),s=await e.kv.list();t([...a.keys()].toSorted((i,c)=>i.localeCompare(c))).toStrictEqual(["s:a","s:b"]),t(s.size).toBe(3),e.cleanup?.()})})})};export{m as defineHostContractSuite};