entrySource

tcmts.cli.web.entrySource · #gwweujne · term · runs on the server

uses node:path

The entry module for a build root: start the app, or show why it can't run in the browser.

import type { Codebase } from "#codebase/tcmts/cli/codebase";
import { escapeHtml } from "#codebase/tcmts/cli/web";
import type { AppState } from "#codebase/tcmts/cli/web";
import { exportId } from "#codebase/tcmts/core/hash";
import path from "node:path";

export function entrySource(cb: Codebase, appName: string, s: AppState, cacheRel: string): string {
  if (s.plan.errors.length) {
    const html = `<pre style="color:#b00;white-space:pre-wrap;font:14px ui-monospace,monospace;padding:1em">${escapeHtml(s.plan.errors.join("\n\n"))}</pre>`;
    return `// ${appName} can't run in the browser yet\ndocument.body.innerHTML = ${JSON.stringify(html)};\n`;
  }
  const rec = cb.store.getDef(s.hash)!;
  const from = `${cacheRel}/${path.basename(cb.modulePath(rec.componentHash))}`;
  if (s.react) {
    // the app is a component: render it into the page with the React DOM of the same version
    return [
      `// generated by tcm: ${appName} ${rec.hash}`,
      `import { createElement } from "${s.react.react}";`,
      `import { createRoot, hydrateRoot } from "${s.react.dom}/client";`,
      `import { ${exportId(rec.hash)} as App } from "${from}";`,
      `// cookies the server set while streaming this page, after its headers had gone out`,
      `declare const __TCM_COOKIES__: string | undefined;`,
      `if (typeof __TCM_COOKIES__ === "string") void fetch((globalThis.__TCM_BASE__ ?? "") + "/__tcm/cookies/" + __TCM_COOKIES__, { method: "POST" });`,
      `const root = document.getElementById("app")!;`,
      `// the server rendered the first paint: take it over, rather than render it again`,
      `if (root.hasChildNodes()) hydrateRoot(root, createElement(App));`,
      `else createRoot(root).render(createElement(App));`,
      "",
    ].join("\n");
  }
  return `// generated by tcm: ${appName} ${rec.hash}\nimport { ${exportId(rec.hash)} as main } from "${from}";\nconst app: unknown = main;\nif (typeof app === "function") await app();\n`;
}

uses

used by