@gjermundgaraba/effect-actions 0.30.0 → 0.32.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 (111) hide show
  1. package/README.md +4 -3
  2. package/dist/Action.d.mts +6 -6
  3. package/dist/Action.mjs +12 -14
  4. package/dist/ActionEntity.d.mts +237 -0
  5. package/dist/ActionEntity.mjs +211 -0
  6. package/dist/ActionHttp.d.mts +5 -5
  7. package/dist/ActionHttp.mjs +24 -28
  8. package/dist/ActionMcp.d.mts +2 -3
  9. package/dist/ActionMcp.mjs +7 -10
  10. package/dist/ActionRpc.d.mts +25 -57
  11. package/dist/ActionRpc.mjs +45 -274
  12. package/dist/ActionToolkit.mjs +4 -3
  13. package/dist/Authentication.d.mts +8 -9
  14. package/dist/Authentication.mjs +49 -51
  15. package/dist/Event.d.mts +26 -6
  16. package/dist/Event.mjs +2 -2
  17. package/dist/Stored.d.mts +49 -0
  18. package/dist/Stored.mjs +78 -0
  19. package/dist/Webhook.d.mts +5 -4
  20. package/dist/Webhook.mjs +11 -4
  21. package/dist/authentication/provider.d.mts +2 -2
  22. package/dist/authentication/refusal.mjs +11 -4
  23. package/dist/cli/commands.mjs +8 -8
  24. package/dist/contract/call.mjs +6 -2
  25. package/dist/contract/callback.mjs +6 -1
  26. package/dist/contract/caller.d.mts +2 -6
  27. package/dist/contract/caller.mjs +3 -3
  28. package/dist/contract/digest.mjs +3 -2
  29. package/dist/contract/event-tables.mjs +90 -0
  30. package/dist/contract/feed.d.mts +15 -3
  31. package/dist/contract/feed.mjs +27 -16
  32. package/dist/contract/hub.d.mts +4 -57
  33. package/dist/contract/hub.mjs +12 -15
  34. package/dist/contract/idempotency.d.mts +6 -18
  35. package/dist/contract/idempotency.mjs +6 -14
  36. package/dist/contract/implementation.mjs +10 -21
  37. package/dist/contract/log.d.mts +0 -26
  38. package/dist/contract/log.mjs +16 -8
  39. package/dist/contract/pages.d.mts +30 -2
  40. package/dist/contract/pages.mjs +27 -3
  41. package/dist/contract/push.mjs +3 -5
  42. package/dist/contract/recent.mjs +3 -2
  43. package/dist/contract/serving.mjs +17 -17
  44. package/dist/contract/stream.d.mts +1 -1
  45. package/dist/contract/stream.mjs +14 -2
  46. package/dist/contract/subscribe.mjs +7 -2
  47. package/dist/contract/wake.mjs +9 -0
  48. package/dist/contract/watch.mjs +24 -22
  49. package/dist/contract/webhooks.d.mts +8 -4
  50. package/dist/contract/webhooks.mjs +50 -28
  51. package/dist/entity/forwarded.d.mts +11 -0
  52. package/dist/entity/forwarded.mjs +32 -0
  53. package/dist/entity/wakes.mjs +39 -0
  54. package/dist/http/client.mjs +8 -6
  55. package/dist/http/events.d.mts +1 -12
  56. package/dist/http/events.mjs +5 -25
  57. package/dist/http/redacted.mjs +9 -0
  58. package/dist/http/streamed.d.mts +1 -0
  59. package/dist/http/streamed.mjs +10 -5
  60. package/dist/mcp/bridge.mjs +14 -24
  61. package/dist/mcp/client.mjs +3 -12
  62. package/dist/mcp/events.mjs +1 -1
  63. package/dist/mcp/progress.mjs +11 -1
  64. package/dist/rpc/erased.d.mts +62 -0
  65. package/dist/rpc/erased.mjs +356 -0
  66. package/dist/rpc/watch.mjs +12 -13
  67. package/dist/webhook/health.mjs +25 -28
  68. package/dist/webhook/receiver.mjs +4 -7
  69. package/dist/webhook/stored.mjs +6 -4
  70. package/dist/webhook/subscriptions.mjs +65 -48
  71. package/docs/Action-streams.md +2 -2
  72. package/docs/Action.md +3 -3
  73. package/docs/ActionEntity-failures.md +10 -0
  74. package/docs/ActionEntity.md +165 -0
  75. package/docs/ActionHttp.md +0 -4
  76. package/docs/ActionMcp.md +2 -2
  77. package/docs/ActionRpc-events.md +2 -2
  78. package/docs/ActionRpc.md +1 -1
  79. package/docs/Authentication-failures.md +1 -0
  80. package/docs/Authentication.md +4 -2
  81. package/docs/Event.md +5 -5
  82. package/docs/README.md +5 -2
  83. package/docs/Webhook.md +1 -1
  84. package/docs/setup-failures.md +1 -1
  85. package/docs/setup.md +6 -5
  86. package/examples/README.md +1 -1
  87. package/examples/kitchen-sink/src/admin/Admin.ts +1 -0
  88. package/examples/kitchen-sink/src/identity/Identity.ts +5 -1
  89. package/examples/live-rpc/src/identity/Identity.ts +3 -1
  90. package/examples/notes-service/src/identity/Identity.ts +3 -1
  91. package/examples/shopping-carts/README.md +46 -0
  92. package/examples/shopping-carts/src/Api.ts +9 -0
  93. package/examples/shopping-carts/src/Rpc.ts +6 -0
  94. package/examples/shopping-carts/src/cart/Cart.ts +47 -0
  95. package/examples/shopping-carts/src/cart/handlers.ts +42 -0
  96. package/examples/shopping-carts/src/cart/held.ts +5 -0
  97. package/examples/shopping-carts/src/cart/store.ts +10 -0
  98. package/examples/shopping-carts/src/entities.ts +7 -0
  99. package/examples/shopping-carts/src/identity/Identity.ts +16 -0
  100. package/examples/shopping-carts/src/identity/shoppers.ts +6 -0
  101. package/examples/shopping-carts/src/identity/verifier.ts +21 -0
  102. package/examples/shopping-carts/src/platform/cluster.ts +7 -0
  103. package/examples/shopping-carts/src/platform/sql-carts.ts +30 -0
  104. package/examples/shopping-carts/src/routes.ts +23 -0
  105. package/examples/shopping-carts/src/server.ts +23 -0
  106. package/examples/shopping-carts/test/routes.test.ts +69 -0
  107. package/package.json +12 -9
  108. package/dist/contract/input-check.d.mts +0 -15
  109. package/dist/contract/input-check.mjs +0 -15
  110. package/dist/http/placed.d.mts +0 -34
  111. package/dist/http/placed.mjs +0 -71
