@gjermundgaraba/effect-actions 0.31.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 (94) hide show
  1. package/README.md +4 -3
  2. package/dist/Action.d.mts +6 -6
  3. package/dist/Action.mjs +3 -4
  4. package/dist/ActionEntity.d.mts +237 -0
  5. package/dist/ActionEntity.mjs +211 -0
  6. package/dist/ActionHttp.d.mts +4 -5
  7. package/dist/ActionHttp.mjs +12 -12
  8. package/dist/ActionMcp.d.mts +2 -3
  9. package/dist/ActionMcp.mjs +1 -1
  10. package/dist/ActionRpc.d.mts +25 -58
  11. package/dist/ActionRpc.mjs +34 -249
  12. package/dist/Authentication.d.mts +8 -9
  13. package/dist/Authentication.mjs +6 -6
  14. package/dist/Event.d.mts +26 -6
  15. package/dist/Event.mjs +2 -2
  16. package/dist/Stored.d.mts +49 -0
  17. package/dist/Stored.mjs +78 -0
  18. package/dist/Webhook.d.mts +5 -4
  19. package/dist/Webhook.mjs +11 -4
  20. package/dist/authentication/provider.d.mts +2 -2
  21. package/dist/contract/call.mjs +6 -2
  22. package/dist/contract/caller.d.mts +2 -6
  23. package/dist/contract/caller.mjs +3 -3
  24. package/dist/contract/event-tables.mjs +90 -0
  25. package/dist/contract/feed.d.mts +15 -3
  26. package/dist/contract/feed.mjs +20 -11
  27. package/dist/contract/hub.d.mts +4 -57
  28. package/dist/contract/hub.mjs +12 -15
  29. package/dist/contract/idempotency.d.mts +6 -18
  30. package/dist/contract/idempotency.mjs +6 -14
  31. package/dist/contract/implementation.mjs +3 -4
  32. package/dist/contract/log.d.mts +0 -26
  33. package/dist/contract/log.mjs +16 -8
  34. package/dist/contract/pages.d.mts +30 -2
  35. package/dist/contract/pages.mjs +27 -3
  36. package/dist/contract/wake.mjs +9 -0
  37. package/dist/contract/watch.mjs +20 -15
  38. package/dist/contract/webhooks.d.mts +8 -4
  39. package/dist/contract/webhooks.mjs +42 -31
  40. package/dist/entity/forwarded.d.mts +11 -0
  41. package/dist/entity/forwarded.mjs +32 -0
  42. package/dist/entity/wakes.mjs +39 -0
  43. package/dist/http/client.mjs +2 -2
  44. package/dist/http/events.d.mts +1 -12
  45. package/dist/http/events.mjs +2 -24
  46. package/dist/http/redacted.mjs +9 -0
  47. package/dist/mcp/bridge.mjs +5 -6
  48. package/dist/mcp/client.mjs +2 -2
  49. package/dist/rpc/erased.d.mts +62 -0
  50. package/dist/rpc/erased.mjs +356 -0
  51. package/dist/rpc/watch.mjs +10 -9
  52. package/dist/webhook/stored.mjs +6 -4
  53. package/dist/webhook/subscriptions.mjs +58 -40
  54. package/docs/Action-streams.md +2 -2
  55. package/docs/Action.md +3 -3
  56. package/docs/ActionEntity-failures.md +10 -0
  57. package/docs/ActionEntity.md +165 -0
  58. package/docs/ActionHttp.md +0 -4
  59. package/docs/ActionMcp.md +2 -2
  60. package/docs/ActionRpc-events.md +2 -2
  61. package/docs/ActionRpc.md +1 -1
  62. package/docs/Authentication-failures.md +1 -0
  63. package/docs/Authentication.md +4 -2
  64. package/docs/Event.md +5 -5
  65. package/docs/README.md +5 -2
  66. package/docs/Webhook.md +1 -1
  67. package/docs/setup-failures.md +1 -1
  68. package/docs/setup.md +6 -5
  69. package/examples/README.md +1 -1
  70. package/examples/kitchen-sink/src/admin/Admin.ts +1 -0
  71. package/examples/kitchen-sink/src/identity/Identity.ts +5 -1
  72. package/examples/live-rpc/src/identity/Identity.ts +3 -1
  73. package/examples/notes-service/src/identity/Identity.ts +3 -1
  74. package/examples/shopping-carts/README.md +46 -0
  75. package/examples/shopping-carts/src/Api.ts +9 -0
  76. package/examples/shopping-carts/src/Rpc.ts +6 -0
  77. package/examples/shopping-carts/src/cart/Cart.ts +47 -0
  78. package/examples/shopping-carts/src/cart/handlers.ts +42 -0
  79. package/examples/shopping-carts/src/cart/held.ts +5 -0
  80. package/examples/shopping-carts/src/cart/store.ts +10 -0
  81. package/examples/shopping-carts/src/entities.ts +7 -0
  82. package/examples/shopping-carts/src/identity/Identity.ts +16 -0
  83. package/examples/shopping-carts/src/identity/shoppers.ts +6 -0
  84. package/examples/shopping-carts/src/identity/verifier.ts +21 -0
  85. package/examples/shopping-carts/src/platform/cluster.ts +7 -0
  86. package/examples/shopping-carts/src/platform/sql-carts.ts +30 -0
  87. package/examples/shopping-carts/src/routes.ts +23 -0
  88. package/examples/shopping-carts/src/server.ts +23 -0
  89. package/examples/shopping-carts/test/routes.test.ts +69 -0
  90. package/package.json +9 -6
  91. package/dist/contract/input-check.d.mts +0 -15
  92. package/dist/contract/input-check.mjs +0 -15
  93. package/dist/http/placed.d.mts +0 -34
  94. package/dist/http/placed.mjs +0 -71
