# Diffuse Elements

## Artwork
### Audio Metadata

Extracts embedded artwork from audio files using the music-metadata library.

```js
import { defineElement, DiffuseElement, query } from "~/common/element.js";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {InputElement} from "@specs/components/input/types.d.ts"
 * @import {Actions} from "@specs/components/artwork/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<Actions>}
 */
class AudioMetadataArtwork extends DiffuseElement {
  static NAME = "diffuse/artwork/audio-metadata";
  static WORKER_URL = "components/artwork/audio-metadata/worker.js";

  constructor() {
    super();

    /** @type {ProxiedActions<Actions>} */
    const p = this.workerProxy();

    this.get = p.get;
  }

  // LIFECYCLE

  /** @override */
  async connectedCallback() {
    super.connectedCallback();

    /** @type {InputElement} */
    this.input = query(this, "input-selector");

    await customElements.whenDefined(this.input.localName);
  }

  // WORKERS

  /**
   * @override
   */
  dependencies() {
    if (!this.input) throw new Error("Input element not defined yet");
    return { input: this.input };
  }
}

export default AudioMetadataArtwork;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = AudioMetadataArtwork;
export const NAME = "da-audio-metadata";

defineElement(NAME, AudioMetadataArtwork);
```
### Input

Fetches artwork by delegating to the configured input element's artwork method.

```js
import { defineElement, DiffuseElement, query } from "~/common/element.js";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {InputElement} from "@specs/components/input/types.d.ts"
 * @import {Actions} from "@specs/components/artwork/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<Actions>}
 */
class InputArtwork extends DiffuseElement {
  static NAME = "diffuse/artwork/input";
  static WORKER_URL = "components/artwork/input/worker.js";

  constructor() {
    super();

    /** @type {ProxiedActions<Actions>} */
    const p = this.workerProxy();

    this.get = p.get;
  }

  // LIFECYCLE

  /** @override */
  async connectedCallback() {
    super.connectedCallback();

    /** @type {InputElement} */
    this.input = query(this, "input-selector");

    await customElements.whenDefined(this.input.localName);
  }

  // WORKERS

  /**
   * @override
   */
  dependencies() {
    if (!this.input) throw new Error("Input element not defined yet");
    return { input: this.input };
  }
}

export default InputArtwork;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = InputArtwork;
export const NAME = "da-input";

defineElement(NAME, InputArtwork);
```
### Last.fm

Fetches cover art from the Last.fm API using track artist and album tags.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Actions} from "@specs/components/artwork/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<Actions>}
 */
class LastFmArtwork extends DiffuseElement {
  static NAME = "diffuse/artwork/last.fm";
  static WORKER_URL = "components/artwork/last.fm/worker.js";

  constructor() {
    super();

    /** @type {ProxiedActions<Actions>} */
    const p = this.workerProxy();

    this.get = p.get;
  }
}

export default LastFmArtwork;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = LastFmArtwork;
export const NAME = "da-lastfm";

defineElement(NAME, LastFmArtwork);
```
### MusicBrainz

Fetches cover art from MusicBrainz and the Cover Art Archive using track artist and album tags.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Actions} from "@specs/components/artwork/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<Actions>}
 */
class MusicBrainzArtwork extends DiffuseElement {
  static NAME = "diffuse/artwork/musicbrainz";
  static WORKER_URL = "components/artwork/musicbrainz/worker.js";

  constructor() {
    super();

    /** @type {ProxiedActions<Actions>} */
    const p = this.workerProxy();

    this.get = p.get;
  }
}

export default MusicBrainzArtwork;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = MusicBrainzArtwork;
export const NAME = "da-musicbrainz";

defineElement(NAME, MusicBrainzArtwork);
```
## Configurators
### Artwork

Takes artwork components as children and tries each in sequence, returning the first non-null result.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {ArtworkElement} from "@specs/components/artwork/types.d.ts"
 * @import {Actions} from "@specs/components/configurator/artwork/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<Actions>}
 */
class ArtworkConfigurator extends DiffuseElement {
  static NAME = "diffuse/configurator/artwork";
  static WORKER_URL = "components/configurator/artwork/worker.js";

  constructor() {
    super();

    /** @type {ProxiedActions<Actions>} */
    const proxy = this.workerProxy();

    this.get = proxy.get;
  }

  // WORKERS

  /**
   * @override
   */
  dependencies() {
    return Object.fromEntries(
      Array.from(this.children).map((element) => {
        const artwork = /** @type {ArtworkElement} */ (element);
        return [artwork.localName, artwork];
      }),
    );
  }
}

export default ArtworkConfigurator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = ArtworkConfigurator;
export const NAME = "dc-artwork";

defineElement(NAME, ArtworkConfigurator);
```
### Collaboration

Holds collaboration sources as children. Each source declares the hint prefix it handles, so the cooperative-playlists orchestrator can resolve collaborators across protocols.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";

/**
 * @import {CollaborationConfiguratorActions} from "@specs/components/configurator/collaboration/types.d.ts"
 * @import {CollaborationSourceElement} from "@specs/components/collaboration/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Holds the available collaboration sources. Append source elements as
 * children; each source declares the hint prefix it handles through `PREFIX`.
 *
 * @implements {CollaborationConfiguratorActions}
 */
class CollaborationConfigurator extends DiffuseElement {
  static NAME = "diffuse/configurator/collaboration";

  // SOURCES

  sources() {
    /** @type {Record<string, CollaborationSourceElement>} */
    const sources = {};

    for (const element of this.children) {
      const source = /** @type {CollaborationSourceElement} */ (element);
      if (typeof source.PREFIX !== "string" || source.PREFIX.length === 0) {
        continue;
      }

      sources[source.PREFIX] = source;
    }

    return sources;
  }

  /**
   * @param {string | undefined} hint
   */
  sourceFor(hint) {
    if (typeof hint !== "string") return undefined;

    const prefix = hint.split("/")[0];
    return prefix ? this.sources()[prefix] : undefined;
  }

  // WORKERS

  /**
   * @override
   */
  dependencies() {
    return this.sources();
  }
}

export default CollaborationConfigurator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = CollaborationConfigurator;
export const NAME = "dc-collaboration";

defineElement(NAME, CLASS);
```
### Input

Allows for multiple inputs to be used at once.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";

/**
 * @import {ProxiedActions, Tunnel} from "~/common/worker.d.ts"
 * @import {InputElement} from "@specs/components/input/types.d.ts"
 * @import {Actions} from "@specs/components/configurator/input/types.d.ts"
 */

/**
 * @typedef {{ element: InputElement, tunnel: Tunnel, worker: Worker | SharedWorker }} Input
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<Actions>}
 */
class InputConfigurator extends DiffuseElement {
  static NAME = "diffuse/configurator/input";
  static WORKER_URL = "components/configurator/input/worker.js";

  constructor() {
    super();

    /** @type {ProxiedActions<Actions>} */
    const proxy = this.workerProxy();

    this.artwork = proxy.artwork;
    this.consult = proxy.consult;
    this.detach = proxy.detach;
    this.groupConsult = proxy.groupConsult;
    this.list = proxy.list;
    this.resolve = proxy.resolve;

    this.cache = proxy.cache;
    this.cacheBlob = proxy.cacheBlob;
    this.listCached = proxy.listCached;
    this.removeFromCache = proxy.removeFromCache;
  }

  // WORKERS

  /**
   * @override
   */
  dependencies() {
    return this.inputs();
  }

  inputs() {
    return Object.fromEntries(
      Array.from(this.children).map((element) => {
        const input = /** @type {InputElement} */ (element);
        return [input.SCHEME, input];
      }),
    );
  }
}

export default InputConfigurator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = InputConfigurator;
export const NAME = "dc-input";

defineElement(NAME, CLASS);
```
### Metadata

Takes metadata components as children and chains their patches in sequence.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {MetadataElement} from "@specs/components/metadata/types.d.ts"
 * @import {Actions} from "@specs/components/configurator/metadata/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<Actions>}
 */
class MetadataConfigurator extends DiffuseElement {
  static NAME = "diffuse/configurator/metadata";
  static WORKER_URL = "components/configurator/metadata/worker.js";

  constructor() {
    super();

    /** @type {ProxiedActions<Actions>} */
    const proxy = this.workerProxy();

    this.patch = proxy.patch;
  }

  // WORKERS

  /**
   * @override
   */
  dependencies() {
    return Object.fromEntries(
      Array.from(this.children).map((element) => {
        const metadata = /** @type {MetadataElement} */ (element);
        return [metadata.localName, metadata];
      }),
    );
  }
}

export default MetadataConfigurator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = MetadataConfigurator;
export const NAME = "dc-metadata";

defineElement(NAME, MetadataConfigurator);
```
### Output

Enables the user to configure a specific output. If no default output is set, it creates a temporary session by storing everything in memory.

```js
import {
  BroadcastableDiffuseElement,
  defineElement,
} from "~/common/element.js";
import { batch, computed, effect, signal } from "~/common/signal.js";

import { PRELUDE_BASE, STARTING_SET_URIS } from "~/common/facets/constants.js";
import { buildFacets } from "~/common/facets/utils.js";
import {
  data as outputData,
  isOutputInitialized,
  markOutputInitialized,
} from "~/common/output.js";

/**
 * @import {DiffuseElement} from "~/common/element.js"
 * @import {Collaboration, Facet, PlaylistItem, Setting, Track} from "~/definitions/types.d.ts"
 * @import {OutputManagerDeputy, OutputElement} from "@specs/components/output/types.d.ts"
 *
 * @import {OutputConfiguratorElement} from "@specs/components/configurator/output/types.d.ts"
 */

/**
 * @typedef {OutputElement} Output
 */

const STORAGE_PREFIX = "diffuse/configurator/output";

/**
 * How long a newly selected output gets to finish its initial connection
 * check before it is treated as disconnected. Outputs that were already
 * usable fall back immediately.
 */
const DISCONNECT_GRACE_MS = 60_000;

/**
 * How long to wait after the output options settle before treating a stored
 * selection that still doesn't resolve as stale.
 *
 * Options are appended asynchronously by the output preludes during bootstrap,
 * so the check can't run immediately. A selection whose element exists is
 * never dropped: resolving it awaits the element's upgrade, so a slow module
 * load can't be mistaken for a removed option.
 */
const STALE_SELECTION_SETTLE_MS = 1_000;

/**
 * Upper bound for `waitForSelected()`. The stale-selection check normally
 * settles it first; the bound only matters when that check can't complete.
 */
const SELECTION_WAIT_MS = 5_000;

const COLLECTIONS = /** @type {const} */ ([
  "collaborations",
  "facets",
  "playlistItems",
  "settings",
  "tracks",
]);

/**
 * An empty indexed-db output reports `loaded` with `undefined` data, so treat
 * anything that isn't an array as an empty collection.
 *
 * @param {unknown} data
 * @returns {any[]}
 */
function asArray(data) {
  return Array.isArray(data) ? data : [];
}

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {OutputConfiguratorElement}
 */
class OutputConfigurator extends BroadcastableDiffuseElement {
  static NAME = "diffuse/configurator/output";

  constructor() {
    super();

    /** @type {OutputManagerDeputy} */
    const manager = {
      collaborations: {
        collection: computed(() => {
          const out = this.#selected.value;
          if (out) return out.collaborations.collection();

          const def = this.#defaultOutput.value;
          if (def) return def.collaborations.collection();
          if (this.hasDefault()) return { state: "loading" };

          return this.#setupFinished.value
            ? { state: "loaded", data: this.#memory.collaborations.value }
            : { state: "loading" };
        }),
        reload: () => {
          const def = this.#defaultOutput.value;
          if (def) def.collaborations.reload();

          const out = this.#selected.value;
          if (out) return out.collaborations.reload();

          return Promise.resolve();
        },
        save: async (newCollaborations) => {
          const out = this.#selected.value;
          if (out) return await out.collaborations.save(newCollaborations);

          const def = this.#defaultOutput.value;
          if (def) return await def.collaborations.save(newCollaborations);

          this.#memory.collaborations.value = newCollaborations;
        },
      },
      facets: {
        collection: computed(() => {
          const out = this.#selected.value;
          if (out) return out.facets.collection();

          const def = this.#defaultOutput.value;
          if (def) {
            const col = def.facets.collection();

            // Recover from the bootstrap deadlock: a non-default output is
            // selected (but its elements aren't created yet, hence `out` is
            // null) and the local bucket has no prelude facets to inject the
            // output-bundle prelude from. Seed the base infrastructure
            // preludes so the page can bootstrap the selected output.
            if (col.state === "loaded" && this.#needsPreludeRecovery(col.data)) {
              return {
                state: "loaded",
                data: [...col.data, ...buildFacets(PRELUDE_BASE)],
              };
            }

            return col;
          }

          if (this.hasDefault()) return { state: "loading" };

          return this.#setupFinished.value
            ? { state: "loaded", data: this.#memory.facets.value }
            : { state: "loading" };
        }),
        reload: () => {
          const def = this.#defaultOutput.value;
          if (def) def.facets.reload();

          const out = this.#selected.value;
          if (out) return out.facets.reload();

          return Promise.resolve();
        },
        save: async (newFacets) => {
          const out = this.#selected.value;
          if (out) return await out.facets.save(newFacets);

          const def = this.#defaultOutput.value;
          if (def) return await def.facets.save(newFacets);

          this.#memory.facets.value = newFacets;
        },
      },
      playlistItems: {
        collection: computed(() => {
          const out = this.#selected.value;
          if (out) return out.playlistItems.collection();

          const def = this.#defaultOutput.value;
          if (def) return def.playlistItems.collection();
          if (this.hasDefault()) return { state: "loading" };

          return this.#setupFinished.value
            ? { state: "loaded", data: this.#memory.playlistItems.value }
            : { state: "loading" };
        }),
        reload: () => {
          const def = this.#defaultOutput.value;
          if (def) def.playlistItems.reload();

          const out = this.#selected.value;
          if (out) return out.playlistItems.reload();

          return Promise.resolve();
        },
        save: async (newPlaylistItems) => {
          const out = this.#selected.value;
          if (out) return await out.playlistItems.save(newPlaylistItems);

          const def = this.#defaultOutput.value;
          if (def) return await def.playlistItems.save(newPlaylistItems);

          this.#memory.playlistItems.value = newPlaylistItems;
        },
      },
      settings: {
        collection: computed(() => {
          const out = this.#selected.value;
          if (out) return out.settings.collection();

          const def = this.#defaultOutput.value;
          if (def) return def.settings.collection();
          if (this.hasDefault()) return { state: "loading" };

          return this.#setupFinished.value
            ? { state: "loaded", data: this.#memory.settings.value }
            : { state: "loading" };
        }),
        reload: () => {
          const def = this.#defaultOutput.value;
          if (def) def.settings.reload();

          const out = this.#selected.value;
          if (out) return out.settings.reload();

          return Promise.resolve();
        },
        save: async (newSettings) => {
          const out = this.#selected.value;
          if (out) return await out.settings.save(newSettings);

          const def = this.#defaultOutput.value;
          if (def) return await def.settings.save(newSettings);

          this.#memory.settings.value = newSettings;
        },
      },
      tracks: {
        collection: computed(() => {
          const out = this.#selected.value;
          if (out) return out.tracks.collection();

          const def = this.#defaultOutput.value;
          if (def) return def.tracks.collection();
          if (this.hasDefault()) return { state: "loading" };

          return this.#setupFinished.value
            ? { state: "loaded", data: this.#memory.tracks.value }
            : { state: "loading" };
        }),
        reload: () => {
          const def = this.#defaultOutput.value;
          if (def) def.tracks.reload();

          const out = this.#selected.value;
          if (out) return out.tracks.reload();

          return Promise.resolve();
        },
        save: async (newTracks) => {
          const out = this.#selected.value;
          if (out) return await out.tracks.save(newTracks);

          const def = this.#defaultOutput.value;
          if (def) return await def.tracks.save(newTracks);

          this.#memory.tracks.value = newTracks;
        },
      },

      // Other
      ready: computed(() => {
        const out = this.#selected.value;
        if (out) return out.ready();

        const def = this.#defaultOutput.value;
        if (def) return def.ready();

        return this.#setupFinished.value;
      }),
    };

    // Assign manager properties to class
    this.collaborations = manager.collaborations;
    this.facets = manager.facets;
    this.playlistItems = manager.playlistItems;
    this.settings = manager.settings;
    this.tracks = manager.tracks;
    this.ready = manager.ready;

    // Effects

    /**
     * When there's a selected output and its collection changes,
     * save it to the default output or memory.
     *
     * An empty selected output that has never been initialized is skipped:
     * its data is about to be carried over from the default (see below), and
     * mirroring the empty value would erase the local copy first.
     */
    this.effect(() => {
      const out = this.#selected.value;
      if (!out) return;

      const col = out.collaborations.collection();
      if (col?.state !== "loaded") return;

      const def = this.#defaultOutput.value;
      if (def) {
        if (!this.#shouldMirror(out)) return;
        def.collaborations.save(col.data);
      } else {
        this.#memory.collaborations.set(col.data);
      }
    });

    this.effect(() => {
      const out = this.#selected.value;
      if (!out) return;

      const col = out.facets.collection();
      if (col?.state !== "loaded") return;

      const def = this.#defaultOutput.value;
      if (def) {
        if (!this.#shouldMirror(out)) return;
        def.facets.save(col.data);
      } else {
        this.#memory.facets.set(col.data);
      }
    });

    this.effect(() => {
      const out = this.#selected.value;
      if (!out) return;

      const col = out.playlistItems.collection();
      if (col?.state !== "loaded") return;

      const def = this.#defaultOutput.value;
      if (def) {
        if (!this.#shouldMirror(out)) return;
        def.playlistItems.save(col.data);
      } else {
        this.#memory.playlistItems.set(col.data);
      }
    });

    this.effect(() => {
      const out = this.#selected.value;
      if (!out) return;

      const col = out.settings.collection();
      if (col?.state !== "loaded") return;

      const def = this.#defaultOutput.value;
      if (def) {
        if (!this.#shouldMirror(out)) return;
        def.settings.save(col.data);
      } else {
        this.#memory.settings.set(col.data);
      }
    });

    this.effect(() => {
      const out = this.#selected.value;
      if (!out) return;

      const col = out.tracks.collection();
      if (col?.state !== "loaded") return;

      const def = this.#defaultOutput.value;
      if (def) {
        if (!this.#shouldMirror(out)) return;
        def.tracks.save(col.data);
      } else {
        this.#memory.tracks.set(col.data);
      }
    });

    /**
     * Copy the default (Local) output's contents into a selected output that
     * has never been used.
     *
     * This is what makes a new remote bucket start with the data already
     * stored locally instead of an empty library. Facets fall back to the
     * starting set when the local store has none, matching the initial-contents
     * refiner.
     */
    this.effect(() => {
      const out = this.#selected.value;
      const def = this.#defaultOutput.value;
      if (!out || !def || out === def) return;

      const id = out.id;
      if (isOutputInitialized(id) || this.#carryingOver.has(id)) return;
      if (!this.#isEmptyAndUninitialized(out)) return;

      this.#carryingOver.add(id);
      void this.#carryOver(out, def, id);
    });

    /**
     * Fall back to the default output when the selected one can't read or
     * write: a remote output reports `ready: false` when its credentials or
     * session are gone, or when the browser is offline. Without this the UI
     * keeps presenting a disconnected store as the one in use.
     *
     * A previously usable output is replaced immediately. On boot the output
     * gets a grace period, because its connection check is asynchronous and
     * `ready` starts out false.
     */
    this.effect(() => {
      const out = this.#selected.value;
      const online = this.#isOnline.value;

      if (out !== this.#readinessOutput) {
        this.#readinessOutput = out;
        this.#readiness = undefined;
      }

      const ready = out ? (out.ready?.() ?? true) : true;
      const becameUnready = this.#readiness === true && !ready;
      this.#readiness = ready;

      this.#clearDisconnectTimer();

      if (!out || out === this.#defaultOutput.value) return;
      if (ready || !online) return;

      if (becameUnready) {
        void this.#fallBackToDefault(out);
        return;
      }

      this.#disconnectTimer = setTimeout(() => {
        this.#disconnectTimer = undefined;

        const current = this.#selected.value;
        if (!current || current === this.#defaultOutput.value) return;
        if (current.ready?.() ?? true) return;
        if (!this.#isOnline.value) return;

        void this.#fallBackToDefault(current);
      }, DISCONNECT_GRACE_MS);
    });
  }

  /**
   * Stop using a selected output that isn't usable, falling back to the
   * default (local) output. Clearing the selection matches a manual
   * disconnect, so the choice isn't silently re-applied while the output is
   * still unavailable.
   *
   * @param {Output} out
   */
  async #fallBackToDefault(out) {
    if (this.#selected.value !== out) return;
    if (out.ready?.() ?? true) return;

    console.warn(
      `Output "${out.id}" is not ready; falling back to the default output.`,
    );

    await this.deselect();
  }

  #clearDisconnectTimer() {
    if (this.#disconnectTimer === undefined) return;

    clearTimeout(this.#disconnectTimer);
    this.#disconnectTimer = undefined;
  }

  /**
   * Watch the configurator's children, which is where output options are
   * appended. A stored selection that points at an option missing from this
   * build can then be re-resolved if the option shows up, and dropped once
   * the options have settled.
   */
  #watchOptions() {
    this.#optionsObserver = new MutationObserver(() =>
      this.#scheduleStaleCheck()
    );

    this.#optionsObserver.observe(this, { childList: true });
    this.#scheduleStaleCheck();
  }

  #stopWatchingOptions() {
    this.#optionsObserver?.disconnect();
    this.#optionsObserver = undefined;

    this.#clearStaleSelectionTimer();
  }

  #clearStaleSelectionTimer() {
    if (this.#staleSelectionTimer === undefined) return;

    clearTimeout(this.#staleSelectionTimer);
    this.#staleSelectionTimer = undefined;
  }

  /**
   * (Re)start the timer that drops a stored selection which can't be resolved
   * to an output element. Restarting on every option change treats a burst of
   * appended options as one settle instead of checking between them.
   */
  #scheduleStaleCheck() {
    this.#clearStaleSelectionTimer();

    if (!this.isConnected) return;
    if (!this.#selectedOutputId() || this.#selected.value) return;

    this.#staleSelectionTimer = setTimeout(() => {
      this.#staleSelectionTimer = undefined;
      void this.#dropStaleSelection();
    }, STALE_SELECTION_SETTLE_MS);
  }

  /**
   * Drop a stored selection whose option no longer exists, leaving the app on
   * the default output instead of a selection that can never resolve.
   *
   * Resolving here rather than checking `localStorage` / `querySelector` also
   * covers an option element that was appended but whose module is still
   * loading, because `#findOutput()` waits for the element to upgrade.
   */
  async #dropStaleSelection() {
    const id = this.#selectedOutputId();
    if (!id || this.#selected.value) return;
    if (await this.#findOutput(id)) return;

    // The selection may have changed while the lookup was pending.
    if (this.#selectedOutputId() !== id || this.#selected.value) return;

    console.warn(
      `Stored output selection "${id}" no longer exists; falling back to the default output.`,
    );

    await this.deselect();
  }

  /**
   * Whether the selected output is completely empty and has never been used.
   * Only then should its contents be carried over from the default output.
   *
   * @param {Output} out
   * @returns {boolean}
   */
  #isEmptyAndUninitialized(out) {
    if (isOutputInitialized(out.id)) return false;

    for (const name of COLLECTIONS) {
      const collection = out[name].collection();
      // A transformer can still be mid-evaluation when a dependency it sets
      // during its own first read flushes this effect. Treat that as "not
      // ready yet"; the change that caused it re-runs this effect.
      if (!collection || collection.state !== "loaded") return false;
      if (asArray(collection.data).length > 0) return false;
    }

    return true;
  }

  /**
   * Mirroring a selected output into the default store is only safe once the
   * output has been used. Before that, an empty collection would overwrite the
   * local copy it is about to be seeded from.
   *
   * @param {Output} out
   * @returns {boolean}
   */
  #shouldMirror(out) {
    return isOutputInitialized(out.id) || this.#hasData(out);
  }

  /**
   * @param {Output} out
   * @returns {boolean}
   */
  #hasData(out) {
    return COLLECTIONS.some((name) => {
      const collection = out[name].collection();
      return collection?.state === "loaded" &&
        asArray(collection.data).length > 0;
    });
  }

  /**
   * Read the default output and write it into an empty selected output. Runs
   * once per output; the initialized flag prevents a later carry-over after
   * the user intentionally emptied it.
   *
   * @param {Output} out
   * @param {Output} def
   * @param {string} id
   */
  async #carryOver(out, def, id) {
    try {
      const data = {
        collaborations: asArray(await outputData(def.collaborations)),
        facets: asArray(await outputData(def.facets)),
        playlistItems: asArray(await outputData(def.playlistItems)),
        settings: asArray(await outputData(def.settings)),
        tracks: asArray(await outputData(def.tracks)),
      };

      // Nothing stored locally yet (a fresh install): leave the output
      // uninitialized so the initial-contents refiner keeps showing the
      // starting set.
      if (!Object.values(data).some((items) => items.length > 0)) return;

      await Promise.all([
        out.collaborations.save(data.collaborations),
        out.facets.save(
          data.facets.length > 0 ? data.facets : buildFacets(STARTING_SET_URIS),
        ),
        out.playlistItems.save(data.playlistItems),
        out.settings.save(data.settings),
        out.tracks.save(data.tracks),
      ]);

      markOutputInitialized(id);
    } catch (err) {
      console.error("Could not carry the local output over:", err);
    } finally {
      this.#carryingOver.delete(id);
    }
  }

  // SIGNALS

  #activated = signal(/** @type {Set<string>} */ (new Set()));

  #defaultOutput = signal(
    /** @type {Output | null | undefined} */ (undefined),
  );

  #memory = {
    collaborations: signal(/** @type {Collaboration[]} */ ([])),
    facets: signal(/** @type {Facet[]} */ ([])),
    playlistItems: signal(/** @type {PlaylistItem[]} */ ([])),
    settings: signal(/** @type {Setting[]} */ ([])),
    tracks: signal(/** @type {Track[]} */ ([])),
  };

  #selected = signal(
    /** @type {Output | null | undefined} */ (undefined),
  );

  /**
   * Bumped when the stored selection changes, so `waitForSelected()` re-checks
   * even when the selected element stays `null` (a stale selection being
   * dropped doesn't change the `#selected` signal's value).
   */
  #selectionChanged = signal(0);

  /**
   * Output ids whose contents are being copied from the default output, so the
   * effect above doesn't start a second copy while the first is in flight.
   *
   * @type {Set<string>}
   */
  #carryingOver = new Set();

  #setupFinished = signal(false);

  #isOnline = signal(navigator.onLine);

  /** @type {ReturnType<typeof setTimeout> | undefined} */
  #disconnectTimer;

  /** @type {ReturnType<typeof setTimeout> | undefined} */
  #staleSelectionTimer;

  /** @type {MutationObserver | undefined} */
  #optionsObserver;

  /** @type {Output | null | undefined} */
  #readinessOutput;

  /** @type {boolean | undefined} */
  #readiness;

  #handleOnline = () => this.#isOnline.value = true;
  #handleOffline = () => this.#isOnline.value = false;;

  // STATE

  activated = this.#activated.get;
  selected = computed(() => this.#selected.value ?? null);

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    // Broadcast if needed
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(this.identifier, {
        selectOutput: {
          strategy: "replicate",
          fn: this.#selectOutput,
        },
      });

      if (actions) {
        this.#selectOutput = actions.selectOutput;
      }
    }

    // Super
    super.connectedCallback();

    globalThis.addEventListener("online", this.#handleOnline);
    globalThis.addEventListener("offline", this.#handleOffline);

    // Outputs
    const def_ault = this.getAttribute("default");
    const selectedOutputId = this.#selectedOutputId();

    batch(() => {
      /** @type {Set<string>} */
      const activated = new Set();

      if (def_ault) {
        activated.add(def_ault);
      }

      if (selectedOutputId) {
        activated.add(selectedOutputId);
      }

      this.#activated.value = activated;
    });

    /** @type {Output | null} */
    const defaultOutput = def_ault ? await this.#findOutput(def_ault) : null;
    const selectedOutput = await this.#findOutput(selectedOutputId);

    batch(() => {
      this.#selected.value = selectedOutput;
      this.#defaultOutput.value = defaultOutput;
      this.#setupFinished.value = true;
    });

    // The element may have been disconnected while its initial lookups were
    // pending; only watch for option changes while it is still connected.
    if (this.isConnected) this.#watchOptions();
  }

  /** @override */
  disconnectedCallback() {
    globalThis.removeEventListener("online", this.#handleOnline);
    globalThis.removeEventListener("offline", this.#handleOffline);

    this.#clearDisconnectTimer();
    this.#stopWatchingOptions();
    super.disconnectedCallback();
  }

  // MISC

  /**
   * @param {string | null} id
   */
  async #findOutput(id) {
    const el = id ? this.root().querySelector(`#${id}`) : null;
    if (!el) return null;

    await customElements.whenDefined(el.localName);

    if (
      "identifier" in el === false ||
      "tracks" in el === false
    ) {
      return null;
    }

    return /** @type {Output} */ (/** @type {unknown} */ (el));
  }

  /**
   * Whether the local bucket needs the base infrastructure preludes seeded
   * into the fallback.
   *
   * @param {Facet[]} localFacets
   * @returns {boolean}
   */
  #needsPreludeRecovery(localFacets) {
    const selectedId = this.#selectedOutputId();
    const defaultId = this.getAttribute("default");

    // Only a non-default selection depends on the prelude to be created.
    if (!selectedId || selectedId === defaultId) return false;

    // If the local bucket already has preludes, the normal path works.
    return !localFacets.some((f) => f.kind === "prelude");
  }

  /**
   * @param {string | null} id
   */
  #selectOutput = async (id) => {
    if (id) {
      this.#activated.value = new Set([...this.#activated.value.values(), id]);
    }

    this.#selected.value = await this.#findOutput(id);
  };

  #selectedOutputId() {
    return localStorage.getItem(`${STORAGE_PREFIX}/selected/id`);
  }

  /**
   * @override
   */
  dependencies = () => {
    return Object.fromEntries(
      Array.from(this.root().children).flatMap((element) => {
        if (element.hasAttribute("id") === false) {
          console.warn(
            "Missing `id` for output configurator child element with `localName` '" +
              element.localName + "'",
          );
          return [];
        }

        const d = /** @type {DiffuseElement} */ (element);
        return [[d.id, d]];
      }),
    );
  };

  // ADDITIONAL ACTIONS

  deselect = async () => {
    localStorage.removeItem(`${STORAGE_PREFIX}/selected/id`);
    this.#selectionChanged.value++;
    await this.#selectOutput(null);
  };

  hasDefault() {
    return this.hasAttribute("default");
  }

  hasSelected() {
    return this.#selectedOutputId() !== null;
  }

  loadSelected = async () => {
    const selectedOutput = await this.#findOutput(this.#selectedOutputId());
    this.#selected.value = selectedOutput;

    this.#scheduleStaleCheck();
  };

  options = async () => {
    const deps = this.dependencies();
    const entries = Object.entries(deps);

    return entries.map(([k, v]) => {
      return {
        id: k,
        label: v.label ?? v.getAttribute("label"),
        element: /** @type {OutputElement} */ (v),
      };
    });
  };

  /**
   * @param {string} id
   */
  select = async (id) => {
    localStorage.setItem(`${STORAGE_PREFIX}/selected/id`, id);
    this.#selectionChanged.value++;
    await this.#selectOutput(id);

    this.#scheduleStaleCheck();
  };

  /**
   * Wait for the selected output element to resolve.
   *
   * Resolves with the selected element, or with `null` once the stored
   * selection has been dropped as stale or when `timeoutMs` elapses. Callers
   * should prefer this over waiting on `selected()` directly, which never
   * resolves when the stored selection points at an option that no longer
   * exists in this build.
   *
   * @param {number} [timeoutMs]
   * @returns {Promise<Output | null>}
   */
  waitForSelected = (timeoutMs = SELECTION_WAIT_MS) => {
    /** @returns {boolean} */
    const settled = () => this.selected() !== null || !this.hasSelected();

    if (settled()) return Promise.resolve(this.selected());

    return new Promise((resolve) => {
      let done = false;
      /** @type {ReturnType<typeof setTimeout> | undefined} */
      let timer = undefined;
      /** @type {() => void} */
      let stop = () => {};

      const finish = () => {
        if (done) return;
        done = true;

        if (timer !== undefined) clearTimeout(timer);
        stop();
        resolve(this.selected());
      };

      stop = effect(() => {
        this.#selectionChanged.get();

        // Re-check at the end of the effect so the dependency reads above are
        // registered before it can settle.
        if (this.selected() !== null || !this.hasSelected()) finish();
      });

      timer = setTimeout(finish, timeoutMs);
    });
  };

  /**
   * @param {string} label
   * @returns {Promise<{ id: string, label: string, element: OutputElement }>}
   */
  waitForOption = (label) => {
    return new Promise((resolve) => {
      const check = async () => {
        const opt = (await this.options()).find((o) => o.label === label);
        if (opt) {
          observer.disconnect();
          resolve(opt);
        }
      };

      const observer = new MutationObserver(check);
      observer.observe(this, { childList: true });
      check();
    });
  };
}

export default OutputConfigurator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = OutputConfigurator;
export const NAME = "dc-output";

defineElement(NAME, CLASS);
```
### Scrobbles

Configure multiple scrobblers (music trackers).

```js
import { defineElement, DiffuseElement } from "~/common/element.js";

/**
 * @import {Track} from "~/definitions/types.d.ts"
 * @import {ScrobbleActions, ScrobbleElement} from "@specs/components/supplement/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ScrobbleActions}
 */
class ScrobblesConfigurator extends DiffuseElement {
  static NAME = "diffuse/configurator/scrobbles";

  // SCROBBLE ACTIONS

  /**
   * @param {Track} track
   */
  async nowPlaying(track) {
    return await Promise.all(
      this.#activeScrobblers().map((s) => s.nowPlaying(track)),
    );
  }

  /**
   * @param {Track} track
   * @param {number} startedAt Unix timestamp in milliseconds
   * @param {{ duration?: number }} [options] duration in milliseconds
   */
  async scrobble(track, startedAt, options) {
    return await Promise.all(
      this.#activeScrobblers().map((s) => s.scrobble(track, startedAt, options)),
    );
  }

  // MISC

  /**
   * All child scrobble elements, regardless of authentication state.
   *
   * @returns {ScrobbleElement[]}
   */
  scrobblers() {
    return Array.from(this.root().children).flatMap((el) => {
      if (!("isAuthenticated" in el && "nowPlaying" in el)) return [];
      return [/** @type {ScrobbleElement} */ (/** @type {unknown} */ (el))];
    });
  }

  /**
   * Child scrobble elements that are currently authenticated.
   *
   * @returns {ScrobbleElement[]}
   */
  #activeScrobblers() {
    return this.scrobblers().filter((s) => s.isAuthenticated());
  }
}

export default ScrobblesConfigurator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = ScrobblesConfigurator;
export const NAME = "dc-scrobbles";

defineElement(NAME, CLASS);
```
### Upload

Takes upload components as children and enables configuring one or more upload destinations.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";

/**
 * @import {ProxiedActions, Tunnel} from "~/common/worker.d.ts"
 * @import {UploadElement} from "@specs/components/upload/types.d.ts"
 * @import {Actions} from "@specs/components/configurator/upload/types.d.ts"
 */

/**
 * @typedef {{ element: UploadElement, tunnel: Tunnel, worker: Worker | SharedWorker }} Upload
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<Actions>}
 */
class UploadConfigurator extends DiffuseElement {
  static NAME = "diffuse/configurator/upload";
  static WORKER_URL = "components/configurator/upload/worker.js";

  constructor() {
    super();

    /** @type {ProxiedActions<Actions>} */
    const proxy = this.workerProxy();

    this.consult = proxy.consult;
    this.upload = proxy.upload;
    this.delete = proxy.delete;
    this.createSource = proxy.createSource;
  }

  // WORKERS

  /**
   * @override
   */
  dependencies() {
    return this.uploaders();
  }

  uploaders() {
    return Object.fromEntries(
      Array.from(this.children).map((element) => {
        const upload = /** @type {UploadElement} */ (element);
        return [upload.SCHEME, upload];
      }),
    );
  }
}

export default UploadConfigurator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = UploadConfigurator;
export const NAME = "dc-upload";

defineElement(NAME, CLASS);
```
## Engines
### Audio

Plays audio through audio elements.

```js
import { repeat } from "lit-html/directives/repeat.js";

import {
  BroadcastableDiffuseElement,
  defineElement,
  nothing,
} from "~/common/element.js";
import { computed, signal, untracked } from "~/common/signal.js";

/**
 * @import {Actions, AudioUrl, AudioState, AudioStateReadOnly, LoadingState} from "@specs/components/engine/audio/types.d.ts"
 * @import {RenderArg} from "~/common/element.d.ts"
 * @import {SignalReader} from "~/common/signal.d.ts"
 */

////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////
/**
 * Mobile Safari caps the number of live media elements and behaves poorly
 * when fresh <audio> nodes are created on every track change. On iOS we
 * therefore render a single <audio> element and reuse its DOM node across
 * track switches instead of keying one per item id.
 */
const IS_IOS = /iPhone|iPad|iPod/.test(navigator.userAgent) ||
  (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);

/**
 * A valid, silent WAV. Assigned to a media element that is being torn down to
 * force resource selection away from its network source.
 *
 * Removing `src` and calling `load()` is not enough everywhere: Firefox keeps
 * an in-flight media request (and its socket) alive until the element is
 * garbage collected, which may never happen while the tab lives. Selecting a
 * local data URL makes the element drop the network resource immediately.
 * (Also documented in `specs/components/engine/audio/SPEC.md`.)
 */
const SILENT_AUDIO_SRC =
  "data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YQAAAAA=";

/**
 * Module-internal Web Audio routing hooks. Accessed only by {@link AudioEngine}
 * and {@link AudioEngineItem} (both live in this file), so these stay out of
 * the public surface — external consumers use `engine.webAudio` instead.
 *
 * @type {unique symbol}
 */
const ROUTE_AUDIO = Symbol("routeAudio");
/** @type {unique symbol} */
const UNROUTE_AUDIO = Symbol("unrouteAudio");
/** @type {unique symbol} */
const CANCEL_PRELOAD = Symbol("cancelPreload");

/**
 * Automatic retry policy for transient media errors (network / CORS-handshake
 * failures). The delay doubles per attempt from {@link RETRY_BASE_DELAY_MS}
 * up to {@link RETRY_MAX_DELAY_MS}, then stays at the ceiling and keeps
 * retrying until playback succeeds, the user pauses, or the item is dropped.
 */
const RETRY_BASE_DELAY_MS = 500;
const RETRY_MAX_DELAY_MS = 30_000;

/**
 * How long a load may go without ANY data (`progress` events) before the load
 * watchdog treats it as hung and reloads. Doubles per trip up to
 * {@link RETRY_MAX_DELAY_MS}, then keeps checking at that ceiling.
 */
const LOAD_WATCHDOG_MS = 3_000;

/**
 * How many consecutive data-less watchdog windows a still-fetching
 * (`NETWORK_LOADING`) load may wait through before the request is considered
 * hung and reloaded. A server that accepts the connection but never sends a
 * byte — a half-open connection after a network change or laptop sleep — keeps
 * the element in `NETWORK_LOADING` indefinitely, so without this bound the load
 * would wait forever. At the base window this is ~30s of patience.
 */
const LOAD_WAIT_LIMIT = 10;

/**
 * How many consecutive data-less watchdog reloads an element may attempt
 * before recovery is declared futile. When the cause is not the element but
 * what it shares with everything else — the browser's connection pool to that
 * host (one wedged HTTP/2 connection carries all of them; on HTTP/1.1 six
 * hung sockets block the rest) or a server that accepts connections but never
 * answers — every fresh request pends forever too. Continuing the cycle
 * cannot recover and only occupies more of the connections recovery needs,
 * while piling up "pending" entries. Past the limit the element stops
 * reloading and surfaces a terminal error; the counter resets on data,
 * playback, a seek, refocus or `online`, each of which grants one fresh
 * bounded budget.
 */
const DATALESS_RELOAD_LIMIT = 5;

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {Actions}
 */
class AudioEngine extends BroadcastableDiffuseElement {
  static NAME = "diffuse/engine/audio";

  constructor() {
    super();

    this.state = this.state.bind(this);
  }

  /** @type {Map<string, string>} MediaSource object URLs created from streams, keyed by item ID */
  #mediaSourceUrls = new Map();

  /** @type {Map<string, ReadableStream>} Streams pending MediaSource setup */
  #streams = new Map();

  /** Aborts in-flight MediaSource setup when the element is disconnected. */
  #streamAbort = new AbortController();

  // WEB AUDIO
  //
  // Every <audio> element is routed through a shared AudioContext so consumers
  // (themes, equalizer / visualizer plugins, …) can tap into the signal. All
  // sources land on a single post-volume `input` node that is connected to the
  // destination by default; a consumer replaces that edge with its own chain
  // (e.g. `input → biquadFilter → destination`) to apply DSP.
  //
  // Chain (unless a consumer splices its nodes in):
  //   mediaElementSource -> input -> destination

  /** @type {AudioContext | undefined} Lazily created, shared by all items. */
  #audioContext = undefined;
  /** @type {GainNode | undefined} Post-volume tap point that all sources feed. */
  #input = undefined;
  /** @type {Map<HTMLAudioElement, MediaElementAudioSourceNode>} */
  #sourceNodes = new Map();

  /**
   * Output device id last applied to the shared context. An empty string is
   * the browser/system default, so a freshly created graph only calls
   * `setSinkId` when this group actually has a stored preference.
   * @type {string}
   */
  #appliedSink = "";

  // SIGNALS

  #items = signal(/** @type {AudioUrl[]} */ ([]));
  #volume = signal(0.75);

  // STATE

  items = this.#items.get;
  volume = this.#volume.get;

  isPlaying = computed(() => {
    const item = this.items()?.[0];
    if (!item) return false;

    const state = this.state(item.id);
    if (!state) return false;

    return state.isPlaying() || state.hasEnded() ||
      (state.duration() > 0 && state.currentTime() === state.duration());
  });

  // LIFECYCLE

  /**
   * @override
   */
  connectedCallback() {
    // Reset teardown signal in case the element is reconnected (moved in DOM).
    this.#streamAbort = new AbortController();

    // Setup broadcasting if part of group
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(
        this.identifier,
        {
          adjustVolume: { strategy: "replicate", fn: this.adjustVolume },
          pause: { strategy: "leaderOnly", fn: this.pause },
          play: { strategy: "leaderOnly", fn: this.play },
          seek: { strategy: "leaderOnly", fn: this.seek },
          supply: { strategy: "replicate", fn: this.supply },

          // State
          items: { strategy: "leaderOnly", fn: this.items },
        },
      );

      if (!actions) return;

      this.adjustVolume = actions.adjustVolume;
      this.pause = actions.pause;
      this.play = actions.play;
      this.seek = actions.seek;
      this.supply = actions.supply;

      // Sync items with leader if needed
      this.broadcastingStatus().then(async (status) => {
        if (status.leader) return;
        this.#items.value = await actions.items();
      });
    }

    // Super
    super.connectedCallback();

    // Get volume from previous session if possible
    const VOLUME_KEY =
      `${this.constructor.prototype.constructor.NAME}/${this.group}/volume`;
    const volume = localStorage.getItem(VOLUME_KEY);

    if (volume != undefined) {
      this.#volume.set(parseFloat(volume));
    }

    // Monitor volume signal
    this.effect(() => {
      // Master volume is applied through the Web Audio graph's input gain node.
      // When the graph hasn't been created yet (e.g. no AudioContext support) we
      // fall back to setting the volume directly on each element.
      if (this.#input) {
        this.#input.gain.value = this.#volume.value;
      }

      Array.from(this.querySelectorAll("de-audio-item")).forEach(
        (node) => {
          const item = /** @type {AudioEngineItem} */ (node);
          if (item.hasAttribute("preload")) return;
          const audio = item.querySelector("audio");
          if (audio && !this.#sourceNodes.has(audio)) {
            audio.volume = this.#volume.value;
          }
        },
      );

      localStorage.setItem(VOLUME_KEY, this.#volume.value.toString());
    });

    // Follow audio-output changes made elsewhere (e.g. the Audio Output facet
    // running in another frame/tab). `storage` fires in every other same-origin
    // document, so each group's engine picks up its own preference live. The
    // key is namespaced by group, so this only reacts to this group's setting.
    this.effect(() => {
      const key = this.#sinkStorageKey();

      /** @param {StorageEvent} event */
      const onStorage = (event) => {
        if (event.key !== null && event.key !== key) return;
        this.#applySink();
      };

      globalThis.addEventListener("storage", onStorage);
      return () => globalThis.removeEventListener("storage", onStorage);
    });

    // iOS: resume playback that silently failed to start while the page is
    // hidden (mobile Safari suspends media loading & the audio session in
    // the background). If playback was requested but the element is paused,
    // replay it now that the page is visible — reloading first if nothing
    // was buffered yet.
    if (IS_IOS) {
      const onVisible = () => {
        if (document.hidden) return;

        this.items().forEach((item) => {
          if (item.isPreload) return;

          const el = this.#itemElement(item.id);
          if (!el?.intendsToPlay) return;

          const audio = el.audio;
          if (!audio.paused) return;

          if (audio.readyState >= 2) {
            this.play({ audioId: item.id });
          } else {
            audio.load();
            audio.addEventListener("canplay", () => {
              if (el.intendsToPlay) this.play({ audioId: item.id });
            }, { once: true });
          }
        });
      };

      this.effect(() => {
        document.addEventListener("visibilitychange", onVisible);
        return () =>
          document.removeEventListener("visibilitychange", onVisible);
      });
    }

    // Only broadcasting stuff from here on out
    if (!this.broadcasted) return;

    // Manage playback across tabs if needed
    this.effect(async () => {
      const status = await this.broadcastingStatus();
      untracked(() => {
        if (!(status.leader && status.initialLeader === false)) return;

        console.log("🧙 Leadership acquired");
        this.items().forEach((item) => {
          const el = this.#itemElement(item.id);
          if (!el) return;

          el.removeAttribute("initial-progress");

          if (!el.audio) return;

          const currentTime = el.$state.currentTime.value;
          const canPlay = () => {
            this.seek({
              audioId: item.id,
              currentTime: currentTime,
            });

            if (el.$state.isPlaying.value) this.play({ audioId: item.id });
          };

          el.audio.addEventListener("canplay", canPlay, { once: true });

          if (el.audio.readyState === 0) el.audio.load();
          else canPlay();
        });
      });
    });
  }

  /**
   * @override
   */
  disconnectedCallback() {
    // Abort in-flight MediaSource setup so #resolveStream can wind down even
    // while it's awaiting `sourceopen` (which may otherwise never fire once
    // the object URL is revoked / the element is detached).
    this.#streamAbort.abort();

    // Revoke every MediaSource object URL. WebKit refcounts these and only
    // frees the buffered data on revokeObjectURL — dropping the map without
    // revoking leaks the decoded track bytes until the tab's process dies.
    for (const objectUrl of this.#mediaSourceUrls.values()) {
      URL.revokeObjectURL(objectUrl);
    }
    this.#mediaSourceUrls.clear();

    // Cancel pending (not-yet-resolved) streams so their underlying sources
    // (e.g. fetches) release immediately instead of draining forever.
    for (const stream of this.#streams.values()) {
      stream.cancel().catch(() => {});
    }
    this.#streams.clear();

    // Stop and unload any live audio nodes before they're dropped so detached
    // media doesn't keep playing / holding the audio session.
    this.querySelectorAll("de-audio-item").forEach((node) => {
      const item = /** @type {AudioEngineItem} */ (node);
      let audio;
      try {
        audio = item.audio; // throws when there's no child <audio>
      } catch {
        return;
      }
      releaseAudioElement(audio);
    });

    // NOTE: The shared Web Audio graph is intentionally left untouched here.
    // `createMediaElementSource` may only be called once per element, so
    // detaching the source nodes or closing the AudioContext while the
    // engine's elements still exist would permanently mute them if the engine
    // is ever re-connected (the nodes cannot be re-created). The graph lives
    // for the page's lifetime instead; re-connected items simply keep feeding
    // it through their existing nodes.
    super.disconnectedCallback();
  }

  // ACTIONS

  /**
   * @type {Actions["adjustVolume"]}
   */
  adjustVolume(args) {
    if (args.audioId) {
      this.#withAudioNode(args.audioId, (audio) => {
        audio.volume = args.volume;
      });
    } else {
      this.#volume.value = args.volume;
    }
  }

  /**
   * @type {Actions["pause"]}
   */
  pause({ audioId }) {
    this.#withAudioNode(audioId, (audio, item) => {
      item.cancelMediaRetry();
      audio.pause();
      item.intendsToPlay = false;
      // Set `isPlaying` to false optimistically, mirroring `play()`. The
      // `pause` event would normally do this via `pauseEvent`, but when
      // `play()` was called before the audio had buffered enough to start
      // (e.g. readyState < HAVE_FUTURE_DATA) the browser may never fire a
      // `pause` event — leaving `isPlaying` stuck on the optimistic `true`
      // that `play()` set. It also prevents `canplayEvent`'s retry-on-ready
      // logic from restarting playback after an explicit pause.
      item.$state.isPlaying.set(false);
    });
  }

  /**
   * @type {Actions["play"]}
   */
  play({ audioId, volume }) {
    this.#resumeContext();

    this.#withAudioNode(audioId, (audio, item) => {
      // Routed elements get master volume from the graph's gain node, so keep
      // their own volume at unity unless a per-item override is given. In the
      // no-Web-Audio fallback the element's volume carries the master level.
      const routed = this.#sourceNodes.has(audio);
      audio.volume = volume ?? (routed ? 1 : this.volume());
      audio.muted = false;

      // An errored element can't be restarted with play() alone — re-run
      // resource selection first so both manual retries and the automatic
      // recovery in `errorEvent` attempt a fresh fetch.
      if (audio.error) audio.load();

      // TODO: Might need this for `data-initial-progress`
      //       Does seem to cause trouble when broadcasting
      //       (open multiple sessions and play the next audio)
      // if (audio.readyState === 0) audio.load();
      if (!audio.isConnected) return;

      const promise = audio.play() || Promise.resolve();
      item.intendsToPlay = true;

      // On iOS a backgrounded play() can resolve without playback ever
      // starting — mobile Safari suspends the load (and the audio session)
      // until the page is visible again. Don't claim it's playing in that
      // case: `playEvent`/`playingEvent` set the state if playback truly
      // starts, and the media session won't show a phantom progress. The
      // visibilitychange handler (see connectedCallback) resumes playback
      // on refocus using `intendsToPlay`.
      if (!(IS_IOS && document.hidden)) {
        item.$state.isPlaying.set(true);
      }

      promise.catch((e) => {
        if (!audio.isConnected) {
          /* The node was removed from the DOM, we can ignore this error */
          return;
        }

        // Interrupted by a subsequent load() or pause() — benign. Crucially
        // the isPlaying intent must survive so stall recovery (see
        // `waitingEvent`) can resume playback on the next canplay.
        if (e?.name === "AbortError") return;

        // Failure of an attempt driven by the automatic retry loop (see
        // `errorEvent`): the loop owns recovery and keeps retrying, so don't
        // clear the intent or surface a "resume manually" error.
        if (item.autoRetrying) return;

        const err =
          "Couldn't play audio automatically. Please resume playback manually.";
        console.error(err, e);

        // A real media error leaves the element dead: keep the intent so the
        // automatic retry (`errorEvent`) reloads and replays it. Only clear
        // the intent when the element itself is still usable.
        if (!audio.error) item.intendsToPlay = false;
        item.$state.isPlaying.set(false);
      });
    });
  }

  /**
   * Reload the audio after an error occurred — or unconditionally when
   * `force`d, which is what a refreshed source URL needs: `supply` only swaps
   * the `<source>` and never interrupts a healthy element. `progress` restores
   * the playback position across the reload.
   *
   * @type {Actions["reload"]}
   */
  reload(args) {
    this.#withAudioNode(args.audioId, (audio, item) => {
      if (args.force || audio.readyState === 0 || audio.error?.code === 2) {
        audio.load();

        if (args.progress !== undefined) {
          item.setAttribute(
            "initial-progress",
            JSON.stringify(args.progress),
          );
        }

        if (args.play) {
          this.play({ audioId: args.audioId, volume: audio.volume });
        }
      }
    });
  }

  /**
   * @type {Actions["seek"]}
   */
  seek({ audioId, currentTime, percentage }) {
    this.#withAudioNode(audioId, (audio, item) => {
      if (currentTime != undefined) {
        audio.currentTime = currentTime;
      } else if (
        percentage != undefined && !isNaN(audio.duration) &&
        audio.duration !== Infinity
      ) {
        audio.currentTime = percentage * audio.duration;
      }

      // A seek starts a fresh load at the new position. If playback was
      // expected, surface the rebuffer as "loading", re-assert the play
      // intent (the retry loop needs it if the range fetch errors — the
      // pending `play()` promise rejection would otherwise clear it before
      // `errorEvent` sees it), and arm the load watchdog (a range fetch that
      // stalls produces no `waiting`/`error` while `audio.seeking` is true).
      if (item.intendsToPlay || item.$state.isPlaying.get()) {
        item.intendsToPlay = true;
        item.$state.loadingState.set("loading");
        item.armLoadWatchdog();
      }
    });
  }

  /**
   * @type {Actions["supply"]}
   */
  supply(args) {
    const previous = this.#items.value;
    const existingMap = new Map(previous.map((a) => [a.id, a]));

    // Start loading new streams
    for (const item of args.audio) {
      if (
        "stream" in item &&
        !existingMap.has(item.id) &&
        !this.#streams.has(item.id)
      ) {
        this.#streams.set(item.id, item.stream);
        this.#resolveStream(
          item.id,
          item.stream,
          item.mimeType ?? "",
          item.seek,
          item.duration,
          this.#streamAbort.signal,
        );
      }
    }

    // Stop streams that are no longer needed
    const newIds = new Set(args.audio.map((a) => a.id));

    for (const [id, objectUrl] of this.#mediaSourceUrls) {
      if (!newIds.has(id)) {
        URL.revokeObjectURL(objectUrl);
        this.#mediaSourceUrls.delete(id);
      }
    }

    for (const id of this.#streams.keys()) {
      if (!newIds.has(id)) this.#streams.delete(id);
    }

    /** @type {AudioUrl[]} Remove `stream` field, replace it with `url` */
    const resolvedAudio = args.audio.map((a) => {
      let url = "stream" in a ? this.#mediaSourceUrls.get(a.id) : a.url;

      if (!url && "stream" in a && this.#streams.has(a.id)) {
        // #resolveStream creates the media source URL synchronously,
        // so this should be unreachable.
        throw new Error("Stream did not produce a media source url");
      }

      // A stream rejected by #resolveStream (e.g. MediaSource unsupported
      // on this browser) renders without a source; #resolveStream flags
      // the error on the item's state instead.
      url = url ?? "";

      return {
        id: a.id,
        isPreload: a.isPreload,
        mimeType: a.mimeType,
        progress: a.progress,
        track: a.track,
        url,
        expiresAt: "url" in a ? a.expiresAt : undefined,
      };
    });

    const hasNewIds = resolvedAudio.some((a) => !existingMap.has(a.id));

    const hasUrlChanges = resolvedAudio.some(
      (a) => existingMap.get(a.id)?.url !== a.url,
    );

    // Recompose the item list whenever it differs from what is rendered,
    // including *removals* and reordering. Comparing only additions/preload/url
    // changes left dropped items (e.g. a preload whose track is no longer next)
    // rendered forever — with its <audio> element still holding a network
    // request open.
    const hasCompositionChanges = previous.length !== resolvedAudio.length ||
      resolvedAudio.some((a, i) => {
        const prev = previous[i];
        return prev.id !== a.id ||
          prev.url !== a.url ||
          prev.isPreload !== a.isPreload ||
          prev.mimeType !== a.mimeType ||
          prev.progress !== a.progress;
      });

    if (hasNewIds || hasCompositionChanges) {
      this.#items.value = resolvedAudio;
    }

    // When only the URL changed for an existing item (e.g. tab leadership handoff invalidated
    // a blob URL), the same <de-audio-item> element is reused via `repeat`. lit-html will
    // update <source src> but the browser won't reload on its own — call audio.load() if the
    // element hasn't successfully loaded yet so it picks up the fresh URL.
    if (hasUrlChanges && !hasNewIds) {
      for (const a of resolvedAudio) {
        if (existingMap.has(a.id) && existingMap.get(a.id)?.url !== a.url) {
          this.#withAudioNode(a.id, (audio) => {
            // Clear any `src` attribute left behind by a previously
            // stream-backed track (#resolveStream sets it imperatively):
            // it takes precedence over the <source> element and may point
            // at a revoked object URL.
            audio.removeAttribute("src");
            if (audio.readyState === 0 || audio.error) audio.load();
          });
        }
      }
    }

    if (args.play) this.play(args.play);
  }

  // STREAMS

  /**
   * @param {string} id
   * @param {ReadableStream} stream
   * @param {string} mimeType
   * @param {((timeSeconds: number) => Promise<ReadableStream>) | undefined} seekFn
   * @param {number | undefined} duration
   * @param {AbortSignal} [signal]
   */
  async #resolveStream(id, stream, mimeType, seekFn, duration, signal) {
    // MediaSource is unavailable on iPhone before iOS 17.1, so bail out
    // early when MSE (or its managed variant) is missing, or when the mime
    // type is unsupported — otherwise the item would hang in a loading
    // state forever with an unhandled rejection.
    const win = /** @type {any} */ (globalThis);
    const MediaSourceCtor = /** @type {typeof MediaSource | undefined} */ (
      win.MediaSource ?? win.ManagedMediaSource
    );

    if (
      !MediaSourceCtor || !mimeType ||
      !MediaSourceCtor.isTypeSupported(mimeType)
    ) {
      // Delete synchronously so `supply()` treats the stream as resolved
      // (it renders the item without a source), then flag the error on the
      // item's state once its element exists.
      this.#streams.delete(id);
      stream.cancel().catch(() => {});
      Promise.resolve().then(() => {
        this.#itemElement(id)?.$state.loadingState.set({
          error: { code: 4 }, // MEDIA_ERR_SRC_NOT_SUPPORTED
        });
      });
      return;
    }

    const mediaSource = new MediaSourceCtor();
    const objectUrl = URL.createObjectURL(mediaSource);

    this.#mediaSourceUrls.set(id, objectUrl);
    this.#streams.delete(id);

    // Yield so the render triggered by supply() can complete, ensuring the
    // audio element is in the DOM before we set its src.
    await Promise.resolve();

    if (!this.#mediaSourceUrls.has(id)) {
      // Item was removed while waiting
      URL.revokeObjectURL(objectUrl);
      stream.cancel().catch(() => {});
      return;
    }

    const itemEl = this.#itemElement(id);
    if (!itemEl) {
      URL.revokeObjectURL(objectUrl);
      this.#mediaSourceUrls.delete(id);
      stream.cancel().catch(() => {});
      return;
    }

    // MediaSource must be attached via audio.src directly;
    // <source> elements do not trigger sourceopen.
    itemEl.audio.src = objectUrl;

    // Wait for `sourceopen`, but bail out if the element is torn down while
    // we're still waiting (sourceopen may never fire then).
    await new Promise((resolve) => {
      const onOpen = () => {
        cleanup();
        resolve(undefined);
      };
      const onAbort = () => {
        cleanup();
        resolve(undefined);
      };
      const cleanup = () => {
        mediaSource.removeEventListener("sourceopen", onOpen);
        signal?.removeEventListener("abort", onAbort);
      };

      mediaSource.addEventListener("sourceopen", onOpen, { once: true });
      signal?.addEventListener("abort", onAbort, { once: true });
    });

    if (!this.#mediaSourceUrls.has(id)) {
      // The item was removed — or the engine torn down — while awaiting
      // `sourceopen`. Nothing to buffer; release the URL if it wasn't already
      // revoked (e.g. by supply()).
      URL.revokeObjectURL(objectUrl);
      this.#mediaSourceUrls.delete(id);
      return;
    }

    // 'reader' is always the current active reader; the seeking handler
    // closes over this variable so it always cancels the right one.
    let reader = stream.getReader();
    let seekPending = false;
    let seekTarget = 0;

    const onSeeking = () => {
      if (!seekFn) return;
      const audio = itemEl.audio;
      const target = audio.currentTime;

      // Only intervene if the target is outside what's already buffered.
      for (let i = 0; i < audio.buffered.length; i++) {
        if (
          audio.buffered.start(i) <= target && target <= audio.buffered.end(i)
        ) {
          return; // Browser can handle it with buffered data.
        }
      }

      seekPending = true;
      seekTarget = target;
      reader.cancel().catch(() => {});
    };

    itemEl.audio.addEventListener("seeking", onSeeking);

    try {
      if (duration !== undefined) mediaSource.duration = duration;

      const sourceBuffer = mediaSource.addSourceBuffer(mimeType);

      while (true) {
        if (!this.#mediaSourceUrls.has(id)) {
          await reader.cancel();
          break;
        }

        let done, value;

        try {
          ({ done, value } = await reader.read());
        } catch {
          done = true;
        }

        if (!this.#mediaSourceUrls.has(id)) break;

        if (seekPending) {
          seekPending = false;

          // Clear all buffered data before feeding from the new position.
          if (sourceBuffer.updating) await waitForUpdateEnd(sourceBuffer);
          const removal = waitForUpdateEnd(sourceBuffer);
          sourceBuffer.remove(0, Infinity);
          if (!(await removal)) {
            throw new Error("SourceBuffer remove failed");
          }

          if (!seekFn) throw new Error("seekFn is undefined");
          reader = (await seekFn(seekTarget)).getReader();

          continue;
        }

        if (done) {
          if (mediaSource.readyState === "open") mediaSource.endOfStream();
          break;
        }

        if (sourceBuffer.updating) await waitForUpdateEnd(sourceBuffer);

        const appending = waitForUpdateEnd(sourceBuffer);
        sourceBuffer.appendBuffer(value);
        if (!(await appending)) {
          throw new Error("SourceBuffer append failed");
        }
      }
    } catch (err) {
      console.error("[audio engine] Stream error:", err);
      if (mediaSource.readyState === "open") mediaSource.endOfStream("decode");

      // Only surface the error if this stream is still the item's source —
      // on iOS the node may already have been reused for another track.
      if (this.#mediaSourceUrls.get(id) === objectUrl) {
        itemEl.$state.loadingState.set({ error: { code: 3 } });
      }
    } finally {
      itemEl.audio.removeEventListener("seeking", onSeeking);

      // Stop pulling from the stream's underlying source (e.g. a fetch).
      // Exiting the read loop without cancelling leaves the producer's
      // request open — a permanently pending connection. Cancelling an
      // already-cancelled/done reader is a no-op.
      reader.cancel().catch(() => {});
    }
  }

  // RENDER

  /**
   * @param {RenderArg} _
   */
  render({ html }) {
    const allItems = this.items();

    // Render every item, including the preloaded next track. On iOS this is
    // what lets the next track's bytes buffer while the current one plays, so
    // the locked-screen handoff only needs play() — no background load() that
    // would tear down the audio session and leave playback silent.
    const items = allItems;

    const ids = allItems.map((i) => i.id);

    this.querySelectorAll("de-audio-item").forEach((element) => {
      if (ids.includes(element.id)) return;

      // Detached media elements can keep playing (notorious on iOS, but
      // possible elsewhere too) and, in Firefox, keep their in-flight network
      // request (and socket) open. Updating <source src> alone doesn't stop
      // that — resource selection only re-runs on load() — so fully release
      // the node before lit-html drops it.
      const audio = element.querySelector("audio");
      if (!audio) return;

      // Unhook it from the Web Audio graph (a `createMediaElementSource` node
      // can only be made once per element, and the element is about to be
      // dropped, so the source node must be released).
      this[UNROUTE_AUDIO](audio);

      releaseAudioElement(audio);
    });

    const group = this.group;

    // Reconcile by track id instead of by list position. Rendering the items
    // as a plain array made lit-html reuse the child parts positionally: when
    // the preloaded next track moved from second to first place, the part in
    // first place was re-created for it (restarting the download) while the
    // preloaded element was dropped from second place *without* being unloaded
    // (its id was still in `ids`, so the cleanup above skipped it). That
    // abandoned element keeps its media request alive — the connection leak.
    // `repeat` moves the existing parts (and their <audio> elements) with the
    // key instead, so a preloaded track is promoted in place.
    const nodes = repeat(
      items,
      (audio) => audio.id,
      (audio) => {
        const ip = audio.progress === undefined
          ? "0"
          : JSON.stringify(audio.progress);

        return html`
          <de-audio-item
            group="${this.broadcasted ? `${group}/${audio.id}` : nothing}"
            id="${audio.id}"
            initial-progress="${ip}"
            mime-type="${audio.mimeType ? audio.mimeType : nothing}"
            preload="${audio.isPreload ? `preload` : nothing}"
            url="${audio.url ?? nothing}"
          >
            <audio
              crossorigin="anonymous"
              preload="auto"
            >
              ${audio.url
                ? html`
                  <source
                    src="${audio.url}"
                    ${audio.mimeType ? 'type="' + audio.mimeType + '"' : ""}
                  />
                `
                : nothing}
            </audio>
          </de-audio-item>
        `;
      },
    );

    return html`
      <section id="audio-nodes">
        ${nodes}
      </section>
    `;
  }

  // 🛠️

  /**
   * Get the state of a single audio item.
   *
   * @param {string} audioId
   * @returns {SignalReader<AudioStateReadOnly | undefined>}
   */
  _state(audioId) {
    return computed(() => {
      const _trigger = this.#items.value;

      const s = this.#itemElement(audioId)?.state;
      return s ? { ...s } : undefined;
    });
  }

  /**
   * Get the state of a single audio item.
   *
   * @param {string} audioId
   * @returns {AudioStateReadOnly | undefined}
   */
  state(audioId) {
    return this._state(audioId)();
  }

  /**
   * @param {string} audioId
   */
  #itemElement(audioId) {
    const node = this.querySelector(
      `de-audio-item[id="${audioId}"]:not([preload])`,
    ) ?? this.querySelector(
      `de-audio-item[id="${audioId}"]`,
    );

    if (node) {
      const item = /** @type {AudioEngineItem} */ (node);
      return item;
    }
  }

  /**
   * @param {string} audioId
   * @param {(audio: HTMLAudioElement, item: AudioEngineItem) => void} fn
   */
  #withAudioNode(audioId, fn) {
    const item = this.#itemElement(audioId);
    if (item) fn(item.audio, item);
  }

  /**
   * Drops a preloaded item whose background fetch is stuck. Removing it from
   * `#items` makes the render cleanup unload its <audio> element, aborting the
   * fetch; the track is re-resolved and re-rendered normally if it later
   * becomes the active track.
   *
   * Module-internal; called by {@link AudioEngineItem}'s load watchdog.
   *
   * @param {string} audioId
   */
  [CANCEL_PRELOAD](audioId) {
    const items = this.#items.value;
    const item = items.find((i) => i.id === audioId);
    if (!item?.isPreload) return;

    this.#items.value = items.filter((i) => i.id !== audioId);
  }

  // WEB AUDIO

  /**
   * The shared Web Audio graph, exposed so consumers (equalizer / visualizer
   * plugins, themes, …) can hook into the audio signal.
   *
   * Every <audio> element is routed into the `input` node (with master volume
   * already applied). By default `input` is connected straight to the
   * destination:
   *
   *   source -> input -> destination
   *
   * To insert processing, disconnect that pass-through edge and reconnect it
   * through your own chain, ending at the destination. For example, wiring in
   * a biquad filter chain and an analyser:
   *
   * ```ignore
   * const { context, input, destination } = engine.webAudio;
   * const eq = context.createBiquadFilter();
   * const analyser = context.createAnalyser();
   * input.disconnect(destination);  // remove the default pass-through
   * input.connect(eq);              // re-route through your chain
   * eq.connect(analyser);
   * analyser.connect(destination);
   * ```
   *
   * Use `context.resume()` to unlock the context on a user gesture (browsers
   * start it suspended until interaction).
   */
  get webAudio() {
    this.#ensureAudioGraph();

    return {
      context: /** @type {AudioContext} */ (this.#audioContext),
      input: /** @type {GainNode} */ (this.#input),
      destination: /** @type {AudioContext} */ (this.#audioContext).destination,
    };
  }

  /** Lazily creates the shared AudioContext and the default (pass-through) graph. */
  #ensureAudioGraph() {
    if (this.#audioContext) return;

    /** @type {typeof AudioContext | undefined} */
    const Ctx = globalThis.AudioContext ?? /** @type {any} */ (globalThis)
        .webkitAudioContext;
    if (!Ctx) return;

    const context = new Ctx();
    const input = context.createGain();

    // Pass-through; consumers disconnect this edge to insert their chain.
    input.connect(context.destination);

    this.#audioContext = context;
    this.#input = input;

    // Apply the (possibly persisted) master volume to the freshly created node.
    input.gain.value = this.#volume.value;

    // Apply the (possibly persisted) audio output device for this group.
    this.#applySink();

    // Unlock the context on any user gesture, for the life of the page.
    // Mobile browsers start the context suspended (autoplay policy) and can
    // suspend it again at any time (audio-session interruptions, route
    // changes, backgrounding). `resume()` is only ever allowed inside a user
    // gesture, so keep the listeners installed permanently: every routed
    // element's output flows through this context, and a context nobody
    // re-unlocks means silent playback. `resume()` on a running context is a
    // no-op, so re-firing on every interaction is safe.
    const unlock = () => {
      if (context.state !== "running") {
        context.resume().catch(() => {});
      }
    };
    ["touchstart", "touchend", "mousedown", "keydown"].forEach((e) => {
      document.addEventListener(e, unlock, { passive: true });
    });

    // Interruption watchdog: attempt an immediate resume whenever the browser
    // suspends the context while the page is visible (e.g. iOS after a
    // lock-screen interaction). If the browser demands a gesture, the
    // persistent listeners above cover the next interaction.
    context.addEventListener("statechange", () => {
      if (context.state === "suspended" && !document.hidden) {
        context.resume().catch(() => {});
      }
    });

    // Re-unlock a context that was suspended while the page was backgrounded
    // (mobile Safari suspends the audio session off-screen).
    document.addEventListener("visibilitychange", unlock);
  }

  /**
   * Routes an <audio> element through the Web Audio graph. Safe to call more
   * than once per element (eg. when a single node is reused on iOS).
   *
   * Module-internal; use `webAudio` to consume the graph.
   *
   * @param {HTMLAudioElement} audio
   */
  [ROUTE_AUDIO](audio) {
    if (this.#sourceNodes.has(audio)) return;

    this.#ensureAudioGraph();
    if (!this.#audioContext || !this.#input) return;

    let source;
    try {
      source = this.#audioContext.createMediaElementSource(audio);
    } catch {
      // A `createMediaElementSource` node can only be created once per element.
      // This can only happen for an element whose node belongs to a graph that
      // was torn down — its output is owned by a dead node and cannot be
      // re-routed. Do NOT register it as routed: the `#sourceNodes` map is
      // also the volume effect's “handled by the graph” marker, and a bogus
      // entry would bypass master volume (full-volume output). Fall back to
      // element-level volume instead, which the volume effect keeps in sync.
      audio.volume = this.#volume.value;
      console.warn(
        "Failed to route audio element through the Web Audio graph; " +
          "falling back to element-level volume.",
        audio,
      );
      return;
    }
    source.connect(this.#input);
    this.#sourceNodes.set(audio, source);

    // Volume is handled by the graph's input gain node; keep the element's own
    // volume at unity so the two don't compound.
    audio.volume = 1;
  }

  /**
   * Removes an <audio> element's source node from the graph. Mostly useful
   * when the element is dropped (no longer in `this.items()`).
   *
   * Module-internal; use `webAudio` to consume the graph.
   *
   * @param {HTMLAudioElement} audio
   */
  [UNROUTE_AUDIO](audio) {
    const source = this.#sourceNodes.get(audio);
    if (!source) return;

    source.disconnect();
    this.#sourceNodes.delete(audio);
  }

  /** Resumes the shared AudioContext if it is suspended (e.g. autoplay policy). */
  #resumeContext() {
    this.#audioContext?.resume().catch(() => {});
  }

  // AUDIO OUTPUT (SINK)

  /**
   * Selects the audio output device for this group and persists the choice.
   *
   * The device id comes from `navigator.mediaDevices.enumerateDevices()`
   * (`kind === "audiooutput"`); an empty string selects the system default.
   * Applied to the shared {@link AudioContext} via `setSinkId`, so every routed
   * `<audio>` element plays through the chosen device. Best-effort: browsers
   * without `AudioContext.setSinkId` (Firefox/Safari) ignore it and keep using
   * the system default.
   *
   * @param {string} sinkId
   */
  async setSink(sinkId) {
    if (sinkId) localStorage.setItem(this.#sinkStorageKey(), sinkId);
    else localStorage.removeItem(this.#sinkStorageKey());

    await this.#applySink();
  }

  /** @returns {string} localStorage key holding this group's output device id. */
  #sinkStorageKey() {
    return `${this.constructor.prototype.constructor.NAME}/${this.group}/sink`;
  }

  /**
   * Applies the stored output device to the shared AudioContext. No-op until
   * the graph exists or when the stored value hasn't changed.
   */
  async #applySink() {
    const context = this.#audioContext;
    if (!context) return;

    const sinkId = localStorage.getItem(this.#sinkStorageKey()) ?? "";
    if (sinkId === this.#appliedSink) return;

    const ctx =
      /** @type {AudioContext & { setSinkId?: (id: string) => Promise<void> }} */ (
        context
      );

    if (typeof ctx.setSinkId !== "function") {
      // No support: remember the value so we don't warn on every interaction.
      this.#appliedSink = sinkId;
      if (sinkId) {
        console.warn(
          "This browser does not support selecting an audio output device " +
            "(AudioContext.setSinkId); using the system default.",
        );
      }
      return;
    }

    try {
      await ctx.setSinkId(sinkId);
      this.#appliedSink = sinkId;
    } catch (err) {
      // e.g. NotAllowedError (permission / cross-origin iframe policy) or
      // NotFoundError (device unplugged). Keep the current device and retry
      // when the preference changes again.
      console.warn("Failed to set the audio output device.", err);
    }
  }
}

export default AudioEngine;

////////////////////////////////////////////
// ITEM ELEMENT
////////////////////////////////////////////

class AudioEngineItem extends BroadcastableDiffuseElement {
  static NAME = "diffuse/engine/audio/item";
  static observedAttributes = ["preload"];

  // MEDIA ERROR RETRY
  /** @type {ReturnType<typeof setTimeout> | undefined} Pending automatic retry timeout. */
  #retryTimer = undefined;
  /** @type {number} Retry attempts already used. */
  #retryAttempt = 0;

  // LOAD WATCHDOG
  /** @type {ReturnType<typeof setTimeout> | undefined} Pending load-watchdog timeout. */
  #watchdogTimer = undefined;
  /** @type {number} Watchdog trips used for backoff growth. */
  #watchdogAttempt = 0;
  /** @type {number} Consecutive data-less windows spent waiting on an in-flight fetch. */
  #loadWaitTrips = 0;
  /** @type {number} Consecutive data-less reloads — recovery-declared-futile counter. */
  #datalessReloads = 0;

  /** @type {(() => void) | undefined} Visibility/online re-arm listener. */
  #rearmListener = undefined;

  constructor() {
    super();

    // TODO:
    // const ip = this.getAttribute("initial-progress");

    /**
     * Playback was requested but hasn't (visibly) started yet. Unlike
     * `$state.isPlaying` this is never claimed optimistically on iOS while
     * hidden, so it survives the "play() resolved but nothing plays" case
     * and lets the engine resume on refocus. Cleared once playback truly
     * starts, on explicit pause, or when playback fails in the foreground.
     */
    this.intendsToPlay = false;

    /**
     * True while the automatic retry loop is active. The engine's `play()`
     * catch uses it to suppress the "resume playback manually" error for
     * attempts the loop itself drives.
     */
    this.autoRetrying = false;

    /**
     * @type {AudioState}
     */
    this.$state = {
      currentTime: signal(0),
      duration: signal(0),
      hasEnded: signal(false),
      isPlaying: signal(false),
      isPreload: signal(this.hasAttribute("preload")),
      loadingState: signal(/** @type {LoadingState} */ ("initialisation")),

      progress: computed(() => {
        const currentTime = this.$state.currentTime.value;
        const duration = this.$state.duration.value;

        if (!duration || isNaN(duration) || duration === Infinity) return 0;

        return currentTime / duration;
      }),
    };
  }

  /**
   * @override
   * @param {string} name
   * @param {string} oldValue
   * @param {string} newValue
   */
  attributeChangedCallback(name, oldValue, newValue) {
    super.attributeChangedCallback(name, oldValue, newValue);
    if (name === "preload") {
      this.$state.isPreload.set(newValue !== null);

      // Now the active track: start watching its load for hangs, with a fresh
      // backoff (a preload phase may have accumulated wait trips).
      if (newValue === null) {
        this.#resetWatchdog();
        this.#armWatchdog();
      }
    }
  }

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    const audio = this.audio;

    // If this item was released while detached (e.g. the engine moved in the
    // DOM), re-select its source so it can load again.
    if (audio.getAttribute("src") === SILENT_AUDIO_SRC) {
      audio.removeAttribute("src");
      audio.load();
    }

    audio.addEventListener("canplay", this.canplayEvent);
    audio.addEventListener("durationchange", this.durationchangeEvent);
    audio.addEventListener("ended", this.endedEvent);
    audio.addEventListener("error", this.errorEvent);
    audio.addEventListener("pause", this.pauseEvent);
    audio.addEventListener("play", this.playEvent);
    audio.addEventListener("playing", this.playingEvent);
    audio.addEventListener("suspend", this.suspendEvent);
    audio.addEventListener("timeupdate", this.timeupdateEvent);
    audio.addEventListener("progress", this.progressEvent);
    audio.addEventListener("waiting", this.waitingEvent);

    // Transition from initialisation to loading for non-preload items. Only
    // on the first connection: the engine's keyed rendering may move a live
    // item to another position (disconnect + reconnect), and resetting a
    // buffered item back to "loading" would strand the UI there — no new
    // `canplay` fires for a resource that is already loaded.
    if (
      !this.hasAttribute("preload") &&
      this.$state.loadingState.get() === "initialisation"
    ) {
      this.$state.loadingState.set("loading");
    }

    // Watch the initial load: a fetch that hangs without data never fires
    // `error`. An active track is reloaded after a data-less window; a preload
    // is cancelled (see `#watchdogTrip`).
    this.#armWatchdog();

    // Re-arm a bounded recovery attempt when conditions may have changed:
    // refocusing (e.g. after background recovery) or the network coming back.
    // An element that gave up (see `#watchdogTrip`) gets one fresh budget
    // here; healthy loads just reset and stop from the trip. Without this,
    // an element that declared recovery futile would never retry on its own.
    // Scoped to elements with play intent or an error so paused, never-loaded
    // items don't start a perpetual trip loop.
    this.#rearmListener = () => {
      if (document.hidden) return;

      let errored = false;
      try {
        errored = this.audio?.error != null;
      } catch {
        // No child <audio> yet — nothing to recover.
        return;
      }

      if (
        !this.intendsToPlay && !this.$state.isPlaying.get() && !errored
      ) return;

      this.#datalessReloads = 0;
      this.#armWatchdog();
    };
    document.addEventListener("visibilitychange", this.#rearmListener);
    globalThis.addEventListener("online", this.#rearmListener);

    // Setup broadcasting if part of group
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(
        this.identifier,
        {
          getCurrentTime: {
            strategy: "leaderOnly",
            fn: this.$state.currentTime.get,
          },
          getDuration: { strategy: "leaderOnly", fn: this.$state.duration.get },
          getHasEnded: { strategy: "leaderOnly", fn: this.$state.hasEnded.get },
          getIsPlaying: {
            strategy: "leaderOnly",
            fn: this.$state.isPlaying.get,
          },
          getIsPreload: {
            strategy: "leaderOnly",
            fn: this.$state.isPreload.get,
          },
          getLoadingState: {
            strategy: "leaderOnly",
            fn: this.$state.loadingState.get,
          },

          // SET
          setCurrentTime: {
            strategy: "replicate",
            fn: this.$state.currentTime.set,
          },
          setDuration: { strategy: "replicate", fn: this.$state.duration.set },
          setHasEnded: { strategy: "replicate", fn: this.$state.hasEnded.set },
          setIsPlaying: {
            strategy: "replicate",
            fn: this.$state.isPlaying.set,
          },
          setIsPreload: {
            strategy: "replicate",
            fn: this.$state.isPreload.set,
          },
          setLoadingState: {
            strategy: "replicate",
            fn: this.$state.loadingState.set,
          },
        },
        {
          // Sync leadership with engine's broadcasting channel
          assumeLeadership: (await this.engine?.broadcastingStatus())?.leader,
        },
      );

      if (actions) {
        this.$state.currentTime.set = actions.setCurrentTime;
        this.$state.duration.set = actions.setDuration;
        this.$state.hasEnded.set = actions.setHasEnded;
        this.$state.isPlaying.set = actions.setIsPlaying;
        this.$state.isPreload.set = actions.setIsPreload;
        this.$state.loadingState.set = actions.setLoadingState;

        untracked(async () => {
          this.$state.currentTime.value = await actions.getCurrentTime();
          this.$state.duration.value = await actions.getDuration();
          this.$state.hasEnded.value = await actions.getHasEnded();
          this.$state.isPlaying.value = await actions.getIsPlaying();
          this.$state.isPreload.value = await actions.getIsPreload();
          this.$state.loadingState.value = await actions.getLoadingState();
        });
      }
    }

    // Super
    super.connectedCallback();

    // Route this item's <audio> through the engine's shared Web Audio graph
    // so volume flows through the gain node and consumers (equalizer,
    // visualizer plugins, etc) can tap into the signal. Idempotent per element.
    this.engine?.[ROUTE_AUDIO](this.audio);
  }

  /**
   * @override
   */
  disconnectedCallback() {
    this.cancelMediaRetry();
    this.#disarmWatchdog();

    if (this.#rearmListener) {
      document.removeEventListener("visibilitychange", this.#rearmListener);
      globalThis.removeEventListener("online", this.#rearmListener);
      this.#rearmListener = undefined;
    }

    // A media element removed from the document keeps its network request (and
    // socket) alive; Firefox in particular can hold it until the element is
    // garbage collected, which may be never while the tab lives. lit-html
    // removes nodes during a render and doesn't always route through the
    // engine's id-based cleanup, so release the resource here too — on a
    // microtask, so a pure DOM move (disconnect + reconnect in the same task)
    // doesn't interrupt playback.
    queueMicrotask(() => {
      if (this.isConnected) return;

      try {
        releaseAudioElement(this.audio);
      } catch {
        // No child <audio> anymore — nothing to release.
      }
    });

    // NOTE: the Web Audio source node is intentionally NOT detached here. A
    // `createMediaElementSource` node can only be made once per element, so
    // un-routing a still-reusable element (e.g. the engine moving in and out
    // of the DOM) would permanently silence it. Items that are actually
    // dropped are un-routed by the engine's render cleanup before lit drops
    // them.
    super.disconnectedCallback();
  }

  // STATE

  /**
   * @type {AudioStateReadOnly}
   */
  get state() {
    return {
      id: this.id,
      mimeType: this.getAttribute("mime-type") ?? undefined,
      url: this.getAttribute("url") ?? "",

      currentTime: this.$state.currentTime.get,
      duration: this.$state.duration.get,
      hasEnded: this.$state.hasEnded.get,
      isPlaying: this.$state.isPlaying.get,
      isPreload: this.$state.isPreload.get,
      loadingState: this.$state.loadingState.get,

      progress: this.$state.progress,
    };
  }

  // RELATED ELEMENTS

  get audio() {
    const el = this.querySelector("audio");
    if (el) return /** @type {HTMLAudioElement} */ (el);
    else throw new Error("Cannot find child audio element");
  }

  get engine() {
    const el = this.closest("de-audio");
    if (el) return /** @type {AudioEngine} */ (el);
    else return null;
  }

  // MEDIA ERROR RETRY

  /**
   * Schedules the next automatic retry after a transient media error. The
   * delay doubles per attempt (from {@link RETRY_BASE_DELAY_MS}) up to a
   * {@link RETRY_MAX_DELAY_MS} ceiling, then keeps retrying at that ceiling
   * until playback succeeds or the loop is cancelled (pause, drop).
   */
  #scheduleMediaRetry() {
    if (this.#retryTimer !== undefined) return;
    if (!this.isConnected) return;

    this.autoRetrying = true;
    const delay = Math.min(
      RETRY_BASE_DELAY_MS * 2 ** this.#retryAttempt,
      RETRY_MAX_DELAY_MS,
    );
    this.#retryAttempt += 1;
    this.#retryTimer = setTimeout(() => {
      this.#retryTimer = undefined;
      this.#retryMedia();
    }, delay);
  }

  /**
   * Reloads an errored element and resumes playback. Called by the retry
   * timer; `initial-progress` (consumed in `canplayEvent`) preserves the
   * playback position across the reload.
   */
  #retryMedia() {
    if (!this.isConnected) return;

    let audio;
    try {
      audio = this.audio;
    } catch {
      return;
    }

    // Only retry while the element actually has an error. If it recovered on
    // its own (browser-side retry, buffered data arriving) a `load()` here
    // would abort a healthy/playing element and start the failure cycle over.
    if (!audio.error) {
      // The element recovered on its own (browser-side retry, buffered data
      // arriving). Leave the loop so it doesn't keep suppressing later
      // `play()` failures, and so the next error starts from the base delay.
      this.autoRetrying = false;
      this.#retryAttempt = 0;
      return;
    }

    if (
      !isNaN(audio.duration) && audio.duration > 0 &&
      audio.duration !== Infinity
    ) {
      this.setAttribute(
        "initial-progress",
        JSON.stringify(audio.currentTime / audio.duration),
      );
    }

    this.$state.loadingState.set("loading");
    audio.load();

    // The error loop only re-acts on a new `error` event; the watchdog covers
    // the case where this retry's fetch hangs without one.
    this.#armWatchdog();

    this.engine?.play({ audioId: this.id });
  }

  /**
   * Stops the automatic retry loop (explicit pause, engine pause, or the
   * item being dropped). Safe to call from the engine for `pause()`.
   * Resets the backoff so the next failure starts from the base delay again.
   */
  cancelMediaRetry() {
    if (this.#retryTimer !== undefined) {
      clearTimeout(this.#retryTimer);
      this.#retryTimer = undefined;
    }
    this.#retryAttempt = 0;
    this.autoRetrying = false;
  }

  /**
   * Watchdog access for the engine (`seek` re-arms it, since a seek starts a
   * fresh load). No-op when already armed.
   */
  armLoadWatchdog() {
    // A seek is explicit intent and starts a fresh load: grant a fresh
    // bounded-recovery budget along with it.
    this.#datalessReloads = 0;
    this.#armWatchdog();
  }

  // EVENTS

  /**
   * @param {Event} event
   */
  canplayEvent(event) {
    const audio = /** @type {HTMLAudioElement} */ (event.target);
    const item = engineItem(audio);

    if (
      item?.hasAttribute("initial-progress") &&
      audio.duration &&
      !isNaN(audio.duration)
    ) {
      const progress = JSON.parse(
        item.getAttribute("initial-progress") ?? "0",
      );
      if (
        progress !== 0 && !isNaN(audio.duration) && audio.duration !== Infinity
      ) {
        audio.currentTime = audio.duration * progress;
      }

      item.removeAttribute("initial-progress");
    }

    // Data arrived or became playable — the load is healthy; stop watching
    // (mid-playback refills are covered by `waitingEvent` re-arming).
    if (item) {
      item.#resetWatchdog();
      item.#disarmWatchdog();
    }

    finishedLoading(event);
  }

  /**
   * @param {Event} event
   */
  durationchangeEvent(event) {
    const audio = /** @type {HTMLAudioElement} */ (event.target);

    if (!isNaN(audio.duration)) {
      engineItem(audio)?.$state.duration.set(audio.duration);
    }
  }

  /**
   * @param {Event} event
   */
  endedEvent(event) {
    const audio = /** @type {HTMLAudioElement} */ (event.target);
    audio.currentTime = 0;

    const item = engineItem(audio);
    if (item) item.intendsToPlay = false;
    item?.$state.hasEnded.set(true);
  }

  /**
   * @param {Event} event
   */
  errorEvent(event) {
    const audio = /** @type {HTMLAudioElement} */ (event.target);
    const code = audio.error?.code || 0;

    const item = engineItem(audio);
    if (!item) return;

    // MEDIA_ERR_ABORTED: benign — fires whenever a `load()` interrupts an
    // in-flight request (our own retry reloads, `waitingEvent` recovery,
    // source swaps). Surface it as an error and the UI would show a stuck
    // "Audio error" after playback already recovered.
    if (code === 1) return;

    item.$state.loadingState.set({ error: { code } });

    // Transient network / CORS-handshake failures: retry automatically so
    // playback resumes on its own once the source is reachable again. The
    // first failure requires intent (the track was supposed to play);
    // afterwards the loop keeps retrying on its own.
    if (item.hasAttribute("preload")) return;
    if (audio.src.startsWith("blob:")) return; // MediaSource items handle their own errors
    if (!isRetryableMediaError(audio.error)) return;
    if (
      item.#retryAttempt === 0 &&
      !item.intendsToPlay &&
      !item.$state.isPlaying.get()
    ) {
      return;
    }
    item.#scheduleMediaRetry();
  }

  /**
   * @param {Event} event
   */
  pauseEvent(event) {
    const audio = /** @type {HTMLAudioElement} */ (event.target);
    const item = engineItem(audio);

    // A pause that coincides with a transient media error is the failure
    // stopping playback, not the user pausing. Tearing down the retry loop and
    // clearing `isPlaying` here would leave the element with no recovery path:
    // `errorEvent`'s intent guard (and the watchdog's error branch) would both
    // bail out, so the item would stay stuck on "Audio error" forever. Leave
    // the loop and playback state untouched — an explicit pause goes through
    // `AudioEngine.pause()`, which cancels the retry and clears the intent
    // before calling `audio.pause()` (so it still stops recovery).
    if (isRetryableMediaError(audio.error)) return;

    item?.cancelMediaRetry();
    if (item) {
      item.#resetWatchdog();
      item.#disarmWatchdog();
    }
    item?.$state.isPlaying.set(false);
  }

  /**
   * @param {Event} event
   */
  playEvent(event) {
    const audio = /** @type {HTMLAudioElement} */ (event.target);

    const item = engineItem(audio);
    item?.$state.hasEnded.set(false);
    item?.$state.isPlaying.set(true);

    // Explicit play intent: grant a fresh bounded-recovery budget (a
    // capped-out element gets one full cycle back on user action).
    if (item) item.#resetWatchdog();

    // In case audio was preloaded:
    if (audio.readyState >= 2) finishedLoading(event);
  }

  /**
   * @param {Event} event
   */
  playingEvent(event) {
    const audio = /** @type {HTMLAudioElement} */ (event.target);
    const item = engineItem(audio);

    // Playback truly started, intent fulfilled. Leave the retry loop and
    // reset the backoffs so the next failure starts from the base delay.
    if (item) {
      item.intendsToPlay = false;
      item.autoRetrying = false;
      item.#retryAttempt = 0;
      item.#resetWatchdog();
      item.#disarmWatchdog();
    }
    item?.$state.isPlaying.set(true);

    finishedLoading(event);
  }

  /**
   * @param {Event} event
   */
  suspendEvent(event) {
    finishedLoading(event);
  }

  /**
   * @param {Event} event
   */
  timeupdateEvent(event) {
    const audio = /** @type {HTMLAudioElement} */ (event.target);
    const item = engineItem(audio);
    if (!item) return;

    // Playback is progressing — clear any lingering "loading" state (set by
    // a mid-playback `waiting`) so the theme doesn't keep showing
    // "Loading audio ..." while the track plays. The browser only restores
    // `canplay`/`playing` when readyState crosses its thresholds, which it
    // may not do after a brief refill stall. A `timeupdate` caused by a seek
    // (position jump while rebuffering) doesn't count as progress.
    if (
      !audio.paused && !audio.seeking &&
      item.$state.loadingState.get() !== "loaded"
    ) {
      item.$state.loadingState.set("loaded");
    }

    if (isNaN(audio.duration) || audio.duration === 0) return;
    item.$state.currentTime.set(audio.currentTime);
  }

  /**
   * @param {Event} event
   */
  progressEvent(event) {
    const item = engineItem(/** @type {HTMLMediaElement} */ (event.target));
    if (!item) return;

    // Bytes are arriving — the load is alive. Restart the watchdog window
    // from the base delay so a slow-but-steady download never trips it, and
    // clear the in-flight wait counter (data did come through).
    item.#resetWatchdog();
    item.#restartWatchdog();
  }

  // LOAD WATCHDOG

  /**
   * Starts watching for a hung load. Browsers don't reliably fire
   * `stalled`/`error` while a fetch sits in NETWORK_LOADING without data, so
   * the watchdog polls instead: `progress` (bytes arriving), `canplay` and
   * `playing` all re-arm or disarm it — if the timer fires anyway, the load
   * has been data-less for the whole backoff window and gets reloaded.
   */
  #armWatchdog() {
    if (this.#watchdogTimer !== undefined) return;
    if (!this.isConnected) return;

    const delay = Math.min(
      LOAD_WATCHDOG_MS * 2 ** this.#watchdogAttempt,
      RETRY_MAX_DELAY_MS,
    );
    this.#watchdogTimer = setTimeout(() => {
      this.#watchdogTimer = undefined;
      this.#watchdogTrip();
    }, delay);
  }

  /**
   * Restarts the watchdog window from the current backoff. Unlike
   * {@link #armWatchdog} this clears an already-pending timer, so a stream of
   * `progress` events (bytes still arriving) keeps pushing the deadline out
   * instead of letting the original timer trip and discard the buffer.
   */
  #restartWatchdog() {
    this.#disarmWatchdog();
    this.#armWatchdog();
  }

  /** Clears the watchdog backoff once the load is known healthy (data/playable). */
  #resetWatchdog() {
    this.#watchdogAttempt = 0;
    this.#loadWaitTrips = 0;
    this.#datalessReloads = 0;
  }

  /** Stops the load watchdog (paused, dropped, playable). */
  #disarmWatchdog() {
    if (this.#watchdogTimer !== undefined) {
      clearTimeout(this.#watchdogTimer);
      this.#watchdogTimer = undefined;
    }
  }

  /**
   * Cancels a stuck preload: the engine drops the item, which unloads its
   * <audio> element and aborts the hung fetch. The track is re-resolved through
   * the normal supply path if it later becomes active.
   */
  #cancelPreload() {
    this.engine?.[CANCEL_PRELOAD](this.id);
  }

  /**
   * Called when a load produced no data (and no error) for the backoff window.
   * While the browser is still fetching (`NETWORK_LOADING`) we keep waiting —
   * a reload would cancel a live request and restart playback — up to
   * {@link LOAD_WAIT_LIMIT} windows, after which a silent request is treated as
   * hung. An active load the browser has given up on (`NETWORK_IDLE`) is
   * reloaded; a preload is cancelled instead.
   */
  #watchdogTrip() {
    if (!this.isConnected) return;

    let audio;
    try {
      audio = this.audio;
    } catch {
      return;
    }

    if (audio.src.startsWith("blob:")) return; // MediaSource items manage their own loads

    // On iOS the OS suspends background loads (and tears down the audio
    // session), so a hidden trip can only observe false positives — bail out.
    // Everywhere else, background tabs keep loading media: a fetch that dies
    // silently while hidden (laptop sleep, network switch) never fires
    // `error`/`progress`, so skipping the trip here would strand its pending
    // request AND leave the watchdog disarmed (this return is the only
    // non-re-arming exit for a connected element). Leaked pending requests
    // pile up until the browser's per-host connection limit starves all
    // traffic to that server, including audio — the same failure mode the
    // `BYTES_TIMEOUT_MS` guard in `components/input/common.js` documents for
    // artwork fetches.
    if (IS_IOS && document.hidden) return;

    // The error retry loop is armed AND the element is errored: it owns
    // reloads until its next attempt clears the error (and re-arms us). If
    // the element isn't errored the loop is between attempts — a hang with no
    // `error` is exactly the watchdog's job, so fall through and reload.
    if (this.autoRetrying && audio.error) return;

    // The load is actually fine — data arrived or the element is playable
    // since the timer was set. Give up watching until the next load kicks in.
    if (!audio.error && audio.readyState >= 2) {
      this.#resetWatchdog();
      return;
    }

    if (audio.error) {
      // An active error retry loop owns reloads and returns just above. If no
      // loop is pending — it was cancelled, or the error happened while the
      // item was still a preload — nothing would ever reload this element, so
      // re-engage the loop when we still intend to play the track.
      if (
        this.#retryTimer === undefined &&
        isRetryableMediaError(audio.error) &&
        (this.intendsToPlay || this.$state.isPlaying.get())
      ) {
        this.#scheduleMediaRetry();
      }
      return;
    }

    // Enough buffered data to play on — a slow refetch isn't a hang.
    if (
      audio.buffered.length > 0 &&
      audio.buffered.end(audio.buffered.length - 1) > audio.currentTime + 5
    ) {
      this.#resetWatchdog();
      return;
    }

    // A preload never starts playback, so there is nothing to resume or retry:
    // a background fetch that produces no data is cancelled outright — the
    // track is re-resolved and re-rendered if it later becomes active. A
    // still-fetching request gets the same bounded patience as an active load.
    if (this.hasAttribute("preload")) {
      if (
        audio.networkState === HTMLMediaElement.NETWORK_LOADING &&
        this.#loadWaitTrips < LOAD_WAIT_LIMIT
      ) {
        this.#loadWaitTrips += 1;
        this.#armWatchdog();
        return;
      }
      this.#cancelPreload();
      return;
    }

    // Nobody asked for this load yet (paused, play pending elsewhere): keep
    // checking, but don't reload — an abort here would discard the bytes a
    // future `play()` could already use.
    if (!this.intendsToPlay && !this.$state.isPlaying.get()) {
      this.#armWatchdog();
      return;
    }

    // The browser is still fetching (`NETWORK_LOADING`): the next chunk is on
    // its way, so wait for it. Reloading here aborts the in-flight request and
    // discards whatever was buffered, restarting playback from the preserved
    // position — the mid-playback restart we're trying to avoid. This is
    // bounded: a half-open connection can sit in `NETWORK_LOADING` forever, so
    // past `LOAD_WAIT_LIMIT` data-less windows we stop trusting the request and
    // reload it below.
    if (
      audio.networkState === HTMLMediaElement.NETWORK_LOADING &&
      this.#loadWaitTrips < LOAD_WAIT_LIMIT
    ) {
      this.#loadWaitTrips += 1;
      this.#armWatchdog();
      return;
    }

    // Sustained data-less failure: stop the reload cycle. See
    // DATALESS_RELOAD_LIMIT — when the wedged state is the connection pool or
    // the server itself, another reload cannot recover and keeps occupying
    // the connections recovery needs. Surface a terminal error instead; the
    // budget is restored by data, playback, a seek, refocus or `online`.
    this.#datalessReloads += 1;
    if (this.#datalessReloads > DATALESS_RELOAD_LIMIT) {
      if (this.#datalessReloads === DATALESS_RELOAD_LIMIT + 1) {
        this.$state.loadingState.set({ error: { code: 2 } }); // MEDIA_ERR_NETWORK
      }
      return;
    }

    this.#watchdogAttempt += 1;
    this.#loadWaitTrips = 0;

    // Preserve position across the reload (no-op for a never-started load).
    if (
      !isNaN(audio.duration) && audio.duration > 0 &&
      audio.duration !== Infinity
    ) {
      this.setAttribute(
        "initial-progress",
        JSON.stringify(audio.currentTime / audio.duration),
      );
    }

    this.$state.loadingState.set("loading");
    audio.load();
    if (this.intendsToPlay) {
      this.engine?.play({ audioId: this.id });
    }
    this.#armWatchdog();
  }

  /**
   * @param {Event} event
   */
  waitingEvent(event) {
    initiateLoading(event);

    const audio = /** @type {HTMLAudioElement} */ (event.target);
    if (audio.seeking) return;

    const item = engineItem(audio);
    if (!item || item.hasAttribute("preload")) return;

    // Playback stalled for data. While the browser is still fetching
    // (`NETWORK_LOADING`) the watchdog just waits for the next chunk; it only
    // reloads a load the browser has given up on (`NETWORK_IDLE`, handled
    // below). `progress`, `seek` and `retryMedia` arm/restart it too; all paths
    // share the single watchdog timer.
    item.#armWatchdog();

    if (audio.networkState !== HTMLMediaElement.NETWORK_IDLE) return;

    const progress = !isNaN(audio.duration) && audio.duration > 0 &&
        audio.duration !== Infinity
      ? audio.currentTime / audio.duration
      : 0;

    if (progress > 0) {
      item.setAttribute("initial-progress", JSON.stringify(progress));
    }

    // Don't force a full reload if the browser already has buffered data —
    // it should be able to continue buffering on its own. This prevents
    // discarding the preloaded buffer when playback briefly catches up to
    // the end of the downloaded portion.
    if (audio.buffered.length > 0) return;

    audio.load();

    audio.addEventListener("canplay", () => {
      if (item.$state.isPlaying.get() || item.intendsToPlay) {
        item.engine?.play({ audioId: item.id });
      }
    }, { once: true });
  }
}

export { AudioEngineItem };

////////////////////////////////////////////
// 🛠️
////////////////////////////////////////////

/**
 * Stops an <audio> element and releases its network resource.
 *
 * `pause()` alone doesn't abort a fetch; `removeAttribute("src")` + `load()`
 * aborts it in most browsers but not reliably in Firefox, where a detached
 * media element can keep the request (and its socket) until it is garbage
 * collected. Assigning the silent data URL forces resource selection onto a
 * local resource immediately.
 *
 * @param {HTMLAudioElement} audio
 */
function releaseAudioElement(audio) {
  audio.pause();
  audio.removeAttribute("src");
  audio.srcObject = null;
  audio.querySelectorAll("source").forEach((source) => {
    source.removeAttribute("src");
  });
  audio.src = SILENT_AUDIO_SRC;
  audio.load();
}

/**
 * Whether a media error is worth retrying automatically. `MEDIA_ERR_NETWORK`
 * and `MEDIA_ERR_SRC_NOT_SUPPORTED` both commonly surface from transient
 * connectivity or CORS-handshake failures; aborted and decode errors don't.
 *
 * @param {MediaError | null | undefined} error
 */
function isRetryableMediaError(error) {
  return error?.code === 2 || error?.code === 4;
}

/**
 * @param {HTMLAudioElement} audio
 */
function engineItem(audio) {
  const c = audio.closest("de-audio-item");
  if (c) return /** @type {AudioEngineItem} */ (c);
  else return null;
}

/**
 * @param {Event} event
 */
function finishedLoading(event) {
  const audio = /** @type {HTMLAudioElement} */ (event.target);
  engineItem(audio)?.$state.loadingState.set("loaded");
}

/**
 * @param {Event} event
 */
function initiateLoading(event) {
  const audio = /** @type {HTMLAudioElement} */ (event.target);
  if (audio.readyState < 4) {
    const item = engineItem(audio);
    if (item?.hasAttribute("preload")) return;
    item?.$state.loadingState.set("loading");
  }
}

/**
 * Resolves once the SourceBuffer finishes its current append/remove
 * operation. `true` on `updateend`, `false` on `updateerror` (which
 * WebKit's MSE may fire without a following `updateend`).
 *
 * @param {SourceBuffer} sourceBuffer
 * @returns {Promise<boolean>}
 */
function waitForUpdateEnd(sourceBuffer) {
  return new Promise((resolve) => {
    const onEnd = () => {
      cleanup();
      resolve(true);
    };
    const onError = () => {
      cleanup();
      resolve(false);
    };
    const cleanup = () => {
      sourceBuffer.removeEventListener("updateend", onEnd);
      sourceBuffer.removeEventListener("updateerror", onError);
    };

    sourceBuffer.addEventListener("updateend", onEnd);
    sourceBuffer.addEventListener("updateerror", onError);
  });
}

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = AudioEngine;
export const NAME = "de-audio";
export const NAME_ITEM = "de-audio-item";

defineElement(NAME, AudioEngine);
defineElement(NAME_ITEM, AudioEngineItem);
```
### Queue

A queue for tracks.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { signal } from "~/common/signal.js";
import { listen } from "~/common/worker.js";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts";
 * @import {Actions, Item, State} from "@specs/components/engine/queue/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<Actions>}
 */
class QueueEngine extends DiffuseElement {
  static NAME = "diffuse/engine/queue";
  static WORKER_URL = "components/engine/queue/worker.js";

  constructor() {
    super();

    /** @type {ProxiedActions<Actions & State>} */
    this.proxy = this.workerProxy();

    this.add = this.proxy.add;
    this.clear = this.proxy.clear;
    this.expel = this.proxy.expel;
    this.fill = this.proxy.fill;
    this.move = this.proxy.move;
    this.shift = this.proxy.shift;
    this.supply = this.proxy.supply;
    this.unshift = this.proxy.unshift;
  }

  // SIGNALS

  #future = signal(/** @type {Array<Item>} */ ([]));
  #now = signal(/** @type {Item | null} */ (null));
  #past = signal(/** @type {Array<Item>} */ ([]));
  #supplyFingerprint = signal(/** @type {string | undefined} */ (undefined));

  // STATE

  future = this.#future.get;
  now = this.#now.get;
  past = this.#past.get;
  supplyFingerprint = this.#supplyFingerprint.get;

  // LIFECYCLE

  /**
   * @override
   */
  connectedCallback() {
    super.connectedCallback();

    // Sync data with worker
    const link = this.workerLink();

    // Listen for remote data changes
    listen("future", this.#future.set, link);
    listen("now", this.#now.set, link);
    listen("past", this.#past.set, link);
    listen("supplyFingerprint", this.#supplyFingerprint.set, link);

    // Fetch current data state
    this.proxy.future().then(this.#future.set);
    this.proxy.now().then(this.#now.set);
    this.proxy.past().then(this.#past.set);
    this.proxy.supplyFingerprint().then(this.#supplyFingerprint.set);
  }
}

export default QueueEngine;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = QueueEngine;
export const NAME = "de-queue";

defineElement(NAME, QueueEngine);
```
### Repeat & Shuffle

Signals synced with local storage (classified by group) that decide if audio should be repeated and if the queue should be shuffled when filling it.

```js
import { BroadcastableDiffuseElement, defineElement } from "~/common/element.js";
import { signal } from "~/common/signal.js";

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

class RepeatShuffleEngine extends BroadcastableDiffuseElement {
  static NAME = "diffuse/engine/repeat-shuffle";

  // SIGNALS

  #repeat = signal(false);
  #shuffle = signal(false);

  repeat = this.#repeat.get;
  shuffle = this.#shuffle.get;

  // LIFECYCLE

  /**
   * @override
   */
  connectedCallback() {
    // Broadcast if needed
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(this.identifier, {
        setRepeat: { strategy: "replicate", fn: this.setRepeat },
        setShuffle: { strategy: "replicate", fn: this.setShuffle },
      });

      if (actions) {
        this.setRepeat = actions.setRepeat;
        this.setShuffle = actions.setShuffle;
      }
    }

    // Super
    super.connectedCallback();

    // Signals
    const storagePrefix =
      `${this.constructor.prototype.constructor.NAME}/${this.group}`;

    this.#repeat.value =
      localStorage.getItem(`${storagePrefix}/repeat`) === "true" ? true : false;
    this.#shuffle.value =
      localStorage.getItem(`${storagePrefix}/shuffle`) === "true"
        ? true
        : false;

    // Effects
    this.effect(() =>
      localStorage.setItem(
        `${storagePrefix}/repeat`,
        this.#repeat.value ? "true" : "false",
      )
    );

    this.effect(() =>
      localStorage.setItem(
        `${storagePrefix}/shuffle`,
        this.#shuffle.value ? "true" : "false",
      )
    );
  }

  // ACTIONS

  /** @param {boolean} bool */
  setRepeat = async (bool) => this.#repeat.value = bool;

  /** @param {boolean} bool */
  setShuffle = async (bool) => this.#shuffle.value = bool;
}

export default RepeatShuffleEngine;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = RepeatShuffleEngine;
export const NAME = "de-repeat-shuffle";

defineElement(NAME, CLASS);
```
### Scope

Signals that could influence the scope of a set of tracks.

```js
import {
  BroadcastableDiffuseElement,
  defineElement,
} from "~/common/element.js";
import { batch, signal } from "~/common/signal.js";

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * A criterion that narrows the track pool on top of the other scope
 * filters (playlist, search). This is what lets a browser reduce the
 * scope to the item currently selected in its own UI (album, artist,
 * year, ...) without having to invent a playlist for it.
 *
 * `eq` (the default) compares stringified values, `prefix` matches a
 * string prefix, and `gte` / `lt` compare numerically — the two range
 * operators together express things like a decade.
 *
 * @typedef {{
 *   field: string;
 *   value: string | number;
 *   op?: "eq" | "prefix" | "gte" | "lt";
 *   transformations?: string[];
 * }} SelectionCriterion
 */

class ScopeEngine extends BroadcastableDiffuseElement {
  static NAME = "diffuse/engine/scope";

  // SIGNALS

  #groupBy = signal(/** @type {string | undefined} */ (undefined));
  #playlist = signal(/** @type {string | undefined} */ (undefined));
  #searchTerm = signal(/** @type {string | undefined} */ (undefined));
  #selection = signal(
    /** @type {SelectionCriterion[] | undefined} */ (undefined),
  );
  #sortBy = signal(
    /** @type {string[]} */ ([
      "tags.artist",
      "tags.album",
      "tags.disc.no",
      "tags.track.no",
    ]),
  );
  #sortDirection = signal(/** @type {"asc" | "desc" | undefined} */ ("asc"));

  groupBy = this.#groupBy.get;
  playlist = this.#playlist.get;
  searchTerm = this.#searchTerm.get;
  selection = this.#selection.get;
  sortBy = this.#sortBy.get;
  sortDirection = this.#sortDirection.get;

  // LIFECYCLE

  /**
   * @override
   */
  connectedCallback() {
    // Broadcast if needed
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(this.identifier, {
        revertToDefaultSort: {
          strategy: "replicate",
          fn: this.revertToDefaultSort,
        },
        setGroupBy: { strategy: "replicate", fn: this.setGroupBy },
        setPlaylist: { strategy: "replicate", fn: this.setPlaylist },
        setSearchTerm: { strategy: "replicate", fn: this.setSearchTerm },
        setSelection: { strategy: "replicate", fn: this.setSelection },
        setSortBy: { strategy: "replicate", fn: this.setSortBy },
        setSortDirection: { strategy: "replicate", fn: this.setSortDirection },
      });

      if (actions) {
        this.revertToDefaultSort = actions.revertToDefaultSort;
        this.setGroupBy = actions.setGroupBy;
        this.setPlaylist = actions.setPlaylist;
        this.setSearchTerm = actions.setSearchTerm;
        this.setSelection = actions.setSelection;
        this.setSortBy = actions.setSortBy;
        this.setSortDirection = actions.setSortDirection;
      }
    }

    // Super
    super.connectedCallback();

    // Signals
    const storagePrefix =
      `${this.constructor.prototype.constructor.NAME}/${this.group}`;

    batch(() => {
      this.#groupBy.value = localStorage.getItem(`${storagePrefix}/groupBy`) ??
        undefined;
      this.#playlist.value =
        localStorage.getItem(`${storagePrefix}/playlistId`) ?? undefined;
      this.#searchTerm.value =
        localStorage.getItem(`${storagePrefix}/searchTerm`) ?? undefined;
      try {
        const rawSelection = localStorage.getItem(
          `${storagePrefix}/selection`,
        );
        this.#selection.value = rawSelection
          ? JSON.parse(rawSelection)
          : undefined;
      } catch {
        this.#selection.value = undefined;
      }
      this.#sortBy.value = JSON.parse(
        localStorage.getItem(`${storagePrefix}/sortBy`) ??
          `["tags.artist", "tags.album", "tags.disc.no", "tags.track.no"]`,
      );
      this.#sortDirection.value =
        /** @type {"desc" | "asc"} */ (localStorage.getItem(
          `${storagePrefix}/sortDirection`,
        ) ?? "asc");
    });

    // Effects
    this.effect(() => {
      const key = `${storagePrefix}/groupBy`;
      const val = this.#groupBy.value;

      if (val) localStorage.setItem(key, val);
      else localStorage.removeItem(key);
    });

    this.effect(() => {
      const key = `${storagePrefix}/playlistId`;
      const val = this.#playlist.value;

      if (val) localStorage.setItem(key, val);
      else localStorage.removeItem(key);
    });

    this.effect(() => {
      const key = `${storagePrefix}/searchTerm`;
      const val = this.#searchTerm.value;

      if (val) localStorage.setItem(key, val);
      else localStorage.removeItem(key);
    });

    this.effect(() => {
      const key = `${storagePrefix}/selection`;
      const val = this.#selection.value;

      if (val?.length) localStorage.setItem(key, JSON.stringify(val));
      else localStorage.removeItem(key);
    });

    this.effect(() => {
      const key = `${storagePrefix}/sortBy`;
      const val = this.#sortBy.value;

      if (val.length) localStorage.setItem(key, JSON.stringify(val));
      else localStorage.removeItem(key);
    });

    this.effect(() => {
      const key = `${storagePrefix}/sortDirection`;
      const val = this.#sortDirection.value;

      if (val) localStorage.setItem(key, val);
      else localStorage.removeItem(key);
    });
  }

  // ACTIONS

  revertToDefaultSort = async () => {
    this.#sortBy.value = [
      "tags.artist",
      "tags.album",
      "tags.disc.no",
      "tags.track.no",
    ];
    this.#sortDirection.value = "asc";
  };

  /** @param {string | undefined} val */
  setGroupBy = async (val) => this.#groupBy.value = val;

  /** @param {string | undefined} val */
  setPlaylist = async (val) => this.#playlist.value = val;

  /** @param {string | undefined} val */
  setSearchTerm = async (val) => this.#searchTerm.value = val;

  /** @param {SelectionCriterion[] | undefined} val */
  setSelection = async (val) => this.#selection.value = val;

  /** @param {string[]} val */
  setSortBy = async (val) => this.#sortBy.value = val;

  /** @param {"asc" | "desc" | undefined} val */
  setSortDirection = async (val) => this.#sortDirection.value = val;
}

export default ScopeEngine;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = ScopeEngine;
export const NAME = "de-scope";

defineElement(NAME, CLASS);
```
## Input
### Dropbox

Dropbox, using the Dropbox v2 HTTP API.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { DEFAULT_APP_KEY, PKCE_VERIFIER_KEY, SCHEME } from "./constants.js";
import { accountsFromTracks, buildURI, generatePKCEPair } from "./common.js";

/**
 * @import {InputActions, InputSchemeProvider} from "@specs/components/input/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<InputActions>}
 * @implements {InputSchemeProvider}
 */
class DropboxInput extends DiffuseElement {
  static NAME = "diffuse/input/dropbox";
  static WORKER_URL = "components/input/dropbox/worker.js";

  SCHEME = SCHEME;

  /** @type {string} */
  appKey = DEFAULT_APP_KEY;

  static observedAttributes = ["app-key"];

  /**
   * @override
   * @param {string} name
   * @param {string} old
   * @param {string} next
   */
  attributeChangedCallback(name, old, next) {
    super.attributeChangedCallback(name, old, next);
    if (name === "app-key" && next !== null) this.appKey = next;
  }

  constructor() {
    super();

    /** @type {ProxiedActions<InputActions>} */
    this.proxy = this.workerProxy();

    this.artwork = this.proxy.artwork;
    this.consult = this.proxy.consult;
    this.detach = this.proxy.detach;
    this.groupConsult = this.proxy.groupConsult;
    this.list = this.proxy.list;
    this.resolve = this.proxy.resolve;
  }

  // 🛠️

  async authorize() {
    localStorage.setItem("oauth/callback/redirect_path", location.pathname + location.search);

    // Use the authorization-code flow with PKCE so we receive a
    // long-lived refresh token that can automatically renew the
    // short-lived access token (4 h) without user interaction.
    const { verifier, challenge } = await generatePKCEPair();
    localStorage.setItem(PKCE_VERIFIER_KEY, verifier);

    const params = new URLSearchParams({
      response_type: "code",
      client_id: this.appKey,
      redirect_uri: location.origin + "/oauth/callback/",
      token_access_type: "offline",
      code_challenge: challenge,
      code_challenge_method: "S256",
    });

    location.assign(`https://www.dropbox.com/oauth2/authorize?${params}`);
  }

  /** @param {Track[]} tracks */
  sources(tracks) {
    return Object.values(accountsFromTracks(tracks)).map((account) => ({
      label: `Dropbox (${account.directoryPath})`,
      uri: buildURI(account),
    }));
  }
}

export default DropboxInput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = DropboxInput;
export const NAME = "di-dropbox";

defineElement(NAME, CLASS);
```
### Ephemeral Cache

Ephemeral blobs stored in indexedDB, resolving creates temporary Blob URLs. Not responsible for storing blobs.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { SCHEME } from "./constants.js";

/**
 * @import { InputActions, InputSchemeProvider } from "@specs/components/input/types.d.ts"
 * @import { ProxiedActions } from "~/common/worker.d.ts"
 * @import { Track } from "~/definitions/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<InputActions>}
 * @implements {InputSchemeProvider}
 */
class EphemeralCacheInput extends DiffuseElement {
  static NAME = "diffuse/input/ephemeral-cache";
  static WORKER_URL = "components/input/ephemeral-cache/worker.js";

  SCHEME = SCHEME;

  constructor() {
    super();

    /** @type {ProxiedActions<InputActions>} */
    const proxy = this.workerProxy();

    this.artwork = proxy.artwork;
    this.consult = proxy.consult;
    this.detach = proxy.detach;
    this.groupConsult = proxy.groupConsult;
    this.list = proxy.list;
    this.resolve = proxy.resolve;
  }

  // 🛠️

  /** @param {Track[]} tracks */
  sources(tracks) {
    return tracks.map((t) => ({
      label: t.uri,
      uri: t.uri,
    }));
  }
}

export default EphemeralCacheInput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = EphemeralCacheInput;
export const NAME = "di-ephemeral-cache";

defineElement(NAME, CLASS);
```
### Firkin

Firkin account files plus generic CID-addressed blobs. Generic blobs resolve anonymously via RASL by default; a read token in the URI opts into authenticated access.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import {
  parseBlobURI,
  parseURI,
  SCHEME,
  SOURCE_URI,
} from "~/common/firkin/files.js";

/**
 * @import {InputActions, InputSchemeProvider} from "@specs/components/input/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Audio source for Firkin account files and generic CID-addressed blobs.
 *
 * Account files are listed from the account's file registry and use the
 * shared Firkin session. Generic `firkin://<host>/blob/<cid>` tracks resolve
 * anonymously via RASL by default; a `?token=` query parameter opts into an
 * authenticated read.
 *
 * The worker reads the shared Firkin session from IndexedDB, so account mode
 * only needs the Connect / Firkin page to have been used once.
 *
 * @implements {ProxiedActions<InputActions>}
 * @implements {InputSchemeProvider}
 */
class FirkinInput extends DiffuseElement {
  static NAME = "diffuse/input/firkin";
  static WORKER_URL = "components/input/firkin/worker.js";

  SCHEME = SCHEME;

  constructor() {
    super();

    /** @type {ProxiedActions<InputActions>} */
    const proxy = this.workerProxy();

    this.artwork = proxy.artwork;
    this.consult = proxy.consult;
    this.detach = proxy.detach;
    this.groupConsult = proxy.groupConsult;
    this.list = proxy.list;
    this.resolve = proxy.resolve;
  }

  // 🛠️

  /** @param {Track[]} tracks */
  sources(tracks) {
    /** @type {Map<string, { label: string; uri: string }>} */
    const generic = new Map();
    let hasAccount = false;

    for (const track of tracks) {
      if (track.uri === SOURCE_URI || parseURI(track.uri)) {
        hasAccount = true;
        continue;
      }

      const blob = parseBlobURI(track.uri);
      if (!blob) continue;

      const uri = `firkin://${blob.host}`;
      if (!generic.has(uri)) {
        generic.set(uri, { label: `Firkin (${blob.host})`, uri });
      }
    }

    /** @type {{ label: string; uri: string }[]} */
    const sources = [...generic.values()];

    // The account source is only meaningful when this is the account library
    // (or there is nothing else to show). Generic CID sources stand alone.
    if (hasAccount || sources.length === 0) {
      sources.unshift({ label: "Firkin", uri: SOURCE_URI });
    }

    return sources;
  }
}

export default FirkinInput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = FirkinInput;
export const NAME = "di-firkin";

defineElement(NAME, CLASS);
```
### HTTPS

HTTPS URLs to audio files or streams.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { SCHEME } from "./constants.js";
import { hostsFromTracks } from "./common.js";

/**
 * @import {InputActions, InputSchemeProvider} from "@specs/components/input/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<InputActions>}
 * @implements {InputSchemeProvider}
 */
class HttpsInput extends DiffuseElement {
  static NAME = "diffuse/input/https";
  static WORKER_URL = "components/input/https/worker.js";

  SCHEME = SCHEME;

  constructor() {
    super();

    /** @type {ProxiedActions<InputActions>} */
    this.proxy = this.workerProxy();

    this.artwork = this.proxy.artwork;
    this.consult = this.proxy.consult;
    this.detach = this.proxy.detach;
    this.groupConsult = this.proxy.groupConsult;
    this.list = this.proxy.list;
    this.resolve = this.proxy.resolve;
  }

  // 🛠️

  /** @param {Track[]} tracks */
  sources(tracks) {
    const hosts = Object.values(hostsFromTracks(tracks));

    return hosts.map((host) => ({
      label: host,
      uri: `https://${host}`,
    }));
  }
}

export default HttpsInput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = HttpsInput;
export const NAME = "di-https";

defineElement(NAME, CLASS);
```
### HTTPS + JSON

HTTPS servers with JSON directory listings.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { SCHEME } from "./constants.js";
import { buildURI, serversFromTracks } from "./common.js";

/**
 * @import {InputActions, InputSchemeProvider} from "@specs/components/input/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<InputActions>}
 * @implements {InputSchemeProvider}
 */
class HttpsJsonInput extends DiffuseElement {
  static NAME = "diffuse/input/https-json";
  static WORKER_URL = "components/input/https-json/worker.js";

  SCHEME = SCHEME;

  constructor() {
    super();

    /** @type {ProxiedActions<InputActions>} */
    this.proxy = this.workerProxy();

    this.artwork = this.proxy.artwork;
    this.consult = this.proxy.consult;
    this.detach = this.proxy.detach;
    this.groupConsult = this.proxy.groupConsult;
    this.list = this.proxy.list;
    this.resolve = this.proxy.resolve;
  }

  // 🛠️

  /** @param {Track[]} tracks */
  sources(tracks) {
    return Object.values(serversFromTracks(tracks)).map((server) => ({
      label: `${server.host}${server.dir}`,
      uri: buildURI(server),
    }));
  }
}

export default HttpsJsonInput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = HttpsJsonInput;
export const NAME = "di-https-json";

defineElement(NAME, CLASS);
```
### Icecast

Icecast internet radio streams. Fetches ICY metadata to populate track information.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { hostsFromTracks } from "./common.js";
import { SCHEME } from "./constants.js";

/**
 * @import {InputActions, InputSchemeProvider} from "@specs/components/input/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<InputActions>}
 * @implements {InputSchemeProvider}
 */
class IcecastInput extends DiffuseElement {
  static NAME = "diffuse/input/icecast";
  static WORKER_URL = "components/input/icecast/worker.js";

  SCHEME = SCHEME;

  constructor() {
    super();

    /** @type {ProxiedActions<InputActions>} */
    this.proxy = this.workerProxy();

    this.artwork = this.proxy.artwork;
    this.consult = this.proxy.consult;
    this.detach = this.proxy.detach;
    this.groupConsult = this.proxy.groupConsult;
    this.list = this.proxy.list;
    this.resolve = this.proxy.resolve;
  }

  // 🛠️

  /** @param {Track[]} tracks */
  sources(tracks) {
    const hosts = Object.values(hostsFromTracks(tracks));

    return hosts.map((host) => ({
      label: host,
      uri: `${SCHEME}://${host}`,
    }));
  }
}

export default IcecastInput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = IcecastInput;
export const NAME = "di-icecast";

defineElement(NAME, CLASS);
```
### Local

Audio files or directories from your local device, using the browser's File System Access API.

```js
import * as TID from "@atcute/tid";
import { defineElement, DiffuseElement } from "~/common/element.js";
import { SCHEME } from "./constants.js";
import {
  buildURI,
  loadHandles,
  saveHandles,
  tidsFromTracks,
} from "./common.js";

/**
 * @import {InputActions, InputSchemeProvider} from "@specs/components/input/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<InputActions>}
 * @implements {InputSchemeProvider}
 */
class LocalInput extends DiffuseElement {
  static NAME = "diffuse/input/local";
  static WORKER_URL = "components/input/local/worker.js";

  SCHEME = SCHEME;

  /** @type {Map<string, string>} tid → handle name */
  #names = new Map();

  constructor() {
    super();

    /** @type {ProxiedActions<InputActions>} */
    this.proxy = this.workerProxy();

    this.artwork = this.proxy.artwork;
    this.consult = this.proxy.consult;
    this.detach = this.proxy.detach;
    this.groupConsult = this.proxy.groupConsult;
    this.list = this.proxy.list;
    this.resolve = this.proxy.resolve;
  }

  // LIFECYCLE

  /** @override */
  async connectedCallback() {
    super.connectedCallback();
    const handles = await loadHandles();
    for (const [tid, handle] of Object.entries(handles)) {
      this.#names.set(tid, handle.name);
    }
  }

  // 🛠️

  /**
   * Prompts the user to pick a directory.
   * Stores handle in IDB.
   * Returns the URI for the track placeholder.
   */
  async addDirectory() {
    const dirHandle = await /** @type {any} */ (globalThis).showDirectoryPicker(
      { mode: "read" },
    );

    const tid = TID.now();
    const handles = await loadHandles();

    handles[tid] = dirHandle;
    await saveHandles(handles);
    this.#names.set(tid, dirHandle.name);

    return buildURI(tid);
  }

  /**
   * Prompts the user to pick one or more files.
   * Stores handles in IDB.
   * Returns the URIs for the track placeholders.
   */
  async addFiles() {
    const fileHandles = await /** @type {any} */ (globalThis)
      .showOpenFilePicker({ multiple: true });
    const handles = await loadHandles();
    const uris = [];

    for (const fileHandle of fileHandles) {
      const tid = TID.now();
      handles[tid] = fileHandle;
      this.#names.set(tid, fileHandle.name);
      uris.push(buildURI(tid));
    }

    await saveHandles(handles);
    return uris;
  }

  /** @param {Track[]} tracks */
  sources(tracks) {
    return Object.values(tidsFromTracks(tracks)).map((tid) => ({
      label: this.#names.get(tid) ?? tid,
      uri: buildURI(tid),
    }));
  }
}

export default LocalInput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = LocalInput;
export const NAME = "di-local";

defineElement(NAME, CLASS);
```
### Opensubsonic

(Open)subsonic audio servers.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { SCHEME } from "./constants.js";
import { buildURI, serversFromTracks } from "./common.js";

/**
 * @import {InputActions, InputSchemeProvider} from "@specs/components/input/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<InputActions>}
 * @implements {InputSchemeProvider}
 */
class OpensubsonicInput extends DiffuseElement {
  static NAME = "diffuse/input/opensubsonic";
  static WORKER_URL = "components/input/opensubsonic/worker.js";

  SCHEME = SCHEME;

  constructor() {
    super();

    /** @type {ProxiedActions<InputActions>} */
    this.proxy = this.workerProxy();

    this.artwork = this.proxy.artwork;
    this.consult = this.proxy.consult;
    this.detach = this.proxy.detach;
    this.groupConsult = this.proxy.groupConsult;
    this.list = this.proxy.list;
    this.resolve = this.proxy.resolve;
  }

  // 🛠️

  /** @param {Track[]} tracks */
  sources(tracks) {
    return Object.values(serversFromTracks(tracks)).map((server) => {
      return {
        label: server.host,
        uri: buildURI(server),
      };
    });
  }
}

export default OpensubsonicInput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = OpensubsonicInput;
export const NAME = "di-opensubsonic";

defineElement(NAME, CLASS);
```
### S3

AWS S3 and services that provide the same surface API such as Cloudflare R2.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { SCHEME } from "./constants.js";
import { bucketsFromTracks, buildURI } from "./common.js";

/**
 * @import {InputActions, InputSchemeProvider} from "@specs/components/input/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 * @import {Demo} from "@specs/components/input/s3/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<InputActions>}
 * @implements {InputSchemeProvider}
 */
class S3Input extends DiffuseElement {
  static NAME = "diffuse/input/s3";
  static WORKER_URL = "components/input/s3/worker.js";

  SCHEME = SCHEME;

  constructor() {
    super();

    /** @type {ProxiedActions<InputActions & { demo: () => Demo }>} */
    this.proxy = this.workerProxy();

    this.artwork = this.proxy.artwork;
    this.consult = this.proxy.consult;
    this.detach = this.proxy.detach;
    this.groupConsult = this.proxy.groupConsult;
    this.list = this.proxy.list;
    this.resolve = this.proxy.resolve;

    this.demo = this.proxy.demo;
  }

  // 🛠️

  /** @param {Track[]} tracks */
  sources(tracks) {
    return Object.values(bucketsFromTracks(tracks)).map((server) => {
      return {
        label: `${server.bucketName} (${server.host})`,
        uri: buildURI(server),
      };
    });
  }
}

export default S3Input;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = S3Input;
export const NAME = "di-s3";

defineElement(NAME, CLASS);
```
### WebDAV

WebDAV servers. Depends on a service worker handling the `diffuse:basic-auth` query parameter and converting it to a `Authorization` header.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { SCHEME } from "./constants.js";
import { buildURI, serversFromTracks } from "./common.js";

/**
 * @import {InputActions, InputSchemeProvider} from "@specs/components/input/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<InputActions>}
 * @implements {InputSchemeProvider}
 */
class WebdavInput extends DiffuseElement {
  static NAME = "diffuse/input/webdav";
  static WORKER_URL = "components/input/webdav/worker.js";

  SCHEME = SCHEME;

  constructor() {
    super();

    /** @type {ProxiedActions<InputActions>} */
    this.proxy = this.workerProxy();

    this.artwork = this.proxy.artwork;
    this.consult = this.proxy.consult;
    this.detach = this.proxy.detach;
    this.groupConsult = this.proxy.groupConsult;
    this.list = this.proxy.list;
    this.resolve = this.proxy.resolve;
  }

  // 🛠️

  /** @param {Track[]} tracks */
  sources(tracks) {
    return Object.values(serversFromTracks(tracks)).map((server) => ({
      label: `${server.host}${server.dir}`,
      uri: buildURI(server),
    }));
  }
}

export default WebdavInput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = WebdavInput;
export const NAME = "di-webdav";

defineElement(NAME, CLASS);
```
## Metadata
### Audio File

Extracts tags and audio stats from audio files using the music-metadata library.

```js
import { defineElement, DiffuseElement, query } from "~/common/element.js";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {InputElement} from "@specs/components/input/types.d.ts"
 * @import {Actions} from "@specs/components/metadata/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<Actions>}
 */
class AudioFileMetadata extends DiffuseElement {
  static NAME = "diffuse/metadata/audio-file";
  static WORKER_URL = "components/metadata/audio-file/worker.js";

  constructor() {
    super();

    /** @type {ProxiedActions<Actions>} */
    const p = this.workerProxy();

    this.patch = p.patch;
  }

  // LIFECYCLE

  /** @override */
  async connectedCallback() {
    super.connectedCallback();

    /** @type {InputElement} */
    this.input = query(this, "input-selector");

    await customElements.whenDefined(this.input.localName);
  }

  // WORKERS

  /**
   * @override
   */
  dependencies() {
    if (!this.input) throw new Error("Input element not defined yet");
    return { input: this.input };
  }
}

export default AudioFileMetadata;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = AudioFileMetadata;
export const NAME = "dm-audio-file";

defineElement(NAME, AudioFileMetadata);
```
### Spectrogram

Decodes a track's audio, computes a spectrogram and stores the derived spectral descriptors (centroid, rolloff, spread, flatness, flux) on the track's stats.

```js
import { defineElement, DiffuseElement, query } from "~/common/element.js";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {InputElement} from "@specs/components/input/types.d.ts"
 * @import {Actions} from "@specs/components/metadata/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Computes a spectrogram for a track and stores the derived spectral
 * descriptors on the track's `stats`.
 *
 * Like the audio-file metadata element, it exposes a `patch(track)` action and
 * is designed to be a child of the `<dc-metadata>` configurator, where it runs
 * alongside `<dm-audio-file>` during track processing.
 *
 * @implements {ProxiedActions<Actions>}
 */
class SpectrogramMetadata extends DiffuseElement {
  static NAME = "diffuse/metadata/spectrogram";
  static WORKER_URL = "components/metadata/spectrogram/worker.js";

  constructor() {
    super();

    /** @type {ProxiedActions<Actions>} */
    const p = this.workerProxy();

    this.abort = p.abort;
    this.patch = p.patch;
  }

  // LIFECYCLE

  /** @override */
  async connectedCallback() {
    super.connectedCallback();

    /** @type {InputElement} */
    this.input = query(this, "input-selector");

    await customElements.whenDefined(this.input.localName);
  }

  // WORKERS

  /**
   * @override
   */
  dependencies() {
    if (!this.input) throw new Error("Input element not defined yet");
    return { input: this.input };
  }
}

export default SpectrogramMetadata;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = SpectrogramMetadata;
export const NAME = "dm-spectrogram";

defineElement(NAME, SpectrogramMetadata);
```
## Orchestrators
### Artwork

Fetches cover art for a given set of tracks, stored locally in indexedDB. Uses the artwork configurator to try each configured source in sequence.

```js
import { defineElement, DiffuseElement, query } from "~/common/element.js";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Actions} from "@specs/components/artwork/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

class ArtworkOrchestrator extends DiffuseElement {
  static NAME = "diffuse/orchestrator/artwork";
  static WORKER_URL = "components/orchestrator/artwork/worker.js";

  constructor() {
    super();

    /** @type {ProxiedActions<Actions>} */
    const p = this.workerProxy();

    this.get = p.get;
  }

  // LIFECYCLE

  /** @override */
  async connectedCallback() {
    super.connectedCallback();

    /** @type {import("~/components/configurator/artwork/element.js").CLASS} */
    this.artworkConfigurator = query(this, "artwork-selector");

    await customElements.whenDefined(this.artworkConfigurator.localName);
  }

  // WORKERS

  /**
   * @override
   */
  dependencies() {
    if (!this.artworkConfigurator) {
      throw new Error("Artwork configurator element not defined yet");
    }

    return {
      artwork: this.artworkConfigurator,
    };
  }
}

export default ArtworkOrchestrator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = ArtworkOrchestrator;
export const NAME = "do-artwork";

defineElement(NAME, ArtworkOrchestrator);
```
### Automatic Queue

Fill the queue automatically with non-manual items (shuffled or regular, based on repeat-shuffle engine).

```js
import { BroadcastableDiffuseElement, defineElement, query } from "~/common/element.js";

/**
 * @import {DiffuseElement} from "~/common/element.js";
 * @import {SignalReader} from "~/common/signal.d.ts";
 * @import {TrackPools} from "@specs/components/orchestrator/scoped-tracks/types.d.ts"
 * @import RepeatShuffleEngine from "~/components/engine/repeat-shuffle/element.js"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Update the queue pool whenever tracks have been loaded,
 * or the tracks collection changes.
 */
class AutoTracksOrchestrator extends BroadcastableDiffuseElement {
  static NAME = "diffuse/orchestrator/auto-queue";

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    // Broadcast if needed
    if (this.hasAttribute("group")) {
      this.broadcast(this.identifier, {});
    }

    // Super
    super.connectedCallback();

    /** @type {import("~/components/engine/queue/element.js").CLASS} */
    const queue = query(this, "queue-engine-selector");

    /** @type {RepeatShuffleEngine} */
    const repeatShuffle = query(this, "repeat-shuffle-engine-selector");

    /** @type {DiffuseElement & { tracks: SignalReader<TrackPools> }} */
    const tracksElement = query(this, "tracks-selector");

    // When defined
    await customElements.whenDefined(queue.localName);
    await customElements.whenDefined(repeatShuffle.localName);
    await customElements.whenDefined(tracksElement.localName);

    // Watch tracks
    this.effect(() => {
      const tracks = tracksElement.tracks().scoped;

      this.isLeader().then(async (isLeader) => {
        if (!isLeader) return;
        queue.supply({ trackIds: tracks.map((t) => t.id) });
      });
    });

    // Automatically fill queue
    let lastShuffle = repeatShuffle.shuffle();
    let lastFingerprint = queue.supplyFingerprint();

    this.effect(() => {
      const trigger = queue.now();
      const fingerprint = queue.supplyFingerprint();
      const shuffled = repeatShuffle.shuffle();

      this.isLeader().then((isLeader) => {
        if (!isLeader) return;

        // Clear non-manual items from the queue
        // when 'shuffle' gets turned off or on;
        // or when queue supply changes.
        if (shuffled !== lastShuffle || fingerprint !== lastFingerprint) {
          lastShuffle = shuffled;
          lastFingerprint = fingerprint;
          queue.clear({ keepManual: true });
        }

        queue.fill({ amount: 10, shuffled: repeatShuffle.shuffle() });

        // Insert now-playing track if there's none
        if (!trigger) queue.shift();
      });
    });
  }
}

export default AutoTracksOrchestrator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = AutoTracksOrchestrator;
export const NAME = "do-auto-queue";

defineElement(NAME, CLASS);
```
### Controller

Provides commonly used computed signals derived from the audio engine, queue engine, and output. Exposes currentTrack(), isPlaying(), and references to the underlying engines.

```js
import { defineElement, DiffuseElement, query, whenElementsDefined } from "~/common/element.js";
import { computed, signal } from "~/common/signal.js";

/**
 * @import {OutputElement} from "@specs/components/output/types.d.ts"
 * @import AudioEngine from "~/components/engine/audio/element.js"
 * @import QueueEngine from "~/components/engine/queue/element.js"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Provides commonly used computed signals derived from the audio engine,
 * queue engine, and output — so theme elements don't need to re-implement them.
 */
class ControllerOrchestrator extends DiffuseElement {
  static NAME = "diffuse/orchestrator/controller";

  // SIGNALS - DEPENDENCIES

  $audio = signal(/** @type {AudioEngine | undefined} */ (undefined));
  $output = signal(/** @type {OutputElement | undefined} */ (undefined));
  $queue = signal(/** @type {QueueEngine | undefined} */ (undefined));

  // SIGNALS - COMPUTED

  audio = computed(() => {
    const curr = this.$queue.value?.now();
    return curr ? this.$audio.value?.state(curr.id) : undefined;
  });

  currentTrack = computed(() => {
    const item = this.$queue.value?.now();
    if (!item) return undefined;
    const col = this.$output.value?.tracks.collection();
    if (!col || col.state !== "loaded") return undefined;
    return col.data.find((t) => t.id === item.id);
  });

  isPlaying = computed(() => {
    return this.$audio.value?.isPlaying();
  });

  // LIFECYCLE

  /**
   * @override
   */
  connectedCallback() {
    super.connectedCallback();

    /** @type {AudioEngine} */
    const audio = query(this, "audio-engine-selector");

    /** @type {OutputElement} */
    const output = query(this, "output-selector");

    /** @type {QueueEngine} */
    const queue = query(this, "queue-engine-selector");

    whenElementsDefined({ audio, output, queue }).then(() => {
      this.$audio.value = audio;
      this.$output.value = output;
      this.$queue.value = queue;
    });
  }
}

export default ControllerOrchestrator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = ControllerOrchestrator;
export const NAME = "do-controller";

defineElement(NAME, CLASS);
```
### Cooperative Playlists

Exposes the cohesive view of playlists shared with collaborators. Reads collaboration records from the given output, resolves collaborators through registered collaboration sources, and provides merged `playlistItems` and `playlists` signals. An AT Protocol source is included. Collaborator items are never written back, so each account only edits its own items.

```js
import {
  BroadcastableDiffuseElement,
  defineElement,
  query,
} from "~/common/element.js";
import { computed, signal } from "~/common/signal.js";
import * as Collaboration from "~/common/collaboration/index.js";
import * as Playlist from "~/common/playlist.js";

/**
 * @import {Collaboration as CollaborationRecord, PlaylistItem} from "~/definitions/types.d.ts"
 * @import {OutputElement} from "@specs/components/output/types.d.ts"
 * @import {CollaborationConfiguratorElement} from "@specs/components/configurator/collaboration/types.d.ts"
 * @import {RemotePlaylistGroup} from "~/common/collaboration/index.js"
 */

/**
 * Builds the cohesive view of playlists shared with collaborators.
 *
 * Unlike a transformer, this orchestrator does not alter the output's
 * `playlistItems` collection. It reads the local collaboration records from the
 * given output, fetches each collaborator's playlist items over AT Protocol,
 * and exposes a merged collection that a facet can render. Items contributed by
 * collaborators are scoped by their owner's DID and filtered out when saving.
 *
 * Collaborator items are fetched by the broadcasted leader only; other tabs
 * receive the merged state through the broadcast channel.
 *
 * The orchestrator is protocol-agnostic: it resolves a collaborator's `hint`
 * through a collaboration configurator (`dc-collaboration`). Append source
 * elements to that configurator — for example `dcs-atproto` — and point the
 * orchestrator at it with `collaboration-configurator-selector`.
 *
 * @extends {BroadcastableDiffuseElement}
 */
class CooperativePlaylistsOrchestrator extends BroadcastableDiffuseElement {
  static NAME = "diffuse/orchestrator/cooperative-playlists";

  static observedAttributes = ["depth"];

  /** @type {import("~/common/signal.d.ts").Signal<OutputElement | null>} */
  #output = signal(/** @type {OutputElement | null} */ (null));

  /** @type {import("~/common/signal.d.ts").Signal<CollaborationConfiguratorElement | null>} */
  #configurator = signal(
    /** @type {CollaborationConfiguratorElement | null} */ (null),
  );

  /** @type {import("~/common/signal.d.ts").Signal<RemotePlaylistGroup[]>} */
  #remote = signal(/** @type {RemotePlaylistGroup[]} */ ([]));

  /** @type {import("~/common/signal.d.ts").Signal<number>} */
  #depth = signal(1);

  /** @type {Map<string, Promise<RemotePlaylistGroup | null>>} */
  #cache = new Map();

  #generation = 0;

  /** @type {CollaborationRecord[] | undefined} */
  #lastCollaborations;

  // STATE

  /**
   * The local collaboration records.
   */
  collaborations = computed(() => {
    const output = this.#output.value;
    if (!output) return [];

    const col = output.collaborations.collection();
    return col.state === "loaded" ? col.data : [];
  });

  /**
   * Local playlist items merged with the items contributed by collaborators.
   */
  playlistItems = computed(() => {
    const output = this.#output.value;
    if (!output) return [];

    const col = output.playlistItems.collection();
    if (col.state !== "loaded") return [];

    return Collaboration.mergeItems(col.data, this.#remote.value);
  });

  /**
   * The merged playlist items grouped by playlist name, with ordered/unordered
   * state, sorted alphabetically.
   */
  playlists = computed(() => {
    return [...Playlist.gather(this.playlistItems()).values()]
      .sort((a, b) => a.name.localeCompare(b.name));
  });

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(this.identifier, {
        getRemoteGroups: {
          strategy: "leaderOnly",
          fn: this.#remote.get,
        },
        setRemoteGroups: {
          strategy: "replicate",
          fn: this.#remote.set,
        },
        refresh: {
          strategy: "leaderOnly",
          fn: this.refresh,
        },
      });

      if (actions) {
        this.#remote.set = actions.setRemoteGroups;
        this.refresh = actions.refresh;

        actions.getRemoteGroups().then((groups) => {
          this.#remote.value = groups;
        });
      }
    }

    super.connectedCallback();

    /** @type {OutputElement} */
    const output = query(this, "output-selector");

    /** @type {CollaborationConfiguratorElement} */
    const configurator = query(
      this,
      "collaboration-configurator-selector",
    );

    await Promise.all([
      customElements.whenDefined(output.localName),
      customElements.whenDefined(configurator.localName),
    ]);

    this.#output.value = output;
    this.#configurator.value = configurator;

    // Fetch collaborator items whenever the collaboration records change.
    this.effect(async () => {
      const configurator = this.#configurator.value;
      if (!configurator) return;

      const col = output.collaborations.collection();
      if (col.state !== "loaded") return;

      const depth = this.#depth.get();

      if ((await this.isLeader()) === false) return;

      if (col.data !== this.#lastCollaborations) {
        this.#lastCollaborations = col.data;
        this.#cache.clear();
      }

      return this.#load(configurator, col.data, depth);
    });
  }

  /**
   * @override
   * @param {string} name
   * @param {string} oldValue
   * @param {string} newValue
   */
  attributeChangedCallback(name, oldValue, newValue) {
    super.attributeChangedCallback(name, oldValue, newValue);

    if (name === "depth") this.#depth.set(parseDepth(newValue));
  }

  // ACTIONS

  /**
   * Re-fetch every collaborator's items, bypassing the cache.
   */
  refresh = async () => {
    const output = this.#output.value;
    const configurator = this.#configurator.value;
    if (!output || !configurator) return;

    await output.collaborations.reload();

    const col = output.collaborations.collection();
    if (col.state !== "loaded") return;

    this.#lastCollaborations = col.data;
    this.#cache.clear();
    await this.#load(configurator, col.data, this.#depth.get());
  };

  /**
   * Save local playlist items. Collaborator items are never written back to the
   * output.
   *
   * @param {PlaylistItem[]} items
   */
  save = async (items) => {
    const output = this.#output.value;
    if (!output) return;

    await output.playlistItems.save(
      items.filter((item) => !Collaboration.isRemoteItem(item)),
    );
  };

  // FETCHING

  /**
   * @param {CollaborationConfiguratorElement} configurator
   * @param {CollaborationRecord[]} collaborations
   * @param {number} depth
   */
  async #load(configurator, collaborations, depth) {
    const generation = ++this.#generation;

    /** @param {import("~/definitions/types.d.ts").Collaborator} collaborator */
    const isSupported = (collaborator) =>
      configurator.sourceFor(collaborator.hint) !== undefined;

    const graph = await Collaboration.expandCollaborators(collaborations, {
      depth,
      load: (collaborator) => {
        const source = configurator.sourceFor(collaborator.hint);
        return source
          ? source.loadCollaborations(collaborator.id)
          : Promise.resolve([]);
      },
      isSupported,
    });

    /** @type {Promise<RemotePlaylistGroup | null>[]} */
    const tasks = [];

    for (const [playlist, collaborators] of graph) {
      for (const collaborator of collaborators) {
        if (!isSupported(collaborator)) continue;
        tasks.push(this.#loadGroup(configurator, playlist, collaborator));
      }
    }

    const groups = (await Promise.all(tasks)).filter(
      (group) => group !== null,
    );

    if (generation !== this.#generation) return;
    this.#remote.value = groups;
  }

  /**
   * @param {CollaborationConfiguratorElement} configurator
   * @param {string} playlist
   * @param {import("~/definitions/types.d.ts").Collaborator} collaborator
   * @returns {Promise<RemotePlaylistGroup | null>}
   */
  #loadGroup(configurator, playlist, collaborator) {
    const source = configurator.sourceFor(collaborator.hint);
    if (!source) return Promise.resolve(null);

    const key = `${playlist}\0${collaborator.id}`;
    const cached = this.#cache.get(key);
    if (cached) return cached;

    const promise = source.loadPlaylistItems(collaborator.id, playlist)
      .then(({ owner, items }) => ({
        playlist,
        owner,
        label: collaborator.id,
        items,
      }))
      .catch((err) => {
        console.warn(
          `Could not load playlist "${playlist}" from ${collaborator.id}:`,
          err,
        );
        return null;
      });

    this.#cache.set(key, promise);
    return promise;
  }
}

/**
 * @param {string | null | undefined} value
 * @returns {number}
 */
function parseDepth(value) {
  const parsed = Number.parseInt(value ?? "", 10);
  if (Number.isNaN(parsed) || parsed < 1) return 1;
  return Math.min(parsed, 5);
}

export default CooperativePlaylistsOrchestrator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = CooperativePlaylistsOrchestrator;
export const NAME = "do-cooperative-playlists";

defineElement(NAME, CLASS);
```
### Cover Groups

Groups tracks by cover art to form collections.

```js
import { defineElement, DiffuseElement, query } from "~/common/element.js";
import { computed, signal } from "~/common/signal.js";

/**
 * @import {SignalReader} from "~/common/signal.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 * @import {TrackPools} from "@specs/components/orchestrator/scoped-tracks/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

class CoverGroupsOrchestrator extends DiffuseElement {
  static NAME = "diffuse/orchestrator/cover-groups";

  // SIGNALS

  #provider = signal(
    /** @type {DiffuseElement & { tracks: SignalReader<TrackPools> } | null} */ (null),
  );

  // STATE

  artistGroups = computed(() => {
    const provider = this.#provider.value;
    return buildArtistGroups(groupsOf(provider), scopedTracksOf(provider));
  });

  coverGroups = computed(() => {
    const provider = this.#provider.value;
    return buildCoverGroups(groupsOf(provider), scopedTracksOf(provider));
  });

  /**
   * Artist groups from the full pool — the catalog a browser shows while
   * its track pool is narrowed by sort / playlist / selection / search.
   */
  catalogArtistGroups = computed(() => {
    const provider = this.#provider.value;
    // Catalogs are ungrouped: the full pool has no scope group-by.
    return buildArtistGroups(undefined, availableTracksOf(provider));
  });

  /**
   * Album groups from the full pool.
   */
  catalogCoverGroups = computed(() => {
    const provider = this.#provider.value;
    return buildCoverGroups(undefined, availableTracksOf(provider));
  });

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    super.connectedCallback();

    /** @type {DiffuseElement & { tracks: SignalReader<TrackPools> }} */
    const provider = query(this, "tracks-selector");

    await customElements.whenDefined(provider.localName);
    this.#provider.value = provider;
  }
}

export default CoverGroupsOrchestrator;

////////////////////////////////////////////
// HELPERS
////////////////////////////////////////////

/**
 * The scoped provider's groups (narrowed by playlist / selection / search).
 *
 * @param {any} provider
 * @returns {{ label: string; tracks: Track[] }[] | undefined}
 */
function groupsOf(provider) {
  return provider?.groups?.();
}

/**
 * @param {any} provider
 * @returns {Track[]}
 */
function scopedTracksOf(provider) {
  return provider?.tracks?.()?.scoped ?? [];
}

/**
 * @param {any} provider
 * @returns {Track[]}
 */
function availableTracksOf(provider) {
  return provider?.tracks?.()?.available ?? [];
}

/**
 * @param {{ label: string; tracks: Track[] }[] | undefined} groups
 * @param {Track[]} allTracks
 * @returns {{ label: string; groups: ArtistGroup[] }[]}
 */
function buildArtistGroups(groups, allTracks) {
  /** @type {{ label: string; groups: ArtistGroup[] }[]} */
  const result = [];

  if (groups?.length) {
    // Total track counts per artist across all groups
    /** @type {Map<string, number>} */
    const totalCounts = new Map();
    for (const track of allTracks) {
      const key = String(track.tags?.artist ?? "").toLowerCase();
      totalCounts.set(key, (totalCounts.get(key) ?? 0) + 1);
    }

    for (const group of groups) {
      const artists = deduplicateArtists(group.tracks).map((a) => ({
        ...a,
        trackCount: totalCounts.get(a.artistKey) ?? a.trackCount,
      }));
      if (artists.length) result.push({ label: group.label, groups: artists });
    }
  } else {
    const artists = deduplicateArtists(allTracks);
    if (artists.length) result.push({ label: "", groups: artists });
  }

  return result;
}

/**
 * @param {{ label: string; tracks: Track[] }[] | undefined} groups
 * @param {Track[]} tracks
 * @returns {{ label: string; groups: CoverGroup[] }[]}
 */
function buildCoverGroups(groups, tracks) {
  /** @type {{ label: string; groups: CoverGroup[] }[]} */
  const result = [];

  if (groups?.length) {
    for (const group of groups) {
      const albums = deduplicateAlbums(group.tracks);
      if (albums.length) result.push({ label: group.label, groups: albums });
    }
  } else {
    const albums = deduplicateAlbums(tracks);
    if (albums.length) result.push({ label: "", groups: albums });
  }

  return result;
}

/**
 * @typedef {{ albumKey: string; albumName: string; artist: string; track: Track }} CoverGroup
 */

/**
 * @typedef {{ artistKey: string; artistName: string; trackCount: number; track: Track }} ArtistGroup
 */

/**
 * Most common casing variant of a group's name — tracks often disagree
 * on letter case ("Boys Noize" vs "boys noize"), and the label should
 * reflect what most of the library uses. Ties keep the first-seen
 * variant. Cheap by construction: the variant maps hold one entry in
 * the common case, so this is O(variants) after an O(1)-per-track count.
 * @param {Map<string, number>} variants raw name → track count
 * @returns {string}
 */
function mostCommonVariant(variants) {
  let best = "";
  let count = 0;

  for (const [name, n] of variants) {
    if (n > count) {
      count = n;
      best = name;
    }
  }

  return best;
}

/**
 * @param {Track[]} tracks
 * @returns {CoverGroup[]}
 */
function deduplicateAlbums(tracks) {
  /** @type {Map<string, { track: Track; artistVariants: Map<string, Map<string, number>>; nameVariants: Map<string, number> }>} */
  const albumMap = new Map();

  for (const track of tracks) {
    const albumKey = String(track.tags?.album ?? "").toLowerCase();
    const albumName = track.tags?.album ?? "Unknown album";
    const artist = track.tags?.artist ?? "Unknown artist";

    const entry = albumMap.get(albumKey) ?? {
      track,
      artistVariants: new Map(),
      nameVariants: new Map(),
    };
    albumMap.set(albumKey, entry);

    // Track per-artist casing variants, keyed case-insensitively so
    // "Boys Noize" / "boys noize" count as ONE artist (not "Various")
    const artistKey = artist.toLowerCase();
    const variants = entry.artistVariants.get(artistKey) ?? new Map();
    variants.set(artist, (variants.get(artist) ?? 0) + 1);
    entry.artistVariants.set(artistKey, variants);

    entry.nameVariants.set(
      albumName,
      (entry.nameVariants.get(albumName) ?? 0) + 1,
    );
  }

  return [...albumMap.entries()]
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([albumKey, { track, artistVariants, nameVariants }]) => ({
      albumKey,
      albumName: mostCommonVariant(nameVariants),
      artist: artistVariants.size > 1
        ? "Various Artists"
        : mostCommonVariant(
          /** @type {Map<string, number>} */
          (artistVariants.values().next().value),
        ),
      track,
    }));
}

/**
 * @param {Track[]} tracks
 * @returns {ArtistGroup[]}
 */
function deduplicateArtists(tracks) {
  /** @type {Map<string, { nameVariants: Map<string, number>; count: number; track: Track }>} */
  const map = new Map();

  for (const track of tracks) {
    const artistKey = String(track.tags?.artist ?? "").toLowerCase();
    const name = track.tags?.artist ?? "Unknown artist";

    const existing = map.get(artistKey);
    if (existing) {
      existing.count++;
      existing.nameVariants.set(
        name,
        (existing.nameVariants.get(name) ?? 0) + 1,
      );
    } else {
      map.set(artistKey, {
        nameVariants: new Map([[name, 1]]),
        count: 1,
        track,
      });
    }
  }

  return [...map.entries()]
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([artistKey, { nameVariants, count, track }]) => ({
      artistKey,
      artistName: mostCommonVariant(nameVariants),
      trackCount: count,
      track,
    }));
}

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = CoverGroupsOrchestrator;
export const NAME = "do-cover-groups";

defineElement(NAME, CLASS);
```
### Favourites

Mark tracks as favourites. Automatically creates an unordered 'Favourites' playlist.

```js
import {
  BroadcastableDiffuseElement,
  defineElement,
  query,
} from "~/common/element.js";
import { match as matchPlaylistItem } from "~/common/playlist.js";
import { computed, signal } from "~/common/signal.js";
import { filterFavourites } from "./common.js";
import * as Output from "~/common/output.js";

/**
 * @import {Track} from "~/definitions/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {OutputElement} from "@specs/components/output/types.d.ts"
 * @import {Actions} from "@specs/components/orchestrator/favourites/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

class FavouritesOrchestrator extends BroadcastableDiffuseElement {
  static NAME = "diffuse/orchestrator/favourites";
  static WORKER_URL = "components/orchestrator/favourites/worker.js";

  /** @type {ProxiedActions<Actions>} */
  #proxy;

  #toggleInFlight = false;

  constructor() {
    super();

    this.#proxy = this.workerProxy();

    // Bind methods for broadcasting
    this.include = this.include.bind(this);
    this.expel = this.expel.bind(this);
    this.toggle = this.toggle.bind(this);
  }

  // SIGNALS

  #output = signal(/** @type {OutputElement | null} */ (null));

  // STATE

  /**
   * Returns the favourites playlist items.
   */
  playlistItems = computed(() => {
    const output = this.#output.value;
    if (!output) return [];

    const col = output.playlistItems.collection();
    if (col.state !== "loaded") return [];
    return filterFavourites(col.data);
  });

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    // Broadcast if needed
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(this.identifier, {
        include: { strategy: "leaderOnly", fn: this.include },
        expel: { strategy: "leaderOnly", fn: this.expel },
        toggle: { strategy: "leaderOnly", fn: this.toggle },
      });

      if (actions) {
        this.include = actions.include;
        this.expel = actions.expel;
        this.toggle = actions.toggle;
      }
    }

    // Super
    super.connectedCallback();

    /** @type {OutputElement} */
    const output = query(this, "output-selector");

    // Wait until defined
    await customElements.whenDefined(output.localName);

    this.#output.value = output;
  }

  // ACTIONS

  /**
   * Add one or more tracks to favourites.
   * @param {Track | Track[]} tracks
   */
  async include(tracks) {
    const tracksArray = Array.isArray(tracks) ? tracks : [tracks];
    if (tracksArray.length === 0) return;

    const output = this.#output.value;
    if (!output) {
      console.warn("Favourites orchestrator: output element not ready");
      return;
    }

    const playlistItems = await Output.data(output.playlistItems);
    const result = await this.#proxy.include({
      playlistItems,
      tracks: tracksArray,
    });

    if (result) await output.playlistItems.save(result);
  }

  /**
   * Remove one or more tracks from favourites.
   * @param {Track | Track[]} tracks
   */
  async expel(tracks) {
    const tracksArray = Array.isArray(tracks) ? tracks : [tracks];
    if (tracksArray.length === 0) return;

    const output = this.#output.value;
    if (!output) {
      console.warn("Favourites orchestrator: output element not ready");
      return;
    }

    const playlistItems = await Output.data(output.playlistItems);
    const result = await this.#proxy.expel({
      playlistItems,
      tracks: tracksArray,
    });

    if (result) await output.playlistItems.save(result);
  }

  /**
   * Toggle favourite status for one or more tracks.
   * Adds tracks if not in favourites, removes if already favourited.
   * @param {Track | Track[]} tracks
   */
  async toggle(tracks) {
    if (this.#toggleInFlight) return;
    this.#toggleInFlight = true;

    try {
      const tracksArray = Array.isArray(tracks) ? tracks : [tracks];
      if (tracksArray.length === 0) return;

      const output = this.#output.value;
      if (!output) {
        console.warn("Favourites orchestrator: output element not ready");
        return;
      }

      const playlistItems = await Output.data(output.playlistItems);
      const result = await this.#proxy.toggle({
        playlistItems,
        tracks: tracksArray,
      });

      if (result) await output.playlistItems.save(result);
    } finally {
      this.#toggleInFlight = false;
    }
  }

  // 🛠️

  /**
   * Check if a track is a favourite.
   *
   * @param {Track} track
   */
  isFavourite(track) {
    return this.playlistItems().some((item) => {
      return matchPlaylistItem(track, item);
    });
  }
}

export default FavouritesOrchestrator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = FavouritesOrchestrator;
export const NAME = "do-favourites";

defineElement(NAME, CLASS);
```
### Media Session

Keeps the browser/os media session in sync with queue and audio state. Adds handlers for previous, next, seek to, etc.

```js
import {
  BroadcastableDiffuseElement,
  defineElement,
  query,
  queryOptional,
} from "~/common/element.js";

/**
 * @import {OutputElement} from "@specs/components/output/types.d.ts"
 * @import ArtworkOrchestrator from "~/components/orchestrator/artwork/element.js"
 * @import {default as AudioEngine} from "~/components/engine/audio/element.js"
 * @import {default as QueueEngine} from "~/components/engine/queue/element.js"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Keeps the browser/OS Media Session in sync with queue and audio engine state.
 *
 * Forwards play, pause, seek and track-skip actions from the OS back to the engines.
 */
class MediaSessionOrchestrator extends BroadcastableDiffuseElement {
  static NAME = "diffuse/orchestrator/media-session";

  // SIGNALS

  /** @type {string | null} */
  #artworkUrl = null;

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    if (this.hasAttribute("group")) {
      this.broadcast(this.identifier, {});
    }

    super.connectedCallback();

    if (!("mediaSession" in navigator)) return;

    /** @type {AudioEngine} */
    this.audio = query(this, "audio-engine-selector");
    /** @type {QueueEngine} */
    this.queue = query(this, "queue-engine-selector");
    /** @type {OutputElement | null} */
    this.output = queryOptional(this, "output-selector");
    /** @type {ArtworkOrchestrator | null} */
    this.artwork = queryOptional(this, "artwork-selector");

    await Promise.all([
      customElements.whenDefined(this.audio.localName),
      customElements.whenDefined(this.queue.localName),
      this.output && customElements.whenDefined(this.output.localName),
      this.artwork && customElements.whenDefined(this.artwork.localName),
    ].filter(Boolean));

    this.#registerActionHandlers();

    this.effect(() => this.#syncMetadata());
    this.effect(() => this.#syncPlaybackState());
    this.effect(() => this.#syncPositionState());
  }

  // 🛠️

  async #syncMetadata() {
    if (!this.queue) return;

    const now = this.queue.now();
    const tracksCol = this.output?.tracks.collection();
    const track = now && tracksCol?.state === "loaded"
      ? tracksCol.data.find((t) => t.id === now.id)
      : undefined;

    if (!track) {
      if (this.#artworkUrl) {
        URL.revokeObjectURL(this.#artworkUrl);
        this.#artworkUrl = null;
      }
      navigator.mediaSession.metadata = null;
      return;
    }

    const tags = track.tags ?? {};

    navigator.mediaSession.metadata = new MediaMetadata({
      title: tags.title ?? "",
      artist: tags.artist ?? tags.albumartist ?? "",
      album: tags.album ?? "",
      artwork: [],
    });

    // Optionally fetch and attach artwork
    if (this.artwork) {
      const artworkOrchestrator = this.artwork;

      /** @type {Uint8Array | null} */
      let bytes = null;

      try {
        bytes = await artworkOrchestrator.get(track);
      } catch {
        bytes = null;
      }

      if (bytes && navigator.mediaSession.metadata) {
        const mime = detectMime(bytes);
        const blob = new Blob([/** @type {ArrayBuffer} */ (bytes.buffer)], {
          type: mime,
        });

        const url = URL.createObjectURL(blob);
        const nowLater = this.queue.now();

        // If in the meantime the now-playing track has changed,
        // don't set the artwork.
        if (nowLater?.id !== now?.id) {
          URL.revokeObjectURL(url);
          return;
        }

        if (this.#artworkUrl) URL.revokeObjectURL(this.#artworkUrl);
        this.#artworkUrl = url;

        navigator.mediaSession.metadata = new MediaMetadata({
          title: tags.title ?? "",
          artist: tags.artist ?? tags.albumartist ?? "",
          album: tags.album ?? "",
          artwork: [{ src: url, type: mime }],
        });
      }
    }
  }

  #syncPlaybackState() {
    if (!this.audio || !this.queue) return;

    // Reflect the real state: "none" when nothing is loaded, so the OS media
    // controls don't linger with stale "paused" UI. Firefox keeps the media
    // session surface alive as long as playbackState is "playing"/"paused",
    // and its `setPositionState` throws while the state is "none" — so
    // keeping this in sync matters on Firefox in particular.
    const playing = this.audio.isPlaying();

    navigator.mediaSession.playbackState = this.queue.now()
      ? playing ? "playing" : "paused"
      : "none";
  }

  #syncPositionState() {
    if (!this.audio || !this.queue) return;

    const now = this.queue.now();
    if (!now) return;

    const state = this.audio.state(now.id);
    if (!state) return;

    const duration = state.duration();
    const progress = state.progress();

    if (!duration || isNaN(duration) || duration === 0) return;
    if (typeof navigator.mediaSession.setPositionState !== "function") return;

    // Don't gate on navigator.mediaSession.playbackState here: that read is
    // set by a separate effect (#syncPlaybackState) from browser state, so it
    // can still be "none" on the first run after a track loads — and on
    // Firefox the position would then never be (re)declared because this
    // effect doesn't re-run when playbackState flips. Firefox throws from
    // setPositionState while the session is "none", which the catch below
    // absorbs, so we only need to gate on whether there is actually a
    // playable current track (checked above via `now`/`state`/`duration`).
    try {
      navigator.mediaSession.setPositionState({
        duration,
        position: Math.min(duration * progress, duration),
        playbackRate: 1,
      });
    } catch {
      // setPositionState may throw (e.g. on Firefox) when the position is
      // not finite or the browser doesn't consider the session playable yet.
    }
  }

  #registerActionHandlers() {
    // Register each handler defensively: `setActionHandler` throws for
    // actions a browser doesn't support (Firefox is stricter than Chrome), so
    // an unsupported action must never abort registration of the rest. An
    // exception here would also escape `connectedCallback` and prevent the
    // metadata / playback-state / position-state effects below from running,
    // leaving the media session completely inert.
    /** @type {Array<[MediaSessionAction, MediaSessionActionHandler]>} */
    const handlers = [
      ["play", () => {
        if (!this.audio || !this.queue) return;
        const now = this.queue.now();
        if (now) this.audio.play({ audioId: now.id });
      }],
      ["pause", () => {
        if (!this.audio || !this.queue) return;
        const now = this.queue.now();
        if (now) this.audio.pause({ audioId: now.id });
      }],
      ["previoustrack", () => {
        if (!this.queue) return;
        this.queue.unshift();
      }],
      ["nexttrack", () => {
        if (!this.queue) return;
        this.queue.shift();
      }],
      ["seekto", (details) => {
        if (!this.audio || !this.queue) return;
        const now = this.queue.now();
        if (!now || details.seekTime == null) return;
        const state = this.audio.state(now.id);
        const duration = state?.duration();
        if (!duration || duration === 0) return;
        this.audio.seek({
          audioId: now.id,
          percentage: details.seekTime / duration,
        });
      }],
    ];

    // NOTE: These handlers deliberately do NOT gate on a local "leader" flag.
    // The underlying engines already resolve cross-tab leadership — `play`/
    // `pause`/`seek` are broadcast "leaderOnly" from the audio engine, and
    // `shift`/`unshift` operate on the queue's shared worker state. Gating the
    // media-session actions here would make every handler a silent no-op in a
    // non-leading tab while metadata still updates (both effects run), which
    // looks exactly like "controls show but do nothing" on Firefox.
    for (const [action, handler] of handlers) {
      try {
        navigator.mediaSession.setActionHandler(action, handler);
      } catch {
        // Action not supported on this browser/platform — skip it.
      }
    }
  }
}

export default MediaSessionOrchestrator;

////////////////////////////////////////////
// 🛠️
////////////////////////////////////////////

/**
 * @param {Uint8Array} bytes
 * @returns {string}
 */
function detectMime(bytes) {
  if (bytes[0] === 0xFF && bytes[1] === 0xD8) return "image/jpeg";
  if (bytes[0] === 0x89 && bytes[1] === 0x50) return "image/png";
  if (bytes[0] === 0x47 && bytes[1] === 0x49) return "image/gif";
  if (bytes[0] === 0x52 && bytes[1] === 0x49) return "image/webp";
  return "image/jpeg";
}

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = MediaSessionOrchestrator;
export const NAME = "do-media-session";

defineElement(NAME, MediaSessionOrchestrator);
```
### Output

A default output configuration. Contains all the outputs provided here along with the relevant transformers.

```js
import { ifDefined } from "lit-html/directives/if-defined.js";
import {
  DEFAULT_GROUP,
  defineElement,
  DiffuseElement,
} from "~/common/element.js";

import "~/components/configurator/output/element.js";
import "~/components/transformer/output/refiner/default/element.js";
import "~/components/transformer/output/refiner/initial-contents/element.js";

import "~/components/output/polymorphic/indexed-db/element.js";
import "~/components/transformer/output/string/json/element.js";

/**
 * @import {RenderArg} from "~/common/element.d.ts"
 * @import {OutputElement} from "@specs/components/output/types.d.ts"
 * @import {OutputConfiguratorElement} from "@specs/components/configurator/output/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * A default setup for managing output.
 *
 * @implements {OutputConfiguratorElement}
 */
class OutputOrchestrator extends DiffuseElement {
  static NAME = "diffuse/orchestrator/output";

  // ELEMENT GETTERS

  /**
   * @returns {OutputElement}
   */
  get output() {
    /** @type {OutputElement | null} */
    const output = this.root().querySelector("#do-output__output");

    if (!output) throw new Error("Output orchestrator did not render yet.");
    return output;
  }

  /**
   * @returns {OutputConfiguratorElement}
   */
  get outputConfigurator() {
    /** @type {OutputConfiguratorElement | null} */
    const outputConfigurator = this.root().querySelector(
      "#do-output__dc-output",
    );

    if (!outputConfigurator) {
      throw new Error("Output orchestrator did not render yet.");
    }

    return outputConfigurator;
  }

  // PROXY OUTPUT ACTIONS

  get collaborations() {
    return this.output.collaborations;
  }

  get facets() {
    return this.output.facets;
  }

  get playlistItems() {
    return this.output.playlistItems;
  }

  get settings() {
    return this.output.settings;
  }

  get tracks() {
    return this.output.tracks;
  }

  get ready() {
    return this.output.ready;
  }

  // PROXY ADDITIONAL OUTPUT CONFIGURATOR ACTIONS

  get activated() {
    return this.outputConfigurator.activated.bind(this.outputConfigurator);
  }

  get deselect() {
    return this.outputConfigurator.deselect.bind(this.outputConfigurator);
  }

  get hasDefault() {
    return this.outputConfigurator.hasDefault.bind(this.outputConfigurator);
  }

  get hasSelected() {
    return this.outputConfigurator.hasSelected.bind(this.outputConfigurator);
  }

  get loadSelected() {
    return this.outputConfigurator.loadSelected.bind(this.outputConfigurator);
  }

  get options() {
    return this.outputConfigurator.options.bind(this.outputConfigurator);
  }

  get select() {
    return this.outputConfigurator.select.bind(this.outputConfigurator);
  }

  get selected() {
    return this.outputConfigurator.selected.bind(this.outputConfigurator);
  }

  get waitForOption() {
    return this.outputConfigurator.waitForOption.bind(this.outputConfigurator);
  }

  get waitForSelected() {
    return this.outputConfigurator.waitForSelected.bind(
      this.outputConfigurator,
    );
  }

  // RENDER

  /**
   * @param {RenderArg} _
   */
  render({ html }) {
    const group = this.group === DEFAULT_GROUP ? undefined : this.group;

    return html`
      <dop-indexed-db
        id="do-output__dop-indexed-db__json"
        namespace="${this.namespace ? this.namespace + "/" : ""}json"
        group="${ifDefined(group)}"
      ></dop-indexed-db>

      <!-- OUTPUT CONFIGURATOR -->
      <dc-output
        id="do-output__dc-output"
        default="do-output__dc-output__local"
        group="${ifDefined(group)}"
      >
        <dtos-json
          id="do-output__dc-output__local"
          output-selector="#do-output__dop-indexed-db__json"
          label="Local"
        ></dtos-json>
      </dc-output>

      <!-- ENTRY ⬆️ -->
      <dtor-initial-contents
        id="do-output__dtor-initial-contents"
        output-selector="#do-output__dc-output"
      ></dtor-initial-contents>

      <dtor-default
        id="do-output__output"
        output-selector="#do-output__dtor-initial-contents"
        group="${ifDefined(group)}"
      ></dtor-default>
    `;
  }
}

export default OutputOrchestrator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = OutputOrchestrator;
export const NAME = "do-output";

defineElement(NAME, CLASS);
```
### Process Inputs Into Tracks

Whenever the cached tracks are initially loaded through the passed output element it will list tracks by using the passed input element. Afterwards it loops over all tracks and checks if metadata needs to be fetched. If anything has changed, it'll pass the results to the output element.

```js
import {
  BroadcastableDiffuseElement,
  defineElement,
  query,
} from "~/common/element.js";
import { data, mergeById } from "~/common/output.js";
import { signal, untracked } from "~/common/signal.js";
import { listen } from "~/common/worker.js";

import { parseDisabledUris } from "~/components/orchestrator/sources/common.js";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {InputElement} from "@specs/components/input/types.d.ts"
 * @import {OutputElement} from "@specs/components/output/types.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 * @import MetadataConfigurator from "~/components/configurator/metadata/element.js"
 *
 * @import {Actions, Progress} from "@specs/components/orchestrator/process-tracks/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Coalesce the worker's progress batches into one save. A save rewrites the
 * collection document and pushes it, so one save per batch makes a large
 * library's metadata pass expensive.
 */
const PATCH_SAVE_MS = 1_000;

/**
 * Processes inputs into tracks whenever
 * the already existing tracks are loaded
 * from the assigned output element.
 */
class ProcessTracksOrchestrator extends BroadcastableDiffuseElement {
  static NAME = "diffuse/orchestrator/process-tracks";
  static WORKER_URL = "components/orchestrator/process-tracks/worker.js";

  /** @type {ProxiedActions<Actions>} */
  #proxy;

  /** Latest progress snapshot from the worker. @type {Track[] | null} */
  #pendingPatch = null;

  /** @type {ReturnType<typeof setTimeout> | undefined} */
  #patchTimer;

  constructor() {
    super();
    this.#proxy = this.workerProxy({
      forceNew: {
        dependencies: { input: true },
      },
    });
  }

  // SIGNALS

  #isProcessing = signal(false);
  #performedInitialProcess = signal(false);
  #progress = signal(/** @type {Progress} */ ({ processed: 0, total: 0 }));

  // STATE

  isProcessing = this.#isProcessing.get;
  progress = this.#progress.get;

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    // Broadcast if needed
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(this.identifier, {
        getPerfInit: {
          strategy: "leaderOnly",
          fn: this.#performedInitialProcess.get,
        },
        setPerfInit: {
          strategy: "replicate",
          fn: this.#performedInitialProcess.set,
        },
        getIsProcessing: {
          strategy: "leaderOnly",
          fn: this.#isProcessing.get,
        },
        setIsProcessing: {
          strategy: "replicate",
          fn: this.#isProcessing.set,
        },
        process: { strategy: "leaderOnly", fn: this.process },
      });

      if (!actions) return;

      this.process = actions.process;
      this.#isProcessing.set = actions.setIsProcessing;

      // Sync #performedInitialProcess and #isProcessing with leader
      actions.getPerfInit().then((val) => {
        this.#performedInitialProcess.value = val;
      });

      actions.getIsProcessing().then((val) => {
        this.#isProcessing.value = val;
      });
    }

    // Super
    super.connectedCallback();

    /** @type {InputElement} */
    const input = query(this, "input-selector");

    /** @type {OutputElement} */
    const output = query(this, "output-selector");

    /** @type {MetadataConfigurator} */
    const metadataConfigurator = query(this, "metadata-selector");

    // Assign to self
    this.input = input;
    this.output = output;
    this.metadataConfigurator = metadataConfigurator;

    // Worker link
    const link = this.workerLink();

    // Wait until defined
    await customElements.whenDefined(input.localName);
    await customElements.whenDefined(output.localName);
    await customElements.whenDefined(metadataConfigurator.localName);

    // Sync progress with worker
    listen("progress", this.#progress.set, link);
    this.#proxy.progress().then(this.#progress.set);

    //
    listen("list", /** @param {Track[]} tracks */ async (tracks) => {
      if (!this.output) return;
      this.output.tracks.save(tracks);
    }, link);

    // Save patched tracks as they arrive so progress isn't lost — but coalesce
    // the worker's batches into one save per second.
    listen("patch", /** @param {Track[]} tracks */ (tracks) => {
      if (!this.output) return;

      this.#pendingPatch = tracks;

      if (this.#patchTimer !== undefined) return;

      this.#patchTimer = setTimeout(
        () => void this.#flushPatch(),
        PATCH_SAVE_MS,
      );
    }, link);

    // Process whenever tracks are initially loaded;
    // unless already done so (possibly through another instance of this element)
    if (this.hasAttribute("process-when-ready")) {
      let unregistered = false;

      const unregister = this.effect(() => {
        if (unregistered) {
          unregister();
          return;
        }

        const col = output.tracks.collection();
        if (col.state !== "loaded") return;

        if (this.#performedInitialProcess.value) {
          unregistered = true;
          return;
        }

        this.#performedInitialProcess.set(true);

        const skip = /** @type {any} */ (import.meta).env
          ?.DISABLE_AUTOMATIC_TRACKS_PROCESSING ?? false;
        if (skip) return;

        unregistered = true;
        untracked(() => this.process());
      });
    }
  }

  // WORKERS

  /**
   * @override
   */
  dependencies() {
    if (!this.input) throw new Error("Input element not defined yet");
    if (!this.metadataConfigurator) {
      throw new Error("Metadata configurator element not defined yet");
    }

    return {
      input: this.input,
      metadata: this.metadataConfigurator,
    };
  }

  // ACTIONS

  /**
   * (Re)processes tracks. When `onlyUris` is provided, only tracks belonging
   * to those source URIs (matched by prefix) are processed; all other tracks
   * are preserved untouched.
   *
   * @param {string[]} [onlyUris]
   */
  async process(onlyUris = []) {
    if (!this.output) return;
    if (this.#isProcessing.value) return;

    // Start
    this.#isProcessing.set(true);
    console.log("🪵 Processing initiated");

    const cachedTracks = await data(this.output.tracks);

    const settings = await data(this.output.settings);
    const disabledUris = parseDisabledUris(settings);

    const result = await this.#proxy.process({
      tracks: cachedTracks,
      disabledUris,
      onlyUris,
    });

    if (result) {
      // The final result supersedes any coalesced progress save.
      this.#cancelPatch();

      // Re-read the current output tracks instead of using the stale
      // `cachedTracks` snapshot from the start of processing. If a track
      // was deleted from the output while processing was in-flight, it
      // won't be in `currentTracks`, so `mergeById` won't bring it back.
      const currentTracks = await data(this.output.tracks);
      await this.output.tracks.save(mergeById(currentTracks, result));
    }

    // Fin
    console.log("🪵 Processing completed");
    this.#isProcessing.set(false);
  }

  /** @override */
  disconnectedCallback() {
    // A progress save still waiting on its timer would otherwise be lost when
    // the page navigates away mid-process.
    if (this.#pendingPatch) void this.#flushPatch();

    super.disconnectedCallback();
  }

  /** Save the latest coalesced progress snapshot. */
  async #flushPatch() {
    if (this.#patchTimer !== undefined) {
      clearTimeout(this.#patchTimer);
      this.#patchTimer = undefined;
    }

    const tracks = this.#pendingPatch;
    this.#pendingPatch = null;

    if (!tracks || !this.output) return;

    const existing = await data(this.output.tracks);
    await this.output.tracks.save(mergeById(existing, tracks));
  }

  #cancelPatch() {
    if (this.#patchTimer !== undefined) {
      clearTimeout(this.#patchTimer);
      this.#patchTimer = undefined;
    }

    this.#pendingPatch = null;
  }
}

export default ProcessTracksOrchestrator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = ProcessTracksOrchestrator;
export const NAME = "do-process-tracks";

defineElement(NAME, ProcessTracksOrchestrator);
```
### Queue + Audio

Connects the given queue engine to the given audio engine.

```js
import { BroadcastableDiffuseElement, defineElement, query } from "~/common/element.js";
import { untracked } from "~/common/signal.js";

/**
 * @import {InputElement} from "@specs/components/input/types.d.ts"
 * @import {OutputElement} from "@specs/components/output/types.d.ts"
 * @import RepeatShuffleEngine from "~/components/engine/repeat-shuffle/element.js"
 */

////////////////////////////////////////////
// EXPIRY
////////////////////////////////////////////

/**
 * How long before a resolved URL expires the active item is re-resolved.
 *
 * Refreshing is cheap for the inputs that hand out links, so the window is
 * generous on purpose: background tabs throttle timers, and reloading a few
 * minutes early is invisible, while a link that lapses mid-playback only
 * surfaces as a media error after the fact.
 */
export const URL_REFRESH_SKEW_SECONDS = 5 * 60;

/**
 * Retry cadence when a refresh didn't produce a usable URL (e.g. the input is
 * unreachable). Prevents a tight resolve loop off a zero-delay expiry.
 */
const REFRESH_RETRY_MS = 15_000;

/** `setTimeout` clamps delays above this to zero. */
const MAX_TIMEOUT_MS = 2 ** 31 - 1;

/**
 * Whether a resolved URL is inside its refresh window, or already expired.
 * Object URLs (and anything without a finite expiry) never need refreshing.
 *
 * @param {number | undefined} expiresAt - Unix seconds.
 * @param {number} [now] - Current time in ms; injectable for tests.
 */
export function isExpiring(expiresAt, now = Date.now()) {
  if (expiresAt === undefined || !Number.isFinite(expiresAt)) return false;
  return expiresAt - URL_REFRESH_SKEW_SECONDS <= now / 1000;
}

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * When the active queue item changes,
 * coordinate the audio engine accordingly.
 *
 * Vice versa, when the audio ends,
 * shift the queue if needed.
 */
class QueueAudioOrchestrator extends BroadcastableDiffuseElement {
  static NAME = "diffuse/orchestrator/queue-audio";

  /** @type {ReturnType<typeof setTimeout> | undefined} */
  #refreshTimer = undefined;

  /**
   * Audio ids with a refresh in flight, so the timer and the error watcher
   * don't race for the same item.
   *
   * @type {Set<string>}
   */
  #refreshing = new Set();

  // LIFE CYCLE

  /**
   * @override
   */
  async connectedCallback() {
    // Broadcast if needed
    if (this.hasAttribute("group")) {
      this.broadcast(this.identifier, {});
    }

    // Super
    super.connectedCallback();

    /** @type {import("~/components/engine/audio/element.js").CLASS} */
    this.audio = query(this, "audio-engine-selector");

    /** @type {InputElement} */
    this.input = query(this, "input-selector");

    /** @type {OutputElement} */
    this.output = query(this, "output-selector");

    /** @type {import("~/components/engine/queue/element.js").CLASS} */
    this.queue = query(this, "queue-engine-selector");

    /** @type {RepeatShuffleEngine} */
    this.repeatShuffle = query(this, "repeat-shuffle-engine-selector");

    // Wait until defined
    await customElements.whenDefined(this.audio.localName);
    await customElements.whenDefined(this.input.localName);
    await customElements.whenDefined(this.queue.localName);
    await customElements.whenDefined(this.repeatShuffle.localName);

    // Effects
    this.effect(() => this.monitorActiveQueueItem());
    this.effect(() => this.monitorAudioEnd());
    this.effect(() => this.monitorExpiringUrl());
  }

  /**
   * @override
   */
  disconnectedCallback() {
    clearTimeout(this.#refreshTimer);
    this.#refreshTimer = undefined;

    super.disconnectedCallback();
  }

  // 🛠️

  /**
   * @param {boolean} [refresh] - Ignore an already-supplied URL (it is
   *   expiring) and reload the element on the freshly resolved one.
   */
  async monitorActiveQueueItem(refresh = false) {
    const audio = this.audio;
    const input = this.input;
    const queue = this.queue;

    if (!audio) return;
    if (!input) return;
    if (!queue) return;

    const activeItem = queue.now();
    const tracksCol = this.output?.tracks.collection();
    const tracks = tracksCol?.state === "loaded" ? tracksCol.data : undefined;

    // Read synchronously so leadership changes (e.g. tab takeover) re-trigger this effect.
    const statusPromise = this.broadcasted ? this.broadcastingStatus() : undefined;

    const activeTrack = activeItem
      ? tracks?.find((t) => t.id === activeItem.id)
      : undefined;

    const status = statusPromise ? await statusPromise : undefined;
    if (status && !status.leader) return;

    const isPlaying = untracked(audio.isPlaying);

    // Fast path: the active track may already be resolved & supplied
    // (e.g. the preload prelude resolved the next track ahead of time).
    // Reusing that URL avoids an async resolve roundtrip between the
    // `ended` event and the play() call — on iOS that gap deactivates the
    // background audio session, and the next track then silently fails to
    // start until the page is refocused. Blob URLs are excluded: they're
    // bound to the context that created them, so they always need a fresh
    // resolve (e.g. after a tab leadership handoff). So is a URL inside its
    // expiry window: its resource is (about to be) gone.
    const supplied = activeTrack
      ? untracked(() => audio.items()).find(
        (i) =>
          i.id === activeTrack.id && i.url && !i.url.startsWith("blob:") &&
          !isExpiring(i.expiresAt),
      )
      : undefined;

    // Resolve active URI
    const resolvedUri = activeTrack
      ? (supplied
        ? {
          url: supplied.url,
          mimeType: supplied.mimeType,
          expiresAt: supplied.expiresAt,
        }
        : await input.resolve({ method: "GET", uri: activeTrack.uri }))
      : undefined;

    // Check if we still need to render
    if (queue.now?.()?.id !== activeItem?.id) return;

    // A failed refresh must not drop the item that is (still) playing — that
    // is what supplying an empty list would do. Keep it and retry on the
    // refresh timer instead.
    if (refresh && !resolvedUri) {
      this.#scheduleRefresh(activeTrack?.id);
      return;
    }

    // Supply active track immediately
    // TODO: Add support for seeking streams
    //       (requires a lot of code, decoding audio frames, etc.)
    const activeAudio = activeTrack && resolvedUri
      ? [{
        id: activeTrack.id,
        isPreload: false,
        track: activeTrack,
        ...resolvedUri,
      }]
      : [];

    // A refresh replaces the source of an item that is already loaded, so the
    // position and play intent it had must survive the reload below.
    const before = refresh && activeTrack
      ? audio.state(activeTrack.id)
      : undefined;

    audio.supply({
      audio: activeAudio,
      // The reload below resumes playback; don't also restart it here.
      play: !refresh && activeItem && isPlaying
        ? { audioId: activeItem.id }
        : undefined,
    });

    if (refresh && activeTrack && resolvedUri && "url" in resolvedUri) {
      const duration = before?.duration() ?? 0;
      const progress = duration > 0 && Number.isFinite(duration)
        ? (before?.currentTime() ?? 0) / duration
        : undefined;

      // `supply` never interrupts a healthy element, so without this the new
      // URL would only take effect at the next full load.
      audio.reload({
        audioId: activeTrack.id,
        force: true,
        progress,
        play: (before?.isPlaying() ?? false) && before?.hasEnded() !== true,
      });
    }

    this.#scheduleRefresh(activeTrack?.id);
  }

  /**
   * Watch the active item for a media error while its URL is expired (or is
   * about to be). The engine retries the *same* URL, so an expired link would
   * retry up to its ceiling and never recover on its own — re-resolving is the
   * only way out.
   */
  monitorExpiringUrl() {
    const audio = this.audio;
    if (!audio) return;

    const active = audio.items().find((item) => !item.isPreload);
    if (!active) return;
    if (!isExpiring(active.expiresAt)) return;

    const loading = audio.state(active.id)?.loadingState();
    const failed = typeof loading === "object" && "error" in loading;
    if (!failed) return;

    // The effect must not track whatever the refresh reads.
    untracked(() => this.#refresh(active.id));
  }

  async monitorAudioEnd() {
    if (!this.audio) return;
    if (!this.queue) return;

    const now = this.queue.now();
    const aud = now ? this.audio.state(now.id) : undefined;

    if (aud?.hasEnded() && (await this.isLeader())) {
      if (this.repeatShuffle?.repeat() && now) {
        this.audio.seek({ audioId: now.id, currentTime: 0 });
        this.audio.play({ audioId: now.id });
        return;
      }

      await this.queue.shift();
    }
  }

  // REFRESH

  /**
   * Re-resolve the active item's URL and reload the element on it. Single
   * flight per item: the expiry timer and the error watcher can fire for the
   * same item at nearly the same time.
   *
   * @param {string} id
   */
  async #refresh(id) {
    if (this.#refreshing.has(id)) return;
    if (this.queue?.now()?.id !== id) return;

    this.#refreshing.add(id);
    try {
      await this.monitorActiveQueueItem(true);
    } finally {
      this.#refreshing.delete(id);
    }
  }

  /**
   * Arm the timer that re-resolves `id` shortly before its URL expires.
   * Items without a finite expiry (object URLs, streams) disarm it.
   *
   * @param {string | undefined} id
   */
  #scheduleRefresh(id) {
    clearTimeout(this.#refreshTimer);
    this.#refreshTimer = undefined;

    if (!id) return;

    const item = untracked(() => this.audio?.items() ?? []).find((i) =>
      i.id === id
    );
    const expiresAt = item?.expiresAt;

    if (expiresAt === undefined || !Number.isFinite(expiresAt)) return;

    // Floor the delay: a URL that is already inside the window (a previous
    // refresh failed, or an input handed out a nearly-expired link) must not
    // turn into a tight resolve loop.
    const delay = Math.max(
      REFRESH_RETRY_MS,
      (expiresAt - URL_REFRESH_SKEW_SECONDS) * 1000 - Date.now(),
    );

    this.#refreshTimer = setTimeout(() => {
      this.#refreshTimer = undefined;
      if (this.queue?.now()?.id !== id) return;
      this.#refresh(id);
    }, Math.min(delay, MAX_TIMEOUT_MS));
  }
}

export default QueueAudioOrchestrator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = QueueAudioOrchestrator;
export const NAME = "do-queue-audio";

defineElement(NAME, QueueAudioOrchestrator);
```
### Scoped Tracks

Watches the given output's tracks collection and runs them through a built-in search index. Can perform a search and other ways to reduce the scope of tracks based on the given scope engine. Provides a tracks signal similar to output.tracks.collection.

```js
import {
  BroadcastableDiffuseElement,
  defineElement,
  query,
  queryOptional,
} from "~/common/element.js";
import { batch, computed, signal } from "~/common/signal.js";
import {
  filterByPlaylist,
  gather,
  orderByPlaylist,
  transform,
} from "~/common/playlist.js";
import { safeDecodeURIComponent } from "~/common/utils.js";
import { listen } from "~/common/worker.js";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 * @import {InputElement} from "@specs/components/input/types.d.ts"
 * @import {OutputElement} from "@specs/components/output/types.d.ts"
 * @import {Actions, State, TrackPools} from "@specs/components/orchestrator/scoped-tracks/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

class ScopedTracksOrchestrator extends BroadcastableDiffuseElement {
  static NAME = "diffuse/orchestrator/scoped-tracks";
  static WORKER_URL = "components/orchestrator/scoped-tracks/worker.js";

  /** @type {ProxiedActions<Actions & State>} */
  #proxy;

  constructor() {
    super();
    this.#proxy = this.workerProxy();
  }

  // SIGNALS

  #input = signal(/** @type {InputElement | null} */ (null));
  #output = signal(/** @type {OutputElement | null} */ (null));

  #scope = signal(
    /** @type {import("~/components/engine/scope/element.js").CLASS | null} */ (null),
  );

  #supplyFingerprint = signal(/** @type {string | undefined} */ (undefined));

  #selectedPlaylistItems = computed(() => {
    const playlist = this.#scope.value?.playlist();
    if (!playlist) return undefined;

    const col = this.#output.value?.playlistItems.collection();
    if (!col || col.state !== "loaded") return undefined;
    return (col.data ?? []).filter((p) => p.playlist === playlist);
  });

  #disabledSources = computed(() => {
    const col = this.#output.value?.settings.collection();
    if (!col || col.state !== "loaded") return [];

    // `data` is `undefined` when the output has nothing stored yet.
    const setting = (col.data ?? []).find((s) =>
      s.key === "sh.diffuse.input.disabled.uris"
    );

    if (!setting) return [];

    try {
      const parsed = JSON.parse(setting.value);
      return Array.isArray(parsed) ? /** @type {string[]} */ (parsed) : [];
    } catch {
      return [];
    }
  });

  #tracksAvailable = signal(/** @type {Track[]} */ ([]));

  /** `undefined` when no search is active; `[]` means an active search with no hits. */
  #tracksSearch = signal(/** @type {Track[] | undefined} */ (undefined));
  #tracksFinal = signal(/** @type {Track[]} */ ([]));

  /**
   * The full available pool minus disabled sources — the base both the
   * catalog and the scoped pipeline start from. Because it derives from
   * signals that are already replicated (`#tracksAvailable`) and shared
   * (`#disabledSources`), it doesn't need its own broadcast channel.
   */
  #tracksBase = computed(() => {
    const available = this.#tracksAvailable.value;
    const disabledSources = this.#disabledSources();

    return disabledSources.length
      ? available.filter((t) =>
        !disabledSources.some((source) => t.uri.startsWith(source))
      )
      : available;
  });

  #tracksGrouped = computed(() => {
    const tracks = this.#tracksFinal.value;
    const groupBy = this.#scope.value?.groupBy();
    if (!groupBy) return undefined;
    return buildGroups(tracks, groupBy);
  });

  // STATE

  supplyFingerprint = this.#supplyFingerprint.get;
  groups = this.#tracksGrouped;

  /** @returns {TrackPools} */
  tracks = computed(() => ({
    available: this.#tracksBase(),
    scoped: this.#tracksFinal.value,
  }));

  /**
   * Whether the currently selected playlist should be rendered in its own
   * order (i.e. its playlist items form a `positionedAfter` chain). When
   * this is true, themes should prefer it over `sortBy` for UI indicators
   * (e.g. don't highlight the "artist" column as the active sort). It is
   * independent of `groupBy`/`sortBy` so grouping may still be applied —
   * in that case tracks are grouped by the `groupBy` key while playlist
   * order is preserved within each group.
   */
  playlistIsOrdered = computed(() => {
    const playlistItems = this.#selectedPlaylistItems();
    const playlistName = this.#scope.value?.playlist();

    return playlistItems?.length && playlistName
      ? gather(playlistItems).get(playlistName)?.unordered === false
      : false;
  });

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    // Broadcast if needed
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(this.identifier, {
        getTracksAvailable: {
          strategy: "leaderOnly",
          fn: this.#tracksAvailable.get,
        },
        getTracksSearch: {
          strategy: "leaderOnly",
          fn: this.#tracksSearch.get,
        },
        getTracksFinal: {
          strategy: "leaderOnly",
          fn: this.#tracksFinal.get,
        },
        setTracksAvailable: {
          strategy: "replicate",
          fn: this.#tracksAvailable.set,
        },
        setTracksSearch: {
          strategy: "replicate",
          fn: this.#tracksSearch.set,
        },
        setTracksFinal: {
          strategy: "replicate",
          fn: this.#tracksFinal.set,
        },
      });

      if (!actions) return;

      this.#tracksAvailable.set = actions.setTracksAvailable;
      this.#tracksSearch.set = actions.setTracksSearch;
      this.#tracksFinal.set = actions.setTracksFinal;

      // Sync signal state with leader
      Promise.all([
        actions.getTracksAvailable(),
        actions.getTracksSearch(),
        actions.getTracksFinal(),
      ]).then(([available, search, final]) =>
        batch(() => {
          this.#tracksAvailable.value = available;
          this.#tracksSearch.value = search;
          this.#tracksFinal.value = final;
        })
      );
    }

    // Super
    super.connectedCallback();

    /** @type {InputElement} */
    const input = query(this, "input-selector");

    /** @type {OutputElement} */
    const output = query(this, "output-selector");

    /** @type {import("~/components/engine/scope/element.js").CLASS | null} */
    const scope = queryOptional(this, "scope-engine-selector");

    // Assign to self
    this.#input.value = input;
    this.#output.value = output;
    if (scope) this.#scope.value = scope;

    // Sync supply fingerprint with worker
    const link = this.workerLink();
    listen("supplyFingerprint", this.#supplyFingerprint.set, link);
    this.#proxy.supplyFingerprint().then(this.#supplyFingerprint.set);

    // When defined
    await customElements.whenDefined(input.localName);
    await customElements.whenDefined(output.localName);
    if (scope) await customElements.whenDefined(scope.localName);

    // Watch tracks collection
    this.effect(async () => {
      const tracksCol = output.tracks.collection();

      if ((await this.isLeader()) === false) return;
      if (tracksCol.state !== "loaded") return;

      /** @type {string[]} */
      const uris = [];
      const tracks = tracksCol.data.filter((t) => {
        uris.push(t.uri);
        return t.kind !== "placeholder";
      });

      // Consult inputs
      const groups = tracksCol.data.length
        ? await input.groupConsult(uris)
        : {};

      /** @type {Set<string>} */
      const availableUris = new Set();

      Object.values(groups).forEach((value) => {
        // Only include tracks whose source confirmed availability ("yes").
        // Both "no" (server explicitly rejected) and "unsure" (transient
        // consult failure — e.g. a laptop waking up before the network
        // is fully back) hide the source's tracks until a real consult
        // succeeds. `cachedConsult` normalises "unsure" to "no" for callers
        // (without caching it), so a brief blip doesn't pin availability
        // to "unavailable" for the full TTL — the next consult retries
        // immediately and repopulates the browser once the server responds.
        if (value.available !== "yes") return;
        for (const uri of value.uris) {
          availableUris.add(uri);
        }
      });

      const availableTracks = tracks.filter((t) => {
        return availableUris.has(t.uri) && !!t.tags;
      });

      // Set pool
      this.#proxy.supply({ tracks: availableTracks });
      this.#tracksAvailable.set(availableTracks);
    });

    // Watch the search term + supplied index
    let searchX = 0;

    this.effect(async () => {
      const _trigger = this.#supplyFingerprint.value;
      const searchTerm = this.#scope.value?.searchTerm();

      const y = ++searchX;

      if ((await this.isLeader()) === false) return;
      if (y !== searchX) return;

      if (searchTerm?.length) {
        const searchResults = await this.#proxy.search({
          term: searchTerm,
        });
        if (y !== searchX) return;
        this.#tracksSearch.set(searchResults);
      } else {
        this.#tracksSearch.set(undefined);
      }
    });

    // Watch `#tracksAvailable` + search + Playlist + Sort + Selection.
    //
    // Pipeline order (deliberate): the catalog is always the full pool;
    // the scoped list is sort → playlist → selection → search.
    let x = 0;

    this.effect(async () => {
      // Read every dependency before the await so reactivity is registered.
      // Disabled sources are a library-level preference, so `#tracksBase`
      // narrows both the catalog and the final list.
      const base = this.#tracksBase();
      const searchResults = this.#tracksSearch.value;
      const playlistItems = this.#selectedPlaylistItems();
      const sortBy = this.#scope.value?.sortBy();
      const sortDirection = this.#scope.value?.sortDirection();
      const groupBy = this.#scope.value?.groupBy();
      const selection = this.#scope.value?.selection();

      const y = ++x;

      if ((await this.isLeader()) === false) return;
      if (y !== x) return;

      // 1. Sort. When groupBy is active, sort by group key first using
      // the group's canonical direction (from GROUP_BY_SORT_OVERRIDES, or
      // the user's direction for firstLetter), then by the user's sortBy.
      //
      // Schwartzian transform: precompute all keys once (O(N)) so the
      // comparator never re-parses URLs or re-splits dot-paths (O(N log N)).
      let final = base;

      const groupOverride = groupBy
        ? GROUP_BY_SORT_OVERRIDES[groupBy]
        : undefined;
      const groupDir =
        (groupOverride?.sortDirection ?? sortDirection) === "desc" ? -1 : 1;
      const userFields = sortBy ?? [];
      const userDir = sortDirection === "desc" ? -1 : 1;
      const splitPaths = userFields.map((f) => f.split("."));

      if (groupBy || userFields.length) {
        const decorated = final.map((track) => ({
          track,
          groupKey: groupBy ? groupKeyLabel(track, groupBy).key : "",
          fieldVals: splitPaths.map((parts) => {
            let v = /** @type {any} */ (track);
            for (const p of parts) v = v?.[p];
            return v;
          }),
        }));

        decorated.sort((a, b) => {
          if (groupBy && a.groupKey !== b.groupKey) {
            if (!a.groupKey) return 1;
            if (!b.groupKey) return -1;
            return collator.compare(a.groupKey, b.groupKey) * groupDir;
          }
          for (let i = 0; i < a.fieldVals.length; i++) {
            const av = a.fieldVals[i];
            const bv = b.fieldVals[i];
            // Null/undefined always sorts last regardless of direction
            if (av == null && bv == null) continue;
            if (av == null) return 1;
            if (bv == null) return -1;
            const cmp = compareValues(av, bv);
            if (cmp !== 0) return cmp * userDir;
          }
          return 0;
        });

        final = decorated.map((d) => d.track);
      }

      // 2. Playlist. Filtering preserves the sorted order; an ordered
      // playlist then re-applies its own `positionedAfter` chain.
      if (playlistItems?.length) {
        final = filterByPlaylist(final, playlistItems);

        if (this.playlistIsOrdered()) {
          final = orderByPlaylist(
            final,
            /** @type {import("~/definitions/types.d.ts").PlaylistItem[]} */ (playlistItems),
          );
        }
      }

      // 3. Selection
      if (selection?.length) {
        final = final.filter((track) => inSelection(track, selection));
      }

      // 4. Search
      if (searchResults) {
        const ids = new Set(searchResults.map((t) => t.id));
        final = final.filter((t) => ids.has(t.id));
      }

      this.#tracksFinal.set(final);
    });
  }
}

export default ScopedTracksOrchestrator;

////////////////////////////////////////////
// HELPERS
////////////////////////////////////////////

const collator = new Intl.Collator();

const MONTHS = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
];

/** @type {Record<string, { sortDirection: "asc" | "desc" }>} */
const GROUP_BY_SORT_OVERRIDES = {
  createdAt: { sortDirection: "desc" },
  directory: { sortDirection: "asc" },
  firstLetter: { sortDirection: "asc" },
  "tags.year": { sortDirection: "desc" },
};

/**
 * Whether a track passes every criterion of the scope's selection filter.
 * Values are compared as strings for `eq`, so tag fields that are stored as
 * numbers (years) still match string criteria. Missing values compare as the
 * empty string, mirroring how album/artist groupings bucket untagged tracks.
 *
 * @param {Track} track
 * @param {import("~/components/engine/scope/element.js").SelectionCriterion[]} selection
 * @returns {boolean}
 */
function inSelection(track, selection) {
  for (const criterion of selection) {
    let value = /** @type {any} */ (track);
    for (const part of criterion.field.split(".")) value = value?.[part];

    const actual = transform(value, criterion.transformations);
    const expected = transform(criterion.value, criterion.transformations);

    switch (criterion.op ?? "eq") {
      case "prefix":
        if (!String(actual ?? "").startsWith(String(expected ?? ""))) {
          return false;
        }
        break;
      case "gte":
        if (!(Number(actual) >= Number(expected))) return false;
        break;
      case "lt":
        if (!(Number(actual) < Number(expected))) return false;
        break;
      default:
        if (String(actual ?? "") !== String(expected ?? "")) return false;
    }
  }

  return true;
}

/**
 * @param {Track[]} tracks
 * @param {string} groupBy  dot-path field, e.g. "createdAt" or "tags.artist"
 * @returns {{ label: string; tracks: Track[] }[]}
 */
function buildGroups(tracks, groupBy) {
  // Bucket by key rather than relying on consecutive runs: the scope list
  // is usually sorted by group, but an ordered playlist can reorder it
  // after the sort, and grouping should still produce one bucket per key.
  /** @type {Map<string, { label: string; tracks: Track[] }>} */
  const groups = new Map();

  for (const track of tracks) {
    const { key, label } = groupKeyLabel(track, groupBy);

    let group = groups.get(key);
    if (!group) {
      group = { label, tracks: [] };
      groups.set(key, group);
    }

    group.tracks.push(track);
  }

  return [...groups.values()];
}

/**
 * @param {Track} track
 * @param {string} fieldPath
 * @returns {{ key: string; label: string }}
 */
function groupKeyLabel(track, fieldPath) {
  if (fieldPath === "createdAt") {
    const iso = track.createdAt;
    if (!iso) return { key: "", label: "Unknown" };
    const year = iso.slice(0, 4);
    const month = iso.slice(5, 7);
    return {
      key: `${year}-${month}`,
      label: `${MONTHS[parseInt(month, 10) - 1]} ${year}`,
    };
  }

  if (fieldPath === "directory") {
    const uri = track.uri ?? "";
    let path = uri;
    try {
      path = new URL(uri).pathname;
    } catch {
      // not a valid URL, use as-is
    }
    const slash = path.lastIndexOf("/");
    const dir = slash > 0 ? path.slice(0, slash) : path;
    const key = uri.slice(0, uri.lastIndexOf("/"));
    return { key, label: safeDecodeURIComponent(dir) || "Unknown" };
  }

  if (fieldPath.startsWith("firstLetter:")) {
    const dotPath = fieldPath.slice("firstLetter:".length);
    let val = /** @type {any} */ (track);
    for (const key of dotPath.split(".")) val = val?.[key];
    const str = val != null ? String(val) : "";
    const letter = str.charAt(0).toUpperCase();
    const key = /[A-Z]/.test(letter) ? letter : "#";
    return { key, label: key };
  }

  // Generic dot-path extraction
  let val = /** @type {any} */ (track);
  for (const key of fieldPath.split(".")) val = val?.[key];
  const str = val != null ? String(val) : "";
  return { key: str, label: str || "Unknown" };
}

/**
 * @param {any} aVal
 * @param {any} bVal
 * @returns {number}
 */
function compareValues(aVal, bVal) {
  if (aVal == null && bVal == null) return 0;
  if (aVal == null) return 1;
  if (bVal == null) return -1;
  return typeof aVal === "string" && typeof bVal === "string"
    ? aVal.localeCompare(bVal)
    : aVal < bVal
    ? -1
    : aVal > bVal
    ? 1
    : 0;
}

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = ScopedTracksOrchestrator;
export const NAME = "do-scoped-tracks";

defineElement(NAME, CLASS);
```
### Scrobble + Audio

Connects the audio engine with a scrobbler element. Calls nowPlaying when a track starts playing and scrobble once the user has listened long enough.

```js
import { BroadcastableDiffuseElement, defineElement, query } from "~/common/element.js";

/**
 * @import {ScrobbleElement} from "@specs/components/supplement/types.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Connects the audio engine with the scrobble configurator.
 *
 * Calls `nowPlaying` when a track starts and `scrobble` once the user
 * has listened long enough per the last.fm rules:
 *   - Track must be at least 30 seconds long.
 *   - User must have listened to at least min(duration / 2, 4 minutes).
 */
class ScrobbleAudioOrchestrator extends BroadcastableDiffuseElement {
  static NAME = "diffuse/orchestrator/scrobble-audio";

  // LIFECYCLE

  /** @override */
  async connectedCallback() {
    if (this.hasAttribute("group")) {
      this.broadcast(this.identifier, {});
    }

    super.connectedCallback();

    /** @type {import("~/components/engine/audio/element.js").CLASS} */
    this.audio = query(this, "audio-engine-selector");

    /** @type {ScrobbleElement} */
    this.scrobble = query(this, "scrobble-selector");

    await customElements.whenDefined(this.audio.localName);
    await customElements.whenDefined(this.scrobble.localName);

    this.effect(() => this.#monitorAudio());
  }

  /** @override */
  disconnectedCallback() {
    super.disconnectedCallback();
    this.#stopTimer();
  }

  // TRACK STATE
  // Resets whenever the active (non-preload) audio item changes.

  /** @type {string | null} */
  #trackId = null;

  /** @type {Track | null} */
  #activeTrack = null;

  /** @type {number | null} Date.now() when track first started, used as the scrobble timestamp. */
  #startedAt = null;

  /** Whether `nowPlaying` has been called for the current track. */
  #nowPlayingSent = false;

  /** Whether `scrobble` has been called for the current track. */
  #scrobbled = false;

  /** Whether the current track has ended (used to detect restarts, e.g. repeat). */
  #hadEnded = false;

  // TIMER STATE
  // Accumulates actual listening time (pauses don't count).

  /** Accumulated listening time in ms before the last pause. */
  #listenedMs = 0;

  /** Date.now() when the timer was last resumed; null when paused. */
  #timerResumedAt = /** @type {number | null} */ (null);

  /** @type {ReturnType<typeof setInterval> | null} */
  #intervalId = null;

  // EFFECT

  /**
   * Reacts to audio item changes and playback state.
   * Detects track changes, resets state, and starts/stops the listening timer.
   */
  #monitorAudio() {
    if (!this.audio) return;

    const active = this.audio.items().find((item) => !item.isPreload);
    const id = active?.id ?? null;

    // Detect track change
    if (id !== this.#trackId) {
      this.#stopTimer();

      this.#trackId = id;
      this.#activeTrack = active?.track ?? null;
      this.#startedAt = id ? Date.now() : null;
      this.#nowPlayingSent = false;
      this.#scrobbled = false;
      this.#listenedMs = 0;
      this.#hadEnded = false;
    }

    if (!id) return;

    const state = this.audio.state(id);
    const loadingState = state?.loadingState() ?? "loading";
    const hasError = typeof loadingState === "object" && "error" in loadingState;
    const isPlaying = !hasError && (state?.isPlaying() ?? false);
    const hasEnded = state?.hasEnded() ?? false;

    // Detect same-track restart (e.g. repeat): the track ended and now plays again.
    if (this.#hadEnded && !hasEnded && isPlaying) {
      this.#stopTimer();
      this.#startedAt = Date.now();
      this.#nowPlayingSent = false;
      this.#scrobbled = false;
      this.#listenedMs = 0;
      this.#hadEnded = false;
    }

    if (hasEnded) this.#hadEnded = true;

    if (isPlaying) {
      this.#startTimer();

      if (!this.#nowPlayingSent) {
        this.#nowPlayingSent = true;
        this.#sendNowPlaying(id);
      }
    } else {
      this.#stopTimer();
    }
  }

  // TIMER

  #startTimer() {
    if (this.#timerResumedAt !== null) return;

    this.#timerResumedAt = Date.now();
    this.#intervalId = setInterval(() => this.#checkScrobble(), 1_000);
  }

  #stopTimer() {
    if (this.#timerResumedAt !== null) {
      this.#listenedMs += Date.now() - this.#timerResumedAt;
      this.#timerResumedAt = null;
    }

    if (this.#intervalId !== null) {
      clearInterval(this.#intervalId);
      this.#intervalId = null;
    }
  }

  #totalListenedMs() {
    return this.#listenedMs +
      (this.#timerResumedAt !== null ? Date.now() - this.#timerResumedAt : 0);
  }

  // SCROBBLING

  /**
   * @param {string} id
   */
  async #sendNowPlaying(id) {
    if (!(await this.isLeader())) return;
    if (this.#trackId !== id || !this.#activeTrack) return;

    try {
      await this.scrobble?.nowPlaying(this.#activeTrack);
    } catch (err) {
      console.warn("scrobble: nowPlaying failed", err);
    }
  }

  async #checkScrobble() {
    if (this.#scrobbled) return;

    const id = this.#trackId;
    if (!id || !this.#startedAt || !this.#activeTrack) return;

    const durationSec = this.audio?.state(id)?.duration() ?? 0;

    // Track must be at least 30 seconds
    if (durationSec < 30) return;

    // Must have listened to at least half the track or 4 minutes
    const listenedSec = this.#totalListenedMs() / 1000;
    if (listenedSec < Math.min(durationSec / 2, 240)) return;

    this.#scrobbled = true;

    if (!(await this.isLeader())) return;
    if (this.#trackId !== id) return;

    const track = this.#activeTrack;
    const startedAt = this.#startedAt;

    try {
      await this.scrobble?.scrobble(track, startedAt, { duration: Math.round(durationSec * 1000) });
    } catch (err) {
      console.warn("Scrobble failed", err);
      this.#scrobbled = false;
    }
  }
}

export default ScrobbleAudioOrchestrator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = ScrobbleAudioOrchestrator;
export const NAME = "do-scrobble-audio";

defineElement(NAME, ScrobbleAudioOrchestrator);
```
### Sources

Monitor tracks from the given output to form a list of sources based on the input's sources return value.

```js
import deepDiff from "@fry69/deep-diff";

import * as Output from "~/common/output.js";
import { BroadcastableDiffuseElement, defineElement, query } from "~/common/element.js";
import { groupTracksPerScheme } from "~/common/utils.js";
import { signal } from "~/common/signal.js";

import { DISABLED_KEY } from "./constants.js";
import { parseDisabledUris, uriKey } from "./common.js";

/**
 * @import {InputElement, Source} from "@specs/components/input/types.d.ts"
 * @import {OutputElement} from "@specs/components/output/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

class Sources extends BroadcastableDiffuseElement {
  static NAME = "diffuse/orchestrator/sources";

  // SIGNALS

  #sources = signal(/** @type {{ [scheme: string]: Source[] }} */ ({}));
  #disabled = signal(/** @type {string[]} */ ([]));

  // STATE

  sources = this.#sources.get;
  disabled = this.#disabled.get;

  #output = signal(/** @type {OutputElement | null} */ (null));

  // METHODS

  /**
   * Returns whether the given source URI is disabled.
   * Strips query params before comparing, matching how {@link toggle} stores keys.
   *
   * @param {string} uri
   * @returns {boolean}
   */
  isDisabled(uri) {
    return this.#disabled.get().includes(uriKey(uri));
  }

  /**
   * @param {string} uri
   */
  async toggle(uri) {
    const key = uriKey(uri);

    const output = this.#output.value;
    if (!output) {
      console.warn("Output element is not available yet.");
      return;
    }

    const settings = await Output.data(output.settings);
    const existing = settings.find((s) => s.key === DISABLED_KEY);

    let disabled = parseDisabledUris(settings);

    if (disabled.includes(key)) {
      disabled = disabled.filter((u) => u !== key);
    } else {
      disabled = [...disabled, key];
    }

    const value = JSON.stringify(disabled);
    const updated = existing
      ? settings.map((s) =>
        s.key === DISABLED_KEY ? { ...s, value } : s
      )
      : [
        ...settings,
        {
          $type: /** @type {"sh.diffuse.output.setting"} */ (
            "sh.diffuse.output.setting"
          ),
          id: crypto.randomUUID(),
          key: DISABLED_KEY,
          value,
        },
      ];

    await output.settings.save(updated);
  }

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    super.connectedCallback();

    /** @type {InputElement} */
    const input = query(this, "input-selector");

    /** @type {OutputElement} */
    const output = query(this, "output-selector");

    // Wait until defined
    await customElements.whenDefined(input.localName);
    await customElements.whenDefined(output.localName);

    // Signals
    this.#output.value = output;

    // Effects
    this.effect(() => {
      const col = output.settings.collection();
      if (col.state !== "loaded") { this.#disabled.value = []; return; }
      this.#disabled.value = parseDisabledUris(col.data);
    });

    // Single input mode + dependencies
    const singleInputMode = !!input.SCHEME;
    const deps =
      /** @type {{ [k: string]: InputElement }} */ (singleInputMode
        ? {}
        : input.dependencies());

    // Effects
    this.effect(() => {
      const col = output.tracks.collection();
      const tracks = col.state === "loaded" ? col.data : [];
      const groups = groupTracksPerScheme(tracks);

      /** @type {{ [scheme: string]: Source[] }} */
      const record = {};

      Object.entries(groups).map(([scheme, tracks]) => {
        /** @type {Source[]} */
        let sources;

        if (singleInputMode) {
          if (input.SCHEME === scheme) {
            sources = input.sources(tracks);
          } else {
            sources = [];
          }
        } else {
          const dep = deps[scheme];
          if (!dep) sources = tracks.map((t) => ({ label: t.uri, uri: t.uri }));
          else sources = dep.sources(tracks);
        }

        record[scheme] = sources;
      });

      if (deepDiff(this.#sources.value, record)) {
        this.#sources.value = record;
      }
    });
  }
}

export default Sources;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = Sources;
export const NAME = "do-sources";

defineElement(NAME, CLASS);
```
### Spectrogram + Audio

When a track starts playing and is missing spectrogram-derived stats, analyses it via the spectrogram metadata element and persists the result to the output. Only the leader tab performs the analysis.

```js
import {
  BroadcastableDiffuseElement,
  defineElement,
  query,
} from "~/common/element.js";
import { data, mergeById } from "~/common/output.js";

/**
 * @import {OutputElement} from "@specs/components/output/types.d.ts"
 * @import AudioEngine from "~/components/engine/audio/element.js"
 * @import {MetadataElement} from "@specs/components/metadata/types.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Fetches spectrogram data for a track when it starts playing, if it doesn't
 * already have spectral stats.
 *
 * Monitors the audio engine for the active (non-preload) track. When playback
 * begins, it checks whether the track is missing spectrogram-derived stats and,
 * if so, asks the spectrogram metadata element to analyse it, then persists the
 * patched track back to the output.
 *
 * Only the leader tab performs the analysis (broadcasting), so multi-tab setups
 * don't duplicate the (expensive) decoding work.
 */
class SpectrogramAudioOrchestrator extends BroadcastableDiffuseElement {
  static NAME = "diffuse/orchestrator/spectrogram-audio";

  // LIFECYCLE

  /** @override */
  async connectedCallback() {
    if (this.hasAttribute("group")) {
      this.broadcast(this.identifier, {});
    }

    super.connectedCallback();

    /** @type {AudioEngine} */
    this.audio = query(this, "audio-engine-selector");

    /** @type {MetadataElement} */
    this.spectrogram = query(this, "spectrogram-selector");

    /** @type {OutputElement} */
    this.output = query(this, "output-selector");

    await customElements.whenDefined(this.audio.localName);
    await customElements.whenDefined(this.spectrogram.localName);
    await customElements.whenDefined(this.output.localName);

    this.effect(() => this.#monitorAudio());
  }

  /** @override */
  disconnectedCallback() {
    if (this.#trackId) this.spectrogram?.abort?.(this.#trackId);
    super.disconnectedCallback();
  }

  // TRACK STATE
  // Resets whenever the active (non-preload) audio item changes.

  /** @type {string | null} */
  #trackId = null;

  /** Whether analysis has already been kicked off for the current track. */
  #analysed = false;

  /**
   * Track ids with an in-flight analysis, so a rapidly toggling play/pause or
   * a track change doesn't trigger duplicate concurrent analyses.
   *
   * @type {Set<string>}
   */
  #inFlight = new Set();

  // EFFECT

  /**
   * Reacts to audio item changes and playback state. When a track starts
   * playing and is missing spectral stats, triggers the spectrogram analysis.
   */
  #monitorAudio() {
    if (!this.audio) return;

    const active = this.audio.items().find((item) => !item.isPreload);
    const id = active?.id ?? null;

    // Detect track change
    if (id !== this.#trackId) {
      // The previous track's full-file download is now pointless: cancel it
      // instead of letting it keep a connection to the audio server busy.
      if (this.#trackId) this.spectrogram?.abort?.(this.#trackId);

      this.#trackId = id;
      this.#analysed = false;
    }

    if (!id || !active) return;

    const state = this.audio.state(id);
    const loadingState = state?.loadingState() ?? "loading";
    const hasError = typeof loadingState === "object" && "error" in loadingState;
    // Wait until `canplay` (loadingState "loaded") before fetching, so the
    // audio element gets first priority for bandwidth during its initial load
    // and the spectrogram's full-file fetch doesn't compete with it.
    const canPlay = !hasError && loadingState === "loaded";

    if (!canPlay) return;
    if (this.#analysed) return;

    this.#analysed = true;
    this.#analyse(id, active.track);
  }

  // ANALYSIS

  /**
   * @param {string} id
   * @param {Track} track
   */
  async #analyse(id, track) {
    // Already has spectral stats — nothing to do.
    if (hasSpectralStats(track.stats)) return;
    // Skip streams and very long tracks, matching the spectrogram worker's
    // own guardrails. Checking here avoids queueing work the worker would drop.
    if (track.kind === "stream") return;
    if (track.stats?.duration && track.stats.duration > MAX_DURATION_MS) return;
    // A previous play is still analysing this same track.
    if (this.#inFlight.has(id)) return;

    if (!(await this.isLeader())) return;
    if (this.#trackId !== id) return; // track changed while we awaited

    this.#inFlight.add(id);

    try {
      const patched = await this.spectrogram?.patch(track);
      if (!patched || patched === track) return;
      if (this.#trackId !== id) return; // track changed during analysis

      await this.#save(patched);
    } catch (err) {
      console.warn("spectrogram-audio: analysis failed", err);
    } finally {
      this.#inFlight.delete(id);
    }
  }

  /**
   * Merges the patched track back into the output's track list and persists it.
   *
   * @param {Track} track
   */
  async #save(track) {
    if (!this.output) return;

    const existing = await data(this.output.tracks);
    const merged = mergeById(existing, [track]);
    await this.output.tracks.save(merged);
  }
}

////////////////////////////////////////////
// STATS HELPERS
////////////////////////////////////////////

const SPECTRAL_KEYS = [
  "spectralCentroid",
  "spectralRolloff",
  "spectralSpread",
  "spectralFlatness",
  "spectralFlux",
];

/**
 * @param {import("~/definitions/types.d.ts").TrackStats | undefined} stats
 * @returns {boolean}
 */
function hasSpectralStats(stats) {
  if (!stats) return false;
  return SPECTRAL_KEYS.every((k) =>
    stats[/** @type {keyof import("~/definitions/types.d.ts").TrackStats} */ (k)] != null
  );
}

// Keep this in sync with the spectrogram worker's `MAX_DURATION_MS`.
const MAX_DURATION_MS = 4 * 60 * 60 * 1000; // 4 hours

export default SpectrogramAudioOrchestrator;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = SpectrogramAudioOrchestrator;
export const NAME = "do-spectrogram-audio";

defineElement(NAME, SpectrogramAudioOrchestrator);
```
## Output
### Polymorphic / IndexedDB

Stores output into the local indexedDB. Supports any type of data that indexedDB supports.

```js
import * as IDB from "idb-keyval";

import { IDB_PREFIX } from "./constants.js";
import { BroadcastedOutputElement, outputManager } from "../../common.js";
import { isSelfDescribing } from "~/common/self-describing.js";
import { decodeCollection, encodeCollection } from "~/common/lens.js";
import { defineElement } from "~/common/element.js";

/**
 * @import {OutputElement, OutputManager, OutputWorkerActions} from "@specs/components/output/types.d.ts"
 * @import {SupportedDataTypes} from "@specs/components/output/polymorphic/indexed-db/types.d.ts"
 * @import {CollectionName} from "~/common/self-describing.js"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {OutputElement<SupportedDataTypes>}
 */
class IndexedDBOutput extends BroadcastedOutputElement {
  static NAME = "diffuse/output/polymorphic/indexed-db";
  static WORKER_URL = "components/output/polymorphic/indexed-db/worker.js";

  #manager;

  constructor() {
    super();

    /** @type {OutputManager<SupportedDataTypes>} */
    this.#manager = outputManager({
      collaborations: {
        empty: () => undefined,
        get: () => this.#get("collaborations"),
        put: (data) => this.#put("collaborations", data),
      },
      facets: {
        empty: () => undefined,
        get: () => this.#get("facets"),
        put: (data) => this.#put("facets", data),
      },
      init: () => this.whenConnected(),
      playlistItems: {
        empty: () => undefined,
        get: () => this.#get("playlistItems"),
        put: (data) => this.#put("playlistItems", data),
      },
      settings: {
        empty: () => undefined,
        get: () => this.#get("settings"),
        put: (data) => this.#put("settings", data),
      },
      tracks: {
        empty: () => undefined,
        get: () => this.#get("tracks"),
        put: (data) => this.#put("tracks", data),
      },
    });

    this.collaborations = this.#manager.collaborations;
    this.facets = this.#manager.facets;
    this.playlistItems = this.#manager.playlistItems;
    this.settings = this.#manager.settings;
    this.tracks = this.#manager.tracks;

    this.ready = () => true;
  }

  // LIFECYCLE

  /** @override */
  connectedCallback() {
    this.replicateSavedData(this.#manager);
    super.connectedCallback();
  }

  // GET & PUT

  /** @param {string} name */
  #get = async (name) => {
    const stored = await IDB.get(`${IDB_PREFIX}/${this.#cat(name)}`);
    if (stored === undefined) return undefined;

    // Bytes/strings were stored by a transformer above and are self-describing
    // at that layer — it decodes them again (automerge binaries cannot be
    // CBOR-decoded here). Only envelopes from a standalone usage are decoded.
    if (stored instanceof Uint8Array || typeof stored === "string") {
      return stored;
    }

    return decodeCollection(
      stored,
      /** @type {CollectionName} */ (name),
    ) ?? undefined;
  };

  /** @param {string} name; @param {any} data */
  #put = async (name, data) => {
    // Bytes/strings produced by a transformer above (bytes/json or string/json
    // envelope bytes/JSON, or automerge/dasl binary) are already self-describing
    // at that layer, so they pass through as-is. Plain collections (arrays) are
    // wrapped so a standalone IndexedDB output is itself self-describing.
    const stored = data instanceof Uint8Array || typeof data === "string" ||
        isSelfDescribing(data)
      ? data
      : encodeCollection(data, /** @type {CollectionName} */ (name));
    await IDB.set(`${IDB_PREFIX}/${this.#cat(name)}`, stored);
  };

  // 🛠️

  /** @param {string} name */
  #cat(name) {
    return `${this.namespace?.length ? this.namespace + "/" : ""}${name}`;
  }
}

export default IndexedDBOutput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = IndexedDBOutput;
export const NAME = "dop-indexed-db";

defineElement(NAME, IndexedDBOutput);
```
### Bytes / Dropbox

Store output data as raw bytes in the Dropbox app folder.

```js
import * as IDB from "idb-keyval";

import { computed, signal } from "~/common/signal.js";
import { BroadcastedOutputElement, outputManager } from "../../common.js";
import { defineElement } from "~/common/element.js";
import { generatePKCEPair } from "~/components/input/dropbox/common.js";
import { APP_KEY, PKCE_VERIFIER_KEY } from "./constants.js";

const STORAGE_PREFIX = "diffuse/output/bytes/dropbox";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {OutputElement, OutputManager} from "@specs/components/output/types.d.ts"
 * @import {DropboxOutputElement, DropboxOutputWorkerActions} from "@specs/components/output/bytes/dropbox/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Stores user-data (tracks, playlists, settings, facets) as raw bytes in
 * the Dropbox app folder. Uses the authorization-code-with-PKCE OAuth flow
 * to obtain a long-lived refresh token, which automatically renews the
 * short-lived access token (~4 h) via the shared `getAccessToken` helper.
 *
 * @implements {OutputElement<Uint8Array | undefined>}
 * @implements {DropboxOutputElement}
 */
class DropboxOutput extends BroadcastedOutputElement {
  static NAME = "diffuse/output/bytes/dropbox";
  static WORKER_URL = "components/output/bytes/dropbox/worker.js";

  #manager;

  constructor() {
    super();

    /** @type {ProxiedActions<DropboxOutputWorkerActions>} */
    this.proxy = this.workerProxy();

    /** @type {OutputManager<Uint8Array | undefined>} */
    this.#manager = outputManager({
      collaborations: {
        empty: () => undefined,
        get: () => this.#get("collaborations"),
        put: (data) => this.#put("collaborations", data),
      },
      facets: {
        empty: () => undefined,
        get: () => this.#get("facets"),
        put: (data) => this.#put("facets", data),
      },
      init: () => this.whenConnected(),
      playlistItems: {
        empty: () => undefined,
        get: () => this.#get("playlistItems"),
        put: (data) => this.#put("playlistItems", data),
      },
      settings: {
        empty: () => undefined,
        get: () => this.#get("settings"),
        put: (data) => this.#put("settings", data),
      },
      tracks: {
        empty: () => undefined,
        get: () => this.#get("tracks"),
        put: (data) => this.#put("tracks", data),
      },
    });

    this.collaborations = this.#manager.collaborations;
    this.facets = this.#manager.facets;
    this.playlistItems = this.#manager.playlistItems;
    this.settings = this.#manager.settings;
    this.tracks = this.#manager.tracks;
  }

  // SIGNALS

  #isOnline = signal(navigator.onLine);

  // STATE

  ready = computed(() => {
    return this.#refreshToken.value !== undefined && this.#isOnline.value;
  });

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    this.replicateSavedData(this.#manager);

    super.connectedCallback();

    /** @type {string | undefined} */
    const stored = await IDB.get(`${STORAGE_PREFIX}/refresh_token`);
    if (stored) this.#refreshToken.value = stored;

    globalThis.addEventListener("online", this.#online);
    globalThis.addEventListener("offline", this.#offline);
  }

  /** @override */
  disconnectedCallback() {
    globalThis.removeEventListener("online", this.#online);
    globalThis.removeEventListener("offline", this.#offline);
  }

  #offline = () => this.#isOnline.set(false);
  #online = () => this.#isOnline.set(true);

  // REFRESH TOKEN

  #refreshToken = signal(/** @type {string | undefined} */ (undefined));

  refreshToken = this.#refreshToken.get;

  /** @returns {Promise<string | undefined>} */
  async getRefreshToken() {
    if (!this.#refreshToken.value) {
      /** @type {string | undefined} */
      const stored = await IDB.get(`${STORAGE_PREFIX}/refresh_token`);
      if (stored) this.#refreshToken.value = stored;
      return stored;
    }

    return this.#refreshToken.value;
  }

  /**
   * @param {string} token
   */
  async setRefreshToken(token) {
    this.#refreshToken.value = token;
    await IDB.set(`${STORAGE_PREFIX}/refresh_token`, token);
  }

  async unsetRefreshToken() {
    this.#refreshToken.value = undefined;
    await IDB.del(`${STORAGE_PREFIX}/refresh_token`);
  }

  // AUTHORIZE

  /**
   * Starts the authorization-code-with-PKCE OAuth flow for the output
   * Dropbox app. The verifier is stored under a separate key so the
   * callback page can distinguish it from the input/upload flow.
   */
  async authorize() {
    localStorage.setItem(
      "oauth/callback/redirect_path",
      location.pathname + location.search,
    );

    const { verifier, challenge } = await generatePKCEPair();
    localStorage.setItem(PKCE_VERIFIER_KEY, verifier);

    const params = new URLSearchParams({
      response_type: "code",
      client_id: APP_KEY,
      redirect_uri: location.origin + "/oauth/callback/",
      token_access_type: "offline",
      code_challenge: challenge,
      code_challenge_method: "S256",
    });

    location.assign(`https://www.dropbox.com/oauth2/authorize?${params}`);
  }

  // GET & PUT

  /** @param {string} name */
  #get = async (name) => {
    const refreshToken = await this.getRefreshToken();
    if (!refreshToken) return undefined;
    return this.proxy.get({ refreshToken, name: this.#cat(name) });
  };

  /** @param {string} name; @param {any} data */
  #put = async (name, data) => {
    const refreshToken = await this.getRefreshToken();
    if (!refreshToken) return undefined;
    return this.proxy.put({ refreshToken, data, name: this.#cat(name) });
  };

  // 🛠️

  /** @param {string} name */
  #cat(name) {
    const ns = this.namespace;
    return `${ns?.length ? ns + "/" : ""}${name}`;
  }
}

export default DropboxOutput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = DropboxOutput;
export const NAME = "dob-dropbox";

defineElement(NAME, DropboxOutput);
```
### Raw / Firkin / Encrypted / Incremental Automerge

The complete Firkin userdata output: an append-only log of encrypted Automerge changes on a Firkin instance. Each save appends only the changes since the log last saw them (a whole document every 32 saves), entries are sealed per save, and per-device manifests are signed by the writer's session key.

```js
import { ApiError, bytesToHex, WebCryptoSigner } from "@tokono.ma/firkin";
import * as IDB from "idb-keyval";

import { computed, signal } from "~/common/signal.js";
import { BroadcastedOutputElement } from "../../../../common.js";
import { defineElement } from "~/common/element.js";
import { collectionSchema } from "~/common/self-describing.js";
import { getSessionClient } from "~/common/firkin/session.js";
import {
  HINT_DEBOUNCE_MS,
  channelName,
  openHintChannel,
} from "~/common/firkin/channel.js";
import { outputKey } from "~/common/firkin/output-key.js";

import {
  BULK_SAVE_THRESHOLD,
  COLLECTIONS,
  FIRST_READ_TIMEOUT_MS,
  IDB_ACTOR,
  IDB_DOCS,
  IDB_FLOORS,
  IDB_PACKS,
  LOCAL_COMPACT_EVERY,
  NAMES_TTL_MS,
  NOT_CONNECTED,
  NOT_READY_GRACE_MS,
  PUSH_COALESCE_MS,
  SNAPSHOT_EVERY,
} from "./constants.js";
import { decryptLog, encryptEntry, frameEntries } from "./crypto.js";
import {
  applyIncremental,
  applyLog,
  changeDocument,
  changeDocumentBatched,
  changesSince,
  createDocument,
  deltaSince,
  encodeDocument,
  hasRecords,
  headsOf,
  loadDocument,
  recordsOf,
} from "./doc.js";
import { appendEntry, readEntries } from "./log.js";
import { verifySignature } from "./verify.js";

/**
 * @import { SignalReader } from "~/common/signal.d.ts";
 * @import { OutputElement } from "@specs/components/output/types.d.ts";
 * @import { CollectionName } from "~/common/self-describing.js";
 * @import { Heads } from "@automerge/automerge";
 * @import { Session } from "~/common/firkin/session.js";
 * @import { LogAuth } from "./log.js";
 * @import { Firkin } from "@tokono.ma/firkin";
 * @import { AutomergeDoc } from "./doc.js";
 */

/**
 * @typedef {Object} BulkActions
 * @property {(args: {
 *   bytes: Uint8Array;
 *   items: any[];
 *   schema?: string;
 *   pushHeads?: string[];
 *   snapshot?: boolean;
 * }) => Promise<{
 *   changed: boolean;
 *   deltas?: Uint8Array[];
 *   docBytes?: Uint8Array;
 *   pushBytes?: Uint8Array;
 *   heads?: string[];
 * }>} applyLargeChange
 */

/**
 * A push whose entry bytes were prepared off the main thread. It is only used
 * while the document and cursor still match what the worker saw.
 *
 * @typedef {Object} PreparedPush
 * @property {Uint8Array} bytes
 * @property {string[]} heads
 * @property {string} cursorHeads
 * @property {boolean} snapshot
 */

/** Yield to the event loop between applying the worker's deltas. */
const yieldToMain = () => new Promise((resolve) => setTimeout(resolve, 0));

/**
 * The userdata output: an **encrypted, incremental Automerge log on Firkin**,
 * in one component.
 *
 * This is deliberately one element rather than a chain of transformers. The
 * three layers are inseparable in practice — the log protocol decides what can
 * be replayed, the encryption framing decides how entries are split back up,
 * and the Automerge layer decides what is appendable — so keeping them in one
 * place removes the cross-component contracts (an `output-selector` chain, a
 * shared plaintext framing, a separately delivered key) that only ever had one
 * consumer.
 *
 * What it does, in order of the data flow:
 *
 * - **Collections** are Automerge documents (see `doc.js`): records live in a
 *   map keyed by `id`, so concurrent edits to different records merge.
 * - **Saves** append only the changes since the log last saw them; a whole
 *   document is appended every `SNAPSHOT_EVERY` saves so the log stays
 *   replayable after `keep` trims old entries.
 * - **Entries** are sealed with AES-GCM (see `crypto.js`): one entry per save,
 *   and the decrypted log is length-prefixed per entry so it can be replayed
 *   entry by entry.
 * - **The log** lives on Firkin (see `log.js`): per-device signed manifests
 *   over content-addressed blobs, with rollback floors, hints and trimming.
 * - **Replay** (see `doc.js`) tolerates interleaved writers and trimmed
 *   dependencies by applying entries one at a time.
 *
 * Local data lives in IndexedDB, so the UI is usable offline and the remote is
 * only read to merge in other devices' changes.
 *
 * @extends {BroadcastedOutputElement}
 */
class FirkinAutomergeOutput extends BroadcastedOutputElement {
  static NAME = "diffuse/output/raw/firkin/encrypted/incremental-automerge";
  static WORKER_URL =
    "components/output/raw/firkin/encrypted/incremental-automerge/worker.js";

  /** @type {import("~/common/worker.d.ts").ProxiedActions<BulkActions> | undefined} */
  #bulkWorker;

  /** @type {Map<string, PreparedPush>} */
  #preparedPushes = new Map();

  // SIGNALS

  #isOnline = signal(navigator.onLine);
  #connected = signal(false);

  /** Whether a connection check has finished (it may have found no session). */
  #connectionChecked = false;

  /** @type {Promise<void> | undefined} */
  #refreshing;

  /** Set when a check is requested while one is already in flight. */
  #refreshAgain = false;

  /** Loaded from local storage; collections stay `loading` until then. */
  #loaded = signal(false);

  /**
   * Bumped whenever a collection's document changes so its computed re-runs.
   * Per collection so saving settings doesn't make the UI re-read the tracks.
   *
   * @type {Map<string, import("~/common/signal.d.ts").Signal<number>>}
   */
  #versions = new Map(COLLECTIONS.map((name) => [name, signal(0)]));

  /**
   * Collections we have an answer for: either a local document with records, or
   * a completed read of the log. Until a collection is in here its state stays
   * `loading`, so the UI shows its loading state instead of flashing an empty
   * list while the first read is still in flight.
   *
   * @type {import("~/common/signal.d.ts").Signal<Set<string>>}
   */
  #ready = signal(new Set());

  // DOCUMENTS

  /** @type {Map<string, AutomergeDoc>} */
  #docs = new Map();

  /** Incremental local-cache deltas appended since the base document. */
  /** @type {Map<string, Uint8Array[]>} */
  #chunks = new Map();

  /** Heads covered by the local cache (base + chunks). @type {Map<string, Heads>} */
  #persistedHeads = new Map();

  /** Collections with a full base document in IndexedDB. */
  #hasBase = new Set();

  /** @type {Map<string, { heads?: Heads; pushes: number }>} */
  #cursors = new Map();

  /**
   * Fingerprint of the log last applied per collection, so a reload that yields
   * the same bytes isn't replayed.
   *
   * @type {Map<string, string>}
   */
  #applied = new Map();

  /** Collections whose in-memory document is known to be on disk. */
  #persisted = new Set();

  /** Collections whose last push failed (offline, signed out, …). */
  #dirty = new Set();

  /** @type {Promise<void> | undefined} */
  #pulling;

  /** @type {Promise<void> | undefined} */
  #initialising;

  /**
   * Serializes document mutations. Without this a pull that started before a
   * save would overwrite the document the save just wrote.
   */
  #queue = Promise.resolve();

  /** @type {Promise<void>} */
  #pushQueue = Promise.resolve();

  /** Pending coalesced pushes, one timer per collection. */
  #pushTimers = new Map();

  // TRANSPORT

  /** @type {Map<string, Uint8Array>} */
  #packs = new Map();

  /** @type {Map<string, Promise<unknown>>} */
  #writes = new Map();

  /** @type {ReturnType<typeof openHintChannel> | undefined} */
  #channel;

  /** @type {Map<string, ReturnType<typeof setTimeout>>} */
  #hints = new Map();

  /**
   * One namespace listing, shared by the collections that read from it.
   *
   * All five collections of an output live in the same namespace, so a pull
   * would otherwise ask the same question five times.
   *
   * @type {Map<string, { at: number; names: Promise<Record<string, string> | null> }>}
   */
  #listings = new Map();

  /** @type {{ publicKey: Uint8Array; auth: LogAuth } | undefined} */
  #authCache;

  /** @type {Map<string, Map<string, number>>} */
  #floorCache = new Map();

  constructor() {
    super();

    for (const name of COLLECTIONS) {
      this.#docs.set(name, createDocument());
    }

    this.collaborations = this.#entry("collaborations");
    this.facets = this.#entry("facets");
    this.playlistItems = this.#entry("playlistItems");
    this.settings = this.#entry("settings");
    this.tracks = this.#entry("tracks");

    // Ready means "usable": with no session or no encryption key the output can
    // report an empty library, and the configurator mirrors whatever a selected
    // output reports into the local store — so an unusable output must not
    // claim to be ready, or it would wipe that mirror.
    this.ready = computed(() =>
      this.#loaded.value &&
      this.#connected.value &&
      this.#isOnline.value &&
      outputKey() !== undefined
    );

    // The session and the output encryption key are stored asynchronously, and
    // sign-in can happen after this element connected (the connect facet adds
    // the option first). Re-check when the key appears, or `ready` stays false
    // until an unrelated online event and the configurator falls back.
    this.effect(() => {
      if (outputKey() === undefined) return;

      void this.#refreshConnected();
    });

    // Pull once the output is usable (signed in, key present, online). Retries
    // whenever that flips back to true after a failure.
    this.effect(() => {
      if (!this.ready()) {
        // Nothing can be read yet. Don't leave the UI spinning if that never
        // changes (no session, no encryption key).
        this.#scheduleSettle();
        return;
      }

      clearTimeout(this.#settle);
      this.#settle = undefined;

      // A save made before the output was usable (e.g. an edit made before the
      // encryption key arrived), a push that failed, or one interrupted by a
      // reload only reached the local cache. Now that it can write, push it.
      void this.#pushUnpushed();

      void this.#pull();
    });
  }

  // ENTRIES

  /**
   * @param {CollectionName} name
   */
  #entry(name) {
    return {
      collection: computed(() => {
        this.#versions.get(name)?.get();
        if (!this.#ready.value.has(name)) return { state: "loading" };

        return {
          state: "loaded",
          data: recordsOf(this.#docs.get(name) ?? createDocument()),
        };
      }),
      reload: () => this.#pullCollection(name),
      save: (/** @type {any[]} */ items) => this.#save(name, items),
    };
  }

  // LIFECYCLE

  /** @override */
  connectedCallback() {
    super.connectedCallback();

    globalThis.addEventListener("online", this.#online);
    globalThis.addEventListener("offline", this.#offline);
    globalThis.addEventListener("pagehide", this.#pageHide);
    document.addEventListener("visibilitychange", this.#visibilityChange);
    globalThis.addEventListener("pageshow", this.#pageShow);

    void this.#initialise();
    void this.#refreshConnected();
  }

  /** @override */
  disconnectedCallback() {
    globalThis.removeEventListener("online", this.#online);
    globalThis.removeEventListener("offline", this.#offline);
    globalThis.removeEventListener("pagehide", this.#pageHide);
    document.removeEventListener("visibilitychange", this.#visibilityChange);
    globalThis.removeEventListener("pageshow", this.#pageShow);

    this.#flushPushes();
    this.#closeChannel();

    super.disconnectedCallback();
  }

  #offline = () => {
    this.#isOnline.set(false);
    this.#closeChannel();
  };

  #online = () => {
    this.#isOnline.set(true);
    void this.#refreshConnected();
  };

  /**
   * A page switch on mobile suspends the page (and usually the hint socket)
   * without unloading it. Anything written while hidden would otherwise wait
   * for the next hint or a reload, so re-read the log when it is shown again.
   */
  #visibilityChange = () => {
    if (document.visibilityState !== "visible") {
      // Don't leave a coalesced push waiting on a timer the browser may never
      // run once the page is in the background.
      this.#flushPushes();
      return;
    }

    this.#catchUp();
  };

  /** The page is going away: send anything still coalescing. */
  #pageHide = () => this.#flushPushes();

  /** A page restored from the back/forward cache skipped its normal load. */
  #pageShow = (/** @type {PageTransitionEvent} */ event) => {
    if (!event.persisted) return;

    this.#catchUp();
  };

  /**
   * Re-read the log after the page was away or the connection was
   * re-established. Hints are best effort, so a missed hint is recovered here
   * rather than waiting for the next write or a reload.
   */
  #catchUp() {
    if (!this.isConnected) return;

    // The session check may be what is stale. A successful one flips `ready`,
    // whose effect pulls.
    if (!this.ready()) {
      void this.#refreshConnected();
      return;
    }

    this.#listings.clear();
    void this.#pull();
  }

  #refreshConnected() {
    // A call can arrive while a check is in flight (the key and the session
    // land separately). Queue one more pass instead of dropping it: the
    // in-flight check may have started before the session was stored.
    if (this.#refreshing) {
      this.#refreshAgain = true;
      return this.#refreshing;
    }

    this.#connectionChecked = false;

    this.#refreshing = (async () => {
      do {
        this.#refreshAgain = false;
        await this.#checkConnected();
      } while (this.#refreshAgain);
    })().finally(() => {
      this.#refreshing = undefined;
      this.#connectionChecked = true;

      // The check may have concluded that nothing is usable. The ready effect
      // won't re-run if no signal changed, so settle this state explicitly
      // (after the grace period) instead of leaving the UI loading forever.
      if (this.isConnected && !this.ready()) this.#scheduleSettle();
    });

    return this.#refreshing;
  }

  async #checkConnected() {
    try {
      const client = await getSessionClient();
      if (!client) {
        this.#connected.value = false;
        return;
      }

      // A stored session is enough to start the local-first path. Validate it
      // in the background: a slow registry round trip must not hold the page's
      // first render (or the first pull) hostage. The pull surfaces real
      // connectivity errors on its own.
      this.#connected.value = true;
      this.#ensureChannel(client);

      try {
        // A cheap authenticated read proves the session (and account) works.
        await client.rb.registryList();
      } catch (err) {
        // Unauthorized/forbidden means the account is unregistered or the
        // delegation was revoked; other errors are treated optimistically.
        if (
          err instanceof ApiError && (err.status === 401 || err.status === 403)
        ) {
          this.#connected.value = false;
        }
      }
    } catch {
      this.#connected.value = false;
    }
  }

  // HINTS

  /**
   * Subscribe to change hints from other devices.
   *
   * Other devices' writes are only visible after a read, so a hint just says
   * which collection to re-read; it never carries data. Without a channel the
   * output still works, it is only less immediate.
   *
   * @param {{ session: Session; rb: Firkin }} client
   */
  #ensureChannel(client) {
    if (this.#channel) return;

    const name = channelName(this.#namespace);
    const device = this.#auth(client.session).device;

    this.#channel = openHintChannel({
      device,
      url: async () => {
        const current = await getSessionClient();
        if (!current) return undefined;

        return await current.rb.channelUrl(name);
      },
      onHint: (collection) => this.#refreshCollection(collection),
      onReconnect: () => this.#catchUp(),
    });
  }

  #closeChannel() {
    this.#channel?.close();
    this.#channel = undefined;

    for (const timer of this.#hints.values()) clearTimeout(timer);
    this.#hints.clear();
  }

  /**
   * Re-read one collection, coalescing a burst of hints into one read.
   *
   * @param {string} collection
   */
  #refreshCollection(collection) {
    if (!COLLECTIONS.includes(/** @type {any} */ (collection))) return;

    const pending = this.#hints.get(collection);
    if (pending !== undefined) clearTimeout(pending);

    this.#hints.set(
      collection,
      setTimeout(() => {
        this.#hints.delete(collection);

        // Another device wrote something: don't trust the cached listing.
        this.#listings.clear();

        void this.#pullCollection(/** @type {CollectionName} */ (collection))
          .catch((err) => {
            console.warn(
              `Could not refresh '${collection}' after a hint:`,
              err,
            );
          });
      }, HINT_DEBOUNCE_MS),
    );
  }

  // CONFIGURATION

  get #namespace() {
    return this.namespace ?? "default";
  }

  /**
   * How many entries to retain per log. Unset (or invalid) keeps everything.
   *
   * @returns {number | undefined}
   */
  get keep() {
    const raw = this.getAttribute("keep");
    if (!raw) return undefined;

    const parsed = Number(raw);

    return Number.isInteger(parsed) && parsed > 0 ? parsed : undefined;
  }

  // LOCAL

  /** @param {CollectionName} name */
  #docKey(name) {
    return `${IDB_DOCS}/${this.#namespace}/${name}`;
  }

  /** @param {CollectionName} name */
  #chunksKey(name) {
    return `${this.#docKey(name)}/changes`;
  }

  /**
   * Persist a collection's document.
   *
   * The first write (and periodic compaction) stores the whole document. Other
   * writes append the delta since the previous save, so a save doesn't serialise
   * the entire library. Loading replays the base and then the chunks.
   *
   * @param {CollectionName} name
   * @param {AutomergeDoc} doc
   * @param {{ compact?: boolean; bytes?: Uint8Array }} [options] - `compact`
   *   rewrites the base instead of appending a delta (a bulk save's delta is as
   *   large as the whole collection); `bytes` supplies the already-encoded base
   *   (prepared by the worker).
   */
  async #persist(name, doc, options = {}) {
    const heads = headsOf(doc);
    const previous = this.#persistedHeads.get(name);

    if (options.compact) {
      await IDB.set(
        this.#docKey(name),
        options.bytes ?? encodeDocument(doc),
      );

      this.#hasBase.add(name);
      this.#persistedHeads.set(name, heads);
      this.#chunks.set(name, []);

      try {
        await IDB.del(this.#chunksKey(name));
      } catch (err) {
        console.warn(`Could not clear the '${name}' local changes:`, err);
      }

      return;
    }

    if (!this.#hasBase.has(name) || previous === undefined) {
      await IDB.set(this.#docKey(name), encodeDocument(doc));

      this.#hasBase.add(name);
      this.#persistedHeads.set(name, heads);
      this.#chunks.set(name, []);

      try {
        await IDB.del(this.#chunksKey(name));
      } catch (err) {
        console.warn(`Could not clear the '${name}' local changes:`, err);
      }

      return;
    }

    if (heads.join(";") === previous.join(";")) return;

    const delta = deltaSince(doc, previous);

    // The document no longer shares the cached base's history (for example an
    // empty local document adopted a remote root). A delta chunk couldn't be
    // replayed, so replace the base instead.
    if (delta === undefined) {
      await IDB.set(this.#docKey(name), encodeDocument(doc));

      this.#persistedHeads.set(name, heads);
      this.#chunks.set(name, []);

      try {
        await IDB.del(this.#chunksKey(name));
      } catch (err) {
        console.warn(`Could not clear the '${name}' local changes:`, err);
      }

      return;
    }

    if (delta.length === 0) {
      this.#persistedHeads.set(name, heads);
      return;
    }

    const chunks = [...(this.#chunks.get(name) ?? []), delta];

    if (chunks.length >= LOCAL_COMPACT_EVERY) {
      await IDB.set(this.#docKey(name), encodeDocument(doc));

      this.#persistedHeads.set(name, heads);
      this.#chunks.set(name, []);

      try {
        await IDB.del(this.#chunksKey(name));
      } catch (err) {
        console.warn(`Could not clear the '${name}' local changes:`, err);
      }

      return;
    }

    await IDB.set(this.#chunksKey(name), chunks);

    this.#chunks.set(name, chunks);
    this.#persistedHeads.set(name, heads);
  }

  /** @param {CollectionName} name */
  async #resetChunks(name) {
    this.#chunks.delete(name);
    this.#hasBase.delete(name);

    try {
      await IDB.del(this.#chunksKey(name));
    } catch (err) {
      console.warn(`Could not reset the '${name}' local changes:`, err);
    }
  }

  /**
   * Load the cached documents. Runs once; subsequent calls await the same work.
   */
  #initialise() {
    this.#initialising ??= (async () => {
      try {
        await Promise.all(COLLECTIONS.map(async (name) => {
          try {
            const stored = await IDB.get(this.#docKey(name));
            let doc = stored instanceof Uint8Array
              ? loadDocument(stored)
              : undefined;

            if (doc) {
              this.#hasBase.add(name);

              // Replay the deltas appended since the base was written.
              try {
                const storedChunks = await IDB.get(this.#chunksKey(name));
                const chunks = Array.isArray(storedChunks)
                  ? storedChunks.filter((chunk) => chunk instanceof Uint8Array)
                  : [];
                /** @type {Uint8Array[]} */
                const applied = [];

                for (const chunk of chunks) {
                  try {
                    doc = applyIncremental(doc, chunk);
                    applied.push(chunk);
                  } catch (err) {
                    console.warn(
                      `Could not apply a cached '${name}' change:`,
                      err,
                    );
                    break;
                  }
                }

                this.#chunks.set(name, applied);
              } catch (err) {
                console.warn(`Could not read the '${name}' local changes:`, err);
              }

              this.#docs.set(name, doc);
              this.#persisted.add(name);
              this.#persistedHeads.set(name, headsOf(doc));

              // Local-first: a collection we have synced before can be shown
              // straight away — even when it is empty, because then "empty" is
              // the truth rather than "unknown".
              const cursor = await this.#cursor(name);
              if (hasRecords(doc) || cursor.heads !== undefined) {
                this.#markReady(name);
              }
            } else {
              // Nothing cached: start from an empty document of our own, under
              // this device's actor so concurrent writers never share a
              // sequence number.
              const empty = createDocument(await this.#actor());

              this.#docs.set(name, empty);
              this.#persisted.delete(name);
              this.#persistedHeads.set(name, headsOf(empty));

              await this.#resetCursor(name);
              await this.#resetAppliedLog(name);
              await this.#resetChunks(name);
            }
          } catch (err) {
            console.warn(`Could not read the local '${name}' document:`, err);
          }
        }));
      } finally {
        // Whatever happened above, the interface must stop loading.
        this.#loaded.value = true;
        this.#bumpAll();
      }
    })();

    return this.#initialising;
  }

  /**
   * @param {CollectionName} name
   * @param {any[]} items
   */
  async #save(name, items) {
    await this.#initialise();

    return await this.#serialize(async () => {
      const current = this.#docs.get(name) ?? createDocument();
      const schema = collectionSchema(name);
      const bulk = items.length >= BULK_SAVE_THRESHOLD;

      let doc;
      let changed;
      /** @type {Uint8Array | undefined} */
      let docBytes;
      /** @type {PreparedPush | undefined} */
      let prepared;

      if (bulk) {
        try {
          const cursor = await this.#cursor(name);
          const snapshot = cursor.pushes > 0 &&
            cursor.pushes % SNAPSHOT_EVERY === 0;

          const result = await this.#applyLargeChange(
            current,
            items,
            schema,
            cursor.heads,
            snapshot,
          );

          if (!result.changed) return;

          doc = result.doc;
          changed = true;
          docBytes = result.docBytes;
          prepared = result.pushBytes && result.heads
            ? {
              bytes: result.pushBytes,
              heads: result.heads,
              cursorHeads: (cursor.heads ?? []).join(";"),
              snapshot,
            }
            : undefined;
        } catch (err) {
          console.warn(
            "Could not apply the save in a worker; falling back:",
            err,
          );

          ({ doc, changed } = await changeDocumentBatched(
            current,
            items,
            { schema },
          ));
        }
      } else {
        ({ doc, changed } = changeDocument(current, items, { schema }));
      }

      if (!changed) return;

      this.#docs.set(name, doc);
      this.#bump(name);

      this.#persisted.delete(name);

      try {
        // A bulk save's delta would be as large as the collection; rewrite the
        // base instead of appending it as a chunk.
        await this.#persist(name, doc, { compact: bulk, bytes: docBytes });
        this.#persisted.add(name);
      } catch (err) {
        console.warn(`Could not cache the '${name}' document locally:`, err);
      }

      this.#schedulePush(name, prepared);
    });
  }

  #bulkProxy() {
    this.#bulkWorker ??= this.workerProxy();
    return this.#bulkWorker;
  }

  /**
   * Apply a large save in the worker, which returns one delta per batch. The
   * deltas are applied here with yields, so neither the Automerge change nor
   * the resulting document update blocks the page. The worker also prepares
   * the push entry and the compact base bytes.
   *
   * @param {AutomergeDoc} current
   * @param {any[]} items
   * @param {string} schema
   * @param {Heads | undefined} pushHeads
   * @param {boolean} snapshot
   * @returns {Promise<{
   *   doc: AutomergeDoc;
   *   changed: boolean;
   *   docBytes?: Uint8Array;
   *   pushBytes?: Uint8Array;
   *   heads?: string[];
   * }>}
   */
  async #applyLargeChange(current, items, schema, pushHeads, snapshot) {
    const result = await this.#bulkProxy().applyLargeChange({
      bytes: encodeDocument(current),
      items,
      schema,
      pushHeads,
      snapshot,
    });

    if (!result.changed) return { doc: current, changed: false };

    let doc = current;

    for (const delta of result.deltas ?? []) {
      doc = applyIncremental(doc, delta);
      await yieldToMain();
    }

    return {
      doc,
      changed: true,
      docBytes: result.docBytes,
      pushBytes: result.pushBytes,
      heads: result.heads,
    };
  }

  /**
   * Queue a push, off the document queue: a slow or dead server must not block
   * reads, saves or other collections.
   *
   * @param {CollectionName} name
   * @param {AutomergeDoc} doc
   * @param {PreparedPush} [prepared]
   */
  #enqueuePush(name, doc, prepared) {
    const run = () => this.#push(name, doc, prepared);

    this.#pushQueue = this.#pushQueue.then(run, run).then(
      () => {},
      () => {},
    );
  }

  /**
   * Coalesce a save's push. A burst of saves (a batch import, a metadata pass)
   * becomes one append of the latest document instead of one manifest rewrite
   * per save. Appends triggered by a pull stay immediate.
   *
   * @param {CollectionName} name
   * @param {PreparedPush} [prepared]
   */
  #schedulePush(name, prepared) {
    if (prepared) this.#preparedPushes.set(name, prepared);

    const pending = this.#pushTimers.get(name);
    if (pending !== undefined) clearTimeout(pending);

    this.#pushTimers.set(
      name,
      setTimeout(() => {
        this.#pushTimers.delete(name);

        const doc = this.#docs.get(name);
        const prepared = this.#preparedPushes.get(name);
        this.#preparedPushes.delete(name);

        if (doc) this.#enqueuePush(name, doc, prepared);
      }, PUSH_COALESCE_MS),
    );
  }

  /** Send every coalesced push now (before the page goes away). */
  #flushPushes() {
    for (const [name, timer] of this.#pushTimers) {
      clearTimeout(timer);

      const doc = this.#docs.get(name);
      const prepared = this.#preparedPushes.get(name);

      if (doc) this.#enqueuePush(name, doc, prepared);
    }

    this.#pushTimers.clear();
    this.#preparedPushes.clear();
  }

  /** @type {ReturnType<typeof setTimeout> | undefined} */
  #settle;

  /**
   * Give up waiting for an output that can't read, so the UI shows an empty
   * library instead of an endless loader.
   */
  #scheduleSettle() {
    if (this.#settle !== undefined) return;

    this.#settle = setTimeout(() => {
      this.#settle = undefined;

      if (this.ready()) return;

      // `ready` is false for different reasons, and "sign in" is no help to a
      // user who already is: name the part that is actually missing.
      /** @type {string} */
      let state;

      if (!this.#isOnline.value) {
        state = "offline — it reads again once the connection is back";
      } else if (!this.#connected.value) {
        // A check may simply still be in flight (a large local cache is loaded
        // in parallel); don't report the user as signed out before it answers.
        if (!this.#connectionChecked) return;

        state = "not signed in on this browser; sign in on Connect → Firkin";
      } else if (outputKey() === undefined) {
        state = "signed in, but this browser has no output encryption key " +
          "(it is derived from your passkey at sign-in) — sign in again on " +
          "this device to derive it";
      } else {
        // Everything is present: a large local cache is simply still being
        // read. It resolves on its own; don't claim the key is missing.
        return;
      }

      console.warn(
        `Firkin output: ${state}. Showing an empty library until then.`,
      );

      for (const name of COLLECTIONS) this.#markReady(name);
    }, NOT_READY_GRACE_MS);
  }

  /**
   * Record that a collection has an answer to show.
   *
   * @param {CollectionName} name
   */
  #markReady(name) {
    if (this.#ready.value.has(name)) return;

    const next = new Set(this.#ready.value);
    next.add(name);
    this.#ready.value = next;
  }

  /** @param {CollectionName} name */
  #bump(name) {
    const version = this.#versions.get(name);
    if (version) version.value++;
  }

  #bumpAll() {
    for (const version of this.#versions.values()) version.value++;
  }

  /**
   * @template T
   * @param {() => Promise<T>} fn
   * @returns {Promise<T>}
   */
  #serialize(fn) {
    const run = this.#queue.then(fn, fn);
    this.#queue = run.then(() => {}, () => {});

    return run;
  }

  /**
   * The log applied to the local document: its ordered pack CIDs and the heads
   * those packs produced. Written only after a complete read, so a missing pack
   * or manifest is retried instead of being mistaken for "nothing changed".
   *
   * @param {CollectionName} name
   */
  #appliedLogKey(name) {
    return `${IDB_DOCS}/${this.#namespace}/${name}/applied`;
  }

  /**
   * @param {CollectionName} name
   * @returns {Promise<{ packs: string; heads: string } | undefined>}
   */
  async #appliedLog(name) {
    try {
      const stored = await IDB.get(this.#appliedLogKey(name));

      if (
        stored && typeof stored === "object" &&
        typeof stored.packs === "string" &&
        typeof stored.heads === "string"
      ) {
        return { packs: stored.packs, heads: stored.heads };
      }
    } catch (err) {
      console.warn(`Could not read the '${name}' applied log:`, err);
    }

    return undefined;
  }

  /**
   * @param {CollectionName} name
   * @param {string} packs - `;`-joined ordered pack CIDs.
   * @param {string} heads - The document heads those packs produced.
   */
  async #setAppliedLog(name, packs, heads) {
    try {
      await IDB.set(this.#appliedLogKey(name), { packs, heads });
    } catch (err) {
      console.warn(`Could not persist the '${name}' applied log:`, err);
    }
  }

  /** @param {CollectionName} name */
  async #resetAppliedLog(name) {
    try {
      await IDB.del(this.#appliedLogKey(name));
    } catch (err) {
      console.warn(`Could not reset the '${name}' applied log:`, err);
    }
  }

  // REMOTE

  /** @param {CollectionName} name */
  #cursorKey(name) {
    return `${IDB_DOCS}/${this.#namespace}/${name}/cursor`;
  }

  /**
   * How far this device has pushed a collection: the heads the log already has,
   * and how many pushes happened since the document was started.
   *
   * @param {CollectionName} name
   * @returns {Promise<{ heads?: Heads; pushes: number }>}
   */
  async #cursor(name) {
    const cached = this.#cursors.get(name);
    if (cached) return cached;

    /** @type {{ heads?: Heads; pushes: number }} */
    const cursor = { pushes: 0 };

    try {
      const stored = await IDB.get(this.#cursorKey(name));
      if (stored && typeof stored === "object") {
        if (Array.isArray(stored.heads)) cursor.heads = stored.heads;
        if (Number.isInteger(stored.pushes)) cursor.pushes = stored.pushes;
      }
    } catch (err) {
      console.warn(`Could not read the '${name}' push cursor:`, err);
    }

    this.#cursors.set(name, cursor);

    return cursor;
  }

  /**
   * @param {CollectionName} name
   * @param {{ heads?: Heads; pushes: number }} cursor
   */
  async #setCursor(name, cursor) {
    this.#cursors.set(name, cursor);

    try {
      await IDB.set(this.#cursorKey(name), cursor);
    } catch (err) {
      console.warn(`Could not persist the '${name}' push cursor:`, err);
    }
  }

  /** @param {CollectionName} name */
  async #resetCursor(name) {
    const cursor = { pushes: 0 };
    this.#cursors.set(name, cursor);

    try {
      await IDB.del(this.#cursorKey(name));
    } catch (err) {
      console.warn(`Could not reset the '${name}' push cursor:`, err);
    }
  }

  /** @type {Promise<string> | undefined} */
  #actorPromise;

  /**
   * This device's Automerge actor id, persisted so reloads keep writing under
   * the same identity.
   *
   * @returns {Promise<string>}
   */
  #actor() {
    this.#actorPromise ??= (async () => {
      const key = `${IDB_ACTOR}/${this.#namespace}`;

      const created = crypto.randomUUID().replace(/-/g, "");

      try {
        const stored = await IDB.get(key);
        if (typeof stored === "string" && /^[0-9a-f]{32}$/.test(stored)) {
          return stored;
        }

        await IDB.set(key, created);
      } catch (err) {
        console.warn("Could not persist the Automerge actor id:", err);
      }

      return created;
    })();

    return this.#actorPromise;
  }

  /**
   * Whether the local document has changes the log hasn't acknowledged.
   *
   * The cursor holds the heads of the last successful push (and the heads a
   * completed read proved the log has), so anything newer is local-only: a
   * save whose push failed, or one interrupted before its queued push ran.
   *
   * @param {CollectionName} name
   * @param {AutomergeDoc} doc
   */
  async #hasUnpushed(name, doc) {
    const cursor = await this.#cursor(name);

    return headsOf(doc).join(";") !== (cursor.heads ?? []).join(";");
  }

  /**
   * Push every collection whose local document is ahead of the log.
   *
   * Saves are written locally first and pushed from memory, so closing the page
   * (or a tab that navigates away) before the queued push runs would otherwise
   * leave the change local-only until the next save of that collection. Checking
   * the persisted cursor against the loaded document on startup is what makes
   * an interrupted upload resume.
   */
  async #pushUnpushed() {
    await this.#initialise();

    for (const name of COLLECTIONS) {
      const doc = this.#docs.get(name);
      if (!doc) continue;
      if (!(await this.#hasUnpushed(name, doc))) continue;

      this.#enqueuePush(name, doc);
    }
  }

  /**
   * Push one document to the log.
   *
   * The first push of a session is a delta when we know what the log has (see
   * the cursor advance after a pull); otherwise `changesSince` returns a whole
   * document anyway.
   *
   * @param {CollectionName} name
   * @param {AutomergeDoc} doc
   * @param {PreparedPush} [prepared]
   */
  async #push(name, doc, prepared) {
    // Only the group leader writes; other tabs read their changes back from the
    // log like any other device.
    if (!(await this.isLeader())) return;

    // Not writable yet: offline, no session, or the output key is not loaded on
    // this browser. The save is already in the local cache, and marking the
    // collection dirty is what makes the ready effect push it later — trying
    // the write here would only log an error for work that is safely stored.
    if (!this.ready()) {
      this.#dirty.add(name);
      return;
    }

    const cursor = await this.#cursor(name);
    const snapshot = cursor.pushes > 0 && cursor.pushes % SNAPSHOT_EVERY === 0;
    const heads = headsOf(doc);

    // Use the worker's precomputed entry only while the document and cursor
    // still match what it saw; otherwise compute it here.
    /** @type {Uint8Array} */
    let bytes;

    if (
      prepared &&
      prepared.snapshot === snapshot &&
      prepared.cursorHeads === (cursor.heads ?? []).join(";") &&
      prepared.heads.join(";") === heads.join(";")
    ) {
      bytes = prepared.bytes;
    } else {
      bytes = snapshot ? encodeDocument(doc) : changesSince(doc, cursor.heads);
    }

    if (bytes.length === 0) return;

    try {
      await this.#append(name, bytes);
    } catch (err) {
      this.#dirty.add(name);
      console.warn(`Could not push the '${name}' changes:`, err);
      return;
    }

    this.#dirty.delete(name);
    await this.#setCursor(name, {
      heads,
      pushes: cursor.pushes + 1,
    });
  }

  /**
   * Append one plaintext entry to the log, sealing it first.
   *
   * @param {CollectionName} name
   * @param {Uint8Array} entry
   * @returns {Promise<void>}
   */
  #append(name, entry) {
    const run = async () => {
      const client = await getSessionClient();
      if (!client) throw new Error(NOT_CONNECTED);

      const key = outputKey();
      if (!key) throw new Error("The output encryption key is not loaded");
      if (!entry || entry.length === 0) return;

      const sealed = await encryptEntry(key, entry);

      const { cid } = await appendEntry(
        client.rb,
        this.#namespace,
        name,
        sealed,
        {
          auth: this.#auth(client.session),
          floors: await this.#floors(name),
          keep: this.keep,
        },
      );

      this.#packs.set(cid, sealed);

      try {
        await IDB.set(`${IDB_PACKS}/${cid}`, sealed);
      } catch (err) {
        console.warn("Could not cache a Firkin entry:", err);
      }

      // Our own write changes the namespace listing.
      this.#listings.clear();

      // Best effort: the entry is already committed, so a lost hint only
      // delays other devices.
      this.#channel?.send(name);
    };

    // Serialize appends per log so concurrent saves can't rewrite the same
    // manifest from a stale read.
    const previous = this.#writes.get(name) ?? Promise.resolve();
    const written = previous.then(run, run);
    this.#writes.set(name, written.then(() => {}, () => {}));

    return written;
  }

  /**
   * Read and decrypt one collection's log, framed entry by entry.
   *
   * @param {CollectionName} name
   * @param {AutomergeDoc} current
   * @returns {Promise<{ data: Uint8Array | undefined; packs: string; unchanged: boolean; complete: boolean; incremental: boolean }>}
   */
  async #readLog(name, current) {
    const client = await getSessionClient();
    if (!client) {
      return {
        data: undefined,
        packs: "",
        unchanged: false,
        complete: false,
        incremental: false,
      };
    }

    const entries = await this.#entries(client, name);
    const packs = entries.map((entry) => entry.cid).join(";");
    const applied = entries.length > 0 ? await this.#appliedLog(name) : undefined;

    // Content-addressed change detection: the ordered pack CIDs are the log's
    // identity, and the stored heads prove the local document still has exactly
    // the result of applying them. Nothing was appended, so skip the fetch,
    // decrypt and replay entirely.
    if (entries.length > 0) {
      if (
        applied?.packs === packs &&
        applied.heads === headsOf(current).join(";") &&
        // The cursor must agree too, or a crash between recording the log and
        // the push cursor would make this skip hide a pending push.
        !(await this.#hasUnpushed(name, current))
      ) {
        return {
          data: undefined,
          packs,
          unchanged: true,
          complete: true,
          incremental: false,
        };
      }
    }

    if (entries.length === 0) {
      return {
        data: undefined,
        packs,
        unchanged: false,
        complete: false,
        incremental: false,
      };
    }

    // The stored log is a prefix of the remote one: another writer appended,
    // which is the usual case. Fetch, decrypt and replay only the new entries
    // instead of the whole (up to `keep`) log.
    const appliedPacks = applied?.packs ? applied.packs.split(";") : [];
    const incremental = appliedPacks.length > 0 &&
      hasRecords(current) &&
      appliedPacks.every((cid, index) => entries[index]?.cid === cid);

    const pending = entries.slice(incremental ? appliedPacks.length : 0);

    const loaded = await Promise.all(
      pending.map((entry) => this.#readPack(client.rb, entry.cid)),
    );
    const present = /** @type {Uint8Array[]} */ (loaded.filter(Boolean));
    if (present.length === 0) {
      return {
        data: undefined,
        packs,
        unchanged: false,
        complete: false,
        incremental,
      };
    }

    const key = outputKey();
    if (!key) {
      return {
        data: undefined,
        packs,
        unchanged: false,
        complete: false,
        incremental,
      };
    }

    return {
      data: frameEntries(await decryptLog(key, concat(present))),
      packs,
      unchanged: false,
      complete: present.length === pending.length,
      incremental,
    };
  }

  /**
   * Pull every collection. Serialized: concurrent calls share one pass.
   */
  #pull() {
    this.#pulling ??= (async () => {
      await this.#initialise();

      // One slow collection must not leave the others loading. The network
      // reads run in parallel; the applies are serialized by `#serialize`.
      const settle = setTimeout(() => {
        for (const name of COLLECTIONS) this.#markReady(name);
      }, FIRST_READ_TIMEOUT_MS);

      try {
        await Promise.all(COLLECTIONS.map(async (name) => {
          try {
            await this.#pullCollection(name);
          } catch (err) {
            console.warn(`Could not pull the '${name}' document:`, err);
            this.#markReady(name);
          }
        }));
      } finally {
        // Deliberately not cleared: if a read resolved but the output still
        // reports `loading`, this is what finally settles the UI.
        this.#pulling = undefined;
      }
    })();

    return this.#pulling;
  }

  /**
   * Re-read one collection from the log and apply it.
   *
   * @param {CollectionName} name
   */
  async #pullCollection(name) {
    await this.#initialise();

    // A slow or unreachable output must not hold the first paint hostage: show
    // what we have (usually nothing) and fill it in when the read lands.
    const settle = setTimeout(() => {
      this.#markReady(name);
    }, FIRST_READ_TIMEOUT_MS);

    try {
      if (!this.ready()) return;

      // Read (network + decrypt) outside the document queue: a slow or dead
      // server must not block saves or the other collections' applies.
      const current = this.#docs.get(name) ?? createDocument();
      const log = await this.#readLog(name, current);

      await this.#serialize(async () => {
        if (!this.ready()) return;

        await this.#applyLocked(
          name,
          { state: "loaded", ...log },
          { bootstrap: true },
        );
      });
    } finally {
      clearTimeout(settle);
    }
  }

  /**
   * The shared body. Must be called inside `#serialize`.
   *
   * @param {CollectionName} name
   * @param {{ state: "loading" } | { state: "loaded"; data: Uint8Array | undefined; packs: string; unchanged: boolean; complete: boolean; incremental: boolean } | { state: "error" }} collection
   * @param {{ bootstrap?: boolean }} [options] - `bootstrap` publishes our local
   *   document when the log has nothing yet; only safe right after a read.
   */
  async #applyLocked(name, collection, options = {}) {
    // A loading collection is not an answer; leave it to the next read.
    if (collection.state !== "loaded") return;

    try {
      // The stored pack list says the local document already is this log.
      if (collection.unchanged) return;

      const bytes = collection.data;
      const current = this.#docs.get(name) ?? createDocument();

      // The incremental read only fetched the entries appended after the stored
      // log. If the document was emptied in the meantime (a save raced the
      // read), those deltas have no base to apply to; the next pull does a full
      // read instead.
      if (collection.incremental && !hasRecords(current)) return;

      const before = headsOf(current).join(";");

      // Capture this before applying: if the local document has changes the log
      // doesn't, the merged heads below must not be recorded as pushed.
      const unpushed = await this.#hasUnpushed(name, current);

      if (!(bytes instanceof Uint8Array)) {
        // Nothing remote yet: publish what we have so the namespace exists and
        // another device can start from it. An empty document counts — it makes
        // the first read cheaper and surfaces a failing push straight away.
        if (options.bootstrap) {
          this.#enqueuePush(name, current);
        }
        return;
      }

      // Replaying an unchanged log is wasted work; the output hands back the
      // same bytes, so remember what was applied.
      const fingerprint = fingerprintOf(bytes);
      if (fingerprint === this.#applied.get(name)) {
        if (
          this.#persisted.has(name) && !unpushed &&
          collection.complete && collection.packs.length > 0
        ) {
          await this.#setAppliedLog(name, collection.packs, before);
        }
        return;
      }

      const doc = applyLog(current, bytes, await this.#actor());

      this.#applied.set(name, fingerprint);
      this.#docs.set(name, doc);

      if (headsOf(doc).join(";") === before) {
        // The log added nothing. Still record it when the document (which is
        // already what the log describes) is on disk, so the next pull can skip
        // reading the log at all.
        if (
          this.#persisted.has(name) && !unpushed &&
          collection.complete && collection.packs.length > 0
        ) {
          await this.#setAppliedLog(name, collection.packs, before);
        }

        // Retry a failed push now that something proved the server is
        // reachable; without this a dirty collection would wait for its next
        // save.
        if (unpushed) this.#enqueuePush(name, doc);
        return;
      }

      this.#bump(name);

      let stored = false;
      this.#persisted.delete(name);

      try {
        await this.#persist(name, doc);
        this.#persisted.add(name);
        stored = true;
      } catch (err) {
        console.warn(`Could not cache the '${name}' document locally:`, err);
      }

      // Only record the log as applied after the document is on disk: a record
      // that leads the document would make the next load skip the entries the
      // stale document is missing. Also skip it when local-only changes remain,
      // or the next pull would stop retrying their push.
      if (
        stored && !unpushed && collection.complete &&
        collection.packs.length > 0
      ) {
        await this.#setAppliedLog(
          name,
          collection.packs,
          headsOf(doc).join(";"),
        );
      }

      // Only record these heads as remotely held when the local document was
      // fully pushed before the merge. Otherwise the merged heads include
      // local-only changes, and recording them would skip those changes on the
      // next push.
      if (!unpushed && !this.#dirty.has(name)) {
        const cursor = await this.#cursor(name);
        await this.#setCursor(name, {
          heads: headsOf(doc),
          pushes: cursor.pushes,
        });
      } else {
        this.#enqueuePush(name, doc);
      }
    } finally {
      this.#markReady(name);
    }
  }

  // READ

  /**
   * Read one pack from memory, IndexedDB, or the server.
   *
   * Caching each pack as it arrives is what makes an interrupted pull resume:
   * the next read re-uses what was already fetched and only asks for the rest.
   *
   * @param {Firkin} rb
   * @param {string} cid
   */
  async #readPack(rb, cid) {
    const cached = this.#packs.get(cid);
    if (cached) return cached;

    try {
      const stored = await IDB.get(`${IDB_PACKS}/${cid}`);
      if (stored instanceof Uint8Array) {
        this.#packs.set(cid, stored);
        return stored;
      }
    } catch (err) {
      console.warn("Could not read a cached Firkin entry:", err);
    }

    try {
      const bytes = await rb.get(cid);
      this.#packs.set(cid, bytes);

      try {
        await IDB.set(`${IDB_PACKS}/${cid}`, bytes);
      } catch (err) {
        console.warn("Could not cache a Firkin entry:", err);
      }

      return bytes;
    } catch (err) {
      // A missing block makes for a shorter log; the reader decides whether
      // what remains is enough.
      if (err instanceof ApiError && err.status === 404) return undefined;
      throw err;
    }
  }

  // AUTH

  /**
   * Signing material for the current session.
   *
   * The device id is the session's public key, so a manifest can only ever be
   * written under the ref its key owns.
   *
   * @param {Session} session
   */
  #auth(session) {
    if (this.#authCache?.publicKey === session.publicKey) {
      return this.#authCache.auth;
    }

    const signer = WebCryptoSigner.fromPersisted(
      session.privateKey,
      session.publicKey,
    );

    const auth = {
      device: bytesToHex(session.publicKey),
      sign: (/** @type {Uint8Array} */ bytes) => signer.sign(bytes),
      verify: verifySignature,
    };

    this.#authCache = { publicKey: session.publicKey, auth };

    return auth;
  }

  // SEQUENCES

  /** @param {string} name */
  #floorsKey(name) {
    return `${IDB_FLOORS}/${this.#namespace}/${name}`;
  }

  /**
   * The newest manifest sequence already accepted per device. A manifest with a
   * lower one is a replay and is ignored.
   *
   * @param {string} name
   * @returns {Promise<Map<string, number>>}
   */
  async #floors(name) {
    const cached = this.#floorCache.get(name);
    if (cached) return cached;

    /** @type {Map<string, number>} */
    const floors = new Map();

    try {
      const stored = await IDB.get(this.#floorsKey(name));
      if (stored && typeof stored === "object") {
        for (const [device, seq] of Object.entries(stored)) {
          if (typeof seq === "number") floors.set(device, seq);
        }
      }
    } catch (err) {
      console.warn(`Could not read the '${name}' manifest floors:`, err);
    }

    this.#floorCache.set(name, floors);

    return floors;
  }

  /**
   * @param {string} name
   * @param {Array<[string, number]>} accepted
   */
  async #recordFloors(name, accepted) {
    if (accepted.length === 0) return;

    const floors = await this.#floors(name);
    let dirty = false;

    for (const [device, seq] of accepted) {
      if ((floors.get(device) ?? 0) >= seq) continue;

      floors.set(device, seq);
      dirty = true;
    }

    if (!dirty) return;

    try {
      await IDB.set(this.#floorsKey(name), Object.fromEntries(floors));
    } catch (err) {
      console.warn(`Could not persist the '${name}' manifest floors:`, err);
    }
  }

  /**
   * The namespace listing, reused for a moment so a pull doesn't ask the same
   * question once per collection.
   *
   * @param {Firkin} rb
   */
  #loadNames(rb) {
    return (/** @type {string} */ namespace) => {
      const cached = this.#listings.get(namespace);
      if (cached && Date.now() - cached.at < NAMES_TTL_MS) {
        return cached.names;
      }

      const names = rb.registryNames(namespace).catch((err) => {
        this.#listings.delete(namespace);
        throw err;
      });

      this.#listings.set(namespace, { at: Date.now(), names });

      return names;
    };
  }

  /**
   * Read a log with signature and rollback checks, recording the sequences it
   * accepted so a later replay can be recognised.
   *
   * @param {{ session: Session; rb: Firkin }} client
   * @param {CollectionName} name
   */
  async #entries(client, name) {
    /** @type {Array<[string, number]>} */
    const accepted = [];

    const entries = await readEntries(client.rb, this.#namespace, name, {
      auth: this.#auth(client.session),
      floors: await this.#floors(name),
      loadNames: this.#loadNames(client.rb),
      onAccept: (device, seq) => accepted.push([device, seq]),
    });

    await this.#recordFloors(name, accepted);

    return entries;
  }
}

/**
 * Cheap content fingerprint. The log only grows, so length plus a hash is
 * enough to tell "same log as last time" from "something changed".
 *
 * @param {Uint8Array} bytes
 */
function fingerprintOf(bytes) {
  let hash = 2166136261;

  for (let index = 0; index < bytes.length; index++) {
    hash ^= bytes[index];
    hash = Math.imul(hash, 16777619);
  }

  return `${bytes.length}:${hash >>> 0}`;
}

/**
 * @param {Uint8Array[]} entries
 */
function concat(entries) {
  const total = entries.reduce((sum, bytes) => sum + bytes.length, 0);
  const out = new Uint8Array(total);

  let offset = 0;
  for (const bytes of entries) {
    out.set(bytes, offset);
    offset += bytes.length;
  }

  return out;
}

export default FirkinAutomergeOutput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = FirkinAutomergeOutput;
export const NAME = "dob-firkin-automerge";

defineElement(NAME, FirkinAutomergeOutput);
```
### Bytes / S3

Store output data on AWS S3 or compatible services such as Cloudflare R2.

```js
import * as IDB from "idb-keyval";

import { computed, signal } from "~/common/signal.js";
import { BroadcastedOutputElement, outputManager } from "../../common.js";
import { defineElement } from "~/common/element.js";

const STORAGE_PREFIX = "diffuse/output/bytes/s3";

/**
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 * @import {OutputElement, OutputManager} from "@specs/components/output/types.d.ts"
 * @import {Bucket} from "@specs/components/input/s3/types.d.ts"
 * @import {S3OutputElement, S3OutputWorkerActions} from "@specs/components/output/bytes/s3/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {OutputElement<Uint8Array | undefined>}
 * @implements {S3OutputElement}
 */
class S3Output extends BroadcastedOutputElement {
  static NAME = "diffuse/output/bytes/s3";
  static WORKER_URL = "components/output/bytes/s3/worker.js";

  #manager;

  constructor() {
    super();

    /** @type {ProxiedActions<S3OutputWorkerActions>} */
    this.proxy = this.workerProxy();

    /** @type {OutputManager<Uint8Array | undefined>} */
    this.#manager = outputManager({
      collaborations: {
        empty: () => undefined,
        get: () => this.#get("collaborations"),
        put: (data) => this.#put("collaborations", data),
      },
      facets: {
        empty: () => undefined,
        get: () => this.#get("facets"),
        put: (data) => this.#put("facets", data),
      },
      init: () => this.whenConnected(),
      playlistItems: {
        empty: () => undefined,
        get: () => this.#get("playlistItems"),
        put: (data) => this.#put("playlistItems", data),
      },
      settings: {
        empty: () => undefined,
        get: () => this.#get("settings"),
        put: (data) => this.#put("settings", data),
      },
      tracks: {
        empty: () => undefined,
        get: () => this.#get("tracks"),
        put: (data) => this.#put("tracks", data),
      },
    });

    this.collaborations = this.#manager.collaborations;
    this.facets = this.#manager.facets;
    this.playlistItems = this.#manager.playlistItems;
    this.settings = this.#manager.settings;
    this.tracks = this.#manager.tracks;
  }

  // SIGNALS

  #isOnline = signal(navigator.onLine);

  // STATE

  ready = computed(() => {
    return this.#bucket.value !== undefined && this.#isOnline.value;
  });

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    this.replicateSavedData(this.#manager);

    super.connectedCallback();

    /** @type {Bucket | undefined} */
    const stored = await IDB.get(`${STORAGE_PREFIX}/bucket`);
    if (stored) this.#bucket.value = stored;

    globalThis.addEventListener("online", this.#online);
    globalThis.addEventListener("offline", this.#offline);
  }

  /** @override */
  disconnectedCallback() {
    globalThis.removeEventListener("online", this.#online);
    globalThis.removeEventListener("offline", this.#offline);
  }

  #offline = () => this.#isOnline.set(false);
  #online = () => this.#isOnline.set(true);

  // BUCKET

  #bucket = signal(/** @type {Bucket | undefined} */ (undefined));

  bucket = this.#bucket.get;

  /** @returns {Promise<Bucket | undefined>} */
  async getBucket() {
    if (!this.#bucket.value) {
      /** @type {Bucket | undefined} */
      const stored = await IDB.get(`${STORAGE_PREFIX}/bucket`);
      if (stored) this.#bucket.value = stored;
      return stored;
    }

    return this.#bucket.value;
  }

  /**
   * @param {Bucket} bucket
   */
  async setBucket(bucket) {
    this.#bucket.value = bucket;
    await IDB.set(`${STORAGE_PREFIX}/bucket`, bucket);
  }

  async unsetBucket() {
    this.#bucket.value = undefined;
    await IDB.del(`${STORAGE_PREFIX}/bucket`);
  }

  // GET & PUT

  /** @param {string} name */
  #get = async (name) => {
    const bucket = await this.getBucket();
    if (!bucket) return undefined;
    return this.proxy.get({ bucket, name: this.#cat(name) });
  };

  /** @param {string} name; @param {any} data */
  #put = async (name, data) => {
    const bucket = await this.getBucket();
    if (!bucket) return undefined;
    return this.proxy.put({ bucket, data, name: this.#cat(name) });
  };

  // 🛠️

  /** @param {string} name */
  #cat(name) {
    const ns = this.namespace;
    return `${ns?.length ? ns + "/" : ""}${name}`;
  }
}

export default S3Output;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = S3Output;
export const NAME = "dob-s3";

defineElement(NAME, S3Output);
```
### Bytes / WNFS (Firkin)

Stores user data in a private WNFS on a Firkin instance, with all blocks held by the account. Playlist items and tracks are written as one file per bundle (per playlist or input source), so a save only rewrites the bundle that changed. Requires a passkey-backed Firkin account.

```js
import * as IDB from "idb-keyval";
import { CID } from "multiformats/cid";
import { base64url } from "iso-base/rfc4648";
import { FileSystem, Path } from "@wnfs-wg/nest";

import { computed, signal } from "~/common/signal.js";
import { BroadcastedOutputElement, outputManager } from "../../common.js";
import { defineElement } from "~/common/element.js";
import { byField, byUriScheme } from "~/common/bundles.js";
import {
  decodeJsonCollection,
  encodeJsonCollection,
} from "~/common/lens.js";

import { FirkinBlockstore } from "./blockstore.js";
import { readCollection, writeCollection } from "./files.js";
import {
  WnfsFirkinRootTree,
} from "./root-tree.js";
import {
  decryptPrivateKey,
  deriveStorageKey,
  encryptPrivateKey,
  generateExchangeKeyPair,
  importExchangePrivateKey,
} from "./passkey.js";
import { readLocalCollection } from "./local.js";
import {
  clientForSession,
  deleteSession,
  readSession,
} from "~/common/firkin/session.js";
import {
  passkeyDid as derivePasskeyDid,
  publishSessionDelegation,
  signInAccount,
  UnregisteredAccountError,
} from "~/common/firkin/account.js";
import {
  EXCHANGE_KEY_NAMESPACE,
  IDB_LOCAL_PREFIX,
  IDB_LOCAL_ROOT,
  IDB_STORAGE,
  REGISTRY_NAMESPACE,
  REGISTRY_PRIVATE_KEY,
  REGISTRY_ROOT,
  RESTORE_TIMEOUT_MS,
  UPLOAD_DEBOUNCE_MS,
  WNFS_OUTPUT_DIR,
} from "./constants.js";

/**
 * @import { OutputElement, OutputManager } from "@specs/components/output/types.d.ts"
 * @import { WnfsFirkinOutputElement } from "@specs/components/output/bytes/wnfs/types.d.ts"
 * @import { BundleSelector } from "~/common/bundles.d.ts"
 * @import { CollectionName } from "~/common/self-describing.js"
 * @import { Firkin } from "@tokono.ma/firkin"
 * @import { Session } from "~/common/firkin/session.js"
 * @import { Track } from "~/definitions/types.d.ts"
 *
 * @typedef {Object} Storage
 * @property {string} apiBase
 * @property {string} did
 * @property {string} root
 * @property {CryptoKey} privateKey
 * @property {Uint8Array} publicKey
 * @property {string} shareId
 *
 * @typedef {Object} EncryptedKeyPayload
 * @property {number} v
 * @property {string} shareId
 * @property {JsonWebKey} privateKey
 * @property {string} publicKey
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Collections copied from the local output when their WNFS file is missing.
 *
 * @type {readonly CollectionName[]}
 */
const SEED_COLLECTIONS = [
  "collaborations",
  "facets",
  "playlistItems",
  "settings",
  "tracks",
];

/**
 * Stores user-data in a private WNFS (via `@wnfs-wg/nest`) with all blocks
 * held by a Firkin instance.
 *
 * The account is a passkey: its PRF "signing" output derives the account's
 * ed25519 key. That key immediately delegates every `/firkin` capability to a
 * session key kept in IndexedDB. The WNFS data root is stored in the account
 * registry, and the WNFS exchange private key is stored there too, encrypted
 * with a symmetric key derived from the passkey's PRF "encryption" output.
 *
 * Playlist items are written as one WNFS file per playlist; tracks as one file
 * per URI scheme (or per input source when a composer sets `tracksBy`), so a
 * save only rewrites the bundles that changed. The other collections stay one
 * file each.
 *
 * @implements {OutputElement}
 * @implements {WnfsFirkinOutputElement}
 */
class WnfsFirkinOutput extends BroadcastedOutputElement {
  static NAME = "diffuse/output/bytes/wnfs";

  /**
   * Optional grouping rule for tracks, supplied by the composition layer.
   * When absent, tracks are grouped by their URI scheme.
   *
   * @type {BundleSelector<Track> | undefined}
   */
  tracksBy = undefined;

  /** @type {OutputManager} */
  #manager;

  // SIGNALS

  #isOnline = signal(navigator.onLine);
  #ready = signal(false);
  #session = signal(/** @type {Session | undefined} */ (undefined));
  #storage = signal(/** @type {Storage | undefined} */ (undefined));
  #lastPasskeyDid = signal(/** @type {string | undefined} */ (undefined));

  // STATE

  /** @type {FileSystem | undefined} */
  #fs;

  /** @type {FirkinBlockstore | undefined} */
  #blockstore;

  /** @type {Firkin | undefined} */
  #rb;

  /** @type {Promise<void>} */
  #restorePromise = Promise.resolve();

  /** @type {Promise<unknown>} */
  #writeQueue = Promise.resolve();

  /** @type {Promise<void> | undefined} */
  #mountPromise;

  /** Whether the local collection cache matches the current WNFS root. */
  #localFresh = false;

  /** @type {Map<CollectionName, Promise<void>>} */
  #refreshing = new Map();

  /** @type {{ root: string; resolve: () => void; reject: (err: unknown) => void }[]} */
  #uploadPending = [];

  /** @type {ReturnType<typeof setTimeout> | undefined} */
  #uploadTimer;

  #uploading = false;

  /** @type {Set<CollectionName>} */
  #accessedNames = new Set();

  constructor() {
    super();

    this.#manager = /** @type {OutputManager} */ (
      /** @type {unknown} */ (outputManager({
      collaborations: {
        empty: () => [],
        get: () => this.#get("collaborations"),
        put: (data) => this.#put("collaborations", data),
      },
      facets: {
        empty: () => [],
        get: () => this.#get("facets"),
        put: (data) => this.#put("facets", data),
      },
      init: () => this.whenConnected(),
      playlistItems: {
        empty: () => [],
        get: () => this.#get("playlistItems"),
        put: (data) => this.#put("playlistItems", data),
      },
      settings: {
        empty: () => [],
        get: () => this.#get("settings"),
        put: (data) => this.#put("settings", data),
      },
      tracks: {
        empty: () => [],
        get: () => this.#get("tracks"),
        put: (data) => this.#put("tracks", data),
      },
      }))
    );

    this.collaborations = this.#manager.collaborations;
    this.facets = this.#manager.facets;
    this.playlistItems = this.#manager.playlistItems;
    this.settings = this.#manager.settings;
    this.tracks = this.#manager.tracks;

    this.ready = computed(() => this.#ready.value && this.#isOnline.value);
  }

  // SIGNALS

  did = computed(() => this.#session.value?.did);
  apiBase = computed(() =>
    this.#session.value?.apiBase ?? this.#storage.value?.apiBase
  );
  dataRoot = computed(() => this.#storage.value?.root);
  sessionExpiresAt = computed(() => this.#session.value?.expiresAt);

  /**
   * The DID the most recent passkey flow derived. Set even when that flow then
   * failed — a freshly created passkey whose account the instance has not
   * registered yet is exactly when the UI needs it.
   */
  lastPasskeyDid = computed(() => this.#lastPasskeyDid.value);

  // LIFECYCLE

  /** @override */
  connectedCallback() {
    this.replicateSavedData(this.#manager);

    super.connectedCallback();

    globalThis.addEventListener("online", this.#online);
    globalThis.addEventListener("offline", this.#offline);

    this.#restorePromise = this.#restore().catch((err) => {
      console.error("Failed to restore Firkin + WNFS:", err);
    });
  }

  /** @override */
  disconnectedCallback() {
    globalThis.removeEventListener("online", this.#online);
    globalThis.removeEventListener("offline", this.#offline);
    super.disconnectedCallback();
  }

  #offline = () => this.#isOnline.set(false);
  #online = () => {
    this.#isOnline.set(true);

    // A restore attempted while offline (or before the instance was
    // reachable) should be retried once connectivity returns.
    if (!this.#ready.value) {
      this.#restorePromise = this.#restore().catch((err) => {
        console.error("Failed to restore Firkin + WNFS:", err);
      });
    }
  };

  /**
   * Wait for the initial restore, but never indefinitely: a hanging registry
   * request should not keep the dashboard on its loading spinner.
   */
  async #waitForRestore() {
    await Promise.race([
      this.#restorePromise,
      new Promise((resolve) => setTimeout(resolve, RESTORE_TIMEOUT_MS)),
    ]);
  }

  /** Resolves after the initial restore attempt. */
  whenRestored() {
    return this.#restorePromise;
  }

  // ACTIONS

  /**
   * Sign in with a passkey, then make sure the WNFS exists and is mounted.
   *
   * @param {{
   *   apiBase?: string
   *   create?: boolean
   * }} [options]
   */
  async signIn(options = {}) {
    await this.whenConnected();
    await this.#restorePromise;
    await this.#writeQueue.catch(() => {});
    await this.#flushUploads();

    // Reset first: only a DID derived by *this* attempt may be shown, so a
    // cancelled prompt never leaves a stale one in the dialog.
    this.#lastPasskeyDid.value = undefined;

    const account = await signInAccount({
      apiBase: options.apiBase,
      create: options.create,
    }).catch((err) => {
      if (err instanceof UnregisteredAccountError) {
        this.#lastPasskeyDid.value = err.did;
      }
      throw err;
    });

    const { apiBase, did: accountDid, prf, session } = account;

    this.#lastPasskeyDid.value = accountDid;
    this.#session.value = session;
    this.#rb = this.#clientFor(session);

    const storageKey = await deriveStorageKey(prf.prfSecond);
    const { root: rootCid, key: keyCid } = await this.#readRegistryPointers();

    /** @type {Storage} */
    let storage;

    if (rootCid && keyCid) {
      storage = await this.#loadExistingStorage(
        rootCid,
        keyCid,
        storageKey,
        apiBase,
        accountDid,
      );
    } else if (rootCid && !keyCid) {
      const cached = await IDB.get(IDB_STORAGE);
      if (
        cached &&
        cached.apiBase === apiBase &&
        cached.did === accountDid &&
        cached.privateKey instanceof CryptoKey
      ) {
        storage = cached;
        await this.#mountStorage(storage, rootCid);
      } else {
        throw new Error(
          "Firkin + WNFS exists, but its private key is missing from the registry and this browser.",
        );
      }
    } else {
      storage = await this.#createStorage(storageKey, apiBase, accountDid);
    }

    // A new WNFS starts without collection files. Copy the local output's
    // collections over before selecting it: the local output has the user's
    // current data (including the preludes that register this output), and the
    // output configurator mirrors the selected output back into the local
    // fallback — mirroring an empty, freshly created output would erase it.
    await this.#seedFromLocal(storage);
    await this.#setLocalFreshness(
      storage.root,
      rootCid ? storage.root : undefined,
    );

    await IDB.set(IDB_STORAGE, storage);
    this.#storage.value = storage;
    this.#ready.value = true;

    return {
      did: accountDid,
      root: storage.root,
      created: !rootCid,
    };
  }

  /**
   * Create a passkey (or authenticate with an existing one) and return the DID
   * it derives. Purely local: it touches neither the session nor the WNFS, and
   * makes no request, which is what the first-time setup needs — a new
   * account's DID has to be registered with the instance before it can be
   * used for anything.
   *
   * @param {{ create?: boolean }} [options]
   * @returns {Promise<string>}
   */
  async passkeyDid(options = {}) {
    await this.whenConnected();

    const did = await derivePasskeyDid(options);

    this.#lastPasskeyDid.value = did;

    return did;
  }

  /**
   * Forget the local session and storage pointer.
   *
   * This does not revoke the server-side delegation; it expires after a year.
   */
  async signOut() {
    await this.#writeQueue.catch(() => {});
    await this.#flushUploads();
    await Promise.all([deleteSession(), IDB.del(IDB_STORAGE)]);

    this.#session.value = undefined;
    this.#storage.value = undefined;
    this.#lastPasskeyDid.value = undefined;
    this.#fs = undefined;
    this.#blockstore = undefined;
    this.#rb = undefined;
    this.#mountPromise = undefined;
    this.#localFresh = false;
    this.#refreshing.clear();
    this.#ready.value = false;
  }

  // RESTORE

  async #restore() {
    const session = await readSession();
    if (!session) return;

    await publishSessionDelegation(session);

    this.#session.value = session;
    this.#rb = this.#clientFor(session);

    /** @type {Storage | undefined} */
    const storage = await IDB.get(IDB_STORAGE);
    if (!storage) return;
    if (!(storage.privateKey instanceof CryptoKey)) return;
    if (storage.apiBase !== session.apiBase || storage.did !== session.did) {
      return;
    }

    const rootCid = await this.#rb.registryGet(
      REGISTRY_NAMESPACE,
      REGISTRY_ROOT,
    );
    if (!rootCid) return;

    // Lazy mount: reads are served from the local collection cache when it
    // matches this root. The WNFS is only mounted for writes or when the cache
    // is stale/missing. This keeps dashboard startup off the private forest.
    this.#storage.value = { ...storage, root: rootCid };
    this.#ready.value = true;
    await this.#setLocalFreshness(rootCid, storage.root);

    if (rootCid !== storage.root) {
      await IDB.set(IDB_STORAGE, this.#storage.value);
    }
  }

  /**
   * Read both WNFS pointers from the account registry in one request.
   *
   * Firkin's registry is namespaced and `registryNames` returns every name in
   * a namespace, so the root and key pointers share one authenticated read.
   *
   * @returns {Promise<{ root: string | null; key: string | null }>}
   */
  async #readRegistryPointers() {
    const rb = this.#rb;
    if (!rb) throw new Error("Firkin client is not ready");

    const names = await rb.registryNames(REGISTRY_NAMESPACE);

    return {
      root: names?.[REGISTRY_ROOT] ?? null,
      key: names?.[REGISTRY_PRIVATE_KEY] ?? null,
    };
  }

  /**
   * @param {Storage} storage
   * @param {string} rootCid
   */
  async #mountStorage(storage, rootCid) {
    if (!this.#rb) throw new Error("Firkin client is not ready");

    const blockstore = new FirkinBlockstore(this.#rb, rootCid);
    // Assign before mounting: the SDK's dagPull uses this blockstore as its
    // block cache, and the cache adapter resolves `this.#blockstore` lazily.
    this.#blockstore = blockstore;

    const fs = await FileSystem.fromCID(CID.parse(rootCid), {
      blockstore,
      rootTreeClass: /** @type {any} */ (WnfsFirkinRootTree),
    });

    await fs.mountPrivateNode({
      path: Path.root(),
      exchangeKeyPair: {
        publicKey: storage.publicKey,
        privateKey: storage.privateKey,
      },
      shareId: storage.shareId || undefined,
    });

    this.#fs = fs;
  }

  // STORAGE

  /**
   * @param {Uint8Array} storageKey
   * @param {string} apiBase
   * @param {string} did
   * @returns {Promise<Storage>}
   */
  async #createStorage(storageKey, apiBase, did) {
    if (!this.#rb) throw new Error("Firkin client is not ready");

    const blockstore = new FirkinBlockstore(this.#rb);
    // Assign early: the SDK's push/pull cache adapter resolves
    // `this.#blockstore` lazily.
    this.#blockstore = blockstore;

    const fs = await FileSystem.create({
      blockstore,
      rootTreeClass: /** @type {any} */ (WnfsFirkinRootTree),
    });

    await fs.assignIdentifier(did);

    const keyPair = await generateExchangeKeyPair();
    const privateJwk = await crypto.subtle.exportKey("jwk", keyPair.privateKey);
    const publicJwk = await crypto.subtle.exportKey("jwk", keyPair.publicKey);

    const publicKey = base64url.decode(
      /** @type {string} */ (publicJwk.n),
    );

    await fs.registerExchangeKey(EXCHANGE_KEY_NAMESPACE, publicKey);

    const { shareId } = await fs.createPrivateNode({
      path: Path.root(),
      exchangeKeyPair: {
        publicKey,
        privateKey: keyPair.privateKey,
      },
    });

    await fs.ensureDirectory(Path.priv(WNFS_OUTPUT_DIR));

    const root = (await fs.calculateDataRoot()).toString();
    blockstore.setRoot(root);

    // Upload the WNFS blocks first, then the encrypted private key, and only
    // then point the registry at the root. A partial failure leaves the old
    // (or no) root, never a root with missing blocks.
    await blockstore.flush(root);

    /** @type {EncryptedKeyPayload} */
    const payload = {
      v: 1,
      shareId,
      privateKey: privateJwk,
      publicKey: base64url.encode(publicKey),
    };

    const encrypted = encryptPrivateKey(storageKey, payload);
    const { cid: keyCid } = await this.#rb.upload(encrypted);

    await this.#rb.registrySet(
      REGISTRY_NAMESPACE,
      REGISTRY_PRIVATE_KEY,
      keyCid,
    );
    await this.#rb.registrySet(REGISTRY_NAMESPACE, REGISTRY_ROOT, root);

    // Keep a non-extractable handle for everyday use.
    const privateKey = await importExchangePrivateKey(privateJwk);

    this.#fs = fs;

    return { apiBase, did, root, privateKey, publicKey, shareId };
  }

  /**
   * @param {string} rootCid
   * @param {string} keyCid
   * @param {Uint8Array} storageKey
   * @param {string} apiBase
   * @param {string} did
   * @returns {Promise<Storage>}
   */
  async #loadExistingStorage(rootCid, keyCid, storageKey, apiBase, did) {
    if (!this.#rb) throw new Error("Firkin client is not ready");

    const encrypted = await this.#rb.get(keyCid);

    /** @type {EncryptedKeyPayload} */
    let payload;
    try {
      payload = /** @type {EncryptedKeyPayload} */ (
        decryptPrivateKey(storageKey, encrypted)
      );
    } catch {
      throw new Error(
        "Could not decrypt the Firkin + WNFS key. Sign in with the passkey that created this storage.",
      );
    }

    if (payload.v !== 1) {
      throw new Error(`Unsupported Firkin + WNFS key version: ${payload.v}`);
    }

    const publicKey = base64url.decode(payload.publicKey);
    const privateKey = await importExchangePrivateKey(payload.privateKey);

    /** @type {Storage} */
    const storage = {
      apiBase,
      did,
      root: rootCid,
      privateKey,
      publicKey,
      shareId: payload.shareId ?? "",
    };

    await this.#mountStorage(storage, rootCid);
    return storage;
  }

  /**
   * Seed missing collection files from the local (default) output.
   *
   * A new WNFS starts without collection files, while the local output still
   * has the user's current data. Copy it over before the output is selected:
   * the output configurator mirrors the selected output back into the local
   * fallback, so mirroring an empty new output would erase the user's data.
   *
   * Collections that already have a file are left untouched: the file existing
   * means the WNFS has been written to (possibly deliberately emptied).
   *
   * @param {Storage} storage
   */
  async #seedFromLocal(storage) {
    const fs = this.#fs;
    const blockstore = this.#blockstore;
    const rb = this.#rb;
    if (!fs || !blockstore || !rb) return;

    const dir = Path.priv(WNFS_OUTPUT_DIR);
    if (!(await fs.exists(dir))) {
      await fs.ensureDirectory(dir);
    }

    let seeded = false;

    for (const name of SEED_COLLECTIONS) {
      const path = Path.priv(WNFS_OUTPUT_DIR, name);
      if (await fs.exists(path)) continue;

      const data = await readLocalCollection(name);
      if (data.length === 0) continue;

      await writeCollection(fs, name, data, this.#selectorFor(name));
      await this.#writeLocalCache(
        name,
        /** @type {Uint8Array} */ (encodeJsonCollection(data, name, true)),
      );
      seeded = true;
    }

    if (!seeded) return;

    const root = (await fs.calculateDataRoot()).toString();
    await blockstore.flush(root);
    blockstore.setRoot(root);

    await rb.registrySet(REGISTRY_NAMESPACE, REGISTRY_ROOT, root);
    storage.root = root;

    await IDB.set(IDB_LOCAL_ROOT, root);
    this.#localFresh = true;
  }

  /** @param {Session} session */
  #clientFor(session) {
    return clientForSession(session, {
      cache: {
        /** @param {string} cid */
        get: (cid) => this.#blockstore?.peek(cid),
        /** @param {string} cid; @param {Uint8Array} bytes */
        set: (cid, bytes) => {
          this.#blockstore?.seed(cid, bytes);
        },
        keys: () => this.#blockstore?.keys() ?? [],
      },
    });
  }

  // COLLECTIONS

  /**
   * @param {string} root
   * @param {string | undefined} knownRoot - Cached storage root, used as a
   *   legacy hint when `IDB_LOCAL_ROOT` has not been written yet.
   */
  async #setLocalFreshness(root, knownRoot) {
    const cached = await IDB.get(IDB_LOCAL_ROOT);
    this.#localFresh = cached === undefined
      ? knownRoot === root
      : cached === root;

    if (this.#localFresh && cached === undefined) {
      await IDB.set(IDB_LOCAL_ROOT, root);
    }
  }

  /** Mount the WNFS on demand (reads can be served from the local cache). */
  async #ensureMounted() {
    if (this.#fs) return;
    if (this.#mountPromise) return await this.#mountPromise;

    const storage = this.#storage.value;
    if (!storage) throw new Error("Firkin + WNFS is not configured");

    this.#mountPromise = this.#mountStorage(storage, storage.root).finally(
      () => {
        this.#mountPromise = undefined;
      },
    );

    await this.#mountPromise;
  }

  /** @param {CollectionName} name */
  #scheduleRefresh(name) {
    const run = () => {
      void this.#refreshCollection(name);
    };

    if (typeof requestIdleCallback === "function") {
      requestIdleCallback(run, { timeout: 2_000 });
    } else {
      setTimeout(run, 0);
    }
  }

  /**
   * The grouping rule for a collection, or `undefined` when it is stored as a
   * single file.
   *
   * Playlist items are one file per playlist. Tracks are one file per input
   * source (an S3 bucket, a Subsonic server, a local folder, …), falling back
   * to their URI scheme when no input can name the source.
   *
   * @param {CollectionName} name
   */
  #selectorFor(name) {
    if (name === "playlistItems") return byField("playlist");
    if (name !== "tracks") return undefined;

    const fallback = byUriScheme();
    const custom = this.tracksBy;

    if (!custom) return fallback;

    /** @type {BundleSelector<Track>} */
    const selector = (track) => custom(track) ?? fallback(track);
    return selector;
  }

  /** @param {CollectionName} name */
  #refreshCollection(name) {
    const existing = this.#refreshing.get(name);
    if (existing) return existing;

    const pending = (async () => {
      try {
        await this.#ensureMounted();
        const fs = this.#fs;
        if (!fs) return;

        const data = await readCollection(fs, name);
        await this.#writeLocalCache(
          name,
          /** @type {Uint8Array} */ (encodeJsonCollection(data, name, true)),
        );
        this.#manager.signals[name].value = data;
      } catch (err) {
        console.error(`Failed to refresh Firkin + WNFS '${name}':`, err);
      } finally {
        this.#refreshing.delete(name);
      }
    })();

    this.#refreshing.set(name, pending);
    return pending;
  }

  // GET & PUT

  /**
   * @param {CollectionName} name
   * @returns {Promise<any[]>}
   */
  #get = async (name) => {
    this.#accessedNames.add(name);

    await this.whenConnected();
    await this.#writeQueue;

    // Cache-first: serve the local collection immediately. The WNFS is only
    // mounted when the cache is stale/absent or on a write. This avoids walking
    // the (potentially large) private forest on every dashboard load.
    const local = await this.#readLocalCache(name);

    if (local.length > 0) {
      if (this.#ready.value && !this.#localFresh) {
        this.#scheduleRefresh(name);
      } else if (!this.#ready.value) {
        // Restore is still in flight. Refresh after it settles (and after the
        // caller has applied the local snapshot) if the root changed.
        this.#restorePromise.then(() => {
          setTimeout(() => {
            if (this.#ready.value && !this.#localFresh) {
              this.#scheduleRefresh(name);
            }
          }, 0);
        });
      }
      return local;
    }

    await this.#waitForRestore();

    if (!this.#ready.value) return [];

    await this.#ensureMounted();

    const fs = this.#fs;
    if (!fs) return [];

    try {
      const data = await readCollection(fs, name);
      if (data.length === 0) return [];

      await this.#writeLocalCache(
        name,
        /** @type {Uint8Array} */ (encodeJsonCollection(data, name, true)),
      );
      return data;
    } catch (err) {
      console.error(`Failed to read Firkin + WNFS '${name}':`, err);
      return await this.#readLocalCache(name);
    }
  };

  /**
   * @param {CollectionName} name
   * @param {any[]} data
   */
  #put = (name, data) => {
    const write = async () => {
      await this.whenConnected();
      await this.#restorePromise;

      const rb = this.#rb;
      const storage = this.#storage.value;

      if (!this.#ready.value || !rb || !storage) {
        throw new Error("Firkin + WNFS is not connected");
      }

      await this.#ensureMounted();

      const fs = this.#fs;
      const blockstore = this.#blockstore;
      if (!fs || !blockstore) {
        throw new Error("Firkin + WNFS could not be mounted");
      }

      const bytes = /** @type {Uint8Array} */ (
        encodeJsonCollection(data, name, true)
      );

      const dir = Path.priv(WNFS_OUTPUT_DIR);
      if (!(await fs.exists(dir))) {
        await fs.ensureDirectory(dir);
      }

      await writeCollection(fs, name, data, this.#selectorFor(name));

      // Keep the local fallback current even if the upload fails.
      await this.#writeLocalCache(name, bytes);

      const root = (await fs.calculateDataRoot()).toString();
      return { root, changed: root !== storage.root };
    };

    // Serialize only the WNFS mutations. The upload is coalesced by the
    // debounced queue, so rapid saves share one `/dag/push`.
    const written = this.#writeQueue.then(write, write);
    this.#writeQueue = written.then(() => {}, () => {});
    return written.then(({ root, changed }) =>
      changed ? this.#enqueueUpload(root) : undefined
    );
  };

  /**
   * Queue an upload for `root`. Multiple saves within the debounce window are
   * batched into one `/dag/push` rooted at the latest root.
   *
   * @param {string} root
   */
  #enqueueUpload(root) {
    return new Promise((resolve, reject) => {
      this.#uploadPending.push({
        root,
        resolve: () => resolve(undefined),
        reject,
      });

      if (this.#uploadTimer !== undefined) clearTimeout(this.#uploadTimer);
      this.#uploadTimer = setTimeout(() => {
        this.#uploadTimer = undefined;
        this.#drainUploads();
      }, UPLOAD_DEBOUNCE_MS);
    });
  }

  async #drainUploads() {
    if (this.#uploading || this.#uploadPending.length === 0) return;
    this.#uploading = true;

    const batch = this.#uploadPending;
    this.#uploadPending = [];
    const root = batch[batch.length - 1].root;

    try {
      const blockstore = this.#blockstore;
      const rb = this.#rb;
      const storage = this.#storage.value;
      if (!blockstore || !rb || !storage) {
        throw new Error("Firkin + WNFS is not connected");
      }

      await blockstore.flush(root);
      await rb.registrySet(REGISTRY_NAMESPACE, REGISTRY_ROOT, root);
      blockstore.setRoot(root);

      const next = { ...storage, root };
      this.#storage.value = next;
      await IDB.set(IDB_STORAGE, next);
      await IDB.set(IDB_LOCAL_ROOT, root);
      this.#localFresh = true;

      for (const item of batch) item.resolve();
    } catch (err) {
      console.error("Failed to upload Firkin + WNFS blocks:", err);
      for (const item of batch) item.reject(err);
    } finally {
      this.#uploading = false;

      if (this.#uploadPending.length > 0) {
        this.#uploadTimer = setTimeout(() => {
          this.#uploadTimer = undefined;
          this.#drainUploads();
        }, UPLOAD_DEBOUNCE_MS);
      }
    }
  }

  /** Flush pending uploads immediately (used when signing out). */
  async #flushUploads() {
    if (this.#uploadTimer !== undefined) {
      clearTimeout(this.#uploadTimer);
      this.#uploadTimer = undefined;
    }

    while (this.#uploading || this.#uploadPending.length > 0) {
      await this.#drainUploads();
      await new Promise((resolve) => setTimeout(resolve, 10));
    }
  }

  // LOCAL CACHE

  /** @param {CollectionName} name */
  #localCacheKey(name) {
    const ns = this.namespace ?? "default";
    return `${IDB_LOCAL_PREFIX}/${ns}/${name}`;
  }

  /**
   * @param {CollectionName} name
   * @returns {Promise<any[]>}
   */
  async #readLocalCache(name) {
    try {
      const cached = await IDB.get(this.#localCacheKey(name));
      if (!(cached instanceof Uint8Array)) return [];
      return decodeJsonCollection(cached, name);
    } catch (err) {
      console.error(
        `Failed to read the local Firkin + WNFS cache for '${name}':`,
        err,
      );
      return [];
    }
  }

  /**
   * @param {CollectionName} name
   * @param {Uint8Array} bytes
   */
  async #writeLocalCache(name, bytes) {
    try {
      await IDB.set(this.#localCacheKey(name), bytes);
    } catch (err) {
      console.error(`Failed to cache Firkin + WNFS file '${name}':`, err);
    }
  }
}

export default WnfsFirkinOutput;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = WnfsFirkinOutput;
export const NAME = "dob-wnfs-firkin";

defineElement(NAME, CLASS);
```
## Supplements
### Publish on the Atmosphere

Publishes playlist items, facets and collaborations to the user's AT Protocol account beside whichever output is selected. Owns the shared AT Protocol publish session and only writes changed records.

```js
import { Client, ClientResponseError, ok } from "@atcute/client";
import { encode } from "@atcute/cbor";

import {
  BroadcastableDiffuseElement,
  defineElement,
  queryOptional,
} from "~/common/element.js";
import { computed, signal } from "~/common/signal.js";
import { flattenBundles, isBundleArray } from "~/common/bundles.js";

import {
  clearStoredSession,
  login as oauthLogin,
  logout as oauthLogout,
  OAuthUserAgent,
  restoreOrFinalize,
  TokenRefreshError,
  withOAuth,
} from "~/oauth/atproto.js";

import {
  bundlePlaylistItems,
  bytesHash,
  stableHash,
} from "./common.js";

/**
 * @import {Session} from "@atcute/oauth-browser-client"
 * @import {Collaboration, Facet, PlaylistItem} from "~/definitions/types.d.ts"
 * @import {OutputElement} from "@specs/components/output/types.d.ts"
 * @import {ATProtoPublishElement} from "@specs/components/supplement/atproto-publish/types.d.ts"
 *
 * @typedef {import("@atcute/atproto").ComAtprotoRepoApplyWrites.$input['writes'][number]} WriteOp
 * @typedef {{ hash: string, rkey: string, playlist?: string }} PublishedRecord
 * @typedef {{
 *   collaborations: Record<string, PublishedRecord>,
 *   playlists: Record<string, PublishedRecord>,
 *   facets: Record<string, PublishedRecord>,
 * }} PublishState
 * @typedef {{ rkey: string, playlist: string, bytes: Uint8Array, hash: string }} PlaylistUpsert
 * @typedef {{ id: string, record: Record<string, unknown>, hash: string }} RecordUpsert
 */

////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////

const COLLABORATION = "sh.diffuse.output.collaboration";
const FACET = "sh.diffuse.output.facet";
const PLAYLIST_ITEM_BUNDLE = "sh.diffuse.output.playlistItemBundle";

/** Local record of what this element has already published, per account. */
const STORAGE_PREFIX = "diffuse/supplement/atproto-publish";

/** Debounce for reacting to output changes (collection signals fire rapidly). */
const SYNC_DEBOUNCE_MS = 1500;

/** Maximum number of deletes per `applyWrites` call. */
const DELETE_BATCH_SIZE = 100;

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Publishes playlist items, facets and collaborations to the user's AT
 * Protocol account.
 *
 * This is deliberately not an output: it reads from whichever output is
 * selected and publishes a copy to the account connected through the shared
 * AT Protocol publish session. That makes it usable alongside any storage
 * method (S3, Dropbox, the local output, …).
 *
 * @implements {ATProtoPublishElement}
 */
class ATProtoPublish extends BroadcastableDiffuseElement {
  static NAME = "diffuse/supplement/atproto-publish";
  static observedAttributes = ["output-selector"];

  // SIGNALS

  #did = signal(/** @type {`did:${string}:${string}` | null} */ (null));
  #handle = signal(/** @type {string | null} */ (null));
  #isOnline = signal(
    typeof navigator === "undefined" ? true : navigator.onLine,
  );
  #authenticated = signal(false);
  #syncing = signal(false);
  #error = signal(/** @type {string | null} */ (null));
  #lastSyncedAt = signal(/** @type {number | null} */ (null));
  #output = signal(/** @type {OutputElement<any> | null} */ (null));

  /** @type {PromiseWithResolvers<void>} */
  #restoreSettled = Promise.withResolvers();

  did = this.#did.get;
  handle = this.#handle.get;
  syncing = this.#syncing.get;
  error = this.#error.get;
  lastSyncedAt = this.#lastSyncedAt.get;

  ready = computed(() => {
    return this.#authenticated.value && this.#did.value !== null &&
      this.#isOnline.value;
  });

  // SESSION

  /** @type {OAuthUserAgent | null} */
  #agent = null;

  /** @type {Client | null} */
  #rpc = null;

  /** Whether a session restore is currently in flight. */
  #restoring = false;

  // SYNC

  /** @type {ReturnType<typeof setTimeout> | null} */
  #timer = null;
  #running = false;
  #queued = false;

  // LIFECYCLE

  /** @override */
  connectedCallback() {
    // Only the leader writes, so two tabs can't upload or delete the same
    // record at the same time.
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(this.identifier, {
        publish: { strategy: "leaderOnly", fn: this.publish },
      });

      if (actions) this.publish = actions.publish;
    }

    super.connectedCallback();

    this.#resolveOutput();
    this.#installWatch();
    this.#tryRestore();

    globalThis.addEventListener("online", this.#online);
    globalThis.addEventListener("offline", this.#offline);
  }

  /** @override */
  disconnectedCallback() {
    globalThis.removeEventListener("online", this.#online);
    globalThis.removeEventListener("offline", this.#offline);

    if (this.#timer !== null) {
      clearTimeout(this.#timer);
      this.#timer = null;
    }

    super.disconnectedCallback();
  }

  /**
   * @override
   * @param {string} name
   * @param {string} oldValue
   * @param {string} newValue
   */
  attributeChangedCallback(name, oldValue, newValue) {
    super.attributeChangedCallback(name, oldValue, newValue);

    if (
      name === "output-selector" && this.isConnected && oldValue !== newValue
    ) {
      this.#resolveOutput();
    }
  }

  #offline = () => this.#isOnline.set(false);

  #online = () => {
    this.#isOnline.set(true);

    // A restore may have failed while offline; give it another chance instead
    // of staying silently disconnected until the page is reloaded.
    if (!this.#rpc) this.#tryRestore();
    else this.#schedule();
  };

  // AUTH

  /**
   * Initiate the OAuth flow. This is the same session as the public AT
   * Protocol output, so signing in here also signs that output in.
   *
   * @param {string} handle
   */
  async login(handle) {
    await oauthLogin(handle);
  }

  /**
   * Sign out and revoke the shared AT Protocol session.
   */
  async logout() {
    const agent = this.#agent;
    this.#resetSession();
    if (agent) await oauthLogout(agent);
  }

  /**
   * @returns {Promise<void>}
   */
  whenRestored() {
    return this.#restoreSettled.promise;
  }

  async #tryRestore() {
    if (this.#restoring) return;
    this.#restoring = true;

    try {
      await this.whenConnected();

      try {
        const session = await restoreOrFinalize();

        if (session) {
          this.#setSession(session);
        } else if (this.#rpc) {
          this.#resetSession();
        } else {
          console.info(
            "ATProto publish: no AT Protocol session; connect an account to publish.",
          );
        }
      } catch (err) {
        if (this.#isSessionError(err)) {
          this.#resetSession();
        } else {
          // Transient failure (offline, timeout, auth server hiccup). The
          // stored session is intact; retry on the next online event.
          console.warn("ATProto publish: failed to restore the session", err);
        }
      }
    } finally {
      this.#restoring = false;
      this.#restoreSettled.resolve();
    }
  }

  /**
   * @param {Session} session
   */
  #setSession(session) {
    const agent = new OAuthUserAgent(session);

    // All RPC goes through `agent.handle()`. Run it with the atcute library
    // configured for the shared AT Protocol client under the shared OAuth
    // lock; otherwise another module (Rocksky) can leave the globals pointing
    // at its own database/client id and a token refresh here would fail.
    const originalHandle = agent.handle.bind(agent);
    agent.handle = /** @type {typeof originalHandle} */ ((pathname, init) => {
      return withOAuth(() => originalHandle(pathname, init));
    });

    this.#agent = agent;
    this.#rpc = new Client({ handler: agent });
    this.#did.value = session.info.sub;
    this.#authenticated.value = true;
    this.#error.value = null;
    this.#fetchHandle(session.info.sub);
  }

  #resetSession() {
    this.#agent = null;
    this.#rpc = null;
    this.#did.value = null;
    this.#handle.value = null;
    this.#authenticated.value = false;
  }

  /**
   * Drop a session that can no longer be refreshed so future syncs stop
   * silently failing.
   */
  #handleSessionLost() {
    this.#resetSession();
    this.#error.value = "The AT Protocol session is no longer valid.";

    // Don't await: a failed refresh may still hold the OAuth lock. The queued
    // clear runs afterwards.
    clearStoredSession().catch((err) => {
      console.warn("ATProto publish: failed to clear the stored session", err);
    });
  }

  /**
   * @param {unknown} err
   * @returns {boolean}
   */
  #isSessionError(err) {
    if (err instanceof TokenRefreshError) return true;
    // OAuthUserAgent.handle() swallows TokenRefreshError and returns the
    // original 401 response, which ok() wraps as a ClientResponseError.
    if (err instanceof ClientResponseError && err.status === 401) return true;
    if (err && typeof err === "object" && "cause" in err) {
      return this.#isSessionError(
        (/** @type {{ cause: unknown }} */ (err)).cause,
      );
    }
    return false;
  }

  /**
   * @param {string} did
   */
  async #fetchHandle(did) {
    const rpc = this.#rpc;
    if (!rpc) return;

    try {
      const result = await ok(rpc.get("com.atproto.repo.describeRepo", {
        params: {
          repo: /** @type {import("@atcute/lexicons").ActorIdentifier} */ (did),
        },
      }));

      if (this.#did.value === did) {
        this.#handle.value = result?.handle ?? null;
      }
    } catch {
      // Non-fatal; handle stays null
    }
  }

  // OUTPUT

  async #resolveOutput() {
    const output = /** @type {Element | null} */ (
      queryOptional(this, "output-selector") ??
        document.querySelector("do-output")
    );

    if (!output) return;

    await customElements.whenDefined(output.localName);

    if (!(await this.#waitForCollections(output))) return;

    this.#output.value = /** @type {OutputElement<any>} */ (
      /** @type {unknown} */ (output)
    );
  }

  /**
   * The orchestrator's proxied collections are only reachable once it has
   * rendered its output chain. Poll briefly instead of reading a getter that
   * throws.
   *
   * @param {Element} output
   * @returns {Promise<boolean>}
   */
  async #waitForCollections(output) {
    for (let attempt = 0; attempt < 100; attempt++) {
      try {
        const out = /** @type {OutputElement<any>} */ (
          /** @type {unknown} */ (output)
        );
        out.playlistItems.collection();
        out.facets.collection();
        out.collaborations.collection();
        return true;
      } catch {
        await new Promise((resolve) => setTimeout(resolve, 50));
      }
    }

    console.warn("ATProto publish: the output never became available");
    return false;
  }

  /**
   * Publish whenever the selected output's collections change.
   */
  #installWatch() {
    this.effect(() => {
      const output = this.#output.value;
      if (!output) return;
      if (!this.#authenticated.value) return;

      try {
        const playlistItems = output.playlistItems.collection();
        const facets = output.facets.collection();
        const collaborations = output.collaborations.collection();

        if (playlistItems.state !== "loaded") return;
        if (facets.state !== "loaded") return;
        if (collaborations.state !== "loaded") return;

        // Read the data so changes are tracked by the effect.
        void playlistItems.data;
        void facets.data;
        void collaborations.data;
      } catch {
        return;
      }

      if (this.#isOnline.value) this.#schedule();
    });
  }

  // SYNC

  #schedule() {
    if (!this.ready()) return;

    if (this.#timer !== null) clearTimeout(this.#timer);

    this.#timer = setTimeout(() => {
      this.#timer = null;
      void this.publish();
    }, SYNC_DEBOUNCE_MS);
  }

  /**
   * Publish the selected output's playlist items, facets and collaborations
   * now.
   *
   * @returns {Promise<void>}
   */
  async publish() {
    if (!this.ready()) return;

    if (this.#running) {
      this.#queued = true;
      return;
    }

    this.#running = true;
    this.#syncing.value = true;
    this.#error.value = null;

    try {
      await this.#publishNow();
      this.#lastSyncedAt.value = Date.now();
    } catch (err) {
      if (this.#isSessionError(err)) {
        this.#handleSessionLost();
      } else {
        console.warn("ATProto publish: could not publish", err);
        this.#error.value = err instanceof Error ? err.message : String(err);
      }
    } finally {
      this.#syncing.value = false;
      this.#running = false;

      if (this.#queued) {
        this.#queued = false;
        this.#schedule();
      }
    }
  }

  async #publishNow() {
    const output = this.#output.value;
    const did = this.#did.value;
    if (!output || !this.#rpc || !did) return;

    const playlistCollection = output.playlistItems.collection();
    const facetCollection = output.facets.collection();
    const collaborationCollection = output.collaborations.collection();

    if (playlistCollection.state !== "loaded") return;
    if (facetCollection.state !== "loaded") return;
    if (collaborationCollection.state !== "loaded") return;

    const playlistItems = /** @type {PlaylistItem[]} */ (
      isBundleArray(playlistCollection.data)
        ? flattenBundles(playlistCollection.data)
        : playlistCollection.data ?? []
    );
    const facets = /** @type {Facet[]} */ (facetCollection.data ?? []);
    const collaborations = /** @type {Collaboration[]} */ (
      collaborationCollection.data ?? []
    );

    const bundles = bundlePlaylistItems(playlistItems);
    const previous = this.#readState(did);

    /** @type {PlaylistUpsert[]} */
    const playlistUpserts = [];
    /** @type {Record<string, PublishedRecord>} */
    const nextPlaylists = { ...previous.playlists };

    for (const { id: rkey, key: playlist, items } of bundles) {
      const bytes = encode(items);
      const hash = bytesHash(bytes);

      if (previous.playlists[rkey]?.hash === hash) continue;

      playlistUpserts.push({ rkey, playlist, bytes, hash });
    }

    const desiredPlaylistKeys = new Set(bundles.map((bundle) => bundle.id));
    const playlistDeletes = Object.keys(previous.playlists).filter(
      (rkey) => !desiredPlaylistKeys.has(rkey),
    );

    /** @type {Map<string, Record<string, unknown>>} */
    const desiredCollaborations = new Map();

    for (const collaboration of collaborations) {
      if (!collaboration || typeof collaboration.id !== "string") continue;
      desiredCollaborations.set(collaboration.id, {
        ...collaboration,
        $type: COLLABORATION,
      });
    }

    /** @type {RecordUpsert[]} */
    const collaborationUpserts = [];
    /** @type {Record<string, PublishedRecord>} */
    const nextCollaborations = { ...previous.collaborations };

    for (const [id, record] of desiredCollaborations) {
      const hash = stableHash(record);
      if (previous.collaborations[id]?.hash === hash) continue;
      collaborationUpserts.push({ id, record, hash });
    }

    const collaborationDeletes = Object.keys(previous.collaborations).filter(
      (id) => !desiredCollaborations.has(id),
    );

    /** @type {Map<string, Record<string, unknown>>} */
    const desiredFacets = new Map();

    for (const facet of facets) {
      if (!facet || typeof facet.id !== "string") continue;
      desiredFacets.set(facet.id, { ...facet, $type: FACET });
    }

    /** @type {RecordUpsert[]} */
    const facetUpserts = [];
    /** @type {Record<string, PublishedRecord>} */
    const nextFacets = { ...previous.facets };

    for (const [id, record] of desiredFacets) {
      const hash = stableHash(record);
      if (previous.facets[id]?.hash === hash) continue;
      facetUpserts.push({ id, record, hash });
    }

    const facetDeletes = Object.keys(previous.facets).filter(
      (id) => !desiredFacets.has(id),
    );

    // Playlists are stored as one bundle record (with a CBOR blob) per
    // playlist, matching the data shape other Diffuse clients expect.
    for (const { rkey, playlist, bytes, hash } of playlistUpserts) {
      const blob = await this.#uploadBlob(bytes);
      if (!blob) continue;

      await this.#putRecord(PLAYLIST_ITEM_BUNDLE, rkey, {
        $type: PLAYLIST_ITEM_BUNDLE,
        id: rkey,
        playlist,
        data: blob,
      });

      nextPlaylists[rkey] = { hash, rkey, playlist };
    }

    for (const { id, record, hash } of collaborationUpserts) {
      await this.#putRecord(COLLABORATION, id, record);
      nextCollaborations[id] = { hash, rkey: id };
    }

    for (const { id, record, hash } of facetUpserts) {
      await this.#putRecord(FACET, id, record);
      nextFacets[id] = { hash, rkey: id };
    }

    // Only delete records this element published itself. Another client may
    // store other records in these collections that the selected output
    // doesn't know about; those must be left alone.
    if (playlistDeletes.length > 0) {
      await this.#applyDeletes(PLAYLIST_ITEM_BUNDLE, playlistDeletes);
      for (const rkey of playlistDeletes) delete nextPlaylists[rkey];
    }

    if (facetDeletes.length > 0) {
      await this.#applyDeletes(FACET, facetDeletes);
      for (const id of facetDeletes) delete nextFacets[id];
    }

    if (collaborationDeletes.length > 0) {
      await this.#applyDeletes(COLLABORATION, collaborationDeletes);
      for (const id of collaborationDeletes) delete nextCollaborations[id];
    }

    this.#writeState(did, {
      collaborations: nextCollaborations,
      playlists: nextPlaylists,
      facets: nextFacets,
    });
  }

  // RPC

  /**
   * @param {string} collection
   * @param {string} rkey
   * @param {Record<string, unknown>} record
   */
  async #putRecord(collection, rkey, record) {
    const rpc = this.#rpc;
    const did = this.#did.value;
    if (!rpc || !did) return;

    await ok(rpc.post("com.atproto.repo.putRecord", {
      input: {
        repo: did,
        collection: /** @type {`${string}.${string}.${string}`} */ (collection),
        rkey,
        record,
      },
    }));
  }

  /**
   * @param {string} collection
   * @param {string[]} rkeys
   */
  async #applyDeletes(collection, rkeys) {
    const rpc = this.#rpc;
    const did = this.#did.value;
    if (!rpc || !did) return;

    for (let i = 0; i < rkeys.length; i += DELETE_BATCH_SIZE) {
      /** @type {WriteOp[]} */
      const writes = rkeys.slice(i, i + DELETE_BATCH_SIZE).map((rkey) => ({
        $type: "com.atproto.repo.applyWrites#delete",
        collection: /** @type {`${string}.${string}.${string}`} */ (collection),
        rkey,
      }));

      await ok(rpc.post("com.atproto.repo.applyWrites", {
        input: { repo: did, writes },
      }));
    }
  }

  /**
   * @param {Uint8Array} bytes
   */
  async #uploadBlob(bytes) {
    const rpc = this.#rpc;
    if (!rpc) return;

    const result = await ok(rpc.post("com.atproto.repo.uploadBlob", {
      input: bytes,
      headers: { "content-type": "application/octet-stream" },
    }));

    return result?.blob;
  }

  // STATE

  /**
   * @param {string} did
   * @returns {PublishState}
   */
  #readState(did) {
    try {
      const raw = localStorage.getItem(`${STORAGE_PREFIX}/${did}`);
      const parsed = raw ? JSON.parse(raw) : null;

      if (parsed && typeof parsed === "object") {
        return {
          collaborations:
            parsed.collaborations && typeof parsed.collaborations === "object"
              ? parsed.collaborations
              : {},
          playlists: parsed.playlists && typeof parsed.playlists === "object"
            ? parsed.playlists
            : {},
          facets: parsed.facets && typeof parsed.facets === "object"
            ? parsed.facets
            : {},
        };
      }
    } catch {
      // A corrupt cache just means everything is published again.
    }

    return { collaborations: {}, playlists: {}, facets: {} };
  }

  /**
   * @param {string} did
   * @param {PublishState} state
   */
  #writeState(did, state) {
    try {
      localStorage.setItem(
        `${STORAGE_PREFIX}/${did}`,
        JSON.stringify(state),
      );
    } catch (err) {
      console.warn(
        "ATProto publish: could not persist the published state",
        err,
      );
    }
  }
}

export default ATProtoPublish;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = ATProtoPublish;
export const NAME = "ds-atproto-publish";

/** Marks the element mounted by the prelude so it is never mounted twice. */
export const MARKER = "data-atproto-publish";

defineElement(NAME, CLASS);
```
### Last.fm Scrobbler

Scrobbles track plays to Last.fm.

```js
import { md5 } from "@noble/hashes/legacy.js";
import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";

import {
  BroadcastableDiffuseElement,
  defineElement,
} from "~/common/element.js";
import { computed, signal } from "~/common/signal.js";
import { clearSession, readSession, saveSession } from "../session.js";

/**
 * @import {Track} from "~/definitions/types.d.ts"
 * @import {ScrobbleElement} from "@specs/components/supplement/types.d.ts"
 */

////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////

const LASTFM_API_URL = "https://ws.audioscrobbler.com/2.0/";
const LASTFM_AUTH_URL = "https://www.last.fm/api/auth/";
const STORAGE_KEY = "diffuse/supplement/last.fm/session";

const DEFAULT_API_KEY = "4f0fe85b67baef8bb7d008a8754a95e5";
const DEFAULT_API_SECRET = "0cec3ca0f58e04a5082f1131aba1e0d3";

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ScrobbleElement}
 */
class LastFmScrobbler extends BroadcastableDiffuseElement {
  static NAME = "diffuse/supplement/last.fm";

  get #apiKey() {
    return this.getAttribute("api-key") ?? DEFAULT_API_KEY;
  }

  get #apiSecret() {
    return this.getAttribute("api-secret") ?? DEFAULT_API_SECRET;
  }

  // SIGNALS

  #handle = signal(/** @type {string | null} */ (null));
  #sessionKey = signal(/** @type {string | null} */ (null));
  #isAuthenticating = signal(false);

  // STATE

  handle = this.#handle.get;
  isAuthenticated = computed(() => this.#sessionKey.value !== null);
  isAuthenticating = this.#isAuthenticating.get;

  // LIFECYCLE

  /** @override */
  connectedCallback() {
    // Broadcast if needed
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(this.identifier, {
        nowPlaying: { strategy: "leaderOnly", fn: this.nowPlaying },
        scrobble: { strategy: "leaderOnly", fn: this.scrobble },

        setHandle: { strategy: "replicate", fn: this.#handle.set },
        setSession: { strategy: "replicate", fn: this.#sessionKey.set },
      });

      if (actions) {
        this.nowPlaying = actions.nowPlaying;
        this.scrobble = actions.scrobble;

        this.#handle.set = actions.setHandle;
        this.#sessionKey.set = actions.setSession;
      }
    }

    super.connectedCallback();

    this.#tryRestore();
  }

  async #tryRestore() {
    await this.whenConnected();

    // last.fm appends ?token=TOKEN to the callback URL after authorization.
    const urlParams = new URLSearchParams(location.search);
    const urlToken = urlParams.get("token");

    if (urlToken) {
      urlParams.delete("token");
      const newSearch = urlParams.toString();
      history.replaceState(
        null,
        "",
        location.pathname + (newSearch ? "?" + newSearch : "") + location.hash,
      );

      this.#isAuthenticating.set(true);

      try {
        const session = await this.#getSession(urlToken);
        await this.#setSession(session);
      } catch (err) {
        console.warn("last.fm: failed to exchange token for session", err);
      } finally {
        this.#isAuthenticating.set(false);
      }

      return;
    }

    const stored = await readSession(this, STORAGE_KEY);

    if (stored) {
      try {
        const { key, name: handle } = JSON.parse(stored);
        if (await this.isLeader()) {
          this.#sessionKey.set(key);
          this.#handle.set(handle);
        } else {
          this.#sessionKey.value = key;
          this.#handle.value = handle;
        }
      } catch {
        await clearSession(this, STORAGE_KEY);
      }
    }
  }

  // AUTH

  /**
   * Initiate the last.fm auth flow.
   * Redirects the browser to the authorization page; last.fm appends ?token=TOKEN to the callback.
   */
  signIn() {
    const callbackUrl = location.origin + location.pathname + location.search;
    const authUrl = new URL(LASTFM_AUTH_URL);
    authUrl.searchParams.set("api_key", this.#apiKey);
    authUrl.searchParams.set("cb", callbackUrl);

    // Navigate the top-level frame so last.fm's X-Frame-Options doesn't block loading
    // when this element is used inside an iframe.
    (window.top ?? window).location.assign(authUrl.toString());
  }

  /**
   * Clear the stored session.
   */
  async signOut() {
    this.#sessionKey.set(null);
    this.#handle.set(null);
    await clearSession(this, STORAGE_KEY);
  }

  /** @param {{ key: string, name: string }} session */
  async #setSession({ key, name: handle }) {
    this.#sessionKey.set(key);
    this.#handle.set(handle);
    await saveSession(this, STORAGE_KEY, JSON.stringify({ key, name: handle }));
  }

  // SCROBBLE ACTIONS

  /**
   * @param {Track} track
   */
  async nowPlaying(track) {
    const tags = track.tags ?? {};
    /** @type {Record<string, string>} */
    const params = {};

    if (tags.title) params.track = tags.title;
    if (tags.artist) params.artist = tags.artist;
    if (tags.album) params.album = tags.album;
    if (tags.albumartist) params.albumArtist = tags.albumartist;
    if (tags.track?.no != null) params.trackNumber = String(tags.track.no);
    if (track.stats?.duration != null) {
      params.duration = String(Math.round(track.stats.duration / 1000));
    }

    return this.#authenticatedCall("track.updateNowPlaying", params);
  }

  /**
   * @param {Track} track
   * @param {number} startedAt Unix timestamp in milliseconds
   * @param {{ duration?: number }} [_options] duration in milliseconds
   */
  async scrobble(track, startedAt, _options) {
    const tags = track.tags ?? {};
    /** @type {Record<string, string>} */
    const params = {
      timestamp: String(Math.floor(startedAt / 1000)),
    };

    if (tags.title) params.track = tags.title;
    if (tags.artist) params.artist = tags.artist;
    if (tags.album) params.album = tags.album;
    if (tags.albumartist) params.albumArtist = tags.albumartist;
    if (tags.track?.no != null) params.trackNumber = String(tags.track.no);
    if (track.stats?.duration != null) {
      params.duration = String(Math.round(track.stats.duration / 1000));
    }

    return this.#authenticatedCall("track.scrobble", params);
  }

  // API

  /**
   * Sign a set of API parameters (excluding `format` and `callback`).
   *
   * @param {Record<string, string>} params
   * @returns {string} MD5 hex digest
   */
  #sign(params) {
    const str = Object.keys(params)
      .sort()
      .map((k) => k + params[k])
      .join("");
    return bytesToHex(md5(utf8ToBytes(str + this.#apiSecret)));
  }

  /**
   * @param {string} method
   * @param {Record<string, string>} [params]
   * @returns {Promise<any>}
   */
  async #call(method, params = {}) {
    const allParams = { ...params, api_key: this.#apiKey, method };
    const api_sig = this.#sign(allParams);
    const body = new URLSearchParams({ ...allParams, api_sig, format: "json" });

    const response = await fetch(LASTFM_API_URL, { method: "POST", body });
    const data = await response.json();

    if (data.error) {
      throw new Error(`last.fm error ${data.error}: ${data.message}`);
    }

    return data;
  }

  /**
   * @param {string} method
   * @param {Record<string, string>} [params]
   * @returns {Promise<any>}
   */
  async #authenticatedCall(method, params = {}) {
    const sk = this.#sessionKey.value;
    if (!sk) throw new Error("Not authenticated with last.fm");
    return this.#call(method, { ...params, sk });
  }

  /**
   * @param {string} token
   * @returns {Promise<{ key: string, name: string }>}
   */
  async #getSession(token) {
    const data = await this.#call("auth.getSession", { token });
    return data.session;
  }
}

export default LastFmScrobbler;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = LastFmScrobbler;
export const NAME = "ds-lastfm-scrobbler";

defineElement(NAME, CLASS);
```
### ListenBrainz Scrobbler

Scrobbles track plays to ListenBrainz.

```js
import { BroadcastableDiffuseElement, defineElement } from "~/common/element.js";
import { computed, signal } from "~/common/signal.js";
import { clearSession, readSession, saveSession } from "../session.js";

/**
 * @import {Track} from "~/definitions/types.d.ts"
 * @import {ScrobbleElement} from "@specs/components/supplement/types.d.ts"
 */

////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////

const API_BASE = "https://api.listenbrainz.org/1/";
const STORAGE_KEY = "diffuse/supplement/listenbrainz/session";

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ScrobbleElement}
 */
class ListenBrainzScrobbler extends BroadcastableDiffuseElement {
  static NAME = "diffuse/supplement/listenbrainz";

  // SIGNALS

  #handle = signal(/** @type {string | null} */ (null));
  #userToken = signal(/** @type {string | null} */ (null));
  #isAuthenticating = signal(false);

  // STATE

  handle = this.#handle.get;
  isAuthenticated = computed(() => this.#userToken.value !== null);
  isAuthenticating = this.#isAuthenticating.get;

  // LIFECYCLE

  /** @override */
  connectedCallback() {
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(this.identifier, {
        nowPlaying: { strategy: "leaderOnly", fn: this.nowPlaying },
        scrobble: { strategy: "leaderOnly", fn: this.scrobble },

        setHandle: { strategy: "replicate", fn: this.#handle.set },
        setUserToken: { strategy: "replicate", fn: this.#userToken.set },
      });

      if (actions) {
        this.nowPlaying = actions.nowPlaying;
        this.scrobble = actions.scrobble;

        this.#handle.set = actions.setHandle;
        this.#userToken.set = actions.setUserToken;
      }
    }

    super.connectedCallback();

    this.#tryRestore();
  }

  async #tryRestore() {
    await this.whenConnected();

    const stored = await readSession(this, STORAGE_KEY);

    if (stored) {
      try {
        const { token, username } = JSON.parse(stored);

        if (await this.isLeader()) {
          this.#userToken.set(token);
          this.#handle.set(username);
        } else {
          this.#userToken.value = token;
          this.#handle.value = username;
        }
      } catch {
        await clearSession(this, STORAGE_KEY);
      }
    }
  }

  // AUTH

  /**
   * Validate a ListenBrainz user token and store the session.
   *
   * @param {string} token
   */
  async signIn(token) {
    this.#isAuthenticating.set(true);
    try {
      const username = await this.#validateToken(token);
      this.#userToken.set(token);
      this.#handle.set(username);
      await saveSession(this, STORAGE_KEY, JSON.stringify({ token, username }));
    } catch (err) {
      console.warn("listenbrainz: failed to authenticate", err);
      throw err;
    } finally {
      this.#isAuthenticating.set(false);
    }
  }

  /**
   * Clear the stored session.
   */
  async signOut() {
    this.#userToken.set(null);
    this.#handle.set(null);
    await clearSession(this, STORAGE_KEY);
  }

  // SCROBBLE ACTIONS

  /**
   * @param {Track} track
   */
  async nowPlaying(track) {
    return this.#submit("playing_now", [
      { track_metadata: this.#trackMetadata(track) },
    ]);
  }

  /**
   * @param {Track} track
   * @param {number} startedAt Unix timestamp in milliseconds
   * @param {{ duration?: number }} [options] duration in milliseconds
   */
  async scrobble(track, startedAt, options) {
    return this.#submit("single", [
      {
        listened_at: Math.floor(startedAt / 1000),
        track_metadata: this.#trackMetadata(track, options?.duration),
      },
    ]);
  }

  // API

  /**
   * @param {Track} track
   * @param {number} [durationMs]
   * @returns {Record<string, unknown>}
   */
  #trackMetadata(track, durationMs) {
    const tags = track.tags ?? {};
    /** @type {Record<string, unknown>} */
    const additional_info = { submission_client: "Diffuse" };

    const duration = track.stats?.duration ?? durationMs;
    if (duration != null) {
      additional_info.duration_ms = duration;
    }
    if (tags.track?.no != null) {
      additional_info.tracknumber = tags.track.no;
    }

    /** @type {Record<string, unknown>} */
    const metadata = { additional_info };

    if (tags.title) metadata.track_name = tags.title;
    if (tags.artist) metadata.artist_name = tags.artist;
    if (tags.album) metadata.release_name = tags.album;

    return metadata;
  }

  /**
   * @param {string} token
   * @returns {Promise<string>} username
   */
  async #validateToken(token) {
    const response = await fetch(`${API_BASE}validate-token`, {
      headers: { Authorization: `Token ${token}` },
    });
    const data = await response.json();

    if (!data.valid) {
      throw new Error(
        `listenbrainz: invalid token — ${data.message ?? "unknown error"}`,
      );
    }

    return data.user_name;
  }

  /**
   * @param {string} listen_type
   * @param {unknown[]} payload
   * @returns {Promise<any>}
   */
  async #submit(listen_type, payload) {
    const token = this.#userToken.value;
    if (!token) throw new Error("Not authenticated with ListenBrainz");

    const response = await fetch(`${API_BASE}submit-listens`, {
      method: "POST",
      headers: {
        Authorization: `Token ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ listen_type, payload }),
    });

    const data = await response.json();

    if (data.code && data.code !== 200) {
      throw new Error(`listenbrainz error ${data.code}: ${data.error}`);
    }

    return data;
  }
}

export default ListenBrainzScrobbler;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = ListenBrainzScrobbler;
export const NAME = "ds-listenbrainz-scrobbler";

defineElement(NAME, CLASS);
```
### Rocksky Scrobbler

Scrobbles track plays to Rocksky.

```js
import { now as tidNow } from "@atcute/tid";

import { BroadcastableDiffuseElement, defineElement } from "~/common/element.js";
import { signal } from "~/common/signal.js";
import { clearSession, readSession, saveSession } from "../session.js";

import {
  clearStoredSession,
  DID_STORAGE_KEY,
  login,
  logout,
  OAuthUserAgent,
  restoreOrFinalize,
  TokenRefreshError,
  withSession,
} from "./oauth.js";

/**
 * @import {Track} from "~/definitions/types.d.ts"
 * @import {ScrobbleElement} from "@specs/components/supplement/types.d.ts"
 */

////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////

const STORAGE_KEY = "diffuse/supplement/rocksky/session";

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ScrobbleElement}
 */
class RockskyScrobbler extends BroadcastableDiffuseElement {
  static NAME = "diffuse/supplement/rocksky";

  // SIGNALS

  #handle = signal(/** @type {string | null} */ (null));
  #connected = signal(false);
  #isAuthenticating = signal(false);

  // STATE

  handle = this.#handle.get;
  isAuthenticated = this.#connected.get;
  isAuthenticating = this.#isAuthenticating.get;

  // LIFECYCLE

  /** @override */
  connectedCallback() {
    // Broadcast if needed
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(this.identifier, {
        nowPlaying: { strategy: "leaderOnly", fn: this.nowPlaying },
        scrobble: { strategy: "leaderOnly", fn: this.scrobble },

        setHandle: { strategy: "replicate", fn: this.#handle.set },
        setConnected: { strategy: "replicate", fn: this.#connected.set },
      });

      if (actions) {
        this.nowPlaying = actions.nowPlaying;
        this.scrobble = actions.scrobble;

        this.#handle.set = actions.setHandle;
        this.#connected.set = actions.setConnected;
      }
    }

    super.connectedCallback();

    this.#tryRestore();
  }

  async #tryRestore() {
    await this.whenConnected();

    try {
      const session = await restoreOrFinalize();

      if (session) {
        const did = session.info.sub;

        await this.#setConnection(did);
        await saveSession(this, STORAGE_KEY, JSON.stringify({ did }));
        return;
      }

      // There is no session on this device. Never advertise a connection we
      // can't scrobble with; that mismatch is what made a dead session look
      // connected while every scrobble was silently dropped.
      await this.#setConnection(null);
      return;
    } catch (err) {
      // Transient failure (offline, timeout, auth server hiccup). The session
      // is still stored, so keep the persisted state and retry later.
      console.warn("Rocksky: Failed to restore/finalize session", err);
    }

    // Restore previously stored connection state.
    const stored = await readSession(this, STORAGE_KEY);

    if (stored) {
      try {
        const { did } = JSON.parse(stored);

        if (typeof did !== "string") throw new Error("invalid stored session");

        await this.#setConnection(did);
      } catch {
        await clearSession(this, STORAGE_KEY);
      }
    }
  }

  /**
   * Update the connection state and broadcast it to the other instances.
   *
   * @param {string | null} did
   */
  async #setConnection(did) {
    const connected = did !== null;

    if (await this.isLeader()) {
      this.#connected.set(connected);
      this.#handle.set(did);
    } else {
      this.#connected.value = connected;
      this.#handle.value = did;
    }

    if (!connected) {
      await clearSession(this, STORAGE_KEY);
    }
  }

  /**
   * Drop a session that can no longer be refreshed and surface the
   * disconnected state, so the user can reconnect instead of getting silent
   * failures forever.
   */
  async #handleSessionLost() {
    console.warn("Rocksky: session expired or revoked; sign-in required");

    try {
      await clearStoredSession();
    } catch (err) {
      console.warn("Rocksky: Failed to clear stored session", err);
    }

    this.#connected.set(false);
    this.#handle.set(null);
    await clearSession(this, STORAGE_KEY);
  }

  // AUTH

  /**
   * Connect to Rocksky by initiating the AT Protocol OAuth flow for the given handle.
   * Navigates the browser away to the authorization server.
   *
   * @param {string} handle
   */
  async signIn(handle) {
    this.#isAuthenticating.set(true);

    try {
      await login(handle);
    } finally {
      this.#isAuthenticating.set(false);
    }
  }

  /**
   * Disconnect from Rocksky.
   */
  async signOut() {
    // Reflect the disconnect immediately; revocation is best-effort.
    this.#connected.set(false);
    this.#handle.set(null);
    await clearSession(this, STORAGE_KEY);

    try {
      await logout();
    } catch (err) {
      console.warn("Rocksky: Failed to sign out", err);
    }
  }

  // SCROBBLE ACTIONS

  /**
   * @param {Track} _track
   */
  async nowPlaying(_track) {
    // Rocksky has no now-playing PDS record type; scrobbles are the source of truth.
  }

  /**
   * @param {Track} track
   * @param {number} startedAt Unix timestamp in milliseconds
   * @param {{ duration?: number }} [options] duration in milliseconds
   */
  async scrobble(track, startedAt, { duration: durationMs } = {}) {
    if (!this.#connected.value) return;

    const did = localStorage.getItem(DID_STORAGE_KEY);
    if (!did) return;

    const tags = track.tags ?? {};
    const duration = track.stats?.duration ?? durationMs;

    // duration has no meaningful fallback value; skip rather than create an invalid record
    if (duration == null) return;

    /** @type {Record<string, unknown>} */
    const record = {
      $type: "app.rocksky.scrobble",
      createdAt: new Date(startedAt).toISOString(),
      title: tags.title || "Unknown",
      artist: tags.artist || "Unknown",
      album: tags.album || "Unknown",
      albumArtist: tags.albumartist || tags.artist || "Unknown",
      duration,
    };

    if (tags.track?.no != null) record.trackNumber = tags.track.no;
    if (tags.disc?.no != null) record.discNumber = tags.disc.no;

    /** @type {Response} */
    let response;

    try {
      response = await withSession((session) => {
        const agent = new OAuthUserAgent(session);

        return agent.handle("/xrpc/com.atproto.repo.putRecord", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            repo: did,
            collection: "app.rocksky.scrobble",
            rkey: tidNow(),
            record,
            validate: false,
          }),
        });
      });
    } catch (err) {
      if (err instanceof TokenRefreshError) {
        await this.#handleSessionLost();
      }

      throw err;
    }

    if (!response.ok) {
      const error = await response.json().catch(() => ({}));

      // `OAuthUserAgent.handle()` swallows a failed token refresh and returns
      // the original 401, so this means the session is unusable rather than
      // the scrobble itself being invalid.
      if (response.status === 401) {
        await this.#handleSessionLost();
      }

      throw new Error(`rocksky: scrobble failed ${response.status}: ${error.message ?? ""}`);
    }
  }
}

export default RockskyScrobbler;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = RockskyScrobbler;
export const NAME = "ds-rocksky-scrobbler";

defineElement(NAME, CLASS);
```
## Transformers
### Output / Bundles

Exposes an output's collections as bundles: one per playlist, and one per track source (an S3 bucket, a Subsonic server, a directory, …). Without an input to name the source, tracks fall back to their URI scheme. Other collections pass through unchanged, and saving bundles flattens them back into the wrapped output.

```js
import { computed } from "~/common/signal.js";
import {
  bundle,
  byField,
  byUriScheme,
  flattenBundles,
  isBundle,
} from "~/common/bundles.js";
import { OutputTransformer } from "../base.js";
import { defineElement } from "~/common/element.js";

/**
 * @import {BundleSelector} from "~/common/bundles.d.ts"
 * @import {Track} from "~/definitions/types.d.ts"
 */

/** @typedef {"collaborations" | "facets" | "playlistItems" | "settings" | "tracks"} CollectionName */

/**
 * The collections that have an obvious "smaller piece" and how to find it.
 *
 * Playlist items belong to a playlist. Tracks are grouped by their URI scheme
 * by default; a composer that knows about inputs can set `tracksBy` to
 * `bySourceProvider(inputs)` (see `~/common/bundles.js`) to group by the
 * input's source instead.
 *
 * The other collections are already one record per item (a facet, a
 * collaboration, a setting), so grouping them would only produce one-item
 * bundles.
 *
 * @type {Record<string, BundleSelector<any>>}
 */
const BUNDLEABLE = {
  playlistItems: byField("playlist"),
  tracks: byUriScheme(),
};

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Exposes an output's collections as bundles.
 *
 * A bundle is a group of items that belong together: one per playlist, or one
 * per track source. Bundles are the unit Diffuse publishes to AT Protocol, but
 * they are useful anywhere a consumer wants smaller, stable pieces instead of
 * one flat collection.
 *
 * The element bundles automatically wherever that is meaningful:
 *
 * - `playlistItems` by their `playlist`
 * - `tracks` by their URI scheme
 *
 * A composer that knows about inputs can set `tracksBy` to a selector that
 * groups tracks by their input source instead (for example
 * `bySourceProvider(inputs)` from `~/common/bundles.js`). The element itself
 * never looks for inputs.
 *
 * Every other collection passes through unchanged. A bundled collection is
 * returned from `collection()` as `Bundle<T>[]`; its `save()` accepts bundles
 * and flattens them before writing to the wrapped output.
 *
 * Because the bundleable collections change shape, this element is meant to sit
 * *between* a consumer and an output (for example, between the AT Protocol
 * publisher and the output the user selected), not inside the orchestrator's
 * main output chain where the UI expects flat collections.
 *
 * ```html
 * <dto-bundles output-selector="#do-output__output"></dto-bundles>
 * ```
 *
 * @extends {OutputTransformer}
 */
class BundlesTransformer extends OutputTransformer {
  static NAME = "diffuse/transformer/output/bundles";

  /**
   * Optional grouping rule for tracks, supplied by the composition layer.
   * When absent, tracks are grouped by their URI scheme.
   *
   * @type {BundleSelector<Track> | undefined}
   */
  tracksBy = undefined;

  constructor() {
    super();

    const base = this.base();

    /** @param {CollectionName} name */
    const wrap = (name) => {
      if (!BUNDLEABLE[name]) return base[name];

      return {
        ...base[name],
        collection: computed(() => {
          const collection = base[name].collection();
          if (collection.state !== "loaded") return collection;

          const data = Array.isArray(collection.data)
            ? /** @type {any[]} */ (collection.data)
            : [];

          const by = name === "tracks"
            ? this.#trackSelector()
            : BUNDLEABLE[name];
          const bundles = bundle(data, { by });

          // A key that matches nothing silently turns a populated collection
          // into an empty one. Both fields are required by their lexicons, so
          // this only happens with unexpected data — make it visible instead of
          // losing the items quietly.
          const bundled = bundles.reduce((n, b) => n + b.items.length, 0);
          if (data.length > 0 && bundled !== data.length) {
            console.warn(
              `Bundles: ${data.length - bundled} item(s) in '${name}' have no grouping key`,
            );
          }

          return /** @type {any} */ ({ state: "loaded", data: bundles });
        }),
        save: async (/** @type {any} */ data) => {
          const items = Array.isArray(data) ? data : [];

          // Only flatten when the caller actually passed bundles; a flat list
          // is still valid and should round-trip unchanged.
          if (items.length > 0 && items.every(isBundle)) {
            await base[name].save(flattenBundles(items));
          } else {
            await base[name].save(data);
          }
        },
      };
    };

    this.collaborations = base.collaborations;
    this.facets = base.facets;
    this.playlistItems = wrap("playlistItems");
    this.settings = base.settings;
    this.tracks = wrap("tracks");

    this.ready = base.ready;
  }

  /** Resolves the track grouping rule, preferring the composer's override. */
  #trackSelector() {
    const custom = this.tracksBy;
    if (!custom) return BUNDLEABLE.tracks;

    const fallback = BUNDLEABLE.tracks;

    /** @type {BundleSelector<Track>} */
    const selector = (track) => custom(track) ?? fallback(track);
    return selector;
  }
}

export default BundlesTransformer;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = BundlesTransformer;
export const NAME = "dto-bundles";

defineElement(NAME, CLASS);
```
### Output / Bytes / DASL Sync

Syncs data between local and remote using CID-based diffing and performs union merges with tombstone tracking when both sides have diverged.

```js
import { decode, encode } from "@atcute/cbor";
import { ifDefined } from "lit-html/directives/if-defined.js";
import deepDiff from "@fry69/deep-diff";

import "~/components/output/polymorphic/indexed-db/element.js";

import * as CID from "~/common/cid.js";
import { diff, strictEquality } from "~/common/compare.js";
import { collectionSchema } from "~/common/self-describing.js";
import { computed, signal } from "~/common/signal.js";
import { compareTimestamps } from "~/common/temporal.js";
import { OutputTransformer } from "../../base.js";
import { defineElement } from "~/common/element.js";

/**
 * @import { SignalReader } from "~/common/signal.d.ts";
 * @import { RenderArg } from "~/common/element.d.ts"
 * @import { OutputElement } from "@specs/components/output/types.d.ts"
 *
 * @import { Container } from "@specs/components/transformer/output/bytes/dasl-sync/types.d.ts"
 */

/** @type {Container<any>} */
const EMPTY = {
  cid: undefined,
  data: [],
  inventory: { current: {}, removed: [] },
};

/**
 * @extends {OutputTransformer<Uint8Array>}
 */
class DaslBytesSyncOutputTransformer extends OutputTransformer {
  static NAME = "diffuse/transformer/output/bytes/dasl-sync";

  constructor() {
    super();

    const remote = this.base();
    const local = this.#localOutput.get;

    /**
     * @template {{ id: string; updatedAt: string }} T
     * @param {string} kind
     * @param {SignalReader<{ state: "loading" } | { state: "loaded"; data: Uint8Array | undefined } | { state: "error" }>} localCollection
     * @param {SignalReader<{ state: "loading" } | { state: "loaded"; data: Uint8Array | undefined } | { state: "error" }>} remoteCollection
     * @param {{ saveLocal: (bytes: Uint8Array) => Promise<void>; saveRemote: (bytes: Uint8Array) => Promise<void> }} sync
     */
    const state = (
      kind,
      localCollection,
      remoteCollection,
      { saveLocal, saveRemote },
    ) => {
      const container = signal(
        /** @type {Container<T>} */ (EMPTY),
        { compare: strictEquality },
      );

      const isReady = signal(false);
      const merging = signal(
        { isBusy: false, lastCID: "", lastRemoteCID: "" },
        { compare: diff },
      );

      this.effect(() => {
        if (!isReady.value) return;
        if (merging.value.isBusy) return;

        const lc = localCollection();
        const rc = remote.ready() ? remoteCollection() : undefined;

        const lb = lc?.state === "loaded" ? lc.data : undefined;
        const rb = rc?.state === "loaded" ? rc.data : undefined;
        const rs = rc?.state;

        /** @type {Container<T> | undefined} */
        const l = lb ? decode(lb) : undefined;

        /** @type {Container<T> | undefined} */
        const r = rb && rs === "loaded" ? decode(rb) : undefined;

        if (!r) {
          if (l) {
            container.value = l;

            if (remote.ready() && rs === "loaded") {
              this.isLeader().then((isLeader) => {
                if (!isLeader) return;
                const bytes = this.save(l);
                saveRemote(bytes);
              });
            }
          }
        } else if (!l) {
          container.value = r;

          this.isLeader().then((isLeader) => {
            if (!isLeader) return;
            const bytes = this.save(r);
            saveLocal(bytes);
          });
        } else if (
          rs === "loaded" && this.hasDiverged({ local: l, remote: r })
        ) {
          // If we've already reconciled this exact (local, remote) pair and it
          // made no progress (e.g. the remote write failed, or the merge
          // resolved to the container we already hold), don't re-enter the
          // merge. Re-merging here only toggles `merging`'s busy flag, which
          // re-runs this effect and spins the reactive sync loop, freezing the
          // page. Wait until local or remote actually changes before trying
          // again.
          const prev = merging.value;
          if (prev.lastCID === (l.cid ?? "") &&
              prev.lastRemoteCID === (r.cid ?? "")) {
            return;
          }

          // Async merge
          this.isLeader().then((isLeader) => {
            if (!isLeader) return;

            merging.value = {
              isBusy: true,
              lastCID: prev.lastCID,
              lastRemoteCID: prev.lastRemoteCID,
            };

            this.merge(l, r).then(async (c) => {
              /**
               * Remote cid after the (possible) push. Stays at the pre-merge
               * remote cid when there's nothing to push or the push fails, so
               * the effect-level guard above knows this reconcile was already
               * attempted and won't retry it in a loop.
               */
              let resolvedRemoteCID = r.cid ?? "";
              let reconciledCID = c.cid ?? "";

              try {
                container.value = c;

                const bytes = this.save(c);

                if (c.cid !== l.cid) {
                  await saveLocal(bytes);
                }

                if (remote.ready() && rs === "loaded" && c.cid !== r.cid) {
                  await saveRemote(bytes);
                  resolvedRemoteCID = c.cid ?? "";
                }
              } catch (err) {
                console.error("Merge failed:", err);
              } finally {
                merging.value = {
                  isBusy: false,
                  lastCID: reconciledCID,
                  lastRemoteCID: resolvedRemoteCID,
                };
              }
            }).catch((err) => {
              // Merge() itself rejected (before producing a reconciled
              // container). Reset the busy flag so the effect isn't stuck, and
              // record the exact (local, remote) pair we attempted so a
              // persistent failure is skipped rather than spinning forever.
              console.error("Merge failed:", err);
              merging.value = {
                isBusy: false,
                lastCID: l.cid ?? "",
                lastRemoteCID: r.cid ?? "",
              };
            });
          });
        } else {
          container.value = l;
        }
      });

      return computed(() => {
        if (!isReady.get()) isReady.value = true;
        return container.get();
      });
    };

    // Container signals
    const collaborations = state(
      "collaborations",
      computed(() =>
        local()?.collaborations.collection() ?? { state: "loading" }
      ),
      remote.collaborations.collection,
      {
        saveLocal: async (v) => local()?.collaborations.save(v),
        saveRemote: remote.collaborations.save,
      },
    );

    const facets = state(
      "facets",
      computed(() => local()?.facets.collection() ?? { state: "loading" }),
      remote.facets.collection,
      {
        saveLocal: async (v) => local()?.facets.save(v),
        saveRemote: remote.facets.save,
      },
    );

    const playlistItems = state(
      "playlistItems",
      computed(() =>
        local()?.playlistItems.collection() ?? { state: "loading" }
      ),
      remote.playlistItems.collection,
      {
        saveLocal: async (v) => local()?.playlistItems.save(v),
        saveRemote: remote.playlistItems.save,
      },
    );

    const settings = state(
      "settings",
      computed(() => local()?.settings.collection() ?? { state: "loading" }),
      remote.settings.collection,
      {
        saveLocal: async (v) => local()?.settings.save(v),
        saveRemote: remote.settings.save,
      },
    );

    const tracks = state(
      "tracks",
      computed(() => local()?.tracks.collection() ?? { state: "loading" }),
      remote.tracks.collection,
      {
        saveLocal: async (v) => local()?.tracks.save(v),
        saveRemote: remote.tracks.save,
      },
    );

    // Output manager
    this.collaborations = this.managerProp(
      { save: async (v) => local()?.collaborations.save(v) },
      remote.collaborations,
      remote.ready,
      collaborations,
      "collaborations",
    );

    this.facets = this.managerProp(
      { save: async (v) => local()?.facets.save(v) },
      remote.facets,
      remote.ready,
      facets,
      "facets",
    );

    this.playlistItems = this.managerProp(
      { save: async (v) => local()?.playlistItems.save(v) },
      remote.playlistItems,
      remote.ready,
      playlistItems,
      "playlistItems",
    );

    this.settings = this.managerProp(
      { save: async (v) => local()?.settings.save(v) },
      remote.settings,
      remote.ready,
      settings,
      "settings",
    );

    this.tracks = this.managerProp(
      { save: async (v) => local()?.tracks.save(v) },
      remote.tracks,
      remote.ready,
      tracks,
      "tracks",
    );

    this.ready = () => true;
  }

  // SIGNALS

  #localOutput = signal(
    /** @type {OutputElement<any> | undefined} */ (undefined),
  );

  // LIFECYCLE

  /**
   * @override
   */
  async connectedCallback() {
    // Broadcast if needed
    if (this.hasAttribute("group")) {
      this.broadcast(this.identifier, {});
    }

    super.connectedCallback();

    /** @type {OutputElement<any> | null} */
    const local = this.root().querySelector("dop-indexed-db");
    if (!local) throw new Error("Can't find local output");

    customElements.whenDefined(local.localName).then(() => {
      this.#localOutput.value = local;
    });
  }

  // DATA FUNCTIONS

  /**
   * @template {{ id: string; updatedAt: string }} T
   * @param {{ previous: Container<T>, collection: T[], name?: import("~/common/self-describing.js").CollectionName }} _
   * @returns {Promise<Container<T>>}
   */
  async updateContainer({ previous, collection, name }) {
    const inventory = previous.inventory;
    const schema = name ? collectionSchema(name) : null;

    const collIds = collection.map(({ id }) => id);

    const currSet = new Set(Object.keys(inventory.current));
    const collSet = new Set(collIds);

    const newSet = collSet.difference(currSet);
    const remSet = currSet.difference(collSet);

    const alreadyRemoved = new Set(inventory.removed);
    const allRemoved = alreadyRemoved.union(remSet);

    /** @type {Record<string, string>} */
    const current = { ...inventory.current };

    remSet.forEach((id) => {
      delete current[id];
    });

    /** @type Promise<void>[] */
    const promises = [];

    collection.forEach((a) => {
      const encoded = encode(a);

      promises.push((async () => {
        const cid = await CID.create(0x71, encoded);
        current[a.id] = cid;
      })());
    });

    await Promise.all(promises);

    const newInventory = {
      current,
      removed: Array.from(allRemoved),
    };

    const container = {
      cid: await CID.create(0x71, encode(newInventory)),
      data: collection,
      inventory: newInventory,
    };
    return schema ? { ...container, $schema: schema } : container;
  }

  /**
   * @template {{ id: string; updatedAt: string }} T
   * @param {{ local: Container<T>, remote: Container<T> }} _
   */
  hasDiverged({ local, remote }) {
    return local.cid !== remote.cid;
  }

  /**
   * @template {{ id: string; updatedAt: string }} T
   * @param {Container<T>} a
   * @param {Container<T>} b
   * @returns {Promise<Container<T>>}
   */
  async merge(a, b) {
    const removedA = new Set(a.inventory.removed);
    const removedB = new Set(b.inventory.removed);
    const allRemoved = removedA.union(removedB);

    const currentA = a.inventory.current;
    const currentB = b.inventory.current;

    const mapA = new Map(a.data.map((item) => [item.id, item]));
    const mapB = new Map(b.data.map((item) => [item.id, item]));

    // Combine all known ids from both sides
    const allIds = new Set([
      ...Object.keys(currentA),
      ...Object.keys(currentB),
    ]);

    /** @type {Record<string, string>} */
    const current = {};

    /** @type {T[]} */
    const data = [];

    // Construct `current` and `data`
    /** @type {Promise<void>[]} */
    const cidPromises = [];

    for (const id of allIds) {
      if (allRemoved.has(id)) continue;

      if (id in currentA && id in currentB) {
        const itemA = mapA.get(id);
        const itemB = mapB.get(id);

        if (!itemA || !itemB) {
          console.warn("Should have found both items but didn't!");
          continue;
        }

        // Items are identical, no merge or CID recomputation needed
        if (currentA[id] === currentB[id]) {
          data.push(itemA);
          current[id] = currentA[id];
          continue;
        }

        const hasAUpdatedAt = Boolean(itemA.updatedAt);
        const hasBUpdatedAt = Boolean(itemB.updatedAt);

        // The side that carries an `updatedAt` is the one that was edited, so
        // it should win over a pristine copy that never recorded a change (e.g.
        // a legacy seeded/starting-set facet persisted before it gained a
        // timestamp). Only when both carry one do we compare clocks.
        const isANewerThanB = (hasAUpdatedAt && !hasBUpdatedAt)
          ? true
          : (!hasAUpdatedAt && hasBUpdatedAt)
          ? false
          : hasAUpdatedAt && hasBUpdatedAt
          ? compareTimestamps(itemA.updatedAt, itemB.updatedAt) > 0
          : false;

        const newestItem = isANewerThanB ? itemA : itemB;
        const oldItem = isANewerThanB ? itemB : itemA;

        /** @type {T} */
        const mergedItem = { ...oldItem };

        deepDiff.applyDiff(mergedItem, newestItem);

        data.push(mergedItem);

        cidPromises.push(
          CID.create(0x71, encode(mergedItem)).then((cid) => {
            current[id] = cid;
          }),
        );
      } else {
        const item = mapA.get(id) ?? mapB.get(id);

        if (item) {
          data.push(item);
          current[id] = currentA[id] ?? currentB[id];
        }
      }
    }

    await Promise.all(cidPromises);

    // New inventory
    const updatedInventory = { current, removed: Array.from(allRemoved) };

    return {
      cid: await CID.create(0x71, encode(updatedInventory)),
      data,
      inventory: updatedInventory,
      $schema: a.$schema,
    };
  }

  /**
   * @template {{ id: string; updatedAt: string }} T
   * @param {Container<T>} container
   * @returns {Uint8Array}
   */
  save(container) {
    return encode(container);
  }

  // OUTPUT MANAGER FUNCTIONS

  /**
   * @template {{ id: string; updatedAt: string }} T
   * @param {{ save: (bytes: Uint8Array) => Promise<void> | void }} local
   * @param {{ collection: SignalReader<{ state: "loading" } | { state: "loaded"; data: Uint8Array | undefined } | { state: "error" }>, reload: () => Promise<void>, save: (bytes: Uint8Array) => Promise<void> }} remote
   * @param {SignalReader<boolean>} remoteReady
   * @param {SignalReader<Container<T>>} container
   * @param {import("~/common/self-describing.js").CollectionName} name
   * @returns {{ collection: SignalReader<{ state: "loading" } | { state: "loaded"; data: T[] } | { state: "error" }>, reload: () => Promise<void>, save: (items: T[]) => Promise<void> }}
   */
  managerProp(local, remote, remoteReady, container, name) {
    return {
      collection: computed(() => {
        const c = container();

        if (c.cid === undefined && remoteReady() && remote.collection().state === "loading") {
          return { state: "loading" };
        }

        return { state: "loaded", data: c.data };
      }),
      reload: remote.reload,
      save: async (/** @type {T[]} */ newItems) => {
        const adjustedContainer = await this.updateContainer({
          collection: newItems,
          previous: container(),
          name,
        });

        const bytes = this.save(adjustedContainer);
        await local.save(bytes);
      },
    };
  }

  // RENDER

  /**
   * @param {RenderArg} _
   */
  render({ html }) {
    return html`
      <dop-indexed-db
        group="${ifDefined(this.getAttribute(`group`))}"
        namespace="${ifDefined(this.getAttribute(`namespace`))}"
      ></dop-indexed-db>
    `;
  }
}

export default DaslBytesSyncOutputTransformer;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = DaslBytesSyncOutputTransformer;
export const NAME = "dtob-dasl-sync";

defineElement(NAME, CLASS);
```
### Output / Bytes / JSON

Raw data schema output to and from JSON Uint8Array.

```js
import { computed } from "~/common/signal.js";
import { OutputTransformer } from "../../base.js";
import {
  decodeJsonCollection,
  saveJsonCollection,
} from "~/common/lens.js";
import { defineElement } from "~/common/element.js";

/**
 * @import { OutputManagerDeputy } from "@specs/components/output/types.d.ts"
 * @import { Collaboration, Facet, PlaylistItem, Setting, Track } from "~/definitions/types.d.ts"
 */

/**
 * @extends {OutputTransformer<Uint8Array>}
 */
class JsonBytesOutputTransformer extends OutputTransformer {
  constructor() {
    super();

    const base = this.base();

    /** @type {OutputManagerDeputy} */
    const manager = {
      collaborations: {
        ...base.collaborations,
        collection: computed(() => {
          const col = base.collaborations.collection();
          if (col.state !== "loaded") return col;
          /** @type {Collaboration[]} */
          const data = decodeJsonCollection(col.data, "collaborations");
          return { state: "loaded", data };
        }),
        save: async (newCollaborations) => {
          await base.collaborations.save(
            /** @type {Uint8Array} */ (
              await saveJsonCollection(
                newCollaborations,
                "collaborations",
                null,
                true,
              )
            ),
          );
        },
      },
      facets: {
        ...base.facets,
        collection: computed(() => {
          const col = base.facets.collection();
          if (col.state !== "loaded") return col;
          /** @type {Facet[]} */
          const data = decodeJsonCollection(col.data, "facets");
          return { state: "loaded", data };
        }),
        save: async (newFacets) => {
          await base.facets.save(
            /** @type {Uint8Array} */ (
              await saveJsonCollection(newFacets, "facets", null, true)
            ),
          );
        },
      },
      playlistItems: {
        ...base.playlistItems,
        collection: computed(() => {
          const col = base.playlistItems.collection();
          if (col.state !== "loaded") return col;
          /** @type {PlaylistItem[]} */
          const data = decodeJsonCollection(col.data, "playlistItems");
          return { state: "loaded", data };
        }),
        save: async (newPlaylistItems) => {
          await base.playlistItems.save(
            /** @type {Uint8Array} */ (
              await saveJsonCollection(newPlaylistItems, "playlistItems", null, true)
            ),
          );
        },
      },
      settings: {
        ...base.settings,
        collection: computed(() => {
          const col = base.settings.collection();
          if (col.state !== "loaded") return col;
          /** @type {Setting[]} */
          const data = decodeJsonCollection(col.data, "settings");
          return { state: "loaded", data };
        }),
        save: async (newSettings) => {
          await base.settings.save(
            /** @type {Uint8Array} */ (
              await saveJsonCollection(newSettings, "settings", null, true)
            ),
          );
        },
      },
      tracks: {
        ...base.tracks,
        collection: computed(() => {
          const col = base.tracks.collection();
          if (col.state !== "loaded") return col;
          /** @type {Track[]} */
          const data = decodeJsonCollection(col.data, "tracks");
          return { state: "loaded", data };
        }),
        save: async (newTracks) => {
          await base.tracks.save(
            /** @type {Uint8Array} */ (
              await saveJsonCollection(newTracks, "tracks", null, true)
            ),
          );
        },
      },

      // Other
      ready: base.ready,
    };

    // Assign manager properties to class
    this.collaborations = manager.collaborations;
    this.facets = manager.facets;
    this.playlistItems = manager.playlistItems;
    this.settings = manager.settings;
    this.tracks = manager.tracks;
    this.ready = manager.ready;
  }
}

export default JsonBytesOutputTransformer;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = JsonBytesOutputTransformer;
export const NAME = "dtob-json";

defineElement(NAME, CLASS);```
### Output / Refiner / Default

Removes output state that is not meant to be saved to storage, such as ephemeral tracks. Ideally part of every theme.

```js
import * as IDB from "idb-keyval";

import { computed, signal } from "~/common/signal.js";
import { OutputTransformer } from "../../base.js";
import { defineElement } from "~/common/element.js";

const IDB_KEY_PLAYLISTS =
  "diffuse/transformer/output/refiner/default/playlistItems/ephemeral";
const IDB_KEY_TRACKS =
  "diffuse/transformer/output/refiner/default/tracks/ephemeral";

/**
 * @import { OutputManagerDeputy } from "@specs/components/output/types.d.ts"
 * @import { Collaboration, Facet, PlaylistItem, Setting, Track } from "~/definitions/types.d.ts"
 */

/**
 * @extends {OutputTransformer}
 */
class DefaultOutputRefinerTransformer extends OutputTransformer {
  constructor() {
    super();

    const base = this.base();

    // Restore stored ephemeral items
    IDB.get(IDB_KEY_PLAYLISTS).then((items) => {
      if (items) this.#ephemeralPlaylistItems.set(items);
    });

    IDB.get(IDB_KEY_TRACKS).then((items) => {
      if (items) this.#ephemeralTracks.set(items);
    });

    /** @type {OutputManagerDeputy} */
    const manager = {
      collaborations: base.collaborations,
      facets: {
        ...base.facets,
        collection: computed(() => {
          const col = base.facets.collection();
          if (col.state !== "loaded") return col;
          return { state: "loaded", data: col.data };
        }),
      },
      playlistItems: {
        ...base.playlistItems,
        collection: computed(() => {
          const col = base.playlistItems.collection();
          if (col.state !== "loaded") return col;
          return {
            state: "loaded",
            data: [...col.data, ...this.#ephemeralPlaylistItems.get()],
          };
        }),
        save: async (newPlaylists) => {
          /** @type {PlaylistItem[]} */
          const ephemeral = [];

          const filtered = newPlaylists.filter((p) => {
            if (p.ephemeral) {
              ephemeral.push(p);
              return false;
            } else {
              return true;
            }
          });

          await IDB.set(IDB_KEY_PLAYLISTS, ephemeral);
          this.#ephemeralPlaylistItems.set(ephemeral);

          await base.playlistItems.save(filtered);
        },
      },
      tracks: {
        ...base.tracks,
        collection: computed(() => {
          const col = base.tracks.collection();
          if (col.state !== "loaded") return col;
          return {
            state: "loaded",
            data: [...col.data, ...this.#ephemeralTracks.get()],
          };
        }),
        save: async (newTracks) => {
          /** @type {Track[]} */
          const ephemeral = [];

          const filtered = newTracks.filter((t) => {
            if (t.ephemeral) {
              ephemeral.push(t);
              return false;
            } else {
              return true;
            }
          });

          await IDB.set(IDB_KEY_TRACKS, ephemeral);
          this.#ephemeralTracks.set(ephemeral);

          await base.tracks.save(filtered);
        },
      },

      settings: base.settings,

      // Other
      ready: base.ready,
    };

    // Assign manager properties to class
    this.collaborations = manager.collaborations;
    this.facets = manager.facets;
    this.playlistItems = manager.playlistItems;
    this.settings = manager.settings;
    this.tracks = manager.tracks;
    this.ready = manager.ready;
  }

  // SIGNALS

  #ephemeralPlaylistItems = signal(/** @type {PlaylistItem[]} */ ([]));
  #ephemeralTracks = signal(/** @type {Track[]} */ ([]));

  // LIFECYCLE

  /** @override */
  connectedCallback() {
    if (this.hasAttribute("group")) {
      const actions = this.broadcast(IDB_KEY_TRACKS, {
        getEphemeralPlaylistItems: {
          strategy: "leaderOnly",
          fn: this.#ephemeralPlaylistItems.get,
        },
        setEphemeralPlaylistItems: {
          strategy: "replicate",
          fn: this.#ephemeralPlaylistItems.set,
        },
        getEphemeralTracks: {
          strategy: "leaderOnly",
          fn: this.#ephemeralTracks.get,
        },
        setEphemeralTracks: {
          strategy: "replicate",
          fn: this.#ephemeralTracks.set,
        },
      });

      if (actions) {
        this.#ephemeralPlaylistItems.set = actions.setEphemeralPlaylistItems;
        this.#ephemeralTracks.set = actions.setEphemeralTracks;

        actions.getEphemeralPlaylistItems().then((items) => {
          this.#ephemeralPlaylistItems.value = items;
        });

        actions.getEphemeralTracks().then((tracks) => {
          this.#ephemeralTracks.value = tracks;
        });
      }
    }

    super.connectedCallback();
  }
}

export default DefaultOutputRefinerTransformer;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = DefaultOutputRefinerTransformer;
export const NAME = "dtor-default";

defineElement(NAME, CLASS);
```
### Output / Refiner / Initial Contents

Sets the initial contents for an output on first load.

```js
import { computed } from "~/common/signal.js";
import { OutputTransformer } from "../../base.js";
import { defineElement } from "~/common/element.js";

import {
  STARTING_SET_URIS,
} from "~/common/facets/constants.js";
import { buildFacets } from "~/common/facets/utils.js";
import { isOutputInitialized, markOutputInitialized } from "~/common/output.js";

/**
 * @import {OutputManagerDeputy} from "@specs/components/output/types.d.ts"
 * @import {OutputConfiguratorElement} from "@specs/components/configurator/output/types.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @extends {OutputTransformer}
 */
class InitialContentsTransformer extends OutputTransformer {
  static NAME = "diffuse/transformer/output/refiner/initial-contents";

  constructor() {
    super();

    const base = this.base();

    // Mark initialized the first time real (non-empty) data is observed,
    // covering data arriving from another device via sync.
    this.effect(() => {
      const col = base.facets.collection();
      if (col.state !== "loaded") return;
      const data = Array.isArray(col.data) ? col.data : [];
      if (data.length === 0) return;
      markOutputInitialized(this.#selectedId());
    });

    /** @type {OutputManagerDeputy} */
    const manager = {
      collaborations: base.collaborations,
      facets: {
        ...base.facets,
        collection: computed(() => {
          const col = base.facets.collection();
          if (col.state !== "loaded") return col;

          // An empty backing output reports "loaded" with no data yet
          // (e.g. an indexed-db output returns undefined for a missing
          // key). Treat that as an empty collection.
          const data = Array.isArray(col.data) ? col.data : [];
          if (data.length > 0) {
            return { state: "loaded", data };
          }

          if (isOutputInitialized(this.#selectedId())) {
            return { state: "loaded", data };
          }

          // Determine starting set
          return { state: "loaded", data: buildFacets(STARTING_SET_URIS) };
        }),

        save: async (newFacets) => {
          // Persist the facets first so the resulting (non-empty) data is
          // visible before the initialized flag flips, avoiding a flash of
          // the empty collection while a fresh output pops its starting set.
          await base.facets.save(newFacets);
          markOutputInitialized(this.#selectedId());
        },
      },

      playlistItems: base.playlistItems,
      settings: base.settings,
      tracks: base.tracks,
      ready: base.ready,
    };

    this.collaborations = manager.collaborations;
    this.facets = manager.facets;
    this.playlistItems = manager.playlistItems;
    this.settings = manager.settings;
    this.tracks = manager.tracks;
    this.ready = manager.ready;
  }

  // METHODS

  /**
   * The id of the current output, used to scope the "initialized" flag per
   * output. When connected to an output configurator this is the id of the
   * selected sub-output; when connected directly to an output element it is
   * that element's own id. Falls back to "local" (the default/local storage).
   */
  #selectedId() {
    const output = /** @type {OutputConfiguratorElement | undefined} */ (
      this.output.signal()
    );
    if (!output) return "local";
    return typeof output.selected === "function"
      ? output.selected()?.id ?? "local"
      : output.id || "local";
  }
}

export default InitialContentsTransformer;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = InitialContentsTransformer;
export const NAME = "dtor-initial-contents";

defineElement(NAME, CLASS);
```
### Output / Refiner / Path Collections

Generates ephemeral playlists based on a path part of each track's URI. The 1-based part can be set using the `path-part` attribute (defaults to the first). Percent-encoded parts are decoded. Items with an id prefixed `path-collections/` are excluded from storage.

```js
import { computed, signal } from "~/common/signal.js";
import { OutputTransformer } from "../../base.js";
import { defineElement } from "~/common/element.js";

/**
 * @import {PlaylistItem, Track} from "~/definitions/types.d.ts"
 */

////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////

// Id prefix of the ephemeral items this transformer generates. Items with
// an id starting with this prefix are excluded from storage on save.
const ID_PREFIX = "path-collections";

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @extends {OutputTransformer}
 */
class PathCollectionsTransformer extends OutputTransformer {
  static NAME = "diffuse/transformer/output/refiner/path-collections";

  /**
   * @override
   */
  static observedAttributes = ["output-selector", "path-part"];

  /** 1-based path part of each track's URI to group playlists by. Defaults to 1. */
  #pathPart = signal(1);

  constructor() {
    super();

    const base = this.base();

    const ephemeralItems = computed(() => {
      const col = base.tracks.collection();
      return createEphemeralItems(
        col.state === "loaded" ? col.data : [],
        this.#pathPart.get(),
      );
    });

    this.facets = base.facets;
    this.collaborations = base.collaborations;
    this.settings = base.settings;
    this.playlistItems = {
      ...base.playlistItems,
      collection: computed(() => {
        const col = base.playlistItems.collection();
        if (col.state !== "loaded") return col;
        return { state: "loaded", data: [...col.data, ...ephemeralItems()] };
      }),
      /** @type {(typeof base.playlistItems.save)} */
      save: async (items) => {
        await base.playlistItems.save(
          (items || []).filter((p) => !p.id.startsWith(`${ID_PREFIX}/`)),
        );
      },
    };
    this.tracks = base.tracks;

    this.ready = base.ready;
  }

  /**
   * @override
   * @param {string} name
   * @param {string} oldValue
   * @param {string} newValue
   */
  attributeChangedCallback(name, oldValue, newValue) {
    super.attributeChangedCallback(name, oldValue, newValue);

    if (name === "path-part") this.#pathPart.set(parsePathPart(newValue));
  }
}

/**
 * One ephemeral playlist item per track: the playlist is named after the
 * track's nth path part, and the item matches exactly that track (criteria
 * only support exact equality). Grouping the items by their `playlist` name
 * (see `Playlist.gather`) then yields one playlist per path part containing
 * all of its tracks.
 *
 * @param {Track[]} tracks
 * @param {number} pathPart
 * @returns {PlaylistItem[]}
 */
function createEphemeralItems(tracks, pathPart) {
  /** @type {PlaylistItem[]} */
  const items = [];

  tracks.forEach((track) => {
    const segment = pathSegment(track.uri, pathPart);
    if (!segment) return;

    items.push({
      $type: "sh.diffuse.output.playlistItem",
      id: `${ID_PREFIX}/${track.id}`,
      playlist: segment,
      criteria: [{ field: "uri", value: /** @type {any} */ (track.uri) }],
      ephemeral: true,
    });
  });

  return items;
}

/**
 * @param {string} uri
 * @param {number} pathPart
 * @returns {string | undefined}
 */
function pathSegment(uri, pathPart) {
  try {
    const url = new URL(uri);
    const segment = url.pathname.split("/").filter(Boolean)[pathPart - 1];

    if (!segment) return undefined;

    try {
      return decodeURIComponent(segment);
    } catch {
      return segment;
    }
  } catch {
    return undefined;
  }
}

/**
 * @param {string | null} value
 * @returns {number}
 */
function parsePathPart(value) {
  const parsed = Number.parseInt(value ?? "", 10);
  return Number.isNaN(parsed) || parsed < 1 ? 1 : parsed;
}

export default PathCollectionsTransformer;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = PathCollectionsTransformer;
export const NAME = "dtor-path-collections";

defineElement(NAME, CLASS);
```
### Output / String / JSON

Raw data schema output to and from JSON UTF8 string.

```js
import { computed } from "~/common/signal.js";
import { OutputTransformer } from "../../base.js";
import {
  decodeJsonCollection,
  saveJsonCollection,
} from "~/common/lens.js";
import { defineElement } from "~/common/element.js";

/**
 * @import { OutputManagerDeputy } from "@specs/components/output/types.d.ts"
 * @import { Collaboration, Facet, PlaylistItem, Setting, Track } from "~/definitions/types.d.ts"
 * @import { CollectionName } from "~/common/self-describing.js"
 */

/**
 * @extends {OutputTransformer<string>}
 */
class JsonStringOutputTransformer extends OutputTransformer {
  constructor() {
    super();

    const base = this.base();

    /** @type {OutputManagerDeputy} */
    const manager = {
      collaborations: {
        ...base.collaborations,
        collection: computed(() => {
          const col = base.collaborations.collection();
          if (col.state !== "loaded") return col;
          /** @type {Collaboration[]} */
          const data = decodeJsonCollection(col.data, "collaborations");
          return { state: "loaded", data };
        }),
        save: async (newCollaborations) => {
          await base.collaborations.save(
            /** @type {string} */ (
              await saveJsonCollection(newCollaborations, "collaborations", null)
            ),
          );
        },
      },
      facets: {
        ...base.facets,
        collection: computed(() => {
          const col = base.facets.collection();
          if (col.state !== "loaded") return col;
          /** @type {Facet[]} */
          const data = decodeJsonCollection(col.data, "facets");
          return { state: "loaded", data };
        }),
        save: async (newFacets) => {
          await base.facets.save(
            /** @type {string} */ (
              await saveJsonCollection(newFacets, "facets", null)
            ),
          );
        },
      },
      playlistItems: {
        ...base.playlistItems,
        collection: computed(() => {
          const col = base.playlistItems.collection();
          if (col.state !== "loaded") return col;
          /** @type {PlaylistItem[]} */
          const data = decodeJsonCollection(col.data, "playlistItems");
          return { state: "loaded", data };
        }),
        save: async (newPlaylistItems) => {
          await base.playlistItems.save(
            /** @type {string} */ (
              await saveJsonCollection(newPlaylistItems, "playlistItems", null)
            ),
          );
        },
      },
      settings: {
        ...base.settings,
        collection: computed(() => {
          const col = base.settings.collection();
          if (col.state !== "loaded") return col;
          /** @type {Setting[]} */
          const data = decodeJsonCollection(col.data, "settings");
          return { state: "loaded", data };
        }),
        save: async (newSettings) => {
          await base.settings.save(
            /** @type {string} */ (
              await saveJsonCollection(newSettings, "settings", null)
            ),
          );
        },
      },
      tracks: {
        ...base.tracks,
        collection: computed(() => {
          const col = base.tracks.collection();
          if (col.state !== "loaded") return col;
          /** @type {Track[]} */
          const data = decodeJsonCollection(col.data, "tracks");
          return { state: "loaded", data };
        }),
        save: async (newTracks) => {
          await base.tracks.save(
            /** @type {string} */ (
              await saveJsonCollection(newTracks, "tracks", null)
            ),
          );
        },
      },

      // Other
      ready: base.ready,
    };

    // Assign manager properties to class
    this.collaborations = manager.collaborations;
    this.facets = manager.facets;
    this.playlistItems = manager.playlistItems;
    this.settings = manager.settings;
    this.tracks = manager.tracks;
    this.ready = manager.ready;
  }
}

export default JsonStringOutputTransformer;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = JsonStringOutputTransformer;
export const NAME = "dtos-json";

defineElement(NAME, CLASS);```
## Upload
### Dropbox

Uploads and deletes files on Dropbox using the Dropbox v2 HTTP API.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { DEFAULT_APP_KEY, PKCE_VERIFIER_KEY, SCHEME } from "~/components/input/dropbox/constants.js";
import { generatePKCEPair } from "~/components/input/dropbox/common.js";

/**
 * @import {UploadActions, UploadSchemeProvider} from "@specs/components/upload/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<UploadActions>}
 * @implements {UploadSchemeProvider}
 */
class DropboxUpload extends DiffuseElement {
  static NAME = "diffuse/upload/dropbox";
  static WORKER_URL = "components/upload/dropbox/worker.js";

  SCHEME = SCHEME;

  /** @type {string} */
  appKey = DEFAULT_APP_KEY;

  static observedAttributes = ["app-key"];

  /**
   * @override
   * @param {string} name
   * @param {string} old
   * @param {string} next
   */
  attributeChangedCallback(name, old, next) {
    super.attributeChangedCallback(name, old, next);
    if (name === "app-key" && next !== null) this.appKey = next;
  }

  constructor() {
    super();

    /** @type {ProxiedActions<UploadActions>} */
    this.proxy = this.workerProxy();

    this.consult = this.proxy.consult;
    this.upload = this.proxy.upload;
    this.delete = this.proxy.delete;
    this.createSource = this.proxy.createSource;
  }

  // 🛠️

  async authorize() {
    localStorage.setItem("oauth/callback/redirect_path", location.pathname + location.search);

    const { verifier, challenge } = await generatePKCEPair();
    localStorage.setItem(PKCE_VERIFIER_KEY, verifier);

    const params = new URLSearchParams({
      response_type: "code",
      client_id: this.appKey,
      redirect_uri: location.origin + "/oauth/callback/",
      token_access_type: "offline",
      code_challenge: challenge,
      code_challenge_method: "S256",
    });

    location.assign(`https://www.dropbox.com/oauth2/authorize?${params}`);
  }
}

export default DropboxUpload;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = DropboxUpload;
export const NAME = "du-dropbox";

defineElement(NAME, CLASS);
```
### Firkin

Uploads files to Firkin and records them in the account's file registry.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { SCHEME } from "~/common/firkin/files.js";

/**
 * @import {UploadActions, UploadSchemeProvider} from "@specs/components/upload/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * Uploader that stores audio on Firkin and records file names in the account's
 * file registry.
 *
 * The worker reads the shared Firkin session from IndexedDB, so this element
 * only needs the Connect / Firkin page to have been used once.
 *
 * @implements {ProxiedActions<UploadActions>}
 * @implements {UploadSchemeProvider}
 */
class FirkinUpload extends DiffuseElement {
  static NAME = "diffuse/upload/firkin";
  static WORKER_URL = "components/upload/firkin/worker.js";

  SCHEME = SCHEME;

  /** Where the Firkin account is connected. */
  CONNECT_PATH = "facets/connect/firkin/index.tile";

  constructor() {
    super();

    /** @type {ProxiedActions<UploadActions>} */
    const proxy = this.workerProxy();

    this.consult = proxy.consult;
    this.upload = proxy.upload;
    this.delete = proxy.delete;
    this.createSource = proxy.createSource;
  }
}

export default FirkinUpload;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = FirkinUpload;
export const NAME = "du-firkin";

defineElement(NAME, CLASS);
```
### S3

Uploads and deletes files in an S3-compatible bucket using the S3 HTTP API. Buckets are connected on the S3 connect page.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { SCHEME } from "~/components/input/s3/constants.js";

/**
 * @import {UploadActions, UploadSchemeProvider} from "@specs/components/upload/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<UploadActions>}
 * @implements {UploadSchemeProvider}
 */
class S3Upload extends DiffuseElement {
  static NAME = "diffuse/upload/s3";
  static WORKER_URL = "components/upload/s3/worker.js";

  SCHEME = SCHEME;

  /** Where a bucket for this scheme is connected. */
  CONNECT_PATH = "facets/connect/s3/index.tile";

  constructor() {
    super();

    /** @type {ProxiedActions<UploadActions>} */
    this.proxy = this.workerProxy();

    this.consult = this.proxy.consult;
    this.upload = this.proxy.upload;
    this.delete = this.proxy.delete;
    this.createSource = this.proxy.createSource;
  }
}

export default S3Upload;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = S3Upload;
export const NAME = "du-s3";

defineElement(NAME, CLASS);
```
### WebDAV

Uploads and deletes files on a WebDAV server using PUT and DELETE requests.

```js
import { defineElement, DiffuseElement } from "~/common/element.js";
import { SCHEME } from "~/components/input/webdav/constants.js";

/**
 * @import {UploadActions, UploadSchemeProvider} from "@specs/components/upload/types.d.ts"
 * @import {ProxiedActions} from "~/common/worker.d.ts"
 */

////////////////////////////////////////////
// ELEMENT
////////////////////////////////////////////

/**
 * @implements {ProxiedActions<UploadActions>}
 * @implements {UploadSchemeProvider}
 */
class WebdavUpload extends DiffuseElement {
  static NAME = "diffuse/upload/webdav";
  static WORKER_URL = "components/upload/webdav/worker.js";

  SCHEME = SCHEME;

  /** Where a server for this scheme is connected. */
  CONNECT_PATH = "facets/connect/webdav/index.tile";

  constructor() {
    super();

    /** @type {ProxiedActions<UploadActions>} */
    this.proxy = this.workerProxy();

    this.consult = this.proxy.consult;
    this.upload = this.proxy.upload;
    this.delete = this.proxy.delete;
    this.createSource = this.proxy.createSource;
  }
}

export default WebdavUpload;

////////////////////////////////////////////
// REGISTER
////////////////////////////////////////////

export const CLASS = WebdavUpload;
export const NAME = "du-webdav";

defineElement(NAME, CLASS);
```
