@lunora/container 1.0.0-alpha.3 → 1.0.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -103,3 +103,29 @@ Unless required by applicable law or agreed to in writing, software distributed
103
103
  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
104
  CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
105
  specific language governing permissions and limitations under the License.
106
+
107
+ <!-- DEPENDENCIES -->
108
+
109
+ # Licenses of bundled dependencies
110
+ The published @lunora/container artifact additionally contains code with the following licenses:
111
+ MIT OR Apache-2.0
112
+
113
+ # Bundled dependencies:
114
+ ## @cloudflare/containers
115
+ License: MIT OR Apache-2.0
116
+ Repository: git+https://github.com/cloudflare/containers.git
117
+
118
+ <!-- /DEPENDENCIES -->
119
+
120
+ <!-- TYPE_DEPENDENCIES -->
121
+
122
+ # Licenses of bundled types
123
+ The published @lunora/container artifact additionally contains code with the following licenses:
124
+ MIT OR Apache-2.0
125
+
126
+ # Bundled types:
127
+ ## @cloudflare/containers
128
+ License: MIT OR Apache-2.0
129
+ Repository: git+https://github.com/cloudflare/containers.git
130
+
131
+ <!-- /TYPE_DEPENDENCIES -->
package/README.md CHANGED
@@ -10,6 +10,8 @@
10
10
 
11
11
  <!-- END_PACKAGE_OG_IMAGE_PLACEHOLDER -->
12
12
 
13
+ > **Experimental** — this package is outside the Lunora 1.0 stability promise: its API may change in any release, without a major version bump.
14
+
13
15
  <br />
14
16
 
15
17
  <div align="center">
@@ -66,6 +68,7 @@ export const transcoder = defineContainer({
66
68
  maxInstances: 5,
67
69
  sleepAfter: "5m",
68
70
  secrets: ["TRANSCODER_API_KEY"], // forwarded from Worker secrets / .dev.vars
71
+ labels: { team: "media" }, // metadata attached to every instance for metrics/observability
69
72
  });
70
73
  ```
71
74
 
@@ -89,10 +92,95 @@ export const transcode = action.input({ videoId: v.id("videos") }).action(async
89
92
  });
90
93
  ```
91
94
 
92
- `ctx.containers` is action-only (container calls are external I/O, like `ctx.fetch`); `.get(name)` handles also expose `start`/`stop`/`destroy`/`getState` lifecycle control.
95
+ `.get()` and `.any()` retry the **same** instance through a cold start — when a request lands while Cloudflare is still provisioning (a `503` "no instance", `500` "Failed to start", `429`, or "not listening"), they back off and retry (default 3 attempts) so the provisioning race never reaches your handler. Genuine app `5xx`s pass straight through. Tune or disable per call with `.get(id, { attempts, backoffMs })` (a pre-built `Request` is sent once and not retried, since its body may not be replayable).
96
+
97
+ `ctx.containers` is action-only (container calls are external I/O, like `ctx.fetch`); `.get(name)` handles also expose `start`/`stop`/`destroy`/`getState` lifecycle control plus `renewActivityTimeout()` and `egress.*` (adjust the allow/deny lists at runtime). HTTP requests and WebSocket frames already keep a busy container awake automatically; `renewActivityTimeout()` is the escape hatch for non-HTTP/non-WS activity.
93
98
 
94
99
  The config layer (`lunora dev` / `lunora deploy`) reconciles the wrangler `containers[]` entry, the `CONTAINER_*` Durable Object binding, and the SQLite-class migration automatically; `wrangler deploy` builds the Dockerfile with local Docker and pushes it to the Cloudflare Registry.
95
100
 
