effect-cf 0.34.0 → 0.36.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.
package/dist/index.mjs CHANGED
@@ -1,13 +1,15 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
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";
3
+ import { n as Service$1, r as layer$17, t as Binding_exports } from "./Binding-C82jRhdr.mjs";
4
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-De4ZojhY.mjs";
6
- import { Cause, Clock, Config, ConfigProvider, Context, Data, DateTime, Duration, Effect, Exit, Function as Function$1, Layer, ManagedRuntime, Option, Predicate, Queue, References, Result, Schema, Tracer } from "effect";
7
- import { FetchHttpClient, HttpClient, HttpClientRequest, HttpEffect, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
5
+ import { t as fromExecutionContext } from "./WorkerContext-Yobnfw-K.mjs";
6
+ import { a as DurableWebSocketAttachmentError, i as DurableObjectWebSocket_exports, n as DurableObjectState_exports, o as fromWebSocket, r as fromDurableObjectState, s as DurableObjectStorage_exports, t as DurableObjectState } from "./DurableObjectState-DCh4PZMN.mjs";
7
+ import { A as QueueDefinition_exports, C as decodeSuccess, D as method$1, E as make$15, O as reservedMethodNames$2, S as decodeArgs, T as encodeSuccess, _ as RpcTracing_exports, a as WorkerDefinition_exports, b as RpcDefinition_exports, c as resolve, d as makeEntrypointRuntime, f as runEventPromise, g as recordDecodedArgs, h as invokeRpcMethod, i as Worker_exports, j as QueueBinding_exports, k as Queue_exports, l as scoped, m as defineEntrypointRpcMethods, n as NativeRequest, o as ServiceBinding_exports, p as assumeEntrypointClass, r as WorkerContext, s as Rpc_exports, t as ExecutionContext, u as scheduleTelemetryFlush$1, v as withRpcClientSpan, w as encodeArgs, x as assertNoReservedMethods, y as withRpcTraceContext } from "./Worker-XsGJsCJX.mjs";
8
+ import { Cause, Clock, Config, ConfigProvider, Context, Data, DateTime, Duration, Effect, Exit, FiberSet, Function as Function$1, Layer, Option, Predicate, Queue, Result, Schema, Tracer } from "effect";
9
+ import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
8
10
  import { OtlpExporter, OtlpLogger, OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
9
11
  import { D1Client } from "@effect/sql-d1";
10
- import { DurableObject, RpcStub, RpcTarget, WorkerEntrypoint, WorkflowEntrypoint } from "cloudflare:workers";
12
+ import { DurableObject, WorkflowEntrypoint } from "cloudflare:workers";
11
13
  import * as RpcMessage from "effect/unstable/rpc/RpcMessage";
12
14
  import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";
13
15
  import * as RpcServer from "effect/unstable/rpc/RpcServer";
@@ -15,13 +17,13 @@ import { SqliteClient } from "@effect/sql-sqlite-do";
15
17
  import { NonRetryableError } from "cloudflare:workflows";
16
18
  //#region src/WorkersAi.ts
17
19
  var WorkersAi_exports = /* @__PURE__ */ __exportAll({
18
- Tag: () => Tag$16,
20
+ Tag: () => Tag$13,
19
21
  WorkersAiOperationError: () => WorkersAiOperationError,
20
22
  embeddingResponse: () => embeddingResponse,
21
23
  isWorkersAiBinding: () => isWorkersAiBinding,
22
- layer: () => layer$18,
23
- make: () => make$18,
24
- makeClient: () => makeClient$15
24
+ layer: () => layer$16,
25
+ make: () => make$14,
26
+ makeClient: () => makeClient$13
25
27
  });
26
28
  const expectedWorkersAiBinding = "Workers AI binding with run(), gateway(), and models()";
27
29
  var WorkersAiOperationError = class extends Data.TaggedError("WorkersAiOperationError") {
@@ -50,11 +52,11 @@ const embeddingResponse = (value) => ({
50
52
  data: value.data ?? [],
51
53
  [embeddingDimensionsKey]: value[embeddingDimensionsKey] ?? []
52
54
  });
53
- const decodeEmbeddingResponse = Schema.decodeUnknownOption(Schema.Struct({
55
+ const decodeEmbeddingResponse = Schema.decodeUnknownEffect(Schema.Struct({
54
56
  data: Schema.optional(Schema.Array(Schema.Array(Schema.Number))),
55
57
  [embeddingDimensionsKey]: Schema.optional(Schema.Array(Schema.Number))
56
58
  }));
57
- const makeClient$15 = (definition) => (ai) => {
59
+ const makeClient$13 = (definition) => (ai) => {
58
60
  const run = Effect.fn("WorkersAi.run")((model, input, options) => tryWorkersAiPromise(definition.binding, "run", () => {
59
61
  return ai.run(model, input, options);
60
62
  }));
@@ -62,22 +64,25 @@ const makeClient$15 = (definition) => (ai) => {
62
64
  definition,
63
65
  aiGatewayLogId: tryWorkersAiSync(definition.binding, "aiGatewayLogId", () => ai.aiGatewayLogId),
64
66
  run,
65
- runEmbedding: Effect.fn("WorkersAi.runEmbedding")((model, input, options) => {
66
- return run(model, input, options).pipe(Effect.map((response) => Option.match(decodeEmbeddingResponse(response), {
67
- onNone: () => embeddingResponse({}),
68
- onSome: embeddingResponse
67
+ runEmbedding: Effect.fn("WorkersAi.runEmbedding")(function* (model, input, options) {
68
+ const response = yield* run(model, input, options);
69
+ const decoded = yield* decodeEmbeddingResponse(response).pipe(Effect.mapError((cause) => new WorkersAiOperationError({
70
+ binding: definition.binding,
71
+ operation: "runEmbedding",
72
+ cause
69
73
  })));
74
+ return embeddingResponse(decoded);
70
75
  }),
71
76
  models: Effect.fn("WorkersAi.models")((params) => tryWorkersAiPromise(definition.binding, "models", () => ai.models(params))),
72
77
  gateway: (gatewayId) => tryWorkersAiSync(definition.binding, "gateway", () => ai.gateway(gatewayId)),
73
78
  rawUnsafe: Effect.succeed(ai)
74
79
  };
75
80
  };
76
- const layer$18 = (tag, definition) => layer$19(tag, definition.binding, (value) => isWorkersAiBinding(value), makeClient$15(definition), { expected: expectedWorkersAiBinding });
77
- const make$18 = (id) => Tag$16()(id);
78
- const Tag$16 = () => (id) => {
81
+ const layer$16 = (tag, definition) => layer$17(tag, definition.binding, (value) => isWorkersAiBinding(value), makeClient$13(definition), { expected: expectedWorkersAiBinding });
82
+ const make$14 = (id) => Tag$13()(id);
83
+ const Tag$13 = () => (id) => {
79
84
  const tag = Context.Service()(id);
80
- const makeLayer = (definition) => layer$18(tag, definition);
85
+ const makeLayer = (definition) => layer$16(tag, definition);
81
86
  return Object.assign(tag, {
82
87
  id,
83
88
  layer: makeLayer
@@ -87,11 +92,11 @@ const Tag$16 = () => (id) => {
87
92
  //#region src/AiGateway.ts
88
93
  var AiGateway_exports = /* @__PURE__ */ __exportAll({
89
94
  AiGatewayOperationError: () => AiGatewayOperationError,
90
- Tag: () => Tag$15,
95
+ Tag: () => Tag$12,
91
96
  isAiGatewayBinding: () => isAiGatewayBinding,
92
- layer: () => layer$17,
93
- make: () => make$17,
94
- makeClient: () => makeClient$14,
97
+ layer: () => layer$15,
98
+ make: () => make$13,
99
+ makeClient: () => makeClient$12,
95
100
  makeClientFromAi: () => makeClientFromAi,
96
101
  makeHttpClient: () => makeHttpClient
97
102
  });
@@ -168,7 +173,7 @@ const ensureSuccessfulResponse = (response) => {
168
173
  if (!response.ok) throw new Error(`AI Gateway HTTP request failed with status ${response.status}`);
169
174
  };
170
175
  const isAiGatewayBinding = (value) => isWorkersAiBinding(value);
171
- const makeClient$14 = (definition, gateway) => ({
176
+ const makeClient$12 = (definition, gateway) => ({
172
177
  definition,
173
178
  run: Effect.fn("AiGateway.run")((data, options) => tryAiGatewayPromise(definition.binding, "run", () => gateway.run(Array.isArray(data) ? [...data] : data, options))),
174
179
  getUrl: Effect.fn("AiGateway.getUrl")((provider) => tryAiGatewayPromise(definition.binding, "getUrl", () => gateway.getUrl(provider))),
@@ -188,11 +193,11 @@ const makeClientFromAi = (definition, ai) => {
188
193
  const withGateway = (operation) => gateway.pipe(Effect.flatMap(operation));
189
194
  return {
190
195
  definition,
191
- run: (data, options) => withGateway((raw) => makeClient$14(definition, raw).run(data, options)),
192
- getUrl: (provider) => withGateway((raw) => makeClient$14(definition, raw).getUrl(provider)),
193
- fetch: (options) => withGateway((raw) => makeClient$14(definition, raw).fetch(options)),
194
- patchLog: (logId, data) => withGateway((raw) => makeClient$14(definition, raw).patchLog(logId, data)),
195
- getLog: (logId) => withGateway((raw) => makeClient$14(definition, raw).getLog(logId)),
196
+ run: (data, options) => withGateway((raw) => makeClient$12(definition, raw).run(data, options)),
197
+ getUrl: (provider) => withGateway((raw) => makeClient$12(definition, raw).getUrl(provider)),
198
+ fetch: (options) => withGateway((raw) => makeClient$12(definition, raw).fetch(options)),
199
+ patchLog: (logId, data) => withGateway((raw) => makeClient$12(definition, raw).patchLog(logId, data)),
200
+ getLog: (logId) => withGateway((raw) => makeClient$12(definition, raw).getLog(logId)),
196
201
  rawUnsafe: gateway
197
202
  };
198
203
  };
@@ -242,11 +247,11 @@ const makeHttpClient = (definition, request = fetch) => {
242
247
  rawUnsafe: Effect.fail(aiGatewayError(binding, "rawUnsafe", /* @__PURE__ */ new TypeError("HTTP AI Gateway clients have no raw binding")))
243
248
  };
244
249
  };
245
- const layer$17 = (tag, definition) => layer$19(tag, definition.binding, isAiGatewayBinding, (ai) => makeClientFromAi(definition, ai), { expected: expectedAiGatewayBinding });
246
- const make$17 = (id) => Tag$15()(id);
247
- const Tag$15 = () => (id) => {
250
+ const layer$15 = (tag, definition) => layer$17(tag, definition.binding, isAiGatewayBinding, (ai) => makeClientFromAi(definition, ai), { expected: expectedAiGatewayBinding });
251
+ const make$13 = (id) => Tag$12()(id);
252
+ const Tag$12 = () => (id) => {
248
253
  const tag = Context.Service()(id);
249
- const makeLayer = (definition) => layer$17(tag, definition);
254
+ const makeLayer = (definition) => layer$15(tag, definition);
250
255
  return Object.assign(tag, {
251
256
  id,
252
257
  layer: makeLayer
@@ -261,13 +266,13 @@ var AnalyticsEngine_exports = /* @__PURE__ */ __exportAll({
261
266
  AnalyticsEngineQueryError: () => AnalyticsEngineQueryError,
262
267
  AnalyticsEngineWriteValidationError: () => AnalyticsEngineWriteValidationError,
263
268
  QueryTag: () => QueryTag,
264
- Tag: () => Tag$14,
269
+ Tag: () => Tag$11,
265
270
  isAnalyticsEngineDataset: () => isAnalyticsEngineDataset,
266
- layer: () => layer$16,
271
+ layer: () => layer$14,
267
272
  layerFetch: () => layerFetch,
268
273
  layerFetchConfig: () => layerFetchConfig,
269
- make: () => make$16,
270
- makeClient: () => makeClient$13,
274
+ make: () => make$12,
275
+ makeClient: () => makeClient$11,
271
276
  makeQuery: () => makeQuery,
272
277
  makeQueryClient: () => makeQueryClient,
273
278
  queryConfig: () => queryConfig,
@@ -413,7 +418,11 @@ const queryRequest = (definition, sql, options) => {
413
418
  };
414
419
  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 }))));
415
420
  const executeQueryRequest = (definition, httpClient, sql, options) => Effect.gen(function* () {
416
- const response = yield* httpClient.execute(queryRequest(definition, sql, options)).pipe(Effect.mapError((cause) => analyticsEngineQueryError(definition, "query", "Analytics Engine SQL API request failed", { cause })));
421
+ const request = yield* Effect.try({
422
+ try: () => queryRequest(definition, sql, options),
423
+ catch: (cause) => analyticsEngineQueryError(definition, "query", "Invalid Analytics Engine SQL API URL", { cause })
424
+ });
425
+ const response = yield* httpClient.execute(request).pipe(Effect.mapError((cause) => analyticsEngineQueryError(definition, "query", "Analytics Engine SQL API request failed", { cause })));
417
426
  if (response.status < 200 || response.status >= 300) {
418
427
  const body = yield* responseText(definition, response, "queryErrorBody");
419
428
  return yield* Effect.fail(analyticsEngineQueryError(definition, "query", `Analytics Engine SQL API returned HTTP ${response.status}`, {
@@ -452,7 +461,7 @@ const makeQueryClientWith = (definition, httpClient) => {
452
461
  };
453
462
  const makeQueryClient = (definition) => Effect.map(HttpClient.HttpClient, (httpClient) => makeQueryClientWith(definition, httpClient));
454
463
  const isAnalyticsEngineDataset = (value) => Predicate.hasProperty(value, "writeDataPoint") && Predicate.isFunction(value.writeDataPoint);
455
- const makeClient$13 = (definition, defaults) => (dataset) => {
464
+ const makeClient$11 = (definition, defaults) => (dataset) => {
456
465
  return {
457
466
  definition,
458
467
  writeDataPoint: Effect.fn("AnalyticsEngine.writeDataPoint")((dataPoint, options) => {
@@ -482,12 +491,12 @@ const queryLayerConfig = (tag, config = queryConfig()) => Layer.effect(tag, Effe
482
491
  return yield* makeQueryClient(definition);
483
492
  }));
484
493
  const layerFetchConfig = (tag, config = queryConfig()) => queryLayerConfig(tag, config).pipe(Layer.provide(FetchHttpClient.layer));
485
- const layer$16 = (tag, definition) => layer$19(tag, definition.binding, isAnalyticsEngineDataset, makeClient$13(definition, definition.write), { expected: expectedAnalyticsEngineDataset });
486
- const make$16 = (id) => Tag$14()(id);
494
+ const layer$14 = (tag, definition) => layer$17(tag, definition.binding, isAnalyticsEngineDataset, makeClient$11(definition, definition.write), { expected: expectedAnalyticsEngineDataset });
495
+ const make$12 = (id) => Tag$11()(id);
487
496
  const makeQuery = (id) => QueryTag()(id);
488
- const Tag$14 = () => (id) => {
497
+ const Tag$11 = () => (id) => {
489
498
  const tag = Context.Service()(id);
490
- const makeLayer = (definition) => layer$16(tag, definition);
499
+ const makeLayer = (definition) => layer$14(tag, definition);
491
500
  return Object.assign(tag, {
492
501
  id,
493
502
  layer: makeLayer
@@ -511,11 +520,11 @@ const QueryTag = () => (id) => {
511
520
  //#region src/BrowserRendering.ts
512
521
  var BrowserRendering_exports = /* @__PURE__ */ __exportAll({
513
522
  BrowserRenderingOperationError: () => BrowserRenderingOperationError,
514
- Tag: () => Tag$13,
523
+ Tag: () => Tag$10,
515
524
  isBrowserRenderingBinding: () => isBrowserRenderingBinding,
516
- layer: () => layer$15,
517
- make: () => make$15,
518
- makeClient: () => makeClient$12
525
+ layer: () => layer$13,
526
+ make: () => make$11,
527
+ makeClient: () => makeClient$10
519
528
  });
520
529
  const expectedBrowserRenderingBinding = "Browser Rendering binding resource";
521
530
  var BrowserRenderingOperationError = class extends Data.TaggedError("BrowserRenderingOperationError") {
@@ -564,17 +573,17 @@ const wrapBrowser = (binding, browser) => ({
564
573
  disconnect: browser.disconnect === void 0 ? Effect.void : tryBrowserRenderingSync(binding, "disconnect", () => browser.disconnect())
565
574
  });
566
575
  const isBrowserRenderingBinding = (value) => Predicate.isObjectOrArray(value) || Predicate.isFunction(value);
567
- const makeClient$12 = (definition) => (binding) => ({
576
+ const makeClient$10 = (definition) => (binding) => ({
568
577
  definition,
569
578
  launchWith: (launch, options) => tryBrowserRenderingPromise(definition.binding, "launch", () => launch(binding, options)).pipe(Effect.map((browser) => wrapBrowser(definition.binding, browser)), Effect.withSpan("BrowserRendering.launchWith")),
570
579
  connectWith: (connect, options) => tryBrowserRenderingPromise(definition.binding, "connect", () => connect(binding, options)).pipe(Effect.map((browser) => wrapBrowser(definition.binding, browser)), Effect.withSpan("BrowserRendering.connectWith")),
571
580
  rawUnsafe: Effect.succeed(binding)
572
581
  });
573
- const layer$15 = (tag, definition) => layer$19(tag, definition.binding, isBrowserRenderingBinding, makeClient$12(definition), { expected: expectedBrowserRenderingBinding });
574
- const make$15 = (id) => Tag$13()(id);
575
- const Tag$13 = () => (id) => {
582
+ const layer$13 = (tag, definition) => layer$17(tag, definition.binding, isBrowserRenderingBinding, makeClient$10(definition), { expected: expectedBrowserRenderingBinding });
583
+ const make$11 = (id) => Tag$10()(id);
584
+ const Tag$10 = () => (id) => {
576
585
  const tag = Context.Service()(id);
577
- const makeLayer = (definition) => layer$15(tag, definition);
586
+ const makeLayer = (definition) => layer$13(tag, definition);
578
587
  return Object.assign(tag, {
579
588
  id,
580
589
  layer: makeLayer
@@ -585,10 +594,10 @@ const Tag$13 = () => (id) => {
585
594
  var Cache_exports = /* @__PURE__ */ __exportAll({
586
595
  CacheOperationError: () => CacheOperationError,
587
596
  CacheStorage: () => CacheStorage,
588
- layer: () => layer$14,
597
+ layer: () => layer$12,
589
598
  layerFrom: () => layerFrom,
590
599
  makeCacheClient: () => makeCacheClient,
591
- makeClient: () => makeClient$11
600
+ makeClient: () => makeClient$9
592
601
  });
593
602
  var CacheOperationError = class extends Data.TaggedError("CacheOperationError") {
594
603
  get message() {
@@ -616,22 +625,23 @@ const makeCacheClient = (cache, name = "default") => ({
616
625
  delete: Effect.fn("Cache.delete", spanOptions$2(name, "delete"))((request, options) => tryCachePromise(name, "delete", () => cache.delete(request, options))),
617
626
  rawUnsafe: Effect.succeed(cache)
618
627
  });
619
- const makeClient$11 = (storage) => ({
628
+ const makeClient$9 = (storage) => ({
620
629
  default: makeCacheClient(storage.default),
621
630
  open: (name) => tryCachePromise(name, "open", () => storage.open(name)).pipe(Effect.map((cache) => makeCacheClient(cache, name)), Effect.withSpan("Cache.open", spanOptions$2(name, "open"))),
622
631
  rawUnsafe: Effect.succeed(storage)
623
632
  });
624
- const layerFrom = (storage) => Layer.succeed(CacheStorage, makeClient$11(storage));
625
- const layer$14 = Layer.sync(CacheStorage, () => makeClient$11(caches));
633
+ const layerFrom = (storage) => Layer.succeed(CacheStorage, makeClient$9(storage));
634
+ const layer$12 = Layer.sync(CacheStorage, () => makeClient$9(caches));
626
635
  //#endregion
627
636
  //#region src/CloudflareOtlp.ts
628
637
  /**
629
- * Worker fetch/RPC and Durable Object alarm/RPC handlers schedule a best-effort
630
- * flusher. It settles within two seconds; queues and other lifecycles must
631
- * flush explicitly. Failures are ignored so telemetry cannot fail user events.
638
+ * Worker fetch/queue/RPC and Durable Object alarm/RPC handlers schedule a
639
+ * best-effort flusher. It settles within two seconds; other lifecycles must
640
+ * flush explicitly. Scheduled flush failures cannot fail user events. Exporter
641
+ * layer finalizers run separately and follow their configured shutdown timeout.
632
642
  */
633
643
  var CloudflareOtlp_exports = /* @__PURE__ */ __exportAll({
634
- layer: () => layer$13,
644
+ layer: () => layer$11,
635
645
  layerDurableObject: () => layerDurableObject,
636
646
  layerJson: () => layerJson,
637
647
  layerProtobuf: () => layerProtobuf,
@@ -697,14 +707,14 @@ const makeLayer = (options = {}, runtimeAttributes = {}) => {
697
707
  * The layer provides {@link OtlpExporter.Flusher} for draining buffered
698
708
  * telemetry before the isolate freezes.
699
709
  */
700
- const layer$13 = (options = {}) => makeLayer(options);
710
+ const layer$11 = (options = {}) => makeLayer(options);
701
711
  /** Base OTLP telemetry layer forced to JSON serialization. */
702
- const layerJson = (options = {}) => layer$13({
712
+ const layerJson = (options = {}) => layer$11({
703
713
  ...options,
704
714
  serialization: "json"
705
715
  });
706
716
  /** Base OTLP telemetry layer forced to protobuf serialization. */
707
- const layerProtobuf = (options = {}) => layer$13({
717
+ const layerProtobuf = (options = {}) => layer$11({
708
718
  ...options,
709
719
  serialization: "protobuf"
710
720
  });
@@ -713,6 +723,8 @@ const layerProtobuf = (options = {}) => layer$13({
713
723
  *
714
724
  * Provide this layer at runtime scope for long-lived metrics aggregation, or at
715
725
  * handler scope when traces/logs should flush as the Cloudflare event finishes.
726
+ * A handler-scoped exporter can delay scope closure while its own finalizer
727
+ * flushes; the two-second background flush limit does not bound layer shutdown.
716
728
  */
717
729
  const layerWorker = (options = {}) => makeLayer(options, {
718
730
  "cloudflare.resource_type": "worker",
@@ -736,11 +748,11 @@ var ContainerNamespace_exports = /* @__PURE__ */ __exportAll({
736
748
  ContainerNamespace: () => ContainerNamespace,
737
749
  ContainerOperationError: () => ContainerOperationError,
738
750
  ContainerState: () => ContainerState,
739
- Tag: () => Tag$12,
751
+ Tag: () => Tag$9,
740
752
  isContainerNamespaceResource: () => isContainerNamespaceResource,
741
- layer: () => layer$12,
742
- make: () => make$14,
743
- makeClient: () => makeClient$10
753
+ layer: () => layer$10,
754
+ make: () => make$10,
755
+ makeClient: () => makeClient$8
744
756
  });
745
757
  const expectedContainerNamespace = "Container namespace binding with getByName()";
746
758
  /** Serializable state reported by a Cloudflare Container instance. */
@@ -816,7 +828,7 @@ const makeInstanceClient = (definition, instance, stub) => {
816
828
  };
817
829
  };
818
830
  const isContainerNamespaceResource = (value) => Predicate.hasProperty(value, "getByName") && Predicate.isFunction(value.getByName);
819
- const makeClient$10 = (definition) => (namespace) => {
831
+ const makeClient$8 = (definition) => (namespace) => {
820
832
  const getByName = (name, options) => Effect.try({
821
833
  try: () => makeInstanceClient(definition, name, namespace.getByName(name, options)),
822
834
  catch: (cause) => new ContainerOperationError({
@@ -852,11 +864,11 @@ const makeClient$10 = (definition) => (namespace) => {
852
864
  rawUnsafe: Effect.succeed(namespace)
853
865
  };
854
866
  };
855
- const layer$12 = (tag, definition) => layer$19(tag, definition.binding, (value) => isContainerNamespaceResource(value), makeClient$10(definition), { expected: expectedContainerNamespace });
856
- const make$14 = (id) => Tag$12()(id);
857
- const Tag$12 = () => (id) => {
867
+ const layer$10 = (tag, definition) => layer$17(tag, definition.binding, (value) => isContainerNamespaceResource(value), makeClient$8(definition), { expected: expectedContainerNamespace });
868
+ const make$10 = (id) => Tag$9()(id);
869
+ const Tag$9 = () => (id) => {
858
870
  const tag = Context.Service()(`effect-cf/Container/${id}`);
859
- const makeLayer = (definition) => layer$12(tag, definition);
871
+ const makeLayer = (definition) => layer$10(tag, definition);
860
872
  const getByName = Effect.fnUntraced(function* (name, options) {
861
873
  return yield* (yield* tag).getByName(name, options);
862
874
  });
@@ -885,19 +897,19 @@ const Tag$12 = () => (id) => {
885
897
  rawUnsafe
886
898
  });
887
899
  };
888
- const ContainerNamespace = Tag$12;
900
+ const ContainerNamespace = Tag$9;
889
901
  //#endregion
890
902
  //#region src/D1.ts
891
903
  var D1_exports = /* @__PURE__ */ __exportAll({
892
- Service: () => Service$1,
893
- make: () => make$13
904
+ Service: () => Service,
905
+ make: () => make$9
894
906
  });
895
- const TypeId$2 = "~effect-cf/D1";
907
+ const TypeId$1 = "~effect-cf/D1";
896
908
  const expectedD1Database = "D1 database binding with prepare(), batch(), and exec()";
897
909
  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);
898
- const make$13 = (id, definition) => Service$1()(id, definition);
899
- const Service$1 = () => (id, definition) => {
900
- const tag = Service$2()(id, definition.binding, isD1Database, void 0, { expected: expectedD1Database });
910
+ const make$9 = (id, definition) => Service()(id, definition);
911
+ const Service = () => (id, definition) => {
912
+ const tag = Service$1()(id, definition.binding, isD1Database, void 0, { expected: expectedD1Database });
901
913
  const sqlLayer = (options) => Layer.unwrap(Effect.gen(function* () {
902
914
  const db = yield* tag;
903
915
  return D1Client.layer({
@@ -906,874 +918,11 @@ const Service$1 = () => (id, definition) => {
906
918
  });
907
919
  })).pipe(Layer.provide(tag.layer));
908
920
  return Object.assign(tag, {
909
- [TypeId$2]: TypeId$2,
910
- definition,
911
- sqlLayer
912
- });
913
- };
914
- //#endregion
915
- //#region src/QueueBinding.ts
916
- var QueueBinding_exports = /* @__PURE__ */ __exportAll({
917
- QueueOperationError: () => QueueOperationError,
918
- isQueue: () => isQueue,
919
- layer: () => layer$11,
920
- makeClient: () => makeClient$9
921
- });
922
- const expectedQueueProducer = "Queue producer binding with send(); optional sendBatch()/metrics()";
923
- var QueueOperationError = class extends Data.TaggedError("QueueOperationError") {};
924
- const tryQueuePromise = (binding, operation, evaluate) => Effect.tryPromise({
925
- try: evaluate,
926
- catch: (cause) => new QueueOperationError({
927
- binding,
928
- operation,
929
- cause,
930
- message: `Cloudflare queue binding "${binding}" operation "${operation}" failed`
931
- })
932
- });
933
- const isQueue = (value) => Predicate.hasProperty(value, "send") && Predicate.isFunction(value.send);
934
- const makeClient$9 = (definition) => {
935
- const encodeMessage = Schema.encodeEffect(definition.message);
936
- return (queue) => ({
937
- send: Effect.fn("QueueBinding.send", { attributes: {
938
- binding: definition.binding,
939
- operation: "send"
940
- } })(function* (message, options) {
941
- const encoded = yield* encodeMessage(message);
942
- yield* tryQueuePromise(definition.binding, "send", () => queue.send(encoded, options));
943
- }),
944
- sendBatch: Effect.fn("QueueBinding.sendBatch", { attributes: {
945
- binding: definition.binding,
946
- operation: "sendBatch"
947
- } })(function* (messages, options) {
948
- const encodedMessages = [];
949
- for (const message of messages) encodedMessages.push({
950
- ...message,
951
- body: yield* encodeMessage(message.body)
952
- });
953
- const sendBatch = queue.sendBatch;
954
- if (sendBatch === void 0) return yield* new QueueOperationError({
955
- binding: definition.binding,
956
- operation: "sendBatch",
957
- cause: /* @__PURE__ */ new Error(`Queue binding "${definition.binding}" does not provide sendBatch()`),
958
- message: `Cloudflare queue binding "${definition.binding}" does not provide sendBatch()`
959
- });
960
- yield* tryQueuePromise(definition.binding, "sendBatch", () => sendBatch.call(queue, encodedMessages, options));
961
- }),
962
- metrics: () => {
963
- const metrics = queue.metrics;
964
- if (metrics === void 0) return Effect.fail(new QueueOperationError({
965
- binding: definition.binding,
966
- operation: "metrics",
967
- cause: /* @__PURE__ */ new Error(`Queue binding "${definition.binding}" does not provide metrics()`),
968
- message: `Cloudflare queue binding "${definition.binding}" does not provide metrics()`
969
- }));
970
- return tryQueuePromise(definition.binding, "metrics", () => metrics.call(queue));
971
- },
972
- rawUnsafe: Effect.succeed(queue)
973
- });
974
- };
975
- const layer$11 = (tag, definition) => layer$19(tag, definition.binding, (value) => isQueue(value), makeClient$9(definition), { expected: expectedQueueProducer });
976
- //#endregion
977
- //#region src/QueueDefinition.ts
978
- var QueueDefinition_exports = /* @__PURE__ */ __exportAll({
979
- Queue: () => Queue$1,
980
- Tag: () => Tag$11,
981
- implement: () => implement$5,
982
- make: () => make$12
983
- });
984
- const makeDefinition$4 = (id, definition) => {
985
- const queueDefinition = {
986
- id,
987
- message: definition.message
988
- };
989
- return Object.assign(queueDefinition, { make: (layer, options) => make$9(layer, {
990
- ...options,
991
- queue: wrapHandler$1(queueDefinition, options.queue)
992
- }) });
993
- };
994
- const make$12 = (id, definition) => Tag$11()(id, definition);
995
- const Tag$11 = () => (id, definition) => {
996
- const queueDefinition = makeDefinition$4(id, definition);
997
- const tag = Context.Service()(`effect-cf/Queue/${id}`);
998
- const layer = (binding) => layer$11(tag, {
999
- ...binding,
1000
- message: definition.message
1001
- });
1002
- const send = Effect.fnUntraced(function* (message, options) {
1003
- yield* (yield* tag).send(message, options);
1004
- });
1005
- const sendBatch = Effect.fnUntraced(function* (messages, options) {
1006
- yield* (yield* tag).sendBatch(messages, options);
1007
- });
1008
- const metrics = Effect.fnUntraced(function* () {
1009
- return yield* (yield* tag).metrics();
1010
- });
1011
- const rawUnsafe = Effect.flatMap(tag, (queue) => queue.rawUnsafe);
1012
- return Object.assign(tag, {
1013
- id: queueDefinition.id,
1014
- message: queueDefinition.message,
1015
- make: queueDefinition.make,
1016
- layer,
1017
- send,
1018
- sendBatch,
1019
- metrics,
1020
- rawUnsafe
1021
- });
1022
- };
1023
- const Queue$1 = Tag$11;
1024
- const wrapHandler$1 = (definition, handler) => {
1025
- const decodeBody = Schema.decodeUnknownEffect(definition.message);
1026
- return Effect.fnUntraced(function* (batch) {
1027
- yield* handler(yield* decodeBatch(batch.raw, decodeBody));
1028
- });
1029
- };
1030
- const implement$5 = (_definition, handler) => handler;
1031
- //#endregion
1032
- //#region src/Queue.ts
1033
- var Queue_exports = /* @__PURE__ */ __exportAll({
1034
- QueueMessageDecodeError: () => QueueMessageDecodeError,
1035
- Tag: () => Tag$10,
1036
- decodeBatch: () => decodeBatch,
1037
- fromMessage: () => fromMessage,
1038
- fromMessageBatch: () => fromMessageBatch,
1039
- implement: () => implement$4
1040
- });
1041
- var QueueMessageDecodeError = class extends Data.TaggedError("QueueMessageDecodeError") {
1042
- get message() {
1043
- return `Queue "${this.queue}" failed to decode message "${this.messageId}" at index ${this.index}: ${causeMessage(this.cause)}`;
1044
- }
1045
- };
1046
- const fromMessage = (message, body) => ({
1047
- raw: message,
1048
- id: message.id,
1049
- timestamp: message.timestamp,
1050
- body,
1051
- attempts: message.attempts,
1052
- ack: Effect.sync(() => message.ack()),
1053
- retry: (options) => Effect.sync(() => message.retry(options))
1054
- });
1055
- const fromMessageBatch = (batch, messages) => ({
1056
- raw: batch,
1057
- messages,
1058
- queue: batch.queue,
1059
- metadata: batch.metadata,
1060
- ackAll: Effect.sync(() => batch.ackAll()),
1061
- retryAll: (options) => Effect.sync(() => batch.retryAll(options))
1062
- });
1063
- const decodeBatch = (batch, decodeBody) => Effect.gen(function* () {
1064
- const messages = [];
1065
- for (let index = 0; index < batch.messages.length; index++) {
1066
- const message = batch.messages[index];
1067
- const body = yield* decodeBody(message.body).pipe(Effect.mapError((cause) => new QueueMessageDecodeError({
1068
- queue: batch.queue,
1069
- messageId: message.id,
1070
- index,
1071
- cause
1072
- })));
1073
- messages.push(fromMessage(message, body));
1074
- }
1075
- return fromMessageBatch(batch, messages);
1076
- });
1077
- const Tag$10 = Tag$11;
1078
- const implement$4 = implement$5;
1079
- //#endregion
1080
- //#region src/RpcDefinition.ts
1081
- var RpcDefinition_exports = /* @__PURE__ */ __exportAll({
1082
- RpcArgumentCountError: () => RpcArgumentCountError,
1083
- RpcArgumentDecodeError: () => RpcArgumentDecodeError,
1084
- RpcArgumentEncodeError: () => RpcArgumentEncodeError,
1085
- RpcReservedMethodNameError: () => RpcReservedMethodNameError,
1086
- RpcSuccessDecodeError: () => RpcSuccessDecodeError,
1087
- RpcSuccessEncodeError: () => RpcSuccessEncodeError,
1088
- assertNoReservedMethods: () => assertNoReservedMethods,
1089
- decodeArgs: () => decodeArgs,
1090
- decodeSuccess: () => decodeSuccess,
1091
- decodeWireError: () => decodeWireError,
1092
- encodeArgs: () => encodeArgs,
1093
- encodeSuccess: () => encodeSuccess,
1094
- encodeWireError: () => encodeWireError,
1095
- isWireError: () => isWireError,
1096
- make: () => make$11,
1097
- method: () => method$2,
1098
- reservedMethodNames: () => reservedMethodNames$4
1099
- });
1100
- var RpcReservedMethodNameError = class extends Data.TaggedError("RpcReservedMethodNameError") {
1101
- get message() {
1102
- return `${this.definition} RPC method "${this.method}" is reserved by Cloudflare Workers RPC`;
1103
- }
1104
- };
1105
- var RpcArgumentCountError = class extends Schema.TaggedError()("RpcArgumentCountError", {
1106
- definition: Schema.String,
1107
- method: Schema.String,
1108
- expected: Schema.Number,
1109
- actual: Schema.Number
1110
- }) {
1111
- get message() {
1112
- return `${this.definition} RPC method "${this.method}" expected ${this.expected} arguments but received ${this.actual}`;
1113
- }
1114
- };
1115
- var RpcArgumentDecodeError = class extends Schema.TaggedError()("RpcArgumentDecodeError", {
1116
- definition: Schema.String,
1117
- method: Schema.String,
1118
- cause: Schema.Defect()
1119
- }) {
1120
- get message() {
1121
- return `${this.definition} RPC method "${this.method}" argument decode failed: ${causeMessage(this.cause)}`;
1122
- }
1123
- };
1124
- var RpcArgumentEncodeError = class extends Data.TaggedError("RpcArgumentEncodeError") {
1125
- get message() {
1126
- return `${this.definition} RPC method "${this.method}" argument encode failed: ${causeMessage(this.cause)}`;
1127
- }
1128
- };
1129
- var RpcSuccessDecodeError = class extends Data.TaggedError("RpcSuccessDecodeError") {
1130
- get message() {
1131
- return `${this.definition} RPC method "${this.method}" success decode failed: ${causeMessage(this.cause)}`;
1132
- }
1133
- };
1134
- var RpcSuccessEncodeError = class extends Schema.TaggedError()("RpcSuccessEncodeError", {
1135
- definition: Schema.String,
1136
- method: Schema.String,
1137
- cause: Schema.Defect()
1138
- }) {
1139
- get message() {
1140
- return `${this.definition} RPC method "${this.method}" success encode failed: ${causeMessage(this.cause)}`;
1141
- }
1142
- };
1143
- const WireErrorSchema = Schema.Union([
1144
- RpcArgumentCountError,
1145
- RpcArgumentDecodeError,
1146
- RpcSuccessEncodeError
1147
- ]);
1148
- const wireErrorKey = "effect-cf/RpcDefinition/wireError";
1149
- const isWireError = (error) => error instanceof RpcArgumentCountError || error instanceof RpcArgumentDecodeError || error instanceof RpcSuccessEncodeError;
1150
- /**
1151
- * Encodes package RPC errors into a plain `Error` envelope so their tags
1152
- * survive Cloudflare RPC serialization, which drops custom error properties.
1153
- */
1154
- const encodeWireError = (error) => {
1155
- if (!isWireError(error)) return error;
1156
- try {
1157
- return new Error(JSON.stringify({ [wireErrorKey]: Schema.encodeSync(WireErrorSchema)(error) }));
1158
- } catch {
1159
- return error;
1160
- }
1161
- };
1162
- const decodeWireError = (cause) => {
1163
- if (!(cause instanceof Error)) return cause;
1164
- try {
1165
- const parsed = Schema.decodeUnknownSync(Schema.Unknown)(JSON.parse(cause.message));
1166
- if (!Predicate.hasProperty(parsed, wireErrorKey)) return cause;
1167
- return Schema.decodeUnknownSync(WireErrorSchema)(parsed[wireErrorKey]);
1168
- } catch {
1169
- return cause;
1170
- }
1171
- };
1172
- const reservedMethodNames$4 = /* @__PURE__ */ new Set([
1173
- "constructor",
1174
- "fetch",
1175
- "connect",
1176
- "alarm",
1177
- "webSocketMessage",
1178
- "webSocketClose",
1179
- "webSocketError",
1180
- "then",
1181
- "dup",
1182
- "dispose",
1183
- "serialize",
1184
- "deserialize"
1185
- ]);
1186
- /**
1187
- * Workers RPC structured-clones every value that crosses an isolate boundary
1188
- * and rejects class instances. Declaration schemas such as `Schema.Result`
1189
- * keep their container instance in their `Encoded` form, so the declared
1190
- * schemas are lowered to their canonical JSON codec before touching the wire.
1191
- */
1192
- const wireCodec = (schema) => Schema.toCodecJson(schema);
1193
- const assertNoReservedMethods = (target, methods, reserved) => {
1194
- for (const method of Object.keys(methods)) if (reserved.has(method)) throw new RpcReservedMethodNameError({
1195
- definition: target,
1196
- method
1197
- });
1198
- };
1199
- function method$2(definition) {
1200
- return {
1201
- args: definition.args ?? [],
1202
- success: definition.success
1203
- };
1204
- }
1205
- const decodeArgs = Effect.fnUntraced(function* (definition, methodName, args) {
1206
- const methodDefinition = definition.methods[methodName];
1207
- if (args.length !== methodDefinition.args.length) return yield* new RpcArgumentCountError({
1208
- definition: definition.id,
1209
- method: methodName,
1210
- expected: methodDefinition.args.length,
1211
- actual: args.length
1212
- });
1213
- return yield* Schema.decodeUnknownEffect(wireCodec(Schema.Tuple(methodDefinition.args)))(args).pipe(Effect.mapError((cause) => new RpcArgumentDecodeError({
1214
- definition: definition.id,
1215
- method: methodName,
1216
- cause
1217
- })));
1218
- });
1219
- const encodeArgs = Effect.fnUntraced(function* (definition, methodName, args) {
1220
- const methodDefinition = definition.methods[methodName];
1221
- if (args.length !== methodDefinition.args.length) return yield* new RpcArgumentCountError({
1222
- definition: definition.id,
1223
- method: methodName,
1224
- expected: methodDefinition.args.length,
1225
- actual: args.length
1226
- });
1227
- return yield* Schema.encodeUnknownEffect(wireCodec(Schema.Tuple(methodDefinition.args)))(args).pipe(Effect.mapError((cause) => new RpcArgumentEncodeError({
1228
- definition: definition.id,
1229
- method: methodName,
1230
- cause
1231
- })));
1232
- });
1233
- const encodeSuccess = (definition, methodName, value) => {
1234
- const methodDefinition = definition.methods[methodName];
1235
- return Schema.encodeUnknownEffect(wireCodec(methodDefinition.success))(value).pipe(Effect.mapError((cause) => new RpcSuccessEncodeError({
1236
- definition: definition.id,
1237
- method: methodName,
1238
- cause
1239
- })));
1240
- };
1241
- const decodeSuccess = (definition, methodName, value) => {
1242
- const methodDefinition = definition.methods[methodName];
1243
- return Schema.decodeUnknownEffect(wireCodec(methodDefinition.success))(value).pipe(Effect.mapError((cause) => new RpcSuccessDecodeError({
1244
- definition: definition.id,
1245
- method: methodName,
1246
- cause
1247
- })));
1248
- };
1249
- const make$11 = (id, methods) => {
1250
- assertNoReservedMethods(id, methods, reservedMethodNames$4);
1251
- return {
1252
- id,
1253
- methods
1254
- };
1255
- };
1256
- //#endregion
1257
- //#region src/RpcTracing.ts
1258
- var RpcTracing_exports = /* @__PURE__ */ __exportAll({
1259
- RpcTraceContext: () => RpcTraceContext,
1260
- withRpcClientSpan: () => withRpcClientSpan,
1261
- withRpcServerSpan: () => withRpcServerSpan,
1262
- withRpcTraceContext: () => withRpcTraceContext
1263
- });
1264
- /**
1265
- * Live native RPC metadata. Opted-in receivers reserve a valid trailing value
1266
- * with this tag for transport context; do not use it as a final domain argument.
1267
- * Never store this in durable messages or envelopes.
1268
- */
1269
- const RpcTraceContext = Schema.Struct({
1270
- _tag: Schema.Literal("effect-cf/RpcTraceContext/v1"),
1271
- traceId: Schema.String.check(Schema.isPattern(/^(?!0{32}$)[0-9a-f]{32}$/)),
1272
- spanId: Schema.String.check(Schema.isPattern(/^(?!0{16}$)[0-9a-f]{16}$/)),
1273
- sampled: Schema.Boolean
1274
- });
1275
- const isRpcTraceContext$1 = Schema.is(RpcTraceContext);
1276
- /**
1277
- * Appends the current live parent only for a receiver that has opted in.
1278
- * Call this inside the CLIENT span, immediately before the native invocation.
1279
- * With no valid propagating parent, the original argument array is returned.
1280
- */
1281
- const withRpcTraceContext = Effect.fnUntraced(function* (args) {
1282
- if (yield* Tracer.DisablePropagation) return args;
1283
- const parent = yield* Effect.serviceOption(Tracer.ParentSpan);
1284
- if (Option.isNone(parent) || Context.get(parent.value.annotations, Tracer.DisablePropagation)) return args;
1285
- const context = {
1286
- _tag: "effect-cf/RpcTraceContext/v1",
1287
- traceId: parent.value.traceId,
1288
- spanId: parent.value.spanId,
1289
- sampled: parent.value.sampled
1290
- };
1291
- return isRpcTraceContext$1(context) ? [...args, context] : args;
1292
- });
1293
- const attributes = (service, method) => ({
1294
- "sentry.op": "rpc",
1295
- "rpc.system.name": "cloudflare",
1296
- "rpc.method": `${service}/${method}`,
1297
- "server.address": service
1298
- });
1299
- const withRpcSpan = (effect, service, method, options) => Effect.useSpan(`${service}/${method}`, {
1300
- ...options,
1301
- attributes: attributes(service, method)
1302
- }, (span) => effect.pipe(Effect.withParentSpan(span), Effect.onExit((exit) => {
1303
- if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause) || span.status._tag === "Ended") return Effect.void;
1304
- return Effect.gen(function* () {
1305
- const endTime = (yield* References.TracerTimingEnabled) ? yield* Clock.currentTimeNanos : 0n;
1306
- span.attribute("error.type", "_OTHER");
1307
- span.end(endTime, Exit.fail("RPC failed"));
1308
- });
1309
- })));
1310
- /** Wrap the whole call, including native result resolution and success decoding. */
1311
- const withRpcClientSpan = (effect, binding, method) => withRpcSpan(effect, binding, method, { kind: "client" });
1312
- /**
1313
- * Optional application instrumentation for the entire receiver effect.
1314
- * Use in a RunSymbol override to include argument decode, handler and encode.
1315
- * Records stable service/method attributes and failure status, not argument or
1316
- * error payloads. The original typed failure still propagates to the caller.
1317
- */
1318
- const withRpcServerSpan = (effect, invocation) => withRpcSpan(effect, invocation.service, invocation.method, {
1319
- kind: "server",
1320
- parent: invocation.parent === void 0 ? void 0 : Tracer.externalSpan(invocation.parent)
1321
- });
1322
- //#endregion
1323
- //#region src/internal/RpcInvocation.ts
1324
- /** Scoped to the incoming event effect, never the instance runtime or storage. */
1325
- var CurrentInvocation = class extends Context.Service()("effect-cf/internal/RpcInvocation") {};
1326
- const recordDecodedArgs = (args) => Effect.map(Effect.serviceOption(CurrentInvocation), (invocation) => {
1327
- if (Option.isSome(invocation)) invocation.value.decodedArgs = args;
1328
- });
1329
- const invokeWithReceiver = (value, receiver, args) => {
1330
- return Function.prototype.apply.call(value, receiver, args);
1331
- };
1332
- const lookupRpcMethod = (target, method, makeError) => Effect.try({
1333
- try: () => {
1334
- if (!Predicate.isObjectKeyword(target)) throw new TypeError(`RPC target is not object-like`);
1335
- const receiver = target;
1336
- const value = receiver[method];
1337
- if (!Predicate.isFunction(value)) throw new TypeError(`RPC method "${String(method)}" is not callable`);
1338
- const callable = value;
1339
- return (...args) => invokeWithReceiver(callable, receiver, args);
1340
- },
1341
- catch: makeError
1342
- });
1343
- const invokeRpcMethod = Effect.fnUntraced(function* (target, method, args, makeError) {
1344
- const fn = yield* lookupRpcMethod(target, method, makeError);
1345
- return yield* Effect.try({
1346
- try: () => fn(...args),
1347
- catch: makeError
1348
- });
1349
- });
1350
- //#endregion
1351
- //#region src/internal/Entrypoint.ts
1352
- const isRpcTraceContext = Schema.is(RpcTraceContext);
1353
- const invokeEntrypointRpcMethod = (self, method, args, run, onExit, service, key, rpcTracing) => {
1354
- const last = args.at(-1);
1355
- const parent = rpcTracing !== void 0 && isRpcTraceContext(last) ? last : void 0;
1356
- const handlerArgs = parent === void 0 ? args : args.slice(0, -1);
1357
- const invocation = {
1358
- service: rpcTracing?.service ?? service,
1359
- method: key,
1360
- args: handlerArgs,
1361
- parent
1362
- };
1363
- const handler = Effect.suspend(() => method(...handlerArgs)).pipe(Effect.provideService(CurrentInvocation, invocation), Effect.mapError(encodeWireError));
1364
- return run(self, onExit === void 0 ? handler : handler.pipe(Effect.onExit(() => onExit(self))), invocation);
1365
- };
1366
- const provideEntrypointServices = (layer, services) => layer.pipe(Layer.provideMerge(services));
1367
- const defineEntrypointRpcMethods = (target, prototype, rpc, reservedMethodNames, run, onExit, rpcTracing) => {
1368
- const methods = rpc ?? {};
1369
- assertNoReservedMethods(target, methods, reservedMethodNames);
1370
- for (const [key, method] of Object.entries(methods)) Object.defineProperty(prototype, key, {
1371
- enumerable: true,
1372
- value(...args) {
1373
- return invokeEntrypointRpcMethod(this, method, args, run, onExit, target, key, rpcTracing);
1374
- }
1375
- });
1376
- };
1377
- const assumeEntrypointClass = (entrypoint) => {
1378
- return entrypoint;
1379
- };
1380
- //#endregion
1381
- //#region src/internal/Runtime.ts
1382
- /**
1383
- * Assembles the shared `ManagedRuntime` used by the Cloudflare entrypoint
1384
- * classes (Worker, Durable Object, Workflow).
1385
- *
1386
- * The entrypoint-specific services are merged with the env-backed
1387
- * `ConfigProvider` and `WorkerEnvironment`, then provided to the user-supplied
1388
- * layer so the resulting runtime satisfies both the user services and the
1389
- * platform services.
1390
- */
1391
- const makeEntrypointRuntime = (layer, env, services) => {
1392
- const entrypointServices = Layer.mergeAll(services, ConfigProvider.layer(WorkerConfig.providerFromEnv(env)), Layer.succeed(WorkerEnvironment, env));
1393
- return ManagedRuntime.make(provideEntrypointServices(layer, entrypointServices));
1394
- };
1395
- function runEventPromise(...args) {
1396
- const [runtime, effect, eventLayer, parent] = args;
1397
- if (eventLayer === void 0) {
1398
- const event = Effect.scoped(effect);
1399
- return runtime.runPromise(parent === void 0 ? event : Effect.withParentSpan(event, parent));
1400
- }
1401
- const event = Effect.scoped(effect.pipe(Effect.provide(eventLayer, { local: true })));
1402
- return runtime.runPromise(parent === void 0 ? event : Effect.withParentSpan(event, parent));
1403
- }
1404
- //#endregion
1405
- //#region src/internal/Telemetry.ts
1406
- /** Maximum event lifetime spent on an internally scheduled telemetry flush. */
1407
- const scheduledFlushTimeout = "2 seconds";
1408
- /**
1409
- * Schedules a configured OTLP flusher through the current Cloudflare event.
1410
- *
1411
- * The handed-off effect is best-effort: it settles within two seconds and
1412
- * silently absorbs every failure cause so telemetry cannot extend or fail the
1413
- * user event, or recursively log through an unhealthy exporter.
1414
- */
1415
- const scheduleTelemetryFlush$2 = (waitUntil) => Effect.gen(function* () {
1416
- const flusher = yield* Effect.serviceOption(OtlpExporter.Flusher);
1417
- if (Option.isNone(flusher)) return;
1418
- yield* waitUntil(flusher.value.flush.pipe(Effect.timeoutOption(scheduledFlushTimeout), Effect.ignoreCause, Effect.asVoid));
1419
- }).pipe(Effect.ignoreCause);
1420
- //#endregion
1421
- //#region src/Rpc.ts
1422
- var Rpc_exports = /* @__PURE__ */ __exportAll({
1423
- RpcStub: () => RpcStub,
1424
- RpcTarget: () => RpcTarget,
1425
- dispose: () => dispose,
1426
- isDisposable: () => isDisposable,
1427
- resolve: () => resolve,
1428
- scoped: () => scoped
1429
- });
1430
- const isDisposable = (value) => Predicate.hasProperty(value, Symbol.dispose) && Predicate.isFunction(value[Symbol.dispose]);
1431
- const dispose = (value) => Effect.sync(() => {
1432
- if (isDisposable(value)) value[Symbol.dispose]();
1433
- });
1434
- const resolve = (value) => Predicate.isPromiseLike(value) ? Effect.tryPromise({
1435
- try: () => Promise.resolve(value),
1436
- catch: (cause) => decodeWireError(cause)
1437
- }) : Effect.sync(() => {
1438
- return value;
1439
- });
1440
- const scoped = (value) => Effect.acquireRelease(resolve(value), (resolved) => dispose(resolved));
1441
- //#endregion
1442
- //#region src/ServiceBinding.ts
1443
- var ServiceBinding_exports = /* @__PURE__ */ __exportAll({
1444
- Service: () => Service,
1445
- ServiceBindingFetchError: () => ServiceBindingFetchError,
1446
- ServiceBindingRpcError: () => ServiceBindingRpcError,
1447
- isServiceBindingClient: () => isServiceBindingClient,
1448
- layer: () => layer$10,
1449
- makeClient: () => makeClient$8,
1450
- makeDirectMethods: () => makeDirectMethods$1
1451
- });
1452
- const TypeId$1 = "effect-cf/ServiceBinding";
1453
- const expectedServiceBinding = "Worker service binding with fetch()";
1454
- /**
1455
- * Failure raised when calling `fetch` on a service binding.
1456
- */
1457
- var ServiceBindingFetchError = class extends Data.TaggedError("ServiceBindingFetchError") {
1458
- get message() {
1459
- return `Service binding "${this.binding}" fetch failed: ${causeMessage(this.cause)}`;
1460
- }
1461
- };
1462
- /**
1463
- * Failure raised when invoking an RPC method on a service binding.
1464
- */
1465
- var ServiceBindingRpcError = class extends Data.TaggedError("ServiceBindingRpcError") {
1466
- get message() {
1467
- return `Service binding "${this.binding}" RPC method "${this.method}" failed: ${causeMessage(this.cause)}`;
1468
- }
1469
- };
1470
- const ServiceBindingSchema = Schema.declare((value) => Predicate.hasProperty(value, "fetch") && Predicate.isFunction(value.fetch));
1471
- const decodeServiceBinding = Schema.decodeUnknownOption(ServiceBindingSchema);
1472
- const isServiceBindingClient = (value) => Option.isSome(decodeServiceBinding(value));
1473
- const makeClient$8 = (definition) => {
1474
- return (service) => {
1475
- const fetch = Effect.fn("ServiceBinding.fetch")(function* (input, init) {
1476
- return yield* Effect.tryPromise({
1477
- try: () => service.fetch(input, init),
1478
- catch: (cause) => new ServiceBindingFetchError({
1479
- binding: definition.binding,
1480
- cause
1481
- })
1482
- });
1483
- });
1484
- const rpc = Effect.fnUntraced(function* (method, ...args) {
1485
- const methodName = String(method);
1486
- const encodedArgs = definition.definition === void 0 ? args : yield* encodeArgs(definition.definition, methodName, args).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1487
- binding: definition.binding,
1488
- method: methodName,
1489
- cause
1490
- })));
1491
- const nativeArgs = definition.rpcTracing ? yield* withRpcTraceContext(encodedArgs) : encodedArgs;
1492
- return yield* invokeRpcMethod(service, method, nativeArgs, (cause) => new ServiceBindingRpcError({
1493
- binding: definition.binding,
1494
- method: methodName,
1495
- cause
1496
- }));
1497
- });
1498
- const decodeSuccess$2 = Effect.fnUntraced(function* (methodName, value) {
1499
- if (definition.definition === void 0) return value;
1500
- return yield* decodeSuccess(definition.definition, methodName, value).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1501
- binding: definition.binding,
1502
- method: methodName,
1503
- cause
1504
- })));
1505
- });
1506
- const call = Effect.fnUntraced(function* (method, ...args) {
1507
- const methodName = String(method);
1508
- const value = yield* resolve(yield* rpc(method, ...args)).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1509
- binding: definition.binding,
1510
- method: methodName,
1511
- cause
1512
- })));
1513
- return yield* decodeSuccess$2(methodName, value);
1514
- }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[0])));
1515
- const scopedCall = Effect.fnUntraced(function* (method, ...args) {
1516
- const methodName = String(method);
1517
- const result = yield* rpc(method, ...args);
1518
- const value = yield* scoped(result);
1519
- return yield* decodeSuccess$2(methodName, value);
1520
- }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[0])));
1521
- const directMethods = makeDirectMethods$1(definition.definition, call);
1522
- return Object.assign(directMethods, {
1523
- fetch,
1524
- rpc,
1525
- call,
1526
- scopedCall
1527
- });
1528
- };
1529
- };
1530
- const layer$10 = (tag, definition) => layer$19(tag, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition), { expected: expectedServiceBinding });
1531
- const Service = () => (id, definition) => {
1532
- const tag = Service$2()(id, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition));
1533
- const fetch = Effect.fnUntraced(function* (input, init) {
1534
- return yield* (yield* tag).fetch(input, init);
1535
- });
1536
- const rpc = Effect.fnUntraced(function* (method, ...args) {
1537
- return yield* (yield* tag).rpc(method, ...args);
1538
- });
1539
- const call = Effect.fnUntraced(function* (method, ...args) {
1540
- return yield* (yield* tag).call(method, ...args);
1541
- });
1542
- const scopedCall = Effect.fnUntraced(function* (method, ...args) {
1543
- return yield* (yield* tag).scopedCall(method, ...args);
1544
- });
1545
- const directMethods = makeDirectMethods$1(definition.definition, call);
1546
- return Object.assign(tag, directMethods, {
1547
921
  [TypeId$1]: TypeId$1,
1548
922
  definition,
1549
- fetch,
1550
- rpc,
1551
- call,
1552
- scopedCall
923
+ sqlLayer
1553
924
  });
1554
925
  };
1555
- const makeDirectMethods$1 = (rpcDefinition, call) => {
1556
- const methods = {};
1557
- if (rpcDefinition !== void 0) {
1558
- const invoke = call;
1559
- for (const methodName of Object.keys(rpcDefinition.methods)) methods[methodName] = (...args) => invoke(methodName, ...args);
1560
- }
1561
- return methods;
1562
- };
1563
- //#endregion
1564
- //#region src/WorkerDefinition.ts
1565
- var WorkerDefinition_exports = /* @__PURE__ */ __exportAll({
1566
- Tag: () => Tag$9,
1567
- Worker: () => Worker,
1568
- implement: () => implement$3,
1569
- make: () => make$10,
1570
- method: () => method$1
1571
- });
1572
- const reservedMethodNames$3 = /* @__PURE__ */ new Set([
1573
- "constructor",
1574
- "dup",
1575
- "fetch",
1576
- "connect",
1577
- "queue",
1578
- "scheduled",
1579
- "tail",
1580
- "tailStream",
1581
- "test",
1582
- "trace",
1583
- "alarm",
1584
- "webSocketMessage",
1585
- "webSocketClose",
1586
- "webSocketError"
1587
- ]);
1588
- const assumeTagClass = (value) => {
1589
- return value;
1590
- };
1591
- /**
1592
- * Defines a single RPC method schema in a worker definition.
1593
- */
1594
- const method$1 = method$2;
1595
- const makeDefinition$3 = (id, methods) => {
1596
- assertNoReservedMethods("Worker", methods, reservedMethodNames$3);
1597
- const definition = make$11(id, methods);
1598
- return Object.assign(definition, { make: (layer, options) => {
1599
- const workerOptions = {
1600
- ...options,
1601
- rpc: wrapHandlers$1(definition, options.rpc)
1602
- };
1603
- if (workerOptions.eventLayer === void 0) return make$9(layer, workerOptions);
1604
- return make$9(layer, workerOptions);
1605
- } });
1606
- };
1607
- const make$10 = (id, methods) => Tag$9()(id, methods);
1608
- const Tag$9 = () => (id, methods) => {
1609
- const definition = makeDefinition$3(id, methods);
1610
- const tag = Context.Service()(id);
1611
- const bindingDefinition = (binding) => ({
1612
- ...binding,
1613
- definition
1614
- });
1615
- const layer = (binding) => layer$10(tag, bindingDefinition(binding));
1616
- const fetch = (input, init) => Effect.gen(function* () {
1617
- return yield* (yield* tag).fetch(input, init);
1618
- });
1619
- const rpc = (method, ...args) => Effect.gen(function* () {
1620
- return yield* (yield* tag).rpc(method, ...args);
1621
- });
1622
- const call = (method, ...args) => Effect.gen(function* () {
1623
- return yield* (yield* tag).call(method, ...args);
1624
- });
1625
- const scopedCall = (method, ...args) => Effect.gen(function* () {
1626
- return yield* (yield* tag).scopedCall(method, ...args);
1627
- });
1628
- const directMethods = makeDirectMethods$1(definition, call);
1629
- return assumeTagClass(Object.assign(tag, directMethods, {
1630
- id: definition.id,
1631
- methods: definition.methods,
1632
- make: definition.make,
1633
- layer,
1634
- fetch,
1635
- rpc,
1636
- call,
1637
- scopedCall
1638
- }));
1639
- };
1640
- const Worker = Tag$9;
1641
- const wrapHandlers$1 = (definition, handlers) => {
1642
- const wrapped = Object.create(null);
1643
- for (const key of Object.keys(definition.methods)) {
1644
- const handler = handlers[key];
1645
- wrapped[key] = (...args) => Effect.gen(function* () {
1646
- const decodedArgs = yield* decodeArgs(definition, key, args);
1647
- yield* recordDecodedArgs(decodedArgs);
1648
- const value = yield* handler(...decodedArgs);
1649
- return yield* encodeSuccess(definition, key, value);
1650
- });
1651
- }
1652
- return wrapped;
1653
- };
1654
- /**
1655
- * Helper for implementing handlers with the exact method shape of a definition.
1656
- */
1657
- const implement$3 = (_definition, handlers) => handlers;
1658
- //#endregion
1659
- //#region src/Worker.ts
1660
- var Worker_exports = /* @__PURE__ */ __exportAll({
1661
- ExecutionContext: () => ExecutionContext,
1662
- NativeRequest: () => NativeRequest,
1663
- RunSymbol: () => RunSymbol$1,
1664
- Tag: () => Tag$9,
1665
- WorkerContext: () => WorkerContext,
1666
- implement: () => implement$3,
1667
- isWebSocketUpgrade: () => isWebSocketUpgrade,
1668
- make: () => make$9,
1669
- makeFetchHandler: () => makeFetchHandler,
1670
- method: () => method$1
1671
- });
1672
- var ExecutionContext = class extends Context.Service()("effect-cf/ExecutionContext") {};
1673
- var WorkerContext = class extends Context.Service()("effect-cf/WorkerContext") {};
1674
- var NativeRequest = class extends Context.Service()("effect-cf/NativeRequest") {};
1675
- const isWebSocketUpgrade = (request) => request.headers.get("Upgrade")?.toLowerCase() === "websocket";
1676
- const reservedMethodNames$2 = /* @__PURE__ */ new Set([
1677
- "constructor",
1678
- "dup",
1679
- "fetch",
1680
- "connect",
1681
- "queue",
1682
- "scheduled",
1683
- "tail",
1684
- "tailStream",
1685
- "test",
1686
- "trace",
1687
- "alarm",
1688
- "webSocketMessage",
1689
- "webSocketClose",
1690
- "webSocketError"
1691
- ]);
1692
- /** Override to instrument the whole event, then call super[RunSymbol]. */
1693
- const RunSymbol$1 = Symbol.for("effect-cf/Worker/run");
1694
- const FetchSymbol = Symbol.for("effect-cf/Worker/fetch");
1695
- const renderFetchSuccess = (effect) => Effect.suspend(() => {
1696
- let nativeResponse;
1697
- let webResponse;
1698
- const handled = HttpEffect.toHandled(Effect.flatMap(effect, (response) => {
1699
- if (response instanceof Response) {
1700
- nativeResponse = response;
1701
- return Effect.succeed(HttpServerResponse.empty());
1702
- }
1703
- return Effect.succeed(response);
1704
- }), (request, response) => nativeResponse !== void 0 ? Effect.void : Effect.map(Effect.context(), (context) => {
1705
- webResponse = HttpServerResponse.toWeb(HttpEffect.scopeTransferToStream(response), {
1706
- withoutBody: request.method === "HEAD",
1707
- context
1708
- });
1709
- }));
1710
- const captured = () => nativeResponse ?? webResponse ?? new Response(null, { status: 500 });
1711
- return Effect.matchCause(handled, {
1712
- onFailure: captured,
1713
- onSuccess: captured
1714
- });
1715
- });
1716
- const isWorkerOptions = (options) => !Effect.isEffect(options);
1717
- /**
1718
- * Drains buffered OTLP telemetry once the fetch handler has produced its
1719
- * response.
1720
- *
1721
- * The flush is handed to `ctx.waitUntil` so it never delays the response
1722
- * (including streaming bodies still being consumed). It is a no-op when the
1723
- * context does not contain an `OtlpExporter.Flusher`. The handed-off effect is
1724
- * best-effort and silently settles within two seconds.
1725
- */
1726
- const scheduleTelemetryFlush$1 = scheduleTelemetryFlush$2((flush) => Effect.flatMap(WorkerContext, (workerContext) => workerContext.waitUntil(flush)));
1727
- function make$9(layer, optionsOrFetch) {
1728
- const options = isWorkerOptions(optionsOrFetch) ? optionsOrFetch : { fetch: optionsOrFetch };
1729
- class EffectWorker extends WorkerEntrypoint {
1730
- runtime;
1731
- constructor(ctx, env) {
1732
- super(ctx, env);
1733
- this.runtime = makeEntrypointRuntime(layer, env, Layer.mergeAll(Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx))));
1734
- }
1735
- [RunSymbol$1](effect, runOptions = {}) {
1736
- const eventLayer = options.eventLayer;
1737
- const parent = runOptions.rpc?.parent;
1738
- const parentSpan = parent === void 0 ? void 0 : Tracer.externalSpan(parent);
1739
- if (eventLayer === void 0) return runEventPromise(this.runtime, effect, void 0, parentSpan);
1740
- return runEventPromise(this.runtime, effect, eventLayer, parentSpan);
1741
- }
1742
- fetch(request) {
1743
- return this[FetchSymbol](request);
1744
- }
1745
- [FetchSymbol](request, requestContext) {
1746
- const fetchHandler = options.fetch;
1747
- if (fetchHandler === void 0) return Promise.resolve(new Response("Not Found", { status: 404 }));
1748
- const ctx = requestContext ?? this.ctx;
1749
- const requestServices = Layer.mergeAll(Layer.succeed(NativeRequest, request), Layer.succeed(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromWeb(request)), Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx)));
1750
- return this[RunSymbol$1](renderFetchSuccess(fetchHandler).pipe(Effect.tap(() => scheduleTelemetryFlush$1), Effect.provide(requestServices)), { event: "fetch" });
1751
- }
1752
- queue(batch) {
1753
- const queueHandler = options.queue;
1754
- if (queueHandler === void 0) return Promise.resolve();
1755
- const messages = batch.messages.map((message) => fromMessage(message, message.body));
1756
- return this[RunSymbol$1](queueHandler(fromMessageBatch(batch, messages)), { event: "queue" });
1757
- }
1758
- }
1759
- defineEntrypointRpcMethods("Worker", EffectWorker.prototype, options.rpc, reservedMethodNames$2, (self, effect, rpc) => self[RunSymbol$1](effect, {
1760
- event: "rpc",
1761
- rpc
1762
- }), () => scheduleTelemetryFlush$1, options.rpcTracing);
1763
- return assumeEntrypointClass(EffectWorker);
1764
- }
1765
- function makeFetchHandler(layer, options) {
1766
- const WorkerClass = options.eventLayer === void 0 ? make$9(layer, options) : make$9(layer, options);
1767
- const instances = /* @__PURE__ */ new WeakMap();
1768
- return { fetch: (request, env, ctx) => {
1769
- let instance = instances.get(env);
1770
- if (instance === void 0) {
1771
- instance = new WorkerClass(ctx, env);
1772
- instances.set(env, instance);
1773
- }
1774
- return instance[FetchSymbol](request, ctx);
1775
- } };
1776
- }
1777
926
  //#endregion
1778
927
  //#region src/DurableObjectNamespace.ts
1779
928
  var DurableObjectNamespace_exports = /* @__PURE__ */ __exportAll({
@@ -1812,7 +961,13 @@ const makeClient$7 = (definition) => {
1812
961
  const getByName = (name, options) => Effect.sync(() => namespace.getByName(name, options));
1813
962
  const jurisdiction = (value) => Effect.sync(() => namespace.jurisdiction(value));
1814
963
  const fetch = (stub, input, init) => Effect.tryPromise({
1815
- try: () => stub.fetch(input, init),
964
+ try: (signal) => {
965
+ const callerSignal = init?.signal !== void 0 ? init.signal : input instanceof Request ? input.signal : void 0;
966
+ return stub.fetch(input, {
967
+ ...init,
968
+ signal: callerSignal === null || callerSignal === void 0 ? signal : AbortSignal.any([callerSignal, signal])
969
+ });
970
+ },
1816
971
  catch: (cause) => new DurableObjectFetchError({
1817
972
  binding: definition.binding,
1818
973
  cause
@@ -1825,8 +980,7 @@ const makeClient$7 = (definition) => {
1825
980
  method: methodName,
1826
981
  cause
1827
982
  })));
1828
- const nativeArgs = definition.rpcTracing ? yield* withRpcTraceContext(encodedArgs) : encodedArgs;
1829
- return yield* invokeRpcMethod(stub, method, nativeArgs, (cause) => new DurableObjectRpcError({
983
+ return yield* invokeRpcMethod(stub, method, definition.rpcTracing ? yield* withRpcTraceContext(encodedArgs) : encodedArgs, (cause) => new DurableObjectRpcError({
1830
984
  binding: definition.binding,
1831
985
  method: methodName,
1832
986
  cause
@@ -1851,8 +1005,11 @@ const makeClient$7 = (definition) => {
1851
1005
  }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[1])));
1852
1006
  const scopedCall = Effect.fnUntraced(function* (stub, method, ...args) {
1853
1007
  const methodName = String(method);
1854
- const result = yield* rpc(stub, method, ...args);
1855
- const value = yield* scoped(result);
1008
+ const value = yield* scoped(yield* rpc(stub, method, ...args)).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1009
+ binding: definition.binding,
1010
+ method: methodName,
1011
+ cause
1012
+ })));
1856
1013
  return yield* decodeSuccess$1(methodName, value);
1857
1014
  }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[1])));
1858
1015
  const directMethods = makeDirectMethods(definition.definition, {
@@ -1876,7 +1033,7 @@ const makeClient$7 = (definition) => {
1876
1033
  });
1877
1034
  };
1878
1035
  };
1879
- const layer$9 = (tag, definition) => layer$19(tag, definition.binding, (value) => isDurableObjectNamespaceClient(value), makeClient$7(definition), { expected: expectedDurableObjectNamespace });
1036
+ const layer$9 = (tag, definition) => layer$17(tag, definition.binding, (value) => isDurableObjectNamespaceClient(value), makeClient$7(definition), { expected: expectedDurableObjectNamespace });
1880
1037
  const makeDirectMethods = (rpcDefinition, helpers) => {
1881
1038
  const methods = {};
1882
1039
  if (rpcDefinition !== void 0) {
@@ -1916,11 +1073,11 @@ const reservedMethodNames$1 = /* @__PURE__ */ new Set([
1916
1073
  "webSocketError"
1917
1074
  ]);
1918
1075
  function method(definition) {
1919
- return method$2(definition);
1076
+ return method$1(definition);
1920
1077
  }
1921
1078
  const makeDefinition$2 = (id, methods) => {
1922
1079
  assertNoReservedMethods("Durable Object", methods, reservedMethodNames$1);
1923
- const definition = make$11(id, methods);
1080
+ const definition = make$15(id, methods);
1924
1081
  return Object.assign(definition, { make: (layer, options) => make$7(layer, {
1925
1082
  ...options,
1926
1083
  rpc: wrapHandlers(definition, options.rpc)
@@ -2023,18 +1180,16 @@ var DurableObject_exports = /* @__PURE__ */ __exportAll({
2023
1180
  make: () => make$7,
2024
1181
  method: () => method
2025
1182
  });
2026
- const reservedMethodNames = /* @__PURE__ */ new Set([
2027
- "constructor",
2028
- "dup",
2029
- "fetch",
2030
- "alarm",
2031
- "webSocketMessage",
2032
- "webSocketClose",
2033
- "webSocketError"
2034
- ]);
1183
+ const reservedMethodNames = reservedMethodNames$2;
2035
1184
  /** Override to instrument the whole event, then call super[RunSymbol]. */
2036
1185
  const RunSymbol = Symbol.for("effect-cf/DurableObject/run");
2037
- const scheduleTelemetryFlush = scheduleTelemetryFlush$2((flush) => Effect.flatMap(DurableObjectState, (state) => state.waitUntil(flush)));
1186
+ const scheduleTelemetryFlush = scheduleTelemetryFlush$1((flush) => Effect.flatMap(DurableObjectState, (state) => state.waitUntil(flush)));
1187
+ /**
1188
+ * Builds a Durable Object whose base `layer` lives for the in-memory instance.
1189
+ * Cloudflare does not expose an eviction or shutdown hook, so finalizers in
1190
+ * that layer are not guaranteed to run. Put resources that require timely
1191
+ * release in `eventLayer`, whose scope closes after each handled event.
1192
+ */
2038
1193
  const make$7 = (layer, options = {}) => {
2039
1194
  class EffectDurableObject extends DurableObject {
2040
1195
  runtime;
@@ -2411,7 +1566,6 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2411
1566
  const disconnects = yield* Queue.make();
2412
1567
  const connectionsBySocket = /* @__PURE__ */ new Map();
2413
1568
  const connectionsById = /* @__PURE__ */ new Map();
2414
- const clientIds = /* @__PURE__ */ new Set();
2415
1569
  const resetSockets = /* @__PURE__ */ new WeakSet();
2416
1570
  const declarationsById = /* @__PURE__ */ new Map();
2417
1571
  const declarationsByTag = /* @__PURE__ */ new Map();
@@ -2427,14 +1581,6 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2427
1581
  declarationsByTag.set(declaration.rpcTag, declaration);
2428
1582
  }
2429
1583
  const reserveClientId = (socket) => {
2430
- const attachment = readAttachment(socket.raw, attachmentKey);
2431
- if (attachment._tag === "Invalid") throw new Error("Invalid Durable Object RPC websocket attachment metadata");
2432
- if (attachment._tag === "Valid") {
2433
- const metadata = attachment.metadata;
2434
- nextClientId = Math.max(nextClientId, metadata.clientId + 1);
2435
- writeAttachment(socket.raw, attachmentKey, metadata);
2436
- return metadata;
2437
- }
2438
1584
  const id = nextClientId++;
2439
1585
  const created = {
2440
1586
  version: legacyAttachmentVersion,
@@ -2487,7 +1633,6 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2487
1633
  for (const subscription of restoredSubscriptions) if (!addSubscription(connection, subscription)) throw new Error("Duplicate restored resumable RPC stream subscription identity");
2488
1634
  connectionsBySocket.set(socket.raw, connection);
2489
1635
  connectionsById.set(connection.id, connection);
2490
- clientIds.add(connection.id);
2491
1636
  nextClientId = Math.max(nextClientId, connection.id + 1);
2492
1637
  return connection;
2493
1638
  };
@@ -2524,7 +1669,6 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2524
1669
  if (connection === void 0) return;
2525
1670
  connectionsBySocket.delete(socket.raw);
2526
1671
  connectionsById.delete(connection.id);
2527
- clientIds.delete(connection.id);
2528
1672
  activeNonResumableRequestCount -= connection.nonResumableRequestIds.size;
2529
1673
  connection.requestIds.clear();
2530
1674
  connection.nonResumableRequestIds.clear();
@@ -2743,7 +1887,7 @@ const layer$8 = (options = {}) => Layer.effectContext(Effect.gen(function* () {
2743
1887
  end: (clientId) => Effect.sync(() => {
2744
1888
  connectionsById.get(clientId)?.socket.raw.close();
2745
1889
  }),
2746
- clientIds: Effect.sync(() => clientIds),
1890
+ clientIds: Effect.sync(() => new Set(connectionsById.keys())),
2747
1891
  initialMessage: Effect.succeedNone,
2748
1892
  supportsAck: true,
2749
1893
  supportsTransferables: false,
@@ -2877,13 +2021,9 @@ const writeAttachment = (socket, key, metadata) => {
2877
2021
  const current = socket.deserializeAttachment();
2878
2022
  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");
2879
2023
  const attachment = Predicate.isObject(current) ? current : {};
2880
- const currentMetadata = Predicate.hasProperty(attachment, key) && Predicate.isObject(attachment[key]) ? attachment[key] : {};
2881
2024
  socket.serializeAttachment({
2882
2025
  ...attachment,
2883
- [key]: {
2884
- ...currentMetadata,
2885
- ...metadata
2886
- }
2026
+ [key]: metadata
2887
2027
  });
2888
2028
  };
2889
2029
  const makeHeartbeatController = (state, serialization, policy) => Effect.gen(function* () {
@@ -3142,7 +2282,7 @@ const makeClient$6 = (definition, options) => (email) => {
3142
2282
  rawUnsafe: Effect.succeed(email)
3143
2283
  };
3144
2284
  };
3145
- const layer$6 = (tag, definition) => layer$19(tag, definition.binding, isEmailBinding, makeClient$6(definition, definition.send), { expected: expectedSendEmailBinding });
2285
+ const layer$6 = (tag, definition) => layer$17(tag, definition.binding, isEmailBinding, makeClient$6(definition, definition.send), { expected: expectedSendEmailBinding });
3146
2286
  const make$6 = (id) => Tag$7()(id);
3147
2287
  const Tag$7 = () => (id) => {
3148
2288
  const tag = Context.Service()(id);
@@ -3168,7 +2308,7 @@ const makeClient$5 = (definition) => (hyperdrive) => ({
3168
2308
  connectionString: hyperdrive.connectionString,
3169
2309
  rawUnsafe: Effect.succeed(hyperdrive)
3170
2310
  });
3171
- const layer$5 = (tag, definition) => layer$19(tag, definition.binding, isHyperdrive, makeClient$5(definition), { expected: expectedHyperdrive });
2311
+ const layer$5 = (tag, definition) => layer$17(tag, definition.binding, isHyperdrive, makeClient$5(definition), { expected: expectedHyperdrive });
3172
2312
  const make$5 = (id) => Tag$6()(id);
3173
2313
  const Tag$6 = () => (id) => {
3174
2314
  const tag = Context.Service()(id);
@@ -3270,7 +2410,7 @@ const makeClient$4 = (definition) => (images) => {
3270
2410
  rawUnsafe: Effect.succeed(images)
3271
2411
  };
3272
2412
  };
3273
- const layer$4 = (tag, definition) => layer$19(tag, definition.binding, isImagesBinding, makeClient$4(definition), { expected: expectedImagesBinding });
2413
+ const layer$4 = (tag, definition) => layer$17(tag, definition.binding, isImagesBinding, makeClient$4(definition), { expected: expectedImagesBinding });
3274
2414
  const make$4 = (id) => Tag$5()(id);
3275
2415
  const Tag$5 = () => (id) => {
3276
2416
  const tag = Context.Service()(id);
@@ -3378,7 +2518,7 @@ const makeClient$3 = (definition) => {
3378
2518
  rawUnsafe: Effect.succeed(kv)
3379
2519
  });
3380
2520
  };
3381
- const layer$3 = (tag, definition) => layer$19(tag, definition.binding, isKvNamespace, makeClient$3(definition), { expected: expectedKvNamespace });
2521
+ const layer$3 = (tag, definition) => layer$17(tag, definition.binding, isKvNamespace, makeClient$3(definition), { expected: expectedKvNamespace });
3382
2522
  const makeDefinition$1 = (id, definition) => {
3383
2523
  const kvDefinition = {
3384
2524
  id,
@@ -3499,7 +2639,7 @@ const makeClient$2 = (definition) => {
3499
2639
  };
3500
2640
  };
3501
2641
  };
3502
- const layer$2 = (tag, definition) => layer$19(tag, definition.binding, isR2Bucket, makeClient$2(definition), { expected: expectedR2Bucket });
2642
+ const layer$2 = (tag, definition) => layer$17(tag, definition.binding, isR2Bucket, makeClient$2(definition), { expected: expectedR2Bucket });
3503
2643
  const make$3 = (id) => Tag$3()(id);
3504
2644
  const Tag$3 = () => (id) => {
3505
2645
  const tag = Context.Service()(id);
@@ -3565,7 +2705,7 @@ const makeClient$1 = (definition) => (index) => {
3565
2705
  rawUnsafe: Effect.succeed(index)
3566
2706
  };
3567
2707
  };
3568
- const layer$1 = (tag, definition) => layer$19(tag, definition.binding, isVectorizeBinding, makeClient$1(definition), { expected: expectedVectorizeBinding });
2708
+ const layer$1 = (tag, definition) => layer$17(tag, definition.binding, isVectorizeBinding, makeClient$1(definition), { expected: expectedVectorizeBinding });
3569
2709
  const make$2 = (id) => Tag$2()(id);
3570
2710
  const Tag$2 = () => (id) => {
3571
2711
  const tag = Context.Service()(id);
@@ -3720,7 +2860,7 @@ const makeClient = (definition) => {
3720
2860
  rawUnsafe: Effect.succeed(workflow)
3721
2861
  });
3722
2862
  };
3723
- const layer = (tag, definition) => layer$19(tag, definition.binding, (value) => isWorkflow(value), makeClient(definition), { expected: expectedWorkflow });
2863
+ const layer = (tag, definition) => layer$17(tag, definition.binding, (value) => isWorkflow(value), makeClient(definition), { expected: expectedWorkflow });
3724
2864
  //#endregion
3725
2865
  //#region src/WorkflowDefinition.ts
3726
2866
  var WorkflowDefinition_exports = /* @__PURE__ */ __exportAll({
@@ -3741,7 +2881,7 @@ const make$1 = (id, definition) => Tag$1()(id, definition);
3741
2881
  const Tag$1 = () => (id, definition) => {
3742
2882
  const workflowDefinition = makeDefinition(id, definition);
3743
2883
  const tag = Context.Service()(`effect-cf/Workflow/${id}`);
3744
- const layer$20 = (binding) => layer(tag, {
2884
+ const layer$18 = (binding) => layer(tag, {
3745
2885
  ...binding,
3746
2886
  payload: definition.payload,
3747
2887
  result: definition.result
@@ -3761,7 +2901,7 @@ const Tag$1 = () => (id, definition) => {
3761
2901
  payload: workflowDefinition.payload,
3762
2902
  result: workflowDefinition.result,
3763
2903
  make: workflowDefinition.make,
3764
- layer: layer$20,
2904
+ layer: layer$18,
3765
2905
  create,
3766
2906
  createBatch,
3767
2907
  get,
@@ -3835,20 +2975,29 @@ const exposeCloudflareNonRetryableError = (effect) => Effect.catchCause(effect,
3835
2975
  const error = Cause.findErrorOption(cause);
3836
2976
  return Option.isSome(error) && error.value instanceof WorkflowStepNonRetryableError ? Effect.die(toCloudflareNonRetryableError(error.value)) : Effect.failCause(cause);
3837
2977
  });
3838
- const fromWorkflowStep = (step, runPromise) => ({
2978
+ const fromWorkflowStep = (step) => ({
3839
2979
  raw: step,
3840
- do: (name, effect, config) => Effect.context().pipe(Effect.flatMap((context) => Effect.tryPromise({
3841
- try: () => {
3842
- const run = (stepContext) => runPromise(exposeCloudflareNonRetryableError(Effect.scoped(Effect.provideService(Effect.provideContext(effect, context), WorkflowStepContext$1, stepContext))));
3843
- const rawStep = step;
3844
- return config === void 0 ? rawStep.do(name, run) : rawStep.do(name, config, run);
3845
- },
3846
- catch: (cause) => new WorkflowStepError({
3847
- step: name,
3848
- operation: "do",
3849
- cause
3850
- })
3851
- }))),
2980
+ do: (name, effect, config) => Effect.gen(function* () {
2981
+ const context = yield* Effect.context();
2982
+ return yield* Effect.scoped(Effect.gen(function* () {
2983
+ const runPromise = yield* FiberSet.makeRuntimePromise();
2984
+ return yield* Effect.tryPromise({
2985
+ try: () => {
2986
+ const run = (stepContext) => {
2987
+ const stepEffect = Effect.scoped(Effect.provideService(effect, WorkflowStepContext$1, stepContext));
2988
+ return runPromise(exposeCloudflareNonRetryableError(Effect.provideContext(stepEffect, context)));
2989
+ };
2990
+ const rawStep = step;
2991
+ return config === void 0 ? rawStep.do(name, run) : rawStep.do(name, config, run);
2992
+ },
2993
+ catch: (cause) => new WorkflowStepError({
2994
+ step: name,
2995
+ operation: "do",
2996
+ cause
2997
+ })
2998
+ });
2999
+ }));
3000
+ }),
3852
3001
  sleep: (name, duration) => Effect.tryPromise({
3853
3002
  try: () => step.sleep(name, duration),
3854
3003
  catch: (cause) => new WorkflowStepError({
@@ -3884,7 +3033,7 @@ const make = (layer, options) => {
3884
3033
  this.runtime = makeEntrypointRuntime(layer, env, Layer.mergeAll(Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx))));
3885
3034
  }
3886
3035
  run(event, step) {
3887
- const workflowServices = Layer.mergeAll(Layer.succeed(WorkflowEvent$1, fromWorkflowEvent(event)), Layer.succeed(WorkflowStep$1, fromWorkflowStep(step, (effect) => this.runtime.runPromise(effect))));
3036
+ const workflowServices = Layer.mergeAll(Layer.succeed(WorkflowEvent$1, fromWorkflowEvent(event)), Layer.succeed(WorkflowStep$1, fromWorkflowStep(step)));
3888
3037
  return runEventPromise(this.runtime, options.run(event.payload), workflowServices);
3889
3038
  }
3890
3039
  }