Skip to content

Vanilla JavaScript ​

tscache couples to a framework in two places only: the client's lifecycle, and the step from a promise to the framework's reactivity. The integration snippets put the lifecycle in one framework-neutral module and add the second step per framework. Every snippet type-checks against the built package in CI; copy them into your app.

The connection ​

connect(open, seeds?) connects once, replaces the client when its worker is lost, and disposes it on teardown. open runs once per client, so it can read the fetcher's current credentials. seeds are a server's reads to start each client's cache from (Server rendering).

ts
// The client's lifecycle, the same in every framework: connect once,
// replace the client when the worker behind it is lost, dispose on
// teardown. A framework adapter turns `state` into its own reactivity (a
// store, a signal, a ref) and reads through `cache()`; the rest of its job
// is turning the read's promise into that reactivity too.

import {
  type CacheConfig,
  type CacheHandle,
  type TscacheClient,
  TscacheError,
} from "@anishbenji/tscache";
import { hydrateRead, type ServerRead } from "./hydration";

/**
 * Where the connection stands. Every change is a new object, so a snapshot
 * compares by identity.
 */
export type ConnectionState =
  | { readonly status: "connecting" }
  | { readonly status: "connected"; readonly client: TscacheClient }
  | { readonly status: "failed"; readonly error: unknown };

/** A server's read of one cache, to start the browser's cache from. */
export interface Seed {
  config: CacheConfig;
  read: ServerRead;
}

/**
 * Its members need no `this`: pass `subscribe`, or a getter of `state`,
 * as they are (React's useSyncExternalStore takes them so).
 */
export interface Connection {
  readonly state: ConnectionState;
  /** Calls `listener` after each change of `state`; returns the unsubscribe. */
  subscribe(listener: () => void): () => void;
  /**
   * `client`'s handle for `config`. Every call goes to `client.cache()`,
   * which opens the same cache for an equal config and rejects a
   * conflicting one with ConfigError (N4, N20): whether two configs name
   * one cache is the library's call, never this code's. On every client, a
   * cache's seed goes in before its first handle is given out, so no read
   * runs ahead of it.
   */
  cache(client: TscacheClient, config: CacheConfig): Promise<CacheHandle>;
  /** Disposes the client and stops replacing it. Idempotent. */
  dispose(): Promise<void>;
}

const CONNECTING: ConnectionState = { status: "connecting" };

// Bundlers replace the exact text `process.env.NODE_ENV` at build time (Vite
// in development and production, webpack, Bun with --production), so it is
// read bare, as the library's own development warnings read it. A page
// without `process` that no bundler prepared counts as production.
declare const process: { env: { NODE_ENV?: string } };

/** Whether this is a development build. */
function development(): boolean {
  try {
    return process.env.NODE_ENV !== "production";
  } catch {
    return false;
  }
}

/**
 * What a warning says of `error`: its name, and a TscacheError's `code` when
 * it has one. Never its message: an error from outside the library, such as
 * `JSON.parse`'s, can quote the snapshot it refused, and the snapshot carries
 * the page's data.
 */
function nameOf(error: unknown): string {
  if (!(error instanceof Error)) return "a non-Error rejection";
  const code: unknown =
    error instanceof TscacheError
      ? (error as { code?: unknown }).code
      : undefined;
  return typeof code === "string" ? `${error.name} ${code}` : error.name;
}

/**
 * Says, in development builds only, that cache `id`'s seed was not applied.
 * Only the error's name goes to the console (`nameOf`), never the error, its
 * message or the snapshot: the snapshot carries the page's data.
 */
function warnNotSeeded(id: string, error: unknown): void {
  if (!development()) return;
  const why = nameOf(error);
  console.warn(
    `tscache: the server's snapshot for cache "${id}" was not applied (${why}), so the cache fetches that range instead; printed in development builds only.`,
  );
}

/**
 * Whether `error` is a disposed client's answer, which every pending and
 * later call gets: the application disposed the client itself, which fires
 * no workerLost, so `live` cannot tell.
 */
