foldkit-remote-server 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -386,7 +386,13 @@ A refusal of who is asking, rather than of what they asked, is
386
386
  `Effect.fail(RemoteServer.forbid('Only an admin may archive.'))`: sent as
387
387
  `Forbidden` with the reason (a 403 over JSON), or with none when `forbid()` is
388
388
  given none, so the refusal says nothing of why. It is the same for every
389
- mutation, so it needs no `Refusal` declared.
389
+ mutation, so it needs no `Refusal` declared. A refusal of a visitor, someone
390
+ not signed in, is `RemoteServer.unauthenticated(reason)` instead (a 401):
391
+ signing in is the remedy, and Remote's outbox keeps a durable write so
392
+ answered waiting for it, where it settles a `Forbidden` one as failed.
393
+ `RemoteServer.write` refuses a visitor a write whose Entity sets a member from
394
+ who asks that way, and `GuardServer` refuses a visitor every write it would
395
+ refuse.
390
396
 
391
397
  A Source may additionally return connection changes:
392
398
 
@@ -532,7 +538,8 @@ from one that changes nothing; `foldkit-remote-drizzle`'s `writer` has both.
532
538
 
533
539
  A Source answers the rows it changed; the client says what it shows of them.
534
540
  `Data.mutate` sends, with each request, what its active Surfaces read of each
535
- entity and every field its optimistic layer shows (`shown`). After the Source runs, the handler reads, of each row the
541
+ entity, every field its optimistic layer shows, and the supplied members a
542
+ created or edited row foresees (`may`) (`shown`). After the Source runs, the handler reads, of each row the
536
543
  outcome names (a patch, or a list insert), the shown fields the patch left out
537
544
  and every shown relation, and answers that read beside the patch (`read`):
538
545
 
@@ -562,6 +569,24 @@ mutation is answered without it: the write has
562
569
  landed, and the client fetches what it lacks as it would have. A deleted row is
563
570
  not read.
564
571
 
572
+ A request also names the lists the client judges the write moves (`lists`):
573
+ each the first page of a query, as the client's read entry would ask for it.
574
+ The handler admits them before the write runs, then reads each after it with
575
+ the query's own handler, so the page is what `FoldkitRemoteQuery` would answer,
576
+ `authorize` and `filter` included, and answers them beside the rows (`lists`):
577
+
578
+ ```text
579
+ request lists -> admitted (before the write) -> read as queries (after it) -> answer.lists
580
+ ```
581
+
582
+ A list is admitted when its query is one the server serves, its window is a
583
+ first page (`first`, no `after`), its `select` names the query's Entity within
584
+ a read's page bound, and the rows of every list admitted so far stay within
585
+ `maxIdsPerEntity` per Entity. One that is not, or whose read fails (reported
586
+ as `AnswerUnread`), is left out; the write runs either way, and the client
587
+ fetches that list as it would have. The wire refuses more than
588
+ `MAX_ANSWER_LISTS` lists in one request.
589
+
565
590
  A declared write (`RemoteServer.write`) also reads each row its row points at
566
591
  through a `one` relation, before and after the write, through the writer's
567
592
  `linked`, where that link can change one of the row's derived members: a
@@ -609,7 +634,7 @@ The stream carries Remote `LiveChange`s: entity patches/deletes and connection
609
634
  insert/remove/invalidate events.
610
635
 
611
636
  `queries` are the lists of this Entity the subscriber reads live
612
- (`Data.query(…, { live: true })`), each a `LiveQuery` the handler has already
637
+ (`liveQuery(Data, …)`), each a `LiveQuery` the handler has already
613
638
  admitted and resolved: `identity` (the connection as the client keys it, for
614
639
  the connection events), `select` (what the read draws of each row), and
615
640
  `edges`, the registered query run as the subscriber with the page's window.
@@ -835,6 +860,21 @@ does), and a server with no `viewer` refuses that Source where it is made,
835
860
  naming it. A query body's `Expr.viewer` and `Expr.now` read this viewer and the
836
861
  server's Effect `Clock` (`exprContext`).
837
862
 
863
+ The viewer is also whom every answer says it is for. A read's, a list's and a
864
+ mutation's result carry `principal`: the viewer's key (`'User:ada'`), or
865
+ `null` for a visitor. The client treats it as opaque, stamps each durable
866
+ write it queues with it, and sends it back with every send of that write. The
867
+ handlers compare it with whom they answer as before the mutation's Source
868
+ runs: another person is refused with `RemotePrincipalChanged` (a 409 over
869
+ JSON), a visitor with `Unauthenticated`, and nothing runs, a ledger's replay
870
+ included, so a write resent after the cookie changed hands is never run, or
871
+ answered from its record, as someone else. A write that names `null` (made
872
+ with no one signed in) runs only for a visitor; asked by someone signed in it
873
+ is refused with `RemotePrincipalChanged`, unrun. A write that names no one
874
+ (made before any answer said who) runs as whoever asks.
875
+ A server with no `viewer` keeps no keys: its answers carry no `principal`, and
876
+ it refuses a write that names one, which it cannot check.
877
+
838
878
  Then compile it into handlers, once per principal, or once for every request