@@ -1,48 +1,35 @@
1
- import { providerOf } from "./authentication/provider.mjs";
2
- import { checked, checkedStream, decodeInput, inputParseOptions, sendingJson, watchInput } from "./contract/call.mjs";
3
- import { Anyone } from "./contract/caller.mjs";
4
1
  import { bindingErrors, bindingOf, eventErrors } from "./contract/declared.mjs";
5
- import { InvalidInput, Unauthenticated } from "./contract/errors.mjs";
6
- import { acquireFeeds } from "./contract/feed.mjs";
7
- import { acquire, elementsOf } from "./contract/implementation.mjs";
2
+ import { Unauthenticated } from "./contract/errors.mjs";
8
3
  import { listed } from "./contract/listed.mjs";
9
4
  import { reservedList, reservedNames } from "./contract/names.mjs";
10
- import { answerFrom, elementsFrom } from "./contract/progress.mjs";
11
- import { PushedOf, Subscription, SubscriptionOf, queuedPush } from "./contract/push.mjs";
12
- import { concealed } from "./contract/reported.mjs";
5
+ import { PushedOf, SubscriptionOf } from "./contract/push.mjs";
13
6
  import { provideServed, servingOf } from "./contract/serving.mjs";
14
- import { elementOf } from "./contract/stream.mjs";
15
- import { watching } from "./contract/watch.mjs";
16
- import { transportOf } from "./rpc/watch.mjs";
17
- import { Cause, Effect, ErrorReporter, Layer, Match, Option, Predicate, Queue, Result, Schedule, Schema, SchemaTransformation, Stream } from "effect";
18
- import { HttpClientRequest, HttpServerRequest } from "effect/http";
19
- import { HttpApiBuilder } from "effect/http-api";
20
- import { Rpc, RpcClient, RpcGroup, RpcMiddleware, RpcSchema, RpcServer } from "effect/rpc";
7
+ import { Poll, erasedCallOf, erasedOf, handlersOf, methodsOf, nativeOf, pollTag, polledTransport, streamedOf, streamedTransport, verifyingNative } from "./rpc/erased.mjs";
8
+ import { isRpcTransient } from "./rpc/watch.mjs";
9
+ import { AnyPage } from "./contract/pages.mjs";
10
+ import { Duration, Effect, Function, Layer, Predicate, Schedule, Schema } from "effect";
11
+ import { Rpc, RpcClient, RpcGroup, RpcMiddleware, RpcServer } from "effect/rpc";
21
12
  // src/rpc/ActionRpc.ts
22
- const ProgressedOf = (progress, success) => Schema.Union([Schema.TaggedStruct("Progress", { value: progress }), Schema.TaggedStruct("Final", { value: success })]);
23
- const elementedOf = (element, progress) => Schema.Union([Schema.TaggedStruct("Element", { value: element }), ...progress === void 0 ? [] : [Schema.TaggedStruct("Progress", { value: progress })]]);
24
- const streams = (action) => action.progress !== void 0 || elementOf(action.success) !== void 0;
25
- const streamedOf = (action) => {
26
- const element = elementOf(action.success);
27
- if (element !== void 0) return elementedOf(element, action.progress);
28
- return action.progress === void 0 ? void 0 : ProgressedOf(action.progress, action.success);
29
- };
30
- const sentOf = (action) => streamedOf(action) ?? action.success;
31
13
  const authenticatedKey = "effect-actions/ActionRpc/Authenticated";
32
- const nativeOf = (group) => group;
33
14
  const authenticatedOf = (authentication) => RpcMiddleware.Service()(authenticatedKey, { error: Schema.Union([Unauthenticated, ...authentication.error]) });
34
15
  const authenticatedIn = (rpc) => [...rpc.middlewares].find(({ key }) => key === authenticatedKey);
