foldkit-remote-server 0.20.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/README.md +124 -3
- package/dist/fetch.d.mts +47 -4
- package/dist/fetch.d.mts.map +1 -1
- package/dist/fetch.mjs +242 -14
- package/dist/fetch.mjs.map +1 -1
- package/dist/{index-B85UhEfk.d.mts → index-pMrHmWZt.d.mts} +42 -5
- package/dist/index-pMrHmWZt.d.mts.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/{src-D8azLxgd.mjs → src-CHkHaItI.mjs} +19 -5
- package/dist/src-CHkHaItI.mjs.map +1 -0
- package/package.json +4 -4
- package/dist/index-B85UhEfk.d.mts.map +0 -1
- package/dist/src-D8azLxgd.mjs.map +0 -1
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; `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 Result,\n Schedule,\n Schema,\n Scope,\n Stream,\n} from 'effect'\nimport {\n DEFAULT_MAX_BODY_BYTES,\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 { declaresTooLarge, readJson, tooLargeAnswer } from './body.js'\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 * 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\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 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 /** `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 answered = yield* RemoteServer.answer(handlers, body.success)\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 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":";;;;;;;;;;;;;;;;;;AAsHA,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;;;;;;;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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,SAAS,KAAI,YAAW,YAAY,QAAQ,OAAO,CAAC,CAAC,CAAC,OAAO,IAAI;;AAG7E,MAAa,eACX,QACA,YAC+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|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Cause, Context, Data, Duration, Effect, Layer, Option, Schema, Stream } from "effect";
|
|
2
2
|
import { AnyQuery, AnyWrite, Computation, EntityRef, ExprContext, MemoryOperators, QueryEvaluateError, Row, WriteAssignment, assertSupported as assertSupported$1, evaluate as evaluate$1, supported } from "foldkit-entity";
|
|
3
|
-
import { Boundary, ConnectionChangeSchema, ConnectionIdentity, ConnectionSpec, Diagnostic, LiveChange, MutationDescriptor, NormalizedPatch, QueryDescriptor, QueryWindow, RelationRequirement, RemoteClient, RemoteDescriptor, RemoteForbidden, RemoteJsonAnswer, RemoteReadError, RemoteRpcClient, RemoteUnauthenticated, Requirement } from "foldkit-remote";
|
|
3
|
+
import { Boundary, CachePolicy, ConnectionChangeSchema, ConnectionIdentity, ConnectionSpec, Diagnostic, LiveChange, MutationDescriptor, NormalizedPatch, QueryDescriptor, QueryWindow, RelationRequirement, RemoteClient, RemoteDescriptor, RemoteForbidden, RemoteJsonAnswer, RemoteReadError, RemoteRpcClient, RemoteUnauthenticated, Requirement } from "foldkit-remote";
|
|
4
4
|
import { HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
5
5
|
/**
|
|
6
6
|
* Effect HTTP middleware refusing a request body over `maxBytes` (default
|
|
@@ -52,8 +52,19 @@ interface ClockSkewed extends Diagnostic {
|
|
|
52
52
|
/** The bound, in milliseconds. */
|
|
53
53
|
readonly bound: number;
|
|
54
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* A read the server judged public answered otherwise for who asked than for
|
|
57
|
+
* the visitor (`serveFetch`'s `cache.check`): its declaration or a source's
|
|
58
|
+
* `read` depends on who asks, so it must not be cached. The asker was given
|
|
59
|
+
* their own answer.
|
|
60
|
+
*/
|
|
61
|
+
interface CachedReadDiffers extends Diagnostic {
|
|
62
|
+
readonly _tag: 'CachedReadDiffers';
|
|
63
|
+
/** The request, as the JSON it was sent as. */
|
|
64
|
+
readonly request: string;
|
|
65
|
+
}
|
|
55
66
|
/** Every diagnostic a Remote server reports. */
|
|
56
|
-
type RemoteServerDiagnostic = ServerDefect | AnswerUnread | PublishFailed | ClockSkewed;
|
|
67
|
+
type RemoteServerDiagnostic = ServerDefect | AnswerUnread | PublishFailed | ClockSkewed | CachedReadDiffers;
|
|
57
68
|
declare const RemoteServerError_base: Schema.Class<RemoteServerError, Schema.TaggedStruct<"RemoteServerError", {
|
|
58
69
|
readonly message: Schema.String;
|
|
59
70
|
}>, Cause.YieldableError>;
|
|
@@ -159,6 +170,12 @@ interface EntitySource<P, R = never> {
|
|
|
159
170
|
* without one.
|
|
160
171
|
*/
|
|
161
172
|
readonly perViewer?: ReadonlyArray<string> | undefined;
|
|
173
|
+
/**
|
|
174
|
+
* How long a read of these rows stays fresh, from the Entity's declaration
|
|
175
|
+
* (`EdgeCache.of`). It never makes a read public: `serveFetch` caches one
|
|
176
|
+
* only where nothing about it depends on who asks.
|
|
177
|
+
*/
|
|
178
|
+
readonly cache?: CachePolicy | undefined;
|
|
162
179
|
}
|
|
163
180
|
/** What `EntitySource.filter` decides for one read. */
|
|
164
181
|
interface ReadPlan {
|
|
@@ -218,6 +235,17 @@ interface WriteRequirement {
|
|
|
218
235
|
readonly holds: RowRequirement;
|
|
219
236
|
readonly reason: Option.Option<string>;
|
|
220
237
|
}
|
|
238
|
+
/**
|
|
239
|
+
* What each row of `entity` a cascading delete would take must hold (#348):
|
|
240
|
+
* that Entity's `Delete` rule for the person deleting. A writer with
|
|
241
|
+
* `cascades` refuses the whole delete as `Forbidden` when any such row does
|
|
242
|
+
* not, and removes nothing. Only rows reached through a relation whose
|
|
243
|
+
* `authorizedBy` is `child` are held to it.
|
|
244
|
+
*/
|
|
245
|
+
interface CascadeRequirement {
|
|
246
|
+
readonly entity: string;
|
|
247
|
+
readonly requires: WriteRequirement;
|
|
248
|
+
}
|
|
221
249
|
/** A row a delete removed with the row it was asked to delete (`onDelete: 'cascade'`). */
|
|
222
250
|
interface CascadedRow {
|
|
223
251
|
readonly entity: string;
|
|
@@ -312,7 +340,9 @@ interface EntityWriter<P, R = never> {
|
|
|
312
340
|
/**
|
|
313
341
|
* Whether `delete` removes, in the transaction that deletes the row, every
|
|
314
342
|
* row declared to go with it (`Entity.cascading`), and answers them as
|
|
315
|
-
* `cascaded
|
|
343
|
+
* `cascaded`; and holds those rows to the `cascading` requirements it is
|
|
344
|
+
* given, judged before anything is removed, refusing the whole delete
|
|
345
|
+
* where one fails. `RemoteServer.write` refuses a delete of an Entity that
|
|
316
346
|
* cascades through a writer without it.
|
|
317
347
|
*/
|
|
318
348
|
readonly cascades?: true;
|
|
@@ -407,6 +437,11 @@ interface EntityWriter<P, R = never> {
|
|
|
407
437
|
readonly when: Option.Option<WriteWhen>;
|
|
408
438
|
/** What the row must hold, judged where it is deleted; only a writer with `requires` is given one. */
|
|
409
439
|
readonly requires?: WriteRequirement | undefined;
|
|
440
|
+
/**
|
|
441
|
+
* What the rows a cascade takes must hold, by Entity; only a writer with
|
|
442
|
+
* `cascades` is given them.
|
|
443
|
+
*/
|
|
444
|
+
readonly cascading?: ReadonlyArray<CascadeRequirement> | undefined;
|
|
410
445
|
readonly principal: P;
|
|
411
446
|
}) => Effect.Effect<DeleteOutcome, RemoteServerError | RemoteForbidden | RemoteUnauthenticated | RemoteUnmet, R>;
|
|
412
447
|
/**
|
|
@@ -551,6 +586,8 @@ interface QuerySource<P, R = never> {
|
|
|
551
586
|
}) => Effect.Effect<QueryPage, RemoteServerError, R>;
|
|
552
587
|
/** The rule that decides which rows the query lists. See `EntitySource.visible`. */
|
|
553
588
|
readonly visible?: unknown;
|
|
589
|
+
/** How long an answer stays fresh, from the Query's declaration. See `EntitySource.cache`. */
|
|
590
|
+
readonly cache?: CachePolicy | undefined;
|
|
554
591
|
}
|
|
555
592
|
/**
|
|
556
593
|
* A list a subscriber reads live (`liveQuery(Data, …)`), admitted
|
|
@@ -994,5 +1031,5 @@ declare const RemoteServer: {
|
|
|
994
1031
|
*/
|
|
995
1032
|
handlers: <P, R, I = never>(server: ServerDefinition<P, R>, principal: P | Context.Key<I, P>, options?: HandlerOptions<P, R>) => RemoteRpcClient<R | I>;
|
|
996
1033
|
};
|
|
997
|
-
export {
|
|
998
|
-
//# sourceMappingURL=index-
|
|
1034
|
+
export { RemoteUnmet as A, RemoteServerDiagnostic as B, QueryPage as C, RemoteServer as D, RemoteInvalid as E, exprContext as F, assertSupported$1 as G, bodyLimit as H, AnswerUnread as I, evaluate$1 as K, CachedReadDiffers as L, ServerDefinition as M, WriteRequirement as N, RemoteServerError as O, WriteWhen as P, ClockSkewed as R, MutationSource as S, ReadPlan as T, QueryEvaluateError as U, ServerDefect as V, Row as W, MemoryRows as _, EntityRecord as a, MutationOutcome as b, EntityWriter as c, LiveQuery as d, LiveSource as f, MemoryReadable as g, MemoryConfig as h, DeleteOutcome as i, RowRequirement as j, RemoteTaken as k, HandlerOptions as l, MemoryBackend as m, CascadedRow as n, EntitySource as o, MemoryAnswering as p, supported as q, ConnectionChange as r, EntitySourceContext as s, CascadeRequirement as t, LiveHub as u, MemoryServed as v, QuerySource as w, MutationRefused as x, MemoryStore as y, PublishFailed as z };
|
|
1035
|
+
//# sourceMappingURL=index-pMrHmWZt.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-pMrHmWZt.d.mts","names":[],"sources":["../src/body.ts","../src/diagnostics.ts","../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;cA4Ga,YAAS,uBAEnB,GAAG,GAAC,UACO,OAAO,OAAO,mBAAmB,oBAAoB,GAAG,OACjE,OAAO,OACR,mBAAmB,oBACnB,GACA,IAAI,kBAAkB;;UCtGT,qBAAqB;WAC3B;WACA,OAAO,MAAM;;;;;;UAOP,qBAAqB;WAC3B;WACA;;WAEA;;;UAIM,sBAAsB;WAC5B;WACA;WACA,OAAO,MAAM;;;;;;;UAQP,oBAAoB;WAC1B;WACA;;WAEA;;WAEA;;WAEA;;;;;;;;UASM,0BAA0B;WAChC;;WAEA;;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.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
export { type AnswerUnread, CascadedRow, type ClockSkewed, ConnectionChange, DeleteOutcome, EntityRecord, EntitySource, EntitySourceContext, EntityWriter, HandlerOptions, LiveHub, LiveQuery, LiveSource, MemoryAnswering, MemoryBackend, MemoryConfig, MemoryReadable, MemoryRows, MemoryServed, MemoryStore, MutationOutcome, MutationRefused, MutationSource, type PublishFailed, QueryEvaluateError, QueryPage, QuerySource, ReadPlan, RemoteInvalid, RemoteServer, type RemoteServerDiagnostic, RemoteServerError, RemoteTaken, RemoteUnmet, type Row, RowRequirement, type ServerDefect, ServerDefinition, WriteRequirement, WriteWhen, assertSupported, bodyLimit, evaluate, exprContext, supported };
|
|
1
|
+
import { A as RemoteUnmet, B as RemoteServerDiagnostic, C as QueryPage, D as RemoteServer, E as RemoteInvalid, F as exprContext, G as assertSupported, H as bodyLimit, I as AnswerUnread, K as evaluate, L as CachedReadDiffers, M as ServerDefinition, N as WriteRequirement, O as RemoteServerError, P as WriteWhen, R as ClockSkewed, S as MutationSource, T as ReadPlan, U as QueryEvaluateError, V as ServerDefect, W as Row, _ as MemoryRows, a as EntityRecord, b as MutationOutcome, c as EntityWriter, d as LiveQuery, f as LiveSource, g as MemoryReadable, h as MemoryConfig, i as DeleteOutcome, j as RowRequirement, k as RemoteTaken, l as HandlerOptions, m as MemoryBackend, n as CascadedRow, o as EntitySource, p as MemoryAnswering, q as supported, r as ConnectionChange, s as EntitySourceContext, t as CascadeRequirement, u as LiveHub, v as MemoryServed, w as QuerySource, x as MutationRefused, y as MemoryStore, z as PublishFailed } from "./index-pMrHmWZt.mjs";
|
|
2
|
+
export { type AnswerUnread, type CachedReadDiffers, CascadeRequirement, CascadedRow, type ClockSkewed, ConnectionChange, DeleteOutcome, EntityRecord, EntitySource, EntitySourceContext, EntityWriter, HandlerOptions, LiveHub, LiveQuery, LiveSource, MemoryAnswering, MemoryBackend, MemoryConfig, MemoryReadable, MemoryRows, MemoryServed, MemoryStore, MutationOutcome, MutationRefused, MutationSource, type PublishFailed, QueryEvaluateError, QueryPage, QuerySource, ReadPlan, RemoteInvalid, RemoteServer, type RemoteServerDiagnostic, RemoteServerError, RemoteTaken, RemoteUnmet, type Row, RowRequirement, type ServerDefect, ServerDefinition, WriteRequirement, WriteWhen, assertSupported, bodyLimit, evaluate, exprContext, supported };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as DeleteOutcome, n as MutationRefused, m as QueryEvaluateError, r as RemoteInvalid, i as RemoteServer, a as RemoteServerError, o as RemoteTaken, s as RemoteUnmet, c as RowRequirement, h as assertSupported, u as bodyLimit, g as evaluate, l as exprContext, _ as supported } from "./src-
|
|
1
|
+
export { t as DeleteOutcome, n as MutationRefused, m as QueryEvaluateError, r as RemoteInvalid, i as RemoteServer, a as RemoteServerError, o as RemoteTaken, s as RemoteUnmet, c as RowRequirement, h as assertSupported, u as bodyLimit, g as evaluate, l as exprContext, _ as supported } from "./src-CHkHaItI.mjs";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Cause, Clock, Context, Data, Duration, Effect, Match, Option, Queue, Schema, Stream } from "effect";
|
|
2
2
|
import { Derivation, Entity, Held, Operators, Query, QueryEvaluateError, SchemaShape, Write, assertSupported, assertSupported as assertSupported$1, evaluate, evaluate as evaluate$1, supported } from "foldkit-entity";
|
|
3
|
-
import { DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_IDS_PER_ENTITY, Diagnostics, MutationRequest, QueryRequest, RELATION_ALIAS, REMOTE_PROTOCOL_VERSION, ReadBatch, Refusal, Remote, RemoteForbidden, RemoteJsonRequest, RemoteLiveError, RemoteLiveRefused, RemoteMutationError, RemotePrincipalChanged, RemoteProtocolError, RemoteQueryError, RemoteReadError, RemoteUnauthenticated, Requirement, aliasedField, connectionIdentity, entityKey, queryIdentity, refParts, refsIn, relationShape, stableStringify } from "foldkit-remote";
|
|
3
|
+
import { DEFAULT_MAX_BODY_BYTES, DEFAULT_MAX_IDS_PER_ENTITY, Diagnostics, EdgeCache, MutationRequest, QueryRequest, RELATION_ALIAS, REMOTE_PROTOCOL_VERSION, ReadBatch, Refusal, Remote, RemoteForbidden, RemoteJsonRequest, RemoteLiveError, RemoteLiveRefused, RemoteMutationError, RemotePrincipalChanged, RemoteProtocolError, RemoteQueryError, RemoteReadError, RemoteUnauthenticated, Requirement, aliasedField, connectionIdentity, entityKey, queryIdentity, refParts, refsIn, relationShape, stableStringify } from "foldkit-remote";
|
|
4
4
|
import { HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
5
5
|
// src/diagnostics.ts
|
|
6
6
|
/**
|
|
@@ -41,6 +41,13 @@ const clockSkewed = (facts) => ({
|
|
|
41
41
|
message: `${facts.mutation} was sent at ${facts.sent}, ${Math.abs(facts.sent - facts.own)} ms from this server's clock (${facts.own}), past its clockSkew of ${facts.bound} ms: it was written at the server's time, so the client's prediction of it moves when the answer lands. The client's clock is off, or the request waited that long.`,
|
|
42
42
|
...facts
|
|
43
43
|
});
|
|
44
|
+
const cachedReadDiffers = (request) => ({
|
|
45
|
+
_tag: "CachedReadDiffers",
|
|
46
|
+
source,
|
|
47
|
+
level: "error",
|
|
48
|
+
message: `a read judged public was answered otherwise for who asked than for a visitor, so it is not the same for everyone and must not be cached; find what in its sources depends on who asks: ${request}`,
|
|
49
|
+
request
|
|
50
|
+
});
|
|
44
51
|
// src/refusal.ts
|
|
45
52
|
/** A caller who could not be told, as a 401 body: the twin of `answer`'s 403. */
|
|
46
53
|
const unauthenticatedAnswer = (refusal) => ({
|
|
@@ -85,7 +92,7 @@ const readBounded = async (request, limit) => {
|
|
|
85
92
|
if (done) break;
|
|
86
93
|
total += value.byteLength;
|
|
87
94
|
if (total > limit) {
|
|
88
|
-
|
|
95
|
+
reader.cancel().catch(() => {});
|
|
89
96
|
throw new BodyTooLarge();
|
|
90
97
|
}
|
|
91
98
|
chunks.push(value);
|
|
@@ -801,6 +808,10 @@ function memory(config) {
|
|
|
801
808
|
const visible = config.readable === void 0 ? {} : { visible: config.readable };
|
|
802
809
|
const entities = [...config.domain.registry.entities.keys()].map((name) => ({
|
|
803
810
|
...visible,
|
|
811
|
+
...Option.match(Option.fromUndefinedOr(config.domain.registry.cached.get(name)), {
|
|
812
|
+
onNone: () => ({}),
|
|
813
|
+
onSome: (cache) => ({ cache })
|
|
814
|
+
}),
|
|
804
815
|
...RemoteServer.entity({ name }, {
|
|
805
816
|
...Object.hasOwn(authorize, name) ? { authorize: authorize[name] } : {},
|
|
806
817
|
...Object.hasOwn(filter, name) ? { filter: filter[name] } : {},
|
|
@@ -1038,6 +1049,7 @@ const RemoteServer = {
|
|
|
1038
1049
|
entity: (entity, options) => {
|
|
1039
1050
|
const declared = entity.members ?? entity.fields;
|
|
1040
1051
|
const fields = declared === void 0 ? void 0 : new Set(Object.keys(declared));
|
|
1052
|
+
const cache = EdgeCache.policyOf(entity);
|
|
1041
1053
|
const unserved = (options.shared ?? []).filter((field) => fields !== void 0 && !fields.has(field));
|
|
1042
1054
|
if (unserved.length > 0) throw new Error(`[foldkit-remote-server] ${entity.name}'s shared fields name no member: ${unserved.join(", ")}`);
|
|
1043
1055
|
return {
|
|
@@ -1046,7 +1058,8 @@ const RemoteServer = {
|
|
|
1046
1058
|
read: options.read,
|
|
1047
1059
|
...options.authorize === void 0 ? {} : { authorize: options.authorize },
|
|
1048
1060
|
...options.filter === void 0 ? {} : { filter: options.filter },
|
|
1049
|
-
...options.shared === void 0 ? {} : { shared: new Set(options.shared) }
|
|
1061
|
+
...options.shared === void 0 ? {} : { shared: new Set(options.shared) },
|
|
1062
|
+
...Option.isSome(cache) ? { cache: cache.value } : {}
|
|
1050
1063
|
};
|
|
1051
1064
|
},
|
|
1052
1065
|
mutation: (mutation, run) => ({
|
|
@@ -1396,6 +1409,7 @@ const RemoteServer = {
|
|
|
1396
1409
|
query: query.name,
|
|
1397
1410
|
entity: query.Result.entity,
|
|
1398
1411
|
Input: query.Input,
|
|
1412
|
+
...query.cache === void 0 ? {} : { cache: query.cache },
|
|
1399
1413
|
run: (context) => run({
|
|
1400
1414
|
input: context.input,
|
|
1401
1415
|
window: context.window,
|
|
@@ -1770,6 +1784,6 @@ const RemoteServer = {
|
|
|
1770
1784
|
};
|
|
1771
1785
|
}
|
|
1772
1786
|
};
|
|
1773
|
-
export { supported as _, RemoteServerError as a, RowRequirement as c, declaresTooLarge as d, readJson as f, evaluate$1 as g, assertSupported$1 as h, RemoteServer as i, exprContext as l, QueryEvaluateError as m, MutationRefused as n, RemoteTaken as o, tooLargeAnswer as p, RemoteInvalid as r, RemoteUnmet as s, DeleteOutcome as t, bodyLimit as u, unauthenticatedAnswer as v,
|
|
1787
|
+
export { supported as _, RemoteServerError as a, serverDefect as b, RowRequirement as c, declaresTooLarge as d, readJson as f, evaluate$1 as g, assertSupported$1 as h, RemoteServer as i, exprContext as l, QueryEvaluateError as m, MutationRefused as n, RemoteTaken as o, tooLargeAnswer as p, RemoteInvalid as r, RemoteUnmet as s, DeleteOutcome as t, bodyLimit as u, unauthenticatedAnswer as v, cachedReadDiffers as y };
|
|
1774
1788
|
|
|
1775
|
-
//# sourceMappingURL=src-
|
|
1789
|
+
//# sourceMappingURL=src-CHkHaItI.mjs.map
|