@riverbankcms/sdk 0.165.0 → 0.167.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.
Files changed (246) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +5 -0
  3. package/dist/_dts/{BlocksIslandsHydrator-CdsSMQEv.d.ts → BlocksIslandsHydrator-Dgb-ptph.d.ts} +1 -1
  4. package/dist/_dts/{Page-D6gp2Ipb.d.ts → Page-Bs3WxFgr.d.ts} +20 -258
  5. package/dist/_dts/{SdkPreviewMode-DNXAvnet.d.ts → SdkPreviewMode-DtUCsaHY.d.ts} +26 -3
  6. package/dist/_dts/{client-BkkExozE.d.ts → client-CwsI23pj.d.ts} +13 -1
  7. package/dist/_dts/{content-types-CXNAD7ef.d.ts → content-types-CAeP_-cV.d.ts} +3 -3
  8. package/dist/_dts/{contracts-XRXhbLWP.d.ts → contracts-BXHCiF-b.d.ts} +8 -5
  9. package/dist/_dts/{footerPageOutline-BP2bJYdY.d.ts → footerPageOutline-Bb2gbppW.d.ts} +6 -6
  10. package/dist/_dts/{generatePageMetadata-DcMtbztV.d.ts → generatePageMetadata-DaBBDx7M.d.ts} +2 -2
  11. package/dist/_dts/{index-DKNEgSOS.d.ts → index-5_jf52sZ.d.ts} +2 -2
  12. package/dist/_dts/{index-CQfJhOEA.d.ts → index-C20yUyob.d.ts} +1 -1
  13. package/dist/_dts/{index-CRRiddNp.d.ts → index-CS6b1B-c.d.ts} +4 -4
  14. package/dist/_dts/{index-B4ozSzFP.d.ts → index-ChpjHK0U.d.ts} +9737 -8316
  15. package/dist/_dts/{index-BdkHhyf8.d.ts → index-D7EbliE3.d.ts} +1 -1
  16. package/dist/_dts/{index-RXkE3a7M.d.ts → index-DeHDwMfu.d.ts} +4 -3
  17. package/dist/_dts/{index-DAPTSmBM.d.ts → index-RugyUnqR.d.ts} +2499 -2218
  18. package/dist/_dts/{index-C_3kdrUb.d.ts → index-bDln38Hm.d.ts} +2 -2
  19. package/dist/_dts/{loadContent-B9vJMq3s.d.ts → loadContent-CTqcL7CS.d.ts} +9 -6
  20. package/dist/_dts/resolveBlockData-C3s9WMPs.d.ts +136 -0
  21. package/dist/_dts/{resolvePageContent-DIQyYUi-.d.ts → resolvePageContent-JPwgRxwh.d.ts} +3 -2
  22. package/dist/_dts/sdk/src/bookings/index.d.ts +2 -2
  23. package/dist/_dts/sdk/src/client/types.d.ts +2 -2
  24. package/dist/_dts/sdk/src/client.d.ts +9 -6
  25. package/dist/_dts/sdk/src/config/index.d.ts +6 -6
  26. package/dist/_dts/sdk/src/config/template-validation.d.ts +1 -1
  27. package/dist/_dts/sdk/src/config/validation.d.ts +1 -1
  28. package/dist/_dts/sdk/src/data/dataLoaderContext.d.ts +20 -0
  29. package/dist/_dts/sdk/src/data/resolveBlockData.d.ts +2 -0
  30. package/dist/_dts/sdk/src/data/types.d.ts +54 -0
  31. package/dist/_dts/sdk/src/index.d.ts +8 -8
  32. package/dist/_dts/sdk/src/manifest/index.d.ts +3 -3
  33. package/dist/_dts/sdk/src/metadata/index.d.ts +6 -1
  34. package/dist/_dts/sdk/src/navigation/index.d.ts +2 -2
  35. package/dist/_dts/sdk/src/next/index.d.ts +9 -8
  36. package/dist/_dts/sdk/src/next/middleware.d.ts +2 -2
  37. package/dist/_dts/sdk/src/page-converter/index.d.ts +36 -48
  38. package/dist/_dts/sdk/src/portal/client.d.ts +1 -1
  39. package/dist/_dts/sdk/src/prebuild/index.d.ts +1 -1
  40. package/dist/_dts/sdk/src/preview-next/before-render.d.ts +2 -2
  41. package/dist/_dts/sdk/src/preview-next/client/index.d.ts +2 -2
  42. package/dist/_dts/sdk/src/preview-next/client/runtime.d.ts +1 -1
  43. package/dist/_dts/sdk/src/rendering/client.d.ts +2 -2
  44. package/dist/_dts/sdk/src/rendering/components/pageShared.d.ts +2 -0
  45. package/dist/_dts/sdk/src/rendering/helpers/loadPage.d.ts +3 -0
  46. package/dist/_dts/sdk/src/rendering/helpers/pageRuntimeSupport.d.ts +260 -0
  47. package/dist/_dts/sdk/src/rendering/index.d.ts +8 -7
  48. package/dist/_dts/sdk/src/rendering/islands/client.d.ts +1 -1
  49. package/dist/_dts/sdk/src/rendering/server.d.ts +3 -3
  50. package/dist/_dts/{themeAdmission-D_qtGYAT.d.ts → sdk/src/rendering/themeAdmission.d.ts} +3 -1
  51. package/dist/_dts/sdk/src/routing/index.d.ts +5 -5
  52. package/dist/_dts/sdk/src/server.d.ts +7 -5
  53. package/dist/_dts/sdk/src/spam-protection/index.d.ts +2 -2
  54. package/dist/_dts/sdk/src/theme/index.d.ts +1 -1
  55. package/dist/_dts/{types-BDF73NzM.d.ts → types-BlaCuPLr.d.ts} +2 -2
  56. package/dist/_dts/{types-Cl0nP6al.d.ts → types-CwtTcaQP.d.ts} +3 -3
  57. package/dist/_dts/{types-mstFvhK4.d.ts → types-D-WElMCy.d.ts} +8 -7
  58. package/dist/_dts/{validation-DVWqSvjK.d.ts → validation-Y5wD9fGK.d.ts} +4 -4
  59. package/dist/client/{BlocksIslandsHydrator-CzKpH9Pm.mjs → BlocksIslandsHydrator-DFqkx158.mjs} +31 -24
  60. package/dist/client/{BookingMailingListNote-rUqsBN7L.mjs → BookingMailingListNote-CCVXX1LN.mjs} +2 -2
  61. package/dist/client/{CalendarNavigationChevron-YGzw2IPB.mjs → CalendarNavigationChevron-DQwJ7BPx.mjs} +167 -18
  62. package/dist/client/{CheckboxChoice-DlTC4J2a.mjs → CheckboxChoice-CZ-anOqV.mjs} +1 -1
  63. package/dist/client/{DemoBookingPortalAccess-D2LyS_Bi.mjs → DemoBookingPortalAccess-DdkY86qI.mjs} +6 -6
  64. package/dist/client/{DemoPortalSignInLink-BaFg2Uit.mjs → DemoPortalSignInLink-B9YrzZt2.mjs} +1 -1
  65. package/dist/client/{EventCalendar.client-tRrhPscX.mjs → EventCalendar.client-DAeQPV76.mjs} +11 -30
  66. package/dist/client/{EventCombined.client-6cfAVtnZ.mjs → EventCombined.client-Bus9R0bj.mjs} +137 -61
  67. package/dist/client/{EventEmbeddedCheckoutStep-CDNUpI0S.mjs → EventEmbeddedCheckoutStep-D_14yqAU.mjs} +27 -2
  68. package/dist/client/{EventItem-dILw2PN_.mjs → EventItem-DPBLjGwj.mjs} +75 -13
  69. package/dist/client/{EventListWeekNavigation-ClgLtjNY.mjs → EventListWeekNavigation-D6cwU82_.mjs} +1 -1
  70. package/dist/client/{EventListing.client-BNueAHmU.mjs → EventListing.client-Bogi_SnJ.mjs} +3 -3
  71. package/dist/client/{EventListing.view-DtVbKVkt.mjs → EventListing.view-CEumpN7i.mjs} +35 -51
  72. package/dist/client/{EventRegistrationPayment-CzkG0NSJ.mjs → EventRegistrationPayment-CIQw6vNy.mjs} +113 -11
  73. package/dist/client/{LocationMapActions-zWQsJhE5.mjs → LocationMapActions-BVO-qx4q.mjs} +2 -2
  74. package/dist/client/{MapDrawingSvg-D1AO_o4h.mjs → MapDrawingSvg-CcGaFawl.mjs} +22 -2
  75. package/dist/client/{Page-DUr2YhFR.mjs → Page-D4_H_u9V.mjs} +23892 -32266
  76. package/dist/client/{ProtectedSubmitButton-2fJqT_NR.mjs → ProtectedSubmitButton-8DuDw2ag.mjs} +1 -1
  77. package/dist/client/{StepIndicator-udNHcpOT.mjs → StepIndicator-Dptantmg.mjs} +3 -3
  78. package/dist/client/{TabBarFragment-C_kt-PXh.mjs → TabBarFragment-BxEGsKUx.mjs} +19 -19
  79. package/dist/client/{ThemedButton-Cfbo1bfh.mjs → ThemedButton-8jUc02mZ.mjs} +64 -2
  80. package/dist/client/{accordion-3CYNWzTS.mjs → accordion--EUHmEGa.mjs} +1 -1
  81. package/dist/client/{booking-form.client-BSbWgLyx.mjs → booking-form.client-BCXwOnhc.mjs} +19 -14
  82. package/dist/client/{bookingForm-2MoFBWSt.mjs → bookingForm-sHHcdism.mjs} +4 -4
  83. package/dist/client/bookings.mjs +6 -6
  84. package/dist/client/{carousel-Cu5mcpO-.mjs → carousel-Cp9xPBFZ.mjs} +2 -2
  85. package/dist/client/{carousel.client-CQLV8_Al.mjs → carousel.client-BO7sCEpH.mjs} +1 -1
  86. package/dist/client/{cart-CDc6x9cR.mjs → cart-CCZZC-Lq.mjs} +3 -3
  87. package/dist/client/{cart.client-BWS2r5Ef.mjs → cart.client-B7JfA19I.mjs} +1 -1
  88. package/dist/client/{checkout-CkxPqSwD.mjs → checkout-CipmYL4A.mjs} +3 -3
  89. package/dist/client/{checkout.client-DJfomKQc.mjs → checkout.client-DraalWdH.mjs} +1 -1
  90. package/dist/client/client.mjs +9550 -17
  91. package/dist/client/{context-CBV21-9L.mjs → context-Cv3QHjAF.mjs} +11 -6
  92. package/dist/client/{cta-Bw-al3cs.mjs → cta-P2vJVTEn.mjs} +45 -28
  93. package/dist/client/{dateFormatting-CFIUJ4Uf.mjs → dateFormatting-D8D47VT4.mjs} +1 -1
  94. package/dist/client/{demoPortalMagicLink-D0veHJyi.mjs → demoPortalMagicLink-CXWZoV-d.mjs} +1 -1
  95. package/dist/client/{enhanceHeaderSection-CEqqq92r.mjs → enhanceHeaderSection-BkAro1DJ.mjs} +4 -4
  96. package/dist/client/{event-details.client-Bk2kQ7ax.mjs → event-details.client-dLmyuPap.mjs} +2 -2
  97. package/dist/client/{event-registration.client-QMqtIywj.mjs → event-registration.client-BEhC2_-Y.mjs} +34 -20
  98. package/dist/client/{eventCalendar-BTDTMosr.mjs → eventCalendar-FBMS2Cpb.mjs} +4 -4
  99. package/dist/client/{eventCombined-BC7a709c.mjs → eventCombined-BrBhUvGe.mjs} +4 -4
  100. package/dist/client/{eventDetails-DL08GpUc.mjs → eventDetails-C7WUrbZ2.mjs} +2 -2
  101. package/dist/client/{eventListing-BfzuEQp_.mjs → eventListing-Bih-BgQM.mjs} +4 -4
  102. package/dist/client/{eventRegistration-Lfyzh1Ab.mjs → eventRegistration-DfTlqGbl.mjs} +4 -4
  103. package/dist/client/{form-L-xZOBUS.mjs → form-Bw1uuiUs.mjs} +3 -3
  104. package/dist/client/{form.client-BtpK3TZW.mjs → form.client-pZ-9gN33.mjs} +5 -5
  105. package/dist/client/{form.parts-Djos5Un4.mjs → form.parts-PXlu6XQO.mjs} +3 -3
  106. package/dist/client/{formatDate-DGmrm7YB.mjs → formatDate-DI3DP48e.mjs} +1 -1
  107. package/dist/client/gifting/client.mjs +3 -4
  108. package/dist/client/{headerSection-f16OGkz-.mjs → headerSection-BpJYUMd6.mjs} +2 -2
  109. package/dist/client/{mediaAssets-DHAmrVIi.mjs → mediaAssets-DpPauppt.mjs} +1 -1
  110. package/dist/client/{mediaContext-CwT6ZOm7.mjs → mediaContext-BLo4NtjP.mjs} +25 -19
  111. package/dist/client/{newsletter-form.client-DpHNZc7k.mjs → newsletter-form.client-CSoP0cGR.mjs} +6 -6
  112. package/dist/client/{newsletter-form.parts-CLGH20PL.mjs → newsletter-form.parts-DDbX_Sj0.mjs} +2 -2
  113. package/dist/client/{newsletterForm-BEU0Ocu9.mjs → newsletterForm-vCxYRar_.mjs} +3 -3
  114. package/dist/client/{noop-CQU7tiMg.mjs → noop-ByVtIWf4.mjs} +420 -170
  115. package/dist/client/portal/client.mjs +13 -14
  116. package/dist/client/{product-detail.client-Be-om1BT.mjs → product-detail.client-7Pi6avM-.mjs} +1 -1
  117. package/dist/client/{product-list.client-DR7hD5Vs.mjs → product-list.client-DEad-Pma.mjs} +1 -1
  118. package/dist/client/{productDetail-BD42UOmG.mjs → productDetail-G1SMXG13.mjs} +3 -3
  119. package/dist/client/{productList-CSk8sXCl.mjs → productList-B21TGdpT.mjs} +3 -3
  120. package/dist/client/{propsDecoder-C_Y6VYnF.mjs → propsDecoder-B3vIBkex.mjs} +4 -5
  121. package/dist/client/{registry.server-CIKtTsCl.mjs → registry.server-B8aQhJpO.mjs} +399 -473
  122. package/dist/client/rendering/client.mjs +29 -28
  123. package/dist/client/rendering/islands.mjs +1 -1
  124. package/dist/client/rendering.mjs +70 -8
  125. package/dist/client/{richText-coerce-spWtx86G.mjs → richText-coerce-DHkBtO0G.mjs} +1 -1
  126. package/dist/client/{routeIslandApiConfig-CROHPlYS.mjs → routeIslandApiConfig-DbHX4JOS.mjs} +1 -1
  127. package/dist/client/{shop-commerce-CDUohm_2.mjs → shop-commerce-B2UmrQg_.mjs} +12 -12
  128. package/dist/client/{shop-commerce-store-B9nw4lRP.mjs → shop-commerce-store-B7n-Z7nY.mjs} +1 -1
  129. package/dist/client/{shop-DscvMz86.mjs → shop-mqyoOvOK.mjs} +3 -3
  130. package/dist/client/{shop.client-M3kNsVPi.mjs → shop.client-BH-BBnA9.mjs} +13 -13
  131. package/dist/client/{shop.interactive-BGmkdIAZ.mjs → shop.interactive-mdM3UMWG.mjs} +74 -36
  132. package/dist/client/{shopShared-BdWp6LHa.mjs → shopShared-CXF5wxdg.mjs} +2 -2
  133. package/dist/client/site-styles-CMCUxsIM.mjs +3 -0
  134. package/dist/{preview-next/client/ThemedButton-Dc6aJ34Z.mjs → client/site-styles-D56hT2u1.mjs} +26000 -16565
  135. package/dist/client/spam-protection.mjs +1 -1
  136. package/dist/client/src-DjnxOjXG.mjs +217 -0
  137. package/dist/client/surfaceTransportMarker-BXepAVF6.mjs +152 -0
  138. package/dist/client/{timetableModel-Dynh5-j4.mjs → timetableModel-CrC80EOG.mjs} +13 -140
  139. package/dist/client/types-sF-IrGQr.mjs +633 -0
  140. package/dist/client/{useAvailableSlots-Cw9paRPY.mjs → useAvailableSlots-C4LOaI_Z.mjs} +8 -5
  141. package/dist/client/{useBookingNowIso-C9SF2rC6.mjs → useBookingNowIso-BDmWkYUW.mjs} +1 -1
  142. package/dist/client/{useDiscountApply-B-QJfBg0.mjs → useDiscountApply-6Q0nToVA.mjs} +3 -3
  143. package/dist/client/{useDiscountCodeUi-Uvum8q9d.mjs → useDiscountCodeUi-CM-DTX5X.mjs} +1 -1
  144. package/dist/client/{useEventPagination-BfM3xk6j.mjs → useEventPagination-Bcs89BR5.mjs} +9 -9
  145. package/dist/client/{view-DlkCDfuN.mjs → view-BN-fxyfq.mjs} +287 -232
  146. package/dist/client/{view-DXOuduIr.mjs → view-Dh2tGoS0.mjs} +4 -4
  147. package/dist/client/{wizardSteps-DManVJpc.mjs → wizardSteps-DtkhwKXK.mjs} +468 -149
  148. package/dist/preview-next/before-render.mjs +3 -140
  149. package/dist/preview-next/client/ArrangementLookControls-D4VjPs-r.mjs +31197 -0
  150. package/dist/preview-next/client/{EventEmbeddedCheckoutStep-Die6Y25O.mjs → EventEmbeddedCheckoutStep-C_h1cMYm.mjs} +33 -4
  151. package/dist/preview-next/client/{LocationPickerEnvironment-Bp4BHLCL.mjs → LocationPickerEnvironment-D56RD3e_.mjs} +1 -1
  152. package/dist/preview-next/client/{MapLibreEditMap-Cb0JhM9p.mjs → MapLibreEditMap-DFnyCckr.mjs} +2 -2
  153. package/dist/preview-next/client/PreviewEditorSidebar-Ckr2zk_L.mjs +37247 -0
  154. package/dist/preview-next/client/{PreviewEditorUI-CxwlLBGw.mjs → PreviewEditorUI-KOZgw_gS.mjs} +45 -17
  155. package/dist/preview-next/client/PreviewShell-CyO2V4kB.mjs +4757 -0
  156. package/dist/preview-next/client/SdkPreviewModeRuntime-DW3uKvNF.mjs +4258 -0
  157. package/dist/preview-next/client/SiteChromeCustomizeButton-CU9VD-7O.mjs +72202 -0
  158. package/dist/preview-next/client/ThemedButton-C0dgGJ5k.mjs +2006 -0
  159. package/dist/preview-next/client/{lucide-react-CqxuVAyz.mjs → lucide-react-CPBCf6QT.mjs} +15 -2
  160. package/dist/preview-next/client/previewAssistantSlot-DBi-WybM.mjs +112193 -0
  161. package/dist/preview-next/client/{previewChromeSurface-yuwnDP3B.mjs → previewChromeSurface-BhkUJst9.mjs} +90 -28
  162. package/dist/preview-next/client/runtime.mjs +3 -3
  163. package/dist/preview-next/client/sdk-runtime-BjCb6lOn.mjs +5 -0
  164. package/dist/preview-next/client/{editorStatusDecision-DR4BBKhy.mjs → useAutosaveStatus-CKxTaC3j.mjs} +40 -3
  165. package/dist/preview-next/client/useBlockCustomizeControls-B7MLTjBX.mjs +2633 -0
  166. package/dist/preview-next/client/useOpenBlockForSetup-BTUc0g9X.mjs +28 -0
  167. package/dist/preview-next/keepAlive.mjs +25 -2
  168. package/dist/preview-next/middleware.mjs +1 -1
  169. package/dist/preview-next/{route-contract-BBAJjFIz.mjs → route-contract-Bv3nkdpV.mjs} +215 -118
  170. package/dist/server/{Block.shared-ClFI3qpX.mjs → Block.shared-4fMqzltx.mjs} +7 -4
  171. package/dist/server/{src-DsYPhTbs.mjs → ThemeScopeCore-C72VC_lR.mjs} +894 -2556
  172. package/dist/server/accessibleSurfaces-B_Y_dA20.mjs +2305 -0
  173. package/dist/server/{bindings-Bi8EoRZD.mjs → bindings-ConMYJ2U.mjs} +2 -3
  174. package/dist/server/{publicProducts-Bz8loTRn.mjs → client-Cot-H5fQ.mjs} +2558 -343
  175. package/dist/server/config-validation.mjs +1 -1
  176. package/dist/server/config.mjs +33 -2
  177. package/dist/server/data/dataLoaderContext.mjs +2 -0
  178. package/dist/server/data/resolveBlockData.mjs +2 -0
  179. package/dist/server/data/types.mjs +1 -0
  180. package/dist/server/dataLoaderContext-B3fXA54R.mjs +47 -0
  181. package/dist/server/identity-Bn9OQiT1.mjs +6 -0
  182. package/dist/server/index.mjs +3 -3
  183. package/dist/server/{loadContent-dEEhQxL7.mjs → loadContent-BkaWYEwt.mjs} +6 -5
  184. package/dist/server/{loadPage-DBFBad8A.mjs → loadPage-kviUdH8c.mjs} +4 -2
  185. package/dist/server/manifest.mjs +1 -1
  186. package/dist/server/media-DnlczCMA.mjs +231 -0
  187. package/dist/server/metadata.mjs +5 -1
  188. package/dist/server/mode-Cv_TG9gP.mjs +63 -0
  189. package/dist/server/next/revalidate.mjs +9 -4
  190. package/dist/server/next.mjs +11 -11
  191. package/dist/server/opaqueSurface-BTnS09GS.mjs +54 -0
  192. package/dist/server/{overrideResolution-BIJbiXYc.mjs → overrideResolution-itXZCXs7.mjs} +2 -1
  193. package/dist/server/overrides-CD4d-1w7.mjs +177 -0
  194. package/dist/server/page-converter.mjs +243 -91
  195. package/dist/server/pageRenderPlan-CDyn7iLy.mjs +4162 -0
  196. package/dist/server/{themeAdmission-CSknYpxk.mjs → pageRuntimeSupport-DZ6cLxrM.mjs} +13 -28
  197. package/dist/server/{overrides-DhF87Vsd.mjs → pageShared-Q_Vij87H.mjs} +3808 -1928
  198. package/dist/server/parseThemeForPersistence-CDrF51tJ.mjs +52 -0
  199. package/dist/server/{prebuild-DaemmWQL.mjs → prebuild-DOG4MkOy.mjs} +1 -1
  200. package/dist/server/prebuild.mjs +1 -1
  201. package/dist/server/prefetchBlockData-DlprLLsc.mjs +756 -0
  202. package/dist/server/{registry-Cdvz1OtL.mjs → registry-BPFcpn6k.mjs} +21838 -709
  203. package/dist/server/rendering/components/pageShared.mjs +2 -0
  204. package/dist/server/rendering/helpers/loadPage.mjs +2 -0
  205. package/dist/server/rendering/helpers/pageRuntimeSupport.mjs +2 -0
  206. package/dist/server/rendering/server.mjs +5 -4
  207. package/dist/server/rendering/themeAdmission.mjs +2 -0
  208. package/dist/server/rendering.mjs +11 -10
  209. package/dist/server/repeaterFields-MIz7r1ez.mjs +9 -0
  210. package/dist/server/{resolveBlockData-CLpAJWWf.mjs → resolveBlockData-BHvfGD4y.mjs} +6 -48
  211. package/dist/server/resolveButtonColourStates-OXFRGn5M.mjs +2682 -0
  212. package/dist/server/responseMedia-D8J3VAFs.mjs +115 -0
  213. package/dist/server/{richTextSchema-YYc85FX4.mjs → richTextSchema-Euhuj-7V.mjs} +26 -1
  214. package/dist/server/routing.mjs +1 -1
  215. package/dist/server/schema-DEizlyi4.mjs +2524 -0
  216. package/dist/server/server.mjs +3 -3
  217. package/dist/server/theme-bridge.mjs +1031 -1
  218. package/dist/server/theme.mjs +2 -1
  219. package/dist/server/themeAdmission-DGSAlFUK.mjs +18 -0
  220. package/dist/server/{three-pass-converter-Chnb1XD-.mjs → three-pass-converter-_j2UE2tR.mjs} +1 -1
  221. package/dist/server/validation-CDd6m8Ry.mjs +140 -0
  222. package/dist/server/{validation-DYxhLzqQ.mjs → validation-bl6WcAi_.mjs} +419 -3
  223. package/dist/server/{version-Beu4q-Gv.mjs → version-BLXZ31S-.mjs} +1 -1
  224. package/dist/styles/index.css +710 -29
  225. package/package.json +39 -1
  226. package/dist/client/events-BmqPeeQm.mjs +0 -20
  227. package/dist/client/purchase-BV5xfaZH.mjs +0 -894
  228. package/dist/client/schema-BdSglH2X.mjs +0 -16084
  229. package/dist/client/site-styles-CWHmlVT5.mjs +0 -14503
  230. package/dist/client/src-VIsPY-kw.mjs +0 -62
  231. package/dist/preview-next/client/PreviewEditorSidebar-DEP3xD9K.mjs +0 -5810
  232. package/dist/preview-next/client/SdkPreviewModeRuntime-Cpe-XP8e.mjs +0 -3
  233. package/dist/preview-next/client/SdkPreviewModeRuntime-QDkMPASV.mjs +0 -8059
  234. package/dist/preview-next/client/SiteChromeCustomizeButton-1JaoGOKX.mjs +0 -9367
  235. package/dist/preview-next/client/previewSidebarNavigation-AXUj9-qQ.mjs +0 -224683
  236. package/dist/preview-next/client/result-BjJUoxUF.mjs +0 -16
  237. package/dist/preview-next/client/sdk-runtime-O-eA9-rV.mjs +0 -4
  238. package/dist/preview-next/refresh-contract-uQ6BXgLJ.mjs +0 -25
  239. package/dist/server/bindings-Dgt_0goJ.mjs +0 -17
  240. package/dist/server/client-DfMDbZ41.mjs +0 -2330
  241. package/dist/server/effectiveNavLinkStyle-BHIYPVG1.mjs +0 -13713
  242. package/dist/server/loadPage-CnVB-aeL.mjs +0 -2
  243. package/dist/server/prefetchBlockData-FwcsT5H2.mjs +0 -4359
  244. package/dist/server/schema-uSA_x1Zh.mjs +0 -16311
  245. package/dist/server/site-styles-CntHn2KI.mjs +0 -793
  246. package/dist/server/siteChromeOverlayClearance-DqP40Ka0.mjs +0 -802
