@hot-updater/console 1.2.0-rc.5 → 1.2.0-rc.50

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 (398) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/assets/-native-builds-search-6aptbS4G.js +1 -0
  3. package/.output/public/assets/BundleIdDisplay-C0X-k49t.js +1 -0
  4. package/.output/public/assets/ChannelPicker-DPR-7lqV.js +1 -0
  5. package/.output/public/assets/CompositeItem-UhIlCBg4.js +1 -0
  6. package/.output/public/assets/{ConsoleFeatureUnavailable-CUtcXuY2.js → ConsoleFeatureUnavailable-B3VCINom.js} +1 -1
  7. package/.output/public/assets/EventDetails-LQ8ejbsd.js +1 -0
  8. package/.output/public/assets/FoldedRows-1NvB9gAS.js +1 -0
  9. package/.output/public/assets/HashValueDisplay-DTSMSH9O.js +1 -0
  10. package/.output/public/assets/InsightsPageHeader-ypKKV3rL.js +1 -0
  11. package/.output/public/assets/IosInstall-BRuSakxm.js +1 -0
  12. package/.output/public/assets/NativeBuildsNav-ChBahvFN.js +1 -0
  13. package/.output/public/assets/{NotFoundPage-DZ3DxyRA.js → NotFoundPage-BEpesHEm.js} +1 -1
  14. package/.output/public/assets/{PlatformIcon-BBWQlWm9.js → PlatformIcon-D4KPXCHL.js} +1 -1
  15. package/.output/public/assets/QrCode-BFSCkbPj.js +1 -0
  16. package/.output/public/assets/RelativeTime-m-FKh1Jb.js +1 -0
  17. package/.output/public/assets/RolloutPercentageBadge-DF4EeZIJ.js +1 -0
  18. package/.output/public/assets/RowReason-BvIxbpPP.js +1 -0
  19. package/.output/public/assets/SandboxBadge-DPmJn40v.js +1 -0
  20. package/.output/public/assets/TargetDisplay-Ctuz3qIp.js +1 -0
  21. package/.output/public/assets/alert-dialog-DGPqJBCk.js +1 -0
  22. package/.output/public/assets/api-keys-CAVLgicI.js +1 -0
  23. package/.output/public/assets/api-keys-ztwXoKcj.js +1 -0
  24. package/.output/public/assets/api-znPyglTl.js +1 -0
  25. package/.output/public/assets/arrow-left-68S4uy4I.js +1 -0
  26. package/.output/public/assets/arrow-right-DjRwIoF1.js +1 -0
  27. package/.output/public/assets/arrow-up-right-C_1ALUCD.js +1 -0
  28. package/.output/public/assets/badge-zMibJGR5.js +1 -0
  29. package/.output/public/assets/card-BAs80yql.js +1 -0
  30. package/.output/public/assets/check-C3VCvMOV.js +1 -0
  31. package/.output/public/assets/chevron-down-BkoJHAll.js +1 -0
  32. package/.output/public/assets/chevron-right-RAuPv9r1.js +1 -0
  33. package/.output/public/assets/{circle-off-C7Muo0ss.js → circle-off-DvYMC5yF.js} +1 -1
  34. package/.output/public/assets/{clipboard-DQbOcrL7.js → clipboard-D0JWZ1KF.js} +1 -1
  35. package/.output/public/assets/{console-features-api-DEXSwFtc.js → console-features-api-CtbGqKyr.js} +1 -1
  36. package/.output/public/assets/{uuidv7-zXMtwR9Q.js → constants-yj-e3ahf.js} +1 -1
  37. package/.output/public/assets/{copy-DsuLj3oj.js → copy-BjVLMKbo.js} +1 -1
  38. package/.output/public/assets/dialog-BvZDZzdQ.js +1 -0
  39. package/.output/public/assets/dist-BEmib-ZM.js +1 -0
  40. package/.output/public/assets/{download-Cf24LBde.js → download-CgpaZb23.js} +1 -1
  41. package/.output/public/assets/empty-C5GqArX9.js +1 -0
  42. package/.output/public/assets/field-DInLQ5oV.js +1 -0
  43. package/.output/public/assets/git-branch-BGatQV8Q.js +1 -0
  44. package/.output/public/assets/history-Ci4dhphE.js +1 -0
  45. package/.output/public/assets/index-oTXLdUR-.js +10 -0
  46. package/.output/public/assets/input-group-CIjTdxCW.js +1 -0
  47. package/.output/public/assets/insights-BL6Z8zFv.js +42 -0
  48. package/.output/public/assets/insights-BMjBMtJU.js +2 -0
  49. package/.output/public/assets/insights-V3D8tYPQ.js +1 -0
  50. package/.output/public/assets/insights-api-C4Dmm34n.js +1 -0
  51. package/.output/public/assets/insights-search-B4NkHGeC.js +1 -0
  52. package/.output/public/assets/insights-usage-rpc-Dw5_pmRH.js +1 -0
  53. package/.output/public/assets/insights_.distribution-Br_CW9s9.js +2 -0
  54. package/.output/public/assets/insights_.distribution-C4E-JuVI.js +1 -0
  55. package/.output/public/assets/insights_.distribution-oIFSv2TC.js +1 -0
  56. package/.output/public/assets/installations-CcPrSZwW.js +1 -0
  57. package/.output/public/assets/installations-Cjx0648C.js +1 -0
  58. package/.output/public/assets/installations-m1v6oE-2.js +2 -0
  59. package/.output/public/assets/{key-round-DwNKkHhy.js → key-round-BkeLvA1m.js} +1 -1
  60. package/.output/public/assets/{link-DTEyW70e.js → link-CRMwpc7-.js} +2 -2
  61. package/.output/public/assets/{list--NIee1FZ.js → list-DQ9YBIDW.js} +1 -1
  62. package/.output/public/assets/loader-circle-8lunBReu.js +1 -0
  63. package/.output/public/assets/native-builds-B0zJ4wjg.js +1 -0
  64. package/.output/public/assets/native-builds-BC0sjxPC.js +2 -0
  65. package/.output/public/assets/native-builds-B_pQ4D5H.js +1 -0
  66. package/.output/public/assets/native-builds_._buildId-CSyC7YAA.js +1 -0
  67. package/.output/public/assets/native-builds_._buildId-GPlkI_2m.js +2 -0
  68. package/.output/public/assets/native-builds_.devices-Cox001IR.js +2 -0
  69. package/.output/public/assets/native-builds_.devices-DAW19hcQ.js +1 -0
  70. package/.output/public/assets/plus-DztQIXYL.js +1 -0
  71. package/.output/public/assets/{relativeTime-YQt84dYr.js → relativeTime-RUNbaMyO.js} +1 -1
  72. package/.output/public/assets/remote-config-BCQHNGRY.js +1 -0
  73. package/.output/public/assets/remote-config-BIIj0Faf.js +1 -0
  74. package/.output/public/assets/remote-config-CDlB7JK8.js +6 -0
  75. package/.output/public/assets/rotate-ccw-tITIe0Bd.js +1 -0
  76. package/.output/public/assets/{rotate-cw-Cv2aVbYr.js → rotate-cw-BFQcpUTO.js} +1 -1
  77. package/.output/public/assets/routes-C7Pv3Cfg.js +1 -0
  78. package/.output/public/assets/routes-JJGRGqsf.js +2 -0
  79. package/.output/public/assets/search-BfEqtE64.js +1 -0
  80. package/.output/public/assets/select-iSWTEY9t.js +1 -0
  81. package/.output/public/assets/sidebar-BmzmPGuv.js +3 -0
  82. package/.output/public/assets/smartphone-Dy13ukaU.js +1 -0
  83. package/.output/public/assets/styles-D5kpHu-Z.css +2 -0
  84. package/.output/public/assets/switch-ByNYRVTN.js +1 -0
  85. package/.output/public/assets/table-DbZPkzdz.js +1 -0
  86. package/.output/public/assets/tabs-Byfy8Qls.js +1 -0
  87. package/.output/public/assets/trash-2-DI0biNI-.js +1 -0
  88. package/.output/public/assets/{undo-2-CUX96_BG.js → undo-2-CxhBbgJw.js} +1 -1
  89. package/.output/public/assets/useAnchoredPopupScrollLock-Cvx6CdPD.js +1 -0
  90. package/.output/public/assets/useCompositeListItem-BEDqZ9Ni.js +1 -0
  91. package/.output/public/assets/{useMutation-DbYw7boA.js → useMutation-D7IuoOLE.js} +1 -1
  92. package/.output/public/assets/valueToPercent-Db73Kirz.js +1 -0
  93. package/.output/server/{__23tanstack-start-server-fn-resolver-BsXXRtkN.mjs → __23tanstack-start-server-fn-resolver-DY-niJR4.mjs} +94 -46
  94. package/.output/server/_chunks/ssr-renderer.mjs +2 -2
  95. package/.output/server/_libs/@base-ui/react+[...].mjs +4436 -3131
  96. package/.output/server/_libs/@tanstack/react-router+[...].mjs +1 -1
  97. package/.output/server/_libs/@tanstack/react-router-ssr-query+[...].mjs +2 -2
  98. package/.output/server/_libs/_.mjs +2 -0
  99. package/.output/server/_libs/lucide-react.mjs +50 -28
  100. package/.output/server/_libs/next-themes.mjs +1 -1
  101. package/.output/server/_libs/react-redux+[...].mjs +1 -1
  102. package/.output/server/_libs/recharts+[...].mjs +1 -1
  103. package/.output/server/_libs/sonner.mjs +1 -1
  104. package/.output/server/_libs/tanstack__react-query.mjs +1 -1
  105. package/.output/server/_ssr/-native-builds-search-D10dMZzL.mjs +62 -0
  106. package/.output/server/_ssr/{BundleIdDisplay-CFz1sCQl.mjs → BundleIdDisplay-CGdSiouM.mjs} +3 -3
  107. package/.output/server/_ssr/ChannelPicker-J5HfKxSS.mjs +251 -0
  108. package/.output/server/_ssr/{ConsoleFeatureUnavailable-CGHVL37b.mjs → ConsoleFeatureUnavailable-C52o4oew.mjs} +8 -8
  109. package/.output/server/_ssr/{EventDetails-DdJyaBZ5.mjs → EventDetails-CDLSkVNA.mjs} +9 -9
  110. package/.output/server/_ssr/FoldedRows-CrRYEVkd.mjs +152 -0
  111. package/.output/server/_ssr/HashValueDisplay-BrT2wgxk.mjs +65 -0
  112. package/.output/server/_ssr/{InsightsPageHeader-KtHEf8Q0.mjs → InsightsPageHeader-DVrudLMJ.mjs} +13 -13
  113. package/.output/server/_ssr/IosInstall-DcKlZU_q.mjs +767 -0
  114. package/.output/server/_ssr/NativeBuildsNav-BC1WIQ1W.mjs +39 -0
  115. package/.output/server/_ssr/{NotFoundPage-DZB6K98c.mjs → NotFoundPage-CEhZtcst.mjs} +3 -3
  116. package/.output/server/_ssr/{PlatformIcon-CFLiTjh1.mjs → PlatformIcon-C22qEcwo.mjs} +13 -3
  117. package/.output/server/_ssr/QrCode-Dj9BKV3l.mjs +50 -0
  118. package/.output/server/_ssr/RelativeTime-Dgbh4UPb.mjs +242 -0
  119. package/.output/server/_ssr/{git-CTA8Aqr0.mjs → RolloutPercentageBadge-BYEDUW1d.mjs} +20 -4
  120. package/.output/server/_ssr/RowReason-BweNBWkA.mjs +59 -0
  121. package/.output/server/_ssr/SandboxBadge-O8-kbXAw.mjs +85 -0
  122. package/.output/server/_ssr/TargetDisplay-D3JAXwcF.mjs +105 -0
  123. package/.output/server/_ssr/{alert-dialog-CDr-Nsoo.mjs → alert-dialog-CxEcyUb6.mjs} +4 -4
  124. package/.output/server/_ssr/{api-DGWwi1WN.mjs → api-IIqxWeDx.mjs} +186 -39
  125. package/.output/server/_ssr/{api-keys-e_eDCNr2.mjs → api-keys-CYefExfc.mjs} +2 -2
  126. package/.output/server/_ssr/{api-keys-rpc-BXiXUAm9.mjs → api-keys-rpc-qkGQ3Sp3.mjs} +4 -4
  127. package/.output/server/_ssr/{api-keys-BBb3xSox.mjs → api-keys-wFak2vKN.mjs} +14 -11
  128. package/.output/server/_ssr/{api-rpc-CLreF5Vr.mjs → api-rpc-3NKc545A.mjs} +83 -35
  129. package/.output/server/_ssr/{auth-rpc-Bbf80tQK.mjs → auth-rpc-PCSJzNJf.mjs} +5 -5
  130. package/.output/server/_ssr/{auth.server-DGwe3eds.mjs → auth.server-NGj7G3bq.mjs} +1334 -279
  131. package/.output/server/_ssr/{badge-BXk5c2yv.mjs → badge-CxSJ-pjU.mjs} +4 -45
  132. package/.output/server/_ssr/{bundleActivity-MLrjNJCT.mjs → bundleActivity-a-pEDiqu.mjs} +1 -1
  133. package/.output/server/_ssr/card-BDXDcrk_.mjs +49 -0
  134. package/.output/server/_ssr/{config.server-BIBSZpZE.mjs → config.server-CwUGPk-F.mjs} +4 -4
  135. package/.output/server/_ssr/{console-access-Cwha8dww.mjs → console-access-BOt-Xxd7.mjs} +2 -2
  136. package/.output/server/_ssr/{console-features-BTV-XuhQ.mjs → console-features-DTYyXrWO.mjs} +1 -1
  137. package/.output/server/_ssr/{console-features-api-Bk24XYA5.mjs → console-features-api-Dw_Tktev.mjs} +5 -5
  138. package/.output/server/_ssr/{console-features-rpc-5WFiUFxb.mjs → console-features-rpc-D8VFHwYj.mjs} +4 -4
  139. package/.output/server/_ssr/constants-D-2jpCiJ.mjs +11 -0
  140. package/.output/server/_ssr/{createServerRpc-BVvRVOz5.mjs → createServerRpc-DJZel12M.mjs} +1 -1
  141. package/.output/server/_ssr/{databaseConfig-B_Bg7qS5.mjs → databaseConfig-B56IJxlu.mjs} +1 -1
  142. package/.output/server/_ssr/{databaseJsonValue-kS7cvEtz.mjs → databaseJsonValue-DuUoft8j.mjs} +1 -1
  143. package/.output/server/_ssr/{databaseRows-B6H8Cmgq.mjs → databaseRows-BZMFl5QV.mjs} +3 -3
  144. package/.output/server/_ssr/deviceProfileToken-xzDLfE0T.mjs +98 -0
  145. package/.output/server/_ssr/{dialog-BG-juN_g.mjs → dialog-CJ4zMagm.mjs} +5 -5
  146. package/.output/server/_ssr/dist-CiOq3ygH.mjs +148 -0
  147. package/.output/server/_ssr/{downloadBundle-DCmr7vsj.mjs → downloadBundle-C1KOnpiF.mjs} +1 -1
  148. package/.output/server/_ssr/{empty-DF3o-H8c.mjs → empty-DYy36pwa.mjs} +3 -3
  149. package/.output/server/_ssr/{empty-plugin-adapters-zrZ0xs6n.mjs → empty-plugin-adapters-BYBYBaxo.mjs} +1 -1
  150. package/.output/server/_ssr/{failureReports-Cn_zU9S8.mjs → failureReports-BVufgM3l.mjs} +3 -3
  151. package/.output/server/_ssr/{field-5zvNofJH.mjs → field-MI8oNc5n.mjs} +3 -3
  152. package/.output/server/_ssr/foldedPage-CUjJqtlF.mjs +176 -0
  153. package/.output/server/_ssr/{getBundleChildren-rtkEEJw5.mjs → getBundleChildren-CnOf4Frp.mjs} +2 -2
  154. package/.output/server/_ssr/{input-group-rcPxMqYq.mjs → input-group-Bf7wHa21.mjs} +3 -3
  155. package/.output/server/_ssr/{insights-BwEiSUUy.mjs → insights-CKTR62Ox.mjs} +5 -5
  156. package/.output/server/_ssr/{insights-BDa6T_cj.mjs → insights-CbGG5htV.mjs} +2 -2
  157. package/.output/server/_ssr/{insights-api-BESfPrTq.mjs → insights-api-CqjIxe1A.mjs} +5 -5
  158. package/.output/server/_ssr/{insights-Din0R0k-.mjs → insights-b3XeQlzF.mjs} +62 -203
  159. package/.output/server/_ssr/{insights-errors-7BCwFybo.mjs → insights-errors-DwUaDs0Z.mjs} +2 -2
  160. package/.output/server/_ssr/{insights-failures-B9VPkzZE.mjs → insights-failures-DGO2_3Vx.mjs} +2 -2
  161. package/.output/server/_ssr/{insights-failures-rpc-BD3vjHse.mjs → insights-failures-rpc-fmWHkLhL.mjs} +11 -11
  162. package/.output/server/_ssr/{insights-recovery-BtXVU3ro.mjs → insights-recovery-Cdg3Msrj.mjs} +1 -1
  163. package/.output/server/_ssr/{insights-recovery-rpc-sVwplV7s.mjs → insights-recovery-rpc-BpwoS9XL.mjs} +7 -7
  164. package/.output/server/_ssr/{insights-rpc-BdtBheBi.mjs → insights-rpc-qwXzuBUQ.mjs} +4 -4
  165. package/.output/server/_ssr/{insights-search-BAaycSRp.mjs → insights-search-B_8PizlM.mjs} +6 -8
  166. package/.output/server/_ssr/{insights-usage-DiGnuxW8.mjs → insights-usage-BVm7CDw9.mjs} +1 -1
  167. package/.output/server/_ssr/{insights-usage-rpc-Bo5p-cuB.mjs → insights-usage-rpc-Cbg82l2g.mjs} +5 -5
  168. package/.output/server/_ssr/{insights-usage-rpc-DCkLNAlG.mjs → insights-usage-rpc-D8lgk1Sk.mjs} +7 -7
  169. package/.output/server/_ssr/{insightsUsage-ClAmoUz8.mjs → insightsUsage-lPKyRC2o.mjs} +3 -3
  170. package/.output/server/_ssr/{insights_.distribution-D4QQxZmG.mjs → insights_.distribution--XTBM-oT.mjs} +17 -16
  171. package/.output/server/_ssr/{insights_.distribution-DoO2NDvS.mjs → insights_.distribution-DTaKryjw.mjs} +2 -2
  172. package/.output/server/_ssr/{insights_.distribution-5sgau7rB.mjs → insights_.distribution-Ed2vqrwP.mjs} +5 -5
  173. package/.output/server/_ssr/{installations-W6DXZ5Tp.mjs → installations-Ce_9dNq0.mjs} +2 -2
  174. package/.output/server/_ssr/{installations-C4MwFvp6.mjs → installations-DyfuFp3L.mjs} +13 -13
  175. package/.output/server/_ssr/{installations-CZZsFoXb.mjs → installations-W8W7AYwn.mjs} +4 -4
  176. package/.output/server/_ssr/ios-devices-rpc-5kZM1bgU.mjs +149 -0
  177. package/.output/server/_ssr/iosDeviceCookie-BTfPOUhS.mjs +155 -0
  178. package/.output/server/_ssr/iosDeviceProfile-BAoo32s_.mjs +176 -0
  179. package/.output/server/_ssr/iosDevices-DuNmS3td.mjs +132 -0
  180. package/.output/server/_ssr/listReleases-QF91GLE7.mjs +94 -0
  181. package/.output/server/_ssr/{request-guard-CPdRBuGW.mjs → local-console-Dtxlsav0.mjs} +2 -9
  182. package/.output/server/_ssr/native-artifact-0tXDLTsd.mjs +1517 -0
  183. package/.output/server/_ssr/{native-builds-BhBltXq2.mjs → native-builds-1s5DIHa2.mjs} +3 -3
  184. package/.output/server/_ssr/native-builds-DEyFHKDa.mjs +696 -0
  185. package/.output/server/_ssr/native-builds-lEyKQemV.mjs +262 -0
  186. package/.output/server/_ssr/native-builds_._buildId-ElCXKaXI.mjs +1194 -0
  187. package/.output/server/_ssr/{native-builds_._buildId-B5QgMg7D.mjs → native-builds_._buildId-mJ8i0pL8.mjs} +3 -3
  188. package/.output/server/_ssr/native-builds_.devices-DNWZLCra.mjs +858 -0
  189. package/.output/server/_ssr/native-builds_.devices-Dz8b48Fo.mjs +10 -0
  190. package/.output/server/_ssr/nativeBuildDownloadLink-D8Se_CCi.mjs +96 -0
  191. package/.output/server/_ssr/nativeBuildInstall-DemC_4Zc.mjs +256 -0
  192. package/.output/server/_ssr/nativeBuilds-BFSeuC75.mjs +306 -0
  193. package/.output/server/_ssr/plistText-BORUpyEb.mjs +15 -0
  194. package/.output/server/_ssr/{plugins-RIryUNWj.mjs → plugins-D9CCkDjn.mjs} +7 -6
  195. package/.output/server/_ssr/publicConsoleBase-C3sNbafy.mjs +15 -0
  196. package/.output/server/_ssr/{release-adoption-DoAtNPED.mjs → release-adoption-gfhE5tz5.mjs} +2 -2
  197. package/.output/server/_ssr/{release-adoption-rpc-T00z1y9o.mjs → release-adoption-rpc-1mKibOdV.mjs} +9 -9
  198. package/.output/server/_ssr/{releaseAdoption-a2byXMfz.mjs → releaseAdoption-DfEYq7I4.mjs} +4 -4
  199. package/.output/server/_ssr/{releaseCatalogCompiler-DLcean2k.mjs → releaseCatalogCompiler-CuL3ptgg.mjs} +5 -4
  200. package/.output/server/_ssr/{releaseManagement-DHUux2az.mjs → releaseManagement-CqIc-SDE.mjs} +1 -1
  201. package/.output/server/_ssr/{releaseReachability-DZOK_dH-.mjs → releaseReachability-Ch1JpJkY.mjs} +2 -2
  202. package/.output/server/_ssr/{remote-config-bTCPTVky.mjs → remote-config-C_HNYPZ_.mjs} +24 -23
  203. package/.output/server/_ssr/{remote-config-Wjia3haX.mjs → remote-config-D2Cohnwn.mjs} +3 -3
  204. package/.output/server/_ssr/{remote-config-D6YMPi4J.mjs → remote-config-q9fegj-G.mjs} +2 -2
  205. package/.output/server/_ssr/{remote-config-rpc-7Zvra2dm.mjs → remote-config-rpc-6hfHFrO6.mjs} +5 -5
  206. package/.output/server/_ssr/request-guard-BPLyogIN.mjs +11 -0
  207. package/.output/server/_ssr/{router-CLK13IPD.mjs → router-DODxASKG.mjs} +137 -64
  208. package/.output/server/_ssr/{routes-CbdYptnV.mjs → routes-BJjTUNSe.mjs} +489 -474
  209. package/.output/server/_ssr/{routes-h_nOUmOr.mjs → routes-C-nYThl0.mjs} +50 -18
  210. package/.output/server/_ssr/{runtime.server-BdMY1blX.mjs → runtime.server-BUbb281Z.mjs} +4 -4
  211. package/.output/server/_ssr/{schema-ChlRtZIo.mjs → schema-CaIuQCXb.mjs} +1 -1
  212. package/.output/server/_ssr/{schema-migration-rpc-yB9ioGZE.mjs → schema-migration-rpc-C31JquTn.mjs} +5 -5
  213. package/.output/server/_ssr/{select-BdzEzz-x.mjs → select-CjACvu9s.mjs} +12 -10
  214. package/.output/server/_ssr/{server-CddZkHk2.mjs → server-Dyw2qgSR.mjs} +7 -7
  215. package/.output/server/_ssr/{sidebar-DabmjV5E.mjs → sidebar-DQkRAO_e.mjs} +17 -10
  216. package/.output/server/_ssr/ssr.mjs +1 -1
  217. package/.output/server/_ssr/{start-BvDsQehg.mjs → start-BSkL2B6C.mjs} +2 -2
  218. package/.output/server/_ssr/{switch-84dzb1yG.mjs → switch-DZJSRVl3.mjs} +4 -4
  219. package/.output/server/_ssr/{table-DP978C4F.mjs → table-BA-6GQFs.mjs} +2 -2
  220. package/.output/server/_ssr/tabs-CtB3PIts.mjs +45 -0
  221. package/.output/server/_ssr/{updateFailures-n-tGv90S.mjs → updateFailures-DcCONz23.mjs} +8 -5
  222. package/.output/server/_ssr/{dist-TEpM_UAD.mjs → uuid-kZvLA0Ly-DNL0qBSj.mjs} +2 -147
  223. package/.output/server/_ssr/{uuidv7-BIF4nb_q.mjs → uuidv7-C0jNe2Om.mjs} +2 -2
  224. package/.output/server/_ssr/{version-CQ98ZBpL-CWSkTT9J.mjs → version-CQ98ZBpL-zW2fpHOZ.mjs} +1 -1
  225. package/.output/server/_tanstack-start-manifest_v-Bfv6fYk6.mjs +229 -0
  226. package/.output/server/index.mjs +487 -375
  227. package/lib/index.d.mts +9 -0
  228. package/package.json +7 -30
  229. package/src/components/AppSidebar.tsx +11 -2
  230. package/src/components/ChannelBadge.tsx +9 -9
  231. package/src/components/ChannelPicker.tsx +227 -0
  232. package/src/components/DataTable.tsx +363 -0
  233. package/src/components/FoldedRows.tsx +219 -0
  234. package/src/components/HashValueDisplay.tsx +27 -8
  235. package/src/components/PlatformIcon.tsx +10 -0
  236. package/src/components/RelativeTime.tsx +31 -0
  237. package/src/components/RowReason.tsx +63 -0
  238. package/src/components/TargetDisplay.tsx +95 -0
  239. package/src/components/ThemeProvider.tsx +11 -2
  240. package/src/components/features/api-keys/ApiKeysPage.tsx +5 -3
  241. package/src/components/features/bundles/BundleMetadata.tsx +22 -1
  242. package/src/components/features/bundles/RolloutCohortsDialog.tsx +8 -1
  243. package/src/components/features/channels/ChannelManagementDialog.tsx +10 -11
  244. package/src/components/features/insights/AppUsage.tsx +3 -5
  245. package/src/components/features/insights/FailureReports.tsx +3 -2
  246. package/src/components/features/insights/InsightsControls.tsx +10 -69
  247. package/src/components/features/insights/InsightsOverview.tsx +7 -1
  248. package/src/components/features/insights/InsightsPageHeader.tsx +10 -15
  249. package/src/components/features/insights/ReleaseActivity.tsx +6 -2
  250. package/src/components/features/insights/ReleaseCombobox.tsx +1 -1
  251. package/src/components/features/insights/UpdateFailures.tsx +36 -10
  252. package/src/components/features/native-builds/BuiltInBundleCard.tsx +122 -61
  253. package/src/components/features/native-builds/CommitLink.tsx +3 -2
  254. package/src/components/features/native-builds/ImportBuild.tsx +1 -1
  255. package/src/components/features/native-builds/InstallCard.tsx +378 -93
  256. package/src/components/features/native-builds/IosDevicesPage.tsx +1145 -0
  257. package/src/components/features/native-builds/IosInstall.tsx +732 -0
  258. package/src/components/features/native-builds/IpaDevicesCard.tsx +123 -0
  259. package/src/components/features/native-builds/NativeBuildDetailPage.tsx +36 -9
  260. package/src/components/features/native-builds/NativeBuildsNav.tsx +45 -0
  261. package/src/components/features/native-builds/NativeBuildsPage.tsx +94 -108
  262. package/src/components/features/native-builds/NativeBuildsTable.tsx +649 -323
  263. package/src/components/features/native-builds/OlderBuildLabel.tsx +61 -0
  264. package/src/components/features/native-builds/PatchesCard.tsx +28 -19
  265. package/src/components/features/native-builds/ReleaseNativeBuildLink.tsx +5 -5
  266. package/src/components/features/native-builds/SandboxBadge.tsx +21 -0
  267. package/src/components/features/native-builds/ServedNowCard.tsx +33 -1
  268. package/src/components/features/native-builds/ShortHash.tsx +6 -3
  269. package/src/components/features/native-builds/StoreSubmission.tsx +18 -12
  270. package/src/components/features/native-builds/playTracks.ts +7 -0
  271. package/src/components/features/releases/ReleaseEditorSheet.tsx +8 -6
  272. package/src/components/features/remote-config/PublishDialog.tsx +4 -1
  273. package/src/components/features/remote-config/VersionsCard.tsx +5 -2
  274. package/src/components/ui/alert-dialog.tsx +2 -2
  275. package/src/components/ui/badge.tsx +2 -0
  276. package/src/components/ui/button.tsx +11 -2
  277. package/src/components/ui/combobox.tsx +2 -2
  278. package/src/components/ui/dialog.tsx +3 -3
  279. package/src/components/ui/input.tsx +1 -1
  280. package/src/components/ui/select.tsx +15 -7
  281. package/src/components/ui/sheet.tsx +1 -1
  282. package/src/components/ui/sidebar.tsx +2 -2
  283. package/src/components/ui/slider.tsx +1 -1
  284. package/src/components/ui/sonner.tsx +3 -1
  285. package/src/components/ui/switch.tsx +1 -1
  286. package/src/components/ui/tabs.tsx +1 -1
  287. package/src/components/ui/textarea.tsx +1 -1
  288. package/src/index.ts +9 -0
  289. package/src/lib/api-rpc.ts +125 -35
  290. package/src/lib/api.ts +171 -16
  291. package/src/lib/constants.ts +18 -0
  292. package/src/lib/insights-search.ts +0 -3
  293. package/src/lib/ios-devices-api.ts +304 -0
  294. package/src/lib/ios-devices-rpc.ts +215 -0
  295. package/src/lib/native-builds.ts +261 -20
  296. package/src/lib/schema-migration-rpc.ts +1 -1
  297. package/src/lib/server/console-runtime.server.ts +9 -2
  298. package/src/lib/server/deviceProfileToken.ts +221 -0
  299. package/src/lib/server/foldedPage.ts +360 -0
  300. package/src/lib/server/iosDeviceCookie.ts +239 -0
  301. package/src/lib/server/iosDeviceProfile.ts +232 -0
  302. package/src/lib/server/iosDevices.ts +232 -0
  303. package/src/lib/server/listReleases.ts +101 -62
  304. package/src/lib/server/local-console.ts +1 -1
  305. package/src/lib/server/nativeBuildDownloadLink.ts +193 -0
  306. package/src/lib/server/nativeBuildInstall.ts +513 -0
  307. package/src/lib/server/nativeBuilds.ts +327 -59
  308. package/src/lib/server/plistText.ts +17 -0
  309. package/src/lib/server/publicConsoleBase.ts +17 -0
  310. package/src/lib/server/updateFailures.ts +6 -1
  311. package/src/routeTree.gen.ts +129 -18
  312. package/src/routes/-native-builds-search.ts +61 -4
  313. package/src/routes/-releases-search.ts +63 -2
  314. package/src/routes/[_]hot-updater/devices/device-response.ts +21 -0
  315. package/src/routes/[_]hot-updater/devices/device[.]mobileconfig.ts +17 -0
  316. package/src/routes/[_]hot-updater/devices/receipt.ts +28 -0
  317. package/src/routes/[_]hot-updater/devices/request.ts +28 -0
  318. package/src/routes/[_]hot-updater/native-builds/$buildId/manifest[.]plist.ts +22 -0
  319. package/src/routes/api/native-builds/$buildId/download.ts +22 -1
  320. package/src/routes/index.tsx +657 -577
  321. package/src/routes/insights.tsx +3 -5
  322. package/src/routes/insights_.distribution.tsx +2 -2
  323. package/src/routes/native-builds_.devices.tsx +21 -0
  324. package/src/styles.css +24 -0
  325. package/.output/public/assets/-native-builds-search-C-TGpFAm.js +0 -1
  326. package/.output/public/assets/EventDetails-Dl2RvPAk.js +0 -1
  327. package/.output/public/assets/HashValueDisplay-6lNRxDJX.js +0 -1
  328. package/.output/public/assets/InsightsPageHeader-DHhqY3DT.js +0 -1
  329. package/.output/public/assets/RolloutPercentageBadge-Cxogpi8F.js +0 -1
  330. package/.output/public/assets/StoreSubmission-ViTkW4eJ.js +0 -1
  331. package/.output/public/assets/alert-dialog-BqYScr9y.js +0 -1
  332. package/.output/public/assets/api-P2g8dCNg.js +0 -1
  333. package/.output/public/assets/api-keys-DWQC2q6y.js +0 -1
  334. package/.output/public/assets/api-keys-FueRkF9q.js +0 -1
  335. package/.output/public/assets/arrow-left-g9cKqXuC.js +0 -1
  336. package/.output/public/assets/arrow-right-CNII8TYn.js +0 -1
  337. package/.output/public/assets/arrow-up-right-DK8Zdg40.js +0 -1
  338. package/.output/public/assets/badge-DWFcDWho.js +0 -1
  339. package/.output/public/assets/check-CXVR3s3X.js +0 -1
  340. package/.output/public/assets/chevron-right-BoUXo82O.js +0 -1
  341. package/.output/public/assets/dialog-CNUPxNxH.js +0 -1
  342. package/.output/public/assets/dist-CPlO6ko9.js +0 -1
  343. package/.output/public/assets/empty-B3Uwdd6k.js +0 -1
  344. package/.output/public/assets/field-D-2-mnNh.js +0 -1
  345. package/.output/public/assets/history-DqHlgSuV.js +0 -1
  346. package/.output/public/assets/index-CqP5HPV6.js +0 -10
  347. package/.output/public/assets/input-group-D3OUBk4n.js +0 -1
  348. package/.output/public/assets/insights-B-0odqpt.js +0 -42
  349. package/.output/public/assets/insights-BSVGfxSL.js +0 -1
  350. package/.output/public/assets/insights-NK5B6ReS.js +0 -2
  351. package/.output/public/assets/insights-api-BVCXJsoV.js +0 -1
  352. package/.output/public/assets/insights-search-DghCbEnk.js +0 -1
  353. package/.output/public/assets/insights-usage-rpc-CKQH0pUS.js +0 -1
  354. package/.output/public/assets/insights_.distribution-CJvgwcVZ.js +0 -2
  355. package/.output/public/assets/insights_.distribution-DblZM0mO.js +0 -1
  356. package/.output/public/assets/insights_.distribution-dvk6vYDM.js +0 -1
  357. package/.output/public/assets/installations-B674P5Z5.js +0 -2
  358. package/.output/public/assets/installations-BWxczZ2t.js +0 -1
  359. package/.output/public/assets/installations-Dv4kWQYz.js +0 -1
  360. package/.output/public/assets/native-builds-BOC71grI.js +0 -1
  361. package/.output/public/assets/native-builds-D6rldpSh.js +0 -2
  362. package/.output/public/assets/native-builds-DAy2678K.js +0 -1
  363. package/.output/public/assets/native-builds_._buildId-DD58_Phd.js +0 -1
  364. package/.output/public/assets/native-builds_._buildId-DvQDKnUQ.js +0 -2
  365. package/.output/public/assets/plus-BReVKct-.js +0 -1
  366. package/.output/public/assets/preload-helper-B44EvKhG.js +0 -1
  367. package/.output/public/assets/refresh-cw-B9HHjLej.js +0 -1
  368. package/.output/public/assets/remote-config-B7ujqhLa.js +0 -6
  369. package/.output/public/assets/remote-config-WjpozBG5.js +0 -1
  370. package/.output/public/assets/remote-config-gXeH6PBW.js +0 -1
  371. package/.output/public/assets/routes-BDdBIxYS.js +0 -1
  372. package/.output/public/assets/routes-CCD33Azv.js +0 -2
  373. package/.output/public/assets/search-BCel4Oy6.js +0 -1
  374. package/.output/public/assets/select-CBIU0_M1.js +0 -1
  375. package/.output/public/assets/sidebar-Di9SN47G.js +0 -3
  376. package/.output/public/assets/smartphone-CMaSy_ir.js +0 -1
  377. package/.output/public/assets/styles-uK-0vUMk.css +0 -2
  378. package/.output/public/assets/switch-BpdiHL_t.js +0 -1
  379. package/.output/public/assets/table-Bpy3SvSo.js +0 -1
  380. package/.output/public/assets/tabs-Xmt7tZeG.js +0 -1
  381. package/.output/public/assets/useCompositeListItem-JmyDfo3-.js +0 -1
  382. package/.output/public/assets/useInfiniteQuery-DX4WpBRG.js +0 -1
  383. package/.output/public/assets/valueToPercent-BLwGy_xK.js +0 -1
  384. package/.output/server/_ssr/-native-builds-search-CwNcoXf4.mjs +0 -37
  385. package/.output/server/_ssr/HashValueDisplay-B85-LoBW.mjs +0 -55
  386. package/.output/server/_ssr/RolloutPercentageBadge-CKFY5OIh.mjs +0 -21
  387. package/.output/server/_ssr/StoreSubmission-CNukW8xF.mjs +0 -139
  388. package/.output/server/_ssr/listReleases-D_GY00SQ.mjs +0 -79
  389. package/.output/server/_ssr/native-builds-CoOxssXa.mjs +0 -510
  390. package/.output/server/_ssr/native-builds-DhXL5zf_.mjs +0 -137
  391. package/.output/server/_ssr/native-builds_._buildId-CysSVBT5.mjs +0 -813
  392. package/.output/server/_ssr/nativeBuildQr-84cnFQPX.mjs +0 -59
  393. package/.output/server/_ssr/nativeBuilds-B_7BPjt_.mjs +0 -133
  394. package/.output/server/_ssr/qr-code-C7kNRIDX.mjs +0 -22
  395. package/.output/server/_ssr/tabs-kQRMEiQT.mjs +0 -45
  396. package/.output/server/_tanstack-start-manifest_v-B5nsO5L4.mjs +0 -184
  397. package/src/lib/server/nativeBuildQr.ts +0 -73
  398. package/src/routes/[_]hot-updater/native-builds/qr.ts +0 -14