35
16
  function make(contracts, options = {}) {
36
17
  const { actions, events } = listed(contracts);
37
18
  const bound = bindingOf("ActionRpc binding", actions, events, options);
38
- const rpcOf = (action) => Rpc.make(action.name, {
39
- payload: action.input,
40
- success: sentOf(action),
41
- error: Schema.Union(bindingErrors(action, bound)),
42
- stream: streams(action)
43
- });
19
+ const security = bound.authentication?.security;
20
+ if (Predicate.isTagged(security, "ApiKey") && security.in === "query") throw new Error(`ActionRpc binding: its authentication reads its API key ${security.key} from the query, which no rpc carries (read it from a header: HttpApiSecurity.apiKey({ in: "header", key }))`);
21
+ const rpcOf = (action) => {
22
+ const streamed = streamedOf(action);
23
+ return Rpc.make(action.name, {
24
+ payload: action.input,
25
+ success: streamed ?? action.success,
26
+ error: Schema.Union(bindingErrors(action, bound)),
27
+ stream: streamed !== void 0
28
+ });
29
+ };
44
30
  const given = options.rpcs === void 0 ? RpcGroup.make() : nativeOf(options.rpcs);
45
- for (const tag of given.requests.keys()) if (reservedNames.includes(tag) || contracts.some((contract) => contract.name === tag)) throw new Error(`ActionRpc binding: the rpc "${tag}" of rpcs is named after an action, an event type or a name the client keeps, ${reservedList} (rename it)`);
31
+ const served = erasedOf(actions, events, "ActionRpc.layer").requests;
32
+ for (const tag of given.requests.keys()) if (reservedNames.includes(tag) || served.has(tag)) throw new Error(`ActionRpc binding: the rpc "${tag}" of rpcs is named after an action, an event type, an event's poll, or a name the client keeps, ${reservedList} (rename it)`);
46
33
  const rpcs = bound.authentication === void 0 ? given : given.middleware(authenticatedOf(bound.authentication));
47
34
  const group = RpcGroup.make(...actions.map(rpcOf), ...events.map((event) => Rpc.make(event.name, {
48
35
  payload: SubscriptionOf(event),
@@ -58,262 +45,46 @@ function make(contracts, options = {}) {
58
45
  group
59
46
  };
60
47
  }
61
- const withSyntheticRequestFromHeaders = (headers) => (effect) => effect.pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, HttpServerRequest.fromClientRequest(HttpClientRequest.get("/", { headers }))), Effect.provideService(HttpServerRequest.ParsedSearchParams, {}));
62
- const throughSteps = (steps, call, options) => {
63
- let wrapped = call;
64
- for (const step of steps) {
65
- const inner = wrapped;
66
- wrapped = Effect.suspend(() => step(inner, options));
67
- }
68
- return wrapped;
69
- };
70
- const authenticatingOf = (authentication) => Effect.map(providerOf(authentication), (provider) => {
71
- const verify = Effect.flatMap(HttpApiBuilder.securityDecode(authentication.security), provider.authenticate);
72
- return (verifying) => (effect, options) => Effect.flatMap(verifying(verify, options), (actor) => Effect.provideService(effect, authentication.identity, actor));
73
- });
74
- var DeclaredFailure = class {
75
- [ErrorReporter.ignore] = true;
76
- json;
77
- constructor(json) {
78
- this.json = json;
79
- }
80
- toString() {
81
- return Predicate.isString(this.json) ? this.json : JSON.stringify(this.json);
82
- }
83
- };
84
- const asJson = () => Schema.link()(Schema.Json, SchemaTransformation.transform({
85
- decode: (json) => new DeclaredFailure(json),
86
- encode: (failure) => failure.json
87
- }));
88
- const Declared = Schema.instanceOf(DeclaredFailure, {
89
- toCodecJson: asJson,
90
- toCodecIso: asJson
91
- });
92
- const streamOf = (name) => Rpc.make(name, {
93
- payload: Schema.Json,
94
- success: Schema.Json,
95
- error: Declared,
96
- stream: true
97
- });
98
- const erasedOf = (actions, events) => RpcGroup.make(...actions.map((action) => streams(action) ? streamOf(action.name) : Rpc.make(action.name, {
99
- payload: Schema.Json,
100
- success: Schema.Json,
101
- error: Declared
102
- })), ...events.map((event) => streamOf(event.name)));
103
- const callBoundaryOf = (error) => {
104
- const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(error));
105
- return (effect) => Effect.catchCause(effect, (cause) => {
106
- if (Cause.hasDies(cause)) return concealed(cause);
107
- const failure = Cause.findFail(cause);
108
- return Result.isSuccess(failure) ? encode(failure.success.error).pipe(Effect.matchCauseEffect({
109
- onFailure: (unencoded) => concealed(Cause.combine(cause, unencoded)),
110
- onSuccess: (encoded) => Effect.fail(new DeclaredFailure(encoded))
111
- })) : Effect.failCause(failure.failure);
112
- });
113
- };
114
- const handlerOf = (action, run, steps, error) => {
115
- const decode = decodeInput(action);
116
- const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(action.success));
117
- const boundary = callBoundaryOf(error);
118
- return (payload, options) => {
119
- const call = Effect.suspend(() => decode(payload)).pipe(Effect.flatMap(run), Effect.flatMap(encode));
120
- const wrapped = throughSteps(steps, call, {
121
- ...options,
122
- payload
123
- });
124
- return boundary(wrapped);
125
- };
126
- };
127
- const streamingHandlerOf = (action, sending, steps, error) => {
128
- const decode = decodeInput(action);
129
- const boundary = callBoundaryOf(error);
130
- const encodeProgress = Schema.encodeUnknownEffect(Schema.toCodecJson(action.progress ?? Schema.Never));
131
- return (payload, options) => {
132
- const call = Effect.gen(function* () {
133
- const input = yield* decode(payload);
134
- const sent = yield* Queue.bounded(1);
135
- const send = (each) => Effect.asVoid(Queue.offer(sent, each));
136
- yield* sending(input, { progress: (value) => Effect.flatMap(Effect.orDie(encodeProgress(value)), (json) => send({
137
- _tag: "Progress",
138
- value: json
139
- })) }, send).pipe(boundary, Queue.into(sent), Effect.forkScoped({ startImmediately: true }));
140
- return sent;
141
- });
142
- const wrapped = throughSteps(steps, call, {
143
- ...options,
144
- payload
145
- });
146
- return boundary(wrapped);
147
- };
148
- };
149
- const sendingAnswer = (success, run) => {
150
- const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(success));
151
- return (input, reporting, send) => run(input, reporting).pipe(Effect.flatMap(encode), Effect.flatMap((value) => send({
152
- _tag: "Final",
153
- value
154
- })));
155
- };
156
- const sendingElements = (element, run) => {
157
- const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(element));
158
- return (input, reporting, send) => Stream.runForEach(elementsOf(run(input, reporting)), (each) => Effect.flatMap(encode(each), (value) => send({
159
- _tag: "Element",
160
- value
161
- })));
162
- };
163
- /** The key a protocol sets to its `SubscriptionKeeper` on its `RpcServer.Protocol` service. */
164
- const subscriptionKeeper = Symbol.for("effect-actions/ActionRpc/subscriptionKeeper");
165
- const isSubscriptionKeeper = (kept) => Predicate.hasProperty(kept, "keep") && Predicate.isFunction(kept.keep);
166
- const keeperOf = (protocol) => {
167
- const kept = Predicate.hasProperty(protocol, subscriptionKeeper) ? protocol[subscriptionKeeper] : void 0;
168
- return isSubscriptionKeeper(kept) ? kept : void 0;
169
- };
170
- const subscriptionHandlerOf = (feed, steps, error, keeper) => {
171
- const decode = Schema.decodeUnknownEffect(Subscription, inputParseOptions);
172
- const decodeEventInput = decodeInput(feed.event);
173
- const sent = Schema.toCodecJson(PushedOf(feed.event));
174
- const encode = Schema.encodeEffect(sent);
175
- const decodeSent = Schema.decodeUnknownOption(sent);
176
- const boundary = callBoundaryOf(error);
177
- return (payload, options) => {
178
- const call = Effect.gen(function* () {
179
- const { input, cursor } = yield* Effect.mapError(decode(payload), InvalidInput.fromSchemaError);
180
- const open = yield* feed.stream(yield* decodeEventInput(input));
181
- if (keeper === void 0) return yield* queuedPush(open, cursor, encode, {
182
- ending: boundary,
183
- positions: "heartbeat"
184
- });
185
- yield* keeper.keep({
186
- clientId: options.client.id,
187
- requestId: options.requestId,
188
- tag: feed.event.name,
189
- payload,
190
- headers: Object.entries(options.headers),
191
- resumeFrom: (values) => {
192
- const reached = values.flatMap((value) => Option.toArray(decodeSent(value))).map((pushed) => Match.value(pushed).pipe(Match.tag("Failed", () => null), Match.orElse((positioned) => positioned.cursor))).findLast(Predicate.isNotNull);
193
- return reached === void 0 ? void 0 : {
194
- input,
195
- cursor: reached
196
- };
197
- }
198
- });
199
- return yield* queuedPush(open, cursor, encode, {
200
- ending: boundary,
201
- positions: "watermark"
202
- });
203
- });
204
- const wrapped = throughSteps(steps, call, {
205
- ...options,
206
- payload
207
- });
208
- return boundary(wrapped);
209
- };
210
- };
211
- /**
212
- * The key a protocol answering each call once sets to `true` on its `RpcServer.Protocol`
213
- * service, as the Cloudflare package's stub protocol does, since Effect's protocol has no flag of
214
- * its own for it: `layer` refuses to serve a streaming action, an event type or a native stream
215
- * rpc on it, where a stream is answered with a defect at its first element and one with none
216
- * waits for good.
217
- */
218
- const unaryProtocol = Symbol.for("effect-actions/ActionRpc/unary");
219
- const verifyingNative = (verify, { headers }) => withSyntheticRequestFromHeaders(headers)(verify).pipe(Effect.catchCauseIf(Cause.hasDies, concealed));
220
- const requested = (effect, { headers }) => withSyntheticRequestFromHeaders(headers)(effect);
221
- const isUnary = (protocol) => Predicate.hasProperty(protocol, unaryProtocol) && protocol[unaryProtocol] === true;
222
48
  function layer(binding, served, options = {}) {
223
49
  const selected = servingOf("RPC binding", binding, served, options);
224
50
  const { apps, actions, events, eventTypes } = selected;
225
51
  const middleware = options.middleware ?? [];
226
- const jsonGroup = erasedOf(actions, eventTypes);
52
+ const jsonGroup = erasedOf(actions, eventTypes, "ActionRpc.layer");
227
53
  const natives = [...nativeOf(binding.rpcs).requests.values()];
228
54
  const authentication = natives.length === 0 ? selected.authentication : binding.authentication;
229
55
  const handlers = Layer.unwrap(Effect.gen(function* () {
230
56
  const unauthenticated = authentication === void 0 ? void 0 : natives.find((rpc) => authenticatedIn(rpc) === void 0);
231
57
  if (unauthenticated !== void 0) return yield* Effect.die(/* @__PURE__ */ new Error(`ActionRpc.layer: the native rpc ${unauthenticated._tag} of a protected binding runs without its authentication: add it to the group ActionRpc.make is given as its rpcs, not to the binding's rpcs after`));
232
- const protocol = yield* RpcServer.Protocol;
233
- const keeper = keeperOf(protocol);
234
- if (isUnary(protocol)) {
235
- const streamed = [...actions.filter(streams), ...eventTypes].map(({ name }) => name);
236
- const nativeStreams = natives.flatMap((rpc) => RpcSchema.isStreamSchema(rpc.successSchema) ? [rpc._tag] : []);
237
- if (streamed.length + nativeStreams.length > 0) return yield* Effect.die(/* @__PURE__ */ new Error(`ActionRpc.layer serves a protocol answering each call once, and ${[...streamed, ...nativeStreams].join(", ")} stream: serve them over a socket or HTTP, and on this protocol the others, ${nativeStreams.length > 0 ? "from a binding whose rpcs do not stream, " : ""}listed in actions`));
238
- }
239
- const listedMiddleware = yield* Effect.forEach(middleware, (key) => Effect.service(key));
240
- const authenticating = authentication === void 0 ? void 0 : yield* authenticatingOf(authentication);
241
- const bound = yield* acquire(apps, authentication);
242
- const feeds = yield* acquireFeeds(events);
243
- const stepsOf = (caller) => caller === Anyone || authenticating === void 0 ? [...listedMiddleware, requested] : [
244
- ...listedMiddleware,
245
- authenticating((verify) => verify),
246
- requested
247
- ];
248
- const handlerFor = (action, run, steps, error) => {
249
- const element = elementOf(action.success);
250
- if (element !== void 0) return streamingHandlerOf(action, sendingElements(element, run), steps, error);
251
- return action.progress === void 0 ? handlerOf(action, run, steps, error) : streamingHandlerOf(action, sendingAnswer(action.success, run), steps, error);
252
- };
253
- const byName = {
254
- ...Object.fromEntries(bound.map(([action, run]) => [action.name, handlerFor(action, run, stepsOf(action.caller), Schema.Union(bindingErrors(action, binding)))])),
255
- ...Object.fromEntries(feeds.map((feed) => [feed.event.name, subscriptionHandlerOf(feed, stepsOf(feed.event.caller), Schema.Union(eventErrors(feed.event, binding)), keeper)]))
256
- };
58
+ const { handlers: byName, authenticating } = yield* handlersOf(binding, {
59
+ apps,
60
+ events,
61
+ authentication,
62
+ server: {
63
+ _tag: "ActionRpc.layer",
64
+ middleware
65
+ }
66
+ });
257
67
  const servedActions = jsonGroup.toLayer(byName);
258
68
  const authenticated = natives.map(authenticatedIn).find(Predicate.isNotUndefined);
259
69
  if (authenticated === void 0 || authenticating === void 0) return servedActions;
260
70
  const authenticate = authenticating(verifyingNative);
261
71
  return Layer.merge(servedActions, Layer.succeed(authenticated)(authenticate));
262
- })).pipe(provideServed(selected));
72
+ })).pipe(provideServed(selected.apps, selected.events));
263
73
  return RpcServer.layer(jsonGroup.merge(binding.rpcs), { disableFatalDefects: true }).pipe(Layer.provide(handlers));
