foldkit-remote-server 0.18.0 → 0.19.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 +442 -154
- package/dist/fetch.d.mts +30 -3
- package/dist/fetch.d.mts.map +1 -1
- package/dist/fetch.mjs +52 -16
- package/dist/fetch.mjs.map +1 -1
- package/dist/index-BnaRbvjr.d.mts +937 -0
- package/dist/index-BnaRbvjr.d.mts.map +1 -0
- package/dist/index.d.mts +2 -670
- package/dist/index.mjs +1 -1
- package/dist/{src-yDMwdGiL.mjs → src-ZV9pARkU.mjs} +468 -58
- package/dist/src-ZV9pARkU.mjs.map +1 -0
- package/package.json +8 -8
- package/dist/index.d.mts.map +0 -1
- package/dist/src-yDMwdGiL.mjs.map +0 -1
package/dist/fetch.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { k as ServerDefinition, s as LiveHub } from "./index-BnaRbvjr.mjs";
|
|
2
2
|
import { Duration, Effect, Layer } from "effect";
|
|
3
|
-
import { RemoteUnauthenticated } from "foldkit-remote";
|
|
3
|
+
import { Diagnostic, RemoteClient, RemoteUnauthenticated } from "foldkit-remote";
|
|
4
4
|
/** What `serveFetch` needs of the host runtime, per request. */
|
|
5
5
|
export interface FetchConfig<P, R, Env, RP = never> {
|
|
6
6
|
/** The server definition, as `RemoteServer.make` built it. */
|
|
@@ -45,6 +45,14 @@ export interface FetchConfig<P, R, Env, RP = never> {
|
|
|
45
45
|
} | undefined;
|
|
46
46
|
/** A heartbeat comment every this often, keeping idle streams alive through proxies. Default 15 seconds. */
|
|
47
47
|
readonly liveHeartbeat?: Duration.Input | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* Where this request's diagnostics go, with the request: each failure
|
|
50
|
+
* answered "Internal error" or ending a live stream (a `ServerDefect`: a
|
|
51
|
+
* broken layer or resolver, a handler's defect), whose cause the caller is
|
|
52
|
+
* never told, and what the handlers report. The reporter in the Effect
|
|
53
|
+
* context (`Diagnostics.Reporter`) when not given, by default the log.
|
|
54
|
+
*/
|
|
55
|
+
readonly diagnostics?: ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>) | undefined;
|
|
48
56
|
/** A read batch may not name more ids of one entity than this; default 1000. */
|
|
49
57
|
readonly maxIdsPerEntity?: number | undefined;
|
|
50
58
|
/** A nested selection may not reach further than this many levels; default 8. */
|
|
@@ -58,7 +66,9 @@ export interface FetchConfig<P, R, Env, RP = never> {
|
|
|
58
66
|
* body that is not JSON, or not a request, is a 400 that reaches no handler;
|
|
59
67
|
* a handler's failure a 500 with its message; anything else this side
|
|
60
68
|
* breaks, the resolver's defects and the layer included, a 500 that says
|
|
61
|
-
* nothing of it. A live open is answered with the stream instead.
|
|
69
|
+
* nothing of it. A live open is answered with the stream instead. Each
|
|
70
|
+
* answer is one principal's, so every response says `cache-control:
|
|
71
|
+
* no-store`, unless `headers` gives a `cache-control` of its own.
|
|
62
72
|
*
|
|
63
73
|
* ```ts
|
|
64
74
|
* export default {
|
|
@@ -72,4 +82,21 @@ export interface FetchConfig<P, R, Env, RP = never> {
|
|
|
72
82
|
* ```
|
|
73
83
|
*/
|
|
74
84
|
export declare const serveFetch: <P, R, Env, RP = never>(config: FetchConfig<P, R, Env, RP>) => ((request: Request, env: Env) => Promise<Response>);
|
|
85
|
+
/** What `pageReader` reads of a `serveFetch` config: the server, its Sources' layer and its limits. */
|
|
86
|
+
export type PageReaderConfig<P, R, Env, RP = never> = Pick<FetchConfig<P, R, Env, RP>, 'server' | 'resolvePrincipal' | 'layer' | 'maxIdsPerEntity' | 'maxDepth'>;
|
|
87
|
+
/**
|
|
88
|
+
* The reader a page render reads through, in the same process: the request's
|
|
89
|
+
* `RemoteClient`, answered by the server's own handlers with no HTTP between
|
|
90
|
+
* them. Give it `serveFetch`'s config with the resolver a page's request
|
|
91
|
+
* needs: a page `GET` is a navigation, which carries no header a script adds
|
|
92
|
+
* (`AuthServer.resolver({ …, requests: 'navigation' })`).
|
|
93
|
+
*
|
|
94
|
+
* The principal is resolved, and `layer` built, when the reader is provided,
|
|
95
|
+
* and `layer` closes when the Effect it was provided to ends, so provide it to
|
|
96
|
+
* the pre-read itself (`Data.satisfy(…).pipe(Effect.provide(reader))`). A
|
|
97
|
+
* refusal fails that Effect with `Unauthenticated`, as a 401 would. It only
|
|
98
|
+
* reads: a mutation fails with `RemoteMutationError` and a live open with
|
|
99
|
+
* `RemoteLiveError`, since a navigation can be started from another site.
|
|
100
|
+
*/
|
|
101
|
+
export declare const pageReader: <P, R, Env, RP = never>(config: PageReaderConfig<P, R, Env, RP>) => (request: Request, env: Env) => Layer.Layer<RemoteClient, RemoteUnauthenticated>;
|
|
75
102
|
//# sourceMappingURL=fetch.d.mts.map
|
package/dist/fetch.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;iBA2CiB,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;;;;;;;;WAQzB,gBACH,YAAY,YAAY,SAAS,YAAY,OAAO;;WAGjD;;WAEA;;;;;;;;;;;;;;;;;;;;;;;;;qBAsJE,aAAc,GAAG,GAAG,KAAK,YAAU,QACtC,YAAY,GAAG,GAAG,KAAK,UAC5B,SAAS,SAAS,KAAK,QAAQ,QAAQ;;YA0HhC,iBAAiB,GAAG,GAAG,KAAK,cAAc,KACpD,YAAY,GAAG,GAAG,KAAK;;;;;;;;;;;;;;;qBAkBZ,aACV,GAAG,GAAG,KAAK,YAAU,QAAU,iBAAiB,GAAG,GAAG,KAAK,SAAG,SACrD,SAAO,KAAO,QAAM,MAAM,MAAM,cAAc"}
|
package/dist/fetch.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { m as serverDefect, p as unauthenticatedAnswer, r as RemoteServer } from "./src-ZV9pARkU.mjs";
|
|
2
2
|
import { Cause, Deferred, Duration, Effect, Exit, Layer, Option, Schedule, Schema, Scope, Stream } from "effect";
|
|
3
|
-
import { LiveRequirement, RemoteLiveError } from "foldkit-remote";
|
|
3
|
+
import { Diagnostics, LiveRequirement, Remote, RemoteLiveError, RemoteMutationError } from "foldkit-remote";
|
|
4
4
|
// src/fetch.ts
|
|
5
5
|
/**
|
|
6
6
|
* `foldkit-remote-server/fetch`: `RemoteServer` over the Fetch API, for
|
|
@@ -42,9 +42,10 @@ const liveBytes = (handlers, payload, heartbeat, checked) => Stream.unwrap(Effec
|
|
|
42
42
|
const ended = yield* Deferred.make();
|
|
43
43
|
const events = Stream.merge(handlers.FoldkitRemoteLive(payload), checked, { haltStrategy: "left" }).pipe(Stream.map((change) => `data: ${JSON.stringify(change)}\n\n`), Stream.catchTags({
|
|
44
44
|
RemoteLiveError: (error) => Stream.succeed(errorFrame(error.message)),
|
|
45
|
+
RemoteLiveRefused: (error) => Stream.succeed(errorFrame(error.message, { refused: true })),
|
|
45
46
|
RemoteProtocolError: (error) => Stream.succeed(errorFrame(error.message)),
|
|
46
47
|
Unauthenticated: (error) => Stream.succeed(errorFrame(error.message, { unauthenticated: unauthenticatedAnswer(error).body.unauthenticated }))
|
|
47
|
-
}), Stream.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Stream.failCause(cause) : Stream.
|
|
48
|
+
}), Stream.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Stream.failCause(cause) : Stream.fromEffect(Effect.as(Diagnostics.report(serverDefect(cause)), errorFrame("Internal error")))), Stream.ensuring(Deferred.succeed(ended, void 0)));
|
|
48
49
|
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)));
|
|
49
50
|
return Stream.merge(events, beats);
|
|
50
51
|
})).pipe(Stream.encodeText);
|
|
@@ -74,8 +75,7 @@ const liveResponse = (handlers, payload, heartbeat, checked, release, headers) =
|
|
|
74
75
|
})),
|
|
75
76
|
onSuccess: (requirement) => Effect.map(Stream.toReadableStreamEffect(liveBytes(handlers, requirement, heartbeat, checked).pipe(Stream.ensuring(release))), (body) => new Response(body, { headers: {
|
|
76
77
|
...headers,
|
|
77
|
-
"content-type": "text/event-stream"
|
|
78
|
-
"cache-control": "no-cache"
|
|
78
|
+
"content-type": "text/event-stream"
|
|
79
79
|
} }))
|
|
80
80
|
}));
|
|
81
81
|
/**
|
|
@@ -86,7 +86,9 @@ const liveResponse = (handlers, payload, heartbeat, checked, release, headers) =
|
|
|
86
86
|
* body that is not JSON, or not a request, is a 400 that reaches no handler;
|
|
87
87
|
* a handler's failure a 500 with its message; anything else this side
|
|
88
88
|
* breaks, the resolver's defects and the layer included, a 500 that says
|
|
89
|
-
* nothing of it. A live open is answered with the stream instead.
|
|
89
|
+
* nothing of it. A live open is answered with the stream instead. Each
|
|
90
|
+
* answer is one principal's, so every response says `cache-control:
|
|
91
|
+
* no-store`, unless `headers` gives a `cache-control` of its own.
|
|
90
92
|
*
|
|
91
93
|
* ```ts
|
|
92
94
|
* export default {
|
|
@@ -103,6 +105,11 @@ const serveFetch = (config) => {
|
|
|
103
105
|
const path = config.path ?? "/remote";
|
|
104
106
|
const heartbeat = config.liveHeartbeat ?? DEFAULT_HEARTBEAT;
|
|
105
107
|
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");
|
|
108
|
+
/** `effect` reporting to `config.diagnostics` with `request`, when it is given. */
|
|
109
|
+
const reportingFor = (request) => (effect) => {
|
|
110
|
+
const { diagnostics } = config;
|
|
111
|
+
return diagnostics === void 0 ? effect : Effect.provideService(effect, Diagnostics.Reporter, (diagnostic) => diagnostics(diagnostic, request));
|
|
112
|
+
};
|
|
106
113
|
/** The live stream's principal, asked again of its request while it runs. */
|
|
107
114
|
const revalidation = (request, env, opened) => {
|
|
108
115
|
const { revalidate } = config;
|
|
@@ -148,18 +155,47 @@ const serveFetch = (config) => {
|
|
|
148
155
|
live: false
|
|
149
156
|
});
|
|
150
157
|
}));
|
|
151
|
-
|
|
158
|
+
const served = async (request, env) => {
|
|
152
159
|
if (request.method !== "POST" || new URL(request.url).pathname !== path) return Response.json({ error: "not found" }, { status: 404 });
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
160
|
+
const exit = await Effect.runPromiseExit(Effect.gen(function* () {
|
|
161
|
+
const scope = yield* Scope.make();
|
|
162
|
+
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;
|
|
163
|
+
}).pipe(reportingFor(request)));
|
|
164
|
+
if (Exit.isSuccess(exit)) return exit.value;
|
|
165
|
+
await Effect.runPromise(Diagnostics.report(serverDefect(exit.cause)).pipe(reportingFor(request)));
|
|
166
|
+
return Response.json({ error: "Internal error" }, { status: 500 });
|
|
167
|
+
};
|
|
168
|
+
return async (request, env) => {
|
|
169
|
+
const response = await served(request, env);
|
|
170
|
+
if (!response.headers.has("cache-control")) response.headers.set("cache-control", "no-store");
|
|
171
|
+
return response;
|
|
161
172
|
};
|
|
162
173
|
};
|
|
163
|
-
|
|
174
|
+
/**
|
|
175
|
+
* The reader a page render reads through, in the same process: the request's
|
|
176
|
+
* `RemoteClient`, answered by the server's own handlers with no HTTP between
|
|
177
|
+
* them. Give it `serveFetch`'s config with the resolver a page's request
|
|
178
|
+
* needs: a page `GET` is a navigation, which carries no header a script adds
|
|
179
|
+
* (`AuthServer.resolver({ …, requests: 'navigation' })`).
|
|
180
|
+
*
|
|
181
|
+
* The principal is resolved, and `layer` built, when the reader is provided,
|
|
182
|
+
* and `layer` closes when the Effect it was provided to ends, so provide it to
|
|
183
|
+
* the pre-read itself (`Data.satisfy(…).pipe(Effect.provide(reader))`). A
|
|
184
|
+
* refusal fails that Effect with `Unauthenticated`, as a 401 would. It only
|
|
185
|
+
* reads: a mutation fails with `RemoteMutationError` and a live open with
|
|
186
|
+
* `RemoteLiveError`, since a navigation can be started from another site.
|
|
187
|
+
*/
|
|
188
|
+
const pageReader = (config) => (request, env) => Layer.unwrap(Effect.map(config.resolvePrincipal(request, env), (principal) => {
|
|
189
|
+
const handlers = RemoteServer.handlers(config.server, principal, {
|
|
190
|
+
maxIdsPerEntity: config.maxIdsPerEntity,
|
|
191
|
+
maxDepth: config.maxDepth
|
|
192
|
+
});
|
|
193
|
+
return Remote.clientLayer({
|
|
194
|
+
...handlers,
|
|
195
|
+
FoldkitRemoteMutate: () => Effect.fail(new RemoteMutationError({ message: "A page render reads; it does not write" })),
|
|
196
|
+
FoldkitRemoteLive: () => Stream.fail(new RemoteLiveError({ message: "A page render keeps no live stream" }))
|
|
197
|
+
});
|
|
198
|
+
})).pipe(Layer.provide(config.layer(env)));
|
|
199
|
+
export { pageReader, serveFetch };
|
|
164
200
|
|
|
165
201
|
//# sourceMappingURL=fetch.mjs.map
|
package/dist/fetch.mjs.map
CHANGED
|
@@ -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 {\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,QAAQ,MAAM;CAChC,SAAS,OAAO;AAClB,CAAC;;;;;AAMD,MAAM,cAAc,SAAiB,UAAqC,CAAC,MACzE,uBAAuB,KAAK,UAAU;CAAE;CAAS,GAAG;AAAQ,CAAC,EAAE;;;;;;;;;;;AAYjE,MAAM,aACJ,UACA,SACA,WACA,YAEA,OAAO,OACL,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,SAAS,KAAW;CAEzC,MAAM,SAAS,OAAO,MAAM,SAAS,kBAAkB,OAAO,GAAG,SAAS,EACxE,cAAc,OAChB,CAAC,CAAC,CAAC,KACD,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;EACtE,kBAAiB,UACf,OAAO,QACL,WAAW,MAAM,SAAS,EACxB,iBAAiB,sBAAsB,KAAK,CAAC,CAAC,KAAK,gBACrD,CAAC,CACH;CACJ,CAAC,GAGD,OAAO,YAAW,UAChB,MAAM,kBAAkB,KAAK,IACzB,OAAO,UAAU,KAAK,IACtB,OAAO,QAAQ,WAAW,gBAAgB,CA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AQ,SAAS;IAAQ;GAAQ,CAAC;GAC3E,MAAM;EACR;CACF,CAAC,CAAC,CAAC,KACD,OAAO,SAAS,oBAAmB,YAAW;EAC5C,MAAM,EAAE,QAAQ,SAAS,sBAAsB,OAAO;EACtD,OAAO,OAAO,QAAQ;GAAE,UAAU,SAAS,KAAK,MAAM,EAAE,OAAO,CAAC;GAAG,MAAM;EAAM,CAAC;CAClF,CAAC,CACH;CACF,OAAO,OAAO,SAAS,QAAQ;EAC7B,IAAI,QAAQ,WAAW,UAAU,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC,aAAa,MACjE,OAAO,SAAS,KAAK,EAAE,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;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"}
|
|
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 Diagnostics,\n LiveRequirement,\n Remote,\n RemoteLiveError,\n RemoteMutationError,\n type Diagnostic,\n type RemoteClient,\n type RemoteJsonAnswer,\n type RemoteRpcClient,\n type RemoteUnauthenticated,\n} from 'foldkit-remote'\nimport { serverDefect } from './diagnostics.js'\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 /**\n * Where this request's diagnostics go, with the request: each failure\n * answered \"Internal error\" or ending a live stream (a `ServerDefect`: a\n * broken layer or resolver, a handler's defect), whose cause the caller is\n * never told, and what the handlers report. The reporter in the Effect\n * context (`Diagnostics.Reporter`) when not given, by default the log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | 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 = (\n message: string,\n refusal: Partial<RemoteJsonAnswer> | { readonly refused: true } = {},\n): string => `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 // The client reads `refused` as asking again being refused again.\n RemoteLiveRefused: error => Stream.succeed(errorFrame(error.message, { refused: true })),\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 to the client, as a 500 does, and is\n // reported; an interruption is the client leaving, with no one to tell.\n Stream.catchCause(cause =>\n Cause.hasInterruptsOnly(cause)\n ? Stream.failCause(cause)\n : Stream.fromEffect(\n Effect.as(Diagnostics.report(serverDefect(cause)), errorFrame('Internal error')),\n ),\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 },\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. Each\n * answer is one principal's, so every response says `cache-control:\n * no-store`, unless `headers` gives a `cache-control` of its own.\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 /** `effect` reporting to `config.diagnostics` with `request`, when it is given. */\n const reportingFor =\n (request: Request) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => {\n const { diagnostics } = config\n return diagnostics === undefined\n ? effect\n : Effect.provideService(effect, Diagnostics.Reporter, diagnostic =>\n diagnostics(diagnostic, request),\n )\n }\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 const served = async (request: Request, env: Env): Promise<Response> => {\n if (request.method !== 'POST' || new URL(request.url).pathname !== path) {\n return Response.json({ error: 'not found' }, { status: 404 })\n }\n const exit = await Effect.runPromiseExit(\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 }).pipe(reportingFor(request)),\n )\n if (Exit.isSuccess(exit)) return exit.value\n // A failure of the layer, or a defect anywhere: this side broke, and the\n // caller learns that it did, not what; the diagnostics learn what. `answer`\n // already maps its own failures and defects to 400/500 answers.\n await Effect.runPromise(\n Diagnostics.report(serverDefect(exit.cause)).pipe(reportingFor(request)),\n )\n return Response.json({ error: 'Internal error' }, { status: 500 })\n }\n // Every answer is read as one principal: no cache may keep it for another.\n // A `cache-control` of the application's own (`headers`) stands.\n return async (request, env) => {\n const response = await served(request, env)\n if (!response.headers.has('cache-control')) response.headers.set('cache-control', 'no-store')\n return response\n }\n}\n\n/** What `pageReader` reads of a `serveFetch` config: the server, its Sources' layer and its limits. */\nexport type PageReaderConfig<P, R, Env, RP = never> = Pick<\n FetchConfig<P, R, Env, RP>,\n 'server' | 'resolvePrincipal' | 'layer' | 'maxIdsPerEntity' | 'maxDepth'\n>\n\n/**\n * The reader a page render reads through, in the same process: the request's\n * `RemoteClient`, answered by the server's own handlers with no HTTP between\n * them. Give it `serveFetch`'s config with the resolver a page's request\n * needs: a page `GET` is a navigation, which carries no header a script adds\n * (`AuthServer.resolver({ …, requests: 'navigation' })`).\n *\n * The principal is resolved, and `layer` built, when the reader is provided,\n * and `layer` closes when the Effect it was provided to ends, so provide it to\n * the pre-read itself (`Data.satisfy(…).pipe(Effect.provide(reader))`). A\n * refusal fails that Effect with `Unauthenticated`, as a 401 would. It only\n * reads: a mutation fails with `RemoteMutationError` and a live open with\n * `RemoteLiveError`, since a navigation can be started from another site.\n */\nexport const pageReader =\n <P, R, Env, RP = never>(config: PageReaderConfig<P, R, Env, RP>) =>\n (request: Request, env: Env): Layer.Layer<RemoteClient, RemoteUnauthenticated> =>\n Layer.unwrap(\n Effect.map(config.resolvePrincipal(request, env), principal => {\n const handlers = RemoteServer.handlers(config.server, principal, {\n maxIdsPerEntity: config.maxIdsPerEntity,\n maxDepth: config.maxDepth,\n })\n return Remote.clientLayer<R>({\n ...handlers,\n FoldkitRemoteMutate: () =>\n Effect.fail(\n new RemoteMutationError({ message: 'A page render reads; it does not write' }),\n ),\n FoldkitRemoteLive: () =>\n Stream.fail(new RemoteLiveError({ message: 'A page render keeps no live stream' })),\n })\n }),\n ).pipe(Layer.provide(config.layer(env)))\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4GA,MAAM,mBAAmB,OAAO,OAAO;CACrC,WAAW,OAAO,QAAQ,MAAM;CAChC,SAAS,OAAO;AAClB,CAAC;;;;;AAMD,MAAM,cACJ,SACA,UAAkE,CAAC,MACxD,uBAAuB,KAAK,UAAU;CAAE;CAAS,GAAG;AAAQ,CAAC,EAAE;;;;;;;;;;;AAY5E,MAAM,aACJ,UACA,SACA,WACA,YAEA,OAAO,OACL,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