@@ -1,14 +1,15 @@
1
- import { n as DatabaseBundleNotFoundError, r as DatabaseRowReferencedError } from "./databaseJsonValue-kS7cvEtz.mjs";
2
- import { O as parseReleaseCatalogScopeKey, a as RELEASE_CATALOG_FALLBACK_POLICY, c as createReleaseCatalogScopeKey, d as getAssetBaseStorageUri, f as getBundlePatch, h as getManifestStorageUri, l as decodeChannelKey, m as getManifestFileHash, r as NIL_UUID, s as canonicalizeAppVersion, u as encodeChannelKey, w as isUUIDv7 } from "./dist-TEpM_UAD.mjs";
3
- import { i as rowToBundle, n as bundleToRow, r as releaseRowToRelease, t as bundleToPatchRows } from "./databaseRows-B6H8Cmgq.mjs";
4
- import { t as ReleaseManagementError } from "./releaseManagement-DHUux2az.mjs";
5
- import { n as createUUIDv7After, t as createUUIDv7 } from "./uuidv7-BIF4nb_q.mjs";
6
- import { i as normalizeRange } from "./version-CQ98ZBpL-CWSkTT9J.mjs";
7
- import { n as projectCompiledCatalog, r as projectCompiledRollbackCatalog, t as compileReleaseCatalog } from "./releaseCatalogCompiler-DLcean2k.mjs";
8
- import { t as isRemoteDatabase } from "./databaseConfig-B_Bg7qS5.mjs";
9
- import { n as defineTable, t as defineAggregate } from "./schema-ChlRtZIo.mjs";
1
+ import { n as DatabaseBundleNotFoundError, r as DatabaseRowReferencedError } from "./databaseJsonValue-DuUoft8j.mjs";
2
+ import { a as getAssetBaseStorageUri, c as getManifestFileHash, i as RELEASE_CATALOG_FALLBACK_POLICY, l as getManifestStorageUri, n as MAX_COMPILED_CATALOG_BYTES, o as getBundlePatch } from "./dist-CiOq3ygH.mjs";
3
+ import { i as rowToBundle, n as bundleToRow, r as releaseRowToRelease, t as bundleToPatchRows } from "./databaseRows-BZMFl5QV.mjs";
4
+ import { a as decodeChannelKey, c as parseReleaseCatalogScopeKey, i as createReleaseCatalogScopeKey, o as encodeChannelKey, r as canonicalizeAppVersion, s as isUUIDv7, t as NIL_UUID } from "./uuid-kZvLA0Ly-DNL0qBSj.mjs";
5
+ import { t as ReleaseManagementError } from "./releaseManagement-CqIc-SDE.mjs";
6
+ import { n as createUUIDv7After, t as createUUIDv7 } from "./uuidv7-C0jNe2Om.mjs";
7
+ import { i as normalizeRange } from "./version-CQ98ZBpL-zW2fpHOZ.mjs";
8
+ import { i as projectCompiledRollbackCatalog, n as compileReleaseCatalog, r as projectCompiledCatalog, t as ReleaseCatalogCompilationError } from "./releaseCatalogCompiler-CuL3ptgg.mjs";
9
+ import { t as isRemoteDatabase } from "./databaseConfig-B56IJxlu.mjs";
10
+ import { n as defineTable, t as defineAggregate } from "./schema-CaIuQCXb.mjs";
10
11
  import { r as rangesIntersect } from "../_libs/verkit.mjs";
