foldkit-remote-server 0.13.4 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -837,6 +837,31 @@ not found) and from every query, and a ref to it is dropped from a relation:
837
837
  a list leaves it out and a `one` ref reads `null`, as a database binding's
838
838
  `visible` hides it.
839
839
 
840
+ An entity no row backs, answered from who is asking (`foldkit-guard`'s
841
+ `Me`, say), is a Source of its own beside the rows, in `entities`. Leave it
842
+ out of the rows' domain: a Source for an entity the domain declares is
843
+ refused when the backend is made, as two Sources for one entity are.
844
+
845
+ ```ts
846
+ const Whoami = Entity.make('Whoami', Schema.Struct({ id: Schema.String, admin: Schema.Boolean }))
847
+ const WhoamiSource = RemoteServer.entity<Principal>(Whoami, {
848
+ read: ({ ids, principal }) =>
849
+ Effect.succeed(ids.map(id => ({ id, values: { admin: principal.isAdmin } }))),
850
+ })
851
+
852
+ // No principal: served through `serveFetch` or `handlers`, as each request's.
853
+ const { server } = RemoteServer.memory({
854
+ domain: Data, // Project only; Whoami is the Source's
855
+ rows: { Project: [{ id: 'p1', name: 'Apollo', privateNotes: 'Internal' }] },
856
+ entities: [WhoamiSource],
857
+ })
858
+ const asVisitor = RemoteServer.handlers(server, { isAdmin: false })
859
+ ```
860
+
861
+ `principal` is only who `layer` answers as. Without it (and a principal type
862
+ that does not admit `undefined`), the backend has no `layer`, only its store
863
+ and `server`, so nothing can read the rows as nobody.
864
+
840
865
  ## Over a MessagePort
841
866
 
842
867
  `servePort(handlers, port)` from `foldkit-remote-server/port` answers
