@bgub/fig-server 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -160,8 +160,10 @@ same protection.
160
160
  ## Data Resources
161
161
 
162
162
  Server render requests have their own data-resource store by default. Reads
163
- through `@bgub/fig` dedupe by key within the request and fulfilled entries are
164
- available through `result.getData()`:
163
+ through `@bgub/fig` dedupe by key within the request. Data read inside a
164
+ Suspense boundary streams ahead of that boundary's reveal, and `hydrateRoot`
165
+ picks it up. Data the shell read is returned by `result.takeData()`; place it
166
+ in the document before the client bootstrap:
165
167
 
166
168
  ```tsx
167
169
  import { dataResource, readData } from "@bgub/fig";
@@ -173,14 +175,15 @@ const userResource = dataResource<[string], { name: string }>({
173
175
  });
174
176
 
175
177
  function Profile({ id }: { id: string }) {
178
+ const data = readDataStore();
176
179
  const user = readData(userResource, id);
177
180
  return <h1>{user.name}</h1>;
178
181
  }
179
182
 
180
183
  const result = renderToStream(<Profile id="one" />);
181
- await result.allReady;
184
+ await result.shellReady;
182
185
 
183
- const initialData = result.getData();
186
+ const initialData = result.takeData();
184
187
  ```
185
188
 
186
189
  Adapters that run loaders before rendering can create the store themselves.
@@ -201,7 +204,7 @@ One renderer may adopt a store, and that renderer owns its lifetime.
201
204
 
202
205
  Pass `initialData` to `createRoot(...)` or `hydrateRoot(...)` on the client to
203
206
  hydrate those values by key. Client imports can use a loader-less resource with
204
- the same key; if no client loader exists, `refreshData(...)` reports
207
+ the same key; if no client loader exists, `data.refreshData(...)` reports
205
208
  `unsupported` and a framework/payload refresh path should revalidate the key.
206
209
 
207
210
  ## Resources
@@ -306,7 +309,7 @@ framework document transports are internal implementation details.
306
309
 
307
310
  The public options cover error sanitization (`onError`), bundler-provided
308
311
  Payload component assets (`componentAssets`), manifest-provided client assets
309
- (`clientReferenceAssets`), data-store partitioning, byte backpressure
312
+ (`clientReferenceAssets`), byte backpressure
310
313
  (`highWaterMark`), and cancellation (`signal`).
311
314
 
312
315
  The server renderer supports function components, fragments, context providers,
@@ -89,8 +89,8 @@ function createStaticDispatcher(options) {
89
89
  readContext(context) {
90
90
  return readContextValue(options.contextValues, context);
91
91
  },
92
+ readBrowser: options.readBrowser,
92
93
  readData: options.readData,
93
- preloadData: options.preloadData,
94
94
  readPromise: options.readPromise
95
95
  };
96
96
  }
@@ -155,6 +155,6 @@ function imageFetchpriority(value) {
155
155
  return value === "high" || value === "auto" ? value : void 0;
156
156
  }
157
157
  //#endregion
158
- export { createStaticDispatcher as a, nonceAttribute as c, streamFlowBlocked as d, streamHighWaterMark as f, cloneContextValues as i, noop as l, suppressesImagePreloads as n, deferred as o, withContextValue as p, STREAMED_METADATA_ATTRIBUTE as r, noLane as s, imagePreloadFromHostProps as t, serverErrorPayload as u };
158
+ export { componentStack as a, noLane as c, serverErrorPayload as d, streamFlowBlocked as f, cloneContextValues as i, nonceAttribute as l, withContextValue as m, suppressesImagePreloads as n, createStaticDispatcher as o, streamHighWaterMark as p, STREAMED_METADATA_ATTRIBUTE as r, deferred as s, imagePreloadFromHostProps as t, noop as u };
159
159
 