11
- //#region node_modules/.nitro/vite/services/ssr/assets/auth.server-DGwe3eds.js
12
+ //#region node_modules/.nitro/vite/services/ssr/assets/auth.server-NGj7G3bq.js
12
13
  var SHA256_FILE_HASH_RE = /^[0-9a-f]{64}$/;
13
14
  var isContentAddressedAssetFileHash = (value) => {
14
15
  return typeof value === "string" && SHA256_FILE_HASH_RE.test(value);
@@ -925,6 +926,10 @@ var releases = defineTable({
925
926
  all: {
926
927
  eq: [],
927
928
  sort: ["id"]
929
+ },
930
+ scopes: {
931
+ eq: [],
932
+ sort: ["scope_key"]
928
933
  }
929
934
  }
930
935
  });
@@ -997,7 +1002,10 @@ var channels = defineTable({
997
1002
  /**
998
1003
  * The native builds `native-build android` and `native-build ios` track, newest first
999
1004
  * in each scope: a platform, a channel, and the fingerprint or app version
1000
- * the build compiled in. `min_bundle_id` names the build's built-in bundle,
1005
+ * the build compiled in. A sandbox build's scope has no channel: its app ID,
1006
+ * URL scheme, artifact kind and distribution in its place, so pull requests
1007
+ * reuse it across channels, while `channel_id` still names the channel it
1008
+ * embeds. `min_bundle_id` names the build's built-in bundle,
1001
1009
  * a `bundles` row no release publishes. Its references keep no counters, so
1002
1010
  * adding this table changes no existing one; a channel with builds is
1003
1011
  * refused deletion through `byChannel`. `build_key` is the native build key
@@ -1007,6 +1015,27 @@ var channels = defineTable({
1007
1015
  * or `versionCode`. `submitted_to`, `submitted_at_ms` and
1008
1016
  * `submitted_version` record the store track a build went to, when, and
1009
1017
  * the store's label of the build; they stay null for a build no store took.
1018
+ * `is_store_build` is true on the build a person or a job says the store
1019
+ * sells, and false on every other: deploys patch from it over the scope's
1020
+ * newest build. The engine copies the scope key into `store_build_scope_key`
1021
+ * for that build alone, so `byStoreBuild` holds one entry per scope at most,
1022
+ * on every store, while any number of a scope's builds hold none.
1023
+ * `is_sandbox` is true on a sandbox build, set from its artifact when it
1024
+ * registers and never changed, and `sandbox_url_scheme` is the URL scheme its artifact registers,
1025
+ * which its preview links open; null on any other build, and on a sandbox
1026
+ * build registered before the column, which registered the derived one.
1027
+ * `export_method` is how an `.ipa` was exported, read from its profile when
1028
+ * it registers and never changed; null on any other artifact, on an `.ipa`
1029
+ * whose profile couldn't be read, and on one registered before the column.
1030
+ * `native_app_version` is the app version the artifact itself reports, its
1031
+ * `CFBundleShortVersionString` or `versionName`, read from the artifact when
1032
+ * it registers and never changed, whatever the update strategy; `app_version`
1033
+ * stays the version OTAs target, null on a fingerprint build. It is null
1034
+ * when the artifact's can't be read, and on a build registered before the
1035
+ * column.
1036
+ * Boolean columns follow one rule: `is_*` for a fact about the row or
1037
+ * `should_*` for an instruction to the client, never null; a unique index over
1038
+ * the rows where one is true keys a derived slot, not the boolean.
1010
1039
  */
1011
1040
  var nativeBuilds = defineTable({
1012
1041
  id: {
@@ -1083,9 +1112,32 @@ var nativeBuilds = defineTable({
1083
1112
  type: "string",
1084
1113
  maxLength: 255,
1085
1114
  required: false
1115
+ },
1116
+ is_store_build: { type: "boolean" },
1117
+ is_sandbox: { type: "boolean" },
1118
+ sandbox_url_scheme: {
1119
+ type: "string",
1120
+ maxLength: 255,
1121
+ ascii: true,
1122
+ required: false
1123
+ },
1124
+ export_method: {
1125
+ type: "string",
1126
+ maxLength: 16,
1127
+ required: false
1128
+ },
1129
+ native_app_version: {
1130
+ type: "string",
1131
+ required: false
1086
1132
  }
1087
1133
  }, {
1088
1134
  key: ["id"],
1135
+ derived: { store_build_scope_key: {
1136
+ type: "string",
1137
+ maxLength: 2048,
1138
+ ascii: true,
1139
+ compute: (row) => row.is_store_build ? row.scope_key : null
1140
+ } },
1089
1141
  indexes: {
1090
1142
  byScope: {
1091
1143
  eq: ["scope_key"],
@@ -1095,6 +1147,15 @@ var nativeBuilds = defineTable({
1095
1147
  eq: ["scope_key", "build_key"],
1096
1148
  sort: ["id"]
1097
1149
  },
1150
+ byScopeKind: {
1151
+ eq: ["scope_key", "artifact_kind"],
1152
+ sort: ["id"]
1153
+ },
1154
+ byStoreBuild: {
1155
+ eq: ["store_build_scope_key"],
1156
+ sort: [],
1157
+ unique: true
1158
+ },
1098
1159
  byChannel: {
1099
1160
  eq: ["channel_id"],
1100
1161
  sort: ["id"],
@@ -1106,6 +1167,119 @@ var nativeBuilds = defineTable({
1106
1167
  }
1107
1168
  }
1108
1169
  });
1170
+ /**
1171
+ * The iPhones a team asks to install ad hoc builds on. A row decides what the
1172
+ * CLI registers with Apple, not what an export includes: Xcode's automatic ad
1173
+ * hoc profile lists every device the Apple account has enabled. `status` is
1174
+ * `pending` until someone approves it, `approved` until a build or
1175
+ * `native-build devices add` registers it with Apple, then `registered`;
1176
+ * declining or removing one deletes its row. `udid` is the UDID in lower case.
1177
+ * `apple_issuer_id` is the App Store Connect issuer whose key registered it,
1178
+ * set once: a build signed by another account never registers these rows.
1179
+ * `apple_error` is Apple's refusal of the device, or why it stopped counting
1180
+ * it, cleared by the next success. `build_id` is the newest native build whose
1181
+ * .ipa the CLI checked lists it; deleting that build never touches the row.
1182
+ * It holds personal data: a UDID, a name, and the emails of who asked and who
1183
+ * approved, null for the CLI.
1184
+ */
1185
+ var iosDevices = defineTable({
1186
+ id: {
1187
+ type: "string",
1188
+ maxLength: 36
1189
+ },
1190
+ udid: {
1191
+ type: "string",
1192
+ maxLength: 40,
1193
+ ascii: true,
1194
+ unique: true
1195
+ },
1196
+ name: {
1197
+ type: "string",
1198
+ maxLength: 100
1199
+ },
1200
+ status: {
1201
+ type: "string",
1202
+ maxLength: 16
1203
+ },
1204
+ requested_by: {
1205
+ type: "string",
1206
+ maxLength: 320,
1207
+ required: false
1208
+ },
1209
+ created_at_ms: { type: "integer" },
1210
+ approved_by: {
1211
+ type: "string",
1212
+ maxLength: 320,
1213
+ required: false
1214
+ },
1215
+ approved_at_ms: {
1216
+ type: "integer",
1217
+ required: false
1218
+ },
1219
+ registered_at_ms: {
1220
+ type: "integer",
1221
+ required: false
1222
+ },
1223
+ apple_issuer_id: {
1224
+ type: "string",
1225
+ maxLength: 64,
1226
+ ascii: true,
1227
+ required: false
1228
+ },
1229
+ apple_error: {
1230
+ type: "string",
1231
+ maxLength: 512,
1232
+ required: false
1233
+ },
1234
+ build_id: {
1235
+ type: "string",
1236
+ maxLength: 36,
1237
+ required: false
1238
+ }
1239
+ }, {
1240
+ key: ["id"],
1241
+ indexes: {
1242
+ byStatus: {
1243
+ eq: ["status"],
1244
+ sort: ["id"]
1245
+ },
1246
+ byRegistration: {
1247
+ eq: [],
1248
+ sort: ["registered_at_ms"]
1249
+ },
1250
+ all: {
1251
+ eq: [],
1252
+ sort: ["id"]
1253
+ }
1254
+ }
1255
+ });
1256
+ /**
1257
+ * The Apple account the iOS device registry belongs to: one row, keyed
1258
+ * `registry`, holding the App Store Connect issuer that first registered a
1259
+ * device. A build claims it before it sends Apple anything, and its key makes
1260
+ * the claim atomic on every store, so two builds of two accounts can't both
1261
+ * spend a slot; another account's build then registers nothing. Removing
1262
+ * devices never releases it.
1263
+ */
1264
+ var iosDeviceAccount = defineTable({
1265
+ id: {
1266
+ type: "string",
1267
+ maxLength: 16,
1268
+ ascii: true
1269
+ },
1270
+ apple_issuer_id: {
1271
+ type: "string",
1272
+ maxLength: 64,
1273
+ ascii: true
1274
+ },
1275
+ claimed_at_ms: { type: "integer" }
1276
+ }, {
1277
+ key: ["id"],
1278
+ indexes: { all: {
1279
+ eq: [],
1280
+ sort: ["id"]
1281
+ } }
1282
+ });
1109
1283
  /** Core's module: always installed, never a plugin. */
1110
1284
  var coreModule = {
1111
1285
  id: "core",
@@ -1126,7 +1300,9 @@ var coreModule = {
1126
1300
  sort: []
1127
1301
  } }
1128
1302
  }),
1129
- native_builds: nativeBuilds
1303
+ native_builds: nativeBuilds,
1304
+ ios_devices: iosDevices,
1305
+ ios_device_account: iosDeviceAccount
1130
1306
  }
1131
1307
  };
1132
1308
  var encoder = new TextEncoder();
@@ -1286,18 +1462,17 @@ var LEASE_TABLE = "aggregate_lease";
1286
1462
  var LEASE = { id: "compaction" };
1287
1463
  /** How long a compaction holds the lease before another process may take it. */
1288
1464
  var LEASE_MS = 3e4;
1289
- /**
1290
- * Default windows: log mode compacts every 60 seconds, since reads compact
1291
- * first; memory mode flushes every 15, since its window is what a crash
1292
- * loses.
1293
- */
1294
- var WINDOW_MS = {
1295
- log: 6e4,
1296
- memory: 15e3
1297
- };
1465
+ /** A commit compacts once this has passed since the last compaction. */
1466
+ var WINDOW_MS = 6e4;
1298
1467
  /** Log rows a compaction reads from each log table for one group. */
1299
1468
  var LOG_PAGE = 200;
1300
1469
  /**
1470
+ * How old a log row this process can't apply must be before its reads step
1471
+ * past it: older than any transaction still committing, between servers
1472
+ * whose clocks agree this closely.
1473
+ */
1474
+ var SKIP_AFTER_MS = 3e5;
1475
+ /**
1301
1476
  * Groups one compaction applies: after a commit, so the request that runs
1302
1477
  * it waits for one group; before a read; and on flush.
1303
1478
  */
@@ -1308,8 +1483,6 @@ var GROUPS = {
1308
1483
  };
1309
1484
  /** Tries per write after a conflict or a transient error. */
1310
1485
  var ATTEMPTS = 5;
1311
- /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
1312
- var MAX_BUFFERED = 1e4;
1313
1486
  var log = defineTable({
1314
1487
  id: {
1315
1488
  type: "string",
@@ -1358,7 +1531,7 @@ var valuesOf = ({ deltas, sketches }) => ({
1358
1531
  /**
1359
1532
  * Merges `values` into the change for `key`'s identity as `tx.aggregate`
1360
1533
  * does: deltas add up and sketches merge. One constant `shardBy` keys each
1361
- * identity to one entry; the write picks the shard.
1534
+ * identity to one entry; `compile` writes it to shard 0.
1362
1535
  */
1363
1536
  var merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
1364
1537
  var mergeAll = (into, changes) => {
@@ -1392,7 +1565,7 @@ var increment = ({ model, deltas }, key) => Object.values(deltas).some((delta) =
1392
1565
  /**
1393
1566
  * The guarded write that merges `change` into `current`: insert, patch, or
1394
1567
  * delete at zero. Unlike a transaction's, a gauge may go below zero here: a
1395
- * shard row holds one writer's net changes, and reads sum every shard.
1568
+ * group can hold a loss without the gain before it, and reads sum every shard.
1396
1569
  */
1397
1570
  var rewrite = (change, key, current) => {
1398
1571
  const { model } = change;
@@ -1429,23 +1602,41 @@ var rewrite = (change, key, current) => {
1429
1602
  previous: current
1430
1603
  };
1431
1604
  };
1605
+ /** A shard row's place in what `readCurrent` read. */
1606
+ var rowId = (model, key) => JSON.stringify([model.table.name, key]);
1607
+ /** The shard key each change writes: shard 0, since one compaction runs at a time. */
1608
+ var keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
1432
1609
  /**
1433
- * The write for each change on its shard: a blind increment that creates
1434
- * the row for counters, and a guarded rewrite for gauges and sketches, whose
1435
- * rows are read in one batch per table.
1610
+ * The current rows of the changes that rewrite theirs (gauges and sketches),
1611
+ * each once, in one batch per table.
1436
1612
  */
1437
- var compile = async (adapter, changes, shard) => {
1438
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
1613
+ var readCurrent = async (adapter, changes) => {
1614
+ const keys = keysOf(changes);
1439
1615
  const reads = /* @__PURE__ */ new Map();
1440
1616
  changes.forEach((change, at) => {
1441
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
1617
+ if (!rewrites(change)) return;
1618
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
1619
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
1620
+ reads.set(change.model, wanted);
1442
1621
  });
1443
1622
  const current = /* @__PURE__ */ new Map();
1444
- await Promise.all([...reads].map(async ([model, positions]) => {
1445
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
1446
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
1623
+ await Promise.all([...reads].map(async ([model, wanted]) => {
1624
+ const keys = [...wanted.values()];
1625
+ const rows = await adapter.get(model.table, keys);
1626
+ keys.forEach((key, at) => {
1627
+ current.set(rowId(model, key), rows[at] ?? null);
1628
+ });
1447
1629
  }));
1448
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
1630
+ return current;
1631
+ };
1632
+ /**
1633
+ * The write for each change: a blind increment that creates the row for
1634
+ * counters, and a guarded rewrite for gauges and sketches, over the rows
1635
+ * `current` read.
1636
+ */
1637
+ var build = (changes, current) => {
1638
+ const keys = keysOf(changes);
1639
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
1449
1640
  };
1450
1641
  var isOp = (op) => op !== void 0;
1451
1642
  var sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
@@ -1489,14 +1680,13 @@ var encode = async (changes) => {
1489
1680
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
1490
1681
  };
1491
1682
  /**
1492
- * Batches changes to aggregates declared `batched`. A transaction records
1493
- * them without writing their rows; once it commits, "memory" mode keeps
1494
- * them in this process until its timer flushes them, and "log" mode has
1495
- * written them as one log row in the same atomic write, which a compaction
1496
- * later merges into the aggregates and deletes, atomically again, so each
1497
- * applies exactly once. One lease row keeps compactions one at a time.
1683
+ * Batches changes to aggregates declared `batched`. A transaction writes
1684
+ * them as one log row in its own atomic write, in place of their rows; a
1685
+ * compaction later merges log rows into the aggregates and deletes them,
1686
+ * atomically again, so each applies exactly once. One lease row keeps
1687
+ * compactions one at a time.
1498
1688
  */
1499
- var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS[mode] }, now }) => {
1689
+ var createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS }, now }) => {
1500
1690
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
1501
1691
  const holder = crypto.randomUUID().replaceAll("-", "");
1502
1692
  const table = (name) => schema.models.get(name).table;
@@ -1524,72 +1714,20 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1524
1714
  }
1525
1715
  return changes;
1526
1716
  };
1527
- /**
1528
- * Writes changes in atomic chunks within `fits`, and returns the ones it
1529
- * could not apply. A write whose outcome is unknown is dropped, never
1530
- * resent, so no change applies twice.
1531
- */
1532
- const apply = async (changes, shard) => {
1533
- let rest = changes;
1534
- let ops = [];
1535
- let read = true;
1536
- for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
1537
- if (read) ops = await compile(adapter, rest, shard);
1538
- let size = rest.length;
1539
- const chunk = () => ops.slice(0, size).filter(isOp);
1540
- while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
1541
- let result = { ok: true };
1542
- if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
1543
- warn("flush")(error);
1544
- return { ok: true };
1545
- });
1546
- read = !result.ok && !("retry" in result);
1547
- if (result.ok) {
1548
- rest = rest.slice(size);
1549
- ops = ops.slice(size);
1550
- failures = 0;
1551
- } else {
1552
- failures += 1;
1553
- if (!read) await sleep(failures);
1554
- }
1555
- } catch (error) {
1556
- warn("flush")(error);
1557
- return rest;
1558
- }
1559
- return rest;
1560
- };
1561
- let buffer = /* @__PURE__ */ new Map();
1562
- let timer;
1563
- let flushing;
1564
- const shards = /* @__PURE__ */ new Map();
1565
- /** Each process writes its own shard, so flushes of two processes rarely meet. */
1566
- const processShard = (model) => {
1567
- if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
1568
- return shards.get(model);
1569
- };
1570
- const schedule = () => {
1571
- if (timer !== void 0 || buffer.size === 0) return;
1572
- timer = setTimeout(() => {
1573
- timer = void 0;
1574
- flushBuffer();
1575
- }, windowMs);
1576
- timer.unref?.();
1577
- };
1578
- /** Never rejects: what it cannot apply goes back into the buffer. */
1579
- const flushBuffer = () => flushing ??= (async () => {
1580
- clearTimeout(timer);
1581
- timer = void 0;
1582
- const pending = [...buffer.values()];
1583
- buffer = /* @__PURE__ */ new Map();
1584
- mergeAll(buffer, await apply(pending, processShard));
1585
- })().catch(warn("flush")).finally(() => {
1586
- flushing = void 0;
1587
- schedule();
1588
- });
1589
1717
  let nextDue = 0;
1590
1718
  let compacting;
1591
1719
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
1592
1720
  const known = /* @__PURE__ */ new Map();
1721
+ /**
1722
+ * Each log table's last row of a run at its head that this process can't
1723
+ * apply (it names an aggregate or metric this schema lacks), whose reads
1724
+ * start past it. The rows wait for a process that can apply them, and a
1725
+ * restart reads them again.
1726
+ */
1727
+ const skipped = LOG_TABLES.map(() => void 0);
1728
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
1729
+ /** When a log row's transaction stamped its ID. */
1730
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
1593
1731
  const idOf = (shard, id) => JSON.stringify([shard, id]);
1594
1732
  /** The lease row as stored once `set` is written over it. */
1595
1733
  const leaseOp = (held, set) => {
@@ -1705,14 +1843,22 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1705
1843
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
1706
1844
  const page = await engine.reads.findMany(name, {
1707
1845
  index: "oldest",
1708
- limit: LOG_PAGE
1846
+ limit: LOG_PAGE,
1847
+ ...past(shard)
1709
1848
  });
1710
1849
  more ||= page.next !== void 0;
1711
- return (await Promise.all(page.rows.map(async (row) => ({
1850
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
1712
1851
  shard,
1713
1852
  row,
1714
1853
  changes: await decode(String(row.changes))
1715
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
1854
+ })));
1855
+ const settled = now() - SKIP_AFTER_MS;
1856
+ for (const { row, changes } of decoded) {
1857
+ const id = String(row.id);
1858
+ if (changes !== void 0 || stampOf(id) >= settled) break;
1859
+ skipped[shard] = id;
1860
+ }
1861
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
1716
1862
  ...entry,
1717
1863
  changes
1718
1864
  }]);
@@ -1720,7 +1866,6 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1720
1866
  more
1721
1867
  };
1722
1868
  };
1723
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
1724
1869
  /**
1725
1870
  * Applies the oldest pending log rows whose merged changes fit in one
1726
1871
  * atomic write with the lease, which lists them as applied; the rows are
@@ -1729,12 +1874,14 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1729
1874
  * log rows it applied whole, or undefined when a conflict stopped it.
1730
1875
  */
1731
1876
  const applyGroup = async (held, logs) => {
1877
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
1878
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
1732
1879
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
1733
1880
  const batch = logs.slice(0, count);
1734
1881
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
1735
1882
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
1736
1883
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
1737
- const ops = [...await rowsFor([...changes.values()]), lease.op];
1884
+ const ops = [...rowsFor([...changes.values()]), lease.op];
1738
1885
  if (!adapter.fits(ops)) continue;
1739
1886
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
1740
1887
  return await commit(ops) ? {
@@ -1756,7 +1903,7 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1756
1903
  };
1757
1904
  const lease = leaseOp(held, {});
1758
1905
  const ops = [
1759
- ...await rowsFor(entries.slice(0, take)),
1906
+ ...rowsFor(entries.slice(0, take)),
1760
1907
  kept,
1761
1908
  lease.op
1762
1909
  ];
@@ -1777,11 +1924,12 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1777
1924
  if (held === void 0) return;
1778
1925
  let pending = true;
1779
1926
  let clear = false;
1927
+ let carried;
1780
1928
  try {
1781
1929
  for (let group = 0;; group += 1) {
1782
1930
  clear = await deleteApplied(held);
1783
1931
  if (!clear || !pending || group === groups) break;
1784
- const { logs, more } = await readLogs();
1932
+ const { logs, more } = carried ?? await readLogs();
1785
1933
  if (logs.length === 0) {
1786
1934
  pending = false;
1787
1935
  break;
@@ -1789,6 +1937,11 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1789
1937
  const applied = await applyGroup(held, logs);
1790
1938
  if (applied === void 0) break;
1791
1939
  [held, clear] = [applied.held, false];
1940
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
1941
+ carried = rest.length > 0 ? {
1942
+ logs: rest,
1943
+ more
1944
+ } : void 0;
1792
1945
  pending = more || applied.count < logs.length;
1793
1946
  }
1794
1947
  } finally {
@@ -1808,26 +1961,13 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1808
1961
  });
1809
1962
  let checking;
1810
1963
  /** Whether any log row waits; reads at once share one check. */
1811
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
1964
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
1812
1965
  index: "oldest",
1813
- limit: 1
1966
+ limit: 1,
1967
+ ...past(shard)
1814
1968
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
1815
1969
  checking = void 0;
1816
1970
  });
1817
- /** Takes a committed transaction's changes; never rejects, since the transaction already committed. */
1818
- const committed = async (changes) => {
1819
- if (mode === "log") {
1820
- if (now() >= nextDue) await compact(false, GROUPS.commit);
1821
- return;
1822
- }
1823
- mergeAll(buffer, changes.values());
1824
- schedule();
1825
- if (buffer.size >= MAX_BUFFERED) await flushBuffer();
1826
- };
1827
- const flush = async () => {
1828
- await flushBuffer();
1829
- if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
1830
- };
1831
1971
  return {
1832
1972
  async transaction(fn) {
1833
1973
  let changes = /* @__PURE__ */ new Map();
@@ -1853,7 +1993,7 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1853
1993
  aggregate
1854
1994
  });
1855
1995
  if (failure) throw failure.error;
1856
- if (mode === "log" && attempt.size > 0) {
1996
+ if (attempt.size > 0) {
1857
1997
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
1858
1998
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
1859
1999
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -1867,24 +2007,18 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1867
2007
  open = false;
1868
2008
  }
1869
2009
  });
1870
- if (changes.size > 0) await committed(changes);
2010
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
1871
2011
  return result;
1872
2012
  },
