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

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 (404) 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-CtbmyR7f.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-ClHLI-NM.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-1a_GRSNg.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-BQErgQRj.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-D0dVdFCk.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-B8BpJ73Y.js +10 -0
  46. package/.output/public/assets/input-group-CIjTdxCW.js +1 -0
  47. package/.output/public/assets/insights-BrdBpqda.js +42 -0
  48. package/.output/public/assets/insights-DsmTCDix.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-BHmK7ufZ.js +1 -0
  54. package/.output/public/assets/insights_.distribution-BNNw0whH.js +2 -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-B6t0ZxKP.js +1 -0
  64. package/.output/public/assets/native-builds-CgPSpNsA.js +2 -0
  65. package/.output/public/assets/native-builds-TF9BhYrQ.js +1 -0
  66. package/.output/public/assets/native-builds_._buildId-2rPrtz9-.js +2 -0
  67. package/.output/public/assets/native-builds_._buildId-BqUOY1Az.js +1 -0
  68. package/.output/public/assets/native-builds_.devices-B9kLHngv.js +2 -0
  69. package/.output/public/assets/native-builds_.devices-COFYZcaA.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-DMooqgLf.js +1 -0
  78. package/.output/public/assets/routes-Z2IGj8MK.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-pdhJfnex.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 +1 -1
  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-Bbf_lM0q.mjs +26 -0
  107. package/.output/server/_ssr/ChannelPicker-D6dQe9hV.mjs +251 -0
  108. package/.output/server/_ssr/{ConsoleFeatureUnavailable-CGHVL37b.mjs → ConsoleFeatureUnavailable-cLOJizHM.mjs} +8 -8
  109. package/.output/server/_ssr/{EventDetails-DdJyaBZ5.mjs → EventDetails-Bf9A0sIH.mjs} +9 -9
  110. package/.output/server/_ssr/FoldedRows-CBXPkthB.mjs +152 -0
  111. package/.output/server/_ssr/HashValueDisplay-CTRuGnTF.mjs +65 -0
  112. package/.output/server/_ssr/{InsightsPageHeader-KtHEf8Q0.mjs → InsightsPageHeader-CZYqpzbC.mjs} +13 -13
  113. package/.output/server/_ssr/IosInstall-Dnv68fhL.mjs +767 -0
  114. package/.output/server/_ssr/NativeBuildsNav-Dg43O2Cd.mjs +39 -0
  115. package/.output/server/_ssr/{NotFoundPage-DZB6K98c.mjs → NotFoundPage-C0hUVtGq.mjs} +3 -3
  116. package/.output/server/_ssr/{PlatformIcon-CFLiTjh1.mjs → PlatformIcon-C22qEcwo.mjs} +13 -3
  117. package/.output/server/_ssr/QrCode-BbK966IU.mjs +50 -0
  118. package/.output/server/_ssr/RelativeTime-CdBbi7fL.mjs +242 -0
  119. package/.output/server/_ssr/{git-CTA8Aqr0.mjs → RolloutPercentageBadge-CaK9SkbN.mjs} +20 -4
  120. package/.output/server/_ssr/RowReason-Cg035uIk.mjs +59 -0
  121. package/.output/server/_ssr/SandboxBadge-Zta6e__x.mjs +85 -0
  122. package/.output/server/_ssr/TargetDisplay-DGqswOee.mjs +105 -0
  123. package/.output/server/_ssr/{alert-dialog-CDr-Nsoo.mjs → alert-dialog-DFz9lm_Y.mjs} +4 -4
  124. package/.output/server/_ssr/{api-DGWwi1WN.mjs → api-B2LCh6pv.mjs} +186 -39
  125. package/.output/server/_ssr/{api-keys-BBb3xSox.mjs → api-keys-BbtiHE85.mjs} +14 -11
  126. package/.output/server/_ssr/{api-keys-e_eDCNr2.mjs → api-keys-D3oOFnP9.mjs} +2 -2
  127. package/.output/server/_ssr/{api-keys-rpc-BXiXUAm9.mjs → api-keys-rpc-CJIR67Ch.mjs} +4 -4
  128. package/.output/server/_ssr/{api-rpc-CLreF5Vr.mjs → api-rpc-Bf7S-MaH.mjs} +83 -35
  129. package/.output/server/_ssr/{auth-rpc-Bbf80tQK.mjs → auth-rpc-Dp-DCqh6.mjs} +5 -5
  130. package/.output/server/_ssr/{auth.server-DGwe3eds.mjs → auth.server-Cc0ZRXjk.mjs} +1876 -358
  131. package/.output/server/_ssr/{badge-BXk5c2yv.mjs → badge-YEmoI1eN.mjs} +4 -45
  132. package/.output/server/_ssr/{bundleActivity-MLrjNJCT.mjs → bundleActivity-a-pEDiqu.mjs} +1 -1
  133. package/.output/server/_ssr/card-D0a_6Dhh.mjs +49 -0
  134. package/.output/server/_ssr/{config.server-BIBSZpZE.mjs → config.server-CZRoGrFp.mjs} +4 -4
  135. package/.output/server/_ssr/{console-access-Cwha8dww.mjs → console-access-OPT4g-IS.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-tjmlaM_N.mjs} +4 -4
  138. package/.output/server/_ssr/{console-features-rpc-5WFiUFxb.mjs → console-features-rpc-SlXJxyZV.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-D6bc51Xq.mjs} +5 -4
  144. package/.output/server/_ssr/deviceProfileToken-xzDLfE0T.mjs +98 -0
  145. package/.output/server/_ssr/{dialog-BG-juN_g.mjs → dialog-ChHbf-yX.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-jogqtpGm.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-Df_Q9TWZ.mjs} +3 -3
  152. package/.output/server/_ssr/foldedPage-CUjJqtlF.mjs +176 -0
  153. package/.output/server/_ssr/{getBundleChildren-rtkEEJw5.mjs → getBundleChildren-DDqsd1pL.mjs} +2 -2
  154. package/.output/server/_ssr/{input-group-rcPxMqYq.mjs → input-group-CVf7oJb7.mjs} +3 -3
  155. package/.output/server/_ssr/{insights-Din0R0k-.mjs → insights-CWe8WEnp.mjs} +93 -215
  156. package/.output/server/_ssr/{insights-BwEiSUUy.mjs → insights-DFSywrbh.mjs} +5 -5
  157. package/.output/server/_ssr/{insights-BDa6T_cj.mjs → insights-DIRlQAyF.mjs} +2 -2
  158. package/.output/server/_ssr/{insights-api-BESfPrTq.mjs → insights-api-C9rxV0Tn.mjs} +5 -5
  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-wIScA1Qn.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-BVt-dUJZ.mjs} +7 -7
  164. package/.output/server/_ssr/{insights-rpc-BdtBheBi.mjs → insights-rpc-BDQqwXjX.mjs} +4 -4
  165. package/.output/server/_ssr/{insights-search-BAaycSRp.mjs → insights-search-B56U9By9.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-C084r9Yl.mjs} +5 -5
  168. package/.output/server/_ssr/{insights-usage-rpc-DCkLNAlG.mjs → insights-usage-rpc-D6QC7xMU.mjs} +7 -7
  169. package/.output/server/_ssr/{insightsUsage-ClAmoUz8.mjs → insightsUsage-lPKyRC2o.mjs} +3 -3
  170. package/.output/server/_ssr/{insights_.distribution-5sgau7rB.mjs → insights_.distribution-BO1VAcAm.mjs} +5 -5
  171. package/.output/server/_ssr/{insights_.distribution-D4QQxZmG.mjs → insights_.distribution-CoTlEOe8.mjs} +16 -15
  172. package/.output/server/_ssr/{insights_.distribution-DoO2NDvS.mjs → insights_.distribution-DP1M7WJo.mjs} +2 -2
  173. package/.output/server/_ssr/{installations-C4MwFvp6.mjs → installations-BczGuyup.mjs} +13 -13
  174. package/.output/server/_ssr/{installations-CZZsFoXb.mjs → installations-CHXPyqGZ.mjs} +4 -4
  175. package/.output/server/_ssr/{installations-W6DXZ5Tp.mjs → installations-CY86CKgz.mjs} +2 -2
  176. package/.output/server/_ssr/ios-devices-rpc-B-9HHSKk.mjs +149 -0
  177. package/.output/server/_ssr/iosDeviceCookie-CZArbhzA.mjs +155 -0
  178. package/.output/server/_ssr/iosDeviceProfile-CxeXYxc-.mjs +176 -0
  179. package/.output/server/_ssr/iosDevices-Ckjp_S09.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-C2xGyB-t.mjs +273 -0
  184. package/.output/server/_ssr/native-builds-CKoFuBrT.mjs +698 -0
  185. package/.output/server/_ssr/{native-builds-BhBltXq2.mjs → native-builds-DGckAE3j.mjs} +3 -3
  186. package/.output/server/_ssr/native-builds_._buildId-BXfvqKmr.mjs +1204 -0
  187. package/.output/server/_ssr/{native-builds_._buildId-B5QgMg7D.mjs → native-builds_._buildId-EqbJ7R4A.mjs} +3 -3
  188. package/.output/server/_ssr/native-builds_.devices-BJ75om8d.mjs +10 -0
  189. package/.output/server/_ssr/native-builds_.devices-X6JpinwG.mjs +858 -0
  190. package/.output/server/_ssr/nativeBuildDownloadLink-BAfCV_k_.mjs +96 -0
  191. package/.output/server/_ssr/nativeBuildInstall-D2rK0m4j.mjs +256 -0
  192. package/.output/server/_ssr/nativeBuilds-B3LcuLs4.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-xKxB0Ir0.mjs} +9 -9
  198. package/.output/server/_ssr/{releaseAdoption-a2byXMfz.mjs → releaseAdoption-BNp2LKR5.mjs} +5 -4
  199. package/.output/server/_ssr/{releaseCatalogCompiler-DLcean2k.mjs → releaseCatalogCompiler-CLDa8DuR.mjs} +23 -11
  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-ByjC_BCV.mjs} +23 -22
  203. package/.output/server/_ssr/{remote-config-Wjia3haX.mjs → remote-config-DmEXPobC.mjs} +3 -3
  204. package/.output/server/_ssr/{remote-config-rpc-7Zvra2dm.mjs → remote-config-rpc-BNPLt44i.mjs} +5 -5
  205. package/.output/server/_ssr/{remote-config-D6YMPi4J.mjs → remote-config-w3s5hFj9.mjs} +2 -2
  206. package/.output/server/_ssr/request-guard-BPLyogIN.mjs +11 -0
  207. package/.output/server/_ssr/{router-CLK13IPD.mjs → router-C8NZ0bVd.mjs} +136 -63
  208. package/.output/server/_ssr/{routes-h_nOUmOr.mjs → routes-B8Gmx46E.mjs} +49 -17
  209. package/.output/server/_ssr/{routes-CbdYptnV.mjs → routes-DvpKW5gf.mjs} +495 -476
  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-DlahGhrf.mjs} +5 -5
  213. package/.output/server/_ssr/{select-BdzEzz-x.mjs → select-Csnyblf2.mjs} +12 -10
  214. package/.output/server/_ssr/{server-CddZkHk2.mjs → server-Yr7QLPLj.mjs} +7 -7
  215. package/.output/server/_ssr/{sidebar-DabmjV5E.mjs → sidebar-bKoOUlMN.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-C-HJ8oZV.mjs} +4 -4
  219. package/.output/server/_ssr/{table-DP978C4F.mjs → table-DSB_9Amh.mjs} +2 -2
  220. package/.output/server/_ssr/tabs-DRTBxZTO.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-MJAIGQWT.mjs +229 -0
  226. package/.output/server/index.mjs +493 -381
  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/BundleIdDisplay.tsx +30 -3
  231. package/src/components/ChannelBadge.tsx +9 -9
  232. package/src/components/ChannelPicker.tsx +227 -0
  233. package/src/components/DataTable.tsx +363 -0
  234. package/src/components/FoldedRows.tsx +219 -0
  235. package/src/components/HashValueDisplay.tsx +27 -8
  236. package/src/components/PlatformIcon.tsx +10 -0
  237. package/src/components/RelativeTime.tsx +31 -0
  238. package/src/components/RowReason.tsx +63 -0
  239. package/src/components/TargetDisplay.tsx +95 -0
  240. package/src/components/ThemeProvider.tsx +11 -2
  241. package/src/components/features/api-keys/ApiKeysPage.tsx +5 -3
  242. package/src/components/features/bundles/BundleMetadata.tsx +22 -1
  243. package/src/components/features/bundles/RolloutCohortsDialog.tsx +8 -1
  244. package/src/components/features/channels/ChannelManagementDialog.tsx +10 -11
  245. package/src/components/features/insights/AppUsage.tsx +3 -5
  246. package/src/components/features/insights/ComparedBundlesChart.tsx +1 -0
  247. package/src/components/features/insights/FailureReports.tsx +3 -2
  248. package/src/components/features/insights/InsightsControls.tsx +38 -73
  249. package/src/components/features/insights/InsightsOverview.tsx +10 -2
  250. package/src/components/features/insights/InsightsPageHeader.tsx +10 -15
  251. package/src/components/features/insights/ReleaseActivity.tsx +6 -2
  252. package/src/components/features/insights/ReleaseCombobox.tsx +8 -3
  253. package/src/components/features/insights/RollbackButton.tsx +1 -1
  254. package/src/components/features/insights/UpdateFailures.tsx +36 -10
  255. package/src/components/features/native-builds/BuiltInBundleCard.tsx +125 -63
  256. package/src/components/features/native-builds/CommitLink.tsx +3 -2
  257. package/src/components/features/native-builds/ImportBuild.tsx +1 -1
  258. package/src/components/features/native-builds/InstallCard.tsx +378 -93
  259. package/src/components/features/native-builds/IosDevicesPage.tsx +1145 -0
  260. package/src/components/features/native-builds/IosInstall.tsx +732 -0
  261. package/src/components/features/native-builds/IpaDevicesCard.tsx +123 -0
  262. package/src/components/features/native-builds/NativeBuildDetailPage.tsx +45 -9
  263. package/src/components/features/native-builds/NativeBuildsNav.tsx +45 -0
  264. package/src/components/features/native-builds/NativeBuildsPage.tsx +94 -108
  265. package/src/components/features/native-builds/NativeBuildsTable.tsx +652 -323
  266. package/src/components/features/native-builds/OlderBuildLabel.tsx +61 -0
  267. package/src/components/features/native-builds/PatchesCard.tsx +28 -19
  268. package/src/components/features/native-builds/ReleaseNativeBuildLink.tsx +5 -5
  269. package/src/components/features/native-builds/SandboxBadge.tsx +21 -0
  270. package/src/components/features/native-builds/ServedNowCard.tsx +39 -4
  271. package/src/components/features/native-builds/ShortHash.tsx +6 -3
  272. package/src/components/features/native-builds/StoreSubmission.tsx +18 -12
  273. package/src/components/features/native-builds/playTracks.ts +7 -0
  274. package/src/components/features/releases/ReleaseEditorSheet.tsx +14 -9
  275. package/src/components/features/remote-config/PublishDialog.tsx +4 -1
  276. package/src/components/features/remote-config/VersionsCard.tsx +5 -2
  277. package/src/components/ui/alert-dialog.tsx +2 -2
  278. package/src/components/ui/badge.tsx +2 -0
  279. package/src/components/ui/button.tsx +11 -2
  280. package/src/components/ui/combobox.tsx +2 -2
  281. package/src/components/ui/dialog.tsx +3 -3
  282. package/src/components/ui/input.tsx +1 -1
  283. package/src/components/ui/select.tsx +15 -7
  284. package/src/components/ui/sheet.tsx +1 -1
  285. package/src/components/ui/sidebar.tsx +2 -2
  286. package/src/components/ui/slider.tsx +1 -1
  287. package/src/components/ui/sonner.tsx +3 -1
  288. package/src/components/ui/switch.tsx +1 -1
  289. package/src/components/ui/tabs.tsx +1 -1
  290. package/src/components/ui/textarea.tsx +1 -1
  291. package/src/index.ts +9 -0
  292. package/src/lib/api-rpc.ts +125 -35
  293. package/src/lib/api.ts +171 -16
  294. package/src/lib/constants.ts +18 -0
  295. package/src/lib/insights-search.ts +0 -3
  296. package/src/lib/ios-devices-api.ts +304 -0
  297. package/src/lib/ios-devices-rpc.ts +215 -0
  298. package/src/lib/native-builds.ts +269 -20
  299. package/src/lib/release-adoption.ts +2 -0
  300. package/src/lib/schema-migration-rpc.ts +1 -1
  301. package/src/lib/server/console-runtime.server.ts +9 -2
  302. package/src/lib/server/deviceProfileToken.ts +221 -0
  303. package/src/lib/server/foldedPage.ts +360 -0
  304. package/src/lib/server/iosDeviceCookie.ts +239 -0
  305. package/src/lib/server/iosDeviceProfile.ts +232 -0
  306. package/src/lib/server/iosDevices.ts +232 -0
  307. package/src/lib/server/listReleases.ts +101 -62
  308. package/src/lib/server/local-console.ts +1 -1
  309. package/src/lib/server/nativeBuildDownloadLink.ts +193 -0
  310. package/src/lib/server/nativeBuildInstall.ts +513 -0
  311. package/src/lib/server/nativeBuilds.ts +327 -59
  312. package/src/lib/server/plistText.ts +17 -0
  313. package/src/lib/server/publicConsoleBase.ts +17 -0
  314. package/src/lib/server/releaseAdoption.ts +1 -0
  315. package/src/lib/server/updateFailures.ts +6 -1
  316. package/src/routeTree.gen.ts +129 -18
  317. package/src/routes/-native-builds-search.ts +61 -4
  318. package/src/routes/-releases-search.ts +63 -2
  319. package/src/routes/[_]hot-updater/devices/device-response.ts +21 -0
  320. package/src/routes/[_]hot-updater/devices/device[.]mobileconfig.ts +17 -0
  321. package/src/routes/[_]hot-updater/devices/receipt.ts +28 -0
  322. package/src/routes/[_]hot-updater/devices/request.ts +28 -0
  323. package/src/routes/[_]hot-updater/native-builds/$buildId/manifest[.]plist.ts +22 -0
  324. package/src/routes/api/native-builds/$buildId/download.ts +22 -1
  325. package/src/routes/index.tsx +662 -578
  326. package/src/routes/insights.tsx +3 -5
  327. package/src/routes/insights_.distribution.tsx +2 -2
  328. package/src/routes/native-builds_.devices.tsx +21 -0
  329. package/src/styles.css +24 -0
  330. package/.output/public/assets/-native-builds-search-C-TGpFAm.js +0 -1
  331. package/.output/public/assets/EventDetails-Dl2RvPAk.js +0 -1
  332. package/.output/public/assets/HashValueDisplay-6lNRxDJX.js +0 -1
  333. package/.output/public/assets/InsightsPageHeader-DHhqY3DT.js +0 -1
  334. package/.output/public/assets/RolloutPercentageBadge-Cxogpi8F.js +0 -1
  335. package/.output/public/assets/StoreSubmission-ViTkW4eJ.js +0 -1
  336. package/.output/public/assets/alert-dialog-BqYScr9y.js +0 -1
  337. package/.output/public/assets/api-P2g8dCNg.js +0 -1
  338. package/.output/public/assets/api-keys-DWQC2q6y.js +0 -1
  339. package/.output/public/assets/api-keys-FueRkF9q.js +0 -1
  340. package/.output/public/assets/arrow-left-g9cKqXuC.js +0 -1
  341. package/.output/public/assets/arrow-right-CNII8TYn.js +0 -1
  342. package/.output/public/assets/arrow-up-right-DK8Zdg40.js +0 -1
  343. package/.output/public/assets/badge-DWFcDWho.js +0 -1
  344. package/.output/public/assets/check-CXVR3s3X.js +0 -1
  345. package/.output/public/assets/chevron-right-BoUXo82O.js +0 -1
  346. package/.output/public/assets/dialog-CNUPxNxH.js +0 -1
  347. package/.output/public/assets/dist-CPlO6ko9.js +0 -1
  348. package/.output/public/assets/empty-B3Uwdd6k.js +0 -1
  349. package/.output/public/assets/field-D-2-mnNh.js +0 -1
  350. package/.output/public/assets/history-DqHlgSuV.js +0 -1
  351. package/.output/public/assets/index-CqP5HPV6.js +0 -10
  352. package/.output/public/assets/input-group-D3OUBk4n.js +0 -1
  353. package/.output/public/assets/insights-B-0odqpt.js +0 -42
  354. package/.output/public/assets/insights-BSVGfxSL.js +0 -1
  355. package/.output/public/assets/insights-NK5B6ReS.js +0 -2
  356. package/.output/public/assets/insights-api-BVCXJsoV.js +0 -1
  357. package/.output/public/assets/insights-search-DghCbEnk.js +0 -1
  358. package/.output/public/assets/insights-usage-rpc-CKQH0pUS.js +0 -1
  359. package/.output/public/assets/insights_.distribution-CJvgwcVZ.js +0 -2
  360. package/.output/public/assets/insights_.distribution-DblZM0mO.js +0 -1
  361. package/.output/public/assets/insights_.distribution-dvk6vYDM.js +0 -1
  362. package/.output/public/assets/installations-B674P5Z5.js +0 -2
  363. package/.output/public/assets/installations-BWxczZ2t.js +0 -1
  364. package/.output/public/assets/installations-Dv4kWQYz.js +0 -1
  365. package/.output/public/assets/native-builds-BOC71grI.js +0 -1
  366. package/.output/public/assets/native-builds-D6rldpSh.js +0 -2
  367. package/.output/public/assets/native-builds-DAy2678K.js +0 -1
  368. package/.output/public/assets/native-builds_._buildId-DD58_Phd.js +0 -1
  369. package/.output/public/assets/native-builds_._buildId-DvQDKnUQ.js +0 -2
  370. package/.output/public/assets/plus-BReVKct-.js +0 -1
  371. package/.output/public/assets/preload-helper-B44EvKhG.js +0 -1
  372. package/.output/public/assets/refresh-cw-B9HHjLej.js +0 -1
  373. package/.output/public/assets/remote-config-B7ujqhLa.js +0 -6
  374. package/.output/public/assets/remote-config-WjpozBG5.js +0 -1
  375. package/.output/public/assets/remote-config-gXeH6PBW.js +0 -1
  376. package/.output/public/assets/routes-BDdBIxYS.js +0 -1
  377. package/.output/public/assets/routes-CCD33Azv.js +0 -2
  378. package/.output/public/assets/search-BCel4Oy6.js +0 -1
  379. package/.output/public/assets/select-CBIU0_M1.js +0 -1
  380. package/.output/public/assets/sidebar-Di9SN47G.js +0 -3
  381. package/.output/public/assets/smartphone-CMaSy_ir.js +0 -1
  382. package/.output/public/assets/styles-uK-0vUMk.css +0 -2
  383. package/.output/public/assets/switch-BpdiHL_t.js +0 -1
  384. package/.output/public/assets/table-Bpy3SvSo.js +0 -1
  385. package/.output/public/assets/tabs-Xmt7tZeG.js +0 -1
  386. package/.output/public/assets/useCompositeListItem-JmyDfo3-.js +0 -1
  387. package/.output/public/assets/useInfiniteQuery-DX4WpBRG.js +0 -1
  388. package/.output/public/assets/valueToPercent-BLwGy_xK.js +0 -1
  389. package/.output/server/_ssr/-native-builds-search-CwNcoXf4.mjs +0 -37
  390. package/.output/server/_ssr/BundleIdDisplay-CFz1sCQl.mjs +0 -13
  391. package/.output/server/_ssr/HashValueDisplay-B85-LoBW.mjs +0 -55
  392. package/.output/server/_ssr/RolloutPercentageBadge-CKFY5OIh.mjs +0 -21
  393. package/.output/server/_ssr/StoreSubmission-CNukW8xF.mjs +0 -139
  394. package/.output/server/_ssr/listReleases-D_GY00SQ.mjs +0 -79
  395. package/.output/server/_ssr/native-builds-CoOxssXa.mjs +0 -510
  396. package/.output/server/_ssr/native-builds-DhXL5zf_.mjs +0 -137
  397. package/.output/server/_ssr/native-builds_._buildId-CysSVBT5.mjs +0 -813
  398. package/.output/server/_ssr/nativeBuildQr-84cnFQPX.mjs +0 -59
  399. package/.output/server/_ssr/nativeBuilds-B_7BPjt_.mjs +0 -133
  400. package/.output/server/_ssr/qr-code-C7kNRIDX.mjs +0 -22
  401. package/.output/server/_ssr/tabs-kQRMEiQT.mjs +0 -45
  402. package/.output/server/_tanstack-start-manifest_v-B5nsO5L4.mjs +0 -184
  403. package/src/lib/server/nativeBuildQr.ts +0 -73
  404. 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-D6bc51Xq.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-CLDa8DuR.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-Cc0ZRXjk.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);
