effect-cf 0.20.0 → 0.22.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 +56 -0
  2. package/README.md +2 -2
  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 +708 -549
  7. package/dist/index.mjs +946 -589
  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 +87 -55
  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 +6 -9
  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 +205 -198
  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 +14 -2
  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";
3
- import { FetchHttpClient, HttpClient, HttpClientRequest, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
4
- import { OtlpLogger, OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
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
+ import { FetchHttpClient, HttpClient, HttpClientRequest, HttpEffect, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
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;
134
150
  };
135
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
+ }
167
+ };
168
+ /** Renders a violation list as a single `path: message; ...` line. */
169
+ const violationsMessage = (violations) => violations.map((violation) => `${violation.path}: ${violation.message}`).join("; ");
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
  });
@@ -936,8 +1012,8 @@ const fromDurableObjectState = (state) => ({
936
1012
  id: state.id,
937
1013
  storage: fromDurableObjectStorage(state.storage),
938
1014
  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)))))),
1015
+ blockConcurrencyWhile: (effect) => Effect.context().pipe(Effect.flatMap((context) => Effect.promise(() => state.blockConcurrencyWhile(() => runPromiseExitPreservingTypedFailures(context, effect)))), Effect.flatten),
1016
+ blockConcurrencyWhileOrReset: (effect) => Effect.context().pipe(Effect.flatMap((context) => Effect.promise(() => state.blockConcurrencyWhile(() => Effect.runPromiseWith(context)(effect))))),
941
1017
  acceptWebSocket: (ws, tags) => Effect.sync(() => state.acceptWebSocket(ws.raw, tags)),
942
1018
  getWebSockets: (tag) => Effect.sync(() => state.getWebSockets(tag).map((socket) => fromWebSocket(socket))),
943
1019
  setWebSocketAutoResponse: (pair) => Effect.sync(() => state.setWebSocketAutoResponse(pair)),
@@ -948,19 +1024,33 @@ const fromDurableObjectState = (state) => ({
948
1024
  getTags: (ws) => Effect.sync(() => state.getTags(ws.raw)),
949
1025
  abort: (reason) => Effect.sync(() => state.abort(reason))
950
1026
  });
951
- const runPromiseExitPreservingTypedFailures = async (effect) => {
952
- const exit = await Effect.runPromiseExit(effect);
1027
+ const runPromiseExitPreservingTypedFailures = async (context, effect) => {
1028
+ const exit = await Effect.runPromiseExitWith(context)(effect);
953
1029
  if (Exit.isFailure(exit) && (Cause.hasDies(exit.cause) || Cause.hasInterrupts(exit.cause))) throw Cause.squash(exit.cause);
954
1030
  return exit;
955
1031
  };
956
1032
  //#endregion
957
1033
  //#region src/CloudflareOtlp.ts
1034
+ /**
1035
+ * OTLP telemetry layers for Cloudflare Workers and Durable Objects.
1036
+ *
1037
+ * Every layer exposes {@link OtlpExporter.Flusher}, which drains buffered
1038
+ * telemetry on demand. Cloudflare isolates can freeze before the periodic
1039
+ * export interval fires, so flush explicitly before returning a response, or
1040
+ * hand the flush to `ctx.waitUntil`:
1041
+ *
1042
+ * ```ts
1043
+ * const flusher = yield* OtlpExporter.Flusher;
1044
+ *
1045
+ * yield* flusher.flush;
1046
+ * ```
1047
+ */
958
1048
  var CloudflareOtlp_exports = /* @__PURE__ */ __exportAll({
959
- durableObjectLayer: () => durableObjectLayer,
960
- layer: () => layer$14,
1049
+ layer: () => layer$13,
1050
+ layerDurableObject: () => layerDurableObject,
961
1051
  layerJson: () => layerJson,
962
1052
  layerProtobuf: () => layerProtobuf,
963
- workerLayer: () => workerLayer
1053
+ layerWorker: () => layerWorker
964
1054
  });
965
1055
  const allSignals = [
966
1056
  "logs",
@@ -1009,7 +1099,7 @@ const makeLayer = (options = {}, runtimeAttributes = {}) => {
1009
1099
  resource,
1010
1100
  headers: options.headers
1011
1101
  }));
1012
- if (layers.length === 0) return Layer.empty;
1102
+ if (layers.length === 0) return OtlpExporter.layerFlusher;
1013
1103
  return mergeSignalLayers(layers).pipe(Layer.provide(cloudflareConfigProviderLayer), Layer.provide(serializationLayer(options.serialization)), Layer.provide(FetchHttpClient.layer));
1014
1104
  };
1015
1105
  /**
@@ -1019,15 +1109,18 @@ const makeLayer = (options = {}, runtimeAttributes = {}) => {
1019
1109
  * layers. In Cloudflare Workers and Durable Objects, the current `env` object is
1020
1110
  * installed as the primary `ConfigProvider`; outside Cloudflare, the ambient
1021
1111
  * Effect `ConfigProvider` remains the fallback.
1112
+ *
1113
+ * The layer provides {@link OtlpExporter.Flusher} for draining buffered
1114
+ * telemetry before the isolate freezes.
1022
1115
  */
1023
- const layer$14 = (options = {}) => makeLayer(options);
1116
+ const layer$13 = (options = {}) => makeLayer(options);
1024
1117
  /** Base OTLP telemetry layer forced to JSON serialization. */