@@ -878,6 +903,13 @@ const route = async (request: Request): Promise<Response> => {
878
903
  - **400** with `{ error }`: the body is not a request, names an operation
879
904
  Remote does not have, or its payload fails the protocol's schema. No
880
905
  handler ran.
906
+ - **401** with `{ error, unauthenticated: { reason? } }`: a handler could not
907
+ tell who is asking (`RemoteServer.unauthenticated`). The client fails the
908
+ call, of whatever kind, with `_tag: 'Unauthenticated'`.
909
+ - **403** with `{ error, forbidden: { reason? } }`: who is asking may not do
910
+ this (`RemoteServer.forbid`).
911
+ - **422** with `{ error, refusal }`: the mutation refused what was asked, in
912
+ its own `Refusal`.
881
913
  - **500** with `{ error }`: the handler failed, and the message is its own;
882
914
  or something on this side broke, and the message is `Internal error`,
883
915
  nothing more.
@@ -890,9 +922,10 @@ data.
890
922
 
891
923
  `serveFetch` from `foldkit-remote-server/fetch` is that route as a value: a
892
924
  `(request: Request, env: Env) => Promise<Response>` for a Worker's `fetch`,
893
- or any other runtime that speaks `Request`/`Response`. The principal is
894
- resolved per request, and the Sources' requirements are provided per request
895
- from the environment:
925
+ or any other runtime that speaks `Request`/`Response`. Each request is one
926
+ Effect: `layer` is built from the environment, then `resolvePrincipal` says
927
+ who is asking, then the request is answered as them. The resolver may need
928
+ what `layer` provides (a session store, an auth service):
896
929
 
897
930
  ```ts
898
931
  import { serveFetch } from 'foldkit-remote-server/fetch'
@@ -900,16 +933,37 @@ import { serveFetch } from 'foldkit-remote-server/fetch'
900
933
  export default {
901
934
  fetch: serveFetch({
902
935
  server,
903
- resolvePrincipal: request => ({ actorId: request.headers.get('x-actor') ?? 'anon' }),
936
+ resolvePrincipal: request =>
937
+ Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),
904
938
  layer: env => databaseLayer(drizzle(env.DB)),
905
939
  }),
906
940
  }
907
941
  ```
908
942
 
909
943
  Only `POST`s to `path` (default `/remote`) are answered; anything else is a 404. A body that is not JSON, or not a request, is a 400 that reaches no
910
- handler; a handler's failure a 500 with its message. A principal resolution
911
- that throws is a 401 with its message; anything else this side breaks,
912
- including layer provision, a 500 that says nothing of it.
944
+ handler; a handler's failure a 500 with its message.
945
+
946
+ A resolver refuses the caller by failing with
947
+ `RemoteServer.unauthenticated(reason?)`: a 401 whose body is
948
+ `{ error, unauthenticated: { reason? } }`, as `answer`'s 403 carries
949
+ `forbidden`, and whose `reason` is the only thing the caller learns. Anything
950
+ else this side breaks, the resolver's defects and the layer included, is a
951
+ 500 that says nothing of it. A visitor is not a refusal: resolve one to the
952
+ principal your Sources treat as nobody, and refuse only a credential that was
953
+ sent and no longer holds.
954
+
955
+ `headers: principal => ({ … })` adds headers to every answer to that
956
+ principal, a live stream's included; a refusal answered no one and carries
957
+ none. `foldkit-auth`'s `AuthServer.answered` uses it to say whom each answer
958
+ was for.
959
+
960
+ `revalidate: { every, key? }` asks `resolvePrincipal` again, of the same
961
+ request, every `every` while a live stream is open. A refusal ends the
962
+ stream with `Unauthenticated`; a principal whose `key` differs from the one
963
+ it opened with ends it as a live error, which the client opens again after,
964
+ as the new principal. `key` is who a principal is, as `liveHub`'s `key`:
965
+ with guards, `key: Policy.keyOf`. Without `revalidate` a stream serves the
966
+ principal it opened with, a revoked session included, until it closes.
913
967
 
914
968
  A body that opens live (`{ operation: 'live', payload }`) is answered with
915
969
  the stream as `text/event-stream`: one `data:` frame per `LiveChange`, then
package/dist/fetch.d.mts CHANGED
@@ -1,18 +1,49 @@
1
1
  import { LiveHub, ServerDefinition } from "./index.mjs";
2
- import { Duration, Layer } from "effect";
2
+ import { Duration, Effect, Layer } from "effect";
3
+ import { RemoteUnauthenticated } from "foldkit-remote";
3
4
  //#region src/fetch.d.ts
4
5
  /** What `serveFetch` needs of the host runtime, per request. */
5
- export interface FetchConfig<P, R, Env> {
6
+ export interface FetchConfig<P, R, Env, RP = never> {
6
7
  /** The server definition, as `RemoteServer.make` built it. */
7
8
  readonly server: ServerDefinition<P, R>;
8
- /** Who this request is, from the request and the environment. May throw. */
9
- readonly resolvePrincipal: (request: Request, env: Env) => P | Promise<P>;
10
- /** What the Sources need, from the environment. Kept cheap: built per request. */
11
- readonly layer: (env: Env) => Layer.Layer<R>;
9
+ /**
10
+ * Who this request is, from the request and the environment. Fails with
11
+ * `RemoteServer.unauthenticated(reason?)` to refuse the caller: a 401.
12
+ * What it needs (a session store, an auth service) comes from `layer`.
13
+ */
14
+ readonly resolvePrincipal: (request: Request, env: Env) => Effect.Effect<P, RemoteUnauthenticated, RP>;
15
+ /**
16
+ * What the Sources and the resolver need, from the environment. Built per
17
+ * request, so kept cheap, and closed when the answer is sent, or, for a
18
+ * live stream, when the stream ends.
19
+ */
20
+ readonly layer: (env: Env) => Layer.Layer<R | RP>;
12
21
  /** The path answered; anything else is a 404. Default `/remote`. */
13
22
  readonly path?: string | undefined;
23
+ /**
24
+ * Headers every answer to `principal` carries, a live stream's included;
25
+ * a refusal has no principal and carries none. Whom the request was
26
+ * answered as, say, for a client to repeat (`foldkit-auth`'s
27
+ * `AuthServer.answered`).
28
+ */
29
+ readonly headers?: ((principal: P) => Readonly<Record<string, string>>) | undefined;
14
30
  /** A hub whose `changed`/`deleted` signals reach the live streams this serves. */
15
31
  readonly live?: LiveHub<P, R> | undefined;
32
+ /**
33
+ * Asks `resolvePrincipal` again, of the same request, every `every` while a
34
+ * live stream is open. A refusal ends the stream with `Unauthenticated`,
35
+ * which the client reads as a lost session; a principal whose `key`
36
+ * differs from the one the stream opened with (`Policy.keyOf`, as
37
+ * `liveHub`'s `key`) ends it as a live error, which the client opens again
38
+ * after, as the new principal; without `key` only a refusal ends it.
39
+ * Without `revalidate` a stream serves the principal it opened with until
40
+ * it closes, a revoked session included.
41
+ * `every` must be longer than zero: each pass asks the session store.
42
+ */
43
+ readonly revalidate?: {
44
+ readonly every: Duration.Input;
45
+ readonly key?: ((principal: P) => unknown) | undefined;
46
+ } | undefined;
16
47
  /** A heartbeat comment every this often, keeping idle streams alive through proxies. Default 15 seconds. */
17
48
  readonly liveHeartbeat?: Duration.Input | undefined;
18
49
  /** A read batch may not name more ids of one entity than this; default 1000. */
@@ -22,21 +53,25 @@ export interface FetchConfig<P, R, Env> {
22
53
  }
23
54
  /**
24
55
  * Answers Remote `POST`s with `Response`s: what a Worker's `fetch` hands to
25
- * the route. A body that is not JSON, or not a request, is a 400 that reaches
26
- * no handler; a handler's failure a 500 with its message; anything this side
27
- * breaks, including principal resolution and layer provision, a 500 that says
56
+ * the route. Each request is one Effect, with `layer` built once for it:
57
+ * `resolvePrincipal` first, which refuses with `RemoteServer.unauthenticated`
58
+ * (a 401, its `reason` the only words the caller reads); then the body. A
59
+ * body that is not JSON, or not a request, is a 400 that reaches no handler;
60
+ * a handler's failure a 500 with its message; anything else this side
61
+ * breaks, the resolver's defects and the layer included, a 500 that says
28
62
  * nothing of it. A live open is answered with the stream instead.
29
63
  *
30
64
  * ```ts
31
65
  * export default {
32
66
  * fetch: serveFetch({
33
67
  * server,
34
- * resolvePrincipal: request => ({ actorId: request.headers.get('x-actor') ?? 'anon' }),
68
+ * resolvePrincipal: request =>
69
+ * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),
35
70
  * layer: env => databaseLayer(drizzle(env.DB)),
36
71
  * }),
37
72
  * }
38
73
  * ```
39
74
  */
40
- export declare const serveFetch: <P, R, Env>(config: FetchConfig<P, R, Env>) => ((request: Request, env: Env) => Promise<Response>);
75
+ export declare const serveFetch: <P, R, Env, RP = never>(config: FetchConfig<P, R, Env, RP>) => ((request: Request, env: Env) => Promise<Response>);
41
76
  //#endregion
42
77
  //# sourceMappingURL=fetch.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;iBAkBiB,YAAY,GAAG,GAAG;;WAExB,QAAQ,iBAAiB,GAAG;;WAE5B,mBAAmB,SAAS,SAAS,KAAK,QAAQ,IAAI,QAAQ;;WAE9D,QAAQ,KAAK,QAAQ,MAAM,MAAM;;WAEjC;;WAEA,OAAO,QAAQ,GAAG;;WAElB,gBAAgB,SAAS;;WAEzB;;WAEA;;;;;;;;;;;;;;;;;;;qBAgHE,aAAc,GAAG,GAAG,KAAG,QAC1B,YAAY,GAAG,GAAG,WACvB,SAAS,SAAS,KAAK,QAAQ,QAAQ"}
1
+ {"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;;iBAqCiB,YAAY,GAAG,GAAG,KAAK;;WAE7B,QAAQ,iBAAiB,GAAG;;;;;;WAM5B,mBACP,SAAS,SACT,KAAK,QACF,OAAO,OAAO,GAAG,uBAAuB;;;;;;WAMpC,QAAQ,KAAK,QAAQ,MAAM,MAAM,IAAI;;WAErC;;;;;;;WAOA,YAAY,WAAW,MAAM,SAAS;;WAEtC,OAAO,QAAQ,GAAG;;;;;;;;;;;;WAYlB;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,gBAAgB,SAAS;;WAEzB;;WAEA;;;;;;;;;;;;;;;;;;;;;;;qBA+IE,aAAc,GAAG,GAAG,KAAK,YAAU,QACtC,YAAY,GAAG,GAAG,KAAK,UAC5B,SAAS,SAAS,KAAK,QAAQ,QAAQ"}
package/dist/fetch.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { RemoteServer } from "./index.mjs";
2
- import { Deferred, Effect, Schedule, Schema, Stream } from "effect";
3
- import { LiveRequirement } from "foldkit-remote";
1
+ import { c as unauthenticatedAnswer, n as RemoteServer } from "./src-DKYZjLc7.mjs";
2
+ import { Cause, Deferred, Duration, Effect, Exit, Layer, Option, Schedule, Schema, Scope, Stream } from "effect";
3
+ import { LiveRequirement, RemoteLiveError } from "foldkit-remote";
4
4
  //#region src/fetch.ts
5
5
  /**
6
6
  * `foldkit-remote-server/fetch`: `RemoteServer` over the Fetch API, for
@@ -20,8 +20,14 @@ const LiveFetchRequest = Schema.Struct({
20
20
  operation: Schema.Literal("live"),
21
21
  payload: Schema.Unknown
22
22
  });
23
- /** A terminal stream failure, so the client fails with its message instead of hanging. */
24
- const errorFrame = (message) => `event: error\ndata: ${JSON.stringify({ message })}\n\n`;
23
+ /**
24
+ * A terminal stream failure, so the client fails with its message instead of
25
+ * hanging; a refusal of who is asking says so, as a 401's body does.
26
+ */
27
+ const errorFrame = (message, refusal = {}) => `event: error\ndata: ${JSON.stringify({
28
+ message,
29
+ ...refusal
30
+ })}\n\n`;
25
31
  /**
26
32
  * The live stream as SSE bytes: one `data:` frame per change, then a
27
33
  * terminal `event: error` frame when the stream fails rather than ends. A
@@ -32,12 +38,13 @@ const errorFrame = (message) => `event: error\ndata: ${JSON.stringify({ message
32
38
  * with nothing to serve still ends. A client that disconnects interrupts
33
39
  * the subscription, as closing the RPC stream would.
34
40
  */
35
- const liveBytes = (handlers, payload, heartbeat) => Stream.unwrap(Effect.gen(function* () {
41
+ const liveBytes = (handlers, payload, heartbeat, checked) => Stream.unwrap(Effect.gen(function* () {
36
42
  const ended = yield* Deferred.make();
37
- const events = handlers.FoldkitRemoteLive(payload).pipe(Stream.map((change) => `data: ${JSON.stringify(change)}\n\n`), Stream.catchTags({
43
+ const events = Stream.merge(handlers.FoldkitRemoteLive(payload), checked, { haltStrategy: "left" }).pipe(Stream.map((change) => `data: ${JSON.stringify(change)}\n\n`), Stream.catchTags({
38
44
  RemoteLiveError: (error) => Stream.succeed(errorFrame(error.message)),
39
- RemoteProtocolError: (error) => Stream.succeed(errorFrame(error.message))
40
- }), Stream.ensuring(Deferred.succeed(ended, void 0)));
45
+ RemoteProtocolError: (error) => Stream.succeed(errorFrame(error.message)),
46
+ Unauthenticated: (error) => Stream.succeed(errorFrame(error.message, { unauthenticated: unauthenticatedAnswer(error).body.unauthenticated }))
47
+ }), Stream.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Stream.failCause(cause) : Stream.succeed(errorFrame("Internal error"))), Stream.ensuring(Deferred.succeed(ended, void 0)));
41
48
  const beats = Stream.concat(Stream.succeed(": ping\n\n"), Stream.fromSchedule(Schedule.spaced(heartbeat)).pipe(Stream.map(() => ": ping\n\n"))).pipe(Stream.interruptWhen(Deferred.await(ended)));
42
49
  return Stream.merge(events, beats);
43
50
  })).pipe(Stream.encodeText);
@@ -57,34 +64,36 @@ const isLiveOpen = (body) => {
57
64
  const DEFAULT_HEARTBEAT = "15 seconds";
58
65
  /**
59
66
  * Answers a live open with the stream as `text/event-stream`. A payload no
60
- * live stream speaks is a 400 that subscribes to nothing; anything this side
61
- * breaks building the stream is a 500 that says nothing of it. Once the
62
- * stream runs, its own failures are its terminal `event: error` frame.
67
+ * live stream speaks is a 400 that subscribes to nothing. Once the stream
68
+ * runs, its own failures are its terminal `event: error` frame.
63
69
  */
64
- const liveResponse = (handlers, payload, layer, heartbeat) => {
65
- let requirement;
66
- try {
67
- requirement = Schema.decodeUnknownSync(LiveRequirement)(payload);
68
- } catch {
69
- return Promise.resolve(Response.json({ error: "The live payload is not a requirement" }, { status: 400 }));
70
- }
71
- return Effect.runPromise(Stream.toReadableStreamEffect(liveBytes(handlers, requirement, heartbeat)).pipe(Effect.provide(layer), Effect.map((body) => new Response(body, { headers: {
70
+ const liveResponse = (handlers, payload, heartbeat, checked, release, headers) => Schema.decodeUnknownEffect(LiveRequirement)(payload).pipe(Effect.matchEffect({
71
+ onFailure: () => Effect.succeed(Response.json({ error: "The live payload is not a requirement" }, {
72
+ status: 400,
73
+ headers
74
+ })),
75
+ onSuccess: (requirement) => Effect.map(Stream.toReadableStreamEffect(liveBytes(handlers, requirement, heartbeat, checked).pipe(Stream.ensuring(release))), (body) => new Response(body, { headers: {
76
+ ...headers,
72
77
  "content-type": "text/event-stream",
73
78
  "cache-control": "no-cache"
74
- } })))).catch(() => Response.json({ error: "Internal error" }, { status: 500 }));
75
- };
79
+ } }))
80
+ }));
76
81
  /**
77
82
  * Answers Remote `POST`s with `Response`s: what a Worker's `fetch` hands to
78
- * the route. A body that is not JSON, or not a request, is a 400 that reaches
79
- * no handler; a handler's failure a 500 with its message; anything this side
80
- * breaks, including principal resolution and layer provision, a 500 that says
83
+ * the route. Each request is one Effect, with `layer` built once for it:
84
+ * `resolvePrincipal` first, which refuses with `RemoteServer.unauthenticated`
85
+ * (a 401, its `reason` the only words the caller reads); then the body. A
86
+ * body that is not JSON, or not a request, is a 400 that reaches no handler;
87
+ * a handler's failure a 500 with its message; anything else this side
88
+ * breaks, the resolver's defects and the layer included, a 500 that says
81
89
  * nothing of it. A live open is answered with the stream instead.
82
90
  *
83
91
  * ```ts
84
92
  * export default {
85
93
  * fetch: serveFetch({
86
94
  * server,
87
- * resolvePrincipal: request => ({ actorId: request.headers.get('x-actor') ?? 'anon' }),
95
+ * resolvePrincipal: request =>
96
+ * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),
88
97
  * layer: env => databaseLayer(drizzle(env.DB)),
89
98
  * }),
90
99
  * }
@@ -92,29 +101,60 @@ const liveResponse = (handlers, payload, layer, heartbeat) => {
92
101
  */
93
102
  const serveFetch = (config) => {
94
103
  const path = config.path ?? "/remote";
95
- return async (request, env) => {
96
- if (request.method !== "POST" || new URL(request.url).pathname !== path) return Response.json({ error: "not found" }, { status: 404 });
97
- let principal;
98
- try {
99
- principal = await config.resolvePrincipal(request, env);
100
- } catch (error) {
101
- return Response.json({ error: error instanceof Error ? error.message : String(error) }, { status: 401 });
102
- }
103
- let body;
104
- try {
105
- body = await request.json();
106
- } catch {
107
- return Response.json({ error: "The body is not JSON" }, { status: 400 });
108
- }
104
+ const heartbeat = config.liveHeartbeat ?? DEFAULT_HEARTBEAT;
105
+ if (config.revalidate !== void 0 && !Duration.isGreaterThan(Duration.fromInputUnsafe(config.revalidate.every), Duration.zero)) throw new Error("serveFetch: revalidate.every must be longer than zero");
106
+ /** The live stream's principal, asked again of its request while it runs. */
107
+ const revalidation = (request, env, opened) => {
108
+ const { revalidate } = config;
109
+ if (revalidate === void 0) return Stream.empty;
110
+ return Stream.fromSchedule(Schedule.spaced(revalidate.every)).pipe(Stream.mapEffect(() => config.resolvePrincipal(request, env)), Stream.mapEffect((now) => revalidate.key === void 0 || revalidate.key(opened) === revalidate.key(now) ? Effect.void : Effect.fail(new RemoteLiveError({ message: "Who is asking changed: open the stream again" }))), Stream.drain);
111
+ };
112
+ /** `live` is whether the response streams, and so owns `scope` until it ends. */
113
+ const respond = (request, env, scope) => Effect.gen(function* () {
114
+ const principal = yield* config.resolvePrincipal(request, env);
115
+ const headers = config.headers?.(principal) ?? {};
116
+ const body = yield* Effect.option(Effect.tryPromise(() => request.json()));
117
+ if (Option.isNone(body)) return {
118
+ response: Response.json({ error: "The body is not JSON" }, {
119
+ status: 400,
120
+ headers
121
+ }),
122
+ live: false
123
+ };
109
124
  const handlers = RemoteServer.handlers(config.server, principal, {
110
125
  live: config.live,
111
126
  maxIdsPerEntity: config.maxIdsPerEntity,
112
127
  maxDepth: config.maxDepth
113
128
  });
114
- if (isLiveOpen(body)) return liveResponse(handlers, body.payload, config.layer(env), config.liveHeartbeat ?? DEFAULT_HEARTBEAT);
129
+ if (isLiveOpen(body.value)) {
130
+ const response = yield* liveResponse(handlers, body.value.payload, heartbeat, revalidation(request, env, principal), Scope.close(scope, Exit.void), headers);
131
+ return {
132
+ response,
133
+ live: response.status === 200
134
+ };
135
+ }
136
+ const answered = yield* RemoteServer.answer(handlers, body.value);
137
+ return {
138
+ response: Response.json(answered.body, {
139
+ status: answered.status,
140
+ headers
141
+ }),
142
+ live: false
143
+ };
144
+ }).pipe(Effect.catchTag("Unauthenticated", (refusal) => {
145
+ const { status, body } = unauthenticatedAnswer(refusal);
146
+ return Effect.succeed({
147
+ response: Response.json(body, { status }),
148
+ live: false
149
+ });
150
+ }));
151
+ return async (request, env) => {
152
+ if (request.method !== "POST" || new URL(request.url).pathname !== path) return Response.json({ error: "not found" }, { status: 404 });
115
153
  try {
116
- const answered = await Effect.runPromise(RemoteServer.answer(handlers, body).pipe(Effect.provide(config.layer(env))));
117
- return Response.json(answered.body, { status: answered.status });
154
+ return await Effect.runPromise(Effect.gen(function* () {
155
+ const scope = yield* Scope.make();
156
+ return (yield* Layer.buildWithScope(config.layer(env), scope).pipe(Effect.flatMap((context) => Effect.provide(respond(request, env, scope), context)), Effect.onExit((exit) => Exit.isSuccess(exit) && exit.value.live ? Effect.void : Scope.close(scope, exit)))).response;
157
+ }));
118
158
  } catch {
119
159
  return Response.json({ error: "Internal error" }, { status: 500 });
120
160
  }
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.mjs","names":[],"sources":["../src/fetch.ts"],"sourcesContent":["/**\n * `foldkit-remote-server/fetch`: `RemoteServer` over the Fetch API, for\n * Cloudflare Workers and any other runtime that speaks `Request`/`Response`.\n *\n * Reads, queries, and mutations ride one `POST` each, as `Remote.http` sends\n * them and `RemoteServer.answer` answers them. Live requirements ride one\n * `POST` that answers with a `text/event-stream` of `LiveChange` frames, one\n * `data:` frame per change and a terminal `event: error` frame when the\n * stream fails; `Remote.httpWithLive` is the other end. The principal is\n * resolved per request, from whatever the runtime hands over (a header, a\n * binding, a session), and the Sources' requirements are provided per\n * request from the environment (a D1 binding, a connection string).\n */\nimport { Deferred, Effect, Schedule, Schema, Stream, type Duration, type Layer } from 'effect'\nimport { LiveRequirement, type RemoteRpcClient } from 'foldkit-remote'\nimport { RemoteServer, type LiveHub, type ServerDefinition } from './index.js'\n\n/** What `serveFetch` needs of the host runtime, per request. */\nexport interface FetchConfig<P, R, Env> {\n /** The server definition, as `RemoteServer.make` built it. */\n readonly server: ServerDefinition<P, R>\n /** Who this request is, from the request and the environment. May throw. */\n readonly resolvePrincipal: (request: Request, env: Env) => P | Promise<P>\n /** What the Sources need, from the environment. Kept cheap: built per request. */\n readonly layer: (env: Env) => Layer.Layer<R>\n /** The path answered; anything else is a 404. Default `/remote`. */\n readonly path?: string | undefined\n /** A hub whose `changed`/`deleted` signals reach the live streams this serves. */\n readonly live?: LiveHub<P, R> | undefined\n /** A heartbeat comment every this often, keeping idle streams alive through proxies. Default 15 seconds. */\n readonly liveHeartbeat?: Duration.Input | undefined\n /** A read batch may not name more ids of one entity than this; default 1000. */\n readonly maxIdsPerEntity?: number | undefined\n /** A nested selection may not reach further than this many levels; default 8. */\n readonly maxDepth?: number | undefined\n}\n\n/** A live open over fetch: the requirements and the cursor it resumes after. */\nconst LiveFetchRequest = Schema.Struct({\n operation: Schema.Literal('live'),\n payload: Schema.Unknown,\n})\n\n/** A terminal stream failure, so the client fails with its message instead of hanging. */\nconst errorFrame = (message: string): string =>\n `event: error\\ndata: ${JSON.stringify({ message })}\\n\\n`\n\n/**\n * The live stream as SSE bytes: one `data:` frame per change, then a\n * terminal `event: error` frame when the stream fails rather than ends. A\n * `: ping` comment opens the stream, so headers and a first byte reach the\n * client at once, and rides along every `heartbeat` so a stream with nothing\n * to say still moves: workers cancel responses that go quiet, and proxies\n * drop idle connections. The heartbeat ends with the events, so a stream\n * with nothing to serve still ends. A client that disconnects interrupts\n * the subscription, as closing the RPC stream would.\n */\nconst liveBytes = <R>(\n handlers: RemoteRpcClient<R>,\n payload: Schema.Schema.Type<typeof LiveRequirement>,\n heartbeat: Duration.Input,\n): Stream.Stream<Uint8Array, never, R> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const ended = yield* Deferred.make<void>()\n const events = handlers.FoldkitRemoteLive(payload).pipe(\n Stream.map(change => `data: ${JSON.stringify(change)}\\n\\n`),\n Stream.catchTags({\n RemoteLiveError: error => Stream.succeed(errorFrame(error.message)),\n RemoteProtocolError: error => Stream.succeed(errorFrame(error.message)),\n }),\n Stream.ensuring(Deferred.succeed(ended, undefined)),\n )\n const beats = Stream.concat(\n Stream.succeed(': ping\\n\\n'),\n Stream.fromSchedule(Schedule.spaced(heartbeat)).pipe(Stream.map(() => ': ping\\n\\n')),\n ).pipe(Stream.interruptWhen(Deferred.await(ended)))\n return Stream.merge(events, beats)\n }),\n ).pipe(Stream.encodeText)\n\n/**\n * Whether the body opens a live stream rather than asking `answer`. Anything\n * else, including a body that is not a request at all, is `answer`'s to\n * refuse with a 400.\n */\nconst isLiveOpen = (body: unknown): body is Schema.Schema.Type<typeof LiveFetchRequest> => {\n try {\n return Schema.decodeUnknownSync(LiveFetchRequest)(body).operation === 'live'\n } catch {\n return false\n }\n}\n\n/** Heartbeats when the caller names none: under proxy idle timeouts. */\nconst DEFAULT_HEARTBEAT: Duration.Input = '15 seconds'\n\n/**\n * Answers a live open with the stream as `text/event-stream`. A payload no\n * live stream speaks is a 400 that subscribes to nothing; anything this side\n * breaks building the stream is a 500 that says nothing of it. Once the\n * stream runs, its own failures are its terminal `event: error` frame.\n */\nconst liveResponse = <R>(\n handlers: RemoteRpcClient<R>,\n payload: unknown,\n layer: Layer.Layer<R>,\n heartbeat: Duration.Input,\n): Promise<Response> => {\n let requirement: Schema.Schema.Type<typeof LiveRequirement>\n try {\n requirement = Schema.decodeUnknownSync(LiveRequirement)(payload)\n } catch {\n return Promise.resolve(\n Response.json({ error: 'The live payload is not a requirement' }, { status: 400 }),\n )\n }\n return Effect.runPromise(\n Stream.toReadableStreamEffect(liveBytes(handlers, requirement, heartbeat)).pipe(\n Effect.provide(layer),\n Effect.map(\n body =>\n new Response(body, {\n headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' },\n }),\n ),\n ),\n ).catch(() => Response.json({ error: 'Internal error' }, { status: 500 }))\n}\n/**\n * Answers Remote `POST`s with `Response`s: what a Worker's `fetch` hands to\n * the route. A body that is not JSON, or not a request, is a 400 that reaches\n * no handler; a handler's failure a 500 with its message; anything this side\n * breaks, including principal resolution and layer provision, a 500 that says\n * nothing of it. A live open is answered with the stream instead.\n *\n * ```ts\n * export default {\n * fetch: serveFetch({\n * server,\n * resolvePrincipal: request => ({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * layer: env => databaseLayer(drizzle(env.DB)),\n * }),\n * }\n * ```\n */\nexport const serveFetch = <P, R, Env>(\n config: FetchConfig<P, R, Env>,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const path = config.path ?? '/remote'\n return async (request, env) => {\n if (request.method !== 'POST' || new URL(request.url).pathname !== path) {\n return Response.json({ error: 'not found' }, { status: 404 })\n }\n let principal: P\n try {\n principal = await config.resolvePrincipal(request, env)\n } catch (error) {\n return Response.json(\n { error: error instanceof Error ? error.message : String(error) },\n { status: 401 },\n )\n }\n let body: unknown\n try {\n body = await request.json()\n } catch {\n return Response.json({ error: 'The body is not JSON' }, { status: 400 })\n }\n // Bound per request: the principal is the request's own, as everywhere else.\n const handlers = RemoteServer.handlers(config.server, principal, {\n live: config.live,\n maxIdsPerEntity: config.maxIdsPerEntity,\n maxDepth: config.maxDepth,\n })\n if (isLiveOpen(body)) {\n return liveResponse(\n handlers,\n body.payload,\n config.layer(env),\n config.liveHeartbeat ?? DEFAULT_HEARTBEAT,\n )\n }\n try {\n const answered = await Effect.runPromise(\n RemoteServer.answer(handlers, body).pipe(Effect.provide(config.layer(env))),\n )\n return Response.json(answered.body, { status: answered.status })\n } catch {\n // A failure of the layer, or a defect anywhere: this side broke, and the\n // caller learns that it did, not what. `answer` already maps its own\n // failures and defects to 400/500 answers above this.\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsCA,MAAM,mBAAmB,OAAO,OAAO;CACrC,WAAW,OAAO,QAAQ,MAAM;CAChC,SAAS,OAAO;AAClB,CAAC;;AAGD,MAAM,cAAc,YAClB,uBAAuB,KAAK,UAAU,EAAE,QAAQ,CAAC,EAAE;;;;;;;;;;;AAYrD,MAAM,aACJ,UACA,SACA,cAEA,OAAO,OACL,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,SAAS,KAAW;CACzC,MAAM,SAAS,SAAS,kBAAkB,OAAO,CAAC,CAAC,KACjD,OAAO,KAAI,WAAU,SAAS,KAAK,UAAU,MAAM,EAAE,KAAK,GAC1D,OAAO,UAAU;EACf,kBAAiB,UAAS,OAAO,QAAQ,WAAW,MAAM,OAAO,CAAC;EAClE,sBAAqB,UAAS,OAAO,QAAQ,WAAW,MAAM,OAAO,CAAC;CACxE,CAAC,GACD,OAAO,SAAS,SAAS,QAAQ,OAAO,KAAA,CAAS,CAAC,CACpD;CACA,MAAM,QAAQ,OAAO,OACnB,OAAO,QAAQ,YAAY,GAC3B,OAAO,aAAa,SAAS,OAAO,SAAS,CAAC,CAAC,CAAC,KAAK,OAAO,UAAU,YAAY,CAAC,CACrF,CAAC,CAAC,KAAK,OAAO,cAAc,SAAS,MAAM,KAAK,CAAC,CAAC;CAClD,OAAO,OAAO,MAAM,QAAQ,K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A,IAAI;EACJ,IAAI;GACF,OAAO,MAAM,QAAQ,KAAK;EAC5B,QAAQ;GACN,OAAO,SAAS,KAAK,EAAE,OAAO,uBAAuB,GAAG,EAAE,QAAQ,IAAI,CAAC;EACzE;EAEA,MAAM,WAAW,aAAa,SAAS,OAAO,QAAQ,WAAW;GAC/D,MAAM,OAAO;GACb,iBAAiB,OAAO;GACxB,UAAU,OAAO;EACnB,CAAC;EACD,IAAI,WAAW,IAAI,GACjB,OAAO,aACL,UACA,KAAK,SACL,OAAO,MAAM,GAAG,GAChB,OAAO,iBAAiB,iBAC1B;EAEF,IAAI;GACF,MAAM,WAAW,MAAM,OAAO,WAC5B,aAAa,OAAO,UAAU,IAAI,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,MAAM,GAAG,CAAC,CAAC,CAC5E;GACA,OAAO,SAAS,KAAK,SAAS,MAAM,EAAE,QAAQ,SAAS,OAAO,CAAC;EACjE,QAAQ;GAIN,OAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;EACnE;CACF;AACF"}
1
+ {"version":3,"file":"fetch.mjs","names":[],"sources":["../src/fetch.ts"],"sourcesContent":["/**\n * `foldkit-remote-server/fetch`: `RemoteServer` over the Fetch API, for\n * Cloudflare Workers and any other runtime that speaks `Request`/`Response`.\n *\n * Reads, queries, and mutations ride one `POST` each, as `Remote.http` sends\n * them and `RemoteServer.answer` answers them. Live requirements ride one\n * `POST` that answers with a `text/event-stream` of `LiveChange` frames, one\n * `data:` frame per change and a terminal `event: error` frame when the\n * stream fails; `Remote.httpWithLive` is the other end. The principal is\n * resolved per request, from whatever the runtime hands over (a header, a\n * binding, a session), and the Sources' requirements are provided per\n * request from the environment (a D1 binding, a connection string).\n */\nimport {\n Cause,\n Deferred,\n Duration,\n Effect,\n Exit,\n Layer,\n Option,\n Schedule,\n Schema,\n Scope,\n Stream,\n} from 'effect'\nimport {\n LiveRequirement,\n RemoteLiveError,\n type RemoteJsonAnswer,\n type RemoteRpcClient,\n type RemoteUnauthenticated,\n} from 'foldkit-remote'\nimport { RemoteServer, type LiveHub, type ServerDefinition } from './index.js'\nimport { unauthenticatedAnswer } from './refusal.js'\n\n/** What `serveFetch` needs of the host runtime, per request. */\nexport interface FetchConfig<P, R, Env, RP = never> {\n /** The server definition, as `RemoteServer.make` built it. */\n readonly server: ServerDefinition<P, R>\n /**\n * Who this request is, from the request and the environment. Fails with\n * `RemoteServer.unauthenticated(reason?)` to refuse the caller: a 401.\n * What it needs (a session store, an auth service) comes from `layer`.\n */\n readonly resolvePrincipal: (\n request: Request,\n env: Env,\n ) => Effect.Effect<P, RemoteUnauthenticated, RP>\n /**\n * What the Sources and the resolver need, from the environment. Built per\n * request, so kept cheap, and closed when the answer is sent, or, for a\n * live stream, when the stream ends.\n */\n readonly layer: (env: Env) => Layer.Layer<R | RP>\n /** The path answered; anything else is a 404. Default `/remote`. */\n readonly path?: string | undefined\n /**\n * Headers every answer to `principal` carries, a live stream's included;\n * a refusal has no principal and carries none. Whom the request was\n * answered as, say, for a client to repeat (`foldkit-auth`'s\n * `AuthServer.answered`).\n */\n readonly headers?: ((principal: P) => Readonly<Record<string, string>>) | undefined\n /** A hub whose `changed`/`deleted` signals reach the live streams this serves. */\n readonly live?: LiveHub<P, R> | undefined\n /**\n * Asks `resolvePrincipal` again, of the same request, every `every` while a\n * live stream is open. A refusal ends the stream with `Unauthenticated`,\n * which the client reads as a lost session; a principal whose `key`\n * differs from the one the stream opened with (`Policy.keyOf`, as\n * `liveHub`'s `key`) ends it as a live error, which the client opens again\n * after, as the new principal; without `key` only a refusal ends it.\n * Without `revalidate` a stream serves the principal it opened with until\n * it closes, a revoked session included.\n * `every` must be longer than zero: each pass asks the session store.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: P) => unknown) | undefined\n }\n | undefined\n /** A heartbeat comment every this often, keeping idle streams alive through proxies. Default 15 seconds. */\n readonly liveHeartbeat?: Duration.Input | undefined\n /** A read batch may not name more ids of one entity than this; default 1000. */\n readonly maxIdsPerEntity?: number | undefined\n /** A nested selection may not reach further than this many levels; default 8. */\n readonly maxDepth?: number | undefined\n}\n\n/** A live open over fetch: the requirements and the cursor it resumes after. */\nconst LiveFetchRequest = Schema.Struct({\n operation: Schema.Literal('live'),\n payload: Schema.Unknown,\n})\n\n/**\n * A terminal stream failure, so the client fails with its message instead of\n * hanging; a refusal of who is asking says so, as a 401's body does.\n */\nconst errorFrame = (message: string, refusal: Partial<RemoteJsonAnswer> = {}): string =>\n `event: error\\ndata: ${JSON.stringify({ message, ...refusal })}\\n\\n`\n\n/**\n * The live stream as SSE bytes: one `data:` frame per change, then a\n * terminal `event: error` frame when the stream fails rather than ends. A\n * `: ping` comment opens the stream, so headers and a first byte reach the\n * client at once, and rides along every `heartbeat` so a stream with nothing\n * to say still moves: workers cancel responses that go quiet, and proxies\n * drop idle connections. The heartbeat ends with the events, so a stream\n * with nothing to serve still ends. A client that disconnects interrupts\n * the subscription, as closing the RPC stream would.\n */\nconst liveBytes = <R, RC>(\n handlers: RemoteRpcClient<R>,\n payload: Schema.Schema.Type<typeof LiveRequirement>,\n heartbeat: Duration.Input,\n checked: Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RC>,\n): Stream.Stream<Uint8Array, never, R | RC> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const ended = yield* Deferred.make<void>()\n // The checks fail the stream, or stop with it.\n const events = Stream.merge(handlers.FoldkitRemoteLive(payload), checked, {\n haltStrategy: 'left',\n }).pipe(\n Stream.map(change => `data: ${JSON.stringify(change)}\\n\\n`),\n Stream.catchTags({\n RemoteLiveError: error => Stream.succeed(errorFrame(error.message)),\n RemoteProtocolError: error => Stream.succeed(errorFrame(error.message)),\n Unauthenticated: error =>\n Stream.succeed(\n errorFrame(error.message, {\n unauthenticated: unauthenticatedAnswer(error).body.unauthenticated,\n }),\n ),\n }),\n // A defect says nothing of itself, as a 500 does; an interruption is\n // the client leaving, with no one to tell.\n Stream.catchCause(cause =>\n Cause.hasInterruptsOnly(cause)\n ? Stream.failCause(cause)\n : Stream.succeed(errorFrame('Internal error')),\n ),\n Stream.ensuring(Deferred.succeed(ended, undefined)),\n )\n const beats = Stream.concat(\n Stream.succeed(': ping\\n\\n'),\n Stream.fromSchedule(Schedule.spaced(heartbeat)).pipe(Stream.map(() => ': ping\\n\\n')),\n ).pipe(Stream.interruptWhen(Deferred.await(ended)))\n return Stream.merge(events, beats)\n }),\n ).pipe(Stream.encodeText)\n\n/**\n * Whether the body opens a live stream rather than asking `answer`. Anything\n * else, including a body that is not a request at all, is `answer`'s to\n * refuse with a 400.\n */\nconst isLiveOpen = (body: unknown): body is Schema.Schema.Type<typeof LiveFetchRequest> => {\n try {\n return Schema.decodeUnknownSync(LiveFetchRequest)(body).operation === 'live'\n } catch {\n return false\n }\n}\n\n/** Heartbeats when the caller names none: under proxy idle timeouts. */\nconst DEFAULT_HEARTBEAT: Duration.Input = '15 seconds'\n\n/**\n * Answers a live open with the stream as `text/event-stream`. A payload no\n * live stream speaks is a 400 that subscribes to nothing. Once the stream\n * runs, its own failures are its terminal `event: error` frame.\n */\nconst liveResponse = <R, RC>(\n handlers: RemoteRpcClient<R>,\n payload: unknown,\n heartbeat: Duration.Input,\n checked: Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RC>,\n release: Effect.Effect<void>,\n headers: Readonly<Record<string, string>>,\n): Effect.Effect<Response, never, R | RC> =>\n Schema.decodeUnknownEffect(LiveRequirement)(payload).pipe(\n Effect.matchEffect({\n onFailure: () =>\n Effect.succeed(\n Response.json(\n { error: 'The live payload is not a requirement' },\n { status: 400, headers },\n ),\n ),\n onSuccess: requirement =>\n Effect.map(\n Stream.toReadableStreamEffect(\n liveBytes(handlers, requirement, heartbeat, checked).pipe(Stream.ensuring(release)),\n ),\n body =>\n new Response(body, {\n headers: {\n ...headers,\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-cache',\n },\n }),\n ),\n }),\n )\n\n/**\n * Answers Remote `POST`s with `Response`s: what a Worker's `fetch` hands to\n * the route. Each request is one Effect, with `layer` built once for it:\n * `resolvePrincipal` first, which refuses with `RemoteServer.unauthenticated`\n * (a 401, its `reason` the only words the caller reads); then the body. A\n * body that is not JSON, or not a request, is a 400 that reaches no handler;\n * a handler's failure a 500 with its message; anything else this side\n * breaks, the resolver's defects and the layer included, a 500 that says\n * nothing of it. A live open is answered with the stream instead.\n *\n * ```ts\n * export default {\n * fetch: serveFetch({\n * server,\n * resolvePrincipal: request =>\n * Effect.succeed({ actorId: request.headers.get('x-actor') ?? 'anon' }),\n * layer: env => databaseLayer(drizzle(env.DB)),\n * }),\n * }\n * ```\n */\nexport const serveFetch = <P, R, Env, RP = never>(\n config: FetchConfig<P, R, Env, RP>,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const path = config.path ?? '/remote'\n const heartbeat = config.liveHeartbeat ?? DEFAULT_HEARTBEAT\n if (\n config.revalidate !== undefined &&\n !Duration.isGreaterThan(Duration.fromInputUnsafe(config.revalidate.every), Duration.zero)\n )\n throw new Error('serveFetch: revalidate.every must be longer than zero')\n /** The live stream's principal, asked again of its request while it runs. */\n const revalidation = (\n request: Request,\n env: Env,\n opened: P,\n ): Stream.Stream<never, RemoteUnauthenticated | RemoteLiveError, RP> => {\n const { revalidate } = config\n if (revalidate === undefined) return Stream.empty\n return Stream.fromSchedule(Schedule.spaced(revalidate.every)).pipe(\n Stream.mapEffect(() => config.resolvePrincipal(request, env)),\n Stream.mapEffect(now =>\n revalidate.key === undefined || revalidate.key(opened) === revalidate.key(now)\n ? Effect.void\n : Effect.fail(\n new RemoteLiveError({ message: 'Who is asking changed: open the stream again' }),\n ),\n ),\n Stream.drain,\n )\n }\n /** `live` is whether the response streams, and so owns `scope` until it ends. */\n const respond = (\n request: Request,\n env: Env,\n scope: Scope.Closeable,\n ): Effect.Effect<{ readonly response: Response; readonly live: boolean }, never, R | RP> =>\n Effect.gen(function* () {\n const principal = yield* config.resolvePrincipal(request, env)\n const headers = config.headers?.(principal) ?? {}\n const body = yield* Effect.option(Effect.tryPromise(() => request.json()))\n if (Option.isNone(body)) {\n return {\n response: Response.json({ error: 'The body is not JSON' }, { status: 400, headers }),\n live: false,\n }\n }\n // Bound per request: the principal is the request's own, as everywhere else.\n const handlers = RemoteServer.handlers(config.server, principal, {\n live: config.live,\n maxIdsPerEntity: config.maxIdsPerEntity,\n maxDepth: config.maxDepth,\n })\n if (isLiveOpen(body.value)) {\n const response = yield* liveResponse(\n handlers,\n body.value.payload,\n heartbeat,\n revalidation(request, env, principal),\n Scope.close(scope, Exit.void),\n headers,\n )\n // A 400 for a payload no stream speaks has no stream to close it.\n return { response, live: response.status === 200 }\n }\n const answered = yield* RemoteServer.answer(handlers, body.value)\n return {\n response: Response.json(answered.body, { status: answered.status, headers }),\n live: false,\n }\n }).pipe(\n Effect.catchTag('Unauthenticated', refusal => {\n const { status, body } = unauthenticatedAnswer(refusal)\n return Effect.succeed({ response: Response.json(body, { status }), live: false })\n }),\n )\n return async (request, env) => {\n if (request.method !== 'POST' || new URL(request.url).pathname !== path) {\n return Response.json({ error: 'not found' }, { status: 404 })\n }\n try {\n return await Effect.runPromise(\n Effect.gen(function* () {\n // Not Effect.provide(layer), which closes it when `respond` returns,\n // before a live stream has served a frame: the stream's re-reads and\n // revalidation would run on released resources.\n const scope = yield* Scope.make()\n const answered = yield* Layer.buildWithScope(config.layer(env), scope).pipe(\n Effect.flatMap(context => Effect.provide(respond(request, env, scope), context)),\n Effect.onExit(exit =>\n Exit.isSuccess(exit) && exit.value.live ? Effect.void : Scope.close(scope, exit),\n ),\n )\n return answered.response\n }),\n )\n } catch {\n // A failure of the layer, or a defect anywhere: this side broke, and the\n // caller learns that it did, not what. `answer` already maps its own\n // failures and defects to 400/500 answers.\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4FA,MAAM,mBAAmB,OAAO,OAAO;CACrC,WAAW,OAAO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AC;EAE9D,IAAI;GACF,OAAO,MAAM,OAAO,WAClB,OAAO,IAAI,aAAa;IAItB,MAAM,QAAQ,OAAO,MAAM,KAAK;IAOhC,QAAO,OANiB,MAAM,eAAe,OAAO,MAAM,GAAG,GAAG,KAAK,CAAC,CAAC,KACrE,OAAO,SAAQ,YAAW,OAAO,QAAQ,QAAQ,SAAS,KAAK,KAAK,GAAG,OAAO,CAAC,GAC/E,OAAO,QAAO,SACZ,KAAK,UAAU,IAAI,KAAK,KAAK,MAAM,OAAO,OAAO,OAAO,MAAM,MAAM,OAAO,IAAI,CACjF,CACF,EAAA,CACgB;GAClB,CAAC,CACH;EACF,QAAQ;GAIN,OAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,GAAG,EAAE,QAAQ,IAAI,CAAC;EACnE;CACF;AACF"}
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Context, Effect, Layer, Option, Schema, Stream } from "effect";
2
2
  import { AnyWrite, EntityRef, QueryEvaluateError, Row, assertSupported, evaluate, supported } from "foldkit-entity";
3
- import { Boundary, ConnectionChangeSchema, ConnectionIdentity, LiveChange, MutationDescriptor, NormalizedPatch, QueryDescriptor, QueryWindow, RelationRequirement, RemoteClient, RemoteDescriptor, RemoteForbidden, RemoteJsonAnswer, RemoteReadError, RemoteRpcClient, Requirement } from "foldkit-remote";
3
+ import { Boundary, ConnectionChangeSchema, ConnectionIdentity, LiveChange, MutationDescriptor, NormalizedPatch, QueryDescriptor, QueryWindow, RelationRequirement, RemoteClient, RemoteDescriptor, RemoteForbidden, RemoteJsonAnswer, RemoteReadError, RemoteRpcClient, RemoteUnauthenticated, Requirement } from "foldkit-remote";
4
4
  //#region src/index.d.ts
5
5
  declare const RemoteServerError_base: Schema.Class<RemoteServerError, Schema.TaggedStruct<"RemoteServerError", {
6
6
  readonly message: Schema.String;
@@ -301,23 +301,36 @@ export interface MemoryStore {
301
301
  readonly write: (entity: string, id: string, values: Readonly<Record<string, unknown>>) => void;
302
302
  readonly remove: (entity: string, id: string) => void;
303
303
  }
304
- export interface MemoryBackend<P = undefined> extends MemoryStore {
304
+ /**
305
+ * A memory backend made without a `principal`: its rows and the server over
306
+ * them, answered as whoever its caller names per request (`serveFetch`,
307
+ * `RemoteServer.handlers(served.server, principal)`).
308
+ */
309
+ export interface MemoryServed<P> extends MemoryStore {
310
+ /**
311
+ * The rows' server, for serving them over a real transport, or as any
312
+ * principal: `RemoteRpc.toLayer(RemoteServer.handlers(backend.server, principal))`.
313
+ */
314
+ readonly server: ServerDefinition<P>;
315
+ }
316
+ export interface MemoryBackend<P = undefined> extends MemoryServed<P> {
305
317
  /**
306
318
  * A `RemoteClient` answering from the rows as the configured `principal`.
307
319
  * Provide it where the real one would go.
308
320
  */
309
321
  readonly layer: Layer.Layer<RemoteClient>;
310
- /**
311
- * The server the layer answers through, for serving the rows over a real
312
- * transport, or as another principal:
313
- * `RemoteRpc.toLayer(RemoteServer.handlers(backend.server, principal))`.
314
- */
315
- readonly server: ServerDefinition<P>;
316
322
  }
317
323
  /** What `RemoteServer.memory` is made from. See `memory`. */
318
324
  export type MemoryConfig<P> = {
319
325
  readonly domain: Pick<RemoteDescriptor, 'registry'>;
320
326
  readonly rows: MemoryRows;
327
+ /**
328
+ * Sources for entities the domain does not declare, which no row backs (a
329
+ * `Me` row answered from the principal, `GuardServer.me`), served beside
330
+ * the rows. One for a declared entity is refused: the rows serve it.
331
+ */
332
+ readonly entities?: ReadonlyArray<EntitySource<P>>;
333
+ /** Sources for queries, beside the domain's: one named as a declared query answers it instead of its body. */
321
334
  readonly queries?: ReadonlyArray<QuerySource<P>>;
322
335
  readonly mutations?: (store: MemoryStore) => ReadonlyArray<MutationSource<P>>;
323
336
  /** Per entity name, the fields a principal may read, as `RemoteServer.entity` takes it. */
@@ -333,12 +346,13 @@ export type MemoryConfig<P> = {
333
346
  * looks another stored row up, for a decision that follows a relation.
334
347
  */
335
348
  readonly readable?: (principal: P, row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>) => Effect.Effect<MemoryReadable, RemoteServerError>;
336
- } & (undefined extends P ? {
349
+ /** Who the `layer` answers as. Without it there is no `layer`, unless `P` admits `undefined`. */
337
350
  readonly principal?: P;
338
- } : {
339
- /** Who the `layer` answers as. */
351
+ };
352
+ /** What a backend needs to give a `layer`: a principal to answer as, or one `undefined` can be. */
353
+ export type MemoryAnswering<P> = undefined extends P ? unknown : {
340
354
  readonly principal: P;
341
- });
355
+ };
342
356
  /** Whether a stored row of `entity` may be read, given its whole stored values. */
343
357
  export type MemoryReadable = (entity: string, row: Readonly<Record<string, unknown>>) => boolean;
344
358
  /**
@@ -356,10 +370,13 @@ export type MemoryReadable = (entity: string, row: Readonly<Record<string, unkno
356
370
  *
357
371
  * Every field of every row is readable unless `authorize` names the entity:
358
372
  * then its function decides, per principal, as `RemoteServer.entity`'s does.
359
- * The `layer` answers as `principal`; `server` answers as any. It does not
360
- * push live changes. It is not a server to deploy.
373
+ * `entities` adds Sources for entities no row backs, which the domain must not
374
+ * declare. The `layer` answers as `principal`, and is absent without one
375
+ * (unless `P` admits `undefined`); `server` answers as any. It does not push
376
+ * live changes. It is not a server to deploy.
361
377
  */
362
- declare const memory: <P = undefined>(config: MemoryConfig<P>) => MemoryBackend<P>;
378
+ declare function memory<P = undefined>(config: MemoryConfig<P> & MemoryAnswering<P>): MemoryBackend<P>;
379
+ declare function memory<P = undefined>(config: MemoryConfig<P>): MemoryServed<P>;
363
380
  export declare const RemoteServer: {
364
381
  /** A backend held in memory, for a first run, a test or a demo. See `memory`. */
365
382
  memory: typeof memory;
@@ -412,6 +429,13 @@ export declare const RemoteServer: {
412
429
  * fails with `_tag: 'Forbidden'`.
413
430
  */
414
431
  forbid: (reason?: string) => RemoteForbidden;
432
+ /**
433
+ * A refusal of a caller who could not be told: a `serveFetch` or
434
+ * `defineDocumentHost` resolver fails with it (`RemoteServer.unauthenticated()`)
435
+ * when the credential it was sent no longer holds. It answers 401, with
436
+ * `reason`, when given, for the person who asked.
437
+ */
438
+ unauthenticated: (reason?: string) => RemoteUnauthenticated;
415
439
  /**
416
440
  * The Source of a mutation that is a declared `Write`, with no handler: the
417
441
  * input bound to the write lands through `writer`, and the row as written
@@ -481,13 +505,13 @@ export declare const RemoteServer: {
481
505
  * worker or a server in the page calls with the body it received, parsed.
482
506
  * The request and its payload are decoded by the protocol's own schemas
483
507
  * before a handler sees them, so an operation name is one of Remote's three
484
- * and nothing else. A body that is not a request is a 400; a refusal of who
485
- * is asking a 403; a handler's failure a 500 with its message; a defect a
486
- * 500 that says nothing of it.
508
+ * and nothing else. A body that is not a request is a 400; a caller who
509
+ * could not be told a 401; a refusal of who is asking a 403; a handler's
510
+ * failure a 500 with its message; a defect a 500 that says nothing of it.
487
511
  * `Remote.json` and `Remote.http` are the other end.
488
512
  */
489
513
  answer: <R>(handlers: RemoteRpcClient<R>, body: unknown) => Effect.Effect<{
490
- readonly status: 200 | 400 | 403 | 422 | 500;
514
+ readonly status: 200 | 400 | 401 | 403 | 422 | 500;
491
515
  readonly body: RemoteJsonAnswer;
492
516
  }, never, R>;
493
517
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;qBA8Da,0BAA0B;;;;;;;;;;;;;qBAY1B,wBAAwB;iBAQpB;WACN;WACA,QAAQ,SAAS;;iBAGX,oBAAoB;WAC1B;WACA;;WAEA,UAAU,SAAS,eAAe;WAClC,WAAW;;iBAGL,aAAa,GAAG;WACtB;;WAEA,SAAS;WACT,OACP,SAAS,oBAAoB,OAC1B,OAAO,OAAO,cAAc,eAAe,mBAAmB;;WAE1D,aAAa,WAAW,GAAG;;;;;;WAM3B,UACP,WAAW,GACX,8BACG,OAAO,OAAO,UAAU,mBAAmB;;;;;;;;WAQvC;;;;;;;WAOA,SAAS;;;iBAIH;;WAEN;;WAEA,QAAQ,QAAQ,iBAAiB;;;;;;;;iBAwB3B,aAAa,GAAG;WACtB;WACA,SAAS;aACP;aACA,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