@@ -892,7 +893,11 @@ var releases = defineTable({
892
893
  }
893
894
  },
894
895
  created_at_ms: { type: "integer" },
895
- updated_at_ms: { type: "integer" }
896
+ updated_at_ms: { type: "integer" },
897
+ label: {
898
+ type: "integer",
899
+ required: false
900
+ }
896
901
  }, {
897
902
  key: ["id"],
898
903
  indexes: {
@@ -925,9 +930,46 @@ var releases = defineTable({
925
930
  all: {
926
931
  eq: [],
927
932
  sort: ["id"]
933
+ },
934
+ scopes: {
935
+ eq: [],
936
+ sort: ["scope_key"]
937
+ },
938
+ byLabel: {
939
+ eq: [
940
+ "channel_id",
941
+ "platform",
942
+ "label"
943
+ ],
944
+ sort: [],
945
+ unique: true
928
946
  }
929
947
  }
930
948
  });
949
+ /**
950
+ * One counter per sequence: `releases/<platform>/<channel ID>` holds the
951
+ * last label that channel and platform's releases took. A deploy or a
952
+ * promote reads it and writes the next value in the transaction that writes
953
+ * the release, so two writers never take one label. `is_filled` is true once
954
+ * every release of the sequence written before labels has one, in ID order;
955
+ * until then a writer fills them first. Deleting a channel deletes its
956
+ * counters, so a channel created again with the name starts at 1.
957
+ */
958
+ var labelSequences = defineTable({
959
+ id: {
960
+ type: "string",
961
+ maxLength: 1440,
962
+ ascii: true
963
+ },
964
+ last_label: { type: "integer" },
965
+ is_filled: { type: "boolean" }
966
+ }, {
967
+ key: ["id"],
968
+ indexes: { all: {
969
+ eq: [],
970
+ sort: ["id"]
971
+ } }
972
+ });
931
973
  /** One compiled catalog per scope; the update check reads exactly this row. */
932
974
  var releaseCatalogs = defineTable({
933
975
  scope_key: {
@@ -997,7 +1039,10 @@ var channels = defineTable({
997
1039
  /**
998
1040
  * The native builds `native-build android` and `native-build ios` track, newest first
999
1041
  * 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,
1042
+ * the build compiled in. A sandbox build's scope has no channel: its app ID,
1043
+ * URL scheme, artifact kind and distribution in its place, so pull requests
1044
+ * reuse it across channels, while `channel_id` still names the channel it
1045
+ * embeds. `min_bundle_id` names the build's built-in bundle,
1001
1046
  * a `bundles` row no release publishes. Its references keep no counters, so
1002
1047
  * adding this table changes no existing one; a channel with builds is
1003
1048
  * refused deletion through `byChannel`. `build_key` is the native build key
@@ -1007,6 +1052,27 @@ var channels = defineTable({
1007
1052
  * or `versionCode`. `submitted_to`, `submitted_at_ms` and
1008
1053
  * `submitted_version` record the store track a build went to, when, and
1009
1054
  * the store's label of the build; they stay null for a build no store took.
1055
+ * `is_store_build` is true on the build a person or a job says the store
1056
+ * sells, and false on every other: deploys patch from it over the scope's
1057
+ * newest build. The engine copies the scope key into `store_build_scope_key`
1058
+ * for that build alone, so `byStoreBuild` holds one entry per scope at most,
1059
+ * on every store, while any number of a scope's builds hold none.
1060
+ * `is_sandbox` is true on a sandbox build, set from its artifact when it
1061
+ * registers and never changed, and `sandbox_url_scheme` is the URL scheme its artifact registers,
1062
+ * which its preview links open; null on any other build, and on a sandbox
1063
+ * build registered before the column, which registered the derived one.
1064
+ * `export_method` is how an `.ipa` was exported, read from its profile when
1065
+ * it registers and never changed; null on any other artifact, on an `.ipa`
1066
+ * whose profile couldn't be read, and on one registered before the column.
1067
+ * `native_app_version` is the app version the artifact itself reports, its
1068
+ * `CFBundleShortVersionString` or `versionName`, read from the artifact when
1069
+ * it registers and never changed, whatever the update strategy; `app_version`
1070
+ * stays the version OTAs target, null on a fingerprint build. It is null
1071
+ * when the artifact's can't be read, and on a build registered before the
1072
+ * column.
1073
+ * Boolean columns follow one rule: `is_*` for a fact about the row or
1074
+ * `should_*` for an instruction to the client, never null; a unique index over
1075
+ * the rows where one is true keys a derived slot, not the boolean.
1010
1076
  */
1011
1077
  var nativeBuilds = defineTable({
1012
1078
  id: {
@@ -1083,9 +1149,32 @@ var nativeBuilds = defineTable({
1083
1149
  type: "string",
1084
1150
  maxLength: 255,
1085
1151
  required: false
1152
+ },
1153
+ is_store_build: { type: "boolean" },
1154
+ is_sandbox: { type: "boolean" },
1155
+ sandbox_url_scheme: {
1156
+ type: "string",
1157
+ maxLength: 255,
1158
+ ascii: true,
1159
+ required: false
1160
+ },
1161
+ export_method: {
1162
+ type: "string",
1163
+ maxLength: 16,
1164
+ required: false
1165
+ },
1166
+ native_app_version: {
1167
+ type: "string",
1168
+ required: false
1086
1169
  }
1087
1170
  }, {
1088
1171
  key: ["id"],
1172
+ derived: { store_build_scope_key: {
1173
+ type: "string",
1174
+ maxLength: 2048,
1175
+ ascii: true,
1176
+ compute: (row) => row.is_store_build ? row.scope_key : null
1177
+ } },
1089
1178
  indexes: {
1090
1179
  byScope: {
1091
1180
  eq: ["scope_key"],
@@ -1095,6 +1184,15 @@ var nativeBuilds = defineTable({
1095
1184
  eq: ["scope_key", "build_key"],
1096
1185
  sort: ["id"]
1097
1186
  },
1187
+ byScopeKind: {
1188
+ eq: ["scope_key", "artifact_kind"],
1189
+ sort: ["id"]
1190
+ },
1191
+ byStoreBuild: {
1192
+ eq: ["store_build_scope_key"],
1193
+ sort: [],
1194
+ unique: true
1195
+ },
1098
1196
  byChannel: {
1099
1197
  eq: ["channel_id"],
1100
1198
  sort: ["id"],
@@ -1106,6 +1204,119 @@ var nativeBuilds = defineTable({
1106
1204
  }
1107
1205
  }
1108
1206
  });
1207
+ /**
1208
+ * The iPhones a team asks to install ad hoc builds on. A row decides what the
1209
+ * CLI registers with Apple, not what an export includes: Xcode's automatic ad
1210
+ * hoc profile lists every device the Apple account has enabled. `status` is
1211
+ * `pending` until someone approves it, `approved` until a build or
1212
+ * `native-build devices add` registers it with Apple, then `registered`;
1213
+ * declining or removing one deletes its row. `udid` is the UDID in lower case.
1214
+ * `apple_issuer_id` is the App Store Connect issuer whose key registered it,
1215
+ * set once: a build signed by another account never registers these rows.
1216
+ * `apple_error` is Apple's refusal of the device, or why it stopped counting
1217
+ * it, cleared by the next success. `build_id` is the newest native build whose
1218
+ * .ipa the CLI checked lists it; deleting that build never touches the row.
1219
+ * It holds personal data: a UDID, a name, and the emails of who asked and who
1220
+ * approved, null for the CLI.
1221
+ */
1222
+ var iosDevices = defineTable({
1223
+ id: {
1224
+ type: "string",
1225
+ maxLength: 36
1226
+ },
1227
+ udid: {
1228
+ type: "string",
1229
+ maxLength: 40,
1230
+ ascii: true,
1231
+ unique: true
1232
+ },
1233
+ name: {
1234
+ type: "string",
1235
+ maxLength: 100
1236
+ },
1237
+ status: {
1238
+ type: "string",
1239
+ maxLength: 16
1240
+ },
1241
+ requested_by: {
1242
+ type: "string",
1243
+ maxLength: 320,
1244
+ required: false
1245
+ },
1246
+ created_at_ms: { type: "integer" },
1247
+ approved_by: {
1248
+ type: "string",
1249
+ maxLength: 320,
1250
+ required: false
1251
+ },
1252
+ approved_at_ms: {
1253
+ type: "integer",
1254
+ required: false
1255
+ },
1256
+ registered_at_ms: {
1257
+ type: "integer",
1258
+ required: false
1259
+ },
1260
+ apple_issuer_id: {
1261
+ type: "string",
1262
+ maxLength: 64,
1263
+ ascii: true,
1264
+ required: false
1265
+ },
1266
+ apple_error: {
1267
+ type: "string",
1268
+ maxLength: 512,
1269
+ required: false
1270
+ },
1271
+ build_id: {
1272
+ type: "string",
1273
+ maxLength: 36,
1274
+ required: false
1275
+ }
1276
+ }, {
1277
+ key: ["id"],
1278
+ indexes: {
1279
+ byStatus: {
1280
+ eq: ["status"],
1281
+ sort: ["id"]
1282
+ },
1283
+ byRegistration: {
1284
+ eq: [],
1285
+ sort: ["registered_at_ms"]
1286
+ },
1287
+ all: {
1288
+ eq: [],
1289
+ sort: ["id"]
1290
+ }
1291
+ }
1292
+ });
1293
+ /**
1294
+ * The Apple account the iOS device registry belongs to: one row, keyed
1295
+ * `registry`, holding the App Store Connect issuer that first registered a
1296
+ * device. A build claims it before it sends Apple anything, and its key makes
1297
+ * the claim atomic on every store, so two builds of two accounts can't both
1298
+ * spend a slot; another account's build then registers nothing. Removing
1299
+ * devices never releases it.
1300
+ */
1301
+ var iosDeviceAccount = defineTable({
1302
+ id: {
1303
+ type: "string",
1304
+ maxLength: 16,
1305
+ ascii: true
1306
+ },
1307
+ apple_issuer_id: {
1308
+ type: "string",
1309
+ maxLength: 64,
1310
+ ascii: true
1311
+ },
1312
+ claimed_at_ms: { type: "integer" }
1313
+ }, {
1314
+ key: ["id"],
1315
+ indexes: { all: {
1316
+ eq: [],
1317
+ sort: ["id"]
1318
+ } }
1319
+ });
1109
1320
  /** Core's module: always installed, never a plugin. */
1110
1321
  var coreModule = {
1111
1322
  id: "core",
@@ -1126,7 +1337,10 @@ var coreModule = {
1126
1337
  sort: []
1127
1338
  } }
1128
1339
  }),
1129
- native_builds: nativeBuilds
1340
+ native_builds: nativeBuilds,
1341
+ ios_devices: iosDevices,
1342
+ ios_device_account: iosDeviceAccount,
1343
+ label_sequences: labelSequences
1130
1344
  }
1131
1345
  };
1132
1346
  var encoder = new TextEncoder();
@@ -1286,18 +1500,17 @@ var LEASE_TABLE = "aggregate_lease";
1286
1500
  var LEASE = { id: "compaction" };
1287
1501
  /** How long a compaction holds the lease before another process may take it. */
1288
1502
  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
- };
1503
+ /** A commit compacts once this has passed since the last compaction. */
1504
+ var WINDOW_MS = 6e4;
1298
1505
  /** Log rows a compaction reads from each log table for one group. */
1299
1506
  var LOG_PAGE = 200;
1300
1507
  /**
1508
+ * How old a log row this process can't apply must be before its reads step
1509
+ * past it: older than any transaction still committing, between servers
1510
+ * whose clocks agree this closely.
1511
+ */
1512
+ var SKIP_AFTER_MS = 3e5;
1513
+ /**
1301
1514
  * Groups one compaction applies: after a commit, so the request that runs
1302
1515
  * it waits for one group; before a read; and on flush.
1303
1516
  */
@@ -1308,8 +1521,6 @@ var GROUPS = {
1308
1521
  };
1309
1522
  /** Tries per write after a conflict or a transient error. */
1310
1523
  var ATTEMPTS = 5;
1311
- /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
1312
- var MAX_BUFFERED = 1e4;
1313
1524
  var log = defineTable({
1314
1525
  id: {
1315
1526
  type: "string",
@@ -1358,7 +1569,7 @@ var valuesOf = ({ deltas, sketches }) => ({
1358
1569
  /**
1359
1570
  * Merges `values` into the change for `key`'s identity as `tx.aggregate`
1360
1571
  * does: deltas add up and sketches merge. One constant `shardBy` keys each
1361
- * identity to one entry; the write picks the shard.
1572
+ * identity to one entry; `compile` writes it to shard 0.
1362
1573
  */
1363
1574
  var merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
1364
1575
  var mergeAll = (into, changes) => {
@@ -1392,7 +1603,7 @@ var increment = ({ model, deltas }, key) => Object.values(deltas).some((delta) =
1392
1603
  /**
1393
1604
  * The guarded write that merges `change` into `current`: insert, patch, or
1394
1605
  * 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.
1606
+ * group can hold a loss without the gain before it, and reads sum every shard.
1396
1607
  */
1397
1608
  var rewrite = (change, key, current) => {
1398
1609
  const { model } = change;
@@ -1429,23 +1640,41 @@ var rewrite = (change, key, current) => {
1429
1640
  previous: current
1430
1641
  };
1431
1642
  };
1643
+ /** A shard row's place in what `readCurrent` read. */
1644
+ var rowId = (model, key) => JSON.stringify([model.table.name, key]);
1645
+ /** The shard key each change writes: shard 0, since one compaction runs at a time. */
1646
+ var keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
1432
1647
  /**
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.
1648
+ * The current rows of the changes that rewrite theirs (gauges and sketches),
1649
+ * each once, in one batch per table.
1436
1650
  */
1437
- var compile = async (adapter, changes, shard) => {
1438
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
1651
+ var readCurrent = async (adapter, changes) => {
1652
+ const keys = keysOf(changes);
1439
1653
  const reads = /* @__PURE__ */ new Map();
1440
1654
  changes.forEach((change, at) => {
1441
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
1655
+ if (!rewrites(change)) return;
1656
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
1657
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
1658
+ reads.set(change.model, wanted);
1442
1659
  });
1443
1660
  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));
1661
+ await Promise.all([...reads].map(async ([model, wanted]) => {
1662
+ const keys = [...wanted.values()];
1663
+ const rows = await adapter.get(model.table, keys);
1664
+ keys.forEach((key, at) => {
1665
+ current.set(rowId(model, key), rows[at] ?? null);
1666
+ });
1447
1667
  }));
1448
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
1668
+ return current;
1669
+ };
1670
+ /**
1671
+ * The write for each change: a blind increment that creates the row for
1672
+ * counters, and a guarded rewrite for gauges and sketches, over the rows
1673
+ * `current` read.
1674
+ */
1675
+ var build = (changes, current) => {
1676
+ const keys = keysOf(changes);
1677
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
1449
1678
  };
1450
1679
  var isOp = (op) => op !== void 0;
1451
1680
  var sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
@@ -1489,14 +1718,13 @@ var encode = async (changes) => {
1489
1718
  return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
1490
1719
  };
1491
1720
  /**
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.
1721
+ * Batches changes to aggregates declared `batched`. A transaction writes
1722
+ * them as one log row in its own atomic write, in place of their rows; a
1723
+ * compaction later merges log rows into the aggregates and deletes them,
1724
+ * atomically again, so each applies exactly once. One lease row keeps
1725
+ * compactions one at a time.
1498
1726
  */
1499
- var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS[mode] }, now }) => {
1727
+ var createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS }, now }) => {
1500
1728
  if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
1501
1729
  const holder = crypto.randomUUID().replaceAll("-", "");
1502
1730
  const table = (name) => schema.models.get(name).table;
@@ -1524,72 +1752,20 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1524
1752
  }
1525
1753
  return changes;
1526
1754
  };
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
1755
  let nextDue = 0;
1590
1756
  let compacting;
1591
1757
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
1592
1758
  const known = /* @__PURE__ */ new Map();
1759
+ /**
1760
+ * Each log table's last row of a run at its head that this process can't
1761
+ * apply (it names an aggregate or metric this schema lacks), whose reads
1762
+ * start past it. The rows wait for a process that can apply them, and a
1763
+ * restart reads them again.
1764
+ */
1765
+ const skipped = LOG_TABLES.map(() => void 0);
1766
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
1767
+ /** When a log row's transaction stamped its ID. */
1768
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
1593
1769
  const idOf = (shard, id) => JSON.stringify([shard, id]);
1594
1770
  /** The lease row as stored once `set` is written over it. */
1595
1771
  const leaseOp = (held, set) => {
@@ -1705,14 +1881,22 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1705
1881
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
1706
1882
  const page = await engine.reads.findMany(name, {
1707
1883
  index: "oldest",
1708
- limit: LOG_PAGE
1884
+ limit: LOG_PAGE,
1885
+ ...past(shard)
1709
1886
  });
1710
1887
  more ||= page.next !== void 0;
1711
- return (await Promise.all(page.rows.map(async (row) => ({
1888
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
1712
1889
  shard,
1713
1890
  row,
1714
1891
  changes: await decode(String(row.changes))
1715
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
1892
+ })));
1893
+ const settled = now() - SKIP_AFTER_MS;
1894
+ for (const { row, changes } of decoded) {
1895
+ const id = String(row.id);
1896
+ if (changes !== void 0 || stampOf(id) >= settled) break;
1897
+ skipped[shard] = id;
1898
+ }
1899
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
1716
1900
  ...entry,
1717
1901
  changes
1718
1902
  }]);
@@ -1720,7 +1904,6 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1720
1904
  more
1721
1905
  };
1722
1906
  };
1723
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
1724
1907
  /**
1725
1908
  * Applies the oldest pending log rows whose merged changes fit in one
1726
1909
  * atomic write with the lease, which lists them as applied; the rows are
@@ -1729,12 +1912,14 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1729
1912
  * log rows it applied whole, or undefined when a conflict stopped it.
1730
1913
  */
1731
1914
  const applyGroup = async (held, logs) => {
1915
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
1916
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
1732
1917
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
1733
1918
  const batch = logs.slice(0, count);
1734
1919
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
1735
1920
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
1736
1921
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
1737
- const ops = [...await rowsFor([...changes.values()]), lease.op];
1922
+ const ops = [...rowsFor([...changes.values()]), lease.op];
1738
1923
  if (!adapter.fits(ops)) continue;
1739
1924
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
1740
1925
  return await commit(ops) ? {
@@ -1756,7 +1941,7 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1756
1941
  };
1757
1942
  const lease = leaseOp(held, {});
1758
1943
  const ops = [
1759
- ...await rowsFor(entries.slice(0, take)),
1944
+ ...rowsFor(entries.slice(0, take)),
1760
1945
  kept,
1761
1946
  lease.op
1762
1947
  ];
@@ -1777,11 +1962,12 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1777
1962
  if (held === void 0) return;
1778
1963
  let pending = true;
1779
1964
  let clear = false;
1965
+ let carried;
1780
1966
  try {
1781
1967
  for (let group = 0;; group += 1) {
1782
1968
  clear = await deleteApplied(held);
1783
1969
  if (!clear || !pending || group === groups) break;
1784
- const { logs, more } = await readLogs();
1970
+ const { logs, more } = carried ?? await readLogs();
1785
1971
  if (logs.length === 0) {
1786
1972
  pending = false;
1787
1973
  break;
@@ -1789,6 +1975,11 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1789
1975
  const applied = await applyGroup(held, logs);
1790
1976
  if (applied === void 0) break;
1791
1977
  [held, clear] = [applied.held, false];
1978
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
1979
+ carried = rest.length > 0 ? {
1980
+ logs: rest,
1981
+ more
1982
+ } : void 0;
1792
1983
  pending = more || applied.count < logs.length;
1793
1984
  }
1794
1985
  } finally {
@@ -1808,26 +1999,13 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1808
1999
  });
1809
2000
  let checking;
1810
2001
  /** 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, {
2002
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
1812
2003
  index: "oldest",
1813
- limit: 1
2004
+ limit: 1,
2005
+ ...past(shard)
1814
2006
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
1815
2007
  checking = void 0;
1816
2008
  });
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
2009
  return {
1832
2010
  async transaction(fn) {
1833
2011
  let changes = /* @__PURE__ */ new Map();
@@ -1853,7 +2031,7 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1853
2031
  aggregate
1854
2032
  });
1855
2033
  if (failure) throw failure.error;
1856
- if (mode === "log" && attempt.size > 0) {
2034
+ if (attempt.size > 0) {
1857
2035
  const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
1858
2036
  const shard = Math.floor(Math.random() * LOG_TABLES.length);
1859
2037
  const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
@@ -1867,24 +2045,18 @@ var createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log
1867
2045
  open = false;
1868
2046
  }
1869
2047
  });
1870
- if (changes.size > 0) await committed(changes);
2048
+ if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
1871
2049
  return result;
1872
2050
  },
1873
2051
  async beforeRead(name) {
1874
2052
  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
- }
2053
+ if (await hasPending().catch((error) => {
2054
+ warn("read")(error);
2055
+ return false;
2056
+ })) await compact(true, GROUPS.read);
1882
2057
  },