160
- //# sourceMappingURL=image-preloads-x38gXLap.js.map
160
+ //# sourceMappingURL=image-preloads-DwTY3DIk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-preloads-DwTY3DIk.js","names":[],"sources":["../src/shared.ts","../src/image-preloads.ts"],"sourcesContent":["import type {\n ActionStateAction,\n ActionStateRunner,\n DependencyList,\n ExternalStoreSubscribe,\n FigContext,\n StateSetter,\n StartTransition,\n TransitionCallback,\n} from \"@bgub/fig\";\nimport type {\n BrowserRenderReason,\n DataResource,\n RenderDispatcher,\n StableEventCallerArgs,\n} from \"@bgub/fig/internal\";\nimport { runTransitionScope } from \"@bgub/fig/internal\";\nimport { escapeAttribute } from \"./escaping.ts\";\nimport type { ServerErrorPayload, ServerRenderOptions } from \"./types.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\n\nexport type ContextValues = Map<FigContext<unknown>, unknown[]>;\n\nexport const STREAMED_METADATA_ATTRIBUTE = \"data-fig-streamed-metadata\";\n\nexport function noLane(): null {\n return null;\n}\n\nexport function noop(): void {}\n\nexport interface StackFrame {\n name: string;\n parent: StackFrame | null;\n}\n\ninterface StaticDispatcherOptions {\n contextValues: ContextValues;\n externalStoreError: string;\n readBrowser(this: void, reason?: BrowserRenderReason): void;\n readData<TArgs extends unknown[], TValue>(\n this: void,\n resource: DataResource<TArgs, TValue>,\n args: TArgs,\n ): TValue;\n readPromise<T>(this: void, promise: PromiseLike<T>): T;\n updateError: string;\n useId(this: void): string;\n}\n\nexport function withContextValue<T>(\n values: ContextValues,\n context: FigContext<unknown>,\n value: unknown,\n callback: () => T,\n): T {\n let stack = values.get(context);\n if (stack === undefined) {\n stack = [];\n values.set(context, stack);\n }\n stack.push(value);\n\n try {\n return callback();\n } finally {\n stack.pop();\n }\n}\n\nfunction readContextValue<T>(values: ContextValues, context: FigContext<T>): T {\n const stack = values.get(context as FigContext<unknown>);\n if (stack !== undefined && stack.length > 0) {\n return stack[stack.length - 1] as T;\n }\n\n return context.defaultValue;\n}\n\nexport interface Deferred<T> {\n promise: Promise<T>;\n reject: (reason: unknown) => void;\n resolve: (value: T) => void;\n}\n\nexport function deferred<T>(): Deferred<T> {\n let resolve: Deferred<T>[\"resolve\"] | null = null;\n let reject: Deferred<T>[\"reject\"] | null = null;\n const promise = new Promise<T>((innerResolve, innerReject) => {\n resolve = innerResolve;\n reject = innerReject;\n });\n if (resolve === null || reject === null) {\n throw new Error(\"Promise executor did not initialize its deferred.\");\n }\n return { promise, reject, resolve };\n}\n\nexport function cloneContextValues(values: ContextValues): ContextValues {\n const clone: ContextValues = new Map();\n for (const [context, stack] of values) clone.set(context, [...stack]);\n return clone;\n}\n\n// Encoded bytes a render result stream's internal queue holds before flushing\n// pauses (resumed by consumer pulls). Shared by the HTML and payload\n// renderers. Large enough that a healthy consumer never blocks a flush; small\n// enough to bound per-connection buffering when the consumer stalls.\n// Rendering itself never pauses — only writing to the stream does.\nconst DEFAULT_STREAM_HIGH_WATER_MARK = 65536;\n\n// 0 would deadlock: desiredSize never goes positive, and read requests alone\n// do not make it so. 1 byte is the honest pure-pull minimum.\nexport function streamHighWaterMark(option: number | undefined): number {\n return Math.max(1, option ?? DEFAULT_STREAM_HIGH_WATER_MARK);\n}\n\n// Blocked means the stream's internal queue is at or past its high-water\n// mark; completed work then waits un-enqueued until the consumer pulls.\n// desiredSize is null on an errored stream — never blocked, because fatal\n// paths close the request before any further writes.\nexport function streamFlowBlocked(\n controller: ReadableStreamDefaultController<Uint8Array> | null,\n): boolean {\n const desiredSize = controller?.desiredSize;\n return typeof desiredSize === \"number\" && desiredSize <= 0;\n}\n\nexport function createStaticDispatcher(\n options: StaticDispatcherOptions,\n): RenderDispatcher {\n const rejectUpdate = (..._args: unknown[]): never => {\n throw new Error(options.updateError);\n };\n\n return {\n useState<S>(initialState: S | (() => S)): [S, StateSetter<S>] {\n const value =\n typeof initialState === \"function\"\n ? (initialState as () => S)()\n : initialState;\n return [value, rejectUpdate];\n },\n useActionState<S, Args extends unknown[]>(\n _action: ActionStateAction<S, Args>,\n initialState: S,\n ): [S, ActionStateRunner<Args>, boolean] {\n return [initialState, rejectUpdate, false];\n },\n useId: options.useId,\n useDeferredValue<T>(\n value: T,\n _initialValue: T | undefined,\n _hasInitialValue: boolean,\n ): T {\n return value;\n },\n useMemo<T>(calculate: () => T, _deps: DependencyList): T {\n return calculate();\n },\n useTransition(): [boolean, StartTransition] {\n return [false, startServerTransition];\n },\n useReactive: noop,\n useBeforePaint: noop,\n useBeforeLayout: noop,\n useSyncExternalStore<T>(\n _subscribe: ExternalStoreSubscribe,\n _getSnapshot: () => T,\n getServerSnapshot?: () => T,\n ): T {\n if (getServerSnapshot === undefined) {\n throw new Error(options.externalStoreError);\n }\n\n return getServerSnapshot();\n },\n useStableEvent<Args extends unknown[], Result>(\n _handler: (...args: Args) => Result,\n ): (...args: StableEventCallerArgs<Args>) => Result {\n return rejectStableEventCall;\n },\n readContext<T>(context: FigContext<T>): T {\n return readContextValue(options.contextValues, context);\n },\n readBrowser: options.readBrowser,\n readData: options.readData,\n readPromise: options.readPromise,\n };\n}\n\n// There is no scheduling priority on the server, but callback lifetimes and\n// explicit update scopes obey the same contract as client transitions.\nfunction startServerTransition(callback: TransitionCallback): void {\n void runTransitionScope(callback, (run) => run());\n}\n\nfunction rejectStableEventCall<Args extends unknown[], Result>(\n ..._args: StableEventCallerArgs<Args>\n): Result {\n throw new Error(\"Stable events cannot be called during server render.\");\n}\n\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport function componentStack(stack: StackFrame | null): string {\n const frames: string[] = [];\n for (let frame = stack; frame !== null; frame = frame.parent) {\n frames.push(` at ${frame.name}`);\n }\n return frames.length === 0 ? \"\" : `\\n${frames.join(\"\\n\")}`;\n}\n\nexport function serverErrorPayload(\n error: unknown,\n stack: StackFrame | null,\n onError: ServerRenderOptions[\"onError\"],\n): ServerErrorPayload {\n if (onError === undefined) {\n return __DEV__ ? { message: errorMessage(error) } : {};\n }\n try {\n return onError(error, { componentStack: componentStack(stack) }) ?? {};\n } catch {\n return {};\n }\n}\n\nexport function nonceAttribute(nonce: string | undefined): string {\n return nonce === undefined ? \"\" : ` nonce=\"${escapeAttribute(nonce)}\"`;\n}\n","import type { PreloadResource, Props } from \"@bgub/fig\";\n\nexport function imagePreloadFromHostProps(\n type: string,\n props: Props,\n suppressed: boolean,\n): PreloadResource | null {\n if (suppressed || type.toLowerCase() !== \"img\") return null;\n if (props.loading === \"lazy\" || props.fetchpriority === \"low\") return null;\n\n const src = stringProp(props.src);\n const srcset = stringProp(props.srcset);\n if (\n (props.src != null && typeof props.src !== \"string\") ||\n (props.srcset != null && typeof props.srcset !== \"string\") ||\n (!src && !srcset) ||\n isDataUrl(src) ||\n isDataUrl(srcset)\n ) {\n return null;\n }\n\n return {\n as: \"image\",\n crossorigin: imageCrossorigin(props.crossorigin),\n fetchpriority: imageFetchpriority(props.fetchpriority),\n href: src || undefined,\n imagesizes: srcset ? stringProp(props.sizes) : undefined,\n imagesrcset: srcset || undefined,\n kind: \"preload\",\n referrerpolicy: stringProp(props.referrerpolicy),\n type: stringProp(props.type),\n };\n}\n\nexport function suppressesImagePreloads(type: string): boolean {\n const normalizedType = type.toLowerCase();\n return normalizedType === \"picture\" || normalizedType === \"noscript\";\n}\n\nfunction stringProp(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction isDataUrl(value: string | undefined): boolean {\n return value?.slice(0, 5).toLowerCase() === \"data:\";\n}\n\nfunction imageCrossorigin(value: unknown): PreloadResource[\"crossorigin\"] {\n if (typeof value !== \"string\") return undefined;\n if (value === \"anonymous\" || value === \"use-credentials\" || value === \"\") {\n return value;\n }\n return \"\";\n}\n\nfunction imageFetchpriority(value: unknown): PreloadResource[\"fetchpriority\"] {\n return value === \"high\" || value === \"auto\" ? value : undefined;\n}\n"],"mappings":";;;AA0BA,MAAa,8BAA8B;AAE3C,SAAgB,SAAe;CAC7B,OAAO;AACT;AAEA,SAAgB,OAAa,CAAC;AAqB9B,SAAgB,iBACd,QACA,SACA,OACA,UACG;CACH,IAAI,QAAQ,OAAO,IAAI,OAAO;CAC9B,IAAI,UAAU,KAAA,GAAW;EACvB,QAAQ,CAAC;EACT,OAAO,IAAI,SAAS,KAAK;CAC3B;CACA,MAAM,KAAK,KAAK;CAEhB,IAAI;EACF,OAAO,SAAS;CAClB,UAAU;EACR,MAAM,IAAI;CACZ;AACF;AAEA,SAAS,iBAAoB,QAAuB,SAA2B;CAC7E,MAAM,QAAQ,OAAO,IAAI,OAA8B;CACvD,IAAI,UAAU,KAAA,KAAa,MAAM,SAAS,GACxC,OAAO,MAAM,MAAM,SAAS;CAG9B,OAAO,QAAQ;AACjB;AAQA,SAAgB,WAA2B;CACzC,IAAI,UAAyC;CAC7C,IAAI,SAAuC;CAC3C,MAAM,UAAU,IAAI,SAAY,cAAc,gBAAgB;EAC5D,UAAU;EACV,SAAS;CACX,CAAC;CACD,IAAI,YAAY,QAAQ,WAAW,MACjC,MAAM,IAAI,MAAM,mDAAmD;CAErE,OAAO;EAAE;EAAS;EAAQ;CAAQ;AACpC;AAEA,SAAgB,mBAAmB,QAAsC;CACvE,MAAM,wBAAuB,IAAI,IAAI;CACrC,KAAK,MAAM,CAAC,SAAS,UAAU,QAAQ,MAAM,IAAI,SAAS,CAAC,GAAG,KAAK,CAAC;CACpE,OAAO;AACT;AAOA,MAAM,iCAAiC;AAIvC,SAAgB,oBAAoB,QAAoC;CACtE,OAAO,KAAK,IAAI,GAAG,UAAU,8BAA8B;AAC7D;AAMA,SAAgB,kBACd,YACS;CACT,MAAM,cAAc,YAAY;CAChC,OAAO,OAAO,gBAAgB,YAAY,eAAe;AAC3D;AAEA,SAAgB,uBACd,SACkB;CAClB,MAAM,gBAAgB,GAAG,UAA4B;EACnD,MAAM,IAAI,MAAM,QAAQ,WAAW;CACrC;CAEA,OAAO;EACL,SAAY,cAAkD;GAK5D,OAAO,CAHL,OAAO,iBAAiB,aACnB,aAAyB,IAC1B,cACS,YAAY;EAC7B;EACA,eACE,SACA,cACuC;GACvC,OAAO;IAAC;IAAc;IAAc;GAAK;EAC3C;EACA,OAAO,QAAQ;EACf,iBACE,OACA,eACA,kBACG;GACH,OAAO;EACT;EACA,QAAW,WAAoB,OAA0B;GACvD,OAAO,UAAU;EACnB;EACA,gBAA4C;GAC1C,OAAO,CAAC,OAAO,qBAAqB;EACtC;EACA,aAAa;EACb,gBAAgB;EAChB,iBAAiB;EACjB,qBACE,YACA,cACA,mBACG;GACH,IAAI,sBAAsB,KAAA,GACxB,MAAM,IAAI,MAAM,QAAQ,kBAAkB;GAG5C,OAAO,kBAAkB;EAC3B;EACA,eACE,UACkD;GAClD,OAAO;EACT;EACA,YAAe,SAA2B;GACxC,OAAO,iBAAiB,QAAQ,eAAe,OAAO;EACxD;EACA,aAAa,QAAQ;EACrB,UAAU,QAAQ;EAClB,aAAa,QAAQ;CACvB;AACF;AAIA,SAAS,sBAAsB,UAAoC;CACjE,mBAAwB,WAAW,QAAQ,IAAI,CAAC;AAClD;AAEA,SAAS,sBACP,GAAG,OACK;CACR,MAAM,IAAI,MAAM,sDAAsD;AACxE;AAMA,SAAgB,eAAe,OAAkC;CAC/D,MAAM,SAAmB,CAAC;CAC1B,KAAK,IAAI,QAAQ,OAAO,UAAU,MAAM,QAAQ,MAAM,QACpD,OAAO,KAAK,UAAU,MAAM,MAAM;CAEpC,OAAO,OAAO,WAAW,IAAI,KAAK,KAAK,OAAO,KAAK,IAAI;AACzD;AAEA,SAAgB,mBACd,OACA,OACA,SACoB;CACpB,IAAI,YAAY,KAAA,GACd,OAAoD,CAAC;CAEvD,IAAI;EACF,OAAO,QAAQ,OAAO,EAAE,gBAAgB,eAAe,KAAK,EAAE,CAAC,KAAK,CAAC;CACvE,QAAQ;EACN,OAAO,CAAC;CACV;AACF;AAEA,SAAgB,eAAe,OAAmC;CAChE,OAAO,UAAU,KAAA,IAAY,KAAK,WAAW,gBAAgB,KAAK,EAAE;AACtE;;;ACzOA,SAAgB,0BACd,MACA,OACA,YACwB;CACxB,IAAI,cAAc,KAAK,YAAY,MAAM,OAAO,OAAO;CACvD,IAAI,MAAM,YAAY,UAAU,MAAM,kBAAkB,OAAO,OAAO;CAEtE,MAAM,MAAM,WAAW,MAAM,GAAG;CAChC,MAAM,SAAS,WAAW,MAAM,MAAM;CACtC,IACG,MAAM,OAAO,QAAQ,OAAO,MAAM,QAAQ,YAC1C,MAAM,UAAU,QAAQ,OAAO,MAAM,WAAW,YAChD,CAAC,OAAO,CAAC,UACV,UAAU,GAAG,KACb,UAAU,MAAM,GAEhB,OAAO;CAGT,OAAO;EACL,IAAI;EACJ,aAAa,iBAAiB,MAAM,WAAW;EAC/C,eAAe,mBAAmB,MAAM,aAAa;EACrD,MAAM,OAAO,KAAA;EACb,YAAY,SAAS,WAAW,MAAM,KAAK,IAAI,KAAA;EAC/C,aAAa,UAAU,KAAA;EACvB,MAAM;EACN,gBAAgB,WAAW,MAAM,cAAc;EAC/C,MAAM,WAAW,MAAM,IAAI;CAC7B;AACF;AAEA,SAAgB,wBAAwB,MAAuB;CAC7D,MAAM,iBAAiB,KAAK,YAAY;CACxC,OAAO,mBAAmB,aAAa,mBAAmB;AAC5D;AAEA,SAAS,WAAW,OAAoC;CACtD,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;AAEA,SAAS,UAAU,OAAoC;CACrD,OAAO,OAAO,MAAM,GAAG,CAAC,CAAC,CAAC,YAAY,MAAM;AAC9C;AAEA,SAAS,iBAAiB,OAAgD;CACxE,IAAI,OAAO,UAAU,UAAU,OAAO,KAAA;CACtC,IAAI,UAAU,eAAe,UAAU,qBAAqB,UAAU,IACpE,OAAO;CAET,OAAO;AACT;AAEA,SAAS,mBAAmB,OAAkD;CAC5E,OAAO,UAAU,UAAU,UAAU,SAAS,QAAQ,KAAA;AACxD"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ServerPreloadHeaderOptions, c as ServerPrerenderResult, d as RenderTreeKind, f as RenderTreeNode, i as ServerFragmentRenderResult, l as ServerRenderOptions, n as ServerErrorInfo, o as ServerPreloadHeaderResource, p as createRenderTreeCollector, r as ServerErrorPayload, s as ServerPrerenderOptions, t as ServerDocumentRenderResult, u as RenderTreeCollector } from "./types-CsnQA5rq.js";
1
+ import { a as ServerPreloadHeaderOptions, c as ServerPrerenderResult, d as RenderTreeCollector, f as RenderTreeKind, i as ServerFragmentRenderResult, l as ServerRenderOptions, m as createRenderTreeCollector, n as ServerErrorInfo, o as ServerPreloadHeaderResource, p as RenderTreeNode, r as ServerErrorPayload, s as ServerPrerenderOptions, t as ServerDocumentRenderResult, u as ServerStreamDataOptions } from "./types-Xrr1OZyd.js";
2
2
  import { FigNode } from "@bgub/fig";
