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