1883
- flush,
1884
- async dispose() {
1885
- clearTimeout(timer);
1886
- timer = void 0;
1887
- await flush();
2058
+ async flush() {
2059
+ if (await hasPending()) await compact(true, GROUPS.flush);
1888
2060
  }
1889
2061
  };
1890
2062
  };
@@ -2022,7 +2194,8 @@ var fieldProblems = (definition, add) => {
2022
2194
  else if (field.required === false) add(`key field "${name}" is nullable`);
2023
2195
  else if (field.type === "json") add(`key field "${name}" is json`);
2024
2196
  }
2025
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
2197
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
2198
+ for (const [name, { type, maxLength, ascii }] of bounded) {
2026
2199
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
2027
2200
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
2028
2201
  }
@@ -2139,11 +2312,13 @@ var resolveSchema = (modules) => {
2139
2312
  ...maxLength === void 0 ? {} : { maxLength },
2140
2313
  ...ascii ? { ascii } : {}
2141
2314
  }));
2142
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
2315
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
2143
2316
  name: field,
2144
2317
  type,
2145
2318
  nullable: true,
2146
- ...multi ? { multi } : {}
2319
+ ...multi ? { multi } : {},
2320
+ ...maxLength === void 0 ? {} : { maxLength },
2321
+ ...ascii ? { ascii } : {}
2147
2322
  });
2148
2323
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
2149
2324
  name: metric,
@@ -2186,6 +2361,12 @@ var pluginModule = ({ id, schema, namespace }) => ({
2186
2361
  /** A row this attempt read changed while it ran; the attempt reruns. */
2187
2362
  var StaleReadError = class extends Error {};
2188
2363
  var idOf = (table, key) => JSON.stringify([table, key]);
2364
+ /** The aggregate rows a write changes, at the versions it read them. */
2365
+ var versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
2366
+ op.table.name,
2367
+ op.key,
2368
+ "guard" in op ? op.guard?.v : void 0
2369
+ ]));
2189
2370
  var versionOf = (row) => Number(row["_v"]);
2190
2371
  var isKeyed = (value) => value !== null && value !== void 0;