264
74
  }
265
- const isDeclared = (failure) => failure instanceof DeclaredFailure;
266
- const failedOf = (error) => {
267
- const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(error));
268
- return (failure) => Effect.flatMap(Effect.orDie(decode(failure.json)), Effect.fail);
269
- };
270
- const actionMethodOf = (action, binding, method) => {
271
- const failed = failedOf(Schema.Union(bindingErrors(action, binding)));
272
- const streamed = streamedOf(action);
273
- if (streamed === void 0) {
274
- const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(action.success));
275
- const call = method;
276
- return checked(action, sendingJson, (json) => call(json).pipe(Effect.catchIf(isDeclared, failed), Effect.flatMap((sent) => Effect.orDie(decode(sent)))));
277
- }
278
- const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(streamed));
279
- const call = method;
280
- const progressed = (json) => call(json).pipe(Stream.catchIf(isDeclared, (failure) => Stream.fromEffect(failed(failure))), Stream.mapEffect((sent) => Effect.orDie(decode(sent))));
281
- return elementOf(action.success) === void 0 ? checked(action, sendingJson, (json, onProgress) => answerFrom(progressed(json), onProgress)) : checkedStream(action, sendingJson, (json, onProgress) => elementsFrom(progressed(json), onProgress));
282
- };
283
- const eventMethodOf = (event, binding, method) => {
284
- const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(PushedOf(event)));
285
- const failed = failedOf(Schema.Union(eventErrors(event, binding)));
286
- const call = method;
287
- return (input) => (cursor) => call({
288
- input,
289
- cursor
290
- }).pipe(Stream.catchIf(isDeclared, (failure) => Stream.fromEffect(failed(failure))), Stream.mapEffect((json) => Effect.orDie(decode(json))));
291
- };
292
- function client(binding, options) {
293
- const actions = new Map(binding.actions.map((action) => [action.name, action]));
294
- const events = new Map(binding.events.map((event) => [event.name, event]));
295
- const clients = Effect.all([RpcClient.make(erasedOf(binding.actions, binding.events).merge(nativeOf(binding.rpcs)), options), Effect.map(Effect.service(RpcClient.Protocol), ({ supportsAck }) => !supportsAck)]);
296
- return Effect.map(clients, ([native, silenceEnds]) => {
297
- const rpcs = Object.entries(native);
298
- const methods = Object.fromEntries(rpcs.filter(([tag]) => !events.has(tag)).map(([tag, method]) => {
299
- const action = actions.get(tag);
300
- return [tag, action === void 0 ? method : actionMethodOf(action, binding, method)];
301
- }));
302
- if (events.size === 0) return methods;
303
- const feeds = new Map(rpcs.flatMap(([tag, method]) => {
304
- const event = events.get(tag);
305
- return event === void 0 ? [] : [[tag, eventMethodOf(event, binding, method)]];
306
- }));
307
- const watch = (event, input, watchOptions) => {
308
- const feed = feeds.get(event.name);
309
- if (feed === void 0) return Stream.die(/* @__PURE__ */ new Error(`ActionRpc.client: the binding holds no event type ${event.name} (watch one the binding ActionRpc.make returned lists)`));
310
- return Stream.unwrap(Effect.map(watchInput(event, input), ({ json }) => watching(transportOf(event, feed(json), silenceEnds), watchOptions)));
311
- };
312
- return {
313
- ...methods,
314
- watch
315
- };
316
- });
75
+ /**
76
+ * How long a polling watch waits for a poll's answer, 4 minutes, before it sends the poll again
77
+ * from the same cursor and interrupts the first.
78
+ */
79
+ const pollResentAfter = Duration.minutes(4);
80
+ function client(binding, options = {}) {
81
+ return Effect.map(Effect.all([RpcClient.make(erasedOf(binding.actions, binding.events, "ActionRpc.layer").merge(nativeOf(binding.rpcs)), {
82
+ ...options,
83
+ flatten: true
84
+ }), Effect.map(Effect.service(RpcClient.Protocol), ({ supportsAck }) => !supportsAck)]), ([call, silenceEnds]) => ({
85
+ ...methodsOf(binding, streamedTransport(silenceEnds, polledTransport(isRpcTransient, pollResentAfter)))(Function.constant(Effect.succeed(erasedCallOf(call)))),
86
+ ...Object.fromEntries([...nativeOf(binding.rpcs).requests.keys()].map((tag) => [tag, (payload, callOptions) => call(tag, payload, callOptions)]))
87
+ }));
317
88
  }
318
89
  /**
319
90
  * A socket client's `retryPolicy`, for `RpcClient.layerProtocolSocket`, that stops connecting
@@ -329,4 +100,4 @@ function client(binding, options) {
329
100
  * - Any other socket error, a drop included, is retried as Effect's default retries it.
330
101
  */
331
102
  const reconnectUntil = (...codes) => Schedule.min([Schedule.exponential(500, 1.5), Schedule.spaced(5e3)]).pipe(Schedule.setInputType(), Schedule.while(({ input: { reason } }) => !(Predicate.isTagged(reason, "SocketCloseError") && Predicate.hasProperty(reason, "code") && codes.some((code) => code === reason.code))));
332
- export { client, layer, make, reconnectUntil, subscriptionKeeper, unaryProtocol };
103
+ export { AnyPage as Page, Poll, client, layer, make, pollResentAfter, pollTag, reconnectUntil };
@@ -1,9 +1,10 @@
1
1
  import { projectedErrors } from "./contract/declared.mjs";
2
2
  import { hintsOf } from "./contract/hints.mjs";
3
- import { Implementation, acquire, answeringWhole, provideHandlers, select, toList } from "./contract/implementation.mjs";
3
+ import { Implementation, acquire, actionKind, answeringWhole, select, toList } from "./contract/implementation.mjs";
4
4
  import { liftOf, liftedFrom } from "./contract/lift.mjs";
5
5
  import { assertOnce, heldOnce } from "./contract/names.mjs";
6
6
  import { progressSink } from "./contract/progress.mjs";
7
+ import { provideServed } from "./contract/serving.mjs";
7
8
  import { toolSuccessOf } from "./contract/stream.mjs";
8
9
  import { Effect, Schema, SchemaGetter } from "effect";
9
10
  import { Prompt, Tool, Toolkit } from "effect/ai";
@@ -50,7 +51,7 @@ const jsonToolOf = (action) => {
50
51
  });
