foldkit-remote-server 0.19.0 → 0.21.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/dist/fetch.mjs CHANGED
@@ -1,6 +1,112 @@
1
- import { m as serverDefect, p as unauthenticatedAnswer, r as RemoteServer } from "./src-ZV9pARkU.mjs";
2
- import { Cause, Deferred, Duration, Effect, Exit, Layer, Option, Schedule, Schema, Scope, Stream } from "effect";
3
- import { Diagnostics, LiveRequirement, Remote, RemoteLiveError, RemoteMutationError } from "foldkit-remote";
1
+ import { b as serverDefect, d as declaresTooLarge, f as readJson, i as RemoteServer, p as tooLargeAnswer, v as unauthenticatedAnswer, y as cachedReadDiffers } from "./src-CHkHaItI.mjs";
2
+ import { Cause, Deferred, Duration, Effect, Exit, Layer, Option, Result, Schedule, Schema, Scope, Stream } from "effect";
3
+ import { CacheStore, CachedRead, DEFAULT_MAX_BODY_BYTES, Diagnostics, LiveRequirement, MutationResult, PageReads, QueryRequest, QueryResult, ReadBatch, ReadBatchResult, Remote, RemoteJsonRequest, RemoteLiveError, RemoteMutationError, listTag, maxAgeSeconds, rowTag, shorterPolicy, stableStringify } from "foldkit-remote";
4
+ // src/edgeCache.ts
5
+ /**
6
+ * Which reads a server may share between whoever asks, and the tags a store
7
+ * keeps them under (#428).
8
+ *
9
+ * A read is public only where the server can prove nothing about it depends
10
+ * on who asks: every source it passes through has no `authorize`, no
11
+ * `filter`, no `visible` rule (a guard's, a binding's, `memory`'s
12
+ * `readable`) and no member answered per viewer, and every one declares how
13
+ * long it stays fresh. Those rules are functions of the principal this
14
+ * module cannot read, so it does not try: a source with one is private,
15
+ * even where its rule happens to read only the row. A public read is then
16
+ * answered as the visitor, whoever asks, so even a source's own `read` that
17
+ * looks at the principal gives everyone one answer, never someone's own.
18
+ */
19
+ /** A source's freshness, where nothing it runs is a rule about who asks. */
20
+ const sourcePolicy = (source) => source === void 0 || source.authorize !== void 0 || source.filter !== void 0 || source.visible !== void 0 || (source.perViewer ?? []).length > 0 ? Option.none() : Option.fromUndefinedOr(source.cache);
21
+ /** Two policies' shorter, none when either is none. */
22
+ const both = (a, b) => Option.flatMap(a, (left) => Option.map(b, (right) => shorterPolicy(left, right)));
23
+ /** A slice's policy: its entity's, and every relation's it reaches. */
24
+ const slicePolicy = (server, slice) => Object.values(slice.relations ?? {}).reduce((policy, relation) => both(policy, slicePolicy(server, relation)), sourcePolicy(server.entities.get(slice.entity)));
25
+ /** A read batch's policy: none for an empty one, which keeps nothing worth a key. */
26
+ const readPolicy = (server, batch) => batch.requests.length === 0 ? Option.none() : batch.requests.map((request) => slicePolicy(server, request)).reduce(both);
27
+ /** A query's policy: its own, its rows' and what its `select` reaches. */
28
+ const queryPolicy = (server, request) => {
29
+ const source = server.queries.get(request.query);
30
+ if (source === void 0 || source.visible !== void 0) return Option.none();
31
+ const own = both(Option.fromUndefinedOr(source.cache), sourcePolicy(server.entities.get(source.entity)));
32
+ return request.select === void 0 ? own : both(own, slicePolicy(server, request.select));
33
+ };
34
+ const rowTags = (rows) => rows.map((row) => rowTag(row.entity, row.id));
35
+ /** What a read's answer holds: each row asked for, found or not, and each it reached. */
36
+ const readTags = (batch, result) => [.../* @__PURE__ */ new Set([
37
+ ...rowTags(batch.requests),
38
+ ...rowTags(result.entities),
39
+ ...rowTags(result.settled)
40
+ ])];
41
+ /** What a query's answer holds: every list of its entity, and each row on the page. */
42
+ const queryTags = (server, request, result) => [.../* @__PURE__ */ new Set([
43
+ ...Option.toArray(Option.map(Option.fromUndefinedOr(server.queries.get(request.query)), (source) => listTag(source.entity))),
44
+ ...rowTags(result.edges),
45
+ ...rowTags(result.entities ?? [])
46
+ ])];
47
+ const decodeMutationResult = Schema.decodeUnknownOption(MutationResult);
48
+ /**
49
+ * What a write's answer names, as tags to purge: each row it wrote, deleted,
50
+ * moved in a list or read back, and every list of each of their entities,
51
+ * which a changed row can join or leave. A write naming nothing purges nothing.
52
+ */
53
+ const writeTags = (result) => Option.match(decodeMutationResult(result), {
54
+ onNone: () => [],
55
+ onSome: (answer) => {
56
+ const rows = [
57
+ ...answer.entities,
58
+ ...answer.deleted ?? [],
59
+ ...(answer.connections ?? []).map((change) => change.edge),
60
+ ...answer.read?.result.entities ?? [],
61
+ ...(answer.lists ?? []).flatMap((list) => [...list.result.edges, ...list.result.entities ?? []])
62
+ ];
63
+ return [.../* @__PURE__ */ new Set([...rowTags(rows), ...rows.map((row) => listTag(row.entity))])];
64
+ }
65
+ });
66
+ /** An answer as anyone may be given it: without whom it was for. */
67
+ const unaddressed = (answer) => {
68
+ const { principal: _, ...rest } = answer;
69
+ return rest;
70
+ };
71
+ const hex = (bytes) => [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
72
+ /**
73
+ * The key a request's answer is kept under: the SHA-256 of `text` (the
74
+ * request as stable JSON), under the request's own origin, since the Workers
75
+ * Cache API keys by URL.
76
+ */
77
+ const cacheKey = (url, kind, text) => Effect.promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))).pipe(Effect.map((digest) => `${new URL(url).origin}/__foldkit/cache/${kind}/${hex(digest)}`));
78
+ /**
79
+ * Handlers that answer every read and query proved public as `visitor`, and
80
+ * note each read in the render's `PageReads`: public with its policy and
81
+ * tags, or private. Without a visitor every read is private, and so is one
82
+ * that fails, since a page drawn without its read is no page to keep.
83
+ */
84
+ const notingHandlers = (server, own, visitor) => {
85
+ const note = (read) => Effect.flatMap(Effect.service(PageReads), (noted) => Effect.sync(() => Option.map(noted, (add) => add(read))));
86
+ return {
87
+ ...own,
88
+ FoldkitRemoteRead: (batch) => Option.match(Option.flatMap(visitor, (handlers) => Option.map(readPolicy(server, batch), (policy) => ({
89
+ handlers,
90
+ policy
91
+ }))), {
92
+ onNone: () => Effect.ensuring(own.FoldkitRemoteRead(batch), note(CachedRead.Private())),
93
+ onSome: ({ handlers, policy }) => Effect.flatMap(handlers.FoldkitRemoteRead(batch), (result) => Effect.as(note(CachedRead.Public({
94
+ policy,
95
+ tags: readTags(batch, result)
96
+ })), unaddressed(result))).pipe(Effect.onError(() => note(CachedRead.Private())))
97
+ }),
98
+ FoldkitRemoteQuery: (request) => Option.match(Option.flatMap(visitor, (handlers) => Option.map(queryPolicy(server, request), (policy) => ({
99
+ handlers,
100
+ policy
101
+ }))), {
102
+ onNone: () => Effect.ensuring(own.FoldkitRemoteQuery(request), note(CachedRead.Private())),
103
+ onSome: ({ handlers, policy }) => Effect.flatMap(handlers.FoldkitRemoteQuery(request), (result) => Effect.as(note(CachedRead.Public({
104
+ policy,
105
+ tags: queryTags(server, request, result)
106
+ })), unaddressed(result))).pipe(Effect.onError(() => note(CachedRead.Private())))
107
+ })
108
+ };
109
+ };
4
110
  // src/fetch.ts
