foldkit-remote 0.11.0 → 0.13.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.
@@ -0,0 +1,3531 @@
1
+ import { Context, Duration, Effect, Layer, Option, Result, Schema, Stream } from "effect";
2
+ import * as Domain from "foldkit-entity";
3
+ import { AnyEntity, AnyQuery, Dependencies, InputExpr, Query } from "foldkit-entity";
4
+ import { Command } from "foldkit/command";
5
+ import { EntryWithoutKeepAlive } from "foldkit/subscription";
6
+ import { ActiveSurface, Contract, Invalid, Metadata, ModelRef, Projection, Surface, Wiring } from "foldkit-surface";
7
+ import { Rpc, RpcClientError, RpcGroup } from "effect/rpc";
8
+ import { KeyValueStore } from "effect/persistence";
9
+ import * as Update from "foldkit/update";
10
+ //#region ../metadata/src/index.d.ts
11
+ /** Marks a `Metadata` value. Its entries are private to this module. */
12
+ declare const MetadataTypeId: unique symbol;
13
+ type MetadataTypeId = typeof MetadataTypeId;
14
+ /**
15
+ * Declarative facts an interpreter attaches to a node it does not own, such as
16
+ * the server data a Remote selection needs. The carrier holds and combines
17
+ * them without knowing what they mean; a package reads only the key it owns.
18
+ *
19
+ * Opaque: only a key's `of` and `Metadata.combine` make one, so entries cannot
20
+ * be forged past a key's type or `merge`, and they are frozen.
21
+ */
22
+ interface Metadata$1 {
23
+ readonly [MetadataTypeId]: MetadataTypeId;
24
+ }
25
+ /**
26
+ * An interpreter's typed slot in `Metadata`. Lookup is by the key object, never
27
+ * its `name`, so two packages cannot collide by choosing the same string.
28
+ */
29
+ interface MetadataKey<A> {
30
+ /** For tooling output only. */
31
+ readonly name: string;
32
+ /** Normalizes the entries gathered from combined values, e.g. unioning duplicates. */
33
+ readonly merge: (values: ReadonlyArray<A>) => ReadonlyArray<A>;
34
+ /** One line per entry for tooling output. */
35
+ readonly summarize: (value: A) => string;
36
+ readonly of: (...values: ReadonlyArray<A>) => Metadata$1;
37
+ readonly get: (metadata: Metadata$1) => ReadonlyArray<A>;
38
+ }
39
+ /** One key's entries as serializable text, named by the key. */
40
+ interface MetadataSummary {
41
+ readonly name: string;
42
+ readonly entries: readonly string[];
43
+ }
44
+ declare const Metadata$1: {
45
+ /**
46
+ * Declares an interpreter's slot. Call once per package, at module level:
47
+ * entries are found by the key object, so two copies of a package (a
48
+ * duplicated install, a reloaded module) do not see each other's entries.
49
+ */
50
+ key: <A>(name: string, options: {
51
+ readonly merge: (values: ReadonlyArray<A>) => ReadonlyArray<A>;
52
+ readonly summarize: (value: A) => string;
53
+ }) => MetadataKey<A>;
54
+ empty: Metadata$1;
55
+ /** True only for a value this module made; a copy or a hand-built brand is not one. */
56
+ is: (value: unknown) => value is Metadata$1;
57
+ /** Gathers every part's entries and runs each key's `merge` over its group. */
58
+ combine: (parts: ReadonlyArray<Metadata$1>) => Metadata$1;
59
+ summarize: (metadata: Metadata$1) => readonly MetadataSummary[];
60
+ };
61
+ //#endregion
62
+ //#region src/connection.d.ts
63
+ interface EdgeRef {
64
+ readonly entity: string;
65
+ readonly id: string;
66
+ }
67
+ /** `key` is the edge identity used for de-duplication. */
68
+ interface Edge {
69
+ readonly key: string;
70
+ readonly ref: EdgeRef;
71
+ }
72
+ declare const edge: (ref: EdgeRef, key?: string) => Edge;
73
+ type Cursor = string;
74
+ type Boundary = {
75
+ readonly _tag: 'Terminal';
76
+ } | {
77
+ readonly _tag: 'Cursor';
78
+ readonly cursor: Cursor;
79
+ } | {
80
+ readonly _tag: 'Unknown';
81
+ };
82
+ declare const terminal: Boundary;
83
+ declare const unknown: Boundary;
84
+ declare const cursor: (value: Cursor) => Boundary;
85
+ interface Segment {
86
+ readonly edges: readonly Edge[];
87
+ readonly start: Boundary;
88
+ readonly end: Boundary;
89
+ }
90
+ interface Connection {
91
+ readonly segments: readonly Segment[];
92
+ readonly stale: boolean;
93
+ }
94
+ declare const emptyConnection: Connection;
95
+ declare const segment: (edges: readonly Edge[], start: Boundary, end: Boundary) => Segment;
96
+ /** Adds a page to the connection, joining contiguous or overlapping segments. */
97
+ declare const merge: (current: Connection, page: Segment) => Connection;
98
+ /** Visible edges, segment by segment. */
99
+ declare const items: (connection: Connection) => ReadonlyArray<Edge>;
100
+ /** There is more before the known region. Derived from boundaries, never row count. */
101
+ declare const hasPrevious: (connection: Connection) => boolean;
102
+ /** There is more after the known region. Derived from boundaries, never row count. */
103
+ declare const hasNext: (connection: Connection) => boolean;
104
+ /** A connection with more than one segment has an explicit unknown gap. */
105
+ declare const isGapped: (connection: Connection) => boolean;
106
+ //#endregion
107
+ //#region src/remoteData.d.ts
108
+ interface RemoteError {
109
+ readonly _tag: string;
110
+ readonly message: string;
111
+ }
112
+ type RemoteData<A> = {
113
+ readonly _tag: 'Initial';
114
+ } | {
115
+ readonly _tag: 'Loading';
116
+ } | {
117
+ readonly _tag: 'Ready';
118
+ readonly value: A;
119
+ } | {
120
+ readonly _tag: 'Refreshing';
121
+ readonly value: A;
122
+ } | {
123
+ readonly _tag: 'Failed';
124
+ readonly error: RemoteError;
125
+ readonly previous?: A;
126
+ } | {
127
+ readonly _tag: 'NotFound';
128
+ };
129
+ /**
130
+ * What `RemoteData.render` tells the `data` branch about the value it is
131
+ * given: whether a newer answer is on its way, and whether this one is what
132
+ * was last known good before a read failed. It is one tag rather than two
133
+ * booleans because a value cannot be both at once, and a type that can say so
134
+ * invites a view to handle a state that never arrives.
135
+ */
136
+ type Freshness = {
137
+ readonly _tag: 'Fresh';
138
+ } | {
139
+ readonly _tag: 'Refreshing';
140
+ } | {
141
+ readonly _tag: 'Stale';
142
+ readonly error: RemoteError;
143
+ };
144
+ declare const remoteErrorSchema: Schema.Struct<{
145
+ readonly _tag: Schema.String;
146
+ readonly message: Schema.String;
147
+ }>;
148
+ declare const remoteDataSchema: <A>(value: Schema.Schema<A>) => Schema.Codec<RemoteData<A>, unknown>;
149
+ declare const RemoteData: {
150
+ /**
151
+ * The `RemoteData` schema for a value schema. Exposed so a `RemoteData` can
152
+ * be embedded in a hand-written Model schema, not only through `Remote.select`.
153
+ */
154
+ schema: <A>(value: Schema.Schema<A>) => Schema.Schema<RemoteData<A>>;
155
+ /**
156
+ * Whether the read has an answer: `Ready`, `Refreshing`, `Failed` or
157
+ * `NotFound`. `Initial` and `Loading` are still waiting for one.
158
+ */
159
+ answered: <A>(data: RemoteData<A>) => boolean;
160
+ /** Exhaustive: omitting a state is a compile error. */
161
+ match: <A, R>(data: RemoteData<A>, cases: {
162
+ readonly Initial: () => R;
163
+ readonly Loading: () => R;
164
+ readonly Ready: (value: A) => R;
165
+ readonly Refreshing: (value: A) => R;
166
+ readonly Failed: (error: RemoteError, previous: Option.Option<A>) => R;
167
+ readonly NotFound: () => R;
168
+ }) => R;
169
+ /**
170
+ * The view-oriented fold: the six states as the three things a view actually
171
+ * draws, under the policy that useful data stays on screen. A value that is
172
+ * being refetched, or that a later read failed to replace, still reaches
173
+ * `data` — with `freshness` saying which — instead of being replaced by a
174
+ * spinner or an error the reader cannot act on.
175
+ *
176
+ * ```ts
177
+ * RemoteData.render(model.user, {
178
+ * loading: () => UserSkeleton(),
179
+ * notFound: () => NoSuchUser(),
180
+ * failed: error => ErrorView(error),
181
+ * data: (user, freshness) => UserView({ user, dimmed: freshness._tag !== 'Fresh' }),
182
+ * })
183
+ * ```
184
+ *
185
+ * `notFound` is its own branch and not optional: a row the server answered
186
+ * for and does not have is neither loading nor a failure, and drawing it as
187
+ * either is a spinner that never ends or an error nobody can fix.
188
+ *
189
+ * This does not replace `match`, which is the exhaustive fold over the states
190
+ * themselves. Reach for `match` when the six states really do draw
191
+ * differently, and for this when they draw the usual three ways.
192
+ */
193
+ render: <A, R>(data: RemoteData<A>, cases: {
194
+ readonly loading: () => R;
195
+ readonly notFound: () => R;
196
+ readonly failed: (error: RemoteError) => R;
197
+ readonly data: (value: A, freshness: Freshness) => R;
198
+ }) => R;
199
+ map: <A, B>(data: RemoteData<A>, f: (value: A) => B) => RemoteData<B>;
200
+ };
201
+ //#endregion
202
+ //#region src/store.d.ts
203
+ type EntityKey = string;
204
+ interface EntityEntry {
205
+ readonly values: Readonly<Record<string, unknown>>;
206
+ readonly present: ReadonlySet<string>;
207
+ /** Present fields whose value may be outdated (revalidation needed). */
208
+ readonly stale: ReadonlySet<string>;
209
+ /**
210
+ * Fields the server settled without a value: asked for, and answered without
211
+ * them, whatever the reason. Not planned again until a refresh asks; a later
212
+ * write of the field clears it.
213
+ */
214
+ readonly unavailable: ReadonlySet<string>;
215
+ /** The entity is known to be absent; a later write clears this. */
216
+ readonly tombstone: boolean;
217
+ /** Injected clock reading of the last write; never read from ambient state. */
218
+ readonly updatedAt: number;
219
+ /**
220
+ * The canonical window each present field was fetched with (`""` for none).
221
+ * A later request with a *known, different* window is planned as missing.
222
+ */
223
+ readonly windows: Readonly<Record<string, string>>;
224
+ }
225
+ type EntityStore = Readonly<Record<EntityKey, EntityEntry>>;
226
+ /** The separator keeps an untrusted id from colliding with a prototype key. */
227
+ declare const entityKey: (entity: string, id: string) => EntityKey;
228
+ declare const emptyStore: EntityStore;
229
+ interface EntityWrite {
230
+ readonly key: EntityKey;
231
+ readonly values: Readonly<Record<string, unknown>>;
232
+ /** The canonical window each written relation field was fetched with. */
233
+ readonly windows?: Readonly<Record<string, string>> | undefined;
234
+ /** When this write dates the entity, instead of the batch's `now`. */
235
+ readonly updatedAt?: number | undefined;
236
+ }
237
+ /**
238
+ * Merges known values into many entities, copying the store once. Every
239
+ * written field becomes present and non-stale; a tombstone is cleared because
240
+ * the entity is evidently not absent.
241
+ */
242
+ declare const writeEntities: (store: EntityStore, writes: ReadonlyArray<EntityWrite>, now?: number) => EntityStore;
243
+ /** `writeEntities` for one entity. */
244
+ declare const writeEntity: (store: EntityStore, key: EntityKey, values: Readonly<Record<string, unknown>>, now?: number, windows?: Readonly<Record<string, string>>) => EntityStore;
245
+ /**
246
+ * Marks present fields stale (`true`) or ends their staleness (`false`) across
247
+ * many entities, copying the store once. A field never present stays missing;
248
+ * an unknown entity is left alone.
249
+ */
250
+ declare const setStale: (store: EntityStore, marks: ReadonlyArray<readonly [key: EntityKey, fields: Iterable<string>]>, stale: boolean) => EntityStore;
251
+ /** Marks present fields stale; fields that were never present stay missing. */
252
+ declare const markStale: (store: EntityStore, key: EntityKey, fields: Iterable<string>) => EntityStore;
253
+ /** Ends a refresh that did not land: the fields are present again as they were. */
254
+ declare const clearStale: (store: EntityStore, key: EntityKey, fields: Iterable<string>) => EntityStore;
255
+ /**
256
+ * Records fields the server settled without a value. A present field is left
257
+ * as it is: the answer that settled it was not about the value it holds.
258
+ * `false` forgets the marks, which is how a refresh asks again.
259
+ */
260
+ declare const setUnavailable: (store: EntityStore, marks: ReadonlyArray<readonly [key: EntityKey, fields: Iterable<string>]>, unavailable: boolean) => EntityStore;
261
+ /** Whether the server settled this field without a value, and nothing has written it since. */
262
+ declare const isFieldUnavailable: (store: EntityStore, key: EntityKey, field: string) => boolean;
263
+ /** Records that the entity is known to be absent, so it is not refetched. */
264
+ declare const tombstone: (store: EntityStore, key: EntityKey) => EntityStore;
265
+ /** Forgets everything known about the entity, including a tombstone. */
266
+ declare const remove: (store: EntityStore, key: EntityKey) => EntityStore;
267
+ declare const entry: (store: EntityStore, key: EntityKey) => Option.Option<EntityEntry>;
268
+ declare const isTombstone: (store: EntityStore, key: EntityKey) => boolean;
269
+ /** A field is known only if it is present and not stale. */
270
+ declare const hasField: (store: EntityStore, key: EntityKey, field: string) => boolean;
271
+ /** A present field whose value may be outdated; absent fields are not stale. */
272
+ declare const isFieldStale: (store: EntityStore, key: EntityKey, field: string) => boolean;
273
+ /**
274
+ * Reads a present field, stale or not. Absence and a tombstone both yield
275
+ * `Option.none()`; a present `undefined`/`null` yields `Option.some`.
276
+ */
277
+ declare const readField: (store: EntityStore, key: EntityKey, field: string) => Option.Option<unknown>;
278
+ /**
279
+ * The fields the planner must fetch. A tombstone makes every field known
280
+ * (absent), so it returns an empty list and the entity is not refetched, and a
281
+ * field the server settled without a value is known the same way. A
282
+ * requested window that differs from the one a field was fetched with also
283
+ * marks it missing, but only when the stored window is known (never `""`), so a
284
+ * writer that does not record windows cannot cause a refetch loop.
285
+ */
286
+ declare const missingFields: (store: EntityStore, key: EntityKey, fields: Iterable<string>, windows?: Readonly<Record<string, string>>) => ReadonlyArray<string>;
287
+ //#endregion
288
+ //#region src/mutation.d.ts
289
+ interface NormalizedPatch {
290
+ readonly entity: string;
291
+ readonly id: string;
292
+ readonly values: Readonly<Record<string, unknown>>;
293
+ }
294
+ interface MutationState {
295
+ readonly pending: ReadonlySet<string>;
296
+ readonly applied: ReadonlySet<string>;
297
+ readonly failed: ReadonlySet<string>;
298
+ /** Why each request in `failed` failed, kept exactly as long as `failed` keeps its id. */
299
+ readonly errors: ReadonlyMap<string, RemoteError>;
300
+ /**
301
+ * How many mutations this model has started. A bound domain takes its next
302
+ * request id from here, so `update` stays pure and the id exists before the
303
+ * Command runs.
304
+ */
305
+ readonly sequence: number;
306
+ }
307
+ declare const emptyMutationState: MutationState;
308
+ declare const beginMutation: (state: MutationState, requestId: string) => MutationState;
309
+ declare const failMutation: (state: MutationState, requestId: string, error: RemoteError) => MutationState;
310
+ /** What Remote knows of one mutation request, by the id `mutate` returned. */
311
+ type MutationStatus =
312
+ /** Never started here, or settled so long ago its id has left the window. */
313
+ {
314
+ readonly _tag: 'Unknown';
315
+ } | {
316
+ readonly _tag: 'Pending';
317
+ } | {
318
+ readonly _tag: 'Applied';
319
+ } | {
320
+ readonly _tag: 'Failed';
321
+ readonly error: RemoteError;
322
+ };
323
+ declare const mutationStatus: (state: MutationState, requestId: string) => MutationStatus;
324
+ interface Reconciled {
325
+ readonly store: EntityStore;
326
+ readonly state: MutationState;
327
+ }
328
+ /** What a settled mutation wrote, as `MutationSucceeded` carries it. */
329
+ interface MutationAnswer {
330
+ readonly entities: ReadonlyArray<NormalizedPatch>;
331
+ /** Entities the mutation deleted; each is tombstoned. */
332
+ readonly deleted?: ReadonlyArray<{
333
+ readonly entity: string;
334
+ readonly id: string;
335
+ }> | undefined;
336
+ /** Injected clock reading of the answer, which dates what it writes. */
337
+ readonly now: number;
338
+ }
339
+ /**
340
+ * Applies a mutation result once and marks the request settled. A second call
341
+ * with the same `requestId` (a retry, or a live event describing the same change)
342
+ * does not re-apply the entities, but still clears `pending`.
343
+ */
344
+ declare const reconcileMutation: (store: EntityStore, state: MutationState, requestId: string, answer: MutationAnswer) => Reconciled;
345
+ /** A mutation an application declares: its name and input/output codecs. */
346
+ interface MutationDescriptor<Name extends string, Input, Output> {
347
+ readonly name: Name;
348
+ readonly Input: Schema.Codec<Input>;
349
+ readonly Output: Schema.Codec<Output>;
350
+ }
351
+ /** A codec, or the fields of a `Schema.Struct` where one is expected. */
352
+ type SchemaOrFields = Schema.Codec<any, any, any, any> | Schema.Struct.Fields;
353
+ /** The decoded type of a codec, or of the Struct the fields describe. */
354
+ type TypeOf<S extends SchemaOrFields> = S extends Schema.Codec<infer T, any, any, any> ? T : S extends Schema.Struct.Fields ? Schema.Struct.Type<S> : never;
355
+ /** The codec itself, or a `Schema.Struct` over the fields. */
356
+ declare const schemaOf: <S extends SchemaOrFields>(shape: S) => Schema.Codec<TypeOf<S>>;
357
+ declare const Mutation: {
358
+ /**
359
+ * Declares a mutation. `Input` and `Output` are codecs, or the fields of the
360
+ * `Schema.Struct` they would be (`{ id: ProjectId, name: Schema.String }`).
361
+ */
362
+ make: <const Name extends string, Input extends SchemaOrFields, Output extends SchemaOrFields>(name: Name, config: {
363
+ readonly Input: Input;
364
+ readonly Output: Output;
365
+ }) => MutationDescriptor<Name, TypeOf<Input>, TypeOf<Output>>;
366
+ };
367
+ //#endregion
368
+ //#region src/query.d.ts
369
+ type LiveInsertion = 'visible' | 'boundary' | 'invalidate' | 'ignore';
370
+ interface LivePolicy {
371
+ readonly prepend?: LiveInsertion;
372
+ readonly append?: LiveInsertion;
373
+ }
374
+ interface ConnectionSpec<Entity extends string = string> {
375
+ readonly entity: Entity;
376
+ readonly edgeKey?: Schema.Schema<unknown>;
377
+ readonly live?: LivePolicy;
378
+ }
379
+ interface QueryWindow {
380
+ readonly first?: number | undefined;
381
+ readonly last?: number | undefined;
382
+ readonly after?: Cursor | undefined;
383
+ readonly before?: Cursor | undefined;
384
+ }
385
+ interface QueryRef<Name extends string, Input> {
386
+ readonly query: Name;
387
+ readonly input: Input;
388
+ /** The input codec, so a `QueryRef` can encode itself without its descriptor. */
389
+ readonly Input: Schema.Codec<Input>;
390
+ readonly window: QueryWindow;
391
+ /** Connection identity: descriptor + canonical input, excluding the window. */
392
+ readonly identity: string;
393
+ }
394
+ interface QueryDescriptor<Name extends string, Input, Result> {
395
+ readonly name: Name;
396
+ readonly Input: Schema.Codec<Input>;
397
+ readonly Result: Result;
398
+ readonly ref: (input: Input) => QueryRef<Name, Input>;
399
+ /**
400
+ * What the query means, when it was declared with `Query.define`: the rows it
401
+ * is about, as a value an interpreter can compile. A descriptor from
402
+ * `Query.make` has none — its meaning lives in whatever the server registered
403
+ * to answer it — and a source is free to answer either.
404
+ */
405
+ readonly body?: AnyQuery | undefined;
406
+ }
407
+ /**
408
+ * The inputs of a definition's body: one placeholder per key of `Input`, typed
409
+ * as that key's value. A body is built once, so these stand for what the query
410
+ * will be given rather than being it.
411
+ */
412
+ type QueryInputs<Input> = { readonly [K in keyof Input & string]: InputExpr<Input[K]>; };
413
+ /**
414
+ * What separates a query's name from its canonical encoded input in a
415
+ * connection identity.
416
+ *
417
+ * NUL, because `JSON.stringify` escapes it inside a string (`\u0000`) and a
418
+ * query name is a TypeScript identifier — so the first occurrence is always the
419
+ * boundary, and a name or an input value cannot forge one. Anything recovering
420
+ * the query from an identity splits here.
421
+ */
422
+ declare const IDENTITY_SEPARATOR = "\0";
423
+ /** Stable stringify: object keys sorted, undefined-valued keys dropped, so equal inputs encode equally. */
424
+ declare const stableStringify: (value: unknown) => string;
425
+ /**
426
+ * `Result: Project` (or anything with the entity's `name`, as `Query.connection`
427
+ * takes) means a connection over it; a `ConnectionSpec` names its `entity`
428
+ * instead and is the result as given.
429
+ */
430
+ type ResultOf<Result> = Result extends {
431
+ readonly name: infer Entity extends string;
432
+ } ? ConnectionSpec<Entity> : Result;
433
+ /** A relational `Query` over one Entity, as `Query.define`'s body returns. */
434
+ type RelationalQueryOf<E extends AnyEntity> = ReturnType<typeof Query.from<E>>;
435
+ declare const Query$1: {
436
+ /** Declares the entity and options a query's result is a connection over. */
437
+ connection: <Entity extends string>(entity: {
438
+ readonly name: Entity;
439
+ }, options?: {
440
+ readonly edgeKey?: Schema.Schema<unknown>;
441
+ readonly live?: LivePolicy;
442
+ }) => ConnectionSpec<Entity>;
443
+ /**
444
+ * Declares a query. `Input` is a codec or the fields of the `Schema.Struct` it
445
+ * would be; `Result` is a `Query.connection(...)`, or the entity the result is
446
+ * a connection over.
447
+ */
448
+ make: <const Name extends string, Input extends SchemaOrFields, Result>(name: Name, config: {
449
+ readonly Input: Input;
450
+ readonly Result: Result;
451
+ }) => QueryDescriptor<Name, TypeOf<Input>, ResultOf<Result>>;
452
+ /**
453
+ * Declares a query by what it means. The body is built once, here, and the
454
+ * `input` it is given holds placeholders rather than values — there is
455
+ * nothing yet to branch on, so a condition that depends on what was passed is
456
+ * a comparison over the placeholder:
457
+ *
458
+ * ```ts
459
+ * const PostsBySlug = Query.define('PostsBySlug', { slug: Schema.String }, ({ input }) =>
460
+ * Query.from(Post).pipe(
461
+ * Query.where(Expr.eq(Post.fields.slug, input.slug)),
462
+ * Query.orderBy(Order.asc(Post.fields.id)),
463
+ * ),
464
+ * )
465
+ * ```
466
+ *
467
+ * What comes back is an ordinary `QueryDescriptor` — the same name, `Input`,
468
+ * `ref` and connection identity `Query.make` gives — carrying its `body`
469
+ * besides. A server can compile that body instead of being told the same
470
+ * thing again in its own dialect, and one that would rather answer the query
471
+ * its own way still can.
472
+ *
473
+ * The result is a connection over the Entity the body reads, so it is not
474
+ * named twice.
475
+ */
476
+ define: <const Name extends string, Input extends SchemaOrFields, E extends AnyEntity>(name: Name, Input: Input, body: (context: {
477
+ readonly input: QueryInputs<TypeOf<Input>>;
478
+ }) => RelationalQueryOf<E>, options?: {
479
+ readonly edgeKey?: Schema.Schema<unknown>;
480
+ readonly live?: LivePolicy;
481
+ }) => QueryDescriptor<Name, TypeOf<Input>, ConnectionSpec<E["name"]>>;
482
+ first: (count: number) => <R extends QueryRef<string, unknown>>(ref: R) => R;
483
+ last: (count: number) => <R extends QueryRef<string, unknown>>(ref: R) => R;
484
+ after: (cursor: Cursor) => <R extends QueryRef<string, unknown>>(ref: R) => R;
485
+ before: (cursor: Cursor) => <R extends QueryRef<string, unknown>>(ref: R) => R;
486
+ from: <E extends AnyEntity>(entity: E) => Query<E>;
487
+ where: (...predicates: ReadonlyArray<import("foldkit-entity").Predicate>) => <E extends AnyEntity>(self: Query<E>) => Query<E>;
488
+ orderBy: (...terms: ReadonlyArray<import("foldkit-entity").OrderTerm>) => <E extends AnyEntity>(self: Query<E>) => Query<E>;
489
+ dependencies: (self: AnyQuery) => import("foldkit-entity").Dependencies;
490
+ unsupported: (self: AnyQuery, supported: ReadonlyArray<import("foldkit-entity").Operation>) => ReadonlyArray<import("foldkit-entity").Operation>;
491
+ show: (self: AnyQuery) => string;
492
+ };
493
+ //#endregion
494
+ //#region src/requirement.d.ts
495
+ /**
496
+ * The slice required of an entity. `windows` carries a pagination window per
497
+ * relation field, and `relations` the slice required of each relation's
498
+ * target, so one requirement describes a whole selection graph.
499
+ */
500
+ interface RelationRequirement {
501
+ readonly entity: string;
502
+ readonly fields: readonly string[];
503
+ readonly windows?: Readonly<Record<string, QueryWindow>> | undefined;
504
+ readonly relations?: Readonly<Record<string, RelationRequirement>> | undefined;
505
+ }
506
+ interface Requirement extends RelationRequirement {
507
+ readonly id: string;
508
+ /** The projection also subscribes to changes of this entity (`Data.live`). */
509
+ readonly live?: boolean | undefined;
510
+ }
511
+ /**
512
+ * A query connection a projection reads: the page it first asks for and the
513
+ * slice it selects of each item. `identity` is the connection's (query plus
514
+ * canonical input, excluding the window).
515
+ */
516
+ interface ConnectionRequirement {
517
+ readonly identity: string;
518
+ readonly window: QueryWindow;
519
+ readonly select: RelationRequirement;
520
+ }
521
+ /**
522
+ * Merges connection requirements for the same connection and window into one,
523
+ * unioning what they select of each item; the first keeps its other properties.
524
+ */
525
+ declare function mergeConnections(connections: readonly ConnectionRequirement[]): readonly ConnectionRequirement[];
526
+ /** Unions two relation slices for the same target: fields, windows, and nested relations. */
527
+ declare function mergeRelation(current: RelationRequirement, next: RelationRequirement): RelationRequirement;
528
+ /** Unions requirements for the same entity + id, dropping duplicate fields. */
529
+ declare function mergeRequirements(requirements: readonly Requirement[]): readonly Requirement[];
530
+ /**
531
+ * Requirement helpers, for the packages that plan and serve requirements.
532
+ * `merge` unions same-entity+id requirements; `mergeRelation` unions two
533
+ * slices of one target (fields, windows, nested relations).
534
+ */
535
+ declare const Requirement: {
536
+ merge: typeof mergeRequirements;
537
+ mergeRelation: typeof mergeRelation;
538
+ mergeConnections: typeof mergeConnections;
539
+ };
540
+ /** Remote's entity requirements on a Projection, unioned per entity and id as nodes compose. */
541
+ declare const RemoteRequirements: MetadataKey<Requirement>;
542
+ /** Remote's query connections on a Projection, unioned per connection and window. */
543
+ declare const RemoteConnections: MetadataKey<ConnectionRequirement>;
544
+ /** The entity requirements a Projection carries. */
545
+ declare const requirementsOf: (projection: {
546
+ readonly metadata: Metadata;
547
+ }) => ReadonlyArray<Requirement>;
548
+ /** The query connections a Projection carries. */
549
+ declare const connectionsOf: (projection: {
550
+ readonly metadata: Metadata;
551
+ }) => ReadonlyArray<ConnectionRequirement>;
552
+ //#endregion
553
+ //#region src/optimistic.d.ts
554
+ interface EntityLayer {
555
+ readonly id: string;
556
+ readonly patches: ReadonlyArray<NormalizedPatch>;
557
+ }
558
+ /**
559
+ * Edges placed outside a connection's server-known region (`prepend`,
560
+ * `append`) or hidden from it (`remove`), owned by the request or live event
561
+ * that produced them.
562
+ */
563
+ interface ConnectionOverlay {
564
+ readonly id: string;
565
+ readonly connection: string;
566
+ readonly edges: ReadonlyArray<Edge>;
567
+ readonly position: 'prepend' | 'append' | 'remove';
568
+ }
569
+ /** A connection change a request makes optimistically or a mutation result confirms. */
570
+ type ConnectionChange = {
571
+ readonly _tag: 'Insert';
572
+ readonly connection: string;
573
+ readonly position: 'prepend' | 'append';
574
+ readonly edge: Edge;
575
+ } | {
576
+ readonly _tag: 'Remove';
577
+ readonly connection: string;
578
+ readonly edge: Edge;
579
+ };
580
+ /** What a request changes before the server answers: entity patches and connection changes. */
581
+ type OptimisticOperation = NormalizedPatch | ConnectionChange;
582
+ /** A connection, by identity string or by anything that carries one (a `QueryRef`). */
583
+ type ConnectionIdentity = string | {
584
+ readonly identity: string;
585
+ };
586
+ declare const connectionIdentity: (connection: ConnectionIdentity) => string;
587
+ /**
588
+ * Constructors for connection changes: what a request shows optimistically
589
+ * (`MutateOptions.optimistic`) and what a mutation source reports it made
590
+ * (`MutationOutcome.connections`).
591
+ */
592
+ declare const ConnectionChange: {
593
+ /** Show `ref` at the front of the connection until the request settles. */
594
+ prepend: (connection: ConnectionIdentity, ref: {
595
+ readonly entity: string;
596
+ readonly id: string;
597
+ }) => ConnectionChange;
598
+ /** Show `ref` at the end of the connection until the request settles. */
599
+ append: (connection: ConnectionIdentity, ref: {
600
+ readonly entity: string;
601
+ readonly id: string;
602
+ }) => ConnectionChange;
603
+ /** Hide `ref` from the connection until the request settles. */
604
+ remove: (connection: ConnectionIdentity, ref: {
605
+ readonly entity: string;
606
+ readonly id: string;
607
+ }) => ConnectionChange;
608
+ };
609
+ /**
610
+ * Applies a request's operations: its patches become one layer and its
611
+ * connection changes become overlays, all owned by `requestId` so settling
612
+ * removes every one of them together.
613
+ */
614
+ declare const beginOptimistic: (optimistic: OptimisticState, requestId: string, operations: ReadonlyArray<OptimisticOperation>) => OptimisticState;
615
+ /** Pending entity layers and connection overlays over the base store. */
616
+ interface OptimisticState {
617
+ readonly layers: ReadonlyArray<EntityLayer>;
618
+ readonly overlays: ReadonlyArray<ConnectionOverlay>;
619
+ }
620
+ declare const emptyOptimistic: OptimisticState;
621
+ declare const addLayer: (optimistic: OptimisticState, layer: EntityLayer) => OptimisticState;
622
+ declare const removeLayer: (optimistic: OptimisticState, id: string) => OptimisticState;
623
+ declare const addOverlay: (optimistic: OptimisticState, overlay: ConnectionOverlay) => OptimisticState;
624
+ declare const removeOverlay: (optimistic: OptimisticState, id: string) => OptimisticState;
625
+ /**
626
+ * Base store with every layer applied in order. Later layers win. A patch is
627
+ * not news from the server, so it keeps the date of the value under it; an
628
+ * entity only a request holds (a temporary id) is not the server's to age, and
629
+ * is dated `Infinity`, so freshness never plans or times it.
630
+ */
631
+ declare const visibleStore: (base: EntityStore, optimistic: OptimisticState) => EntityStore;
632
+ /**
633
+ * A fresh page is newer than any settled overlay it covers: an edge the page
634
+ * carries no longer needs an insert overlay, and a `remove` overlay hiding it
635
+ * is stale (the server says it is back). A pending request's overlays are
636
+ * left alone; they settle with the request.
637
+ */
638
+ declare const pruneOverlays: (optimistic: OptimisticState, connection: string, covered: ReadonlySet<string>, pending: ReadonlySet<string>) => OptimisticState;
639
+ /**
640
+ * Applies a result idempotently and releases the request's layer and overlays:
641
+ * a later layer re-wins on rebase. Confirmed connection changes are recorded
642
+ * once per request, as overlays the request no longer owns.
643
+ */
644
+ declare const settleSuccess: (base: EntityStore, optimistic: OptimisticState, state: MutationState, requestId: string, answer: MutationAnswer & {
645
+ /** Connection changes the server confirmed; they replace the request's own. */
646
+ readonly connections?: ReadonlyArray<ConnectionChange> | undefined;
647
+ }) => {
648
+ readonly store: EntityStore;
649
+ readonly state: MutationState;
650
+ readonly optimistic: OptimisticState;
651
+ };
652
+ /** A failed request's layer and overlays are dropped; the base was never mutated. */
653
+ declare const settleFailure: (optimistic: OptimisticState, requestId: string) => OptimisticState;
654
+ /**
655
+ * Visible edges for one connection: applicable overlays are placed outside the
656
+ * server-known segments and de-duplicated by edge identity (across overlays too),
657
+ * so a pending insert never corrupts server-known ordering; a `remove` overlay
658
+ * hides its edges wherever they are, and so does a tombstone on the edge's
659
+ * target when `store` is given. A later prepend lands before an earlier one, a
660
+ * later append after, so pending inserts read in the order they were made.
661
+ * Boundaries still come from the connection's segments.
662
+ */
663
+ declare const visibleItems: (connection: Connection, connectionId: string, overlays: ReadonlyArray<ConnectionOverlay>, store?: EntityStore) => ReadonlyArray<Edge>;
664
+ //#endregion
665
+ //#region src/live.d.ts
666
+ type LiveCursor = number;
667
+ type LiveEvent = {
668
+ readonly _tag: 'EntityPatched';
669
+ readonly ref: EdgeRef;
670
+ readonly values: Readonly<Record<string, unknown>>;
671
+ readonly changed: ReadonlyArray<string>;
672
+ readonly cursor: LiveCursor;
673
+ } | {
674
+ readonly _tag: 'EntityDeleted';
675
+ readonly ref: EdgeRef;
676
+ readonly cursor: LiveCursor;
677
+ } | {
678
+ readonly _tag: 'ConnectionInsert';
679
+ readonly connection: string;
680
+ readonly position: 'prepend' | 'append';
681
+ readonly edge: Edge;
682
+ readonly cursor: LiveCursor;
683
+ } | {
684
+ readonly _tag: 'ConnectionRemove';
685
+ readonly connection: string;
686
+ readonly edge: Edge;
687
+ readonly cursor: LiveCursor;
688
+ } | {
689
+ readonly _tag: 'ConnectionInvalidate';
690
+ readonly connection: string;
691
+ readonly cursor: LiveCursor;
692
+ };
693
+ interface BoundaryCounts {
694
+ readonly before: number;
695
+ readonly after: number;
696
+ }
697
+ interface LiveState {
698
+ /** Last applied cursor for this stream. */
699
+ readonly cursor: LiveCursor;
700
+ /** Edges recorded outside the loaded boundary, not visible in `items`. */
701
+ readonly boundary: Readonly<Record<string, BoundaryCounts>>;
702
+ }
703
+ declare const emptyLiveState: LiveState;
704
+ type LiveOutcome = 'applied' | 'duplicate' | 'gap';
705
+ /**
706
+ * Ordering per stream: at most the next cursor; ahead is a gap. Cursor `0` means
707
+ * "no baseline yet" (cursors are 1-based), so the first event of a stream is
708
+ * accepted whatever its cursor — otherwise a stream not starting at 1 would be a
709
+ * spurious gap.
710
+ */
711
+ declare const classifyLive: (state: LiveState, cursor: LiveCursor) => LiveOutcome;
712
+ interface EntityApplied {
713
+ readonly state: LiveState;
714
+ readonly store: EntityStore;
715
+ readonly outcome: LiveOutcome;
716
+ }
717
+ declare const applyEntityEvent: (state: LiveState, store: EntityStore, event: Extract<LiveEvent, {
718
+ _tag: "EntityPatched" | "EntityDeleted";
719
+ }>, now?: number) => EntityApplied;
720
+ interface ConnectionApplied {
721
+ readonly state: LiveState;
722
+ readonly optimistic: OptimisticState;
723
+ readonly outcome: LiveOutcome;
724
+ /**
725
+ * A connection the event says to refetch. Reported rather than recorded here,
726
+ * because staleness lives on the connection in the Model — which is what the
727
+ * planner and every read consult. It used to be written into a set on this
728
+ * live state that nothing read, so an invalidating event did nothing at all.
729
+ */
730
+ readonly invalidated?: string | undefined;
731
+ }
732
+ declare const applyConnectionEvent: (state: LiveState, optimistic: OptimisticState, event: Extract<LiveEvent, {
733
+ _tag: "ConnectionInsert" | "ConnectionRemove" | "ConnectionInvalidate";
734
+ }>, policy?: LivePolicy) => ConnectionApplied;
735
+ /** `hasPrevious` accounting for edges recorded outside the loaded boundary. */
736
+ declare const liveHasPrevious: (connection: Connection, state: LiveState, connectionId: string) => boolean;
737
+ /** `hasNext` accounting for edges recorded outside the loaded boundary. */
738
+ declare const liveHasNext: (connection: Connection, state: LiveState, connectionId: string) => boolean;
739
+ //#endregion
740
+ //#region src/retain.d.ts
741
+ /** A connection to keep: its identity, and what a page of it selects of each item, if a projection reads it. */
742
+ interface ConnectionRoot {
743
+ readonly identity: string;
744
+ readonly select?: RelationRequirement | undefined;
745
+ }
746
+ interface RetentionRoots {
747
+ readonly requirements: ReadonlyArray<Requirement>;
748
+ /** Connections (`QueryRef.identity`) to keep, with their edges' targets and what `select` reaches through them. */
749
+ readonly connections: ReadonlyArray<ConnectionRoot>;
750
+ }
751
+ interface Retained {
752
+ readonly entities: EntityStore;
753
+ readonly connections: Readonly<Record<string, Connection>>;
754
+ readonly optimistic: OptimisticState;
755
+ }
756
+ /**
757
+ * The entity keys the roots reach: each root entity, the targets its retained
758
+ * fields refer to, and recursively the targets a nested relation selects.
759
+ */
760
+ declare const reachable: (store: EntityStore, roots: RetentionRoots, connections: Readonly<Record<string, Connection>>, optimistic: OptimisticState, pending: ReadonlySet<string>) => ReadonlySet<EntityKey>;
761
+ /**
762
+ * Drops every entity the roots do not reach, every connection they do not
763
+ * name, and every settled overlay on a dropped connection, keeping whatever a
764
+ * pending request's layer or overlays touch. Pure.
765
+ */
766
+ declare const gc: (state: Retained & {
767
+ readonly mutations: MutationState;
768
+ }, roots: RetentionRoots) => Retained;
769
+ //#endregion
770
+ //#region src/persistence.d.ts
771
+ /** Bump when the serialized shape changes; a mismatch discards the cache. */
772
+ declare const REMOTE_CACHE_VERSION = 5;
773
+ /**
774
+ * What survives a reload: the entity cache, and the connections an application
775
+ * **declared** should come back.
776
+ *
777
+ * Connections are session state by default and stay that way — `snapshotOf`
778
+ * takes none unless asked. What a declared one keeps is its **edges and
779
+ * nothing else**, which is not a simplification but the rule: a connection's
780
+ * boundaries are cursors the server minted, and a cursor may name server state
781
+ * that no longer exists. Restoring one would be claiming to know where the
782
+ * page ends. The shape has nowhere to put a cursor, so that cannot be got
783
+ * wrong later.
784
+ */
785
+ interface Snapshot {
786
+ readonly entities: EntityStore;
787
+ /**
788
+ * By connection identity: its **segments**, each a run of edges. No
789
+ * boundaries.
790
+ *
791
+ * Segments rather than one flat list, because the gaps between them are
792
+ * knowledge too. A connection paged from both ends holds a head and a tail
793
+ * with an unfetched middle; flattening those into one run would claim the
794
+ * tail's first row follows the head's last, which is a thing the client was
795
+ * never told.
796
+ */
797
+ readonly connections: Readonly<Record<string, ReadonlyArray<ReadonlyArray<Edge>>>>;
798
+ }
799
+ interface SnapshotOptions {
800
+ /**
801
+ * Who or what the snapshot is for (a user id, a tenant, a build). A snapshot
802
+ * taken under another scope is discarded rather than shown to the wrong
803
+ * reader. Default: unscoped, which only matches unscoped.
804
+ */
805
+ readonly scope?: string | undefined;
806
+ /** Snapshots larger than this many bytes are not written and not read. */
807
+ readonly maxBytes?: number | undefined;
808
+ }
809
+ /** How a snapshot meets a store that already has entries. */
810
+ type MergePolicy = 'replace' | 'preserve-existing';
811
+ /**
812
+ * The snapshot text, or `undefined` when it would exceed `maxBytes`. Build the
813
+ * snapshot with `snapshotOf`, which is where the connections that survive are
814
+ * named; runtime state — optimistic layers, live cursors, gaps, the mutation
815
+ * ledger — is never in one.
816
+ */
817
+ declare function dehydrate(snapshot: Snapshot, options?: SnapshotOptions & {
818
+ readonly maxBytes?: undefined;
819
+ }): string;
820
+ declare function dehydrate(snapshot: Snapshot, options?: SnapshotOptions): string | undefined;
821
+ declare const RemotePersistence: {
822
+ /** The snapshot text, or `undefined` when it would exceed `maxBytes`. */
823
+ dehydrate: typeof dehydrate;
824
+ /** What a snapshot text holds, or `undefined` when it is refused. */
825
+ hydrate: (raw: string | undefined | null, options?: SnapshotOptions) => Snapshot | undefined;
826
+ /**
827
+ * What to keep of a Model, naming the connections that should survive a
828
+ * reload. Naming none is the default and is what Remote always did.
829
+ */
830
+ snapshotOf: (model: {
831
+ readonly entities: EntityStore;
832
+ readonly connections: Readonly<Record<string, Connection>>;
833
+ }, options?: {
834
+ readonly connections?: ReadonlyArray<ConnectionIdentity> | undefined;
835
+ }) => Snapshot;
836
+ /** A snapshot's entities brought into a store by policy. */
837
+ mergeStores: (current: EntityStore, snapshot: EntityStore, policy: MergePolicy) => EntityStore;
838
+ /** The cache as a fresh session has it; what a refused `restore` yields. */
839
+ emptySnapshot: Snapshot;
840
+ /**
841
+ * Writes the snapshot under `key`, or removes the key when the store would
842
+ * exceed `maxBytes`, so a stale smaller snapshot cannot outlive a larger
843
+ * store it no longer describes.
844
+ */
845
+ save: (snapshot: Snapshot, options: {
846
+ readonly key: string;
847
+ } & SnapshotOptions) => Effect.Effect<void, KeyValueStore.KeyValueStoreError, KeyValueStore.KeyValueStore>;
848
+ /**
849
+ * Reads the cache. A missing key yields `emptySnapshot`; anything `hydrate`
850
+ * refuses yields `emptySnapshot` and removes the key, so the next `restore`
851
+ * is clean and the planner refetches.
852
+ */
853
+ restore: (options: {
854
+ readonly key: string;
855
+ } & SnapshotOptions) => Effect.Effect<Snapshot, KeyValueStore.KeyValueStoreError, KeyValueStore.KeyValueStore>;
856
+ };
857
+ //#endregion
858
+ //#region src/wire.d.ts
859
+ /**
860
+ * The read/live protocol version. A batch names the version it speaks and the
861
+ * server refuses a mismatch with `RemoteProtocolError`, so a shape change never
862
+ * drifts silently: bump it whenever `ReadRequest` or `LiveRequirement` change.
863
+ */
864
+ declare const REMOTE_PROTOCOL_VERSION = 4;
865
+ declare const RemoteReadError_base: Schema.Class<RemoteReadError, Schema.TaggedStruct<"RemoteReadError", {
866
+ readonly message: Schema.String;
867
+ }>, import("effect/Cause").YieldableError>;
868
+ declare class RemoteReadError extends RemoteReadError_base {}
869
+ declare const RemoteMutationError_base: Schema.Class<RemoteMutationError, Schema.TaggedStruct<"RemoteMutationError", {
870
+ readonly message: Schema.String;
871
+ }>, import("effect/Cause").YieldableError>;
872
+ declare class RemoteMutationError extends RemoteMutationError_base {}
873
+ declare const RemoteLiveError_base: Schema.Class<RemoteLiveError, Schema.TaggedStruct<"RemoteLiveError", {
874
+ readonly message: Schema.String;
875
+ }>, import("effect/Cause").YieldableError>;
876
+ declare class RemoteLiveError extends RemoteLiveError_base {}
877
+ declare const RemoteProtocolError_base: Schema.Class<RemoteProtocolError, Schema.TaggedStruct<"RemoteProtocolError", {
878
+ readonly message: Schema.String;
879
+ readonly expected: Schema.Number;
880
+ readonly received: Schema.Number;
881
+ }>, import("effect/Cause").YieldableError>;
882
+ /** The peer speaks another protocol version; nothing was read. */
883
+ declare class RemoteProtocolError extends RemoteProtocolError_base {}
884
+ /** A page size: a non-negative integer, refused at decode otherwise rather than defaulted. */
885
+ declare const PageSize: Schema.Number;
886
+ declare const WindowSchema: Schema.Struct<{
887
+ readonly first: Schema.optional<Schema.Number>;
888
+ readonly last: Schema.optional<Schema.Number>;
889
+ readonly after: Schema.optional<Schema.String>;
890
+ readonly before: Schema.optional<Schema.String>;
891
+ }>;
892
+ /** A request may not name more fields of one entity than this; a selection never does. */
893
+ declare const MAX_FIELDS_PER_REQUEST = 256;
894
+ /** A selection may not nest relations deeper than this; the wire refuses more. */
895
+ declare const MAX_RELATION_DEPTH = 8;
896
+ declare const RelationRequest: Schema.Codec<RelationRequirement, RelationRequirement, never, never>;
897
+ declare const ReadRequest: Schema.Codec<Requirement, Requirement>;
898
+ declare const ReadBatch: Schema.Struct<{
899
+ readonly version: Schema.Number;
900
+ readonly requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
901
+ }>;
902
+ declare const NormalizedEntity: Schema.Struct<{
903
+ readonly entity: Schema.String;
904
+ readonly id: Schema.String;
905
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
906
+ }>;
907
+ /**
908
+ * Fields a read asked for that the server answered without, and will not
909
+ * answer with: the client stops asking. It says nothing about why, so a rule
910
+ * that withholds a field is not itself on the wire.
911
+ */
912
+ declare const SettledFields: Schema.Struct<{
913
+ readonly entity: Schema.String;
914
+ readonly id: Schema.String;
915
+ readonly fields: Schema.$Array<Schema.String>;
916
+ }>;
917
+ declare const ReadBatchResult: Schema.Struct<{
918
+ readonly entities: Schema.$Array<Schema.Struct<{
919
+ readonly entity: Schema.String;
920
+ readonly id: Schema.String;
921
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
922
+ }>>;
923
+ readonly settled: Schema.$Array<Schema.Struct<{
924
+ readonly entity: Schema.String;
925
+ readonly id: Schema.String;
926
+ readonly fields: Schema.$Array<Schema.String>;
927
+ }>>;
928
+ }>;
929
+ declare const MutationRequest: Schema.Struct<{
930
+ /** Stable across transport retries so a mutation is not applied twice. */
931
+ readonly requestId: Schema.String;
932
+ readonly mutation: Schema.String;
933
+ readonly input: Schema.Unknown;
934
+ }>;
935
+ declare const LiveEdge: Schema.Struct<{
936
+ readonly entity: Schema.String;
937
+ readonly id: Schema.String;
938
+ readonly key: Schema.String;
939
+ }>;
940
+ /** A connection change a mutation confirms: the same facts a live event carries, without a cursor. */
941
+ declare const ConnectionChangeSchema: Schema.Union<readonly [Schema.Struct<{
942
+ readonly _tag: Schema.Literal<"Insert">;
943
+ readonly connection: Schema.String;
944
+ readonly position: Schema.Union<readonly [Schema.Literal<"prepend">, Schema.Literal<"append">]>;
945
+ readonly edge: Schema.Struct<{
946
+ readonly entity: Schema.String;
947
+ readonly id: Schema.String;
948
+ readonly key: Schema.String;
949
+ }>;
950
+ }>, Schema.Struct<{
951
+ readonly _tag: Schema.Literal<"Remove">;
952
+ readonly connection: Schema.String;
953
+ readonly edge: Schema.Struct<{
954
+ readonly entity: Schema.String;
955
+ readonly id: Schema.String;
956
+ readonly key: Schema.String;
957
+ }>;
958
+ }>]>;
959
+ declare const MutationResult: Schema.Struct<{
960
+ readonly output: Schema.Unknown;
961
+ readonly entities: Schema.$Array<Schema.Struct<{
962
+ readonly entity: Schema.String;
963
+ readonly id: Schema.String;
964
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
965
+ }>>;
966
+ /** Connection changes the mutation made, applied alongside its entity patches. */
967
+ readonly connections: Schema.optional<Schema.$Array<Schema.Union<readonly [Schema.Struct<{
968
+ readonly _tag: Schema.Literal<"Insert">;
969
+ readonly connection: Schema.String;
970
+ readonly position: Schema.Union<readonly [Schema.Literal<"prepend">, Schema.Literal<"append">]>;
971
+ readonly edge: Schema.Struct<{
972
+ readonly entity: Schema.String;
973
+ readonly id: Schema.String;
974
+ readonly key: Schema.String;
975
+ }>;
976
+ }>, Schema.Struct<{
977
+ readonly _tag: Schema.Literal<"Remove">;
978
+ readonly connection: Schema.String;
979
+ readonly edge: Schema.Struct<{
980
+ readonly entity: Schema.String;
981
+ readonly id: Schema.String;
982
+ readonly key: Schema.String;
983
+ }>;
984
+ }>]>>>;
985
+ /** Entities the mutation deleted; the client knows them absent from then on. */
986
+ readonly deleted: Schema.optional<Schema.$Array<Schema.Struct<{
987
+ readonly entity: Schema.String;
988
+ readonly id: Schema.String;
989
+ }>>>;
990
+ }>;
991
+ declare const LiveRequirement: Schema.Struct<{
992
+ readonly version: Schema.Number;
993
+ readonly requirements: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
994
+ /** Resume cursor; events at or before it are duplicates. */
995
+ readonly after: Schema.Number;
996
+ }>;
997
+ /**
998
+ * A live change. Entity changes update the store; connection changes alter
999
+ * membership and ordering; both carry a per-stream cursor.
1000
+ */
1001
+ declare const LiveChange: Schema.Union<readonly [Schema.Struct<{
1002
+ readonly _tag: Schema.Literal<"EntityPatched">;
1003
+ readonly cursor: Schema.Number;
1004
+ readonly entity: Schema.String;
1005
+ readonly id: Schema.String;
1006
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1007
+ readonly changed: Schema.$Array<Schema.String>;
1008
+ }>, Schema.Struct<{
1009
+ readonly _tag: Schema.Literal<"EntityDeleted">;
1010
+ readonly cursor: Schema.Number;
1011
+ readonly entity: Schema.String;
1012
+ readonly id: Schema.String;
1013
+ }>, Schema.Struct<{
1014
+ readonly _tag: Schema.Literal<"ConnectionInsert">;
1015
+ readonly cursor: Schema.Number;
1016
+ readonly connection: Schema.String;
1017
+ readonly position: Schema.Union<readonly [Schema.Literal<"prepend">, Schema.Literal<"append">]>;
1018
+ readonly edge: Schema.Struct<{
1019
+ readonly entity: Schema.String;
1020
+ readonly id: Schema.String;
1021
+ readonly key: Schema.String;
1022
+ }>;
1023
+ }>, Schema.Struct<{
1024
+ readonly _tag: Schema.Literal<"ConnectionRemove">;
1025
+ readonly cursor: Schema.Number;
1026
+ readonly connection: Schema.String;
1027
+ readonly edge: Schema.Struct<{
1028
+ readonly entity: Schema.String;
1029
+ readonly id: Schema.String;
1030
+ readonly key: Schema.String;
1031
+ }>;
1032
+ }>, Schema.Struct<{
1033
+ readonly _tag: Schema.Literal<"ConnectionInvalidate">;
1034
+ readonly cursor: Schema.Number;
1035
+ readonly connection: Schema.String;
1036
+ }>]>;
1037
+ declare const Read: Rpc.Rpc<"FoldkitRemoteRead", Schema.Struct<{
1038
+ readonly version: Schema.Number;
1039
+ readonly requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
1040
+ }>, Schema.Struct<{
1041
+ readonly entities: Schema.$Array<Schema.Struct<{
1042
+ readonly entity: Schema.String;
1043
+ readonly id: Schema.String;
1044
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1045
+ }>>;
1046
+ readonly settled: Schema.$Array<Schema.Struct<{
1047
+ readonly entity: Schema.String;
1048
+ readonly id: Schema.String;
1049
+ readonly fields: Schema.$Array<Schema.String>;
1050
+ }>>;
1051
+ }>, Schema.Union<readonly [typeof RemoteReadError, typeof RemoteProtocolError]>, never, never>;
1052
+ declare const Mutate: Rpc.Rpc<"FoldkitRemoteMutate", Schema.Struct<{
1053
+ /** Stable across transport retries so a mutation is not applied twice. */
1054
+ readonly requestId: Schema.String;
1055
+ readonly mutation: Schema.String;
1056
+ readonly input: Schema.Unknown;
1057
+ }>, Schema.Struct<{
1058
+ readonly output: Schema.Unknown;
1059
+ readonly entities: Schema.$Array<Schema.Struct<{
1060
+ readonly entity: Schema.String;
1061
+ readonly id: Schema.String;
1062
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1063
+ }>>;
1064
+ /** Connection changes the mutation made, applied alongside its entity patches. */
1065
+ readonly connections: Schema.optional<Schema.$Array<Schema.Union<readonly [Schema.Struct<{
1066
+ readonly _tag: Schema.Literal<"Insert">;
1067
+ readonly connection: Schema.String;
1068
+ readonly position: Schema.Union<readonly [Schema.Literal<"prepend">, Schema.Literal<"append">]>;
1069
+ readonly edge: Schema.Struct<{
1070
+ readonly entity: Schema.String;
1071
+ readonly id: Schema.String;
1072
+ readonly key: Schema.String;
1073
+ }>;
1074
+ }>, Schema.Struct<{
1075
+ readonly _tag: Schema.Literal<"Remove">;
1076
+ readonly connection: Schema.String;
1077
+ readonly edge: Schema.Struct<{
1078
+ readonly entity: Schema.String;
1079
+ readonly id: Schema.String;
1080
+ readonly key: Schema.String;
1081
+ }>;
1082
+ }>]>>>;
1083
+ /** Entities the mutation deleted; the client knows them absent from then on. */
1084
+ readonly deleted: Schema.optional<Schema.$Array<Schema.Struct<{
1085
+ readonly entity: Schema.String;
1086
+ readonly id: Schema.String;
1087
+ }>>>;
1088
+ }>, typeof RemoteMutationError, never, never>;
1089
+ declare const Live: Rpc.Rpc<"FoldkitRemoteLive", Schema.Struct<{
1090
+ readonly version: Schema.Number;
1091
+ readonly requirements: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
1092
+ /** Resume cursor; events at or before it are duplicates. */
1093
+ readonly after: Schema.Number;
1094
+ }>, import("effect/rpc/RpcSchema").Stream<Schema.Union<readonly [Schema.Struct<{
1095
+ readonly _tag: Schema.Literal<"EntityPatched">;
1096
+ readonly cursor: Schema.Number;
1097
+ readonly entity: Schema.String;
1098
+ readonly id: Schema.String;
1099
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1100
+ readonly changed: Schema.$Array<Schema.String>;
1101
+ }>, Schema.Struct<{
1102
+ readonly _tag: Schema.Literal<"EntityDeleted">;
1103
+ readonly cursor: Schema.Number;
1104
+ readonly entity: Schema.String;
1105
+ readonly id: Schema.String;
1106
+ }>, Schema.Struct<{
1107
+ readonly _tag: Schema.Literal<"ConnectionInsert">;
1108
+ readonly cursor: Schema.Number;
1109
+ readonly connection: Schema.String;
1110
+ readonly position: Schema.Union<readonly [Schema.Literal<"prepend">, Schema.Literal<"append">]>;
1111
+ readonly edge: Schema.Struct<{
1112
+ readonly entity: Schema.String;
1113
+ readonly id: Schema.String;
1114
+ readonly key: Schema.String;
1115
+ }>;
1116
+ }>, Schema.Struct<{
1117
+ readonly _tag: Schema.Literal<"ConnectionRemove">;
1118
+ readonly cursor: Schema.Number;
1119
+ readonly connection: Schema.String;
1120
+ readonly edge: Schema.Struct<{
1121
+ readonly entity: Schema.String;
1122
+ readonly id: Schema.String;
1123
+ readonly key: Schema.String;
1124
+ }>;
1125
+ }>, Schema.Struct<{
1126
+ readonly _tag: Schema.Literal<"ConnectionInvalidate">;
1127
+ readonly cursor: Schema.Number;
1128
+ readonly connection: Schema.String;
1129
+ }>]>, Schema.Union<readonly [typeof RemoteLiveError, typeof RemoteProtocolError]>>, Schema.Never, never, never>;
1130
+ declare const RemoteQueryError_base: Schema.Class<RemoteQueryError, Schema.TaggedStruct<"RemoteQueryError", {
1131
+ readonly message: Schema.String;
1132
+ }>, import("effect/Cause").YieldableError>;
1133
+ declare class RemoteQueryError extends RemoteQueryError_base {}
1134
+ declare const WireBoundary: Schema.Union<readonly [Schema.Struct<{
1135
+ readonly _tag: Schema.Literal<"Terminal">;
1136
+ }>, Schema.Struct<{
1137
+ readonly _tag: Schema.Literal<"Cursor">;
1138
+ readonly cursor: Schema.String;
1139
+ }>, Schema.Struct<{
1140
+ readonly _tag: Schema.Literal<"Unknown">;
1141
+ }>]>;
1142
+ declare const QueryRequest: Schema.Struct<{
1143
+ readonly query: Schema.String;
1144
+ readonly input: Schema.Unknown;
1145
+ readonly window: Schema.Struct<{
1146
+ readonly first: Schema.optional<Schema.Number>;
1147
+ readonly last: Schema.optional<Schema.Number>;
1148
+ readonly after: Schema.optional<Schema.String>;
1149
+ readonly before: Schema.optional<Schema.String>;
1150
+ }>;
1151
+ /**
1152
+ * What to read of each item, as the relation slice a read asks the server
1153
+ * for. Absent for a query run without one: the response carries only edges,
1154
+ * and the client's read entry fetches fields in a second round trip.
1155
+ */
1156
+ readonly select: Schema.optional<Schema.Codec<RelationRequirement, RelationRequirement, never, never>>;
1157
+ }>;
1158
+ declare const QueryEdge: Schema.Struct<{
1159
+ readonly entity: Schema.String;
1160
+ readonly id: Schema.String;
1161
+ readonly key: Schema.String;
1162
+ }>;
1163
+ declare const QueryResult: Schema.Struct<{
1164
+ readonly edges: Schema.$Array<Schema.Struct<{
1165
+ readonly entity: Schema.String;
1166
+ readonly id: Schema.String;
1167
+ readonly key: Schema.String;
1168
+ }>>;
1169
+ readonly start: Schema.Union<readonly [Schema.Struct<{
1170
+ readonly _tag: Schema.Literal<"Terminal">;
1171
+ }>, Schema.Struct<{
1172
+ readonly _tag: Schema.Literal<"Cursor">;
1173
+ readonly cursor: Schema.String;
1174
+ }>, Schema.Struct<{
1175
+ readonly _tag: Schema.Literal<"Unknown">;
1176
+ }>]>;
1177
+ readonly end: Schema.Union<readonly [Schema.Struct<{
1178
+ readonly _tag: Schema.Literal<"Terminal">;
1179
+ }>, Schema.Struct<{
1180
+ readonly _tag: Schema.Literal<"Cursor">;
1181
+ readonly cursor: Schema.String;
1182
+ }>, Schema.Struct<{
1183
+ readonly _tag: Schema.Literal<"Unknown">;
1184
+ }>]>;
1185
+ /**
1186
+ * The selected fields of the page's items, in the same shape a read batch
1187
+ * returns. Absent from a server that predates payload planning: the client
1188
+ * reads it as empty and fetches fields as before.
1189
+ */
1190
+ readonly entities: Schema.optional<Schema.$Array<Schema.Struct<{
1191
+ readonly entity: Schema.String;
1192
+ readonly id: Schema.String;
1193
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1194
+ }>>>;
1195
+ readonly settled: Schema.optional<Schema.$Array<Schema.Struct<{
1196
+ readonly entity: Schema.String;
1197
+ readonly id: Schema.String;
1198
+ readonly fields: Schema.$Array<Schema.String>;
1199
+ }>>>;
1200
+ }>;
1201
+ declare const QueryRpc: Rpc.Rpc<"FoldkitRemoteQuery", Schema.Struct<{
1202
+ readonly query: Schema.String;
1203
+ readonly input: Schema.Unknown;
1204
+ readonly window: Schema.Struct<{
1205
+ readonly first: Schema.optional<Schema.Number>;
1206
+ readonly last: Schema.optional<Schema.Number>;
1207
+ readonly after: Schema.optional<Schema.String>;
1208
+ readonly before: Schema.optional<Schema.String>;
1209
+ }>;
1210
+ /**
1211
+ * What to read of each item, as the relation slice a read asks the server
1212
+ * for. Absent for a query run without one: the response carries only edges,
1213
+ * and the client's read entry fetches fields in a second round trip.
1214
+ */
1215
+ readonly select: Schema.optional<Schema.Codec<RelationRequirement, RelationRequirement, never, never>>;
1216
+ }>, Schema.Struct<{
1217
+ readonly edges: Schema.$Array<Schema.Struct<{
1218
+ readonly entity: Schema.String;
1219
+ readonly id: Schema.String;
1220
+ readonly key: Schema.String;
1221
+ }>>;
1222
+ readonly start: Schema.Union<readonly [Schema.Struct<{
1223
+ readonly _tag: Schema.Literal<"Terminal">;
1224
+ }>, Schema.Struct<{
1225
+ readonly _tag: Schema.Literal<"Cursor">;
1226
+ readonly cursor: Schema.String;
1227
+ }>, Schema.Struct<{
1228
+ readonly _tag: Schema.Literal<"Unknown">;
1229
+ }>]>;
1230
+ readonly end: Schema.Union<readonly [Schema.Struct<{
1231
+ readonly _tag: Schema.Literal<"Terminal">;
1232
+ }>, Schema.Struct<{
1233
+ readonly _tag: Schema.Literal<"Cursor">;
1234
+ readonly cursor: Schema.String;
1235
+ }>, Schema.Struct<{
1236
+ readonly _tag: Schema.Literal<"Unknown">;
1237
+ }>]>;
1238
+ /**
1239
+ * The selected fields of the page's items, in the same shape a read batch
1240
+ * returns. Absent from a server that predates payload planning: the client
1241
+ * reads it as empty and fetches fields as before.
1242
+ */
1243
+ readonly entities: Schema.optional<Schema.$Array<Schema.Struct<{
1244
+ readonly entity: Schema.String;
1245
+ readonly id: Schema.String;
1246
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1247
+ }>>>;
1248
+ readonly settled: Schema.optional<Schema.$Array<Schema.Struct<{
1249
+ readonly entity: Schema.String;
1250
+ readonly id: Schema.String;
1251
+ readonly fields: Schema.$Array<Schema.String>;
1252
+ }>>>;
1253
+ }>, typeof RemoteQueryError, never, never>;
1254
+ declare const RemoteRpc: RpcGroup.RpcGroup<Rpc.Rpc<"FoldkitRemoteRead", Schema.Struct<{
1255
+ readonly version: Schema.Number;
1256
+ readonly requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
1257
+ }>, Schema.Struct<{
1258
+ readonly entities: Schema.$Array<Schema.Struct<{
1259
+ readonly entity: Schema.String;
1260
+ readonly id: Schema.String;
1261
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1262
+ }>>;
1263
+ readonly settled: Schema.$Array<Schema.Struct<{
1264
+ readonly entity: Schema.String;
1265
+ readonly id: Schema.String;
1266
+ readonly fields: Schema.$Array<Schema.String>;
1267
+ }>>;
1268
+ }>, Schema.Union<readonly [typeof RemoteReadError, typeof RemoteProtocolError]>, never, never> | Rpc.Rpc<"FoldkitRemoteMutate", Schema.Struct<{
1269
+ /** Stable across transport retries so a mutation is not applied twice. */
1270
+ readonly requestId: Schema.String;
1271
+ readonly mutation: Schema.String;
1272
+ readonly input: Schema.Unknown;
1273
+ }>, Schema.Struct<{
1274
+ readonly output: Schema.Unknown;
1275
+ readonly entities: Schema.$Array<Schema.Struct<{
1276
+ readonly entity: Schema.String;
1277
+ readonly id: Schema.String;
1278
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1279
+ }>>;
1280
+ /** Connection changes the mutation made, applied alongside its entity patches. */
1281
+ readonly connections: Schema.optional<Schema.$Array<Schema.Union<readonly [Schema.Struct<{
1282
+ readonly _tag: Schema.Literal<"Insert">;
1283
+ readonly connection: Schema.String;
1284
+ readonly position: Schema.Union<readonly [Schema.Literal<"prepend">, Schema.Literal<"append">]>;
1285
+ readonly edge: Schema.Struct<{
1286
+ readonly entity: Schema.String;
1287
+ readonly id: Schema.String;
1288
+ readonly key: Schema.String;
1289
+ }>;
1290
+ }>, Schema.Struct<{
1291
+ readonly _tag: Schema.Literal<"Remove">;
1292
+ readonly connection: Schema.String;
1293
+ readonly edge: Schema.Struct<{
1294
+ readonly entity: Schema.String;
1295
+ readonly id: Schema.String;
1296
+ readonly key: Schema.String;
1297
+ }>;
1298
+ }>]>>>;
1299
+ /** Entities the mutation deleted; the client knows them absent from then on. */
1300
+ readonly deleted: Schema.optional<Schema.$Array<Schema.Struct<{
1301
+ readonly entity: Schema.String;
1302
+ readonly id: Schema.String;
1303
+ }>>>;
1304
+ }>, typeof RemoteMutationError, never, never> | Rpc.Rpc<"FoldkitRemoteLive", Schema.Struct<{
1305
+ readonly version: Schema.Number;
1306
+ readonly requirements: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
1307
+ /** Resume cursor; events at or before it are duplicates. */
1308
+ readonly after: Schema.Number;
1309
+ }>, import("effect/rpc/RpcSchema").Stream<Schema.Union<readonly [Schema.Struct<{
1310
+ readonly _tag: Schema.Literal<"EntityPatched">;
1311
+ readonly cursor: Schema.Number;
1312
+ readonly entity: Schema.String;
1313
+ readonly id: Schema.String;
1314
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1315
+ readonly changed: Schema.$Array<Schema.String>;
1316
+ }>, Schema.Struct<{
1317
+ readonly _tag: Schema.Literal<"EntityDeleted">;
1318
+ readonly cursor: Schema.Number;
1319
+ readonly entity: Schema.String;
1320
+ readonly id: Schema.String;
1321
+ }>, Schema.Struct<{
1322
+ readonly _tag: Schema.Literal<"ConnectionInsert">;
1323
+ readonly cursor: Schema.Number;
1324
+ readonly connection: Schema.String;
1325
+ readonly position: Schema.Union<readonly [Schema.Literal<"prepend">, Schema.Literal<"append">]>;
1326
+ readonly edge: Schema.Struct<{
1327
+ readonly entity: Schema.String;
1328
+ readonly id: Schema.String;
1329
+ readonly key: Schema.String;
1330
+ }>;
1331
+ }>, Schema.Struct<{
1332
+ readonly _tag: Schema.Literal<"ConnectionRemove">;
1333
+ readonly cursor: Schema.Number;
1334
+ readonly connection: Schema.String;
1335
+ readonly edge: Schema.Struct<{
1336
+ readonly entity: Schema.String;
1337
+ readonly id: Schema.String;
1338
+ readonly key: Schema.String;
1339
+ }>;
1340
+ }>, Schema.Struct<{
1341
+ readonly _tag: Schema.Literal<"ConnectionInvalidate">;
1342
+ readonly cursor: Schema.Number;
1343
+ readonly connection: Schema.String;
1344
+ }>]>, Schema.Union<readonly [typeof RemoteLiveError, typeof RemoteProtocolError]>>, Schema.Never, never, never> | Rpc.Rpc<"FoldkitRemoteQuery", Schema.Struct<{
1345
+ readonly query: Schema.String;
1346
+ readonly input: Schema.Unknown;
1347
+ readonly window: Schema.Struct<{
1348
+ readonly first: Schema.optional<Schema.Number>;
1349
+ readonly last: Schema.optional<Schema.Number>;
1350
+ readonly after: Schema.optional<Schema.String>;
1351
+ readonly before: Schema.optional<Schema.String>;
1352
+ }>;
1353
+ /**
1354
+ * What to read of each item, as the relation slice a read asks the server
1355
+ * for. Absent for a query run without one: the response carries only edges,
1356
+ * and the client's read entry fetches fields in a second round trip.
1357
+ */
1358
+ readonly select: Schema.optional<Schema.Codec<RelationRequirement, RelationRequirement, never, never>>;
1359
+ }>, Schema.Struct<{
1360
+ readonly edges: Schema.$Array<Schema.Struct<{
1361
+ readonly entity: Schema.String;
1362
+ readonly id: Schema.String;
1363
+ readonly key: Schema.String;
1364
+ }>>;
1365
+ readonly start: Schema.Union<readonly [Schema.Struct<{
1366
+ readonly _tag: Schema.Literal<"Terminal">;
1367
+ }>, Schema.Struct<{
1368
+ readonly _tag: Schema.Literal<"Cursor">;
1369
+ readonly cursor: Schema.String;
1370
+ }>, Schema.Struct<{
1371
+ readonly _tag: Schema.Literal<"Unknown">;
1372
+ }>]>;
1373
+ readonly end: Schema.Union<readonly [Schema.Struct<{
1374
+ readonly _tag: Schema.Literal<"Terminal">;
1375
+ }>, Schema.Struct<{
1376
+ readonly _tag: Schema.Literal<"Cursor">;
1377
+ readonly cursor: Schema.String;
1378
+ }>, Schema.Struct<{
1379
+ readonly _tag: Schema.Literal<"Unknown">;
1380
+ }>]>;
1381
+ /**
1382
+ * The selected fields of the page's items, in the same shape a read batch
1383
+ * returns. Absent from a server that predates payload planning: the client
1384
+ * reads it as empty and fetches fields as before.
1385
+ */
1386
+ readonly entities: Schema.optional<Schema.$Array<Schema.Struct<{
1387
+ readonly entity: Schema.String;
1388
+ readonly id: Schema.String;
1389
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1390
+ }>>>;
1391
+ readonly settled: Schema.optional<Schema.$Array<Schema.Struct<{
1392
+ readonly entity: Schema.String;
1393
+ readonly id: Schema.String;
1394
+ readonly fields: Schema.$Array<Schema.String>;
1395
+ }>>>;
1396
+ }>, typeof RemoteQueryError, never, never>>;
1397
+ //#endregion
1398
+ //#region src/model.d.ts
1399
+ /**
1400
+ * The normalized cache as a Foldkit Submodel. `Remote.define` returns a schema
1401
+ * and an `update` for this shape; `updateRemote` reconciles every producer.
1402
+ */
1403
+ interface RemoteModel {
1404
+ /** Entity values, presence, staleness, tombstones, and applied windows. */
1405
+ readonly entities: EntityStore;
1406
+ /** Normalized ordered connections, keyed by connection identity. */
1407
+ readonly connections: Readonly<Record<string, Connection>>;
1408
+ /**
1409
+ * How many rows `Data.more` has grown a read's window to, by
1410
+ * `windowGrowthKey`. A read shows at most its window, so this is what "load
1411
+ * more" changes; it lives here because a list holds no state of its own.
1412
+ */
1413
+ readonly grown: Readonly<Record<string, number>>;
1414
+ /** Optimistic entity layers and connection overlays over the base store. */
1415
+ readonly optimistic: OptimisticState;
1416
+ /** Live cursor and boundary state, keyed by the subscription's stream key. */
1417
+ readonly live: Readonly<Record<string, LiveState>>;
1418
+ /** Mutation pending/applied/failed ledger. */
1419
+ readonly mutations: MutationState;
1420
+ /** Streams whose live cursor fell behind; the caller should resync or refetch. */
1421
+ readonly gaps: ReadonlySet<string>;
1422
+ /**
1423
+ * The `entity\0id\0field` marks a read is currently fetching. A field absent
1424
+ * from the store reads as `Loading` while its mark is here and `Initial`
1425
+ * otherwise, which is what separates "being fetched" from "nothing is
1426
+ * fetching this".
1427
+ */
1428
+ readonly loading: ReadonlySet<string>;
1429
+ /**
1430
+ * `Remote.refresh` generations, held per field rather than for the store as a
1431
+ * whole. A read entry restarts when the generation over the fields it plans
1432
+ * moves, so a read sent before a refresh of its own fields cannot land after
1433
+ * it, and a refresh of one field leaves every other entry's read alone.
1434
+ */
1435
+ readonly refresh: RefreshState;
1436
+ /**
1437
+ * The reads that failed and have not been settled since, so a read can say
1438
+ * `Failed` rather than `Initial`.
1439
+ *
1440
+ * Without them a read that failed before anything loaded read exactly like
1441
+ * one nobody had asked for, and nothing asked again: a read entry restarts
1442
+ * only when what it plans changes, and a failure changed nothing. What failed
1443
+ * is not planned again on its own either, so a persistent error is not
1444
+ * retried every time an unrelated read restarts the entry. `Remote.refresh`
1445
+ * is how a view retries.
1446
+ */
1447
+ readonly failures: Failures;
1448
+ }
1449
+ /**
1450
+ * Failed reads, as the errors they failed with.
1451
+ *
1452
+ * `connections` is by connection identity, and is settled by a page arriving,
1453
+ * an invalidation, or retention dropping the connection. `fields` is by field
1454
+ * mark (`entity\0id\0field`, the marks `loading` uses), and is settled by the
1455
+ * field being written again, a refresh asking for it, or retention dropping the
1456
+ * entity. A read of it in flight reads `Loading` over the failure without
1457
+ * settling it: if that read fails too, the failure is simply recorded again.
1458
+ */
1459
+ interface Failures {
1460
+ readonly connections: Readonly<Record<string, RemoteError>>;
1461
+ readonly fields: Readonly<Record<string, RemoteError>>;
1462
+ }
1463
+ declare const noFailures: Failures;
1464
+ /**
1465
+ * `Remote.refresh` generations, per field mark. `generation` is the last one
1466
+ * handed out; `requested` is when each field was last refreshed, and `started`
1467
+ * is the generation each field's read last began under. Holding them per field
1468
+ * is what keeps one Projection's refresh from restarting every read entry.
1469
+ */
1470
+ interface RefreshState {
1471
+ readonly generation: number;
1472
+ readonly requested: ReadonlyMap<string, number>;
1473
+ readonly started: ReadonlyMap<string, number>;
1474
+ /**
1475
+ * The generation every entry is refreshed at, at least: `forgetRemote` moves
1476
+ * it, so every read and live entry restarts, and a read or stream begun for
1477
+ * the principal before is interrupted rather than landing after.
1478
+ */
1479
+ readonly floor: number;
1480
+ }
1481
+ declare const emptyRefresh: RefreshState;
1482
+ /**
1483
+ * The Model with everything the server told it forgotten: values, tombstones,
1484
+ * unavailable fields, connections, live cursors, failures, and what is in
1485
+ * flight. For a change of principal, whose facts these were. The mutation
1486
+ * sequence is kept, so request ids stay unique, and a mutation in flight is
1487
+ * treated as applied: its answer, when it comes, writes nothing here.
1488
+ */
1489
+ declare const forgetRemote: (model: RemoteModel) => RemoteModel;
1490
+ declare const initialRemoteModel: RemoteModel;
1491
+ declare const remoteModelSchema: () => Schema.Codec<RemoteModel, unknown>;
1492
+ /** The submodel's Messages; each reduces to `RemoteModel` through `updateRemote`. */
1493
+ type RemoteMessage = {
1494
+ readonly _tag: 'ReadReceived';
1495
+ readonly requests: readonly Requirement[];
1496
+ readonly result: Schema.Schema.Type<typeof ReadBatchResult>;
1497
+ readonly now: number;
1498
+ } | {
1499
+ readonly _tag: 'ReadFailed';
1500
+ readonly requests: readonly Requirement[];
1501
+ readonly error: RemoteError;
1502
+ /**
1503
+ * The live stream whose subscription broke, when this is that rather
1504
+ * than a read. Nothing was being read, so no field failed: the stream is
1505
+ * recorded as a gap, since changes after it are missed until the host
1506
+ * resubscribes.
1507
+ */
1508
+ readonly stream?: string | undefined;
1509
+ } |
1510
+ /** A refetch of present fields began; they read as `Refreshing` until it lands. */
1511
+ {
1512
+ readonly _tag: 'RefreshStarted';
1513
+ readonly requests: readonly Requirement[];
1514
+ } |
1515
+ /** A read began; the fields it asks for that the store lacks read as `Loading`. */
1516
+ {
1517
+ readonly _tag: 'ReadStarted';
1518
+ readonly requests: readonly Requirement[];
1519
+ /** The refresh generation the read was planned under. */
1520
+ readonly refresh?: number | undefined;
1521
+ } |
1522
+ /**
1523
+ * Queries for these connections were sent. One with nothing to show reads
1524
+ * `Loading` until its page or its failure arrives, which is what separates
1525
+ * "being fetched" from `Initial`, "nothing is fetching this".
1526
+ */
1527
+ {
1528
+ readonly _tag: 'QueryStarted';
1529
+ readonly connections: readonly string[];
1530
+ } |
1531
+ /** The active Surfaces' roots changed; everything they do not reach is collected. */
1532
+ {
1533
+ readonly _tag: 'RetentionChanged';
1534
+ readonly roots: RetentionRoots;
1535
+ } |
1536
+ /** A restored snapshot meets the store; runtime state is untouched. */
1537
+ {
1538
+ readonly _tag: 'Hydrated';
1539
+ readonly entities: EntityStore;
1540
+ /**
1541
+ * The connections a snapshot declared should survive, as their edges.
1542
+ * Restored with **unknown** boundaries and marked stale: the rows show
1543
+ * at once and the connection is refetched, because a persisted cursor
1544
+ * may name server state that is gone.
1545
+ */
1546
+ readonly connections?: Readonly<Record<string, ReadonlyArray<ReadonlyArray<Edge>>>> | undefined;
1547
+ readonly merge: MergePolicy;
1548
+ } |
1549
+ /** A mutation began; its optimistic operations show until it settles. */
1550
+ {
1551
+ readonly _tag: 'MutationStarted';
1552
+ readonly requestId: string;
1553
+ readonly optimistic?: ReadonlyArray<OptimisticOperation> | undefined;
1554
+ } | {
1555
+ readonly _tag: 'MutationSucceeded';
1556
+ readonly requestId: string;
1557
+ readonly entities: readonly NormalizedPatch[];
1558
+ /** Connection changes the server confirmed; they replace the request's own. */
1559
+ readonly connections?: ReadonlyArray<ConnectionChange> | undefined;
1560
+ /** Entities the mutation deleted: tombstoned, which hides them from every connection. */
1561
+ readonly deleted?: ReadonlyArray<{
1562
+ readonly entity: string;
1563
+ readonly id: string;
1564
+ }> | undefined;
1565
+ /** Injected clock reading of the answer: how fresh the written entities are. */
1566
+ readonly now: number;
1567
+ } | {
1568
+ readonly _tag: 'MutationFailed';
1569
+ readonly requestId: string;
1570
+ readonly error: RemoteError;
1571
+ } |
1572
+ /**
1573
+ * Operations shown over the store with no request behind them, until they are
1574
+ * lifted: a preview of a change nobody has made. Showing an id again replaces
1575
+ * what it showed.
1576
+ */
1577
+ {
1578
+ readonly _tag: 'OverlayShown';
1579
+ readonly id: string;
1580
+ readonly optimistic: ReadonlyArray<OptimisticOperation>;
1581
+ } | {
1582
+ readonly _tag: 'OverlayLifted';
1583
+ readonly id: string;
1584
+ } |
1585
+ /** `Data.more`: a read's window, by `windowGrowthKey`, now shows `size` rows. */
1586
+ {
1587
+ readonly _tag: 'WindowGrown';
1588
+ readonly window: string;
1589
+ readonly size: number;
1590
+ } | {
1591
+ readonly _tag: 'LiveReceived';
1592
+ readonly stream: string;
1593
+ readonly event: LiveEvent;
1594
+ readonly policy?: LivePolicy;
1595
+ readonly now: number;
1596
+ } | {
1597
+ readonly _tag: 'GapCleared';
1598
+ readonly stream: string;
1599
+ } | {
1600
+ readonly _tag: 'ConnectionMerged';
1601
+ readonly connection: string;
1602
+ readonly page: Segment;
1603
+ /** The page answers the connection's refresh, so the merge also clears `stale`. */
1604
+ readonly refreshes?: boolean | undefined;
1605
+ /**
1606
+ * The slice the query asked for, so the payload's entities write like a
1607
+ * read: one request per matching edge. Absent for a page from a server
1608
+ * that predates payload planning, which carries edges only.
1609
+ */
1610
+ readonly select?: RelationRequirement | undefined;
1611
+ /** The selected fields of the page's items, as a read batch returns them. */
1612
+ readonly entities?: ReadonlyArray<{
1613
+ readonly entity: string;
1614
+ readonly id: string;
1615
+ readonly values: Record<string, unknown>;
1616
+ }> | undefined;
1617
+ /** Fields asked for that the server settled without a value. */
1618
+ readonly settled?: ReadonlyArray<{
1619
+ readonly entity: string;
1620
+ readonly id: string;
1621
+ readonly fields: ReadonlyArray<string>;
1622
+ }> | undefined;
1623
+ /** Injected clock reading of the answer, dating what the payload writes. */
1624
+ readonly now?: number | undefined;
1625
+ } | {
1626
+ readonly _tag: 'ConnectionInvalidated';
1627
+ readonly connection: string;
1628
+ } | {
1629
+ readonly _tag: 'ConnectionRefreshed';
1630
+ readonly connection: string;
1631
+ } |
1632
+ /**
1633
+ * A query for the connection failed. Its pages stay as they were, and it
1634
+ * reads `Failed` — with them as `previous`, when it has any — until a page
1635
+ * arrives, it is invalidated, or retention drops it.
1636
+ */
1637
+ {
1638
+ readonly _tag: 'QueryFailed';
1639
+ readonly connection: string;
1640
+ readonly error: RemoteError;
1641
+ };
1642
+ declare const retentionRootsSchema: Schema.Struct<{
1643
+ readonly requirements: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
1644
+ readonly connections: Schema.$Array<Schema.Struct<{
1645
+ readonly identity: Schema.String;
1646
+ readonly select: Schema.optional<Schema.Codec<RelationRequirement, RelationRequirement, never, never>>;
1647
+ }>>;
1648
+ }>;
1649
+ /**
1650
+ * The Messages' fields by tag, without `_tag`: what `defineMessageUnion` takes,
1651
+ * so an application spreads them into its own union (`Remote.messages`).
1652
+ */
1653
+ declare const remoteMessageCases: {
1654
+ ReadReceived: {
1655
+ requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
1656
+ result: Schema.Struct<{
1657
+ readonly entities: Schema.$Array<Schema.Struct<{
1658
+ readonly entity: Schema.String;
1659
+ readonly id: Schema.String;
1660
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1661
+ }>>;
1662
+ readonly settled: Schema.$Array<Schema.Struct<{
1663
+ readonly entity: Schema.String;
1664
+ readonly id: Schema.String;
1665
+ readonly fields: Schema.$Array<Schema.String>;
1666
+ }>>;
1667
+ }>;
1668
+ now: Schema.Number;
1669
+ };
1670
+ ReadFailed: {
1671
+ requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
1672
+ error: Schema.Struct<{
1673
+ readonly _tag: Schema.String;
1674
+ readonly message: Schema.String;
1675
+ }>;
1676
+ stream: Schema.optional<Schema.String>;
1677
+ };
1678
+ RefreshStarted: {
1679
+ requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
1680
+ };
1681
+ ReadStarted: {
1682
+ requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
1683
+ refresh: Schema.optional<Schema.Number>;
1684
+ };
1685
+ QueryStarted: {
1686
+ connections: Schema.$Array<Schema.String>;
1687
+ };
1688
+ RetentionChanged: {
1689
+ roots: Schema.Struct<{
1690
+ readonly requirements: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
1691
+ readonly connections: Schema.$Array<Schema.Struct<{
1692
+ readonly identity: Schema.String;
1693
+ readonly select: Schema.optional<Schema.Codec<RelationRequirement, RelationRequirement, never, never>>;
1694
+ }>>;
1695
+ }>;
1696
+ };
1697
+ Hydrated: {
1698
+ connections: Schema.optional<Schema.Unknown>;
1699
+ entities: Schema.Unknown;
1700
+ merge: Schema.Union<readonly [Schema.Literal<"replace">, Schema.Literal<"preserve-existing">]>;
1701
+ };
1702
+ MutationStarted: {
1703
+ requestId: Schema.String;
1704
+ optimistic: Schema.optional<Schema.$Array<Schema.Unknown>>;
1705
+ };
1706
+ MutationSucceeded: {
1707
+ requestId: Schema.String;
1708
+ entities: Schema.$Array<Schema.Struct<{
1709
+ readonly entity: Schema.String;
1710
+ readonly id: Schema.String;
1711
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1712
+ }>>;
1713
+ connections: Schema.optional<Schema.$Array<Schema.Unknown>>;
1714
+ deleted: Schema.optional<Schema.$Array<Schema.Struct<{
1715
+ readonly entity: Schema.String;
1716
+ readonly id: Schema.String;
1717
+ }>>>;
1718
+ now: Schema.Number;
1719
+ };
1720
+ MutationFailed: {
1721
+ requestId: Schema.String;
1722
+ error: Schema.Struct<{
1723
+ readonly _tag: Schema.String;
1724
+ readonly message: Schema.String;
1725
+ }>;
1726
+ };
1727
+ OverlayShown: {
1728
+ id: Schema.String;
1729
+ optimistic: Schema.$Array<Schema.Unknown>;
1730
+ };
1731
+ OverlayLifted: {
1732
+ id: Schema.String;
1733
+ };
1734
+ WindowGrown: {
1735
+ window: Schema.String;
1736
+ size: Schema.Number;
1737
+ };
1738
+ LiveReceived: {
1739
+ stream: Schema.String;
1740
+ event: Schema.Unknown;
1741
+ policy: Schema.optional<Schema.Unknown>;
1742
+ now: Schema.Number;
1743
+ };
1744
+ GapCleared: {
1745
+ stream: Schema.String;
1746
+ };
1747
+ ConnectionMerged: {
1748
+ connection: Schema.String;
1749
+ page: Schema.Unknown;
1750
+ refreshes: Schema.optional<Schema.Boolean>;
1751
+ select: Schema.optional<Schema.Codec<RelationRequirement, RelationRequirement, never, never>>;
1752
+ entities: Schema.optional<Schema.$Array<Schema.Struct<{
1753
+ readonly entity: Schema.String;
1754
+ readonly id: Schema.String;
1755
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
1756
+ }>>>;
1757
+ settled: Schema.optional<Schema.$Array<Schema.Struct<{
1758
+ readonly entity: Schema.String;
1759
+ readonly id: Schema.String;
1760
+ readonly fields: Schema.$Array<Schema.String>;
1761
+ }>>>;
1762
+ now: Schema.optional<Schema.Number>;
1763
+ };
1764
+ ConnectionInvalidated: {
1765
+ connection: Schema.String;
1766
+ };
1767
+ ConnectionRefreshed: {
1768
+ connection: Schema.String;
1769
+ };
1770
+ QueryFailed: {
1771
+ connection: Schema.String;
1772
+ error: Schema.Struct<{
1773
+ readonly _tag: Schema.String;
1774
+ readonly message: Schema.String;
1775
+ }>;
1776
+ };
1777
+ };
1778
+ type RemoteMessageTag = RemoteMessage['_tag'];
1779
+ /**
1780
+ * A Remote Message as an application's union constructs it from
1781
+ * `remoteMessageCases`: the same shape `RemoteMessage` names, with the runtime
1782
+ * slots (`entities`, `event`, `page`) typed `unknown` by their schemas.
1783
+ */
1784
+ type RemoteMessageInput = { [Tag in RemoteMessageTag]: {
1785
+ readonly _tag: Tag;
1786
+ } & Schema.Struct.Type<(typeof remoteMessageCases)[Tag]>; }[RemoteMessageTag];
1787
+ /**
1788
+ * Whether a Message is one of Remote's, by tag. Narrows an application's union
1789
+ * to its Remote cases, and its complement to the application's own.
1790
+ */
1791
+ declare const isRemoteMessage: <M extends {
1792
+ readonly _tag: string;
1793
+ }>(message: M) => message is Extract<M, {
1794
+ readonly _tag: RemoteMessageTag;
1795
+ }>;
1796
+ declare const remoteMessageSchema: Schema.Schema<RemoteMessage>;
1797
+ /** The key a grown window is kept under: its connection and the window first asked for. */
1798
+ declare const windowGrowthKey: (identity: string, window: string) => string;
1799
+ /**
1800
+ * Whether only overlays show this entity: the server has told the store
1801
+ * nothing of it and no request's layer writes it, so nothing will fetch what an
1802
+ * overlay leaves out.
1803
+ */
1804
+ declare const onlyOverlaid: (model: RemoteModel, entity: string, id: string) => boolean;
1805
+ /** Whether a query for this connection is in flight. */
1806
+ declare const isQueryLoading: (model: RemoteModel, identity: string) => boolean;
1807
+ /**
1808
+ * The generation a read is planned under: the highest any of the fields it
1809
+ * reads or connections it runs was refreshed at. A read entry carries this as a
1810
+ * dependency, so it restarts when what it observes is refreshed and not when
1811
+ * anything else is.
1812
+ */
1813
+ declare const refreshedAt: (refresh: RefreshState, requests: ReadonlyArray<Requirement>, connections?: ReadonlyArray<string>) => number;
1814
+ /**
1815
+ * Marks every field of `requests` and every connection in `connections`
1816
+ * refreshed at the next generation.
1817
+ */
1818
+ declare const withRefreshRequested: (refresh: RefreshState, requests: ReadonlyArray<Requirement>, connections?: ReadonlyArray<string>) => RefreshState;
1819
+ /**
1820
+ * Whether one field's read already began under the generation that field was
1821
+ * last refreshed at. Such a read is in flight and would otherwise outlive the
1822
+ * refresh, so the refresh takes a new generation to restart it even though the
1823
+ * field is already stale.
1824
+ */
1825
+ declare const refreshIsInFlight: (refresh: RefreshState, request: Requirement, field: string) => boolean;
1826
+ /**
1827
+ * Whether a read is fetching any of `fields` for this entity. Consulted only
1828
+ * when the store lacks the value, which is what separates `Loading` from
1829
+ * `Initial`.
1830
+ */
1831
+ declare const isLoading: (model: RemoteModel, entity: string, id: string, fields: ReadonlyArray<string>) => boolean;
1832
+ /**
1833
+ * The pure reducer all four producers share. A live event that arrives ahead of
1834
+ * its cursor is a gap: it is not applied, and the stream is recorded so the host
1835
+ * can resubscribe rather than silently miss facts. When every field a Message
1836
+ * touches keeps its identity, `model` itself is returned, so the application's
1837
+ * root keeps its identity and Foldkit does not render. The common no-ops do (a
1838
+ * duplicate live event, a repeated `ReadStarted`); a repeated failure, or a
1839
+ * `preserve-existing` restore of entities already held, still makes an equal
1840
+ * copy.
1841
+ */
1842
+ declare const updateRemote: (model: RemoteModel, message: RemoteMessage) => RemoteModel;
1843
+ /** Whether this field's last read failed and nothing has settled it since. */
1844
+ declare const isFieldFailed: (model: RemoteModel, entity: string, id: string, field: string) => boolean;
1845
+ /**
1846
+ * Whether a read is fetching any field `relation` reads of an entity, its own
1847
+ * or, through each relation the store holds, its targets'. A value whose owner
1848
+ * is being fetched is loading, not `Initial`: nothing is missing a fetch.
1849
+ */
1850
+ declare const isLoadingThrough: (model: RemoteModel, entity: string, id: string, relation: RelationRequirement) => boolean;
1851
+ /**
1852
+ * The first failure among the fields `relation` reads of an entity, following
1853
+ * each relation the store holds into its targets, as `assemble` does. A read
1854
+ * that consults it shows `Failed` for a related entity's failure too, rather
1855
+ * than waiting on a field nothing will fetch.
1856
+ */
1857
+ declare const failureOf: (model: RemoteModel, entity: string, id: string, relation: RelationRequirement) => RemoteError | undefined;
1858
+ /**
1859
+ * Writes a read result into the store, recording each field's applied window so
1860
+ * a later request with a different window refetches. A relation page requested
1861
+ * with a cursor is merged onto the page already stored, so "load more"
1862
+ * accumulates rather than replaces. Every read path should use this rather than
1863
+ * reducing `writeEntity` by hand.
1864
+ */
1865
+ declare const writeRead: (store: EntityStore, requests: ReadonlyArray<Requirement>, result: Schema.Schema.Type<typeof ReadBatchResult>, now?: number) => EntityStore;
1866
+ //#endregion
1867
+ //#region src/resume.d.ts
1868
+ /**
1869
+ * A resume part, in the shape `foldkit-ssr`'s `SSR.plan` takes in `parts`.
1870
+ * Declared here structurally, so neither package depends on the other.
1871
+ */
1872
+ interface RemoteResumePart<AppModel> {
1873
+ readonly id: string;
1874
+ /** The metadata key names whose reads this part resumes. */
1875
+ readonly covers: ReadonlyArray<string>;
1876
+ readonly capture: (model: AppModel, projections: ReadonlyArray<{
1877
+ readonly metadata: Metadata;
1878
+ }>) => unknown;
1879
+ readonly restore: (model: AppModel, value: unknown) => Result.Result<AppModel, string>;
1880
+ /** Whether a Subscription entry is one of this domain's, which may start late. */
1881
+ readonly deferrable: (key: string, entry: unknown) => boolean;
1882
+ }
1883
+ //#endregion
1884
+ //#region src/coalesce.d.ts
1885
+ type Batch = Schema.Schema.Type<typeof ReadBatch>;
1886
+ type BatchResult = Schema.Schema.Type<typeof ReadBatchResult>;
1887
+ type ReadError = RemoteReadError | RemoteProtocolError;
1888
+ type BatchRead = (batch: Batch) => Effect.Effect<BatchResult, ReadError>;
1889
+ type QueryRequestValue = Schema.Schema.Type<typeof QueryRequest>;
1890
+ type QueryResultValue = Schema.Schema.Type<typeof QueryResult>;
1891
+ type QueryRun = (request: QueryRequestValue) => Effect.Effect<QueryResultValue, RemoteQueryError>;
1892
+ interface CoalesceOptions {
1893
+ /**
1894
+ * How long a batch waits to collect more requirements before it runs.
1895
+ * Requirements issued concurrently coalesce even at the default of no wait.
1896
+ */
1897
+ readonly window?: Duration.Input | undefined;
1898
+ }
1899
+ /** A stable key for a requirement, so an equal requirement in flight is joined. */
1900
+ declare const requirementKey: (requirement: Requirement) => string;
1901
+ /**
1902
+ * Wraps a raw query so that an identical query in flight (same query, input,
1903
+ * and window) is joined rather than run again; distinct queries run
1904
+ * concurrently. A page answers exactly one window, so nothing is batched.
1905
+ */
1906
+ declare const coalesceQueries: (query: QueryRun, options?: CoalesceOptions) => Effect.Effect<QueryRun>;
1907
+ /**
1908
+ * Wraps a raw batch read so that requirements are batched and deduplicated.
1909
+ * Every waiter receives the whole batch result; `Remote.writeRead` is
1910
+ * idempotent, so writing it more than once is harmless.
1911
+ */
1912
+ declare const coalesceReads: (read: BatchRead, options?: CoalesceOptions) => Effect.Effect<BatchRead>;
1913
+ //#endregion
1914
+ //#region src/client.d.ts
1915
+ declare const RemoteClient_base: Context.ServiceClass<RemoteClient, "foldkit-remote/RemoteClient", {
1916
+ readonly read: (batch: Schema.Schema.Type<typeof ReadBatch>) => Effect.Effect<Schema.Schema.Type<typeof ReadBatchResult>, RemoteReadError | RemoteProtocolError>;
1917
+ readonly query: (request: Schema.Schema.Type<typeof QueryRequest>) => Effect.Effect<Schema.Schema.Type<typeof QueryResult>, RemoteQueryError>;
1918
+ readonly mutate: (request: Schema.Schema.Type<typeof MutationRequest>) => Effect.Effect<Schema.Schema.Type<typeof MutationResult>, RemoteMutationError>;
1919
+ readonly live: (request: {
1920
+ readonly requirements: ReadonlyArray<Requirement>;
1921
+ readonly after: LiveCursor;
1922
+ }) => Stream.Stream<LiveEvent, RemoteLiveError | RemoteProtocolError>;
1923
+ }>;
1924
+ /**
1925
+ * The transport boundary. `foldkit-remote` never talks to a transport directly;
1926
+ * it depends on this Effect service, which a later phase wires to Effect RPC.
1927
+ */
1928
+ declare class RemoteClient extends RemoteClient_base {}
1929
+ /**
1930
+ * The methods an Effect RPC client for `RemoteRpc` exposes. `R` is the
1931
+ * environment a handler needs; it defaults to `never`, which is what a real
1932
+ * transport client satisfies. `RemoteServer.handlers` returns this type with its
1933
+ * own `R`, so the two sides cannot drift apart.
1934
+ *
1935
+ * `TransportError` is what the transport itself may fail with on top of the
1936
+ * declared errors: `RpcClientError` for the client `RpcClient.make` builds,
1937
+ * `never` for in-process handlers.
1938
+ */
1939
+ interface RemoteRpcClient<R = never, TransportError = never> {
1940
+ readonly FoldkitRemoteRead: (payload: Schema.Schema.Type<typeof ReadBatch>) => Effect.Effect<Schema.Schema.Type<typeof ReadBatchResult>, RemoteReadError | RemoteProtocolError | TransportError, R>;
1941
+ readonly FoldkitRemoteQuery: (payload: Schema.Schema.Type<typeof QueryRequest>) => Effect.Effect<Schema.Schema.Type<typeof QueryResult>, RemoteQueryError | TransportError, R>;
1942
+ readonly FoldkitRemoteMutate: (payload: Schema.Schema.Type<typeof MutationRequest>) => Effect.Effect<Schema.Schema.Type<typeof MutationResult>, RemoteMutationError | TransportError, R>;
1943
+ readonly FoldkitRemoteLive: (payload: Schema.Schema.Type<typeof LiveRequirement>) => Stream.Stream<Schema.Schema.Type<typeof LiveChange>, RemoteLiveError | RemoteProtocolError | TransportError, R>;
1944
+ }
1945
+ /** Reconstructs the client's `ConnectionChange` from the wire's flattened edge. */
1946
+ declare const connectionChangeOf: (change: Schema.Schema.Type<typeof ConnectionChangeSchema>) => ConnectionChange;
1947
+ /** Reconstructs the client's `LiveEvent` from the wire's flattened `LiveChange`. */
1948
+ declare const liveEventOf: (change: Schema.Schema.Type<typeof LiveChange>) => LiveEvent;
1949
+ declare const remoteError: (error: {
1950
+ readonly _tag: string;
1951
+ readonly message: string;
1952
+ }) => RemoteError;
1953
+ declare const coalescedLayer: <E, R>(layer: Layer.Layer<RemoteClient, E, R>, options?: CoalesceOptions) => Layer.Layer<RemoteClient, E, R>;
1954
+ /**
1955
+ * `Remote.mutate` as a standalone effect, so `Remote.mutateInto` can reuse it
1956
+ * without the object literal referencing itself.
1957
+ */
1958
+ declare const mutateRemote: <Name extends string, Input, Output>(mutation: MutationDescriptor<Name, Input, Output>, input: Input, requestId: string) => Effect.Effect<{
1959
+ output: Output;
1960
+ entities: readonly {
1961
+ readonly entity: string;
1962
+ readonly id: string;
1963
+ readonly values: {
1964
+ readonly [x: string]: unknown;
1965
+ };
1966
+ }[];
1967
+ connections: ConnectionChange[];
1968
+ deleted: readonly {
1969
+ readonly entity: string;
1970
+ readonly id: string;
1971
+ }[];
1972
+ }, RemoteMutationError, RemoteClient>;
1973
+ //#endregion
1974
+ //#region src/json.d.ts
1975
+ /** A request: which of Remote's calls, and its payload as the RPC protocol encodes it. */
1976
+ declare const RemoteJsonRequest: Schema.Struct<{
1977
+ readonly operation: Schema.Literals<readonly ["read", "query", "mutate"]>;
1978
+ readonly payload: Schema.Unknown;
1979
+ }>;
1980
+ type RemoteJsonRequest = typeof RemoteJsonRequest.Type;
1981
+ /** An answer: the call's result, or why there is none. */
1982
+ declare const RemoteJsonAnswer: Schema.Union<readonly [Schema.Struct<{
1983
+ readonly result: Schema.Unknown;
1984
+ }>, Schema.Struct<{
1985
+ readonly error: Schema.String;
1986
+ }>]>;
1987
+ type RemoteJsonAnswer = typeof RemoteJsonAnswer.Type;
1988
+ /**
1989
+ * Sends one request's text and resolves with its answer as parsed JSON. It
1990
+ * rejects when nothing came back, and the call fails with that message.
1991
+ */
1992
+ type RemoteJsonSend = (request: string) => Promise<unknown>;
1993
+ //#endregion
1994
+ //#region src/relation.d.ts
1995
+ interface RefParts {
1996
+ readonly entity: string;
1997
+ readonly id: string;
1998
+ }
1999
+ /** A page of refs as the wire and the store hold it. */
2000
+ interface RefPageValue {
2001
+ readonly refs: ReadonlyArray<string>;
2002
+ readonly hasNext: boolean;
2003
+ readonly hasPrevious: boolean;
2004
+ }
2005
+ /** Marks the codec `Entity.ref`/`Entity.refPage` produce, so a Selection can tell the field's shape. */
2006
+ declare const RelationAnnotation = "foldkitRemoteRelation";
2007
+ /** The target entity's name on the same codec, so a nested selection of another entity is refused. */
2008
+ declare const RelationEntityAnnotation = "foldkitRemoteRelationEntity";
2009
+ type RelationKind = 'one' | 'many' | 'page';
2010
+ interface RelationShape {
2011
+ readonly kind: RelationKind;
2012
+ readonly nullable: boolean;
2013
+ readonly entity: string;
2014
+ }
2015
+ /**
2016
+ * A page of a relation that is a whole list is read under a name of its own, the
2017
+ * field's name and the page's size: `comments@first=10`. It is a field like any
2018
+ * other to the store, the planner, and the wire, so the whole list and a page of
2019
+ * it are held side by side, merged, marked stale, and persisted each on its own.
2020
+ * The server reads the name apart, reads the relation with the window, and
2021
+ * answers under the alias. A cursor is not part of the name: a page read from a
2022
+ * cursor merges onto the page it continues.
2023
+ */
2024
+ declare const RELATION_ALIAS = "@";
2025
+ /** The alias a relation field is read under, for a window of this size. */
2026
+ declare const relationAlias: (field: string, window: {
2027
+ readonly first?: number | undefined;
2028
+ readonly last?: number | undefined;
2029
+ readonly after?: string | undefined;
2030
+ readonly before?: string | undefined;
2031
+ }) => string;
2032
+ /** The field an alias reads; a name that is no alias is its own field. */
2033
+ declare const aliasedField: (name: string) => string;
2034
+ /** Splits a ref key (`"Entity:id"`, the store key too) back into its parts. */
2035
+ declare const refParts: (encoded: string) => RefParts;
2036
+ /**
2037
+ * The refs a relation value carries, in order. Anything that is not a ref key,
2038
+ * an array of them, or a page of them contributes nothing.
2039
+ */
2040
+ declare const refsIn: (value: unknown) => ReadonlyArray<RefParts>;
2041
+ /** The refs in a relation value that name the relation's target entity, and no other. */
2042
+ declare const targetsOf: (value: unknown, relation: RelationRequirement) => ReadonlyArray<RefParts>;
2043
+ declare const isRefPage: (value: unknown) => value is RefPageValue;
2044
+ /**
2045
+ * The relation shape an entity field schema declares: a ref (`one`), a nullable
2046
+ * ref, an array of refs (`many`), or a page of refs (`page`). `undefined` for a
2047
+ * scalar field, which cannot take a nested selection.
2048
+ */
2049
+ declare const relationShape: (schema: Schema.Top) => RelationShape | undefined;
2050
+ //#endregion
2051
+ //#region src/selection.d.ts
2052
+ /** One page of a paginated relation with each target assembled through a nested selection. */
2053
+ interface Page<Item> {
2054
+ readonly items: ReadonlyArray<Item>;
2055
+ readonly hasNext: boolean;
2056
+ readonly hasPrevious: boolean;
2057
+ }
2058
+ /**
2059
+ * The fields a projection reads of one entity, plus the slice it reads of each
2060
+ * relation's target. `Shape` tells a parent selection whether this one is a
2061
+ * paginated relation (`connection`) or a plain entity slice (`entity`).
2062
+ */
2063
+ interface Selection<Value, Name extends string = string, Shape extends 'entity' | 'connection' = 'entity' | 'connection'> {
2064
+ readonly entity: Name;
2065
+ readonly fields: readonly string[];
2066
+ /** A pure codec: entity fields carry no decoding or encoding services. */
2067
+ readonly schema: Schema.Codec<Value, unknown, never, never>;
2068
+ /** Pagination windows for nested relation fields, keyed by field name. */
2069
+ readonly connections?: Readonly<Record<string, QueryWindow>> | undefined;
2070
+ /** The slice required of each nested relation's target, keyed by field name. */
2071
+ readonly relations?: Readonly<Record<string, RelationRequirement>> | undefined;
2072
+ /** Present when this selection is itself a paginated relation. */
2073
+ readonly window?: QueryWindow | undefined;
2074
+ /** Phantom: see `Shape`. */
2075
+ readonly shape?: Shape | undefined;
2076
+ }
2077
+ /** Flattens a mapped type so hovers show the picked fields, not the machinery. */
2078
+ type Simplify<T> = T extends (infer O) ? { readonly [K in keyof O]: O[K]; } : never;
2079
+ /** The value a Selection reads: `Selection.Value<typeof ProjectCard>`. */
2080
+ type SelectionValueOf<S> = S extends Selection<infer V, any, any> ? V : never;
2081
+ /** The nested selections a relation field admits: of its target entity, in the shapes its value takes. */
2082
+ type NestedFor<Field> = Exclude<Field, null | undefined> extends ReadonlyArray<EntityRef<infer Name, any>> ? Selection<unknown, Name, 'entity' | 'connection'> : Exclude<Field, null | undefined> extends RefPage<infer Name, any> ? Selection<unknown, Name, 'entity' | 'connection'> : Exclude<Field, null | undefined> extends EntityRef<infer Name, any> ? Selection<unknown, Name, 'entity'> : never;
2083
+ /** What a selection of an entity with fields `F` may pick: `true` per scalar, a nested selection per relation. */
2084
+ type SelectionOf<F extends Schema.Struct.Fields> = { readonly [K in keyof F]?: true | NestedFor<Schema.Schema.Type<F[K]>>; };
2085
+ /** `T | null` when the field admits `null` or `undefined` (both assemble to `null`). */
2086
+ type Nullable<Field, T> = [Extract<Field, null | undefined>] extends [never] ? T : T | null;
2087
+ /** A nested selection's value takes the shape of the field it selects through. */
2088
+ type NestedValue<Field, Sel> = Sel extends Selection<infer V, string, 'connection'> ? Nullable<Field, V> : Sel extends Selection<infer V, string, 'entity'> ? Nullable<Field, Exclude<Field, null | undefined> extends ReadonlyArray<EntityRef<any, any>> ? ReadonlyArray<V> : Exclude<Field, null | undefined> extends RefPage<any, any> ? Page<V> : V> : never;
2089
+ /** The value a selection `Sel` of fields `F` reads. */
2090
+ type SelectionValue<F extends Schema.Struct.Fields, Sel> = Simplify<{ readonly [K in keyof Sel & keyof F]: Sel[K] extends true ? Schema.Schema.Type<F[K]> : NestedValue<Schema.Schema.Type<F[K]>, Sel[K]>; }>;
2091
+ declare const pageSchema: (item: AnySchema) => AnySchema;
2092
+ /** The requirement a nested selection contributes for its relation's target. */
2093
+ declare const relationOf: (selection: Selection<unknown>) => RelationRequirement;
2094
+ declare const Selection: {
2095
+ /**
2096
+ * The Remote Selection of a `foldkit-entity` Selection: the same members, read
2097
+ * from Remote's store. `true` on a relation reads its refs, as it does here.
2098
+ */
2099
+ from: <Name extends string, S extends Schema.Constraint>(selection: Domain.Selection<Name, unknown, S>) => Selection<S["Type"], Name, "entity">;
2100
+ /**
2101
+ * The fields to read of `entity`. A nested `Selection` on a relation field
2102
+ * reads through the ref (or refs, or page of refs) the field holds into the
2103
+ * target's fields; a scalar field cannot take one.
2104
+ */
2105
+ make: <Name extends string, F extends Schema.Struct.Fields, const Sel extends SelectionOf<F>>(entity: EntityDescriptor<Name, F>, selection: Sel) => Selection<SelectionValue<F, Sel>, Name, "entity">;
2106
+ /**
2107
+ * A paginated relation: one page of refs to `entity` with a window, or, with
2108
+ * a nested selection, one page of targets assembled through it.
2109
+ */
2110
+ connection: {
2111
+ <Name extends string, F extends Schema.Struct.Fields>(entity: EntityDescriptor<Name, F>, window: QueryWindow): Selection<RefPage<Name, F>, Name, "connection">;
2112
+ <Name extends string, F extends Schema.Struct.Fields, Item>(entity: EntityDescriptor<Name, F>, window: QueryWindow, selection: Selection<Item, NoInfer<Name>, "entity">): Selection<Page<Item>, Name, "connection">;
2113
+ };
2114
+ };
2115
+ interface Assembled {
2116
+ readonly values: unknown;
2117
+ readonly refreshing: boolean;
2118
+ }
2119
+ /**
2120
+ * Reads an entity's selected fields out of the store, following each nested
2121
+ * relation into its targets. `undefined` means some field, at any depth, is
2122
+ * not present yet. A tombstoned target reads as `null` (or is dropped from a
2123
+ * list), so the Selection's codec decides whether that is a failure.
2124
+ */
2125
+ declare const assemble: (store: EntityStore, key: string, requirement: RelationRequirement) => Assembled | undefined;
2126
+ /**
2127
+ * The first field `requirement` reads, at any depth, that the server settled
2128
+ * without a value, as `Entity:id.field`. A read that consults it says why it
2129
+ * cannot assemble rather than waiting on a field nothing will fetch.
2130
+ */
2131
+ declare const unavailableOf: (store: EntityStore, key: string, requirement: RelationRequirement) => string | undefined;
2132
+ //#endregion
2133
+ //#region src/entity.d.ts
2134
+ type AnySchema = Schema.Schema<unknown>;
2135
+ declare const entityRefFields: unique symbol;
2136
+ /**
2137
+ * A normalized reference to an entity. `F` is a phantom carrying the entity's
2138
+ * fields so `Entity.patch` can type its patch; it is absent at runtime.
2139
+ */
2140
+ interface EntityRef<Name extends string, F extends Schema.Struct.Fields = Schema.Struct.Fields> {
2141
+ readonly entity: Name;
2142
+ readonly id: string;
2143
+ readonly [entityRefFields]?: F;
2144
+ }
2145
+ interface EntityDescriptor<Name extends string, F extends Schema.Struct.Fields> {
2146
+ readonly name: Name;
2147
+ readonly schema: Schema.Struct<F>;
2148
+ readonly fields: F;
2149
+ ref(id: Schema.Schema.Type<F['id']>): EntityRef<Name, F>;
2150
+ /** The fields a Surface reads of this entity; `Selection.make(entity, …)` with the entity as receiver. */
2151
+ select<const Sel extends SelectionOf<F>>(selection: Sel): Selection<SelectionValue<F, Sel>, Name, 'entity'>;
2152
+ /** A patch of this entity's wire-shaped values; `Entity.patch(entity.ref(id), values)`. */
2153
+ patch(id: Schema.Schema.Type<F['id']>, values: Partial<Schema.Struct.Encoded<F>>): EntityPatch<Name, F>;
2154
+ }
2155
+ /**
2156
+ * Relations are **references**, never inline target schemas: a ref cannot
2157
+ * reconstruct a full entity, and dereferencing is a store concern. Because the
2158
+ * target schema is not inlined, recursive relations cannot arise through the
2159
+ * schema graph.
2160
+ */
2161
+ /**
2162
+ * A ref as the wire carries it: the target's name, a colon, and its id. Typed
2163
+ * with the name, so a relation to `User` takes `'User:u1'` and not a ref to
2164
+ * some other entity, which would read as a row that does not exist.
2165
+ */
2166
+ type RefKey<Name extends string> = `${Name}:${string}`;
2167
+ /**
2168
+ * A patch in wire shape: the values the store holds, so a relation is its ref
2169
+ * key (`Entity.refKey`), not an `EntityRef`.
2170
+ */
2171
+ interface EntityPatch<Name extends string, F extends Schema.Struct.Fields> {
2172
+ readonly entity: Name;
2173
+ readonly id: string;
2174
+ readonly values: Partial<Schema.Struct.Encoded<F>>;
2175
+ }
2176
+ /**
2177
+ * One authoritative page of a paginated relation: refs (never inline entities)
2178
+ * plus whether more exist. The adapter does not hold segmentation state; the
2179
+ * client merges pages.
2180
+ */
2181
+ interface RefPage<Name extends string, F extends Schema.Struct.Fields = Schema.Struct.Fields> {
2182
+ readonly refs: ReadonlyArray<EntityRef<Name, F>>;
2183
+ readonly hasNext: boolean;
2184
+ readonly hasPrevious: boolean;
2185
+ }
2186
+ /** The ref codec a `foldkit-entity` relation becomes: one ref, a nullable ref, or an array of refs. */
2187
+ type RelationField<Spec> = Spec extends Domain.RelationSpec<infer Target, infer Cardinality, infer Optional> ? Cardinality extends 'many' ? Schema.$Array<Schema.Codec<EntityRef<Target['name']>, RefKey<Target['name']>>> : Optional extends true ? Schema.NullOr<Schema.Codec<EntityRef<Target['name']>, RefKey<Target['name']>>> : Schema.Codec<EntityRef<Target['name']>, RefKey<Target['name']>> : never;
2188
+ /**
2189
+ * The fields Remote stores for a `foldkit-entity` Entity: its own fields, its
2190
+ * derived members (the server supplies them like any field), and each relation
2191
+ * as refs.
2192
+ */
2193
+ type FieldsFrom<E> = E extends Domain.Entity<any, infer Fields, infer Relations, infer Derived> ? Fields & { readonly [K in keyof Derived]: Derived[K]['schema']; } & { readonly [K in keyof Relations]: RelationField<Relations[K]>; } : never;
2194
+ declare const Entity$2: {
2195
+ /**
2196
+ * The Remote descriptor of a `foldkit-entity` Entity. Relations declared with
2197
+ * `Entity.relate` become ref fields, so the store, the planner, and the server
2198
+ * treat it as they treat an `Entity.make` descriptor.
2199
+ */
2200
+ from: <E extends Domain.AnyEntity>(entity: E & {
2201
+ readonly fields: {
2202
+ readonly id: unknown;
2203
+ };
2204
+ }) => EntityDescriptor<E["name"], FieldsFrom<E>>;
2205
+ make: <const Name extends string, const F extends Schema.Struct.Fields & {
2206
+ readonly id: Schema.Schema<unknown>;
2207
+ }>(name: Name, schema: Schema.Struct<F>) => EntityDescriptor<Name, F>;
2208
+ /** A relation to a known entity, decoded as a reference. */
2209
+ ref: <Name extends string, F extends Schema.Struct.Fields>(entity: EntityDescriptor<Name, F>) => Schema.Codec<EntityRef<Name, F>, RefKey<Name>>;
2210
+ /** A relation by name, for recursive or forward references. */
2211
+ refTo: <Name extends string>(name: Name) => Schema.Codec<EntityRef<Name>, RefKey<Name>>;
2212
+ /**
2213
+ * The wire key a relation field carries (`"Entity:id"`). Adapters that read a
2214
+ * foreign key emit this so the ref codec can decode it on the client.
2215
+ */
2216
+ refKey: (ref: {
2217
+ readonly entity: string;
2218
+ readonly id: string;
2219
+ }) => string;
2220
+ /** Splits a ref key back into its entity and id. */
2221
+ refParts: (encoded: string) => RefParts;
2222
+ /** A relation value of one authoritative page of refs. */
2223
+ refPage: <Name extends string, F extends Schema.Struct.Fields>(entity: EntityDescriptor<Name, F>) => Schema.Codec<RefPage<Name, F>, {
2224
+ readonly refs: ReadonlyArray<string>;
2225
+ readonly hasNext: boolean;
2226
+ readonly hasPrevious: boolean;
2227
+ }>;
2228
+ /**
2229
+ * A normalized patch for an entity, typed against its fields' wire shape:
2230
+ * write a relation as its ref key (`Entity.refKey`), as the server does.
2231
+ */
2232
+ patch: <Name extends string, F extends Schema.Struct.Fields>(ref: EntityRef<Name, F>, patch: Partial<Schema.Struct.Encoded<F>>) => EntityPatch<Name, F>;
2233
+ };
2234
+ //#endregion
2235
+ //#region src/matching.d.ts
2236
+ /**
2237
+ * An answer over the rows the client holds — never over the rows that exist.
2238
+ *
2239
+ * `complete` is the whole reason this is its own type rather than a `Page`. A
2240
+ * `Page` carries `hasNext`/`hasPrevious`, which are facts the *server* stated
2241
+ * about rows beyond the ones it delivered; a local answer has no such facts and
2242
+ * cannot invent them. What it can say is whether the population it judged was
2243
+ * all of it, which is decidable: a connection terminal at both ends is wholly
2244
+ * held, and nothing was skipped for a missing field.
2245
+ *
2246
+ * An incomplete answer is not wrong — it is an answer about less than the
2247
+ * caller may have meant, and the flag is what lets a view say "3 so far" rather
2248
+ * than "3", or a caller decide to ask the server.
2249
+ */
2250
+ interface Matched<A> {
2251
+ readonly items: ReadonlyArray<A>;
2252
+ /** Whether every row the answer is about was judged. */
2253
+ readonly complete: boolean;
2254
+ }
2255
+ /**
2256
+ * What the rows the client holds had to say about a body.
2257
+ *
2258
+ * `skipped` is the honest half. A row missing a field the body reads cannot be
2259
+ * judged — it is neither a match nor a non-match — and dropping it silently
2260
+ * would turn "I could not tell" into "no". Naming it lets a caller decide:
2261
+ * fetch the field, ask the server, or say the answer is partial.
2262
+ */
2263
+ interface Judged {
2264
+ /** Keys of the rows that satisfy the body, in the order the body asks for. */
2265
+ readonly matched: ReadonlyArray<EntityKey>;
2266
+ /** Keys of rows held but missing a field the body reads, so not judged either way. */
2267
+ readonly skipped: ReadonlyArray<EntityKey>;
2268
+ }
2269
+ interface MatchingOptions {
2270
+ /**
2271
+ * Judge only these keys. Without it every row of the body's Entity in the
2272
+ * store is a candidate, which is what a filter over a loaded list wants; with
2273
+ * it, a caller narrows to a connection's own edges.
2274
+ */
2275
+ readonly among?: ReadonlyArray<EntityKey> | undefined;
2276
+ }
2277
+ /**
2278
+ * The rows of `descriptor`'s Entity that the store holds and the body matches.
2279
+ *
2280
+ * The input is given **decoded**, as an application writes it, and encoded here
2281
+ * through the descriptor's own `Input` codec. That is deliberate and is the
2282
+ * whole reason this takes a descriptor rather than a bare body: a store holds
2283
+ * wire values, so an input has to be in that space to be compared against them,
2284
+ * and handing an interpreter a decoded value is a mistake **no runtime error
2285
+ * catches** — the reference interpreter answers "no rows", which reads exactly
2286
+ * like a correct answer. Doing it here means a caller cannot get it wrong.
2287
+ *
2288
+ * Literals in the body are deliberately *not* encoded. A literal written in
2289
+ * domain terms is already broken against the server, which binds it to a column
2290
+ * the same way; accepting it here would make the client quietly more permissive
2291
+ * than the thing it has to agree with.
2292
+ */
2293
+ declare const matching: <Name extends string, Input>(store: EntityStore, descriptor: QueryDescriptor<Name, Input, unknown>, input: Input, options?: MatchingOptions) => Judged;
2294
+ /**
2295
+ * Whether one row belongs to a query, as far as the client can tell.
2296
+ *
2297
+ * Three answers, and the third is the one that makes this usable. `'unknown'`
2298
+ * is a row the store never fetched, or holds without a field the body reads —
2299
+ * a caller that collapses it into `'no'` has turned "I could not tell" into an
2300
+ * answer, which is the mistake this whole module is shaped against.
2301
+ *
2302
+ * **Membership is decidable where position is not.** Whether a row satisfies
2303
+ * `eq`, `isNull` or `contains` needs no collation: equality on text is exact
2304
+ * and `contains` folds ASCII, both stated in §6.0.1. *Where* a row sorts needs
2305
+ * text collation, which is the backend's and deliberately outside the
2306
+ * conformant subset — so this answers the half that is always answerable, and
2307
+ * ordering stays the server's until a query can declare its collation.
2308
+ */
2309
+ type Belongs = 'yes' | 'no' | 'unknown';
2310
+ /**
2311
+ * Takes the input **encoded**, because its one caller holds it that way: a
2312
+ * connection identity carries the canonical encoded input, and making it decode
2313
+ * only for this to encode again would be a round trip that can fail.
2314
+ *
2315
+ * A decoded-input sibling was written first and deleted: nothing called it. The
2316
+ * asymmetry with `matching`, which takes a decoded input, is the shape of the
2317
+ * two real callers rather than an oversight.
2318
+ */
2319
+ declare const belongsEncoded: <Name extends string, Input>(store: EntityStore, descriptor: QueryDescriptor<Name, Input, unknown>, encoded: Readonly<Record<string, unknown>>, key: EntityKey) => Belongs;
2320
+ //#endregion
2321
+ //#region src/inspect.d.ts
2322
+ /** A query body's `Dependencies` as plain data: each field by its Entity's name and key. */
2323
+ interface ExplainedDependencies {
2324
+ readonly fields: ReadonlyArray<{
2325
+ readonly entity: string;
2326
+ readonly key: string;
2327
+ }>;
2328
+ readonly inputs: Dependencies['inputs'];
2329
+ readonly operations: Dependencies['operations'];
2330
+ }
2331
+ /** A serializable summary of a RemoteModel for DevTools and diagnostics. */
2332
+ interface RemoteInspection {
2333
+ readonly entities: ReadonlyArray<{
2334
+ readonly key: string;
2335
+ readonly present: ReadonlyArray<string>;
2336
+ readonly stale: ReadonlyArray<string>;
2337
+ readonly unavailable: ReadonlyArray<string>;
2338
+ readonly tombstone: boolean;
2339
+ readonly updatedAt: number;
2340
+ readonly windows: Readonly<Record<string, string>>;
2341
+ }>;
2342
+ readonly connections: ReadonlyArray<string>;
2343
+ readonly live: ReadonlyArray<string>;
2344
+ readonly gaps: ReadonlyArray<string>;
2345
+ /**
2346
+ * The `entity\0id\0field` marks of reads in flight, and a
2347
+ * `\0connection\0identity` mark for each query in flight. This is what "Remote is
2348
+ * working" means here, and it is read from the Model rather than from the
2349
+ * fibers doing the work: a tool that shows it shows something the Model can
2350
+ * be replayed to, and nothing that needs the runtime to be asked.
2351
+ */
2352
+ readonly loading: ReadonlyArray<string>;
2353
+ /**
2354
+ * The reads that failed and are not yet settled: queries by connection
2355
+ * identity, entity fields by `entity\0id\0field` mark, each with its error.
2356
+ */
2357
+ readonly failures: Failures;
2358
+ readonly mutations: {
2359
+ readonly pending: ReadonlyArray<string>;
2360
+ readonly failed: ReadonlyArray<string>;
2361
+ readonly applied: number;
2362
+ };
2363
+ }
2364
+ /** A pure, serializable view of the whole cache. */
2365
+ declare const inspectRemote: (model: RemoteModel) => RemoteInspection;
2366
+ /** A pure, serializable view of one entity, or `undefined` if unknown. */
2367
+ declare const inspectEntity: (model: RemoteModel, key: string) => RemoteInspection["entities"][number] | undefined;
2368
+ /**
2369
+ * Why a read shows what it shows, in words, and for `Initial`, which of the
2370
+ * usual mistakes it is.
2371
+ *
2372
+ * `Initial` means nothing is fetching the read, and that is almost always
2373
+ * wiring rather than the network: no active Surface reads it, or one does and
2374
+ * Remote's Subscriptions are not running. The Model can tell those apart when
2375
+ * it is given the active record, so this says which, and what to do.
2376
+ */
2377
+ interface ReadDiagnosis {
2378
+ readonly state: RemoteData<unknown>['_tag'];
2379
+ /**
2380
+ * For `Initial` only. `NotObserved`: no active Surface reads it.
2381
+ * `NotFetching`: one does, and nothing is fetching it, so Remote's
2382
+ * Subscriptions are most likely not installed. `Unknown`: no active record
2383
+ * was given to tell.
2384
+ */
2385
+ readonly reason?: 'NotObserved' | 'NotFetching' | 'Unknown' | undefined;
2386
+ /** One or two sentences a developer can act on. */
2387
+ readonly message: string;
2388
+ /** The active Surfaces reading it, when the active record was given. */
2389
+ readonly surfaces?: ReadonlyArray<string> | undefined;
2390
+ }
2391
+ /**
2392
+ * What one query read is, and what it currently is — data-query-DESIGN §29.1.
2393
+ *
2394
+ * Every member is gathered from something that already existed: the read was
2395
+ * always this many pieces, and nothing had ever been asked to put them in one
2396
+ * place. It is plain serializable data, so a DevTools panel, a log line and a
2397
+ * test assert on the same value.
2398
+ *
2399
+ * Two members of §29.1's sketch are **not** here, and their absence is the
2400
+ * finding rather than an omission:
2401
+ *
2402
+ * - **Surface.** A Projection does not know which Surface reads it, and often
2403
+ * several do — so it is not a property of the read, and `explain` cannot
2404
+ * recover it alone. Given the active Surfaces (the same record
2405
+ * `subscriptions` takes), it reports **every** Surface reading the connection
2406
+ * rather than guessing one, and omits the member entirely when it was not
2407
+ * given them.
2408
+ * - **Executor.** The thing that answers a query is a `RemoteClient` Layer in
2409
+ * the runtime, not a value in the Model, and a pure read of the Model cannot
2410
+ * see it. That is the same boundary that makes this function pure and
2411
+ * replayable, so it is worth more than the line of text.
2412
+ *
2413
+ * And one that the design proposed and this does not want: *expectation*
2414
+ * (required versus optional). §11 left it unbuilt for want of a consumer, and
2415
+ * the explanation was the likeliest consumer. It turns out not to need it — a
2416
+ * query's result is a connection, so the shape is a `Page`, decided by the
2417
+ * definition rather than by the read. Nothing here has an opinion about whether
2418
+ * an empty one is an error, because nothing here has to have one.
2419
+ */
2420
+ interface QueryExplanation {
2421
+ /** The bound Remote domain that answers it. */
2422
+ readonly domain: string;
2423
+ /** The definition's name. */
2424
+ readonly query: string;
2425
+ /** The input as encoded, which is what the identity is built from. */
2426
+ readonly input: unknown;
2427
+ /** The connection identity: definition plus canonical input, excluding the window. */
2428
+ readonly identity: string;
2429
+ /** How much of the connection this read asks for. */
2430
+ readonly window: QueryWindow;
2431
+ /** What it reads of each item, as the slice asked of the server. */
2432
+ readonly select: RelationRequirement;
2433
+ /**
2434
+ * What the query means, as readable text — `Query.show`, and so neither SQL
2435
+ * nor whatever the backend compiled. Absent for a definition made with
2436
+ * `Query.make`, whose meaning lives on the server that answers it.
2437
+ */
2438
+ readonly body?: string | undefined;
2439
+ /**
2440
+ * The fields, inputs and operations the body reads; absent with the body.
2441
+ * Plain data, so it serializes: a field is its Entity's name and key, which
2442
+ * is unambiguous because a query reads one Entity.
2443
+ */
2444
+ readonly dependencies?: ExplainedDependencies | undefined;
2445
+ /** What the read answers from this Model right now. */
2446
+ readonly state: RemoteData<unknown>['_tag'];
2447
+ /**
2448
+ * The active Surfaces reading this connection at this Model, if the active
2449
+ * record was supplied. Plural because several may, which is why a Projection
2450
+ * cannot carry the answer itself.
2451
+ */
2452
+ readonly surfaces?: ReadonlyArray<string> | undefined;
2453
+ /**
2454
+ * Why each of those Surfaces is active, where it was placed with
2455
+ * `Surface.when` — the Model path and the tag, without running anything. A
2456
+ * Surface placed with `Surface.at` has no entry: a callback cannot be read.
2457
+ */
2458
+ readonly activation?: ReadonlyArray<{
2459
+ readonly surface: string;
2460
+ readonly path: readonly string[];
2461
+ readonly tag: string;
2462
+ }> | undefined;
2463
+ }
2464
+ //#endregion
2465
+ //#region src/plan.d.ts
2466
+ type Window = NonNullable<Requirement['windows']>[string];
2467
+ /** A stable key for a window, so two equal windows compare equal. */
2468
+ declare const windowKey: (window: Window) => string;
2469
+ interface PlanFreshness {
2470
+ readonly now: number;
2471
+ /** A present entry older than this many milliseconds is refreshed whole. */
2472
+ readonly freshness: number;
2473
+ }
2474
+ interface PlanOptions {
2475
+ readonly freshness?: PlanFreshness | undefined;
2476
+ /** Plan every requested field, present or not, tombstoned or not. */
2477
+ readonly force?: boolean | undefined;
2478
+ }
2479
+ /** When present values next go stale, and the requirements of the entities that do. */
2480
+ interface Deadline {
2481
+ readonly at: number;
2482
+ readonly due: ReadonlyArray<Requirement>;
2483
+ }
2484
+ /**
2485
+ * The earliest moment a value `requirements` read, following the relations the
2486
+ * store holds as `plan` does, goes stale under `freshness`, with the
2487
+ * requirements of the entities that go stale then. A field the server settled
2488
+ * without a value ages with its entity too, since `plan` asks for it again once
2489
+ * the entity expires. Nothing when no such field is still fresh: what is
2490
+ * already expired or stale is planned, not awaited, which is what keeps a
2491
+ * timer from firing on what it already fired on. It is the next moment the
2492
+ * plan can change with the clock alone, which the read entry relies on to
2493
+ * reuse its plan until then.
2494
+ */
2495
+ declare const deadlineOf: (store: EntityStore, requirements: readonly Requirement[], freshness: PlanFreshness) => Deadline | undefined;
2496
+ declare const plan: (store: EntityStore, requirements: readonly Requirement[], options?: PlanOptions) => ReadonlyArray<Requirement>;
2497
+ //#endregion
2498
+ //#region src/policy.d.ts
2499
+ type RemotePolicy =
2500
+ /** Fetch only fields the store lacks (missing, stale, or re-windowed). */
2501
+ {
2502
+ readonly _tag: 'CacheFirst';
2503
+ } |
2504
+ /**
2505
+ * Keep present values visible, read them as `Refreshing`, and refetch an
2506
+ * entry older than `maxAge` milliseconds.
2507
+ */
2508
+ {
2509
+ readonly _tag: 'StaleWhileRevalidate';
2510
+ readonly maxAge: number;
2511
+ } |
2512
+ /** Fetch every selected field regardless of coverage; cached values stay visible meanwhile. */
2513
+ {
2514
+ readonly _tag: 'NetworkOnly';
2515
+ };
2516
+ declare const RemotePolicy: {
2517
+ /** Fetch only what the store lacks. */
2518
+ cacheFirst: {
2519
+ readonly _tag: "CacheFirst";
2520
+ };
2521
+ /** Keep present values visible, read as `Refreshing`, and refetch an entry older than `maxAge` ms. */
2522
+ staleWhileRevalidate: (options: {
2523
+ readonly maxAge: number;
2524
+ }) => RemotePolicy;
2525
+ /** Fetch every selected field regardless of coverage; cached values stay visible meanwhile. */
2526
+ networkOnly: {
2527
+ readonly _tag: "NetworkOnly";
2528
+ };
2529
+ /** The planner options a policy compiles to at `now`. */
2530
+ toPlan: (policy: RemotePolicy, now: number) => PlanOptions;
2531
+ /**
2532
+ * Whether a read under this policy may refetch fields the store already
2533
+ * holds, so an observer marks them stale (read as `Refreshing`) while the
2534
+ * request is pending.
2535
+ */
2536
+ refreshes: (policy: RemotePolicy) => boolean;
2537
+ };
2538
+ //#endregion
2539
+ //#region src/index.d.ts
2540
+ /** What a domain registers: a Remote descriptor, or a `foldkit-entity` Entity (read through `Entity.from`). */
2541
+ type EntityLike = EntityDescriptor<any, any> | Domain.AnyEntity;
2542
+ /**
2543
+ * What a read selects: a Remote Selection, or a `foldkit-entity` Selection
2544
+ * (read through `Selection.from`).
2545
+ */
2546
+ type EntitySelection<Value, Name extends string, Id extends string = string> = Selection<Value, Name, 'entity'> | Domain.Selection<Name, unknown, Schema.Constraint & {
2547
+ readonly Type: Value;
2548
+ }, Id>;
2549
+ /** The Remote descriptor either kind of entity reads as, at the type level. */
2550
+ type DescriptorOf<E extends EntityLike> = E extends EntityDescriptor<any, any> ? E : E extends Domain.AnyEntity ? EntityDescriptor<E['name'], FieldsFrom<E>> : never;
2551
+ type NameOf<E extends EntityLike> = DescriptorOf<E> extends EntityDescriptor<infer N, any> ? N : never;
2552
+ type FieldsOf<E extends EntityLike> = DescriptorOf<E> extends EntityDescriptor<any, infer F> ? F : never;
2553
+ type EntityName<D> = D extends {
2554
+ readonly name: infer Name extends string;
2555
+ } ? Name : never;
2556
+ type QueryName<D> = D extends QueryDescriptor<infer Name, any, any> ? Name : never;
2557
+ type MutationName<D> = D extends MutationDescriptor<infer Name, any, any> ? Name : never;
2558
+ /**
2559
+ * Nothing when `Name` is one of the domain's registered `Names`; otherwise a
2560
+ * branded failure naming the descriptor, so `Data.get(Team.select(…))` for an
2561
+ * unregistered `Team` errors at the selection in one line.
2562
+ */
2563
+ type Registered<Name extends string, Names extends string, Kind extends string> = [Name] extends [Names] ? unknown : Invalid<`${Kind} "${Name}" is not registered with this Remote domain`>;
2564
+ /** Nothing when a selection is of the query's entity; otherwise a branded failure naming both. */
2565
+ type SelectsEntity<Entity extends string, Of extends string> = [Entity] extends [Of] ? unknown : Invalid<`the selection is of "${Entity}", but the query lists "${Of}"`>;
2566
+ interface RemoteDescriptor<Entities extends readonly EntityLike[] = readonly EntityLike[], Queries extends readonly QueryDescriptor<any, any, any>[] = readonly QueryDescriptor<any, any, any>[], Mutations extends readonly MutationDescriptor<any, any, any>[] = readonly MutationDescriptor<any, any, any>[]> {
2567
+ readonly entities: Entities;
2568
+ readonly queries: Queries;
2569
+ readonly mutations: Mutations;
2570
+ readonly Model: Schema.Codec<RemoteModel, unknown>;
2571
+ readonly initial: RemoteModel;
2572
+ readonly Message: Schema.Schema<RemoteMessage>;
2573
+ readonly update: (model: RemoteModel, message: RemoteMessage) => RemoteModel;
2574
+ readonly rpc: typeof RemoteRpc;
2575
+ /** Name-keyed lookups built from the declared entities, queries, and mutations. */
2576
+ readonly registry: {
2577
+ readonly entities: ReadonlyMap<string, EntityDescriptor<any, any>>;
2578
+ readonly queries: ReadonlyMap<string, QueryDescriptor<any, any, any>>;
2579
+ readonly mutations: ReadonlyMap<string, MutationDescriptor<any, any, any>>;
2580
+ };
2581
+ }
2582
+ declare const boundRemoteNames: unique symbol;
2583
+ interface BoundRemote<AppModel, Store extends RemoteModel, Names extends string = string> {
2584
+ readonly definition: RemoteDescriptor;
2585
+ readonly store: ModelRef<AppModel, Store>;
2586
+ /** For `Module`: owns the store's Model path. */
2587
+ readonly contract: Contract;
2588
+ /** Phantom: the entity names this Remote definition registers. */
2589
+ readonly [boundRemoteNames]?: Names;
2590
+ }
2591
+ type MutationInput<M> = M extends MutationDescriptor<any, infer Input, any> ? Input : never;
2592
+ interface DomainMutateOptions {
2593
+ /** Overrides the generated id, for a retry, a durable bridge, or a test. */
2594
+ readonly requestId?: string | undefined;
2595
+ /**
2596
+ * What the request changes before the server answers, released when it
2597
+ * settles. A function receives the generated ids, so a created entity can
2598
+ * carry `tempId` until the result names the real one.
2599
+ */
2600
+ readonly optimistic?: ReadonlyArray<OptimisticOperation> | ((ids: {
2601
+ readonly requestId: string;
2602
+ readonly tempId: string;
2603
+ }) => ReadonlyArray<OptimisticOperation>) | undefined;
2604
+ /** The clock `MutationSucceeded` stamps the answer with; default `Date.now`, read at each use. */
2605
+ readonly now?: (() => number) | undefined;
2606
+ }
2607
+ /** A Foldkit Subscription entry of the Remote domain, emitting its Messages through `RemoteClient`. */
2608
+ type RemoteEntry<AppModel, Dependencies> = EntryWithoutKeepAlive<AppModel, RemoteMessage, Dependencies, RemoteClient>;
2609
+ /**
2610
+ * The entries `RemoteDomain.subscriptions` returns for an active record: a read
2611
+ * and a live entry per key (the live one idles when nothing is read live), and
2612
+ * `retain`.
2613
+ */
2614
+ type SubscriptionEntries<AppModel, Active, Message = RemoteMessage> = { readonly [K in keyof Active & (string | number) as `${K}.read`]: EntryWithoutKeepAlive<AppModel, Message, ReadDependencies, RemoteClient>; } & { readonly [K in keyof Active & (string | number) as `${K}.live`]: EntryWithoutKeepAlive<AppModel, Message, LiveDependencies, RemoteClient>; } & {
2615
+ readonly retain: EntryWithoutKeepAlive<AppModel, Message, RetentionRoots, never>;
2616
+ };
2617
+ /** The dependencies of a live entry: what it subscribes to, and where a restart resumes. */
2618
+ interface LiveDependencies {
2619
+ readonly requirements: ReadonlyArray<Requirement>;
2620
+ readonly cursor: LiveCursor;
2621
+ readonly floor: number;
2622
+ }
2623
+ interface SubscriptionsOptions extends ObserveOptions, LiveOptions, RetainOptions {}
2624
+ /** A Remote domain's wiring for an assembly: it routes Remote's Messages into `reduce`, brings its Subscriptions and contract, and requires `RemoteClient` from the runtime's resources Layer. */
2625
+ type RemoteWiring<AppModel> = Wiring<AppModel, RemoteMessage | RemoteMessageInput, RemoteClient>;
2626
+ /** What `RemoteDomain.mutate` hands `update`: the Model with the request started, and the Command that settles it. */
2627
+ interface MutationStarted<AppModel> {
2628
+ readonly model: AppModel;
2629
+ readonly requestId: string;
2630
+ readonly tempId: string;
2631
+ /** Yields `MutationSucceeded` or `MutationFailed`; never fails. */
2632
+ readonly command: Command<RemoteMessage, never, RemoteClient>;
2633
+ }
2634
+ /**
2635
+ * A Remote domain bound to its place in the application Model: the descriptor
2636
+ * (`Remote.define`), the binding (`Remote.at`), and the application-facing
2637
+ * operations over them. Every method compiles to the `Remote.*` function of the
2638
+ * same name, which stays exported for tooling, SSR, and tests.
2639
+ */
2640
+ interface RemoteDomain<AppModel, Store extends RemoteModel, Entities extends readonly EntityLike[], Queries extends readonly QueryDescriptor<any, any, any>[], Mutations extends readonly MutationDescriptor<any, any, any>[]> extends BoundRemote<AppModel, Store, EntityName<Entities[number]>>, RemoteDescriptor<Entities, Queries, Mutations> {
2641
+ /** `Remote.select`: a Projection reading one entity through a selection of a registered entity. */
2642
+ get<Value, Name extends string, Id extends string = string>(selection: EntitySelection<Value, Name, Id> & Registered<Name, EntityName<Entities[number]>, 'Entity'>, id: NoInfer<Id>): Projection<AppModel, RemoteData<Value>>;
2643
+ /**
2644
+ * `get`, and the projection also subscribes to the entity's changes: its
2645
+ * requirements are marked `live`, so `subscriptions` derives a live entry for
2646
+ * the Surfaces that read it.
2647
+ */
2648
+ live<Value, Name extends string, Id extends string = string>(selection: EntitySelection<Value, Name, Id> & Registered<Name, EntityName<Entities[number]>, 'Entity'>, id: NoInfer<Id>): Projection<AppModel, RemoteData<Value>>;
2649
+ /**
2650
+ * A query connection read as a `Page` of items selected of the query's
2651
+ * entity: `Initial` until the page and every item's selected fields are
2652
+ * present, `Refreshing` while any of them is being refetched. The window is
2653
+ * the page first asked for; the pages `next`, `previous` and `fetch` merge
2654
+ * onto the connection read through the same projection.
2655
+ */
2656
+ query<Q extends QueryDescriptor<any, any, any>, Value, Entity extends string>(query: Q & Registered<Q['name'], QueryName<Queries[number]>, 'Query'>, input: QueryInput<Q>, options: QueryOptions<Value, Entity, QueryEntity<Q>>): QueryProjection<AppModel, Value, Q['name'], QueryInput<Q>>;
2657
+ /**
2658
+ * "Load more": the Model with the read's window grown by one page, so it
2659
+ * shows that many more rows; the read entry fetches what the connection
2660
+ * lacks. None when the read shows everything there is (or is not a sized
2661
+ * window). Called from `update`.
2662
+ */
2663
+ more<Name extends string, Input>(model: AppModel, projection: QueryProjection<AppModel, any, Name, Input>): Option.Option<AppModel>;
2664
+ /**
2665
+ * What a query read is and what it currently is, as one serializable value —
2666
+ * data-query-DESIGN §29.1: the domain, the definition and its input, the
2667
+ * connection identity, the window, the Selection, the body as readable text
2668
+ * with what it depends on, and what the read answers from this Model.
2669
+ *
2670
+ * Pure, so a DevTools panel showing it shows something the Model can be
2671
+ * replayed to.
2672
+ *
2673
+ * Given `surfaces` — the same active record `subscriptions` takes — it also
2674
+ * reports which of them read this connection, and why each is active where
2675
+ * that is a readable fact (`Surface.when`) rather than a callback
2676
+ * (`Surface.at`). A Projection cannot carry this itself: several Surfaces may
2677
+ * read one connection, so it is not a property of the read.
2678
+ */
2679
+ explain<Name extends string, Input>(model: AppModel, projection: QueryProjection<AppModel, any, Name, Input>, options?: {
2680
+ readonly surfaces?: Readonly<Record<string, ActiveSurface<AppModel>>> | undefined;
2681
+ }): QueryExplanation;
2682
+ /**
2683
+ * Why a read shows what it shows, in words. Any Remote read: `Data.get`,
2684
+ * `Data.live` or `Data.query`.
2685
+ *
2686
+ * Its point is `Initial`, which means nothing is fetching the read and is
2687
+ * almost always a wiring mistake. Given `surfaces`, the same active record
2688
+ * `subscriptions` takes, it says which: no active Surface reads it, or one
2689
+ * does and Remote's Subscriptions are not running. Pure, like `explain`.
2690
+ */
2691
+ why(model: AppModel, projection: Projection<AppModel, RemoteData<unknown>>, options?: {
2692
+ readonly surfaces?: Readonly<Record<string, ActiveSurface<AppModel>>> | undefined;
2693
+ }): ReadDiagnosis;
2694
+ /**
2695
+ * The rows of a loaded list that a body matches, decoded as the list decodes
2696
+ * them — a filter that asks the server nothing.
2697
+ *
2698
+ * **It filters a list; it does not run a query.** That distinction is what
2699
+ * keeps it honest. "Which rows match" would need to know that the list holds
2700
+ * every row the body could match, which is predicate containment and is
2701
+ * deliberately not built. "Which rows *of this list* match" is decidable from
2702
+ * what is already here, and is what a search box over a loaded page actually
2703
+ * wants.
2704
+ *
2705
+ * `complete` says whether the answer is about the whole list: every edge
2706
+ * judged, and the connection terminal at both ends. An incomplete answer is
2707
+ * not wrong — it is about less than the caller may have meant, which is why
2708
+ * it is said rather than left for a view to assume.
2709
+ *
2710
+ * Creates no connection, so there is nothing new to retain and nothing new to
2711
+ * fetch. The server stays authoritative for which rows exist.
2712
+ */
2713
+ filtered<Value, Name extends string, Input, Q extends QueryDescriptor<any, any, any>>(model: AppModel, over: QueryProjection<AppModel, Value, Name, Input>, by: Q & Registered<Q['name'], QueryName<Queries[number]>, 'Query'>, input: QueryInput<Q>): Matched<Value>;
2714
+ /**
2715
+ * Shows operations over the store with no request behind them, as a mutation's
2716
+ * `optimistic` ones show while it is in flight: every Selection and view draws
2717
+ * them. For a preview of a change nobody has made. They stay until `lift`;
2718
+ * showing an id again replaces what it showed. Called from `update`. A read
2719
+ * of an entity only overlays show, lacking a field it selects, is `Failed`
2720
+ * (`Overlaid`): nothing will fetch that field.
2721
+ */
2722
+ overlay(model: AppModel, id: string, optimistic: ReadonlyArray<OptimisticOperation>): AppModel;
2723
+ /** Lifts what `overlay` showed under this id. Lifting nothing returns the same Model. */
2724
+ lift(model: AppModel, id: string): AppModel;
2725
+ /** `Remote.refresh`: marks what a projection or a Surface requires as due, for its read entry to refetch. */
2726
+ refresh(model: AppModel, target: Projection<AppModel, unknown> | Surface<AppModel, any, any, void>): AppModel;
2727
+ /** `Remote.forget`: the Model with every server-derived fact gone, for a change of principal. */
2728
+ forget(model: AppModel): AppModel;
2729
+ /**
2730
+ * A read of this domain as an active Surface, for `subscriptions` and
2731
+ * `wiring`: `projectionOf` is what it reads for a Model, none while it
2732
+ * reads nothing. It belongs to the domain's application, and lists no
2733
+ * Messages: it is a requirement, not a sender. A domain made from a raw
2734
+ * optic names no application, so this throws for one.
2735
+ */
2736
+ active<Value>(name: string, projectionOf: (model: AppModel) => Option.Option<Projection<AppModel, Value>>): ActiveSurface<AppModel>;
2737
+ /**
2738
+ * The Foldkit Subscription entries for the active Surfaces, keyed for
2739
+ * `Subscription.make`: a read entry per Surface (`Remote.observe`), a live
2740
+ * entry per Surface that reads through `live` (`Remote.live`), and one
2741
+ * retain entry (`Remote.retain`). Retention is the domain's: the retain
2742
+ * entry of every call roots the active Surfaces of every call, so reads
2743
+ * split over calls (one per policy) do not collect each other's data. A
2744
+ * Surface's params are a function of the Model (`Surface.at`), so what is
2745
+ * fetched, subscribed, and retained follows the Model.
2746
+ */
2747
+ subscriptions<const Active extends Readonly<Record<string, ActiveSurface<AppModel> | Surface<AppModel, any, any, void>>>>(active: Active, options?: SubscriptionsOptions): SubscriptionEntries<AppModel, Active>;
2748
+ /** `Remote.plan`: the requirements the store does not satisfy. */
2749
+ plan<Value>(model: AppModel, projection: Projection<AppModel, Value>, options?: PlanOptions): ReadonlyArray<Requirement>;
2750
+ /** `Remote.meta`: when what a projection shows was last received, and whether it is stale or loading. */
2751
+ meta<Value>(model: AppModel, projection: Projection<AppModel, Value>): ReadMeta;
2752
+ /** `Remote.storeOf`: the visible store, base under the pending optimistic layers. */
2753
+ storeOf(model: AppModel): EntityStore;
2754
+ /**
2755
+ * `Remote.confirmed`: the same projection read against the server-derived
2756
+ * store alone, with every pending optimistic layer and connection overlay
2757
+ * left off. What it plans is unchanged — the requirements are the
2758
+ * projection's own — so observing it reads exactly what observing the
2759
+ * projection reads; only what it *shows* differs.
2760
+ *
2761
+ * A view usually wants the projection itself, which is the visible read:
2762
+ * the optimistic layers are there so a change shows before the server has
2763
+ * agreed to it. This is for the reader that must not believe a change until
2764
+ * the server has confirmed it, which in practice is an Agent capability
2765
+ * reporting that what it was asked to do is done:
2766
+ *
2767
+ * ```ts
2768
+ * Agent.when({
2769
+ * projection: Data.confirmed(ProjectPage.model.project),
2770
+ * predicate: (project, request) => project.name === request.name,
2771
+ * })
2772
+ * ```
2773
+ *
2774
+ * There is deliberately no `visible`: a projection is already the visible
2775
+ * read, and a wrapper that only forwards would be a second name for it.
2776
+ */
2777
+ confirmed<P extends Projection<AppModel, any>>(projection: P): P;
2778
+ /**
2779
+ * The plan run through `RemoteClient` and reduced into the Model: the
2780
+ * projection's pending queries first, then the fields it lacks (the pages'
2781
+ * items included). For SSR, route or hover prefetch, and tests.
2782
+ */
2783
+ prefetch<Value>(model: AppModel, projection: Projection<AppModel, Value>, options?: ObserveOptions): Effect.Effect<AppModel, RemoteReadError | RemoteProtocolError | RemoteQueryError, RemoteClient>;
2784
+ /**
2785
+ * The Model with everything the active Surfaces read, for a render that
2786
+ * fetches nothing (SSR, a prerender). Each pass prefetches every Surface
2787
+ * that plans a read, over the Model the one before it left, so a Surface
2788
+ * active only once another's read has arrived is read in the next pass (or
2789
+ * the same one, when it comes later in `active`). It stops at the first
2790
+ * pass that plans nothing, and fails with `RemoteUnsatisfied` when
2791
+ * `options.passes` run out first. Reads are cache-first: a field already
2792
+ * held is not asked again.
2793
+ */
2794
+ satisfy(model: AppModel, active: Readonly<Record<string, ActiveSurface<AppModel> | Surface<AppModel, any, any, void>>>, options?: SatisfyOptions): Effect.Effect<AppModel, RemoteReadError | RemoteProtocolError | RemoteQueryError | RemoteUnsatisfied, RemoteClient>;
2795
+ /**
2796
+ * Starts a registered mutation from `update`: applies `MutationStarted` (with
2797
+ * the optimistic operations) to the Model and returns the Command that runs
2798
+ * it and yields the settling Message. The request id comes from the model's
2799
+ * mutation sequence unless `options.requestId` is given.
2800
+ */
2801
+ mutate<M extends MutationDescriptor<any, any, any>>(model: AppModel, mutation: M & Registered<M['name'], MutationName<Mutations[number]>, 'Mutation'>, input: MutationInput<M>, options?: DomainMutateOptions): MutationStarted<AppModel>;
2802
+ /**
2803
+ * What Remote knows of a mutation `mutate` started, by its request id:
2804
+ * pending, applied, or failed with the error the server or transport gave.
2805
+ */
2806
+ mutation(model: AppModel, requestId: string): MutationStatus;
2807
+ /** `updateRemote` on the bound slice: reduces one of Remote's Messages, as `RemoteMessage` or as the application's union constructs it. */
2808
+ reduce(model: AppModel, message: RemoteMessage | RemoteMessageInput): AppModel;
2809
+ /**
2810
+ * How this domain joins an assembly: it routes Remote's Messages into
2811
+ * `reduce`, brings its Subscriptions and contract, and requires
2812
+ * `RemoteClient` from the runtime's resources Layer. One assembly holds at
2813
+ * most one Remote wiring: every domain claims the same tags, and routing
2814
+ * takes the first claimant.
2815
+ */
2816
+ wiring: <const Active extends Readonly<Record<string, ActiveSurface<AppModel> | Surface<AppModel, any, any, void>>>>(active: Active, options?: SubscriptionsOptions) => RemoteWiring<AppModel>;
2817
+ /** `Remote.inspect` of the bound slice. */
2818
+ inspect(model: AppModel): RemoteInspection;
2819
+ }
2820
+ /** What `Remote.fold(Data, …).mutate` starts: `Data.mutate`'s result with its Command lifted. */
2821
+ type FoldedMutationStarted<AppModel, ParentMessage> = Omit<MutationStarted<AppModel>, 'command'> & {
2822
+ readonly command: Command<ParentMessage, never, RemoteClient>;
2823
+ };
2824
+ /**
2825
+ * A bound domain folded under one of the application's own Message variants,
2826
+ * from `Remote.fold`. Calling it reduces a Remote Message into the Model; the
2827
+ * members that produce Messages, `fetch`, `mutate`, and `subscriptions`,
2828
+ * yield the wrapper Message instead of `RemoteMessage`, with the lift recorded
2829
+ * so Story and Scene can resolve a fetch or a mutation by Remote's own answer.
2830
+ * Members that only read or write the Model (`get`, `refresh`, `next`,
2831
+ * `overlay`, and the rest) stay on the domain itself.
2832
+ */
2833
+ interface RemoteFold<AppModel, ParentMessage, Domain extends RemoteDomain<AppModel, any, any, any, any>> {
2834
+ (model: AppModel, message: RemoteMessage | RemoteMessageInput): Update.Return<AppModel, ParentMessage>;
2835
+ /** `Data.mutate`, its Command lifted. */
2836
+ readonly mutate: (...args: Parameters<Domain['mutate']>) => FoldedMutationStarted<AppModel, ParentMessage>;
2837
+ /** `Data.subscriptions`, every entry lifted to the wrapper Message. */
2838
+ readonly subscriptions: <const Active extends Readonly<Record<string, ActiveSurface<AppModel> | Surface<AppModel, any, any, void>>>>(active: Active, options?: SubscriptionsOptions) => SubscriptionEntries<AppModel, Active, ParentMessage>;
2839
+ }
2840
+ /** The application Model a bound domain is over. */
2841
+ type ModelOfDomain<Domain> = Domain extends RemoteDomain<infer AppModel, any, any, any, any> ? AppModel : never;
2842
+ /** A projection's connection requirement with the `QueryRef` that runs it. */
2843
+ interface QueryRequirement extends ConnectionRequirement {
2844
+ readonly ref: QueryRef<string, unknown>;
2845
+ }
2846
+ /** A page forward (`first`, `after`) or back (`last`, `before`); mixing the two is a type error. */
2847
+ type QueryWindowOptions = {
2848
+ readonly first?: number | undefined;
2849
+ readonly after?: string | undefined;
2850
+ readonly last?: undefined;
2851
+ readonly before?: undefined;
2852
+ } | {
2853
+ readonly last: number;
2854
+ readonly before?: string | undefined;
2855
+ readonly first?: undefined;
2856
+ readonly after?: undefined;
2857
+ };
2858
+ type QueryOptions<Value, Entity extends string, Of extends string = Entity> = {
2859
+ /** What to read of each item: a selection of the query's entity (`Of`). */
2860
+ readonly select: EntitySelection<Value, Entity> & SelectsEntity<Entity, Of>;
2861
+ } & QueryWindowOptions;
2862
+ /** A query connection read as a `Page` of selected items; `ref` is the connection with its first window. */
2863
+ interface QueryProjection<AppModel, Value, Name extends string, Input> extends Projection<AppModel, RemoteData<Page<Value>>> {
2864
+ readonly ref: QueryRef<Name, Input>;
2865
+ /** What it reads of each item, so a filter over the same list decodes identically. */
2866
+ readonly selection: Selection<Value, string>;
2867
+ }
2868
+ /** The input of a query descriptor. */
2869
+ type QueryInput<Q> = Q extends QueryDescriptor<any, infer Input, any> ? Input : never;
2870
+ /** The entity a query's connection is over. */
2871
+ type QueryEntity<Q> = Q extends QueryDescriptor<any, any, ConnectionSpec<infer Entity>> ? Entity : string;
2872
+ /**
2873
+ * When what a projection shows was last received, and whether it is stale
2874
+ * or loading. See `Remote.meta`.
2875
+ */
2876
+ interface ReadMeta {
2877
+ /** The newest server write among what is shown; none received reads `undefined`. */
2878
+ readonly updatedAt: number | undefined;
2879
+ /** Any shown field or connection is marked stale. */
2880
+ readonly stale: boolean;
2881
+ /** Any shown field or connection is in flight. */
2882
+ readonly loading: boolean;
2883
+ }
2884
+ interface MutateOptions {
2885
+ /** What the request changes before the server answers; released when it settles. */
2886
+ readonly optimistic?: ReadonlyArray<OptimisticOperation> | undefined;
2887
+ /** The clock `MutationSucceeded` stamps the answer with; default `Date.now`, read at each use. */
2888
+ readonly now?: (() => number) | undefined;
2889
+ }
2890
+ interface RetainOptions {
2891
+ /** The query connections the application shows, by `QueryRef` or identity. */
2892
+ readonly connections?: ReadonlyArray<ConnectionIdentity> | undefined;
2893
+ /** How long the roots must be stable before collecting; default none. */
2894
+ readonly grace?: Duration.Input | undefined;
2895
+ }
2896
+ /** How `Remote.observe` and `Remote.prefetch` treat fields the store already holds. */
2897
+ interface ObserveOptions {
2898
+ /** Default `RemotePolicy.cacheFirst`. */
2899
+ readonly policy?: RemotePolicy | undefined;
2900
+ /** The clock a refreshing policy reads; default `Date.now`, read at each use. */
2901
+ readonly now?: (() => number) | undefined;
2902
+ }
2903
+ /** How `Data.satisfy` reads: how many passes it may take, and the clock. */
2904
+ interface SatisfyOptions {
2905
+ /** At most this many passes over the Surfaces; default 8. */
2906
+ readonly passes?: number | undefined;
2907
+ /** The clock the reads are stamped with; default `Date.now`, read at each use. */
2908
+ readonly now?: (() => number) | undefined;
2909
+ }
2910
+ declare const RemoteUnsatisfied_base: Schema.Class<RemoteUnsatisfied, Schema.TaggedStruct<"RemoteUnsatisfied", {
2911
+ readonly surfaces: Schema.$Array<Schema.String>;
2912
+ readonly passes: Schema.Number;
2913
+ }>, import("effect/Cause").YieldableError>;
2914
+ /**
2915
+ * `Data.satisfy` reached its bound with Surfaces still reading, such as a
2916
+ * chain whose every read reveals one more. It names them, so a page that
2917
+ * would have rendered them loading fails instead. (A read the server leaves
2918
+ * unanswered settles as missing and ends the loop.)
2919
+ */
2920
+ declare class RemoteUnsatisfied extends RemoteUnsatisfied_base {}
2921
+ interface LiveOptions {
2922
+ /** The clock `LiveReceived` stamps events with; default `Date.now`, read at each use. */
2923
+ readonly now?: (() => number) | undefined;
2924
+ }
2925
+ /** A query the read entry runs, as its dependencies carry it: plain data Foldkit compares. */
2926
+ declare const PlannedQuery: Schema.Struct<{
2927
+ readonly identity: Schema.String;
2928
+ readonly window: Schema.Struct<{
2929
+ readonly first: Schema.optional<Schema.Number>;
2930
+ readonly last: Schema.optional<Schema.Number>;
2931
+ readonly after: Schema.optional<Schema.String>;
2932
+ readonly before: Schema.optional<Schema.String>;
2933
+ }>;
2934
+ readonly select: Schema.Codec<RelationRequirement, RelationRequirement, never, never>;
2935
+ }>;
2936
+ /** The dependencies of the read entry: the entity fields to read and the queries to run. */
2937
+ interface ReadDependencies {
2938
+ readonly requirements: ReadonlyArray<Requirement>;
2939
+ readonly queries: ReadonlyArray<Schema.Schema.Type<typeof PlannedQuery>>;
2940
+ /**
2941
+ * The highest generation the fields this entry reads were refreshed at: a
2942
+ * refresh of any of them restarts the entry, and a refresh of anything else
2943
+ * leaves it running.
2944
+ */
2945
+ readonly refresh: number;
2946
+ /**
2947
+ * Under a refreshing policy, when a value the entry holds next ages out and
2948
+ * what is due then. Time reaches Remote only as a Message: the entry sleeps
2949
+ * until then and emits `RefreshStarted`, which marks the fields stale, and
2950
+ * the plan that follows fetches them. A Model that does not change past its
2951
+ * `maxAge` is otherwise never looked at again.
2952
+ */
2953
+ readonly expires: Deadline | null;
2954
+ }
2955
+ declare const Remote: {
2956
+ /** The submodel's schema, the same for every domain; embed it in the application Model. */
2957
+ Model: Schema.Codec<RemoteModel, unknown, never, never>;
2958
+ /** The submodel's initial value. */
2959
+ initial: RemoteModel;
2960
+ /**
2961
+ * Remote's Message cases for `defineMessageUnion`: spread them into the
2962
+ * application's union, and reduce the ones `Remote.reduces` recognizes with
2963
+ * `RemoteDomain.reduce`.
2964
+ */
2965
+ messages: {
2966
+ ReadReceived: {
2967
+ requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
2968
+ result: Schema.Struct<{
2969
+ readonly entities: Schema.$Array<Schema.Struct<{
2970
+ readonly entity: Schema.String;
2971
+ readonly id: Schema.String;
2972
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
2973
+ }>>;
2974
+ readonly settled: Schema.$Array<Schema.Struct<{
2975
+ readonly entity: Schema.String;
2976
+ readonly id: Schema.String;
2977
+ readonly fields: Schema.$Array<Schema.String>;
2978
+ }>>;
2979
+ }>;
2980
+ now: Schema.Number;
2981
+ };
2982
+ ReadFailed: {
2983
+ requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
2984
+ error: Schema.Struct<{
2985
+ readonly _tag: Schema.String;
2986
+ readonly message: Schema.String;
2987
+ }>;
2988
+ stream: Schema.optional<Schema.String>;
2989
+ };
2990
+ RefreshStarted: {
2991
+ requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
2992
+ };
2993
+ ReadStarted: {
2994
+ requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
2995
+ refresh: Schema.optional<Schema.Number>;
2996
+ };
2997
+ QueryStarted: {
2998
+ connections: Schema.$Array<Schema.String>;
2999
+ };
3000
+ RetentionChanged: {
3001
+ roots: Schema.Struct<{
3002
+ readonly requirements: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
3003
+ readonly connections: Schema.$Array<Schema.Struct<{
3004
+ readonly identity: Schema.String;
3005
+ readonly select: Schema.optional<Schema.Codec<RelationRequirement, RelationRequirement, never, never>>;
3006
+ }>>;
3007
+ }>;
3008
+ };
3009
+ Hydrated: {
3010
+ connections: Schema.optional<Schema.Unknown>;
3011
+ entities: Schema.Unknown;
3012
+ merge: Schema.Union<readonly [Schema.Literal<"replace">, Schema.Literal<"preserve-existing">]>;
3013
+ };
3014
+ MutationStarted: {
3015
+ requestId: Schema.String;
3016
+ optimistic: Schema.optional<Schema.$Array<Schema.Unknown>>;
3017
+ };
3018
+ MutationSucceeded: {
3019
+ requestId: Schema.String;
3020
+ entities: Schema.$Array<Schema.Struct<{
3021
+ readonly entity: Schema.String;
3022
+ readonly id: Schema.String;
3023
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
3024
+ }>>;
3025
+ connections: Schema.optional<Schema.$Array<Schema.Unknown>>;
3026
+ deleted: Schema.optional<Schema.$Array<Schema.Struct<{
3027
+ readonly entity: Schema.String;
3028
+ readonly id: Schema.String;
3029
+ }>>>;
3030
+ now: Schema.Number;
3031
+ };
3032
+ MutationFailed: {
3033
+ requestId: Schema.String;
3034
+ error: Schema.Struct<{
3035
+ readonly _tag: Schema.String;
3036
+ readonly message: Schema.String;
3037
+ }>;
3038
+ };
3039
+ OverlayShown: {
3040
+ id: Schema.String;
3041
+ optimistic: Schema.$Array<Schema.Unknown>;
3042
+ };
3043
+ OverlayLifted: {
3044
+ id: Schema.String;
3045
+ };
3046
+ WindowGrown: {
3047
+ window: Schema.String;
3048
+ size: Schema.Number;
3049
+ };
3050
+ LiveReceived: {
3051
+ stream: Schema.String;
3052
+ event: Schema.Unknown;
3053
+ policy: Schema.optional<Schema.Unknown>;
3054
+ now: Schema.Number;
3055
+ };
3056
+ GapCleared: {
3057
+ stream: Schema.String;
3058
+ };
3059
+ ConnectionMerged: {
3060
+ connection: Schema.String;
3061
+ page: Schema.Unknown;
3062
+ refreshes: Schema.optional<Schema.Boolean>;
3063
+ select: Schema.optional<Schema.Codec<RelationRequirement, RelationRequirement, never, never>>;
3064
+ entities: Schema.optional<Schema.$Array<Schema.Struct<{
3065
+ readonly entity: Schema.String;
3066
+ readonly id: Schema.String;
3067
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
3068
+ }>>>;
3069
+ settled: Schema.optional<Schema.$Array<Schema.Struct<{
3070
+ readonly entity: Schema.String;
3071
+ readonly id: Schema.String;
3072
+ readonly fields: Schema.$Array<Schema.String>;
3073
+ }>>>;
3074
+ now: Schema.optional<Schema.Number>;
3075
+ };
3076
+ ConnectionInvalidated: {
3077
+ connection: Schema.String;
3078
+ };
3079
+ ConnectionRefreshed: {
3080
+ connection: Schema.String;
3081
+ };
3082
+ QueryFailed: {
3083
+ connection: Schema.String;
3084
+ error: Schema.Struct<{
3085
+ readonly _tag: Schema.String;
3086
+ readonly message: Schema.String;
3087
+ }>;
3088
+ };
3089
+ };
3090
+ /** Whether a Message is one of Remote's, by tag. */
3091
+ reduces: <M extends {
3092
+ readonly _tag: string;
3093
+ }>(message: M) => message is Extract<M, {
3094
+ readonly _tag: RemoteMessageTag;
3095
+ }>;
3096
+ /**
3097
+ * Remote's Messages as one Schema, for a wrapper variant in the
3098
+ * application's union: `GotRemoteMessage: { message: Remote.Message }`. With
3099
+ * a wrapper, `update` matches the application's union exhaustively and
3100
+ * `Remote.fold` reduces what arrives inside it.
3101
+ */
3102
+ Message: import("foldkit/message").MessageUnion<{
3103
+ ReadReceived: {
3104
+ requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
3105
+ result: Schema.Struct<{
3106
+ readonly entities: Schema.$Array<Schema.Struct<{
3107
+ readonly entity: Schema.String;
3108
+ readonly id: Schema.String;
3109
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
3110
+ }>>;
3111
+ readonly settled: Schema.$Array<Schema.Struct<{
3112
+ readonly entity: Schema.String;
3113
+ readonly id: Schema.String;
3114
+ readonly fields: Schema.$Array<Schema.String>;
3115
+ }>>;
3116
+ }>;
3117
+ now: Schema.Number;
3118
+ };
3119
+ ReadFailed: {
3120
+ requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
3121
+ error: Schema.Struct<{
3122
+ readonly _tag: Schema.String;
3123
+ readonly message: Schema.String;
3124
+ }>;
3125
+ stream: Schema.optional<Schema.String>;
3126
+ };
3127
+ RefreshStarted: {
3128
+ requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
3129
+ };
3130
+ ReadStarted: {
3131
+ requests: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
3132
+ refresh: Schema.optional<Schema.Number>;
3133
+ };
3134
+ QueryStarted: {
3135
+ connections: Schema.$Array<Schema.String>;
3136
+ };
3137
+ RetentionChanged: {
3138
+ roots: Schema.Struct<{
3139
+ readonly requirements: Schema.$Array<Schema.Codec<Requirement, Requirement, never, never>>;
3140
+ readonly connections: Schema.$Array<Schema.Struct<{
3141
+ readonly identity: Schema.String;
3142
+ readonly select: Schema.optional<Schema.Codec<RelationRequirement, RelationRequirement, never, never>>;
3143
+ }>>;
3144
+ }>;
3145
+ };
3146
+ Hydrated: {
3147
+ connections: Schema.optional<Schema.Unknown>;
3148
+ entities: Schema.Unknown;
3149
+ merge: Schema.Union<readonly [Schema.Literal<"replace">, Schema.Literal<"preserve-existing">]>;
3150
+ };
3151
+ MutationStarted: {
3152
+ requestId: Schema.String;
3153
+ optimistic: Schema.optional<Schema.$Array<Schema.Unknown>>;
3154
+ };
3155
+ MutationSucceeded: {
3156
+ requestId: Schema.String;
3157
+ entities: Schema.$Array<Schema.Struct<{
3158
+ readonly entity: Schema.String;
3159
+ readonly id: Schema.String;
3160
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
3161
+ }>>;
3162
+ connections: Schema.optional<Schema.$Array<Schema.Unknown>>;
3163
+ deleted: Schema.optional<Schema.$Array<Schema.Struct<{
3164
+ readonly entity: Schema.String;
3165
+ readonly id: Schema.String;
3166
+ }>>>;
3167
+ now: Schema.Number;
3168
+ };
3169
+ MutationFailed: {
3170
+ requestId: Schema.String;
3171
+ error: Schema.Struct<{
3172
+ readonly _tag: Schema.String;
3173
+ readonly message: Schema.String;
3174
+ }>;
3175
+ };
3176
+ OverlayShown: {
3177
+ id: Schema.String;
3178
+ optimistic: Schema.$Array<Schema.Unknown>;
3179
+ };
3180
+ OverlayLifted: {
3181
+ id: Schema.String;
3182
+ };
3183
+ WindowGrown: {
3184
+ window: Schema.String;
3185
+ size: Schema.Number;
3186
+ };
3187
+ LiveReceived: {
3188
+ stream: Schema.String;
3189
+ event: Schema.Unknown;
3190
+ policy: Schema.optional<Schema.Unknown>;
3191
+ now: Schema.Number;
3192
+ };
3193
+ GapCleared: {
3194
+ stream: Schema.String;
3195
+ };
3196
+ ConnectionMerged: {
3197
+ connection: Schema.String;
3198
+ page: Schema.Unknown;
3199
+ refreshes: Schema.optional<Schema.Boolean>;
3200
+ select: Schema.optional<Schema.Codec<RelationRequirement, RelationRequirement, never, never>>;
3201
+ entities: Schema.optional<Schema.$Array<Schema.Struct<{
3202
+ readonly entity: Schema.String;
3203
+ readonly id: Schema.String;
3204
+ readonly values: Schema.$Record<Schema.String, Schema.Unknown>;
3205
+ }>>>;
3206
+ settled: Schema.optional<Schema.$Array<Schema.Struct<{
3207
+ readonly entity: Schema.String;
3208
+ readonly id: Schema.String;
3209
+ readonly fields: Schema.$Array<Schema.String>;
3210
+ }>>>;
3211
+ now: Schema.optional<Schema.Number>;
3212
+ };
3213
+ ConnectionInvalidated: {
3214
+ connection: Schema.String;
3215
+ };
3216
+ ConnectionRefreshed: {
3217
+ connection: Schema.String;
3218
+ };
3219
+ QueryFailed: {
3220
+ connection: Schema.String;
3221
+ error: Schema.Struct<{
3222
+ readonly _tag: Schema.String;
3223
+ readonly message: Schema.String;
3224
+ }>;
3225
+ };
3226
+ }>;
3227
+ /**
3228
+ * A bound domain under one wrapper variant of the application's union, the
3229
+ * same shape Foldkit gives a Submodel: `toParentMessage` wraps Remote's
3230
+ * Messages, the fold reduces them, and its `fetch`, `mutate`, and
3231
+ * `subscriptions` yield the wrapper. Spreading `Remote.messages` and
3232
+ * narrowing with `Remote.reduces` remains the shorter path for an
3233
+ * application whose `update` only reduces.
3234
+ *
3235
+ * @example
3236
+ * ```ts
3237
+ * const Message = defineMessageUnion({ GotRemoteMessage: { message: Remote.Message } })
3238
+ * const foldData = Remote.fold(Data, message => Message.GotRemoteMessage({ message }))
3239
+ *
3240
+ * const update = (model: Model, message: Message): Return =>
3241
+ * Message.match(message, {
3242
+ * GotRemoteMessage: ({ message }) => foldData(model, message),
3243
+ * })
3244
+ * const subscriptions = Subscription.make<Model, Message, RemoteClient>()(() =>
3245
+ * foldData.subscriptions({ page: Surface.at(ProjectPage, …) }),
3246
+ * )
3247
+ * ```
3248
+ */
3249
+ fold: <Domain extends RemoteDomain<any, any, any, any, any>, ParentMessage>(domain: Domain, toParentMessage: (message: RemoteMessage) => ParentMessage) => RemoteFold<ModelOfDomain<Domain>, ParentMessage, Domain>;
3250
+ /**
3251
+ * A patch of one entity's values, for a mutation's `optimistic` list or an
3252
+ * overlay. Takes a `foldkit-entity` Entity or a Remote descriptor alike, so
3253
+ * the domain you declared once is the one you patch:
3254
+ * `Remote.patch(Project, 'p1', { name: 'Apollo II' })`. Values are the
3255
+ * fields' wire shape, as the server writes them; a relation is its ref key
3256
+ * (`'User:u1'`).
3257
+ */
3258
+ patch: <E extends EntityLike>(entity: E, id: string, values: Partial<Schema.Struct.Encoded<FieldsOf<E>>>) => EntityPatch<NameOf<E>, FieldsOf<E>>;
3259
+ /**
3260
+ * A reference to one entity, for `ConnectionChange` and anything else that
3261
+ * names a row: `Remote.ref(Project, 'p3')`. Either kind of entity, as with
3262
+ * `Remote.patch`.
3263
+ */
3264
+ ref: <E extends EntityLike>(entity: E, id: string) => EntityRef<NameOf<E>, FieldsOf<E>>;
3265
+ /**
3266
+ * Declares a Remote domain and binds it to its place in the application Model
3267
+ * in one step; the result carries the application-facing operations. The
3268
+ * descriptor alone is `Remote.define`, the binding alone `Remote.at`.
3269
+ */
3270
+ make: <AppModel, Store extends RemoteModel, const Entities extends readonly EntityLike[], const Queries extends readonly QueryDescriptor<any, any, any>[] = readonly [], const Mutations extends readonly MutationDescriptor<any, any, any>[] = readonly []>(config: {
3271
+ readonly model: ModelRef<AppModel, Store>;
3272
+ readonly entities: Entities;
3273
+ readonly queries?: Queries;
3274
+ readonly mutations?: Mutations;
3275
+ }) => RemoteDomain<AppModel, Store, Entities, Queries, Mutations>;
3276
+ /**
3277
+ * Declares a Remote domain without binding it: its entities, queries, and
3278
+ * mutations, plus the submodel. For a domain reused across applications or
3279
+ * bound in a test; `Remote.make` is the one-step form.
3280
+ */
3281
+ define: <const Entities extends readonly EntityLike[], const Queries extends readonly QueryDescriptor<any, any, any>[] = readonly QueryDescriptor<any, any, any>[], const Mutations extends readonly MutationDescriptor<any, any, any>[] = readonly MutationDescriptor<any, any, any>[]>(config: {
3282
+ readonly entities: Entities;
3283
+ readonly queries?: Queries;
3284
+ readonly mutations?: Mutations;
3285
+ }) => RemoteDescriptor<Entities, Queries, Mutations>;
3286
+ /**
3287
+ * Binds a Remote domain to its store's location in the application Model. The
3288
+ * registered entity names are carried on the returned value, so `Remote.select`
3289
+ * rejects a selection for an entity this domain never declared.
3290
+ */
3291
+ at: <AppModel, Store extends RemoteModel, Entities extends readonly EntityLike[], Queries extends readonly QueryDescriptor<any, any, any>[], Mutations extends readonly MutationDescriptor<any, any, any>[]>(definition: RemoteDescriptor<Entities, Queries, Mutations>, store: ModelRef<AppModel, Store>) => BoundRemote<AppModel, Store, EntityName<Entities[number]>>;
3292
+ /**
3293
+ * The resume part for this domain, for `foldkit-ssr`'s `SSR.plan({ parts })`:
3294
+ * a server render sends what the plan's active Surfaces read from the store,
3295
+ * each connection with its boundaries and each live cursor with it, and
3296
+ * nothing else. `id` tells two domains in one application apart.
3297
+ */
3298
+ resume: <AppModel, Store extends RemoteModel>(domain: {
3299
+ readonly store: ModelRef<AppModel, Store>;
3300
+ }, options?: {
3301
+ readonly id?: string | undefined;
3302
+ }) => RemoteResumePart<AppModel>;
3303
+ /**
3304
+ * A Projection node that reads a `RemoteData` value out of the store. The id
3305
+ * is supplied by the caller, usually from a Surface's params. The assembled
3306
+ * value is decoded against the Selection, so malformed server data surfaces
3307
+ * as `Failed` instead of being asserted into `Value`. A present value with a
3308
+ * stale field reads as `Refreshing`: an observer is refetching it.
3309
+ */
3310
+ select: <AppModel, Store extends RemoteModel, Names extends string, Value, Name extends string>(bound: BoundRemote<AppModel, Store, Names>, given: EntitySelection<Value, Name> & Registered<Name, Names, "Entity">) => (id: string) => Projection<AppModel, RemoteData<Value>>;
3311
+ /**
3312
+ * When what a projection shows was last received, and whether it is stale
3313
+ * or loading. Pure, so a view can show "updated 5s ago" without I/O.
3314
+ *
3315
+ * `updatedAt` is the newest server write among what is shown, as the
3316
+ * store dates it; `undefined` when nothing shown was received (nothing
3317
+ * loaded, or only an optimistic preview). `stale` is any shown field or
3318
+ * connection marked stale; `loading` is any of them in flight. Optimistic
3319
+ * previews do not date: showing only one reads `updatedAt: undefined`.
3320
+ */
3321
+ meta: <AppModel, Store extends RemoteModel, Value>(bound: BoundRemote<AppModel, Store>, model: AppModel, projection: Projection<AppModel, Value>) => ReadMeta;
3322
+ /**
3323
+ * The pure plan for a projection against a Model: the requirements its
3324
+ * remote store does not satisfy, under `options` (freshness, force). A
3325
+ * Surface's projection is `surface.projection(params)`.
3326
+ */
3327
+ plan: <AppModel, Store extends RemoteModel, Value>(bound: BoundRemote<AppModel, Store>, model: AppModel, projection: Projection<AppModel, Value>, options?: PlanOptions) => ReadonlyArray<Requirement>;
3328
+ /**
3329
+ * The queries a projection needs run before its connections read: those the
3330
+ * Model does not hold, or holds stale (every one under `force`).
3331
+ */
3332
+ planQueries: <AppModel, Store extends RemoteModel, Value>(bound: BoundRemote<AppModel, Store>, model: AppModel, projection: Projection<AppModel, Value>, options?: PlanOptions) => ReadonlyArray<QueryRef<string, unknown>>;
3333
+ /**
3334
+ * The store reads see: the base store under the pending optimistic layers.
3335
+ * One store is shared by every read and plan of a Model whose remote state
3336
+ * has not changed.
3337
+ */
3338
+ storeOf: <AppModel, Store extends RemoteModel>(bound: BoundRemote<AppModel, Store>, model: AppModel) => EntityStore;
3339
+ /**
3340
+ * The projection read against the server-derived store alone: the same
3341
+ * requirements, planned the same way, with the pending optimistic layers and
3342
+ * connection overlays left off. See the bound `Remote.confirmed`.
3343
+ */
3344
+ confirmed: <AppModel, Store extends RemoteModel, P extends Projection<AppModel, any>>(bound: BoundRemote<AppModel, Store>, projection: P) => P;
3345
+ /**
3346
+ * Executes the plan against the `RemoteClient` and returns a new store. Used
3347
+ * for SSR route prefetch, hover prefetch, and tests. Never called during render.
3348
+ * `policy` decides what a present field means (default cache-first); `now`
3349
+ * is the clock it reads, so the planner itself stays pure and time-injected.
3350
+ */
3351
+ prefetch: <AppModel, Store extends RemoteModel, Value>(bound: BoundRemote<AppModel, Store, string>, model: AppModel, projection: Projection<AppModel, Value>, options?: ObserveOptions | undefined) => Effect.Effect<Readonly<Record<string, EntityEntry>>, RemoteReadError | RemoteProtocolError, RemoteClient>;
3352
+ /**
3353
+ * Marks what a projection, or a Surface without params, requires as due again.
3354
+ * Called from `update`: every selected field the store holds reads `Refreshing`,
3355
+ * and every loaded query connection is invalidated. Nothing is fetched here.
3356
+ * The read entries `Data.subscriptions` derives refetch it, because a stale
3357
+ * field or connection is planned again under every policy, so a refresh never
3358
+ * sends a request beside the entry already observing the same data.
3359
+ *
3360
+ * A refreshed connection's page replaces its pages, so items the server removed
3361
+ * or reordered follow it; pages loaded past the first are dropped and paged
3362
+ * again with `next`/`previous`. The read entries restart, so a read or query
3363
+ * sent before the refresh is not applied after it.
3364
+ *
3365
+ * It is also how a failed query is retried: a connection whose query failed
3366
+ * is not run again on its own, so its read stays `Failed` until this asks.
3367
+ *
3368
+ * The projection must be observed, which it is while it is on screen. Live
3369
+ * subscriptions are left as they are. For data nothing observes (SSR, tests),
3370
+ * use `Remote.prefetch` with `RemotePolicy.networkOnly`. Refreshing what is
3371
+ * already being refreshed returns the same Model.
3372
+ */
3373
+ refresh: <AppModel, Store extends RemoteModel>(bound: BoundRemote<AppModel, Store>, model: AppModel, target: Projection<AppModel, unknown> | Surface<AppModel, any, any, void>) => AppModel;
3374
+ /**
3375
+ * Forgets everything the server told this Model: values, tombstones,
3376
+ * unavailable fields, connections, live cursors, failures. What is known is
3377
+ * known for a principal, and this is the one boundary for a login, a logout
3378
+ * or a switch of organization: called from `update`, it performs no I/O, and
3379
+ * every active Surface's read and live entries restart, so the screen asks
3380
+ * again as whoever the client now is. A read or stream begun before is
3381
+ * interrupted rather than landing after. A mutation in flight is treated as
3382
+ * applied: its answer writes nothing here.
3383
+ */
3384
+ forget: <AppModel, Store extends RemoteModel>(bound: BoundRemote<AppModel, Store>, model: AppModel) => AppModel;
3385
+ /**
3386
+ * Writes a read result into the store, recording each field's applied window.
3387
+ * `requests` are the planned requirements the result answers.
3388
+ */
3389
+ writeRead: (store: EntityStore, requests: ReadonlyArray<Requirement>, result: Schema.Schema.Type<typeof ReadBatchResult>, now?: number) => EntityStore;
3390
+ /**
3391
+ * Adapts an Effect RPC client for `RemoteRpc` to `RemoteClient`, so an
3392
+ * application provides the transport's RPC layer instead of writing the
3393
+ * `LiveChange`-to-`LiveEvent` mapping by hand. The client `RpcClient.make`
3394
+ * builds is accepted as it is: when its transport fails (`RpcClientError`),
3395
+ * the call fails with its own Remote error, which the application shows and
3396
+ * retries like any failed read, query, mutation or live stream.
3397
+ */
3398
+ /**
3399
+ * Remote's client over any way of sending one JSON request and receiving its
3400
+ * answer, for `clientLayer`: a worker, a server in the page. `RemoteServer.answer`
3401
+ * is the other end.
3402
+ */
3403
+ json: (send: RemoteJsonSend) => RemoteRpcClient;
3404
+ /**
3405
+ * Remote's client over HTTP, for `clientLayer`: each call a `POST` of the JSON
3406
+ * request to `url`. `headers` is read per request (a session token, say).
3407
+ */
3408
+ http: (url: string, options?: {
3409
+ readonly headers?: () => Readonly<Record<string, string>>;
3410
+ }) => RemoteRpcClient;
3411
+ clientLayer: <R = never>(client: RemoteRpcClient<R, RpcClientError.RpcClientError>, options?: CoalesceOptions) => Layer.Layer<RemoteClient, never, R>;
3412
+ /**
3413
+ * Wraps a `RemoteClient` layer so its reads coalesce: requirements issued
3414
+ * together become one batch, and a requirement already in flight is joined.
3415
+ * `Remote.clientLayer` applies this; use it on a hand-written client.
3416
+ */
3417
+ coalesced: <E, R>(layer: Layer.Layer<RemoteClient, E, R>, options?: CoalesceOptions) => Layer.Layer<RemoteClient, E, R>;
3418
+ /**
3419
+ * A Foldkit Subscription entry that keeps the cache to what the active
3420
+ * Surfaces reach. `projections` are the ones the application observes (the
3421
+ * same it passes to `Remote.observe`), `connections` the query connections
3422
+ * it shows; anything else is collected once the roots have been stable for
3423
+ * `grace`, so a route transition that comes straight back does not thrash.
3424
+ */
3425
+ retain: <AppModel, Message = RemoteMessage>(projections: ReadonlyArray<Projection<AppModel, unknown>>, toMessage?: (message: RemoteMessage) => Message, options?: RetainOptions) => EntryWithoutKeepAlive<AppModel, Message, RetentionRoots, never>;
3426
+ /**
3427
+ * Runs a `Query` through `RemoteClient`, encoding its input from the ref.
3428
+ * Pair the result with `Remote.queryMessage` to merge the page into the Model.
3429
+ * With `select`, the server also returns the selected fields of the page's
3430
+ * items, so one response populates both the connection and the store.
3431
+ */
3432
+ query: <Name extends string, Input>(ref: QueryRef<Name, Input>, select?: RelationRequirement | undefined) => Effect.Effect<{
3433
+ readonly edges: readonly {
3434
+ readonly entity: string;
3435
+ readonly id: string;
3436
+ readonly key: string;
3437
+ }[];
3438
+ readonly start: {
3439
+ readonly _tag: "Terminal";
3440
+ } | {
3441
+ readonly _tag: "Cursor";
3442
+ readonly cursor: string;
3443
+ } | {
3444
+ readonly _tag: "Unknown";
3445
+ };
3446
+ readonly end: {
3447
+ readonly _tag: "Terminal";
3448
+ } | {
3449
+ readonly _tag: "Cursor";
3450
+ readonly cursor: string;
3451
+ } | {
3452
+ readonly _tag: "Unknown";
3453
+ };
3454
+ readonly entities?: readonly {
3455
+ readonly entity: string;
3456
+ readonly id: string;
3457
+ readonly values: {
3458
+ readonly [x: string]: unknown;
3459
+ };
3460
+ }[] | undefined;
3461
+ readonly settled?: readonly {
3462
+ readonly entity: string;
3463
+ readonly id: string;
3464
+ readonly fields: readonly string[];
3465
+ }[] | undefined;
3466
+ }, RemoteQueryError, RemoteClient>;
3467
+ /** The `RemoteMessage` that merges a query page into its connection. */
3468
+ queryMessage: <Name extends string, Input>(ref: QueryRef<Name, Input>, result: Schema.Schema.Type<typeof QueryResult>, select?: RelationRequirement | undefined, now?: number | undefined) => RemoteMessage;
3469
+ /**
3470
+ * The edges a connection shows: its server-known region with pending and
3471
+ * confirmed overlays placed around it, minus removed edges and edges whose
3472
+ * target is a tombstone.
3473
+ */
3474
+ visibleItems: (model: RemoteModel, connection: ConnectionIdentity) => ReadonlyArray<Edge>;
3475
+ /** A pure, serializable view of the whole cache. */
3476
+ inspect: (model: RemoteModel) => RemoteInspection;
3477
+ /** A pure, serializable view of one entity, or `undefined` if unknown. */
3478
+ inspectEntity: (model: RemoteModel, key: string) => RemoteInspection["entities"][number] | undefined;
3479
+ /**
3480
+ * Runs a mutation through `RemoteClient`, decoding its typed Output and
3481
+ * returning the result's normalized patches so the caller can reconcile them
3482
+ * through `updateRemote`'s `MutationSucceeded` (or `Remote.mutateInto`).
3483
+ */
3484
+ mutate: <Name extends string, Input, Output>(mutation: MutationDescriptor<Name, Input, Output>, input: Input, requestId: string) => Effect.Effect<{
3485
+ output: Output;
3486
+ entities: readonly {
3487
+ readonly entity: string;
3488
+ readonly id: string;
3489
+ readonly values: {
3490
+ readonly [x: string]: unknown;
3491
+ };
3492
+ }[];
3493
+ connections: ConnectionChange[];
3494
+ deleted: readonly {
3495
+ readonly entity: string;
3496
+ readonly id: string;
3497
+ }[];
3498
+ }, RemoteMutationError, RemoteClient>;
3499
+ /**
3500
+ * Runs a mutation and reconciles its patches into a `RemoteModel` in one step,
3501
+ * returning the new model alongside the typed Output. The model-level form of
3502
+ * `MutationStarted` → `RemoteClient.mutate` → `MutationSucceeded`; in an
3503
+ * application the three are `update` (with `optimistic`), a Command, and the
3504
+ * Message the Command returns, so the optimistic operations show meanwhile.
3505
+ */
3506
+ mutateInto: <Name extends string, Input, Output, AppModel, Store extends RemoteModel>(bound: BoundRemote<AppModel, Store, string>, model: AppModel, mutation: MutationDescriptor<Name, Input, Output>, input: Input, requestId: string, options?: MutateOptions | undefined) => Effect.Effect<{
3507
+ output: Output;
3508
+ model: AppModel;
3509
+ }, RemoteMutationError, RemoteClient>;
3510
+ /**
3511
+ * A Foldkit Subscription entry that plans a Surface's missing fields from the
3512
+ * Model and fetches them through `RemoteClient`, emitting a `RemoteMessage`
3513
+ * per outcome. Wrap it in an application Message (`toMessage`) and reduce it
3514
+ * with the domain's `update`. Under a refreshing `policy` the entry first
3515
+ * emits `RefreshStarted`, so the fields being refetched read as `Refreshing`
3516
+ * while the request is pending.
3517
+ */
3518
+ observe: <AppModel, Store extends RemoteModel, Names extends string, Model, SurfaceMessage, Params, Message = RemoteMessage>(bound: BoundRemote<AppModel, Store, Names>, surface: Surface<AppModel, Model, SurfaceMessage, Params>, params: Params, toMessage?: (message: RemoteMessage) => Message, options?: ObserveOptions) => EntryWithoutKeepAlive<AppModel, Message, ReadDependencies, RemoteClient>;
3519
+ /**
3520
+ * A Foldkit Subscription entry that consumes the live stream for a Surface's
3521
+ * requirements, emitting a `LiveReceived` per event and a `ReadFailed`
3522
+ * carrying its `stream` when the stream breaks (including
3523
+ * `ResumeUnavailable`). That records a gap on the stream rather than a failed
3524
+ * read, since nothing was being read. The resume cursor is read
3525
+ * from `RemoteModel.live`, so the application tracks no cursor of its own.
3526
+ */
3527
+ live: <AppModel, Store extends RemoteModel, Names extends string, Model, SurfaceMessage, Params, Message = RemoteMessage>(bound: BoundRemote<AppModel, Store, Names>, surface: Surface<AppModel, Model, SurfaceMessage, Params>, params: Params, toMessage?: (message: RemoteMessage) => Message, options?: LiveOptions) => EntryWithoutKeepAlive<AppModel, Message, LiveDependencies, RemoteClient>;
3528
+ };
3529
+ //#endregion
3530
+ export { Entity$2 as $, isGapped as $i, Snapshot as $n, ResultOf as $r, failureOf as $t, SelectsEntity as A, readField as Ai, PageSize as An, pruneOverlays as Ar, RemoteJsonRequest as At, ExplainedDependencies as B, remoteDataSchema as Bi, RelationRequest as Bn, RemoteRequirements as Br, CoalesceOptions as Bt, RemoteDomain as C, entry as Ci, LiveRequirement as Cn, OptimisticOperation as Cr, isRefPage as Ct, RemoteWiring as D, isTombstone as Di, MutationRequest as Dn, beginOptimistic as Dr, relationShape as Dt, RemoteUnsatisfied as E, isFieldUnavailable as Ei, Mutate as En, addOverlay as Er, relationAlias as Et, PlanFreshness as F, writeEntities as Fi, REMOTE_PROTOCOL_VERSION as Fn, visibleItems as Fr, connectionChangeOf as Ft, inspectRemote as G, Edge as Gi, RemoteReadError as Gn, IDENTITY_SEPARATOR as Gr, RemoteResumePart as Gt, ReadDiagnosis as H, Boundary as Hi, RemoteMutationError as Hn, connectionsOf as Hr, coalesceQueries as Ht, PlanOptions as I, writeEntity as Ii, Read as In, visibleStore as Ir, liveEventOf as It, Matched as J, cursor as Ji, WindowSchema as Jn, Query$1 as Jr, RemoteMessage as Jt, Belongs as K, EdgeRef as Ki, RemoteRpc as Kn, LiveInsertion as Kr, Failures as Kt, deadlineOf as L, Freshness as Li, ReadBatch as Ln, ConnectionRequirement as Lr, mutateRemote as Lt, SubscriptionsOptions as M, setStale as Mi, QueryRequest as Mn, removeOverlay as Mr, RemoteClient as Mt, RemotePolicy as N, setUnavailable as Ni, QueryResult as Nn, settleFailure as Nr, RemoteRpcClient as Nt, RetainOptions as O, markStale as Oi, MutationResult as On, connectionIdentity as Or, targetsOf as Ot, Deadline as P, tombstone as Pi, QueryRpc as Pn, settleSuccess as Pr, coalescedLayer as Pt, AnySchema as Q, hasPrevious as Qi, RemotePersistence as Qn, QueryWindow as Qr, emptyRefresh as Qt, plan as R, RemoteData as Ri, ReadBatchResult as Rn, RelationRequirement as Rr, remoteError as Rt, RemoteDescriptor as S, entityKey as Si, LiveEdge as Sn, EntityLayer as Sr, aliasedField as St, RemoteFold as T, isFieldStale as Ti, MAX_RELATION_DEPTH as Tn, addLayer as Tr, refsIn as Tt, RemoteInspection as U, Connection as Ui, RemoteProtocolError as Un, requirementsOf as Ur, coalesceReads as Ut, QueryExplanation as V, remoteErrorSchema as Vi, RemoteLiveError as Vn, Requirement as Vr, QueryRun as Vt, inspectEntity as W, Cursor as Wi, RemoteQueryError as Wn, ConnectionSpec as Wr, requirementKey as Wt, belongsEncoded as X, emptyConnection as Xi, MergePolicy as Xn, QueryInputs as Xr, RemoteMessageTag as Xt, MatchingOptions as Y, edge as Yi, WireBoundary as Yn, QueryDescriptor as Yr, RemoteMessageInput as Yt, matching as Z, hasNext as Zi, REMOTE_CACHE_VERSION as Zn, QueryRef as Zr, RemoteModel as Zt, QueryWindowOptions as _, EntityKey as _i, withRefreshRequested as _n, liveHasNext as _r, RefParts as _t, FoldedMutationStarted as a, MutationStatus as ai, isQueryLoading as an, reachable as ar, RefPage as at, Registered as b, clearStale as bi, Live as bn, ConnectionIdentity as br, RelationKind as bt, ModelOfDomain as c, SchemaOrFields as ci, onlyOverlaid as cn, EntityApplied as cr, SelectionOf as ct, ObserveOptions as d, emptyMutationState as di, remoteMessageCases as dn, LiveOutcome as dr, assemble as dt, items as ea, stableStringify as ei, forgetRemote as en, SnapshotOptions as er, EntityDescriptor as et, QueryEntity as f, failMutation as fi, remoteMessageSchema as fn, LiveState as fr, pageSchema as ft, QueryRequirement as g, EntityEntry as gi, windowGrowthKey as gn, emptyLiveState as gr, RefPageValue as gt, QueryProjection as h, schemaOf as hi, updateRemote as hn, classifyLive as hr, RELATION_ALIAS as ht, EntitySelection as i, unknown as ia, MutationState as ii, isLoadingThrough as in, gc as ir, RefKey as it, SubscriptionEntries as j, remove as ji, QueryEdge as jn, removeLayer as jr, RemoteJsonSend as jt, SatisfyOptions as k, missingFields as ki, NormalizedEntity as kn, emptyOptimistic as kr, RemoteJsonAnswer as kt, MutateOptions as l, TypeOf as li, refreshIsInFlight as ln, LiveCursor as lr, SelectionValue as lt, QueryOptions as m, reconcileMutation as mi, retentionRootsSchema as mn, applyEntityEvent as mr, unavailableOf as mt, DomainMutateOptions as n, segment as na, MutationAnswer as ni, isFieldFailed as nn, Retained as nr, EntityRef as nt, LiveDependencies as o, NormalizedPatch as oi, isRemoteMessage as on, BoundaryCounts as or, Page as ot, QueryInput as p, mutationStatus as pi, remoteModelSchema as pn, applyConnectionEvent as pr, relationOf as pt, Judged as q, Segment as qi, SettledFields as qn, LivePolicy as qr, RefreshState as qt, EntityLike as r, terminal as ra, MutationDescriptor as ri, isLoading as rn, RetentionRoots as rr, FieldsFrom as rt, LiveOptions as s, Reconciled as si, noFailures as sn, ConnectionApplied as sr, Selection as st, BoundRemote as t, merge as ta, Mutation as ti, initialRemoteModel as tn, ConnectionRoot as tr, EntityPatch as tt, MutationStarted as u, beginMutation as ui, refreshedAt as un, LiveEvent as ur, SelectionValueOf as ut, ReadDependencies as v, EntityStore as vi, writeRead as vn, liveHasPrevious as vr, RelationAnnotation as vt, RemoteEntry as w, hasField as wi, MAX_FIELDS_PER_REQUEST as wn, OptimisticState as wr, refParts as wt, Remote as x, emptyStore as xi, LiveChange as xn, ConnectionOverlay as xr, RelationShape as xt, ReadMeta as y, EntityWrite as yi, ConnectionChangeSchema as yn, ConnectionChange as yr, RelationEntityAnnotation as yt, windowKey as z, RemoteError as zi, ReadRequest as zn, RemoteConnections as zr, BatchRead as zt };
3531
+ //# sourceMappingURL=index-Dh4qdXfE.d.mts.map