REACT_CACHE

tcmts.cli.react_api.REACT_CACHE · #7xq2gwud · term · runs anywhere

The generated tcm-cache.js: React's cache and cacheSignal, as code tcm renders imports them. React's own work only in its server components' build, which tcm doesn't use; in the one it does, cache keeps nothing and cacheSignal is null. Here, in a request tcm answers (a page rendered on the server, a server component's tree, a server function call), what cache keeps lasts the request, shared by everything rendered for it (by its arguments: values by value, objects by identity, as React's), and cacheSignal is the request's signal, aborted if the browser goes away. Anywhere else (the browser, a test) they're React's: nothing kept.

export const REACT_CACHE = `// generated by tcm — do not edit: React's cache and cacheSignal, for code tcm runs on the server
const now = () => globalThis.__tcmCall?.();
export function cache(fn) {
  return function cached(...args) {
    const call = now();
    if (!call) return fn.apply(this, args);
    let node = call.memo.get(fn);
    if (!node) call.memo.set(fn, (node = { p: new Map(), o: new WeakMap() }));
    for (const a of args) {
      const table = (typeof a === "object" && a !== null) || typeof a === "function" ? node.o : node.p;
      let next = table.get(a);
      if (!next) table.set(a, (next = { p: new Map(), o: new WeakMap() }));
      node = next;
    }
    if (node.done) {
      if (node.failed) throw node.value;
      return node.value;
    }
    try {
      node.value = fn.apply(this, args);
    } catch (e) {
      node.failed = true;
      node.value = e;
      throw e;
    } finally {
      node.done = true;
    }
    return node.value;
  };
}
export function cacheSignal() {
  return now()?.signal ?? null;
}
`

used by