UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

1 lines • 58.6 kB
{"version":3,"file":"client.cjs","names":["collectionOptionsClaim","codedMessage","collectionOptionsBrand","collectionOptionsFactory","hasCollectionOptionsBrand","truncatesSourceKey","TransactionScope","prepareLiveQueryValue","getLiveQueryHash","getPreparedLiveQuerySources","getLiveQueryRowOptions","createLiveQueryCollection","createLiveQueryObserver","createCollection","getBuilderFromConfig","LiveQueryObserverClient","createDeferred","collectionsById","pendingHydration","hydratedLiveQueries","ssrQueryWaiters","preloadedLiveQueries","liveQueryResources","ssrStreamingEnabled","ssrServerCleanupEnabled","lastLiveQueryTimestamp","transactionScope","startLiveQueryPreload","discardPreloadedLiveQuery","materializeCollection","reuseMaterializedCollection","applyRows","hydrateLiveQuery","ssrStreamFailure","failSsrQueryWaiters","nextLiveQueryTimestamp","createLiveQueryRecord"],"sources":["../../src/client.ts"],"sourcesContent":["import { createCollection } from './collection/index.js'\nimport { validateCollectionIndexing } from './collection/validate-indexing.js'\nimport {\n  collectionOptionsBrand,\n  collectionOptionsClaim,\n  collectionOptionsFactory,\n  hasCollectionOptionsBrand,\n} from './collection-options.js'\nimport { TransactionScope } from './transactions.js'\nimport { getBuilderFromConfig } from './query/live/collection-registry.js'\nimport { createLiveQueryCollection } from './query/live-query-collection.js'\nimport { createLiveQueryObserver } from './live-query-observer.js'\nimport { LiveQueryObserverClient } from './live-query-observer-client.js'\nimport { createDeferred } from './deferred.js'\nimport {\n  getLiveQueryHash,\n  getLiveQueryRowOptions,\n  getPreparedLiveQuerySources,\n  prepareLiveQueryValue,\n  resumeDeferredLiveQueryCollections,\n} from './live-query-options.js'\nimport { codedMessage, devBuild } from './error-message.js'\nimport { truncatesSourceKey } from './collection/state.js'\nimport type { LiveQueryObserverClientHost } from './live-query-observer-client.js'\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type { Collection } from './collection/index.js'\nimport type { CollectionOptionsIdentity } from './collection-options.js'\nimport type { Deferred } from './deferred.js'\nimport type {\n  CollectionConfig,\n  InferSchemaInput,\n  InferSchemaOutput,\n  NonSingleResult,\n  SingleResult,\n  TransactionConfig,\n  UtilsRecord,\n} from './types.js'\nimport type {\n  DeferredLiveQueryCollections,\n  LiveQueryOptions,\n  LiveQueryRowOptions,\n} from './live-query-options.js'\nimport type {\n  CollectionStateManager,\n  PendingMetadataWrite,\n  StagedSyncTransaction,\n} from './collection/state.js'\n\nconst collectionConfigFactory: unique symbol = Symbol.for(\n  `@tanstack/db.collectionConfig.factory`,\n) as never\n\ntype AnyCollectionConfig = CollectionConfig<any, any, any, any>\n\nexport type CollectionOptions<\n  T extends object = Record<string, unknown>,\n  TKey extends string | number = string | number,\n  TSchema extends StandardSchemaV1 = never,\n  TUtils extends UtilsRecord = UtilsRecord,\n> = CollectionOptionsIdentity<T, TKey, TSchema, TUtils, DbClient>\n\ntype AnyCollectionOptions = CollectionOptions<any, any, any, any>\ntype AnyCollection = Collection<any, any, any, any, any>\n\nfunction sameSourcesAtEachPosition(\n  left: ReadonlyArray<AnyCollection>,\n  right: ReadonlyArray<AnyCollection>,\n): boolean {\n  return (\n    left.length === right.length &&\n    left.every((source, index) => source === right[index])\n  )\n}\n\ntype DescriptorFromConfig<TConfig extends AnyCollectionConfig> =\n  TConfig extends {\n    getKey: (item: infer T) => infer TKey\n  }\n    ? CollectionOptions<\n        Extract<T, object>,\n        Extract<TKey, string | number>,\n        TConfig extends {\n          schema: infer TSchema extends StandardSchemaV1\n        }\n          ? TSchema\n          : never,\n        TConfig extends {\n          utils: infer TUtils extends UtilsRecord\n        }\n          ? TUtils\n          : UtilsRecord\n      > &\n        (TConfig extends SingleResult ? SingleResult : NonSingleResult)\n    : never\n\ntype CollectionConfigWithFactory<TConfig extends AnyCollectionConfig> =\n  TConfig & {\n    readonly [collectionConfigFactory]: (client: DbClient) => TConfig\n  }\n\n/**\n * Adds a fresh-config materializer to an adapter options object.\n *\n * Adapter option creators should use this so a module-scoped descriptor can be\n * materialized safely by more than one DbClient.\n */\nexport function withCollectionConfigFactory<\n  TConfig extends AnyCollectionConfig,\n>(\n  config: TConfig,\n  factory: (client: DbClient) => TConfig,\n  claim?: () => void | (() => void),\n): CollectionConfigWithFactory<TConfig> {\n  Object.defineProperty(config, collectionConfigFactory, {\n    value: factory,\n    enumerable: false,\n  })\n  if (claim) {\n    Object.defineProperty(config, collectionOptionsClaim, {\n      value: claim,\n      enumerable: true,\n    })\n  }\n  return config as CollectionConfigWithFactory<TConfig>\n}\n\nexport type CollectionMaterializeOptions<T extends object> = {\n  initialData?: Array<T>\n}\n\nexport type DehydratedCollectionRow<\n  T extends object = Record<string, unknown>,\n  TKey extends string | number = string | number,\n> = {\n  key: TKey\n  value: T\n  metadata?: unknown\n}\n\nexport type DehydratedCollectionChunk<\n  T extends object = Record<string, unknown>,\n  TKey extends string | number = string | number,\n> = {\n  collectionId: string\n  rows: Array<DehydratedCollectionRow<T, TKey>>\n  syncMeta?: unknown\n}\n\nexport type DehydratedLiveQuery = {\n  queryHash: string\n  dehydratedAt: number\n  /** Earlier ordinary markup may precede a shared Suspense result. */\n  initialSnapshot?: DehydratedLiveQueryResult\n  snapshot?: DehydratedLiveQueryResult\n  promise?: Promise<DehydratedLiveQueryResult>\n}\n\nexport type DehydratedLiveQueryResult<\n  T extends object = object,\n  TKey extends string | number = string | number,\n> = {\n  rows: Array<DehydratedCollectionRow<T, TKey>>\n  /** An initial SSR view may precede query readiness. Omitted means ready. */\n  status?: `loading` | `error`\n}\n\nexport type DehydratedDbState = {\n  collections: Array<DehydratedCollectionChunk>\n  liveQueries?: Array<DehydratedLiveQuery>\n}\n\nexport type DbClientLiveQueryState = `pending` | `success` | `error`\n\nexport type DbClientLiveQuery = {\n  readonly queryHash: string\n  readonly dehydratedAt: number\n  readonly status: DbClientLiveQueryState\n  readonly promise: Promise<void>\n  /** Initial hydration view retained while a local preload completes. */\n  readonly initialSnapshot?: DehydratedLiveQueryResult\n  readonly snapshot?: DehydratedLiveQueryResult\n  readonly error?: unknown\n}\n\nexport type DbClientEvent =\n  | {\n      type: `liveQueryAdded` | `liveQueryUpdated`\n      query: DbClientLiveQuery\n    }\n  | {\n      type: `liveQueryStreamError`\n      error: unknown\n    }\n\nexport type DehydrateDbClientOptions = {\n  shouldDehydrateCollection?: (collection: Collection) => boolean\n  shouldDehydrateLiveQuery?: (query: DbClientLiveQuery) => boolean\n}\n\ntype CollectionRecord = {\n  collection: AnyCollection\n  shouldDehydrate: boolean\n  hydrated: boolean\n}\n\ntype LiveQueryRecord = {\n  rowOptions?: LiveQueryRowOptions\n  queryHash: string\n  sources?: ReadonlyArray<AnyCollection>\n  dehydratedAt: number\n  status: DbClientLiveQueryState\n  promise: Promise<void>\n  resultPromise: Promise<DehydratedLiveQueryResult>\n  succeed: (snapshot: DehydratedLiveQueryResult) => void\n  fail: (error: unknown) => void\n  initialSnapshot?: DehydratedLiveQueryResult\n  snapshot?: DehydratedLiveQueryResult\n  error?: unknown\n}\n\nexport type DbClientOptions = Record<string, unknown>\n\nexport function collectionOptions<\n  T extends StandardSchemaV1,\n  TKey extends string | number,\n  TUtils extends UtilsRecord,\n>(\n  options: CollectionConfig<InferSchemaOutput<T>, TKey, T, TUtils> & {\n    schema: T\n  } & NonSingleResult,\n): CollectionOptions<InferSchemaOutput<T>, TKey, T, TUtils> & NonSingleResult\nexport function collectionOptions<\n  T extends StandardSchemaV1,\n  TKey extends string | number,\n  TUtils extends UtilsRecord,\n>(\n  options: CollectionConfig<InferSchemaOutput<T>, TKey, T, TUtils> & {\n    schema: T\n  } & SingleResult,\n): CollectionOptions<InferSchemaOutput<T>, TKey, T, TUtils> & SingleResult\nexport function collectionOptions<\n  T extends object,\n  TKey extends string | number = string | number,\n  TUtils extends UtilsRecord = UtilsRecord,\n>(\n  options: CollectionConfig<T, TKey, never, TUtils> & {\n    schema?: never\n  } & NonSingleResult,\n): CollectionOptions<T, TKey, never, TUtils> & NonSingleResult\nexport function collectionOptions<\n  T extends object,\n  TKey extends string | number = string | number,\n  TUtils extends UtilsRecord = UtilsRecord,\n>(\n  options: CollectionConfig<T, TKey, never, TUtils> & {\n    schema?: never\n  } & SingleResult,\n): CollectionOptions<T, TKey, never, TUtils> & SingleResult\nexport function collectionOptions<TConfig extends AnyCollectionConfig>(\n  id: string,\n  factory: (client: DbClient) => TConfig,\n): DescriptorFromConfig<TConfig>\nexport function collectionOptions(\n  optionsOrId: AnyCollectionConfig | string,\n  explicitFactory?: (client: DbClient) => unknown,\n): any {\n  const config = typeof optionsOrId === `string` ? undefined : optionsOrId\n  const id = typeof optionsOrId === `string` ? optionsOrId : optionsOrId.id\n\n  if (!id) {\n    throw new Error(\n      devBuild() && process.env.NODE_ENV !== `production`\n        ? `collectionOptions requires a non-empty explicit id so the descriptor is stable across DbClient instances and SSR boundaries.`\n        : codedMessage(88),\n    )\n  }\n\n  if (typeof optionsOrId === `string` && !explicitFactory) {\n    throw new Error(\n      devBuild() && process.env.NODE_ENV !== `production`\n        ? `collectionOptions(\"${id}\") requires a factory as its second argument.`\n        : codedMessage(89, { id }),\n    )\n  }\n\n  const reusableFactory:\n    ((client: DbClient) => AnyCollectionConfig) | undefined = config\n    ? (config as CollectionConfigWithFactory<AnyCollectionConfig>)[\n        collectionConfigFactory\n      ]\n    : (explicitFactory as\n        ((client: DbClient) => AnyCollectionConfig) | undefined)\n\n  let owner: DbClient | undefined\n  const materialize = (client: DbClient): AnyCollectionConfig => {\n    let materialized: AnyCollectionConfig\n\n    if (reusableFactory) {\n      materialized = reusableFactory(client)\n    } else {\n      if (owner && owner !== client) {\n        throw new Error(\n          devBuild() && process.env.NODE_ENV !== `production`\n            ? `Collection descriptor \"${id}\" was created from a concrete config that cannot be safely reused across DbClient instances. ` +\n                `Use collectionOptions(\"${id}\", (client) => adapterCollectionOptions(...)) or an adapter options creator that supports DbClient materialization.`\n            : codedMessage(90, { id }),\n        )\n      }\n      owner = client\n      materialized = config!\n    }\n\n    if (materialized.id !== undefined && materialized.id !== id) {\n      throw new Error(\n        devBuild() && process.env.NODE_ENV !== `production`\n          ? `Collection descriptor \"${id}\" materialized a config with id \"${materialized.id}\". Descriptor and collection ids must match.`\n          : codedMessage(91, { id, materializedId: materialized.id }),\n      )\n    }\n\n    return materialized.id === id ? materialized : { ...materialized, id }\n  }\n\n  const descriptor = {\n    id,\n    ...((config as { singleResult?: boolean } | undefined)?.singleResult ===\n    true\n      ? { singleResult: true as const }\n      : {}),\n  } as Record<PropertyKey, unknown>\n\n  Object.defineProperties(descriptor, {\n    [collectionOptionsBrand]: {\n      value: true,\n      enumerable: false,\n    },\n    [collectionOptionsFactory]: {\n      value: materialize,\n      enumerable: false,\n    },\n  })\n\n  return Object.freeze(descriptor) as CollectionOptions<\n    any,\n    string | number,\n    any,\n    UtilsRecord\n  >\n}\n\nexport function isCollectionOptions(\n  value: unknown,\n): value is CollectionOptions<any, string | number, any, UtilsRecord> {\n  return hasCollectionOptionsBrand(value)\n}\n\n/**\n * A late hydration seed cannot supersede committed adapter work. Row data\n * and row metadata are separate objects, so each has its own lookup. A\n * wrapping sync's committed transactions that it has not handed to this\n * Collection yet count as committed adapter work.\n */\nfunction createAdapterAuthorityLookups<TKey extends string | number>(\n  state: CollectionStateManager<any, TKey, any, any>,\n): {\n  rows: (key: TKey) => boolean\n  metadata: (key: TKey) => boolean\n} {\n  const rowKeys = new Set<TKey>()\n  const metadataKeys = new Set<TKey>()\n  // The latest source truncate, with the held seeds a schema reset kept.\n  let truncate: StagedSyncTransaction<TKey> | undefined =\n    state.hasAppliedAdapterTruncate\n      ? {\n          truncate: true,\n          operations: [],\n          rowMetadataWrites: new Map(),\n          preserveHydrationSeedKeys: state.adapterTruncateKeptKeys,\n          sourceTruncate: true,\n        }\n      : undefined\n  for (const transaction of [\n    ...state.pendingSyncedTransactions.filter((pending) => pending.committed),\n    ...state.getStagedSyncTransactions(),\n  ]) {\n    if (\n      transaction.truncate &&\n      (!transaction.preserveHydrationSeedKeys || transaction.sourceTruncate)\n    )\n      truncate = transaction\n    for (const operation of transaction.operations)\n      if (!transaction.preserveHydrationSeedKeys?.has(operation.key as TKey))\n        rowKeys.add(operation.key as TKey)\n    for (const key of transaction.rowMetadataWrites.keys())\n      if (!transaction.preserveHydrationSeedKeys?.has(key))\n        metadataKeys.add(key)\n  }\n  return {\n    rows: (key) =>\n      (truncate !== undefined && truncatesSourceKey(truncate, key)) ||\n      rowKeys.has(key) ||\n      state.appliedAdapterKeys?.get(key) === true ||\n      (state.syncedData.has(key) && !state.hydrationSeedKeys.has(key)),\n    // A key whose row an applied adapter write deleted is in the map too.\n    metadata: (key) =>\n      (truncate !== undefined && truncatesSourceKey(truncate, key)) ||\n      metadataKeys.has(key) ||\n      state.appliedAdapterKeys?.has(key) === true,\n  }\n}\n\nexport class DbClient {\n  private collectionsById = new Map<string, CollectionRecord>()\n  private pendingHydration = new Map<string, Array<DehydratedCollectionChunk>>()\n  private liveQueries = new Map<string, LiveQueryRecord>()\n  // A committed reader cannot consume a later boundary's server snapshot.\n  // Retain transported records for server getters until this client cleans up.\n  private hydratedLiveQueries = new Map<string, LiveQueryRecord>()\n  private ssrQueryWaiters = new Map<\n    string,\n    Deferred<void> | { cause: unknown }\n  >()\n  private ssrStreamFailure: { cause: unknown } | undefined\n  private preloadedLiveQueries = new Map<\n    string,\n    {\n      collection: AnyCollection\n      observer: { dispose: () => void }\n      sources: ReadonlyArray<AnyCollection>\n    }\n  >()\n  private liveQueryResources = new Map<object, () => Promise<void>>()\n  private listeners = new Set<(event: DbClientEvent) => void>()\n  private ssrStreamingEnabled = false\n  private ssrServerCleanupEnabled = false\n  private lastLiveQueryTimestamp = 0\n  private readonly transactionScope = new TransactionScope()\n\n  constructor(private readonly options: DbClientOptions = {}) {}\n\n  getDependency<T>(key: string): T | undefined {\n    return this.options[key] as T | undefined\n  }\n\n  requireDependency<T>(key: string): T {\n    const dependency = this.getDependency<T>(key)\n    if (dependency === undefined) {\n      throw new Error(\n        devBuild() && process.env.NODE_ENV !== `production`\n          ? `DbClient is missing the required \"${key}\" dependency. Pass it explicitly when constructing the client: new DbClient({ ${key} }).`\n          : codedMessage(92, { key }),\n      )\n    }\n    return dependency\n  }\n\n  get activeTransaction() {\n    return this.transactionScope.getActiveTransaction()\n  }\n\n  createTransaction<T extends object = Record<string, unknown>>(\n    config: TransactionConfig<T>,\n  ) {\n    return this.transactionScope.createTransaction(config)\n  }\n\n  preloadLiveQuery(options: LiveQueryOptions): Promise<void> {\n    const deferredCollections: DeferredLiveQueryCollections = new Set()\n    let started:\n      | {\n          result: Promise<void>\n          registration?: { queryHash: string; record: LiveQueryRecord }\n        }\n      | undefined\n    let primaryFailure: { error: unknown } | undefined\n    try {\n      started = this.startLiveQueryPreload(options, deferredCollections)\n    } catch (error) {\n      primaryFailure = { error }\n    }\n\n    let resumeFailure: { error: unknown } | undefined\n    try {\n      resumeDeferredLiveQueryCollections(deferredCollections, true)\n    } catch (error) {\n      resumeFailure = { error }\n    }\n    if (primaryFailure) throw primaryFailure.error\n    if (resumeFailure) {\n      const registration = started?.registration\n      if (\n        registration &&\n        this.liveQueries.get(registration.queryHash) === registration.record\n      ) {\n        registration.record.fail(resumeFailure.error)\n        this.discardPreloadedLiveQuery(registration.queryHash)\n      }\n      void started?.result.catch(() => {})\n      throw resumeFailure.error\n    }\n    return started!.result\n  }\n\n  private discardPreloadedLiveQuery(queryHash: string): void {\n    const preloaded = this.preloadedLiveQueries.get(queryHash)\n    if (!preloaded) return\n    preloaded.observer.dispose()\n    void preloaded.collection.cleanup({ dependents: true }).catch(() => {})\n    this.preloadedLiveQueries.delete(queryHash)\n  }\n\n  private startLiveQueryPreload(\n    options: LiveQueryOptions,\n    deferredCollections: DeferredLiveQueryCollections,\n  ): {\n    result: Promise<void>\n    registration?: { queryHash: string; record: LiveQueryRecord }\n  } {\n    const prepared = prepareLiveQueryValue(options, this, deferredCollections)\n    validateCollectionIndexing(prepared as LiveQueryOptions)\n    const queryHash = getLiveQueryHash(prepared, options.queryKey)\n    const sources = getPreparedLiveQuerySources(prepared)\n    const existing = this.liveQueries.get(queryHash)\n    const rowOptions = getLiveQueryRowOptions(prepared)\n    this._assertLiveQuerySources(queryHash, sources, rowOptions)\n    if (\n      existing &&\n      (existing.status === `pending` ||\n        (existing.status === `success` &&\n          existing.snapshot?.status === undefined))\n    ) {\n      return { result: existing.promise }\n    }\n\n    this.discardPreloadedLiveQuery(queryHash)\n\n    const collection = createLiveQueryCollection({\n      ...(prepared as LiveQueryOptions),\n      startSync: true,\n    }) as AnyCollection\n    const observer = createLiveQueryObserver(collection, {\n      client: this,\n      queryHash,\n      mode: `wholesale`,\n    })\n    this.preloadedLiveQueries.set(queryHash, {\n      collection,\n      observer,\n      sources,\n    })\n\n    const result = this._registerLiveQuery(\n      queryHash,\n      collection.preload().then(() => observer.dehydrate()),\n      sources,\n      rowOptions,\n    )\n    return {\n      result,\n      registration: { queryHash, record: this.liveQueries.get(queryHash)! },\n    }\n  }\n\n  collection<\n    T extends StandardSchemaV1,\n    TKey extends string | number,\n    TUtils extends UtilsRecord,\n  >(\n    options: CollectionOptions<InferSchemaOutput<T>, TKey, T, TUtils> &\n      NonSingleResult,\n    materializeOptions?: CollectionMaterializeOptions<InferSchemaInput<T>>,\n  ): Collection<InferSchemaOutput<T>, TKey, TUtils, T, InferSchemaInput<T>> &\n    NonSingleResult\n  collection<\n    T extends StandardSchemaV1,\n    TKey extends string | number,\n    TUtils extends UtilsRecord,\n  >(\n    options: CollectionOptions<InferSchemaOutput<T>, TKey, T, TUtils> &\n      SingleResult,\n    materializeOptions?: CollectionMaterializeOptions<InferSchemaInput<T>>,\n  ): Collection<InferSchemaOutput<T>, TKey, TUtils, T, InferSchemaInput<T>> &\n    SingleResult\n  collection<\n    T extends object,\n    TKey extends string | number = string | number,\n    TUtils extends UtilsRecord = UtilsRecord,\n  >(\n    options: CollectionOptions<T, TKey, never, TUtils> & NonSingleResult,\n    materializeOptions?: CollectionMaterializeOptions<T>,\n  ): Collection<T, TKey, TUtils, never, T> & NonSingleResult\n  collection<\n    T extends object,\n    TKey extends string | number = string | number,\n    TUtils extends UtilsRecord = UtilsRecord,\n  >(\n    options: CollectionOptions<T, TKey, never, TUtils> & SingleResult,\n    materializeOptions?: CollectionMaterializeOptions<T>,\n  ): Collection<T, TKey, TUtils, never, T> & SingleResult\n  collection(\n    options: AnyCollectionOptions,\n    materializeOptions?: CollectionMaterializeOptions<any>,\n  ): AnyCollection {\n    return this.materializeCollection(options, materializeOptions, false)\n  }\n\n  /** @internal */\n  _materializeCollectionForRender<\n    T extends object,\n    TKey extends string | number,\n    TSchema extends StandardSchemaV1,\n    TUtils extends UtilsRecord,\n  >(\n    options: CollectionOptions<T, TKey, TSchema, TUtils>,\n  ): Collection<\n    T,\n    TKey,\n    TUtils,\n    TSchema,\n    [TSchema] extends [never] ? T : InferSchemaInput<TSchema>\n  > {\n    return this.materializeCollection(options, undefined, true)\n  }\n\n  private materializeCollection(\n    options: AnyCollectionOptions,\n    materializeOptions: CollectionMaterializeOptions<any> | undefined,\n    deferSyncStart: boolean,\n  ): AnyCollection {\n    const existing = this.collectionsById.get(options.id)\n    if (existing) {\n      return this.reuseMaterializedCollection(existing, deferSyncStart)\n    }\n\n    const config = options[collectionOptionsFactory](this)\n    const materializedDuringFactory = this.collectionsById.get(options.id)\n    if (materializedDuringFactory) {\n      return this.reuseMaterializedCollection(\n        materializedDuringFactory,\n        deferSyncStart,\n      )\n    }\n\n    const shouldStartSync = config.startSync === true\n    const collection = createCollection({\n      ...config,\n      startSync: false,\n    } as any)\n    collection._setTransactionScope(this.transactionScope)\n    collection._state.enableHydrationAuthorityTracking()\n    if (deferSyncStart) {\n      collection._deferSyncStart()\n    }\n\n    this.collectionsById.set(collection.id, {\n      collection,\n      shouldDehydrate: !deferSyncStart,\n      hydrated: this.pendingHydration.has(collection.id),\n    })\n\n    if (materializeOptions?.initialData?.length) {\n      this.applyRows(\n        collection,\n        {\n          collectionId: collection.id,\n          rows: materializeOptions.initialData.map((value) => ({ value })),\n        },\n        `initialData`,\n      )\n    }\n\n    const pendingChunks = this.pendingHydration.get(collection.id)\n    if (pendingChunks) {\n      for (const chunk of pendingChunks) {\n        this.applyRows(collection, chunk, `hydration`)\n      }\n      this.pendingHydration.delete(collection.id)\n    }\n\n    if (shouldStartSync) {\n      collection.startSyncImmediate()\n    }\n\n    return collection\n  }\n\n  private reuseMaterializedCollection(\n    record: CollectionRecord,\n    deferSyncStart: boolean,\n  ): AnyCollection {\n    if (deferSyncStart) {\n      record.collection._deferSyncStart()\n    } else {\n      record.shouldDehydrate = true\n    }\n    return record.collection\n  }\n\n  dehydrate(options: DehydrateDbClientOptions = {}): DehydratedDbState {\n    const collections: Array<DehydratedCollectionChunk> = []\n\n    for (const {\n      collection,\n      shouldDehydrate,\n    } of this.collectionsById.values()) {\n      const collectionDecision = options.shouldDehydrateCollection?.(collection)\n      if (\n        getBuilderFromConfig(collection.config) ||\n        collectionDecision === false ||\n        (!shouldDehydrate && collectionDecision !== true)\n      ) {\n        continue\n      }\n\n      const rows = Array.from(collection._state.syncedData.entries()).map(\n        ([key, value]) => {\n          const metadata = collection._state.syncedMetadata.get(key)\n          return {\n            key,\n            value,\n            ...(metadata === undefined ? {} : { metadata }),\n          }\n        },\n      )\n\n      collections.push({\n        collectionId: collection.id,\n        rows,\n        syncMeta: collection.config.sync.exportSyncMeta?.(),\n      })\n    }\n\n    const liveQueries = Array.from(this.liveQueries.values()).flatMap(\n      (query): Array<DehydratedLiveQuery> => {\n        const decision = options.shouldDehydrateLiveQuery?.(query)\n        const shouldDehydrate =\n          decision ??\n          (query.status === `success` || query.snapshot !== undefined)\n        if (!shouldDehydrate || query.status === `error`) {\n          return []\n        }\n\n        return [\n          {\n            queryHash: query.queryHash,\n            dehydratedAt: query.dehydratedAt,\n            ...(query.initialSnapshot &&\n            query.initialSnapshot !== query.snapshot\n              ? { initialSnapshot: query.initialSnapshot }\n              : {}),\n            ...(query.snapshot ? { snapshot: query.snapshot } : {}),\n            ...(query.status === `pending` &&\n            (!query.snapshot || this.ssrStreamingEnabled || decision === true)\n              ? { promise: query.resultPromise }\n              : {}),\n          },\n        ]\n      },\n    )\n\n    return {\n      collections,\n      ...(liveQueries.length > 0 ? { liveQueries } : {}),\n    }\n  }\n\n  hydrate(state: DehydratedDbState): void {\n    for (const chunk of state.collections) {\n      const record = this.collectionsById.get(chunk.collectionId)\n      if (record) {\n        record.hydrated = true\n        this.applyRows(record.collection, chunk, `hydration`)\n        continue\n      }\n\n      const pendingChunks = this.pendingHydration.get(chunk.collectionId) ?? []\n      pendingChunks.push(chunk)\n      this.pendingHydration.set(chunk.collectionId, pendingChunks)\n    }\n\n    for (const dehydratedQuery of state.liveQueries ?? []) {\n      this.hydrateLiveQuery(dehydratedQuery)\n    }\n  }\n\n  applyCollectionChunk(chunk: DehydratedCollectionChunk): void {\n    this.hydrate({ collections: [chunk] })\n  }\n\n  subscribe(listener: (event: DbClientEvent) => void): () => void {\n    this.listeners.add(listener)\n    return () => this.listeners.delete(listener)\n  }\n\n  /** @internal Supply transport behavior without coupling ordinary observers to SSR. */\n  _bindLiveQueryObserver<T extends object, TKey extends string | number>(\n    collection: Collection<T, TKey, any> | null,\n    queryHash: string | undefined,\n    suspendUntilReady: boolean,\n    host: LiveQueryObserverClientHost<T, TKey>,\n  ): LiveQueryObserverClient<T, TKey> {\n    return new LiveQueryObserverClient(\n      this,\n      collection,\n      queryHash,\n      suspendUntilReady,\n      host,\n    )\n  }\n\n  /** @internal Normalized source transport carries rows, not readiness. */\n  _hasSsrCollectionSnapshot(collection: AnyCollection): boolean {\n    const sources = getBuilderFromConfig(\n      collection.config,\n    )?.getSourceCollections()\n    if (sources)\n      return sources.every((source) => this._hasSsrCollectionSnapshot(source))\n    const record = this.collectionsById.get(collection.id)\n    return (\n      record?.collection === collection &&\n      (record.shouldDehydrate || record.hydrated)\n    )\n  }\n\n  /** @internal */\n  _setSsrStreamingEnabled(enabled: boolean): void {\n    if (enabled && !this.ssrStreamingEnabled) {\n      this.ssrStreamFailure = undefined\n      this.ssrQueryWaiters.clear()\n    } else if (!enabled && this.ssrStreamingEnabled && !this.ssrStreamFailure)\n      this.failSsrQueryWaiters(\n        new Error(\n          devBuild() && process.env.NODE_ENV !== `production`\n            ? `The DB stream ended before the server-rendered query snapshot arrived.`\n            : codedMessage(253),\n        ),\n      )\n    this.ssrStreamingEnabled = enabled\n  }\n\n  /** @internal Wait for transport without claiming or starting a local source. */\n  _waitForSsrLiveQuery(\n    queryHash: string,\n    forHydration = false,\n  ): Promise<void> | undefined {\n    let waiter = this.ssrQueryWaiters.get(queryHash)\n    if (waiter && `cause` in waiter) throw waiter.cause\n    if (!forHydration || this.hydratedLiveQueries.has(queryHash)) return\n    if (this.ssrStreamFailure) {\n      this.ssrQueryWaiters.set(queryHash, this.ssrStreamFailure)\n      throw this.ssrStreamFailure.cause\n    }\n    if (!this.ssrStreamingEnabled) return\n    if (!waiter) {\n      waiter = createDeferred<void>()\n      waiter.promise.catch(() => {})\n      this.ssrQueryWaiters.set(queryHash, waiter)\n    }\n    return waiter.promise\n  }\n\n  private failSsrQueryWaiters(cause: unknown): void {\n    // The wrapper distinguishes a terminal undefined cause from an open stream.\n    this.ssrStreamFailure ??= { cause }\n    for (const [queryHash, waiter] of this.ssrQueryWaiters) {\n      this.ssrQueryWaiters.set(queryHash, this.ssrStreamFailure)\n      if (`promise` in waiter) waiter.reject(this.ssrStreamFailure.cause)\n    }\n  }\n\n  /** @internal */\n  _isSsrStreamingEnabled(): boolean {\n    return this.ssrStreamingEnabled\n  }\n\n  /** @internal */\n  _setSsrServerCleanupEnabled(enabled: boolean): void {\n    this.ssrServerCleanupEnabled = enabled\n  }\n\n  /** @internal */\n  _isSsrServerCleanupEnabled(): boolean {\n    return this.ssrServerCleanupEnabled\n  }\n\n  /** @internal */\n  _getLiveQuery(\n    queryHash: string,\n    forServerSnapshot = false,\n  ): DbClientLiveQuery | undefined {\n    return (\n      (forServerSnapshot && this.hydratedLiveQueries.get(queryHash)) ||\n      this.liveQueries.get(queryHash)\n    )\n  }\n\n  /** @internal Reject incompatible local sources or row behavior for a reusable stream. */\n  _assertLiveQuerySources(\n    queryHash: string,\n    sources: ReadonlyArray<AnyCollection>,\n    rowOptions?: LiveQueryRowOptions,\n  ): void {\n    const record = this.liveQueries.get(queryHash)\n    // A failed or consumed stream has no result to reuse and claims no sources.\n    if (!record || record.status === `error`) return\n    const priorSources =\n      record.sources ?? this.preloadedLiveQueries.get(queryHash)?.sources\n    if (\n      (priorSources && !sameSourcesAtEachPosition(priorSources, sources)) ||\n      (rowOptions &&\n        record.rowOptions &&\n        rowOptions.some(\n          (option, index) => option !== record.rowOptions![index],\n        ))\n    ) {\n      throw new Error(\n        devBuild() && process.env.NODE_ENV !== `production`\n          ? `DbClient cannot reuse live query \"${queryHash}\" with different source Collections or getKey/schema options. Use the same Collection objects and options, or a distinct query key.`\n          : codedMessage(234, { queryHash }),\n      )\n    }\n    record.rowOptions ??= rowOptions\n    // Hydration has a portable hash but no server-side Collection objects.\n    // The first local consumer claims them for later same-hash requests.\n    if (!record.sources) record.sources = [...sources]\n  }\n\n  /** @internal */\n  _consumeLiveQueryResult(queryHash: string, dehydratedAt: number): void {\n    const record = this.liveQueries.get(queryHash)\n    if (record?.dehydratedAt === dehydratedAt) {\n      this.liveQueries.delete(queryHash)\n    }\n  }\n\n  /** @internal Capture the first server view without starting acquisition. */\n  _captureServerQuery(\n    queryHash: string,\n    snapshot: DehydratedLiveQueryResult,\n    sources?: ReadonlyArray<AnyCollection>,\n    rowOptions?: LiveQueryRowOptions,\n  ): void {\n    const existing = this.liveQueries.get(queryHash)\n    if (existing) {\n      if (sources) this._assertLiveQuerySources(queryHash, sources, rowOptions)\n      if (\n        existing.snapshot &&\n        (snapshot.status === undefined || existing.initialSnapshot)\n      )\n        return\n      if (snapshot.status !== undefined) existing.initialSnapshot ??= snapshot\n      existing.snapshot ??= snapshot\n      // A queued promise cannot carry an ordinary reader's later initial view.\n      // Advance transport without replacing that promise or its source claim.\n      existing.dehydratedAt = this.nextLiveQueryTimestamp()\n      this.emit({ type: `liveQueryUpdated`, query: existing })\n      return\n    }\n    const record = this.createLiveQueryRecord(\n      queryHash,\n      this.nextLiveQueryTimestamp(),\n    )\n    record.rowOptions = rowOptions\n    record.sources = sources\n    if (snapshot.status !== undefined) record.initialSnapshot = snapshot\n    this.liveQueries.set(queryHash, record)\n    this.emit({ type: `liveQueryAdded`, query: record })\n    record.succeed(snapshot)\n  }\n\n  /** @internal */\n  _registerLiveQuery(\n    queryHash: string,\n    promise: Promise<DehydratedLiveQueryResult>,\n    sources?: ReadonlyArray<AnyCollection>,\n    rowOptions?: LiveQueryRowOptions,\n  ): Promise<void> {\n    // Observe even a rejected incoming promise when a source conflict discards it.\n    void Promise.resolve(promise).catch(() => {})\n    if (sources) this._assertLiveQuerySources(queryHash, sources, rowOptions)\n    const existing = this.liveQueries.get(queryHash)\n    if (\n      existing &&\n      (existing.status === `pending` ||\n        (existing.status === `success` &&\n          existing.snapshot?.status === undefined))\n    ) {\n      return existing.promise\n    }\n\n    const record = this.createLiveQueryRecord(\n      queryHash,\n      this.nextLiveQueryTimestamp(),\n    )\n    record.rowOptions = rowOptions\n    record.sources = sources\n    record.initialSnapshot = existing?.initialSnapshot\n\n    this.liveQueries.set(queryHash, record)\n    this.emit({ type: `liveQueryAdded`, query: record })\n    Promise.resolve(promise).then(record.succeed, record.fail)\n    return record.promise\n  }\n\n  /** @internal */\n  _registerLiveQueryResource(\n    owner: object,\n    cleanup: () => Promise<void>,\n  ): () => void {\n    this.liveQueryResources.set(owner, cleanup)\n    return () => {\n      if (this.liveQueryResources.get(owner) === cleanup) {\n        this.liveQueryResources.delete(owner)\n      }\n    }\n  }\n\n  /** @internal */\n  _failPendingLiveQueries(error: unknown): void {\n    this.failSsrQueryWaiters(error)\n    for (const record of this.liveQueries.values()) {\n      if (record.status === `pending`) record.fail(error)\n    }\n    this.emit({ type: `liveQueryStreamError`, error })\n  }\n\n  async cleanup(): Promise<void> {\n    try {\n      const materializedCollections = Array.from(\n        this.collectionsById.values(),\n        ({ collection }) => collection,\n      )\n      const preloadedQueries = Array.from(this.preloadedLiveQueries.values())\n      const liveQueryCollections = new Set([\n        ...preloadedQueries.map(({ collection }) => collection),\n        ...materializedCollections.filter((collection) =>\n          getBuilderFromConfig(collection.config),\n        ),\n      ])\n\n      for (const { observer } of preloadedQueries) observer.dispose()\n\n      const cleanupResults = [\n        ...(await Promise.allSettled(\n          Array.from(this.liveQueryResources.values(), (cleanup) => cleanup()),\n        )),\n        ...(await Promise.allSettled(\n          Array.from(liveQueryCollections, (collection) =>\n            collection.cleanup({ dependents: true }),\n          ),\n        )),\n        ...(await Promise.allSettled(\n          materializedCollections\n            .filter((collection) => !liveQueryCollections.has(collection))\n            .map((collection) => collection.cleanup({ dependents: true })),\n        )),\n      ]\n      const failure = cleanupResults.find(\n        (result): result is PromiseRejectedResult =>\n          result.status === `rejected`,\n      )\n      if (failure) throw failure.reason\n    } finally {\n      this._setSsrStreamingEnabled(false)\n      this.transactionScope.clear()\n      this.collectionsById.clear()\n      this.pendingHydration.clear()\n      this.liveQueries.clear()\n      this.hydratedLiveQueries.clear()\n      this.preloadedLiveQueries.clear()\n      this.liveQueryResources.clear()\n      this.listeners.clear()\n      this.ssrServerCleanupEnabled = false\n      this.lastLiveQueryTimestamp = 0\n    }\n  }\n\n  private hydrateLiveQuery(dehydratedQuery: DehydratedLiveQuery): void {\n    const existing = this.liveQueries.get(dehydratedQuery.queryHash)\n    // Browser preload time cannot order server transport versions. Apply the\n    // active-record guard only when that active record came from transport.\n    if (\n      existing &&\n      existing === this.hydratedLiveQueries.get(dehydratedQuery.queryHash) &&\n      existing.dehydratedAt >= dehydratedQuery.dehydratedAt\n    ) {\n      return\n    }\n\n    const record = this.createLiveQueryRecord(\n      dehydratedQuery.queryHash,\n      dehydratedQuery.dehydratedAt,\n    )\n    if (existing?.status === `error`) {\n      this.discardPreloadedLiveQuery(dehydratedQuery.queryHash)\n    } else {\n      record.sources = existing?.sources\n      record.rowOptions = existing?.rowOptions\n    }\n    this.liveQueries.set(record.queryHash, record)\n    if (existing?.status === `pending`) {\n      void record.resultPromise.then(existing.succeed, existing.fail)\n    }\n    record.initialSnapshot =\n      dehydratedQuery.initialSnapshot ?? dehydratedQuery.snapshot\n    this.hydratedLiveQueries.set(record.queryHash, record)\n    const waiter = this.ssrQueryWaiters.get(record.queryHash)\n    if (waiter && `promise` in waiter) waiter.resolve()\n    this.ssrQueryWaiters.delete(record.queryHash)\n    if (dehydratedQuery.promise) record.snapshot = dehydratedQuery.snapshot\n    this.emit({ type: `liveQueryAdded`, query: record })\n\n    if (dehydratedQuery.snapshot && !dehydratedQuery.promise) {\n      record.succeed(dehydratedQuery.snapshot)\n    } else if (dehydratedQuery.promise) {\n      Promise.resolve(dehydratedQuery.promise).then(record.succeed, record.fail)\n    } else {\n      record.fail(\n        new Error(\n          devBuild() && process.env.NODE_ENV !== `production`\n            ? `Dehydrated live query \"${dehydratedQuery.queryHash}\" has neither a snapshot nor a promise.`\n            : codedMessage(93, { queryHash: dehydratedQuery.queryHash }),\n        ),\n      )\n    }\n  }\n\n  private nextLiveQueryTimestamp(): number {\n    this.lastLiveQueryTimestamp = Math.max(\n      Date.now(),\n      this.lastLiveQueryTimestamp + 1,\n    )\n    return this.lastLiveQueryTimestamp\n  }\n\n  private createLiveQueryRecord(\n    queryHash: string,\n    dehydratedAt: number,\n  ): LiveQueryRecord {\n    this.lastLiveQueryTimestamp = Math.max(\n      this.lastLiveQueryTimestamp,\n      dehydratedAt,\n    )\n\n    let resolveResult!: (snapshot: DehydratedLiveQueryResult) => void\n    let rejectResult!: (error: unknown) => void\n    let settled = false\n    const resultPromise = new Promise<DehydratedLiveQueryResult>(\n      (resolve, reject) => {\n        resolveResult = resolve\n        rejectResult = reject\n      },\n    )\n    const promise = resultPromise.then(() => undefined)\n    resultPromise.catch(() => {})\n    promise.catch(() => {})\n\n    const record: LiveQueryRecord = {\n      queryHash,\n      dehydratedAt,\n      status: `pending`,\n      promise,\n      resultPromise,\n      succeed: (snapshot) => {\n        if (settled) return\n        settled = true\n        record.status = `success`\n        record.snapshot = snapshot\n        resolveResult(snapshot)\n        if (this.liveQueries.get(queryHash) === record) {\n          this.emit({ type: `liveQueryUpdated`, query: record })\n        }\n      },\n      fail: (error) => {\n        if (settled) return\n        settled = true\n        record.status = `error`\n        record.error = error\n        rejectResult(error)\n        if (this.liveQueries.get(queryHash) === record) {\n          this.emit({ type: `liveQueryUpdated`, query: record })\n        }\n      },\n    }\n\n    return record\n  }\n\n  private emit(event: DbClientEvent): void {\n    for (const listener of this.listeners) {\n      listener(event)\n    }\n  }\n\n  private applyRows(\n    collection: Collection<any, string | number, any, any, any>,\n    chunk: Omit<DehydratedCollectionChunk, `rows`> & {\n      rows: Array<\n        Omit<DehydratedCollectionRow, `key`> & {\n          key?: string | number\n        }\n      >\n    },\n    seedKind?: `initialData` | `hydration`,\n  ): void {\n    // A hydration seed supplies only the row data and row metadata that no\n    // committed adapter write has written; each object is judged alone.\n    const hydrating = seedKind === `hydration`\n    const authority = createAdapterAuthorityLookups(collection._state)\n    const seeds = chunk.rows.map((row) => {\n      const value = collection.validateData(row.value, `insert`)\n      return { ...row, key: collection.config.getKey(value), value }\n    })\n    const rows = seeds.filter((row) => !hydrating || !authority.rows(row.key))\n    const rowMetadataWrites = new Map<string | number, PendingMetadataWrite>()\n\n    for (const row of seeds) {\n      if (hydrating && authority.metadata(row.key)) continue\n      // The latest seed wins whole, so one without metadata clears it.\n      if (row.metadata !== undefined)\n        rowMetadataWrites.set(row.key, { type: `set`, value: row.metadata })\n      else if (hydrating) rowMetadataWrites.set(row.key, { type: `delete` })\n    }\n\n    if (seedKind) {\n      for (const row of rows) {\n        collection._state.hydrationSeedKeys.add(row.key)\n        if (seedKind === `hydration`) {\n          collection._state.hydratedKeys.add(row.key)\n        }\n      }\n    }\n\n    if (rows.length > 0 || rowMetadataWrites.size > 0) {\n      const applied = createDeferred<void>()\n      // Nothing awaits a seed's receipt; cleanup may still reject it.\n      void applied.promise.catch(() => undefined)\n      collection._state.acceptSyncTransaction({\n        committed: true,\n        applicationStarted: false,\n        layoutChanged: false,\n        // A seed replaces any earlier seed of its row whole.\n        operations: rows.map((row) => ({\n          type: `insert` as const,\n          key: row.key,\n          value: row.value,\n        })),\n        rowMetadataWrites,\n        // An accepted transaction's metadata writes are never rebuilt.\n        explicitRowMetadataWrites: new Map(),\n        collectionMetadataWrites: new Map(),\n        applied,\n        // A seed chunk keeps its keys' seed status.\n        preserveHydrationSeedKeys: seedKind\n          ? new Set([\n              ...rows.map((row) => row.key),\n              ...rowMetadataWrites.keys(),\n            ])\n          : undefined,\n      })\n    }\n\n    if (chunk.syncMeta !== undefined) {\n      const currentMeta = collection.config.sync.exportSyncMeta?.()\n      const mergedMeta =\n        currentMeta === undefined\n          ? chunk.syncMeta\n          : (collection.config.sync.mergeSyncMeta?.(\n              currentMeta,\n              chunk.syncMeta,\n            ) ?? chunk.syncMeta)\n      collection.config.sync.importSyncMeta?.(mergedMeta)\n    }\n  }\n}\n"],"mappings":";;;;;;;;;;;;;AAgDA,IAAM,0BAAyC,uBAAO,IACpD,uCACF;AAcA,SAAS,0BACP,MACA,OACS;CACT,OACE,KAAK,WAAW,MAAM,UACtB,KAAK,OAAO,QAAQ,UAAU,WAAW,MAAM,MAAM;AAEzD;AAkCA,SAAgB,4BAGd,QACA,SACA,OACsC;CACtC,OAAO,eAAe,QAAQ,yBAAyB;EACrD,OAAO;EACP,YAAY;CACd,CAAC;CACD,IAAI,OACF,OAAO,eAAe,QAAQA,2BAAAA,wBAAwB;EACpD,OAAO;EACP,YAAY;CACd,CAAC;CAEH,OAAO;AACT;AA0IA,SAAgB,kBACd,aACA,iBACK;CACL,MAAM,SAAS,OAAO,gBAAgB,WAAW,KAAA,IAAY;CAC7D,MAAM,KAAK,OAAO,gBAAgB,WAAW,cAAc,YAAY;CAEvE,IAAI,CAAC,IACH,MAAM,IAAI,MACR,sCAAA,SAAS,KAAA,QAAA,IAAA,aAA8B,eACnC,iIACA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