@gjermundgaraba/effect-actions 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. package/README.md +9 -3
  2. package/dist/Action.d.mts +2 -2
  3. package/dist/Action.mjs +1 -0
  4. package/dist/ActionCli.d.mts +1 -1
  5. package/dist/ActionCli.mjs +1 -2
  6. package/dist/ActionHttp.d.mts +2 -2
  7. package/dist/ActionMcp.d.mts +20 -20
  8. package/dist/ActionMcp.mjs +9 -11
  9. package/dist/ActionRpc.d.mts +8 -15
  10. package/dist/ActionRpc.mjs +29 -54
  11. package/dist/ActionToolkit.d.mts +0 -2
  12. package/dist/ActionToolkit.mjs +0 -2
  13. package/dist/Event.d.mts +0 -23
  14. package/dist/Testing.mjs +3 -2
  15. package/dist/Webhook.mjs +2 -2
  16. package/dist/authentication/refusal.mjs +0 -1
  17. package/dist/cli/commands.mjs +0 -5
  18. package/dist/contract/authorizer.mjs +0 -5
  19. package/dist/contract/call.mjs +0 -23
  20. package/dist/contract/callback.mjs +0 -1
  21. package/dist/contract/caller.mjs +0 -11
  22. package/dist/contract/canonical.mjs +0 -5
  23. package/dist/contract/codec.d.mts +0 -1
  24. package/dist/contract/codec.mjs +0 -1
  25. package/dist/contract/codes.mjs +1 -15
  26. package/dist/contract/declared.mjs +0 -15
  27. package/dist/contract/digest.mjs +0 -1
  28. package/dist/contract/errors.d.mts +0 -4
  29. package/dist/contract/errors.mjs +0 -4
  30. package/dist/contract/feed.d.mts +0 -1
  31. package/dist/contract/feed.mjs +0 -20
  32. package/dist/contract/hints.mjs +0 -6
  33. package/dist/contract/hub.mjs +0 -3
  34. package/dist/contract/idempotency.mjs +0 -4
  35. package/dist/contract/implementation.d.mts +0 -1
  36. package/dist/contract/implementation.mjs +0 -27
  37. package/dist/contract/input-check.mjs +0 -1
  38. package/dist/contract/lease.mjs +0 -1
  39. package/dist/contract/listed.mjs +0 -6
  40. package/dist/contract/log.mjs +0 -8
  41. package/dist/contract/names.mjs +0 -1
  42. package/dist/contract/occurrence.mjs +0 -8
  43. package/dist/contract/pages.mjs +5 -12
  44. package/dist/contract/progress.mjs +2 -25
  45. package/dist/contract/push.d.mts +0 -5
  46. package/dist/contract/push.mjs +1 -24
  47. package/dist/contract/receiving.mjs +0 -7
  48. package/dist/contract/reported.mjs +0 -5
  49. package/dist/contract/serving.mjs +0 -18
  50. package/dist/contract/status.mjs +0 -3
  51. package/dist/contract/stream.mjs +0 -2
  52. package/dist/contract/subscribe.d.mts +0 -2
  53. package/dist/contract/subscribe.mjs +0 -8
  54. package/dist/contract/transient.mjs +0 -12
  55. package/dist/contract/watch.mjs +5 -17
  56. package/dist/contract/webhooks.mjs +0 -11
  57. package/dist/http/client.mjs +0 -1
  58. package/dist/http/events.d.mts +0 -10
  59. package/dist/http/events.mjs +2 -31
  60. package/dist/http/placed.d.mts +0 -2
  61. package/dist/http/streamed.d.mts +0 -1
  62. package/dist/http/streamed.mjs +4 -32
  63. package/dist/http/watch.mjs +0 -6
  64. package/dist/mcp/bridge.mjs +1 -26
  65. package/dist/mcp/client.d.mts +0 -1
  66. package/dist/mcp/client.mjs +0 -1
  67. package/dist/mcp/events.mjs +0 -6
  68. package/dist/mcp/progress.mjs +0 -7
  69. package/dist/mcp/protocol.mjs +0 -6
  70. package/dist/mcp/reply.mjs +0 -11
  71. package/dist/mcp/request.mjs +0 -1
  72. package/dist/mcp/watch.mjs +0 -6
  73. package/dist/rpc/watch.mjs +0 -6
  74. package/dist/stdio/console.mjs +2 -2
  75. package/dist/webhook/address.mjs +4 -9
  76. package/dist/webhook/attempt.mjs +2 -15
  77. package/dist/webhook/receiver.mjs +2 -8
  78. package/dist/webhook/signing.mjs +0 -3
  79. package/dist/webhook/stored.mjs +8 -17
  80. package/dist/webhook/subscriptions.mjs +19 -23
  81. package/docs/Action-streams.md +0 -12
  82. package/docs/Action.md +0 -10
  83. package/docs/ActionCli.md +2 -26
  84. package/docs/ActionHttp-failures.md +1 -1
  85. package/docs/ActionHttp.md +0 -28
  86. package/docs/ActionMcp-failures.md +2 -1
  87. package/docs/ActionMcp.md +2 -37
  88. package/docs/ActionRpc-events.md +0 -16
  89. package/docs/ActionRpc.md +0 -63
  90. package/docs/ActionToolkit.md +0 -11
  91. package/docs/Authentication-advanced.md +0 -31
  92. package/docs/Authentication.md +4 -13
  93. package/docs/Event.md +0 -37
  94. package/docs/README.md +1 -1
  95. package/docs/Testing-failures.md +1 -1
  96. package/docs/Testing.md +3 -13
  97. package/docs/Webhook.md +0 -46
  98. package/docs/setup-failures.md +1 -1
  99. package/docs/setup.md +5 -10
  100. package/examples/README.md +7 -1
  101. package/examples/assistant/src/agent.ts +8 -31
  102. package/examples/assistant/src/cli.ts +2 -9
  103. package/examples/assistant/src/commands.ts +0 -8
  104. package/examples/assistant/src/identity/Identity.ts +0 -10
  105. package/examples/assistant/src/identity/authorize.ts +0 -4
  106. package/examples/assistant/src/identity/members.ts +1 -3
  107. package/examples/assistant/src/identity/permissions.ts +0 -5
  108. package/examples/assistant/src/platform/tasks-file.ts +1 -6
  109. package/examples/assistant/src/scripted.ts +0 -4
  110. package/examples/assistant/src/tasks/Tasks.ts +0 -2
  111. package/examples/assistant/src/tasks/handlers.ts +0 -3
  112. package/examples/assistant/src/tasks/store.ts +0 -7
  113. package/examples/assistant/src/toolkit.ts +0 -11
  114. package/examples/assistant/test/commands.test.ts +0 -5
  115. package/examples/assistant/test/identity/identity.test.ts +6 -6
  116. package/examples/assistant/test/platform/tasks-file.test.ts +2 -6
  117. package/examples/assistant/test/tasks/tasks.test.ts +13 -14
  118. package/examples/assistant/test/toolkit.test.ts +7 -18
  119. package/examples/build-events/README.md +2 -0
  120. package/examples/build-events/src/Api.ts +0 -3
  121. package/examples/build-events/src/Rpc.ts +0 -2
  122. package/examples/build-events/src/builds/Builds.ts +0 -15
  123. package/examples/build-events/src/builds/events.ts +0 -10
  124. package/examples/build-events/src/builds/handlers.ts +0 -6
  125. package/examples/build-events/src/builds/log.ts +0 -6
  126. package/examples/build-events/src/builds/status.ts +0 -4
  127. package/examples/build-events/src/builds/store.ts +0 -21
  128. package/examples/build-events/src/cli.ts +0 -2
  129. package/examples/build-events/src/commands.ts +0 -9
  130. package/examples/build-events/src/deploys/approvers.ts +0 -3
  131. package/examples/build-events/src/deploys/events.ts +0 -8
  132. package/examples/build-events/src/deploys/handlers.ts +0 -2
  133. package/examples/build-events/src/identity/Identity.ts +0 -11
  134. package/examples/build-events/src/identity/members.ts +1 -2
  135. package/examples/build-events/src/identity/verifier.ts +8 -9
  136. package/examples/build-events/src/notifier/Notices.ts +0 -3
  137. package/examples/build-events/src/notifier/routes.ts +0 -10
  138. package/examples/build-events/src/notifier.ts +0 -8
  139. package/examples/build-events/src/routes.ts +0 -24
  140. package/examples/build-events/src/server.ts +0 -14
  141. package/examples/build-events/test/builds/events.test.ts +0 -6
  142. package/examples/build-events/test/builds/log.test.ts +0 -1
  143. package/examples/build-events/test/builds/progress.test.ts +0 -1
  144. package/examples/build-events/test/commands.test.ts +0 -5
  145. package/examples/build-events/test/deploys/events.test.ts +0 -1
  146. package/examples/build-events/test/http.test.ts +0 -4
  147. package/examples/build-events/test/notifier.test.ts +0 -9
  148. package/examples/build-events/test/routes.test.ts +0 -9
  149. package/examples/build-events/test/rpc.test.ts +0 -4
  150. package/examples/build-events/test/support/as.ts +3 -4
  151. package/examples/build-events/test/support/memory.ts +0 -5
  152. package/examples/build-events/test/webhooks.test.ts +0 -12
  153. package/examples/kitchen-sink/README.md +1 -1
  154. package/examples/kitchen-sink/src/Actions.ts +0 -10
  155. package/examples/kitchen-sink/src/Api.ts +0 -8
  156. package/examples/kitchen-sink/src/Rpc.ts +0 -4
  157. package/examples/kitchen-sink/src/admin/Admin.ts +0 -9
  158. package/examples/kitchen-sink/src/admin/authenticate.ts +2 -6
  159. package/examples/kitchen-sink/src/admin/authorize.ts +0 -5
  160. package/examples/kitchen-sink/src/admin/grants.ts +0 -5
  161. package/examples/kitchen-sink/src/admin/handlers.ts +0 -2
  162. package/examples/kitchen-sink/src/admin/keys.ts +1 -3
  163. package/examples/kitchen-sink/src/agent.ts +2 -13
  164. package/examples/kitchen-sink/src/assistant/Assistant.ts +7 -24
  165. package/examples/kitchen-sink/src/assistant/conversations.ts +3 -21
  166. package/examples/kitchen-sink/src/assistant/demo-model.ts +0 -5
  167. package/examples/kitchen-sink/src/assistant/handlers.ts +1 -30
  168. package/examples/kitchen-sink/src/attachments/Attachments.ts +0 -4
  169. package/examples/kitchen-sink/src/attachments/download.ts +0 -10
  170. package/examples/kitchen-sink/src/attachments/handlers.ts +0 -3
  171. package/examples/kitchen-sink/src/attachments/store.ts +0 -3
  172. package/examples/kitchen-sink/src/browser.ts +0 -9
  173. package/examples/kitchen-sink/src/cli.ts +0 -19
  174. package/examples/kitchen-sink/src/config.ts +3 -11
  175. package/examples/kitchen-sink/src/identity/Identity.ts +0 -18
  176. package/examples/kitchen-sink/src/identity/authenticate.ts +3 -14
  177. package/examples/kitchen-sink/src/identity/authorize.ts +0 -6
  178. package/examples/kitchen-sink/src/identity/directory.ts +8 -18
  179. package/examples/kitchen-sink/src/identity/handlers.ts +0 -3
  180. package/examples/kitchen-sink/src/identity/members.ts +1 -5
  181. package/examples/kitchen-sink/src/identity/quota.ts +0 -11
  182. package/examples/kitchen-sink/src/issues/Issues.ts +0 -24
  183. package/examples/kitchen-sink/src/issues/assistant.ts +0 -10
  184. package/examples/kitchen-sink/src/issues/events.ts +2 -16
  185. package/examples/kitchen-sink/src/issues/export.ts +0 -5
  186. package/examples/kitchen-sink/src/issues/guide.ts +0 -5
  187. package/examples/kitchen-sink/src/issues/handlers.ts +0 -5
  188. package/examples/kitchen-sink/src/issues/store.ts +19 -23
  189. package/examples/kitchen-sink/src/issues/write-limit.ts +0 -12
  190. package/examples/kitchen-sink/src/memory.ts +0 -9
  191. package/examples/kitchen-sink/src/ops.ts +0 -6
  192. package/examples/kitchen-sink/src/request-policy.ts +0 -17
  193. package/examples/kitchen-sink/src/routes.ts +0 -48
  194. package/examples/kitchen-sink/src/sdk.ts +0 -12
  195. package/examples/kitchen-sink/src/seed.ts +0 -10
  196. package/examples/kitchen-sink/src/server.ts +0 -22
  197. package/examples/kitchen-sink/src/stdio.ts +2 -12
  198. package/examples/kitchen-sink/src/workspaces/Workspaces.ts +0 -4
  199. package/examples/kitchen-sink/src/workspaces/handlers.ts +0 -4
  200. package/examples/kitchen-sink/src/workspaces/registry.ts +0 -5
  201. package/examples/kitchen-sink/src/workspaces/tenant.ts +0 -4
  202. package/examples/kitchen-sink/test/admin/admin.test.ts +0 -1
  203. package/examples/kitchen-sink/test/assistant/assistant.test.ts +0 -18
  204. package/examples/kitchen-sink/test/attachments/attachments.test.ts +0 -9
  205. package/examples/kitchen-sink/test/identity/identity.test.ts +0 -10
  206. package/examples/kitchen-sink/test/identity/session.test.ts +0 -10
  207. package/examples/kitchen-sink/test/issues/assistant.test.ts +3 -7
  208. package/examples/kitchen-sink/test/issues/events.test.ts +2 -9
  209. package/examples/kitchen-sink/test/issues/export.test.ts +0 -3
  210. package/examples/kitchen-sink/test/issues/issues.test.ts +6 -12
  211. package/examples/kitchen-sink/test/request-policy.test.ts +0 -6
  212. package/examples/kitchen-sink/test/routes.test.ts +0 -6
  213. package/examples/kitchen-sink/test/support/as.ts +3 -5
  214. package/examples/kitchen-sink/test/support/scripted.ts +0 -3
  215. package/examples/kitchen-sink/test/support/services.ts +0 -3
  216. package/examples/live-rpc/src/Rpc.ts +0 -4
  217. package/examples/live-rpc/src/browser.ts +0 -24
  218. package/examples/live-rpc/src/chat/Chat.ts +0 -22
  219. package/examples/live-rpc/src/chat/authorize.ts +0 -3
  220. package/examples/live-rpc/src/chat/events.ts +0 -14
  221. package/examples/live-rpc/src/chat/handlers.ts +0 -5
  222. package/examples/live-rpc/src/chat/room.ts +0 -6
  223. package/examples/live-rpc/src/chat/store.ts +0 -9
  224. package/examples/live-rpc/src/client.ts +0 -6
  225. package/examples/live-rpc/src/identity/Identity.ts +0 -6
  226. package/examples/live-rpc/src/identity/members.ts +1 -3
  227. package/examples/live-rpc/src/identity/verifier.ts +6 -12
  228. package/examples/live-rpc/src/page.ts +0 -10
  229. package/examples/live-rpc/src/routes.ts +0 -13
  230. package/examples/live-rpc/src/server.ts +0 -16
  231. package/examples/live-rpc/test/browser.test.ts +0 -9
  232. package/examples/live-rpc/test/chat/chat.test.ts +3 -11
  233. package/examples/live-rpc/test/routes.test.ts +0 -8
  234. package/examples/live-rpc/test/server.test.ts +0 -13
  235. package/examples/mcp-tools/src/instructions.ts +0 -4
  236. package/examples/mcp-tools/src/platform/fake-farm.ts +0 -6
  237. package/examples/mcp-tools/src/platform/print-farm.ts +0 -16
  238. package/examples/mcp-tools/src/printers/Printers.ts +0 -21
  239. package/examples/mcp-tools/src/printers/farm.ts +0 -5
  240. package/examples/mcp-tools/src/printers/handlers.ts +0 -6
  241. package/examples/mcp-tools/src/routes.ts +0 -11
  242. package/examples/mcp-tools/src/server.ts +0 -9
  243. package/examples/mcp-tools/src/stdio.ts +1 -13
  244. package/examples/mcp-tools/test/printers/printers.test.ts +0 -10
  245. package/examples/mcp-tools/test/routes.test.ts +0 -14
  246. package/examples/notes-service/src/Api.ts +0 -4
  247. package/examples/notes-service/src/browser.ts +0 -12
  248. package/examples/notes-service/src/cli.ts +0 -2
  249. package/examples/notes-service/src/commands.ts +0 -30
  250. package/examples/notes-service/src/identity/Identity.ts +0 -2
  251. package/examples/notes-service/src/identity/authorize.ts +0 -4
  252. package/examples/notes-service/src/identity/users.ts +1 -3
  253. package/examples/notes-service/src/identity/verifier.ts +4 -11
  254. package/examples/notes-service/src/notes/Notes.ts +0 -12
  255. package/examples/notes-service/src/notes/handlers.ts +0 -4
  256. package/examples/notes-service/src/notes/store.ts +62 -48
  257. package/examples/notes-service/src/routes.ts +0 -12
  258. package/examples/notes-service/src/server.ts +0 -6
  259. package/examples/notes-service/src/status/Status.ts +0 -1
  260. package/examples/notes-service/src/status/handlers.ts +0 -1
  261. package/examples/notes-service/src/stdio.ts +2 -12
  262. package/examples/notes-service/src/worker.ts +0 -7
  263. package/examples/notes-service/test/commands.test.ts +0 -20
  264. package/examples/notes-service/test/notes/as.ts +3 -4
  265. package/examples/notes-service/test/notes/in-process.test.ts +3 -6
  266. package/examples/notes-service/test/notes/notes.test.ts +0 -6
  267. package/examples/notes-service/test/routes.test.ts +0 -5
  268. package/examples/notes-service/test/worker.test.ts +0 -1
  269. package/examples/quickstart/src/Api.ts +0 -1
  270. package/examples/quickstart/src/client.ts +0 -3
  271. package/examples/quickstart/src/greeting/Greeting.ts +0 -2
  272. package/examples/quickstart/src/greeting/handlers.ts +0 -1
  273. package/examples/quickstart/src/routes.ts +0 -1
  274. package/examples/quickstart/src/server.ts +3 -6
  275. package/examples/quickstart/test/routes.test.ts +0 -1
  276. package/package.json +6 -6
