effect-cf 0.33.0 → 0.35.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 (74) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +31 -1079
  3. package/dist/{Artifacts-DnHQA-Ax.d.mts → Artifacts-B3r3RuTB.d.mts} +1 -48
  4. package/dist/{Artifacts-CSIk1Oml.mjs → Artifacts-CBxWGeZB.mjs} +2 -7
  5. package/dist/{Binding-pfilNJmP.mjs → Binding-C82jRhdr.mjs} +1 -2
  6. package/dist/{Binding-xJJJPmiD.d.mts → Binding-DKcLrQCM.d.mts} +0 -45
  7. package/dist/ComputerArtifacts.d.mts +1 -3
  8. package/dist/ComputerArtifacts.mjs +1 -2
  9. package/dist/ComputerWorkspace.d.mts +11 -12
  10. package/dist/ComputerWorkspace.mjs +31 -10
  11. package/dist/ComputerWorkspaceHost.d.mts +1 -9
  12. package/dist/{ContainerNamespace-CFjiLw8b.d.mts → ContainerNamespace-DbLaeFhN.d.mts} +1 -14
  13. package/dist/{DurableObjectState-CVLLse69.mjs → DurableObjectState-DcqElJ4e.mjs} +82 -89
  14. package/dist/{DurableObjectState-BpRjz6-q.d.mts → DurableObjectState-DpYdNZgT.d.mts} +102 -266
  15. package/dist/{ErrorMessage-BM0K-Nik.mjs → ErrorMessage-Byx2OgNd.mjs} +0 -1
  16. package/dist/{Hyperdrive-z-9fFz15.d.mts → Hyperdrive-HrwFlZ6x.d.mts} +1 -4
  17. package/dist/HyperdrivePg.d.mts +2 -11
  18. package/dist/HyperdrivePg.mjs +0 -8
  19. package/dist/Sandbox.d.mts +2 -32
  20. package/dist/Sandbox.mjs +2 -11
  21. package/dist/Vitest.d.mts +3 -31
  22. package/dist/Vitest.mjs +8 -26
  23. package/dist/{WorkflowBinding-lBR4_-op.d.mts → WorkflowBinding-Cn3AuUyP.d.mts} +2 -5
  24. package/dist/index.d.mts +42 -480
  25. package/dist/index.mjs +267 -380
  26. package/package.json +1 -1
  27. package/src/AiGateway.ts +0 -6
  28. package/src/AnalyticsEngine.ts +8 -10
  29. package/src/Artifacts.ts +0 -47
  30. package/src/Binding.ts +0 -8
  31. package/src/BrowserRendering.ts +0 -4
  32. package/src/Cache.ts +0 -19
  33. package/src/CloudflareOtlp.ts +6 -39
  34. package/src/ComputerArtifacts.ts +0 -2
  35. package/src/ComputerWorkspace.ts +53 -35
  36. package/src/ComputerWorkspaceHost.ts +0 -8
  37. package/src/ContainerNamespace.ts +0 -13
  38. package/src/D1.ts +0 -22
  39. package/src/DurableObject.ts +51 -32
  40. package/src/DurableObjectAlarm.ts +6 -210
  41. package/src/DurableObjectDefinition.ts +8 -20
  42. package/src/DurableObjectNamespace.ts +88 -115
  43. package/src/DurableObjectRpcWebSocket.ts +5 -46
  44. package/src/DurableObjectSqlite.ts +0 -12
  45. package/src/DurableObjectState.ts +18 -38
  46. package/src/DurableObjectStorage.ts +55 -70
  47. package/src/DurableObjectWebSocket.ts +23 -72
  48. package/src/Email.ts +0 -12
  49. package/src/Environment.ts +0 -37
  50. package/src/Hyperdrive.ts +0 -3
  51. package/src/HyperdrivePg.ts +0 -9
  52. package/src/Images.ts +0 -5
  53. package/src/Kv.ts +0 -15
  54. package/src/QueueBinding.ts +0 -2
  55. package/src/R2.ts +0 -5
  56. package/src/RpcDefinition.ts +5 -17
  57. package/src/RpcTracing.ts +133 -0
  58. package/src/Sandbox.ts +0 -30
  59. package/src/ServiceBinding.ts +83 -128
  60. package/src/Vectorize.ts +0 -5
  61. package/src/Vitest.ts +18 -43
  62. package/src/WebTransport.ts +0 -15
  63. package/src/Worker.ts +140 -108
  64. package/src/WorkerDefinition.ts +5 -14
  65. package/src/WorkersAi.ts +21 -18
  66. package/src/Workflow.ts +45 -54
  67. package/src/WorkflowBinding.ts +0 -3
  68. package/src/index.ts +1 -0
  69. package/src/internal/Entrypoint.ts +23 -4
  70. package/src/internal/ErrorMessage.ts +0 -1
  71. package/src/internal/NativeCallback.ts +55 -0
  72. package/src/internal/RpcInvocation.ts +18 -1
  73. package/src/internal/Runtime.ts +12 -7
  74. package/src/internal/WorkerContext.ts +5 -14