3
3
  //#region src/index.d.ts
4
4
  /** Renders to stream. */
@@ -22,4 +22,4 @@ declare function renderToDocumentHtml(node: FigNode, options?: ServerRenderOptio
22
22
  */
23
23
  declare function prerender(node: FigNode, options?: ServerPrerenderOptions): Promise<ServerPrerenderResult>;
24
24
  //#endregion
25
- export { type RenderTreeCollector, type RenderTreeKind, type RenderTreeNode, type ServerDocumentRenderResult, type ServerErrorInfo, type ServerErrorPayload, type ServerFragmentRenderResult, type ServerPreloadHeaderOptions, type ServerPreloadHeaderResource, type ServerPrerenderOptions, type ServerPrerenderResult, type ServerRenderOptions, createRenderTreeCollector, prerender, renderToDocumentHtml, renderToDocumentStream, renderToHtml, renderToStream };
25
+ export { type RenderTreeCollector, type RenderTreeKind, type RenderTreeNode, type ServerDocumentRenderResult, type ServerErrorInfo, type ServerErrorPayload, type ServerFragmentRenderResult, type ServerPreloadHeaderOptions, type ServerPreloadHeaderResource, type ServerPrerenderOptions, type ServerPrerenderResult, type ServerRenderOptions, type ServerStreamDataOptions, createRenderTreeCollector, prerender, renderToDocumentHtml, renderToDocumentStream, renderToHtml, renderToStream };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { i as escapeText, n as escapeScriptJson, t as escapeAttribute } from "./escaping-2fHOwhEM.js";
2
- import { a as createStaticDispatcher, c as nonceAttribute, d as streamFlowBlocked, f as streamHighWaterMark, i as cloneContextValues, l as noop, n as suppressesImagePreloads, o as deferred, p as withContextValue, r as STREAMED_METADATA_ATTRIBUTE, s as noLane, t as imagePreloadFromHostProps, u as serverErrorPayload } from "./image-preloads-x38gXLap.js";
2
+ import { a as componentStack, c as noLane, d as serverErrorPayload, f as streamFlowBlocked, i as cloneContextValues, l as nonceAttribute, m as withContextValue, n as suppressesImagePreloads, o as createStaticDispatcher, p as streamHighWaterMark, r as STREAMED_METADATA_ATTRIBUTE, s as deferred, t as imagePreloadFromHostProps, u as noop } from "./image-preloads-DwTY3DIk.js";
3
3
  import { Fragment, createElement, isValidElement } from "@bgub/fig";
4
- import { ACTIVITY_TEMPLATE_ATTRIBUTE, EARLY_EVENT_HANDLER_PROPERTY, EARLY_EVENT_QUEUE_PROPERTY, HYDRATION_SKIP_ATTRIBUTE, REPLAYABLE_EVENT_TYPES, SUSPENSE_CLIENT_MARKER, SUSPENSE_COMPLETED_MARKER, SUSPENSE_END_MARKER, SUSPENSE_MARKER_PREFIX, SUSPENSE_PENDING_PREFIX, TEXT_SEPARATOR_DATA, VIEW_TRANSITION_CLASS_ATTRIBUTE, VIEW_TRANSITION_NAME_ATTRIBUTE, VIEW_TRANSITION_PENDING_PROPERTY, VIEW_TRANSITION_TIMEOUT_MS, assetResourceFromHostProps, assetResourceHostProps, assetResourceKey, attachDataStore, collectChildren, createRendererDataStore, invalidChildError, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPortal, isSuspense, isThenable, isViewTransition, readThenable, setCurrentDataStore, setCurrentDispatcher } from "@bgub/fig/internal";
4
+ import { ACTIVITY_TEMPLATE_ATTRIBUTE, EARLY_EVENT_HANDLER_PROPERTY, EARLY_EVENT_QUEUE_PROPERTY, HYDRATION_SKIP_ATTRIBUTE, REPLAYABLE_EVENT_TYPES, STREAMED_DATA_PROPERTY, SUSPENSE_BROWSER_MARKER, SUSPENSE_CLIENT_MARKER, SUSPENSE_COMPLETED_MARKER, SUSPENSE_END_MARKER, SUSPENSE_MARKER_PREFIX, SUSPENSE_PENDING_PREFIX, TEXT_SEPARATOR_DATA, VIEW_TRANSITION_CLASS_ATTRIBUTE, VIEW_TRANSITION_NAME_ATTRIBUTE, VIEW_TRANSITION_PENDING_PROPERTY, VIEW_TRANSITION_TIMEOUT_MS, assetResourceFromHostProps, assetResourceHostProps, assetResourceKey, attachDataStore, collectChildren, createRendererDataStore, decodePayloadDataEntries, encodePayloadDataEntries, invalidChildError, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPortal, isSuspense, isThenable, isViewTransition, normalizeDataResourceKey, readThenable, setCurrentDataStore, setCurrentDispatcher } from "@bgub/fig/internal";
5
5
  //#region src/html.ts
6
6
  const voidElements = /* @__PURE__ */ new Set([
7
7
  "area",
@@ -183,7 +183,7 @@ function snapshotPreloadHeaderResources(resources, isEarlyImage) {
183
183
  if (!isServerPreloadHeaderResource(resource)) continue;
184
184
  const snapshot = { ...resource };
185
185
  if (resource.kind === "preconnect") preconnects.push(snapshot);
186
- else if (resource.kind === "font" || resource.kind === "preload" && (resource.as === "font" || resource.as === "image" && (resource.fetchpriority === "high" || isEarlyImage?.(resource) === true))) criticalPreloads.push(snapshot);
186
+ else if (resource.kind === "preload" && (resource.as === "font" || resource.as === "image" && (resource.fetchpriority === "high" || isEarlyImage?.(resource) === true))) criticalPreloads.push(snapshot);
187
187
  else if (resource.kind === "stylesheet") stylesheets.push(snapshot);
188
188
  else remaining.push(snapshot);
189
189
  }
@@ -233,13 +233,6 @@ function preloadHeaderValue(resource) {
233
233
  ["crossorigin", resource.crossorigin],
234
234
  ["fetchpriority", resource.fetchpriority]
235
235
  ]);
236
- case "font": return serializeLink(resource.href, [
237
- ["rel", "preload"],
238
- ["as", "font"],
239
- ["crossorigin", resource.crossorigin ?? "anonymous"],
240
- ["type", resource.type],
241
- ["fetchpriority", resource.fetchpriority]
242
- ]);
243
236
  case "preconnect": return serializeLink(resource.href, [["rel", "preconnect"], ["crossorigin", resource.crossorigin]]);
244
237
  }
245
238
  }
