effect-cf 0.35.0 → 0.37.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-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";
5
+ import { t as fromExecutionContext } from "./WorkerContext-Yobnfw-K.mjs";
6
+ import { a as DurableWebSocketAttachmentError, c as StorageOperationError, i as DurableObjectWebSocket_exports, n as DurableObjectState_exports, o as fromWebSocket, r as fromDurableObjectState, s as DurableObjectStorage_exports, t as DurableObjectState } from "./DurableObjectState-DLL0YgBd.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") {
@@ -54,7 +56,7 @@ 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
  }));
@@ -76,11 +78,11 @@ const makeClient$15 = (definition) => (ai) => {
76
78
  rawUnsafe: Effect.succeed(ai)
77
79
  };
78
80
  };
79
- const layer$18 = (tag, definition) => layer$19(tag, definition.binding, (value) => isWorkersAiBinding(value), makeClient$15(definition), { expected: expectedWorkersAiBinding });
80
- const make$18 = (id) => Tag$16()(id);
81
- 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) => {
82
84
  const tag = Context.Service()(id);
83
- const makeLayer = (definition) => layer$18(tag, definition);
85
+ const makeLayer = (definition) => layer$16(tag, definition);
84
86
  return Object.assign(tag, {
85
87
  id,
86
88
  layer: makeLayer
@@ -90,11 +92,11 @@ const Tag$16 = () => (id) => {
90
92
  //#region src/AiGateway.ts
91
93
  var AiGateway_exports = /* @__PURE__ */ __exportAll({
92
94
  AiGatewayOperationError: () => AiGatewayOperationError,
93
- Tag: () => Tag$15,
95
+ Tag: () => Tag$12,
94
96
  isAiGatewayBinding: () => isAiGatewayBinding,
95
- layer: () => layer$17,
96
- make: () => make$17,
97
- makeClient: () => makeClient$14,
97
+ layer: () => layer$15,
98
+ make: () => make$13,
99
+ makeClient: () => makeClient$12,
98
100
  makeClientFromAi: () => makeClientFromAi,
99
101
  makeHttpClient: () => makeHttpClient
100
102
  });
@@ -171,7 +173,7 @@ const ensureSuccessfulResponse = (response) => {
171
173
  if (!response.ok) throw new Error(`AI Gateway HTTP request failed with status ${response.status}`);
172
174
  };
173
175
  const isAiGatewayBinding = (value) => isWorkersAiBinding(value);
174
- const makeClient$14 = (definition, gateway) => ({
176
+ const makeClient$12 = (definition, gateway) => ({
175
177
  definition,
176
178
  run: Effect.fn("AiGateway.run")((data, options) => tryAiGatewayPromise(definition.binding, "run", () => gateway.run(Array.isArray(data) ? [...data] : data, options))),
177
179
  getUrl: Effect.fn("AiGateway.getUrl")((provider) => tryAiGatewayPromise(definition.binding, "getUrl", () => gateway.getUrl(provider))),
@@ -191,11 +193,11 @@ const makeClientFromAi = (definition, ai) => {
191
193
  const withGateway = (operation) => gateway.pipe(Effect.flatMap(operation));
192
194
  return {
193
195
  definition,
194
- run: (data, options) => withGateway((raw) => makeClient$14(definition, raw).run(data, options)),
195
- getUrl: (provider) => withGateway((raw) => makeClient$14(definition, raw).getUrl(provider)),
196
- fetch: (options) => withGateway((raw) => makeClient$14(definition, raw).fetch(options)),
197
- patchLog: (logId, data) => withGateway((raw) => makeClient$14(definition, raw).patchLog(logId, data)),
198
- 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)),
199
201
  rawUnsafe: gateway
200
202
  };
201
203
  };
@@ -245,11 +247,11 @@ const makeHttpClient = (definition, request = fetch) => {
245
247
  rawUnsafe: Effect.fail(aiGatewayError(binding, "rawUnsafe", /* @__PURE__ */ new TypeError("HTTP AI Gateway clients have no raw binding")))
246
248
  };
247
249
  };
248
- const layer$17 = (tag, definition) => layer$19(tag, definition.binding, isAiGatewayBinding, (ai) => makeClientFromAi(definition, ai), { expected: expectedAiGatewayBinding });
249
- const make$17 = (id) => Tag$15()(id);
250
- 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) => {
251
253
  const tag = Context.Service()(id);
252
- const makeLayer = (definition) => layer$17(tag, definition);
254
+ const makeLayer = (definition) => layer$15(tag, definition);
253
255
  return Object.assign(tag, {
254
256
  id,
255
257
  layer: makeLayer
@@ -264,13 +266,13 @@ var AnalyticsEngine_exports = /* @__PURE__ */ __exportAll({
264
266
  AnalyticsEngineQueryError: () => AnalyticsEngineQueryError,
265
267
  AnalyticsEngineWriteValidationError: () => AnalyticsEngineWriteValidationError,
266
268
  QueryTag: () => QueryTag,
267
- Tag: () => Tag$14,
269
+ Tag: () => Tag$11,
268
270
  isAnalyticsEngineDataset: () => isAnalyticsEngineDataset,
269
- layer: () => layer$16,
271
+ layer: () => layer$14,
270
272
  layerFetch: () => layerFetch,
271
273
  layerFetchConfig: () => layerFetchConfig,
272
- make: () => make$16,
273
- makeClient: () => makeClient$13,
274
+ make: () => make$12,
275
+ makeClient: () => makeClient$11,
274
276
  makeQuery: () => makeQuery,
275
277
  makeQueryClient: () => makeQueryClient,
276
278
  queryConfig: () => queryConfig,
@@ -459,7 +461,7 @@ const makeQueryClientWith = (definition, httpClient) => {
459
461
  };
460
462
  const makeQueryClient = (definition) => Effect.map(HttpClient.HttpClient, (httpClient) => makeQueryClientWith(definition, httpClient));
461
463
  const isAnalyticsEngineDataset = (value) => Predicate.hasProperty(value, "writeDataPoint") && Predicate.isFunction(value.writeDataPoint);
462
- const makeClient$13 = (definition, defaults) => (dataset) => {
464
+ const makeClient$11 = (definition, defaults) => (dataset) => {
463
465
  return {
464
466
  definition,
465
467
  writeDataPoint: Effect.fn("AnalyticsEngine.writeDataPoint")((dataPoint, options) => {
@@ -489,12 +491,12 @@ const queryLayerConfig = (tag, config = queryConfig()) => Layer.effect(tag, Effe
489
491
  return yield* makeQueryClient(definition);
490
492
  }));
491
493
  const layerFetchConfig = (tag, config = queryConfig()) => queryLayerConfig(tag, config).pipe(Layer.provide(FetchHttpClient.layer));
492
- const layer$16 = (tag, definition) => layer$19(tag, definition.binding, isAnalyticsEngineDataset, makeClient$13(definition, definition.write), { expected: expectedAnalyticsEngineDataset });
493
- 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);
494
496
  const makeQuery = (id) => QueryTag()(id);
495
- const Tag$14 = () => (id) => {
497
+ const Tag$11 = () => (id) => {
496
498
  const tag = Context.Service()(id);
497
- const makeLayer = (definition) => layer$16(tag, definition);
499
+ const makeLayer = (definition) => layer$14(tag, definition);
498
500
  return Object.assign(tag, {
499
501
  id,
500
502
  layer: makeLayer
@@ -518,11 +520,11 @@ const QueryTag = () => (id) => {
518
520
  //#region src/BrowserRendering.ts
519
521
  var BrowserRendering_exports = /* @__PURE__ */ __exportAll({
520
522
  BrowserRenderingOperationError: () => BrowserRenderingOperationError,
521
- Tag: () => Tag$13,
523
+ Tag: () => Tag$10,
522
524
  isBrowserRenderingBinding: () => isBrowserRenderingBinding,
523
- layer: () => layer$15,
524
- make: () => make$15,
525
- makeClient: () => makeClient$12
525
+ layer: () => layer$13,
526
+ make: () => make$11,
527
+ makeClient: () => makeClient$10
526
528
  });
527
529
  const expectedBrowserRenderingBinding = "Browser Rendering binding resource";
528
530
  var BrowserRenderingOperationError = class extends Data.TaggedError("BrowserRenderingOperationError") {
@@ -571,17 +573,17 @@ const wrapBrowser = (binding, browser) => ({
571
573
  disconnect: browser.disconnect === void 0 ? Effect.void : tryBrowserRenderingSync(binding, "disconnect", () => browser.disconnect())
572
574
  });
573
575
  const isBrowserRenderingBinding = (value) => Predicate.isObjectOrArray(value) || Predicate.isFunction(value);
574
- const makeClient$12 = (definition) => (binding) => ({
576
+ const makeClient$10 = (definition) => (binding) => ({
575
577
  definition,
576
578
  launchWith: (launch, options) => tryBrowserRenderingPromise(definition.binding, "launch", () => launch(binding, options)).pipe(Effect.map((browser) => wrapBrowser(definition.binding, browser)), Effect.withSpan("BrowserRendering.launchWith")),
577
579
  connectWith: (connect, options) => tryBrowserRenderingPromise(definition.binding, "connect", () => connect(binding, options)).pipe(Effect.map((browser) => wrapBrowser(definition.binding, browser)), Effect.withSpan("BrowserRendering.connectWith")),
578
580
  rawUnsafe: Effect.succeed(binding)
579
581
  });
580
- const layer$15 = (tag, definition) => layer$19(tag, definition.binding, isBrowserRenderingBinding, makeClient$12(definition), { expected: expectedBrowserRenderingBinding });
581
- const make$15 = (id) => Tag$13()(id);
582
- 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) => {
583
585
  const tag = Context.Service()(id);
584
- const makeLayer = (definition) => layer$15(tag, definition);
586
+ const makeLayer = (definition) => layer$13(tag, definition);
585
587
  return Object.assign(tag, {
586
588
  id,
587
589
  layer: makeLayer
@@ -592,10 +594,10 @@ const Tag$13 = () => (id) => {
592
594
  var Cache_exports = /* @__PURE__ */ __exportAll({
593
595
  CacheOperationError: () => CacheOperationError,
594
596
  CacheStorage: () => CacheStorage,
595
- layer: () => layer$14,
597
+ layer: () => layer$12,
596
598
  layerFrom: () => layerFrom,
597
599
  makeCacheClient: () => makeCacheClient,
598
- makeClient: () => makeClient$11
600
+ makeClient: () => makeClient$9
599
601
  });
600
602
  var CacheOperationError = class extends Data.TaggedError("CacheOperationError") {
601
603
  get message() {
@@ -623,13 +625,13 @@ const makeCacheClient = (cache, name = "default") => ({
623
625
  delete: Effect.fn("Cache.delete", spanOptions$2(name, "delete"))((request, options) => tryCachePromise(name, "delete", () => cache.delete(request, options))),
624
626
  rawUnsafe: Effect.succeed(cache)
625
627
  });
626
- const makeClient$11 = (storage) => ({
628
+ const makeClient$9 = (storage) => ({
627
629
  default: makeCacheClient(storage.default),
628
630
  open: (name) => tryCachePromise(name, "open", () => storage.open(name)).pipe(Effect.map((cache) => makeCacheClient(cache, name)), Effect.withSpan("Cache.open", spanOptions$2(name, "open"))),
629
631
  rawUnsafe: Effect.succeed(storage)
630
632
  });
631
- const layerFrom = (storage) => Layer.succeed(CacheStorage, makeClient$11(storage));
632
- 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));
633
635
  //#endregion
634
636
  //#region src/CloudflareOtlp.ts
635
637
  /**
@@ -639,7 +641,7 @@ const layer$14 = Layer.sync(CacheStorage, () => makeClient$11(caches));
639
641
  * layer finalizers run separately and follow their configured shutdown timeout.
640
642
  */
641
643
  var CloudflareOtlp_exports = /* @__PURE__ */ __exportAll({
642
- layer: () => layer$13,
644
+ layer: () => layer$11,
643
645
  layerDurableObject: () => layerDurableObject,
644
646
  layerJson: () => layerJson,
645
647
  layerProtobuf: () => layerProtobuf,
@@ -705,14 +707,14 @@ const makeLayer = (options = {}, runtimeAttributes = {}) => {
705
707
  * The layer provides {@link OtlpExporter.Flusher} for draining buffered
706
708
  * telemetry before the isolate freezes.
707
709
  */
708
- const layer$13 = (options = {}) => makeLayer(options);
710
+ const layer$11 = (options = {}) => makeLayer(options);
709
711
  /** Base OTLP telemetry layer forced to JSON serialization. */
710
- const layerJson = (options = {}) => layer$13({
712
+ const layerJson = (options = {}) => layer$11({
711
713
  ...options,
712
714
  serialization: "json"
713
715
  });
714
716
  /** Base OTLP telemetry layer forced to protobuf serialization. */
715
- const layerProtobuf = (options = {}) => layer$13({
717
+ const layerProtobuf = (options = {}) => layer$11({
716
718
  ...options,
717
719
  serialization: "protobuf"
718
720
  });
@@ -746,11 +748,11 @@ var ContainerNamespace_exports = /* @__PURE__ */ __exportAll({
746
748
  ContainerNamespace: () => ContainerNamespace,
747
749
  ContainerOperationError: () => ContainerOperationError,
748
750
  ContainerState: () => ContainerState,
749
- Tag: () => Tag$12,
751
+ Tag: () => Tag$9,
750
752
  isContainerNamespaceResource: () => isContainerNamespaceResource,
751
- layer: () => layer$12,
752
- make: () => make$14,
753
- makeClient: () => makeClient$10
753
+ layer: () => layer$10,
754
+ make: () => make$10,
755
+ makeClient: () => makeClient$8
754
756
  });
755
757
  const expectedContainerNamespace = "Container namespace binding with getByName()";
756
758
  /** Serializable state reported by a Cloudflare Container instance. */
@@ -826,7 +828,7 @@ const makeInstanceClient = (definition, instance, stub) => {
826
828
  };
827
829
  };
828
830
  const isContainerNamespaceResource = (value) => Predicate.hasProperty(value, "getByName") && Predicate.isFunction(value.getByName);
829
- const makeClient$10 = (definition) => (namespace) => {
831
+ const makeClient$8 = (definition) => (namespace) => {
830
832
  const getByName = (name, options) => Effect.try({
831
833
  try: () => makeInstanceClient(definition, name, namespace.getByName(name, options)),
832
834
  catch: (cause) => new ContainerOperationError({
@@ -862,11 +864,11 @@ const makeClient$10 = (definition) => (namespace) => {
862
864
  rawUnsafe: Effect.succeed(namespace)
863
865
  };
864
866
  };
865
- const layer$12 = (tag, definition) => layer$19(tag, definition.binding, (value) => isContainerNamespaceResource(value), makeClient$10(definition), { expected: expectedContainerNamespace });
866
- const make$14 = (id) => Tag$12()(id);
867
- 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) => {
868
870
  const tag = Context.Service()(`effect-cf/Container/${id}`);
869
- const makeLayer = (definition) => layer$12(tag, definition);
871
+ const makeLayer = (definition) => layer$10(tag, definition);
870
872
  const getByName = Effect.fnUntraced(function* (name, options) {
871
873
  return yield* (yield* tag).getByName(name, options);
872
874
  });
@@ -895,19 +897,19 @@ const Tag$12 = () => (id) => {
895
897
  rawUnsafe
896
898
  });
897
899
  };
898
- const ContainerNamespace = Tag$12;
900
+ const ContainerNamespace = Tag$9;
899
901
  //#endregion
900
902
  //#region src/D1.ts
901
903
  var D1_exports = /* @__PURE__ */ __exportAll({
902
- Service: () => Service$1,
903
- make: () => make$13
904
+ Service: () => Service,
905
+ make: () => make$9
904
906
  });
905
- const TypeId$2 = "~effect-cf/D1";
907
+ const TypeId$1 = "~effect-cf/D1";
906
908
  const expectedD1Database = "D1 database binding with prepare(), batch(), and exec()";
907
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);
908
- const make$13 = (id, definition) => Service$1()(id, definition);
909
- const Service$1 = () => (id, definition) => {
910
- 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 });
911
913
  const sqlLayer = (options) => Layer.unwrap(Effect.gen(function* () {
912
914
  const db = yield* tag;
913
915
  return D1Client.layer({
@@ -916,887 +918,11 @@ const Service$1 = () => (id, definition) => {
916
918
  });
917
919
  })).pipe(Layer.provide(tag.layer));
918
920
  return Object.assign(tag, {
919
- [TypeId$2]: TypeId$2,
920
- definition,
921
- sqlLayer
922
- });
923
- };
924
- //#endregion
925
- //#region src/QueueBinding.ts
926
- var QueueBinding_exports = /* @__PURE__ */ __exportAll({
927
- QueueOperationError: () => QueueOperationError,
928
- isQueue: () => isQueue,
929
- layer: () => layer$11,
930
- makeClient: () => makeClient$9
931
- });
932
- const expectedQueueProducer = "Queue producer binding with send(); optional sendBatch()/metrics()";
933
- var QueueOperationError = class extends Data.TaggedError("QueueOperationError") {};
934
- const tryQueuePromise = (binding, operation, evaluate) => Effect.tryPromise({
935
- try: evaluate,
936
- catch: (cause) => new QueueOperationError({
937
- binding,
938
- operation,
939
- cause,
940
- message: `Cloudflare queue binding "${binding}" operation "${operation}" failed`
941
- })
942
- });
943
- const isQueue = (value) => Predicate.hasProperty(value, "send") && Predicate.isFunction(value.send);
944
- const makeClient$9 = (definition) => {
945
- const encodeMessage = Schema.encodeEffect(definition.message);
946
- return (queue) => ({
947
- send: Effect.fn("QueueBinding.send", { attributes: {
948
- binding: definition.binding,
949
- operation: "send"
950
- } })(function* (message, options) {
951
- const encoded = yield* encodeMessage(message);
952
- yield* tryQueuePromise(definition.binding, "send", () => queue.send(encoded, options));
953
- }),
954
- sendBatch: Effect.fn("QueueBinding.sendBatch", { attributes: {
955
- binding: definition.binding,
956
- operation: "sendBatch"
957
- } })(function* (messages, options) {
958
- const encodedMessages = [];
959
- for (const message of messages) encodedMessages.push({
960
- ...message,
961
- body: yield* encodeMessage(message.body)
962
- });
963
- const sendBatch = queue.sendBatch;
964
- if (sendBatch === void 0) return yield* new QueueOperationError({
965
- binding: definition.binding,
966
- operation: "sendBatch",
967
- cause: /* @__PURE__ */ new Error(`Queue binding "${definition.binding}" does not provide sendBatch()`),
968
- message: `Cloudflare queue binding "${definition.binding}" does not provide sendBatch()`
969
- });
970
- yield* tryQueuePromise(definition.binding, "sendBatch", () => sendBatch.call(queue, encodedMessages, options));
971
- }),
972
- metrics: () => {
973
- const metrics = queue.metrics;
974
- if (metrics === void 0) return Effect.fail(new QueueOperationError({
975
- binding: definition.binding,
976
- operation: "metrics",
977
- cause: /* @__PURE__ */ new Error(`Queue binding "${definition.binding}" does not provide metrics()`),
978
- message: `Cloudflare queue binding "${definition.binding}" does not provide metrics()`
979
- }));
980
- return tryQueuePromise(definition.binding, "metrics", () => metrics.call(queue));
981
- },
982
- rawUnsafe: Effect.succeed(queue)
983
- });
984
- };
985
- const layer$11 = (tag, definition) => layer$19(tag, definition.binding, (value) => isQueue(value), makeClient$9(definition), { expected: expectedQueueProducer });
986
- //#endregion
987
- //#region src/QueueDefinition.ts
988
- var QueueDefinition_exports = /* @__PURE__ */ __exportAll({
989
- Queue: () => Queue$1,
990
- Tag: () => Tag$11,
991
- implement: () => implement$5,
992
- make: () => make$12
993
- });
994
- const makeDefinition$4 = (id, definition) => {
995
- const queueDefinition = {
996
- id,
997
- message: definition.message
998
- };
999
- return Object.assign(queueDefinition, { make: (layer, options) => make$9(layer, {
1000
- ...options,
1001
- queue: wrapHandler$1(queueDefinition, options.queue)
1002
- }) });
1003
- };
1004
- const make$12 = (id, definition) => Tag$11()(id, definition);
1005
- const Tag$11 = () => (id, definition) => {
1006
- const queueDefinition = makeDefinition$4(id, definition);
1007
- const tag = Context.Service()(`effect-cf/Queue/${id}`);
1008
- const layer = (binding) => layer$11(tag, {
1009
- ...binding,
1010
- message: definition.message
1011
- });
1012
- const send = Effect.fnUntraced(function* (message, options) {
1013
- yield* (yield* tag).send(message, options);
1014
- });
1015
- const sendBatch = Effect.fnUntraced(function* (messages, options) {
1016
- yield* (yield* tag).sendBatch(messages, options);
1017
- });
1018
- const metrics = Effect.fnUntraced(function* () {
1019
- return yield* (yield* tag).metrics();
1020
- });
1021
- const rawUnsafe = Effect.flatMap(tag, (queue) => queue.rawUnsafe);
1022
- return Object.assign(tag, {
1023
- id: queueDefinition.id,
1024
- message: queueDefinition.message,
1025
- make: queueDefinition.make,
1026
- layer,
1027
- send,
1028
- sendBatch,
1029
- metrics,
1030
- rawUnsafe
1031
- });
1032
- };
1033
- const Queue$1 = Tag$11;
1034
- const wrapHandler$1 = (definition, handler) => {
1035
- const decodeBody = Schema.decodeUnknownEffect(definition.message);
1036
- return Effect.fnUntraced(function* (batch) {
1037
- yield* handler(yield* decodeBatch(batch.raw, decodeBody));
1038
- });
1039
- };
1040
- const implement$5 = (_definition, handler) => handler;
1041
- //#endregion
1042
- //#region src/Queue.ts
1043
- var Queue_exports = /* @__PURE__ */ __exportAll({
1044
- QueueMessageDecodeError: () => QueueMessageDecodeError,
1045
- Tag: () => Tag$10,
1046
- decodeBatch: () => decodeBatch,
1047
- fromMessage: () => fromMessage,
1048
- fromMessageBatch: () => fromMessageBatch,
1049
- implement: () => implement$4
1050
- });
1051
- var QueueMessageDecodeError = class extends Data.TaggedError("QueueMessageDecodeError") {
1052
- get message() {
1053
- return `Queue "${this.queue}" failed to decode message "${this.messageId}" at index ${this.index}: ${causeMessage(this.cause)}`;
1054
- }
1055
- };
1056
- const fromMessage = (message, body) => ({
1057
- raw: message,
1058
- id: message.id,
1059
- timestamp: message.timestamp,
1060
- body,
1061
- attempts: message.attempts,
1062
- ack: Effect.sync(() => message.ack()),
1063
- retry: (options) => Effect.sync(() => message.retry(options))
1064
- });
1065
- const fromMessageBatch = (batch, messages) => ({
1066
- raw: batch,
1067
- messages,
1068
- queue: batch.queue,
1069
- metadata: batch.metadata,
1070
- ackAll: Effect.sync(() => batch.ackAll()),
1071
- retryAll: (options) => Effect.sync(() => batch.retryAll(options))
1072
- });
1073
- const decodeBatch = (batch, decodeBody) => Effect.gen(function* () {
1074
- const messages = [];
1075
- for (let index = 0; index < batch.messages.length; index++) {
1076
- const message = batch.messages[index];
1077
- const body = yield* decodeBody(message.body).pipe(Effect.mapError((cause) => new QueueMessageDecodeError({
1078
- queue: batch.queue,
1079
- messageId: message.id,
1080
- index,
1081
- cause
1082
- })));
1083
- messages.push(fromMessage(message, body));
1084
- }
1085
- return fromMessageBatch(batch, messages);
1086
- });
1087
- const Tag$10 = Tag$11;
1088
- const implement$4 = implement$5;
1089
- //#endregion
1090
- //#region src/RpcDefinition.ts
1091
- var RpcDefinition_exports = /* @__PURE__ */ __exportAll({
1092
- RpcArgumentCountError: () => RpcArgumentCountError,
1093
- RpcArgumentDecodeError: () => RpcArgumentDecodeError,
1094
- RpcArgumentEncodeError: () => RpcArgumentEncodeError,
1095
- RpcReservedMethodNameError: () => RpcReservedMethodNameError,
1096
- RpcSuccessDecodeError: () => RpcSuccessDecodeError,
1097
- RpcSuccessEncodeError: () => RpcSuccessEncodeError,
1098
- assertNoReservedMethods: () => assertNoReservedMethods,
1099
- decodeArgs: () => decodeArgs,
1100
- decodeSuccess: () => decodeSuccess,
1101
- decodeWireError: () => decodeWireError,
1102
- encodeArgs: () => encodeArgs,
1103
- encodeSuccess: () => encodeSuccess,
1104
- encodeWireError: () => encodeWireError,
1105
- isWireError: () => isWireError,
1106
- make: () => make$11,
1107
- method: () => method$2,
1108
- reservedMethodNames: () => reservedMethodNames$4
1109
- });
1110
- var RpcReservedMethodNameError = class extends Data.TaggedError("RpcReservedMethodNameError") {
1111
- get message() {
1112
- return `${this.definition} RPC method "${this.method}" is reserved by Cloudflare Workers RPC`;
1113
- }
1114
- };
1115
- var RpcArgumentCountError = class extends Schema.TaggedError()("RpcArgumentCountError", {
1116
- definition: Schema.String,
1117
- method: Schema.String,
1118
- expected: Schema.Number,
1119
- actual: Schema.Number
1120
- }) {
1121
- get message() {
1122
- return `${this.definition} RPC method "${this.method}" expected ${this.expected} arguments but received ${this.actual}`;
1123
- }
1124
- };
1125
- var RpcArgumentDecodeError = class extends Schema.TaggedError()("RpcArgumentDecodeError", {
1126
- definition: Schema.String,
1127
- method: Schema.String,
1128
- cause: Schema.Defect()
1129
- }) {
1130
- get message() {
1131
- return `${this.definition} RPC method "${this.method}" argument decode failed: ${causeMessage(this.cause)}`;
1132
- }
1133
- };
1134
- var RpcArgumentEncodeError = class extends Data.TaggedError("RpcArgumentEncodeError") {
1135
- get message() {
1136
- return `${this.definition} RPC method "${this.method}" argument encode failed: ${causeMessage(this.cause)}`;
1137
- }
1138
- };
1139
- var RpcSuccessDecodeError = class extends Data.TaggedError("RpcSuccessDecodeError") {
1140
- get message() {
1141
- return `${this.definition} RPC method "${this.method}" success decode failed: ${causeMessage(this.cause)}`;
1142
- }
1143
- };
1144
- var RpcSuccessEncodeError = class extends Schema.TaggedError()("RpcSuccessEncodeError", {
1145
- definition: Schema.String,
1146
- method: Schema.String,
1147
- cause: Schema.Defect()
1148
- }) {
1149
- get message() {
1150
- return `${this.definition} RPC method "${this.method}" success encode failed: ${causeMessage(this.cause)}`;
1151
- }
1152
- };
1153
- const WireErrorSchema = Schema.Union([
1154
- RpcArgumentCountError,
1155
- RpcArgumentDecodeError,
1156
- RpcSuccessEncodeError
1157
- ]);
1158
- const wireErrorKey = "effect-cf/RpcDefinition/wireError";
1159
- const isWireError = (error) => error instanceof RpcArgumentCountError || error instanceof RpcArgumentDecodeError || error instanceof RpcSuccessEncodeError;
1160
- /**
1161
- * Encodes package RPC errors into a plain `Error` envelope so their tags
1162
- * survive Cloudflare RPC serialization, which drops custom error properties.
1163
- */
1164
- const encodeWireError = (error) => {
1165
- if (!isWireError(error)) return error;
1166
- try {
1167
- return new Error(JSON.stringify({ [wireErrorKey]: Schema.encodeSync(WireErrorSchema)(error) }));
1168
- } catch {
1169
- return error;
1170
- }
1171
- };
1172
- const decodeWireError = (cause) => {
1173
- if (!(cause instanceof Error)) return cause;
1174
- try {
1175
- const parsed = Schema.decodeUnknownSync(Schema.Unknown)(JSON.parse(cause.message));
1176
- if (!Predicate.hasProperty(parsed, wireErrorKey)) return cause;
1177
- return Schema.decodeUnknownSync(WireErrorSchema)(parsed[wireErrorKey]);
1178
- } catch {
1179
- return cause;
1180
- }
1181
- };
1182
- const reservedMethodNames$4 = /* @__PURE__ */ new Set([
1183
- "constructor",
1184
- "fetch",
1185
- "connect",
1186
- "alarm",
1187
- "webSocketMessage",
1188
- "webSocketClose",
1189
- "webSocketError",
1190
- "then",
1191
- "dup",
1192
- "dispose",
1193
- "serialize",
1194
- "deserialize"
1195
- ]);
1196
- /**
1197
- * Workers RPC structured-clones every value that crosses an isolate boundary
1198
- * and rejects class instances. Declaration schemas such as `Schema.Result`
1199
- * keep their container instance in their `Encoded` form, so the declared
1200
- * schemas are lowered to their canonical JSON codec before touching the wire.
1201
- */
1202
- const wireCodec = (schema) => Schema.toCodecJson(schema);
1203
- const assertNoReservedMethods = (target, methods, reserved) => {
1204
- for (const method of Object.keys(methods)) if (reserved.has(method)) throw new RpcReservedMethodNameError({
1205
- definition: target,
1206
- method
1207
- });
1208
- };
1209
- function method$2(definition) {
1210
- return {
1211
- args: definition.args ?? [],
1212
- success: definition.success
1213
- };
1214
- }
1215
- const decodeArgs = Effect.fnUntraced(function* (definition, methodName, args) {
1216
- const methodDefinition = definition.methods[methodName];
1217
- if (args.length !== methodDefinition.args.length) return yield* new RpcArgumentCountError({
1218
- definition: definition.id,
1219
- method: methodName,
1220
- expected: methodDefinition.args.length,
1221
- actual: args.length
1222
- });
1223
- return yield* Schema.decodeUnknownEffect(wireCodec(Schema.Tuple(methodDefinition.args)))(args).pipe(Effect.mapError((cause) => new RpcArgumentDecodeError({
1224
- definition: definition.id,
1225
- method: methodName,
1226
- cause
1227
- })));
1228
- });
1229
- const encodeArgs = Effect.fnUntraced(function* (definition, methodName, args) {
1230
- const methodDefinition = definition.methods[methodName];
1231
- if (args.length !== methodDefinition.args.length) return yield* new RpcArgumentCountError({
1232
- definition: definition.id,
1233
- method: methodName,
1234
- expected: methodDefinition.args.length,
1235
- actual: args.length
1236
- });
1237
- return yield* Schema.encodeUnknownEffect(wireCodec(Schema.Tuple(methodDefinition.args)))(args).pipe(Effect.mapError((cause) => new RpcArgumentEncodeError({
1238
- definition: definition.id,
1239
- method: methodName,
1240
- cause
1241
- })));
1242
- });
1243
- const encodeSuccess = (definition, methodName, value) => {
1244
- const methodDefinition = definition.methods[methodName];
1245
- return Schema.encodeUnknownEffect(wireCodec(methodDefinition.success))(value).pipe(Effect.mapError((cause) => new RpcSuccessEncodeError({
1246
- definition: definition.id,
1247
- method: methodName,
1248
- cause
1249
- })));
1250
- };
1251
- const decodeSuccess = (definition, methodName, value) => {
1252
- const methodDefinition = definition.methods[methodName];
1253
- return Schema.decodeUnknownEffect(wireCodec(methodDefinition.success))(value).pipe(Effect.mapError((cause) => new RpcSuccessDecodeError({
1254
- definition: definition.id,
1255
- method: methodName,
1256
- cause
1257
- })));
1258
- };
1259
- const make$11 = (id, methods) => {
1260
- assertNoReservedMethods(id, methods, reservedMethodNames$4);
1261
- return {
1262
- id,
1263
- methods
1264
- };
1265
- };
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
1361
- //#region src/internal/Entrypoint.ts
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);
1375
- };
1376
- const provideEntrypointServices = (layer, services) => layer.pipe(Layer.provideMerge(services));
1377
- const defineEntrypointRpcMethods = (target, prototype, rpc, reservedMethodNames, run, onExit, rpcTracing) => {
1378
- const methods = rpc ?? {};
1379
- assertNoReservedMethods(target, methods, reservedMethodNames);
1380
- for (const [key, method] of Object.entries(methods)) Object.defineProperty(prototype, key, {
1381
- enumerable: true,
1382
- value(...args) {
1383
- return invokeEntrypointRpcMethod(this, method, args, run, onExit, target, key, rpcTracing);
1384
- }
1385
- });
1386
- };
1387
- const assumeEntrypointClass = (entrypoint) => {
1388
- return entrypoint;
1389
- };
1390
- //#endregion
1391
- //#region src/internal/Runtime.ts
1392
- /**
1393
- * Assembles the shared `ManagedRuntime` used by the Cloudflare entrypoint
1394
- * classes (Worker, Durable Object, Workflow).
1395
- *
1396
- * The entrypoint-specific services are merged with the env-backed
1397
- * `ConfigProvider` and `WorkerEnvironment`, then provided to the user-supplied
1398
- * layer so the resulting runtime satisfies both the user services and the
1399
- * platform services.
1400
- */
1401
- const makeEntrypointRuntime = (layer, env, services) => {
1402
- const entrypointServices = Layer.mergeAll(services, ConfigProvider.layer(WorkerConfig.providerFromEnv(env)), Layer.succeed(WorkerEnvironment, env));
1403
- return ManagedRuntime.make(provideEntrypointServices(layer, entrypointServices));
1404
- };
1405
- function runEventPromise(...args) {
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));
1413
- }
1414
- //#endregion
1415
- //#region src/internal/Telemetry.ts
1416
- /** Maximum event lifetime spent on an internally scheduled telemetry flush. */
1417
- const scheduledFlushTimeout = "2 seconds";
1418
- /**
1419
- * Schedules a configured OTLP flusher through the current Cloudflare event.
1420
- *
1421
- * The handed-off effect is best-effort: it settles within two seconds and
1422
- * silently absorbs every failure cause so telemetry cannot extend or fail the
1423
- * user event, or recursively log through an unhealthy exporter.
1424
- */
1425
- const scheduleTelemetryFlush$2 = (waitUntil) => Effect.gen(function* () {
1426
- const flusher = yield* Effect.serviceOption(OtlpExporter.Flusher);
1427
- if (Option.isNone(flusher)) return;
1428
- yield* waitUntil(flusher.value.flush.pipe(Effect.timeoutOption(scheduledFlushTimeout), Effect.ignoreCause, Effect.asVoid));
1429
- }).pipe(Effect.ignoreCause);
1430
- //#endregion
1431
- //#region src/Rpc.ts
1432
- var Rpc_exports = /* @__PURE__ */ __exportAll({
1433
- RpcStub: () => RpcStub,
1434
- RpcTarget: () => RpcTarget,
1435
- dispose: () => dispose,
1436
- isDisposable: () => isDisposable,
1437
- resolve: () => resolve,
1438
- scoped: () => scoped
1439
- });
1440
- const isDisposable = (value) => Predicate.hasProperty(value, Symbol.dispose) && Predicate.isFunction(value[Symbol.dispose]);
1441
- const dispose = (value) => Effect.sync(() => {
1442
- if (isDisposable(value)) value[Symbol.dispose]();
1443
- });
1444
- const resolve = (value) => Predicate.isPromiseLike(value) ? Effect.tryPromise({
1445
- try: () => Promise.resolve(value),
1446
- catch: (cause) => decodeWireError(cause)
1447
- }) : Effect.sync(() => {
1448
- return value;
1449
- });
1450
- const scoped = (value) => Effect.acquireRelease(resolve(value), (resolved) => dispose(resolved));
1451
- //#endregion
1452
- //#region src/ServiceBinding.ts
1453
- var ServiceBinding_exports = /* @__PURE__ */ __exportAll({
1454
- Service: () => Service,
1455
- ServiceBindingFetchError: () => ServiceBindingFetchError,
1456
- ServiceBindingRpcError: () => ServiceBindingRpcError,
1457
- isServiceBindingClient: () => isServiceBindingClient,
1458
- layer: () => layer$10,
1459
- makeClient: () => makeClient$8,
1460
- makeDirectMethods: () => makeDirectMethods$1
1461
- });
1462
- const TypeId$1 = "effect-cf/ServiceBinding";
1463
- const expectedServiceBinding = "Worker service binding with fetch()";
1464
- /**
1465
- * Failure raised when calling `fetch` on a service binding.
1466
- */
1467
- var ServiceBindingFetchError = class extends Data.TaggedError("ServiceBindingFetchError") {
1468
- get message() {
1469
- return `Service binding "${this.binding}" fetch failed: ${causeMessage(this.cause)}`;
1470
- }
1471
- };
1472
- /**
1473
- * Failure raised when invoking an RPC method on a service binding.
1474
- */
1475
- var ServiceBindingRpcError = class extends Data.TaggedError("ServiceBindingRpcError") {
1476
- get message() {
1477
- return `Service binding "${this.binding}" RPC method "${this.method}" failed: ${causeMessage(this.cause)}`;
1478
- }
1479
- };
1480
- const ServiceBindingSchema = Schema.declare((value) => Predicate.hasProperty(value, "fetch") && Predicate.isFunction(value.fetch));
1481
- const decodeServiceBinding = Schema.decodeUnknownOption(ServiceBindingSchema);
1482
- const isServiceBindingClient = (value) => Option.isSome(decodeServiceBinding(value));
1483
- const makeClient$8 = (definition) => {
1484
- return (service) => {
1485
- const fetch = Effect.fn("ServiceBinding.fetch")(function* (input, init) {
1486
- return yield* Effect.tryPromise({
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
- },
1494
- catch: (cause) => new ServiceBindingFetchError({
1495
- binding: definition.binding,
1496
- cause
1497
- })
1498
- });
1499
- });
1500
- const rpc = Effect.fnUntraced(function* (method, ...args) {
1501
- const methodName = String(method);
1502
- const encodedArgs = definition.definition === void 0 ? args : yield* encodeArgs(definition.definition, methodName, args).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1503
- binding: definition.binding,
1504
- method: methodName,
1505
- cause
1506
- })));
1507
- const nativeArgs = definition.rpcTracing ? yield* withRpcTraceContext(encodedArgs) : encodedArgs;
1508
- return yield* invokeRpcMethod(service, method, nativeArgs, (cause) => new ServiceBindingRpcError({
1509
- binding: definition.binding,
1510
- method: methodName,
1511
- cause
1512
- }));
1513
- });
1514
- const decodeSuccess$2 = Effect.fnUntraced(function* (methodName, value) {
1515
- if (definition.definition === void 0) return value;
1516
- return yield* decodeSuccess(definition.definition, methodName, value).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1517
- binding: definition.binding,
1518
- method: methodName,
1519
- cause
1520
- })));
1521
- });
1522
- const call = Effect.fnUntraced(function* (method, ...args) {
1523
- const methodName = String(method);
1524
- const value = yield* resolve(yield* rpc(method, ...args)).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1525
- binding: definition.binding,
1526
- method: methodName,
1527
- cause
1528
- })));
1529
- return yield* decodeSuccess$2(methodName, value);
1530
- }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[0])));
1531
- const scopedCall = Effect.fnUntraced(function* (method, ...args) {
1532
- const methodName = String(method);
1533
- const result = yield* rpc(method, ...args);
1534
- const value = yield* scoped(result).pipe(Effect.mapError((cause) => new ServiceBindingRpcError({
1535
- binding: definition.binding,
1536
- method: methodName,
1537
- cause
1538
- })));
1539
- return yield* decodeSuccess$2(methodName, value);
1540
- }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[0])));
1541
- const directMethods = makeDirectMethods$1(definition.definition, call);
1542
- return Object.assign(directMethods, {
1543
- fetch,
1544
- rpc,
1545
- call,
1546
- scopedCall
1547
- });
1548
- };
1549
- };
1550
- const layer$10 = (tag, definition) => layer$19(tag, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition), { expected: expectedServiceBinding });
1551
- const Service = () => (id, definition) => {
1552
- const tag = Service$2()(id, definition.binding, (value) => isServiceBindingClient(value), makeClient$8(definition));
1553
- const fetch = Effect.fnUntraced(function* (input, init) {
1554
- return yield* (yield* tag).fetch(input, init);
1555
- });
1556
- const rpc = Effect.fnUntraced(function* (method, ...args) {
1557
- return yield* (yield* tag).rpc(method, ...args);
1558
- });
1559
- const call = Effect.fnUntraced(function* (method, ...args) {
1560
- return yield* (yield* tag).call(method, ...args);
1561
- });
1562
- const scopedCall = Effect.fnUntraced(function* (method, ...args) {
1563
- return yield* (yield* tag).scopedCall(method, ...args);
1564
- });
1565
- const directMethods = makeDirectMethods$1(definition.definition, call);
1566
- return Object.assign(tag, directMethods, {
1567
921
  [TypeId$1]: TypeId$1,
1568
922
  definition,
1569
- fetch,
1570
- rpc,
1571
- call,
1572
- scopedCall
1573
- });
1574
- };
1575
- const makeDirectMethods$1 = (rpcDefinition, call) => {
1576
- const methods = {};
1577
- if (rpcDefinition !== void 0) {
1578
- const invoke = call;
1579
- for (const methodName of Object.keys(rpcDefinition.methods)) methods[methodName] = (...args) => invoke(methodName, ...args);
1580
- }
1581
- return methods;
1582
- };
1583
- //#endregion
1584
- //#region src/WorkerDefinition.ts
1585
- var WorkerDefinition_exports = /* @__PURE__ */ __exportAll({
1586
- Tag: () => Tag$9,
1587
- Worker: () => Worker,
1588
- implement: () => implement$3,
1589
- make: () => make$10,
1590
- method: () => method$1
1591
- });
1592
- const reservedMethodNames$3 = /* @__PURE__ */ new Set([
1593
- "constructor",
1594
- "dup",
1595
- "fetch",
1596
- "connect",
1597
- "queue",
1598
- "scheduled",
1599
- "tail",
1600
- "tailStream",
1601
- "test",
1602
- "trace",
1603
- "alarm",
1604
- "webSocketMessage",
1605
- "webSocketClose",
1606
- "webSocketError"
1607
- ]);
1608
- const assumeTagClass = (value) => {
1609
- return value;
1610
- };
1611
- /**
1612
- * Defines a single RPC method schema in a worker definition.
1613
- */
1614
- const method$1 = method$2;
1615
- const makeDefinition$3 = (id, methods) => {
1616
- assertNoReservedMethods("Worker", methods, reservedMethodNames$3);
1617
- const definition = make$11(id, methods);
1618
- return Object.assign(definition, { make: (layer, options) => {
1619
- const workerOptions = {
1620
- ...options,
1621
- rpc: wrapHandlers$1(definition, options.rpc)
1622
- };
1623
- if (workerOptions.eventLayer === void 0) return make$9(layer, workerOptions);
1624
- return make$9(layer, workerOptions);
1625
- } });
1626
- };
1627
- const make$10 = (id, methods) => Tag$9()(id, methods);
1628
- const Tag$9 = () => (id, methods) => {
1629
- const definition = makeDefinition$3(id, methods);
1630
- const tag = Context.Service()(id);
1631
- const bindingDefinition = (binding) => ({
1632
- ...binding,
1633
- definition
1634
- });
1635
- const layer = (binding) => layer$10(tag, bindingDefinition(binding));
1636
- const fetch = (input, init) => Effect.gen(function* () {
1637
- return yield* (yield* tag).fetch(input, init);
1638
- });
1639
- const rpc = (method, ...args) => Effect.gen(function* () {
1640
- return yield* (yield* tag).rpc(method, ...args);
1641
- });
1642
- const call = (method, ...args) => Effect.gen(function* () {
1643
- return yield* (yield* tag).call(method, ...args);
1644
- });
1645
- const scopedCall = (method, ...args) => Effect.gen(function* () {
1646
- return yield* (yield* tag).scopedCall(method, ...args);
923
+ sqlLayer
1647
924
  });
1648
- const directMethods = makeDirectMethods$1(definition, call);
1649
- return assumeTagClass(Object.assign(tag, directMethods, {
1650
- id: definition.id,
1651
- methods: definition.methods,
1652
- make: definition.make,
1653
- layer,
1654
- fetch,
1655
- rpc,
1656
- call,
1657
- scopedCall
1658
- }));
1659
- };
1660
- const Worker = Tag$9;
1661
- const wrapHandlers$1 = (definition, handlers) => {
1662
- const wrapped = Object.create(null);
1663
- for (const key of Object.keys(definition.methods)) {
1664
- const handler = handlers[key];
1665
- wrapped[key] = (...args) => Effect.gen(function* () {
1666
- const decodedArgs = yield* decodeArgs(definition, key, args);
1667
- yield* recordDecodedArgs(decodedArgs);
1668
- const value = yield* handler(...decodedArgs);
1669
- return yield* encodeSuccess(definition, key, value);
1670
- });
1671
- }
1672
- return wrapped;
1673
925
  };
1674
- /**
1675
- * Helper for implementing handlers with the exact method shape of a definition.
1676
- */
1677
- const implement$3 = (_definition, handlers) => handlers;
1678
- //#endregion
1679
- //#region src/Worker.ts
1680
- var Worker_exports = /* @__PURE__ */ __exportAll({
1681
- ExecutionContext: () => ExecutionContext,
1682
- NativeRequest: () => NativeRequest,
1683
- RunSymbol: () => RunSymbol$1,
1684
- Tag: () => Tag$9,
1685
- WorkerContext: () => WorkerContext,
1686
- implement: () => implement$3,
1687
- isWebSocketUpgrade: () => isWebSocketUpgrade,
1688
- make: () => make$9,
1689
- makeFetchHandler: () => makeFetchHandler,
1690
- method: () => method$1
1691
- });
1692
- var ExecutionContext = class extends Context.Service()("effect-cf/ExecutionContext") {};
1693
- var WorkerContext = class extends Context.Service()("effect-cf/WorkerContext") {};
1694
- var NativeRequest = class extends Context.Service()("effect-cf/NativeRequest") {};
1695
- const isWebSocketUpgrade = (request) => request.headers.get("Upgrade")?.toLowerCase() === "websocket";
1696
- const reservedMethodNames$2 = /* @__PURE__ */ new Set([
1697
- ...reservedMethodNames$4,
1698
- "queue",
1699
- "scheduled",
1700
- "tail",
1701
- "tailStream",
1702
- "test",
1703
- "trace"
1704
- ]);
1705
- /** Override to instrument the whole event, then call super[RunSymbol]. */
1706
- const RunSymbol$1 = Symbol.for("effect-cf/Worker/run");
1707
- const FetchSymbol = Symbol.for("effect-cf/Worker/fetch");
1708
- const renderFetchSuccess = (effect, eventLayer) => Effect.suspend(() => {
1709
- let nativeResponse;
1710
- let webResponse;
1711
- const httpApp = Effect.flatMap(effect, (response) => {
1712
- if (response instanceof Response) {
1713
- nativeResponse = response;
1714
- return Effect.succeed(HttpServerResponse.empty());
1715
- }
1716
- return Effect.succeed(response);
1717
- });
1718
- const handleResponse = (request, response) => nativeResponse !== void 0 ? Effect.void : Effect.map(Effect.context(), (context) => {
1719
- webResponse = HttpServerResponse.toWeb(HttpEffect.scopeTransferToStream(response), {
1720
- withoutBody: request.method === "HEAD",
1721
- context
1722
- });
1723
- });
1724
- const telemetryMiddleware = HttpMiddleware.make((self) => Effect.gen(function* () {
1725
- yield* Effect.addFinalizer(() => scheduleTelemetryFlush$1);
1726
- return yield* self;
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)));
1733
- const captured = () => nativeResponse ?? webResponse ?? new Response(null, { status: 500 });
1734
- return Effect.matchCause(handled, {
1735
- onFailure: captured,
1736
- onSuccess: captured
1737
- });
1738
- });
1739
- const isWorkerOptions = (options) => !Effect.isEffect(options);
1740
- /**
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.
1744
- *
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.
1748
- */
1749
- const scheduleTelemetryFlush$1 = scheduleTelemetryFlush$2((flush) => Effect.flatMap(WorkerContext, (workerContext) => workerContext.waitUntil(flush)));
1750
- function make$9(layer, optionsOrFetch) {
1751
- const options = isWorkerOptions(optionsOrFetch) ? optionsOrFetch : { fetch: optionsOrFetch };
1752
- class EffectWorker extends WorkerEntrypoint {
1753
- runtime;
1754
- constructor(ctx, env) {
1755
- super(ctx, env);
1756
- this.runtime = makeEntrypointRuntime(layer, env, Layer.mergeAll(Layer.succeed(ExecutionContext, ctx), Layer.succeed(WorkerContext, fromExecutionContext(ctx))));
1757
- }
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);
1764
- }
1765
- fetch(request) {
1766
- return this[FetchSymbol](request);
1767
- }
1768
- [FetchSymbol](request, requestContext) {
1769
- const fetchHandler = options.fetch;
1770
- if (fetchHandler === void 0) return Promise.resolve(new Response("Not Found", { status: 404 }));
1771
- const ctx = requestContext ?? this.ctx;
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)));
1773
- return this[RunSymbol$1](renderFetchSuccess(fetchHandler, options.eventLayer).pipe(Effect.provide(requestServices)), { event: "fetch" });
1774
- }
1775
- queue(batch) {
1776
- const queueHandler = options.queue;
1777
- if (queueHandler === void 0) return Promise.resolve();
1778
- const messages = batch.messages.map((message) => fromMessage(message, message.body));
1779
- return this[RunSymbol$1](queueHandler(fromMessageBatch(batch, messages)).pipe(Effect.onExit(() => scheduleTelemetryFlush$1)), { event: "queue" });
1780
- }
1781
- }
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);
1786
- return assumeEntrypointClass(EffectWorker);
1787
- }
1788
- function makeFetchHandler(layer, options) {
1789
- const WorkerClass = options.eventLayer === void 0 ? make$9(layer, options) : make$9(layer, options);
1790
- const instances = /* @__PURE__ */ new WeakMap();
1791
- return { fetch: (request, env, ctx) => {
1792
- let instance = instances.get(env);
1793
- if (instance === void 0) {
1794
- instance = new WorkerClass(ctx, env);
1795
- instances.set(env, instance);
1796
- }
1797
- return instance[FetchSymbol](request, ctx);
1798
- } };
1799
- }
1800
926
  //#endregion
1801
927
  //#region src/DurableObjectNamespace.ts
1802
928
  var DurableObjectNamespace_exports = /* @__PURE__ */ __exportAll({
@@ -1854,8 +980,7 @@ const makeClient$7 = (definition) => {
1854
980
  method: methodName,
1855
981
  cause
1856
982
  })));
1857
- const nativeArgs = definition.rpcTracing ? yield* withRpcTraceContext(encodedArgs) : encodedArgs;
1858
- return yield* invokeRpcMethod(stub, method, nativeArgs, (cause) => new DurableObjectRpcError({
983
+ return yield* invokeRpcMethod(stub, method, definition.rpcTracing ? yield* withRpcTraceContext(encodedArgs) : encodedArgs, (cause) => new DurableObjectRpcError({
1859
984
  binding: definition.binding,
1860
985
  method: methodName,
1861
986
  cause
@@ -1880,8 +1005,7 @@ const makeClient$7 = (definition) => {
1880
1005
  }, (effect, ...args) => withRpcClientSpan(effect, definition.binding, String(args[1])));
1881
1006
  const scopedCall = Effect.fnUntraced(function* (stub, method, ...args) {
1882
1007
  const methodName = String(method);
1883
- const result = yield* rpc(stub, method, ...args);
1884
- const value = yield* scoped(result).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1008
+ const value = yield* scoped(yield* rpc(stub, method, ...args)).pipe(Effect.mapError((cause) => new DurableObjectRpcError({
1885
1009
  binding: definition.binding,
1886
1010
  method: methodName,
1887
1011
  cause
@@ -1909,7 +1033,7 @@ const makeClient$7 = (definition) => {
1909
1033
  });
1910
1034
  };
1911
1035
  };
1912
- 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 });
1913
1037
  const makeDirectMethods = (rpcDefinition, helpers) => {
1914
1038
  const methods = {};
1915
1039
  if (rpcDefinition !== void 0) {
@@ -1949,11 +1073,11 @@ const reservedMethodNames$1 = /* @__PURE__ */ new Set([
1949
1073
  "webSocketError"
1950
1074
  ]);
1951
1075
  function method(definition) {
1952
- return method$2(definition);
1076
+ return method$1(definition);
1953
1077
  }
1954
1078
  const makeDefinition$2 = (id, methods) => {
1955
1079
  assertNoReservedMethods("Durable Object", methods, reservedMethodNames$1);
1956
- const definition = make$11(id, methods);
1080
+ const definition = make$15(id, methods);
1957
1081
  return Object.assign(definition, { make: (layer, options) => make$7(layer, {
1958
1082
  ...options,
1959
1083
  rpc: wrapHandlers(definition, options.rpc)
@@ -2056,10 +1180,10 @@ var DurableObject_exports = /* @__PURE__ */ __exportAll({
2056
1180
  make: () => make$7,
2057
1181
  method: () => method
2058
1182
  });
2059
- const reservedMethodNames = reservedMethodNames$4;
1183
+ const reservedMethodNames = reservedMethodNames$2;
2060
1184
  /** Override to instrument the whole event, then call super[RunSymbol]. */
2061
1185
  const RunSymbol = Symbol.for("effect-cf/DurableObject/run");
2062
- 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)));
2063
1187
  /**
2064
1188
  * Builds a Durable Object whose base `layer` lives for the in-memory instance.
2065
1189
  * Cloudflare does not expose an eviction or shutdown hook, so finalizers in
@@ -2306,25 +1430,35 @@ var DurableObjectAlarm = class DurableObjectAlarm extends Context.Service()("eff
2306
1430
  });
2307
1431
  const cancelAlarm = Effect.fn("DurableObjectAlarm.cancelAlarm")(function* (input) {
2308
1432
  const ref = yield* decodeAlarmRef(input);
2309
- yield* state.storage.transaction(() => Effect.gen(function* () {
2310
- yield* ensureTable(state);
2311
- yield* state.storage.sql.exec(`DELETE FROM effect_cf_scheduled_alarms WHERE storage_id = ?`, getScheduledEventId(ref)).pipe(Effect.asVoid);
2312
- yield* reconcileAlarm();
2313
- }));
1433
+ yield* state.storage.sql.exec(`DELETE FROM effect_cf_scheduled_alarms WHERE storage_id = ?`, getScheduledEventId(ref));
2314
1434
  });
2315
1435
  const scheduleAlarm = Effect.fn("DurableObjectAlarm.scheduleAlarm")(function* (input) {
2316
1436
  const ref = yield* decodeAlarmRef(input);
2317
1437
  const repeatEveryMillis = yield* toRepeatEveryMillis(input.repeatEvery);
2318
1438
  const payload = yield* encodeStoredPayload(input.payload);
2319
1439
  const runAt = DateTime.toEpochMillis(input.runAt);
2320
- yield* state.storage.transaction(() => Effect.gen(function* () {
2321
- yield* ensureTable(state);
2322
- yield* state.storage.sql.exec(`INSERT OR REPLACE INTO effect_cf_scheduled_alarms
1440
+ yield* state.storage.sql.exec(`INSERT OR REPLACE INTO effect_cf_scheduled_alarms
2323
1441
  (storage_id, alarm_id, tag, run_at, repeat_every_ms, payload)
2324
- VALUES (?, ?, ?, ?, ?, ?)`, getScheduledEventId(ref), ref.id, ref.tag, runAt, repeatEveryMillis, payload).pipe(Effect.asVoid);
2325
- yield* reconcileAlarm();
2326
- }));
1442
+ VALUES (?, ?, ?, ?, ?, ?)`, getScheduledEventId(ref), ref.id, ref.tag, runAt, repeatEveryMillis, payload);
2327
1443
  });
1444
+ const transaction = (closure) => state.storage.transaction(() => Effect.withFiber((owner) => {
1445
+ let active = true;
1446
+ const requireActive = (effect) => Effect.withFiber((fiber) => active && fiber === owner ? effect : Effect.fail(new StorageOperationError({
1447
+ operation: "alarm.transaction",
1448
+ cause: /* @__PURE__ */ new Error("Alarm mutations require their active transaction callback")
1449
+ })));
1450
+ return Effect.gen(function* () {
1451
+ yield* ensureTable(state);
1452
+ const result = yield* Effect.suspend(() => closure({
1453
+ cancelAlarm: (input) => requireActive(cancelAlarm(input)),
1454
+ scheduleAlarm: (input) => requireActive(scheduleAlarm(input))
1455
+ })).pipe(Effect.ensuring(Effect.sync(() => {
1456
+ active = false;
1457
+ })));
1458
+ yield* reconcileAlarm();
1459
+ return result;
1460
+ });
1461
+ }));
2328
1462
  const processDueAlarms = Effect.fn("DurableObjectAlarm.processDueAlarms")(function* (handle, options) {
2329
1463
  yield* ensureTable(state);
2330
1464
  const mode = options?.mode ?? "isolated";
@@ -2383,9 +1517,10 @@ var DurableObjectAlarm = class DurableObjectAlarm extends Context.Service()("eff
2383
1517
  };
2384
1518
  });
2385
1519
  return DurableObjectAlarm.of({
2386
- cancelAlarm,
1520
+ cancelAlarm: (input) => transaction((alarms) => alarms.cancelAlarm(input)),
2387
1521
  processDueAlarms,
2388
- scheduleAlarm
1522
+ scheduleAlarm: (input) => transaction((alarms) => alarms.scheduleAlarm(input)),
1523
+ transaction
2389
1524
  });
2390
1525
  }).pipe(Effect.withSpan("DurableObjectAlarm.layer")));
2391
1526
  };
@@ -3158,7 +2293,7 @@ const makeClient$6 = (definition, options) => (email) => {
3158
2293
  rawUnsafe: Effect.succeed(email)
3159
2294
  };
3160
2295
  };