@@ -0,0 +1,42 @@
1
+ import * as Action from "@gjermundgaraba/effect-actions/Action";
2
+ import { Effect } from "effect";
3
+
4
+ import { CurrentShopper } from "../identity/Identity.js";
5
+ import { CartFull, cartLimit, Carts } from "./Cart.js";
6
+ import { CurrentCart } from "./held.js";
7
+ import { CartStore } from "./store.js";
8
+
9
+ const ownCart = Effect.map(CurrentCart, (cart) =>
10
+ Effect.fn("ownCart")(function* () {
11
+ const shopper = yield* CurrentShopper;
12
+
13
+ if (shopper.id !== cart) {
14
+ return yield* new Action.Forbidden({ message: "Not your cart." });
15
+ }
16
+ })
17
+ );
18
+
19
+ export const carts = Action.implement(
20
+ Carts,
21
+ Effect.gen(function* () {
22
+ const cart = yield* CurrentCart;
23
+ const store = yield* CartStore;
24
+
25
+ return {
26
+ addItem: ({ item }) =>
27
+ Effect.gen(function* () {
28
+ const items = yield* store.items(cart);
29
+
30
+ if (items.length >= cartLimit) {
31
+ return yield* new CartFull({ cart, limit: cartLimit });
32
+ }
33
+
34
+ yield* store.add(cart, item);
35
+
36
+ return { items: [...items, item] };
37
+ }),
38
+ viewCart: () => Effect.map(store.items(cart), (items) => ({ items })),
39
+ };
40
+ }),
41
+ { authorize: ownCart }
42
+ );
@@ -0,0 +1,5 @@
1
+ import { Context } from "effect";
2
+
3
+ export class CurrentCart extends Context.Service<CurrentCart, string>()(
4
+ "shopping-carts/CurrentCart"
5
+ ) {}
@@ -0,0 +1,10 @@
1
+ import { Context } from "effect";
2
+ import type { Effect } from "effect";
3
+
4
+ export class CartStore extends Context.Service<
5
+ CartStore,
6
+ {
7
+ readonly items: (cart: string) => Effect.Effect<readonly string[]>;
8
+ readonly add: (cart: string, item: string) => Effect.Effect<void>;
9
+ }
10
+ >()("shopping-carts/CartStore") {}
@@ -0,0 +1,7 @@
1
+ import * as ActionEntity from "@gjermundgaraba/effect-actions/ActionEntity";
2
+
3
+ import { CartRpc } from "./Rpc.js";
4
+
5
+ export const Cart = ActionEntity.make("Cart", CartRpc, {
6
+ key: ({ cart }) => cart,
7
+ });
@@ -0,0 +1,16 @@
1
+ import * as Authentication from "@gjermundgaraba/effect-actions/Authentication";
2
+ import { Context } from "effect";
3
+
4
+ export interface Shopper {
5
+ readonly id: string;
6
+ }
7
+
8
+ export class CurrentShopper extends Context.Service<CurrentShopper, Shopper>()(
9
+ "shopping-carts/CurrentShopper"
10
+ ) {}
11
+
12
+ export const Login = Authentication.make(
13
+ "shopping-carts.Login",
14
+ CurrentShopper,
15
+ { principal: (shopper) => shopper.id }
16
+ );
@@ -0,0 +1,6 @@
1
+ import type { Shopper } from "./Identity.js";
2
+
3
+ export const demoShoppers = {
4
+ ada: { id: "ada" },
5
+ grace: { id: "grace" },
6
+ } satisfies Record<string, Shopper>;
@@ -0,0 +1,21 @@
1
+ import * as Action from "@gjermundgaraba/effect-actions/Action";
2
+ import * as Authentication from "@gjermundgaraba/effect-actions/Authentication";
3
+ import { Effect, Redacted } from "effect";
4
+
5
+ import { Login } from "./Identity.js";
6
+ import { demoShoppers } from "./shoppers.js";
7
+
8
+ const isToken = (token: string): token is keyof typeof demoShoppers =>
9
+ Object.hasOwn(demoShoppers, token);
10
+
11
+ const demoVerify = (token: Redacted.Redacted) => {
12
+ const name = Redacted.value(token);
13
+
14
+ return isToken(name)
15
+ ? Effect.succeed(demoShoppers[name])
16
+ : Effect.fail(
17
+ new Action.Unauthenticated({ message: "Unknown demo token." })
18
+ );
19
+ };
20
+
21
+ export const authenticate = Authentication.layer(Login, demoVerify);
@@ -0,0 +1,7 @@
1
+ import { Layer } from "effect";
2
+ import { SingleRunner } from "effect/cluster";
3
+ import { Digest } from "effect/crypto";
4
+
5
+ export const layerSingleRunner = SingleRunner.layer({
6
+ runnerStorage: "memory",
7
+ }).pipe(Layer.orDie, Layer.provide(Digest.layerWebCrypto));
@@ -0,0 +1,30 @@
1
+ import { Effect, Layer, Schema } from "effect";
2
+ import { SqlClient } from "effect/sql";
3
+
4
+ import { CartStore } from "../cart/store.js";
5
+
6
+ const decodeItems = Schema.decodeUnknownEffect(
7
+ Schema.Array(Schema.Struct({ item: Schema.String }))
8
+ );
9
+
10
+ export const layerSqlCarts = Layer.effect(CartStore)(
11
+ Effect.gen(function* () {
12
+ const sql = yield* SqlClient.SqlClient;
13
+
14
+ yield* sql`CREATE TABLE IF NOT EXISTS cart_items (id INTEGER PRIMARY KEY AUTOINCREMENT, cart TEXT NOT NULL, item TEXT NOT NULL)`;
15
+
16
+ return CartStore.of({
17
+ items: (cart) =>
18
+ sql`SELECT item FROM cart_items WHERE cart = ${cart} ORDER BY id`.pipe(
19
+ Effect.flatMap(decodeItems),
20
+ Effect.map((rows) => rows.map(({ item }) => item)),
21
+ Effect.orDie
22
+ ),
23
+ add: (cart, item) =>
24
+ sql`INSERT INTO cart_items (cart, item) VALUES (${cart}, ${item})`.pipe(
25
+ Effect.asVoid,
26
+ Effect.orDie
27
+ ),
28
+ });
29
+ }).pipe(Effect.orDie)
30
+ );
@@ -0,0 +1,23 @@
1
+ import * as ActionEntity from "@gjermundgaraba/effect-actions/ActionEntity";
2
+ import * as ActionHttp from "@gjermundgaraba/effect-actions/ActionHttp";
3
+ import { Effect, Layer } from "effect";
4
+ import { Entity } from "effect/cluster";
5
+
6
+ import { CartHttp } from "./Api.js";
7
+ import { carts } from "./cart/handlers.js";
8
+ import { CurrentCart } from "./cart/held.js";
9
+ import { Cart } from "./entities.js";
10
+ import { authenticate } from "./identity/verifier.js";
11
+
12
+ const cartOfAddress = Layer.effect(CurrentCart)(
13
+ Effect.map(Entity.CurrentAddress, ({ entityId }) => entityId)
14
+ );
15
+
16
+ export const entities = ActionEntity.layer(Cart, carts, {
17
+ services: cartOfAddress,
18
+ }).pipe(Layer.provide(authenticate));
19
+
20
+ export const routes = ActionHttp.layer(
21
+ CartHttp,
22
+ ActionEntity.reaching(Cart)
23
+ ).pipe(Layer.provide(authenticate));
@@ -0,0 +1,23 @@
1
+ import { createServer } from "node:http";
2
+
3
+ import { NodeHttpServer, NodeRuntime } from "@effect/platform-node";
4
+ import { SqliteClient } from "@effect/sql-sqlite-node";
5
+ import { Layer } from "effect";
6
+ import { HttpRouter } from "effect/http";
7
+
8
+ import { layerSingleRunner } from "./platform/cluster.js";
9
+ import { layerSqlCarts } from "./platform/sql-carts.js";
10
+ import { entities, routes } from "./routes.js";
11
+
12
+ const demoListen = { host: "127.0.0.1", port: 3000 };
13
+
14
+ const demoDatabase = SqliteClient.layer({ filename: "shopping-carts.db" });
15
+
16
+ HttpRouter.serve(routes).pipe(
17
+ Layer.provideMerge(entities),
18
+ Layer.provide([layerSingleRunner, layerSqlCarts]),
19
+ Layer.provide(Layer.orDie(demoDatabase)),
20
+ Layer.provide(NodeHttpServer.layer(createServer, demoListen)),
21
+ Layer.launch,
22
+ NodeRuntime.runMain()
23
+ );
@@ -0,0 +1,69 @@
1
+ import { SqliteClient } from "@effect/sql-sqlite-node";
2
+ import { expect, it } from "@effect/vitest";
3
+ import * as ActionHttp from "@gjermundgaraba/effect-actions/ActionHttp";
4
+ import * as Testing from "@gjermundgaraba/effect-actions/Testing";
5
+ import { Effect, Layer, Result } from "effect";
6
+ import { TestRunner } from "effect/cluster";
7
+ import { HttpClient, HttpClientRequest } from "effect/http";
8
+
9
+ import { CartHttp } from "../src/Api.js";
10
+ import { cartLimit } from "../src/cart/Cart.js";
11
+ import { layerSqlCarts } from "../src/platform/sql-carts.js";
12
+ import { entities, routes } from "../src/routes.js";
13
+
14
+ const server = Testing.layer(routes).pipe(
15
+ Layer.provideMerge(entities),
16
+ Layer.provide([TestRunner.layer, layerSqlCarts]),
17
+ Layer.provide(Layer.orDie(SqliteClient.layer({ filename: ":memory:" })))
18
+ );
19
+
20
+ const shopperAs = (token: string) =>
21
+ ActionHttp.client(CartHttp, {
22
+ transformClient: HttpClient.mapRequest(
23
+ HttpClientRequest.bearerToken(token)
24
+ ),
25
+ });
26
+
27
+ it.live("keeps each cart in the entity its id names, its own shopper's", () =>
28
+ Effect.gen(function* () {
29
+ const ada = yield* shopperAs("ada");
30
+ const grace = yield* shopperAs("grace");
31
+
32
+ yield* ada.addItem({ cart: "ada", item: "tea" });
33
+ yield* grace.addItem({ cart: "grace", item: "milk" });
34
+
35
+ expect(yield* ada.viewCart({ cart: "ada" })).toStrictEqual({
36
+ items: ["tea"],
37
+ });
38
+
39
+ const refused = yield* Effect.flip(
40
+ grace.addItem({ cart: "ada", item: "salt" })
41
+ );
42
+
43
+ expect(refused._tag).toBe("Forbidden");
44
+ expect(yield* grace.viewCart({ cart: "grace" })).toStrictEqual({
45
+ items: ["milk"],
46
+ });
47
+ }).pipe(Effect.provide(server))
48
+ );
49
+
50
+ it.live(
51
+ "adds one item past the cart's limit nowhere, however many arrive at once",
52
+ () =>
53
+ Effect.gen(function* () {
54
+ const ada = yield* shopperAs("ada");
55
+
56
+ const added = yield* Effect.forEach(
57
+ Array.from({ length: cartLimit + 1 }, (_, n) => `item ${n}`),
58
+ (item) => Effect.result(ada.addItem({ cart: "ada", item })),
59
+ { concurrency: "unbounded" }
60
+ );
61
+
62
+ expect(added.filter(Result.isFailure)).toMatchObject([
63
+ { failure: { _tag: "CartFull", limit: cartLimit } },
64
+ ]);
65
+ expect((yield* ada.viewCart({ cart: "ada" })).items).toHaveLength(
66
+ cartLimit
67
+ );
68
+ }).pipe(Effect.provide(server))
69
+ );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjermundgaraba/effect-actions",
3
- "version": "0.31.0",
3
+ "version": "0.32.0",
4
4
  "description": "Define Effect action contracts once and project them onto HTTP, MCP, Effect RPC, native Toolkits, and CLIs.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -37,6 +37,7 @@