@@ -356,7 +349,7 @@ var AssetResourceRegistry = class {
356
349
  for (const resource of resources) {
357
350
  if (isMetadataResource(resource)) continue;
358
351
  if (resource.kind === "preconnect") preconnects.push(resource);
359
- else if (resource.kind === "font" || resource.kind === "preload" && (resource.as === "font" || resource.as === "image" && (resource.fetchpriority === "high" || this.isEarlyImage(resource)))) criticalPreloads.push(resource);
352
+ else if (resource.kind === "preload" && (resource.as === "font" || resource.as === "image" && (resource.fetchpriority === "high" || this.isEarlyImage(resource)))) criticalPreloads.push(resource);
360
353
  else if (resource.kind === "stylesheet") stylesheets.push(resource);
361
354
  else afterMetadata.push(resource);
362
355
  }
@@ -512,7 +505,6 @@ function assetSignature(resource) {
512
505
  return signature(resource.kind, imagesrcset === void 0 ? resource.href ?? "" : "", resource.as, resource.type ?? "", resource.crossorigin ?? "", resource.fetchpriority ?? "", imagesrcset ?? "", imagesrcset === void 0 ? "" : resource.imagesizes ?? "", resource.referrerpolicy ?? "");
513
506
  }
514
507
  case "modulepreload": return signature(resource.kind, resource.href, resource.crossorigin ?? "", resource.fetchpriority ?? "");
515
- case "font": return signature("preload", resource.href, "font", resource.type, resource.crossorigin ?? "anonymous", resource.fetchpriority ?? "", "", "", "");
516
508
  case "preconnect": return signature(resource.kind, resource.href, resource.crossorigin ?? "");
517
509
  case "script": return signature(resource.kind, resource.src, resource.module === true, resource.async !== false, resource.defer === true, resource.crossorigin ?? "");
518
510
  case "title": return signature(resource.kind, resource.value);
@@ -543,7 +535,7 @@ function signature(...values) {
543
535
  //#endregion
544
536
  //#region src/protocol.ts
545
537
  function buildServerRuntimeCode(runtimeName) {
546
- 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)}}`;
538
+ 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,()=>{if(!s.isConnected)return;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||!s.isConnected)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,a,r){this.y(document.getElementById(b),d,m,a,r)},y(b,d,m,a,r){for(let i of a||[])document.getElementById(i)?.remove();if(!b)return;let s=b.previousSibling;if(s&&s.nodeType===8){s.data=r?'${SUSPENSE_BROWSER_MARKER}':'${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,a,r){this.y(this.b(t,b),d,m,a,r)},d(p,r){((document.${STREAMED_DATA_PROPERTY}??={})[p]??=[]).push(r)}}`;
547
539
  }