1873
2013
  async beforeRead(name) {
1874
2014
  if (!isBatched(schema.models.get(name))) return;
1875
- if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
1876
- if (mode === "log") {
1877
- if (await hasPending().catch((error) => {
1878
- warn("read")(error);
1879
- return false;
1880
- })) await compact(true, GROUPS.read);
1881
- }
2015
+ if (await hasPending().catch((error) => {
2016
+ warn("read")(error);
2017
+ return false;
2018
+ })) await compact(true, GROUPS.read);
1882
2019
  },
1883
- flush,
1884
- async dispose() {
1885
- clearTimeout(timer);
1886
- timer = void 0;
1887
- await flush();
2020
+ async flush() {
2021
+ if (await hasPending()) await compact(true, GROUPS.flush);
1888
2022
  }
1889
2023
  };
1890
2024
  };
@@ -2022,7 +2156,8 @@ var fieldProblems = (definition, add) => {
2022
2156
  else if (field.required === false) add(`key field "${name}" is nullable`);
2023
2157
  else if (field.type === "json") add(`key field "${name}" is json`);
2024
2158
  }
2025
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
2159
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
2160
+ for (const [name, { type, maxLength, ascii }] of bounded) {
2026
2161
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
2027
2162
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
2028
2163
  }
@@ -2139,11 +2274,13 @@ var resolveSchema = (modules) => {
2139
2274
  ...maxLength === void 0 ? {} : { maxLength },
2140
2275
  ...ascii ? { ascii } : {}
2141
2276
  }));
2142
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
2277
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
2143
2278
  name: field,
2144
2279
  type,
2145
2280
  nullable: true,
2146
- ...multi ? { multi } : {}
2281
+ ...multi ? { multi } : {},
2282
+ ...maxLength === void 0 ? {} : { maxLength },
2283
+ ...ascii ? { ascii } : {}
2147
2284
  });
2148
2285
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
2149
2286
  name: metric,
@@ -2186,6 +2323,12 @@ var pluginModule = ({ id, schema, namespace }) => ({
2186
2323
  /** A row this attempt read changed while it ran; the attempt reruns. */
2187
2324
  var StaleReadError = class extends Error {};
2188
2325
  var idOf = (table, key) => JSON.stringify([table, key]);
2326
+ /** The aggregate rows a write changes, at the versions it read them. */
2327
+ var versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
2328
+ op.table.name,
2329
+ op.key,
2330
+ "guard" in op ? op.guard?.v : void 0
2331
+ ]));
2189
2332
  var versionOf = (row) => Number(row["_v"]);
2190
2333
  var isKeyed = (value) => value !== null && value !== void 0;
