@bgub/fig-server 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +295 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +1429 -0
- package/dist/index.js.map +1 -0
- package/dist/payload.d.ts +258 -0
- package/dist/payload.js +1700 -0
- package/dist/payload.js.map +1 -0
- package/dist/shared-CQn6Dje6.js +105 -0
- package/dist/shared-CQn6Dje6.js.map +1 -0
- package/dist/types-4X0JT0wt.d.ts +83 -0
- package/package.json +52 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["writeRuntime","writeScript"],"sources":["../src/html.ts","../src/asset-registry.ts","../src/protocol.ts","../src/renderer.ts","../src/render-tree.ts","../src/index.ts"],"sourcesContent":["import type { Props } from \"@bgub/fig\";\nimport { isPortal } from \"@bgub/fig/internal\";\n\ninterface HtmlSink {\n write(chunk: string): void;\n}\n\nconst voidElements = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\nexport function writeText(value: string, sink: HtmlSink): void {\n sink.write(escapeText(value));\n}\n\nexport function writeElementStart(\n type: string,\n props: Props,\n sink: HtmlSink,\n inheritedProps: Props = {},\n): void {\n validateTagName(type);\n sink.write(`<${type}`);\n writeAttributes(type, props, inheritedProps, sink);\n sink.write(\">\");\n}\n\nexport function writeElementEnd(type: string, sink: HtmlSink): void {\n sink.write(`</${type}>`);\n}\n\nexport function isVoidElement(type: string): boolean {\n return voidElements.has(type);\n}\n\nexport function hasRenderableChild(node: unknown): boolean {\n if (Array.isArray(node)) return node.some(hasRenderableChild);\n if (isPortal(node)) return false;\n return !emptyChild(node);\n}\n\nexport function formTextContent(type: string, props: Props): string | null {\n if (type !== \"textarea\") return null;\n\n const value = props.value !== undefined ? props.value : props.defaultValue;\n return formString(value);\n}\n\nexport function unsafeHTMLContent(props: Props): string | null {\n const value = props.unsafeHTML;\n if (emptyValue(value)) return null;\n if (typeof value === \"string\") return value;\n throw new Error(\"The unsafeHTML prop must be a string during server render.\");\n}\n\nfunction writeAttributes(\n type: string,\n props: Props,\n inheritedProps: Props,\n sink: HtmlSink,\n): void {\n for (const [name, value] of Object.entries(props)) {\n if (reservedProp(name)) continue;\n if (name === \"value\" && props.defaultValue !== undefined) continue;\n if (name === \"checked\" && props.defaultChecked !== undefined) continue;\n\n if (name === \"style\") {\n const style = serializeStyle(value);\n if (style !== \"\") writeAttribute(sink, \"style\", style);\n continue;\n }\n\n const attribute = formAttribute(type, name, value);\n if (attribute === null) continue;\n\n const [attributeNameValue, attributeValue] = attribute;\n validateAttributeName(attributeNameValue);\n\n if (attributeValue === true) {\n sink.write(` ${attributeNameValue}`);\n continue;\n }\n\n if (serializableAttributeValue(attributeValue)) {\n writeAttribute(sink, attributeNameValue, String(attributeValue));\n continue;\n }\n\n throw new Error(`Cannot serialize prop \"${name}\" to HTML.`);\n }\n\n if (\n type === \"option\" &&\n props.selected === undefined &&\n optionSelected(optionValue(props), inheritedProps)\n ) {\n sink.write(\" selected\");\n }\n}\n\nfunction formAttribute(\n type: string,\n name: string,\n value: unknown,\n): [string, unknown] | null {\n if ((type === \"textarea\" || type === \"select\") && valueProp(name)) {\n return null;\n }\n\n if (valueProp(name)) {\n return valueAttribute(value);\n }\n\n if (name === \"defaultChecked\") {\n return value === true ? [\"checked\", true] : null;\n }\n\n if (type === \"option\" && name === \"selected\") {\n return value === true ? [\"selected\", true] : null;\n }\n\n return attributeValue(name, value);\n}\n\nfunction attributeValue(\n name: string,\n value: unknown,\n): [string, unknown] | null {\n return emptyValue(value) ? null : [name, value];\n}\n\nfunction valueAttribute(value: unknown): [string, unknown] | null {\n if (emptyValue(value)) return null;\n if (serializableAttributeValue(value)) return [\"value\", String(value)];\n return [\"value\", value];\n}\n\nfunction optionSelected(value: unknown, selectProps: Props): boolean {\n const selectValue =\n selectProps.value !== undefined\n ? selectProps.value\n : selectProps.defaultValue;\n if (emptyValue(selectValue)) return false;\n\n const optionValue = formString(value);\n if (optionValue === null) return false;\n\n return selectedValueSet(selectValue).has(optionValue);\n}\n\nfunction optionValue(props: Props): string | null {\n return props.value === undefined\n ? optionTextValue(props.children)\n : formString(props.value);\n}\n\nfunction optionTextValue(node: unknown): string | null {\n if (typeof node === \"string\" || typeof node === \"number\") {\n return String(node);\n }\n if (Array.isArray(node)) {\n let text = \"\";\n for (const child of node) {\n const childText = optionTextValue(child);\n if (childText === null) return null;\n text += childText;\n }\n return text;\n }\n return null;\n}\n\nfunction formString(value: unknown): string | null {\n if (emptyValue(value)) return null;\n if (serializableAttributeValue(value)) return String(value);\n return null;\n}\n\nfunction selectedValueSet(value: unknown): Set<string> {\n return new Set(Array.isArray(value) ? value.map(String) : [String(value)]);\n}\n\nfunction serializableAttributeValue(value: unknown): boolean {\n return (\n value === true ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\"\n );\n}\n\nfunction emptyValue(value: unknown): boolean {\n return value === null || value === undefined || value === false;\n}\n\nfunction emptyChild(value: unknown): boolean {\n return value === null || value === undefined || typeof value === \"boolean\";\n}\n\nfunction writeAttribute(sink: HtmlSink, name: string, value: string): void {\n sink.write(` ${name}=\"${escapeAttribute(value)}\"`);\n}\n\nfunction serializeStyle(value: unknown): string {\n if (emptyValue(value)) return \"\";\n if (typeof value !== \"object\" || value === null) {\n throw new Error(\"The style prop must be an object during server render.\");\n }\n\n const declarations: string[] = [];\n for (const [name, item] of Object.entries(value)) {\n if (emptyValue(item)) continue;\n if (\n typeof item !== \"string\" &&\n typeof item !== \"number\" &&\n typeof item !== \"bigint\"\n ) {\n throw new Error(`Cannot serialize style property \"${name}\" to HTML.`);\n }\n\n declarations.push(`${styleName(name)}:${String(item)}`);\n }\n\n return declarations.join(\";\");\n}\n\nfunction reservedProp(name: string): boolean {\n return (\n name === \"children\" ||\n name === \"key\" ||\n name === \"events\" ||\n name === \"bind\" ||\n name === \"suppressHydrationWarning\" ||\n name === \"unsafeHTML\" ||\n /^on[A-Z]/.test(name)\n );\n}\n\nfunction valueProp(name: string): boolean {\n return name === \"value\" || name === \"defaultValue\";\n}\n\nfunction styleName(name: string): string {\n if (name.startsWith(\"--\")) return name;\n return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n\nfunction validateTagName(name: string): void {\n if (!/^[A-Za-z][A-Za-z0-9:._-]*$/.test(name)) {\n throw new Error(`Invalid HTML tag name \"${name}\".`);\n }\n}\n\nfunction validateAttributeName(name: string): void {\n if (/[\\s\"'<>/=]/.test(name)) {\n throw new Error(`Invalid HTML attribute name \"${name}\".`);\n }\n}\n\nexport function escapeText(value: string): string {\n return value.replace(/[&<>]/g, (character) => {\n if (character === \"&\") return \"&\";\n if (character === \"<\") return \"<\";\n return \">\";\n });\n}\n\nexport function escapeAttribute(value: string): string {\n return value.replace(/[&\"<>]/g, (character) => {\n if (character === \"&\") return \"&\";\n if (character === '\"') return \""\";\n if (character === \"<\") return \"<\";\n return \">\";\n });\n}\n","import { type FigAssetResource, type Props } from \"@bgub/fig\";\nimport {\n assetResourceDestination,\n assetResourceHostAttributes,\n assetResourceKey,\n} from \"@bgub/fig/internal\";\nimport { writeElementEnd, writeElementStart, writeText } from \"./html.ts\";\n\nexport class AssetResourceRegistry {\n private readonly emittedResources = new Set<string>();\n private readonly resources = new Map<string, FigAssetResource>();\n private readonly stylesheetIds = new Map<string, string>();\n private nextStylesheetId = 0;\n\n constructor(private readonly identifierPrefix: string) {}\n\n register(resource: FigAssetResource): boolean {\n return this.canonical(resource).added;\n }\n\n write(resource: FigAssetResource, sink: AssetSink): string | null {\n const { key, resource: current } = this.canonical(resource);\n const id = this.revealBlockerId(key, current);\n\n if (assetResourceDestination(current) === \"head\") return id;\n if (this.emittedResources.has(key)) return id;\n\n this.emittedResources.add(key);\n writeAssetTag(sink, current, id);\n return id;\n }\n\n headHtml(nonce?: string): string {\n let html = \"\";\n const sink = {\n nonce,\n write(chunk: string) {\n html += chunk;\n },\n };\n\n for (const resource of this.resources.values()) {\n if (assetResourceDestination(resource) === \"head\") {\n writeAssetTag(sink, resource, null);\n }\n }\n\n return html;\n }\n\n private canonical(resource: FigAssetResource): {\n added: boolean;\n key: string;\n resource: FigAssetResource;\n } {\n const key = assetResourceKey(resource);\n const current = this.resources.get(key);\n\n if (current !== undefined) {\n if (assetSignature(current) !== assetSignature(resource)) {\n if (resource.kind === \"title\") {\n this.resources.set(key, resource);\n return { added: false, key, resource };\n }\n throw new AssetResourceConflictError(key, current, resource);\n }\n\n return { added: false, key, resource: current };\n }\n\n this.resources.set(key, resource);\n return { added: true, key, resource };\n }\n\n private revealBlockerId(\n key: string,\n resource: FigAssetResource,\n ): string | null {\n if (resource.kind !== \"stylesheet\") return null;\n if (resource.blocking === \"none\") return null;\n\n return this.stylesheetIdFor(key);\n }\n\n private stylesheetIdFor(key: string): string {\n const current = this.stylesheetIds.get(key);\n if (current !== undefined) return current;\n\n const id =\n this.identifierPrefix === \"\"\n ? `r-${this.nextStylesheetId}`\n : `${this.identifierPrefix}-r-${this.nextStylesheetId}`;\n this.nextStylesheetId += 1;\n this.stylesheetIds.set(key, id);\n return id;\n }\n}\n\nexport class AssetResourceConflictError extends Error {\n constructor(\n key: string,\n current: FigAssetResource,\n incoming: FigAssetResource,\n ) {\n super(\n `Conflicting Fig resource for key \"${key}\". Existing: ${JSON.stringify(\n current,\n )}. Incoming: ${JSON.stringify(incoming)}.`,\n );\n }\n}\n\ninterface AssetSink {\n nonce?: string;\n write(chunk: string): void;\n}\n\nfunction writeAssetTag(\n sink: AssetSink,\n resource: FigAssetResource,\n id: string | null,\n): void {\n switch (resource.kind) {\n case \"title\":\n writeElementStart(\"title\", {}, sink);\n writeText(resource.value, sink);\n writeElementEnd(\"title\", sink);\n return;\n case \"meta\":\n writeElementStart(\n \"meta\",\n {\n charset: resource.charset,\n name: resource.name,\n property: resource.property,\n \"http-equiv\": resource.httpEquiv,\n content: resource.content,\n \"data-fig-resource-key\": resource.key,\n },\n sink,\n );\n return;\n default: {\n // The attribute set is shared with the client's head insertion; only\n // the server-side reveal-blocker id and nonce are appended here.\n const props: Props = Object.fromEntries(\n assetResourceHostAttributes(resource),\n );\n if (resource.kind === \"stylesheet\" && id !== null) props.id = id;\n\n const tag = resource.kind === \"script\" ? \"script\" : \"link\";\n writeElementStart(tag, withNonce(sink, props), sink);\n if (tag === \"script\") writeElementEnd(\"script\", sink);\n }\n }\n}\n\nfunction withNonce(sink: AssetSink, props: Props): Props {\n return sink.nonce === undefined ? props : { ...props, nonce: sink.nonce };\n}\n\nfunction assetSignature(resource: FigAssetResource): string {\n switch (resource.kind) {\n case \"stylesheet\":\n return signature(\n resource.kind,\n resource.href,\n resource.media ?? \"\",\n resource.precedence ?? \"\",\n resource.crossOrigin ?? \"\",\n resource.blocking ?? \"reveal\",\n );\n case \"preload\":\n return signature(\n resource.kind,\n resource.href,\n resource.as,\n resource.type ?? \"\",\n resource.crossOrigin ?? \"\",\n resource.fetchPriority ?? \"\",\n );\n case \"modulepreload\":\n return signature(\n resource.kind,\n resource.href,\n resource.crossOrigin ?? \"\",\n resource.fetchPriority ?? \"\",\n );\n case \"font\":\n // Mirror the preload-as-font signature: a font shares the preload-font key\n // space (see assetResourceKey), so an equivalent preload(href, \"font\") must\n // produce the same signature and dedupe rather than raising a conflict.\n return signature(\n \"preload\",\n resource.href,\n \"font\",\n resource.type,\n resource.crossOrigin ?? \"anonymous\",\n resource.fetchPriority ?? \"\",\n );\n case \"preconnect\":\n return signature(\n resource.kind,\n resource.href,\n resource.crossOrigin ?? \"\",\n );\n case \"script\":\n return signature(\n resource.kind,\n resource.src,\n resource.module === true,\n resource.async !== false,\n resource.defer === true,\n resource.crossOrigin ?? \"\",\n );\n case \"title\":\n return signature(resource.kind, resource.value);\n case \"meta\":\n return signature(\n resource.kind,\n resource.charset ?? \"\",\n resource.name ?? \"\",\n resource.property ?? \"\",\n resource.httpEquiv ?? \"\",\n resource.content ?? \"\",\n );\n }\n\n return unsupportedAssetResource(resource);\n}\n\nfunction unsupportedAssetResource(resource: FigAssetResource): never {\n throw new Error(`Unsupported asset resource kind: ${resource.kind}`);\n}\n\nfunction signature(...values: Array<string | boolean>): string {\n return JSON.stringify(values);\n}\n","import {\n EARLY_EVENT_HANDLER_PROPERTY,\n EARLY_EVENT_QUEUE_PROPERTY,\n REPLAYABLE_EVENT_TYPES,\n SUSPENSE_CLIENT_MARKER,\n SUSPENSE_COMPLETED_MARKER,\n SUSPENSE_END_MARKER,\n SUSPENSE_MARKER_PREFIX,\n VIEW_TRANSITION_CLASS_ATTRIBUTE,\n VIEW_TRANSITION_NAME_ATTRIBUTE,\n VIEW_TRANSITION_PENDING_PROPERTY,\n} from \"@bgub/fig/internal\";\nimport { escapeAttribute } from \"./html.ts\";\n\ninterface ProtocolRequest {\n identifierPrefix: string;\n nonce?: string;\n runtimeName: string;\n runtimeWritten: boolean;\n}\n\ntype WriteChunk = (chunk: string) => void;\ntype IdentifierRequest = Pick<ProtocolRequest, \"identifierPrefix\">;\n\n// Runtime ops, in order: r=resource gate, s=fill partial segment, c=reveal\n// boundary, x=client-render boundary, ac/ax=the Activity-aware variants. The\n// boundary markers sit in the activity's inert <template>, whose `.content`\n// DocumentFragment is unreachable by getElementById, so Activity-aware ops first\n// search that fragment and then fall back to the light DOM if the activity has\n// already revealed and unpacked.\nexport function serverRuntimeCodeFor(runtimeName: string): string {\n return `globalThis[${jsString(runtimeName)}]??={r(a,f){let n=0,d=()=>{--n||f()};for(let i of a){let e=document.getElementById(i);if(e&&e.tagName==='LINK'&&e.rel==='stylesheet'&&!e.sheet){n++;e.addEventListener('load',d,{once:true});e.addEventListener('error',d,{once:true})}}n||f()},q(e,a){if(e&&e.nodeType===1){if(e.hasAttribute&&e.hasAttribute('${VIEW_TRANSITION_NAME_ATTRIBUTE}'))a.push([e,e.getAttribute('${VIEW_TRANSITION_NAME_ATTRIBUTE}'),e.getAttribute('${VIEW_TRANSITION_CLASS_ATTRIBUTE}')]);if(e.querySelectorAll)for(let x of e.querySelectorAll('[${VIEW_TRANSITION_NAME_ATTRIBUTE}]'))a.push([x,x.getAttribute('${VIEW_TRANSITION_NAME_ATTRIBUTE}'),x.getAttribute('${VIEW_TRANSITION_CLASS_ATTRIBUTE}')])}},g(r){let a=[];this.q(r,a);return a},h(b){let a=[],d=0;for(let e=b;e;){if(e.nodeType===8){if(e.data.indexOf('${SUSPENSE_MARKER_PREFIX}')===0)d++;else if(e.data==='${SUSPENSE_END_MARKER}'){if(d===0)break;d--}}else this.q(e,a);e=e.nextSibling}return a},a(l){for(let x of l){let e=x[0],s=e.style;x[3]=s.viewTransitionName;x[4]=s.viewTransitionClass;s.viewTransitionName=x[1];if(x[2])s.viewTransitionClass=x[2]}},u(l){for(let x of l){let e=x[0],s=e.style;s.viewTransitionName=x[3]||'';s.viewTransitionClass=x[4]||'';!(e.getAttribute&&e.getAttribute('style'))&&e.removeAttribute&&e.removeAttribute('style')}},z(l){for(let f of l)f()},j(t,r){let p=t&&(t.ready||t.finished);p&&p.then?p.then(r,()=>{let f=t&&t.finished;f&&f.then?f.then(r,r):r()}):r()},v(b,s,f){let o=this.h(b),n=this.g(s);if(!o.length&&!n.length){f();return}let d=document,w=d.startViewTransition;if(typeof w!='function'){f();return}let p=d.${VIEW_TRANSITION_PENDING_PROPERTY},pw=p&&(p.finished||p.ready);if(pw&&pw.then){let g=()=>this.v(b,s,f);pw.then(g,g);return}this.a(o);let m=0,l=[],r=()=>{this.u(o);this.u(n);this.z(l)};try{let t=w.call(d,()=>{m=1;f(l);this.a(n)});if(t){d.${VIEW_TRANSITION_PENDING_PROPERTY}=t;let c=()=>{d.${VIEW_TRANSITION_PENDING_PROPERTY}===t&&(d.${VIEW_TRANSITION_PENDING_PROPERTY}=null)},cw=t.finished||t.ready;cw&&cw.then?cw.then(c,c):c()}this.j(t,r)}catch(e){r();if(m)throw e;f()}},s(p,s){p=document.getElementById(p);s=document.getElementById(s);if(!p||!s)return;this.v(p,s,()=>{while(s.firstChild)p.parentNode.insertBefore(s.firstChild,p);p.remove();s.remove()})},f(r,i){if(!r)return null;if(r.id===i)return r;for(let e of r.querySelectorAll?r.querySelectorAll('[id]'):[])if(e.id===i)return e;return null},b(t,b){let e=document.getElementById(t),r=e&&(e.content||e);return this.f(r,b)||document.getElementById(b)},c(b,s){let x=document.getElementById(b),y=document.getElementById(s);this.v(x,y,r=>this.o(x,y,r))},o(b,s,l){if(!b||!s)return;let a=b.previousSibling||b,p=a.parentNode,c=s.content||s;if(!p)return;while(c.firstChild)p.insertBefore(c.firstChild,b);for(let e=b,d=0;e;){if(e.nodeType===8){if(e.data.indexOf('${SUSPENSE_MARKER_PREFIX}')===0)d++;else if(e.data==='${SUSPENSE_END_MARKER}'){if(d===0)break;d--}}let x=e.nextSibling;e.remove();e=x}s.remove();if(a.nodeType===8){a.data='${SUSPENSE_COMPLETED_MARKER}';let r=a.__figRetry;if(r){if(l)l.push(r);else r()}}},x(b,d,m){this.y(document.getElementById(b),d,m)},y(b,d,m){if(!b)return;let s=b.previousSibling;if(s&&s.nodeType===8){s.data='${SUSPENSE_CLIENT_MARKER}';if(d)b.dataset.dgst=d;if(m)b.dataset.msg=m;s.__figRetry&&s.__figRetry()}},ac(t,b,s){let x=this.b(t,b),y=document.getElementById(s);this.v(x,y,r=>this.o(x,y,r))},ax(t,b,d,m){this.y(this.b(t,b),d,m)}}`;\n}\n\nexport function writeRuntime(\n request: ProtocolRequest,\n write: WriteChunk,\n): void {\n if (request.runtimeWritten) return;\n request.runtimeWritten = true;\n writeScript(request, serverRuntimeCodeFor(request.runtimeName), write);\n}\n\nexport function writeScript(\n request: Pick<ProtocolRequest, \"nonce\">,\n code: string,\n write: WriteChunk,\n): void {\n write(\n `<script${request.nonce === undefined ? \"\" : ` nonce=\"${escapeAttribute(request.nonce)}\"`}>${code}</script>`,\n );\n}\n\n// Queues replayable events that fire before the client bundle executes so\n// hydration can honor a user's first interaction instead of losing it. Sits\n// first in <head> — capture must be live before any content paints. The\n// first hydration root drains the queue and removes these listeners\n// (fig-dom's adoptEarlyEvents); a document without a client bundle just\n// carries a small inert array.\nexport function earlyEventCaptureCode(): string {\n const types = REPLAYABLE_EVENT_TYPES.map((type) => `'${type}'`).join(\",\");\n return `(d=>{if(d.${EARLY_EVENT_QUEUE_PROPERTY})return;let q=d.${EARLY_EVENT_QUEUE_PROPERTY}=[],h=d.${EARLY_EVENT_HANDLER_PROPERTY}=e=>{q.push(e)};for(let t of [${types}])d.addEventListener(t,h,!0)})(document)`;\n}\n\nexport function earlyEventCaptureMarkup(\n request: Pick<ProtocolRequest, \"nonce\">,\n): string {\n let markup = \"\";\n writeScript(request, earlyEventCaptureCode(), (chunk) => {\n markup += chunk;\n });\n return markup;\n}\n\nexport function placeholderMarkup(\n request: IdentifierRequest,\n id: number,\n): string {\n return templateMarkup(placeholderId(request, id));\n}\n\nexport function boundaryPlaceholderMarkup(\n request: IdentifierRequest,\n id: number,\n): string {\n return templateMarkup(boundaryId(request, id));\n}\n\nfunction templateMarkup(id: string): string {\n return `<template id=\"${escapeAttribute(id)}\"></template>`;\n}\n\nexport function segmentContainerStartMarkup(\n request: IdentifierRequest,\n id: number,\n): string {\n const escapedId = escapeAttribute(segmentId(request, id));\n return `<div hidden id=\"${escapedId}\">`;\n}\n\nexport function activityId(request: IdentifierRequest, id: number): string {\n return prefixedId(request, \"a\", id);\n}\n\nexport function placeholderId(request: IdentifierRequest, id: number): string {\n return prefixedId(request, \"p\", id);\n}\n\nexport function segmentId(request: IdentifierRequest, id: number): string {\n return prefixedId(request, \"s\", id);\n}\n\nexport function boundaryId(request: IdentifierRequest, id: number): string {\n return prefixedId(request, \"b\", id);\n}\n\nexport function jsString(value: string): string {\n return JSON.stringify(value).replace(/</g, \"\\\\u003C\");\n}\n\nfunction prefixedId(\n request: IdentifierRequest,\n kind: string,\n id: number,\n): string {\n return request.identifierPrefix === \"\"\n ? `${kind}-${id}`\n : `${request.identifierPrefix}-${kind}-${id}`;\n}\n","import {\n createElement,\n type ElementType,\n type FigAssetResource,\n type FigClientReference,\n type FigContext,\n type FigElement,\n type FigNode,\n Fragment,\n type Props,\n type ViewTransitionProps,\n} from \"@bgub/fig\";\nimport {\n ACTIVITY_TEMPLATE_ATTRIBUTE,\n assetResourceDestination,\n assetResourceFromHostProps,\n assetResourceKey,\n collectChildren,\n createDataStore,\n type DataStore,\n invalidChildError,\n isActivity,\n isAssets,\n isClientReference,\n isContext,\n isErrorBoundary,\n isFigAssetResource,\n isPortal,\n isSuspense,\n isThenable,\n isValidElement,\n isViewTransition,\n type NormalizedChild,\n type RenderDispatcher,\n readThenable,\n SUSPENSE_CLIENT_MARKER,\n SUSPENSE_COMPLETED_MARKER,\n SUSPENSE_END_MARKER,\n SUSPENSE_PENDING_PREFIX,\n setCurrentDataStore,\n setCurrentDispatcher,\n type Thenable,\n validateInstanceNesting,\n validateTextNesting,\n VIEW_TRANSITION_CLASS_ATTRIBUTE,\n VIEW_TRANSITION_NAME_ATTRIBUTE,\n} from \"@bgub/fig/internal\";\nimport { AssetResourceRegistry } from \"./asset-registry.ts\";\nimport {\n escapeAttribute,\n formTextContent,\n hasRenderableChild,\n isVoidElement,\n unsafeHTMLContent,\n writeElementEnd,\n writeElementStart,\n writeText,\n} from \"./html.ts\";\nimport {\n activityId,\n boundaryId,\n boundaryPlaceholderMarkup,\n earlyEventCaptureMarkup,\n jsString,\n placeholderId,\n placeholderMarkup,\n segmentContainerStartMarkup,\n segmentId,\n writeRuntime as writeProtocolRuntime,\n writeScript as writeProtocolScript,\n} from \"./protocol.ts\";\nimport {\n type ContextValues,\n cloneContextValues,\n createStaticDispatcher,\n type Deferred,\n deferred,\n withContextValue,\n} from \"./shared.ts\";\nimport type { RenderTreeNode } from \"./render-tree.ts\";\nimport type {\n ServerErrorPayload,\n ServerFragmentRenderResult,\n ServerRenderOptions,\n} from \"./types.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\n\ninterface Request {\n abortableTasks: Set<Task>;\n abortListener: (() => void) | null;\n abortSignal: AbortSignal | null;\n allReady: Deferred<void>;\n completedBoundaries: Set<SuspenseBoundary>;\n completedRootSegment: Segment | null;\n controller: ReadableStreamDefaultController<Uint8Array> | null;\n dataStore: DataStore<object, null>;\n fatalError: unknown;\n identifierPrefix: string;\n nextBoundaryId: number;\n nextSegmentId: number;\n nextActivityId: number;\n nextViewTransitionId: number;\n nonce?: string;\n onError?: ServerRenderOptions[\"onError\"];\n onAssetError?: ServerRenderOptions[\"onAssetError\"];\n pendingRootTasks: number;\n pendingTasks: number;\n pingedTasks: Task[];\n assetSink: AssetSink;\n rootSegment: Segment;\n runtimeName: string;\n runtimeWritten: boolean;\n headReady: Deferred<string>;\n // Set exactly once, when the shell completes and the head is sealed; also\n // the \"head is sealed\" flag.\n headSnapshot: string | null;\n shellReady: Deferred<void>;\n status: \"opening\" | \"open\" | \"aborting\" | \"closed\";\n stream: ReadableStream<Uint8Array>;\n clientRenderedBoundaries: Set<SuspenseBoundary>;\n clientReferenceFallback?: ServerRenderOptions[\"clientReferenceFallback\"];\n partialBoundaries: Set<SuspenseBoundary>;\n prerender: boolean;\n componentAssets?: ServerRenderOptions[\"assets\"];\n document: DocumentState | null;\n assetRegistry: AssetResourceRegistry;\n resolveAssetKey?: ServerRenderOptions[\"resolveAssetKey\"];\n workScheduled: boolean;\n // Chunks accumulate here per flush pass and leave as one encoded enqueue,\n // instead of one tiny Uint8Array per attribute/text write.\n writeBuffer: string[];\n}\n\n// Render-scope state shared by queued tasks and live frames; forked (with\n// context values cloned) whenever work is spawned or resumed.\ninterface RenderScope {\n abortSet: Set<Task>;\n boundary: SuspenseBoundary | null;\n contextValues: ContextValues;\n // The nearest enclosing hidden Activity's template id, or null when not inside\n // one. Threaded so suspended content streamed for that boundary can be revealed\n // into the activity template's inert content.\n hiddenActivityId: string | null;\n // Logical host-ancestor tags (nearest first) for DOM-nesting validation.\n // Suspended segments stream into staging nodes but are moved into place on\n // the client, so their spawn-point ancestors stay authoritative.\n hostAncestors: readonly string[];\n idPath: string;\n selectProps: Props | null;\n stack: StackFrame | null;\n // Where collected render-tree nodes attach; null when no collector was\n // passed. Forked into suspended tasks so resumed content lands under its\n // boundary's node.\n treeParent: RenderTreeNode | null;\n viewTransition: ServerViewTransitionContext | null;\n}\n\ninterface Task extends RenderScope {\n // Index of the suspended child within its original normalized children\n // sequence. Resuming id-path numbering here keeps useId paths identical to\n // the never-suspending render (and to client fiber indices).\n childIndexBase: number;\n node: FigNode;\n segment: Segment;\n}\n\ninterface Segment {\n boundary: SuspenseBoundary | null;\n children: Segment[];\n chunks: Array<string | typeof documentHeadMarker>;\n id: number | null;\n index: number;\n // True when the trailing edge of everything written so far — including the\n // inherited parent position for spawned segments — is document text. The\n // next text write must lead with TEXT_SEPARATOR so the browser's parser\n // does not merge the two into one DOM text node.\n lastPushedText: boolean;\n parentFlushed: boolean;\n assetResources: FigAssetResource[];\n status: SegmentStatus;\n // Spawned suspended segments splice between their parent's chunks, so text\n // may directly follow their end; when such a segment completes ending in\n // text, it closes with a trailing TEXT_SEPARATOR.\n textEmbedded: boolean;\n write(chunk: string): void;\n}\n\ninterface SuspenseBoundary {\n // Non-null when this boundary lives inside a hidden Activity: the activity\n // template id its streamed completion must be revealed into. See `ac`/`ax` in\n // protocol.ts.\n activityId: string | null;\n completedSegments: Segment[];\n contentSegment: Segment;\n error: ServerErrorPayload | null;\n fallbackAbortableTasks: Set<Task>;\n id: number | null;\n parentFlushed: boolean;\n pendingTasks: number;\n status: BoundaryStatus;\n}\n\ntype BoundaryStatus = \"pending\" | \"completed\" | \"client-rendered\";\ntype SegmentStatus = \"pending\" | \"rendering\" | \"completed\" | \"flushed\";\ntype Component = (props: Props & { children?: FigNode }) => FigNode;\n\ninterface RenderFrame extends RenderScope {\n dispatcher: RenderDispatcher;\n localIdCounter: number;\n pendingLeadingNewlineHost: string | null;\n request: Request;\n segment: Segment;\n}\n\ninterface StackFrame {\n name: string;\n parent: StackFrame | null;\n}\n\ninterface DocumentState {\n hasHead: boolean;\n}\n\ninterface ServerViewTransitionContext {\n className: string | null;\n index: number;\n name: string;\n}\n\ninterface AssetSink {\n nonce?: string;\n write(chunk: string): void;\n}\n\nconst errorStacks = new WeakMap<object, StackFrame>();\nconst textEncoder = new TextEncoder();\nconst documentHeadMarker = Symbol(\"fig.document-head\");\nconst RUNTIME_REF = \"__figSSR\";\n// Emitted between two adjacent text writes that come from different\n// normalized text children (component seams, resumed suspended segments).\n// The HTML parser merges back-to-back character data into ONE DOM text node,\n// while the client tree keeps one text fiber per normalized child (see\n// collectChildren in @bgub/fig) — the comment keeps the nodes apart so each\n// fiber can claim its own during hydration. fig-dom's hydration cursor skips\n// comments whose data is exactly \",\" (and only those; suspense markers use\n// the fig:suspense prefixes).\nconst TEXT_SEPARATOR = \"<!--,-->\";\nlet nextRuntimeId = 0;\n\nexport function createServerRenderRequest(\n node: FigNode,\n options: ServerRenderOptions = {},\n mode: { document?: boolean; prerender?: boolean } = {},\n): ServerFragmentRenderResult {\n throwIfAborted(options.signal);\n\n const shellReady = deferred<void>();\n const headReady = deferred<string>();\n const allReady = deferred<void>();\n // The readiness promises also reject through the stream; pre-attached\n // no-op handlers keep the ones a caller does not await from becoming\n // unhandled rejections (await-ers still observe the rejection).\n void shellReady.promise.catch(() => undefined);\n void headReady.promise.catch(() => undefined);\n void allReady.promise.catch(() => undefined);\n const rootSegment = createSegment(0, null);\n\n const request: Request = {\n abortableTasks: new Set<Task>(),\n abortListener: null,\n abortSignal: options.signal ?? null,\n allReady,\n completedBoundaries: new Set(),\n completedRootSegment: null,\n controller: null,\n dataStore: createDataStore<object, null>({\n getLane: () => null,\n partition: options.dataPartition,\n schedule: () => undefined,\n }),\n fatalError: null,\n identifierPrefix: options.identifierPrefix ?? \"\",\n nextBoundaryId: 0,\n nextSegmentId: 0,\n nextActivityId: 0,\n nextViewTransitionId: 0,\n nonce: options.nonce,\n onError: options.onError,\n onAssetError: options.onAssetError,\n pendingRootTasks: 0,\n pendingTasks: 0,\n pingedTasks: [],\n assetSink: null as never,\n rootSegment,\n runtimeName: createRuntimeName(options.identifierPrefix),\n runtimeWritten: false,\n headReady,\n headSnapshot: null,\n shellReady,\n status: \"opening\",\n stream: null as never,\n clientRenderedBoundaries: new Set(),\n clientReferenceFallback: options.clientReferenceFallback,\n partialBoundaries: new Set(),\n prerender: mode.prerender === true,\n componentAssets: options.assets,\n document: mode.document === true ? { hasHead: false } : null,\n assetRegistry: new AssetResourceRegistry(options.identifierPrefix ?? \"\"),\n resolveAssetKey: options.resolveAssetKey,\n workScheduled: false,\n writeBuffer: [],\n };\n request.assetSink = {\n nonce: options.nonce,\n write: (chunk) => write(request, chunk),\n };\n\n const stream = new ReadableStream<Uint8Array>({\n start(streamController) {\n request.controller = streamController;\n flushCompletedQueues(request);\n },\n cancel(reason) {\n abort(request, reason);\n },\n });\n request.stream = stream;\n\n rootSegment.parentFlushed = true;\n const rootTask = createTask(request, node, rootSegment, {\n abortSet: request.abortableTasks,\n boundary: null,\n contextValues: new Map(),\n hiddenActivityId: null,\n hostAncestors: [],\n idPath: \"\",\n selectProps: null,\n stack: null,\n treeParent: options.renderTree?.tree ?? null,\n viewTransition: null,\n });\n request.pingedTasks.push(rootTask);\n\n if (options.signal !== undefined) {\n const abortListener = () => abort(request, options.signal?.reason);\n request.abortListener = abortListener;\n options.signal.addEventListener(\"abort\", abortListener, { once: true });\n }\n\n request.workScheduled = true;\n queueMicrotask(() => {\n request.workScheduled = false;\n performWork(request);\n });\n\n return {\n abort: (reason?: unknown) => abort(request, reason),\n allReady: allReady.promise,\n contentType: \"text/html; charset=utf-8\",\n getData: () => request.dataStore.snapshot(),\n getHead: () =>\n request.headSnapshot ?? request.assetRegistry.headHtml(request.nonce),\n headReady: headReady.promise,\n shellReady: shellReady.promise,\n stream,\n };\n}\n\nfunction createTask(\n request: Request,\n node: FigNode,\n segment: Segment,\n scope: RenderScope,\n childIndexBase = 0,\n): Task {\n request.pendingTasks += 1;\n if (scope.boundary === null) {\n request.pendingRootTasks += 1;\n } else {\n scope.boundary.pendingTasks += 1;\n }\n\n const task: Task = { ...scope, childIndexBase, node, segment };\n request.abortableTasks.add(task);\n scope.abortSet.add(task);\n return task;\n}\n\n// Copies a scope for spawned or resumed work. Context values are cloned so\n// the fork observes the provider stack as of the fork point.\nfunction forkScope(scope: RenderScope): RenderScope {\n return {\n abortSet: scope.abortSet,\n boundary: scope.boundary,\n contextValues: cloneContextValues(scope.contextValues),\n hiddenActivityId: scope.hiddenActivityId,\n hostAncestors: scope.hostAncestors,\n idPath: scope.idPath,\n selectProps: scope.selectProps,\n stack: scope.stack,\n treeParent: scope.treeParent,\n // Forked branches get their own surface-index cursor from the same\n // snapshot. A Suspense fallback and its streamed content then produce\n // the SAME name sequence, so the reveal pairs (morphs) them instead of\n // cross-fading two differently suffixed names — and names stay\n // deterministic under parallel task completion.\n viewTransition:\n scope.viewTransition === null ? null : { ...scope.viewTransition },\n };\n}\n\nfunction createSegment(\n index: number,\n boundary: SuspenseBoundary | null,\n textSeams: { lastPushedText: boolean; textEmbedded: boolean } = {\n lastPushedText: false,\n textEmbedded: false,\n },\n): Segment {\n return {\n boundary,\n children: [],\n chunks: [],\n id: null,\n index,\n lastPushedText: textSeams.lastPushedText,\n parentFlushed: false,\n assetResources: [],\n status: \"pending\",\n textEmbedded: textSeams.textEmbedded,\n write(chunk) {\n // Every non-text write (tags, comments, scripts) breaks text adjacency;\n // renderNode's text path re-marks the flag after writing text.\n this.lastPushedText = false;\n this.chunks.push(chunk);\n },\n };\n}\n\nfunction createBoundary(\n fallbackAbortableTasks: Set<Task>,\n contentSegment: Segment,\n): SuspenseBoundary {\n return {\n activityId: null,\n completedSegments: [],\n contentSegment,\n error: null,\n fallbackAbortableTasks,\n id: null,\n parentFlushed: false,\n pendingTasks: 0,\n status: \"pending\",\n };\n}\n\nfunction performWork(request: Request): void {\n if (request.status === \"closed\") return;\n if (request.status === \"opening\") request.status = \"open\";\n\n const tasks = request.pingedTasks;\n request.pingedTasks = [];\n\n for (const task of tasks) retryTask(request, task);\n\n flushCompletedQueues(request);\n}\n\nfunction retryTask(request: Request, task: Task): void {\n if (task.segment.status !== \"pending\") return;\n\n task.segment.status = \"rendering\";\n const frame = createRenderFrame(request, task.segment, forkScope(task));\n\n try {\n renderChildSequence(collectChildren(task.node), frame, task.childIndexBase);\n completeSegmentText(task.segment);\n task.segment.status = \"completed\";\n detachTask(request, task);\n finishedTask(request, task, task.segment);\n } catch (error) {\n detachTask(request, task);\n task.segment.status = \"completed\";\n erroredTask(request, task, error);\n }\n}\n\nfunction createRenderFrame(\n request: Request,\n segment: Segment,\n scope: RenderScope,\n): RenderFrame {\n const frame = {\n ...scope,\n dispatcher: null as unknown as RenderDispatcher,\n localIdCounter: 0,\n pendingLeadingNewlineHost: null,\n request,\n segment,\n };\n frame.dispatcher = createServerDispatcher(frame);\n return frame;\n}\n\nfunction createServerDispatcher(frame: RenderFrame): RenderDispatcher {\n return createStaticDispatcher({\n contextValues: frame.contextValues,\n externalStoreError:\n \"useSyncExternalStore requires getServerSnapshot during server render.\",\n readPromise(promise) {\n throwIfAborting(frame.request);\n return readThenable(promise);\n },\n readData(resource, args) {\n throwIfAborting(frame.request);\n return frame.request.dataStore.readData(resource, args, frame);\n },\n preloadData(resource, args) {\n throwIfAborting(frame.request);\n frame.request.dataStore.preloadData(resource, ...args);\n },\n useId() {\n const id = `${frame.request.identifierPrefix}fig-${frame.idPath}-${frame.localIdCounter.toString(32)}`;\n frame.localIdCounter += 1;\n return id;\n },\n updateError: \"State updates are not allowed during server render.\",\n });\n}\n\nfunction renderNode(node: FigNode, frame: RenderFrame): void {\n if (Array.isArray(node)) {\n renderChildren(node, frame);\n return;\n }\n\n if (node === null || node === undefined || typeof node === \"boolean\") {\n return;\n }\n\n if (typeof node === \"string\" || typeof node === \"number\") {\n const text = String(node);\n if (frame.request.document !== null && !frame.request.document.hasHead) {\n if (text.trim() !== \"\") throw invalidDocumentShellError();\n }\n if (__DEV__) {\n validateTextNesting(text, frame.hostAncestors);\n }\n if (text !== \"\") {\n if (frame.treeParent !== null) {\n frame.treeParent.children.push({\n children: [],\n key: null,\n kind: \"text\",\n name: \"#text\",\n props: { nodeValue: text },\n });\n }\n const output = consumePendingLeadingNewline(frame)\n ? preserveParserStrippedLeadingNewline(text)\n : text;\n // Directly adjacent text from a different fiber: separate it so the\n // browser's parser yields one DOM text node per client text fiber.\n if (frame.segment.lastPushedText) frame.segment.write(TEXT_SEPARATOR);\n writeText(output, frame.segment);\n frame.segment.lastPushedText = true;\n }\n return;\n }\n\n if (isPortal(node)) return;\n\n if (!isValidElement(node)) throw invalidChildError(node);\n\n renderElement(node, frame);\n}\n\nfunction renderChildren(node: FigNode, frame: RenderFrame): void {\n renderChildSequence(collectChildren(node), frame);\n}\n\nfunction renderChildSequence(\n children: NormalizedChild[],\n frame: RenderFrame,\n // Non-zero when resuming a suspended task: `children` starts at the\n // suspended child's original index, so id-path segments stay stable.\n indexBase = 0,\n): void {\n for (let index = 0; index < children.length; index += 1) {\n try {\n withIdSegment(frame, indexBase + index, () =>\n renderNode(children[index], frame),\n );\n } catch (error) {\n if (isThenable(error)) {\n spawnSuspendedTask(frame, children[index], error, indexBase + index);\n continue;\n }\n\n throw error;\n }\n }\n}\n\n// A spawned segment cannot know what follows its splice point once its\n// parent resumes (or what a sibling spawned segment will start with), so a\n// segment ending in text conservatively closes with a separator; hydration\n// skips any it did not need.\nfunction completeSegmentText(segment: Segment): void {\n if (segment.textEmbedded && segment.lastPushedText) {\n segment.write(TEXT_SEPARATOR);\n }\n}\n\nfunction withIdSegment<T>(\n frame: RenderFrame,\n index: number,\n callback: () => T,\n): T {\n const previousIdPath = frame.idPath;\n const segment = index.toString(32);\n frame.idPath =\n previousIdPath === \"\" ? segment : `${previousIdPath}-${segment}`;\n\n try {\n return callback();\n } finally {\n frame.idPath = previousIdPath;\n }\n}\n\nfunction renderElement(element: FigElement, frame: RenderFrame): void {\n if (frame.treeParent === null) {\n renderElementKind(element, frame);\n return;\n }\n\n const treeNode = collectedTreeNode(element);\n frame.treeParent.children.push(treeNode);\n const previousTreeParent = frame.treeParent;\n frame.treeParent = treeNode;\n try {\n renderElementKind(element, frame);\n } finally {\n frame.treeParent = previousTreeParent;\n }\n}\n\nfunction collectedTreeNode(element: FigElement): RenderTreeNode {\n const { children: _children, ...ownProps } = element.props;\n const [name, kind] = collectedNameAndKind(element.type);\n return {\n children: [],\n key: element.key ?? null,\n kind,\n name,\n props: ownProps,\n };\n}\n\nfunction collectedNameAndKind(type: unknown): [string, RenderTreeNode[\"kind\"]] {\n if (typeof type === \"string\") return [type, \"host\"];\n if (type === Fragment) return [\"Fragment\", \"fragment\"];\n if (isContext(type)) {\n const named = type as { displayName?: unknown };\n const name =\n typeof named.displayName === \"string\" && named.displayName !== \"\"\n ? named.displayName\n : \"Context\";\n return [`${name}.Provider`, \"context-provider\"];\n }\n if (isAssets(type)) return [\"Assets\", \"assets\"];\n if (isSuspense(type)) return [\"Suspense\", \"suspense\"];\n if (isErrorBoundary(type)) return [\"ErrorBoundary\", \"error-boundary\"];\n if (isActivity(type)) return [\"Activity\", \"activity\"];\n if (isViewTransition(type)) return [\"ViewTransition\", \"view-transition\"];\n if (isClientReference(type)) {\n const id = (type as FigClientReference).id;\n const exportName = id.slice(id.lastIndexOf(\"#\") + 1);\n return [\n exportName === \"\" ? \"ClientReference\" : exportName,\n \"client-reference\",\n ];\n }\n if (typeof type === \"function\") {\n return [type.name === \"\" ? \"Anonymous\" : type.name, \"function\"];\n }\n return [\"Anonymous\", \"function\"];\n}\n\nfunction renderElementKind(element: FigElement, frame: RenderFrame): void {\n const type = element.type;\n\n if (typeof type === \"string\") {\n renderHostElement(type, element.props, frame);\n return;\n }\n\n if (type === Fragment) {\n renderChildren(element.props.children, frame);\n return;\n }\n\n if (isContext(type)) {\n renderContextProvider(type, element.props, frame);\n return;\n }\n\n if (isAssets(type)) {\n renderAssets(element.props, frame);\n return;\n }\n\n if (isSuspense(type)) {\n renderSuspense(element.props, frame);\n return;\n }\n\n if (isErrorBoundary(type)) {\n renderChildren(element.props.children, frame);\n return;\n }\n\n if (isClientReference(type)) {\n renderClientReference(type, element.props, frame);\n return;\n }\n\n if (isActivity(type)) {\n renderActivity(element.props, frame);\n return;\n }\n\n if (isViewTransition(type)) {\n renderViewTransition(element.props, frame);\n return;\n }\n\n if (typeof type === \"function\") {\n renderFunctionComponent(type as Component, element.props, frame);\n return;\n }\n\n throw new Error(\n `Unsupported Fig element type: ${describeElementType(type)}.`,\n );\n}\n\nfunction renderFunctionComponent(\n type: Component,\n props: Props,\n frame: RenderFrame,\n): void {\n const previousDispatcher = setCurrentDispatcher(frame.dispatcher);\n const previousDataStore = setCurrentDataStore(frame.request.dataStore);\n const previousStack = frame.stack;\n const previousLocalIdCounter = frame.localIdCounter;\n frame.stack = { name: type.name || \"Anonymous\", parent: previousStack };\n frame.localIdCounter = 0;\n\n try {\n renderComponentAssets(type, frame);\n renderChildren(type(props), frame);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n } finally {\n frame.stack = previousStack;\n frame.localIdCounter = previousLocalIdCounter;\n setCurrentDataStore(previousDataStore);\n setCurrentDispatcher(previousDispatcher);\n }\n}\n\nfunction renderClientReference(\n type: FigClientReference,\n props: Props,\n frame: RenderFrame,\n): void {\n if (type.ssr !== undefined) {\n renderComponentAssets(type, frame);\n renderElement(createElement(type.ssr, props), frame);\n return;\n }\n\n const fallback = frame.request.clientReferenceFallback;\n if (fallback === undefined) {\n renderFunctionComponent(type as Component, props, frame);\n return;\n }\n\n renderComponentAssets(type, frame);\n renderChildren(fallback(type, props), frame);\n}\n\nfunction renderComponentAssets(type: ElementType, frame: RenderFrame): void {\n const key = isClientReference(type)\n ? type.id\n : frame.request.resolveAssetKey?.(type);\n if (key !== undefined) {\n renderAssetValue(frame.request.componentAssets?.[key], frame);\n }\n}\n\nfunction renderContextProvider(\n context: FigContext<unknown>,\n props: Props,\n frame: RenderFrame,\n): void {\n withContextValue(frame.contextValues, context, props.value, () =>\n renderChildren(props.children, frame),\n );\n}\n\nfunction renderAssets(props: Props, frame: RenderFrame): void {\n renderAssetValue(props.assets, frame);\n renderChildren(props.children, frame);\n}\n\nfunction renderAssetValue(value: unknown, frame: RenderFrame): void {\n if (value === undefined || value === null || value === false) return;\n\n for (const resource of Array.isArray(value) ? value : [value]) {\n if (!isFigAssetResource(resource)) {\n throw new Error(\"The assets prop must contain Fig asset resources.\");\n }\n\n try {\n if (frame.request.assetRegistry.register(resource)) {\n reportLateHeadAsset(frame.request, resource, frame.stack);\n }\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n }\n\n frame.segment.assetResources.push(resource);\n }\n}\n\nfunction reportLateHeadAsset(\n request: Request,\n resource: FigAssetResource,\n stack: StackFrame | null,\n): void {\n if (\n request.headSnapshot === null ||\n assetResourceDestination(resource) !== \"head\"\n ) {\n return;\n }\n\n const key = assetResourceKey(resource);\n const error = new Error(\n `Fig head resource \"${key}\" was discovered after headReady. Move required metadata outside pending Suspense boundaries, or wait for allReady before reading getHead().`,\n );\n\n try {\n request.onAssetError?.(error, {\n componentStack: componentStack(stack),\n destination: \"head\",\n key,\n resource,\n });\n } catch {\n // Resource diagnostics are recoverable and should not change render output.\n }\n}\n\nfunction renderSuspense(props: Props, frame: RenderFrame): void {\n consumePendingLeadingNewline(frame);\n const fallbackAbortableTasks = new Set<Task>();\n const contentSegment = createSegment(0, null);\n const boundary = createBoundary(fallbackAbortableTasks, contentSegment);\n boundary.activityId = frame.hiddenActivityId;\n const parentSegment = frame.segment;\n const boundarySegment = createSegment(parentSegment.chunks.length, boundary);\n parentSegment.children.push(boundarySegment);\n // The boundary always flushes comment markers around its content, so text\n // on either side of it never merges; no separators needed at this seam.\n parentSegment.lastPushedText = false;\n\n contentSegment.parentFlushed = true;\n const contentFrame = createRenderFrame(frame.request, contentSegment, {\n ...forkScope(frame),\n boundary,\n });\n\n try {\n renderChildren(props.children, contentFrame);\n contentSegment.status = \"completed\";\n boundary.completedSegments.push(contentSegment);\n if (boundary.pendingTasks === 0) boundary.status = \"completed\";\n } catch (error) {\n // Suspensions never reach here: renderChildSequence is the single\n // suspend seam and contentFrame always has a boundary, so it spawns a\n // suspended task and continues instead of throwing.\n contentSegment.status = \"completed\";\n markBoundaryClientRendered(frame.request, boundary, error, frame.stack);\n }\n\n // Surfaces after the boundary must not reuse suffixes the branches\n // already claimed. Suspended content tasks may still allocate past this\n // watermark; those deep-tail collisions are accepted (the browser skips\n // pairing for duplicated names rather than breaking the reveal).\n const advanceSurfaceWatermark = (branch: RenderFrame): void => {\n if (frame.viewTransition !== null && branch.viewTransition !== null) {\n frame.viewTransition.index = Math.max(\n frame.viewTransition.index,\n branch.viewTransition.index,\n );\n }\n };\n advanceSurfaceWatermark(contentFrame);\n\n if (boundary.status === \"completed\") return;\n\n const fallbackFrame = createRenderFrame(frame.request, boundarySegment, {\n ...forkScope(frame),\n abortSet: fallbackAbortableTasks,\n });\n\n try {\n renderChildren(props.fallback as FigNode, fallbackFrame);\n boundarySegment.status = \"completed\";\n } catch (error) {\n if (boundary.pendingTasks > 0) {\n for (const task of Array.from(boundary.fallbackAbortableTasks)) {\n abortTask(frame.request, task);\n }\n }\n throw error;\n } finally {\n advanceSurfaceWatermark(fallbackFrame);\n }\n}\n\nfunction renderViewTransition(props: Props, frame: RenderFrame): void {\n const previousViewTransition = frame.viewTransition;\n frame.viewTransition = createServerViewTransition(\n props as ViewTransitionProps,\n frame.request,\n );\n\n try {\n renderChildren(props.children, frame);\n } finally {\n frame.viewTransition = previousViewTransition;\n }\n}\n\nfunction createServerViewTransition(\n props: ViewTransitionProps,\n request: Request,\n): ServerViewTransitionContext {\n return {\n className: serverViewTransitionClass(props),\n index: 0,\n name:\n props.name === undefined || props.name === \"auto\"\n ? `fig-vt-${request.nextViewTransitionId++}`\n : props.name,\n };\n}\n\nfunction serverViewTransitionClass(props: ViewTransitionProps): string | null {\n const className = props.default;\n if (className === undefined || className === \"auto\" || className === \"none\") {\n return null;\n }\n\n return className;\n}\n\nfunction renderActivity(props: Props, frame: RenderFrame): void {\n if (props.mode !== \"hidden\") {\n renderChildren(props.children, frame);\n return;\n }\n\n // Hidden Activity content streams inside an inert template so neither\n // elements nor bare text render before hydration; the client keeps the\n // boundary dehydrated until reveal. The template carries an id so Suspense\n // boundaries that suspend inside it can stream their completions into this\n // inert content (see `ac`/`ax` in protocol.ts).\n const id = activityId(frame.request, frame.request.nextActivityId++);\n frame.segment.write(\n `<template ${ACTIVITY_TEMPLATE_ATTRIBUTE}=\"\" id=\"${escapeAttribute(id)}\">`,\n );\n const previousHiddenActivityId = frame.hiddenActivityId;\n frame.hiddenActivityId = id;\n try {\n renderChildren(props.children, frame);\n } finally {\n frame.hiddenActivityId = previousHiddenActivityId;\n }\n frame.segment.write(\"</template>\");\n}\n\nfunction renderHostElement(\n type: string,\n props: Props,\n frame: RenderFrame,\n): void {\n if (renderHostAsset(type, props, frame)) return;\n\n if (__DEV__) {\n validateInstanceNesting(type, frame.hostAncestors);\n }\n\n const document = frame.request.document;\n\n if (document !== null && !document.hasHead) {\n if (type !== \"html\" && type !== \"head\") throw invalidDocumentShellError();\n }\n\n if (document !== null && type === \"html\") {\n frame.segment.write(\"<!doctype html>\");\n }\n if (document !== null && type === \"head\") {\n document.hasHead = true;\n }\n\n const isVoid = isVoidElement(type);\n const unsafeHTML = unsafeHTMLContent(props);\n\n // hasRenderableChild is an O(children) scan; only the error checks need it.\n if (isVoid && hasRenderableChild(props.children)) {\n throw new Error(`Void element <${type}> cannot have children.`);\n }\n if (isVoid && unsafeHTML !== null) {\n throw new Error(`Void element <${type}> cannot have unsafeHTML.`);\n }\n if (unsafeHTML !== null && hasRenderableChild(props.children)) {\n throw new Error(\"Host elements cannot have both unsafeHTML and children.\");\n }\n\n consumePendingLeadingNewline(frame);\n const viewTransition = frame.viewTransition;\n const hostProps =\n viewTransition === null\n ? props\n : viewTransitionHostProps(props, viewTransition);\n writeElementStart(type, hostProps, frame.segment, frame.selectProps ?? {});\n if (document !== null && type === \"head\") {\n // First thing in <head>: events must be capturable before any content\n // can paint, or a user's first interaction races bundle execution.\n frame.segment.write(earlyEventCaptureMarkup(frame.request));\n }\n if (isVoid) return;\n\n const previousPendingLeadingNewlineHost = frame.pendingLeadingNewlineHost;\n frame.pendingLeadingNewlineHost = leadingNewlineStrippedHost(type)\n ? type\n : null;\n\n if (unsafeHTML !== null) {\n frame.segment.write(\n consumePendingLeadingNewline(frame)\n ? preserveParserStrippedLeadingNewline(unsafeHTML)\n : unsafeHTML,\n );\n frame.pendingLeadingNewlineHost = previousPendingLeadingNewlineHost;\n writeElementEnd(type, frame.segment);\n return;\n }\n\n const formText = formTextContent(type, props);\n if (formText !== null) {\n writeText(\n consumePendingLeadingNewline(frame)\n ? preserveParserStrippedLeadingNewline(formText)\n : formText,\n frame.segment,\n );\n frame.pendingLeadingNewlineHost = previousPendingLeadingNewlineHost;\n writeElementEnd(type, frame.segment);\n return;\n }\n\n const previousSelectProps = frame.selectProps;\n if (type === \"select\") frame.selectProps = props;\n const previousHostAncestors = frame.hostAncestors;\n const previousViewTransition = frame.viewTransition;\n if (viewTransition !== null) frame.viewTransition = null;\n if (__DEV__) {\n frame.hostAncestors = [type, ...previousHostAncestors];\n }\n\n try {\n // Suspensions are handled inside renderChildSequence (the single suspend\n // seam), so no thenable can reach this frame; plain errors propagate.\n renderChildren(props.children, frame);\n } finally {\n frame.selectProps = previousSelectProps;\n frame.hostAncestors = previousHostAncestors;\n frame.viewTransition = previousViewTransition;\n frame.pendingLeadingNewlineHost = previousPendingLeadingNewlineHost;\n }\n if (document !== null && type === \"head\") {\n writeDocumentHeadMarker(frame.segment);\n }\n writeElementEnd(type, frame.segment);\n}\n\nfunction renderHostAsset(\n type: string,\n props: Props,\n frame: RenderFrame,\n): boolean {\n const resource = assetResourceFromHostProps(type, props);\n if (resource === null) return false;\n\n renderAssetValue(resource, frame);\n return true;\n}\n\nfunction viewTransitionHostProps(\n props: Props,\n viewTransition: ServerViewTransitionContext,\n): Props {\n const index = viewTransition.index++;\n const name =\n index === 0 ? viewTransition.name : `${viewTransition.name}_${index}`;\n const nextProps: Props = {\n ...props,\n [VIEW_TRANSITION_NAME_ATTRIBUTE]: name,\n };\n\n if (viewTransition.className !== null) {\n nextProps[VIEW_TRANSITION_CLASS_ATTRIBUTE] = viewTransition.className;\n }\n\n return nextProps;\n}\n\nfunction spawnSuspendedTask(\n frame: RenderFrame,\n node: FigNode,\n thenable: Thenable,\n childIndexBase: number,\n): void {\n const request = frame.request;\n // The spawned segment splices between the parent's text chunks: it adopts\n // the parent's trailing-text state (so its own leading text writes a\n // separator against the text before the splice point) and marks itself\n // text-embedded (so completeSegmentText appends a trailing separator when\n // it ends in text). The parent's cursor resets — the seam is now owned by\n // the spawned segment.\n const segment = createSegment(frame.segment.chunks.length, null, {\n lastPushedText: frame.segment.lastPushedText,\n textEmbedded: true,\n });\n frame.segment.lastPushedText = false;\n frame.segment.children.push(segment);\n\n const task = createTask(\n request,\n node,\n segment,\n forkScope(frame),\n childIndexBase,\n );\n thenable.then(\n () => pingTask(request, task),\n () => pingTask(request, task),\n );\n}\n\nfunction pingTask(request: Request, task: Task): void {\n if (request.status === \"closed\" || request.status === \"aborting\") return;\n request.pingedTasks.push(task);\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 finishedTask(request: Request, task: Task, segment: Segment): void {\n request.pendingTasks -= 1;\n\n const boundary = task.boundary;\n if (boundary === null) {\n request.pendingRootTasks -= 1;\n if (\n segment === request.rootSegment ||\n request.completedRootSegment === null\n ) {\n request.completedRootSegment = request.rootSegment;\n }\n if (request.pendingRootTasks === 0) finishRootShell(request);\n } else {\n boundary.pendingTasks -= 1;\n\n if (segment.parentFlushed) {\n enqueueUnique(boundary.completedSegments, segment);\n }\n\n if (!completeBoundaryIfReady(request, boundary) && boundary.parentFlushed) {\n request.partialBoundaries.add(boundary);\n }\n }\n\n if (request.pendingTasks === 0) request.allReady.resolve(undefined);\n}\n\nfunction erroredTask(request: Request, task: Task, error: unknown): void {\n request.pendingTasks -= 1;\n\n const boundary = task.boundary;\n if (boundary === null) {\n request.pendingRootTasks -= 1;\n fatalError(request, error);\n return;\n }\n\n boundary.pendingTasks -= 1;\n markBoundaryClientRendered(request, boundary, error, task.stack);\n\n if (request.pendingTasks === 0) request.allReady.resolve(undefined);\n}\n\nfunction detachTask(request: Request, task: Task): void {\n task.abortSet.delete(task);\n request.abortableTasks.delete(task);\n}\n\nfunction abortTask(request: Request, task: Task): void {\n if (!request.abortableTasks.delete(task)) return;\n\n task.segment.status = \"completed\";\n task.abortSet.delete(task);\n request.pendingTasks -= 1;\n\n const boundary = task.boundary;\n if (boundary === null) {\n request.pendingRootTasks -= 1;\n if (request.pendingRootTasks === 0) finishRootShell(request);\n } else {\n boundary.pendingTasks -= 1;\n completeBoundaryIfReady(request, boundary);\n }\n\n if (request.pendingTasks === 0) request.allReady.resolve(undefined);\n}\n\nfunction completeBoundaryIfReady(\n request: Request,\n boundary: SuspenseBoundary,\n): boolean {\n if (boundary.pendingTasks !== 0 || boundary.status !== \"pending\") {\n return false;\n }\n\n boundary.status = \"completed\";\n abortFallbackTasks(request, boundary);\n if (boundary.parentFlushed) request.completedBoundaries.add(boundary);\n return true;\n}\n\nfunction abortFallbackTasks(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n for (const fallbackTask of Array.from(boundary.fallbackAbortableTasks)) {\n abortTask(request, fallbackTask);\n }\n}\n\nfunction markBoundaryClientRendered(\n request: Request,\n boundary: SuspenseBoundary,\n error: unknown,\n stack: StackFrame | null,\n payload?: ServerErrorPayload,\n): void {\n if (boundary.status !== \"client-rendered\") {\n boundary.status = \"client-rendered\";\n boundary.error = payload ?? reportBoundaryError(request, error, stack);\n }\n\n boundary.completedSegments = [];\n request.completedBoundaries.delete(boundary);\n request.partialBoundaries.delete(boundary);\n\n for (const task of Array.from(request.abortableTasks)) {\n if (task.boundary === boundary) abortTask(request, task);\n }\n\n for (const task of Array.from(boundary.fallbackAbortableTasks)) {\n abortTask(request, task);\n }\n\n if (boundary.parentFlushed) {\n request.clientRenderedBoundaries.add(boundary);\n }\n}\n\nfunction abort(request: Request, reason?: unknown): void {\n if (request.status === \"closed\") return;\n cleanupAbortListener(request);\n request.status = \"aborting\";\n request.dataStore.dispose();\n const error = abortError(reason);\n request.fatalError = error;\n\n if (request.pendingRootTasks > 0) {\n fatalError(request, error);\n return;\n }\n\n for (const task of Array.from(request.abortableTasks)) {\n const boundary = task.boundary;\n if (boundary !== null) {\n markBoundaryClientRendered(request, boundary, error, task.stack, {});\n }\n }\n\n request.abortableTasks.clear();\n request.pendingTasks = 0;\n request.allReady.resolve(undefined);\n flushCompletedQueues(request);\n}\n\nfunction fatalError(request: Request, error: unknown): void {\n if (request.status === \"closed\") return;\n\n cleanupAbortListener(request);\n request.status = \"closed\";\n request.dataStore.dispose();\n request.fatalError = error;\n request.headReady.reject(error);\n request.shellReady.reject(error);\n request.allReady.reject(error);\n request.controller?.error(error);\n}\n\nfunction finishRootShell(request: Request): void {\n if (request.document !== null && !request.document.hasHead) {\n fatalError(request, invalidDocumentShellError());\n return;\n }\n\n if (!request.prerender) sealHead(request);\n request.shellReady.resolve(undefined);\n}\n\nfunction flushCompletedQueues(request: Request): void {\n if (request.controller === null || request.status === \"closed\") return;\n if (request.status === \"opening\") return;\n if (request.pendingRootTasks > 0) return;\n if (request.prerender && request.pendingTasks > 0) return;\n\n sealHead(request);\n\n if (request.completedRootSegment !== null) {\n flushSegment(request, request.completedRootSegment);\n request.completedRootSegment = null;\n flushWriteBuffer(request);\n }\n\n drainBoundaryQueue(\n request,\n request.clientRenderedBoundaries,\n flushClientRenderedBoundary,\n );\n drainBoundaryQueue(\n request,\n request.completedBoundaries,\n flushCompletedBoundary,\n );\n drainBoundaryQueue(request, request.partialBoundaries, flushPartialBoundary);\n\n flushWriteBuffer(request);\n\n if (\n request.pendingTasks === 0 &&\n request.completedBoundaries.size === 0 &&\n request.clientRenderedBoundaries.size === 0 &&\n request.partialBoundaries.size === 0\n ) {\n cleanupAbortListener(request);\n request.status = \"closed\";\n request.dataStore.dispose();\n request.controller.close();\n }\n}\n\nfunction flushSegment(request: Request, segment: Segment): void {\n if (segment.boundary !== null) {\n flushSuspenseBoundary(request, segment, segment.boundary);\n return;\n }\n\n flushSubtree(request, segment);\n}\n\nfunction flushSubtree(request: Request, segment: Segment): void {\n segment.parentFlushed = true;\n\n if (segment.status === \"pending\" || segment.status === \"rendering\") {\n write(\n request,\n placeholderMarkup(request, ensureSegmentId(request, segment)),\n );\n return;\n }\n\n if (segment.status === \"flushed\") return;\n\n segment.status = \"flushed\";\n if (request.document === null || segment !== request.rootSegment) {\n flushSegmentAssets(request, segment);\n }\n let chunkIndex = 0;\n\n for (const child of segment.children) {\n for (; chunkIndex < child.index; chunkIndex += 1) {\n writeChunk(request, segment.chunks[chunkIndex], segment);\n }\n flushSegment(request, child);\n }\n\n for (; chunkIndex < segment.chunks.length; chunkIndex += 1) {\n writeChunk(request, segment.chunks[chunkIndex], segment);\n }\n}\n\nfunction flushSuspenseBoundary(\n request: Request,\n segment: Segment,\n boundary: SuspenseBoundary,\n): void {\n segment.boundary = null;\n boundary.parentFlushed = true;\n\n if (boundary.status === \"completed\") {\n write(request, `<!--${SUSPENSE_COMPLETED_MARKER}-->`);\n flushBoundaryContent(request, boundary);\n write(request, `<!--${SUSPENSE_END_MARKER}-->`);\n return;\n }\n\n if (request.prerender && boundary.status === \"client-rendered\") {\n // Static prerender does not hoist assets discovered only in failed content:\n // the retry path loads them on demand, and pure-static consumers see only\n // the fallback.\n write(request, `<!--${SUSPENSE_CLIENT_MARKER}-->`);\n write(request, clientRenderedBoundaryPlaceholderMarkup(request, boundary));\n flushSubtree(request, segment);\n write(request, `<!--${SUSPENSE_END_MARKER}-->`);\n return;\n }\n\n const boundaryIdValue = ensureBoundaryId(request, boundary);\n flushSegmentAssets(request, boundary.contentSegment);\n write(request, `<!--${SUSPENSE_PENDING_PREFIX}${boundaryIdValue}-->`);\n write(request, boundaryPlaceholderMarkup(request, boundaryIdValue));\n flushSubtree(request, segment);\n write(request, `<!--${SUSPENSE_END_MARKER}-->`);\n\n if (boundary.status === \"client-rendered\") {\n request.clientRenderedBoundaries.add(boundary);\n } else if (boundary.completedSegments.length > 0) {\n request.partialBoundaries.add(boundary);\n }\n}\n\nfunction flushBoundaryContent(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n for (const segment of boundary.completedSegments) {\n flushSegment(request, segment);\n }\n boundary.completedSegments = [];\n}\n\nfunction clientRenderedBoundaryPlaceholderMarkup(\n request: Request,\n boundary: SuspenseBoundary,\n): string {\n const id = escapeAttribute(\n boundaryId(request, ensureBoundaryId(request, boundary)),\n );\n const digest = boundary.error?.digest;\n const message = boundary.error?.message;\n const digestAttr =\n digest === undefined || digest === \"\"\n ? \"\"\n : ` data-dgst=\"${escapeAttribute(digest)}\"`;\n const messageAttr =\n message === undefined || message === \"\"\n ? \"\"\n : ` data-msg=\"${escapeAttribute(message)}\"`;\n\n return `<template id=\"${id}\"${digestAttr}${messageAttr}></template>`;\n}\n\nfunction sealHead(request: Request): void {\n if (request.headSnapshot !== null) return;\n\n const head = request.assetRegistry.headHtml(request.nonce);\n request.headSnapshot = head;\n request.headReady.resolve(head);\n}\n\nfunction flushCompletedBoundary(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n flushPartialBoundary(request, boundary);\n writeBoundaryRevealScript(request, boundary);\n}\n\nfunction flushPartialBoundary(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n for (const segment of boundary.completedSegments) {\n flushBoundarySegment(request, boundary, segment);\n }\n boundary.completedSegments = [];\n}\n\nfunction flushBoundarySegment(\n request: Request,\n boundary: SuspenseBoundary,\n segment: Segment,\n): void {\n ensureBoundaryId(request, boundary);\n ensureSegmentId(request, segment);\n const blockingIds = flushSegmentContainer(request, segment);\n\n if (segment !== boundary.contentSegment) {\n writeSegmentRevealScript(request, segment, blockingIds);\n }\n}\n\nfunction writeSegmentRevealScript(\n request: Request,\n segment: Segment,\n blockingIds: string[],\n): void {\n const id = ensureSegmentId(request, segment);\n writeRuntime(request);\n // Partial segments — including those of a hidden-Activity boundary — stage and\n // fill in light-DOM hidden divs; only the boundary's final reveal (`ac`) moves\n // the assembled content into the inert activity template.\n writeScript(\n request,\n withAssetGate(\n request,\n blockingIds,\n `${RUNTIME_REF}.s(${jsString(placeholderId(request, id))},${jsString(\n segmentId(request, id),\n )})`,\n ),\n );\n}\n\nfunction writeBoundaryRevealScript(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n const blockingIds = flushSegmentAssets(request, boundary.contentSegment);\n writeRuntime(request);\n const boundaryRef = jsString(\n boundaryId(request, ensureBoundaryId(request, boundary)),\n );\n const contentRef = jsString(\n segmentId(request, ensureSegmentId(request, boundary.contentSegment)),\n );\n // Inside a hidden Activity the boundary markers live in the activity\n // template's inert content; reveal the completion there with `ac`.\n const runtime = RUNTIME_REF;\n const call =\n boundary.activityId === null\n ? `${runtime}.c(${boundaryRef},${contentRef})`\n : `${runtime}.ac(${jsString(boundary.activityId)},${boundaryRef},${contentRef})`;\n writeScript(request, withAssetGate(request, blockingIds, call));\n}\n\nfunction flushSegmentContainer(request: Request, segment: Segment): string[] {\n if (segment.status === \"flushed\") return [];\n const blockingIds = flushSegmentAssets(request, segment);\n\n write(\n request,\n segmentContainerStartMarkup(request, ensureSegmentId(request, segment)),\n );\n flushSegment(request, segment);\n write(request, \"</div>\");\n return blockingIds;\n}\n\nfunction flushSegmentAssets(request: Request, segment: Segment): string[] {\n const blockingIds = new Set<string>();\n collectSegmentAssets(request, segment, request.assetSink, blockingIds);\n return [...blockingIds];\n}\n\nfunction collectSegmentAssets(\n request: Request,\n segment: Segment,\n sink: AssetSink,\n blockingIds: Set<string>,\n): void {\n if (segment.status !== \"pending\" && segment.status !== \"rendering\") {\n flushAssetList(request, segment.assetResources, sink, blockingIds);\n }\n\n for (const child of segment.children) {\n collectSegmentAssets(request, child, sink, blockingIds);\n }\n}\n\nfunction flushAssetList(\n request: Request,\n resources: FigAssetResource[],\n sink: AssetSink,\n blockingIds: Set<string>,\n): void {\n for (const resource of resources) {\n const id = request.assetRegistry.write(resource, sink);\n if (id !== null) blockingIds.add(id);\n }\n}\n\nfunction withAssetGate(\n request: Request,\n blockingIds: string[],\n call: string,\n): string {\n if (blockingIds.length === 0) return call;\n return `${RUNTIME_REF}.r([${blockingIds.map(jsString).join(\",\")}],()=>{${call}})`;\n}\n\nfunction flushClientRenderedBoundary(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n if (boundary.id === null) return;\n writeRuntime(request);\n const boundaryRef = jsString(boundaryId(request, boundary.id));\n const digest = jsString(boundary.error?.digest ?? \"\");\n const message = jsString(boundary.error?.message ?? \"\");\n const runtime = RUNTIME_REF;\n const call =\n boundary.activityId === null\n ? `${runtime}.x(${boundaryRef},${digest},${message})`\n : `${runtime}.ax(${jsString(boundary.activityId)},${boundaryRef},${digest},${message})`;\n writeScript(request, call);\n}\n\n// A boundary deliberately stays in the queue while it flushes so a re-add\n// during its own flush is a no-op (Set semantics), then leaves afterwards.\nfunction drainBoundaryQueue(\n request: Request,\n queue: Set<SuspenseBoundary>,\n flush: (request: Request, boundary: SuspenseBoundary) => void,\n): void {\n for (;;) {\n const first = queue.values().next();\n if (first.done === true) return;\n flush(request, first.value);\n queue.delete(first.value);\n // One encoded enqueue per drained boundary: keeps chunk boundaries at\n // meaningful stream points (consumers interleave companion content per\n // chunk) while still coalescing the per-attribute writes within.\n flushWriteBuffer(request);\n }\n}\n\nfunction enqueueUnique<T>(queue: T[], item: T): void {\n if (!queue.includes(item)) queue.push(item);\n}\n\nfunction reportBoundaryError(\n request: Request,\n error: unknown,\n stack: StackFrame | null,\n): ServerErrorPayload {\n const info = { componentStack: componentStack(stackForError(error, stack)) };\n if (request.onError === undefined) {\n return __DEV__ ? { message: errorMessage(error) } : {};\n }\n\n try {\n return request.onError(error, info) ?? {};\n } catch {\n return {};\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction recordErrorStack(error: unknown, stack: StackFrame | null): void {\n if (stack === null) return;\n if (typeof error !== \"object\" && typeof error !== \"function\") return;\n if (error === null || isThenable(error)) 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 (\n (typeof error !== \"object\" && typeof error !== \"function\") ||\n error === null\n ) {\n return fallback;\n }\n\n return errorStacks.get(error) ?? fallback;\n}\n\nfunction writeRuntime(request: Request): void {\n writeProtocolRuntime(request, (chunk) => write(request, chunk));\n}\n\n// Classic <script> elements share the page's global lexical environment, so a\n// top-level `let` would redeclare across op scripts and throw; the IIFE keeps\n// a per-script binding that async op callbacks (the stylesheet gate) close\n// over even if a later stream rebinds the runtime name.\nfunction writeScript(request: Request, code: string): void {\n writeProtocolScript(\n request,\n `(__figSSR=>{${code}})(globalThis[${jsString(request.runtimeName)}])`,\n (chunk) => write(request, chunk),\n );\n}\n\nfunction createRuntimeName(identifierPrefix: string | undefined): string {\n const id = nextRuntimeId.toString(36);\n nextRuntimeId += 1;\n const prefix = identifierPrefix?.replace(/[^A-Za-z0-9_$]/g, \"_\") ?? \"\";\n return prefix === \"\" ? `__figSSR_${id}` : `__figSSR_${prefix}_${id}`;\n}\n\nfunction writeChunk(\n request: Request,\n chunk: string | typeof documentHeadMarker,\n segment: Segment,\n): void {\n if (chunk !== documentHeadMarker) {\n write(request, chunk);\n return;\n }\n\n if (request.document === null) return;\n\n write(request, request.assetRegistry.headHtml(request.nonce));\n flushAssetList(request, segment.assetResources, request.assetSink, new Set());\n}\n\nfunction write(request: Request, chunk: string): void {\n request.writeBuffer.push(chunk);\n}\n\nfunction writeDocumentHeadMarker(segment: Segment): void {\n segment.lastPushedText = false;\n segment.chunks.push(documentHeadMarker);\n}\n\nfunction consumePendingLeadingNewline(frame: RenderFrame): boolean {\n const pending = frame.pendingLeadingNewlineHost !== null;\n frame.pendingLeadingNewlineHost = null;\n return pending;\n}\n\nfunction leadingNewlineStrippedHost(type: string): boolean {\n return type === \"pre\" || type === \"textarea\";\n}\n\nfunction preserveParserStrippedLeadingNewline(text: string): string {\n return text.startsWith(\"\\n\") ? `\\n${text}` : text;\n}\n\nfunction cleanupAbortListener(request: Request): void {\n if (request.abortListener === null || request.abortSignal === null) return;\n request.abortSignal.removeEventListener(\"abort\", request.abortListener);\n request.abortListener = null;\n request.abortSignal = null;\n}\n\nfunction flushWriteBuffer(request: Request): void {\n if (request.writeBuffer.length === 0 || request.controller === null) return;\n request.controller.enqueue(textEncoder.encode(request.writeBuffer.join(\"\")));\n request.writeBuffer = [];\n}\n\nfunction invalidDocumentShellError(): Error {\n return new Error(\n \"renderToDocumentStream requires the root to render an <html> document with a <head>.\",\n );\n}\n\nfunction ensureSegmentId(request: Request, segment: Segment): number {\n segment.id ??= request.nextSegmentId++;\n return segment.id;\n}\n\nfunction ensureBoundaryId(\n request: Request,\n boundary: SuspenseBoundary,\n): number {\n boundary.id ??= request.nextBoundaryId++;\n return boundary.id;\n}\n\nfunction 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\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted === true) throw abortReason(signal.reason);\n}\n\nfunction throwIfAborting(request: Request): void {\n if (request.status === \"aborting\") throw abortReason(request.fatalError);\n}\n\nfunction abortError(reason: unknown): Error {\n if (reason instanceof Error) return reason;\n return new Error(\n typeof reason === \"string\" ? reason : \"Server render was aborted.\",\n );\n}\n\nfunction abortReason(reason: unknown): unknown {\n return reason ?? new Error(\"Server render was aborted.\");\n}\n\nfunction describeElementType(type: ElementType): string {\n if (typeof type === \"symbol\") return String(type);\n if (typeof type === \"function\") return type.name || \"anonymous function\";\n return typeof type;\n}\n","// Optional render-tree collection: a caller-owned collector the renderer\n// fills with the component structure as it renders, one node per element or\n// text child. The collector is readable at any point — a subtree rendered\n// later in document order (a DevTools panel in an aside, for example) sees\n// everything rendered before it, so prerendering introspection UI needs no\n// second pass. Suspended content attaches under its boundary when the task\n// resumes; content still pending when the collector is read simply is not\n// there yet.\nexport type RenderTreeKind =\n | \"activity\"\n | \"assets\"\n | \"client-reference\"\n | \"context-provider\"\n | \"error-boundary\"\n | \"fragment\"\n | \"function\"\n | \"host\"\n | \"root\"\n | \"suspense\"\n | \"text\"\n | \"view-transition\";\n\nexport interface RenderTreeNode {\n children: RenderTreeNode[];\n key: string | number | null;\n kind: RenderTreeKind;\n name: string;\n props: Record<string, unknown>;\n}\n\nexport interface RenderTreeCollector {\n readonly tree: RenderTreeNode;\n}\n\nexport function createRenderTreeCollector(): RenderTreeCollector {\n return {\n tree: {\n children: [],\n key: null,\n kind: \"root\",\n name: \"Root\",\n props: {},\n },\n };\n}\n","import type { FigNode } from \"@bgub/fig\";\nimport { createServerRenderRequest } from \"./renderer.ts\";\nimport type {\n ServerDocumentRenderResult,\n ServerFragmentRenderResult,\n ServerPrerenderOptions,\n ServerPrerenderResult,\n ServerRenderOptions,\n} from \"./types.ts\";\n\nexport { escapeAttribute, escapeText } from \"./html.ts\";\nexport {\n createRenderTreeCollector,\n type RenderTreeCollector,\n type RenderTreeKind,\n type RenderTreeNode,\n} from \"./render-tree.ts\";\n\n// The four render entry points form one grid: render + To + (Document?) +\n// output form. Stream results are returned synchronously — a shell failure\n// rejects `shellReady` (and the stream); there is no callback channel.\n\nexport function renderToStream(\n node: FigNode,\n options: ServerRenderOptions = {},\n): ServerFragmentRenderResult {\n return createServerRenderRequest(node, options);\n}\n\nexport function renderToDocumentStream(\n node: FigNode,\n options: ServerRenderOptions = {},\n): ServerDocumentRenderResult {\n const request = createServerRenderRequest(node, options, {\n document: true,\n });\n\n // Document mode owns the head: expose the stream result without the\n // fragment-only head accessors.\n return {\n abort: (reason) => request.abort(reason),\n allReady: request.allReady,\n contentType: request.contentType,\n getData: () => request.getData(),\n shellReady: request.shellReady,\n stream: request.stream,\n };\n}\n\n/**\n * The streamed output, buffered: awaits `allReady` and concatenates exactly\n * the bytes a streaming client would have received — including the inline\n * streaming runtime and boundary-reveal scripts when the tree suspends past\n * the shell. Right for caching responses and snapshotting wire output; it is\n * NOT React's `renderToString` (use `prerender` for settled, script-free\n * static markup).\n */\nexport async function renderToHtml(\n node: FigNode,\n options: ServerRenderOptions = {},\n): Promise<string> {\n const result = renderToStream(node, options);\n await result.allReady;\n return readStreamToString(result.stream);\n}\n\n/** Document-mode {@link renderToHtml}: the streamed document, buffered. */\nexport async function renderToDocumentHtml(\n node: FigNode,\n options: ServerRenderOptions = {},\n): Promise<string> {\n const result = renderToDocumentStream(node, options);\n await result.allReady;\n return readStreamToString(result.stream);\n}\n\n/**\n * Settled static HTML: waits for all async work before flushing, so completed\n * Suspense content is emitted in logical position without streaming scripts.\n */\nexport async function prerender(\n node: FigNode,\n options: ServerPrerenderOptions = {},\n): Promise<ServerPrerenderResult> {\n const { document = false, ...renderOptions } = options;\n const result = createServerRenderRequest(node, renderOptions, {\n document,\n prerender: true,\n });\n\n await result.allReady;\n const html = await readStreamToString(result.stream);\n\n return {\n data: result.getData(),\n head: document ? \"\" : result.getHead(),\n html,\n };\n}\n\nasync function readStreamToString(\n stream: ReadableStream<Uint8Array>,\n): Promise<string> {\n const reader = stream.getReader();\n const textDecoder = new TextDecoder();\n let output = \"\";\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return output + textDecoder.decode();\n output += textDecoder.decode(value, { stream: true });\n }\n}\n\nexport type {\n ServerAssetDestination,\n ServerAssetErrorInfo,\n ServerDocumentRenderResult,\n ServerErrorInfo,\n ServerErrorPayload,\n ServerFragmentRenderResult,\n ServerPrerenderOptions,\n ServerPrerenderResult,\n ServerRenderOptions,\n} from \"./types.ts\";\n"],"mappings":";;;;AAOA,MAAM,+BAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,UAAU,OAAe,MAAsB;CAC7D,KAAK,MAAM,WAAW,KAAK,CAAC;AAC9B;AAEA,SAAgB,kBACd,MACA,OACA,MACA,iBAAwB,CAAC,GACnB;CACN,gBAAgB,IAAI;CACpB,KAAK,MAAM,IAAI,MAAM;CACrB,gBAAgB,MAAM,OAAO,gBAAgB,IAAI;CACjD,KAAK,MAAM,GAAG;AAChB;AAEA,SAAgB,gBAAgB,MAAc,MAAsB;CAClE,KAAK,MAAM,KAAK,KAAK,EAAE;AACzB;AAEA,SAAgB,cAAc,MAAuB;CACnD,OAAO,aAAa,IAAI,IAAI;AAC9B;AAEA,SAAgB,mBAAmB,MAAwB;CACzD,IAAI,MAAM,QAAQ,IAAI,GAAG,OAAO,KAAK,KAAK,kBAAkB;CAC5D,IAAI,SAAS,IAAI,GAAG,OAAO;CAC3B,OAAO,CAAC,WAAW,IAAI;AACzB;AAEA,SAAgB,gBAAgB,MAAc,OAA6B;CACzE,IAAI,SAAS,YAAY,OAAO;CAGhC,OAAO,WADO,MAAM,UAAU,KAAA,IAAY,MAAM,QAAQ,MAAM,YACvC;AACzB;AAEA,SAAgB,kBAAkB,OAA6B;CAC7D,MAAM,QAAQ,MAAM;CACpB,IAAI,WAAW,KAAK,GAAG,OAAO;CAC9B,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,MAAM,IAAI,MAAM,4DAA4D;AAC9E;AAEA,SAAS,gBACP,MACA,OACA,gBACA,MACM;CACN,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,KAA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GACf;CACjB,MAAM,SAAS,eAAe,MAAM,OAAO;CAC3C,MAAM,OAAO;CACb,OAAO,mBAAmB,OAAO,MAAM;AACzC;;AAGA,eAAsB,qBACpB,MACA,UAA+B,CAAC,GACf;CACjB,MAAM,SAAS,uBAAuB,MAAM,OAAO;CACnD,MAAM,OAAO;CACb,OAAO,mBAAmB,OAAO,MAAM;AACzC;;;;;AAMA,eAAsB,UACpB,MACA,UAAkC,CAAC,GACH;CAChC,MAAM,EAAE,WAAW,OAAO,GAAG,kBAAkB;CAC/C,MAAM,SAAS,0BAA0B,MAAM,eAAe;EAC5D;EACA,WAAW;CACb,CAAC;CAED,MAAM,OAAO;CACb,MAAM,OAAO,MAAM,mBAAmB,OAAO,MAAM;CAEnD,OAAO;EACL,MAAM,OAAO,QAAQ;EACrB,MAAM,WAAW,KAAK,OAAO,QAAQ;EACrC;CACF;AACF;AAEA,eAAe,mBACb,QACiB;CACjB,MAAM,SAAS,OAAO,UAAU;CAChC,MAAM,cAAc,IAAI,YAAY;CACpC,IAAI,SAAS;CAEb,SAAS;EACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;EAC1C,IAAI,MAAM,OAAO,SAAS,YAAY,OAAO;EAC7C,UAAU,YAAY,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC;CACtD;AACF"}
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { a as ServerErrorPayload, i as ServerErrorInfo } from "./types-4X0JT0wt.js";
|
|
2
|
+
import { DataResourceKeyInput, ElementType, FigAssetResource, FigAssetResourceList, FigDataHydrationEntry, FigDataStoreHandle, FigNode, FontResource, Key, ModulePreloadResource, PreconnectResource, PreloadResource, ScriptResource, StylesheetResource } from "@bgub/fig";
|
|
3
|
+
//#region src/payload.d.ts
|
|
4
|
+
interface PayloadRenderResult {
|
|
5
|
+
abort(reason?: unknown): void;
|
|
6
|
+
allReady: Promise<void>;
|
|
7
|
+
contentType: string;
|
|
8
|
+
stream: ReadableStream<Uint8Array>;
|
|
9
|
+
}
|
|
10
|
+
interface PayloadRenderOptions {
|
|
11
|
+
clientReferenceAssets?: (metadata: {
|
|
12
|
+
id: string;
|
|
13
|
+
}) => FigAssetResourceList;
|
|
14
|
+
codec?: PayloadCodec;
|
|
15
|
+
dataPartition?: DataResourceKeyInput;
|
|
16
|
+
signal?: AbortSignal;
|
|
17
|
+
/**
|
|
18
|
+
* Decides what crosses the wire when a server render throws, mirroring the
|
|
19
|
+
* HTML renderer's contract: the returned payload is authoritative. Without
|
|
20
|
+
* a handler, development includes the error message and production sends
|
|
21
|
+
* an empty payload.
|
|
22
|
+
*/
|
|
23
|
+
onError?: (error: unknown, info: ServerErrorInfo) => ServerErrorPayload | undefined;
|
|
24
|
+
refreshBoundary?: string;
|
|
25
|
+
}
|
|
26
|
+
interface PayloadRootLike {
|
|
27
|
+
data?: FigDataStoreHandle;
|
|
28
|
+
render(node: FigNode): void;
|
|
29
|
+
}
|
|
30
|
+
type SerializedAssetResource = {
|
|
31
|
+
crossOrigin?: StylesheetResource["crossOrigin"];
|
|
32
|
+
href: string;
|
|
33
|
+
kind: "stylesheet";
|
|
34
|
+
media?: string;
|
|
35
|
+
precedence?: string;
|
|
36
|
+
} | {
|
|
37
|
+
as: string;
|
|
38
|
+
crossOrigin?: PreloadResource["crossOrigin"];
|
|
39
|
+
fetchPriority?: PreloadResource["fetchPriority"];
|
|
40
|
+
href: string;
|
|
41
|
+
kind: "preload";
|
|
42
|
+
type?: string;
|
|
43
|
+
} | {
|
|
44
|
+
crossOrigin?: ModulePreloadResource["crossOrigin"];
|
|
45
|
+
fetchPriority?: ModulePreloadResource["fetchPriority"];
|
|
46
|
+
href: string;
|
|
47
|
+
kind: "modulepreload";
|
|
48
|
+
} | {
|
|
49
|
+
async?: boolean;
|
|
50
|
+
crossOrigin?: ScriptResource["crossOrigin"];
|
|
51
|
+
defer?: boolean;
|
|
52
|
+
kind: "script";
|
|
53
|
+
module?: boolean;
|
|
54
|
+
src: string;
|
|
55
|
+
} | {
|
|
56
|
+
crossOrigin?: FontResource["crossOrigin"];
|
|
57
|
+
fetchPriority?: FontResource["fetchPriority"];
|
|
58
|
+
href: string;
|
|
59
|
+
kind: "font";
|
|
60
|
+
type: string;
|
|
61
|
+
} | {
|
|
62
|
+
crossOrigin?: PreconnectResource["crossOrigin"];
|
|
63
|
+
href: string;
|
|
64
|
+
kind: "preconnect";
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Semantic payload row before a PayloadCodec turns it into bytes. This row
|
|
68
|
+
* model is the stable contract; a codec's byte layout is intentionally opaque.
|
|
69
|
+
*/
|
|
70
|
+
type PayloadRow = {
|
|
71
|
+
tag: "assets";
|
|
72
|
+
value: SerializedAssetResource[];
|
|
73
|
+
} | {
|
|
74
|
+
id: number;
|
|
75
|
+
tag: "client";
|
|
76
|
+
value: {
|
|
77
|
+
id: string;
|
|
78
|
+
assets?: SerializedAssetResource[];
|
|
79
|
+
exportName?: string;
|
|
80
|
+
ssr?: true;
|
|
81
|
+
};
|
|
82
|
+
} | {
|
|
83
|
+
tag: "data";
|
|
84
|
+
value: PayloadDataHydrationEntry[];
|
|
85
|
+
} | {
|
|
86
|
+
id: number;
|
|
87
|
+
tag: "error";
|
|
88
|
+
value: ServerErrorPayload;
|
|
89
|
+
} | {
|
|
90
|
+
id: number;
|
|
91
|
+
tag: "model";
|
|
92
|
+
value: PayloadModel;
|
|
93
|
+
} | {
|
|
94
|
+
boundary: string;
|
|
95
|
+
tag: "refresh-error";
|
|
96
|
+
value: ServerErrorPayload;
|
|
97
|
+
} | {
|
|
98
|
+
boundary: string;
|
|
99
|
+
tag: "refresh";
|
|
100
|
+
value: PayloadModel;
|
|
101
|
+
};
|
|
102
|
+
/**
|
|
103
|
+
* Transport-safe model value used inside payload rows. The shape is public so
|
|
104
|
+
* custom codecs and framework integrations can encode/decode rows, but callers
|
|
105
|
+
* should not treat the exact tagged representation as an app data format.
|
|
106
|
+
*/
|
|
107
|
+
type PayloadModel = null | boolean | number | string | PayloadModel[] | {
|
|
108
|
+
[key: string]: PayloadModel;
|
|
109
|
+
} | PayloadElementModel | PayloadSpecialModel;
|
|
110
|
+
type PayloadElementModel = {
|
|
111
|
+
$fig: "element";
|
|
112
|
+
id?: number;
|
|
113
|
+
key: Key | null;
|
|
114
|
+
props: PayloadModel;
|
|
115
|
+
type: string | PayloadSpecialModel;
|
|
116
|
+
};
|
|
117
|
+
type PayloadSpecialModel = {
|
|
118
|
+
$fig: "array";
|
|
119
|
+
id: number;
|
|
120
|
+
value: PayloadModel[];
|
|
121
|
+
} | {
|
|
122
|
+
$fig: "boundary";
|
|
123
|
+
child: PayloadModel;
|
|
124
|
+
id: string;
|
|
125
|
+
} | {
|
|
126
|
+
$fig: "bigint";
|
|
127
|
+
value: string;
|
|
128
|
+
} | {
|
|
129
|
+
$fig: "client";
|
|
130
|
+
id: number;
|
|
131
|
+
} | {
|
|
132
|
+
$fig: "date";
|
|
133
|
+
value: string;
|
|
134
|
+
} | {
|
|
135
|
+
$fig: "fragment";
|
|
136
|
+
} | {
|
|
137
|
+
$fig: "lazy";
|
|
138
|
+
id: number;
|
|
139
|
+
} | {
|
|
140
|
+
$fig: "map";
|
|
141
|
+
entries: Array<[PayloadModel, PayloadModel]>;
|
|
142
|
+
id: number;
|
|
143
|
+
} | {
|
|
144
|
+
$fig: "number";
|
|
145
|
+
value: "Infinity" | "-Infinity" | "-0" | "NaN";
|
|
146
|
+
} | {
|
|
147
|
+
$fig: "object";
|
|
148
|
+
id?: number;
|
|
149
|
+
value: Record<string, PayloadModel>;
|
|
150
|
+
} | {
|
|
151
|
+
$fig: "promise";
|
|
152
|
+
id: number;
|
|
153
|
+
} | {
|
|
154
|
+
$fig: "ref";
|
|
155
|
+
id: number;
|
|
156
|
+
} | {
|
|
157
|
+
$fig: "set";
|
|
158
|
+
id: number;
|
|
159
|
+
values: PayloadModel[];
|
|
160
|
+
} | {
|
|
161
|
+
$fig: "symbol";
|
|
162
|
+
key: string;
|
|
163
|
+
} | {
|
|
164
|
+
$fig: "suspense";
|
|
165
|
+
} | {
|
|
166
|
+
$fig: "undefined";
|
|
167
|
+
} | {
|
|
168
|
+
$fig: "view-transition";
|
|
169
|
+
};
|
|
170
|
+
type PayloadDataHydrationEntry = Omit<FigDataHydrationEntry, "value"> & {
|
|
171
|
+
value: PayloadModel;
|
|
172
|
+
};
|
|
173
|
+
interface PayloadClientReferenceMetadata {
|
|
174
|
+
id: string;
|
|
175
|
+
exportName?: string;
|
|
176
|
+
ssr?: boolean;
|
|
177
|
+
}
|
|
178
|
+
interface PayloadClientReferenceRecord extends PayloadClientReferenceMetadata {
|
|
179
|
+
assets?: readonly FigAssetResource[];
|
|
180
|
+
}
|
|
181
|
+
interface PayloadResponseOptions {
|
|
182
|
+
codec?: PayloadCodec;
|
|
183
|
+
loadClientReference?: (metadata: PayloadClientReferenceMetadata) => Promise<unknown>;
|
|
184
|
+
resolveClientReference?: (metadata: PayloadClientReferenceMetadata) => ElementType<any> | undefined;
|
|
185
|
+
}
|
|
186
|
+
interface PayloadResponse {
|
|
187
|
+
bindRoot(root: PayloadRootLike): () => void;
|
|
188
|
+
readonly codec: PayloadCodec;
|
|
189
|
+
getAssetResources(): readonly FigAssetResource[];
|
|
190
|
+
getClientReferences(): readonly PayloadClientReferenceRecord[];
|
|
191
|
+
getRoot(): FigNode;
|
|
192
|
+
preloadClientReferences(): Promise<void>;
|
|
193
|
+
processBytesChunk(chunk: Uint8Array): void;
|
|
194
|
+
processStream(stream: ReadableStream<Uint8Array>, signal?: AbortSignal | null): Promise<void>;
|
|
195
|
+
processStringChunk(chunk: string): void;
|
|
196
|
+
readonly rootReady: Promise<void>;
|
|
197
|
+
subscribe(listener: () => void): () => void;
|
|
198
|
+
}
|
|
199
|
+
type PayloadFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
200
|
+
interface PayloadFetchOptions extends RequestInit {
|
|
201
|
+
fetch?: PayloadFetch;
|
|
202
|
+
refreshBoundary?: string;
|
|
203
|
+
}
|
|
204
|
+
interface PayloadCodec {
|
|
205
|
+
/**
|
|
206
|
+
* Opaque implementation id, e.g. "json" or "binary". Fig checks this id at
|
|
207
|
+
* transport boundaries; the encoded byte layout is not a public contract.
|
|
208
|
+
*/
|
|
209
|
+
readonly id: string;
|
|
210
|
+
readonly contentType: string;
|
|
211
|
+
/**
|
|
212
|
+
* Creates a streaming row decoder. The decoder calls `onRow` for each
|
|
213
|
+
* complete semantic row. If `onRow` throws, the decoder must propagate that
|
|
214
|
+
* error; when it can already see more complete sibling rows in the same
|
|
215
|
+
* input chunk, it should process those siblings before rethrowing so
|
|
216
|
+
* notifications already implied by earlier rows are not lost.
|
|
217
|
+
*/
|
|
218
|
+
createDecoder(onRow: (row: PayloadRow) => void): PayloadDecoder;
|
|
219
|
+
encodeRow(row: PayloadRow): Uint8Array;
|
|
220
|
+
}
|
|
221
|
+
interface PayloadDecoder {
|
|
222
|
+
decode(chunk: Uint8Array): void;
|
|
223
|
+
flush(): void;
|
|
224
|
+
}
|
|
225
|
+
declare const PAYLOAD_BOUNDARY_HEADER = "x-fig-payload-boundary";
|
|
226
|
+
declare class PayloadFetchError extends Error {
|
|
227
|
+
readonly response: Response;
|
|
228
|
+
readonly status: number;
|
|
229
|
+
constructor(response: Response);
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Readable development-oriented codec: one JSON payload row per newline.
|
|
233
|
+
*/
|
|
234
|
+
declare const jsonPayloadCodec: PayloadCodec;
|
|
235
|
+
type PayloadBoundaryProps = {
|
|
236
|
+
children?: FigNode;
|
|
237
|
+
id: string;
|
|
238
|
+
};
|
|
239
|
+
declare const PayloadBoundary: {
|
|
240
|
+
(props: PayloadBoundaryProps): FigNode;
|
|
241
|
+
readonly $$typeof: symbol;
|
|
242
|
+
};
|
|
243
|
+
declare function renderToPayloadStream(node: FigNode, options?: PayloadRenderOptions): PayloadRenderResult;
|
|
244
|
+
declare function createPayloadResponse(options?: PayloadResponseOptions): PayloadResponse;
|
|
245
|
+
declare function isPayloadRequestCancelled(error: unknown): boolean;
|
|
246
|
+
declare function fetchPayload(response: PayloadResponse, input: RequestInfo | URL, options?: PayloadFetchOptions): Promise<Response>;
|
|
247
|
+
/**
|
|
248
|
+
* Encode ordinary data values into PayloadModel. Server component references
|
|
249
|
+
* such as Fig elements, promises, and client references are handled by the
|
|
250
|
+
* payload renderer before ordinary values reach this helper.
|
|
251
|
+
*/
|
|
252
|
+
declare function encodePayloadValue(value: unknown): PayloadModel;
|
|
253
|
+
/** Decode values produced by encodePayloadValue. */
|
|
254
|
+
declare function decodePayloadValue(model: PayloadModel): unknown;
|
|
255
|
+
declare function encodePayloadDataEntries(entries: readonly FigDataHydrationEntry[]): PayloadDataHydrationEntry[];
|
|
256
|
+
declare function decodePayloadDataEntries(entries: readonly PayloadDataHydrationEntry[]): FigDataHydrationEntry[];
|
|
257
|
+
//#endregion
|
|
258
|
+
export { PAYLOAD_BOUNDARY_HEADER, PayloadBoundary, PayloadClientReferenceMetadata, PayloadClientReferenceRecord, PayloadCodec, PayloadDataHydrationEntry, PayloadDecoder, PayloadFetch, PayloadFetchError, PayloadFetchOptions, PayloadModel, PayloadRenderOptions, PayloadRenderResult, PayloadResponse, PayloadResponseOptions, PayloadRootLike, PayloadRow, SerializedAssetResource, createPayloadResponse, decodePayloadDataEntries, decodePayloadValue, encodePayloadDataEntries, encodePayloadValue, fetchPayload, isPayloadRequestCancelled, jsonPayloadCodec, renderToPayloadStream };
|