548
540
  const RUNTIME_CODE_PREFIX = "globalThis[";
549
541
  const EMPTY_RUNTIME_REFERENCE = `${RUNTIME_CODE_PREFIX}${jsString("")}`;
@@ -613,6 +605,7 @@ function flushCompletedQueues(request) {
613
605
  sealHead(request);
614
606
  if (request.rootSegment.status !== "flushed") {
615
607
  flushSegment(request, request.rootSegment);
608
+ request.pendingDataKeys?.clear();
616
609
  flushWriteBuffer(request);
617
610
  }
618
611
  if (!drainBoundaryQueue(request, request.clientRenderedBoundaries, flushClientRenderedBoundary) && !drainBoundaryQueue(request, request.completedBoundaries, flushCompletedBoundary)) drainBoundaryQueue(request, request.partialBoundaries, flushPartialBoundary);
@@ -622,7 +615,12 @@ function flushCompletedQueues(request) {
622
615
  }
623
616
  if (request.abortableTasks.size === 0 && request.completedBoundaries.size === 0 && request.clientRenderedBoundaries.size === 0 && request.partialBoundaries.size === 0) {
624
617
  request.status = "closed";
625
- request.dispose();
618
+ try {
619
+ request.dispose();
620
+ } catch (error) {
621
+ request.controller.error(error);
622
+ return;
623
+ }
626
624
  request.controller.close();
627
625
  }
628
626
  }
@@ -653,6 +651,10 @@ function flushSubtree(request, segment) {
653
651
  }
654
652
  if (segment.status === "flushed") return;
655
653
  segment.status = "flushed";
654
+ if (segment.dataKeys !== null) {
655
+ for (const key of segment.dataKeys) request.pendingDataKeys?.add(key);
656
+ segment.dataKeys = null;
657
+ }
656
658
  if (request.documentHasHead === null || segment !== request.rootSegment) collectSegmentAssets(request, segment, null);
657
659
  let chunkIndex = 0;