101
+ ### Multi-port containers
102
+
103
+ Declare every port the container must be listening on with `requiredPorts` (start-up waits for all of them); `defaultPort` is the target when a request doesn't pick one. Route a single request to another port with `.port(n)` — it composes with `.get()`, `.any()`, and `.pool()`:
104
+
105
+ ```ts
106
+ export const app = defineContainer({
107
+ image: "./containers/app",
108
+ defaultPort: 8080,
109
+ requiredPorts: [8080, 9090], // app + admin
110
+ });
111
+
112
+ // in an action:
113
+ await ctx.containers.app.get(tenantId).fetch("/work"); // → 8080
114
+ await ctx.containers.app.get(tenantId).port(9090).fetch("/admin"); // → 9090
115
+ ```
116
+
117
+ ### Build-time args
118
+
119
+ `env` and `secrets` are runtime values; for build-time `docker build --build-arg` values (wrangler `image_vars`, exposed to the Dockerfile as `ARG`) use `buildArgs`. They apply only to an image Lunora builds and are ignored for a pre-built `{ registry }` image.
120
+
121
+ ```ts
122
+ export const worker = defineContainer({
123
+ image: "./containers/worker",
124
+ buildArgs: { NODE_VERSION: "22", BUILD_TARGET: "production" },
125
+ });
126
+ ```
127
+
128
+ ### Secrets and Secrets Store
129
+
130
+ `secrets` forwards plain Worker secrets into the container env; `secretsStore` maps a _container env-var name → Cloudflare [Secrets Store](https://developers.cloudflare.com/secrets-store/) binding name_ and resolves each with its async `.get()` at first start (memoised). A collision with `env`/`secrets` is rejected at authoring time; a missing binding fails the start — the same fail-closed stance as `secrets`. Like `env`/`secrets`, these injected values only apply to implicit starts or a bare `start()`; a per-instance `start({ envVars })` replaces the env set wholesale (and skips Secrets Store resolution entirely).
131
+
132
+ ```ts
133
+ export const worker = defineContainer({
134
+ image: "./containers/worker",
135
+ secrets: ["TRANSCODER_API_KEY"], // plain Worker secret → same-named env var
136
+ secretsStore: { STRIPE_KEY: "STRIPE_SECRET" }, // env.STRIPE_SECRET.get() → STRIPE_KEY
137
+ });
138
+ ```
139
+
140
+ ### Egress firewall
141
+
142
+ Pair `enableInternet: false` with an `allowedHosts` allow-list (or layer a `deniedHosts` deny-list that overrides everything) to constrain a container's outbound traffic; `interceptHttps: true` extends the lists to TLS connections (the image must trust the Cloudflare CA). Codegen re-exports the `ContainerProxy` worker entrypoint the interception path needs automatically.
143
+
144
+ ```ts
145
+ export const fetcher = defineContainer({
146
+ image: "./containers/fetcher",
147
+ enableInternet: false,
148
+ allowedHosts: ["*.stripe.com", "api.github.com"],
149
+ deniedHosts: ["*.evil.com"],
150
+ });
151
+
152
+ // tighten or relax one running instance at runtime:
153
+ await ctx.containers.fetcher.get(tenantId).egress.allow("hooks.slack.com");
154
+ ```
155
+
156
+ For advanced egress rewriting in worker code, `@lunora/container/do` re-exports Cloudflare's custom outbound-handler types (`OutboundHandler`, `OutboundHandlers`, `outboundParams`) — wire them onto a hand-authored `LunoraContainer` subclass to inject auth, route, or mock a container's outbound calls.
157
+
158
+ ### Readiness gating
159
+
160
+ The platform health check waits for an open port, not necessarily a _ready_ app. `readyOn` adds application-level probes that gate request proxying: a `ctx.containers.<name>` fetch holds until every probe responds with its expected status, so callers never hit a container still applying migrations or warming caches. Probes are declarative data (path + optional `port`/`status`), run in parallel at start, and probe the container's TCP port directly.
161
+
162
+ ```ts
163
+ export const api = defineContainer({
164
+ image: "./containers/api",
165
+ defaultPort: 8080,
166
+ readyOn: [
167
+ { path: "/ready" }, // expect 200 on defaultPort
168
+ { path: "/live", port: 9090, status: 204 }, // own port + expected status
169
+ ],
170
+ });
171
+ ```
172
+
173
+ ### Hard timeout
174
+
175
+ `sleepAfter` caps _idle_ time; `hardTimeout` caps _total_ lifetime — a runaway-cost backstop measured from start, regardless of activity (same grammar as `sleepAfter`). When it elapses the generated class's `onHardTimeoutExpired` hook runs (default: `stop()`); the timer is run-generation-stamped so a stale timer from a slept/crashed run can't kill a fresh one.
176
+
177
+ ```ts
178
+ export const job = defineContainer({
179
+ image: "./containers/job",
180
+ hardTimeout: "1h", // never run longer than an hour, busy or not
181
+ });
182
+ ```
183
+
96
184
  ### Calling Lunora from inside a container
97
185
 
98
186
  Container code calls back into your app's functions with the bridge client (any JS runtime), over the Worker's HTTP RPC endpoint:
@@ -118,6 +206,16 @@ Secure the bridge in `resolveIdentity`: read `request.headers.get("authorization
118
206
 
119
207
  > This README covers the basics. For the full API, options, and guides, see the **[documentation](https://lunora.sh/docs/addons/containers)**.
120
208
 
209
+ ### Known platform limitations
210
+
211
+ Some constraints live in Cloudflare Containers itself (open issues on [`cloudflare/containers`](https://github.com/cloudflare/containers/issues)). Lunora papers over what it can — cold-start retry and WebSocket keep-alive — and surfaces the rest:
212
+
213
+ - **No autoscaling / location-aware routing** — pools are fixed-size and pick uniformly at random ([#226](https://github.com/cloudflare/containers/issues/226)).
214
+ - **Ephemeral disk; no FUSE / tmpfs / some `node:net` modes** — persist to [`@lunora/storage`](https://www.npmjs.com/package/@lunora/storage) (R2) ([#112](https://github.com/cloudflare/containers/issues/112), [#160](https://github.com/cloudflare/containers/issues/160), [#67](https://github.com/cloudflare/containers/issues/67)).
215
+ - **Egress interception is HTTP-first** — HTTPS needs `interceptHttps`; raw gRPC isn't interceptable yet ([#195](https://github.com/cloudflare/containers/issues/195)).
216
+ - **Long jobs can be terminated on rollout** — use `hardTimeout` and make work resumable ([#138](https://github.com/cloudflare/containers/issues/138)).
217
+ - **Local dev can't pull from the Cloudflare Registry** — build from a local Dockerfile ([#155](https://github.com/cloudflare/containers/issues/155)).
218
+
121
219
  ## Related
122
220
 
123
221
  - [`@lunora/server`](https://www.npmjs.com/package/@lunora/server) — defines the actions that drive containers via `ctx.containers`.
package/dist/bridge.d.mts CHANGED
@@ -1,4 +1,8 @@
1
- /** A `fetch` implementation defaults to the runtime global. */
1
+ import { LunoraError } from '@lunora/errors';
2
+ /**
3
+ * A `fetch` implementation — defaults to the runtime global.
4
+ * @experimental
5
+ */
2
6
  type FetchLike = (input: string, init: {
3
7
  body: string;
4
8
  headers: Record<string, string>;
@@ -9,34 +13,41 @@ type FetchLike = (input: string, init: {
9
13
  status: number;
10
14
  statusText?: string;
11
15
  }>;
16
+ /**
17
+ * `ContainerBridgeOptions` is part of the experimental `@lunora/container` API and may change without a major version bump.
18
+ * @experimental
19
+ */
12
20
  interface ContainerBridgeOptions {
13
21
  /**
14
- * Base URL of the deployed Lunora Worker (no trailing `/_lunora/rpc`), e.g.
15
- * `https://my-app.workers.dev`. In a Lunora container, surface it as an
16
- * `env` value on the definition.
17
- */
22
+ * Base URL of the deployed Lunora Worker (no trailing `/_lunora/rpc`), e.g.
23
+ * `https://my-app.workers.dev`. In a Lunora container, surface it as an
24
+ * `env` value on the definition.
25
+ */
18
26
  baseUrl: string;
19
27
  /** Injectable `fetch` (tests / non-global runtimes). Defaults to `globalThis.fetch`. */
20
28
  fetch?: FetchLike;
21
29
  /**
22
- * Bearer token sent as `Authorization: Bearer &lt;token>`. Your Worker's
23
- * `resolveIdentity` maps it to the identity the called functions run as.
24
- * Pass it to the container as a `secret`, never bake it into the image.
25
- */
30
+ * Bearer token sent as `Authorization: Bearer <token>`. Your Worker's
31
+ * `resolveIdentity` maps it to the identity the called functions run as.
32
+ * Pass it to the container as a `secret`, never bake it into the image.
33
+ */
26
34
  token?: string;
27
35
  }