function closed(error: unknown): boolean {
  return error instanceof TscacheError && error.message === "client disposed";
}

/**
 * The applying of `seeds`: given a client and a cache id, the applying of
 * that cache's seed to that client, started on the first ask and shared by
 * every later one; undefined for a cache without a seed. It rejects only
 * when the cache cannot be opened: a snapshot that fails to apply leaves
 * the cache not seeded (decision 98 C). The warning is given only while
 * `live` holds for the client and the client was not disposed: a client
 * lost or disposed meanwhile fails every pending call, `hydrate` included,
 * and that is no news about the snapshot.
 */
function seeder(
  seeds: readonly Seed[],
  live: (client: TscacheClient) => boolean,
): (client: TscacheClient, id: string) => Promise<void> | undefined {
  const byId = new Map(seeds.map((seed) => [seed.config.id, seed]));
  /** Per client, the applying of each cache's seed, started on the first ask. */
  const seedings = new WeakMap<TscacheClient, Map<string, Promise<void>>>();
  return (client, id) => {
    const seed = byId.get(id);
    if (seed === undefined) return undefined;
    let ofClient = seedings.get(client);
    if (ofClient === undefined) {
      ofClient = new Map();
      seedings.set(client, ofClient);
    }
    let applying = ofClient.get(id);
    if (applying === undefined) {
      applying = client.cache(seed.config).then((cache) =>
        hydrateRead(cache, seed.read).then(
          () => {},
          (error: unknown) => {
            if (live(client) && !closed(error)) warnNotSeeded(id, error);
          },
        ),
      );
      ofClient.set(id, applying);
    }
    return applying;
  };
}

/**
 * Connects with `open`, and again each time the worker behind the client
 * is lost, as when the tab hosting the SharedWorker crashes: the new client
 * starts a new worker with an empty cache (docs/guides/worker-setup.md).
 * `open` runs once per client, so it can read the fetcher's current
 * credentials.
 *
 * Every client gets the seeds, a replacement's empty worker included:
 * `hydrate` refuses a snapshot of another dataset version and never
 * touches what a cache covers, so a page-old seed cannot replace newer
 * data (N39). Each seed is applied once per client, when its cache is
 * first asked for, into the cache opened with the seed's own config: a
 * reader asking for a conflicting config is refused by the client's check,
 * rather than handed coverage read on another grid.
 *
 * A snapshot that fails to apply counts as "not seeded" (decision 98 C,
 * architecture §2.8: hydration is an optimisation, never a requirement for
 * correctness): `cache()` still hands out the cache, which fetches what the
 * seed would have filled, and a development build warns once per client
 * and cache with the error's name (never its message, which can quote the
 * snapshot), unless the client was lost or disposed or the connection
 * disposed meanwhile. `hydrate` validates the whole
 * snapshot before it changes anything, so a refused snapshot leaves
 * nothing behind; a write that fails part way (an allocation failure)
 * keeps only the parts it finished, each recorded as coverage. A worker
 * without `hydrate` is not seeded either, without a warning
 * (`hydrateRead`). The seed is not applied again on that client. Only a
 * seed's cache that cannot be opened with the seed's config rejects: every
 * later `cache()` call for it on that client rejects with the same error
 * until a replacement client seeds afresh.
 */