51
52
  };
52
53
  function make(apps, options) {
53
- const served = select(toList(apps), options?.actions);
54
+ const served = select(actionKind, toList(apps), options?.actions);
54
55
  const needsApproval = options?.needsApproval;
55
56
  assertOnce("tool", served.flatMap((app) => app.actions), heldOnce);
56
57
  const toolOf = (action, app) => Object.assign(needsApproval === void 0 ? jsonToolOf(action) : jsonToolOf(action).setNeedsApproval((input, context) => {
@@ -67,7 +68,7 @@ function make(apps, options) {
67
68
  layer: toolkit.toLayer(Effect.map(acquire(served, void 0), (bound) => Object.fromEntries(bound.map(([action, handler]) => {
68
69
  const run = answeringWhole(action, handler);
69
70
  return [action.name, (input, { preliminary }) => run(input, progressSink((value) => preliminary(new Reported(value))))];
70
- })))).pipe(provideHandlers(served))
71
+ })))).pipe(provideServed(served))
71
72
  };
72
73
  }
73
74
  /**
@@ -2,7 +2,7 @@ import { Errors } from "./Action.mjs";
2
2
  import { Codec } from "./contract/codec.mjs";
3
3
  import { ErrorsOf } from "./contract/declared.mjs";
4
4
  import { Refusal } from "./contract/errors.mjs";
5
- import { Known, OptionalUnless } from "./contract/implementation.mjs";
5
+ import { Known } from "./contract/implementation.mjs";
6
6
  import { Any, Descriptor, Provider, Security } from "./authentication/provider.mjs";
7
7
  import { Array, Context, Effect, Layer, Option, Redacted, Schema, Scope } from "effect";
8
8
  import { HttpRouter, HttpServerResponse } from "effect/http";
@@ -92,6 +92,7 @@ export interface Options<A = unknown> {
92
92
  * **Gotchas**
93
93
  *
94
94
  * - One scheme per descriptor, with no fallback: a host accepting two credentials for one identity declares two descriptors and serves them on two bindings or endpoints.
95
+ * - An API key in the query, or in a header the host's `HttpMiddleware.TracerHeaderFilter` records, is redacted from the spans of `ActionHttp` endpoints and `ActionHttp.client` calls alone: any other route, `ActionMcp` and `protect`ed routes included, records it as sent in its span's URL or headers.
95
96
  */