5
111
  /**
6
112
  * `foldkit-remote-server/fetch`: `RemoteServer` over the Fetch API, for
@@ -10,11 +116,46 @@ import { Diagnostics, LiveRequirement, Remote, RemoteLiveError, RemoteMutationEr
10
116
  * them and `RemoteServer.answer` answers them. Live requirements ride one
11
117
  * `POST` that answers with a `text/event-stream` of `LiveChange` frames, one
12
118
  * `data:` frame per change and a terminal `event: error` frame when the
13
- * stream fails; `Remote.httpWithLive` is the other end. The principal is
119
+ * stream fails; `httpWithLive` (`foldkit-remote/live`) is the other end. The principal is
14
120
  * resolved per request, from whatever the runtime hands over (a header, a
15
121
  * binding, a session), and the Sources' requirements are provided per
16
122
  * request from the environment (a D1 binding, a connection string).
17
123
  */
124
+ const decodeRequest = Schema.decodeUnknownOption(RemoteJsonRequest);
125
+ const decodeBatch = Schema.decodeUnknownOption(ReadBatch);
126
+ const decodeQuery = Schema.decodeUnknownOption(QueryRequest);
127
+ const decodeReadResult = Schema.decodeUnknownOption(ReadBatchResult);
128
+ const decodeQueryResult = Schema.decodeUnknownOption(QueryResult);
129
+ /** `body`, when it is a read or query every source of which is public. */
130
+ const shareableOf = (server, body) => Option.flatMap(decodeRequest(body), ({ operation, payload }) => ({
131
+ read: () => Option.flatMap(decodeBatch(payload), (batch) => Option.map(readPolicy(server, batch), (policy) => ({
132
+ policy,
133
+ tagsOf: (result) => Option.match(decodeReadResult(result), {
134
+ onNone: () => [],
135
+ onSome: (read) => readTags(batch, read)
136
+ })
137
+ }))),
138
+ query: () => Option.flatMap(decodeQuery(payload), (request) => Option.map(queryPolicy(server, request), (policy) => ({
139
+ policy,
140
+ tagsOf: (result) => Option.match(decodeQueryResult(result), {
141
+ onNone: () => [],
142
+ onSome: (page) => queryTags(server, request, page)
143
+ })
144
+ }))),
145
+ mutate: () => Option.none()
146
+ })[operation]());
147
+ /** An answer as anyone may be given it: its result without whom it was for. */
148
+ const unaddressedAnswer = (answer) => {
149
+ if (!("result" in answer) || typeof answer.result !== "object" || answer.result === null) return answer;
150
+ const { principal: _, ...result } = answer.result;
151
+ return { result };
152
+ };
153
+ /** Whether `body` is a write: what it names, a cache purges. */
154
+ const isWrite = (body) => Option.exists(decodeRequest(body), (request) => request.operation === "mutate");
155
+ /** A visitor the server's `viewer` names a row for is someone: their reads are their own. */
156
+ const refuseSomeone = (server, cache) => {
157
+ if (cache !== void 0 && server.viewer !== void 0 && Option.isSome(server.viewer(cache.visitor))) throw new Error("foldkit-remote-server: cache.visitor must be no one, but the server viewer names a row for it");
158
+ };
18
159
  /** A live open over fetch: the requirements and the cursor it resumes after. */