839
879
  with a Context key as the principal (see Authentication vs authorization):
840
880
 
@@ -887,7 +927,13 @@ The handler applies bounded, protocol-level safeguards before or around Sources:
887
927
 
888
928
  - a read batch may name at most `maxIdsPerEntity` distinct ids for one Entity
889
929
  (default `1000`); oversized client batches fail rather than loading unbounded
890
- rows;
930
+ rows. Remote's client cuts its batches to the same default, and to the
931
+ number given in `Remote.clientLayer(…, { maxIdsPerEntity })`;
932
+ - a request body may be at most `maxBodyBytes` (default 1 MiB) where bytes are
933
+ read: `serveFetch`'s option, and `bodyLimit` in front of an `RpcServer`
934
+ route. A larger one is a 413, `{ error, tooLarge: { limit } }`, refused by
935
+ its `content-length` before anything else, or cancelled the moment the bytes
936
+ read pass the limit, and never decoded;
891
937
  - nested resolution is bounded by `maxDepth` (default `8`);
892
938
  - the wire decoder also rejects a selection deeper than
893
939
  `MAX_RELATION_DEPTH` (`8`) or more than `MAX_FIELDS_PER_REQUEST` (`256`)
@@ -909,7 +955,7 @@ pages of one relation than a read may ask, fails the stream with
909
955
  lists fails the wire decoder before that. That matters most for a polling
910
956
  Source such as `pollLive`, which re-reads every subscribed row each tick. A
911
957
  refusal is not truncation: the client does not reconnect it, and
912
- `Data.liveStatus` reads `Refused`. A hand-written live Source can rely on what
958
+ `liveStatus(Data, …)` reads `Refused`. A hand-written live Source can rely on what
913
959
  it is given having passed, and is responsible for any further bounds its
914
960
  backend needs.
915
961
 
