foldkit-remote 0.21.0 → 0.22.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.
Files changed (198) hide show
  1. package/README.md +977 -193
  2. package/dist/answerGaps.d.ts +16 -0
  3. package/dist/answerGaps.d.ts.map +1 -0
  4. package/dist/answerGaps.js +60 -0
  5. package/dist/answerGaps.js.map +1 -0
  6. package/dist/client-B055kQuP.d.ts +110 -0
  7. package/dist/client-B055kQuP.d.ts.map +1 -0
  8. package/dist/client.d.ts +2 -0
  9. package/dist/client.js +142 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/coalesce-CLAr92Nk.d.ts +34 -0
  12. package/dist/coalesce-CLAr92Nk.d.ts.map +1 -0
  13. package/dist/coalesce.d.ts +2 -0
  14. package/dist/coalesce.js +131 -0
  15. package/dist/coalesce.js.map +1 -0
  16. package/dist/connection-BRyaJy89.d.ts +45 -0
  17. package/dist/connection-BRyaJy89.d.ts.map +1 -0
  18. package/dist/connection.d.ts +2 -0
  19. package/dist/connection.js +170 -0
  20. package/dist/connection.js.map +1 -0
  21. package/dist/data.d.ts +7 -0
  22. package/dist/data.d.ts.map +1 -0
  23. package/dist/data.js +21 -0
  24. package/dist/data.js.map +1 -0
  25. package/dist/diagnostics-DHhVYflV.d.ts +125 -0
  26. package/dist/diagnostics-DHhVYflV.d.ts.map +1 -0
  27. package/dist/diagnostics.d.ts +2 -0
  28. package/dist/diagnostics.js +60 -0
  29. package/dist/diagnostics.js.map +1 -0
  30. package/dist/entity-CgsG5Uel.d.ts +196 -0
  31. package/dist/entity-CgsG5Uel.d.ts.map +1 -0
  32. package/dist/entity-DuDxaa3n.js +279 -0
  33. package/dist/entity-DuDxaa3n.js.map +1 -0
  34. package/dist/entity.d.ts +2 -0
  35. package/dist/entity.js +1 -0
  36. package/dist/held.d.ts +19 -0
  37. package/dist/held.d.ts.map +1 -0
  38. package/dist/held.js +70 -0
  39. package/dist/held.js.map +1 -0
  40. package/dist/impact.d.ts +79 -0
  41. package/dist/impact.d.ts.map +1 -0
  42. package/dist/impact.js +166 -0
  43. package/dist/impact.js.map +1 -0
  44. package/dist/index.d.ts +1542 -0
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +2791 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/inspect-DtRQGCRP.d.ts +134 -0
  49. package/dist/inspect-DtRQGCRP.d.ts.map +1 -0
  50. package/dist/inspect.d.ts +2 -0
  51. package/dist/inspect.js +33 -0
  52. package/dist/inspect.js.map +1 -0
  53. package/dist/json-DowLl1eB.d.ts +52 -0
  54. package/dist/json-DowLl1eB.d.ts.map +1 -0
  55. package/dist/json.d.ts +2 -0
  56. package/dist/json.js +123 -0
  57. package/dist/json.js.map +1 -0
  58. package/dist/law.d.ts +56 -0
  59. package/dist/law.d.ts.map +1 -0
  60. package/dist/law.js +201 -0
  61. package/dist/law.js.map +1 -0
  62. package/dist/live-BpTzlCnY.d.ts +79 -0
  63. package/dist/live-BpTzlCnY.d.ts.map +1 -0
  64. package/dist/live.d.ts +2 -0
  65. package/dist/live.js +126 -0
  66. package/dist/live.js.map +1 -0
  67. package/dist/matching-DF5F9Us8.d.ts +100 -0
  68. package/dist/matching-DF5F9Us8.d.ts.map +1 -0
  69. package/dist/matching.d.ts +2 -0
  70. package/dist/matching.js +172 -0
  71. package/dist/matching.js.map +1 -0
  72. package/dist/model-B6zk1NMB.d.ts +710 -0
  73. package/dist/model-B6zk1NMB.d.ts.map +1 -0
  74. package/dist/model.d.ts +2 -0
  75. package/dist/model.js +1308 -0
  76. package/dist/model.js.map +1 -0
  77. package/dist/mutation.d.ts +2 -0
  78. package/dist/mutation.js +612 -0
  79. package/dist/mutation.js.map +1 -0
  80. package/dist/optimistic-CECsfNGY.d.ts +523 -0
  81. package/dist/optimistic-CECsfNGY.d.ts.map +1 -0
  82. package/dist/optimistic.d.ts +2 -0
  83. package/dist/optimistic.js +336 -0
  84. package/dist/optimistic.js.map +1 -0
  85. package/dist/outbox-DNuc4kZp.d.ts +259 -0
  86. package/dist/outbox-DNuc4kZp.d.ts.map +1 -0
  87. package/dist/outbox.d.ts +2 -0
  88. package/dist/outbox.js +326 -0
  89. package/dist/outbox.js.map +1 -0
  90. package/dist/patchValues.d.ts +10 -0
  91. package/dist/patchValues.d.ts.map +1 -0
  92. package/dist/patchValues.js +57 -0
  93. package/dist/patchValues.js.map +1 -0
  94. package/dist/persistence-CCMnvg7-.d.ts +114 -0
  95. package/dist/persistence-CCMnvg7-.d.ts.map +1 -0
  96. package/dist/persistence.d.ts +2 -0
  97. package/dist/persistence.js +205 -0
  98. package/dist/persistence.js.map +1 -0
  99. package/dist/placement-jZdsIpmj.d.ts +50 -0
  100. package/dist/placement-jZdsIpmj.d.ts.map +1 -0
  101. package/dist/placement.d.ts +2 -0
  102. package/dist/placement.js +116 -0
  103. package/dist/placement.js.map +1 -0
  104. package/dist/plan-D9cftxC_.d.ts +35 -0
  105. package/dist/plan-D9cftxC_.d.ts.map +1 -0
  106. package/dist/plan.d.ts +2 -0
  107. package/dist/plan.js +100 -0
  108. package/dist/plan.js.map +1 -0
  109. package/dist/policy-DsWHmIAq.d.ts +42 -0
  110. package/dist/policy-DsWHmIAq.d.ts.map +1 -0
  111. package/dist/policy.d.ts +2 -0
  112. package/dist/policy.js +32 -0
  113. package/dist/policy.js.map +1 -0
  114. package/dist/{port.d.mts → port.d.ts} +3 -2
  115. package/dist/port.d.ts.map +1 -0
  116. package/dist/{port.mjs → port.js} +3 -2
  117. package/dist/port.js.map +1 -0
  118. package/dist/query-BuIU93xA.d.ts +141 -0
  119. package/dist/query-BuIU93xA.d.ts.map +1 -0
  120. package/dist/query.d.ts +2 -0
  121. package/dist/query.js +0 -0
  122. package/dist/query.js.map +1 -0
  123. package/dist/record.d.ts +11 -0
  124. package/dist/record.d.ts.map +1 -0
  125. package/dist/record.js +21 -0
  126. package/dist/record.js.map +1 -0
  127. package/dist/relation-BLBGOZom.d.ts +59 -0
  128. package/dist/relation-BLBGOZom.d.ts.map +1 -0
  129. package/dist/relation.d.ts +2 -0
  130. package/dist/relation.js +93 -0
  131. package/dist/relation.js.map +1 -0
  132. package/dist/remoteData-mK1suYi1.d.ts +148 -0
  133. package/dist/remoteData-mK1suYi1.d.ts.map +1 -0
  134. package/dist/remoteData.d.ts +2 -0
  135. package/dist/remoteData.js +179 -0
  136. package/dist/remoteData.js.map +1 -0
  137. package/dist/reporting.d.ts +12 -0
  138. package/dist/reporting.d.ts.map +1 -0
  139. package/dist/reporting.js +45 -0
  140. package/dist/reporting.js.map +1 -0
  141. package/dist/requirement-D57S2LpH.d.ts +64 -0
  142. package/dist/requirement-D57S2LpH.d.ts.map +1 -0
  143. package/dist/requirement.d.ts +2 -0
  144. package/dist/requirement.js +114 -0
  145. package/dist/requirement.js.map +1 -0
  146. package/dist/resume-Ct5R6yli.d.ts +92 -0
  147. package/dist/resume-Ct5R6yli.d.ts.map +1 -0
  148. package/dist/resume.d.ts +2 -0
  149. package/dist/resume.js +222 -0
  150. package/dist/resume.js.map +1 -0
  151. package/dist/retain-BfNTvBRb.d.ts +48 -0
  152. package/dist/retain-BfNTvBRb.d.ts.map +1 -0
  153. package/dist/retain.d.ts +2 -0
  154. package/dist/retain.js +107 -0
  155. package/dist/retain.js.map +1 -0
  156. package/dist/selection.d.ts +2 -0
  157. package/dist/selection.js +1 -0
  158. package/dist/shown.d.ts +20 -0
  159. package/dist/shown.d.ts.map +1 -0
  160. package/dist/shown.js +40 -0
  161. package/dist/shown.js.map +1 -0
  162. package/dist/sse-C7LhdbiQ.d.ts +17 -0
  163. package/dist/sse-C7LhdbiQ.d.ts.map +1 -0
  164. package/dist/sse.d.ts +2 -0
  165. package/dist/sse.js +127 -0
  166. package/dist/sse.js.map +1 -0
  167. package/dist/store-ah2qjcJW.d.ts +100 -0
  168. package/dist/store-ah2qjcJW.d.ts.map +1 -0
  169. package/dist/store.d.ts +2 -0
  170. package/dist/store.js +218 -0
  171. package/dist/store.js.map +1 -0
  172. package/dist/testing.d.ts +133 -0
  173. package/dist/testing.d.ts.map +1 -0
  174. package/dist/testing.js +0 -0
  175. package/dist/testing.js.map +1 -0
  176. package/dist/why-kgp_Wr3z.d.ts +483 -0
  177. package/dist/why-kgp_Wr3z.d.ts.map +1 -0
  178. package/dist/why.d.ts +2 -0
  179. package/dist/why.js +293 -0
  180. package/dist/why.js.map +1 -0
  181. package/dist/whyReasons.d.ts +42 -0
  182. package/dist/whyReasons.d.ts.map +1 -0
  183. package/dist/whyReasons.js +211 -0
  184. package/dist/whyReasons.js.map +1 -0
  185. package/dist/wire-DthPcTM6.d.ts +787 -0
  186. package/dist/wire-DthPcTM6.d.ts.map +1 -0
  187. package/dist/wire.d.ts +2 -0
  188. package/dist/wire.js +329 -0
  189. package/dist/wire.js.map +1 -0
  190. package/package.json +18 -13
  191. package/dist/index-YyucgTYm.d.mts +0 -4115
  192. package/dist/index-YyucgTYm.d.mts.map +0 -1
  193. package/dist/index.d.mts +0 -2
  194. package/dist/index.mjs +0 -1
  195. package/dist/port.d.mts.map +0 -1
  196. package/dist/port.mjs.map +0 -1
  197. package/dist/src-lVP_7bf4.mjs +0 -6382
  198. package/dist/src-lVP_7bf4.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["DomainEntity","Relational","jsonClient","httpClient","httpWithLiveClient"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-remote` — normalized application-facing server state.\n *\n * The pure core (entities, selections, the store, the planner, connections,\n * live classification, optimistic layers) performs no I/O. The `Remote.*`\n * helpers that read or mutate go through the `RemoteClient` Effect service.\n */\nimport {\n Clock,\n Duration,\n Effect,\n Layer,\n Match,\n Option,\n Queue,\n Record,\n Result,\n Schema,\n Stream,\n} from 'effect'\nimport { KeyValueStore } from 'effect/persistence'\nimport {\n Derivation,\n Entity as DomainEntity,\n Query as Relational,\n QueryEvaluateError,\n Operators,\n ReadFilter,\n SelectionTypeId,\n type ExprContext,\n type MemoryOperators,\n} from 'foldkit-entity'\nimport type * as Domain from 'foldkit-entity'\nimport type { RpcClientError } from 'effect/rpc'\nimport { mapMessage, type Command } from 'foldkit/command'\nimport { defineMessageUnion } from 'foldkit/message'\nimport type * as Update from 'foldkit/update'\nimport * as Subscription from 'foldkit/subscription'\nimport type { EntryWithoutKeepAlive } from 'foldkit/subscription'\nimport {\n type ActiveSurface,\n type Contract,\n type Invalid,\n ModelRef,\n type Focus,\n type Projection,\n type Surface,\n type SurfaceSource,\n type Wiring,\n} from 'foldkit-surface'\nimport {\n RemoteClient,\n coalescedLayer,\n liveEventOf,\n mintOperation,\n mutateRemote,\n remoteError,\n type RemoteRpcClient,\n} from './client.js'\nimport {\n emptyConnection,\n hasNext,\n hasPrevious,\n isGapped,\n items,\n type Connection,\n type Edge,\n} from './connection.js'\nimport {\n Entity,\n type EntityDescriptor,\n type EntityPatch,\n type EntityRef,\n type FieldsFrom,\n type PatchValues,\n} from './entity.js'\nimport { wireValues } from './patchValues.js'\nimport { EntityChange, Impact, changesOf, impactOn, type HeldConnection } from './impact.js'\nimport { belongsEncoded, matching, type Judged, type Matched } from './matching.js'\nimport { readWhy, regressed, Why, type ReadStep, type ReadWhy } from './why.js'\nimport { failedReasons, reasonsOf, type WhyReader } from './whyReasons.js'\n\n/** A body's dependencies as an explanation carries them: without the owner identity, which holds a symbol. */\nconst explainedDependencies = (dependencies: Domain.Dependencies): ExplainedDependencies => ({\n fields: dependencies.fields.map(({ entity, key }) => ({ entity, key })),\n inputs: dependencies.inputs,\n operations: dependencies.operations,\n operators: dependencies.operators.map(({ id, version }) => ({ id, version })),\n})\nimport {\n inspectEntity,\n inspectRemote,\n type ExplainedDependencies,\n type QueryExplanation,\n type RemoteInspection,\n} from './inspect.js'\nimport type { LiveCursor, LiveEvent } from './live.js'\nimport {\n failureOf,\n initialRemoteModel,\n overlaysOf,\n isFieldFailed,\n isLoadingThrough,\n onlyOverlaid,\n windowGrowthKey,\n isQueryLoading,\n isRemoteMessage,\n dismissQueued,\n forgetRemote,\n refreshIsInFlight,\n refreshedAt,\n remoteMessageCases,\n remoteMessageSchema,\n remoteModelSchema,\n retentionRootsSchema,\n invalidateConnections,\n updateRemote,\n withRefreshRequested,\n writeRead,\n type RemoteMessage,\n type RemoteMessageInput,\n type RemoteMessageTag,\n type RemoteModel,\n} from './model.js'\nimport {\n forgetFailure,\n mutationStatus,\n predictionOfWrite,\n brokenByWrite,\n forbiddenByWrite,\n DerivedBy,\n type MutationDescriptor,\n type MutationStatus,\n type NormalizedPatch,\n type PendingDelete,\n} from './mutation.js'\nimport {\n connectionIdentity,\n emptyOptimistic,\n goneIn,\n heldOnlyByRequests,\n plannedStore,\n resolvedPatches,\n visibleItems,\n visibleStore,\n type ConnectionIdentity,\n type ConnectionOverlay,\n type EntityLayer,\n type OptimisticState,\n type OptimisticOperation,\n} from './optimistic.js'\nimport { RowPlace, placeIn, withEdge } from './placement.js'\nimport { deadlineOf, plan, type Deadline, type PlanOptions } from './plan.js'\nimport { RemotePolicy } from './policy.js'\nimport { IDENTITY_SEPARATOR, stableStringify } from './query.js'\nimport type { ConnectionSpec, LivePolicy, QueryDescriptor, QueryRef, QueryWindow } from './query.js'\nimport { remoteDataSchema, type RemoteData, type RemoteError } from './remoteData.js'\nimport type { ConnectionRoot, RetentionRoots } from './retain.js'\nimport {\n Selection,\n assemble,\n pageSchema,\n relationOf,\n unavailableOf,\n type Page,\n} from './selection.js'\nimport { sameData } from './data.js'\nimport {\n emptyStore,\n entityKey,\n isTombstone,\n missingFields,\n readField,\n type EntityStore,\n} from './store.js'\nimport { RemotePersistence, type Snapshot } from './persistence.js'\nimport {\n backoff,\n channelFor,\n headOf,\n mergeStored,\n onlineAgain,\n operationOf,\n outboxStatus,\n readEntries,\n othersWaiting,\n readStored,\n sendLock,\n storedFromText,\n storedOf,\n storedText,\n storeLock,\n StoredWrite,\n settledIn,\n withLock,\n type OutboxStatus,\n type RetryOptions,\n type StoredOutbox,\n} from './outbox.js'\nimport { targetsOf } from './relation.js'\nimport {\n QueryRequest,\n QueryResult,\n ReadRequest,\n RelationRequest,\n REMOTE_PROTOCOL_VERSION,\n WindowSchema,\n RemoteLiveError,\n RemoteForbidden,\n RemoteLiveRefused,\n RemoteProtocolError,\n RemoteQueryError,\n RemoteReadError,\n RemoteRpc,\n RemoteUnauthenticated,\n RemoteUnreachable,\n} from './wire.js'\nimport type { CoalesceOptions } from './coalesce.js'\nimport {\n Requirement,\n RemoteConnections,\n RemoteRequirements,\n connectionsOf,\n requirementsOf,\n type ConnectionRequirement,\n type RelationRequirement,\n} from './requirement.js'\nimport { markAll, resumePart } from './resume.js'\nimport { answerGaps } from './answerGaps.js'\nimport {\n PredictionPart,\n predictionMismatch,\n withDiagnostics,\n type PredictionMismatch,\n} from './diagnostics.js'\nimport { reduceReporting } from './reporting.js'\nimport { patchedFields, shownOf } from './shown.js'\n\nimport { http as httpClient, json as jsonClient } from './json.js'\nimport { httpWithLive as httpWithLiveClient } from './sse.js'\nexport * from './client.js'\nexport type { RemoteResumePart } from './resume.js'\nexport {\n PredictionPart,\n type LiveRefused,\n type OutboxUnreadable,\n type OutboxUnsaved,\n type PredictionMismatch,\n type RemoteDiagnostic,\n type WriteUnheard,\n} from './diagnostics.js'\n// The channel Remote reports into, for a server or a test that uses Remote alone.\nexport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nexport * from './coalesce.js'\nexport { RemoteJsonAnswer, RemoteJsonRequest, type RemoteJsonSend } from './json.js'\nexport { httpWithLive, liveFetch, type LiveFetchOptions } from './sse.js'\nexport * from './connection.js'\nexport * from './entity.js'\nexport * from './inspect.js'\nexport * from './live.js'\nexport * from './matching.js'\nexport { placeIn, RowPlace } from './placement.js'\nexport { ReadWhy, ShownBy, Why, WhyTerm, type ReadStep } from './why.js'\nexport * from './model.js'\nexport * from './mutation.js'\nexport * from './optimistic.js'\nexport * from './persistence.js'\nexport { OutboxItemState, type OutboxItem, type OutboxStatus, type RetryOptions } from './outbox.js'\nexport * from './plan.js'\nexport * from './policy.js'\nexport * from './query.js'\nexport * from './relation.js'\nexport * from './remoteData.js'\nexport * from './requirement.js'\nexport * from './retain.js'\nexport * from './selection.js'\nexport * from './store.js'\nexport * from './wire.js'\n\n/** What a domain registers: a Remote descriptor, or a `foldkit-entity` Entity (read through `Entity.from`). */\nexport type EntityLike = EntityDescriptor<any, any> | Domain.AnyEntity\n\n/**\n * What a read selects: a Remote Selection, or a `foldkit-entity` Selection\n * (read through `Selection.from`).\n */\nexport type EntitySelection<Value, Name extends string, Id extends string = string> =\n | Selection<Value, Name, 'entity'>\n | Domain.Selection<Name, unknown, Schema.Constraint & { readonly Type: Value }, Id>\n\nconst descriptorOf = (entity: EntityLike): EntityDescriptor<any, any> =>\n DomainEntity.is(entity) ? Entity.from(entity as never) : entity\n\n/** The Remote descriptor either kind of entity reads as, at the type level. */\ntype DescriptorOf<E extends EntityLike> =\n E extends EntityDescriptor<any, any>\n ? E\n : E extends Domain.AnyEntity\n ? EntityDescriptor<E['name'], FieldsFrom<E>>\n : never\n\ntype NameOf<E extends EntityLike> =\n DescriptorOf<E> extends EntityDescriptor<infer N, any> ? N : never\ntype FieldsOf<E extends EntityLike> =\n DescriptorOf<E> extends EntityDescriptor<any, infer F> ? F : never\n\nconst selectionOf = <Value, Name extends string>(\n selection: EntitySelection<Value, Name>,\n): Selection<Value, Name, 'entity'> =>\n SelectionTypeId in selection ? (Selection.from(selection) as never) : selection\n\ntype EntityName<D> = D extends { readonly name: infer Name extends string } ? Name : never\ntype QueryName<D> = D extends QueryDescriptor<infer Name, any, any> ? Name : never\ntype MutationName<D> = D extends MutationDescriptor<infer Name, any, any> ? Name : never\n\n/**\n * Nothing when `Name` is one of the domain's registered `Names`; otherwise a\n * branded failure naming the descriptor, so `Data.get(Team.select(…))` for an\n * unregistered `Team` errors at the selection in one line.\n */\nexport type Registered<Name extends string, Names extends string, Kind extends string> = [\n Name,\n] extends [Names]\n ? unknown\n : Invalid<`${Kind} \"${Name}\" is not registered with this Remote domain`>\n\n/** Nothing when a selection is of the query's entity; otherwise a branded failure naming both. */\nexport type SelectsEntity<Entity extends string, Of extends string> = [Entity] extends [Of]\n ? unknown\n : Invalid<`the selection is of \"${Entity}\", but the query lists \"${Of}\"`>\n\nexport interface RemoteDescriptor<\n Entities extends readonly EntityLike[] = readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[] = readonly QueryDescriptor<\n any,\n any,\n any\n >[],\n Mutations extends readonly MutationDescriptor<any, any, any>[] = readonly MutationDescriptor<\n any,\n any,\n any\n >[],\n> {\n readonly entities: Entities\n readonly queries: Queries\n readonly mutations: Mutations\n readonly Model: Schema.Codec<RemoteModel, unknown>\n readonly initial: RemoteModel\n readonly Message: Schema.Schema<RemoteMessage>\n readonly update: (model: RemoteModel, message: RemoteMessage) => RemoteModel\n readonly rpc: typeof RemoteRpc\n /** Name-keyed lookups built from the declared entities, queries, and mutations. */\n readonly registry: {\n readonly entities: ReadonlyMap<string, EntityDescriptor<any, any>>\n readonly queries: ReadonlyMap<string, QueryDescriptor<any, any, any>>\n readonly mutations: ReadonlyMap<string, MutationDescriptor<any, any, any>>\n /**\n * Per entity name, the members its server filters rows by under a rule\n * the client does not run (`ReadFilter`), so a change to one is fetched,\n * not placed.\n */\n readonly filtered: ReadonlyMap<string, ReadonlyArray<string>>\n /**\n * Per entity name, the members other registered Entities derive over its\n * relations (`Derived.count`, `Derived.exists`), which a write of it\n * moves: what a declared write predicts.\n */\n readonly derived: ReadonlyMap<string, ReadonlyArray<DerivedBy>>\n }\n}\n\ndeclare const boundRemoteNames: unique symbol\n\nexport interface BoundRemote<AppModel, Store extends RemoteModel, Names extends string = string> {\n readonly definition: RemoteDescriptor\n /** The focus of the store's place in the application Model. */\n readonly store: Focus<AppModel, Store>\n /** For `Module`: owns the store's Model path. */\n readonly contract: Contract\n /**\n * How the client runs primitive operators: `Remote.make`'s table, which a\n * pending computed assignment is predicted by wherever the store is read.\n */\n readonly operators: MemoryOperators\n /** Phantom: the entity names this Remote definition registers. */\n readonly [boundRemoteNames]?: Names\n}\n\ntype MutationInput<M> = M extends MutationDescriptor<any, infer Input, any> ? Input : never\ntype MutationRefusal<M> =\n M extends MutationDescriptor<any, any, any, infer Refused> ? Refused : never\n\n/** How `Data.persistence` keeps the cache across a reload. */\nexport interface PersistenceOptions<AppModel> {\n /**\n * Where the snapshot is stored, from the Model: one key per principal, so a\n * change of principal reads and writes another snapshot.\n */\n readonly key: (model: AppModel) => string\n /** Who the snapshot is for; one taken under another scope is discarded. */\n readonly scope: (model: AppModel) => string\n /** The query connections whose rows survive a reload; none by default. */\n readonly connections?: ReadonlyArray<ConnectionIdentity> | undefined\n /** What to keep, when it is not `snapshotOf` the `connections`. */\n readonly snapshot?: ((remote: RemoteModel) => Snapshot) | undefined\n /** A snapshot larger than this is neither written nor read. */\n readonly maxBytes?: number | undefined\n /** How long the cache must be unchanged before it is written; default 250 milliseconds. */\n readonly debounce?: Duration.Input | undefined\n}\n\n/** `Data.persistence`'s wiring, and the restore its runtime's `init` starts from. */\nexport interface PersistenceWiring<AppModel> extends Wiring<\n AppModel,\n RemoteMessage,\n KeyValueStore.KeyValueStore\n> {\n /**\n * The Model with the snapshot stored under its `key` restored, as the wiring\n * would restore it. Resolve it as the runtime's `flags` and start `init`\n * from it, so the first frame draws the stored rows; the wiring then\n * restores only when `key` changes. A store it cannot read leaves the Model\n * as it is, and the wiring tries again.\n */\n readonly restore: (model: AppModel) => Effect.Effect<AppModel, never, KeyValueStore.KeyValueStore>\n}\n\n/** How `Data.outbox` keeps durable writes across a reload. */\nexport interface OutboxOptions<AppModel> {\n /**\n * Where the queue is stored, from the Model: one key per principal, so one\n * person's waiting writes are never sent as another's.\n */\n readonly key: (model: AppModel) => string\n /**\n * Who the queue is for, the principal. One stored under another scope reads\n * as empty and is never written over; a page whose scope changes sends\n * nothing it read for the old one, and reads the new one's.\n */\n readonly scope: (model: AppModel) => string\n /** The wait between sends nothing answered: 1 second doubling to 30, unless given. */\n readonly retry?: RetryOptions | undefined\n}\n\n/** `Data.outbox`'s wiring, and the restore its runtime's `init` starts from. */\nexport interface OutboxWiring<AppModel> extends Wiring<\n AppModel,\n RemoteMessage,\n KeyValueStore.KeyValueStore | RemoteClient\n> {\n /**\n * The Model with the stored queue under its `key` read back, as the wiring\n * would read it, and this page's session minted. Resolve it as the runtime's\n * `flags` and start `init` from it: a durable write needs the session, and\n * the first frame then shows the waiting writes.\n */\n readonly restore: (model: AppModel) => Effect.Effect<AppModel, never, KeyValueStore.KeyValueStore>\n}\n\nexport interface DomainMutateOptions {\n /** Overrides the generated id, for a retry, a durable bridge, or a test. Not with `durable`. */\n readonly requestId?: string | undefined\n /**\n * Queues the write in `Data.outbox` rather than sending it: stored first,\n * sent in order by one tab, sent again after a reload with the same\n * operation id and `now`, and after a failure that nothing answered. Its\n * Command answers `MutationQueued`; the outbox's Subscriptions send it. Needs\n * the outbox's `restore` to have run, and an input its Mutation encodes.\n */\n readonly durable?: boolean | undefined\n /**\n * What the request changes before the server answers, released when it\n * settles. A function receives the generated ids, so a created entity can\n * carry `tempId` until the result names the real one.\n */\n readonly optimistic?:\n | ReadonlyArray<OptimisticOperation>\n | ((ids: {\n readonly requestId: string\n readonly tempId: string\n }) => ReadonlyArray<OptimisticOperation>)\n | undefined\n /**\n * When the reader acted, in milliseconds since the epoch: what a time the\n * write sets (`Expr.now` in `Entity.sets`) is predicted as, and the same\n * number the request sends, which the server takes within its `clockSkew`.\n * Read it where the action is, with `Remote.now`, since `update` reads no\n * clock. Without it the time is not predicted, and the server's clock decides.\n */\n readonly now?: number | undefined\n /**\n * For a mutation that is a `Write`: the input keys to write, when only some\n * changed (what an author edited). The rest of the input is still sent, whole.\n */\n readonly keys?: ReadonlyArray<string> | undefined\n}\n\n/**\n * One entry of the active record `subscriptions`, `wiring` and `satisfy`\n * take: a Surface as the Model activates it (`Surface.at`/`Surface.when`),\n * a source of keyed instances (`Surface.each`, or any `SurfaceSource`), or a\n * Surface without params read whole. A family joins its parent's\n * requirements with its instances', so passing the family alone fetches both\n * the page and what the page reveals.\n */\nexport type ActiveEntry<AppModel> =\n | ActiveSurface<AppModel>\n | Surface<AppModel, any, any, void>\n | SurfaceSource<AppModel>\n\n/** A Foldkit Subscription entry of the Remote domain, emitting its Messages through `RemoteClient`. */\nexport type RemoteEntry<AppModel, Dependencies> = EntryWithoutKeepAlive<\n AppModel,\n RemoteMessage,\n Dependencies,\n RemoteClient\n>\n\n/**\n * The entries `RemoteDomain.subscriptions` returns for an active record: a read\n * and a live entry per key (the live one idles when nothing is read live), and\n * `retain`.\n */\nexport type SubscriptionEntries<AppModel, Active, Message = RemoteMessage> = {\n // `Object.entries` turns a numeric key into a string, so numeric keys have entries too.\n readonly [K in keyof Active & (string | number) as `${K}.read`]: EntryWithoutKeepAlive<\n AppModel,\n Message,\n ReadDependencies,\n RemoteClient\n >\n} & {\n readonly [K in keyof Active & (string | number) as `${K}.live`]: EntryWithoutKeepAlive<\n AppModel,\n Message,\n LiveDependencies,\n RemoteClient\n >\n} & {\n readonly retain: EntryWithoutKeepAlive<AppModel, Message, RetentionRoots, never>\n}\n\n/** The dependencies of a live entry: what it subscribes to, and where a restart resumes. */\nexport interface LiveDependencies {\n readonly requirements: ReadonlyArray<Requirement>\n /** The lists read live, each as its read sends it. */\n readonly queries: ReadonlyArray<Schema.Schema.Type<typeof QueryRequest>>\n readonly cursor: LiveCursor\n readonly floor: number\n /** How many times the stream broke; each break restarts it. */\n readonly restarts: number\n /** Breaks since its last applied event, which the restart's backoff grows with. */\n readonly failures: number\n}\n\n/**\n * Whether what an active entry reads live is arriving. `Reconnecting` is a\n * stream that broke and waits to resubscribe; until it has, changes are\n * missed, and its rows may be out of date. `Refused` is a stream the server\n * would not open for what it asks: it is not retried until that changes.\n */\nexport type LiveStatus =\n /** It reads nothing live. */\n | { readonly _tag: 'Idle' }\n /** Subscribed, and not broken since. */\n | { readonly _tag: 'Live' }\n | {\n readonly _tag: 'Reconnecting'\n /** Breaks in a row, the first being 1. */\n readonly attempt: number\n /** Why it broke; none for a gap in its events. */\n readonly error: Option.Option<RemoteError>\n }\n /** The server refused it (`RemoteLiveRefused`); it waits for what it asks to change. */\n | { readonly _tag: 'Refused'; readonly error: RemoteError }\n\nexport interface SubscriptionsOptions extends ObserveOptions, LiveOptions, RetainOptions {}\n\n/**\n * A Remote domain's wiring for an assembly: it routes Remote's Messages into\n * `reduce`, brings its Subscriptions and contract, and requires `RemoteClient`\n * from the runtime's resources Layer. The `Shared` tags reach the\n * application's own update too, after Remote has reduced them.\n */\nexport type RemoteWiring<AppModel, Shared extends RemoteMessageTag = never> = Wiring<\n AppModel,\n RemoteMessage | RemoteMessageInput,\n RemoteClient,\n RemoteMessageTag\n> & { readonly shared: ReadonlyArray<Shared> }\n\n/** How `Data.wiring` joins an assembly: its Subscriptions' options, and what the application hears. */\nexport interface WiringOptions<\n Shared extends RemoteMessageTag = never,\n> extends SubscriptionsOptions {\n /**\n * Remote's Messages the application's own `update` receives as well, after\n * Remote has reduced them, so the Model it gets already holds what they say:\n * `['MutationFailed']` to react to a write that failed.\n */\n readonly shared?: ReadonlyArray<Shared> | undefined\n}\n\n/**\n * A write that failed and is neither retried nor dismissed, typed by its\n * mutation: what `Data.failedWrites` lists.\n */\nexport interface FailedWrite<M extends MutationDescriptor<any, any, any, any>> {\n readonly requestId: string\n readonly mutation: M\n /** The input it was started with, to show or give back. */\n readonly input: MutationInput<M>\n readonly error: RemoteError\n /** Why the server refused it, as `mutation` declares; none for any other failure. */\n readonly refusal: Option.Option<MutationRefusal<M>>\n}\n\n/** `FailedWrite` of each of a union of mutations. */\nexport type FailedWriteOf<M> =\n M extends MutationDescriptor<any, any, any, any> ? FailedWrite<M> : never\n\n/** What `RemoteDomain.mutate` hands `update`: the Model with the request started, and the Command that settles it. */\nexport interface MutationStarted<AppModel> {\n readonly model: AppModel\n readonly requestId: string\n readonly tempId: string\n /** Yields `MutationSucceeded` or `MutationFailed`; never fails. */\n readonly command: Command<RemoteMessage, never, RemoteClient>\n}\n\n/**\n * A Remote domain bound to its place in the application Model: the descriptor\n * (`Remote.define`), the binding (`Remote.at`), and the application-facing\n * operations over them. Every method compiles to the `Remote.*` function of the\n * same name, which stays exported for tooling, SSR, and tests.\n */\nexport interface RemoteDomain<\n AppModel,\n Store extends RemoteModel,\n Entities extends readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[],\n Mutations extends readonly MutationDescriptor<any, any, any>[],\n>\n extends\n BoundRemote<AppModel, Store, EntityName<Entities[number]>>,\n RemoteDescriptor<Entities, Queries, Mutations> {\n /** `Remote.select`: a Projection reading one entity through a selection of a registered entity. */\n get<Value, Name extends string, Id extends string = string>(\n selection: EntitySelection<Value, Name, Id> &\n Registered<Name, EntityName<Entities[number]>, 'Entity'>,\n // The id type of the Entity selected: another Entity's branded id does not fit.\n id: NoInfer<Id>,\n ): Projection<AppModel, RemoteData<Value>>\n /**\n * `get`, and the projection also subscribes to the entity's changes: its\n * requirements are marked `live`, so `subscriptions` derives a live entry for\n * the Surfaces that read it.\n */\n live<Value, Name extends string, Id extends string = string>(\n selection: EntitySelection<Value, Name, Id> &\n Registered<Name, EntityName<Entities[number]>, 'Entity'>,\n // The id type of the Entity selected: another Entity's branded id does not fit.\n id: NoInfer<Id>,\n ): Projection<AppModel, RemoteData<Value>>\n /**\n * A query connection read as a `Page` of items selected of the query's\n * entity: `Initial` until the page and every item's selected fields are\n * present, `Refreshing` while any of them is being refetched. The window is\n * the page first asked for; the pages `next`, `previous` and `fetch` merge\n * onto the connection read through the same projection.\n */\n query<Q extends QueryDescriptor<any, any, any>, Value, Entity extends string>(\n query: Q & Registered<Q['name'], QueryName<Queries[number]>, 'Query'>,\n input: QueryInput<Q>,\n options: QueryOptions<Value, Entity, QueryEntity<Q>>,\n ): QueryProjection<AppModel, Value, Q['name'], QueryInput<Q>>\n /**\n * \"Load more\": the Model with the read's window grown by one page, so it\n * shows that many more rows; the read entry fetches what the connection\n * lacks. None when the read shows everything there is (or is not a sized\n * window). Called from `update`.\n */\n more<Name extends string, Input>(\n model: AppModel,\n projection: QueryProjection<AppModel, any, Name, Input>,\n ): Option.Option<AppModel>\n /**\n * What a query read is and what it currently is, as one serializable value —\n * data-query-DESIGN §29.1: the domain, the definition and its input, the\n * connection identity, the window, the Selection, the body as readable text\n * with what it depends on, and what the read answers from this Model.\n *\n * Pure, so a DevTools panel showing it shows something the Model can be\n * replayed to.\n *\n * Given `surfaces` — the same active record `subscriptions` takes — it also\n * reports which of them read this connection, and why each is active where\n * that is a readable fact (`Surface.when`) rather than a callback\n * (`Surface.at`). A Projection cannot carry this itself: several Surfaces may\n * read one connection, so it is not a property of the read.\n */\n explain<Name extends string, Input>(\n model: AppModel,\n projection: QueryProjection<AppModel, any, Name, Input>,\n options?: {\n readonly surfaces?:\n | Readonly<Record<string, ActiveSurface<AppModel> | SurfaceSource<AppModel>>>\n | undefined\n },\n ): QueryExplanation\n /**\n * Why a read shows what it shows. Any Remote read: `Data.get`, `Data.live`\n * or `Data.query`, or a projection made of them.\n *\n * `because` is every fact the Model holds about what it reads, as typed\n * references: a list or a row's fields missing, stale, in flight or\n * failed; a pending write showing a value, and which `where` term put a row\n * in a list or took it out. The reason that decides the state comes first,\n * and `message` says it, with what restarts it. For `Initial`, given\n * `surfaces` (the record `subscriptions` takes), it tells the two wiring\n * mistakes apart: no active Surface reads it, or one does and Remote's\n * Subscriptions are not running. Pure: it reads the Model and plans nothing.\n */\n why(\n model: AppModel,\n projection: Projection<AppModel, RemoteData<unknown>>,\n options?: {\n readonly surfaces?:\n | Readonly<Record<string, ActiveSurface<AppModel> | SurfaceSource<AppModel>>>\n | undefined\n },\n ): ReadWhy\n /**\n * Each change of each read's tag across a recorded history (the Messages\n * `update` handled, each with the Model it left, as Foldkit's devtools\n * records them), with the Message that made it and `why` at the Model it\n * changed to. `regression` marks a read that showed a value and stopped\n * with no reason a reader can see (#234).\n */\n timeline<Message>(\n start: AppModel,\n history: ReadonlyArray<{ readonly message: Message; readonly model: AppModel }>,\n reads: Readonly<Record<string, Projection<AppModel, RemoteData<unknown>>>>,\n options?: {\n readonly surfaces?:\n | Readonly<Record<string, ActiveSurface<AppModel> | SurfaceSource<AppModel>>>\n | undefined\n },\n ): ReadonlyArray<ReadStep<Message>>\n /**\n * The rows of a loaded list that a body matches, decoded as the list decodes\n * them — a filter that asks the server nothing.\n *\n * **It filters a list; it does not run a query.** That distinction is what\n * keeps it honest. \"Which rows match\" would need to know that the list holds\n * every row the body could match, which is predicate containment and is\n * deliberately not built. \"Which rows *of this list* match\" is decidable from\n * what is already here, and is what a search box over a loaded page actually\n * wants.\n *\n * `complete` says whether the answer is about the whole list: every edge\n * judged, and the connection terminal at both ends. An incomplete answer is\n * not wrong — it is about less than the caller may have meant, which is why\n * it is said rather than left for a view to assume.\n *\n * Creates no connection, so there is nothing new to retain and nothing new to\n * fetch. The server stays authoritative for which rows exist.\n */\n filtered<Value, Name extends string, Input, Q extends QueryDescriptor<any, any, any>>(\n model: AppModel,\n over: QueryProjection<AppModel, Value, Name, Input>,\n by: Q & Registered<Q['name'], QueryName<Queries[number]>, 'Query'>,\n input: QueryInput<Q>,\n ): Matched<Value>\n /**\n * Shows operations over the store with no request behind them, as a mutation's\n * `optimistic` ones show while it is in flight: every Selection and view draws\n * them. For a preview of a change nobody has made. They stay until `lift`;\n * showing an id again replaces what it showed. Called from `update`. A read\n * of an entity only overlays show, lacking a field it selects, is `Failed`\n * (`Overlaid`): nothing will fetch that field.\n */\n overlay(model: AppModel, id: string, optimistic: ReadonlyArray<OptimisticOperation>): AppModel\n /** Lifts what `overlay` showed under this id. Lifting nothing returns the same Model. */\n lift(model: AppModel, id: string): AppModel\n /**\n * The ids `overlay` shows now, in the order they are drawn, a later one over\n * an earlier: what a caller that overlays from its own state reconciles\n * against.\n */\n overlays(model: AppModel): ReadonlyArray<string>\n /**\n * The edges a connection shows, as its reads draw them: the server's pages\n * with pending edits placed, each inserted row where the body's order puts\n * it (or at the end its overlay names, when it cannot be placed), minus\n * removed edges and tombstones. Takes the `RemoteModel`, so a persistence\n * `snapshot` can store a list as it is shown.\n */\n visibleItems(remote: RemoteModel, connection: ConnectionIdentity): ReadonlyArray<Edge>\n /**\n * `Remote.refresh`: marks what `target` reads for this Model as due, for its\n * read entries to refetch. `target` is a projection, a Surface without\n * params, one entry of the active record, or the record itself, whose\n * params come from the Model as they do for `subscriptions`; or a\n * registered query's ref, which invalidates that list whatever its window. With\n * `{ failed: true }` only what failed is asked again: a \"Try again\".\n */\n refresh(\n model: AppModel,\n target: RefreshTarget<AppModel, QueryName<Queries[number]>>,\n options?: RefreshOptions,\n ): AppModel\n /** `Remote.forget`: the Model with every server-derived fact gone, for a change of principal. */\n forget(model: AppModel): AppModel\n /**\n * A read of this domain as an active Surface, for `subscriptions` and\n * `wiring`: `projectionOf` is what it reads for a Model, none while it\n * reads nothing. It belongs to the domain's application, and lists no\n * Messages: it is a requirement, not a sender. A domain made from a raw\n * optic names no application, so this throws for one.\n */\n active<Value>(\n name: string,\n projectionOf: (model: AppModel) => Option.Option<Projection<AppModel, Value>>,\n ): ActiveSurface<AppModel, Value>\n /**\n * The Foldkit Subscription entries for the active record, keyed for\n * `Subscription.make`: a read entry per record entry (`Remote.observe`), a\n * live entry per record entry that reads through `live` (`Remote.live`), and\n * one retain entry (`Remote.retain`). A `Surface.each` family is one record\n * entry whose read unions its parent's requirements with its instances'.\n * Retention is the domain's: the retain entry of every call roots the active\n * Surfaces of every call, so reads split over calls (one per policy) do not\n * collect each other's data. A Surface's params are a function of the Model\n * (`Surface.at`), so what is fetched, subscribed, and retained follows the\n * Model.\n */\n subscriptions<const Active extends Readonly<Record<string, ActiveEntry<AppModel>>>>(\n active: Active,\n options?: SubscriptionsOptions,\n ): SubscriptionEntries<AppModel, Active>\n /** `Remote.plan`: the requirements the store does not satisfy. */\n plan<Value>(\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options?: PlanOptions,\n ): ReadonlyArray<Requirement>\n /** `Remote.meta`: when what a projection shows was last received, and whether it is stale or loading. */\n meta<Value>(model: AppModel, projection: Projection<AppModel, Value>): ReadMeta\n /** `Remote.storeOf`: the visible store, base under the pending optimistic layers. */\n storeOf(model: AppModel): EntityStore\n /**\n * `Remote.confirmed`: the same projection read against the server-derived\n * store alone, with every pending optimistic layer and connection overlay\n * left off. What it plans is unchanged — the requirements are the\n * projection's own — so observing it reads exactly what observing the\n * projection reads; only what it *shows* differs.\n *\n * A view usually wants the projection itself, which is the visible read:\n * the optimistic layers are there so a change shows before the server has\n * agreed to it. This is for the reader that must not believe a change until\n * the server has confirmed it, which in practice is an Agent capability\n * reporting that what it was asked to do is done:\n *\n * ```ts\n * Agent.when({\n * projection: Data.confirmed(ProjectPage.model.project),\n * predicate: (project, request) => project.name === request.name,\n * })\n * ```\n *\n * There is deliberately no `visible`: a projection is already the visible\n * read, and a wrapper that only forwards would be a second name for it.\n */\n confirmed<P extends Projection<AppModel, any>>(projection: P): P\n /**\n * The plan run through `RemoteClient` and reduced into the Model: the\n * projection's pending queries first, then the fields it lacks (the pages'\n * items included). For SSR, route or hover prefetch, and tests.\n */\n prefetch<Value>(\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options?: ObserveOptions,\n ): Effect.Effect<\n AppModel,\n RemoteReadError | RemoteProtocolError | RemoteQueryError | RemoteUnauthenticated,\n RemoteClient\n >\n /**\n * The Model with everything the active Surfaces read, for a render that\n * fetches nothing (SSR, a prerender). Each pass prefetches every Surface\n * that plans a read, over the Model the one before it left, so a Surface\n * active only once another's read has arrived is read in the next pass (or\n * the same one, when it comes later in `active`). It stops at the first\n * pass that plans nothing, and fails with `RemoteUnsatisfied` when\n * `options.passes` run out first. Reads are cache-first: a field already\n * held is not asked again. A server that could not tell who is asking\n * fails it with `RemoteUnauthenticated`, for the host to answer as it\n * answers a lost session.\n */\n satisfy(\n model: AppModel,\n active: Readonly<Record<string, ActiveEntry<AppModel>>>,\n options?: SatisfyOptions,\n ): Effect.Effect<\n AppModel,\n | RemoteReadError\n | RemoteProtocolError\n | RemoteQueryError\n | RemoteUnauthenticated\n | RemoteUnsatisfied,\n RemoteClient\n >\n /**\n * `satisfy` from `update`, for a destination the reader has not reached:\n * a hover over a link, or a navigation the app expects. `model` is the\n * Model as it would be there (the route set to the target's); the Command\n * reads what `active` would read in it and yields one `Preloaded`\n * carrying the Messages that wrote it, which reduce into the Model as it is\n * by then. It never fails: a read that fails is one the destination makes\n * again, and what was read before it still arrives.\n *\n * What it reads is kept like any other read until the next change of what\n * is retained, so preload close to the navigation it expects.\n */\n preload(\n model: AppModel,\n active: Readonly<Record<string, ActiveEntry<AppModel>>>,\n options?: SatisfyOptions,\n ): Command<RemoteMessage, never, RemoteClient>\n /**\n * Starts a registered mutation from `update`: applies `MutationStarted` (with\n * the optimistic operations) to the Model and returns the Command that runs\n * it and yields the settling Message. The request id comes from the model's\n * mutation sequence unless `options.requestId` is given.\n */\n mutate<M extends MutationDescriptor<any, any, any>>(\n model: AppModel,\n mutation: M & Registered<M['name'], MutationName<Mutations[number]>, 'Mutation'>,\n input: MutationInput<M>,\n options?: DomainMutateOptions,\n ): MutationStarted<AppModel>\n /**\n * What Remote knows of a mutation `mutate` started, by its request id:\n * pending, applied, or failed with the error the server or transport gave.\n */\n mutation(model: AppModel, requestId: string): MutationStatus\n /**\n * Why the server refused a mutation, as the value its `Refusal` declares:\n * none while it is pending or applied, when it failed for another reason,\n * or when the refusal does not decode as `mutation`'s.\n */\n refusal<Refused>(\n model: AppModel,\n requestId: string,\n mutation: MutationDescriptor<string, any, any, Refused>,\n ): Option.Option<Refused>\n /**\n * The writes that failed and are still owed an answer, oldest first, each\n * with its mutation, the input it was started with, and why it failed. Given\n * a mutation, only its writes, with its input type. A write is listed until\n * `retry` sends it again, `dismiss` forgets it, or `forget` changes the\n * principal; nothing drops one on a timer, since that would hide a failure\n * the reader has not seen.\n */\n failedWrites(model: AppModel): ReadonlyArray<FailedWriteOf<Mutations[number]>>\n failedWrites<M extends MutationDescriptor<any, any, any, any>>(\n model: AppModel,\n mutation: M & Registered<M['name'], MutationName<Mutations[number]>, 'Mutation'>,\n ): ReadonlyArray<FailedWrite<M>>\n /**\n * Sends a failed write again as itself: the same input, request id and\n * operation id (so a server that applied it answers from its record), with\n * its optimistic operations shown again. None unless `failedWrites` lists it.\n * A durable one is queued again, and the outbox sends it.\n */\n retry(model: AppModel, requestId: string): Option.Option<MutationStarted<AppModel>>\n /**\n * Forgets a failed write, so `failedWrites` no longer lists it; a durable one,\n * or one the outbox cannot read, goes from its store and every tab. Anything\n * else (a write still waiting, too) returns the same Model.\n */\n dismiss(model: AppModel, requestId: string): AppModel\n /**\n * The durable writes not yet settled, every tab's, in the order the outbox\n * sends them: how many wait, how many the server refused, and each one's\n * state, for a \"3 changes waiting\" line.\n */\n outboxStatus(model: AppModel): OutboxStatus\n /**\n * Whether what `active` reads live is arriving: `Reconnecting` from the\n * moment its stream breaks until it resubscribes, which its live entry does\n * on its own, with backoff.\n */\n liveStatus(model: AppModel, active: ActiveEntry<AppModel>): LiveStatus\n /** `updateRemote` on the bound slice: reduces one of Remote's Messages, as `RemoteMessage` or as the application's union constructs it. */\n reduce(model: AppModel, message: RemoteMessage | RemoteMessageInput): AppModel\n /**\n * How this domain joins an assembly: it routes Remote's Messages into\n * `reduce`, brings its Subscriptions and contract, and requires\n * `RemoteClient` from the runtime's resources Layer. One assembly holds at\n * most one Remote wiring: every domain claims the same tags, and routing\n * takes the first claimant. `shared` names the Messages the application's\n * own update hears too.\n */\n wiring: <\n const Active extends Readonly<Record<string, ActiveEntry<AppModel>>>,\n const Shared extends RemoteMessageTag = never,\n >(\n active: Active,\n options?: WiringOptions<Shared>,\n ) => RemoteWiring<AppModel, Shared>\n /**\n * Keeps the cache across a reload, as a wiring beside `wiring`: the stored\n * snapshot for `key` is restored (`Hydrated`, with what the store already\n * holds kept over it, so a page resumed from the server wins) whenever the\n * Model is not yet restored from `key`; and the cache is written back when it\n * changes, once its own snapshot is in. Start `init` from its `restore` so\n * the first frame already holds the snapshot. Overlays, optimistic layers,\n * the mutation ledger, live cursors and gaps are never stored. A change of\n * principal should `forget` in `update`, and name another `key`.\n */\n persistence(options: PersistenceOptions<AppModel>): PersistenceWiring<AppModel>\n /**\n * Keeps durable writes (`mutate`'s `durable`) across a reload and sends\n * them, as a wiring beside `wiring`: the queue is written to `key` before a\n * write is sent, sent oldest first by one tab (a Web Lock), sent again after\n * a failure that nothing answered with a backoff, and read back by every\n * tab. Start `init` from its `restore`. A change of principal should\n * `forget` in `update`, and name another `key`.\n */\n outbox(options: OutboxOptions<AppModel>): OutboxWiring<AppModel>\n /** `Remote.inspect` of the bound slice. */\n inspect(model: AppModel): RemoteInspection\n}\n\n/** What `Remote.fold(Data, …).mutate` starts: `Data.mutate`'s result with its Command lifted. */\nexport type FoldedMutationStarted<AppModel, ParentMessage> = Omit<\n MutationStarted<AppModel>,\n 'command'\n> & {\n readonly command: Command<ParentMessage, never, RemoteClient>\n}\n\n/**\n * A bound domain folded under one of the application's own Message variants,\n * from `Remote.fold`. Calling it reduces a Remote Message into the Model; the\n * members that produce Messages, `fetch`, `mutate`, and `subscriptions`,\n * yield the wrapper Message instead of `RemoteMessage`, with the lift recorded\n * so Story and Scene can resolve a fetch or a mutation by Remote's own answer.\n * Members that only read or write the Model (`get`, `refresh`, `next`,\n * `overlay`, and the rest) stay on the domain itself.\n */\nexport interface RemoteFold<\n AppModel,\n ParentMessage,\n Domain extends RemoteDomain<AppModel, any, any, any, any>,\n> {\n (\n model: AppModel,\n message: RemoteMessage | RemoteMessageInput,\n ): Update.Return<AppModel, ParentMessage>\n /** `Data.mutate`, its Command lifted. */\n readonly mutate: (\n ...args: Parameters<Domain['mutate']>\n ) => FoldedMutationStarted<AppModel, ParentMessage>\n /** `Data.retry`, its Command lifted. */\n readonly retry: (\n ...args: Parameters<Domain['retry']>\n ) => Option.Option<FoldedMutationStarted<AppModel, ParentMessage>>\n /** `Data.preload`, its Command lifted. */\n readonly preload: (\n ...args: Parameters<Domain['preload']>\n ) => Command<ParentMessage, never, RemoteClient>\n /** `Data.subscriptions`, every entry lifted to the wrapper Message. */\n readonly subscriptions: <const Active extends Readonly<Record<string, ActiveEntry<AppModel>>>>(\n active: Active,\n options?: SubscriptionsOptions,\n ) => SubscriptionEntries<AppModel, Active, ParentMessage>\n}\n\n/** The application Model a bound domain is over. */\nexport type ModelOfDomain<Domain> =\n Domain extends RemoteDomain<infer AppModel, any, any, any, any> ? AppModel : never\n\n/** A projection's connection requirement with the `QueryRef` that runs it. */\nexport interface QueryRequirement extends ConnectionRequirement {\n readonly ref: QueryRef<string, unknown>\n}\n\n/** A page forward (`first`, `after`) or back (`last`, `before`); mixing the two is a type error. */\nexport type QueryWindowOptions =\n | {\n readonly first?: number | undefined\n readonly after?: string | undefined\n readonly last?: undefined\n readonly before?: undefined\n }\n | {\n readonly last: number\n readonly before?: string | undefined\n readonly first?: undefined\n readonly after?: undefined\n }\n\nexport type QueryOptions<Value, Entity extends string, Of extends string = Entity> = {\n /** What to read of each item: a selection of the query's entity (`Of`). */\n readonly select: EntitySelection<Value, Entity> & SelectsEntity<Entity, Of>\n /**\n * Watch the list live while a Surface reads it: rows that join, change or\n * leave it are streamed (by a live source that watches queries, such as\n * `foldkit-remote-drizzle`'s `pollLive`). Needs `first`.\n */\n readonly live?: boolean | undefined\n} & QueryWindowOptions\n\n/** A query connection read as a `Page` of selected items; `ref` is the connection with its first window. */\nexport interface QueryProjection<AppModel, Value, Name extends string, Input> extends Projection<\n AppModel,\n RemoteData<Page<Value>>\n> {\n readonly ref: QueryRef<Name, Input>\n /** What it reads of each item, so a filter over the same list decodes identically. */\n readonly selection: Selection<Value, string>\n}\n\n/** The input of a query descriptor. */\nexport type QueryInput<Q> = Q extends QueryDescriptor<any, infer Input, any> ? Input : never\n/** The entity a query's connection is over. */\nexport type QueryEntity<Q> =\n Q extends QueryDescriptor<any, any, ConnectionSpec<infer Entity>> ? Entity : string\n\n/**\n * What one consumer asks of one connection, as the pieces it is actually made\n * of — data-query-DESIGN §11's read contract, with only the parts that exist\n * here:\n *\n * - **source** — the `QueryRef`: the query and its input, whose `identity`\n * names the connection and deliberately excludes the window.\n * - **window** — how much of it this consumer wants.\n * - **shape** — the Selection, as the relation slice a read asks the server for.\n *\n * The design's other two are absent on purpose. *Expectation* (required versus\n * optional) has no consumer yet, so there is nothing to carry. *Observation* is\n * a policy of the subscription that runs the read, not of the read itself: one\n * policy covers every connection an active Surface asks for.\n *\n * This is a shaping step, not a public type. The design asked for the\n * separation, not for a new API to compose it with.\n *\n * Note what is *not* here: a read identity keyed on the shape. Two consumers\n * asking one connection and window for different Selections merge into one\n * requirement whose fields are the union, so one read serves both — see\n * `Requirement.mergeConnections`. An identity that included the Selection would\n * split them and fetch twice.\n */\ninterface ReadContract<Name extends string, Input> {\n readonly ref: QueryRef<Name, Input>\n readonly relation: RelationRequirement\n readonly requirement: QueryRequirement\n}\n\nconst readContract = <Name extends string, Input, Value, Entity extends string>(\n source: QueryRef<Name, Input>,\n shape: Selection<Value, Entity>,\n window: QueryWindowOptions,\n): ReadContract<Name, Input> => {\n const ref: QueryRef<Name, Input> = { ...source, window: pickWindow(window) }\n const relation = relationOf(shape)\n return {\n ref,\n relation,\n requirement: { identity: ref.identity, window: ref.window, select: relation, ref },\n }\n}\n\n/**\n * A read contract whose connection, when a client can place rows in it, also\n * reads every field its body filters and orders by: a changed row is then\n * compared with neighbours that hold those fields. What the view reads, and so\n * decodes, stays its Selection.\n */\nconst placeableReadContract = <Name extends string, Input>(\n contract: ReadContract<Name, Input>,\n body: Domain.AnyQuery | undefined,\n operators: MemoryOperators,\n): ReadContract<Name, Input> => {\n if (body === undefined) return contract\n const { requirement, ref } = contract\n const encoded = Schema.encodeSync(ref.Input)(ref.input) as Readonly<Record<string, unknown>>\n if (Relational.placement(body, encoded, { operators })._tag !== 'Placeable') return contract\n const missing = Relational.dependencies(body).fields.filter(\n field => !requirement.select.fields.includes(field.key),\n )\n if (missing.length === 0) return contract\n return {\n ...contract,\n requirement: {\n ...requirement,\n select: {\n ...requirement.select,\n fields: [...requirement.select.fields, ...missing.map(field => field.key)],\n },\n },\n }\n}\n\n/**\n * When what a projection shows was last received, and whether it is stale\n * or loading. See `Remote.meta`.\n */\nexport interface ReadMeta {\n /** The newest server write among what is shown; none received reads `undefined`. */\n readonly updatedAt: number | undefined\n /** Any shown field or connection is marked stale. */\n readonly stale: boolean\n /** Any shown field or connection is in flight. */\n readonly loading: boolean\n}\n\nconst metaOf = (remote: RemoteModel, asked: Asked, operators: MemoryOperators): ReadMeta => {\n const visible = visibleStoreOf(remote.entities, remote.optimistic, operators)\n let updatedAt: number | undefined\n let stale = false\n let loading = false\n const seen = new Set<string>()\n const touch = (entity: string, id: string, requirement: RelationRequirement): void => {\n const key = entityKey(entity, id)\n const memo = `${key}\\u0000${stableStringify(requirement)}`\n if (seen.has(memo)) return\n seen.add(memo)\n const entry = visible[key]\n if (entry !== undefined && !entry.tombstone) {\n for (const field of requirement.fields) {\n if (!entry.present.has(field)) continue\n if (Number.isFinite(entry.updatedAt))\n updatedAt =\n updatedAt === undefined ? entry.updatedAt : Math.max(updatedAt, entry.updatedAt)\n if (entry.stale.has(field)) stale = true\n }\n }\n if (isLoadingThrough(remote, entity, id, requirement)) loading = true\n for (const [field, relation] of Object.entries(requirement.relations ?? {})) {\n const value = readField(visible, key, field)\n if (value._tag === 'None' || value.value === null || value.value === undefined) continue\n for (const ref of targetsOf(value.value, relation)) touch(ref.entity, ref.id, relation)\n }\n }\n for (const requirement of asked.requirements)\n touch(requirement.entity, requirement.id, requirement)\n for (const connection of asked.connections) {\n const known = remote.connections[connection.identity]\n if (known === undefined) {\n if (isQueryLoading(remote, connection.identity)) loading = true\n continue\n }\n if (known.stale) stale = true\n if (isQueryLoading(remote, connection.identity)) loading = true\n for (const edge of visibleItems(\n known,\n connection.identity,\n remote.optimistic.overlays,\n goneIn(remote.entities, remote.optimistic),\n )) {\n if (edge.ref.entity !== connection.select.entity) continue\n touch(edge.ref.entity, edge.ref.id, connection.select)\n }\n }\n return { updatedAt, stale, loading }\n}\n\n/**\n * The store a read or plan sees: the base with every pending optimistic layer\n * applied, so a request's patches show until it settles and a temporary id is\n * not planned as a fetch.\n */\nconst storeOf = <AppModel, Store extends RemoteModel, Names extends string>(\n bound: BoundRemote<AppModel, Store, Names>,\n model: AppModel,\n): EntityStore => {\n const remote = bound.store.get(model)\n return visibleStoreOf(remote.entities, remote.optimistic, bound.operators)\n}\n\n/**\n * The Model as it would be with nothing optimistic pending. Every read reaches\n * the layers through the Model it is given, so dropping them here is what makes\n * a read confirmed — no read has to know it is being read confirmed.\n */\nconst withoutOptimistic = <AppModel, Store extends RemoteModel, Names extends string>(\n bound: BoundRemote<AppModel, Store, Names>,\n model: AppModel,\n): AppModel => {\n const remote = bound.store.get(model)\n return remote.optimistic.layers.length === 0 && remote.optimistic.overlays.length === 0\n ? model\n : bound.store.set(model, { ...remote, optimistic: emptyOptimistic } as Store)\n}\n\nconst confirmed = <AppModel, Store extends RemoteModel, P extends Projection<AppModel, any>>(\n bound: BoundRemote<AppModel, Store>,\n projection: P,\n): P => ({\n ...projection,\n read: (root: AppModel) => projection.read(withoutOptimistic(bound, root)),\n})\n\n// The visible store is recomputed only when the base store or the layers\n// change, so reads and plans across renders of one Model share it. Keyed on\n// the layers rather than the whole optimistic state, which also changes with\n// every overlay (a live insert, a page pruning one) that no layer is part of.\n// By the client's table, then the layers, then the store: a prediction depends on all three.\nconst visibleStores = new WeakMap<\n MemoryOperators,\n WeakMap<object, WeakMap<EntityStore, EntityStore>>\n>()\n\nconst visibleStoreOf = (\n entities: EntityStore,\n optimistic: OptimisticState,\n operators: MemoryOperators,\n): EntityStore => {\n let byLayers = visibleStores.get(operators)\n if (byLayers === undefined) {\n byLayers = new WeakMap()\n visibleStores.set(operators, byLayers)\n }\n let byStore = byLayers.get(optimistic.layers)\n if (byStore === undefined) {\n byStore = new WeakMap()\n byLayers.set(optimistic.layers, byStore)\n }\n let visible = byStore.get(entities)\n if (visible === undefined) {\n visible = visibleStore(entities, optimistic, operators)\n byStore.set(entities, visible)\n }\n return visible\n}\n\n// A visible store is made from one store and one set of layers, so it keys\n// what is planned over it; the read entries ask on every Model change.\nconst plannedStores = new WeakMap<EntityStore, EntityStore>()\n\n/** `plannedStore` of the visible store, kept by it. */\nconst plannedStoreOf = (\n entities: EntityStore,\n optimistic: OptimisticState,\n visible: EntityStore,\n): EntityStore => {\n let planned = plannedStores.get(visible)\n if (planned === undefined) {\n planned = plannedStore(entities, visible, optimistic)\n plannedStores.set(visible, planned)\n }\n return planned\n}\n\n/**\n * `Failed` naming a field the server settled without a value, when one is\n * among what `relation` reads of the entity; otherwise nothing, and the store\n * merely lacks the value. The reason stays with the server, so a view shows\n * the field it cannot have, not why.\n */\nconst unavailableFailure = (\n store: EntityStore,\n key: string,\n relation: RelationRequirement,\n): { readonly _tag: 'Failed'; readonly error: RemoteError } | undefined => {\n const field = unavailableOf(store, key, relation)\n return field === undefined\n ? undefined\n : {\n _tag: 'Failed',\n error: {\n _tag: 'Unavailable',\n message: `The server answered without ${field}, and will not answer with it: the field is not available to this client.`,\n },\n }\n}\n\n/**\n * A row's decoded value, kept while the data it was assembled from is the same,\n * so a refetch or live patch that brought equal data hands a view the object it\n * already rendered. Keyed on the row's own values object, which the store keeps\n * across equal writes; a relation's targets are covered by comparing what was\n * assembled.\n */\nconst decodedRows = new WeakMap<\n object,\n {\n readonly decode: (values: unknown) => Result.Result<unknown, Schema.SchemaError>\n readonly rows: WeakMap<object, { readonly values: unknown; readonly decoded: unknown }>\n }\n>()\n\nconst decodeRow = <Value>(\n schema: Schema.Codec<Value, unknown, never, never>,\n source: object,\n values: unknown,\n): Result.Result<Value, Schema.SchemaError> => {\n let bySchema = decodedRows.get(schema)\n if (bySchema === undefined) {\n bySchema = { decode: Schema.decodeUnknownResult(schema), rows: new WeakMap() }\n decodedRows.set(schema, bySchema)\n }\n const cached = bySchema.rows.get(source)\n if (cached !== undefined && sameData(cached.values, values)) {\n return cached.decoded as Result.Result<Value, Schema.SchemaError>\n }\n const decoded = bySchema.decode(values)\n bySchema.rows.set(source, { values, decoded })\n return decoded as Result.Result<Value, Schema.SchemaError>\n}\n\ninterface ReadScope {\n readonly inner: WeakMap<object, ReadScope>\n readonly results: Map<string, unknown>\n}\n\nconst readResults: ReadScope = { inner: new WeakMap(), results: new Map() }\n\n// A read's result per snapshot of everything it reads. `Remote.storeOf` is\n// shared across every read of one Model state, so equal reads of one render\n// assemble and decode once and return one value (a view may compare by\n// identity). A query read also depends on its connection and the overlays,\n// which change independently of the store, so it keys on those too. Weak on\n// every scope, bounded by what is read.\nconst memoRead = <T>(scopes: ReadonlyArray<object>, key: string, compute: () => T): T => {\n let scope = readResults\n for (const by of scopes) {\n let inner = scope.inner.get(by)\n if (inner === undefined) {\n inner = { inner: new WeakMap(), results: new Map() }\n scope.inner.set(by, inner)\n }\n scope = inner\n }\n if (scope.results.has(key)) return scope.results.get(key) as T\n const value = compute()\n scope.results.set(key, value)\n return value\n}\n\nexport interface MutateOptions {\n /** What the request changes before the server answers; released when it settles. */\n readonly optimistic?: ReadonlyArray<OptimisticOperation> | undefined\n /**\n * When the reader acted, in milliseconds since the epoch, as `Remote.now`\n * read it: sent for a time the write sets, which the server takes within\n * its `clockSkew`.\n */\n readonly now?: number | undefined\n}\n\n/**\n * The default clock. It reads `Date.now` when called rather than holding the\n * function, so fake timers installed after the domain was made move it.\n */\nconst wallClock = (): number => Date.now()\n\n/** The default `toMessage`: the application reduces `RemoteMessage` itself. */\nconst identityMessage = (message: RemoteMessage): RemoteMessage => message\n\nexport interface RetainOptions {\n /** The query connections the application shows, by `QueryRef` or identity. */\n readonly connections?: ReadonlyArray<ConnectionIdentity> | undefined\n /** How long the roots must be stable before collecting; default none. */\n readonly grace?: Duration.Input | undefined\n}\n\n/** How `Remote.observe` and `Remote.prefetch` treat fields the store already holds. */\nexport interface ObserveOptions {\n /** Default `RemotePolicy.cacheFirst`. */\n readonly policy?: RemotePolicy | undefined\n /** The clock a refreshing policy reads; default `Date.now`, read at each use. */\n readonly now?: (() => number) | undefined\n}\n\n/** How `Data.satisfy` reads: how many passes it may take, and the clock. */\nexport interface SatisfyOptions {\n /** At most this many passes over the Surfaces; default 8. */\n readonly passes?: number | undefined\n /** The clock the reads are stamped with; default `Date.now`, read at each use. */\n readonly now?: (() => number) | undefined\n}\n\n/**\n * `Data.satisfy` reached its bound with Surfaces still reading, such as a\n * chain whose every read reveals one more. It names them, so a page that\n * would have rendered them loading fails instead. (A read the server leaves\n * unanswered settles as missing and ends the loop.)\n */\nexport class RemoteUnsatisfied extends Schema.TaggedError<RemoteUnsatisfied>()(\n 'RemoteUnsatisfied',\n { surfaces: Schema.Array(Schema.String), passes: Schema.Number },\n) {}\n\nexport interface LiveOptions {\n /** The clock `LiveReceived` stamps events with; default `Date.now`, read at each use. */\n readonly now?: (() => number) | undefined\n /**\n * The first restart's delay after a stream breaks, doubled for each break in\n * a row, with ±20% jitter: Sync's transport policy. Default `50 millis`.\n */\n readonly retryBase?: Duration.Input | undefined\n /** The longest a restart waits. Default `5 seconds`. */\n readonly maxRetryDelay?: Duration.Input | undefined\n}\n\n/** A stable key for a live subscription's rows and lists. */\nconst liveStreamKey = ({ requirements, queries }: LiveAsk): string =>\n [\n ...requirements.map(\n requirement =>\n `${entityKey(requirement.entity, requirement.id)}:${[...requirement.fields].sort().join(',')}`,\n ),\n ...queries.map(query => stableStringify(query)),\n ]\n .sort()\n .join('|')\n\n/** Each registered Entity's `Derived.count`s and `Derived.exists`, under the pointing Entity. */\nconst derivedMembersBy = (\n entities: ReadonlyArray<EntityLike>,\n): ReadonlyMap<string, ReadonlyArray<DerivedBy>> => {\n const byPointing = new Map<string, Array<DerivedBy>>()\n const add = (pointing: string, member: DerivedBy): void => {\n const members = byPointing.get(pointing) ?? []\n members.push(member)\n byPointing.set(pointing, members)\n }\n for (const entity of entities) {\n if (!DomainEntity.is(entity)) continue\n const derived: Readonly<\n Record<string, Domain.EntityDerived<string, string, Schema.Constraint>>\n > = entity.derived\n for (const [field, member] of Object.entries(derived))\n Derivation.$match(member.derives, {\n Supplied: () => undefined,\n Count: ({ relation }) =>\n add(\n relation.owner.name,\n DerivedBy.Count({ relation: relation.key, owner: entity.name, field }),\n ),\n Exists: ({ relation, viewer }) =>\n add(\n relation.owner.name,\n DerivedBy.Exists({\n relation: relation.key,\n viewer: viewer.key,\n owner: entity.name,\n field,\n }),\n ),\n })\n }\n return byPointing\n}\n\n/** Declares a Remote domain: its entities, queries, and mutations, plus the submodel. */\nconst defineRemote = <\n const Entities extends readonly EntityLike[],\n const Queries extends readonly QueryDescriptor<any, any, any>[] = readonly QueryDescriptor<\n any,\n any,\n any\n >[],\n const Mutations extends readonly MutationDescriptor<any, any, any>[] =\n readonly MutationDescriptor<any, any, any>[],\n>(config: {\n readonly entities: Entities\n readonly queries?: Queries\n readonly mutations?: Mutations\n}): RemoteDescriptor<Entities, Queries, Mutations> => {\n const entities = config.entities.map(descriptorOf)\n return {\n entities: entities as unknown as Entities,\n queries: (config.queries ?? []) as unknown as Queries,\n mutations: (config.mutations ?? []) as unknown as Mutations,\n Model: remoteModelSchema(),\n initial: initialRemoteModel,\n Message: remoteMessageSchema,\n update: updateRemote,\n rpc: RemoteRpc,\n registry: {\n entities: new Map(entities.map(entity => [entity.name, entity])),\n queries: new Map((config.queries ?? []).map(query => [query.name, query])),\n mutations: new Map((config.mutations ?? []).map(mutation => [mutation.name, mutation])),\n // Read from the Entities as given: a descriptor keeps no metadata.\n filtered: new Map(\n config.entities.flatMap(entity =>\n DomainEntity.is(entity) ? [[entity.name, ReadFilter.members(entity.metadata)]] : [],\n ),\n ),\n derived: derivedMembersBy(config.entities),\n },\n }\n}\n\n/** Binds a Remote domain to its store's location in the application Model. */\nconst bindRemote = <\n AppModel,\n Store extends RemoteModel,\n Entities extends readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[],\n Mutations extends readonly MutationDescriptor<any, any, any>[],\n>(\n definition: RemoteDescriptor<Entities, Queries, Mutations>,\n ref: ModelRef<AppModel, Store>,\n operators: MemoryOperators,\n): BoundRemote<AppModel, Store, EntityName<Entities[number]>> => {\n const store = ModelRef.focus(ref)\n return {\n definition,\n store,\n operators,\n contract: {\n kind: 'remote',\n name: store.dependency.join('.') || 'remote',\n // A generated field reference knows its application and its path; a raw\n // optic (`ModelRef.fromOptic`) knows neither, so it claims nothing.\n owner: (store as { readonly owner?: object }).owner,\n owns: store.dependency.length === 0 ? [] : [store.dependency],\n observes: store.dependency.length === 0 ? [] : [store.dependency],\n messages: [],\n metadata: [],\n },\n }\n}\n\n/** The runtime half of `Registered`: a descriptor the domain never declared is an error naming both. */\nconst assertRegistered = (\n bound: BoundRemote<any, any>,\n kind: 'Entity' | 'Query' | 'Mutation',\n registered: ReadonlyMap<string, unknown>,\n name: string,\n): void => {\n if (!registered.has(name)) {\n throw new Error(\n `Remote: ${kind} \"${name}\" is not registered with domain \"${bound.contract.name}\"`,\n )\n }\n}\n\n/** What a projection asks of the remote: entity requirements and query connections. */\ninterface Asked {\n readonly requirements: ReadonlyArray<Requirement>\n readonly connections: ReadonlyArray<ConnectionRequirement>\n}\n\nconst askedOf = (projection: Projection<any, unknown>): Asked => ({\n requirements: requirementsOf(projection),\n connections: connectionsOf(projection),\n})\n\n/**\n * Whether `outer` asks for everything `inner` does of one entity: each field,\n * each relation's own slice of its target, and each page window alike.\n */\nconst sliceCovers = (outer: RelationRequirement, inner: RelationRequirement): boolean =>\n outer.entity === inner.entity &&\n inner.fields.every(field => outer.fields.includes(field)) &&\n Object.entries(inner.relations ?? {}).every(([field, relation]) => {\n const wider = outer.relations?.[field]\n return wider !== undefined && sliceCovers(wider, relation)\n }) &&\n Object.entries(inner.windows ?? {}).every(\n ([field, window]) =>\n outer.windows?.[field] !== undefined &&\n stableStringify(outer.windows[field]) === stableStringify(window),\n )\n\n/**\n * Whether what `outer` asks includes everything `inner` asks: each list with\n * the slice it selects of its rows, and each entity with the slice it reads,\n * relations included. A Surface that shows a read is one whose projection\n * asks for all of it; one that reads part of it cannot be why it is fetched.\n * A Surface that asks for one entity in several pieces is already one\n * requirement here: projection metadata unions them per entity and id.\n */\nconst covers = (outer: Asked, inner: Asked): boolean => {\n const { connections, requirements } = outer\n return (\n inner.connections.every(connection =>\n connections.some(\n wider =>\n wider.identity === connection.identity &&\n (connection.select === undefined ||\n (wider.select !== undefined && sliceCovers(wider.select, connection.select))),\n ),\n ) &&\n inner.requirements.every(requirement =>\n requirements.some(wider => wider.id === requirement.id && sliceCovers(wider, requirement)),\n )\n )\n}\n\n/** The plan for what a projection asks: the entity fields to read, and the queries to run. */\ninterface Planned {\n readonly requirements: ReadonlyArray<Requirement>\n readonly queries: ReadonlyArray<QueryRequirement>\n /** Under a freshness, when what is held next goes stale; `null` when nothing held will. */\n readonly expires: Deadline | null\n}\n\n/**\n * Plans what a projection asks against the Model. A connection the Model holds\n * fresh contributes its visible items' selected fields to the entity plan; one\n * it does not hold, or holds stale, is a query to run (its items are planned\n * once the page arrives).\n *\n * A connection whose query failed is not run again here, short of `force`: the\n * failure is what its read shows, and retrying is `Remote.refresh`'s to ask\n * for. The rows it already holds are still planned, since they are on screen.\n */\n/**\n * One requirement per connection and direction: of the sized windows reading\n * a connection from its start (or end), the widest, which covers the rest.\n * Windows with a cursor are pages of their own and stay as they are.\n */\nconst widest = (\n remote: RemoteModel,\n connections: ReadonlyArray<QueryRequirement>,\n): ReadonlyArray<QueryRequirement> => {\n const kept = new Map<string, QueryRequirement>()\n const rest: QueryRequirement[] = []\n for (const connection of connections) {\n const size = windowSize(remote, connection)\n if (size === undefined) {\n rest.push(connection)\n continue\n }\n const key = `${connection.identity}${String.fromCharCode(0)}${connection.window.first === undefined ? 'last' : 'first'}`\n const current = kept.get(key)\n if (current === undefined) kept.set(key, connection)\n else if (size > (windowSize(remote, current) ?? 0))\n kept.set(key, {\n ...connection,\n select: Requirement.mergeRelation(current.select, connection.select),\n })\n else\n kept.set(key, {\n ...current,\n select: Requirement.mergeRelation(current.select, connection.select),\n })\n }\n return [...kept.values(), ...rest]\n}\n\nconst withWindow = (connection: QueryRequirement, window: QueryWindow): QueryRequirement => ({\n ...connection,\n window,\n ref: { ...connection.ref, window },\n})\n\n/**\n * The page a connection lacks for a window of `size` from its start (or end):\n * the rows after its first segment's end cursor (or before its last's start).\n * Undefined when it holds enough, reaches the end, or does not know where it\n * starts.\n */\nconst missingRows = (\n known: Connection,\n window: QueryWindow,\n size: number,\n): QueryWindow | undefined => {\n const forward = window.first !== undefined\n const segment = forward ? known.segments[0] : known.segments[known.segments.length - 1]\n if (segment === undefined) return undefined\n const [from, to] = forward ? [segment.start, segment.end] : [segment.end, segment.start]\n if (from._tag !== 'Terminal' || to._tag !== 'Cursor' || segment.edges.length >= size)\n return undefined\n const lacking = size - segment.edges.length\n return forward ? { first: lacking, after: to.cursor } : { last: lacking, before: to.cursor }\n}\n\nconst planAsked = (\n remote: RemoteModel,\n asked: Asked,\n options: PlanOptions,\n operators: MemoryOperators,\n): Planned => {\n const queries: QueryRequirement[] = []\n const items: Requirement[] = []\n const connections = Requirement.mergeConnections(\n asked.connections,\n ) as ReadonlyArray<QueryRequirement>\n for (const connection of widest(remote, connections)) {\n const known = remote.connections[connection.identity]\n const failed = options.force !== true && connection.identity in remote.failures.connections\n const size = windowSize(remote, connection)\n if (!failed && (known === undefined || known.stale || options.force === true)) {\n queries.push(\n size === undefined\n ? connection\n : withWindow(\n connection,\n connection.window.first === undefined ? { last: size } : { first: size },\n ),\n )\n continue\n }\n if (known === undefined) continue\n // A wider window than the connection holds asks for the rows it lacks.\n const tail =\n failed || size === undefined ? undefined : missingRows(known, connection.window, size)\n if (tail !== undefined) queries.push(withWindow(connection, tail))\n const edges = visibleItems(\n known,\n connection.identity,\n remote.optimistic.overlays,\n goneIn(remote.entities, remote.optimistic),\n )\n items.push(\n ...itemsOf(\n edges.map(edge => edge.ref),\n connection.select,\n ),\n )\n }\n const visible = visibleStoreOf(remote.entities, remote.optimistic, operators)\n const read = [...asked.requirements, ...items]\n const held = heldOnlyByRequests(remote.entities, remote.optimistic)\n const planned = plan(plannedStoreOf(remote.entities, remote.optimistic, visible), read, options)\n const sent = planned.filter(\n requirement => !held.has(entityKey(requirement.entity, requirement.id)),\n )\n return {\n requirements: options.force === true ? sent : withoutFailedFields(remote, sent),\n queries,\n expires:\n options.freshness === undefined\n ? null\n : (deadlineOf(visible, read, options.freshness) ?? null),\n }\n}\n\n/**\n * The plan without the fields whose last read failed. Like a failed query,\n * a failed field is shown rather than retried on its own, so a persistent\n * error is not asked again on every unrelated restart of the read entry. A\n * field leaving the request takes its window and its relation with it.\n */\nconst withoutFailedFields = (\n remote: RemoteModel,\n planned: ReadonlyArray<Requirement>,\n): ReadonlyArray<Requirement> => {\n if (Object.keys(remote.failures.fields).length === 0) return planned\n return planned.flatMap(requirement => {\n const fields = requirement.fields.filter(\n field => !isFieldFailed(remote, requirement.entity, requirement.id, field),\n )\n if (fields.length === requirement.fields.length) return [requirement]\n if (fields.length === 0) return []\n const kept = new Set(fields)\n const only = <T>(record: Readonly<Record<string, T>> | undefined) =>\n record === undefined\n ? undefined\n : Object.fromEntries(Object.entries(record).filter(([field]) => kept.has(field)))\n const windows = only(requirement.windows)\n const relations = only(requirement.relations)\n return [\n {\n entity: requirement.entity,\n id: requirement.id,\n fields,\n ...(windows === undefined || Object.keys(windows).length === 0 ? {} : { windows }),\n ...(relations === undefined || Object.keys(relations).length === 0 ? {} : { relations }),\n ...(requirement.live === undefined ? {} : { live: requirement.live }),\n },\n ]\n })\n}\n\n/** The entity requirements a page's edges add under a selection. */\nconst itemsOf = (\n edges: ReadonlyArray<{ readonly entity: string; readonly id: string }>,\n select: RelationRequirement,\n): ReadonlyArray<Requirement> =>\n edges.filter(edge => edge.entity === select.entity).map(edge => ({ ...select, id: edge.id }))\n\n/**\n * The wire request of a planned query; a `QueryRef` identity carries the query\n * name and the canonical encoded input. A connection requirement built by hand\n * with another identity cannot be run, and fails as a query would.\n */\nconst parsedQueryRequest = (query: {\n readonly identity: string\n readonly window: QueryWindow\n readonly select?: RelationRequirement | undefined\n}): Result.Result<Schema.Schema.Type<typeof QueryRequest>, RemoteQueryError> => {\n const separator = query.identity.indexOf('\\u0000')\n if (separator < 0) {\n return Result.fail(\n new RemoteQueryError({\n message: `connection \"${query.identity}\" is not a query's: only a QueryRef identity can be run`,\n }),\n )\n }\n try {\n return Result.succeed({\n query: query.identity.slice(0, separator),\n input: JSON.parse(query.identity.slice(separator + 1)) as unknown,\n window: query.window,\n ...(query.select === undefined ? {} : { select: query.select }),\n })\n } catch {\n return Result.fail(\n new RemoteQueryError({ message: `connection \"${query.identity}\" carries no encoded input` }),\n )\n }\n}\n\nconst queryRequestOf = (\n query: Parameters<typeof parsedQueryRequest>[0],\n): Effect.Effect<Schema.Schema.Type<typeof QueryRequest>, RemoteQueryError> =>\n Effect.suspend(() =>\n Result.match(parsedQueryRequest(query), { onFailure: Effect.fail, onSuccess: Effect.succeed }),\n )\n\n/** What a live stream subscribes to: rows, and lists as their reads send them. */\ninterface LiveAsk {\n readonly requirements: ReadonlyArray<Requirement>\n readonly queries: ReadonlyArray<Schema.Schema.Type<typeof QueryRequest>>\n}\n\n/**\n * The live rows and lists of what projections ask. A list read live is a\n * `Data.query`, whose identity is always a query's, so one that is not is\n * this package's bug, and throws.\n */\nconst liveAskOf = (asked: Asked): LiveAsk => ({\n requirements: asked.requirements.filter(requirement => requirement.live === true),\n queries: asked.connections.flatMap(connection =>\n connection.live === true ? [Result.getOrThrow(parsedQueryRequest(connection))] : [],\n ),\n})\n\n/**\n * The `ConnectionMerged` for a query result, in the client's edge shape.\n * `refreshes` marks the page as answering the connection's refresh, so one\n * Message both merges it and clears `stale`.\n */\n/**\n * The page a window asked for, or the number of edges that came back instead.\n *\n * A window is a request the client made and the server answered, so more edges\n * than were asked for is a protocol disagreement rather than a windfall: the\n * client cannot tell which of them the window meant, the connection's\n * boundaries stop describing what it holds, and a `first: 25` that quietly\n * becomes a thousand is a memory event with no error attached to it.\n *\n * `undefined` when the page is within its window, or when no size was asked\n * for — `after`/`before` with no `first`/`last` bounds nothing.\n */\nconst overrun = (\n window: QueryWindow,\n edges: ReadonlyArray<unknown>,\n): { readonly asked: number; readonly got: number } | undefined => {\n const asked = window.first ?? window.last\n return asked !== undefined && edges.length > asked ? { asked, got: edges.length } : undefined\n}\n\nconst pageMessage = (\n connection: string,\n result: Schema.Schema.Type<typeof QueryResult>,\n refreshes = false,\n window: QueryWindow = {},\n select?: RelationRequirement | undefined,\n now?: number | undefined,\n): RemoteMessage => {\n // Failed the way any query fails, with a named protocol error, rather than\n // the page being silently accepted or an exception escaping a subscription.\n const over = overrun(window, result.edges)\n if (over !== undefined) {\n return {\n _tag: 'QueryFailed',\n connection,\n error: {\n _tag: 'RemoteProtocolError',\n message: `the server returned ${over.got} edges for a window of ${over.asked}`,\n },\n }\n }\n const hasPayload =\n select !== undefined &&\n ((result.entities !== undefined && result.entities.length > 0) ||\n (result.settled !== undefined && result.settled.length > 0))\n return {\n _tag: 'ConnectionMerged',\n connection,\n page: {\n edges: result.edges.map(edge => ({\n key: edge.key,\n ref: { entity: edge.entity, id: edge.id },\n })),\n start: result.start,\n end: result.end,\n },\n ...(refreshes ? { refreshes } : {}),\n ...(select === undefined || !hasPayload ? {} : { select }),\n ...(hasPayload\n ? {\n entities: [...(result.entities ?? [])],\n settled: [...(result.settled ?? [])],\n now: now ?? 0,\n }\n : {}),\n }\n}\n\n/**\n * The retention roots of some projections: their requirements, their\n * connections (each with the union of what the projections select of its\n * items), and the connections listed by identity alone.\n */\nconst rootsOf = (\n projections: ReadonlyArray<Projection<any, unknown>>,\n options: RetainOptions,\n): RetentionRoots => {\n const connections = new Map<string, ConnectionRoot>()\n for (const identity of (options.connections ?? []).map(connectionIdentity)) {\n connections.set(identity, { identity })\n }\n for (const { identity, select } of projections.flatMap(connectionsOf)) {\n const current = connections.get(identity)?.select\n connections.set(identity, {\n identity,\n select: current === undefined ? select : Requirement.mergeRelation(current, select),\n })\n }\n return {\n requirements: Requirement.merge(projections.flatMap(requirementsOf)),\n connections: [...connections.values()].sort((a, b) => (a.identity < b.identity ? -1 : 1)),\n }\n}\n\n/** Reads requirements and reports the Message that settles them. Never fails. */\nconst readMessage = (\n requirements: ReadonlyArray<Requirement>,\n now: () => number,\n): Effect.Effect<RemoteMessage, never, RemoteClient> =>\n Effect.gen(function* () {\n const client = yield* RemoteClient\n const at = now()\n const result = yield* Effect.result(\n client.read({ version: REMOTE_PROTOCOL_VERSION, requests: requirements }),\n )\n return Result.isFailure(result)\n ? { _tag: 'ReadFailed', requests: requirements, error: remoteError(result.failure) }\n : { _tag: 'ReadReceived', requests: requirements, result: result.success, now: at }\n })\n\n/** Runs a query and reports the page that refreshes its connection, or the failure. Never fails. */\nconst queryMessage = (\n query: {\n readonly identity: string\n readonly window: QueryWindow\n readonly select?: RelationRequirement | undefined\n },\n now: () => number = wallClock,\n): Effect.Effect<RemoteMessage, never, RemoteClient> =>\n Effect.gen(function* () {\n const client = yield* RemoteClient\n const result = yield* Effect.result(\n queryRequestOf(query).pipe(Effect.flatMap(request => client.query(request))),\n )\n return Result.isFailure(result)\n ? { _tag: 'QueryFailed', connection: query.identity, error: remoteError(result.failure) }\n : pageMessage(query.identity, result.success, true, query.window, query.select, now())\n })\n\n/** A query the read entry runs, as its dependencies carry it: plain data Foldkit compares. */\nconst PlannedQuery = Schema.Struct({\n identity: Schema.String,\n window: WindowSchema,\n select: RelationRequest,\n})\n\n/** The dependencies of the read entry: the entity fields to read and the queries to run. */\nexport interface ReadDependencies {\n readonly requirements: ReadonlyArray<Requirement>\n readonly queries: ReadonlyArray<Schema.Schema.Type<typeof PlannedQuery>>\n /**\n * The highest generation the fields this entry reads were refreshed at: a\n * refresh of any of them restarts the entry, and a refresh of anything else\n * leaves it running.\n */\n readonly refresh: number\n /**\n * Under a refreshing policy, when a value the entry holds next ages out and\n * what is due then. Time reaches Remote only as a Message: the entry sleeps\n * until then and emits `RefreshStarted`, which marks the fields stale, and\n * the plan that follows fetches them. A Model that does not change past its\n * `maxAge` is otherwise never looked at again.\n */\n readonly expires: Deadline | null\n}\n\n/**\n * The read entry: plans what `askedOf(model)` asks against the Model and runs\n * the entity read and the queries concurrently. Each Message it emits changes\n * the Model, so Foldkit recomputes the dependencies and restarts the stream\n * (`switchMap`): a merged page's items are planned by that next computation,\n * against the store as it then is, rather than read here unplanned. Nothing\n * the entry needs is spread over two Messages, since the second could be lost\n * to the restart; a page and its refresh are one `ConnectionMerged`.\n */\nconst observeEntry = <AppModel, Store extends RemoteModel, Message>(\n bound: BoundRemote<AppModel, Store>,\n askedOf: (model: AppModel) => Asked,\n toMessage: (message: RemoteMessage) => Message,\n options: ObserveOptions,\n): EntryWithoutKeepAlive<AppModel, Message, ReadDependencies, RemoteClient> => {\n const { policy = RemotePolicy.cacheFirst, now = wallClock } = options\n const read = (requirements: ReadonlyArray<Requirement>) =>\n Effect.map(readMessage(requirements, now), toMessage)\n const run = (query: ReadDependencies['queries'][number]) =>\n Effect.map(queryMessage(query, now), toMessage)\n // A plan is a function of the Remote model, what is asked, and the clock only\n // until the next value ages out (`expires`, which `deadlineOf` computes as\n // exactly that moment), so a Model change the Remote model is not part of\n // (typing in a field) reuses it rather than walking every row again.\n const planned = new WeakMap<\n RemoteModel,\n Map<string, { readonly until: number; readonly dependencies: ReadDependencies }>\n >()\n return {\n dependenciesSchema: Schema.Struct({\n requirements: Schema.Array(ReadRequest),\n queries: Schema.Array(PlannedQuery),\n refresh: Schema.Number,\n expires: Schema.NullOr(Schema.Struct({ at: Schema.Number, due: Schema.Array(ReadRequest) })),\n }),\n modelToDependencies: model => {\n const remote = bound.store.get(model)\n const asked = askedOf(model)\n const askedKey = stableStringify(asked)\n const at = now()\n let byAsked = planned.get(remote)\n const known = byAsked?.get(askedKey)\n if (known !== undefined && at < known.until) return known.dependencies\n const plan = planAsked(remote, asked, RemotePolicy.toPlan(policy, at), bound.operators)\n const dependencies: ReadDependencies = {\n refresh: refreshedAt(\n remote.refresh,\n plan.requirements,\n plan.queries.map(query => query.identity),\n ),\n requirements: plan.requirements,\n queries: plan.queries.map(({ identity, window, select }) => ({\n identity,\n window,\n select,\n })),\n expires: plan.expires,\n }\n if (byAsked === undefined) {\n byAsked = new Map()\n planned.set(remote, byAsked)\n }\n byAsked.set(askedKey, { until: plan.expires?.at ?? Infinity, dependencies })\n return dependencies\n },\n dependenciesToStream: ({ requirements, queries, refresh, expires }) =>\n Stream.concat(\n Stream.fromIterable([\n ...(requirements.length === 0\n ? []\n : [\n // Absent fields read as `Loading` until the read lands.\n toMessage({ _tag: 'ReadStarted', requests: requirements, refresh }),\n // A refreshing policy also marks the present ones stale.\n ...(RemotePolicy.refreshes(policy)\n ? [toMessage({ _tag: 'RefreshStarted', requests: requirements })]\n : []),\n ]),\n // A list with nothing to show reads `Loading` until its page lands.\n ...(queries.length === 0\n ? []\n : [\n toMessage({\n _tag: 'QueryStarted',\n connections: queries.map(query => query.identity),\n }),\n ]),\n ]),\n Stream.merge(\n Stream.mergeAll(\n [\n ...(requirements.length === 0 ? [] : [Stream.fromEffect(read(requirements))]),\n ...queries.map(query => Stream.fromEffect(run(query))),\n ],\n { concurrency: 'unbounded' },\n ),\n // The clock's say, as a Message. Under the Effect clock, so a test\n // can move it; against `now`, so the same clock sets and fires it.\n expires === null\n ? Stream.empty\n : Stream.fromEffect(\n Effect.as(\n Effect.sleep(Math.max(0, expires.at - now())),\n toMessage({ _tag: 'RefreshStarted', requests: expires.due }),\n ),\n ),\n ),\n ),\n }\n}\n\n// Where a restarted stream resumes, not a reason to restart it: every applied\n// event advances the cursor, and a restart per event would close and reopen\n// the server stream each time. Said in the schema rather than with Foldkit's\n// `keepAliveEquivalence`, which would change the entry's public type\n// (`EntryWithoutKeepAlive`, the only entry type Foldkit exports) for every\n// application that spreads Remote's entries into its own.\nconst resumeCursor = Schema.Number.pipe(Schema.overrideToEquivalence(() => () => true))\n\n/** The wait before a stream's restart after `failures` breaks in a row: Sync's transport backoff. */\nconst restartDelay = (options: LiveOptions, failures: number): Duration.Duration => {\n const base = Duration.toMillis(Duration.fromInputUnsafe(options.retryBase ?? '50 millis'))\n const max = Duration.toMillis(Duration.fromInputUnsafe(options.maxRetryDelay ?? '5 seconds'))\n const backoff = Math.min(max, base * 2 ** Math.min(Math.max(failures, 1) - 1, 30))\n return Duration.millis(backoff * (0.8 + Math.random() * 0.4))\n}\n\n/** The live entry: subscribes to `liveOf(model)` from the Model's resume cursor. */\nconst liveEntry = <AppModel, Store extends RemoteModel, Message>(\n bound: BoundRemote<AppModel, Store>,\n liveOf: (model: AppModel) => LiveAsk,\n toMessage: (message: RemoteMessage) => Message,\n options: LiveOptions,\n): EntryWithoutKeepAlive<AppModel, Message, LiveDependencies, RemoteClient> => ({\n dependenciesSchema: Schema.Struct({\n requirements: Schema.Array(ReadRequest),\n queries: Schema.Array(QueryRequest),\n cursor: resumeCursor,\n floor: Schema.Number,\n restarts: Schema.Number,\n // Read when a break restarts the stream; an applied event resetting it is no reason to.\n failures: resumeCursor,\n }),\n modelToDependencies: model => {\n const asked = liveOf(model)\n const stream = liveStreamKey(asked)\n const remote = bound.store.get(model)\n const health = remote.streams[stream]\n return {\n requirements: asked.requirements,\n queries: asked.queries,\n cursor: remote.live[stream]?.cursor ?? 0,\n // A stream is the principal's: `forget` moves the floor, and it restarts.\n floor: remote.refresh.floor,\n restarts: health?.restarts ?? 0,\n failures: health?.failures ?? 0,\n }\n },\n dependenciesToStream: ({ requirements, queries, cursor, restarts, failures }) => {\n if (requirements.length === 0 && queries.length === 0) return Stream.empty\n const stream = liveStreamKey({ requirements, queries })\n const live = Stream.unwrap(\n Effect.gen(function* () {\n const client = yield* RemoteClient\n return client.live({ requirements, queries, after: cursor })\n }),\n ).pipe(\n Stream.map(event =>\n toMessage({\n _tag: 'LiveReceived',\n stream,\n event,\n now: (options.now ?? wallClock)(),\n }),\n ),\n Stream.catchIf(\n (\n _error,\n ): _error is\n | RemoteLiveError\n | RemoteLiveRefused\n | RemoteProtocolError\n | RemoteUnauthenticated => true,\n error =>\n Stream.succeed(\n toMessage({\n _tag: 'ReadFailed',\n requests: requirements,\n error: remoteError(error),\n stream,\n }),\n ),\n ),\n )\n if (restarts === 0) return live\n // The server replays nothing a stream missed while it was down, so a\n // restart refetches what the stream covers. The gap closes before the\n // resubscribe, so a resubscribe that fails is a break of its own; were the\n // two concurrent, its failure could land on the open gap and be ignored,\n // and the late `GapCleared` would leave the stream stopped.\n return Stream.fromEffect(Effect.sleep(restartDelay(options, failures))).pipe(\n Stream.drain,\n Stream.concat(\n Stream.make(\n toMessage({ _tag: 'RefreshStarted', requests: requirements }),\n toMessage({ _tag: 'GapCleared', stream }),\n ),\n ),\n Stream.concat(live),\n )\n },\n})\n\n/** The projection an active entry has for this Model; none while it is inactive. */\nconst projectionOf = <AppModel>(\n entry: ActiveEntry<AppModel>,\n model: AppModel,\n): Option.Option<Projection<AppModel, unknown>> => {\n if ('projectionOf' in entry) return entry.projectionOf(model)\n // A bare Surface without params reads whole; a source without `instancesOf`\n // cannot happen, and resolves to nothing if it does.\n if ('projection' in entry) return Option.some(entry.projection())\n return Option.none()\n}\n\n/** One of an entry's reads, named for diagnostics: a lone Surface keeps its name, a family instance takes `Child[key]`. */\ninterface NamedProjection<AppModel> {\n readonly name: string\n readonly projection: Projection<AppModel, unknown>\n}\n\n/**\n * Every projection an entry resolves to for a Model: the lone one of a\n * `Surface.at`/`Surface.when` value or a bare Surface, or a family's parent\n * first and then each instance. The parent joins so an unloaded parent is\n * fetched before what it reveals; `Data.satisfy` reaches the instances in a\n * later pass. A caller that also passes the parent separately double-covers\n * its requirements, as overlapping Surfaces already do.\n */\nconst resolvedOf = <AppModel>(\n entry: ActiveEntry<AppModel>,\n model: AppModel,\n): ReadonlyArray<NamedProjection<AppModel>> => {\n const source = entry as Partial<SurfaceSource<AppModel>>\n if (typeof source.instancesOf === 'function') {\n const instances = source.instancesOf(model)\n const from = (entry as { readonly from?: ActiveSurface<AppModel> }).from\n // A lone `Surface.at`/`Surface.when` keeps its name; a family names each\n // instance after its key, with the parent first.\n if (from === undefined)\n return instances.map(instance => ({ name: entry.name, projection: instance.projection }))\n return [\n ...Option.toArray(from.projectionOf(model)).map(projection => ({\n name: from.name,\n projection,\n })),\n ...instances.map(instance => ({\n name: `${entry.name}[${instance.key}]`,\n projection: instance.projection,\n })),\n ]\n }\n return Option.toArray(projectionOf(entry, model)).map(projection => ({\n name: entry.name,\n projection,\n }))\n}\n\n/** What some projections ask for together: their requirements and connections unioned. */\nconst askedUnion = (projections: ReadonlyArray<Projection<any, unknown>>): Asked => ({\n requirements: projections.flatMap(requirementsOf),\n connections: projections.flatMap(connectionsOf),\n})\n\n/**\n * `resolvedOf` computed once per Model: the read, live, and retain entries\n * all derive their dependencies from the same projections on the same Model\n * change, and a Surface's `model` callback (which lifts and builds schemas)\n * need not run three times for it. Models are objects, so the memo is weak.\n */\nconst memoizedResolved = <AppModel>(\n entry: ActiveEntry<AppModel>,\n): ((model: AppModel) => ReadonlyArray<NamedProjection<AppModel>>) => {\n const cache = new WeakMap<object, ReadonlyArray<NamedProjection<AppModel>>>()\n return model => {\n const key: unknown = model\n if (typeof key !== 'object' || key === null) return resolvedOf(entry, model)\n const known = cache.get(key)\n if (known !== undefined) return known\n const resolved = resolvedOf(entry, model)\n cache.set(key, resolved)\n return resolved\n }\n}\n\n/**\n * What `Data.refresh` asks again: a projection, a Surface without params, one\n * entry of the active record (a `Surface.at`/`Surface.when` value, a family),\n * the whole record, or one list by its query and input (`Everyone.ref({})`),\n * whatever window reads it.\n */\nexport type RefreshTarget<AppModel, Queries extends string = string> =\n | Projection<AppModel, unknown>\n | ActiveEntry<AppModel>\n | Readonly<Record<string, ActiveEntry<AppModel>>>\n | QueryRef<Queries, any>\n\n/** How `Data.refresh` asks again. */\nexport interface RefreshOptions {\n /** Only what failed: a \"Try again\" leaves what loaded as it is. */\n readonly failed?: boolean | undefined\n}\n\n/** Why the server refused a write, as `mutation` declares it: none for any other failure, or one that does not decode. */\nconst refusalOf = <Refused>(\n error: RemoteError,\n mutation: MutationDescriptor<string, any, any, Refused>,\n): Option.Option<Refused> =>\n error.refusal === undefined\n ? Option.none()\n : Schema.decodeUnknownOption(mutation.Refusal)(error.refusal)\n\n/** Refuses an entry of another application: two can share a Model type, and the owner token tells them apart. */\nconst assertOwnedBy = <AppModel>(contract: Contract, entry: ActiveEntry<AppModel>): void => {\n if (contract.owner === undefined) return\n const from = (entry as { readonly from?: ActiveSurface<AppModel> }).from\n for (const surface of from === undefined ? [entry] : [entry, from]) {\n if (surface.owner !== contract.owner) {\n throw new Error(\n `Remote: Surface \"${surface.name}\" belongs to another application than domain \"${contract.name}\"`,\n )\n }\n }\n}\n\n/** Whether a refresh target is one list by its query and input. */\nconst isQueryRef = <AppModel>(target: RefreshTarget<AppModel>): target is QueryRef<string, any> =>\n // No projection or entry has an identity, and a record's values are entries,\n // never strings, so a record keyed `identity` cannot pass for a ref.\n typeof (target as Partial<Record<'identity', unknown>>).identity === 'string'\n\n/** Whether a refresh target is a projection, the one kind that is not a Surface. */\nconst isProjection = <AppModel>(\n target: RefreshTarget<AppModel>,\n): target is Projection<AppModel, unknown> =>\n typeof (target as Partial<Record<'read', unknown>>).read === 'function'\n\n/** Whether a refresh target is one entry of an active record rather than the record. */\nconst isActiveEntry = <AppModel>(\n target: ActiveEntry<AppModel> | Readonly<Record<string, ActiveEntry<AppModel>>>,\n): target is ActiveEntry<AppModel> => {\n // A record's values are entries, never functions, so a key that happens to\n // be named like a member cannot pass for one.\n const members = target as Partial<Record<'projection' | 'projectionOf' | 'instancesOf', unknown>>\n return (\n typeof members.projectionOf === 'function' ||\n typeof members.instancesOf === 'function' ||\n typeof members.projection === 'function'\n )\n}\n\n/** Every projection a refresh target reads for this Model, each entry resolved as the read entries resolve it. */\nconst targetProjections = <AppModel>(\n contract: Contract,\n target: Exclude<RefreshTarget<AppModel>, QueryRef<string, any>>,\n model: AppModel,\n): ReadonlyArray<Projection<AppModel, unknown>> => {\n if (isProjection(target)) return [target]\n const entries = isActiveEntry(target) ? [target] : Object.values(target)\n // Checked before any is resolved, so a refused call reads nothing.\n for (const entry of entries) assertOwnedBy(contract, entry)\n return entries.flatMap(entry => resolvedOf(entry, model).map(({ projection }) => projection))\n}\n\nexport const Remote = {\n /** The submodel's schema, the same for every domain; embed it in the application Model. */\n Model: remoteModelSchema(),\n /** The submodel's initial value. */\n initial: initialRemoteModel,\n /**\n * Remote's Message cases for `defineMessageUnion`: spread them into the\n * application's union, and reduce the ones `Remote.reduces` recognizes with\n * `RemoteDomain.reduce`.\n */\n messages: remoteMessageCases,\n /** Whether a Message is one of Remote's, by tag. */\n reduces: isRemoteMessage,\n /**\n * Remote's Messages as one Schema, for a wrapper variant in the\n * application's union: `GotRemoteMessage: { message: Remote.Message }`. With\n * a wrapper, `update` matches the application's union exhaustively and\n * `Remote.fold` reduces what arrives inside it.\n */\n Message: defineMessageUnion(remoteMessageCases),\n /**\n * A bound domain under one wrapper variant of the application's union, the\n * same shape Foldkit gives a Submodel: `toParentMessage` wraps Remote's\n * Messages, the fold reduces them, and its `fetch`, `mutate`, and\n * `subscriptions` yield the wrapper. Spreading `Remote.messages` and\n * narrowing with `Remote.reduces` remains the shorter path for an\n * application whose `update` only reduces.\n *\n * @example\n * ```ts\n * const Message = defineMessageUnion({ GotRemoteMessage: { message: Remote.Message } })\n * const foldData = Remote.fold(Data, message => Message.GotRemoteMessage({ message }))\n *\n * const update = (model: Model, message: Message): Return =>\n * Message.match(message, {\n * GotRemoteMessage: ({ message }) => foldData(model, message),\n * })\n * const subscriptions = Subscription.make<Model, Message, RemoteClient>()(() =>\n * foldData.subscriptions({ page: Surface.at(ProjectPage, …) }),\n * )\n * ```\n */\n fold: <Domain extends RemoteDomain<any, any, any, any, any>, ParentMessage>(\n domain: Domain,\n toParentMessage: (message: RemoteMessage) => ParentMessage,\n ): RemoteFold<ModelOfDomain<Domain>, ParentMessage, Domain> => {\n type AppModel = ModelOfDomain<Domain>\n // The application's own update receives every Remote Message here, so it hears each failure.\n const fold = (model: AppModel, message: RemoteMessage | RemoteMessageInput) => {\n const reduced = reduceReporting(domain.store, domain.reduce, model, message, true)\n return {\n model: reduced.model,\n commands: (reduced.commands ?? []).map(command => mapMessage(command, toParentMessage)),\n }\n }\n return Object.assign(fold, {\n mutate: (...args: Parameters<Domain['mutate']>) => {\n const started = domain.mutate(\n ...(args as Parameters<RemoteDomain<AppModel, any, any, any, any>['mutate']>),\n )\n return { ...started, command: mapMessage(started.command, toParentMessage) }\n },\n retry: (...args: Parameters<Domain['retry']>) =>\n Option.map(\n domain.retry(\n ...(args as Parameters<RemoteDomain<AppModel, any, any, any, any>['retry']>),\n ),\n started => ({ ...started, command: mapMessage(started.command, toParentMessage) }),\n ),\n preload: (...args: Parameters<Domain['preload']>) =>\n mapMessage(\n domain.preload(\n ...(args as Parameters<RemoteDomain<AppModel, any, any, any, any>['preload']>),\n ),\n toParentMessage,\n ),\n subscriptions: (\n active: Readonly<Record<string, ActiveEntry<AppModel>>>,\n options?: SubscriptionsOptions,\n ) =>\n markAll(\n messagesAs(brandEntries(domain.subscriptions(active, options)), toParentMessage),\n ) as never,\n })\n },\n\n /**\n * A patch of one entity's values, for a mutation's `optimistic` list or an\n * overlay. Takes a `foldkit-entity` Entity or a Remote descriptor alike, so\n * the domain you declared once is the one you patch:\n * `Remote.patch(Project, 'p1', { name: 'Apollo II' })`. Values are the\n * fields' wire shape, as the server writes them, except a relation, which is\n * a ref (`owner: Remote.ref(User, 'u1')`), an array of refs, or `null` where\n * it is optional. A ref key typed by hand, or a ref to another Entity, is\n * refused, in the type and when the patch is made.\n */\n patch: <E extends EntityLike>(\n entity: E,\n id: string,\n values: PatchValues<FieldsOf<E>>,\n ): EntityPatch<NameOf<E>, FieldsOf<E>> => {\n const descriptor = descriptorOf(entity)\n return descriptor.patch(id, wireValues(descriptor, values)) as EntityPatch<\n NameOf<E>,\n FieldsOf<E>\n >\n },\n\n /**\n * A deletion of one entity, for a mutation's `optimistic` list or an\n * overlay: `Remote.tombstone(Post, 'p1')`. Until it settles the row reads\n * `NotFound` and leaves every list and relation, as an answer's `deleted`\n * does; a failure brings it back. Keeping it gone is the answer's to say.\n */\n tombstone: <E extends EntityLike>(entity: E, id: string): PendingDelete => ({\n _tag: 'Delete',\n ...descriptorOf(entity).ref(id),\n }),\n\n /**\n * A reference to one entity, for `ConnectionChange` and anything else that\n * names a row: `Remote.ref(Project, 'p3')`. Either kind of entity, as with\n * `Remote.patch`.\n */\n ref: <E extends EntityLike>(entity: E, id: string): EntityRef<NameOf<E>, FieldsOf<E>> =>\n descriptorOf(entity).ref(id) as EntityRef<NameOf<E>, FieldsOf<E>>,\n\n /**\n * Declares a Remote domain and binds it to its place in the application Model\n * in one step; the result carries the application-facing operations. The\n * descriptor alone is `Remote.define`, the binding alone `Remote.at`.\n */\n make: <\n AppModel,\n Store extends RemoteModel,\n const Entities extends readonly EntityLike[],\n const Queries extends readonly QueryDescriptor<any, any, any>[] = readonly [],\n const Mutations extends readonly MutationDescriptor<any, any, any>[] = readonly [],\n >(config: {\n readonly model: ModelRef<AppModel, Store>\n readonly entities: Entities\n readonly queries?: Queries\n readonly mutations?: Mutations\n /**\n * Checks each prediction against the server's answer, and records a\n * `PredictionMismatch` in `diagnostics` for each part that disagrees:\n * `Value`, a field a pending write showed that the answer holds otherwise;\n * `Placement`, a list placed in an order the server's first page does not\n * keep (each placed list is fetched too, for its page; a pending edit is\n * not checked, since the server does not have it yet); `Gap`, a row whose\n * answer left out fields the client showed while it was pending and the\n * store does not otherwise hold, so they are read again and the row reads\n * `Loading` meanwhile. Everything else behaves as without it. For\n * development and tests.\n */\n readonly verifyPredictions?: boolean | undefined\n /**\n * How the client runs a body's primitive operators when it judges rows it\n * holds (`Operators`): the kernel's when not given. A body calling one this\n * table lacks is judged by the server instead, as any row the client cannot\n * judge is.\n */\n readonly operators?: MemoryOperators | undefined\n /**\n * Who reads, as a row (`Remote.ref(User, model.me)`), or none for a\n * visitor: whom a declared write predicts each `Derived.exists` for. The\n * store holds one viewer's values, as it holds one principal's: a change\n * of viewer is a change of principal, which `Data.forget`s. Without it, an\n * exists is predicted only where a write takes it away.\n */\n readonly viewer?:\n | ((model: AppModel) => Option.Option<{ readonly entity: string; readonly id: string }>)\n | undefined\n }): RemoteDomain<AppModel, Store, Entities, Queries, Mutations> =>\n bindDomain(defineRemote(config), config.model, {\n verifyPredictions: config.verifyPredictions,\n operators: config.operators,\n viewer: config.viewer,\n }),\n\n /**\n * Declares a Remote domain without binding it: its entities, queries, and\n * mutations, plus the submodel. For a domain reused across applications or\n * bound in a test; `Remote.make` is the one-step form.\n */\n define: defineRemote,\n\n /**\n * Binds a Remote domain to its store's location in the application Model. The\n * registered entity names are carried on the returned value, so `Remote.select`\n * rejects a selection for an entity this domain never declared. `operators`\n * is the client's table, which a pending computed assignment is predicted by\n * (`Operators.kernel` when not given), as `Remote.make`'s is.\n */\n at: <\n AppModel,\n Store extends RemoteModel,\n Entities extends readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[],\n Mutations extends readonly MutationDescriptor<any, any, any>[],\n >(\n definition: RemoteDescriptor<Entities, Queries, Mutations>,\n store: ModelRef<AppModel, Store>,\n options: { readonly operators?: MemoryOperators | undefined } = {},\n ): BoundRemote<AppModel, Store, EntityName<Entities[number]>> =>\n bindRemote(definition, store, options.operators ?? Operators.kernel),\n\n /**\n * The resume part for this domain, for `foldkit-ssr`'s `SSR.plan({ parts })`:\n * a server render sends what the plan's active Surfaces read from the store,\n * each connection with its boundaries and each live cursor with it, and\n * nothing else. `id` tells two domains in one application apart.\n */\n resume: resumePart,\n\n /**\n * A Projection node that reads a `RemoteData` value out of the store. The id\n * is supplied by the caller, usually from a Surface's params. The assembled\n * value is decoded against the Selection, so malformed server data surfaces\n * as `Failed` instead of being asserted into `Value`. A present value with a\n * stale field reads as `Refreshing`: an observer is refetching it.\n */\n select: <AppModel, Store extends RemoteModel, Names extends string, Value, Name extends string>(\n bound: BoundRemote<AppModel, Store, Names>,\n given: EntitySelection<Value, Name> & Registered<Name, Names, 'Entity'>,\n ) => {\n const selection = selectionOf<Value, Name>(given)\n assertRegistered(bound, 'Entity', bound.definition.registry.entities, selection.entity)\n const relation = relationOf(selection)\n const relationKey = stableStringify(relation)\n return (id: string): Projection<AppModel, RemoteData<Value>> => ({\n Model: remoteDataSchema(selection.schema),\n dependencies: [],\n metadata: RemoteRequirements.of({ ...relation, id }),\n read: (root: AppModel): RemoteData<Value> => {\n const store = storeOf(bound, root)\n const key = entityKey(selection.entity, id)\n // The store-dependent half is memoized per store snapshot; `undefined`\n // means the store lacks the value. Whether that reads as `Loading` or\n // `Initial` depends on the in-flight marks, which change independently\n // of the store, so it is decided outside the memo.\n const present = memoRead<RemoteData<Value> | undefined>(\n [store],\n `${key}\\u0000${relationKey}`,\n () => {\n if (isTombstone(store, key)) return { _tag: 'NotFound' }\n const assembled = assemble(store, key, relation)\n if (assembled === undefined) return unavailableFailure(store, key, relation)\n const decoded = decodeRow(selection.schema, store[key]!.values, assembled.values)\n return Result.isFailure(decoded)\n ? { _tag: 'Failed', error: { _tag: 'DecodeError', message: decoded.failure.message } }\n : assembled.refreshing\n ? { _tag: 'Refreshing', value: decoded.success }\n : { _tag: 'Ready', value: decoded.success }\n },\n )\n // Decided outside the memo, as loading is: a failure can arrive\n // without the store changing.\n const remote = bound.store.get(root)\n const failure = failureOf(remote, selection.entity, id, relation)\n if (present !== undefined) {\n // A value on screen whose refresh failed stays on screen, with the\n // error, which `RemoteData.render` draws as stale.\n return failure !== undefined &&\n (present._tag === 'Ready' || present._tag === 'Refreshing')\n ? { _tag: 'Failed', error: failure, previous: present.value }\n : present\n }\n if (isLoadingThrough(remote, selection.entity, id, relation)) return { _tag: 'Loading' }\n if (failure !== undefined) return { _tag: 'Failed', error: failure }\n // A preview of something the server has not seen: what the overlay\n // leaves out will never arrive, so waiting would be `Initial` for good.\n if (onlyOverlaid(remote, selection.entity, id)) {\n const lacking = missingFields(store, key, relation.fields)\n return {\n _tag: 'Failed',\n error: {\n _tag: 'Overlaid',\n message: `${selection.entity} ${id} is shown only by an overlay, which does not hold ${\n lacking.length === 0 ? 'what its relations select' : lacking.join(', ')\n }; the server has not seen it, so nothing will fetch them.`,\n },\n }\n }\n // Nothing is fetching this: no active Surface observes it, which is\n // usually a wiring mistake.\n return { _tag: 'Initial' }\n },\n })\n },\n\n /**\n * When what a projection shows was last received, and whether it is stale\n * or loading. Pure, so a view can show \"updated 5s ago\" without I/O.\n *\n * `updatedAt` is the newest server write among what is shown, as the\n * store dates it; `undefined` when nothing shown was received (nothing\n * loaded, or only an optimistic preview). `stale` is any shown field or\n * connection marked stale; `loading` is any of them in flight. Optimistic\n * previews do not date: showing only one reads `updatedAt: undefined`.\n */\n meta: <AppModel, Store extends RemoteModel, Value>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n projection: Projection<AppModel, Value>,\n ): ReadMeta => metaOf(bound.store.get(model), askedOf(projection), bound.operators),\n\n /**\n * The pure plan for a projection against a Model: the requirements its\n * remote store does not satisfy, under `options` (freshness, force). A\n * Surface's projection is `surface.projection(params)`.\n */\n plan: <AppModel, Store extends RemoteModel, Value>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options?: PlanOptions,\n ): ReadonlyArray<Requirement> =>\n planAsked(bound.store.get(model), askedOf(projection), options ?? {}, bound.operators)\n .requirements,\n\n /**\n * The queries a projection needs run before its connections read: those the\n * Model does not hold, or holds stale (every one under `force`).\n */\n planQueries: <AppModel, Store extends RemoteModel, Value>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options?: PlanOptions,\n ): ReadonlyArray<QueryRef<string, unknown>> =>\n planAsked(\n bound.store.get(model),\n askedOf(projection),\n options ?? {},\n bound.operators,\n ).queries.flatMap(query => (query.ref === undefined ? [] : [query.ref])),\n\n /**\n * The store reads see: the base store under the pending optimistic layers.\n * One store is shared by every read and plan of a Model whose remote state\n * has not changed.\n */\n storeOf: <AppModel, Store extends RemoteModel>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n ): EntityStore => storeOf(bound, model),\n\n /**\n * The projection read against the server-derived store alone: the same\n * requirements, planned the same way, with the pending optimistic layers and\n * connection overlays left off. See the bound `Remote.confirmed`.\n */\n confirmed: <AppModel, Store extends RemoteModel, P extends Projection<AppModel, any>>(\n bound: BoundRemote<AppModel, Store>,\n projection: P,\n ): P => confirmed(bound, projection),\n\n /**\n * Executes the plan against the `RemoteClient` and returns a new store. Used\n * for SSR route prefetch, hover prefetch, and tests. Never called during render.\n * `policy` decides what a present field means (default cache-first); `now`\n * is the clock it reads, so the planner itself stays pure and time-injected.\n */\n prefetch: Effect.fn('Remote.prefetch')(function* <AppModel, Store extends RemoteModel, Value>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n projection: Projection<AppModel, Value>,\n options: ObserveOptions = {},\n ) {\n const store = storeOf(bound, model)\n const { policy = RemotePolicy.cacheFirst, now = wallClock } = options\n const at = now()\n const missing = plan(store, requirementsOf(projection), RemotePolicy.toPlan(policy, at))\n if (missing.length === 0) return store\n yield* Effect.annotateCurrentSpan('requirementCount', missing.length)\n const client = yield* RemoteClient\n const result = yield* client.read({ version: REMOTE_PROTOCOL_VERSION, requests: missing })\n return writeRead(store, missing, result, at)\n }),\n\n /**\n * Marks what a read requires as due again: a projection, a Surface without\n * params, one entry of the active record, or the whole record, each entry\n * resolved for this Model as `subscriptions` resolves it. Called from\n * `update`: every selected field the store holds reads `Refreshing`, and\n * every loaded query connection is invalidated. Nothing is fetched here.\n * The read entries `Data.subscriptions` derives refetch it, because a stale\n * field or connection is planned again under every policy, so a refresh never\n * sends a request beside the entry already observing the same data.\n *\n * A refreshed connection's page replaces its pages, so items the server removed\n * or reordered follow it; pages loaded past the first are dropped and paged\n * again with `next`/`previous`. The read entries restart, so a read or query\n * sent before the refresh is not applied after it.\n *\n * It is also how a failed read is retried: nothing that failed is asked\n * again on its own, so its read stays `Failed` until this asks. A failed\n * read with nothing to show reads `Loading` from here, and `Failed` again if\n * the retry fails. `{ failed: true }` asks again only what failed, which is\n * what a \"Try again\" means: what loaded keeps its value and its pages.\n *\n * The projection must be observed, which it is while it is on screen. Live\n * subscriptions are left as they are. For data nothing observes (SSR, tests),\n * use `Remote.prefetch` with `RemotePolicy.networkOnly`. Refreshing what is\n * already being refreshed returns the same Model.\n */\n refresh: <AppModel, Store extends RemoteModel>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n target: RefreshTarget<AppModel>,\n options: RefreshOptions = {},\n ): AppModel => {\n const remote = bound.store.get(model)\n if (isQueryRef(target)) {\n assertRegistered(bound, 'Query', bound.definition.registry.queries, target.query)\n // Only a list the Model holds, or whose query failed, has anything to ask again.\n const failed = Object.hasOwn(remote.failures.connections, target.identity)\n const due =\n failed || (options.failed !== true && remote.connections[target.identity] !== undefined)\n return due\n ? bound.store.set(model, invalidateConnections(remote, [target.identity]) as Store)\n : model\n }\n const asked = askedUnion(targetProjections(bound.contract, target, model))\n const merged = Requirement.mergeConnections(\n asked.connections,\n ) as ReadonlyArray<QueryRequirement>\n // A loaded connection's current items are marked with the entities; its page\n // is re-run by the read entry, and new items are planned when it lands.\n const items = merged.flatMap(connection => {\n const known = remote.connections[connection.identity]\n return known === undefined\n ? []\n : itemsOf(\n visibleItems(\n known,\n connection.identity,\n remote.optimistic.overlays,\n goneIn(remote.entities, remote.optimistic),\n ).map(edge => edge.ref),\n connection.select,\n )\n })\n const asking = [...asked.requirements, ...items]\n // `failed` asks again only what failed: each entity read whose own or\n // related fields failed, and each list whose query did. The rest, a\n // list's later pages included, stays as it is.\n const connections =\n options.failed === true\n ? merged.filter(connection => connection.identity in remote.failures.connections)\n : merged\n const requirements = plan(\n visibleStoreOf(remote.entities, remote.optimistic, bound.operators),\n options.failed === true\n ? asking.filter(\n requirement =>\n failureOf(remote, requirement.entity, requirement.id, requirement) !== undefined,\n )\n : asking,\n { force: true },\n )\n\n // A connection the Model never loaded is already a query to run: there is\n // nothing to invalidate and nothing to restart, so it takes no generation\n // either — unless its query failed, which is exactly what a refresh retries.\n const invalidated = connections\n .filter(\n connection =>\n remote.connections[connection.identity] !== undefined ||\n connection.identity in remote.failures.connections,\n )\n .map(connection => connection.identity)\n const marks: RemoteMessage[] = [\n ...(requirements.length === 0\n ? []\n : [{ _tag: 'RefreshStarted' as const, requests: requirements }]),\n ...invalidated.map(connection => ({\n _tag: 'ConnectionInvalidated' as const,\n connection,\n })),\n ]\n const marked = marks.reduce(updateRemote, remote)\n // Fields already stale may be in a read that began before this refresh (a\n // refreshing policy marks what it refetches); unless no read has begun since\n // the last refresh, that read is restarted too.\n const inFlight = requirements.some(requirement =>\n requirement.fields.some(\n field =>\n remote.entities[entityKey(requirement.entity, requirement.id)]?.stale.has(field) ===\n true && refreshIsInFlight(remote.refresh, requirement, field),\n ),\n )\n // Marking what is already marked changes nothing, so the Model keeps its identity.\n if (marked === remote && !inFlight) return model\n const refresh = withRefreshRequested(marked.refresh, requirements, invalidated)\n return bound.store.set(model, { ...marked, refresh } as Store)\n },\n\n /**\n * Forgets everything the server told this Model: values, tombstones,\n * unavailable fields, connections, live cursors, failures. What is known is\n * known for a principal, and this is the one boundary for a login, a logout\n * or a switch of organization: called from `update`, it performs no I/O, and\n * every active Surface's read and live entries restart, so the screen asks\n * again as whoever the client now is. A read or stream begun before is\n * interrupted rather than landing after. A mutation in flight is treated as\n * applied: its answer writes nothing here.\n */\n forget: <AppModel, Store extends RemoteModel>(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n ): AppModel => bound.store.set(model, forgetRemote(bound.store.get(model)) as Store),\n\n /**\n * Writes a read result into the store, recording each field's applied window.\n * `requests` are the planned requirements the result answers.\n */\n writeRead,\n\n /**\n * Adapts an Effect RPC client for `RemoteRpc` to `RemoteClient`, so an\n * application provides the transport's RPC layer instead of writing the\n * `LiveChange`-to-`LiveEvent` mapping by hand. The client `RpcClient.make`\n * builds is accepted as it is: when its transport fails (`RpcClientError`),\n * the call fails with its own Remote error, which the application shows and\n * retries like any failed read, query, mutation or live stream.\n */\n /**\n * Remote's client over any way of sending one JSON request and receiving its\n * answer, for `clientLayer`: a worker, a server in the page. `RemoteServer.answer`\n * is the other end.\n */\n json: jsonClient,\n\n /**\n * Remote's client over HTTP, for `clientLayer`: each call a `POST` of the JSON\n * request to `url`. `headers` is read per request (a session token, say).\n */\n http: httpClient,\n\n /**\n * Remote's client over HTTP with live, for `clientLayer`: reads, queries,\n * and mutations as `http` sends them, live requirements as one `POST`\n * answered with a `text/event-stream` of changes.\n * `foldkit-remote-server/fetch` is the other end.\n */\n httpWithLive: httpWithLiveClient,\n\n clientLayer: <R = never>(\n client: RemoteRpcClient<R, RpcClientError.RpcClientError | RemoteUnreachable>,\n options: CoalesceOptions = {},\n ): Layer.Layer<RemoteClient, never, R> =>\n coalescedLayer(\n Layer.effect(\n RemoteClient,\n Effect.gen(function* () {\n // What the RPC client needs (a database under in-process handlers,\n // nothing under a transport) is supplied once, when the layer is built.\n const context = yield* Effect.context<R>()\n return {\n read: batch =>\n client.FoldkitRemoteRead(batch).pipe(\n Effect.catchTag(['RpcClientError', 'Unreachable'], error =>\n Effect.fail(new RemoteReadError({ message: error.message })),\n ),\n Effect.provideContext(context),\n ),\n query: request =>\n client.FoldkitRemoteQuery(request).pipe(\n Effect.catchTag(['RpcClientError', 'Unreachable'], error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n Effect.provideContext(context),\n ),\n mutate: request =>\n client.FoldkitRemoteMutate(request).pipe(\n // The transport failed: the request may not have reached the server.\n Effect.catchTag('RpcClientError', error =>\n Effect.fail(new RemoteUnreachable({ message: error.message })),\n ),\n Effect.provideContext(context),\n ),\n live: ({ requirements, queries, after }) =>\n client\n .FoldkitRemoteLive({\n version: REMOTE_PROTOCOL_VERSION,\n requirements,\n ...(queries.length === 0 ? {} : { queries }),\n after,\n })\n .pipe(\n Stream.catchTag(['RpcClientError', 'Unreachable'], error =>\n Stream.fail(new RemoteLiveError({ message: error.message })),\n ),\n Stream.map(liveEventOf),\n Stream.provideContext(context),\n ),\n }\n }),\n ),\n options,\n ),\n\n /**\n * Wraps a `RemoteClient` layer so its reads coalesce: requirements issued\n * together become one batch, and a requirement already in flight is joined.\n * `Remote.clientLayer` applies this; use it on a hand-written client.\n */\n coalesced: coalescedLayer,\n\n /**\n * A Foldkit Subscription entry that keeps the cache to what the active\n * Surfaces reach. `projections` are the ones the application observes (the\n * same it passes to `Remote.observe`), `connections` the query connections\n * it shows; anything else is collected once the roots have been stable for\n * `grace`, so a route transition that comes straight back does not thrash.\n */\n retain: <AppModel, Message = RemoteMessage>(\n projections: ReadonlyArray<Projection<AppModel, unknown>>,\n toMessage: (message: RemoteMessage) => Message = identityMessage as never,\n options: RetainOptions = {},\n ): EntryWithoutKeepAlive<AppModel, Message, RetentionRoots, never> => {\n const roots = rootsOf(projections, options)\n return {\n dependenciesSchema: retentionRootsSchema,\n modelToDependencies: () => roots,\n dependenciesToStream: current =>\n Stream.fromEffect(\n Effect.succeed(toMessage({ _tag: 'RetentionChanged', roots: current })).pipe(\n Effect.delay(options.grace ?? 0),\n ),\n ),\n }\n },\n\n /**\n * Runs a `Query` through `RemoteClient`, encoding its input from the ref.\n * Pair the result with `Remote.queryMessage` to merge the page into the Model.\n * With `select`, the server also returns the selected fields of the page's\n * items, so one response populates both the connection and the store.\n */\n query: Effect.fn('Remote.query')(function* <Name extends string, Input>(\n ref: QueryRef<Name, Input>,\n select?: RelationRequirement | undefined,\n ) {\n const client = yield* RemoteClient\n const input = yield* Schema.encodeUnknownEffect(ref.Input)(ref.input).pipe(\n Effect.catchTag('SchemaError', error =>\n Effect.fail(new RemoteQueryError({ message: error.message })),\n ),\n )\n return yield* client.query({\n query: ref.query,\n input,\n window: ref.window,\n ...(select === undefined ? {} : { select }),\n })\n }),\n\n /** The `RemoteMessage` that merges a query page into its connection. */\n queryMessage: <Name extends string, Input>(\n ref: QueryRef<Name, Input>,\n result: Schema.Schema.Type<typeof QueryResult>,\n select?: RelationRequirement | undefined,\n now?: number | undefined,\n ): RemoteMessage => pageMessage(ref.identity, result, false, ref.window, select, now),\n\n /** A pure, serializable view of the whole cache. */\n inspect: inspectRemote,\n\n /** A pure, serializable view of one entity, or `undefined` if unknown. */\n inspectEntity,\n\n /**\n * Runs a mutation through `RemoteClient`, decoding its typed Output and\n * returning the result's normalized patches so the caller can reconcile them\n * through `updateRemote`'s `MutationSucceeded` (or `Remote.mutateInto`).\n */\n mutate: mutateRemote,\n\n /**\n * Reads the clock where the reader acts, for `Data.mutate`'s `now`: a\n * Command that yields `toMessage(now)`, the time in milliseconds since the\n * epoch. It reads Effect's `Clock`, so a test pins it, and `Trace.run`\n * runs it at the trace's time. Chirp's compose box answers a submit with\n * `Remote.now(now => Message.ClockedPost({ post, now }))`, and\n * `ClockedPost` starts the write.\n */\n now: <M>(\n toMessage: (now: number) => M,\n ): { readonly name: 'Remote.now'; readonly effect: Effect.Effect<M> } => ({\n name: 'Remote.now',\n effect: Effect.map(Clock.currentTimeMillis, toMessage),\n }),\n\n /**\n * Runs a mutation and reconciles its patches into a `RemoteModel` in one step,\n * returning the new model alongside the typed Output. The model-level form of\n * `MutationStarted` → `RemoteClient.mutate` → `MutationSucceeded`; in an\n * application the three are `update` (with `optimistic`), a Command, and the\n * Message the Command returns, so the optimistic operations show meanwhile.\n */\n mutateInto: Effect.fn('Remote.mutateInto')(function* <\n Name extends string,\n Input,\n Output,\n AppModel,\n Store extends RemoteModel,\n >(\n bound: BoundRemote<AppModel, Store>,\n model: AppModel,\n mutation: MutationDescriptor<Name, Input, Output>,\n input: Input,\n requestId: string,\n options: MutateOptions = {},\n ) {\n const started = updateRemote(bound.store.get(model), {\n _tag: 'MutationStarted',\n requestId,\n ...(options.optimistic === undefined ? {} : { optimistic: options.optimistic }),\n })\n const outcome = yield* mutateRemote(mutation, input, requestId, { now: options.now })\n const settled = updateRemote(started, {\n _tag: 'MutationSucceeded',\n requestId,\n entities: outcome.entities,\n connections: outcome.connections,\n deleted: outcome.deleted,\n now: yield* Clock.currentTimeMillis,\n })\n return {\n output: outcome.output,\n model: bound.store.set(model, settled as Store),\n }\n }),\n\n /**\n * A Foldkit Subscription entry that plans a Surface's missing fields from the\n * Model and fetches them through `RemoteClient`, emitting a `RemoteMessage`\n * per outcome. Wrap it in an application Message (`toMessage`) and reduce it\n * with the domain's `update`. Under a refreshing `policy` the entry first\n * emits `RefreshStarted`, so the fields being refetched read as `Refreshing`\n * while the request is pending.\n */\n observe: <\n AppModel,\n Store extends RemoteModel,\n Names extends string,\n Model,\n SurfaceMessage,\n Params,\n Message = RemoteMessage,\n >(\n bound: BoundRemote<AppModel, Store, Names>,\n surface: Surface<AppModel, Model, SurfaceMessage, Params>,\n params: Params,\n toMessage: (message: RemoteMessage) => Message = identityMessage as never,\n options: ObserveOptions = {},\n ): EntryWithoutKeepAlive<AppModel, Message, ReadDependencies, RemoteClient> =>\n observeEntry(bound, () => askedOf(surface.projection(params)), toMessage, options),\n\n /**\n * A Foldkit Subscription entry that consumes the live stream for a Surface's\n * requirements, emitting a `LiveReceived` per event and a `ReadFailed`\n * carrying its `stream` when the stream breaks (including\n * `ResumeUnavailable`). That records a gap on the stream rather than a failed\n * read, since nothing was being read, and restarts the entry after a\n * backoff; the restart refetches what it covers. The resume cursor is read\n * from `RemoteModel.live`, so the application tracks no cursor of its own.\n */\n live: <\n AppModel,\n Store extends RemoteModel,\n Names extends string,\n Model,\n SurfaceMessage,\n Params,\n Message = RemoteMessage,\n >(\n bound: BoundRemote<AppModel, Store, Names>,\n surface: Surface<AppModel, Model, SurfaceMessage, Params>,\n params: Params,\n toMessage: (message: RemoteMessage) => Message = identityMessage as never,\n options: LiveOptions = {},\n ): EntryWithoutKeepAlive<AppModel, Message, LiveDependencies, RemoteClient> =>\n liveEntry(\n bound,\n () => {\n const projection = surface.projection(params)\n // Every row the Surface reads; a list only where it is read live.\n return { ...liveAskOf(askedOf(projection)), requirements: requirementsOf(projection) }\n },\n toMessage,\n options,\n ),\n}\n\n// A domain's Subscription entries are unbranded so an application can spread\n// them into its own `Subscription.make`; wiring hands them over as a branded record.\n/**\n * Each entry with its Messages as the parent's and its dependencies as they\n * were. The Model is the parent's already, and `Subscription.lift` would wrap\n * every entry's dependencies in `maybeDependencies` (since Foldkit 0.166).\n */\nconst messagesAs = <AppModel, ParentMessage>(\n entries: Subscription.Subscriptions<AppModel, RemoteMessage, RemoteClient>,\n toParentMessage: (message: RemoteMessage) => ParentMessage,\n) =>\n Record.map(entries, entry => ({\n ...entry,\n dependenciesToStream: (dependencies: unknown, read: () => unknown) =>\n Stream.map(entry.dependenciesToStream(dependencies, read), toParentMessage),\n }))\n\ntype Answer = Extract<RemoteMessage, { readonly _tag: 'MutationSucceeded' }>\n\n/**\n * An answer with what it read folded into its patches, one per row, so a list\n * is placed by every value the answer wrote, a derived field it read included.\n */\nconst withAnswerRead = (answer: Answer): Answer => {\n if (answer.read === undefined) return answer\n const rows = new Map<string, NormalizedPatch>()\n for (const patch of [...answer.entities, ...answer.read.result.entities]) {\n const key = entityKey(patch.entity, patch.id)\n const held = rows.get(key)\n rows.set(\n key,\n held === undefined ? patch : { ...held, values: { ...held.values, ...patch.values } },\n )\n }\n return { ...answer, entities: [...rows.values()] }\n}\n\nconst brandEntries = <AppModel>(\n entries: Readonly<Record<string, RemoteEntry<AppModel, any>>>,\n): Subscription.Subscriptions<AppModel, RemoteMessage, RemoteClient> =>\n Subscription.make<AppModel, RemoteMessage, RemoteClient>()(() => entries)\n\n/** The bound domain: the descriptor, the binding, and the operations over them. */\nconst bindDomain = <\n AppModel,\n Store extends RemoteModel,\n Entities extends readonly EntityLike[],\n Queries extends readonly QueryDescriptor<any, any, any>[],\n Mutations extends readonly MutationDescriptor<any, any, any>[],\n>(\n definition: RemoteDescriptor<Entities, Queries, Mutations>,\n ref: ModelRef<AppModel, Store>,\n options: {\n readonly verifyPredictions?: boolean | undefined\n readonly operators?: MemoryOperators | undefined\n readonly viewer?:\n | ((model: AppModel) => Option.Option<{ readonly entity: string; readonly id: string }>)\n | undefined\n } = {},\n): RemoteDomain<AppModel, Store, Entities, Queries, Mutations> => {\n const operators = options.operators ?? Operators.kernel\n const bound = bindRemote(definition, ref, operators)\n const store = bound.store\n const viewerOf = options.viewer ?? (() => Option.none())\n // What a body's `Expr.viewer` reads here. The client has no reading of the\n // time a server judges a list at, so a body over `Expr.now` is the server's.\n const contextOf = (model: AppModel): ExprContext => ({\n viewer: viewerOf(model),\n now: Option.none(),\n })\n // Every reader any `subscriptions` call names, and every connection one keeps:\n // retention is the domain's, so each call's retain entry roots them all, and\n // one call with its own policy does not collect what another call reads.\n const readers = new Map<\n ActiveEntry<AppModel>,\n (model: AppModel) => ReadonlyArray<NamedProjection<AppModel>>\n >()\n const keptConnections = new Set<string>()\n /**\n * What to do with a row a live event says was inserted into a connection.\n *\n * Resolved here rather than in the pure reducer because this is the only\n * place with both the Model and the registry, and two separate things needed\n * one or the other.\n *\n * **The declared policy reaches the decision.** `Query.connection(E, { live })`\n * has always been typed, documented, carried on the descriptor and encoded in\n * the Message schema — and nothing ever put it on a Message, so every live\n * insert took the default whatever an application asked for. It does now.\n *\n * **A row the client can judge does not need a policy.** The policy exists\n * because nothing could tell whether an inserted row belonged to the query.\n * Where the body says it does not, `ignore` is not a guess. Where the body\n * says it does, or the client cannot tell — a row it never fetched, or holds\n * without a field the body reads — the declared policy is the answer, exactly\n * as it was meant to be.\n *\n * Only membership is decided here. *Where* a row sorts needs text collation,\n * which is the backend's, so the position the event carries stands.\n */\n const livePolicyFor = (model: AppModel, event: LiveEvent): LivePolicy | undefined => {\n if (event._tag !== 'ConnectionInsert') return undefined\n // An identity is always `name`, the separator, and the encoded input — it\n // is minted in exactly one place — so the separator is always present.\n const identity = event.connection\n const descriptor = definition.registry.queries.get(\n identity.slice(0, identity.indexOf(IDENTITY_SEPARATOR)),\n )\n const declared = (descriptor?.Result as Partial<ConnectionSpec> | undefined)?.live\n if (descriptor?.body === undefined) return declared\n const encoded = JSON.parse(identity.slice(identity.indexOf(IDENTITY_SEPARATOR) + 1)) as Record<\n string,\n unknown\n >\n const decided = belongsEncoded(\n storeOf(bound, model),\n descriptor,\n encoded,\n entityKey(event.edge.ref.entity, event.edge.ref.id),\n operators,\n contextOf(model),\n )\n return decided === 'no' ? { prepend: 'ignore', append: 'ignore' } : declared\n }\n\n // An application-union case has the runtime shape of the `RemoteMessage` it names.\n const reduce = (model: AppModel, message: RemoteMessage | RemoteMessageInput): AppModel => {\n const live =\n message._tag === 'LiveReceived'\n ? (message as Extract<RemoteMessage, { _tag: 'LiveReceived' }>)\n : undefined\n // A caller that said what it wanted keeps it; `updateRemote` on its own is\n // unchanged, so the pure reducer stays testable without a registry.\n const resolved =\n live === undefined || live.policy !== undefined\n ? message\n : { ...live, policy: livePolicyFor(model, live.event) }\n const remote = store.get(model)\n const reduced = updateRemote(remote, resolved as RemoteMessage)\n const answer =\n message._tag === 'MutationSucceeded'\n ? (message as Extract<RemoteMessage, { _tag: 'MutationSucceeded' }>)\n : undefined\n // A repeated answer finds every value it carries already held, so it\n // changes nothing and invalidates nothing.\n const next =\n answer === undefined\n ? placedNews(reduced, newsOf(message), remote.entities, contextOf(model))\n : impactOf(\n reduced,\n remote.mutations.applied.has(answer.requestId) ? answer : withAnswerRead(answer),\n remote.entities,\n contextOf(model),\n )\n const checked =\n answer === undefined || options.verifyPredictions !== true\n ? next\n : withAnswerChecked(model, remote, next, answer)\n return checked === remote ? model : store.set(model, checked as Store)\n }\n\n /**\n * `after` with each part of the request's prediction the answer disagreed\n * with (`verifyPredictions`): a field it showed that the answer holds\n * otherwise (`Value`), and a row it left without fields the client showed\n * (`Gap`).\n */\n const withAnswerChecked = (\n model: AppModel,\n before: RemoteModel,\n after: RemoteModel,\n answer: Extract<RemoteMessage, { _tag: 'MutationSucceeded' }>,\n ): RemoteModel => {\n const { requestId } = answer\n // A repeated answer writes nothing, so it leaves nothing out.\n if (before.mutations.applied.has(requestId)) return after\n const mutation = Option.map(\n Option.fromUndefinedOr(before.mutations.writes.get(requestId)),\n write => write.mutation,\n )\n const settled = store.set(model, after as Store)\n const projections = [...readers.values()].flatMap(resolvedAt =>\n resolvedAt(settled).map(({ projection }) => projection),\n )\n const found = [\n ...valueMismatches(requestId, mutation, before, after, answer),\n ...answerGaps(\n requestId,\n mutation,\n before.optimistic,\n after.optimistic,\n visibleStoreOf(after.entities, after.optimistic, operators),\n planAsked(unverified(after), askedUnion(projections), {}, operators).requirements,\n ),\n ]\n return found.length === 0\n ? after\n : { ...after, diagnostics: withDiagnostics(after.diagnostics, found) }\n }\n\n /**\n * `remote` with each list placed only to be checked (`placed`) read as it\n * would be without the check: such a list is fetched for its page, and a\n * stale list plans no reads of its rows, so a gap in them would go unseen.\n */\n const unverified = (remote: RemoteModel): RemoteModel => {\n const checked = Object.keys(remote.placed).filter(\n identity => remote.connections[identity] !== undefined,\n )\n if (checked.length === 0) return remote\n const connections = { ...remote.connections }\n for (const identity of checked)\n connections[identity] = { ...connections[identity]!, stale: false }\n return { ...remote, connections }\n }\n\n /**\n * Each field the request's layer showed that its answer carries another\n * value of. A field the answer does not carry is the `Gap`'s; one a request\n * still pending also patches shows that request's value before and after,\n * so it is not judged.\n */\n const valueMismatches = (\n requestId: string,\n mutation: Option.Option<string>,\n before: RemoteModel,\n after: RemoteModel,\n answer: Extract<RemoteMessage, { _tag: 'MutationSucceeded' }>,\n ): ReadonlyArray<PredictionMismatch> => {\n const layer = before.optimistic.layers.find(each => each.id === requestId)\n if (layer === undefined) return []\n const shown = visibleStoreOf(before.entities, before.optimistic, operators)\n const answered = new Map<string, Readonly<Record<string, unknown>>>()\n for (const row of [...answer.entities, ...(answer.read?.result.entities ?? [])]) {\n const key = entityKey(row.entity, row.id)\n answered.set(key, { ...answered.get(key), ...row.values })\n }\n const stillPatched = new Set(\n after.optimistic.layers.flatMap(each =>\n each.patches.flatMap(patch =>\n patchedFields(patch).map(field => `${entityKey(patch.entity, patch.id)}.${field}`),\n ),\n ),\n )\n return layer.patches.flatMap(patch => {\n const key = entityKey(patch.entity, patch.id)\n const values = answered.get(key)\n const entry = shown[key]\n if (values === undefined || entry === undefined || entry.tombstone) return []\n return patchedFields(patch).flatMap(field =>\n stillPatched.has(`${key}.${field}`) ||\n !entry.present.has(field) ||\n !Object.hasOwn(values, field) ||\n sameData(entry.values[field], values[field])\n ? []\n : [\n predictionMismatch(\n PredictionPart.Value({\n requestId,\n mutation,\n entity: patch.entity,\n id: patch.id,\n field,\n shown: entry.values[field],\n answered: values[field],\n }),\n ),\n ],\n )\n })\n }\n\n /** The registered query a connection identity names, and its encoded input. */\n const queryOf = (\n identity: string,\n ): Option.Option<Pick<HeldConnection, 'descriptor' | 'encoded' | 'filtered'>> => {\n const separator = identity.indexOf(IDENTITY_SEPARATOR)\n const descriptor = definition.registry.queries.get(identity.slice(0, separator))\n if (descriptor === undefined) return Option.none()\n const encoded = JSON.parse(identity.slice(separator + 1)) as Record<string, unknown>\n const over = descriptor.body?.entity.name\n const filtered = (over === undefined ? undefined : definition.registry.filtered.get(over)) ?? []\n return Option.some({ descriptor, encoded, filtered })\n }\n\n /**\n * `pages` with each change to a row they hold placed, judged against\n * `store`: a row that moved goes where the body's order puts it, and one\n * that stopped matching leaves. A row a pending write creates joins where\n * the body puts it, since the write holds all it is. Another row a change\n * brings in is not added, since what the list selects of it may not be\n * loaded, and a change the client cannot place leaves the row where it is.\n */\n const placedHeld = (\n identity: string,\n pages: Connection,\n changes: ReadonlyArray<EntityChange>,\n store: EntityStore,\n // For pending placement, the viewer its operations were predicted for; none\n // when no operation named one, and a body over the context is the server's.\n context?: ExprContext,\n ): Connection => {\n const query = queryOf(identity)\n if (Option.isNone(query)) return pages\n // Built once: each change is of a row of its own, judged against the store\n // as every change left it, so what the list held before them all is enough.\n const holds = new Set(items(pages).map(edge => entityKey(edge.ref.entity, edge.ref.id)))\n let placed = pages\n for (const change of changes) {\n const created = EntityChange.match(change, {\n Changed: ({ created }) => created,\n Deleted: () => false,\n })\n if (!holds.has(entityKey(change.entity, change.id)) && !created) continue\n placed = Impact.$match(\n impactOn({ ...query.value, connection: placed, holds }, store, change, operators, context),\n {\n Kept: () => placed,\n Placed: ({ connection }) => connection,\n Invalidated: () => placed,\n },\n )\n }\n return placed\n }\n\n /**\n * What a list body's context reads while pending layers are placed: the\n * viewer the newest operation was predicted for. The viewer is the\n * reader's, so every operation since the last `forget` names the same one.\n */\n const layersContext = (layers: ReadonlyArray<EntityLayer>): ExprContext | undefined => {\n const viewer = [...layers].reverse().find(layer => Option.isSome(layer.viewer))?.viewer\n return viewer === undefined ? undefined : { viewer, now: Option.none() }\n }\n\n /**\n * A loaded list with the pending layers placed in its pages, so a row a\n * pending edit moves, or takes out of the list, shows where its answer\n * will be placed until the edit settles.\n */\n const pendingPlaced = (remote: RemoteModel, identity: string, pages: Connection): Connection => {\n const { layers } = remote.optimistic\n if (layers.length === 0) return pages\n return memoRead([pages, layers, remote.entities], `placed:${identity}`, () =>\n placedHeld(\n identity,\n pages,\n changesOf(\n { entities: resolvedPatches(remote.entities, remote.optimistic, operators) },\n remote.entities,\n ),\n visibleStoreOf(remote.entities, remote.optimistic, operators),\n layersContext(layers),\n ),\n )\n }\n\n /**\n * The edges a loaded list shows: its pages with pending edits placed, and\n * each row an insert overlay shows (a pending create, a confirmed or a live\n * insert) where the body's order puts it, or left out when it sorts past\n * what is loaded. An overlay says a row is in the list; in a list the\n * client can place, the order says where. A row it cannot place stays at\n * the end its overlay names.\n */\n const shownEdges = (\n remote: RemoteModel,\n identity: string,\n connection: Connection,\n ): ReadonlyArray<Edge> => {\n const pages = pendingPlaced(remote, identity, connection)\n const inserts = remote.optimistic.overlays.some(\n overlay => overlay.connection === identity && overlay.position !== 'remove',\n )\n const shown = inserts\n ? insertsPlaced(remote, identity, pages)\n : { pages, overlays: remote.optimistic.overlays }\n return visibleItems(\n shown.pages,\n identity,\n shown.overlays,\n goneIn(remote.entities, remote.optimistic),\n )\n }\n\n const insertsPlaced = (\n remote: RemoteModel,\n identity: string,\n pages: Connection,\n ): { readonly pages: Connection; readonly overlays: ReadonlyArray<ConnectionOverlay> } => {\n const { overlays } = remote.optimistic\n const store = visibleStoreOf(remote.entities, remote.optimistic, operators)\n return memoRead([pages, overlays, store], `inserted:${identity}`, () => {\n const query = queryOf(identity)\n const body = Option.isSome(query) ? query.value.descriptor.body : undefined\n if (Option.isNone(query) || body === undefined) return { pages, overlays }\n // A row a later remove hides is placed too: `visibleItems` hides it\n // wherever it is.\n const inserted = new Map<string, Edge>()\n for (const overlay of overlays) {\n if (overlay.connection !== identity || overlay.position === 'remove') continue\n for (const edge of overlay.edges) inserted.set(edge.key, edge)\n }\n const held = new Set(items(pages).map(edge => edge.key))\n let placed = pages\n const outside: Array<Edge> = []\n for (const edge of inserted.values()) {\n if (held.has(edge.key)) continue\n const key = entityKey(edge.ref.entity, edge.ref.id)\n RowPlace.$match(placeIn(store, placed, body, query.value.encoded, key, operators), {\n Before: place => void (placed = withEdge(placed, edge, place)),\n End: place => void (placed = withEdge(placed, edge, place)),\n Outside: () => void outside.push(edge),\n Unknown: () => undefined,\n })\n }\n return {\n pages: placed,\n overlays:\n outside.length === 0\n ? overlays\n : [\n ...overlays,\n { id: 'placed:outside', connection: identity, edges: outside, position: 'remove' },\n ],\n }\n })\n }\n\n /**\n * The loaded lists with what the server said of rows they hold placed: a\n * read or a live patch that changes a held row's ordering or filtered field\n * moves it, or takes it out, as a mutation's answer does. A list it cannot\n * place stands as it is, as a read is no write: its own refetch or live\n * stream says otherwise. Only a value the client held before counts, so a\n * row's first read judges nothing.\n */\n const placedNews = (\n remote: RemoteModel,\n news: ReadonlyArray<NormalizedPatch>,\n before: EntityStore,\n context: ExprContext,\n ): RemoteModel => {\n if (news.length === 0) return remote\n const held = news.map(patch => {\n const values = before[entityKey(patch.entity, patch.id)]?.values ?? {}\n return {\n ...patch,\n values: Object.fromEntries(\n Object.entries(patch.values).filter(([field]) => Object.hasOwn(values, field)),\n ),\n }\n })\n const changes = changesOf({ entities: held }, before)\n if (changes.length === 0) return remote\n const placed: Record<string, Connection> = {}\n for (const [identity, pages] of Object.entries(remote.connections)) {\n const after = placedHeld(identity, pages, changes, remote.entities, context)\n if (after !== pages) placed[identity] = after\n }\n return withPlacements(remote, placed, [])\n }\n\n /** The rows a read or a live patch says the server holds now. */\n const newsOf = (message: RemoteMessage | RemoteMessageInput): ReadonlyArray<NormalizedPatch> => {\n if (message._tag === 'ReadReceived') return message.result.entities\n if (message._tag !== 'LiveReceived') return []\n const event = message.event as LiveEvent\n if (event._tag !== 'EntityPatched') return []\n return [{ entity: event.ref.entity, id: event.ref.id, values: event.values }]\n }\n\n /**\n * The loaded connections as a write left them: each judged by its body\n * against the store as the write left it, a change it can place placed in\n * its pages, and one it cannot invalidated for its read entry to fetch.\n */\n const impactOf = (\n remote: RemoteModel,\n answer: Extract<RemoteMessage, { readonly _tag: 'MutationSucceeded' }>,\n // The store before the answer, to tell a value it changed from one it repeated.\n before: EntityStore,\n context: ExprContext,\n ): RemoteModel => {\n const changes = changesOf(answer, before)\n if (changes.length === 0) return remote\n // A row the answer itself put in or took out of a list is where the server\n // says; every other change to that list's rows is judged as anywhere.\n const named = new Map<string, Set<string>>()\n for (const change of answer.connections ?? []) {\n const keys = named.get(change.connection) ?? new Set<string>()\n keys.add(change.edge.key)\n named.set(change.connection, keys)\n }\n const visible = visibleStoreOf(remote.entities, remote.optimistic, operators)\n const placed: Record<string, Connection> = {}\n const invalidated: Array<string> = []\n for (const identity of Object.keys(remote.connections)) {\n const answered = named.get(identity)\n const judged =\n answered === undefined\n ? changes\n : changes.filter(change => !answered.has(entityKey(change.entity, change.id)))\n if (judged.length === 0) continue\n const query = queryOf(identity)\n if (Option.isNone(query)) continue\n const original = remote.connections[identity]!\n // Each change is judged against the pages the one before it left. What the\n // list holds is read once: a change is of a row of its own, judged against\n // the store as the whole answer left it.\n const holds = new Set(\n visibleItems(\n original,\n identity,\n remote.optimistic.overlays,\n goneIn(remote.entities, remote.optimistic),\n ).map(edge => entityKey(edge.ref.entity, edge.ref.id)),\n )\n let pages = original\n let invalid = false\n for (const change of judged) {\n const held: HeldConnection = { ...query.value, connection: pages, holds }\n const after = Impact.$match(impactOn(held, visible, change, operators, context), {\n Kept: () => Option.some(pages),\n Placed: ({ connection }) => Option.some(connection),\n Invalidated: () => Option.none<Connection>(),\n })\n if (Option.isNone(after)) {\n invalid = true\n break\n }\n pages = after.value\n }\n if (invalid) invalidated.push(identity)\n else if (pages !== original) placed[identity] = pages\n }\n return withPlacements(remote, placed, invalidated)\n }\n\n /**\n * The lists placed and invalidated. Under `verifyPredictions`, each placed\n * list is fetched too, and the order it was placed in kept to compare with\n * the server's page.\n */\n const withPlacements = (\n remote: RemoteModel,\n placed: Readonly<Record<string, Connection>>,\n invalidated: ReadonlyArray<string>,\n ): RemoteModel => {\n const identities = Object.keys(placed)\n if (identities.length === 0) return invalidateConnections(remote, invalidated)\n const withPlaced = { ...remote, connections: { ...remote.connections, ...placed } }\n if (options.verifyPredictions !== true) return invalidateConnections(withPlaced, invalidated)\n const firstPage = (connection: Connection | undefined) =>\n (connection?.segments[0]?.edges ?? []).map(edge => edge.key)\n const orders = Object.fromEntries(\n identities.map(identity => {\n const order = firstPage(placed[identity])\n const kept = new Set(order)\n return [\n identity,\n {\n order,\n dropped: firstPage(remote.connections[identity]).filter(key => !kept.has(key)),\n },\n ]\n }),\n )\n return invalidateConnections({ ...withPlaced, placed: { ...remote.placed, ...orders } }, [\n ...invalidated,\n ...identities,\n ])\n }\n const assertOwned = (entry: ActiveEntry<AppModel>) => assertOwnedBy(bound.contract, entry)\n /**\n * What the reader is shown of each entity in `model`, and what the write\n * itself shows (`predicted`), for its answer to carry (#245, #265).\n */\n const shownAt = (\n model: AppModel,\n predicted: ReadonlyArray<OptimisticOperation>,\n ): ReadonlyArray<RelationRequirement> =>\n shownOf(\n askedUnion(\n [...readers.values()].flatMap(resolvedAt =>\n resolvedAt(model).map(({ projection }) => projection),\n ),\n ),\n predicted,\n )\n /**\n * A durable write's request id, which is its operation id: this page's\n * session and the next in its sequence, unique across tabs and loads. Only\n * a retry names one, and only one the outbox holds.\n */\n const durableId = (remote: RemoteModel, mutation: string, given: string | undefined): string => {\n if (given !== undefined) {\n if (remote.outbox.queue.some(queued => operationOf(queued) === given)) return given\n throw new Error(\n `[foldkit-remote] Data.mutate(${mutation}, { durable: true, requestId: \"${given}\" }): a durable write is named by the outbox; pass no requestId`,\n )\n }\n return Option.match(remote.outbox.session, {\n onNone: () => {\n throw new Error(\n `[foldkit-remote] Data.mutate(${mutation}, { durable: true }) before the outbox's restore has run: start init from Data.outbox(…).restore(model), as the runtime's flags, so a durable write has an id no other tab or page load uses`,\n )\n },\n onSome: session => `${session}-${remote.mutations.sequence + 1}`,\n })\n }\n /** The descriptor a recorded write names; only a hand-built `MutationStarted` names another. */\n const registeredMutation = (name: string): MutationDescriptor<any, any, any> => {\n const descriptor = definition.registry.mutations.get(name)\n if (descriptor === undefined) {\n throw new Error(\n `Remote: a failed write names mutation \"${name}\", which domain \"${bound.contract.name}\" does not register`,\n )\n }\n return descriptor\n }\n /**\n * `prefetch` and `satisfy`, each Message they reduce also kept in `heard`,\n * so `preload` can hand them to the Model as it is by the time they land.\n */\n const prefetchInto = (\n model: AppModel,\n projection: Projection<AppModel, unknown>,\n options: ObserveOptions,\n heard: Array<RemoteMessage>,\n ) => {\n const hear = (current: AppModel, message: RemoteMessage): AppModel => {\n heard.push(message)\n return reduce(current, message)\n }\n return Effect.gen(function* () {\n const { policy = RemotePolicy.cacheFirst, now = wallClock } = options\n const client = yield* RemoteClient\n const planOptions = RemotePolicy.toPlan(policy, now())\n let current = model\n // The pages first, so their items join the one entity read below. A\n // page with a payload already writes its items' selected fields, so\n // the read below is only for what the server left out.\n for (const query of planAsked(store.get(current), askedOf(projection), planOptions, operators)\n .queries) {\n const page = yield* queryRequestOf(query).pipe(\n Effect.flatMap(request => client.query(request)),\n )\n current = hear(\n current,\n pageMessage(query.identity, page, true, query.window, query.select, now()),\n )\n }\n const requirements = planAsked(\n store.get(current),\n askedOf(projection),\n planOptions,\n operators,\n ).requirements\n if (requirements.length === 0) return current\n const at = now()\n const result = yield* client.read({\n version: REMOTE_PROTOCOL_VERSION,\n requests: requirements,\n })\n return hear(current, { _tag: 'ReadReceived', requests: requirements, result, now: at })\n })\n }\n const satisfyInto = (\n model: AppModel,\n active: Readonly<Record<string, ActiveEntry<AppModel>>>,\n options: SatisfyOptions,\n heard: Array<RemoteMessage>,\n ) =>\n Effect.gen(function* () {\n const { passes = 8, now = wallClock } = options\n const entries = Object.values(active)\n entries.forEach(assertOwned)\n const planOptions = RemotePolicy.toPlan(RemotePolicy.cacheFirst, now())\n const plans = (\n current: AppModel,\n projections: ReadonlyArray<Projection<AppModel, unknown>>,\n ) => {\n const planned = planAsked(\n store.get(current),\n askedUnion(projections),\n planOptions,\n operators,\n )\n return planned.queries.length > 0 || planned.requirements.length > 0\n }\n let current = model\n for (let pass = 0; pass < passes; pass++) {\n if (\n !entries.some(entry =>\n plans(\n current,\n resolvedOf(entry, current).map(({ projection }) => projection),\n ),\n )\n )\n return current\n for (const entry of entries) {\n // Asked again over the Model the Surface before it left. A family\n // resolves its parent first: a pass fetches the parent, and the\n // instances the parent reveals are read in a later pass.\n for (const { projection } of resolvedOf(entry, current))\n current = yield* prefetchInto(current, projection, { now }, heard)\n }\n }\n const reading = entries.flatMap(entry =>\n resolvedOf(entry, current).filter(({ projection }) => plans(current, [projection])),\n )\n if (reading.length === 0) return current\n return yield* new RemoteUnsatisfied({\n surfaces: reading.map(({ name }) => name),\n passes,\n })\n })\n const domain: RemoteDomain<AppModel, Store, Entities, Queries, Mutations> = {\n ...definition,\n ...bound,\n get: (selection, id) => Remote.select(bound, selection)(id),\n live: (selection, id) => {\n const projection = Remote.select(bound, selection)(id)\n return {\n ...projection,\n metadata: RemoteRequirements.of(\n ...requirementsOf(projection).map(requirement => ({ ...requirement, live: true })),\n ),\n }\n },\n active: (name, projectionOf) => {\n const { owner } = bound.contract\n if (owner === undefined)\n throw new Error(\n `Remote: \"${name}\" reads domain \"${bound.contract.name}\", whose Model field is a raw optic that names no application; make the domain from an application's field (App.model.remote) to give it reads`,\n )\n return { name, owner, messages: [], projectionOf }\n },\n subscriptions: (active, options = {}) => {\n // Dependencies differ per entry, as in Foldkit's own `Subscriptions` record.\n const entries: Record<string, RemoteEntry<AppModel, any>> = {}\n // Checked before any reader joins the domain, so a refused call adds none.\n for (const entry of Object.values(active)) assertOwned(entry)\n for (const [key, entry] of Object.entries(active)) {\n const resolvedAt = readers.get(entry) ?? memoizedResolved(entry)\n readers.set(entry, resolvedAt)\n const asked = (model: AppModel) =>\n askedUnion(resolvedAt(model).map(({ projection }) => projection))\n entries[`${key}.read`] = observeEntry(bound, asked, identityMessage, options)\n entries[`${key}.live`] = liveEntry(\n bound,\n model => liveAskOf(asked(model)),\n identityMessage,\n options,\n )\n }\n for (const identity of options.connections ?? [])\n keptConnections.add(connectionIdentity(identity))\n entries.retain = {\n dependenciesSchema: retentionRootsSchema,\n modelToDependencies: model =>\n rootsOf(\n [...readers.values()].flatMap(resolvedAt =>\n resolvedAt(model).map(({ projection }) => projection),\n ),\n { connections: [...keptConnections] },\n ),\n dependenciesToStream: (current: RetentionRoots) =>\n Stream.fromEffect(\n Effect.succeed<RemoteMessage>({ _tag: 'RetentionChanged', roots: current }).pipe(\n Effect.delay(options.grace ?? 0),\n ),\n ),\n }\n markAll(entries)\n // The loop above wrote exactly the keys the mapped type names.\n return entries as SubscriptionEntries<AppModel, typeof active>\n },\n plan: (model, projection, options) => Remote.plan(bound, model, projection, options),\n meta: (model, projection) => Remote.meta(bound, model, projection),\n storeOf: model => storeOf(bound, model),\n confirmed: projection => confirmed(bound, projection),\n prefetch: (model, projection, options = {}) => prefetchInto(model, projection, options, []),\n satisfy: (model, active, options = {}) => satisfyInto(model, active, options, []),\n preload: (model, active, options = {}) => {\n // A Surface of another application is a mistake in `update`, refused there.\n Object.values(active).forEach(assertOwned)\n return {\n name: 'Remote.preload',\n args: { active: Object.keys(active).join(', ') },\n effect: Effect.suspend(() => {\n const heard: Array<RemoteMessage> = []\n // Speculative: however the read ends, defects included, what it\n // heard is all it hands on, and the destination reads the rest.\n return satisfyInto(model, active, options, heard).pipe(\n Effect.exit,\n Effect.map((): RemoteMessage => ({ _tag: 'Preloaded', messages: heard })),\n )\n }),\n }\n },\n query: <Q extends QueryDescriptor<any, any, any>, Value, Entity extends string>(\n query: Q,\n input: QueryInput<Q>,\n options: QueryOptions<Value, Entity, QueryEntity<Q>>,\n ): QueryProjection<AppModel, Value, Q['name'], QueryInput<Q>> => {\n assertRegistered(bound, 'Query', definition.registry.queries, query.name)\n const { select: given, live, ...window } = options\n const select = selectionOf<Value, Entity>(given)\n for (const [side, size] of [\n ['first', window.first],\n ['last', window.last],\n ] as const) {\n if (size !== undefined && !(Number.isInteger(size) && size >= 0)) {\n throw new Error(\n `Remote: query \"${query.name}\" asks for ${side}: ${String(size)}; a page size is a non-negative integer`,\n )\n }\n }\n if (live === true && window.first === undefined) {\n throw new Error(\n `Remote: query \"${query.name}\" is read live without first; a list watched live is read again every tick, so it needs a size`,\n )\n }\n const listed = (query.Result as Partial<ConnectionSpec>).entity\n if (listed === undefined) {\n throw new Error(\n `Remote: query \"${query.name}\" is not a connection over an entity, so it has no page to select`,\n )\n }\n if (select.entity !== listed) {\n throw new Error(\n `Remote: the selection is of \"${select.entity}\", but query \"${query.name}\" lists \"${listed}\"`,\n )\n }\n const contract = placeableReadContract(\n readContract(query.ref(input), select, window),\n query.body,\n operators,\n )\n const { ref, relation } = contract\n const requirement = live === true ? { ...contract.requirement, live } : contract.requirement\n const relationKey = stableStringify(relation)\n // A read shows at most its window, whatever else loaded the connection:\n // a picker's `first: 50` and a Block's `first: 3` of one query share it.\n const sizeOf = (remote: RemoteModel) => windowSize(remote, ref)\n const shown = (remote: RemoteModel, connection: Connection) =>\n cutToWindow(shownEdges(remote, ref.identity, connection), ref.window, sizeOf(remote))\n // The first failed field among the rows a list shows, if any. Decided\n // outside the memo, which is keyed on what the rows are read from: a\n // failure can arrive without any of it changing.\n const failedItem = (\n remote: RemoteModel,\n connection: Connection,\n ): { readonly _tag: 'Failed'; readonly error: RemoteError } | undefined => {\n if (Object.keys(remote.failures.fields).length === 0) return undefined\n for (const edge of shown(remote, connection).edges) {\n if (edge.ref.entity !== relation.entity) continue\n const error = failureOf(remote, edge.ref.entity, edge.ref.id, relation)\n if (error !== undefined) return { _tag: 'Failed', error }\n }\n return undefined\n }\n // A page carries refs; its rows' fields are read after it lands. While\n // that read is in flight the list is loading, not `Initial`.\n const loadingItem = (\n remote: RemoteModel,\n connection: Connection,\n ): { readonly _tag: 'Loading' } | undefined => {\n if (remote.loading.size === 0) return undefined\n for (const edge of shown(remote, connection).edges) {\n if (edge.ref.entity !== relation.entity) continue\n if (isLoadingThrough(remote, edge.ref.entity, edge.ref.id, relation)) {\n return { _tag: 'Loading' }\n }\n }\n return undefined\n }\n // The page as the rows held make it, before any failure is laid over it.\n // A row missing a field is left out until it arrives, and the page reads\n // `Refreshing` meanwhile: a list showing rows keeps showing them while a\n // joined or re-read row is fetched. `undefined` when no row can be shown\n // and no row the window would show was deleted: a list that lost its rows\n // to a delete is a known list without them, not one waiting for its first\n // rows (#263).\n const readPage = (\n remote: RemoteModel,\n connection: Connection,\n ): RemoteData<Page<Value>> | undefined => {\n const visible = visibleStoreOf(remote.entities, remote.optimistic, operators)\n return memoRead<RemoteData<Page<Value>> | undefined>(\n [visible, connection, remote.optimistic.overlays],\n `${ref.identity}\\u0000${relationKey}\\u0000${String(sizeOf(remote))}`,\n () => {\n const rows: Value[] = []\n let refreshing = connection.stale\n let missing = false\n const { edges, cutBefore, cutAfter } = shown(remote, connection)\n for (const edge of edges) {\n const key = entityKey(edge.ref.entity, edge.ref.id)\n const assembled = assemble(visible, key, relation)\n if (assembled === undefined) {\n const unavailable = unavailableFailure(visible, key, relation)\n if (unavailable !== undefined) return unavailable\n missing = true\n continue\n }\n const decoded = decodeRow(select.schema, visible[key]!.values, assembled.values)\n if (Result.isFailure(decoded)) {\n return {\n _tag: 'Failed',\n error: { _tag: 'DecodeError', message: decoded.failure.message },\n }\n }\n refreshing ||= assembled.refreshing\n rows.push(decoded.success)\n }\n if (\n missing &&\n rows.length === 0 &&\n !deletedInWindow(\n items(connection),\n new Set(shownEdges(remote, ref.identity, connection).map(edge => edge.key)),\n ref.window,\n sizeOf(remote),\n goneIn(remote.entities, remote.optimistic),\n )\n ) {\n return undefined\n }\n const page = {\n items: rows,\n hasNext: cutAfter || hasNext(connection),\n hasPrevious: cutBefore || hasPrevious(connection),\n }\n return refreshing || missing\n ? { _tag: 'Refreshing', value: page }\n : { _tag: 'Ready', value: page }\n },\n )\n }\n return {\n Model: remoteDataSchema(pageSchema(select.schema)) as Schema.Codec<\n RemoteData<Page<Value>>,\n unknown\n >,\n dependencies: [],\n metadata: RemoteConnections.of(requirement),\n ref,\n selection: select as Selection<Value, string>,\n read: (root: AppModel): RemoteData<Page<Value>> => {\n const remote = store.get(root)\n const connection = remote.connections[ref.identity]\n const failure = remote.failures.connections[ref.identity]\n // Invalidating a connection the Model never loaded records it stale with no\n // segments: still nothing to show. (A loaded empty page is not stale.)\n if (connection === undefined || (connection.stale && connection.segments.length === 0)) {\n if (isQueryLoading(remote, ref.identity)) return { _tag: 'Loading' }\n return failure === undefined ? { _tag: 'Initial' } : { _tag: 'Failed', error: failure }\n }\n // A query that answered is not the whole of a list: its rows' fields\n // are read separately, and one of those failing is the list's failure.\n const read = readPage(remote, connection) ??\n failedItem(remote, connection) ??\n loadingItem(remote, connection) ?? { _tag: 'Initial' }\n if (failure === undefined) {\n if (read._tag !== 'Ready' && read._tag !== 'Refreshing') return read\n const item = failedItem(remote, connection)\n return item === undefined\n ? read\n : { _tag: 'Failed', error: item.error, previous: read.value }\n }\n // The rows held before the failure are still the best there is, so they\n // go with it as `previous`, which `RemoteData.render` shows as stale.\n switch (read._tag) {\n case 'Ready':\n case 'Refreshing':\n return { _tag: 'Failed', error: failure, previous: read.value }\n case 'Failed':\n return read\n case 'Initial':\n case 'Loading':\n case 'NotFound':\n return { _tag: 'Failed', error: failure }\n }\n },\n }\n },\n more: (model, projection) => {\n const remote = store.get(model)\n const { ref } = projection\n const size = windowSize(remote, ref)\n const page = ref.window.first ?? ref.window.last\n if (size === undefined || page === undefined || page === 0) return Option.none()\n const read = projection.read(model)\n const beyond =\n (read._tag === 'Ready' || read._tag === 'Refreshing') &&\n (ref.window.first === undefined ? read.value.hasPrevious : read.value.hasNext)\n return beyond\n ? Option.some(\n bound.store.set(\n model,\n updateRemote(remote, {\n _tag: 'WindowGrown',\n window: windowGrowthKey(ref.identity, stableStringify(ref.window)),\n size: size + page,\n }) as Store,\n ),\n )\n : Option.none()\n },\n explain: (model, projection, options) => {\n const { ref } = projection\n // Which active Surfaces read this connection, asked of the Model rather\n // than of the projection: a Surface's projection is rebuilt per Model, so\n // the only honest comparison is by connection identity. A family names\n // each reading instance (`Grid[all]`), not just the Surface.\n const reading = Object.values(options?.surfaces ?? {}).flatMap(source => {\n const matched = resolvedOf(source, model).filter(({ projection: shown }) =>\n connectionsOf(shown).some(connection => connection.identity === ref.identity),\n )\n // An inactive Surface reads nothing, which is not the same as reading\n // something else.\n if (matched.length === 0) return []\n return [{ source, names: matched.map(({ name }) => name) }]\n })\n // The body lives on the descriptor, and a projection keeps only its\n // `QueryRef` — so the explanation looks the definition back up by name.\n // Which it can, because `Data` is bound to the domain that registered it.\n const body = definition.registry.queries.get(ref.query)?.body\n const [connection] = RemoteConnections.get(projection.metadata)\n return {\n domain: bound.contract.name,\n query: ref.query,\n input: Schema.encodeSync(ref.Input)(ref.input),\n identity: ref.identity,\n window: ref.window,\n select: connection!.select,\n ...(body === undefined\n ? {}\n : {\n body: Relational.show(body),\n dependencies: explainedDependencies(Relational.dependencies(body)),\n }),\n state: projection.read(model)._tag,\n ...(options?.surfaces === undefined\n ? {}\n : {\n surfaces: reading.flatMap(read => read.names),\n activation: reading.flatMap(read => {\n const activation = 'activation' in read.source ? read.source.activation : undefined\n return activation === undefined\n ? []\n : [{ surface: read.source.name, ...activation }]\n }),\n }),\n }\n },\n why: (model, projection, options) => {\n const data = projection.read(model)\n const asked = askedOf(projection)\n const entries = options?.surfaces === undefined ? [] : Object.values(options.surfaces)\n // Each active entry whose reads ask for all of this one: one that reads\n // part of it cannot be why it is fetched.\n const reading = entries.flatMap(entry => {\n const names = resolvedOf(entry, model)\n .filter(({ projection: shown }) => covers(askedOf(shown), asked))\n .map(({ name }) => name)\n return names.length === 0 ? [] : [{ entry, names }]\n })\n const surfaces =\n options?.surfaces === undefined\n ? Option.none()\n : Option.some(reading.flatMap(read => read.names))\n const initial: ReadonlyArray<Why> =\n data._tag !== 'Initial'\n ? []\n : [\n Option.match(surfaces, {\n onNone: () => Why.NoActiveRecord(),\n onSome: names =>\n names.length === 0 ? Why.NotObserved() : Why.NotFetching({ surfaces: names }),\n }),\n ]\n const remote = store.get(model)\n const live =\n asked.requirements.some(requirement => requirement.live === true) ||\n asked.connections.some(connection => connection.live === true)\n const streams: ReadonlyArray<Why> = live\n ? reading.flatMap(({ entry }): ReadonlyArray<Why> => {\n return Match.valueTags(domain.liveStatus(model, entry), {\n Idle: () => [],\n Live: () => [],\n Reconnecting: ({ attempt, error }) => [\n Why.LiveReconnecting({ surface: entry.name, attempt, error }),\n ],\n Refused: ({ error }) => [Why.LiveRefused({ surface: entry.name, error })],\n })\n })\n : []\n const reader: WhyReader = {\n remote,\n visible: visibleStoreOf(remote.entities, remote.optimistic, operators),\n listOf: identity => ({\n query: Option.match(queryOf(identity), {\n onNone: () => identity,\n onSome: query => query.descriptor.name,\n }),\n identity,\n }),\n bodyOf: identity =>\n Option.flatMap(queryOf(identity), query =>\n Option.map(Option.fromUndefinedOr(query.descriptor.body), body => ({\n body,\n encoded: query.encoded,\n })),\n ),\n edgesOf: ({ identity, window }) => {\n const connection = remote.connections[identity] ?? emptyConnection\n const placed = shownEdges(remote, identity, connection)\n return {\n shown: cutToWindow(placed, window, windowSize(remote, { identity, window })).edges,\n placed,\n pages: items(connection),\n }\n },\n operators,\n context: layersContext(remote.optimistic.layers),\n }\n return readWhy(\n data._tag,\n [...initial, ...failedReasons(data), ...reasonsOf(reader, asked), ...streams],\n surfaces,\n )\n },\n timeline: (start, history, reads, options) => {\n let before = start\n return history.flatMap((entry, index) => {\n const from = before\n before = entry.model\n return Object.entries(reads).flatMap(([read, projection]): ReadonlyArray<ReadStep<any>> => {\n const was = projection.read(from)\n const is = projection.read(entry.model)\n if (was._tag === is._tag) return []\n return [\n {\n read,\n index,\n message: entry.message,\n from: was._tag,\n to: is._tag,\n why: domain.why(entry.model, projection, options),\n regression: regressed(was, is),\n },\n ]\n })\n })\n },\n filtered: (model, over, by, input) => {\n assertRegistered(bound, 'Query', definition.registry.queries, by.name)\n // A filter over a different Entity can never match anything, and would\n // otherwise answer \"I checked the whole list and found nothing\" — a\n // confident wrong answer rather than a refusal.\n const filters = by.body?.entity.name\n if (filters !== undefined && filters !== over.selection.entity) {\n throw new Error(\n `Remote: query \"${by.name}\" is over \"${filters}\", but the list is of \"${over.selection.entity}\", so it cannot filter it`,\n )\n }\n const remote = store.get(model)\n const connection = remote.connections[over.ref.identity]\n const visible = visibleStoreOf(remote.entities, remote.optimistic, operators)\n const edges =\n connection === undefined ? [] : shownEdges(remote, over.ref.identity, connection)\n const among = edges.map(edge => entityKey(edge.ref.entity, edge.ref.id))\n let judged: Judged\n try {\n judged = matching(visible, by, input, { among, operators, context: contextOf(model) })\n } catch (error) {\n // An input the reference interpreter refuses (a search holding NUL) is\n // one the server refuses too: nothing here can be said about the list.\n // Thrown on, it would end the `update` that asked.\n if (error instanceof QueryEvaluateError) return { items: [], complete: false }\n throw error\n }\n const relation = relationOf(over.selection)\n\n const items: unknown[] = []\n let assembledAll = true\n for (const key of judged.matched) {\n const assembled = assemble(visible, key, relation)\n // A matching row whose selected fields are not all here cannot be shown.\n // It is not dropped from the truth, only from the list: `complete` says\n // the answer is about less than the whole.\n if (assembled === undefined) {\n assembledAll = false\n continue\n }\n const decoded = decodeRow(over.selection.schema, visible[key]!.values, assembled.values)\n if (Result.isFailure(decoded)) {\n assembledAll = false\n continue\n }\n items.push(decoded.success)\n }\n\n return {\n items: items as never,\n // Whole only if every edge was judged, every match could be shown, and\n // the list itself is all there. `hasNext`/`hasPrevious` read the outer\n // boundaries alone, so `isGapped` is the third question: a connection\n // paged from both ends is `Terminal` at both and still missing its\n // middle.\n complete:\n judged.skipped.length === 0 &&\n assembledAll &&\n connection !== undefined &&\n !isGapped(connection) &&\n !hasNext(connection) &&\n !hasPrevious(connection),\n }\n },\n refresh: (model, target, options) => Remote.refresh(bound, model, target, options),\n forget: model => Remote.forget(bound, model),\n overlay: (model, id, optimistic) => reduce(model, { _tag: 'OverlayShown', id, optimistic }),\n lift: (model, id) => reduce(model, { _tag: 'OverlayLifted', id }),\n overlays: model => overlaysOf(store.get(model)),\n visibleItems: (remote, connection) => {\n const identity = connectionIdentity(connection)\n return shownEdges(remote, identity, remote.connections[identity] ?? emptyConnection)\n },\n mutate: (model, mutation, input, options = {}) => {\n assertRegistered(bound, 'Mutation', definition.registry.mutations, mutation.name)\n const remote = store.get(model)\n const durable = options.durable === true\n const requestId = durable\n ? durableId(remote, mutation.name, options.requestId)\n : (options.requestId ?? `${bound.contract.name}-${remote.mutations.sequence + 1}`)\n const tempId = `${requestId}.tmp`\n // A retry of a failed request sends the operation id it was first sent with.\n const known = Option.fromUndefinedOr(remote.mutations.operations.get(requestId))\n // A declared write shows what it writes until the server answers; one given wins.\n const viewer = viewerOf(model)\n const visible = visibleStoreOf(remote.entities, remote.optimistic, bound.operators)\n const predicted =\n mutation.write === undefined\n ? undefined\n : predictionOfWrite(mutation.write, input, options.keys, {\n derived: definition.registry.derived,\n store: visible,\n viewer,\n now: Option.fromUndefinedOr(options.now),\n })\n // A write the client can tell the server refuses is refused here, as the\n // server would refuse it, and nothing is sent or shown: one its held `may`\n // forbids, then, as the server decides in that order, one whose row\n // breaks an invariant.\n const write = mutation.write\n const refused =\n write === undefined || options.optimistic !== undefined\n ? Option.none()\n : Option.orElse(\n Option.map(\n forbiddenByWrite(write, input, options.keys, visible),\n ({ reason }): RemoteError =>\n remoteError(\n new RemoteForbidden({\n message: Option.getOrElse(reason, () => 'Forbidden'),\n ...Option.match(reason, {\n onNone: () => ({}),\n onSome: said => ({ reason: said }),\n }),\n }),\n ),\n ),\n () =>\n Option.map(\n brokenByWrite(\n write,\n input,\n options.keys,\n { viewer, now: Option.fromUndefinedOr(options.now) },\n visible,\n bound.operators,\n ),\n (held): RemoteError =>\n remoteError({\n _tag: 'RemoteMutationError',\n message: held.message,\n refusal: Schema.encodeUnknownSync(mutation.Refusal)({\n _tag: 'Invalid',\n entity: Option.some(held.entity),\n rule: Option.some(held.id),\n message: held.message,\n path: held.path,\n }),\n }),\n ),\n )\n const optimistic = Option.isSome(refused)\n ? undefined\n : typeof options.optimistic === 'function'\n ? options.optimistic({ requestId, tempId })\n : (options.optimistic ?? predicted)\n // A write refused where it is made is settled at once, durable or not.\n const queued = durable && Option.isNone(refused)\n const started = updateRemote(remote, {\n _tag: 'MutationStarted',\n requestId,\n ...(optimistic === undefined ? {} : { optimistic }),\n ...(Option.isSome(viewer) ? { viewer: viewer.value } : {}),\n write: {\n mutation: mutation.name,\n input,\n ...(options.keys === undefined ? {} : { keys: options.keys }),\n ...(options.now === undefined ? {} : { now: options.now }),\n ...(queued\n ? {\n // Encoded here, so an input its Mutation cannot encode throws at the call.\n durable: {\n input: Schema.encodeUnknownSync(mutation.Input)(input),\n shown: shownAt(model, optimistic ?? []),\n },\n }\n : {}),\n },\n })\n const startedModel = store.set(model, started as Store)\n return {\n model: startedModel,\n requestId,\n tempId,\n command: {\n name: `Remote.mutate(${mutation.name})`,\n args: { requestId },\n // Minted where the Command runs, so `update` stays pure; a retry finds it in the Model.\n effect: Effect.flatMap(\n Effect.sync(() => Option.getOrElse(known, mintOperation)),\n (operation): Effect.Effect<RemoteMessage, never, RemoteClient> =>\n queued\n ? // The outbox sends it, once its store holds it.\n Effect.succeed({ _tag: 'MutationQueued', requestId })\n : Option.isSome(refused)\n ? Effect.succeed({\n _tag: 'MutationFailed',\n requestId,\n error: refused.value,\n operation,\n })\n : mutateRemote(mutation, input, requestId, {\n keys: options.keys,\n operation,\n shown: shownAt(startedModel, optimistic ?? []),\n now: options.now,\n }).pipe(\n Effect.matchEffect({\n onFailure: error =>\n Effect.succeed<RemoteMessage>({\n _tag: 'MutationFailed',\n requestId,\n error: remoteError(error),\n operation,\n }),\n // Dated when it lands, by the clock a test pins.\n onSuccess: outcome =>\n Effect.map(Clock.currentTimeMillis, (at): RemoteMessage => ({\n _tag: 'MutationSucceeded',\n requestId,\n entities: outcome.entities,\n connections: outcome.connections,\n deleted: outcome.deleted,\n ...(outcome.read === undefined ? {} : { read: outcome.read }),\n now: at,\n })),\n }),\n ),\n ),\n },\n }\n },\n mutation: (model, requestId) => mutationStatus(store.get(model).mutations, requestId),\n refusal: (model, requestId, mutation) => {\n const status = mutationStatus(store.get(model).mutations, requestId)\n return status._tag === 'Failed' ? refusalOf(status.error, mutation) : Option.none()\n },\n failedWrites: (model: AppModel, mutation?: MutationDescriptor<any, any, any, any>) => {\n if (mutation !== undefined)\n assertRegistered(bound, 'Mutation', definition.registry.mutations, mutation.name)\n const { mutations } = store.get(model)\n // A retry in flight is pending again, and not listed until it fails again.\n const listed = [...mutations.failed].flatMap(requestId => {\n const write = mutations.writes.get(requestId)\n const error = mutations.errors.get(requestId)\n if (write === undefined || error === undefined || mutations.pending.has(requestId))\n return []\n if (mutation !== undefined && write.mutation !== mutation.name) return []\n const descriptor = registeredMutation(write.mutation)\n return [\n {\n requestId,\n mutation: descriptor,\n input: write.input,\n error,\n refusal: refusalOf(error, descriptor),\n },\n ]\n })\n // `Data.mutate` recorded each input as its mutation's Input.\n return listed as never\n },\n retry: (model, requestId) => {\n const { mutations, outbox } = store.get(model)\n const write = mutations.writes.get(requestId)\n if (write === undefined || mutationStatus(mutations, requestId)._tag !== 'Failed')\n return Option.none()\n return Option.some(\n domain.mutate(model, registeredMutation(write.mutation), write.input, {\n requestId,\n optimistic: write.optimistic,\n keys: write.keys,\n // The same time, so the server stores what the retry shows again.\n now: Option.getOrUndefined(write.now),\n durable: outbox.queue.some(queued => operationOf(queued) === requestId),\n }),\n )\n },\n dismiss: (model, requestId) => {\n const remote = store.get(model)\n const dismissed = dismissQueued(remote, requestId)\n if (dismissed !== remote) return store.set(model, dismissed as Store)\n if (mutationStatus(remote.mutations, requestId)._tag !== 'Failed') return model\n return store.set(model, {\n ...remote,\n mutations: forgetFailure(remote.mutations, requestId),\n } as Store)\n },\n liveStatus: (model, active) => {\n assertOwned(active)\n const resolvedAt = readers.get(active) ?? memoizedResolved(active)\n const live = liveAskOf(askedUnion(resolvedAt(model).map(({ projection }) => projection)))\n if (live.requirements.length === 0 && live.queries.length === 0) return { _tag: 'Idle' }\n const remote = store.get(model)\n const stream = liveStreamKey(live)\n const health = remote.streams[stream]\n if (health === undefined) return { _tag: 'Live' }\n return Option.match(health.refused, {\n onSome: error => ({ _tag: 'Refused', error }),\n onNone: () =>\n remote.gaps.has(stream)\n ? { _tag: 'Reconnecting', attempt: health.failures, error: health.error }\n : { _tag: 'Live' },\n })\n },\n outboxStatus: model => outboxStatus(store.get(model).outbox),\n reduce,\n inspect: model => inspectRemote(store.get(model)),\n persistence: options => {\n const connections = (options.connections ?? []).map(connectionIdentity)\n const snapshotOf =\n options.snapshot ??\n ((remote: RemoteModel) => RemotePersistence.snapshotOf(remote, { connections }))\n const debounce = options.debounce ?? '250 millis'\n // The snapshot text is derived on every Model change; it changes only with\n // the store, the connections and the scope, so it is kept by them.\n let last: {\n readonly entities: EntityStore\n readonly connections: RemoteModel['connections']\n readonly scope: string\n readonly text: Option.Option<string>\n } = { entities: emptyStore, connections: {}, scope: '', text: Option.none() }\n const textOf = (remote: RemoteModel, scope: string): Option.Option<string> => {\n if (\n last.entities !== remote.entities ||\n last.connections !== remote.connections ||\n last.scope !== scope\n ) {\n last = {\n entities: remote.entities,\n connections: remote.connections,\n scope,\n text: Option.fromUndefinedOr(\n RemotePersistence.dehydrate(snapshotOf(remote), {\n scope,\n maxBytes: options.maxBytes,\n }),\n ),\n }\n }\n return last.text\n }\n // A store that cannot be read restores nothing, so nothing is saved\n // under this key: an unread snapshot is never written over.\n const hydratedFrom = (\n key: string,\n scope: string,\n ): Effect.Effect<Option.Option<RemoteMessage>, never, KeyValueStore.KeyValueStore> =>\n RemotePersistence.restore({ key, scope, maxBytes: options.maxBytes }).pipe(\n Effect.map((snapshot): RemoteMessage => ({\n _tag: 'Hydrated',\n entities: snapshot.entities,\n connections: snapshot.connections,\n merge: 'preserve-existing',\n from: key,\n })),\n Effect.option,\n )\n // Restores the key the Model is not yet restored from: at start, unless\n // `init` began from `restore`, and whenever the key changes.\n const restoreEntry: EntryWithoutKeepAlive<\n AppModel,\n RemoteMessage,\n { readonly key: string; readonly scope: string; readonly restored: boolean },\n KeyValueStore.KeyValueStore\n > = {\n dependenciesSchema: Schema.Struct({\n key: Schema.String,\n scope: Schema.String,\n restored: Schema.Boolean,\n }),\n modelToDependencies: model => {\n const key = options.key(model)\n return {\n key,\n scope: options.scope(model),\n restored: Option.contains(store.get(model).restoredFrom, key),\n }\n },\n dependenciesToStream: ({ key, scope, restored }) =>\n restored\n ? Stream.empty\n : Stream.fromEffect(hydratedFrom(key, scope)).pipe(\n Stream.flatMap(Option.match({ onNone: () => Stream.empty, onSome: Stream.make })),\n ),\n }\n const save: EntryWithoutKeepAlive<\n AppModel,\n RemoteMessage,\n { readonly key: string; readonly restored: boolean; readonly text: Option.Option<string> },\n KeyValueStore.KeyValueStore\n > = {\n dependenciesSchema: Schema.Struct({\n key: Schema.String,\n restored: Schema.Boolean,\n text: Schema.OptionFromNullOr(Schema.String),\n }),\n modelToDependencies: model => {\n const remote = store.get(model)\n const key = options.key(model)\n const restored = Option.contains(remote.restoredFrom, key)\n return {\n key,\n restored,\n text: restored ? textOf(remote, options.scope(model)) : Option.none(),\n }\n },\n // A changed cache restarts this stream, so the wait is the debounce.\n dependenciesToStream: ({ key, restored, text }) =>\n restored\n ? Stream.fromEffect(\n Effect.gen(function* () {\n yield* Effect.sleep(debounce)\n const kv = yield* KeyValueStore.KeyValueStore\n // Too large to keep: no stale smaller snapshot may outlive it.\n yield* Option.match(text, {\n onNone: () => kv.remove(key),\n onSome: written => kv.set(key, written),\n })\n }).pipe(\n // A full store keeps the snapshot it had; the next change tries again.\n Effect.ignore,\n ),\n ).pipe(Stream.drain)\n : Stream.empty,\n }\n return {\n key: `persistence:${bound.contract.name}`,\n handles: [],\n subscriptions: Subscription.make<AppModel, RemoteMessage, KeyValueStore.KeyValueStore>()(\n () => ({ 'persistence.restore': restoreEntry, 'persistence.save': save }),\n ),\n restore: model =>\n Effect.map(\n hydratedFrom(options.key(model), options.scope(model)),\n Option.match({ onNone: () => model, onSome: message => reduce(model, message) }),\n ),\n }\n },\n outbox: options => {\n /** How this version reads a stored input of `mutation`; none for one it does not register. */\n const inputOf = (mutation: string) =>\n Option.map(\n Option.fromUndefinedOr(definition.registry.mutations.get(mutation)),\n descriptor => (input: unknown) =>\n Option.map(Schema.decodeUnknownOption(descriptor.Input)(input), decoded => ({\n decoded,\n })),\n )\n const readOf = (\n key: string,\n scope: string,\n stored: StoredOutbox,\n extra: { readonly session?: string; readonly unsaved?: string } = {},\n ): RemoteMessage => ({\n _tag: 'OutboxRead',\n key,\n scope,\n entries: readEntries(stored, inputOf),\n done: stored.done,\n ...extra,\n })\n /** Tells the other tabs on `key` the store changed, with the answer that changed it. */\n const announce = (key: string, outcome: Option.Option<RemoteMessage>) =>\n Effect.sync(() =>\n Option.map(channelFor(key), channel => {\n channel.postMessage({ outcome: Option.getOrUndefined(outcome) })\n channel.close()\n }),\n )\n /** The store with `change` merged in, under its lock, so two tabs never write it at once. */\n const writeStored = (key: string, scope: string, change: StoredOutbox) =>\n withLock(\n storeLock(key),\n Effect.gen(function* () {\n // Another scope's waiting writes are never written over: a key that\n // is not one per principal fails the save, and says why.\n if (yield* othersWaiting(key, scope)) {\n return yield* Effect.fail(\n new Error(\n `the store under ${key} holds another scope's waiting writes; give each principal a key of its own`,\n ),\n )\n }\n const merged = mergeStored(yield* readStored(key, scope), change)\n const kv = yield* KeyValueStore.KeyValueStore\n yield* kv.set(key, storedText(merged, scope))\n return merged\n }),\n )\n /** What the store holds, as a page reads it; this page's own queue, and why, where it cannot be read. */\n const restored = (key: string, scope: string, session: Option.Option<string>) =>\n readStored(key, scope).pipe(\n Effect.map(stored =>\n readOf(\n key,\n scope,\n stored,\n Option.match(session, {\n onNone: () => ({}),\n onSome: minted => ({ session: minted }),\n }),\n ),\n ),\n Effect.catch(error =>\n Effect.succeed(\n readOf(\n key,\n scope,\n { entries: [], done: [] },\n {\n ...Option.match(session, {\n onNone: () => ({}),\n onSome: minted => ({ session: minted }),\n }),\n unsaved: error.message,\n },\n ),\n ),\n ),\n )\n /** Whether the page's queue is the one stored under `key` for `scope`. */\n const holding = (outbox: RemoteModel['outbox'], key: string, scope: string) =>\n Option.contains(outbox.key, key) && Option.contains(outbox.scope, scope)\n const minted = (has: boolean) =>\n has\n ? Effect.succeed(Option.none<string>())\n : Effect.sync(() => Option.some(mintOperation()))\n\n // The queue's text changes only with the queue and the scope, so it is kept by them.\n let lastText: {\n readonly outbox: RemoteModel['outbox'] | undefined\n readonly scope: string\n readonly text: string\n } = { outbox: undefined, scope: '', text: '' }\n const textOf = (outbox: RemoteModel['outbox'], scope: string): string => {\n if (lastText.outbox !== outbox || lastText.scope !== scope) {\n lastText = { outbox, scope, text: storedText(storedOf(outbox), scope) }\n }\n return lastText.text\n }\n\n const restoreEntry: EntryWithoutKeepAlive<\n AppModel,\n RemoteMessage,\n {\n readonly key: string\n readonly scope: string\n readonly restored: boolean\n readonly session: boolean\n },\n KeyValueStore.KeyValueStore\n > = {\n dependenciesSchema: Schema.Struct({\n key: Schema.String,\n scope: Schema.String,\n restored: Schema.Boolean,\n session: Schema.Boolean,\n }),\n modelToDependencies: model => {\n const { outbox } = store.get(model)\n const key = options.key(model)\n const scope = options.scope(model)\n return {\n key,\n scope,\n restored: holding(outbox, key, scope),\n session: Option.isSome(outbox.session),\n }\n },\n dependenciesToStream: ({ key, scope, restored: done, session }) =>\n done\n ? Stream.empty\n : Stream.fromEffect(\n Effect.flatMap(minted(session), mint => restored(key, scope, mint)),\n ),\n }\n\n // Written whenever the queue changes, merged with what other tabs wrote,\n // and read back: what the store holds is what may be sent.\n const save: EntryWithoutKeepAlive<\n AppModel,\n RemoteMessage,\n { readonly key: string; readonly scope: string; readonly text: Option.Option<string> },\n KeyValueStore.KeyValueStore\n > = {\n dependenciesSchema: Schema.Struct({\n key: Schema.String,\n scope: Schema.String,\n text: Schema.OptionFromNullOr(Schema.String),\n }),\n modelToDependencies: model => {\n const { outbox } = store.get(model)\n const key = options.key(model)\n const scope = options.scope(model)\n return {\n key,\n scope,\n // Saved only under the key and scope it was read for: never over a queue not yet read.\n text: holding(outbox, key, scope) ? Option.some(textOf(outbox, scope)) : Option.none(),\n }\n },\n dependenciesToStream: ({ key, scope, text }) =>\n Option.match(text, {\n onNone: () => Stream.empty,\n onSome: written => {\n const mine = storedFromText(written)\n return Stream.fromEffect(\n writeStored(key, scope, mine).pipe(\n Effect.tap(() => announce(key, Option.none())),\n Effect.map(merged => readOf(key, scope, merged)),\n // A store that cannot be written does not hold the writes back:\n // they are sent, and a reload before the answer loses them.\n Effect.catch(error =>\n Effect.succeed(readOf(key, scope, mine, { unsaved: error.message })),\n ),\n ),\n )\n },\n }),\n }\n\n /** Sends `write`, as the one tab on `key` that sends, until the server answers it. */\n const sent = (key: string, scope: string, write: StoredWrite) =>\n Stream.callback<RemoteMessage, never, KeyValueStore.KeyValueStore | RemoteClient>(queue => {\n const emit = (message: RemoteMessage) => Queue.offer(queue, message)\n /**\n * The outcome told this tab and the others first, so each settles\n * with the server's answer, then written to the store before the\n * lock goes, so the next sender reads it.\n */\n const settle = (message: RemoteMessage, change: StoredOutbox) =>\n emit(message).pipe(\n Effect.andThen(announce(key, Option.some(message))),\n Effect.andThen(writeStored(key, scope, change)),\n Effect.andThen(announce(key, Option.none())),\n // Unwritten, the store still says waiting: the next sender sends it\n // again, and the operation id has the server answer from its record.\n Effect.ignore,\n )\n const operation = write.operation\n return withLock(\n sendLock(key),\n Effect.gen(function* () {\n // Another tab may have settled it while this one waited for the lock.\n const there = yield* Effect.option(readStored(key, scope))\n if (Option.isSome(there) && settledIn(there.value, operation)) {\n yield* emit(readOf(key, scope, there.value))\n return\n }\n const mutation = registeredMutation(write.mutation)\n const input = Schema.decodeUnknownSync(mutation.Input)(write.input)\n for (let attempt = 1; ; attempt++) {\n const result = yield* Effect.result(\n mutateRemote(mutation, input, operation, {\n keys: write.keys,\n operation,\n shown: write.shown,\n now: write.now,\n }),\n )\n if (Result.isSuccess(result)) {\n const outcome = result.success\n const at = yield* Clock.currentTimeMillis\n return yield* settle(\n {\n _tag: 'MutationSucceeded',\n requestId: operation,\n entities: outcome.entities,\n connections: outcome.connections,\n deleted: outcome.deleted,\n ...(outcome.read === undefined ? {} : { read: outcome.read }),\n now: at,\n },\n { entries: [], done: [operation] },\n )\n }\n const error = remoteError(result.failure)\n // Nothing answered: kept waiting, and sent again after a wait.\n if (result.failure._tag === 'Unreachable') {\n yield* emit({ _tag: 'OutboxDelayed', requestId: operation, attempt, error })\n yield* Effect.race(\n Effect.flatMap(backoff(attempt, options.retry), Effect.sleep),\n onlineAgain,\n )\n continue\n }\n return yield* settle(\n { _tag: 'MutationFailed', requestId: operation, error, operation },\n {\n entries: [\n { ...write, revision: write.revision + 1, state: { _tag: 'Failed', error } },\n ],\n done: [],\n },\n )\n }\n }),\n ).pipe(Effect.ensuring(Queue.end(queue)))\n })\n\n // The head's text changes only with the head, so a send is not restarted\n // by anything else the Model does while it waits for its answer.\n let lastHead: {\n readonly outbox: RemoteModel['outbox'] | undefined\n readonly head: Option.Option<string>\n } = { outbox: undefined, head: Option.none() }\n const headTextOf = (outbox: RemoteModel['outbox']): Option.Option<string> => {\n if (lastHead.outbox !== outbox) {\n lastHead = { outbox, head: Option.map(headOf(outbox), write => JSON.stringify(write)) }\n }\n return lastHead.head\n }\n const send: EntryWithoutKeepAlive<\n AppModel,\n RemoteMessage,\n { readonly key: string; readonly scope: string; readonly head: Option.Option<string> },\n KeyValueStore.KeyValueStore | RemoteClient\n > = {\n dependenciesSchema: Schema.Struct({\n key: Schema.String,\n scope: Schema.String,\n head: Schema.OptionFromNullOr(Schema.String),\n }),\n modelToDependencies: model => {\n const { outbox } = store.get(model)\n const key = options.key(model)\n const scope = options.scope(model)\n return {\n key,\n scope,\n // Another scope's queue is never sent: it was made as someone else.\n head: holding(outbox, key, scope) ? headTextOf(outbox) : Option.none(),\n }\n },\n dependenciesToStream: ({ key, scope, head }) =>\n Option.match(head, {\n onNone: () => Stream.empty,\n onSome: text =>\n sent(key, scope, Schema.decodeUnknownSync(StoredWrite)(JSON.parse(text))),\n }),\n }\n\n /** What another tab announced: the answer it heard first, then the store as it now is. */\n const heard = (key: string, scope: string, data: unknown) =>\n Effect.map(restored(key, scope, Option.none()), (read): ReadonlyArray<RemoteMessage> => [\n ...Option.toArray(outcomeOf(data)),\n read,\n ])\n const watch: EntryWithoutKeepAlive<\n AppModel,\n RemoteMessage,\n { readonly key: string; readonly scope: string; readonly restored: boolean },\n KeyValueStore.KeyValueStore\n > = {\n dependenciesSchema: Schema.Struct({\n key: Schema.String,\n scope: Schema.String,\n restored: Schema.Boolean,\n }),\n modelToDependencies: model => {\n const key = options.key(model)\n const scope = options.scope(model)\n return {\n key,\n scope,\n restored: holding(store.get(model).outbox, key, scope),\n }\n },\n dependenciesToStream: ({ key, scope, restored: read }) =>\n read\n ? Stream.callback<unknown>(queue =>\n Effect.acquireRelease(\n Effect.sync(() =>\n Option.map(channelFor(key), channel => {\n channel.onmessage = (event: MessageEvent<unknown>) => {\n Queue.offerUnsafe(queue, event.data)\n }\n return channel\n }),\n ),\n channel => Effect.sync(() => Option.map(channel, open => open.close())),\n ),\n ).pipe(\n Stream.mapEffect(data => heard(key, scope, data)),\n Stream.flatMap(messages => Stream.fromIterable(messages)),\n )\n : Stream.empty,\n }\n\n return {\n key: `outbox:${bound.contract.name}`,\n handles: [],\n subscriptions: Subscription.make<\n AppModel,\n RemoteMessage,\n KeyValueStore.KeyValueStore | RemoteClient\n >()(() => ({\n 'outbox.restore': restoreEntry,\n 'outbox.save': save,\n 'outbox.send': send,\n 'outbox.watch': watch,\n })),\n restore: model =>\n Effect.map(\n Effect.flatMap(minted(Option.isSome(store.get(model).outbox.session)), mint =>\n restored(options.key(model), options.scope(model), mint),\n ),\n message => reduce(model, message),\n ),\n }\n },\n wiring: (active, options = {}) => ({\n key: `remote:${bound.contract.name}`,\n shared: options.shared ?? [],\n // Every domain claims the same tags with no per-domain discriminator, so\n // the assembly's claimant check keeps one assembly to one domain.\n handles: Record.keys(remoteMessageCases),\n route: (model, message) =>\n isRemoteMessage(message)\n ? Option.some(\n reduceReporting(\n bound.store,\n reduce,\n model,\n message,\n (options.shared ?? []).some(tag => tag === 'MutationFailed'),\n ),\n )\n : Option.none(),\n subscriptions: brandEntries(domain.subscriptions(active, options)),\n contract: bound.contract,\n }),\n }\n return domain\n}\n\n/** The outbox's own answers, as another tab announced them: a settled write, and nothing else. */\nconst announcedOutcome = Schema.Struct({ outcome: Schema.optional(remoteMessageSchema) })\nconst outcomeOf = (data: unknown): Option.Option<RemoteMessage> =>\n Option.filter(\n Option.flatMap(Schema.decodeUnknownOption(announcedOutcome)(data), ({ outcome }) =>\n Option.fromUndefinedOr(outcome),\n ),\n outcome => outcome._tag === 'MutationSucceeded' || outcome._tag === 'MutationFailed',\n )\n\n/** The window keys of a `QueryOptions`, and only those, without the undefined ones. */\n/**\n * How many rows a read of `ref` shows: its window's `first` or `last`, as\n * `Data.more` has grown it. `undefined` for a window with a cursor or no size,\n * which shows whatever the connection holds.\n */\nconst windowSize = (\n remote: RemoteModel,\n ref: { readonly identity: string; readonly window: QueryWindow },\n): number | undefined => {\n const { first, last, after, before } = ref.window\n if (after !== undefined || before !== undefined) return undefined\n const size = first ?? last\n return size === undefined\n ? undefined\n : (remote.grown[windowGrowthKey(ref.identity, stableStringify(ref.window))] ?? size)\n}\n\n/** The edges a window of `size` shows, from the start (`first`) or the end (`last`), and which end it cut. */\nconst cutToWindow = (\n edges: ReadonlyArray<Edge>,\n window: QueryWindow,\n size: number | undefined,\n): {\n readonly edges: ReadonlyArray<Edge>\n readonly cutBefore: boolean\n readonly cutAfter: boolean\n} => {\n if (size === undefined || edges.length <= size) {\n return { edges, cutBefore: false, cutAfter: false }\n }\n return window.first === undefined\n ? { edges: edges.slice(edges.length - size), cutBefore: true, cutAfter: false }\n : { edges: edges.slice(0, size), cutBefore: false, cutAfter: true }\n}\n\n/**\n * Whether a row a window of `size` would show was deleted: one of `edges`\n * gone before the window, read from its end, fills with rows still `shown`.\n * A delete past the window is another window's (#287).\n */\nconst deletedInWindow = (\n edges: ReadonlyArray<Edge>,\n shown: ReadonlySet<string>,\n window: QueryWindow,\n size: number | undefined,\n gone: (key: string) => boolean,\n): boolean => {\n const ordered = window.first === undefined ? [...edges].reverse() : edges\n let filled = 0\n for (const edge of ordered) {\n if (size !== undefined && filled >= size) return false\n if (gone(entityKey(edge.ref.entity, edge.ref.id))) return true\n if (shown.has(edge.key)) filled++\n }\n return false\n}\n\nconst pickWindow = (window: QueryWindowOptions): QueryWindow => ({\n ...(window.first === undefined ? {} : { first: window.first }),\n ...(window.last === undefined ? {} : { last: window.last }),\n ...(window.after === undefined ? {} : { after: window.after }),\n ...(window.before === undefined ? {} : { before: window.before }),\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFA,MAAM,yBAAyB,kBAA8D;CAC3F,QAAQ,aAAa,OAAO,KAAK,EAAE,QAAQ,WAAW;EAAE;EAAQ;CAAI,EAAE;CACtE,QAAQ,aAAa;CACrB,YAAY,aAAa;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