19
160
  const LiveFetchRequest = Schema.Struct({
20
161
  operation: Schema.Literal("live"),
@@ -103,6 +244,8 @@ const liveResponse = (handlers, payload, heartbeat, checked, release, headers) =
103
244
  */
104
245
  const serveFetch = (config) => {
105
246
  const path = config.path ?? "/remote";
247
+ refuseSomeone(config.server, config.cache);
248
+ const maxBodyBytes = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
106
249
  const heartbeat = config.liveHeartbeat ?? DEFAULT_HEARTBEAT;
107
250
  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
251
  /** `effect` reporting to `config.diagnostics` with `request`, when it is given. */
@@ -116,31 +259,83 @@ const serveFetch = (config) => {
116
259
  if (revalidate === void 0) return Stream.empty;
117
260
  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);
118
261
  };
262
+ /**
263
+ * A public read: the visitor's answer, from the store or answered and kept.
264
+ * Under `check`, also the asker's own, which is given instead where they differ.
265
+ */
266
+ const answerShared = (request, body, cache, shareable, own, headers) => Effect.gen(function* () {
267
+ const asked = stableStringify(body);
268
+ const key = yield* cacheKey(request.url, "remote", asked);
269
+ const kept = yield* cache.store.match(key);
270
+ let text;
271
+ if (Option.isSome(kept)) text = kept.value;
272
+ else {
273
+ const visitor = RemoteServer.handlers(config.server, cache.visitor, {
274
+ maxIdsPerEntity: config.maxIdsPerEntity,
275
+ maxDepth: config.maxDepth
276
+ });
277
+ const answered = yield* RemoteServer.answer(visitor, body);
278
+ if (answered.status !== 200) return Response.json(answered.body, {
279
+ status: answered.status,
280
+ headers
281
+ });
282
+ text = JSON.stringify(unaddressedAnswer(answered.body));
283
+ yield* cache.store.put(key, text, {
284
+ maxAge: shareable.policy.maxAge,
285
+ tags: shareable.tagsOf("result" in answered.body ? answered.body.result : {})
286
+ });
287
+ }
288
+ if (cache.check === true) {
289
+ const mine = yield* RemoteServer.answer(own, body);
290
+ if (stableStringify(unaddressedAnswer(mine.body)) !== stableStringify(JSON.parse(text))) {
291
+ yield* Diagnostics.report(cachedReadDiffers(asked));
292
+ return Response.json(mine.body, {
293
+ status: mine.status,
294
+ headers
295
+ });
296
+ }
297
+ }
298
+ return new Response(text, { headers: {
299
+ "content-type": "application/json",
300
+ "cache-control": `public, max-age=${maxAgeSeconds(shareable.policy)}`,
301
+ ...headers
302
+ } });
303
+ });
119
304
  /** `live` is whether the response streams, and so owns `scope` until it ends. */
120
305
  const respond = (request, env, scope) => Effect.gen(function* () {
121
306
  const principal = yield* config.resolvePrincipal(request, env);
122
307
  const headers = config.headers?.(principal) ?? {};
123
- const body = yield* Effect.option(Effect.tryPromise(() => request.json()));
124
- if (Option.isNone(body)) return {
125
- response: Response.json({ error: "The body is not JSON" }, {
126
- status: 400,
127
- headers
128
- }),
129
- live: false
130
- };
308
+ const body = yield* Effect.result(readJson(request, maxBodyBytes));
309
+ if (Result.isFailure(body)) {
310
+ const { status, answer } = body.failure;
311
+ return {
312
+ response: Response.json(answer, {
313
+ status,
314
+ headers
315
+ }),
316
+ live: false
317
+ };
318
+ }
131
319
  const handlers = RemoteServer.handlers(config.server, principal, {
132
320
  live: config.live,
133
321
  maxIdsPerEntity: config.maxIdsPerEntity,
134
322
  maxDepth: config.maxDepth
135
323
  });
136
- if (isLiveOpen(body.value)) {
137
- const response = yield* liveResponse(handlers, body.value.payload, heartbeat, revalidation(request, env, principal), Scope.close(scope, Exit.void), headers);
324
+ if (isLiveOpen(body.success)) {
325
+ const response = yield* liveResponse(handlers, body.success.payload, heartbeat, revalidation(request, env, principal), Scope.close(scope, Exit.void), headers);
138
326
  return {
139
327
  response,
140
328
  live: response.status === 200
141
329
  };
142
330
  }
143
- const answered = yield* RemoteServer.answer(handlers, body.value);
331
+ const { cache } = config;
332
+ const shareable = cache === void 0 ? Option.none() : shareableOf(config.server, body.success);
333
+ if (cache !== void 0 && Option.isSome(shareable)) return {
334
+ response: yield* answerShared(request, body.success, cache, shareable.value, handlers, headers),
335
+ live: false
336
+ };
337
+ const answered = yield* RemoteServer.answer(handlers, body.success);
338
+ if (cache !== void 0 && answered.status === 200 && isWrite(body.success)) yield* cache.store.purge(writeTags("result" in answered.body ? answered.body.result : {}));
144
339
  return {
145
340
  response: Response.json(answered.body, {
146
341
  status: answered.status,
@@ -157,6 +352,7 @@ const serveFetch = (config) => {
157
352
  }));
158
353
  const served = async (request, env) => {
159
354
  if (request.method !== "POST" || new URL(request.url).pathname !== path) return Response.json({ error: "not found" }, { status: 404 });
355
+ if (declaresTooLarge(request, maxBodyBytes)) return Response.json(tooLargeAnswer(maxBodyBytes), { status: 413 });
160
356
  const exit = await Effect.runPromiseExit(Effect.gen(function* () {
161
357
  const scope = yield* Scope.make();
162
358
  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;
@@ -167,11 +363,38 @@ const serveFetch = (config) => {
167
363
  };
168
364
  return async (request, env) => {
169
365
  const response = await served(request, env);
170
- if (!response.headers.has("cache-control")) response.headers.set("cache-control", "no-store");
366
+ if (!response.headers.has("cache-control")) response.headers.set("cache-control", "private, no-store");
171
367
  return response;
172
368
  };
173
369
  };
174
370
  /**
371
+ * The cache's checker, for a test: serves each request twice through
372
+ * `serveFetch` with `cache.check` and a store in memory, so every public read
373
+ * is answered both as the visitor (kept, then from the store) and as whoever
374
+ * the request resolves to. Rejects naming each read whose answers differ, and
375
+ * when no read was public, which would check nothing. Give requests from at
376
+ * least two principals, a visitor's and someone's; each is a function, since
377
+ * a body is read once.
378
+ */
379
+ const checkCache = async (config, requests, env) => {
380
+ const store = CacheStore.memory();
381
+ const differs = [];
382
+ const serve = serveFetch({
383
+ ...config,
384
+ cache: {
385
+ ...config.cache,
386
+ store,
387
+ check: true
388
+ },
389
+ diagnostics: (diagnostic) => Effect.sync(() => {
390
+ if (diagnostic._tag === "CachedReadDiffers") differs.push(diagnostic.message);
391
+ })
392
+ });
393
+ for (const _round of [1, 2]) for (const make of requests) await serve(make(), env);
394
+ if (differs.length > 0) throw new Error(differs.join("\n"));
395
+ if (store.size() === 0) throw new Error("checkCache: no request was a public read, so nothing was checked");
396
+ };
397
+ /**
175
398
  * The reader a page render reads through, in the same process: the request's
176
399
  * `RemoteClient`, answered by the server's own handlers with no HTTP between
177
400
  * them. Give it `serveFetch`'s config with the resolver a page's request
@@ -184,18 +407,28 @@ const serveFetch = (config) => {
184
407
  * refusal fails that Effect with `Unauthenticated`, as a 401 would. It only
185
408
  * reads: a mutation fails with `RemoteMutationError` and a live open with
186
409
  * `RemoteLiveError`, since a navigation can be started from another site.
410
+ *
411
+ * Each read is noted for a render `foldkit-ssr` may cache (`PageReads`):
412
+ * with `cache`, one proved public as `serveFetch` proves it is answered as
413
+ * `cache.visitor` and noted public; every other read, and every read without
414
+ * `cache`, is noted private, which keeps the page from being cached.
187
415
  */
188
- const pageReader = (config) => (request, env) => Layer.unwrap(Effect.map(config.resolvePrincipal(request, env), (principal) => {
189
- const handlers = RemoteServer.handlers(config.server, principal, {
416
+ const pageReader = (config) => {
417
+ refuseSomeone(config.server, config.cache);
418
+ const limits = {
190
419
  maxIdsPerEntity: config.maxIdsPerEntity,
191
420
  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 };
421
+ };
422
+ const visitor = Option.map(Option.fromUndefinedOr(config.cache), (cache) => RemoteServer.handlers(config.server, cache.visitor, limits));
423
+ return (request, env) => Layer.unwrap(Effect.map(config.resolvePrincipal(request, env), (principal) => {
424
+ const handlers = notingHandlers(config.server, RemoteServer.handlers(config.server, principal, limits), visitor);
425
+ return Remote.clientLayer({
426
+ ...handlers,
427
+ FoldkitRemoteMutate: () => Effect.fail(new RemoteMutationError({ message: "A page render reads; it does not write" })),
428
+ FoldkitRemoteLive: () => Stream.fail(new RemoteLiveError({ message: "A page render keeps no live stream" }))
429
+ });
430
+ })).pipe(Layer.provide(config.layer(env)));
431
+ };
432
+ export { checkCache, pageReader, serveFetch };
200
433
 
201
434
  //# sourceMappingURL=fetch.mjs.map
@@ -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 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.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;;;;;;;;AAsBA,MAAa,cACa,YACvB,SAAkB,QACjB,MAAM,OACJ,OAAO,IAAI,OAAO,iBAAiB,SAAS,GAAG,IAAG,cAAa;CAC7D,MAAM,WAAW,aAAa,SAAS,OAAO,QAAQ,WAAW;EAC/D,iBAAiB,OAAO;EACxB,UAAU,OAAO;CACnB,CAAC;CACD,OAAO,OAAO,YAAe;EAC3B,GAAG;EACH,2BACE,OAAO,KACL,IAAI,oBAAoB,EAAE,SAAS,yCAAyC,CAAC,CAC/E;EACF,yBACE,OAAO,KAAK,IAAI,gBAAgB,EAAE,SAAS,qCAAqC,CAAC,CAAC;CACtF,CAAC;AACH,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQ,OAAO,MAAM,GAAG,CAAC,CAAC"}
1
+ {"version":3,"file":"fetch.mjs","names":[],"sources":["../src/edgeCache.ts","../src/fetch.ts"],"sourcesContent":["/**\n * Which reads a server may share between whoever asks, and the tags a store\n * keeps them under (#428).\n *\n * A read is public only where the server can prove nothing about it depends\n * on who asks: every source it passes through has no `authorize`, no\n * `filter`, no `visible` rule (a guard's, a binding's, `memory`'s\n * `readable`) and no member answered per viewer, and every one declares how\n * long it stays fresh. Those rules are functions of the principal this\n * module cannot read, so it does not try: a source with one is private,\n * even where its rule happens to read only the row. A public read is then\n * answered as the visitor, whoever asks, so even a source's own `read` that\n * looks at the principal gives everyone one answer, never someone's own.\n */\nimport { Effect, Option, Schema } from 'effect'\nimport {\n CachedRead,\n MutationResult,\n PageReads,\n QueryResult,\n ReadBatchResult,\n listTag,\n rowTag,\n shorterPolicy,\n type CachePolicy,\n type ReadBatch,\n type QueryRequest,\n type RelationRequirement,\n type RemoteRpcClient,\n} from 'foldkit-remote'\nimport type { EntitySource, ServerDefinition } from './index.js'\n\ntype Batch = Schema.Schema.Type<typeof ReadBatch>\ntype QueryAsked = Schema.Schema.Type<typeof QueryRequest>\n\n/** A source's freshness, where nothing it runs is a rule about who asks. */\nconst sourcePolicy = <P, R>(source: EntitySource<P, R> | undefined): Option.Option<CachePolicy> =>\n source === undefined ||\n source.authorize !== undefined ||\n source.filter !== undefined ||\n source.visible !== undefined ||\n (source.perViewer ?? []).length > 0\n ? Option.none()\n : Option.fromUndefinedOr(source.cache)\n\n/** Two policies' shorter, none when either is none. */\nconst both = (a: Option.Option<CachePolicy>, b: Option.Option<CachePolicy>) =>\n Option.flatMap(a, left => Option.map(b, right => shorterPolicy(left, right)))\n\n/** A slice's policy: its entity's, and every relation's it reaches. */\nconst slicePolicy = <P, R>(\n server: ServerDefinition<P, R>,\n slice: RelationRequirement,\n): Option.Option<CachePolicy> =>\n Object.values(slice.relations ?? {}).reduce(\n (policy, relation) => both(policy, slicePolicy(server, relation)),\n sourcePolicy(server.entities.get(slice.entity)),\n )\n\n/** A read batch's policy: none for an empty one, which keeps nothing worth a key. */\nexport const readPolicy = <P, R>(\n server: ServerDefinition<P, R>,\n batch: Batch,\n): Option.Option<CachePolicy> =>\n batch.requests.length === 0\n ? Option.none()\n : batch.requests.map(request => slicePolicy(server, request)).reduce(both)\n\n/** A query's policy: its own, its rows' and what its `select` reaches. */\nexport const queryPolicy = <P, R>(\n server: ServerDefinition<P, R>,\n request: QueryAsked,\n): Option.Option<CachePolicy> => {\n const source = server.queries.get(request.query)\n if (source === undefined || source.visible !== undefined) return Option.none()\n const own = both(\n Option.fromUndefinedOr(source.cache),\n sourcePolicy(server.entities.get(source.entity)),\n )\n return request.select === undefined ? own : both(own, slicePolicy(server, request.select))\n}\n\ntype Row = { readonly entity: string; readonly id: string }\n\nconst rowTags = (rows: ReadonlyArray<Row>): ReadonlyArray<string> =>\n rows.map(row => rowTag(row.entity, row.id))\n\n/** What a read's answer holds: each row asked for, found or not, and each it reached. */\nexport const readTags = (\n batch: Batch,\n result: Schema.Schema.Type<typeof ReadBatchResult>,\n): ReadonlyArray<string> => [\n ...new Set([...rowTags(batch.requests), ...rowTags(result.entities), ...rowTags(result.settled)]),\n]\n\n/** What a query's answer holds: every list of its entity, and each row on the page. */\nexport const queryTags = <P, R>(\n server: ServerDefinition<P, R>,\n request: QueryAsked,\n result: Schema.Schema.Type<typeof QueryResult>,\n): ReadonlyArray<string> => [\n ...new Set([\n ...Option.toArray(\n Option.map(Option.fromUndefinedOr(server.queries.get(request.query)), source =>\n listTag(source.entity),\n ),\n ),\n ...rowTags(result.edges),\n ...rowTags(result.entities ?? []),\n ]),\n]\n\nconst decodeMutationResult = Schema.decodeUnknownOption(MutationResult)\n\n/**\n * What a write's answer names, as tags to purge: each row it wrote, deleted,\n * moved in a list or read back, and every list of each of their entities,\n * which a changed row can join or leave. A write naming nothing purges nothing.\n */\nexport const writeTags = (result: unknown): ReadonlyArray<string> =>\n Option.match(decodeMutationResult(result), {\n onNone: () => [],\n onSome: answer => {\n const rows: ReadonlyArray<Row> = [\n ...answer.entities,\n ...(answer.deleted ?? []),\n ...(answer.connections ?? []).map(change => change.edge),\n ...(answer.read?.result.entities ?? []),\n ...(answer.lists ?? []).flatMap(list => [\n ...list.result.edges,\n ...(list.result.entities ?? []),\n ]),\n ]\n return [...new Set([...rowTags(rows), ...rows.map(row => listTag(row.entity))])]\n },\n })\n\n/** An answer as anyone may be given it: without whom it was for. */\nconst unaddressed = <A extends { readonly principal?: unknown }>(\n answer: A,\n): Omit<A, 'principal'> => {\n const { principal: _, ...rest } = answer\n return rest\n}\n\nconst hex = (bytes: ArrayBuffer): string =>\n [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, '0')).join('')\n\n/**\n * The key a request's answer is kept under: the SHA-256 of `text` (the\n * request as stable JSON), under the request's own origin, since the Workers\n * Cache API keys by URL.\n */\nexport const cacheKey = (url: string, kind: string, text: string): Effect.Effect<string> =>\n Effect.promise(() => crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).pipe(\n Effect.map(digest => `${new URL(url).origin}/__foldkit/cache/${kind}/${hex(digest)}`),\n )\n\n/**\n * Handlers that answer every read and query proved public as `visitor`, and\n * note each read in the render's `PageReads`: public with its policy and\n * tags, or private. Without a visitor every read is private, and so is one\n * that fails, since a page drawn without its read is no page to keep.\n */\nexport const notingHandlers = <P, R>(\n server: ServerDefinition<P, R>,\n own: RemoteRpcClient<R>,\n visitor: Option.Option<RemoteRpcClient<R>>,\n): RemoteRpcClient<R> => {\n const note = (read: CachedRead) =>\n Effect.flatMap(Effect.service(PageReads), noted =>\n Effect.sync(() => Option.map(noted, add => add(read))),\n )\n return {\n ...own,\n FoldkitRemoteRead: batch =>\n Option.match(\n Option.flatMap(visitor, handlers =>\n Option.map(readPolicy(server, batch), policy => ({ handlers, policy })),\n ),\n {\n onNone: () => Effect.ensuring(own.FoldkitRemoteRead(batch), note(CachedRead.Private())),\n onSome: ({ handlers, policy }) =>\n Effect.flatMap(handlers.FoldkitRemoteRead(batch), result =>\n Effect.as(\n note(CachedRead.Public({ policy, tags: readTags(batch, result) })),\n unaddressed(result),\n ),\n ).pipe(Effect.onError(() => note(CachedRead.Private()))),\n },\n ),\n FoldkitRemoteQuery: request =>\n Option.match(\n Option.flatMap(visitor, handlers =>\n Option.map(queryPolicy(server, request), policy => ({ handlers, policy })),\n ),\n {\n onNone: () =>\n Effect.ensuring(own.FoldkitRemoteQuery(request), note(CachedRead.Private())),\n onSome: ({ handlers, policy }) =>\n Effect.flatMap(handlers.FoldkitRemoteQuery(request), result =>\n Effect.as(\n note(CachedRead.Public({ policy, tags: queryTags(server, request, result) })),\n unaddressed(result),\n ),\n ).pipe(Effect.onError(() => note(CachedRead.Private()))),\n },\n ),\n }\n}\n","/**\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; `httpWithLive` (`foldkit-remote/live`) 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 Result,\n Schedule,\n Schema,\n Scope,\n Stream,\n} from 'effect'\nimport {\n DEFAULT_MAX_BODY_BYTES,\n CacheStore,\n Diagnostics,\n LiveRequirement,\n QueryRequest,\n QueryResult,\n ReadBatch,\n ReadBatchResult,\n Remote,\n RemoteJsonRequest,\n RemoteLiveError,\n RemoteMutationError,\n maxAgeSeconds,\n stableStringify,\n type CachePolicy,\n type Diagnostic,\n type RemoteClient,\n type RemoteJsonAnswer,\n type RemoteRpcClient,\n type RemoteUnauthenticated,\n} from 'foldkit-remote'\nimport { declaresTooLarge, readJson, tooLargeAnswer } from './body.js'\nimport { cachedReadDiffers, serverDefect } from './diagnostics.js'\nimport {\n cacheKey,\n notingHandlers,\n queryPolicy,\n queryTags,\n readPolicy,\n readTags,\n writeTags,\n} from './edgeCache.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 * A request body may not be larger than this many bytes; default 1 MiB. A\n * larger one is a 413 with Remote's `tooLarge` answer, refused before it is\n * decoded: by its `content-length` before the principal is resolved, or\n * once the bytes read pass the limit. Give the client the same number\n * (`Remote.clientLayer(…, { maxBodyBytes })`), so it cuts its reads to fit.\n */\n readonly maxBodyBytes?: number | undefined\n /**\n * Keeps public reads in `store` (#428). A read or query is public where\n * none of the sources it passes through has a rule about who asks\n * (`authorize`, `filter`, `visible`, a member per viewer) and each declares\n * how long it stays fresh (`EdgeCache.of` on its Entity, `cache` on its\n * Query). A public read is answered as `visitor`, whoever asks, so one\n * answer is right for everyone, and kept for the shortest `maxAge` it\n * reaches; it says `cache-control: public, max-age=…`. Every other answer\n * says `private, no-store`. A write answered here purges the kept reads\n * holding a row it names, and every list of that row's entity.\n *\n * `visitor` is the principal of someone not signed in: refused when the\n * server's `viewer` names a row for it. With `check`, for development and\n * tests, each public read is also answered as who asks, and a difference\n * is reported (`CachedReadDiffers`) and answered with the asker's own.\n */\n readonly cache?:\n | {\n readonly store: CacheStore\n readonly visitor: P\n readonly check?: boolean | undefined\n }\n | undefined\n}\n\n/** A read or query a cache may keep: how long, and the tags of its answer. */\ninterface Shareable {\n readonly policy: CachePolicy\n readonly tagsOf: (result: unknown) => ReadonlyArray<string>\n}\n\nconst decodeRequest = Schema.decodeUnknownOption(RemoteJsonRequest)\nconst decodeBatch = Schema.decodeUnknownOption(ReadBatch)\nconst decodeQuery = Schema.decodeUnknownOption(QueryRequest)\nconst decodeReadResult = Schema.decodeUnknownOption(ReadBatchResult)\nconst decodeQueryResult = Schema.decodeUnknownOption(QueryResult)\n\n/** `body`, when it is a read or query every source of which is public. */\nconst shareableOf = <P, R>(\n server: ServerDefinition<P, R>,\n body: unknown,\n): Option.Option<Shareable> =>\n Option.flatMap(decodeRequest(body), ({ operation, payload }) =>\n ({\n read: () =>\n Option.flatMap(decodeBatch(payload), batch =>\n Option.map(readPolicy(server, batch), policy => ({\n policy,\n tagsOf: (result: unknown) =>\n Option.match(decodeReadResult(result), {\n onNone: () => [],\n onSome: read => readTags(batch, read),\n }),\n })),\n ),\n query: () =>\n Option.flatMap(decodeQuery(payload), request =>\n Option.map(queryPolicy(server, request), policy => ({\n policy,\n tagsOf: (result: unknown) =>\n Option.match(decodeQueryResult(result), {\n onNone: () => [],\n onSome: page => queryTags(server, request, page),\n }),\n })),\n ),\n mutate: () => Option.none<Shareable>(),\n })[operation](),\n )\n\n/** An answer as anyone may be given it: its result without whom it was for. */\nconst unaddressedAnswer = (answer: RemoteJsonAnswer): RemoteJsonAnswer => {\n if (!('result' in answer) || typeof answer.result !== 'object' || answer.result === null)\n return answer\n const { principal: _, ...result } = answer.result as Readonly<Record<string, unknown>>\n return { result }\n}\n\n/** Whether `body` is a write: what it names, a cache purges. */\nconst isWrite = (body: unknown): boolean =>\n Option.exists(decodeRequest(body), request => request.operation === 'mutate')\n\n/** A visitor the server's `viewer` names a row for is someone: their reads are their own. */\nconst refuseSomeone = <P, R>(\n server: ServerDefinition<P, R>,\n cache: { readonly visitor: P } | undefined,\n): void => {\n if (\n cache !== undefined &&\n server.viewer !== undefined &&\n Option.isSome(server.viewer(cache.visitor))\n )\n throw new Error(\n 'foldkit-remote-server: cache.visitor must be no one, but the server viewer names a row for it',\n )\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 refuseSomeone(config.server, config.cache)\n const maxBodyBytes = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES\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 /**\n * A public read: the visitor's answer, from the store or answered and kept.\n * Under `check`, also the asker's own, which is given instead where they differ.\n */\n const answerShared = (\n request: Request,\n body: unknown,\n cache: NonNullable<FetchConfig<P, R, Env, RP>['cache']>,\n shareable: Shareable,\n own: RemoteRpcClient<R>,\n headers: Readonly<Record<string, string>>,\n ): Effect.Effect<Response, never, R> =>\n Effect.gen(function* () {\n const asked = stableStringify(body)\n const key = yield* cacheKey(request.url, 'remote', asked)\n const kept = yield* cache.store.match(key)\n let text: string\n if (Option.isSome(kept)) {\n text = kept.value\n } else {\n const visitor = RemoteServer.handlers(config.server, cache.visitor, {\n maxIdsPerEntity: config.maxIdsPerEntity,\n maxDepth: config.maxDepth,\n })\n const answered = yield* RemoteServer.answer(visitor, body)\n // A refusal or a failure is nobody's to keep.\n if (answered.status !== 200) {\n return Response.json(answered.body, { status: answered.status, headers })\n }\n text = JSON.stringify(unaddressedAnswer(answered.body))\n yield* cache.store.put(key, text, {\n maxAge: shareable.policy.maxAge,\n tags: shareable.tagsOf('result' in answered.body ? answered.body.result : {}),\n })\n }\n if (cache.check === true) {\n const mine = yield* RemoteServer.answer(own, body)\n if (stableStringify(unaddressedAnswer(mine.body)) !== stableStringify(JSON.parse(text))) {\n yield* Diagnostics.report(cachedReadDiffers(asked))\n return Response.json(mine.body, { status: mine.status, headers })\n }\n }\n return new Response(text, {\n headers: {\n 'content-type': 'application/json',\n 'cache-control': `public, max-age=${maxAgeSeconds(shareable.policy)}`,\n ...headers,\n },\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.result(readJson(request, maxBodyBytes))\n if (Result.isFailure(body)) {\n const { status, answer } = body.failure\n return { response: Response.json(answer, { status, headers }), live: false }\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.success)) {\n const response = yield* liveResponse(\n handlers,\n body.success.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 { cache } = config\n const shareable =\n cache === undefined ? Option.none<Shareable>() : shareableOf(config.server, body.success)\n if (cache !== undefined && Option.isSome(shareable)) {\n const response = yield* answerShared(\n request,\n body.success,\n cache,\n shareable.value,\n handlers,\n headers,\n )\n return { response, live: false }\n }\n const answered = yield* RemoteServer.answer(handlers, body.success)\n if (cache !== undefined && answered.status === 200 && isWrite(body.success)) {\n yield* cache.store.purge(writeTags('result' in answered.body ? answered.body.result : {}))\n }\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 // Refused on what it says of itself: no layer built, no principal asked, nothing read.\n if (declaresTooLarge(request, maxBodyBytes)) {\n return Response.json(tooLargeAnswer(maxBodyBytes), { status: 413 })\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 but a public read's is read as one principal: no cache may\n // keep it for another. 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')) {\n response.headers.set('cache-control', 'private, no-store')\n }\n return response\n }\n}\n\n/**\n * The cache's checker, for a test: serves each request twice through\n * `serveFetch` with `cache.check` and a store in memory, so every public read\n * is answered both as the visitor (kept, then from the store) and as whoever\n * the request resolves to. Rejects naming each read whose answers differ, and\n * when no read was public, which would check nothing. Give requests from at\n * least two principals, a visitor's and someone's; each is a function, since\n * a body is read once.\n */\nexport const checkCache = async <P, R, Env, RP = never>(\n config: Omit<FetchConfig<P, R, Env, RP>, 'cache' | 'diagnostics'> & {\n readonly cache: { readonly visitor: P }\n },\n requests: ReadonlyArray<() => Request>,\n env: Env,\n): Promise<void> => {\n const store = CacheStore.memory()\n const differs: Array<string> = []\n const serve = serveFetch({\n ...config,\n cache: { ...config.cache, store, check: true },\n diagnostics: diagnostic =>\n Effect.sync(() => {\n // tag-check: open -- a Diagnostic's tag is any package's; this one is ours.\n if (diagnostic._tag === 'CachedReadDiffers') differs.push(diagnostic.message)\n }),\n })\n for (const _round of [1, 2]) {\n for (const make of requests) await serve(make(), env)\n }\n if (differs.length > 0) throw new Error(differs.join('\\n'))\n if (store.size() === 0) {\n throw new Error('checkCache: no request was a public read, so nothing was checked')\n }\n}\n\n/**\n * What `pageReader` reads of a `serveFetch` config: the server, its Sources'\n * layer, its limits, and the cache's `visitor`.\n */\nexport type PageReaderConfig<P, R, Env, RP = never> = Pick<\n FetchConfig<P, R, Env, RP>,\n 'server' | 'resolvePrincipal' | 'layer' | 'maxIdsPerEntity' | 'maxDepth' | 'cache'\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 *\n * Each read is noted for a render `foldkit-ssr` may cache (`PageReads`):\n * with `cache`, one proved public as `serveFetch` proves it is answered as\n * `cache.visitor` and noted public; every other read, and every read without\n * `cache`, is noted private, which keeps the page from being cached.\n */\nexport const pageReader = <P, R, Env, RP = never>(config: PageReaderConfig<P, R, Env, RP>) => {\n refuseSomeone(config.server, config.cache)\n const limits = { maxIdsPerEntity: config.maxIdsPerEntity, maxDepth: config.maxDepth }\n const visitor = Option.map(Option.fromUndefinedOr(config.cache), cache =>\n RemoteServer.handlers(config.server, cache.visitor, limits),\n )\n return (request: Request, env: Env): Layer.Layer<RemoteClient, RemoteUnauthenticated> =>\n Layer.unwrap(\n Effect.map(config.resolvePrincipal(request, env), principal => {\n const handlers = notingHandlers(\n config.server,\n RemoteServer.handlers(config.server, principal, limits),\n visitor,\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}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoCA,MAAM,gBAAsB,WAC1B,WAAW,KAAA,KACX,OAAO,cAAc,KAAA,KACrB,OAAO,WAAW,KAAA,KAClB,OAAO,YAAY,KAAA,MAClB,OAAO,aAAa,CAAC,EAAA,CAAG,SAAS,IAC9B,OAAO,KAAK,IACZ,OAAO,gBAAgB,OAAO,KAAK;;AAGzC,MAAM,QAAQ,GAA+B,MAC3C,OAAO,QAAQ,IAAG,SAAQ,OAAO,IAAI,IAAG,UAAS,cAAc,MAAM,KAAK,CAAC,CAAC;;AAG9E,MAAM,eACJ,QACA,UAEA,OAAO,OAAO,MAAM,aAAa,CAAC,CAAC,CAAC,CAAC,QAClC,QAAQ,aAAa,KAAK,QAAQ,YAAY,QAAQ,QAAQ,CAAC,GAChE,aAAa,OAAO,SAAS,IAAI,MAAM,MAAM,CAAC,CAChD;;AAGF,MAAa,cACX,QACA,UAEA,MAAM,SAAS,WAAW,IACtB,OAAO,KAAK,IACZ,MAAM,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