37
37
  "exports": {
38
38
  "./Action": "./dist/Action.mjs",
39
39
  "./ActionCli": "./dist/ActionCli.mjs",
40
+ "./ActionEntity": "./dist/ActionEntity.mjs",
40
41
  "./ActionHttp": "./dist/ActionHttp.mjs",
41
42
  "./ActionMcp": "./dist/ActionMcp.mjs",
42
43
  "./ActionRpc": "./dist/ActionRpc.mjs",
@@ -44,6 +45,7 @@
44
45
  "./Authentication": "./dist/Authentication.mjs",
45
46
  "./Event": "./dist/Event.mjs",
46
47
  "./RequestPolicy": "./dist/RequestPolicy.mjs",
48
+ "./Stored": "./dist/Stored.mjs",
47
49
  "./Testing": "./dist/Testing.mjs",
48
50
  "./Webhook": "./dist/Webhook.mjs",
49
51
  "./package.json": "./package.json"
@@ -53,12 +55,13 @@
53
55
  },
54
56
  "devDependencies": {
55
57
  "@clanker-stuff/oxlint-config": "0.5.0",
56
- "@effect/platform-node": "4.1.3",
58
+ "@effect/platform-node": "4.1.4",
59
+ "@effect/sql-sqlite-node": "4.1.4",
57
60
  "@effect/tsgo": "0.67.7",
58
- "@effect/vitest": "4.1.3",
61
+ "@effect/vitest": "4.1.4",
59
62
  "@modelcontextprotocol/client": "2.4.0",
60
63
  "@types/node": "26.6.6",
61
- "effect": "4.1.3",
64
+ "effect": "4.1.4",
62
65
  "tsx": "4.23.15",
63
66
  "typescript": "7.0.2",
64
67
  "ultracite": "8.1.1",
@@ -67,12 +70,12 @@
67
70
  "vitest": "5.1.0"
68
71
  },
