{"version":3,"file":"changes.cjs","names":["codedMessage","createSingleRowRefProxy","toExpression","CollectionSubscription","getBuilderFromConfig","NegativeActiveSubscribersError","layoutChangeListeners","subscriberOrPreload","subscriberOrPreloadListeners","enrichChangeWithVirtualProps","composeBatchedChange","deferral","publishEvents","addSubscriber","resumeSubscriber","removeSubscriber","startSyncForSubscriber","changeAcquiringSubscribers","startSyncIfStopped"],"sources":["../../../src/collection/changes.ts"],"sourcesContent":["import { NegativeActiveSubscribersError } from '../errors'\nimport { recordPublicationError, withPublicationContext } from '../scheduler.js'\nimport { runAllCallbacks } from '../utils/callbacks.js'\nimport {\n  createSingleRowRefProxy,\n  toExpression,\n} from '../query/builder/ref-proxy.js'\nimport { codedMessage, devBuild } from '../error-message.js'\nimport { getBuilderFromConfig } from '../query/live/collection-registry.js'\nimport { CollectionSubscription } from './subscription.js'\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type { ChangeMessage, SubscribeChangesOptions } from '../types'\nimport type { CollectionLifecycleManager } from './lifecycle.js'\nimport type { CollectionSyncManager } from './sync.js'\nimport type { CollectionEventsManager } from './events.js'\nimport type { CollectionImpl } from './index.js'\nimport type { CollectionStateManager } from './state.js'\nimport type { WithVirtualProps } from '../virtual-props.js'\n\nexport type PublicationDeferral = {\n  publish: () => void\n  discard: () => void\n}\n\nexport class CollectionChangesManager<\n  TOutput extends object = Record<string, unknown>,\n  TKey extends string | number = string | number,\n  TSchema extends StandardSchemaV1 = StandardSchemaV1,\n  TInput extends object = TOutput,\n> {\n  private lifecycle!: CollectionLifecycleManager<TOutput, TKey, TSchema, TInput>\n  private sync!: CollectionSyncManager<TOutput, TKey, TSchema, TInput>\n  private events!: CollectionEventsManager\n  private collection!: CollectionImpl<TOutput, TKey, any, TSchema, TInput>\n  private state!: CollectionStateManager<TOutput, TKey, TSchema, TInput>\n\n  public activeSubscribersCount = 0\n  // Subscribers that ask for data: every one except a subscription that still\n  // defers acquisition. `subscriberCount` and `subscribers:change` report it;\n  // garbage collection uses `activeSubscribersCount`.\n  public acquiringSubscribersCount = 0\n  public changeSubscriptions = new Set<CollectionSubscription>()\n  public batchedEvents: Array<ChangeMessage<TOutput, TKey>> = []\n  public shouldBatchEvents = false\n  private deferral:\n    | {\n        depth: number\n        discard: boolean\n        layoutRevision: number\n        publications: Array<{\n          changes: Array<ChangeMessage<TOutput, TKey>>\n          layoutChanged: boolean\n        }>\n      }\n    | undefined\n  private layoutChangeListeners = new Set<() => void>()\n  // Whether this Collection has had a subscriber or a preload in its current\n  // sync run. A live-query Collection defers acquisition on its own source\n  // subscriptions until then.\n  private subscriberOrPreload = false\n  private subscriberOrPreloadListeners = new Set<() => void>()\n\n  /**\n   * Monotonic revision of the collection's visible state, advanced once per\n   * committed batch of changes, cleanup, and discarded layout epochs — even\n   * while nothing is subscribed.\n   * Lets consumers (the live-query observer) cheaply detect \"did the data\n   * change\" without subscribing, and stays untouched by subscription\n   * bootstrap replays, which do not go through emitEvents.\n   */\n  public stateRevision = 0\n\n  /**\n   * Revision of explicit layout-only publications. A discarded deferral can\n   * restore it; stateRevision fences that invalidation for detached observers.\n   */\n  public layoutRevision = 0\n\n  /**\n   * Creates a new CollectionChangesManager instance\n   */\n  constructor() {}\n\n  public setDeps(deps: {\n    lifecycle: CollectionLifecycleManager<TOutput, TKey, TSchema, TInput>\n    sync: CollectionSyncManager<TOutput, TKey, TSchema, TInput>\n    events: CollectionEventsManager\n    collection: CollectionImpl<TOutput, TKey, any, TSchema, TInput>\n    state: CollectionStateManager<TOutput, TKey, TSchema, TInput>\n  }) {\n    this.lifecycle = deps.lifecycle\n    this.sync = deps.sync\n    this.events = deps.events\n    this.collection = deps.collection\n    this.state = deps.state\n  }\n\n  /**\n   * Emit an empty ready event to notify subscribers that the collection is ready\n   * This bypasses the normal empty array check in emitEvents\n   */\n  public emitEmptyReadyEvent(): void {\n    withPublicationContext(() => {\n      try {\n        runAllCallbacks(\n          [...this.changeSubscriptions].map(\n            (subscription) => () => subscription.emitEvents([]),\n          ),\n        )\n      } catch (error) {\n        recordPublicationError(error)\n      }\n    })\n  }\n\n  /**\n   * Enriches a change message with virtual properties ($hasPendingWrites, $origin, $key, $collectionId).\n   * Uses the \"add-if-missing\" pattern to preserve virtual properties from upstream collections.\n   */\n  private enrichChangeWithVirtualProps(\n    change: ChangeMessage<TOutput, TKey>,\n  ): ChangeMessage<WithVirtualProps<TOutput, TKey>, TKey> {\n    return this.state.enrichChangeMessage(change)\n  }\n\n  // Reduce unpublished same-key changes relative to the subscriber's last\n  // visible row: keep the earliest previous row and latest value, and cancel\n  // an insert followed by a delete.\n  private composeBatchedChange(\n    pending: ChangeMessage<TOutput, TKey> | undefined,\n    change: ChangeMessage<TOutput, TKey>,\n  ): ChangeMessage<TOutput, TKey> | undefined {\n    if (!pending) return change\n\n    if (pending.type === `insert`) {\n      if (change.type === `delete`) return undefined\n      return { ...change, type: `insert`, previousValue: undefined }\n    }\n\n    const previousValue =\n      pending.type === `update`\n        ? (pending.previousValue ?? pending.value)\n        : pending.value\n\n    if (change.type === `delete`) {\n      return { ...change, value: previousValue, previousValue: undefined }\n    }\n\n    return { ...change, type: `update`, previousValue }\n  }\n\n  /**\n   * Emit events either immediately or batch them for later emission\n   */\n  public emitEvents(\n    changes: Array<ChangeMessage<TOutput, TKey>>,\n    forceEmit = false,\n    layoutChanged = false,\n  ): void {\n    // The visible state was already committed by the caller, so the revision\n    // advances even when the events below end up batched for later emission.\n    if (changes.length > 0) this.stateRevision++\n    if (layoutChanged) this.layoutRevision++\n\n    // Skip batching for user actions (forceEmit=true) to keep UI responsive\n    if (this.shouldBatchEvents && !forceEmit) {\n      // Snapshot virtual properties before later state changes can replace them.\n      this.batchedEvents.push(\n        ...changes.map((change) => this.enrichChangeWithVirtualProps(change)),\n      )\n      return\n    }\n\n    // Either we're not batching, or we're forcing emission (user action or ending batch cycle)\n    let rawEvents = changes\n\n    if (forceEmit) {\n      // Force emit is used to end a batch (e.g. after a sync commit). Combine any\n      // buffered optimistic events with the final changes so subscribers see the\n      // whole picture, even if the sync diff is empty.\n      if (this.batchedEvents.length > 0) {\n        // Undefined tombstones retain each key's first-seen publication order\n        // when an insert/delete pair cancels before a later change revives it.\n        const combined = new Map<\n          TKey,\n          ChangeMessage<TOutput, TKey> | undefined\n        >()\n        for (const change of [...this.batchedEvents, ...changes]) {\n          combined.set(\n            change.key,\n            this.composeBatchedChange(combined.get(change.key), change),\n          )\n        }\n        rawEvents = [...combined.values()].flatMap((change) => {\n          return change ? [change] : []\n        })\n      }\n      this.batchedEvents = []\n      this.shouldBatchEvents = false\n    }\n\n    if (this.deferral) {\n      this.deferral.publications.push({ changes: rawEvents, layoutChanged })\n      return\n    }\n\n    this.publishEvents(rawEvents, layoutChanged)\n  }\n\n  /**\n   * Defers subscriber delivery while a coherent multi-Collection publication\n   * installs all of its visible state. State and indexes still commit at their\n   * normal transaction boundaries.\n   */\n  public deferPublication(): PublicationDeferral {\n    const deferral = (this.deferral ??= {\n      depth: 0,\n      discard: false,\n      layoutRevision: this.layoutRevision,\n      publications: [],\n    })\n    deferral.depth++\n    let closed = false\n\n    const close = (discard: boolean) => {\n      // Cleanup can retire this handle while a later sync run owns a deferral.\n      if (closed || this.deferral !== deferral) return\n      closed = true\n      deferral.discard ||= discard\n\n      if (--deferral.depth > 0) return\n\n      const publications = deferral.publications\n      deferral.publications = []\n      this.deferral = undefined\n      if (deferral.discard) {\n        // State already committed, so its row clock must never rewind. A\n        // discarded layout clock also needs a fresh invalidation token: a\n        // detached observer may have read while delivery was deferred.\n        if (this.layoutRevision !== deferral.layoutRevision)\n          this.stateRevision++\n        this.layoutRevision = deferral.layoutRevision\n        return\n      }\n      this.publishEvents(\n        publications.flatMap(({ changes }) => changes),\n        publications.some(({ layoutChanged }) => layoutChanged),\n      )\n    }\n\n    return {\n      publish: () => close(false),\n      discard: () => close(true),\n    }\n  }\n\n  private publishEvents(\n    rawEvents: Array<ChangeMessage<TOutput, TKey>>,\n    layoutChanged: boolean,\n  ): void {\n    if (rawEvents.length === 0 && !layoutChanged) {\n      return\n    }\n\n    // Enrich all change messages with virtual properties\n    // This uses the \"add-if-missing\" pattern to preserve pass-through semantics\n    const enrichedEvents: Array<\n      ChangeMessage<WithVirtualProps<TOutput, TKey>, TKey>\n    > = rawEvents.map((change) => this.enrichChangeWithVirtualProps(change))\n\n    // Every subscriber sees one committed source batch before dependent query\n    // graphs run. This keeps repeated aliases and sibling subqueries coherent.\n    const layoutListeners = [...this.layoutChangeListeners]\n    const subscriptions = [...this.changeSubscriptions]\n    withPublicationContext(() => {\n      const callbacks: Array<() => void> = subscriptions.map(\n        (subscription) => () => subscription.emitEvents(enrichedEvents),\n      )\n      if (rawEvents.length === 0) {\n        callbacks.unshift(...layoutListeners)\n      }\n      try {\n        runAllCallbacks(callbacks)\n      } catch (error) {\n        recordPublicationError(error)\n      }\n    })\n  }\n\n  /** Subscribe to layout-only publications. Internal observer channel. */\n  public subscribeLayoutChanges(listener: () => void): () => void {\n    this.layoutChangeListeners.add(listener)\n    return () => this.layoutChangeListeners.delete(listener)\n  }\n\n  /**\n   * Subscribe to changes in the collection\n   */\n  public subscribeChanges(\n    callback: (\n      changes: Array<ChangeMessage<WithVirtualProps<TOutput, TKey>, TKey>>,\n    ) => void,\n    options: SubscribeChangesOptions<TOutput, TKey> = {},\n  ): CollectionSubscription {\n    // Compile where callback to whereExpression if provided\n    if (options.where && options.whereExpression) {\n      throw new Error(\n        devBuild() && process.env.NODE_ENV !== `production`\n          ? `Cannot specify both 'where' and 'whereExpression' options. Use one or the other.`\n          : codedMessage(95),\n      )\n    }\n\n    const { where, ...opts } = options\n    let whereExpression = opts.whereExpression\n    if (where) {\n      const proxy = createSingleRowRefProxy<\n        WithVirtualProps<TOutput, TKey>,\n        TKey\n      >()\n      const result = where(proxy)\n      whereExpression = toExpression(result)\n    }\n\n    // Acquire ownership only after all fallible option validation and\n    // user-provided predicate compilation has completed.\n    const defersAcquisition = opts.deferAcquisition === true\n    this.addSubscriber(defersAcquisition)\n\n    let subscription: CollectionSubscription | undefined\n    const setupState = { closed: false }\n    try {\n      subscription = new CollectionSubscription(this.collection, callback, {\n        ...opts,\n        whereExpression,\n        deferAcquisition: defersAcquisition,\n        onResumeAcquisition: () => this.resumeSubscriber(),\n        onUnsubscribe: () => {\n          setupState.closed = true\n          this.removeSubscriber(subscription?.isDeferringAcquisition() ?? false)\n          if (subscription) this.changeSubscriptions.delete(subscription)\n        },\n      })\n\n      // Register status listener BEFORE requesting snapshot to avoid race condition.\n      // This ensures the listener catches all status transitions, even if the\n      // loadSubset promise resolves synchronously or very quickly.\n      if (options.onStatusChange) {\n        subscription.on(`status:change`, options.onStatusChange)\n      }\n\n      if (options.includeInitialState) {\n        subscription.requestSnapshot({\n          trackLoadSubsetPromise: false,\n          orderBy: options.orderBy,\n          limit: options.limit,\n          onLoadSubsetResult: options.onLoadSubsetResult,\n        })\n      } else if (options.includeInitialState === false) {\n        // When explicitly set to false (not just undefined), mark all state as \"seen\"\n        // so that all future changes (including deletes) pass through unfiltered.\n        subscription.markAllStateAsSeen()\n      }\n\n      // Add to batched listeners\n      if (!setupState.closed) this.changeSubscriptions.add(subscription)\n    } catch (error) {\n      if (subscription) {\n        try {\n          subscription.unsubscribe()\n        } catch {\n          // Preserve the setup error. Cleanup still releases subscriber\n          // ownership and attempts every subset unload before it throws.\n        }\n      } else {\n        this.removeSubscriber(defersAcquisition)\n      }\n      throw error\n    }\n\n    return subscription\n  }\n\n  /** Whether this Collection had a subscriber or a preload in this sync run. */\n  public hasSubscriberOrPreload(): boolean {\n    return this.subscriberOrPreload || this.acquiringSubscribersCount > 0\n  }\n\n  /** Listen for the first subscriber or preload in the current sync run. */\n  public onFirstSubscriberOrPreload(listener: () => void): () => void {\n    this.subscriberOrPreloadListeners.add(listener)\n    return () => this.subscriberOrPreloadListeners.delete(listener)\n  }\n\n  /**\n   * Record a subscriber or a preload in the current sync run. A live-query\n   * Collection listens for the first one to resume deferred acquisition on its\n   * own source subscriptions.\n   */\n  public markSubscriberOrPreload(): void {\n    if (this.subscriberOrPreload) return\n    this.subscriberOrPreload = true\n    // One source's failed start must not keep the others deferred.\n    const errors: Array<unknown> = []\n    for (const listener of [...this.subscriberOrPreloadListeners]) {\n      try {\n        listener()\n      } catch (error) {\n        errors.push(error)\n      }\n    }\n    if (errors.length) throw errors[0]\n  }\n\n  /** A deferring subscription resumed: it may now start this sync run. */\n  private resumeSubscriber(): () => void {\n    this.lifecycle.assertCanStartSync()\n    this.startSyncForSubscriber()\n    return () => this.changeAcquiringSubscribers(1)\n  }\n\n  private startSyncForSubscriber(): void {\n    const syncRunGeneration = this.sync.getSyncRunGeneration()\n    // Mark first, so a sync run that starts now builds non-deferred demand.\n    this.markSubscriberOrPreload()\n    // A first-demand callback may itself retire this start.\n    if (syncRunGeneration !== this.sync.getSyncRunGeneration()) return\n    this.startSyncIfStopped()\n    // Independent demand releases even an abandoned render's sync-start gate.\n    this.sync.resumeStart()\n  }\n\n  private changeAcquiringSubscribers(delta: 1 | -1): void {\n    const previous = this.acquiringSubscribersCount\n    this.acquiringSubscribersCount += delta\n    this.events.emitSubscribersChange(this.acquiringSubscribersCount, previous)\n    // Cleanup during startup can clear the earlier demand mark. Commit it for\n    // surviving owners, including a replacement started by a cleanup listener.\n    if (delta === 1 && this.acquiringSubscribersCount > 0) {\n      this.markSubscriberOrPreload()\n    }\n  }\n\n  private startSyncIfStopped(): void {\n    if (\n      this.lifecycle.status === `cleaned-up` ||\n      this.lifecycle.status === `idle`\n    ) {\n      this.sync.startSync()\n    }\n  }\n\n  /**\n   * Increment the active subscribers count and start sync if needed. A\n   * subscriber that defers acquisition starts no provider work. It still\n   * starts a live-query Collection, whose sync run reads local memory and\n   * defers its own acquisition, but no other Collection's sync run.\n   */\n  private addSubscriber(defersAcquisition: boolean): void {\n    if (!defersAcquisition) this.lifecycle.assertCanStartSync()\n    this.activeSubscribersCount++\n    this.lifecycle.cancelGCTimer()\n    let acquiring = false\n\n    try {\n      if (!defersAcquisition) {\n        this.startSyncForSubscriber()\n      } else if (\n        !this.lifecycle.isCleaningUp() &&\n        getBuilderFromConfig(this.collection.config)\n      ) {\n        this.startSyncIfStopped()\n      }\n      // A deferring subscriber asks for no data, so adapters do not see it.\n      if (!defersAcquisition) {\n        acquiring = true\n        this.changeAcquiringSubscribers(1)\n      }\n    } catch (error) {\n      this.activeSubscribersCount--\n      if (acquiring) {\n        try {\n          this.changeAcquiringSubscribers(-1)\n        } catch {\n          // Keep the setup failure primary if a release listener also throws.\n        }\n      }\n      if (this.activeSubscribersCount === 0) {\n        this.lifecycle.startGCTimer()\n      }\n      throw error\n    }\n  }\n\n  /**\n   * Decrement the active subscribers count and start GC timer if needed\n   */\n  private removeSubscriber(wasDeferring: boolean): void {\n    this.activeSubscribersCount--\n\n    if (this.activeSubscribersCount === 0) {\n      this.lifecycle.startGCTimer()\n    } else if (this.activeSubscribersCount < 0) {\n      throw new NegativeActiveSubscribersError()\n    }\n\n    if (!wasDeferring) this.changeAcquiringSubscribers(-1)\n  }\n\n  /**\n   * Clean up the collection by stopping sync and clearing data\n   * This can be called manually or automatically by garbage collection\n   */\n  public cleanup(): void {\n    // A preload belongs to one sync run, but subscriptions survive cleanup. A\n    // restarted live-query Collection defers acquisition again unless one of\n    // its surviving subscribers already asks for data.\n    this.subscriberOrPreload = [...this.changeSubscriptions].some(\n      (subscription) => !subscription.isDeferringAcquisition(),\n    )\n    // Cleanup clears visible state without publishing row changes. Detached\n    // consumers may miss every status transition before an empty restart.\n    this.stateRevision++\n    this.batchedEvents = []\n    this.shouldBatchEvents = false\n    if (this.deferral) this.deferral.publications.length = 0\n    this.deferral = undefined\n  }\n}\n"],"mappings":";;;;;;;AAwBA,IAAa,2BAAb,MAKE;;;;CAoDA,cAAc;EA7CkB,KAAA,yBAAA;EAIG,KAAA,4BAAA;EACN,KAAA,sCAAA,IAAI,IAA4B;EACD,KAAA,gBAAA,CAAC;EAClC,KAAA,oBAAA;EAYK,KAAAM,qBAAA,IAAI,IAAgB;EAItB,KAAAC,K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