@hyper-fetch/db 0.0.0-stage → 10.2.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 (141) hide show
  1. package/README.md +180 -2
  2. package/__tests__/e2e/db.e2e.spec.ts +269 -0
  3. package/__tests__/features/connection/connection.spec.ts +23 -0
  4. package/__tests__/features/model/live-query.model.spec.ts +320 -0
  5. package/__tests__/features/operators/operators.spec.ts +113 -0
  6. package/__tests__/features/runtime/runtime.spec.ts +185 -0
  7. package/__tests__/features/serializer/serializer.spec.ts +73 -0
  8. package/__tests__/features/store/store.spec.ts +147 -0
  9. package/__tests__/features/types/db.types.spec.ts +337 -0
  10. package/__tests__/integration/audit.spec.ts +639 -0
  11. package/__tests__/integration/competitors.spec.ts +393 -0
  12. package/__tests__/integration/convergence.model.spec.ts +162 -0
  13. package/__tests__/integration/edge-cases.spec.ts +465 -0
  14. package/__tests__/integration/errors.spec.ts +178 -0
  15. package/__tests__/integration/infinite.model.spec.ts +142 -0
  16. package/__tests__/integration/infinite.spec.ts +290 -0
  17. package/__tests__/integration/inspect.spec.ts +103 -0
  18. package/__tests__/integration/joins-many.spec.ts +177 -0
  19. package/__tests__/integration/joins.spec.ts +179 -0
  20. package/__tests__/integration/key-loaders.spec.ts +196 -0
  21. package/__tests__/integration/links.spec.ts +105 -0
  22. package/__tests__/integration/mutations.spec.ts +337 -0
  23. package/__tests__/integration/normalize.spec.ts +80 -0
  24. package/__tests__/integration/offline.spec.ts +479 -0
  25. package/__tests__/integration/queries.spec.ts +513 -0
  26. package/__tests__/integration/races.spec.ts +127 -0
  27. package/__tests__/integration/server-operators.spec.ts +123 -0
  28. package/__tests__/integration/ssr.spec.ts +111 -0
  29. package/__tests__/integration/syncs.spec.ts +564 -0
  30. package/__tests__/integration/transactions.spec.ts +344 -0
  31. package/__tests__/integration/windows.spec.ts +192 -0
  32. package/__tests__/tsconfig.json +11 -0
  33. package/__tests__/type-budget/budget.fixture.ts +2476 -0
  34. package/__tests__/type-budget/tsconfig.json +4 -0
  35. package/__tests__/utils/fixtures.ts +225 -0
  36. package/__tests__/utils/random.ts +19 -0
  37. package/__tests__/vitest.setup.ts +11 -0
  38. package/dist/collection/collection.d.ts +111 -0
  39. package/dist/collection/collection.d.ts.map +1 -0
  40. package/dist/collection/collection.types.d.ts +316 -0
  41. package/dist/collection/collection.types.d.ts.map +1 -0
  42. package/dist/collection/resource.types.d.ts +77 -0
  43. package/dist/collection/resource.types.d.ts.map +1 -0
  44. package/dist/db/collection.runtime.d.ts +98 -0
  45. package/dist/db/collection.runtime.d.ts.map +1 -0
  46. package/dist/db/db.d.ts +154 -0
  47. package/dist/db/db.d.ts.map +1 -0
  48. package/dist/db/db.runtime.d.ts +114 -0
  49. package/dist/db/db.runtime.d.ts.map +1 -0
  50. package/dist/db/db.types.d.ts +162 -0
  51. package/dist/db/db.types.d.ts.map +1 -0
  52. package/dist/graphql/connection.d.ts +25 -0
  53. package/dist/graphql/connection.d.ts.map +1 -0
  54. package/dist/index.d.ts +17 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/index.mjs +4220 -0
  57. package/dist/index.mjs.map +1 -0
  58. package/dist/mutation/mutation.d.ts +136 -0
  59. package/dist/mutation/mutation.d.ts.map +1 -0
  60. package/dist/mutation/mutation.errors.d.ts +6 -0
  61. package/dist/mutation/mutation.errors.d.ts.map +1 -0
  62. package/dist/mutation/mutation.utils.d.ts +35 -0
  63. package/dist/mutation/mutation.utils.d.ts.map +1 -0
  64. package/dist/operators/operators.d.ts +33 -0
  65. package/dist/operators/operators.d.ts.map +1 -0
  66. package/dist/operators/operators.types.d.ts +68 -0
  67. package/dist/operators/operators.types.d.ts.map +1 -0
  68. package/dist/operators/operators.utils.d.ts +19 -0
  69. package/dist/operators/operators.utils.d.ts.map +1 -0
  70. package/dist/persistence/persistence.d.ts +42 -0
  71. package/dist/persistence/persistence.d.ts.map +1 -0
  72. package/dist/persistence/serializer.d.ts +23 -0
  73. package/dist/persistence/serializer.d.ts.map +1 -0
  74. package/dist/persistence/snapshot.d.ts +29 -0
  75. package/dist/persistence/snapshot.d.ts.map +1 -0
  76. package/dist/persistence/tabs.d.ts +53 -0
  77. package/dist/persistence/tabs.d.ts.map +1 -0
  78. package/dist/query/infinite-query.d.ts +59 -0
  79. package/dist/query/infinite-query.d.ts.map +1 -0
  80. package/dist/query/live-query.d.ts +85 -0
  81. package/dist/query/live-query.d.ts.map +1 -0
  82. package/dist/query/planner.d.ts +57 -0
  83. package/dist/query/planner.d.ts.map +1 -0
  84. package/dist/query/query.d.ts +155 -0
  85. package/dist/query/query.d.ts.map +1 -0
  86. package/dist/query/query.types.d.ts +71 -0
  87. package/dist/query/query.types.d.ts.map +1 -0
  88. package/dist/schema/schema.types.d.ts +33 -0
  89. package/dist/schema/schema.types.d.ts.map +1 -0
  90. package/dist/store/store.d.ts +76 -0
  91. package/dist/store/store.d.ts.map +1 -0
  92. package/dist/store/store.types.d.ts +27 -0
  93. package/dist/store/store.types.d.ts.map +1 -0
  94. package/dist/subset/base-subset.d.ts +66 -0
  95. package/dist/subset/base-subset.d.ts.map +1 -0
  96. package/dist/subset/key-subset.d.ts +23 -0
  97. package/dist/subset/key-subset.d.ts.map +1 -0
  98. package/dist/subset/list-subset.d.ts +63 -0
  99. package/dist/subset/list-subset.d.ts.map +1 -0
  100. package/dist/sync/sync.d.ts +42 -0
  101. package/dist/sync/sync.d.ts.map +1 -0
  102. package/dist/utils/request.utils.d.ts +11 -0
  103. package/dist/utils/request.utils.d.ts.map +1 -0
  104. package/package.json +71 -4
  105. package/project.json +4 -0
  106. package/scripts/docs-typescript.mjs +24 -0
  107. package/scripts/type-budget.mjs +37 -0
  108. package/src/collection/collection.ts +330 -0
  109. package/src/collection/collection.types.ts +383 -0
  110. package/src/collection/resource.types.ts +114 -0
  111. package/src/db/collection.runtime.ts +572 -0
  112. package/src/db/db.runtime.ts +537 -0
  113. package/src/db/db.ts +451 -0
  114. package/src/db/db.types.ts +157 -0
  115. package/src/graphql/connection.ts +23 -0
  116. package/src/index.ts +16 -0
  117. package/src/mutation/mutation.errors.ts +7 -0
  118. package/src/mutation/mutation.ts +776 -0
  119. package/src/mutation/mutation.utils.ts +58 -0
  120. package/src/operators/operators.ts +90 -0
  121. package/src/operators/operators.types.ts +67 -0
  122. package/src/operators/operators.utils.ts +169 -0
  123. package/src/persistence/persistence.ts +168 -0
  124. package/src/persistence/serializer.ts +123 -0
  125. package/src/persistence/snapshot.ts +76 -0
  126. package/src/persistence/tabs.ts +86 -0
  127. package/src/query/infinite-query.ts +206 -0
  128. package/src/query/live-query.ts +552 -0
  129. package/src/query/planner.ts +199 -0
  130. package/src/query/query.ts +319 -0
  131. package/src/query/query.types.ts +90 -0
  132. package/src/schema/schema.types.ts +29 -0
  133. package/src/store/store.ts +300 -0
  134. package/src/store/store.types.ts +17 -0
  135. package/src/subset/base-subset.ts +169 -0
  136. package/src/subset/key-subset.ts +44 -0
  137. package/src/subset/list-subset.ts +328 -0
  138. package/src/sync/sync.ts +99 -0
  139. package/src/utils/request.utils.ts +67 -0
  140. package/tsconfig.json +12 -0
  141. package/vite.config.ts +71 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/collection/collection.ts","../src/utils/request.utils.ts","../src/mutation/mutation.errors.ts","../src/mutation/mutation.utils.ts","../src/mutation/mutation.ts","../src/operators/operators.utils.ts","../src/query/infinite-query.ts","../src/query/query.ts","../src/persistence/snapshot.ts","../src/persistence/persistence.ts","../src/persistence/serializer.ts","../src/persistence/tabs.ts","../src/query/planner.ts","../src/query/live-query.ts","../src/subset/base-subset.ts","../src/subset/list-subset.ts","../src/store/store.ts","../src/subset/key-subset.ts","../src/sync/sync.ts","../src/db/collection.runtime.ts","../src/db/db.runtime.ts","../src/db/db.ts","../src/graphql/connection.ts","../src/operators/operators.ts"],"sourcesContent":["import type { ExtractResponseType, RequestInstance } from \"@hyper-fetch/core\";\nimport type { ListenerInstance } from \"@hyper-fetch/sockets\";\n\nimport type { InferSchemaInput, InferSchemaOutput, StandardSchemaV1 } from \"../schema/schema.types\";\nimport type {\n AnyRequestPatch,\n CollectionConfig,\n CollectionOptions,\n DefaultRows,\n DeleteMutation,\n DescribeLoader,\n DescribeMutations,\n Inferred,\n IngestConfig,\n IngestOptions,\n IngestType,\n InsertMutation,\n IsExactRow,\n IsIngestRow,\n IsPartialRow,\n IsSyncRow,\n IsWriteHandled,\n KeyFieldOf,\n LoaderConfig,\n LoaderDescriptor,\n LoaderOptions,\n MutationConfig,\n MutationDescriptor,\n RowMismatch,\n SyncChangesOptions,\n SyncConfig,\n SyncMessage,\n SyncOptions,\n SyncType,\n UpdateMutation,\n} from \"./collection.types\";\nimport type {\n IsResourceValid,\n ResourceListOptions,\n ResourceLoaders,\n ResourceMutations,\n ResourceOptions,\n} from \"./resource.types\";\n\n/**\n * A typed set of complete rows, defined by a schema and a key. It declares how its backend loads rows (`load`), keeps\n * them live (`sync`), feeds them from other responses (`ingest`) and changes them (`mutate`). A collection is\n * immutable: every method returns a new collection, so it is defined in one chain and passed to `createDb`.\n *\n * When rows a method reads do not match the row type, it returns a `RowMismatch` instead of a collection, so the chain\n * and `createDb` do not compile.\n */\nexport class Collection<\n Row,\n Input = Row,\n KeyField extends KeyFieldOf<Row> = KeyFieldOf<Row>,\n Loaders extends LoaderDescriptor = never,\n Mutations extends MutationDescriptor = {},\n> {\n /** Type-only carrier of the collection's generics, never set at runtime */\n declare readonly __types?: { row: Row; input: Input; key: KeyField; loaders: Loaders; mutations: Mutations };\n\n constructor(readonly config: CollectionConfig) {}\n\n /**\n * Adds a loader: a request plus the way to read complete rows from its response. A list loader declares the filters\n * and orders it can send and whether it is paginated. A loader with `byKey` or `byKeys` reads rows by key.\n */\n load<Req extends RequestInstance, Mapped, Where, Order, Cursor, Limit, ByKey, ByKeys, LoaderNotation>(\n request: Req,\n options?: LoaderOptions<\n Row,\n NonNullable<Row[KeyField]>,\n Req,\n Mapped,\n Where,\n Order,\n Cursor,\n Limit,\n ByKey,\n ByKeys,\n LoaderNotation\n >,\n ): IsExactRow<Inferred<Mapped, DefaultRows<Req>>, Row> extends true\n ? Collection<\n Row,\n Input,\n KeyField,\n Loaders | DescribeLoader<Row, Where, Order, Cursor, Limit, ByKey, ByKeys, LoaderNotation>,\n Mutations\n >\n : RowMismatch<Inferred<Mapped, DefaultRows<Req>>, Row> {\n const loaderOptions = (options ?? {}) as Omit<LoaderConfig, \"kind\" | \"request\">;\n let kind: LoaderConfig[\"kind\"] = \"list\";\n if (loaderOptions.byKey) {\n kind = \"byKey\";\n } else if (loaderOptions.byKeys) {\n kind = \"byKeys\";\n }\n const loader: LoaderConfig = { ...loaderOptions, kind, request };\n return new Collection({ ...this.config, loaders: [...this.config.loaders, loader] }) as never;\n }\n\n /**\n * Derives loaders and mutations from an SDK resource that follows REST conventions: `$get` lists, `item.$get` reads\n * by key, `$post` inserts, `item.$patch` or `item.$put` updates and `item.$delete` deletes. Path params of the list\n * endpoint become required `eq` filters, and the query params listed in `list.where` become `eq` filters.\n *\n * @example\n * collection(PostSchema, { key: \"id\" }).resource(sdk.posts, { item: \"$postId\" });\n */\n resource<Node, Item, Mapped, Filters, Cursor, InsertSuccess, UpdateSuccess, ListOption>(\n node: Node,\n options: ResourceOptions<Row, Node, Item, Mapped, Filters, Cursor, InsertSuccess, UpdateSuccess> & {\n list?: ListOption;\n },\n ): IsResourceValid<\n Row,\n KeyField,\n Node,\n Item,\n Mapped,\n ListOption extends false ? false : true,\n InsertSuccess,\n UpdateSuccess\n > extends true\n ? Collection<\n Row,\n Input,\n KeyField,\n Loaders | ResourceLoaders<Row, Node, Item, Filters, Cursor, ListOption extends false ? false : true>,\n Mutations & ResourceMutations<Input, Row, Node, Item>\n >\n : RowMismatch<unknown, Row> {\n type Endpoint = Record<string, RequestInstance & Record<string, unknown>>;\n const resourceNode = node as unknown as Endpoint;\n const itemKey = options.item as string;\n const itemParam = itemKey.slice(1);\n const itemNode = resourceNode[itemKey] as unknown as Endpoint;\n const toKeyPatch = (key: unknown): AnyRequestPatch => ({ params: { [itemParam]: key } });\n const loaders: LoaderConfig[] = [];\n const list =\n options.list === false\n ? undefined\n : ((options.list as ResourceListOptions<Row, Node, Mapped, Filters, Cursor> | undefined) ?? {});\n if (list) {\n const listRequest = resourceNode.$get;\n const endpoint = String(listRequest.requestOptions.endpoint);\n const pathParams = [...endpoint.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1]);\n const where: NonNullable<LoaderConfig[\"where\"]> = {};\n pathParams.forEach((param) => {\n where[param] = { eq: (value: unknown) => ({ params: { [param]: value } }), required: true };\n });\n (list.where ?? []).forEach((field) => {\n where[field as string] = { eq: (value: unknown) => ({ queryParams: { [field as string]: value } }) };\n });\n loaders.push({\n kind: \"list\",\n request: listRequest,\n rows: list.rows as LoaderConfig[\"rows\"],\n where,\n cursor: list.cursor as LoaderConfig[\"cursor\"],\n page: list.page as LoaderConfig[\"page\"],\n });\n }\n loaders.push({ kind: \"byKey\", request: itemNode.$get, byKey: toKeyPatch });\n return new Collection({\n ...this.config,\n loaders: [...this.config.loaders, ...loaders],\n mutations: {\n ...this.config.mutations,\n insert: {\n request: resourceNode.$post,\n map: (row: unknown) => ({ payload: row }),\n onSuccess: options.insert?.onSuccess,\n },\n update: {\n request: itemNode[options.update?.method ?? \"$patch\"],\n map: (key: unknown, changes: unknown) => ({ ...toKeyPatch(key), payload: changes }),\n onSuccess: options.update?.onSuccess,\n },\n delete: { request: itemNode.$delete, map: (key: unknown) => toKeyPatch(key), onSuccess: \"keep\" },\n },\n }) as never;\n }\n\n /**\n * Keeps rows current from a listener. `insert` messages carry complete rows, `update` messages the key and some\n * fields, and `delete` messages the key. One listener can sync several collections.\n */\n sync<Listener extends ListenerInstance, Type extends SyncType, Mapped>(\n listener: Listener,\n options: SyncOptions<Row, KeyField, Listener, Type, Mapped>,\n ): IsSyncRow<Row, KeyField, Type, Inferred<Mapped, SyncMessage<Listener>>> extends true\n ? Collection<Row, Input, KeyField, Loaders, Mutations>\n : RowMismatch<Inferred<Mapped, SyncMessage<Listener>>, Row> {\n const sync = { ...options, listener } as SyncConfig;\n return new Collection({ ...this.config, syncs: [...this.config.syncs, sync] }) as never;\n }\n\n /**\n * Writes the rows nested in this collection's rows into another collection, for example the author of a post into\n * the `user` collection. It runs on every complete write from the server: loads, inserts, ingested responses and\n * mutation responses. The target is the collection itself, so renaming or removing it breaks the build.\n *\n * @example\n * collection(PostSchema, { key: \"id\" }).normalize(User, (post) => (post.author ? [post.author] : []));\n */\n normalize<TargetRow, Mapped>(\n target: { readonly config: CollectionConfig; readonly __types?: { row: TargetRow } },\n extract: (row: Row) => readonly Mapped[],\n ): ([Mapped] extends [never] ? true : IsExactRow<Mapped, TargetRow>) extends true\n ? Collection<Row, Input, KeyField, Loaders, Mutations>\n : RowMismatch<Mapped, TargetRow> {\n const normalize = [...(this.config.normalize ?? []), { target: target.config, extract: extract as never }];\n return new Collection({ ...this.config, normalize }) as never;\n }\n\n /**\n * Keeps rows current from a listener whose events carry several changes at once, such as a Firestore snapshot.\n * `changes` reads the complete rows to write and the keys to delete. With `notation`, the sync covers every subset\n * by sending its conditions to the listener. Adapter presets such as `firestoreCollection` use it.\n */\n syncChanges<Listener extends ListenerInstance, Mapped>(\n listener: Listener,\n options: SyncChangesOptions<Row, KeyField, Listener, Mapped>,\n ): ([Mapped] extends [never] ? true : IsExactRow<Mapped, Row>) extends true\n ? Collection<Row, Input, KeyField, Loaders, Mutations>\n : RowMismatch<Mapped, Row> {\n const sync = { ...options, type: \"changes\", listener } as SyncConfig;\n return new Collection({ ...this.config, syncs: [...this.config.syncs, sync] }) as never;\n }\n\n /**\n * Writes the rows of another request's responses into the collection, for example a search endpoint or a\n * `useSubmit` whose response is the changed row. The request does not become a loader.\n */\n ingest<Req extends RequestInstance, Mapped, Type>(\n request: Req,\n options?: IngestOptions<Req, Mapped, Type>,\n ): IsIngestRow<Row, KeyField, Inferred<Type, \"insert\"> & IngestType, Inferred<Mapped, DefaultRows<Req>>> extends true\n ? Collection<Row, Input, KeyField, Loaders, Mutations>\n : RowMismatch<Inferred<Mapped, DefaultRows<Req>>, Row> {\n const ingestOptions = (options ?? {}) as Partial<IngestConfig>;\n const ingest: IngestConfig = { ...ingestOptions, request, type: ingestOptions.type ?? \"insert\" };\n return new Collection({ ...this.config, ingests: [...this.config.ingests, ingest] }) as never;\n }\n\n /**\n * Declares how inserts, updates and deletes reach the backend. Each `map` turns the write into the request's params,\n * query params and payload. A response that is not the row needs `onSuccess`.\n */\n mutate<InsertReq, UpdateReq, DeleteReq, InsertMapped, UpdateMapped, InsertSuccess, UpdateSuccess>(mutations: {\n insert?: InsertMutation<Row, InsertReq, InsertMapped, InsertSuccess>;\n update?: UpdateMutation<Row, KeyField, UpdateReq, UpdateMapped, UpdateSuccess>;\n delete?: DeleteMutation<Row, KeyField, DeleteReq>;\n }): [\n IsWriteHandled<InsertReq, IsExactRow<Inferred<InsertMapped, ExtractResponseType<InsertReq>>, Row>, InsertSuccess>,\n IsWriteHandled<\n UpdateReq,\n IsPartialRow<Inferred<UpdateMapped, ExtractResponseType<UpdateReq>>, Row, KeyField>,\n UpdateSuccess\n >,\n ] extends [true, true]\n ? Collection<\n Row,\n Input,\n KeyField,\n Loaders,\n Mutations & DescribeMutations<Input, Row, InsertReq, UpdateReq, DeleteReq>\n >\n : RowMismatch<ExtractResponseType<InsertReq> | ExtractResponseType<UpdateReq>, Row> {\n const config = mutations as Record<\"insert\" | \"update\" | \"delete\", MutationConfig | undefined>;\n return new Collection({\n ...this.config,\n mutations: {\n ...this.config.mutations,\n ...(config.insert ? { insert: config.insert } : {}),\n ...(config.update ? { update: config.update } : {}),\n ...(config.delete ? { delete: config.delete } : {}),\n },\n }) as never;\n }\n}\n\n/** Any collection, whatever its row type */\nexport type CollectionInstance = {\n readonly config: CollectionConfig;\n readonly __types?: { row: any; input: any; key: any; loaders: any; mutations: any };\n};\n\nconst emptyConfig = (options: CollectionOptions<any, string>, schema?: StandardSchemaV1): CollectionConfig => ({\n schema,\n key: options.key,\n version: options.version,\n validate: options.validate ?? \"client\",\n loaders: [],\n syncs: [],\n ingests: [],\n mutations: {},\n});\n\n/** A row type without a schema, for `collection(rowType<Post>(), { key: \"id\" })`. Rows are not validated. */\nexport type RowType<Row> = { readonly kind: \"row-type\"; readonly __row?: Row };\n\n/** Declares a collection's row type without a schema, so writes are not validated */\nexport const rowType = <Row>(): RowType<Row> => ({ kind: \"row-type\" });\n\n/**\n * Creates a collection from a Standard Schema, such as a Zod, Valibot or ArkType schema, or from `rowType<Row>()`.\n *\n * @example\n * const Post = collection(PostSchema, { key: \"id\", version: \"updatedAt\" });\n * const Draft = collection(rowType<Draft>(), { key: \"id\" });\n */\nexport function collection<Schema extends StandardSchemaV1, KeyField extends KeyFieldOf<InferSchemaOutput<Schema>>>(\n schema: Schema,\n options: CollectionOptions<InferSchemaOutput<Schema>, KeyField>,\n): Collection<InferSchemaOutput<Schema>, InferSchemaInput<Schema>, KeyField>;\nexport function collection<Row, KeyField extends KeyFieldOf<Row>>(\n type: RowType<Row>,\n options: CollectionOptions<Row, KeyField>,\n): Collection<Row, Row, KeyField>;\nexport function collection(\n schemaOrType: StandardSchemaV1 | RowType<unknown>,\n options: CollectionOptions<any, string>,\n): CollectionInstance {\n const schema = \"~standard\" in schemaOrType ? schemaOrType : undefined;\n return new Collection(emptyConfig(options, schema));\n}\n","import type { RequestInstance } from \"@hyper-fetch/core\";\nimport type { ListenerInstance } from \"@hyper-fetch/sockets\";\n\nimport type { AnyRequestPatch, ListenerPatch } from \"../collection/collection.types\";\n\nexport const isPlainObject = (value: unknown): value is Record<string, unknown> => {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value) && !(value instanceof Date);\n};\n\n/** Objects merge and arrays, such as Firestore constraints, add up. Anything else replaces the current value. */\nconst mergeValue = (current: unknown, next: unknown) => {\n if (isPlainObject(current) && isPlainObject(next)) {\n return { ...current, ...next };\n }\n if (Array.isArray(current) && Array.isArray(next)) {\n return [...current, ...next];\n }\n return next;\n};\n\n/** Applies patches to a request, merging params, query params and object payloads into what it already has */\nexport const applyRequestPatches = <Req extends RequestInstance>(\n request: Req,\n patches: readonly AnyRequestPatch[],\n): Req => {\n let next: RequestInstance = request;\n patches.forEach((patch) => {\n if (patch.params) {\n next = next.setParams({ ...(next.params as Record<string, unknown> | undefined), ...patch.params } as never);\n }\n if (patch.queryParams !== undefined) {\n next = next.setQueryParams(mergeValue(next.queryParams, patch.queryParams) as never);\n }\n if (\"payload\" in patch) {\n next = next.setPayload(mergeValue(next.payload, patch.payload));\n }\n });\n return next as Req;\n};\n\n/** Applies patches to a listener, merging topic params, payloads and query params into what it already has */\nexport const applyListenerPatches = (listener: ListenerInstance, patches: readonly ListenerPatch[]) => {\n let next = listener;\n patches.forEach((patch) => {\n if (patch.params) {\n next = next.setParams({ ...next.params, ...patch.params } as never);\n }\n if (\"payload\" in patch) {\n next = next.setPayload(mergeValue(next.payload, patch.payload));\n }\n if (patch.queryParams !== undefined) {\n next = next.setQueryParams(mergeValue(next.queryParams, patch.queryParams) as never);\n }\n });\n return next;\n};\n\nlet idCounter = 0;\n\n/** A unique id for transactions and temporary keys */\nexport const createId = (): string => {\n if (typeof globalThis.crypto?.randomUUID === \"function\") {\n return globalThis.crypto.randomUUID();\n }\n idCounter += 1;\n return `${Date.now().toString(36)}-${idCounter.toString(36)}-${Math.random().toString(36).slice(2)}`;\n};\n","/** Why a write was dropped: an earlier write it was built on failed */\nexport class DependencyError extends Error {\n constructor(readonly transactionId: string) {\n super(`An earlier write this one depends on (${transactionId}) failed`);\n this.name = \"DependencyError\";\n }\n}\n","import type { ClientInstance, ResponseType } from \"@hyper-fetch/core\";\n\nimport type { RowKey } from \"../collection/collection.types\";\nimport type { CollectionRuntime } from \"../db/collection.runtime\";\nimport type { MutationOperation, MutationResult, TransactionRecord } from \"../db/db.types\";\nimport type { Row } from \"../store/store.types\";\n\nexport type AnyResponse = ResponseType<unknown, unknown, any>;\n\n/**\n * A pending write: a promise of the write's result that never rejects, with the write's `id`. The `id`, or the\n * transaction itself, can be passed to `dependsOn` of a later write, so the later write is dropped when this one is\n * rejected.\n */\nexport type Transaction = Promise<MutationResult> & { readonly id: string };\n\nexport const createTransaction = (id: string, result: Promise<MutationResult>): Transaction => {\n return Object.assign(result, { id });\n};\n\n/** By default a 4xx response other than 408 and 429 is permanent, and everything else is retried */\nexport const isTemporaryFailure = (response: AnyResponse) => {\n const status = Number(response.status);\n if (!status) {\n return true;\n }\n return status >= 500 || status === 408 || status === 429;\n};\n\n/** A write of a transaction, validated and ready to apply */\nexport type PreparedWrite = { collection: CollectionRuntime; op: MutationOperation; key: RowKey; values: Row };\n\n/** The rows a record writes, as `collection:key` */\nexport const rowsOf = (record: TransactionRecord) => {\n const writes = record.transaction?.writes ?? [record];\n return writes.map((write) => `${write.collection}:${String(write.key)}`);\n};\n\n/** One result for several writes: the first failure, or every write's data */\nexport const combineResults = (results: MutationResult[]): MutationResult => {\n const failed = results.find((result) => !result.success);\n return failed ?? { success: true, data: results.map((result) => result.data), error: null };\n};\n\nexport const defaultRetryDelay = (attempt: number) => Math.min(1000 * 2 ** (attempt - 1), 30_000);\n\n/** Resolves once the client is online again. `cancel` stops listening, for `destroy`. */\nexport const waitForOnline = (client: ClientInstance) => {\n let resolve!: () => void;\n const promise = new Promise<void>((done) => {\n resolve = done;\n });\n const cancel = client.appManager.events.onOnline(() => {\n cancel();\n resolve();\n });\n return { promise, cancel };\n};\n","import type { ClientInstance } from \"@hyper-fetch/core\";\n\nimport type { RowKey } from \"../collection/collection.types\";\nimport type { CollectionRuntime } from \"../db/collection.runtime\";\nimport type { DbRuntime } from \"../db/db.runtime\";\nimport type {\n DbOfflineOptions,\n MutationOperation,\n MutationResult,\n TransactionConfig,\n TransactionRecord,\n TransactionWrite,\n} from \"../db/db.types\";\nimport type { Row } from \"../store/store.types\";\nimport { applyRequestPatches, isPlainObject } from \"../utils/request.utils\";\nimport { DependencyError } from \"./mutation.errors\";\nimport type { AnyResponse, PreparedWrite, Transaction } from \"./mutation.utils\";\nimport {\n combineResults,\n createTransaction,\n defaultRetryDelay,\n isTemporaryFailure,\n rowsOf,\n waitForOnline,\n} from \"./mutation.utils\";\n\nexport type { PreparedWrite, Transaction } from \"./mutation.utils\";\nexport { createTransaction, isTemporaryFailure } from \"./mutation.utils\";\n\n/**\n * Sends writes. Each write shows at once as an optimistic layer. Writes to one row go out one at a time, and a failure\n * drops the writes queued after it on that row. With `offline`, every write goes through a persisted outbox that is\n * replayed in order across the whole db by one tab.\n */\nexport class MutationEngine {\n /** The outbox, in replay order */\n outbox: TransactionRecord[] = [];\n /** The last write of each row, which the next write to the row waits for while it is pending */\n private chains = new Map<string, { id: string; run: Promise<boolean> }>();\n private inFlight = new Map<string, number>();\n private settleWaiters = new Map<string, (() => void)[]>();\n private resolvers = new Map<string, (result: MutationResult) => void>();\n /** Writes counted as in flight, so a write is counted once however its sending ends */\n private begun = new Set<string>();\n /** Whether each settled write succeeded, so `dependsOn` can name a write that already settled */\n private outcomes = new Map<string, boolean>();\n private outcomeWaiters = new Map<string, ((success: boolean) => void)[]>();\n /** When each write's request was sent, so a sync event that arrived while it was in flight confirms it */\n private sentAt = new Map<string, number>();\n private pumping = false;\n private retryTimer: ReturnType<typeof setTimeout> | undefined;\n private cancelWait = () => {};\n private readonly offline: DbOfflineOptions | undefined;\n\n constructor(\n private readonly db: DbRuntime,\n offline: boolean | DbOfflineOptions | undefined,\n private readonly transactions: Record<string, TransactionConfig> = {},\n ) {\n this.offline = offline === true ? {} : offline || undefined;\n }\n\n /**\n * Applies several writes as one transaction. A named transaction sends them through its `mutationFn` as one request.\n * Without a name, each write goes through its collection's `mutate`, in order, and a failure drops the writes after\n * it and refetches the subsets holding the rows already written.\n */\n submitTransaction = ({\n id,\n name,\n writes,\n }: {\n id: string;\n name: string | undefined;\n writes: PreparedWrite[];\n }): Transaction => {\n if (writes.length === 0) {\n return createTransaction(id, Promise.resolve({ success: true, data: [], error: null }));\n }\n return name === undefined ? this.submitSequence(id, writes) : this.submitNamed(id, name, writes);\n };\n\n private createRecord = (write: PreparedWrite & { id: string; dependsOn: string[] }): TransactionRecord => ({\n id: write.id,\n collection: write.collection.name,\n op: write.op,\n key: write.key,\n values: write.values,\n dependsOn: write.dependsOn,\n sent: false,\n createdAt: Date.now(),\n });\n\n /** The result promise of a record, resolved once the record settles */\n private track = (record: TransactionRecord) => {\n return new Promise<MutationResult>((resolve) => {\n this.resolvers.set(record.id, resolve);\n this.generations.set(record.id, this.db.generation);\n });\n };\n\n private submitSequence = (id: string, writes: PreparedWrite[]): Transaction => {\n const records = writes.map((write, index) =>\n this.createRecord({ ...write, id: `${id}:${index}`, dependsOn: index > 0 ? [`${id}:${index - 1}`] : [] }),\n );\n const results = records.map(this.track);\n this.db.batch(() => {\n writes.forEach((write, index) => {\n if (write.collection.config.mutations[write.op]?.optimistic !== false) {\n write.collection.store.addLayer({\n id: records[index].id,\n key: write.key,\n type: write.op,\n values: write.values,\n });\n }\n });\n });\n if (this.offline) {\n // The outbox replays them in order, and a rejected write drops the ones that depend on it\n records.forEach((record) => this.enqueue(record));\n } else {\n this.runSequence(records, results, 0);\n }\n return createTransaction(id, Promise.all(results).then(combineResults));\n };\n\n /** Sends the writes of an unnamed transaction one after another */\n private runSequence = async (records: TransactionRecord[], results: Promise<MutationResult>[], index: number) => {\n const record = records[index];\n this.runDirect(record);\n const result = await results[index];\n if (!result.success) {\n records.slice(index + 1).forEach((later) => this.fail(later, new DependencyError(record.id)));\n records.slice(0, index).forEach((written) => {\n const collection = this.db.collections.get(written.collection)!;\n collection.getSubsetsHolding(collection.resolveKey(written.key)).forEach((subset) => subset.reload());\n });\n return;\n }\n if (index + 1 < records.length) {\n await this.runSequence(records, results, index + 1);\n }\n };\n\n private submitNamed = (id: string, name: string, writes: PreparedWrite[]): Transaction => {\n const transactionWrites: TransactionWrite[] = writes.map((write) => ({\n collection: write.collection.name,\n op: write.op,\n key: write.key,\n values: write.values,\n }));\n const record: TransactionRecord = {\n ...this.createRecord({ ...writes[0], id, dependsOn: [] }),\n values: {},\n transaction: { name, writes: transactionWrites },\n };\n const result = this.track(record);\n this.addTransactionLayers(record);\n if (this.offline) {\n this.enqueue(record);\n } else {\n this.runDirect(record);\n }\n return createTransaction(id, result);\n };\n\n private addTransactionLayers = (record: TransactionRecord) => {\n this.db.batch(() => {\n record.transaction!.writes.forEach((write, index) => {\n this.db.collections\n .get(write.collection)!\n .store.addLayer({ id: `${record.id}:${index}`, key: write.key, type: write.op, values: write.values });\n });\n });\n };\n\n /** Runs a callback for each write of a named transaction, as a plain record with its layer id */\n private eachWrite = (record: TransactionRecord, callback: (write: TransactionRecord) => void) => {\n record.transaction!.writes.forEach((write, index) => {\n callback({ ...record, ...write, id: `${record.id}:${index}`, transaction: undefined });\n });\n };\n\n /** Applies a write optimistically and sends it */\n submit = ({\n collection,\n op,\n key,\n values,\n dependsOn,\n id,\n temporaryKey,\n }: {\n collection: CollectionRuntime;\n op: MutationOperation;\n key: RowKey;\n values: Row;\n dependsOn: string[];\n id: string;\n temporaryKey?: boolean;\n }): Transaction => {\n const record: TransactionRecord = {\n id,\n collection: collection.name,\n op,\n key,\n values,\n dependsOn,\n sent: false,\n createdAt: Date.now(),\n ...(temporaryKey ? { temporaryKey: true } : {}),\n };\n const result = new Promise<MutationResult>((resolve) => {\n this.resolvers.set(id, resolve);\n this.generations.set(id, this.db.generation);\n });\n const mutation = collection.config.mutations[op];\n // Backends that apply writes locally on their own, such as Firestore, would apply them twice with a layer\n if (mutation?.optimistic !== false) {\n this.db.batch(() => collection.store.addLayer({ id, key, type: op, values }));\n }\n if (this.offline && mutation?.outbox !== false) {\n this.enqueue(record);\n } else {\n this.runDirect(record);\n }\n return createTransaction(id, result);\n };\n\n /** A write rejected before it was sent, for example by validation */\n reject = (error: unknown, id: string): Transaction => {\n return createTransaction(id, Promise.resolve({ success: false, data: null, error }));\n };\n\n /** Whether writes go through the outbox */\n get usesOutbox() {\n return Boolean(this.offline);\n }\n\n /** Resolves once no write of the collection is in flight */\n settled = (collection: string): Promise<void> => {\n if (!this.inFlight.get(collection)) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n this.settleWaiters.set(collection, [...(this.settleWaiters.get(collection) ?? []), resolve]);\n });\n };\n\n /** Rebuilds the optimistic layers of a restored outbox and replays it */\n restore = (records: TransactionRecord[]) => {\n this.addRecords(records);\n this.persistOutbox();\n this.pump();\n };\n\n /**\n * Writes another tab made: a follower sent them to this tab, the leader, or this tab became the leader and adopts the\n * outbox the previous leader persisted. They are persisted together with this tab's own writes and replayed.\n */\n mergeOutbox = (records: TransactionRecord[]) => {\n this.addRecords(records);\n this.persistOutbox();\n this.pump();\n };\n\n /** A new leader asks for the writes followers still wait for */\n resendToLeader = () => {\n if (this.outbox.length > 0) {\n this.db.tabs?.post({ type: \"enqueue\", records: [...this.outbox] });\n }\n };\n\n /** Adds records this tab does not hold yet, with their optimistic layers, in the order they were made */\n private addRecords = (records: TransactionRecord[]) => {\n const fresh = this.replayable(records).filter((record) => !this.outbox.some((item) => item.id === record.id));\n if (fresh.length === 0) {\n return;\n }\n fresh.forEach((record) => this.generations.set(record.id, this.db.generation));\n this.db.batch(() => {\n fresh.forEach((record) => {\n if (record.transaction) {\n this.addTransactionLayers(record);\n return;\n }\n const collection = this.db.collections.get(record.collection)!;\n collection.store.addLayer({ id: record.id, key: record.key, type: record.op, values: record.values });\n });\n });\n this.outbox = [...this.outbox, ...fresh].toSorted((left, right) => left.createdAt - right.createdAt);\n };\n\n /** The records this db can replay. The others are reported, never dropped silently. */\n private replayable = (records: TransactionRecord[]) => {\n return records.filter((record) => {\n const canReplay = record.transaction\n ? Boolean(this.transactions[record.transaction.name])\n : Boolean(this.db.collections.get(record.collection)?.config.mutations[record.op]);\n if (!canReplay) {\n const target = record.transaction\n ? `the transaction \"${record.transaction.name}\"`\n : `a write to \"${record.collection}\"`;\n this.db.emitError({\n type: \"outbox\",\n error: new Error(`The outbox holds ${target} that the db cannot replay`),\n transaction: record,\n });\n }\n return canReplay;\n });\n };\n\n /** The replaying tab reports a write's outcome */\n applyOutcome = (outcome: { id: string; success: boolean; error?: unknown; key?: RowKey }) => {\n const record = this.outbox.find((item) => item.id === outcome.id);\n if (!record) {\n return;\n }\n this.outbox = this.outbox.filter((item) => item.id !== outcome.id);\n if (outcome.success) {\n const collection = this.db.collections.get(record.collection)!;\n // The leader learned the key the server gave this tab's insert, so the row moves to it as on the leader\n if (record.temporaryKey && outcome.key !== undefined && outcome.key !== record.key) {\n collection.aliases.set(record.key, outcome.key);\n collection.setRenderKey(outcome.key, collection.getRenderKey(record.key));\n collection.store.rekeyLayers(record.key, outcome.key);\n }\n this.keep(record);\n this.resolve(record, { success: true, data: null, error: null });\n } else {\n this.fail(record, outcome.error);\n }\n };\n\n /** Replays the outbox when this tab is the one that replays it, one write at a time and in order */\n pump = async () => {\n /* oxlint-disable no-await-in-loop -- writes replay strictly one after another */\n if (!this.offline || this.pumping || !this.db.isLeader) {\n return;\n }\n this.pumping = true;\n await this.db.ready;\n let attempt = 0;\n while (this.outbox.length > 0 && !this.db.isDestroyed) {\n const record = this.outbox[0];\n const client = this.getClient(record);\n if (client && !client.appManager.isOnline) {\n const online = waitForOnline(client);\n this.cancelWait = online.cancel;\n await online.promise;\n continue;\n }\n record.sent = true;\n await this.persistOutbox();\n try {\n const response = await this.send(record, true);\n if (!response) {\n this.removeFromOutbox([record.id]);\n } else if (response.success) {\n attempt = 0;\n await this.succeed(record, response);\n this.end(record);\n this.removeFromOutbox([record.id]);\n const serverKey = this.db.collections.get(record.collection)?.resolveKey(record.key);\n this.db.tabs?.post({\n type: \"outcome\",\n id: record.id,\n success: true,\n ...(record.temporaryKey ? { key: serverKey } : {}),\n });\n } else if ((this.offline.retryable ?? isTemporaryFailure)(response)) {\n attempt += 1;\n this.end(record);\n const delay = (this.offline.retryDelay ?? defaultRetryDelay)(attempt);\n await new Promise((resolve) => {\n this.retryTimer = setTimeout(resolve, delay);\n });\n } else {\n attempt = 0;\n this.drop(record, response.error ?? response);\n }\n } catch (error) {\n // A mapping or `mutationFn` that throws can never succeed, so the write is dropped and replay goes on\n attempt = 0;\n this.drop(record, error);\n }\n }\n /* oxlint-enable no-await-in-loop */\n this.pumping = false;\n };\n\n /**\n * Drops every pending write, for example on sign-out. Writes in flight resolve as failed now, and their responses,\n * which carry the previous user's data, are never written.\n */\n clear = () => {\n this.outbox = [];\n this.chains.clear();\n const cleared = { success: false, data: null, error: new Error(\"Cleared\") };\n [...this.resolvers.values()].forEach((resolve) => resolve(cleared));\n this.resolvers.clear();\n this.sentAt.clear();\n this.persistOutbox();\n };\n\n /** Stops the retry timer, for `destroy` */\n destroy = () => {\n clearTimeout(this.retryTimer);\n this.cancelWait();\n };\n\n /** The generation each write was made or restored in, so `clear` ends the writes of the previous user */\n private generations = new Map<string, number>();\n\n /** Whether a write belongs to the current user, rather than to one `clear` ended */\n private isActive = (record: TransactionRecord) => this.generations.get(record.id) === this.db.generation;\n\n /** Resolves with whether a write succeeded. A write this db never saw, such as one from another session, is done. */\n private waitForOutcome = (id: string): Promise<boolean> => {\n if (this.outcomes.has(id)) {\n return Promise.resolve(this.outcomes.get(id)!);\n }\n if (!this.resolvers.has(id)) {\n return Promise.resolve(true);\n }\n return new Promise((resolve) => {\n this.outcomeWaiters.set(id, [...(this.outcomeWaiters.get(id) ?? []), resolve]);\n });\n };\n\n private enqueue = async (record: TransactionRecord) => {\n const failed = record.dependsOn.find((id) => this.outcomes.get(id) === false);\n if (failed) {\n this.fail(record, new DependencyError(failed));\n return;\n }\n this.outbox.push(record);\n if (!this.db.isLeader) {\n // Only the leader writes the shared outbox, so two tabs never write over each other's writes\n this.db.tabs?.post({ type: \"enqueue\", records: [record] });\n this.db.notifyChange();\n return;\n }\n await this.persistOutbox();\n this.pump();\n };\n\n private persistOutbox = () => {\n this.db.notifyChange();\n if (!this.db.isLeader) {\n return Promise.resolve();\n }\n return this.db.persistence?.saveOutbox(this.outbox) ?? Promise.resolve();\n };\n\n private removeFromOutbox = (ids: string[]) => {\n this.outbox = this.outbox.filter((record) => !ids.includes(record.id));\n this.persistOutbox();\n };\n\n private runDirect = (record: TransactionRecord) => {\n const chainKey = `${record.collection}:${String(record.key)}`;\n // A write made after the previous one settled does not depend on it, even when it failed\n const last = this.chains.get(chainKey);\n const previous = last && !this.outcomes.has(last.id) ? last.run : Promise.resolve(true);\n // Counted as in flight from now, so a refetch that starts while it waits is newer than it\n this.begin(record);\n const run = previous.then(async (previousSucceeded) => {\n const dependencies = await Promise.all(record.dependsOn.map(this.waitForOutcome));\n const failedDependency = record.dependsOn.find((_id, index) => !dependencies[index]);\n if (!previousSucceeded || failedDependency) {\n this.fail(record, new DependencyError(failedDependency ?? chainKey));\n return false;\n }\n if (!this.isActive(record)) {\n return false;\n }\n try {\n const response = await this.send(record, false);\n if (!response) {\n return false;\n }\n if (response.success) {\n await this.succeed(record, response);\n return true;\n }\n this.fail(record, response.error ?? response);\n return false;\n } catch (error) {\n this.fail(record, error);\n return false;\n }\n });\n this.chains.set(chainKey, { id: record.id, run });\n run.then(() => {\n this.end(record);\n if (this.chains.get(chainKey)?.run === run) {\n this.chains.delete(chainKey);\n }\n });\n };\n\n /** The client a record's request goes through, so replay waits while it is offline */\n private getClient = (record: TransactionRecord): ClientInstance | undefined => {\n if (record.transaction) {\n const config = this.transactions[record.transaction.name];\n return config?.mutationFn({ id: record.id, mutations: record.transaction.writes }).client;\n }\n return this.db.collections.get(record.collection)?.config.mutations[record.op]?.request.client;\n };\n\n private send = async (record: TransactionRecord, fromOutbox: boolean): Promise<AnyResponse | undefined> => {\n if (record.transaction) {\n return this.sendNamed(record, fromOutbox);\n }\n const collection = this.db.collections.get(record.collection)!;\n const mutation = collection.config.mutations[record.op];\n if (!mutation) {\n this.fail(record, new Error(`\"${record.collection}\" declares no ${record.op} mutation`));\n return undefined;\n }\n if (fromOutbox) {\n this.begin(record);\n }\n const key = collection.resolveKey(record.key);\n const context = { id: record.id };\n // `map` is the collection's request mapping, not an array method\n /* oxlint-disable no-array-method-this-argument */\n let patch;\n if (record.op === \"insert\") {\n const keyField = collection.config.key;\n const withoutKey = Object.fromEntries(Object.entries(record.values).filter(([field]) => field !== keyField));\n patch = mutation.map(record.temporaryKey ? withoutKey : record.values, context);\n } else if (record.op === \"update\") {\n patch = mutation.map(key, record.values, context);\n } else {\n patch = mutation.map(key, context);\n }\n /* oxlint-enable no-array-method-this-argument */\n let request = applyRequestPatches(mutation.request, [patch]);\n if (fromOutbox) {\n request = request.setOffline(false);\n }\n this.sentAt.set(record.id, this.db.tick());\n return request.send();\n };\n\n private sendNamed = (record: TransactionRecord, fromOutbox: boolean): Promise<AnyResponse> => {\n const { name, writes } = record.transaction!;\n if (fromOutbox) {\n this.begin(record);\n }\n let request = this.transactions[name].mutationFn({ id: record.id, mutations: writes });\n if (fromOutbox) {\n request = request.setOffline(false);\n }\n this.sentAt.set(record.id, this.db.tick());\n return request.send();\n };\n\n /** A named transaction succeeded: its changes become the server state, or the subsets holding them reload */\n private succeedNamed = async (record: TransactionRecord, response: AnyResponse) => {\n const { onSuccess = \"keep\" } = this.transactions[record.transaction!.name];\n if (onSuccess === \"refetch\") {\n this.end(record);\n const refetches: Promise<void>[] = [];\n this.eachWrite(record, (write) => {\n refetches.push(this.refetch(this.db.collections.get(write.collection)!, write));\n });\n await Promise.all(refetches);\n this.removeTransactionLayers(record);\n } else {\n this.keep(record);\n }\n this.resolve(record, { success: true, data: response.data, error: null });\n };\n\n private removeTransactionLayers = (record: TransactionRecord) => {\n this.db.batch(() => {\n this.eachWrite(record, (write) => this.db.collections.get(write.collection)!.store.removeLayer(write.id));\n });\n };\n\n private succeed = async (record: TransactionRecord, response: AnyResponse) => {\n // After `clear`, the response belongs to the previous user and is never written\n if (!this.isActive(record)) {\n return;\n }\n if (record.transaction) {\n await this.succeedNamed(record, response);\n return;\n }\n const collection = this.db.collections.get(record.collection)!;\n const mutation = collection.config.mutations[record.op]!;\n const key = collection.resolveKey(record.key);\n // The server assigned the key, but the response is not the row, so only the lists the row belongs to can tell it\n if (record.op === \"insert\" && record.temporaryKey && mutation.onSuccess) {\n this.end(record);\n const lists = [...collection.listSubsets.values()].filter(\n (subset) => subset.hasLoaded && subset.matchesSent(record.values),\n );\n await Promise.all(lists.map((subset) => subset.reload({ waitForWrites: false })));\n this.db.batch(() => collection.store.removeLayer(record.id));\n this.resolve(record, { success: true, data: response.data, error: null });\n return;\n }\n if (mutation.onSuccess === \"refetch\" || mutation.onSuccess === \"sync\") {\n this.end(record);\n let confirmed = false;\n if (mutation.onSuccess === \"sync\") {\n const since = this.sentAt.get(record.id)!;\n confirmed = await this.db.waitForSync({\n collection: record.collection,\n key,\n since,\n timeout: this.db.syncTimeout,\n });\n }\n if (!confirmed) {\n await this.refetch(collection, record);\n }\n this.db.batch(() => collection.store.removeLayer(record.id));\n this.resolve(record, { success: true, data: response.data, error: null });\n return;\n }\n this.db.batch(() => {\n if (mutation.onSuccess === \"keep\") {\n this.writeKept(collection, record);\n } else {\n this.writeResponse(collection, record, mutation.row ? mutation.row(response.data) : response.data);\n }\n collection.store.removeLayer(record.id);\n });\n this.resolve(record, { success: true, data: response.data, error: null });\n };\n\n /** A write confirmed by another tab: its values become the server state */\n private keep = (record: TransactionRecord) => {\n if (record.transaction) {\n this.db.batch(() => this.eachWrite(record, this.keep));\n return;\n }\n const collection = this.db.collections.get(record.collection)!;\n this.db.batch(() => {\n this.writeKept(collection, record);\n collection.store.removeLayer(record.id);\n });\n };\n\n private writeKept = (collection: CollectionRuntime, record: TransactionRecord) => {\n const key = collection.resolveKey(record.key);\n const stamp = { kind: \"now\" as const, seq: this.db.tick(), wall: Date.now() };\n if (record.op === \"delete\") {\n collection.store.remove(key, stamp);\n return;\n }\n collection.store.write(\n key,\n { ...record.values, [collection.config.key]: key },\n { complete: record.op === \"insert\", stamp },\n );\n };\n\n private writeResponse = (collection: CollectionRuntime, record: TransactionRecord, data: unknown) => {\n const key = collection.resolveKey(record.key);\n const stamp = { kind: \"now\" as const, seq: this.db.tick(), wall: Date.now() };\n if (record.op === \"delete\") {\n collection.store.remove(key, stamp);\n return;\n }\n if (!isPlainObject(data)) {\n return;\n }\n const serverKey = (data[collection.config.key] as RowKey | undefined) ?? key;\n collection.writeServerRows([{ ...data, [collection.config.key]: serverKey }], record.op === \"insert\", stamp);\n if (record.op !== \"insert\") {\n return;\n }\n if (serverKey !== record.key) {\n collection.aliases.set(record.key, serverKey);\n collection.setRenderKey(serverKey, collection.getRenderKey(record.key));\n collection.store.rekeyLayers(record.key, serverKey);\n }\n collection.noteInsert(serverKey);\n };\n\n /** Reloads the subsets that hold the row, after the loads already in flight */\n private refetch = async (collection: CollectionRuntime, record: TransactionRecord) => {\n const key = collection.resolveKey(record.key);\n const subsets = collection.getSubsetsHolding(key);\n if (subsets.length === 0) {\n this.db.batch(() => this.writeKept(collection, record));\n return;\n }\n // The writes queued behind this one wait for it, so its refetch must not wait for them\n await Promise.all(subsets.map((subset) => subset.reload({ waitForWrites: false })));\n };\n\n /** Drops a rejected outbox write and every later write that was built on it */\n private drop = (record: TransactionRecord, error: unknown) => {\n const droppedIds = new Set([record.id]);\n const droppedRows = new Set(rowsOf(record));\n const dropped = [record];\n this.outbox.slice(1).forEach((later) => {\n const rows = rowsOf(later);\n if (rows.some((row) => droppedRows.has(row)) || later.dependsOn.some((id) => droppedIds.has(id))) {\n droppedIds.add(later.id);\n rows.forEach((row) => droppedRows.add(row));\n dropped.push(later);\n }\n });\n this.end(record);\n this.removeFromOutbox([...droppedIds]);\n dropped.forEach((item) => {\n const reason = item === record ? error : new DependencyError(record.id);\n this.fail(item, reason);\n this.db.tabs?.post({ type: \"outcome\", id: item.id, success: false, error: String(reason) });\n });\n };\n\n private fail = (record: TransactionRecord, error: unknown) => {\n const active = this.isActive(record);\n if (record.transaction) {\n this.removeTransactionLayers(record);\n } else {\n const collection = this.db.collections.get(record.collection);\n this.db.batch(() => collection?.store.removeLayer(record.id));\n }\n this.resolve(record, { success: false, data: null, error });\n // A write `clear` already ended is not reported again\n if (active) {\n this.db.emitError({ type: \"mutation\", error, collection: record.collection, transaction: record });\n }\n };\n\n private resolve = (record: TransactionRecord, result: MutationResult) => {\n this.resolvers.get(record.id)?.(result);\n this.resolvers.delete(record.id);\n this.sentAt.delete(record.id);\n this.outcomes.set(record.id, result.success);\n this.outcomeWaiters.get(record.id)?.forEach((notify) => notify(result.success));\n this.outcomeWaiters.delete(record.id);\n };\n\n /** The collections a write changes: one, or every collection a named transaction writes */\n private collectionsOf = (record: TransactionRecord) => [\n ...new Set((record.transaction?.writes ?? [record]).map((write) => write.collection)),\n ];\n\n /** Counts a sent write as in flight in every collection it changes, once per attempt */\n private begin = (record: TransactionRecord) => {\n this.begun.add(record.id);\n this.collectionsOf(record).forEach((collection) => {\n this.inFlight.set(collection, (this.inFlight.get(collection) ?? 0) + 1);\n });\n };\n\n /** Ends a write's in-flight state once, even when its success handling ended it early */\n private end = (record: TransactionRecord) => {\n if (!this.begun.delete(record.id)) {\n return;\n }\n this.collectionsOf(record).forEach((collection) => {\n const count = this.inFlight.get(collection)! - 1;\n this.inFlight.set(collection, count);\n if (count > 0) {\n return;\n }\n const waiters = this.settleWaiters.get(collection) ?? [];\n this.settleWaiters.delete(collection);\n waiters.forEach((resolve) => resolve());\n });\n };\n}\n","import type { ComparisonNode, ExpressionNode } from \"./operators.types\";\n\n/** Turns a value into the form the db compares: dates become their instant */\nconst normalize = (value: unknown): unknown => (value instanceof Date ? value.getTime() : value);\n\n/** Compares two strings by Unicode code point, so the order does not depend on the runtime's locale */\nconst compareStrings = (left: string, right: string): number => {\n const leftPoints = [...left];\n const rightPoints = [...right];\n const length = Math.min(leftPoints.length, rightPoints.length);\n for (let index = 0; index < length; index += 1) {\n const difference = leftPoints[index].codePointAt(0)! - rightPoints[index].codePointAt(0)!;\n if (difference !== 0) {\n return difference < 0 ? -1 : 1;\n }\n }\n if (leftPoints.length === rightPoints.length) {\n return 0;\n }\n return leftPoints.length < rightPoints.length ? -1 : 1;\n};\n\n/** Two values are equal when they are the same value, or dates of the same instant */\nexport const isEqualValue = (left: unknown, right: unknown): boolean => {\n return Object.is(normalize(left), normalize(right));\n};\n\n/**\n * Orders two values. `null` and `undefined` sort before every other value. Strings compare by code point, dates by\n * instant, and values of different types by their type name, so the order is always total.\n */\nexport const compareValues = (left: unknown, right: unknown): number => {\n const a = normalize(left);\n const b = normalize(right);\n const aEmpty = a === null || a === undefined;\n const bEmpty = b === null || b === undefined;\n if (aEmpty || bEmpty) {\n if (aEmpty && bEmpty) {\n return 0;\n }\n return aEmpty ? -1 : 1;\n }\n if (typeof a === \"string\" && typeof b === \"string\") {\n return compareStrings(a, b);\n }\n if (typeof a !== typeof b) {\n return compareStrings(typeof a, typeof b);\n }\n if (Object.is(a, b)) {\n return 0;\n }\n // NaN sorts after every number, so the order stays consistent\n if (Number.isNaN(a) || Number.isNaN(b)) {\n return Number.isNaN(a) ? 1 : -1;\n }\n return (a as number) < (b as number) ? -1 : 1;\n};\n\nconst isEmpty = (value: unknown) => value === null || value === undefined;\n\nconst evaluateComparison = (node: ComparisonNode, row: Record<string, unknown>): boolean => {\n const value = row[node.field];\n switch (node.op) {\n case \"eq\": {\n return isEqualValue(value, node.value);\n }\n case \"inArray\": {\n return (node.value as unknown[]).some((item) => isEqualValue(value, item));\n }\n case \"gt\": {\n return !isEmpty(value) && compareValues(value, node.value) > 0;\n }\n case \"gte\": {\n return !isEmpty(value) && compareValues(value, node.value) >= 0;\n }\n case \"lt\": {\n return !isEmpty(value) && compareValues(value, node.value) < 0;\n }\n default: {\n return !isEmpty(value) && compareValues(value, node.value) <= 0;\n }\n }\n};\n\n/** Evaluates a filter expression on one row */\nexport const evaluate = (node: ExpressionNode, row: Record<string, unknown>): boolean => {\n switch (node.op) {\n case \"and\": {\n return node.items.every((item) => evaluate(item, row));\n }\n case \"or\": {\n return node.items.some((item) => evaluate(item, row));\n }\n case \"not\": {\n return !evaluate(node.item, row);\n }\n case \"server\": {\n // Only the server can tell, so the subset that loaded the row decides whether it belongs\n return true;\n }\n default: {\n return evaluateComparison(node, row);\n }\n }\n};\n\n/** Splits an expression at its top-level `and`, flattening nested `and` nodes */\nexport const splitAnd = (node: ExpressionNode | undefined): ExpressionNode[] => {\n if (!node) {\n return [];\n }\n if (node.op === \"and\") {\n return node.items.flatMap((item) => splitAnd(item));\n }\n return [node];\n};\n\n/** The fields an expression reads */\nexport const getExpressionFields = (node: ExpressionNode): string[] => {\n switch (node.op) {\n case \"and\":\n case \"or\": {\n return node.items.flatMap((item) => getExpressionFields(item));\n }\n case \"not\": {\n return getExpressionFields(node.item);\n }\n default: {\n return [node.field];\n }\n }\n};\n\n/** A JSON value that identifies a value structurally. Dates keep their instant. */\nexport const toStableValue = (value: unknown): unknown => {\n if (value instanceof Date) {\n return { $date: value.getTime() };\n }\n // JSON cannot tell these apart from each other or from null, so two different queries would share a subset\n if (typeof value === \"bigint\") {\n return { $bigint: value.toString() };\n }\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n return { $number: String(value) };\n }\n if (value === undefined) {\n return { $undefined: true };\n }\n if (value instanceof Map) {\n return { $map: [...value.entries()].map(([key, item]) => [toStableValue(key), toStableValue(item)]) };\n }\n if (value instanceof Set) {\n return { $set: [...value].map((item) => toStableValue(item)) };\n }\n if (Array.isArray(value)) {\n return value.map((item) => toStableValue(item));\n }\n if (value && typeof value === \"object\") {\n return Object.fromEntries(\n Object.keys(value)\n .toSorted()\n .map((key) => [key, toStableValue((value as Record<string, unknown>)[key])]),\n );\n }\n return value;\n};\n\n/** A string that is equal for structurally equal values */\nexport const stableStringify = (value: unknown): string => JSON.stringify(toStableValue(value));\n","import type { DbRuntime } from \"../db/db.runtime\";\nimport { stableStringify } from \"../operators/operators.utils\";\nimport type { LiveQuery } from \"./live-query\";\nimport type { QueryDefinition, QueryState } from \"./query.types\";\n\n/** The state of an infinite query: the rows of its window, split into pages */\nexport type InfiniteQueryState<Item> = QueryState<Item[]> & {\n /** `data` split into pages of `pageSize` */\n pages: Item[][];\n /** Whether more rows are loading to fill the window after `fetchNextPage` */\n isFetchingNextPage: boolean;\n};\n\nexport type InfiniteQueryOptions = {\n /** How many rows each page holds. Pages are independent of the backend's page size. */\n pageSize: number;\n};\n\nconst toPages = <Item>(items: Item[], pageSize: number): Item[][] => {\n return Array.from({ length: Math.ceil(items.length / pageSize) }, (_, index) =>\n items.slice(index * pageSize, (index + 1) * pageSize),\n );\n};\n\n/**\n * A window over an ordered live query: the first `pageSize` times the number of pages rows of its result. Widening it\n * shows rows the db holds at once and loads more from the query's loader only when the window runs past them.\n *\n * The window belongs to this instance, so two components showing the same query share its live query and its subset,\n * and each keeps its own number of pages.\n */\nexport class InfiniteQuery<Item> {\n /** Identifies the infinite query by its query's structure and page size */\n readonly key: string;\n private pageCount = 1;\n private live: LiveQuery;\n /** The live query of the previous window, shown while a wider `limit` loads */\n private previous: { live: LiveQuery; unsubscribe: () => void; pageCount: number } | undefined;\n private unsubscribeLive: (() => void) | undefined;\n private listeners = new Set<() => void>();\n private filling: Promise<void> | undefined;\n private widening: Promise<void> | undefined;\n private readonly paging: \"cursor\" | \"limit\" | \"none\";\n private snapshot: { source: QueryState<unknown>; pageCount: number; fetching: boolean; value: unknown } | undefined;\n\n constructor(\n private readonly runtime: DbRuntime,\n private readonly definition: QueryDefinition,\n private readonly options: InfiniteQueryOptions,\n ) {\n if (!Number.isInteger(options.pageSize) || options.pageSize < 1) {\n throw new Error(`An infinite query needs a whole pageSize of at least 1, received ${options.pageSize}`);\n }\n this.key = stableStringify({ definition, pageSize: options.pageSize });\n this.paging = runtime.getLiveQuery(definition).getPaging();\n this.live = runtime.getLiveQuery(this.getDefinition());\n }\n\n subscribe = (listener: () => void) => {\n this.listeners.add(listener);\n if (this.listeners.size === 1) {\n // The db forgets live queries nobody uses, so the window attaches to the one the db serves now\n this.live = this.runtime.getLiveQuery(this.getDefinition());\n this.unsubscribeLive = this.live.subscribe(this.onLiveChange);\n this.fill();\n }\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) {\n this.unsubscribeLive!();\n this.unsubscribeLive = undefined;\n this.dropPrevious();\n }\n };\n };\n\n getSnapshot = (): InfiniteQueryState<Item> => {\n const { source, pageCount } = this.getSource();\n const fetching = this.isFetchingNextPage();\n const cached = this.snapshot;\n if (cached && cached.source === source && cached.pageCount === pageCount && cached.fetching === fetching) {\n return cached.value as InfiniteQueryState<Item>;\n }\n const size = pageCount * this.options.pageSize;\n const rows = source.data as Item[] | undefined;\n const data = rows?.slice(0, size);\n const value: InfiniteQueryState<Item> = {\n ...(source as QueryState<Item[]>),\n data,\n pages: data ? toPages(data, this.options.pageSize) : [],\n hasNextPage: (rows?.length ?? 0) > size || (this.paging === \"cursor\" && source.hasNextPage),\n isFetchingNextPage: fetching,\n };\n this.snapshot = { source, pageCount, fetching, value };\n return value;\n };\n\n /**\n * Widens the window by one page. Rows the db holds show at once, and the loader loads more when the window runs past\n * them. Resolves once the window is filled or the backend has no more rows.\n */\n fetchNextPage = (): Promise<void> => {\n // A page that is still loading answers a second call, so a double scroll event loads one page\n if (this.filling || this.previous) {\n return this.filling ?? this.widening!;\n }\n // Pages load for subscribers, as queries do\n if (!this.unsubscribeLive || !this.getSnapshot().hasNextPage) {\n return Promise.resolve();\n }\n this.pageCount += 1;\n if (this.paging === \"limit\") {\n return this.widenLimit();\n }\n this.notify();\n return this.fill();\n };\n\n /** Loads the query again from its first page */\n refetch = (): Promise<void> => this.live.refetch();\n\n private getDefinition = (): QueryDefinition => {\n if (this.paging !== \"limit\") {\n return this.definition;\n }\n return { ...this.definition, limit: this.pageCount * this.options.pageSize + 1 };\n };\n\n /** The state and window the snapshot shows: the previous window while a wider one loads its first response */\n private getSource = () => {\n const state = this.live.getState();\n if (this.previous && state.status === \"loading\") {\n return { source: this.previous.live.getState(), pageCount: this.previous.pageCount };\n }\n return { source: state, pageCount: this.pageCount };\n };\n\n private isFetchingNextPage = () => Boolean(this.filling) || Boolean(this.previous);\n\n private onLiveChange = () => {\n if (this.previous && this.live.getState().status !== \"loading\") {\n this.dropPrevious();\n }\n this.fill();\n this.notify();\n };\n\n /** Loads backend pages until the db holds one row past the window, or the backend has none */\n private fill = (): Promise<void> => {\n if (this.filling) {\n return this.filling;\n }\n const state = this.live.getState();\n const size = this.pageCount * this.options.pageSize;\n const held = (state.data as unknown[] | undefined)?.length ?? 0;\n // Only subscribers load pages, so an unsubscribed query never loops on a subset it does not attach to\n const blocked = !this.unsubscribeLive || this.paging !== \"cursor\" || state.status === \"loading\";\n if (blocked || !state.hasNextPage || held > size) {\n return Promise.resolve();\n }\n this.filling = this.live.fetchNextPage().then(() => {\n this.filling = undefined;\n const next = this.live.getState();\n // A failed page stops filling, so a broken backend is not asked again in a loop, and so does a page that\n // brought no row, such as an empty page a server filtered\n const failed = next.error !== null && next.error !== undefined;\n this.notify();\n // A call that brought no row stops filling, so filling never spins; the next `fetchNextPage` goes on\n return failed || (next.data as unknown[]).length <= held ? undefined : this.fill();\n });\n this.notify();\n return this.filling;\n };\n\n /** A loader with `limit` and no cursor is sent the window size plus one, as a new live query */\n private widenLimit = (): Promise<void> => {\n const next = this.runtime.getLiveQuery(this.getDefinition());\n this.previous = { live: this.live, unsubscribe: this.unsubscribeLive!, pageCount: this.pageCount - 1 };\n this.live = next;\n this.unsubscribeLive = next.subscribe(this.onLiveChange);\n this.notify();\n this.widening = new Promise((resolve) => {\n let settled = false;\n const check = () => {\n if (!settled && next.getState().status !== \"loading\") {\n settled = true;\n resolve();\n // The first state can arrive while subscribing, before `stop` exists\n queueMicrotask(() => stop());\n }\n };\n const stop = next.subscribe(check);\n check();\n });\n return this.widening;\n };\n\n private dropPrevious = () => {\n this.previous?.unsubscribe();\n this.previous = undefined;\n };\n\n private notify = () => {\n this.listeners.forEach((listener) => listener());\n };\n}\n","import type { SortDirection } from \"../collection/collection.types\";\nimport type { DbRuntime } from \"../db/db.runtime\";\nimport type {\n Condition,\n ExtractConditionEq,\n ExtractConditionTokens,\n FieldRef,\n RowRefs,\n} from \"../operators/operators.types\";\nimport { stableStringify } from \"../operators/operators.utils\";\nimport type { InfiniteQueryOptions } from \"./infinite-query\";\nimport { InfiniteQuery } from \"./infinite-query\";\nimport type { IsServable, QueryDefinition, QueryExplanation, QueryState } from \"./query.types\";\n\nconst createRefs = <Row>(): RowRefs<Row> => {\n return new Proxy(\n {},\n {\n get: (_target, field) => ({ kind: \"field\", field }),\n },\n ) as RowRefs<Row>;\n};\n\n/** What a query's `data` holds: a list of results, or one result for `findOne` */\nexport type QueryData<Result, Mode extends \"list\" | \"one\"> = Mode extends \"one\" ? Result : Result[];\n\n/** A collection a query can join: a handle of the db, with its name, row and key field */\nexport type JoinTarget = { readonly collectionName: string; readonly __types?: { row: unknown; key: string } };\n\n/** The row of a joined collection */\nexport type JoinedRowOf<Target extends JoinTarget> = NonNullable<Target[\"__types\"]>[\"row\"];\n\n/** The key type of a joined collection, which the foreign key must hold */\nexport type JoinedKeyOf<Target extends JoinTarget> = JoinedRowOf<Target>[NonNullable<Target[\"__types\"]>[\"key\"] &\n keyof JoinedRowOf<Target>];\n\n/** What a join adds to each result: one row, one row or `undefined`, or an array of rows with `on` */\nexport type JoinedValue<JoinedRow, On, Type> = unknown extends On\n ? [Type] extends [\"inner\"]\n ? JoinedRow\n : JoinedRow | undefined\n : JoinedRow[];\n\n/** The value the foreign key must hold: the joined collection's key, or its `on` field */\nexport type JoinedMatchOf<Target extends JoinTarget, On> = unknown extends On\n ? JoinedKeyOf<Target>\n : On extends keyof JoinedRowOf<Target>\n ? JoinedRowOf<Target>[On]\n : never;\n\n/** The field that holds the joined key, alone or with join options */\nexport type JoinSpec<Row, Field extends keyof Row & string, Match, On, Type> =\n | JoinBy<Row, Field, Match>\n | { by: JoinBy<Row, Field, Match>; on?: On; type?: Type & (\"left\" | \"inner\") };\n\n/** Picks the field of a row that holds the joined key or value */\nexport type JoinBy<Row, Field extends keyof Row & string, Match> = (\n row: RowRefs<Row>,\n) => FieldRef<Field, Row[Field] & (Match | null | undefined)>;\n\n/** The result of a query with one more joined value */\ntype Joined<Result, Name extends string, Value> = {\n [Field in keyof Result | Name]: Field extends Name ? Value : Field extends keyof Result ? Result[Field] : never;\n};\n\ntype Selected<Selection> = {\n [Output in keyof Selection]: Selection[Output] extends FieldRef<string, infer Value> ? Value : never;\n};\n\n/**\n * An immutable description of a query over one collection. Each method returns a new query, and two queries with the\n * same structure are the same query, so a component can rebuild its query on every render.\n *\n * The type parameters record what the query asks a backend for, so the types can check that a loader serves it.\n */\nexport class Query<\n Row,\n Loaders,\n Result,\n Tokens extends string = never,\n Eq extends string = never,\n Order extends string = never,\n Mode extends \"list\" | \"one\" = \"list\",\n Local extends boolean = false,\n> {\n /** Type-only carrier of the query's generics, never set at runtime */\n declare readonly __types?: {\n row: Row;\n loaders: Loaders;\n result: Result;\n tokens: Tokens;\n eq: Eq;\n order: Order;\n mode: Mode;\n local: Local;\n };\n\n /** Identifies the query by its structure */\n readonly key: string;\n\n constructor(\n private readonly runtime: DbRuntime,\n readonly definition: QueryDefinition,\n ) {\n this.key = stableStringify(definition);\n }\n\n /**\n * Filters rows. The db splits the condition at its top-level `and`: conditions the loader declares are sent to the\n * backend, and the rest run on the rows the db holds. Calling it again adds conditions.\n */\n where<C extends Condition<string, string>>(\n this: Query<Row, Loaders, Result, Tokens, Eq, Order, \"list\", Local>,\n callback: (row: RowRefs<Row>) => C,\n ): Query<Row, Loaders, Result, Tokens | ExtractConditionTokens<C>, Eq | ExtractConditionEq<C>, Order, Mode, Local> {\n const { node } = callback(createRefs<Row>());\n const where = this.definition.where ? { op: \"and\" as const, items: [this.definition.where, node] } : node;\n return new Query(this.runtime, { ...this.definition, where });\n }\n\n /** Sorts rows by a field. Calling it again adds a sort that breaks ties of the previous ones. */\n orderBy<Name extends keyof Row & string>(\n this: Query<Row, Loaders, Result, Tokens, Eq, Order, \"list\", Local>,\n callback: (row: RowRefs<Row>) => FieldRef<Name, Row[Name]>,\n direction: SortDirection = \"asc\",\n ): Query<Row, Loaders, Result, Tokens, Eq, Order | Name, Mode, Local> {\n const { field } = callback(createRefs<Row>());\n return new Query(this.runtime, { ...this.definition, orderBy: [...this.definition.orderBy, { field, direction }] });\n }\n\n /** Picks and renames the fields each result holds */\n select<Selection extends Record<string, FieldRef<string, unknown>>>(\n callback: (row: RowRefs<Row>) => Selection,\n ): Query<Row, Loaders, Selected<Selection>, Tokens, Eq, Order, Mode, Local> {\n const selection = callback(createRefs<Row>());\n const select = Object.fromEntries(Object.entries(selection).map(([output, ref]) => [output, ref.field]));\n return new Query(this.runtime, { ...this.definition, select });\n }\n\n /**\n * Adds the row of another collection whose key is the given field, as a left join: each result holds it under `name`,\n * or `undefined` while it is not loaded or when there is none. With `{ type: \"inner\" }`, results without a joined row\n * are left out. With `{ on: \"postId\" }`, the join matches that field of the joined collection instead of its key and\n * holds an array of every matching row, loaded through a list loader that can send `inArray` on it. Options go in an\n * object with the field as `by`, as in `join(\"comments\", db.comment, { by: (post) => post.id, on: \"postId\" })`. The db loads joined rows in batches through the joined\n * collection's key loader, and a result updates whenever its joined row changes. Joined rows are loaded by key, so\n * only syncs without `where` reach them.\n */\n join<Name extends string, Target extends JoinTarget, Field extends keyof Row & string, const On, const Type>(\n name: Name,\n collection: Target,\n by: JoinSpec<Row, Field, JoinedMatchOf<Target, On>, On, Type>,\n ): Query<\n Row,\n Loaders,\n Joined<Result, Name, JoinedValue<JoinedRowOf<Target>, On, Type>>,\n Tokens,\n Eq,\n Order,\n Mode,\n Local\n > {\n const options: { type?: string; on?: unknown } = typeof by === \"function\" ? {} : by;\n const callback = typeof by === \"function\" ? by : by.by;\n const { field } = callback(createRefs<Row>());\n const join = {\n name,\n collection: collection.collectionName,\n field,\n ...(options.type === \"inner\" ? { type: \"inner\" as const } : {}),\n ...(options.on ? { on: options.on as string } : {}),\n };\n return new Query(this.runtime, { ...this.definition, joins: [...(this.definition.joins ?? []), join] });\n }\n\n /** Limits the number of results. A paginated loader that declares `limit` receives it as its page size. */\n limit(\n this: Query<Row, Loaders, Result, Tokens, Eq, Order, \"list\", Local>,\n limit: number,\n ): Query<Row, Loaders, Result, Tokens, Eq, Order, Mode, Local> {\n return new Query(this.runtime, { ...this.definition, limit });\n }\n\n /** Reads only the rows the db holds and never sends a request */\n local(): Query<Row, Loaders, Result, Tokens, Eq, Order, Mode, true> {\n return new Query(this.runtime, { ...this.definition, local: true });\n }\n\n /**\n * Subscribes to the query's state. The first subscriber attaches the query to the subset that serves it, which loads\n * when it is stale. Returns a function that unsubscribes.\n */\n subscribe(\n this: Query<Row, Loaders, Result, Tokens, Eq, Order, Mode, Local> &\n ServableCheck<Loaders, Tokens, Eq, Order, Mode, Local>,\n listener: () => void,\n ): () => void {\n return this.runtime.getLiveQuery(this.definition).subscribe(listener);\n }\n\n /** The current state. It keeps its identity until something changes, as `useSyncExternalStore` expects. */\n getSnapshot(): QueryState<QueryData<Result, Mode>> {\n return this.runtime.getLiveQuery(this.definition).getState() as QueryState<QueryData<Result, Mode>>;\n }\n\n /** Reads the query once: resolves with the first state that is not loading */\n get(\n this: Query<Row, Loaders, Result, Tokens, Eq, Order, Mode, Local> &\n ServableCheck<Loaders, Tokens, Eq, Order, Mode, Local>,\n ): Promise<QueryState<QueryData<Result, Mode>>> {\n const live = this.runtime.getLiveQuery(this.definition);\n return new Promise((resolve) => {\n let settled = false;\n const settle = () => {\n const state = live.getState();\n if (settled || state.status === \"loading\") {\n return;\n }\n settled = true;\n resolve(state as QueryState<QueryData<Result, Mode>>);\n // The first state can arrive while subscribing, before `unsubscribe` exists\n queueMicrotask(() => unsubscribe());\n };\n const unsubscribe = live.subscribe(settle);\n settle();\n });\n }\n\n /**\n * A window over the query's ordered result, widened one page at a time with `fetchNextPage`. Rows the db holds show\n * at once, and the loader loads more only when the window runs past them. The query must have `orderBy`, so a page\n * never shifts between renders.\n *\n * @example\n * const feed = db.post.orderBy((post) => post.createdAt, \"desc\").infinite({ pageSize: 20 });\n * feed.subscribe(() => render(feed.getSnapshot().pages));\n */\n infinite(\n this: Query<Row, Loaders, Result, Tokens, Eq, Order, Mode, Local> &\n ServableCheck<Loaders, Tokens, Eq, Order, Mode, Local> &\n InfiniteCheck<Order, Mode>,\n options: InfiniteQueryOptions,\n ): InfiniteQuery<Result> {\n return new InfiniteQuery<Result>(this.runtime, this.definition, options);\n }\n\n /** Loads the query's subset again */\n refetch(): Promise<void> {\n return this.runtime.getLiveQuery(this.definition).refetch();\n }\n\n /** Loads the next page of a paginated query */\n fetchNextPage(): Promise<void> {\n return this.runtime.getLiveQuery(this.definition).fetchNextPage();\n }\n\n /** How the db serves the query: the loader, what is sent, what runs locally and which syncs keep it live */\n explain(): QueryExplanation {\n return this.runtime.getLiveQuery(this.definition).explain();\n }\n}\n\n/** Fails to compile when no loader can serve the query */\nexport type ServableCheck<\n Loaders,\n Tokens extends string,\n Eq extends string,\n Order extends string,\n Mode extends \"list\" | \"one\",\n Local extends boolean,\n> = IsServable<Loaders, Tokens, Eq, Order, Mode, Local> extends true ? unknown : { servable: never };\n\n/** Fails to compile for a query without `orderBy` or one that reads one row */\nexport type InfiniteCheck<Order extends string, Mode extends \"list\" | \"one\"> = [Order] extends [never]\n ? { orderBy: never }\n : Mode extends \"one\"\n ? { list: never }\n : unknown;\n\n/** The type arguments a query instance records, read directly so that `never` stays `never` */\ntype QueryTypes<Q> = Q extends { __types?: infer Types } ? NonNullable<Types> : never;\n\n/** Fails to compile when a query cannot be read as an infinite query */\nexport type InfiniteQueryCheck<Q> =\n QueryTypes<Q> extends {\n loaders: infer Loaders;\n tokens: infer Tokens extends string;\n eq: infer Eq extends string;\n order: infer Order extends string;\n mode: infer Mode extends \"list\" | \"one\";\n local: infer Local extends boolean;\n }\n ? ServableCheck<Loaders, Tokens, Eq, Order, Mode, Local> & InfiniteCheck<Order, Mode>\n : never;\n\n/** The item type of a query instance's results */\nexport type ExtractQueryResult<Q> = QueryTypes<Q> extends { result: infer Result } ? Result : never;\n\n/** Any query, whatever its collection and result */\nexport type QueryInstance = Query<any, any, any, any, any, any, any, any>;\n\n/** Fails to compile when no loader can serve the query */\nexport type ServableQuery<Q> =\n QueryTypes<Q> extends {\n loaders: infer Loaders;\n tokens: infer Tokens extends string;\n eq: infer Eq extends string;\n order: infer Order extends string;\n mode: infer Mode extends \"list\" | \"one\";\n local: infer Local extends boolean;\n }\n ? ServableCheck<Loaders, Tokens, Eq, Order, Mode, Local>\n : never;\n\n/** The data of a query instance */\nexport type ExtractQueryData<Q> =\n QueryTypes<Q> extends { result: infer Result; mode: infer Mode extends \"list\" | \"one\" }\n ? QueryData<Result, Mode>\n : never;\n","import type { RowKey } from \"../collection/collection.types\";\nimport type { CollectionRuntime } from \"../db/collection.runtime\";\nimport type { ListPlan } from \"../query/planner\";\nimport type { QueryDefinition } from \"../query/query.types\";\nimport type { Row } from \"../store/store.types\";\n\n/** A loaded subset as persistence and server rendering keep it */\nexport type SubsetSnapshot = {\n plan: ListPlan;\n definition: Pick<QueryDefinition, \"orderBy\" | \"limit\">;\n owned: RowKey[];\n cursor: unknown;\n hasMore: boolean;\n /** How many pages a paginated subset had loaded, so a refetch reloads all of them */\n pages: number;\n /** When the subset loaded, or 0 when that is unknown */\n loadedAt: number;\n};\n\n/** A collection's server rows and loaded subsets. Optimistic layers are never part of it. */\nexport type CollectionSnapshot = {\n rows: [RowKey, Row][];\n subsets: SubsetSnapshot[];\n};\n\nexport const snapshotCollection = (collection: CollectionRuntime): CollectionSnapshot => {\n const { store } = collection;\n return {\n rows: store.getServerKeys().map((key) => [key, store.getServerRow(key)!]),\n subsets: [...collection.listSubsets.values()]\n .filter((subset) => subset.hasLoaded)\n .map((subset) => ({\n plan: subset.plan,\n definition: subset.definition,\n // In the order the last load returned, so a restored list without `orderBy` keeps its order\n owned: [...subset.owned].toSorted(\n (left, right) => subset.orderIndex.get(left)! - subset.orderIndex.get(right)!,\n ),\n cursor: subset.cursor,\n hasMore: subset.hasMore,\n pages: subset.pages,\n loadedAt: subset.loadedAt,\n })),\n };\n};\n\n/**\n * Writes a snapshot's rows and subsets into a collection. The subsets answer queries at once but count as stale,\n * because events sent since the snapshot was taken were missed, so they refetch when a query mounts.\n */\nexport const restoreSnapshot = (collection: CollectionRuntime, snapshot: CollectionSnapshot) => {\n collection.db.batch(() => {\n snapshot.rows.forEach(([rowKey, row]) => {\n collection.store.write(rowKey, row, { complete: true, stamp: { kind: \"sent\", seq: 0, wall: 0 } });\n });\n snapshot.subsets.forEach((stored) => {\n const subset = collection.getListSubset(stored.plan, {\n collection: collection.name,\n orderBy: stored.definition.orderBy,\n limit: stored.definition.limit,\n local: false,\n });\n stored.owned.forEach((ownedKey, index) => {\n subset.owned.add(ownedKey);\n subset.orderIndex.set(ownedKey, index);\n });\n subset.cursor = stored.cursor;\n subset.hasMore = stored.hasMore;\n subset.pages = stored.pages;\n subset.hasLoaded = true;\n subset.loadedAt = stored.loadedAt;\n subset.invalidated = true;\n subset.notify();\n });\n });\n};\n","import type { CollectionRuntime } from \"../db/collection.runtime\";\nimport type { DbRuntime } from \"../db/db.runtime\";\nimport type { DbPersistenceOptions, DbStorage, TransactionRecord } from \"../db/db.types\";\nimport type { Serializer } from \"./serializer\";\nimport type { CollectionSnapshot } from \"./snapshot\";\nimport { restoreSnapshot, snapshotCollection } from \"./snapshot\";\n\n/** The outbox's own format version. It changes only when the stored shape of a transaction changes. */\nexport const OUTBOX_FORMAT = 1;\n\ntype PersistedCollection = CollectionSnapshot & { version: string | number };\n\ntype PersistedOutbox = { format: number; entries: TransactionRecord[] };\n\n/**\n * Persists server rows, loaded subsets and the outbox under a scope, such as the user id. Rows of another db version\n * are cleared, because the server holds a copy. The outbox is never cleared with them.\n */\nexport class Persistence {\n readonly networkTimeout: number;\n private readonly storage: DbStorage;\n private readonly prefix: string;\n private readonly version: string | number;\n private readonly serializer: Serializer;\n /** Set when the stored outbox cannot be read, so it is never written over */\n private outboxLocked = false;\n private scheduled = new Set<CollectionRuntime>();\n private timer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n private readonly db: DbRuntime,\n options: DbPersistenceOptions,\n serializer: Serializer,\n ) {\n this.storage = options.storage;\n this.prefix = `hf-db:${options.scope ?? \"default\"}`;\n this.version = options.version ?? 1;\n this.networkTimeout = options.networkTimeout ?? 5000;\n this.serializer = serializer;\n }\n\n /** Restores every collection and returns the persisted outbox */\n restore = async (): Promise<TransactionRecord[]> => {\n await Promise.all([...this.db.collections.values()].map((collection) => this.restoreCollection(collection)));\n return this.loadOutbox();\n };\n\n /**\n * Reads the outbox. An outbox this version cannot read, corrupt or of another format, is reported and never written\n * over, because it may hold the only copy of writes another version of the app can replay.\n */\n loadOutbox = async (): Promise<TransactionRecord[]> => {\n const key = `${this.prefix}:outbox`;\n let raw: string | null;\n try {\n raw = await this.storage.getItem(key);\n } catch (error) {\n this.db.emitError({ type: \"persistence\", error });\n return [];\n }\n if (!raw) {\n return [];\n }\n let stored: PersistedOutbox;\n try {\n stored = this.serializer.parse(raw) as PersistedOutbox;\n } catch (error) {\n this.outboxLocked = true;\n this.db.emitError({ type: \"persistence\", error });\n return [];\n }\n if (stored.format !== OUTBOX_FORMAT) {\n this.outboxLocked = true;\n this.db.emitError({\n type: \"outbox\",\n error: new Error(`The persisted outbox has format ${stored.format}, which this version cannot replay`),\n });\n return [];\n }\n return stored.entries;\n };\n\n saveOutbox = (entries: TransactionRecord[]) => {\n if (this.outboxLocked) {\n return Promise.resolve();\n }\n const value: PersistedOutbox = { format: OUTBOX_FORMAT, entries };\n return this.write(`${this.prefix}:outbox`, value);\n };\n\n /** Saves the collections whose rows changed, once the current tick is over */\n scheduleSave = (collections: Iterable<CollectionRuntime>) => {\n if (!this.db.isLeader || !this.db.isReady) {\n return;\n }\n [...collections].forEach((collection) => this.scheduled.add(collection));\n if (this.timer || this.scheduled.size === 0) {\n return;\n }\n this.timer = setTimeout(() => {\n this.timer = undefined;\n const due = [...this.scheduled];\n this.scheduled.clear();\n due.forEach((collection) => this.saveCollection(collection));\n }, 0);\n };\n\n saveCollection = (collection: CollectionRuntime) => {\n const value: PersistedCollection = { version: this.version, ...snapshotCollection(collection) };\n return this.write(`${this.prefix}:rows:${collection.name}`, value);\n };\n\n /** Removes everything this scope persisted */\n clear = async () => {\n clearTimeout(this.timer);\n this.timer = undefined;\n this.scheduled.clear();\n await Promise.all([\n this.remove(`${this.prefix}:outbox`),\n ...[...this.db.collections.keys()].map((name) => this.remove(`${this.prefix}:rows:${name}`)),\n ]);\n };\n\n destroy = () => {\n clearTimeout(this.timer);\n this.timer = undefined;\n };\n\n private restoreCollection = async (collection: CollectionRuntime) => {\n const key = `${this.prefix}:rows:${collection.name}`;\n const stored = await this.read<PersistedCollection>(key);\n if (!stored) {\n return;\n }\n if (stored.version !== this.version) {\n await this.remove(key);\n return;\n }\n // Restored load times are not trusted, because the app may have been closed for a long time\n restoreSnapshot(collection, { ...stored, subsets: stored.subsets.map((subset) => ({ ...subset, loadedAt: 0 })) });\n };\n\n private read = async <T>(key: string): Promise<T | undefined> => {\n try {\n const raw = await this.storage.getItem(key);\n return raw ? (this.serializer.parse(raw) as T) : undefined;\n } catch (error) {\n this.db.emitError({ type: \"persistence\", error });\n return undefined;\n }\n };\n\n private write = async (key: string, value: unknown) => {\n try {\n await this.storage.setItem(key, this.serializer.stringify(value));\n } catch (error) {\n this.db.emitError({ type: \"persistence\", error });\n }\n };\n\n private remove = async (key: string) => {\n try {\n await this.storage.removeItem(key);\n } catch (error) {\n this.db.emitError({ type: \"persistence\", error });\n }\n };\n}\n","/** A value type the db stores as tagged JSON, beyond the ones it knows */\nexport type DbCodec = {\n /** The tag stored with encoded values. It must stay the same across releases. */\n name: string;\n /** Whether a value is of this type */\n test: (value: unknown) => boolean;\n /** Turns a value into one the serializer can store */\n encode: (value: unknown) => unknown;\n /** Turns a stored value back */\n decode: (value: unknown) => unknown;\n};\n\nconst TAG = \"$hf\";\n\ntype Tagged = { [TAG]: string; v?: unknown };\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\n\nconst isTagged = (value: unknown): value is Tagged => isPlainObject(value) && typeof value[TAG] === \"string\";\n\n/**\n * Stores values as type-tagged JSON, so `Date`, `bigint`, `Map`, `Set`, `undefined`, `NaN` and the infinities come back\n * as they were. Persistence, the outbox and server rendering use it.\n */\nexport const createSerializer = (codecs: readonly DbCodec[] = []) => {\n const encode = (value: unknown): unknown => {\n const codec = codecs.find((item) => item.test(value));\n if (codec) {\n return { [TAG]: codec.name, v: encode(codec.encode(value)) };\n }\n if (value === undefined) {\n return { [TAG]: \"undefined\" };\n }\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n return { [TAG]: \"number\", v: String(value) };\n }\n if (typeof value === \"bigint\") {\n return { [TAG]: \"bigint\", v: value.toString() };\n }\n if (value instanceof Date) {\n return { [TAG]: \"Date\", v: encode(value.getTime()) };\n }\n if (value instanceof Map) {\n return { [TAG]: \"Map\", v: [...value.entries()].map(([key, item]) => [encode(key), encode(item)]) };\n }\n if (value instanceof Set) {\n return { [TAG]: \"Set\", v: [...value].map(encode) };\n }\n if (Array.isArray(value)) {\n return value.map(encode);\n }\n if (isPlainObject(value)) {\n const encoded = Object.fromEntries(Object.entries(value).map(([key, item]) => [key, encode(item)]));\n // An object that has the tag's key itself is wrapped, so it is never read as a tagged value\n return TAG in value ? { [TAG]: \"object\", v: encoded } : encoded;\n }\n return value;\n };\n\n const decodeEntries = (value: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(value).map(([key, item]) => [key, decode(item)]));\n\n const decodeTagged = ({ [TAG]: tag, v }: Tagged): unknown => {\n switch (tag) {\n case \"undefined\": {\n return undefined;\n }\n case \"number\": {\n return Number(v);\n }\n case \"bigint\": {\n return BigInt(v as string);\n }\n case \"Date\": {\n return new Date(decode(v) as number);\n }\n case \"Map\": {\n return new Map((v as [unknown, unknown][]).map(([key, item]) => [decode(key), decode(item)]));\n }\n case \"Set\": {\n return new Set((v as unknown[]).map(decode));\n }\n case \"object\": {\n return decodeEntries(v as Record<string, unknown>);\n }\n default: {\n const codec = codecs.find((item) => item.name === tag);\n if (!codec) {\n throw new Error(`No codec decodes stored values tagged \"${tag}\"`);\n }\n return codec.decode(decode(v));\n }\n }\n };\n\n function decode(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(decode);\n }\n if (isTagged(value)) {\n return decodeTagged(value);\n }\n if (isPlainObject(value)) {\n return decodeEntries(value);\n }\n return value;\n }\n\n return {\n encode,\n decode,\n stringify: (value: unknown) => JSON.stringify(encode(value)),\n parse: (raw: string) => decode(JSON.parse(raw)),\n };\n};\n\nexport type Serializer = ReturnType<typeof createSerializer>;\n","import type { DbChannel, DbLockManager, TransactionRecord } from \"../db/db.types\";\n\nexport type TabsMessage =\n /** A follower's writes, which only the leader persists and replays */\n | { type: \"enqueue\"; records: TransactionRecord[] }\n /** A tab became the leader: followers send it the writes they still wait for */\n | { type: \"leader\" }\n /** A tab cleared the db, for example on sign-out */\n | { type: \"clear\" }\n /** A replayed write settled. `key` is the key the server gave an insert that left it to the server. */\n | { type: \"outcome\"; id: string; success: boolean; error?: unknown; key?: string | number }\n | { type: \"rows\"; collection: string; rows: [string | number, Record<string, unknown>][] };\n\nconst getDefaultLocks = (): DbLockManager | undefined => {\n const navigatorLike = (globalThis as { navigator?: { locks?: DbLockManager } }).navigator;\n return navigatorLike?.locks;\n};\n\nconst getDefaultChannel = (name: string): DbChannel | undefined => {\n if (typeof BroadcastChannel === \"undefined\") {\n return undefined;\n }\n return new BroadcastChannel(name) as unknown as DbChannel;\n};\n\n/**\n * Elects the one tab that replays the outbox and writes persisted rows, with Web Locks. Without Web Locks every tab\n * treats itself as the leader. Tabs exchange outbox changes, outcomes and rows over a `BroadcastChannel`.\n */\nexport class Tabs {\n isLeader = false;\n private closed = false;\n private readonly locks: DbLockManager | undefined;\n private readonly channel: DbChannel | undefined;\n private releaseLock: (() => void) | undefined;\n private readonly listener = (event: { data: unknown }) => this.handlers.onMessage(event.data as TabsMessage);\n\n constructor(\n private readonly name: string,\n options: { locks?: DbLockManager; channel?: DbChannel } | undefined,\n private readonly handlers: { onLeader: () => void; onMessage: (message: TabsMessage) => void },\n ) {\n this.locks = options ? options.locks : getDefaultLocks();\n this.channel = options ? options.channel : getDefaultChannel(name);\n }\n\n start = () => {\n this.channel?.addEventListener(\"message\", this.listener);\n if (!this.locks) {\n this.becomeLeader();\n return;\n }\n this.locks.request(`${this.name}:leader`, () => {\n // A tab destroyed while it waited releases the lock at once instead of leading\n if (this.closed) {\n return Promise.resolve();\n }\n this.becomeLeader();\n return new Promise<void>((resolve) => {\n this.releaseLock = resolve;\n });\n });\n };\n\n post = (message: TabsMessage) => {\n // A write can finish after the db was destroyed, and a closed channel throws on post\n if (this.closed) {\n return;\n }\n this.channel?.postMessage(message);\n };\n\n close = () => {\n this.closed = true;\n this.releaseLock?.();\n this.releaseLock = undefined;\n this.isLeader = false;\n this.channel?.removeEventListener(\"message\", this.listener);\n this.channel?.close();\n };\n\n private becomeLeader = () => {\n this.isLeader = true;\n this.handlers.onLeader();\n };\n}\n","import type {\n AnyRequestPatch,\n CollectionConfig,\n LoaderConfig,\n RowKey,\n SortDirection,\n} from \"../collection/collection.types\";\nimport type { DbNotation } from \"../db/db.types\";\nimport type { ComparisonNode, ExpressionNode, SendableNode } from \"../operators/operators.types\";\nimport { getExpressionFields, splitAnd, stableStringify } from \"../operators/operators.utils\";\nimport type { QueryDefinition } from \"./query.types\";\n\nexport type ListPlan = {\n kind: \"list\";\n loaderIndex: number;\n /** Conditions sent to the backend */\n sent: SendableNode[];\n /** Conditions evaluated on the rows the db holds */\n local: ExpressionNode[];\n /** Whether the query's order is sent to the backend */\n sendOrder: boolean;\n /** Whether the query's limit is sent to the backend */\n sendLimit: boolean;\n paginated: boolean;\n /** Whether the query filters or sorts by a field the backend compares differently, so it is never answered locally */\n serverOnly: boolean;\n subsetId: string;\n};\n\nexport type OnePlan = { kind: \"one\"; key: RowKey; loaderIndex: number | undefined };\n\nexport type LocalPlan = { kind: \"local\" };\n\nexport type ErrorPlan = { kind: \"error\"; error: Error };\n\nexport type QueryPlan = ListPlan | OnePlan | LocalPlan | ErrorPlan;\n\nexport const isPaginatedLoader = (loader: LoaderConfig) => Boolean(loader.cursor || loader.limit);\n\n/**\n * How a loader sends a comparison: its own mapping, the db-wide notation for one declared with `true`, or the loader's\n * adapter notation for any field. `undefined` when it cannot send it.\n */\nexport const getWhereMapping = (\n loader: LoaderConfig,\n node: SendableNode,\n notation: DbNotation | undefined,\n): ((value: unknown) => AnyRequestPatch) | undefined => {\n if (node.op === \"server\") {\n // Server-only operators have no notation, so the loader maps them itself\n const declaration = (loader.where?.[node.field] as Record<string, unknown> | undefined)?.[node.name];\n return typeof declaration === \"function\" ? (declaration as (value: unknown) => AnyRequestPatch) : undefined;\n }\n const declaration = loader.where?.[node.field]?.[node.op];\n if (typeof declaration === \"function\") {\n return declaration as (value: unknown) => AnyRequestPatch;\n }\n const shared = declaration === true ? notation?.where?.[node.op] : loader.notation?.where?.[node.op];\n return shared && ((value) => shared(node.field, value));\n};\n\n/** How a loader sends an order, resolved like `getWhereMapping` */\nexport const getOrderMapping = (\n loader: LoaderConfig,\n field: string,\n notation: DbNotation | undefined,\n): ((direction: SortDirection) => AnyRequestPatch) | undefined => {\n const declaration = loader.orderBy?.[field];\n if (typeof declaration === \"function\") {\n return declaration as (direction: SortDirection) => AnyRequestPatch;\n }\n const shared = declaration === true ? notation?.orderBy : loader.notation?.orderBy;\n return shared && ((direction) => shared(field, direction));\n};\n\n/** Whether an expression uses a server-only operator anywhere */\nconst containsServerNode = (node: ExpressionNode): boolean => {\n if (node.op === \"and\" || node.op === \"or\") {\n return node.items.some(containsServerNode);\n }\n if (node.op === \"not\") {\n return containsServerNode(node.item);\n }\n return node.op === \"server\";\n};\n\n/** Whether a loader can send a condition. `and`, `or` and `not` run on the client. */\nexport const canSend = (loader: LoaderConfig, node: ExpressionNode, notation: DbNotation | undefined): boolean => {\n if (node.op === \"and\" || node.op === \"or\" || node.op === \"not\") {\n return false;\n }\n return Boolean(getWhereMapping(loader, node, notation));\n};\n\nconst canSendOrder = (loader: LoaderConfig, field: string, notation: DbNotation | undefined) =>\n Boolean(getOrderMapping(loader, field, notation));\n\n/** Builds the id of the loaded subset that serves a plan, shared by every query with the same backend request */\nexport const getSubsetId = (\n collectionName: string,\n plan: Omit<ListPlan, \"subsetId\">,\n definition: QueryDefinition,\n): string => {\n const sent = plan.sent.map((node) => stableStringify(node)).toSorted();\n return stableStringify([\n collectionName,\n plan.loaderIndex,\n sent,\n plan.sendOrder ? definition.orderBy : null,\n plan.sendLimit ? definition.limit : null,\n ]);\n};\n\n/**\n * Picks how the db serves a query. Among the list loaders whose required filters the query sets, it picks the one that\n * can send the most of the query's top-level conditions; ties go to the loader declared first. A paginated loader is a\n * candidate only when it can send every condition and order, because filtering one page on the client is wrong.\n */\nexport const planQuery = ({\n collectionName,\n config,\n definition,\n notation,\n}: {\n collectionName: string;\n config: CollectionConfig;\n definition: QueryDefinition;\n notation: DbNotation | undefined;\n}): QueryPlan => {\n if (definition.one) {\n const index = config.loaders.findIndex((loader) => loader.kind === \"byKeys\");\n const byKey = config.loaders.findIndex((loader) => loader.kind === \"byKey\");\n const loaderIndex = index === -1 ? byKey : index;\n const usable = !definition.local && loaderIndex !== -1;\n return { kind: \"one\", key: definition.one.key, loaderIndex: usable ? loaderIndex : undefined };\n }\n\n if (definition.local) {\n if (definition.where && containsServerNode(definition.where)) {\n return { kind: \"error\", error: new Error(\"A local query cannot use a server-only operator\") };\n }\n return { kind: \"local\" };\n }\n\n const conditions = splitAnd(definition.where);\n const eqFields = new Set(\n conditions.filter((node): node is ComparisonNode => node.op === \"eq\").map((node) => node.field),\n );\n\n let best: Omit<ListPlan, \"subsetId\"> | undefined;\n\n config.loaders.forEach((loader, loaderIndex) => {\n if (loader.kind !== \"list\") {\n return;\n }\n const required = Object.keys(loader.where ?? {}).filter((field) => loader.where?.[field]?.required);\n if (!required.every((field) => eqFields.has(field))) {\n return;\n }\n const sent = conditions.filter((node): node is SendableNode => canSend(loader, node, notation));\n const local = conditions.filter((node) => !canSend(loader, node, notation));\n const ordersSendable = definition.orderBy.every((order) => canSendOrder(loader, order.field, notation));\n const paginated = isPaginatedLoader(loader);\n if (paginated && (local.length > 0 || !ordersSendable)) {\n return;\n }\n // The client cannot evaluate a server-only operator, so a loader that cannot send it cannot serve the query\n if (local.some((node) => containsServerNode(node))) {\n return;\n }\n if (best && best.sent.length >= sent.length) {\n return;\n }\n const serverOnly = new Set(loader.serverOnly);\n const readFields = [\n ...conditions.flatMap((node) => getExpressionFields(node)),\n ...definition.orderBy.map((order) => order.field),\n ];\n best = {\n kind: \"list\",\n loaderIndex,\n sent,\n local,\n sendOrder: ordersSendable && definition.orderBy.length > 0,\n sendLimit: Boolean(loader.limit && definition.limit !== undefined),\n paginated,\n serverOnly: readFields.some((field) => serverOnly.has(field)) || sent.some((node) => node.op === \"server\"),\n };\n });\n\n if (!best) {\n return {\n kind: \"error\",\n error: new Error(`No loader of \"${collectionName}\" can serve this query. Set its required filters.`),\n };\n }\n\n return { ...best, subsetId: getSubsetId(collectionName, best, definition) };\n};\n","import type { RowKey } from \"../collection/collection.types\";\nimport type { CollectionRuntime } from \"../db/collection.runtime\";\nimport { evaluate } from \"../operators/operators.utils\";\nimport type { Row } from \"../store/store.types\";\nimport type { SubsetObserver } from \"../subset/base-subset\";\nimport type { KeySubset } from \"../subset/key-subset\";\nimport type { ListSubset } from \"../subset/list-subset\";\nimport type { QueryPlan } from \"./planner\";\nimport { planQuery } from \"./planner\";\nimport type { QueryDefinition, QueryExplanation, QueryState } from \"./query.types\";\n\nconst isSameState = (left: QueryState<unknown>, right: QueryState<unknown>) => {\n return (\n left.data === right.data &&\n left.status === right.status &&\n left.error === right.error &&\n left.stale === right.stale &&\n left.isFetching === right.isFetching &&\n left.hasNextPage === right.hasNextPage\n );\n};\n\ntype JoinDefinition = NonNullable<QueryDefinition[\"joins\"]>[number];\n\nconst EMPTY_ROWS: Row[] = [];\n\n/** Joined values are the same row, or arrays of the same rows */\nconst sameJoined = (left: unknown, right: unknown) => {\n if (Array.isArray(left) && Array.isArray(right)) {\n return left.length === right.length && left.every((item, index) => item === right[index]);\n }\n return left === right;\n};\n\nconst sameItems = (left: unknown, right: unknown[]) => {\n return (\n Array.isArray(left) && left.length === right.length && left.every((item, index) => Object.is(item, right[index]))\n );\n};\n\n/**\n * The running form of a query: it attaches to the loaded subset that serves it, keeps its result current as rows\n * change and tells its subscribers. Queries with the same definition share one live query.\n */\nexport class LiveQuery implements SubsetObserver {\n readonly plan: QueryPlan;\n private listeners = new Set<() => void>();\n private source: ListSubset | undefined;\n private keySubset: KeySubset | undefined;\n private answeredLocally = false;\n /** The subset a query that nothing subscribes to reads, see `getSource` */\n private peeked: ListSubset | undefined;\n private sorted: RowKey[] = [];\n private members = new Set<RowKey>();\n private selections = new Map<RowKey, { row: Row; joined: unknown[]; value: unknown }>();\n /** Key subsets that load the joined rows, by `collection:key` */\n private joinSubsets = new Map<string, KeySubset>();\n /** Live queries that load the rows of one-to-many joins, by join name */\n private joinQueries = new Map<string, { key: string; unsubscribe: () => void }>();\n /** The rows of each one-to-many join by the value of its `on` field, built when first read */\n private childIndex = new Map<string, Map<unknown, Row[]>>();\n private state: QueryState<unknown> = {\n data: undefined,\n status: \"loading\",\n error: null,\n stale: false,\n isFetching: false,\n hasNextPage: false,\n };\n\n constructor(\n readonly collection: CollectionRuntime,\n readonly definition: QueryDefinition,\n readonly key: string,\n ) {\n this.plan = planQuery({\n collectionName: collection.name,\n config: collection.config,\n definition,\n notation: collection.db.notation,\n });\n this.state = this.computeState();\n }\n\n /** The current state. A query nobody subscribes to is computed from the rows the db holds right now. */\n getState = () => {\n if (!this.isActive()) {\n this.rebuild();\n }\n return this.state;\n };\n\n subscribe = (listener: () => void) => {\n this.listeners.add(listener);\n if (this.listeners.size === 1) {\n this.attach();\n }\n return () => {\n this.listeners.delete(listener);\n if (this.listeners.size === 0) {\n this.detach();\n }\n };\n };\n\n /** Whether anything subscribes to the query */\n isActive = () => this.listeners.size > 0;\n\n /** How many listeners subscribe to the query */\n get subscriberCount() {\n return this.listeners.size;\n }\n\n refetch = (): Promise<void> => {\n return (this.source ?? this.keySubset)?.load() ?? Promise.resolve();\n };\n\n /** How the query's loader pages: by cursor, by a growing `limit`, or not at all */\n getPaging = (): \"cursor\" | \"limit\" | \"none\" => {\n if (this.plan.kind !== \"list\") {\n return \"none\";\n }\n const loader = this.collection.config.loaders[this.plan.loaderIndex];\n if (loader.cursor) {\n return \"cursor\";\n }\n return loader.limit ? \"limit\" : \"none\";\n };\n\n fetchNextPage = (): Promise<void> => {\n return this.source?.loadNext() ?? Promise.resolve();\n };\n\n /** Refetches the query's subset when it is stale, after focus or reconnect */\n revalidate = () => {\n (this.source ?? this.keySubset)?.revalidate();\n };\n\n explain = (): QueryExplanation => {\n const { plan } = this;\n const subset = this.source ?? this.keySubset;\n const syncs = (subset?.subscriptions ?? []).map((subscription) => ({\n type: subscription.sync.type,\n topic: subscription.listener.topic,\n }));\n if (plan.kind === \"error\") {\n return { kind: \"error\", sent: [], local: [], answeredLocally: false, syncs, error: plan.error };\n }\n if (plan.kind === \"local\") {\n return {\n kind: \"local\",\n sent: [],\n local: this.definition.where ? [this.definition.where] : [],\n answeredLocally: true,\n syncs,\n };\n }\n if (plan.kind === \"one\") {\n return {\n kind: \"one\",\n loader: plan.loaderIndex,\n sent: [],\n local: [],\n answeredLocally: plan.loaderIndex === undefined,\n syncs,\n };\n }\n const container = this.source ? undefined : this.collection.findContainingSubset(plan);\n const answeredLocally = this.source ? this.answeredLocally : Boolean(container && container.id !== plan.subsetId);\n return { kind: \"list\", loader: plan.loaderIndex, sent: plan.sent, local: plan.local, answeredLocally, syncs };\n };\n\n /** Rows changed: update membership and order of just those rows */\n onRowsChanged = (keys: Iterable<RowKey>) => {\n if (this.plan.kind === \"error\" || !this.isActive()) {\n return;\n }\n // Most writes touch rows a query does not show, so those queries do no further work\n const touched = [...keys].filter((key) => this.members.has(key) || this.isMember(key));\n if (touched.length === 0) {\n return;\n }\n const compare = this.getComparator();\n touched.forEach((key) => {\n if (this.members.has(key)) {\n this.sorted.splice(this.sorted.indexOf(key), 1);\n this.members.delete(key);\n }\n if (this.isMember(key)) {\n this.insertSorted(key, compare);\n }\n });\n this.syncJoins();\n this.emit();\n };\n\n /** The subset's rows or status changed */\n onSubsetChange = () => {\n this.collection.db.markQueryDirty(this);\n };\n\n /** Recomputes the whole result */\n rebuild = () => {\n this.childIndex.clear();\n this.peeked = this.peekSource();\n // A list query without a subset to read shows nothing yet\n const readable = this.plan.kind !== \"list\" || this.getSource() !== undefined;\n if (this.plan.kind !== \"error\") {\n const compare = this.getComparator();\n this.members = new Set(readable ? this.collection.store.keys().filter((key) => this.isMember(key)) : []);\n this.sorted = [...this.members].toSorted(compare);\n }\n if (this.isActive()) {\n this.syncJoins();\n }\n this.emit();\n };\n\n private attach = () => {\n const { plan, collection } = this;\n if (plan.kind === \"one\") {\n if (plan.loaderIndex !== undefined) {\n this.keySubset = collection.getKeySubset(collection.resolveKey(plan.key), plan.loaderIndex);\n this.keySubset.attach(this);\n if (!collection.store.get(collection.resolveKey(plan.key)) || !this.keySubset.isFresh()) {\n this.keySubset.revalidate();\n }\n }\n } else if (plan.kind === \"list\") {\n const container = collection.findContainingSubset(plan);\n this.answeredLocally = Boolean(container && container.id !== plan.subsetId);\n this.source = this.answeredLocally ? container : collection.getListSubset(plan, this.definition);\n this.source!.attach(this);\n if (!this.answeredLocally) {\n this.source!.revalidate();\n }\n }\n this.rebuild();\n };\n\n private detach = () => {\n this.collection.db.releaseLater(this);\n this.source?.detach(this);\n this.keySubset?.detach(this);\n this.joinSubsets.forEach((subset) => subset.detach(this));\n this.joinSubsets.clear();\n this.joinQueries.forEach((entry) => entry.unsubscribe());\n this.joinQueries.clear();\n this.source = undefined;\n this.keySubset = undefined;\n this.answeredLocally = false;\n this.members.clear();\n this.sorted = [];\n this.selections.clear();\n };\n\n private getComparator = () => this.collection.createComparator(this.definition.orderBy, this.getSource());\n\n private insertSorted = (key: RowKey, compare: (left: RowKey, right: RowKey) => number) => {\n let low = 0;\n let high = this.sorted.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (compare(this.sorted[middle], key) <= 0) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n this.sorted.splice(low, 0, key);\n this.members.add(key);\n };\n\n private isMember = (key: RowKey): boolean => {\n const { plan, collection, definition } = this;\n const row = collection.store.get(key);\n if (!row) {\n return false;\n }\n if (plan.kind === \"one\") {\n return key === collection.resolveKey(plan.key);\n }\n if (definition.where && !evaluate(definition.where, row)) {\n return false;\n }\n if (plan.kind === \"local\") {\n return true;\n }\n const source = this.getSource()!;\n const plannedLoader = collection.config.loaders[(plan as Extract<QueryPlan, { kind: \"list\" }>).loaderIndex];\n const fixed = plannedLoader.fixed ?? {};\n if (!Object.keys(fixed).every((field) => evaluate({ op: \"eq\", field, value: fixed[field] }, row))) {\n return false;\n }\n // Pages and server-only operators hold exactly what the backend returned\n if (source.ownsOnly) {\n return source.holds(key);\n }\n return !source.excluded.has(key);\n };\n\n /** The joined value of a row: the row with that key, or every row whose `on` field holds the value */\n private resolveJoin = (join: JoinDefinition, row: Row) => {\n const value = row[join.field];\n if (!join.on) {\n return this.collection.db.collections.get(join.collection)!.store.get(value as RowKey);\n }\n return this.getChildren(join).get(value) ?? EMPTY_ROWS;\n };\n\n private getChildren = (join: JoinDefinition) => {\n const existing = this.childIndex.get(join.name);\n if (existing) {\n return existing;\n }\n const { store } = this.collection.db.collections.get(join.collection)!;\n const index = new Map<unknown, Row[]>();\n store.keys().forEach((childKey) => {\n const child = store.get(childKey)!;\n const value = child[join.on!];\n index.set(value, [...(index.get(value) ?? []), child]);\n });\n this.childIndex.set(join.name, index);\n return index;\n };\n\n private hasInnerJoins = () => (this.definition.joins ?? []).some((join) => join.type === \"inner\");\n\n /** Whether a row has every row its inner joins need */\n private passesInnerJoins = (key: RowKey) => {\n const row = this.collection.store.get(key)!;\n return (this.definition.joins ?? []).every((join) => {\n if (join.type !== \"inner\") {\n return true;\n }\n const joined = this.resolveJoin(join, row);\n return Array.isArray(joined) ? joined.length > 0 : joined !== undefined;\n });\n };\n\n private select = (key: RowKey) => {\n const row = this.collection.store.get(key)!;\n const joins = this.definition.joins ?? [];\n const joined = joins.map((join) => this.resolveJoin(join, row));\n const cached = this.selections.get(key);\n const sameJoins = Boolean(cached?.joined.every((item, index) => sameJoined(item, joined[index])));\n if (cached && cached.row === row && sameJoins) {\n return cached.value;\n }\n const { select } = this.definition;\n // A change to a field the query does not select keeps the result, so components that read it do not render\n if (\n cached &&\n select &&\n sameJoins &&\n Object.values(select).every((field) => Object.is(cached.row[field], row[field]))\n ) {\n this.selections.set(key, { ...cached, row });\n return cached.value;\n }\n const selected = select\n ? Object.fromEntries(Object.entries(select).map(([output, field]) => [output, row[field]]))\n : row;\n const value =\n joins.length > 0\n ? { ...selected, ...Object.fromEntries(joins.map(({ name }, index) => [name, joined[index]])) }\n : selected;\n this.selections.set(key, { row, joined, value });\n return value;\n };\n\n /** Whether the query reads rows of a collection, its own or a joined one */\n dependsOn = (collection: CollectionRuntime) => {\n return (this.definition.joins ?? []).some((join) => join.collection === collection.name);\n };\n\n /** Rows of a joined collection changed: results that point at them select again */\n onJoinedRowsChanged = () => {\n this.childIndex.clear();\n this.syncJoins();\n this.emit();\n };\n\n /** Attaches the key subsets that load the joined rows of the current result and releases the others */\n private syncJoins = () => {\n const needed = new Map<string, { collection: CollectionRuntime; key: RowKey }>();\n // Local queries never load, so they read the joined rows the db holds\n const joins = this.definition.local ? [] : (this.definition.joins ?? []);\n this.syncChildQueries(joins.filter((join) => join.on));\n joins\n .filter((join) => !join.on)\n .forEach(({ collection: name, field }) => {\n const collection = this.collection.db.collections.get(name)!;\n this.members.forEach((member) => {\n const key = this.collection.store.get(member)![field] as RowKey | null | undefined;\n if (key !== null && key !== undefined) {\n needed.set(`${name}:${String(key)}`, { collection, key });\n }\n });\n });\n this.joinSubsets.forEach((subset, id) => {\n if (!needed.has(id)) {\n subset.detach(this);\n this.joinSubsets.delete(id);\n }\n });\n needed.forEach(({ collection, key }, id) => {\n const loaderIndex = collection.config.loaders.findIndex((loader) => loader.kind !== \"list\");\n if (this.joinSubsets.has(id) || loaderIndex === -1) {\n return;\n }\n const subset = collection.getKeySubset(key, loaderIndex);\n subset.attach(this);\n subset.revalidate();\n this.joinSubsets.set(id, subset);\n });\n };\n\n /**\n * Loads the rows of one-to-many joins: one query of the joined collection for the values of the whole result, when\n * one of its list loaders can send `inArray` on the joined field. Otherwise the join reads the rows the db holds.\n */\n private syncChildQueries = (joins: JoinDefinition[]) => {\n // A query's joins never change, so `detach` releases these queries\n joins.forEach((join) => {\n const values = [\n ...new Set(\n [...this.members]\n .map((member) => this.collection.store.get(member)![join.field])\n .filter((value) => value !== null && value !== undefined),\n ),\n ].toSorted();\n const definition: QueryDefinition = {\n collection: join.collection,\n where: { op: \"inArray\", field: join.on!, value: values },\n orderBy: [],\n local: false,\n };\n const query = this.collection.db.getLiveQuery(definition);\n const current = this.joinQueries.get(join.name);\n if (current?.key === query.key) {\n return;\n }\n current?.unsubscribe();\n this.joinQueries.delete(join.name);\n const sendsValues =\n query.plan.kind === \"list\" && query.plan.sent.some((node) => node.op === \"inArray\" && node.field === join.on);\n if (values.length > 0 && sendsValues) {\n this.joinQueries.set(join.name, { key: query.key, unsubscribe: query.subscribe(() => {}) });\n }\n });\n };\n\n private buildList = () => {\n const { plan, definition } = this;\n const paginated = plan.kind === \"list\" && plan.paginated;\n const included = this.hasInnerJoins() ? this.sorted.filter(this.passesInnerJoins) : this.sorted;\n const keys = definition.limit !== undefined && !paginated ? included.slice(0, definition.limit) : included;\n const items = keys.map((key) => this.select(key));\n [...this.selections.keys()].forEach((key) => {\n if (!this.members.has(key)) {\n this.selections.delete(key);\n }\n });\n return sameItems(this.state.data, items) ? this.state.data : items;\n };\n\n private computeState = (): QueryState<unknown> => {\n const { plan, collection } = this;\n const { db } = collection;\n const base = { error: null as unknown, stale: false, isFetching: false, hasNextPage: false };\n\n if (plan.kind === \"error\") {\n return { ...base, data: undefined, status: \"error\", error: plan.error };\n }\n // While persisted rows are restored, a query has nothing reliable to show, unless a server rendered it: hydrated\n // subsets are loaded, so the first render matches the server's\n if (!db.isReady && !this.getSource()?.hasLoaded && !(plan.kind === \"one\" && this.members.size > 0)) {\n return { ...base, data: undefined, status: \"loading\" };\n }\n if (plan.kind === \"local\") {\n return { ...base, data: this.buildList(), status: \"ready\" };\n }\n if (plan.kind === \"one\") {\n const subset = this.keySubset;\n const key = collection.resolveKey(plan.key);\n const row = this.members.has(key) && this.passesInnerJoins(key) ? this.select(key) : undefined;\n let status: QueryState<unknown>[\"status\"] = \"loading\";\n if (row || !subset || subset.hasLoaded) {\n status = \"ready\";\n } else if (subset.error) {\n status = \"error\";\n }\n return {\n data: row,\n status,\n error: subset?.error ?? null,\n stale: subset ? !subset.isFresh() : false,\n isFetching: subset?.isLoading ?? false,\n hasNextPage: false,\n };\n }\n const source = this.getSource();\n if (!source) {\n return { ...base, data: undefined, status: \"loading\" };\n }\n let status: QueryState<unknown>[\"status\"] = \"loading\";\n if (source.hasLoaded) {\n status = \"ready\";\n } else if (source.error) {\n status = \"error\";\n }\n return {\n data: status === \"ready\" ? this.buildList() : undefined,\n status,\n error: source.error,\n stale: !source.isFresh(),\n isFetching: source.isLoading,\n hasNextPage: plan.paginated && source.hasMore,\n };\n };\n\n /**\n * The subset that serves a list query. Before anything subscribes, such as on a component's first render, it is the\n * loaded subset that would serve it, read without attaching to it or loading it.\n */\n private getSource = () => this.source ?? this.peeked;\n\n private peekSource = () => {\n const { collection, plan } = this;\n if (this.source || plan.kind !== \"list\") {\n return;\n }\n return collection.findContainingSubset(plan) ?? collection.listSubsets.get(plan.subsetId);\n };\n\n private emit = () => {\n const next = this.computeState();\n if (isSameState(this.state, next)) {\n return;\n }\n this.state = next;\n this.listeners.forEach((listener) => {\n // A listener that throws, such as a broken component, is reported and never stops the others\n try {\n listener();\n } catch (error) {\n this.collection.db.emitError({ type: \"subscriber\", error, collection: this.collection.name });\n }\n });\n };\n}\n","import type { LoaderConfig, RowKey } from \"../collection/collection.types\";\nimport type { CollectionRuntime } from \"../db/collection.runtime\";\nimport type { SyncSubscription } from \"../sync/sync\";\n\n/** A query attached to a subset, told when the subset's status or rows change */\nexport type SubsetObserver = { onSubsetChange: () => void };\n\nconst getStaleTime = (loader: LoaderConfig) => loader.request.staleTime;\n\n/** What every loaded subset shares: who uses it, its load status, freshness and garbage collection */\nexport type LoadOptions = {\n /**\n * Whether the load waits for the collection's writes in flight, so its response is never older than them. A write's\n * own `onSuccess: \"refetch\"` does not wait, because the writes queued behind it wait for that refetch.\n */\n waitForWrites?: boolean;\n};\n\nexport abstract class BaseSubset {\n hasLoaded = false;\n isLoading = false;\n error: unknown = null;\n loadedAt = 0;\n /** Set when events may have been missed, so only a load makes the subset fresh again */\n invalidated = false;\n subscriptions: SyncSubscription[] = [];\n protected observers = new Set<SubsetObserver>();\n protected pending: Promise<void> | undefined;\n private gcTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n readonly collection: CollectionRuntime,\n readonly loader: LoaderConfig,\n ) {}\n\n /** Whether a query is attached */\n isUsed = () => this.observers.size > 0;\n\n /** How many queries read the subset */\n get observerCount() {\n return this.observers.size;\n }\n\n attach = (observer: SubsetObserver) => {\n if (this.gcTimer) {\n clearTimeout(this.gcTimer);\n this.gcTimer = undefined;\n }\n this.observers.add(observer);\n if (this.observers.size === 1 && this.subscriptions.length === 0) {\n this.subscriptions = this.collection.subscribeSyncs(this);\n }\n };\n\n detach = (observer: SubsetObserver) => {\n this.observers.delete(observer);\n if (this.observers.size > 0) {\n return;\n }\n this.gcTimer = setTimeout(() => this.dispose(), this.collection.db.gcTime);\n };\n\n /** The values that pick a sync's subscription for the subset, by field */\n abstract getEqValues: () => Record<string, unknown>;\n\n /**\n * Moves the subset to the sync subscriptions its values pick now, for example when the row a key subset holds moved\n * to another team, and leaves the ones it no longer needs.\n */\n refreshSyncs = () => {\n if (!this.isUsed()) {\n return;\n }\n const next = this.collection.subscribeSyncs(this);\n this.subscriptions.filter((subscription) => !next.includes(subscription)).forEach((item) => item.removeUser(this));\n this.subscriptions = next;\n };\n\n /** Stops the garbage collection timer, for `destroy` */\n cancelGc = () => {\n clearTimeout(this.gcTimer);\n this.gcTimer = undefined;\n };\n\n /** Releases the subset: stops its syncs and removes the rows nothing else holds */\n dispose = () => {\n this.gcTimer = undefined;\n this.subscriptions.forEach((subscription) => subscription.removeUser(this));\n this.subscriptions = [];\n this.collection.removeSubset(this);\n };\n\n /** Whether syncs deliver every insert, update and delete for the subset */\n isLive = (): boolean => {\n const types = new Set(\n this.subscriptions.filter((subscription) => subscription.isLive()).map((item) => item.sync.type),\n );\n return types.has(\"changes\") || (types.has(\"insert\") && types.has(\"update\") && types.has(\"delete\"));\n };\n\n isFresh = (): boolean => {\n if (!this.hasLoaded || this.invalidated) {\n return false;\n }\n if (this.isLive()) {\n return true;\n }\n return this.loadedAt > 0 && Date.now() - this.loadedAt < getStaleTime(this.loader);\n };\n\n /** Marks the subset stale, for example after a reconnect that may have missed events */\n invalidate = () => {\n this.invalidated = true;\n this.notify();\n };\n\n notify = () => {\n this.observers.forEach((observer) => observer.onSubsetChange());\n };\n\n /** Whether the load in flight loads the whole subset, rather than its next page */\n protected pendingIsFull = true;\n\n /** Loads the subset unless a load of the whole subset is in flight. One asked during a next page runs after it. */\n load = (options: LoadOptions = {}): Promise<void> => {\n if (this.pending && !this.pendingIsFull) {\n return this.pending.then(() => this.load(options));\n }\n if (!this.pending) {\n this.pendingIsFull = true;\n const pending: Promise<void> = this.run(options).finally(() => {\n // A next page may have started meanwhile, and it is the load in flight now\n if (this.pending === pending) {\n this.pending = undefined;\n }\n });\n this.pending = pending;\n }\n return this.pending;\n };\n\n /** Loads again after the load in flight, so the result is newer than anything sent before */\n reload = async (options: LoadOptions = {}): Promise<void> => {\n await this.pending;\n return this.load(options);\n };\n\n /** Refetches when the subset is stale and no load is in flight */\n revalidate = () => {\n if (!this.isLoading && !this.isFresh()) {\n this.load();\n }\n };\n\n abstract holds: (key: RowKey) => boolean;\n\n protected abstract run: (options: LoadOptions) => Promise<void>;\n\n protected beginLoad = () => {\n this.isLoading = true;\n this.subscriptions.forEach((subscription) => subscription.beginLoad(this));\n this.notify();\n };\n\n protected endLoad = () => {\n this.isLoading = false;\n this.subscriptions.forEach((subscription) => subscription.endLoad(this));\n };\n}\n","import type { AnyRequestPatch, LoaderConfig, RowKey } from \"../collection/collection.types\";\nimport type { CollectionRuntime } from \"../db/collection.runtime\";\nimport { evaluate } from \"../operators/operators.utils\";\nimport type { ListPlan } from \"../query/planner\";\nimport { getOrderMapping, getWhereMapping } from \"../query/planner\";\nimport type { QueryDefinition } from \"../query/query.types\";\nimport type { Row } from \"../store/store.types\";\nimport { applyRequestPatches } from \"../utils/request.utils\";\nimport type { LoadOptions } from \"./base-subset\";\nimport { BaseSubset } from \"./base-subset\";\n\n/**\n * The rows one list loader returned for one set of sent conditions, order and range. It owns those rows until it is\n * released, and records which rows a refetch no longer returned.\n */\nexport class ListSubset extends BaseSubset {\n owned = new Set<RowKey>();\n /** Rows that inserts added inside a paginated subset's range */\n inserted = new Set<RowKey>();\n /** Rows a refetch no longer returned, which another subset still holds */\n excluded = new Set<RowKey>();\n orderIndex = new Map<RowKey, number>();\n cursor: unknown = undefined;\n hasMore = false;\n /** How many pages a paginated subset has loaded, so a refetch reloads all of them */\n pages = 0;\n\n readonly listLoader: LoaderConfig;\n readonly plan: ListPlan;\n readonly definition: Pick<QueryDefinition, \"orderBy\" | \"limit\">;\n\n constructor(\n collection: CollectionRuntime,\n options: { loader: LoaderConfig; plan: ListPlan; definition: Pick<QueryDefinition, \"orderBy\" | \"limit\"> },\n ) {\n super(collection, options.loader);\n this.listLoader = options.loader;\n this.plan = options.plan;\n this.definition = options.definition;\n }\n\n get id() {\n return this.plan.subsetId;\n }\n\n /** The values of the subset's sent `eq` conditions, which syncs use to pick their subscription */\n getEqValues = (): Record<string, unknown> => {\n return Object.fromEntries(\n this.plan.sent.filter((node) => node.op === \"eq\").map((node) => [node.field, node.value]),\n );\n };\n\n /** Whether a row matches what the backend was asked for, including the loader's fixed filters */\n matchesSent = (row: Row) => {\n const fixed = this.listLoader.fixed ?? {};\n const fixedMatch = Object.keys(fixed).every((field) => evaluate({ op: \"eq\", field, value: fixed[field] }, row));\n return fixedMatch && this.plan.sent.every((node) => evaluate(node, row));\n };\n\n /** Whether the backend decides membership alone: pages, or a server-only operator the client cannot evaluate */\n get ownsOnly() {\n return this.plan.paginated || this.plan.sent.some((node) => node.op === \"server\");\n }\n\n holds = (key: RowKey) => {\n if (this.ownsOnly) {\n return this.owned.has(key) || this.inserted.has(key);\n }\n if (this.excluded.has(key)) {\n return false;\n }\n const row = this.collection.store.getServerRow(key);\n return this.owned.has(key) || Boolean(row && this.matchesSent(row));\n };\n\n /** Adds an inserted row to a paginated subset when it sorts inside the loaded range */\n noteInsert = (key: RowKey) => {\n this.excluded.delete(key);\n if (!this.plan.paginated) {\n // A new row may match a server-only operator, which only a refetch can tell\n if (this.ownsOnly && this.hasLoaded) {\n this.invalidate();\n }\n return;\n }\n const row = this.collection.store.get(key);\n if (!row || !this.matchesSent(row)) {\n return;\n }\n if (!this.hasMore) {\n this.inserted.add(key);\n return;\n }\n const compare = this.collection.createComparator(this.definition.orderBy, this);\n const last = [...this.owned].toSorted(compare).pop();\n if (last !== undefined && compare(key, last) < 0) {\n this.inserted.add(key);\n }\n };\n\n /** Loads the page after the last loaded one */\n loadNext = (): Promise<void> => {\n if (!this.hasMore || this.isLoading) {\n return this.pending ?? Promise.resolve();\n }\n this.pendingIsFull = false;\n const pending: Promise<void> = this.loadPages(false).finally(() => {\n if (this.pending === pending) {\n this.pending = undefined;\n }\n });\n this.pending = pending;\n return pending;\n };\n\n protected run = (options: LoadOptions) => this.loadPages(true, options.waitForWrites !== false);\n\n private buildRequest = (cursor: { value: unknown } | undefined) => {\n const loader = this.listLoader;\n const { notation } = this.collection.db;\n // The planner only sends conditions and orders that have a mapping\n const patches: AnyRequestPatch[] = this.plan.sent.map((node) =>\n getWhereMapping(loader, node, notation)!(node.value),\n );\n if (this.plan.sendOrder) {\n this.definition.orderBy.forEach(({ field, direction }) => {\n patches.push(getOrderMapping(loader, field, notation)!(direction));\n });\n }\n if (this.plan.sendLimit) {\n patches.push(loader.limit!(this.definition.limit!));\n }\n if (cursor && loader.page) {\n patches.push(loader.page(cursor.value));\n }\n return applyRequestPatches(loader.request.setCache(false), patches);\n };\n\n /**\n * Loads from the first page, or the page after the last loaded one. A paginated subset is a prefix of its result, so\n * loading from the first page reloads every page loaded so far, in order, and then releases the rows none of them\n * returned. The rows stay until the last page is back, so the list does not jump while it reloads.\n */\n private loadPages = async (fromStart: boolean, waitForWrites = true) => {\n const { db } = this.collection;\n const { generation } = db;\n this.beginLoad();\n const timeout = this.startNetworkTimeout();\n const returned: RowKey[] = fromStart ? [] : [...this.orderIndex.keys()];\n let loadSeq = 0;\n let result: Awaited<ReturnType<typeof this.fetchPages>>;\n try {\n await db.ready;\n if (waitForWrites) {\n await this.collection.mutationsSettled();\n }\n // Rows written after this point are newer than what the load can return, so a reload never releases them\n loadSeq = db.tick();\n result = await this.fetchPages({\n cursor: fromStart ? undefined : { value: this.cursor },\n remaining: fromStart ? Math.max(1, this.pages) : 1,\n returned,\n timeout,\n generation,\n });\n } catch (error) {\n // A mapping that throws, such as `rows` on an unexpected response, fails the load instead of leaving it pending\n clearTimeout(timeout);\n result = { success: false, error };\n db.emitError({ type: \"load\", error, collection: this.collection.name });\n }\n // After `clear`, the response belongs to the previous user\n if (db.generation !== generation) {\n db.batch(() => {\n this.endLoad();\n this.collection.markSubsetChanged(this);\n });\n return;\n }\n if (!result.success) {\n // Read before the callback: TypeScript before 5.4 drops the narrowing of a `let` inside closures\n const { error } = result;\n db.batch(() => {\n this.error = error;\n this.endLoad();\n this.collection.markSubsetChanged(this);\n });\n return;\n }\n const { cursor, loaded } = result;\n db.batch(() => {\n if (fromStart) {\n this.release(returned, loadSeq);\n }\n this.orderIndex.clear();\n returned.forEach((key, index) => this.orderIndex.set(key, index));\n this.cursor = cursor;\n this.hasMore = cursor !== undefined && cursor !== null;\n this.pages = (fromStart ? 0 : this.pages) + loaded;\n this.hasLoaded = true;\n this.loadedAt = Date.now();\n this.invalidated = false;\n this.error = null;\n this.endLoad();\n this.collection.markSubsetChanged(this);\n });\n };\n\n /** Loads pages one after another, each with the cursor the previous one returned, until `remaining` are loaded */\n private fetchPages = async (options: {\n cursor: { value: unknown } | undefined;\n remaining: number;\n returned: RowKey[];\n timeout: ReturnType<typeof setTimeout> | undefined;\n generation: number;\n }): Promise<{ success: true; cursor: unknown; loaded: number } | { success: false; error: unknown }> => {\n const result = await this.fetchPage(options.cursor, options.returned, options.generation);\n clearTimeout(options.timeout);\n if (!result.success) {\n return result;\n }\n const more = result.next !== undefined && result.next !== null;\n if (!more || options.remaining <= 1) {\n return { success: true, cursor: result.next, loaded: 1 };\n }\n const rest = await this.fetchPages({\n ...options,\n cursor: { value: result.next },\n remaining: options.remaining - 1,\n });\n return rest.success ? { ...rest, loaded: rest.loaded + 1 } : rest;\n };\n\n /** Sends one page's request and writes its rows, adding their keys to `returned` in order */\n private fetchPage = async (\n cursor: { value: unknown } | undefined,\n returned: RowKey[],\n generation: number,\n ): Promise<{ success: true; next: unknown } | { success: false; error: unknown }> => {\n const { db } = this.collection;\n const seq = db.tick();\n const wall = Date.now();\n db.trackRequest(seq);\n try {\n const response = await this.buildRequest(cursor).send();\n if (!response.success) {\n return { success: false, error: response.error ?? response };\n }\n const items = this.collection.readItems(this.listLoader, response.data);\n const next = this.listLoader.cursor?.(response.data);\n const rows = await this.collection.prepareServerRows(items);\n if (db.generation !== generation) {\n return { success: false, error: new Error(\"Cleared\") };\n }\n db.batch(() => {\n const keys = this.collection.writeServerRows(rows, true, { kind: \"sent\", seq, wall });\n keys.forEach((key) => {\n this.owned.add(key);\n this.excluded.delete(key);\n if (!this.orderIndex.has(key)) {\n this.orderIndex.set(key, this.orderIndex.size);\n }\n });\n returned.push(...keys);\n this.collection.markSubsetChanged(this);\n });\n return { success: true, next };\n } finally {\n db.settleRequest(seq);\n }\n };\n\n /**\n * Releases rows a complete reload no longer returned: rows it owned, rows inserts had added to its pages, and rows\n * nothing else holds that match what it sent, such as a confirmed insert someone else deleted since. The server\n * answered for its conditions, so such a row is not in them.\n */\n private release = (returned: RowKey[], loadSeq: number) => {\n const returnedKeys = new Set(returned);\n const { store } = this.collection;\n // A row written after the load was sent, by a write, an event or another response, is newer than the load knows\n const isNewer = (key: RowKey) => store.getLastSeq(key) > loadSeq;\n this.inserted.forEach((key) => {\n this.inserted.delete(key);\n if (!returnedKeys.has(key)) {\n this.owned.add(key);\n }\n });\n if (!this.ownsOnly) {\n // Rows another subset or a pending write holds still show, as every matching row the db holds does\n this.collection.store.getServerKeys().forEach((key) => {\n const row = this.collection.store.getServerRow(key)!;\n const unheld = !this.collection.isHeldByOthers(key, this);\n if (!returnedKeys.has(key) && !isNewer(key) && this.matchesSent(row) && unheld) {\n this.collection.store.drop(key);\n }\n });\n }\n this.owned.forEach((key) => {\n if (returnedKeys.has(key) || isNewer(key)) {\n return;\n }\n this.owned.delete(key);\n if (this.collection.isHeldByOthers(key, this)) {\n this.excluded.add(key);\n } else {\n this.collection.store.drop(key);\n }\n });\n };\n\n /** With persistence, a subset that restored no rows shows an empty result once the network took too long */\n private startNetworkTimeout = () => {\n const { persistence } = this.collection.db;\n if (!persistence || this.hasLoaded) {\n return;\n }\n return setTimeout(() => {\n if (this.hasLoaded) {\n return;\n }\n this.hasLoaded = true;\n this.loadedAt = 0;\n this.invalidated = true;\n this.notify();\n }, persistence.networkTimeout);\n };\n}\n","import type { RowKey } from \"../collection/collection.types\";\nimport { compareValues, isEqualValue } from \"../operators/operators.utils\";\nimport type { FieldMeta, Layer, Row, Stamp } from \"./store.types\";\n\n/**\n * Holds one collection's rows. Server rows and optimistic layers are kept apart: queries read the server row with\n * every pending layer applied on top, and dropping a layer reverts exactly what it changed.\n *\n * Writes are ordered per field. A field keeps its value when the write is older than the one that set it: an older\n * `version`, or a response to a request sent before the field was written.\n */\nexport class Store {\n private rows = new Map<RowKey, Row>();\n private meta = new Map<RowKey, Map<string, FieldMeta>>();\n private tombstones = new Map<RowKey, { seq: number; wall: number }>();\n private layers: Layer[] = [];\n private visible = new Map<RowKey, Row | undefined>();\n private arrival = new Map<RowKey, number>();\n private arrivalCounter = 0;\n /** Stores of linked collections, which hold some of this store's fields for the same keys */\n private links: Store[] = [];\n\n constructor(\n private readonly options: {\n keyField: string;\n versionField?: string;\n onChange: (key: RowKey) => void;\n },\n ) {}\n\n /** Whether the server state holds the row */\n hasServerRow = (key: RowKey) => this.rows.has(key);\n\n /** The pending optimistic layers, oldest first */\n getLayers = (): readonly Layer[] => this.layers;\n\n /** The server row, without optimistic layers */\n getServerRow = (key: RowKey) => this.rows.get(key);\n\n /** The newest `seq` that wrote any field of a server row, or 0 */\n getLastSeq = (key: RowKey): number => {\n const fields = this.meta.get(key);\n return fields ? Math.max(0, ...[...fields.values()].map((meta) => meta.seq)) : 0;\n };\n\n /** Every key with a server row */\n getServerKeys = () => [...this.rows.keys()];\n\n /** The row as queries see it: the server row with every pending layer applied */\n get = (key: RowKey): Row | undefined => {\n if (this.visible.has(key)) {\n return this.visible.get(key);\n }\n let row = this.rows.get(key);\n for (const layer of this.layers) {\n if (layer.key !== key) {\n continue;\n }\n if (layer.type === \"insert\") {\n row = { ...layer.values };\n } else if (layer.type === \"update\") {\n row = row ? { ...row, ...layer.values } : undefined;\n } else {\n row = undefined;\n }\n }\n const visible = row && row !== this.rows.get(key) ? Object.freeze(row) : row;\n this.visible.set(key, visible);\n return visible;\n };\n\n /** Every key queries can see */\n keys = (): RowKey[] => {\n const keys = new Set<RowKey>(this.rows.keys());\n this.layers.forEach((layer) => keys.add(layer.key));\n return [...keys].filter((key) => this.get(key) !== undefined);\n };\n\n /** The order in which the db first saw a row, used when a query has no `orderBy` */\n getArrival = (key: RowKey) => this.arrival.get(key)!;\n\n /** Whether a pending write touches the row */\n hasLayer = (key: RowKey) => this.layers.some((layer) => layer.key === key);\n\n /**\n * Writes server fields. A complete write creates the row or replaces its fields, a partial write changes only the\n * fields it carries and is ignored for a row the store does not hold. Returns whether the row changed.\n */\n /** Links another store: writes, deletes and layers on one change the fields the other has, for the same key */\n link = (store: Store) => {\n this.links.push(store);\n };\n\n write = (\n key: RowKey,\n written: Row,\n { complete, stamp, linked = true }: { complete: boolean; stamp: Stamp; linked?: boolean },\n ): boolean => {\n // `undefined` is not a value: an update leaves the field as it is, and a complete row leaves it out, which drops it\n const values = Object.fromEntries(Object.entries(written).filter(([, value]) => value !== undefined));\n const tombstone = this.tombstones.get(key);\n if (tombstone) {\n if (stamp.seq < tombstone.seq) {\n return false;\n }\n this.tombstones.delete(key);\n }\n\n const current = this.rows.get(key);\n if (!current && !complete) {\n return false;\n }\n\n const fieldsMeta = this.meta.get(key) ?? new Map<string, FieldMeta>();\n const { versionField } = this.options;\n const incomingVersion = versionField ? values[versionField] : undefined;\n const hasVersion = incomingVersion !== undefined;\n const next: Row = current ? { ...current } : {};\n const accepted: Row = {};\n let changed = !current;\n\n Object.keys(values).forEach((field) => {\n const meta = fieldsMeta.get(field);\n if (!this.accepts(meta, stamp, hasVersion ? incomingVersion : undefined)) {\n return;\n }\n fieldsMeta.set(field, {\n seq: stamp.seq,\n wall: stamp.wall,\n version: hasVersion ? incomingVersion : meta?.version,\n });\n accepted[field] = values[field];\n if (!current || !isEqualValue(current[field], values[field])) {\n next[field] = values[field];\n changed = true;\n }\n });\n\n // A complete row replaces the stored one, so a field it leaves out is gone, unless a newer write set it\n if (complete && current) {\n Object.keys(current).forEach((field) => {\n if (field in values || !this.accepts(fieldsMeta.get(field), stamp, hasVersion ? incomingVersion : undefined)) {\n return;\n }\n fieldsMeta.set(field, { seq: stamp.seq, wall: stamp.wall, version: hasVersion ? incomingVersion : undefined });\n delete next[field];\n changed = true;\n });\n }\n\n this.meta.set(key, fieldsMeta);\n if (!this.arrival.has(key)) {\n this.arrivalCounter += 1;\n this.arrival.set(key, this.arrivalCounter);\n }\n if (changed) {\n // Rows are shared with every query and component, so changing one in place must fail rather than corrupt them\n this.rows.set(key, Object.freeze(next));\n this.invalidate(key);\n }\n if (linked) {\n this.links.forEach((store) => store.mirrorWrite(key, accepted, stamp));\n }\n return changed;\n };\n\n /** Removes a row the server deleted, and remembers the key so an older response cannot bring it back */\n remove = (key: RowKey, stamp: Stamp, linked = true): boolean => {\n // The newest delete wins, so an older \"not found\" never lets a response sent before a newer delete bring it back\n const tombstone = this.tombstones.get(key);\n if (!tombstone || tombstone.seq < stamp.seq) {\n this.tombstones.set(key, { seq: stamp.seq, wall: stamp.wall });\n }\n if (linked) {\n this.links.forEach((store) => store.remove(key, stamp, false));\n }\n // A row written after the delete, such as an insert event after an older \"not found\", stays\n if (this.getLastSeq(key) > stamp.seq) {\n return false;\n }\n return this.drop(key);\n };\n\n /** Removes a row without remembering it, for rows no subset holds any more */\n drop = (key: RowKey): boolean => {\n if (!this.rows.has(key)) {\n return false;\n }\n this.rows.delete(key);\n this.meta.delete(key);\n this.invalidate(key);\n return true;\n };\n\n /** Forgets deleted keys once every request sent before the delete has settled */\n forgetTombstones = (oldestPendingSeq: number) => {\n this.tombstones.forEach((tombstone, key) => {\n if (tombstone.seq < oldestPendingSeq) {\n this.tombstones.delete(key);\n }\n });\n };\n\n addLayer = (layer: Layer, linked = true) => {\n if (linked) {\n this.links.forEach((store) => store.mirrorLayer(layer));\n }\n this.layers.push(layer);\n if (!this.arrival.has(layer.key)) {\n this.arrivalCounter += 1;\n this.arrival.set(layer.key, this.arrivalCounter);\n }\n this.invalidate(layer.key);\n };\n\n removeLayer = (id: string, linked = true) => {\n if (linked) {\n this.links.forEach((store) => store.removeLayer(`${id}@link`, false));\n }\n const layer = this.layers.find((item) => item.id === id);\n if (!layer) {\n return;\n }\n this.layers = this.layers.filter((item) => item.id !== id);\n this.invalidate(layer.key);\n };\n\n /** Moves the pending layers of a temporary key to the key the server assigned */\n rekeyLayers = (from: RowKey, to: RowKey) => {\n // The row keeps its place in lists without an order, when it had one\n if (this.arrival.has(from)) {\n this.arrival.set(to, this.arrival.get(from)!);\n }\n this.layers = this.layers.map((layer) => {\n if (layer.key !== from) {\n return layer;\n }\n return { ...layer, key: to, values: { ...layer.values, [this.options.keyField]: to } };\n });\n this.invalidate(from);\n this.invalidate(to);\n };\n\n /** Removes every row, layer and tombstone */\n clear = () => {\n const keys = new Set<RowKey>([...this.rows.keys(), ...this.layers.map((layer) => layer.key)]);\n this.rows.clear();\n this.meta.clear();\n this.tombstones.clear();\n this.layers = [];\n keys.forEach((key) => this.invalidate(key));\n };\n\n /** The fields a linked store wrote, limited to the fields this store's row has. Rows it does not hold stay away. */\n /** The fields of a row this store also has, by its server row, which a pending delete layer does not hide */\n private pickLinked = (key: RowKey, values: Row): Row | undefined => {\n const row = this.rows.get(key) ?? this.get(key);\n if (!row) {\n return undefined;\n }\n return Object.fromEntries(Object.entries(values).filter(([field]) => field in row));\n };\n\n private mirrorWrite = (key: RowKey, values: Row, stamp: Stamp) => {\n if (!this.rows.has(key)) {\n return;\n }\n this.write(key, this.pickLinked(key, values)!, { complete: false, stamp, linked: false });\n };\n\n /** Mirrors an update or delete layer. An insert cannot make a complete row of another shape, so it stays away. */\n private mirrorLayer = (layer: Layer) => {\n const values = this.pickLinked(layer.key, layer.values);\n if (!values || layer.type === \"insert\") {\n return;\n }\n this.addLayer({ ...layer, id: `${layer.id}@link`, values }, false);\n };\n\n private accepts = (meta: FieldMeta | undefined, stamp: Stamp, version: unknown): boolean => {\n if (version !== undefined) {\n if (meta?.version === undefined) {\n return true;\n }\n const order = compareValues(meta.version, version);\n // An equal version says nothing about which write is newer, so the one made later wins\n return order < 0 || (order === 0 && meta.seq <= stamp.seq);\n }\n // Events count from when they arrived, so one applied late, after a buffer, never beats a newer write\n if (!meta) {\n return true;\n }\n return meta.seq < stamp.seq;\n };\n\n private invalidate = (key: RowKey) => {\n this.visible.delete(key);\n this.options.onChange(key);\n };\n}\n","import type { LoaderConfig, RowKey } from \"../collection/collection.types\";\nimport type { CollectionRuntime } from \"../db/collection.runtime\";\nimport type { Stamp } from \"../store/store.types\";\nimport type { LoadOptions } from \"./base-subset\";\nimport { BaseSubset } from \"./base-subset\";\n\n/** One row read by key, for `findOne`. Keys read in the same tick are batched when the loader has `byKeys`. */\nexport class KeySubset extends BaseSubset {\n constructor(\n collection: CollectionRuntime,\n loader: LoaderConfig,\n readonly key: RowKey,\n ) {\n super(collection, loader);\n }\n\n holds = (key: RowKey) => key === this.key;\n\n /** The fields of the row the server sent, so syncs scoped by those fields keep it live */\n getEqValues = (): Record<string, unknown> => this.collection.store.getServerRow(this.key) ?? {};\n\n /** Called by the collection when the batched request for this key settled */\n complete = (result: { success: true; found: boolean; stamp: Stamp } | { success: false; error: unknown }) => {\n if (result.success) {\n // The server answered for this key, so a row it did not return is gone, and older events cannot bring it back\n if (!result.found) {\n this.collection.store.remove(this.key, result.stamp);\n }\n this.hasLoaded = true;\n this.loadedAt = Date.now();\n this.invalidated = false;\n this.error = null;\n } else {\n this.error = result.error;\n }\n this.endLoad();\n this.collection.markSubsetChanged(this);\n };\n\n protected run = async (options: LoadOptions) => {\n this.beginLoad();\n await this.collection.loadKey(this, options.waitForWrites !== false);\n };\n}\n","import type { ListenerInstance } from \"@hyper-fetch/sockets\";\n\nimport type { SyncConfig } from \"../collection/collection.types\";\nimport type { Stamp } from \"../store/store.types\";\n\nexport type SyncHost = {\n tick: () => number;\n applySyncMessage: (sync: SyncConfig, message: unknown, stamp: Stamp) => void;\n onLiveChange: () => void;\n onRemove: (subscription: SyncSubscription) => void;\n};\n\n/**\n * One server-side subscription of a sync, for one set of filter values. Subsets that need the same subscription\n * share it, and it stops when the last one releases it.\n *\n * While a subset that uses it is loading, events are buffered and applied after the response, so an `update` for a row\n * that only the response brings is not lost.\n */\nexport class SyncSubscription {\n started = false;\n private users = new Set<object>();\n private loading = new Set<object>();\n private buffer: { message: unknown; stamp: Stamp }[] = [];\n private unsubscribe: (() => void) | undefined;\n\n readonly id: string;\n readonly sync: SyncConfig;\n readonly listener: ListenerInstance;\n private readonly host: SyncHost;\n\n constructor(options: { id: string; sync: SyncConfig; listener: ListenerInstance; host: SyncHost }) {\n this.id = options.id;\n this.sync = options.sync;\n this.listener = options.listener;\n this.host = options.host;\n }\n\n /** Whether the server has started the subscription and the socket is connected */\n isLive = () => this.started && this.listener.socket.adapter.connected;\n\n addUser = (user: object) => {\n this.users.add(user);\n if (this.unsubscribe) {\n return;\n }\n // A `changes` sync reads the whole event, such as a Firestore snapshot with its grouped changes\n const toMessage = (event: { data: unknown }) => (this.sync.type === \"changes\" ? event : event.data);\n this.unsubscribe = this.listener.listen((event: { data: unknown }) => this.receive(toMessage(event)), {\n onStart: () => {\n this.started = true;\n this.host.onLiveChange();\n },\n onEnd: () => {\n this.started = false;\n this.unsubscribe = undefined;\n this.host.onLiveChange();\n },\n });\n };\n\n removeUser = (user: object) => {\n this.users.delete(user);\n this.endLoad(user);\n if (this.users.size > 0) {\n return;\n }\n this.unsubscribe?.();\n this.unsubscribe = undefined;\n this.started = false;\n this.host.onRemove(this);\n };\n\n getUsers = () => [...this.users];\n\n beginLoad = (user: object) => {\n this.loading.add(user);\n };\n\n endLoad = (user: object) => {\n this.loading.delete(user);\n if (this.loading.size > 0) {\n return;\n }\n const buffered = this.buffer;\n this.buffer = [];\n buffered.forEach(({ message, stamp }) => this.host.applySyncMessage(this.sync, message, stamp));\n };\n\n private receive = (message: unknown) => {\n const seq = this.host.tick();\n const stamp: Stamp = { kind: \"now\", seq, wall: Date.now() };\n if (this.loading.size > 0) {\n this.buffer.push({ message, stamp });\n return;\n }\n this.host.applySyncMessage(this.sync, message, stamp);\n };\n}\n","import type { RequestInstance } from \"@hyper-fetch/core\";\n\nimport type {\n CollectionConfig,\n IngestConfig,\n ListenerPatch,\n LoaderConfig,\n RowKey,\n SortDirection,\n SyncConfig,\n} from \"../collection/collection.types\";\nimport type { ComparisonNode } from \"../operators/operators.types\";\nimport { compareValues, stableStringify } from \"../operators/operators.utils\";\nimport type { ListPlan } from \"../query/planner\";\nimport type { QueryDefinition } from \"../query/query.types\";\nimport { Store } from \"../store/store\";\nimport type { Row, Stamp } from \"../store/store.types\";\nimport type { BaseSubset } from \"../subset/base-subset\";\nimport { KeySubset } from \"../subset/key-subset\";\nimport { ListSubset } from \"../subset/list-subset\";\nimport { SyncSubscription } from \"../sync/sync\";\nimport { applyListenerPatches, applyRequestPatches, isPlainObject } from \"../utils/request.utils\";\nimport type { DbRuntime } from \"./db.runtime\";\n\ntype KeyRequest = { subset: KeySubset; resolve: () => void; waitForWrites: boolean };\n\n/** Everything the db keeps for one collection: its rows, loaded subsets, sync subscriptions and ingested requests */\nexport class CollectionRuntime {\n readonly store: Store;\n readonly listSubsets = new Map<string, ListSubset>();\n readonly keySubsets = new Map<RowKey, KeySubset>();\n readonly subscriptions = new Map<string, SyncSubscription>();\n /** Server keys that replaced temporary keys of inserts */\n readonly aliases = new Map<RowKey, RowKey>();\n private renderKeys = new Map<RowKey, string>();\n private keyRequests: KeyRequest[] = [];\n private cleanups: (() => void)[] = [];\n\n constructor(\n readonly db: DbRuntime,\n readonly name: string,\n readonly config: CollectionConfig,\n ) {\n this.store = new Store({\n keyField: config.key,\n versionField: config.version,\n onChange: (key) => db.markRowChanged(this, key),\n });\n config.ingests.forEach((ingest) => this.listenToIngest(ingest));\n }\n\n /** The stable key for rendering a row, which survives swapping a temporary key for the server's */\n getRenderKey = (key: RowKey): string => this.renderKeys.get(key) ?? String(key);\n\n setRenderKey = (key: RowKey, renderKey: string) => {\n this.renderKeys.set(key, renderKey);\n };\n\n /** Resolves a temporary insert key to the key the server assigned, when it has */\n resolveKey = (key: RowKey): RowKey => this.aliases.get(key) ?? key;\n\n getListSubset = (plan: ListPlan, definition: QueryDefinition): ListSubset => {\n const existing = this.listSubsets.get(plan.subsetId);\n if (existing) {\n return existing;\n }\n const loader = this.config.loaders[plan.loaderIndex];\n const subset = new ListSubset(this, {\n loader,\n plan,\n definition: { orderBy: definition.orderBy, limit: definition.limit },\n });\n this.listSubsets.set(plan.subsetId, subset);\n return subset;\n };\n\n getKeySubset = (key: RowKey, loaderIndex: number): KeySubset => {\n const existing = this.keySubsets.get(key);\n if (existing) {\n return existing;\n }\n const subset = new KeySubset(this, this.config.loaders[loaderIndex], key);\n this.keySubsets.set(key, subset);\n return subset;\n };\n\n /**\n * Finds a fresh subset whose rows contain every row a query can return, so the query is answered locally. The\n * subset must not be paginated, its sent conditions must all be part of the query's, and its loader's fixed filters\n * must be part of the query loader's.\n */\n findContainingSubset = (plan: ListPlan): ListSubset | undefined => {\n if (plan.paginated || plan.serverOnly) {\n return undefined;\n }\n const queryLoader = this.config.loaders[plan.loaderIndex];\n const sent = new Set(plan.sent.map((node) => stableStringify(node)));\n return [...this.listSubsets.values()].find((subset) => {\n // A subset of a server-only operator holds what the server matched, which says nothing about other queries\n if (subset.plan.paginated || subset.plan.serverOnly || !subset.isFresh()) {\n return false;\n }\n const fixed = subset.listLoader.fixed ?? {};\n const fixedContained = Object.keys(fixed).every(\n (field) => stableStringify(queryLoader.fixed?.[field]) === stableStringify(fixed[field]),\n );\n return fixedContained && subset.plan.sent.every((node) => sent.has(stableStringify(node)));\n });\n };\n\n removeSubset = (subset: BaseSubset) => {\n if (subset instanceof ListSubset) {\n this.listSubsets.delete(subset.id);\n } else {\n this.keySubsets.delete((subset as KeySubset).key);\n }\n this.sweep();\n };\n\n /** Every subset, list and key */\n getSubsets = (): BaseSubset[] => [...this.listSubsets.values(), ...this.keySubsets.values()];\n\n /** Whether a subset other than `except`, or a pending write, holds the row */\n isHeldByOthers = (key: RowKey, except?: BaseSubset) => {\n return this.store.hasLayer(key) || this.getSubsets().some((subset) => subset !== except && subset.holds(key));\n };\n\n /** The subsets whose rows include the key, which a refetch after a write reloads */\n getSubsetsHolding = (key: RowKey) => this.getSubsets().filter((subset) => subset.holds(key));\n\n /** Removes rows that no subset and no pending write holds */\n sweep = () => {\n this.db.batch(() => {\n this.store.getServerKeys().forEach((key) => {\n if (!this.isHeldByOthers(key)) {\n this.store.drop(key);\n }\n });\n });\n };\n\n /** Tells the queries of a subset that its rows or status changed */\n markSubsetChanged = (subset: BaseSubset) => {\n subset.notify();\n };\n\n /** Orders keys by the query's orders, then by the order the loader returned, then by arrival and key */\n createComparator = (\n orderBy: readonly { field: string; direction: SortDirection }[],\n source: ListSubset | undefined,\n ) => {\n return (left: RowKey, right: RowKey): number => {\n const leftRow = this.store.get(left);\n const rightRow = this.store.get(right);\n for (const { field, direction } of orderBy) {\n const result = compareValues(leftRow?.[field], rightRow?.[field]);\n if (result !== 0) {\n return direction === \"desc\" ? -result : result;\n }\n }\n if (orderBy.length === 0) {\n const leftIndex = source?.orderIndex.get(left) ?? Number.MAX_SAFE_INTEGER;\n const rightIndex = source?.orderIndex.get(right) ?? Number.MAX_SAFE_INTEGER;\n if (leftIndex !== rightIndex) {\n return leftIndex - rightIndex;\n }\n // Every row the db holds has a distinct arrival, so this settles the order\n return this.store.getArrival(left) - this.store.getArrival(right);\n }\n return compareValues(left, right);\n };\n };\n\n /** Reads the items of a response: the `rows` mapping, or the response itself */\n readItems = (source: Pick<LoaderConfig, \"rows\">, data: unknown): unknown[] => {\n if (source.rows) {\n return [...source.rows(data)];\n }\n return Array.isArray(data) ? data : [data];\n };\n\n /** Validates rows when the collection validates server data */\n prepareServerRows = (items: unknown[]): Row[] | Promise<Row[]> => {\n const mapped = items as Row[];\n const { schema } = this.config;\n if (!schema || this.config.validate !== \"all\") {\n return mapped;\n }\n const results = mapped.map((row) => schema[\"~standard\"].validate(row));\n const collect = (settled: Awaited<(typeof results)[number]>[]) => {\n const rows: Row[] = [];\n settled.forEach((result) => {\n if (result.issues) {\n this.db.emitError({ type: \"validation\", error: result.issues, collection: this.name });\n } else {\n rows.push(result.value as Row);\n }\n });\n return rows;\n };\n if (results.some((result) => result instanceof Promise)) {\n return Promise.all(results).then(collect);\n }\n return collect(results as Awaited<(typeof results)[number]>[]);\n };\n\n /** Writes server rows and returns their keys in order */\n writeServerRows = (rows: Row[], complete: boolean, stamp: Stamp): RowKey[] => {\n return rows.map((row) => {\n const key = row[this.config.key] as RowKey;\n this.store.write(key, row, { complete, stamp });\n if (complete) {\n this.normalize(row, stamp);\n }\n return key;\n });\n };\n\n /** Writes the rows nested in a complete row into the collections that hold them */\n normalize = (row: Row, stamp: Stamp) => {\n (this.config.normalize ?? []).forEach(({ target, extract }) => {\n const collection = this.db.getCollectionByConfig(target)!;\n const rows = collection.prepareServerRows([...extract(row)]);\n const write = (nested: Row[]) => {\n this.db.batch(() => {\n collection.writeServerRows(nested, true, stamp).forEach((key) => collection.noteInsert(key));\n });\n };\n if (rows instanceof Promise) {\n rows.then(write);\n } else {\n write(rows);\n }\n });\n };\n\n /** Rows of this collection were written: key subsets move to the sync subscriptions their rows' values pick */\n refreshKeySyncs = (keys: Iterable<RowKey>) => {\n [...keys].forEach((key) => this.keySubsets.get(key)?.refreshSyncs());\n };\n\n /** Tells paginated subsets about an inserted row, so it can join their loaded range */\n noteInsert = (key: RowKey) => {\n this.listSubsets.forEach((subset) => {\n subset.noteInsert(key);\n });\n };\n\n /** Starts or joins the sync subscriptions that cover a subset */\n subscribeSyncs = (subset: BaseSubset): SyncSubscription[] => {\n const eqValues = subset.getEqValues();\n const subscriptions: SyncSubscription[] = [];\n this.config.syncs.forEach((sync, index) => {\n const target = this.getSyncTarget({ sync, index, subset, eqValues });\n if (!target) {\n return;\n }\n const { id, patches } = target;\n let subscription = this.subscriptions.get(id);\n if (!subscription) {\n const listener = applyListenerPatches(sync.listener, patches);\n subscription = new SyncSubscription({\n id,\n sync,\n listener,\n host: {\n tick: this.db.tick,\n applySyncMessage: this.applySyncMessage,\n onLiveChange: () => this.getSubsets().forEach((item) => item.notify()),\n onRemove: (removed) => this.subscriptions.delete(removed.id),\n },\n });\n this.subscriptions.set(id, subscription);\n this.db.watchSocket(listener.socket);\n }\n subscription.addUser(subset);\n subscriptions.push(subscription);\n });\n return subscriptions;\n };\n\n /**\n * Which subscription of a sync covers a subset, and the listener params it needs.\n *\n * - A sync with `byKey` covers a row read by key with a listener of its own, and with a notation it also covers every\n * list subset with its sent conditions. Without `byKey`, a sync with a notation covers list subsets only, because\n * a listener on the whole collection for one row is wasteful and, on Firestore, billed.\n * - A sync with `where` covers subsets whose values fill every field it declares: the sent `eq` conditions of a list,\n * or the fields of the row a key subset holds, so a post read by key joins its team's subscription.\n */\n private getSyncTarget = ({\n sync,\n index,\n subset,\n eqValues,\n }: {\n sync: SyncConfig;\n index: number;\n subset: BaseSubset;\n eqValues: Record<string, unknown>;\n }): { id: string; patches: ListenerPatch[] } | undefined => {\n if (subset instanceof KeySubset && sync.byKey) {\n return { id: stableStringify([index, \"key\", subset.key]), patches: [sync.byKey(subset.key)] };\n }\n if (sync.notation) {\n if (subset instanceof KeySubset) {\n return undefined;\n }\n // A server-only operator has no notation, and a loader that sends one needs no listener notation either\n const conditions = (subset as ListSubset).plan.sent.filter(\n (node): node is ComparisonNode => node.op !== \"server\",\n );\n return { id: stableStringify([index, conditions]), patches: [sync.notation(conditions)] };\n }\n if (sync.byKey && subset instanceof ListSubset) {\n return undefined;\n }\n const fields = Object.keys(sync.where ?? {});\n if (!fields.every((field) => field in eqValues)) {\n return undefined;\n }\n const values = Object.fromEntries(fields.map((field) => [field, eqValues[field]]));\n return {\n id: stableStringify([index, values]),\n patches: fields.map((field) => sync.where![field].eq(values[field])),\n };\n };\n\n /** Applies a `changes` event: complete rows to write and keys to delete */\n private applyChanges = (sync: SyncConfig, message: unknown, stamp: Stamp) => {\n const { upsert, delete: deleted, refetch = [] } = sync.changes!(message);\n refetch.forEach((key) => this.fetchByKey(key));\n const apply = (rows: Row[]) => {\n this.db.batch(() => {\n rows.forEach((row) => {\n const key = row[this.config.key] as RowKey;\n this.writeServerRows([row], true, stamp);\n this.noteInsert(key);\n this.db.notifySyncWrite(this.name, key);\n });\n deleted.forEach((key) => {\n this.store.remove(key, stamp);\n this.db.notifySyncWrite(this.name, key);\n });\n });\n };\n const rows = this.prepareServerRows([...upsert]);\n if (rows instanceof Promise) {\n rows.then(apply);\n } else {\n apply(rows);\n }\n };\n\n /** Applies one sync event */\n /** Applies a sync event. A mapping that throws on one event is reported, and the next events still apply. */\n applySyncMessage = (sync: SyncConfig, message: unknown, stamp: Stamp) => {\n try {\n this.applySyncEvent(sync, message, stamp);\n } catch (error) {\n this.db.emitError({ type: \"sync\", error, collection: this.name });\n }\n };\n\n private applySyncEvent = (sync: SyncConfig, message: unknown, stamp: Stamp) => {\n const keyField = this.config.key;\n if (sync.type === \"changes\") {\n this.applyChanges(sync, message, stamp);\n return;\n }\n if (sync.type === \"delete\") {\n const key = sync.key ? sync.key(message) : ((message as Row)[keyField] as RowKey);\n this.db.batch(() => {\n this.store.remove(key, stamp);\n this.db.notifySyncWrite(this.name, key);\n });\n return;\n }\n const apply = (rows: Row[]) => {\n this.db.batch(() => {\n rows.forEach((row) => {\n const key = row[keyField] as RowKey;\n if (sync.type === \"insert\") {\n this.writeServerRows([row], true, stamp);\n this.noteInsert(key);\n } else if (this.store.hasServerRow(key)) {\n this.store.write(key, row, { complete: false, stamp });\n this.listSubsets.forEach((subset) => subset.excluded.delete(key));\n } else if (sync.incomplete === \"refetch\") {\n this.fetchByKey(key);\n }\n this.db.notifySyncWrite(this.name, key);\n });\n });\n };\n const rows = this.prepareServerRows([sync.row ? sync.row(message) : message]);\n if (rows instanceof Promise) {\n rows.then(apply);\n } else {\n apply(rows);\n }\n };\n\n /** Loads one row by key without a query, for example for an incomplete sync event */\n fetchByKey = (key: RowKey) => {\n const loaderIndex = this.config.loaders.findIndex((loader) => loader.kind !== \"list\");\n if (loaderIndex === -1) {\n return Promise.resolve();\n }\n const subset = this.getKeySubset(key, loaderIndex);\n const observer = { onSubsetChange: () => {} };\n subset.attach(observer);\n return subset.load().then(() => subset.detach(observer));\n };\n\n /** Loads a key subset's row, batched with the other keys requested in the same tick */\n loadKey = (subset: KeySubset, waitForWrites = true): Promise<void> => {\n return new Promise((resolve) => {\n this.keyRequests.push({ subset, resolve, waitForWrites });\n if (this.keyRequests.length === 1) {\n queueMicrotask(() => this.flushKeyRequests());\n }\n });\n };\n\n /** Resolves once no write of this collection is in flight */\n mutationsSettled = () => this.db.mutations.settled(this.name);\n\n /** Removes every row and resets the loaded subsets, for example on sign-out */\n clear = () => {\n this.store.clear();\n this.listSubsets.forEach((subset) => {\n subset.owned.clear();\n subset.inserted.clear();\n subset.excluded.clear();\n subset.orderIndex.clear();\n subset.pages = 0;\n subset.hasLoaded = false;\n subset.loadedAt = 0;\n });\n this.keySubsets.forEach((subset) => {\n subset.hasLoaded = false;\n subset.loadedAt = 0;\n });\n this.getSubsets().forEach((subset) => subset.notify());\n };\n\n destroy = () => {\n this.cleanups.forEach((cleanup) => cleanup());\n this.cleanups = [];\n this.getSubsets().forEach((subset) => subset.cancelGc());\n this.subscriptions.forEach((subscription) => {\n subscription.getUsers().forEach((user) => subscription.removeUser(user));\n });\n };\n\n private flushKeyRequests = async () => {\n const requests = this.keyRequests;\n this.keyRequests = [];\n await this.db.ready;\n if (requests.some((request) => request.waitForWrites)) {\n await this.mutationsSettled();\n }\n const groups = new Map<LoaderConfig, KeyRequest[]>();\n requests.forEach((request) => {\n const { loader } = request.subset;\n groups.set(loader, [...(groups.get(loader) ?? []), request]);\n });\n await Promise.all(\n [...groups.entries()].map(([loader, group]) => {\n if (loader.kind === \"byKeys\") {\n return this.sendKeyRequest(loader, group, loader.byKeys!(group.map(({ subset }) => subset.key)));\n }\n return Promise.all(\n group.map((request) => this.sendKeyRequest(loader, [request], loader.byKey!(request.subset.key))),\n );\n }),\n );\n };\n\n private sendKeyRequest = async (\n loader: LoaderConfig,\n group: KeyRequest[],\n patch: ReturnType<NonNullable<LoaderConfig[\"byKey\"]>>,\n ) => {\n const seq = this.db.tick();\n const wall = Date.now();\n const { generation } = this.db;\n this.db.trackRequest(seq);\n try {\n const request: RequestInstance = applyRequestPatches(loader.request.setCache(false), [patch]);\n const response = await request.send();\n const items = response.success ? this.readItems(loader, response.data) : [];\n const rows = await this.prepareServerRows(items);\n if (this.db.generation !== generation) {\n group.forEach(({ subset }) => subset.complete({ success: false, error: new Error(\"Cleared\") }));\n return;\n }\n // A row the response returned but the schema rejected exists on the server, so it is not removed as missing\n const returnedKeys = new Set(items.filter(isPlainObject).map((item) => item[this.config.key] as RowKey));\n this.db.batch(() => {\n if (response.success) {\n const keys = new Set(this.writeServerRows(rows, true, { kind: \"sent\", seq, wall }));\n const stamp = { kind: \"sent\" as const, seq, wall };\n group.forEach(({ subset }) => {\n subset.complete({ success: true, found: keys.has(subset.key) || returnedKeys.has(subset.key), stamp });\n });\n } else {\n group.forEach(({ subset }) => subset.complete({ success: false, error: response.error ?? response }));\n }\n });\n } catch (error) {\n this.db.emitError({ type: \"load\", error, collection: this.name });\n this.db.batch(() => group.forEach(({ subset }) => subset.complete({ success: false, error })));\n } finally {\n this.db.settleRequest(seq);\n group.forEach(({ resolve }) => resolve());\n }\n };\n\n private listenToIngest = (ingest: IngestConfig) => {\n const { request: ingested } = ingest;\n const { events } = ingested.client.requestManager;\n const matches = (request: RequestInstance) =>\n request.requestOptions.endpoint === ingested.requestOptions.endpoint && request.method === ingested.method;\n // A response is ordered by when its request was sent, so it never beats a write made after it went out\n const sentAt = new Map<string, number>();\n const generations = new Map<string, number>();\n const unsubscribeStart = events.onRequestStart(({ request, requestId }) => {\n if (matches(request)) {\n const seq = this.db.tick();\n sentAt.set(requestId, seq);\n generations.set(requestId, this.db.generation);\n this.db.trackRequest(seq);\n }\n });\n const unsubscribe = events.onResponse(({ request, requestId, response }) => {\n if (!matches(request)) {\n return;\n }\n const seq = sentAt.get(requestId);\n const generation = generations.get(requestId) ?? this.db.generation;\n sentAt.delete(requestId);\n generations.delete(requestId);\n if (seq !== undefined) {\n this.db.settleRequest(seq);\n }\n // A response to a request sent before `clear` belongs to the previous user\n if (!response.success || generation !== this.db.generation) {\n return;\n }\n const items = this.readItems(ingest, response.data).filter(isPlainObject);\n const write = (rows: Row[]) => {\n // A request that started before the db existed counts from now\n const stamp: Stamp = { kind: \"sent\", seq: seq ?? this.db.tick(), wall: response.requestTimestamp };\n this.db.batch(() => {\n const keys = this.writeServerRows(rows, ingest.type === \"insert\", stamp);\n if (ingest.type === \"insert\") {\n keys.forEach((key) => this.noteInsert(key));\n }\n });\n };\n const rows = this.prepareServerRows(items);\n if (rows instanceof Promise) {\n rows.then(write);\n } else {\n write(rows);\n }\n });\n this.cleanups.push(unsubscribe, unsubscribeStart);\n };\n}\n","import type { ClientInstance } from \"@hyper-fetch/core\";\nimport type { SocketInstance } from \"@hyper-fetch/sockets\";\n\nimport type { CollectionInstance } from \"../collection/collection\";\nimport type { CollectionConfig, RowKey } from \"../collection/collection.types\";\nimport { MutationEngine } from \"../mutation/mutation\";\nimport { stableStringify } from \"../operators/operators.utils\";\nimport { Persistence } from \"../persistence/persistence\";\nimport type { Serializer } from \"../persistence/serializer\";\nimport { createSerializer } from \"../persistence/serializer\";\nimport type { CollectionSnapshot } from \"../persistence/snapshot\";\nimport { restoreSnapshot, snapshotCollection } from \"../persistence/snapshot\";\nimport type { TabsMessage } from \"../persistence/tabs\";\nimport { Tabs } from \"../persistence/tabs\";\nimport { LiveQuery } from \"../query/live-query\";\nimport type { QueryDefinition } from \"../query/query.types\";\nimport type { KeySubset } from \"../subset/key-subset\";\nimport { ListSubset } from \"../subset/list-subset\";\nimport { CollectionRuntime } from \"./collection.runtime\";\nimport type {\n DbErrorEvent,\n DbInspection,\n DbNotation,\n DbOptions,\n DehydratedDb,\n TransactionConfig,\n TransactionRecord,\n} from \"./db.types\";\n\nconst DEFAULT_GC_TIME = 5 * 60 * 1000;\nconst DEFAULT_SYNC_TIMEOUT = 5000;\n\n/**\n * The running db. It owns the collections, batches writes into transactions so every query updates once, revalidates\n * stale subsets on focus and reconnect, and connects persistence, the outbox and other tabs.\n */\nexport class DbRuntime {\n readonly collections = new Map<string, CollectionRuntime>();\n readonly gcTime: number;\n readonly syncTimeout: number;\n readonly notation: DbNotation;\n readonly mutations: MutationEngine;\n readonly persistence: Persistence | undefined;\n private readonly serializer: Serializer;\n private changeListeners = new Set<() => void>();\n /** Timers of sync waits, cleared on `destroy` */\n private timers = new Set<ReturnType<typeof setTimeout>>();\n private queryTimers = new Map<LiveQuery, ReturnType<typeof setTimeout>>();\n readonly tabs: Tabs | undefined;\n readonly ready: Promise<void>;\n /** Changes on `clear`, so responses to requests sent before are never written */\n generation = 0;\n isReady = true;\n isDestroyed = false;\n private seq = 0;\n private batchDepth = 0;\n private changedRows = new Map<CollectionRuntime, Set<RowKey>>();\n private dirtyQueries = new Set<LiveQuery>();\n private liveQueries = new Map<string, LiveQuery>();\n private inflight = new Set<number>();\n private errorListeners = new Set<(event: DbErrorEvent) => void>();\n private syncWaiters = new Map<string, Set<() => void>>();\n private lastSyncWrite = new Map<string, number>();\n private sockets = new Set<SocketInstance>();\n private cleanups: (() => void)[] = [];\n\n constructor(\n collections: Record<string, CollectionInstance>,\n options: DbOptions & {\n links?: readonly (readonly [string, string])[];\n transactions?: Record<string, TransactionConfig>;\n } = {},\n ) {\n this.gcTime = options.gcTime ?? DEFAULT_GC_TIME;\n this.syncTimeout = options.syncTimeout ?? DEFAULT_SYNC_TIMEOUT;\n this.notation = { where: options.where, orderBy: options.orderBy };\n this.mutations = new MutationEngine(this, options.offline, options.transactions);\n this.serializer = createSerializer(options.codecs);\n\n Object.entries(collections).forEach(([name, definition]) => {\n this.collections.set(name, new CollectionRuntime(this, name, definition.config));\n });\n // A reference to a collection the db does not hold is a setup mistake, so it fails here and not during a write\n this.collections.forEach((collection) => {\n (collection.config.normalize ?? []).forEach(({ target }) => {\n if (!this.getCollectionByConfig(target)) {\n throw new Error(`\"${collection.name}\" normalizes into a collection that was not passed to createDb`);\n }\n });\n });\n (options.links ?? []).forEach(([first, second]) => {\n const left = this.collections.get(first)!.store;\n const right = this.collections.get(second)!.store;\n left.link(right);\n right.link(left);\n });\n this.collections.forEach((collection) => {\n collection.config.loaders.forEach((loader) => this.watchClient(loader.request.client));\n Object.values(collection.config.mutations).forEach((mutation) => this.watchClient(mutation!.request.client));\n });\n\n if (options.state) {\n this.hydrate(options.state);\n }\n\n if (options.persistence) {\n const scope = options.persistence.scope ?? \"default\";\n this.persistence = new Persistence(this, options.persistence, this.serializer);\n if (options.tabs !== false) {\n this.tabs = new Tabs(`hf-db:${scope}`, options.tabs, {\n onLeader: this.takeLead,\n onMessage: this.onTabsMessage,\n });\n }\n this.isReady = false;\n this.ready = this.restore();\n this.tabs?.start();\n } else {\n this.ready = Promise.resolve();\n }\n }\n\n /** Listens to every change the db makes, once per batch of writes, load or outbox change. Returns the unsubscribe. */\n onChange = (listener: () => void) => {\n this.changeListeners.add(listener);\n return () => {\n this.changeListeners.delete(listener);\n };\n };\n\n notifyChange = () => {\n this.changeListeners.forEach((listener) => listener());\n };\n\n /** What the db holds right now: collections with their layers and subsets, live queries and the outbox */\n inspect = (): DbInspection => ({\n collections: [...this.collections.values()].map((collection) => ({\n name: collection.name,\n rows: collection.store.keys().length,\n layers: collection.store.getLayers().map(({ id, key, type }) => ({ id, key, type })),\n subsets: collection.getSubsets().map((subset) => ({\n id: subset instanceof ListSubset ? subset.id : String((subset as KeySubset).key),\n kind: subset instanceof ListSubset ? (\"list\" as const) : (\"key\" as const),\n loader: collection.config.loaders.indexOf(subset.loader),\n rows:\n subset instanceof ListSubset\n ? subset.owned.size\n : Number(Boolean(collection.store.get((subset as KeySubset).key))),\n fresh: subset.isFresh(),\n live: subset.isLive(),\n loading: subset.isLoading,\n error: subset.error,\n loadedAt: subset.loadedAt,\n observers: subset.observerCount,\n })),\n })),\n queries: [...this.liveQueries.values()].map((query) => {\n const state = query.getState();\n return {\n key: query.key,\n collection: query.collection.name,\n subscribers: query.subscriberCount,\n status: state.status,\n rows: Array.isArray(state.data) ? state.data.length : undefined,\n plan: query.explain(),\n };\n }),\n outbox: [...this.mutations.outbox],\n });\n\n /** The server rows and loaded subsets of every collection that holds any, as type-tagged JSON */\n dehydrate = (): DehydratedDb => {\n const collections = Object.fromEntries(\n [...this.collections.values()]\n .map((collection) => [collection.name, snapshotCollection(collection)] as const)\n .filter(([, snapshot]) => snapshot.rows.length > 0 || snapshot.subsets.length > 0),\n );\n return { __dehydrated: true, collections: this.serializer.encode(collections) };\n };\n\n /** Writes a server's rows and subsets, before anything renders, so the first render matches the server's */\n private hydrate = (state: DehydratedDb) => {\n const collections = this.serializer.decode(state.collections) as Record<string, CollectionSnapshot>;\n Object.entries(collections).forEach(([name, snapshot]) => {\n const collection = this.collections.get(name);\n if (collection) {\n restoreSnapshot(collection, snapshot);\n }\n });\n };\n\n /** Whether this tab replays the outbox and writes persisted rows */\n get isLeader() {\n return this.tabs ? this.tabs.isLeader : true;\n }\n\n /** The collection a config belongs to, for references between collections such as `normalize` */\n getCollectionByConfig = (config: CollectionConfig): CollectionRuntime | undefined => {\n return [...this.collections.values()].find((item) => item.config === config);\n };\n\n tick = () => {\n this.seq += 1;\n return this.seq;\n };\n\n /** Runs writes as one transaction: every query updates once, after the last write */\n batch = <T>(callback: () => T): T => {\n this.batchDepth += 1;\n try {\n return callback();\n } finally {\n this.batchDepth -= 1;\n if (this.batchDepth === 0) {\n this.flush();\n }\n }\n };\n\n /** Records a changed row. Every store write runs inside `batch`, which flushes the changes once it ends. */\n markRowChanged = (collection: CollectionRuntime, key: RowKey) => {\n const keys = this.changedRows.get(collection) ?? new Set<RowKey>();\n keys.add(key);\n this.changedRows.set(collection, keys);\n };\n\n markQueryDirty = (query: LiveQuery) => {\n this.dirtyQueries.add(query);\n if (this.batchDepth === 0) {\n this.flush();\n }\n };\n\n /** The live query for a definition, shared by every query with the same structure */\n getLiveQuery = (definition: QueryDefinition): LiveQuery => {\n const key = stableStringify(definition);\n const existing = this.liveQueries.get(key);\n if (existing) {\n return existing;\n }\n const collection = this.collections.get(definition.collection)!;\n const query = new LiveQuery(collection, definition, key);\n this.liveQueries.set(key, query);\n this.releaseLater(query);\n return query;\n };\n\n /**\n * Forgets a live query nobody subscribes to after `gcTime`, so queries made once, such as each search, do not pile\n * up and slow every write. A query read again later is made again.\n */\n releaseLater = (query: LiveQuery) => {\n clearTimeout(this.queryTimers.get(query));\n const timer = setTimeout(() => {\n this.queryTimers.delete(query);\n if (!query.isActive() && this.liveQueries.get(query.key) === query) {\n this.liveQueries.delete(query.key);\n }\n }, this.gcTime);\n this.queryTimers.set(query, timer);\n };\n\n trackRequest = (seq: number) => {\n this.inflight.add(seq);\n };\n\n /** A request the db sent settled, so deletes made after every pending request no longer need remembering */\n settleRequest = (seq: number) => {\n this.inflight.delete(seq);\n const oldest = this.inflight.size > 0 ? Math.min(...this.inflight) : Number.POSITIVE_INFINITY;\n this.collections.forEach((collection) => collection.store.forgetTombstones(oldest));\n };\n\n onError = (listener: (event: DbErrorEvent) => void) => {\n this.errorListeners.add(listener);\n return () => {\n this.errorListeners.delete(listener);\n };\n };\n\n emitError = (event: DbErrorEvent) => {\n this.errorListeners.forEach((listener) => listener(event));\n };\n\n /** A sync event touched a row, which writes with `onSuccess: \"sync\"` wait for */\n notifySyncWrite = (collection: string, key: RowKey) => {\n const id = `${collection}:${String(key)}`;\n this.lastSyncWrite.set(id, this.tick());\n const waiters = this.syncWaiters.get(id);\n this.syncWaiters.delete(id);\n waiters?.forEach((resolve) => resolve());\n };\n\n /**\n * Resolves with `true` when a sync event touched the row after `since`, also while the write was in flight, or with\n * `false` after the timeout\n */\n waitForSync = ({\n collection,\n key,\n since,\n timeout,\n }: {\n collection: string;\n key: RowKey;\n since: number;\n timeout: number;\n }): Promise<boolean> => {\n const id = `${collection}:${String(key)}`;\n if ((this.lastSyncWrite.get(id) ?? 0) > since) {\n return Promise.resolve(true);\n }\n return new Promise((resolve) => {\n const waiters = this.syncWaiters.get(id) ?? new Set<() => void>();\n const timer = setTimeout(() => {\n this.timers.delete(timer);\n waiters.delete(onSync);\n resolve(false);\n }, timeout);\n this.timers.add(timer);\n const onSync = () => {\n clearTimeout(timer);\n this.timers.delete(timer);\n resolve(true);\n };\n waiters.add(onSync);\n this.syncWaiters.set(id, waiters);\n });\n };\n\n /** Marks the subsets a socket's syncs covered stale after a reconnect, unless their subscriptions resume */\n watchSocket = (socket: SocketInstance) => {\n if (this.sockets.has(socket)) {\n return;\n }\n this.sockets.add(socket);\n // A connection after an earlier one is a reconnect, whether or not the disconnect was reported\n let connectedBefore = socket.adapter.connected;\n const notifyAll = () => {\n this.collections.forEach((collection) => collection.getSubsets().forEach((subset) => subset.notify()));\n };\n this.cleanups.push(\n socket.events.onDisconnected(notifyAll),\n socket.events.onConnected(() => {\n if (connectedBefore) {\n this.collections.forEach((collection) => {\n collection.subscriptions.forEach((subscription) => {\n if (subscription.listener.socket !== socket || subscription.sync.resumes) {\n return;\n }\n subscription.getUsers().forEach((user) => {\n const subset = user as ReturnType<CollectionRuntime[\"getSubsets\"]>[number];\n subset.invalidate();\n if (subset.isUsed()) {\n subset.revalidate();\n }\n });\n });\n });\n }\n connectedBefore = true;\n notifyAll();\n }),\n );\n };\n\n /** Removes every row, loaded subset and pending write, and the persisted data of the scope */\n clear = async () => {\n this.tabs?.post({ type: \"clear\" });\n this.clearLocal();\n await this.persistence?.clear();\n this.revalidateActive();\n };\n\n /** Refetches the stale subsets of every mounted query */\n private revalidateActive = () => {\n this.liveQueries.forEach((query) => {\n if (query.isActive()) {\n query.revalidate();\n }\n });\n };\n\n /**\n * Drops rows, subsets and pending writes in this tab. Responses to requests sent before belong to the previous user,\n * so the generation changes and they are never written.\n */\n private clearLocal = () => {\n this.generation += 1;\n this.mutations.clear();\n this.batch(() => this.collections.forEach((collection) => collection.clear()));\n };\n\n /** This tab became the leader: it adopts the persisted outbox, so the previous leader's writes are replayed */\n private takeLead = async () => {\n // Tabs coordinate only a db that persists, so there is always a stored outbox to adopt\n const stored = await this.persistence!.loadOutbox();\n this.mutations.mergeOutbox(stored);\n this.tabs?.post({ type: \"leader\" });\n };\n\n destroy = () => {\n this.isDestroyed = true;\n this.mutations.destroy();\n this.timers.forEach((timer) => clearTimeout(timer));\n this.timers.clear();\n this.queryTimers.forEach((timer) => clearTimeout(timer));\n this.queryTimers.clear();\n this.liveQueries.clear();\n this.cleanups.forEach((cleanup) => cleanup());\n this.cleanups = [];\n this.collections.forEach((collection) => collection.destroy());\n this.persistence?.destroy();\n this.tabs?.close();\n };\n\n private watchClients = new Set<ClientInstance>();\n\n private watchClient = (client: ClientInstance) => {\n if (this.watchClients.has(client)) {\n return;\n }\n this.watchClients.add(client);\n const revalidate = () => {\n this.liveQueries.forEach((query) => {\n if (query.isActive()) {\n query.revalidate();\n }\n });\n };\n this.cleanups.push(\n client.appManager.events.onFocus(revalidate),\n client.appManager.events.onOnline(() => {\n revalidate();\n this.mutations.pump();\n }),\n );\n };\n\n private flush = () => {\n const changed = this.changedRows.size > 0 || this.dirtyQueries.size > 0;\n this.flushPending();\n if (changed) {\n this.notifyChange();\n }\n };\n\n private flushPending = () => {\n while (this.changedRows.size > 0 || this.dirtyQueries.size > 0) {\n const rows = this.changedRows;\n const dirty = this.dirtyQueries;\n this.changedRows = new Map();\n this.dirtyQueries = new Set();\n this.liveQueries.forEach((query) => {\n const keys = rows.get(query.collection);\n if (keys && !dirty.has(query)) {\n query.onRowsChanged(keys);\n }\n if (\n !dirty.has(query) &&\n query.isActive() &&\n [...rows.keys()].some((collection) => query.dependsOn(collection))\n ) {\n query.onJoinedRowsChanged();\n }\n });\n dirty.forEach((query) => query.rebuild());\n rows.forEach((keys, collection) => collection.refreshKeySyncs(keys));\n if (rows.size > 0) {\n this.persistence?.scheduleSave(rows.keys());\n this.forwardRows(rows);\n }\n }\n };\n\n /** Tabs that do not persist send their server rows to the tab that does */\n private forwardRows = (rows: Map<CollectionRuntime, Set<RowKey>>) => {\n if (!this.tabs || this.isLeader || !this.isReady) {\n return;\n }\n rows.forEach((keys, collection) => {\n const entries = [...keys]\n .map((key) => [key, collection.store.getServerRow(key)] as const)\n .filter((entry): entry is readonly [RowKey, Record<string, unknown>] => Boolean(entry[1]));\n if (entries.length > 0) {\n this.tabs!.post({ type: \"rows\", collection: collection.name, rows: entries.map(([key, row]) => [key, row]) });\n }\n });\n };\n\n private onTabsMessage = (message: TabsMessage) => {\n if (message.type === \"outcome\") {\n this.mutations.applyOutcome(message);\n return;\n }\n if (message.type === \"clear\") {\n this.clearLocal();\n this.revalidateActive();\n return;\n }\n if (message.type === \"leader\") {\n this.mutations.resendToLeader();\n return;\n }\n if (!this.isLeader) {\n return;\n }\n if (message.type === \"enqueue\") {\n this.mutations.mergeOutbox(message.records);\n return;\n }\n const collection = this.collections.get(message.collection);\n if (!collection) {\n return;\n }\n this.batch(() => {\n message.rows.forEach(([key, row]) => {\n if (!collection.store.hasServerRow(key)) {\n collection.store.write(key, row, { complete: true, stamp: { kind: \"sent\", seq: 0, wall: 0 } });\n }\n });\n });\n };\n\n private restore = async () => {\n let outbox: TransactionRecord[] = [];\n try {\n outbox = await this.persistence!.restore();\n } catch (error) {\n // A broken store must not keep the db from starting: it starts with what the network brings\n this.emitError({ type: \"persistence\", error });\n }\n this.isReady = true;\n this.mutations.restore(outbox);\n this.batch(() => this.liveQueries.forEach((query) => this.markQueryDirty(query)));\n };\n}\n","import type { CollectionInstance } from \"../collection/collection\";\nimport type {\n KeyFieldOf,\n LoaderDescriptor,\n MutationDescriptor,\n RowKey,\n SortDirection,\n} from \"../collection/collection.types\";\nimport type { Transaction } from \"../mutation/mutation\";\nimport { createTransaction } from \"../mutation/mutation\";\nimport type {\n Condition,\n ExtractConditionEq,\n ExtractConditionTokens,\n FieldRef,\n RowRefs,\n} from \"../operators/operators.types\";\nimport { Query } from \"../query/query\";\nimport type { JoinSpec, JoinTarget, JoinedMatchOf } from \"../query/query\";\nimport type { Row as StoreRow } from \"../store/store.types\";\nimport { createId } from \"../utils/request.utils\";\nimport type { CollectionRuntime } from \"./collection.runtime\";\nimport { DbRuntime } from \"./db.runtime\";\nimport type {\n DbErrorEvent,\n DbInspection,\n DbOptions,\n DehydratedDb,\n MutationOperation,\n TransactionConfig,\n} from \"./db.types\";\n\nexport type WriteOptions = {\n /** Writes this one is built on. When one of them is rejected, this write is dropped too. */\n dependsOn?: readonly (Transaction | string)[];\n};\n\ntype InsertMethod<Mutations> = Mutations extends { insert: infer Input }\n ? (row: Input, options?: WriteOptions) => Transaction\n : never;\n\ntype UpdateMethod<Key, Mutations> = Mutations extends { update: infer Changes }\n ? (key: Key, changes: Changes, options?: WriteOptions) => Transaction\n : never;\n\ntype DeleteMethod<Key, Mutations> = Mutations extends { delete: true }\n ? (key: Key, options?: WriteOptions) => Transaction\n : never;\n\nconst TEMPORARY_KEY_PREFIX = \"tmp:\";\n\n/** A collection inside a db: queries start here, and writes go through it */\nexport class CollectionHandle<\n Row,\n Input,\n KeyField extends KeyFieldOf<Row>,\n Loaders extends LoaderDescriptor,\n Mutations extends MutationDescriptor,\n> {\n /** Type-only carrier of the handle's generics, never set at runtime */\n declare readonly __types?: { row: Row; input: Input; key: KeyField; loaders: Loaders; mutations: Mutations };\n\n /** The collection's name in `createDb` */\n readonly collectionName: string;\n\n /** Adds an optimistic insert and sends it. A row without a key gets a temporary one until the server assigns it. */\n readonly insert: InsertMethod<Mutations>;\n /** Adds an optimistic update and sends it */\n readonly update: UpdateMethod<NonNullable<Row[KeyField]>, Mutations>;\n /** Adds an optimistic delete and sends it */\n readonly delete: DeleteMethod<NonNullable<Row[KeyField]>, Mutations>;\n\n constructor(\n private readonly runtime: DbRuntime,\n private readonly name: string,\n ) {\n this.collectionName = name;\n this.insert = ((row: StoreRow, options?: WriteOptions) =>\n this.write({ op: \"insert\", key: undefined, input: row, options })) as never;\n this.update = ((key: RowKey, changes: StoreRow, options?: WriteOptions) =>\n this.write({ op: \"update\", key, input: changes, options })) as never;\n this.delete = ((key: RowKey, options?: WriteOptions) =>\n this.write({ op: \"delete\", key, input: {}, options })) as never;\n }\n\n where<C extends Condition<string, string>>(callback: (row: RowRefs<Row>) => C) {\n return this.start().where(callback) as Query<Row, Loaders, Row, ExtractConditionTokens<C>, ExtractConditionEq<C>>;\n }\n\n orderBy<Name extends keyof Row & string>(\n callback: (row: RowRefs<Row>) => FieldRef<Name, Row[Name]>,\n direction?: SortDirection,\n ) {\n return this.start().orderBy(callback, direction);\n }\n\n select<Selection extends Record<string, FieldRef<string, unknown>>>(callback: (row: RowRefs<Row>) => Selection) {\n return this.start().select(callback);\n }\n\n limit(limit: number) {\n return this.start().limit(limit);\n }\n\n /** Adds the row of another collection whose key is the given field. See `Query.join`. */\n join<Name extends string, Target extends JoinTarget, Field extends keyof Row & string, const On, const Type>(\n name: Name,\n collection: Target,\n by: JoinSpec<Row, Field, JoinedMatchOf<Target, On>, On, Type>,\n ) {\n return this.start().join(name, collection, by);\n }\n\n /** Reads only the rows the db holds and never sends a request */\n local() {\n return this.start().local();\n }\n\n /** Reads one row by key */\n findOne(key: NonNullable<Row[KeyField]>): Query<Row, Loaders, Row, never, never, never, \"one\"> {\n return new Query(this.runtime, { collection: this.name, orderBy: [], local: false, one: { key: key as RowKey } });\n }\n\n /** The key to render a row with. It stays the same when a temporary key is swapped for the server's. */\n renderKey(key: NonNullable<Row[KeyField]>): string {\n return this.getRuntime().getRenderKey(key as RowKey);\n }\n\n private start() {\n return new Query<Row, Loaders, Row>(this.runtime, { collection: this.name, orderBy: [], local: false });\n }\n\n private getRuntime() {\n return this.runtime.collections.get(this.name)!;\n }\n\n private write({\n op,\n key: givenKey,\n input,\n options,\n }: {\n op: MutationOperation;\n key: RowKey | undefined;\n input: StoreRow;\n options: WriteOptions | undefined;\n }) {\n const collection = this.getRuntime();\n const { mutations } = this.runtime;\n // A temporary key the server replaced still names the row, so writes made with it reach the server's key\n const key = givenKey === undefined ? undefined : collection.resolveKey(givenKey);\n const dependsOn = (options?.dependsOn ?? []).map((item) => (typeof item === \"string\" ? item : item.id));\n const { key: keyField } = collection.config;\n\n const id = createId();\n const submit = (values: StoreRow) => {\n if (op !== \"insert\") {\n return mutations.submit({ collection, op, key: key!, values, dependsOn, id });\n }\n const rowKey = values[keyField] as RowKey | undefined;\n if (rowKey !== undefined && rowKey !== null) {\n return mutations.submit({ collection, op, key: rowKey, values, dependsOn, id });\n }\n const insertRequest = collection.config.mutations.insert?.request;\n if (mutations.usesOutbox && insertRequest && !insertRequest.client.appManager.isOnline) {\n return mutations.reject(new Error(\"An insert that leaves the key to the server cannot be made offline\"), id);\n }\n const temporaryKey = `${TEMPORARY_KEY_PREFIX}${id}`;\n return mutations.submit({\n collection,\n op,\n key: temporaryKey,\n values: { ...values, [keyField]: temporaryKey },\n dependsOn,\n id,\n temporaryKey: true,\n });\n };\n\n const mistake = findWriteMistake({ collection, op, key, input });\n if (mistake) {\n this.runtime.emitError({ type: \"mutation\", error: mistake, collection: this.name });\n return mutations.reject(mistake, id);\n }\n const prepared = prepareWrite({ collection, op, key, input });\n const finish = (result: PreparedValues) => {\n if (\"issues\" in result) {\n this.runtime.emitError({ type: \"validation\", error: result.issues, collection: this.name });\n return mutations.reject(result.issues, id);\n }\n return submit(result.values);\n };\n if (prepared instanceof Promise) {\n return createTransaction(id, prepared.then(finish));\n }\n return finish(prepared);\n }\n}\n\ntype PreparedValues = { values: StoreRow } | { issues: unknown };\n\n/** A write that cannot be right whatever the server says: an insert of a key the db holds, or an update of the key */\nconst findWriteMistake = ({\n collection,\n op,\n key,\n input,\n}: {\n collection: CollectionRuntime;\n op: MutationOperation;\n key: RowKey | undefined;\n input: StoreRow;\n}): Error | undefined => {\n const keyField = collection.config.key;\n const insertedKey = input[keyField] as RowKey | undefined;\n if (op === \"insert\" && insertedKey !== undefined && collection.store.get(insertedKey)) {\n return new Error(`\"${collection.name}\" already holds a row with the key ${String(insertedKey)}`);\n }\n if (op === \"update\" && keyField in input && input[keyField] !== key) {\n return new Error(`An update cannot change the key of a row in \"${collection.name}\"`);\n }\n return undefined;\n};\n\n/**\n * Validates a write against the collection's schema. An insert is validated as a row; an update is validated merged\n * with the current row, and only its changed fields are kept. A delete, a collection without a schema, and an update of\n * a row the db does not hold pass as they are.\n */\nconst prepareWrite = ({\n collection,\n op,\n key,\n input,\n}: {\n collection: CollectionRuntime;\n op: MutationOperation;\n key: RowKey | undefined;\n input: StoreRow;\n}): PreparedValues | Promise<PreparedValues> => {\n const { schema } = collection.config;\n const current = op === \"update\" ? collection.store.get(key!) : undefined;\n // An update that carries `undefined` for a field leaves that field as it is; `null` clears it\n const defined =\n op === \"update\" ? Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined)) : input;\n if (!schema || op === \"delete\" || (op === \"update\" && !current)) {\n return { values: defined };\n }\n const candidate = op === \"update\" ? { ...current, ...defined } : input;\n const finish = (result: Awaited<ReturnType<(typeof schema)[\"~standard\"][\"validate\"]>>): PreparedValues => {\n if (result.issues) {\n return { issues: result.issues };\n }\n const output = result.value as StoreRow;\n return {\n values:\n op === \"insert\" ? output : Object.fromEntries(Object.keys(defined).map((field) => [field, output[field]])),\n };\n };\n const validation = schema[\"~standard\"].validate(candidate);\n return validation instanceof Promise ? validation.then(finish) : finish(validation);\n};\n\ntype HandleOf<C> = C extends {\n __types?: {\n row: infer Row;\n input: infer Input;\n key: infer KeyField;\n loaders: infer Loaders;\n mutations: infer Mutations;\n };\n}\n ? [KeyField, Loaders, Mutations] extends [KeyFieldOf<Row>, LoaderDescriptor, MutationDescriptor]\n ? CollectionHandle<\n Row,\n Input,\n KeyField & KeyFieldOf<Row>,\n Loaders & LoaderDescriptor,\n Mutations & MutationDescriptor\n >\n : never\n : never;\n\n/** The writes a transaction can make to one collection. Named transactions can write any collection. */\ntype TransactionHandleOf<C, Named extends boolean> = C extends {\n __types?: { row: infer Row; input: infer Input; key: infer KeyField; mutations: infer Mutations };\n}\n ? KeyField extends keyof Row\n ? Named extends true\n ? {\n /** Needs its key, because one request cannot tell which key the server gave which row */\n insert: (row: Input & { [Field in KeyField]: NonNullable<Row[KeyField]> }) => void;\n update: (key: NonNullable<Row[KeyField]>, changes: Partial<Row>) => void;\n delete: (key: NonNullable<Row[KeyField]>) => void;\n }\n : {\n insert: Mutations extends { insert: infer Inserted }\n ? (row: Inserted & { [Field in KeyField]: NonNullable<Row[KeyField]> }) => void\n : never;\n update: Mutations extends { update: infer Changes }\n ? (key: NonNullable<Row[KeyField]>, changes: Changes) => void\n : never;\n delete: Mutations extends { delete: true } ? (key: NonNullable<Row[KeyField]>) => void : never;\n }\n : never\n : never;\n\n/** What a transaction callback receives: one handle per collection, which records writes instead of sending them */\nexport type TransactionHandles<Collections, Named extends boolean> = {\n [Name in keyof Collections]: TransactionHandleOf<Collections[Name], Named>;\n};\n\ntype TransactionMethod<Collections, Transactions> = {\n /**\n * Groups writes into one optimistic layer, kept or dropped as a whole. Each write goes through its collection's\n * `mutate`, in order; when one fails, the writes after it are dropped and the subsets holding rows already written\n * refetch.\n */\n (callback: (tx: TransactionHandles<Collections, false>) => void): Transaction;\n /**\n * Groups writes into one optimistic layer and sends them as one request, through the `mutationFn` of the named\n * transaction in `createDb`. The name is stored in the outbox, so the transaction can be replayed after a restart.\n */\n <Name extends keyof Transactions & string>(\n name: Name,\n callback: (tx: TransactionHandles<Collections, true>) => void,\n ): Transaction;\n};\n\ntype ReservedName = \"clear\" | \"destroy\" | \"ready\" | \"onError\" | \"transaction\" | \"dehydrate\" | \"inspect\" | \"onChange\";\n\nexport type DbMethods = {\n /** Resolves once persisted rows and the outbox are restored */\n ready: Promise<void>;\n /** Removes every row, loaded subset and pending write, and the persisted data of the scope, for example on sign-out */\n clear: () => Promise<void>;\n /** Stops every sync, timer and tab channel */\n destroy: () => void;\n /** Listens to failed writes, rejected validation, outbox and persistence errors */\n onError: (listener: (event: DbErrorEvent) => void) => () => void;\n /**\n * The server rows and loaded subsets, as type-tagged JSON, for server rendering. Optimistic layers, the outbox and\n * syncs are never included. Pass it to `createDb(collections, { state })` on the client.\n */\n dehydrate: () => DehydratedDb;\n /** What the db holds right now: collections with their layers and subsets, live queries and the outbox */\n inspect: () => DbInspection;\n /** Listens to every change the db makes, once per batch of writes, load or outbox change */\n onChange: (listener: () => void) => () => void;\n};\n\nexport type Db<Collections extends Record<string, CollectionInstance>, Transactions = unknown> = {\n [Name in keyof Collections]: HandleOf<Collections[Name]>;\n} & DbMethods & { transaction: TransactionMethod<Collections, Transactions> };\n\ntype TransactionCallback = (tx: Record<string, Record<MutationOperation, (...args: never[]) => void>>) => void;\n\ntype RecordedWrite = { collection: string; op: MutationOperation; key: RowKey | undefined; input: StoreRow };\n\n/** Records the writes a transaction callback makes, validates them, and submits them together */\nconst runTransaction = (runtime: DbRuntime, name: string | undefined, callback: TransactionCallback): Transaction => {\n const id = createId();\n const recorded: RecordedWrite[] = [];\n const tx = Object.fromEntries(\n [...runtime.collections.keys()].map((collection) => [\n collection,\n {\n insert: (row: StoreRow) => recorded.push({ collection, op: \"insert\", key: undefined, input: row }),\n update: (key: RowKey, changes: StoreRow) => recorded.push({ collection, op: \"update\", key, input: changes }),\n delete: (key: RowKey) => recorded.push({ collection, op: \"delete\", key, input: {} }),\n },\n ]),\n );\n callback(tx as never);\n\n const fail = (error: unknown) => runtime.mutations.reject(error, id);\n const writes = recorded.map((write) => {\n const collection = runtime.collections.get(write.collection)!;\n const key = write.op === \"insert\" ? (write.input[collection.config.key] as RowKey | undefined) : write.key;\n return {\n collection,\n op: write.op,\n key,\n prepared: prepareWrite({ collection, op: write.op, key, input: write.input }),\n };\n });\n if (writes.some((write) => write.key === undefined || write.key === null)) {\n return fail(new Error(\"An insert in a transaction needs its key, such as a UUID generated on the client\"));\n }\n const submit = (results: PreparedValues[]) => {\n const invalid = results.find((result): result is { issues: unknown } => \"issues\" in result);\n if (invalid) {\n runtime.emitError({ type: \"validation\", error: invalid.issues });\n return fail(invalid.issues);\n }\n return runtime.mutations.submitTransaction({\n id,\n name,\n writes: writes.map((write, index) => ({\n collection: write.collection,\n op: write.op,\n key: write.key!,\n values: (results[index] as { values: StoreRow }).values,\n })),\n });\n };\n const prepared = writes.map((write) => write.prepared);\n if (prepared.some((item) => item instanceof Promise)) {\n return createTransaction(id, Promise.all(prepared).then(submit));\n }\n return submit(prepared as PreparedValues[]);\n};\n\n/**\n * Creates the db that queries and writes go through. The names given to it are the names on the db, as in `db.post`.\n * Requests carry their Client and listeners carry their Socket, so it needs neither.\n *\n * @example\n * const db = createDb({ post: Post, user: User });\n */\nexport const createDb = <Collections extends Record<string, CollectionInstance>, Transactions>(\n collections: Collections & { [Name in Extract<keyof Collections, ReservedName>]: never },\n options?: DbOptions & {\n /**\n * Collections that hold the same records in different shapes, such as `[\"post\", \"postSummary\"]`. A write, delete\n * or optimistic change to one changes the fields the other has, for the same key.\n */\n links?: readonly (readonly [keyof Collections & string, keyof Collections & string])[];\n /** Named transactions: each sends the writes of `db.transaction(name, ...)` as one request */\n transactions?: Transactions & Record<string, TransactionConfig>;\n },\n): Db<Collections, Transactions> => {\n const runtime = new DbRuntime(collections, options);\n const methods: DbMethods = {\n ready: runtime.ready,\n clear: runtime.clear,\n destroy: runtime.destroy,\n onError: runtime.onError,\n dehydrate: runtime.dehydrate,\n inspect: runtime.inspect,\n onChange: runtime.onChange,\n };\n const handles = Object.fromEntries(\n Object.keys(collections).map((name) => [name, new CollectionHandle(runtime, name)]),\n );\n const transaction = (first: string | TransactionCallback, second?: TransactionCallback) => {\n const [name, callback] = typeof first === \"string\" ? [first, second!] : [undefined, first];\n return runTransaction(runtime, name, callback);\n };\n return { ...handles, ...methods, transaction } as Db<Collections, Transactions>;\n};\n","/** A Relay connection, the shape many GraphQL APIs use for paginated lists */\nexport type RelayConnection<Node> = {\n edges?: readonly ({ node: Node } | null)[] | null;\n pageInfo: { hasNextPage: boolean; endCursor?: string | null };\n};\n\n/**\n * Reads the rows and the next cursor of a Relay connection (`edges` / `node`), for a paginated GraphQL loader. Spread it\n * into the loader options and add `page` to send the cursor.\n *\n * @example\n * collection(PostSchema, { key: \"id\" }).load(getPosts, {\n * ...relayConnection((response: PostsResponse) => response.posts),\n * page: (after) => ({ payload: { after } }),\n * });\n */\nexport const relayConnection = <Response, Node>(select: (response: Response) => RelayConnection<Node>) => ({\n rows: (response: Response): Node[] => (select(response).edges ?? []).flatMap((edge) => (edge ? [edge.node] : [])),\n cursor: (response: Response): string | null => {\n const { pageInfo } = select(response);\n return pageInfo.hasNextPage ? (pageInfo.endCursor ?? null) : null;\n },\n});\n","import type {\n ComparableValue,\n Condition,\n ExtractConditionEq,\n ExtractConditionTokens,\n FieldRef,\n LocalToken,\n NoInferValue,\n} from \"./operators.types\";\n\nconst comparison = (op: \"eq\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"inArray\", ref: FieldRef, value: unknown) => {\n return { kind: \"condition\", node: { op, field: ref.field, value } } as const;\n};\n\n/** Matches rows whose field equals the value. Dates are equal when they are the same instant. */\nexport const eq = <Name extends string, Value>(\n ref: FieldRef<Name, Value>,\n value: NoInferValue<Value>,\n): Condition<`${Name}:eq`, Name> => comparison(\"eq\", ref, value);\n\n/** Matches rows whose field is greater than the value */\nexport const gt = <Name extends string, Value extends ComparableValue | null | undefined>(\n ref: FieldRef<Name, Value>,\n value: NoInferValue<NonNullable<Value>>,\n): Condition<`${Name}:gt`, never> => comparison(\"gt\", ref, value);\n\n/** Matches rows whose field is greater than or equal to the value */\nexport const gte = <Name extends string, Value extends ComparableValue | null | undefined>(\n ref: FieldRef<Name, Value>,\n value: NoInferValue<NonNullable<Value>>,\n): Condition<`${Name}:gte`, never> => comparison(\"gte\", ref, value);\n\n/** Matches rows whose field is less than the value */\nexport const lt = <Name extends string, Value extends ComparableValue | null | undefined>(\n ref: FieldRef<Name, Value>,\n value: NoInferValue<NonNullable<Value>>,\n): Condition<`${Name}:lt`, never> => comparison(\"lt\", ref, value);\n\n/** Matches rows whose field is less than or equal to the value */\nexport const lte = <Name extends string, Value extends ComparableValue | null | undefined>(\n ref: FieldRef<Name, Value>,\n value: NoInferValue<NonNullable<Value>>,\n): Condition<`${Name}:lte`, never> => comparison(\"lte\", ref, value);\n\n/** Matches rows whose field equals one of the values */\nexport const inArray = <Name extends string, Value>(\n ref: FieldRef<Name, Value>,\n values: readonly NoInferValue<Value>[],\n): Condition<`${Name}:inArray`, never> => comparison(\"inArray\", ref, values);\n\n/**\n * A server-only operator, such as full-text search, which has no meaning on the client. A loader maps it under its\n * name like any operator, as in `title: { search: (text: string) => ({ queryParams: { q: text } }) }`. A query that\n * uses one must send it, or it does not compile. Its subset never answers other queries, and new rows never join it:\n * an insert marks it stale instead.\n *\n * @example\n * db.post.where((post) => op(\"search\", post.title, \"tea\"));\n */\nexport const op = <Operator extends string, Name extends string, Value>(\n name: Operator,\n ref: FieldRef<Name, unknown>,\n value: Value,\n): Condition<`${Name}:${Operator}`, never> => ({\n kind: \"condition\",\n node: { op: \"server\", name, field: ref.field, value },\n});\n\n/**\n * Matches rows that match every condition. Top-level `and` is where the db splits a query: the conditions a loader\n * declares are sent to the backend and the rest run on the rows the db holds.\n */\nexport const and = <Conditions extends readonly Condition<string, string>[]>(\n ...conditions: Conditions\n): Condition<ExtractConditionTokens<Conditions[number]>, ExtractConditionEq<Conditions[number]>> => ({\n kind: \"condition\",\n node: { op: \"and\", items: conditions.map((condition) => condition.node) },\n});\n\n/** Matches rows that match at least one condition. It runs on the rows the db holds. */\nexport const or = (...conditions: readonly Condition<string, string>[]): Condition<LocalToken, never> => ({\n kind: \"condition\",\n node: { op: \"or\", items: conditions.map((condition) => condition.node) },\n});\n\n/** Matches rows that do not match the condition. It runs on the rows the db holds. */\nexport const not = (condition: Condition<string, string>): Condition<LocalToken, never> => ({\n kind: \"condition\",\n node: { op: \"not\", item: condition.node },\n});\n"],"mappings":";;;;;;;;;AAoDA,IAAa,aAAb,MAAa,WAMX;CAIA,YAAY,QAAmC;AAA1B,OAAA,SAAA;;;;;;CAMrB,KACE,SACA,SAqBuD;EACvD,MAAM,gBAAiB,WAAW,EAAE;EACpC,IAAI,OAA6B;AACjC,MAAI,cAAc,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