package/dist/index.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { a as WorkerEnvironment, i as WorkerConfig, n as violationsMessage, r as Environment_exports, t as causeMessage } from "./ErrorMessage-BM0K-Nik.mjs";
3
- import { n as Service$2, r as layer$19, t as Binding_exports } from "./Binding-pfilNJmP.mjs";
4
- import { n as Artifacts_exports } from "./Artifacts-CSIk1Oml.mjs";
5
- import { a as DurableObjectWebSocket_exports, c as DurableObjectStorage_exports, i as fromExecutionContext, n as DurableObjectState_exports, o as DurableWebSocketAttachmentError, r as fromDurableObjectState, s as fromWebSocket, t as DurableObjectState } from "./DurableObjectState-CVLLse69.mjs";
6
- import { Cause, Clock, Config, ConfigProvider, Context, Data, DateTime, Duration, Effect, Exit, Function as Function$1, Layer, ManagedRuntime, Option, Predicate, Queue, Result, Schema } from "effect";
7
- import { FetchHttpClient, HttpClient, HttpClientRequest, HttpEffect, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
2
+ import { a as WorkerEnvironment, i as WorkerConfig, n as violationsMessage, r as Environment_exports, t as causeMessage } from "./ErrorMessage-Byx2OgNd.mjs";
3
+ import { n as Service$2, r as layer$19, t as Binding_exports } from "./Binding-C82jRhdr.mjs";
4
+ import { n as Artifacts_exports } from "./Artifacts-CBxWGeZB.mjs";
5
+ import { a as DurableObjectWebSocket_exports, c as DurableObjectStorage_exports, i as fromExecutionContext, n as DurableObjectState_exports, o as DurableWebSocketAttachmentError, r as fromDurableObjectState, s as fromWebSocket, t as DurableObjectState } from "./DurableObjectState-DcqElJ4e.mjs";
6
+ import { Cause, Clock, Config, ConfigProvider, Context, Data, DateTime, Duration, Effect, Exit, FiberSet, Function as Function$1, Layer, ManagedRuntime, Option, Predicate, Queue, References, Result, Schema, Tracer } from "effect";
7
+ import { FetchHttpClient, HttpClient, HttpClientRequest, HttpEffect, HttpMiddleware, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
8
8
  import { OtlpExporter, OtlpLogger, OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
9
9
  import { D1Client } from "@effect/sql-d1";
10
10
  import { DurableObject, RpcStub, RpcTarget, WorkerEntrypoint, WorkflowEntrypoint } from "cloudflare:workers";
@@ -24,7 +24,6 @@ var WorkersAi_exports = /* @__PURE__ */ __exportAll({
24
24
  makeClient: () => makeClient$15
25
25
  });
26
26
  const expectedWorkersAiBinding = "Workers AI binding with run(), gateway(), and models()";
27
- /** Error raised when a Workers AI operation fails. */
28
27
  var WorkersAiOperationError = class extends Data.TaggedError("WorkersAiOperationError") {
29
28
  get message() {
30
29
  return `Workers AI ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -51,7 +50,7 @@ const embeddingResponse = (value) => ({
51
50
  data: value.data ?? [],
52
51
  [embeddingDimensionsKey]: value[embeddingDimensionsKey] ?? []
53
52
  });
54
- const decodeEmbeddingResponse = Schema.decodeUnknownOption(Schema.Struct({
53
+ const decodeEmbeddingResponse = Schema.decodeUnknownEffect(Schema.Struct({
55
54
  data: Schema.optional(Schema.Array(Schema.Array(Schema.Number))),
56
55
  [embeddingDimensionsKey]: Schema.optional(Schema.Array(Schema.Number))
57
56
  }));
@@ -63,11 +62,14 @@ const makeClient$15 = (definition) => (ai) => {
63
62
  definition,
64
63
  aiGatewayLogId: tryWorkersAiSync(definition.binding, "aiGatewayLogId", () => ai.aiGatewayLogId),
65
64
  run,
66
- runEmbedding: Effect.fn("WorkersAi.runEmbedding")((model, input, options) => {
67
- return run(model, input, options).pipe(Effect.map((response) => Option.match(decodeEmbeddingResponse(response), {
68
- onNone: () => embeddingResponse({}),
69
- onSome: embeddingResponse
65
+ runEmbedding: Effect.fn("WorkersAi.runEmbedding")(function* (model, input, options) {
66
+ const response = yield* run(model, input, options);
67
+ const decoded = yield* decodeEmbeddingResponse(response).pipe(Effect.mapError((cause) => new WorkersAiOperationError({
68
+ binding: definition.binding,
69
+ operation: "runEmbedding",
70
+ cause
70
71
  })));
72
+ return embeddingResponse(decoded);
71
73
  }),
72
74
  models: Effect.fn("WorkersAi.models")((params) => tryWorkersAiPromise(definition.binding, "models", () => ai.models(params))),
73
75
  gateway: (gatewayId) => tryWorkersAiSync(definition.binding, "gateway", () => ai.gateway(gatewayId)),
@@ -97,7 +99,6 @@ var AiGateway_exports = /* @__PURE__ */ __exportAll({
97
99
  makeHttpClient: () => makeHttpClient
98
100
  });
99
101
  const expectedAiGatewayBinding = "Workers AI binding with gateway()";
100
- /** Error raised when an AI Gateway operation fails. */
101
102
  var AiGatewayOperationError = class extends Data.TaggedError("AiGatewayOperationError") {
102
103
  get message() {
103
104
  return `AI Gateway ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -306,19 +307,16 @@ const AnalyticsEngineDataPointSchema = Schema.Struct({
306
307
  });
307
308
  const decodeQueryResponse = Schema.decodeUnknownEffect(queryResponseSchema);
308
309
  const decodeDataPoint = Schema.decodeUnknownEffect(AnalyticsEngineDataPointSchema);
309
- /** Error raised when an Analytics Engine operation fails. */
310
310
  var AnalyticsEngineOperationError = class extends Data.TaggedError("AnalyticsEngineOperationError") {
311
311
  get message() {
312
312
  return `Analytics Engine ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
313
313
  }
314
314
  };
315
- /** Error raised when an Analytics Engine write input violates Cloudflare limits. */
316
315
  var AnalyticsEngineWriteValidationError = class extends Data.TaggedError("AnalyticsEngineWriteValidationError") {
317
316
  get message() {
318
317
  return `Analytics Engine ${this.operation} for binding "${this.binding}" failed validation: ${violationsMessage(this.violations)}`;
319
318
  }
320
319
  };
321
- /** Error raised when an Analytics Engine SQL API query fails. */
322
320
  var AnalyticsEngineQueryError = class extends Data.TaggedError("AnalyticsEngineQueryError") {};
323
321
  const analyticsEngineError = (binding, operation, cause) => new AnalyticsEngineOperationError({
324
322
  binding,
@@ -418,7 +416,11 @@ const queryRequest = (definition, sql, options) => {
418
416
  };
419
417
  const responseText = (definition, response, operation) => response.text.pipe(Effect.catch((cause) => Effect.fail(analyticsEngineQueryError(definition, operation, "Failed to read Analytics Engine SQL API response body", { cause }))));
420
418
  const executeQueryRequest = (definition, httpClient, sql, options) => Effect.gen(function* () {
421
- const response = yield* httpClient.execute(queryRequest(definition, sql, options)).pipe(Effect.mapError((cause) => analyticsEngineQueryError(definition, "query", "Analytics Engine SQL API request failed", { cause })));
419
+ const request = yield* Effect.try({
420
+ try: () => queryRequest(definition, sql, options),
421
+ catch: (cause) => analyticsEngineQueryError(definition, "query", "Invalid Analytics Engine SQL API URL", { cause })
422
+ });
423
+ const response = yield* httpClient.execute(request).pipe(Effect.mapError((cause) => analyticsEngineQueryError(definition, "query", "Analytics Engine SQL API request failed", { cause })));
422
424
  if (response.status < 200 || response.status >= 300) {
423
425
  const body = yield* responseText(definition, response, "queryErrorBody");
424
426
  return yield* Effect.fail(analyticsEngineQueryError(definition, "query", `Analytics Engine SQL API returned HTTP ${response.status}`, {
@@ -523,7 +525,6 @@ var BrowserRendering_exports = /* @__PURE__ */ __exportAll({
523
525
  makeClient: () => makeClient$12
524
526
  });
525
527
  const expectedBrowserRenderingBinding = "Browser Rendering binding resource";
526
- /** Error raised when a Browser Rendering operation fails. */
527
528
  var BrowserRenderingOperationError = class extends Data.TaggedError("BrowserRenderingOperationError") {
528
529
  get message() {
529
530
  return `Browser Rendering ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -596,13 +597,11 @@ var Cache_exports = /* @__PURE__ */ __exportAll({
596
597
  makeCacheClient: () => makeCacheClient,
597
598
  makeClient: () => makeClient$11
598
599
  });
599
- /** Error raised when a Cloudflare Cache API operation fails. */
600
600
  var CacheOperationError = class extends Data.TaggedError("CacheOperationError") {
601
601
  get message() {
602
602
  return `Cache ${this.operation} failed for cache "${this.cache}": ${causeMessage(this.cause)}`;
603
603
  }
604
604
  };
605
- /** Service for Cloudflare's global Cache API. */
606
605
  var CacheStorage = class extends Context.Service()("effect-cf/CacheStorage") {};
607
606
  const cacheError = (cache, operation, cause) => new CacheOperationError({
608
607
  cache,
@@ -617,7 +616,6 @@ const spanOptions$2 = (cache, operation) => ({ attributes: {
617
616
  cache,
618
617
  operation
619
618
  } });
620
- /** Wraps a native Cloudflare `Cache` instance. */
621
619
  const makeCacheClient = (cache, name = "default") => ({
622
620
  name,
623
621
  match: Effect.fn("Cache.match", spanOptions$2(name, "match"))((request, options) => tryCachePromise(name, "match", () => cache.match(request, options)).pipe(Effect.map(Option.fromUndefinedOr))),
@@ -625,43 +623,20 @@ const makeCacheClient = (cache, name = "default") => ({
625
623
  delete: Effect.fn("Cache.delete", spanOptions$2(name, "delete"))((request, options) => tryCachePromise(name, "delete", () => cache.delete(request, options))),
626
624
  rawUnsafe: Effect.succeed(cache)
627
625
  });
628
- /** Wraps a native Cloudflare `CacheStorage` instance. */
629
626
  const makeClient$11 = (storage) => ({
630
627
  default: makeCacheClient(storage.default),
631
628
  open: (name) => tryCachePromise(name, "open", () => storage.open(name)).pipe(Effect.map((cache) => makeCacheClient(cache, name)), Effect.withSpan("Cache.open", spanOptions$2(name, "open"))),
632
629
  rawUnsafe: Effect.succeed(storage)
633
630
  });
634
- /** Provides Cache API services from an explicit native `CacheStorage` instance. */
635
631
  const layerFrom = (storage) => Layer.succeed(CacheStorage, makeClient$11(storage));
636
- /** Provides Cache API services from Cloudflare's global `caches` object. */
637
632
  const layer$14 = Layer.sync(CacheStorage, () => makeClient$11(caches));
638
633
  //#endregion
639
634
  //#region src/CloudflareOtlp.ts
640
635
  /**
641
- * OTLP telemetry layers for Cloudflare Workers and Durable Objects.
642
- *
643
- * Every layer exposes {@link OtlpExporter.Flusher}, which drains buffered
644
- * telemetry on demand. Cloudflare isolates can freeze before the periodic
645
- * export interval fires. Effect-backed Worker fetch handlers, Worker or
646
- * Durable Object native RPC handlers, and Durable Object alarm handlers
647
- * schedule this flusher automatically. These automatic flushes are capped at
648
- * two seconds and silently discard timeouts and failures so telemetry cannot
649
- * extend or fail the user event, or recursively log through an unhealthy
650
- * exporter.
651
- *
652
- * Other entrypoint lifecycles, including queue handlers, do not flush
653
- * automatically. Applications can flush explicitly or hand the flush to their
654
- * `waitUntil` mechanism, and own the timeout and failure policy at that call
655
- * site:
656
- *
657
- * ```ts
658
- * const flusher = yield* OtlpExporter.Flusher;
659
- *
660
- * yield* flusher.flush.pipe(
661
- * Effect.timeoutOption("2 seconds"),
662
- * Effect.ignoreCause,
663
- * );
664
- * ```
636
+ * Worker fetch/queue/RPC and Durable Object alarm/RPC handlers schedule a
637
+ * best-effort flusher. It settles within two seconds; other lifecycles must
638
+ * flush explicitly. Scheduled flush failures cannot fail user events. Exporter
639
+ * layer finalizers run separately and follow their configured shutdown timeout.
665
640
  */
666
641
  var CloudflareOtlp_exports = /* @__PURE__ */ __exportAll({
667
642
  layer: () => layer$13,
@@ -692,7 +667,6 @@ const makeResource = (options, runtimeAttributes) => ({
692
667
  }
693
668
  });
694
669
  const serializationLayer = (serialization) => serialization === "json" ? OtlpSerialization.layerJson : OtlpSerialization.layerProtobuf;
695
- /** Merges a non-empty signal layer list; callers handle the empty case. */
696
670
  const mergeSignalLayers = (layers) => {
697
671
  let merged = layers[0];
698
672
  for (let index = 1; index < layers.length; index++) merged = Layer.mergeAll(merged, layers[index]);
@@ -747,6 +721,8 @@ const layerProtobuf = (options = {}) => layer$13({
747
721
  *
748
722
  * Provide this layer at runtime scope for long-lived metrics aggregation, or at
749
723
  * handler scope when traces/logs should flush as the Cloudflare event finishes.
724
+ * A handler-scoped exporter can delay scope closure while its own finalizer
725
+ * flushes; the two-second background flush limit does not bound layer shutdown.
750
726
  */
751
727
  const layerWorker = (options = {}) => makeLayer(options, {
752
728
  "cloudflare.resource_type": "worker",
@@ -791,7 +767,6 @@ const ContainerState = Schema.Union([Schema.Struct({
791
767
  status: Schema.Literal("stopped_with_code"),
792
768
  exitCode: Schema.optionalKey(Schema.Int)
793
769
  })]);
794
- /** Failure raised when invoking a named Container operation. */
795
770
  var ContainerOperationError = class extends Data.TaggedError("ContainerOperationError") {
796
771
  get message() {
797
772
  return `Container ${this.operation} failed for binding "${this.binding}" instance "${this.instance}": ${causeMessage(this.cause)}`;
@@ -889,7 +864,6 @@ const makeClient$10 = (definition) => (namespace) => {
889
864
  };
890
865
  const layer$12 = (tag, definition) => layer$19(tag, definition.binding, (value) => isContainerNamespaceResource(value), makeClient$10(definition), { expected: expectedContainerNamespace });
891
866
  const make$14 = (id) => Tag$12()(id);
892
- /** Creates a typed Effect service for a Cloudflare Container namespace. */
893
867
  const Tag$12 = () => (id) => {
894
868
  const tag = Context.Service()(`effect-cf/Container/${id}`);
895
869
  const makeLayer = (definition) => layer$12(tag, definition);
@@ -931,25 +905,7 @@ var D1_exports = /* @__PURE__ */ __exportAll({
931
905
  const TypeId$2 = "~effect-cf/D1";
932
906
  const expectedD1Database = "D1 database binding with prepare(), batch(), and exec()";
933
907
  const isD1Database = (value) => Predicate.hasProperty(value, "prepare") && Predicate.isFunction(value.prepare) && Predicate.hasProperty(value, "batch") && Predicate.isFunction(value.batch) && Predicate.hasProperty(value, "exec") && Predicate.isFunction(value.exec);
934
- /**
935
- * Creates a typed D1 service tag plus Effect helpers.
936
- */
937
908
  const make$13 = (id, definition) => Service$1()(id, definition);
938
- /**
939
- * Builds a D1 service around a Cloudflare D1 database binding.
940
- *
941
- * The returned service exposes the raw `D1Database` binding and `sqlLayer(...)`
942
- * for providing `effect/unstable/sql` via `@effect/sql-d1`.
943
- *
944
- * @example
945
- * ```ts
946
- * class TodoDatabase extends D1.Service<TodoDatabase>()("TodoDatabase", {
947
- * binding: "TODO_DB",
948
- * }) {}
949
- *
950
- * const SqlLive = TodoDatabase.sqlLayer();
951
- * ```
952
- */
953
909
  const Service$1 = () => (id, definition) => {
954
910
  const tag = Service$2()(id, definition.binding, isD1Database, void 0, { expected: expectedD1Database });
955
911
  const sqlLayer = (options) => Layer.unwrap(Effect.gen(function* () {
@@ -1213,7 +1169,6 @@ const encodeWireError = (error) => {
1213
1169
  return error;
1214
1170
  }
1215
1171
  };
1216
- /** Restores package RPC errors from the {@link encodeWireError} envelope. */
1217
1172
  const decodeWireError = (cause) => {
1218
1173
  if (!(cause instanceof Error)) return cause;
1219
1174
  try {
@@ -1309,19 +1264,123 @@ const make$11 = (id, methods) => {
1309
1264
  };
1310
1265
  };
1311
1266
  //#endregion
1267
+ //#region src/RpcTracing.ts
1268
+ var RpcTracing_exports = /* @__PURE__ */ __exportAll({
1269
+ RpcTraceContext: () => RpcTraceContext,
1270
+ withRpcClientSpan: () => withRpcClientSpan,
1271
+ withRpcServerSpan: () => withRpcServerSpan,
1272
+ withRpcTraceContext: () => withRpcTraceContext
1273
+ });
1274
+ /**
1275
+ * Live native RPC metadata. Opted-in receivers reserve a valid trailing value
1276
+ * with this tag for transport context; do not use it as a final domain argument.
1277
+ * Never store this in durable messages or envelopes.
1278
+ */
1279
+ const RpcTraceContext = Schema.Struct({
1280
+ _tag: Schema.Literal("effect-cf/RpcTraceContext/v1"),
1281
+ traceId: Schema.String.check(Schema.isPattern(/^(?!0{32}$)[0-9a-f]{32}$/)),
1282
+ spanId: Schema.String.check(Schema.isPattern(/^(?!0{16}$)[0-9a-f]{16}$/)),
1283
+ sampled: Schema.Boolean
1284
+ });
1285
+ const isRpcTraceContext$1 = Schema.is(RpcTraceContext);
1286
+ /**
1287
+ * Appends the current live parent only for a receiver that has opted in.
1288
+ * Call this inside the CLIENT span, immediately before the native invocation.
1289
+ * With no valid propagating parent, the original argument array is returned.
1290
+ */
1291
+ const withRpcTraceContext = Effect.fnUntraced(function* (args) {
1292
+ if (yield* Tracer.DisablePropagation) return args;
1293
+ const parent = yield* Effect.serviceOption(Tracer.ParentSpan);
1294
+ if (Option.isNone(parent) || Context.get(parent.value.annotations, Tracer.DisablePropagation)) return args;
1295
+ const context = {
1296
+ _tag: "effect-cf/RpcTraceContext/v1",
1297
+ traceId: parent.value.traceId,
1298
+ spanId: parent.value.spanId,
1299
+ sampled: parent.value.sampled
1300
+ };
1301
+ return isRpcTraceContext$1(context) ? [...args, context] : args;
1302
+ });
1303
+ const attributes = (service, method) => ({
1304
+ "sentry.op": "rpc",
1305
+ "rpc.system.name": "cloudflare",
1306
+ "rpc.method": `${service}/${method}`,
1307
+ "server.address": service
1308
+ });
1309
+ const withRpcSpan = (effect, service, method, options) => Effect.useSpan(`${service}/${method}`, {
1310
+ ...options,
1311
+ attributes: attributes(service, method)
1312
+ }, (span) => effect.pipe(Effect.withParentSpan(span), Effect.onExit((exit) => {
1313
+ if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause) || span.status._tag === "Ended") return Effect.void;
1314
+ return Effect.gen(function* () {
1315
+ const endTime = (yield* References.TracerTimingEnabled) ? yield* Clock.currentTimeNanos : 0n;
1316
+ span.attribute("error.type", "_OTHER");
1317
+ span.end(endTime, Exit.fail("RPC failed"));
1318
+ });
1319
+ })));
1320
+ /** Wrap the whole call, including native result resolution and success decoding. */
1321
+ const withRpcClientSpan = (effect, binding, method) => withRpcSpan(effect, binding, method, { kind: "client" });
1322
+ /**
1323
+ * Optional application instrumentation for the entire receiver effect.
1324
+ * Use in a RunSymbol override to include argument decode, handler and encode.
1325
+ * Records stable service/method attributes and failure status, not argument or
1326
+ * error payloads. The original typed failure still propagates to the caller.
1327
+ */
1328
+ const withRpcServerSpan = (effect, invocation) => withRpcSpan(effect, invocation.service, invocation.method, {
1329
+ kind: "server",
1330
+ parent: invocation.parent === void 0 ? void 0 : Tracer.externalSpan(invocation.parent)
1331
+ });
1332
+ //#endregion
1333
+ //#region src/internal/RpcInvocation.ts
1334
+ /** Scoped to the incoming event effect, never the instance runtime or storage. */
1335
+ var CurrentInvocation = class extends Context.Service()("effect-cf/internal/RpcInvocation") {};
1336
+ const recordDecodedArgs = (args) => Effect.map(Effect.serviceOption(CurrentInvocation), (invocation) => {
1337
+ if (Option.isSome(invocation)) invocation.value.decodedArgs = args;
1338
+ });
1339
+ const invokeWithReceiver = (value, receiver, args) => {
1340
+ return Function.prototype.apply.call(value, receiver, args);
1341
+ };
1342
+ const lookupRpcMethod = (target, method, makeError) => Effect.try({
1343
+ try: () => {
1344
+ if (!Predicate.isObjectKeyword(target)) throw new TypeError(`RPC target is not object-like`);
1345
+ const receiver = target;
1346
+ const value = receiver[method];
1347
+ if (!Predicate.isFunction(value)) throw new TypeError(`RPC method "${String(method)}" is not callable`);
1348
+ const callable = value;
1349
+ return (...args) => invokeWithReceiver(callable, receiver, args);
1350
+ },
1351
+ catch: makeError
1352
+ });
1353
+ const invokeRpcMethod = Effect.fnUntraced(function* (target, method, args, makeError) {
1354
+ const fn = yield* lookupRpcMethod(target, method, makeError);
1355
+ return yield* Effect.try({
1356
+ try: () => fn(...args),
1357
+ catch: makeError
1358
+ });
1359
+ });
1360
+ //#endregion
1312
1361
  //#region src/internal/Entrypoint.ts
1313
- const invokeEntrypointRpcMethod = (self, method, args, run, onExit) => {
1314
- const handler = Effect.suspend(() => method(...args)).pipe(Effect.mapError(encodeWireError));
1315
- return run(self, onExit === void 0 ? handler : handler.pipe(Effect.onExit(() => onExit(self))));
1362
+ const isRpcTraceContext = Schema.is(RpcTraceContext);
1363
+ const invokeEntrypointRpcMethod = (self, method, args, run, onExit, service, key, rpcTracing) => {
1364
+ const last = args.at(-1);
1365
+ const parent = rpcTracing !== void 0 && isRpcTraceContext(last) ? last : void 0;
1366
+ const handlerArgs = parent === void 0 ? args : args.slice(0, -1);
1367
+ const invocation = {
1368
+ service: rpcTracing?.service ?? service,
1369
+ method: key,
1370
+ args: handlerArgs,
1371
+ parent
1372
+ };
1373
+ const handler = Effect.suspend(() => method(...handlerArgs)).pipe(Effect.provideService(CurrentInvocation, invocation), Effect.mapError(encodeWireError));
1374
+ return run(self, onExit === void 0 ? handler : handler.pipe(Effect.onExit(() => onExit(self))), invocation);
1316
1375
  };
1317
1376
  const provideEntrypointServices = (layer, services) => layer.pipe(Layer.provideMerge(services));
1318
- const defineEntrypointRpcMethods = (target, prototype, rpc, reservedMethodNames, run, onExit) => {
1377
+ const defineEntrypointRpcMethods = (target, prototype, rpc, reservedMethodNames, run, onExit, rpcTracing) => {
1319
1378
  const methods = rpc ?? {};
1320
1379
  assertNoReservedMethods(target, methods, reservedMethodNames);
1321
1380
  for (const [key, method] of Object.entries(methods)) Object.defineProperty(prototype, key, {
1322
1381
  enumerable: true,
1323
1382
  value(...args) {
1324
- return invokeEntrypointRpcMethod(this, method, args, run, onExit);
1383
+ return invokeEntrypointRpcMethod(this, method, args, run, onExit, target, key, rpcTracing);
1325
1384
  }
1326
1385
  });
1327
1386
  };
@@ -1344,9 +1403,13 @@ const makeEntrypointRuntime = (layer, env, services) => {
1344
1403
  return ManagedRuntime.make(provideEntrypointServices(layer, entrypointServices));
1345
1404
  };
1346
1405
  function runEventPromise(...args) {
1347
- const [runtime, effect, eventLayer] = args;
1348
- if (eventLayer === void 0) return runtime.runPromise(Effect.scoped(effect));
1349
- return runtime.runPromise(Effect.scoped(effect.pipe(Effect.provide(eventLayer, { local: true }))));
1406
+ const [runtime, effect, eventLayer, parent] = args;
1407
+ if (eventLayer === void 0) {
1408
+ const event = Effect.scoped(effect);
1409
+ return runtime.runPromise(parent === void 0 ? event : Effect.withParentSpan(event, parent));
1410
+ }
1411
+ const event = Effect.scoped(effect.pipe(Effect.provide(eventLayer, { local: true })));
1412
+ return runtime.runPromise(parent === void 0 ? event : Effect.withParentSpan(event, parent));
1350
1413
  }
1351
1414
  //#endregion
1352
1415
  //#region src/internal/Telemetry.ts
@@ -1386,29 +1449,6 @@ const resolve = (value) => Predicate.isPromiseLike(value) ? Effect.tryPromise({
1386
1449
  });
1387
1450
  const scoped = (value) => Effect.acquireRelease(resolve(value), (resolved) => dispose(resolved));
1388
1451
  //#endregion
1389
- //#region src/internal/RpcInvocation.ts
1390
- const invokeWithReceiver = (value, receiver, args) => {
1391
- return Function.prototype.apply.call(value, receiver, args);
1392
- };
1393
- const lookupRpcMethod = (target, method, makeError) => Effect.try({
1394
- try: () => {
1395
- if (!Predicate.isObjectKeyword(target)) throw new TypeError(`RPC target is not object-like`);
1396
- const receiver = target;
1397
- const value = receiver[method];
1398
- if (!Predicate.isFunction(value)) throw new TypeError(`RPC method "${String(method)}" is not callable`);
1399
- const callable = value;
1400
- return (...args) => invokeWithReceiver(callable, receiver, args);
1401
- },
1402
- catch: makeError
1403
- });
1404
- const invokeRpcMethod = Effect.fnUntraced(function* (target, method, args, makeError) {
1405
- const fn = yield* lookupRpcMethod(target, method, makeError);
1406
- return yield* Effect.try({
1407
- try: () => fn(...args),
1408
- catch: makeError
1409
- });
1410
- });
1411
- //#endregion
1412
1452
  //#region src/ServiceBinding.ts
1413
1453
  var ServiceBinding_exports = /* @__PURE__ */ __exportAll({
1414
1454
  Service: () => Service,
@@ -1444,21 +1484,28 @@ const makeClient$8 = (definition) => {
1444
1484
  return (service) => {
1445
1485
  const fetch = Effect.fn("ServiceBinding.fetch")(function* (input, init) {
1446
1486
  return yield* Effect.tryPromise({
1447
- try: () => service.fetch(input, init),
1487
+ try: (signal) => {
1488
+ const callerSignal = init?.signal !== void 0 ? init.signal : input instanceof Request ? input.signal : void 0;
1489
+ return service.fetch(input, {
1490
+ ...init,
1491
+ signal: callerSignal === null || callerSignal === void 0 ? signal : AbortSignal.any([callerSignal, signal])
1492
+ });
1493
+ },
1448
1494
  catch: (cause) => new ServiceBindingFetchError({
1449
1495
  binding: definition.binding,
1450
1496
  cause
1451
1497
  })
1452
1498
  });
1453
1499
  });
1454
- const rpc = Effect.fn("ServiceBinding.rpc")(function* (method, ...args) {
1500
+ const rpc = Effect.fnUntraced(function* (method, ...args) {
1455
1501
  const methodName = String(method);
1456
1502
  const encodedArgs = definition.definition === void 0 ? args : yield* encodeArgs(definition.definition, methodName, args).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1457
1503
  binding: definition.binding,
1458
1504
  method: methodName,
1459
1505
  cause
1460
1506
  })));
1461
- return yield* invokeRpcMethod(service, method, encodedArgs, (cause) => new ServiceBindingRpcError({
1507
+ const nativeArgs = definition.rpcTracing ? yield* withRpcTraceContext(encodedArgs) : encodedArgs;
1508
+ return yield* invokeRpcMethod(service, method, nativeArgs, (cause) => new ServiceBindingRpcError({
1462
1509
  binding: definition.binding,
1463
1510
  method: methodName,
1464
1511
  cause
@@ -1472,7 +1519,7 @@ const makeClient$8 = (definition) => {
1472
1519
  cause
1473
1520
  })));
1474
1521
  });
1475
- const call = Effect.fn("ServiceBinding.call")(function* (method, ...args) {
1522
+ const call = Effect.fnUntraced(function* (method, ...args) {
1476
1523
  const methodName = String(method);
1477
1524
  const value = yield* resolve(yield* rpc(method, ...args)).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1478
1525
  binding: definition.binding,
@@ -1480,13 +1527,17 @@ const makeClient$8 = (definition) => {
1480
1527
  cause
1481
1528
  })));
1482
1529
  return yield* decodeSuccess$2(methodName, value);
1483
- });
1484
- const scopedCall = Effect.fn("ServiceBinding.scopedCall")(function* (method, ...args) {
1530
+ }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[0])));
1531
+ const scopedCall = Effect.fnUntraced(function* (method, ...args) {
1485
1532
  const methodName = String(method);
1486
1533
  const result = yield* rpc(method, ...args);
1487
- const value = yield* scoped(result);
1534
+ const value = yield* scoped(result).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1535
+ binding: definition.binding,
1536
+ method: methodName,
1537
+ cause
1538
+ })));
1488
1539
  return yield* decodeSuccess$2(methodName, value);
1489
- });
1540
+ }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[0])));
1490
1541
  const directMethods = makeDirectMethods$1(definition.definition, call);
1491
1542
  return Object.assign(directMethods, {
1492
1543
  fetch,
@@ -1497,35 +1548,6 @@ const makeClient$8 = (definition) => {
1497
1548
  };
1498
1549
  };
1499
1550
  const layer$10 = (tag, definition) => layer$19(tag, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition), { expected: expectedServiceBinding });
1500
- /**
1501
- * Creates a typed Effect service for a Worker service binding.
1502
- *
1503
- * Returned value includes:
1504
- * - a Context tag for dependency injection
1505
- * - `fetch(...)` for raw HTTP forwarding
1506
- * - `rpc(...)` for raw Cloudflare RPC results
1507
- * - `call(...)` for resolved and decoded RPC results
1508
- * - `scopedCall(...)` for scoped and decoded disposable RPC results
1509
- * - direct RPC methods when `definition` is provided
1510
- *
1511
- * @example
1512
- * ```ts
1513
- * const Counter = WorkerDefinition.make("Counter", {
1514
- * increment: WorkerDefinition.method({
1515
- * args: [Schema.Number],
1516
- * success: Schema.Number,
1517
- * }),
1518
- * });
1519
- *
1520
- * const CounterLive = Counter.layer({ binding: "COUNTER" });
1521
- *
1522
- * const program = Effect.gen(function* () {
1523
- * const counter = yield* Counter;
1524
- * const next = yield* counter.increment(1);
1525
- * return next;
1526
- * });
1527
- * ```
1528
- */
1529
1551
  const Service = () => (id, definition) => {
1530
1552
  const tag = Service$2()(id, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition));
1531
1553
  const fetch = Effect.fnUntraced(function* (input, init) {
@@ -1590,19 +1612,6 @@ const assumeTagClass = (value) => {
1590
1612
  * Defines a single RPC method schema in a worker definition.
1591
1613
  */
1592
1614
  const method$1 = method$2;
1593
- /**
1594
- * Creates a typed worker RPC definition plus helpers for implementation and bindings.
1595
- *
1596
- * @example
1597
- * ```ts
1598
- * const CounterWorker = WorkerDefinition.make("CounterWorker", {
1599
- * increment: WorkerDefinition.method({
1600
- * args: [Schema.Number],
1601
- * success: Schema.Number,
1602
- * }),
1603
- * });
1604
- * ```
1605
- */
1606
1615
  const makeDefinition$3 = (id, methods) => {
1607
1616
  assertNoReservedMethods("Worker", methods, reservedMethodNames$3);
1608
1617
  const definition = make$11(id, methods);
@@ -1655,6 +1664,7 @@ const wrapHandlers$1 = (definition, handlers) => {
1655
1664
  const handler = handlers[key];
1656
1665
  wrapped[key] = (...args) => Effect.gen(function* () {
1657
1666
  const decodedArgs = yield* decodeArgs(definition, key, args);
1667
+ yield* recordDecodedArgs(decodedArgs);
1658
1668
  const value = yield* handler(...decodedArgs);
1659
1669
  return yield* encodeSuccess(definition, key, value);
1660
1670
  });
@@ -1670,6 +1680,7 @@ const implement$3 = (_definition, handlers) => handlers;
1670
1680
  var Worker_exports = /* @__PURE__ */ __exportAll({
1671
1681
  ExecutionContext: () => ExecutionContext,
1672
1682
  NativeRequest: () => NativeRequest,
1683
+ RunSymbol: () => RunSymbol$1,
1673
1684
  Tag: () => Tag$9,
1674
1685
  WorkerContext: () => WorkerContext,
1675
1686
  implement: () => implement$3,
@@ -1678,64 +1689,47 @@ var Worker_exports = /* @__PURE__ */ __exportAll({
1678
1689
  makeFetchHandler: () => makeFetchHandler,
1679
1690
  method: () => method$1
1680
1691
  });
1681
- /**
1682
- * Access to Cloudflare's native `ExecutionContext`.
1683
- */
1684
1692
  var ExecutionContext = class extends Context.Service()("effect-cf/ExecutionContext") {};
1685
- /**
1686
- * Service used inside handlers to schedule background work via `waitUntil`.
1687
- *
1688
- * @example
1689
- * ```ts
1690
- * const handler = Effect.gen(function* () {
1691
- * const ctx = yield* Worker.WorkerContext;
1692
- * yield* ctx.waitUntil(Effect.log("flush analytics"));
1693
- * return new Response("ok");
1694
- * });
1695
- * ```
1696
- */
1697
1693
  var WorkerContext = class extends Context.Service()("effect-cf/WorkerContext") {};
1698
- /**
1699
- * Access to the incoming `Request` currently handled by a worker or Durable Object fetch.
1700
- */
1701
1694
  var NativeRequest = class extends Context.Service()("effect-cf/NativeRequest") {};
1702
- /**
1703
- * Returns `true` when the request is a websocket upgrade request.
1704
- */
1705
1695
  const isWebSocketUpgrade = (request) => request.headers.get("Upgrade")?.toLowerCase() === "websocket";
1706
1696
  const reservedMethodNames$2 = /* @__PURE__ */ new Set([
1707
- "constructor",
1708
- "dup",
1709
- "fetch",
1710
- "connect",
1697
+ ...reservedMethodNames$4,
1711
1698
  "queue",
1712
1699
  "scheduled",
1713
1700
  "tail",
1714
1701
  "tailStream",
1715
1702
  "test",
1716
- "trace",
1717
- "alarm",
1718
- "webSocketMessage",
1719
- "webSocketClose",
1720
- "webSocketError"
1703
+ "trace"
1721
1704
  ]);
1705
+ /** Override to instrument the whole event, then call super[RunSymbol]. */
1722
1706
  const RunSymbol$1 = Symbol.for("effect-cf/Worker/run");
1723
1707
  const FetchSymbol = Symbol.for("effect-cf/Worker/fetch");
1724
- const renderFetchSuccess = (effect) => Effect.suspend(() => {
1708
+ const renderFetchSuccess = (effect, eventLayer) => Effect.suspend(() => {
1725
1709
  let nativeResponse;
1726
1710
  let webResponse;
1727
- const handled = HttpEffect.toHandled(Effect.flatMap(effect, (response) => {
1711
+ const httpApp = Effect.flatMap(effect, (response) => {
1728
1712
  if (response instanceof Response) {
1729
1713
  nativeResponse = response;
1730
1714
  return Effect.succeed(HttpServerResponse.empty());
1731
1715
  }
1732
1716
  return Effect.succeed(response);
1733
- }), (request, response) => nativeResponse !== void 0 ? Effect.void : Effect.map(Effect.context(), (context) => {
1717
+ });
1718
+ const handleResponse = (request, response) => nativeResponse !== void 0 ? Effect.void : Effect.map(Effect.context(), (context) => {
1734
1719
  webResponse = HttpServerResponse.toWeb(HttpEffect.scopeTransferToStream(response), {
1735
1720
  withoutBody: request.method === "HEAD",
1736
1721
  context
1737
1722
  });
1723
+ });
1724
+ const telemetryMiddleware = HttpMiddleware.make((self) => Effect.gen(function* () {
1725
+ yield* Effect.addFinalizer(() => scheduleTelemetryFlush$1);
1726
+ return yield* self;
1738
1727
  }));
1728
+ const handled = eventLayer === void 0 ? HttpEffect.toHandled(httpApp, handleResponse, telemetryMiddleware) : Effect.flatMap(References.TracerEnabled, (tracerEnabled) => HttpEffect.toHandled(httpApp, handleResponse, HttpMiddleware.make((self) => Effect.provideService(Effect.gen(function* () {
1729
+ const context = yield* Layer.build(Layer.fresh(eventLayer));
1730
+ yield* Effect.addFinalizer(() => Effect.provideContext(scheduleTelemetryFlush$1, context));
1731
+ return yield* HttpMiddleware.tracer(self).pipe(Effect.onExit(() => Effect.yieldNow), Effect.provideContext(context));
1732
+ }), References.TracerEnabled, tracerEnabled))).pipe(Effect.withTracerEnabled(false)));
1739
1733
  const captured = () => nativeResponse ?? webResponse ?? new Response(null, { status: 500 });
1740
1734
  return Effect.matchCause(handled, {
1741
1735
  onFailure: captured,
@@ -1744,13 +1738,13 @@ const renderFetchSuccess = (effect) => Effect.suspend(() => {
1744
1738
  });
1745
1739
  const isWorkerOptions = (options) => !Effect.isEffect(options);
1746
1740
  /**
1747
- * Drains buffered OTLP telemetry once the fetch handler has produced its
1748
- * response.
1741
+ * Drains buffered OTLP telemetry when the fetch Effect scope closes. Effect
1742
+ * response streams transfer that scope to the body and schedule the flush when
1743
+ * the body finishes or is canceled.
1749
1744
  *
1750
- * The flush is handed to `ctx.waitUntil` so it never delays the response
1751
- * (including streaming bodies still being consumed). It is a no-op when the
1752
- * context does not contain an `OtlpExporter.Flusher`. The handed-off effect is
1753
- * best-effort and silently settles within two seconds.
1745
+ * The flush is handed to `ctx.waitUntil` instead of being awaited by the
1746
+ * handler. It is a no-op when the context does not contain an
1747
+ * `OtlpExporter.Flusher`, and silently settles within two seconds.
1754
1748
  */
1755
1749
  const scheduleTelemetryFlush$1 = scheduleTelemetryFlush$2((flush) => Effect.flatMap(WorkerContext, (workerContext) => workerContext.waitUntil(flush)));
1756
1750
  function make$9(layer, optionsOrFetch) {
@@ -1761,10 +1755,12 @@ function make$9(layer, optionsOrFetch) {
1761
1755
  super(ctx, env);
1762
1756
  this.runtime = makeEntrypointRuntime(layer, env, Layer.mergeAll(Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx))));
1763
1757
  }
1764
- [RunSymbol$1](effect) {
1765
- const eventLayer = options.eventLayer;
1766
- if (eventLayer === void 0) return runEventPromise(this.runtime, effect);
1767
- return runEventPromise(this.runtime, effect, eventLayer);
1758
+ [RunSymbol$1](effect, runOptions = {}) {
1759
+ const eventLayer = runOptions.event === "fetch" ? void 0 : options.eventLayer;
1760
+ const parent = runOptions.rpc?.parent;
1761
+ const parentSpan = parent === void 0 ? void 0 : Tracer.externalSpan(parent);
1762
+ if (eventLayer === void 0) return runEventPromise(this.runtime, effect, void 0, parentSpan);
1763
+ return runEventPromise(this.runtime, effect, eventLayer, parentSpan);
1768
1764
  }
1769
1765
  fetch(request) {
1770
1766
  return this[FetchSymbol](request);
@@ -1774,16 +1770,19 @@ function make$9(layer, optionsOrFetch) {
1774
1770
  if (fetchHandler === void 0) return Promise.resolve(new Response("Not Found", { status: 404 }));
1775
1771
  const ctx = requestContext ?? this.ctx;
1776
1772
  const requestServices = Layer.mergeAll(Layer.succeed(NativeRequest, request), Layer.succeed(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(request)), Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx)));
1777
- return this[RunSymbol$1](renderFetchSuccess(fetchHandler).pipe(Effect.tap(() => scheduleTelemetryFlush$1), Effect.provide(requestServices)));
1773
+ return this[RunSymbol$1](renderFetchSuccess(fetchHandler, options.eventLayer).pipe(Effect.provide(requestServices)), { event: "fetch" });
1778
1774
  }
1779
1775
  queue(batch) {
1780
1776
  const queueHandler = options.queue;
1781
1777
  if (queueHandler === void 0) return Promise.resolve();
1782
1778
  const messages = batch.messages.map((message) => fromMessage(message, message.body));
1783
- return this[RunSymbol$1](queueHandler(fromMessageBatch(batch, messages)));
1779
+ return this[RunSymbol$1](queueHandler(fromMessageBatch(batch, messages)).pipe(Effect.onExit(() => scheduleTelemetryFlush$1)), { event: "queue" });
1784
1780
  }
1785
1781
  }
1786
- defineEntrypointRpcMethods("Worker", EffectWorker.prototype, options.rpc, reservedMethodNames$2, (self, effect) => self[RunSymbol$1](effect), () => scheduleTelemetryFlush$1);
1782
+ defineEntrypointRpcMethods("Worker", EffectWorker.prototype, options.rpc, reservedMethodNames$2, (self, effect, rpc) => self[RunSymbol$1](effect, {
1783
+ event: "rpc",
1784
+ rpc
1785
+ }), () => scheduleTelemetryFlush$1, options.rpcTracing);
1787
1786
  return assumeEntrypointClass(EffectWorker);
1788
1787
  }
1789
1788
  function makeFetchHandler(layer, options) {
@@ -1836,26 +1835,33 @@ const makeClient$7 = (definition) => {
1836
1835
  const getByName = (name, options) => Effect.sync(() => namespace.getByName(name, options));
1837
1836
  const jurisdiction = (value) => Effect.sync(() => namespace.jurisdiction(value));
1838
1837
  const fetch = (stub, input, init) => Effect.tryPromise({
1839
- try: () => stub.fetch(input, init),
1838
+ try: (signal) => {
1839
+ const callerSignal = init?.signal !== void 0 ? init.signal : input instanceof Request ? input.signal : void 0;
1840
+ return stub.fetch(input, {
1841
+ ...init,
1842
+ signal: callerSignal === null || callerSignal === void 0 ? signal : AbortSignal.any([callerSignal, signal])
1843
+ });
1844
+ },
1840
1845
  catch: (cause) => new DurableObjectFetchError({
1841
1846
  binding: definition.binding,
1842
1847
  cause
1843
1848
  })
1844
1849
  });
1845
- const rpc = Effect.fn("DurableObjectNamespace.rpc")(function* (stub, method, ...args) {
1850
+ const rpc = Effect.fnUntraced(function* (stub, method, ...args) {
1846
1851
  const methodName = String(method);
1847
1852
  const encodedArgs = definition.definition === void 0 ? args : yield* encodeArgs(definition.definition, methodName, args).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1848
1853
  binding: definition.binding,
1849
1854
  method: methodName,
1850
1855
  cause
1851
1856
  })));
1852
- return yield* invokeRpcMethod(stub, method, encodedArgs, (cause) => new DurableObjectRpcError({
1857
+ const nativeArgs = definition.rpcTracing ? yield* withRpcTraceContext(encodedArgs) : encodedArgs;
1858
+ return yield* invokeRpcMethod(stub, method, nativeArgs, (cause) => new DurableObjectRpcError({
1853
1859
  binding: definition.binding,
1854
1860
  method: methodName,
1855
1861
  cause
1856
1862
  }));
1857
1863
  });
1858
- const decodeSuccess$1 = Effect.fn("DurableObjectNamespace.decodeSuccess")(function* (methodName, value) {
1864
+ const decodeSuccess$1 = Effect.fnUntraced(function* (methodName, value) {
1859
1865
  if (definition.definition === void 0) return value;
1860
1866
  return yield* decodeSuccess(definition.definition, methodName, value).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1861
1867
  binding: definition.binding,
@@ -1863,7 +1869,7 @@ const makeClient$7 = (definition) => {
1863
1869
  cause
1864
1870
  })));
1865
1871
  });
1866
- const call = Effect.fn("DurableObjectNamespace.call")(function* (stub, method, ...args) {
1872
+ const call = Effect.fnUntraced(function* (stub, method, ...args) {
1867
1873
  const methodName = String(method);
1868
1874
  const value = yield* resolve(yield* rpc(stub, method, ...args)).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1869
1875
  binding: definition.binding,
@@ -1871,13 +1877,17 @@ const makeClient$7 = (definition) => {
1871
1877
  cause
1872
1878
  })));
1873
1879
  return yield* decodeSuccess$1(methodName, value);
1874
- });
1875
- const scopedCall = Effect.fn("DurableObjectNamespace.scopedCall")(function* (stub, method, ...args) {
1880
+ }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[1])));
1881
+ const scopedCall = Effect.fnUntraced(function* (stub, method, ...args) {
1876
1882
  const methodName = String(method);
1877
1883
  const result = yield* rpc(stub, method, ...args);
1878
- const value = yield* scoped(result);
1884
+ const value = yield* scoped(result).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1885
+ binding: definition.binding,
1886
+ method: methodName,
1887
+ cause
1888
+ })));
1879
1889
  return yield* decodeSuccess$1(methodName, value);
1880
- });
1890
+ }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[1])));
1881
1891
  const directMethods = makeDirectMethods(definition.definition, {
1882
1892
  call,
1883
1893
  fetch,
@@ -1941,19 +1951,6 @@ const reservedMethodNames$1 = /* @__PURE__ */ new Set([
1941
1951
  function method(definition) {
1942
1952
  return method$2(definition);
1943
1953
  }
1944
- /**
1945
- * Creates a Durable Object RPC definition plus implementation/binding helpers.
1946
- *
1947
- * @example
1948
- * ```ts
1949
- * const ChatRoom = DurableObjectDefinition.make("ChatRoom", {
1950
- * postMessage: DurableObjectDefinition.method({
1951
- * args: [Schema.String],
1952
- * success: Schema.Void,
1953
- * }),
1954
- * });
1955
- * ```
1956
- */
1957
1954
  const makeDefinition$2 = (id, methods) => {
1958
1955
  assertNoReservedMethods("Durable Object", methods, reservedMethodNames$1);
1959
1956
  const definition = make$11(id, methods);
@@ -1993,15 +1990,15 @@ const Tag$8 = () => (id, methods) => {
1993
1990
  const fetch = Effect.fn("DurableObject.fetch")(function* (stub, input, init) {
1994
1991
  return yield* (yield* tag).fetch(stub, input, init);
1995
1992
  });
1996
- const rpc = Effect.fn("DurableObject.rpc")(function* (stub, methodName, ...args) {
1993
+ const rpc = Effect.fnUntraced(function* (stub, methodName, ...args) {
1997
1994
  const invokeRpc = (yield* tag).rpc;
1998
1995
  return yield* invokeRpc(stub, methodName, ...args);
1999
1996
  });
2000
- const call = Effect.fn("DurableObject.call")(function* (stub, methodName, ...args) {
1997
+ const call = Effect.fnUntraced(function* (stub, methodName, ...args) {
2001
1998
  const invokeCall = (yield* tag).call;
2002
1999
  return yield* invokeCall(stub, methodName, ...args);
2003
2000
  });
2004
- const scopedCall = Effect.fn("DurableObject.scopedCall")(function* (stub, methodName, ...args) {
2001
+ const scopedCall = Effect.fnUntraced(function* (stub, methodName, ...args) {
2005
2002
  const invokeScopedCall = (yield* tag).scopedCall;
2006
2003
  return yield* invokeScopedCall(stub, methodName, ...args);
2007
2004
  });
@@ -2039,6 +2036,7 @@ const wrapHandlers = (definition, handlers) => {
2039
2036
  const handler = handlers[key];
2040
2037
  wrapped[key] = (...args) => Effect.gen(function* () {
2041
2038
  const decodedArgs = yield* decodeArgs(definition, key, args);
2039
+ yield* recordDecodedArgs(decodedArgs);
2042
2040
  const value = yield* handler(...decodedArgs);
2043
2041
  return yield* encodeSuccess(definition, key, value);
2044
2042
  });
@@ -2052,24 +2050,21 @@ const implement$2 = (_definition, handlers) => handlers;
2052
2050
  //#endregion
2053
2051
  //#region src/DurableObject.ts
2054
2052
  var DurableObject_exports = /* @__PURE__ */ __exportAll({
2053
+ RunSymbol: () => RunSymbol,
2055
2054
  Tag: () => Tag$8,
2056
2055
  implement: () => implement$2,
2057
2056
  make: () => make$7,
2058
2057
  method: () => method
2059
2058
  });
2060
- const reservedMethodNames = /* @__PURE__ */ new Set([
2061
- "constructor",
2062
- "dup",
2063
- "fetch",
2064
- "alarm",
2065
- "webSocketMessage",
2066
- "webSocketClose",
2067
- "webSocketError"
2068
- ]);
2059
+ const reservedMethodNames = reservedMethodNames$4;
2060
+ /** Override to instrument the whole event, then call super[RunSymbol]. */
2069
2061
  const RunSymbol = Symbol.for("effect-cf/DurableObject/run");
2070
2062
  const scheduleTelemetryFlush = scheduleTelemetryFlush$2((flush) => Effect.flatMap(DurableObjectState, (state) => state.waitUntil(flush)));
2071
2063
  /**
2072
- * Creates a Durable Object class backed by a single managed Effect runtime.
2064
+ * Builds a Durable Object whose base `layer` lives for the in-memory instance.
2065
+ * Cloudflare does not expose an eviction or shutdown hook, so finalizers in
2066
+ * that layer are not guaranteed to run. Put resources that require timely
2067
+ * release in `eventLayer`, whose scope closes after each handled event.
2073
2068
  */
2074
2069
  const make$7 = (layer, options = {}) => {
2075
2070
  class EffectDurableObject extends DurableObject {
@@ -2082,13 +2077,15 @@ const make$7 = (layer, options = {}) => {
2082
2077
  }
2083
2078
  [RunSymbol](effect, runOptions = {}) {
2084
2079
  const eventLayer = runOptions.eventLayer === false ? void 0 : options.eventLayer;
2085
- if (eventLayer === void 0) return runEventPromise(this.runtime, effect);
2086
- return runEventPromise(this.runtime, effect, eventLayer);
2080
+ const parent = runOptions.rpc?.parent;
2081
+ const parentSpan = parent === void 0 ? void 0 : Tracer.externalSpan(parent);
2082
+ if (eventLayer === void 0) return runEventPromise(this.runtime, effect, void 0, parentSpan);
2083
+ return runEventPromise(this.runtime, effect, eventLayer, parentSpan);
2087
2084
  }
2088
2085
  fetch(request) {
2089
2086
  const fetchHandler = options.fetch;
2090
2087
  if (fetchHandler === void 0) return Promise.resolve(new Response("Not Found", { status: 404 }));
2091
- return this[RunSymbol](Effect.provideService(fetchHandler, NativeRequest, request));
2088
+ return this[RunSymbol](Effect.provideService(fetchHandler, NativeRequest, request), { event: "fetch" });
2092
2089
  }
2093
2090
  alarm(alarmInfo) {
2094
2091
  const logicalAlarms = options.alarms?.pipe(Effect.asVoid);
@@ -2097,19 +2094,22 @@ const make$7 = (layer, options = {}) => {
2097
2094
  yield* logicalAlarms;
2098
2095
  yield* rawAlarm;
2099
2096
  }) : logicalAlarms ?? rawAlarm;
2100
- if (alarmEffect !== void 0) return this[RunSymbol](alarmEffect.pipe(Effect.onExit(() => scheduleTelemetryFlush)));
2097
+ if (alarmEffect !== void 0) return this[RunSymbol](alarmEffect.pipe(Effect.onExit(() => scheduleTelemetryFlush)), { event: "alarm" });
2101
2098
  }
2102
2099
  webSocketMessage(socket, message) {
2103
- if (options.webSocketMessage !== void 0) return this[RunSymbol](options.webSocketMessage(fromWebSocket(socket), message));
2100
+ if (options.webSocketMessage !== void 0) return this[RunSymbol](options.webSocketMessage(fromWebSocket(socket), message), { event: "webSocketMessage" });
2104
2101
  }
2105
2102
  webSocketClose(socket, code, reason, wasClean) {
2106
- if (options.webSocketClose !== void 0) return this[RunSymbol](options.webSocketClose(fromWebSocket(socket), code, reason, wasClean));
2103
+ if (options.webSocketClose !== void 0) return this[RunSymbol](options.webSocketClose(fromWebSocket(socket), code, reason, wasClean), { event: "webSocketClose" });
2107
2104
  }
2108
2105
  webSocketError(socket, cause) {
2109
- if (options.webSocketError !== void 0) return this[RunSymbol](options.webSocketError(fromWebSocket(socket), cause));
2106
+ if (options.webSocketError !== void 0) return this[RunSymbol](options.webSocketError(fromWebSocket(socket), cause), { event: "webSocketError" });
2110
2107
  }
2111
2108
  }
2112
- defineEntrypointRpcMethods("Durable Object", EffectDurableObject.prototype, options.rpc, reservedMethodNames, (self, effect) => self[RunSymbol](effect), () => scheduleTelemetryFlush);
2109
+ defineEntrypointRpcMethods("Durable Object", EffectDurableObject.prototype, options.rpc, reservedMethodNames, (self, effect, rpc) => self[RunSymbol](effect, {
2110
+ event: "rpc",
2111
+ rpc
2112
+ }), () => scheduleTelemetryFlush, options.rpcTracing);
2113
2113
  return assumeEntrypointClass(EffectDurableObject);
2114
2114
  };
2115
2115
  //#endregion
@@ -2165,30 +2165,10 @@ var StoredAlarmDecodeError = class extends Data.TaggedError("StoredAlarmDecodeEr
2165
2165
  return `Failed to decode stored alarm "${this.storageId}": ${causeMessage(this.cause)}`;
2166
2166
  }
2167
2167
  };
2168
- /**
2169
- * Events handled by `processDueAlarms`.
2170
- *
2171
- * `AlarmDue` represents one durable alarm whose scheduled time is now due. The
2172
- * `tag` is the consumer-owned routing key, while `id` is the stable alarm id
2173
- * within that tag.
2174
- *
2175
- * `scheduledAt` is the logical due-after timestamp from durable storage. It is
2176
- * not expected to match the current Durable Object alarm invocation time,
2177
- * especially during retries. Retries re-scan durable rows with `run_at <= now`
2178
- * and identify logical events by `{ tag, id }`.
2179
- *
2180
- * @example Handling events by tag
2181
- * ```ts
2182
- * yield* durableObjectAlarm.processDueAlarms((event) =>
2183
- * event.tag === "heartbeat"
2184
- * ? heartbeatManager.handleAlarmEvent(event).pipe(Effect.asVoid)
2185
- * : Effect.void
2186
- * );
2187
- * ```
2188
- */
2189
2168
  const DurableObjectAlarmEvent = Schema.TaggedUnion({ AlarmDue: {
2190
2169
  id: Schema.NonEmptyString,
2191
2170
  payload: Schema.Json,
2171
+ /** Persisted due time, which can differ from the invocation time during retries. */
2192
2172
  scheduledAt: Schema.DateTimeUtc,
2193
2173
  tag: Schema.NonEmptyString
2194
2174
  } });
@@ -2278,50 +2258,6 @@ const define = (definitions) => ({ handlers: (handlers, options) => processDue((
2278
2258
  return action ?? optionAction;
2279
2259
  })
2280
2260
  }) });
2281
- /**
2282
- * SQLite-backed Durable Object alarm scheduler.
2283
- *
2284
- * `DurableObjectAlarm` stores alarms in the current Durable Object's SQLite storage
2285
- * and keeps the platform alarm set to the earliest pending scheduled alarm. The
2286
- * platform alarm timestamp is only a wake-up hint; logical event identity comes
2287
- * from persisted `{ tag, id }` rows.
2288
- *
2289
- * Retry safety depends on acknowledgement ordering. `processDueAlarms` runs the
2290
- * caller's handler first and only then conditionally deletes or advances the
2291
- * same selected row. By default, handler failures are isolated: the failed row
2292
- * is retried after a delay, later due rows continue, and the platform alarm is
2293
- * reconciled once at the end. Use `mode: "ordered"` for strict workflows where
2294
- * one failed logical alarm should block later due alarms.
2295
- *
2296
- * Provide `DurableObjectAlarm.layer` anywhere `DurableObjectState` is available.
2297
- *
2298
- * @example Providing the service
2299
- * ```ts
2300
- * const program = Effect.gen(function* () {
2301
- * const durableObjectAlarm = yield* DurableObjectAlarm;
2302
- * const now = yield* DateTime.now;
2303
- *
2304
- * yield* durableObjectAlarm.scheduleAlarm({
2305
- * tag: "heartbeat",
2306
- * id: "heartbeat-check",
2307
- * runAt: DateTime.add(now, { seconds: 5 }),
2308
- * repeatEvery: Duration.seconds(5),
2309
- * payload: null,
2310
- * });
2311
- * }).pipe(Effect.provide(DurableObjectAlarm.layer));
2312
- * ```
2313
- *
2314
- * @example Processing due alarms
2315
- * ```ts
2316
- * const handledEvents = yield* durableObjectAlarm.processDueAlarms((event) =>
2317
- * Effect.gen(function* () {
2318
- * if (event.tag === "heartbeat") {
2319
- * yield* heartbeatManager.handleAlarmEvent(event);
2320
- * }
2321
- * })
2322
- * );
2323
- * ```
2324
- */
2325
2261
  var DurableObjectAlarm = class DurableObjectAlarm extends Context.Service()("effect-cf/DurableObjectAlarm") {
2326
2262
  static layer = Layer.effect(DurableObjectAlarm, Effect.gen(function* () {
2327
2263
  const state = yield* DurableObjectState;
@@ -2486,9 +2422,6 @@ const ResumableAttachmentMetadataSchema = Schema.Struct({
2486
2422
  subscriptions: Schema.Array(PersistedSubscriptionSchema)
2487
2423
  });
2488
2424
  const decodeResumableAttachment = Schema.decodeUnknownOption(ResumableAttachmentMetadataSchema);
2489
- /**
2490
- * Context tag for the Durable Object RPC websocket service.
2491
- */
2492
2425
  var DurableObjectRpcWebSocket = class extends Context.Service()("effect-cf/DurableObjectRpcWebSocket") {};
2493
2426
  /**
2494
2427
  * Builds a hibernation-aware transport that bridges Durable Object websocket
@@ -2509,7 +2442,6 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2509
2442
  const disconnects = yield* Queue.make();
2510
2443
  const connectionsBySocket = /* @__PURE__ */ new Map();
2511
2444
  const connectionsById = /* @__PURE__ */ new Map();
2512
- const clientIds = /* @__PURE__ */ new Set();
2513
2445
  const resetSockets = /* @__PURE__ */ new WeakSet();
2514
2446
  const declarationsById = /* @__PURE__ */ new Map();
2515
2447
  const declarationsByTag = /* @__PURE__ */ new Map();
@@ -2525,14 +2457,6 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2525
2457
  declarationsByTag.set(declaration.rpcTag, declaration);
2526
2458
  }
2527
2459
  const reserveClientId = (socket) => {
2528
- const attachment = readAttachment(socket.raw, attachmentKey);
2529
- if (attachment._tag === "Invalid") throw new Error("Invalid Durable Object RPC websocket attachment metadata");
2530
- if (attachment._tag === "Valid") {
2531
- const metadata = attachment.metadata;
2532
- nextClientId = Math.max(nextClientId, metadata.clientId + 1);
2533
- writeAttachment(socket.raw, attachmentKey, metadata);
2534
- return metadata;
2535
- }
2536
2460
  const id = nextClientId++;
2537
2461
  const created = {
2538
2462
  version: legacyAttachmentVersion,
@@ -2585,7 +2509,6 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2585
2509
  for (const subscription of restoredSubscriptions) if (!addSubscription(connection, subscription)) throw new Error("Duplicate restored resumable RPC stream subscription identity");
2586
2510
  connectionsBySocket.set(socket.raw, connection);
2587
2511
  connectionsById.set(connection.id, connection);
2588
- clientIds.add(connection.id);
2589
2512
  nextClientId = Math.max(nextClientId, connection.id + 1);
2590
2513
  return connection;
2591
2514
  };
@@ -2622,7 +2545,6 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2622
2545
  if (connection === void 0) return;
2623
2546
  connectionsBySocket.delete(socket.raw);
2624
2547
  connectionsById.delete(connection.id);
2625
- clientIds.delete(connection.id);
2626
2548
  activeNonResumableRequestCount -= connection.nonResumableRequestIds.size;
2627
2549
  connection.requestIds.clear();
2628
2550
  connection.nonResumableRequestIds.clear();
@@ -2841,7 +2763,7 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2841
2763
  end: (clientId) => Effect.sync(() => {
2842
2764
  connectionsById.get(clientId)?.socket.raw.close();
2843
2765
  }),
2844
- clientIds: Effect.sync(() => clientIds),
2766
+ clientIds: Effect.sync(() => new Set(connectionsById.keys())),
2845
2767
  initialMessage: Effect.succeedNone,
2846
2768
  supportsAck: true,
2847
2769
  supportsTransferables: false,
@@ -2975,13 +2897,9 @@ const writeAttachment = (socket, key, metadata) => {
2975
2897
  const current = socket.deserializeAttachment();
2976
2898
  if (current !== null && current !== void 0 && !Predicate.isObject(current)) throw new Error("DurableObjectRpcWebSocket requires object-shaped websocket attachments so adapter metadata can preserve application fields");
2977
2899
  const attachment = Predicate.isObject(current) ? current : {};
2978
- const currentMetadata = Predicate.hasProperty(attachment, key) && Predicate.isObject(attachment[key]) ? attachment[key] : {};
2979
2900
  socket.serializeAttachment({
2980
2901
  ...attachment,
2981
- [key]: {
2982
- ...currentMetadata,
2983
- ...metadata
2984
- }
2902
+ [key]: metadata
2985
2903
  });
2986
2904
  };
2987
2905
  const makeHeartbeatController = (state, serialization, policy) => Effect.gen(function* () {
@@ -3004,17 +2922,6 @@ const makeHeartbeatController = (state, serialization, policy) => Effect.gen(fun
3004
2922
  //#endregion
3005
2923
  //#region src/DurableObjectSqlite.ts
3006
2924
  var DurableObjectSqlite_exports = /* @__PURE__ */ __exportAll({ layer: () => layer$7 });
3007
- /**
3008
- * Provides `effect/unstable/sql` from the current Durable Object SQLite storage.
3009
- *
3010
- * @example
3011
- * ```ts
3012
- * const RoomLayer = Layer.mergeAll(
3013
- * DurableObjectSqlite.layer(),
3014
- * OtherRoomServices,
3015
- * );
3016
- * ```
3017
- */
3018
2925
  const layer$7 = (options) => Layer.unwrap(Effect.gen(function* () {
3019
2926
  const state = yield* DurableObjectState;
3020
2927
  return SqliteClient.layer({
@@ -3038,17 +2945,13 @@ var Email_exports = /* @__PURE__ */ __exportAll({
3038
2945
  });
3039
2946
  const expectedSendEmailBinding = "Send Email binding with send()";
3040
2947
  const textEncoder = new TextEncoder();
3041
- /** Documented Cloudflare Email Sending limits. */
3042
2948
  const sendLimits = {
3043
- /** Combined `to`, `cc`, and `bcc` addresses per message. */
3044
2949
  maxRecipients: 50,
3045
2950
  maxAttachments: 32,
3046
- /** Total message size, including attachments. Not enforced client side. */
3047
2951
  maxMessageBytes: 5 * 1024 * 1024,
3048
2952
  maxHeaderNameBytes: 100,
3049
2953
  maxHeaderValueBytes: 2048,
3050
2954
  maxHeadersBytes: 16 * 1024,
3051
- /** Allowlisted custom headers, excluding `X-` prefixed headers. */
3052
2955
  maxAllowlistHeaders: 20
3053
2956
  };
3054
2957
  /**
@@ -3081,14 +2984,12 @@ const emailErrorCodes = [
3081
2984
  "E_HEADERS_TOO_LARGE",
3082
2985
  "E_HEADERS_TOO_MANY"
3083
2986
  ];
3084
- /** Error raised when a Cloudflare Send Email operation fails. */
3085
2987
  var EmailOperationError = class extends Data.TaggedError("EmailOperationError") {
3086
2988
  get message() {
3087
2989
  const code = this.code === void 0 ? "" : ` (${this.code})`;
3088
2990
  return `Email ${this.operation} failed for binding "${this.binding}"${code}: ${causeMessage(this.cause)}`;
3089
2991
  }
3090
2992
  };
3091
- /** Error raised when a message violates documented Cloudflare Email Sending limits. */
3092
2993
  var EmailValidationError = class extends Data.TaggedError("EmailValidationError") {
3093
2994
  get message() {
3094
2995
  return `Email ${this.operation} for binding "${this.binding}" failed validation: ${violationsMessage(this.violations)}`;
@@ -3309,7 +3210,6 @@ var Images_exports = /* @__PURE__ */ __exportAll({
3309
3210
  });
3310
3211
  const TypeId = "~effect-cf/Images/Steps";
3311
3212
  const expectedImagesBinding = "Images binding with info() and input()";
3312
- /** Error raised when a Cloudflare Images operation fails. */
3313
3213
  var ImagesOperationError = class extends Data.TaggedError("ImagesOperationError") {
3314
3214
  get message() {
3315
3215
  return `Images ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -3320,7 +3220,6 @@ const makeSteps = (steps) => ({
3320
3220
  [TypeId]: TypeId,
3321
3221
  steps
3322
3222
  });
3323
- /** Empty Images transformation pipeline. */
3324
3223
  const empty = makeSteps([]);
3325
3224
  const transform = Function$1.dual(2, (steps, transformValue) => makeSteps([...steps.steps, Step.Transform({ transform: transformValue })]));
3326
3225
  const draw = Function$1.dual(2, (steps, drawValue) => makeSteps([...steps.steps, Step.Draw(drawValue)]));
@@ -3407,7 +3306,6 @@ var Kv_exports = /* @__PURE__ */ __exportAll({
3407
3306
  makeClient: () => makeClient$3
3408
3307
  });
3409
3308
  const expectedKvNamespace = "KV namespace binding with get(), put(), delete(), getWithMetadata(), and list()";
3410
- /** Error raised when a KV operation fails. */
3411
3309
  var KvOperationError = class extends Data.TaggedError("KvOperationError") {
3412
3310
  get message() {
3413
3311
  return `Kv ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -3531,7 +3429,6 @@ var R2_exports = /* @__PURE__ */ __exportAll({
3531
3429
  makeClient: () => makeClient$2
3532
3430
  });
3533
3431
  const expectedR2Bucket = "R2 bucket binding with head(), get(), put(), createMultipartUpload(), resumeMultipartUpload(), delete(), and list()";
3534
- /** Error raised when an R2 operation fails. */
3535
3432
  var R2OperationError = class extends Data.TaggedError("R2OperationError") {
3536
3433
  get message() {
3537
3434
  return `R2 ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -3639,7 +3536,6 @@ var Vectorize_exports = /* @__PURE__ */ __exportAll({
3639
3536
  makeClient: () => makeClient$1
3640
3537
  });
3641
3538
  const expectedVectorizeBinding = "Vectorize index binding with describe(), query(), insert(), upsert(), deleteByIds(), and getByIds()";
3642
- /** Error raised when a Vectorize operation fails. */
3643
3539
  var VectorizeOperationError = class extends Data.TaggedError("VectorizeOperationError") {
3644
3540
  get message() {
3645
3541
  return `Vectorize ${this.operation} failed for binding "${this.binding}": ${causeMessage(this.cause)}`;
@@ -3715,11 +3611,8 @@ var WebTransport_exports = /* @__PURE__ */ __exportAll({
3715
3611
  * `Record<string, unknown>` side of `request.cf`.
3716
3612
  */
3717
3613
  var InboundTransport = class extends Schema.Class("InboundTransport")({
3718
- /** The HTTP protocol the client used, e.g. `"HTTP/2"` or `"HTTP/3"`. */
3719
3614
  httpProtocol: Schema.String,
3720
- /** Client round-trip time; only present for QUIC (HTTP/3) connections. */
3721
3615
  clientQuicRtt: Schema.optional(Schema.Number),
3722
- /** Client round-trip time; only present for TCP (HTTP/1.x, HTTP/2) connections. */
3723
3616
  clientTcpRtt: Schema.optional(Schema.Number)
3724
3617
  }) {};
3725
3618
  const decodeInboundTransport = Schema.decodeUnknownResult(InboundTransport);
@@ -3731,16 +3624,7 @@ const decodeInboundTransport = Schema.decodeUnknownResult(InboundTransport);
3731
3624
  * the expected shape.
3732
3625
  */
3733
3626
  const inboundTransport = (request) => Result.getSuccess(decodeInboundTransport(request.cf));
3734
- /**
3735
- * Returns `true` when the client reached Cloudflare's edge over QUIC
3736
- * (HTTP/3). Prefers the documented QUIC signal (`clientQuicRtt` is only
3737
- * present for QUIC connections) and falls back to the `httpProtocol` string.
3738
- *
3739
- * Note this describes the browser→edge hop only: the edge always terminates
3740
- * QUIC, and the Worker still handles an ordinary `fetch` Request.
3741
- */
3742
3627
  const isHttp3 = (transport) => transport.clientQuicRtt !== void 0 || transport.httpProtocol === "HTTP/3";
3743
- /** Feature-detects the WebTransport capabilities of the current runtime. */
3744
3628
  const capabilities = Effect.sync(() => {
3745
3629
  const runtime = globalThis;
3746
3630
  return {
@@ -3748,7 +3632,6 @@ const capabilities = Effect.sync(() => {
3748
3632
  outboundSessions: Predicate.hasProperty(runtime, "WebTransport") && Predicate.isFunction(runtime["WebTransport"])
3749
3633
  };
3750
3634
  });
3751
- /** Raised when a WebTransport capability is unavailable in this runtime. */
3752
3635
  var WebTransportUnsupportedError = class extends Data.TaggedError("WebTransportUnsupportedError") {
3753
3636
  get message() {
3754
3637
  return this.capability === "inbound-sessions" ? "Cloudflare Workers cannot accept inbound WebTransport sessions: the edge terminates QUIC and no runtime session API exists (cloudflare/workerd#6451). Use Durable Object WebSockets for bidirectional push." : "This Workers runtime provides no WebTransport client: workerd has no QUIC stack and cloudflare:sockets is TCP-only.";
@@ -3918,10 +3801,6 @@ const wrapHandler = (definition, handler) => {
3918
3801
  const implement$1 = (_definition, handler) => handler;
3919
3802
  //#endregion
3920
3803
  //#region src/Workflow.ts
3921
- /**
3922
- * Effect wrapper for Cloudflare Workflows entrypoints and bindings; distinct
3923
- * from Effect's runtime-agnostic `effect/unstable/workflow` cluster module.
3924
- */
3925
3804
  var Workflow_exports = /* @__PURE__ */ __exportAll({
3926
3805
  Tag: () => Tag,
3927
3806
  WorkflowEvent: () => WorkflowEvent$1,
@@ -3937,7 +3816,6 @@ var Workflow_exports = /* @__PURE__ */ __exportAll({
3937
3816
  waitForEvent: () => waitForEvent
3938
3817
  });
3939
3818
  var WorkflowEvent$1 = class extends Context.Service()("effect-cf/WorkflowEvent") {};
3940
- /** Failure raised when a Cloudflare Workflow step operation rejects. */
3941
3819
  var WorkflowStepError = class extends Data.TaggedError("WorkflowStepError") {
3942
3820
  get message() {
3943
3821
  const step = this.step === void 0 ? "" : ` in step "${this.step}"`;
@@ -3973,20 +3851,29 @@ const exposeCloudflareNonRetryableError = (effect) => Effect.catchCause(effect,
3973
3851
  const error = Cause.findErrorOption(cause);
3974
3852
  return Option.isSome(error) && error.value instanceof WorkflowStepNonRetryableError ? Effect.die(toCloudflareNonRetryableError(error.value)) : Effect.failCause(cause);
3975
3853
  });
3976
- const fromWorkflowStep = (step, runPromise) => ({
3854
+ const fromWorkflowStep = (step) => ({
3977
3855
  raw: step,
3978
- do: (name, effect, config) => Effect.context().pipe(Effect.flatMap((context) => Effect.tryPromise({
3979
- try: () => {
3980
- const run = (stepContext) => runPromise(exposeCloudflareNonRetryableError(Effect.scoped(Effect.provideService(Effect.provideContext(effect, context), WorkflowStepContext$1, stepContext))));
3981
- const rawStep = step;
3982
- return config === void 0 ? rawStep.do(name, run) : rawStep.do(name, config, run);
3983
- },
3984
- catch: (cause) => new WorkflowStepError({
3985
- step: name,
3986
- operation: "do",
3987
- cause
3988
- })
3989
- }))),
3856
+ do: (name, effect, config) => Effect.gen(function* () {
3857
+ const context = yield* Effect.context();
3858
+ return yield* Effect.scoped(Effect.gen(function* () {
3859
+ const runPromise = yield* FiberSet.makeRuntimePromise();
3860
+ return yield* Effect.tryPromise({
3861
+ try: () => {
3862
+ const run = (stepContext) => {
3863
+ const stepEffect = Effect.scoped(Effect.provideService(effect, WorkflowStepContext$1, stepContext));
3864
+ return runPromise(exposeCloudflareNonRetryableError(Effect.provideContext(stepEffect, context)));
3865
+ };
3866
+ const rawStep = step;
3867
+ return config === void 0 ? rawStep.do(name, run) : rawStep.do(name, config, run);
3868
+ },
3869
+ catch: (cause) => new WorkflowStepError({
3870
+ step: name,
3871
+ operation: "do",
3872
+ cause
3873
+ })
3874
+ });
3875
+ }));
3876
+ }),
3990
3877
  sleep: (name, duration) => Effect.tryPromise({
3991
3878
  try: () => step.sleep(name, duration),
3992
3879
  catch: (cause) => new WorkflowStepError({
@@ -4022,7 +3909,7 @@ const make = (layer, options) => {
4022
3909
  this.runtime = makeEntrypointRuntime(layer, env, Layer.mergeAll(Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx))));
4023
3910
  }
4024
3911
  run(event, step) {
4025
- const workflowServices = Layer.mergeAll(Layer.succeed(WorkflowEvent$1, fromWorkflowEvent(event)), Layer.succeed(WorkflowStep$1, fromWorkflowStep(step, (effect) => this.runtime.runPromise(effect))));
3912
+ const workflowServices = Layer.mergeAll(Layer.succeed(WorkflowEvent$1, fromWorkflowEvent(event)), Layer.succeed(WorkflowStep$1, fromWorkflowStep(step)));
4026
3913
  return runEventPromise(this.runtime, options.run(event.payload), workflowServices);
4027
3914
  }
4028
3915
  }
@@ -4035,4 +3922,4 @@ const waitForEvent = (name, options) => Effect.flatMap(WorkflowStep$1, (workflow
4035
3922
  const Tag = Tag$1;
4036
3923
  const implement = implement$1;
4037
3924
  //#endregion
4038
- export { AiGateway_exports as AiGateway, AnalyticsEngine_exports as AnalyticsEngine, Artifacts_exports as Artifacts, 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, WebTransport_exports as WebTransport, 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 };
3925
+ export { AiGateway_exports as AiGateway, AnalyticsEngine_exports as AnalyticsEngine, Artifacts_exports as Artifacts, 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, RpcTracing_exports as RpcTracing, ServiceBinding_exports as ServiceBinding, Vectorize_exports as Vectorize, WebTransport_exports as WebTransport, 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 };