658
660
  for (const child of segment.children) {
@@ -673,8 +675,9 @@ function flushSuspenseBoundary(request, segment, boundary) {
673
675
  segment.chunks.length = 0;
674
676
  return;
675
677
  }
676
- if (request.prerender && boundary.status === "client-rendered") {
677
- request.write(`<!--${SUSPENSE_CLIENT_MARKER}-->`);
678
+ if (request.prerender && (boundary.status === "browser-rendered" || boundary.status === "client-rendered")) {
679
+ const marker = boundary.status === "browser-rendered" ? SUSPENSE_BROWSER_MARKER : SUSPENSE_CLIENT_MARKER;
680
+ request.write(`<!--${marker}-->`);
678
681
  request.write(clientRenderedBoundaryPlaceholderMarkup(request, boundary));
679
682
  flushSubtree(request, segment);
680
683
  request.write(`<!--${SUSPENSE_END_MARKER}-->`);
@@ -686,7 +689,7 @@ function flushSuspenseBoundary(request, segment, boundary) {
686
689
  request.write(boundaryPlaceholderMarkup(request, boundaryIdValue));
687
690
  flushSubtree(request, segment);
688
691
  request.write(`<!--${SUSPENSE_END_MARKER}-->`);
689
- if (boundary.status === "client-rendered") request.clientRenderedBoundaries.add(boundary);
692
+ if (boundary.status === "browser-rendered" || boundary.status === "client-rendered") request.clientRenderedBoundaries.add(boundary);
690
693
  else if (boundary.completedSegments.length > 0) request.partialBoundaries.add(boundary);
691
694
  }
692
695
  function clientRenderedBoundaryPlaceholderMarkup(request, boundary) {
@@ -708,15 +711,18 @@ function flushBoundarySegment(request, boundary, segment) {
708
711
  let blockingIds = "";
709
712
  if (segment.status !== "flushed") {
710
713
  blockingIds = flushSegmentAssets(request, segment);
711
- request.write(segmentContainerStartMarkup(request, ensureSegmentId(request, segment)));
714
+ const id = ensureSegmentId(request, segment);
715
+ boundary.stagedSegmentIds.add(id);
716
+ request.write(segmentContainerStartMarkup(request, id));
712
717
  flushSegment(request, segment);
713
718
  request.write("</div>");
714
719
  }
715
- if (segment !== boundary.contentSegment) writeSegmentRevealScript(request, segment, blockingIds);
720
+ if (segment !== boundary.contentSegment) writeSegmentRevealScript(request, boundary, segment, blockingIds);
716
721
  }
717
- function writeSegmentRevealScript(request, segment, blockingIds) {
722
+ function writeSegmentRevealScript(request, boundary, segment, blockingIds) {
718
723
  const id = ensureSegmentId(request, segment);
719
724
  writeRuntime(request);
725
+ writeDataOperation(request, boundary);
720
726
  writeScript(request, withAssetGate(blockingIds, `${RUNTIME_REF}.s(${jsString(placeholderId(request, id))},${jsString(segmentId(request, id))})`));
721
727
  }
722
728
  function writeBoundaryRevealScript(request, boundary) {
@@ -724,9 +730,86 @@ function writeBoundaryRevealScript(request, boundary) {
724
730
  const metadata = switchBoundaryMetadata(request, boundary);
725
731
  const metadataArgument = metadata === null ? "" : `,${metadata}`;
726
732
  writeRuntime(request);
733
+ writeDataOperation(request, boundary);
727
734
  const boundaryRef = jsString(boundaryId(request, ensureBoundaryId(request, boundary)));
728
735
  const contentRef = jsString(segmentId(request, ensureSegmentId(request, boundary.contentSegment)));
729
736
  writeScript(request, withAssetGate(blockingIds, boundary.activityId === null ? `${RUNTIME_REF}.c(${boundaryRef},${contentRef}${metadataArgument})` : `${RUNTIME_REF}.ac(${jsString(boundary.activityId)},${boundaryRef},${contentRef}${metadataArgument})`));
737
+ writeLateDataOperations(request, boundary);
738
+ }
739
+ function takeData(request) {
740
+ return [...[...new Set(request.queuedDataRows.values())].flatMap((batch) => decodePayloadDataEntries(takeQueuedDataBatch(request, batch))), ...claimData(request, request.dataStore.snapshot())];
741
+ }
742
+ function claimData(request, entries) {
743
+ return entries.filter((entry) => {
744
+ const key = normalizeDataResourceKey(entry.key);
745
+ if (request.writtenDataKeys.has(key)) return false;
746
+ if (request.streamDataFilter?.(entry) === false) return false;
747
+ request.writtenDataKeys.add(key);
748
+ return true;
749
+ });
750
+ }
751
+ function unqueuedData(request, entries) {
752
+ return entries.filter((entry) => {
753
+ const key = normalizeDataResourceKey(entry.key);
754
+ if (request.writtenDataKeys.has(key)) return false;
755
+ if (request.queuedDataRows.has(key)) return false;
756
+ return request.streamDataFilter?.(entry) !== false;
757
+ });
758
+ }
759
+ function writeDataOperation(request, boundary) {
760
+ const pending = request.pendingDataKeys;
761
+ if (pending === null || pending.size === 0) return;
762
+ for (const key of pending) {
763
+ const batch = request.queuedDataRows.get(key);
764
+ if (batch !== void 0) writeDataRows(request, takeQueuedDataBatch(request, batch));
765
+ }
766
+ const dependencies = [];
767
+ const rows = encodeDataRows(claimData(request, request.dataStore.snapshotKeys(pending, dependencies)));
768
+ pending.clear();
769
+ for (const entry of dependencies) {
770
+ const batch = request.queuedDataRows.get(normalizeDataResourceKey(entry.key));
771
+ if (batch !== void 0 && !boundary.lateDataRows.includes(batch)) boundary.lateDataRows.push(batch);
772
+ }
773
+ const late = encodeDataRows(unqueuedData(request, dependencies));
774
+ if (late.length > 0) {
775
+ boundary.lateDataRows.push(late);
776
+ for (const row of late) request.queuedDataRows.set(normalizeDataResourceKey(row.key), late);
777
+ }
778
+ writeDataRows(request, [...late.map((row) => ({
779
+ key: row.key,
780
+ pending: true
781
+ })), ...rows]);
782
+ }
783
+ function writeLateDataOperations(request, boundary) {
784
+ const batches = boundary.lateDataRows;
785
+ boundary.lateDataRows = [];
786
+ for (const rows of batches) writeDataRows(request, takeQueuedDataBatch(request, rows));
787
+ }
788
+ function takeQueuedDataBatch(request, batch) {
789
+ const rows = batch.splice(0);
790
+ for (const row of rows) {
791
+ const key = normalizeDataResourceKey(row.key);
792
+ request.queuedDataRows.delete(key);
793
+ request.writtenDataKeys.add(key);
794
+ }
795
+ return rows;
796
+ }
797
+ function writeDataRows(request, rows) {
798
+ if (rows.length === 0) return;
799
+ writeScript(request, `${RUNTIME_REF}.d(${jsString(request.identifierPrefix)},${escapeScriptJson(rows)})`);
800
+ }
801
+ function encodeDataRows(entries) {
802
+ try {
803
+ return encodePayloadDataEntries(entries);
804
+ } catch {
805
+ return entries.flatMap((entry) => {
806
+ try {
807
+ return encodePayloadDataEntries([entry]);
808
+ } catch {
809
+ return [];
810
+ }
811
+ });
812
+ }
730
813
  }
731
814
  function switchBoundaryMetadata(request, boundary) {
732
815
  if (!boundary.metadataVisible) return null;
@@ -788,7 +871,13 @@ function flushClientRenderedBoundary(request, boundary) {
788
871
  const boundaryRef = jsString(boundaryId(request, boundary.id));
789
872
  const digest = jsString(boundary.error?.digest ?? "");
790
873
  const message = jsString(boundary.error?.message ?? "");
791
- writeScript(request, boundary.activityId === null ? `${RUNTIME_REF}.x(${boundaryRef},${digest},${message})` : `${RUNTIME_REF}.ax(${jsString(boundary.activityId)},${boundaryRef},${digest},${message})`);
874
+ const stagedIds = [...boundary.stagedSegmentIds].map((id) => segmentId(request, id));
875
+ const browser = boundary.status === "browser-rendered";
876
+ const cleanup = stagedIds.length === 0 && !browser ? "" : `,${escapeScriptJson(stagedIds)}${browser ? ",1" : ""}`;
877
+ const call = boundary.activityId === null ? `${RUNTIME_REF}.x(${boundaryRef},${digest},${message}${cleanup})` : `${RUNTIME_REF}.ax(${jsString(boundary.activityId)},${boundaryRef},${digest},${message}${cleanup})`;
878
+ boundary.stagedSegmentIds.clear();
879
+ writeScript(request, call);
880
+ writeLateDataOperations(request, boundary);
792
881
  }
793
882
  function drainBoundaryQueue(request, queue, flush) {
794
883
  for (;;) {
@@ -840,6 +929,7 @@ function ensureBoundaryId(request, boundary) {
840
929
  //#endregion
841
930
  //#region src/renderer.ts
842
931
  const errorStacks = /* @__PURE__ */ new WeakMap();
932
+ const browserBailoutBrand = Symbol("fig.browser-bailout");
843
933
  const TEXT_SEPARATOR = `<!--${TEXT_SEPARATOR_DATA}-->`;
844
934
  let nextRuntimeId = 0;
845
935
  function createServerRenderRequest(node, options, mode) {
@@ -854,7 +944,6 @@ function createServerRenderRequest(node, options, mode) {
854
944
  const rootSegment = createSegment(0);
855
945
  const dataStoreHost = {
856
946
  getLane: noLane,
857
- partition: options.dataPartition,
858
947
  schedule: noop
859
948
  };
860
949
  const dataStore = options.dataStore === void 0 ? createRendererDataStore(dataStoreHost) : attachDataStore(options.dataStore, dataStoreHost, options.initialData);
@@ -865,6 +954,10 @@ function createServerRenderRequest(node, options, mode) {
865
954
  completedBoundaries: /* @__PURE__ */ new Set(),
866
955
  controller: null,
867
956
  dataStore,
957
+ pendingDataKeys: mode?.prerender === true || options.streamData === false ? null : /* @__PURE__ */ new Set(),
958
+ streamDataFilter: typeof options.streamData === "object" ? options.streamData.filter ?? null : null,
959
+ writtenDataKeys: /* @__PURE__ */ new Set(),
960
+ queuedDataRows: /* @__PURE__ */ new Map(),
868
961
  dispose: disposeRequest,
869
962
  abortReason: null,
870
963
  identifierPrefix,
@@ -874,6 +967,7 @@ function createServerRenderRequest(node, options, mode) {
874
967
  nextActivityId: 0,
875
968
  nextViewTransitionId: 0,
876
969
  nonce: options.nonce,
970
+ onBrowserBailout: options.onBrowserBailout,
877
971
  onError: options.onError,
878
972
  pendingRootTasks: 0,
879
973
  pingedTasks: [],
@@ -948,6 +1042,7 @@ function createServerRenderRequest(node, options, mode) {
948
1042
  contentType: "text/html; charset=utf-8",
949
1043
  data: request.dataStore,
950
1044
  getData: () => request.dataStore.snapshot(),
1045
+ takeData: () => takeData(request),
951
1046
  getPreloadHeader: (headerOptions) => {
952
1047
  const snapshot = request.headSnapshot;
953
1048
  if (snapshot === null) return void 0;
@@ -1010,6 +1105,7 @@ function createSegment(index, boundary = null) {
1010
1105
  boundary,
1011
1106
  children: [],
1012
1107
  chunks: [],
1108
+ dataKeys: null,
1013
1109
  id: null,
1014
1110
  index,
1015
1111
  lastPushedText: false,
@@ -1059,17 +1155,18 @@ function createServerDispatcher(frame) {
1059
1155
  return createStaticDispatcher({
1060
1156
  contextValues: frame.contextValues,
1061
1157
  externalStoreError: "useSyncExternalStore requires getServerSnapshot during server render.",
1158
+ readBrowser(reason) {
1159
+ throw browserBailout(reason);
1160
+ },
1062
1161
  readPromise(promise) {
1063
1162
  throwIfAborting(frame.request);
1064
1163
  return readThenable(promise);
1065
1164
  },
1066
1165
  readData(resource, args) {
1067
1166
  throwIfAborting(frame.request);
1068
- return frame.request.dataStore.readData(resource, args);
1069
- },
1070
- preloadData(resource, args) {
1071
- throwIfAborting(frame.request);
1072
- frame.request.dataStore.preloadData(resource, ...args);
1167
+ const value = frame.request.dataStore.readData(resource, args);
1168
+ if (frame.request.pendingDataKeys !== null) (frame.segment.dataKeys ??= /* @__PURE__ */ new Set()).add(normalizeDataResourceKey(resource.key(...args)));
1169
+ return value;
1073
1170
  },
1074
1171
  useId() {
1075
1172
  frame.idPathString ??= formatIdPath(frame.idPath);
@@ -1239,7 +1336,7 @@ function renderFunctionComponent(type, props, frame) {
1239
1336
  const previousDataStore = setCurrentDataStore(frame.request.dataStore);
1240
1337
  const previousStack = frame.stack;
1241
1338
  const previousLocalIdCounter = frame.localIdCounter;
1242
- if (frame.request.onError !== void 0) frame.stack = {
1339
+ if (frame.request.onBrowserBailout !== void 0 || frame.request.onError !== void 0) frame.stack = {
1243
1340
  name: type.name || "Anonymous",
1244
1341
  parent: previousStack
1245
1342
  };
@@ -1316,6 +1413,8 @@ function renderSuspense(props, frame) {
1316
1413
  error: null,
1317
1414
  fallbackSegment: null,
1318
1415
  fallbackTasks: /* @__PURE__ */ new Set(),
1416
+ lateDataRows: [],
1417
+ stagedSegmentIds: /* @__PURE__ */ new Set(),
1319
1418
  id: null,
1320
1419
  metadataVisible: false,
1321
1420
  parentFlushed: false,
@@ -1336,7 +1435,7 @@ function renderSuspense(props, frame) {
1336
1435
  if (boundary.pendingTasks === 0) boundary.status = "completed";
1337
1436
  } catch (error) {
1338
1437
  contentSegment.status = "completed";
1339
- markBoundaryClientRendered(frame.request, boundary, error, frame.stack);
1438
+ markBoundaryForClientRender(frame.request, boundary, error, frame.stack);
1340
1439
  }
1341
1440
  advanceViewTransitionWatermark(frame, contentFrame);
1342
1441
  if (boundary.status === "completed") return;
@@ -1492,13 +1591,13 @@ function settleTask(task, outcome, error) {
1492
1591
  if (boundary === null) {
1493
1592
  request.pendingRootTasks -= 1;
1494
1593
  if (outcome === "errored") {
1495
- fatalError(request, error);
1594
+ fatalError(request, isBrowserBailout(error) ? browserBailoutError(error) : error);
1496
1595
  return;
1497
1596
  }
1498
1597
  if (request.pendingRootTasks === 0) finishRootShell(request);
1499
1598
  } else {
1500
1599
  boundary.pendingTasks -= 1;
1501
- if (outcome === "errored") markBoundaryClientRendered(request, boundary, error, stack);
1600
+ if (outcome === "errored") markBoundaryForClientRender(request, boundary, error, stack);
1502
1601
  else if (outcome === "completed" && segment.parentFlushed) boundary.completedSegments.push(segment);
1503
1602
  if (outcome !== "errored") {
1504
1603
  const boundaryCompleted = completeBoundaryIfReady(request, boundary);
@@ -1529,13 +1628,77 @@ function markBoundaryClientRendered(request, boundary, error, stack, payload) {
1529
1628
  boundary.status = "client-rendered";
1530
1629
  boundary.error = payload ?? serverErrorPayload(error, stackForError(error, stack), request.onError);
1531
1630
  }
1631
+ discardBoundaryServerWork(request, boundary);
1632
+ }
1633
+ function discardBoundaryServerWork(request, boundary) {
1532
1634
  boundary.completedSegments.length = 0;
1533
1635
  request.completedBoundaries.delete(boundary);
1534
1636
  request.partialBoundaries.delete(boundary);
1535
- for (const task of request.abortableTasks) if (task.frame.boundary === boundary) abortTask(task);
1536
- for (const task of boundary.fallbackTasks) abortTask(task);
1637
+ const discardedSegments = /* @__PURE__ */ new Set();
1638
+ discardSegmentTree(request, boundary.contentSegment, discardedSegments, boundary);
1639
+ for (const task of request.abortableTasks) if (discardedSegments.has(task.frame.segment)) abortTask(task);
1537
1640
  if (boundary.parentFlushed) request.clientRenderedBoundaries.add(boundary);
1538
1641
  }
1642
+ function markBoundaryBrowserRendered(request, boundary, bailout, stack) {
1643
+ if (boundary.status !== "browser-rendered") {
1644
+ boundary.status = "browser-rendered";
1645
+ boundary.error = null;
1646
+ reportBrowserBailout(request, bailout, stackForError(bailout, stack));
1647
+ }
1648
+ discardBoundaryServerWork(request, boundary);
1649
+ }
1650
+ function markBoundaryForClientRender(request, boundary, error, stack) {
1651
+ if (isBrowserBailout(error)) {
1652
+ markBoundaryBrowserRendered(request, boundary, error, stack);
1653
+ return;
1654
+ }
1655
+ markBoundaryClientRendered(request, boundary, error, stack);
1656
+ }
1657
+ function browserBailout(reason) {
1658
+ return reason === void 0 ? { [browserBailoutBrand]: true } : {
1659
+ [browserBailoutBrand]: true,
1660
+ reason
1661
+ };
1662
+ }
1663
+ function isBrowserBailout(value) {
1664
+ return typeof value === "object" && value !== null && browserBailoutBrand in value;
1665
+ }
1666
+ function browserBailoutError(bailout, message = "A component requires browser rendering, but it is not inside a Suspense boundary.") {
1667
+ let cause;
1668
+ try {
1669
+ cause = typeof bailout.reason === "function" ? bailout.reason() : bailout.reason;
1670
+ } catch (error) {
1671
+ cause = error;
1672
+ }
1673
+ const error = new Error(message);
1674
+ if (cause !== void 0) error.cause = cause;
1675
+ return error;
1676
+ }
1677
+ function reportBrowserBailout(request, bailout, stack) {
1678
+ const error = browserBailoutError(bailout, "The server left a Suspense boundary for browser rendering.");
1679
+ const report = request.onBrowserBailout;
1680
+ if (report === void 0) return;
1681
+ try {
1682
+ report(error, { componentStack: componentStack(stack) });
1683
+ } catch {}
1684
+ }
1685
+ function discardSegmentTree(request, segment, discarded, owner) {
1686
+ discarded.add(segment);
1687
+ const boundary = segment.boundary;
1688
+ if (boundary !== null) {
1689
+ boundary.status = "client-rendered";
1690
+ for (const id of boundary.stagedSegmentIds) owner.stagedSegmentIds.add(id);
1691
+ boundary.stagedSegmentIds.clear();
1692
+ owner.lateDataRows.push(...boundary.lateDataRows);
1693
+ boundary.lateDataRows = [];
1694
+ boundary.completedSegments.length = 0;
1695
+ request.completedBoundaries.delete(boundary);
1696
+ request.partialBoundaries.delete(boundary);
1697
+ request.clientRenderedBoundaries.delete(boundary);
1698
+ discardSegmentTree(request, boundary.contentSegment, discarded, owner);
1699
+ }
1700
+ for (const child of segment.children) discardSegmentTree(request, child, discarded, owner);
1701
+ }
1539
1702
  function abort(request, reason) {
1540
1703
  if (request.status === "closed") return;
1541
1704
  request.status = "aborting";
@@ -1545,7 +1708,12 @@ function abort(request, reason) {
1545
1708
  fatalError(request, error);
1546
1709
  return;
1547
1710
  }
1548
- request.dispose();
1711
+ try {
1712
+ request.dispose();
1713
+ } catch {
1714
+ fatalError(request, error);
1715
+ return;
1716
+ }
1549
1717
  for (const task of request.abortableTasks) {
1550
1718
  const { boundary, stack } = task.frame;
1551
1719
  if (boundary !== null) markBoundaryClientRendered(request, boundary, error, stack, {});
@@ -1557,7 +1725,9 @@ function abort(request, reason) {
1557
1725
  function fatalError(request, error) {
1558
1726
  if (request.status === "closed") return;
1559
1727
  request.status = "closed";
1560
- request.dispose();
1728
+ try {
1729
+ request.dispose();
1730
+ } catch {}
1561
1731
  request.headReady.reject(error);
1562
1732
  request.shellReady.reject(error);
1563
1733
  request.allReady.reject(error);