effect-cf 0.20.1 → 0.23.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +27 -3
  3. package/dist/{Hyperdrive-RTjgirMV.d.mts → Hyperdrive-COyg7R26.d.mts} +40 -13
  4. package/dist/HyperdrivePg.d.mts +13 -5
  5. package/dist/HyperdrivePg.mjs +12 -7
  6. package/dist/index.d.mts +1113 -922
  7. package/dist/index.mjs +980 -604
  8. package/package.json +10 -5
  9. package/src/AiGateway.ts +82 -47
  10. package/src/AnalyticsEngine.ts +74 -58
  11. package/src/Binding.ts +66 -13
  12. package/src/BrowserRendering.ts +30 -7
  13. package/src/Cache.ts +32 -8
  14. package/src/CloudflareOtlp.ts +32 -9
  15. package/src/ContainerNamespace.ts +251 -80
  16. package/src/D1.ts +13 -3
  17. package/src/DurableObject.ts +27 -164
  18. package/src/DurableObjectAlarm.ts +30 -9
  19. package/src/DurableObjectDefinition.ts +58 -54
  20. package/src/DurableObjectNamespace.ts +99 -96
  21. package/src/DurableObjectRpcWebSocket.ts +14 -6
  22. package/src/DurableObjectSqlite.ts +6 -3
  23. package/src/DurableObjectState.ts +63 -39
  24. package/src/DurableObjectStorage.ts +7 -1
  25. package/src/DurableObjectWebSocket.ts +51 -41
  26. package/src/Email.ts +40 -13
  27. package/src/Environment.ts +26 -6
  28. package/src/Hyperdrive.ts +2 -2
  29. package/src/HyperdrivePg.ts +25 -13
  30. package/src/Images.ts +77 -82
  31. package/src/Kv.ts +37 -27
  32. package/src/Queue.ts +6 -1
  33. package/src/QueueBinding.ts +18 -21
  34. package/src/QueueDefinition.ts +15 -14
  35. package/src/R2.ts +107 -29
  36. package/src/Rpc.ts +3 -1
  37. package/src/RpcDefinition.ts +177 -133
  38. package/src/ServiceBinding.ts +112 -108
  39. package/src/Vectorize.ts +59 -14
  40. package/src/Worker.ts +172 -192
  41. package/src/WorkerDefinition.ts +5 -10
  42. package/src/WorkersAi.ts +27 -17
  43. package/src/Workflow.ts +54 -49
  44. package/src/WorkflowBinding.ts +19 -11
  45. package/src/WorkflowDefinition.ts +24 -27
  46. package/src/index.ts +4 -3
  47. package/src/internal/Entrypoint.ts +3 -1
  48. package/src/internal/ErrorMessage.ts +24 -0
  49. package/src/internal/RpcInvocation.ts +11 -8
  50. package/src/internal/Runtime.ts +52 -0
  51. package/src/internal/WorkerContext.ts +39 -17
  52. package/src/Entry.ts +0 -259
  53. package/src/internal/Clock.ts +0 -37
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { Cause, Clock, Config, ConfigProvider, Context, Data, DateTime, Duration, Effect, Exit, Layer, ManagedRuntime, Option, Queue, Result, Schema } from "effect";
2
+ import { Cause, Clock, Config, ConfigProvider, Context, Data, DateTime, Duration, Effect, Exit, Function as Function$1, Layer, ManagedRuntime, Option, Predicate, Queue, Result, Schema } from "effect";
3
3
  import { FetchHttpClient, HttpClient, HttpClientRequest, HttpEffect, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
4
- import { OtlpLogger, OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
4
+ import { OtlpExporter, OtlpLogger, OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
5
5
  import { D1Client } from "@effect/sql-d1";
6
6
  import { DurableObject, RpcStub, RpcTarget, WorkerEntrypoint, WorkflowEntrypoint } from "cloudflare:workers";
7
7
  import * as RpcMessage from "effect/unstable/rpc/RpcMessage";
@@ -9,6 +9,10 @@ import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";
9
9
  import * as RpcServer from "effect/unstable/rpc/RpcServer";
10
10
  import { SqliteClient } from "@effect/sql-sqlite-do";
11
11
  //#region src/Environment.ts
12
+ var Environment_exports = /* @__PURE__ */ __exportAll({
13
+ WorkerConfig: () => WorkerConfig,
14
+ WorkerEnvironment: () => WorkerEnvironment
15
+ });
12
16
  /**
13
17
  * Context service for reading worker bindings from the current `env` object.
14
18
  */
@@ -20,7 +24,7 @@ let WorkerConfig;
20
24
  _WorkerConfig.number = (name) => Config.number(name);
21
25
  _WorkerConfig.integer = (name) => Config.int(name);
22
26
  _WorkerConfig.boolean = (name) => Config.boolean(name);
23
- const providerFromEnv = _WorkerConfig.providerFromEnv = (env) => ConfigProvider.fromUnknown(env);
27
+ const providerFromEnv = _WorkerConfig.providerFromEnv = (env, options) => ConfigProvider.fromUnknown(env, options);
24
28
  const providerWith = _WorkerConfig.providerWith = (makeProvider) => Effect.map(WorkerEnvironment, makeProvider);
25
29
  const provider = _WorkerConfig.provider = providerWith(providerFromEnv);
26
30
  _WorkerConfig.layer = _WorkerConfig.providerLayer = ConfigProvider.layer(provider);
@@ -33,10 +37,10 @@ var Binding_exports = /* @__PURE__ */ __exportAll({
33
37
  BindingValidationError: () => BindingValidationError,
34
38
  Service: () => Service$2,
35
39
  TypeId: () => TypeId$3,
36
- layer: () => layer$20
40
+ layer: () => layer$19
37
41
  });
38
42
  /** Internal type id marker used by binding helper services. */
39
- const TypeId$3 = "effect-cf/Binding";
43
+ const TypeId$3 = "~effect-cf/Binding";
40
44
  /** Error raised when a configured binding does not exist on `env`. */
41
45
  var BindingNotFoundError = class extends Data.TaggedError("BindingNotFoundError") {};
42
46
  /** Error raised when a binding exists but does not match the expected shape. */
@@ -118,34 +122,69 @@ const getBinding = (env, binding, isResource, options) => Effect.gen(function* (
118
122
  }
119
123
  return resource;
120
124
  });
121
- const layer$20 = (tag, binding, isResource, wrap, options) => Layer.effect(tag, Effect.gen(function* () {
125
+ /**
126
+ * The overloads on {@link layer} and {@link Service} guarantee that
127
+ * `Service = Resource` whenever `wrap` is absent, making the fallback cast
128
+ * safe.
129
+ */
130
+ const makeBindingLayer = (tag, binding, isResource, wrap, options) => Layer.effect(tag, Effect.gen(function* () {
122
131
  const env = yield* WorkerEnvironment;
123
132
  const resource = yield* getBinding(env, binding, isResource, options);
124
133
  return wrap === void 0 ? resource : wrap(resource);
125
134
  }));
126
- const Service$2 = () => (id, binding, isResource, wrap, options) => {
127
- const tag = Context.Service()(id);
128
- const serviceLayer = layer$20(tag, binding, isResource, wrap, options);
129
- return Object.assign(tag, {
130
- [TypeId$3]: TypeId$3,
131
- binding,
132
- layer: serviceLayer
133
- });
135
+ function layer$19(tag, binding, isResource, wrap, options) {
136
+ return makeBindingLayer(tag, binding, isResource, wrap, options);
137
+ }
138
+ const Service$2 = () => {
139
+ function makeService(id, binding, isResource, wrap, options) {
140
+ const tag = Context.Service()(`effect-cf/Binding/${id}`);
141
+ const serviceLayer = makeBindingLayer(tag, binding, isResource, wrap, options);
142
+ return Object.assign(tag, {
143
+ [TypeId$3]: TypeId$3,
144
+ id,
145
+ binding,
146
+ layer: serviceLayer
147
+ });
148
+ }
149
+ return makeService;
150
+ };
151
+ //#endregion
152
+ //#region src/internal/ErrorMessage.ts
153
+ /**
154
+ * Renders the most useful human-readable description of an unknown `cause`
155
+ * for use in tagged error `message` getters.
156
+ */
157
+ const causeMessage = (cause) => {
158
+ if (typeof cause === "object" && cause !== null) {
159
+ const message = Reflect.get(cause, "message");
160
+ if (typeof message === "string" && message.length > 0) return message;
161
+ }
162
+ try {
163
+ return String(cause);
164
+ } catch {
165
+ return "unknown cause";
166
+ }
134
167
  };
168
+ /** Renders a violation list as a single `path: message; ...` line. */
169
+ const violationsMessage = (violations) => violations.map((violation) => `${violation.path}: ${violation.message}`).join("; ");
135
170
  //#endregion
136
171
  //#region src/WorkersAi.ts
137
172
  var WorkersAi_exports = /* @__PURE__ */ __exportAll({
138
- Tag: () => Tag$18,
173
+ Tag: () => Tag$16,
139
174
  WorkersAiOperationError: () => WorkersAiOperationError,
140
175
  embeddingResponse: () => embeddingResponse,
141
176
  isWorkersAiBinding: () => isWorkersAiBinding,
142
- layer: () => layer$19,
177
+ layer: () => layer$18,
143
178
  make: () => make$18,
144
179
  makeClient: () => makeClient$15
145
180
  });
146
181
  const expectedWorkersAiBinding = "Workers AI binding with run(), gateway(), and models()";
147
182
  /** Error raised when a Workers AI operation fails. */
148
- var WorkersAiOperationError = class extends Data.TaggedError("WorkersAiOperationError") {};
183
+ var WorkersAiOperationError = class extends Data.TaggedError("WorkersAiOperationError") {
184
+ get message() {
185
+ return `Workers AI ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
186
+ }
187
+ };
149
188
  const workersAiError = (binding, operation, cause) => new WorkersAiOperationError({
150
189
  binding,
151
190
  operation,
@@ -166,22 +205,22 @@ const embeddingResponse = (value) => ({
166
205
  shape: value.shape ?? []
167
206
  });
168
207
  const makeClient$15 = (definition) => (ai) => {
169
- const run = ((model, input, options) => tryWorkersAiPromise(definition.binding, "run", () => ai.run(model, input, options)));
208
+ const run = Effect.fn("WorkersAi.run")((model, input, options) => tryWorkersAiPromise(definition.binding, "run", () => ai.run(model, input, options)));
170
209
  return {
171
210
  definition,
172
211
  aiGatewayLogId: tryWorkersAiSync(definition.binding, "aiGatewayLogId", () => ai.aiGatewayLogId),
173
212
  run,
174
- runEmbedding: (model, input, options) => run(model, input, options).pipe(Effect.map((response) => embeddingResponse(response))),
175
- models: (params) => tryWorkersAiPromise(definition.binding, "models", () => ai.models(params)),
213
+ runEmbedding: Effect.fn("WorkersAi.runEmbedding")((model, input, options) => run(model, input, options).pipe(Effect.map((response) => embeddingResponse(response)))),
214
+ models: Effect.fn("WorkersAi.models")((params) => tryWorkersAiPromise(definition.binding, "models", () => ai.models(params))),
176
215
  gateway: (gatewayId) => tryWorkersAiSync(definition.binding, "gateway", () => ai.gateway(gatewayId)),
177
- unsafeRaw: Effect.succeed(ai)
216
+ rawUnsafe: Effect.succeed(ai)
178
217
  };
179
218
  };
180
- const layer$19 = (tag, definition) => layer$20(tag, definition.binding, (value) => isWorkersAiBinding(value), makeClient$15(definition), { expected: expectedWorkersAiBinding });
181
- const make$18 = (id) => Tag$18()(id);
182
- const Tag$18 = () => (id) => {
219
+ const layer$18 = (tag, definition) => layer$19(tag, definition.binding, (value) => isWorkersAiBinding(value), makeClient$15(definition), { expected: expectedWorkersAiBinding });
220
+ const make$18 = (id) => Tag$16()(id);
221
+ const Tag$16 = () => (id) => {
183
222
  const tag = Context.Service()(id);
184
- const makeLayer = (definition) => layer$19(tag, definition);
223
+ const makeLayer = (definition) => layer$18(tag, definition);
185
224
  return Object.assign(tag, {
186
225
  id,
187
226
  layer: makeLayer
@@ -191,9 +230,9 @@ const Tag$18 = () => (id) => {
191
230
  //#region src/AiGateway.ts
192
231
  var AiGateway_exports = /* @__PURE__ */ __exportAll({
193
232
  AiGatewayOperationError: () => AiGatewayOperationError,
194
- Tag: () => Tag$17,
233
+ Tag: () => Tag$15,
195
234
  isAiGatewayBinding: () => isAiGatewayBinding,
196
- layer: () => layer$18,
235
+ layer: () => layer$17,
197
236
  make: () => make$17,
198
237
  makeClient: () => makeClient$14,
199
238
  makeClientFromAi: () => makeClientFromAi,
@@ -201,7 +240,11 @@ var AiGateway_exports = /* @__PURE__ */ __exportAll({
201
240
  });
202
241
  const expectedAiGatewayBinding = "Workers AI binding with gateway()";
203
242
  /** Error raised when an AI Gateway operation fails. */
204
- var AiGatewayOperationError = class extends Data.TaggedError("AiGatewayOperationError") {};
243
+ var AiGatewayOperationError = class extends Data.TaggedError("AiGatewayOperationError") {
244
+ get message() {
245
+ return `AI Gateway ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
246
+ }
247
+ };
205
248
  const aiGatewayError = (binding, operation, cause) => new AiGatewayOperationError({
206
249
  binding,
207
250
  operation,
@@ -211,6 +254,7 @@ const tryAiGatewayPromise = (binding, operation, evaluate) => Effect.tryPromise(
211
254
  try: evaluate,
212
255
  catch: (cause) => aiGatewayError(binding, operation, cause)
213
256
  });
257
+ const mergeAbortSignals = (userSignal, signal) => userSignal === null || userSignal === void 0 ? signal : AbortSignal.any([userSignal, signal]);
214
258
  const tryAiGatewaySync = (binding, operation, evaluate) => Effect.try({
215
259
  try: evaluate,
216
260
  catch: (cause) => aiGatewayError(binding, operation, cause)
@@ -224,15 +268,18 @@ const gatewayUrl = (definition) => `https://gateway.ai.cloudflare.com/v1/${defin
224
268
  const isAiGatewayBinding = (value) => isWorkersAiBinding(value);
225
269
  const makeClient$14 = (definition, gateway) => ({
226
270
  definition,
227
- run: (data, options) => tryAiGatewayPromise(definition.binding, "run", () => gateway.run(Array.isArray(data) ? [...data] : data, options)),
228
- getUrl: (provider) => tryAiGatewayPromise(definition.binding, "getUrl", () => gateway.getUrl(provider)),
229
- fetch: (options) => Effect.gen(function* () {
271
+ run: Effect.fn("AiGateway.run")((data, options) => tryAiGatewayPromise(definition.binding, "run", () => gateway.run(Array.isArray(data) ? [...data] : data, options))),
272
+ getUrl: Effect.fn("AiGateway.getUrl")((provider) => tryAiGatewayPromise(definition.binding, "getUrl", () => gateway.getUrl(provider))),
273
+ fetch: Effect.fn("AiGateway.fetch")(function* (options) {
230
274
  const baseUrl = yield* tryAiGatewayPromise(definition.binding, "getUrl", () => gateway.getUrl(options.provider));
231
- return yield* tryAiGatewayPromise(definition.binding, "fetch", () => fetch(providerUrl(baseUrl, options.path).href, options.init));
275
+ return yield* tryAiGatewayPromise(definition.binding, "fetch", (signal) => fetch(providerUrl(baseUrl, options.path).href, {
276
+ ...options.init,
277
+ signal: mergeAbortSignals(options.init?.signal, signal)
278
+ }));
232
279
  }),
233
- patchLog: (logId, data) => tryAiGatewayPromise(definition.binding, "patchLog", () => gateway.patchLog(logId, data)),
234
- getLog: (logId) => tryAiGatewayPromise(definition.binding, "getLog", () => gateway.getLog(logId)),
235
- unsafeRaw: Effect.succeed(gateway)
280
+ patchLog: Effect.fn("AiGateway.patchLog")((logId, data) => tryAiGatewayPromise(definition.binding, "patchLog", () => gateway.patchLog(logId, data))),
281
+ getLog: Effect.fn("AiGateway.getLog")((logId) => tryAiGatewayPromise(definition.binding, "getLog", () => gateway.getLog(logId))),
282
+ rawUnsafe: Effect.succeed(gateway)
236
283
  });
237
284
  const makeClientFromAi = (definition, ai) => {
238
285
  const gateway = tryAiGatewaySync(definition.binding, "gateway", () => ai.gateway(definition.gatewayId));
@@ -244,7 +291,7 @@ const makeClientFromAi = (definition, ai) => {
244
291
  fetch: (options) => withGateway((raw) => makeClient$14(definition, raw).fetch(options)),
245
292
  patchLog: (logId, data) => withGateway((raw) => makeClient$14(definition, raw).patchLog(logId, data)),
246
293
  getLog: (logId) => withGateway((raw) => makeClient$14(definition, raw).getLog(logId)),
247
- unsafeRaw: gateway
294
+ rawUnsafe: gateway
248
295
  };
249
296
  };
250
297
  const makeHttpClient = (definition, request = fetch) => {
@@ -261,33 +308,37 @@ const makeHttpClient = (definition, request = fetch) => {
261
308
  };
262
309
  return {
263
310
  definition: clientDefinition,
264
- run: (data, options) => tryAiGatewayPromise(binding, "run", () => request(gatewayUrl(definition), {
311
+ run: Effect.fn("AiGateway.run")((data, options) => tryAiGatewayPromise(binding, "run", (signal) => request(gatewayUrl(definition), {
265
312
  method: "POST",
266
313
  body: JSON.stringify(data),
267
314
  headers: new Headers({
268
315
  "content-type": "application/json",
269
316
  ...Object.fromEntries(new Headers(extraHeaders(options)).entries())
270
317
  }),
271
- signal: options?.signal
272
- })),
318
+ signal: mergeAbortSignals(options?.signal, signal)
319
+ }))),
273
320
  getUrl,
274
- fetch: (options) => getUrl(options.provider).pipe(Effect.flatMap((baseUrl) => tryAiGatewayPromise(binding, "fetch", () => request(providerUrl(baseUrl, options.path).href, options.init)))),
275
- patchLog: (logId, data) => tryAiGatewayPromise(binding, "patchLog", () => request(providerUrl(gatewayUrl(definition), `logs/${logId}`).href, {
321
+ fetch: Effect.fn("AiGateway.fetch")((options) => getUrl(options.provider).pipe(Effect.flatMap((baseUrl) => tryAiGatewayPromise(binding, "fetch", (signal) => request(providerUrl(baseUrl, options.path).href, {
322
+ ...options.init,
323
+ signal: mergeAbortSignals(options.init?.signal, signal)
324
+ }))))),
325
+ patchLog: Effect.fn("AiGateway.patchLog")((logId, data) => tryAiGatewayPromise(binding, "patchLog", (signal) => request(providerUrl(gatewayUrl(definition), `logs/${logId}`).href, {
276
326
  method: "PATCH",
277
327
  body: JSON.stringify(data),
278
- headers: { "content-type": "application/json" }
279
- }).then(() => void 0)),
280
- getLog: (logId) => tryAiGatewayPromise(binding, "getLog", async () => {
281
- return await (await request(providerUrl(gatewayUrl(definition), `logs/${logId}`).href)).json();
282
- }),
283
- unsafeRaw: Effect.fail(aiGatewayError(binding, "unsafeRaw", /* @__PURE__ */ new TypeError("HTTP AI Gateway clients have no raw binding")))
328
+ headers: { "content-type": "application/json" },
329
+ signal
330
+ }).then(() => void 0))),
331
+ getLog: Effect.fn("AiGateway.getLog")((logId) => tryAiGatewayPromise(binding, "getLog", async (signal) => {
332
+ return await (await request(providerUrl(gatewayUrl(definition), `logs/${logId}`).href, { signal })).json();
333
+ })),
334
+ rawUnsafe: Effect.fail(aiGatewayError(binding, "rawUnsafe", /* @__PURE__ */ new TypeError("HTTP AI Gateway clients have no raw binding")))
284
335
  };
285
336
  };
286
- const layer$18 = (tag, definition) => layer$20(tag, definition.binding, isAiGatewayBinding, (ai) => makeClientFromAi(definition, ai), { expected: expectedAiGatewayBinding });
287
- const make$17 = (id) => Tag$17()(id);
288
- const Tag$17 = () => (id) => {
337
+ const layer$17 = (tag, definition) => layer$19(tag, definition.binding, isAiGatewayBinding, (ai) => makeClientFromAi(definition, ai), { expected: expectedAiGatewayBinding });
338
+ const make$17 = (id) => Tag$15()(id);
339
+ const Tag$15 = () => (id) => {
289
340
  const tag = Context.Service()(id);
290
- const makeLayer = (definition) => layer$18(tag, definition);
341
+ const makeLayer = (definition) => layer$17(tag, definition);
291
342
  return Object.assign(tag, {
292
343
  id,
293
344
  layer: makeLayer
@@ -302,16 +353,16 @@ var AnalyticsEngine_exports = /* @__PURE__ */ __exportAll({
302
353
  AnalyticsEngineQueryError: () => AnalyticsEngineQueryError,
303
354
  AnalyticsEngineWriteValidationError: () => AnalyticsEngineWriteValidationError,
304
355
  QueryTag: () => QueryTag,
305
- Tag: () => Tag$16,
356
+ Tag: () => Tag$14,
306
357
  isAnalyticsEngineDataset: () => isAnalyticsEngineDataset,
307
- layer: () => layer$17,
358
+ layer: () => layer$16,
359
+ layerFetch: () => layerFetch,
360
+ layerFetchConfig: () => layerFetchConfig,
308
361
  make: () => make$16,
309
362
  makeClient: () => makeClient$13,
310
363
  makeQuery: () => makeQuery,
311
364
  makeQueryClient: () => makeQueryClient,
312
365
  queryConfig: () => queryConfig,
313
- queryFetchLayer: () => queryFetchLayer,
314
- queryFetchLayerConfig: () => queryFetchLayerConfig,
315
366
  queryLayer: () => queryLayer,
316
367
  queryLayerConfig: () => queryLayerConfig,
317
368
  writeLimits: () => writeLimits
@@ -346,9 +397,17 @@ const AnalyticsEngineDataPointSchema = Schema.Struct({
346
397
  const decodeQueryResponse = Schema.decodeUnknownEffect(queryResponseSchema);
347
398
  const decodeDataPoint = Schema.decodeUnknownEffect(AnalyticsEngineDataPointSchema);
348
399
  /** Error raised when an Analytics Engine operation fails. */
349
- var AnalyticsEngineOperationError = class extends Data.TaggedError("AnalyticsEngineOperationError") {};
400
+ var AnalyticsEngineOperationError = class extends Data.TaggedError("AnalyticsEngineOperationError") {
401
+ get message() {
402
+ return `Analytics Engine ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
403
+ }
404
+ };
350
405
  /** Error raised when an Analytics Engine write input violates Cloudflare limits. */
351
- var AnalyticsEngineWriteValidationError = class extends Data.TaggedError("AnalyticsEngineWriteValidationError") {};
406
+ var AnalyticsEngineWriteValidationError = class extends Data.TaggedError("AnalyticsEngineWriteValidationError") {
407
+ get message() {
408
+ return `Analytics Engine ${this.operation} for binding "${this.binding}" failed validation: ${violationsMessage(this.violations)}`;
409
+ }
410
+ };
352
411
  /** Error raised when an Analytics Engine SQL API query fails. */
353
412
  var AnalyticsEngineQueryError = class extends Data.TaggedError("AnalyticsEngineQueryError") {};
354
413
  const analyticsEngineError = (binding, operation, cause) => new AnalyticsEngineOperationError({
@@ -470,8 +529,8 @@ const executeQueryRequest = (definition, httpClient, sql, options) => Effect.gen
470
529
  return response;
471
530
  });
472
531
  const makeQueryClientWith = (definition, httpClient) => {
473
- const raw = (sql, options) => executeQueryRequest(definition, httpClient, sql, options);
474
- const query = (sql, options) => Effect.gen(function* () {
532
+ const raw = Effect.fn("AnalyticsEngine.raw")((sql, options) => executeQueryRequest(definition, httpClient, sql, options));
533
+ const query = Effect.fn("AnalyticsEngine.query")(function* (sql, options) {
475
534
  const json = yield* (yield* raw(sql, options)).json.pipe(Effect.catch((cause) => Effect.fail(analyticsEngineQueryError(definition, "json", "Failed to read Analytics Engine SQL API JSON response body", { cause }))));
476
535
  return yield* decodeQueryResponse(json);
477
536
  });
@@ -485,15 +544,15 @@ const makeQueryClientWith = (definition, httpClient) => {
485
544
  data,
486
545
  rows: result.rows
487
546
  };
488
- });
547
+ }).pipe(Effect.withSpan("AnalyticsEngine.queryResult"));
489
548
  return {
490
549
  definition,
491
550
  raw,
492
551
  query,
493
552
  queryResult,
494
- queryRows: (row, sql, options) => queryResult(row, sql, options).pipe(Effect.map((result) => result.data)),
495
- queryOne: (row, sql, options) => queryResult(row, sql, options).pipe(Effect.map((result) => result.data[0] === void 0 ? Option.none() : Option.some(result.data[0]))),
496
- queryText: (sql, options) => raw(sql, options).pipe(Effect.flatMap((response) => responseText(definition, response, "text")))
553
+ queryRows: (row, sql, options) => queryResult(row, sql, options).pipe(Effect.map((result) => result.data), Effect.withSpan("AnalyticsEngine.queryRows")),
554
+ queryOne: (row, sql, options) => queryResult(row, sql, options).pipe(Effect.map((result) => result.data[0] === void 0 ? Option.none() : Option.some(result.data[0])), Effect.withSpan("AnalyticsEngine.queryOne")),
555
+ queryText: Effect.fn("AnalyticsEngine.queryText")((sql, options) => raw(sql, options).pipe(Effect.flatMap((response) => responseText(definition, response, "text"))))
497
556
  };
498
557
  };
499
558
  const makeQueryClient = (definition) => Effect.map(HttpClient.HttpClient, (httpClient) => makeQueryClientWith(definition, httpClient));
@@ -502,27 +561,25 @@ const isAnalyticsEngineDataset = (value) => {
502
561
  return typeof Reflect.get(value, "writeDataPoint") === "function";
503
562
  };
504
563
  const makeClient$13 = (definition, defaults) => (dataset) => {
505
- const writeDataPoint = (dataPoint, options) => {
564
+ const writeDataPoint = Effect.fn("AnalyticsEngine.writeDataPoint")((dataPoint, options) => {
506
565
  const policy = resolveWritePolicy(defaults, options);
507
566
  return validateOptionalDataPoint(definition.binding, "writeDataPoint", dataPoint).pipe(Effect.matchEffect({
508
567
  onFailure: (error) => policy.onInvalid === "drop" ? Effect.succeed(void 0) : Effect.fail(error),
509
568
  onSuccess: (point) => tryAnalyticsEngineSync(definition.binding, "writeDataPoint", () => dataset.writeDataPoint(point))
510
569
  }));
511
- };
512
- const writeDataPoints = (dataPoints, options) => {
570
+ });
571
+ const writeDataPoints = Effect.fn("AnalyticsEngine.writeDataPoints")(function* (dataPoints, options) {
513
572
  const policy = resolveWritePolicy(defaults, options);
514
- return Effect.gen(function* () {
515
- const validPoints = yield* validateDataPoints(definition.binding, "writeDataPoints", dataPoints, policy);
516
- yield* writeChunks(definition.binding, "writeDataPoints", dataset, validPoints, policy.batchSize);
517
- });
518
- };
573
+ const validPoints = yield* validateDataPoints(definition.binding, "writeDataPoints", dataPoints, policy);
574
+ yield* writeChunks(definition.binding, "writeDataPoints", dataset, validPoints, policy.batchSize);
575
+ });
519
576
  return {
520
577
  definition,
521
578
  writeDataPoint,
522
579
  write: writeDataPoint,
523
580
  writeDataPoints,
524
581
  writeBatch: writeDataPoints,
525
- unsafeRaw: Effect.succeed(dataset)
582
+ rawUnsafe: Effect.succeed(dataset)
526
583
  };
527
584
  };
528
585
  const queryConfig = (options) => Config.all({
@@ -531,18 +588,18 @@ const queryConfig = (options) => Config.all({
531
588
  apiBaseUrl: options?.apiBaseUrl ?? Config.string("CLOUDFLARE_API_BASE_URL").pipe(Config.withDefault(defaultQueryApiBaseUrl))
532
589
  });
533
590
  const queryLayer = (tag, definition) => Layer.effect(tag, makeQueryClient(definition));
534
- const queryFetchLayer = (tag, definition) => queryLayer(tag, definition).pipe(Layer.provide(FetchHttpClient.layer));
591
+ const layerFetch = (tag, definition) => queryLayer(tag, definition).pipe(Layer.provide(FetchHttpClient.layer));
535
592
  const queryLayerConfig = (tag, config = queryConfig()) => Layer.effect(tag, Effect.gen(function* () {
536
593
  const definition = yield* config;
537
594
  return yield* makeQueryClient(definition);
538
595
  }));
539
- const queryFetchLayerConfig = (tag, config = queryConfig()) => queryLayerConfig(tag, config).pipe(Layer.provide(FetchHttpClient.layer));
540
- const layer$17 = (tag, definition) => layer$20(tag, definition.binding, isAnalyticsEngineDataset, makeClient$13(definition, definition.write), { expected: expectedAnalyticsEngineDataset });
541
- const make$16 = (id) => Tag$16()(id);
596
+ const layerFetchConfig = (tag, config = queryConfig()) => queryLayerConfig(tag, config).pipe(Layer.provide(FetchHttpClient.layer));
597
+ const layer$16 = (tag, definition) => layer$19(tag, definition.binding, isAnalyticsEngineDataset, makeClient$13(definition, definition.write), { expected: expectedAnalyticsEngineDataset });
598
+ const make$16 = (id) => Tag$14()(id);
542
599
  const makeQuery = (id) => QueryTag()(id);
543
- const Tag$16 = () => (id) => {
600
+ const Tag$14 = () => (id) => {
544
601
  const tag = Context.Service()(id);
545
- const makeLayer = (definition) => layer$17(tag, definition);
602
+ const makeLayer = (definition) => layer$16(tag, definition);
546
603
  return Object.assign(tag, {
547
604
  id,
548
605
  layer: makeLayer
@@ -551,30 +608,34 @@ const Tag$16 = () => (id) => {
551
608
  const QueryTag = () => (id) => {
552
609
  const tag = Context.Service()(id);
553
610
  const makeLayer = (definition) => queryLayer(tag, definition);
554
- const makeFetchLayer = (definition) => queryFetchLayer(tag, definition);
611
+ const makeLayerFetch = (definition) => layerFetch(tag, definition);
555
612
  const makeLayerConfig = (config) => queryLayerConfig(tag, config);
556
- const makeFetchLayerConfig = (config) => queryFetchLayerConfig(tag, config);
613
+ const makeLayerFetchConfig = (config) => layerFetchConfig(tag, config);
557
614
  return Object.assign(tag, {
558
615
  id,
559
616
  layer: makeLayer,
560
- fetchLayer: makeFetchLayer,
617
+ layerFetch: makeLayerFetch,
561
618
  layerConfig: makeLayerConfig,
562
- fetchLayerConfig: makeFetchLayerConfig
619
+ layerFetchConfig: makeLayerFetchConfig
563
620
  });
564
621
  };
565
622
  //#endregion
566
623
  //#region src/BrowserRendering.ts
567
624
  var BrowserRendering_exports = /* @__PURE__ */ __exportAll({
568
625
  BrowserRenderingOperationError: () => BrowserRenderingOperationError,
569
- Tag: () => Tag$15,
626
+ Tag: () => Tag$13,
570
627
  isBrowserRenderingBinding: () => isBrowserRenderingBinding,
571
- layer: () => layer$16,
628
+ layer: () => layer$15,
572
629
  make: () => make$15,
573
630
  makeClient: () => makeClient$12
574
631
  });
575
632
  const expectedBrowserRenderingBinding = "Browser Rendering binding resource";
576
633
  /** Error raised when a Browser Rendering operation fails. */
577
- var BrowserRenderingOperationError = class extends Data.TaggedError("BrowserRenderingOperationError") {};
634
+ var BrowserRenderingOperationError = class extends Data.TaggedError("BrowserRenderingOperationError") {
635
+ get message() {
636
+ return `Browser Rendering ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
637
+ }
638
+ };
578
639
  const browserRenderingError = (binding, operation, cause) => new BrowserRenderingOperationError({
579
640
  binding,
580
641
  operation,
@@ -609,15 +670,15 @@ const wrapBrowser = (binding, browser) => ({
609
670
  const isBrowserRenderingBinding = (value) => (typeof value === "object" || typeof value === "function") && value !== null;
610
671
  const makeClient$12 = (definition) => (binding) => ({
611
672
  definition,
612
- launchWith: (launch, options) => tryBrowserRenderingPromise(definition.binding, "launch", () => launch(binding, options)).pipe(Effect.map((browser) => wrapBrowser(definition.binding, browser))),
613
- connectWith: (connect, options) => tryBrowserRenderingPromise(definition.binding, "connect", () => connect(binding, options)).pipe(Effect.map((browser) => wrapBrowser(definition.binding, browser))),
614
- unsafeRaw: Effect.succeed(binding)
673
+ launchWith: (launch, options) => tryBrowserRenderingPromise(definition.binding, "launch", () => launch(binding, options)).pipe(Effect.map((browser) => wrapBrowser(definition.binding, browser)), Effect.withSpan("BrowserRendering.launchWith")),
674
+ connectWith: (connect, options) => tryBrowserRenderingPromise(definition.binding, "connect", () => connect(binding, options)).pipe(Effect.map((browser) => wrapBrowser(definition.binding, browser)), Effect.withSpan("BrowserRendering.connectWith")),
675
+ rawUnsafe: Effect.succeed(binding)
615
676
  });
616
- const layer$16 = (tag, definition) => layer$20(tag, definition.binding, isBrowserRenderingBinding, makeClient$12(definition), { expected: expectedBrowserRenderingBinding });
617
- const make$15 = (id) => Tag$15()(id);
618
- const Tag$15 = () => (id) => {
677
+ const layer$15 = (tag, definition) => layer$19(tag, definition.binding, isBrowserRenderingBinding, makeClient$12(definition), { expected: expectedBrowserRenderingBinding });
678
+ const make$15 = (id) => Tag$13()(id);
679
+ const Tag$13 = () => (id) => {
619
680
  const tag = Context.Service()(id);
620
- const makeLayer = (definition) => layer$16(tag, definition);
681
+ const makeLayer = (definition) => layer$15(tag, definition);
621
682
  return Object.assign(tag, {
622
683
  id,
623
684
  layer: makeLayer
@@ -628,13 +689,17 @@ const Tag$15 = () => (id) => {
628
689
  var Cache_exports = /* @__PURE__ */ __exportAll({
629
690
  CacheOperationError: () => CacheOperationError,
630
691
  CacheStorage: () => CacheStorage,
631
- layer: () => layer$15,
692
+ layer: () => layer$14,
632
693
  layerFrom: () => layerFrom,
633
694
  makeCacheClient: () => makeCacheClient,
634
695
  makeClient: () => makeClient$11
635
696
  });
636
697
  /** Error raised when a Cloudflare Cache API operation fails. */
637
- var CacheOperationError = class extends Data.TaggedError("CacheOperationError") {};
698
+ var CacheOperationError = class extends Data.TaggedError("CacheOperationError") {
699
+ get message() {
700
+ return `Cache ${this.operation} failed for cache "${this.cache}": ${causeMessage(this.cause)}`;
701
+ }
702
+ };
638
703
  /** Service for Cloudflare's global Cache API. */
639
704
  var CacheStorage = class extends Context.Service()("effect-cf/CacheStorage") {};
640
705
  const cacheError = (cache, operation, cause) => new CacheOperationError({
@@ -646,24 +711,28 @@ const tryCachePromise = (cache, operation, evaluate) => Effect.tryPromise({
646
711
  try: evaluate,
647
712
  catch: (cause) => cacheError(cache, operation, cause)
648
713
  });
714
+ const spanOptions$2 = (cache, operation) => ({ attributes: {
715
+ cache,
716
+ operation
717
+ } });
649
718
  /** Wraps a native Cloudflare `Cache` instance. */
650
719
  const makeCacheClient = (cache, name = "default") => ({
651
720
  name,
652
- match: (request, options) => tryCachePromise(name, "match", () => cache.match(request, options)).pipe(Effect.map(Option.fromUndefinedOr)),
653
- put: (request, response) => tryCachePromise(name, "put", () => cache.put(request, response)),
654
- delete: (request, options) => tryCachePromise(name, "delete", () => cache.delete(request, options)),
655
- unsafeRaw: Effect.succeed(cache)
721
+ match: Effect.fn("Cache.match", spanOptions$2(name, "match"))((request, options) => tryCachePromise(name, "match", () => cache.match(request, options)).pipe(Effect.map(Option.fromUndefinedOr))),
722
+ put: Effect.fn("Cache.put", spanOptions$2(name, "put"))((request, response) => tryCachePromise(name, "put", () => cache.put(request, response))),
723
+ delete: Effect.fn("Cache.delete", spanOptions$2(name, "delete"))((request, options) => tryCachePromise(name, "delete", () => cache.delete(request, options))),
724
+ rawUnsafe: Effect.succeed(cache)
656
725
  });
657
726
  /** Wraps a native Cloudflare `CacheStorage` instance. */
658
727
  const makeClient$11 = (storage) => ({
659
728
  default: makeCacheClient(storage.default),
660
- open: (name) => tryCachePromise(name, "open", () => storage.open(name)).pipe(Effect.map((cache) => makeCacheClient(cache, name))),
661
- unsafeRaw: Effect.succeed(storage)
729
+ open: (name) => tryCachePromise(name, "open", () => storage.open(name)).pipe(Effect.map((cache) => makeCacheClient(cache, name)), Effect.withSpan("Cache.open", spanOptions$2(name, "open"))),
730
+ rawUnsafe: Effect.succeed(storage)
662
731
  });
663
732
  /** Provides Cache API services from an explicit native `CacheStorage` instance. */
664
733
  const layerFrom = (storage) => Layer.succeed(CacheStorage, makeClient$11(storage));
665
734
  /** Provides Cache API services from Cloudflare's global `caches` object. */
666
- const layer$15 = Layer.sync(CacheStorage, () => makeClient$11(caches));
735
+ const layer$14 = Layer.sync(CacheStorage, () => makeClient$11(caches));
667
736
  //#endregion
668
737
  //#region src/DurableObjectStorage.ts
669
738
  var DurableObjectStorage_exports = /* @__PURE__ */ __exportAll({
@@ -671,7 +740,11 @@ var DurableObjectStorage_exports = /* @__PURE__ */ __exportAll({
671
740
  fromDurableObjectStorage: () => fromDurableObjectStorage
672
741
  });
673
742
  /** Error type used when a storage operation throws or rejects. */
674
- var StorageOperationError = class extends Data.TaggedError("StorageOperationError") {};
743
+ var StorageOperationError = class extends Data.TaggedError("StorageOperationError") {
744
+ get message() {
745
+ return `Durable Object storage ${this.operation} failed: ${causeMessage(this.cause)}`;
746
+ }
747
+ };
675
748
  const storageError = (operation, cause) => new StorageOperationError({
676
749
  operation,
677
750
  cause
@@ -798,11 +871,23 @@ var DurableObjectWebSocket_exports = /* @__PURE__ */ __exportAll({
798
871
  handlers: () => handlers
799
872
  });
800
873
  /** Error raised when sending on a Durable Object websocket fails. */
801
- var DurableWebSocketSendError = class extends Data.TaggedError("DurableWebSocketSendError") {};
874
+ var DurableWebSocketSendError = class extends Data.TaggedError("DurableWebSocketSendError") {
875
+ get message() {
876
+ return `Durable Object websocket send failed: ${causeMessage(this.cause)}`;
877
+ }
878
+ };
802
879
  /** Error raised when closing a Durable Object websocket fails. */
803
- var DurableWebSocketCloseError = class extends Data.TaggedError("DurableWebSocketCloseError") {};
880
+ var DurableWebSocketCloseError = class extends Data.TaggedError("DurableWebSocketCloseError") {
881
+ get message() {
882
+ return `Durable Object websocket close failed: ${causeMessage(this.cause)}`;
883
+ }
884
+ };
804
885
  /** Error raised when serializing or deserializing a websocket attachment fails. */
805
- var DurableWebSocketAttachmentError = class extends Data.TaggedError("DurableWebSocketAttachmentError") {};
886
+ var DurableWebSocketAttachmentError = class extends Data.TaggedError("DurableWebSocketAttachmentError") {
887
+ get message() {
888
+ return `Durable Object websocket attachment ${this.operation} failed: ${causeMessage(this.cause)}`;
889
+ }
890
+ };
806
891
  const wrappers = /* @__PURE__ */ new WeakMap();
807
892
  /** Wraps a native Cloudflare websocket in the Effect-native Durable Object API. */
808
893
  const fromWebSocket = (raw) => {
@@ -848,12 +933,12 @@ const fromWebSocket = (raw) => {
848
933
  * return response.response;
849
934
  * ```
850
935
  */
851
- const acceptUpgrade = (options = {}) => Effect.gen(function* () {
936
+ const acceptUpgrade = Effect.fn("DurableObjectWebSocket.acceptUpgrade")(function* (options = {}) {
852
937
  const state = yield* DurableObjectState;
853
938
  const pair = new WebSocketPair();
854
939
  const client = pair[0];
855
940
  const server = fromWebSocket(pair[1]);
856
- if (options.attachment !== void 0) server.raw.serializeAttachment(options.attachment);
941
+ if (options.attachment !== void 0) yield* server.serializeAttachment(options.attachment);
857
942
  yield* state.acceptWebSocket(server, options.tags === void 0 ? void 0 : [...options.tags]);
858
943
  return {
859
944
  client,
@@ -883,25 +968,16 @@ const attachment = (schema) => {
883
968
  const restored = [];
884
969
  const onInvalid = options.onInvalid ?? "ignore";
885
970
  for (const socket of sockets) {
886
- const decoded = yield* deserialize(socket).pipe(Effect.match({
887
- onFailure: (error) => ({
888
- _tag: "Failure",
889
- error
890
- }),
891
- onSuccess: (value) => ({
892
- _tag: "Success",
893
- value
894
- })
895
- }));
896
- if (decoded._tag === "Success" && Option.isSome(decoded.value)) {
971
+ const decoded = yield* Effect.result(deserialize(socket));
972
+ if (Result.isSuccess(decoded) && Option.isSome(decoded.success)) {
897
973
  restored.push({
898
974
  socket,
899
- attachment: decoded.value.value
975
+ attachment: decoded.success.value
900
976
  });
901
977
  continue;
902
978
  }
903
- if (decoded._tag === "Failure" && onInvalid === "fail") return yield* Effect.fail(decoded.error);
904
- if (decoded._tag === "Failure" && onInvalid === "ignore-and-close") yield* socket.close(1008, "invalid websocket attachment").pipe(Effect.ignore);
979
+ if (Result.isFailure(decoded) && onInvalid === "fail") return yield* Effect.fail(decoded.failure);
980
+ if (Result.isFailure(decoded) && onInvalid === "ignore-and-close") yield* socket.close(1008, "invalid websocket attachment").pipe(Effect.ignore);
905
981
  }
906
982
  return restored;
907
983
  });
@@ -919,6 +995,45 @@ const handlers = (options) => ({
919
995
  webSocketError: options.error
920
996
  });
921
997
  //#endregion
998
+ //#region src/internal/WorkerContext.ts
999
+ const causeError = (cause) => {
1000
+ const squashed = Cause.squash(cause);
1001
+ return squashed instanceof Error ? squashed : new Error(Cause.pretty(cause), { cause: squashed });
1002
+ };
1003
+ const failureHandler = (label, cause, options) => (options?.onFailure?.(cause) ?? Effect.logError(`${label} failed`, Cause.pretty(cause))).pipe(Effect.catchCause((handlerCause) => Effect.logError(`${label} failure handler failed`, Cause.pretty(cause), Cause.pretty(handlerCause))));
1004
+ /**
1005
+ * Builds a `waitUntil` scheduler for any Cloudflare lifecycle that accepts
1006
+ * background promises (`ExecutionContext`, `DurableObjectState`).
1007
+ *
1008
+ * Background effects capture the calling fiber's context via `Effect.context`
1009
+ * before being registered, so the default module-level `Effect.runPromiseExit`
1010
+ * runner is sufficient; entrypoints may still pass a runtime-bound runner.
1011
+ */
1012
+ const makeWaitUntilScheduler = (label, register, runPromiseExit = (effect) => Effect.runPromiseExit(effect)) => {
1013
+ return (effect, options, mode) => Effect.context().pipe(Effect.flatMap((context) => Effect.sync(() => {
1014
+ const runHandler = (cause) => runPromiseExit(Effect.scoped(Effect.provideContext(failureHandler(label, cause, options), context))).then((exit) => {
1015
+ if (Exit.isFailure(exit)) console.error(`${label} failure handler failed`, Cause.pretty(exit.cause));
1016
+ });
1017
+ register(runPromiseExit(Effect.scoped(Effect.provideContext(effect, context))).then(async (exit) => {
1018
+ if (Exit.isSuccess(exit)) return;
1019
+ await runHandler(exit.cause);
1020
+ if (mode === "propagate") throw causeError(exit.cause);
1021
+ }));
1022
+ })));
1023
+ };
1024
+ /**
1025
+ * Builds the `WorkerContext` service from a native `ExecutionContext`.
1026
+ */
1027
+ const fromExecutionContext = (ctx, runPromiseExit = (effect) => Effect.runPromiseExit(effect)) => {
1028
+ const schedule = makeWaitUntilScheduler("WorkerContext.waitUntil", (promise) => ctx.waitUntil(promise), runPromiseExit);
1029
+ return {
1030
+ raw: ctx,
1031
+ waitUntil: (effect, options) => schedule(effect, options, options?.mode ?? "observe"),
1032
+ waitUntilPropagating: (effect, options) => schedule(effect, options, "propagate"),
1033
+ passThroughOnException: Effect.sync(() => ctx.passThroughOnException())
1034
+ };
1035
+ };
1036
+ //#endregion
922
1037
  //#region src/DurableObjectState.ts
923
1038
  var DurableObjectState_exports = /* @__PURE__ */ __exportAll({
924
1039
  DurableObjectState: () => DurableObjectState,
@@ -931,36 +1046,54 @@ var DurableObjectState = class extends Context.Service()("effect-cf/DurableObjec
931
1046
  /**
932
1047
  * Wraps a native Cloudflare `DurableObjectState` as a {@link DurableObjectStateService}.
933
1048
  */
934
- const fromDurableObjectState = (state) => ({
935
- raw: state,
936
- id: state.id,
937
- storage: fromDurableObjectStorage(state.storage),
938
- waitUntil: (promise) => Effect.sync(() => state.waitUntil(promise)),
939
- blockConcurrencyWhile: (effect) => Effect.context().pipe(Effect.flatMap((context) => Effect.promise(() => state.blockConcurrencyWhile(() => runPromiseExitPreservingTypedFailures(Effect.provideContext(effect, context))))), Effect.flatten),
940
- blockConcurrencyWhileOrReset: (effect) => Effect.context().pipe(Effect.flatMap((context) => Effect.promise(() => state.blockConcurrencyWhile(() => Effect.runPromise(Effect.provideContext(effect, context)))))),
941
- acceptWebSocket: (ws, tags) => Effect.sync(() => state.acceptWebSocket(ws.raw, tags)),
942
- getWebSockets: (tag) => Effect.sync(() => state.getWebSockets(tag).map((socket) => fromWebSocket(socket))),
943
- setWebSocketAutoResponse: (pair) => Effect.sync(() => state.setWebSocketAutoResponse(pair)),
944
- getWebSocketAutoResponse: Effect.sync(() => state.getWebSocketAutoResponse()),
945
- getWebSocketAutoResponseTimestamp: (ws) => Effect.sync(() => state.getWebSocketAutoResponseTimestamp(ws.raw)),
946
- setHibernatableWebSocketEventTimeout: (timeoutMs) => Effect.sync(() => state.setHibernatableWebSocketEventTimeout(timeoutMs)),
947
- getHibernatableWebSocketEventTimeout: Effect.sync(() => state.getHibernatableWebSocketEventTimeout()),
948
- getTags: (ws) => Effect.sync(() => state.getTags(ws.raw)),
949
- abort: (reason) => Effect.sync(() => state.abort(reason))
950
- });
951
- const runPromiseExitPreservingTypedFailures = async (effect) => {
952
- const exit = await Effect.runPromiseExit(effect);
1049
+ const fromDurableObjectState = (state) => {
1050
+ const scheduleWaitUntil = makeWaitUntilScheduler("DurableObjectState.waitUntil", (promise) => state.waitUntil(promise));
1051
+ const waitUntil = ((input, options) => Effect.isEffect(input) ? scheduleWaitUntil(input, options, options?.mode ?? "observe") : Effect.sync(() => state.waitUntil(input)));
1052
+ return {
1053
+ raw: state,
1054
+ id: state.id,
1055
+ storage: fromDurableObjectStorage(state.storage),
1056
+ waitUntil,
1057
+ blockConcurrencyWhile: (effect) => Effect.context().pipe(Effect.flatMap((context) => Effect.promise(() => state.blockConcurrencyWhile(() => runPromiseExitPreservingTypedFailures(context, effect)))), Effect.flatten),
1058
+ blockConcurrencyWhileOrReset: (effect) => Effect.context().pipe(Effect.flatMap((context) => Effect.promise(() => state.blockConcurrencyWhile(() => Effect.runPromiseWith(context)(effect))))),
1059
+ acceptWebSocket: (ws, tags) => Effect.sync(() => state.acceptWebSocket(ws.raw, tags)),
1060
+ getWebSockets: (tag) => Effect.sync(() => state.getWebSockets(tag).map((socket) => fromWebSocket(socket))),
1061
+ setWebSocketAutoResponse: (pair) => Effect.sync(() => state.setWebSocketAutoResponse(pair)),
1062
+ getWebSocketAutoResponse: Effect.sync(() => state.getWebSocketAutoResponse()),
1063
+ getWebSocketAutoResponseTimestamp: (ws) => Effect.sync(() => state.getWebSocketAutoResponseTimestamp(ws.raw)),
1064
+ setHibernatableWebSocketEventTimeout: (timeoutMs) => Effect.sync(() => state.setHibernatableWebSocketEventTimeout(timeoutMs)),
1065
+ getHibernatableWebSocketEventTimeout: Effect.sync(() => state.getHibernatableWebSocketEventTimeout()),
1066
+ getTags: (ws) => Effect.sync(() => state.getTags(ws.raw)),
1067
+ abort: (reason) => Effect.sync(() => state.abort(reason))
1068
+ };
1069
+ };
1070
+ const runPromiseExitPreservingTypedFailures = async (context, effect) => {
1071
+ const exit = await Effect.runPromiseExitWith(context)(effect);
953
1072
  if (Exit.isFailure(exit) && (Cause.hasDies(exit.cause) || Cause.hasInterrupts(exit.cause))) throw Cause.squash(exit.cause);
954
1073
  return exit;
955
1074
  };
956
1075
  //#endregion
957
1076
  //#region src/CloudflareOtlp.ts
1077
+ /**
1078
+ * OTLP telemetry layers for Cloudflare Workers and Durable Objects.
1079
+ *
1080
+ * Every layer exposes {@link OtlpExporter.Flusher}, which drains buffered
1081
+ * telemetry on demand. Cloudflare isolates can freeze before the periodic
1082
+ * export interval fires, so flush explicitly before returning a response, or
1083
+ * hand the flush to `ctx.waitUntil`:
1084
+ *
1085
+ * ```ts
1086
+ * const flusher = yield* OtlpExporter.Flusher;
1087
+ *
1088
+ * yield* flusher.flush;
1089
+ * ```
1090
+ */
958
1091
  var CloudflareOtlp_exports = /* @__PURE__ */ __exportAll({
959
- durableObjectLayer: () => durableObjectLayer,
960
- layer: () => layer$14,
1092
+ layer: () => layer$13,
1093
+ layerDurableObject: () => layerDurableObject,
961
1094
  layerJson: () => layerJson,
962
1095
  layerProtobuf: () => layerProtobuf,
963
- workerLayer: () => workerLayer
1096
+ layerWorker: () => layerWorker
964
1097
  });
965
1098
  const allSignals = [
966
1099
  "logs",
@@ -1009,7 +1142,7 @@ const makeLayer = (options = {}, runtimeAttributes = {}) => {
1009
1142
  resource,
1010
1143
  headers: options.headers
1011
1144
  }));
1012
- if (layers.length === 0) return Layer.empty;
1145
+ if (layers.length === 0) return OtlpExporter.layerFlusher;
1013
1146
  return mergeSignalLayers(layers).pipe(Layer.provide(cloudflareConfigProviderLayer), Layer.provide(serializationLayer(options.serialization)), Layer.provide(FetchHttpClient.layer));
1014
1147
  };
1015
1148
  /**
@@ -1019,15 +1152,18 @@ const makeLayer = (options = {}, runtimeAttributes = {}) => {
1019
1152
  * layers. In Cloudflare Workers and Durable Objects, the current `env` object is
1020
1153
  * installed as the primary `ConfigProvider`; outside Cloudflare, the ambient
1021
1154
  * Effect `ConfigProvider` remains the fallback.
1155
+ *
1156
+ * The layer provides {@link OtlpExporter.Flusher} for draining buffered
1157
+ * telemetry before the isolate freezes.
1022
1158
  */
1023
- const layer$14 = (options = {}) => makeLayer(options);
1159
+ const layer$13 = (options = {}) => makeLayer(options);
1024
1160
  /** Base OTLP telemetry layer forced to JSON serialization. */
1025
- const layerJson = (options = {}) => layer$14({
1161
+ const layerJson = (options = {}) => layer$13({
1026
1162
  ...options,
1027
1163
  serialization: "json"
1028
1164
  });
1029
1165
  /** Base OTLP telemetry layer forced to protobuf serialization. */
1030
- const layerProtobuf = (options = {}) => layer$14({
1166
+ const layerProtobuf = (options = {}) => layer$13({
1031
1167
  ...options,
1032
1168
  serialization: "protobuf"
1033
1169
  });
@@ -1037,7 +1173,7 @@ const layerProtobuf = (options = {}) => layer$14({
1037
1173
  * Provide this layer at runtime scope for long-lived metrics aggregation, or at
1038
1174
  * handler scope when traces/logs should flush as the Cloudflare event finishes.
1039
1175
  */
1040
- const workerLayer = (options = {}) => makeLayer(options, {
1176
+ const layerWorker = (options = {}) => makeLayer(options, {
1041
1177
  "cloudflare.resource_type": "worker",
1042
1178
  "cloudflare.worker.name": options.workerName
1043
1179
  });
@@ -1048,7 +1184,7 @@ const workerLayer = (options = {}) => makeLayer(options, {
1048
1184
  * Durable Object id. Prefer leaving `includeObjectId` disabled unless the
1049
1185
  * backend can tolerate high-cardinality resource attributes.
1050
1186
  */
1051
- const durableObjectLayer = (options = {}) => Layer.unwrap(Effect.map(DurableObjectState, (state) => makeLayer(options, {
1187
+ const layerDurableObject = (options = {}) => Layer.unwrap(Effect.map(DurableObjectState, (state) => makeLayer(options, {
1052
1188
  "cloudflare.resource_type": "durable_object",
1053
1189
  "cloudflare.durable_object.class": options.className,
1054
1190
  "cloudflare.durable_object.id": options.includeObjectId ? state.id.toString() : void 0
@@ -1059,9 +1195,9 @@ var ContainerNamespace_exports = /* @__PURE__ */ __exportAll({
1059
1195
  ContainerNamespace: () => ContainerNamespace,
1060
1196
  ContainerOperationError: () => ContainerOperationError,
1061
1197
  ContainerState: () => ContainerState,
1062
- Tag: () => Tag$14,
1198
+ Tag: () => Tag$12,
1063
1199
  isContainerNamespaceResource: () => isContainerNamespaceResource,
1064
- layer: () => layer$13,
1200
+ layer: () => layer$12,
1065
1201
  make: () => make$14,
1066
1202
  makeClient: () => makeClient$10
1067
1203
  });
@@ -1081,7 +1217,11 @@ const ContainerState = Schema.Union([Schema.Struct({
1081
1217
  exitCode: Schema.optionalKey(Schema.Int)
1082
1218
  })]);
1083
1219
  /** Failure raised when invoking a named Container operation. */
1084
- var ContainerOperationError = class extends Data.TaggedError("ContainerOperationError") {};
1220
+ var ContainerOperationError = class extends Data.TaggedError("ContainerOperationError") {
1221
+ get message() {
1222
+ return `Container ${this.operation} failed for binding "${this.binding}" instance "${this.instance}": ${causeMessage(this.cause)}`;
1223
+ }
1224
+ };
1085
1225
  const tryContainerPromise = (definition, instance, operation, evaluate) => Effect.tryPromise({
1086
1226
  try: evaluate,
1087
1227
  catch: (cause) => new ContainerOperationError({
@@ -1091,20 +1231,50 @@ const tryContainerPromise = (definition, instance, operation, evaluate) => Effec
1091
1231
  cause
1092
1232
  })
1093
1233
  });
1094
- const makeInstanceClient = (definition, instance, stub) => ({
1095
- unsafeRaw: Effect.succeed(stub),
1096
- state: tryContainerPromise(definition, instance, "state", () => stub.getState()).pipe(Effect.flatMap(Schema.decodeUnknownEffect(ContainerState)), Effect.mapError((cause) => cause instanceof ContainerOperationError ? cause : new ContainerOperationError({
1234
+ const makeInstanceClient = (definition, instance, stub) => {
1235
+ const spanOptions = (operation) => ({ attributes: {
1097
1236
  binding: definition.binding,
1098
1237
  instance,
1099
- operation: "state",
1100
- cause
1101
- }))),
1102
- fetch: (input, init) => tryContainerPromise(definition, instance, "fetch", () => stub.fetch(input, init)),
1103
- start: (options, waitOptions) => tryContainerPromise(definition, instance, "start", () => stub.start(options, waitOptions)),
1104
- startAndWaitForPorts: (options) => tryContainerPromise(definition, instance, "startAndWaitForPorts", () => stub.startAndWaitForPorts(options)),
1105
- stop: (signal) => tryContainerPromise(definition, instance, "stop", () => stub.stop(signal)),
1106
- destroy: tryContainerPromise(definition, instance, "destroy", () => stub.destroy())
1107
- });
1238
+ operation
1239
+ } });
1240
+ const hostListOperation = (operation) => Effect.fn(`ContainerNamespace.${operation}`, spanOptions(operation))(function* (hosts) {
1241
+ return yield* tryContainerPromise(definition, instance, operation, () => stub[operation]([...hosts]));
1242
+ });
1243
+ const hostnameOperation = (operation) => Effect.fn(`ContainerNamespace.${operation}`, spanOptions(operation))(function* (hostname) {
1244
+ return yield* tryContainerPromise(definition, instance, operation, () => stub[operation](hostname));
1245
+ });
1246
+ return {
1247
+ rawUnsafe: Effect.succeed(stub),
1248
+ state: tryContainerPromise(definition, instance, "state", () => stub.getState()).pipe(Effect.flatMap(Schema.decodeUnknownEffect(ContainerState)), Effect.mapError((cause) => cause instanceof ContainerOperationError ? cause : new ContainerOperationError({
1249
+ binding: definition.binding,
1250
+ instance,
1251
+ operation: "state",
1252
+ cause
1253
+ })), Effect.withSpan("ContainerNamespace.state", spanOptions("state"))),
1254
+ fetch: Effect.fn("ContainerNamespace.fetch", spanOptions("fetch"))(function* (input, init) {
1255
+ return yield* tryContainerPromise(definition, instance, "fetch", () => stub.fetch(input, init));
1256
+ }),
1257
+ start: Effect.fn("ContainerNamespace.start", spanOptions("start"))(function* (options, waitOptions) {
1258
+ return yield* tryContainerPromise(definition, instance, "start", () => stub.start(options, waitOptions));
1259
+ }),
1260
+ startAndWaitForPorts: Effect.fn("ContainerNamespace.startAndWaitForPorts", spanOptions("startAndWaitForPorts"))(function* (options) {
1261
+ return yield* tryContainerPromise(definition, instance, "startAndWaitForPorts", () => stub.startAndWaitForPorts(options));
1262
+ }),
1263
+ waitForPort: Effect.fn("ContainerNamespace.waitForPort", spanOptions("waitForPort"))(function* (options) {
1264
+ return yield* tryContainerPromise(definition, instance, "waitForPort", () => stub.waitForPort(options));
1265
+ }),
1266
+ stop: Effect.fn("ContainerNamespace.stop", spanOptions("stop"))(function* (signal) {
1267
+ return yield* tryContainerPromise(definition, instance, "stop", () => stub.stop(signal));
1268
+ }),
1269
+ destroy: tryContainerPromise(definition, instance, "destroy", () => stub.destroy()).pipe(Effect.withSpan("ContainerNamespace.destroy", spanOptions("destroy"))),
1270
+ setAllowedHosts: hostListOperation("setAllowedHosts"),
1271
+ setDeniedHosts: hostListOperation("setDeniedHosts"),
1272
+ allowHost: hostnameOperation("allowHost"),
1273
+ denyHost: hostnameOperation("denyHost"),
1274
+ removeAllowedHost: hostnameOperation("removeAllowedHost"),
1275
+ removeDeniedHost: hostnameOperation("removeDeniedHost")
1276
+ };
1277
+ };
1108
1278
  const isContainerNamespaceResource = (value) => typeof value === "object" && value !== null && typeof Reflect.get(value, "getByName") === "function";
1109
1279
  const makeClient$10 = (definition) => (namespace) => {
1110
1280
  const getByName = (name, options) => Effect.try({
@@ -1119,29 +1289,36 @@ const makeClient$10 = (definition) => (namespace) => {
1119
1289
  const byName = (name, options) => {
1120
1290
  const instance = getByName(name, options);
1121
1291
  return {
1122
- unsafeRaw: Effect.flatMap(instance, (client) => client.unsafeRaw),
1292
+ rawUnsafe: Effect.flatMap(instance, (client) => client.rawUnsafe),
1123
1293
  state: Effect.flatMap(instance, (client) => client.state),
1124
1294
  fetch: (input, init) => Effect.flatMap(instance, (client) => client.fetch(input, init)),
1125
1295
  start: (startOptions, waitOptions) => Effect.flatMap(instance, (client) => client.start(startOptions, waitOptions)),
1126
1296
  startAndWaitForPorts: (startOptions) => Effect.flatMap(instance, (client) => client.startAndWaitForPorts(startOptions)),
1297
+ waitForPort: (waitOptions) => Effect.flatMap(instance, (client) => client.waitForPort(waitOptions)),
1127
1298
  stop: (signal) => Effect.flatMap(instance, (client) => client.stop(signal)),
1128
- destroy: Effect.flatMap(instance, (client) => client.destroy)
1299
+ destroy: Effect.flatMap(instance, (client) => client.destroy),
1300
+ setAllowedHosts: (hosts) => Effect.flatMap(instance, (client) => client.setAllowedHosts(hosts)),
1301
+ setDeniedHosts: (hosts) => Effect.flatMap(instance, (client) => client.setDeniedHosts(hosts)),
1302
+ allowHost: (hostname) => Effect.flatMap(instance, (client) => client.allowHost(hostname)),
1303
+ denyHost: (hostname) => Effect.flatMap(instance, (client) => client.denyHost(hostname)),
1304
+ removeAllowedHost: (hostname) => Effect.flatMap(instance, (client) => client.removeAllowedHost(hostname)),
1305
+ removeDeniedHost: (hostname) => Effect.flatMap(instance, (client) => client.removeDeniedHost(hostname))
1129
1306
  };
1130
1307
  };
1131
1308
  return {
1132
1309
  definition,
1133
1310
  getByName,
1134
1311
  byName,
1135
- unsafeRaw: Effect.succeed(namespace)
1312
+ rawUnsafe: Effect.succeed(namespace)
1136
1313
  };
1137
1314
  };
1138
- const layer$13 = (tag, definition) => layer$20(tag, definition.binding, isContainerNamespaceResource, makeClient$10(definition), { expected: expectedContainerNamespace });
1139
- const make$14 = (id) => Tag$14()(id);
1315
+ const layer$12 = (tag, definition) => layer$19(tag, definition.binding, isContainerNamespaceResource, makeClient$10(definition), { expected: expectedContainerNamespace });
1316
+ const make$14 = (id) => Tag$12()(id);
1140
1317
  /** Creates a typed Effect service for a Cloudflare Container namespace. */
1141
- const Tag$14 = () => (id) => {
1142
- const tag = Context.Service()(id);
1143
- const makeLayer = (definition) => layer$13(tag, definition);
1144
- const getByName = (name, options) => Effect.gen(function* () {
1318
+ const Tag$12 = () => (id) => {
1319
+ const tag = Context.Service()(`effect-cf/Container/${id}`);
1320
+ const makeLayer = (definition) => layer$12(tag, definition);
1321
+ const getByName = Effect.fnUntraced(function* (name, options) {
1145
1322
  return yield* (yield* tag).getByName(name, options);
1146
1323
  });
1147
1324
  const byName = (name, options) => ({
@@ -1149,29 +1326,34 @@ const Tag$14 = () => (id) => {
1149
1326
  fetch: (input, init) => Effect.flatMap(getByName(name, options), (instance) => instance.fetch(input, init)),
1150
1327
  start: (startOptions, waitOptions) => Effect.flatMap(getByName(name, options), (instance) => instance.start(startOptions, waitOptions)),
1151
1328
  startAndWaitForPorts: (startOptions) => Effect.flatMap(getByName(name, options), (instance) => instance.startAndWaitForPorts(startOptions)),
1329
+ waitForPort: (waitOptions) => Effect.flatMap(getByName(name, options), (instance) => instance.waitForPort(waitOptions)),
1152
1330
  stop: (signal) => Effect.flatMap(getByName(name, options), (instance) => instance.stop(signal)),
1153
1331
  destroy: Effect.flatMap(getByName(name, options), (instance) => instance.destroy),
1154
- unsafeRaw: Effect.flatMap(getByName(name, options), (instance) => instance.unsafeRaw)
1155
- });
1156
- const unsafeRaw = Effect.fn(function* () {
1157
- return yield* (yield* tag).unsafeRaw;
1158
- });
1332
+ setAllowedHosts: (hosts) => Effect.flatMap(getByName(name, options), (instance) => instance.setAllowedHosts(hosts)),
1333
+ setDeniedHosts: (hosts) => Effect.flatMap(getByName(name, options), (instance) => instance.setDeniedHosts(hosts)),
1334
+ allowHost: (hostname) => Effect.flatMap(getByName(name, options), (instance) => instance.allowHost(hostname)),
1335
+ denyHost: (hostname) => Effect.flatMap(getByName(name, options), (instance) => instance.denyHost(hostname)),
1336
+ removeAllowedHost: (hostname) => Effect.flatMap(getByName(name, options), (instance) => instance.removeAllowedHost(hostname)),
1337
+ removeDeniedHost: (hostname) => Effect.flatMap(getByName(name, options), (instance) => instance.removeDeniedHost(hostname)),
1338
+ rawUnsafe: Effect.flatMap(getByName(name, options), (instance) => instance.rawUnsafe)
1339
+ });
1340
+ const rawUnsafe = Effect.flatMap(tag, (namespace) => namespace.rawUnsafe);
1159
1341
  return Object.assign(tag, {
1160
1342
  id,
1161
1343
  layer: makeLayer,
1162
1344
  getByName,
1163
1345
  byName,
1164
- unsafeRaw
1346
+ rawUnsafe
1165
1347
  });
1166
1348
  };
1167
- const ContainerNamespace = Tag$14;
1349
+ const ContainerNamespace = Tag$12;
1168
1350
  //#endregion
1169
1351
  //#region src/D1.ts
1170
1352
  var D1_exports = /* @__PURE__ */ __exportAll({
1171
1353
  Service: () => Service$1,
1172
1354
  make: () => make$13
1173
1355
  });
1174
- const TypeId$2 = "effect-cf/D1";
1356
+ const TypeId$2 = "~effect-cf/D1";
1175
1357
  const expectedD1Database = "D1 database binding with prepare(), batch(), and exec()";
1176
1358
  const isD1Database = (value) => {
1177
1359
  if (typeof value !== "object" || value === null) return false;
@@ -1217,7 +1399,7 @@ const Service$1 = () => (id, definition) => {
1217
1399
  var QueueBinding_exports = /* @__PURE__ */ __exportAll({
1218
1400
  QueueOperationError: () => QueueOperationError,
1219
1401
  isQueue: () => isQueue,
1220
- layer: () => layer$12,
1402
+ layer: () => layer$11,
1221
1403
  makeClient: () => makeClient$9
1222
1404
  });
1223
1405
  const expectedQueueProducer = "Queue producer binding with send(); optional sendBatch()/metrics()";
@@ -1238,27 +1420,30 @@ const isQueue = (value) => {
1238
1420
  const makeClient$9 = (definition) => {
1239
1421
  const encodeMessage = Schema.encodeEffect(definition.message);
1240
1422
  return (queue) => ({
1241
- send: Effect.fnUntraced(function* (message, options) {
1423
+ send: Effect.fn("QueueBinding.send", { attributes: {
1424
+ binding: definition.binding,
1425
+ operation: "send"
1426
+ } })(function* (message, options) {
1242
1427
  const encoded = yield* encodeMessage(message);
1243
1428
  yield* tryQueuePromise(definition.binding, "send", () => queue.send(encoded, options));
1244
1429
  }),
1245
- sendBatch: Effect.fnUntraced(function* (messages, options) {
1430
+ sendBatch: Effect.fn("QueueBinding.sendBatch", { attributes: {
1431
+ binding: definition.binding,
1432
+ operation: "sendBatch"
1433
+ } })(function* (messages, options) {
1246
1434
  const encodedMessages = [];
1247
1435
  for (const message of messages) encodedMessages.push({
1248
1436
  ...message,
1249
1437
  body: yield* encodeMessage(message.body)
1250
1438
  });
1251
1439
  const sendBatch = queue.sendBatch;
1252
- if (sendBatch !== void 0) {
1253
- yield* tryQueuePromise(definition.binding, "sendBatch", () => sendBatch.call(queue, encodedMessages, options));
1254
- return;
1255
- }
1256
- yield* tryQueuePromise(definition.binding, "sendBatch", async () => {
1257
- for (const message of encodedMessages) await queue.send(message.body, {
1258
- contentType: message.contentType,
1259
- delaySeconds: message.delaySeconds ?? options?.delaySeconds
1260
- });
1440
+ if (sendBatch === void 0) return yield* new QueueOperationError({
1441
+ binding: definition.binding,
1442
+ operation: "sendBatch",
1443
+ cause: /* @__PURE__ */ new Error(`Queue binding "${definition.binding}" does not provide sendBatch()`),
1444
+ message: `Cloudflare queue binding "${definition.binding}" does not provide sendBatch()`
1261
1445
  });
1446
+ yield* tryQueuePromise(definition.binding, "sendBatch", () => sendBatch.call(queue, encodedMessages, options));
1262
1447
  }),
1263
1448
  metrics: () => {
1264
1449
  const metrics = queue.metrics;
@@ -1270,16 +1455,16 @@ const makeClient$9 = (definition) => {
1270
1455
  }));
1271
1456
  return tryQueuePromise(definition.binding, "metrics", () => metrics.call(queue));
1272
1457
  },
1273
- unsafeRaw: Effect.succeed(queue)
1458
+ rawUnsafe: Effect.succeed(queue)
1274
1459
  });
1275
1460
  };
1276
- const layer$12 = (tag, definition) => layer$20(tag, definition.binding, (value) => isQueue(value), makeClient$9(definition), { expected: expectedQueueProducer });
1461
+ const layer$11 = (tag, definition) => layer$19(tag, definition.binding, (value) => isQueue(value), makeClient$9(definition), { expected: expectedQueueProducer });
1277
1462
  //#endregion
1278
1463
  //#region src/QueueDefinition.ts
1279
1464
  var QueueDefinition_exports = /* @__PURE__ */ __exportAll({
1280
1465
  Queue: () => Queue$1,
1281
- Tag: () => Tag$13,
1282
- implement: () => implement$7,
1466
+ Tag: () => Tag$11,
1467
+ implement: () => implement$5,
1283
1468
  make: () => make$12
1284
1469
  });
1285
1470
  const makeDefinition$4 = (id, definition) => {
@@ -1292,11 +1477,11 @@ const makeDefinition$4 = (id, definition) => {
1292
1477
  queue: wrapHandler$1(queueDefinition, options.queue)
1293
1478
  }) });
1294
1479
  };
1295
- const make$12 = (id, definition) => Tag$13()(id, definition);
1296
- const Tag$13 = () => (id, definition) => {
1480
+ const make$12 = (id, definition) => Tag$11()(id, definition);
1481
+ const Tag$11 = () => (id, definition) => {
1297
1482
  const queueDefinition = makeDefinition$4(id, definition);
1298
- const tag = Context.Service()(id);
1299
- const layer = (binding) => layer$12(tag, {
1483
+ const tag = Context.Service()(`effect-cf/Queue/${id}`);
1484
+ const layer = (binding) => layer$11(tag, {
1300
1485
  ...binding,
1301
1486
  message: definition.message
1302
1487
  });
@@ -1309,9 +1494,7 @@ const Tag$13 = () => (id, definition) => {
1309
1494
  const metrics = Effect.fnUntraced(function* () {
1310
1495
  return yield* (yield* tag).metrics();
1311
1496
  });
1312
- const unsafeRaw = Effect.fnUntraced(function* () {
1313
- return yield* (yield* tag).unsafeRaw;
1314
- });
1497
+ const rawUnsafe = Effect.flatMap(tag, (queue) => queue.rawUnsafe);
1315
1498
  return Object.assign(tag, {
1316
1499
  id: queueDefinition.id,
1317
1500
  message: queueDefinition.message,
@@ -1320,28 +1503,32 @@ const Tag$13 = () => (id, definition) => {
1320
1503
  send,
1321
1504
  sendBatch,
1322
1505
  metrics,
1323
- unsafeRaw
1506
+ rawUnsafe
1324
1507
  });
1325
1508
  };
1326
- const Queue$1 = Tag$13;
1509
+ const Queue$1 = Tag$11;
1327
1510
  const wrapHandler$1 = (definition, handler) => {
1328
1511
  const decodeBody = Schema.decodeUnknownEffect(definition.message);
1329
- return (batch) => Effect.gen(function* () {
1512
+ return Effect.fnUntraced(function* (batch) {
1330
1513
  yield* handler(yield* decodeBatch(batch.raw, decodeBody));
1331
1514
  });
1332
1515
  };
1333
- const implement$7 = (_definition, handler) => handler;
1516
+ const implement$5 = (_definition, handler) => handler;
1334
1517
  //#endregion
1335
1518
  //#region src/Queue.ts
1336
1519
  var Queue_exports = /* @__PURE__ */ __exportAll({
1337
1520
  QueueMessageDecodeError: () => QueueMessageDecodeError,
1338
- Tag: () => Tag$12,
1521
+ Tag: () => Tag$10,
1339
1522
  decodeBatch: () => decodeBatch,
1340
1523
  fromMessage: () => fromMessage,
1341
1524
  fromMessageBatch: () => fromMessageBatch,
1342
- implement: () => implement$6
1525
+ implement: () => implement$4
1343
1526
  });
1344
- var QueueMessageDecodeError = class extends Data.TaggedError("QueueMessageDecodeError") {};
1527
+ var QueueMessageDecodeError = class extends Data.TaggedError("QueueMessageDecodeError") {
1528
+ get message() {
1529
+ return `Queue "${this.queue}" failed to decode message "${this.messageId}" at index ${this.index}: ${causeMessage(this.cause)}`;
1530
+ }
1531
+ };
1345
1532
  const fromMessage = (message, body) => ({
1346
1533
  raw: message,
1347
1534
  id: message.id,
@@ -1373,34 +1560,102 @@ const decodeBatch = (batch, decodeBody) => Effect.gen(function* () {
1373
1560
  }
1374
1561
  return fromMessageBatch(batch, messages);
1375
1562
  });
1376
- const Tag$12 = Tag$13;
1377
- const implement$6 = implement$7;
1563
+ const Tag$10 = Tag$11;
1564
+ const implement$4 = implement$5;
1378
1565
  //#endregion
1379
1566
  //#region src/RpcDefinition.ts
1380
1567
  var RpcDefinition_exports = /* @__PURE__ */ __exportAll({
1381
- ReservedMethodNameError: () => ReservedMethodNameError,
1382
1568
  RpcArgumentCountError: () => RpcArgumentCountError,
1383
1569
  RpcArgumentDecodeError: () => RpcArgumentDecodeError,
1384
1570
  RpcArgumentEncodeError: () => RpcArgumentEncodeError,
1385
1571
  RpcReservedMethodNameError: () => RpcReservedMethodNameError,
1386
1572
  RpcSuccessDecodeError: () => RpcSuccessDecodeError,
1387
1573
  RpcSuccessEncodeError: () => RpcSuccessEncodeError,
1388
- assertNoReservedMethodNames: () => assertNoReservedMethodNames,
1389
1574
  assertNoReservedMethods: () => assertNoReservedMethods,
1390
1575
  decodeArgs: () => decodeArgs,
1391
1576
  decodeSuccess: () => decodeSuccess,
1577
+ decodeWireError: () => decodeWireError,
1392
1578
  encodeArgs: () => encodeArgs,
1393
1579
  encodeSuccess: () => encodeSuccess,
1580
+ encodeWireError: () => encodeWireError,
1581
+ isWireError: () => isWireError,
1394
1582
  make: () => make$11,
1395
- method: () => method$4,
1583
+ method: () => method$2,
1396
1584
  reservedMethodNames: () => reservedMethodNames$4
1397
1585
  });
1398
- var RpcReservedMethodNameError = class extends Data.TaggedError("RpcReservedMethodNameError") {};
1399
- var RpcArgumentCountError = class extends Data.TaggedError("RpcArgumentCountError") {};
1400
- var RpcArgumentDecodeError = class extends Data.TaggedError("RpcArgumentDecodeError") {};
1401
- var RpcArgumentEncodeError = class extends Data.TaggedError("RpcArgumentEncodeError") {};
1402
- var RpcSuccessDecodeError = class extends Data.TaggedError("RpcSuccessDecodeError") {};
1403
- var RpcSuccessEncodeError = class extends Data.TaggedError("RpcSuccessEncodeError") {};
1586
+ var RpcReservedMethodNameError = class extends Data.TaggedError("RpcReservedMethodNameError") {
1587
+ get message() {
1588
+ return `${this.definition} RPC method "${this.method}" is reserved by Cloudflare Workers RPC`;
1589
+ }
1590
+ };
1591
+ var RpcArgumentCountError = class extends Schema.TaggedError()("RpcArgumentCountError", {
1592
+ definition: Schema.String,
1593
+ method: Schema.String,
1594
+ expected: Schema.Number,
1595
+ actual: Schema.Number
1596
+ }) {
1597
+ get message() {
1598
+ return `${this.definition} RPC method "${this.method}" expected ${this.expected} arguments but received ${this.actual}`;
1599
+ }
1600
+ };
1601
+ var RpcArgumentDecodeError = class extends Schema.TaggedError()("RpcArgumentDecodeError", {
1602
+ definition: Schema.String,
1603
+ method: Schema.String,
1604
+ cause: Schema.Defect()
1605
+ }) {
1606
+ get message() {
1607
+ return `${this.definition} RPC method "${this.method}" argument decode failed: ${causeMessage(this.cause)}`;
1608
+ }
1609
+ };
1610
+ var RpcArgumentEncodeError = class extends Data.TaggedError("RpcArgumentEncodeError") {
1611
+ get message() {
1612
+ return `${this.definition} RPC method "${this.method}" argument encode failed: ${causeMessage(this.cause)}`;
1613
+ }
1614
+ };
1615
+ var RpcSuccessDecodeError = class extends Data.TaggedError("RpcSuccessDecodeError") {
1616
+ get message() {
1617
+ return `${this.definition} RPC method "${this.method}" success decode failed: ${causeMessage(this.cause)}`;
1618
+ }
1619
+ };
1620
+ var RpcSuccessEncodeError = class extends Schema.TaggedError()("RpcSuccessEncodeError", {
1621
+ definition: Schema.String,
1622
+ method: Schema.String,
1623
+ cause: Schema.Defect()
1624
+ }) {
1625
+ get message() {
1626
+ return `${this.definition} RPC method "${this.method}" success encode failed: ${causeMessage(this.cause)}`;
1627
+ }
1628
+ };
1629
+ const WireErrorSchema = Schema.Union([
1630
+ RpcArgumentCountError,
1631
+ RpcArgumentDecodeError,
1632
+ RpcSuccessEncodeError
1633
+ ]);
1634
+ const wireErrorKey = "effect-cf/RpcDefinition/wireError";
1635
+ const isWireError = (error) => error instanceof RpcArgumentCountError || error instanceof RpcArgumentDecodeError || error instanceof RpcSuccessEncodeError;
1636
+ /**
1637
+ * Encodes package RPC errors into a plain `Error` envelope so their tags
1638
+ * survive Cloudflare RPC serialization, which drops custom error properties.
1639
+ */
1640
+ const encodeWireError = (error) => {
1641
+ if (!isWireError(error)) return error;
1642
+ try {
1643
+ return new Error(JSON.stringify({ [wireErrorKey]: Schema.encodeSync(WireErrorSchema)(error) }));
1644
+ } catch {
1645
+ return error;
1646
+ }
1647
+ };
1648
+ /** Restores package RPC errors from the {@link encodeWireError} envelope. */
1649
+ const decodeWireError = (cause) => {
1650
+ if (!(cause instanceof Error)) return cause;
1651
+ try {
1652
+ const parsed = JSON.parse(cause.message);
1653
+ if (!Predicate.hasProperty(parsed, wireErrorKey)) return cause;
1654
+ return Schema.decodeUnknownSync(WireErrorSchema)(parsed[wireErrorKey]);
1655
+ } catch {
1656
+ return cause;
1657
+ }
1658
+ };
1404
1659
  const reservedMethodNames$4 = /* @__PURE__ */ new Set([
1405
1660
  "constructor",
1406
1661
  "fetch",
@@ -1415,72 +1670,56 @@ const reservedMethodNames$4 = /* @__PURE__ */ new Set([
1415
1670
  "serialize",
1416
1671
  "deserialize"
1417
1672
  ]);
1418
- var ReservedMethodNameError = class extends Error {
1419
- method;
1420
- target;
1421
- constructor(target, method) {
1422
- super(`${target} RPC method "${method}" is reserved by Cloudflare Workers RPC`);
1423
- this.name = "ReservedMethodNameError";
1424
- this.target = target;
1425
- this.method = method;
1426
- }
1427
- };
1673
+ /**
1674
+ * Workers RPC structured-clones every value that crosses an isolate boundary
1675
+ * and rejects class instances. Declaration schemas such as `Schema.Result`
1676
+ * keep their container instance in their `Encoded` form, so the declared
1677
+ * schemas are lowered to their canonical JSON codec before touching the wire.
1678
+ */
1679
+ const wireCodec = (schema) => Schema.toCodecJson(schema);
1428
1680
  const assertNoReservedMethods = (target, methods, reserved) => {
1429
- for (const method of Object.keys(methods)) if (reserved.has(method)) throw new ReservedMethodNameError(target, method);
1681
+ for (const method of Object.keys(methods)) if (reserved.has(method)) throw new RpcReservedMethodNameError({
1682
+ definition: target,
1683
+ method
1684
+ });
1430
1685
  };
1431
- function method$4(definition) {
1686
+ function method$2(definition) {
1432
1687
  return {
1433
1688
  args: definition.args ?? [],
1434
1689
  success: definition.success
1435
1690
  };
1436
1691
  }
1437
- const assertNoReservedMethodNames = (definition) => Effect.forEach(Object.keys(definition.methods), (method) => reservedMethodNames$4.has(method) ? Effect.fail(new RpcReservedMethodNameError({
1438
- definition: definition.id,
1439
- method
1440
- })) : Effect.void).pipe(Effect.asVoid);
1441
- const decodeArgs = (definition, methodName, args) => Effect.gen(function* () {
1692
+ const decodeArgs = Effect.fnUntraced(function* (definition, methodName, args) {
1442
1693
  const methodDefinition = definition.methods[methodName];
1443
- if (args.length !== methodDefinition.args.length) return yield* Effect.fail(new RpcArgumentCountError({
1694
+ if (args.length !== methodDefinition.args.length) return yield* new RpcArgumentCountError({
1444
1695
  definition: definition.id,
1445
1696
  method: methodName,
1446
1697
  expected: methodDefinition.args.length,
1447
1698
  actual: args.length
1448
- }));
1449
- const decoded = [];
1450
- for (let index = 0; index < methodDefinition.args.length; index++) {
1451
- const schema = methodDefinition.args[index];
1452
- decoded.push(yield* Schema.decodeUnknownEffect(schema)(args[index]).pipe(Effect.mapError((cause) => new RpcArgumentDecodeError({
1453
- definition: definition.id,
1454
- method: methodName,
1455
- index,
1456
- cause
1457
- }))));
1458
- }
1459
- return decoded;
1699
+ });
1700
+ return yield* Schema.decodeUnknownEffect(wireCodec(Schema.Tuple(methodDefinition.args)))(args).pipe(Effect.mapError((cause) => new RpcArgumentDecodeError({
1701
+ definition: definition.id,
1702
+ method: methodName,
1703
+ cause
1704
+ })));
1460
1705
  });
1461
- const encodeArgs = (definition, methodName, args) => Effect.gen(function* () {
1706
+ const encodeArgs = Effect.fnUntraced(function* (definition, methodName, args) {
1462
1707
  const methodDefinition = definition.methods[methodName];
1463
- if (args.length !== methodDefinition.args.length) return yield* Effect.fail(new RpcArgumentCountError({
1708
+ if (args.length !== methodDefinition.args.length) return yield* new RpcArgumentCountError({
1464
1709
  definition: definition.id,
1465
1710
  method: methodName,
1466
1711
  expected: methodDefinition.args.length,
1467
1712
  actual: args.length
1468
- }));
1469
- const encoded = [];
1470
- for (let index = 0; index < methodDefinition.args.length; index++) {
1471
- const schema = methodDefinition.args[index];
1472
- encoded.push(yield* Schema.encodeEffect(schema)(args[index]).pipe(Effect.mapError((cause) => new RpcArgumentEncodeError({
1473
- definition: definition.id,
1474
- method: methodName,
1475
- index,
1476
- cause
1477
- }))));
1478
- }
1479
- return encoded;
1713
+ });
1714
+ return yield* Schema.encodeUnknownEffect(wireCodec(Schema.Tuple(methodDefinition.args)))(args).pipe(Effect.mapError((cause) => new RpcArgumentEncodeError({
1715
+ definition: definition.id,
1716
+ method: methodName,
1717
+ cause
1718
+ })));
1480
1719
  });
1481
1720
  const encodeSuccess = (definition, methodName, value) => {
1482
1721
  const methodDefinition = definition.methods[methodName];
1483
- return Schema.encodeEffect(methodDefinition.success)(value).pipe(Effect.mapError((cause) => new RpcSuccessEncodeError({
1722
+ return Schema.encodeUnknownEffect(wireCodec(methodDefinition.success))(value).pipe(Effect.mapError((cause) => new RpcSuccessEncodeError({
1484
1723
  definition: definition.id,
1485
1724
  method: methodName,
1486
1725
  cause
@@ -1488,23 +1727,59 @@ const encodeSuccess = (definition, methodName, value) => {
1488
1727
  };
1489
1728
  const decodeSuccess = (definition, methodName, value) => {
1490
1729
  const methodDefinition = definition.methods[methodName];
1491
- return Schema.decodeUnknownEffect(methodDefinition.success)(value).pipe(Effect.mapError((cause) => new RpcSuccessDecodeError({
1730
+ return Schema.decodeUnknownEffect(wireCodec(methodDefinition.success))(value).pipe(Effect.mapError((cause) => new RpcSuccessDecodeError({
1492
1731
  definition: definition.id,
1493
1732
  method: methodName,
1494
1733
  cause
1495
1734
  })));
1496
1735
  };
1497
1736
  const make$11 = (id, methods) => {
1498
- const definition = {
1737
+ assertNoReservedMethods(id, methods, reservedMethodNames$4);
1738
+ return {
1499
1739
  id,
1500
1740
  methods
1501
1741
  };
1502
- const reserved = Object.keys(definition.methods).find((methodName) => reservedMethodNames$4.has(methodName));
1503
- if (reserved !== void 0) throw new RpcReservedMethodNameError({
1504
- definition: id,
1505
- method: reserved
1742
+ };
1743
+ //#endregion
1744
+ //#region src/internal/Entrypoint.ts
1745
+ const provideEntrypointServices = (layer, services) => layer.pipe(Layer.provideMerge(services));
1746
+ const defineEntrypointRpcMethods = (target, prototype, rpc, reservedMethodNames, run) => {
1747
+ const methods = rpc ?? {};
1748
+ assertNoReservedMethods(target, methods, reservedMethodNames);
1749
+ for (const [key, method] of Object.entries(methods)) Object.defineProperty(prototype, key, {
1750
+ enumerable: true,
1751
+ value(...args) {
1752
+ return run(this, Effect.suspend(() => method(...args)).pipe(Effect.mapError(encodeWireError)));
1753
+ }
1506
1754
  });
1507
- return definition;
1755
+ };
1756
+ const assumeEntrypointClass = (entrypoint) => entrypoint;
1757
+ //#endregion
1758
+ //#region src/internal/Runtime.ts
1759
+ /**
1760
+ * Assembles the shared `ManagedRuntime` used by the Cloudflare entrypoint
1761
+ * classes (Worker, Durable Object, Workflow).
1762
+ *
1763
+ * The entrypoint-specific services are merged with the env-backed
1764
+ * `ConfigProvider` and `WorkerEnvironment`, then provided to the user-supplied
1765
+ * layer so the resulting runtime satisfies both the user services and the
1766
+ * platform services.
1767
+ */
1768
+ const makeEntrypointRuntime = (layer, env, services) => {
1769
+ const entrypointServices = Layer.mergeAll(services, ConfigProvider.layer(WorkerConfig.providerFromEnv(env)), Layer.succeed(WorkerEnvironment, env));
1770
+ return ManagedRuntime.make(provideEntrypointServices(layer, entrypointServices));
1771
+ };
1772
+ /**
1773
+ * Runs a Cloudflare event effect on an entrypoint runtime.
1774
+ *
1775
+ * When an event layer is given it is built inside the event's Effect scope
1776
+ * (finalized when the event effect completes). The casts widen away the
1777
+ * `REvent` requirement satisfied by the event layer; TypeScript cannot reduce
1778
+ * `Exclude<...>` over the generic union.
1779
+ */
1780
+ const runEventPromise = (runtime, effect, eventLayer) => {
1781
+ const withEventLayer = eventLayer === void 0 ? effect : effect.pipe(Effect.provide(eventLayer, { local: true }));
1782
+ return runtime.runPromise(Effect.scoped(withEventLayer));
1508
1783
  };
1509
1784
  //#endregion
1510
1785
  //#region src/Rpc.ts
@@ -1522,7 +1797,7 @@ const dispose = (value) => Effect.sync(() => {
1522
1797
  });
1523
1798
  const resolve = (value) => isPromiseLike(value) ? Effect.tryPromise({
1524
1799
  try: () => value,
1525
- catch: (cause) => cause
1800
+ catch: (cause) => decodeWireError(cause)
1526
1801
  }) : Effect.sync(() => value);
1527
1802
  const scoped = (value) => Effect.acquireRelease(resolve(value), (resolved) => dispose(resolved));
1528
1803
  const isPromiseLike = (value) => (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
@@ -1538,7 +1813,7 @@ const lookupRpcMethod = (target, method, makeError) => Effect.try({
1538
1813
  },
1539
1814
  catch: makeError
1540
1815
  });
1541
- const invokeRpcMethod = (target, method, args, makeError) => Effect.gen(function* () {
1816
+ const invokeRpcMethod = Effect.fnUntraced(function* (target, method, args, makeError) {
1542
1817
  const fn = yield* lookupRpcMethod(target, method, makeError);
1543
1818
  return yield* Effect.try({
1544
1819
  try: () => fn(...args),
@@ -1552,7 +1827,7 @@ var ServiceBinding_exports = /* @__PURE__ */ __exportAll({
1552
1827
  ServiceBindingFetchError: () => ServiceBindingFetchError,
1553
1828
  ServiceBindingRpcError: () => ServiceBindingRpcError,
1554
1829
  isServiceBindingClient: () => isServiceBindingClient,
1555
- layer: () => layer$11,
1830
+ layer: () => layer$10,
1556
1831
  makeClient: () => makeClient$8,
1557
1832
  makeDirectMethods: () => makeDirectMethods$1
1558
1833
  });
@@ -1561,22 +1836,32 @@ const expectedServiceBinding = "Worker service binding with fetch()";
1561
1836
  /**
1562
1837
  * Failure raised when calling `fetch` on a service binding.
1563
1838
  */
1564
- var ServiceBindingFetchError = class extends Data.TaggedError("ServiceBindingFetchError") {};
1839
+ var ServiceBindingFetchError = class extends Data.TaggedError("ServiceBindingFetchError") {
1840
+ get message() {
1841
+ return `Service binding "${this.binding}" fetch failed: ${causeMessage(this.cause)}`;
1842
+ }
1843
+ };
1565
1844
  /**
1566
1845
  * Failure raised when invoking an RPC method on a service binding.
1567
1846
  */
1568
- var ServiceBindingRpcError = class extends Data.TaggedError("ServiceBindingRpcError") {};
1847
+ var ServiceBindingRpcError = class extends Data.TaggedError("ServiceBindingRpcError") {
1848
+ get message() {
1849
+ return `Service binding "${this.binding}" RPC method "${this.method}" failed: ${causeMessage(this.cause)}`;
1850
+ }
1851
+ };
1569
1852
  const isServiceBindingClient = (value) => typeof value === "object" && value !== null && typeof Reflect.get(value, "fetch") === "function";
1570
1853
  const makeClient$8 = (definition) => {
1571
1854
  return (service) => {
1572
- const fetch = (input, init) => Effect.tryPromise({
1573
- try: () => service.fetch(input, init),
1574
- catch: (cause) => new ServiceBindingFetchError({
1575
- binding: definition.binding,
1576
- cause
1577
- })
1855
+ const fetch = Effect.fn("ServiceBinding.fetch")(function* (input, init) {
1856
+ return yield* Effect.tryPromise({
1857
+ try: () => service.fetch(input, init),
1858
+ catch: (cause) => new ServiceBindingFetchError({
1859
+ binding: definition.binding,
1860
+ cause
1861
+ })
1862
+ });
1578
1863
  });
1579
- const rpc = (method, ...args) => Effect.gen(function* () {
1864
+ const rpc = Effect.fn("ServiceBinding.rpc")(function* (method, ...args) {
1580
1865
  const methodName = String(method);
1581
1866
  const encodedArgs = definition.definition === void 0 ? args : yield* encodeArgs(definition.definition, methodName, args).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1582
1867
  binding: definition.binding,
@@ -1589,7 +1874,7 @@ const makeClient$8 = (definition) => {
1589
1874
  cause
1590
1875
  }));
1591
1876
  });
1592
- const decodeSuccess$2 = (methodName, value) => Effect.gen(function* () {
1877
+ const decodeSuccess$2 = Effect.fnUntraced(function* (methodName, value) {
1593
1878
  if (definition.definition === void 0) return value;
1594
1879
  return yield* decodeSuccess(definition.definition, methodName, value).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1595
1880
  binding: definition.binding,
@@ -1597,7 +1882,7 @@ const makeClient$8 = (definition) => {
1597
1882
  cause
1598
1883
  })));
1599
1884
  });
1600
- const call = (method, ...args) => Effect.gen(function* () {
1885
+ const call = Effect.fn("ServiceBinding.call")(function* (method, ...args) {
1601
1886
  const methodName = String(method);
1602
1887
  const value = yield* resolve(yield* rpc(method, ...args)).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1603
1888
  binding: definition.binding,
@@ -1606,7 +1891,7 @@ const makeClient$8 = (definition) => {
1606
1891
  })));
1607
1892
  return yield* decodeSuccess$2(methodName, value);
1608
1893
  });
1609
- const scopedCall = (method, ...args) => Effect.gen(function* () {
1894
+ const scopedCall = Effect.fn("ServiceBinding.scopedCall")(function* (method, ...args) {
1610
1895
  const methodName = String(method);
1611
1896
  const result = yield* rpc(method, ...args);
1612
1897
  const value = yield* scoped(result);
@@ -1621,7 +1906,7 @@ const makeClient$8 = (definition) => {
1621
1906
  });
1622
1907
  };
1623
1908
  };
1624
- const layer$11 = (tag, definition) => layer$20(tag, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition), { expected: expectedServiceBinding });
1909
+ const layer$10 = (tag, definition) => layer$19(tag, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition), { expected: expectedServiceBinding });
1625
1910
  /**
1626
1911
  * Creates a typed Effect service for a Worker service binding.
1627
1912
  *
@@ -1653,16 +1938,16 @@ const layer$11 = (tag, definition) => layer$20(tag, definition.binding, (value)
1653
1938
  */
1654
1939
  const Service = () => (id, definition) => {
1655
1940
  const tag = Service$2()(id, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition));
1656
- const fetch = (input, init) => Effect.gen(function* () {
1941
+ const fetch = Effect.fnUntraced(function* (input, init) {
1657
1942
  return yield* (yield* tag).fetch(input, init);
1658
1943
  });
1659
- const rpc = (method, ...args) => Effect.gen(function* () {
1944
+ const rpc = Effect.fnUntraced(function* (method, ...args) {
1660
1945
  return yield* (yield* tag).rpc(method, ...args);
1661
1946
  });
1662
- const call = (method, ...args) => Effect.gen(function* () {
1947
+ const call = Effect.fnUntraced(function* (method, ...args) {
1663
1948
  return yield* (yield* tag).call(method, ...args);
1664
1949
  });
1665
- const scopedCall = (method, ...args) => Effect.gen(function* () {
1950
+ const scopedCall = Effect.fnUntraced(function* (method, ...args) {
1666
1951
  return yield* (yield* tag).scopedCall(method, ...args);
1667
1952
  });
1668
1953
  const directMethods = makeDirectMethods$1(definition.definition, call);
@@ -1683,11 +1968,11 @@ const makeDirectMethods$1 = (rpcDefinition, call) => {
1683
1968
  //#endregion
1684
1969
  //#region src/WorkerDefinition.ts
1685
1970
  var WorkerDefinition_exports = /* @__PURE__ */ __exportAll({
1686
- Tag: () => Tag$11,
1971
+ Tag: () => Tag$9,
1687
1972
  Worker: () => Worker,
1688
- implement: () => implement$5,
1973
+ implement: () => implement$3,
1689
1974
  make: () => make$10,
1690
- method: () => method$3
1975
+ method: () => method$1
1691
1976
  });
1692
1977
  const reservedMethodNames$3 = /* @__PURE__ */ new Set([
1693
1978
  "constructor",
@@ -1708,7 +1993,7 @@ const reservedMethodNames$3 = /* @__PURE__ */ new Set([
1708
1993
  /**
1709
1994
  * Defines a single RPC method schema in a worker definition.
1710
1995
  */
1711
- const method$3 = method$4;
1996
+ const method$1 = method$2;
1712
1997
  /**
1713
1998
  * Creates a typed worker RPC definition plus helpers for implementation and bindings.
1714
1999
  *
@@ -1730,15 +2015,15 @@ const makeDefinition$3 = (id, methods) => {
1730
2015
  rpc: wrapHandlers$1(definition, options.rpc)
1731
2016
  }) });
1732
2017
  };
1733
- const make$10 = (id, methods) => Tag$11()(id, methods);
1734
- const Tag$11 = () => (id, methods) => {
2018
+ const make$10 = (id, methods) => Tag$9()(id, methods);
2019
+ const Tag$9 = () => (id, methods) => {
1735
2020
  const definition = makeDefinition$3(id, methods);
1736
2021
  const tag = Context.Service()(id);
1737
2022
  const bindingDefinition = (binding) => ({
1738
2023
  ...binding,
1739
2024
  definition
1740
2025
  });
1741
- const layer = (binding) => layer$11(tag, bindingDefinition(binding));
2026
+ const layer = (binding) => layer$10(tag, bindingDefinition(binding));
1742
2027
  const fetch = (input, init) => Effect.gen(function* () {
1743
2028
  return yield* (yield* tag).fetch(input, init);
1744
2029
  });
@@ -1763,7 +2048,7 @@ const Tag$11 = () => (id, methods) => {
1763
2048
  scopedCall
1764
2049
  });
1765
2050
  };
1766
- const Worker = Tag$11;
2051
+ const Worker = Tag$9;
1767
2052
  const wrapHandlers$1 = (definition, handlers) => {
1768
2053
  const wrapped = {};
1769
2054
  for (const key of Object.keys(definition.methods)) {
@@ -1779,82 +2064,44 @@ const wrapHandlers$1 = (definition, handlers) => {
1779
2064
  /**
1780
2065
  * Helper for implementing handlers with the exact method shape of a definition.
1781
2066
  */
1782
- const implement$5 = (_definition, handlers) => handlers;
1783
- //#endregion
1784
- //#region src/internal/Clock.ts
1785
- const maxTimerMillis = 2 ** 31 - 1;
1786
- const nanosPerMilli = BigInt(1e6);
1787
- const clock = {
1788
- currentTimeMillisUnsafe: () => Date.now(),
1789
- currentTimeMillis: Effect.sync(() => clock.currentTimeMillisUnsafe()),
1790
- currentTimeNanosUnsafe: () => BigInt(Date.now()) * nanosPerMilli,
1791
- currentTimeNanos: Effect.sync(() => clock.currentTimeNanosUnsafe()),
1792
- monotonicTimeNanosUnsafe: () => typeof performance === "undefined" ? BigInt(Date.now()) * nanosPerMilli : BigInt(Math.round(performance.now() * 1e6)),
1793
- monotonicTimeNanos: Effect.sync(() => clock.monotonicTimeNanosUnsafe()),
1794
- sleep: (duration) => {
1795
- const millis = Duration.toMillis(duration);
1796
- if (millis <= 0) return Effect.yieldNow;
1797
- return Effect.callback((resume) => {
1798
- if (millis > maxTimerMillis) return;
1799
- const handle = setTimeout(() => resume(Effect.void), millis);
1800
- return Effect.sync(() => clearTimeout(handle));
1801
- });
1802
- }
1803
- };
1804
- const layer$10 = Layer.effect(Clock.Clock, Effect.succeed(clock));
1805
- //#endregion
1806
- //#region src/internal/Entrypoint.ts
1807
- const provideEntrypointServices = (layer, services) => layer.pipe(Layer.provideMerge(services));
1808
- const defineEntrypointRpcMethods = (target, prototype, rpc, reservedMethodNames, run) => {
1809
- const methods = rpc ?? {};
1810
- assertNoReservedMethods(target, methods, reservedMethodNames);
1811
- for (const [key, method] of Object.entries(methods)) Object.defineProperty(prototype, key, {
1812
- enumerable: true,
1813
- value(...args) {
1814
- return run(this, Effect.suspend(() => method(...args)));
1815
- }
1816
- });
1817
- };
1818
- const assumeEntrypointClass = (entrypoint) => entrypoint;
1819
- //#endregion
1820
- //#region src/internal/WorkerContext.ts
1821
- const causeError = (cause) => new Error(Cause.pretty(cause));
1822
- const failureHandler = (cause, options) => (options?.onFailure?.(cause) ?? Effect.logError("WorkerContext.waitUntil failed", Cause.pretty(cause))).pipe(Effect.catchCause((handlerCause) => Effect.logError("WorkerContext.waitUntil failure handler failed", Cause.pretty(cause), Cause.pretty(handlerCause))));
1823
- const fromExecutionContext = (ctx, runPromiseExit) => {
1824
- const schedule = (effect, options, mode) => Effect.context().pipe(Effect.flatMap((context) => Effect.sync(() => {
1825
- const runHandler = (cause) => runPromiseExit(Effect.scoped(Effect.provideContext(failureHandler(cause, options), context))).then((exit) => {
1826
- if (Exit.isFailure(exit)) console.error("WorkerContext.waitUntil failure handler failed", Cause.pretty(exit.cause));
1827
- });
1828
- ctx.waitUntil(runPromiseExit(Effect.scoped(Effect.provideContext(effect, context))).then(async (exit) => {
1829
- if (Exit.isSuccess(exit)) return;
1830
- await runHandler(exit.cause);
1831
- if (mode === "propagate") throw causeError(exit.cause);
1832
- }));
1833
- })));
1834
- return {
1835
- raw: ctx,
1836
- waitUntil: (effect, options) => schedule(effect, options, options?.mode ?? "observe"),
1837
- waitUntilPropagating: (effect, options) => schedule(effect, options, "propagate"),
1838
- passThroughOnException: Effect.sync(() => ctx.passThroughOnException())
1839
- };
1840
- };
2067
+ const implement$3 = (_definition, handlers) => handlers;
1841
2068
  //#endregion
1842
2069
  //#region src/Worker.ts
1843
2070
  var Worker_exports = /* @__PURE__ */ __exportAll({
1844
2071
  ExecutionContext: () => ExecutionContext,
1845
2072
  NativeRequest: () => NativeRequest,
1846
- Tag: () => Tag$10,
2073
+ Tag: () => Tag$9,
1847
2074
  WorkerContext: () => WorkerContext,
1848
- implement: () => implement$4,
2075
+ implement: () => implement$3,
1849
2076
  isWebSocketUpgrade: () => isWebSocketUpgrade,
1850
2077
  make: () => make$9,
1851
2078
  makeFetchHandler: () => makeFetchHandler,
1852
- method: () => method$2,
1853
- renderHttpResponse: () => renderHttpResponse
2079
+ method: () => method$1
1854
2080
  });
2081
+ /**
2082
+ * Access to Cloudflare's native `ExecutionContext`.
2083
+ */
1855
2084
  var ExecutionContext = class extends Context.Service()("effect-cf/ExecutionContext") {};
2085
+ /**
2086
+ * Service used inside handlers to schedule background work via `waitUntil`.
2087
+ *
2088
+ * @example
2089
+ * ```ts
2090
+ * const handler = Effect.gen(function* () {
2091
+ * const ctx = yield* Worker.WorkerContext;
2092
+ * yield* ctx.waitUntil(Effect.log("flush analytics"));
2093
+ * return new Response("ok");
2094
+ * });
2095
+ * ```
2096
+ */
1856
2097
  var WorkerContext = class extends Context.Service()("effect-cf/WorkerContext") {};
2098
+ /**
2099
+ * Access to the incoming `Request` currently handled by a worker or Durable Object fetch.
2100
+ */
1857
2101
  var NativeRequest = class extends Context.Service()("effect-cf/NativeRequest") {};
2102
+ /**
2103
+ * Returns `true` when the request is a websocket upgrade request.
2104
+ */
1858
2105
  const isWebSocketUpgrade = (request) => request.headers.get("Upgrade")?.toLowerCase() === "websocket";
1859
2106
  const reservedMethodNames$2 = /* @__PURE__ */ new Set([
1860
2107
  "constructor",
@@ -1873,7 +2120,7 @@ const reservedMethodNames$2 = /* @__PURE__ */ new Set([
1873
2120
  "webSocketError"
1874
2121
  ]);
1875
2122
  const RunSymbol$1 = Symbol.for("effect-cf/Worker/run");
1876
- const renderHttpResponse = (effect) => Effect.flatMap(effect, (response) => Effect.map(Effect.context(), (context) => HttpServerResponse.toWeb(response, { context })));
2123
+ const FetchSymbol = Symbol.for("effect-cf/Worker/fetch");
1877
2124
  const renderFetchSuccess = (effect) => Effect.suspend(() => {
1878
2125
  let nativeResponse;
1879
2126
  let webResponse;
@@ -1895,28 +2142,39 @@ const renderFetchSuccess = (effect) => Effect.suspend(() => {
1895
2142
  onSuccess: captured
1896
2143
  });
1897
2144
  });
1898
- const isWorkerOptions = (options) => typeof options === "object" && options !== null && ("eventLayer" in options || "fetch" in options || "queue" in options || "rpc" in options);
2145
+ const isWorkerOptions = (options) => !Effect.isEffect(options);
2146
+ /**
2147
+ * Drains buffered OTLP telemetry once the fetch handler has produced its
2148
+ * response.
2149
+ *
2150
+ * The flush is handed to `ctx.waitUntil` so it never delays the response
2151
+ * (including streaming bodies still being consumed). It is a no-op when the
2152
+ * context does not contain an `OtlpExporter.Flusher`.
2153
+ */
2154
+ const scheduleTelemetryFlush = Effect.flatMap(Effect.serviceOption(OtlpExporter.Flusher), Option.match({
2155
+ onNone: () => Effect.void,
2156
+ onSome: (flusher) => Effect.flatMap(WorkerContext, (workerContext) => workerContext.waitUntil(flusher.flush))
2157
+ }));
1899
2158
  function make$9(layer, optionsOrFetch) {
1900
2159
  const options = isWorkerOptions(optionsOrFetch) ? optionsOrFetch : { fetch: optionsOrFetch };
1901
2160
  class EffectWorker extends WorkerEntrypoint {
1902
2161
  runtime;
1903
2162
  constructor(ctx, env) {
1904
2163
  super(ctx, env);
1905
- let runWaitUntilEffect = () => Promise.reject(/* @__PURE__ */ new Error("WorkerContext runtime is not initialized"));
1906
- const services = Layer.mergeAll(layer$10, Layer.succeed(ExecutionContext, ctx), ConfigProvider.layer(Effect.succeed(WorkerConfig.providerFromEnv(env))), Layer.succeed(WorkerContext, fromExecutionContext(ctx, (effect) => runWaitUntilEffect(effect))), Layer.succeed(WorkerEnvironment, env));
1907
- const runtimeLayer = provideEntrypointServices(layer, services);
1908
- this.runtime = ManagedRuntime.make(runtimeLayer);
1909
- runWaitUntilEffect = (effect) => this.runtime.runPromiseExit(effect);
2164
+ this.runtime = makeEntrypointRuntime(layer, env, Layer.mergeAll(Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx))));
1910
2165
  }
1911
2166
  [RunSymbol$1](effect, runOptions = {}) {
1912
- const effectWithEventLayer = runOptions.eventLayer === false || options.eventLayer === void 0 ? effect : effect.pipe(Effect.provide(options.eventLayer, { local: true }));
1913
- return this.runtime.runPromise(Effect.scoped(effectWithEventLayer));
2167
+ return runEventPromise(this.runtime, effect, runOptions.eventLayer === false ? void 0 : options.eventLayer);
1914
2168
  }
1915
2169
  fetch(request) {
2170
+ return this[FetchSymbol](request);
2171
+ }
2172
+ [FetchSymbol](request, requestContext) {
1916
2173
  const fetchHandler = options.fetch;
1917
2174
  if (fetchHandler === void 0) return Promise.resolve(new Response("Not Found", { status: 404 }));
1918
- const requestServices = Layer.mergeAll(Layer.succeed(NativeRequest, request), Layer.succeed(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(request)));
1919
- return this[RunSymbol$1](renderFetchSuccess(fetchHandler).pipe(Effect.provide(requestServices)));
2175
+ const ctx = requestContext ?? this.ctx;
2176
+ const requestServices = Layer.mergeAll(Layer.succeed(NativeRequest, request), Layer.succeed(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(request)), Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx)));
2177
+ return this[RunSymbol$1](renderFetchSuccess(fetchHandler).pipe(Effect.tap(() => scheduleTelemetryFlush), Effect.provide(requestServices)));
1920
2178
  }
1921
2179
  queue(batch) {
1922
2180
  const queueHandler = options.queue;
@@ -1928,13 +2186,29 @@ function make$9(layer, optionsOrFetch) {
1928
2186
  defineEntrypointRpcMethods("Worker", EffectWorker.prototype, options.rpc, reservedMethodNames$2, (self, effect) => self[RunSymbol$1](effect));
1929
2187
  return assumeEntrypointClass(EffectWorker);
1930
2188
  }
2189
+ /**
2190
+ * Creates an `ExportedHandler`-compatible `{ fetch }` object backed by
2191
+ * {@link make}.
2192
+ *
2193
+ * The Effect runtime is cached per `env` identity, so the user layer builds
2194
+ * once per isolate instead of once per request. `ExecutionContext`-backed
2195
+ * services (`Worker.ExecutionContext`, `Worker.WorkerContext`) are still
2196
+ * provided fresh for every request. Layer finalizers do not run when the
2197
+ * isolate is evicted; Cloudflare provides no shutdown hook. Use `eventLayer`
2198
+ * for resources that must be finalized per event.
2199
+ */
1931
2200
  const makeFetchHandler = (layer, options) => {
1932
2201
  const WorkerClass = make$9(layer, options);
1933
- return { fetch: (request, env, ctx) => Promise.resolve(new WorkerClass(ctx, env).fetch(request)) };
2202
+ const instances = /* @__PURE__ */ new WeakMap();
2203
+ return { fetch: (request, env, ctx) => {
2204
+ let instance = instances.get(env);
2205
+ if (instance === void 0) {
2206
+ instance = new WorkerClass(ctx, env);
2207
+ instances.set(env, instance);
2208
+ }
2209
+ return instance[FetchSymbol](request, ctx);
2210
+ } };
1934
2211
  };
1935
- const Tag$10 = Tag$11;
1936
- const method$2 = method$3;
1937
- const implement$4 = implement$5;
1938
2212
  //#endregion
1939
2213
  //#region src/DurableObjectNamespace.ts
1940
2214
  var DurableObjectNamespace_exports = /* @__PURE__ */ __exportAll({
@@ -1949,11 +2223,19 @@ const expectedDurableObjectNamespace = "Durable Object namespace binding with ge
1949
2223
  /**
1950
2224
  * Failure raised when invoking an RPC method on a Durable Object stub.
1951
2225
  */
1952
- var DurableObjectRpcError = class extends Data.TaggedError("DurableObjectRpcError") {};
2226
+ var DurableObjectRpcError = class extends Data.TaggedError("DurableObjectRpcError") {
2227
+ get message() {
2228
+ return `Durable Object RPC method "${this.method}" failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
2229
+ }
2230
+ };
1953
2231
  /**
1954
2232
  * Failure raised when forwarding a request to a Durable Object stub.
1955
2233
  */
1956
- var DurableObjectFetchError = class extends Data.TaggedError("DurableObjectFetchError") {};
2234
+ var DurableObjectFetchError = class extends Data.TaggedError("DurableObjectFetchError") {
2235
+ get message() {
2236
+ return `Durable Object fetch failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
2237
+ }
2238
+ };
1957
2239
  const hasFunction$2 = (value, key) => typeof Reflect.get(value, key) === "function";
1958
2240
  const isDurableObjectNamespaceClient = (value) => typeof value === "object" && value !== null && hasFunction$2(value, "getByName") && hasFunction$2(value, "get") && hasFunction$2(value, "idFromName") && hasFunction$2(value, "idFromString") && hasFunction$2(value, "newUniqueId") && hasFunction$2(value, "jurisdiction");
1959
2241
  const makeClient$7 = (definition) => {
@@ -1971,7 +2253,7 @@ const makeClient$7 = (definition) => {
1971
2253
  cause
1972
2254
  })
1973
2255
  });
1974
- const rpc = (stub, method, ...args) => Effect.gen(function* () {
2256
+ const rpc = Effect.fn("DurableObjectNamespace.rpc")(function* (stub, method, ...args) {
1975
2257
  const methodName = String(method);
1976
2258
  const encodedArgs = definition.definition === void 0 ? args : yield* encodeArgs(definition.definition, methodName, args).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1977
2259
  binding: definition.binding,
@@ -1984,7 +2266,7 @@ const makeClient$7 = (definition) => {
1984
2266
  cause
1985
2267
  }));
1986
2268
  });
1987
- const decodeSuccess$1 = (methodName, value) => Effect.gen(function* () {
2269
+ const decodeSuccess$1 = Effect.fn("DurableObjectNamespace.decodeSuccess")(function* (methodName, value) {
1988
2270
  if (definition.definition === void 0) return value;
1989
2271
  return yield* decodeSuccess(definition.definition, methodName, value).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1990
2272
  binding: definition.binding,
@@ -1992,7 +2274,7 @@ const makeClient$7 = (definition) => {
1992
2274
  cause
1993
2275
  })));
1994
2276
  });
1995
- const call = (stub, method, ...args) => Effect.gen(function* () {
2277
+ const call = Effect.fn("DurableObjectNamespace.call")(function* (stub, method, ...args) {
1996
2278
  const methodName = String(method);
1997
2279
  const value = yield* resolve(yield* rpc(stub, method, ...args)).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1998
2280
  binding: definition.binding,
@@ -2001,7 +2283,7 @@ const makeClient$7 = (definition) => {
2001
2283
  })));
2002
2284
  return yield* decodeSuccess$1(methodName, value);
2003
2285
  });
2004
- const scopedCall = (stub, method, ...args) => Effect.gen(function* () {
2286
+ const scopedCall = Effect.fn("DurableObjectNamespace.scopedCall")(function* (stub, method, ...args) {
2005
2287
  const methodName = String(method);
2006
2288
  const result = yield* rpc(stub, method, ...args);
2007
2289
  const value = yield* scoped(result);
@@ -2024,11 +2306,11 @@ const makeClient$7 = (definition) => {
2024
2306
  rpc,
2025
2307
  call,
2026
2308
  scopedCall,
2027
- unsafeRaw: Effect.succeed(namespace)
2309
+ rawUnsafe: Effect.succeed(namespace)
2028
2310
  });
2029
2311
  };
2030
2312
  };
2031
- const layer$9 = (tag, definition) => layer$20(tag, definition.binding, (value) => isDurableObjectNamespaceClient(value), makeClient$7(definition), { expected: expectedDurableObjectNamespace });
2313
+ const layer$9 = (tag, definition) => layer$19(tag, definition.binding, (value) => isDurableObjectNamespaceClient(value), makeClient$7(definition), { expected: expectedDurableObjectNamespace });
2032
2314
  const makeDirectMethods = (rpcDefinition, helpers) => {
2033
2315
  const methods = {};
2034
2316
  if (rpcDefinition !== void 0) {
@@ -2053,10 +2335,10 @@ const makeDirectMethods = (rpcDefinition, helpers) => {
2053
2335
  //#region src/DurableObjectDefinition.ts
2054
2336
  var DurableObjectDefinition_exports = /* @__PURE__ */ __exportAll({
2055
2337
  DurableObject: () => DurableObject$1,
2056
- Tag: () => Tag$9,
2057
- implement: () => implement$3,
2338
+ Tag: () => Tag$8,
2339
+ implement: () => implement$2,
2058
2340
  make: () => make$8,
2059
- method: () => method$1
2341
+ method: () => method
2060
2342
  });
2061
2343
  const reservedMethodNames$1 = /* @__PURE__ */ new Set([
2062
2344
  "constructor",
@@ -2070,7 +2352,7 @@ const reservedMethodNames$1 = /* @__PURE__ */ new Set([
2070
2352
  /**
2071
2353
  * Defines a single RPC method schema in a Durable Object definition.
2072
2354
  */
2073
- const method$1 = method$4;
2355
+ const method = method$2;
2074
2356
  /**
2075
2357
  * Creates a Durable Object RPC definition plus implementation/binding helpers.
2076
2358
  *
@@ -2092,47 +2374,48 @@ const makeDefinition$2 = (id, methods) => {
2092
2374
  rpc: wrapHandlers(definition, options.rpc)
2093
2375
  }) });
2094
2376
  };
2095
- const make$8 = (id, methods) => Tag$9()(id, methods);
2096
- const Tag$9 = () => (id, methods) => {
2377
+ const make$8 = (id, methods) => Tag$8()(id, methods);
2378
+ const Tag$8 = () => (id, methods) => {
2097
2379
  const definition = makeDefinition$2(id, methods);
2098
- const tag = Context.Service()(id);
2380
+ const serviceKey = `effect-cf/DurableObject/${id}`;
2381
+ const tag = Context.Service()(serviceKey);
2099
2382
  const bindingDefinition = (binding) => ({
2100
2383
  ...binding,
2101
2384
  definition
2102
2385
  });
2103
2386
  const layer = (binding) => layer$9(tag, bindingDefinition(binding));
2104
- const newUniqueId = Effect.fnUntraced(function* (options) {
2387
+ const newUniqueId = Effect.fn("DurableObject.newUniqueId")(function* (options) {
2105
2388
  return yield* (yield* tag).newUniqueId(options);
2106
2389
  });
2107
- const idFromName = Effect.fnUntraced(function* (name) {
2390
+ const idFromName = Effect.fn("DurableObject.idFromName")(function* (name) {
2108
2391
  return yield* (yield* tag).idFromName(name);
2109
2392
  });
2110
- const idFromString = Effect.fnUntraced(function* (value) {
2393
+ const idFromString = Effect.fn("DurableObject.idFromString")(function* (value) {
2111
2394
  return yield* (yield* tag).idFromString(value);
2112
2395
  });
2113
- const get = Effect.fnUntraced(function* (objectId, options) {
2396
+ const get = Effect.fn("DurableObject.get")(function* (objectId, options) {
2114
2397
  return yield* (yield* tag).get(objectId, options);
2115
2398
  });
2116
- const getByName = Effect.fnUntraced(function* (name, options) {
2399
+ const getByName = Effect.fn("DurableObject.getByName")(function* (name, options) {
2117
2400
  return yield* (yield* tag).getByName(name, options);
2118
2401
  });
2119
- const jurisdiction = Effect.fnUntraced(function* (value) {
2402
+ const jurisdiction = Effect.fn("DurableObject.jurisdiction")(function* (value) {
2120
2403
  return yield* (yield* tag).jurisdiction(value);
2121
2404
  });
2122
- const fetch = (stub, input, init) => Effect.gen(function* () {
2405
+ const fetch = Effect.fn("DurableObject.fetch")(function* (stub, input, init) {
2123
2406
  return yield* (yield* tag).fetch(stub, input, init);
2124
2407
  });
2125
- const rpc = (stub, method, ...args) => Effect.gen(function* () {
2408
+ const rpc = Effect.fn("DurableObject.rpc")(function* (stub, method, ...args) {
2126
2409
  return yield* (yield* tag).rpc(stub, method, ...args);
2127
2410
  });
2128
- const call = (stub, method, ...args) => Effect.gen(function* () {
2411
+ const call = Effect.fn("DurableObject.call")(function* (stub, method, ...args) {
2129
2412
  return yield* (yield* tag).call(stub, method, ...args);
2130
2413
  });
2131
- const scopedCall = (stub, method, ...args) => Effect.gen(function* () {
2414
+ const scopedCall = Effect.fn("DurableObject.scopedCall")(function* (stub, method, ...args) {
2132
2415
  return yield* (yield* tag).scopedCall(stub, method, ...args);
2133
2416
  });
2134
- const unsafeRaw = Effect.fnUntraced(function* () {
2135
- return yield* (yield* tag).unsafeRaw;
2417
+ const rawUnsafe = Effect.fnUntraced(function* () {
2418
+ return yield* (yield* tag).rawUnsafe;
2136
2419
  });
2137
2420
  const directMethods = makeDirectMethods(definition, {
2138
2421
  call,
@@ -2155,10 +2438,10 @@ const Tag$9 = () => (id, methods) => {
2155
2438
  rpc,
2156
2439
  call,
2157
2440
  scopedCall,
2158
- unsafeRaw
2441
+ rawUnsafe
2159
2442
  });
2160
2443
  };
2161
- const DurableObject$1 = Tag$9;
2444
+ const DurableObject$1 = Tag$8;
2162
2445
  const wrapHandlers = (definition, handlers) => {
2163
2446
  const wrapped = {};
2164
2447
  for (const key of Object.keys(definition.methods)) {
@@ -2174,7 +2457,7 @@ const wrapHandlers = (definition, handlers) => {
2174
2457
  /**
2175
2458
  * Helper for implementing handlers with the exact method shape of a definition.
2176
2459
  */
2177
- const implement$3 = (_definition, handlers) => handlers;
2460
+ const implement$2 = (_definition, handlers) => handlers;
2178
2461
  //#endregion
2179
2462
  //#region src/DurableObject.ts
2180
2463
  var DurableObject_exports = /* @__PURE__ */ __exportAll({
@@ -2201,15 +2484,12 @@ const make$7 = (layer, options = {}) => {
2201
2484
  runtime;
2202
2485
  constructor(state, env) {
2203
2486
  super(state, env);
2204
- const services = Layer.mergeAll(layer$10, ConfigProvider.layer(Effect.succeed(WorkerConfig.providerFromEnv(env))), Layer.succeed(DurableObjectState, fromDurableObjectState(state)), Layer.succeed(WorkerEnvironment, env));
2205
- const runtimeLayer = provideEntrypointServices(layer, services);
2206
- this.runtime = ManagedRuntime.make(runtimeLayer);
2487
+ this.runtime = makeEntrypointRuntime(layer, env, Layer.succeed(DurableObjectState, fromDurableObjectState(state)));
2207
2488
  const initialize = options.initialize;
2208
2489
  if (initialize !== void 0) state.waitUntil(this[RunSymbol](initialize, { eventLayer: false }));
2209
2490
  }
2210
2491
  [RunSymbol](effect, runOptions = {}) {
2211
- const effectWithEventLayer = runOptions.eventLayer === false || options.eventLayer === void 0 ? effect : effect.pipe(Effect.provide(options.eventLayer, { local: true }));
2212
- return this.runtime.runPromise(Effect.scoped(effectWithEventLayer));
2492
+ return runEventPromise(this.runtime, effect, runOptions.eventLayer === false ? void 0 : options.eventLayer);
2213
2493
  }
2214
2494
  fetch(request) {
2215
2495
  const fetchHandler = options.fetch;
@@ -2239,9 +2519,6 @@ const make$7 = (layer, options = {}) => {
2239
2519
  defineEntrypointRpcMethods("Durable Object", EffectDurableObject.prototype, options.rpc, reservedMethodNames, (self, effect) => self[RunSymbol](effect));
2240
2520
  return assumeEntrypointClass(EffectDurableObject);
2241
2521
  };
2242
- const Tag$8 = Tag$9;
2243
- const method = method$1;
2244
- const implement$2 = implement$3;
2245
2522
  //#endregion
2246
2523
  //#region src/DurableObjectAlarm.ts
2247
2524
  var DurableObjectAlarm_exports = /* @__PURE__ */ __exportAll({
@@ -2271,11 +2548,31 @@ CREATE INDEX IF NOT EXISTS idx_effect_cf_scheduled_alarms_run_at_storage_id
2271
2548
  const DEFAULT_PROCESS_DUE_ALARMS_LIMIT = 100;
2272
2549
  const DEFAULT_PROCESS_DUE_ALARMS_FAILURE_RESCHEDULE_AFTER = "30 seconds";
2273
2550
  const getScheduledEventId = (input) => `effect-cf-alarm:${encodeURIComponent(input.tag)}:${encodeURIComponent(input.id)}`;
2274
- var InvalidAlarmRefError = class extends Data.TaggedError("InvalidAlarmRefError") {};
2275
- var InvalidAlarmPayloadError = class extends Data.TaggedError("InvalidAlarmPayloadError") {};
2276
- var InvalidRepeatEveryError = class extends Data.TaggedError("InvalidRepeatEveryError") {};
2277
- var InvalidProcessDueAlarmsOptionsError = class extends Data.TaggedError("InvalidProcessDueAlarmsOptionsError") {};
2278
- var StoredAlarmDecodeError = class extends Data.TaggedError("StoredAlarmDecodeError") {};
2551
+ var InvalidAlarmRefError = class extends Data.TaggedError("InvalidAlarmRefError") {
2552
+ get message() {
2553
+ return `Invalid Durable Object alarm ref: ${causeMessage(this.cause)}`;
2554
+ }
2555
+ };
2556
+ var InvalidAlarmPayloadError = class extends Data.TaggedError("InvalidAlarmPayloadError") {
2557
+ get message() {
2558
+ return `Invalid Durable Object alarm payload: ${causeMessage(this.cause)}`;
2559
+ }
2560
+ };
2561
+ var InvalidRepeatEveryError = class extends Data.TaggedError("InvalidRepeatEveryError") {
2562
+ get message() {
2563
+ return `Invalid Durable Object alarm repeatEvery: ${causeMessage(this.cause)}`;
2564
+ }
2565
+ };
2566
+ var InvalidProcessDueAlarmsOptionsError = class extends Data.TaggedError("InvalidProcessDueAlarmsOptionsError") {
2567
+ get message() {
2568
+ return `Invalid processDueAlarms options: ${causeMessage(this.cause)}`;
2569
+ }
2570
+ };
2571
+ var StoredAlarmDecodeError = class extends Data.TaggedError("StoredAlarmDecodeError") {
2572
+ get message() {
2573
+ return `Failed to decode stored alarm "${this.storageId}": ${causeMessage(this.cause)}`;
2574
+ }
2575
+ };
2279
2576
  /**
2280
2577
  * Events handled by `processDueAlarms`.
2281
2578
  *
@@ -2319,7 +2616,7 @@ const toRepeatEveryMillis = (input) => {
2319
2616
  if (input === void 0) return Effect.succeed(null);
2320
2617
  return Effect.try({
2321
2618
  try: () => {
2322
- const millis = Duration.toMillis(Duration.fromInputUnsafe(input));
2619
+ const millis = Duration.toMillis(input);
2323
2620
  if (!Number.isFinite(millis) || millis <= 0) throw new Error("Alarm repeatEvery must be a positive finite duration");
2324
2621
  return Math.ceil(millis);
2325
2622
  },
@@ -2335,7 +2632,7 @@ const toAlarmDue = (row) => Effect.gen(function* () {
2335
2632
  _tag: "AlarmDue",
2336
2633
  id: row.alarm_id,
2337
2634
  payload: yield* decodeStoredPayload(row),
2338
- scheduledAt: DateTime.toUtc(DateTime.makeUnsafe(row.run_at)),
2635
+ scheduledAt: DateTime.makeUnsafe(row.run_at),
2339
2636
  tag: row.tag
2340
2637
  });
2341
2638
  });
@@ -2346,7 +2643,7 @@ const getProcessLimit = (options) => {
2346
2643
  };
2347
2644
  const toFailureRescheduleMillis = (input) => Effect.try({
2348
2645
  try: () => {
2349
- const millis = Duration.toMillis(Duration.fromInputUnsafe(input));
2646
+ const millis = Duration.toMillis(input);
2350
2647
  if (!Number.isFinite(millis) || millis <= 0) throw new Error("Alarm failure rescheduleAfter must be a positive finite duration");
2351
2648
  return Math.ceil(millis);
2352
2649
  },
@@ -2644,7 +2941,7 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2644
2941
  connectionsById.get(clientId)?.socket.raw.close();
2645
2942
  }),
2646
2943
  clientIds: Effect.sync(() => clientIds),
2647
- initialMessage: Effect.succeed(Option.none()),
2944
+ initialMessage: Effect.succeedNone,
2648
2945
  supportsAck: true,
2649
2946
  supportsTransferables: false,
2650
2947
  supportsSpanPropagation: true
@@ -2659,7 +2956,7 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2659
2956
  const connection = register(socket);
2660
2957
  const decoded = yield* Effect.try({
2661
2958
  try: () => connection.parser.decode(normalizeMessage(message)),
2662
- catch: RpcMessage.ResponseDefectEncoded
2959
+ catch: (cause) => cause
2663
2960
  });
2664
2961
  const run = writeRequest;
2665
2962
  if (run === void 0) {
@@ -2667,9 +2964,9 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2667
2964
  return;
2668
2965
  }
2669
2966
  for (const current of decoded) yield* run(connection.id, current);
2670
- }).pipe(Effect.catch((error) => {
2967
+ }).pipe(Effect.catch((cause) => {
2671
2968
  const connection = register(socket);
2672
- return send(connection, error);
2969
+ return Predicate.isTagged(cause, "MaxBufferSizeExceeded") ? Effect.ignore(connection.socket.close(1009, String(cause))) : send(connection, RpcMessage.ResponseDefectEncoded(cause));
2673
2970
  })),
2674
2971
  close: unregister,
2675
2972
  error: (socket, error) => Effect.gen(function* () {
@@ -2710,7 +3007,7 @@ const layer$7 = (options) => Layer.unwrap(Effect.gen(function* () {
2710
3007
  const state = yield* DurableObjectState;
2711
3008
  return SqliteClient.layer({
2712
3009
  ...options,
2713
- db: state.raw.storage.sql
3010
+ storage: state.raw.storage
2714
3011
  });
2715
3012
  }));
2716
3013
  //#endregion
@@ -2743,7 +3040,14 @@ const sendLimits = {
2743
3040
  /** Allowlisted custom headers, excluding `X-` prefixed headers. */
2744
3041
  maxAllowlistHeaders: 20
2745
3042
  };
2746
- /** Error codes reported by Cloudflare Email Sending. */
3043
+ /**
3044
+ * Error codes reported by Cloudflare Email Sending.
3045
+ *
3046
+ * Surfaced on {@link EmailOperationError} `code` on a best-effort basis: the
3047
+ * runtime attaches them as a non-standard `code` property on thrown errors,
3048
+ * which may be missing depending on the runtime or dev-time proxying
3049
+ * (miniflare remote bindings serialize errors and can strip it).
3050
+ */
2747
3051
  const emailErrorCodes = [
2748
3052
  "E_VALIDATION_ERROR",
2749
3053
  "E_FIELD_MISSING",
@@ -2767,9 +3071,24 @@ const emailErrorCodes = [
2767
3071
  "E_HEADERS_TOO_MANY"
2768
3072
  ];
2769
3073
  /** Error raised when a Cloudflare Send Email operation fails. */
2770
- var EmailOperationError = class extends Data.TaggedError("EmailOperationError") {};
3074
+ var EmailOperationError = class extends Data.TaggedError("EmailOperationError") {
3075
+ get message() {
3076
+ const code = this.code === void 0 ? "" : ` (${this.code})`;
3077
+ return `Email ${this.operation} failed for binding "${this.binding}"${code}: ${causeMessage(this.cause)}`;
3078
+ }
3079
+ };
2771
3080
  /** Error raised when a message violates documented Cloudflare Email Sending limits. */
2772
- var EmailValidationError = class extends Data.TaggedError("EmailValidationError") {};
3081
+ var EmailValidationError = class extends Data.TaggedError("EmailValidationError") {
3082
+ get message() {
3083
+ return `Email ${this.operation} for binding "${this.binding}" failed validation: ${violationsMessage(this.violations)}`;
3084
+ }
3085
+ };
3086
+ /**
3087
+ * Best-effort extraction of the Cloudflare error `code` from a thrown error.
3088
+ * Returns `undefined` when the property is absent — e.g. when a dev-time
3089
+ * proxy such as a miniflare remote binding (`"remote": true`) serializes the
3090
+ * error and strips non-standard properties.
3091
+ */
2773
3092
  const emailErrorCode = (cause) => {
2774
3093
  if (typeof cause !== "object" || cause === null) return;
2775
3094
  const code = Reflect.get(cause, "code");
@@ -2939,18 +3258,16 @@ const isEmailBinding = (value) => {
2939
3258
  const makeClient$6 = (definition, options) => (email) => {
2940
3259
  const runtime = email;
2941
3260
  const validate = options?.validate ?? true;
2942
- const send = ((message) => {
2943
- const dispatch = () => tryEmailPromise(definition.binding, "send", () => runtime.send(message));
2944
- if (!validate || !isEmailMessageBuilder(message)) return dispatch();
2945
- return validateSendInput(definition.binding, "send", message).pipe(Effect.flatMap(dispatch));
2946
- });
2947
3261
  return {
2948
3262
  definition,
2949
- send,
2950
- unsafeRaw: Effect.succeed(email)
3263
+ send: Effect.fn("Email.send")(function* (message) {
3264
+ if (validate && isEmailMessageBuilder(message)) yield* validateSendInput(definition.binding, "send", message);
3265
+ return yield* tryEmailPromise(definition.binding, "send", () => runtime.send(message));
3266
+ }),
3267
+ rawUnsafe: Effect.succeed(email)
2951
3268
  };
2952
3269
  };
2953
- const layer$6 = (tag, definition) => layer$20(tag, definition.binding, isEmailBinding, makeClient$6(definition, definition.send), { expected: expectedSendEmailBinding });
3270
+ const layer$6 = (tag, definition) => layer$19(tag, definition.binding, isEmailBinding, makeClient$6(definition, definition.send), { expected: expectedSendEmailBinding });
2954
3271
  const make$6 = (id) => Tag$7()(id);
2955
3272
  const Tag$7 = () => (id) => {
2956
3273
  const tag = Context.Service()(id);
@@ -2977,9 +3294,9 @@ const isHyperdrive = (value) => {
2977
3294
  const makeClient$5 = (definition) => (hyperdrive) => ({
2978
3295
  definition,
2979
3296
  connectionString: hyperdrive.connectionString,
2980
- unsafeRaw: Effect.succeed(hyperdrive)
3297
+ rawUnsafe: Effect.succeed(hyperdrive)
2981
3298
  });
2982
- const layer$5 = (tag, definition) => layer$20(tag, definition.binding, isHyperdrive, makeClient$5(definition), { expected: expectedHyperdrive });
3299
+ const layer$5 = (tag, definition) => layer$19(tag, definition.binding, isHyperdrive, makeClient$5(definition), { expected: expectedHyperdrive });
2983
3300
  const make$5 = (id) => Tag$6()(id);
2984
3301
  const Tag$6 = () => (id) => {
2985
3302
  const tag = Context.Service()(id);
@@ -2993,6 +3310,7 @@ const Tag$6 = () => (id) => {
2993
3310
  //#region src/Images.ts
2994
3311
  var Images_exports = /* @__PURE__ */ __exportAll({
2995
3312
  ImagesOperationError: () => ImagesOperationError,
3313
+ Step: () => Step,
2996
3314
  Tag: () => Tag$5,
2997
3315
  draw: () => draw,
2998
3316
  empty: () => empty,
@@ -3002,30 +3320,23 @@ var Images_exports = /* @__PURE__ */ __exportAll({
3002
3320
  makeClient: () => makeClient$4,
3003
3321
  transform: () => transform
3004
3322
  });
3005
- const TypeId = "effect-cf/Images/Steps";
3323
+ const TypeId = "~effect-cf/Images/Steps";
3006
3324
  const expectedImagesBinding = "Images binding with info() and input()";
3007
3325
  /** Error raised when a Cloudflare Images operation fails. */
3008
- var ImagesOperationError = class extends Data.TaggedError("ImagesOperationError") {};
3326
+ var ImagesOperationError = class extends Data.TaggedError("ImagesOperationError") {
3327
+ get message() {
3328
+ return `Images ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
3329
+ }
3330
+ };
3331
+ const Step = Data.taggedEnum();
3009
3332
  const makeSteps = (steps) => ({
3010
3333
  [TypeId]: TypeId,
3011
3334
  steps
3012
3335
  });
3013
3336
  /** Empty Images transformation pipeline. */
3014
3337
  const empty = makeSteps([]);
3015
- function transform(stepsOrTransform, transformValue) {
3016
- if (transformValue === void 0) return (steps) => transform(steps, stepsOrTransform);
3017
- return makeSteps([...stepsOrTransform.steps, {
3018
- _tag: "Transform",
3019
- transform: transformValue
3020
- }]);
3021
- }
3022
- function draw(stepsOrDraw, drawValue) {
3023
- if (drawValue === void 0) return (steps) => draw(steps, stepsOrDraw);
3024
- return makeSteps([...stepsOrDraw.steps, {
3025
- _tag: "Draw",
3026
- ...drawValue
3027
- }]);
3028
- }
3338
+ const transform = Function$1.dual(2, (steps, transformValue) => makeSteps([...steps.steps, Step.Transform({ transform: transformValue })]));
3339
+ const draw = Function$1.dual(2, (steps, drawValue) => makeSteps([...steps.steps, Step.Draw(drawValue)]));
3029
3340
  const imagesError = (binding, operation, cause) => new ImagesOperationError({
3030
3341
  binding,
3031
3342
  operation,
@@ -3039,7 +3350,7 @@ const tryImagesSync = (binding, operation, evaluate) => Effect.try({
3039
3350
  try: evaluate,
3040
3351
  catch: (cause) => imagesError(binding, operation, cause)
3041
3352
  });
3042
- const maybe$1 = (value) => value === null ? Option.none() : Option.some(value);
3353
+ const maybe = (value) => value === null ? Option.none() : Option.some(value);
3043
3354
  const hasFunction$1 = (value, key) => typeof Reflect.get(value, key) === "function";
3044
3355
  const isHostedImagesBinding = (value) => typeof value === "object" && value !== null && hasFunction$1(value, "image") && hasFunction$1(value, "upload") && hasFunction$1(value, "list");
3045
3356
  const isImagesBinding = (value) => typeof value === "object" && value !== null && hasFunction$1(value, "info") && hasFunction$1(value, "input");
@@ -3051,42 +3362,38 @@ const wrapResult = (binding, result) => ({
3051
3362
  });
3052
3363
  const wrapHandle = (binding, handle) => ({
3053
3364
  raw: handle,
3054
- details: tryImagesPromise(binding, "details", () => handle.details()).pipe(Effect.map(maybe$1)),
3055
- bytes: tryImagesPromise(binding, "bytes", () => handle.bytes()).pipe(Effect.map(maybe$1)),
3056
- update: (options) => tryImagesPromise(binding, "update", () => handle.update(options)),
3057
- delete: tryImagesPromise(binding, "delete", () => handle.delete())
3365
+ details: tryImagesPromise(binding, "details", () => handle.details()).pipe(Effect.map(maybe), Effect.withSpan("Images.details")),
3366
+ bytes: tryImagesPromise(binding, "bytes", () => handle.bytes()).pipe(Effect.map(maybe), Effect.withSpan("Images.bytes")),
3367
+ update: Effect.fn("Images.update")((options) => tryImagesPromise(binding, "update", () => handle.update(options))),
3368
+ delete: tryImagesPromise(binding, "delete", () => handle.delete()).pipe(Effect.withSpan("Images.delete"))
3058
3369
  });
3059
3370
  const wrapHosted = (binding, hosted) => ({
3060
3371
  image: (imageId) => wrapHandle(binding, hosted.image(imageId)),
3061
- upload: (image, options) => tryImagesPromise(binding, "upload", () => hosted.upload(image, options)),
3062
- list: (options) => tryImagesPromise(binding, "list", () => hosted.list(options)),
3063
- unsafeRaw: Effect.succeed(hosted)
3372
+ upload: Effect.fn("Images.upload")((image, options) => tryImagesPromise(binding, "upload", () => hosted.upload(image, options))),
3373
+ list: Effect.fn("Images.list")((options) => tryImagesPromise(binding, "list", () => hosted.list(options))),
3374
+ rawUnsafe: Effect.succeed(hosted)
3064
3375
  });
3065
3376
  const makeClient$4 = (definition) => (images) => {
3066
3377
  const input = (image, options) => tryImagesSync(definition.binding, "input", () => images.input(image, options));
3067
- const process = (steps, options) => Effect.gen(function* () {
3378
+ const process = Effect.fn("Images.process")(function* (steps, options) {
3068
3379
  let transformer = yield* input(options.stream, options.inputOptions);
3069
- for (const step of steps.steps) switch (step._tag) {
3070
- case "Draw":
3071
- transformer = yield* tryImagesSync(definition.binding, "draw", () => transformer.draw(step.image, step.options));
3072
- break;
3073
- case "Transform":
3074
- transformer = yield* tryImagesSync(definition.binding, "transform", () => transformer.transform(step.transform));
3075
- break;
3076
- }
3380
+ for (const step of steps.steps) transformer = yield* Step.$match(step, {
3381
+ Draw: (drawStep) => tryImagesSync(definition.binding, "draw", () => transformer.draw(drawStep.image, drawStep.options)),
3382
+ Transform: (transformStep) => tryImagesSync(definition.binding, "transform", () => transformer.transform(transformStep.transform))
3383
+ });
3077
3384
  const result = yield* tryImagesPromise(definition.binding, "output", () => transformer.output(options.outputOptions));
3078
3385
  return wrapResult(definition.binding, result);
3079
3386
  });
3080
3387
  return {
3081
3388
  definition,
3082
- info: (image, options) => tryImagesPromise(definition.binding, "info", () => images.info(image, options)),
3389
+ info: Effect.fn("Images.info")((image, options) => tryImagesPromise(definition.binding, "info", () => images.info(image, options))),
3083
3390
  input,
3084
3391
  process,
3085
3392
  hosted: isHostedImagesBinding(images.hosted) ? Option.some(wrapHosted(definition.binding, images.hosted)) : Option.none(),
3086
- unsafeRaw: Effect.succeed(images)
3393
+ rawUnsafe: Effect.succeed(images)
3087
3394
  };
3088
3395
  };
3089
- const layer$4 = (tag, definition) => layer$20(tag, definition.binding, isImagesBinding, makeClient$4(definition), { expected: expectedImagesBinding });
3396
+ const layer$4 = (tag, definition) => layer$19(tag, definition.binding, isImagesBinding, makeClient$4(definition), { expected: expectedImagesBinding });
3090
3397
  const make$4 = (id) => Tag$5()(id);
3091
3398
  const Tag$5 = () => (id) => {
3092
3399
  const tag = Context.Service()(id);
@@ -3107,9 +3414,11 @@ var Kv_exports = /* @__PURE__ */ __exportAll({
3107
3414
  });
3108
3415
  const expectedKvNamespace = "KV namespace binding with get(), put(), delete(), getWithMetadata(), and list()";
3109
3416
  /** Error raised when a KV operation fails. */
3110
- var KvOperationError = class extends Data.TaggedError("KvOperationError") {};
3111
- const maybeString = (value) => value === null || value === void 0 ? Option.none() : Option.some(value);
3112
- const maybeNumber = (value) => value === void 0 ? Option.none() : Option.some(value);
3417
+ var KvOperationError = class extends Data.TaggedError("KvOperationError") {
3418
+ get message() {
3419
+ return `Kv ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
3420
+ }
3421
+ };
3113
3422
  const kvError = (binding, operation, cause) => new KvOperationError({
3114
3423
  binding,
3115
3424
  operation,
@@ -3127,22 +3436,32 @@ const isKvNamespace = (value) => {
3127
3436
  const makeClient$3 = (definition) => {
3128
3437
  const encodeKey = Schema.encodeEffect(definition.key);
3129
3438
  const decodeKey = Schema.decodeUnknownEffect(definition.key);
3130
- const encodeValue = Schema.encodeEffect(Schema.fromJsonString(Schema.toCodecJson(definition.value)));
3131
- const decodeValue = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.toCodecJson(definition.value)));
3439
+ const jsonValue = Schema.fromJsonString(Schema.toCodecJson(definition.value));
3440
+ const encodeValue = Schema.encodeEffect(jsonValue);
3441
+ const decodeValue = Schema.decodeUnknownEffect(jsonValue);
3132
3442
  return (kv) => ({
3133
3443
  definition,
3134
- put: Effect.fnUntraced(function* (key, value, options) {
3444
+ put: Effect.fn("Kv.put", { attributes: {
3445
+ binding: definition.binding,
3446
+ operation: "put"
3447
+ } })(function* (key, value, options) {
3135
3448
  const keyEncoded = yield* encodeKey(key);
3136
3449
  const valueEncoded = yield* encodeValue(value);
3137
3450
  yield* tryKvPromise(definition.binding, "put", () => kv.put(keyEncoded, valueEncoded, options));
3138
3451
  }),
3139
- get: Effect.fnUntraced(function* (key) {
3452
+ get: Effect.fn("Kv.get", { attributes: {
3453
+ binding: definition.binding,
3454
+ operation: "get"
3455
+ } })(function* (key) {
3140
3456
  const keyEncoded = yield* encodeKey(key);
3141
3457
  const valueEncoded = yield* tryKvPromise(definition.binding, "get", () => kv.get(keyEncoded));
3142
3458
  if (valueEncoded === null) return Option.none();
3143
3459
  return yield* decodeValue(valueEncoded).pipe(Effect.map(Option.some));
3144
3460
  }),
3145
- getWithMetadata: Effect.fnUntraced(function* (key, metadataSchema) {
3461
+ getWithMetadata: Effect.fn("Kv.getWithMetadata", { attributes: {
3462
+ binding: definition.binding,
3463
+ operation: "getWithMetadata"
3464
+ } })(function* (key, metadataSchema) {
3146
3465
  const keyEncoded = yield* encodeKey(key);
3147
3466
  const result = yield* tryKvPromise(definition.binding, "getWithMetadata", () => kv.getWithMetadata(keyEncoded));
3148
3467
  if (result.value === null) return Option.none();
@@ -3151,10 +3470,13 @@ const makeClient$3 = (definition) => {
3151
3470
  return Option.some({
3152
3471
  value,
3153
3472
  metadata,
3154
- cacheStatus: maybeString(result.cacheStatus)
3473
+ cacheStatus: Option.fromNullishOr(result.cacheStatus)
3155
3474
  });
3156
3475
  }),
3157
- list: Effect.fnUntraced(function* (options) {
3476
+ list: Effect.fn("Kv.list", { attributes: {
3477
+ binding: definition.binding,
3478
+ operation: "list"
3479
+ } })(function* (options) {
3158
3480
  const { metadataSchema, ...kvOptions } = options ?? {};
3159
3481
  const result = yield* tryKvPromise(definition.binding, "list", () => kv.list(kvOptions));
3160
3482
  const keys = [];
@@ -3163,25 +3485,28 @@ const makeClient$3 = (definition) => {
3163
3485
  const decodedMetadata = key.metadata === void 0 ? Option.none() : metadataSchema === void 0 ? Option.some(key.metadata) : Option.some(yield* Schema.decodeUnknownEffect(metadataSchema)(key.metadata));
3164
3486
  keys.push({
3165
3487
  name: decodedName,
3166
- expiration: maybeNumber(key.expiration),
3488
+ expiration: Option.fromUndefinedOr(key.expiration),
3167
3489
  metadata: decodedMetadata
3168
3490
  });
3169
3491
  }
3170
3492
  return {
3171
3493
  keys,
3172
3494
  listComplete: result.list_complete,
3173
- cursor: maybeString("cursor" in result ? result.cursor : void 0),
3174
- cacheStatus: maybeString(result.cacheStatus)
3495
+ cursor: Option.fromNullishOr("cursor" in result ? result.cursor : void 0),
3496
+ cacheStatus: Option.fromNullishOr(result.cacheStatus)
3175
3497
  };
3176
3498
  }),
3177
- remove: Effect.fnUntraced(function* (key) {
3499
+ delete: Effect.fn("Kv.delete", { attributes: {
3500
+ binding: definition.binding,
3501
+ operation: "delete"
3502
+ } })(function* (key) {
3178
3503
  const keyEncoded = yield* encodeKey(key);
3179
3504
  yield* tryKvPromise(definition.binding, "delete", () => kv.delete(keyEncoded));
3180
3505
  }),
3181
- unsafeRaw: Effect.succeed(kv)
3506
+ rawUnsafe: Effect.succeed(kv)
3182
3507
  });
3183
3508
  };
3184
- const layer$3 = (tag, definition) => layer$20(tag, definition.binding, isKvNamespace, makeClient$3(definition), { expected: expectedKvNamespace });
3509
+ const layer$3 = (tag, definition) => layer$19(tag, definition.binding, isKvNamespace, makeClient$3(definition), { expected: expectedKvNamespace });
3185
3510
  const makeDefinition$1 = (id, definition) => {
3186
3511
  const kvDefinition = {
3187
3512
  id,
@@ -3217,7 +3542,11 @@ var R2_exports = /* @__PURE__ */ __exportAll({
3217
3542
  });
3218
3543
  const expectedR2Bucket = "R2 bucket binding with head(), get(), put(), createMultipartUpload(), resumeMultipartUpload(), delete(), and list()";
3219
3544
  /** Error raised when an R2 operation fails. */
3220
- var R2OperationError = class extends Data.TaggedError("R2OperationError") {};
3545
+ var R2OperationError = class extends Data.TaggedError("R2OperationError") {
3546
+ get message() {
3547
+ return `R2 ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
3548
+ }
3549
+ };
3221
3550
  const r2Error = (binding, operation, cause) => new R2OperationError({
3222
3551
  binding,
3223
3552
  operation,
@@ -3231,7 +3560,10 @@ const tryR2Sync = (binding, operation, evaluate) => Effect.try({
3231
3560
  try: evaluate,
3232
3561
  catch: (cause) => r2Error(binding, operation, cause)
3233
3562
  });
3234
- const maybe = (value) => value === null ? Option.none() : Option.some(value);
3563
+ const spanOptions$1 = (binding, operation) => ({ attributes: {
3564
+ binding,
3565
+ operation
3566
+ } });
3235
3567
  const isR2ObjectBody = (value) => "body" in value && typeof value.arrayBuffer === "function" && typeof value.bytes === "function" && typeof value.text === "function" && typeof value.json === "function" && typeof value.blob === "function";
3236
3568
  const wrapObjectBody = (binding, object) => ({
3237
3569
  key: object.key,
@@ -3252,11 +3584,11 @@ const wrapObjectBody = (binding, object) => ({
3252
3584
  get bodyUsed() {
3253
3585
  return object.bodyUsed;
3254
3586
  },
3255
- arrayBuffer: tryR2Promise(binding, "arrayBuffer", () => object.arrayBuffer()),
3256
- bytes: tryR2Promise(binding, "bytes", () => object.bytes()),
3257
- text: tryR2Promise(binding, "text", () => object.text()),
3258
- json: () => tryR2Promise(binding, "json", () => object.json()),
3259
- blob: tryR2Promise(binding, "blob", () => object.blob())
3587
+ arrayBuffer: tryR2Promise(binding, "arrayBuffer", () => object.arrayBuffer()).pipe(Effect.withSpan("R2.arrayBuffer", spanOptions$1(binding, "arrayBuffer"))),
3588
+ bytes: tryR2Promise(binding, "bytes", () => object.bytes()).pipe(Effect.withSpan("R2.bytes", spanOptions$1(binding, "bytes"))),
3589
+ text: tryR2Promise(binding, "text", () => object.text()).pipe(Effect.withSpan("R2.text", spanOptions$1(binding, "text"))),
3590
+ json: () => tryR2Promise(binding, "json", () => object.json()).pipe(Effect.withSpan("R2.json", spanOptions$1(binding, "json"))),
3591
+ blob: tryR2Promise(binding, "blob", () => object.blob()).pipe(Effect.withSpan("R2.blob", spanOptions$1(binding, "blob")))
3260
3592
  });
3261
3593
  const wrapGetResult = (binding, object) => {
3262
3594
  if (object === null || !isR2ObjectBody(object)) return object;
@@ -3272,33 +3604,33 @@ const makeClient$2 = (definition) => {
3272
3604
  raw: upload,
3273
3605
  key: upload.key,
3274
3606
  uploadId: upload.uploadId,
3275
- uploadPart: (partNumber, value, options) => tryR2Promise(definition.binding, "uploadPart", () => upload.uploadPart(partNumber, value, options)),
3276
- abort: tryR2Promise(definition.binding, "abortMultipartUpload", () => upload.abort()),
3277
- complete: (uploadedParts) => tryR2Promise(definition.binding, "completeMultipartUpload", () => upload.complete([...uploadedParts]))
3607
+ uploadPart: Effect.fn("R2.uploadPart", spanOptions$1(definition.binding, "uploadPart"))((partNumber, value, options) => tryR2Promise(definition.binding, "uploadPart", () => upload.uploadPart(partNumber, value, options))),
3608
+ abort: tryR2Promise(definition.binding, "abortMultipartUpload", () => upload.abort()).pipe(Effect.withSpan("R2.abortMultipartUpload", spanOptions$1(definition.binding, "abortMultipartUpload"))),
3609
+ complete: Effect.fn("R2.completeMultipartUpload", spanOptions$1(definition.binding, "completeMultipartUpload"))((uploadedParts) => tryR2Promise(definition.binding, "completeMultipartUpload", () => upload.complete([...uploadedParts])))
3278
3610
  });
3279
3611
  return (bucket) => {
3280
- const get = ((key, options) => tryR2Promise(definition.binding, "get", () => bucket.get(key, options)).pipe(Effect.map((object) => maybe(wrapGetResult(definition.binding, object)))));
3612
+ const get = Effect.fn("R2.get", spanOptions$1(definition.binding, "get"))((key, options) => tryR2Promise(definition.binding, "get", () => bucket.get(key, options)).pipe(Effect.map((object) => Option.fromNullOr(wrapGetResult(definition.binding, object)))));
3281
3613
  return {
3282
3614
  definition,
3283
- head: (key) => tryR2Promise(definition.binding, "head", () => bucket.head(key)).pipe(Effect.map(maybe)),
3615
+ head: Effect.fn("R2.head", spanOptions$1(definition.binding, "head"))((key) => tryR2Promise(definition.binding, "head", () => bucket.head(key)).pipe(Effect.map(Option.fromNullOr))),
3284
3616
  get,
3285
- put: ((key, value, options) => tryR2Promise(definition.binding, "put", () => bucket.put(key, value, options)).pipe(Effect.map((object) => {
3617
+ put: Effect.fn("R2.put", spanOptions$1(definition.binding, "put"))((key, value, options) => tryR2Promise(definition.binding, "put", () => bucket.put(key, value, options)).pipe(Effect.map((object) => {
3286
3618
  if (object === null) return Option.none();
3287
3619
  if (options !== void 0 && "onlyIf" in options) return Option.some(object);
3288
3620
  return object;
3289
3621
  }))),
3290
- createMultipartUpload: (key, options) => tryR2Promise(definition.binding, "createMultipartUpload", () => bucket.createMultipartUpload(key, options)).pipe(Effect.map(wrapUpload)),
3291
- resumeMultipartUpload: (key, uploadId) => tryR2Sync(definition.binding, "resumeMultipartUpload", () => wrapUpload(bucket.resumeMultipartUpload(key, uploadId))),
3292
- delete: (keys) => {
3622
+ createMultipartUpload: Effect.fn("R2.createMultipartUpload", spanOptions$1(definition.binding, "createMultipartUpload"))((key, options) => tryR2Promise(definition.binding, "createMultipartUpload", () => bucket.createMultipartUpload(key, options)).pipe(Effect.map(wrapUpload))),
3623
+ resumeMultipartUpload: Effect.fn("R2.resumeMultipartUpload", spanOptions$1(definition.binding, "resumeMultipartUpload"))((key, uploadId) => tryR2Sync(definition.binding, "resumeMultipartUpload", () => wrapUpload(bucket.resumeMultipartUpload(key, uploadId)))),
3624
+ delete: Effect.fn("R2.delete", spanOptions$1(definition.binding, "delete"))((keys) => {
3293
3625
  const nativeKeys = typeof keys === "string" ? keys : [...keys];
3294
3626
  return tryR2Promise(definition.binding, "delete", () => bucket.delete(nativeKeys));
3295
- },
3296
- list: (options) => tryR2Promise(definition.binding, "list", () => bucket.list(options)),
3297
- unsafeRaw: Effect.succeed(bucket)
3627
+ }),
3628
+ list: Effect.fn("R2.list", spanOptions$1(definition.binding, "list"))((options) => tryR2Promise(definition.binding, "list", () => bucket.list(options))),
3629
+ rawUnsafe: Effect.succeed(bucket)
3298
3630
  };
3299
3631
  };
3300
3632
  };
3301
- const layer$2 = (tag, definition) => layer$20(tag, definition.binding, isR2Bucket, makeClient$2(definition), { expected: expectedR2Bucket });
3633
+ const layer$2 = (tag, definition) => layer$19(tag, definition.binding, isR2Bucket, makeClient$2(definition), { expected: expectedR2Bucket });
3302
3634
  const make$3 = (id) => Tag$3()(id);
3303
3635
  const Tag$3 = () => (id) => {
3304
3636
  const tag = Context.Service()(id);
@@ -3309,17 +3641,83 @@ const Tag$3 = () => (id) => {
3309
3641
  });
3310
3642
  };
3311
3643
  //#endregion
3644
+ //#region src/Vectorize.ts
3645
+ var Vectorize_exports = /* @__PURE__ */ __exportAll({
3646
+ Tag: () => Tag$2,
3647
+ VectorizeOperationError: () => VectorizeOperationError,
3648
+ isVectorizeBinding: () => isVectorizeBinding,
3649
+ layer: () => layer$1,
3650
+ make: () => make$2,
3651
+ makeClient: () => makeClient$1
3652
+ });
3653
+ const expectedVectorizeBinding = "Vectorize index binding with describe(), query(), insert(), upsert(), deleteByIds(), and getByIds()";
3654
+ /** Error raised when a Vectorize operation fails. */
3655
+ var VectorizeOperationError = class extends Data.TaggedError("VectorizeOperationError") {
3656
+ get message() {
3657
+ return `Vectorize ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
3658
+ }
3659
+ };
3660
+ const vectorizeError = (binding, operation, cause) => new VectorizeOperationError({
3661
+ binding,
3662
+ operation,
3663
+ cause
3664
+ });
3665
+ const tryVectorizePromise = (binding, operation, evaluate) => Effect.tryPromise({
3666
+ try: evaluate,
3667
+ catch: (cause) => vectorizeError(binding, operation, cause)
3668
+ });
3669
+ const spanOptions = (binding, operation) => ({ attributes: {
3670
+ binding,
3671
+ operation
3672
+ } });
3673
+ const hasFunction = (value, key) => typeof Reflect.get(value, key) === "function";
3674
+ const isVectorizeBinding = (value) => typeof value === "object" && value !== null && hasFunction(value, "describe") && hasFunction(value, "query") && hasFunction(value, "insert") && hasFunction(value, "upsert") && hasFunction(value, "deleteByIds") && hasFunction(value, "getByIds");
3675
+ const makeClient$1 = (definition) => (index) => {
3676
+ const runtime = index;
3677
+ const deleteByIds = Effect.fn("Vectorize.deleteByIds", spanOptions(definition.binding, "deleteByIds"))((ids) => tryVectorizePromise(definition.binding, "deleteByIds", () => runtime.deleteByIds([...ids])));
3678
+ return {
3679
+ definition,
3680
+ describe: tryVectorizePromise(definition.binding, "describe", () => runtime.describe()).pipe(Effect.withSpan("Vectorize.describe", spanOptions(definition.binding, "describe"))),
3681
+ query: Effect.fn("Vectorize.query", spanOptions(definition.binding, "query"))((vector, options) => tryVectorizePromise(definition.binding, "query", () => runtime.query(vector, options))),
3682
+ queryById: Effect.fn("Vectorize.queryById", spanOptions(definition.binding, "queryById"))((vectorId, options) => runtime.queryById !== void 0 ? tryVectorizePromise(definition.binding, "queryById", () => runtime.queryById(vectorId, options)) : Effect.fail(vectorizeError(definition.binding, "queryById", /* @__PURE__ */ new TypeError("Vectorize binding does not expose queryById()")))),
3683
+ insert: Effect.fn("Vectorize.insert", spanOptions(definition.binding, "insert"))((vectors) => tryVectorizePromise(definition.binding, "insert", () => runtime.insert([...vectors]))),
3684
+ upsert: Effect.fn("Vectorize.upsert", spanOptions(definition.binding, "upsert"))((vectors) => tryVectorizePromise(definition.binding, "upsert", () => runtime.upsert([...vectors]))),
3685
+ deleteByIds,
3686
+ delete: deleteByIds,
3687
+ getByIds: Effect.fn("Vectorize.getByIds", spanOptions(definition.binding, "getByIds"))((ids) => tryVectorizePromise(definition.binding, "getByIds", () => runtime.getByIds([...ids]))),
3688
+ rawUnsafe: Effect.succeed(index)
3689
+ };
3690
+ };
3691
+ const layer$1 = (tag, definition) => layer$19(tag, definition.binding, isVectorizeBinding, makeClient$1(definition), { expected: expectedVectorizeBinding });
3692
+ const make$2 = (id) => Tag$2()(id);
3693
+ const Tag$2 = () => (id) => {
3694
+ const tag = Context.Service()(id);
3695
+ const makeLayer = (definition) => layer$1(tag, definition);
3696
+ return Object.assign(tag, {
3697
+ id,
3698
+ layer: makeLayer
3699
+ });
3700
+ };
3701
+ //#endregion
3312
3702
  //#region src/WorkflowBinding.ts
3313
3703
  var WorkflowBinding_exports = /* @__PURE__ */ __exportAll({
3314
3704
  WorkflowOperationError: () => WorkflowOperationError,
3315
3705
  WorkflowResultDecodeError: () => WorkflowResultDecodeError,
3316
3706
  isWorkflow: () => isWorkflow,
3317
- layer: () => layer$1,
3318
- makeClient: () => makeClient$1
3707
+ layer: () => layer,
3708
+ makeClient: () => makeClient
3319
3709
  });
3320
3710
  const expectedWorkflow = "Workflow binding with create(), createBatch(), and get()";
3321
- var WorkflowOperationError = class extends Data.TaggedError("WorkflowOperationError") {};
3322
- var WorkflowResultDecodeError = class extends Data.TaggedError("WorkflowResultDecodeError") {};
3711
+ var WorkflowOperationError = class extends Data.TaggedError("WorkflowOperationError") {
3712
+ get message() {
3713
+ return `Workflow ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
3714
+ }
3715
+ };
3716
+ var WorkflowResultDecodeError = class extends Data.TaggedError("WorkflowResultDecodeError") {
3717
+ get message() {
3718
+ return `Workflow result decode failed for binding "${this.binding}" instance "${this.instanceId}": ${causeMessage(this.cause)}`;
3719
+ }
3720
+ };
3323
3721
  const workflowError = (binding, operation, cause) => new WorkflowOperationError({
3324
3722
  binding,
3325
3723
  operation,
@@ -3334,7 +3732,7 @@ const isWorkflow = (value) => {
3334
3732
  const resource = value;
3335
3733
  return typeof resource.create === "function" && typeof resource.createBatch === "function" && typeof resource.get === "function";
3336
3734
  };
3337
- const makeClient$1 = (definition) => {
3735
+ const makeClient = (definition) => {
3338
3736
  const encodePayload = Schema.encodeEffect(definition.payload);
3339
3737
  const decodeResult = Schema.decodeUnknownEffect(definition.result);
3340
3738
  const wrapInstance = (raw) => {
@@ -3362,7 +3760,10 @@ const makeClient$1 = (definition) => {
3362
3760
  };
3363
3761
  };
3364
3762
  return (workflow) => ({
3365
- create: Effect.fnUntraced(function* (payload, options) {
3763
+ create: Effect.fn("WorkflowBinding.create", { attributes: {
3764
+ binding: definition.binding,
3765
+ operation: "create"
3766
+ } })(function* (payload, options) {
3366
3767
  const encoded = yield* encodePayload(payload);
3367
3768
  const raw = yield* tryWorkflowPromise(definition.binding, "create", () => workflow.create({
3368
3769
  ...options,
@@ -3370,7 +3771,10 @@ const makeClient$1 = (definition) => {
3370
3771
  }));
3371
3772
  return wrapInstance(raw);
3372
3773
  }),
3373
- createBatch: Effect.fnUntraced(function* (batch) {
3774
+ createBatch: Effect.fn("WorkflowBinding.createBatch", { attributes: {
3775
+ binding: definition.binding,
3776
+ operation: "createBatch"
3777
+ } })(function* (batch) {
3374
3778
  const encodedBatch = [];
3375
3779
  for (const item of batch) {
3376
3780
  const { payload, ...options } = item;
@@ -3382,17 +3786,17 @@ const makeClient$1 = (definition) => {
3382
3786
  return (yield* tryWorkflowPromise(definition.binding, "createBatch", () => workflow.createBatch(encodedBatch))).map(wrapInstance);
3383
3787
  }),
3384
3788
  get: (instanceId) => tryWorkflowPromise(definition.binding, "get", () => workflow.get(instanceId)).pipe(Effect.map(wrapInstance)),
3385
- unsafeRaw: Effect.succeed(workflow)
3789
+ rawUnsafe: Effect.succeed(workflow)
3386
3790
  });
3387
3791
  };
3388
- const layer$1 = (tag, definition) => layer$20(tag, definition.binding, (value) => isWorkflow(value), makeClient$1(definition), { expected: expectedWorkflow });
3792
+ const layer = (tag, definition) => layer$19(tag, definition.binding, (value) => isWorkflow(value), makeClient(definition), { expected: expectedWorkflow });
3389
3793
  //#endregion
3390
3794
  //#region src/WorkflowDefinition.ts
3391
3795
  var WorkflowDefinition_exports = /* @__PURE__ */ __exportAll({
3392
- Tag: () => Tag$2,
3796
+ Tag: () => Tag$1,
3393
3797
  Workflow: () => Workflow,
3394
3798
  implement: () => implement$1,
3395
- make: () => make$2
3799
+ make: () => make$1
3396
3800
  });
3397
3801
  const makeDefinition = (id, definition) => {
3398
3802
  const workflowDefinition = {
@@ -3400,13 +3804,13 @@ const makeDefinition = (id, definition) => {
3400
3804
  payload: definition.payload,
3401
3805
  result: definition.result
3402
3806
  };
3403
- return Object.assign(workflowDefinition, { make: (layer, options) => make$1(layer, { run: wrapHandler(workflowDefinition, options.run) }) });
3807
+ return Object.assign(workflowDefinition, { make: (layer, options) => make(layer, { run: wrapHandler(workflowDefinition, options.run) }) });
3404
3808
  };
3405
- const make$2 = (id, definition) => Tag$2()(id, definition);
3406
- const Tag$2 = () => (id, definition) => {
3809
+ const make$1 = (id, definition) => Tag$1()(id, definition);
3810
+ const Tag$1 = () => (id, definition) => {
3407
3811
  const workflowDefinition = makeDefinition(id, definition);
3408
- const tag = Context.Service()(id);
3409
- const layer = (binding) => layer$1(tag, {
3812
+ const tag = Context.Service()(`effect-cf/Workflow/${id}`);
3813
+ const layer$20 = (binding) => layer(tag, {
3410
3814
  ...binding,
3411
3815
  payload: definition.payload,
3412
3816
  result: definition.result
@@ -3420,26 +3824,24 @@ const Tag$2 = () => (id, definition) => {
3420
3824
  const get = Effect.fnUntraced(function* (instanceId) {
3421
3825
  return yield* (yield* tag).get(instanceId);
3422
3826
  });
3423
- const unsafeRaw = Effect.fnUntraced(function* () {
3424
- return yield* (yield* tag).unsafeRaw;
3425
- });
3827
+ const rawUnsafe = Effect.flatMap(tag, (workflow) => workflow.rawUnsafe);
3426
3828
  return Object.assign(tag, {
3427
3829
  id: workflowDefinition.id,
3428
3830
  payload: workflowDefinition.payload,
3429
3831
  result: workflowDefinition.result,
3430
3832
  make: workflowDefinition.make,
3431
- layer,
3833
+ layer: layer$20,
3432
3834
  create,
3433
3835
  createBatch,
3434
3836
  get,
3435
- unsafeRaw
3837
+ rawUnsafe
3436
3838
  });
3437
3839
  };
3438
- const Workflow = Tag$2;
3840
+ const Workflow = Tag$1;
3439
3841
  const wrapHandler = (definition, handler) => {
3440
3842
  const decodePayload = Schema.decodeUnknownEffect(definition.payload);
3441
3843
  const encodeResult = Schema.encodeEffect(definition.result);
3442
- return (payload) => Effect.gen(function* () {
3844
+ return Effect.fnUntraced(function* (payload) {
3443
3845
  const decodedPayload = yield* decodePayload(payload);
3444
3846
  const decodedEvent = {
3445
3847
  ...yield* WorkflowEvent$1,
@@ -3452,19 +3854,31 @@ const wrapHandler = (definition, handler) => {
3452
3854
  const implement$1 = (_definition, handler) => handler;
3453
3855
  //#endregion
3454
3856
  //#region src/Workflow.ts
3857
+ /**
3858
+ * Effect wrapper for Cloudflare Workflows entrypoints and bindings; distinct
3859
+ * from Effect's runtime-agnostic `effect/unstable/workflow` cluster module.
3860
+ */
3455
3861
  var Workflow_exports = /* @__PURE__ */ __exportAll({
3456
- Tag: () => Tag$1,
3862
+ Tag: () => Tag,
3457
3863
  WorkflowEvent: () => WorkflowEvent$1,
3458
3864
  WorkflowStep: () => WorkflowStep$1,
3459
3865
  WorkflowStepContext: () => WorkflowStepContext$1,
3866
+ WorkflowStepError: () => WorkflowStepError,
3460
3867
  implement: () => implement,
3461
- make: () => make$1,
3868
+ make: () => make,
3462
3869
  sleep: () => sleep,
3463
3870
  sleepUntil: () => sleepUntil,
3464
3871
  step: () => step,
3465
3872
  waitForEvent: () => waitForEvent
3466
3873
  });
3467
3874
  var WorkflowEvent$1 = class extends Context.Service()("effect-cf/WorkflowEvent") {};
3875
+ /** Failure raised when a Cloudflare Workflow step operation rejects. */
3876
+ var WorkflowStepError = class extends Data.TaggedError("WorkflowStepError") {
3877
+ get message() {
3878
+ const step = this.step === void 0 ? "" : ` in step "${this.step}"`;
3879
+ return `Workflow ${this.operation} failed${step}: ${causeMessage(this.cause)}`;
3880
+ }
3881
+ };
3468
3882
  var WorkflowStep$1 = class extends Context.Service()("effect-cf/WorkflowStep") {};
3469
3883
  var WorkflowStepContext$1 = class extends Context.Service()("effect-cf/WorkflowStepContext") {};
3470
3884
  const fromWorkflowEvent = (event) => ({
@@ -3482,35 +3896,47 @@ const fromWorkflowStep = (step, runPromise) => ({
3482
3896
  const rawStep = step;
3483
3897
  return config === void 0 ? rawStep.do(name, run) : rawStep.do(name, config, run);
3484
3898
  },
3485
- catch: (cause) => cause
3899
+ catch: (cause) => new WorkflowStepError({
3900
+ step: name,
3901
+ operation: "do",
3902
+ cause
3903
+ })
3486
3904
  }))),
3487
3905
  sleep: (name, duration) => Effect.tryPromise({
3488
3906
  try: () => step.sleep(name, duration),
3489
- catch: (cause) => cause
3907
+ catch: (cause) => new WorkflowStepError({
3908
+ step: name,
3909
+ operation: "sleep",
3910
+ cause
3911
+ })
3490
3912
  }),
3491
3913
  sleepUntil: (name, timestamp) => Effect.tryPromise({
3492
3914
  try: () => step.sleepUntil(name, timestamp),
3493
- catch: (cause) => cause
3915
+ catch: (cause) => new WorkflowStepError({
3916
+ step: name,
3917
+ operation: "sleepUntil",
3918
+ cause
3919
+ })
3494
3920
  }),
3495
3921
  waitForEvent: (name, options) => Effect.tryPromise({
3496
3922
  try: () => step.waitForEvent(name, options),
3497
- catch: (cause) => cause
3923
+ catch: (cause) => new WorkflowStepError({
3924
+ step: name,
3925
+ operation: "waitForEvent",
3926
+ cause
3927
+ })
3498
3928
  })
3499
3929
  });
3500
- const make$1 = (layer, options) => {
3930
+ const make = (layer, options) => {
3501
3931
  class EffectWorkflow extends WorkflowEntrypoint {
3502
3932
  runtime;
3503
3933
  constructor(ctx, env) {
3504
3934
  super(ctx, env);
3505
- let runWaitUntilEffect = () => Promise.reject(/* @__PURE__ */ new Error("WorkerContext runtime is not initialized"));
3506
- const services = Layer.mergeAll(Layer.succeed(ExecutionContext, ctx), ConfigProvider.layer(Effect.succeed(WorkerConfig.providerFromEnv(env))), Layer.succeed(WorkerContext, fromExecutionContext(ctx, (effect) => runWaitUntilEffect(effect))), Layer.succeed(WorkerEnvironment, env));
3507
- const runtimeLayer = provideEntrypointServices(layer, services);
3508
- this.runtime = ManagedRuntime.make(runtimeLayer);
3509
- runWaitUntilEffect = (effect) => this.runtime.runPromiseExit(effect);
3935
+ this.runtime = makeEntrypointRuntime(layer, env, Layer.mergeAll(Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx))));
3510
3936
  }
3511
3937
  run(event, step) {
3512
3938
  const workflowServices = Layer.mergeAll(Layer.succeed(WorkflowEvent$1, fromWorkflowEvent(event)), Layer.succeed(WorkflowStep$1, fromWorkflowStep(step, (effect) => this.runtime.runPromise(effect))));
3513
- return this.runtime.runPromise(Effect.scoped(options.run(event.payload).pipe(Effect.provide(workflowServices))));
3939
+ return runEventPromise(this.runtime, options.run(event.payload), workflowServices);
3514
3940
  }
3515
3941
  }
3516
3942
  return assumeEntrypointClass(EffectWorkflow);
@@ -3519,57 +3945,7 @@ const step = (name, effect, config) => Effect.flatMap(WorkflowStep$1, (workflowS
3519
3945
  const sleep = (name, duration) => Effect.flatMap(WorkflowStep$1, (workflowStep) => workflowStep.sleep(name, duration));
3520
3946
  const sleepUntil = (name, timestamp) => Effect.flatMap(WorkflowStep$1, (workflowStep) => workflowStep.sleepUntil(name, timestamp));
3521
3947
  const waitForEvent = (name, options) => Effect.flatMap(WorkflowStep$1, (workflowStep) => workflowStep.waitForEvent(name, options));
3522
- const Tag$1 = Tag$2;
3948
+ const Tag = Tag$1;
3523
3949
  const implement = implement$1;
3524
3950
  //#endregion
3525
- //#region src/Vectorize.ts
3526
- var Vectorize_exports = /* @__PURE__ */ __exportAll({
3527
- Tag: () => Tag,
3528
- VectorizeOperationError: () => VectorizeOperationError,
3529
- isVectorizeBinding: () => isVectorizeBinding,
3530
- layer: () => layer,
3531
- make: () => make,
3532
- makeClient: () => makeClient
3533
- });
3534
- const expectedVectorizeBinding = "Vectorize index binding with describe(), query(), insert(), upsert(), deleteByIds(), and getByIds()";
3535
- /** Error raised when a Vectorize operation fails. */
3536
- var VectorizeOperationError = class extends Data.TaggedError("VectorizeOperationError") {};
3537
- const vectorizeError = (binding, operation, cause) => new VectorizeOperationError({
3538
- binding,
3539
- operation,
3540
- cause
3541
- });
3542
- const tryVectorizePromise = (binding, operation, evaluate) => Effect.tryPromise({
3543
- try: evaluate,
3544
- catch: (cause) => vectorizeError(binding, operation, cause)
3545
- });
3546
- const hasFunction = (value, key) => typeof Reflect.get(value, key) === "function";
3547
- const isVectorizeBinding = (value) => typeof value === "object" && value !== null && hasFunction(value, "describe") && hasFunction(value, "query") && hasFunction(value, "insert") && hasFunction(value, "upsert") && hasFunction(value, "deleteByIds") && hasFunction(value, "getByIds");
3548
- const makeClient = (definition) => (index) => {
3549
- const runtime = index;
3550
- const deleteByIds = (ids) => tryVectorizePromise(definition.binding, "deleteByIds", () => runtime.deleteByIds([...ids]));
3551
- return {
3552
- definition,
3553
- describe: tryVectorizePromise(definition.binding, "describe", () => runtime.describe()),
3554
- query: (vector, options) => tryVectorizePromise(definition.binding, "query", () => runtime.query(vector, options)),
3555
- queryById: (vectorId, options) => runtime.queryById !== void 0 ? tryVectorizePromise(definition.binding, "queryById", () => runtime.queryById(vectorId, options)) : Effect.fail(vectorizeError(definition.binding, "queryById", /* @__PURE__ */ new TypeError("Vectorize binding does not expose queryById()"))),
3556
- insert: (vectors) => tryVectorizePromise(definition.binding, "insert", () => runtime.insert([...vectors])),
3557
- upsert: (vectors) => tryVectorizePromise(definition.binding, "upsert", () => runtime.upsert([...vectors])),
3558
- deleteByIds,
3559
- delete: deleteByIds,
3560
- getByIds: (ids) => tryVectorizePromise(definition.binding, "getByIds", () => runtime.getByIds([...ids])),
3561
- unsafeRaw: Effect.succeed(index)
3562
- };
3563
- };
3564
- const layer = (tag, definition) => layer$20(tag, definition.binding, isVectorizeBinding, makeClient(definition), { expected: expectedVectorizeBinding });
3565
- const make = (id) => Tag()(id);
3566
- const Tag = () => (id) => {
3567
- const tag = Context.Service()(id);
3568
- const makeLayer = (definition) => layer(tag, definition);
3569
- return Object.assign(tag, {
3570
- id,
3571
- layer: makeLayer
3572
- });
3573
- };
3574
- //#endregion
3575
- export { AiGateway_exports as AiGateway, AnalyticsEngine_exports as AnalyticsEngine, Binding_exports as Binding, BrowserRendering_exports as BrowserRendering, Cache_exports as Cache, CloudflareOtlp_exports as CloudflareOtlp, ContainerNamespace_exports as ContainerNamespace, D1_exports as D1, DurableObject_exports as DurableObject, DurableObjectAlarm_exports as DurableObjectAlarm, DurableObjectDefinition_exports as DurableObjectDefinition, DurableObjectNamespace_exports as DurableObjectNamespace, DurableObjectRpcWebSocket_exports as DurableObjectRpcWebSocket, DurableObjectSqlite_exports as DurableObjectSqlite, DurableObjectState_exports as DurableObjectState, DurableObjectStorage_exports as DurableObjectStorage, DurableObjectWebSocket_exports as DurableObjectWebSocket, Email_exports as Email, Hyperdrive_exports as Hyperdrive, Images_exports as Images, Kv_exports as Kv, Queue_exports as Queue, QueueBinding_exports as QueueBinding, QueueDefinition_exports as QueueDefinition, R2_exports as R2, Rpc_exports as Rpc, RpcDefinition_exports as RpcDefinition, ServiceBinding_exports as ServiceBinding, Vectorize_exports as Vectorize, Worker_exports as Worker, WorkerConfig, WorkerDefinition_exports as WorkerDefinition, WorkerEnvironment, WorkersAi_exports as WorkersAi, Workflow_exports as Workflow, WorkflowBinding_exports as WorkflowBinding, WorkflowDefinition_exports as WorkflowDefinition };
3951
+ export { AiGateway_exports as AiGateway, AnalyticsEngine_exports as AnalyticsEngine, Binding_exports as Binding, BrowserRendering_exports as BrowserRendering, Cache_exports as Cache, CloudflareOtlp_exports as CloudflareOtlp, ContainerNamespace_exports as ContainerNamespace, D1_exports as D1, DurableObject_exports as DurableObject, DurableObjectAlarm_exports as DurableObjectAlarm, DurableObjectDefinition_exports as DurableObjectDefinition, DurableObjectNamespace_exports as DurableObjectNamespace, DurableObjectRpcWebSocket_exports as DurableObjectRpcWebSocket, DurableObjectSqlite_exports as DurableObjectSqlite, DurableObjectState_exports as DurableObjectState, DurableObjectStorage_exports as DurableObjectStorage, DurableObjectWebSocket_exports as DurableObjectWebSocket, Email_exports as Email, Environment_exports as Environment, Hyperdrive_exports as Hyperdrive, Images_exports as Images, Kv_exports as Kv, Queue_exports as Queue, QueueBinding_exports as QueueBinding, QueueDefinition_exports as QueueDefinition, R2_exports as R2, Rpc_exports as Rpc, RpcDefinition_exports as RpcDefinition, ServiceBinding_exports as ServiceBinding, Vectorize_exports as Vectorize, Worker_exports as Worker, WorkerConfig, WorkerDefinition_exports as WorkerDefinition, WorkerEnvironment, WorkersAi_exports as WorkersAi, Workflow_exports as Workflow, WorkflowBinding_exports as WorkflowBinding, WorkflowDefinition_exports as WorkflowDefinition };