@bgub/fig-server 2.1.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import { c as noLane, d as serverErrorPayload, f as streamFlowBlocked, i as cloneContextValues, m as withContextValue, n as suppressesImagePreloads, o as createStaticDispatcher, p as streamHighWaterMark, s as deferred, t as imagePreloadFromHostProps, u as noop } from "./image-preloads-CztoSryT.js";
2
2
  import { Fragment, isValidElement } from "@bgub/fig";
3
- import { assetResourceDestination, assetResourceKey, checkpointPayloadGraph, clientOnlyHostBehavior, clientReferenceAssets, createPayloadGraphEncodeContext, createRendererDataStore, definePayloadGraphElement, describeInvalidChild, encodePayloadDataEntries, encodePayloadValueWithGraph, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPlainPayloadValue, isPortal, isSuspense, isThenable, isViewTransition, jsonPayloadCodec, readThenable, rollbackPayloadGraph, serializePayloadArray, serializePayloadMap, serializePayloadPlainObject, serializePayloadSet, setCurrentDataStore, setCurrentDispatcher } from "@bgub/fig/internal";
3
+ import { assetResourceDestination, assetResourceKey, checkpointPayloadGraph, clientOnlyHostBehavior, clientReferenceAssets, createPayloadGraphEncodeContext, createRendererDataStore, definePayloadGraphElement, describeInvalidChild, encodePayloadDataEntries, encodePayloadValueWithGraph, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPlainPayloadValue, isPortal, isSuspense, isThenable, isViewTransition, jsonPayloadCodec, normalizeDataResourceKey, readThenable, rollbackPayloadGraph, serializePayloadArray, serializePayloadMap, serializePayloadPlainObject, serializePayloadSet, setCurrentDataStore, setCurrentDispatcher } from "@bgub/fig/internal";
4
4
  //#region src/payload-assets.ts
5
5
  /** Owns request-wide delivery-asset dedupe and wire lowering. */