2191
2334
  var misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -2528,7 +2671,9 @@ var createTransactions = ({ adapter, schema, reads, retry = {} }) => {
2528
2671
  assertOutsideTransaction();
2529
2672
  let run;
2530
2673
  let negative;
2531
- for (let round = 0; round < attempts; round += 1) {
2674
+ let failures = 0;
2675
+ let lost;
2676
+ for (let round = 0;; round += 1) {
2532
2677
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
2533
2678
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
2534
2679
  run ??= await attempt(fn).catch((error) => {
@@ -2537,6 +2682,8 @@ var createTransactions = ({ adapter, schema, reads, retry = {} }) => {
2537
2682
  });
2538
2683
  if (run === void 0) {
2539
2684
  onRetry?.("rerun", round + 1);
2685
+ lost = void 0;
2686
+ if ((failures += 1) >= attempts) break;
2540
2687
  continue;
2541
2688
  }
2542
2689
  let aggregates;
@@ -2547,8 +2694,14 @@ var createTransactions = ({ adapter, schema, reads, retry = {} }) => {
2547
2694
  negative = error;
2548
2695
  onRetry?.("rerun", round + 1);
2549
2696
  run = void 0;
2697
+ lost = void 0;
2698
+ if ((failures += 1) >= attempts) break;
2550
2699
  continue;
2551
2700
  }
2701
+ const versions = versionsOf(aggregates);
2702
+ if (lost !== void 0 && versions !== lost) failures -= 1;
2703
+ lost = void 0;
2704
+ if (failures >= attempts) break;
2552
2705
  const ops = [...run.ops, ...aggregates];
2553
2706
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
2554
2707
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -2562,12 +2715,16 @@ var createTransactions = ({ adapter, schema, reads, retry = {} }) => {
2562
2715
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
2563
2716
  if (failed === void 0 || failed >= run.ops.length) {
2564
2717
  onRetry?.("resend", round + 1);
2718
+ failures += 1;
2719
+ if (failed !== void 0) lost = versions;
2720
+ else if (failures >= attempts) break;
2565
2721
  continue;
2566
2722
  }
2567
2723
  const reason = await classify(ops[failed], run.read);
2568
2724
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
2569
2725
  onRetry?.("rerun", round + 1);
2570
2726
  run = void 0;
2727
+ if ((failures += 1) >= attempts) break;
2571
2728
  }
2572
2729
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
2573
2730
  } };
@@ -2801,9 +2958,6 @@ var createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =>
2801
2958
  flush: async () => {
2802
2959
  await batches?.flush();
2803
2960
  },
2804
- dispose: async () => {
2805
- await batches?.dispose();
2806
- },
2807
2961
  database(module) {
2808
2962
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
2809
2963
  return {
@@ -2882,11 +3036,10 @@ var createEngine = (database, { plugins = [], now = Date.now } = {}) => {
2882
3036
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
2883
3037
  return engine.database(module);
2884
3038
  },
2885
- flush: () => engine.flush(),
2886
- dispose: () => engine.dispose()
3039
+ flush: () => engine.flush()
2887
3040
  };
2888
3041
  };
2889
- var HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.5";
3042
+ var HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.50";
2890
3043
  /**
2891
3044
  * `/version` on both mounts. The admin mount also lists the ids of the
2892
3045
  * plugins the server runs, sorted; apps never learn which plugins a server
@@ -3038,10 +3191,15 @@ var releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? cre
3038
3191
  platform: input.platform,
3039
3192
  strategy: "FINGERPRINT"
3040
3193
  });
3041
- /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
3042
- var projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
3043
- if (row === null || row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
3044
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
3194
+ var parseReleaseCatalogRow = ({ payload, ...row }) => ({
3195
+ row,
3196
+ compiled: parseCompiledCatalog(payload, row.strategy)
3197
+ });
3198
+ /** Projects a parsed catalog row for one update check; null when the row is not this scope's. */
3199
+ var projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
3200
+ if (parsed === null) return null;
3201
+ const { row, compiled } = parsed;
3202
+ if (row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
3045
3203
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
3046
3204
  return {
3047
3205
  catalogId: row.catalog_id,
@@ -3054,6 +3212,8 @@ var projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(
3054
3212
  scopeKey
3055
3213
  };
3056
3214
  };
3215
+ /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
3216
+ var projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
3057
3217
  var HBC_ASSET_PATH_RE = /\.bundle$/;
3058
3218
  var asByteSize = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
3059
3219
  var resolveUniqueHbcAssetPath = (manifest) => {
@@ -3321,8 +3481,8 @@ var baseBundleIdsOf = (row, range, bundleId, limit) => {
3321
3481
  return ids;
3322
3482
  };
3323
3483
  var PAGE$2 = 500;
3324
- var pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
3325
- var toBundleRow = pick$1([
3484
+ var pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
3485
+ var toBundleRow = pick$2([
3326
3486
  "id",
3327
3487
  "platform",
3328
3488
  "git_commit_hash",
@@ -3331,7 +3491,7 @@ var toBundleRow = pick$1([
3331
3491
  "manifest_file_hash",
3332
3492
  "asset_base_storage_uri"
3333
3493
  ]);
3334
- var toPatchRow = pick$1([
3494
+ var toPatchRow = pick$2([
3335
3495
  "id",
3336
3496
  "bundle_id",
3337
3497
  "base_bundle_id",
@@ -3341,7 +3501,7 @@ var toPatchRow = pick$1([
3341
3501
  "byte_size",
3342
3502
  "order_index"
3343
3503
  ]);
3344
- var toReleaseRow = pick$1([
3504
+ var toReleaseRow = pick$2([
3345
3505
  "id",
3346
3506
  "revision",
3347
3507
  "scope_key",
@@ -3362,7 +3522,7 @@ var toReleaseRow = pick$1([
3362
3522
  "created_at_ms",
3363
3523
  "updated_at_ms"
3364
3524
  ]);
3365
- var toCatalogRow = pick$1([
3525
+ var toCatalogRow = pick$2([
3366
3526
  "scope_key",
3367
3527
  "catalog_id",
3368
3528
  "strategy",
@@ -3377,7 +3537,7 @@ var toCatalogRow = pick$1([
3377
3537
  "is_tombstone",
3378
3538
  "updated_at_ms"
3379
3539
  ]);
3380
- var toChannelRow = pick$1(["id", "name"]);
3540
+ var toChannelRow = pick$2(["id", "name"]);
3381
3541
  /** Every page of one read, in order. */
3382
3542
  var drain = async (read) => {
3383
3543
  const rows = [];
@@ -3390,8 +3550,16 @@ var drain = async (read) => {
3390
3550
  return rows;
3391
3551
  };
3392
3552
  /** A keyset page's range: the keys strictly after `after`, in `order`. */
3393
- var after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
3394
- /** Core's reads, each through one declared index or key. */
3553
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
3554
+ var after = (input) => {
3555
+ const asc = (input.order ?? "asc") === "asc";
3556
+ const range = {
3557
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
3558
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
3559
+ };
3560
+ return Object.keys(range).length === 0 ? {} : { range };
3561
+ };
3562
+ /** Core's reads, each through one declared index or key; plugins get `CoreReads`. */
3395
3563
  var createCoreReads = (db, storage) => {
3396
3564
  /** A bundle row's patches, exactly as many as its reference counter holds. */
3397
3565
  const detail = async (row) => {
@@ -3568,7 +3736,29 @@ var createCoreReads = (db, storage) => {
3568
3736
  ...after(input)
3569
3737
  })).rows.map(toCatalogRow);
3570
3738
  },
3571
- async listChannels() {
3739
+ async listReleaseScopeKeys(input) {
3740
+ const scopeKeys = [];
3741
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
3742
+ const { rows } = await db.findMany("releases", {
3743
+ index: "scopes",
3744
+ where: {},
3745
+ limit: 1,
3746
+ range: { gt: last }
3747
+ });
3748
+ if (rows[0] === void 0) break;
3749
+ last = rows[0].scope_key;
3750
+ scopeKeys.push(last);
3751
+ }
3752
+ return scopeKeys;
3753
+ },
3754
+ async listChannels(input) {
3755
+ if (input !== void 0) return (await db.findMany("channels", {
3756
+ index: "all",
3757
+ where: {},
3758
+ order: input.order ?? "asc",
3759
+ limit: input.limit,
3760
+ ...after(input)
3761
+ })).rows.map(toChannelRow);
3572
3762
  return (await drain((page) => db.findMany("channels", {
3573
3763
  index: "all",
3574
3764
  where: {},
@@ -3576,12 +3766,325 @@ var createCoreReads = (db, storage) => {
3576
3766
  ...page
3577
3767
  }))).map(toChannelRow);
3578
3768
  },
3769
+ async getChannels(ids) {
3770
+ const unique = [...new Set(ids)];
3771
+ if (unique.length === 0) return [];
3772
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
3773
+ },
3579
3774
  async findChannelByName(name) {
3580
3775
  const row = await db.findOne("channels", { name });
3581
3776
  return row === null ? null : toChannelRow(row);
3582
3777
  }
3583
3778
  };
3584
3779
  };
3780
+ /**
3781
+ * A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. The same
3782
+ * rule as `normalizeIosUdid` of `@hot-updater/protocol/native-artifact`,
3783
+ * implemented here so the server's runtime never loads the artifact readers.
3784
+ */
3785
+ var UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
3786
+ /** The form the registry stores and compares a UDID in, or null for text that isn't one. */
3787
+ var normalizeIosUdid = (value) => {
3788
+ const trimmed = value.trim();
3789
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
3790
+ };
3791
+ /** `ios_devices.name`'s bound in core's schema. */
3792
+ var NAME_MAX_LENGTH = 100;
3793
+ /** `ios_devices.requested_by` and `approved_by`'s bound: an email address. */
3794
+ var EMAIL_MAX_LENGTH = 320;
3795
+ /** `ios_devices.apple_issuer_id`'s bound. */
3796
+ var ISSUER_MAX_LENGTH = 64;
3797
+ /** The one row of `ios_device_account`. */
3798
+ var ACCOUNT_ROW = "registry";
3799
+ /** `ios_devices.apple_error`'s bound. */
3800
+ var ERROR_MAX_LENGTH = 512;
3801
+ var STATUSES = [
3802
+ "pending",
3803
+ "approved",
3804
+ "registered"
3805
+ ];
3806
+ var OUTCOMES = [
3807
+ "registered",
3808
+ "refused",
3809
+ "disabled",
3810
+ "missing"
3811
+ ];
3812
+ /** The `apple_error` of a device Apple has disabled. */
3813
+ var IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
3814
+ /** The `apple_error` of a registered device Apple no longer lists. */
3815
+ var IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
3816
+ /** A device or registry request core cannot store: the caller's input. */
3817
+ var IosDeviceInputError = class extends TypeError {
3818
+ name = "IosDeviceInputError";
3819
+ };
3820
+ var pick$1 = (row) => ({
3821
+ id: row.id,
3822
+ udid: row.udid,
3823
+ name: row.name,
3824
+ status: row.status,
3825
+ requested_by: row.requested_by ?? null,
3826
+ created_at_ms: row.created_at_ms,
3827
+ approved_by: row.approved_by ?? null,
3828
+ approved_at_ms: row.approved_at_ms ?? null,
3829
+ registered_at_ms: row.registered_at_ms ?? null,
3830
+ apple_issuer_id: row.apple_issuer_id ?? null,
3831
+ apple_error: row.apple_error ?? null,
3832
+ build_id: row.build_id ?? null
3833
+ });
3834
+ var udidOf = (udid) => {
3835
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
3836
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
3837
+ return key;
3838
+ };
3839
+ var nameOf = (name) => {
3840
+ const trimmed = typeof name === "string" ? name.trim() : "";
3841
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
3842
+ return trimmed;
3843
+ };
3844
+ /** An email, lower-cased, or null for the CLI. */
3845
+ var personOf = (value, field) => {
3846
+ if (value === null) return null;
3847
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
3848
+ if (email.length === 0 || email.length > EMAIL_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: ${field} must be an email of at most ${EMAIL_MAX_LENGTH} characters, or null.`);
3849
+ return email;
3850
+ };
3851
+ /** Apple's words, on one line and within the column's bound. */
3852
+ var errorText = (text) => {
3853
+ const line = text.replace(/\s+/gu, " ").trim();
3854
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
3855
+ };
3856
+ /**
3857
+ * The iOS device registry: the iPhones and iPads a team asked to install ad hoc
3858
+ * builds on. The Console writes requests and approvals, and the CLI what Apple
3859
+ * said, each over the row it read.
3860
+ */
3861
+ var createIosDeviceApi = (db, { now = Date.now } = {}) => {
3862
+ const findIosDevice = async (udid) => {
3863
+ const key = normalizeIosUdid(udid);
3864
+ if (key === null) return null;
3865
+ const row = await db.findOne("ios_devices", { udid: key });
3866
+ return row === null ? null : pick$1(row);
3867
+ };
3868
+ /**
3869
+ * The issuer of the registry's earliest registration among its rows, by
3870
+ * when and then by ID, or null when no row names one: read only while the
3871
+ * registry has no account yet, in one read of its first registration. A
3872
+ * row names an issuer exactly when it has a registration time: both are
3873
+ * set by its first registration and never cleared.
3874
+ */
3875
+ const accountOfRows = async () => {
3876
+ const { rows } = await db.findMany("ios_devices", {
3877
+ index: "byRegistration",
3878
+ where: {},
3879
+ order: "asc",
3880
+ limit: 1,
3881
+ range: { gte: 0 }
3882
+ });
3883
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
3884
+ };
3885
+ return {
3886
+ async listIosDevices(input) {
3887
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
3888
+ const page = {
3889
+ order: input.order ?? "asc",
3890
+ limit: input.limit,
3891
+ ...after(input)
3892
+ };
3893
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
3894
+ index: "all",
3895
+ where: {},
3896
+ ...page
3897
+ }) : await db.findMany("ios_devices", {
3898
+ index: "byStatus",
3899
+ where: { status: input.status },
3900
+ ...page
3901
+ });
3902
+ return rows.map(pick$1);
3903
+ },
3904
+ findIosDevice,
3905
+ async requestIosDevice(input) {
3906
+ const udid = udidOf(input.udid);
3907
+ const name = nameOf(input.name);
3908
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
3909
+ const existing = await db.findOne("ios_devices", { udid });
3910
+ if (existing !== null) return {
3911
+ device: pick$1(existing),
3912
+ created: false
3913
+ };
3914
+ const device = {
3915
+ id: createUUIDv7(),
3916
+ udid,
3917
+ name,
3918
+ status: "pending",
3919
+ requested_by: requestedBy,
3920
+ created_at_ms: now(),
3921
+ approved_by: null,
3922
+ approved_at_ms: null,
3923
+ registered_at_ms: null,
3924
+ apple_issuer_id: null,
3925
+ apple_error: null,
3926
+ build_id: null
3927
+ };
3928
+ try {
3929
+ await db.transaction(async (tx) => {
3930
+ tx.create("ios_devices", device);
3931
+ });
3932
+ } catch (error) {
3933
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
3934
+ const winner = await db.findOne("ios_devices", { udid });
3935
+ if (winner !== null) return {
3936
+ device: pick$1(winner),
3937
+ created: false
3938
+ };
3939
+ }
3940
+ throw error;
3941
+ }
3942
+ return {
3943
+ device,
3944
+ created: true
3945
+ };
3946
+ },
3947
+ async approveIosDevice(id, input) {
3948
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
3949
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
3950
+ return db.transaction(async (tx) => {
3951
+ const row = await tx.findOne("ios_devices", { id });
3952
+ if (row === null) return null;
3953
+ const device = pick$1(row);
3954
+ const set = {
3955
+ ...name === void 0 || name === device.name ? {} : { name },
3956
+ ...device.status === "pending" ? {
3957
+ status: "approved",
3958
+ approved_by: approvedBy,
3959
+ approved_at_ms: now()
3960
+ } : {}
3961
+ };
3962
+ if (Object.keys(set).length === 0) return device;
3963
+ tx.update("ios_devices", row, set);
3964
+ return {
3965
+ ...device,
3966
+ ...set
3967
+ };
3968
+ });
3969
+ },
3970
+ async renameIosDevice(id, input) {
3971
+ const name = nameOf(input);
3972
+ return db.transaction(async (tx) => {
3973
+ const row = await tx.findOne("ios_devices", { id });
3974
+ if (row === null) return null;
3975
+ const device = pick$1(row);
3976
+ if (device.name === name) return device;
3977
+ tx.update("ios_devices", row, { name });
3978
+ return {
3979
+ ...device,
3980
+ name
3981
+ };
3982
+ });
3983
+ },
3984
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
3985
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
3986
+ if (typeof issuerId !== "string" || issuerId.trim().length === 0 || issuerId.length > ISSUER_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device outcome: issuerId must be an App Store Connect issuer of at most ${ISSUER_MAX_LENGTH} characters.`);
3987
+ return db.transaction(async (tx) => {
3988
+ const row = await tx.findOne("ios_devices", { id });
3989
+ if (row === null) return null;
3990
+ const device = pick$1(row);
3991
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
3992
+ let set;
3993
+ switch (outcome) {
3994
+ case "registered":
3995
+ if (device.status === "pending") return null;
3996
+ set = {
3997
+ status: "registered",
3998
+ registered_at_ms: device.registered_at_ms ?? now(),
3999
+ apple_issuer_id: issuerId,
4000
+ apple_error: null
4001
+ };
4002
+ break;
4003
+ case "refused":
4004
+ if (device.status !== "approved") return null;
4005
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
4006
+ break;
4007
+ case "disabled":
4008
+ if (device.status === "pending") return null;
4009
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
4010
+ break;
4011
+ case "missing":
4012
+ if (device.status !== "registered") return null;
4013
+ set = {
4014
+ status: "pending",
4015
+ approved_by: null,
4016
+ approved_at_ms: null,
4017
+ apple_error: IOS_DEVICE_MISSING_ERROR
4018
+ };
4019
+ }
4020
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
4021
+ return {
4022
+ ...device,
4023
+ ...set
4024
+ };
4025
+ });
4026
+ },
4027
+ async markIosDevicesInBuild({ buildId, ids }) {
4028
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
4029
+ const row = await tx.findOne("ios_devices", { id });
4030
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
4031
+ tx.update("ios_devices", row, { build_id: buildId });
4032
+ });
4033
+ },
4034
+ async findIosDeviceAccount() {
4035
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
4036
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
4037
+ return issuerId === null ? null : { issuerId };
4038
+ },
4039
+ async claimIosDeviceAccount(issuerId) {
4040
+ if (typeof issuerId !== "string" || issuerId.trim().length === 0 || issuerId.length > ISSUER_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device account: issuerId must be an App Store Connect issuer of at most ${ISSUER_MAX_LENGTH} characters.`);
4041
+ const answer = (held) => ({
4042
+ issuerId: held,
4043
+ claimed: held === issuerId
4044
+ });
4045
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
4046
+ if (existing !== null) return answer(existing.apple_issuer_id);
4047
+ const holder = await accountOfRows() ?? issuerId;
4048
+ try {
4049
+ await db.transaction(async (tx) => {
4050
+ tx.create("ios_device_account", {
4051
+ id: ACCOUNT_ROW,
4052
+ apple_issuer_id: holder,
4053
+ claimed_at_ms: now()
4054
+ });
4055
+ });
4056
+ return answer(holder);
4057
+ } catch (error) {
4058
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
4059
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
4060
+ if (winner !== null) return answer(winner.apple_issuer_id);
4061
+ }
4062
+ throw error;
4063
+ }
4064
+ },
4065
+ async deleteIosDevice(id, only) {
4066
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
4067
+ return db.transaction(async (tx) => {
4068
+ const row = await tx.findOne("ios_devices", { id });
4069
+ if (row === null) return null;
4070
+ const device = pick$1(row);
4071
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
4072
+ await tx.delete("ios_devices", row);
4073
+ return device;
4074
+ });
4075
+ }
4076
+ };
4077
+ };
4078
+ /** Store destinations accepted for each native platform. */
4079
+ var NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
4080
+ android: [
4081
+ "play-internal",
4082
+ "play-closed",
4083
+ "play-open",
4084
+ "play-production"
4085
+ ],
4086
+ ios: ["testflight"]
4087
+ };
3585
4088
  var PAGE$1 = 500;
3586
4089
  /** Moves one bundle into or out of its platform's total and the overall total. */
3587
4090
  var countBundle = (tx, platform, delta) => {
@@ -3610,8 +4113,10 @@ var deleteBundle = async (tx, current) => {
3610
4113
  /**
3611
4114
  * Replaces a bundle's patches with `rows`: kept patches are updated where
3612
4115
  * they changed, others deleted or created, so no key is written twice.
4116
+ * `checkNew` sees each patch it is about to create, and refuses one by
4117
+ * throwing, which leaves the transaction's writes undone.
3613
4118
  */
3614
- var replaceBundlePatches = async (tx, bundle, rows) => {
4119
+ var replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
3615
4120
  const wanted = new Map(rows.map((row) => [row.id, row]));
3616
4121
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
3617
4122
  let cursor;
@@ -3636,6 +4141,7 @@ var replaceBundlePatches = async (tx, bundle, rows) => {
3636
4141
  if (page.next === void 0) break;
3637
4142
  cursor = page.next;
3638
4143
  }
4144
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
3639
4145
  for (const row of wanted.values()) tx.create("bundle_patches", row);
3640
4146
  };
3641
4147
  /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
@@ -3696,6 +4202,27 @@ var GIT_COMMIT_HASH_MAX_LENGTH = 255;
3696
4202
  * and looks up nothing else.
3697
4203
  */
3698
4204
  var BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
4205
+ /** `native_builds.sandbox_url_scheme`'s bound in core's schema. */
4206
+ var SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
4207
+ /**
4208
+ * A URL scheme as RFC 3986 spells it, in lower case: what a sandbox build's
4209
+ * artifact registers, as `@hot-updater/protocol/native-artifact` reads it.
4210
+ */
4211
+ var URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
4212
+ /**
4213
+ * A bundle identifier or application ID, as an artifact reports it: letters,
4214
+ * digits, dots, dashes and underscores, which a scope key holds as they are.
4215
+ */
4216
+ var APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
4217
+ /** A fingerprint hash as a Release Catalog scope key holds it. */
4218
+ var FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
4219
+ /** How each kind of artifact can install. */
4220
+ var DISTRIBUTIONS = {
4221
+ apk: ["direct"],
4222
+ app: ["direct"],
4223
+ aab: ["store"],
4224
+ ipa: ["direct", "store"]
4225
+ };
3699
4226
  /** A native build or scope core cannot store or look up: the caller's input. */
3700
4227
  var NativeBuildInputError = class extends TypeError {
3701
4228
  name = "NativeBuildInputError";
@@ -3717,24 +4244,73 @@ var pick = (row) => ({
3717
4244
  build_number: row.build_number ?? null,
3718
4245
  submitted_to: row.submitted_to ?? null,
3719
4246
  submitted_at_ms: row.submitted_at_ms ?? null,
3720
- submitted_version: row.submitted_version ?? null
4247
+ submitted_version: row.submitted_version ?? null,
4248
+ is_store_build: row.is_store_build === true,
4249
+ is_sandbox: row.is_sandbox === true,
4250
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
4251
+ export_method: row.export_method ?? null,
4252
+ native_app_version: row.native_app_version ?? null
3721
4253
  });
3722
- /** The store track each platform's builds are submitted to. */
3723
- var SUBMISSION_DESTINATIONS = {
3724
- android: "play-internal",
3725
- ios: "testflight"
3726
- };
4254
+ /** The export methods an `.ipa` registers with. */
4255
+ var EXPORT_METHODS = /* @__PURE__ */ new Set([
4256
+ "app-store",
4257
+ "ad-hoc",
4258
+ "development",
4259
+ "enterprise"
4260
+ ]);
4261
+ /**
4262
+ * How many older builds of a scope one read takes, looking for one older than
4263
+ * a bundle when a build made after the bundle is the newest.
4264
+ */
4265
+ var OLDER_BUILDS_PAGE = 20;
4266
+ /**
4267
+ * How many pages of older builds that look reads before it answers null: 100
4268
+ * builds made after the bundle in one scope, where a deploy's new bundle has
4269
+ * none or a few registered while it deploys.
4270
+ */
4271
+ var OLDER_BUILDS_PAGES = 5;
4272
+ /** How many times a mark runs again after losing its scope's mark to another. */
4273
+ var MARK_ATTEMPTS = 8;
3727
4274
  /** `native_builds.build_number`'s bound in core's schema. */
3728
4275
  var BUILD_NUMBER_MAX_LENGTH = 64;
3729
4276
  /** `native_builds.submitted_version`'s bound in core's schema. */
3730
4277
  var SUBMITTED_VERSION_MAX_LENGTH = 255;
4278
+ var checkedScopeKey = (scopeKey) => {
4279
+ if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
4280
+ return scopeKey;
4281
+ };
4282
+ /**
4283
+ * How a registered artifact installs: an `.ipa` by its export method, and
4284
+ * `unknown` for one whose export no profile confirmed, which no lookup asks
4285
+ * for, so it is never reused as either.
4286
+ */
4287
+ var registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
4288
+ /**
4289
+ * A sandbox build scope's key, which names no channel: the app ID, URL
4290
+ * scheme, artifact kind and distribution in its place, then the fingerprint,
4291
+ * or the app-version strategy and the exact app version. `v1:sandbox:` is no
4292
+ * Release Catalog strategy, so it never meets a normal build's key.
4293
+ */
4294
+ var sandboxScopeKey = (scope, sandbox) => {
4295
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
4296
+ const problem = typeof appId !== "string" || !APP_ID.test(appId) ? "its app ID must be a bundle identifier or application ID, up to 255 characters" : typeof urlScheme !== "string" || !URL_SCHEME.test(urlScheme) ? `its URL scheme must be a URL scheme in lower case, up to ${SANDBOX_URL_SCHEME_MAX_LENGTH} characters` : !ARTIFACT_KINDS[scope.platform]?.includes(artifactKind) ? `its artifact kind must be one an ${scope.platform} build makes` : distribution !== "unknown" && !DISTRIBUTIONS[artifactKind].includes(distribution) ? `an .${artifactKind} doesn't install as ${String(distribution)}` : scope.fingerprintHash !== null && !FINGERPRINT_HASH.test(scope.fingerprintHash) ? "its fingerprint hash must be 1-255 URL-safe ASCII characters" : null;
4297
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
4298
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
4299
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
4300
+ };
3731
4301
  /**
3732
4302
  * A native build scope's key: the Release Catalog scope key of a
3733
4303
  * fingerprint, or of the app-version strategy followed by the exact app
3734
4304
  * version the build compiled in. One key serves both strategies, so one
3735
- * index finds the newest build of either.
4305
+ * index finds the newest build of either. A sandbox scope's key names no
4306
+ * channel, so pull requests find a sandbox build on any.
3736
4307
  */
3737
4308
  var nativeBuildScopeKey = (scope) => {
4309
+ const { sandbox } = scope;
4310
+ if (sandbox !== void 0 && sandbox !== null) {
4311
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
4312
+ return sandboxScopeKey(scope, sandbox);
4313
+ }
3738
4314
  let scopeKey;
3739
4315
  try {
3740
4316
  const channelKey = encodeChannelKey(scope.channel);
@@ -3751,32 +4327,126 @@ var nativeBuildScopeKey = (scope) => {
3751
4327
  } catch (error) {
3752
4328
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
3753
4329
  }
3754
- if (scopeKey.length > SCOPE_KEY_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build scope: its key is longer than ${SCOPE_KEY_MAX_LENGTH} characters; shorten the channel or app version.`);
3755
- return scopeKey;
4330
+ return checkedScopeKey(scopeKey);
4331
+ };
4332
+ /** The channel row a registration names, or the refusal of its channel. */
4333
+ var channelIdOf = (channel) => {
4334
+ try {
4335
+ return `channel:${encodeChannelKey(channel)}`;
4336
+ } catch (error) {
4337
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
4338
+ }
4339
+ };
4340
+ /**
4341
+ * A registration's scope key, from the registration's own facts: a sandbox
4342
+ * build's from what its artifact says, whatever `sandbox` it names.
4343
+ */
4344
+ var registrationScopeKey = (registration) => {
4345
+ channelIdOf(registration.channel);
4346
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
4347
+ appId: registration.sandboxAppId,
4348
+ urlScheme: registration.sandboxUrlScheme,
4349
+ artifactKind: registration.artifact.kind,
4350
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
4351
+ }) : nativeBuildScopeKey({
4352
+ ...registration,
4353
+ sandbox: null
4354
+ });
4355
+ };
4356
+ /**
4357
+ * Refuses a patch from a sandbox build's built-in bundle: no deploy patches
4358
+ * from one, so no store or test install of the app gets a patch made for a
4359
+ * sandbox build. One unique read of the base.
4360
+ */
4361
+ var refuseSandboxPatchBase = async (db, baseBundleId) => {
4362
+ if ((await db.findOne("native_builds", { min_bundle_id: baseBundleId }))?.is_sandbox === true) throw new NativeBuildInputError("A sandbox build's built-in bundle is no patch base.");
3756
4363
  };
3757
4364
  /** Whether `bundleId` is a native build's built-in bundle: one unique read. */
3758
4365
  var isBuiltInBundle = async (db, bundleId) => await db.findOne("native_builds", { min_bundle_id: bundleId }) !== null;
3759
- var problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, artifact }) => {
4366
+ var problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
3760
4367
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
3761
4368
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
3762
4369
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
3763
4370
  if (channel.trim().length === 0) return "channel is required";
4371
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
4372
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
4373
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
4374
+ if (typeof sandboxUrlScheme !== "string" || !URL_SCHEME.test(sandboxUrlScheme)) return `sandboxUrlScheme must be a URL scheme in lower case, up to ${SANDBOX_URL_SCHEME_MAX_LENGTH} characters, or null`;
4375
+ }
4376
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
4377
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
4378
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
4379
+ }
4380
+ if (isSandbox === true) {
4381
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
4382
+ if (sandboxAppId === void 0 || sandboxAppId === null) return "a sandbox build needs the sandboxAppId its artifact reports, which an older hot-updater CLI doesn't send. Upgrade the hot-updater CLI to the version that matches this server, and build again";
4383
+ }
3764
4384
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
3765
4385
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
3766
4386
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
3767
4387
  if (buildNumber !== void 0 && buildNumber !== null && (buildNumber.trim().length === 0 || buildNumber.length > BUILD_NUMBER_MAX_LENGTH)) return `buildNumber must be the artifact's build number, up to ${BUILD_NUMBER_MAX_LENGTH} characters, or null`;
4388
+ if (nativeAppVersion !== void 0 && nativeAppVersion !== null && (typeof nativeAppVersion !== "string" || nativeAppVersion.trim().length === 0)) return "nativeAppVersion must be the artifact's app version, or null";
3768
4389
  const kinds = ARTIFACT_KINDS[platform];
3769
4390
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
4391
+ if (exportMethod !== void 0 && exportMethod !== null) {
4392
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
4393
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
4394
+ }
3770
4395
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
3771
4396
  return null;
3772
4397
  };
4398
+ /** The other install target of an iOS sandbox build's native code. */
4399
+ var SIBLING_KINDS = {
4400
+ app: "ipa",
4401
+ ipa: "app"
4402
+ };
4403
+ /**
4404
+ * Whether a build is one a person installs from its file: a Simulator `.app`,
4405
+ * or an `.ipa` exported for direct install, that no store took and that isn't
4406
+ * the store build. One rule for a sibling and the build it is found from, so
4407
+ * a build that shows its sibling is shown by it.
4408
+ */
4409
+ var isInstallTarget = (build) => !build.is_store_build && build.submitted_to === null && (build.artifact_kind === "app" || build.artifact_kind === "ipa" && build.export_method !== null && build.export_method !== "app-store");
4410
+ /**
4411
+ * The scope key of the other install target of a sandbox build, from its own
4412
+ * key's app ID and URL scheme, which hold no colon, and its row's fingerprint
4413
+ * or app version, through `sandboxScopeKey`; null for a key it didn't make.
4414
+ */
4415
+ var siblingSandboxScopeKey = (build, artifactKind) => {
4416
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
4417
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
4418
+ const target = build.fingerprint_hash === null ? {
4419
+ platform: build.platform,
4420
+ fingerprintHash: null,
4421
+ appVersion: build.app_version ?? ""
4422
+ } : {
4423
+ platform: build.platform,
4424
+ fingerprintHash: build.fingerprint_hash,
4425
+ appVersion: null
4426
+ };
4427
+ try {
4428
+ return sandboxScopeKey(target, {
4429
+ appId,
4430
+ urlScheme,
4431
+ artifactKind: build.artifact_kind,
4432
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
4433
+ }) === build.scope_key ? sandboxScopeKey(target, {
4434
+ appId,
4435
+ urlScheme,
4436
+ artifactKind,
4437
+ distribution: "direct"
4438
+ }) : null;
4439
+ } catch {
4440
+ return null;
4441
+ }
4442
+ };
3773
4443
  /** The native build registry: core's `native_builds` and the built-in bundle rows. */
3774
4444
  var createNativeBuildApi = (db, { now = Date.now } = {}) => ({
3775
4445
  async registerNativeBuild(registration) {
3776
4446
  const problem = problemOf(registration);
3777
4447
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
3778
- const scopeKey = nativeBuildScopeKey(registration);
3779
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
4448
+ const scopeKey = registrationScopeKey(registration);
4449
+ const channelId = channelIdOf(registration.channel);
3780
4450
  const { embeddedBundle } = registration;
3781
4451
  const row = {
3782
4452
  id: registration.id,
@@ -3795,7 +4465,12 @@ var createNativeBuildApi = (db, { now = Date.now } = {}) => ({
3795
4465
  build_number: registration.buildNumber ?? null,
3796
4466
  submitted_to: null,
3797
4467
  submitted_at_ms: null,
3798
- submitted_version: null
4468
+ submitted_version: null,
4469
+ is_store_build: false,
4470
+ is_sandbox: registration.isSandbox === true,
4471
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
4472
+ export_method: registration.exportMethod ?? null,
4473
+ native_app_version: registration.nativeAppVersion ?? null
3799
4474
  };
3800
4475
  for (let attempt = 1;; attempt += 1) {
3801
4476
  await insertChannel(db, {
@@ -3829,25 +4504,82 @@ var createNativeBuildApi = (db, { now = Date.now } = {}) => ({
3829
4504
  const row = await db.findOne("native_builds", { id });
3830
4505
  return row === null ? null : pick(row);
3831
4506
  },
4507
+ async findNativeBuildByBuiltInBundle(bundleId) {
4508
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
4509
+ return row === null ? null : pick(row);
4510
+ },
3832
4511
  async findNativeBuild(scope, options) {
3833
4512
  const scopeKey = nativeBuildScopeKey(scope);
3834
4513
  const buildKey = options?.buildKey;
3835
4514
  if (buildKey !== void 0 && !BUILD_KEY.test(buildKey)) throw new NativeBuildInputError("Invalid native build key: it must be nbk1: and a SHA-256.");
3836
- const { rows } = buildKey === void 0 ? await db.findMany("native_builds", {
4515
+ const artifactKind = options?.artifactKind;
4516
+ if (artifactKind !== void 0 && !ARTIFACT_KINDS[scope.platform].includes(artifactKind)) throw new NativeBuildInputError(`Invalid native build kind: an ${scope.platform} build is ${ARTIFACT_KINDS[scope.platform].join(" or ")}.`);
4517
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
4518
+ if (options?.storeBuild) {
4519
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
4520
+ return marked === null || !ofKind(marked) ? null : pick(marked);
4521
+ }
4522
+ const read = (limit, before) => {
4523
+ const page = {
4524
+ order: "desc",
4525
+ limit,
4526
+ ...before === void 0 ? {} : { range: { lt: before } }
4527
+ };
4528
+ return buildKey !== void 0 ? db.findMany("native_builds", {
4529
+ index: "byBuildKey",
4530
+ where: {
4531
+ scope_key: scopeKey,
4532
+ build_key: buildKey
4533
+ },
4534
+ ...page
4535
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
4536
+ index: "byScopeKind",
4537
+ where: {
4538
+ scope_key: scopeKey,
4539
+ artifact_kind: artifactKind
4540
+ },
4541
+ ...page
4542
+ }) : db.findMany("native_builds", {
4543
+ index: "byScope",
4544
+ where: { scope_key: scopeKey },
4545
+ ...page
4546
+ });
4547
+ };
4548
+ const bundleId = options?.builtInOlderThan;
4549
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
4550
+ const { rows } = await read(1);
4551
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
3837
4552
  index: "byScope",
3838
4553
  where: { scope_key: scopeKey },
3839
4554
  order: "desc",
3840
4555
  limit: 1
3841
- }) : await db.findMany("native_builds", {
3842
- index: "byBuildKey",
3843
- where: {
3844
- scope_key: scopeKey,
3845
- build_key: buildKey
3846
- },
4556
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
4557
+ if (newest === void 0 || !ofKind(newest)) return null;
4558
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
4559
+ let before = newest.id;
4560
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
4561
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
4562
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
4563
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
4564
+ const last = older.at(-1);
4565
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
4566
+ before = last.id;
4567
+ }
4568
+ return null;
4569
+ },
4570
+ async findNativeBuildSibling(build) {
4571
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
4572
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
4573
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
4574
+ if (scopeKey === null) return null;
4575
+ const { rows } = await db.findMany("native_builds", {
4576
+ index: "byScope",
4577
+ where: { scope_key: scopeKey },
3847
4578
  order: "desc",
3848
4579
  limit: 1
3849
4580
  });
3850
- return rows[0] === void 0 ? null : pick(rows[0]);
4581
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
4582
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
3851
4583
  },
3852
4584
  async recordNativeBuildSubmission(id, { destination, version }) {
3853
4585
  if (version.trim().length === 0 || version.length > SUBMITTED_VERSION_MAX_LENGTH) throw new NativeBuildInputError(`Invalid native build submission: version must be the store's label of the build, up to ${SUBMITTED_VERSION_MAX_LENGTH} characters.`);
@@ -3855,7 +4587,8 @@ var createNativeBuildApi = (db, { now = Date.now } = {}) => ({
3855
4587
  const row = await tx.findOne("native_builds", { id });
3856
4588
  if (row === null) return null;
3857
4589
  const build = pick(row);
3858
- if (SUBMISSION_DESTINATIONS[build.platform] !== destination) throw new NativeBuildInputError(`Invalid native build submission: an ${build.platform} build is submitted to ${SUBMISSION_DESTINATIONS[build.platform]}, not ${destination}.`);
4590
+ if (!NATIVE_BUILD_SUBMISSION_DESTINATIONS[build.platform].includes(destination)) throw new NativeBuildInputError(`Invalid native build submission: an ${build.platform} build is submitted to ${NATIVE_BUILD_SUBMISSION_DESTINATIONS[build.platform].join(" or ")}, not ${destination}.`);
4591
+ if (build.is_sandbox && destination !== "testflight" && destination !== "play-internal") throw new NativeBuildInputError("A sandbox build can submit only to TestFlight or Play internal testing.");
3859
4592
  const set = {
3860
4593
  submitted_to: destination,
3861
4594
  submitted_at_ms: now(),
@@ -3868,6 +4601,46 @@ var createNativeBuildApi = (db, { now = Date.now } = {}) => ({
3868
4601
  };
3869
4602
  });
3870
4603
  },
4604
+ async markNativeBuild(id, { storeBuild }) {
4605
+ for (let attempt = 1;; attempt += 1) try {
4606
+ return await db.transaction(async (tx) => {
4607
+ const row = await tx.findOne("native_builds", { id });
4608
+ if (row === null) return null;
4609
+ const build = pick(row);
4610
+ if (!storeBuild) {
4611
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
4612
+ return {
4613
+ nativeBuild: {
4614
+ ...build,
4615
+ is_store_build: false
4616
+ },
4617
+ previous: null
4618
+ };
4619
+ }
4620
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
4621
+ if (build.is_store_build) return {
4622
+ nativeBuild: build,
4623
+ previous: null
4624
+ };
4625
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
4626
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
4627
+ tx.update("native_builds", row, { is_store_build: true });
4628
+ return {
4629
+ nativeBuild: {
4630
+ ...build,
4631
+ is_store_build: true
4632
+ },
4633
+ previous: holder === null ? null : {
4634
+ ...pick(holder),
4635
+ is_store_build: false
4636
+ }
4637
+ };
4638
+ });
4639
+ } catch (error) {
4640
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
4641
+ throw error;
4642
+ }
4643
+ },
3871
4644
  async deleteNativeBuild(id) {
3872
4645
  return db.transaction(async (tx) => {
3873
4646
  const row = await tx.findOne("native_builds", { id });
@@ -3921,25 +4694,28 @@ var checkScope = (scope) => {
3921
4694
  });
3922
4695
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
3923
4696
  };
3924
- /** A scope's enabled releases, all of them, under the catalog's guard. */
3925
- var enabledReleases = async (tx, scopeKey) => {
4697
+ /** Every row of a paged read, as release rows. */
4698
+ var drainReleases = async (page) => {
3926
4699
  const rows = [];
3927
4700
  let cursor;
3928
4701
  do {
3929
- const page = await tx.findMany("releases", {
3930
- index: "byScopeEnabled",
3931
- where: {
3932
- scope_key: scopeKey,
3933
- enabled: true
3934
- },
3935
- limit: PAGE,
3936
- ...cursor === void 0 ? {} : { cursor }
3937
- });
3938
- rows.push(...page.rows.map(toReleaseRow));
3939
- cursor = page.next;
4702
+ const found = await page(cursor);
4703
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
4704
+ cursor = found.next;
3940
4705
  } while (cursor !== void 0);
3941
4706
  return rows;
3942
4707
  };
4708
+ var enabledIn = (scopeKey, cursor) => ({
4709
+ index: "byScopeEnabled",
4710
+ where: {
4711
+ scope_key: scopeKey,
4712
+ enabled: true
4713
+ },
4714
+ limit: PAGE,
4715
+ ...cursor === void 0 ? {} : { cursor }
4716
+ });
4717
+ /** A scope's enabled releases, all of them, under the catalog's guard. */
4718
+ var enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
3943
4719
  /** The scope's newest release id: `byScope` descending, limit 1. */
3944
4720
  var latestReleaseId = async (tx, scopeKey) => {
3945
4721
  const { rows } = await tx.findMany("releases", {
@@ -3950,15 +4726,11 @@ var latestReleaseId = async (tx, scopeKey) => {
3950
4726
  });
3951
4727
  return rows[0]?.id ?? null;
3952
4728
  };
3953
- /** Compiles `enabled` and writes it as the scope's next catalog generation. */
3954
- var writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
3955
- const compilation = await compileReleaseCatalog({
3956
- strategy: scope.strategy,
3957
- releases: enabled.map(releaseRowToRelease)
3958
- });
3959
- const generation = (stored.generation ?? 0) + 1;
4729
+ /** The scope's next catalog generation, compiled as `compilation`. */
4730
+ var nextCatalog = (scope, stored, compilation, updatedAtMs) => {
4731
+ const generation = (stored.catalog?.generation ?? 0) + 1;
3960
4732
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
3961
- const catalog = {
4733
+ return {
3962
4734
  scope_key: scope.scopeKey,
3963
4735
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
3964
4736
  strategy: scope.strategy,
@@ -3973,6 +4745,26 @@ var writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
3973
4745
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
3974
4746
  updated_at_ms: updatedAtMs
3975
4747
  };
4748
+ };
4749
+ /**
4750
+ * Compiles a scope's enabled releases. A catalog over the size limit is
4751
+ * refused naming its channel and platform, and what frees room in it.
4752
+ */
4753
+ var compileScope = async (scope, enabled) => {
4754
+ try {
4755
+ return await compileReleaseCatalog({
4756
+ strategy: scope.strategy,
4757
+ releases: enabled.map(releaseRowToRelease)
4758
+ });
4759
+ } catch (error) {
4760
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
4761
+ throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `The ${scope.platform} release catalog of channel "${scope.channelName}" would be over its ${MAX_COMPILED_CATALOG_BYTES / 1024} KiB limit.\nDisable or delete old bundles on that channel, then try again.`);
4762
+ }
4763
+ };
4764
+ /** Compiles `enabled` and writes it as the scope's next catalog generation. */
4765
+ var writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
4766
+ const compilation = await compileScope(scope, enabled);
4767
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
3976
4768
  const { scope_key: _scopeKey, ...set } = catalog;
3977
4769
  if (stored.row === null) tx.create("release_catalogs", catalog);
3978
4770
  else tx.update("release_catalogs", stored.row, set);
@@ -4060,18 +4852,48 @@ var changeReleases = (db, inputs) => {
4060
4852
  return results;
4061
4853
  });
4062
4854
  };
4855
+ /** Whether `current` is what the scope's enabled releases compile to. */
4856
+ var isCurrent = (scope, current, compilation) => current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash;
4857
+ /** The scope a catalog row names. */
4858
+ var catalogRowScope = (row) => ({
4859
+ channelId: row.channel_id,
4860
+ channelName: decodeChannelKey(row.channel_key),
4861
+ fingerprintHash: row.fingerprint_hash,
4862
+ platform: row.platform,
4863
+ scopeKey: row.scope_key,
4864
+ strategy: row.strategy
4865
+ });
4866
+ /**
4867
+ * What a rebuild of the scope's catalog would write, without writing: one
4868
+ * read of the catalog row and one of the scope's enabled releases. It needs
4869
+ * no transaction, whose guards would read the catalog again for each read
4870
+ * beneath it, nor the scope's newest release, which matters only to a scope
4871
+ * without a catalog row; that one is not found.
4872
+ */
4873
+ var preflightRebuild = async (db, scopeKey, updatedAtMs) => {
4874
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
4875
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
4876
+ const current = toCatalogRow(row);
4877
+ const scope = catalogRowScope(current);
4878
+ checkScope(scope);
4879
+ const compilation = await compileScope(scope, await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor))));
4880
+ const changed = !isCurrent(scope, current, compilation);
4881
+ return {
4882
+ changed,
4883
+ currentCatalog: current,
4884
+ diagnostics: compilation.diagnostics,
4885
+ projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
4886
+ };
4887
+ };
4063
4888
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
4064
4889
  var rebuildScope = async (tx, scope, updatedAtMs) => {
4065
4890
  checkScope(scope);
4066
4891
  const stored = await readCatalog(tx, scope.scopeKey);
4067
4892
  assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
4068
4893
  const enabled = await enabledReleases(tx, scope.scopeKey);
4069
- const compilation = await compileReleaseCatalog({
4070
- strategy: scope.strategy,
4071
- releases: enabled.map(releaseRowToRelease)
4072
- });
4894
+ const compilation = await compileScope(scope, enabled);
4073
4895
  const current = stored.catalog;
4074
- if (current !== null && current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash) return {
4896
+ if (current !== null && isCurrent(scope, current, compilation)) return {
4075
4897
  catalog: current,
4076
4898
  current,
4077
4899
  changed: false,
@@ -4173,14 +4995,7 @@ var mutationResult = ({ catalog, release }) => ({
4173
4995
  var catalogScope = async (tx, scopeKey) => {
4174
4996
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
4175
4997
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
4176
- return {
4177
- channelId: row.channel_id,
4178
- channelName: decodeChannelKey(row.channel_key),
4179
- fingerprintHash: row.fingerprint_hash,
4180
- platform: row.platform,
4181
- scopeKey: row.scope_key,
4182
- strategy: row.strategy
4183
- };
4998
+ return catalogRowScope(toCatalogRow(row));
4184
4999
  };
4185
5000
  /**
4186
5001
  * Core's typed writes: each runs in one engine transaction rooted at the
@@ -4209,7 +5024,11 @@ var createCoreOperations = (db, { now = Date.now } = {}) => {
4209
5024
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
4210
5025
  const platforms = /* @__PURE__ */ new Map();
4211
5026
  for (const deployment of deployments) {
4212
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
5027
+ if (!("bundleId" in deployment)) {
5028
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
5029
+ continue;
5030
+ }
5031
+ if (platforms.has(deployment.bundleId)) continue;
4213
5032
  const row = await db.findOne("bundles", { id: deployment.bundleId });
4214
5033
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
4215
5034
  if (await isBuiltInBundle(db, deployment.bundleId)) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", `Bundle "${deployment.bundleId}" is a native build's built-in bundle, which no release publishes.`);
@@ -4384,18 +5203,7 @@ var createCoreOperations = (db, { now = Date.now } = {}) => {
4384
5203
  };
4385
5204
  });
4386
5205
  },
4387
- preflightReleaseCatalogRebuild: (scopeKey) => {
4388
- const updatedAtMs = now();
4389
- return dryRun(db, async (tx) => {
4390
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
4391
- return {
4392
- changed: rebuilt.changed,
4393
- currentCatalog: rebuilt.current,
4394
- diagnostics: rebuilt.diagnostics,
4395
- projectedCatalog: rebuilt.catalog
4396
- };
4397
- });
4398
- },
5206
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
4399
5207
  ensureChannel,
4400
5208
  deleteChannel: (id) => deleteChannel(db, id),
4401
5209
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -4412,7 +5220,7 @@ var createCoreOperations = (db, { now = Date.now } = {}) => {
4412
5220
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
4413
5221
  ...next,
4414
5222
  patches
4415
- }));
5223
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
4416
5224
  }),
4417
5225
  deleteBundles: async (ids) => {
4418
5226
  try {
@@ -4472,6 +5280,7 @@ var createCoreApi = (db, storage, options = {}) => {
4472
5280
  ...reads,
4473
5281
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
4474
5282
  ...createNativeBuildApi(db, options),
5283
+ ...createIosDeviceApi(db, options),
4475
5284
  ready: async () => {
4476
5285
  await reads.listReleaseCatalogs({ limit: 1 });
4477
5286
  }
@@ -4655,6 +5464,10 @@ var answer = async (operation) => {
4655
5464
  error: error.message
4656
5465
  }, status);
4657
5466
  }
5467
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json({
5468
+ code: error.code,
5469
+ error: error.message
5470
+ }, 400);
4658
5471
  if (error instanceof DatabaseBundleNotFoundError) return json({
4659
5472
  code: "BUNDLE_NOT_FOUND",
4660
5473
  error: error.message
@@ -4674,18 +5487,22 @@ var LIMITS = {
4674
5487
  defaultValue: 50,
4675
5488
  maxValue: 500
4676
5489
  };
5490
+ /** The most IDs one request names: a lookup's, or a write's. */
5491
+ var MAX_IDS = 100;
4677
5492
  /** `order`, `cursor`, and `limit`: one keyset page. */
4678
- var keyset = (url, maxValue = LIMITS.maxValue) => {
4679
- const order = url.searchParams.get("order") ?? "desc";
5493
+ var keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
5494
+ const order = url.searchParams.get("order") ?? defaultOrder;
4680
5495
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
4681
5496
  const limitParam = url.searchParams.get("limit");
4682
5497
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
4683
5498
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
4684
5499
  const cursor = url.searchParams.get("cursor");
5500
+ const through = url.searchParams.get("through");
4685
5501
  return {
4686
5502
  order,
4687
5503
  limit,
4688
- ...cursor === null ? {} : { after: cursor }
5504
+ ...cursor === null ? {} : { after: cursor },
5505
+ ...through === null ? {} : { through }
4689
5506
  };
4690
5507
  };
4691
5508
  /** A page and the cursor of the next one, when the page is full. */
@@ -4783,7 +5600,8 @@ var nativeBuildScopeOf = (url) => {
4783
5600
  const fingerprintHash = params.get("fingerprintHash");
4784
5601
  const appVersion = params.get("appVersion");
4785
5602
  if (platform === void 0 || !isText(channel) || fingerprintHash === null === (appVersion === null) || fingerprintHash === "" || appVersion === "") throw new HandlerBadRequestError("A native build lookup needs platform, channel, and fingerprintHash or appVersion.");
4786
- return fingerprintHash !== null ? {
5603
+ const sandbox = sandboxScopeOf(params);
5604
+ const scope = fingerprintHash !== null ? {
4787
5605
  platform,
4788
5606
  channel,
4789
5607
  fingerprintHash,
@@ -4794,17 +5612,49 @@ var nativeBuildScopeOf = (url) => {
4794
5612
  fingerprintHash: null,
4795
5613
  appVersion
4796
5614
  };
5615
+ return sandbox === null ? scope : {
5616
+ ...scope,
5617
+ sandbox
5618
+ };
5619
+ };
5620
+ /** The query parameters a sandbox lookup names, all four or none. */
5621
+ var SANDBOX_SCOPE_PARAMS = [
5622
+ "sandboxAppId",
5623
+ "sandboxUrlScheme",
5624
+ "artifactKind",
5625
+ "distribution"
5626
+ ];
5627
+ /**
5628
+ * A lookup's sandbox scope: null without one, and a bad request for one
5629
+ * named in part. Core checks each value.
5630
+ */
5631
+ var sandboxScopeOf = (params) => {
5632
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
5633
+ const named = [
5634
+ appId,
5635
+ urlScheme,
5636
+ artifactKind,
5637
+ distribution
5638
+ ].filter((value) => value !== null).length;
5639
+ if (named === 0) return null;
5640
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
5641
+ return {
5642
+ appId,
5643
+ urlScheme,
5644
+ artifactKind,
5645
+ distribution
5646
+ };
4797
5647
  };
4798
5648
  /** A native build or scope core refuses: a bad request. */
4799
5649
  var refusingInvalid = async (operation) => {
4800
5650
  try {
4801
5651
  return await operation();
4802
5652
  } catch (error) {
4803
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
5653
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
4804
5654
  throw error;
4805
5655
  }
4806
5656
  };
4807
- var isNativeBuildRegistration = (value) => isRecord$1(value) && isText(value.id) && isText(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText(value.channel) && isTextOrNull(value.fingerprintHash) && isTextOrNull(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull(value.gitCommitHash) && isTextOrNull(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull(value.buildNumber)) && isRecord$1(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$1(value.embeddedBundle) && isText(value.embeddedBundle.manifestStorageUri) && isText(value.embeddedBundle.manifestFileHash) && isText(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$1(value.embeddedBundle.metadata));
5657
+ var isNativeBuildRegistration = (value) => isRecord$1(value) && isText(value.id) && isText(value.minBundleId) && typeof value.platform === "string" && isPlatform(value.platform) && isText(value.channel) && isTextOrNull(value.fingerprintHash) && isTextOrNull(value.appVersion) && value.fingerprintHash === null !== (value.appVersion === null) && isTextOrNull(value.gitCommitHash) && isTextOrNull(value.buildKey) && (value.buildNumber === void 0 || isTextOrNull(value.buildNumber)) && (value.isSandbox === void 0 || typeof value.isSandbox === "boolean") && (value.sandboxUrlScheme === void 0 || isTextOrNull(value.sandboxUrlScheme)) && (value.sandboxAppId === void 0 || isTextOrNull(value.sandboxAppId)) && (value.exportMethod === void 0 || isTextOrNull(value.exportMethod)) && (value.nativeAppVersion === void 0 || isTextOrNull(value.nativeAppVersion)) && isRecord$1(value.artifact) && typeof value.artifact.kind === "string" && NATIVE_BUILD_ARTIFACT_KINDS.has(value.artifact.kind) && isText(value.artifact.storageUri) && Number.isSafeInteger(value.artifact.byteSize) && value.artifact.byteSize >= 0 && isRecord$1(value.embeddedBundle) && isText(value.embeddedBundle.manifestStorageUri) && isText(value.embeddedBundle.manifestFileHash) && isText(value.embeddedBundle.assetBaseStorageUri) && (value.embeddedBundle.metadata === void 0 || isRecord$1(value.embeddedBundle.metadata));
4808
5658
  var scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
4809
5659
  /** Every admin route's handler, by the name `ADMIN_ROUTES` mounts it under. */
4810
5660
  var createAdminRouteHandlers = () => ({
@@ -4835,11 +5685,32 @@ var createAdminRouteHandlers = () => ({
4835
5685
  const input = keyset(new URL(request.url));
4836
5686
  return page(await core.listReleaseCatalogs(input), input, (row) => row.scope_key);
4837
5687
  }),
5688
+ listReleaseScopeKeys: onCore(async (core, request) => {
5689
+ const input = keyset(new URL(request.url), 100, "asc");
5690
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
5691
+ return page(await core.listReleaseScopeKeys({
5692
+ limit: input.limit,
5693
+ ...input.after === void 0 ? {} : { after: input.after }
5694
+ }), input, (scopeKey) => scopeKey);
5695
+ }),
4838
5696
  getChannels: onCore(async (core, request) => {
4839
- const name = new URL(request.url).searchParams.get("name");
4840
- if (name === null) return json({ data: await core.listChannels() });
4841
- const channel = await core.findChannelByName(name);
4842
- return channel === null ? notFound() : json({ data: channel });
5697
+ const url = new URL(request.url);
5698
+ const name = url.searchParams.get("name");
5699
+ if (name !== null) {
5700
+ const channel = await core.findChannelByName(name);
5701
+ return channel === null ? notFound() : json({ data: channel });
5702
+ }
5703
+ const ids = url.searchParams.get("ids");
5704
+ if (ids !== null) {
5705
+ const list = ids.split(",").filter((id) => id.length > 0);
5706
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
5707
+ return json({ data: await core.getChannels(list) });
5708
+ }
5709
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
5710
+ const input = keyset(url, LIMITS.maxValue, "asc");
5711
+ return page(await core.listChannels(input), input, (row) => row.name);
5712
+ }
5713
+ return json({ data: await core.listChannels() });
4843
5714
  }),
4844
5715
  createChannel: onCore(async (core, request) => {
4845
5716
  const { name } = await body(request);
@@ -4880,13 +5751,14 @@ var createAdminRouteHandlers = () => ({
4880
5751
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
4881
5752
  updateBundle: onCore(async (core, request, params) => {
4882
5753
  const bundleId = requireRouteParam(params, "id");
4883
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
5754
+ const update = bundleUpdateOf(await request.json(), bundleId);
5755
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
4884
5756
  return noContent();
4885
5757
  }),
4886
5758
  countBundles: onCore(async (core, request) => json({ data: await core.countBundles(platformOf(new URL(request.url))) })),
4887
5759
  countBundleChildren: onCore(async (core, request) => {
4888
5760
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
4889
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
5761
+ if (ids.length === 0 || ids.length > MAX_IDS) throw new HandlerBadRequestError(`Bundle child counts take ids=<bundle id>,... with 1 to ${MAX_IDS} ids.`);
4890
5762
  return json({ data: await core.countBundleChildren(ids) });
4891
5763
  }),
4892
5764
  listBundleChildren: onCore(async (core, request, params) => {
@@ -4903,7 +5775,7 @@ var createAdminRouteHandlers = () => ({
4903
5775
  deployReleases: onCore(async (core, request) => {
4904
5776
  const { deployments } = await body(request);
4905
5777
  if (!Array.isArray(deployments) || deployments.length === 0 || !deployments.every(isDeployment)) throw new HandlerBadRequestError("Deploy needs deployments, each a bundle and its release policy.");
4906
- return json({ data: await core.deploy(deployments) }, 201);
5778
+ return json({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
4907
5779
  }),
4908
5780
  promoteRelease: onCore(async (core, request, params) => {
4909
5781
  const input = await body(request);
@@ -4926,9 +5798,22 @@ var createAdminRouteHandlers = () => ({
4926
5798
  const url = new URL(request.url);
4927
5799
  const scope = nativeBuildScopeOf(url);
4928
5800
  const buildKey = url.searchParams.get("buildKey");
4929
- return json({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
5801
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
5802
+ const kind = url.searchParams.get("kind");
5803
+ const options = {
5804
+ ...buildKey === null ? {} : { buildKey },
5805
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
5806
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
5807
+ ...kind === null ? {} : { artifactKind: kind }
5808
+ };
5809
+ return json({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
5810
+ }),
5811
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
5812
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
5813
+ return json({ data: build === null ? null : await core.findNativeBuildSibling(build) });
4930
5814
  }),
4931
5815
  getNativeBuild: onCore(async (core, _request, params) => json({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
5816
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
4932
5817
  listNativeBuilds: onCore(async (core, request) => {
4933
5818
  const url = new URL(request.url);
4934
5819
  const input = keyset(url);
@@ -4940,14 +5825,97 @@ var createAdminRouteHandlers = () => ({
4940
5825
  }),
4941
5826
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
4942
5827
  const input = await body(request);
4943
- if (!isRecord$1(input) || input.destination !== "testflight" && input.destination !== "play-internal" || !isText(input.version)) throw new HandlerBadRequestError("A native build submission needs destination (testflight or play-internal) and version.");
5828
+ if (!isRecord$1(input) || !Object.values(NATIVE_BUILD_SUBMISSION_DESTINATIONS).flat().includes(input.destination) || !isText(input.version)) throw new HandlerBadRequestError("A native build submission needs a valid store destination and version.");
4944
5829
  const submission = {
4945
5830
  destination: input.destination,
4946
5831
  version: input.version
4947
5832
  };
4948
5833
  return json({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
4949
5834
  }),
5835
+ markNativeBuild: onCore(async (core, request, params) => {
5836
+ const input = await body(request);
5837
+ if (!isRecord$1(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
5838
+ const mark = { storeBuild: input.storeBuild };
5839
+ return json({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
5840
+ }),
4950
5841
  deleteNativeBuild: onCore(async (core, _request, params) => json({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
5842
+ listIosDevices: onCore(async (core, request) => {
5843
+ const url = new URL(request.url);
5844
+ const input = keyset(url);
5845
+ const status = url.searchParams.get("status");
5846
+ return page(await refusingInvalid(() => core.listIosDevices({
5847
+ ...input,
5848
+ ...status === null ? {} : { status }
5849
+ })), input, ({ id }) => id);
5850
+ }),
5851
+ findIosDevice: onCore(async (core, _request, params) => json({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
5852
+ requestIosDevice: onCore(async (core, request) => {
5853
+ const input = await body(request);
5854
+ if (!isText(input.udid) || !isText(input.name) || !isTextOrNull(input.requestedBy)) throw new HandlerBadRequestError("An iOS device request needs udid, name, and requestedBy, an email or null.");
5855
+ const device = {
5856
+ udid: input.udid,
5857
+ name: input.name,
5858
+ requestedBy: input.requestedBy
5859
+ };
5860
+ return json({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
5861
+ }),
5862
+ approveIosDevice: onCore(async (core, request, params) => {
5863
+ const input = await body(request);
5864
+ if (!isTextOrNull(input.approvedBy) || input.name !== void 0 && !isText(input.name)) throw new HandlerBadRequestError("An iOS device approval needs approvedBy, an email or null, and an optional name.");
5865
+ const approval = {
5866
+ approvedBy: input.approvedBy,
5867
+ ...input.name === void 0 ? {} : { name: input.name }
5868
+ };
5869
+ return json({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
5870
+ }),
5871
+ renameIosDevice: onCore(async (core, request, params) => {
5872
+ const input = await body(request);
5873
+ if (!isText(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
5874
+ const name = input.name;
5875
+ return json({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
5876
+ }),
5877
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
5878
+ const input = await body(request);
5879
+ const seen = input.seen;
5880
+ if (!isRecord$1(seen) || typeof seen.status !== "string" || !(seen.approvedAtMs === null || Number.isSafeInteger(seen.approvedAtMs)) || !isText(input.issuerId) || typeof input.outcome !== "string" || input.reason !== void 0 && typeof input.reason !== "string") throw new HandlerBadRequestError("An iOS device outcome needs seen { status, approvedAtMs }, issuerId, outcome, and an optional reason.");
5881
+ const outcome = {
5882
+ id: requireRouteParam(params, "id"),
5883
+ seen: {
5884
+ status: seen.status,
5885
+ approvedAtMs: seen.approvedAtMs
5886
+ },
5887
+ issuerId: input.issuerId,
5888
+ outcome: input.outcome,
5889
+ ...input.reason === void 0 ? {} : { reason: input.reason }
5890
+ };
5891
+ return json({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
5892
+ }),
5893
+ claimIosDeviceAccount: onCore(async (core, request) => {
5894
+ const { issuerId } = await body(request);
5895
+ if (!isText(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
5896
+ return json({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
5897
+ }),
5898
+ findIosDeviceAccount: onCore(async (core) => json({ data: await core.findIosDeviceAccount() })),
5899
+ markIosDevicesInBuild: onCore(async (core, request) => {
5900
+ const { buildId, ids } = await body(request);
5901
+ if (!isText(buildId) || !Array.isArray(ids) || !ids.every((id) => isText(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
5902
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
5903
+ await core.markIosDevicesInBuild({
5904
+ buildId,
5905
+ ids
5906
+ });
5907
+ return noContent();
5908
+ }),
5909
+ deleteIosDevice: onCore(async (core, request, params) => {
5910
+ const url = new URL(request.url);
5911
+ const status = url.searchParams.get("status");
5912
+ const requestedBy = url.searchParams.get("requestedBy");
5913
+ const only = {
5914
+ ...status === null ? {} : { status },
5915
+ ...requestedBy === null ? {} : { requestedBy }
5916
+ };
5917
+ return json({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
5918
+ }),
4951
5919
  deleteBundles: onCore(async (core, request) => {
4952
5920
  const { ids } = await body(request);
4953
5921
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -5002,6 +5970,11 @@ var ADMIN_ROUTES = [
5002
5970
  path: "/release-catalogs",
5003
5971
  handler: "listReleaseCatalogs"
5004
5972
  },
5973
+ {
5974
+ method: "GET",
5975
+ path: "/release-scopes",
5976
+ handler: "listReleaseScopeKeys"
5977
+ },
5005
5978
  {
5006
5979
  method: "POST",
5007
5980
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -5077,6 +6050,16 @@ var ADMIN_ROUTES = [
5077
6050
  path: "/native-builds/latest",
5078
6051
  handler: "findNativeBuild"
5079
6052
  },
6053
+ {
6054
+ method: "GET",
6055
+ path: "/native-builds/built-in/:bundleId",
6056
+ handler: "findNativeBuildByBuiltInBundle"
6057
+ },
6058
+ {
6059
+ method: "GET",
6060
+ path: "/native-builds/:id/sibling",
6061
+ handler: "findNativeBuildSibling"
6062
+ },
5080
6063
  {
5081
6064
  method: "GET",
5082
6065
  path: "/native-builds/:id",
@@ -5092,10 +6075,65 @@ var ADMIN_ROUTES = [
5092
6075
  path: "/native-builds/:id/submission",
5093
6076
  handler: "recordNativeBuildSubmission"
5094
6077
  },
6078
+ {
6079
+ method: "POST",
6080
+ path: "/native-builds/:id/store-build",
6081
+ handler: "markNativeBuild"
6082
+ },
5095
6083
  {
5096
6084
  method: "DELETE",
5097
6085
  path: "/native-builds/:id",
5098
6086
  handler: "deleteNativeBuild"
6087
+ },
6088
+ {
6089
+ method: "GET",
6090
+ path: "/ios-devices",
6091
+ handler: "listIosDevices"
6092
+ },
6093
+ {
6094
+ method: "POST",
6095
+ path: "/ios-devices",
6096
+ handler: "requestIosDevice"
6097
+ },
6098
+ {
6099
+ method: "GET",
6100
+ path: "/ios-devices/udid/:udid",
6101
+ handler: "findIosDevice"
6102
+ },
6103
+ {
6104
+ method: "POST",
6105
+ path: "/ios-devices/in-build",
6106
+ handler: "markIosDevicesInBuild"
6107
+ },
6108
+ {
6109
+ method: "GET",
6110
+ path: "/ios-devices/account",
6111
+ handler: "findIosDeviceAccount"
6112
+ },
6113
+ {
6114
+ method: "POST",
6115
+ path: "/ios-devices/account",
6116
+ handler: "claimIosDeviceAccount"
6117
+ },
6118
+ {
6119
+ method: "POST",
6120
+ path: "/ios-devices/:id/approval",
6121
+ handler: "approveIosDevice"
6122
+ },
6123
+ {
6124
+ method: "POST",
6125
+ path: "/ios-devices/:id/outcome",
6126
+ handler: "recordIosDeviceOutcome"
6127
+ },
6128
+ {
6129
+ method: "PATCH",
6130
+ path: "/ios-devices/:id",
6131
+ handler: "renameIosDevice"
6132
+ },
6133
+ {
6134
+ method: "DELETE",
6135
+ path: "/ios-devices/:id",
6136
+ handler: "deleteIosDevice"
5099
6137
  }
5100
6138
  ];
5101
6139
  var CATALOG_CONTENT_TYPE = "application/vnd.hot-updater.release-catalog+json; version=1";
@@ -5116,9 +6154,9 @@ var CATALOG_CACHE_CONTROL = "public, max-age=0, s-maxage=5";
5116
6154
  * background. `stale-if-error=0` keeps origin errors visible: without it,
5117
6155
  * Cloudflare serves a stale copy on error indefinitely.
5118
6156
  *
5119
- * A device can see a catalog up to 15 seconds after a deploy or a Roll back
5120
- * replaced it: the origin's 5-second catalog memo, then 5 seconds fresh and
5121
- * 5 stale at the CDN. A revoked API key can read a cached catalog up to
6157
+ * A device can see a catalog, or a scope's lack of one, up to 15 seconds
6158
+ * after a deploy or a Roll back replaced it: the origin's 5-second catalog
6159
+ * memo, then 5 seconds fresh and 5 stale at the CDN. A revoked API key can read a cached catalog up to
5122
6160
  * 10 seconds. Devices and caches that don't read the header keep
5123
6161
  * `Cache-Control`.
5124
6162
  */
@@ -5197,38 +6235,52 @@ var catalogResponse = async (catalog, request) => {
5197
6235
  };
5198
6236
  var createReleaseCatalogRouteHandlers = () => {
5199
6237
  const cache = /* @__PURE__ */ new Map();
6238
+ const evict = (insertedHit) => {
6239
+ const now = Date.now();
6240
+ let oldestMiss;
6241
+ let oldest;
6242
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
6243
+ else {
6244
+ if (entry.row === null) oldestMiss ??= key;
6245
+ oldest ??= key;
6246
+ }
6247
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
6248
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
6249
+ if (victim !== void 0) cache.delete(victim);
6250
+ };
5200
6251
  const inFlight = /* @__PURE__ */ new Map();
5201
- const loadCatalog = async (key, load) => {
5202
- const cached = cache.get(key);
6252
+ const loadRow = async (scopeKey, load) => {
6253
+ const cached = cache.get(scopeKey);
5203
6254
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
5204
- cache.delete(key);
5205
- cache.set(key, cached);
5206
- return cached.catalog;
6255
+ cache.delete(scopeKey);
6256
+ cache.set(scopeKey, cached);
6257
+ return cached.row;
5207
6258
  }
5208
- if (cached !== void 0) cache.delete(key);
5209
- const pending = inFlight.get(key);
6259
+ if (cached !== void 0) cache.delete(scopeKey);
6260
+ const pending = inFlight.get(scopeKey);
5210
6261
  if (pending !== void 0) return pending;
5211
- const next = load().then((catalog) => {
5212
- if (catalog !== null) {
5213
- cache.set(key, {
5214
- catalog,
5215
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
5216
- });
5217
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
5218
- const oldestKey = cache.keys().next().value;
5219
- if (oldestKey === void 0) break;
5220
- cache.delete(oldestKey);
5221
- }
5222
- }
5223
- return catalog;
6262
+ const next = load().then((row) => {
6263
+ cache.set(scopeKey, {
6264
+ row,
6265
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
6266
+ });
6267
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
6268
+ return row;
5224
6269
  });
5225
- inFlight.set(key, next);
6270
+ inFlight.set(scopeKey, next);
5226
6271
  try {
5227
6272
  return await next;
5228
6273
  } finally {
5229
- inFlight.delete(key);
6274
+ inFlight.delete(scopeKey);
5230
6275
  }
5231
6276
  };
6277
+ const loadCatalog = async (core, input) => {
6278
+ const scopeKey = releaseCatalogScopeKeyOf(input);
6279
+ return projectParsedReleaseCatalogRow(await loadRow(scopeKey, async () => {
6280
+ const row = await core.getReleaseCatalogRow(scopeKey);
6281
+ return row === null ? null : parseReleaseCatalogRow(row);
6282
+ }), input, scopeKey);
6283
+ };
5232
6284
  return {
5233
6285
  appVersionReleaseCatalog: async (params, request, { core }) => {
5234
6286
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -5242,7 +6294,7 @@ var createReleaseCatalogRouteHandlers = () => {
5242
6294
  };
5243
6295
  const invalid = invalidScope(input);
5244
6296
  if (invalid) return invalid;
5245
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
6297
+ return catalogResponse(await loadCatalog(core, input), request);
5246
6298
  },
5247
6299
  fingerprintReleaseCatalog: async (params, request, { core }) => {
5248
6300
  const input = {
@@ -5253,7 +6305,7 @@ var createReleaseCatalogRouteHandlers = () => {
5253
6305
  };
5254
6306
  const invalid = invalidScope(input);
5255
6307
  if (invalid) return invalid;
5256
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
6308
+ return catalogResponse(await loadCatalog(core, input), request);
5257
6309
  },
5258
6310
  artifactV2: async (params, _request, { core }) => {
5259
6311
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -5603,8 +6655,11 @@ var resolveConsoleConfig = async (request) => {
5603
6655
  const { default: source } = await import("./config-CjIBFhJX.mjs");
5604
6656
  const config = typeof source === "function" ? await source(request) : source;
5605
6657
  const { database, storage, plugins = [] } = config;
5606
- const { gitUrl } = config.console ?? {};
5607
- const consoleOptions = gitUrl === void 0 ? {} : { gitUrl };
6658
+ const { gitUrl, deviceApprovers = [] } = config.console ?? {};
6659
+ const consoleOptions = {
6660
+ ...gitUrl === void 0 ? {} : { gitUrl },
6661
+ deviceApprovers: deviceApprovers.map((email) => email.trim().toLowerCase()).filter((email) => email.length > 0)
6662
+ };
5608
6663
  if (isRemoteDatabase(database)) {
5609
6664
  const checked = assemble({
5610
6665
  name: "memory",