@@ -1,11 +1,6 @@
1
1
  import { Cause, Data, Effect, Exit, Fiber, Option, Queue, Schema, Stream } from "effect";
2
2
  // src/contract/progress.ts
3
3
  const capacity = 16;
4
- /**
5
- * What a handler reports by, where `progress` is declared: each value checked by the schema, one
6
- * breaking it a defect, and handed to `sink` from a buffer dropping the oldest, so the handler
7
- * never waits. Without a `sink`, values are checked and dropped.
8
- */
9
4
  const buffering = (progress, sink) => {
10
5
  const check = Schema.decodeUnknownEffect(Schema.toType(progress));
11
6
  const checked = (value) => Effect.orDie(check(value));
@@ -22,12 +17,7 @@ const buffering = (progress, sink) => {
22
17
  };
23
18
  });
24
19
  };
25
- /** Whether what is buffered still reaches the caller after `cause` ends a call. */
26
20
  const drainsAfter = (cause) => !Cause.hasInterruptsOnly(cause);
27
- /**
28
- * Runs `handle` with what it reports by, as `buffering` makes it; what is buffered when it
29
- * succeeds or fails reaches `sink` before its answer.
30
- */
31
21
  const reportedTo = (progress, sink, handle) => {
32
22
  if (progress === void 0) return handle(void 0);
33
23
  return Effect.gen(function* () {
@@ -37,23 +27,14 @@ const reportedTo = (progress, sink, handle) => {
37
27
  return yield* exit;
38
28
  });
39
29
  };
40
- /**
41
- * Runs the stream `handle` gives with what it reports by, as `buffering` makes it, in the
42
- * stream's scope; what is buffered when it ends or fails reaches `sink` before its end.
43
- */
44
30
  const streamReportedTo = (progress, sink, handle) => {
45
31
  if (progress === void 0) return handle(void 0);
46
32
  return Stream.unwrap(Effect.map(buffering(progress, sink), ({ reporting, drained }) => handle(reporting).pipe(Stream.onEnd(drained), Stream.catchCause((cause) => drainsAfter(cause) ? Stream.unwrap(Effect.as(drained, Stream.failCause(cause))) : Stream.failCause(cause)))));
47
33
  };
48
- const shown = (onProgress) => (value) => Effect.catchCauseIf(Effect.suspend(() => onProgress(value)), (cause) => !Cause.hasInterruptsOnly(cause), (cause) => Effect.logWarning("onProgress failed", cause));
49
- /** What a caller in process hands a call for `onProgress`, as `Action.client` and the toolkit do. */
50
- const progressSink = (onProgress) => onProgress === void 0 ? void 0 : { progress: shown(onProgress) };
34
+ const shownIgnoringFailures = (onProgress) => (value) => Effect.catchCauseIf(Effect.suspend(() => onProgress(value)), (cause) => !Cause.hasInterruptsOnly(cause), (cause) => Effect.logWarning("onProgress failed", cause));
35
+ const progressSink = (onProgress) => onProgress === void 0 ? void 0 : { progress: shownIgnoringFailures(onProgress) };
51
36
  const Progressed = Data.taggedEnum();
52
37
  const endedEarly = Effect.die(/* @__PURE__ */ new Error("An answer streamed with its progress ended without its final element"));
53
- /**
54
- * A client's answer from a call's `stream`: each `Progress` value handed to `onProgress`, where
55
- * the call gave one, then the `Final` value. A stream ending without one is a defect.
56
- */
57
38
  const answerFrom = (stream, onProgress) => {
58
39
  const report = progressSink(onProgress)?.progress ?? (() => Effect.void);
59
40
  return Effect.flatMap(Stream.runFoldEffect(stream, () => Option.none(), (final, element) => Progressed.$is("Final")(element) ? Effect.succeedSome(element.value) : Effect.as(report(element.value), final)), Option.match({
@@ -61,10 +42,6 @@ const answerFrom = (stream, onProgress) => {
61
42
  onSome: Effect.succeed
62
43
  }));
63
44
  };
64
- /**
65
- * A client's elements from a call's `stream` of an action answering a stream: each `Progress`
66
- * value handed to `onProgress`, where the call gave one, and each `Element` value streamed.
67
- */
68
45
  const elementsFrom = (stream, onProgress) => {
69
46
  const report = progressSink(onProgress)?.progress ?? (() => Effect.void);
70
47
  return Stream.flatMap(stream, (sent) => Progressed.$is("Progress")(sent) ? Stream.fromEffectDrain(report(sent.value)) : Stream.make(sent.value));
@@ -4,16 +4,11 @@ import { OccurrenceSchema } from "./occurrence.mjs";
4
4
  import "./pages.mjs";
5
5
  import { Any } from "../Event.mjs";
6
6
  import { Cause, Effect, Queue, Schema, Stream } from "effect";
7
- /** What a push subscription of `event` sends, as each surface's stream encodes it. */
8
7
  export declare const PushedOf: <E extends Any>(event: E) => Schema.Union<readonly [OccurrenceSchema<E>, Schema.TaggedStruct<"Gap", {
9
8
  readonly cursor: Schema.NullOr<Schema.String>;
10
9
  }>, Schema.TaggedStruct<"Checked", {
11
10
  readonly cursor: Schema.NullOr<Schema.String>;
12
11
  }>, Schema.TaggedStruct<"Failed", {}>]>;
13
- /**
14
- * What a subscription's request carries: the event's input, and the cursor it resumes from,
15
- * `null` where it is omitted.
16
- */
17
12
  export declare const SubscriptionOf: <E extends Any>(event: E) => Schema.Struct<{
18
13
  readonly input: Codec;
19
14
  readonly cursor: Schema.withDecodingDefaultKey<Schema.NullOr<Schema.String>, never>;
@@ -9,7 +9,6 @@ import { Cause, Duration, Effect, Latch, Match, Queue, Schema, Stream } from "ef
9
9
  * outage: its cause is logged and reported, and reading resumes from the position reached.
10
10
  */
11
11
  const Failed = Schema.TaggedStruct("Failed", {});
12
- /** What a push subscription of `event` sends, as each surface's stream encodes it. */
13
12
  const PushedOf = (event) => Schema.Union([
14
13
  OccurrenceOf(event),
15
14
  Gap,
@@ -20,26 +19,14 @@ const subscriptionWith = (input) => Schema.Struct({
20
19
  input,
21
20
  cursor: Schema.NullOr(Schema.String).annotate({ description: "Where to resume: a cursor an occurrence or a page carried; null or omitted, from now." }).pipe(Schema.withDecodingDefaultKey(Effect.succeed(null)))
22
21
  });
23
- /**
24
- * What a subscription's request carries: the event's input, and the cursor it resumes from,
25
- * `null` where it is omitted.
26
- */
27
22
  const SubscriptionOf = (event) => subscriptionWith(event.input);
28
- /** A subscription's request, its input left as JSON for its event's schema to decode. */
29
23
  const Subscription = subscriptionWith(Schema.Json);
30
24
  const queued = 16;
31
25
  const heartbeatEvery = Duration.seconds(30);
32
26
  const isFailed = Schema.is(Failed);
33
- /** Each element of a push stream of `surface`'s event `name` but `Failed`, which is logged. */
34
27
  const readOn = (surface, name) => (sent) => sent.pipe(Stream.mapEffect((element) => isFailed(element) ? Effect.as(Effect.logWarning(`${surface} event "${name}" failed to read, and resumes`), []) : Effect.succeed([element])), Stream.flattenIterable);
35
28
  const isRefused = Schema.is(Refusal);
36
- /** The refusal that `cause` fails with, unless it also holds a defect. */
37
29
  const refusalIn = (cause) => Cause.hasDies(cause) ? void 0 : cause.reasons.flatMap((reason) => Cause.isFailReason(reason) && isRefused(reason.error) ? [reason.error] : [])[0];
38
- /**
39
- * A poll of `name` that answers a failure no refusal explains, reported, as a page of none from
40
- * the cursor asked, read again after the poll interval: where no network carries a 500 for a
41
- * client to retry, as in process, it reads on as `pushed` does.
42
- */
43
30
  const polledOn = (surface, name) => (poll) => (cursor) => Effect.catchCauseIf(poll(cursor), (cause) => !Cause.hasInterruptsOnly(cause) && refusalIn(cause) === void 0, (cause) => Effect.as(Effect.andThen(reported(cause), Effect.logWarning(`${surface} event "${name}" failed to read, and resumes`)), {
44
31
  events: [],
45
32
  cursor,
@@ -47,12 +34,6 @@ const polledOn = (surface, name) => (poll) => (cursor) => Effect.catchCauseIf(po
47
34
  hasMore: false,
48
35
  nextPoll: defaultNextPoll
49
36
  }));
50
- /**
51
- * One push subscription of a feed `open` reads from a cursor, starting at `cursor`, each thing it
52
- * sends given to `deliver`. A refusal, an interruption, or, unless `resumesUnconfirmed`, a failure
53
- * before it is confirmed ends it; any other failure of a read or of its delivery is reported,
54
- * sent as `Failed`, and reading resumes from the position delivered after the poll interval.
55
- */
56
37
  const pushed = (open, cursor, deliver, { resumesUnconfirmed = false, inOrder = false } = {}) => Effect.gen(function* () {
57
38
  const confirmed = yield* Latch.make();
58
39
  let reached = cursor;
@@ -81,11 +62,7 @@ const pushed = (open, cursor, deliver, { resumesUnconfirmed = false, inOrder = f
81
62
  const heartbeat = Effect.andThen(confirmed.await, Effect.forever(Effect.andThen(Effect.sleep(heartbeatEvery), () => Effect.suspend(() => deliver(Checked.make({ cursor: reached }))))));
82
63
  return yield* inOrder ? Effect.forever(once) : Effect.raceFirst(Effect.forever(once), heartbeat);
83
64
  });
84
- /**
85
- * A push subscription for a surface's streamed response: read into a bounded queue, each element
86
- * as `encode` gives it, forked in the current scope.
87
- */
88
- const queuedPush = (open, cursor, encode, { ending = (run) => run, inOrder = false, capacity = queued } = {}) => Effect.gen(function* () {
65
+ const queuedPush = (open, cursor, encode, { ending, inOrder = false, capacity = queued }) => Effect.gen(function* () {
89
66
  const queue = yield* Queue.bounded(capacity);
90
67
  yield* pushed(open, cursor, (sent) => Effect.flatMap(encode(sent), (element) => Queue.offer(queue, element)), {
91
68
  resumesUnconfirmed: true,
@@ -3,7 +3,6 @@ import { Gap, untaggedOccurrenceOf } from "./occurrence.mjs";
3
3
  import { reasonOf, refusalOf } from "./codes.mjs";
4
4
  import { Context, Effect, Option, Schema, Struct } from "effect";
5
5
  // src/contract/receiving.ts
6
- /** The query parameter of a watch's delivery URL naming its place at the receiver. */
7
6
  const watchParameter = "watch";
8
7
  /**
9
8
  * Where a watch by webhook receives its deliveries in this process: `Webhook.layerReceiver`
@@ -20,12 +19,6 @@ const Terminated = Schema.Struct({ error: Schema.Struct({
20
19
  const decodeTerminated = Schema.decodeUnknownOption(Terminated);
21
20
  const decodeGap = Schema.decodeUnknownEffect(Schema.toCodecJson(Gap.mapFields(Struct.omit(["_tag"]))));
22
21
  const ended = new Forbidden({ message: "The subscription was ended." });
23
- /**
24
- * What a watch of `event` reads from one delivered body: its occurrence, or the gap an envelope
25
- * reports; a `terminated` envelope fails with the reason its error's code names, its refusal for
26
- * any other, an envelope of another type is skipped, and a body that does not decode fails with a
27
- * `SchemaError`.
28
- */
29
22
  const webhookFed = (event) => {
30
23
  const occurrenceOf = untaggedOccurrenceOf(event);
31
24
  return (body) => {
@@ -1,6 +1,5 @@
1
1
  import { Effect, ErrorReporter } from "effect";
2
2
  // src/contract/reported.ts
3
- /** Logs `cause` and gives it to the request's `ErrorReporter`s, as a failed call's is. */
4
3
  const reported = (cause) => Effect.andThen(Effect.logError(cause), ErrorReporter.report(cause));
5
4
  var InternalError = class extends Error {
6
5
  [ErrorReporter.ignore] = true;
@@ -8,9 +7,5 @@ var InternalError = class extends Error {
8
7
  super("Internal server error");
9
8
  }
10
9
  };
11
- /**
12
- * `cause` `reported`, then a defect that says no more than "Internal server error", reported no
13
- * further: what a surface sends where it would otherwise encode a defect's details.
14
- */
15
10
  const concealed = (cause) => Effect.andThen(reported(cause), Effect.die(new InternalError()));
16
11
  export { concealed, reported };
@@ -4,10 +4,6 @@ import { Implementation, assertHeld, markingOthers, notHeld, provideBuilders, se
4
4
  import { eventsOf, feedBuilders, selectEvents } from "./feed.mjs";
5
5
  import { selection } from "./listed.mjs";
6
6
  // src/contract/serving.ts
7
- /**
8
- * What a surface without a binding serves of `served`: the actions and event types `actions`
9
- * lists, each implementation holding those alone, or every one where it lists none.
10
- */
11
7
  const selectFrom = (served, actions) => {
12
8
  const listed = selection(actions);
13
9
  return {
@@ -15,11 +11,6 @@ const selectFrom = (served, actions) => {
15
11
  events: selectEvents(eventsOf(served), listed.events)
16
12
  };
17
13
  };
18
- /**
19
- * The event implementations among `served` a binding of `bound` serves, each holding the served
20
- * event types alone: those `listed` lists, or else every bound one, refusing implementations none
21
- * of whose event types it binds, as `servedBy` refuses such action implementations.
22
- */
23
14
  const eventsServedBy = (what, bound, served, listed) => {
24
15
  const apps = eventsOf(served);
25
16
  if (listed !== void 0) assertHeld(notHeld.byBinding, listed, bound);
@@ -33,11 +24,6 @@ const eventsServedBy = (what, bound, served, listed) => {
33
24
  assertOnce("served event", selected.flatMap((app) => app.events), heldOnce);
34
25
  return selected;
35
26
  };
36
- /**
37
- * What `ActionHttp.layer` and `ActionRpc.layer` serve, with the checks they share: the actions
38
- * and event types `options.actions` lists, or every one of the binding's the implementations
39
- * hold; `authentication` is the binding's where a served contract is protected.
40
- */
41
27
  const servingOf = (what, binding, served, options) => {
42
28
  const listed = selection(options.actions);
43
29
  const apps = servedBy(what, binding.actions, toList(served), listed.actions);
@@ -55,9 +41,5 @@ const servingOf = (what, binding, served, options) => {
55
41
  authentication: [...actions, ...eventTypes].some((contract) => contract.caller !== Anyone) ? binding.authentication : void 0
56
42
  };
57
43
  };
58
- /**
59
- * Provide the builders of what `servingOf` selects, the action implementations' and the event
60
- * implementations', to a surface's layer.
61
- */
62
44
  const provideServed = (served) => provideBuilders([...served.apps.map((app) => Implementation.layerOf(app)), ...feedBuilders(served.events)]);
63
45
  export { provideServed, selectFrom, servingOf };
@@ -9,11 +9,8 @@ const transientStatuses = /* @__PURE__ */ new Set([
9
9
  503,
10
10
  504
11
11
  ]);
12
- /** Whether a server answering `status` may answer otherwise once it recovers. */
13
12
  const isTransientStatus = (status) => transientStatuses.has(status);
14
13
  const statusThroughSuspensions = (ast) => httpApiStatusOf(ast) ?? (SchemaAST.isSuspend(ast) ? statusThroughSuspensions(ast.thunk()) : void 0);
15
- /** The status an endpoint answers `error` with: its own, through suspensions, 422 without one. */
16
14
  const declaredStatus = (error) => statusThroughSuspensions(error.ast) ?? 422;
17
- /** One error schema, from `errorSchemas`, as an endpoint declares it: with its status, 422 without one. */
18
15
  const declared = (error) => httpApiStatusOf(error.ast) === void 0 ? error.annotate({ httpApiStatus: declaredStatus(error) }) : error;
19
16
  export { declared, declaredStatus, httpApiStatusOf, isTransientStatus };
@@ -21,9 +21,7 @@ const Stream$1 = (element) => Schema.make(streams.ast, {
21
21
  element: codecOf(element)
22
22
  });
23
23
  const isStreamOf = (success) => Predicate.hasProperty(success, TypeId);
24
- /** The element schema of an action answering a stream, `undefined` for any other action. */
25
24
  const elementOf = (success) => isStreamOf(success) ? success.element : void 0;
26
- /** The success a tool answers for an action with `success`, as `ToolSuccess` types it. */
27
25
  const toolSuccessOf = (success) => {
28
26
  const element = elementOf(success);
29
27
  return element === void 0 ? success : Schema.Array(element);
@@ -1,7 +1,6 @@
1
1
  import { Codec } from "./codec.mjs";
2
2
  import { Any } from "../Event.mjs";
3
3
  import { Schema } from "effect";
4
- /** What a webhook subscribe to `event` takes: a subscription's input and cursor, and its fields. */
5
4
  export declare const WebhookSubscriptionOf: <E extends Any>(event: E) => Schema.Struct<{
6
5
  readonly input: Codec;
7
6
  readonly cursor: Schema.withDecodingDefaultKey<Schema.NullOr<Schema.String>, never>;
@@ -16,7 +15,6 @@ export declare const WebhookSubscriptionOf: <E extends Any>(event: E) => Schema.
16
15
  }>;
17
16
  /** A webhook subscribe's request, its input decoded, as a surface reads it whatever its event. */
18
17
  export type AnyWebhookSubscription = ReturnType<typeof WebhookSubscriptionOf<Any>>["Type"];
19
- /** What a webhook unsubscribe from `event` takes: the input and callback it subscribed with. */
20
18
  export declare const WebhookCancellationOf: <E extends Any>(event: E) => Schema.Struct<{
21
19
  readonly input: Codec;
22
20
  readonly delivery: Schema.Struct<{
@@ -3,24 +3,16 @@ import { CallbackUrl, WebhookSecret } from "./callback.mjs";
3
3
  import { SubscriptionOf } from "./push.mjs";
4
4
  import { Schema, Struct } from "effect";
5
5
  // src/contract/subscribe.ts
6
- /** Where a webhook subscription delivers: its callback, and the secret signing each POST. */
7
6
  const WebhookCallback = Schema.Struct({
8
7
  url: CallbackUrl,
9
8
  secret: WebhookSecret
10
9
  });
11
- /** The callback a webhook unsubscribe names: its URL alone. */
12
10
  const WebhookTarget = WebhookCallback.mapFields(Struct.pick(["url"]));
13
- /**
14
- * What a webhook subscribe asks beside the subscription it names: its callback, and the lifetime
15
- * it suggests in milliseconds, `null` asking for none.
16
- */
17
11
  const webhookFields = {
18
12
  delivery: WebhookCallback,
19
13
  ttlMs: Schema.optional(Schema.NullOr(Schema.Finite)).annotate({ description: "The lifetime it suggests, in milliseconds; the answer's refreshBefore is the grant." })
20
14
  };
21
- /** What a webhook subscribe to `event` takes: a subscription's input and cursor, and its fields. */
22
15
  const WebhookSubscriptionOf = (event) => SubscriptionOf(event).pipe(Schema.fieldsAssign(webhookFields));
23
- /** What a webhook unsubscribe from `event` takes: the input and callback it subscribed with. */
24
16
  const WebhookCancellationOf = (event) => Schema.Struct({
25
17
  input: event.input,
26
18
  delivery: WebhookTarget
@@ -3,26 +3,14 @@ import { readOn } from "./push.mjs";
3
3
  import { Cause, Duration, Effect, Function, Match, Predicate, Stream } from "effect";
4
4
  import { HttpClientError } from "effect/http";
5
5
  // src/contract/transient.ts
6
- /** The status a server answered with, where `error` is a failure to read its answer. */
7
6
  const answeredStatus = ({ reason }) => Match.value(reason).pipe(Match.tag("StatusCodeError", "DecodeError", ({ response }) => response.status), Match.orElse(Function.constUndefined));
8
- /** Whether an HTTP client's failure, by its `reason`, is one a reconnect may outlast. */
9
7
  const isTransientReason = (reason) => Match.value(reason).pipe(Match.tag("TransportError", () => true), Match.tag("DecodeError", ({ response }) => response.status < 300 || isTransientStatus(response.status)), Match.tag("StatusCodeError", ({ response }) => isTransientStatus(response.status)), Match.orElse(() => false));
10
- /** Whether a remote watch's failure is one a reconnect may outlast. */
11
8
  const isTransient = Predicate.or(Cause.isTimeoutError, Predicate.compose(HttpClientError.isHttpClientError, ({ reason }) => isTransientReason(reason)));
12
9
  const silentFor = Duration.seconds(60);
13
- /**
14
- * `request`, failing with a `TimeoutError`, which `isTransient` admits, when it is unanswered for
15
- * as long as a stream may be silent, such as a server that holds its status back.
16
- */
17
10
  const failingWhenUnanswered = (request) => Effect.timeout(request, silentFor);
18
- /** `stream`, failing with a `TimeoutError`, which `isTransient` admits, once it goes silent. */
19
11
  const failingWhenSilent = (stream) => stream.pipe(Stream.timeoutOrElse({
20
12
  duration: silentFor,
21
13
  orElse: () => Stream.fail(new Cause.TimeoutError("The event stream went silent"))
22
14
  }));
23
- /**
24
- * What a client reads from a push stream of `surface`'s event `name`: each element but `Failed`,
25
- * which is logged, the server having read on; failing with a `TimeoutError` once it goes silent.
26
- */
27
15
  const receivedFrom = (surface, name) => (sent) => sent.pipe(failingWhenSilent, readOn(surface, name));
28
16
  export { answeredStatus, failingWhenSilent, failingWhenUnanswered, isTransient, isTransientReason, receivedFrom };
@@ -10,17 +10,10 @@ const reconnectDelay = Duration.seconds(1);
10
10
  const maxReconnectDelay = Duration.seconds(30);
11
11
  const afterFailures = (transient) => Schedule.min([Schedule.exponential(reconnectDelay), Schedule.spaced(maxReconnectDelay)]).pipe(Schedule.setInputType(), Schedule.while(({ input }) => transient(input)), Schedule.tap(({ input, duration }) => Effect.logWarning(`A watch reconnects in ${Duration.format(duration)} after a failure`, input)));
12
12
  const isSubscriptionError = Schema.is(SubscriptionError);
13
- /** Whether a watch's failure says the server serves its event by poll alone, refusing to push it. */
14
13
  const pushRefused = Predicate.compose(isSubscriptionError, ({ reason }) => Predicate.isTagged(reason, "Unsupported") && reason.feature === "deliveryMode" && reason.value === "push");
15
14
  const dedupeWindow = 1e3;
16
15
  const capacity = 16;
17
16
  const unsubscribeTimeout = Duration.seconds(5);
18
- /**
19
- * One webhook subscription from `cursor`, read from `received`, where its receiver puts each
20
- * body: each grant, the subscribe's and each refresh's when half of it is left, is put there too,
21
- * behind what was accepted before it, so its position is kept in order; a refresh's failure is
22
- * put there as well, and ends the run where it is read.
23
- */
24
17
  const delivered = (webhook, request, received, cursor) => {
25
18
  let at = cursor;
26
19
  const subscribed = Effect.suspend(() => webhook.subscribe({
@@ -36,11 +29,6 @@ const delivered = (webhook, request, received, cursor) => {
36
29
  })));
37
30
  }));
38
31
  };
39
- /**
40
- * The occurrences and gaps of one subscription, as every client's `watch` answers them. Each run
41
- * starts from `options`: what one run saw, the cursor and the ids it deduplicates by, ends with
42
- * it, and only `resume` carries a cursor to the next.
43
- */
44
32
  const watching = (transport, { cursor: given, mode, resume } = {}) => {
45
33
  const reconnecting = (open, cursor, polled) => {
46
34
  const { transient } = transport;
@@ -76,7 +64,7 @@ const watching = (transport, { cursor: given, mode, resume } = {}) => {
76
64
  }));
77
65
  return Stream.suspend(() => {
78
66
  const seen = makeRecent(dedupeWindow);
79
- let pending = null;
67
+ let keptOnNextPull = null;
80
68
  const keep = (cursor) => cursor === null || resume === void 0 ? Effect.void : resume.store.set(resume.key, cursor);
81
69
  const fresh = (eventId) => {
82
70
  if (seen.has(eventId)) return false;
@@ -84,14 +72,14 @@ const watching = (transport, { cursor: given, mode, resume } = {}) => {
84
72
  return true;
85
73
  };
86
74
  const handled = Effect.fnUntraced(function* (fed) {
87
- yield* keep(pending);
88
- pending = null;
75
+ yield* keep(keptOnNextPull);
76
+ keptOnNextPull = null;
89
77
  if (Predicate.isTagged(fed, "Checked")) {
90
78
  yield* keep(fed.cursor);
91
79
  return [];
92
80
  }
93
81
  if (Predicate.isTagged(fed, "Gap")) return [fed];
94
- pending = fed.cursor;
82
+ keptOnNextPull = fed.cursor;
95
83
  return fresh(fed.eventId) ? [fed] : [];
96
84
  });
97
85
  const start = given !== void 0 || resume === void 0 ? Effect.succeed(given ?? null) : Effect.map(resume.store.get(resume.key), (kept) => kept ?? null);
@@ -99,7 +87,7 @@ const watching = (transport, { cursor: given, mode, resume } = {}) => {
99
87
  if (Predicate.isTagged(mode, "WebhookDelivery")) return webhooked(mode, cursor);
100
88
  if (mode === "poll") return polled(cursor);
101
89
  return reconnecting(transport.stream, cursor, mode === "stream" ? void 0 : polled);
102
- })).pipe(Stream.rechunk(1), Stream.mapEffect(handled), Stream.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Stream.failCause(cause) : Stream.concat(Stream.fromEffectDrain(keep(pending)), Stream.failCause(cause))), Stream.flattenIterable);
90
+ })).pipe(Stream.rechunk(1), Stream.mapEffect(handled), Stream.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Stream.failCause(cause) : Stream.concat(Stream.fromEffectDrain(keep(keptOnNextPull)), Stream.failCause(cause))), Stream.flattenIterable);
103
91
  });
104
92
  };
105
93
  export { watching };
@@ -12,13 +12,7 @@ import { Context, Effect, Option } from "effect";
12
12
  */
13
13
  var Webhooks = class extends Context.Service()("effect-actions/Webhooks") {};
14
14
  const isProtected = (event) => event.caller !== Anyone;
15
- /** Whether a surface offers `event` by webhook: a protected event, its subscribers `keyed`. */
16
15
  const offersWebhook = (event, keyed) => isProtected(event) && isNamed(keyed);
17
- /**
18
- * Serves the feeds among `feeds` a surface offers by webhook, its subscribers `keyed`, to the
19
- * `Webhooks` it is given, as it builds: restoring their kept subscriptions, and dying where they
20
- * cannot be kept. Answers the service, where given, and those feeds.
21
- */
22
16
  const servedWebhooks = (feeds, keyed) => Effect.gen(function* () {
23
17
  const webhooks = yield* Effect.serviceOption(Webhooks);
24
18
  const offered = feeds.filter((feed) => offersWebhook(feed.event, keyed));
@@ -28,11 +22,6 @@ const servedWebhooks = (feeds, keyed) => Effect.gen(function* () {
28
22
  offered
29
23
  };
30
24
  });
31
- /**
32
- * The webhook subscriber calling a subscribe or unsubscribe of `feed`'s event on a surface given
33
- * `webhooks`, its subscribers `keyed`; `Unsupported` where the surface does not offer it by
34
- * webhook.
35
- */
36
25
  const webhookSubscriber = (feed, keyed, webhooks) => {
37
26
  const { event } = feed;
38
27
  if (Option.isNone(webhooks) || !isNamed(keyed) || !isProtected(event)) return Effect.fail(SubscriptionError.of(event.name, new Unsupported({
@@ -23,7 +23,6 @@ const actionMethodOf = (action, native) => {
23
23
  if (action.progress === void 0) return checked(action, sendingValue, (payload) => method({ payload }));
24
24
  return checked(action, sendingValue, (payload, onProgress) => Effect.flatMap(method({ payload }), (answer) => readWithProgress(answer, onProgress)));
25
25
  };
26
- /** The `Senders` of `http` over `httpClient`: its native clients, built once. */
27
26
  const sendersWith = (http, httpClient, baseUrl) => Effect.gen(function* () {
28
27
  const native = yield* nativeOf(http, acceptingStreams(httpClient), baseUrl);
29
28
  const plain = yield* nativeOf(http, httpClient, baseUrl);
@@ -11,10 +11,6 @@ import "../contract/push.mjs";
11
11
  import "../contract/webhooks.mjs";
12
12
  import { Effect, Option, Schema, Stream } from "effect";
13
13
  import { HttpApiEndpoint, HttpApiSchema } from "effect/http-api";
14
- /**
15
- * One poll's answer: the occurrences since the cursor, and when to ask again, sent as
16
- * `nextPollMs`, its milliseconds.
17
- */
18
14
  export declare const pageOf: <E extends Any>(event: E) => Schema.encodeKeys<Schema.Struct<{
19
15
  readonly events: Schema.$Array<OccurrenceSchema<E>>;
20
16
  readonly cursor: Schema.NullOr<Schema.String>;
@@ -24,12 +20,6 @@ export declare const pageOf: <E extends Any>(event: E) => Schema.encodeKeys<Sche
24
20
  }>, {
25
21
  readonly nextPoll: "nextPollMs";
26
22
  }>;
27
- /**
28
- * What a subscription's event stream sends, each as one SSE `message`: a `Checked` with the
29
- * position it starts from, or a `Gap` where that was no longer served, then each occurrence, a
30
- * `Gap` where some were missed, a `Checked` every 30 seconds, and a `Failed` where reading
31
- * failed and resumes. A later refusal ends it, as Effect's stream failure event.
32
- */
33
23
  export declare const sentOf: <E extends Any>(event: E) => HttpApiSchema.StreamSse<HttpApiSchema.SseEventFromData<Schema.toCodecJson<Schema.Union<readonly [OccurrenceSchema<E>, Schema.TaggedStruct<"Gap", {
34
24
  readonly cursor: Schema.NullOr<Schema.String>;
35
25
  }>, Schema.TaggedStruct<"Checked", {
@@ -7,14 +7,10 @@ import { SubscriptionError } from "../Event.mjs";
7
7
  import { webhookSubscriber } from "../contract/webhooks.mjs";
8
8
  import { PushedOf, SubscriptionOf, queuedPush } from "../contract/push.mjs";
9
9
  import { Subscribed, WebhookCancellationOf, WebhookSubscriptionOf } from "../contract/subscribe.mjs";
10
- import { Effect, Schema, Stream } from "effect";
10
+ import { Effect, Function, Schema, Stream } from "effect";
11
11
  import { HttpServerRequest } from "effect/http";
12
12
  import { HttpApiEndpoint, HttpApiSchema, OpenApi } from "effect/http-api";
13
13
  // src/http/events.ts
14
- /**
15
- * One poll's answer: the occurrences since the cursor, and when to ask again, sent as
16
- * `nextPollMs`, its milliseconds.
17
- */
18
14
  const pageOf = (event) => Schema.Struct({
19
15
  events: Schema.Array(OccurrenceOf(event)),
20
16
  cursor: Schema.NullOr(Schema.String),
@@ -22,34 +18,19 @@ const pageOf = (event) => Schema.Struct({
22
18
  hasMore: Schema.Boolean,
23
19
  nextPoll: Schema.DurationFromMillis
24
20
  }).pipe(Schema.encodeKeys({ nextPoll: "nextPollMs" }));
25
- /**
26
- * What a subscription's event stream sends, each as one SSE `message`: a `Checked` with the
27
- * position it starts from, or a `Gap` where that was no longer served, then each occurrence, a
28
- * `Gap` where some were missed, a `Checked` every 30 seconds, and a `Failed` where reading
29
- * failed and resumes. A later refusal ends it, as Effect's stream failure event.
30
- */
31
21
  const sentOf = (event) => HttpApiSchema.StreamSse({
32
22
  data: Schema.toCodecJson(PushedOf(event)),
33
23
  error: Refusal
34
24
  });
35
- /** What a served subscription's event stream sends: each element's JSON, as `sentOf` encodes it. */
36
25
  const servedSent = HttpApiSchema.StreamSse({
37
26
  data: Schema.Json,
38
27
  error: Refusal
39
28
  });
40
- /**
41
- * The route of one event type at `path`, its poll answered as JSON and its stream as SSE, as
42
- * `sent` declares it.
43
- */
44
29
  const eventEndpointOf = (event, path, errors, sent = sentOf(event)) => HttpApiEndpoint.post(event.name, path, {
45
30
  payload: SubscriptionOf(event).pipe(HttpApiSchema.asJson()),
46
31
  success: [pageOf(event), sent],
47
32
  error: errors.map(declared)
48
33
  }).annotate(OpenApi.Description, event.description);
49
- /**
50
- * The webhook routes of one protected event type at `path`: `/subscribe`, which starts or
51
- * refreshes a subscription and answers its grant, and `/unsubscribe`, which ends it.
52
- */
53
34
  const webhookEndpointsOf = (event, path, errors) => {
54
35
  const withWebhooks = [...errors, SubscriptionError];
55
36
  assertDistinctTags(`ActionHttp binding of event "${event.name}"'s webhook routes`, withWebhooks);
@@ -64,10 +45,6 @@ const webhookEndpointsOf = (event, path, errors) => {
64
45
  error
65
46
  }).annotate(OpenApi.Description, `Stop delivering ${event.name} to a webhook.`)];
66
47
  };
67
- /**
68
- * The handlers of `feed`'s webhook routes, through `webhooks` where the host provided
69
- * `Webhook.layer`; without it, both fail with `Unsupported`.
70
- */
71
48
  const webhookAnswers = (feed, authentication, webhooks) => {
72
49
  const served = webhookSubscriber(feed, authentication, webhooks);
73
50
  return {
@@ -82,18 +59,12 @@ const webhookAnswers = (feed, authentication, webhooks) => {
82
59
  }))
83
60
  };
84
61
  };
85
- /**
86
- * Answers a subscription's request to `feed`: a page, or, where it accepts `text/event-stream`,
87
- * the subscription's stream, each element its JSON. Both admit the subscriber first, so a refusal
88
- * is the route's error; `authentication`'s principal names a poll's subscriber, for its
89
- * `subscription` hook.
90
- */
91
62
  const answering = (feed, authentication) => {
92
63
  const encode = Schema.encodeEffect(Schema.toCodecJson(PushedOf(feed.event)));
93
64
  return ({ payload: { input, cursor } }) => Effect.gen(function* () {
94
65
  if (((yield* HttpServerRequest.HttpServerRequest).headers["accept"] ?? "").includes("text/event-stream")) {
95
66
  const open = yield* feed.stream(input);
96
- return Stream.fromQueue(yield* queuedPush(open, cursor, encode));
67
+ return Stream.fromQueue(yield* queuedPush(open, cursor, encode, { ending: Function.identity }));
97
68
  }
98
69
  const subscriber = yield* principalOf(feed.event, authentication);
99
70
  return yield* feed.poll(input, cursor, { subscriber });
@@ -5,8 +5,6 @@ import { Any as Any$1 } from "../Action.mjs";
5
5
  import { AnyHttp } from "./client.mjs";
6
6
  import { HttpClient } from "effect/http";
7
7
  type Contract<H extends AnyHttp> = H["actions"][number] | H["events"][number];
8
- /** A call's or a subscription's decoded input, beside its contract, one of `C`. */
9
- /** What the contracts `C` require per request, by name: nothing. */
10
8
  type Nothing<C extends Any$1 | Any> = { readonly [K in C["name"]]: never; };
11
9
  /**
12
10
  * What `placed` returns: an implementation of the binding's actions where it has some, and one of
@@ -5,7 +5,6 @@ import { StreamOf } from "../contract/stream.mjs";
5
5
  import { Any } from "../Action.mjs";
6
6
  import { Effect, Schema, Stream } from "effect";
7
7
  import { HttpApiSchema } from "effect/http-api";
8
- /** One event a route streams: a progress value, an element, or the answer it ends with. */
9
8
  interface Sent {
10
9
  readonly event: "progress" | "element" | "final";
11
10
  readonly data: ErasedValue;
@@ -10,28 +10,16 @@ const eventOf = (event, data) => Schema.Struct({
10
10
  event: Schema.Literal(event),
11
11
  data: Schema.fromJsonString(Schema.toCodecJson(data))
12
12
  });
13
- /** What a route of an action declaring `progress` answers without its stream: `success`. */
14
13
  const answeredWithProgress = (success) => HttpApiSchema.isNoContent(success.ast) ? HttpApiSchema.NoContent : success;
15
- /**
16
- * What a route of an action declaring `progress` answers a request accepting
17
- * `text/event-stream`: a `progress` event for each value its handler reports, then a `final`
18
- * event with its answer. A declared failure after the first event ends the stream as Effect's
19
- * stream failure event, and a defect as one saying `Internal server error`.
20
- */
21
14
  const progressStreamOf = (progress, success, errors) => HttpApiSchema.StreamSse({
22
15
  events: Schema.Union([eventOf("progress", progress), eventOf("final", success)]),
23
16
  error: Schema.Union(errors)
24
17
  });
25
- /**
26
- * What a route of an action answering a stream answers: an `element` event for each element,
27
- * beside a `progress` event for each value its handler reports where it declares `progress`. A
28
- * declared failure after the first event ends the stream as Effect's stream failure event, and
29
- * a defect as one saying `Internal server error`.
30
- */
31
18
  const elementStreamOf = (element, progress, errors) => HttpApiSchema.StreamSse({
32
19
  events: Schema.Union(progress === void 0 ? [eventOf("element", element)] : [eventOf("element", element), eventOf("progress", progress)]),
33
20
  error: Schema.Union(errors)
34
21
  });
22
+ const gatedOnFirst = (sent) => Effect.map(Effect.catchIf(Queue.take(sent), Cause.isDone, () => Effect.undefined), (first) => first === void 0 ? Stream.empty : Stream.concat(Stream.make(first), Stream.fromQueue(sent)));
35
23
  const streamed = (answer) => Effect.gen(function* () {
36
24
  const sent = yield* Queue.bounded(1);
37
25
  let streaming = false;
@@ -42,23 +30,17 @@ const streamed = (answer) => Effect.gen(function* () {
42
30
  event: "progress",
43
31
  data
44
32
  }) };
45
- const ended = (cause) => {
33
+ const endedReportingMidStream = (cause) => {
46
34
  if (Cause.hasDies(cause)) return concealed(cause);
47
35
  return streaming ? Effect.andThen(ErrorReporter.report(cause), Effect.failCause(cause)) : Effect.failCause(cause);
48
36
  };
49
- yield* answer(reporting, send).pipe(Effect.catchCause(ended), Queue.into(sent), Effect.forkScoped({ startImmediately: true }));
50
- const first = yield* Effect.catchIf(Queue.take(sent), Cause.isDone, () => Effect.undefined);
51
- return first === void 0 ? Stream.empty : Stream.concat(Stream.make(first), Stream.fromQueue(sent));
37
+ yield* answer(reporting, send).pipe(Effect.catchCause(endedReportingMidStream), Queue.into(sent), Effect.forkScoped({ startImmediately: true }));
38
+ return yield* gatedOnFirst(sent);
52
39
  });
53
- /** A check of `schema` failing as a defect, inside the call's boundary. */
54
40
  const checkedBy = (schema) => {
55
41
  const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(schema));
56
42
  return (data) => Effect.orDie(encode(data));
57
43
  };
58
- /**
59
- * The route handler of an action declaring `progress`: its answer streamed with its progress
60
- * where the request's `Accept` names `text/event-stream`, its answer alone otherwise.
61
- */
62
44
  const answeringWithProgress = (success, run) => {
63
45
  const check = checkedBy(success);
64
46
  return (payload) => Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => (request.headers["accept"] ?? "").includes("text/event-stream") ? streamed((reporting, send) => run(payload, reporting).pipe(Effect.tap(check), Effect.flatMap((data) => send({
@@ -66,7 +48,6 @@ const answeringWithProgress = (success, run) => {
66
48
  data
67
49
  })))) : run(payload));
68
50
  };
69
- /** The route handler of an action answering a stream: its elements and its progress, streamed. */
70
51
  const answeringElements = (element, run) => {
71
52
  const check = checkedBy(element);
72
53
  return (payload) => streamed((reporting, send) => Stream.runForEach(elementsOf(run(payload, reporting)), (data) => Effect.andThen(check(data), send({
@@ -79,16 +60,7 @@ const progressedOf = ({ event, data }) => {
79
60
  return event === "final" ? Progressed.Final({ value: data }) : Progressed.Element({ value: data });
80
61
  };
81
62
  const answeredWithout = /* @__PURE__ */ new Error("A route of an action declaring progress or answering a stream answered without its event stream");
82
- /** The events of a route's answer, as one stream of `Progressed`. */
83
63
  const sentFrom = (answer) => Stream.isStream(answer) ? Stream.map(answer, progressedOf) : Stream.die(answeredWithout);
84
- /**
85
- * A client's answer from a route of an action declaring `progress`: each `progress` event handed
86
- * to `onProgress`, where the call gave one, then the `final` event's answer.
87
- */
88
64
  const readWithProgress = (answer, onProgress) => answerFrom(sentFrom(answer), onProgress);
89
- /**
90
- * A client's elements from a route of an action answering a stream: each `element` event's
91
- * data, each `progress` event's handed to `onProgress`.
92
- */
93
65
  const readElements = (answer, onProgress) => elementsFrom(sentFrom(answer), onProgress);
94
66
  export { answeredWithProgress, answeringElements, answeringWithProgress, elementStreamOf, progressStreamOf, readElements, readWithProgress };