@@ -0,0 +1,4757 @@
1
+ "use client";
2
+ import { i as useOptionalPreviewLayout, t as PreviewQueryProvider } from "./PreviewQueryProvider-BC0V7iAR.mjs";
3
+ import { $c as SITE_STICKY_CHROME_HEIGHT_FALLBACK, Ap as DialogDescription, B as renewPreviewSession, Dp as Dialog, E as PreviewRenderObservationsProvider, Fm as isEdited, G as useEntryEditorController, Gg as buildRenderableMediaAssetIndex, Gt as ApiRequestError, H as usePreviewToken, Jt as createSnapshotFromPageRecord, Kg as renderableMediaAssetSchema$1, L as createGuardedPreviewApiClient, Lt as blocksKeys, Lv as assertNever$2, Mm as cn, Mp as DialogHeader, Np as DialogTitle, Pm as baselineRevisionOf, Qc as SITE_STICKY_CHROME_HEIGHT_CSS_VAR, Qf as API_ENDPOINTS, R as initPreviewAuth, Rm as canEditorWrite, Tm as Button, Tn as unsafeAsLinkedContentEntryId, U as EntryControllerProvider, V as usePreviewAuth, X as useServerRefresh, Xf as observeEditorAdmission, Yf as editorAdmissionSession, Zc as SITE_OVERLAY_HEADER_CLEARANCE_CSS_VAR, Zf as OPERATION_ID_HEADER, _n as remoteDraftValues, _p as Callout, a as PreviewPageDesignEditorStateProvider, at as EditLeaseModal, bn as resolveRenderedValues, cn as parseStoredSidebarWidth, el as measureSiteStickyChromeHeightPx, en as useEditorUiStore, et as savedContentReceipt, f as PreviewThemeJournalProvider, g as previewThemeBase, gn as planLinkedSaveHandoverRetention, h_ as authoredValuesEqual, hn as activeLinkedSaveHandover, i as usePreviewSidebarNavigation, it as EditLeaseDiscardedNotice, iv as unsafeAsEditorBlockId, jp as DialogFooter, kp as DialogContent, l as SiteChromeCustomizeProvider, lt as getEditorClientId, m as usePreviewThemeSourceOptional, nl as planSiteOverlayHeaderClearance, nn as useOptionalEditorUiStoreInstance, nt as useRetentionTicks, ot as EditorWriteSurface, p as usePreviewThemeSource, q_ as parseEditLeaseScope, qf as editorAdmissionNotice, qg as indexRenderableMediaAssets, qt as createRoutingHelpers, r as PreviewSidebarBootstrap, rl as siteTopChromeMeasurementTargets, rp as unwrapResponse, rt as VIEWING_PARTICIPATION, sn as SIDEBAR_WIDTH, t as PreviewAssistantSlotProvider, t_ as assertNever$1, tn as useEditorUiStoreInstance, tt as savedRouteReceipt, vn as renderSourceFor, vp as CalloutDescription, xa as buildResolveImageUrlContext, yl as planSiteChromePlacement, z as registerPreviewRenewalFetcher } from "./previewAssistantSlot-DBi-WybM.mjs";
4
+ import { G as GripVertical } from "./lucide-react-CPBCf6QT.mjs";
5
+ import { $t as getResponsiveScopeSpec, Bt as getLinkedContentEntryMeta, E as usePreviewCompiledTheme, I as SessionJournalHost, Jt as themeRuntimeScopeProps, Kt as buildThemeDataAttrs, N as mergeResolvedDataContext, Qt as DEFAULT_THEME_RESPONSIVE_MODE, R as renderSiteChromeBlock, Rt as LINKED_CONTENT_ENTRY_META_KEY, T as PreviewThemeRenderingProvider, V as createEditorApiClientFactory, Xt as escapeStyleContent, Z as MediaEditorContextProvider, a as PreviewChromeLayerProvider, an as TabsContent, b as SiteFontStorageProvider, bn as parseFooterModuleId, bt as ThemeScopeCore, c as PREVIEW_SITE_BANNER_ATTRIBUTE, en as Toaster, et as useApiMediaUploader, f as canInspectSiteStyle, g as sanitizeDashboardPath, h as resolvePreviewDashboardSetupHandoff, in as Tabs, it as ImageResolveContextProvider, m as buildPreviewDashboardSetupUrl, on as TabsList, p as resolveSiteStyleAccess, sn as TabsTrigger, st as BlockApiProvider, t as SiteChromeCustomizeButton, v as resolvePreviewSetupBannerModel, w as PreviewCompiledThemeProvider, xt as containerResponsiveThemeCss, yt as revealEditorElement } from "./SiteChromeCustomizeButton-CU9VD-7O.mjs";
6
+ import { n as LocationPickerEnvironmentProvider } from "./LocationPickerEnvironment-D56RD3e_.mjs";
7
+ import { a as resolvePreviewChromeSurface, c as writePreviewThemeCookie, d as EditorProvider, f as useEditor, i as getPreviewChromeSurfaceDataProps, l as PREVIEW_KEEP_ALIVE_INTERVAL_MS, n as PREVIEW_CHROME_THEME_CLASS_NAME, o as readPreviewThemeCookie, p as FixedBottomSurface, s as subscribePreviewThemeCookie, u as PREVIEW_KEEP_ALIVE_JITTER_RATIO } from "./previewChromeSurface-BhkUJst9.mjs";
8
+ import React, { Children, Fragment, cloneElement, createContext, isValidElement, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
9
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
10
+ import { useQueryClient } from "@tanstack/react-query";
11
+ import { z } from "zod";
12
+ import { useRouter } from "next/navigation";
13
+ //#region ../ui/src/resizable-split-pane.tsx
14
+ /**
15
+ * Resizable split pane component
16
+ *
17
+ * Two-panel layout with draggable resize handle.
18
+ * On mobile (<1024px), switches to tabs.
19
+ */
20
+ /** The right pane's width for a container: within its own bounds, leaving the left pane at least `minLeft` where it can. */
21
+ function clampPaneWidth(px, containerWidth, bounds) {
22
+ const roomBesideLeft = containerWidth > 0 ? containerWidth - bounds.minLeft : bounds.max;
23
+ return Math.round(Math.max(bounds.min, Math.min(px, bounds.max, roomBesideLeft)));
24
+ }
25
+ const KEYBOARD_RESIZE_STEP = 16;
26
+ function ResizableSplitPane({ left, right, defaultSplit = 40, minLeftWidth = 300, minRightWidth = 400, leftLabel = "Editor", rightLabel = "Preview", defaultTab = "left", className, leftPaneClassName, rightPaneClassName, onSplitChange, splitPercent: controlledSplitPercent, rightWidth }) {
27
+ const [internalSplitPercent, setInternalSplitPercent] = useState(defaultSplit);
28
+ const [isDragging, setIsDragging] = useState(false);
29
+ const [isMobile, setIsMobile] = useState(false);
30
+ const containerRef = useRef(null);
31
+ const pixelPane = usePixelRightPane(rightWidth, containerRef, isMobile, rightLabel);
32
+ const splitPercent = controlledSplitPercent ?? internalSplitPercent;
33
+ const setSplitPercent = useCallback((value) => {
34
+ setInternalSplitPercent(value);
35
+ onSplitChange?.(value);
36
+ }, [onSplitChange]);
37
+ useEffect(() => {
38
+ const checkMobile = () => {
39
+ setIsMobile(window.innerWidth < 1024);
40
+ };
41
+ checkMobile();
42
+ window.addEventListener("resize", checkMobile);
43
+ return () => window.removeEventListener("resize", checkMobile);
44
+ }, []);
45
+ const handleMouseDown = useCallback((e) => {
46
+ e.preventDefault();
47
+ setIsDragging(true);
48
+ }, []);
49
+ const handleMouseMove = useCallback((e) => {
50
+ if (!isDragging || !containerRef.current) return;
51
+ const containerRect = containerRef.current.getBoundingClientRect();
52
+ const containerWidth = containerRect.width;
53
+ if (pixelPane) return pixelPane.dragTo(containerRect.right - e.clientX);
54
+ let newSplitPercent = (e.clientX - containerRect.left) / containerWidth * 100;
55
+ const minLeftPercent = minLeftWidth / containerWidth * 100;
56
+ const minRightPercent = minRightWidth / containerWidth * 100;
57
+ newSplitPercent = Math.max(minLeftPercent, newSplitPercent);
58
+ newSplitPercent = Math.min(100 - minRightPercent, newSplitPercent);
59
+ setSplitPercent(newSplitPercent);
60
+ }, [
61
+ isDragging,
62
+ minLeftWidth,
63
+ minRightWidth,
64
+ setSplitPercent,
65
+ pixelPane
66
+ ]);
67
+ const handleMouseUp = useCallback(() => {
68
+ setIsDragging(false);
69
+ }, []);
70
+ useEffect(() => {
71
+ if (isDragging) {
72
+ document.addEventListener("mousemove", handleMouseMove);
73
+ document.addEventListener("mouseup", handleMouseUp);
74
+ return () => {
75
+ document.removeEventListener("mousemove", handleMouseMove);
76
+ document.removeEventListener("mouseup", handleMouseUp);
77
+ };
78
+ }
79
+ }, [
80
+ isDragging,
81
+ handleMouseMove,
82
+ handleMouseUp
83
+ ]);
84
+ if (isMobile) return /* @__PURE__ */ jsx("div", {
85
+ className: cn("h-full min-h-0 overflow-hidden", className),
86
+ children: /* @__PURE__ */ jsxs(Tabs, {
87
+ defaultValue: defaultTab,
88
+ className: "flex h-full flex-col",
89
+ children: [
90
+ /* @__PURE__ */ jsxs(TabsList, {
91
+ className: "w-full justify-start rounded-none border-b",
92
+ children: [/* @__PURE__ */ jsx(TabsTrigger, {
93
+ value: "left",
94
+ className: "flex-1",
95
+ children: leftLabel
96
+ }), /* @__PURE__ */ jsx(TabsTrigger, {
97
+ value: "right",
98
+ className: "flex-1",
99
+ children: rightLabel
100
+ })]
101
+ }),
102
+ /* @__PURE__ */ jsx(TabsContent, {
103
+ value: "left",
104
+ forceMount: true,
105
+ className: "flex-1 overflow-auto min-h-0 data-[state=inactive]:hidden",
106
+ children: left
107
+ }),
108
+ /* @__PURE__ */ jsx(TabsContent, {
109
+ value: "right",
110
+ forceMount: true,
111
+ className: "flex-1 overflow-auto min-h-0 data-[state=inactive]:hidden",
112
+ children: right
113
+ })
114
+ ]
115
+ })
116
+ });
117
+ const sizing = paneSizing(pixelPane, splitPercent);
118
+ return /* @__PURE__ */ jsxs("div", {
119
+ ref: containerRef,
120
+ "data-testid": "resizable-split-pane",
121
+ className: cn("relative flex h-full min-h-0 overflow-hidden", className),
122
+ style: { cursor: isDragging ? "col-resize" : void 0 },
123
+ children: [
124
+ /* @__PURE__ */ jsx("div", {
125
+ className: cn("h-full min-h-0 overflow-auto", sizing.leftClassName, leftPaneClassName),
126
+ style: sizing.leftStyle,
127
+ children: left
128
+ }),
129
+ /* @__PURE__ */ jsx("div", {
130
+ "data-testid": "resizable-split-pane-handle",
131
+ role: "separator",
132
+ "aria-orientation": "vertical",
133
+ ...sizing.separatorProps,
134
+ className: cn("focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "group relative flex w-1.5 flex-shrink-0 cursor-col-resize items-center justify-center border-x bg-border/30 transition-colors hover:bg-border", isDragging && "bg-primary"),
135
+ onMouseDown: handleMouseDown,
136
+ children: /* @__PURE__ */ jsx("div", {
137
+ className: "absolute inset-y-0 flex items-center",
138
+ children: /* @__PURE__ */ jsx(GripVertical, { className: cn("h-3 w-3 text-muted-foreground transition-colors group-hover:text-foreground", isDragging && "text-primary-foreground") })
139
+ })
140
+ }),
141
+ /* @__PURE__ */ jsx("div", {
142
+ className: cn("relative z-10 h-full min-h-0 shrink-0 overflow-auto", rightPaneClassName),
143
+ style: sizing.rightStyle,
144
+ children: right
145
+ }),
146
+ isDragging && /* @__PURE__ */ jsx("div", { className: "pointer-events-none fixed inset-0 z-50 cursor-col-resize" })
147
+ ]
148
+ });
149
+ }
150
+ /**
151
+ * The right pane's pixel width for the container it is in, with drag and
152
+ * keyboard resizing. Null when the pane is sized by percentage.
153
+ */
154
+ function usePixelRightPane(rightWidth, containerRef, isMobile, rightLabel) {
155
+ const [containerWidth, setContainerWidth] = useState(0);
156
+ useEffect(() => {
157
+ const container = containerRef.current;
158
+ if (!rightWidth || !container) return;
159
+ const observer = new ResizeObserver(([entry]) => setContainerWidth(entry?.contentRect.width ?? 0));
160
+ observer.observe(container);
161
+ return () => observer.disconnect();
162
+ }, [
163
+ rightWidth,
164
+ containerRef,
165
+ isMobile
166
+ ]);
167
+ if (!rightWidth) return null;
168
+ const width = clampPaneWidth(rightWidth.px, containerWidth, rightWidth);
169
+ const resizeTo = (px) => rightWidth.onChange(clampPaneWidth(px, containerWidth, rightWidth));
170
+ return {
171
+ width,
172
+ dragTo: resizeTo,
173
+ separatorProps: pixelSeparatorProps(rightWidth, width, rightLabel, resizeTo)
174
+ };
175
+ }
176
+ /** The separator as a keyboard control: Left widens the right pane, Right narrows it. */
177
+ function pixelSeparatorProps(bounds, width, rightLabel, resizeTo) {
178
+ return {
179
+ tabIndex: 0,
180
+ "aria-label": `Resize ${rightLabel.toLocaleLowerCase()}`,
181
+ "aria-valuenow": width,
182
+ "aria-valuemin": bounds.min,
183
+ "aria-valuemax": bounds.max,
184
+ onKeyDown: (event) => {
185
+ const delta = KEYBOARD_RESIZE_DELTAS[event.key];
186
+ if (!delta) return;
187
+ event.preventDefault();
188
+ resizeTo(width + delta);
189
+ }
190
+ };
191
+ }
192
+ const KEYBOARD_RESIZE_DELTAS = {
193
+ ArrowLeft: KEYBOARD_RESIZE_STEP,
194
+ ArrowRight: -16
195
+ };
196
+ /** Pane widths and separator behaviour for either sizing mode. */
197
+ function paneSizing(pixelPane, splitPercent) {
198
+ if (pixelPane) return {
199
+ leftClassName: "min-w-0 flex-1",
200
+ leftStyle: void 0,
201
+ rightStyle: { width: `${pixelPane.width}px` },
202
+ separatorProps: pixelPane.separatorProps
203
+ };
204
+ return {
205
+ leftClassName: void 0,
206
+ leftStyle: { width: `${splitPercent}%` },
207
+ rightStyle: { width: `${100 - splitPercent}%` },
208
+ separatorProps: {}
209
+ };
210
+ }
211
+ //#endregion
212
+ //#region ../ui/src/toast.tsx
213
+ function ToastProvider() {
214
+ return /* @__PURE__ */ jsx(Toaster, {
215
+ position: "bottom-right",
216
+ offset: {
217
+ right: "calc(var(--assistant-dock-inset, 0px) + 24px)",
218
+ bottom: "24px"
219
+ },
220
+ richColors: false,
221
+ className: "rb-sonner-toaster",
222
+ toastOptions: { classNames: {
223
+ toast: "rb-sonner-toast",
224
+ success: "rb-sonner-toast-success",
225
+ info: "rb-sonner-toast-info",
226
+ error: "rb-sonner-toast-error"
227
+ } }
228
+ });
229
+ }
230
+ //#endregion
231
+ //#region ../theme-core/src/ResponsiveScope.tsx
232
+ /**
233
+ * Structural responsive root for SDK/runtime chrome that opts out of CMS theme
234
+ * styling but still depends on scoped rb-* responsive utility classes.
235
+ */
236
+ function ResponsiveScope({ children, responsiveMode = DEFAULT_THEME_RESPONSIVE_MODE, className }) {
237
+ const responsiveScope = getResponsiveScopeSpec(responsiveMode);
238
+ const isContainerResponsive = responsiveScope.kind === "container";
239
+ const wrapperStyle = isContainerResponsive ? {
240
+ containerType: "inline-size",
241
+ containerName: responsiveScope.containerName
242
+ } : {};
243
+ return /* @__PURE__ */ jsxs("div", {
244
+ className: className ? `theme-scope ${className}` : "theme-scope",
245
+ style: wrapperStyle,
246
+ "data-rb-responsive-mode": responsiveScope.kind,
247
+ children: [isContainerResponsive && /* @__PURE__ */ jsx("style", {
248
+ "data-container-responsive-overrides": true,
249
+ dangerouslySetInnerHTML: { __html: escapeStyleContent(containerResponsiveThemeCss) }
250
+ }), children]
251
+ });
252
+ }
253
+ //#endregion
254
+ //#region ../theme-core/src/SiteStickyChromeOffset.tsx
255
+ /**
256
+ * Publishes how far a sticky or fixed site header reaches below the top of the
257
+ * page as {@link SITE_STICKY_CHROME_HEIGHT_CSS_VAR} on its own site document
258
+ * layout. Sticky page columns (.rb-sticky-below-site-chrome) and anchor targets
259
+ * inside the layout read it, so they stay clear of the header as it shrinks,
260
+ * wraps or gains a banner. The layout renders a fallback until this measures.
261
+ */
262
+ function SiteStickyChromeOffset() {
263
+ const markerRef = useRef(null);
264
+ useEffect(() => {
265
+ const layoutRoot = markerRef.current?.closest("[data-site-document-layout]");
266
+ if (!layoutRoot) return void 0;
267
+ const publish = () => {
268
+ layoutRoot.style.setProperty(SITE_STICKY_CHROME_HEIGHT_CSS_VAR, `${measureSiteStickyChromeHeightPx(layoutRoot)}px`);
269
+ };
270
+ const targets = siteTopChromeMeasurementTargets(void 0, layoutRoot);
271
+ const shells = targets.flatMap((target) => target.parentElement ? [target.parentElement] : []);
272
+ const observer = new ResizeObserver(publish);
273
+ for (const target of /* @__PURE__ */ new Set([...targets, ...shells])) observer.observe(target);
274
+ return () => {
275
+ observer.disconnect();
276
+ layoutRoot.style.removeProperty(SITE_STICKY_CHROME_HEIGHT_CSS_VAR);
277
+ };
278
+ }, []);
279
+ return /* @__PURE__ */ jsx("span", {
280
+ ref: markerRef,
281
+ hidden: true,
282
+ "data-site-sticky-chrome-offset": ""
283
+ });
284
+ }
285
+ //#endregion
286
+ //#region ../theme-core/src/siteChromePlanning.ts
287
+ function planSiteDocument(input) {
288
+ const placement = planSiteChromePlacement(input.hasVisibleHeader ?? true ? input.headerPositioning : "static");
289
+ const topShell = planSiteTopShell(input);
290
+ const layoutMode = topShell.contentStartsUnderHeader ? "header-overlay" : "normal-flow";
291
+ return {
292
+ placement,
293
+ topShell,
294
+ layoutMode,
295
+ overlayHeaderClearance: planSiteOverlayHeaderClearance({
296
+ topShell,
297
+ layoutMode
298
+ })
299
+ };
300
+ }
301
+ function planSiteTopShell(input) {
302
+ if (input.hasVisibleHeader === false) return {
303
+ behavior: "normal-flow",
304
+ contentStartsUnderHeader: false,
305
+ requiresHeaderOffset: false
306
+ };
307
+ const isOverlayHeader = input.headerVariant === "floating" && (input.headerPositioning === "sticky" || input.headerPositioning === "fixed");
308
+ if (input.hasVisibleBanner && isOverlayHeader) return {
309
+ behavior: "banner-above-overlay-header",
310
+ contentStartsUnderHeader: true,
311
+ requiresHeaderOffset: true
312
+ };
313
+ if (input.hasVisibleBanner && (input.headerPositioning === "sticky" || input.headerPositioning === "fixed")) return {
314
+ behavior: "shared-sticky-shell",
315
+ contentStartsUnderHeader: false,
316
+ requiresHeaderOffset: false
317
+ };
318
+ return {
319
+ behavior: "normal-flow",
320
+ contentStartsUnderHeader: isOverlayHeader,
321
+ requiresHeaderOffset: false
322
+ };
323
+ }
324
+ //#endregion
325
+ //#region ../theme-core/src/siteChrome.tsx
326
+ const SITE_CHROME_CLASS_NAMES = {
327
+ standaloneStickyHeaderShell: "sticky top-0 z-40 w-full",
328
+ standaloneFixedHeaderShell: "fixed left-0 right-0 top-0 z-40 w-full",
329
+ sharedStickyTopShell: "rb-sticky rb-top-0 rb-z-40 rb-w-full",
330
+ defaultMinHeight: "rb-min-h-screen",
331
+ fullMinHeight: "rb-min-h-full",
332
+ overlayRoot: "rb-grid rb-grid-rows-main-footer rb-grid-cols-1",
333
+ normalFlowRoot: "rb-flex rb-flex-col",
334
+ overlayTopShell: "rb-row-start-1 rb-col-start-1 rb-z-40",
335
+ overlayTopShellPlacementMarker: "rb-site-document-overlay-top-shell",
336
+ overlayContent: "rb-row-start-1 rb-col-start-1",
337
+ overlayFooter: "rb-row-start-2 rb-col-start-1",
338
+ normalFlowContent: "rb-flex-1"
339
+ };
340
+ function renderSiteTopChrome({ headerNode, bannerNode = null, bannerShellBehavior = "normal-flow" }) {
341
+ switch (bannerShellBehavior) {
342
+ case "normal-flow": return /* @__PURE__ */ jsxs(Fragment$1, { children: [headerNode, bannerNode] });
343
+ case "shared-sticky-shell": return /* @__PURE__ */ jsxs("div", {
344
+ className: SITE_CHROME_CLASS_NAMES.sharedStickyTopShell,
345
+ children: [headerNode, bannerNode]
346
+ });
347
+ case "banner-above-overlay-header": return /* @__PURE__ */ jsxs(Fragment$1, { children: [bannerNode, headerNode] });
348
+ default: return assertNever$1(bannerShellBehavior);
349
+ }
350
+ }
351
+ function SiteDocumentLayout({ plan, headerNode, bannerNode = null, footerNode, children, as: Root = "div", role, className = null, minHeightClassName = SITE_CHROME_CLASS_NAMES.defaultMinHeight, contentClassName = null, style }) {
352
+ const isHeaderOverlay = plan.layoutMode === "header-overlay";
353
+ const stickyChromeOffset = renderStickyChromeOffset(plan);
354
+ const topShell = renderSiteTopChrome({
355
+ headerNode,
356
+ bannerNode,
357
+ bannerShellBehavior: plan.topShell.behavior
358
+ });
359
+ const layoutStyle = stickyChromeLayoutStyle(plan, style);
360
+ const rootStyle = isHeaderOverlay ? {
361
+ ...layoutStyle,
362
+ gridTemplateColumns: "minmax(0, 1fr)",
363
+ gridTemplateRows: "1fr auto"
364
+ } : layoutStyle;
365
+ const rootClassName = joinSiteChromeClassNames(minHeightClassName, isHeaderOverlay ? SITE_CHROME_CLASS_NAMES.overlayRoot : SITE_CHROME_CLASS_NAMES.normalFlowRoot, className);
366
+ if (isHeaderOverlay) {
367
+ const contentStyle = plan.overlayHeaderClearance.kind === "opening-content" ? {
368
+ gridColumn: "1",
369
+ gridRow: "1",
370
+ [SITE_OVERLAY_HEADER_CLEARANCE_CSS_VAR]: plan.overlayHeaderClearance.cssValue
371
+ } : {
372
+ gridColumn: "1",
373
+ gridRow: "1"
374
+ };
375
+ return /* @__PURE__ */ jsxs(Root, {
376
+ role,
377
+ className: rootClassName,
378
+ style: rootStyle,
379
+ "data-site-document-layout": "",
380
+ "data-site-document-layout-mode": plan.layoutMode,
381
+ children: [
382
+ /* @__PURE__ */ jsx("div", {
383
+ className: joinSiteChromeClassNames(SITE_CHROME_CLASS_NAMES.overlayTopShell, SITE_CHROME_CLASS_NAMES.overlayTopShellPlacementMarker, plan.placement.headerRootClassName),
384
+ "data-site-document-overlay-top-shell": "",
385
+ style: {
386
+ gridColumn: "1",
387
+ gridRow: "1",
388
+ alignSelf: "start"
389
+ },
390
+ children: topShell
391
+ }),
392
+ stickyChromeOffset,
393
+ /* @__PURE__ */ jsx("div", {
394
+ "data-site-document-overlay-content": plan.overlayHeaderClearance.kind === "opening-content" ? "true" : void 0,
395
+ className: joinSiteChromeClassNames(SITE_CHROME_CLASS_NAMES.overlayContent, contentClassName),
396
+ style: contentStyle,
397
+ children
398
+ }),
399
+ /* @__PURE__ */ jsx("div", {
400
+ className: SITE_CHROME_CLASS_NAMES.overlayFooter,
401
+ style: {
402
+ gridColumn: "1",
403
+ gridRow: "2"
404
+ },
405
+ children: footerNode
406
+ })
407
+ ]
408
+ });
409
+ }
410
+ return /* @__PURE__ */ jsxs(Root, {
411
+ role,
412
+ className: rootClassName,
413
+ style: layoutStyle,
414
+ "data-site-document-layout": "",
415
+ "data-site-document-layout-mode": plan.layoutMode,
416
+ children: [
417
+ topShell,
418
+ stickyChromeOffset,
419
+ /* @__PURE__ */ jsx("div", {
420
+ className: joinSiteChromeClassNames(SITE_CHROME_CLASS_NAMES.normalFlowContent, contentClassName),
421
+ children
422
+ }),
423
+ footerNode
424
+ ]
425
+ });
426
+ }
427
+ /**
428
+ * A header that stays on screen gets a guessed height from the server, so a
429
+ * link straight to a section clears it before the layout has measured it.
430
+ */
431
+ function stickyChromeLayoutStyle(plan, style) {
432
+ return plan.placement.kind === "static" ? style : {
433
+ ...style,
434
+ [SITE_STICKY_CHROME_HEIGHT_CSS_VAR]: SITE_STICKY_CHROME_HEIGHT_FALLBACK
435
+ };
436
+ }
437
+ /** Only a header that stays on screen needs its height published. */
438
+ function renderStickyChromeOffset(plan) {
439
+ return plan.placement.kind === "static" ? null : /* @__PURE__ */ jsx(SiteStickyChromeOffset, {});
440
+ }
441
+ function joinSiteChromeClassNames(...values) {
442
+ const className = values.filter(Boolean).join(" ");
443
+ return className.length > 0 ? className : void 0;
444
+ }
445
+ //#endregion
446
+ //#region ../api/src/siteOnboarding.ts
447
+ const LAUNCH_REQUIREMENT_OVERRIDE_DEFINITIONS = { configure_appointments: {
448
+ requirementId: "configure_appointments",
449
+ reason: "launch_anyway"
450
+ } };
451
+ z.discriminatedUnion("requirementId", [z.object({ requirementId: z.literal("review_generated_site") }), z.object({
452
+ requirementId: z.literal(LAUNCH_REQUIREMENT_OVERRIDE_DEFINITIONS.configure_appointments.requirementId),
453
+ overrideReason: z.literal(LAUNCH_REQUIREMENT_OVERRIDE_DEFINITIONS.configure_appointments.reason)
454
+ })]);
455
+ z.object({ acceptExtraSiteCharge: z.boolean().optional() });
456
+ //#endregion
457
+ //#region ../api/src/launchRequirementPriority.ts
458
+ const REQUIREMENT_PRIORITIES = {
459
+ confirm_email: "required",
460
+ review_generated_site: "required",
461
+ configure_appointments: "required",
462
+ configure_events: "required",
463
+ configure_courses: "recommended",
464
+ connect_payments: "required",
465
+ add_first_offering: "recommended",
466
+ add_cover_image: "recommended",
467
+ add_public_contact: "recommended"
468
+ };
469
+ /** A booking page can go live with bookings setup still unfinished. */
470
+ const HOSTED_BOOKING_PRIORITIES = {
471
+ configure_appointments: "recommended",
472
+ configure_events: "recommended"
473
+ };
474
+ function requirementPriorityFor(id, publicExperience = "website") {
475
+ return (publicExperience === "hosted_booking" ? HOSTED_BOOKING_PRIORITIES[id] : void 0) ?? REQUIREMENT_PRIORITIES[id];
476
+ }
477
+ //#endregion
478
+ //#region ../api/src/launchReadiness.ts
479
+ const DEFAULT_LAUNCH_READINESS_INPUT = {
480
+ siteId: null,
481
+ email: { kind: "pending_confirmation" },
482
+ reviewGeneratedSite: { kind: "pending_review" },
483
+ appointments: { kind: "disabled" },
484
+ events: { kind: "disabled" },
485
+ courses: { kind: "not_applicable" },
486
+ payments: { kind: "not_applicable" },
487
+ offerings: { kind: "none" },
488
+ coverImage: { kind: "missing" },
489
+ publicContact: { kind: "missing" },
490
+ overrides: []
491
+ };
492
+ function makeDashboardPath(siteId, path) {
493
+ if (!siteId) return null;
494
+ return `/dashboard/sites/${siteId}${path}`;
495
+ }
496
+ function informationalAction(label) {
497
+ return {
498
+ kind: "informational_only",
499
+ label
500
+ };
501
+ }
502
+ function openDashboardPathAction(siteId, path, label) {
503
+ const dashboardPath = makeDashboardPath(siteId, path);
504
+ if (!dashboardPath) return informationalAction(label);
505
+ return {
506
+ kind: "open_dashboard_path",
507
+ label,
508
+ path: dashboardPath
509
+ };
510
+ }
511
+ function appendQueryString(path, query) {
512
+ const params = new URLSearchParams();
513
+ for (const [key, value] of Object.entries(query)) if (value) params.set(key, value);
514
+ const queryString = params.toString();
515
+ return queryString ? `${path}?${queryString}` : path;
516
+ }
517
+ function evidenceFromDerivedState(state) {
518
+ return state === "complete" ? { kind: "derived" } : {
519
+ kind: "deferred",
520
+ reason: "pending_setup"
521
+ };
522
+ }
523
+ function requirement(publicExperience, input) {
524
+ return {
525
+ ...input,
526
+ priority: requirementPriorityFor(input.id, publicExperience)
527
+ };
528
+ }
529
+ /** The shared fields of a requirement derived from a done/not-done fact. */
530
+ function derivedFields(context, spec) {
531
+ const state = spec.complete ? "complete" : "pending";
532
+ const [title, description] = spec.copy[state];
533
+ return {
534
+ packId: spec.packId,
535
+ owner: "admin",
536
+ title,
537
+ description,
538
+ action: openDashboardPathAction(context.siteId, spec.path, spec.actionLabel),
539
+ evidence: evidenceFromDerivedState(state)
540
+ };
541
+ }
542
+ function derivedRequirement(context, spec) {
543
+ return requirement(context.publicExperience, {
544
+ ...derivedFields(context, spec),
545
+ id: spec.id,
546
+ state: spec.complete ? "complete" : "pending"
547
+ });
548
+ }
549
+ function onlyForBookingPages(context, build) {
550
+ return context.publicExperience === "hosted_booking" ? [build()] : [];
551
+ }
552
+ function buildGoLiveDecision(requirements) {
553
+ const pendingRequiredRequirements = requirements.filter((item) => item.priority === "required" && item.state === "pending");
554
+ const overriddenRequirementIds = pendingRequiredRequirements.filter((item) => item.evidence.kind === "overridden").map((item) => item.id);
555
+ const blockingRequirementIds = pendingRequiredRequirements.filter((item) => item.evidence.kind !== "overridden").map((item) => item.id);
556
+ return blockingRequirementIds.length > 0 ? {
557
+ kind: "blocked",
558
+ blockingRequirementIds,
559
+ overriddenRequirementIds
560
+ } : {
561
+ kind: "allowed",
562
+ overriddenRequirementIds
563
+ };
564
+ }
565
+ function findLaunchOverride(overrides, requirementId) {
566
+ return overrides.find((override) => override.requirementId === requirementId) ?? null;
567
+ }
568
+ function confirmEmailRequirement(context, email) {
569
+ const state = email.kind === "confirmed" ? "complete" : "pending";
570
+ return requirement(context.publicExperience, {
571
+ id: "confirm_email",
572
+ packId: "core",
573
+ state,
574
+ owner: "either",
575
+ title: "Confirm your email",
576
+ description: state === "complete" ? "Email confirmed. Your dashboard and launch path are unlocked." : "Confirm your email before the site can go live.",
577
+ action: informationalAction("Confirm your email"),
578
+ evidence: evidenceFromDerivedState(state)
579
+ });
580
+ }
581
+ function generatedSiteReviewRequirements(context, reviewGeneratedSite) {
582
+ if (context.publicExperience === "hosted_booking") return [];
583
+ const isGeneratedSiteReviewed = reviewGeneratedSite.kind === "reviewed";
584
+ return [requirement(context.publicExperience, {
585
+ id: "review_generated_site",
586
+ packId: "core",
587
+ state: isGeneratedSiteReviewed ? "complete" : "pending",
588
+ owner: "admin",
589
+ title: "Check your pages",
590
+ description: isGeneratedSiteReviewed ? "You've read through your pages and confirmed they look good." : "We wrote a first draft of every page when we set up your site. Read through each one and change anything that doesn't feel like you.",
591
+ action: isGeneratedSiteReviewed ? informationalAction("Review complete") : {
592
+ kind: "acknowledge_requirement",
593
+ label: "I've checked it",
594
+ requirementId: "review_generated_site",
595
+ acknowledgementKind: "review"
596
+ },
597
+ evidence: isGeneratedSiteReviewed ? {
598
+ kind: "acknowledged",
599
+ acknowledgedAt: reviewGeneratedSite.reviewedAt,
600
+ acknowledgedBy: reviewGeneratedSite.reviewedBy
601
+ } : {
602
+ kind: "deferred",
603
+ reason: "pending_acknowledgement"
604
+ }
605
+ })];
606
+ }
607
+ /** Booking pages have no "launch anyway": appointments never block them. */
608
+ function appointmentsOverrideFor(context, input) {
609
+ if (context.publicExperience === "hosted_booking" || input.appointments.kind !== "pending_setup") return null;
610
+ return findLaunchOverride(input.overrides ?? [], LAUNCH_REQUIREMENT_OVERRIDE_DEFINITIONS.configure_appointments.requirementId);
611
+ }
612
+ function appointmentsSecondaryAction(context, appointments, override) {
613
+ if (appointments.kind !== "pending_setup" || context.publicExperience === "hosted_booking") return null;
614
+ if (override) return informationalAction("Launch override saved");
615
+ const definition = LAUNCH_REQUIREMENT_OVERRIDE_DEFINITIONS.configure_appointments;
616
+ return {
617
+ kind: "acknowledge_requirement",
618
+ label: "Launch anyway",
619
+ requirementId: definition.requirementId,
620
+ acknowledgementKind: "override",
621
+ overrideReason: definition.reason
622
+ };
623
+ }
624
+ function appointmentsDescription(appointments, override) {
625
+ if (appointments.kind === "ready") return "Appointments have at least one bookable service with a practitioner and availability.";
626
+ return override ? "Appointment setup is still unfinished. You chose to launch anyway and finish it later." : "Finish appointment setup so customers can book at least one service before launch, or launch anyway and come back later.";
627
+ }
628
+ function appointmentsRequirements(context, input) {
629
+ const appointments = input.appointments;
630
+ if (appointments.kind === "disabled") return [];
631
+ const override = appointmentsOverrideFor(context, input);
632
+ const state = appointments.kind === "ready" ? "complete" : "pending";
633
+ const path = appointments.kind === "pending_setup" ? appendQueryString("/bookings/appointments/setup", {
634
+ step: appointments.targetStep,
635
+ returnTo: "launch"
636
+ }) : "/bookings/services";
637
+ const evidence = override ? {
638
+ kind: "overridden",
639
+ reason: override.reason,
640
+ acknowledgedAt: override.acknowledgedAt,
641
+ acknowledgedBy: override.acknowledgedBy
642
+ } : evidenceFromDerivedState(state);
643
+ const fields = {
644
+ packId: "bookings_appointments",
645
+ owner: "admin",
646
+ title: "Configure appointments",
647
+ description: appointmentsDescription(appointments, override),
648
+ action: openDashboardPathAction(context.siteId, path, "Set up appointments"),
649
+ secondaryAction: appointmentsSecondaryAction(context, appointments, override),
650
+ evidence
651
+ };
652
+ return [requirement(context.publicExperience, appointments.kind === "pending_setup" ? {
653
+ ...fields,
654
+ id: "configure_appointments",
655
+ state: "pending",
656
+ detail: {
657
+ kind: "appointments_gap",
658
+ missing: appointments.missing
659
+ }
660
+ } : {
661
+ ...fields,
662
+ id: "configure_appointments",
663
+ state: "complete"
664
+ })];
665
+ }
666
+ function eventsRequirements(context, events) {
667
+ if (events.kind === "disabled") return [];
668
+ const fields = derivedFields(context, {
669
+ packId: "bookings_events",
670
+ complete: events.kind === "ready",
671
+ copy: {
672
+ complete: ["Configure events", "Events already include at least one future-dated offering."],
673
+ pending: ["Configure events", "Create at least one future-dated event offering before launch."]
674
+ },
675
+ path: "/bookings/events/new",
676
+ actionLabel: "Create an event"
677
+ });
678
+ return [requirement(context.publicExperience, events.kind === "pending_setup" ? {
679
+ ...fields,
680
+ id: "configure_events",
681
+ state: "pending",
682
+ detail: {
683
+ kind: "event_kinds",
684
+ offeredKinds: events.offeredKinds
685
+ }
686
+ } : {
687
+ ...fields,
688
+ id: "configure_events",
689
+ state: "complete"
690
+ })];
691
+ }
692
+ function coursesRequirements(context, courses) {
693
+ if (courses.kind === "not_applicable") return [];
694
+ return [derivedRequirement(context, {
695
+ id: "configure_courses",
696
+ packId: "bookings_courses",
697
+ complete: courses.kind === "ready",
698
+ copy: {
699
+ complete: ["Configure courses", "Courses already include at least one real course run."],
700
+ pending: ["Configure courses", "You chose courses during setup. Add your first course when you're ready so the dashboard reflects that plan."]
701
+ },
702
+ path: "/bookings/events/new/course",
703
+ actionLabel: "Create a course"
704
+ })];
705
+ }
706
+ function paymentsRequirements(context, payments) {
707
+ if (payments.kind === "not_applicable") return [];
708
+ const fields = derivedFields(context, {
709
+ packId: "payments",
710
+ complete: payments.kind === "ready",
711
+ copy: {
712
+ complete: ["Connect payments", "Stripe is connected and ready for paid bookings."],
713
+ pending: ["Connect payments", "Connect Stripe before visitors can pay for paid bookings online."]
714
+ },
715
+ path: "/money/settings",
716
+ actionLabel: "Connect payments"
717
+ });
718
+ return [requirement(context.publicExperience, payments.kind === "ready" ? {
719
+ ...fields,
720
+ id: "connect_payments",
721
+ state: "complete"
722
+ } : {
723
+ ...fields,
724
+ id: "connect_payments",
725
+ state: "pending",
726
+ detail: {
727
+ kind: "payments_gap",
728
+ stage: payments.kind
729
+ }
730
+ })];
731
+ }
732
+ function firstOfferingRequirements(context, offerings) {
733
+ return onlyForBookingPages(context, () => derivedRequirement(context, {
734
+ id: "add_first_offering",
735
+ packId: "offerings",
736
+ complete: offerings.kind === "has_offerings",
737
+ copy: {
738
+ complete: ["First offering added", "Your page has something people can book."],
739
+ pending: ["Add your first offering", "Your page is ready for something people can book: a class, a course or a private session."]
740
+ },
741
+ path: "/bookings",
742
+ actionLabel: "Add an offering"
743
+ }));
744
+ }
745
+ function publicContactRequirements(context, publicContact) {
746
+ return onlyForBookingPages(context, () => derivedRequirement(context, {
747
+ id: "add_public_contact",
748
+ packId: "presence",
749
+ complete: publicContact.kind === "published",
750
+ copy: {
751
+ complete: ["Contact details added", "Your page shows a way to reach you."],
752
+ pending: ["Add a way to reach you", "Your page doesn't show an email or phone number yet, so people can't ask a question before they book."]
753
+ },
754
+ path: "/settings/business",
755
+ actionLabel: "Add contact details"
756
+ }));
757
+ }
758
+ function coverImageRequirements(context, coverImage) {
759
+ return onlyForBookingPages(context, () => derivedRequirement(context, {
760
+ id: "add_cover_image",
761
+ packId: "presence",
762
+ complete: coverImage.kind === "set",
763
+ copy: {
764
+ complete: ["Cover photo added", "Your page has a cover photo."],
765
+ pending: ["Add a cover photo", "A photo of your space or your work sits at the top of your page. It works without one, but a photo makes it feel like yours."]
766
+ },
767
+ path: "/settings/general",
768
+ actionLabel: "Add a photo"
769
+ }));
770
+ }
771
+ /**
772
+ * While a booking page has nothing to offer, "Add your first offering" stands
773
+ * in for the per-kind setup items, so a new owner sees one place to start.
774
+ * Lives here, not in a presentation, so every count agrees with the list.
775
+ */
776
+ function isSupersededByFirstOffering(input, id) {
777
+ if (input.publicExperience !== "hosted_booking" || input.offerings.kind !== "none") return false;
778
+ if (id === "configure_events" || id === "configure_courses") return true;
779
+ return id === "configure_appointments" && input.appointments.kind === "pending_setup" && input.appointments.missing === "not_started";
780
+ }
781
+ function countPending(requirements, priority) {
782
+ return requirements.filter((item) => item.priority === priority && item.state === "pending").length;
783
+ }
784
+ function deriveLaunchReadiness(input) {
785
+ const context = {
786
+ siteId: input.siteId ?? null,
787
+ publicExperience: input.publicExperience ?? "website"
788
+ };
789
+ const requirements = [
790
+ confirmEmailRequirement(context, input.email),
791
+ ...generatedSiteReviewRequirements(context, input.reviewGeneratedSite),
792
+ ...firstOfferingRequirements(context, input.offerings),
793
+ ...appointmentsRequirements(context, input),
794
+ ...eventsRequirements(context, input.events),
795
+ ...coursesRequirements(context, input.courses),
796
+ ...paymentsRequirements(context, input.payments),
797
+ ...publicContactRequirements(context, input.publicContact),
798
+ ...coverImageRequirements(context, input.coverImage)
799
+ ].filter((item) => !isSupersededByFirstOffering(input, item.id));
800
+ return {
801
+ requirements,
802
+ pendingRequiredCount: countPending(requirements, "required"),
803
+ pendingRecommendedCount: countPending(requirements, "recommended"),
804
+ pendingOptionalCount: countPending(requirements, "optional"),
805
+ goLiveDecision: buildGoLiveDecision(requirements)
806
+ };
807
+ }
808
+ //#endregion
809
+ //#region ../media-storage-supabase/dist/index.mjs
810
+ function ok(value) {
811
+ return {
812
+ ok: true,
813
+ value
814
+ };
815
+ }
816
+ function err(error) {
817
+ return {
818
+ ok: false,
819
+ error
820
+ };
821
+ }
822
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
823
+ function parseUuidBrand(value, unsafeConstructor) {
824
+ if (typeof value !== "string") return err({ kind: "not_string" });
825
+ const normalized = value.trim().toLowerCase();
826
+ if (normalized.length === 0) return err({ kind: "empty_string" });
827
+ if (!UUID_PATTERN.test(normalized)) return err({ kind: "invalid_uuid" });
828
+ return ok(unsafeConstructor(normalized));
829
+ }
830
+ const unsafeAsSiteId = (id) => id;
831
+ const unsafeAsSiteFontId = (id) => id;
832
+ const unsafeAsMediaAssetId = (id) => id;
833
+ const unsafeAsStorageBucketName = (value) => value;
834
+ const parseMediaAssetId = (value) => parseUuidBrand(value, unsafeAsMediaAssetId);
835
+ const unsafeAsBookingSessionId = (id) => id;
836
+ const unsafeAsEntitlementId = (id) => id;
837
+ const unsafeAsBookingRequirementId = (id) => id;
838
+ function fromArray(items) {
839
+ const [first, ...rest] = items;
840
+ if (first === void 0) return err("empty_array");
841
+ return ok([first, ...rest]);
842
+ }
843
+ /**
844
+ * Narrow nullable values to the present value.
845
+ */
846
+ function isPresent(value) {
847
+ return value !== null && value !== void 0;
848
+ }
849
+ /**
850
+ * Return true for string values that contain at least one character.
851
+ */
852
+ function isNonEmptyString(value) {
853
+ return typeof value === "string" && value.length > 0;
854
+ }
855
+ /**
856
+ * Narrow optional string values to non-empty strings.
857
+ */
858
+ function hasText(value) {
859
+ return isNonEmptyString(value);
860
+ }
861
+ const CONTROL_CHARACTER_PATTERN = /[\u0000-\u001f\u007f]/u;
862
+ function containsUnsafePathSegmentCharacter(value) {
863
+ return value.includes("/") || value.includes("\\") || CONTROL_CHARACTER_PATTERN.test(value);
864
+ }
865
+ function isReservedPathSegment(value) {
866
+ return value === "." || value === "..";
867
+ }
868
+ function isUnsafePathSegment(segment) {
869
+ return segment.trim().length === 0 || segment !== segment.trim() || isReservedPathSegment(segment) || containsUnsafePathSegmentCharacter(segment);
870
+ }
871
+ const STORAGE_OBJECT_CHARACTER = "A-Za-z0-9_!.*'() &$=@;:+,-";
872
+ const unsupportedFilenameCharacters = new RegExp(`[^${STORAGE_OBJECT_CHARACTER}]+`, "gu");
873
+ const supportedObjectKey = new RegExp(`^[/${STORAGE_OBJECT_CHARACTER}]+$`, "u");
874
+ /** Validate without trimming or rewriting: supplied keys are object identities. */
875
+ function parseWritableStoragePath(value) {
876
+ if (typeof value !== "string" || value.split("/").some(isUnsafePathSegment)) return err("unsafe-path-segment");
877
+ if (!supportedObjectKey.test(value)) return err("unsupported-storage-character");
878
+ return ok(value);
879
+ }
880
+ /** Choose a new internal filename; never use this to rewrite an existing key. */
881
+ function storageObjectFilename(filename, maxLength = 255) {
882
+ const converted = filename.trim().normalize("NFKD").replace(/[\u0300-\u036f]/gu, "").replace(unsupportedFilenameCharacters, "-").trim();
883
+ const usable = isUnsafePathSegment(converted) ? "upload" : converted;
884
+ const extension = /\.[A-Za-z0-9]{1,16}$/u.exec(usable)?.[0] ?? "";
885
+ const stem = extension.length > 0 ? usable.slice(0, -extension.length) : usable;
886
+ const shortenedFilename = `${(/[A-Za-z0-9]/u.test(stem) || converted === filename.trim() ? stem : "upload").slice(0, Math.max(1, maxLength - extension.length)).trim() || "upload"}${extension}`;
887
+ return isUnsafePathSegment(shortenedFilename) ? "upload" : shortenedFilename;
888
+ }
889
+ const FILE_STORAGE_BUCKETS = {
890
+ publicSite: unsafeAsStorageBucketName("media"),
891
+ privateSite: unsafeAsStorageBucketName("site-files-private"),
892
+ temporary: unsafeAsStorageBucketName("temp-uploads"),
893
+ siteAssets: unsafeAsStorageBucketName("site-assets"),
894
+ siteFonts: unsafeAsStorageBucketName("site-fonts"),
895
+ bookingRequirementDocuments: unsafeAsStorageBucketName("booking-requirement-documents")
896
+ };
897
+ FILE_STORAGE_BUCKETS.publicSite, FILE_STORAGE_BUCKETS.siteAssets, FILE_STORAGE_BUCKETS.siteFonts;
898
+ FILE_STORAGE_BUCKETS.publicSite, FILE_STORAGE_BUCKETS.privateSite, FILE_STORAGE_BUCKETS.temporary, FILE_STORAGE_BUCKETS.siteAssets, FILE_STORAGE_BUCKETS.siteFonts, FILE_STORAGE_BUCKETS.bookingRequirementDocuments;
899
+ const IMAGE_FILE_FORMATS = [
900
+ "jpeg",
901
+ "png",
902
+ "webp",
903
+ "gif",
904
+ "avif",
905
+ "heic",
906
+ "heif",
907
+ "svg"
908
+ ];
909
+ const VIDEO_FILE_FORMATS = [
910
+ "mp4",
911
+ "webm",
912
+ "mov"
913
+ ];
914
+ const AUDIO_FILE_FORMATS = [
915
+ "mpeg",
916
+ "mp4",
917
+ "wav",
918
+ "ogg",
919
+ "webm",
920
+ "flac"
921
+ ];
922
+ const DOCUMENT_FILE_FORMATS = [
923
+ "pdf",
924
+ "docx",
925
+ "txt",
926
+ "rtf"
927
+ ];
928
+ const SPREADSHEET_FILE_FORMATS = ["csv"];
929
+ const FONT_FILE_FORMATS = ["woff2"];
930
+ const ARCHIVE_FILE_FORMATS = ["zip"];
931
+ const FILE_KIND_TAGS = [
932
+ "image",
933
+ "video",
934
+ "audio",
935
+ "document",
936
+ "spreadsheet",
937
+ "font",
938
+ "archive"
939
+ ];
940
+ const RENDERABLE_FILE_KIND_TAGS = [
941
+ "image",
942
+ "video",
943
+ "audio"
944
+ ];
945
+ const FILE_USE_TAGS = [
946
+ "media-library",
947
+ "content-download",
948
+ "digital-product-file",
949
+ "workflow-input",
950
+ "booking-evidence",
951
+ "site-brand-asset",
952
+ "site-background-asset",
953
+ "site-font-file",
954
+ "temporary-ingestion"
955
+ ];
956
+ const WORKFLOW_INPUT_KINDS = ["audio-enrichment", "generic-file-processing"];
957
+ const SITE_BRAND_ASSET_USES = ["logo", "social-image"];
958
+ const SITE_BACKGROUND_ASSET_USES = ["selected-background", ...[
959
+ "light-texture",
960
+ "proof-band-dark",
961
+ "cta-wash",
962
+ "footer-detail",
963
+ "style-atmosphere-1",
964
+ "style-atmosphere-2"
965
+ ]];
966
+ const TEMPORARY_INGESTION_KINDS = [
967
+ "backup-zip",
968
+ "newsletter-csv",
969
+ "instagram-zip"
970
+ ];
971
+ const ACCESS_POLICY_TAGS = [
972
+ "public-read",
973
+ "site-editor-read",
974
+ "signed-public-render",
975
+ "entitled-customer-read",
976
+ "booking-session-read",
977
+ "management-api-read"
978
+ ];
979
+ function asPositiveSeconds(value) {
980
+ if (!Number.isSafeInteger(value) || value <= 0) return err("not-positive-seconds");
981
+ return ok(value);
982
+ }
983
+ function ok$1(value) {
984
+ return {
985
+ ok: true,
986
+ value
987
+ };
988
+ }
989
+ function fail(error) {
990
+ return {
991
+ ok: false,
992
+ error
993
+ };
994
+ }
995
+ function normalizeStringInput(value) {
996
+ if (typeof value !== "string") return fail({ tag: "MISSING" });
997
+ const trimmed = value.trim();
998
+ if (!trimmed) return fail({ tag: "EMPTY" });
999
+ return ok$1(trimmed);
1000
+ }
1001
+ function validateRelativeStoragePath(value) {
1002
+ if (value.startsWith("sites/")) return fail({ tag: "SITE_SCOPED_PATH" });
1003
+ if (value.startsWith("/")) return fail({ tag: "LEADING_SLASH" });
1004
+ if (value.includes("//")) return fail({ tag: "DOUBLE_SLASH" });
1005
+ if (value.includes("%")) return fail({ tag: "PERCENT_ENCODING" });
1006
+ if (value.split("/").some((segment) => segment === "." || segment === "..")) return fail({ tag: "TRAVERSAL" });
1007
+ return ok$1(value);
1008
+ }
1009
+ function brandRelativeStoragePath(value) {
1010
+ return value;
1011
+ }
1012
+ function parseRelativeStoragePath(value) {
1013
+ const normalized = normalizeStringInput(value);
1014
+ if (!normalized.ok) return normalized;
1015
+ const validated = validateRelativeStoragePath(normalized.value);
1016
+ if (!validated.ok) return validated;
1017
+ return ok$1(brandRelativeStoragePath(validated.value));
1018
+ }
1019
+ function isRecord$3(value) {
1020
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1021
+ }
1022
+ function parseFileKindJson(value) {
1023
+ const recordResult = requireRecord(value);
1024
+ if (!recordResult.ok) return recordResult;
1025
+ const record = recordResult.value;
1026
+ const tag = parseTag(record.tag, FILE_KIND_TAGS);
1027
+ if (!tag.ok) return tag;
1028
+ switch (tag.value) {
1029
+ case "image": {
1030
+ const family = requireString(record.family);
1031
+ if (!family.ok || family.value !== "raster") return err("invalid-field");
1032
+ const format = parseOneOf(record.format, IMAGE_FILE_FORMATS);
1033
+ if (!format.ok) return format;
1034
+ return ok({
1035
+ tag: "image",
1036
+ family: "raster",
1037
+ format: format.value
1038
+ });
1039
+ }
1040
+ case "video": {
1041
+ const format = parseOneOf(record.format, VIDEO_FILE_FORMATS);
1042
+ if (!format.ok) return format;
1043
+ return ok({
1044
+ tag: "video",
1045
+ format: format.value
1046
+ });
1047
+ }
1048
+ case "audio": {
1049
+ const format = parseOneOf(record.format, AUDIO_FILE_FORMATS);
1050
+ if (!format.ok) return format;
1051
+ return ok({
1052
+ tag: "audio",
1053
+ format: format.value
1054
+ });
1055
+ }
1056
+ case "document": {
1057
+ const format = parseOneOf(record.format, DOCUMENT_FILE_FORMATS);
1058
+ if (!format.ok) return format;
1059
+ return ok({
1060
+ tag: "document",
1061
+ format: format.value
1062
+ });
1063
+ }
1064
+ case "spreadsheet": {
1065
+ const format = parseOneOf(record.format, SPREADSHEET_FILE_FORMATS);
1066
+ if (!format.ok) return format;
1067
+ return ok({
1068
+ tag: "spreadsheet",
1069
+ format: format.value
1070
+ });
1071
+ }
1072
+ case "font": {
1073
+ const format = parseOneOf(record.format, FONT_FILE_FORMATS);
1074
+ if (!format.ok) return format;
1075
+ return ok({
1076
+ tag: "font",
1077
+ format: format.value
1078
+ });
1079
+ }
1080
+ case "archive": {
1081
+ const format = parseOneOf(record.format, ARCHIVE_FILE_FORMATS);
1082
+ if (!format.ok) return format;
1083
+ return ok({
1084
+ tag: "archive",
1085
+ format: format.value
1086
+ });
1087
+ }
1088
+ }
1089
+ }
1090
+ function parseFileUseJson(value) {
1091
+ const recordResult = requireRecord(value);
1092
+ if (!recordResult.ok) return recordResult;
1093
+ const record = recordResult.value;
1094
+ const tag = parseTag(record.tag, FILE_USE_TAGS);
1095
+ if (!tag.ok) return tag;
1096
+ switch (tag.value) {
1097
+ case "media-library": {
1098
+ const renderUse = parseOneOf(record.renderUse, RENDERABLE_FILE_KIND_TAGS);
1099
+ if (!renderUse.ok) return renderUse;
1100
+ return ok({
1101
+ tag: "media-library",
1102
+ renderUse: renderUse.value
1103
+ });
1104
+ }
1105
+ case "content-download": return ok({ tag: "content-download" });
1106
+ case "digital-product-file": {
1107
+ const fulfillmentVisibility = requireString(record.fulfillmentVisibility);
1108
+ if (!fulfillmentVisibility.ok || fulfillmentVisibility.value !== "entitled-customer") return err("invalid-field");
1109
+ return ok({
1110
+ tag: "digital-product-file",
1111
+ fulfillmentVisibility: "entitled-customer"
1112
+ });
1113
+ }
1114
+ case "workflow-input": {
1115
+ const workflowKind = parseOneOf(record.workflowKind, WORKFLOW_INPUT_KINDS);
1116
+ if (!workflowKind.ok) return workflowKind;
1117
+ return ok({
1118
+ tag: "workflow-input",
1119
+ workflowKind: workflowKind.value
1120
+ });
1121
+ }
1122
+ case "booking-evidence": {
1123
+ const requirementId = requireNonEmptyString(record.requirementId);
1124
+ if (!requirementId.ok) return requirementId;
1125
+ return ok({
1126
+ tag: "booking-evidence",
1127
+ requirementId: unsafeAsBookingRequirementId(requirementId.value)
1128
+ });
1129
+ }
1130
+ case "site-brand-asset": {
1131
+ const brandUse = parseOneOf(record.brandUse, SITE_BRAND_ASSET_USES);
1132
+ if (!brandUse.ok) return brandUse;
1133
+ return ok({
1134
+ tag: "site-brand-asset",
1135
+ brandUse: brandUse.value
1136
+ });
1137
+ }
1138
+ case "site-background-asset": {
1139
+ const backgroundUse = parseOneOf(record.backgroundUse, SITE_BACKGROUND_ASSET_USES);
1140
+ if (!backgroundUse.ok) return backgroundUse;
1141
+ return ok({
1142
+ tag: "site-background-asset",
1143
+ backgroundUse: backgroundUse.value
1144
+ });
1145
+ }
1146
+ case "site-font-file": {
1147
+ const fontId = requireNonEmptyString(record.fontId);
1148
+ if (!fontId.ok) return fontId;
1149
+ return ok({
1150
+ tag: "site-font-file",
1151
+ fontId: unsafeAsSiteFontId(fontId.value)
1152
+ });
1153
+ }
1154
+ case "temporary-ingestion": {
1155
+ const ingestionKind = parseOneOf(record.ingestionKind, TEMPORARY_INGESTION_KINDS);
1156
+ if (!ingestionKind.ok) return ingestionKind;
1157
+ return ok({
1158
+ tag: "temporary-ingestion",
1159
+ ingestionKind: ingestionKind.value
1160
+ });
1161
+ }
1162
+ }
1163
+ }
1164
+ function parseFileUsesJson(value) {
1165
+ if (!Array.isArray(value)) return err("expected-array");
1166
+ const parsed = traverse(value, parseFileUseJson);
1167
+ if (!parsed.ok) return parsed;
1168
+ const nonEmpty = fromArray(parsed.value);
1169
+ if (!nonEmpty.ok) return err("expected-non-empty-array");
1170
+ return ok(nonEmpty.value);
1171
+ }
1172
+ function parseAccessPolicyJson(value) {
1173
+ const recordResult = requireRecord(value);
1174
+ if (!recordResult.ok) return recordResult;
1175
+ const record = recordResult.value;
1176
+ const tag = parseTag(record.tag, ACCESS_POLICY_TAGS);
1177
+ if (!tag.ok) return tag;
1178
+ switch (tag.value) {
1179
+ case "public-read": return ok({ tag: "public-read" });
1180
+ case "site-editor-read": {
1181
+ const siteId = requireNonEmptyString(record.siteId);
1182
+ if (!siteId.ok) return siteId;
1183
+ return ok({
1184
+ tag: "site-editor-read",
1185
+ siteId: unsafeAsSiteId(siteId.value)
1186
+ });
1187
+ }
1188
+ case "signed-public-render": {
1189
+ const expiresInSeconds = parsePositiveSeconds$1(record.expiresInSeconds);
1190
+ if (!expiresInSeconds.ok) return expiresInSeconds;
1191
+ return ok({
1192
+ tag: "signed-public-render",
1193
+ expiresInSeconds: expiresInSeconds.value
1194
+ });
1195
+ }
1196
+ case "entitled-customer-read": {
1197
+ const scope = parseEntitledCustomerAccessScopeJson(record.scope);
1198
+ if (!scope.ok) return scope;
1199
+ const expiresInSeconds = parseOptionalPositiveSeconds(record.expiresInSeconds);
1200
+ if (!expiresInSeconds.ok) return expiresInSeconds;
1201
+ return ok({
1202
+ tag: "entitled-customer-read",
1203
+ scope: scope.value,
1204
+ ...expiresInSeconds.value !== void 0 ? { expiresInSeconds: expiresInSeconds.value } : {}
1205
+ });
1206
+ }
1207
+ case "booking-session-read": {
1208
+ const sessionId = requireNonEmptyString(record.sessionId);
1209
+ if (!sessionId.ok) return sessionId;
1210
+ const expiresInSeconds = parseOptionalPositiveSeconds(record.expiresInSeconds);
1211
+ if (!expiresInSeconds.ok) return expiresInSeconds;
1212
+ return ok({
1213
+ tag: "booking-session-read",
1214
+ sessionId: unsafeAsBookingSessionId(sessionId.value),
1215
+ ...expiresInSeconds.value !== void 0 ? { expiresInSeconds: expiresInSeconds.value } : {}
1216
+ });
1217
+ }
1218
+ case "management-api-read": return ok({ tag: "management-api-read" });
1219
+ }
1220
+ }
1221
+ function parseEntitledCustomerAccessScopeJson(value) {
1222
+ const recordResult = requireRecord(value);
1223
+ if (!recordResult.ok) return recordResult;
1224
+ const record = recordResult.value;
1225
+ const tag = parseTag(record.tag, ["any-entitled-customer", "specific-entitlement"]);
1226
+ if (!tag.ok) return tag;
1227
+ switch (tag.value) {
1228
+ case "any-entitled-customer": return ok({ tag: "any-entitled-customer" });
1229
+ case "specific-entitlement": {
1230
+ const entitlementId = requireNonEmptyString(record.entitlementId);
1231
+ if (!entitlementId.ok) return entitlementId;
1232
+ return ok({
1233
+ tag: "specific-entitlement",
1234
+ entitlementId: unsafeAsEntitlementId(entitlementId.value)
1235
+ });
1236
+ }
1237
+ }
1238
+ }
1239
+ function requireRecord(value) {
1240
+ if (!isRecord$3(value)) return err("expected-object");
1241
+ return ok(value);
1242
+ }
1243
+ function requireString(value) {
1244
+ if (typeof value !== "string") return err("invalid-string");
1245
+ return ok(value);
1246
+ }
1247
+ function requireNonEmptyString(value) {
1248
+ const string = requireString(value);
1249
+ if (!string.ok) return string;
1250
+ const trimmed = string.value.trim();
1251
+ if (!trimmed || trimmed !== string.value) return err("invalid-string");
1252
+ return ok(string.value);
1253
+ }
1254
+ function parseOneOf(value, allowed) {
1255
+ return parseStringIn(value, allowed, "invalid-field");
1256
+ }
1257
+ function parseTag(value, allowed) {
1258
+ return parseStringIn(value, allowed, "invalid-tag");
1259
+ }
1260
+ function parseStringIn(value, allowed, outOfSetError) {
1261
+ const string = requireString(value);
1262
+ if (!string.ok) return string;
1263
+ if (!isOneOf(string.value, allowed)) return err(outOfSetError);
1264
+ return ok(string.value);
1265
+ }
1266
+ function parsePositiveSeconds$1(value) {
1267
+ if (typeof value !== "number") return err("invalid-number");
1268
+ const parsed = asPositiveSeconds(value);
1269
+ if (!parsed.ok) return err("invalid-positive-seconds");
1270
+ return ok(parsed.value);
1271
+ }
1272
+ function parseOptionalPositiveSeconds(value) {
1273
+ if (value === void 0 || value === null) return ok(void 0);
1274
+ return parsePositiveSeconds$1(value);
1275
+ }
1276
+ function traverse(items, parse) {
1277
+ const values = [];
1278
+ for (const item of items) {
1279
+ const parsed = parse(item);
1280
+ if (!parsed.ok) return parsed;
1281
+ values.push(parsed.value);
1282
+ }
1283
+ return ok(values);
1284
+ }
1285
+ function isOneOf(value, allowed) {
1286
+ return allowed.includes(value);
1287
+ }
1288
+ new TextDecoder("latin1");
1289
+ const ImageKindSchema = z.enum([
1290
+ "photo",
1291
+ "logo",
1292
+ "icon",
1293
+ "illustration",
1294
+ "graphic-with-text",
1295
+ "screenshot",
1296
+ "document",
1297
+ "other"
1298
+ ]);
1299
+ z.enum(["original", "light-dark-composite"]);
1300
+ const ImageFactsSchema = z.strictObject({
1301
+ kind: ImageKindSchema,
1302
+ description: z.string().trim().min(1).max(600),
1303
+ readableText: z.string().trim().max(2e3)
1304
+ });
1305
+ /** Canonical English search slugs; unusable output cannot become an empty label. */
1306
+ function normalizeImageLabels(labels) {
1307
+ return [...new Set(labels.map((label) => label.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")).filter((label) => /[a-z]/.test(label)))];
1308
+ }
1309
+ const ImageLabelsSchema = z.array(z.string().trim().min(1).max(64)).min(1).max(10).transform(normalizeImageLabels).pipe(z.array(z.string().min(1).max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)).min(1).max(10));
1310
+ ImageFactsSchema.extend({ labels: ImageLabelsSchema });
1311
+ z.strictObject({
1312
+ version: z.literal(1),
1313
+ facts: ImageFactsSchema,
1314
+ modelId: z.string().trim().min(1),
1315
+ promptVersion: z.string().trim().min(1),
1316
+ sourceChecksum: z.string().regex(/^[a-f0-9]{64}$/),
1317
+ analyzedAt: z.iso.datetime({ offset: true }),
1318
+ embeddingModelId: z.string().trim().min(1)
1319
+ });
1320
+ function slugifyMediaIdentifier(value) {
1321
+ return value.toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-");
1322
+ }
1323
+ function parseMediaIdentifier(value) {
1324
+ if (typeof value !== "string") return err({ kind: "not_string" });
1325
+ const trimmed = value.trim();
1326
+ if (trimmed.length === 0) return err({ kind: "empty_identifier" });
1327
+ const normalized = slugifyMediaIdentifier(trimmed);
1328
+ if (normalized.length === 0) return err({
1329
+ kind: "empty_after_normalization",
1330
+ value
1331
+ });
1332
+ return ok(normalized);
1333
+ }
1334
+ /**
1335
+ * Admits identifiers read from trusted persistence without repairing dirty data in memory.
1336
+ * User input should use parseMediaIdentifier, which intentionally canonicalizes it.
1337
+ */
1338
+ function parseCanonicalMediaIdentifier(value) {
1339
+ if (typeof value !== "string") return err({ kind: "not_string" });
1340
+ const parsed = parseMediaIdentifier(value);
1341
+ if (!parsed.ok) return parsed;
1342
+ if (value !== parsed.value) return err({
1343
+ kind: "non_canonical_identifier",
1344
+ value,
1345
+ canonical: parsed.value
1346
+ });
1347
+ return parsed;
1348
+ }
1349
+ /** Strict stored-reference admission delegates the canonical identifier decision. */
1350
+ const mediaIdentifierSchema$1 = z.string().transform((value, context) => {
1351
+ const parsed = parseCanonicalMediaIdentifier(value);
1352
+ if (parsed.ok) return parsed.value;
1353
+ context.addIssue({
1354
+ code: "custom",
1355
+ message: "Expected a canonical media identifier"
1356
+ });
1357
+ return z.NEVER;
1358
+ });
1359
+ const mediaTypeDiscriminants = [
1360
+ "image",
1361
+ "video",
1362
+ "audio",
1363
+ "document",
1364
+ "spreadsheet",
1365
+ "archive"
1366
+ ];
1367
+ const mediaAssetIdSchema = z.string().transform((value, context) => {
1368
+ const parsed = parseMediaAssetId(value);
1369
+ if (parsed.ok) return parsed.value;
1370
+ context.addIssue({
1371
+ code: "custom",
1372
+ message: "Expected a media asset ID"
1373
+ });
1374
+ return z.NEVER;
1375
+ });
1376
+ const nonemptyStorageValue = z.string().refine((value) => value.trim().length > 0);
1377
+ const renderableMediaAssetSchema = z.object({
1378
+ id: mediaAssetIdSchema,
1379
+ identifier: mediaIdentifierSchema$1,
1380
+ storageBucket: nonemptyStorageValue,
1381
+ storagePath: nonemptyStorageValue,
1382
+ mimeType: nonemptyStorageValue,
1383
+ filename: z.string().optional(),
1384
+ width: z.number().positive().nullable(),
1385
+ height: z.number().positive().nullable()
1386
+ });
1387
+ const hotspotSchema = z.object({
1388
+ x: z.number().min(0).max(1),
1389
+ y: z.number().min(0).max(1),
1390
+ radius: z.number().optional()
1391
+ });
1392
+ const rotationSchema = z.union([
1393
+ z.literal(0),
1394
+ z.literal(90),
1395
+ z.literal(180),
1396
+ z.literal(270)
1397
+ ]);
1398
+ const rectSchema = z.tuple([
1399
+ z.number(),
1400
+ z.number(),
1401
+ z.number(),
1402
+ z.number()
1403
+ ]);
1404
+ const aspectCropSchema = z.object({
1405
+ aspect: z.preprocess((value) => value == null ? void 0 : value, z.string().optional()),
1406
+ rect: z.preprocess((value) => value == null ? void 0 : value, rectSchema.optional()),
1407
+ hotspot: z.preprocess((value) => value == null ? void 0 : value, hotspotSchema.optional()),
1408
+ rotation: z.preprocess((value) => value == null ? void 0 : value, rotationSchema.optional())
1409
+ });
1410
+ const transformSchema = z.object({
1411
+ aspectCrops: z.preprocess((value) => {
1412
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
1413
+ return value;
1414
+ }, z.record(z.string(), aspectCropSchema.catch({}))).optional(),
1415
+ rect: rectSchema.optional(),
1416
+ hotspot: hotspotSchema.optional(),
1417
+ rotation: rotationSchema.optional()
1418
+ });
1419
+ const mediaPosterSchema = z.discriminatedUnion("tag", [z.object({
1420
+ tag: z.literal("media"),
1421
+ identifier: mediaIdentifierSchema$1
1422
+ }).strict(), z.object({
1423
+ tag: z.literal("external-src"),
1424
+ src: z.string().url()
1425
+ }).strict()]);
1426
+ const mediaUsageShape = {
1427
+ purpose: z.string().optional(),
1428
+ placeholder: z.boolean().default(true).optional(),
1429
+ alt: z.string().optional(),
1430
+ filename: z.string().optional(),
1431
+ width: z.number().optional(),
1432
+ height: z.number().optional(),
1433
+ poster: mediaPosterSchema.optional(),
1434
+ transform: transformSchema.optional()
1435
+ };
1436
+ const environmentExclusions = {
1437
+ assetId: z.never().optional(),
1438
+ id: z.never().optional(),
1439
+ src: z.never().optional(),
1440
+ storageBucket: z.never().optional(),
1441
+ storagePath: z.never().optional(),
1442
+ mimeType: z.never().optional()
1443
+ };
1444
+ const mediaBaseSchema = z.object({
1445
+ ...mediaUsageShape,
1446
+ ...environmentExclusions,
1447
+ identifier: mediaIdentifierSchema$1
1448
+ }).strict();
1449
+ mediaBaseSchema.extend({ type: z.literal("image") });
1450
+ mediaBaseSchema.extend({ type: z.literal("video") });
1451
+ const mediaSchema = mediaBaseSchema.extend({ type: z.enum(mediaTypeDiscriminants) });
1452
+ const externalMediaSchema = z.object({
1453
+ ...mediaUsageShape,
1454
+ ...environmentExclusions,
1455
+ type: z.enum(mediaTypeDiscriminants),
1456
+ src: z.string().min(1),
1457
+ identifier: z.never().optional()
1458
+ }).strict();
1459
+ const assetMediaSchema = z.object({
1460
+ ...mediaUsageShape,
1461
+ ...environmentExclusions,
1462
+ type: z.enum(mediaTypeDiscriminants),
1463
+ asset: renderableMediaAssetSchema,
1464
+ identifier: z.never().optional()
1465
+ }).strict();
1466
+ z.union([
1467
+ mediaSchema,
1468
+ externalMediaSchema,
1469
+ assetMediaSchema
1470
+ ]);
1471
+ new Set(mediaTypeDiscriminants);
1472
+ const MEDIA_KINDS = [
1473
+ "image",
1474
+ "video",
1475
+ "audio",
1476
+ "document",
1477
+ "spreadsheet",
1478
+ "archive"
1479
+ ];
1480
+ const MEDIA_ASSET_FILE_FILTERS = [
1481
+ "all",
1482
+ "images",
1483
+ "videos",
1484
+ "audio",
1485
+ "documents",
1486
+ "downloads"
1487
+ ];
1488
+ const MEDIA_ASSET_LIBRARY_SCOPES = ["files-and-media", "product-files"];
1489
+ var MediaStorageError = class extends Error {
1490
+ constructor(message, options = {}) {
1491
+ super(message);
1492
+ this.name = "MediaStorageError";
1493
+ this.status = options.status;
1494
+ this.code = options.code;
1495
+ this.details = options.details ?? null;
1496
+ this.cause = options.cause;
1497
+ }
1498
+ };
1499
+ z.enum([
1500
+ "active",
1501
+ "pending-delete",
1502
+ "deleted"
1503
+ ]).optional();
1504
+ const pad = (value) => value.toString().padStart(2, "0");
1505
+ const extractExtension = (filename) => {
1506
+ if (!hasText(filename)) return "";
1507
+ const internalFilename = storageObjectFilename(filename);
1508
+ const lastDot = internalFilename.lastIndexOf(".");
1509
+ if (lastDot === -1) return "";
1510
+ return internalFilename.slice(lastDot).toLowerCase();
1511
+ };
1512
+ const generateId = () => {
1513
+ const crypto = globalThis.crypto;
1514
+ if (isPresent(crypto) && typeof crypto.getRandomValues === "function") {
1515
+ const array = crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(4));
1516
+ return Array.from(array).map((value) => value.toString(16).padStart(8, "0")).join("-");
1517
+ }
1518
+ return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
1519
+ };
1520
+ /**
1521
+ * Generate a relative storage path for a media file.
1522
+ *
1523
+ * Returns a path WITHOUT the site prefix (e.g., "originals/2025/01/abc.jpg").
1524
+ * Use `toSiteScopedStoragePath()` to prepend the site prefix for actual storage operations.
1525
+ *
1526
+ * This design allows content to be synced between sites without path conflicts,
1527
+ * since the site ID is prepended at runtime rather than stored in content data.
1528
+ */
1529
+ const generateStoragePath = ({ filename, folder = "originals", variantKey, now = /* @__PURE__ */ new Date() }) => {
1530
+ const id = generateId();
1531
+ const nowParts = {
1532
+ year: now.getUTCFullYear(),
1533
+ month: pad(now.getUTCMonth() + 1)
1534
+ };
1535
+ const path = decideGeneratedStoragePath({
1536
+ extension: extractExtension(filename),
1537
+ folder,
1538
+ ...nowParts,
1539
+ id,
1540
+ variantKey: variantKey ?? (folder === "originals" ? id : generateId())
1541
+ });
1542
+ if (!path.ok) {
1543
+ const reason = typeof path.error === "string" ? path.error : path.error.tag;
1544
+ throw new Error(`Invalid generated storage path: ${reason}`);
1545
+ }
1546
+ return path.value;
1547
+ };
1548
+ function decideGeneratedStoragePath(input) {
1549
+ const writable = parseWritableStoragePath(input.folder === "variants" ? `variants/${input.variantKey}/${input.id}${input.extension}` : input.folder === "imports" ? `imports/${input.variantKey}${input.extension}` : `originals/${input.year}/${input.month}/${input.id}${input.extension}`);
1550
+ return writable.ok ? parseRelativeStoragePath(writable.value) : writable;
1551
+ }
1552
+ const DEFAULT_BUCKET = "media";
1553
+ const MAX_LIMIT = 100;
1554
+ const fileKindSchema = z.custom((value) => parseFileKindJson(value).ok, { message: "Invalid file kind JSON" });
1555
+ const fileUsesSchema = z.custom((value) => parseFileUsesJson(value).ok, { message: "Invalid file uses JSON" });
1556
+ const accessPolicySchema = z.custom((value) => parseAccessPolicyJson(value).ok, { message: "Invalid access policy JSON" });
1557
+ const mediaIdentifierSchema = z.string().transform((value, context) => {
1558
+ const parsed = parseCanonicalMediaIdentifier(value);
1559
+ if (parsed.ok) return parsed.value;
1560
+ context.addIssue({
1561
+ code: "custom",
1562
+ message: "Invalid media identifier"
1563
+ });
1564
+ return z.NEVER;
1565
+ });
1566
+ const fileDomainSchema = z.object({
1567
+ fileKind: fileKindSchema,
1568
+ fileUses: fileUsesSchema,
1569
+ accessPolicy: accessPolicySchema,
1570
+ storageClass: z.enum([
1571
+ "public-site",
1572
+ "private-site",
1573
+ "temporary"
1574
+ ]),
1575
+ mimeTypeDetected: z.string().min(1).optional().nullable(),
1576
+ safeDownloadFilename: z.string().min(1).optional().nullable(),
1577
+ lifecycleState: z.enum([
1578
+ "active",
1579
+ "pending-delete",
1580
+ "deleted"
1581
+ ]),
1582
+ originAssetId: z.string().uuid().optional().nullable(),
1583
+ derivativeKind: z.enum([
1584
+ "image-variant",
1585
+ "video-poster",
1586
+ "audio-waveform"
1587
+ ]).optional().nullable(),
1588
+ uploadSessionId: z.string().uuid().optional().nullable()
1589
+ });
1590
+ const fileDomainPatchSchema = fileDomainSchema.partial();
1591
+ z.object({
1592
+ id: z.string().min(1).optional(),
1593
+ siteId: z.string().min(1),
1594
+ storagePath: z.string().min(1),
1595
+ storageBucket: z.string().min(1).default(DEFAULT_BUCKET),
1596
+ filename: z.string().min(1),
1597
+ identifier: mediaIdentifierSchema,
1598
+ mimeType: z.string().min(1),
1599
+ width: z.number().int().nonnegative().optional(),
1600
+ height: z.number().int().nonnegative().optional(),
1601
+ bytes: z.number().int().nonnegative(),
1602
+ checksumSha256: z.string().min(1).optional().nullable(),
1603
+ fileDomain: fileDomainSchema,
1604
+ source: z.enum(["upload", "instagram"]).optional(),
1605
+ title: z.string().optional().nullable(),
1606
+ altText: z.string().optional().nullable(),
1607
+ caption: z.string().optional().nullable(),
1608
+ exif: z.record(z.string(), z.any()).optional().nullable(),
1609
+ createdBy: z.string().min(1).optional().nullable(),
1610
+ durationSeconds: z.number().positive().nullable().optional(),
1611
+ thumbnailAssetId: z.string().uuid().nullable().optional(),
1612
+ isThumbnail: z.boolean().optional()
1613
+ });
1614
+ z.object({
1615
+ filename: z.string().optional(),
1616
+ mimeType: z.string().optional(),
1617
+ storagePath: z.string().optional(),
1618
+ storageBucket: z.string().optional(),
1619
+ width: z.number().int().nonnegative().nullable().optional(),
1620
+ height: z.number().int().nonnegative().nullable().optional(),
1621
+ bytes: z.number().int().nonnegative().nullable().optional(),
1622
+ checksumSha256: z.string().nullable().optional(),
1623
+ fileDomain: fileDomainPatchSchema.optional(),
1624
+ source: z.enum(["upload", "instagram"]).optional(),
1625
+ title: z.string().nullable().optional(),
1626
+ altText: z.string().nullable().optional(),
1627
+ caption: z.string().nullable().optional(),
1628
+ exif: z.record(z.string(), z.any()).nullable().optional(),
1629
+ durationSeconds: z.number().positive().nullable().optional(),
1630
+ thumbnailAssetId: z.string().uuid().nullable().optional(),
1631
+ isThumbnail: z.boolean().optional()
1632
+ }).refine((value) => Object.keys(value).length > 0, { message: "Update payload must include at least one field" });
1633
+ z.object({
1634
+ siteId: z.string().min(1),
1635
+ limit: z.number().int().min(1).max(MAX_LIMIT).optional(),
1636
+ offset: z.number().int().min(0).optional(),
1637
+ search: z.string().optional(),
1638
+ orderBy: z.enum(["created_at", "filename"]).optional(),
1639
+ orderDirection: z.enum(["asc", "desc"]).optional(),
1640
+ labels: z.array(z.string()).optional(),
1641
+ mediaKinds: z.array(z.enum(MEDIA_KINDS)).optional(),
1642
+ fileFilter: z.enum(MEDIA_ASSET_FILE_FILTERS).optional(),
1643
+ libraryScope: z.enum(MEDIA_ASSET_LIBRARY_SCOPES).optional()
1644
+ });
1645
+ const searchMatchRowSchema = z.object({
1646
+ id: z.string(),
1647
+ score: z.number().nullable(),
1648
+ tier: z.enum([
1649
+ "exact",
1650
+ "partial",
1651
+ "semantic"
1652
+ ]),
1653
+ reasons: z.array(z.enum([
1654
+ "label",
1655
+ "exact_text",
1656
+ "text",
1657
+ "semantic"
1658
+ ]))
1659
+ });
1660
+ z.array(searchMatchRowSchema);
1661
+ z.object({
1662
+ siteId: z.string().uuid(),
1663
+ vector: z.array(z.number().finite()).length(1536).nullable(),
1664
+ query: z.string().trim().nullable().default(null),
1665
+ labels: z.array(z.string()).default([]),
1666
+ fileFilter: z.enum(MEDIA_ASSET_FILE_FILTERS).default("all"),
1667
+ offset: z.number().int().nonnegative().default(0),
1668
+ preferredKind: z.literal("logo").nullable().default(null),
1669
+ limit: z.number().int().min(1).max(200).default(20),
1670
+ threshold: z.number().positive().default(1.5),
1671
+ libraryScope: z.enum(MEDIA_ASSET_LIBRARY_SCOPES).default("files-and-media")
1672
+ });
1673
+ z.array(z.number().finite()).length(1536);
1674
+ z.enum([
1675
+ "committed",
1676
+ "conflict",
1677
+ "superseded",
1678
+ "claim-lost"
1679
+ ]);
1680
+ //#endregion
1681
+ //#region ../media-storage-api/dist/index.mjs
1682
+ const DEFAULT_MESSAGES = {
1683
+ list: "Failed to load media assets",
1684
+ listProductFiles: "Failed to load product file assets",
1685
+ get: "Failed to load media asset",
1686
+ create: "Failed to create media asset",
1687
+ update: "Failed to update media asset",
1688
+ delete: "Failed to delete media asset"
1689
+ };
1690
+ function isRecord$2(value) {
1691
+ return typeof value === "object" && value !== null;
1692
+ }
1693
+ const normalizeLabels = (labels) => labels !== void 0 && labels.length > 0 ? labels.map((label) => label.trim()).filter((label) => label.length > 0).join(",") : void 0;
1694
+ const fileFilterForMediaKinds = (mediaKinds) => {
1695
+ if (mediaKinds === void 0 || mediaKinds.length !== 1) return void 0;
1696
+ const [mediaKind] = mediaKinds;
1697
+ if (mediaKind === void 0) return void 0;
1698
+ switch (mediaKind) {
1699
+ case "image": return "images";
1700
+ case "video": return "videos";
1701
+ case "audio": return "audio";
1702
+ case "document":
1703
+ case "spreadsheet":
1704
+ case "archive": return "documents";
1705
+ }
1706
+ };
1707
+ const filterUpdatePayload = (input) => {
1708
+ const payload = {};
1709
+ if (input.filename !== void 0) payload.filename = input.filename;
1710
+ if (input.altText !== void 0) payload.altText = input.altText;
1711
+ if (input.caption !== void 0) payload.caption = input.caption;
1712
+ if (input.mimeType !== void 0) payload.mimeType = input.mimeType;
1713
+ if (input.storagePath !== void 0) payload.storagePath = input.storagePath;
1714
+ if (input.storageBucket !== void 0) payload.storageBucket = input.storageBucket;
1715
+ if (input.width !== void 0) payload.width = input.width;
1716
+ if (input.height !== void 0) payload.height = input.height;
1717
+ if (input.bytes !== void 0) payload.bytes = input.bytes;
1718
+ if (input.checksumSha256 !== void 0) payload.checksumSha256 = input.checksumSha256;
1719
+ if (input.source !== void 0) payload.source = input.source;
1720
+ if (input.exif !== void 0) payload.exif = input.exif;
1721
+ return payload;
1722
+ };
1723
+ const extractErrorMessage = (body) => {
1724
+ if (!isRecord$2(body)) return typeof body === "string" && body.trim().length > 0 ? body : null;
1725
+ for (const key of [
1726
+ "error",
1727
+ "message",
1728
+ "detail",
1729
+ "reason"
1730
+ ]) {
1731
+ const value = body[key];
1732
+ if (typeof value === "string" && value.trim().length > 0) return value;
1733
+ }
1734
+ const details = body.details;
1735
+ if (Array.isArray(details)) for (const entry of details) {
1736
+ if (typeof entry === "string" && entry.trim().length > 0) return entry;
1737
+ if (isRecord$2(entry) && typeof entry.message === "string" && entry.message.trim().length > 0) return entry.message;
1738
+ }
1739
+ const errors = body.errors;
1740
+ if (Array.isArray(errors)) {
1741
+ for (const entry of errors) if (isRecord$2(entry) && typeof entry.message === "string" && entry.message.trim().length > 0) return entry.message;
1742
+ }
1743
+ return null;
1744
+ };
1745
+ const toMediaStorageError = (error, fallback) => {
1746
+ if (error instanceof MediaStorageError) return error;
1747
+ if (error instanceof ApiRequestError) return new MediaStorageError(extractErrorMessage(error.body ?? null) ?? fallback, {
1748
+ status: error.status,
1749
+ cause: error
1750
+ });
1751
+ if (error instanceof Error && error.message.trim().length > 0) return new MediaStorageError(error.message, { cause: error });
1752
+ return new MediaStorageError(fallback, { cause: error });
1753
+ };
1754
+ const callClient = async (client, params, mapError) => {
1755
+ try {
1756
+ return unwrapResponse(await client(params));
1757
+ } catch (error) {
1758
+ throw mapError(error);
1759
+ }
1760
+ };
1761
+ const createApiMediaRepo = ({ client }) => ({
1762
+ async getAsset(assetId) {
1763
+ try {
1764
+ return unwrapResponse(await client({
1765
+ endpoint: "mediaGet",
1766
+ params: { assetId }
1767
+ }));
1768
+ } catch (error) {
1769
+ if (error instanceof ApiRequestError && error.status === 404) return null;
1770
+ throw toMediaStorageError(error, DEFAULT_MESSAGES.get);
1771
+ }
1772
+ },
1773
+ async listAssets(options) {
1774
+ return callClient(client, {
1775
+ endpoint: "mediaList",
1776
+ params: {
1777
+ siteId: options.siteId,
1778
+ q: options.search,
1779
+ limit: options.limit === void 0 ? void 0 : String(options.limit),
1780
+ offset: options.offset === void 0 ? void 0 : String(options.offset),
1781
+ labels: normalizeLabels(options.labels),
1782
+ fileFilter: options.fileFilter ?? fileFilterForMediaKinds(options.mediaKinds)
1783
+ }
1784
+ }, (error) => toMediaStorageError(error, DEFAULT_MESSAGES.list));
1785
+ },
1786
+ async createAsset(input) {
1787
+ return callClient(client, {
1788
+ endpoint: "createMediaAsset",
1789
+ body: {
1790
+ siteId: input.siteId,
1791
+ storageBucket: input.storageBucket ?? "media",
1792
+ storagePath: input.storagePath,
1793
+ filename: input.filename,
1794
+ mimeType: input.mimeType,
1795
+ width: input.width,
1796
+ height: input.height,
1797
+ bytes: input.bytes,
1798
+ checksumSha256: input.checksumSha256 ?? null,
1799
+ source: input.source ?? "upload",
1800
+ altText: input.altText ?? null,
1801
+ caption: input.caption ?? null,
1802
+ exif: input.exif ?? null
1803
+ }
1804
+ }, (error) => toMediaStorageError(error, DEFAULT_MESSAGES.create));
1805
+ },
1806
+ async updateAsset(assetId, input) {
1807
+ const payload = filterUpdatePayload(input);
1808
+ if (Object.keys(payload).length === 0) throw new MediaStorageError("No update payload provided");
1809
+ return callClient(client, {
1810
+ endpoint: "mediaUpdate",
1811
+ params: { assetId },
1812
+ body: payload
1813
+ }, (error) => toMediaStorageError(error, DEFAULT_MESSAGES.update));
1814
+ },
1815
+ async deleteAsset(assetId, options) {
1816
+ const response = await callClient(client, {
1817
+ endpoint: "mediaDelete",
1818
+ params: { assetId },
1819
+ body: { deleteObject: options?.deleteObject }
1820
+ }, (error) => toMediaStorageError(error, DEFAULT_MESSAGES.delete));
1821
+ if (response.kind === "deleted") return response;
1822
+ const orphanWarning = response.warnings.find((warning) => warning.kind === "ORPHAN_CLEANUP_FAILED");
1823
+ return orphanWarning === void 0 ? { kind: "deleted" } : {
1824
+ kind: "deleted_with_orphan_warning",
1825
+ warning: orphanWarning
1826
+ };
1827
+ },
1828
+ generateStoragePath
1829
+ });
1830
+ const DEFAULT_CACHE_TTL_MS = 3e4;
1831
+ const globalListCache = /* @__PURE__ */ new Map();
1832
+ const globalAssetCache = /* @__PURE__ */ new Map();
1833
+ const globalAssetInflightRequests = /* @__PURE__ */ new Map();
1834
+ /**
1835
+ * Creates a caching wrapper around a media repository.
1836
+ *
1837
+ * - Caches `listAssets()` results by cache key (siteId + filters)
1838
+ * - Caches `getAsset()` results by assetId
1839
+ * - 30-second TTL for cache entries
1840
+ * - Invalidates cache on write operations (create/update/delete)
1841
+ * - Prevents redundant fetches when blocks expand/collapse
1842
+ * - Deduplicates parallel requests to the same asset
1843
+ * - Uses global cache shared across all instances
1844
+ */
1845
+ function createCachedMediaRepo(baseRepo, options) {
1846
+ const cacheTtlMs = options?.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
1847
+ function buildCacheKey(options) {
1848
+ return [
1849
+ options.siteId,
1850
+ options.search ?? "",
1851
+ options.limit ?? "all",
1852
+ options.offset ?? 0,
1853
+ options.labels ?? "",
1854
+ JSON.stringify(options.mediaKinds ?? null),
1855
+ options.fileFilter ?? "all",
1856
+ options.libraryScope ?? "files-and-media"
1857
+ ].join(":");
1858
+ }
1859
+ function readCache(key, cache) {
1860
+ const entry = cache.get(key);
1861
+ if (entry === void 0) return null;
1862
+ if (entry.expiresAt <= Date.now()) {
1863
+ cache.delete(key);
1864
+ return null;
1865
+ }
1866
+ return entry.data;
1867
+ }
1868
+ function writeCache(key, data, cache) {
1869
+ cache.set(key, {
1870
+ data,
1871
+ expiresAt: Date.now() + cacheTtlMs
1872
+ });
1873
+ }
1874
+ function invalidateCache() {
1875
+ globalListCache.clear();
1876
+ globalAssetCache.clear();
1877
+ }
1878
+ return {
1879
+ invalidate: invalidateCache,
1880
+ async getAsset(assetId) {
1881
+ const cacheKey = `asset:${assetId}`;
1882
+ const entry = globalAssetCache.get(cacheKey);
1883
+ if (entry !== void 0) if (entry.expiresAt > Date.now()) return entry.data;
1884
+ else globalAssetCache.delete(cacheKey);
1885
+ const inflightRequest = globalAssetInflightRequests.get(assetId);
1886
+ if (inflightRequest !== void 0) return inflightRequest;
1887
+ const fetchPromise = baseRepo.getAsset(assetId).then((result) => {
1888
+ writeCache(cacheKey, result, globalAssetCache);
1889
+ globalAssetInflightRequests.delete(assetId);
1890
+ return result;
1891
+ }).catch((error) => {
1892
+ globalAssetInflightRequests.delete(assetId);
1893
+ throw error;
1894
+ });
1895
+ globalAssetInflightRequests.set(assetId, fetchPromise);
1896
+ return fetchPromise;
1897
+ },
1898
+ async listAssets(options) {
1899
+ const cacheKey = buildCacheKey(options);
1900
+ const cached = readCache(cacheKey, globalListCache);
1901
+ if (cached !== null) return cached;
1902
+ const result = await baseRepo.listAssets(options);
1903
+ writeCache(cacheKey, result, globalListCache);
1904
+ return result;
1905
+ },
1906
+ async createAsset(input) {
1907
+ const result = await baseRepo.createAsset(input);
1908
+ invalidateCache();
1909
+ return result;
1910
+ },
1911
+ async updateAsset(assetId, input) {
1912
+ const result = await baseRepo.updateAsset(assetId, input);
1913
+ invalidateCache();
1914
+ return result;
1915
+ },
1916
+ async deleteAsset(assetId, options) {
1917
+ const outcome = await baseRepo.deleteAsset(assetId, options);
1918
+ invalidateCache();
1919
+ return outcome;
1920
+ },
1921
+ generateStoragePath: baseRepo.generateStoragePath
1922
+ };
1923
+ }
1924
+ //#endregion
1925
+ //#region ../media-editor/src/runtimeMediaAssetState.ts
1926
+ function areShallowEqualRecords(left, right) {
1927
+ const leftKeys = Object.keys(left);
1928
+ const rightKeys = Object.keys(right);
1929
+ if (leftKeys.length !== rightKeys.length) return false;
1930
+ return leftKeys.every((key) => left[key] === right[key]);
1931
+ }
1932
+ function areEqualAssetLists(left, right) {
1933
+ return left.length === right.length && left.every((asset, index) => {
1934
+ const other = right[index];
1935
+ return other !== void 0 && areShallowEqualRecords(asset, other);
1936
+ });
1937
+ }
1938
+ function dedupeById(items) {
1939
+ return Array.from(new Map(items.map((item) => [item.id, item])).values());
1940
+ }
1941
+ function upsertById(assets, asset) {
1942
+ const existingIndex = assets.findIndex((item) => item.id === asset.id);
1943
+ if (existingIndex === -1) return [...assets, asset];
1944
+ const existing = assets[existingIndex];
1945
+ if (!existing) return [...assets, asset];
1946
+ if (areShallowEqualRecords(existing, asset)) return assets;
1947
+ const next = assets.slice();
1948
+ next[existingIndex] = asset;
1949
+ return next;
1950
+ }
1951
+ function createRuntimeMediaAssetState(siteId, baseAssets) {
1952
+ const mediaAssetIndex = buildRenderableMediaAssetIndex(baseAssets);
1953
+ return {
1954
+ siteId,
1955
+ baseAssets: mediaAssetIndex?.assets ?? [],
1956
+ registeredAssets: [],
1957
+ mediaAssetIndex
1958
+ };
1959
+ }
1960
+ function reduceRuntimeMediaAssetState(state, action) {
1961
+ switch (action.type) {
1962
+ case "siteSnapshotReplaced": {
1963
+ const { snapshot } = action;
1964
+ if (snapshot.siteId !== state.siteId) return snapshot;
1965
+ const nextBaseAssets = snapshot.baseAssets;
1966
+ if (areEqualAssetLists(nextBaseAssets, state.baseAssets)) return state;
1967
+ return {
1968
+ ...state,
1969
+ baseAssets: nextBaseAssets,
1970
+ mediaAssetIndex: state.registeredAssets.length ? indexRenderableMediaAssets(dedupeById([...nextBaseAssets, ...state.registeredAssets])) : snapshot.mediaAssetIndex
1971
+ };
1972
+ }
1973
+ case "assetRegistered":
1974
+ if (action.siteId !== state.siteId) return state;
1975
+ const nextRegisteredAssets = upsertById(state.registeredAssets, action.asset);
1976
+ if (nextRegisteredAssets === state.registeredAssets) return state;
1977
+ return {
1978
+ ...state,
1979
+ registeredAssets: nextRegisteredAssets,
1980
+ mediaAssetIndex: indexRenderableMediaAssets(dedupeById([...state.baseAssets, ...nextRegisteredAssets]))
1981
+ };
1982
+ }
1983
+ }
1984
+ //#endregion
1985
+ //#region ../media-editor/src/provider.tsx
1986
+ const DEFAULT_MEDIA_BUCKET = process.env.NEXT_PUBLIC_MEDIA_BUCKET ?? "media";
1987
+ const DEFAULT_SUPABASE_URL = (process.env.NEXT_PUBLIC_SUPABASE_URL ?? "").replace(/\/$/, "");
1988
+ function toRuntimeMediaAssetIndexItem(asset) {
1989
+ return {
1990
+ id: asset.id,
1991
+ identifier: asset.identifier,
1992
+ storageBucket: asset.storageBucket,
1993
+ storagePath: asset.storagePath,
1994
+ width: asset.width ?? null,
1995
+ height: asset.height ?? null,
1996
+ mimeType: asset.mimeType
1997
+ };
1998
+ }
1999
+ function MediaEditorProvider({ siteId, apiClient, children, bucket = DEFAULT_MEDIA_BUCKET, getPublicUrl, augmentRequest, uploaderOptions, bearerToken, supabaseUrl, mediaAssets }) {
2000
+ const snapshot = useMemo(() => createRuntimeMediaAssetState(siteId, mediaAssets ?? []), [mediaAssets, siteId]);
2001
+ const [runtimeMediaAssetState, dispatchRuntimeMediaAssetAction] = useReducer(reduceRuntimeMediaAssetState, snapshot);
2002
+ useEffect(() => {
2003
+ dispatchRuntimeMediaAssetAction({
2004
+ type: "siteSnapshotReplaced",
2005
+ snapshot
2006
+ });
2007
+ }, [snapshot]);
2008
+ const repo = useMemo(() => {
2009
+ const clientFn = (request) => {
2010
+ return apiClient(augmentRequest ? augmentRequest(request, { siteId }) : request);
2011
+ };
2012
+ return createCachedMediaRepo(createApiMediaRepo({ client: clientFn }));
2013
+ }, [
2014
+ apiClient,
2015
+ augmentRequest,
2016
+ siteId
2017
+ ]);
2018
+ const uploader = useApiMediaUploader({
2019
+ siteId,
2020
+ apiClient,
2021
+ ...uploaderOptions
2022
+ });
2023
+ const imageResolveContext = useMemo(() => buildResolveImageUrlContext({
2024
+ siteId,
2025
+ supabaseUrl: supabaseUrl ?? (DEFAULT_SUPABASE_URL || void 0),
2026
+ mediaAssetIndex: runtimeMediaAssetState.siteId === siteId ? runtimeMediaAssetState.mediaAssetIndex : snapshot.mediaAssetIndex
2027
+ }), [
2028
+ runtimeMediaAssetState,
2029
+ siteId,
2030
+ supabaseUrl,
2031
+ snapshot
2032
+ ]);
2033
+ const resolvedSupabaseUrl = imageResolveContext.supabaseUrl;
2034
+ const registerMediaAsset = useCallback((asset) => {
2035
+ if (asset.siteId !== siteId) return;
2036
+ dispatchRuntimeMediaAssetAction({
2037
+ type: "assetRegistered",
2038
+ siteId,
2039
+ asset: renderableMediaAssetSchema$1.parse(toRuntimeMediaAssetIndexItem(asset))
2040
+ });
2041
+ }, [siteId]);
2042
+ const computePublicUrl = useCallback((asset) => {
2043
+ if (getPublicUrl) return getPublicUrl(asset, { siteId });
2044
+ const targetBucket = asset.storageBucket || bucket;
2045
+ if (!resolvedSupabaseUrl) return "";
2046
+ return `${resolvedSupabaseUrl}/storage/v1/object/public/${targetBucket}/${asset.storagePath.split("/").map((segment) => encodeURIComponent(segment)).join("/")}`;
2047
+ }, [
2048
+ bucket,
2049
+ getPublicUrl,
2050
+ resolvedSupabaseUrl,
2051
+ siteId
2052
+ ]);
2053
+ return /* @__PURE__ */ jsx(MediaEditorContextProvider, {
2054
+ value: useMemo(() => ({
2055
+ siteId,
2056
+ apiClient,
2057
+ repo,
2058
+ uploader,
2059
+ uploaderOptions,
2060
+ getPublicUrl: computePublicUrl,
2061
+ registerMediaAsset,
2062
+ bearerToken,
2063
+ imageResolveContext
2064
+ }), [
2065
+ apiClient,
2066
+ bearerToken,
2067
+ computePublicUrl,
2068
+ imageResolveContext,
2069
+ registerMediaAsset,
2070
+ repo,
2071
+ siteId,
2072
+ uploader,
2073
+ uploaderOptions
2074
+ ]),
2075
+ children: /* @__PURE__ */ jsx(ImageResolveContextProvider, {
2076
+ value: imageResolveContext,
2077
+ children
2078
+ })
2079
+ });
2080
+ }
2081
+ //#endregion
2082
+ //#region ../content-editor/src/services/pageSurfaceEditorServices.ts
2083
+ async function writePageSurfaceContent(apiClient, writer, call) {
2084
+ const request = {
2085
+ params: { ...call.params },
2086
+ body: { ...call.body }
2087
+ };
2088
+ switch (writer) {
2089
+ case "draft": return savedContentReceipt(unwrapResponse(await apiClient({
2090
+ endpoint: "updatePageSurfaceDraftContent",
2091
+ ...request
2092
+ })).document);
2093
+ case "eventContentTab": {
2094
+ const result = unwrapResponse(await apiClient({
2095
+ endpoint: "saveEventContentTab",
2096
+ ...request
2097
+ }));
2098
+ return {
2099
+ ...savedContentReceipt(result.document),
2100
+ ...result.visibility === "live" ? { publication: {
2101
+ kind: "published",
2102
+ result: result.publication
2103
+ } } : {}
2104
+ };
2105
+ }
2106
+ }
2107
+ }
2108
+ function createPageSurfaceEditorServices(input, deps) {
2109
+ const params = {
2110
+ siteId: input.siteId,
2111
+ pageSurfaceId: input.pageSurfaceId
2112
+ };
2113
+ return {
2114
+ kind: "surface",
2115
+ async saveContent(content, optimisticHash) {
2116
+ return writePageSurfaceContent(deps.apiClient, input.contentWriter ?? "draft", {
2117
+ params,
2118
+ body: {
2119
+ data: content,
2120
+ optimisticHash
2121
+ }
2122
+ });
2123
+ },
2124
+ async saveMetadata(payload, expectedDraftUpdatedAt, operationId) {
2125
+ const result = unwrapResponse(await deps.apiClient({
2126
+ endpoint: "updatePageSurfaceRouteMetadata",
2127
+ params,
2128
+ options: { headers: { [OPERATION_ID_HEADER]: operationId } },
2129
+ body: {
2130
+ ...toPageSurfaceMetadataPayload(payload, input.route),
2131
+ expectedDraftUpdatedAt
2132
+ }
2133
+ }));
2134
+ return {
2135
+ ...savedRouteReceipt(result.route),
2136
+ editRevision: result.editRevision
2137
+ };
2138
+ },
2139
+ async publish() {
2140
+ return {
2141
+ kind: "pageSurface",
2142
+ publication: unwrapResponse(await deps.apiClient({
2143
+ endpoint: "publishPageSurface",
2144
+ params
2145
+ }))
2146
+ };
2147
+ },
2148
+ async discardDraft({ contentRevision }) {
2149
+ if (contentRevision === null) throw new Error("This draft could not be discarded. Refresh the page, then try again.");
2150
+ const result = unwrapResponse(await deps.apiClient({
2151
+ endpoint: "discardPageSurfaceDraftContent",
2152
+ params,
2153
+ body: { optimisticHash: contentRevision }
2154
+ }));
2155
+ return result.kind === "unchanged" ? result : {
2156
+ kind: "serverDocument",
2157
+ journal: result.journal,
2158
+ document: result.document,
2159
+ blockState: result.blockState
2160
+ };
2161
+ },
2162
+ deletion: { kind: "deletedWithOwner" }
2163
+ };
2164
+ }
2165
+ function toPageSurfaceMetadataPayload(payload, baseline) {
2166
+ const allowed = /* @__PURE__ */ new Set([
2167
+ "draftMetaTitle",
2168
+ "draftMetaDescription",
2169
+ "ogImageId"
2170
+ ]);
2171
+ const managedFields = {
2172
+ draftTitle: baseline.draftTitle,
2173
+ draftPath: baseline.draftPath
2174
+ };
2175
+ const changedManagedFields = Object.entries(managedFields).filter(([key, value]) => key in payload && payload[key] !== value).map(([key]) => key);
2176
+ const unknownFields = Object.keys(payload).filter((key) => !allowed.has(key) && !(key in managedFields));
2177
+ const unsupported = [...changedManagedFields, ...unknownFields];
2178
+ if (unsupported.length > 0) throw new Error(`Page surface metadata does not support: ${unsupported.join(", ")}`);
2179
+ return {
2180
+ ...typeof payload.draftMetaTitle === "string" || payload.draftMetaTitle === null ? { draftMetaTitle: payload.draftMetaTitle } : {},
2181
+ ...typeof payload.draftMetaDescription === "string" || payload.draftMetaDescription === null ? { draftMetaDescription: payload.draftMetaDescription } : {},
2182
+ ...typeof payload.ogImageId === "string" || payload.ogImageId === null ? { ogImageId: payload.ogImageId } : {}
2183
+ };
2184
+ }
2185
+ const PREVIEW_EDITABLE_OUTLINE = `1px dashed rgba(156, 163, 175, 0.75)`;
2186
+ //#endregion
2187
+ //#region ../content-editor/src/session-journal/SiteAdmissionObserver.tsx
2188
+ /** Node-free SDK hosts read the same owner. Notifications prompt a read; focus and interval cover missed events. */
2189
+ function SiteAdmissionObserver({ siteId, apiClient, siteOnly, subscribeToAdmissionChanges }) {
2190
+ const store = useEditorUiStoreInstance();
2191
+ useLayoutEffect(() => store.getState().bindAdmission(editorAdmissionSession.site(siteId)), [siteId, store]);
2192
+ useEffect(() => {
2193
+ if (!siteOnly) return;
2194
+ const abort = new AbortController();
2195
+ const refresh = () => {
2196
+ rereadSiteAdmission(apiClient, siteId, abort.signal).catch((error) => {
2197
+ if (!abort.signal.aborted) console.error("Failed to refresh editor admission", error);
2198
+ });
2199
+ };
2200
+ const unsubscribe = subscribeToAdmissionChanges?.(refresh);
2201
+ window.addEventListener("focus", refresh);
2202
+ const interval = window.setInterval(refresh, 25e3);
2203
+ return () => {
2204
+ abort.abort();
2205
+ unsubscribe?.();
2206
+ window.removeEventListener("focus", refresh);
2207
+ window.clearInterval(interval);
2208
+ };
2209
+ }, [
2210
+ apiClient,
2211
+ siteId,
2212
+ siteOnly,
2213
+ store,
2214
+ subscribeToAdmissionChanges
2215
+ ]);
2216
+ return null;
2217
+ }
2218
+ /** Read the site's admission again and hand it to the one owner, unless the observer has gone. */
2219
+ async function rereadSiteAdmission(apiClient, siteId, signal) {
2220
+ const read = unwrapResponse(await apiClient({
2221
+ endpoint: "readEditAdmission",
2222
+ params: { siteId },
2223
+ options: {
2224
+ headers: { "X-Riverbank-Editor-Client": getEditorClientId() },
2225
+ cache: "no-store",
2226
+ signal
2227
+ }
2228
+ }));
2229
+ if (!signal.aborted) observeEditorAdmission(siteId, read);
2230
+ }
2231
+ //#endregion
2232
+ //#region ../preview-next/src/client/preview/previewRenderingOverride.ts
2233
+ const noCookie = () => null;
2234
+ const noOverride = { kind: "none" };
2235
+ /** A choice ends this rendering override; an explicit cookie choice can start it again. */
2236
+ function usePreviewRenderingOverride(input) {
2237
+ const [dismissed, setDismissed] = useState(null);
2238
+ const cookie = useSyncExternalStore(subscribePreviewThemeCookie, readPreviewThemeCookie, noCookie);
2239
+ const end = useCallback(() => {
2240
+ setDismissed(input);
2241
+ writePreviewThemeCookie(null);
2242
+ }, [input]);
2243
+ return {
2244
+ override: !cookie && dismissed && authoredValuesEqual(dismissed, input) ? noOverride : input,
2245
+ end
2246
+ };
2247
+ }
2248
+ //#endregion
2249
+ //#region ../preview-next/src/client/preview/PreviewAuthInit.tsx
2250
+ function PreviewAuthInit({ children, session, siteId, siteSlug, pageId, token }) {
2251
+ const lastInitRef = useRef(null);
2252
+ const sessionKey = session ? session.kind === "userSession" ? `${session.kind}:${session.canEdit}:${session.canManage}:${session.expiresAt ?? "no-expiry"}` : `${session.kind}:${session.expiresAt ?? "no-expiry"}` : "none";
2253
+ const currentKey = `${siteId}:${pageId ?? "no-page"}:${sessionKey}:${token ?? "no-token"}`;
2254
+ if (lastInitRef.current !== currentKey) {
2255
+ initPreviewAuth({
2256
+ session,
2257
+ siteId,
2258
+ siteSlug,
2259
+ pageId,
2260
+ token
2261
+ });
2262
+ lastInitRef.current = currentKey;
2263
+ }
2264
+ return /* @__PURE__ */ jsx(Fragment$1, { children });
2265
+ }
2266
+ //#endregion
2267
+ //#region ../preview-next/src/client/preview/pageSchema.ts
2268
+ const PAGE_CONTENT_TYPE_SCHEMA = {
2269
+ version: 1,
2270
+ fields: [],
2271
+ labels: {
2272
+ singular: "Page",
2273
+ plural: "Pages"
2274
+ },
2275
+ routing: {
2276
+ enabled: true,
2277
+ pattern: "/{slug}",
2278
+ slugField: "slug",
2279
+ prefix: "/"
2280
+ }
2281
+ };
2282
+ //#endregion
2283
+ //#region ../preview-next/src/client/blocks/linkedEntryRenderOverlay.ts
2284
+ /**
2285
+ * What a tab rendering its own edits lays over the server render for one record:
2286
+ * its edit, or else its accepted save until the render catches up (rows H1, H3, H4).
2287
+ * A pristine record with no handover (even one kept after a discard, issue 1553 D2)
2288
+ * contributes nothing, so it never masks later server-rendered content.
2289
+ */
2290
+ function ownEditsOverlay(entry, handovers) {
2291
+ if (isEdited(entry.sync)) {
2292
+ const content = resolveRenderedValues("own-edits", entry, null);
2293
+ return content ? {
2294
+ content: { ...content },
2295
+ optimisticHash: baselineRevisionOf(entry.sync) ?? null
2296
+ } : null;
2297
+ }
2298
+ const handover = activeLinkedSaveHandover(handovers, entry.meta.entryId, entry.sync);
2299
+ const saved = entry.sync.baseline.values;
2300
+ return handover && saved ? {
2301
+ content: { ...saved },
2302
+ optimisticHash: handover.revision,
2303
+ handoverRevision: handover.revision
2304
+ } : null;
2305
+ }
2306
+ /** A viewer lays another tab's live draft over the render, and nothing else. */
2307
+ function liveDraftOverlay(entry, remote) {
2308
+ const content = remote ? resolveRenderedValues("live-drafts", entry, remote) : null;
2309
+ return content ? {
2310
+ content: { ...content },
2311
+ optimisticHash: baselineRevisionOf(entry.sync) ?? null
2312
+ } : null;
2313
+ }
2314
+ /**
2315
+ * The linked-entry values the preview renders, following the tab's render source
2316
+ * (its own edits, or another tab's live drafts while it only views). Entries only
2317
+ * another tab is editing are included too. A viewer never reads its own handovers,
2318
+ * so a later external write is never masked (row H8).
2319
+ */
2320
+ function linkedEntryRenderOverlaysFromStore(uiStore) {
2321
+ const state = uiStore.getState();
2322
+ const source = renderSourceFor(state.editability);
2323
+ const entries = state.linkedEntries.inspect();
2324
+ const local = entries.flatMap((entry) => {
2325
+ const remote = remoteDraftValues(state.remoteDrafts, {
2326
+ kind: "linked-entry",
2327
+ id: entry.meta.entryId
2328
+ });
2329
+ const overlay = source === "own-edits" ? ownEditsOverlay(entry, state.linkedSaveHandovers) : liveDraftOverlay(entry, remote);
2330
+ return overlay ? [[entry.meta.entryId, overlay]] : [];
2331
+ });
2332
+ const localIds = new Set(entries.map((entry) => entry.meta.entryId));
2333
+ const remoteOnly = [...state.remoteDrafts?.values() ?? []].flatMap((entry) => {
2334
+ if (entry.item.kind !== "linked-entry") return [];
2335
+ const entryId = unsafeAsLinkedContentEntryId(entry.item.id);
2336
+ return localIds.has(entryId) ? [] : [[entryId, { content: entry.item.values }]];
2337
+ });
2338
+ return new Map([...local, ...remoteOnly]);
2339
+ }
2340
+ function applyLinkedEntryRenderOverlay(value, overlays) {
2341
+ if (overlays.size === 0) return value;
2342
+ return overlayValue(value, overlays);
2343
+ }
2344
+ function applyLinkedEntryRenderOverlayToDataContext(dataContext, overlays) {
2345
+ if (!dataContext?.resolvedData || overlays.size === 0) return dataContext;
2346
+ const resolvedData = applyLinkedEntryRenderOverlay(dataContext.resolvedData, overlays);
2347
+ if (resolvedData === dataContext.resolvedData) return dataContext;
2348
+ return {
2349
+ ...dataContext,
2350
+ resolvedData
2351
+ };
2352
+ }
2353
+ function overlayValue(value, overlays) {
2354
+ if (Array.isArray(value)) {
2355
+ let changed = false;
2356
+ const next = value.map((item) => {
2357
+ const overlaid = overlayValue(item, overlays);
2358
+ if (overlaid !== item) changed = true;
2359
+ return overlaid;
2360
+ });
2361
+ return changed ? next : value;
2362
+ }
2363
+ if (!isRecord$1(value)) return value;
2364
+ const match = matchingOverlay(value, overlays);
2365
+ if (match) return overlaidEntry(value, match.meta, match.overlay);
2366
+ let changed = false;
2367
+ const next = {};
2368
+ for (const [key, child] of Object.entries(value)) {
2369
+ const overlaid = overlayValue(child, overlays);
2370
+ if (overlaid !== child) changed = true;
2371
+ next[key] = overlaid;
2372
+ }
2373
+ return changed ? next : value;
2374
+ }
2375
+ /**
2376
+ * The overlay for a rendered linked entry, if one applies. A handover stops at an
2377
+ * occurrence already rendered at the saved revision (issue 1553, DP6).
2378
+ */
2379
+ function matchingOverlay(value, overlays) {
2380
+ const meta = parseLinkedEntryMeta(value[LINKED_CONTENT_ENTRY_META_KEY]);
2381
+ const overlay = meta ? overlays.get(unsafeAsLinkedContentEntryId(meta.entryId)) : void 0;
2382
+ if (!meta || !overlay) return null;
2383
+ return overlay.handoverRevision !== void 0 && meta.optimisticHash === overlay.handoverRevision ? null : {
2384
+ meta,
2385
+ overlay
2386
+ };
2387
+ }
2388
+ function overlaidEntry(value, meta, overlay) {
2389
+ const displayProjections = resolveOverlayDisplayProjections(overlay.content, meta);
2390
+ const titleProjection = resolveOverlayTitleProjection({
2391
+ currentValue: value,
2392
+ content: overlay.content,
2393
+ meta,
2394
+ displayProjections
2395
+ });
2396
+ const title = titleProjection ? { title: titleProjection } : {};
2397
+ return {
2398
+ ...value,
2399
+ ...displayProjections,
2400
+ ...title,
2401
+ content: overlay.content,
2402
+ optimisticHash: overlayRevision(overlay, meta),
2403
+ [LINKED_CONTENT_ENTRY_META_KEY]: {
2404
+ ...meta,
2405
+ ...title,
2406
+ optimisticHash: overlayRevision(overlay, meta)
2407
+ }
2408
+ };
2409
+ }
2410
+ /**
2411
+ * Each linked entry's rendered revisions, one per occurrence in the loader data, read
2412
+ * before any overlay. Local handover retention compares them with the saved revision
2413
+ * (issue 1553, DP7).
2414
+ */
2415
+ function renderedLinkedRevisions(dataContext) {
2416
+ const occurrences = linkedEntryOccurrences(dataContext?.resolvedData);
2417
+ const entryIds = [...new Set(occurrences.map((meta) => meta.entryId))];
2418
+ return new Map(entryIds.map((entryId) => [unsafeAsLinkedContentEntryId(entryId), occurrences.filter((meta) => meta.entryId === entryId).map((meta) => meta.optimisticHash)]));
2419
+ }
2420
+ function linkedEntryOccurrences(value) {
2421
+ if (Array.isArray(value)) return value.flatMap(linkedEntryOccurrences);
2422
+ if (!isRecord$1(value)) return [];
2423
+ const meta = parseLinkedEntryMeta(value[LINKED_CONTENT_ENTRY_META_KEY]);
2424
+ const nested = Object.entries(value).filter(([key]) => key !== LINKED_CONTENT_ENTRY_META_KEY).flatMap(([, child]) => linkedEntryOccurrences(child));
2425
+ return meta ? [meta, ...nested] : nested;
2426
+ }
2427
+ function resolveOverlayDisplayProjections(content, meta) {
2428
+ const projections = {};
2429
+ for (const source of meta.fieldSources) {
2430
+ if (source.kind !== "content-field") continue;
2431
+ if (source.displayPath.startsWith("content.")) continue;
2432
+ if (source.displayPath.includes(".")) continue;
2433
+ if (!(source.fieldPath in content)) continue;
2434
+ projections[source.displayPath] = content[source.fieldPath];
2435
+ }
2436
+ return projections;
2437
+ }
2438
+ function resolveOverlayTitleProjection(input) {
2439
+ const projectedTitle = input.displayProjections.title;
2440
+ if (typeof projectedTitle === "string") return projectedTitle;
2441
+ if (input.meta.fieldSources.find((source) => source.displayPath === "title")?.kind === "read-only") {
2442
+ const currentTitle = input.currentValue.title;
2443
+ return typeof currentTitle === "string" ? currentTitle : input.meta.title;
2444
+ }
2445
+ return resolveOverlayTitle(input.content, input.meta);
2446
+ }
2447
+ function resolveOverlayTitle(content, meta) {
2448
+ const titleField = meta.contentType.titleField;
2449
+ if (titleField) {
2450
+ const value = content[titleField];
2451
+ if (typeof value === "string" && value.trim().length > 0) return value;
2452
+ }
2453
+ return meta.title;
2454
+ }
2455
+ function parseLinkedEntryMeta(value) {
2456
+ return getLinkedContentEntryMeta({ [LINKED_CONTENT_ENTRY_META_KEY]: value });
2457
+ }
2458
+ function isRecord$1(value) {
2459
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2460
+ }
2461
+ function overlayRevision(overlay, meta) {
2462
+ return overlay.optimisticHash === void 0 ? meta.optimisticHash : overlay.optimisticHash;
2463
+ }
2464
+ //#endregion
2465
+ //#region ../preview-next/src/client/blocks/useLinkedSaveHandoverRetention.ts
2466
+ /**
2467
+ * The host's refresh of its server data: the same callback live drafts give a viewer
2468
+ * whose saved remote draft lags. Absent when the host supplies none.
2469
+ */
2470
+ const PreviewRefreshBaselinesContext = createContext(null);
2471
+ /** Changes whenever a handover is recorded or dropped, so the renderer re-renders. */
2472
+ function linkedSaveHandoversVersion(handovers) {
2473
+ return [...handovers].map(([entryId, handover]) => `${entryId}@${handover.revision}`).join("|");
2474
+ }
2475
+ /**
2476
+ * Local retention of this tab's linked-entry save handovers (issue 1553, DP7). The
2477
+ * renderer holds the rendered data, so it decides catch-up: a handover whose entry is
2478
+ * rendered at the saved revision everywhere drops with no refresh (row H1b); otherwise
2479
+ * the shared timing asks the host for one refresh, then drops it (row H2).
2480
+ */
2481
+ function useLinkedSaveHandoverRetention(uiStore, dataContext, liveResolvedData) {
2482
+ const rendered = useMemo(() => renderedLinkedRevisions(mergeResolvedDataContext(dataContext, liveResolvedData)), [dataContext, liveResolvedData]);
2483
+ const refreshBaselines = useContext(PreviewRefreshBaselinesContext);
2484
+ const refreshRef = useRef(refreshBaselines);
2485
+ useEffect(() => {
2486
+ refreshRef.current = refreshBaselines;
2487
+ });
2488
+ useRetentionTicks(uiStore, useCallback(() => {
2489
+ const state = uiStore.getState();
2490
+ if (state.linkedSaveHandovers.size === 0) return;
2491
+ const plan = planLinkedSaveHandoverRetention(state.linkedSaveHandovers, rendered, Date.now());
2492
+ if (!plan.changed) return;
2493
+ state.setLinkedSaveHandovers(plan.entries);
2494
+ if (plan.refresh) refreshRef.current?.();
2495
+ }, [rendered, uiStore]));
2496
+ }
2497
+ //#endregion
2498
+ //#region ../preview-next/src/client/preview/PreviewEntryControllerProvider.tsx
2499
+ function previewLiveDraftsConfig(liveDrafts, previewToken, siteId, scope, refreshBaselines) {
2500
+ if (!liveDrafts || !previewToken) return null;
2501
+ return {
2502
+ client: liveDrafts.client,
2503
+ auth: {
2504
+ kind: "token",
2505
+ accessToken: previewToken
2506
+ },
2507
+ siteId,
2508
+ scope,
2509
+ refreshBaselines
2510
+ };
2511
+ }
2512
+ function previewEntryRoute(entryData) {
2513
+ return {
2514
+ draftMetaTitle: entryData.draftMetaTitle ?? null,
2515
+ draftMetaDescription: entryData.draftMetaDescription ?? null,
2516
+ publishedMetaTitle: entryData.metaTitle ?? null,
2517
+ publishedMetaDescription: entryData.metaDescription ?? null,
2518
+ ogImageId: entryData.ogImageId ?? null
2519
+ };
2520
+ }
2521
+ function snapshotFromPreviewEntry(entryData) {
2522
+ const title = entryData.title ?? "";
2523
+ const status = entryData.status ?? "draft";
2524
+ const publishAt = entryData.publishAt ?? null;
2525
+ return {
2526
+ kind: "routable",
2527
+ id: entryData.id,
2528
+ draft: {
2529
+ title,
2530
+ slug: entryData.slug || "",
2531
+ status,
2532
+ publishAt,
2533
+ path: entryData.draftPath ?? entryData.path ?? ""
2534
+ },
2535
+ published: {
2536
+ title,
2537
+ path: entryData.path ?? "",
2538
+ status,
2539
+ publishAt: entryData.lastPublishedAt ?? null
2540
+ },
2541
+ status,
2542
+ route: previewEntryRoute(entryData)
2543
+ };
2544
+ }
2545
+ function snapshotFromPreviewPage(pageId, metadata, schema) {
2546
+ return createSnapshotFromPageRecord({
2547
+ id: pageId,
2548
+ draftTitle: metadata.draftTitle,
2549
+ draftPath: metadata.draftPath,
2550
+ draftStatus: metadata.draftStatus,
2551
+ title: metadata.title,
2552
+ path: metadata.path,
2553
+ status: metadata.status,
2554
+ publishedAt: metadata.publishedAt,
2555
+ lastPublishedAt: metadata.lastPublishedAt,
2556
+ draftMetaTitle: metadata.draftMetaTitle,
2557
+ draftMetaDescription: metadata.draftMetaDescription,
2558
+ publishedMetaTitle: metadata.publishedMetaTitle,
2559
+ publishedMetaDescription: metadata.publishedMetaDescription,
2560
+ ogImageId: metadata.ogImageId
2561
+ }, createRoutingHelpers(schema, { slug: null }), {
2562
+ title: "",
2563
+ slug: null
2564
+ });
2565
+ }
2566
+ function initialPreviewEntry(entryData, pageMetadata, pageId, schema) {
2567
+ if (entryData) return snapshotFromPreviewEntry(entryData);
2568
+ return pageMetadata && pageId ? snapshotFromPreviewPage(pageId, pageMetadata, schema) : void 0;
2569
+ }
2570
+ function previewEntity(pageId, pageNodeType, entryData, routeId) {
2571
+ return {
2572
+ id: pageId || entryData?.id || "",
2573
+ type: entryData?.type || "page",
2574
+ label: entryData && pageNodeType !== "page_surface" ? "Entry" : "Page",
2575
+ routeId: routeId ?? void 0
2576
+ };
2577
+ }
2578
+ function previewValues(entryData, pageMetadata) {
2579
+ if (!entryData) return {
2580
+ kind: "page",
2581
+ metadataRevision: pageMetadata?.draftUpdatedAt ?? null
2582
+ };
2583
+ const revision = entryData.editorRevision;
2584
+ if (!revision?.content) throw new Error("Preview draft is missing its editor revision");
2585
+ return {
2586
+ kind: "content",
2587
+ content: revision.contentValues,
2588
+ publishedContent: revision.publishedContent,
2589
+ contentRevision: revision.content,
2590
+ metadataRevision: revision.metadata,
2591
+ editRevision: typeof revision.editRevision === "number" ? revision.editRevision : null
2592
+ };
2593
+ }
2594
+ /** Loading may render the document, but grants neither lease participation nor shortcuts. */
2595
+ function previewAuthoringMode(mode, admitted) {
2596
+ return { requestedEditingMode: admitted && mode.requestedEditingMode };
2597
+ }
2598
+ function PreviewEntryControllerProvider({ children, businessTimeZone, siteId, pageId, pageNodeType = "page", routeId: providedRouteId, entryData, contentTypeSchema, initialStatus = "draft", blockFieldExtensions, pageMetadata, initialPageJournalState, authoringAdmitted, apiClient, subscribeToLeaseChanges, liveDrafts }) {
2599
+ const { requestServerRefresh } = useServerRefresh();
2600
+ const authoring = previewAuthoringMode(useEditor(), authoringAdmitted);
2601
+ const previewToken = usePreviewToken();
2602
+ const schema = contentTypeSchema ?? PAGE_CONTENT_TYPE_SCHEMA;
2603
+ const initialEntry = useMemo(() => initialPreviewEntry(entryData, pageMetadata, pageId, schema), [
2604
+ entryData,
2605
+ pageMetadata,
2606
+ pageId,
2607
+ schema
2608
+ ]);
2609
+ const entity = previewEntity(pageId, pageNodeType, entryData, providedRouteId);
2610
+ const leaseScope = previewLeaseScope(entity.id, pageNodeType, entryData);
2611
+ const values = previewValues(entryData, pageMetadata);
2612
+ const rendered = /* @__PURE__ */ jsx(RefreshBaselinesForRender, {
2613
+ liveDrafts,
2614
+ children
2615
+ });
2616
+ const editLease = usePreviewLeaseParticipation({
2617
+ requestedEditingMode: authoring.requestedEditingMode,
2618
+ siteId,
2619
+ pageId,
2620
+ pageNodeType,
2621
+ leaseScope,
2622
+ subscribeToLeaseChanges
2623
+ });
2624
+ const apiClientFactory = useMemo(() => createEditorApiClientFactory(apiClient), [apiClient]);
2625
+ const common = {
2626
+ displayContext: useMemo(() => ({
2627
+ locale: "en-GB",
2628
+ timeZone: businessTimeZone
2629
+ }), [businessTimeZone]),
2630
+ apiClientFactory,
2631
+ editLease,
2632
+ type: entity.type,
2633
+ siteId,
2634
+ owner: {
2635
+ kind: "contentEntry",
2636
+ contentEntryId: entity.id
2637
+ },
2638
+ routeId: entity.routeId,
2639
+ schema,
2640
+ entityLabel: entity.label,
2641
+ initialEntry,
2642
+ initialMetadataRevision: values.metadataRevision,
2643
+ initialPageJournalState,
2644
+ blockFieldExtensions,
2645
+ liveDrafts: previewLiveDraftsForScope(liveDrafts, previewToken, siteId, leaseScope, requestServerRefresh)
2646
+ };
2647
+ if (pageNodeType === "page_surface" && pageId && pageMetadata) {
2648
+ if (values.kind !== "content") throw new Error("Preview draft is missing its editor revision");
2649
+ return /* @__PURE__ */ jsx(PreviewPageSurfaceController, {
2650
+ common,
2651
+ pageSurfaceId: pageId,
2652
+ pageMetadata,
2653
+ values,
2654
+ children: rendered
2655
+ });
2656
+ }
2657
+ return values.kind === "content" ? /* @__PURE__ */ jsx(EntryControllerProvider, {
2658
+ ...common,
2659
+ kind: "content",
2660
+ initialContent: values.content,
2661
+ initialPublishedContent: values.publishedContent,
2662
+ initialContentRevision: values.contentRevision,
2663
+ initialEditRevision: values.editRevision,
2664
+ children: rendered
2665
+ }) : /* @__PURE__ */ jsx(EntryControllerProvider, {
2666
+ ...common,
2667
+ kind: "page",
2668
+ initialStatus,
2669
+ children: rendered
2670
+ });
2671
+ }
2672
+ function previewLeaseScope(id, pageNodeType, entryData) {
2673
+ return id ? requiredPreviewLeaseScope({
2674
+ nodeType: previewLeaseNodeType(pageNodeType, entryData),
2675
+ nodeId: id
2676
+ }) : null;
2677
+ }
2678
+ function previewLiveDraftsForScope(liveDrafts, token, siteId, scope, refreshBaselines) {
2679
+ return scope ? previewLiveDraftsConfig(liveDrafts, token, siteId, scope, refreshBaselines) : null;
2680
+ }
2681
+ /** Lease participation and its server-read invalidation share the same preview identity. */
2682
+ function usePreviewLeaseParticipation({ requestedEditingMode, siteId, pageId, pageNodeType, leaseScope, subscribeToLeaseChanges }) {
2683
+ const queryClient = useQueryClient();
2684
+ const { requestServerRefresh } = useServerRefresh();
2685
+ if (requestedEditingMode && !leaseScope) return {
2686
+ kind: "exempt",
2687
+ reason: "sdk"
2688
+ };
2689
+ return requestedEditingMode && leaseScope ? {
2690
+ siteId,
2691
+ scope: leaseScope,
2692
+ subscribeToLeaseChanges,
2693
+ onGranted: () => {
2694
+ requestServerRefresh();
2695
+ if (pageId && pageNodeType === "page_surface") queryClient.invalidateQueries({ queryKey: blocksKeys.surfaceSlots(siteId, pageId) });
2696
+ }
2697
+ } : VIEWING_PARTICIPATION;
2698
+ }
2699
+ function RefreshBaselinesForRender({ liveDrafts, children }) {
2700
+ const { requestServerRefresh } = useServerRefresh();
2701
+ return /* @__PURE__ */ jsx(PreviewRefreshBaselinesContext.Provider, {
2702
+ value: liveDrafts ? requestServerRefresh : null,
2703
+ children
2704
+ });
2705
+ }
2706
+ /**
2707
+ * An event's page in preview: its content is the page surface's, saved and
2708
+ * published through the page-surface services. Its published content is what
2709
+ * the draft is compared with, and a page with none has never been published,
2710
+ * so it has no Discard.
2711
+ */
2712
+ function PreviewPageSurfaceController({ common, pageSurfaceId, pageMetadata, values, children }) {
2713
+ const route = {
2714
+ draftTitle: pageMetadata.draftTitle,
2715
+ draftPath: pageMetadata.draftPath
2716
+ };
2717
+ const siteId = common.siteId;
2718
+ return /* @__PURE__ */ jsx(EntryControllerProvider, {
2719
+ ...common,
2720
+ kind: "content",
2721
+ owner: {
2722
+ kind: "pageSurface",
2723
+ pageSurfaceId
2724
+ },
2725
+ services: (client) => createPageSurfaceEditorServices({
2726
+ siteId,
2727
+ pageSurfaceId,
2728
+ route
2729
+ }, { apiClient: client }),
2730
+ initialContent: values.content,
2731
+ initialContentRevision: values.contentRevision,
2732
+ initialEditRevision: values.editRevision,
2733
+ initialPublishedContent: values.publishedContent,
2734
+ children
2735
+ });
2736
+ }
2737
+ function previewLeaseNodeType(pageNodeType, entryData) {
2738
+ if (pageNodeType === "page_surface") return "page_surface";
2739
+ return entryData ? "content_entry" : "page";
2740
+ }
2741
+ function requiredPreviewLeaseScope(input) {
2742
+ const scope = parseEditLeaseScope(input);
2743
+ if (!scope) throw new Error("Invalid preview editor lease scope");
2744
+ return scope;
2745
+ }
2746
+ //#endregion
2747
+ //#region ../preview-next/src/client/preview/usePreviewKeepAlive.ts
2748
+ function withJitter(baseMs) {
2749
+ const delta = (Math.random() * 2 - 1) * PREVIEW_KEEP_ALIVE_JITTER_RATIO * baseMs;
2750
+ return Math.max(15e3, Math.round(baseMs + delta));
2751
+ }
2752
+ function usePreviewKeepAlive({ enabled, fetcher, intervalMs = PREVIEW_KEEP_ALIVE_INTERVAL_MS }) {
2753
+ useEffect(() => {
2754
+ if (!enabled) return void 0;
2755
+ const unregister = registerPreviewRenewalFetcher(fetcher);
2756
+ const keepAlive = () => {
2757
+ renewPreviewSession();
2758
+ };
2759
+ const checkWhenVisible = () => {
2760
+ if (document.visibilityState === "visible") keepAlive();
2761
+ };
2762
+ keepAlive();
2763
+ const id = window.setInterval(keepAlive, withJitter(intervalMs));
2764
+ document.addEventListener("visibilitychange", checkWhenVisible);
2765
+ return () => {
2766
+ unregister();
2767
+ window.clearInterval(id);
2768
+ document.removeEventListener("visibilitychange", checkWhenVisible);
2769
+ };
2770
+ }, [
2771
+ enabled,
2772
+ fetcher,
2773
+ intervalMs
2774
+ ]);
2775
+ }
2776
+ //#endregion
2777
+ //#region ../preview-next/src/client/preview/PreviewKeepAliveClient.tsx
2778
+ function PreviewKeepAliveClient({ baseFetch }) {
2779
+ const { canRenew } = usePreviewAuth();
2780
+ usePreviewKeepAlive({
2781
+ enabled: canRenew,
2782
+ fetcher: baseFetch ?? fetch
2783
+ });
2784
+ return null;
2785
+ }
2786
+ //#endregion
2787
+ //#region ../preview-next/src/client/preview/PreviewLeaseEditingMode.tsx
2788
+ function projectEditingAvailability({ canEdit, requestedEditingMode, editability }) {
2789
+ if (!canEdit || !requestedEditingMode) return "blocked";
2790
+ if (canEditorWrite(editability)) return "ready";
2791
+ if (editability.kind === "acquiring" || editability.kind === "viewing") return "pending";
2792
+ return "blocked";
2793
+ }
2794
+ /** Derives preview editing permission from the live auth and lease authorities. */
2795
+ function PreviewLeaseEditingMode() {
2796
+ const { canEdit } = usePreviewAuth();
2797
+ const editability = useEditorUiStore((state) => state.editability);
2798
+ const drawerOpen = useEditorUiStore((state) => state.drawerOpen);
2799
+ const setDrawerOpen = useEditorUiStore((state) => state.setDrawerOpen);
2800
+ const { requestedEditingMode, setEditingAvailability } = useEditor();
2801
+ const availability = projectEditingAvailability({
2802
+ canEdit,
2803
+ requestedEditingMode,
2804
+ editability
2805
+ });
2806
+ useEffect(() => setEditingAvailability(availability), [availability, setEditingAvailability]);
2807
+ useEffect(() => {
2808
+ if (!requestedEditingMode && drawerOpen) setDrawerOpen(false);
2809
+ }, [
2810
+ requestedEditingMode,
2811
+ drawerOpen,
2812
+ setDrawerOpen
2813
+ ]);
2814
+ return null;
2815
+ }
2816
+ //#endregion
2817
+ //#region ../preview-next/src/client/preview/previewModeRootAttribute.ts
2818
+ /**
2819
+ * Marks the document root with the preview's mode while the preview shell is
2820
+ * mounted: "view" or "edit". Site CSS keys off it to put floating site
2821
+ * overlays (`[data-rb-site-overlay]`) away while editing, without the site
2822
+ * knowing about the editor.
2823
+ */
2824
+ const PREVIEW_MODE_ATTRIBUTE = "data-rb-preview-mode";
2825
+ function previewModeValue(isEditingMode) {
2826
+ return isEditingMode ? "edit" : "view";
2827
+ }
2828
+ /** Follows mode changes, and leaves the root as it found it on unmount. */
2829
+ function usePreviewModeRootAttribute(isEditingMode) {
2830
+ useEffect(() => {
2831
+ const root = document.documentElement;
2832
+ root.setAttribute(PREVIEW_MODE_ATTRIBUTE, previewModeValue(isEditingMode));
2833
+ return () => root.removeAttribute(PREVIEW_MODE_ATTRIBUTE);
2834
+ }, [isEditingMode]);
2835
+ }
2836
+ //#endregion
2837
+ //#region ../preview-next/src/client/preview/PreviewEditingModeProvider.tsx
2838
+ function resolvePreviewEditingMode(stored) {
2839
+ return stored === "edit";
2840
+ }
2841
+ /** Tab-local intent only. Auth and the destination's lease still own write permission. */
2842
+ function PreviewEditingModeProvider({ children, siteId }) {
2843
+ return /* @__PURE__ */ jsxs(EditorProvider, {
2844
+ initialEditingAllowed: false,
2845
+ children: [/* @__PURE__ */ jsx(PreviewEditingModePersistence, { siteId }), children]
2846
+ }, siteId);
2847
+ }
2848
+ function readMode(key) {
2849
+ try {
2850
+ return resolvePreviewEditingMode(window.sessionStorage.getItem(key));
2851
+ } catch {
2852
+ return false;
2853
+ }
2854
+ }
2855
+ function writeMode(key, requested) {
2856
+ try {
2857
+ window.sessionStorage.setItem(key, previewModeValue(requested));
2858
+ } catch {}
2859
+ }
2860
+ function PreviewEditingModePersistence({ siteId }) {
2861
+ const { requestedEditingMode, setEditingMode } = useEditor();
2862
+ const [restored, setRestored] = useState(false);
2863
+ const key = `riverbank:preview-mode:${siteId}`;
2864
+ useEffect(() => {
2865
+ const restore = () => setEditingMode(readMode(key));
2866
+ setEditingMode(Boolean(new URLSearchParams(window.location.search).get("preview_block")) || readMode(key));
2867
+ setRestored(true);
2868
+ window.addEventListener("pageshow", restore);
2869
+ return () => window.removeEventListener("pageshow", restore);
2870
+ }, [key, setEditingMode]);
2871
+ useEffect(() => {
2872
+ if (restored) writeMode(key, requestedEditingMode);
2873
+ }, [
2874
+ key,
2875
+ requestedEditingMode,
2876
+ restored
2877
+ ]);
2878
+ return null;
2879
+ }
2880
+ //#endregion
2881
+ //#region ../preview-next/src/client/preview/previewDocumentFrame.ts
2882
+ const PREVIEW_DOCUMENT_FRAME_CLASS_NAME = "builder-preview-document-frame";
2883
+ /** Requested editing survives lease/loading changes; exiting edit mode ignores saved editor preferences. */
2884
+ function resolvePreviewViewport(input) {
2885
+ if (!input.requestedEditingMode) return {
2886
+ viewportMode: "squeeze",
2887
+ viewportWidth: "full",
2888
+ scale: 1
2889
+ };
2890
+ const scale = input.viewportMode === "squeeze" ? 1 : previewEditorScale(input);
2891
+ return {
2892
+ viewportMode: input.viewportMode,
2893
+ viewportWidth: input.viewportWidth,
2894
+ scale
2895
+ };
2896
+ }
2897
+ function previewEditorScale(input) {
2898
+ if (input.zoom !== "fit") return input.zoom / 100;
2899
+ if (input.containerWidth <= 0) return 1;
2900
+ const targetWidth = input.viewportWidth === "full" ? 1440 : input.viewportWidth;
2901
+ return Math.min(1, input.containerWidth / targetWidth);
2902
+ }
2903
+ function planPreviewDocumentFrame(input) {
2904
+ switch (input.viewportMode) {
2905
+ case "squeeze": return {
2906
+ kind: "squeeze",
2907
+ frameClassName: PREVIEW_DOCUMENT_FRAME_CLASS_NAME,
2908
+ frameDataProps: {
2909
+ "data-builder-preview-document-frame": "squeeze",
2910
+ "data-builder-preview-document-scale": "none"
2911
+ }
2912
+ };
2913
+ case "fixed": return planFixedPreviewDocumentFrame(input);
2914
+ default: return assertNever(input.viewportMode);
2915
+ }
2916
+ }
2917
+ function planFixedPreviewDocumentFrame(input) {
2918
+ const scale = normalizePreviewScale(input.scale);
2919
+ const targetWidthPx = input.viewportWidth === "full" ? 1440 : input.viewportWidth;
2920
+ const scaledWidth = targetWidthPx * scale;
2921
+ const scaledHeight = input.contentHeight > 0 ? input.contentHeight * scale : null;
2922
+ const wrapperStyle = {
2923
+ width: `${scaledWidth}px`,
2924
+ margin: "0 auto"
2925
+ };
2926
+ if (scaledHeight !== null) wrapperStyle.height = `${scaledHeight}px`;
2927
+ else wrapperStyle.minHeight = "100%";
2928
+ return {
2929
+ kind: "fixed",
2930
+ targetWidthPx,
2931
+ wrapperStyle,
2932
+ contentStyle: {
2933
+ minHeight: "100%",
2934
+ boxSizing: "content-box",
2935
+ width: `${targetWidthPx}px`,
2936
+ ...scale === 1 ? {} : { zoom: scale }
2937
+ },
2938
+ siteDocumentStyle: { width: `${targetWidthPx}px` },
2939
+ frameClassName: PREVIEW_DOCUMENT_FRAME_CLASS_NAME,
2940
+ frameDataProps: {
2941
+ "data-builder-preview-document-frame": "fixed",
2942
+ "data-builder-preview-document-scale": scale === 1 ? "none" : "scaled",
2943
+ "data-builder-preview-fixed-header-behavior": "fixed-as-sticky"
2944
+ }
2945
+ };
2946
+ }
2947
+ function normalizePreviewScale(scale) {
2948
+ if (!Number.isFinite(scale) || scale <= 0) return 1;
2949
+ return scale;
2950
+ }
2951
+ function assertNever(value) {
2952
+ throw new Error(`Unhandled preview viewport mode: ${String(value)}`);
2953
+ }
2954
+ //#endregion
2955
+ //#region ../preview-next/src/client/preview/PreviewScrollViewport.tsx
2956
+ const frameStore = {
2957
+ frames: [],
2958
+ frame: null,
2959
+ listeners: /* @__PURE__ */ new Set(),
2960
+ publish() {
2961
+ const next = frameStore.frames.at(-1) ?? null;
2962
+ if (frameStore.frame === next) return;
2963
+ frameStore.frame = next;
2964
+ frameStore.listeners.forEach((listener) => listener());
2965
+ },
2966
+ register(frame) {
2967
+ if (!frame) return;
2968
+ frameStore.frames = [...frameStore.frames, frame];
2969
+ frameStore.publish();
2970
+ return () => {
2971
+ frameStore.frames = frameStore.frames.filter((mounted) => mounted !== frame);
2972
+ frameStore.publish();
2973
+ };
2974
+ },
2975
+ subscribe(listener) {
2976
+ frameStore.listeners.add(listener);
2977
+ return () => {
2978
+ frameStore.listeners.delete(listener);
2979
+ };
2980
+ }
2981
+ };
2982
+ /** The canvas can remount when the split pane opens or a phone tab changes. */
2983
+ function PreviewScrollViewport({ children }) {
2984
+ const viewportRef = useRef(null);
2985
+ const selection = usePreviewSidebarNavigation();
2986
+ const blockId = selection.navigation.selectedBlock?.blockId;
2987
+ const requestId = selection.requestId;
2988
+ useEffect(() => {
2989
+ const viewport = viewportRef.current;
2990
+ if (!blockId || !viewport) return;
2991
+ const frames = { pending: 0 };
2992
+ const reveal = () => {
2993
+ if (document.documentElement.getAttribute("data-rb-preview-mode") !== "edit") return;
2994
+ const block = viewport.querySelector(`[data-block-id="${CSS.escape(blockId)}"]`);
2995
+ if (!block) return;
2996
+ observer.disconnect();
2997
+ revealEditorElement(block);
2998
+ };
2999
+ const observer = new MutationObserver(() => {
3000
+ cancelAnimationFrame(frames.pending);
3001
+ frames.pending = requestAnimationFrame(reveal);
3002
+ });
3003
+ observer.observe(document.documentElement, {
3004
+ attributes: true,
3005
+ attributeFilter: ["data-rb-preview-mode"]
3006
+ });
3007
+ observer.observe(viewport, {
3008
+ childList: true,
3009
+ subtree: true
3010
+ });
3011
+ frames.pending = requestAnimationFrame(reveal);
3012
+ return () => {
3013
+ cancelAnimationFrame(frames.pending);
3014
+ observer.disconnect();
3015
+ };
3016
+ }, [blockId, requestId]);
3017
+ return /* @__PURE__ */ jsx("div", {
3018
+ ref: frameStore.register,
3019
+ className: "relative h-full min-h-0 overflow-hidden bg-muted/30",
3020
+ style: {
3021
+ contain: "layout paint",
3022
+ isolation: "isolate",
3023
+ transform: "translateZ(0)"
3024
+ },
3025
+ children: /* @__PURE__ */ jsx("div", {
3026
+ ref: viewportRef,
3027
+ "data-preview-scroll-viewport": "",
3028
+ className: "relative flex h-full min-h-0 flex-col overflow-auto",
3029
+ children
3030
+ })
3031
+ });
3032
+ }
3033
+ //#endregion
3034
+ //#region ../preview-next/src/client/preview/previewSetupGuidance.ts
3035
+ function resolvePreviewSetupBannerState(input) {
3036
+ if (input.authMode === "onboardingGrant") return input.dashboardUnlocked ? "dashboard_ready" : "awaiting_confirmation";
3037
+ if (input.hasDashboardSetupHandoff) return "dashboard_resume";
3038
+ return null;
3039
+ }
3040
+ //#endregion
3041
+ //#region ../preview-next/src/client/preview/PreviewConfirmationDialog.tsx
3042
+ function PreviewConfirmationDialog({ dashboardContinueUrl, dialogState, isCheckingConfirmation, onCheckConfirmation, onClose, onCompleteSetup }) {
3043
+ return /* @__PURE__ */ jsx(Dialog, {
3044
+ open: dialogState !== null,
3045
+ onOpenChange: (open) => !open && onClose(),
3046
+ children: /* @__PURE__ */ jsx(DialogContent, { children: dialogState?.kind === "ready" ? /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs(DialogHeader, { children: [/* @__PURE__ */ jsx(DialogTitle, { children: "Your dashboard is ready" }), /* @__PURE__ */ jsx(DialogDescription, { children: "Keep exploring here, or use Complete setup in dashboard to review your pages, add offerings, connect payments, and finish launch setup." })] }), /* @__PURE__ */ jsxs(DialogFooter, { children: [/* @__PURE__ */ jsx(Button, {
3047
+ type: "button",
3048
+ variant: "outline",
3049
+ onClick: onClose,
3050
+ children: "Continue previewing"
3051
+ }), /* @__PURE__ */ jsx(Button, {
3052
+ type: "button",
3053
+ onClick: onCompleteSetup,
3054
+ disabled: !dashboardContinueUrl,
3055
+ children: "Complete setup in dashboard"
3056
+ })] })] }) : dialogState?.kind === "pending" ? /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs(DialogHeader, { children: [/* @__PURE__ */ jsx(DialogTitle, { children: "Still waiting on email confirmation" }), /* @__PURE__ */ jsx(DialogDescription, { children: "We haven't seen the confirmation come through yet. Keep exploring your preview, then try again after you've clicked the email link." })] }), /* @__PURE__ */ jsxs(DialogFooter, { children: [/* @__PURE__ */ jsx(Button, {
3057
+ type: "button",
3058
+ variant: "outline",
3059
+ onClick: onClose,
3060
+ children: "Keep previewing"
3061
+ }), /* @__PURE__ */ jsx(Button, {
3062
+ type: "button",
3063
+ onClick: () => void onCheckConfirmation(),
3064
+ disabled: isCheckingConfirmation,
3065
+ children: isCheckingConfirmation ? "Checking..." : "Check again"
3066
+ })] })] }) : dialogState?.kind === "error" ? /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs(DialogHeader, { children: [/* @__PURE__ */ jsx(DialogTitle, { children: "We couldn't check your confirmation yet" }), /* @__PURE__ */ jsx(DialogDescription, { children: dialogState.message })] }), /* @__PURE__ */ jsxs(DialogFooter, { children: [/* @__PURE__ */ jsx(Button, {
3067
+ type: "button",
3068
+ variant: "outline",
3069
+ onClick: onClose,
3070
+ children: "Keep previewing"
3071
+ }), /* @__PURE__ */ jsx(Button, {
3072
+ type: "button",
3073
+ onClick: () => void onCheckConfirmation(),
3074
+ disabled: isCheckingConfirmation,
3075
+ children: isCheckingConfirmation ? "Checking..." : "Try again"
3076
+ })] })] }) : null })
3077
+ });
3078
+ }
3079
+ //#endregion
3080
+ //#region ../preview-next/src/onboarding-preview-planner.ts
3081
+ const DEFAULT_CHECK_ERROR_MESSAGE = "Unable to check your confirmation status right now.";
3082
+ const DEFAULT_RESEND_ERROR_MESSAGE = "Unable to resend your confirmation email right now.";
3083
+ const RESEND_LIMIT_MESSAGE = "You’ve requested all the emails we can send for this sign-up. Check your inbox and spam folder for the latest link.";
3084
+ const RESEND_SUCCESS_MESSAGE = "We sent a fresh confirmation email. Check your inbox and spam folder.";
3085
+ const ALREADY_CONFIRMED_MESSAGE = "Your email is already confirmed. You can complete setup in the dashboard.";
3086
+ function applyOnboardingConfirmationUpdate(state, update) {
3087
+ switch (update.kind) {
3088
+ case "setDashboardUnlocked": return {
3089
+ ...state,
3090
+ dashboardUnlocked: update.dashboardUnlocked
3091
+ };
3092
+ case "setDialogState": return {
3093
+ ...state,
3094
+ dialogState: update.dialogState
3095
+ };
3096
+ case "setHasLoadedStatus": return {
3097
+ ...state,
3098
+ hasLoadedStatus: update.hasLoadedStatus
3099
+ };
3100
+ case "setLaunchReadiness": return {
3101
+ ...state,
3102
+ launchReadiness: update.launchReadiness
3103
+ };
3104
+ case "setResendFeedback": return {
3105
+ ...state,
3106
+ resendFeedback: update.resendFeedback
3107
+ };
3108
+ case "setStatusLoadFailed": return {
3109
+ ...state,
3110
+ statusLoadFailed: update.statusLoadFailed
3111
+ };
3112
+ default: return assertNever$2(update);
3113
+ }
3114
+ }
3115
+ function applyOnboardingConfirmationUpdates(state, updates) {
3116
+ return updates.reduce(applyOnboardingConfirmationUpdate, state);
3117
+ }
3118
+ function planNoEffect(updates) {
3119
+ return {
3120
+ updates,
3121
+ effect: { kind: "none" }
3122
+ };
3123
+ }
3124
+ function planPreviewUpgrade(facts) {
3125
+ if (facts.authMode !== "onboardingGrant" || facts.upgradeAlreadyStarted || !facts.dashboardBaseUrl || !facts.siteSlug || !facts.currentUrl) return { kind: "none" };
3126
+ return {
3127
+ kind: "startPreviewUpgrade",
3128
+ input: {
3129
+ dashboardBaseUrl: facts.dashboardBaseUrl,
3130
+ returnUrl: facts.currentUrl,
3131
+ fallbackUrl: facts.currentUrl,
3132
+ siteSlug: facts.siteSlug
3133
+ }
3134
+ };
3135
+ }
3136
+ function planStatusApplied(input) {
3137
+ return {
3138
+ updates: [
3139
+ ...input.status.dashboardUnlocked && (input.authMode === "onboardingGrant" || input.allowUserSessionUnlock) ? [{
3140
+ kind: "setDashboardUnlocked",
3141
+ dashboardUnlocked: true
3142
+ }] : [],
3143
+ {
3144
+ kind: "setLaunchReadiness",
3145
+ launchReadiness: input.status.launchReadiness
3146
+ },
3147
+ {
3148
+ kind: "setHasLoadedStatus",
3149
+ hasLoadedStatus: true
3150
+ },
3151
+ {
3152
+ kind: "setStatusLoadFailed",
3153
+ statusLoadFailed: false
3154
+ }
3155
+ ],
3156
+ effect: input.status.dashboardUnlocked ? planPreviewUpgrade(input) : { kind: "none" }
3157
+ };
3158
+ }
3159
+ function planAlreadyUnlockedManualCheck() {
3160
+ return planNoEffect([{
3161
+ kind: "setDialogState",
3162
+ dialogState: { kind: "ready" }
3163
+ }]);
3164
+ }
3165
+ function planMissingConfirmationStatusConfig(message = DEFAULT_CHECK_ERROR_MESSAGE) {
3166
+ return planNoEffect([{
3167
+ kind: "setDialogState",
3168
+ dialogState: {
3169
+ kind: "error",
3170
+ message
3171
+ }
3172
+ }]);
3173
+ }
3174
+ function planConfirmationStatusFailure(message = DEFAULT_CHECK_ERROR_MESSAGE) {
3175
+ return planNoEffect([{
3176
+ kind: "setDialogState",
3177
+ dialogState: {
3178
+ kind: "error",
3179
+ message
3180
+ }
3181
+ }]);
3182
+ }
3183
+ function planManualConfirmationStatusSuccess(input) {
3184
+ const applied = planStatusApplied({
3185
+ allowUserSessionUnlock: true,
3186
+ authMode: input.authMode,
3187
+ currentUrl: input.currentUrl,
3188
+ dashboardBaseUrl: input.dashboardBaseUrl,
3189
+ siteSlug: input.siteSlug,
3190
+ status: input.status,
3191
+ upgradeAlreadyStarted: input.upgradeAlreadyStarted
3192
+ });
3193
+ if (applied.effect.kind === "startPreviewUpgrade") return applied;
3194
+ return {
3195
+ updates: [...applied.updates, {
3196
+ kind: "setDialogState",
3197
+ dialogState: input.status.dashboardUnlocked ? { kind: "ready" } : { kind: "pending" }
3198
+ }],
3199
+ effect: applied.effect
3200
+ };
3201
+ }
3202
+ function planInitialStatusLoadFailure() {
3203
+ return planNoEffect([{
3204
+ kind: "setStatusLoadFailed",
3205
+ statusLoadFailed: true
3206
+ }]);
3207
+ }
3208
+ function planResendConfirmationFailure(message = DEFAULT_RESEND_ERROR_MESSAGE) {
3209
+ return planNoEffect([{
3210
+ kind: "setResendFeedback",
3211
+ resendFeedback: {
3212
+ kind: "error",
3213
+ message
3214
+ }
3215
+ }]);
3216
+ }
3217
+ function planResendConfirmationSuccess(input) {
3218
+ return {
3219
+ updates: [
3220
+ {
3221
+ kind: "setLaunchReadiness",
3222
+ launchReadiness: input.response.launchReadiness
3223
+ },
3224
+ ...input.response.dashboardUnlocked ? [{
3225
+ kind: "setDashboardUnlocked",
3226
+ dashboardUnlocked: true
3227
+ }] : [],
3228
+ {
3229
+ kind: "setResendFeedback",
3230
+ resendFeedback: {
3231
+ kind: "success",
3232
+ message: input.response.result === "already_confirmed" ? ALREADY_CONFIRMED_MESSAGE : input.response.result === "limit_reached" ? RESEND_LIMIT_MESSAGE : input.response.limitReached ? `We’ve sent another email. ${RESEND_LIMIT_MESSAGE}` : RESEND_SUCCESS_MESSAGE
3233
+ }
3234
+ }
3235
+ ],
3236
+ effect: input.response.dashboardUnlocked ? planPreviewUpgrade({
3237
+ authMode: input.authMode,
3238
+ currentUrl: input.currentUrl,
3239
+ dashboardBaseUrl: input.dashboardBaseUrl,
3240
+ siteSlug: input.siteSlug,
3241
+ upgradeAlreadyStarted: input.upgradeAlreadyStarted
3242
+ }) : { kind: "none" }
3243
+ };
3244
+ }
3245
+ //#endregion
3246
+ //#region ../preview-next/src/route-contract.ts
3247
+ const previewBrowserEntries = { previewAuthEntry: { pathname: "/preview/auth" } };
3248
+ const previewDashboardApiEndpoints = {
3249
+ previewAuthExchange: { path: `/api${API_ENDPOINTS.previewExchangeCode.path}` },
3250
+ previewAuthRefresh: { path: `/api${API_ENDPOINTS.previewRefreshSession.path}` },
3251
+ onboardingPreviewStatus: { path: `/api${API_ENDPOINTS.getOnboardingPreviewStatus.path}` },
3252
+ onboardingResendConfirmation: { path: `/api${API_ENDPOINTS.resendOnboardingPreviewConfirmation.path}` }
3253
+ };
3254
+ previewBrowserEntries.previewAuthEntry.pathname;
3255
+ function buildDashboardUrl(dashboardBaseUrl, pathname) {
3256
+ return new URL(pathname, dashboardBaseUrl);
3257
+ }
3258
+ function replaceSiteId(path, siteId) {
3259
+ return path.replace("{siteId}", encodeURIComponent(siteId));
3260
+ }
3261
+ /** The configured dashboard surface and site are required; there is no fallback surface. */
3262
+ function planPreviewRestart(input) {
3263
+ if (!input.dashboardBaseUrl) return {
3264
+ kind: "unavailable",
3265
+ reason: "missing_dashboard"
3266
+ };
3267
+ if (!input.siteSlug) return {
3268
+ kind: "unavailable",
3269
+ reason: "missing_site"
3270
+ };
3271
+ try {
3272
+ const url = new URL(input.dashboardBaseUrl);
3273
+ if (!["https:", "http:"].includes(url.protocol)) return {
3274
+ kind: "unavailable",
3275
+ reason: "invalid_dashboard"
3276
+ };
3277
+ return {
3278
+ kind: "ready",
3279
+ entry: {
3280
+ dashboardBaseUrl: url.origin,
3281
+ siteSlug: input.siteSlug,
3282
+ returnUrl: input.returnUrl,
3283
+ fallbackUrl: input.returnUrl
3284
+ }
3285
+ };
3286
+ } catch {
3287
+ return {
3288
+ kind: "unavailable",
3289
+ reason: "invalid_dashboard"
3290
+ };
3291
+ }
3292
+ }
3293
+ function buildPreviewAuthEntryUrl(input) {
3294
+ const url = buildDashboardUrl(input.dashboardBaseUrl, previewBrowserEntries.previewAuthEntry.pathname);
3295
+ url.searchParams.set("return", input.returnUrl);
3296
+ url.searchParams.set("fallback", input.fallbackUrl);
3297
+ if (input.siteSlug) url.searchParams.set("siteSlug", input.siteSlug);
3298
+ return url.toString();
3299
+ }
3300
+ function buildOnboardingPreviewStatusUrl(input) {
3301
+ const url = buildDashboardUrl(input.dashboardBaseUrl, replaceSiteId(previewDashboardApiEndpoints.onboardingPreviewStatus.path, input.siteId));
3302
+ url.searchParams.set("stage", "preview");
3303
+ return url.toString();
3304
+ }
3305
+ function buildOnboardingResendConfirmationUrl(input) {
3306
+ const url = buildDashboardUrl(input.dashboardBaseUrl, replaceSiteId(previewDashboardApiEndpoints.onboardingResendConfirmation.path, input.siteId));
3307
+ url.searchParams.set("stage", "preview");
3308
+ return url.toString();
3309
+ }
3310
+ //#endregion
3311
+ //#region ../preview-next/src/client/preview/usePreviewConfirmationResend.ts
3312
+ function stateAfterReply(reply) {
3313
+ if (reply.kind === "failed") return reply.retryAfterSeconds > 0 ? {
3314
+ kind: "cooling",
3315
+ seconds: reply.retryAfterSeconds
3316
+ } : { kind: "idle" };
3317
+ const data = reply.data;
3318
+ if (data.result === "limit_reached" || data.result === "resent" && data.limitReached) return { kind: "exhausted" };
3319
+ return data.result === "resent" ? {
3320
+ kind: "cooling",
3321
+ seconds: Math.ceil(data.retryAfterSeconds)
3322
+ } : { kind: "idle" };
3323
+ }
3324
+ function decideResendButton(state) {
3325
+ switch (state.kind) {
3326
+ case "idle": return {
3327
+ disabled: false,
3328
+ label: "Resend confirmation email"
3329
+ };
3330
+ case "sending": return {
3331
+ disabled: true,
3332
+ label: "Sending..."
3333
+ };
3334
+ case "exhausted": return {
3335
+ disabled: true,
3336
+ label: "No more emails available"
3337
+ };
3338
+ case "cooling": return {
3339
+ disabled: true,
3340
+ label: `Send again in ${state.seconds} seconds`
3341
+ };
3342
+ }
3343
+ }
3344
+ /** Owns duplicate submission, cooldown and exhaustion for preview's resend action. */
3345
+ function usePreviewConfirmationResend(input) {
3346
+ const [state, setState] = useState({ kind: "idle" });
3347
+ const inFlight = useRef(false);
3348
+ const resendButton = decideResendButton(state);
3349
+ useEffect(() => {
3350
+ if (state.kind !== "cooling") return;
3351
+ const timer = setTimeout(() => setState((current) => current.kind !== "cooling" ? current : current.seconds <= 1 ? { kind: "idle" } : {
3352
+ kind: "cooling",
3353
+ seconds: current.seconds - 1
3354
+ }), 1e3);
3355
+ return () => clearTimeout(timer);
3356
+ }, [state]);
3357
+ return {
3358
+ resendConfirmation: useCallback(async () => {
3359
+ if (inFlight.current || resendButton.disabled) return;
3360
+ inFlight.current = true;
3361
+ setState({ kind: "sending" });
3362
+ try {
3363
+ const reply = await input.request();
3364
+ setState(stateAfterReply(reply));
3365
+ if (reply.kind === "failed") input.failed(reply.message);
3366
+ else input.succeeded(reply.data);
3367
+ } catch (error) {
3368
+ setState({ kind: "idle" });
3369
+ input.failed(error instanceof Error ? error.message : "Unable to resend your confirmation email right now.");
3370
+ } finally {
3371
+ inFlight.current = false;
3372
+ }
3373
+ }, [input, resendButton.disabled]),
3374
+ resendButton,
3375
+ resendNeedsSupport: state.kind === "exhausted"
3376
+ };
3377
+ }
3378
+ //#endregion
3379
+ //#region ../preview-next/src/client/preview/useOnboardingConfirmationCheck.ts
3380
+ const INITIAL_ONBOARDING_CONFIRMATION_STATE = {
3381
+ dashboardUnlocked: false,
3382
+ dialogState: null,
3383
+ hasLoadedStatus: false,
3384
+ launchReadiness: deriveLaunchReadiness(DEFAULT_LAUNCH_READINESS_INPUT),
3385
+ resendFeedback: null,
3386
+ statusLoadFailed: false
3387
+ };
3388
+ function isRecord(value) {
3389
+ return value !== null && typeof value === "object";
3390
+ }
3391
+ function getErrorMessageFromEnvelope(payload, fallback) {
3392
+ const error = isRecord(payload) ? payload.error : null;
3393
+ const message = isRecord(error) ? error.message : null;
3394
+ return typeof message === "string" && message.trim().length > 0 ? message : fallback;
3395
+ }
3396
+ function isLaunchReadiness(value) {
3397
+ return isRecord(value) && Array.isArray(value.requirements) && typeof value.pendingRequiredCount === "number" && typeof value.pendingRecommendedCount === "number" && typeof value.pendingOptionalCount === "number" && isRecord(value.goLiveDecision) && (value.goLiveDecision.kind === "allowed" || value.goLiveDecision.kind === "blocked");
3398
+ }
3399
+ function isOnboardingPreviewStatusResponse(value) {
3400
+ return isRecord(value) && typeof value.dashboardUnlocked === "boolean" && typeof value.requiresEmailConfirmation === "boolean" && isLaunchReadiness(value.launchReadiness);
3401
+ }
3402
+ function isResendResult(value) {
3403
+ if (value.result === "already_confirmed" || value.result === "limit_reached") return true;
3404
+ return value.result === "resent" && typeof value.retryAfterSeconds === "number" && Number.isFinite(value.retryAfterSeconds) && value.retryAfterSeconds >= 0 && typeof value.limitReached === "boolean";
3405
+ }
3406
+ function isResendOnboardingPreviewConfirmationResponse(value) {
3407
+ return isRecord(value) && isResendResult(value) && typeof value.dashboardUnlocked === "boolean" && typeof value.requiresEmailConfirmation === "boolean" && isLaunchReadiness(value.launchReadiness);
3408
+ }
3409
+ function getSuccessData(payload, isData) {
3410
+ if (!isRecord(payload) || payload.success !== true || !isData(payload.data)) return null;
3411
+ return payload.data;
3412
+ }
3413
+ function useOnboardingConfirmationCheck(input) {
3414
+ const [isCheckingConfirmation, setIsCheckingConfirmation] = useState(false);
3415
+ const [confirmationState, dispatchConfirmationUpdates] = useReducer(applyOnboardingConfirmationUpdates, INITIAL_ONBOARDING_CONFIRMATION_STATE);
3416
+ const previewUpgradeStartedRef = useRef(false);
3417
+ const { dashboardUnlocked, dialogState, hasLoadedStatus, launchReadiness, resendFeedback, statusLoadFailed } = confirmationState;
3418
+ const confirmationStatusUrl = useMemo(() => {
3419
+ if (!input.dashboardBaseUrl || !input.siteId) return null;
3420
+ return buildOnboardingPreviewStatusUrl({
3421
+ dashboardBaseUrl: input.dashboardBaseUrl,
3422
+ siteId: input.siteId
3423
+ });
3424
+ }, [input.dashboardBaseUrl, input.siteId]);
3425
+ const resendConfirmationUrl = useMemo(() => {
3426
+ if (!input.dashboardBaseUrl || !input.siteId) return null;
3427
+ return buildOnboardingResendConfirmationUrl({
3428
+ dashboardBaseUrl: input.dashboardBaseUrl,
3429
+ siteId: input.siteId
3430
+ });
3431
+ }, [input.dashboardBaseUrl, input.siteId]);
3432
+ const dashboardContinueUrl = useMemo(() => {
3433
+ if (!input.dashboardBaseUrl || !input.siteId) return null;
3434
+ const dashboardPath = sanitizeDashboardPath(`/dashboard/sites/${input.siteId}/launch`);
3435
+ if (!dashboardPath) return null;
3436
+ return new URL(dashboardPath, input.dashboardBaseUrl).toString();
3437
+ }, [input.dashboardBaseUrl, input.siteId]);
3438
+ const currentPreviewUrl = useCallback(() => typeof window === "undefined" ? null : window.location.href, []);
3439
+ const applyPlan = useCallback((plan) => {
3440
+ dispatchConfirmationUpdates(plan.updates);
3441
+ switch (plan.effect.kind) {
3442
+ case "none": return false;
3443
+ case "startPreviewUpgrade":
3444
+ if (previewUpgradeStartedRef.current || typeof window === "undefined") return previewUpgradeStartedRef.current;
3445
+ previewUpgradeStartedRef.current = true;
3446
+ window.location.assign(buildPreviewAuthEntryUrl(plan.effect.input));
3447
+ return true;
3448
+ default: return plan.effect;
3449
+ }
3450
+ }, []);
3451
+ const readConfirmationStatus = useCallback(async () => {
3452
+ if (!confirmationStatusUrl || !input.previewToken) throw new Error(DEFAULT_CHECK_ERROR_MESSAGE);
3453
+ const response = await fetch(confirmationStatusUrl, {
3454
+ method: "GET",
3455
+ headers: { Authorization: `Bearer ${input.previewToken}` }
3456
+ });
3457
+ const payload = await response.json().catch(() => null);
3458
+ if (!response.ok) throw new Error(getErrorMessageFromEnvelope(payload, DEFAULT_CHECK_ERROR_MESSAGE));
3459
+ const status = getSuccessData(payload, isOnboardingPreviewStatusResponse);
3460
+ if (!status) throw new Error(DEFAULT_CHECK_ERROR_MESSAGE);
3461
+ return status;
3462
+ }, [confirmationStatusUrl, input.previewToken]);
3463
+ const checkConfirmation = useCallback(async () => {
3464
+ if (dashboardUnlocked) {
3465
+ applyPlan(planAlreadyUnlockedManualCheck());
3466
+ return;
3467
+ }
3468
+ if (!confirmationStatusUrl || !input.previewToken) {
3469
+ applyPlan(planMissingConfirmationStatusConfig());
3470
+ return;
3471
+ }
3472
+ setIsCheckingConfirmation(true);
3473
+ try {
3474
+ const status = await readConfirmationStatus();
3475
+ if (applyPlan(planManualConfirmationStatusSuccess({
3476
+ authMode: input.authMode,
3477
+ currentUrl: currentPreviewUrl(),
3478
+ dashboardBaseUrl: input.dashboardBaseUrl,
3479
+ siteSlug: input.siteSlug,
3480
+ status,
3481
+ upgradeAlreadyStarted: previewUpgradeStartedRef.current
3482
+ }))) return;
3483
+ } catch (error) {
3484
+ applyPlan(planConfirmationStatusFailure(error instanceof Error ? error.message : DEFAULT_CHECK_ERROR_MESSAGE));
3485
+ } finally {
3486
+ setIsCheckingConfirmation(false);
3487
+ }
3488
+ }, [
3489
+ applyPlan,
3490
+ confirmationStatusUrl,
3491
+ currentPreviewUrl,
3492
+ dashboardUnlocked,
3493
+ input.authMode,
3494
+ input.dashboardBaseUrl,
3495
+ input.previewToken,
3496
+ input.siteSlug,
3497
+ readConfirmationStatus
3498
+ ]);
3499
+ const resend = usePreviewConfirmationResend({
3500
+ request: useCallback(async () => {
3501
+ if (!resendConfirmationUrl || !input.previewToken) throw new Error(DEFAULT_RESEND_ERROR_MESSAGE);
3502
+ const response = await fetch(resendConfirmationUrl, {
3503
+ method: "POST",
3504
+ headers: { Authorization: `Bearer ${input.previewToken}` }
3505
+ });
3506
+ const payload = await response.json().catch(() => null);
3507
+ if (!response.ok) {
3508
+ const delay = Number(response.headers.get("Retry-After"));
3509
+ return {
3510
+ kind: "failed",
3511
+ message: getErrorMessageFromEnvelope(payload, DEFAULT_RESEND_ERROR_MESSAGE),
3512
+ retryAfterSeconds: response.status === 429 ? Number.isFinite(delay) && delay > 0 ? Math.ceil(delay) : 60 : 0
3513
+ };
3514
+ }
3515
+ const data = getSuccessData(payload, isResendOnboardingPreviewConfirmationResponse);
3516
+ if (!data) throw new Error(DEFAULT_RESEND_ERROR_MESSAGE);
3517
+ return {
3518
+ kind: "success",
3519
+ data
3520
+ };
3521
+ }, [resendConfirmationUrl, input.previewToken]),
3522
+ failed: (message) => applyPlan(planResendConfirmationFailure(message)),
3523
+ succeeded: (response) => applyPlan(planResendConfirmationSuccess({
3524
+ authMode: input.authMode,
3525
+ currentUrl: currentPreviewUrl(),
3526
+ dashboardBaseUrl: input.dashboardBaseUrl,
3527
+ response,
3528
+ siteSlug: input.siteSlug,
3529
+ upgradeAlreadyStarted: previewUpgradeStartedRef.current
3530
+ }))
3531
+ });
3532
+ useEffect(() => {
3533
+ if (!input.shouldLoadStatus || !confirmationStatusUrl || !input.previewToken) return;
3534
+ let cancelled = false;
3535
+ (async () => {
3536
+ try {
3537
+ const status = await readConfirmationStatus();
3538
+ if (cancelled) return;
3539
+ applyPlan(planStatusApplied({
3540
+ allowUserSessionUnlock: true,
3541
+ authMode: input.authMode,
3542
+ currentUrl: currentPreviewUrl(),
3543
+ dashboardBaseUrl: input.dashboardBaseUrl,
3544
+ siteSlug: input.siteSlug,
3545
+ status,
3546
+ upgradeAlreadyStarted: previewUpgradeStartedRef.current
3547
+ }));
3548
+ } catch {
3549
+ if (cancelled) return;
3550
+ applyPlan(planInitialStatusLoadFailure());
3551
+ }
3552
+ })();
3553
+ return () => {
3554
+ cancelled = true;
3555
+ };
3556
+ }, [
3557
+ applyPlan,
3558
+ confirmationStatusUrl,
3559
+ currentPreviewUrl,
3560
+ input.authMode,
3561
+ input.dashboardBaseUrl,
3562
+ input.previewToken,
3563
+ input.siteSlug,
3564
+ input.shouldLoadStatus,
3565
+ readConfirmationStatus
3566
+ ]);
3567
+ return {
3568
+ checkConfirmation,
3569
+ closeDialog: () => dispatchConfirmationUpdates([{
3570
+ kind: "setDialogState",
3571
+ dialogState: null
3572
+ }]),
3573
+ dashboardContinueUrl,
3574
+ dashboardUnlocked,
3575
+ dialogState,
3576
+ hasLoadedStatus,
3577
+ isCheckingConfirmation,
3578
+ ...resend,
3579
+ launchReadiness,
3580
+ resendFeedback,
3581
+ statusLoadFailed
3582
+ };
3583
+ }
3584
+ //#endregion
3585
+ //#region ../preview-next/src/client/preview/PreviewAuthBanner.tsx
3586
+ function usePreviewRestart(dashboardBaseUrl, siteSlug) {
3587
+ return {
3588
+ restartAvailable: planPreviewRestart({
3589
+ dashboardBaseUrl,
3590
+ siteSlug,
3591
+ returnUrl: ""
3592
+ }).kind === "ready",
3593
+ reauthenticate: useCallback(() => {
3594
+ if (typeof window === "undefined") return;
3595
+ const plan = planPreviewRestart({
3596
+ dashboardBaseUrl,
3597
+ siteSlug,
3598
+ returnUrl: window.location.href
3599
+ });
3600
+ if (plan.kind === "ready") window.location.assign(buildPreviewAuthEntryUrl(plan.entry));
3601
+ }, [dashboardBaseUrl, siteSlug])
3602
+ };
3603
+ }
3604
+ function ConfirmationResendSupport({ visible, dashboardBaseUrl }) {
3605
+ if (!visible || !dashboardBaseUrl) return null;
3606
+ return /* @__PURE__ */ jsx("a", {
3607
+ className: "text-xs underline underline-offset-2",
3608
+ href: new URL("/contact", dashboardBaseUrl).toString(),
3609
+ target: "_blank",
3610
+ rel: "noopener noreferrer",
3611
+ children: "Contact us for help"
3612
+ });
3613
+ }
3614
+ function PreviewRecoveryBanner({ state, renewalPending, restartAvailable, reauthenticate }) {
3615
+ const unavailable = state === "unavailable";
3616
+ return /* @__PURE__ */ jsx(FixedBottomSurface, {
3617
+ variant: "dark",
3618
+ width: "centered",
3619
+ offsetCssVar: "--builder-editor-chrome-offset",
3620
+ reserveOffsetCssVar: "--builder-preview-banner-offset",
3621
+ className: "backdrop-blur supports-[backdrop-filter]:bg-slate-950/60",
3622
+ children: /* @__PURE__ */ jsxs("div", {
3623
+ className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",
3624
+ children: [/* @__PURE__ */ jsxs("div", {
3625
+ className: "space-y-1",
3626
+ children: [/* @__PURE__ */ jsx("p", {
3627
+ className: "text-sm font-medium tracking-tight",
3628
+ children: unavailable ? "We couldn't reconnect to your editing session." : "Sign in to continue editing"
3629
+ }), unavailable ? /* @__PURE__ */ jsx("p", {
3630
+ className: "text-xs text-slate-300",
3631
+ children: "Keep this tab open and try again."
3632
+ }) : null]
3633
+ }), /* @__PURE__ */ jsx("div", {
3634
+ className: "flex items-center gap-2",
3635
+ children: /* @__PURE__ */ jsx(Button, {
3636
+ type: "button",
3637
+ size: "sm",
3638
+ variant: "onDark",
3639
+ disabled: unavailable ? renewalPending : !restartAvailable,
3640
+ onClick: unavailable ? () => void renewPreviewSession() : reauthenticate,
3641
+ children: unavailable ? "Try again" : "Sign in"
3642
+ })
3643
+ })]
3644
+ })
3645
+ });
3646
+ }
3647
+ function PreviewAuthBanner({ dashboardBaseUrl = null, surfaceId }) {
3648
+ const { authMode, state, renewalPending, siteId, siteSlug } = usePreviewAuth();
3649
+ const previewToken = usePreviewToken();
3650
+ const dashboardSetupHandoff = useMemo(() => resolvePreviewDashboardSetupHandoff(), []);
3651
+ const onboardingConfirmationCheck = useOnboardingConfirmationCheck({
3652
+ authMode,
3653
+ dashboardBaseUrl,
3654
+ previewToken,
3655
+ siteId,
3656
+ siteSlug,
3657
+ shouldLoadStatus: authMode === "onboardingGrant" || dashboardSetupHandoff?.kind === "dashboard_setup"
3658
+ });
3659
+ const launchReadiness = onboardingConfirmationCheck.launchReadiness;
3660
+ const setupSummary = useMemo(() => {
3661
+ const parts = [];
3662
+ if (launchReadiness.pendingRequiredCount > 0) parts.push(`${launchReadiness.pendingRequiredCount} required ${launchReadiness.pendingRequiredCount === 1 ? "step" : "steps"}`);
3663
+ if (launchReadiness.pendingRecommendedCount > 0) parts.push(`${launchReadiness.pendingRecommendedCount} recommended ${launchReadiness.pendingRecommendedCount === 1 ? "step" : "steps"}`);
3664
+ if (launchReadiness.pendingOptionalCount > 0) parts.push(`${launchReadiness.pendingOptionalCount} optional ${launchReadiness.pendingOptionalCount === 1 ? "step" : "steps"}`);
3665
+ return parts.length > 0 ? parts.join(" left, ") : "Checklist complete";
3666
+ }, [
3667
+ launchReadiness.pendingOptionalCount,
3668
+ launchReadiness.pendingRecommendedCount,
3669
+ launchReadiness.pendingRequiredCount
3670
+ ]);
3671
+ const { restartAvailable, reauthenticate } = usePreviewRestart(dashboardBaseUrl, siteSlug);
3672
+ const dashboardContinueUrl = useMemo(() => {
3673
+ if (!dashboardBaseUrl) return null;
3674
+ if (authMode === "onboardingGrant") return onboardingConfirmationCheck.dashboardUnlocked ? onboardingConfirmationCheck.dashboardContinueUrl : siteId ? (() => {
3675
+ const continueUrl = new URL("/auth/onboarding/continue", dashboardBaseUrl);
3676
+ continueUrl.searchParams.set("dashboard", `/dashboard/sites/${siteId}/launch`);
3677
+ return continueUrl.toString();
3678
+ })() : null;
3679
+ if (dashboardSetupHandoff?.kind === "dashboard_setup") return buildPreviewDashboardSetupUrl(dashboardBaseUrl, dashboardSetupHandoff);
3680
+ return null;
3681
+ }, [
3682
+ authMode,
3683
+ dashboardBaseUrl,
3684
+ dashboardSetupHandoff,
3685
+ onboardingConfirmationCheck.dashboardContinueUrl,
3686
+ onboardingConfirmationCheck.dashboardUnlocked,
3687
+ siteId
3688
+ ]);
3689
+ const handleCompleteSetup = useCallback(() => {
3690
+ if (!dashboardContinueUrl || typeof window === "undefined") return;
3691
+ window.location.href = dashboardContinueUrl;
3692
+ }, [dashboardContinueUrl]);
3693
+ if (state !== "ok") return /* @__PURE__ */ jsx(PreviewRecoveryBanner, {
3694
+ state,
3695
+ renewalPending,
3696
+ restartAvailable,
3697
+ reauthenticate
3698
+ });
3699
+ const showOnboardingGrantGuidance = authMode === "onboardingGrant";
3700
+ const showDashboardSetupGuidance = dashboardSetupHandoff?.kind === "dashboard_setup";
3701
+ const hasActionableSetup = launchReadiness.pendingRequiredCount > 0 || launchReadiness.pendingRecommendedCount > 0 || launchReadiness.pendingOptionalCount > 0;
3702
+ const shouldAwaitDashboardSetupStatus = showDashboardSetupGuidance && !showOnboardingGrantGuidance && !onboardingConfirmationCheck.hasLoadedStatus && !onboardingConfirmationCheck.statusLoadFailed;
3703
+ const shouldHideDashboardSetupGuidance = showDashboardSetupGuidance && !showOnboardingGrantGuidance && (onboardingConfirmationCheck.statusLoadFailed || !hasActionableSetup);
3704
+ const bannerState = resolvePreviewSetupBannerState({
3705
+ authMode: showOnboardingGrantGuidance ? "onboardingGrant" : null,
3706
+ hasDashboardSetupHandoff: showDashboardSetupGuidance && !shouldHideDashboardSetupGuidance,
3707
+ dashboardUnlocked: onboardingConfirmationCheck.dashboardUnlocked
3708
+ });
3709
+ const bannerModel = resolvePreviewSetupBannerModel({
3710
+ surfaceId,
3711
+ bannerState,
3712
+ dashboardUnlocked: onboardingConfirmationCheck.dashboardUnlocked
3713
+ });
3714
+ const showDashboardCta = bannerState === "dashboard_ready" || bannerState === "dashboard_resume";
3715
+ if (shouldAwaitDashboardSetupStatus || shouldHideDashboardSetupGuidance) return null;
3716
+ if (!bannerState || !bannerModel) return null;
3717
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(FixedBottomSurface, {
3718
+ variant: "light",
3719
+ width: "centered",
3720
+ offsetCssVar: "--builder-editor-chrome-offset",
3721
+ reserveOffsetCssVar: "--builder-preview-banner-offset",
3722
+ className: bannerModel.bannerClassName,
3723
+ children: /* @__PURE__ */ jsxs("div", {
3724
+ className: "flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between",
3725
+ children: [/* @__PURE__ */ jsxs("div", {
3726
+ className: "space-y-1.5",
3727
+ children: [
3728
+ /* @__PURE__ */ jsx("h4", {
3729
+ className: bannerModel.titleClassName,
3730
+ children: bannerModel.copy.title
3731
+ }),
3732
+ /* @__PURE__ */ jsx("p", {
3733
+ className: bannerModel.descriptionClassName,
3734
+ children: bannerModel.copy.description
3735
+ }),
3736
+ bannerModel.copy.detail ? /* @__PURE__ */ jsx("p", {
3737
+ className: bannerModel.detailClassName,
3738
+ children: bannerModel.copy.detail
3739
+ }) : null,
3740
+ bannerModel.copy.checklistNote ? /* @__PURE__ */ jsxs("div", {
3741
+ className: bannerModel.summaryClassName,
3742
+ children: [/* @__PURE__ */ jsx("p", {
3743
+ className: bannerModel.summaryTitleClassName,
3744
+ children: setupSummary
3745
+ }), /* @__PURE__ */ jsx("p", {
3746
+ className: bannerModel.summaryBodyClassName,
3747
+ children: bannerModel.copy.checklistNote
3748
+ })]
3749
+ }) : null
3750
+ ]
3751
+ }), /* @__PURE__ */ jsxs("div", {
3752
+ className: "flex flex-col gap-2 sm:items-end",
3753
+ children: [
3754
+ /* @__PURE__ */ jsx("div", {
3755
+ className: "flex flex-col gap-2 sm:flex-row sm:items-center",
3756
+ children: showDashboardCta ? /* @__PURE__ */ jsx(Button, {
3757
+ type: "button",
3758
+ size: "sm",
3759
+ className: bannerModel.primaryButtonClassName,
3760
+ onClick: handleCompleteSetup,
3761
+ disabled: !dashboardContinueUrl,
3762
+ children: bannerModel.ctaLabel
3763
+ }) : /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(Button, {
3764
+ type: "button",
3765
+ size: "sm",
3766
+ variant: "outline",
3767
+ className: bannerModel.secondaryButtonClassName,
3768
+ onClick: () => void onboardingConfirmationCheck.resendConfirmation(),
3769
+ disabled: onboardingConfirmationCheck.resendButton.disabled,
3770
+ children: onboardingConfirmationCheck.resendButton.label
3771
+ }), /* @__PURE__ */ jsx(Button, {
3772
+ type: "button",
3773
+ size: "sm",
3774
+ className: bannerModel.primaryButtonClassName,
3775
+ onClick: () => void onboardingConfirmationCheck.checkConfirmation(),
3776
+ disabled: !dashboardContinueUrl || onboardingConfirmationCheck.isCheckingConfirmation,
3777
+ children: onboardingConfirmationCheck.isCheckingConfirmation ? "Checking..." : "I've confirmed my email"
3778
+ })] })
3779
+ }),
3780
+ /* @__PURE__ */ jsx(ConfirmationResendSupport, {
3781
+ visible: onboardingConfirmationCheck.resendNeedsSupport,
3782
+ dashboardBaseUrl
3783
+ }),
3784
+ showOnboardingGrantGuidance && onboardingConfirmationCheck.resendFeedback ? /* @__PURE__ */ jsx("p", {
3785
+ "aria-live": "polite",
3786
+ className: onboardingConfirmationCheck.resendFeedback.kind === "error" ? "text-xs text-destructive" : "text-xs text-muted-foreground",
3787
+ children: onboardingConfirmationCheck.resendFeedback.message
3788
+ }) : null
3789
+ ]
3790
+ })]
3791
+ })
3792
+ }), /* @__PURE__ */ jsx(PreviewConfirmationDialog, {
3793
+ dashboardContinueUrl,
3794
+ dialogState: onboardingConfirmationCheck.dialogState,
3795
+ isCheckingConfirmation: onboardingConfirmationCheck.isCheckingConfirmation,
3796
+ onCheckConfirmation: onboardingConfirmationCheck.checkConfirmation,
3797
+ onClose: onboardingConfirmationCheck.closeDialog,
3798
+ onCompleteSetup: handleCompleteSetup
3799
+ })] });
3800
+ }
3801
+ //#endregion
3802
+ //#region ../preview-next/src/client/preview/PreviewAccessBanners.tsx
3803
+ function previewLeaseThing(isEntry, pageNodeType) {
3804
+ if (pageNodeType === "page_surface") return "this event page";
3805
+ return isEntry ? "this entry" : "this page";
3806
+ }
3807
+ function PreviewAccessBanners({ dashboardBaseUrl, surfaceId, isEntry, pageNodeType }) {
3808
+ const { state } = usePreviewAuth();
3809
+ const { requestedEditingMode, setEditingMode } = useEditor();
3810
+ const showDiscardedNotice = useEditorUiStore((editor) => canEditorWrite(editor.editability) && editor.leaseDiscardedChanges);
3811
+ const thing = previewLeaseThing(isEntry, pageNodeType);
3812
+ const admissionNotice = useEditorUiStore((editor) => editorAdmissionNotice(editor.getAdmission()));
3813
+ const active = state === "ok";
3814
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [
3815
+ /* @__PURE__ */ jsx(PreviewAuthBanner, {
3816
+ dashboardBaseUrl,
3817
+ surfaceId
3818
+ }),
3819
+ active && admissionNotice ? /* @__PURE__ */ jsx(FixedBottomSurface, {
3820
+ variant: "light",
3821
+ width: "centered",
3822
+ offsetCssVar: "--builder-editor-chrome-offset",
3823
+ reserveOffsetCssVar: "--builder-preview-banner-offset",
3824
+ children: /* @__PURE__ */ jsx(Callout, {
3825
+ tone: "info",
3826
+ role: "status",
3827
+ children: /* @__PURE__ */ jsx(CalloutDescription, { children: admissionNotice })
3828
+ })
3829
+ }) : null,
3830
+ active && requestedEditingMode ? /* @__PURE__ */ jsx(EditLeaseModal, {
3831
+ thing,
3832
+ onKeepViewing: () => setEditingMode(false)
3833
+ }) : null,
3834
+ active && showDiscardedNotice ? /* @__PURE__ */ jsx(FixedBottomSurface, {
3835
+ variant: "light",
3836
+ width: "centered",
3837
+ offsetCssVar: "--builder-editor-chrome-offset",
3838
+ reserveOffsetCssVar: "--builder-preview-banner-offset",
3839
+ children: /* @__PURE__ */ jsx(EditLeaseDiscardedNotice, { thing })
3840
+ }) : null
3841
+ ] });
3842
+ }
3843
+ //#endregion
3844
+ //#region ../preview-next/src/client/preview/SiteChromeEditableSurface.tsx
3845
+ function SiteChromeEditableSurface({ surface, children, preserveSingleComponentRoot = false }) {
3846
+ return renderEditableSurface(children, surface, { preserveSingleComponentRoot });
3847
+ }
3848
+ function renderEditableSurface(children, surface, options) {
3849
+ const childArray = Children.toArray(children);
3850
+ const child = childArray.length === 1 ? childArray[0] : null;
3851
+ if (isValidElement(child) && child.type !== Fragment && (isHostElement(child) || options.preserveSingleComponentRoot || isEditableSurfaceForwardingElement(child))) return cloneElement(child, {
3852
+ className: joinClassNames(child.props.className, "group/site-chrome relative"),
3853
+ "data-preview-site-chrome-surface": surface,
3854
+ children: /* @__PURE__ */ jsxs(Fragment$1, { children: [surface === "footer" ? /* @__PURE__ */ jsx(FooterModuleInspectionSurface, { children: child.props.children }) : child.props.children, /* @__PURE__ */ jsx(SiteChromeCustomizeButton, { surface })] })
3855
+ });
3856
+ if (surface === "header") return /* @__PURE__ */ jsxs("div", {
3857
+ className: "group/site-chrome",
3858
+ "data-preview-site-chrome-surface": surface,
3859
+ style: { display: "contents" },
3860
+ children: [children, /* @__PURE__ */ jsx(SiteChromeCustomizeButton, {
3861
+ surface,
3862
+ containerClassName: "pointer-events-auto fixed right-4 top-4 z-[70] opacity-0 transition group-focus-within/site-chrome:opacity-100 group-hover/site-chrome:opacity-100"
3863
+ })]
3864
+ });
3865
+ return /* @__PURE__ */ jsxs("div", {
3866
+ className: "group/site-chrome relative",
3867
+ "data-preview-site-chrome-surface": surface,
3868
+ children: [/* @__PURE__ */ jsx(FooterModuleInspectionSurface, { children }), /* @__PURE__ */ jsx(SiteChromeCustomizeButton, { surface })]
3869
+ });
3870
+ }
3871
+ function FooterModuleInspectionSurface({ children }) {
3872
+ const editorUiStore = useOptionalEditorUiStoreInstance();
3873
+ return editorUiStore ? /* @__PURE__ */ jsx(EnabledFooterModuleInspectionSurface, {
3874
+ editorUiStore,
3875
+ children
3876
+ }) : /* @__PURE__ */ jsx(Fragment$1, { children });
3877
+ }
3878
+ const FOOTER_MODULE_SELECTOR = "[data-preview-footer-module-id]";
3879
+ /**
3880
+ * Footer sections are edited like in-place text: hovering one, or keyboard
3881
+ * focus anywhere inside it, draws the preview's standard dashed outline.
3882
+ *
3883
+ * - A section with nothing interactive inside (logo, text) is itself a
3884
+ * button: click, Enter or Space opens the footer composer on it.
3885
+ * - A section holding links or form controls is a labelled group, never a
3886
+ * button (no nested interactive content, no extra tab stop). Activating one
3887
+ * of its links, by click or Enter, opens the section; form controls (the
3888
+ * footer signup form) keep working.
3889
+ *
3890
+ * The footer-wide Edit and Customize pills live in SiteChromeCustomizeButton.
3891
+ */
3892
+ const footerModuleAffordanceCss = `
3893
+ ${FOOTER_MODULE_SELECTOR} {
3894
+ cursor: pointer;
3895
+ border-radius: 2px;
3896
+ }
3897
+ ${FOOTER_MODULE_SELECTOR}:hover,
3898
+ ${FOOTER_MODULE_SELECTOR}:focus-visible,
3899
+ ${FOOTER_MODULE_SELECTOR}:has(:focus-visible) {
3900
+ outline: ${PREVIEW_EDITABLE_OUTLINE};
3901
+ outline-offset: 2px;
3902
+ }
3903
+ `;
3904
+ function EnabledFooterModuleInspectionSurface({ children, editorUiStore }) {
3905
+ const rootRef = useRef(null);
3906
+ useEffect(() => {
3907
+ const root = rootRef.current;
3908
+ if (!root) return;
3909
+ const modules = root.querySelectorAll(FOOTER_MODULE_SELECTOR);
3910
+ for (const module of modules) {
3911
+ if (module.querySelector(INTERACTIVE_CONTENT_SELECTOR)) {
3912
+ module.setAttribute("role", "group");
3913
+ module.removeAttribute("tabindex");
3914
+ } else {
3915
+ module.setAttribute("role", "button");
3916
+ module.tabIndex = 0;
3917
+ }
3918
+ const label = module.dataset.previewFooterModuleId?.replace(/-/gu, " ") ?? "footer section";
3919
+ module.setAttribute("aria-label", `Edit ${label}`);
3920
+ }
3921
+ }, [children]);
3922
+ const inspect = (moduleId, event) => {
3923
+ event.preventDefault();
3924
+ editorUiStore.getState().openSidebarView({
3925
+ kind: "chrome",
3926
+ target: "footer",
3927
+ moduleId
3928
+ });
3929
+ };
3930
+ return /* @__PURE__ */ jsxs("div", {
3931
+ ref: rootRef,
3932
+ style: { display: "contents" },
3933
+ onClick: (event) => {
3934
+ const moduleId = footerModuleIdForClick(event.target);
3935
+ if (moduleId) inspect(moduleId, event);
3936
+ },
3937
+ onKeyDown: (event) => {
3938
+ if (event.key !== "Enter" && event.key !== " ") return;
3939
+ const moduleId = footerModuleIdForKey(event.target);
3940
+ if (moduleId) inspect(moduleId, event);
3941
+ },
3942
+ children: [/* @__PURE__ */ jsx("style", { children: footerModuleAffordanceCss }), children]
3943
+ });
3944
+ }
3945
+ const FORM_CONTROL_SELECTOR = "input, select, textarea, button, label";
3946
+ const INTERACTIVE_CONTENT_SELECTOR = `a[href], ${FORM_CONTROL_SELECTOR}`;
3947
+ function footerModuleIdOf(element) {
3948
+ if (!(element instanceof HTMLElement)) return null;
3949
+ const parsed = parseFooterModuleId(element.dataset.previewFooterModuleId);
3950
+ return parsed.ok ? parsed.value : null;
3951
+ }
3952
+ /** The footer section a click should open, or null to let the click through. */
3953
+ function footerModuleIdForClick(target) {
3954
+ if (!(target instanceof Element) || target.closest(FORM_CONTROL_SELECTOR)) return null;
3955
+ return footerModuleIdOf(target.closest(FOOTER_MODULE_SELECTOR));
3956
+ }
3957
+ /** Enter/Space only opens a section when the section itself has focus. */
3958
+ function footerModuleIdForKey(target) {
3959
+ return target instanceof Element && target.matches(FOOTER_MODULE_SELECTOR) ? footerModuleIdOf(target) : null;
3960
+ }
3961
+ function isHostElement(child) {
3962
+ return typeof child.type === "string";
3963
+ }
3964
+ function isEditableSurfaceForwardingElement(child) {
3965
+ return typeof child.type !== "string" && child.type !== Fragment && child.type["forwardsSiteChromeEditableSurface"] === true;
3966
+ }
3967
+ function joinClassNames(...values) {
3968
+ const className = values.filter(Boolean).join(" ");
3969
+ return className.length > 0 ? className : void 0;
3970
+ }
3971
+ //#endregion
3972
+ //#region ../preview-next/src/client/preview/themeRuntime.ts
3973
+ const defaultPreviewThemeRuntime = { kind: "cms-theme" };
3974
+ //#endregion
3975
+ //#region ../preview-next/src/client/preview/PreviewThemedSiteDocument.tsx
3976
+ function planPreviewSiteDocument(theme, bannerNode, headerNode) {
3977
+ return planSiteDocument({
3978
+ headerPositioning: theme.header?.positioning ?? "static",
3979
+ headerVariant: theme.header?.variant ?? null,
3980
+ hasVisibleBanner: Boolean(bannerNode),
3981
+ hasVisibleHeader: Boolean(headerNode)
3982
+ });
3983
+ }
3984
+ function resolveDocumentResponsiveMode(runtime, useContainerResponsiveMode) {
3985
+ return runtime.kind === "none" ? void 0 : runtime.responsiveMode ?? (useContainerResponsiveMode ? "container" : "viewport");
3986
+ }
3987
+ function renderPreviewHeader(model, theme, fallback) {
3988
+ if (!model?.header) return fallback;
3989
+ return /* @__PURE__ */ jsx(SiteChromeEditableSurface, {
3990
+ surface: "header",
3991
+ children: renderSiteChromeBlock(model, "header", theme, { themeConfigOverrideMode: "ignore" })
3992
+ });
3993
+ }
3994
+ function PreviewThemedSiteDocument({ children, themeRuntime = defaultPreviewThemeRuntime, useContainerResponsiveMode, viewportMode, viewportWidth, scale, contentHeight, scaleContainerRef, contentRef, staticHeaderNode, bannerNode, staticFooterNode, siteChromeRenderModel }) {
3995
+ const compiled = usePreviewCompiledTheme();
3996
+ const effectiveTheme = compiled.theme;
3997
+ const headerNode = renderPreviewHeader(siteChromeRenderModel, effectiveTheme, staticHeaderNode);
3998
+ const siteDocumentPlan = planPreviewSiteDocument(effectiveTheme, bannerNode, headerNode);
3999
+ const footerNode = renderPreviewFooter(siteChromeRenderModel, effectiveTheme, staticFooterNode);
4000
+ const responsiveMode = resolveDocumentResponsiveMode(themeRuntime, useContainerResponsiveMode);
4001
+ return renderPreviewDocument({
4002
+ wrapDocument: (document) => renderThemedDocument(themeRuntime, compiled, responsiveMode, document),
4003
+ viewportMode,
4004
+ viewportWidth,
4005
+ scale,
4006
+ contentHeight,
4007
+ scaleContainerRef,
4008
+ contentRef,
4009
+ siteDocumentPlan,
4010
+ headerNode,
4011
+ bannerNode: markPreviewSiteBanner(bannerNode),
4012
+ footerNode,
4013
+ children
4014
+ });
4015
+ }
4016
+ /**
4017
+ * The shell marks whatever banner it's given, so preview chrome can stay clear
4018
+ * of it without the site's own markup having to cooperate (SDK sites render
4019
+ * their own). The wrapper has no box; the banner's elements are its children.
4020
+ */
4021
+ function markPreviewSiteBanner(bannerNode) {
4022
+ return bannerNode ? /* @__PURE__ */ jsx("div", {
4023
+ [PREVIEW_SITE_BANNER_ATTRIBUTE]: "",
4024
+ style: { display: "contents" },
4025
+ children: bannerNode
4026
+ }) : null;
4027
+ }
4028
+ function renderPreviewFooter(model, theme, fallback) {
4029
+ if (!model || model.footer.canRenderReactively === false) return fallback;
4030
+ return /* @__PURE__ */ jsx(SiteChromeEditableSurface, {
4031
+ surface: "footer",
4032
+ preserveSingleComponentRoot: true,
4033
+ children: renderSiteChromeBlock(model, "footer", theme, { themeConfigOverrideMode: "ignore" })
4034
+ });
4035
+ }
4036
+ function renderThemedDocument(runtime, compiled, responsiveMode, documentNode) {
4037
+ switch (runtime.kind) {
4038
+ case "cms-theme": return /* @__PURE__ */ jsx(ThemeScopeCore, {
4039
+ ...themeRuntimeScopeProps(compiled.runtime),
4040
+ dataAttrs: buildThemeDataAttrs(compiled.theme.axes, "theme-default", compiled.theme.skin),
4041
+ suppressHydrationWarning: true,
4042
+ responsiveMode,
4043
+ className: "rb-flex rb-flex-1 rb-flex-col",
4044
+ children: documentNode
4045
+ });
4046
+ case "responsive-only": return /* @__PURE__ */ jsx(ResponsiveScope, {
4047
+ responsiveMode,
4048
+ className: "rb-flex rb-flex-1 rb-flex-col",
4049
+ children: documentNode
4050
+ });
4051
+ case "none": return documentNode;
4052
+ default: return assertNever$2(runtime);
4053
+ }
4054
+ }
4055
+ function PreviewOverrideOnlySiteDocument({ children, runtime, useContainerResponsiveMode, viewportMode, viewportWidth, scale, contentHeight, scaleContainerRef, contentRef }) {
4056
+ return renderPreviewDocument({
4057
+ wrapDocument: (document) => runtime.kind === "none" ? document : /* @__PURE__ */ jsx(ResponsiveScope, {
4058
+ responsiveMode: runtime.responsiveMode ?? (useContainerResponsiveMode ? "container" : "viewport"),
4059
+ className: "rb-flex rb-flex-1 rb-flex-col",
4060
+ children: document
4061
+ }),
4062
+ viewportMode,
4063
+ viewportWidth,
4064
+ scale,
4065
+ contentHeight,
4066
+ scaleContainerRef,
4067
+ contentRef,
4068
+ siteDocumentPlan: planSiteDocument({
4069
+ headerPositioning: "static",
4070
+ headerVariant: null,
4071
+ hasVisibleBanner: false,
4072
+ hasVisibleHeader: false
4073
+ }),
4074
+ headerNode: null,
4075
+ bannerNode: null,
4076
+ footerNode: null,
4077
+ children
4078
+ });
4079
+ }
4080
+ /** The selected frame owns the unscaled responsive scope, for themed and SDK documents alike. */
4081
+ function renderPreviewDocument(input) {
4082
+ const frame = planPreviewDocumentFrame(input);
4083
+ const document = input.wrapDocument(/* @__PURE__ */ jsx(SiteDocumentLayout, {
4084
+ as: "main",
4085
+ role: "main",
4086
+ plan: input.siteDocumentPlan,
4087
+ headerNode: input.headerNode,
4088
+ bannerNode: input.bannerNode,
4089
+ footerNode: input.footerNode,
4090
+ minHeightClassName: frame.kind === "fixed" ? SITE_CHROME_CLASS_NAMES.fullMinHeight : null,
4091
+ className: frame.kind === "squeeze" ? `${frame.frameClassName} rb-flex-1 rb-preview-editor-offset` : "rb-preview-editor-offset",
4092
+ style: frame.kind === "fixed" ? frame.siteDocumentStyle : void 0,
4093
+ children: input.children
4094
+ }));
4095
+ if (frame.kind === "squeeze") return document;
4096
+ return /* @__PURE__ */ jsx("div", {
4097
+ ref: input.scaleContainerRef,
4098
+ className: "h-full overflow-auto",
4099
+ children: /* @__PURE__ */ jsx("div", {
4100
+ style: frame.wrapperStyle,
4101
+ children: /* @__PURE__ */ jsx("div", {
4102
+ ref: input.contentRef,
4103
+ className: `${frame.frameClassName} border-x shadow-sm`,
4104
+ style: frame.contentStyle,
4105
+ ...frame.frameDataProps,
4106
+ children: document
4107
+ })
4108
+ })
4109
+ });
4110
+ }
4111
+ //#endregion
4112
+ //#region ../preview-next/src/client/preview/linkedEntryEditEvents.ts
4113
+ const LINKED_ENTRY_EDIT_EVENT = "riverbank:preview:linked-entry-edit";
4114
+ const LINKED_ENTRY_FIELD_FOCUS_EVENT = "riverbank:preview:linked-entry-field-focus";
4115
+ const BLOCK_FIELD_FOCUS_EVENT = "riverbank:preview:block-field-focus";
4116
+ function dispatchLinkedEntryEditEvent(target) {
4117
+ window.dispatchEvent(new CustomEvent(LINKED_ENTRY_EDIT_EVENT, { detail: target }));
4118
+ }
4119
+ function dispatchLinkedEntryFieldFocusEvent(binding) {
4120
+ window.dispatchEvent(new CustomEvent(LINKED_ENTRY_FIELD_FOCUS_EVENT, { detail: binding }));
4121
+ }
4122
+ function dispatchBlockFieldFocusEvent(target) {
4123
+ window.dispatchEvent(new CustomEvent(BLOCK_FIELD_FOCUS_EVENT, { detail: target }));
4124
+ }
4125
+ function isLinkedEntryEditEvent(event) {
4126
+ if (!(event instanceof CustomEvent)) return false;
4127
+ const detail = event.detail;
4128
+ return Boolean(detail) && typeof detail === "object" && detail.kind === "linked-content-entry";
4129
+ }
4130
+ function isLinkedEntryFieldFocusEvent(event) {
4131
+ if (!(event instanceof CustomEvent)) return false;
4132
+ const detail = event.detail;
4133
+ const write = detail?.write;
4134
+ return Boolean(detail) && typeof detail === "object" && detail.kind === "linked-entry-field" && Boolean(detail.target) && Boolean(write) && typeof write === "object" && typeof write.fieldPath === "string";
4135
+ }
4136
+ function isBlockFieldFocusEvent(event) {
4137
+ if (!(event instanceof CustomEvent)) return false;
4138
+ const detail = event.detail;
4139
+ return Boolean(detail) && typeof detail === "object" && detail.kind === "block-field" && typeof detail.blockId === "string" && typeof detail.fieldPath === "string";
4140
+ }
4141
+ //#endregion
4142
+ //#region ../preview-next/src/client/preview/LinkedEntryEditEventBridge.tsx
4143
+ function LinkedEntryEditEventBridge() {
4144
+ const uiStore = useEditorUiStoreInstance();
4145
+ useEffect(() => {
4146
+ const handleLinkedEntryEdit = (event) => {
4147
+ if (!isLinkedEntryEditEvent(event)) return;
4148
+ uiStore.getState().linkedEntries.open(event.detail);
4149
+ };
4150
+ const handleLinkedEntryFieldFocus = (event) => {
4151
+ if (!isLinkedEntryFieldFocusEvent(event)) return;
4152
+ const state = uiStore.getState();
4153
+ if (state.linkedEntries.getSelectedEntryId() !== event.detail.write.entryId) state.linkedEntries.open(event.detail.target);
4154
+ state.setActivePreviewField({
4155
+ kind: "linked-entry",
4156
+ entryId: unsafeAsLinkedContentEntryId(event.detail.write.entryId),
4157
+ fieldPath: event.detail.write.fieldPath
4158
+ });
4159
+ };
4160
+ const handleBlockFieldFocus = (event) => {
4161
+ if (!isBlockFieldFocusEvent(event)) return;
4162
+ const state = uiStore.getState();
4163
+ const blockId = unsafeAsEditorBlockId(event.detail.blockId);
4164
+ state.setActivePreviewField({
4165
+ kind: "block",
4166
+ blockId,
4167
+ fieldPath: event.detail.fieldPath
4168
+ });
4169
+ };
4170
+ window.addEventListener(LINKED_ENTRY_EDIT_EVENT, handleLinkedEntryEdit);
4171
+ window.addEventListener(LINKED_ENTRY_FIELD_FOCUS_EVENT, handleLinkedEntryFieldFocus);
4172
+ window.addEventListener(BLOCK_FIELD_FOCUS_EVENT, handleBlockFieldFocus);
4173
+ return () => {
4174
+ window.removeEventListener(LINKED_ENTRY_EDIT_EVENT, handleLinkedEntryEdit);
4175
+ window.removeEventListener(LINKED_ENTRY_FIELD_FOCUS_EVENT, handleLinkedEntryFieldFocus);
4176
+ window.removeEventListener(BLOCK_FIELD_FOCUS_EVENT, handleBlockFieldFocus);
4177
+ };
4178
+ }, [uiStore]);
4179
+ return null;
4180
+ }
4181
+ //#endregion
4182
+ //#region ../preview-next/src/client/preview/PreviewShellLayout.tsx
4183
+ /** The preview keeps at least this much room beside the sidebar; the sidebar narrows first. */
4184
+ const PREVIEW_MIN_WIDTH = 640;
4185
+ function isOverrideOnlyPreviewShellLayout(props) {
4186
+ return props.rendering?.kind === "overrides-only";
4187
+ }
4188
+ function resolveShellThemeRoles(props, journalSource) {
4189
+ if (isOverrideOnlyPreviewShellLayout(props)) return null;
4190
+ const source = journalSource;
4191
+ if (!source) throw new Error("The theme source must be mounted above the preview design providers");
4192
+ const theme = previewThemeBase(source);
4193
+ return theme ? {
4194
+ source,
4195
+ persistenceTheme: theme
4196
+ } : null;
4197
+ }
4198
+ const previewContainerResponsiveEnabled = process.env.NEXT_PUBLIC_ENABLE_PREVIEW_CONTAINER_RESPONSIVE !== "false";
4199
+ const PreviewEditorSidebar = React.lazy(async () => {
4200
+ return { default: (await import("./PreviewEditorSidebar-Ckr2zk_L.mjs")).PreviewEditorSidebar };
4201
+ });
4202
+ const PreviewEditorUI = React.lazy(async () => {
4203
+ return { default: (await import("./PreviewEditorUI-KOZgw_gS.mjs")).PreviewEditorUI };
4204
+ });
4205
+ function renderShellProviders(input) {
4206
+ if (!input.themeRoles) return input.content;
4207
+ const { props, themeRoles } = input;
4208
+ return /* @__PURE__ */ jsx(PreviewThemeRenderingProvider, {
4209
+ source: themeRoles.source,
4210
+ renderingOverride: props.renderingOverride,
4211
+ pageAdaptationFacts: props.pageAdaptationFacts,
4212
+ children: /* @__PURE__ */ jsx(PreviewCompiledThemeProvider, {
4213
+ responsiveMode: previewCompiledResponsiveMode(props),
4214
+ children: input.content
4215
+ })
4216
+ });
4217
+ }
4218
+ function PreviewDocumentContent(input) {
4219
+ if (input.rendering?.kind === "overrides-only") return /* @__PURE__ */ jsx(PreviewOverrideOnlySiteDocument, {
4220
+ runtime: input.rendering.runtime,
4221
+ useContainerResponsiveMode: previewContainerResponsiveEnabled,
4222
+ viewportMode: input.viewportMode,
4223
+ viewportWidth: input.viewportWidth,
4224
+ scale: input.scale,
4225
+ contentHeight: input.contentHeight,
4226
+ scaleContainerRef: input.scaleContainerRef,
4227
+ contentRef: input.contentRef,
4228
+ children: input.children
4229
+ });
4230
+ return /* @__PURE__ */ jsx(PreviewChromeLayerProvider, { children: /* @__PURE__ */ jsx(PreviewThemedSiteDocument, {
4231
+ themeRuntime: input.themeRuntime,
4232
+ useContainerResponsiveMode: previewContainerResponsiveEnabled,
4233
+ viewportMode: input.viewportMode,
4234
+ viewportWidth: input.viewportWidth,
4235
+ scale: input.scale,
4236
+ contentHeight: input.contentHeight,
4237
+ scaleContainerRef: input.scaleContainerRef,
4238
+ contentRef: input.contentRef,
4239
+ staticHeaderNode: input.headerNode,
4240
+ bannerNode: input.bannerNode,
4241
+ staticFooterNode: input.footerNode,
4242
+ siteChromeRenderModel: input.siteChromeRenderModel,
4243
+ children: input.children
4244
+ }) });
4245
+ }
4246
+ function PreviewShellLayout(props) {
4247
+ const themeRoles = resolveShellThemeRoles(props, usePreviewThemeSourceOptional());
4248
+ if (!isOverrideOnlyPreviewShellLayout(props) && !themeRoles) return /* @__PURE__ */ jsx(PreviewThemeUnavailable, {});
4249
+ return isOverrideOnlyPreviewShellLayout(props) || themeRoles ? /* @__PURE__ */ jsx(AvailablePreviewShellLayout, {
4250
+ props,
4251
+ themeRoles
4252
+ }) : null;
4253
+ }
4254
+ function PreviewThemeUnavailable() {
4255
+ return /* @__PURE__ */ jsx("div", {
4256
+ role: "alert",
4257
+ className: "flex h-full items-center justify-center p-6 text-center",
4258
+ children: "This site's design couldn't be loaded. Try reloading the page."
4259
+ });
4260
+ }
4261
+ function AvailablePreviewShellLayout({ props, themeRoles }) {
4262
+ const { children, rendering, surfaceId, siteId, dashboardBaseUrl = null, pageId, entryData, contentTypeSchema, referenceContentTypeKeys = [], draftContent, currentTemplate, apiClient, themeSelectionButtonStyleRepairs, isSiteLaunched, maintenanceModeEnabled, entrySubrouteContext, sdkConfig, bookingOfferingPresets, themeRuntime = defaultPreviewThemeRuntime, siteStyleAccess = { kind: "hidden" } } = props;
4263
+ const layout = useOptionalPreviewLayout();
4264
+ const headerNode = layout?.headerNode ?? null;
4265
+ const bannerNode = layout?.bannerNode ?? null;
4266
+ const footerNode = layout?.footerNode ?? null;
4267
+ const siteChromeRenderModel = layout?.siteChromeRenderModel ?? null;
4268
+ const surfaceDocument = useMemo(() => resolvePreviewChromeSurface(surfaceId), [surfaceId]);
4269
+ const isOpen = usePreviewDrawerOpen();
4270
+ const { requestedEditingMode, isEditingMode } = useEditor();
4271
+ usePreviewModeRootAttribute(isEditingMode);
4272
+ const viewportMode = useEditorUiStore((s) => s.viewport.mode);
4273
+ const viewportWidth = useEditorUiStore((s) => s.viewport.width);
4274
+ const sidebarWidth = useEditorUiStore((s) => s.viewport.sidebarWidth);
4275
+ const zoom = useEditorUiStore((s) => s.viewport.zoom);
4276
+ const setViewportMode = useEditorUiStore((s) => s.viewport.setMode);
4277
+ const setViewportWidth = useEditorUiStore((s) => s.viewport.setWidth);
4278
+ const setSidebarWidth = useEditorUiStore((s) => s.viewport.setSidebarWidth);
4279
+ const setZoom = useEditorUiStore((s) => s.viewport.setZoom);
4280
+ useEffect(() => {
4281
+ const storedMode = localStorage.getItem("preview-viewport-mode");
4282
+ const storedWidth = localStorage.getItem("preview-viewport-width");
4283
+ const storedSidebarWidth = localStorage.getItem("preview-sidebar-width");
4284
+ const storedZoom = localStorage.getItem("preview-zoom-level");
4285
+ if (storedMode === "squeeze" || storedMode === "fixed") setViewportMode(storedMode);
4286
+ if (storedWidth) if (storedWidth === "full") setViewportWidth("full");
4287
+ else {
4288
+ const width = parseInt(storedWidth, 10);
4289
+ if (Number.isFinite(width)) setViewportWidth(width);
4290
+ }
4291
+ const sidebarWidthPreference = parseStoredSidebarWidth(storedSidebarWidth);
4292
+ if (sidebarWidthPreference !== null) setSidebarWidth(sidebarWidthPreference);
4293
+ if (storedZoom) if (storedZoom === "fit") setZoom("fit");
4294
+ else {
4295
+ const zoomValue = parseInt(storedZoom, 10);
4296
+ if (zoomValue === 33 || zoomValue === 50 || zoomValue === 75 || zoomValue === 100) setZoom(zoomValue);
4297
+ }
4298
+ }, [
4299
+ setViewportMode,
4300
+ setViewportWidth,
4301
+ setSidebarWidth,
4302
+ setZoom
4303
+ ]);
4304
+ useEffect(() => {
4305
+ localStorage.setItem("preview-viewport-mode", viewportMode);
4306
+ }, [viewportMode]);
4307
+ useEffect(() => {
4308
+ localStorage.setItem("preview-viewport-width", String(viewportWidth));
4309
+ }, [viewportWidth]);
4310
+ useEffect(() => {
4311
+ localStorage.setItem("preview-sidebar-width", String(sidebarWidth));
4312
+ }, [sidebarWidth]);
4313
+ useEffect(() => {
4314
+ localStorage.setItem("preview-zoom-level", String(zoom));
4315
+ }, [zoom]);
4316
+ const editorScopeKey = entryData?.id ? `entry:${entryData.id}` : `page:${pageId ?? "none"}`;
4317
+ const handleSidebarWidthChange = useCallback((width) => {
4318
+ setSidebarWidth(width);
4319
+ }, [setSidebarWidth]);
4320
+ const [containerWidth, setContainerWidth] = useState(0);
4321
+ const [contentHeight, setContentHeight] = useState(0);
4322
+ const containerObserverRef = useRef(null);
4323
+ const contentObserverRef = useRef(null);
4324
+ const contentRef = useRef(null);
4325
+ const scaleContainerRef = useCallback((node) => {
4326
+ if (containerObserverRef.current) {
4327
+ containerObserverRef.current.disconnect();
4328
+ containerObserverRef.current = null;
4329
+ }
4330
+ if (node) {
4331
+ const updateWidth = () => {
4332
+ setContainerWidth(node.offsetWidth);
4333
+ };
4334
+ containerObserverRef.current = new ResizeObserver(updateWidth);
4335
+ containerObserverRef.current.observe(node);
4336
+ updateWidth();
4337
+ }
4338
+ }, []);
4339
+ useEffect(() => {
4340
+ const contentNode = contentRef.current;
4341
+ if (!contentNode) return;
4342
+ const updateHeight = () => {
4343
+ setContentHeight(contentNode.scrollHeight);
4344
+ };
4345
+ contentObserverRef.current = new ResizeObserver(updateHeight);
4346
+ contentObserverRef.current.observe(contentNode);
4347
+ updateHeight();
4348
+ return () => {
4349
+ contentObserverRef.current?.disconnect();
4350
+ };
4351
+ }, [viewportMode, viewportWidth]);
4352
+ const renderedViewport = resolvePreviewViewport({
4353
+ requestedEditingMode,
4354
+ viewportMode,
4355
+ viewportWidth,
4356
+ zoom,
4357
+ containerWidth
4358
+ });
4359
+ const leftPane = /* @__PURE__ */ jsx(PreviewScrollViewport, { children: /* @__PURE__ */ jsx(PreviewDocumentContent, {
4360
+ rendering,
4361
+ themeRuntime,
4362
+ viewportMode: renderedViewport.viewportMode,
4363
+ viewportWidth: renderedViewport.viewportWidth,
4364
+ scale: renderedViewport.scale,
4365
+ contentHeight,
4366
+ scaleContainerRef,
4367
+ contentRef,
4368
+ headerNode,
4369
+ bannerNode,
4370
+ footerNode,
4371
+ siteChromeRenderModel,
4372
+ children
4373
+ }) });
4374
+ const rightPane = /* @__PURE__ */ jsx("div", {
4375
+ className: `${PREVIEW_CHROME_THEME_CLASS_NAME} flex h-full min-h-0 flex-col overflow-hidden ${surfaceDocument.surfaceClassName ?? ""}`,
4376
+ ...getPreviewChromeSurfaceDataProps(surfaceDocument),
4377
+ children: /* @__PURE__ */ jsx(React.Suspense, {
4378
+ fallback: null,
4379
+ children: /* @__PURE__ */ jsx(PreviewEditorSidebar, {
4380
+ surfaceId,
4381
+ siteId,
4382
+ dashboardBaseUrl,
4383
+ pageId,
4384
+ pageNodeType: props.pageNodeType,
4385
+ entryData,
4386
+ contentTypeSchema,
4387
+ referenceContentTypeKeys,
4388
+ draftContent,
4389
+ currentTemplate,
4390
+ theme: themeRoles?.persistenceTheme,
4391
+ apiClient,
4392
+ themeSelectionButtonStyleRepairs,
4393
+ sdkConfig: sdkConfig ?? null,
4394
+ entrySubrouteContext: entrySubrouteContext ?? null,
4395
+ bookingOfferingPresets,
4396
+ siteStyleAccess
4397
+ }, editorScopeKey)
4398
+ })
4399
+ });
4400
+ return renderShellProviders({
4401
+ props,
4402
+ themeRoles,
4403
+ content: /* @__PURE__ */ jsxs(PreviewRenderObservationsProvider, { children: [
4404
+ /* @__PURE__ */ jsx(PreviewSidebarBootstrap, {}),
4405
+ /* @__PURE__ */ jsx(LinkedEntryEditEventBridge, {}),
4406
+ /* @__PURE__ */ jsx(React.Suspense, {
4407
+ fallback: null,
4408
+ children: /* @__PURE__ */ jsx(PreviewEditorUI, {
4409
+ entryData,
4410
+ dashboardBaseUrl,
4411
+ inMaintenanceMode: maintenanceModeEnabled,
4412
+ siteId,
4413
+ surfaceId,
4414
+ isSiteLaunched,
4415
+ apiClient
4416
+ })
4417
+ }),
4418
+ /* @__PURE__ */ jsx(PreviewAccessBanners, {
4419
+ dashboardBaseUrl,
4420
+ surfaceId,
4421
+ isEntry: Boolean(entryData),
4422
+ pageNodeType: props.pageNodeType
4423
+ }),
4424
+ /* @__PURE__ */ jsx("div", {
4425
+ className: "fixed inset-0 overflow-hidden bg-background",
4426
+ children: isOpen ? /* @__PURE__ */ jsx(ResizableSplitPane, {
4427
+ left: leftPane,
4428
+ right: /* @__PURE__ */ jsx(EditorWriteSurface, { children: rightPane }),
4429
+ rightWidth: {
4430
+ px: sidebarWidth,
4431
+ min: SIDEBAR_WIDTH.min,
4432
+ max: SIDEBAR_WIDTH.max,
4433
+ minLeft: PREVIEW_MIN_WIDTH,
4434
+ onChange: handleSidebarWidthChange
4435
+ },
4436
+ leftLabel: "Preview",
4437
+ rightLabel: "Editor",
4438
+ defaultTab: "right",
4439
+ rightPaneClassName: "h-full min-h-0 overflow-hidden"
4440
+ }) : leftPane
4441
+ })
4442
+ ] })
4443
+ });
4444
+ }
4445
+ /** The sidebar belongs to edit mode; a stale open preference cannot expose it while viewing. */
4446
+ function usePreviewDrawerOpen() {
4447
+ const { requestedEditingMode } = useEditor();
4448
+ const drawerOpen = useEditorUiStore((s) => s.drawerOpen);
4449
+ return requestedEditingMode && drawerOpen;
4450
+ }
4451
+ function previewCompiledResponsiveMode(props) {
4452
+ const runtime = props.themeRuntime;
4453
+ return runtime && runtime.kind !== "none" && runtime.responsiveMode ? runtime.responsiveMode : previewContainerResponsiveEnabled ? "container" : "viewport";
4454
+ }
4455
+ //#endregion
4456
+ //#region ../preview-next/src/client/preview/PreviewAssistantEnvironment.tsx
4457
+ const Environment = createContext(null);
4458
+ function PreviewAssistantHostProvider({ value, children }) {
4459
+ return /* @__PURE__ */ jsx(Environment.Provider, {
4460
+ value,
4461
+ children
4462
+ });
4463
+ }
4464
+ //#endregion
4465
+ //#region ../preview-next/src/client/preview/PreviewSessionJournalHost.tsx
4466
+ /** Preview supplies its existing server refresh to the shared document-session host. */
4467
+ function PreviewSessionJournalHost(props) {
4468
+ const router = useRouter();
4469
+ return /* @__PURE__ */ jsx(SessionJournalHost, {
4470
+ ...props,
4471
+ onReplay: router.refresh
4472
+ });
4473
+ }
4474
+ //#endregion
4475
+ //#region ../preview-next/src/auth-contract.ts
4476
+ function isPreviewRuntimeSessionEditable(session) {
4477
+ return session?.kind === "userSession" && session.canEdit;
4478
+ }
4479
+ //#endregion
4480
+ //#region ../preview-next/src/client/preview/PreviewShell.tsx
4481
+ function isOverrideOnlyPreviewShell(props) {
4482
+ return props.rendering?.kind === "overrides-only";
4483
+ }
4484
+ function resolveShellLayoutProps(input) {
4485
+ const { props } = input;
4486
+ return {
4487
+ surfaceId: props.surfaceId,
4488
+ siteId: props.siteId,
4489
+ dashboardBaseUrl: props.dashboardBaseUrl ?? null,
4490
+ pageId: props.pageId,
4491
+ pageNodeType: props.pageNodeType,
4492
+ entryData: props.entryData ?? null,
4493
+ contentTypeSchema: props.contentTypeSchema,
4494
+ referenceContentTypeKeys: props.referenceContentTypeKeys ?? [],
4495
+ draftContent: props.draftContent,
4496
+ currentTemplate: props.currentTemplate,
4497
+ apiClient: input.apiClient,
4498
+ renderingOverride: props.renderingOverride,
4499
+ pageAdaptationFacts: props.pageAdaptationFacts,
4500
+ themeId: props.themeId ?? null,
4501
+ themeSelectionButtonStyleSelection: props.themeSelectionButtonStyleSelection ?? null,
4502
+ themeSelectionButtonStyleRepairs: props.themeSelectionButtonStyleRepairs ?? [],
4503
+ themeSelectionHeaderPreferences: props.themeSelectionHeaderPreferences ?? null,
4504
+ themeSelectionFooterPreferences: props.themeSelectionFooterPreferences,
4505
+ themeSelectionHeaderSelection: props.themeSelectionHeaderSelection ?? null,
4506
+ themeSelectionFooterLookId: props.themeSelectionFooterLookId ?? null,
4507
+ themeSelectionHeaderLogo: props.themeSelectionHeaderLogo,
4508
+ isSiteLaunched: props.isSiteLaunched,
4509
+ maintenanceModeEnabled: props.maintenanceModeEnabled,
4510
+ entrySubrouteContext: props.entrySubrouteContext,
4511
+ sdkConfig: props.sdkConfig ?? null,
4512
+ bookingOfferingPresets: props.bookingOfferingPresets,
4513
+ siteStyleAccess: input.siteStyleAccess
4514
+ };
4515
+ }
4516
+ function renderShellLayout(input) {
4517
+ const { props } = input;
4518
+ const layoutProps = resolveShellLayoutProps(input);
4519
+ return isOverrideOnlyPreviewShell(props) ? /* @__PURE__ */ jsx(PreviewShellLayout, {
4520
+ ...layoutProps,
4521
+ rendering: props.rendering,
4522
+ children: props.children
4523
+ }) : /* @__PURE__ */ jsx(PreviewShellLayout, {
4524
+ ...layoutProps,
4525
+ themeRuntime: props.themeRuntime ?? defaultPreviewThemeRuntime,
4526
+ children: props.children
4527
+ });
4528
+ }
4529
+ function wrapPreviewSiteFontStorage(children, siteFontStorageUrl) {
4530
+ return /* @__PURE__ */ jsx(SiteFontStorageProvider, {
4531
+ siteFontStorageUrl,
4532
+ children
4533
+ });
4534
+ }
4535
+ function PreviewEditorBody(input) {
4536
+ const { apiClient } = useEntryEditorController();
4537
+ const { props } = input;
4538
+ if (isOverrideOnlyPreviewShell(props)) return /* @__PURE__ */ jsx(PreviewEditorPage, {
4539
+ ...input,
4540
+ apiClient,
4541
+ onAcceptedChoice: () => {}
4542
+ });
4543
+ return /* @__PURE__ */ jsx(PreviewThemeJournalProvider, {
4544
+ input: props.themeInput,
4545
+ siteId: props.siteId,
4546
+ children: /* @__PURE__ */ jsx(PreviewEditorTheme, {
4547
+ ...input,
4548
+ props,
4549
+ apiClient
4550
+ })
4551
+ });
4552
+ }
4553
+ function initialChromeSelections(props) {
4554
+ return {
4555
+ buttonStyleSelection: props.themeSelectionButtonStyleSelection ?? null,
4556
+ headerSelection: props.themeSelectionHeaderSelection ?? null,
4557
+ footerLookId: props.themeSelectionFooterLookId ?? null
4558
+ };
4559
+ }
4560
+ function PreviewEditorTheme({ props, apiClient, designEditorEnabled, siteStyleAccess }) {
4561
+ const source = usePreviewThemeSource();
4562
+ const rendering = usePreviewRenderingOverride(props.renderingOverride);
4563
+ return /* @__PURE__ */ jsx(SiteChromeCustomizeProvider, {
4564
+ siteId: props.siteId,
4565
+ apiClient,
4566
+ theme: previewThemeBase(source),
4567
+ headerPreferences: props.themeSelectionHeaderPreferences ?? null,
4568
+ footerPreferences: props.themeSelectionFooterPreferences,
4569
+ themeId: props.themeId ?? null,
4570
+ selectionId: props.themeSelectionId ?? null,
4571
+ initialSelections: initialChromeSelections(props),
4572
+ headerLogoContext: props.themeSelectionHeaderLogo,
4573
+ siteStyleAccess,
4574
+ canOpenDesignEditor: props.entryData == null && props.pageId !== null && canInspectSiteStyle(siteStyleAccess),
4575
+ onAcceptedChoice: rendering.end,
4576
+ children: /* @__PURE__ */ jsx(PreviewEditorPage, {
4577
+ props: {
4578
+ ...props,
4579
+ renderingOverride: rendering.override
4580
+ },
4581
+ apiClient,
4582
+ designEditorEnabled,
4583
+ siteStyleAccess,
4584
+ onAcceptedChoice: rendering.end
4585
+ })
4586
+ });
4587
+ }
4588
+ function PreviewEditorPage({ props, apiClient, designEditorEnabled, siteStyleAccess, onAcceptedChoice }) {
4589
+ const bearerToken = usePreviewToken();
4590
+ return /* @__PURE__ */ jsx(PreviewPageDesignEditorStateProvider, {
4591
+ apiClient,
4592
+ siteId: props.siteId,
4593
+ pageId: props.pageId,
4594
+ enabled: designEditorEnabled,
4595
+ onAcceptedChoice,
4596
+ children: /* @__PURE__ */ jsxs(MediaEditorProvider, {
4597
+ siteId: props.siteId,
4598
+ apiClient,
4599
+ bearerToken,
4600
+ supabaseUrl: props.supabaseUrl,
4601
+ mediaAssets: props.mediaAssets,
4602
+ children: [/* @__PURE__ */ jsx(PreviewKeepAliveClient, { baseFetch: props.baseFetch }), wrapPreviewSiteFontStorage(renderShellLayout({
4603
+ props,
4604
+ apiClient,
4605
+ siteStyleAccess
4606
+ }), props.siteFontStorageUrl)]
4607
+ })
4608
+ });
4609
+ }
4610
+ function PreviewBlockApiProvider({ config, children }) {
4611
+ const token = usePreviewToken();
4612
+ return /* @__PURE__ */ jsx(BlockApiProvider, {
4613
+ config: useMemo(() => {
4614
+ if (!config || !token) return config;
4615
+ return {
4616
+ ...config,
4617
+ auth: config.auth.type === "bearer" ? {
4618
+ ...config.auth,
4619
+ token
4620
+ } : config.auth,
4621
+ readAuthority: config.readAuthority?.kind === "preview" ? {
4622
+ ...config.readAuthority,
4623
+ token
4624
+ } : config.readAuthority
4625
+ };
4626
+ }, [config, token]),
4627
+ children
4628
+ });
4629
+ }
4630
+ function PreviewShell(props) {
4631
+ const apiClient = useMemo(() => createGuardedPreviewApiClient(props.apiBaseUrl), [props.apiBaseUrl]);
4632
+ const access = resolveShellAccess({
4633
+ ...props,
4634
+ hideSiteStyleConfigurator: props.hideSiteStyleConfigurator ?? false
4635
+ });
4636
+ return /* @__PURE__ */ jsxs(LocationPickerEnvironmentProvider, {
4637
+ siteId: props.siteId,
4638
+ apiClient,
4639
+ tilesKey: props.previewSession?.tilesKey,
4640
+ dashboardBaseUrl: props.dashboardBaseUrl ?? props.apiBaseUrl,
4641
+ children: [/* @__PURE__ */ jsx(ToastProvider, {}), /* @__PURE__ */ jsx(PreviewQueryProvider, { children: /* @__PURE__ */ jsx(PreviewAuthInit, {
4642
+ session: props.previewSession,
4643
+ token: props.previewToken,
4644
+ siteId: props.siteId,
4645
+ siteSlug: props.siteSlug,
4646
+ pageId: props.editableId,
4647
+ children: /* @__PURE__ */ jsx(PreviewBlockApiProvider, {
4648
+ config: props.blockApiConfig,
4649
+ children: /* @__PURE__ */ jsx(PreviewEditingModeProvider, {
4650
+ siteId: props.siteId,
4651
+ children: /* @__PURE__ */ jsx(PreviewEditorMount, {
4652
+ props,
4653
+ apiClient,
4654
+ access
4655
+ })
4656
+ })
4657
+ })
4658
+ }) })]
4659
+ });
4660
+ }
4661
+ function previewJournalScope(props) {
4662
+ const nodeId = props.pageId ?? props.entryData?.id;
4663
+ return isPreviewRuntimeSessionEditable(props.previewSession) && nodeId ? {
4664
+ siteId: props.siteId,
4665
+ nodeId,
4666
+ nodeType: props.pageNodeType === "page_surface" ? "page_surface" : props.entryData ? "content_entry" : "page"
4667
+ } : null;
4668
+ }
4669
+ /** Render the preview during admission loading through the existing viewing participation. */
4670
+ function PreviewEditorMount({ props, apiClient, access }) {
4671
+ const scope = useMemo(() => previewJournalScope(props), [
4672
+ props.pageId,
4673
+ props.entryData,
4674
+ props.previewSession,
4675
+ props.pageNodeType,
4676
+ props.siteId
4677
+ ]);
4678
+ const editable = isPreviewRuntimeSessionEditable(props.previewSession);
4679
+ const ordinaryPageId = props.pageId && !props.entryData && props.pageNodeType !== "page_surface" ? props.pageId : null;
4680
+ const renderContent = (initialPageJournalState, authoringAdmitted, editorClient = null) => /* @__PURE__ */ jsx(PreviewAssistantHostProvider, {
4681
+ value: {
4682
+ siteId: props.siteId,
4683
+ pageId: ordinaryPageId,
4684
+ apiBaseUrl: props.apiBaseUrl,
4685
+ dashboardBaseUrl: props.dashboardBaseUrl,
4686
+ businessTimeZone: props.businessTimeZone,
4687
+ apiClient,
4688
+ editorClient
4689
+ },
4690
+ children: /* @__PURE__ */ jsx(PreviewEntryControllerProvider, {
4691
+ blockFieldExtensions: props.sdkConfig?.blockFieldExtensions ?? null,
4692
+ businessTimeZone: props.businessTimeZone,
4693
+ siteId: props.siteId,
4694
+ pageId: props.pageId,
4695
+ pageNodeType: props.pageNodeType,
4696
+ routeId: props.routeId,
4697
+ entryData: props.entryData,
4698
+ contentTypeSchema: props.contentTypeSchema,
4699
+ initialStatus: props.initialStatus,
4700
+ pageMetadata: props.pageMetadata,
4701
+ initialPageJournalState,
4702
+ authoringAdmitted,
4703
+ apiClient,
4704
+ subscribeToLeaseChanges: props.subscribeToLeaseChanges,
4705
+ liveDrafts: props.liveDrafts ?? void 0,
4706
+ children: /* @__PURE__ */ jsxs(PreviewAssistantSlotProvider, {
4707
+ slot: props.assistant ?? null,
4708
+ surfaceId: props.surfaceId,
4709
+ children: [
4710
+ authoringAdmitted && /* @__PURE__ */ jsx(SiteAdmissionObserver, {
4711
+ siteId: props.siteId,
4712
+ apiClient,
4713
+ siteOnly: !scope && editable,
4714
+ subscribeToAdmissionChanges: props.subscribeToAdmissionChanges
4715
+ }),
4716
+ /* @__PURE__ */ jsx(PreviewLeaseEditingMode, {}),
4717
+ /* @__PURE__ */ jsx(PreviewEditorBody, {
4718
+ props,
4719
+ ...access,
4720
+ designEditorEnabled: authoringAdmitted && access.designEditorEnabled,
4721
+ siteStyleAccess: authoringAdmitted ? access.siteStyleAccess : { kind: "hidden" }
4722
+ })
4723
+ ]
4724
+ })
4725
+ })
4726
+ });
4727
+ return /* @__PURE__ */ jsx(PreviewSessionJournalHost, {
4728
+ apiClient,
4729
+ siteId: props.siteId,
4730
+ editable,
4731
+ scope,
4732
+ pageRefreshInputs: {
4733
+ blocks: props.initialBlocks,
4734
+ metadata: props.pageMetadata
4735
+ },
4736
+ ordinaryPageId,
4737
+ fallback: renderContent(void 0, false),
4738
+ children: (initialPageJournalState, session) => renderContent(initialPageJournalState, true, session.apiClient)
4739
+ });
4740
+ }
4741
+ function defaultDesignEditorEligibility(input) {
4742
+ if (input.entryData) return { kind: "content-entry" };
4743
+ if (input.pageId) return { kind: "managed-page" };
4744
+ return { kind: "unsupported" };
4745
+ }
4746
+ function resolveShellAccess(input) {
4747
+ const eligibility = input.designEditorEligibility ?? defaultDesignEditorEligibility({
4748
+ pageId: input.pageId,
4749
+ entryData: input.entryData
4750
+ });
4751
+ return {
4752
+ designEditorEnabled: isPreviewRuntimeSessionEditable(input.previewSession) && eligibility.kind === "managed-page" && Boolean(input.pageId),
4753
+ siteStyleAccess: input.hideSiteStyleConfigurator ? { kind: "hidden" } : resolveSiteStyleAccess(input.previewSession)
4754
+ };
4755
+ }
4756
+ //#endregion
4757
+ export { dispatchLinkedEntryFieldFocusEvent as a, useLinkedSaveHandoverRetention as c, linkedEntryRenderOverlaysFromStore as d, PREVIEW_EDITABLE_OUTLINE as f, dispatchLinkedEntryEditEvent as i, applyLinkedEntryRenderOverlay as l, PreviewShellLayout as n, defaultPreviewThemeRuntime as o, dispatchBlockFieldFocusEvent as r, linkedSaveHandoversVersion as s, PreviewShell as t, applyLinkedEntryRenderOverlayToDataContext as u };