import { pathToFileURL } from 'node:url'; import { Window } from 'happy-dom'; import { getSsrSnapshotBuilder, SSR_MODULE_RESOLVER_KEY, SSR_ORCHESTRATED_VALUE } from './protocol/ssrSnapshot'; import { setInnerHTML } from './setInnerHTML'; /** * globalThis を差し替える renderToString の並列実行を防止する Mutex。 * 同一 Node プロセス内で複数リクエストが同時に renderToString を呼んでも * シリアライズされ、グローバル状態の衝突を防ぐ。 */ class Mutex { private _queue: (() => void)[] = []; private _locked = false; async acquire(): Promise<() => void> { if (this._locked) { await new Promise(resolve => this._queue.push(resolve)); } this._locked = true; return () => { this._locked = false; this._queue.shift()?.(); }; } } const renderMutex = new Mutex(); export const GLOBALS_KEYS = [ 'document', 'customElements', 'HTMLElement', 'DocumentFragment', 'Node', 'NodeFilter', 'Comment', 'Text', 'MutationObserver', 'ShadowRoot', 'Element', 'HTMLTemplateElement', // URL を持つコンポーネント(@wcstack/router 等)が window.location / // history を読めるようにする(docs/ssr-router-design.md §3.1)。 'window', 'location', 'history', // コンポーネントが発火するイベントをレンダリングウィンドウの realm に揃える。 // Node ネイティブの CustomEvent は happy-dom の EventTarget に拒否される // ("parameter 1 is not of type 'Event'")。vitest の happy-dom 環境では // グローバルが happy-dom 側なので隠れ、素の Node サーバーでだけ顕在化する 'Event', 'CustomEvent', ]; export function installGlobals(window: Window): () => void { const saved: Record = {}; for (const key of GLOBALS_KEYS) { saved[key] = (globalThis as any)[key]; (globalThis as any)[key] = (window as any)[key]; } // URL.createObjectURL を無効化して、 // loadFromInnerScript が base64 data: URL フォールバックを使うようにする const origCreateObjectURL = URL.createObjectURL; (URL as any).createObjectURL = undefined; return () => { URL.createObjectURL = origCreateObjectURL; for (const key of GLOBALS_KEYS) { (globalThis as any)[key] = saved[key]; } }; } export function installBaseUrl(baseUrl: string): () => void { const OrigURL = globalThis.URL; const base = baseUrl; globalThis.URL = class extends OrigURL { constructor(input: string | URL, inputBase?: string | URL) { if (typeof input === 'string' && input.startsWith('/') && inputBase === undefined) { super(input, base); } else { super(input as string, inputBase); } } } as typeof URL; // 静的メソッドを引き継ぐ globalThis.URL.createObjectURL = OrigURL.createObjectURL; globalThis.URL.revokeObjectURL = OrigURL.revokeObjectURL; return () => { globalThis.URL = OrigURL; }; } /** * 同期の bootstrap 関数、または非同期ローダー。 * `HTMLElement` を継承するクラスはモジュール評価時にグローバルの `HTMLElement` を * 参照するため、純 Node 環境ではトップレベル import できないパッケージがある。 * その場合は `async () => (await import('@wcstack/router')).bootstrapRouter()` の * ように非同期ローダーを渡す — 呼び出しは installGlobals の後なので、モジュール * 評価時にはグローバルが揃っている(docs/ssr-router-design.md §3.1)。 */ export type BootstrapFunction = () => void | Promise; export interface RenderOptions { /** 相対 URL を解決するベース URL (例: "http://localhost:3001")。省略時は `url` の origin */ baseUrl?: string; /** bootstrap 関数の配列。省略時は @wcstack/state を自動ロード */ bootstraps?: BootstrapFunction[]; /** * このリクエストの完全 URL (例: "http://localhost:3000/products/1")。 * `window.location` / `document.baseURI` に反映される。ルーティングする * コンポーネント(@wcstack/router 等)のサーバーレンダリングに必要 * (docs/ssr-router-design.md §3.1)。 */ url?: string; /** * `` へ注入する `` の値。`url` 指定時の既定は "/"。 * ブラウザで `` を置く SPA と同じ条件をサーバー内に再現する * (深い URL での basename 誤認を防ぐ)。サブパス配備では明示する。 */ baseHref?: string; /** * ページが ready になるのを待つ上限(ミリ秒・既定 30,000)。 * * **無効(無制限)になる値**: `0` 以下・`NaN`・`2,147,483,647`(2^31−1)より大きい値 * (`Infinity` を含む)。上限を外したいときは `0` を渡すのが正規の書き方。 * 大きすぎる値を無制限に倒しているのは Node の都合で、`setTimeout` は 2^31−1 を超える * delay(`Infinity` も)を **1 ms に丸める** — 「上限を上げたつもり」が即時タイムアウトに * 反転するため(実測: `Infinity` で 13 ms で reject)。 * * **プロセス毒性の防波堤**(サイクル 4 の指摘 3)。`renderToString` は `globalThis` を * 差し替えるため `renderMutex` で直列化しており、解放は `finally` にある。1 ページの * 不具合で `waitForReady` が永久 pending になると `finally` に到達せず、**以後そのプロセスの * 健全なページまで永久に返らなくなる**(実測済み)。上限を超えたら reject して `finally` へ * 抜け、mutex を必ず解放する。既定は十分長く取ってあり、正常なページは触れない。 * * 実時間の最悪値は `timeoutMs + CLEANUP_MIN_TIMEOUT_MS`。ready 待ちと `finally` の * 後始末(バインディング構築の drain)は**同じ予算を共有**し、後始末は残り時間、 * 残っていなければ最低 {@link CLEANUP_MIN_TIMEOUT_MS} だけ待つ(0 にすると * 「上限なし」と同義になり mutex が漏れるため)。`0`(無制限)では後始末も無制限。 */ timeoutMs?: number; /** * `` のモジュールを読むローカルのファイル。ページが名指す URL(`baseUrl` / `url` で解決した * 絶対 URL)を受け取り、ファイルのパスか `file:` URL を返す(例: `(url) => join(publicDir, url.pathname)`)。 * Node のモジュールローダは `file:` と `data:` しか読まないので、これが無いと `src` の状態は * サーバーで描けない — 厳しい CSP の下で文書が勧める形なのに(docs/seam-apps.md、ssr-news。著者の決定は * docs/v4-direction-2026-10.md §5.1)。`null` / `undefined` を返した URL と、この選択肢の無い描画は、 * 理由を言う例外で状態の初期化を失敗させる。モジュールは描画ごとに読み直す(inline の状態と同じく、状態の * オブジェクトをリクエストの間で共有しない)。`.json` の `src` は従来どおり fetch で読む。 */ resolveModule?: (url: URL) => string | URL | null | undefined; } /** 既定のレンダリング上限(ms)。`RenderOptions.timeoutMs` で変えられる。 */ export const DEFAULT_RENDER_TIMEOUT_MS = 30_000; /** * `setTimeout` が受け付ける最大 delay(2^31−1)。これを超える値は Node が 1 ms に丸めるので、 * 「上限を上げたつもりが即時タイムアウト」になる前に無制限へ倒す。 */ export const MAX_RENDER_TIMEOUT_MS = 2_147_483_647; /** `finally` の後始末に必ず与える最低の上限(ms)。予算を使い切っていても mutex は解放する。 */ export const CLEANUP_MIN_TIMEOUT_MS = 1_000; /** * `RenderOptions.timeoutMs` を内部表現(`0` = 無制限、それ以外は有効な delay)へ畳む。 * 無効値(`NaN` / 負 / 2^31−1 超 / `Infinity`)はすべて無制限に倒す。 */ export function normalizeRenderTimeout(value: number | undefined): number { const ms = value ?? DEFAULT_RENDER_TIMEOUT_MS; return Number.isFinite(ms) && ms > 0 && ms <= MAX_RENDER_TIMEOUT_MS ? ms : 0; } /** * `promise` を上限つきで待つ。時間切れは `onTimeout()` の値で決着させる * (`reject` を渡せば reject、`resolve` を渡せば「諦めて先へ進む」)。 * 勝敗にかかわらずタイマーは必ず解除する(サーバープロセスを生かし続けない)。 * `ms` は `normalizeRenderTimeout` を通した値(`0` = 無制限)であること。 */ function withDeadline(promise: Promise, ms: number, onTimeout: () => T | Promise): Promise { if (!(ms > 0)) { return promise; } let timer: ReturnType | undefined; const timeout = new Promise((resolve, reject) => { timer = setTimeout(() => { try { resolve(onTimeout()); } catch (error) { reject(error); } }, ms); // Node のイベントループをこのタイマーだけで生かし続けない (timer as unknown as { unref?: () => void }).unref?.(); }); return Promise.race([promise, timeout]).finally(() => { if (timer !== undefined) clearTimeout(timer); }); } async function loadDefaultBootstraps(): Promise { const { bootstrapState } = await import('@wcstack/state'); return [bootstrapState]; } export interface WaitForReadyOptions { /** * 安定化ループの上限。`$connectedCallback` が動的に追加した要素を拾うため、 * 新しい要素が見つからなくなるまで走査を繰り返す(既定 10)。 */ maxIterations?: number; } /** * `root`(document / ShadowRoot)配下のカスタム要素が readiness プロトコルに従って * 初期化を終えるまで待つ。renderToString がシリアライズ前に行う待機と同じ手順で、 * `@wcstack/testing` の `mount()` もこれを呼ぶ(docs/app-testing-and-typescript-impl-plan.md D11)。 * * 1. `static hasConnectedCallbackPromise = true` を持つ全要素の `connectedCallbackPromise` * を待つ。待っている間に追加された要素も拾う(安定化ループ)。 * `` の初期ルート適用・`` の状態ロードはここで完了する。 * 2. `static getBindingsReady(root)` を持つクラス(``)の、この root に対する * バインディング構築完了を待つ。Promise の取得はループの後 — 実体は各要素の * connectedCallback 内・最初の await より後に登録されるため、先に掴むと「まだ * 登録前」の即時解決 Promise を取り逃す。 * * バインディング初期化の失敗は reject として伝わる(state v1.26+)。 */ export async function waitForReady(root: ParentNode & Node, options?: WaitForReadyOptions): Promise { const maxIterations = options?.maxIterations ?? 10; const awaitedElements = new WeakSet(); const readyCtors = new Set<{ getBindingsReady(root: Node): Promise }>(); for (let i = 0; i < maxIterations; i++) { const connectedPromises: Promise[] = []; for (const el of root.querySelectorAll('*-*')) { if (awaitedElements.has(el)) continue; const ctor = el.constructor as any; if (ctor.hasConnectedCallbackPromise) { awaitedElements.add(el); connectedPromises.push((el as any).connectedCallbackPromise); } if (typeof ctor.getBindingsReady === 'function') { readyCtors.add(ctor); } } if (connectedPromises.length === 0) break; await Promise.all(connectedPromises); } await Promise.all(Array.from(readyCtors, (ctor) => ctor.getBindingsReady(root))); } /** * 要素が接続の後に始めた仕事を待つ(readiness プロトコルの任意の段)。`static hasPendingPromise = true` * を持つ要素の `pendingPromise`(実行中の仕事。無ければ null)— state が束縛で `url` を書いた * `` の要求など。その結果は状態へ届き、それが描いたもの(行と、その中の要素)も続けて待つ * (waitForReady をもう一度)。以前は待たず、ページは値の無いまま(「Loading…」で)直列化された * (docs/seam-apps.md、ssr-news。著者の決定は docs/v4-direction-2026-10.md §5.1)。仕事の失敗は待ち終わりと * して扱う(要素が自分の error に出す)。 */ async function settlePendingWork(root: ParentNode & Node, maxIterations = 10): Promise { for (let i = 0; i < maxIterations; i++) { const pending: Promise[] = []; for (const el of root.querySelectorAll('*-*')) { if (!(el.constructor as any).hasPendingPromise) continue; const p = (el as any).pendingPromise as Promise | null | undefined; if (p) pending.push(Promise.resolve(p).catch(() => undefined)); } if (pending.length === 0) return; await Promise.all(pending); await waitForReady(root, { maxIterations }); } } /** * HTML 文字列を SSR レンダリングして返す。 * * ## 入力 HTML のルール * - `` の中身だけを渡す(``, ``, `` タグは含めない) * - ` * * ``` * * ### wcs-fetch を使ったサーバー通信 * - `` の auto-fetch(`manual` なし)はサーバーでも実行される * - `manual` + `$connectedCallback` で明示的に制御する場合: * * ```html * * * * * ``` * ※ `bootstraps` に `bootstrapFetch` を含める必要あり * * ### バインディングと構造レンダリング * - `data-wcs` バインディングの適用(text, attribute, class, style, property) * - `