96
97
  readonly security?: Security;
97
98
  /**
@@ -104,17 +105,15 @@ export interface Options<A = unknown> {
104
105
  */
105
106
  readonly error?: Errors | Errors[number];
106
107
  /**
107
- * The stable id of an identity, such as its user id: what tells subscribers apart where a
108
- * surface keeps a subscription between requests, such as an MCP poll subscription's lease.
108
+ * The stable id of an identity, such as its user id, `(user) => user.id`: what a surface keys
109
+ * by caller, a poll subscription's `subscription` hook, a webhook subscription and an
110
+ * idempotency key.
109
111
  *
110
112
  * **Gotchas**
111
113
  *
112
- * - A surface serving a protected event type whose source has a `subscription` hook refuses to start without it, its message naming this option.
113
- * - Two identities with one principal share those subscriptions, so give each its own: a tenant's id alone merges its users.
114
- * - Without it no surface offers a protected event by webhook, which a subscription keys by its principal: the listing names no webhook, and a webhook subscription fails with `Event.SubscriptionError`, reason `Unsupported`.
115
- * - Without it every caller shares one idempotency key space: another caller sending a key with the same input is given the first call's answer, as `Action.Options.idempotencyKey` says.
114
+ * - Two identities with one principal share those, so give each its own: a tenant's id alone merges its users, who share subscription hooks, webhook subscriptions and each other's kept answers.
116
115
  */
117
- readonly principal?: ((identity: A) => string) | undefined;
116
+ readonly principal: (identity: A) => string;
118
117
  /**
119
118
  * The identity's schema, its `Type` the identity: how a surface keeps an identity past a
120
119
  * restart, as `Webhook.layer` with `persist` keeps each webhook subscriber's, its JSON in the
@@ -142,7 +141,7 @@ type SecurityOf<O> = O extends {
142
141
  * one name only for one declaration, whose values a server and a client may hold as `layer` says.
143
142
  * Guide: `docs/Authentication.md` in this package; in an application: `examples/notes-service/src/identity/`.
144
143
  */