@@ -1080,6 +1126,10 @@ const route = async (request: Request): Promise<Response> => {
1080
1126
  this (`RemoteServer.forbid`).
1081
1127
  - **409** with `{ error, refusal }`: a declared insert's id is already a
1082
1128
  row's, refused as `Refusal.taken`.
1129
+ - **409** with `{ error, principalChanged: {} }`: the write names someone
1130
+ other than who asks (`RemotePrincipalChanged`). Nothing ran. The client
1131
+ fails it with `_tag: 'PrincipalChanged'`, and the outbox keeps it waiting
1132
+ for them.
1083
1133
  - **422** with `{ error, refusal }`: the mutation refused what was asked, in
1084
1134
  its own `Refusal`.
1085
1135
  - **500** with `{ error }`: the handler failed, and the message is its own;
@@ -1098,6 +1148,33 @@ It binds no principal: pass the `handlers` for the request's own,
1098
1148
  established by your authentication, as everywhere else. It carries no live
1099
1149
  data.
1100
1150
 
1151
+ For an endpoint that serves `RemoteRpc` through Effect's own `RpcServer`,
1152
+ `bodyLimit(maxBytes)` is the same limit as HTTP middleware (Effect's
1153
+ `MaxBodySize` fails the RPC body read as a defect, a 500):
1154
+
1155
+ ```ts
1156
+ import { Layer } from 'effect'
1157
+ import { HttpRouter } from 'effect/http'
1158
+ import { RpcSerialization, RpcServer } from 'effect/rpc'
1159
+ import { RemoteRpc } from 'foldkit-remote'
1160
+ import { RemoteServer, bodyLimit } from 'foldkit-remote-server'
1161
+
1162
+ // `server` is your RemoteServer.make; answered as an anonymous principal here.
1163
+ const RpcRoutes = RpcServer.layer(RemoteRpc).pipe(
1164
+ Layer.provide(RemoteRpc.toLayer(RemoteServer.handlers(server, 'anonymous'))),
1165
+ Layer.provide(RpcServer.layerProtocolHttp({ path: '/rpc' })),
1166
+ Layer.provide(RpcSerialization.layerJson),
1167
+ Layer.provide(HttpRouter.middleware(bodyLimit(64 * 1024)).layer),
1168
+ )
1169
+ ```
1170
+
1171
+ The client reads that 413 as the call's own error, and a 401 or 403 from
1172
+ session middleware in front of the route as `Unauthenticated` or `Forbidden`,
1173
+ only over `Remote.rpcProtocolHttp(url)` in place of
1174
+ `RpcClient.layerProtocolHttp({ url })`, which reads the refusal as RPC frames
1175
+ and loses its status: a durable write would then read as unreachable and be
1176
+ sent again for good.
1177
+
1101
1178
  ## Over fetch (Workers)
1102
1179
 
1103
1180
  `serveFetch` from `foldkit-remote-server/fetch` is that route as a value: a
@@ -1122,8 +1199,14 @@ export default {
1122
1199
  ```
1123
1200
 
1124
1201
  Only `POST`s to `path` (default `/remote`) are answered; anything else is a
1125
- 404. A body that is not JSON, or not a request, is a 400 that reaches no
1126
- handler; a handler's failure a 500 with its message. Every response, refusals
1202
+ 404. A body larger than `maxBodyBytes` (default 1 MiB) is a 413 with
1203
+ `{ error, tooLarge: { limit } }`: one whose `content-length` says so before
1204
+ the layer is built or the principal resolved, any other once the bytes read
1205
+ pass the limit, its stream cancelled there. Give the client the same number
1206
+ (`Remote.clientLayer(Remote.http('/remote'), { maxBodyBytes })`) and it cuts its
1207
+ reads to fit; `Remote.http` reads a 413 as the call's own error, so a durable
1208
+ write is not resent. A body that is not UTF-8 JSON, or not a request, is a 400
1209
+ that reaches no handler; a handler's failure a 500 with its message. Every response, refusals
1127
1210
  and errors included, says `cache-control: no-store` unless `headers` gives a
1128
1211
  `cache-control` of its own: each answer is one principal's rows (and `may`), so
1129
1212
  no shared cache may keep one.
@@ -1154,7 +1237,7 @@ A body that opens live (`{ operation: 'live', payload }`) is answered with
1154
1237
  the stream as `text/event-stream`: one `data:` frame per `LiveChange`, then
1155
1238
  a terminal `event: error` frame carrying the failure's message when the
1156
1239
  stream fails rather than ends. A payload no live stream speaks is a 400 that
1157
- subscribes to nothing. `Remote.httpWithLive` is the other end; a client that
1240
+ subscribes to nothing. `httpWithLive` (`foldkit-remote/live`) is the other end; a client that
1158
1241
  disconnects interrupts the subscription, as closing the RPC stream would.
1159
1242
 
1160
1243
  The stream moves on its own even when nothing changes: a `: ping` comment opens
package/dist/fetch.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { k as ServerDefinition, s as LiveHub } from "./index-BnaRbvjr.mjs";
1
+ import { j as ServerDefinition, l as LiveHub } from "./index-B85UhEfk.mjs";
2
2
  import { Duration, Effect, Layer } from "effect";
3
3
  import { Diagnostic, RemoteClient, RemoteUnauthenticated } from "foldkit-remote";
4
4
  /** What `serveFetch` needs of the host runtime, per request. */
@@ -57,6 +57,14 @@ export interface FetchConfig<P, R, Env, RP = never> {
57
57
  readonly maxIdsPerEntity?: number | undefined;
58
58
  /** A nested selection may not reach further than this many levels; default 8. */
59
59
  readonly maxDepth?: number | undefined;
60
+ /**
61
+ * A request body may not be larger than this many bytes; default 1 MiB. A
62
+ * larger one is a 413 with Remote's `tooLarge` answer, refused before it is
63
+ * decoded: by its `content-length` before the principal is resolved, or
64
+ * once the bytes read pass the limit. Give the client the same number
65
+ * (`Remote.clientLayer(…, { maxBodyBytes })`), so it cuts its reads to fit.
66
+ */
67
+ readonly maxBodyBytes?: number | undefined;
60
68
  }
61
69
  /**
62
70
  * Answers Remote `POST`s with `Response`s: what a Worker's `fetch` hands to
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;iBA2CiB,YAAY,GAAG,GAAG,KAAK;;WAE7B,QAAQ,iBAAiB,GAAG;;;;;;WAM5B,mBACP,SAAS,SACT,KAAK,QACF,OAAO,OAAO,GAAG,uBAAuB;;;;;;WAMpC,QAAQ,KAAK,QAAQ,MAAM,MAAM,IAAI;;WAErC;;;;;;;WAOA,YAAY,WAAW,MAAM,SAAS;;WAEtC,OAAO,QAAQ,GAAG;;;;;;;;;;;;WAYlB;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,gBAAgB,SAAS;;;;;;;;WAQzB,gBACH,YAAY,YAAY,SAAS,YAAY,OAAO;;WAGjD;;WAEA;;;;;;;;;;;;;;;;;;;;;;;;;qBAsJE,aAAc,GAAG,GAAG,KAAK,YAAU,QACtC,YAAY,GAAG,GAAG,KAAK,UAC5B,SAAS,SAAS,KAAK,QAAQ,QAAQ;;YA0HhC,iBAAiB,GAAG,GAAG,KAAK,cAAc,KACpD,YAAY,GAAG,GAAG,KAAK;;;;;;;;;;;;;;;qBAkBZ,aACV,GAAG,GAAG,KAAK,YAAU,QAAU,iBAAiB,GAAG,GAAG,KAAK,SAAG,SACrD,SAAO,KAAO,QAAM,MAAM,MAAM,cAAc"}
1
+ {"version":3,"file":"fetch.d.mts","names":[],"sources":["../src/fetch.ts"],"mappings":";;;;iBA6CiB,YAAY,GAAG,GAAG,KAAK;;WAE7B,QAAQ,iBAAiB,GAAG;;;;;;WAM5B,mBACP,SAAS,SACT,KAAK,QACF,OAAO,OAAO,GAAG,uBAAuB;;;;;;WAMpC,QAAQ,KAAK,QAAQ,MAAM,MAAM,IAAI;;WAErC;;;;;;;WAOA,YAAY,WAAW,MAAM,SAAS;;WAEtC,OAAO,QAAQ,GAAG;;;;;;;;;;;;WAYlB;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,gBAAgB,SAAS;;;;;;;;WAQzB,gBACH,YAAY,YAAY,SAAS,YAAY,OAAO;;WAGjD;;WAEA;;;;;;;;WAQA;;;;;;;;;;;;;;;;;;;;;;;;;qBAsJE,aAAc,GAAG,GAAG,KAAK,YAAU,QACtC,YAAY,GAAG,GAAG,KAAK,UAC5B,SAAS,SAAS,KAAK,QAAQ,QAAQ;;YA6HhC,iBAAiB,GAAG,GAAG,KAAK,cAAc,KACpD,YAAY,GAAG,GAAG,KAAK;;;;;;;;;;;;;;;qBAkBZ,aACV,GAAG,GAAG,KAAK,YAAU,QAAU,iBAAiB,GAAG,GAAG,KAAK,SAAG,SACrD,SAAO,KAAO,QAAM,MAAM,MAAM,cAAc"}
package/dist/fetch.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { 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 { d as declaresTooLarge, f as readJson, i as RemoteServer, p as tooLargeAnswer, v as unauthenticatedAnswer, y as serverDefect } from "./src-D8azLxgd.mjs";
2
+ import { Cause, Deferred, Duration, Effect, Exit, Layer, Result, Schedule, Schema, Scope, Stream } from "effect";
3
+ import { DEFAULT_MAX_BODY_BYTES, Diagnostics, LiveRequirement, Remote, RemoteLiveError, RemoteMutationError } from "foldkit-remote";
4
4
  // src/fetch.ts
5
5
  /**
6
6
  * `foldkit-remote-server/fetch`: `RemoteServer` over the Fetch API, for
@@ -10,7 +10,7 @@ import { Diagnostics, LiveRequirement, Remote, RemoteLiveError, RemoteMutationEr
10
10
  * them and `RemoteServer.answer` answers them. Live requirements ride one
11
11
  * `POST` that answers with a `text/event-stream` of `LiveChange` frames, one
12
12
  * `data:` frame per change and a terminal `event: error` frame when the
13
- * stream fails; `Remote.httpWithLive` is the other end. The principal is
13
+ * stream fails; `httpWithLive` (`foldkit-remote/live`) is the other end. The principal is
14
14
  * resolved per request, from whatever the runtime hands over (a header, a
15
15
  * binding, a session), and the Sources' requirements are provided per
16
16
  * request from the environment (a D1 binding, a connection string).
@@ -103,6 +103,7 @@ const liveResponse = (handlers, payload, heartbeat, checked, release, headers) =
103
103
  */
104
104
  const serveFetch = (config) => {
105
105
  const path = config.path ?? "/remote";
106
+ const maxBodyBytes = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
106
107
  const heartbeat = config.liveHeartbeat ?? DEFAULT_HEARTBEAT;
107
108
  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
109
  /** `effect` reporting to `config.diagnostics` with `request`, when it is given. */
@@ -120,27 +121,30 @@ const serveFetch = (config) => {
120
121
  const respond = (request, env, scope) => Effect.gen(function* () {
121
122
  const principal = yield* config.resolvePrincipal(request, env);
122
123
  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
- };
124
+ const body = yield* Effect.result(readJson(request, maxBodyBytes));
125
+ if (Result.isFailure(body)) {
126
+ const { status, answer } = body.failure;
127
+ return {
128
+ response: Response.json(answer, {
129
+ status,
130
+ headers
131
+ }),
132
+ live: false
133
+ };
134
+ }
131
135
  const handlers = RemoteServer.handlers(config.server, principal, {
132
136
  live: config.live,
133
137
  maxIdsPerEntity: config.maxIdsPerEntity,
134
138
  maxDepth: config.maxDepth
135
139
  });
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);
140
+ if (isLiveOpen(body.success)) {
141
+ const response = yield* liveResponse(handlers, body.success.payload, heartbeat, revalidation(request, env, principal), Scope.close(scope, Exit.void), headers);
138
142
  return {
139
143
  response,
140
144
  live: response.status === 200
141
145
  };
142
146
  }
143
- const answered = yield* RemoteServer.answer(handlers, body.value);
147
+ const answered = yield* RemoteServer.answer(handlers, body.success);
144
148
  return {
145
149
  response: Response.json(answered.body, {
146
150
  status: answered.status,
@@ -157,6 +161,7 @@ const serveFetch = (config) => {
157
161
  }));
158
162
  const served = async (request, env) => {
159
163
  if (request.method !== "POST" || new URL(request.url).pathname !== path) return Response.json({ error: "not found" }, { status: 404 });
164
+ if (declaresTooLarge(request, maxBodyBytes)) return Response.json(tooLargeAnswer(maxBodyBytes), { status: 413 });
160
165
  const exit = await Effect.runPromiseExit(Effect.gen(function* () {
161
166
  const scope = yield* Scope.make();
162
167
  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;
@@ -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.provide(config.layer(env)))\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4GA,MAAM,mBAAmB,OAAO,OAAO;CACrC,WAAW,OAAO,QAAQ,MAAM;CAChC,SAAS,OAAO;AAClB,CAAC;;;;;AAMD,MAAM,cACJ,SACA,UAAkE,CAAC,MACxD,uBAAuB,KAAK,UAAU;CAAE;CAAS,GAAG;AAAQ,CAAC,EAAE;;;;;;;;;;;AAY5E,MAAM,aACJ,U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AAoB,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/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;;;;;;;;;;;AAY5E,MAAM,aACJ,UACA,SACA,WACA,YAEA,OAAO,OACL,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,SAAS,KAAW;CAEzC,MAAM,SAAS,OAAO,MAAM,SAAS,kBAAkB,OAAO,GAAG,SAAS,EACxE,cAAc,OAChB,CAAC,CAAC,CAAC,KACD,OAAO,KAAI,WAAU,SAAS,KAAK,UAAU,MAAM,EAAE,KAAK,GAC1D,OAAO,UAAU;EACf,kBAAiB,UAAS,OAAO,QAAQ,WAAW,MAAM,OAAO,CAAC;EAElE,oBAAmB,UAAS,OA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AAC"}
@@ -1,12 +1,30 @@
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
3
  import { Boundary, ConnectionChangeSchema, ConnectionIdentity, ConnectionSpec, Diagnostic, LiveChange, MutationDescriptor, NormalizedPatch, QueryDescriptor, QueryWindow, RelationRequirement, RemoteClient, RemoteDescriptor, RemoteForbidden, RemoteJsonAnswer, RemoteReadError, RemoteRpcClient, RemoteUnauthenticated, Requirement } from "foldkit-remote";
4
+ import { HttpServerRequest, HttpServerResponse } from "effect/http";
5
+ /**
6
+ * Effect HTTP middleware refusing a request body over `maxBytes` (default
7
+ * 1 MiB, `serveFetch`'s) with a 413 and Remote's `tooLarge` answer, before
8
+ * the endpoint reads it. For an endpoint that serves `RemoteRpc` through
9
+ * `RpcServer`, where Effect's own `MaxBodySize` fails the body read as a
10
+ * defect, a 500:
11
+ *
12
+ * ```ts
13
+ * HttpRouter.add('POST', '/rpc', bodyLimit(64 * 1024)(rpcHttpEffect))
14
+ * ```
15
+ *
16
+ * A body within the limit reaches the endpoint whole, read once.
17
+ */
18
+ declare const bodyLimit: (maxBytes?: number) => <E, R>(endpoint: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R | HttpServerRequest.HttpServerRequest>;
4
19
  /** A failure on this side, answered "Internal error"; the caller is told nothing of it. */
5
20
  interface ServerDefect extends Diagnostic {
6
21
  readonly _tag: 'ServerDefect';
7
22
  readonly cause: Cause.Cause<unknown>;
8
23
  }
9
- /** A mutation that committed, answered without the read of the rows it names: the client reads them again. */
24
+ /**
25
+ * A mutation that committed, answered without the read of the rows it names or
26
+ * of a list it was asked for: the client reads them again.
27
+ */
10
28
  interface AnswerUnread extends Diagnostic {
11
29
  readonly _tag: 'AnswerUnread';
12
30
  readonly mutation: string;
@@ -200,6 +218,34 @@ interface WriteRequirement {
200
218
  readonly holds: RowRequirement;
201
219
  readonly reason: Option.Option<string>;
202
220
  }
221
+ /** A row a delete removed with the row it was asked to delete (`onDelete: 'cascade'`). */
222
+ interface CascadedRow {
223
+ readonly entity: string;
224
+ readonly id: string;
225
+ /** Each `one` relation it pointed, by key: what the answer re-reads (the counts it moved). */
226
+ readonly links: Readonly<Record<string, Option.Option<EntityRef>>>;
227
+ }
228
+ /**
229
+ * What a writer's `delete` did. `Deleted`: the row is gone, with `cascaded`,
230
+ * the rows declared to go with it (`Relation.one(…, { onDelete: 'cascade' })`)
231
+ * that the principal may see. `Absent`: no row, so nothing to delete (a
232
+ * retry's case). `Moved`: the row is there at another revision, and stays.
233
+ */
234
+ type DeleteOutcome = Data.TaggedEnum<{
235
+ Deleted: {
236
+ readonly cascaded: ReadonlyArray<CascadedRow>;
237
+ };
238
+ Absent: {};
239
+ Moved: {};
240
+ }>;
241
+ declare const DeleteOutcome: Data.TaggedEnum.Constructor<{
242
+ readonly _tag: "Absent";
243
+ } | {
244
+ readonly _tag: "Deleted";
245
+ readonly cascaded: ReadonlyArray<CascadedRow>;
246
+ } | {
247
+ readonly _tag: "Moved";
248
+ }>;
203
249
  interface EntityWriter<P, R = never> {
204
250
  readonly entity: string;
205
251
  /**
@@ -263,6 +309,13 @@ interface EntityWriter<P, R = never> {
263
309
  * a writer without it.
264
310
  */
265
311
  readonly invariants?: true;
312
+ /**
313
+ * Whether `delete` removes, in the transaction that deletes the row, every
314
+ * row declared to go with it (`Entity.cascading`), and answers them as
315
+ * `cascaded`. `RemoteServer.write` refuses a delete of an Entity that
316
+ * cascades through a writer without it.
317
+ */
318
+ readonly cascades?: true;
266
319
  /**
267
320
  * Why this writer cannot land `write`, each a sentence; none when it can.
268
321
  * `RemoteServer.write` asks once, where the write is registered, for what
@@ -318,7 +371,7 @@ interface EntityWriter<P, R = never> {
318
371
  /** What the row must hold, judged where it is written; only a writer with `requires` is given one. */
319
372
  readonly requires?: WriteRequirement | undefined;
320
373
  readonly principal: P;
321
- }) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError | RemoteForbidden | RemoteUnmet | RemoteInvalid, R>;
374
+ }) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError | RemoteForbidden | RemoteUnauthenticated | RemoteUnmet | RemoteInvalid, R>;
322
375
  /**
323
376
  * Inserts the row and answers it. An id already taken fails with
324
377
  * `RemoteTaken`, whatever the row there holds and whether its asker may see
@@ -339,11 +392,11 @@ interface EntityWriter<P, R = never> {
339
392
  readonly values: Readonly<Record<string, unknown>>;
340
393
  readonly links: Readonly<Record<string, Option.Option<EntityRef>>>;
341
394
  readonly principal: P;
342
- }) => Effect.Effect<Readonly<Record<string, unknown>>, RemoteServerError | RemoteForbidden | RemoteInvalid | RemoteTaken, R>;
395
+ }) => Effect.Effect<Readonly<Record<string, unknown>>, RemoteServerError | RemoteForbidden | RemoteUnauthenticated | RemoteInvalid | RemoteTaken, R>;
343
396
  /**
344
- * Deletes the row, while it is still at the revision when one is expected:
345
- * `deleted`, `absent` (no row, so nothing to delete; a retry's case), or
346
- * `moved` (the row is there at another revision, and stays).
397
+ * Deletes the row, while it is still at the revision when one is expected,
398
+ * and, when it `cascades`, the rows declared to go with it, in the same
399
+ * transaction: a `DeleteOutcome`.
347
400
  */
348
401
  readonly delete: (context: {
349
402
  readonly id: string;
@@ -355,7 +408,7 @@ interface EntityWriter<P, R = never> {
355
408
  /** What the row must hold, judged where it is deleted; only a writer with `requires` is given one. */
356
409
  readonly requires?: WriteRequirement | undefined;
357
410
  readonly principal: P;
358
- }) => Effect.Effect<'deleted' | 'absent' | 'moved', RemoteServerError | RemoteForbidden | RemoteUnmet, R>;
411
+ }) => Effect.Effect<DeleteOutcome, RemoteServerError | RemoteForbidden | RemoteUnauthenticated | RemoteUnmet, R>;
359
412
  /**
360
413
  * The row as `principal` may see it, under the read rule its Source applies:
361
414
  * none when there is no such row, or it is hidden. Given, a write's answer
@@ -466,7 +519,7 @@ interface MutationSource<P, R = never> {
466
519
  readonly entity: string;
467
520
  readonly id: string;
468
521
  }>;
469
- }, RemoteServerError | MutationRefused | RemoteForbidden, R>;
522
+ }, RemoteServerError | MutationRefused | RemoteForbidden | RemoteUnauthenticated, R>;
470
523
  }
471
524
  interface QueryPage {
472
525
  readonly edges: ReadonlyArray<{
@@ -500,7 +553,7 @@ interface QuerySource<P, R = never> {
500
553
  readonly visible?: unknown;
501
554
  }
502
555
  /**
503
- * A list a subscriber reads live (`Data.query(…, { live: true })`), admitted
556
+ * A list a subscriber reads live (`liveQuery(Data, …)`), admitted
504
557
  * and resolved by `handlers`: what a live source diffs to tell a row that
505
558
  * joins, changes or leaves it.
506
559
  */
@@ -771,7 +824,7 @@ declare const RemoteServer: {
771
824
  readonly operation: Option.Option<string>;
772
825
  /** The write's time: the client's within the server's `clockSkew`, or its own; see `MutationSource`. */
773
826
  readonly now: number;
774
- }) => Effect.Effect<MutationOutcome<Output>, RemoteServerError | MutationRefused | RemoteForbidden, R>) => MutationSource<P, R>;
827
+ }) => Effect.Effect<MutationOutcome<Output>, RemoteServerError | MutationRefused | RemoteForbidden | RemoteUnauthenticated, R>) => MutationSource<P, R>;
775
828
  /**
776
829
  * A refusal of `mutation`, as a value of its declared `Refusal`: fail a
777
830
  * Source with it (`yield* RemoteServer.refuse(SavePost, { _tag: 'Field', ... })`)
@@ -809,8 +862,10 @@ declare const RemoteServer: {
809
862
  /**
810
863
  * A refusal of a caller who could not be told: a `serveFetch` or
811
864
  * `defineDocumentHost` resolver fails with it (`RemoteServer.unauthenticated()`)
812
- * when the credential it was sent no longer holds. It answers 401, with
813
- * `reason`, when given, for the person who asked.
865
+ * when the credential it was sent no longer holds, and a write refused to a
866
+ * visitor fails with it (`GuardServer` does), so a client can tell a session
867
+ * that ended from a refusal. It answers 401, with `reason`, when given, for
868
+ * the person who asked; a durable write so answered waits for a sign-in.
814
869
  */
815
870
  unauthenticated: (reason?: string) => RemoteUnauthenticated;
816
871
  /**
@@ -868,7 +923,12 @@ declare const RemoteServer: {
868
923
  * The server: its sources by name. `viewer` says who asks, as a row
869
924
  * (`principal => Option.some(Remote.ref(User, principal.id))`), or none for
870
925
  * a visitor: what a declared write's `Expr.viewer` sets. A server
871
- * registering such an insert without one is refused here.
926
+ * registering such an insert without one is refused here. It is also whom
927
+ * each answer says it is for (`principal`, the row's key), which a durable
928
+ * write carries back: one made for another viewer than who asks is refused
929
+ * before it runs (`RemotePrincipalChanged`). A server without `viewer`
930
+ * names no one in its answers, and refuses a write that names someone,
931
+ * since it cannot check it; a write that names no one runs (#405).
872
932
  *
873
933
  * `clockSkew` is how far from this server's clock a client's time (the
874
934
  * `now` a write is sent with, when the reader acted) may be and still be
@@ -914,7 +974,8 @@ declare const RemoteServer: {
914
974
  * The request and its payload are decoded by the protocol's own schemas
915
975
  * before a handler sees them, so an operation name is one of Remote's three
916
976
  * and nothing else. A body that is not a request is a 400; a caller who
917
- * could not be told a 401; a refusal of who is asking a 403; a mutation's
977
+ * could not be told a 401; a refusal of who is asking a 403; a write made
978
+ * for someone else (`RemotePrincipalChanged`) a 409; a mutation's
918
979
  * declared refusal a 422, or a 409 when it is `Refusal.taken`; a handler's
919
980
  * failure a 500 with its message; a defect a 500 that says nothing of it,
920
981
  * its cause reported as a `ServerDefect` (`Diagnostics`, by default the log).
@@ -933,5 +994,5 @@ declare const RemoteServer: {
933
994
  */
934
995
  handlers: <P, R, I = never>(server: ServerDefinition<P, R>, principal: P | Context.Key<I, P>, options?: HandlerOptions<P, R>) => RemoteRpcClient<R | I>;
935
996
  };
936
- export { WriteRequirement as A, assertSupported$1 as B, RemoteInvalid as C, RemoteUnmet as D, RemoteTaken as E, PublishFailed as F, supported as H, RemoteServerDiagnostic as I, ServerDefect as L, exprContext as M, AnswerUnread as N, RowRequirement as O, ClockSkewed as P, QueryEvaluateError as R, ReadPlan as S, RemoteServerError as T, evaluate$1 as V, MutationOutcome as _, EntityWriter as a, QueryPage as b, LiveQuery as c, MemoryBackend as d, MemoryConfig as f, MemoryStore as g, MemoryServed as h, EntitySourceContext as i, WriteWhen as j, ServerDefinition as k, LiveSource as l, MemoryRows as m, EntityRecord as n, HandlerOptions as o, MemoryReadable as p, EntitySource as r, LiveHub as s, ConnectionChange as t, MemoryAnswering as u, MutationRefused as v, RemoteServer as w, QuerySource as x, MutationSource as y, Row as z };
937
- //# sourceMappingURL=index-BnaRbvjr.d.mts.map
997
+ export { RowRequirement as A, bodyLimit as B, QuerySource as C, RemoteServerError as D, RemoteServer as E, AnswerUnread as F, supported as G, Row as H, ClockSkewed as I, PublishFailed as L, WriteRequirement as M, WriteWhen as N, RemoteTaken as O, exprContext as P, RemoteServerDiagnostic as R, QueryPage as S, RemoteInvalid as T, assertSupported$1 as U, QueryEvaluateError as V, evaluate$1 as W, MemoryServed as _, EntitySource as a, MutationRefused as b, HandlerOptions as c, LiveSource as d, MemoryAnswering as f, MemoryRows as g, MemoryReadable as h, EntityRecord as i, ServerDefinition as j, RemoteUnmet as k, LiveHub as l, MemoryConfig as m, ConnectionChange as n, EntitySourceContext as o, MemoryBackend as p, DeleteOutcome as r, EntityWriter as s, CascadedRow as t, LiveQuery as u, MemoryStore as v, ReadPlan as w, MutationSource as x, MutationOutcome as y, ServerDefect as z };
998
+ //# sourceMappingURL=index-B85UhEfk.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-B85UhEfk.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;WAC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1,2 +1,2 @@
1
- import { A as WriteRequirement, B as assertSupported, C as RemoteInvalid, D as RemoteUnmet, E as RemoteTaken, F as PublishFailed, H as supported, I as RemoteServerDiagnostic, L as ServerDefect, M as exprContext, N as AnswerUnread, O as RowRequirement, P as ClockSkewed, R as QueryEvaluateError, S as ReadPlan, T as RemoteServerError, V as evaluate, _ as MutationOutcome, a as EntityWriter, b as QueryPage, c as LiveQuery, d as MemoryBackend, f as MemoryConfig, g as MemoryStore, h as MemoryServed, i as EntitySourceContext, j as WriteWhen, k as ServerDefinition, l as LiveSource, m as MemoryRows, n as EntityRecord, o as HandlerOptions, p as MemoryReadable, r as EntitySource, s as LiveHub, t as ConnectionChange, u as MemoryAnswering, v as MutationRefused, w as RemoteServer, x as QuerySource, y as MutationSource, z as Row } from "./index-BnaRbvjr.mjs";
2
- export { type AnswerUnread, type ClockSkewed, ConnectionChange, 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, evaluate, exprContext, supported };
1
+ import { A as RowRequirement, B as bodyLimit, C as QuerySource, D as RemoteServerError, E as RemoteServer, F as AnswerUnread, G as supported, H as Row, I as ClockSkewed, L as PublishFailed, M as WriteRequirement, N as WriteWhen, O as RemoteTaken, P as exprContext, R as RemoteServerDiagnostic, S as QueryPage, T as RemoteInvalid, U as assertSupported, V as QueryEvaluateError, W as evaluate, _ as MemoryServed, a as EntitySource, b as MutationRefused, c as HandlerOptions, d as LiveSource, f as MemoryAnswering, g as MemoryRows, h as MemoryReadable, i as EntityRecord, j as ServerDefinition, k as RemoteUnmet, l as LiveHub, m as MemoryConfig, n as ConnectionChange, o as EntitySourceContext, p as MemoryBackend, r as DeleteOutcome, s as EntityWriter, t as CascadedRow, u as LiveQuery, v as MemoryStore, w as ReadPlan, x as MutationSource, y as MutationOutcome, z as ServerDefect } from "./index-B85UhEfk.mjs";
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 };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export { t as MutationRefused, l as QueryEvaluateError, n as RemoteInvalid, r as RemoteServer, i as RemoteServerError, a as RemoteTaken, o as RemoteUnmet, s as RowRequirement, u as assertSupported, d as evaluate, c as exprContext, f as supported } from "./src-ZV9pARkU.mjs";
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-D8azLxgd.mjs";