3161
- const layer$6 = (tag, definition) => layer$19(tag, definition.binding, isEmailBinding, makeClient$6(definition, definition.send), { expected: expectedSendEmailBinding });
2296
+ const layer$6 = (tag, definition) => layer$17(tag, definition.binding, isEmailBinding, makeClient$6(definition, definition.send), { expected: expectedSendEmailBinding });
3162
2297
  const make$6 = (id) => Tag$7()(id);
3163
2298
  const Tag$7 = () => (id) => {
3164
2299
  const tag = Context.Service()(id);
@@ -3184,7 +2319,7 @@ const makeClient$5 = (definition) => (hyperdrive) => ({
3184
2319
  connectionString: hyperdrive.connectionString,
3185
2320
  rawUnsafe: Effect.succeed(hyperdrive)
3186
2321
  });
3187
- const layer$5 = (tag, definition) => layer$19(tag, definition.binding, isHyperdrive, makeClient$5(definition), { expected: expectedHyperdrive });
2322
+ const layer$5 = (tag, definition) => layer$17(tag, definition.binding, isHyperdrive, makeClient$5(definition), { expected: expectedHyperdrive });
3188
2323
  const make$5 = (id) => Tag$6()(id);
3189
2324
  const Tag$6 = () => (id) => {
3190
2325
  const tag = Context.Service()(id);
@@ -3286,7 +2421,7 @@ const makeClient$4 = (definition) => (images) => {
3286
2421
  rawUnsafe: Effect.succeed(images)
3287
2422
  };
3288
2423
  };
3289
- const layer$4 = (tag, definition) => layer$19(tag, definition.binding, isImagesBinding, makeClient$4(definition), { expected: expectedImagesBinding });
2424
+ const layer$4 = (tag, definition) => layer$17(tag, definition.binding, isImagesBinding, makeClient$4(definition), { expected: expectedImagesBinding });
3290
2425
  const make$4 = (id) => Tag$5()(id);
3291
2426
  const Tag$5 = () => (id) => {
3292
2427
  const tag = Context.Service()(id);
@@ -3394,7 +2529,7 @@ const makeClient$3 = (definition) => {
3394
2529
  rawUnsafe: Effect.succeed(kv)
3395
2530
  });
3396
2531
  };
