@bgub/fig-server 1.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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-CXnAwZ0S.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-CztoSryT.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, validateInstanceNesting, validateTextNesting } 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, validateInstanceNesting, validateTextNesting } 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, frame);
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);
@@ -1317,6 +1364,7 @@ function renderSuspense(props, frame) {
1317
1364
  error: null,
1318
1365
  fallbackSegment: null,
1319
1366
  fallbackTasks: /* @__PURE__ */ new Set(),
1367
+ stagedSegmentIds: /* @__PURE__ */ new Set(),
1320
1368
  id: null,
1321
1369
  metadataVisible: false,
1322
1370
  parentFlushed: false,
@@ -1337,7 +1385,7 @@ function renderSuspense(props, frame) {
1337
1385
  if (boundary.pendingTasks === 0) boundary.status = "completed";
1338
1386
  } catch (error) {
1339
1387
  contentSegment.status = "completed";
1340
- markBoundaryClientRendered(frame.request, boundary, error, frame.stack);
1388
+ markBoundaryForClientRender(frame.request, boundary, error, frame.stack);
1341
1389
  }
1342
1390
  advanceViewTransitionWatermark(frame, contentFrame);
1343
1391
  if (boundary.status === "completed") return;
@@ -1495,13 +1543,13 @@ function settleTask(task, outcome, error) {
1495
1543
  if (boundary === null) {
1496
1544
  request.pendingRootTasks -= 1;
1497
1545
  if (outcome === "errored") {
1498
- fatalError(request, error);
1546
+ fatalError(request, isBrowserBailout(error) ? browserBailoutError(error) : error);
1499
1547
  return;
1500
1548
  }
1501
1549
  if (request.pendingRootTasks === 0) finishRootShell(request);
1502
1550
  } else {
1503
1551
  boundary.pendingTasks -= 1;
1504
- if (outcome === "errored") markBoundaryClientRendered(request, boundary, error, stack);
1552
+ if (outcome === "errored") markBoundaryForClientRender(request, boundary, error, stack);
1505
1553
  else if (outcome === "completed" && segment.parentFlushed) boundary.completedSegments.push(segment);
1506
1554
  if (outcome !== "errored") {
1507
1555
  const boundaryCompleted = completeBoundaryIfReady(request, boundary);
@@ -1532,13 +1580,75 @@ function markBoundaryClientRendered(request, boundary, error, stack, payload) {
1532
1580
  boundary.status = "client-rendered";
1533
1581
  boundary.error = payload ?? serverErrorPayload(error, stackForError(error, stack), request.onError);
1534
1582
  }
1583
+ discardBoundaryServerWork(request, boundary);
1584
+ }
1585
+ function discardBoundaryServerWork(request, boundary) {
1535
1586
  boundary.completedSegments.length = 0;
1536
1587
  request.completedBoundaries.delete(boundary);
1537
1588
  request.partialBoundaries.delete(boundary);
1538
- for (const task of request.abortableTasks) if (task.frame.boundary === boundary) abortTask(task);
1539
- for (const task of boundary.fallbackTasks) abortTask(task);
1589
+ const discardedSegments = /* @__PURE__ */ new Set();
1590
+ discardSegmentTree(request, boundary.contentSegment, discardedSegments, boundary.stagedSegmentIds);
1591
+ for (const task of request.abortableTasks) if (discardedSegments.has(task.frame.segment)) abortTask(task);
1540
1592
  if (boundary.parentFlushed) request.clientRenderedBoundaries.add(boundary);
1541
1593
  }
1594
+ function markBoundaryBrowserRendered(request, boundary, bailout, stack) {
1595
+ if (boundary.status !== "browser-rendered") {
1596
+ boundary.status = "browser-rendered";
1597
+ boundary.error = null;
1598
+ reportBrowserBailout(request, bailout, stackForError(bailout, stack));
1599
+ }
1600
+ discardBoundaryServerWork(request, boundary);
1601
+ }
1602
+ function markBoundaryForClientRender(request, boundary, error, stack) {
1603
+ if (isBrowserBailout(error)) {
1604
+ markBoundaryBrowserRendered(request, boundary, error, stack);
1605
+ return;
1606
+ }
1607
+ markBoundaryClientRendered(request, boundary, error, stack);
1608
+ }
1609
+ function browserBailout(reason) {
1610
+ return reason === void 0 ? { [browserBailoutBrand]: true } : {
1611
+ [browserBailoutBrand]: true,
1612
+ reason
1613
+ };
1614
+ }
1615
+ function isBrowserBailout(value) {
1616
+ return typeof value === "object" && value !== null && browserBailoutBrand in value;
1617
+ }
1618
+ function browserBailoutError(bailout, message = "A component requires browser rendering, but it is not inside a Suspense boundary.") {
1619
+ let cause;
1620
+ try {
1621
+ cause = typeof bailout.reason === "function" ? bailout.reason() : bailout.reason;
1622
+ } catch (error) {
1623
+ cause = error;
1624
+ }
1625
+ const error = new Error(message);
1626
+ if (cause !== void 0) error.cause = cause;
1627
+ return error;
1628
+ }
1629
+ function reportBrowserBailout(request, bailout, stack) {
1630
+ const error = browserBailoutError(bailout, "The server left a Suspense boundary for browser rendering.");
1631
+ const report = request.onBrowserBailout;
1632
+ if (report === void 0) return;
1633
+ try {
1634
+ report(error, { componentStack: componentStack(stack) });
1635
+ } catch {}
1636
+ }
1637
+ function discardSegmentTree(request, segment, discarded, stagedSegmentIds) {
1638
+ discarded.add(segment);
1639
+ const boundary = segment.boundary;
1640
+ if (boundary !== null) {
1641
+ boundary.status = "client-rendered";
1642
+ for (const id of boundary.stagedSegmentIds) stagedSegmentIds.add(id);
1643
+ boundary.stagedSegmentIds.clear();
1644
+ boundary.completedSegments.length = 0;
1645
+ request.completedBoundaries.delete(boundary);
1646
+ request.partialBoundaries.delete(boundary);
1647
+ request.clientRenderedBoundaries.delete(boundary);
1648
+ discardSegmentTree(request, boundary.contentSegment, discarded, stagedSegmentIds);
1649
+ }
1650
+ for (const child of segment.children) discardSegmentTree(request, child, discarded, stagedSegmentIds);
1651
+ }
1542
1652
  function abort(request, reason) {
1543
1653
  if (request.status === "closed") return;
1544
1654
  request.status = "aborting";