@bgub/fig-server 1.0.0 → 2.1.0
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.
- package/README.md +9 -6
- package/dist/{image-preloads-x38gXLap.js → image-preloads-DwTY3DIk.js} +3 -3
- package/dist/image-preloads-DwTY3DIk.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +140 -30
- package/dist/index.js.map +1 -1
- package/dist/payload.d.ts +2 -3
- package/dist/payload.js +10 -13
- package/dist/payload.js.map +1 -1
- package/dist/{types-CsnQA5rq.d.ts → types-Xrr1OZyd.d.ts} +23 -3
- package/dist-development/{image-preloads-CXnAwZ0S.js → image-preloads-CztoSryT.js} +3 -3
- package/dist-development/image-preloads-CztoSryT.js.map +1 -0
- package/dist-development/index.js +139 -29
- package/dist-development/index.js.map +1 -1
- package/dist-development/payload.js +10 -13
- package/dist-development/payload.js.map +1 -1
- package/package.json +3 -3
- package/dist/image-preloads-x38gXLap.js.map +0 -1
- package/dist-development/image-preloads-CXnAwZ0S.js.map +0 -1
package/dist/payload.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as ServerErrorInfo, r as ServerErrorPayload } from "./types-
|
|
2
|
-
import {
|
|
1
|
+
import { n as ServerErrorInfo, r as ServerErrorPayload } from "./types-Xrr1OZyd.js";
|
|
2
|
+
import { FigAssetResourceList, FigNode, Props } from "@bgub/fig";
|
|
3
3
|
//#region src/payload.d.ts
|
|
4
4
|
/** Describes payload render result. */
|
|
5
5
|
interface PayloadRenderResult {
|
|
@@ -17,7 +17,6 @@ interface PayloadRenderOptions {
|
|
|
17
17
|
id: string;
|
|
18
18
|
}) => FigAssetResourceList;
|
|
19
19
|
componentAssets?: (type: PayloadComponent) => FigAssetResourceList | undefined;
|
|
20
|
-
dataPartition?: DataResourceKeyInput;
|
|
21
20
|
/**
|
|
22
21
|
* Encoded bytes the result stream buffers before row flushing pauses until
|
|
23
22
|
* the consumer reads (rendering itself never pauses; encoded rows wait
|
package/dist/payload.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
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-DwTY3DIk.js";
|
|
2
2
|
import { Fragment, isValidElement } from "@bgub/fig";
|
|
3
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";
|
|
4
4
|
//#region src/payload-assets.ts
|
|
@@ -68,13 +68,6 @@ function serializeAssetResource(resource) {
|
|
|
68
68
|
defer: resource.defer,
|
|
69
69
|
module: resource.module
|
|
70
70
|
};
|
|
71
|
-
case "font": return {
|
|
72
|
-
href: resource.href,
|
|
73
|
-
kind: resource.kind,
|
|
74
|
-
type: resource.type,
|
|
75
|
-
crossorigin: resource.crossorigin,
|
|
76
|
-
fetchpriority: resource.fetchpriority
|
|
77
|
-
};
|
|
78
71
|
case "preconnect": return {
|
|
79
72
|
href: resource.href,
|
|
80
73
|
kind: resource.kind,
|
|
@@ -97,6 +90,11 @@ function serializeAssetResource(resource) {
|
|
|
97
90
|
}
|
|
98
91
|
//#endregion
|
|
99
92
|
//#region src/payload.ts
|
|
93
|
+
/**
|
|
94
|
+
* Server-side encoding APIs for Fig's server-component payload.
|
|
95
|
+
*
|
|
96
|
+
* @module
|
|
97
|
+
*/
|
|
100
98
|
var PayloadRequestCancelledError = class extends Error {
|
|
101
99
|
constructor() {
|
|
102
100
|
super("Payload request cancelled.");
|
|
@@ -120,7 +118,6 @@ function renderToPayloadStream(node, options = {}) {
|
|
|
120
118
|
onEntryChange: (entry) => {
|
|
121
119
|
pendingDataSnapshots.set(entry.canonicalKey, entry);
|
|
122
120
|
},
|
|
123
|
-
partition: options.dataPartition,
|
|
124
121
|
schedule: noop
|
|
125
122
|
}),
|
|
126
123
|
emittedDataKeys: /* @__PURE__ */ new Set(),
|
|
@@ -270,12 +267,12 @@ function createPayloadDispatcher(frame) {
|
|
|
270
267
|
return createStaticDispatcher({
|
|
271
268
|
contextValues: frame.contextValues,
|
|
272
269
|
externalStoreError: "useSyncExternalStore requires getServerSnapshot during payload render.",
|
|
270
|
+
readBrowser() {
|
|
271
|
+
throw new Error("readBrowser cannot be used during payload render: serialized components do not run in the browser. Move browser-only behavior into a client reference.");
|
|
272
|
+
},
|
|
273
273
|
readPromise: readThenable,
|
|
274
274
|
readData(resource, args) {
|
|
275
|
-
return frame.request.dataStore.readData(resource, args
|
|
276
|
-
},
|
|
277
|
-
preloadData(resource, args) {
|
|
278
|
-
frame.request.dataStore.preloadData(resource, ...args);
|
|
275
|
+
return frame.request.dataStore.readData(resource, args);
|
|
279
276
|
},
|
|
280
277
|
useId() {
|
|
281
278
|
const id = `fig-pl-${frame.request.nextUseId.toString(32)}`;
|
package/dist/payload.js.map
CHANGED
|
@@ -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 \"font\":\n return {\n href: resource.href,\n kind: resource.kind,\n type: resource.type,\n crossorigin: resource.crossorigin,\n fetchpriority: resource.fetchpriority,\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 type { DataResourceKeyInput } from \"@bgub/fig\";\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 dataPartition?: DataResourceKeyInput;\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 partition: options.dataPartition,\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 readPromise: readThenable,\n readData(resource, args) {\n return frame.request.dataStore.readData(resource, args, frame);\n },\n preloadData(resource, args) {\n frame.request.dataStore.preloadData(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/preloadData,\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,KAAK,YAAY,IAAI,GAAG;EAC1B;EACA,OAAO,KAAK,uBAAuB,QAAQ,CAAC;CAC9C;AACF;AAEA,SAAS,uBACP,UACyB;CAGzB,QAAQ,SAAS,MAAjB;EACE,KAAK,cACH,OAAO;GACL,MAAM,SAAS;GACf,MAAM,SAAS;GACf,aAAa,SAAS;GACtB,OAAO,SAAS;GAChB,YAAY,SAAS;EACvB;EACF,KAAK,WACH,OAAO;GACL,IAAI,SAAS;GACb,MAAM,SAAS;GACf,aAAa,SAAS;GACtB,eAAe,SAAS;GACxB,MAAM,SAAS;GACf,YAAY,SAAS;GACrB,aAAa,SAAS;GAC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,YAAY,OAAO;CACrB,CAAC;AACH;AAEA,SAAS,UAAU,SAA+B;CAChD,IAAI,QAAQ,eAAe,QAAQ,QAAQ,QAAQ;CACnD,IAAI,QAAQ,cAAc;CAE1B,QAAQ,eAAe;CACvB,IAAI;EAIF,IAAI,UAAU;EACd,OACE,UAAU,QAAQ,WAAW,UAC7B,CAAC,kBAAkB,QAAQ,UAAU,GACrC;GACA,QAAQ,WAAW,QAAQ,QAAQ,WAAW,QAAQ;GACtD,WAAW;EACb;EACA,IAAI,YAAY,QAAQ,WAAW,QAAQ,QAAQ,WAAW,SAAS;OAClE,IAAI,UAAU,GACjB,QAAQ,aAAa,QAAQ,WAAW,MAAM,OAAO;CAEzD,UAAU;EACR,QAAQ,eAAe;CACzB;CAIA,IAAI,QAAQ,iBAAiB,KAAK,QAAQ,WAAW,WAAW,GAAG;EACjE,QAAQ,SAAS;EACjB,QAAQ,uBAAuB;EAC/B,QAAQ,UAAU,QAAQ;EAC1B,QAAQ,WAAW,MAAM;CAC3B;AACF;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 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,KAAK,YAAY,IAAI,GAAG;EAC1B;EACA,OAAO,KAAK,uBAAuB,QAAQ,CAAC;CAC9C;AACF;AAEA,SAAS,uBACP,UACyB;CAGzB,QAAQ,SAAS,MAAjB;EACE,KAAK,cACH,OAAO;GACL,MAAM,SAAS;GACf,MAAM,SAAS;GACf,aAAa,SAAS;GACtB,OAAO,SAAS;GAChB,YAAY,SAAS;EACvB;EACF,KAAK,WACH,OAAO;GACL,IAAI,SAAS;GACb,MAAM,SAAS;GACf,aAAa,SAAS;GACtB,eAAe,SAAS;GACxB,MAAM,SAAS;GACf,YAAY,SAAS;G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vB,IAAI;EAIF,IAAI,UAAU;EACd,OACE,UAAU,QAAQ,WAAW,UAC7B,CAAC,kBAAkB,QAAQ,UAAU,GACrC;GACA,QAAQ,WAAW,QAAQ,QAAQ,WAAW,QAAQ;GACtD,WAAW;EACb;EACA,IAAI,YAAY,QAAQ,WAAW,QAAQ,QAAQ,WAAW,SAAS;OAClE,IAAI,UAAU,GACjB,QAAQ,aAAa,QAAQ,WAAW,MAAM,OAAO;CAEzD,UAAU;EACR,QAAQ,eAAe;CACzB;CAIA,IAAI,QAAQ,iBAAiB,KAAK,QAAQ,WAAW,WAAW,GAAG;EACjE,QAAQ,SAAS;EACjB,QAAQ,uBAAuB;EAC/B,QAAQ,UAAU,QAAQ;EAC1B,QAAQ,WAAW,MAAM;CAC3B;AACF;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,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ElementType, FigAssetResource, FigAssetResourceList, FigClientReference, FigDataHydrationEntry, FigDataStoreController, FigDataStoreHandle, FigNode, PreloadResource, Props } from "@bgub/fig";
|
|
2
2
|
//#region src/render-tree.d.ts
|
|
3
3
|
/** Describes render tree kind. */
|
|
4
4
|
type RenderTreeKind = "activity" | "assets" | "client-reference" | "context-provider" | "error-boundary" | "fragment" | "function" | "host" | "root" | "suspense" | "text" | "view-transition";
|
|
@@ -33,9 +33,10 @@ interface ServerRenderOptions {
|
|
|
33
33
|
highWaterMark?: number;
|
|
34
34
|
nonce?: string;
|
|
35
35
|
onError?: (error: unknown, info: ServerErrorInfo) => ServerErrorPayload | undefined;
|
|
36
|
+
/** Reports an intentional browser-only Suspense fallback. */
|
|
37
|
+
onBrowserBailout?: (error: Error, info: ServerErrorInfo) => void;
|
|
36
38
|
clientReferenceFallback?: (reference: FigClientReference, props: Props) => FigNode;
|
|
37
39
|
resolveAssetKey?: (type: ElementType) => string | undefined;
|
|
38
|
-
dataPartition?: DataResourceKeyInput;
|
|
39
40
|
/** Adopt a store populated by request loaders before rendering. */
|
|
40
41
|
dataStore?: FigDataStoreController;
|
|
41
42
|
/**
|
|
@@ -43,6 +44,14 @@ interface ServerRenderOptions {
|
|
|
43
44
|
* the request store before the first component reads it.
|
|
44
45
|
*/
|
|
45
46
|
initialData?: readonly FigDataHydrationEntry[];
|
|
47
|
+
/**
|
|
48
|
+
* Streams the data each Suspense boundary read ahead of its reveal, so the
|
|
49
|
+
* client store has it before that boundary hydrates. Defaults to `true`.
|
|
50
|
+
* `filter` excludes entries an adapter transports another way; entries the
|
|
51
|
+
* Payload value codec cannot encode are always skipped and load in the
|
|
52
|
+
* browser. Shell data is not streamed: deliver it with `takeData()`.
|
|
53
|
+
*/
|
|
54
|
+
streamData?: boolean | ServerStreamDataOptions;
|
|
46
55
|
assets?: Record<string, FigAssetResourceList>;
|
|
47
56
|
/**
|
|
48
57
|
* Caller-owned collector the renderer fills with the component structure
|
|
@@ -53,6 +62,10 @@ interface ServerRenderOptions {
|
|
|
53
62
|
renderTree?: RenderTreeCollector;
|
|
54
63
|
signal?: AbortSignal;
|
|
55
64
|
}
|
|
65
|
+
/** Describes server stream data options. */
|
|
66
|
+
interface ServerStreamDataOptions {
|
|
67
|
+
filter?: (entry: FigDataHydrationEntry) => boolean;
|
|
68
|
+
}
|
|
56
69
|
/** Describes server prerender options. */
|
|
57
70
|
interface ServerPrerenderOptions extends ServerRenderOptions {
|
|
58
71
|
/**
|
|
@@ -85,6 +98,13 @@ interface ServerStreamRenderResult {
|
|
|
85
98
|
getPreloadHeader(options?: ServerPreloadHeaderOptions): string | undefined;
|
|
86
99
|
shellReady: Promise<void>;
|
|
87
100
|
stream: ReadableStream<Uint8Array>;
|
|
101
|
+
/**
|
|
102
|
+
* Returns settled entries the stream has not delivered and will not
|
|
103
|
+
* deliver, honoring the `streamData` filter. Call it where the document
|
|
104
|
+
* places its hydration snapshot, before the client bootstrap; later
|
|
105
|
+
* boundaries stream only what this call did not return.
|
|
106
|
+
*/
|
|
107
|
+
takeData(): FigDataHydrationEntry[];
|
|
88
108
|
}
|
|
89
109
|
/** Describes server preload header options. */
|
|
90
110
|
interface ServerPreloadHeaderOptions {
|
|
@@ -118,4 +138,4 @@ interface ServerPrerenderResult {
|
|
|
118
138
|
html: string;
|
|
119
139
|
}
|
|
120
140
|
//#endregion
|
|
121
|
-
export { ServerPreloadHeaderOptions as a, ServerPrerenderResult as c,
|
|
141
|
+
export { ServerPreloadHeaderOptions as a, ServerPrerenderResult as c, RenderTreeCollector as d, RenderTreeKind as f, ServerFragmentRenderResult as i, ServerRenderOptions as l, createRenderTreeCollector as m, ServerErrorInfo as n, ServerPreloadHeaderResource as o, RenderTreeNode as p, ServerErrorPayload as r, ServerPrerenderOptions as s, ServerDocumentRenderResult as t, ServerStreamDataOptions as u };
|
|
@@ -89,8 +89,8 @@ function createStaticDispatcher(options) {
|
|
|
89
89
|
readContext(context) {
|
|
90
90
|
return readContextValue(options.contextValues, context);
|
|
91
91
|
},
|
|
92
|
+
readBrowser: options.readBrowser,
|
|
92
93
|
readData: options.readData,
|
|
93
|
-
preloadData: options.preloadData,
|
|
94
94
|
readPromise: options.readPromise
|
|
95
95
|
};
|
|
96
96
|
}
|
|
@@ -158,6 +158,6 @@ function imageFetchpriority(value) {
|
|
|
158
158
|
return value === "high" || value === "auto" ? value : void 0;
|
|
159
159
|
}
|
|
160
160
|
//#endregion
|
|
161
|
-
export {
|
|
161
|
+
export { componentStack as a, noLane as c, serverErrorPayload as d, streamFlowBlocked as f, cloneContextValues as i, nonceAttribute as l, withContextValue as m, suppressesImagePreloads as n, createStaticDispatcher as o, streamHighWaterMark as p, STREAMED_METADATA_ATTRIBUTE as r, deferred as s, imagePreloadFromHostProps as t, noop as u };
|
|
162
162
|
|
|
163
|
-
//# sourceMappingURL=image-preloads-
|
|
163
|
+
//# sourceMappingURL=image-preloads-CztoSryT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-preloads-CztoSryT.js","names":[],"sources":["../src/shared.ts","../src/image-preloads.ts"],"sourcesContent":["import type {\n ActionStateAction,\n ActionStateRunner,\n DependencyList,\n ExternalStoreSubscribe,\n FigContext,\n StateSetter,\n StartTransition,\n TransitionCallback,\n} from \"@bgub/fig\";\nimport type {\n BrowserRenderReason,\n DataResource,\n RenderDispatcher,\n StableEventCallerArgs,\n} from \"@bgub/fig/internal\";\nimport { runTransitionScope } from \"@bgub/fig/internal\";\nimport { escapeAttribute } from \"./escaping.ts\";\nimport type { ServerErrorPayload, ServerRenderOptions } from \"./types.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\n\nexport type ContextValues = Map<FigContext<unknown>, unknown[]>;\n\nexport const STREAMED_METADATA_ATTRIBUTE = \"data-fig-streamed-metadata\";\n\nexport function noLane(): null {\n return null;\n}\n\nexport function noop(): void {}\n\nexport interface StackFrame {\n name: string;\n parent: StackFrame | null;\n}\n\ninterface StaticDispatcherOptions {\n contextValues: ContextValues;\n externalStoreError: string;\n readBrowser(this: void, reason?: BrowserRenderReason): void;\n readData<TArgs extends unknown[], TValue>(\n this: void,\n resource: DataResource<TArgs, TValue>,\n args: TArgs,\n ): TValue;\n readPromise<T>(this: void, promise: PromiseLike<T>): T;\n updateError: string;\n useId(this: void): string;\n}\n\nexport function withContextValue<T>(\n values: ContextValues,\n context: FigContext<unknown>,\n value: unknown,\n callback: () => T,\n): T {\n let stack = values.get(context);\n if (stack === undefined) {\n stack = [];\n values.set(context, stack);\n }\n stack.push(value);\n\n try {\n return callback();\n } finally {\n stack.pop();\n }\n}\n\nfunction readContextValue<T>(values: ContextValues, context: FigContext<T>): T {\n const stack = values.get(context as FigContext<unknown>);\n if (stack !== undefined && stack.length > 0) {\n return stack[stack.length - 1] as T;\n }\n\n return context.defaultValue;\n}\n\nexport interface Deferred<T> {\n promise: Promise<T>;\n reject: (reason: unknown) => void;\n resolve: (value: T) => void;\n}\n\nexport function deferred<T>(): Deferred<T> {\n let resolve: Deferred<T>[\"resolve\"] | null = null;\n let reject: Deferred<T>[\"reject\"] | null = null;\n const promise = new Promise<T>((innerResolve, innerReject) => {\n resolve = innerResolve;\n reject = innerReject;\n });\n if (resolve === null || reject === null) {\n throw new Error(\"Promise executor did not initialize its deferred.\");\n }\n return { promise, reject, resolve };\n}\n\nexport function cloneContextValues(values: ContextValues): ContextValues {\n const clone: ContextValues = new Map();\n for (const [context, stack] of values) clone.set(context, [...stack]);\n return clone;\n}\n\n// Encoded bytes a render result stream's internal queue holds before flushing\n// pauses (resumed by consumer pulls). Shared by the HTML and payload\n// renderers. Large enough that a healthy consumer never blocks a flush; small\n// enough to bound per-connection buffering when the consumer stalls.\n// Rendering itself never pauses — only writing to the stream does.\nconst DEFAULT_STREAM_HIGH_WATER_MARK = 65536;\n\n// 0 would deadlock: desiredSize never goes positive, and read requests alone\n// do not make it so. 1 byte is the honest pure-pull minimum.\nexport function streamHighWaterMark(option: number | undefined): number {\n return Math.max(1, option ?? DEFAULT_STREAM_HIGH_WATER_MARK);\n}\n\n// Blocked means the stream's internal queue is at or past its high-water\n// mark; completed work then waits un-enqueued until the consumer pulls.\n// desiredSize is null on an errored stream — never blocked, because fatal\n// paths close the request before any further writes.\nexport function streamFlowBlocked(\n controller: ReadableStreamDefaultController<Uint8Array> | null,\n): boolean {\n const desiredSize = controller?.desiredSize;\n return typeof desiredSize === \"number\" && desiredSize <= 0;\n}\n\nexport function createStaticDispatcher(\n options: StaticDispatcherOptions,\n): RenderDispatcher {\n const rejectUpdate = (..._args: unknown[]): never => {\n throw new Error(options.updateError);\n };\n\n return {\n useState<S>(initialState: S | (() => S)): [S, StateSetter<S>] {\n const value =\n typeof initialState === \"function\"\n ? (initialState as () => S)()\n : initialState;\n return [value, rejectUpdate];\n },\n useActionState<S, Args extends unknown[]>(\n _action: ActionStateAction<S, Args>,\n initialState: S,\n ): [S, ActionStateRunner<Args>, boolean] {\n return [initialState, rejectUpdate, false];\n },\n useId: options.useId,\n useDeferredValue<T>(\n value: T,\n _initialValue: T | undefined,\n _hasInitialValue: boolean,\n ): T {\n return value;\n },\n useMemo<T>(calculate: () => T, _deps: DependencyList): T {\n return calculate();\n },\n useTransition(): [boolean, StartTransition] {\n return [false, startServerTransition];\n },\n useReactive: noop,\n useBeforePaint: noop,\n useBeforeLayout: noop,\n useSyncExternalStore<T>(\n _subscribe: ExternalStoreSubscribe,\n _getSnapshot: () => T,\n getServerSnapshot?: () => T,\n ): T {\n if (getServerSnapshot === undefined) {\n throw new Error(options.externalStoreError);\n }\n\n return getServerSnapshot();\n },\n useStableEvent<Args extends unknown[], Result>(\n _handler: (...args: Args) => Result,\n ): (...args: StableEventCallerArgs<Args>) => Result {\n return rejectStableEventCall;\n },\n readContext<T>(context: FigContext<T>): T {\n return readContextValue(options.contextValues, context);\n },\n readBrowser: options.readBrowser,\n readData: options.readData,\n readPromise: options.readPromise,\n };\n}\n\n// There is no scheduling priority on the server, but callback lifetimes and\n// explicit update scopes obey the same contract as client transitions.\nfunction startServerTransition(callback: TransitionCallback): void {\n void runTransitionScope(callback, (run) => run());\n}\n\nfunction rejectStableEventCall<Args extends unknown[], Result>(\n ..._args: StableEventCallerArgs<Args>\n): Result {\n throw new Error(\"Stable events cannot be called during server render.\");\n}\n\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function componentStack(stack: StackFrame | null): string {\n const frames: string[] = [];\n for (let frame = stack; frame !== null; frame = frame.parent) {\n frames.push(` at ${frame.name}`);\n }\n return frames.length === 0 ? \"\" : `\\n${frames.join(\"\\n\")}`;\n}\n\nexport function serverErrorPayload(\n error: unknown,\n stack: StackFrame | null,\n onError: ServerRenderOptions[\"onError\"],\n): ServerErrorPayload {\n if (onError === undefined) {\n return __DEV__ ? { message: errorMessage(error) } : {};\n }\n try {\n return onError(error, { componentStack: componentStack(stack) }) ?? {};\n } catch {\n return {};\n }\n}\n\nexport function nonceAttribute(nonce: string | undefined): string {\n return nonce === undefined ? \"\" : ` nonce=\"${escapeAttribute(nonce)}\"`;\n}\n","import type { PreloadResource, Props } from \"@bgub/fig\";\n\nexport function imagePreloadFromHostProps(\n type: string,\n props: Props,\n suppressed: boolean,\n): PreloadResource | null {\n if (suppressed || type.toLowerCase() !== \"img\") return null;\n if (props.loading === \"lazy\" || props.fetchpriority === \"low\") return null;\n\n const src = stringProp(props.src);\n const srcset = stringProp(props.srcset);\n if (\n (props.src != null && typeof props.src !== \"string\") ||\n (props.srcset != null && typeof props.srcset !== \"string\") ||\n (!src && !srcset) ||\n isDataUrl(src) ||\n isDataUrl(srcset)\n ) {\n return null;\n }\n\n return {\n as: \"image\",\n crossorigin: imageCrossorigin(props.crossorigin),\n fetchpriority: imageFetchpriority(props.fetchpriority),\n href: src || undefined,\n imagesizes: srcset ? stringProp(props.sizes) : undefined,\n imagesrcset: srcset || undefined,\n kind: \"preload\",\n referrerpolicy: stringProp(props.referrerpolicy),\n type: stringProp(props.type),\n };\n}\n\nexport function suppressesImagePreloads(type: string): boolean {\n const normalizedType = type.toLowerCase();\n return normalizedType === \"picture\" || normalizedType === \"noscript\";\n}\n\nfunction stringProp(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction isDataUrl(value: string | undefined): boolean {\n return value?.slice(0, 5).toLowerCase() === \"data:\";\n}\n\nfunction imageCrossorigin(value: unknown): PreloadResource[\"crossorigin\"] {\n if (typeof value !== \"string\") return undefined;\n if (value === \"anonymous\" || value === \"use-credentials\" || value === \"\") {\n return value;\n }\n return \"\";\n}\n\nfunction imageFetchpriority(value: unknown): PreloadResource[\"fetchpriority\"] {\n return value === \"high\" || value === \"auto\" ? value : undefined;\n}\n"],"mappings":";;;AA0BA,MAAa,8BAA8B;AAE3C,SAAgB,SAAe;CAC7B,OAAO;AACT;AAEA,SAAgB,OAAa,CAAC;AAqB9B,SAAgB,iBACd,QACA,SACA,OACA,UACG;CACH,IAAI,QAAQ,OAAO,IAAI,OAAO;CAC9B,IAAI,UAAU,KAAA,GAAW;EACvB,QAAQ,CAAC;EACT,OAAO,IAAI,SAAS,KAAK;CAC3B;CACA,MAAM,KAAK,KAAK;CAEhB,IAAI;EACF,OAAO,SAAS;CAClB,UAAU;EACR,MAAM,IAAI;CACZ;AACF;AAEA,SAAS,iBAAoB,QAAuB,SAA2B;CAC7E,MAAM,QAAQ,OAAO,IAAI,OAA8B;CACvD,IAAI,UAAU,KAAA,KAAa,MAAM,SAAS,GACxC,OAAO,MAAM,MAAM,SAAS;CAG9B,OAAO,QAAQ;AACjB;AAQA,SAAgB,WAA2B;CACzC,IAAI,UAAyC;CAC7C,IAAI,SAAuC;CAC3C,MAAM,UAAU,IAAI,SAAY,cAAc,gBAAgB;EAC5D,UAAU;EACV,SAAS;CACX,CAAC;CACD,IAAI,YAAY,QAAQ,WAAW,MACjC,MAAM,IAAI,MAAM,mDAAmD;CAErE,OAAO;EAAE;EAAS;EAAQ;CAAQ;AACpC;AAEA,SAAgB,mBAAmB,QAAsC;CACvE,MAAM,wBAAuB,IAAI,IAAI;CACrC,KAAK,MAAM,CAAC,SAAS,UAAU,QAAQ,MAAM,IAAI,SAAS,CAAC,GAAG,KAAK,CAAC;CACpE,OAAO;AACT;AAOA,MAAM,iCAAiC;AAIvC,SAAgB,oBAAoB,QAAoC;CAC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