@bgub/fig-server 0.1.0-alpha.7 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["writeScript"],"sources":["../src/html.ts","../src/preload-header.ts","../src/asset-registry.ts","../src/protocol.ts","../src/renderer-flush.ts","../src/renderer.ts","../src/render-tree.ts","../src/index.ts"],"sourcesContent":["import type { Props } from \"@bgub/fig\";\nimport { isPortal } from \"@bgub/fig/internal\";\nimport { escapeAttribute, escapeText } from \"./escaping.ts\";\n\nexport {\n escapeAttribute,\n escapeScriptJson,\n escapeScriptText,\n escapeText,\n} from \"./escaping.ts\";\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\nconst attributeNamePattern = /[\\s\"'<>/=]/;\nconst eventPropPattern = /^on[A-Z]/;\nconst styleNamePattern = /[A-Z]/g;\nconst tagNamePattern = /^[A-Za-z][A-Za-z0-9:._-]*$/;\n\nfunction hyphenateStyleLetter(letter: string): string {\n return `-${letter.toLowerCase()}`;\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 selectProps: Props | null = null,\n): void {\n validateTagName(type);\n sink.write(`<${type}${serializeAttributes(type, props, selectProps)}>`);\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 node !== null && node !== undefined && typeof node !== \"boolean\";\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 serializeAttributes(\n type: string,\n props: Props,\n selectProps: Props | null,\n): string {\n let attributes = \"\";\n\n for (const name of Object.keys(props)) {\n const value = props[name];\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 !== \"\") attributes += serializeAttribute(\"style\", style);\n continue;\n }\n\n attributes += serializeProp(type, name, value);\n }\n\n if (\n type === \"option\" &&\n props.selected === undefined &&\n optionSelected(optionValue(props), selectProps)\n ) {\n attributes += \" selected\";\n }\n\n return attributes;\n}\n\nfunction serializeProp(type: string, name: string, value: unknown): string {\n const isValueProp = name === \"value\" || name === \"defaultValue\";\n if ((type === \"textarea\" || type === \"select\") && isValueProp) {\n return \"\";\n }\n\n let attributeName = name;\n let attributeValue = value;\n\n if (isValueProp) {\n attributeName = \"value\";\n if (serializableAttributeValue(value)) attributeValue = String(value);\n } else if (name === \"defaultChecked\") {\n attributeName = \"checked\";\n attributeValue = value === true ? true : null;\n } else if (type === \"option\" && name === \"selected\") {\n attributeValue = value === true ? true : null;\n }\n\n if (emptyValue(attributeValue)) return \"\";\n\n validateAttributeName(attributeName);\n if (attributeValue === true) return ` ${attributeName}`;\n if (serializableAttributeValue(attributeValue)) {\n return serializeAttribute(attributeName, String(attributeValue));\n }\n\n throw new Error(`Cannot serialize prop \"${name}\" to HTML.`);\n}\n\nfunction optionSelected(value: unknown, selectProps: Props | null): boolean {\n if (selectProps === null) return false;\n\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 if (!Array.isArray(selectValue)) return String(selectValue) === optionValue;\n for (const selectedValue of selectValue) {\n if (String(selectedValue) === optionValue) return true;\n }\n return false;\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 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 serializeAttribute(name: string, value: string): string {\n return ` ${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 styles = value as Record<string, unknown>;\n let serialized = \"\";\n for (const name of Object.keys(styles)) {\n const item = styles[name];\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 if (serialized !== \"\") serialized += \";\";\n serialized += `${styleName(name)}:${String(item)}`;\n }\n\n return serialized;\n}\n\nfunction reservedProp(name: string): boolean {\n return (\n name === \"children\" ||\n name === \"key\" ||\n name === \"mix\" ||\n name === \"bind\" ||\n name === \"suppressHydrationWarning\" ||\n name === \"unsafeHTML\" ||\n eventPropPattern.test(name)\n );\n}\n\nfunction styleName(name: string): string {\n if (name.startsWith(\"--\")) return name;\n return name.replace(styleNamePattern, hyphenateStyleLetter);\n}\n\nfunction validateTagName(name: string): void {\n if (!tagNamePattern.test(name)) {\n throw new Error(`Invalid HTML tag name \"${name}\".`);\n }\n}\n\nfunction validateAttributeName(name: string): void {\n if (attributeNamePattern.test(name)) {\n throw new Error(`Invalid HTML attribute name \"${name}\".`);\n }\n}\n","import type { FigAssetResource, PreloadResource } from \"@bgub/fig\";\nimport type {\n ServerPreloadHeaderOptions,\n ServerPreloadHeaderResource,\n} from \"./types.ts\";\n\ntype DeliveryResource = Exclude<FigAssetResource, { kind: \"meta\" | \"title\" }>;\n\nexport type PreloadHeaderResourceSnapshot =\n readonly ServerPreloadHeaderResource[];\n\nexport interface PreloadHeaderEntry {\n readonly resource: ServerPreloadHeaderResource;\n readonly value: string;\n}\n\nconst DEFAULT_LENGTH = 2_000;\nconst HEX_ESCAPE = /^[0-9A-Fa-f]{2}$/;\nconst PARAMETER_TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst URI_REFERENCE_PUNCTUATION = \"-._~:/?#[]@!$&'()*+,;=\";\n\nexport function createPreloadHeaderEntries(\n resources: Iterable<DeliveryResource>,\n): PreloadHeaderEntry[] {\n const entries: PreloadHeaderEntry[] = [];\n\n for (const resource of resources) {\n if (!isServerPreloadHeaderResource(resource)) continue;\n const value = preloadHeaderValue(resource);\n if (value !== null) entries.push({ resource, value });\n }\n\n return entries;\n}\n\nexport function snapshotPreloadHeaderResources(\n resources: Iterable<DeliveryResource>,\n isEarlyImage?: (resource: PreloadResource) => boolean,\n): PreloadHeaderResourceSnapshot {\n const preconnects: ServerPreloadHeaderResource[] = [];\n const criticalPreloads: ServerPreloadHeaderResource[] = [];\n const stylesheets: ServerPreloadHeaderResource[] = [];\n const remaining: ServerPreloadHeaderResource[] = [];\n\n for (const resource of resources) {\n if (!isServerPreloadHeaderResource(resource)) continue;\n const snapshot: ServerPreloadHeaderResource = { ...resource };\n\n if (resource.kind === \"preconnect\") {\n preconnects.push(snapshot);\n } else if (\n resource.kind === \"font\" ||\n (resource.kind === \"preload\" &&\n (resource.as === \"font\" ||\n (resource.as === \"image\" &&\n (resource.fetchpriority === \"high\" ||\n isEarlyImage?.(resource) === true))))\n ) {\n criticalPreloads.push(snapshot);\n } else if (resource.kind === \"stylesheet\") {\n stylesheets.push(snapshot);\n } else {\n remaining.push(snapshot);\n }\n }\n\n return [...preconnects, ...criticalPreloads, ...stylesheets, ...remaining];\n}\n\nexport function formatPreloadHeader(\n entries: readonly PreloadHeaderEntry[],\n options: ServerPreloadHeaderOptions = {},\n): string | undefined {\n const maxLength = normalizedLength(options.maxLength);\n if (maxLength === 0) return undefined;\n\n const seen = new Set<string>();\n const values: string[] = [];\n let length = 0;\n\n for (const entry of entries) {\n if (options.filter !== undefined && !options.filter(entry.resource)) {\n continue;\n }\n if (seen.has(entry.value)) continue;\n\n const addedLength = entry.value.length + (values.length === 0 ? 0 : 2);\n if (length + addedLength > maxLength) continue;\n\n seen.add(entry.value);\n values.push(entry.value);\n length += addedLength;\n }\n\n return values.length === 0 ? undefined : values.join(\", \");\n}\n\nfunction preloadHeaderValue(\n resource: ServerPreloadHeaderResource,\n): string | null {\n switch (resource.kind) {\n case \"stylesheet\":\n return serializeLink(resource.href, [\n [\"rel\", \"preload\"],\n [\"as\", \"style\"],\n [\"crossorigin\", resource.crossorigin],\n [\"media\", resource.media],\n ]);\n case \"preload\":\n return serializeLink(resource.href, [\n [\"rel\", \"preload\"],\n [\"as\", resource.as],\n [\"crossorigin\", resource.crossorigin],\n [\"type\", resource.type],\n [\"fetchpriority\", resource.fetchpriority],\n [\"referrerpolicy\", resource.referrerpolicy],\n ]);\n case \"modulepreload\":\n return serializeLink(resource.href, [\n [\"rel\", \"modulepreload\"],\n [\"as\", \"script\"],\n [\"crossorigin\", resource.crossorigin],\n [\"fetchpriority\", resource.fetchpriority],\n ]);\n case \"font\":\n return serializeLink(resource.href, [\n [\"rel\", \"preload\"],\n [\"as\", \"font\"],\n [\"crossorigin\", resource.crossorigin ?? \"anonymous\"],\n [\"type\", resource.type],\n [\"fetchpriority\", resource.fetchpriority],\n ]);\n case \"preconnect\":\n return serializeLink(resource.href, [\n [\"rel\", \"preconnect\"],\n [\"crossorigin\", resource.crossorigin],\n ]);\n }\n}\n\nfunction isServerPreloadHeaderResource(\n resource: DeliveryResource,\n): resource is ServerPreloadHeaderResource {\n if (resource.kind === \"script\") return false;\n return (\n resource.kind !== \"preload\" ||\n (resource.href !== undefined &&\n (resource.as !== \"image\" || !resource.imagesrcset))\n );\n}\n\nfunction serializeLink(\n target: string,\n parameters: ReadonlyArray<readonly [name: string, value?: string]>,\n): string | null {\n const encodedTarget = encodeLinkTarget(target);\n if (encodedTarget === null) return null;\n\n const parts = [`<${encodedTarget}>`];\n for (const [name, value] of parameters) {\n if (value === undefined) continue;\n const parameter = serializeParameter(name, value);\n if (parameter === null) return null;\n parts.push(parameter);\n }\n return parts.join(\"; \");\n}\n\nfunction serializeParameter(name: string, value: string): string | null {\n if (value === \"\") return name;\n if (hasInvalidParameterCharacter(value)) return null;\n if (PARAMETER_TOKEN.test(value)) return `${name}=${value}`;\n return `${name}=\"${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"')}\"`;\n}\n\nfunction encodeLinkTarget(value: string): string | null {\n if (value === \"\") return null;\n let encoded = \"\";\n\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code <= 0x20 || code === 0x7f) return null;\n\n const character = value[index];\n if (\n character === \"%\" &&\n HEX_ESCAPE.test(value.slice(index + 1, index + 3))\n ) {\n encoded += value.slice(index, index + 3);\n index += 2;\n continue;\n }\n if (\n (code >= 0x30 && code <= 0x39) ||\n (code >= 0x41 && code <= 0x5a) ||\n (code >= 0x61 && code <= 0x7a) ||\n URI_REFERENCE_PUNCTUATION.includes(character)\n ) {\n encoded += character;\n continue;\n }\n\n const codePoint = value.codePointAt(index);\n if (codePoint === undefined) return null;\n const symbol = String.fromCodePoint(codePoint);\n if (symbol.length === 2) index += 1;\n try {\n encoded += encodeURIComponent(symbol);\n } catch {\n return null;\n }\n }\n return encoded;\n}\n\nfunction hasInvalidParameterCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code < 0x20 || code === 0x7f || code > 0xff) return true;\n }\n return false;\n}\n\nfunction normalizedLength(value: number | undefined): number {\n if (value === undefined || Number.isNaN(value)) return DEFAULT_LENGTH;\n return Math.max(0, Math.floor(value));\n}\n","import { type FigAssetResource, type PreloadResource } from \"@bgub/fig\";\nimport {\n assetResourceHostProps,\n assetResourceKey,\n HYDRATION_SKIP_ATTRIBUTE,\n} from \"@bgub/fig/internal\";\nimport { writeElementEnd, writeElementStart, writeText } from \"./html.ts\";\nimport {\n type PreloadHeaderResourceSnapshot,\n snapshotPreloadHeaderResources,\n} from \"./preload-header.ts\";\nimport { STREAMED_METADATA_ATTRIBUTE } from \"./shared.ts\";\n\nexport type MetadataSnapshotEntry =\n | readonly [key: string, kind: \"title\", value: string]\n | readonly [\n key: string,\n kind: \"meta\",\n attributes: ReadonlyArray<readonly [name: string, value: string]>,\n ];\n\ntype MetadataResource = Extract<FigAssetResource, { kind: \"meta\" | \"title\" }>;\ntype DeliveryResource = Exclude<FigAssetResource, MetadataResource>;\n\nexport interface HeadMetadataHtml {\n preamble: string;\n metadata: string;\n}\n\nexport class AssetResourceRegistry {\n private readonly earlyImageKeys = new Set<string>();\n private readonly emittedResources = new Set<string>();\n private readonly deliveryResources = new Map<string, DeliveryResource>();\n private readonly metadataByOwner = new Map<\n object,\n readonly MetadataResource[]\n >();\n private readonly stylesheetIds = new Map<string, string>();\n private nextStylesheetId = 0;\n\n constructor(private readonly identifierPrefix: string) {}\n\n register(resource: FigAssetResource): void {\n if (isMetadataResource(resource)) return;\n this.canonical(assetResourceKey(resource), resource);\n }\n\n registerAutomaticImage(resource: PreloadResource): void {\n const key = assetResourceKey(resource);\n const current = this.canonical(key, resource);\n if (\n this.earlyImageKeys.size < 10 ||\n (current.kind === \"preload\" &&\n current.as === \"image\" &&\n current.fetchpriority === \"high\")\n ) {\n this.earlyImageKeys.add(key);\n }\n }\n\n activateMetadata(\n owner: object,\n resources: readonly FigAssetResource[],\n ): void {\n let metadata: MetadataResource[] | null = null;\n for (const resource of resources) {\n if (isMetadataResource(resource)) (metadata ??= []).push(resource);\n }\n if (metadata === null) {\n this.metadataByOwner.delete(owner);\n return;\n }\n // Map.set preserves an existing key's position, so updating an owner does\n // not steal precedence from owners activated later.\n this.metadataByOwner.set(owner, metadata);\n }\n\n releaseMetadata(owner: object): void {\n this.metadataByOwner.delete(owner);\n }\n\n write(resource: FigAssetResource, sink: AssetSink): string | null {\n if (isMetadataResource(resource)) return null;\n\n const key = assetResourceKey(resource);\n const current = this.canonical(key, resource);\n const id = this.revealBlockerId(key, current);\n\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 writeDocumentHead(\n resources: readonly FigAssetResource[],\n metadata: HeadMetadataHtml,\n sink: AssetSink,\n ): void {\n const preconnects: DeliveryResource[] = [];\n const criticalPreloads: DeliveryResource[] = [];\n const stylesheets: DeliveryResource[] = [];\n const afterMetadata: DeliveryResource[] = [];\n\n for (const resource of resources) {\n if (isMetadataResource(resource)) continue;\n if (resource.kind === \"preconnect\") {\n preconnects.push(resource);\n } else if (\n resource.kind === \"font\" ||\n (resource.kind === \"preload\" &&\n (resource.as === \"font\" ||\n (resource.as === \"image\" &&\n (resource.fetchpriority === \"high\" ||\n this.isEarlyImage(resource)))))\n ) {\n criticalPreloads.push(resource);\n } else if (resource.kind === \"stylesheet\") {\n stylesheets.push(resource);\n } else {\n afterMetadata.push(resource);\n }\n }\n\n sink.write(metadata.preamble);\n for (const resource of preconnects) this.write(resource, sink);\n for (const resource of criticalPreloads) this.write(resource, sink);\n for (const resource of stylesheets) this.write(resource, sink);\n sink.write(metadata.metadata);\n for (const resource of afterMetadata) this.write(resource, sink);\n }\n\n headHtml(nonce?: string, streamMetadata = false): string {\n const { preamble, metadata } = this.headMetadataHtml(nonce, streamMetadata);\n return preamble + metadata;\n }\n\n headMetadataHtml(nonce?: string, streamMetadata = false): HeadMetadataHtml {\n const buckets: Record<MetadataPhase, string[]> = {\n charset: [],\n parser: [],\n viewport: [],\n metadata: [],\n };\n\n for (const resource of this.visibleMetadata().values()) {\n const bucket = buckets[metadataPhase(resource)];\n writeAssetTag(\n { nonce, streamMetadata, write: (chunk) => bucket.push(chunk) },\n resource,\n null,\n );\n }\n\n return {\n preamble:\n buckets.charset.join(\"\") +\n buckets.parser.join(\"\") +\n buckets.viewport.join(\"\"),\n metadata: buckets.metadata.join(\"\"),\n };\n }\n\n metadataSnapshot(): MetadataSnapshotEntry[] {\n const snapshot: MetadataSnapshotEntry[] = [];\n for (const [key, resource] of this.visibleMetadata()) {\n if (resource.kind === \"title\") {\n snapshot.push([key, resource.kind, resource.value]);\n } else {\n snapshot.push([key, resource.kind, metadataAttributes(resource)]);\n }\n }\n return snapshot;\n }\n\n preloadHeaderResources(): PreloadHeaderResourceSnapshot {\n return snapshotPreloadHeaderResources(\n this.deliveryResources.values(),\n (resource) => this.isEarlyImage(resource),\n );\n }\n\n private isEarlyImage(resource: PreloadResource): boolean {\n return this.earlyImageKeys.has(assetResourceKey(resource));\n }\n\n private visibleMetadata(): Map<string, MetadataResource> {\n const visible = new Map<string, MetadataResource>();\n for (const metadata of this.metadataByOwner.values()) {\n for (const resource of metadata) {\n visible.set(assetResourceKey(resource), resource);\n }\n }\n return visible;\n }\n\n private canonical(key: string, resource: DeliveryResource): DeliveryResource {\n const current = this.deliveryResources.get(key);\n\n if (current !== undefined) {\n if (assetSignature(current) !== assetSignature(resource)) {\n const promoted = promoteCompatibleImagePreload(current, resource);\n if (promoted === null) {\n throw new AssetResourceConflictError(key, current, resource);\n }\n this.deliveryResources.set(key, promoted);\n return promoted;\n }\n\n return current;\n }\n\n this.deliveryResources.set(key, resource);\n return 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 streamMetadata?: boolean;\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(\n \"title\",\n {\n [HYDRATION_SKIP_ATTRIBUTE]: true,\n [STREAMED_METADATA_ATTRIBUTE]: sink.streamMetadata\n ? assetResourceKey(resource)\n : undefined,\n },\n sink,\n );\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[\"http-equiv\"],\n content: resource.content,\n [HYDRATION_SKIP_ATTRIBUTE]: true,\n [STREAMED_METADATA_ATTRIBUTE]: sink.streamMetadata\n ? assetResourceKey(resource)\n : undefined,\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 = assetResourceHostProps(resource, {\n [HYDRATION_SKIP_ATTRIBUTE]: true,\n });\n if (resource.kind === \"stylesheet\" && id !== null) props.id = id;\n if (sink.nonce !== undefined) props.nonce = sink.nonce;\n\n const tag = resource.kind === \"script\" ? \"script\" : \"link\";\n writeElementStart(tag, props, sink);\n if (tag === \"script\") writeElementEnd(\"script\", sink);\n }\n }\n}\n\nfunction isMetadataResource(\n resource: FigAssetResource,\n): resource is MetadataResource {\n return resource.kind === \"title\" || resource.kind === \"meta\";\n}\n\ntype MetadataPhase = \"charset\" | \"parser\" | \"viewport\" | \"metadata\";\n\nfunction metadataPhase(resource: MetadataResource): MetadataPhase {\n if (resource.kind === \"title\") return \"metadata\";\n if (resource.charset !== undefined) return \"charset\";\n if (\n normalizedMetadataName(resource[\"http-equiv\"]) === \"content-security-policy\"\n ) {\n return \"parser\";\n }\n if (normalizedMetadataName(resource.name) === \"viewport\") return \"viewport\";\n return \"metadata\";\n}\n\nfunction normalizedMetadataName(value: string | undefined): string | undefined {\n return value?.trim().toLowerCase();\n}\n\nfunction metadataAttributes(\n resource: Extract<FigAssetResource, { kind: \"meta\" }>,\n): Array<readonly [string, string]> {\n const attributes: Array<readonly [string, string | undefined]> = [\n [\"charset\", resource.charset],\n [\"name\", resource.name],\n [\"property\", resource.property],\n [\"http-equiv\", resource[\"http-equiv\"]],\n [\"content\", resource.content],\n [\"data-fig-resource-key\", resource.key],\n ];\n return attributes.filter(\n (entry): entry is readonly [string, string] => entry[1] !== undefined,\n );\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 const imagesrcset =\n resource.as === \"image\" ? resource.imagesrcset || undefined : undefined;\n return signature(\n resource.kind,\n imagesrcset === undefined ? (resource.href ?? \"\") : \"\",\n resource.as,\n resource.type ?? \"\",\n resource.crossorigin ?? \"\",\n resource.fetchpriority ?? \"\",\n imagesrcset ?? \"\",\n imagesrcset === undefined ? \"\" : (resource.imagesizes ?? \"\"),\n resource.referrerpolicy ?? \"\",\n );\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 \"\",\n \"\",\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[\"http-equiv\"] ?? \"\",\n resource.content ?? \"\",\n );\n }\n\n return unsupportedAssetResource(resource);\n}\n\nfunction promoteCompatibleImagePreload(\n current: DeliveryResource,\n incoming: DeliveryResource,\n): DeliveryResource | null {\n if (\n current.kind !== \"preload\" ||\n incoming.kind !== \"preload\" ||\n current.as !== \"image\" ||\n incoming.as !== \"image\" ||\n assetSignature({\n ...current,\n fetchpriority: incoming.fetchpriority,\n }) !== assetSignature(incoming)\n ) {\n return null;\n }\n\n const currentPriority =\n current.fetchpriority === \"auto\" ? undefined : current.fetchpriority;\n const incomingPriority =\n incoming.fetchpriority === \"auto\" ? undefined : incoming.fetchpriority;\n if (currentPriority === incomingPriority) return current;\n if (currentPriority === \"low\" || incomingPriority === \"low\") return null;\n return currentPriority === \"high\"\n ? current\n : { ...current, fetchpriority: \"high\" };\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 HYDRATION_SKIP_ATTRIBUTE,\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 VIEW_TRANSITION_TIMEOUT_MS,\n} from \"@bgub/fig/internal\";\nimport { escapeAttribute, escapeScriptJson } from \"./escaping.ts\";\nimport { nonceAttribute, STREAMED_METADATA_ATTRIBUTE } from \"./shared.ts\";\n\ninterface ProtocolRequest {\n identifierPrefix: string;\n nonce?: string;\n runtimeName: string;\n runtimeWritten: boolean;\n write(chunk: string): void;\n}\n\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.\nfunction buildServerRuntimeCode(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 q=0,i,g=()=>{if(q)return;q=1;clearTimeout(i);d.${VIEW_TRANSITION_PENDING_PROPERTY}===p&&(d.${VIEW_TRANSITION_PENDING_PROPERTY}=null);this.v(b,s,f)};i=setTimeout(g,${VIEW_TRANSITION_TIMEOUT_MS});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()}},m(a){let h=document.head,e=new Map;for(let n of h.querySelectorAll('[${STREAMED_METADATA_ATTRIBUTE}]'))e.set(n.getAttribute('${STREAMED_METADATA_ATTRIBUTE}'),n);for(let d of a){let k=d[0],t=d[1],v=d[2],n=e.get(k);if(!n||n.tagName.toLowerCase()!==t){n&&n.remove();n=document.createElement(t);n.setAttribute('${STREAMED_METADATA_ATTRIBUTE}',k);n.setAttribute('${HYDRATION_SKIP_ATTRIBUTE}','');h.appendChild(n)}e.delete(k);if(t==='title')n.textContent=v;else{for(let x of Array.from(n.attributes))if(x.name!=='${STREAMED_METADATA_ATTRIBUTE}'&&x.name!=='${HYDRATION_SKIP_ATTRIBUTE}')n.removeAttribute(x.name);for(let x of v)n.setAttribute(x[0],x[1])}}for(let n of e.values())n.remove()},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,m){let x=document.getElementById(b),y=document.getElementById(s);this.v(x,y,r=>this.o(x,y,r,m))},o(b,s,l,m){if(!b||!s)return;let a=b.previousSibling||b,p=a.parentNode,c=s.content||s;if(!p)return;let r=a.nodeType===8&&a.__figRetry;if(!r&&m)this.m(m);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}';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,m){let x=this.b(t,b),y=document.getElementById(s);this.v(x,y,r=>this.o(x,y,r,m))},ax(t,b,d,m){this.y(this.b(t,b),d,m)}}`;\n}\n\nconst RUNTIME_CODE_PREFIX = \"globalThis[\";\nconst EMPTY_RUNTIME_REFERENCE = `${RUNTIME_CODE_PREFIX}${jsString(\"\")}`;\nconst SERVER_RUNTIME_SUFFIX = buildServerRuntimeCode(\"\").slice(\n EMPTY_RUNTIME_REFERENCE.length,\n);\n\nexport function serverRuntimeCodeFor(runtimeName: string): string {\n return `${RUNTIME_CODE_PREFIX}${jsString(runtimeName)}${SERVER_RUNTIME_SUFFIX}`;\n}\n\nexport function writeRuntime(request: ProtocolRequest): void {\n if (request.runtimeWritten) return;\n request.runtimeWritten = true;\n writeScript(request, serverRuntimeCodeFor(request.runtimeName));\n}\n\nexport function writeScript(\n request: Pick<ProtocolRequest, \"nonce\" | \"write\">,\n code: string,\n): void {\n request.write(\n `<script ${HYDRATION_SKIP_ATTRIBUTE}=\"\"${nonceAttribute(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 return EARLY_EVENT_CAPTURE_CODE;\n}\n\nconst EARLY_EVENT_CAPTURE_CODE = `(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 [${REPLAYABLE_EVENT_TYPES.map((type) => `'${type}'`).join(\",\")}])d.addEventListener(t,h,!0)})(document)`;\n\nexport function earlyEventCaptureMarkup(\n request: Pick<ProtocolRequest, \"nonce\">,\n): string {\n return `<script ${HYDRATION_SKIP_ATTRIBUTE}=\"\"${nonceAttribute(request.nonce)}>${earlyEventCaptureCode()}</script>`;\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 escapeScriptJson(value);\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 SUSPENSE_CLIENT_MARKER,\n SUSPENSE_COMPLETED_MARKER,\n SUSPENSE_END_MARKER,\n SUSPENSE_PENDING_PREFIX,\n} from \"@bgub/fig/internal\";\nimport { escapeAttribute, escapeScriptJson } from \"./escaping.ts\";\nimport {\n boundaryId,\n boundaryPlaceholderMarkup,\n jsString,\n placeholderId,\n placeholderMarkup,\n segmentContainerStartMarkup,\n segmentId,\n writeRuntime as writeProtocolRuntime,\n writeScript as writeProtocolScript,\n} from \"./protocol.ts\";\nimport type { Request, Segment, SuspenseBoundary } from \"./renderer.ts\";\nimport { streamFlowBlocked } from \"./shared.ts\";\n\nexport const documentHeadMarker = Symbol(\"fig.document-head\");\nexport const leadingNewlineStartMarker = Symbol(\"fig.leading-newline-start\");\nexport const leadingNewlineEndMarker = Symbol(\"fig.leading-newline-end\");\n\nexport type SegmentChunk =\n | string\n | typeof documentHeadMarker\n | typeof leadingNewlineStartMarker\n | typeof leadingNewlineEndMarker\n | { value: string };\n\nconst RUNTIME_REF = \"__figSSR\";\nconst textEncoder = new TextEncoder();\n\nexport function flushCompletedQueues(request: Request): void {\n if (request.controller === null || request.status === \"closed\") return;\n if (request.pendingRootTasks > 0) return;\n if (request.prerender && request.abortableTasks.size > 0) return;\n if (request.flushing) return;\n\n request.flushing = true;\n try {\n sealHead(request);\n\n // The shell flushes ungated: the queue is empty before the first enqueue,\n // and shell latency outranks flow control.\n if (request.rootSegment.status !== \"flushed\") {\n flushSegment(request, request.rootSegment);\n flushWriteBuffer(request);\n }\n\n // Stop at the first blocked drain; the stream's pull handler re-enters\n // here when the consumer makes room.\n if (\n !drainBoundaryQueue(\n request,\n request.clientRenderedBoundaries,\n flushClientRenderedBoundary,\n ) &&\n !drainBoundaryQueue(\n request,\n request.completedBoundaries,\n flushCompletedBoundary,\n )\n ) {\n drainBoundaryQueue(\n request,\n request.partialBoundaries,\n flushPartialBoundary,\n );\n }\n\n flushWriteBuffer(request);\n } finally {\n request.flushing = false;\n }\n\n // Deliberately not conditioned on flow: close() only marks the end of the\n // queue, so a full queue with nothing left to write still closes here.\n if (\n request.abortableTasks.size === 0 &&\n request.completedBoundaries.size === 0 &&\n request.clientRenderedBoundaries.size === 0 &&\n request.partialBoundaries.size === 0\n ) {\n request.status = \"closed\";\n request.dispose();\n request.controller.close();\n }\n}\n\nexport function sealHead(request: Request): void {\n if (request.headSnapshot !== null) return;\n\n activateVisibleMetadata(request, request.rootSegment);\n const metadata = request.assetRegistry.headMetadataHtml(\n request.nonce,\n !request.prerender && request.abortableTasks.size > 0,\n );\n request.headSnapshot = {\n ...metadata,\n preloadHeaderEntries: null,\n preloadHeaderResources: request.assetRegistry.preloadHeaderResources(),\n };\n request.headReady.resolve(metadata.preamble + metadata.metadata);\n}\n\nfunction flushSegment(request: Request, segment: Segment): void {\n if (segment.status === \"flushed\") return;\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 request.write(\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.documentHasHead === null || segment !== request.rootSegment) {\n collectSegmentAssets(request, segment, null);\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 // A flushed segment never needs its serialized fragments again. Releasing\n // them here keeps a completed render from retaining a second copy of the\n // response while the encoded stream chunk is consumed.\n segment.chunks.length = 0;\n}\n\nfunction flushSuspenseBoundary(\n request: Request,\n segment: Segment,\n boundary: SuspenseBoundary,\n): void {\n boundary.parentFlushed = true;\n\n if (boundary.status === \"completed\") {\n request.write(`<!--${SUSPENSE_COMPLETED_MARKER}-->`);\n for (const completedSegment of boundary.completedSegments) {\n flushSegment(request, completedSegment);\n }\n boundary.completedSegments.length = 0;\n request.write(`<!--${SUSPENSE_END_MARKER}-->`);\n segment.status = \"flushed\";\n segment.chunks.length = 0;\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 request.write(`<!--${SUSPENSE_CLIENT_MARKER}-->`);\n request.write(clientRenderedBoundaryPlaceholderMarkup(request, boundary));\n flushSubtree(request, segment);\n request.write(`<!--${SUSPENSE_END_MARKER}-->`);\n return;\n }\n\n const boundaryIdValue = ensureBoundaryId(request, boundary);\n collectSegmentAssets(request, boundary.contentSegment, null);\n request.write(`<!--${SUSPENSE_PENDING_PREFIX}${boundaryIdValue}-->`);\n request.write(boundaryPlaceholderMarkup(request, boundaryIdValue));\n flushSubtree(request, segment);\n request.write(`<!--${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 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 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.length = 0;\n}\n\nfunction flushBoundarySegment(\n request: Request,\n boundary: SuspenseBoundary,\n segment: Segment,\n): void {\n ensureBoundaryId(request, boundary);\n let blockingIds = \"\";\n if (segment.status !== \"flushed\") {\n blockingIds = flushSegmentAssets(request, segment);\n request.write(\n segmentContainerStartMarkup(request, ensureSegmentId(request, segment)),\n );\n flushSegment(request, segment);\n request.write(\"</div>\");\n }\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 writeProtocolRuntime(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 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 const metadata = switchBoundaryMetadata(request, boundary);\n const metadataArgument = metadata === null ? \"\" : `,${metadata}`;\n writeProtocolRuntime(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 call =\n boundary.activityId === null\n ? `${RUNTIME_REF}.c(${boundaryRef},${contentRef}${metadataArgument})`\n : `${RUNTIME_REF}.ac(${jsString(boundary.activityId)},${boundaryRef},${contentRef}${metadataArgument})`;\n writeScript(request, withAssetGate(blockingIds, call));\n}\n\nfunction switchBoundaryMetadata(\n request: Request,\n boundary: SuspenseBoundary,\n): string | null {\n // A nested boundary may complete while an ancestor's primary content is\n // still staged. Its segment fill is useful, but its metadata is not visible;\n // the ancestor reveal traversal will activate the settled branch later.\n if (!boundary.metadataVisible) return null;\n\n const before = escapeScriptJson(request.assetRegistry.metadataSnapshot());\n const fallback = boundary.fallbackSegment;\n if (fallback !== null) {\n request.assetRegistry.releaseMetadata(fallback);\n for (const child of fallback.children) {\n deactivateMetadataTree(request, child);\n }\n }\n activateVisibleMetadata(request, boundary.contentSegment);\n const after = escapeScriptJson(request.assetRegistry.metadataSnapshot());\n return before === after ? null : after;\n}\n\nfunction activateVisibleMetadata(request: Request, segment: Segment): void {\n if (segment.status === \"pending\" || segment.status === \"rendering\") return;\n\n const boundary = segment.boundary;\n if (boundary !== null) {\n boundary.metadataVisible = true;\n if (boundary.status === \"completed\") {\n activateVisibleMetadata(request, boundary.contentSegment);\n return;\n }\n }\n\n request.assetRegistry.activateMetadata(segment, segment.assetResources);\n for (const child of segment.children) {\n activateVisibleMetadata(request, child);\n }\n}\n\nfunction deactivateMetadataTree(request: Request, segment: Segment): void {\n request.assetRegistry.releaseMetadata(segment);\n for (const child of segment.children) deactivateMetadataTree(request, child);\n\n const boundary = segment.boundary;\n if (boundary === null) return;\n boundary.metadataVisible = false;\n deactivateMetadataTree(request, boundary.contentSegment);\n}\n\nfunction flushSegmentAssets(request: Request, segment: Segment): string {\n const blockingIds = new Set<string>();\n collectSegmentAssets(request, segment, blockingIds);\n let serialized = \"\";\n for (const id of blockingIds) {\n if (serialized !== \"\") serialized += \",\";\n serialized += jsString(id);\n }\n return serialized;\n}\n\nfunction collectSegmentAssets(\n request: Request,\n segment: Segment,\n blockingIds: Set<string> | null,\n): void {\n if (segment.status !== \"pending\" && segment.status !== \"rendering\") {\n for (const resource of segment.assetResources) {\n const id = request.assetRegistry.write(resource, request);\n if (id !== null) blockingIds?.add(id);\n }\n }\n\n for (const child of segment.children) {\n collectSegmentAssets(request, child, blockingIds);\n }\n}\n\nfunction withAssetGate(blockingIds: string, call: string): string {\n if (blockingIds === \"\") return call;\n return `${RUNTIME_REF}.r([${blockingIds}],()=>{${call}})`;\n}\n\nfunction flushClientRenderedBoundary(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n if (boundary.id === null) return;\n writeProtocolRuntime(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 call =\n boundary.activityId === null\n ? `${RUNTIME_REF}.x(${boundaryRef},${digest},${message})`\n : `${RUNTIME_REF}.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.\n// Returns true when the drain stopped because the flow is blocked; blocked\n// boundaries stay queued for the next pull-driven pass. Gating sits between\n// boundaries — never mid-buffer — so every chunk still ends on complete\n// markup.\nfunction drainBoundaryQueue(\n request: Request,\n queue: Set<SuspenseBoundary>,\n flush: (request: Request, boundary: SuspenseBoundary) => void,\n): boolean {\n for (;;) {\n if (streamFlowBlocked(request.controller)) return true;\n const first = queue.values().next();\n if (first.done === true) return false;\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\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 );\n}\n\nfunction writeChunk(\n request: Request,\n chunk: SegmentChunk,\n segment: Segment,\n): void {\n if (chunk === leadingNewlineStartMarker) {\n request.leadingNewlineStack.push(false);\n return;\n }\n if (chunk === leadingNewlineEndMarker) {\n request.leadingNewlineStack.pop();\n return;\n }\n if (typeof chunk === \"object\") {\n request.write(\n request.leadingNewlineStack.at(-1) === false &&\n chunk.value.startsWith(\"\\n\")\n ? `\\n${chunk.value}`\n : chunk.value,\n );\n return;\n }\n if (chunk !== documentHeadMarker) {\n request.write(chunk);\n return;\n }\n\n if (request.documentHasHead === null) return;\n\n const metadata =\n request.headSnapshot ??\n request.assetRegistry.headMetadataHtml(request.nonce);\n request.assetRegistry.writeDocumentHead(\n segment.assetResources,\n metadata,\n request,\n );\n}\n\nfunction flushWriteBuffer(request: Request): void {\n if (request.writeBuffer === \"\" || request.controller === null) return;\n request.controller.enqueue(textEncoder.encode(request.writeBuffer));\n request.writeBuffer = \"\";\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","import {\n type ComponentType,\n createElement,\n type ElementType,\n type FigAssetResource,\n type FigClientReference,\n type FigContext,\n type FigElement,\n type FigNode,\n Fragment,\n isValidElement,\n type PreloadResource,\n type Props,\n type ViewTransitionProps,\n} from \"@bgub/fig\";\nimport {\n ACTIVITY_TEMPLATE_ATTRIBUTE,\n assetResourceFromHostProps,\n attachDataStore,\n collectChildren,\n createRendererDataStore,\n type FigDataStore,\n invalidChildError,\n isActivity,\n isAssets,\n isClientReference,\n isContext,\n isErrorBoundary,\n isFigAssetResource,\n isPortal,\n isSuspense,\n isThenable,\n isViewTransition,\n type NormalizedChild,\n type RenderDispatcher,\n readThenable,\n setCurrentDataStore,\n setCurrentDispatcher,\n type Thenable,\n TEXT_SEPARATOR_DATA,\n validateInstanceNesting,\n validateTextNesting,\n VIEW_TRANSITION_CLASS_ATTRIBUTE,\n VIEW_TRANSITION_NAME_ATTRIBUTE,\n} from \"@bgub/fig/internal\";\nimport {\n AssetResourceRegistry,\n type HeadMetadataHtml,\n} from \"./asset-registry.ts\";\nimport {\n escapeAttribute,\n escapeText,\n formTextContent,\n hasRenderableChild,\n isVoidElement,\n unsafeHTMLContent,\n writeElementEnd,\n writeElementStart,\n writeText,\n} from \"./html.ts\";\nimport {\n imagePreloadFromHostProps,\n suppressesImagePreloads,\n} from \"./image-preloads.ts\";\nimport { activityId, earlyEventCaptureMarkup } from \"./protocol.ts\";\nimport {\n createPreloadHeaderEntries,\n formatPreloadHeader,\n type PreloadHeaderEntry,\n type PreloadHeaderResourceSnapshot,\n} from \"./preload-header.ts\";\nimport {\n documentHeadMarker,\n flushCompletedQueues,\n leadingNewlineEndMarker,\n leadingNewlineStartMarker,\n sealHead,\n type SegmentChunk,\n} from \"./renderer-flush.ts\";\nimport {\n type ContextValues,\n type StackFrame,\n cloneContextValues,\n createStaticDispatcher,\n type Deferred,\n deferred,\n noLane,\n noop,\n serverErrorPayload,\n streamHighWaterMark,\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 HeadSnapshot extends HeadMetadataHtml {\n preloadHeaderEntries: readonly PreloadHeaderEntry[] | null;\n preloadHeaderResources: PreloadHeaderResourceSnapshot | null;\n}\n\nexport interface Request {\n abortableTasks: Set<Task>;\n allReady: Deferred<void>;\n cleanupAbortListener: (() => void) | null;\n completedBoundaries: Set<SuspenseBoundary>;\n controller: ReadableStreamDefaultController<Uint8Array> | null;\n dataStore: FigDataStore;\n dispose(): void;\n abortReason: unknown;\n identifierPrefix: string;\n // Flush-time parser state for nested <pre>/<textarea> hosts. Rendering may\n // complete child segments out of order; only logical flush order can decide\n // which text is the parser's first child.\n leadingNewlineStack: boolean[];\n nextBoundaryId: number;\n nextSegmentId: number;\n nextActivityId: number;\n nextViewTransitionId: number;\n nonce?: string;\n onError?: ServerRenderOptions[\"onError\"];\n pendingRootTasks: number;\n pingedTasks: Task[];\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: HeadSnapshot | null;\n shellReady: Deferred<void>;\n status: \"open\" | \"aborting\" | \"closed\";\n clientRenderedBoundaries: Set<SuspenseBoundary>;\n clientReferenceFallback?: ServerRenderOptions[\"clientReferenceFallback\"];\n partialBoundaries: Set<SuspenseBoundary>;\n prerender: boolean;\n componentAssets?: ServerRenderOptions[\"assets\"];\n // null for fragment renders; otherwise whether the document's <head> has\n // been rendered.\n documentHasHead: boolean | null;\n assetRegistry: AssetResourceRegistry;\n resolveAssetKey?: ServerRenderOptions[\"resolveAssetKey\"];\n // Reentrancy guard: enqueueing inside a flush pass can synchronously invoke\n // the stream's pull handler, which must not restart the pass — a boundary\n // stays in its queue while it flushes, so a reentrant drain would emit it\n // twice.\n flushing: boolean;\n // Markup accumulates here per flush pass and leaves as one encoded enqueue,\n // instead of one tiny Uint8Array per attribute/text write.\n writeBuffer: string;\n write(chunk: string): void;\n}\n\n// Mutable state for one synchronous render branch. A suspended branch keeps\n// this frame on its Task and resumes it directly; forks clone only the state\n// that must be isolated from the parent branch.\ninterface RenderFrame {\n // Only fallback work needs a second owner; every task already belongs to\n // request.abortableTasks.\n fallbackTasks: Set<Task> | null;\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 // Namespace inherited by the next host element. Unlike dev-only nesting\n // ancestry this is runtime semantics: asset lowering applies only to HTML.\n hostNamespace: HostNamespace;\n // True inside HTML <picture> and <noscript>, where an <img> does not name a\n // standalone preload candidate.\n imagePreloadsSuppressed: boolean;\n idPath: number[];\n pendingLeadingNewline: boolean;\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 dispatcher: RenderDispatcher | null;\n idPathString: string | null;\n localIdCounter: number;\n request: Request;\n segment: Segment;\n}\n\ninterface Task {\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 frame: RenderFrame;\n node: FigNode;\n}\n\nexport interface Segment {\n readonly boundary: SuspenseBoundary | null;\n children: Segment[];\n chunks: SegmentChunk[];\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: SegmentChunk): void;\n}\n\nexport interface 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 fallbackSegment: Segment | null;\n fallbackTasks: Set<Task>;\n id: number | null;\n parentFlushed: boolean;\n pendingTasks: number;\n status: BoundaryStatus;\n metadataVisible: boolean;\n}\n\ntype BoundaryStatus = \"pending\" | \"completed\" | \"client-rendered\";\ntype SegmentStatus = \"pending\" | \"rendering\" | \"completed\" | \"flushed\";\ntype HostNamespace = \"html\" | \"mathml\" | \"svg\";\n\ninterface ServerViewTransitionContext {\n className: string | null;\n index: number;\n name: string;\n}\n\nconst errorStacks = new WeakMap<object, StackFrame>();\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. The comment data is the shared\n// TEXT_SEPARATOR_DATA protocol constant that fig-dom's hydration cursor\n// skips (and only that; suspense markers use the fig:suspense prefixes).\nconst TEXT_SEPARATOR = `<!--${TEXT_SEPARATOR_DATA}-->`;\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 identifierPrefix = options.identifierPrefix ?? \"\";\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(noop);\n void headReady.promise.catch(noop);\n void allReady.promise.catch(noop);\n const rootSegment = createSegment(0);\n const dataStoreHost = {\n getLane: noLane,\n partition: options.dataPartition,\n schedule: noop,\n };\n const dataStore =\n options.dataStore === undefined\n ? createRendererDataStore<object, null>(dataStoreHost)\n : attachDataStore(options.dataStore, dataStoreHost, options.initialData);\n\n const request: Request = {\n abortableTasks: new Set<Task>(),\n allReady,\n cleanupAbortListener: null,\n completedBoundaries: new Set(),\n controller: null,\n dataStore,\n dispose: disposeRequest,\n abortReason: null,\n identifierPrefix,\n leadingNewlineStack: [],\n nextBoundaryId: 0,\n nextSegmentId: 0,\n nextActivityId: 0,\n nextViewTransitionId: 0,\n nonce: options.nonce,\n onError: options.onError,\n pendingRootTasks: 0,\n pingedTasks: [],\n rootSegment,\n runtimeName: createRuntimeName(identifierPrefix),\n runtimeWritten: false,\n headReady,\n headSnapshot: null,\n shellReady,\n status: \"open\",\n clientRenderedBoundaries: new Set(),\n clientReferenceFallback: options.clientReferenceFallback,\n partialBoundaries: new Set(),\n prerender: mode?.prerender === true,\n componentAssets: options.assets,\n documentHasHead: mode?.document === true ? false : null,\n assetRegistry: new AssetResourceRegistry(identifierPrefix),\n resolveAssetKey: options.resolveAssetKey,\n flushing: false,\n writeBuffer: \"\",\n write: writeRequestChunk,\n };\n if (options.dataStore === undefined && options.initialData !== undefined) {\n request.dataStore.hydrate(options.initialData);\n }\n\n rootSegment.parentFlushed = true;\n const rootTask = createTask(node, {\n boundary: null,\n contextValues: new Map(),\n dispatcher: null,\n fallbackTasks: null,\n hiddenActivityId: null,\n hostAncestors: [],\n hostNamespace: \"html\",\n imagePreloadsSuppressed: false,\n idPath: [],\n idPathString: null,\n localIdCounter: 0,\n pendingLeadingNewline: false,\n request,\n selectProps: null,\n segment: rootSegment,\n stack: null,\n treeParent: options.renderTree?.tree ?? null,\n viewTransition: null,\n });\n pingTask(rootTask);\n\n const stream = new ReadableStream<Uint8Array>(\n {\n start(streamController) {\n request.controller = streamController;\n flushCompletedQueues(request);\n },\n pull() {\n // The consumer drained below the high-water mark: resume flushing\n // whatever completed while the flow was blocked.\n flushCompletedQueues(request);\n },\n cancel(reason) {\n // The consumer is gone: drop the sink before aborting so the abort\n // pass does not enqueue into (or close) a cancelled stream.\n request.controller = null;\n request.writeBuffer = \"\";\n abort(request, reason);\n request.status = \"closed\";\n },\n },\n new ByteLengthQueuingStrategy({\n highWaterMark: streamHighWaterMark(options.highWaterMark),\n }),\n );\n\n if (options.signal !== undefined) {\n const signal = options.signal;\n const abortListener = () => abort(request, signal.reason);\n signal.addEventListener(\"abort\", abortListener, { once: true });\n request.cleanupAbortListener = () => {\n signal.removeEventListener(\"abort\", abortListener);\n request.cleanupAbortListener = null;\n };\n }\n\n return {\n abort: (reason?: unknown) => abort(request, reason),\n allReady: allReady.promise,\n contentType: \"text/html; charset=utf-8\",\n data: request.dataStore,\n getData: () => request.dataStore.snapshot(),\n getPreloadHeader: (headerOptions) => {\n const snapshot = request.headSnapshot;\n if (snapshot === null) return undefined;\n\n let entries = snapshot.preloadHeaderEntries;\n if (entries === null) {\n const resources = snapshot.preloadHeaderResources;\n if (resources === null) {\n throw new Error(\"Missing preload-header resource snapshot.\");\n }\n entries = createPreloadHeaderEntries(resources);\n snapshot.preloadHeaderEntries = entries;\n snapshot.preloadHeaderResources = null;\n }\n return formatPreloadHeader(entries, headerOptions);\n },\n getHead: () => {\n const snapshot = request.headSnapshot;\n return snapshot === null\n ? request.assetRegistry.headHtml(request.nonce)\n : snapshot.preamble + snapshot.metadata;\n },\n headReady: headReady.promise,\n shellReady: shellReady.promise,\n stream,\n };\n}\n\nfunction createTask(\n node: FigNode,\n frame: RenderFrame,\n childIndexBase = 0,\n): Task {\n const { request } = frame;\n if (frame.boundary === null) {\n request.pendingRootTasks += 1;\n } else {\n frame.boundary.pendingTasks += 1;\n }\n\n const task: Task = { childIndexBase, frame, node };\n request.abortableTasks.add(task);\n frame.fallbackTasks?.add(task);\n return task;\n}\n\n// Forks a branch that can outlive the current stack. Context values, the id\n// path, and the view-transition cursor are snapshots; the remaining fields\n// are immutable or restored by balanced push/pop pairs.\nfunction forkFrame(\n frame: RenderFrame,\n segment: Segment,\n boundary = frame.boundary,\n fallbackTasks = frame.fallbackTasks,\n): RenderFrame {\n return {\n boundary,\n contextValues: cloneContextValues(frame.contextValues),\n dispatcher: null,\n fallbackTasks,\n hiddenActivityId: frame.hiddenActivityId,\n hostAncestors: frame.hostAncestors,\n hostNamespace: frame.hostNamespace,\n imagePreloadsSuppressed: frame.imagePreloadsSuppressed,\n idPath: [...frame.idPath],\n idPathString: null,\n localIdCounter: 0,\n pendingLeadingNewline: frame.pendingLeadingNewline,\n request: frame.request,\n selectProps: frame.selectProps,\n segment,\n stack: frame.stack,\n treeParent: frame.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 frame.viewTransition === null ? null : { ...frame.viewTransition },\n };\n}\n\nfunction createSegment(\n index: number,\n boundary: SuspenseBoundary | null = null,\n): Segment {\n return {\n boundary,\n children: [],\n chunks: [],\n id: null,\n index,\n lastPushedText: false,\n parentFlushed: false,\n assetResources: [],\n status: \"pending\",\n textEmbedded: false,\n write: writeSegmentChunk,\n };\n}\n\nfunction writeRequestChunk(this: Request, chunk: string): void {\n if (chunk !== \"\" && this.leadingNewlineStack.length > 0) {\n this.leadingNewlineStack[this.leadingNewlineStack.length - 1] = true;\n }\n this.writeBuffer += chunk;\n}\n\nfunction disposeRequest(this: Request): void {\n this.cleanupAbortListener?.();\n this.dataStore.dispose();\n}\n\nfunction writeSegmentChunk(this: Segment, chunk: SegmentChunk): void {\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\nfunction performWork(request: Request): void {\n if (request.status === \"closed\") return;\n\n const tasks = request.pingedTasks;\n request.pingedTasks = [];\n\n for (const task of tasks) retryTask(task);\n\n flushCompletedQueues(request);\n}\n\nfunction retryTask(task: Task): void {\n const { frame } = task;\n if (frame.segment.status !== \"pending\") return;\n\n frame.segment.status = \"rendering\";\n\n try {\n renderChildren(task.node, frame, task.childIndexBase);\n completeSegmentText(frame.segment);\n frame.segment.status = \"completed\";\n detachTask(task);\n settleTask(task, \"completed\");\n } catch (error) {\n detachTask(task);\n frame.segment.status = \"completed\";\n settleTask(task, \"errored\", error);\n }\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 frame.idPathString ??= formatIdPath(frame.idPath);\n const id = `${frame.request.identifierPrefix}fig-${frame.idPathString}-${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: NormalizedChild | number, frame: RenderFrame): void {\n if (typeof node === \"string\" || typeof node === \"number\") {\n const text = String(node);\n if (frame.request.documentHasHead === false) {\n if (text.trim() !== \"\") throw invalidDocumentShellError();\n }\n if (__DEV__ && frame.hostNamespace === \"html\") {\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 // 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 if (consumePendingLeadingNewline(frame)) {\n frame.segment.write({ value: escapeText(text) });\n } else {\n writeText(text, frame.segment);\n }\n frame.segment.lastPushedText = true;\n }\n return;\n }\n\n if (isPortal(node)) return;\n\n if (isValidElement(node)) {\n renderElement(node, frame);\n return;\n }\n\n if (isThenable(node)) {\n renderChildren(readThenable(node), frame);\n return;\n }\n\n throw invalidChildError(node);\n}\n\nfunction renderChildren(\n node: FigNode,\n frame: RenderFrame,\n indexBase = 0,\n): void {\n if (Array.isArray(node)) {\n const children = collectChildren(node);\n for (let index = 0; index < children.length; index += 1) {\n renderChildAtIndex(children[index], frame, indexBase + index);\n }\n return;\n }\n if (\n node === null ||\n node === undefined ||\n typeof node === \"boolean\" ||\n node === \"\"\n ) {\n return;\n }\n renderChildAtIndex(node, frame, indexBase);\n}\n\nfunction renderChildAtIndex(\n child: NormalizedChild | number,\n frame: RenderFrame,\n index: number,\n): void {\n const previousIdPathString = frame.idPathString;\n frame.idPath.push(index);\n frame.idPathString = null;\n\n try {\n renderNode(child, frame);\n } catch (error) {\n // A retry task stores the parent path plus this child index, so fork its\n // scope only after restoring the parent path.\n frame.idPath.pop();\n frame.idPathString = previousIdPathString;\n if (isThenable(error)) {\n spawnSuspendedTask(frame, child, error, index);\n return;\n }\n throw error;\n }\n\n frame.idPath.pop();\n frame.idPathString = previousIdPathString;\n}\n\nfunction formatIdPath(path: readonly number[]): string {\n let value = \"\";\n for (let index = 0; index < path.length; index += 1) {\n if (index > 0) value += \"-\";\n value += path[index].toString(32);\n }\n return value;\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 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)) return [\"Context.Provider\", \"context-provider\"];\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 name = type.id.slice(type.id.lastIndexOf(\"#\") + 1);\n return [name || \"ClientReference\", \"client-reference\"];\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, 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: ComponentType,\n props: Props,\n frame: RenderFrame,\n): void {\n frame.dispatcher ??= createServerDispatcher(frame);\n const previousDispatcher = setCurrentDispatcher(frame.dispatcher);\n const previousDataStore = setCurrentDataStore(frame.request.dataStore);\n const previousStack = frame.stack;\n const previousLocalIdCounter = frame.localIdCounter;\n if (__DEV__ || frame.request.onError !== undefined) {\n frame.stack = { name: type.name || \"Anonymous\", parent: previousStack };\n }\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, 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 if (Array.isArray(value)) {\n for (const resource of value) renderAssetResource(resource, frame);\n } else {\n renderAssetResource(value, frame);\n }\n}\n\nfunction renderAssetResource(resource: unknown, frame: RenderFrame): void {\n if (!isFigAssetResource(resource)) {\n throw new Error(\"The assets prop must contain Fig asset resources.\");\n }\n\n try {\n frame.request.assetRegistry.register(resource);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n }\n\n frame.segment.assetResources.push(resource);\n}\n\nfunction renderAutomaticImagePreload(\n resource: PreloadResource,\n frame: RenderFrame,\n): void {\n try {\n frame.request.assetRegistry.registerAutomaticImage(resource);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n }\n frame.segment.assetResources.push(resource);\n}\n\nfunction renderSuspense(props: Props, frame: RenderFrame): void {\n consumePendingLeadingNewline(frame);\n const contentSegment = createSegment(0);\n const boundary: SuspenseBoundary = {\n activityId: frame.hiddenActivityId,\n completedSegments: [],\n contentSegment,\n error: null,\n fallbackSegment: null,\n fallbackTasks: new Set(),\n id: null,\n metadataVisible: false,\n parentFlushed: false,\n pendingTasks: 0,\n status: \"pending\",\n };\n const parentSegment = frame.segment;\n const boundarySegment = createSegment(parentSegment.chunks.length, boundary);\n boundary.fallbackSegment = boundarySegment;\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 = forkFrame(frame, contentSegment, boundary);\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: renderChildAtIndex 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 advanceViewTransitionWatermark(frame, contentFrame);\n\n if (boundary.status === \"completed\") return;\n\n const fallbackFrame = forkFrame(\n frame,\n boundarySegment,\n frame.boundary,\n boundary.fallbackTasks,\n );\n\n try {\n renderChildren(props.fallback, fallbackFrame);\n boundarySegment.status = \"completed\";\n } catch (error) {\n if (boundary.pendingTasks > 0) {\n for (const task of boundary.fallbackTasks) {\n abortTask(task);\n }\n }\n throw error;\n } finally {\n advanceViewTransitionWatermark(frame, fallbackFrame);\n }\n}\n\nfunction advanceViewTransitionWatermark(\n parent: RenderFrame,\n branch: RenderFrame,\n): void {\n if (parent.viewTransition !== null && branch.viewTransition !== null) {\n parent.viewTransition.index = Math.max(\n parent.viewTransition.index,\n branch.viewTransition.index,\n );\n }\n}\n\nfunction renderViewTransition(\n props: ViewTransitionProps,\n frame: RenderFrame,\n): void {\n const previousViewTransition = frame.viewTransition;\n const className = props.default;\n frame.viewTransition = {\n className:\n className === undefined || className === \"auto\" || className === \"none\"\n ? null\n : className,\n index: 0,\n name:\n props.name === undefined || props.name === \"auto\"\n ? `fig-vt-${frame.request.nextViewTransitionId++}`\n : props.name,\n };\n\n try {\n renderChildren(props.children, frame);\n } finally {\n frame.viewTransition = previousViewTransition;\n }\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 const normalizedType = type.toLowerCase();\n const namespace =\n normalizedType === \"svg\"\n ? \"svg\"\n : normalizedType === \"math\"\n ? \"mathml\"\n : frame.hostNamespace;\n if (namespace === \"html\" && renderHostAsset(normalizedType, props, frame)) {\n return;\n }\n\n if (__DEV__ && namespace === \"html\") {\n validateInstanceNesting(type, frame.hostAncestors);\n }\n\n const isDocument = frame.request.documentHasHead !== null;\n const isDocumentHead = isDocument && type === \"head\";\n if (frame.request.documentHasHead === false) {\n if (type !== \"html\" && type !== \"head\") throw invalidDocumentShellError();\n }\n\n if (isDocument && type === \"html\") {\n frame.segment.write(\"<!doctype html>\");\n }\n if (isDocumentHead) frame.request.documentHasHead = true;\n\n const isVoid = namespace === \"html\" && 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 if (namespace === \"html\") {\n const imagePreload = imagePreloadFromHostProps(\n type,\n props,\n frame.imagePreloadsSuppressed,\n );\n if (imagePreload !== null) {\n renderAutomaticImagePreload(imagePreload, frame);\n }\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 (isDocumentHead) {\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 previousPendingLeadingNewline = frame.pendingLeadingNewline;\n const tracksLeadingNewline = type === \"pre\" || type === \"textarea\";\n frame.pendingLeadingNewline = tracksLeadingNewline;\n\n const formText = namespace === \"html\" ? formTextContent(type, props) : null;\n const staticContent = unsafeHTML ?? formText;\n if (staticContent !== null) {\n const content =\n consumePendingLeadingNewline(frame) && staticContent.startsWith(\"\\n\")\n ? `\\n${staticContent}`\n : staticContent;\n if (unsafeHTML === null) writeText(content, frame.segment);\n else frame.segment.write(content);\n frame.pendingLeadingNewline = previousPendingLeadingNewline;\n writeElementEnd(type, frame.segment);\n return;\n }\n\n const previousSelectProps = frame.selectProps;\n if (namespace === \"html\" && type === \"select\") frame.selectProps = props;\n const previousHostAncestors = frame.hostAncestors;\n const previousHostNamespace = frame.hostNamespace;\n const previousImagePreloadsSuppressed = frame.imagePreloadsSuppressed;\n const previousViewTransition = frame.viewTransition;\n if (viewTransition !== null) frame.viewTransition = null;\n if (__DEV__) {\n frame.hostAncestors = [type, ...previousHostAncestors];\n }\n frame.hostNamespace =\n namespace === \"svg\" && normalizedType === \"foreignobject\"\n ? \"html\"\n : namespace;\n frame.imagePreloadsSuppressed =\n previousImagePreloadsSuppressed ||\n (namespace === \"html\" && suppressesImagePreloads(type));\n if (tracksLeadingNewline) {\n frame.segment.chunks.push(leadingNewlineStartMarker);\n }\n\n try {\n // Suspensions are handled inside renderChildAtIndex (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.hostNamespace = previousHostNamespace;\n frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed;\n frame.viewTransition = previousViewTransition;\n frame.pendingLeadingNewline = previousPendingLeadingNewline;\n }\n if (tracksLeadingNewline) {\n frame.segment.chunks.push(leadingNewlineEndMarker);\n }\n if (isDocumentHead) frame.segment.write(documentHeadMarker);\n writeElementEnd(type, frame.segment);\n}\n\nfunction renderHostAsset(\n normalizedType: string,\n props: Props,\n frame: RenderFrame,\n): boolean {\n // Deliberately gate before assetResourceFromHostProps, which allocates a\n // prop accessor. These names mirror the core classifier; other tags dominate.\n if (normalizedType.length < 4 || normalizedType.length > 6) return false;\n switch (normalizedType) {\n case \"link\":\n case \"meta\":\n case \"script\":\n case \"title\":\n break;\n default:\n return false;\n }\n\n const resource = assetResourceFromHostProps(normalizedType, 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 // 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);\n segment.lastPushedText = frame.segment.lastPushedText;\n segment.textEmbedded = true;\n frame.segment.lastPushedText = false;\n frame.segment.children.push(segment);\n\n const task = createTask(node, forkFrame(frame, segment), childIndexBase);\n const ping = () => pingTask(task);\n thenable.then(ping, ping);\n}\n\nfunction pingTask(task: Task): void {\n const { request } = task.frame;\n if (request.status === \"closed\" || request.status === \"aborting\") return;\n const shouldSchedule = request.pingedTasks.length === 0;\n request.pingedTasks.push(task);\n // An empty queue has no scheduled drain. Many thenables settling in one\n // tick append behind the first and share its microtask.\n if (shouldSchedule) queueMicrotask(() => performWork(request));\n}\n\nfunction settleTask(\n task: Task,\n outcome: \"aborted\" | \"completed\" | \"errored\",\n error?: unknown,\n): void {\n const { boundary, request, segment, stack } = task.frame;\n if (boundary === null) {\n request.pendingRootTasks -= 1;\n if (outcome === \"errored\") {\n fatalError(request, error);\n return;\n }\n if (request.pendingRootTasks === 0) finishRootShell(request);\n } else {\n boundary.pendingTasks -= 1;\n\n if (outcome === \"errored\") {\n markBoundaryClientRendered(request, boundary, error, stack);\n } else if (outcome === \"completed\" && segment.parentFlushed) {\n boundary.completedSegments.push(segment);\n }\n\n if (outcome !== \"errored\") {\n const boundaryCompleted = completeBoundaryIfReady(request, boundary);\n if (\n outcome === \"completed\" &&\n !boundaryCompleted &&\n boundary.parentFlushed\n ) {\n request.partialBoundaries.add(boundary);\n }\n }\n }\n\n if (request.abortableTasks.size === 0) request.allReady.resolve(undefined);\n}\n\nfunction detachTask(task: Task): boolean {\n task.frame.fallbackTasks?.delete(task);\n return task.frame.request.abortableTasks.delete(task);\n}\n\nfunction abortTask(task: Task): void {\n if (!detachTask(task)) return;\n\n const { frame } = task;\n frame.segment.status = \"completed\";\n settleTask(task, \"aborted\");\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 for (const fallbackTask of boundary.fallbackTasks) {\n abortTask(fallbackTask);\n }\n if (boundary.parentFlushed) request.completedBoundaries.add(boundary);\n return true;\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 =\n payload ??\n serverErrorPayload(error, stackForError(error, stack), request.onError);\n }\n\n boundary.completedSegments.length = 0;\n request.completedBoundaries.delete(boundary);\n request.partialBoundaries.delete(boundary);\n\n for (const task of request.abortableTasks) {\n if (task.frame.boundary === boundary) abortTask(task);\n }\n\n for (const task of boundary.fallbackTasks) {\n abortTask(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 request.status = \"aborting\";\n const error = abortError(reason);\n request.abortReason = error;\n\n if (request.pendingRootTasks > 0) {\n fatalError(request, error);\n return;\n }\n\n request.dispose();\n for (const task of request.abortableTasks) {\n const { boundary, stack } = task.frame;\n if (boundary !== null) {\n markBoundaryClientRendered(request, boundary, error, stack, {});\n }\n }\n\n request.abortableTasks.clear();\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 request.status = \"closed\";\n request.dispose();\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.documentHasHead === false) {\n fatalError(request, invalidDocumentShellError());\n return;\n }\n\n if (!request.prerender) sealHead(request);\n request.shellReady.resolve(undefined);\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 createRuntimeName(identifierPrefix: string): 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 consumePendingLeadingNewline(frame: RenderFrame): boolean {\n const pending = frame.pendingLeadingNewline;\n frame.pendingLeadingNewline = false;\n return pending;\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 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.abortReason);\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 {\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 {\n getHead: _getHead,\n headReady: _headReady,\n ...result\n } = createServerRenderRequest(node, options, {\n document: true,\n });\n return result;\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 = options.document === true;\n const result = createServerRenderRequest(node, options, {\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 ServerDocumentRenderResult,\n ServerErrorInfo,\n ServerErrorPayload,\n ServerFragmentRenderResult,\n ServerPreloadHeaderOptions,\n ServerPreloadHeaderResource,\n ServerPrerenderOptions,\n ServerPrerenderResult,\n ServerRenderOptions,\n} from \"./types.ts\";\n"],"mappings":";;;;;AAeA,MAAM,+BAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;C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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"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["writeScript"],"sources":["../src/html.ts","../src/preload-header.ts","../src/asset-registry.ts","../src/protocol.ts","../src/renderer-flush.ts","../src/renderer.ts","../src/render-tree.ts","../src/index.ts"],"sourcesContent":["import type { Props } from \"@bgub/fig\";\nimport { isPortal } from \"@bgub/fig/internal\";\nimport { escapeAttribute, escapeText } from \"./escaping.ts\";\n\nexport {\n escapeAttribute,\n escapeScriptJson,\n escapeScriptText,\n escapeText,\n} from \"./escaping.ts\";\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\nconst attributeNamePattern = /[\\s\"'<>/=]/;\nconst eventPropPattern = /^on[A-Z]/;\nconst styleNamePattern = /[A-Z]/g;\nconst tagNamePattern = /^[A-Za-z][A-Za-z0-9:._-]*$/;\n\nfunction hyphenateStyleLetter(letter: string): string {\n return `-${letter.toLowerCase()}`;\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 selectProps: Props | null = null,\n): void {\n validateTagName(type);\n sink.write(`<${type}${serializeAttributes(type, props, selectProps)}>`);\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 node !== null && node !== undefined && typeof node !== \"boolean\";\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 serializeAttributes(\n type: string,\n props: Props,\n selectProps: Props | null,\n): string {\n let attributes = \"\";\n\n for (const name of Object.keys(props)) {\n const value = props[name];\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 !== \"\") attributes += serializeAttribute(\"style\", style);\n continue;\n }\n\n attributes += serializeProp(type, name, value);\n }\n\n if (\n type === \"option\" &&\n props.selected === undefined &&\n optionSelected(optionValue(props), selectProps)\n ) {\n attributes += \" selected\";\n }\n\n return attributes;\n}\n\nfunction serializeProp(type: string, name: string, value: unknown): string {\n const isValueProp = name === \"value\" || name === \"defaultValue\";\n if ((type === \"textarea\" || type === \"select\") && isValueProp) {\n return \"\";\n }\n\n let attributeName = name;\n let attributeValue = value;\n\n if (isValueProp) {\n attributeName = \"value\";\n if (serializableAttributeValue(value)) attributeValue = String(value);\n } else if (name === \"defaultChecked\") {\n attributeName = \"checked\";\n attributeValue = value === true ? true : null;\n } else if (type === \"option\" && name === \"selected\") {\n attributeValue = value === true ? true : null;\n }\n\n if (emptyValue(attributeValue)) return \"\";\n\n validateAttributeName(attributeName);\n if (attributeValue === true) return ` ${attributeName}`;\n if (serializableAttributeValue(attributeValue)) {\n return serializeAttribute(attributeName, String(attributeValue));\n }\n\n throw new Error(`Cannot serialize prop \"${name}\" to HTML.`);\n}\n\nfunction optionSelected(value: unknown, selectProps: Props | null): boolean {\n if (selectProps === null) return false;\n\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 if (!Array.isArray(selectValue)) return String(selectValue) === optionValue;\n for (const selectedValue of selectValue) {\n if (String(selectedValue) === optionValue) return true;\n }\n return false;\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 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 serializeAttribute(name: string, value: string): string {\n return ` ${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 styles = value as Record<string, unknown>;\n let serialized = \"\";\n for (const name of Object.keys(styles)) {\n const item = styles[name];\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 if (serialized !== \"\") serialized += \";\";\n serialized += `${styleName(name)}:${String(item)}`;\n }\n\n return serialized;\n}\n\nfunction reservedProp(name: string): boolean {\n return (\n name === \"children\" ||\n name === \"key\" ||\n name === \"mix\" ||\n name === \"bind\" ||\n name === \"suppressHydrationWarning\" ||\n name === \"unsafeHTML\" ||\n eventPropPattern.test(name)\n );\n}\n\nfunction styleName(name: string): string {\n if (name.startsWith(\"--\")) return name;\n return name.replace(styleNamePattern, hyphenateStyleLetter);\n}\n\nfunction validateTagName(name: string): void {\n if (!tagNamePattern.test(name)) {\n throw new Error(`Invalid HTML tag name \"${name}\".`);\n }\n}\n\nfunction validateAttributeName(name: string): void {\n if (attributeNamePattern.test(name)) {\n throw new Error(`Invalid HTML attribute name \"${name}\".`);\n }\n}\n","import type { FigAssetResource, PreloadResource } from \"@bgub/fig\";\nimport type {\n ServerPreloadHeaderOptions,\n ServerPreloadHeaderResource,\n} from \"./types.ts\";\n\ntype DeliveryResource = Exclude<FigAssetResource, { kind: \"meta\" | \"title\" }>;\n\nexport type PreloadHeaderResourceSnapshot =\n readonly ServerPreloadHeaderResource[];\n\nexport interface PreloadHeaderEntry {\n readonly resource: ServerPreloadHeaderResource;\n readonly value: string;\n}\n\nconst DEFAULT_LENGTH = 2_000;\nconst HEX_ESCAPE = /^[0-9A-Fa-f]{2}$/;\nconst PARAMETER_TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst URI_REFERENCE_PUNCTUATION = \"-._~:/?#[]@!$&'()*+,;=\";\n\nexport function createPreloadHeaderEntries(\n resources: Iterable<DeliveryResource>,\n): PreloadHeaderEntry[] {\n const entries: PreloadHeaderEntry[] = [];\n\n for (const resource of resources) {\n if (!isServerPreloadHeaderResource(resource)) continue;\n const value = preloadHeaderValue(resource);\n if (value !== null) entries.push({ resource, value });\n }\n\n return entries;\n}\n\nexport function snapshotPreloadHeaderResources(\n resources: Iterable<DeliveryResource>,\n isEarlyImage?: (resource: PreloadResource) => boolean,\n): PreloadHeaderResourceSnapshot {\n const preconnects: ServerPreloadHeaderResource[] = [];\n const criticalPreloads: ServerPreloadHeaderResource[] = [];\n const stylesheets: ServerPreloadHeaderResource[] = [];\n const remaining: ServerPreloadHeaderResource[] = [];\n\n for (const resource of resources) {\n if (!isServerPreloadHeaderResource(resource)) continue;\n const snapshot: ServerPreloadHeaderResource = { ...resource };\n\n if (resource.kind === \"preconnect\") {\n preconnects.push(snapshot);\n } else if (\n resource.kind === \"font\" ||\n (resource.kind === \"preload\" &&\n (resource.as === \"font\" ||\n (resource.as === \"image\" &&\n (resource.fetchpriority === \"high\" ||\n isEarlyImage?.(resource) === true))))\n ) {\n criticalPreloads.push(snapshot);\n } else if (resource.kind === \"stylesheet\") {\n stylesheets.push(snapshot);\n } else {\n remaining.push(snapshot);\n }\n }\n\n return [...preconnects, ...criticalPreloads, ...stylesheets, ...remaining];\n}\n\nexport function formatPreloadHeader(\n entries: readonly PreloadHeaderEntry[],\n options: ServerPreloadHeaderOptions = {},\n): string | undefined {\n const maxLength = normalizedLength(options.maxLength);\n if (maxLength === 0) return undefined;\n\n const seen = new Set<string>();\n const values: string[] = [];\n let length = 0;\n\n for (const entry of entries) {\n if (options.filter !== undefined && !options.filter(entry.resource)) {\n continue;\n }\n if (seen.has(entry.value)) continue;\n\n const addedLength = entry.value.length + (values.length === 0 ? 0 : 2);\n if (length + addedLength > maxLength) continue;\n\n seen.add(entry.value);\n values.push(entry.value);\n length += addedLength;\n }\n\n return values.length === 0 ? undefined : values.join(\", \");\n}\n\nfunction preloadHeaderValue(\n resource: ServerPreloadHeaderResource,\n): string | null {\n switch (resource.kind) {\n case \"stylesheet\":\n return serializeLink(resource.href, [\n [\"rel\", \"preload\"],\n [\"as\", \"style\"],\n [\"crossorigin\", resource.crossorigin],\n [\"media\", resource.media],\n ]);\n case \"preload\":\n return serializeLink(resource.href, [\n [\"rel\", \"preload\"],\n [\"as\", resource.as],\n [\"crossorigin\", resource.crossorigin],\n [\"type\", resource.type],\n [\"fetchpriority\", resource.fetchpriority],\n [\"referrerpolicy\", resource.referrerpolicy],\n ]);\n case \"modulepreload\":\n return serializeLink(resource.href, [\n [\"rel\", \"modulepreload\"],\n [\"as\", \"script\"],\n [\"crossorigin\", resource.crossorigin],\n [\"fetchpriority\", resource.fetchpriority],\n ]);\n case \"font\":\n return serializeLink(resource.href, [\n [\"rel\", \"preload\"],\n [\"as\", \"font\"],\n [\"crossorigin\", resource.crossorigin ?? \"anonymous\"],\n [\"type\", resource.type],\n [\"fetchpriority\", resource.fetchpriority],\n ]);\n case \"preconnect\":\n return serializeLink(resource.href, [\n [\"rel\", \"preconnect\"],\n [\"crossorigin\", resource.crossorigin],\n ]);\n }\n}\n\nfunction isServerPreloadHeaderResource(\n resource: DeliveryResource,\n): resource is ServerPreloadHeaderResource {\n if (resource.kind === \"script\") return false;\n return (\n resource.kind !== \"preload\" ||\n (resource.href !== undefined &&\n (resource.as !== \"image\" || !resource.imagesrcset))\n );\n}\n\nfunction serializeLink(\n target: string,\n parameters: ReadonlyArray<readonly [name: string, value?: string]>,\n): string | null {\n const encodedTarget = encodeLinkTarget(target);\n if (encodedTarget === null) return null;\n\n const parts = [`<${encodedTarget}>`];\n for (const [name, value] of parameters) {\n if (value === undefined) continue;\n const parameter = serializeParameter(name, value);\n if (parameter === null) return null;\n parts.push(parameter);\n }\n return parts.join(\"; \");\n}\n\nfunction serializeParameter(name: string, value: string): string | null {\n if (value === \"\") return name;\n if (hasInvalidParameterCharacter(value)) return null;\n if (PARAMETER_TOKEN.test(value)) return `${name}=${value}`;\n return `${name}=\"${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"')}\"`;\n}\n\nfunction encodeLinkTarget(value: string): string | null {\n if (value === \"\") return null;\n let encoded = \"\";\n\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code <= 0x20 || code === 0x7f) return null;\n\n const character = value[index];\n if (\n character === \"%\" &&\n HEX_ESCAPE.test(value.slice(index + 1, index + 3))\n ) {\n encoded += value.slice(index, index + 3);\n index += 2;\n continue;\n }\n if (\n (code >= 0x30 && code <= 0x39) ||\n (code >= 0x41 && code <= 0x5a) ||\n (code >= 0x61 && code <= 0x7a) ||\n URI_REFERENCE_PUNCTUATION.includes(character)\n ) {\n encoded += character;\n continue;\n }\n\n const codePoint = value.codePointAt(index);\n if (codePoint === undefined) return null;\n const symbol = String.fromCodePoint(codePoint);\n if (symbol.length === 2) index += 1;\n try {\n encoded += encodeURIComponent(symbol);\n } catch {\n return null;\n }\n }\n return encoded;\n}\n\nfunction hasInvalidParameterCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code < 0x20 || code === 0x7f || code > 0xff) return true;\n }\n return false;\n}\n\nfunction normalizedLength(value: number | undefined): number {\n if (value === undefined || Number.isNaN(value)) return DEFAULT_LENGTH;\n return Math.max(0, Math.floor(value));\n}\n","import { type FigAssetResource, type PreloadResource } from \"@bgub/fig\";\nimport {\n assetResourceHostProps,\n assetResourceKey,\n HYDRATION_SKIP_ATTRIBUTE,\n} from \"@bgub/fig/internal\";\nimport { writeElementEnd, writeElementStart, writeText } from \"./html.ts\";\nimport {\n type PreloadHeaderResourceSnapshot,\n snapshotPreloadHeaderResources,\n} from \"./preload-header.ts\";\nimport { STREAMED_METADATA_ATTRIBUTE } from \"./shared.ts\";\n\nexport type MetadataSnapshotEntry =\n | readonly [key: string, kind: \"title\", value: string]\n | readonly [\n key: string,\n kind: \"meta\",\n attributes: ReadonlyArray<readonly [name: string, value: string]>,\n ];\n\ntype MetadataResource = Extract<FigAssetResource, { kind: \"meta\" | \"title\" }>;\ntype DeliveryResource = Exclude<FigAssetResource, MetadataResource>;\n\nexport interface HeadMetadataHtml {\n preamble: string;\n metadata: string;\n}\n\nexport class AssetResourceRegistry {\n private readonly earlyImageKeys = new Set<string>();\n private readonly emittedResources = new Set<string>();\n private readonly deliveryResources = new Map<string, DeliveryResource>();\n private readonly metadataByOwner = new Map<\n object,\n readonly MetadataResource[]\n >();\n private readonly stylesheetIds = new Map<string, string>();\n private nextStylesheetId = 0;\n\n constructor(private readonly identifierPrefix: string) {}\n\n register(resource: FigAssetResource): void {\n if (isMetadataResource(resource)) return;\n this.canonical(assetResourceKey(resource), resource);\n }\n\n registerAutomaticImage(resource: PreloadResource): void {\n const key = assetResourceKey(resource);\n const current = this.canonical(key, resource);\n if (\n this.earlyImageKeys.size < 10 ||\n (current.kind === \"preload\" &&\n current.as === \"image\" &&\n current.fetchpriority === \"high\")\n ) {\n this.earlyImageKeys.add(key);\n }\n }\n\n activateMetadata(\n owner: object,\n resources: readonly FigAssetResource[],\n ): void {\n let metadata: MetadataResource[] | null = null;\n for (const resource of resources) {\n if (isMetadataResource(resource)) (metadata ??= []).push(resource);\n }\n if (metadata === null) {\n this.metadataByOwner.delete(owner);\n return;\n }\n // Map.set preserves an existing key's position, so updating an owner does\n // not steal precedence from owners activated later.\n this.metadataByOwner.set(owner, metadata);\n }\n\n releaseMetadata(owner: object): void {\n this.metadataByOwner.delete(owner);\n }\n\n write(resource: FigAssetResource, sink: AssetSink): string | null {\n if (isMetadataResource(resource)) return null;\n\n const key = assetResourceKey(resource);\n const current = this.canonical(key, resource);\n const id = this.revealBlockerId(key, current);\n\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 writeDocumentHead(\n resources: readonly FigAssetResource[],\n metadata: HeadMetadataHtml,\n sink: AssetSink,\n ): void {\n const preconnects: DeliveryResource[] = [];\n const criticalPreloads: DeliveryResource[] = [];\n const stylesheets: DeliveryResource[] = [];\n const afterMetadata: DeliveryResource[] = [];\n\n for (const resource of resources) {\n if (isMetadataResource(resource)) continue;\n if (resource.kind === \"preconnect\") {\n preconnects.push(resource);\n } else if (\n resource.kind === \"font\" ||\n (resource.kind === \"preload\" &&\n (resource.as === \"font\" ||\n (resource.as === \"image\" &&\n (resource.fetchpriority === \"high\" ||\n this.isEarlyImage(resource)))))\n ) {\n criticalPreloads.push(resource);\n } else if (resource.kind === \"stylesheet\") {\n stylesheets.push(resource);\n } else {\n afterMetadata.push(resource);\n }\n }\n\n sink.write(metadata.preamble);\n for (const resource of preconnects) this.write(resource, sink);\n for (const resource of criticalPreloads) this.write(resource, sink);\n for (const resource of stylesheets) this.write(resource, sink);\n sink.write(metadata.metadata);\n for (const resource of afterMetadata) this.write(resource, sink);\n }\n\n headHtml(nonce?: string, streamMetadata = false): string {\n const { preamble, metadata } = this.headMetadataHtml(nonce, streamMetadata);\n return preamble + metadata;\n }\n\n headMetadataHtml(nonce?: string, streamMetadata = false): HeadMetadataHtml {\n const buckets: Record<MetadataPhase, string[]> = {\n charset: [],\n parser: [],\n viewport: [],\n metadata: [],\n };\n\n for (const resource of this.visibleMetadata().values()) {\n const bucket = buckets[metadataPhase(resource)];\n writeAssetTag(\n { nonce, streamMetadata, write: (chunk) => bucket.push(chunk) },\n resource,\n null,\n );\n }\n\n return {\n preamble:\n buckets.charset.join(\"\") +\n buckets.parser.join(\"\") +\n buckets.viewport.join(\"\"),\n metadata: buckets.metadata.join(\"\"),\n };\n }\n\n metadataSnapshot(): MetadataSnapshotEntry[] {\n const snapshot: MetadataSnapshotEntry[] = [];\n for (const [key, resource] of this.visibleMetadata()) {\n if (resource.kind === \"title\") {\n snapshot.push([key, resource.kind, resource.value]);\n } else {\n snapshot.push([key, resource.kind, metadataAttributes(resource)]);\n }\n }\n return snapshot;\n }\n\n preloadHeaderResources(): PreloadHeaderResourceSnapshot {\n return snapshotPreloadHeaderResources(\n this.deliveryResources.values(),\n (resource) => this.isEarlyImage(resource),\n );\n }\n\n private isEarlyImage(resource: PreloadResource): boolean {\n return this.earlyImageKeys.has(assetResourceKey(resource));\n }\n\n private visibleMetadata(): Map<string, MetadataResource> {\n const visible = new Map<string, MetadataResource>();\n for (const metadata of this.metadataByOwner.values()) {\n for (const resource of metadata) {\n visible.set(assetResourceKey(resource), resource);\n }\n }\n return visible;\n }\n\n private canonical(key: string, resource: DeliveryResource): DeliveryResource {\n const current = this.deliveryResources.get(key);\n\n if (current !== undefined) {\n if (assetSignature(current) !== assetSignature(resource)) {\n const promoted = promoteCompatibleImagePreload(current, resource);\n if (promoted === null) {\n throw new AssetResourceConflictError(key, current, resource);\n }\n this.deliveryResources.set(key, promoted);\n return promoted;\n }\n\n return current;\n }\n\n this.deliveryResources.set(key, resource);\n return 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 streamMetadata?: boolean;\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(\n \"title\",\n {\n [HYDRATION_SKIP_ATTRIBUTE]: true,\n [STREAMED_METADATA_ATTRIBUTE]: sink.streamMetadata\n ? assetResourceKey(resource)\n : undefined,\n },\n sink,\n );\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[\"http-equiv\"],\n content: resource.content,\n [HYDRATION_SKIP_ATTRIBUTE]: true,\n [STREAMED_METADATA_ATTRIBUTE]: sink.streamMetadata\n ? assetResourceKey(resource)\n : undefined,\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 = assetResourceHostProps(resource, {\n [HYDRATION_SKIP_ATTRIBUTE]: true,\n });\n if (resource.kind === \"stylesheet\" && id !== null) props.id = id;\n if (sink.nonce !== undefined) props.nonce = sink.nonce;\n\n const tag = resource.kind === \"script\" ? \"script\" : \"link\";\n writeElementStart(tag, props, sink);\n if (tag === \"script\") writeElementEnd(\"script\", sink);\n }\n }\n}\n\nfunction isMetadataResource(\n resource: FigAssetResource,\n): resource is MetadataResource {\n return resource.kind === \"title\" || resource.kind === \"meta\";\n}\n\ntype MetadataPhase = \"charset\" | \"parser\" | \"viewport\" | \"metadata\";\n\nfunction metadataPhase(resource: MetadataResource): MetadataPhase {\n if (resource.kind === \"title\") return \"metadata\";\n if (resource.charset !== undefined) return \"charset\";\n if (\n normalizedMetadataName(resource[\"http-equiv\"]) === \"content-security-policy\"\n ) {\n return \"parser\";\n }\n if (normalizedMetadataName(resource.name) === \"viewport\") return \"viewport\";\n return \"metadata\";\n}\n\nfunction normalizedMetadataName(value: string | undefined): string | undefined {\n return value?.trim().toLowerCase();\n}\n\nfunction metadataAttributes(\n resource: Extract<FigAssetResource, { kind: \"meta\" }>,\n): Array<readonly [string, string]> {\n const attributes: Array<readonly [string, string | undefined]> = [\n [\"charset\", resource.charset],\n [\"name\", resource.name],\n [\"property\", resource.property],\n [\"http-equiv\", resource[\"http-equiv\"]],\n [\"content\", resource.content],\n [\"data-fig-resource-key\", resource.key],\n ];\n return attributes.filter(\n (entry): entry is readonly [string, string] => entry[1] !== undefined,\n );\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 const imagesrcset =\n resource.as === \"image\" ? resource.imagesrcset || undefined : undefined;\n return signature(\n resource.kind,\n imagesrcset === undefined ? (resource.href ?? \"\") : \"\",\n resource.as,\n resource.type ?? \"\",\n resource.crossorigin ?? \"\",\n resource.fetchpriority ?? \"\",\n imagesrcset ?? \"\",\n imagesrcset === undefined ? \"\" : (resource.imagesizes ?? \"\"),\n resource.referrerpolicy ?? \"\",\n );\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 \"\",\n \"\",\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[\"http-equiv\"] ?? \"\",\n resource.content ?? \"\",\n );\n }\n\n return unsupportedAssetResource(resource);\n}\n\nfunction promoteCompatibleImagePreload(\n current: DeliveryResource,\n incoming: DeliveryResource,\n): DeliveryResource | null {\n if (\n current.kind !== \"preload\" ||\n incoming.kind !== \"preload\" ||\n current.as !== \"image\" ||\n incoming.as !== \"image\" ||\n assetSignature({\n ...current,\n fetchpriority: incoming.fetchpriority,\n }) !== assetSignature(incoming)\n ) {\n return null;\n }\n\n const currentPriority =\n current.fetchpriority === \"auto\" ? undefined : current.fetchpriority;\n const incomingPriority =\n incoming.fetchpriority === \"auto\" ? undefined : incoming.fetchpriority;\n if (currentPriority === incomingPriority) return current;\n if (currentPriority === \"low\" || incomingPriority === \"low\") return null;\n return currentPriority === \"high\"\n ? current\n : { ...current, fetchpriority: \"high\" };\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 HYDRATION_SKIP_ATTRIBUTE,\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 VIEW_TRANSITION_TIMEOUT_MS,\n} from \"@bgub/fig/internal\";\nimport { escapeAttribute, escapeScriptJson } from \"./escaping.ts\";\nimport { nonceAttribute, STREAMED_METADATA_ATTRIBUTE } from \"./shared.ts\";\n\ninterface ProtocolRequest {\n identifierPrefix: string;\n nonce?: string;\n runtimeName: string;\n runtimeWritten: boolean;\n write(chunk: string): void;\n}\n\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.\nfunction buildServerRuntimeCode(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 q=0,i,g=()=>{if(q)return;q=1;clearTimeout(i);d.${VIEW_TRANSITION_PENDING_PROPERTY}===p&&(d.${VIEW_TRANSITION_PENDING_PROPERTY}=null);this.v(b,s,f)};i=setTimeout(g,${VIEW_TRANSITION_TIMEOUT_MS});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()}},m(a){let h=document.head,e=new Map;for(let n of h.querySelectorAll('[${STREAMED_METADATA_ATTRIBUTE}]'))e.set(n.getAttribute('${STREAMED_METADATA_ATTRIBUTE}'),n);for(let d of a){let k=d[0],t=d[1],v=d[2],n=e.get(k);if(!n||n.tagName.toLowerCase()!==t){n&&n.remove();n=document.createElement(t);n.setAttribute('${STREAMED_METADATA_ATTRIBUTE}',k);n.setAttribute('${HYDRATION_SKIP_ATTRIBUTE}','');h.appendChild(n)}e.delete(k);if(t==='title')n.textContent=v;else{for(let x of Array.from(n.attributes))if(x.name!=='${STREAMED_METADATA_ATTRIBUTE}'&&x.name!=='${HYDRATION_SKIP_ATTRIBUTE}')n.removeAttribute(x.name);for(let x of v)n.setAttribute(x[0],x[1])}}for(let n of e.values())n.remove()},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,m){let x=document.getElementById(b),y=document.getElementById(s);this.v(x,y,r=>this.o(x,y,r,m))},o(b,s,l,m){if(!b||!s)return;let a=b.previousSibling||b,p=a.parentNode,c=s.content||s;if(!p)return;let r=a.nodeType===8&&a.__figRetry;if(!r&&m)this.m(m);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}';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,m){let x=this.b(t,b),y=document.getElementById(s);this.v(x,y,r=>this.o(x,y,r,m))},ax(t,b,d,m){this.y(this.b(t,b),d,m)}}`;\n}\n\nconst RUNTIME_CODE_PREFIX = \"globalThis[\";\nconst EMPTY_RUNTIME_REFERENCE = `${RUNTIME_CODE_PREFIX}${jsString(\"\")}`;\nconst SERVER_RUNTIME_SUFFIX = buildServerRuntimeCode(\"\").slice(\n EMPTY_RUNTIME_REFERENCE.length,\n);\n\nexport function serverRuntimeCodeFor(runtimeName: string): string {\n return `${RUNTIME_CODE_PREFIX}${jsString(runtimeName)}${SERVER_RUNTIME_SUFFIX}`;\n}\n\nexport function writeRuntime(request: ProtocolRequest): void {\n if (request.runtimeWritten) return;\n request.runtimeWritten = true;\n writeScript(request, serverRuntimeCodeFor(request.runtimeName));\n}\n\nexport function writeScript(\n request: Pick<ProtocolRequest, \"nonce\" | \"write\">,\n code: string,\n): void {\n request.write(\n `<script ${HYDRATION_SKIP_ATTRIBUTE}=\"\"${nonceAttribute(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 return EARLY_EVENT_CAPTURE_CODE;\n}\n\nconst EARLY_EVENT_CAPTURE_CODE = `(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 [${REPLAYABLE_EVENT_TYPES.map((type) => `'${type}'`).join(\",\")}])d.addEventListener(t,h,!0)})(document)`;\n\nexport function earlyEventCaptureMarkup(\n request: Pick<ProtocolRequest, \"nonce\">,\n): string {\n return `<script ${HYDRATION_SKIP_ATTRIBUTE}=\"\"${nonceAttribute(request.nonce)}>${earlyEventCaptureCode()}</script>`;\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 escapeScriptJson(value);\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 SUSPENSE_CLIENT_MARKER,\n SUSPENSE_COMPLETED_MARKER,\n SUSPENSE_END_MARKER,\n SUSPENSE_PENDING_PREFIX,\n} from \"@bgub/fig/internal\";\nimport { escapeAttribute, escapeScriptJson } from \"./escaping.ts\";\nimport {\n boundaryId,\n boundaryPlaceholderMarkup,\n jsString,\n placeholderId,\n placeholderMarkup,\n segmentContainerStartMarkup,\n segmentId,\n writeRuntime as writeProtocolRuntime,\n writeScript as writeProtocolScript,\n} from \"./protocol.ts\";\nimport type { Request, Segment, SuspenseBoundary } from \"./renderer.ts\";\nimport { streamFlowBlocked } from \"./shared.ts\";\n\nexport const documentHeadMarker = Symbol(\"fig.document-head\");\nexport const leadingNewlineStartMarker = Symbol(\"fig.leading-newline-start\");\nexport const leadingNewlineEndMarker = Symbol(\"fig.leading-newline-end\");\n\nexport type SegmentChunk =\n | string\n | typeof documentHeadMarker\n | typeof leadingNewlineStartMarker\n | typeof leadingNewlineEndMarker\n | { value: string };\n\nconst RUNTIME_REF = \"__figSSR\";\nconst textEncoder = new TextEncoder();\n\nexport function flushCompletedQueues(request: Request): void {\n if (request.controller === null || request.status === \"closed\") return;\n if (request.pendingRootTasks > 0) return;\n if (request.prerender && request.abortableTasks.size > 0) return;\n if (request.flushing) return;\n\n request.flushing = true;\n try {\n sealHead(request);\n\n // The shell flushes ungated: the queue is empty before the first enqueue,\n // and shell latency outranks flow control.\n if (request.rootSegment.status !== \"flushed\") {\n flushSegment(request, request.rootSegment);\n flushWriteBuffer(request);\n }\n\n // Stop at the first blocked drain; the stream's pull handler re-enters\n // here when the consumer makes room.\n if (\n !drainBoundaryQueue(\n request,\n request.clientRenderedBoundaries,\n flushClientRenderedBoundary,\n ) &&\n !drainBoundaryQueue(\n request,\n request.completedBoundaries,\n flushCompletedBoundary,\n )\n ) {\n drainBoundaryQueue(\n request,\n request.partialBoundaries,\n flushPartialBoundary,\n );\n }\n\n flushWriteBuffer(request);\n } finally {\n request.flushing = false;\n }\n\n // Deliberately not conditioned on flow: close() only marks the end of the\n // queue, so a full queue with nothing left to write still closes here.\n if (\n request.abortableTasks.size === 0 &&\n request.completedBoundaries.size === 0 &&\n request.clientRenderedBoundaries.size === 0 &&\n request.partialBoundaries.size === 0\n ) {\n request.status = \"closed\";\n request.dispose();\n request.controller.close();\n }\n}\n\nexport function sealHead(request: Request): void {\n if (request.headSnapshot !== null) return;\n\n activateVisibleMetadata(request, request.rootSegment);\n const metadata = request.assetRegistry.headMetadataHtml(\n request.nonce,\n !request.prerender && request.abortableTasks.size > 0,\n );\n request.headSnapshot = {\n ...metadata,\n preloadHeaderEntries: null,\n preloadHeaderResources: request.assetRegistry.preloadHeaderResources(),\n };\n request.headReady.resolve(metadata.preamble + metadata.metadata);\n}\n\nfunction flushSegment(request: Request, segment: Segment): void {\n if (segment.status === \"flushed\") return;\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 request.write(\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.documentHasHead === null || segment !== request.rootSegment) {\n collectSegmentAssets(request, segment, null);\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 // A flushed segment never needs its serialized fragments again. Releasing\n // them here keeps a completed render from retaining a second copy of the\n // response while the encoded stream chunk is consumed.\n segment.chunks.length = 0;\n}\n\nfunction flushSuspenseBoundary(\n request: Request,\n segment: Segment,\n boundary: SuspenseBoundary,\n): void {\n boundary.parentFlushed = true;\n\n if (boundary.status === \"completed\") {\n request.write(`<!--${SUSPENSE_COMPLETED_MARKER}-->`);\n for (const completedSegment of boundary.completedSegments) {\n flushSegment(request, completedSegment);\n }\n boundary.completedSegments.length = 0;\n request.write(`<!--${SUSPENSE_END_MARKER}-->`);\n segment.status = \"flushed\";\n segment.chunks.length = 0;\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 request.write(`<!--${SUSPENSE_CLIENT_MARKER}-->`);\n request.write(clientRenderedBoundaryPlaceholderMarkup(request, boundary));\n flushSubtree(request, segment);\n request.write(`<!--${SUSPENSE_END_MARKER}-->`);\n return;\n }\n\n const boundaryIdValue = ensureBoundaryId(request, boundary);\n collectSegmentAssets(request, boundary.contentSegment, null);\n request.write(`<!--${SUSPENSE_PENDING_PREFIX}${boundaryIdValue}-->`);\n request.write(boundaryPlaceholderMarkup(request, boundaryIdValue));\n flushSubtree(request, segment);\n request.write(`<!--${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 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 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.length = 0;\n}\n\nfunction flushBoundarySegment(\n request: Request,\n boundary: SuspenseBoundary,\n segment: Segment,\n): void {\n ensureBoundaryId(request, boundary);\n let blockingIds = \"\";\n if (segment.status !== \"flushed\") {\n blockingIds = flushSegmentAssets(request, segment);\n request.write(\n segmentContainerStartMarkup(request, ensureSegmentId(request, segment)),\n );\n flushSegment(request, segment);\n request.write(\"</div>\");\n }\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 writeProtocolRuntime(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 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 const metadata = switchBoundaryMetadata(request, boundary);\n const metadataArgument = metadata === null ? \"\" : `,${metadata}`;\n writeProtocolRuntime(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 call =\n boundary.activityId === null\n ? `${RUNTIME_REF}.c(${boundaryRef},${contentRef}${metadataArgument})`\n : `${RUNTIME_REF}.ac(${jsString(boundary.activityId)},${boundaryRef},${contentRef}${metadataArgument})`;\n writeScript(request, withAssetGate(blockingIds, call));\n}\n\nfunction switchBoundaryMetadata(\n request: Request,\n boundary: SuspenseBoundary,\n): string | null {\n // A nested boundary may complete while an ancestor's primary content is\n // still staged. Its segment fill is useful, but its metadata is not visible;\n // the ancestor reveal traversal will activate the settled branch later.\n if (!boundary.metadataVisible) return null;\n\n const before = escapeScriptJson(request.assetRegistry.metadataSnapshot());\n const fallback = boundary.fallbackSegment;\n if (fallback !== null) {\n request.assetRegistry.releaseMetadata(fallback);\n for (const child of fallback.children) {\n deactivateMetadataTree(request, child);\n }\n }\n activateVisibleMetadata(request, boundary.contentSegment);\n const after = escapeScriptJson(request.assetRegistry.metadataSnapshot());\n return before === after ? null : after;\n}\n\nfunction activateVisibleMetadata(request: Request, segment: Segment): void {\n if (segment.status === \"pending\" || segment.status === \"rendering\") return;\n\n const boundary = segment.boundary;\n if (boundary !== null) {\n boundary.metadataVisible = true;\n if (boundary.status === \"completed\") {\n activateVisibleMetadata(request, boundary.contentSegment);\n return;\n }\n }\n\n request.assetRegistry.activateMetadata(segment, segment.assetResources);\n for (const child of segment.children) {\n activateVisibleMetadata(request, child);\n }\n}\n\nfunction deactivateMetadataTree(request: Request, segment: Segment): void {\n request.assetRegistry.releaseMetadata(segment);\n for (const child of segment.children) deactivateMetadataTree(request, child);\n\n const boundary = segment.boundary;\n if (boundary === null) return;\n boundary.metadataVisible = false;\n deactivateMetadataTree(request, boundary.contentSegment);\n}\n\nfunction flushSegmentAssets(request: Request, segment: Segment): string {\n const blockingIds = new Set<string>();\n collectSegmentAssets(request, segment, blockingIds);\n let serialized = \"\";\n for (const id of blockingIds) {\n if (serialized !== \"\") serialized += \",\";\n serialized += jsString(id);\n }\n return serialized;\n}\n\nfunction collectSegmentAssets(\n request: Request,\n segment: Segment,\n blockingIds: Set<string> | null,\n): void {\n if (segment.status !== \"pending\" && segment.status !== \"rendering\") {\n for (const resource of segment.assetResources) {\n const id = request.assetRegistry.write(resource, request);\n if (id !== null) blockingIds?.add(id);\n }\n }\n\n for (const child of segment.children) {\n collectSegmentAssets(request, child, blockingIds);\n }\n}\n\nfunction withAssetGate(blockingIds: string, call: string): string {\n if (blockingIds === \"\") return call;\n return `${RUNTIME_REF}.r([${blockingIds}],()=>{${call}})`;\n}\n\nfunction flushClientRenderedBoundary(\n request: Request,\n boundary: SuspenseBoundary,\n): void {\n if (boundary.id === null) return;\n writeProtocolRuntime(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 call =\n boundary.activityId === null\n ? `${RUNTIME_REF}.x(${boundaryRef},${digest},${message})`\n : `${RUNTIME_REF}.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.\n// Returns true when the drain stopped because the flow is blocked; blocked\n// boundaries stay queued for the next pull-driven pass. Gating sits between\n// boundaries — never mid-buffer — so every chunk still ends on complete\n// markup.\nfunction drainBoundaryQueue(\n request: Request,\n queue: Set<SuspenseBoundary>,\n flush: (request: Request, boundary: SuspenseBoundary) => void,\n): boolean {\n for (;;) {\n if (streamFlowBlocked(request.controller)) return true;\n const first = queue.values().next();\n if (first.done === true) return false;\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\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 );\n}\n\nfunction writeChunk(\n request: Request,\n chunk: SegmentChunk,\n segment: Segment,\n): void {\n if (chunk === leadingNewlineStartMarker) {\n request.leadingNewlineStack.push(false);\n return;\n }\n if (chunk === leadingNewlineEndMarker) {\n request.leadingNewlineStack.pop();\n return;\n }\n if (typeof chunk === \"object\") {\n request.write(\n request.leadingNewlineStack.at(-1) === false &&\n chunk.value.startsWith(\"\\n\")\n ? `\\n${chunk.value}`\n : chunk.value,\n );\n return;\n }\n if (chunk !== documentHeadMarker) {\n request.write(chunk);\n return;\n }\n\n if (request.documentHasHead === null) return;\n\n const metadata =\n request.headSnapshot ??\n request.assetRegistry.headMetadataHtml(request.nonce);\n request.assetRegistry.writeDocumentHead(\n segment.assetResources,\n metadata,\n request,\n );\n}\n\nfunction flushWriteBuffer(request: Request): void {\n if (request.writeBuffer === \"\" || request.controller === null) return;\n request.controller.enqueue(textEncoder.encode(request.writeBuffer));\n request.writeBuffer = \"\";\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","import {\n type ComponentType,\n createElement,\n type ElementType,\n type FigAssetResource,\n type FigClientReference,\n type FigContext,\n type FigElement,\n type FigNode,\n Fragment,\n isValidElement,\n type PreloadResource,\n type Props,\n type ViewTransitionProps,\n} from \"@bgub/fig\";\nimport {\n ACTIVITY_TEMPLATE_ATTRIBUTE,\n assetResourceFromHostProps,\n attachDataStore,\n collectChildren,\n createRendererDataStore,\n type FigDataStore,\n invalidChildError,\n isActivity,\n isAssets,\n isClientReference,\n isContext,\n isErrorBoundary,\n isFigAssetResource,\n isPortal,\n isSuspense,\n isThenable,\n isViewTransition,\n type NormalizedChild,\n type RenderDispatcher,\n readThenable,\n setCurrentDataStore,\n setCurrentDispatcher,\n type Thenable,\n TEXT_SEPARATOR_DATA,\n validateInstanceNesting,\n validateTextNesting,\n VIEW_TRANSITION_CLASS_ATTRIBUTE,\n VIEW_TRANSITION_NAME_ATTRIBUTE,\n} from \"@bgub/fig/internal\";\nimport {\n AssetResourceRegistry,\n type HeadMetadataHtml,\n} from \"./asset-registry.ts\";\nimport {\n escapeAttribute,\n escapeText,\n formTextContent,\n hasRenderableChild,\n isVoidElement,\n unsafeHTMLContent,\n writeElementEnd,\n writeElementStart,\n writeText,\n} from \"./html.ts\";\nimport {\n imagePreloadFromHostProps,\n suppressesImagePreloads,\n} from \"./image-preloads.ts\";\nimport { activityId, earlyEventCaptureMarkup } from \"./protocol.ts\";\nimport {\n createPreloadHeaderEntries,\n formatPreloadHeader,\n type PreloadHeaderEntry,\n type PreloadHeaderResourceSnapshot,\n} from \"./preload-header.ts\";\nimport {\n documentHeadMarker,\n flushCompletedQueues,\n leadingNewlineEndMarker,\n leadingNewlineStartMarker,\n sealHead,\n type SegmentChunk,\n} from \"./renderer-flush.ts\";\nimport {\n type ContextValues,\n type StackFrame,\n cloneContextValues,\n createStaticDispatcher,\n type Deferred,\n deferred,\n noLane,\n noop,\n serverErrorPayload,\n streamHighWaterMark,\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 HeadSnapshot extends HeadMetadataHtml {\n preloadHeaderEntries: readonly PreloadHeaderEntry[] | null;\n preloadHeaderResources: PreloadHeaderResourceSnapshot | null;\n}\n\nexport interface Request {\n abortableTasks: Set<Task>;\n allReady: Deferred<void>;\n cleanupAbortListener: (() => void) | null;\n completedBoundaries: Set<SuspenseBoundary>;\n controller: ReadableStreamDefaultController<Uint8Array> | null;\n dataStore: FigDataStore;\n dispose(): void;\n abortReason: unknown;\n identifierPrefix: string;\n // Flush-time parser state for nested <pre>/<textarea> hosts. Rendering may\n // complete child segments out of order; only logical flush order can decide\n // which text is the parser's first child.\n leadingNewlineStack: boolean[];\n nextBoundaryId: number;\n nextSegmentId: number;\n nextActivityId: number;\n nextViewTransitionId: number;\n nonce?: string;\n onError?: ServerRenderOptions[\"onError\"];\n pendingRootTasks: number;\n pingedTasks: Task[];\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: HeadSnapshot | null;\n shellReady: Deferred<void>;\n status: \"open\" | \"aborting\" | \"closed\";\n clientRenderedBoundaries: Set<SuspenseBoundary>;\n clientReferenceFallback?: ServerRenderOptions[\"clientReferenceFallback\"];\n partialBoundaries: Set<SuspenseBoundary>;\n prerender: boolean;\n componentAssets?: ServerRenderOptions[\"assets\"];\n // null for fragment renders; otherwise whether the document's <head> has\n // been rendered.\n documentHasHead: boolean | null;\n assetRegistry: AssetResourceRegistry;\n resolveAssetKey?: ServerRenderOptions[\"resolveAssetKey\"];\n // Reentrancy guard: enqueueing inside a flush pass can synchronously invoke\n // the stream's pull handler, which must not restart the pass — a boundary\n // stays in its queue while it flushes, so a reentrant drain would emit it\n // twice.\n flushing: boolean;\n // Markup accumulates here per flush pass and leaves as one encoded enqueue,\n // instead of one tiny Uint8Array per attribute/text write.\n writeBuffer: string;\n write(chunk: string): void;\n}\n\n// Mutable state for one synchronous render branch. A suspended branch keeps\n// this frame on its Task and resumes it directly; forks clone only the state\n// that must be isolated from the parent branch.\ninterface RenderFrame {\n // Only fallback work needs a second owner; every task already belongs to\n // request.abortableTasks.\n fallbackTasks: Set<Task> | null;\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 // Namespace inherited by the next host element. Unlike dev-only nesting\n // ancestry this is runtime semantics: asset lowering applies only to HTML.\n hostNamespace: HostNamespace;\n // True inside HTML <picture> and <noscript>, where an <img> does not name a\n // standalone preload candidate.\n imagePreloadsSuppressed: boolean;\n idPath: number[];\n pendingLeadingNewline: boolean;\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 dispatcher: RenderDispatcher | null;\n idPathString: string | null;\n localIdCounter: number;\n request: Request;\n segment: Segment;\n}\n\ninterface Task {\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 frame: RenderFrame;\n node: FigNode;\n}\n\nexport interface Segment {\n readonly boundary: SuspenseBoundary | null;\n children: Segment[];\n chunks: SegmentChunk[];\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: SegmentChunk): void;\n}\n\nexport interface 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 fallbackSegment: Segment | null;\n fallbackTasks: Set<Task>;\n id: number | null;\n parentFlushed: boolean;\n pendingTasks: number;\n status: BoundaryStatus;\n metadataVisible: boolean;\n}\n\ntype BoundaryStatus = \"pending\" | \"completed\" | \"client-rendered\";\ntype SegmentStatus = \"pending\" | \"rendering\" | \"completed\" | \"flushed\";\ntype HostNamespace = \"html\" | \"mathml\" | \"svg\";\n\ninterface ServerViewTransitionContext {\n className: string | null;\n index: number;\n name: string;\n}\n\nconst errorStacks = new WeakMap<object, StackFrame>();\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. The comment data is the shared\n// TEXT_SEPARATOR_DATA protocol constant that fig-dom's hydration cursor\n// skips (and only that; suspense markers use the fig:suspense prefixes).\nconst TEXT_SEPARATOR = `<!--${TEXT_SEPARATOR_DATA}-->`;\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 identifierPrefix = options.identifierPrefix ?? \"\";\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(noop);\n void headReady.promise.catch(noop);\n void allReady.promise.catch(noop);\n const rootSegment = createSegment(0);\n const dataStoreHost = {\n getLane: noLane,\n partition: options.dataPartition,\n schedule: noop,\n };\n const dataStore =\n options.dataStore === undefined\n ? createRendererDataStore<object, null>(dataStoreHost)\n : attachDataStore(options.dataStore, dataStoreHost, options.initialData);\n\n const request: Request = {\n abortableTasks: new Set<Task>(),\n allReady,\n cleanupAbortListener: null,\n completedBoundaries: new Set(),\n controller: null,\n dataStore,\n dispose: disposeRequest,\n abortReason: null,\n identifierPrefix,\n leadingNewlineStack: [],\n nextBoundaryId: 0,\n nextSegmentId: 0,\n nextActivityId: 0,\n nextViewTransitionId: 0,\n nonce: options.nonce,\n onError: options.onError,\n pendingRootTasks: 0,\n pingedTasks: [],\n rootSegment,\n runtimeName: createRuntimeName(identifierPrefix),\n runtimeWritten: false,\n headReady,\n headSnapshot: null,\n shellReady,\n status: \"open\",\n clientRenderedBoundaries: new Set(),\n clientReferenceFallback: options.clientReferenceFallback,\n partialBoundaries: new Set(),\n prerender: mode?.prerender === true,\n componentAssets: options.assets,\n documentHasHead: mode?.document === true ? false : null,\n assetRegistry: new AssetResourceRegistry(identifierPrefix),\n resolveAssetKey: options.resolveAssetKey,\n flushing: false,\n writeBuffer: \"\",\n write: writeRequestChunk,\n };\n if (options.dataStore === undefined && options.initialData !== undefined) {\n request.dataStore.hydrate(options.initialData);\n }\n\n rootSegment.parentFlushed = true;\n const rootTask = createTask(node, {\n boundary: null,\n contextValues: new Map(),\n dispatcher: null,\n fallbackTasks: null,\n hiddenActivityId: null,\n hostAncestors: [],\n hostNamespace: \"html\",\n imagePreloadsSuppressed: false,\n idPath: [],\n idPathString: null,\n localIdCounter: 0,\n pendingLeadingNewline: false,\n request,\n selectProps: null,\n segment: rootSegment,\n stack: null,\n treeParent: options.renderTree?.tree ?? null,\n viewTransition: null,\n });\n pingTask(rootTask);\n\n const stream = new ReadableStream<Uint8Array>(\n {\n start(streamController) {\n request.controller = streamController;\n flushCompletedQueues(request);\n },\n pull() {\n // The consumer drained below the high-water mark: resume flushing\n // whatever completed while the flow was blocked.\n flushCompletedQueues(request);\n },\n cancel(reason) {\n // The consumer is gone: drop the sink before aborting so the abort\n // pass does not enqueue into (or close) a cancelled stream.\n request.controller = null;\n request.writeBuffer = \"\";\n abort(request, reason);\n request.status = \"closed\";\n },\n },\n new ByteLengthQueuingStrategy({\n highWaterMark: streamHighWaterMark(options.highWaterMark),\n }),\n );\n\n if (options.signal !== undefined) {\n const signal = options.signal;\n const abortListener = () => abort(request, signal.reason);\n signal.addEventListener(\"abort\", abortListener, { once: true });\n request.cleanupAbortListener = () => {\n signal.removeEventListener(\"abort\", abortListener);\n request.cleanupAbortListener = null;\n };\n }\n\n return {\n abort: (reason?: unknown) => abort(request, reason),\n allReady: allReady.promise,\n contentType: \"text/html; charset=utf-8\",\n data: request.dataStore,\n getData: () => request.dataStore.snapshot(),\n getPreloadHeader: (headerOptions) => {\n const snapshot = request.headSnapshot;\n if (snapshot === null) return undefined;\n\n let entries = snapshot.preloadHeaderEntries;\n if (entries === null) {\n const resources = snapshot.preloadHeaderResources;\n if (resources === null) {\n throw new Error(\"Missing preload-header resource snapshot.\");\n }\n entries = createPreloadHeaderEntries(resources);\n snapshot.preloadHeaderEntries = entries;\n snapshot.preloadHeaderResources = null;\n }\n return formatPreloadHeader(entries, headerOptions);\n },\n getHead: () => {\n const snapshot = request.headSnapshot;\n return snapshot === null\n ? request.assetRegistry.headHtml(request.nonce)\n : snapshot.preamble + snapshot.metadata;\n },\n headReady: headReady.promise,\n shellReady: shellReady.promise,\n stream,\n };\n}\n\nfunction createTask(\n node: FigNode,\n frame: RenderFrame,\n childIndexBase = 0,\n): Task {\n const { request } = frame;\n if (frame.boundary === null) {\n request.pendingRootTasks += 1;\n } else {\n frame.boundary.pendingTasks += 1;\n }\n\n const task: Task = { childIndexBase, frame, node };\n request.abortableTasks.add(task);\n frame.fallbackTasks?.add(task);\n return task;\n}\n\n// Forks a branch that can outlive the current stack. Context values, the id\n// path, and the view-transition cursor are snapshots; the remaining fields\n// are immutable or restored by balanced push/pop pairs.\nfunction forkFrame(\n frame: RenderFrame,\n segment: Segment,\n boundary = frame.boundary,\n fallbackTasks = frame.fallbackTasks,\n): RenderFrame {\n return {\n boundary,\n contextValues: cloneContextValues(frame.contextValues),\n dispatcher: null,\n fallbackTasks,\n hiddenActivityId: frame.hiddenActivityId,\n hostAncestors: frame.hostAncestors,\n hostNamespace: frame.hostNamespace,\n imagePreloadsSuppressed: frame.imagePreloadsSuppressed,\n idPath: [...frame.idPath],\n idPathString: null,\n localIdCounter: 0,\n pendingLeadingNewline: frame.pendingLeadingNewline,\n request: frame.request,\n selectProps: frame.selectProps,\n segment,\n stack: frame.stack,\n treeParent: frame.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 frame.viewTransition === null ? null : { ...frame.viewTransition },\n };\n}\n\nfunction createSegment(\n index: number,\n boundary: SuspenseBoundary | null = null,\n): Segment {\n return {\n boundary,\n children: [],\n chunks: [],\n id: null,\n index,\n lastPushedText: false,\n parentFlushed: false,\n assetResources: [],\n status: \"pending\",\n textEmbedded: false,\n write: writeSegmentChunk,\n };\n}\n\nfunction writeRequestChunk(this: Request, chunk: string): void {\n if (chunk !== \"\" && this.leadingNewlineStack.length > 0) {\n this.leadingNewlineStack[this.leadingNewlineStack.length - 1] = true;\n }\n this.writeBuffer += chunk;\n}\n\nfunction disposeRequest(this: Request): void {\n this.cleanupAbortListener?.();\n this.dataStore.dispose();\n}\n\nfunction writeSegmentChunk(this: Segment, chunk: SegmentChunk): void {\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\nfunction performWork(request: Request): void {\n if (request.status === \"closed\") return;\n\n const tasks = request.pingedTasks;\n request.pingedTasks = [];\n\n for (const task of tasks) retryTask(task);\n\n flushCompletedQueues(request);\n}\n\nfunction retryTask(task: Task): void {\n const { frame } = task;\n if (frame.segment.status !== \"pending\") return;\n\n frame.segment.status = \"rendering\";\n\n try {\n renderChildren(task.node, frame, task.childIndexBase);\n completeSegmentText(frame.segment);\n frame.segment.status = \"completed\";\n detachTask(task);\n settleTask(task, \"completed\");\n } catch (error) {\n detachTask(task);\n frame.segment.status = \"completed\";\n settleTask(task, \"errored\", error);\n }\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 frame.idPathString ??= formatIdPath(frame.idPath);\n const id = `${frame.request.identifierPrefix}fig-${frame.idPathString}-${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: NormalizedChild | number, frame: RenderFrame): void {\n if (typeof node === \"string\" || typeof node === \"number\") {\n const text = String(node);\n if (frame.request.documentHasHead === false) {\n if (text.trim() !== \"\") throw invalidDocumentShellError();\n }\n if (__DEV__ && frame.hostNamespace === \"html\") {\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 // 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 if (consumePendingLeadingNewline(frame)) {\n frame.segment.write({ value: escapeText(text) });\n } else {\n writeText(text, frame.segment);\n }\n frame.segment.lastPushedText = true;\n }\n return;\n }\n\n if (isPortal(node)) return;\n\n if (isValidElement(node)) {\n renderElement(node, frame);\n return;\n }\n\n if (isThenable(node)) {\n renderChildren(readThenable(node), frame);\n return;\n }\n\n throw invalidChildError(node);\n}\n\nfunction renderChildren(\n node: FigNode,\n frame: RenderFrame,\n indexBase = 0,\n): void {\n if (Array.isArray(node)) {\n const children = collectChildren(node);\n for (let index = 0; index < children.length; index += 1) {\n renderChildAtIndex(children[index], frame, indexBase + index);\n }\n return;\n }\n if (\n node === null ||\n node === undefined ||\n typeof node === \"boolean\" ||\n node === \"\"\n ) {\n return;\n }\n renderChildAtIndex(node, frame, indexBase);\n}\n\nfunction renderChildAtIndex(\n child: NormalizedChild | number,\n frame: RenderFrame,\n index: number,\n): void {\n const previousIdPathString = frame.idPathString;\n frame.idPath.push(index);\n frame.idPathString = null;\n\n try {\n renderNode(child, frame);\n } catch (error) {\n // A retry task stores the parent path plus this child index, so fork its\n // scope only after restoring the parent path.\n frame.idPath.pop();\n frame.idPathString = previousIdPathString;\n if (isThenable(error)) {\n spawnSuspendedTask(frame, child, error, index);\n return;\n }\n throw error;\n }\n\n frame.idPath.pop();\n frame.idPathString = previousIdPathString;\n}\n\nfunction formatIdPath(path: readonly number[]): string {\n let value = \"\";\n for (let index = 0; index < path.length; index += 1) {\n if (index > 0) value += \"-\";\n value += path[index].toString(32);\n }\n return value;\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 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)) return [\"Context.Provider\", \"context-provider\"];\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 name = type.id.slice(type.id.lastIndexOf(\"#\") + 1);\n return [name || \"ClientReference\", \"client-reference\"];\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, 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: ComponentType,\n props: Props,\n frame: RenderFrame,\n): void {\n frame.dispatcher ??= createServerDispatcher(frame);\n const previousDispatcher = setCurrentDispatcher(frame.dispatcher);\n const previousDataStore = setCurrentDataStore(frame.request.dataStore);\n const previousStack = frame.stack;\n const previousLocalIdCounter = frame.localIdCounter;\n if (__DEV__ || frame.request.onError !== undefined) {\n frame.stack = { name: type.name || \"Anonymous\", parent: previousStack };\n }\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, 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 if (Array.isArray(value)) {\n for (const resource of value) renderAssetResource(resource, frame);\n } else {\n renderAssetResource(value, frame);\n }\n}\n\nfunction renderAssetResource(resource: unknown, frame: RenderFrame): void {\n if (!isFigAssetResource(resource)) {\n throw new Error(\"The assets prop must contain Fig asset resources.\");\n }\n\n try {\n frame.request.assetRegistry.register(resource);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n }\n\n frame.segment.assetResources.push(resource);\n}\n\nfunction renderAutomaticImagePreload(\n resource: PreloadResource,\n frame: RenderFrame,\n): void {\n try {\n frame.request.assetRegistry.registerAutomaticImage(resource);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n }\n frame.segment.assetResources.push(resource);\n}\n\nfunction renderSuspense(props: Props, frame: RenderFrame): void {\n consumePendingLeadingNewline(frame);\n const contentSegment = createSegment(0);\n const boundary: SuspenseBoundary = {\n activityId: frame.hiddenActivityId,\n completedSegments: [],\n contentSegment,\n error: null,\n fallbackSegment: null,\n fallbackTasks: new Set(),\n id: null,\n metadataVisible: false,\n parentFlushed: false,\n pendingTasks: 0,\n status: \"pending\",\n };\n const parentSegment = frame.segment;\n const boundarySegment = createSegment(parentSegment.chunks.length, boundary);\n boundary.fallbackSegment = boundarySegment;\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 = forkFrame(frame, contentSegment, boundary);\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: renderChildAtIndex 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 advanceViewTransitionWatermark(frame, contentFrame);\n\n if (boundary.status === \"completed\") return;\n\n const fallbackFrame = forkFrame(\n frame,\n boundarySegment,\n frame.boundary,\n boundary.fallbackTasks,\n );\n\n try {\n renderChildren(props.fallback, fallbackFrame);\n boundarySegment.status = \"completed\";\n } catch (error) {\n if (boundary.pendingTasks > 0) {\n for (const task of boundary.fallbackTasks) {\n abortTask(task);\n }\n }\n throw error;\n } finally {\n advanceViewTransitionWatermark(frame, fallbackFrame);\n }\n}\n\nfunction advanceViewTransitionWatermark(\n parent: RenderFrame,\n branch: RenderFrame,\n): void {\n if (parent.viewTransition !== null && branch.viewTransition !== null) {\n parent.viewTransition.index = Math.max(\n parent.viewTransition.index,\n branch.viewTransition.index,\n );\n }\n}\n\nfunction renderViewTransition(\n props: ViewTransitionProps,\n frame: RenderFrame,\n): void {\n const previousViewTransition = frame.viewTransition;\n const className = props.default;\n frame.viewTransition = {\n className:\n className === undefined || className === \"auto\" || className === \"none\"\n ? null\n : className,\n index: 0,\n name:\n props.name === undefined || props.name === \"auto\"\n ? `fig-vt-${frame.request.nextViewTransitionId++}`\n : props.name,\n };\n\n try {\n renderChildren(props.children, frame);\n } finally {\n frame.viewTransition = previousViewTransition;\n }\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 const normalizedType = type.toLowerCase();\n const namespace =\n normalizedType === \"svg\"\n ? \"svg\"\n : normalizedType === \"math\"\n ? \"mathml\"\n : frame.hostNamespace;\n if (namespace === \"html\" && renderHostAsset(normalizedType, props, frame)) {\n return;\n }\n\n if (__DEV__ && namespace === \"html\") {\n validateInstanceNesting(type, frame.hostAncestors);\n }\n\n const isDocument = frame.request.documentHasHead !== null;\n const isDocumentHead = isDocument && type === \"head\";\n if (frame.request.documentHasHead === false) {\n if (type !== \"html\" && type !== \"head\") throw invalidDocumentShellError();\n }\n\n if (isDocument && type === \"html\") {\n frame.segment.write(\"<!doctype html>\");\n }\n if (isDocumentHead) frame.request.documentHasHead = true;\n\n const isVoid = namespace === \"html\" && 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 if (namespace === \"html\") {\n const imagePreload = imagePreloadFromHostProps(\n type,\n props,\n frame.imagePreloadsSuppressed,\n );\n if (imagePreload !== null) {\n renderAutomaticImagePreload(imagePreload, frame);\n }\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 (isDocumentHead) {\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 previousPendingLeadingNewline = frame.pendingLeadingNewline;\n const tracksLeadingNewline = type === \"pre\" || type === \"textarea\";\n frame.pendingLeadingNewline = tracksLeadingNewline;\n\n const formText = namespace === \"html\" ? formTextContent(type, props) : null;\n const staticContent = unsafeHTML ?? formText;\n if (staticContent !== null) {\n const content =\n consumePendingLeadingNewline(frame) && staticContent.startsWith(\"\\n\")\n ? `\\n${staticContent}`\n : staticContent;\n if (unsafeHTML === null) writeText(content, frame.segment);\n else frame.segment.write(content);\n frame.pendingLeadingNewline = previousPendingLeadingNewline;\n writeElementEnd(type, frame.segment);\n return;\n }\n\n const previousSelectProps = frame.selectProps;\n if (namespace === \"html\" && type === \"select\") frame.selectProps = props;\n const previousHostAncestors = frame.hostAncestors;\n const previousHostNamespace = frame.hostNamespace;\n const previousImagePreloadsSuppressed = frame.imagePreloadsSuppressed;\n const previousViewTransition = frame.viewTransition;\n if (viewTransition !== null) frame.viewTransition = null;\n if (__DEV__) {\n frame.hostAncestors = [type, ...previousHostAncestors];\n }\n frame.hostNamespace =\n namespace === \"svg\" && normalizedType === \"foreignobject\"\n ? \"html\"\n : namespace;\n frame.imagePreloadsSuppressed =\n previousImagePreloadsSuppressed ||\n (namespace === \"html\" && suppressesImagePreloads(type));\n if (tracksLeadingNewline) {\n frame.segment.chunks.push(leadingNewlineStartMarker);\n }\n\n try {\n // Suspensions are handled inside renderChildAtIndex (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.hostNamespace = previousHostNamespace;\n frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed;\n frame.viewTransition = previousViewTransition;\n frame.pendingLeadingNewline = previousPendingLeadingNewline;\n }\n if (tracksLeadingNewline) {\n frame.segment.chunks.push(leadingNewlineEndMarker);\n }\n if (isDocumentHead) frame.segment.write(documentHeadMarker);\n writeElementEnd(type, frame.segment);\n}\n\nfunction renderHostAsset(\n normalizedType: string,\n props: Props,\n frame: RenderFrame,\n): boolean {\n // Deliberately gate before assetResourceFromHostProps, which allocates a\n // prop accessor. These names mirror the core classifier; other tags dominate.\n if (normalizedType.length < 4 || normalizedType.length > 6) return false;\n switch (normalizedType) {\n case \"link\":\n case \"meta\":\n case \"script\":\n case \"title\":\n break;\n default:\n return false;\n }\n\n const resource = assetResourceFromHostProps(normalizedType, 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 // 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);\n segment.lastPushedText = frame.segment.lastPushedText;\n segment.textEmbedded = true;\n frame.segment.lastPushedText = false;\n frame.segment.children.push(segment);\n\n const task = createTask(node, forkFrame(frame, segment), childIndexBase);\n const ping = () => pingTask(task);\n thenable.then(ping, ping);\n}\n\nfunction pingTask(task: Task): void {\n const { request } = task.frame;\n if (request.status === \"closed\" || request.status === \"aborting\") return;\n const shouldSchedule = request.pingedTasks.length === 0;\n request.pingedTasks.push(task);\n // An empty queue has no scheduled drain. Many thenables settling in one\n // tick append behind the first and share its microtask.\n if (shouldSchedule) queueMicrotask(() => performWork(request));\n}\n\nfunction settleTask(\n task: Task,\n outcome: \"aborted\" | \"completed\" | \"errored\",\n error?: unknown,\n): void {\n const { boundary, request, segment, stack } = task.frame;\n if (boundary === null) {\n request.pendingRootTasks -= 1;\n if (outcome === \"errored\") {\n fatalError(request, error);\n return;\n }\n if (request.pendingRootTasks === 0) finishRootShell(request);\n } else {\n boundary.pendingTasks -= 1;\n\n if (outcome === \"errored\") {\n markBoundaryClientRendered(request, boundary, error, stack);\n } else if (outcome === \"completed\" && segment.parentFlushed) {\n boundary.completedSegments.push(segment);\n }\n\n if (outcome !== \"errored\") {\n const boundaryCompleted = completeBoundaryIfReady(request, boundary);\n if (\n outcome === \"completed\" &&\n !boundaryCompleted &&\n boundary.parentFlushed\n ) {\n request.partialBoundaries.add(boundary);\n }\n }\n }\n\n if (request.abortableTasks.size === 0) request.allReady.resolve(undefined);\n}\n\nfunction detachTask(task: Task): boolean {\n task.frame.fallbackTasks?.delete(task);\n return task.frame.request.abortableTasks.delete(task);\n}\n\nfunction abortTask(task: Task): void {\n if (!detachTask(task)) return;\n\n const { frame } = task;\n frame.segment.status = \"completed\";\n settleTask(task, \"aborted\");\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 for (const fallbackTask of boundary.fallbackTasks) {\n abortTask(fallbackTask);\n }\n if (boundary.parentFlushed) request.completedBoundaries.add(boundary);\n return true;\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 =\n payload ??\n serverErrorPayload(error, stackForError(error, stack), request.onError);\n }\n\n boundary.completedSegments.length = 0;\n request.completedBoundaries.delete(boundary);\n request.partialBoundaries.delete(boundary);\n\n for (const task of request.abortableTasks) {\n if (task.frame.boundary === boundary) abortTask(task);\n }\n\n for (const task of boundary.fallbackTasks) {\n abortTask(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 request.status = \"aborting\";\n const error = abortError(reason);\n request.abortReason = error;\n\n if (request.pendingRootTasks > 0) {\n fatalError(request, error);\n return;\n }\n\n request.dispose();\n for (const task of request.abortableTasks) {\n const { boundary, stack } = task.frame;\n if (boundary !== null) {\n markBoundaryClientRendered(request, boundary, error, stack, {});\n }\n }\n\n request.abortableTasks.clear();\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 request.status = \"closed\";\n request.dispose();\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.documentHasHead === false) {\n fatalError(request, invalidDocumentShellError());\n return;\n }\n\n if (!request.prerender) sealHead(request);\n request.shellReady.resolve(undefined);\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 createRuntimeName(identifierPrefix: string): 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 consumePendingLeadingNewline(frame: RenderFrame): boolean {\n const pending = frame.pendingLeadingNewline;\n frame.pendingLeadingNewline = false;\n return pending;\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 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.abortReason);\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 {\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 {\n getHead: _getHead,\n headReady: _headReady,\n ...result\n } = createServerRenderRequest(node, options, {\n document: true,\n });\n return result;\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 = options.document === true;\n const result = createServerRenderRequest(node, options, {\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 ServerDocumentRenderResult,\n ServerErrorInfo,\n ServerErrorPayload,\n ServerFragmentRenderResult,\n ServerPreloadHeaderOptions,\n ServerPreloadHeaderResource,\n ServerPrerenderOptions,\n ServerPrerenderResult,\n ServerRenderOptions,\n} from \"./types.ts\";\n"],"mappings":";;;;;AAeA,MAAM,+BAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;C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