3397
- const layer$3 = (tag, definition) => layer$19(tag, definition.binding, isKvNamespace, makeClient$3(definition), { expected: expectedKvNamespace });
2532
+ const layer$3 = (tag, definition) => layer$17(tag, definition.binding, isKvNamespace, makeClient$3(definition), { expected: expectedKvNamespace });
3398
2533
  const makeDefinition$1 = (id, definition) => {
3399
2534
  const kvDefinition = {
3400
2535
  id,
@@ -3515,7 +2650,7 @@ const makeClient$2 = (definition) => {
3515
2650
  };
3516
2651
  };
3517
2652
  };
3518
- const layer$2 = (tag, definition) => layer$19(tag, definition.binding, isR2Bucket, makeClient$2(definition), { expected: expectedR2Bucket });
2653
+ const layer$2 = (tag, definition) => layer$17(tag, definition.binding, isR2Bucket, makeClient$2(definition), { expected: expectedR2Bucket });
3519
2654
  const make$3 = (id) => Tag$3()(id);
3520
2655
  const Tag$3 = () => (id) => {
3521
2656
  const tag = Context.Service()(id);
@@ -3581,7 +2716,7 @@ const makeClient$1 = (definition) => (index) => {
3581
2716
  rawUnsafe: Effect.succeed(index)
3582
2717
  };
3583
2718
  };