export function connect(
  open: () => Promise<TscacheClient>,
  seeds: readonly Seed[] = [],
): Connection {
  let state = CONNECTING;
  let disposed = false;
  const seeding = seeder(
    seeds,
    (client) =>
      !disposed && state.status === "connected" && state.client === client,
  );
  const listeners = new Set<() => void>();

  function set(next: ConnectionState): void {
    state = next;
    for (const listener of listeners) listener();
  }

  function start(): void {
    open().then(
      (client) => {
        if (disposed) return void client.dispose();
        client.on("workerLost", () => {
          if (disposed) return;
          set(CONNECTING);
          start();
        });
        set({ status: "connected", client });
      },
      (error: unknown) => {
        if (!disposed) set({ status: "failed", error });
      },
    );
  }

  start();
  return {
    get state() {
      return state;
    },
    subscribe(listener) {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    async cache(client, config) {
      await seeding(client, config.id);
      return client.cache(config);
    },
    async dispose() {
      if (disposed) return;
      disposed = true;
      listeners.clear();
      if (state.status === "connected") await state.client.dispose();
    },
  };
}

A series ​

A series shows the cache's answer for the latest range it was asked for, and drops answers a newer range overtook. A read rejected because the worker was lost is not an error: the next client reads again.

ts
// tscache without a framework: a series shows the cache's answer for the
// range on screen, and drops answers that a newer range has overtaken. It
// follows the cache's changes, from any tab (shared/changes.ts): an event
// over the range on screen reads it again, at most once per frame. One
// connection (shared/connection.ts) serves every series of the page.

import type { CacheConfig, GetResult, Range } from "@anishbenji/tscache";
import { type Frame, type ReadMode, ViewReads } from "../shared/changes";
import type { Connection } from "../shared/connection";

/** The cache's answer for a range. */
export interface Answer {
  range: Range;
  result: GetResult;
}

export interface SeriesOptions {
  config: CacheConfig;
  /** Draws an answer. Only the answer for the latest range arrives here. */
  render(answer: Answer): void;
  /** A read failed, or the client could not connect. Default: reportError. */
  fail?(error: unknown): void;
  /** For tests: the frame scheduler of the change watch. */
  frame?: Frame;
}

export interface Series {
  /** Reads `range` and renders the answer, unless a later show() overtakes it. */
  show(range: Range): void;
  /**
   * Reads `range` (by default the range on screen) from the cache alone,
   * without fetching: after a put of pushed data, say. It becomes the range
   * on screen. Skipped while a show()'s read is still in flight, whose
   * answer replaces this one anyway.
   */
  refresh(range?: Range): void;
  /**
   * Stops rendering and following changes; an answer still in flight is
   * dropped, and later show() and refresh() calls (from a callback still
   * pending) do nothing.
   */
  dispose(): void;
}

export function series(
  connection: Connection,
  { config, render, fail = reportError, frame }: SeriesOptions,
): Series {
  let range: Range | undefined;
  let latest = 0;
  /** The request number of the show() read in flight, or 0. */
  let showing = 0;
  let disposed = false;
  // Holds a change during a fetching read, keeps failure labels, and
  // releases after the answer landed (shared/changes.ts).
  const views = new ViewReads({
    shown: () => range,
    interval: config.interval,
    alignmentOffset: config.alignmentOffset ?? 0,
    reread: () => read("auto"),
    ...(frame === undefined ? {} : { frame }),
  });

  function read(mode: ReadMode): void {
    if (disposed) return;
    const state = connection.state;
    if (state.status === "failed") {
      fail(state.error);
      return;
    }
    if (state.status !== "connected" || range === undefined) return;
    const request = ++latest;
    const asked = range;
    const reading = views.read(
      connection.cache(state.client, config),
      asked,
      state,
      mode,
    );
    if (!reading.cacheOnly) showing = request;
    reading.answer
      .then(
        (result) => {
          if (request === latest) render({ range: asked, result });
        },
        (error: unknown) => {
          // A lost worker rejects what was pending; the connection's next
          // client reads again, so only a failure on a live client counts.
          if (request === latest && connection.state === state) fail(error);
        },
      )
      .finally(() => {
        if (showing === request) showing = 0;
      });
  }

  function refresh(next = range): void {
    if (showing !== 0 || next === undefined) return;
    range = next;
    read("cache");
  }

  // A new client (the first, or one replacing a lost worker) reads again.
  const unsubscribe = connection.subscribe(() => read("fetch"));
  return {
    show(next) {
      range = next;
      read("fetch");
    },
    refresh,
    dispose() {
      disposed = true;
      unsubscribe();
      views.dispose();
      latest++;
    },
  };
}

A client-only page ​

ts
// A page with one chart, client-only. Connect once, give the chart a
// series, show the range on screen.

import { type ClientOptions, createClient } from "@anishbenji/tscache";
import { candles, describe, lastDays } from "../shared/candles";
import { connect } from "../shared/connection";
import { series } from "./series";

/**
 * A page with one chart, showing the last 90 days. `options` carries the
 * worker and fetcher URLs as your bundler serves them
 * (docs/guides/worker-setup.md). Returns the page's teardown; a page that
 * simply closes needs none, since a client disposes itself on `pagehide`.
 */
export function startPage(
  options: ClientOptions,
  element: HTMLElement,
): () => Promise<void> {
  const connection = connect(() => createClient(options));
  const chart = series(connection, {
    config: candles,
    // A chart library would take result.timestamps and result.fields here.
    render: ({ result }) => {
      element.textContent = describe(result);
    },
  });
  chart.show(lastDays(90, Date.now()));
  // Scrolling the chart calls chart.show() with its visible range; the
  // cache fetches only what it does not hold.
  return async () => {
    chart.dispose();
    await connection.dispose();
  };
}

Server-rendered ​

The server's half reads with one in-process client per process and writes the answer as markup and as a JSON script element:

ts
// A server-rendered page without a framework, the server's half. The
// server reads with its own client and writes the answer into the page
// twice: as markup, and as data the browser starts its cache from
// (ssr-browser.ts). Without the browser's half, this is a page rendered on
// the server alone.

import { candles, describe, lastDays } from "../shared/candles";
import { dehydrate, jsonScript, SERVER_READ } from "../shared/hydration";
import { type ServerOptions, serverReader } from "../shared/server";

/**
 * The page renderer for this server process; create it once at startup,
 * since it owns the process's client (docs/guides/worker-setup.md, "Server
 * rendering").
 */
export function pageRenderer(
  options: ServerOptions,
): (now: number) => Promise<string> {
  const reader = serverReader(options);
  return async (now) => {
    const read = await reader(candles, lastDays(90, now));
    // describe() writes numbers only; HTML-escape anything that holds text.
    return `<p id="chart">${describe(read.result)}</p>${jsonScript(SERVER_READ, dehydrate(read))}`;
  };
}

The browser's half keeps the server's markup until its own answer arrives, and seeds its cache:

ts
// A server-rendered page without a framework, the browser's half. It keeps
// the server's markup until its own answer arrives, and fetches only what
// the server's answer did not cover (the provisional last day, say).

import { type ClientOptions, createClient } from "@anishbenji/tscache";
import { candles, describe } from "../shared/candles";
import { connect } from "../shared/connection";
import {
  type Dehydrated,
  readJson,
  rehydrate,
  SERVER_READ,
} from "../shared/hydration";
import { series } from "./series";

/** Takes over the server's page. Returns its teardown. */
export function hydratePage(options: ClientOptions): () => Promise<void> {
  const element = document.getElementById("chart");
  if (element === null) throw new Error("the page has no #chart");
  const read = rehydrate(candles, readJson<Dehydrated>(SERVER_READ));
  const connection = connect(
    () => createClient(options),
    [{ config: candles, read }],
  );
  const chart = series(connection, {
    config: candles,
    render: ({ result }) => {
      element.textContent = describe(result);
    },
  });
  // The server's range: its covered parts come from the seed, so the
  // first answer costs at most the uncovered tail.
  chart.show(read.range);
  return async () => {
    chart.dispose();
    await connection.dispose();
  };
}

The helpers they use are integrations/shared/server.ts and integrations/shared/hydration.ts.

A complete app ​

The vanilla reference client (reference/vanilla) adds scrolling, both chart libraries, a live feed and the credential refresh; examples/vanilla-uplot is a live metrics dashboard with a volatile tail and a sparse event series.