1025
- const layerJson = (options = {}) => layer$14({
1118
+ const layerJson = (options = {}) => layer$13({
1026
1119
  ...options,
1027
1120
  serialization: "json"
1028
1121
  });
1029
1122
  /** Base OTLP telemetry layer forced to protobuf serialization. */
1030
- const layerProtobuf = (options = {}) => layer$14({
1123
+ const layerProtobuf = (options = {}) => layer$13({
1031
1124
  ...options,
1032
1125
  serialization: "protobuf"
1033
1126
  });
@@ -1037,7 +1130,7 @@ const layerProtobuf = (options = {}) => layer$14({
1037
1130
  * Provide this layer at runtime scope for long-lived metrics aggregation, or at
1038
1131
  * handler scope when traces/logs should flush as the Cloudflare event finishes.
1039
1132
  */
1040
- const workerLayer = (options = {}) => makeLayer(options, {
1133
+ const layerWorker = (options = {}) => makeLayer(options, {
1041
1134
  "cloudflare.resource_type": "worker",
1042
1135
  "cloudflare.worker.name": options.workerName
1043
1136
  });
@@ -1048,7 +1141,7 @@ const workerLayer = (options = {}) => makeLayer(options, {
1048
1141
  * Durable Object id. Prefer leaving `includeObjectId` disabled unless the
1049
1142
  * backend can tolerate high-cardinality resource attributes.
1050
1143
  */
1051
- const durableObjectLayer = (options = {}) => Layer.unwrap(Effect.map(DurableObjectState, (state) => makeLayer(options, {
1144
+ const layerDurableObject = (options = {}) => Layer.unwrap(Effect.map(DurableObjectState, (state) => makeLayer(options, {
1052
1145
  "cloudflare.resource_type": "durable_object",
1053
1146
  "cloudflare.durable_object.class": options.className,
1054
1147
  "cloudflare.durable_object.id": options.includeObjectId ? state.id.toString() : void 0
@@ -1059,9 +1152,9 @@ var ContainerNamespace_exports = /* @__PURE__ */ __exportAll({
1059
1152
  ContainerNamespace: () => ContainerNamespace,
1060
1153
  ContainerOperationError: () => ContainerOperationError,
1061
1154
  ContainerState: () => ContainerState,
1062
- Tag: () => Tag$14,
1155
+ Tag: () => Tag$12,
1063
1156
  isContainerNamespaceResource: () => isContainerNamespaceResource,
1064
- layer: () => layer$13,
1157
+ layer: () => layer$12,
1065
1158
  make: () => make$14,
1066
1159
  makeClient: () => makeClient$10
1067
1160
  });
@@ -1081,7 +1174,11 @@ const ContainerState = Schema.Union([Schema.Struct({
1081
1174
  exitCode: Schema.optionalKey(Schema.Int)
1082
1175
  })]);
1083
1176
  /** Failure raised when invoking a named Container operation. */
1084
- var ContainerOperationError = class extends Data.TaggedError("ContainerOperationError") {};
1177
+ var ContainerOperationError = class extends Data.TaggedError("ContainerOperationError") {
1178
+ get message() {
1179
+ return `Container ${this.operation} failed for binding "${this.binding}" instance "${this.instance}": ${causeMessage(this.cause)}`;
1180
+ }
1181
+ };
1085
1182
  const tryContainerPromise = (definition, instance, operation, evaluate) => Effect.tryPromise({
1086
1183
  try: evaluate,
1087
1184
  catch: (cause) => new ContainerOperationError({
@@ -1091,20 +1188,35 @@ const tryContainerPromise = (definition, instance, operation, evaluate) => Effec
1091
1188
  cause
1092
1189
  })
1093
1190
  });
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({
1191
+ const makeInstanceClient = (definition, instance, stub) => {
1192
+ const spanOptions = (operation) => ({ attributes: {
1097
1193
  binding: definition.binding,
1098
1194
  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
- });
1195
+ operation
1196
+ } });
1197
+ return {
1198
+ rawUnsafe: Effect.succeed(stub),
1199
+ state: tryContainerPromise(definition, instance, "state", () => stub.getState()).pipe(Effect.flatMap(Schema.decodeUnknownEffect(ContainerState)), Effect.mapError((cause) => cause instanceof ContainerOperationError ? cause : new ContainerOperationError({
1200
+ binding: definition.binding,
1201
+ instance,
1202
+ operation: "state",
1203
+ cause
1204
+ })), Effect.withSpan("ContainerNamespace.state", spanOptions("state"))),
1205
+ fetch: Effect.fn("ContainerNamespace.fetch", spanOptions("fetch"))(function* (input, init) {
1206
+ return yield* tryContainerPromise(definition, instance, "fetch", () => stub.fetch(input, init));
1207
+ }),
1208
+ start: Effect.fn("ContainerNamespace.start", spanOptions("start"))(function* (options, waitOptions) {
1209
+ return yield* tryContainerPromise(definition, instance, "start", () => stub.start(options, waitOptions));
1210
+ }),
1211
+ startAndWaitForPorts: Effect.fn("ContainerNamespace.startAndWaitForPorts", spanOptions("startAndWaitForPorts"))(function* (options) {
1212
+ return yield* tryContainerPromise(definition, instance, "startAndWaitForPorts", () => stub.startAndWaitForPorts(options));
1213
+ }),
1214
+ stop: Effect.fn("ContainerNamespace.stop", spanOptions("stop"))(function* (signal) {
1215
+ return yield* tryContainerPromise(definition, instance, "stop", () => stub.stop(signal));
1216
+ }),
1217
+ destroy: tryContainerPromise(definition, instance, "destroy", () => stub.destroy()).pipe(Effect.withSpan("ContainerNamespace.destroy", spanOptions("destroy")))
1218
+ };
1219
+ };
1108
1220
  const isContainerNamespaceResource = (value) => typeof value === "object" && value !== null && typeof Reflect.get(value, "getByName") === "function";
1109
1221
  const makeClient$10 = (definition) => (namespace) => {
1110
1222
  const getByName = (name, options) => Effect.try({
@@ -1119,7 +1231,7 @@ const makeClient$10 = (definition) => (namespace) => {
1119
1231
  const byName = (name, options) => {
1120
1232
  const instance = getByName(name, options);
1121
1233
  return {
1122
- unsafeRaw: Effect.flatMap(instance, (client) => client.unsafeRaw),
1234
+ rawUnsafe: Effect.flatMap(instance, (client) => client.rawUnsafe),
1123
1235
  state: Effect.flatMap(instance, (client) => client.state),
1124
1236
  fetch: (input, init) => Effect.flatMap(instance, (client) => client.fetch(input, init)),
1125
1237
  start: (startOptions, waitOptions) => Effect.flatMap(instance, (client) => client.start(startOptions, waitOptions)),
@@ -1132,16 +1244,16 @@ const makeClient$10 = (definition) => (namespace) => {
1132
1244
  definition,
1133
1245
  getByName,
1134
1246
  byName,
1135
- unsafeRaw: Effect.succeed(namespace)
1247
+ rawUnsafe: Effect.succeed(namespace)
1136
1248
  };
1137
1249
  };
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);
1250
+ const layer$12 = (tag, definition) => layer$19(tag, definition.binding, isContainerNamespaceResource, makeClient$10(definition), { expected: expectedContainerNamespace });
1251
+ const make$14 = (id) => Tag$12()(id);
1140
1252
  /** 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* () {
1253
+ const Tag$12 = () => (id) => {
1254
+ const tag = Context.Service()(`effect-cf/Container/${id}`);
1255
+ const makeLayer = (definition) => layer$12(tag, definition);
1256
+ const getByName = Effect.fnUntraced(function* (name, options) {
1145
1257
  return yield* (yield* tag).getByName(name, options);
1146
1258
  });
1147
1259
  const byName = (name, options) => ({
@@ -1151,27 +1263,25 @@ const Tag$14 = () => (id) => {
1151
1263
  startAndWaitForPorts: (startOptions) => Effect.flatMap(getByName(name, options), (instance) => instance.startAndWaitForPorts(startOptions)),
1152
1264
  stop: (signal) => Effect.flatMap(getByName(name, options), (instance) => instance.stop(signal)),
1153
1265
  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;
1266
+ rawUnsafe: Effect.flatMap(getByName(name, options), (instance) => instance.rawUnsafe)
1158
1267
  });
1268
+ const rawUnsafe = Effect.flatMap(tag, (namespace) => namespace.rawUnsafe);
1159
1269
  return Object.assign(tag, {
1160
1270
  id,
1161
1271
  layer: makeLayer,
1162
1272
  getByName,
1163
1273
  byName,
1164
- unsafeRaw
1274
+ rawUnsafe
1165
1275
  });
1166
1276
  };
1167
- const ContainerNamespace = Tag$14;
1277
+ const ContainerNamespace = Tag$12;
1168
1278
  //#endregion
1169
1279
  //#region src/D1.ts
1170
1280
  var D1_exports = /* @__PURE__ */ __exportAll({
1171
1281
  Service: () => Service$1,
1172
1282
  make: () => make$13
1173
1283
  });
1174
- const TypeId$2 = "effect-cf/D1";
1284
+ const TypeId$2 = "~effect-cf/D1";
1175
1285
  const expectedD1Database = "D1 database binding with prepare(), batch(), and exec()";
1176
1286
  const isD1Database = (value) => {
1177
1287
  if (typeof value !== "object" || value === null) return false;
@@ -1217,7 +1327,7 @@ const Service$1 = () => (id, definition) => {
1217
1327
  var QueueBinding_exports = /* @__PURE__ */ __exportAll({
1218
1328
  QueueOperationError: () => QueueOperationError,
1219
1329
  isQueue: () => isQueue,
1220
- layer: () => layer$12,
1330
+ layer: () => layer$11,
1221
1331
  makeClient: () => makeClient$9
1222
1332
  });
1223
1333
  const expectedQueueProducer = "Queue producer binding with send(); optional sendBatch()/metrics()";
@@ -1238,27 +1348,30 @@ const isQueue = (value) => {
1238
1348
  const makeClient$9 = (definition) => {
1239
1349
  const encodeMessage = Schema.encodeEffect(definition.message);
1240
1350
  return (queue) => ({
1241
- send: Effect.fnUntraced(function* (message, options) {
1351
+ send: Effect.fn("QueueBinding.send", { attributes: {
1352
+ binding: definition.binding,
1353
+ operation: "send"
1354
+ } })(function* (message, options) {
1242
1355
  const encoded = yield* encodeMessage(message);
1243
1356
  yield* tryQueuePromise(definition.binding, "send", () => queue.send(encoded, options));
1244
1357
  }),
1245
- sendBatch: Effect.fnUntraced(function* (messages, options) {
1358
+ sendBatch: Effect.fn("QueueBinding.sendBatch", { attributes: {
1359
+ binding: definition.binding,
1360
+ operation: "sendBatch"
1361
+ } })(function* (messages, options) {
1246
1362
  const encodedMessages = [];
1247
1363
  for (const message of messages) encodedMessages.push({
1248
1364
  ...message,
1249
1365
  body: yield* encodeMessage(message.body)
1250
1366
  });
1251
1367
  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
- });
1368
+ if (sendBatch === void 0) return yield* new QueueOperationError({
1369
+ binding: definition.binding,
1370
+ operation: "sendBatch",
1371
+ cause: /* @__PURE__ */ new Error(`Queue binding "${definition.binding}" does not provide sendBatch()`),
1372
+ message: `Cloudflare queue binding "${definition.binding}" does not provide sendBatch()`
1261
1373
  });
1374
+ yield* tryQueuePromise(definition.binding, "sendBatch", () => sendBatch.call(queue, encodedMessages, options));
1262
1375
  }),
1263
1376
  metrics: () => {
1264
1377
  const metrics = queue.metrics;
@@ -1270,16 +1383,16 @@ const makeClient$9 = (definition) => {
1270
1383
  }));
1271
1384
  return tryQueuePromise(definition.binding, "metrics", () => metrics.call(queue));
1272
1385
  },
1273
- unsafeRaw: Effect.succeed(queue)
1386
+ rawUnsafe: Effect.succeed(queue)
1274
1387
  });
1275
1388
  };
1276
- const layer$12 = (tag, definition) => layer$20(tag, definition.binding, (value) => isQueue(value), makeClient$9(definition), { expected: expectedQueueProducer });
1389
+ const layer$11 = (tag, definition) => layer$19(tag, definition.binding, (value) => isQueue(value), makeClient$9(definition), { expected: expectedQueueProducer });
1277
1390
  //#endregion
1278
1391
  //#region src/QueueDefinition.ts
1279
1392
  var QueueDefinition_exports = /* @__PURE__ */ __exportAll({
1280
1393
  Queue: () => Queue$1,
1281
- Tag: () => Tag$13,
1282
- implement: () => implement$7,
1394
+ Tag: () => Tag$11,
1395
+ implement: () => implement$5,
1283
1396
  make: () => make$12
1284
1397
  });
1285
1398
  const makeDefinition$4 = (id, definition) => {
@@ -1292,11 +1405,11 @@ const makeDefinition$4 = (id, definition) => {
1292
1405
  queue: wrapHandler$1(queueDefinition, options.queue)
1293
1406
  }) });
1294
1407
  };
1295
- const make$12 = (id, definition) => Tag$13()(id, definition);
1296
- const Tag$13 = () => (id, definition) => {
1408
+ const make$12 = (id, definition) => Tag$11()(id, definition);
1409
+ const Tag$11 = () => (id, definition) => {
1297
1410
  const queueDefinition = makeDefinition$4(id, definition);
1298
- const tag = Context.Service()(id);
1299
- const layer = (binding) => layer$12(tag, {
1411
+ const tag = Context.Service()(`effect-cf/Queue/${id}`);
1412
+ const layer = (binding) => layer$11(tag, {
1300
1413
  ...binding,
1301
1414
  message: definition.message
1302
1415
  });
@@ -1309,9 +1422,7 @@ const Tag$13 = () => (id, definition) => {
1309
1422
  const metrics = Effect.fnUntraced(function* () {
1310
1423
  return yield* (yield* tag).metrics();
1311
1424
  });
1312
- const unsafeRaw = Effect.fnUntraced(function* () {
1313
- return yield* (yield* tag).unsafeRaw;
1314
- });
1425
+ const rawUnsafe = Effect.flatMap(tag, (queue) => queue.rawUnsafe);
1315
1426
  return Object.assign(tag, {
1316
1427
  id: queueDefinition.id,
1317
1428
  message: queueDefinition.message,
@@ -1320,28 +1431,32 @@ const Tag$13 = () => (id, definition) => {
1320
1431
  send,
1321
1432
  sendBatch,
1322
1433
  metrics,
1323
- unsafeRaw
1434
+ rawUnsafe
1324
1435
  });
1325
1436
  };
1326
- const Queue$1 = Tag$13;
1437
+ const Queue$1 = Tag$11;
1327
1438
  const wrapHandler$1 = (definition, handler) => {
1328
1439
  const decodeBody = Schema.decodeUnknownEffect(definition.message);
1329
- return (batch) => Effect.gen(function* () {
1440
+ return Effect.fnUntraced(function* (batch) {
1330
1441
  yield* handler(yield* decodeBatch(batch.raw, decodeBody));
1331
1442
  });
1332
1443
  };
1333
- const implement$7 = (_definition, handler) => handler;
1444
+ const implement$5 = (_definition, handler) => handler;
1334
1445
  //#endregion
1335
1446
  //#region src/Queue.ts
1336
1447
  var Queue_exports = /* @__PURE__ */ __exportAll({
1337
1448
  QueueMessageDecodeError: () => QueueMessageDecodeError,
1338
- Tag: () => Tag$12,
1449
+ Tag: () => Tag$10,
1339
1450
  decodeBatch: () => decodeBatch,
1340
1451
  fromMessage: () => fromMessage,
1341
1452
  fromMessageBatch: () => fromMessageBatch,
1342
- implement: () => implement$6
1453
+ implement: () => implement$4
1343
1454
  });
1344
- var QueueMessageDecodeError = class extends Data.TaggedError("QueueMessageDecodeError") {};
1455
+ var QueueMessageDecodeError = class extends Data.TaggedError("QueueMessageDecodeError") {
1456
+ get message() {
1457
+ return `Queue "${this.queue}" failed to decode message "${this.messageId}" at index ${this.index}: ${causeMessage(this.cause)}`;
1458
+ }
1459
+ };
1345
1460
  const fromMessage = (message, body) => ({
1346
1461
  raw: message,
1347
1462
  id: message.id,
@@ -1373,34 +1488,102 @@ const decodeBatch = (batch, decodeBody) => Effect.gen(function* () {
1373
1488
  }
1374
1489
  return fromMessageBatch(batch, messages);
1375
1490
  });
1376
- const Tag$12 = Tag$13;
1377
- const implement$6 = implement$7;
1491
+ const Tag$10 = Tag$11;
1492
+ const implement$4 = implement$5;
1378
1493
  //#endregion
1379
1494
  //#region src/RpcDefinition.ts
1380
1495
  var RpcDefinition_exports = /* @__PURE__ */ __exportAll({
1381
- ReservedMethodNameError: () => ReservedMethodNameError,
1382
1496
  RpcArgumentCountError: () => RpcArgumentCountError,
1383
1497
  RpcArgumentDecodeError: () => RpcArgumentDecodeError,
1384
1498
  RpcArgumentEncodeError: () => RpcArgumentEncodeError,
1385
1499
  RpcReservedMethodNameError: () => RpcReservedMethodNameError,
1386
1500
  RpcSuccessDecodeError: () => RpcSuccessDecodeError,
1387
1501
  RpcSuccessEncodeError: () => RpcSuccessEncodeError,
1388
- assertNoReservedMethodNames: () => assertNoReservedMethodNames,
1389
1502
  assertNoReservedMethods: () => assertNoReservedMethods,
1390
1503
  decodeArgs: () => decodeArgs,
1391
1504
  decodeSuccess: () => decodeSuccess,
1505
+ decodeWireError: () => decodeWireError,
1392
1506
  encodeArgs: () => encodeArgs,
1393
1507
  encodeSuccess: () => encodeSuccess,
1508
+ encodeWireError: () => encodeWireError,
1509
+ isWireError: () => isWireError,
1394
1510
  make: () => make$11,
1395
- method: () => method$4,
1511
+ method: () => method$2,
1396
1512
  reservedMethodNames: () => reservedMethodNames$4
1397
1513
  });
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") {};
1514
+ var RpcReservedMethodNameError = class extends Data.TaggedError("RpcReservedMethodNameError") {
1515
+ get message() {
1516
+ return `${this.definition} RPC method "${this.method}" is reserved by Cloudflare Workers RPC`;
1517
+ }
1518
+ };
1519
+ var RpcArgumentCountError = class extends Schema.TaggedError()("RpcArgumentCountError", {
1520
+ definition: Schema.String,
1521
+ method: Schema.String,
1522
+ expected: Schema.Number,
1523
+ actual: Schema.Number
1524
+ }) {
1525
+ get message() {
1526
+ return `${this.definition} RPC method "${this.method}" expected ${this.expected} arguments but received ${this.actual}`;
1527
+ }
1528
+ };
1529
+ var RpcArgumentDecodeError = class extends Schema.TaggedError()("RpcArgumentDecodeError", {
1530
+ definition: Schema.String,
1531
+ method: Schema.String,
1532
+ cause: Schema.Defect()
1533
+ }) {
1534
+ get message() {
1535
+ return `${this.definition} RPC method "${this.method}" argument decode failed: ${causeMessage(this.cause)}`;
1536
+ }
1537
+ };
1538
+ var RpcArgumentEncodeError = class extends Data.TaggedError("RpcArgumentEncodeError") {
1539
+ get message() {
1540
+ return `${this.definition} RPC method "${this.method}" argument encode failed: ${causeMessage(this.cause)}`;
1541
+ }
1542
+ };
1543
+ var RpcSuccessDecodeError = class extends Data.TaggedError("RpcSuccessDecodeError") {
1544
+ get message() {
1545
+ return `${this.definition} RPC method "${this.method}" success decode failed: ${causeMessage(this.cause)}`;
1546
+ }
1547
+ };
1548
+ var RpcSuccessEncodeError = class extends Schema.TaggedError()("RpcSuccessEncodeError", {
1549
+ definition: Schema.String,
1550
+ method: Schema.String,
1551
+ cause: Schema.Defect()
1552
+ }) {
1553
+ get message() {
1554
+ return `${this.definition} RPC method "${this.method}" success encode failed: ${causeMessage(this.cause)}`;
1555
+ }
1556
+ };
1557
+ const WireErrorSchema = Schema.Union([
1558
+ RpcArgumentCountError,
1559
+ RpcArgumentDecodeError,
1560
+ RpcSuccessEncodeError
1561
+ ]);
1562
+ const wireErrorKey = "effect-cf/RpcDefinition/wireError";
1563
+ const isWireError = (error) => error instanceof RpcArgumentCountError || error instanceof RpcArgumentDecodeError || error instanceof RpcSuccessEncodeError;
1564
+ /**
1565
+ * Encodes package RPC errors into a plain `Error` envelope so their tags
1566
+ * survive Cloudflare RPC serialization, which drops custom error properties.
1567
+ */
1568
+ const encodeWireError = (error) => {
1569
+ if (!isWireError(error)) return error;
1570
+ try {
1571
+ return new Error(JSON.stringify({ [wireErrorKey]: Schema.encodeSync(WireErrorSchema)(error) }));
1572
+ } catch {
1573
+ return error;
1574
+ }
1575
+ };
1576
+ /** Restores package RPC errors from the {@link encodeWireError} envelope. */
1577
+ const decodeWireError = (cause) => {
1578
+ if (!(cause instanceof Error)) return cause;
1579
+ try {
1580
+ const parsed = JSON.parse(cause.message);
1581
+ if (!Predicate.hasProperty(parsed, wireErrorKey)) return cause;
1582
+ return Schema.decodeUnknownSync(WireErrorSchema)(parsed[wireErrorKey]);
1583
+ } catch {
1584
+ return cause;
1585
+ }
1586
+ };
1404
1587
  const reservedMethodNames$4 = /* @__PURE__ */ new Set([
1405
1588
  "constructor",
1406
1589
  "fetch",
@@ -1415,72 +1598,56 @@ const reservedMethodNames$4 = /* @__PURE__ */ new Set([
1415
1598
  "serialize",
1416
1599
  "deserialize"
1417
1600
  ]);
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
- };
1601
+ /**
1602
+ * Workers RPC structured-clones every value that crosses an isolate boundary
1603
+ * and rejects class instances. Declaration schemas such as `Schema.Result`
1604
+ * keep their container instance in their `Encoded` form, so the declared
1605
+ * schemas are lowered to their canonical JSON codec before touching the wire.
1606
+ */
1607
+ const wireCodec = (schema) => Schema.toCodecJson(schema);
1428
1608
  const assertNoReservedMethods = (target, methods, reserved) => {
1429
- for (const method of Object.keys(methods)) if (reserved.has(method)) throw new ReservedMethodNameError(target, method);
1609
+ for (const method of Object.keys(methods)) if (reserved.has(method)) throw new RpcReservedMethodNameError({
1610
+ definition: target,
1611
+ method
1612
+ });
1430
1613
  };
1431
- function method$4(definition) {
1614
+ function method$2(definition) {
1432
1615
  return {
1433
1616
  args: definition.args ?? [],
1434
1617
  success: definition.success
1435
1618
  };
1436
1619
  }
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* () {
1620
+ const decodeArgs = Effect.fnUntraced(function* (definition, methodName, args) {
1442
1621
  const methodDefinition = definition.methods[methodName];
1443
- if (args.length !== methodDefinition.args.length) return yield* Effect.fail(new RpcArgumentCountError({
1622
+ if (args.length !== methodDefinition.args.length) return yield* new RpcArgumentCountError({
1444
1623
  definition: definition.id,
1445
1624
  method: methodName,
1446
1625
  expected: methodDefinition.args.length,
1447
1626
  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;
1627
+ });
1628
+ return yield* Schema.decodeUnknownEffect(wireCodec(Schema.Tuple(methodDefinition.args)))(args).pipe(Effect.mapError((cause) => new RpcArgumentDecodeError({
1629
+ definition: definition.id,
1630
+ method: methodName,
1631
+ cause
1632
+ })));
1460
1633
  });
1461
- const encodeArgs = (definition, methodName, args) => Effect.gen(function* () {
1634
+ const encodeArgs = Effect.fnUntraced(function* (definition, methodName, args) {
1462
1635
  const methodDefinition = definition.methods[methodName];
1463
- if (args.length !== methodDefinition.args.length) return yield* Effect.fail(new RpcArgumentCountError({
1636
+ if (args.length !== methodDefinition.args.length) return yield* new RpcArgumentCountError({
1464
1637
  definition: definition.id,
1465
1638
  method: methodName,
1466
1639
  expected: methodDefinition.args.length,
1467
1640
  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;
1641
+ });
1642
+ return yield* Schema.encodeUnknownEffect(wireCodec(Schema.Tuple(methodDefinition.args)))(args).pipe(Effect.mapError((cause) => new RpcArgumentEncodeError({
1643
+ definition: definition.id,
1644
+ method: methodName,
1645
+ cause
1646
+ })));
1480
1647
  });
1481
1648
  const encodeSuccess = (definition, methodName, value) => {
1482
1649
  const methodDefinition = definition.methods[methodName];
1483
- return Schema.encodeEffect(methodDefinition.success)(value).pipe(Effect.mapError((cause) => new RpcSuccessEncodeError({
1650
+ return Schema.encodeUnknownEffect(wireCodec(methodDefinition.success))(value).pipe(Effect.mapError((cause) => new RpcSuccessEncodeError({
1484
1651
  definition: definition.id,
1485
1652
  method: methodName,
1486
1653
  cause
@@ -1488,23 +1655,92 @@ const encodeSuccess = (definition, methodName, value) => {
1488
1655
  };
1489
1656
  const decodeSuccess = (definition, methodName, value) => {
1490
1657
  const methodDefinition = definition.methods[methodName];
1491
- return Schema.decodeUnknownEffect(methodDefinition.success)(value).pipe(Effect.mapError((cause) => new RpcSuccessDecodeError({
1658
+ return Schema.decodeUnknownEffect(wireCodec(methodDefinition.success))(value).pipe(Effect.mapError((cause) => new RpcSuccessDecodeError({
1492
1659
  definition: definition.id,
1493
1660
  method: methodName,
1494
1661
  cause
1495
1662
  })));
1496
1663
  };
1497
1664
  const make$11 = (id, methods) => {
1498
- const definition = {
1665
+ assertNoReservedMethods(id, methods, reservedMethodNames$4);
1666
+ return {
1499
1667
  id,
1500
1668
  methods
1501
1669
  };
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
1670
+ };
1671
+ //#endregion
1672
+ //#region src/internal/Entrypoint.ts
1673
+ const provideEntrypointServices = (layer, services) => layer.pipe(Layer.provideMerge(services));
1674
+ const defineEntrypointRpcMethods = (target, prototype, rpc, reservedMethodNames, run) => {
1675
+ const methods = rpc ?? {};
1676
+ assertNoReservedMethods(target, methods, reservedMethodNames);
1677
+ for (const [key, method] of Object.entries(methods)) Object.defineProperty(prototype, key, {
1678
+ enumerable: true,
1679
+ value(...args) {
1680
+ return run(this, Effect.suspend(() => method(...args)).pipe(Effect.mapError(encodeWireError)));
1681
+ }
1506
1682
  });
1507
- return definition;
1683
+ };
1684
+ const assumeEntrypointClass = (entrypoint) => entrypoint;
1685
+ //#endregion
1686
+ //#region src/internal/Runtime.ts
1687
+ /**
1688
+ * Assembles the shared `ManagedRuntime` used by the Cloudflare entrypoint
1689
+ * classes (Worker, Durable Object, Workflow).
1690
+ *
1691
+ * The entrypoint-specific services are merged with the env-backed
1692
+ * `ConfigProvider` and `WorkerEnvironment`, then provided to the user-supplied
1693
+ * layer so the resulting runtime satisfies both the user services and the
1694
+ * platform services.
1695
+ */
1696
+ const makeEntrypointRuntime = (layer, env, services) => {
1697
+ const entrypointServices = Layer.mergeAll(services, ConfigProvider.layer(WorkerConfig.providerFromEnv(env)), Layer.succeed(WorkerEnvironment, env));
1698
+ return ManagedRuntime.make(provideEntrypointServices(layer, entrypointServices));
1699
+ };
1700
+ /**
1701
+ * Runs a Cloudflare event effect on an entrypoint runtime.
1702
+ *
1703
+ * When an event layer is given it is built inside the event's Effect scope
1704
+ * (finalized when the event effect completes). The casts widen away the
1705
+ * `REvent` requirement satisfied by the event layer; TypeScript cannot reduce
1706
+ * `Exclude<...>` over the generic union.
1707
+ */
1708
+ const runEventPromise = (runtime, effect, eventLayer) => {
1709
+ const withEventLayer = eventLayer === void 0 ? effect : effect.pipe(Effect.provide(eventLayer, { local: true }));
1710
+ return runtime.runPromise(Effect.scoped(withEventLayer));
1711
+ };
1712
+ //#endregion
1713
+ //#region src/internal/WorkerContext.ts
1714
+ const causeError = (cause) => {
1715
+ const squashed = Cause.squash(cause);
1716
+ return squashed instanceof Error ? squashed : new Error(Cause.pretty(cause), { cause: squashed });
1717
+ };
1718
+ 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))));
1719
+ /**
1720
+ * Builds the `WorkerContext` service from a native `ExecutionContext`.
1721
+ *
1722
+ * Background effects capture the calling fiber's context via `Effect.context`
1723
+ * before being handed to `ctx.waitUntil`, so the default module-level
1724
+ * `Effect.runPromiseExit` runner is sufficient; entrypoints may still pass a
1725
+ * runtime-bound runner.
1726
+ */
1727
+ const fromExecutionContext = (ctx, runPromiseExit = (effect) => Effect.runPromiseExit(effect)) => {
1728
+ const schedule = (effect, options, mode) => Effect.context().pipe(Effect.flatMap((context) => Effect.sync(() => {
1729
+ const runHandler = (cause) => runPromiseExit(Effect.scoped(Effect.provideContext(failureHandler(cause, options), context))).then((exit) => {
1730
+ if (Exit.isFailure(exit)) console.error("WorkerContext.waitUntil failure handler failed", Cause.pretty(exit.cause));
1731
+ });
1732
+ ctx.waitUntil(runPromiseExit(Effect.scoped(Effect.provideContext(effect, context))).then(async (exit) => {
1733
+ if (Exit.isSuccess(exit)) return;
1734
+ await runHandler(exit.cause);
1735
+ if (mode === "propagate") throw causeError(exit.cause);
1736
+ }));
1737
+ })));
1738
+ return {
1739
+ raw: ctx,
1740
+ waitUntil: (effect, options) => schedule(effect, options, options?.mode ?? "observe"),
1741
+ waitUntilPropagating: (effect, options) => schedule(effect, options, "propagate"),
1742
+ passThroughOnException: Effect.sync(() => ctx.passThroughOnException())
1743
+ };
1508
1744
  };
1509
1745
  //#endregion
1510
1746
  //#region src/Rpc.ts
@@ -1522,7 +1758,7 @@ const dispose = (value) => Effect.sync(() => {
1522
1758
  });
1523
1759
  const resolve = (value) => isPromiseLike(value) ? Effect.tryPromise({
1524
1760
  try: () => value,
1525
- catch: (cause) => cause
1761
+ catch: (cause) => decodeWireError(cause)
1526
1762
  }) : Effect.sync(() => value);
1527
1763
  const scoped = (value) => Effect.acquireRelease(resolve(value), (resolved) => dispose(resolved));
1528
1764
  const isPromiseLike = (value) => (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
@@ -1538,7 +1774,7 @@ const lookupRpcMethod = (target, method, makeError) => Effect.try({
1538
1774
  },
1539
1775
  catch: makeError
1540
1776
  });
1541
- const invokeRpcMethod = (target, method, args, makeError) => Effect.gen(function* () {
1777
+ const invokeRpcMethod = Effect.fnUntraced(function* (target, method, args, makeError) {
1542
1778
  const fn = yield* lookupRpcMethod(target, method, makeError);
1543
1779
  return yield* Effect.try({
1544
1780
  try: () => fn(...args),
@@ -1552,7 +1788,7 @@ var ServiceBinding_exports = /* @__PURE__ */ __exportAll({
1552
1788
  ServiceBindingFetchError: () => ServiceBindingFetchError,
1553
1789
  ServiceBindingRpcError: () => ServiceBindingRpcError,
1554
1790
  isServiceBindingClient: () => isServiceBindingClient,
1555
- layer: () => layer$11,
1791
+ layer: () => layer$10,
1556
1792
  makeClient: () => makeClient$8,
1557
1793
  makeDirectMethods: () => makeDirectMethods$1
1558
1794
  });
@@ -1561,22 +1797,32 @@ const expectedServiceBinding = "Worker service binding with fetch()";
1561
1797
  /**
1562
1798
  * Failure raised when calling `fetch` on a service binding.
1563
1799
  */
1564
- var ServiceBindingFetchError = class extends Data.TaggedError("ServiceBindingFetchError") {};
1800
+ var ServiceBindingFetchError = class extends Data.TaggedError("ServiceBindingFetchError") {
1801
+ get message() {
1802
+ return `Service binding "${this.binding}" fetch failed: ${causeMessage(this.cause)}`;
1803
+ }
1804
+ };
1565
1805
  /**
1566
1806
  * Failure raised when invoking an RPC method on a service binding.
1567
1807
  */
1568
- var ServiceBindingRpcError = class extends Data.TaggedError("ServiceBindingRpcError") {};
1808
+ var ServiceBindingRpcError = class extends Data.TaggedError("ServiceBindingRpcError") {
1809
+ get message() {
1810
+ return `Service binding "${this.binding}" RPC method "${this.method}" failed: ${causeMessage(this.cause)}`;
1811
+ }
1812
+ };
1569
1813
  const isServiceBindingClient = (value) => typeof value === "object" && value !== null && typeof Reflect.get(value, "fetch") === "function";
1570
1814
  const makeClient$8 = (definition) => {
1571
1815
  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
- })
1816
+ const fetch = Effect.fn("ServiceBinding.fetch")(function* (input, init) {
1817
+ return yield* Effect.tryPromise({
1818
+ try: () => service.fetch(input, init),
1819
+ catch: (cause) => new ServiceBindingFetchError({
1820
+ binding: definition.binding,
1821
+ cause
1822
+ })
1823
+ });
1578
1824
  });
1579
- const rpc = (method, ...args) => Effect.gen(function* () {
1825
+ const rpc = Effect.fn("ServiceBinding.rpc")(function* (method, ...args) {
1580
1826
  const methodName = String(method);
1581
1827
  const encodedArgs = definition.definition === void 0 ? args : yield* encodeArgs(definition.definition, methodName, args).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1582
1828
  binding: definition.binding,
@@ -1589,7 +1835,7 @@ const makeClient$8 = (definition) => {
1589
1835
  cause
1590
1836
  }));
1591
1837
  });
1592
- const decodeSuccess$2 = (methodName, value) => Effect.gen(function* () {
1838
+ const decodeSuccess$2 = Effect.fnUntraced(function* (methodName, value) {
1593
1839
  if (definition.definition === void 0) return value;
1594
1840
  return yield* decodeSuccess(definition.definition, methodName, value).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1595
1841
  binding: definition.binding,
@@ -1597,7 +1843,7 @@ const makeClient$8 = (definition) => {
1597
1843
  cause
1598
1844
  })));
1599
1845
  });
1600
- const call = (method, ...args) => Effect.gen(function* () {
1846
+ const call = Effect.fn("ServiceBinding.call")(function* (method, ...args) {
1601
1847
  const methodName = String(method);
1602
1848
  const value = yield* resolve(yield* rpc(method, ...args)).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1603
1849
  binding: definition.binding,
@@ -1606,7 +1852,7 @@ const makeClient$8 = (definition) => {
1606
1852
  })));
1607
1853
  return yield* decodeSuccess$2(methodName, value);
1608
1854
  });
1609
- const scopedCall = (method, ...args) => Effect.gen(function* () {
1855
+ const scopedCall = Effect.fn("ServiceBinding.scopedCall")(function* (method, ...args) {
1610
1856
  const methodName = String(method);
1611
1857
  const result = yield* rpc(method, ...args);
1612
1858
  const value = yield* scoped(result);
@@ -1621,7 +1867,7 @@ const makeClient$8 = (definition) => {
1621
1867
  });
1622
1868
  };
1623
1869
  };
1624
- const layer$11 = (tag, definition) => layer$20(tag, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition), { expected: expectedServiceBinding });
1870
+ const layer$10 = (tag, definition) => layer$19(tag, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition), { expected: expectedServiceBinding });
1625
1871
  /**
1626
1872
  * Creates a typed Effect service for a Worker service binding.
1627
1873
  *
@@ -1653,16 +1899,16 @@ const layer$11 = (tag, definition) => layer$20(tag, definition.binding, (value)
1653
1899
  */
1654
1900
  const Service = () => (id, definition) => {
1655
1901
  const tag = Service$2()(id, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition));
1656
- const fetch = (input, init) => Effect.gen(function* () {
1902
+ const fetch = Effect.fnUntraced(function* (input, init) {
1657
1903
  return yield* (yield* tag).fetch(input, init);
1658
1904
  });
1659
- const rpc = (method, ...args) => Effect.gen(function* () {
1905
+ const rpc = Effect.fnUntraced(function* (method, ...args) {
1660
1906
  return yield* (yield* tag).rpc(method, ...args);
1661
1907
  });
1662
- const call = (method, ...args) => Effect.gen(function* () {
1908
+ const call = Effect.fnUntraced(function* (method, ...args) {
1663
1909
  return yield* (yield* tag).call(method, ...args);
1664
1910
  });
1665
- const scopedCall = (method, ...args) => Effect.gen(function* () {
1911
+ const scopedCall = Effect.fnUntraced(function* (method, ...args) {
1666
1912
  return yield* (yield* tag).scopedCall(method, ...args);
1667
1913
  });
1668
1914
  const directMethods = makeDirectMethods$1(definition.definition, call);
@@ -1683,11 +1929,11 @@ const makeDirectMethods$1 = (rpcDefinition, call) => {
1683
1929
  //#endregion
1684
1930
  //#region src/WorkerDefinition.ts
1685
1931
  var WorkerDefinition_exports = /* @__PURE__ */ __exportAll({
1686
- Tag: () => Tag$11,
1932
+ Tag: () => Tag$9,
1687
1933
  Worker: () => Worker,
1688
- implement: () => implement$5,
1934
+ implement: () => implement$3,
1689
1935
  make: () => make$10,
1690
- method: () => method$3
1936
+ method: () => method$1
1691
1937
  });
1692
1938
  const reservedMethodNames$3 = /* @__PURE__ */ new Set([
1693
1939
  "constructor",
@@ -1708,7 +1954,7 @@ const reservedMethodNames$3 = /* @__PURE__ */ new Set([
1708
1954
  /**
1709
1955
  * Defines a single RPC method schema in a worker definition.
1710
1956
  */
1711
- const method$3 = method$4;
1957
+ const method$1 = method$2;
1712
1958
  /**
1713
1959
  * Creates a typed worker RPC definition plus helpers for implementation and bindings.
1714
1960
  *
@@ -1730,15 +1976,15 @@ const makeDefinition$3 = (id, methods) => {
1730
1976
  rpc: wrapHandlers$1(definition, options.rpc)
1731
1977
  }) });
1732
1978
  };
1733
- const make$10 = (id, methods) => Tag$11()(id, methods);
1734
- const Tag$11 = () => (id, methods) => {
1979
+ const make$10 = (id, methods) => Tag$9()(id, methods);
1980
+ const Tag$9 = () => (id, methods) => {
1735
1981
  const definition = makeDefinition$3(id, methods);
1736
1982
  const tag = Context.Service()(id);
1737
1983
  const bindingDefinition = (binding) => ({
1738
1984
  ...binding,
1739
1985
  definition
1740
1986
  });
1741
- const layer = (binding) => layer$11(tag, bindingDefinition(binding));
1987
+ const layer = (binding) => layer$10(tag, bindingDefinition(binding));
1742
1988
  const fetch = (input, init) => Effect.gen(function* () {
1743
1989
  return yield* (yield* tag).fetch(input, init);
1744
1990
  });
@@ -1763,7 +2009,7 @@ const Tag$11 = () => (id, methods) => {
1763
2009
  scopedCall
1764
2010
  });
1765
2011
  };
1766
- const Worker = Tag$11;
2012
+ const Worker = Tag$9;
1767
2013
  const wrapHandlers$1 = (definition, handlers) => {
1768
2014
  const wrapped = {};
1769
2015
  for (const key of Object.keys(definition.methods)) {
@@ -1779,82 +2025,44 @@ const wrapHandlers$1 = (definition, handlers) => {
1779
2025
  /**
1780
2026
  * Helper for implementing handlers with the exact method shape of a definition.
1781
2027
  */
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
- };
2028
+ const implement$3 = (_definition, handlers) => handlers;
1841
2029
  //#endregion
1842
2030
  //#region src/Worker.ts
1843
2031
  var Worker_exports = /* @__PURE__ */ __exportAll({
1844
2032
  ExecutionContext: () => ExecutionContext,
1845
2033
  NativeRequest: () => NativeRequest,
1846
- Tag: () => Tag$10,
2034
+ Tag: () => Tag$9,
1847
2035
  WorkerContext: () => WorkerContext,
1848
- implement: () => implement$4,
2036
+ implement: () => implement$3,
1849
2037
  isWebSocketUpgrade: () => isWebSocketUpgrade,
1850
2038
  make: () => make$9,
1851
2039
  makeFetchHandler: () => makeFetchHandler,
1852
- method: () => method$2,
1853
- renderHttpResponse: () => renderHttpResponse
2040
+ method: () => method$1
1854
2041
  });
2042
+ /**
2043
+ * Access to Cloudflare's native `ExecutionContext`.
2044
+ */
1855
2045
  var ExecutionContext = class extends Context.Service()("effect-cf/ExecutionContext") {};
2046
+ /**
2047
+ * Service used inside handlers to schedule background work via `waitUntil`.
2048
+ *
2049
+ * @example
2050
+ * ```ts
2051
+ * const handler = Effect.gen(function* () {
2052
+ * const ctx = yield* Worker.WorkerContext;
2053
+ * yield* ctx.waitUntil(Effect.log("flush analytics"));
2054
+ * return new Response("ok");
2055
+ * });
2056
+ * ```
2057
+ */
1856
2058
  var WorkerContext = class extends Context.Service()("effect-cf/WorkerContext") {};
2059
+ /**
2060
+ * Access to the incoming `Request` currently handled by a worker or Durable Object fetch.
2061
+ */
1857
2062
  var NativeRequest = class extends Context.Service()("effect-cf/NativeRequest") {};
2063
+ /**
2064
+ * Returns `true` when the request is a websocket upgrade request.
2065
+ */
1858
2066
  const isWebSocketUpgrade = (request) => request.headers.get("Upgrade")?.toLowerCase() === "websocket";
1859
2067
  const reservedMethodNames$2 = /* @__PURE__ */ new Set([
1860
2068
  "constructor",
@@ -1873,30 +2081,61 @@ const reservedMethodNames$2 = /* @__PURE__ */ new Set([
1873
2081
  "webSocketError"
1874
2082
  ]);
1875
2083
  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 })));
1877
- const renderFetchSuccess = (effect) => Effect.flatMap(effect, (response) => response instanceof Response ? Effect.succeed(response) : Effect.map(Effect.context(), (context) => HttpServerResponse.toWeb(response, { context })));
1878
- const isWorkerOptions = (options) => typeof options === "object" && options !== null && ("eventLayer" in options || "fetch" in options || "queue" in options || "rpc" in options);
2084
+ const FetchSymbol = Symbol.for("effect-cf/Worker/fetch");
2085
+ const renderFetchSuccess = (effect) => Effect.suspend(() => {
2086
+ let nativeResponse;
2087
+ let webResponse;
2088
+ const handled = HttpEffect.toHandled(Effect.flatMap(effect, (response) => {
2089
+ if (response instanceof Response) {
2090
+ nativeResponse = response;
2091
+ return Effect.succeed(HttpServerResponse.empty());
2092
+ }
2093
+ return Effect.succeed(response);
2094
+ }), (request, response) => nativeResponse !== void 0 ? Effect.void : Effect.map(Effect.context(), (context) => {
2095
+ webResponse = HttpServerResponse.toWeb(HttpEffect.scopeTransferToStream(response), {
2096
+ withoutBody: request.method === "HEAD",
2097
+ context
2098
+ });
2099
+ }));
2100
+ const captured = () => nativeResponse ?? webResponse ?? new Response(null, { status: 500 });
2101
+ return Effect.matchCause(handled, {
2102
+ onFailure: captured,
2103
+ onSuccess: captured
2104
+ });
2105
+ });
2106
+ const isWorkerOptions = (options) => !Effect.isEffect(options);
2107
+ /**
2108
+ * Drains buffered OTLP telemetry once the fetch handler has produced its
2109
+ * response.
2110
+ *
2111
+ * The flush is handed to `ctx.waitUntil` so it never delays the response
2112
+ * (including streaming bodies still being consumed). It is a no-op when the
2113
+ * context does not contain an `OtlpExporter.Flusher`.
2114
+ */
2115
+ const scheduleTelemetryFlush = Effect.flatMap(Effect.serviceOption(OtlpExporter.Flusher), Option.match({
2116
+ onNone: () => Effect.void,
2117
+ onSome: (flusher) => Effect.flatMap(WorkerContext, (workerContext) => workerContext.waitUntil(flusher.flush))
2118
+ }));
1879
2119
  function make$9(layer, optionsOrFetch) {
1880
2120
  const options = isWorkerOptions(optionsOrFetch) ? optionsOrFetch : { fetch: optionsOrFetch };
1881
2121
  class EffectWorker extends WorkerEntrypoint {
1882
2122
  runtime;
1883
2123
  constructor(ctx, env) {
1884
2124
  super(ctx, env);
1885
- let runWaitUntilEffect = () => Promise.reject(/* @__PURE__ */ new Error("WorkerContext runtime is not initialized"));
1886
- 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));
1887
- const runtimeLayer = provideEntrypointServices(layer, services);
1888
- this.runtime = ManagedRuntime.make(runtimeLayer);
1889
- runWaitUntilEffect = (effect) => this.runtime.runPromiseExit(effect);
2125
+ this.runtime = makeEntrypointRuntime(layer, env, Layer.mergeAll(Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx))));
1890
2126
  }
1891
2127
  [RunSymbol$1](effect, runOptions = {}) {
1892
- const effectWithEventLayer = runOptions.eventLayer === false || options.eventLayer === void 0 ? effect : effect.pipe(Effect.provide(options.eventLayer, { local: true }));
1893
- return this.runtime.runPromise(Effect.scoped(effectWithEventLayer));
2128
+ return runEventPromise(this.runtime, effect, runOptions.eventLayer === false ? void 0 : options.eventLayer);
1894
2129
  }
1895
2130
  fetch(request) {
2131
+ return this[FetchSymbol](request);
2132
+ }
2133
+ [FetchSymbol](request, requestContext) {
1896
2134
  const fetchHandler = options.fetch;
1897
2135
  if (fetchHandler === void 0) return Promise.resolve(new Response("Not Found", { status: 404 }));
1898
- const requestServices = Layer.mergeAll(Layer.succeed(NativeRequest, request), Layer.succeed(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(request)));
1899
- return this[RunSymbol$1](renderFetchSuccess(fetchHandler).pipe(Effect.provide(requestServices)));
2136
+ const ctx = requestContext ?? this.ctx;
2137
+ const requestServices = Layer.mergeAll(Layer.succeed(NativeRequest, request), Layer.succeed(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(request)), Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx)));
2138
+ return this[RunSymbol$1](renderFetchSuccess(fetchHandler).pipe(Effect.tap(() => scheduleTelemetryFlush), Effect.provide(requestServices)));
1900
2139
  }
1901
2140
  queue(batch) {
1902
2141
  const queueHandler = options.queue;
@@ -1908,13 +2147,29 @@ function make$9(layer, optionsOrFetch) {
1908
2147
  defineEntrypointRpcMethods("Worker", EffectWorker.prototype, options.rpc, reservedMethodNames$2, (self, effect) => self[RunSymbol$1](effect));
1909
2148
  return assumeEntrypointClass(EffectWorker);
1910
2149
  }
2150
+ /**
2151
+ * Creates an `ExportedHandler`-compatible `{ fetch }` object backed by
2152
+ * {@link make}.
2153
+ *
2154
+ * The Effect runtime is cached per `env` identity, so the user layer builds
2155
+ * once per isolate instead of once per request. `ExecutionContext`-backed
2156
+ * services (`Worker.ExecutionContext`, `Worker.WorkerContext`) are still
2157
+ * provided fresh for every request. Layer finalizers do not run when the
2158
+ * isolate is evicted; Cloudflare provides no shutdown hook. Use `eventLayer`
2159
+ * for resources that must be finalized per event.
2160
+ */
1911
2161
  const makeFetchHandler = (layer, options) => {
1912
2162
  const WorkerClass = make$9(layer, options);
1913
- return { fetch: (request, env, ctx) => Promise.resolve(new WorkerClass(ctx, env).fetch(request)) };
2163
+ const instances = /* @__PURE__ */ new WeakMap();
2164
+ return { fetch: (request, env, ctx) => {
2165
+ let instance = instances.get(env);
2166
+ if (instance === void 0) {
2167
+ instance = new WorkerClass(ctx, env);
2168
+ instances.set(env, instance);
2169
+ }
2170
+ return instance[FetchSymbol](request, ctx);
2171
+ } };
1914
2172
  };
1915
- const Tag$10 = Tag$11;
1916
- const method$2 = method$3;
1917
- const implement$4 = implement$5;
1918
2173
  //#endregion
1919
2174
  //#region src/DurableObjectNamespace.ts
1920
2175
  var DurableObjectNamespace_exports = /* @__PURE__ */ __exportAll({
@@ -1929,11 +2184,19 @@ const expectedDurableObjectNamespace = "Durable Object namespace binding with ge
1929
2184
  /**
1930
2185
  * Failure raised when invoking an RPC method on a Durable Object stub.
1931
2186
  */
1932
- var DurableObjectRpcError = class extends Data.TaggedError("DurableObjectRpcError") {};
2187
+ var DurableObjectRpcError = class extends Data.TaggedError("DurableObjectRpcError") {
2188
+ get message() {
2189
+ return `Durable Object RPC method "${this.method}" failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
2190
+ }
2191
+ };
1933
2192
  /**
1934
2193
  * Failure raised when forwarding a request to a Durable Object stub.
1935
2194
  */
1936
- var DurableObjectFetchError = class extends Data.TaggedError("DurableObjectFetchError") {};
2195
+ var DurableObjectFetchError = class extends Data.TaggedError("DurableObjectFetchError") {
2196
+ get message() {
2197
+ return `Durable Object fetch failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
2198
+ }
2199
+ };
1937
2200
  const hasFunction$2 = (value, key) => typeof Reflect.get(value, key) === "function";
1938
2201
  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");
1939
2202
  const makeClient$7 = (definition) => {
@@ -1951,7 +2214,7 @@ const makeClient$7 = (definition) => {
1951
2214
  cause
1952
2215
  })
1953
2216
  });
1954
- const rpc = (stub, method, ...args) => Effect.gen(function* () {
2217
+ const rpc = Effect.fn("DurableObjectNamespace.rpc")(function* (stub, method, ...args) {
1955
2218
  const methodName = String(method);
1956
2219
  const encodedArgs = definition.definition === void 0 ? args : yield* encodeArgs(definition.definition, methodName, args).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1957
2220
  binding: definition.binding,
@@ -1964,7 +2227,7 @@ const makeClient$7 = (definition) => {
1964
2227
  cause
1965
2228
  }));
1966
2229
  });
1967
- const decodeSuccess$1 = (methodName, value) => Effect.gen(function* () {
2230
+ const decodeSuccess$1 = Effect.fn("DurableObjectNamespace.decodeSuccess")(function* (methodName, value) {
1968
2231
  if (definition.definition === void 0) return value;
1969
2232
  return yield* decodeSuccess(definition.definition, methodName, value).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1970
2233
  binding: definition.binding,
@@ -1972,7 +2235,7 @@ const makeClient$7 = (definition) => {
1972
2235
  cause
1973
2236
  })));
1974
2237
  });
1975
- const call = (stub, method, ...args) => Effect.gen(function* () {
2238
+ const call = Effect.fn("DurableObjectNamespace.call")(function* (stub, method, ...args) {
1976
2239
  const methodName = String(method);
1977
2240
  const value = yield* resolve(yield* rpc(stub, method, ...args)).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1978
2241
  binding: definition.binding,
@@ -1981,7 +2244,7 @@ const makeClient$7 = (definition) => {
1981
2244
  })));
1982
2245
  return yield* decodeSuccess$1(methodName, value);
1983
2246
  });
1984
- const scopedCall = (stub, method, ...args) => Effect.gen(function* () {
2247
+ const scopedCall = Effect.fn("DurableObjectNamespace.scopedCall")(function* (stub, method, ...args) {
1985
2248
  const methodName = String(method);
1986
2249
  const result = yield* rpc(stub, method, ...args);
1987
2250
  const value = yield* scoped(result);
@@ -2004,11 +2267,11 @@ const makeClient$7 = (definition) => {
2004
2267
  rpc,
2005
2268
  call,
2006
2269
  scopedCall,
2007
- unsafeRaw: Effect.succeed(namespace)
2270
+ rawUnsafe: Effect.succeed(namespace)
2008
2271
  });
2009
2272
  };
2010
2273
  };
2011
- const layer$9 = (tag, definition) => layer$20(tag, definition.binding, (value) => isDurableObjectNamespaceClient(value), makeClient$7(definition), { expected: expectedDurableObjectNamespace });
2274
+ const layer$9 = (tag, definition) => layer$19(tag, definition.binding, (value) => isDurableObjectNamespaceClient(value), makeClient$7(definition), { expected: expectedDurableObjectNamespace });
2012
2275
  const makeDirectMethods = (rpcDefinition, helpers) => {
2013
2276
  const methods = {};
2014
2277
  if (rpcDefinition !== void 0) {
@@ -2033,10 +2296,10 @@ const makeDirectMethods = (rpcDefinition, helpers) => {
2033
2296
  //#region src/DurableObjectDefinition.ts
2034
2297
  var DurableObjectDefinition_exports = /* @__PURE__ */ __exportAll({
2035
2298
  DurableObject: () => DurableObject$1,
2036
- Tag: () => Tag$9,
2037
- implement: () => implement$3,
2299
+ Tag: () => Tag$8,
2300
+ implement: () => implement$2,
2038
2301
  make: () => make$8,
2039
- method: () => method$1
2302
+ method: () => method
2040
2303
  });
2041
2304
  const reservedMethodNames$1 = /* @__PURE__ */ new Set([
2042
2305
  "constructor",
@@ -2050,7 +2313,7 @@ const reservedMethodNames$1 = /* @__PURE__ */ new Set([
2050
2313
  /**
2051
2314
  * Defines a single RPC method schema in a Durable Object definition.
2052
2315
  */
2053
- const method$1 = method$4;
2316
+ const method = method$2;
2054
2317
  /**
2055
2318
  * Creates a Durable Object RPC definition plus implementation/binding helpers.
2056
2319
  *
@@ -2072,47 +2335,48 @@ const makeDefinition$2 = (id, methods) => {
2072
2335
  rpc: wrapHandlers(definition, options.rpc)
2073
2336
  }) });
2074
2337
  };
2075
- const make$8 = (id, methods) => Tag$9()(id, methods);
2076
- const Tag$9 = () => (id, methods) => {
2338
+ const make$8 = (id, methods) => Tag$8()(id, methods);
2339
+ const Tag$8 = () => (id, methods) => {
2077
2340
  const definition = makeDefinition$2(id, methods);
2078
- const tag = Context.Service()(id);
2341
+ const serviceKey = `effect-cf/DurableObject/${id}`;
2342
+ const tag = Context.Service()(serviceKey);
2079
2343
  const bindingDefinition = (binding) => ({
2080
2344
  ...binding,
2081
2345
  definition
2082
2346
  });
2083
2347
  const layer = (binding) => layer$9(tag, bindingDefinition(binding));
2084
- const newUniqueId = Effect.fnUntraced(function* (options) {
2348
+ const newUniqueId = Effect.fn("DurableObject.newUniqueId")(function* (options) {
2085
2349
  return yield* (yield* tag).newUniqueId(options);
2086
2350
  });
2087
- const idFromName = Effect.fnUntraced(function* (name) {
2351
+ const idFromName = Effect.fn("DurableObject.idFromName")(function* (name) {
2088
2352
  return yield* (yield* tag).idFromName(name);
2089
2353
  });
2090
- const idFromString = Effect.fnUntraced(function* (value) {
2354
+ const idFromString = Effect.fn("DurableObject.idFromString")(function* (value) {
2091
2355
  return yield* (yield* tag).idFromString(value);
2092
2356
  });
2093
- const get = Effect.fnUntraced(function* (objectId, options) {
2357
+ const get = Effect.fn("DurableObject.get")(function* (objectId, options) {
2094
2358
  return yield* (yield* tag).get(objectId, options);
2095
2359
  });
2096
- const getByName = Effect.fnUntraced(function* (name, options) {
2360
+ const getByName = Effect.fn("DurableObject.getByName")(function* (name, options) {
2097
2361
  return yield* (yield* tag).getByName(name, options);
2098
2362
  });
2099
- const jurisdiction = Effect.fnUntraced(function* (value) {
2363
+ const jurisdiction = Effect.fn("DurableObject.jurisdiction")(function* (value) {
2100
2364
  return yield* (yield* tag).jurisdiction(value);
2101
2365
  });
2102
- const fetch = (stub, input, init) => Effect.gen(function* () {
2366
+ const fetch = Effect.fn("DurableObject.fetch")(function* (stub, input, init) {
2103
2367
  return yield* (yield* tag).fetch(stub, input, init);
2104
2368
  });
2105
- const rpc = (stub, method, ...args) => Effect.gen(function* () {
2369
+ const rpc = Effect.fn("DurableObject.rpc")(function* (stub, method, ...args) {
2106
2370
  return yield* (yield* tag).rpc(stub, method, ...args);
2107
2371
  });
2108
- const call = (stub, method, ...args) => Effect.gen(function* () {
2372
+ const call = Effect.fn("DurableObject.call")(function* (stub, method, ...args) {
2109
2373
  return yield* (yield* tag).call(stub, method, ...args);
2110
2374
  });
2111
- const scopedCall = (stub, method, ...args) => Effect.gen(function* () {
2375
+ const scopedCall = Effect.fn("DurableObject.scopedCall")(function* (stub, method, ...args) {
2112
2376
  return yield* (yield* tag).scopedCall(stub, method, ...args);
2113
2377
  });
2114
- const unsafeRaw = Effect.fnUntraced(function* () {
2115
- return yield* (yield* tag).unsafeRaw;
2378
+ const rawUnsafe = Effect.fnUntraced(function* () {
2379
+ return yield* (yield* tag).rawUnsafe;
2116
2380
  });
2117
2381
  const directMethods = makeDirectMethods(definition, {
2118
2382
  call,
@@ -2135,10 +2399,10 @@ const Tag$9 = () => (id, methods) => {
2135
2399
  rpc,
2136
2400
  call,
2137
2401
  scopedCall,
2138
- unsafeRaw
2402
+ rawUnsafe
2139
2403
  });
2140
2404
  };
2141
- const DurableObject$1 = Tag$9;
2405
+ const DurableObject$1 = Tag$8;
2142
2406
  const wrapHandlers = (definition, handlers) => {
2143
2407
  const wrapped = {};
2144
2408
  for (const key of Object.keys(definition.methods)) {
@@ -2154,7 +2418,7 @@ const wrapHandlers = (definition, handlers) => {
2154
2418
  /**
2155
2419
  * Helper for implementing handlers with the exact method shape of a definition.
2156
2420
  */
2157
- const implement$3 = (_definition, handlers) => handlers;
2421
+ const implement$2 = (_definition, handlers) => handlers;
2158
2422
  //#endregion
2159
2423
  //#region src/DurableObject.ts
2160
2424
  var DurableObject_exports = /* @__PURE__ */ __exportAll({
@@ -2181,15 +2445,12 @@ const make$7 = (layer, options = {}) => {
2181
2445
  runtime;
2182
2446
  constructor(state, env) {
2183
2447
  super(state, env);
2184
- const services = Layer.mergeAll(layer$10, ConfigProvider.layer(Effect.succeed(WorkerConfig.providerFromEnv(env))), Layer.succeed(DurableObjectState, fromDurableObjectState(state)), Layer.succeed(WorkerEnvironment, env));
2185
- const runtimeLayer = provideEntrypointServices(layer, services);
2186
- this.runtime = ManagedRuntime.make(runtimeLayer);
2448
+ this.runtime = makeEntrypointRuntime(layer, env, Layer.succeed(DurableObjectState, fromDurableObjectState(state)));
2187
2449
  const initialize = options.initialize;
2188
2450
  if (initialize !== void 0) state.waitUntil(this[RunSymbol](initialize, { eventLayer: false }));
2189
2451
  }
2190
2452
  [RunSymbol](effect, runOptions = {}) {
2191
- const effectWithEventLayer = runOptions.eventLayer === false || options.eventLayer === void 0 ? effect : effect.pipe(Effect.provide(options.eventLayer, { local: true }));
2192
- return this.runtime.runPromise(Effect.scoped(effectWithEventLayer));
2453
+ return runEventPromise(this.runtime, effect, runOptions.eventLayer === false ? void 0 : options.eventLayer);
2193
2454
  }
2194
2455
  fetch(request) {
2195
2456
  const fetchHandler = options.fetch;
@@ -2219,9 +2480,6 @@ const make$7 = (layer, options = {}) => {
2219
2480
  defineEntrypointRpcMethods("Durable Object", EffectDurableObject.prototype, options.rpc, reservedMethodNames, (self, effect) => self[RunSymbol](effect));
2220
2481
  return assumeEntrypointClass(EffectDurableObject);
2221
2482
  };
2222
- const Tag$8 = Tag$9;
2223
- const method = method$1;
2224
- const implement$2 = implement$3;
2225
2483
  //#endregion
2226
2484
  //#region src/DurableObjectAlarm.ts
2227
2485
  var DurableObjectAlarm_exports = /* @__PURE__ */ __exportAll({
@@ -2251,11 +2509,31 @@ CREATE INDEX IF NOT EXISTS idx_effect_cf_scheduled_alarms_run_at_storage_id
2251
2509
  const DEFAULT_PROCESS_DUE_ALARMS_LIMIT = 100;
2252
2510
  const DEFAULT_PROCESS_DUE_ALARMS_FAILURE_RESCHEDULE_AFTER = "30 seconds";
2253
2511
  const getScheduledEventId = (input) => `effect-cf-alarm:${encodeURIComponent(input.tag)}:${encodeURIComponent(input.id)}`;
2254
- var InvalidAlarmRefError = class extends Data.TaggedError("InvalidAlarmRefError") {};
2255
- var InvalidAlarmPayloadError = class extends Data.TaggedError("InvalidAlarmPayloadError") {};
2256
- var InvalidRepeatEveryError = class extends Data.TaggedError("InvalidRepeatEveryError") {};
2257
- var InvalidProcessDueAlarmsOptionsError = class extends Data.TaggedError("InvalidProcessDueAlarmsOptionsError") {};
2258
- var StoredAlarmDecodeError = class extends Data.TaggedError("StoredAlarmDecodeError") {};
2512
+ var InvalidAlarmRefError = class extends Data.TaggedError("InvalidAlarmRefError") {
2513
+ get message() {
2514
+ return `Invalid Durable Object alarm ref: ${causeMessage(this.cause)}`;
2515
+ }
2516
+ };
2517
+ var InvalidAlarmPayloadError = class extends Data.TaggedError("InvalidAlarmPayloadError") {
2518
+ get message() {
2519
+ return `Invalid Durable Object alarm payload: ${causeMessage(this.cause)}`;
2520
+ }
2521
+ };
2522
+ var InvalidRepeatEveryError = class extends Data.TaggedError("InvalidRepeatEveryError") {
2523
+ get message() {
2524
+ return `Invalid Durable Object alarm repeatEvery: ${causeMessage(this.cause)}`;
2525
+ }
2526
+ };
2527
+ var InvalidProcessDueAlarmsOptionsError = class extends Data.TaggedError("InvalidProcessDueAlarmsOptionsError") {
2528
+ get message() {
2529
+ return `Invalid processDueAlarms options: ${causeMessage(this.cause)}`;
2530
+ }
2531
+ };
2532
+ var StoredAlarmDecodeError = class extends Data.TaggedError("StoredAlarmDecodeError") {
2533
+ get message() {
2534
+ return `Failed to decode stored alarm "${this.storageId}": ${causeMessage(this.cause)}`;
2535
+ }
2536
+ };
2259
2537
  /**
2260
2538
  * Events handled by `processDueAlarms`.
2261
2539
  *
@@ -2299,7 +2577,7 @@ const toRepeatEveryMillis = (input) => {
2299
2577
  if (input === void 0) return Effect.succeed(null);
2300
2578
  return Effect.try({
2301
2579
  try: () => {
2302
- const millis = Duration.toMillis(Duration.fromInputUnsafe(input));
2580
+ const millis = Duration.toMillis(input);
2303
2581
  if (!Number.isFinite(millis) || millis <= 0) throw new Error("Alarm repeatEvery must be a positive finite duration");
2304
2582
  return Math.ceil(millis);
2305
2583
  },
@@ -2315,7 +2593,7 @@ const toAlarmDue = (row) => Effect.gen(function* () {
2315
2593
  _tag: "AlarmDue",
2316
2594
  id: row.alarm_id,
2317
2595
  payload: yield* decodeStoredPayload(row),
2318
- scheduledAt: DateTime.toUtc(DateTime.makeUnsafe(row.run_at)),
2596
+ scheduledAt: DateTime.makeUnsafe(row.run_at),
2319
2597
  tag: row.tag
2320
2598
  });
2321
2599
  });
@@ -2326,7 +2604,7 @@ const getProcessLimit = (options) => {
2326
2604
  };
2327
2605
  const toFailureRescheduleMillis = (input) => Effect.try({
2328
2606
  try: () => {
2329
- const millis = Duration.toMillis(Duration.fromInputUnsafe(input));
2607
+ const millis = Duration.toMillis(input);
2330
2608
  if (!Number.isFinite(millis) || millis <= 0) throw new Error("Alarm failure rescheduleAfter must be a positive finite duration");
2331
2609
  return Math.ceil(millis);
2332
2610
  },
@@ -2624,7 +2902,7 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2624
2902
  connectionsById.get(clientId)?.socket.raw.close();
2625
2903
  }),
2626
2904
  clientIds: Effect.sync(() => clientIds),
2627
- initialMessage: Effect.succeed(Option.none()),
2905
+ initialMessage: Effect.succeedNone,
2628
2906
  supportsAck: true,
2629
2907
  supportsTransferables: false,
2630
2908
  supportsSpanPropagation: true
@@ -2639,7 +2917,7 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2639
2917
  const connection = register(socket);
2640
2918
  const decoded = yield* Effect.try({
2641
2919
  try: () => connection.parser.decode(normalizeMessage(message)),
2642
- catch: RpcMessage.ResponseDefectEncoded
2920
+ catch: (cause) => cause
2643
2921
  });
2644
2922
  const run = writeRequest;
2645
2923
  if (run === void 0) {
@@ -2647,9 +2925,9 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2647
2925
  return;
2648
2926
  }
2649
2927
  for (const current of decoded) yield* run(connection.id, current);
2650
- }).pipe(Effect.catch((error) => {
2928
+ }).pipe(Effect.catch((cause) => {
2651
2929
  const connection = register(socket);
2652
- return send(connection, error);
2930
+ return Predicate.isTagged(cause, "MaxBufferSizeExceeded") ? Effect.ignore(connection.socket.close(1009, String(cause))) : send(connection, RpcMessage.ResponseDefectEncoded(cause));
2653
2931
  })),
2654
2932
  close: unregister,
2655
2933
  error: (socket, error) => Effect.gen(function* () {
@@ -2690,7 +2968,7 @@ const layer$7 = (options) => Layer.unwrap(Effect.gen(function* () {
2690
2968
  const state = yield* DurableObjectState;
2691
2969
  return SqliteClient.layer({
2692
2970
  ...options,
2693
- db: state.raw.storage.sql
2971
+ storage: state.raw.storage
2694
2972
  });
2695
2973
  }));
2696
2974
  //#endregion
@@ -2723,7 +3001,14 @@ const sendLimits = {
2723
3001
  /** Allowlisted custom headers, excluding `X-` prefixed headers. */
2724
3002
  maxAllowlistHeaders: 20
2725
3003
  };
2726
- /** Error codes reported by Cloudflare Email Sending. */
3004
+ /**
3005
+ * Error codes reported by Cloudflare Email Sending.
3006
+ *
3007
+ * Surfaced on {@link EmailOperationError} `code` on a best-effort basis: the
3008
+ * runtime attaches them as a non-standard `code` property on thrown errors,
3009
+ * which may be missing depending on the runtime or dev-time proxying
3010
+ * (miniflare remote bindings serialize errors and can strip it).
3011
+ */
2727
3012
  const emailErrorCodes = [
2728
3013
  "E_VALIDATION_ERROR",
2729
3014
  "E_FIELD_MISSING",
@@ -2747,9 +3032,24 @@ const emailErrorCodes = [
2747
3032
  "E_HEADERS_TOO_MANY"
2748
3033
  ];
2749
3034
  /** Error raised when a Cloudflare Send Email operation fails. */
2750
- var EmailOperationError = class extends Data.TaggedError("EmailOperationError") {};
3035
+ var EmailOperationError = class extends Data.TaggedError("EmailOperationError") {
3036
+ get message() {
3037
+ const code = this.code === void 0 ? "" : ` (${this.code})`;
3038
+ return `Email ${this.operation} failed for binding "${this.binding}"${code}: ${causeMessage(this.cause)}`;
3039
+ }
3040
+ };
2751
3041
  /** Error raised when a message violates documented Cloudflare Email Sending limits. */
2752
- var EmailValidationError = class extends Data.TaggedError("EmailValidationError") {};
3042
+ var EmailValidationError = class extends Data.TaggedError("EmailValidationError") {
3043
+ get message() {
3044
+ return `Email ${this.operation} for binding "${this.binding}" failed validation: ${violationsMessage(this.violations)}`;
3045
+ }
3046
+ };
3047
+ /**
3048
+ * Best-effort extraction of the Cloudflare error `code` from a thrown error.
3049
+ * Returns `undefined` when the property is absent — e.g. when a dev-time
3050
+ * proxy such as a miniflare remote binding (`"remote": true`) serializes the
3051
+ * error and strips non-standard properties.
3052
+ */
2753
3053
  const emailErrorCode = (cause) => {
2754
3054
  if (typeof cause !== "object" || cause === null) return;
2755
3055
  const code = Reflect.get(cause, "code");
@@ -2919,18 +3219,16 @@ const isEmailBinding = (value) => {
2919
3219
  const makeClient$6 = (definition, options) => (email) => {
2920
3220
  const runtime = email;
2921
3221
  const validate = options?.validate ?? true;
2922
- const send = ((message) => {
2923
- const dispatch = () => tryEmailPromise(definition.binding, "send", () => runtime.send(message));
2924
- if (!validate || !isEmailMessageBuilder(message)) return dispatch();
2925
- return validateSendInput(definition.binding, "send", message).pipe(Effect.flatMap(dispatch));
2926
- });
2927
3222
  return {
2928
3223
  definition,
2929
- send,
2930
- unsafeRaw: Effect.succeed(email)
3224
+ send: Effect.fn("Email.send")(function* (message) {
3225
+ if (validate && isEmailMessageBuilder(message)) yield* validateSendInput(definition.binding, "send", message);
3226
+ return yield* tryEmailPromise(definition.binding, "send", () => runtime.send(message));
3227
+ }),
3228
+ rawUnsafe: Effect.succeed(email)
2931
3229
  };
2932
3230
  };
2933
- const layer$6 = (tag, definition) => layer$20(tag, definition.binding, isEmailBinding, makeClient$6(definition, definition.send), { expected: expectedSendEmailBinding });
3231
+ const layer$6 = (tag, definition) => layer$19(tag, definition.binding, isEmailBinding, makeClient$6(definition, definition.send), { expected: expectedSendEmailBinding });
2934
3232
  const make$6 = (id) => Tag$7()(id);
2935
3233
  const Tag$7 = () => (id) => {
2936
3234
  const tag = Context.Service()(id);
@@ -2957,9 +3255,9 @@ const isHyperdrive = (value) => {
2957
3255
  const makeClient$5 = (definition) => (hyperdrive) => ({
2958
3256
  definition,
2959
3257
  connectionString: hyperdrive.connectionString,
2960
- unsafeRaw: Effect.succeed(hyperdrive)
3258
+ rawUnsafe: Effect.succeed(hyperdrive)
2961
3259
  });
2962
- const layer$5 = (tag, definition) => layer$20(tag, definition.binding, isHyperdrive, makeClient$5(definition), { expected: expectedHyperdrive });
3260
+ const layer$5 = (tag, definition) => layer$19(tag, definition.binding, isHyperdrive, makeClient$5(definition), { expected: expectedHyperdrive });
2963
3261
  const make$5 = (id) => Tag$6()(id);
2964
3262
  const Tag$6 = () => (id) => {
2965
3263
  const tag = Context.Service()(id);
@@ -2973,6 +3271,7 @@ const Tag$6 = () => (id) => {
2973
3271
  //#region src/Images.ts
2974
3272
  var Images_exports = /* @__PURE__ */ __exportAll({
2975
3273
  ImagesOperationError: () => ImagesOperationError,
3274
+ Step: () => Step,
2976
3275
  Tag: () => Tag$5,
2977
3276
  draw: () => draw,
2978
3277
  empty: () => empty,
@@ -2982,30 +3281,23 @@ var Images_exports = /* @__PURE__ */ __exportAll({
2982
3281
  makeClient: () => makeClient$4,
2983
3282
  transform: () => transform
2984
3283
  });
2985
- const TypeId = "effect-cf/Images/Steps";
3284
+ const TypeId = "~effect-cf/Images/Steps";
2986
3285
  const expectedImagesBinding = "Images binding with info() and input()";
2987
3286
  /** Error raised when a Cloudflare Images operation fails. */
2988
- var ImagesOperationError = class extends Data.TaggedError("ImagesOperationError") {};
3287
+ var ImagesOperationError = class extends Data.TaggedError("ImagesOperationError") {
3288
+ get message() {
3289
+ return `Images ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
3290
+ }
3291
+ };
3292
+ const Step = Data.taggedEnum();
2989
3293
  const makeSteps = (steps) => ({
2990
3294
  [TypeId]: TypeId,
2991
3295
  steps
2992
3296
  });
2993
3297
  /** Empty Images transformation pipeline. */
2994
3298
  const empty = makeSteps([]);
2995
- function transform(stepsOrTransform, transformValue) {
2996
- if (transformValue === void 0) return (steps) => transform(steps, stepsOrTransform);
2997
- return makeSteps([...stepsOrTransform.steps, {
2998
- _tag: "Transform",
2999
- transform: transformValue
3000
- }]);
3001
- }
3002
- function draw(stepsOrDraw, drawValue) {
3003
- if (drawValue === void 0) return (steps) => draw(steps, stepsOrDraw);
3004
- return makeSteps([...stepsOrDraw.steps, {
3005
- _tag: "Draw",
3006
- ...drawValue
3007
- }]);
3008
- }
3299
+ const transform = Function$1.dual(2, (steps, transformValue) => makeSteps([...steps.steps, Step.Transform({ transform: transformValue })]));
3300
+ const draw = Function$1.dual(2, (steps, drawValue) => makeSteps([...steps.steps, Step.Draw(drawValue)]));
3009
3301
  const imagesError = (binding, operation, cause) => new ImagesOperationError({
3010
3302
  binding,
3011
3303
  operation,
@@ -3019,7 +3311,7 @@ const tryImagesSync = (binding, operation, evaluate) => Effect.try({
3019
3311
  try: evaluate,
3020
3312
  catch: (cause) => imagesError(binding, operation, cause)
3021
3313
  });
3022
- const maybe$1 = (value) => value === null ? Option.none() : Option.some(value);
3314
+ const maybe = (value) => value === null ? Option.none() : Option.some(value);
3023
3315
  const hasFunction$1 = (value, key) => typeof Reflect.get(value, key) === "function";
3024
3316
  const isHostedImagesBinding = (value) => typeof value === "object" && value !== null && hasFunction$1(value, "image") && hasFunction$1(value, "upload") && hasFunction$1(value, "list");
3025
3317
  const isImagesBinding = (value) => typeof value === "object" && value !== null && hasFunction$1(value, "info") && hasFunction$1(value, "input");
@@ -3031,42 +3323,38 @@ const wrapResult = (binding, result) => ({
3031
3323
  });
3032
3324
  const wrapHandle = (binding, handle) => ({
3033
3325
  raw: handle,
3034
- details: tryImagesPromise(binding, "details", () => handle.details()).pipe(Effect.map(maybe$1)),
3035
- bytes: tryImagesPromise(binding, "bytes", () => handle.bytes()).pipe(Effect.map(maybe$1)),
3036
- update: (options) => tryImagesPromise(binding, "update", () => handle.update(options)),
3037
- delete: tryImagesPromise(binding, "delete", () => handle.delete())
3326
+ details: tryImagesPromise(binding, "details", () => handle.details()).pipe(Effect.map(maybe), Effect.withSpan("Images.details")),
3327
+ bytes: tryImagesPromise(binding, "bytes", () => handle.bytes()).pipe(Effect.map(maybe), Effect.withSpan("Images.bytes")),
3328
+ update: Effect.fn("Images.update")((options) => tryImagesPromise(binding, "update", () => handle.update(options))),
3329
+ delete: tryImagesPromise(binding, "delete", () => handle.delete()).pipe(Effect.withSpan("Images.delete"))
3038
3330
  });
3039
3331
  const wrapHosted = (binding, hosted) => ({
3040
3332
  image: (imageId) => wrapHandle(binding, hosted.image(imageId)),
3041
- upload: (image, options) => tryImagesPromise(binding, "upload", () => hosted.upload(image, options)),
3042
- list: (options) => tryImagesPromise(binding, "list", () => hosted.list(options)),
3043
- unsafeRaw: Effect.succeed(hosted)
3333
+ upload: Effect.fn("Images.upload")((image, options) => tryImagesPromise(binding, "upload", () => hosted.upload(image, options))),
3334
+ list: Effect.fn("Images.list")((options) => tryImagesPromise(binding, "list", () => hosted.list(options))),
3335
+ rawUnsafe: Effect.succeed(hosted)
3044
3336
  });
3045
3337
  const makeClient$4 = (definition) => (images) => {
3046
3338
  const input = (image, options) => tryImagesSync(definition.binding, "input", () => images.input(image, options));
3047
- const process = (steps, options) => Effect.gen(function* () {
3339
+ const process = Effect.fn("Images.process")(function* (steps, options) {
3048
3340
  let transformer = yield* input(options.stream, options.inputOptions);
3049
- for (const step of steps.steps) switch (step._tag) {
3050
- case "Draw":
3051
- transformer = yield* tryImagesSync(definition.binding, "draw", () => transformer.draw(step.image, step.options));
3052
- break;
3053
- case "Transform":
3054
- transformer = yield* tryImagesSync(definition.binding, "transform", () => transformer.transform(step.transform));
3055
- break;
3056
- }
3341
+ for (const step of steps.steps) transformer = yield* Step.$match(step, {
3342
+ Draw: (drawStep) => tryImagesSync(definition.binding, "draw", () => transformer.draw(drawStep.image, drawStep.options)),
3343
+ Transform: (transformStep) => tryImagesSync(definition.binding, "transform", () => transformer.transform(transformStep.transform))
3344
+ });
3057
3345
  const result = yield* tryImagesPromise(definition.binding, "output", () => transformer.output(options.outputOptions));
3058
3346
  return wrapResult(definition.binding, result);
3059
3347
  });
3060
3348
  return {
3061
3349
  definition,
3062
- info: (image, options) => tryImagesPromise(definition.binding, "info", () => images.info(image, options)),
3350
+ info: Effect.fn("Images.info")((image, options) => tryImagesPromise(definition.binding, "info", () => images.info(image, options))),
3063
3351
  input,
3064
3352
  process,
3065
3353
  hosted: isHostedImagesBinding(images.hosted) ? Option.some(wrapHosted(definition.binding, images.hosted)) : Option.none(),
3066
- unsafeRaw: Effect.succeed(images)
3354
+ rawUnsafe: Effect.succeed(images)
3067
3355
  };
3068
3356
  };
3069
- const layer$4 = (tag, definition) => layer$20(tag, definition.binding, isImagesBinding, makeClient$4(definition), { expected: expectedImagesBinding });
3357
+ const layer$4 = (tag, definition) => layer$19(tag, definition.binding, isImagesBinding, makeClient$4(definition), { expected: expectedImagesBinding });
3070
3358
  const make$4 = (id) => Tag$5()(id);
3071
3359
  const Tag$5 = () => (id) => {
3072
3360
  const tag = Context.Service()(id);
@@ -3087,9 +3375,11 @@ var Kv_exports = /* @__PURE__ */ __exportAll({
3087
3375
  });
3088
3376
  const expectedKvNamespace = "KV namespace binding with get(), put(), delete(), getWithMetadata(), and list()";
3089
3377
  /** Error raised when a KV operation fails. */
3090
- var KvOperationError = class extends Data.TaggedError("KvOperationError") {};
3091
- const maybeString = (value) => value === null || value === void 0 ? Option.none() : Option.some(value);
3092
- const maybeNumber = (value) => value === void 0 ? Option.none() : Option.some(value);
3378
+ var KvOperationError = class extends Data.TaggedError("KvOperationError") {
3379
+ get message() {
3380
+ return `Kv ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
3381
+ }
3382
+ };
3093
3383
  const kvError = (binding, operation, cause) => new KvOperationError({
3094
3384
  binding,
3095
3385
  operation,
@@ -3107,22 +3397,32 @@ const isKvNamespace = (value) => {
3107
3397
  const makeClient$3 = (definition) => {
3108
3398
  const encodeKey = Schema.encodeEffect(definition.key);
3109
3399
  const decodeKey = Schema.decodeUnknownEffect(definition.key);
3110
- const encodeValue = Schema.encodeEffect(Schema.fromJsonString(Schema.toCodecJson(definition.value)));
3111
- const decodeValue = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.toCodecJson(definition.value)));
3400
+ const jsonValue = Schema.fromJsonString(Schema.toCodecJson(definition.value));
3401
+ const encodeValue = Schema.encodeEffect(jsonValue);
3402
+ const decodeValue = Schema.decodeUnknownEffect(jsonValue);
3112
3403
  return (kv) => ({
3113
3404
  definition,
3114
- put: Effect.fnUntraced(function* (key, value, options) {
3405
+ put: Effect.fn("Kv.put", { attributes: {
3406
+ binding: definition.binding,
3407
+ operation: "put"
3408
+ } })(function* (key, value, options) {
3115
3409
  const keyEncoded = yield* encodeKey(key);
3116
3410
  const valueEncoded = yield* encodeValue(value);
3117
3411
  yield* tryKvPromise(definition.binding, "put", () => kv.put(keyEncoded, valueEncoded, options));
3118
3412
  }),
3119
- get: Effect.fnUntraced(function* (key) {
3413
+ get: Effect.fn("Kv.get", { attributes: {
3414
+ binding: definition.binding,
3415
+ operation: "get"
3416
+ } })(function* (key) {
3120
3417
  const keyEncoded = yield* encodeKey(key);
3121
3418
  const valueEncoded = yield* tryKvPromise(definition.binding, "get", () => kv.get(keyEncoded));
3122
3419
  if (valueEncoded === null) return Option.none();
3123
3420
  return yield* decodeValue(valueEncoded).pipe(Effect.map(Option.some));
3124
3421
  }),
3125
- getWithMetadata: Effect.fnUntraced(function* (key, metadataSchema) {
3422
+ getWithMetadata: Effect.fn("Kv.getWithMetadata", { attributes: {
3423
+ binding: definition.binding,
3424
+ operation: "getWithMetadata"
3425
+ } })(function* (key, metadataSchema) {
3126
3426
  const keyEncoded = yield* encodeKey(key);
3127
3427
  const result = yield* tryKvPromise(definition.binding, "getWithMetadata", () => kv.getWithMetadata(keyEncoded));
3128
3428
  if (result.value === null) return Option.none();
@@ -3131,10 +3431,13 @@ const makeClient$3 = (definition) => {
3131
3431
  return Option.some({
3132
3432
  value,
3133
3433
  metadata,
3134
- cacheStatus: maybeString(result.cacheStatus)
3434
+ cacheStatus: Option.fromNullishOr(result.cacheStatus)
3135
3435
  });
3136
3436
  }),
3137
- list: Effect.fnUntraced(function* (options) {
3437
+ list: Effect.fn("Kv.list", { attributes: {
3438
+ binding: definition.binding,
3439
+ operation: "list"
3440
+ } })(function* (options) {
3138
3441
  const { metadataSchema, ...kvOptions } = options ?? {};
3139
3442
  const result = yield* tryKvPromise(definition.binding, "list", () => kv.list(kvOptions));
3140
3443
  const keys = [];
@@ -3143,25 +3446,28 @@ const makeClient$3 = (definition) => {
3143
3446
  const decodedMetadata = key.metadata === void 0 ? Option.none() : metadataSchema === void 0 ? Option.some(key.metadata) : Option.some(yield* Schema.decodeUnknownEffect(metadataSchema)(key.metadata));
3144
3447
  keys.push({
3145
3448
  name: decodedName,
3146
- expiration: maybeNumber(key.expiration),
3449
+ expiration: Option.fromUndefinedOr(key.expiration),
3147
3450
  metadata: decodedMetadata
3148
3451
  });
3149
3452
  }
3150
3453
  return {
3151
3454
  keys,
3152
3455
  listComplete: result.list_complete,
3153
- cursor: maybeString("cursor" in result ? result.cursor : void 0),
3154
- cacheStatus: maybeString(result.cacheStatus)
3456
+ cursor: Option.fromNullishOr("cursor" in result ? result.cursor : void 0),
3457
+ cacheStatus: Option.fromNullishOr(result.cacheStatus)
3155
3458
  };
3156
3459
  }),
3157
- remove: Effect.fnUntraced(function* (key) {
3460
+ delete: Effect.fn("Kv.delete", { attributes: {
3461
+ binding: definition.binding,
3462
+ operation: "delete"
3463
+ } })(function* (key) {
3158
3464
  const keyEncoded = yield* encodeKey(key);
3159
3465
  yield* tryKvPromise(definition.binding, "delete", () => kv.delete(keyEncoded));
3160
3466
  }),
3161
- unsafeRaw: Effect.succeed(kv)
3467
+ rawUnsafe: Effect.succeed(kv)
3162
3468
  });
3163
3469
  };
3164
- const layer$3 = (tag, definition) => layer$20(tag, definition.binding, isKvNamespace, makeClient$3(definition), { expected: expectedKvNamespace });
3470
+ const layer$3 = (tag, definition) => layer$19(tag, definition.binding, isKvNamespace, makeClient$3(definition), { expected: expectedKvNamespace });
3165
3471
  const makeDefinition$1 = (id, definition) => {
3166
3472
  const kvDefinition = {
3167
3473
  id,
@@ -3197,7 +3503,11 @@ var R2_exports = /* @__PURE__ */ __exportAll({
3197
3503
  });
3198
3504
  const expectedR2Bucket = "R2 bucket binding with head(), get(), put(), createMultipartUpload(), resumeMultipartUpload(), delete(), and list()";
3199
3505
  /** Error raised when an R2 operation fails. */
3200
- var R2OperationError = class extends Data.TaggedError("R2OperationError") {};
3506
+ var R2OperationError = class extends Data.TaggedError("R2OperationError") {
3507
+ get message() {
3508
+ return `R2 ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
3509
+ }
3510
+ };
3201
3511
  const r2Error = (binding, operation, cause) => new R2OperationError({
3202
3512
  binding,
3203
3513
  operation,
@@ -3211,7 +3521,10 @@ const tryR2Sync = (binding, operation, evaluate) => Effect.try({
3211
3521
  try: evaluate,
3212
3522
  catch: (cause) => r2Error(binding, operation, cause)
3213
3523
  });
3214
- const maybe = (value) => value === null ? Option.none() : Option.some(value);
3524
+ const spanOptions$1 = (binding, operation) => ({ attributes: {
3525
+ binding,
3526
+ operation
3527
+ } });
3215
3528
  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";
3216
3529
  const wrapObjectBody = (binding, object) => ({
3217
3530
  key: object.key,
@@ -3232,11 +3545,11 @@ const wrapObjectBody = (binding, object) => ({
3232
3545
  get bodyUsed() {
3233
3546
  return object.bodyUsed;
3234
3547
  },
3235
- arrayBuffer: tryR2Promise(binding, "arrayBuffer", () => object.arrayBuffer()),
3236
- bytes: tryR2Promise(binding, "bytes", () => object.bytes()),
3237
- text: tryR2Promise(binding, "text", () => object.text()),
3238
- json: () => tryR2Promise(binding, "json", () => object.json()),
3239
- blob: tryR2Promise(binding, "blob", () => object.blob())
3548
+ arrayBuffer: tryR2Promise(binding, "arrayBuffer", () => object.arrayBuffer()).pipe(Effect.withSpan("R2.arrayBuffer", spanOptions$1(binding, "arrayBuffer"))),
3549
+ bytes: tryR2Promise(binding, "bytes", () => object.bytes()).pipe(Effect.withSpan("R2.bytes", spanOptions$1(binding, "bytes"))),
3550
+ text: tryR2Promise(binding, "text", () => object.text()).pipe(Effect.withSpan("R2.text", spanOptions$1(binding, "text"))),
3551
+ json: () => tryR2Promise(binding, "json", () => object.json()).pipe(Effect.withSpan("R2.json", spanOptions$1(binding, "json"))),
3552
+ blob: tryR2Promise(binding, "blob", () => object.blob()).pipe(Effect.withSpan("R2.blob", spanOptions$1(binding, "blob")))
3240
3553
  });
3241
3554
  const wrapGetResult = (binding, object) => {
3242
3555
  if (object === null || !isR2ObjectBody(object)) return object;
@@ -3252,33 +3565,33 @@ const makeClient$2 = (definition) => {
3252
3565
  raw: upload,
3253
3566
  key: upload.key,
3254
3567
  uploadId: upload.uploadId,
3255
- uploadPart: (partNumber, value, options) => tryR2Promise(definition.binding, "uploadPart", () => upload.uploadPart(partNumber, value, options)),
3256
- abort: tryR2Promise(definition.binding, "abortMultipartUpload", () => upload.abort()),
3257
- complete: (uploadedParts) => tryR2Promise(definition.binding, "completeMultipartUpload", () => upload.complete([...uploadedParts]))
3568
+ uploadPart: Effect.fn("R2.uploadPart", spanOptions$1(definition.binding, "uploadPart"))((partNumber, value, options) => tryR2Promise(definition.binding, "uploadPart", () => upload.uploadPart(partNumber, value, options))),
3569
+ abort: tryR2Promise(definition.binding, "abortMultipartUpload", () => upload.abort()).pipe(Effect.withSpan("R2.abortMultipartUpload", spanOptions$1(definition.binding, "abortMultipartUpload"))),
3570
+ complete: Effect.fn("R2.completeMultipartUpload", spanOptions$1(definition.binding, "completeMultipartUpload"))((uploadedParts) => tryR2Promise(definition.binding, "completeMultipartUpload", () => upload.complete([...uploadedParts])))
3258
3571
  });
3259
3572
  return (bucket) => {
3260
- const get = ((key, options) => tryR2Promise(definition.binding, "get", () => bucket.get(key, options)).pipe(Effect.map((object) => maybe(wrapGetResult(definition.binding, object)))));
3573
+ 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)))));
3261
3574
  return {
3262
3575
  definition,
3263
- head: (key) => tryR2Promise(definition.binding, "head", () => bucket.head(key)).pipe(Effect.map(maybe)),
3576
+ head: Effect.fn("R2.head", spanOptions$1(definition.binding, "head"))((key) => tryR2Promise(definition.binding, "head", () => bucket.head(key)).pipe(Effect.map(Option.fromNullOr))),
3264
3577
  get,
3265
- put: ((key, value, options) => tryR2Promise(definition.binding, "put", () => bucket.put(key, value, options)).pipe(Effect.map((object) => {
3578
+ 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) => {
3266
3579
  if (object === null) return Option.none();
3267
3580
  if (options !== void 0 && "onlyIf" in options) return Option.some(object);
3268
3581
  return object;
3269
3582
  }))),
3270
- createMultipartUpload: (key, options) => tryR2Promise(definition.binding, "createMultipartUpload", () => bucket.createMultipartUpload(key, options)).pipe(Effect.map(wrapUpload)),
3271
- resumeMultipartUpload: (key, uploadId) => tryR2Sync(definition.binding, "resumeMultipartUpload", () => wrapUpload(bucket.resumeMultipartUpload(key, uploadId))),
3272
- delete: (keys) => {
3583
+ createMultipartUpload: Effect.fn("R2.createMultipartUpload", spanOptions$1(definition.binding, "createMultipartUpload"))((key, options) => tryR2Promise(definition.binding, "createMultipartUpload", () => bucket.createMultipartUpload(key, options)).pipe(Effect.map(wrapUpload))),
3584
+ resumeMultipartUpload: Effect.fn("R2.resumeMultipartUpload", spanOptions$1(definition.binding, "resumeMultipartUpload"))((key, uploadId) => tryR2Sync(definition.binding, "resumeMultipartUpload", () => wrapUpload(bucket.resumeMultipartUpload(key, uploadId)))),
3585
+ delete: Effect.fn("R2.delete", spanOptions$1(definition.binding, "delete"))((keys) => {
3273
3586
  const nativeKeys = typeof keys === "string" ? keys : [...keys];
3274
3587
  return tryR2Promise(definition.binding, "delete", () => bucket.delete(nativeKeys));
3275
- },
3276
- list: (options) => tryR2Promise(definition.binding, "list", () => bucket.list(options)),
3277
- unsafeRaw: Effect.succeed(bucket)
3588
+ }),
3589
+ list: Effect.fn("R2.list", spanOptions$1(definition.binding, "list"))((options) => tryR2Promise(definition.binding, "list", () => bucket.list(options))),
3590
+ rawUnsafe: Effect.succeed(bucket)
3278
3591
  };
3279
3592
  };
3280
3593
  };
3281
- const layer$2 = (tag, definition) => layer$20(tag, definition.binding, isR2Bucket, makeClient$2(definition), { expected: expectedR2Bucket });
3594
+ const layer$2 = (tag, definition) => layer$19(tag, definition.binding, isR2Bucket, makeClient$2(definition), { expected: expectedR2Bucket });
3282
3595
  const make$3 = (id) => Tag$3()(id);
3283
3596
  const Tag$3 = () => (id) => {
3284
3597
  const tag = Context.Service()(id);
@@ -3289,17 +3602,83 @@ const Tag$3 = () => (id) => {
3289
3602
  });
3290
3603
  };
3291
3604
  //#endregion
3605
+ //#region src/Vectorize.ts
3606
+ var Vectorize_exports = /* @__PURE__ */ __exportAll({
3607
+ Tag: () => Tag$2,
3608
+ VectorizeOperationError: () => VectorizeOperationError,
3609
+ isVectorizeBinding: () => isVectorizeBinding,
3610
+ layer: () => layer$1,
3611
+ make: () => make$2,
3612
+ makeClient: () => makeClient$1
3613
+ });
3614
+ const expectedVectorizeBinding = "Vectorize index binding with describe(), query(), insert(), upsert(), deleteByIds(), and getByIds()";
3615
+ /** Error raised when a Vectorize operation fails. */
3616
+ var VectorizeOperationError = class extends Data.TaggedError("VectorizeOperationError") {
3617
+ get message() {
3618
+ return `Vectorize ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
3619
+ }
3620
+ };
3621
+ const vectorizeError = (binding, operation, cause) => new VectorizeOperationError({
3622
+ binding,
3623
+ operation,
3624
+ cause
3625
+ });
3626
+ const tryVectorizePromise = (binding, operation, evaluate) => Effect.tryPromise({
3627
+ try: evaluate,
3628
+ catch: (cause) => vectorizeError(binding, operation, cause)
3629
+ });
3630
+ const spanOptions = (binding, operation) => ({ attributes: {
3631
+ binding,
3632
+ operation
3633
+ } });
3634
+ const hasFunction = (value, key) => typeof Reflect.get(value, key) === "function";
3635
+ 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");
3636
+ const makeClient$1 = (definition) => (index) => {
3637
+ const runtime = index;
3638
+ const deleteByIds = Effect.fn("Vectorize.deleteByIds", spanOptions(definition.binding, "deleteByIds"))((ids) => tryVectorizePromise(definition.binding, "deleteByIds", () => runtime.deleteByIds([...ids])));
3639
+ return {
3640
+ definition,
3641
+ describe: tryVectorizePromise(definition.binding, "describe", () => runtime.describe()).pipe(Effect.withSpan("Vectorize.describe", spanOptions(definition.binding, "describe"))),
3642
+ query: Effect.fn("Vectorize.query", spanOptions(definition.binding, "query"))((vector, options) => tryVectorizePromise(definition.binding, "query", () => runtime.query(vector, options))),
3643
+ 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()")))),
3644
+ insert: Effect.fn("Vectorize.insert", spanOptions(definition.binding, "insert"))((vectors) => tryVectorizePromise(definition.binding, "insert", () => runtime.insert([...vectors]))),
3645
+ upsert: Effect.fn("Vectorize.upsert", spanOptions(definition.binding, "upsert"))((vectors) => tryVectorizePromise(definition.binding, "upsert", () => runtime.upsert([...vectors]))),
3646
+ deleteByIds,
3647
+ delete: deleteByIds,
3648
+ getByIds: Effect.fn("Vectorize.getByIds", spanOptions(definition.binding, "getByIds"))((ids) => tryVectorizePromise(definition.binding, "getByIds", () => runtime.getByIds([...ids]))),
3649
+ rawUnsafe: Effect.succeed(index)
3650
+ };
3651
+ };
3652
+ const layer$1 = (tag, definition) => layer$19(tag, definition.binding, isVectorizeBinding, makeClient$1(definition), { expected: expectedVectorizeBinding });
3653
+ const make$2 = (id) => Tag$2()(id);
3654
+ const Tag$2 = () => (id) => {
3655
+ const tag = Context.Service()(id);
3656
+ const makeLayer = (definition) => layer$1(tag, definition);
3657
+ return Object.assign(tag, {
3658
+ id,
3659
+ layer: makeLayer
3660
+ });
3661
+ };
3662
+ //#endregion
3292
3663
  //#region src/WorkflowBinding.ts
3293
3664
  var WorkflowBinding_exports = /* @__PURE__ */ __exportAll({
3294
3665
  WorkflowOperationError: () => WorkflowOperationError,
3295
3666
  WorkflowResultDecodeError: () => WorkflowResultDecodeError,
3296
3667
  isWorkflow: () => isWorkflow,
3297
- layer: () => layer$1,
3298
- makeClient: () => makeClient$1
3668
+ layer: () => layer,
3669
+ makeClient: () => makeClient
3299
3670
  });
3300
3671
  const expectedWorkflow = "Workflow binding with create(), createBatch(), and get()";
3301
- var WorkflowOperationError = class extends Data.TaggedError("WorkflowOperationError") {};
3302
- var WorkflowResultDecodeError = class extends Data.TaggedError("WorkflowResultDecodeError") {};
3672
+ var WorkflowOperationError = class extends Data.TaggedError("WorkflowOperationError") {
3673
+ get message() {
3674
+ return `Workflow ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
3675
+ }
3676
+ };
3677
+ var WorkflowResultDecodeError = class extends Data.TaggedError("WorkflowResultDecodeError") {
3678
+ get message() {
3679
+ return `Workflow result decode failed for binding "${this.binding}" instance "${this.instanceId}": ${causeMessage(this.cause)}`;
3680
+ }
3681
+ };
3303
3682
  const workflowError = (binding, operation, cause) => new WorkflowOperationError({
3304
3683
  binding,
3305
3684
  operation,
@@ -3314,7 +3693,7 @@ const isWorkflow = (value) => {
3314
3693
  const resource = value;
3315
3694
  return typeof resource.create === "function" && typeof resource.createBatch === "function" && typeof resource.get === "function";
3316
3695
  };
3317
- const makeClient$1 = (definition) => {
3696
+ const makeClient = (definition) => {
3318
3697
  const encodePayload = Schema.encodeEffect(definition.payload);
3319
3698
  const decodeResult = Schema.decodeUnknownEffect(definition.result);
3320
3699
  const wrapInstance = (raw) => {
@@ -3342,7 +3721,10 @@ const makeClient$1 = (definition) => {
3342
3721
  };
3343
3722
  };
3344
3723
  return (workflow) => ({
3345
- create: Effect.fnUntraced(function* (payload, options) {
3724
+ create: Effect.fn("WorkflowBinding.create", { attributes: {
3725
+ binding: definition.binding,
3726
+ operation: "create"
3727
+ } })(function* (payload, options) {
3346
3728
  const encoded = yield* encodePayload(payload);
3347
3729
  const raw = yield* tryWorkflowPromise(definition.binding, "create", () => workflow.create({
3348
3730
  ...options,
@@ -3350,7 +3732,10 @@ const makeClient$1 = (definition) => {
3350
3732
  }));
3351
3733
  return wrapInstance(raw);
3352
3734
  }),
3353
- createBatch: Effect.fnUntraced(function* (batch) {
3735
+ createBatch: Effect.fn("WorkflowBinding.createBatch", { attributes: {
3736
+ binding: definition.binding,
3737
+ operation: "createBatch"
3738
+ } })(function* (batch) {
3354
3739
  const encodedBatch = [];
3355
3740
  for (const item of batch) {
3356
3741
  const { payload, ...options } = item;
@@ -3362,17 +3747,17 @@ const makeClient$1 = (definition) => {
3362
3747
  return (yield* tryWorkflowPromise(definition.binding, "createBatch", () => workflow.createBatch(encodedBatch))).map(wrapInstance);
3363
3748
  }),
3364
3749
  get: (instanceId) => tryWorkflowPromise(definition.binding, "get", () => workflow.get(instanceId)).pipe(Effect.map(wrapInstance)),
3365
- unsafeRaw: Effect.succeed(workflow)
3750
+ rawUnsafe: Effect.succeed(workflow)
3366
3751
  });
3367
3752
  };
3368
- const layer$1 = (tag, definition) => layer$20(tag, definition.binding, (value) => isWorkflow(value), makeClient$1(definition), { expected: expectedWorkflow });
3753
+ const layer = (tag, definition) => layer$19(tag, definition.binding, (value) => isWorkflow(value), makeClient(definition), { expected: expectedWorkflow });
3369
3754
  //#endregion
3370
3755
  //#region src/WorkflowDefinition.ts
3371
3756
  var WorkflowDefinition_exports = /* @__PURE__ */ __exportAll({
3372
- Tag: () => Tag$2,
3757
+ Tag: () => Tag$1,
3373
3758
  Workflow: () => Workflow,
3374
3759
  implement: () => implement$1,
3375
- make: () => make$2
3760
+ make: () => make$1
3376
3761
  });
3377
3762
  const makeDefinition = (id, definition) => {
3378
3763
  const workflowDefinition = {
@@ -3380,13 +3765,13 @@ const makeDefinition = (id, definition) => {
3380
3765
  payload: definition.payload,
3381
3766
  result: definition.result
3382
3767
  };
3383
- return Object.assign(workflowDefinition, { make: (layer, options) => make$1(layer, { run: wrapHandler(workflowDefinition, options.run) }) });
3768
+ return Object.assign(workflowDefinition, { make: (layer, options) => make(layer, { run: wrapHandler(workflowDefinition, options.run) }) });
3384
3769
  };
3385
- const make$2 = (id, definition) => Tag$2()(id, definition);
3386
- const Tag$2 = () => (id, definition) => {
3770
+ const make$1 = (id, definition) => Tag$1()(id, definition);
3771
+ const Tag$1 = () => (id, definition) => {
3387
3772
  const workflowDefinition = makeDefinition(id, definition);
3388
- const tag = Context.Service()(id);
3389
- const layer = (binding) => layer$1(tag, {
3773
+ const tag = Context.Service()(`effect-cf/Workflow/${id}`);
3774
+ const layer$20 = (binding) => layer(tag, {
3390
3775
  ...binding,
3391
3776
  payload: definition.payload,
3392
3777
  result: definition.result
@@ -3400,26 +3785,24 @@ const Tag$2 = () => (id, definition) => {
3400
3785
  const get = Effect.fnUntraced(function* (instanceId) {
3401
3786
  return yield* (yield* tag).get(instanceId);
3402
3787
  });
3403
- const unsafeRaw = Effect.fnUntraced(function* () {
3404
- return yield* (yield* tag).unsafeRaw;
3405
- });
3788
+ const rawUnsafe = Effect.flatMap(tag, (workflow) => workflow.rawUnsafe);
3406
3789
  return Object.assign(tag, {
3407
3790
  id: workflowDefinition.id,
3408
3791
  payload: workflowDefinition.payload,
3409
3792
  result: workflowDefinition.result,
3410
3793
  make: workflowDefinition.make,
3411
- layer,
3794
+ layer: layer$20,
3412
3795
  create,
3413
3796
  createBatch,
3414
3797
  get,
3415
- unsafeRaw
3798
+ rawUnsafe
3416
3799
  });
3417
3800
  };
3418
- const Workflow = Tag$2;
3801
+ const Workflow = Tag$1;
3419
3802
  const wrapHandler = (definition, handler) => {
3420
3803
  const decodePayload = Schema.decodeUnknownEffect(definition.payload);
3421
3804
  const encodeResult = Schema.encodeEffect(definition.result);
3422
- return (payload) => Effect.gen(function* () {
3805
+ return Effect.fnUntraced(function* (payload) {
3423
3806
  const decodedPayload = yield* decodePayload(payload);
3424
3807
  const decodedEvent = {
3425
3808
  ...yield* WorkflowEvent$1,
@@ -3432,19 +3815,31 @@ const wrapHandler = (definition, handler) => {
3432
3815
  const implement$1 = (_definition, handler) => handler;
3433
3816
  //#endregion
3434
3817
  //#region src/Workflow.ts
3818
+ /**
3819
+ * Effect wrapper for Cloudflare Workflows entrypoints and bindings; distinct
3820
+ * from Effect's runtime-agnostic `effect/unstable/workflow` cluster module.
3821
+ */
3435
3822
  var Workflow_exports = /* @__PURE__ */ __exportAll({
3436
- Tag: () => Tag$1,
3823
+ Tag: () => Tag,
3437
3824
  WorkflowEvent: () => WorkflowEvent$1,
3438
3825
  WorkflowStep: () => WorkflowStep$1,
3439
3826
  WorkflowStepContext: () => WorkflowStepContext$1,
3827
+ WorkflowStepError: () => WorkflowStepError,
3440
3828
  implement: () => implement,
3441
- make: () => make$1,
3829
+ make: () => make,
3442
3830
  sleep: () => sleep,
3443
3831
  sleepUntil: () => sleepUntil,
3444
3832
  step: () => step,
3445
3833
  waitForEvent: () => waitForEvent
3446
3834
  });
3447
3835
  var WorkflowEvent$1 = class extends Context.Service()("effect-cf/WorkflowEvent") {};
3836
+ /** Failure raised when a Cloudflare Workflow step operation rejects. */
3837
+ var WorkflowStepError = class extends Data.TaggedError("WorkflowStepError") {
3838
+ get message() {
3839
+ const step = this.step === void 0 ? "" : ` in step "${this.step}"`;
3840
+ return `Workflow ${this.operation} failed${step}: ${causeMessage(this.cause)}`;
3841
+ }
3842
+ };
3448
3843
  var WorkflowStep$1 = class extends Context.Service()("effect-cf/WorkflowStep") {};
3449
3844
  var WorkflowStepContext$1 = class extends Context.Service()("effect-cf/WorkflowStepContext") {};
3450
3845
  const fromWorkflowEvent = (event) => ({
@@ -3462,35 +3857,47 @@ const fromWorkflowStep = (step, runPromise) => ({
3462
3857
  const rawStep = step;
3463
3858
  return config === void 0 ? rawStep.do(name, run) : rawStep.do(name, config, run);
3464
3859
  },
3465
- catch: (cause) => cause
3860
+ catch: (cause) => new WorkflowStepError({
3861
+ step: name,
3862
+ operation: "do",
3863
+ cause
3864
+ })
3466
3865
  }))),
3467
3866
  sleep: (name, duration) => Effect.tryPromise({
3468
3867
  try: () => step.sleep(name, duration),
3469
- catch: (cause) => cause
3868
+ catch: (cause) => new WorkflowStepError({
3869
+ step: name,
3870
+ operation: "sleep",
3871
+ cause
3872
+ })
3470
3873
  }),
3471
3874
  sleepUntil: (name, timestamp) => Effect.tryPromise({
3472
3875
  try: () => step.sleepUntil(name, timestamp),
3473
- catch: (cause) => cause
3876
+ catch: (cause) => new WorkflowStepError({
3877
+ step: name,
3878
+ operation: "sleepUntil",
3879
+ cause
3880
+ })
3474
3881
  }),
3475
3882
  waitForEvent: (name, options) => Effect.tryPromise({
3476
3883
  try: () => step.waitForEvent(name, options),
3477
- catch: (cause) => cause
3884
+ catch: (cause) => new WorkflowStepError({
3885
+ step: name,
3886
+ operation: "waitForEvent",
3887
+ cause
3888
+ })
3478
3889
  })
3479
3890
  });
3480
- const make$1 = (layer, options) => {
3891
+ const make = (layer, options) => {
3481
3892
  class EffectWorkflow extends WorkflowEntrypoint {
3482
3893
  runtime;
3483
3894
  constructor(ctx, env) {
3484
3895
  super(ctx, env);
3485
- let runWaitUntilEffect = () => Promise.reject(/* @__PURE__ */ new Error("WorkerContext runtime is not initialized"));
3486
- 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));
3487
- const runtimeLayer = provideEntrypointServices(layer, services);
3488
- this.runtime = ManagedRuntime.make(runtimeLayer);
3489
- runWaitUntilEffect = (effect) => this.runtime.runPromiseExit(effect);
3896
+ this.runtime = makeEntrypointRuntime(layer, env, Layer.mergeAll(Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx))));
3490
3897
  }
3491
3898
  run(event, step) {
3492
3899
  const workflowServices = Layer.mergeAll(Layer.succeed(WorkflowEvent$1, fromWorkflowEvent(event)), Layer.succeed(WorkflowStep$1, fromWorkflowStep(step, (effect) => this.runtime.runPromise(effect))));
3493
- return this.runtime.runPromise(Effect.scoped(options.run(event.payload).pipe(Effect.provide(workflowServices))));
3900
+ return runEventPromise(this.runtime, options.run(event.payload), workflowServices);
3494
3901
  }
3495
3902
  }
3496
3903
  return assumeEntrypointClass(EffectWorkflow);
@@ -3499,57 +3906,7 @@ const step = (name, effect, config) => Effect.flatMap(WorkflowStep$1, (workflowS
3499
3906
  const sleep = (name, duration) => Effect.flatMap(WorkflowStep$1, (workflowStep) => workflowStep.sleep(name, duration));
3500
3907
  const sleepUntil = (name, timestamp) => Effect.flatMap(WorkflowStep$1, (workflowStep) => workflowStep.sleepUntil(name, timestamp));
3501
3908
  const waitForEvent = (name, options) => Effect.flatMap(WorkflowStep$1, (workflowStep) => workflowStep.waitForEvent(name, options));
3502
- const Tag$1 = Tag$2;
3909
+ const Tag = Tag$1;
3503
3910
  const implement = implement$1;
3504
3911
  //#endregion
3505
- //#region src/Vectorize.ts
3506
- var Vectorize_exports = /* @__PURE__ */ __exportAll({
3507
- Tag: () => Tag,
3508
- VectorizeOperationError: () => VectorizeOperationError,
3509
- isVectorizeBinding: () => isVectorizeBinding,
3510
- layer: () => layer,
3511
- make: () => make,
3512
- makeClient: () => makeClient
3513
- });
3514
- const expectedVectorizeBinding = "Vectorize index binding with describe(), query(), insert(), upsert(), deleteByIds(), and getByIds()";
3515
- /** Error raised when a Vectorize operation fails. */
3516
- var VectorizeOperationError = class extends Data.TaggedError("VectorizeOperationError") {};
3517
- const vectorizeError = (binding, operation, cause) => new VectorizeOperationError({
3518
- binding,
3519
- operation,
3520
- cause
3521
- });
3522
- const tryVectorizePromise = (binding, operation, evaluate) => Effect.tryPromise({
3523
- try: evaluate,
3524
- catch: (cause) => vectorizeError(binding, operation, cause)
3525
- });
3526
- const hasFunction = (value, key) => typeof Reflect.get(value, key) === "function";
3527
- 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");
3528
- const makeClient = (definition) => (index) => {
3529
- const runtime = index;
3530
- const deleteByIds = (ids) => tryVectorizePromise(definition.binding, "deleteByIds", () => runtime.deleteByIds([...ids]));
3531
- return {
3532
- definition,
3533
- describe: tryVectorizePromise(definition.binding, "describe", () => runtime.describe()),
3534
- query: (vector, options) => tryVectorizePromise(definition.binding, "query", () => runtime.query(vector, options)),
3535
- 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()"))),
3536
- insert: (vectors) => tryVectorizePromise(definition.binding, "insert", () => runtime.insert([...vectors])),
3537
- upsert: (vectors) => tryVectorizePromise(definition.binding, "upsert", () => runtime.upsert([...vectors])),
3538
- deleteByIds,
3539
- delete: deleteByIds,
3540
- getByIds: (ids) => tryVectorizePromise(definition.binding, "getByIds", () => runtime.getByIds([...ids])),
3541
- unsafeRaw: Effect.succeed(index)
3542
- };
3543
- };
3544
- const layer = (tag, definition) => layer$20(tag, definition.binding, isVectorizeBinding, makeClient(definition), { expected: expectedVectorizeBinding });
3545
- const make = (id) => Tag()(id);
3546
- const Tag = () => (id) => {
3547
- const tag = Context.Service()(id);
3548
- const makeLayer = (definition) => layer(tag, definition);
3549
- return Object.assign(tag, {
3550
- id,
3551
- layer: makeLayer
3552
- });
3553
- };
3554
- //#endregion
3555
- 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 };
3912
+ 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 };