145
- export declare const make: <const Name extends string, I, A, const O extends Options<never> = {}>(name: Name, identity: Context.Key<I, A>, ...options: OptionalUnless<O, O & NoInfer<Known<O, Options>> & PrincipalOf<A> & SchemaOf<O, A>>) => Descriptor<I, A, SecurityOf<O>, Name, ErrorsOf<O>>;
144
+ export declare const make: <const Name extends string, I, A, const O extends Options<never>>(name: Name, identity: Context.Key<I, A>, options: O & NoInfer<Known<O, Options>> & PrincipalOf<A> & SchemaOf<O, A>) => Descriptor<I, A, SecurityOf<O>, Name, ErrorsOf<O>>;
146
145
  /**
147
146
  * A descriptor's verifier: the credential its scheme decodes, as Effect's own decoder gives
148
147
  * it, to the identity, or a refusal, or an error the descriptor declares, `E`. Its services
@@ -25,12 +25,6 @@ const namedOf = (options) => ({
25
25
  scope: options?.scopesRequired?.join(" "),
26
26
  metadataUrl: options === void 0 ? void 0 : metadataUrlOf(options).href
27
27
  });
28
- const presentsBearerToken = (authorization) => Option.isSome(bearerTokenOf(authorization));
29
- const bearerChallengeOf = (named, presented) => bearer([
30
- ["error", presented ? "invalid_token" : void 0],
31
- ["scope", named.scope],
32
- ["resource_metadata", named.metadataUrl]
33
- ]);
34
28
  const assertPublishableResource = (oauth, options) => {
35
29
  if (options === void 0) return;
36
30
  if (!oauth) throw new Error("A protected resource is published only for a Bearer scheme: drop `protectedResource`, or authenticate with a Bearer descriptor");
@@ -50,6 +44,32 @@ const withNoStoreAndChallenge = (response, wwwAuthenticate) => HttpServerRespons
50
44
  const isBearer = (security) => Predicate.isTagged(security, "Http") && security.scheme.toLowerCase() === "bearer";
51
45
  const openApiComponentKey = /^[\w.-]+$/u;
52
46
  const nonBearerChallengeOf = (security, name) => Match.value(security).pipe(Match.tag("Http", ({ scheme }) => challenge(scheme, [])), Match.tag("Basic", () => challenge("Basic", [["realm", name]])), Match.tag("ApiKey", Function.constUndefined), Match.exhaustive);
47
+ const refusingOf = (authentication, resource) => {
48
+ const oauth = authentication === void 0 || isBearer(authentication.security);
49
+ assertPublishableResource(oauth, resource);
50
+ const { scope, metadataUrl } = namedOf(resource);
51
+ const bearerChallenge = (presented) => bearer([
52
+ ["error", presented ? "invalid_token" : void 0],
53
+ ["scope", scope],
54
+ ["resource_metadata", metadataUrl]
55
+ ]);
56
+ const invalid = bearerChallenge(true);
57
+ const anonymous = bearerChallenge(false);
58
+ const other = authentication === void 0 || oauth ? void 0 : nonBearerChallengeOf(authentication.security, authentication.name);
59
+ return {
60
+ missing: new Unauthenticated({ message: oauth ? "A bearer token is required." : "A credential is required." }),
61
+ challenge: (presented) => {
62
+ if (!oauth) return other;
63
+ return presented ? invalid : anonymous;
64
+ },
65
+ response: (error) => {
66
+ if (!isRefusal(error)) return declaredResponse(authentication?.error ?? [], error);
67
+ return oauth ? answer(error, metadataUrl) : plain(error);
68
+ },
69
+ stepUp: (route) => oauth ? Effect.catchIf(route, isStepUp, (error) => Effect.succeed(answer(error, metadataUrl))) : route,
70
+ answeringStepUp: (route) => oauth ? answerStepUp(route, metadataUrl) : route
71
+ };
72
+ };
53
73
  /**
54
74
  * The response `layer` answers a refusal with, for a caller the router never routes, such as a
55
75
  * Node `upgrade` handler admitting a socket, which holds a header and no request: read its token
@@ -59,17 +79,10 @@ const nonBearerChallengeOf = (security, name) => Match.value(security).pipe(Matc
59
79
  * naming scopes. `HttpServerResponse.toWeb` gives it as a web `Response`.
60
80
  */
61
81
  const refusalResponse = (error, options) => {
62
- const authentication = options?.authentication;
63
- const oauth = authentication === void 0 || isBearer(authentication.security);
64
- assertPublishableResource(oauth, options?.protectedResource);
65
- const named = namedOf(options?.protectedResource);
66
- const wwwAuthenticate = authentication !== void 0 && !oauth ? nonBearerChallengeOf(authentication.security, authentication.name) : bearerChallengeOf(named, presentsBearerToken(options?.authorization));
67
- if (!isRefusal(error)) {
68
- const response = declaredResponse(authentication?.error ?? [], error);
69
- if (response === void 0) throw new Error("Not a refusal, nor an error the authentication declares: pass the descriptor declaring it as `authentication`, or answer the error yourself");
70
- return withNoStoreAndChallenge(response, wwwAuthenticate);
71
- }
72
- return withNoStoreAndChallenge(oauth ? answer(error, named.metadataUrl) : plain(error), wwwAuthenticate);
82
+ const refusing = refusingOf(options?.authentication, options?.protectedResource);
83
+ const response = refusing.response(error);
84
+ if (response === void 0) throw new Error("Not a refusal, nor an error the authentication declares: pass the descriptor declaring it as `authentication`, or answer the error yourself");
85
+ return withNoStoreAndChallenge(response, refusing.challenge(Option.isSome(bearerTokenOf(options?.authorization))));
73
86
  };
74
87
  const mayResolveToDiscoveryPath = /\.well-known|[\t\n\r]/u;
75
88
  const corsPreflight = (request) => {
@@ -103,15 +116,6 @@ const discoveryMiddleware = (options) => {
103
116
  return next;
104
117
  });
105
118
  };
106
- const resourceAnswersOf = (options) => {
107
- const named = namedOf(options);
108
- return {
109
- metadataUrl: named.metadataUrl,
110
- invalid: bearerChallengeOf(named, true),
111
- anonymous: bearerChallengeOf(named, false),
112
- published: options === void 0 ? void 0 : discoveryMiddleware(options)
113
- };
114
- };
115
119
  /**
116
120
  * Browser-safe declaration shared by clients and remote surfaces: the `identity` it
117
121
  * authenticates, and the scheme a caller proves it by, `Options.security`. The literal name
@@ -119,11 +123,11 @@ const resourceAnswersOf = (options) => {
119
123
  * one name only for one declaration, whose values a server and a client may hold as `layer` says.
120
124
  * Guide: `docs/Authentication.md` in this package; in an application: `examples/notes-service/src/identity/`.
121
125
  */