69
72
  "peerDependencies": {
70
- "effect": "~4.1.3"
73
+ "effect": "~4.1.4"
71
74
  },
72
75
  "devEngines": {
73
76
  "packageManager": {
74
77
  "name": "pnpm",
75
- "version": "12.17.0",
78
+ "version": "12.18.0",
76
79
  "onFail": "download"
77
80
  }
78
81
  },
@@ -1,15 +0,0 @@
1
- import { Any } from "../Action.mjs";
2
- import { Forbidden } from "./errors.mjs";
3
- import { Any as Any$1 } from "../Event.mjs";
4
- import { Context, Effect } from "effect";
5
- /**
6
- * A check every call and every subscription runs on its decoded input, on every surface, once the
7
- * surface has verified its caller and before its authorizer: what a host provides, as a Durable
8
- * Object refuses an input naming another object, to refuse an input it does not serve. Defaults
9
- * to none.
10
- *
11
- * **Gotchas**
12
- *
13
- * - Provide it to the layer graph the surfaces are built in, as `Layer.succeed(Action.InputCheck)(check)`: provided per request, it misses a socket's later calls.
14
- */
15
- export declare const InputCheck: Context.Reference<(contract: Any | Any$1, input: Any["input"]["Type"]) => Effect.Effect<void, Forbidden>>;
@@ -1,15 +0,0 @@
1
- import { Context, Effect } from "effect";
2
- // src/contract/input-check.ts
3
- /**
4
- * A check every call and every subscription runs on its decoded input, on every surface, once the
5
- * surface has verified its caller and before its authorizer: what a host provides, as a Durable
6
- * Object refuses an input naming another object, to refuse an input it does not serve. Defaults
7
- * to none.
8
- *
9
- * **Gotchas**
10
- *
11
- * - Provide it to the layer graph the surfaces are built in, as `Layer.succeed(Action.InputCheck)(check)`: provided per request, it misses a socket's later calls.
12
- */
13
- const InputCheck = Context.Reference("effect-actions/Action/InputCheck", { defaultValue: () => () => Effect.void });
14
- const checkInput = (contract, input) => Effect.flatMap(Effect.service(InputCheck), (check) => check(contract, input));
15
- export { InputCheck, checkInput };
@@ -1,34 +0,0 @@
1
- import { Any } from "../Action.mjs";
2
- import { Any as Any$1 } from "../Event.mjs";
3
- import { EventImplementation } from "../contract/feed.mjs";
4
- import { Implementation } from "../contract/implementation.mjs";
5
- import { AnyHttp } from "./client.mjs";
6
- import { HttpClient } from "effect/http";
7
- type Contract<H extends AnyHttp> = H["actions"][number] | H["events"][number];
8
- type Nothing<C extends Any | Any$1> = { readonly [K in C["name"]]: never; };
9
- /**
10
- * What `placed` returns: an implementation of the binding's actions where it has some, and one of
11
- * its event types where it has some, which require nothing.
12
- */
13
- export type Placed<H extends AnyHttp> = ReadonlyArray<Implementation<H["actions"][number], Nothing<H["actions"][number]>, never, never> | EventImplementation<H["events"][number], Nothing<H["events"][number]>, never, never>>;
14
- /**
15
- * The actions and event types of `binding` served where another server serves them, as a
16
- * surface's implementations: each call and subscription sent on over `binding` with the client
17
- * `client` answers for its decoded input and its contract, one of the binding's, carrying the
18
- * caller's headers, and its answer, its errors and its occurrences passed back as they are. The
19
- * surface serving them authenticates a protected one as its own and authorizes every caller; the
20
- * server reached authenticates and authorizes again.
21
- *
22
- * **Gotchas**
23
- *
24
- * - The caller's credential is verified twice, by the surface serving these and by the server reached, so both are given the verifier: a credential expiring between the two is refused by the second.
25
- * - The server reached builds its own verifier: one caching signing keys in memory fetches them in each of its instances, a Durable Object's again after each eviction.
26
- * - Every header of the caller's request is sent on but its connection's, its body's, what it accepts and an MCP request's routing headers (`mcp-*`): one that must not reach the server reached is removed per contract by the client `client` returns, `HttpClient.mapRequest(HttpClientRequest.removeHeader("cookie"))`, which runs after them.
27
- * - A header `client`'s client sets replaces the caller's of that name, as it is set after them: a service's own `authorization` is sent in place of the caller's.
28
- * - A call with no HTTP request, as through `Action.client` in process or an MCP stdio surface, sends no header on: a protected one reaches the server reached with no credential, which refuses it with `Unauthenticated`.
29
- * - An error the server reached declares beyond the action's own and the built-in ones, its binding's `error` or its verifier's, is a defect where it is passed back, answered as one.
30
- * - A server reached that does not serve one of them, its route a 404, is a defect naming it, with the fix: a declared error whose status is 404 is passed back as it is.
31
- * - A refusal of a subscription by the server reached comes after the surface admitted it, so it ends the subscription's stream where the surface's own would have answered its 401 or 403.
32
- */
33
- export declare const placed: <const H extends AnyHttp>(binding: H, client: (input: Contract<H>["input"]["Type"], contract: Contract<H>) => HttpClient.HttpClient) => Placed<H>;
34
- export {};
@@ -1,71 +0,0 @@
1
- import { allowAll } from "../Action.mjs";
2
- import { SubscriptionError, allowAll as allowAll$1 } from "../Event.mjs";
3
- import { EventImplementation } from "../contract/feed.mjs";
4
- import { Implementation, memoized } from "../contract/implementation.mjs";
5
- import { sendersWith } from "./client.mjs";
6
- import { isNotFound } from "./watch.mjs";
7
- import { Context, Effect, Option, Predicate, Schema, Stream } from "effect";
8
- import { Headers, HttpClient, HttpClientRequest, HttpServerRequest } from "effect/http";
9
- // src/http/placed.ts
10
- const ownedByTheRequest = (name) => [
11
- "host",
12
- "connection",
13
- "keep-alive",
14
- "te",
15
- "trailer",
16
- "transfer-encoding",
17
- "upgrade"
18
- ].includes(name) || [
19
- "content-",
20
- "accept",
21
- "proxy-",
22
- "sec-websocket-",
23
- "mcp-"
24
- ].some((family) => name.startsWith(family));
25
- const forwarded = Effect.map(Effect.serviceOption(HttpServerRequest.HttpServerRequest), Option.match({
26
- onNone: () => Headers.empty,
27
- onSome: ({ headers }) => Headers.fromInput(Object.entries(headers).filter(([name]) => !ownedByTheRequest(name)))
28
- }));
29
- var Sending = class extends Context.Service()("effect-actions/ActionHttp/placed/Sending") {};
30
- const dispatching = HttpClient.makeWith((request) => Effect.flatMap(Effect.all([request, Effect.service(Sending)]), ([sent, client]) => client.execute(sent)), (request) => Effect.succeed(request));
31
- const isSubscriptionError = Schema.is(SubscriptionError);
32
- const isNotServed = Predicate.compose(isSubscriptionError, (error) => Predicate.isTagged(error.reason, "NotServed"));
33
- const notServedThere = (name) => /* @__PURE__ */ new Error(`ActionHttp.placed: the server its client reaches does not serve ${name} (serve its implementation in that server's ActionHttp.layer of this binding)`);
34
- /**
35
- * The actions and event types of `binding` served where another server serves them, as a
36
- * surface's implementations: each call and subscription sent on over `binding` with the client
37
- * `client` answers for its decoded input and its contract, one of the binding's, carrying the
38
- * caller's headers, and its answer, its errors and its occurrences passed back as they are. The
39
- * surface serving them authenticates a protected one as its own and authorizes every caller; the
40
- * server reached authenticates and authorizes again.
41
- *
42
- * **Gotchas**
43
- *
44
- * - The caller's credential is verified twice, by the surface serving these and by the server reached, so both are given the verifier: a credential expiring between the two is refused by the second.
45
- * - The server reached builds its own verifier: one caching signing keys in memory fetches them in each of its instances, a Durable Object's again after each eviction.
46
- * - Every header of the caller's request is sent on but its connection's, its body's, what it accepts and an MCP request's routing headers (`mcp-*`): one that must not reach the server reached is removed per contract by the client `client` returns, `HttpClient.mapRequest(HttpClientRequest.removeHeader("cookie"))`, which runs after them.
47
- * - A header `client`'s client sets replaces the caller's of that name, as it is set after them: a service's own `authorization` is sent in place of the caller's.
48
- * - A call with no HTTP request, as through `Action.client` in process or an MCP stdio surface, sends no header on: a protected one reaches the server reached with no credential, which refuses it with `Unauthenticated`.
49
- * - An error the server reached declares beyond the action's own and the built-in ones, its binding's `error` or its verifier's, is a defect where it is passed back, answered as one.
50
- * - A server reached that does not serve one of them, its route a 404, is a defect naming it, with the fix: a declared error whose status is 404 is passed back as it is.
51
- * - A refusal of a subscription by the server reached comes after the surface admitted it, so it ends the subscription's stream where the surface's own would have answered its 401 or 403.
52
- */
53
- const placed = (binding, client) => {
54
- const route = client;
55
- const sendingTo = (input, contract) => HttpClient.mapRequestInputEffect(route(input, contract), (request) => Effect.map(forwarded, (headers) => HttpClientRequest.setHeaders(request, headers)));
56
- const senders = sendersWith(binding, dispatching, void 0);
57
- const handlerOf = ({ method }, action) => {
58
- const send = method(action);
59
- return (input, reporting) => {
60
- const sent = send(input, ...reporting === void 0 ? [] : [{ onProgress: reporting.progress }]);
61
- const sending = sendingTo(input, action);
62
- return Stream.isStream(sent) ? sent.pipe(Stream.provideService(Sending, sending), Stream.catchIf(isNotFound, () => Stream.die(notServedThere(action.name)))) : sent.pipe(Effect.provideService(Sending, sending), Effect.catchIf(isNotFound, () => Effect.die(notServedThere(action.name))));
63
- };
64
- };
65
- const runOf = ({ transport }, event) => ({
66
- poll: (input, cursor) => transport(event, input).poll(cursor).pipe(Effect.provideService(Sending, sendingTo(input, event)), Effect.catchIf(isNotServed, () => Effect.die(notServedThere(event.name)))),
67
- stream: (input, cursor) => transport(event, input).stream(cursor).pipe(Stream.provideService(Sending, sendingTo(input, event)), Stream.catchIf(isNotServed, () => Stream.die(notServedThere(event.name))))
68
- });
69
- return [...binding.actions.length === 0 ? [] : [new Implementation(binding.actions, memoized(Effect.map(senders, (built) => binding.actions.map((action) => [action, handlerOf(built, action)]))), memoized(Effect.succeed(allowAll)))], ...binding.events.length === 0 ? [] : [new EventImplementation(binding.events, binding.events.map((event) => [event, memoized(Effect.map(senders, (built) => runOf(built, event)))]), memoized(Effect.succeed(allowAll$1)))]];
70
- };
71
- export { placed };