@bgub/fig-server 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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":"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"}
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, 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);
@@ -653,6 +646,10 @@ function flushSubtree(request, segment) {
653
646
  }
654
647
  if (segment.status === "flushed") return;
655
648
  segment.status = "flushed";
649
+ if (segment.dataKeys !== null) {
650
+ for (const key of segment.dataKeys) request.pendingDataKeys?.add(key);
651
+ segment.dataKeys = null;
652
+ }
656
653
  if (request.documentHasHead === null || segment !== request.rootSegment) collectSegmentAssets(request, segment, null);
657
654
  let chunkIndex = 0;
658
655
  for (const child of segment.children) {
@@ -673,8 +670,9 @@ function flushSuspenseBoundary(request, segment, boundary) {
673
670
  segment.chunks.length = 0;
674
671
  return;
675
672
  }
676
- if (request.prerender && boundary.status === "client-rendered") {
677
- request.write(`<!--${SUSPENSE_CLIENT_MARKER}-->`);
673
+ if (request.prerender && (boundary.status === "browser-rendered" || boundary.status === "client-rendered")) {
674
+ const marker = boundary.status === "browser-rendered" ? SUSPENSE_BROWSER_MARKER : SUSPENSE_CLIENT_MARKER;
675
+ request.write(`<!--${marker}-->`);
678
676
  request.write(clientRenderedBoundaryPlaceholderMarkup(request, boundary));
679
677
  flushSubtree(request, segment);
680
678
  request.write(`<!--${SUSPENSE_END_MARKER}-->`);
@@ -686,7 +684,7 @@ function flushSuspenseBoundary(request, segment, boundary) {
686
684
  request.write(boundaryPlaceholderMarkup(request, boundaryIdValue));
687
685
  flushSubtree(request, segment);
688
686
  request.write(`<!--${SUSPENSE_END_MARKER}-->`);
689
- if (boundary.status === "client-rendered") request.clientRenderedBoundaries.add(boundary);
687
+ if (boundary.status === "browser-rendered" || boundary.status === "client-rendered") request.clientRenderedBoundaries.add(boundary);
690
688
  else if (boundary.completedSegments.length > 0) request.partialBoundaries.add(boundary);
691
689
  }
692
690
  function clientRenderedBoundaryPlaceholderMarkup(request, boundary) {
@@ -708,7 +706,9 @@ function flushBoundarySegment(request, boundary, segment) {
708
706
  let blockingIds = "";
709
707
  if (segment.status !== "flushed") {
710
708
  blockingIds = flushSegmentAssets(request, segment);
711
- request.write(segmentContainerStartMarkup(request, ensureSegmentId(request, segment)));
709
+ const id = ensureSegmentId(request, segment);
710
+ boundary.stagedSegmentIds.add(id);
711
+ request.write(segmentContainerStartMarkup(request, id));
712
712
  flushSegment(request, segment);
713
713
  request.write("</div>");
714
714
  }
@@ -717,6 +717,7 @@ function flushBoundarySegment(request, boundary, segment) {
717
717
  function writeSegmentRevealScript(request, segment, blockingIds) {
718
718
  const id = ensureSegmentId(request, segment);
719
719
  writeRuntime(request);
720
+ writeDataOperation(request);
720
721
  writeScript(request, withAssetGate(blockingIds, `${RUNTIME_REF}.s(${jsString(placeholderId(request, id))},${jsString(segmentId(request, id))})`));
721
722
  }
722
723
  function writeBoundaryRevealScript(request, boundary) {
@@ -724,10 +725,44 @@ function writeBoundaryRevealScript(request, boundary) {
724
725
  const metadata = switchBoundaryMetadata(request, boundary);
725
726
  const metadataArgument = metadata === null ? "" : `,${metadata}`;
726
727
  writeRuntime(request);
728
+ writeDataOperation(request);
727
729
  const boundaryRef = jsString(boundaryId(request, ensureBoundaryId(request, boundary)));
728
730
  const contentRef = jsString(segmentId(request, ensureSegmentId(request, boundary.contentSegment)));
729
731
  writeScript(request, withAssetGate(blockingIds, boundary.activityId === null ? `${RUNTIME_REF}.c(${boundaryRef},${contentRef}${metadataArgument})` : `${RUNTIME_REF}.ac(${jsString(boundary.activityId)},${boundaryRef},${contentRef}${metadataArgument})`));
730
732
  }
733
+ function takeData(request) {
734
+ return claimData(request, request.dataStore.snapshot());
735
+ }
736
+ function claimData(request, entries) {
737
+ return entries.filter((entry) => {
738
+ const key = normalizeDataResourceKey(entry.key);
739
+ if (request.writtenDataKeys.has(key)) return false;
740
+ if (request.streamDataFilter?.(entry) === false) return false;
741
+ request.writtenDataKeys.add(key);
742
+ return true;
743
+ });
744
+ }
745
+ function writeDataOperation(request) {
746
+ const pending = request.pendingDataKeys;
747
+ if (pending === null || pending.size === 0) return;
748
+ const rows = encodeDataRows(claimData(request, request.dataStore.snapshotKeys(pending)));
749
+ pending.clear();
750
+ if (rows.length === 0) return;
751
+ writeScript(request, `${RUNTIME_REF}.d(${jsString(request.identifierPrefix)},${escapeScriptJson(rows)})`);
752
+ }
753
+ function encodeDataRows(entries) {
754
+ try {
755
+ return encodePayloadDataEntries(entries);
756
+ } catch {
757
+ return entries.flatMap((entry) => {
758
+ try {
759
+ return encodePayloadDataEntries([entry]);
760
+ } catch {
761
+ return [];
762
+ }
763
+ });
764
+ }
765
+ }
731
766
  function switchBoundaryMetadata(request, boundary) {
732
767
  if (!boundary.metadataVisible) return null;
733
768
  const before = escapeScriptJson(request.assetRegistry.metadataSnapshot());
@@ -788,7 +823,12 @@ function flushClientRenderedBoundary(request, boundary) {
788
823
  const boundaryRef = jsString(boundaryId(request, boundary.id));
789
824
  const digest = jsString(boundary.error?.digest ?? "");
790
825
  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})`);
826
+ const stagedIds = [...boundary.stagedSegmentIds].map((id) => segmentId(request, id));
827
+ const browser = boundary.status === "browser-rendered";
828
+ const cleanup = stagedIds.length === 0 && !browser ? "" : `,${escapeScriptJson(stagedIds)}${browser ? ",1" : ""}`;
829
+ const call = boundary.activityId === null ? `${RUNTIME_REF}.x(${boundaryRef},${digest},${message}${cleanup})` : `${RUNTIME_REF}.ax(${jsString(boundary.activityId)},${boundaryRef},${digest},${message}${cleanup})`;
830
+ boundary.stagedSegmentIds.clear();
831
+ writeScript(request, call);
792
832
  }
793
833
  function drainBoundaryQueue(request, queue, flush) {
794
834
  for (;;) {
@@ -840,6 +880,7 @@ function ensureBoundaryId(request, boundary) {
840
880
  //#endregion
841
881
  //#region src/renderer.ts
842
882
  const errorStacks = /* @__PURE__ */ new WeakMap();
883
+ const browserBailoutBrand = Symbol("fig.browser-bailout");
843
884
  const TEXT_SEPARATOR = `<!--${TEXT_SEPARATOR_DATA}-->`;
844
885
  let nextRuntimeId = 0;
845
886
  function createServerRenderRequest(node, options, mode) {
@@ -854,7 +895,6 @@ function createServerRenderRequest(node, options, mode) {
854
895
  const rootSegment = createSegment(0);
855
896
  const dataStoreHost = {
856
897
  getLane: noLane,
857
- partition: options.dataPartition,
858
898
  schedule: noop
859
899
  };
860
900
  const dataStore = options.dataStore === void 0 ? createRendererDataStore(dataStoreHost) : attachDataStore(options.dataStore, dataStoreHost, options.initialData);
@@ -865,6 +905,9 @@ function createServerRenderRequest(node, options, mode) {
865
905
  completedBoundaries: /* @__PURE__ */ new Set(),
866
906
  controller: null,
867
907
  dataStore,
908
+ pendingDataKeys: mode?.prerender === true || options.streamData === false ? null : /* @__PURE__ */ new Set(),
909
+ streamDataFilter: typeof options.streamData === "object" ? options.streamData.filter ?? null : null,
910
+ writtenDataKeys: /* @__PURE__ */ new Set(),
868
911
  dispose: disposeRequest,
869
912
  abortReason: null,
870
913
  identifierPrefix,
@@ -874,6 +917,7 @@ function createServerRenderRequest(node, options, mode) {
874
917
  nextActivityId: 0,
875
918
  nextViewTransitionId: 0,
876
919
  nonce: options.nonce,
920
+ onBrowserBailout: options.onBrowserBailout,
877
921
  onError: options.onError,
878
922
  pendingRootTasks: 0,
879
923
  pingedTasks: [],
@@ -948,6 +992,7 @@ function createServerRenderRequest(node, options, mode) {
948
992
  contentType: "text/html; charset=utf-8",
949
993
  data: request.dataStore,
950
994
  getData: () => request.dataStore.snapshot(),
995
+ takeData: () => takeData(request),
951
996
  getPreloadHeader: (headerOptions) => {
952
997
  const snapshot = request.headSnapshot;
953
998
  if (snapshot === null) return void 0;
@@ -1010,6 +1055,7 @@ function createSegment(index, boundary = null) {
1010
1055
  boundary,
1011
1056
  children: [],
1012
1057
  chunks: [],
1058
+ dataKeys: null,
1013
1059
  id: null,
1014
1060
  index,
1015
1061
  lastPushedText: false,
@@ -1059,17 +1105,18 @@ function createServerDispatcher(frame) {
1059
1105
  return createStaticDispatcher({
1060
1106
  contextValues: frame.contextValues,
1061
1107
  externalStoreError: "useSyncExternalStore requires getServerSnapshot during server render.",
1108
+ readBrowser(reason) {
1109
+ throw browserBailout(reason);
1110
+ },
1062
1111
  readPromise(promise) {
1063
1112
  throwIfAborting(frame.request);
1064
1113
  return readThenable(promise);
1065
1114
  },
1066
1115
  readData(resource, args) {
1067
1116
  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);
1117
+ const value = frame.request.dataStore.readData(resource, args);
1118
+ if (frame.request.pendingDataKeys !== null) (frame.segment.dataKeys ??= /* @__PURE__ */ new Set()).add(normalizeDataResourceKey(resource.key(...args)));
1119
+ return value;
1073
1120
  },
1074
1121
  useId() {
1075
1122
  frame.idPathString ??= formatIdPath(frame.idPath);
@@ -1239,7 +1286,7 @@ function renderFunctionComponent(type, props, frame) {
1239
1286
  const previousDataStore = setCurrentDataStore(frame.request.dataStore);
1240
1287
  const previousStack = frame.stack;
1241
1288
  const previousLocalIdCounter = frame.localIdCounter;
1242
- if (frame.request.onError !== void 0) frame.stack = {
1289
+ if (frame.request.onBrowserBailout !== void 0 || frame.request.onError !== void 0) frame.stack = {
1243
1290
  name: type.name || "Anonymous",
1244
1291
  parent: previousStack
1245
1292
  };
@@ -1316,6 +1363,7 @@ function renderSuspense(props, frame) {
1316
1363
  error: null,
1317
1364
  fallbackSegment: null,
1318
1365
  fallbackTasks: /* @__PURE__ */ new Set(),
1366
+ stagedSegmentIds: /* @__PURE__ */ new Set(),
1319
1367
  id: null,
1320
1368
  metadataVisible: false,
1321
1369
  parentFlushed: false,
@@ -1336,7 +1384,7 @@ function renderSuspense(props, frame) {
1336
1384
  if (boundary.pendingTasks === 0) boundary.status = "completed";
1337
1385
  } catch (error) {
1338
1386
  contentSegment.status = "completed";
1339
- markBoundaryClientRendered(frame.request, boundary, error, frame.stack);
1387
+ markBoundaryForClientRender(frame.request, boundary, error, frame.stack);
1340
1388
  }
1341
1389
  advanceViewTransitionWatermark(frame, contentFrame);
1342
1390
  if (boundary.status === "completed") return;
@@ -1492,13 +1540,13 @@ function settleTask(task, outcome, error) {
1492
1540
  if (boundary === null) {
1493
1541
  request.pendingRootTasks -= 1;
1494
1542
  if (outcome === "errored") {
1495
- fatalError(request, error);
1543
+ fatalError(request, isBrowserBailout(error) ? browserBailoutError(error) : error);
1496
1544
  return;
1497
1545
  }
1498
1546
  if (request.pendingRootTasks === 0) finishRootShell(request);
1499
1547
  } else {
1500
1548
  boundary.pendingTasks -= 1;
1501
- if (outcome === "errored") markBoundaryClientRendered(request, boundary, error, stack);
1549
+ if (outcome === "errored") markBoundaryForClientRender(request, boundary, error, stack);
1502
1550
  else if (outcome === "completed" && segment.parentFlushed) boundary.completedSegments.push(segment);
1503
1551
  if (outcome !== "errored") {
1504
1552
  const boundaryCompleted = completeBoundaryIfReady(request, boundary);
@@ -1529,13 +1577,75 @@ function markBoundaryClientRendered(request, boundary, error, stack, payload) {
1529
1577
  boundary.status = "client-rendered";
1530
1578
  boundary.error = payload ?? serverErrorPayload(error, stackForError(error, stack), request.onError);
1531
1579
  }
1580
+ discardBoundaryServerWork(request, boundary);
1581
+ }
1582
+ function discardBoundaryServerWork(request, boundary) {
1532
1583
  boundary.completedSegments.length = 0;
1533
1584
  request.completedBoundaries.delete(boundary);
1534
1585
  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);
1586
+ const discardedSegments = /* @__PURE__ */ new Set();
1587
+ discardSegmentTree(request, boundary.contentSegment, discardedSegments, boundary.stagedSegmentIds);
1588
+ for (const task of request.abortableTasks) if (discardedSegments.has(task.frame.segment)) abortTask(task);
1537
1589
  if (boundary.parentFlushed) request.clientRenderedBoundaries.add(boundary);
1538
1590
  }
1591
+ function markBoundaryBrowserRendered(request, boundary, bailout, stack) {
1592
+ if (boundary.status !== "browser-rendered") {
1593
+ boundary.status = "browser-rendered";
1594
+ boundary.error = null;
1595
+ reportBrowserBailout(request, bailout, stackForError(bailout, stack));
1596
+ }
1597
+ discardBoundaryServerWork(request, boundary);
1598
+ }
1599
+ function markBoundaryForClientRender(request, boundary, error, stack) {
1600
+ if (isBrowserBailout(error)) {
1601
+ markBoundaryBrowserRendered(request, boundary, error, stack);
1602
+ return;
1603
+ }
1604
+ markBoundaryClientRendered(request, boundary, error, stack);
1605
+ }
1606
+ function browserBailout(reason) {
1607
+ return reason === void 0 ? { [browserBailoutBrand]: true } : {
1608
+ [browserBailoutBrand]: true,
1609
+ reason
1610
+ };
1611
+ }
1612
+ function isBrowserBailout(value) {
1613
+ return typeof value === "object" && value !== null && browserBailoutBrand in value;
1614
+ }
1615
+ function browserBailoutError(bailout, message = "A component requires browser rendering, but it is not inside a Suspense boundary.") {
1616
+ let cause;
1617
+ try {
1618
+ cause = typeof bailout.reason === "function" ? bailout.reason() : bailout.reason;
1619
+ } catch (error) {
1620
+ cause = error;
1621
+ }
1622
+ const error = new Error(message);
1623
+ if (cause !== void 0) error.cause = cause;
1624
+ return error;
1625
+ }
1626
+ function reportBrowserBailout(request, bailout, stack) {
1627
+ const error = browserBailoutError(bailout, "The server left a Suspense boundary for browser rendering.");
1628
+ const report = request.onBrowserBailout;
1629
+ if (report === void 0) return;
1630
+ try {
1631
+ report(error, { componentStack: componentStack(stack) });
1632
+ } catch {}
1633
+ }
1634
+ function discardSegmentTree(request, segment, discarded, stagedSegmentIds) {
1635
+ discarded.add(segment);
1636
+ const boundary = segment.boundary;
1637
+ if (boundary !== null) {
1638
+ boundary.status = "client-rendered";
1639
+ for (const id of boundary.stagedSegmentIds) stagedSegmentIds.add(id);
1640
+ boundary.stagedSegmentIds.clear();
1641
+ boundary.completedSegments.length = 0;
1642
+ request.completedBoundaries.delete(boundary);
1643
+ request.partialBoundaries.delete(boundary);
1644
+ request.clientRenderedBoundaries.delete(boundary);
1645
+ discardSegmentTree(request, boundary.contentSegment, discarded, stagedSegmentIds);
1646
+ }
1647
+ for (const child of segment.children) discardSegmentTree(request, child, discarded, stagedSegmentIds);
1648
+ }
1539
1649
  function abort(request, reason) {
1540
1650
  if (request.status === "closed") return;
1541
1651
  request.status = "aborting";