28
- /** Thrown when a Lunora function returns an error envelope. Carries the wire `code`. */
29
- declare class ContainerBridgeError extends Error {
30
- readonly code: string;
36
+ /**
37
+ * Thrown when a Lunora function returns an error envelope. A `LunoraError` subclass carrying the wire `code`.
38
+ * @experimental
39
+ */
40
+ declare class ContainerBridgeError extends LunoraError {
31
41
  constructor(code: string, message: string);
32
42
  }
33
43
  /**
34
- * Structural mirror of `@lunora/client`'s `FunctionReference` — the typed
35
- * handle the generated `_generated/api` object carries. Declared locally (not
36
- * imported) so the bridge stays dependency-free and its `.d.ts` is
37
- * self-contained; the `__lunoraPhantom` shape matches, so a real `api.x.y`
38
- * reference is assignable and its arg/return types are inferable.
39
- */
44
+ * Structural mirror of `@lunora/client`'s `FunctionReference` — the typed
45
+ * handle the generated `_generated/api` object carries. Declared locally (not
46
+ * imported) so the bridge stays dependency-free and its `.d.ts` is
47
+ * self-contained; the `__lunoraPhantom` shape matches, so a real `api.x.y`
48
+ * reference is assignable and its arg/return types are inferable.
49
+ * @experimental
50
+ */
40
51
  interface BridgeFunctionReference<Args = unknown, Result = unknown> {
41
52
  readonly __lunoraPhantom?: {
42
53
  args: Args;
@@ -56,6 +67,10 @@ type ResultOfReference<Reference> = Reference extends {
56
67
  returns: infer Result;
57
68
  };
58
69
  } ? Result : never;
70
+ /**
71
+ * `ContainerBridge` is part of the experimental `@lunora/container` API and may change without a major version bump.
72
+ * @experimental
73
+ */
59
74
  interface ContainerBridge {
60
75
  /** Call an `action` by `namespace:fn` path. Alias of {@link ContainerBridge.call} for intent. */
61
76
  action: <Result = unknown>(functionPath: string, args?: Record<string, unknown>, shardKey?: string) => Promise<Result>;
@@ -66,25 +81,26 @@ interface ContainerBridge {
66
81
  /** Call a `query` by `namespace:fn` path. Alias of {@link ContainerBridge.call} for intent. */
67
82
  query: <Result = unknown>(functionPath: string, args?: Record<string, unknown>, shardKey?: string) => Promise<Result>;
68
83
  /**
69
- * Fully-typed call via a generated function reference. Pass a reference from
70
- * the project's `_generated/api` (e.g. `api.messages.list`) and the args +
71
- * result are inferred from it — the typed counterpart to {@link ContainerBridge.call}
72
- * for JS/TS containers that can import the generated `api`.
73
- */
84
+ * Fully-typed call via a generated function reference. Pass a reference from
85
+ * the project's `_generated/api` (e.g. `api.messages.list`) and the args +
86
+ * result are inferred from it — the typed counterpart to {@link ContainerBridge.call}
87
+ * for JS/TS containers that can import the generated `api`.
88
+ */
74
89
  run: <Reference extends BridgeFunctionReference>(reference: Reference, args: ArgsOfReference<Reference>, shardKey?: string) => Promise<ResultOfReference<Reference>>;
75
90
  }
76
91
  /**
77
- * Build a container→Lunora bridge bound to a Worker URL + token.
78
- *
79
- * ```ts
80
- * const lunora = createContainerBridge({ baseUrl: process.env.LUNORA_URL!, token: process.env.LUNORA_TOKEN });
81
- * const messages = await lunora.query("messages:list", { limit: 20 });
82
- * await lunora.mutation("messages:markProcessed", { id });
83
- * ```
84
- *
85
- * `query`/`mutation`/`action` are intent-revealing aliases of one `call` — the
86
- * wire is identical and the server dispatches by the function's registered
87
- * kind, so a query path called via `.mutation(...)` still runs as a query.
88
- */
92
+ * Build a container→Lunora bridge bound to a Worker URL + token.
93
+ *
94
+ * ```ts
95
+ * const lunora = createContainerBridge({ baseUrl: process.env.LUNORA_URL!, token: process.env.LUNORA_TOKEN });
96
+ * const messages = await lunora.query("messages:list", { limit: 20 });
97
+ * await lunora.mutation("messages:markProcessed", { id });
98
+ * ```
99
+ *
100
+ * `query`/`mutation`/`action` are intent-revealing aliases of one `call` — the
101
+ * wire is identical and the server dispatches by the function's registered
102
+ * kind, so a query path called via `.mutation(...)` still runs as a query.
103
+ * @experimental
104
+ */
89
105
  declare const createContainerBridge: (options: ContainerBridgeOptions) => ContainerBridge;
90
106
  export { type BridgeFunctionReference, type ContainerBridge, ContainerBridgeError, type ContainerBridgeOptions, type FetchLike, createContainerBridge };
package/dist/bridge.d.ts CHANGED
@@ -1,4 +1,8 @@
1
- /** A `fetch` implementation defaults to the runtime global. */
1
+ import { LunoraError } from '@lunora/errors';
2
+ /**
3
+ * A `fetch` implementation — defaults to the runtime global.
4
+ * @experimental
5
+ */
2
6
  type FetchLike = (input: string, init: {
3
7
  body: string;
4
8
  headers: Record<string, string>;
@@ -9,34 +13,41 @@ type FetchLike = (input: string, init: {
9
13
  status: number;
10
14
  statusText?: string;
11
15
  }>;
16
+ /**
17
+ * `ContainerBridgeOptions` is part of the experimental `@lunora/container` API and may change without a major version bump.
18
+ * @experimental
19
+ */
12
20
  interface ContainerBridgeOptions {
13
21
  /**
14
- * Base URL of the deployed Lunora Worker (no trailing `/_lunora/rpc`), e.g.
15
- * `https://my-app.workers.dev`. In a Lunora container, surface it as an
16
- * `env` value on the definition.
17
- */
22
+ * Base URL of the deployed Lunora Worker (no trailing `/_lunora/rpc`), e.g.
23
+ * `https://my-app.workers.dev`. In a Lunora container, surface it as an
24
+ * `env` value on the definition.
25
+ */
18
26
  baseUrl: string;
19
27
  /** Injectable `fetch` (tests / non-global runtimes). Defaults to `globalThis.fetch`. */
20
28
  fetch?: FetchLike;
21
29
  /**
22
- * Bearer token sent as `Authorization: Bearer &lt;token>`. Your Worker's
23
- * `resolveIdentity` maps it to the identity the called functions run as.
24
- * Pass it to the container as a `secret`, never bake it into the image.
25
- */
30
+ * Bearer token sent as `Authorization: Bearer <token>`. Your Worker's
31
+ * `resolveIdentity` maps it to the identity the called functions run as.
32
+ * Pass it to the container as a `secret`, never bake it into the image.
33
+ */
26
34
  token?: string;
27
35
  }
28
- /** Thrown when a Lunora function returns an error envelope. Carries the wire `code`. */
29
- declare class ContainerBridgeError extends Error {
30
- readonly code: string;
36
+ /**
37
+ * Thrown when a Lunora function returns an error envelope. A `LunoraError` subclass carrying the wire `code`.
38
+ * @experimental
39
+ */
40
+ declare class ContainerBridgeError extends LunoraError {
31
41
  constructor(code: string, message: string);
32
42
  }
33
43
  /**
34
- * Structural mirror of `@lunora/client`'s `FunctionReference` — the typed
35
- * handle the generated `_generated/api` object carries. Declared locally (not
36
- * imported) so the bridge stays dependency-free and its `.d.ts` is
37
- * self-contained; the `__lunoraPhantom` shape matches, so a real `api.x.y`
38
- * reference is assignable and its arg/return types are inferable.
39
- */
44
+ * Structural mirror of `@lunora/client`'s `FunctionReference` — the typed
45
+ * handle the generated `_generated/api` object carries. Declared locally (not
46
+ * imported) so the bridge stays dependency-free and its `.d.ts` is
47
+ * self-contained; the `__lunoraPhantom` shape matches, so a real `api.x.y`
48
+ * reference is assignable and its arg/return types are inferable.
49
+ * @experimental
50
+ */
40
51
  interface BridgeFunctionReference<Args = unknown, Result = unknown> {
41
52
  readonly __lunoraPhantom?: {
42
53
  args: Args;
@@ -56,6 +67,10 @@ type ResultOfReference<Reference> = Reference extends {
56
67
  returns: infer Result;
57
68
  };
58
69
  } ? Result : never;
70
+ /**
71
+ * `ContainerBridge` is part of the experimental `@lunora/container` API and may change without a major version bump.
72
+ * @experimental
73
+ */
59
74
  interface ContainerBridge {
60
75
  /** Call an `action` by `namespace:fn` path. Alias of {@link ContainerBridge.call} for intent. */
61
76
  action: <Result = unknown>(functionPath: string, args?: Record<string, unknown>, shardKey?: string) => Promise<Result>;
@@ -66,25 +81,26 @@ interface ContainerBridge {
66
81
  /** Call a `query` by `namespace:fn` path. Alias of {@link ContainerBridge.call} for intent. */
67
82
  query: <Result = unknown>(functionPath: string, args?: Record<string, unknown>, shardKey?: string) => Promise<Result>;
68
83
  /**
69
- * Fully-typed call via a generated function reference. Pass a reference from
70
- * the project's `_generated/api` (e.g. `api.messages.list`) and the args +
71
- * result are inferred from it — the typed counterpart to {@link ContainerBridge.call}
72
- * for JS/TS containers that can import the generated `api`.
73
- */
84
+ * Fully-typed call via a generated function reference. Pass a reference from
85
+ * the project's `_generated/api` (e.g. `api.messages.list`) and the args +
86
+ * result are inferred from it — the typed counterpart to {@link ContainerBridge.call}
87
+ * for JS/TS containers that can import the generated `api`.
88
+ */
74
89
  run: <Reference extends BridgeFunctionReference>(reference: Reference, args: ArgsOfReference<Reference>, shardKey?: string) => Promise<ResultOfReference<Reference>>;
75
90
  }
76
91
  /**
77
- * Build a container→Lunora bridge bound to a Worker URL + token.
78
- *
79
- * ```ts
80
- * const lunora = createContainerBridge({ baseUrl: process.env.LUNORA_URL!, token: process.env.LUNORA_TOKEN });
81
- * const messages = await lunora.query("messages:list", { limit: 20 });
82
- * await lunora.mutation("messages:markProcessed", { id });
83
- * ```
84
- *
85
- * `query`/`mutation`/`action` are intent-revealing aliases of one `call` — the
86
- * wire is identical and the server dispatches by the function's registered
87
- * kind, so a query path called via `.mutation(...)` still runs as a query.
88
- */
92
+ * Build a container→Lunora bridge bound to a Worker URL + token.
93
+ *
94
+ * ```ts
95
+ * const lunora = createContainerBridge({ baseUrl: process.env.LUNORA_URL!, token: process.env.LUNORA_TOKEN });
96
+ * const messages = await lunora.query("messages:list", { limit: 20 });
97
+ * await lunora.mutation("messages:markProcessed", { id });
98
+ * ```
99
+ *
100
+ * `query`/`mutation`/`action` are intent-revealing aliases of one `call` — the
101
+ * wire is identical and the server dispatches by the function's registered
102
+ * kind, so a query path called via `.mutation(...)` still runs as a query.
103
+ * @experimental
104
+ */
89
105
  declare const createContainerBridge: (options: ContainerBridgeOptions) => ContainerBridge;
90
106
  export { type BridgeFunctionReference, type ContainerBridge, ContainerBridgeError, type ContainerBridgeOptions, type FetchLike, createContainerBridge };
package/dist/bridge.mjs CHANGED
@@ -1,76 +1 @@
1
- const RPC_PATH = "/_lunora/rpc";
2
- class ContainerBridgeError extends Error {
3
- code;
4
- constructor(code, message) {
5
- super(message);
6
- this.name = "ContainerBridgeError";
7
- this.code = code;
8
- }
9
- }
10
- const joinUrl = (baseUrl, path) => {
11
- let base = baseUrl;
12
- while (base.endsWith("/")) {
13
- base = base.slice(0, -1);
14
- }
15
- return `${base}${path}`;
16
- };
17
- const statusError = (functionPath, response) => new Error(
18
- `createContainerBridge: request to "${functionPath}" failed (status ${String(response.status)}${response.statusText ? ` ${response.statusText}` : ""})`
19
- );
20
- const parseResponseBody = async (response, functionPath) => {
21
- try {
22
- return await response.json();
23
- } catch {
24
- if (!response.ok) {
25
- throw statusError(functionPath, response);
26
- }
27
- throw new Error(`createContainerBridge: request to "${functionPath}" returned a non-JSON response (status ${String(response.status)})`);
28
- }
29
- };
30
- const createContainerBridge = (options) => {
31
- if (typeof options.baseUrl !== "string" || options.baseUrl.length === 0) {
32
- throw new TypeError("createContainerBridge: `baseUrl` must be a non-empty Worker URL (e.g. https://my-app.workers.dev) — is the URL env var set?");
33
- }
34
- const fetchImpl = options.fetch ?? globalThis.fetch;
35
- const call = async (functionPath, args = {}, shardKey) => {
36
- if (typeof fetchImpl !== "function") {
37
- throw new TypeError("createContainerBridge: no `fetch` available — pass `fetch` in options for this runtime.");
38
- }
39
- const headers = { "content-type": "application/json" };
40
- if (options.token !== void 0) {
41
- headers.authorization = `Bearer ${options.token}`;
42
- }
43
- const response = await fetchImpl(joinUrl(options.baseUrl, RPC_PATH), {
44
- body: JSON.stringify({ args, functionPath, shardKey }),
45
- headers,
46
- method: "POST"
47
- });
48
- const body = await parseResponseBody(response, functionPath);
49
- if (typeof body === "object" && body !== null && "error" in body) {
50
- const { error } = body;
51
- if (typeof error === "object" && error !== null) {
52
- const { code, message } = error;
53
- if (typeof code === "string" && typeof message === "string") {
54
- throw new ContainerBridgeError(code, message);
55
- }
56
- }
57
- let detail;
58
- try {
59
- detail = JSON.stringify(error);
60
- } catch {
61
- detail = String(error);
62
- }
63
- throw new Error(
64
- `createContainerBridge: request to "${functionPath}" returned a malformed error envelope (status ${String(response.status)}): ${detail}`
65
- );
66
- }
67
- if (!response.ok) {
68
- throw statusError(functionPath, response);
69
- }
70
- return body.result;
71
- };
72
- const run = async (reference, args, shardKey) => call(reference.__lunoraRef, args, shardKey);
73
- return { action: call, call, mutation: call, query: call, run };
74
- };
75
-
76
- export { ContainerBridgeError, createContainerBridge };
1
+ import{LunoraError as f}from"@lunora/errors";const g="/_lunora/rpc";class y extends f{constructor(r,e){super(r,e,{name:"ContainerBridgeError"})}}const w=(t,r)=>{let e=t;for(;e.endsWith("/");)e=e.slice(0,-1);return`${e}${r}`},d=(t,r)=>new Error(`createContainerBridge: request to "${t}" failed (status ${String(r.status)}${r.statusText?` ${r.statusText}`:""})`),m=async(t,r)=>{try{return await t.json()}catch{throw t.ok?new f("INTERNAL",`createContainerBridge: request to "${r}" returned a non-JSON response (status ${String(t.status)})`):d(r,t)}},b=t=>{if(typeof t.baseUrl!="string"||t.baseUrl.length===0)throw new TypeError("createContainerBridge: `baseUrl` must be a non-empty Worker URL (e.g. https://my-app.workers.dev) — is the URL env var set?");const r=t.fetch??globalThis.fetch,e=async(n,i={},c)=>{if(typeof r!="function")throw new TypeError("createContainerBridge: no `fetch` available — pass `fetch` in options for this runtime.");const l={"content-type":"application/json"};t.token!==void 0&&(l.authorization=`Bearer ${t.token}`);const s=await r(w(t.baseUrl,g),{body:JSON.stringify({args:i,functionPath:n,shardKey:c}),headers:l,method:"POST"}),o=await m(s,n);if(typeof o=="object"&&o!==null&&"error"in o){const{error:a}=o;if(typeof a=="object"&&a!==null){const{code:h,message:p}=a;if(typeof h=="string"&&typeof p=="string")throw new y(h,p)}let u;try{u=JSON.stringify(a)}catch{u=String(a)}throw new f("INTERNAL",`createContainerBridge: request to "${n}" returned a malformed error envelope (status ${String(s.status)}): ${u}`)}if(!s.ok)throw d(n,s);return o.result};return{action:e,call:e,mutation:e,query:e,run:async(n,i,c)=>e(n.__lunoraRef,i,c)}};export{y as ContainerBridgeError,b as createContainerBridge};