3584
- const layer$1 = (tag, definition) => layer$19(tag, definition.binding, isVectorizeBinding, makeClient$1(definition), { expected: expectedVectorizeBinding });
2719
+ const layer$1 = (tag, definition) => layer$17(tag, definition.binding, isVectorizeBinding, makeClient$1(definition), { expected: expectedVectorizeBinding });
3585
2720
  const make$2 = (id) => Tag$2()(id);
3586
2721
  const Tag$2 = () => (id) => {
3587
2722
  const tag = Context.Service()(id);
@@ -3736,7 +2871,7 @@ const makeClient = (definition) => {
3736
2871
  rawUnsafe: Effect.succeed(workflow)
3737
2872
  });
3738
2873
  };
3739
- const layer = (tag, definition) => layer$19(tag, definition.binding, (value) => isWorkflow(value), makeClient(definition), { expected: expectedWorkflow });
2874
+ const layer = (tag, definition) => layer$17(tag, definition.binding, (value) => isWorkflow(value), makeClient(definition), { expected: expectedWorkflow });
3740
2875
  //#endregion
3741
2876
  //#region src/WorkflowDefinition.ts
3742
2877
  var WorkflowDefinition_exports = /* @__PURE__ */ __exportAll({
@@ -3757,7 +2892,7 @@ const make$1 = (id, definition) => Tag$1()(id, definition);
3757
2892
  const Tag$1 = () => (id, definition) => {
3758
2893
  const workflowDefinition = makeDefinition(id, definition);
3759
2894
  const tag = Context.Service()(`effect-cf/Workflow/${id}`);
3760
- const layer$20 = (binding) => layer(tag, {
2895
+ const layer$18 = (binding) => layer(tag, {
3761
2896
  ...binding,
3762
2897
  payload: definition.payload,
3763
2898
  result: definition.result
@@ -3777,7 +2912,7 @@ const Tag$1 = () => (id, definition) => {
3777
2912
  payload: workflowDefinition.payload,
3778
2913
  result: workflowDefinition.result,
3779
2914
  make: workflowDefinition.make,
3780
- layer: layer$20,
2915
+ layer: layer$18,
3781
2916
  create,
3782
2917
  createBatch,
3783
2918
  get,