122
- const make = (name, identity, ...options) => {
123
- const security = options[0]?.security ?? HttpApiSecurity.bearer;
124
- const error = errorList(options[0]?.error);
125
- const principal = options[0]?.principal;
126
- const schema = options[0]?.schema;
126
+ const make = (name, identity, options) => {
127
+ if (!Predicate.hasProperty(options, "principal") || !Predicate.isFunction(options.principal)) throw new TypeError(`Authentication "${name}" has no principal: give it the stable id of an identity, such as (user) => user.id`);
128
+ const security = options.security ?? HttpApiSecurity.bearer;
129
+ const error = errorList(options.error);
130
+ const { principal, schema } = options;
127
131
  if (!openApiComponentKey.test(name)) throw new Error(`Invalid authentication name: ${JSON.stringify(name)}, not an OpenAPI key: use only letters, digits, "_", "." and "-"`);
128
132
  assertDistinctTags(`Authentication "${name}"`, [...builtIns, ...error]);
129
133
  if (!Predicate.isTagged(security, "Http") && !Predicate.isTagged(security, "ApiKey") && !Predicate.isTagged(security, "Basic")) throw new Error("Authentication takes one native HttpApiSecurity scheme as `security`: omit it for Bearer, or give one scheme, such as `HttpApiSecurity.basic`, never a record of them");
@@ -132,7 +136,7 @@ const make = (name, identity, ...options) => {
132
136
  identity,
133
137
  security,
134
138
  error,
135
- ...principal === void 0 ? {} : { principal },
139
+ principal,
136
140
  ...schema === void 0 ? {} : { schema },
137
141
  "~provider": Context.Service(`effect-actions/Authentication/Provider/${name}`),
138
142
  "~middleware": HttpApiMiddleware.Service()(`effect-actions/Authentication/Security/${name}`, { security: { [name]: security } }),
@@ -142,31 +146,25 @@ const make = (name, identity, ...options) => {
142
146
  const presented = (credential) => Redacted.isRedacted(credential) ? Redacted.value(credential) !== "" : credential.username !== "" || Redacted.value(credential.password) !== "";
143
147
  function layer(authentication, verify, options = {}) {
144
148
  const { security } = authentication;
145
- const oauth = isBearer(security);
146
149
  const { protectedResource } = options;
147
- assertPublishableResource(oauth, protectedResource);
148
- const resource = Effect.isEffect(protectedResource) ? Effect.map(protectedResource, (built) => {
149
- assertPublishableResource(oauth, built);
150
- return resourceAnswersOf(built);
151
- }) : Effect.succeed(resourceAnswersOf(protectedResource));
152
- const missing = new Unauthenticated({ message: oauth ? "A bearer token is required." : "A credential is required." });
150
+ const published = (built) => ({
151
+ refusing: refusingOf(authentication, built),
152
+ discovery: built === void 0 ? void 0 : discoveryMiddleware(built)
153
+ });
154
+ const resource = Effect.isEffect(protectedResource) ? Effect.map(protectedResource, published) : Effect.succeed(published(protectedResource));
153
155
  return Layer.effect(authentication["~provider"], Effect.gen(function* () {
154
- const { metadataUrl, invalid, anonymous, published } = yield* resource;
155
- if (published !== void 0) yield* (yield* HttpRouter.HttpRouter).addGlobalMiddleware(published);
156
+ const { refusing, discovery } = yield* resource;
157
+ if (discovery !== void 0) yield* (yield* HttpRouter.HttpRouter).addGlobalMiddleware(discovery);
156
158
  const verifier = Effect.isEffect(verify) ? yield* verify : verify;
157
159
  if (!Predicate.isFunction(verifier)) return yield* Effect.die(/* @__PURE__ */ new Error("Missing verify: pass a verify function, or an Effect building one"));
158
- const authenticate = (credential) => presented(credential) ? verifier(credential) : Effect.fail(missing);
160
+ const authenticate = (credential) => presented(credential) ? verifier(credential) : Effect.fail(refusing.missing);
159
161
  const noStoreOnFailure = HttpEffect.appendPreResponseHandler((_request, response) => Effect.succeed(HttpServerResponse.setHeader(response, "cache-control", "no-store")));
160
- const challengeOf = (credential) => {
161
- if (!oauth) return nonBearerChallengeOf(security, authentication.name);
162
- return presented(credential) ? invalid : anonymous;
163
- };
164
- const refuse = (error) => isRefusal(error) ? Effect.succeed(oauth ? answer(error, metadataUrl) : plain(error)) : Effect.suspend(() => {
165
- const response = declaredResponse(authentication.error, error);
162
+ const refuse = (error) => Effect.suspend(() => {
163
+ const response = refusing.response(error);
166
164
  return response === void 0 ? Effect.die(error) : Effect.succeed(response);
167
165
  });
168
166
  const verified = (credential, route, slot) => {
169
- const wwwAuthenticate = challengeOf(credential);
167
+ const wwwAuthenticate = refusing.challenge(presented(credential));
170
168
  return Effect.matchEffect(authenticate(credential), {
171
169
  onFailure: refuse,
172
170
  onSuccess: (actor) => Effect.provideService(route, slot, actor)
@@ -176,8 +174,8 @@ function layer(authentication, verify, options = {}) {
176
174
  descriptor: authentication,
177
175
  authenticate,
178
176
  middleware: { [authentication.name]: (route, { credential }) => verified(credential, route, authentication.identity) },
179
- stepUp: (route) => oauth ? Effect.catchIf(route, isStepUp, (error) => Effect.succeed(answer(error, metadataUrl))) : route,
180
- http: ((route, optional) => Effect.flatMap(HttpApiBuilder.securityDecode(security), (credential) => optional && !presented(credential) ? route : verified(credential, oauth ? answerStepUp(route, metadataUrl) : route, authentication["~verified"]))),
177
+ stepUp: refusing.stepUp,
178
+ http: ((route, optional) => Effect.flatMap(HttpApiBuilder.securityDecode(security), (credential) => optional && !presented(credential) ? route : verified(credential, refusing.answeringStepUp(route), authentication["~verified"]))),
181
179
  route: ((route) => Effect.flatMap(HttpApiBuilder.securityDecode(security), (credential) => verified(credential, Effect.catchIf(route, isRefusal, refuse), authentication.identity)))
182
180
  };
183
181
  }));