2191
2372
  var misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -2528,7 +2709,9 @@ var createTransactions = ({ adapter, schema, reads, retry = {} }) => {
2528
2709
  assertOutsideTransaction();
2529
2710
  let run;
2530
2711
  let negative;
2531
- for (let round = 0; round < attempts; round += 1) {
2712
+ let failures = 0;
2713
+ let lost;
2714
+ for (let round = 0;; round += 1) {
2532
2715
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
2533
2716
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
2534
2717
  run ??= await attempt(fn).catch((error) => {
@@ -2537,6 +2720,8 @@ var createTransactions = ({ adapter, schema, reads, retry = {} }) => {
2537
2720
  });
2538
2721
  if (run === void 0) {
2539
2722
  onRetry?.("rerun", round + 1);
2723
+ lost = void 0;
2724
+ if ((failures += 1) >= attempts) break;
2540
2725
  continue;
2541
2726
  }
2542
2727
  let aggregates;
@@ -2547,8 +2732,14 @@ var createTransactions = ({ adapter, schema, reads, retry = {} }) => {
2547
2732
  negative = error;
2548
2733
  onRetry?.("rerun", round + 1);
2549
2734
  run = void 0;
2735
+ lost = void 0;
2736
+ if ((failures += 1) >= attempts) break;
2550
2737
  continue;
2551
2738
  }
2739
+ const versions = versionsOf(aggregates);
2740
+ if (lost !== void 0 && versions !== lost) failures -= 1;
2741
+ lost = void 0;
2742
+ if (failures >= attempts) break;
2552
2743
  const ops = [...run.ops, ...aggregates];
2553
2744
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
2554
2745
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -2562,12 +2753,16 @@ var createTransactions = ({ adapter, schema, reads, retry = {} }) => {
2562
2753
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
2563
2754
  if (failed === void 0 || failed >= run.ops.length) {
2564
2755
  onRetry?.("resend", round + 1);
2756
+ failures += 1;
2757
+ if (failed !== void 0) lost = versions;
2758
+ else if (failures >= attempts) break;
2565
2759
  continue;
2566
2760
  }
2567
2761
  const reason = await classify(ops[failed], run.read);
2568
2762
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
2569
2763
  onRetry?.("rerun", round + 1);
2570
2764
  run = void 0;
2765
+ if ((failures += 1) >= attempts) break;
2571
2766
  }
2572
2767
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
2573
2768
  } };
@@ -2801,9 +2996,6 @@ var createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =>
2801
2996
  flush: async () => {
2802
2997
  await batches?.flush();
2803
2998
  },
2804
- dispose: async () => {
2805
- await batches?.dispose();
2806
- },
2807
2999
  database(module) {
2808
3000
  const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
2809
3001
  return {
@@ -2882,11 +3074,10 @@ var createEngine = (database, { plugins = [], now = Date.now } = {}) => {
2882
3074
  if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
2883
3075
  return engine.database(module);
2884
3076
  },
2885
- flush: () => engine.flush(),
2886
- dispose: () => engine.dispose()
3077
+ flush: () => engine.flush()
2887
3078
  };
2888
3079
  };
2889
- var HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.5";
3080
+ var HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.51";
2890
3081
  /**
2891
3082
  * `/version` on both mounts. The admin mount also lists the ids of the
2892
3083
  * plugins the server runs, sorted; apps never learn which plugins a server
@@ -3038,10 +3229,15 @@ var releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? cre
3038
3229
  platform: input.platform,
3039
3230
  strategy: "FINGERPRINT"
3040
3231
  });
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);
3232
+ var parseReleaseCatalogRow = ({ payload, ...row }) => ({
3233
+ row,
3234
+ compiled: parseCompiledCatalog(payload, row.strategy)
3235
+ });
3236
+ /** Projects a parsed catalog row for one update check; null when the row is not this scope's. */
3237
+ var projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
3238
+ if (parsed === null) return null;
3239
+ const { row, compiled } = parsed;
3240
+ 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
3241
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
3046
3242
  return {
3047
3243
  catalogId: row.catalog_id,
@@ -3054,6 +3250,8 @@ var projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(
3054
3250
  scopeKey
3055
3251
  };
3056
3252
  };
3253
+ /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
3254
+ var projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
3057
3255
  var HBC_ASSET_PATH_RE = /\.bundle$/;
3058
3256
  var asByteSize = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
3059
3257
  var resolveUniqueHbcAssetPath = (manifest) => {
@@ -3320,9 +3518,9 @@ var baseBundleIdsOf = (row, range, bundleId, limit) => {
3320
3518
  }
3321
3519
  return ids;
3322
3520
  };
3323
- var PAGE$2 = 500;
3324
- var pick$1 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
3325
- var toBundleRow = pick$1([
3521
+ var PAGE$3 = 500;
3522
+ var pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
3523
+ var toBundleRow = pick$2([
3326
3524
  "id",
3327
3525
  "platform",
3328
3526
  "git_commit_hash",
@@ -3331,7 +3529,7 @@ var toBundleRow = pick$1([
3331
3529
  "manifest_file_hash",
3332
3530
  "asset_base_storage_uri"
3333
3531
  ]);
3334
- var toPatchRow = pick$1([
3532
+ var toPatchRow = pick$2([
3335
3533
  "id",
3336
3534
  "bundle_id",
3337
3535
  "base_bundle_id",
@@ -3341,7 +3539,7 @@ var toPatchRow = pick$1([
3341
3539
  "byte_size",
3342
3540
  "order_index"
3343
3541
  ]);
3344
- var toReleaseRow = pick$1([
3542
+ var pickReleaseRow = pick$2([
3345
3543
  "id",
3346
3544
  "revision",
3347
3545
  "scope_key",
@@ -3362,7 +3560,14 @@ var toReleaseRow = pick$1([
3362
3560
  "created_at_ms",
3363
3561
  "updated_at_ms"
3364
3562
  ]);
3365
- var toCatalogRow = pick$1([
3563
+ /** A release row; `label` null where the store holds none, as before the column. */
3564
+ var toReleaseRow = (row) => {
3565
+ return {
3566
+ ...pickReleaseRow(row),
3567
+ label: typeof row.label === "number" ? row.label : null
3568
+ };
3569
+ };
3570
+ var toCatalogRow = pick$2([
3366
3571
  "scope_key",
3367
3572
  "catalog_id",
3368
3573
  "strategy",
@@ -3377,7 +3582,7 @@ var toCatalogRow = pick$1([
3377
3582
  "is_tombstone",
3378
3583
  "updated_at_ms"
3379
3584
  ]);
3380
- var toChannelRow = pick$1(["id", "name"]);
3585
+ var toChannelRow = pick$2(["id", "name"]);
3381
3586
  /** Every page of one read, in order. */
3382
3587
  var drain = async (read) => {
3383
3588
  const rows = [];
@@ -3390,8 +3595,16 @@ var drain = async (read) => {
3390
3595
  return rows;
3391
3596
  };
3392
3597
  /** 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. */
3598
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
3599
+ var after = (input) => {
3600
+ const asc = (input.order ?? "asc") === "asc";
3601
+ const range = {
3602
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
3603
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
3604
+ };
3605
+ return Object.keys(range).length === 0 ? {} : { range };
3606
+ };
3607
+ /** Core's reads, each through one declared index or key; plugins get `CoreReads`. */
3395
3608
  var createCoreReads = (db, storage) => {
3396
3609
  /** A bundle row's patches, exactly as many as its reference counter holds. */
3397
3610
  const detail = async (row) => {
@@ -3402,7 +3615,7 @@ var createCoreReads = (db, storage) => {
3402
3615
  const page = await db.findMany("bundle_patches", {
3403
3616
  index: "byBundle",
3404
3617
  where: { bundle_id: row.id },
3405
- limit: Math.min(count - patches.length, PAGE$2),
3618
+ limit: Math.min(count - patches.length, PAGE$3),
3406
3619
  ...cursor === void 0 ? {} : { cursor }
3407
3620
  });
3408
3621
  patches.push(...page.rows.map(toPatchRow));
@@ -3503,6 +3716,18 @@ var createCoreReads = (db, storage) => {
3503
3716
  const row = await db.findOne("releases", { id });
3504
3717
  return row === null ? null : toReleaseRow(row);
3505
3718
  },
3719
+ async getReleaseByLabel({ channel, platform, label }) {
3720
+ const found = await db.findOne("releases", {
3721
+ channel_id: `channel:${encodeChannelKey(channel)}`,
3722
+ platform,
3723
+ label
3724
+ });
3725
+ if (found === null) return null;
3726
+ const row = await db.findOne("releases", { id: found.id });
3727
+ if (row === null) return null;
3728
+ const release = toReleaseRow(row);
3729
+ return release.label === label && release.platform === platform ? release : null;
3730
+ },
3506
3731
  async listReleases(input) {
3507
3732
  const { filter } = input;
3508
3733
  const options = {
@@ -3568,89 +3793,732 @@ var createCoreReads = (db, storage) => {
3568
3793
  ...after(input)
3569
3794
  })).rows.map(toCatalogRow);
3570
3795
  },
3571
- async listChannels() {
3796
+ async listReleaseScopeKeys(input) {
3797
+ const scopeKeys = [];
3798
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
3799
+ const { rows } = await db.findMany("releases", {
3800
+ index: "scopes",
3801
+ where: {},
3802
+ limit: 1,
3803
+ range: { gt: last }
3804
+ });
3805
+ if (rows[0] === void 0) break;
3806
+ last = rows[0].scope_key;
3807
+ scopeKeys.push(last);
3808
+ }
3809
+ return scopeKeys;
3810
+ },
3811
+ async listChannels(input) {
3812
+ if (input !== void 0) return (await db.findMany("channels", {
3813
+ index: "all",
3814
+ where: {},
3815
+ order: input.order ?? "asc",
3816
+ limit: input.limit,
3817
+ ...after(input)
3818
+ })).rows.map(toChannelRow);
3572
3819
  return (await drain((page) => db.findMany("channels", {
3573
3820
  index: "all",
3574
3821
  where: {},
3575
- limit: PAGE$2,
3822
+ limit: PAGE$3,
3576
3823
  ...page
3577
3824
  }))).map(toChannelRow);
3578
3825
  },
3826
+ async getChannels(ids) {
3827
+ const unique = [...new Set(ids)];
3828
+ if (unique.length === 0) return [];
3829
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
3830
+ },
3579
3831
  async findChannelByName(name) {
3580
3832
  const row = await db.findOne("channels", { name });
3581
3833
  return row === null ? null : toChannelRow(row);
3582
3834
  }
3583
3835
  };
3584
3836
  };
3585
- var PAGE$1 = 500;
3586
- /** Moves one bundle into or out of its platform's total and the overall total. */
3587
- var countBundle = (tx, platform, delta) => {
3588
- for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
3589
- };
3590
- var insertBundle = (tx, row) => {
3591
- tx.create("bundles", row);
3592
- countBundle(tx, row.platform, 1);
3593
- };
3594
3837
  /**
3595
- * Updates a bundle; a platform change moves it between platform totals,
3596
- * except for a native build's built-in bundle, which they never count.
3838
+ * A device's UDID: 40 hex digits, or 8 and 16 joined by a hyphen. The same
3839
+ * rule as `normalizeIosUdid` of `@hot-updater/protocol/native-artifact`,
3840
+ * implemented here so the server's runtime never loads the artifact readers.
3597
3841
  */
3598
- var updateBundle = (tx, current, set, { counted = true } = {}) => {
3599
- tx.update("bundles", current, set);
3600
- if (counted && set.platform !== void 0 && set.platform !== current.platform) {
3601
- countBundle(tx, current.platform, -1);
3602
- countBundle(tx, set.platform, 1);
3603
- }
3604
- };
3605
- /** Deletes a bundle and, by cascade, every patch to or from it; a release on it refuses. */
3606
- var deleteBundle = async (tx, current) => {
3607
- await tx.delete("bundles", current);
3608
- countBundle(tx, current.platform, -1);
3842
+ var UDID = /^(?:[0-9a-f]{40}|[0-9a-f]{8}-[0-9a-f]{16})$/iu;
3843
+ /** The form the registry stores and compares a UDID in, or null for text that isn't one. */
3844
+ var normalizeIosUdid = (value) => {
3845
+ const trimmed = value.trim();
3846
+ return UDID.test(trimmed) ? trimmed.toLowerCase() : null;
3847
+ };
3848
+ /** `ios_devices.name`'s bound in core's schema. */
3849
+ var NAME_MAX_LENGTH = 100;
3850
+ /** `ios_devices.requested_by` and `approved_by`'s bound: an email address. */
3851
+ var EMAIL_MAX_LENGTH = 320;
3852
+ /** `ios_devices.apple_issuer_id`'s bound. */
3853
+ var ISSUER_MAX_LENGTH = 64;
3854
+ /** The one row of `ios_device_account`. */
3855
+ var ACCOUNT_ROW = "registry";
3856
+ /** `ios_devices.apple_error`'s bound. */
3857
+ var ERROR_MAX_LENGTH = 512;
3858
+ var STATUSES = [
3859
+ "pending",
3860
+ "approved",
3861
+ "registered"
3862
+ ];
3863
+ var OUTCOMES = [
3864
+ "registered",
3865
+ "refused",
3866
+ "disabled",
3867
+ "missing"
3868
+ ];
3869
+ /** The `apple_error` of a device Apple has disabled. */
3870
+ var IOS_DEVICE_DISABLED_ERROR = "Disabled in the Apple account.";
3871
+ /** The `apple_error` of a registered device Apple no longer lists. */
3872
+ var IOS_DEVICE_MISSING_ERROR = "Gone from the Apple account. Approve it again to register it.";
3873
+ /** A device or registry request core cannot store: the caller's input. */
3874
+ var IosDeviceInputError = class extends TypeError {
3875
+ name = "IosDeviceInputError";
3876
+ };
3877
+ var pick$1 = (row) => ({
3878
+ id: row.id,
3879
+ udid: row.udid,
3880
+ name: row.name,
3881
+ status: row.status,
3882
+ requested_by: row.requested_by ?? null,
3883
+ created_at_ms: row.created_at_ms,
3884
+ approved_by: row.approved_by ?? null,
3885
+ approved_at_ms: row.approved_at_ms ?? null,
3886
+ registered_at_ms: row.registered_at_ms ?? null,
3887
+ apple_issuer_id: row.apple_issuer_id ?? null,
3888
+ apple_error: row.apple_error ?? null,
3889
+ build_id: row.build_id ?? null
3890
+ });
3891
+ var udidOf = (udid) => {
3892
+ const key = typeof udid === "string" ? normalizeIosUdid(udid) : null;
3893
+ if (key === null) throw new IosDeviceInputError("Invalid iOS device: udid must be 40 hex digits, or 8 and 16 joined by a hyphen.");
3894
+ return key;
3895
+ };
3896
+ var nameOf = (name) => {
3897
+ const trimmed = typeof name === "string" ? name.trim() : "";
3898
+ if (trimmed.length === 0 || trimmed.length > NAME_MAX_LENGTH) throw new IosDeviceInputError(`Invalid iOS device: name must be 1 to ${NAME_MAX_LENGTH} characters.`);
3899
+ return trimmed;
3900
+ };
3901
+ /** An email, lower-cased, or null for the CLI. */
3902
+ var personOf = (value, field) => {
3903
+ if (value === null) return null;
3904
+ const email = typeof value === "string" ? value.trim().toLowerCase() : "";
3905
+ 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.`);
3906
+ return email;
3907
+ };
3908
+ /** Apple's words, on one line and within the column's bound. */
3909
+ var errorText = (text) => {
3910
+ const line = text.replace(/\s+/gu, " ").trim();
3911
+ return line.length > ERROR_MAX_LENGTH ? `${line.slice(0, 511)}…` : line;
3609
3912
  };
3610
3913
  /**
3611
- * Replaces a bundle's patches with `rows`: kept patches are updated where
3612
- * they changed, others deleted or created, so no key is written twice.
3914
+ * The iOS device registry: the iPhones and iPads a team asked to install ad hoc
3915
+ * builds on. The Console writes requests and approvals, and the CLI what Apple
3916
+ * said, each over the row it read.
3613
3917
  */
3614
- var replaceBundlePatches = async (tx, bundle, rows) => {
3615
- const wanted = new Map(rows.map((row) => [row.id, row]));
3616
- const count = bundle._refs_bundle_patches_bundle_id ?? 0;
3617
- let cursor;
3618
- for (let seen = 0; seen < count;) {
3619
- const page = await tx.findMany("bundle_patches", {
3620
- index: "byBundle",
3621
- where: { bundle_id: bundle.id },
3622
- limit: Math.min(count - seen, PAGE$1),
3623
- ...cursor === void 0 ? {} : { cursor }
3918
+ var createIosDeviceApi = (db, { now = Date.now } = {}) => {
3919
+ const findIosDevice = async (udid) => {
3920
+ const key = normalizeIosUdid(udid);
3921
+ if (key === null) return null;
3922
+ const row = await db.findOne("ios_devices", { udid: key });
3923
+ return row === null ? null : pick$1(row);
3924
+ };
3925
+ /**
3926
+ * The issuer of the registry's earliest registration among its rows, by
3927
+ * when and then by ID, or null when no row names one: read only while the
3928
+ * registry has no account yet, in one read of its first registration. A
3929
+ * row names an issuer exactly when it has a registration time: both are
3930
+ * set by its first registration and never cleared.
3931
+ */
3932
+ const accountOfRows = async () => {
3933
+ const { rows } = await db.findMany("ios_devices", {
3934
+ index: "byRegistration",
3935
+ where: {},
3936
+ order: "asc",
3937
+ limit: 1,
3938
+ range: { gte: 0 }
3624
3939
  });
3625
- for (const stored of page.rows) {
3626
- const next = wanted.get(stored.id);
3627
- wanted.delete(stored.id);
3628
- if (next === void 0) {
3629
- await tx.delete("bundle_patches", stored);
3630
- continue;
3631
- }
3632
- const set = Object.fromEntries(Object.entries(next).filter(([field, value]) => field !== "id" && stored[field] !== value));
3633
- if (Object.keys(set).length > 0) tx.update("bundle_patches", stored, set);
3634
- }
3635
- seen += page.rows.length;
3636
- if (page.next === void 0) break;
3637
- cursor = page.next;
3638
- }
3639
- for (const row of wanted.values()) tx.create("bundle_patches", row);
3640
- };
3641
- /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
3642
- var insertChannel = async (db, row) => {
3643
- for (let attempt = 1;; attempt += 1) try {
3644
- return await db.transaction(async (tx) => {
3645
- const existing = await tx.findOne("channels", { name: row.name });
3940
+ return (rows[0] === void 0 ? null : pick$1(rows[0]))?.apple_issuer_id ?? null;
3941
+ };
3942
+ return {
3943
+ async listIosDevices(input) {
3944
+ if (input.status !== void 0 && !STATUSES.includes(input.status)) throw new IosDeviceInputError(`Invalid iOS device status: ${String(input.status)}. Expected ${STATUSES.join(", ")}.`);
3945
+ const page = {
3946
+ order: input.order ?? "asc",
3947
+ limit: input.limit,
3948
+ ...after(input)
3949
+ };
3950
+ const { rows } = input.status === void 0 ? await db.findMany("ios_devices", {
3951
+ index: "all",
3952
+ where: {},
3953
+ ...page
3954
+ }) : await db.findMany("ios_devices", {
3955
+ index: "byStatus",
3956
+ where: { status: input.status },
3957
+ ...page
3958
+ });
3959
+ return rows.map(pick$1);
3960
+ },
3961
+ findIosDevice,
3962
+ async requestIosDevice(input) {
3963
+ const udid = udidOf(input.udid);
3964
+ const name = nameOf(input.name);
3965
+ const requestedBy = personOf(input.requestedBy, "requestedBy");
3966
+ const existing = await db.findOne("ios_devices", { udid });
3646
3967
  if (existing !== null) return {
3647
- row: toChannelRow(existing),
3648
- inserted: false
3968
+ device: pick$1(existing),
3969
+ created: false
3649
3970
  };
3650
- tx.create("channels", row);
3651
- return {
3652
- row,
3653
- inserted: true
3971
+ const device = {
3972
+ id: createUUIDv7(),
3973
+ udid,
3974
+ name,
3975
+ status: "pending",
3976
+ requested_by: requestedBy,
3977
+ created_at_ms: now(),
3978
+ approved_by: null,
3979
+ approved_at_ms: null,
3980
+ registered_at_ms: null,
3981
+ apple_issuer_id: null,
3982
+ apple_error: null,
3983
+ build_id: null
3984
+ };
3985
+ try {
3986
+ await db.transaction(async (tx) => {
3987
+ tx.create("ios_devices", device);
3988
+ });
3989
+ } catch (error) {
3990
+ if (error instanceof DatabaseConstraintError && error.reason === "unique") {
3991
+ const winner = await db.findOne("ios_devices", { udid });
3992
+ if (winner !== null) return {
3993
+ device: pick$1(winner),
3994
+ created: false
3995
+ };
3996
+ }
3997
+ throw error;
3998
+ }
3999
+ return {
4000
+ device,
4001
+ created: true
4002
+ };
4003
+ },
4004
+ async approveIosDevice(id, input) {
4005
+ const name = input.name === void 0 ? void 0 : nameOf(input.name);
4006
+ const approvedBy = personOf(input.approvedBy, "approvedBy");
4007
+ return db.transaction(async (tx) => {
4008
+ const row = await tx.findOne("ios_devices", { id });
4009
+ if (row === null) return null;
4010
+ const device = pick$1(row);
4011
+ const set = {
4012
+ ...name === void 0 || name === device.name ? {} : { name },
4013
+ ...device.status === "pending" ? {
4014
+ status: "approved",
4015
+ approved_by: approvedBy,
4016
+ approved_at_ms: now()
4017
+ } : {}
4018
+ };
4019
+ if (Object.keys(set).length === 0) return device;
4020
+ tx.update("ios_devices", row, set);
4021
+ return {
4022
+ ...device,
4023
+ ...set
4024
+ };
4025
+ });
4026
+ },
4027
+ async renameIosDevice(id, input) {
4028
+ const name = nameOf(input);
4029
+ return db.transaction(async (tx) => {
4030
+ const row = await tx.findOne("ios_devices", { id });
4031
+ if (row === null) return null;
4032
+ const device = pick$1(row);
4033
+ if (device.name === name) return device;
4034
+ tx.update("ios_devices", row, { name });
4035
+ return {
4036
+ ...device,
4037
+ name
4038
+ };
4039
+ });
4040
+ },
4041
+ async recordIosDeviceOutcome({ id, seen, issuerId, outcome, reason }) {
4042
+ if (!OUTCOMES.includes(outcome)) throw new IosDeviceInputError(`Invalid iOS device outcome: ${String(outcome)}. Expected ${OUTCOMES.join(", ")}.`);
4043
+ 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.`);
4044
+ return db.transaction(async (tx) => {
4045
+ const row = await tx.findOne("ios_devices", { id });
4046
+ if (row === null) return null;
4047
+ const device = pick$1(row);
4048
+ if (device.status !== seen.status || device.approved_at_ms !== seen.approvedAtMs || device.apple_issuer_id !== null && device.apple_issuer_id !== issuerId) return null;
4049
+ let set;
4050
+ switch (outcome) {
4051
+ case "registered":
4052
+ if (device.status === "pending") return null;
4053
+ set = {
4054
+ status: "registered",
4055
+ registered_at_ms: device.registered_at_ms ?? now(),
4056
+ apple_issuer_id: issuerId,
4057
+ apple_error: null
4058
+ };
4059
+ break;
4060
+ case "refused":
4061
+ if (device.status !== "approved") return null;
4062
+ set = { apple_error: errorText(reason === void 0 || reason.trim() === "" ? "Apple refused it." : reason) };
4063
+ break;
4064
+ case "disabled":
4065
+ if (device.status === "pending") return null;
4066
+ set = { apple_error: IOS_DEVICE_DISABLED_ERROR };
4067
+ break;
4068
+ case "missing":
4069
+ if (device.status !== "registered") return null;
4070
+ set = {
4071
+ status: "pending",
4072
+ approved_by: null,
4073
+ approved_at_ms: null,
4074
+ apple_error: IOS_DEVICE_MISSING_ERROR
4075
+ };
4076
+ }
4077
+ if (Object.entries(set).some(([column, value]) => device[column] !== (value ?? null))) tx.update("ios_devices", row, set);
4078
+ return {
4079
+ ...device,
4080
+ ...set
4081
+ };
4082
+ });
4083
+ },
4084
+ async markIosDevicesInBuild({ buildId, ids }) {
4085
+ for (const id of new Set(ids)) await db.transaction(async (tx) => {
4086
+ const row = await tx.findOne("ios_devices", { id });
4087
+ if (row === null || typeof row.build_id === "string" && row.build_id >= buildId) return;
4088
+ tx.update("ios_devices", row, { build_id: buildId });
4089
+ });
4090
+ },
4091
+ async findIosDeviceAccount() {
4092
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
4093
+ const issuerId = existing === null ? await accountOfRows() : existing.apple_issuer_id;
4094
+ return issuerId === null ? null : { issuerId };
4095
+ },
4096
+ async claimIosDeviceAccount(issuerId) {
4097
+ 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.`);
4098
+ const answer = (held) => ({
4099
+ issuerId: held,
4100
+ claimed: held === issuerId
4101
+ });
4102
+ const existing = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
4103
+ if (existing !== null) return answer(existing.apple_issuer_id);
4104
+ const holder = await accountOfRows() ?? issuerId;
4105
+ try {
4106
+ await db.transaction(async (tx) => {
4107
+ tx.create("ios_device_account", {
4108
+ id: ACCOUNT_ROW,
4109
+ apple_issuer_id: holder,
4110
+ claimed_at_ms: now()
4111
+ });
4112
+ });
4113
+ return answer(holder);
4114
+ } catch (error) {
4115
+ if (error instanceof DatabaseConstraintError && (error.reason === "exists" || error.reason === "unique")) {
4116
+ const winner = await db.findOne("ios_device_account", { id: ACCOUNT_ROW });
4117
+ if (winner !== null) return answer(winner.apple_issuer_id);
4118
+ }
4119
+ throw error;
4120
+ }
4121
+ },
4122
+ async deleteIosDevice(id, only) {
4123
+ const requestedBy = only?.requestedBy === void 0 ? void 0 : personOf(only.requestedBy, "requestedBy");
4124
+ return db.transaction(async (tx) => {
4125
+ const row = await tx.findOne("ios_devices", { id });
4126
+ if (row === null) return null;
4127
+ const device = pick$1(row);
4128
+ if (only?.status !== void 0 && device.status !== only.status || requestedBy !== void 0 && device.requested_by !== requestedBy) return null;
4129
+ await tx.delete("ios_devices", row);
4130
+ return device;
4131
+ });
4132
+ }
4133
+ };
4134
+ };
4135
+ /** Store destinations accepted for each native platform. */
4136
+ var NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
4137
+ android: [
4138
+ "play-internal",
4139
+ "play-closed",
4140
+ "play-open",
4141
+ "play-production"
4142
+ ],
4143
+ ios: ["testflight"]
4144
+ };
4145
+ /**
4146
+ * The counter of a channel and platform's release labels: one
4147
+ * `label_sequences` row, which every writer of the pair reads and bumps.
4148
+ */
4149
+ var labelSequenceId = (channelId, platform) => `releases/${platform}/${channelId}`;
4150
+ /** The pairs a channel's counters belong to, which deleting it removes. */
4151
+ var LABEL_PLATFORMS = ["ios", "android"];
4152
+ /**
4153
+ * A channel and platform whose releases written before labels have none
4154
+ * yet, or that has no counter: the write stops before taking a label, the
4155
+ * core labels the pair with `fillLabels`, and the write runs again.
4156
+ */
4157
+ var NeedsLabelFill = class extends Error {
4158
+ channelId;
4159
+ platform;
4160
+ constructor(channelId, platform) {
4161
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
4162
+ this.channelId = channelId;
4163
+ this.platform = platform;
4164
+ }
4165
+ };
4166
+ var createLabelAllocator = (tx, used, caughtUp) => {
4167
+ const sequences = /* @__PURE__ */ new Map();
4168
+ return {
4169
+ async next(channelId, platform) {
4170
+ const id = labelSequenceId(channelId, platform);
4171
+ let sequence = sequences.get(id);
4172
+ if (sequence === void 0) {
4173
+ const row = await tx.findOne("label_sequences", { id });
4174
+ if (row === null || !row.is_filled) {
4175
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
4176
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
4177
+ }
4178
+ const read = row?.last_label ?? 0;
4179
+ sequence = {
4180
+ row,
4181
+ read,
4182
+ last: read
4183
+ };
4184
+ sequences.set(id, sequence);
4185
+ used.set(id, {
4186
+ channelId,
4187
+ platform,
4188
+ read
4189
+ });
4190
+ }
4191
+ sequence.last += 1;
4192
+ return sequence.last;
4193
+ },
4194
+ caughtUp(channelId, platform) {
4195
+ caughtUp.set(labelSequenceId(channelId, platform), {
4196
+ channelId,
4197
+ platform
4198
+ });
4199
+ },
4200
+ flush() {
4201
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
4202
+ id,
4203
+ last_label: last,
4204
+ is_filled: true
4205
+ });
4206
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
4207
+ }
4208
+ };
4209
+ };
4210
+ var FILL_BATCH = 25;
4211
+ var PAGE$2 = 500;
4212
+ /**
4213
+ * Labels a channel and platform's releases that have none, in ID order,
4214
+ * which is the order they were created in, and marks its counter filled:
4215
+ * each batch reads the counter and its rows guarded, so a concurrent fill or
4216
+ * write serializes on the counter and skips what another labeled. With
4217
+ * `dryRun`, it only counts them. Answers how many it labeled.
4218
+ */
4219
+ var fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
4220
+ const id = labelSequenceId(channelId, platform);
4221
+ let labeled = 0;
4222
+ let batchSize = FILL_BATCH;
4223
+ const label = async (ids) => {
4224
+ for (let at = 0; at < ids.length;) {
4225
+ const batch = ids.slice(at, at + batchSize);
4226
+ try {
4227
+ labeled += await db.transaction(async (tx) => {
4228
+ const counter = await tx.findOne("label_sequences", { id });
4229
+ let last = counter?.last_label ?? 0;
4230
+ let count = 0;
4231
+ for (const releaseId of batch) {
4232
+ const row = await tx.findOne("releases", { id: releaseId });
4233
+ if (row === null || typeof row.label === "number") continue;
4234
+ last += 1;
4235
+ count += 1;
4236
+ tx.update("releases", row, { label: last });
4237
+ }
4238
+ if (counter === null) tx.create("label_sequences", {
4239
+ id,
4240
+ last_label: last,
4241
+ is_filled: false
4242
+ });
4243
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
4244
+ return count;
4245
+ });
4246
+ at += batch.length;
4247
+ } catch (error) {
4248
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
4249
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
4250
+ continue;
4251
+ }
4252
+ throw error;
4253
+ }
4254
+ }
4255
+ };
4256
+ let cursor;
4257
+ do {
4258
+ const page = await db.findMany("releases", {
4259
+ index: "byChannelPlatform",
4260
+ where: {
4261
+ channel_id: channelId,
4262
+ platform
4263
+ },
4264
+ limit: PAGE$2,
4265
+ ...cursor === void 0 ? {} : { cursor }
4266
+ });
4267
+ const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
4268
+ if (dryRun) labeled += unlabeled.length;
4269
+ else await label(unlabeled);
4270
+ cursor = page.next;
4271
+ } while (cursor !== void 0);
4272
+ if (dryRun) return labeled;
4273
+ await db.transaction(async (tx) => {
4274
+ const counter = await tx.findOne("label_sequences", { id });
4275
+ if (counter === null) tx.create("label_sequences", {
4276
+ id,
4277
+ last_label: 0,
4278
+ is_filled: true
4279
+ });
4280
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
4281
+ });
4282
+ return labeled;
4283
+ };
4284
+ /**
4285
+ * Reads what a pair's fill writes, its counter and its label index, without
4286
+ * writing: a database without release labels' schema, such as one a 1.2
4287
+ * prerelease migrated, fails here as the fill would. The schema is the
4288
+ * database's, so one pair tells. Two reads.
4289
+ */
4290
+ var probeLabelSchema = async (db, { channelId, platform }) => {
4291
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
4292
+ await db.findMany("releases", {
4293
+ index: "byLabel",
4294
+ where: {
4295
+ channel_id: channelId,
4296
+ platform,
4297
+ label: 0
4298
+ },
4299
+ limit: 1
4300
+ });
4301
+ };
4302
+ var REPAIRS = 4;
4303
+ var RACES = 32;
4304
+ /**
4305
+ * Runs a release write that takes labels, in one transaction with the
4306
+ * counters it bumps. A pair that still needs its fill is filled, and the
4307
+ * write runs again; so is a pair whose catch-up made the write too large for
4308
+ * the store. A label another row holds, such as an index item a release
4309
+ * deleted by a server of an earlier release left on a key-value store, is
4310
+ * skipped: its counters move past it and the write runs again.
4311
+ */
4312
+ var writeWithLabels = async (db, write) => {
4313
+ const filled = /* @__PURE__ */ new Set();
4314
+ const fill = async (pairs) => {
4315
+ for (const pair of pairs) {
4316
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
4317
+ await fillLabels(db, pair);
4318
+ }
4319
+ };
4320
+ for (let repairs = 0, races = 0;;) {
4321
+ const used = /* @__PURE__ */ new Map();
4322
+ const caughtUp = /* @__PURE__ */ new Map();
4323
+ try {
4324
+ return await db.transaction(async (tx) => {
4325
+ used.clear();
4326
+ caughtUp.clear();
4327
+ const labels = createLabelAllocator(tx, used, caughtUp);
4328
+ const result = await write(tx, labels);
4329
+ labels.flush();
4330
+ return result;
4331
+ });
4332
+ } catch (error) {
4333
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
4334
+ if (needs.length > 0) {
4335
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
4336
+ if (fresh || repairs < REPAIRS) {
4337
+ if (!fresh) repairs += 1;
4338
+ await fill(needs);
4339
+ continue;
4340
+ }
4341
+ }
4342
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
4343
+ if (await db.transaction(async (tx) => {
4344
+ const moves = [];
4345
+ for (const [id, { channelId, read }] of used) {
4346
+ const counter = await tx.findOne("label_sequences", { id });
4347
+ if (counter !== null) {
4348
+ if (counter.last_label !== read) return false;
4349
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
4350
+ continue;
4351
+ }
4352
+ const channel = await tx.findOne("channels", { id: channelId });
4353
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
4354
+ moves.push(() => tx.create("label_sequences", {
4355
+ id,
4356
+ last_label: read + 1,
4357
+ is_filled: true
4358
+ }));
4359
+ }
4360
+ for (const move of moves) move();
4361
+ return true;
4362
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
4363
+ }
4364
+ throw error;
4365
+ }
4366
+ }
4367
+ };
4368
+ /**
4369
+ * Labels a scope's releases a server of an earlier release wrote after its
4370
+ * newest labeled one, oldest first, before the write takes its own label:
4371
+ * `latest` is the scope's newest release, so a labeled one costs no read.
4372
+ * Answers the labels it gave, by release ID.
4373
+ */
4374
+ var catchUpLabels = async (tx, labels, latest) => {
4375
+ const given = /* @__PURE__ */ new Map();
4376
+ if (latest === null || typeof latest.label === "number") return given;
4377
+ const unlabeled = [];
4378
+ let cursor;
4379
+ scan: do {
4380
+ const page = await tx.findMany("releases", {
4381
+ index: "byScope",
4382
+ where: { scope_key: latest.scope_key },
4383
+ order: "desc",
4384
+ limit: FILL_BATCH,
4385
+ ...cursor === void 0 ? {} : { cursor }
4386
+ });
4387
+ for (const row of page.rows) {
4388
+ if (typeof row.label === "number") break scan;
4389
+ unlabeled.push(row);
4390
+ }
4391
+ cursor = page.next;
4392
+ } while (cursor !== void 0);
4393
+ labels.caughtUp(latest.channel_id, latest.platform);
4394
+ for (const row of unlabeled.reverse()) {
4395
+ const { id, channel_id, platform } = toReleaseRow(row);
4396
+ const label = await labels.next(channel_id, platform);
4397
+ tx.update("releases", row, { label });
4398
+ given.set(id, label);
4399
+ }
4400
+ return given;
4401
+ };
4402
+ /**
4403
+ * The channels and platforms whose releases need labels: a scope whose
4404
+ * newest release has none, or a pair without a filled counter. Releases a
4405
+ * server of an earlier release wrote in a filled pair come after its
4406
+ * labeled ones in their scope, so the newest release of each scope tells.
4407
+ * Two reads per scope, one per pair.
4408
+ */
4409
+ var pendingLabelPairs = async (db) => {
4410
+ const pairs = /* @__PURE__ */ new Map();
4411
+ for (let last = "";;) {
4412
+ const { rows } = await db.findMany("releases", {
4413
+ index: "scopes",
4414
+ where: {},
4415
+ limit: 1,
4416
+ range: { gt: last }
4417
+ });
4418
+ if (rows[0] === void 0) break;
4419
+ last = rows[0].scope_key;
4420
+ const { rows: newest } = await db.findMany("releases", {
4421
+ index: "byScope",
4422
+ where: { scope_key: last },
4423
+ order: "desc",
4424
+ limit: 1
4425
+ });
4426
+ if (newest[0] === void 0) continue;
4427
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
4428
+ const id = labelSequenceId(channelId, platform);
4429
+ const pair = pairs.get(id) ?? {
4430
+ channelId,
4431
+ platform,
4432
+ pending: false
4433
+ };
4434
+ pair.pending ||= label === null;
4435
+ pairs.set(id, pair);
4436
+ }
4437
+ const pending = [];
4438
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
4439
+ if (!unlabeled) {
4440
+ const counter = await db.findOne("label_sequences", { id });
4441
+ if (counter !== null && counter.is_filled) continue;
4442
+ }
4443
+ pending.push({
4444
+ channelId,
4445
+ platform
4446
+ });
4447
+ }
4448
+ return pending;
4449
+ };
4450
+ var PAGE$1 = 500;
4451
+ /** Moves one bundle into or out of its platform's total and the overall total. */
4452
+ var countBundle = (tx, platform, delta) => {
4453
+ for (const key of [platform, "*"]) tx.aggregate("bundle_totals", { platform_key: key }, { bundles: delta });
4454
+ };
4455
+ var insertBundle = (tx, row) => {
4456
+ tx.create("bundles", row);
4457
+ countBundle(tx, row.platform, 1);
4458
+ };
4459
+ /**
4460
+ * Updates a bundle; a platform change moves it between platform totals,
4461
+ * except for a native build's built-in bundle, which they never count.
4462
+ */
4463
+ var updateBundle = (tx, current, set, { counted = true } = {}) => {
4464
+ tx.update("bundles", current, set);
4465
+ if (counted && set.platform !== void 0 && set.platform !== current.platform) {
4466
+ countBundle(tx, current.platform, -1);
4467
+ countBundle(tx, set.platform, 1);
4468
+ }
4469
+ };
4470
+ /** Deletes a bundle and, by cascade, every patch to or from it; a release on it refuses. */
4471
+ var deleteBundle = async (tx, current) => {
4472
+ await tx.delete("bundles", current);
4473
+ countBundle(tx, current.platform, -1);
4474
+ };
4475
+ /**
4476
+ * Replaces a bundle's patches with `rows`: kept patches are updated where
4477
+ * they changed, others deleted or created, so no key is written twice.
4478
+ * `checkNew` sees each patch it is about to create, and refuses one by
4479
+ * throwing, which leaves the transaction's writes undone.
4480
+ */
4481
+ var replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
4482
+ const wanted = new Map(rows.map((row) => [row.id, row]));
4483
+ const count = bundle._refs_bundle_patches_bundle_id ?? 0;
4484
+ let cursor;
4485
+ for (let seen = 0; seen < count;) {
4486
+ const page = await tx.findMany("bundle_patches", {
4487
+ index: "byBundle",
4488
+ where: { bundle_id: bundle.id },
4489
+ limit: Math.min(count - seen, PAGE$1),
4490
+ ...cursor === void 0 ? {} : { cursor }
4491
+ });
4492
+ for (const stored of page.rows) {
4493
+ const next = wanted.get(stored.id);
4494
+ wanted.delete(stored.id);
4495
+ if (next === void 0) {
4496
+ await tx.delete("bundle_patches", stored);
4497
+ continue;
4498
+ }
4499
+ const set = Object.fromEntries(Object.entries(next).filter(([field, value]) => field !== "id" && stored[field] !== value));
4500
+ if (Object.keys(set).length > 0) tx.update("bundle_patches", stored, set);
4501
+ }
4502
+ seen += page.rows.length;
4503
+ if (page.next === void 0) break;
4504
+ cursor = page.next;
4505
+ }
4506
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
4507
+ for (const row of wanted.values()) tx.create("bundle_patches", row);
4508
+ };
4509
+ /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
4510
+ var insertChannel = async (db, row) => {
4511
+ for (let attempt = 1;; attempt += 1) try {
4512
+ return await db.transaction(async (tx) => {
4513
+ const existing = await tx.findOne("channels", { name: row.name });
4514
+ if (existing !== null) return {
4515
+ row: toChannelRow(existing),
4516
+ inserted: false
4517
+ };
4518
+ tx.create("channels", row);
4519
+ return {
4520
+ row,
4521
+ inserted: true
3654
4522
  };
3655
4523
  });
3656
4524
  } catch (error) {
@@ -3658,7 +4526,11 @@ var insertChannel = async (db, row) => {
3658
4526
  throw error;
3659
4527
  }
3660
4528
  };
3661
- /** Deletes a channel no release or native build uses: 1 read, 1 query, 1 write. */
4529
+ /**
4530
+ * Deletes a channel no release or native build uses, with its label
4531
+ * counters, so one created again with its name starts at 1: 3 reads,
4532
+ * 1 query, 1 write.
4533
+ */
3662
4534
  var deleteChannel = (db, id) => db.transaction(async (tx) => {
3663
4535
  const row = await tx.findOne("channels", { id });
3664
4536
  if (row === null) return {
@@ -3678,6 +4550,10 @@ var deleteChannel = (db, id) => db.transaction(async (tx) => {
3678
4550
  deleted: false,
3679
4551
  reason: "not_empty"
3680
4552
  };
4553
+ for (const platform of LABEL_PLATFORMS) {
4554
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
4555
+ if (counter !== null) await tx.delete("label_sequences", counter);
4556
+ }
3681
4557
  await tx.delete("channels", row);
3682
4558
  return { deleted: true };
3683
4559
  });
@@ -3696,6 +4572,27 @@ var GIT_COMMIT_HASH_MAX_LENGTH = 255;
3696
4572
  * and looks up nothing else.
3697
4573
  */
3698
4574
  var BUILD_KEY = /^nbk1:[0-9a-f]{64}$/;
4575
+ /** `native_builds.sandbox_url_scheme`'s bound in core's schema. */
4576
+ var SANDBOX_URL_SCHEME_MAX_LENGTH = 255;
4577
+ /**
4578
+ * A URL scheme as RFC 3986 spells it, in lower case: what a sandbox build's
4579
+ * artifact registers, as `@hot-updater/protocol/native-artifact` reads it.
4580
+ */
4581
+ var URL_SCHEME = new RegExp(`^[a-z][a-z0-9+.-]{0,254}$`);
4582
+ /**
4583
+ * A bundle identifier or application ID, as an artifact reports it: letters,
4584
+ * digits, dots, dashes and underscores, which a scope key holds as they are.
4585
+ */
4586
+ var APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/;
4587
+ /** A fingerprint hash as a Release Catalog scope key holds it. */
4588
+ var FINGERPRINT_HASH = /^[A-Za-z0-9._~-]{1,255}$/;
4589
+ /** How each kind of artifact can install. */
4590
+ var DISTRIBUTIONS = {
4591
+ apk: ["direct"],
4592
+ app: ["direct"],
4593
+ aab: ["store"],
4594
+ ipa: ["direct", "store"]
4595
+ };
3699
4596
  /** A native build or scope core cannot store or look up: the caller's input. */
3700
4597
  var NativeBuildInputError = class extends TypeError {
3701
4598
  name = "NativeBuildInputError";
@@ -3717,24 +4614,73 @@ var pick = (row) => ({
3717
4614
  build_number: row.build_number ?? null,
3718
4615
  submitted_to: row.submitted_to ?? null,
3719
4616
  submitted_at_ms: row.submitted_at_ms ?? null,
3720
- submitted_version: row.submitted_version ?? null
4617
+ submitted_version: row.submitted_version ?? null,
4618
+ is_store_build: row.is_store_build === true,
4619
+ is_sandbox: row.is_sandbox === true,
4620
+ sandbox_url_scheme: row.sandbox_url_scheme ?? null,
4621
+ export_method: row.export_method ?? null,
4622
+ native_app_version: row.native_app_version ?? null
3721
4623
  });
3722
- /** The store track each platform's builds are submitted to. */
3723
- var SUBMISSION_DESTINATIONS = {
3724
- android: "play-internal",
3725
- ios: "testflight"
3726
- };
4624
+ /** The export methods an `.ipa` registers with. */
4625
+ var EXPORT_METHODS = /* @__PURE__ */ new Set([
4626
+ "app-store",
4627
+ "ad-hoc",
4628
+ "development",
4629
+ "enterprise"
4630
+ ]);
4631
+ /**
4632
+ * How many older builds of a scope one read takes, looking for one older than
4633
+ * a bundle when a build made after the bundle is the newest.
4634
+ */
4635
+ var OLDER_BUILDS_PAGE = 20;
4636
+ /**
4637
+ * How many pages of older builds that look reads before it answers null: 100
4638
+ * builds made after the bundle in one scope, where a deploy's new bundle has
4639
+ * none or a few registered while it deploys.
4640
+ */
4641
+ var OLDER_BUILDS_PAGES = 5;
4642
+ /** How many times a mark runs again after losing its scope's mark to another. */
4643
+ var MARK_ATTEMPTS = 8;
3727
4644
  /** `native_builds.build_number`'s bound in core's schema. */
3728
4645
  var BUILD_NUMBER_MAX_LENGTH = 64;
3729
4646
  /** `native_builds.submitted_version`'s bound in core's schema. */
3730
4647
  var SUBMITTED_VERSION_MAX_LENGTH = 255;
4648
+ var checkedScopeKey = (scopeKey) => {
4649
+ 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.`);
4650
+ return scopeKey;
4651
+ };
4652
+ /**
4653
+ * How a registered artifact installs: an `.ipa` by its export method, and
4654
+ * `unknown` for one whose export no profile confirmed, which no lookup asks
4655
+ * for, so it is never reused as either.
4656
+ */
4657
+ var registeredDistribution = (kind, exportMethod) => kind !== "ipa" ? DISTRIBUTIONS[kind][0] : exportMethod === void 0 || exportMethod === null ? "unknown" : exportMethod === "app-store" ? "store" : "direct";
4658
+ /**
4659
+ * A sandbox build scope's key, which names no channel: the app ID, URL
4660
+ * scheme, artifact kind and distribution in its place, then the fingerprint,
4661
+ * or the app-version strategy and the exact app version. `v1:sandbox:` is no
4662
+ * Release Catalog strategy, so it never meets a normal build's key.
4663
+ */
4664
+ var sandboxScopeKey = (scope, sandbox) => {
4665
+ const { appId, urlScheme, artifactKind, distribution } = sandbox;
4666
+ 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;
4667
+ if (problem !== null) throw new NativeBuildInputError(`Invalid sandbox build scope: ${problem}.`);
4668
+ const target = scope.fingerprintHash === null ? `app-version:${encodeURIComponent(scope.appVersion)}` : `fingerprint:${scope.fingerprintHash}`;
4669
+ return checkedScopeKey(`v1:sandbox:${scope.platform}:${appId}:${urlScheme}:${artifactKind}:${distribution}:${target}`);
4670
+ };
3731
4671
  /**
3732
4672
  * A native build scope's key: the Release Catalog scope key of a
3733
4673
  * fingerprint, or of the app-version strategy followed by the exact app
3734
4674
  * version the build compiled in. One key serves both strategies, so one
3735
- * index finds the newest build of either.
4675
+ * index finds the newest build of either. A sandbox scope's key names no
4676
+ * channel, so pull requests find a sandbox build on any.
3736
4677
  */
3737
4678
  var nativeBuildScopeKey = (scope) => {
4679
+ const { sandbox } = scope;
4680
+ if (sandbox !== void 0 && sandbox !== null) {
4681
+ if (sandbox.distribution !== "direct" && sandbox.distribution !== "store") throw new NativeBuildInputError("Invalid sandbox build scope: its distribution must be direct or store.");
4682
+ return sandboxScopeKey(scope, sandbox);
4683
+ }
3738
4684
  let scopeKey;
3739
4685
  try {
3740
4686
  const channelKey = encodeChannelKey(scope.channel);
@@ -3751,32 +4697,126 @@ var nativeBuildScopeKey = (scope) => {
3751
4697
  } catch (error) {
3752
4698
  throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
3753
4699
  }
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;
4700
+ return checkedScopeKey(scopeKey);
4701
+ };
4702
+ /** The channel row a registration names, or the refusal of its channel. */
4703
+ var channelIdOf = (channel) => {
4704
+ try {
4705
+ return `channel:${encodeChannelKey(channel)}`;
4706
+ } catch (error) {
4707
+ throw new NativeBuildInputError(`Invalid native build scope: ${error instanceof Error ? error.message : String(error)}.`);
4708
+ }
4709
+ };
4710
+ /**
4711
+ * A registration's scope key, from the registration's own facts: a sandbox
4712
+ * build's from what its artifact says, whatever `sandbox` it names.
4713
+ */
4714
+ var registrationScopeKey = (registration) => {
4715
+ channelIdOf(registration.channel);
4716
+ return registration.isSandbox === true ? sandboxScopeKey(registration, {
4717
+ appId: registration.sandboxAppId,
4718
+ urlScheme: registration.sandboxUrlScheme,
4719
+ artifactKind: registration.artifact.kind,
4720
+ distribution: registeredDistribution(registration.artifact.kind, registration.exportMethod)
4721
+ }) : nativeBuildScopeKey({
4722
+ ...registration,
4723
+ sandbox: null
4724
+ });
4725
+ };
4726
+ /**
4727
+ * Refuses a patch from a sandbox build's built-in bundle: no deploy patches
4728
+ * from one, so no store or test install of the app gets a patch made for a
4729
+ * sandbox build. One unique read of the base.
4730
+ */
4731
+ var refuseSandboxPatchBase = async (db, baseBundleId) => {
4732
+ 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
4733
  };
3757
4734
  /** Whether `bundleId` is a native build's built-in bundle: one unique read. */
3758
4735
  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 }) => {
4736
+ var problemOf = ({ id, minBundleId, platform, channel, fingerprintHash, appVersion, gitCommitHash, buildKey, buildNumber, isSandbox, sandboxUrlScheme, sandboxAppId, exportMethod, nativeAppVersion, artifact }) => {
3760
4737
  if (!isUUIDv7(id)) return "id must be a UUIDv7";
3761
4738
  if (!isUUIDv7(minBundleId)) return "minBundleId must be the UUIDv7 a release build compiles in";
3762
4739
  if (platform !== "ios" && platform !== "android") return "platform must be ios or android";
3763
4740
  if (channel.trim().length === 0) return "channel is required";
4741
+ if (isSandbox !== void 0 && typeof isSandbox !== "boolean") return "isSandbox must be true or false";
4742
+ if (sandboxUrlScheme !== void 0 && sandboxUrlScheme !== null) {
4743
+ if (isSandbox !== true) return "sandboxUrlScheme is a sandbox build's, and this isn't one";
4744
+ 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`;
4745
+ }
4746
+ if (sandboxAppId !== void 0 && sandboxAppId !== null) {
4747
+ if (isSandbox !== true) return "sandboxAppId is a sandbox build's, and this isn't one";
4748
+ if (typeof sandboxAppId !== "string" || !APP_ID.test(sandboxAppId)) return "sandboxAppId must be the artifact's bundle identifier or application ID, up to 255 characters";
4749
+ }
4750
+ if (isSandbox === true) {
4751
+ if (sandboxUrlScheme === void 0 || sandboxUrlScheme === null) return "a sandbox build needs the sandboxUrlScheme its artifact registers";
4752
+ 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";
4753
+ }
3764
4754
  if (gitCommitHash !== null && gitCommitHash.length > GIT_COMMIT_HASH_MAX_LENGTH) return `gitCommitHash must be at most ${GIT_COMMIT_HASH_MAX_LENGTH} characters`;
3765
4755
  if (fingerprintHash === null === (appVersion === null)) return "exactly one of fingerprintHash and appVersion is required";
3766
4756
  if (buildKey !== null && !BUILD_KEY.test(buildKey)) return "buildKey must be nbk1: and a SHA-256, or null";
3767
4757
  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`;
4758
+ 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
4759
  const kinds = ARTIFACT_KINDS[platform];
3769
4760
  if (!kinds.includes(artifact.kind)) return `artifact.kind of an ${platform} build must be ${kinds.join(" or ")}`;
4761
+ if (exportMethod !== void 0 && exportMethod !== null) {
4762
+ if (artifact.kind !== "ipa") return "exportMethod is an .ipa's, and this artifact isn't one";
4763
+ if (!EXPORT_METHODS.has(exportMethod)) return `exportMethod must be ${[...EXPORT_METHODS].join(", ")}, or null`;
4764
+ }
3770
4765
  if (!Number.isSafeInteger(artifact.byteSize) || artifact.byteSize < 0) return "artifact.byteSize must be a byte count";
3771
4766
  return null;
3772
4767
  };
4768
+ /** The other install target of an iOS sandbox build's native code. */
4769
+ var SIBLING_KINDS = {
4770
+ app: "ipa",
4771
+ ipa: "app"
4772
+ };
4773
+ /**
4774
+ * Whether a build is one a person installs from its file: a Simulator `.app`,
4775
+ * or an `.ipa` exported for direct install, that no store took and that isn't
4776
+ * the store build. One rule for a sibling and the build it is found from, so
4777
+ * a build that shows its sibling is shown by it.
4778
+ */
4779
+ 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");
4780
+ /**
4781
+ * The scope key of the other install target of a sandbox build, from its own
4782
+ * key's app ID and URL scheme, which hold no colon, and its row's fingerprint
4783
+ * or app version, through `sandboxScopeKey`; null for a key it didn't make.
4784
+ */
4785
+ var siblingSandboxScopeKey = (build, artifactKind) => {
4786
+ const [version, sandbox, platform, appId, urlScheme] = build.scope_key.split(":");
4787
+ if (version !== "v1" || sandbox !== "sandbox" || platform !== build.platform || appId === void 0 || urlScheme === void 0) return null;
4788
+ const target = build.fingerprint_hash === null ? {
4789
+ platform: build.platform,
4790
+ fingerprintHash: null,
4791
+ appVersion: build.app_version ?? ""
4792
+ } : {
4793
+ platform: build.platform,
4794
+ fingerprintHash: build.fingerprint_hash,
4795
+ appVersion: null
4796
+ };
4797
+ try {
4798
+ return sandboxScopeKey(target, {
4799
+ appId,
4800
+ urlScheme,
4801
+ artifactKind: build.artifact_kind,
4802
+ distribution: registeredDistribution(build.artifact_kind, build.export_method)
4803
+ }) === build.scope_key ? sandboxScopeKey(target, {
4804
+ appId,
4805
+ urlScheme,
4806
+ artifactKind,
4807
+ distribution: "direct"
4808
+ }) : null;
4809
+ } catch {
4810
+ return null;
4811
+ }
4812
+ };
3773
4813
  /** The native build registry: core's `native_builds` and the built-in bundle rows. */
3774
4814
  var createNativeBuildApi = (db, { now = Date.now } = {}) => ({
3775
4815
  async registerNativeBuild(registration) {
3776
4816
  const problem = problemOf(registration);
3777
4817
  if (problem !== null) throw new NativeBuildInputError(`Invalid native build: ${problem}.`);
3778
- const scopeKey = nativeBuildScopeKey(registration);
3779
- const channelId = `channel:${encodeChannelKey(registration.channel)}`;
4818
+ const scopeKey = registrationScopeKey(registration);
4819
+ const channelId = channelIdOf(registration.channel);
3780
4820
  const { embeddedBundle } = registration;
3781
4821
  const row = {
3782
4822
  id: registration.id,
@@ -3795,7 +4835,12 @@ var createNativeBuildApi = (db, { now = Date.now } = {}) => ({
3795
4835
  build_number: registration.buildNumber ?? null,
3796
4836
  submitted_to: null,
3797
4837
  submitted_at_ms: null,
3798
- submitted_version: null
4838
+ submitted_version: null,
4839
+ is_store_build: false,
4840
+ is_sandbox: registration.isSandbox === true,
4841
+ sandbox_url_scheme: registration.sandboxUrlScheme ?? null,
4842
+ export_method: registration.exportMethod ?? null,
4843
+ native_app_version: registration.nativeAppVersion ?? null
3799
4844
  };
3800
4845
  for (let attempt = 1;; attempt += 1) {
3801
4846
  await insertChannel(db, {
@@ -3829,25 +4874,82 @@ var createNativeBuildApi = (db, { now = Date.now } = {}) => ({
3829
4874
  const row = await db.findOne("native_builds", { id });
3830
4875
  return row === null ? null : pick(row);
3831
4876
  },
4877
+ async findNativeBuildByBuiltInBundle(bundleId) {
4878
+ const row = await db.findOne("native_builds", { min_bundle_id: bundleId });
4879
+ return row === null ? null : pick(row);
4880
+ },
3832
4881
  async findNativeBuild(scope, options) {
3833
4882
  const scopeKey = nativeBuildScopeKey(scope);
3834
4883
  const buildKey = options?.buildKey;
3835
4884
  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", {
4885
+ const artifactKind = options?.artifactKind;
4886
+ 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 ")}.`);
4887
+ const ofKind = (row) => artifactKind === void 0 || row.artifact_kind === artifactKind;
4888
+ if (options?.storeBuild) {
4889
+ const marked = await db.findOne("native_builds", { store_build_scope_key: scopeKey });
4890
+ return marked === null || !ofKind(marked) ? null : pick(marked);
4891
+ }
4892
+ const read = (limit, before) => {
4893
+ const page = {
4894
+ order: "desc",
4895
+ limit,
4896
+ ...before === void 0 ? {} : { range: { lt: before } }
4897
+ };
4898
+ return buildKey !== void 0 ? db.findMany("native_builds", {
4899
+ index: "byBuildKey",
4900
+ where: {
4901
+ scope_key: scopeKey,
4902
+ build_key: buildKey
4903
+ },
4904
+ ...page
4905
+ }) : artifactKind !== void 0 ? db.findMany("native_builds", {
4906
+ index: "byScopeKind",
4907
+ where: {
4908
+ scope_key: scopeKey,
4909
+ artifact_kind: artifactKind
4910
+ },
4911
+ ...page
4912
+ }) : db.findMany("native_builds", {
4913
+ index: "byScope",
4914
+ where: { scope_key: scopeKey },
4915
+ ...page
4916
+ });
4917
+ };
4918
+ const bundleId = options?.builtInOlderThan;
4919
+ if (bundleId !== void 0 && scope.sandbox !== void 0 && scope.sandbox !== null) return null;
4920
+ const { rows } = await read(1);
4921
+ const newest = (rows[0] === void 0 ? void 0 : pick(rows[0])) ?? (artifactKind !== void 0 && buildKey === void 0 ? await db.findMany("native_builds", {
3837
4922
  index: "byScope",
3838
4923
  where: { scope_key: scopeKey },
3839
4924
  order: "desc",
3840
4925
  limit: 1
3841
- }) : await db.findMany("native_builds", {
3842
- index: "byBuildKey",
3843
- where: {
3844
- scope_key: scopeKey,
3845
- build_key: buildKey
3846
- },
4926
+ }).then(({ rows: [row] }) => row?.artifact_kind === artifactKind ? pick(row) : void 0) : void 0);
4927
+ if (newest === void 0 || !ofKind(newest)) return null;
4928
+ if (bundleId === void 0 || newest.min_bundle_id < bundleId) return newest;
4929
+ let before = newest.id;
4930
+ for (let page = 0; page < OLDER_BUILDS_PAGES; page += 1) {
4931
+ const { rows: older } = await read(OLDER_BUILDS_PAGE, before);
4932
+ const usable = older.find(({ min_bundle_id }) => min_bundle_id < bundleId);
4933
+ if (usable !== void 0) return ofKind(usable) ? pick(usable) : null;
4934
+ const last = older.at(-1);
4935
+ if (older.length < OLDER_BUILDS_PAGE || last === void 0) return null;
4936
+ before = last.id;
4937
+ }
4938
+ return null;
4939
+ },
4940
+ async findNativeBuildSibling(build) {
4941
+ const artifactKind = SIBLING_KINDS[build.artifact_kind];
4942
+ if (build.platform !== "ios" || !build.is_sandbox || artifactKind === void 0 || !isInstallTarget(build)) return null;
4943
+ const scopeKey = siblingSandboxScopeKey(build, artifactKind);
4944
+ if (scopeKey === null) return null;
4945
+ const { rows } = await db.findMany("native_builds", {
4946
+ index: "byScope",
4947
+ where: { scope_key: scopeKey },
3847
4948
  order: "desc",
3848
4949
  limit: 1
3849
4950
  });
3850
- return rows[0] === void 0 ? null : pick(rows[0]);
4951
+ const sibling = rows[0] === void 0 ? null : pick(rows[0]);
4952
+ return sibling !== null && isInstallTarget(sibling) ? sibling : null;
3851
4953
  },
3852
4954
  async recordNativeBuildSubmission(id, { destination, version }) {
3853
4955
  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 +4957,8 @@ var createNativeBuildApi = (db, { now = Date.now } = {}) => ({
3855
4957
  const row = await tx.findOne("native_builds", { id });
3856
4958
  if (row === null) return null;
3857
4959
  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}.`);
4960
+ 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}.`);
4961
+ 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
4962
  const set = {
3860
4963
  submitted_to: destination,
3861
4964
  submitted_at_ms: now(),
@@ -3868,6 +4971,46 @@ var createNativeBuildApi = (db, { now = Date.now } = {}) => ({
3868
4971
  };
3869
4972
  });
3870
4973
  },
4974
+ async markNativeBuild(id, { storeBuild }) {
4975
+ for (let attempt = 1;; attempt += 1) try {
4976
+ return await db.transaction(async (tx) => {
4977
+ const row = await tx.findOne("native_builds", { id });
4978
+ if (row === null) return null;
4979
+ const build = pick(row);
4980
+ if (!storeBuild) {
4981
+ if (build.is_store_build) tx.update("native_builds", row, { is_store_build: false });
4982
+ return {
4983
+ nativeBuild: {
4984
+ ...build,
4985
+ is_store_build: false
4986
+ },
4987
+ previous: null
4988
+ };
4989
+ }
4990
+ if (build.is_sandbox) throw new NativeBuildInputError("A sandbox build can't be the store build.");
4991
+ if (build.is_store_build) return {
4992
+ nativeBuild: build,
4993
+ previous: null
4994
+ };
4995
+ const holder = await tx.findOne("native_builds", { store_build_scope_key: build.scope_key });
4996
+ if (holder !== null) tx.update("native_builds", holder, { is_store_build: false });
4997
+ tx.update("native_builds", row, { is_store_build: true });
4998
+ return {
4999
+ nativeBuild: {
5000
+ ...build,
5001
+ is_store_build: true
5002
+ },
5003
+ previous: holder === null ? null : {
5004
+ ...pick(holder),
5005
+ is_store_build: false
5006
+ }
5007
+ };
5008
+ });
5009
+ } catch (error) {
5010
+ if (attempt < MARK_ATTEMPTS && error instanceof DatabaseConstraintError && error.reason === "unique") continue;
5011
+ throw error;
5012
+ }
5013
+ },
3871
5014
  async deleteNativeBuild(id) {
3872
5015
  return db.transaction(async (tx) => {
3873
5016
  const row = await tx.findOne("native_builds", { id });
@@ -3921,44 +5064,43 @@ var checkScope = (scope) => {
3921
5064
  });
3922
5065
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
3923
5066
  };
3924
- /** A scope's enabled releases, all of them, under the catalog's guard. */
3925
- var enabledReleases = async (tx, scopeKey) => {
5067
+ /** Every row of a paged read, as release rows. */
5068
+ var drainReleases = async (page) => {
3926
5069
  const rows = [];
3927
5070
  let cursor;
3928
5071
  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;
5072
+ const found = await page(cursor);
5073
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
5074
+ cursor = found.next;
3940
5075
  } while (cursor !== void 0);
3941
5076
  return rows;
3942
5077
  };
3943
- /** The scope's newest release id: `byScope` descending, limit 1. */
3944
- var latestReleaseId = async (tx, scopeKey) => {
5078
+ var enabledIn = (scopeKey, cursor) => ({
5079
+ index: "byScopeEnabled",
5080
+ where: {
5081
+ scope_key: scopeKey,
5082
+ enabled: true
5083
+ },
5084
+ limit: PAGE,
5085
+ ...cursor === void 0 ? {} : { cursor }
5086
+ });
5087
+ /** A scope's enabled releases, all of them, under the catalog's guard. */
5088
+ var enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
5089
+ /** The scope's newest release: `byScope` descending, limit 1. */
5090
+ var latestRelease = async (tx, scopeKey) => {
3945
5091
  const { rows } = await tx.findMany("releases", {
3946
5092
  index: "byScope",
3947
5093
  where: { scope_key: scopeKey },
3948
5094
  order: "desc",
3949
5095
  limit: 1
3950
5096
  });
3951
- return rows[0]?.id ?? null;
5097
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
3952
5098
  };
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;
5099
+ /** The scope's next catalog generation, compiled as `compilation`. */
5100
+ var nextCatalog = (scope, stored, compilation, updatedAtMs) => {
5101
+ const generation = (stored.catalog?.generation ?? 0) + 1;
3960
5102
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
3961
- const catalog = {
5103
+ return {
3962
5104
  scope_key: scope.scopeKey,
3963
5105
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
3964
5106
  strategy: scope.strategy,
@@ -3973,6 +5115,26 @@ var writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
3973
5115
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
3974
5116
  updated_at_ms: updatedAtMs
3975
5117
  };
5118
+ };
5119
+ /**
5120
+ * Compiles a scope's enabled releases. A catalog over the size limit is
5121
+ * refused naming its channel and platform, and what frees room in it.
5122
+ */
5123
+ var compileScope = async (scope, enabled) => {
5124
+ try {
5125
+ return await compileReleaseCatalog({
5126
+ strategy: scope.strategy,
5127
+ releases: enabled.map(releaseRowToRelease)
5128
+ });
5129
+ } catch (error) {
5130
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
5131
+ 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.`);
5132
+ }
5133
+ };
5134
+ /** Compiles `enabled` and writes it as the scope's next catalog generation. */
5135
+ var writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
5136
+ const compilation = await compileScope(scope, enabled);
5137
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
3976
5138
  const { scope_key: _scopeKey, ...set } = catalog;
3977
5139
  if (stored.row === null) tx.create("release_catalogs", catalog);
3978
5140
  else tx.update("release_catalogs", stored.row, set);
@@ -3994,11 +5156,16 @@ var readCatalog = async (tx, scopeKey) => {
3994
5156
  var assertHistory = (stored, hasReleases) => {
3995
5157
  if (stored.catalog === null && hasReleases) fail$1("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
3996
5158
  };
3997
- /** One release change and its scope's next catalog, inside `tx`. */
3998
- var changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
5159
+ /**
5160
+ * One release change and its scope's next catalog, inside `tx`. An insert
5161
+ * takes its channel and platform's next label from `labels`, after labeling
5162
+ * the releases a server of an earlier release wrote in the scope since its
5163
+ * last labeled one.
5164
+ */
5165
+ var changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
3999
5166
  checkScope(scope);
4000
5167
  const stored = await readCatalog(tx, scope.scopeKey);
4001
- const enabled = await enabledReleases(tx, scope.scopeKey);
5168
+ let enabled = await enabledReleases(tx, scope.scopeKey);
4002
5169
  if (bundle !== void 0) {
4003
5170
  insertBundle(tx, bundle.row);
4004
5171
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -4006,14 +5173,22 @@ var changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
4006
5173
  let before = null;
4007
5174
  let release;
4008
5175
  if (change.operation === "insert") {
4009
- const latest = await latestReleaseId(tx, scope.scopeKey);
5176
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
5177
+ const newest = await latestRelease(tx, scope.scopeKey);
5178
+ const latest = newest?.id ?? null;
4010
5179
  assertHistory(stored, latest !== null);
4011
5180
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
4012
5181
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
4013
5182
  if (latest !== null && id <= latest) fail$1("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
5183
+ const given = await catchUpLabels(tx, labels, newest);
5184
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
5185
+ ...row,
5186
+ label: given.get(row.id)
5187
+ } : row);
4014
5188
  release = {
4015
5189
  ...change.row,
4016
- id
5190
+ id,
5191
+ label: await labels.next(scope.channelId, scope.platform)
4017
5192
  };
4018
5193
  if (release.scope_key !== scope.scopeKey || release.channel_id !== scope.channelId || release.platform !== scope.platform || release.strategy !== scope.strategy || release.fingerprint_hash !== scope.fingerprintHash || release.revision !== 1) fail$1("INVALID_SCOPE", "Inserted Release does not match its catalog scope");
4019
5194
  tx.create("releases", release);
@@ -4026,8 +5201,9 @@ var changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
4026
5201
  await tx.delete("releases", row);
4027
5202
  release = null;
4028
5203
  } else {
5204
+ const { label: _label, ...update } = change.update;
4029
5205
  const set = {
4030
- ...change.update,
5206
+ ...update,
4031
5207
  revision: before.revision + 1
4032
5208
  };
4033
5209
  tx.update("releases", row, set);
@@ -4054,24 +5230,69 @@ var changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
4054
5230
  */
4055
5231
  var changeReleases = (db, inputs) => {
4056
5232
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail$1("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
4057
- return db.transaction(async (tx) => {
5233
+ return writeWithLabels(db, async (tx, labels) => {
4058
5234
  const results = [];
4059
- for (const input of inputs) results.push(await changeRelease(tx, input));
5235
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
4060
5236
  return results;
4061
5237
  });
4062
5238
  };
5239
+ /** Whether `current` is what the scope's enabled releases compile to. */
5240
+ 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;
5241
+ /** A compiled payload with its descriptors' labels left out. */
5242
+ var withoutLabels = (payload) => {
5243
+ const parsed = JSON.parse(payload);
5244
+ return JSON.stringify({
5245
+ ...parsed,
5246
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
5247
+ });
5248
+ };
5249
+ /**
5250
+ * Whether `projected` differs from `current` only by release labels, as a
5251
+ * catalog compiled before its releases had them does.
5252
+ */
5253
+ var differsInLabelsOnly = (current, projected) => current.payload !== projected.payload && current.strategy === projected.strategy && current.channel_id === projected.channel_id && current.channel_key === projected.channel_key && current.platform === projected.platform && current.fingerprint_hash === projected.fingerprint_hash && withoutLabels(current.payload) === withoutLabels(projected.payload);
5254
+ /** The scope a catalog row names. */
5255
+ var catalogRowScope = (row) => ({
5256
+ channelId: row.channel_id,
5257
+ channelName: decodeChannelKey(row.channel_key),
5258
+ fingerprintHash: row.fingerprint_hash,
5259
+ platform: row.platform,
5260
+ scopeKey: row.scope_key,
5261
+ strategy: row.strategy
5262
+ });
5263
+ /**
5264
+ * What a rebuild of the scope's catalog would write, without writing: one
5265
+ * read of the catalog row and one of the scope's enabled releases. It needs
5266
+ * no transaction, whose guards would read the catalog again for each read
5267
+ * beneath it, nor the scope's newest release, which matters only to a scope
5268
+ * without a catalog row; that one is not found.
5269
+ */
5270
+ var preflightRebuild = async (db, scopeKey, updatedAtMs) => {
5271
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
5272
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
5273
+ const current = toCatalogRow(row);
5274
+ const scope = catalogRowScope(current);
5275
+ checkScope(scope);
5276
+ const compilation = await compileScope(scope, await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor))));
5277
+ const changed = !isCurrent(scope, current, compilation);
5278
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
5279
+ return {
5280
+ changed,
5281
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
5282
+ currentCatalog: current,
5283
+ diagnostics: compilation.diagnostics,
5284
+ projectedCatalog
5285
+ };
5286
+ };
4063
5287
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
4064
5288
  var rebuildScope = async (tx, scope, updatedAtMs) => {
4065
5289
  checkScope(scope);
4066
5290
  const stored = await readCatalog(tx, scope.scopeKey);
4067
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
5291
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
4068
5292
  const enabled = await enabledReleases(tx, scope.scopeKey);
4069
- const compilation = await compileReleaseCatalog({
4070
- strategy: scope.strategy,
4071
- releases: enabled.map(releaseRowToRelease)
4072
- });
5293
+ const compilation = await compileScope(scope, enabled);
4073
5294
  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 {
5295
+ if (current !== null && isCurrent(scope, current, compilation)) return {
4075
5296
  catalog: current,
4076
5297
  current,
4077
5298
  changed: false,
@@ -4085,6 +5306,7 @@ var rebuildScope = async (tx, scope, updatedAtMs) => {
4085
5306
  diagnostics: written.compilation.diagnostics
4086
5307
  };
4087
5308
  };
5309
+ var CATALOG_PAGE = 100;
4088
5310
  /** Carries a preflight's result out of the transaction it stops, so nothing is written. */
4089
5311
  var Preflight = class extends Error {
4090
5312
  result;
@@ -4173,14 +5395,7 @@ var mutationResult = ({ catalog, release }) => ({
4173
5395
  var catalogScope = async (tx, scopeKey) => {
4174
5396
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
4175
5397
  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
- };
5398
+ return catalogRowScope(toCatalogRow(row));
4184
5399
  };
4185
5400
  /**
4186
5401
  * Core's typed writes: each runs in one engine transaction rooted at the
@@ -4209,7 +5424,11 @@ var createCoreOperations = (db, { now = Date.now } = {}) => {
4209
5424
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
4210
5425
  const platforms = /* @__PURE__ */ new Map();
4211
5426
  for (const deployment of deployments) {
4212
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
5427
+ if (!("bundleId" in deployment)) {
5428
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
5429
+ continue;
5430
+ }
5431
+ if (platforms.has(deployment.bundleId)) continue;
4213
5432
  const row = await db.findOne("bundles", { id: deployment.bundleId });
4214
5433
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
4215
5434
  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.`);
@@ -4319,7 +5538,7 @@ var createCoreOperations = (db, { now = Date.now } = {}) => {
4319
5538
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
4320
5539
  const channel = await ensureChannel(targetChannel);
4321
5540
  const updatedAtMs = now();
4322
- return db.transaction(async (tx) => {
5541
+ return writeWithLabels(db, async (tx, labels) => {
4323
5542
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
4324
5543
  checkSource(source);
4325
5544
  const targetScope = scopeOf(channel, source.platform, source.fingerprint_hash);
@@ -4347,12 +5566,13 @@ var createCoreOperations = (db, { now = Date.now } = {}) => {
4347
5566
  },
4348
5567
  updatedAtMs
4349
5568
  }) : null;
5569
+ const { label: _label, ...copied } = source;
4350
5570
  const target = await changeRelease(tx, {
4351
5571
  scope: targetScope,
4352
5572
  change: {
4353
5573
  operation: "insert",
4354
5574
  row: {
4355
- ...source,
5575
+ ...copied,
4356
5576
  id: createUUIDv7After(floor ?? null, updatedAtMs),
4357
5577
  revision: 1,
4358
5578
  scope_key: targetScope.scopeKey,
@@ -4367,7 +5587,7 @@ var createCoreOperations = (db, { now = Date.now } = {}) => {
4367
5587
  }
4368
5588
  },
4369
5589
  updatedAtMs
4370
- });
5590
+ }, labels);
4371
5591
  return {
4372
5592
  source: moved === null ? null : mutationResult(moved),
4373
5593
  target: mutationResult(target)
@@ -4384,17 +5604,38 @@ var createCoreOperations = (db, { now = Date.now } = {}) => {
4384
5604
  };
4385
5605
  });
4386
5606
  },
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
- });
5607
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
5608
+ fillReleaseLabels: async ({ dryRun = false, catalogs = true } = {}) => {
5609
+ let releases = 0;
5610
+ const pairs = await pendingLabelPairs(db);
5611
+ if (dryRun && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
5612
+ for (const pair of pairs) releases += await fillLabels(db, pair, { dryRun });
5613
+ let rebuilt = 0;
5614
+ if (catalogs) {
5615
+ let cursor;
5616
+ do {
5617
+ const page = await db.findMany("release_catalogs", {
5618
+ index: "all",
5619
+ where: {},
5620
+ limit: CATALOG_PAGE,
5621
+ ...cursor === void 0 ? {} : { cursor }
5622
+ });
5623
+ for (const row of page.rows) {
5624
+ if (row.is_tombstone) continue;
5625
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
5626
+ if (preflight === null || !preflight.labelsOnly) continue;
5627
+ rebuilt += 1;
5628
+ if (dryRun) continue;
5629
+ const updatedAtMs = now();
5630
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
5631
+ }
5632
+ cursor = page.next;
5633
+ } while (cursor !== void 0);
5634
+ }
5635
+ return {
5636
+ releases,
5637
+ catalogs: rebuilt
5638
+ };
4398
5639
  },
4399
5640
  ensureChannel,
4400
5641
  deleteChannel: (id) => deleteChannel(db, id),
@@ -4412,7 +5653,7 @@ var createCoreOperations = (db, { now = Date.now } = {}) => {
4412
5653
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
4413
5654
  ...next,
4414
5655
  patches
4415
- }));
5656
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
4416
5657
  }),
4417
5658
  deleteBundles: async (ids) => {
4418
5659
  try {
@@ -4472,6 +5713,7 @@ var createCoreApi = (db, storage, options = {}) => {
4472
5713
  ...reads,
4473
5714
  ...createCoreOperations(purgingCachedRoutes(db, options.onCachedRoutesChange), options),
4474
5715
  ...createNativeBuildApi(db, options),
5716
+ ...createIosDeviceApi(db, options),
4475
5717
  ready: async () => {
4476
5718
  await reads.listReleaseCatalogs({ limit: 1 });
4477
5719
  }
@@ -4655,6 +5897,10 @@ var answer = async (operation) => {
4655
5897
  error: error.message
4656
5898
  }, status);
4657
5899
  }
5900
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json({
5901
+ code: error.code,
5902
+ error: error.message
5903
+ }, 400);
4658
5904
  if (error instanceof DatabaseBundleNotFoundError) return json({
4659
5905
  code: "BUNDLE_NOT_FOUND",
4660
5906
  error: error.message
@@ -4674,18 +5920,22 @@ var LIMITS = {
4674
5920
  defaultValue: 50,
4675
5921
  maxValue: 500
4676
5922
  };
5923
+ /** The most IDs one request names: a lookup's, or a write's. */
5924
+ var MAX_IDS = 100;
4677
5925
  /** `order`, `cursor`, and `limit`: one keyset page. */
4678
- var keyset = (url, maxValue = LIMITS.maxValue) => {
4679
- const order = url.searchParams.get("order") ?? "desc";
5926
+ var keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
5927
+ const order = url.searchParams.get("order") ?? defaultOrder;
4680
5928
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
4681
5929
  const limitParam = url.searchParams.get("limit");
4682
5930
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
4683
5931
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > maxValue) throw new HandlerBadRequestError(`limit must be between 1 and ${maxValue}.`);
4684
5932
  const cursor = url.searchParams.get("cursor");
5933
+ const through = url.searchParams.get("through");
4685
5934
  return {
4686
5935
  order,
4687
5936
  limit,
4688
- ...cursor === null ? {} : { after: cursor }
5937
+ ...cursor === null ? {} : { after: cursor },
5938
+ ...through === null ? {} : { through }
4689
5939
  };
4690
5940
  };
4691
5941
  /** A page and the cursor of the next one, when the page is full. */
@@ -4783,7 +6033,8 @@ var nativeBuildScopeOf = (url) => {
4783
6033
  const fingerprintHash = params.get("fingerprintHash");
4784
6034
  const appVersion = params.get("appVersion");
4785
6035
  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 ? {
6036
+ const sandbox = sandboxScopeOf(params);
6037
+ const scope = fingerprintHash !== null ? {
4787
6038
  platform,
4788
6039
  channel,
4789
6040
  fingerprintHash,
@@ -4794,17 +6045,49 @@ var nativeBuildScopeOf = (url) => {
4794
6045
  fingerprintHash: null,
4795
6046
  appVersion
4796
6047
  };
6048
+ return sandbox === null ? scope : {
6049
+ ...scope,
6050
+ sandbox
6051
+ };
6052
+ };
6053
+ /** The query parameters a sandbox lookup names, all four or none. */
6054
+ var SANDBOX_SCOPE_PARAMS = [
6055
+ "sandboxAppId",
6056
+ "sandboxUrlScheme",
6057
+ "artifactKind",
6058
+ "distribution"
6059
+ ];
6060
+ /**
6061
+ * A lookup's sandbox scope: null without one, and a bad request for one
6062
+ * named in part. Core checks each value.
6063
+ */
6064
+ var sandboxScopeOf = (params) => {
6065
+ const [appId, urlScheme, artifactKind, distribution] = SANDBOX_SCOPE_PARAMS.map((name) => params.get(name));
6066
+ const named = [
6067
+ appId,
6068
+ urlScheme,
6069
+ artifactKind,
6070
+ distribution
6071
+ ].filter((value) => value !== null).length;
6072
+ if (named === 0) return null;
6073
+ if (named !== SANDBOX_SCOPE_PARAMS.length) throw new HandlerBadRequestError(`A sandbox build lookup needs ${SANDBOX_SCOPE_PARAMS.join(", ")}.`);
6074
+ return {
6075
+ appId,
6076
+ urlScheme,
6077
+ artifactKind,
6078
+ distribution
6079
+ };
4797
6080
  };
4798
6081
  /** A native build or scope core refuses: a bad request. */
4799
6082
  var refusingInvalid = async (operation) => {
4800
6083
  try {
4801
6084
  return await operation();
4802
6085
  } catch (error) {
4803
- if (error instanceof NativeBuildInputError) throw new HandlerBadRequestError(error.message);
6086
+ if (error instanceof NativeBuildInputError || error instanceof IosDeviceInputError) throw new HandlerBadRequestError(error.message);
4804
6087
  throw error;
4805
6088
  }
4806
6089
  };
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));
6090
+ 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
6091
  var scopeKeyOf = (params) => decodeMaybe(requireRouteParam(params, "scopeKey")) ?? "";
4809
6092
  /** Every admin route's handler, by the name `ADMIN_ROUTES` mounts it under. */
4810
6093
  var createAdminRouteHandlers = () => ({
@@ -4835,11 +6118,32 @@ var createAdminRouteHandlers = () => ({
4835
6118
  const input = keyset(new URL(request.url));
4836
6119
  return page(await core.listReleaseCatalogs(input), input, (row) => row.scope_key);
4837
6120
  }),
6121
+ listReleaseScopeKeys: onCore(async (core, request) => {
6122
+ const input = keyset(new URL(request.url), 100, "asc");
6123
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
6124
+ return page(await core.listReleaseScopeKeys({
6125
+ limit: input.limit,
6126
+ ...input.after === void 0 ? {} : { after: input.after }
6127
+ }), input, (scopeKey) => scopeKey);
6128
+ }),
4838
6129
  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 });
6130
+ const url = new URL(request.url);
6131
+ const name = url.searchParams.get("name");
6132
+ if (name !== null) {
6133
+ const channel = await core.findChannelByName(name);
6134
+ return channel === null ? notFound() : json({ data: channel });
6135
+ }
6136
+ const ids = url.searchParams.get("ids");
6137
+ if (ids !== null) {
6138
+ const list = ids.split(",").filter((id) => id.length > 0);
6139
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
6140
+ return json({ data: await core.getChannels(list) });
6141
+ }
6142
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
6143
+ const input = keyset(url, LIMITS.maxValue, "asc");
6144
+ return page(await core.listChannels(input), input, (row) => row.name);
6145
+ }
6146
+ return json({ data: await core.listChannels() });
4843
6147
  }),
4844
6148
  createChannel: onCore(async (core, request) => {
4845
6149
  const { name } = await body(request);
@@ -4878,15 +6182,36 @@ var createAdminRouteHandlers = () => ({
4878
6182
  return row === null ? notFound() : json({ data: row });
4879
6183
  }),
4880
6184
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
6185
+ getReleaseByLabel: onCore(async (core, request) => {
6186
+ const url = new URL(request.url);
6187
+ const channel = url.searchParams.get("channel");
6188
+ const platform = platformOf(url);
6189
+ const label = Number(url.searchParams.get("label"));
6190
+ if (channel === null || channel.length === 0 || platform === void 0 || !Number.isSafeInteger(label) || label < 1) throw new HandlerBadRequestError("A release label lookup takes channel, platform, and a label of 1 or more.");
6191
+ return json({ data: await core.getReleaseByLabel({
6192
+ channel,
6193
+ platform,
6194
+ label
6195
+ }) });
6196
+ }),
6197
+ fillReleaseLabels: onCore(async (core, request) => {
6198
+ const body = await request.json().catch(() => ({}));
6199
+ const input = body !== null && typeof body === "object" ? body : {};
6200
+ return json({ data: await core.fillReleaseLabels({
6201
+ dryRun: input.dryRun === true,
6202
+ catalogs: input.catalogs !== false
6203
+ }) });
6204
+ }),
4881
6205
  updateBundle: onCore(async (core, request, params) => {
4882
6206
  const bundleId = requireRouteParam(params, "id");
4883
- await core.updateBundle(bundleId, bundleUpdateOf(await request.json(), bundleId));
6207
+ const update = bundleUpdateOf(await request.json(), bundleId);
6208
+ await refusingInvalid(() => core.updateBundle(bundleId, update));
4884
6209
  return noContent();
4885
6210
  }),
4886
6211
  countBundles: onCore(async (core, request) => json({ data: await core.countBundles(platformOf(new URL(request.url))) })),
4887
6212
  countBundleChildren: onCore(async (core, request) => {
4888
6213
  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.");
6214
+ 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
6215
  return json({ data: await core.countBundleChildren(ids) });
4891
6216
  }),
4892
6217
  listBundleChildren: onCore(async (core, request, params) => {
@@ -4903,7 +6228,7 @@ var createAdminRouteHandlers = () => ({
4903
6228
  deployReleases: onCore(async (core, request) => {
4904
6229
  const { deployments } = await body(request);
4905
6230
  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);
6231
+ return json({ data: await refusingInvalid(() => core.deploy(deployments)) }, 201);
4907
6232
  }),
4908
6233
  promoteRelease: onCore(async (core, request, params) => {
4909
6234
  const input = await body(request);
@@ -4926,9 +6251,22 @@ var createAdminRouteHandlers = () => ({
4926
6251
  const url = new URL(request.url);
4927
6252
  const scope = nativeBuildScopeOf(url);
4928
6253
  const buildKey = url.searchParams.get("buildKey");
4929
- return json({ data: await refusingInvalid(() => buildKey === null ? core.findNativeBuild(scope) : core.findNativeBuild(scope, { buildKey })) });
6254
+ const builtInOlderThan = url.searchParams.get("builtInOlderThan");
6255
+ const kind = url.searchParams.get("kind");
6256
+ const options = {
6257
+ ...buildKey === null ? {} : { buildKey },
6258
+ ...url.searchParams.get("storeBuild") === "true" ? { storeBuild: true } : {},
6259
+ ...builtInOlderThan === null ? {} : { builtInOlderThan },
6260
+ ...kind === null ? {} : { artifactKind: kind }
6261
+ };
6262
+ return json({ data: await refusingInvalid(() => Object.keys(options).length === 0 ? core.findNativeBuild(scope) : core.findNativeBuild(scope, options)) });
6263
+ }),
6264
+ findNativeBuildSibling: onCore(async (core, _request, params) => {
6265
+ const build = await core.getNativeBuild(requireRouteParam(params, "id"));
6266
+ return json({ data: build === null ? null : await core.findNativeBuildSibling(build) });
4930
6267
  }),
4931
6268
  getNativeBuild: onCore(async (core, _request, params) => json({ data: await core.getNativeBuild(requireRouteParam(params, "id")) })),
6269
+ findNativeBuildByBuiltInBundle: onCore(async (core, _request, params) => json({ data: await core.findNativeBuildByBuiltInBundle(requireRouteParam(params, "bundleId")) })),
4932
6270
  listNativeBuilds: onCore(async (core, request) => {
4933
6271
  const url = new URL(request.url);
4934
6272
  const input = keyset(url);
@@ -4940,14 +6278,97 @@ var createAdminRouteHandlers = () => ({
4940
6278
  }),
4941
6279
  recordNativeBuildSubmission: onCore(async (core, request, params) => {
4942
6280
  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.");
6281
+ 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
6282
  const submission = {
4945
6283
  destination: input.destination,
4946
6284
  version: input.version
4947
6285
  };
4948
6286
  return json({ data: await refusingInvalid(() => core.recordNativeBuildSubmission(requireRouteParam(params, "id"), submission)) });
4949
6287
  }),
6288
+ markNativeBuild: onCore(async (core, request, params) => {
6289
+ const input = await body(request);
6290
+ if (!isRecord$1(input) || typeof input.storeBuild !== "boolean") throw new HandlerBadRequestError("A native build's store build mark needs storeBuild, true or false.");
6291
+ const mark = { storeBuild: input.storeBuild };
6292
+ return json({ data: await refusingInvalid(() => core.markNativeBuild(requireRouteParam(params, "id"), mark)) });
6293
+ }),
4950
6294
  deleteNativeBuild: onCore(async (core, _request, params) => json({ data: await core.deleteNativeBuild(requireRouteParam(params, "id")) })),
6295
+ listIosDevices: onCore(async (core, request) => {
6296
+ const url = new URL(request.url);
6297
+ const input = keyset(url);
6298
+ const status = url.searchParams.get("status");
6299
+ return page(await refusingInvalid(() => core.listIosDevices({
6300
+ ...input,
6301
+ ...status === null ? {} : { status }
6302
+ })), input, ({ id }) => id);
6303
+ }),
6304
+ findIosDevice: onCore(async (core, _request, params) => json({ data: await core.findIosDevice(requireRouteParam(params, "udid")) })),
6305
+ requestIosDevice: onCore(async (core, request) => {
6306
+ const input = await body(request);
6307
+ 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.");
6308
+ const device = {
6309
+ udid: input.udid,
6310
+ name: input.name,
6311
+ requestedBy: input.requestedBy
6312
+ };
6313
+ return json({ data: await refusingInvalid(() => core.requestIosDevice(device)) });
6314
+ }),
6315
+ approveIosDevice: onCore(async (core, request, params) => {
6316
+ const input = await body(request);
6317
+ 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.");
6318
+ const approval = {
6319
+ approvedBy: input.approvedBy,
6320
+ ...input.name === void 0 ? {} : { name: input.name }
6321
+ };
6322
+ return json({ data: await refusingInvalid(() => core.approveIosDevice(requireRouteParam(params, "id"), approval)) });
6323
+ }),
6324
+ renameIosDevice: onCore(async (core, request, params) => {
6325
+ const input = await body(request);
6326
+ if (!isText(input.name)) throw new HandlerBadRequestError("An iOS device's new name is required.");
6327
+ const name = input.name;
6328
+ return json({ data: await refusingInvalid(() => core.renameIosDevice(requireRouteParam(params, "id"), name)) });
6329
+ }),
6330
+ recordIosDeviceOutcome: onCore(async (core, request, params) => {
6331
+ const input = await body(request);
6332
+ const seen = input.seen;
6333
+ 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.");
6334
+ const outcome = {
6335
+ id: requireRouteParam(params, "id"),
6336
+ seen: {
6337
+ status: seen.status,
6338
+ approvedAtMs: seen.approvedAtMs
6339
+ },
6340
+ issuerId: input.issuerId,
6341
+ outcome: input.outcome,
6342
+ ...input.reason === void 0 ? {} : { reason: input.reason }
6343
+ };
6344
+ return json({ data: await refusingInvalid(() => core.recordIosDeviceOutcome(outcome)) });
6345
+ }),
6346
+ claimIosDeviceAccount: onCore(async (core, request) => {
6347
+ const { issuerId } = await body(request);
6348
+ if (!isText(issuerId)) throw new HandlerBadRequestError("Claiming the iOS device account needs issuerId.");
6349
+ return json({ data: await refusingInvalid(() => core.claimIosDeviceAccount(issuerId)) });
6350
+ }),
6351
+ findIosDeviceAccount: onCore(async (core) => json({ data: await core.findIosDeviceAccount() })),
6352
+ markIosDevicesInBuild: onCore(async (core, request) => {
6353
+ const { buildId, ids } = await body(request);
6354
+ if (!isText(buildId) || !Array.isArray(ids) || !ids.every((id) => isText(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
6355
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
6356
+ await core.markIosDevicesInBuild({
6357
+ buildId,
6358
+ ids
6359
+ });
6360
+ return noContent();
6361
+ }),
6362
+ deleteIosDevice: onCore(async (core, request, params) => {
6363
+ const url = new URL(request.url);
6364
+ const status = url.searchParams.get("status");
6365
+ const requestedBy = url.searchParams.get("requestedBy");
6366
+ const only = {
6367
+ ...status === null ? {} : { status },
6368
+ ...requestedBy === null ? {} : { requestedBy }
6369
+ };
6370
+ return json({ data: await refusingInvalid(() => Object.keys(only).length === 0 ? core.deleteIosDevice(requireRouteParam(params, "id")) : core.deleteIosDevice(requireRouteParam(params, "id"), only)) });
6371
+ }),
4951
6372
  deleteBundles: onCore(async (core, request) => {
4952
6373
  const { ids } = await body(request);
4953
6374
  if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new HandlerBadRequestError("Bundle deletion needs ids");
@@ -5002,6 +6423,21 @@ var ADMIN_ROUTES = [
5002
6423
  path: "/release-catalogs",
5003
6424
  handler: "listReleaseCatalogs"
5004
6425
  },
6426
+ {
6427
+ method: "GET",
6428
+ path: "/release-scopes",
6429
+ handler: "listReleaseScopeKeys"
6430
+ },
6431
+ {
6432
+ method: "GET",
6433
+ path: "/release-labels",
6434
+ handler: "getReleaseByLabel"
6435
+ },
6436
+ {
6437
+ method: "POST",
6438
+ path: "/release-labels/fill",
6439
+ handler: "fillReleaseLabels"
6440
+ },
5005
6441
  {
5006
6442
  method: "POST",
5007
6443
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -5077,6 +6513,16 @@ var ADMIN_ROUTES = [
5077
6513
  path: "/native-builds/latest",
5078
6514
  handler: "findNativeBuild"
5079
6515
  },
6516
+ {
6517
+ method: "GET",
6518
+ path: "/native-builds/built-in/:bundleId",
6519
+ handler: "findNativeBuildByBuiltInBundle"
6520
+ },
6521
+ {
6522
+ method: "GET",
6523
+ path: "/native-builds/:id/sibling",
6524
+ handler: "findNativeBuildSibling"
6525
+ },
5080
6526
  {
5081
6527
  method: "GET",
5082
6528
  path: "/native-builds/:id",
@@ -5092,10 +6538,65 @@ var ADMIN_ROUTES = [
5092
6538
  path: "/native-builds/:id/submission",
5093
6539
  handler: "recordNativeBuildSubmission"
5094
6540
  },
6541
+ {
6542
+ method: "POST",
6543
+ path: "/native-builds/:id/store-build",
6544
+ handler: "markNativeBuild"
6545
+ },
5095
6546
  {
5096
6547
  method: "DELETE",
5097
6548
  path: "/native-builds/:id",
5098
6549
  handler: "deleteNativeBuild"
6550
+ },
6551
+ {
6552
+ method: "GET",
6553
+ path: "/ios-devices",
6554
+ handler: "listIosDevices"
6555
+ },
6556
+ {
6557
+ method: "POST",
6558
+ path: "/ios-devices",
6559
+ handler: "requestIosDevice"
6560
+ },
6561
+ {
6562
+ method: "GET",
6563
+ path: "/ios-devices/udid/:udid",
6564
+ handler: "findIosDevice"
6565
+ },
6566
+ {
6567
+ method: "POST",
6568
+ path: "/ios-devices/in-build",
6569
+ handler: "markIosDevicesInBuild"
6570
+ },
6571
+ {
6572
+ method: "GET",
6573
+ path: "/ios-devices/account",
6574
+ handler: "findIosDeviceAccount"
6575
+ },
6576
+ {
6577
+ method: "POST",
6578
+ path: "/ios-devices/account",
6579
+ handler: "claimIosDeviceAccount"
6580
+ },
6581
+ {
6582
+ method: "POST",
6583
+ path: "/ios-devices/:id/approval",
6584
+ handler: "approveIosDevice"
6585
+ },
6586
+ {
6587
+ method: "POST",
6588
+ path: "/ios-devices/:id/outcome",
6589
+ handler: "recordIosDeviceOutcome"
6590
+ },
6591
+ {
6592
+ method: "PATCH",
6593
+ path: "/ios-devices/:id",
6594
+ handler: "renameIosDevice"
6595
+ },
6596
+ {
6597
+ method: "DELETE",
6598
+ path: "/ios-devices/:id",
6599
+ handler: "deleteIosDevice"
5099
6600
  }
5100
6601
  ];
5101
6602
  var CATALOG_CONTENT_TYPE = "application/vnd.hot-updater.release-catalog+json; version=1";
@@ -5116,9 +6617,9 @@ var CATALOG_CACHE_CONTROL = "public, max-age=0, s-maxage=5";
5116
6617
  * background. `stale-if-error=0` keeps origin errors visible: without it,
5117
6618
  * Cloudflare serves a stale copy on error indefinitely.
5118
6619
  *
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
6620
+ * A device can see a catalog, or a scope's lack of one, up to 15 seconds
6621
+ * after a deploy or a Roll back replaced it: the origin's 5-second catalog
6622
+ * memo, then 5 seconds fresh and 5 stale at the CDN. A revoked API key can read a cached catalog up to
5122
6623
  * 10 seconds. Devices and caches that don't read the header keep
5123
6624
  * `Cache-Control`.
5124
6625
  */
@@ -5197,38 +6698,52 @@ var catalogResponse = async (catalog, request) => {
5197
6698
  };
5198
6699
  var createReleaseCatalogRouteHandlers = () => {
5199
6700
  const cache = /* @__PURE__ */ new Map();
6701
+ const evict = (insertedHit) => {
6702
+ const now = Date.now();
6703
+ let oldestMiss;
6704
+ let oldest;
6705
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
6706
+ else {
6707
+ if (entry.row === null) oldestMiss ??= key;
6708
+ oldest ??= key;
6709
+ }
6710
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
6711
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
6712
+ if (victim !== void 0) cache.delete(victim);
6713
+ };
5200
6714
  const inFlight = /* @__PURE__ */ new Map();
5201
- const loadCatalog = async (key, load) => {
5202
- const cached = cache.get(key);
6715
+ const loadRow = async (scopeKey, load) => {
6716
+ const cached = cache.get(scopeKey);
5203
6717
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
5204
- cache.delete(key);
5205
- cache.set(key, cached);
5206
- return cached.catalog;
6718
+ cache.delete(scopeKey);
6719
+ cache.set(scopeKey, cached);
6720
+ return cached.row;
5207
6721
  }
5208
- if (cached !== void 0) cache.delete(key);
5209
- const pending = inFlight.get(key);
6722
+ if (cached !== void 0) cache.delete(scopeKey);
6723
+ const pending = inFlight.get(scopeKey);
5210
6724
  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;
6725
+ const next = load().then((row) => {
6726
+ cache.set(scopeKey, {
6727
+ row,
6728
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
6729
+ });
6730
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
6731
+ return row;
5224
6732
  });
5225
- inFlight.set(key, next);
6733
+ inFlight.set(scopeKey, next);
5226
6734
  try {
5227
6735
  return await next;
5228
6736
  } finally {
5229
- inFlight.delete(key);
6737
+ inFlight.delete(scopeKey);
5230
6738
  }
5231
6739
  };
6740
+ const loadCatalog = async (core, input) => {
6741
+ const scopeKey = releaseCatalogScopeKeyOf(input);
6742
+ return projectParsedReleaseCatalogRow(await loadRow(scopeKey, async () => {
6743
+ const row = await core.getReleaseCatalogRow(scopeKey);
6744
+ return row === null ? null : parseReleaseCatalogRow(row);
6745
+ }), input, scopeKey);
6746
+ };
5232
6747
  return {
5233
6748
  appVersionReleaseCatalog: async (params, request, { core }) => {
5234
6749
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -5242,7 +6757,7 @@ var createReleaseCatalogRouteHandlers = () => {
5242
6757
  };
5243
6758
  const invalid = invalidScope(input);
5244
6759
  if (invalid) return invalid;
5245
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
6760
+ return catalogResponse(await loadCatalog(core, input), request);
5246
6761
  },
5247
6762
  fingerprintReleaseCatalog: async (params, request, { core }) => {
5248
6763
  const input = {
@@ -5253,7 +6768,7 @@ var createReleaseCatalogRouteHandlers = () => {
5253
6768
  };
5254
6769
  const invalid = invalidScope(input);
5255
6770
  if (invalid) return invalid;
5256
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
6771
+ return catalogResponse(await loadCatalog(core, input), request);
5257
6772
  },
5258
6773
  artifactV2: async (params, _request, { core }) => {
5259
6774
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -5603,8 +7118,11 @@ var resolveConsoleConfig = async (request) => {
5603
7118
  const { default: source } = await import("./config-CjIBFhJX.mjs");
5604
7119
  const config = typeof source === "function" ? await source(request) : source;
5605
7120
  const { database, storage, plugins = [] } = config;
5606
- const { gitUrl } = config.console ?? {};
5607
- const consoleOptions = gitUrl === void 0 ? {} : { gitUrl };
7121
+ const { gitUrl, deviceApprovers = [] } = config.console ?? {};
7122
+ const consoleOptions = {
7123
+ ...gitUrl === void 0 ? {} : { gitUrl },
7124
+ deviceApprovers: deviceApprovers.map((email) => email.trim().toLowerCase()).filter((email) => email.length > 0)
7125
+ };
5608
7126
  if (isRemoteDatabase(database)) {
5609
7127
  const checked = assemble({
5610
7128
  name: "memory",