6
6
  var PayloadAssets = class {
@@ -126,6 +126,7 @@ function renderToPayloadStream(node, options = {}) {
126
126
  nextUseId: 0,
127
127
  onError: options.onError,
128
128
  pendingDataSnapshots,
129
+ readDataKeys: /* @__PURE__ */ new Set(),
129
130
  pendingTasks: 0,
130
131
  pingedTasks: [],
131
132
  queuedRows: [],
@@ -233,21 +234,19 @@ function finishTask(request) {
233
234
  }
234
235
  function emitDataRows(request) {
235
236
  if (request.pendingDataSnapshots.size === 0) return;
236
- const entries = [];
237
+ const keys = [];
237
238
  for (const snapshot of request.pendingDataSnapshots.values()) {
238
239
  if (!snapshot.hasValue || snapshot.status === "refreshing") continue;
239
- const key = snapshot.canonicalKey;
240
- if (request.emittedDataKeys.has(key)) {
241
- request.pendingDataSnapshots.delete(snapshot.canonicalKey);
242
- continue;
243
- }
244
- request.emittedDataKeys.add(key);
245
- request.pendingDataSnapshots.delete(snapshot.canonicalKey);
246
- entries.push({
247
- key: snapshot.key,
248
- value: snapshot.value
249
- });
240
+ if (!request.readDataKeys.has(snapshot.canonicalKey)) continue;
241
+ keys.push(snapshot.canonicalKey);
250
242
  }
243
+ const entries = request.dataStore.snapshotKeys(keys).filter((entry) => {
244
+ const key = normalizeDataResourceKey(entry.key);
245
+ request.pendingDataSnapshots.delete(key);
246
+ if (request.emittedDataKeys.has(key)) return false;
247
+ request.emittedDataKeys.add(key);
248
+ return true;
249
+ });
251
250
  if (entries.length > 0) emitRow(request, {
252
251
  tag: "data",
253
252
  value: encodePayloadDataEntries(entries)
@@ -272,6 +271,7 @@ function createPayloadDispatcher(frame) {
272
271
  },
273
272
  readPromise: readThenable,
274
273
  readData(resource, args) {
274
+ frame.request.readDataKeys.add(normalizeDataResourceKey(resource.key(...args)));
275
275
  return frame.request.dataStore.readData(resource, args);
276
276
  },
277
277
  useId() {
@@ -551,7 +551,12 @@ function flushRows(request) {
551
551
  if (request.pendingTasks === 0 && request.queuedRows.length === 0) {
552
552
  request.closed = true;
553
553
  request.cleanupAbortListener?.();
554
- request.dataStore.dispose();
554
+ try {
555
+ request.dataStore.dispose();
556
+ } catch (error) {
557
+ request.controller.error(error);
558
+ return;
559
+ }
555
560
  request.controller.close();
556
561
  }
557
562
  }
@@ -559,7 +564,9 @@ function closeWithError(request, error) {
559
564
  if (request.closed) return;
560
565
  request.cleanupAbortListener?.();
561
566
  request.closed = true;
562
- request.dataStore.dispose();
567
+ try {
568
+ request.dataStore.dispose();
569
+ } catch {}
563
570
  request.allReady.reject(error);
564
571
  request.controller?.error(error);
565
572
  }
@@ -1 +1 @@
1
- {"version":3,"file":"payload.js","names":["invalidChildError"],"sources":["../src/payload-assets.ts","../src/payload.ts"],"sourcesContent":["import type {\n FigAssetResource,\n FigAssetResourceList,\n FigClientReference,\n} from \"@bgub/fig\";\nimport {\n assetResourceDestination,\n assetResourceKey,\n clientReferenceAssets,\n isFigAssetResource,\n type SerializedAssetResource,\n} from \"@bgub/fig/internal\";\n\ntype ResolveClientReferenceAssets = (metadata: {\n id: string;\n}) => FigAssetResourceList;\n\n/** Owns request-wide delivery-asset dedupe and wire lowering. */\nexport class PayloadAssets {\n private readonly emittedKeys = new Set<string>();\n\n constructor(\n private readonly resolveClientReference?: ResolveClientReferenceAssets,\n ) {}\n\n append(value: unknown, output: SerializedAssetResource[]): void {\n if (isFigAssetResource(value)) {\n this.appendResource(value, output);\n return;\n }\n if (!Array.isArray(value)) return;\n for (const resource of value) {\n if (isFigAssetResource(resource)) this.appendResource(resource, output);\n }\n }\n\n serializeClientReference(\n reference: FigClientReference,\n ): SerializedAssetResource[] {\n const declared = clientReferenceAssets(reference);\n const resolved = this.resolveClientReference?.({ id: reference.id });\n const serialized: SerializedAssetResource[] = [];\n this.append(declared, serialized);\n this.append(resolved, serialized);\n return serialized;\n }\n\n private appendResource(\n resource: FigAssetResource,\n output: SerializedAssetResource[],\n ): void {\n // Delivery assets are request-global and persistent, so the first\n // definition wins. Metadata remains owner-scoped and may repeat.\n if (assetResourceDestination(resource) === \"stream\") {\n const key = assetResourceKey(resource);\n if (this.emittedKeys.has(key)) return;\n this.emittedKeys.add(key);\n }\n output.push(serializeAssetResource(resource));\n }\n}\n\nfunction serializeAssetResource(\n resource: FigAssetResource,\n): SerializedAssetResource {\n // Delivery assets intentionally omit author-supplied `key` and dedupe by\n // concrete URL. JSON omits the optional fields that remain undefined.\n switch (resource.kind) {\n case \"stylesheet\":\n return {\n href: resource.href,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n media: resource.media,\n precedence: resource.precedence,\n };\n case \"preload\":\n return {\n as: resource.as,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n fetchpriority: resource.fetchpriority,\n href: resource.href,\n imagesizes: resource.imagesizes,\n imagesrcset: resource.imagesrcset,\n referrerpolicy: resource.referrerpolicy,\n type: resource.type,\n };\n case \"modulepreload\":\n return {\n href: resource.href,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n fetchpriority: resource.fetchpriority,\n };\n case \"script\":\n return {\n kind: resource.kind,\n src: resource.src,\n async: resource.async,\n crossorigin: resource.crossorigin,\n defer: resource.defer,\n module: resource.module,\n };\n case \"preconnect\":\n return {\n href: resource.href,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n };\n case \"title\":\n return { kind: resource.kind, value: resource.value };\n case \"meta\":\n return {\n kind: resource.kind,\n charset: resource.charset,\n content: resource.content,\n \"http-equiv\": resource[\"http-equiv\"],\n key: resource.key,\n name: resource.name,\n property: resource.property,\n };\n }\n}\n","/**\n * Server-side encoding APIs for Fig's server-component payload.\n *\n * @module\n */\nimport {\n type AwaitedFigNode,\n type FigAssetResourceList,\n type FigClientReference,\n type FigContext,\n type FigDataHydrationEntry,\n type FigElement,\n type FigNode,\n Fragment,\n isValidElement,\n type Props,\n} from \"@bgub/fig\";\nimport {\n checkpointPayloadGraph,\n clientOnlyHostBehavior,\n createRendererDataStore,\n createPayloadGraphEncodeContext,\n type DataStore,\n type DataStoreEntrySnapshot,\n definePayloadGraphElement,\n describeInvalidChild,\n encodePayloadDataEntries,\n encodePayloadValueWithGraph,\n isActivity,\n isAssets,\n isClientReference,\n isContext,\n isErrorBoundary,\n isPlainPayloadValue,\n isPortal,\n isSuspense,\n isThenable,\n isViewTransition,\n jsonPayloadCodec,\n type PayloadElementModel,\n type PayloadGraphEncodeContext,\n type PayloadModel,\n type PayloadRow,\n type PayloadSpecialModel,\n type RenderDispatcher,\n readThenable,\n rollbackPayloadGraph,\n serializePayloadArray,\n serializePayloadMap,\n serializePayloadPlainObject,\n serializePayloadSet,\n type SerializedAssetResource,\n setCurrentDataStore,\n setCurrentDispatcher,\n type Thenable,\n} from \"@bgub/fig/internal\";\nimport { PayloadAssets } from \"./payload-assets.ts\";\nimport {\n type ContextValues,\n type StackFrame,\n cloneContextValues,\n createStaticDispatcher,\n type Deferred,\n deferred,\n noLane,\n noop,\n serverErrorPayload,\n streamFlowBlocked,\n streamHighWaterMark,\n withContextValue,\n} from \"./shared.ts\";\nimport {\n imagePreloadFromHostProps,\n suppressesImagePreloads,\n} from \"./image-preloads.ts\";\nimport type { ServerErrorInfo, ServerErrorPayload } from \"./types.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\n\n/** Describes payload render result. */\nexport interface PayloadRenderResult {\n allReady: Promise<void>;\n contentType: string;\n stream: ReadableStream<Uint8Array>;\n}\n\n/** Describes payload component. */\nexport type PayloadComponent = (\n props: Props & { children?: FigNode },\n) => FigNode;\n\n/** Describes payload render options. */\nexport interface PayloadRenderOptions {\n clientReferenceAssets?: (metadata: { id: string }) => FigAssetResourceList;\n componentAssets?: (\n type: PayloadComponent,\n ) => FigAssetResourceList | undefined;\n /**\n * Encoded bytes the result stream buffers before row flushing pauses until\n * the consumer reads (rendering itself never pauses; encoded rows wait\n * queued). Defaults to 65536; values below 1 are clamped to 1.\n */\n highWaterMark?: number;\n signal?: AbortSignal;\n /**\n * Decides what crosses the wire when a server render throws, mirroring the\n * HTML renderer's contract: the returned payload is authoritative. Without\n * a handler, development includes the error message and production sends\n * an empty payload.\n */\n onError?: (\n error: unknown,\n info: ServerErrorInfo,\n ) => ServerErrorPayload | undefined;\n}\n\nclass PayloadRequestCancelledError extends Error {\n constructor() {\n super(\"Payload request cancelled.\");\n this.name = \"PayloadRequestCancelledError\";\n }\n}\n\ntype PayloadRequest = {\n allReady: Deferred<void>;\n assets: PayloadAssets;\n cleanupAbortListener: (() => void) | null;\n clientReferenceRows: Map<string, number>;\n componentAssets: PayloadRenderOptions[\"componentAssets\"];\n controller: ReadableStreamDefaultController<Uint8Array> | null;\n dataStore: DataStore<object, null>;\n emittedDataKeys: Set<string>;\n graph: PayloadGraphEncodeContext;\n nextRowId: number;\n nextUseId: number;\n onError: PayloadRenderOptions[\"onError\"];\n pendingDataSnapshots: Map<string, DataStoreEntrySnapshot>;\n pendingTasks: number;\n pingedTasks: Task[];\n queuedRows: Uint8Array[];\n // Reentrancy guard: enqueueing inside flushRows can synchronously invoke\n // the stream's pull handler, which must not restart the drain — queuedRows\n // is spliced only after the loop, so a reentrant pass would re-enqueue the\n // same rows.\n flushingRows: boolean;\n closed: boolean;\n workScheduled: boolean;\n};\n\ntype Task = {\n contextValues: ContextValues;\n id: number;\n imagePreloadsSuppressed: boolean;\n stack: StackFrame | null;\n} & TaskValue;\n\ntype TaskValue =\n | { kind: \"node\"; value: FigNode }\n | { kind: \"node-promise\"; value: Thenable<AwaitedFigNode> }\n | { kind: \"promise\"; value: Thenable };\n\ntype Component = PayloadComponent;\n\ntype RenderFrame = {\n contextValues: ContextValues;\n // Built lazily on the first function component; reused for the whole task\n // (the dispatcher reads context through the frame, so it stays current).\n dispatcher: RenderDispatcher | null;\n // Assets discovered during this attempt whose owning row is not yet known.\n // Assets rows carry `for` — the row id whose reveal depends on them — and\n // the owner is only decided at scope exit: a subtree that completes keeps\n // its assets with the enclosing row, while one that suspends or fails takes\n // the assets discovered inside it to its outlined row. Scope exits happen\n // within the same synchronous attempt, so buffering costs no wire latency.\n pendingAssets: SerializedAssetResource[];\n request: PayloadRequest;\n imagePreloadsSuppressed: boolean;\n stack: StackFrame | null;\n};\n\nconst errorStacks = new WeakMap<object, StackFrame>();\ntype TreePropMode = \"children\" | \"suspense\" | null;\ntype OutlineKind = \"lazy\" | \"promise\";\ntype PayloadOutline = Extract<PayloadSpecialModel, { $fig: OutlineKind }>;\n\n/** Renders to payload stream. */\nexport function renderToPayloadStream(\n node: FigNode,\n options: PayloadRenderOptions = {},\n): PayloadRenderResult {\n throwIfAborted(options.signal);\n\n const pendingDataSnapshots = new Map<string, DataStoreEntrySnapshot>();\n const request: PayloadRequest = {\n allReady: deferred<void>(),\n assets: new PayloadAssets(options.clientReferenceAssets),\n cleanupAbortListener: null,\n clientReferenceRows: new Map(),\n componentAssets: options.componentAssets,\n controller: null,\n dataStore: createRendererDataStore<object, null>({\n getLane: noLane,\n onEntryChange: (entry: DataStoreEntrySnapshot) => {\n pendingDataSnapshots.set(entry.canonicalKey, entry);\n },\n schedule: noop,\n }),\n emittedDataKeys: new Set(),\n graph: createPayloadGraphEncodeContext(),\n nextRowId: 1,\n nextUseId: 0,\n onError: options.onError,\n pendingDataSnapshots,\n pendingTasks: 0,\n pingedTasks: [],\n queuedRows: [],\n flushingRows: false,\n closed: false,\n workScheduled: false,\n };\n // allReady also rejects through the stream when a consumer cancels (the\n // normal client-disconnect path); the pre-attached no-op handler keeps it\n // from becoming an unhandled rejection for callers that do not await it\n // (await-ers still observe the rejection).\n void request.allReady.promise.catch(noop);\n\n request.pingedTasks.push(\n createTask(\n request,\n 0,\n { kind: \"node\", value: node },\n new Map(),\n false,\n null,\n ),\n );\n\n const stream = new ReadableStream<Uint8Array>(\n {\n start(controller) {\n request.controller = controller;\n flushRows(request);\n },\n pull() {\n // The consumer drained below the high-water mark: resume flushing\n // rows that queued while the flow was blocked.\n flushRows(request);\n },\n cancel(reason) {\n abortPayloadRequest(request, reason);\n },\n },\n new ByteLengthQueuingStrategy({\n highWaterMark: streamHighWaterMark(options.highWaterMark),\n }),\n );\n\n const signal = options.signal;\n if (signal !== undefined) {\n const abortListener = () => abortPayloadRequest(request, signal.reason);\n signal.addEventListener(\"abort\", abortListener, { once: true });\n request.cleanupAbortListener = () => {\n signal.removeEventListener(\"abort\", abortListener);\n request.cleanupAbortListener = null;\n };\n }\n\n scheduleWork(request);\n\n return {\n allReady: request.allReady.promise,\n contentType: jsonPayloadCodec.contentType,\n stream,\n };\n}\n\nfunction createTask(\n request: PayloadRequest,\n id: number,\n value: TaskValue,\n contextValues: ContextValues,\n imagePreloadsSuppressed: boolean,\n stack: StackFrame | null,\n): Task {\n request.pendingTasks += 1;\n return { contextValues, id, imagePreloadsSuppressed, stack, ...value };\n}\n\nfunction performWork(request: PayloadRequest): void {\n if (request.closed) return;\n\n const tasks = request.pingedTasks;\n request.pingedTasks = [];\n\n for (const task of tasks) retryTask(request, task);\n\n flushRows(request);\n}\n\nfunction retryTask(request: PayloadRequest, task: Task): void {\n const frame: RenderFrame = {\n // Tasks already capture a context snapshot when outlined. Provider\n // mutation is balanced, so retries can use that snapshot directly.\n contextValues: task.contextValues,\n dispatcher: null,\n pendingAssets: [],\n request,\n imagePreloadsSuppressed: task.imagePreloadsSuppressed,\n stack: task.stack,\n };\n\n try {\n let value: PayloadModel;\n switch (task.kind) {\n case \"node\":\n value = serializeNode(task.value, frame);\n break;\n case \"node-promise\":\n value = serializeNode(readThenable(task.value), frame);\n break;\n case \"promise\":\n value = serializeValue(readThenable(task.value), frame);\n break;\n }\n flushFrameAssets(frame, task.id);\n emitDataRows(request);\n emitRow(request, { id: task.id, tag: \"model\", value });\n finishTask(request);\n } catch (error) {\n if (isThenable(error)) {\n // The retry re-discovers nothing already deduped by request.assets, so\n // this attempt's assets must ship now; the task still settles into id.\n flushFrameAssets(frame, task.id);\n const ping = () => pingTask(request, task);\n error.then(ping, ping);\n return;\n }\n\n flushFrameAssets(frame, task.id);\n emitRow(request, {\n id: task.id,\n tag: \"error\",\n value: errorRowPayload(request, error, task.stack),\n });\n finishTask(request);\n }\n}\n\nfunction finishTask(request: PayloadRequest): void {\n request.pendingTasks -= 1;\n if (request.pendingTasks === 0) request.allReady.resolve(undefined);\n}\n\nfunction emitDataRows(request: PayloadRequest): void {\n if (request.pendingDataSnapshots.size === 0) return;\n const entries: FigDataHydrationEntry[] = [];\n\n for (const snapshot of request.pendingDataSnapshots.values()) {\n // Stream only settled values. A \"refreshing\" entry exposes a transient stale\n // value while its background refresh is in flight; emitting it would mark the\n // key emitted forever and permanently suppress the fresh value. Skipping it\n // lets the entry stream once its refresh settles.\n if (!snapshot.hasValue || snapshot.status === \"refreshing\") continue;\n\n const key = snapshot.canonicalKey;\n if (request.emittedDataKeys.has(key)) {\n request.pendingDataSnapshots.delete(snapshot.canonicalKey);\n continue;\n }\n\n request.emittedDataKeys.add(key);\n request.pendingDataSnapshots.delete(snapshot.canonicalKey);\n entries.push({ key: snapshot.key, value: snapshot.value });\n }\n\n if (entries.length > 0) {\n emitRow(request, { tag: \"data\", value: encodePayloadDataEntries(entries) });\n }\n}\n\nfunction flushFrameAssets(frame: RenderFrame, rowId: number): void {\n if (frame.pendingAssets.length === 0) return;\n const value = frame.pendingAssets;\n frame.pendingAssets = [];\n emitRow(frame.request, { for: rowId, tag: \"assets\", value });\n}\n\nfunction createPayloadDispatcher(frame: RenderFrame): RenderDispatcher {\n const dispatcher = createStaticDispatcher({\n contextValues: frame.contextValues,\n externalStoreError:\n \"useSyncExternalStore requires getServerSnapshot during payload render.\",\n readBrowser() {\n throw new Error(\n \"readBrowser cannot be used during payload render: serialized components do not run in the browser. Move browser-only behavior into a client reference.\",\n );\n },\n readPromise: readThenable,\n readData(resource, args) {\n return frame.request.dataStore.readData(resource, args);\n },\n useId() {\n const id = `fig-pl-${frame.request.nextUseId.toString(32)}`;\n frame.request.nextUseId += 1;\n return id;\n },\n updateError: \"State updates are not allowed during payload render.\",\n });\n\n // Serialized components are render-only: they never re-run on the client,\n // so state, effects, and interactivity are meaningless there — dev throws\n // at first use instead of silently freezing initial state into the wire.\n // Reads stay server-safe: readContext/readData/readPromise,\n // useMemo, useId, and useSyncExternalStore's getServerSnapshot path (a\n // read, not a subscription — the static dispatcher already requires it).\n if (__DEV__) {\n const throwClientApi = (hook: string) => (): never => {\n throw new Error(\n `${hook} cannot be used during payload render: serialized components are render-only. Move state, effects, and interactivity into a client reference.`,\n );\n };\n dispatcher.useState = throwClientApi(\"useState\");\n dispatcher.useActionState = throwClientApi(\"useActionState\");\n dispatcher.useTransition = throwClientApi(\"useTransition\");\n dispatcher.useStableEvent = throwClientApi(\"useStableEvent\");\n dispatcher.useReactive = throwClientApi(\"useReactive\");\n dispatcher.useBeforePaint = throwClientApi(\"useBeforePaint\");\n dispatcher.useBeforeLayout = throwClientApi(\"useBeforeLayout\");\n }\n\n return dispatcher;\n}\n\nfunction serializeNode(node: FigNode, frame: RenderFrame): PayloadModel {\n if (Array.isArray(node)) {\n return serializeTreeArray(node, frame);\n }\n\n if (node === null || node === undefined || typeof node === \"boolean\") {\n return node === undefined ? { $fig: \"undefined\" } : node;\n }\n\n if (typeof node === \"string\" || typeof node === \"number\") {\n return node;\n }\n\n if (isPortal(node)) return null;\n if (isValidElement(node)) return serializeElement(node, frame, false);\n if (isThenable(node)) {\n return outlineTask(\n frame,\n { kind: \"node-promise\", value: node },\n \"promise\",\n node,\n );\n }\n\n throw invalidChildError(node);\n}\n\nfunction serializeNodeOrLazy(\n node: FigNode,\n frame: RenderFrame,\n preserveElementIdentity = false,\n): PayloadModel {\n const graphCheckpoint = checkpointPayloadGraph(frame.request.graph);\n const assetCheckpoint = frame.pendingAssets.length;\n try {\n if (!isValidElement(node)) return serializeNode(node, frame);\n return serializeElement(node, frame, preserveElementIdentity);\n } catch (error) {\n rollbackPayloadGraph(frame.request.graph, graphCheckpoint);\n // Assets discovered inside this subtree belong to the outlined row, not\n // the enclosing one: gating the enclosing row would hold the whole tree's\n // reveal on stylesheets only the hole's content needs.\n const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);\n if (isThenable(error)) {\n return outlineTask(\n frame,\n { kind: \"node\", value: node },\n \"lazy\",\n error,\n scopedAssets,\n );\n }\n return outlineError(frame, error, \"lazy\", scopedAssets);\n }\n}\n\nfunction serializeElement(\n element: FigElement,\n frame: RenderFrame,\n preserveIdentity: boolean,\n): PayloadModel {\n const type = element.type;\n\n if (typeof type === \"string\") {\n return serializeHostElement(element, type, frame, preserveIdentity);\n }\n\n if (type === Fragment) {\n return serializeElementModel(\n element,\n { $fig: \"fragment\" },\n frame,\n preserveIdentity,\n \"children\",\n );\n }\n\n if (isClientReference(type)) {\n const clientId = emitClientReference(frame.request, type);\n return serializeElementModel(\n element,\n { $fig: \"client\", id: clientId },\n frame,\n preserveIdentity,\n );\n }\n\n if (isContext(type)) {\n return serializeContextProvider(type, element.props, frame);\n }\n\n if (isAssets(type)) {\n return serializeAssets(element.props, frame);\n }\n\n if (isSuspense(type)) {\n return serializeElementModel(\n element,\n { $fig: \"suspense\" },\n frame,\n preserveIdentity,\n \"suspense\",\n );\n }\n\n if (isErrorBoundary(type)) {\n return serializeNode(element.props.children, frame);\n }\n\n if (isActivity(type)) {\n return serializeElementModel(\n element,\n { $fig: \"activity\" },\n frame,\n preserveIdentity,\n \"children\",\n );\n }\n\n if (isViewTransition(type)) {\n return serializeElementModel(\n element,\n { $fig: \"view-transition\" },\n frame,\n preserveIdentity,\n \"children\",\n );\n }\n\n if (typeof type === \"function\") {\n return serializeFunctionComponent(type, element.props, frame);\n }\n\n throw new Error(\"Unsupported Fig element type during payload render.\");\n}\n\nfunction serializeHostElement(\n element: FigElement,\n type: string,\n frame: RenderFrame,\n preserveIdentity: boolean,\n): PayloadModel {\n const preload = imagePreloadFromHostProps(\n type,\n element.props,\n frame.imagePreloadsSuppressed,\n );\n if (preload !== null) {\n frame.request.assets.append(preload, frame.pendingAssets);\n }\n\n const previousImagePreloadsSuppressed = frame.imagePreloadsSuppressed;\n frame.imagePreloadsSuppressed =\n previousImagePreloadsSuppressed || suppressesImagePreloads(type);\n try {\n return serializeElementModel(\n element,\n type,\n frame,\n preserveIdentity,\n \"children\",\n );\n } finally {\n frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed;\n }\n}\n\nfunction serializeElementModel(\n element: FigElement,\n type: PayloadElementModel[\"type\"],\n frame: RenderFrame,\n preserveIdentity: boolean,\n treeProps: TreePropMode = null,\n): PayloadModel {\n const id = preserveIdentity\n ? definePayloadGraphElement(frame.request.graph, element)\n : undefined;\n if (typeof id === \"object\") return id;\n const model: PayloadElementModel = {\n $fig: \"element\",\n key: element.key,\n props: serializeProps(\n element.props,\n frame,\n treeProps,\n typeof type === \"string\",\n ),\n type,\n };\n if (id !== undefined) model.id = id;\n return model;\n}\n\nfunction serializeFunctionComponent(\n type: Component,\n props: Props,\n frame: RenderFrame,\n): PayloadModel {\n const assetCheckpoint = frame.pendingAssets.length;\n frame.request.assets.append(\n frame.request.componentAssets?.(type),\n frame.pendingAssets,\n );\n frame.dispatcher ??= createPayloadDispatcher(frame);\n const previousDispatcher = setCurrentDispatcher(frame.dispatcher);\n const previousDataStore = setCurrentDataStore(frame.request.dataStore);\n const previousStack = frame.stack;\n if (__DEV__ || frame.request.onError !== undefined) {\n frame.stack = { name: type.name || \"Anonymous\", parent: previousStack };\n }\n\n try {\n if (\n __DEV__ &&\n \"$$typeof\" in type &&\n type.$$typeof === Symbol.for(\"fig.data-resource\")\n ) {\n throw new Error(\n \"Payload components cannot be rendered inside Payload. Render the underlying server component directly, or mount separate Payload components from the client tree.\",\n );\n }\n const result = type(props);\n if (isThenable(result)) {\n const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);\n return outlineTask(\n frame,\n { kind: \"node-promise\", value: result },\n \"promise\",\n result,\n scopedAssets,\n );\n }\n return serializeNode(result, frame);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n } finally {\n frame.stack = previousStack;\n setCurrentDataStore(previousDataStore);\n setCurrentDispatcher(previousDispatcher);\n }\n}\n\nfunction serializeContextProvider(\n context: FigContext<unknown>,\n props: Props,\n frame: RenderFrame,\n): PayloadModel {\n return withContextValue(frame.contextValues, context, props.value, () =>\n serializeNode(props.children, frame),\n );\n}\n\nfunction serializeAssets(props: Props, frame: RenderFrame): PayloadModel {\n // Buffered, not emitted: the owning row id is decided at scope exit (see\n // RenderFrame.pendingAssets). Dedupe happens here, so a retried subtree\n // does not re-buffer assets an earlier attempt already shipped.\n frame.request.assets.append(props.assets, frame.pendingAssets);\n return serializeNode(props.children, frame);\n}\n\nfunction serializeProps(\n props: Props,\n frame: RenderFrame,\n treeProps: TreePropMode,\n hostElement = false,\n): PayloadModel {\n const clientOnlyBehavior = hostElement\n ? clientOnlyHostBehavior(props)\n : undefined;\n if (clientOnlyBehavior !== undefined) {\n throw new Error(\n `Client-only host behavior from ${clientOnlyBehavior} cannot be ` +\n \"serialized in a payload; move it into a client reference.\",\n );\n }\n\n const value: Record<string, PayloadModel> = {};\n for (const name of Object.keys(props)) {\n // A host `mix` already resolved into these props at element creation;\n // the marker itself holds descriptors (functions) and stays server-side.\n // Component `mix` props still serialize (and fail loudly on functions).\n if (hostElement && name === \"mix\") continue;\n const child = props[name];\n const isTreeProp =\n treeProps !== null &&\n (name === \"children\" ||\n (treeProps === \"suspense\" && name === \"fallback\"));\n value[name] = isTreeProp\n ? serializeTreeProp(child, frame)\n : serializeValue(child, frame);\n }\n return {\n $fig: \"object\",\n value,\n };\n}\n\nfunction serializeTreeProp(value: FigNode, frame: RenderFrame): PayloadModel {\n if (Array.isArray(value)) return serializeTreeArray(value, frame);\n return serializeNodeOrLazy(value, frame);\n}\n\nfunction serializeTreeArray(\n value: FigNode[],\n frame: RenderFrame,\n): PayloadModel[] {\n // Array.map preserves sparse root slots, which encode as null on the wire.\n // Once nested arrays are flattened, iteration intentionally makes holes\n // explicit undefined children, matching the existing flattening semantics.\n if (!value.some(Array.isArray)) {\n return value.map((child) => serializeNodeOrLazy(child, frame));\n }\n const serialized: PayloadModel[] = [];\n appendTreeArray(value, frame, serialized);\n return serialized;\n}\n\n// Payload flattens nested child arrays without dropping empty children or\n// merging text; the client performs normal child collection after decoding.\nfunction appendTreeArray(\n children: FigNode[],\n frame: RenderFrame,\n output: PayloadModel[],\n): void {\n for (const child of children) {\n if (Array.isArray(child)) appendTreeArray(child, frame, output);\n else output.push(serializeNodeOrLazy(child, frame));\n }\n}\n\nfunction serializeValue(value: unknown, frame: RenderFrame): PayloadModel {\n // Scalar values return from the shared encoder before any graph access, so\n // reusing the request graph here is free (no per-value context allocation).\n if (isPlainPayloadValue(value)) {\n return encodePayloadValueWithGraph(value, frame.request.graph);\n }\n\n if (isClientReference(value)) {\n return { $fig: \"client\", id: emitClientReference(frame.request, value) };\n }\n\n if (isValidElement(value)) return serializeNodeOrLazy(value, frame, true);\n if (isPortal(value)) return null;\n if (isThenable(value)) {\n return outlineTask(frame, { kind: \"promise\", value }, \"promise\", value);\n }\n if (typeof value === \"function\") {\n throw new Error(\"Functions cannot be passed to client references.\");\n }\n\n if (typeof value === \"object\" && value !== null) {\n if (value instanceof Date) {\n return encodePayloadValueWithGraph(value, frame.request.graph);\n }\n if (value instanceof Map) {\n return serializePayloadMap(value, frame.request.graph, ([key, item]) => [\n serializeValue(key, frame),\n serializeValue(item, frame),\n ]);\n }\n if (value instanceof Set) {\n return serializePayloadSet(value, frame.request.graph, (item) =>\n serializeValue(item, frame),\n );\n }\n\n if (Array.isArray(value)) {\n return serializePayloadArray(value, frame.request.graph, (item) =>\n serializeValue(item, frame),\n );\n }\n\n return serializePayloadPlainObject(value, frame.request.graph, (child) =>\n serializeValue(child, frame),\n );\n }\n\n throw new Error(`Cannot serialize ${typeof value} into the payload.`);\n}\nfunction outlineTask(\n frame: RenderFrame,\n value: TaskValue,\n referenceKind: OutlineKind,\n wakeable: Thenable,\n scopedAssets: SerializedAssetResource[] = [],\n): PayloadSpecialModel {\n const request = frame.request;\n const outline = createOutline(request, referenceKind, scopedAssets);\n const task = createTask(\n request,\n outline.id,\n value,\n cloneContextValues(frame.contextValues),\n frame.imagePreloadsSuppressed,\n stackForError(wakeable, frame.stack),\n );\n\n const ping = () => pingTask(request, task);\n wakeable.then(ping, ping);\n\n return outline;\n}\n\nfunction outlineError(\n frame: RenderFrame,\n error: unknown,\n referenceKind: OutlineKind,\n scopedAssets: SerializedAssetResource[],\n): PayloadSpecialModel {\n const request = frame.request;\n const outline = createOutline(request, referenceKind, scopedAssets);\n // Assets first so a decoder that drops gates on error rows sees the row\n // order it expects; the assets still preload even though the row failed.\n emitRow(request, {\n id: outline.id,\n tag: \"error\",\n value: errorRowPayload(request, error, frame.stack),\n });\n return outline;\n}\n\nfunction createOutline(\n request: PayloadRequest,\n kind: OutlineKind,\n assets: SerializedAssetResource[],\n): PayloadOutline {\n const outline: PayloadOutline = {\n $fig: kind,\n id: request.nextRowId++,\n };\n if (assets.length > 0) {\n emitRow(request, { for: outline.id, tag: \"assets\", value: assets });\n }\n return outline;\n}\n\n// The onError return value is authoritative, like the HTML renderer's\n// reportBoundaryError: message crosses the wire only when the handler says\n// so. Without a handler, development keeps the real message for debugging\n// (payload errors never re-execute on the client, so the wire is the only\n// surface) and production sends an empty payload.\nfunction errorRowPayload(\n request: PayloadRequest,\n error: unknown,\n stack: StackFrame | null,\n): ServerErrorPayload {\n return serverErrorPayload(\n error,\n stackForError(error, stack),\n request.onError,\n );\n}\n\nfunction recordErrorStack(error: unknown, stack: StackFrame | null): void {\n if (stack === null) return;\n if (typeof error !== \"object\" || error === null) return;\n if (!errorStacks.has(error)) errorStacks.set(error, stack);\n}\n\nfunction stackForError(\n error: unknown,\n fallback: StackFrame | null,\n): StackFrame | null {\n if (typeof error !== \"object\" || error === null) return fallback;\n return errorStacks.get(error) ?? fallback;\n}\n\nfunction clientReferenceExportName(id: string): string | undefined {\n const hashIndex = id.lastIndexOf(\"#\");\n if (hashIndex === -1) return undefined;\n return id.slice(hashIndex + 1) || undefined;\n}\n\nfunction emitClientReference(\n request: PayloadRequest,\n reference: FigClientReference,\n): number {\n const existing = request.clientReferenceRows.get(reference.id);\n if (existing !== undefined) return existing;\n\n // Resolve assets BEFORE reserving the row id and recording the mapping. A lazy\n // resource thunk (bundler-manifest resolution) may throw; reserving first would\n // leave a row id mapped but never emitted, so a later retry returns the cached\n // id and the client suspends on a chunk that never arrives. Resolving first\n // lets the throw propagate as an ordinary serialization error with no poisoned\n // mapping, so the reference can be retried cleanly.\n const assets = request.assets.serializeClientReference(reference);\n const value: Extract<PayloadRow, { tag: \"client\" }>[\"value\"] = {\n id: reference.id,\n };\n if (assets.length > 0) value.assets = assets;\n // The \"<module>#<export>\" authoring convention is split here, once, so the\n // wire is self-describing and the client never string-parses ids.\n const exportName = clientReferenceExportName(reference.id);\n if (exportName !== undefined) value.exportName = exportName;\n if (reference.ssr !== undefined) value.ssr = true;\n const id = request.nextRowId++;\n request.clientReferenceRows.set(reference.id, id);\n emitRow(request, {\n id,\n tag: \"client\",\n value,\n });\n return id;\n}\n\nfunction emitRow(request: PayloadRequest, row: PayloadRow): void {\n request.queuedRows.push(jsonPayloadCodec.encodeRow(row));\n flushRows(request);\n}\n\nfunction pingTask(request: PayloadRequest, task: Task): void {\n if (request.closed) return;\n request.pingedTasks.push(task);\n scheduleWork(request);\n}\n\nfunction scheduleWork(request: PayloadRequest): void {\n // Many thenables settling in one tick ping many tasks; one performWork\n // pass drains them all, so schedule at most one.\n if (request.workScheduled) return;\n request.workScheduled = true;\n queueMicrotask(() => {\n request.workScheduled = false;\n performWork(request);\n });\n}\n\nfunction flushRows(request: PayloadRequest): void {\n if (request.controller === null || request.closed) return;\n if (request.flushingRows) return;\n\n request.flushingRows = true;\n try {\n // Row-granular gating: rows already encode one complete wire row each,\n // so stopping between rows keeps every chunk parse-safe for consumers\n // that interleave per chunk.\n let flushed = 0;\n while (\n flushed < request.queuedRows.length &&\n !streamFlowBlocked(request.controller)\n ) {\n request.controller.enqueue(request.queuedRows[flushed]);\n flushed += 1;\n }\n if (flushed === request.queuedRows.length) request.queuedRows.length = 0;\n else if (flushed > 0) {\n request.queuedRows = request.queuedRows.slice(flushed);\n }\n } finally {\n request.flushingRows = false;\n }\n\n // Deliberately not conditioned on flow: close() only marks the end of the\n // queue, so a full queue with no rows left to write still closes here.\n if (request.pendingTasks === 0 && request.queuedRows.length === 0) {\n request.closed = true;\n request.cleanupAbortListener?.();\n request.dataStore.dispose();\n request.controller.close();\n }\n}\n\nfunction closeWithError(request: PayloadRequest, error: unknown): void {\n if (request.closed) return;\n request.cleanupAbortListener?.();\n request.closed = true;\n request.dataStore.dispose();\n request.allReady.reject(error);\n request.controller?.error(error);\n}\n\nfunction abortPayloadRequest(request: PayloadRequest, reason?: unknown): void {\n closeWithError(request, reason ?? new PayloadRequestCancelledError());\n}\n\nfunction invalidChildError(value: unknown): Error {\n return new Error(\n `Invalid Fig child in payload render: ${describeInvalidChild(value)}.`,\n );\n}\n\nfunction throwIfAborted(signal?: AbortSignal | null): void {\n if (signal?.aborted) throw new PayloadRequestCancelledError();\n}\n"],"mappings":";;;;;AAkBA,IAAa,gBAAb,MAA2B;CAIN;CAHnB,8BAA+B,IAAI,IAAY;CAE/C,YACE,wBACA;EADiB,KAAA,yBAAA;CAChB;CAEH,OAAO,OAAgB,QAAyC;EAC9D,IAAI,mBAAmB,KAAK,GAAG;GAC7B,KAAK,eAAe,OAAO,MAAM;GACjC;EACF;EACA,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG;EAC3B,KAAK,MAAM,YAAY,OACrB,IAAI,mBAAmB,QAAQ,GAAG,KAAK,eAAe,UAAU,MAAM;CAE1E;CAEA,yBACE,WAC2B;EAC3B,MAAM,WAAW,sBAAsB,SAAS;EAChD,MAAM,WAAW,KAAK,yBAAyB,EAAE,IAAI,UAAU,GAAG,CAAC;EACnE,MAAM,aAAwC,CAAC;EAC/C,KAAK,OAAO,UAAU,UAAU;EAChC,KAAK,OAAO,UAAU,UAAU;EAChC,OAAO;CACT;CAEA,eACE,UACA,QACM;EAGN,IAAI,yBAAyB,QAAQ,MAAM,UAAU;GACnD,MAAM,MAAM,iBAAiB,QAAQ;GACrC,IAAI,KAAK,YAAY,IAAI,GAAG,GAAG;GAC/B,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F;AAEA,SAAS,eAAe,SAAyB,OAAsB;CACrE,IAAI,QAAQ,QAAQ;CACpB,QAAQ,uBAAuB;CAC/B,QAAQ,SAAS;CACjB,QAAQ,UAAU,QAAQ;CAC1B,QAAQ,SAAS,OAAO,KAAK;CAC7B,QAAQ,YAAY,MAAM,KAAK;AACjC;AAEA,SAAS,oBAAoB,SAAyB,QAAwB;CAC5E,eAAe,SAAS,UAAU,IAAI,6BAA6B,CAAC;AACtE;AAEA,SAASA,oBAAkB,OAAuB;CAChD,uBAAO,IAAI,MACT,wCAAwC,qBAAqB,KAAK,EAAE,EACtE;AACF;AAEA,SAAS,eAAe,QAAmC;CACzD,IAAI,QAAQ,SAAS,MAAM,IAAI,6BAA6B;AAC9D"}
1
+ {"version":3,"file":"payload.js","names":["invalidChildError"],"sources":["../src/payload-assets.ts","../src/payload.ts"],"sourcesContent":["import type {\n FigAssetResource,\n FigAssetResourceList,\n FigClientReference,\n} from \"@bgub/fig\";\nimport {\n assetResourceDestination,\n assetResourceKey,\n clientReferenceAssets,\n isFigAssetResource,\n type SerializedAssetResource,\n} from \"@bgub/fig/internal\";\n\ntype ResolveClientReferenceAssets = (metadata: {\n id: string;\n}) => FigAssetResourceList;\n\n/** Owns request-wide delivery-asset dedupe and wire lowering. */\nexport class PayloadAssets {\n private readonly emittedKeys = new Set<string>();\n\n constructor(\n private readonly resolveClientReference?: ResolveClientReferenceAssets,\n ) {}\n\n append(value: unknown, output: SerializedAssetResource[]): void {\n if (isFigAssetResource(value)) {\n this.appendResource(value, output);\n return;\n }\n if (!Array.isArray(value)) return;\n for (const resource of value) {\n if (isFigAssetResource(resource)) this.appendResource(resource, output);\n }\n }\n\n serializeClientReference(\n reference: FigClientReference,\n ): SerializedAssetResource[] {\n const declared = clientReferenceAssets(reference);\n const resolved = this.resolveClientReference?.({ id: reference.id });\n const serialized: SerializedAssetResource[] = [];\n this.append(declared, serialized);\n this.append(resolved, serialized);\n return serialized;\n }\n\n private appendResource(\n resource: FigAssetResource,\n output: SerializedAssetResource[],\n ): void {\n // Delivery assets are request-global and persistent, so the first\n // definition wins. Metadata remains owner-scoped and may repeat.\n if (assetResourceDestination(resource) === \"stream\") {\n const key = assetResourceKey(resource);\n if (this.emittedKeys.has(key)) return;\n this.emittedKeys.add(key);\n }\n output.push(serializeAssetResource(resource));\n }\n}\n\nfunction serializeAssetResource(\n resource: FigAssetResource,\n): SerializedAssetResource {\n // Delivery assets intentionally omit author-supplied `key` and dedupe by\n // concrete URL. JSON omits the optional fields that remain undefined.\n switch (resource.kind) {\n case \"stylesheet\":\n return {\n href: resource.href,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n media: resource.media,\n precedence: resource.precedence,\n };\n case \"preload\":\n return {\n as: resource.as,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n fetchpriority: resource.fetchpriority,\n href: resource.href,\n imagesizes: resource.imagesizes,\n imagesrcset: resource.imagesrcset,\n referrerpolicy: resource.referrerpolicy,\n type: resource.type,\n };\n case \"modulepreload\":\n return {\n href: resource.href,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n fetchpriority: resource.fetchpriority,\n };\n case \"script\":\n return {\n kind: resource.kind,\n src: resource.src,\n async: resource.async,\n crossorigin: resource.crossorigin,\n defer: resource.defer,\n module: resource.module,\n };\n case \"preconnect\":\n return {\n href: resource.href,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n };\n case \"title\":\n return { kind: resource.kind, value: resource.value };\n case \"meta\":\n return {\n kind: resource.kind,\n charset: resource.charset,\n content: resource.content,\n \"http-equiv\": resource[\"http-equiv\"],\n key: resource.key,\n name: resource.name,\n property: resource.property,\n };\n }\n}\n","/**\n * Server-side encoding APIs for Fig's server-component payload.\n *\n * @module\n */\nimport {\n type AwaitedFigNode,\n type FigAssetResourceList,\n type FigClientReference,\n type FigContext,\n type FigElement,\n type FigNode,\n Fragment,\n isValidElement,\n type Props,\n} from \"@bgub/fig\";\nimport {\n checkpointPayloadGraph,\n clientOnlyHostBehavior,\n createRendererDataStore,\n createPayloadGraphEncodeContext,\n type DataStore,\n type DataStoreEntrySnapshot,\n definePayloadGraphElement,\n describeInvalidChild,\n encodePayloadDataEntries,\n encodePayloadValueWithGraph,\n isActivity,\n isAssets,\n isClientReference,\n isContext,\n isErrorBoundary,\n isPlainPayloadValue,\n isPortal,\n isSuspense,\n isThenable,\n isViewTransition,\n jsonPayloadCodec,\n normalizeDataResourceKey,\n type PayloadElementModel,\n type PayloadGraphEncodeContext,\n type PayloadModel,\n type PayloadRow,\n type PayloadSpecialModel,\n type RenderDispatcher,\n readThenable,\n rollbackPayloadGraph,\n serializePayloadArray,\n serializePayloadMap,\n serializePayloadPlainObject,\n serializePayloadSet,\n type SerializedAssetResource,\n setCurrentDataStore,\n setCurrentDispatcher,\n type Thenable,\n} from \"@bgub/fig/internal\";\nimport { PayloadAssets } from \"./payload-assets.ts\";\nimport {\n type ContextValues,\n type StackFrame,\n cloneContextValues,\n createStaticDispatcher,\n type Deferred,\n deferred,\n noLane,\n noop,\n serverErrorPayload,\n streamFlowBlocked,\n streamHighWaterMark,\n withContextValue,\n} from \"./shared.ts\";\nimport {\n imagePreloadFromHostProps,\n suppressesImagePreloads,\n} from \"./image-preloads.ts\";\nimport type { ServerErrorInfo, ServerErrorPayload } from \"./types.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\n\n/** Describes payload render result. */\nexport interface PayloadRenderResult {\n allReady: Promise<void>;\n contentType: string;\n stream: ReadableStream<Uint8Array>;\n}\n\n/** Describes payload component. */\nexport type PayloadComponent = (\n props: Props & { children?: FigNode },\n) => FigNode;\n\n/** Describes payload render options. */\nexport interface PayloadRenderOptions {\n clientReferenceAssets?: (metadata: { id: string }) => FigAssetResourceList;\n componentAssets?: (\n type: PayloadComponent,\n ) => FigAssetResourceList | undefined;\n /**\n * Encoded bytes the result stream buffers before row flushing pauses until\n * the consumer reads (rendering itself never pauses; encoded rows wait\n * queued). Defaults to 65536; values below 1 are clamped to 1.\n */\n highWaterMark?: number;\n signal?: AbortSignal;\n /**\n * Decides what crosses the wire when a server render throws, mirroring the\n * HTML renderer's contract: the returned payload is authoritative. Without\n * a handler, development includes the error message and production sends\n * an empty payload.\n */\n onError?: (\n error: unknown,\n info: ServerErrorInfo,\n ) => ServerErrorPayload | undefined;\n}\n\nclass PayloadRequestCancelledError extends Error {\n constructor() {\n super(\"Payload request cancelled.\");\n this.name = \"PayloadRequestCancelledError\";\n }\n}\n\ntype PayloadRequest = {\n allReady: Deferred<void>;\n assets: PayloadAssets;\n cleanupAbortListener: (() => void) | null;\n clientReferenceRows: Map<string, number>;\n componentAssets: PayloadRenderOptions[\"componentAssets\"];\n controller: ReadableStreamDefaultController<Uint8Array> | null;\n dataStore: DataStore<object, null>;\n emittedDataKeys: Set<string>;\n // Keys this render read. Only these (and the opted-in dependencies their\n // loads ensured) become data rows, so any new read path must record its\n // keys here or its entries silently stop streaming.\n readDataKeys: Set<string>;\n graph: PayloadGraphEncodeContext;\n nextRowId: number;\n nextUseId: number;\n onError: PayloadRenderOptions[\"onError\"];\n pendingDataSnapshots: Map<string, DataStoreEntrySnapshot>;\n pendingTasks: number;\n pingedTasks: Task[];\n queuedRows: Uint8Array[];\n // Reentrancy guard: enqueueing inside flushRows can synchronously invoke\n // the stream's pull handler, which must not restart the drain — queuedRows\n // is spliced only after the loop, so a reentrant pass would re-enqueue the\n // same rows.\n flushingRows: boolean;\n closed: boolean;\n workScheduled: boolean;\n};\n\ntype Task = {\n contextValues: ContextValues;\n id: number;\n imagePreloadsSuppressed: boolean;\n stack: StackFrame | null;\n} & TaskValue;\n\ntype TaskValue =\n | { kind: \"node\"; value: FigNode }\n | { kind: \"node-promise\"; value: Thenable<AwaitedFigNode> }\n | { kind: \"promise\"; value: Thenable };\n\ntype Component = PayloadComponent;\n\ntype RenderFrame = {\n contextValues: ContextValues;\n // Built lazily on the first function component; reused for the whole task\n // (the dispatcher reads context through the frame, so it stays current).\n dispatcher: RenderDispatcher | null;\n // Assets discovered during this attempt whose owning row is not yet known.\n // Assets rows carry `for` — the row id whose reveal depends on them — and\n // the owner is only decided at scope exit: a subtree that completes keeps\n // its assets with the enclosing row, while one that suspends or fails takes\n // the assets discovered inside it to its outlined row. Scope exits happen\n // within the same synchronous attempt, so buffering costs no wire latency.\n pendingAssets: SerializedAssetResource[];\n request: PayloadRequest;\n imagePreloadsSuppressed: boolean;\n stack: StackFrame | null;\n};\n\nconst errorStacks = new WeakMap<object, StackFrame>();\ntype TreePropMode = \"children\" | \"suspense\" | null;\ntype OutlineKind = \"lazy\" | \"promise\";\ntype PayloadOutline = Extract<PayloadSpecialModel, { $fig: OutlineKind }>;\n\n/** Renders to payload stream. */\nexport function renderToPayloadStream(\n node: FigNode,\n options: PayloadRenderOptions = {},\n): PayloadRenderResult {\n throwIfAborted(options.signal);\n\n const pendingDataSnapshots = new Map<string, DataStoreEntrySnapshot>();\n const request: PayloadRequest = {\n allReady: deferred<void>(),\n assets: new PayloadAssets(options.clientReferenceAssets),\n cleanupAbortListener: null,\n clientReferenceRows: new Map(),\n componentAssets: options.componentAssets,\n controller: null,\n dataStore: createRendererDataStore<object, null>({\n getLane: noLane,\n onEntryChange: (entry: DataStoreEntrySnapshot) => {\n pendingDataSnapshots.set(entry.canonicalKey, entry);\n },\n schedule: noop,\n }),\n emittedDataKeys: new Set(),\n graph: createPayloadGraphEncodeContext(),\n nextRowId: 1,\n nextUseId: 0,\n onError: options.onError,\n pendingDataSnapshots,\n readDataKeys: new Set(),\n pendingTasks: 0,\n pingedTasks: [],\n queuedRows: [],\n flushingRows: false,\n closed: false,\n workScheduled: false,\n };\n // allReady also rejects through the stream when a consumer cancels (the\n // normal client-disconnect path); the pre-attached no-op handler keeps it\n // from becoming an unhandled rejection for callers that do not await it\n // (await-ers still observe the rejection).\n void request.allReady.promise.catch(noop);\n\n request.pingedTasks.push(\n createTask(\n request,\n 0,\n { kind: \"node\", value: node },\n new Map(),\n false,\n null,\n ),\n );\n\n const stream = new ReadableStream<Uint8Array>(\n {\n start(controller) {\n request.controller = controller;\n flushRows(request);\n },\n pull() {\n // The consumer drained below the high-water mark: resume flushing\n // rows that queued while the flow was blocked.\n flushRows(request);\n },\n cancel(reason) {\n abortPayloadRequest(request, reason);\n },\n },\n new ByteLengthQueuingStrategy({\n highWaterMark: streamHighWaterMark(options.highWaterMark),\n }),\n );\n\n const signal = options.signal;\n if (signal !== undefined) {\n const abortListener = () => abortPayloadRequest(request, signal.reason);\n signal.addEventListener(\"abort\", abortListener, { once: true });\n request.cleanupAbortListener = () => {\n signal.removeEventListener(\"abort\", abortListener);\n request.cleanupAbortListener = null;\n };\n }\n\n scheduleWork(request);\n\n return {\n allReady: request.allReady.promise,\n contentType: jsonPayloadCodec.contentType,\n stream,\n };\n}\n\nfunction createTask(\n request: PayloadRequest,\n id: number,\n value: TaskValue,\n contextValues: ContextValues,\n imagePreloadsSuppressed: boolean,\n stack: StackFrame | null,\n): Task {\n request.pendingTasks += 1;\n return { contextValues, id, imagePreloadsSuppressed, stack, ...value };\n}\n\nfunction performWork(request: PayloadRequest): void {\n if (request.closed) return;\n\n const tasks = request.pingedTasks;\n request.pingedTasks = [];\n\n for (const task of tasks) retryTask(request, task);\n\n flushRows(request);\n}\n\nfunction retryTask(request: PayloadRequest, task: Task): void {\n const frame: RenderFrame = {\n // Tasks already capture a context snapshot when outlined. Provider\n // mutation is balanced, so retries can use that snapshot directly.\n contextValues: task.contextValues,\n dispatcher: null,\n pendingAssets: [],\n request,\n imagePreloadsSuppressed: task.imagePreloadsSuppressed,\n stack: task.stack,\n };\n\n try {\n let value: PayloadModel;\n switch (task.kind) {\n case \"node\":\n value = serializeNode(task.value, frame);\n break;\n case \"node-promise\":\n value = serializeNode(readThenable(task.value), frame);\n break;\n case \"promise\":\n value = serializeValue(readThenable(task.value), frame);\n break;\n }\n flushFrameAssets(frame, task.id);\n emitDataRows(request);\n emitRow(request, { id: task.id, tag: \"model\", value });\n finishTask(request);\n } catch (error) {\n if (isThenable(error)) {\n // The retry re-discovers nothing already deduped by request.assets, so\n // this attempt's assets must ship now; the task still settles into id.\n flushFrameAssets(frame, task.id);\n const ping = () => pingTask(request, task);\n error.then(ping, ping);\n return;\n }\n\n flushFrameAssets(frame, task.id);\n emitRow(request, {\n id: task.id,\n tag: \"error\",\n value: errorRowPayload(request, error, task.stack),\n });\n finishTask(request);\n }\n}\n\nfunction finishTask(request: PayloadRequest): void {\n request.pendingTasks -= 1;\n if (request.pendingTasks === 0) request.allReady.resolve(undefined);\n}\n\nfunction emitDataRows(request: PayloadRequest): void {\n if (request.pendingDataSnapshots.size === 0) return;\n const keys: string[] = [];\n\n for (const snapshot of request.pendingDataSnapshots.values()) {\n // Stream only settled values. A \"refreshing\" entry exposes a transient stale\n // value while its background refresh is in flight; emitting it would mark the\n // key emitted forever and permanently suppress the fresh value. Skipping it\n // lets the entry stream once its refresh settles.\n if (!snapshot.hasValue || snapshot.status === \"refreshing\") continue;\n\n // Keep dependency-only snapshots available in case a later task reads\n // them directly without changing their cached value.\n if (!request.readDataKeys.has(snapshot.canonicalKey)) continue;\n keys.push(snapshot.canonicalKey);\n }\n\n // Each key, including opted-in sources a read's load ensured, is emitted once;\n // the resource's transfer rule decides what crosses.\n const entries = request.dataStore.snapshotKeys(keys).filter((entry) => {\n const key = normalizeDataResourceKey(entry.key);\n // A transfer that returns undefined must stay pending: its live state\n // can become transferable before a later task reads it again.\n request.pendingDataSnapshots.delete(key);\n if (request.emittedDataKeys.has(key)) return false;\n request.emittedDataKeys.add(key);\n return true;\n });\n\n if (entries.length > 0) {\n emitRow(request, { tag: \"data\", value: encodePayloadDataEntries(entries) });\n }\n}\n\nfunction flushFrameAssets(frame: RenderFrame, rowId: number): void {\n if (frame.pendingAssets.length === 0) return;\n const value = frame.pendingAssets;\n frame.pendingAssets = [];\n emitRow(frame.request, { for: rowId, tag: \"assets\", value });\n}\n\nfunction createPayloadDispatcher(frame: RenderFrame): RenderDispatcher {\n const dispatcher = createStaticDispatcher({\n contextValues: frame.contextValues,\n externalStoreError:\n \"useSyncExternalStore requires getServerSnapshot during payload render.\",\n readBrowser() {\n throw new Error(\n \"readBrowser cannot be used during payload render: serialized components do not run in the browser. Move browser-only behavior into a client reference.\",\n );\n },\n readPromise: readThenable,\n readData(resource, args) {\n frame.request.readDataKeys.add(\n normalizeDataResourceKey(resource.key(...args)),\n );\n return frame.request.dataStore.readData(resource, args);\n },\n useId() {\n const id = `fig-pl-${frame.request.nextUseId.toString(32)}`;\n frame.request.nextUseId += 1;\n return id;\n },\n updateError: \"State updates are not allowed during payload render.\",\n });\n\n // Serialized components are render-only: they never re-run on the client,\n // so state, effects, and interactivity are meaningless there — dev throws\n // at first use instead of silently freezing initial state into the wire.\n // Reads stay server-safe: readContext/readData/readPromise,\n // useMemo, useId, and useSyncExternalStore's getServerSnapshot path (a\n // read, not a subscription — the static dispatcher already requires it).\n if (__DEV__) {\n const throwClientApi = (hook: string) => (): never => {\n throw new Error(\n `${hook} cannot be used during payload render: serialized components are render-only. Move state, effects, and interactivity into a client reference.`,\n );\n };\n dispatcher.useState = throwClientApi(\"useState\");\n dispatcher.useActionState = throwClientApi(\"useActionState\");\n dispatcher.useTransition = throwClientApi(\"useTransition\");\n dispatcher.useStableEvent = throwClientApi(\"useStableEvent\");\n dispatcher.useReactive = throwClientApi(\"useReactive\");\n dispatcher.useBeforePaint = throwClientApi(\"useBeforePaint\");\n dispatcher.useBeforeLayout = throwClientApi(\"useBeforeLayout\");\n }\n\n return dispatcher;\n}\n\nfunction serializeNode(node: FigNode, frame: RenderFrame): PayloadModel {\n if (Array.isArray(node)) {\n return serializeTreeArray(node, frame);\n }\n\n if (node === null || node === undefined || typeof node === \"boolean\") {\n return node === undefined ? { $fig: \"undefined\" } : node;\n }\n\n if (typeof node === \"string\" || typeof node === \"number\") {\n return node;\n }\n\n if (isPortal(node)) return null;\n if (isValidElement(node)) return serializeElement(node, frame, false);\n if (isThenable(node)) {\n return outlineTask(\n frame,\n { kind: \"node-promise\", value: node },\n \"promise\",\n node,\n );\n }\n\n throw invalidChildError(node);\n}\n\nfunction serializeNodeOrLazy(\n node: FigNode,\n frame: RenderFrame,\n preserveElementIdentity = false,\n): PayloadModel {\n const graphCheckpoint = checkpointPayloadGraph(frame.request.graph);\n const assetCheckpoint = frame.pendingAssets.length;\n try {\n if (!isValidElement(node)) return serializeNode(node, frame);\n return serializeElement(node, frame, preserveElementIdentity);\n } catch (error) {\n rollbackPayloadGraph(frame.request.graph, graphCheckpoint);\n // Assets discovered inside this subtree belong to the outlined row, not\n // the enclosing one: gating the enclosing row would hold the whole tree's\n // reveal on stylesheets only the hole's content needs.\n const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);\n if (isThenable(error)) {\n return outlineTask(\n frame,\n { kind: \"node\", value: node },\n \"lazy\",\n error,\n scopedAssets,\n );\n }\n return outlineError(frame, error, \"lazy\", scopedAssets);\n }\n}\n\nfunction serializeElement(\n element: FigElement,\n frame: RenderFrame,\n preserveIdentity: boolean,\n): PayloadModel {\n const type = element.type;\n\n if (typeof type === \"string\") {\n return serializeHostElement(element, type, frame, preserveIdentity);\n }\n\n if (type === Fragment) {\n return serializeElementModel(\n element,\n { $fig: \"fragment\" },\n frame,\n preserveIdentity,\n \"children\",\n );\n }\n\n if (isClientReference(type)) {\n const clientId = emitClientReference(frame.request, type);\n return serializeElementModel(\n element,\n { $fig: \"client\", id: clientId },\n frame,\n preserveIdentity,\n );\n }\n\n if (isContext(type)) {\n return serializeContextProvider(type, element.props, frame);\n }\n\n if (isAssets(type)) {\n return serializeAssets(element.props, frame);\n }\n\n if (isSuspense(type)) {\n return serializeElementModel(\n element,\n { $fig: \"suspense\" },\n frame,\n preserveIdentity,\n \"suspense\",\n );\n }\n\n if (isErrorBoundary(type)) {\n return serializeNode(element.props.children, frame);\n }\n\n if (isActivity(type)) {\n return serializeElementModel(\n element,\n { $fig: \"activity\" },\n frame,\n preserveIdentity,\n \"children\",\n );\n }\n\n if (isViewTransition(type)) {\n return serializeElementModel(\n element,\n { $fig: \"view-transition\" },\n frame,\n preserveIdentity,\n \"children\",\n );\n }\n\n if (typeof type === \"function\") {\n return serializeFunctionComponent(type, element.props, frame);\n }\n\n throw new Error(\"Unsupported Fig element type during payload render.\");\n}\n\nfunction serializeHostElement(\n element: FigElement,\n type: string,\n frame: RenderFrame,\n preserveIdentity: boolean,\n): PayloadModel {\n const preload = imagePreloadFromHostProps(\n type,\n element.props,\n frame.imagePreloadsSuppressed,\n );\n if (preload !== null) {\n frame.request.assets.append(preload, frame.pendingAssets);\n }\n\n const previousImagePreloadsSuppressed = frame.imagePreloadsSuppressed;\n frame.imagePreloadsSuppressed =\n previousImagePreloadsSuppressed || suppressesImagePreloads(type);\n try {\n return serializeElementModel(\n element,\n type,\n frame,\n preserveIdentity,\n \"children\",\n );\n } finally {\n frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed;\n }\n}\n\nfunction serializeElementModel(\n element: FigElement,\n type: PayloadElementModel[\"type\"],\n frame: RenderFrame,\n preserveIdentity: boolean,\n treeProps: TreePropMode = null,\n): PayloadModel {\n const id = preserveIdentity\n ? definePayloadGraphElement(frame.request.graph, element)\n : undefined;\n if (typeof id === \"object\") return id;\n const model: PayloadElementModel = {\n $fig: \"element\",\n key: element.key,\n props: serializeProps(\n element.props,\n frame,\n treeProps,\n typeof type === \"string\",\n ),\n type,\n };\n if (id !== undefined) model.id = id;\n return model;\n}\n\nfunction serializeFunctionComponent(\n type: Component,\n props: Props,\n frame: RenderFrame,\n): PayloadModel {\n const assetCheckpoint = frame.pendingAssets.length;\n frame.request.assets.append(\n frame.request.componentAssets?.(type),\n frame.pendingAssets,\n );\n frame.dispatcher ??= createPayloadDispatcher(frame);\n const previousDispatcher = setCurrentDispatcher(frame.dispatcher);\n const previousDataStore = setCurrentDataStore(frame.request.dataStore);\n const previousStack = frame.stack;\n if (__DEV__ || frame.request.onError !== undefined) {\n frame.stack = { name: type.name || \"Anonymous\", parent: previousStack };\n }\n\n try {\n if (\n __DEV__ &&\n \"$$typeof\" in type &&\n type.$$typeof === Symbol.for(\"fig.data-resource\")\n ) {\n throw new Error(\n \"Payload components cannot be rendered inside Payload. Render the underlying server component directly, or mount separate Payload components from the client tree.\",\n );\n }\n const result = type(props);\n if (isThenable(result)) {\n const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);\n return outlineTask(\n frame,\n { kind: \"node-promise\", value: result },\n \"promise\",\n result,\n scopedAssets,\n );\n }\n return serializeNode(result, frame);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n } finally {\n frame.stack = previousStack;\n setCurrentDataStore(previousDataStore);\n setCurrentDispatcher(previousDispatcher);\n }\n}\n\nfunction serializeContextProvider(\n context: FigContext<unknown>,\n props: Props,\n frame: RenderFrame,\n): PayloadModel {\n return withContextValue(frame.contextValues, context, props.value, () =>\n serializeNode(props.children, frame),\n );\n}\n\nfunction serializeAssets(props: Props, frame: RenderFrame): PayloadModel {\n // Buffered, not emitted: the owning row id is decided at scope exit (see\n // RenderFrame.pendingAssets). Dedupe happens here, so a retried subtree\n // does not re-buffer assets an earlier attempt already shipped.\n frame.request.assets.append(props.assets, frame.pendingAssets);\n return serializeNode(props.children, frame);\n}\n\nfunction serializeProps(\n props: Props,\n frame: RenderFrame,\n treeProps: TreePropMode,\n hostElement = false,\n): PayloadModel {\n const clientOnlyBehavior = hostElement\n ? clientOnlyHostBehavior(props)\n : undefined;\n if (clientOnlyBehavior !== undefined) {\n throw new Error(\n `Client-only host behavior from ${clientOnlyBehavior} cannot be ` +\n \"serialized in a payload; move it into a client reference.\",\n );\n }\n\n const value: Record<string, PayloadModel> = {};\n for (const name of Object.keys(props)) {\n // A host `mix` already resolved into these props at element creation;\n // the marker itself holds descriptors (functions) and stays server-side.\n // Component `mix` props still serialize (and fail loudly on functions).\n if (hostElement && name === \"mix\") continue;\n const child = props[name];\n const isTreeProp =\n treeProps !== null &&\n (name === \"children\" ||\n (treeProps === \"suspense\" && name === \"fallback\"));\n value[name] = isTreeProp\n ? serializeTreeProp(child, frame)\n : serializeValue(child, frame);\n }\n return {\n $fig: \"object\",\n value,\n };\n}\n\nfunction serializeTreeProp(value: FigNode, frame: RenderFrame): PayloadModel {\n if (Array.isArray(value)) return serializeTreeArray(value, frame);\n return serializeNodeOrLazy(value, frame);\n}\n\nfunction serializeTreeArray(\n value: FigNode[],\n frame: RenderFrame,\n): PayloadModel[] {\n // Array.map preserves sparse root slots, which encode as null on the wire.\n // Once nested arrays are flattened, iteration intentionally makes holes\n // explicit undefined children, matching the existing flattening semantics.\n if (!value.some(Array.isArray)) {\n return value.map((child) => serializeNodeOrLazy(child, frame));\n }\n const serialized: PayloadModel[] = [];\n appendTreeArray(value, frame, serialized);\n return serialized;\n}\n\n// Payload flattens nested child arrays without dropping empty children or\n// merging text; the client performs normal child collection after decoding.\nfunction appendTreeArray(\n children: FigNode[],\n frame: RenderFrame,\n output: PayloadModel[],\n): void {\n for (const child of children) {\n if (Array.isArray(child)) appendTreeArray(child, frame, output);\n else output.push(serializeNodeOrLazy(child, frame));\n }\n}\n\nfunction serializeValue(value: unknown, frame: RenderFrame): PayloadModel {\n // Scalar values return from the shared encoder before any graph access, so\n // reusing the request graph here is free (no per-value context allocation).\n if (isPlainPayloadValue(value)) {\n return encodePayloadValueWithGraph(value, frame.request.graph);\n }\n\n if (isClientReference(value)) {\n return { $fig: \"client\", id: emitClientReference(frame.request, value) };\n }\n\n if (isValidElement(value)) return serializeNodeOrLazy(value, frame, true);\n if (isPortal(value)) return null;\n if (isThenable(value)) {\n return outlineTask(frame, { kind: \"promise\", value }, \"promise\", value);\n }\n if (typeof value === \"function\") {\n throw new Error(\"Functions cannot be passed to client references.\");\n }\n\n if (typeof value === \"object\" && value !== null) {\n if (value instanceof Date) {\n return encodePayloadValueWithGraph(value, frame.request.graph);\n }\n if (value instanceof Map) {\n return serializePayloadMap(value, frame.request.graph, ([key, item]) => [\n serializeValue(key, frame),\n serializeValue(item, frame),\n ]);\n }\n if (value instanceof Set) {\n return serializePayloadSet(value, frame.request.graph, (item) =>\n serializeValue(item, frame),\n );\n }\n\n if (Array.isArray(value)) {\n return serializePayloadArray(value, frame.request.graph, (item) =>\n serializeValue(item, frame),\n );\n }\n\n return serializePayloadPlainObject(value, frame.request.graph, (child) =>\n serializeValue(child, frame),\n );\n }\n\n throw new Error(`Cannot serialize ${typeof value} into the payload.`);\n}\nfunction outlineTask(\n frame: RenderFrame,\n value: TaskValue,\n referenceKind: OutlineKind,\n wakeable: Thenable,\n scopedAssets: SerializedAssetResource[] = [],\n): PayloadSpecialModel {\n const request = frame.request;\n const outline = createOutline(request, referenceKind, scopedAssets);\n const task = createTask(\n request,\n outline.id,\n value,\n cloneContextValues(frame.contextValues),\n frame.imagePreloadsSuppressed,\n stackForError(wakeable, frame.stack),\n );\n\n const ping = () => pingTask(request, task);\n wakeable.then(ping, ping);\n\n return outline;\n}\n\nfunction outlineError(\n frame: RenderFrame,\n error: unknown,\n referenceKind: OutlineKind,\n scopedAssets: SerializedAssetResource[],\n): PayloadSpecialModel {\n const request = frame.request;\n const outline = createOutline(request, referenceKind, scopedAssets);\n // Assets first so a decoder that drops gates on error rows sees the row\n // order it expects; the assets still preload even though the row failed.\n emitRow(request, {\n id: outline.id,\n tag: \"error\",\n value: errorRowPayload(request, error, frame.stack),\n });\n return outline;\n}\n\nfunction createOutline(\n request: PayloadRequest,\n kind: OutlineKind,\n assets: SerializedAssetResource[],\n): PayloadOutline {\n const outline: PayloadOutline = {\n $fig: kind,\n id: request.nextRowId++,\n };\n if (assets.length > 0) {\n emitRow(request, { for: outline.id, tag: \"assets\", value: assets });\n }\n return outline;\n}\n\n// The onError return value is authoritative, like the HTML renderer's\n// reportBoundaryError: message crosses the wire only when the handler says\n// so. Without a handler, development keeps the real message for debugging\n// (payload errors never re-execute on the client, so the wire is the only\n// surface) and production sends an empty payload.\nfunction errorRowPayload(\n request: PayloadRequest,\n error: unknown,\n stack: StackFrame | null,\n): ServerErrorPayload {\n return serverErrorPayload(\n error,\n stackForError(error, stack),\n request.onError,\n );\n}\n\nfunction recordErrorStack(error: unknown, stack: StackFrame | null): void {\n if (stack === null) return;\n if (typeof error !== \"object\" || error === null) return;\n if (!errorStacks.has(error)) errorStacks.set(error, stack);\n}\n\nfunction stackForError(\n error: unknown,\n fallback: StackFrame | null,\n): StackFrame | null {\n if (typeof error !== \"object\" || error === null) return fallback;\n return errorStacks.get(error) ?? fallback;\n}\n\nfunction clientReferenceExportName(id: string): string | undefined {\n const hashIndex = id.lastIndexOf(\"#\");\n if (hashIndex === -1) return undefined;\n return id.slice(hashIndex + 1) || undefined;\n}\n\nfunction emitClientReference(\n request: PayloadRequest,\n reference: FigClientReference,\n): number {\n const existing = request.clientReferenceRows.get(reference.id);\n if (existing !== undefined) return existing;\n\n // Resolve assets BEFORE reserving the row id and recording the mapping. A lazy\n // resource thunk (bundler-manifest resolution) may throw; reserving first would\n // leave a row id mapped but never emitted, so a later retry returns the cached\n // id and the client suspends on a chunk that never arrives. Resolving first\n // lets the throw propagate as an ordinary serialization error with no poisoned\n // mapping, so the reference can be retried cleanly.\n const assets = request.assets.serializeClientReference(reference);\n const value: Extract<PayloadRow, { tag: \"client\" }>[\"value\"] = {\n id: reference.id,\n };\n if (assets.length > 0) value.assets = assets;\n // The \"<module>#<export>\" authoring convention is split here, once, so the\n // wire is self-describing and the client never string-parses ids.\n const exportName = clientReferenceExportName(reference.id);\n if (exportName !== undefined) value.exportName = exportName;\n if (reference.ssr !== undefined) value.ssr = true;\n const id = request.nextRowId++;\n request.clientReferenceRows.set(reference.id, id);\n emitRow(request, {\n id,\n tag: \"client\",\n value,\n });\n return id;\n}\n\nfunction emitRow(request: PayloadRequest, row: PayloadRow): void {\n request.queuedRows.push(jsonPayloadCodec.encodeRow(row));\n flushRows(request);\n}\n\nfunction pingTask(request: PayloadRequest, task: Task): void {\n if (request.closed) return;\n request.pingedTasks.push(task);\n scheduleWork(request);\n}\n\nfunction scheduleWork(request: PayloadRequest): void {\n // Many thenables settling in one tick ping many tasks; one performWork\n // pass drains them all, so schedule at most one.\n if (request.workScheduled) return;\n request.workScheduled = true;\n queueMicrotask(() => {\n request.workScheduled = false;\n performWork(request);\n });\n}\n\nfunction flushRows(request: PayloadRequest): void {\n if (request.controller === null || request.closed) return;\n if (request.flushingRows) return;\n\n request.flushingRows = true;\n try {\n // Row-granular gating: rows already encode one complete wire row each,\n // so stopping between rows keeps every chunk parse-safe for consumers\n // that interleave per chunk.\n let flushed = 0;\n while (\n flushed < request.queuedRows.length &&\n !streamFlowBlocked(request.controller)\n ) {\n request.controller.enqueue(request.queuedRows[flushed]);\n flushed += 1;\n }\n if (flushed === request.queuedRows.length) request.queuedRows.length = 0;\n else if (flushed > 0) {\n request.queuedRows = request.queuedRows.slice(flushed);\n }\n } finally {\n request.flushingRows = false;\n }\n\n // Deliberately not conditioned on flow: close() only marks the end of the\n // queue, so a full queue with no rows left to write still closes here.\n if (request.pendingTasks === 0 && request.queuedRows.length === 0) {\n request.closed = true;\n request.cleanupAbortListener?.();\n try {\n request.dataStore.dispose();\n } catch (error) {\n request.controller.error(error);\n return;\n }\n request.controller.close();\n }\n}\n\nfunction closeWithError(request: PayloadRequest, error: unknown): void {\n if (request.closed) return;\n request.cleanupAbortListener?.();\n request.closed = true;\n try {\n request.dataStore.dispose();\n } catch {\n // Preserve the failure that caused teardown; disposal already ran cleanup.\n }\n request.allReady.reject(error);\n request.controller?.error(error);\n}\n\nfunction abortPayloadRequest(request: PayloadRequest, reason?: unknown): void {\n closeWithError(request, reason ?? new PayloadRequestCancelledError());\n}\n\nfunction invalidChildError(value: unknown): Error {\n return new Error(\n `Invalid Fig child in payload render: ${describeInvalidChild(value)}.`,\n );\n}\n\nfunction throwIfAborted(signal?: AbortSignal | null): void {\n if (signal?.aborted) throw new PayloadRequestCancelledError();\n}\n"],"mappings":";;;;;AAkBA,IAAa,gBAAb,MAA2B;CAIN;CAHnB,8BAA+B,IAAI,IAAY;CAE/C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IAAI,MACT,wCAAwC,qBAAqB,KAAK,EAAE,EACtE;AACF;AAEA,SAAS,eAAe,QAAmC;CACzD,IAAI,QAAQ,SAAS,MAAM,IAAI,6BAA6B;AAC9D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bgub/fig-server",
3
- "version": "2.1.0",
3
+ "version": "2.2.1",
4
4
  "description": "Fig server renderer",
5
5
  "keywords": [],
6
6
  "homepage": "https://github.com/bgub/fig",
@@ -46,10 +46,10 @@
46
46
  "access": "public"
47
47
  },
48
48
  "peerDependencies": {
49
- "@bgub/fig": "2.1.0"
49
+ "@bgub/fig": "2.2.1"
50
50
  },
51
51
  "devDependencies": {
52
- "@bgub/fig": "2.1.0"
52
+ "@bgub/fig": "2.2.1"
53
53
  },
54
54
  "engines": {
55
55
  "node": "^20.19.0 || >=22.12.0"