@hot-updater/console 1.0.0-rc.4 → 1.0.0-rc.41

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 (330) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/assets/ConsoleFeatureUnavailable-DRzeMGRM.js +1 -0
  3. package/.output/public/assets/EventDetails-SB5ygJzS.js +1 -0
  4. package/.output/public/assets/HashValueDisplay-BFX_kY3-.js +1 -0
  5. package/.output/public/assets/InsightsInfo-btYppp0B.js +1 -0
  6. package/.output/public/assets/InsightsPageHeader-Ba8psD8t.js +1 -0
  7. package/.output/public/assets/NotFoundPage-CyRG2eca.js +1 -0
  8. package/.output/public/assets/alert-dialog-Bbk_4-WJ.js +1 -0
  9. package/.output/public/assets/api-DUgI6yOI.js +1 -0
  10. package/.output/public/assets/api-keys-CIO9L_wu.js +1 -0
  11. package/.output/public/assets/api-keys-CmkNKOhS.js +1 -0
  12. package/.output/public/assets/arrow-left-CnMYpqB7.js +1 -0
  13. package/.output/public/assets/arrow-up-right-BtffZA6e.js +1 -0
  14. package/.output/public/assets/chevron-right-BqD5wtFb.js +1 -0
  15. package/.output/public/assets/clipboard-DS9ucUQL.js +1 -0
  16. package/.output/public/assets/console-features-api-BMsI3Bj8.js +1 -0
  17. package/.output/public/assets/dialog-Bqbb7B0N.js +1 -0
  18. package/.output/public/assets/dist-LxKJB-Vu.js +1 -0
  19. package/.output/public/assets/empty-CuT2UhFp.js +1 -0
  20. package/.output/public/assets/field-BBDpjIqu.js +1 -0
  21. package/.output/public/assets/index-BEfQ2_7f.js +11 -0
  22. package/.output/public/assets/input-group-ja_30qaF.js +1 -0
  23. package/.output/public/assets/insights-B0ib9qOE.js +2 -0
  24. package/.output/public/assets/insights-BIMJx-0p.js +1 -0
  25. package/.output/public/assets/insights-CndqcWEj.js +42 -0
  26. package/.output/public/assets/insights-api-B6Ewc-OG.js +1 -0
  27. package/.output/public/assets/insights-usage-rpc-DYEhsCKT.js +1 -0
  28. package/.output/public/assets/insights_.distribution-B26PMy4k.js +2 -0
  29. package/.output/public/assets/insights_.distribution-BBDtqqYS.js +1 -0
  30. package/.output/public/assets/insights_.distribution-DhHmYS8k.js +1 -0
  31. package/.output/public/assets/installations-C3cMuwRx.js +1 -0
  32. package/.output/public/assets/installations-C3yrjwDh.js +2 -0
  33. package/.output/public/assets/installations-D3edlN75.js +1 -0
  34. package/.output/public/assets/key-round-wS_SIZ6b.js +1 -0
  35. package/.output/public/assets/list-CgrYiadM.js +1 -0
  36. package/.output/public/assets/refresh-cw-BYgoNCco.js +1 -0
  37. package/.output/public/assets/remote-config-0i-gDkeU.js +1 -0
  38. package/.output/public/assets/remote-config-An1ROIOQ.js +6 -0
  39. package/.output/public/assets/remote-config-CoeWgA9i.js +1 -0
  40. package/.output/public/assets/routes-DNoaJIQV.js +2 -0
  41. package/.output/public/assets/routes-cWBDtghZ.js +1 -0
  42. package/.output/public/assets/search-DaTDPW25.js +1 -0
  43. package/.output/public/assets/select-CZMQKT7F.js +1 -0
  44. package/.output/public/assets/sidebar-DNVyJPfX.js +3 -0
  45. package/.output/public/assets/smartphone-DpTFgtKf.js +1 -0
  46. package/.output/public/assets/styles-D8mxMvCB.css +2 -0
  47. package/.output/public/assets/switch-CU4-fupc.js +1 -0
  48. package/.output/public/assets/table-Gm4qRWwE.js +1 -0
  49. package/.output/public/assets/tabs-R1I8CRjR.js +1 -0
  50. package/.output/public/assets/undo-2-CmrHjwFc.js +1 -0
  51. package/.output/public/assets/useCompositeListItem-BaPeC9ZO.js +1 -0
  52. package/.output/public/assets/valueToPercent-CH8GCHaL.js +1 -0
  53. package/.output/server/__23tanstack-start-server-fn-resolver-DTAqlLRd.mjs +178 -0
  54. package/.output/server/_libs/@base-ui/react+[...].mjs +6450 -2741
  55. package/.output/server/_libs/@tanstack/react-router+[...].mjs +3802 -4022
  56. package/.output/server/_libs/@tanstack/react-router-ssr-query+[...].mjs +140 -97
  57. package/.output/server/_libs/lucide-react.mjs +235 -31
  58. package/.output/server/_libs/next-themes.mjs +1 -1
  59. package/.output/server/_libs/react-redux+[...].mjs +1 -1
  60. package/.output/server/_libs/recharts+[...].mjs +483 -901
  61. package/.output/server/_libs/sonner.mjs +1 -1
  62. package/.output/server/_libs/tanstack__history.mjs +68 -41
  63. package/.output/server/_libs/tanstack__query-core.mjs +2010 -309
  64. package/.output/server/_libs/tanstack__react-query.mjs +448 -21
  65. package/.output/server/_libs/verkit.mjs +102 -1
  66. package/.output/server/_ssr/BundleIdDisplay-BNoVW3Dv.mjs +13 -0
  67. package/.output/server/_ssr/ConsoleFeatureUnavailable-BPFa-cmJ.mjs +58 -0
  68. package/.output/server/_ssr/EventDetails-9CeshfdR.mjs +344 -0
  69. package/.output/server/_ssr/HashValueDisplay-DXZlkcps.mjs +55 -0
  70. package/.output/server/_ssr/InsightsInfo-DLNdJQ0m.mjs +75 -0
  71. package/.output/server/_ssr/InsightsPageHeader-DZGVDgvv.mjs +145 -0
  72. package/.output/server/_ssr/NotFoundPage-mYHHg-2s.mjs +37 -0
  73. package/.output/server/_ssr/{dialog-DUaIgpgd.mjs → alert-dialog-Chkim7vZ.mjs} +6 -83
  74. package/.output/server/_ssr/api-C-Il5-sa.mjs +203 -0
  75. package/.output/server/_ssr/api-keys-01FGqj4d.mjs +5 -0
  76. package/.output/server/_ssr/{api-keys-DJml_XoK.mjs → api-keys-B_f9h7ln.mjs} +48 -10
  77. package/.output/server/_ssr/api-keys-rpc-Cf4YCyFc.mjs +52 -0
  78. package/.output/server/_ssr/api-rpc-DRqwxxT_.mjs +296 -0
  79. package/.output/server/_ssr/{auth-BF8mbAgF.mjs → auth-UP0wXs4i.mjs} +1 -1
  80. package/.output/server/_ssr/{auth-rpc-D_hv52-J.mjs → auth-rpc-D8nFpU9C.mjs} +6 -6
  81. package/.output/server/_ssr/auth.server-COZoXu4i.mjs +5425 -0
  82. package/.output/server/_ssr/bundleActivity-M5gzBFNg.mjs +18 -0
  83. package/.output/server/_ssr/config-WVX4IxSR.mjs +15 -0
  84. package/.output/server/_ssr/config.server-Dm2l7w0O.mjs +36 -0
  85. package/.output/server/_ssr/console-access--o9FXikU.mjs +17 -0
  86. package/.output/server/_ssr/console-features-BftSkf3f.mjs +60 -0
  87. package/.output/server/_ssr/console-features-api-CYclUQ4h.mjs +43 -0
  88. package/.output/server/_ssr/console-features-rpc-1WaAkPM_.mjs +19 -0
  89. package/.output/server/_ssr/{createServerFn-B2hcXoPM.mjs → createMiddleware-Cm6Tn0_Y.mjs} +67 -56
  90. package/.output/server/_ssr/{createServerRpc-DB29C_5p.mjs → createServerRpc-RLR4H-Fn.mjs} +2 -2
  91. package/.output/server/_ssr/databaseConfig-C5SkAyUy.mjs +5 -0
  92. package/.output/server/_ssr/{databaseJsonValue-d6I3nAS4.mjs → databaseJsonValue-Csbuzc9Q.mjs} +28 -5
  93. package/.output/server/_ssr/databaseRows-BUuNU-qt.mjs +74 -0
  94. package/.output/server/_ssr/dialog-mfSANqjC.mjs +84 -0
  95. package/.output/server/_ssr/{dist-CyzPaI5v.mjs → dist-wmnTk7w6.mjs} +140 -6
  96. package/.output/server/_ssr/{downloadBundle-B3ert-pY.mjs → downloadBundle-DViuIa9U.mjs} +10 -10
  97. package/.output/server/_ssr/empty-BPayFad3.mjs +60 -0
  98. package/.output/server/_ssr/{empty-plugin-adapters-B5QvGpEl.mjs → empty-plugin-adapters-CPtwX8a7.mjs} +1 -1
  99. package/.output/server/_ssr/failureReports-DKDhVsXA.mjs +33 -0
  100. package/.output/server/_ssr/field-DjZ5t7rH.mjs +189 -0
  101. package/.output/server/_ssr/getBundleChildren-CmjDg6Re.mjs +22 -0
  102. package/.output/server/_ssr/{input-group-Bb8ueylQ.mjs → input-group-Dx-MEkNM.mjs} +3 -52
  103. package/.output/server/_ssr/insights-BopxyJjk.mjs +14 -0
  104. package/.output/server/_ssr/insights-Bvm03d61.mjs +5 -0
  105. package/.output/server/_ssr/insights-CrLAHSDy.mjs +2315 -0
  106. package/.output/server/_ssr/insights-api-Bg8ZV_h_.mjs +122 -0
  107. package/.output/server/_ssr/insights-errors-BjnFUyZj.mjs +34 -0
  108. package/.output/server/_ssr/insights-failures-rpc-tyy5m9Cc.mjs +36 -0
  109. package/.output/server/_ssr/insights-failures-xaa41Buf.mjs +46 -0
  110. package/.output/server/_ssr/{insights-recovery-DSFM-YTL.mjs → insights-recovery-BWQhiZaF.mjs} +9 -2
  111. package/.output/server/_ssr/insights-recovery-rpc-CPJOiJAV.mjs +32 -0
  112. package/.output/server/_ssr/{insights-rpc-DrIQCjpD.mjs → insights-rpc-DoC3hla9.mjs} +22 -14
  113. package/.output/server/_ssr/insights-usage-BpBM0U0c.mjs +29 -0
  114. package/.output/server/_ssr/insights-usage-rpc-CFuTYp3T.mjs +29 -0
  115. package/.output/server/_ssr/insights-usage-rpc-O2ruP4iE.mjs +41 -0
  116. package/.output/server/_ssr/insightsUsage-CzhVjsc8.mjs +56 -0
  117. package/.output/server/_ssr/insights_.distribution-B3BVPD00.mjs +16 -0
  118. package/.output/server/_ssr/insights_.distribution-BMoisxRG.mjs +347 -0
  119. package/.output/server/_ssr/insights_.distribution-BiCcFyrG.mjs +7 -0
  120. package/.output/server/_ssr/{installations-YumqpNpa.mjs → installations-Cx3jIrwl.mjs} +280 -364
  121. package/.output/server/_ssr/installations-DTGPaKXx.mjs +69 -0
  122. package/.output/server/_ssr/installations-osiAuNKr.mjs +5 -0
  123. package/.output/server/_ssr/listReleases-BfUBlCHo.mjs +79 -0
  124. package/.output/server/_ssr/release-adoption-005tQRpo.mjs +55 -0
  125. package/.output/server/_ssr/release-adoption-rpc-BVySDR0L.mjs +41 -0
  126. package/.output/server/_ssr/releaseAdoption-2PJPA09N.mjs +114 -0
  127. package/.output/server/_ssr/releaseManagement-BTCWEY8-.mjs +11 -0
  128. package/.output/server/_ssr/remote-config-CUoAxUMy.mjs +430 -0
  129. package/.output/server/_ssr/remote-config-Cc5P4J-r.mjs +17 -0
  130. package/.output/server/_ssr/remote-config-CjdxcZ9B.mjs +5 -0
  131. package/.output/server/_ssr/remote-config-D2GmbGwI.mjs +2594 -0
  132. package/.output/server/_ssr/remote-config-rpc-kjoZ9PRS.mjs +115 -0
  133. package/.output/server/_ssr/rolldown-runtime-rSIU-vHC.mjs +13 -0
  134. package/.output/server/_ssr/{router-iP95Vqi2.mjs → router-DwGVewL-.mjs} +141 -139
  135. package/.output/server/_ssr/{routes-ivsV2TDu.mjs → routes-C4yxv3JU.mjs} +192 -685
  136. package/.output/server/_ssr/routes-D3_aegLY.mjs +409 -0
  137. package/.output/server/_ssr/runtime.server-BoWf4QhU.mjs +1716 -0
  138. package/.output/server/_ssr/schema-DrOtkRVD.mjs +361 -0
  139. package/.output/server/_ssr/select-DkzM2miy.mjs +107 -0
  140. package/.output/server/_ssr/server-BW0gzB0p.mjs +8325 -0
  141. package/.output/server/_ssr/{createSsrRpc-NHF2PxuK.mjs → sidebar-DPcOijvL.mjs} +107 -47
  142. package/.output/server/_ssr/ssr.mjs +1 -1
  143. package/.output/server/_ssr/start-BfFbHKMK.mjs +4 -0
  144. package/.output/server/_ssr/switch-BqJ2mAwC.mjs +17 -0
  145. package/.output/server/_ssr/{table-D1mL8fJu.mjs → table-R7RY92q9.mjs} +2 -2
  146. package/.output/server/_ssr/tabs-trDcbRkT.mjs +45 -0
  147. package/.output/server/_ssr/updateFailures-H6pnnYK4.mjs +40 -0
  148. package/.output/server/_ssr/{uuidv7-D0QFkPL_.mjs → uuidv7-ctA_XVZA.mjs} +2 -2
  149. package/.output/server/_tanstack-start-manifest_v-BwInaUTw.mjs +139 -0
  150. package/.output/server/index.mjs +315 -154
  151. package/LICENSE +13 -14
  152. package/README.md +82 -72
  153. package/lib/index.d.mts +23 -11
  154. package/lib/vite-internal.mjs +13 -3
  155. package/lib/vite.d.mts +2 -0
  156. package/package.json +14 -14
  157. package/src/components/AppSidebar.tsx +100 -71
  158. package/src/components/ConsoleAccessPage.tsx +5 -1
  159. package/src/components/ConsoleFeatureUnavailable.tsx +80 -0
  160. package/src/components/NotFoundPage.tsx +7 -7
  161. package/src/components/features/FeatureSlots.tsx +103 -0
  162. package/src/components/features/api-keys/apiKeysFeatureUi.tsx +15 -0
  163. package/src/components/features/bundles/BundleMetadata.tsx +8 -5
  164. package/src/components/features/bundles/RolloutCohortsDialog.tsx +1 -1
  165. package/src/components/features/channels/ChannelManagementDialog.tsx +2 -5
  166. package/src/components/features/insights/AppUsage.tsx +366 -0
  167. package/src/components/features/insights/BuiltinBundle.tsx +36 -0
  168. package/src/components/features/insights/ComparedBundlesChart.tsx +310 -0
  169. package/src/components/features/insights/EstimatedCount.tsx +18 -0
  170. package/src/components/features/insights/EventDetails.tsx +400 -39
  171. package/src/components/features/insights/EventHistoryCard.tsx +112 -26
  172. package/src/components/features/insights/EventHistoryList.tsx +2 -2
  173. package/src/components/features/insights/FailureReports.tsx +407 -0
  174. package/src/components/features/insights/InsightsControls.tsx +265 -88
  175. package/src/components/features/insights/InsightsErrorAlert.tsx +14 -1
  176. package/src/components/features/insights/InsightsInfo.tsx +48 -0
  177. package/src/components/features/insights/InsightsOverview.tsx +604 -355
  178. package/src/components/features/insights/InsightsPageHeader.tsx +35 -20
  179. package/src/components/features/insights/InsightsPeriodSelector.tsx +89 -0
  180. package/src/components/features/insights/InstallationHistoryCard.tsx +66 -11
  181. package/src/components/features/insights/InstallationMatchesCard.tsx +1 -1
  182. package/src/components/features/insights/ReleaseActivity.tsx +308 -0
  183. package/src/components/features/insights/ReportingDevicesSummary.tsx +48 -0
  184. package/src/components/features/insights/RollbackButton.tsx +118 -0
  185. package/src/components/features/insights/UpdateFailures.tsx +382 -0
  186. package/src/components/features/insights/insightsFeatureUi.tsx +35 -0
  187. package/src/components/features/releases/ReleaseEditorSheet.tsx +26 -12
  188. package/src/components/features/remote-config/ConditionDialog.tsx +581 -0
  189. package/src/components/features/remote-config/ConditionsCard.tsx +244 -0
  190. package/src/components/features/remote-config/ParameterDialog.tsx +407 -0
  191. package/src/components/features/remote-config/ParametersCard.tsx +244 -0
  192. package/src/components/features/remote-config/PreviewCard.tsx +284 -0
  193. package/src/components/features/remote-config/PublishDialog.tsx +319 -0
  194. package/src/components/features/remote-config/RemoteConfigPage.tsx +353 -0
  195. package/src/components/features/remote-config/RuleSummary.tsx +21 -0
  196. package/src/components/features/remote-config/ValueInput.tsx +148 -0
  197. package/src/components/features/remote-config/VersionsCard.tsx +361 -0
  198. package/src/components/features/remote-config/remoteConfigFeatureUi.tsx +15 -0
  199. package/src/components/features/remote-config/useDateTimeText.ts +16 -0
  200. package/src/components/ui/card.tsx +1 -1
  201. package/src/components/ui/scroll-area.tsx +52 -0
  202. package/src/components/ui/sidebar.tsx +22 -29
  203. package/src/components/ui/tabs.tsx +81 -0
  204. package/src/index.ts +26 -19
  205. package/src/lib/api-keys-api.ts +0 -28
  206. package/src/lib/api-keys-rpc.ts +27 -38
  207. package/src/lib/api-rpc.ts +189 -266
  208. package/src/lib/api.ts +19 -102
  209. package/src/lib/bundle-activity.ts +24 -4
  210. package/src/lib/console-access.ts +20 -0
  211. package/src/lib/console-features-api.ts +68 -0
  212. package/src/lib/console-features-rpc.ts +13 -0
  213. package/src/lib/console-features.ts +97 -0
  214. package/src/lib/insights-api.ts +56 -2
  215. package/src/lib/insights-errors.ts +64 -0
  216. package/src/lib/insights-failures-rpc.ts +36 -0
  217. package/src/lib/insights-failures.ts +130 -0
  218. package/src/lib/insights-recovery-rpc.ts +13 -17
  219. package/src/lib/insights-recovery.ts +10 -27
  220. package/src/lib/insights-retention.ts +21 -0
  221. package/src/lib/insights-rpc.ts +30 -12
  222. package/src/lib/insights-search.ts +93 -0
  223. package/src/lib/insights-usage-rpc.ts +29 -0
  224. package/src/lib/insights-usage.ts +76 -0
  225. package/src/lib/insights-view.ts +34 -5
  226. package/src/lib/release-adoption-api.ts +214 -0
  227. package/src/lib/release-adoption-rpc.ts +49 -0
  228. package/src/lib/release-adoption.ts +164 -0
  229. package/src/lib/remote-config-api.ts +119 -0
  230. package/src/lib/remote-config-draft.ts +652 -0
  231. package/src/lib/remote-config-rpc.ts +196 -0
  232. package/src/lib/scroll-restoration.ts +21 -0
  233. package/src/lib/server/adminInsights.ts +124 -0
  234. package/src/lib/server/auth.server.ts +13 -5
  235. package/src/lib/server/bundleActivity.ts +27 -28
  236. package/src/lib/server/config.server.ts +21 -74
  237. package/src/lib/server/console-feature-apis.ts +70 -0
  238. package/src/lib/server/console-runtime.server.ts +82 -38
  239. package/src/lib/server/downloadBundle.ts +16 -15
  240. package/src/lib/server/failureReports.ts +49 -0
  241. package/src/lib/server/getBundleChildren.ts +31 -122
  242. package/src/lib/server/insightsUsage.ts +63 -0
  243. package/src/lib/server/listReleases.ts +109 -44
  244. package/src/lib/server/releaseAdoption.ts +154 -0
  245. package/src/lib/server/releaseReachability.ts +8 -7
  246. package/src/lib/server/remoteConfig.ts +191 -0
  247. package/src/lib/server/runtime.server.ts +120 -31
  248. package/src/lib/server/updateFailures.ts +65 -0
  249. package/src/routeTree.gen.ts +65 -44
  250. package/src/router.tsx +3 -2
  251. package/src/routes/-installations-search.ts +32 -8
  252. package/src/routes/-releases-search.ts +76 -29
  253. package/src/routes/__root.tsx +10 -4
  254. package/src/routes/api/bundles/$bundleId/download.ts +2 -5
  255. package/src/routes/api-keys.tsx +5 -2
  256. package/src/routes/index.tsx +210 -152
  257. package/src/routes/insights.tsx +133 -18
  258. package/src/routes/insights_.distribution.tsx +422 -0
  259. package/src/routes/installations.tsx +98 -41
  260. package/src/routes/remote-config.tsx +42 -0
  261. package/src/styles.css +9 -0
  262. package/src/vite-internal.ts +15 -3
  263. package/src/vite.ts +2 -0
  264. package/.output/public/assets/InsightsPageHeader-C-Xc2MB9.js +0 -1
  265. package/.output/public/assets/api-keys-C1sgC6ko.js +0 -1
  266. package/.output/public/assets/api-keys-api-LchP65vQ.js +0 -1
  267. package/.output/public/assets/badge-BuMDU0Rf.js +0 -1
  268. package/.output/public/assets/card-BEvx_QKh.js +0 -1
  269. package/.output/public/assets/chart-no-axes-combined-C0G0fQ3J.js +0 -1
  270. package/.output/public/assets/composite-CHTH1Xhh.js +0 -1
  271. package/.output/public/assets/createServerFn-DHc2erub.js +0 -3
  272. package/.output/public/assets/dialog-dyZ1SphZ.js +0 -1
  273. package/.output/public/assets/dist-Bh1gaDfB.js +0 -1
  274. package/.output/public/assets/field-79SVH26s.js +0 -1
  275. package/.output/public/assets/index-BNkxg4jz.js +0 -10
  276. package/.output/public/assets/input-group-BbHfaBzQ.js +0 -1
  277. package/.output/public/assets/insights-D_7uSKfc.js +0 -1
  278. package/.output/public/assets/installations-BzoHWuXw.js +0 -1
  279. package/.output/public/assets/installations-DvjbUqd1.js +0 -2
  280. package/.output/public/assets/lazyRouteComponent-BN0MS05o.js +0 -1
  281. package/.output/public/assets/link-BG06whwB.js +0 -1
  282. package/.output/public/assets/loader-circle-Bbp8LGVC.js +0 -1
  283. package/.output/public/assets/preload-helper-uTix4PVD.js +0 -1
  284. package/.output/public/assets/refresh-cw-DZgiAOMk.js +0 -1
  285. package/.output/public/assets/routes-BFE-oRIT.js +0 -1
  286. package/.output/public/assets/routes-DaPMY31P.js +0 -2
  287. package/.output/public/assets/shield-check-DoIiaaXU.js +0 -1
  288. package/.output/public/assets/signing-BTRhaF5D.js +0 -1
  289. package/.output/public/assets/styles-C7U0oVke.css +0 -2
  290. package/.output/public/assets/table-BBEzJ7Xl.js +0 -1
  291. package/.output/public/assets/useCompositeListItem-BkPDaqyj.js +0 -42
  292. package/.output/server/__23tanstack-start-server-fn-resolver-Dr2ixDgQ.mjs +0 -146
  293. package/.output/server/_ssr/InsightsPageHeader-C5Has8Ry.mjs +0 -60
  294. package/.output/server/_ssr/api-keys-api-CrCZyvnl.mjs +0 -60
  295. package/.output/server/_ssr/api-keys-rpc-CFaNf-q0.mjs +0 -136
  296. package/.output/server/_ssr/api-rpc-B61KL3Eo.mjs +0 -1399
  297. package/.output/server/_ssr/auth.server-DF_shCeq.mjs +0 -47
  298. package/.output/server/_ssr/badge-BgsCP9Dp.mjs +0 -28
  299. package/.output/server/_ssr/bundle-signing-rpc-BBipZnFs.mjs +0 -16
  300. package/.output/server/_ssr/bundle-signing.server-Co_zHdJx.mjs +0 -12
  301. package/.output/server/_ssr/bundleActivity-D3_fIda2.mjs +0 -27
  302. package/.output/server/_ssr/card-DrbxCPtG.mjs +0 -86
  303. package/.output/server/_ssr/chart-qxa-_30a.mjs +0 -162
  304. package/.output/server/_ssr/config-Dv8qLDZ0.mjs +0 -13
  305. package/.output/server/_ssr/config.server-CBr6PDj5.mjs +0 -368
  306. package/.output/server/_ssr/databaseRows-5bCRTxm-.mjs +0 -126
  307. package/.output/server/_ssr/deleteBundle-BAq3JuGr.mjs +0 -66
  308. package/.output/server/_ssr/field-CqNUlqUq.mjs +0 -74
  309. package/.output/server/_ssr/getBundleChildren-COMt16m_.mjs +0 -50
  310. package/.output/server/_ssr/insights-B-DUbksX.mjs +0 -502
  311. package/.output/server/_ssr/insights-recovery-rpc-P71FH66n.mjs +0 -37
  312. package/.output/server/_ssr/insightsContract-fjJDBeEE.mjs +0 -303
  313. package/.output/server/_ssr/insightsRecovery-CqcosG7B.mjs +0 -149
  314. package/.output/server/_ssr/installations-BQrppti7.mjs +0 -29
  315. package/.output/server/_ssr/routes-BDabsmc7.mjs +0 -37
  316. package/.output/server/_ssr/runtime.server-jmZOKIQM.mjs +0 -438
  317. package/.output/server/_ssr/server-p7yrVBfD.mjs +0 -7468
  318. package/.output/server/_ssr/signing-CxCbnFCt.mjs +0 -134
  319. package/.output/server/_ssr/start-DpViQGnt.mjs +0 -4
  320. package/.output/server/_tanstack-start-manifest_v-Cwpu0C9Q.mjs +0 -100
  321. package/src/components/features/bundles/BundleActivityChart.tsx +0 -95
  322. package/src/components/features/bundles/BundleInsightsSummary.tsx +0 -121
  323. package/src/components/features/signing/BundleSigningPage.tsx +0 -139
  324. package/src/lib/bundle-signing-api.ts +0 -14
  325. package/src/lib/bundle-signing-rpc.ts +0 -16
  326. package/src/lib/server/bundle-signing.server.ts +0 -23
  327. package/src/lib/server/deleteBundle.ts +0 -145
  328. package/src/lib/server/insightsHistory.ts +0 -52
  329. package/src/lib/server/insightsRecovery.ts +0 -186
  330. package/src/routes/signing.tsx +0 -37
@@ -0,0 +1,1716 @@
1
+ import { i as resolveConsoleFeatures, n as consoleFeatures, t as ConsoleFeatureUnavailableError } from "./console-features-BftSkf3f.mjs";
2
+ import { C as isUUIDv7 } from "./dist-wmnTk7w6.mjs";
3
+ import { i as isDatabaseJsonObject, t as DatabaseAdapterInputError } from "./databaseJsonValue-Csbuzc9Q.mjs";
4
+ import { i as defineTable, r as defineAggregate } from "./schema-DrOtkRVD.mjs";
5
+ import { t as createUUIDv7 } from "./uuidv7-ctA_XVZA.mjs";
6
+ import { t as isRemoteDatabase } from "./databaseConfig-C5SkAyUy.mjs";
7
+ import { n as RemoteConfigValidationError } from "./remote-config-CUoAxUMy.mjs";
8
+ //#region node_modules/.nitro/vite/services/ssr/assets/runtime.server-BoWf4QhU.js
9
+ var DAY_MS$1 = 864e5;
10
+ var DEFAULT_INSIGHTS_RETENTION = {
11
+ rawDays: 90,
12
+ dailyDays: 400
13
+ };
14
+ var bucketRetention = (days) => ({
15
+ field: "bucket_start_ms",
16
+ days
17
+ });
18
+ /** Every kind of row the table keeps belongs in installation history. */
19
+ var MOVEMENTS = /* @__PURE__ */ new Set([
20
+ "UPDATE_DOWNLOADED",
21
+ "UPDATE_APPLIED",
22
+ "RECOVERED",
23
+ "UPDATE_FAILED",
24
+ "UNCHANGED"
25
+ ]);
26
+ /** A failed update check: it names no target bundle, so no bundle list shows it. */
27
+ var isFailedCheck = (row) => row.type === "UPDATE_FAILED" && row.metadata?.failure?.stage === "check";
28
+ var metadataOf = (row) => row.metadata ?? {};
29
+ /** A download or apply that arrived after its target ran: it counts nothing. */
30
+ var isLateEvent = (row) => metadataOf(row).late === true;
31
+ /**
32
+ * Whether a stored row launched its installation into a bundle release: an
33
+ * apply, or a kept UNCHANGED row that moved the installation to another
34
+ * bundle of a release, as when the apply report never arrived or a rollback
35
+ * to the built-in bundle took it there. A first report, a release change of
36
+ * the bundle already running, and a late row launch nothing.
37
+ */
38
+ var isLaunch = (row) => {
39
+ if (isLateEvent(row)) return false;
40
+ if (row.type === "UPDATE_APPLIED") return true;
41
+ if (row.type !== "UNCHANGED") return false;
42
+ const kinds = metadataOf(row).change?.kinds ?? [];
43
+ return kinds.includes("bundle") && !kinds.includes("first_seen") && row.to_release_id !== null;
44
+ };
45
+ /**
46
+ * The bundle a stored row's bundle filter matches: `from:<bundle>` for a
47
+ * recovery; `to:<bundle>` for a download, an apply, and an update failure;
48
+ * `on:<bundle>` for an UNCHANGED row that launched a bundle (`isLaunch`), a
49
+ * key no other row uses. None for a failed check, which targets no bundle, a
50
+ * late row, or any other UNCHANGED row.
51
+ */
52
+ var bundleRefsOf = (row) => {
53
+ if (isFailedCheck(row) || isLateEvent(row)) return [];
54
+ if (row.type === "RECOVERED") return [`from:${row.from_bundle_id}`];
55
+ if (row.type === "UNCHANGED") return isLaunch(row) ? [`on:${row.to_bundle_id}`] : [];
56
+ return [`to:${row.to_bundle_id}`];
57
+ };
58
+ /** The key a bundle filter reads, as `bundleRefsOf` writes it. */
59
+ var bundleRefOfFilter = (filter) => filter.type === "RECOVERED" ? `from:${filter.fromBundleId}` : filter.type === "UNCHANGED" ? `on:${filter.toBundleId}` : `to:${filter.toBundleId}`;
60
+ /**
61
+ * Downloads, applies, recoveries, update failures, and the UNCHANGED
62
+ * reports that changed what their installation runs, whole. An UNCHANGED
63
+ * report that changes nothing counts as a launch and moves its
64
+ * installation's head, but no row keeps it.
65
+ */
66
+ var bundleEvents = (days) => defineTable({
67
+ id: {
68
+ type: "string",
69
+ maxLength: 36
70
+ },
71
+ type: {
72
+ type: "string",
73
+ maxLength: 32
74
+ },
75
+ install_id: {
76
+ type: "string",
77
+ maxLength: 255
78
+ },
79
+ user_id: {
80
+ type: "string",
81
+ maxLength: 255,
82
+ required: false
83
+ },
84
+ from_release_id: {
85
+ type: "string",
86
+ maxLength: 36,
87
+ required: false
88
+ },
89
+ from_bundle_id: {
90
+ type: "string",
91
+ maxLength: 36,
92
+ required: false
93
+ },
94
+ to_release_id: {
95
+ type: "string",
96
+ maxLength: 36,
97
+ required: false
98
+ },
99
+ to_bundle_id: {
100
+ type: "string",
101
+ maxLength: 36
102
+ },
103
+ platform: {
104
+ type: "string",
105
+ maxLength: 16
106
+ },
107
+ app_version: { type: "string" },
108
+ channel: { type: "string" },
109
+ metadata: { type: "json" },
110
+ received_at_ms: { type: "integer" }
111
+ }, {
112
+ key: ["id"],
113
+ derived: {
114
+ day: {
115
+ type: "integer",
116
+ compute: (row) => row.received_at_ms - row.received_at_ms % DAY_MS$1
117
+ },
118
+ movement_install_id: {
119
+ type: "string",
120
+ compute: (row) => MOVEMENTS.has(row.type) ? row.install_id : null
121
+ },
122
+ bundle_ref: {
123
+ type: "string",
124
+ multi: true,
125
+ compute: (row) => bundleRefsOf(row)
126
+ }
127
+ },
128
+ indexes: {
129
+ movementsByInstall: {
130
+ eq: ["movement_install_id"],
131
+ sort: ["received_at_ms"]
132
+ },
133
+ byBundle: {
134
+ eq: [
135
+ "platform",
136
+ "channel",
137
+ "type",
138
+ "bundle_ref",
139
+ "day"
140
+ ],
141
+ sort: ["received_at_ms"]
142
+ },
143
+ byDay: {
144
+ eq: ["day"],
145
+ sort: ["received_at_ms"]
146
+ }
147
+ },
148
+ retention: {
149
+ field: "day",
150
+ days
151
+ }
152
+ });
153
+ /**
154
+ * Each installation's latest event, whole, so reading it is one point read.
155
+ * Its gauges count it in the UTC day of that event. An update failure moves
156
+ * nothing, so no head holds one.
157
+ */
158
+ var bundleEventHeads = (days) => defineTable({
159
+ install_id: {
160
+ type: "string",
161
+ maxLength: 255
162
+ },
163
+ id: {
164
+ type: "string",
165
+ maxLength: 36
166
+ },
167
+ type: {
168
+ type: "string",
169
+ maxLength: 32
170
+ },
171
+ user_id: {
172
+ type: "string",
173
+ maxLength: 255,
174
+ required: false
175
+ },
176
+ from_release_id: {
177
+ type: "string",
178
+ maxLength: 36,
179
+ required: false
180
+ },
181
+ from_bundle_id: {
182
+ type: "string",
183
+ maxLength: 36,
184
+ required: false
185
+ },
186
+ to_release_id: {
187
+ type: "string",
188
+ maxLength: 36,
189
+ required: false
190
+ },
191
+ to_bundle_id: {
192
+ type: "string",
193
+ maxLength: 36
194
+ },
195
+ platform: {
196
+ type: "string",
197
+ maxLength: 16
198
+ },
199
+ app_version: { type: "string" },
200
+ channel: { type: "string" },
201
+ metadata: { type: "json" },
202
+ received_at_ms: { type: "integer" }
203
+ }, {
204
+ key: ["install_id"],
205
+ indexes: { byUser: {
206
+ eq: ["user_id"],
207
+ sort: ["install_id"]
208
+ } },
209
+ retention: {
210
+ field: "received_at_ms",
211
+ days
212
+ }
213
+ });
214
+ /**
215
+ * Shards are keyed by install id. Counters are blind increments and never
216
+ * conflict, so they keep 8. Gauges and sketches are read, merged, and written
217
+ * back. B3's rollout gate on PostgreSQL retried 2.4% of transactions at 8
218
+ * shards and 1.3% at 16. DynamoDB's transactions take longer, so D8's gate
219
+ * on DynamoDB Local retried 2–24% at 16, almost all on gauge rows, and 1–5%
220
+ * with gauges at 32. Sketches stay at 16: each shard row carries 2 KB of
221
+ * registers that every read merges.
222
+ *
223
+ * Every Insights aggregate is `batched`: on DynamoDB and Firestore, which
224
+ * bill each write, an event's changes apply after it commits, merged with
225
+ * other events' into one write per row, on one shard per writer.
226
+ */
227
+ var COUNTER_SHARDS = 8;
228
+ var GAUGE_SHARDS = 32;
229
+ var SKETCH_SHARDS = 16;
230
+ /** Rows keyed by a hashed identity (scope and period) and a bucket. */
231
+ var identityFields = {
232
+ identity: {
233
+ type: "string",
234
+ maxLength: 32
235
+ },
236
+ bucket_start_ms: { type: "integer" }
237
+ };
238
+ var window = {
239
+ eq: ["identity"],
240
+ sort: ["bucket_start_ms"]
241
+ };
242
+ /** What a release or channel row counts in every period kind. */
243
+ var WINDOW_COUNTERS = [
244
+ "downloads",
245
+ "failed_launches",
246
+ "patch_downloads",
247
+ "patch_fallbacks"
248
+ ];
249
+ /**
250
+ * Hourly or daily counters: a release or channel row counts downloads,
251
+ * launches that crashed and recovered (`failed_launches`), and downloads a
252
+ * patch delivered and those that fell back from one.
253
+ */
254
+ var counters = (retention) => defineAggregate(identityFields, {
255
+ key: ["identity", "bucket_start_ms"],
256
+ counters: WINDOW_COUNTERS,
257
+ shards: COUNTER_SHARDS,
258
+ batched: true,
259
+ indexes: { window },
260
+ retention
261
+ });
262
+ /**
263
+ * A release's counters since its first report, at bucket 0: the windowed
264
+ * counters, its applies, which the bundle list reads, and its failed updates
265
+ * (`failed_updates`), since no breakdown row outlives the raw period; windowed
266
+ * reads sum `insights_failures` instead.
267
+ */
268
+ var lifetimeCounters = () => defineAggregate(identityFields, {
269
+ key: ["identity", "bucket_start_ms"],
270
+ counters: [
271
+ ...WINDOW_COUNTERS,
272
+ "applies",
273
+ "failed_updates"
274
+ ],
275
+ shards: COUNTER_SHARDS,
276
+ batched: true,
277
+ indexes: { window }
278
+ });
279
+ /**
280
+ * Unique-installation sketches of one period kind: a usage row's active
281
+ * installations (`activity_users`), and a `failure` or `check` row's
282
+ * installations whose update or update check failed (`failed_users`).
283
+ */
284
+ var sketches = (retention) => defineAggregate(identityFields, {
285
+ key: ["identity", "bucket_start_ms"],
286
+ distinct: ["activity_users", "failed_users"],
287
+ shards: SKETCH_SHARDS,
288
+ batched: true,
289
+ indexes: { window },
290
+ retention
291
+ });
292
+ /** Installations whose update to a release failed, since its first failure: kept, at bucket 0. */
293
+ var lifetimeSketches = () => defineAggregate(identityFields, {
294
+ key: ["identity", "bucket_start_ms"],
295
+ distinct: ["failed_users"],
296
+ shards: SKETCH_SHARDS,
297
+ batched: true,
298
+ indexes: { window }
299
+ });
300
+ /**
301
+ * Update failures by what failed, a row an hour. `release_id` is the failed
302
+ * update's target release, or empty for a failed check or an unknown target.
303
+ * `stage` and `reason` say where and why it failed, and `detail` what else
304
+ * the client knew, as the JSON array `[resource, httpStatus, originCode,
305
+ * transport]`. Every index is in key order, so its counters stay blind
306
+ * increments.
307
+ */
308
+ var insightsFailures = (retention) => defineAggregate({
309
+ platform: {
310
+ type: "string",
311
+ maxLength: 16
312
+ },
313
+ channel: { type: "string" },
314
+ bucket_start_ms: { type: "integer" },
315
+ release_id: {
316
+ type: "string",
317
+ maxLength: 36
318
+ },
319
+ stage: {
320
+ type: "string",
321
+ maxLength: 16
322
+ },
323
+ reason: {
324
+ type: "string",
325
+ maxLength: 64
326
+ },
327
+ detail: {
328
+ type: "string",
329
+ maxLength: 160
330
+ }
331
+ }, {
332
+ key: [
333
+ "platform",
334
+ "channel",
335
+ "bucket_start_ms",
336
+ "release_id",
337
+ "stage",
338
+ "reason",
339
+ "detail"
340
+ ],
341
+ counters: ["events"],
342
+ shards: COUNTER_SHARDS,
343
+ batched: true,
344
+ indexes: { byScope: {
345
+ eq: ["platform", "channel"],
346
+ sort: ["bucket_start_ms"]
347
+ } },
348
+ retention
349
+ });
350
+ /** Installations counted in the UTC day of their latest event, so reads sum whole UTC days. */
351
+ var insightsDistribution = (retention) => defineAggregate({
352
+ channel: { type: "string" },
353
+ platform: {
354
+ type: "string",
355
+ maxLength: 16
356
+ },
357
+ app_version: { type: "string" },
358
+ release_id: {
359
+ type: "string",
360
+ maxLength: 36
361
+ },
362
+ bucket_start_ms: { type: "integer" }
363
+ }, {
364
+ key: [
365
+ "channel",
366
+ "platform",
367
+ "app_version",
368
+ "release_id",
369
+ "bucket_start_ms"
370
+ ],
371
+ gauges: ["latest_installations"],
372
+ shards: GAUGE_SHARDS,
373
+ batched: true,
374
+ indexes: {
375
+ byScope: {
376
+ eq: ["channel", "platform"],
377
+ sort: ["bucket_start_ms"]
378
+ },
379
+ byVersion: {
380
+ eq: [
381
+ "channel",
382
+ "platform",
383
+ "app_version"
384
+ ],
385
+ sort: ["bucket_start_ms"]
386
+ }
387
+ },
388
+ retention
389
+ });
390
+ /**
391
+ * The installations of `insights_distribution` that run their native build's
392
+ * built-in bundle, by its ID (`builtin_bundle_id`), within the same rows:
393
+ * reads move them out of the row of their release, or of no release.
394
+ */
395
+ var insightsBuiltinDistribution = (retention) => defineAggregate({
396
+ channel: { type: "string" },
397
+ platform: {
398
+ type: "string",
399
+ maxLength: 16
400
+ },
401
+ app_version: { type: "string" },
402
+ release_id: {
403
+ type: "string",
404
+ maxLength: 36
405
+ },
406
+ builtin_bundle_id: {
407
+ type: "string",
408
+ maxLength: 36
409
+ },
410
+ bucket_start_ms: { type: "integer" }
411
+ }, {
412
+ key: [
413
+ "channel",
414
+ "platform",
415
+ "app_version",
416
+ "release_id",
417
+ "builtin_bundle_id",
418
+ "bucket_start_ms"
419
+ ],
420
+ gauges: ["latest_installations"],
421
+ shards: GAUGE_SHARDS,
422
+ batched: true,
423
+ indexes: {
424
+ byScope: {
425
+ eq: ["channel", "platform"],
426
+ sort: ["bucket_start_ms"]
427
+ },
428
+ byVersion: {
429
+ eq: [
430
+ "channel",
431
+ "platform",
432
+ "app_version"
433
+ ],
434
+ sort: ["bucket_start_ms"]
435
+ }
436
+ },
437
+ retention
438
+ });
439
+ /** Latest events by the bundle they came from or went to, bucketed like the distribution. */
440
+ var insightsLatestByBundle = (retention) => defineAggregate({
441
+ platform: {
442
+ type: "string",
443
+ maxLength: 16
444
+ },
445
+ channel: { type: "string" },
446
+ bundle_field: {
447
+ type: "string",
448
+ maxLength: 16
449
+ },
450
+ bundle_id: {
451
+ type: "string",
452
+ maxLength: 36
453
+ },
454
+ type: {
455
+ type: "string",
456
+ maxLength: 32
457
+ },
458
+ bucket_start_ms: { type: "integer" }
459
+ }, {
460
+ key: [
461
+ "platform",
462
+ "channel",
463
+ "bundle_field",
464
+ "bundle_id",
465
+ "type",
466
+ "bucket_start_ms"
467
+ ],
468
+ gauges: ["installations"],
469
+ shards: GAUGE_SHARDS,
470
+ batched: true,
471
+ indexes: { byBundle: {
472
+ eq: [
473
+ "platform",
474
+ "channel",
475
+ "bundle_field",
476
+ "bundle_id",
477
+ "type"
478
+ ],
479
+ sort: ["bucket_start_ms"]
480
+ } },
481
+ retention
482
+ });
483
+ /**
484
+ * Stored events by outcome and the bundle a bundle filter matches, a row an
485
+ * hour, which a failed check has none of; and every stored event, a row a UTC
486
+ * day (`DAILY_EVENTS`). Bundle counts sum the hourly rows, and event lists
487
+ * read either to skip days without events.
488
+ */
489
+ var insightsOutcomes = (retention) => defineAggregate({
490
+ platform: {
491
+ type: "string",
492
+ maxLength: 16
493
+ },
494
+ channel: { type: "string" },
495
+ type: {
496
+ type: "string",
497
+ maxLength: 32
498
+ },
499
+ bundle_ref: {
500
+ type: "string",
501
+ maxLength: 41
502
+ },
503
+ bucket_start_ms: { type: "integer" }
504
+ }, {
505
+ key: [
506
+ "platform",
507
+ "channel",
508
+ "type",
509
+ "bundle_ref",
510
+ "bucket_start_ms"
511
+ ],
512
+ counters: ["events"],
513
+ shards: COUNTER_SHARDS,
514
+ batched: true,
515
+ indexes: { byRef: {
516
+ eq: [
517
+ "platform",
518
+ "channel",
519
+ "type",
520
+ "bundle_ref"
521
+ ],
522
+ sort: ["bucket_start_ms"]
523
+ } },
524
+ retention
525
+ });
526
+ /**
527
+ * Insights' tables, each expiring after its period. The periods are values
528
+ * the engine applies at runtime; the tables and indexes are the same for
529
+ * any periods.
530
+ */
531
+ var createInsightsSchema = ({ rawDays, dailyDays } = DEFAULT_INSIGHTS_RETENTION) => {
532
+ const hourly = bucketRetention(rawDays);
533
+ const daily = bucketRetention(dailyDays);
534
+ return {
535
+ bundle_events: bundleEvents(rawDays),
536
+ bundle_event_heads: bundleEventHeads(dailyDays),
537
+ insights_overview: counters(hourly),
538
+ insights_sketches: sketches(hourly),
539
+ insights_overview_daily: counters(daily),
540
+ insights_sketches_daily: sketches(daily),
541
+ insights_overview_lifetime: lifetimeCounters(),
542
+ insights_sketches_lifetime: lifetimeSketches(),
543
+ insights_distribution: insightsDistribution(daily),
544
+ insights_builtin_distribution: insightsBuiltinDistribution(daily),
545
+ insights_latest_by_bundle: insightsLatestByBundle(daily),
546
+ insights_outcomes: insightsOutcomes(hourly),
547
+ insights_failures: insightsFailures(hourly)
548
+ };
549
+ };
550
+ createInsightsSchema();
551
+ var CHANGE_KINDS = /* @__PURE__ */ new Set([
552
+ "first_seen",
553
+ "bundle",
554
+ "release",
555
+ "app_version",
556
+ "channel",
557
+ "native_build"
558
+ ]);
559
+ var isBundleEventChange = (value) => isDatabaseJsonObject(value) && Array.isArray(value.kinds) && value.kinds.length > 0 && value.kinds.every((kind) => CHANGE_KINDS.has(kind)) && (value.previous === null || isDatabaseJsonObject(value.previous) && typeof value.previous.bundle_id === "string" && (value.previous.release_id === null || typeof value.previous.release_id === "string") && typeof value.previous.app_version === "string" && typeof value.previous.channel === "string" && isOptional(value.previous, "min_bundle_id", isString));
560
+ var isOptional = (value, key, valid) => !Object.hasOwn(value, key) || valid(value[key]);
561
+ var isString = (value) => typeof value === "string";
562
+ var isDatabaseHttpResponse = (value) => isDatabaseJsonObject(value) && (value.resource === "catalog" || value.resource === "artifact") && isString(value.path) && Number.isSafeInteger(value.status) && (value.body === null || isString(value.body)) && typeof value.body_truncated === "boolean" && Number.isSafeInteger(value.received_at_ms);
563
+ /** An `UPDATE_FAILED` report's stored failure: a stage and a reason, and what else the client knew. */
564
+ var isDatabaseBundleEventFailure = (value) => isDatabaseJsonObject(value) && isString(value.stage) && isString(value.reason) && isOptional(value, "resource", isString) && isOptional(value, "http_status", (status) => Number.isSafeInteger(status)) && isOptional(value, "transport", isString) && isOptional(value, "origin_code", isString) && isOptional(value, "error_message", isString) && isOptional(value, "error_stack", isString);
565
+ var isDatabaseBundleEventMetadata = (value) => isDatabaseJsonObject(value) && typeof value.cohort === "string" && (value.update_strategy === null || value.update_strategy === "fingerprint" || value.update_strategy === "appVersion") && (value.fingerprint_hash === null || typeof value.fingerprint_hash === "string") && (value.sdk_version === null || typeof value.sdk_version === "string") && isOptional(value, "min_bundle_id", isString) && isOptional(value, "failure", isDatabaseBundleEventFailure) && isOptional(value, "http_response", isDatabaseHttpResponse) && isOptional(value, "delivery", isString) && isOptional(value, "patch_fallback", (flag) => typeof flag === "boolean") && isOptional(value, "change", isBundleEventChange) && isOptional(value, "late", (flag) => flag === true) && isOptional(value, "implied_download", (flag) => flag === true);
566
+ var isRecord$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
567
+ var isIdentity$1 = (value) => typeof value === "string" && value.length > 0 && value.length <= 255;
568
+ var isTextOrNull = (value) => value === null || typeof value === "string";
569
+ /** Each bundle event field and what it holds. */
570
+ var BUNDLE_EVENT_FIELDS = {
571
+ id: (value) => typeof value === "string",
572
+ type: (value) => value === "UPDATE_DOWNLOADED" || value === "UPDATE_APPLIED" || value === "RECOVERED" || value === "UPDATE_FAILED" || value === "UNCHANGED",
573
+ install_id: isIdentity$1,
574
+ user_id: (value) => value === null || isIdentity$1(value),
575
+ from_bundle_id: isTextOrNull,
576
+ from_release_id: isTextOrNull,
577
+ to_release_id: isTextOrNull,
578
+ to_bundle_id: (value) => typeof value === "string",
579
+ platform: (value) => value === "ios" || value === "android",
580
+ app_version: (value) => typeof value === "string",
581
+ channel: (value) => typeof value === "string",
582
+ metadata: isDatabaseBundleEventMetadata,
583
+ received_at_ms: (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0
584
+ };
585
+ var hasMetadata = (row, key) => isRecord$3(row.metadata) && Object.hasOwn(row.metadata, key);
586
+ var updateStrategyOf = (row) => isRecord$3(row.metadata) ? row.metadata.update_strategy : void 0;
587
+ /**
588
+ * A movement, or a failed update, names the bundle it left and how the
589
+ * device updates, and a failed update says what failed; an unchanged report
590
+ * names neither.
591
+ */
592
+ var hasEventInvariants = (row) => (row.type === "UPDATE_DOWNLOADED" || row.type === "UPDATE_APPLIED" || row.type === "RECOVERED" || row.type === "UPDATE_FAILED") && typeof row.from_bundle_id === "string" && (updateStrategyOf(row) === "fingerprint" || updateStrategyOf(row) === "appVersion") && (row.type !== "UPDATE_FAILED" || isRecord$3(row.metadata) && isRecord$3(row.metadata.failure)) && !hasMetadata(row, "change") && (!hasMetadata(row, "late") || row.type === "UPDATE_DOWNLOADED" || row.type === "UPDATE_APPLIED") && (!hasMetadata(row, "implied_download") || row.type === "UPDATE_APPLIED" || row.type === "RECOVERED") || row.type === "UNCHANGED" && !hasMetadata(row, "late") && row.from_bundle_id === null && updateStrategyOf(row) === null;
593
+ /**
594
+ * Throws unless `row` has exactly the bundle event fields, each of its type,
595
+ * and the invariants of its event type: `invalid-field` for an unknown field,
596
+ * `invalid-data` for anything else.
597
+ */
598
+ var validateBundleEventFields = (row) => {
599
+ if (!isRecord$3(row)) throw new DatabaseAdapterInputError("invalid-data");
600
+ for (const field of Object.keys(row)) if (!Object.hasOwn(BUNDLE_EVENT_FIELDS, field)) throw new DatabaseAdapterInputError("invalid-field");
601
+ for (const [field, valid] of Object.entries(BUNDLE_EVENT_FIELDS)) if (!Object.hasOwn(row, field) || !valid(row[field])) throw new DatabaseAdapterInputError("invalid-data");
602
+ if (!hasEventInvariants(row)) throw new DatabaseAdapterInputError("invalid-data");
603
+ };
604
+ var encoder = new TextEncoder();
605
+ /** Exact UTF-8 byte ordering, without case folding or Unicode normalization. */
606
+ var compareInsightsText = (left, right) => {
607
+ const a = encoder.encode(left);
608
+ const b = encoder.encode(right);
609
+ for (let index = 0; index < Math.min(a.length, b.length); index += 1) if (a[index] !== b[index]) return a[index] - b[index];
610
+ return a.length - b.length;
611
+ };
612
+ var isWellFormedText = (value) => {
613
+ for (const character of value) {
614
+ const point = character.codePointAt(0);
615
+ if (point >= 55296 && point <= 57343) return false;
616
+ }
617
+ return true;
618
+ };
619
+ var isIdentity = (value) => typeof value === "string" && value.length > 0 && value.length <= 255 && isWellFormedText(value);
620
+ var isText = (value) => typeof value === "string" && value.length > 0 && isWellFormedText(value);
621
+ var isTimestamp = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
622
+ var isLimit = (value) => isTimestamp(value) && value >= 1 && value <= 101;
623
+ var hasOnlyKeys = (value, keys) => Object.keys(value).every((key) => keys.includes(key));
624
+ var hasScope = (value) => (value.platform === "ios" || value.platform === "android") && isText(value.channel);
625
+ var isBundleFilter = (value, withKind = false) => {
626
+ if (!isRecord$3(value) || !hasScope(value)) return false;
627
+ const keys = [
628
+ "platform",
629
+ "channel",
630
+ "type",
631
+ ...withKind ? ["kind"] : []
632
+ ];
633
+ return value.type === "RECOVERED" ? isText(value.fromBundleId) && hasOnlyKeys(value, [...keys, "fromBundleId"]) : (value.type === "UPDATE_DOWNLOADED" || value.type === "UPDATE_APPLIED" || value.type === "UPDATE_FAILED" || value.type === "UNCHANGED") && isText(value.toBundleId) && hasOnlyKeys(value, [...keys, "toBundleId"]);
634
+ };
635
+ var isEventFilter = (value) => {
636
+ if (!isRecord$3(value)) return false;
637
+ if (value.kind === "all") return hasOnlyKeys(value, ["kind"]);
638
+ if (value.kind === "installationMovement") return isIdentity(value.installId) && hasOnlyKeys(value, ["kind", "installId"]);
639
+ return value.kind === "bundle" && isBundleFilter(value, true);
640
+ };
641
+ var validateRow = (model, row, result = false) => {
642
+ try {
643
+ validateBundleEventFields(row);
644
+ if (!isRecord$3(row) || typeof row.id !== "string" || !isUUIDv7(row.id) || [...Object.values(row), ...isRecord$3(row.metadata) ? Object.values(row.metadata) : []].some((value) => typeof value === "string" && !isWellFormedText(value))) throw new DatabaseAdapterInputError("invalid-data");
645
+ } catch (error) {
646
+ if (result) throw new DatabaseAdapterInputError("invalid-result");
647
+ throw error;
648
+ }
649
+ };
650
+ /**
651
+ * Downloads, applies, recoveries, failed updates, and the UNCHANGED rows
652
+ * kept for a change belong in installation history.
653
+ */
654
+ var isInsightsMovementEvent = (event) => event.type === "UPDATE_DOWNLOADED" || event.type === "UPDATE_APPLIED" || event.type === "RECOVERED" || event.type === "UPDATE_FAILED" || event.type === "UNCHANGED";
655
+ var matchesInsightsEventFilter = (event, filter) => {
656
+ if (filter.kind === "all") return true;
657
+ if (filter.kind === "installationMovement") return event.install_id === filter.installId && isInsightsMovementEvent(event);
658
+ return event.type === filter.type && event.platform === filter.platform && event.channel === filter.channel && bundleRefsOf(event).includes(bundleRefOfFilter(filter));
659
+ };
660
+ var invalidQuery = () => {
661
+ throw new DatabaseAdapterInputError("invalid-query");
662
+ };
663
+ var invalidResult = () => {
664
+ throw new DatabaseAdapterInputError("invalid-result");
665
+ };
666
+ var validateCount = (count) => isTimestamp(count) ? count : invalidResult();
667
+ var isTimeRange = (value) => isRecord$3(value) && hasOnlyKeys(value, ["start", "end"]) && isTimestamp(value.start) && isTimestamp(value.end) && value.start < value.end;
668
+ var isReleaseReference = (value) => isRecord$3(value) && hasOnlyKeys(value, [
669
+ "releaseId",
670
+ "platform",
671
+ "channel"
672
+ ]) && isIdentity(value.releaseId) && hasScope(value);
673
+ var validateAggregateResult = (value) => {
674
+ const result = isRecord$3(value) ? value : invalidResult();
675
+ if (!isTimestamp(result.measuredAtMs)) invalidResult();
676
+ const coverage = result.coverage;
677
+ if (!isRecord$3(coverage) || coverage.kind !== "complete" && coverage.kind !== "partial" || coverage.sinceMs !== null && !isTimestamp(coverage.sinceMs)) invalidResult();
678
+ };
679
+ /** Validate custom and bundled providers at the same public boundary. */
680
+ var createValidatedInsightsModel = (model) => ({
681
+ async recordEvent(input) {
682
+ if (!isRecord$3(input) || !hasOnlyKeys(input, ["event"])) throw new DatabaseAdapterInputError("invalid-data");
683
+ validateRow("bundle_events", input.event);
684
+ await model.recordEvent(input);
685
+ },
686
+ async listEvents(input) {
687
+ if (!isRecord$3(input) || !hasOnlyKeys(input, [
688
+ "filter",
689
+ "sinceMs",
690
+ "beforeReceivedAtMs",
691
+ "after",
692
+ "limit"
693
+ ]) || !isEventFilter(input.filter) || !isLimit(input.limit) || !isTimestamp(input.beforeReceivedAtMs) || input.sinceMs !== void 0 && !isTimestamp(input.sinceMs)) invalidQuery();
694
+ const sinceMs = input.sinceMs ?? 0;
695
+ if (sinceMs > input.beforeReceivedAtMs || input.after !== void 0 && (!isRecord$3(input.after) || !hasOnlyKeys(input.after, ["receivedAtMs", "id"]) || !isTimestamp(input.after.receivedAtMs) || typeof input.after.id !== "string" || !isUUIDv7(input.after.id) || input.after.receivedAtMs < sinceMs || input.after.receivedAtMs >= input.beforeReceivedAtMs)) invalidQuery();
696
+ const rows = await model.listEvents(input);
697
+ if (!Array.isArray(rows) || rows.length > input.limit) invalidResult();
698
+ let previous = input.after;
699
+ for (const row of rows) {
700
+ validateRow("bundle_events", row, true);
701
+ if (row.received_at_ms < sinceMs || row.received_at_ms >= input.beforeReceivedAtMs || !matchesInsightsEventFilter(row, input.filter) || previous !== void 0 && (row.received_at_ms > previous.receivedAtMs || row.received_at_ms === previous.receivedAtMs && row.id >= previous.id)) invalidResult();
702
+ previous = {
703
+ receivedAtMs: row.received_at_ms,
704
+ id: row.id
705
+ };
706
+ }
707
+ return rows;
708
+ },
709
+ async findLatestEvents(input) {
710
+ if (!isRecord$3(input)) invalidQuery();
711
+ if ("installId" in input) {
712
+ if (!hasOnlyKeys(input, ["installId"]) || !isIdentity(input.installId)) invalidQuery();
713
+ } else if (!hasOnlyKeys(input, [
714
+ "userId",
715
+ "afterInstallId",
716
+ "limit"
717
+ ]) || !isIdentity(input.userId) || !isLimit(input.limit) || input.afterInstallId !== void 0 && !isIdentity(input.afterInstallId)) invalidQuery();
718
+ const rows = await model.findLatestEvents(input);
719
+ if (!Array.isArray(rows) || rows.length > ("installId" in input ? 1 : input.limit)) invalidResult();
720
+ let previous = "installId" in input ? void 0 : input.afterInstallId;
721
+ for (const row of rows) {
722
+ validateRow("bundle_events", row, true);
723
+ if ("installId" in input ? row.install_id !== input.installId : row.user_id !== input.userId || previous !== void 0 && compareInsightsText(row.install_id, previous) <= 0) invalidResult();
724
+ previous = row.install_id;
725
+ }
726
+ return rows;
727
+ },
728
+ async countLatestEvents(input) {
729
+ if (!isRecord$3(input) || !hasOnlyKeys(input, [
730
+ "platform",
731
+ "channel",
732
+ "sinceMs",
733
+ "bundle"
734
+ ]) || !hasScope(input) || !isTimestamp(input.sinceMs) || input.bundle !== void 0 && (!Array.isArray(input.bundle) || input.bundle.length < 1 || input.bundle.length > 2 || input.bundle.some((bundle) => !isRecord$3(bundle) || !hasOnlyKeys(bundle, [
735
+ "field",
736
+ "value",
737
+ "types"
738
+ ]) || bundle.field !== "from_bundle_id" && bundle.field !== "to_bundle_id" || !isText(bundle.value) || !Array.isArray(bundle.types) || bundle.types.length === 0 || bundle.types.some((type) => ![
739
+ "UNCHANGED",
740
+ "UPDATE_DOWNLOADED",
741
+ "UPDATE_APPLIED",
742
+ "RECOVERED"
743
+ ].includes(type))))) invalidQuery();
744
+ return validateCount(await model.countLatestEvents(input));
745
+ },
746
+ async countEvents(input) {
747
+ if (!isRecord$3(input) || !hasOnlyKeys(input, [
748
+ "filter",
749
+ "sinceMs",
750
+ "beforeReceivedAtMs"
751
+ ]) || !isBundleFilter(input.filter) || !isTimestamp(input.sinceMs) || !isTimestamp(input.beforeReceivedAtMs) || input.sinceMs > input.beforeReceivedAtMs) invalidQuery();
752
+ return validateCount(await model.countEvents(input));
753
+ },
754
+ async countEventSeries(input) {
755
+ if (!isRecord$3(input) || !hasOnlyKeys(input, [
756
+ "filter",
757
+ "timeRange",
758
+ "intervalMs"
759
+ ]) || !isBundleFilter(input.filter) || !isTimeRange(input.timeRange) || !isTimestamp(input.intervalMs)) invalidQuery();
760
+ const { start, end } = input.timeRange;
761
+ const { intervalMs } = input;
762
+ if (intervalMs === 0 || intervalMs % 36e5 !== 0 || start % 36e5 !== 0 || (end - start) % intervalMs !== 0 || end - start > 7776e6) invalidQuery();
763
+ const points = await model.countEventSeries(input);
764
+ if (!Array.isArray(points) || points.length !== (end - start) / intervalMs || points.some((point, index) => !isRecord$3(point) || !hasOnlyKeys(point, ["startMs", "events"]) || point.startMs !== start + index * intervalMs || !isTimestamp(point.events))) invalidResult();
765
+ return points;
766
+ },
767
+ async getReleaseActivity(input) {
768
+ if (!isRecord$3(input) || !hasOnlyKeys(input, ["releases"]) || !Array.isArray(input.releases) || input.releases.length < 1 || input.releases.length > 100 || !input.releases.every(isReleaseReference)) invalidQuery();
769
+ const result = await model.getReleaseActivity(input);
770
+ if (!isRecord$3(result) || !isTimestamp(result.measuredAtMs) || !Array.isArray(result.data) || result.data.some((item) => !isRecord$3(item) || !isReleaseReference(item.release) || !isRecord$3(item.metrics) || !isTimestamp(item.metrics.downloads) || !isTimestamp(item.metrics.applies) || !isTimestamp(item.metrics.failedLaunches))) invalidResult();
771
+ return result;
772
+ },
773
+ async getAppUsage(input) {
774
+ if (!isRecord$3(input) || !hasOnlyKeys(input, [
775
+ "channel",
776
+ "platform",
777
+ "appVersion",
778
+ "timeRange",
779
+ "intervalMs"
780
+ ]) || !isText(input.channel) || ![
781
+ "all",
782
+ "ios",
783
+ "android"
784
+ ].includes(input.platform) || input.appVersion !== void 0 && !isText(input.appVersion) || !isTimeRange(input.timeRange) || !isTimestamp(input.intervalMs) || input.intervalMs < 36e5) invalidQuery();
785
+ const result = await model.getAppUsage(input);
786
+ validateAggregateResult(result);
787
+ if (!isTimestamp(result.activeInstallations) || !Array.isArray(result.points) || !Array.isArray(result.appVersions) || !Array.isArray(result.versions) || !Array.isArray(result.platforms) || !Array.isArray(result.bundleDistribution)) invalidResult();
788
+ return result;
789
+ }
790
+ });
791
+ /**
792
+ * The plugin's API as `InsightsModel`, validated at its boundary: what the
793
+ * Insights routes, the console, and the e2e harness read through.
794
+ */
795
+ var createInsightsModel = (api) => createValidatedInsightsModel({
796
+ recordEvent: ({ event }) => api.recordEvent(event),
797
+ listEvents: api.listEvents,
798
+ findLatestEvents: api.findLatestEvents,
799
+ countLatestEvents: api.countLatestEvents,
800
+ countEvents: api.countEvents,
801
+ countEventSeries: api.countEventSeries,
802
+ getReleaseActivity: api.getReleaseActivity,
803
+ getAppUsage: api.getAppUsage
804
+ });
805
+ /**
806
+ * What Insights' API throws for an input it refuses, such as an unknown
807
+ * event field or a malformed cursor; its routes answer 400 for it.
808
+ */
809
+ var InsightsBadRequestError = class extends Error {
810
+ name = "InsightsBadRequestError";
811
+ };
812
+ var MAX_EVENT_STRING_LENGTH = 1024;
813
+ var MAX_IDENTITY_LENGTH$1 = 255;
814
+ function isRecord$2(value) {
815
+ return typeof value === "object" && value !== null && !Array.isArray(value);
816
+ }
817
+ function requireStringField(payload, key) {
818
+ const value = payload[key];
819
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_EVENT_STRING_LENGTH || new TextDecoder("utf-8", { ignoreBOM: true }).decode(new TextEncoder().encode(value)) !== value) throw new InsightsBadRequestError(`Invalid event field: ${key}`);
820
+ return value;
821
+ }
822
+ function requireNullableStringField(payload, key) {
823
+ if (payload[key] === null) return null;
824
+ return requireStringField(payload, key);
825
+ }
826
+ function requireIdentityField(payload, key) {
827
+ const value = requireStringField(payload, key);
828
+ if (value.length > MAX_IDENTITY_LENGTH$1) throw new InsightsBadRequestError(`Invalid event field: ${key}`);
829
+ return value;
830
+ }
831
+ /**
832
+ * The report's idempotency key, when the client sends one: it creates the
833
+ * UUIDv7 once and repeats it on every retry of that report.
834
+ */
835
+ function readEventId(payload) {
836
+ const value = payload.eventId;
837
+ if (value === void 0) return void 0;
838
+ if (!isUUIDv7(value)) throw new InsightsBadRequestError("Invalid event field: eventId");
839
+ return value;
840
+ }
841
+ /**
842
+ * The native build's built-in bundle ID: a bundle ID's length at most, and
843
+ * left out when it is missing or malformed, so the report still records.
844
+ */
845
+ var readMinBundleId = (value) => typeof value === "string" && value.length > 0 && value.length <= 36 ? value : null;
846
+ /** One value of an open set: any other value reads as `unknown`. */
847
+ var oneOf = (values, value) => values.includes(value) ? value : "unknown";
848
+ var STAGES = [
849
+ "check",
850
+ "download",
851
+ "install"
852
+ ];
853
+ var REASONS = [
854
+ "network",
855
+ "http",
856
+ "invalid_response",
857
+ "hash_mismatch",
858
+ "signature",
859
+ "patch",
860
+ "extract",
861
+ "storage"
862
+ ];
863
+ var RESOURCES = [
864
+ "catalog",
865
+ "artifact",
866
+ "manifest",
867
+ "file",
868
+ "patch",
869
+ "archive"
870
+ ];
871
+ var TRANSPORTS = [
872
+ "timeout",
873
+ "dns",
874
+ "tls",
875
+ "connection",
876
+ "offline",
877
+ "cancelled"
878
+ ];
879
+ var DELIVERIES = [
880
+ "patch",
881
+ "manifest",
882
+ "archive"
883
+ ];
884
+ /** A storage error code: letters, digits, and `._-`. */
885
+ var CODE = /^[A-Za-z0-9._-]{1,64}$/;
886
+ var readCode = (value) => typeof value === "string" && CODE.test(value) ? value : void 0;
887
+ var readMetadata = (payload) => isRecord$2(payload.metadata) ? payload.metadata : {};
888
+ /**
889
+ * What an UPDATE_FAILED report says failed. It never refuses the report: an
890
+ * unknown value of a set reads as `unknown`, a missing or malformed failure
891
+ * as an unknown stage and reason, and a malformed optional field is left out,
892
+ * as is a null one.
893
+ */
894
+ function readFailure(value) {
895
+ const failure = isRecord$2(value) ? value : {};
896
+ const httpStatus = failure.httpStatus;
897
+ const originCode = readCode(failure.originCode);
898
+ const errorMessage = typeof failure.errorMessage === "string" && failure.errorMessage.length <= 2048 ? failure.errorMessage : void 0;
899
+ const errorStack = typeof failure.errorStack === "string" && failure.errorStack.length <= 4096 ? failure.errorStack : void 0;
900
+ return {
901
+ stage: oneOf(STAGES, failure.stage),
902
+ reason: oneOf(REASONS, failure.reason),
903
+ ...failure.resource == null ? {} : { resource: oneOf(RESOURCES, failure.resource) },
904
+ ...Number.isSafeInteger(httpStatus) && httpStatus >= 100 && httpStatus <= 599 ? { httpStatus } : {},
905
+ ...failure.transport == null ? {} : { transport: oneOf(TRANSPORTS, failure.transport) },
906
+ ...originCode === void 0 ? {} : { originCode },
907
+ ...errorMessage === void 0 ? {} : { errorMessage },
908
+ ...errorStack === void 0 ? {} : { errorStack }
909
+ };
910
+ }
911
+ function readHttpResponse(value) {
912
+ if (!isRecord$2(value) || value.resource !== "catalog" && value.resource !== "artifact" || typeof value.path !== "string" || value.path.length > 1024 || !Number.isSafeInteger(value.status) || value.status < 100 || value.status > 599 || value.body !== null && (typeof value.body !== "string" || new TextEncoder().encode(JSON.stringify(value.body)).byteLength > 4096) || typeof value.bodyTruncated !== "boolean" || !Number.isSafeInteger(value.receivedAtMs) || value.receivedAtMs < 0) throw new InsightsBadRequestError("Invalid HTTP response details");
913
+ return {
914
+ resource: value.resource,
915
+ path: value.path,
916
+ status: value.status,
917
+ body: value.body,
918
+ bodyTruncated: value.bodyTruncated,
919
+ receivedAtMs: value.receivedAtMs
920
+ };
921
+ }
922
+ function requireEvent(payload) {
923
+ if (!isRecord$2(payload)) throw new InsightsBadRequestError("Invalid event payload");
924
+ const platform = requireStringField(payload, "platform");
925
+ if (platform !== "ios" && platform !== "android") throw new InsightsBadRequestError("Invalid event field: platform");
926
+ const eventId = readEventId(payload);
927
+ const metadata = readMetadata(payload);
928
+ const httpMetadata = metadata.httpResponse === void 0 ? {} : { httpResponse: readHttpResponse(metadata.httpResponse) };
929
+ const base = {
930
+ ...metadata.httpResponse === void 0 ? {} : { metadata: httpMetadata },
931
+ ...eventId === void 0 ? {} : { eventId },
932
+ installId: requireIdentityField(payload, "installId"),
933
+ toBundleId: requireStringField(payload, "toBundleId"),
934
+ ...payload.userId === void 0 ? {} : { userId: requireIdentityField(payload, "userId") },
935
+ platform,
936
+ appVersion: requireStringField(payload, "appVersion"),
937
+ channel: requireStringField(payload, "channel"),
938
+ cohort: requireStringField(payload, "cohort"),
939
+ fingerprintHash: requireNullableStringField(payload, "fingerprintHash"),
940
+ sdkVersion: payload.sdkVersion === void 0 ? null : requireNullableStringField(payload, "sdkVersion"),
941
+ minBundleId: readMinBundleId(payload.minBundleId),
942
+ fromReleaseId: requireNullableStringField(payload, "fromReleaseId"),
943
+ toReleaseId: requireNullableStringField(payload, "toReleaseId")
944
+ };
945
+ const type = requireStringField(payload, "type");
946
+ const movement = () => {
947
+ const updateStrategy = requireStringField(payload, "updateStrategy");
948
+ if (updateStrategy !== "fingerprint" && updateStrategy !== "appVersion") throw new InsightsBadRequestError("Invalid event field: updateStrategy");
949
+ return {
950
+ ...base,
951
+ fromBundleId: requireStringField(payload, "fromBundleId"),
952
+ updateStrategy
953
+ };
954
+ };
955
+ switch (type) {
956
+ case "UPDATE_DOWNLOADED": {
957
+ const delivery = metadata.delivery;
958
+ const read = {
959
+ ...httpMetadata,
960
+ ...delivery == null ? {} : { delivery: oneOf(DELIVERIES, delivery) },
961
+ ...metadata.patchFallback === true ? { patchFallback: true } : {}
962
+ };
963
+ return {
964
+ ...movement(),
965
+ type,
966
+ ...Object.keys(read).length === 0 ? {} : { metadata: read }
967
+ };
968
+ }
969
+ case "UPDATE_APPLIED":
970
+ case "RECOVERED": return {
971
+ ...movement(),
972
+ type
973
+ };
974
+ case "UPDATE_FAILED": return {
975
+ ...movement(),
976
+ type,
977
+ metadata: {
978
+ ...httpMetadata,
979
+ failure: readFailure(metadata.failure)
980
+ }
981
+ };
982
+ case "UNCHANGED":
983
+ if (payload.fromBundleId !== null || payload.updateStrategy !== null) throw new InsightsBadRequestError("Invalid unchanged event shape");
984
+ return {
985
+ ...base,
986
+ type,
987
+ fromBundleId: null,
988
+ updateStrategy: null
989
+ };
990
+ default: throw new InsightsBadRequestError("Invalid event field: type");
991
+ }
992
+ }
993
+ function createBundleEventRow(input) {
994
+ input = requireEvent(input);
995
+ const base = {
996
+ app_version: input.appVersion,
997
+ channel: input.channel,
998
+ from_release_id: input.fromReleaseId,
999
+ id: input.eventId ?? createUUIDv7(),
1000
+ install_id: input.installId,
1001
+ platform: input.platform,
1002
+ received_at_ms: Date.now(),
1003
+ to_bundle_id: input.toBundleId,
1004
+ to_release_id: input.toReleaseId,
1005
+ user_id: input.userId ?? null
1006
+ };
1007
+ const response = input.metadata?.httpResponse;
1008
+ const metadata = {
1009
+ ...response ? { http_response: {
1010
+ resource: response.resource,
1011
+ path: response.path,
1012
+ status: response.status,
1013
+ body: response.body,
1014
+ body_truncated: response.bodyTruncated,
1015
+ received_at_ms: response.receivedAtMs
1016
+ } } : {},
1017
+ cohort: input.cohort,
1018
+ fingerprint_hash: input.fingerprintHash,
1019
+ sdk_version: input.sdkVersion ?? null,
1020
+ ...input.minBundleId ? { min_bundle_id: input.minBundleId } : {},
1021
+ update_strategy: input.updateStrategy
1022
+ };
1023
+ switch (input.type) {
1024
+ case "UPDATE_DOWNLOADED": {
1025
+ const { delivery, patchFallback } = input.metadata ?? {};
1026
+ return {
1027
+ ...base,
1028
+ from_bundle_id: input.fromBundleId,
1029
+ type: input.type,
1030
+ metadata: {
1031
+ ...metadata,
1032
+ ...delivery === void 0 ? {} : { delivery },
1033
+ ...patchFallback ? { patch_fallback: true } : {}
1034
+ }
1035
+ };
1036
+ }
1037
+ case "UPDATE_APPLIED":
1038
+ case "RECOVERED": return {
1039
+ ...base,
1040
+ from_bundle_id: input.fromBundleId,
1041
+ type: input.type,
1042
+ metadata
1043
+ };
1044
+ case "UPDATE_FAILED": {
1045
+ const { failure } = input.metadata;
1046
+ return {
1047
+ ...base,
1048
+ from_bundle_id: input.fromBundleId,
1049
+ type: input.type,
1050
+ metadata: {
1051
+ ...metadata,
1052
+ failure: {
1053
+ stage: failure.stage,
1054
+ reason: failure.reason,
1055
+ ...failure.errorMessage === void 0 ? {} : { error_message: failure.errorMessage },
1056
+ ...failure.errorStack === void 0 ? {} : { error_stack: failure.errorStack },
1057
+ ...failure.resource === void 0 ? {} : { resource: failure.resource },
1058
+ ...failure.httpStatus === void 0 ? {} : { http_status: failure.httpStatus },
1059
+ ...failure.transport === void 0 ? {} : { transport: failure.transport },
1060
+ ...failure.originCode === void 0 ? {} : { origin_code: failure.originCode }
1061
+ }
1062
+ }
1063
+ };
1064
+ }
1065
+ case "UNCHANGED": return {
1066
+ ...base,
1067
+ from_bundle_id: null,
1068
+ type: input.type,
1069
+ metadata
1070
+ };
1071
+ }
1072
+ }
1073
+ var DEFAULT_PAGE_LIMIT = 50;
1074
+ var MAX_PAGE_LIMIT = 100;
1075
+ var MAX_EVENT_ID_LENGTH = 1024;
1076
+ var MAX_IDENTITY_LENGTH = 255;
1077
+ var MAX_CURSOR_LENGTH = 8192;
1078
+ var HOUR_MS = 36e5;
1079
+ var DAY_MS = 24 * HOUR_MS;
1080
+ var WINDOW_MS = {
1081
+ "24h": 864e5,
1082
+ "7d": 6048e5,
1083
+ "30d": 2592e6
1084
+ };
1085
+ /**
1086
+ * The longest receipt range, `[sinceMs, beforeReceivedAtMs)`, of a global or
1087
+ * bundle event list, and the range one covers without `sinceMs`: raw events
1088
+ * are listed inside a time range, as analytics products list them. It is a
1089
+ * duration, so a range that ends mid-day touches 91 UTC days. Installation
1090
+ * history is one index range and reads back to `sinceMs`.
1091
+ */
1092
+ var EVENT_LIST_RANGE_MS = 2160 * HOUR_MS;
1093
+ var isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1094
+ var requireString = (value, label, maximumLength) => {
1095
+ if (typeof value !== "string" || value.length === 0 || value.length > maximumLength || new TextDecoder("utf-8", { ignoreBOM: true }).decode(new TextEncoder().encode(value)) !== value) throw new InsightsBadRequestError(`Invalid ${label}.`);
1096
+ return value;
1097
+ };
1098
+ var requireTimestamp = (value, label) => {
1099
+ if (!Number.isSafeInteger(value) || Number(value) < 0) throw new InsightsBadRequestError(`Invalid ${label}.`);
1100
+ return Number(value);
1101
+ };
1102
+ var readLimit = (value) => {
1103
+ const limit = value ?? DEFAULT_PAGE_LIMIT;
1104
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_PAGE_LIMIT) throw new InsightsBadRequestError("Invalid page limit.");
1105
+ return limit;
1106
+ };
1107
+ var encodeBase64Url = (value) => {
1108
+ const bytes = new TextEncoder().encode(value);
1109
+ let binary = "";
1110
+ for (const byte of bytes) binary += String.fromCharCode(byte);
1111
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
1112
+ };
1113
+ var decodeBase64Url = (value) => {
1114
+ if (value.length === 0 || value.length > MAX_CURSOR_LENGTH) throw new InsightsBadRequestError("Invalid Insights cursor.");
1115
+ try {
1116
+ const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
1117
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
1118
+ const binary = atob(padded);
1119
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
1120
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1121
+ } catch {
1122
+ throw new InsightsBadRequestError("Invalid Insights cursor.");
1123
+ }
1124
+ };
1125
+ var encodeCursor = (value) => encodeBase64Url(JSON.stringify(value));
1126
+ var decodeCursor = (value) => {
1127
+ try {
1128
+ return JSON.parse(decodeBase64Url(value));
1129
+ } catch (error) {
1130
+ if (error instanceof InsightsBadRequestError) throw error;
1131
+ throw new InsightsBadRequestError("Invalid Insights cursor.");
1132
+ }
1133
+ };
1134
+ var readScope = (input) => {
1135
+ if (input.platform !== "ios" && input.platform !== "android") throw new InsightsBadRequestError("Invalid Insights platform.");
1136
+ return {
1137
+ platform: input.platform,
1138
+ channel: requireString(input.channel, "channel", MAX_EVENT_ID_LENGTH)
1139
+ };
1140
+ };
1141
+ var bundleFilter = (input) => {
1142
+ const scope = readScope(input);
1143
+ const bundleId = requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
1144
+ switch (input.outcome) {
1145
+ case "downloaded": return {
1146
+ ...scope,
1147
+ type: "UPDATE_DOWNLOADED",
1148
+ toBundleId: bundleId
1149
+ };
1150
+ case "applied": return {
1151
+ ...scope,
1152
+ type: "UPDATE_APPLIED",
1153
+ toBundleId: bundleId
1154
+ };
1155
+ case "recovered": return {
1156
+ ...scope,
1157
+ type: "RECOVERED",
1158
+ fromBundleId: bundleId
1159
+ };
1160
+ case "failed": return {
1161
+ ...scope,
1162
+ type: "UPDATE_FAILED",
1163
+ toBundleId: bundleId
1164
+ };
1165
+ default: throw new InsightsBadRequestError("Invalid Insights outcome.");
1166
+ }
1167
+ };
1168
+ var sameFilter = (left, right) => {
1169
+ if (!isRecord$1(left) || left.kind !== right.kind) return false;
1170
+ switch (right.kind) {
1171
+ case "all": return true;
1172
+ case "installationMovement": return left.installId === right.installId;
1173
+ case "bundle": return left.platform === right.platform && left.channel === right.channel && left.type === right.type && (right.type === "RECOVERED" ? left.fromBundleId === right.fromBundleId : left.toBundleId === right.toBundleId);
1174
+ }
1175
+ };
1176
+ var readEventCursor = (value, filter) => {
1177
+ const cursor = decodeCursor(value);
1178
+ if (!isRecord$1(cursor) || cursor.version !== 2 || cursor.kind !== "events" || !isRecord$1(cursor.filter) || !isRecord$1(cursor.after)) throw new InsightsBadRequestError("Invalid Insights cursor.");
1179
+ if (!sameFilter(cursor.filter, filter)) throw new InsightsBadRequestError("Insights cursor does not match the requested events.");
1180
+ if (typeof cursor.after.id !== "string" || !isUUIDv7(cursor.after.id)) throw new InsightsBadRequestError("Invalid Insights event cursor ID.");
1181
+ return {
1182
+ after: {
1183
+ id: cursor.after.id,
1184
+ receivedAtMs: requireTimestamp(cursor.after.receivedAtMs, "event cursor")
1185
+ },
1186
+ beforeReceivedAtMs: requireTimestamp(cursor.beforeReceivedAtMs, "event cutoff"),
1187
+ kind: "events",
1188
+ sinceMs: requireTimestamp(cursor.sinceMs, "event start"),
1189
+ filter,
1190
+ version: 2
1191
+ };
1192
+ };
1193
+ var readUserInstallationCursor = (value, userId) => {
1194
+ const cursor = decodeCursor(value);
1195
+ if (!isRecord$1(cursor) || cursor.version !== 1 || cursor.kind !== "user-installations" || cursor.userId !== userId) throw new InsightsBadRequestError("Insights cursor does not match the requested user ID.");
1196
+ return {
1197
+ afterInstallId: requireString(cursor.afterInstallId, "installation cursor", MAX_IDENTITY_LENGTH),
1198
+ kind: "user-installations",
1199
+ userId,
1200
+ version: 1
1201
+ };
1202
+ };
1203
+ var compareEventNewest = (left, right) => right.received_at_ms - left.received_at_ms || compareInsightsText(right.id, left.id);
1204
+ var isAfterEventCursor = (row, after) => row.received_at_ms < after.receivedAtMs || row.received_at_ms === after.receivedAtMs && compareInsightsText(row.id, after.id) < 0;
1205
+ var assertEventRows = (rows, input) => {
1206
+ if (rows.length > input.limit) throw new Error("Insights database returned too many event rows.");
1207
+ for (let index = 0; index < rows.length; index += 1) {
1208
+ const row = rows[index];
1209
+ const previous = rows[index - 1];
1210
+ if (!row || typeof row.id !== "string" || !isUUIDv7(row.id) || !Number.isSafeInteger(row.received_at_ms) || row.received_at_ms >= input.beforeReceivedAtMs || row.received_at_ms < input.sinceMs || previous !== void 0 && compareEventNewest(previous, row) >= 0 || input.after !== void 0 && !isAfterEventCursor(row, input.after) || input.filter.kind === "installationMovement" && (row.install_id !== input.filter.installId || !isInsightsMovementEvent(row)) || input.filter.kind === "bundle" && (row.platform !== input.filter.platform || row.channel !== input.filter.channel || row.type !== input.filter.type || (input.filter.type === "RECOVERED" ? row.from_bundle_id !== input.filter.fromBundleId : row.to_bundle_id !== input.filter.toBundleId))) throw new Error("Insights database returned invalid event rows.");
1211
+ }
1212
+ };
1213
+ /** An `UPDATE_FAILED` row's failure, as the event lists show it. */
1214
+ var toFailure = (failure) => ({
1215
+ stage: failure.stage,
1216
+ reason: failure.reason,
1217
+ ...failure.error_message === void 0 ? {} : { errorMessage: failure.error_message },
1218
+ ...failure.error_stack === void 0 ? {} : { errorStack: failure.error_stack },
1219
+ ...failure.resource === void 0 ? {} : { resource: failure.resource },
1220
+ ...failure.http_status === void 0 ? {} : { httpStatus: failure.http_status },
1221
+ ...failure.transport === void 0 ? {} : { transport: failure.transport },
1222
+ ...failure.origin_code === void 0 ? {} : { originCode: failure.origin_code }
1223
+ });
1224
+ /** What a row's metadata adds for its type: a failure or a delivery. */
1225
+ var eventDetails = ({ type, metadata }) => ({
1226
+ ...metadata.http_response !== void 0 ? { httpResponse: {
1227
+ resource: metadata.http_response.resource,
1228
+ path: metadata.http_response.path,
1229
+ status: metadata.http_response.status,
1230
+ body: metadata.http_response.body,
1231
+ bodyTruncated: metadata.http_response.body_truncated,
1232
+ receivedAtMs: metadata.http_response.received_at_ms
1233
+ } } : {},
1234
+ ...type === "UPDATE_FAILED" && metadata.failure !== void 0 ? { failure: toFailure(metadata.failure) } : {},
1235
+ ...type === "UPDATE_DOWNLOADED" && metadata.delivery !== void 0 ? { delivery: metadata.delivery } : {},
1236
+ ...type === "UPDATE_DOWNLOADED" && metadata.patch_fallback === true ? { patchFallback: true } : {},
1237
+ ...type === "UNCHANGED" && metadata.change !== void 0 ? { change: {
1238
+ kinds: metadata.change.kinds,
1239
+ ...metadata.change.previous === null ? {} : { previous: {
1240
+ bundleId: metadata.change.previous.bundle_id,
1241
+ releaseId: metadata.change.previous.release_id,
1242
+ appVersion: metadata.change.previous.app_version,
1243
+ channel: metadata.change.previous.channel,
1244
+ ...metadata.change.previous.min_bundle_id === void 0 ? {} : { minBundleId: metadata.change.previous.min_bundle_id }
1245
+ } }
1246
+ } } : {},
1247
+ ...metadata.late === true ? { late: true } : {},
1248
+ ...metadata.implied_download === true ? { impliedDownload: true } : {}
1249
+ });
1250
+ var toEventHistoryRow = (row) => ({
1251
+ ...row.to_release_id == null ? {} : { toReleaseId: row.to_release_id },
1252
+ ...row.metadata.sdk_version == null ? {} : { sdkVersion: row.metadata.sdk_version },
1253
+ ...row.metadata.min_bundle_id === void 0 ? {} : { minBundleId: row.metadata.min_bundle_id },
1254
+ appVersion: row.app_version,
1255
+ channel: row.channel,
1256
+ cohort: row.metadata.cohort,
1257
+ fromBundleId: row.from_bundle_id,
1258
+ id: row.id,
1259
+ installId: row.install_id,
1260
+ platform: row.platform,
1261
+ receivedAtMs: row.received_at_ms,
1262
+ toBundleId: row.to_bundle_id,
1263
+ type: row.type,
1264
+ userId: row.user_id,
1265
+ ...eventDetails(row)
1266
+ });
1267
+ var toInstallationRow = (row) => ({
1268
+ ...eventDetails(row).httpResponse ? { httpResponse: eventDetails(row).httpResponse } : {},
1269
+ ...row.metadata.min_bundle_id === void 0 ? {} : { minBundleId: row.metadata.min_bundle_id },
1270
+ appVersion: row.app_version,
1271
+ channel: row.channel,
1272
+ cohort: row.metadata.cohort,
1273
+ installId: row.install_id,
1274
+ lastKnownBundleId: row.type === "UPDATE_DOWNLOADED" ? row.from_bundle_id : row.to_bundle_id,
1275
+ pendingBundleId: row.type === "UPDATE_DOWNLOADED" ? row.to_bundle_id : null,
1276
+ pendingReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.to_release_id : null,
1277
+ latestStatus: row.type,
1278
+ platform: row.platform,
1279
+ receivedAtMs: row.received_at_ms,
1280
+ userId: row.user_id
1281
+ });
1282
+ /**
1283
+ * Where a list without `sinceMs` starts: 90 days before its cutoff for the
1284
+ * global and bundle lists, at the first event for installation history.
1285
+ */
1286
+ var defaultEventStart = (filter, beforeReceivedAtMs) => filter.kind === "installationMovement" ? 0 : Math.max(0, beforeReceivedAtMs - EVENT_LIST_RANGE_MS);
1287
+ /** Whether a cursor's row lies inside the list's range. */
1288
+ var isInsideBounds = ({ after }, bounds) => after.receivedAtMs >= bounds.sinceMs && after.receivedAtMs < bounds.beforeReceivedAtMs;
1289
+ /** A page's range: its cursor's, which the request may repeat but not change. */
1290
+ var readEventBounds = (input, cursor, filter) => {
1291
+ const beforeReceivedAtMs = cursor?.beforeReceivedAtMs ?? (input.beforeReceivedAtMs === void 0 ? Date.now() : requireTimestamp(input.beforeReceivedAtMs, "event cutoff"));
1292
+ if (cursor !== void 0 && input.beforeReceivedAtMs !== void 0 && input.beforeReceivedAtMs !== beforeReceivedAtMs) throw new InsightsBadRequestError("Insights cursor does not match the requested event cutoff.");
1293
+ const sinceMs = cursor?.sinceMs ?? (input.sinceMs === void 0 ? defaultEventStart(filter, beforeReceivedAtMs) : requireTimestamp(input.sinceMs, "event start"));
1294
+ const bounds = {
1295
+ beforeReceivedAtMs,
1296
+ sinceMs
1297
+ };
1298
+ if (sinceMs > beforeReceivedAtMs || input.sinceMs !== void 0 && input.sinceMs !== sinceMs || cursor !== void 0 && !isInsideBounds(cursor, bounds)) throw new InsightsBadRequestError("Insights cursor or range does not match the requested event start.");
1299
+ if (filter.kind !== "installationMovement" && beforeReceivedAtMs - sinceMs > 7776e6) throw new InsightsBadRequestError("Insights event lists cover at most 90 days: send a sinceMs no more than 90 days before beforeReceivedAtMs.");
1300
+ return bounds;
1301
+ };
1302
+ var pageEventRows = async (model, input, filter, map) => {
1303
+ const limit = readLimit(input.limit);
1304
+ const cursor = input.cursor === void 0 ? void 0 : readEventCursor(input.cursor, filter);
1305
+ const bounds = readEventBounds(input, cursor, filter);
1306
+ const query = {
1307
+ filter,
1308
+ ...bounds,
1309
+ ...cursor === void 0 ? {} : { after: cursor.after },
1310
+ limit
1311
+ };
1312
+ const rows = await model.listEvents(query);
1313
+ assertEventRows(rows, query);
1314
+ const last = rows.at(-1);
1315
+ return {
1316
+ beforeReceivedAtMs: bounds.beforeReceivedAtMs,
1317
+ data: rows.map(map),
1318
+ nextCursor: rows.length === limit && last ? encodeCursor({
1319
+ after: {
1320
+ id: last.id,
1321
+ receivedAtMs: last.received_at_ms
1322
+ },
1323
+ ...bounds,
1324
+ kind: "events",
1325
+ filter,
1326
+ version: 2
1327
+ }) : null
1328
+ };
1329
+ };
1330
+ var assertInstallationRows = (rows, input) => {
1331
+ if (rows.length > input.limit) throw new Error("Insights database returned too many installation rows.");
1332
+ for (let index = 0; index < rows.length; index += 1) {
1333
+ const row = rows[index];
1334
+ const previous = rows[index - 1];
1335
+ if (!row || row.user_id !== input.userId || input.afterInstallId !== void 0 && compareInsightsText(row.install_id, input.afterInstallId) <= 0 || previous !== void 0 && compareInsightsText(previous.install_id, row.install_id) >= 0) throw new Error("Insights database returned invalid installation rows.");
1336
+ }
1337
+ };
1338
+ var createInsightsProvider = (model) => Object.freeze({
1339
+ async appendBundleEvent(input) {
1340
+ const event = createBundleEventRow(input);
1341
+ await model.recordEvent({ event });
1342
+ },
1343
+ listEvents(input) {
1344
+ return pageEventRows(model, input, input.bundle === void 0 ? { kind: "all" } : {
1345
+ kind: "bundle",
1346
+ ...bundleFilter(input.bundle)
1347
+ }, toEventHistoryRow);
1348
+ },
1349
+ async listInstallationEvents(input) {
1350
+ if ("bundle" in input && input.bundle !== void 0) throw new InsightsBadRequestError("Installation movement queries cannot include a bundle filter.");
1351
+ return pageEventRows(model, input, {
1352
+ kind: "installationMovement",
1353
+ installId: requireString(input.installId, "install ID", MAX_IDENTITY_LENGTH)
1354
+ }, (row) => toEventHistoryRow(row));
1355
+ },
1356
+ async getInstallation({ installId }) {
1357
+ const normalizedInstallId = requireString(installId, "install ID", MAX_IDENTITY_LENGTH);
1358
+ const rows = await model.findLatestEvents({ installId: normalizedInstallId });
1359
+ const row = rows[0] ?? null;
1360
+ if (rows.length > 1 || row !== null && row.install_id !== normalizedInstallId) throw new Error("Insights database returned an invalid installation.");
1361
+ return row === null ? null : toInstallationRow(row);
1362
+ },
1363
+ async pageInstallationsByCurrentUserId(input) {
1364
+ const userId = requireString(input.userId, "user ID", MAX_IDENTITY_LENGTH);
1365
+ const limit = readLimit(input.limit);
1366
+ const cursor = input.cursor === void 0 ? void 0 : readUserInstallationCursor(input.cursor, userId);
1367
+ const databaseInput = {
1368
+ userId,
1369
+ ...cursor === void 0 ? {} : { afterInstallId: cursor.afterInstallId },
1370
+ limit
1371
+ };
1372
+ const rows = await model.findLatestEvents(databaseInput);
1373
+ assertInstallationRows(rows, databaseInput);
1374
+ const last = rows.at(-1);
1375
+ return {
1376
+ data: rows.map(toInstallationRow),
1377
+ nextCursor: rows.length === limit && last ? encodeCursor({
1378
+ afterInstallId: last.install_id,
1379
+ kind: "user-installations",
1380
+ userId,
1381
+ version: 1
1382
+ }) : null
1383
+ };
1384
+ },
1385
+ async getReportingOverview(input) {
1386
+ const scope = readScope(input);
1387
+ const { window } = input;
1388
+ if (!Object.hasOwn(WINDOW_MS, window)) throw new InsightsBadRequestError("Invalid reporting installation window.");
1389
+ const now = Date.now();
1390
+ const beforeReceivedAtMs = now - now % HOUR_MS + (now % HOUR_MS === 0 ? 0 : HOUR_MS);
1391
+ const reach = Math.max(0, beforeReceivedAtMs - WINDOW_MS[window]);
1392
+ const sinceMs = reach - reach % DAY_MS;
1393
+ const measure = async (count) => {
1394
+ const value = await count;
1395
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("Insights database returned an invalid count.");
1396
+ return {
1397
+ count: value,
1398
+ measuredAtMs: Date.now()
1399
+ };
1400
+ };
1401
+ const bundleId = input.bundleId === void 0 ? void 0 : requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
1402
+ const reporting = measure(model.countLatestEvents({
1403
+ ...scope,
1404
+ sinceMs
1405
+ }));
1406
+ if (bundleId === void 0) return {
1407
+ ...scope,
1408
+ window,
1409
+ sinceMs,
1410
+ beforeReceivedAtMs,
1411
+ reportingInstallations: await reporting
1412
+ };
1413
+ const countOutcome = (outcome) => measure(model.countEvents({
1414
+ filter: bundleFilter({
1415
+ ...scope,
1416
+ bundleId,
1417
+ outcome
1418
+ }),
1419
+ sinceMs,
1420
+ beforeReceivedAtMs
1421
+ }));
1422
+ const [reportingInstallations, bundleInstallations, downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
1423
+ reporting,
1424
+ measure(model.countLatestEvents({
1425
+ ...scope,
1426
+ sinceMs,
1427
+ bundle: [{
1428
+ field: "from_bundle_id",
1429
+ value: bundleId,
1430
+ types: ["UPDATE_DOWNLOADED"]
1431
+ }, {
1432
+ field: "to_bundle_id",
1433
+ value: bundleId,
1434
+ types: [
1435
+ "UNCHANGED",
1436
+ "UPDATE_APPLIED",
1437
+ "RECOVERED"
1438
+ ]
1439
+ }]
1440
+ })),
1441
+ countOutcome("downloaded"),
1442
+ countOutcome("applied"),
1443
+ countOutcome("recovered"),
1444
+ countOutcome("failed")
1445
+ ]);
1446
+ return {
1447
+ ...scope,
1448
+ window,
1449
+ sinceMs,
1450
+ beforeReceivedAtMs,
1451
+ reportingInstallations,
1452
+ bundle: {
1453
+ bundleId,
1454
+ reportingInstallations: bundleInstallations,
1455
+ downloadedReports,
1456
+ appliedReports,
1457
+ recoveredReports,
1458
+ failedReports
1459
+ }
1460
+ };
1461
+ }
1462
+ });
1463
+ 30 * DAY_MS$1;
1464
+ /** The `error` a failed admin route answered with, or a message naming its status. */
1465
+ var errorOf = async (response, path) => {
1466
+ const body = await response.json().catch(() => null);
1467
+ return new Error(typeof body === "object" && body !== null && typeof Reflect.get(body, "error") === "string" ? String(Reflect.get(body, "error")) : `The server answered ${path.split("?")[0]} with ${response.status}.`);
1468
+ };
1469
+ var withQuery = (path, input) => {
1470
+ const query = new URLSearchParams();
1471
+ for (const [key, value] of Object.entries(input)) if (value !== void 0) query.set(key, String(value));
1472
+ const value = query.toString();
1473
+ return value.length === 0 ? path : `${path}?${value}`;
1474
+ };
1475
+ var eventQuery = ({ beforeReceivedAtMs, sinceMs, cursor, limit }) => ({
1476
+ beforeReceivedAtMs,
1477
+ sinceMs,
1478
+ cursor,
1479
+ limit
1480
+ });
1481
+ /**
1482
+ * A self-hosted server's Insights, read through the admin routes its
1483
+ * `insights()` plugin serves.
1484
+ */
1485
+ var createAdminInsightsReads = (fetchAdmin) => {
1486
+ const read = async (path) => {
1487
+ const response = await fetchAdmin(path);
1488
+ if (response.status === 404) return null;
1489
+ if (!response.ok) throw await errorOf(response, path);
1490
+ return await response.json();
1491
+ };
1492
+ const required = async (path) => {
1493
+ const value = await read(path);
1494
+ if (value === null) throw new ConsoleFeatureUnavailableError("insights", { remote: true });
1495
+ return value;
1496
+ };
1497
+ return {
1498
+ getReportingOverview: ({ platform, channel, window, bundleId }) => required(withQuery("/overview", {
1499
+ platform,
1500
+ channel,
1501
+ window,
1502
+ bundleId
1503
+ })),
1504
+ listEvents: ({ bundle, ...input }) => required(withQuery("/events", {
1505
+ ...eventQuery(input),
1506
+ ...bundle === void 0 ? {} : {
1507
+ platform: bundle.platform,
1508
+ channel: bundle.channel,
1509
+ bundleId: bundle.bundleId,
1510
+ outcome: bundle.outcome
1511
+ }
1512
+ })),
1513
+ listInstallationEvents: ({ installId, ...input }) => required(withQuery(`/installations/${encodeURIComponent(installId)}/events`, eventQuery(input))),
1514
+ getInstallation: ({ installId }) => read(`/installations/${encodeURIComponent(installId)}`),
1515
+ pageInstallationsByCurrentUserId: ({ userId, cursor, limit }) => required(withQuery("/installations", {
1516
+ userId,
1517
+ cursor,
1518
+ limit
1519
+ })),
1520
+ getUpdateFailures: ({ platform, channel, releaseId, timeRange }) => required(withQuery("/failures", {
1521
+ platform,
1522
+ channel,
1523
+ releaseId,
1524
+ start: timeRange?.start,
1525
+ end: timeRange?.end
1526
+ })),
1527
+ getRetention: () => required("/retention")
1528
+ };
1529
+ };
1530
+ var invalidOf = (error) => {
1531
+ if (error instanceof RemoteConfigValidationError) return {
1532
+ status: "invalid",
1533
+ issues: error.issues
1534
+ };
1535
+ throw error;
1536
+ };
1537
+ /** Remote Config over the `remoteConfig()` API the console assembled on the database. */
1538
+ var createLocalRemoteConfig = (api) => ({
1539
+ getActive: () => api.getActive(),
1540
+ listVersions: (input) => api.listVersions(input),
1541
+ getVersion: (version) => api.getVersion(version),
1542
+ publish: (input) => api.publish(input).catch(invalidOf),
1543
+ rollback: (input) => api.rollback(input)
1544
+ });
1545
+ var readBody = async (response) => response.json().catch(() => null);
1546
+ var field = (body, name) => typeof body === "object" && body !== null ? Reflect.get(body, name) : void 0;
1547
+ /** A published version's record, as a publish or a rollback answers it. */
1548
+ var isPublishedVersion = (body) => {
1549
+ const version = field(body, "version");
1550
+ const updateType = field(body, "updateType");
1551
+ return typeof version === "number" && Number.isSafeInteger(version) && version > 0 && (updateType === "PUBLISH" || updateType === "ROLLBACK") && typeof field(body, "createdAtMs") === "number";
1552
+ };
1553
+ var errorText = (body) => {
1554
+ const error = field(body, "error");
1555
+ return typeof error === "string" ? error : void 0;
1556
+ };
1557
+ /**
1558
+ * Remote Config over a self-hosted server's admin routes. A route the server
1559
+ * does not mount answers core's 404: it runs without `remoteConfig()`.
1560
+ */
1561
+ var createAdminRemoteConfig = (fetchAdmin) => {
1562
+ const unavailable = () => new ConsoleFeatureUnavailableError("remoteConfig", { remote: true });
1563
+ const request = async (path, init) => {
1564
+ const response = await fetchAdmin(path, init === void 0 ? void 0 : {
1565
+ method: init.method,
1566
+ headers: { "content-type": "application/json" },
1567
+ body: JSON.stringify(init.body)
1568
+ });
1569
+ const body = await readBody(response);
1570
+ if (response.status === 404 && errorText(body) === "Not found") throw unavailable();
1571
+ return {
1572
+ status: response.status,
1573
+ body
1574
+ };
1575
+ };
1576
+ const expectOk = (path, { status, body }) => {
1577
+ if (status >= 200 && status < 300) return body;
1578
+ throw new Error(errorText(body) ?? `The server answered ${path.split("?")[0]} with ${status}.`);
1579
+ };
1580
+ const published = (path, result) => {
1581
+ const currentVersion = field(result.body, "currentVersion");
1582
+ if (result.status === 409 && typeof currentVersion === "number" && Number.isSafeInteger(currentVersion)) return {
1583
+ status: "conflict",
1584
+ currentVersion
1585
+ };
1586
+ const issues = field(result.body, "issues");
1587
+ if (result.status === 400 && Array.isArray(issues)) return {
1588
+ status: "invalid",
1589
+ issues
1590
+ };
1591
+ const version = expectOk(path, result);
1592
+ if (!isPublishedVersion(version)) throw new Error(`The server answered ${path} without the version it published.`);
1593
+ return {
1594
+ status: "published",
1595
+ version
1596
+ };
1597
+ };
1598
+ return {
1599
+ getActive: async () => {
1600
+ const path = "/remote-config/template";
1601
+ return expectOk(path, await request(path));
1602
+ },
1603
+ listVersions: async ({ limit, cursor }) => {
1604
+ const query = new URLSearchParams();
1605
+ if (limit !== void 0) query.set("limit", String(limit));
1606
+ if (cursor !== void 0) query.set("cursor", cursor);
1607
+ const path = `/remote-config/versions${query.size === 0 ? "" : `?${query}`}`;
1608
+ return expectOk(path, await request(path));
1609
+ },
1610
+ getVersion: async (version) => {
1611
+ const path = `/remote-config/versions/${version}`;
1612
+ const result = await request(path);
1613
+ return result.status === 404 ? null : expectOk(path, result);
1614
+ },
1615
+ publish: async ({ template, baseVersion, description }) => {
1616
+ const path = "/remote-config/template";
1617
+ return published(path, await request(path, {
1618
+ method: "PUT",
1619
+ body: {
1620
+ template,
1621
+ baseVersion,
1622
+ description
1623
+ }
1624
+ }));
1625
+ },
1626
+ rollback: async ({ version, baseVersion }) => {
1627
+ const path = `/remote-config/versions/${version}/rollback`;
1628
+ const result = await request(path, {
1629
+ method: "POST",
1630
+ body: { baseVersion }
1631
+ });
1632
+ return result.status === 404 ? { status: "not_found" } : published(path, result);
1633
+ }
1634
+ };
1635
+ };
1636
+ var featureApi = (api) => api;
1637
+ /** What serves each console feature, keyed like `consoleFeatures`. */
1638
+ var consoleFeatureApis = {
1639
+ insights: featureApi({
1640
+ local: (api) => ({
1641
+ ...createInsightsProvider(createInsightsModel(api)),
1642
+ getRetention: async () => api.retention,
1643
+ getUpdateFailures: api.getUpdateFailures
1644
+ }),
1645
+ remote: createAdminInsightsReads
1646
+ }),
1647
+ insightsAnalytics: featureApi({ local: (api) => createInsightsModel(api) }),
1648
+ apiKeys: featureApi({ local: (api) => api }),
1649
+ remoteConfig: featureApi({
1650
+ local: (api) => createLocalRemoteConfig(api),
1651
+ remote: createAdminRemoteConfig
1652
+ })
1653
+ };
1654
+ var isRecord = (value) => typeof value === "object" && value !== null;
1655
+ /**
1656
+ * Whether one of Hot Updater's own factories made `plugin`: the brand they
1657
+ * set under a registered symbol, read here with a copy of the key so the
1658
+ * console imports no package's internals. Assembly refuses any other plugin
1659
+ * that takes one of their ids, so features key on it.
1660
+ */
1661
+ var isOfficialPlugin = (plugin) => isRecord(plugin) && Reflect.get(plugin, Symbol.for("@hot-updater/server/official-plugin")) === true;
1662
+ var featureIds = Object.keys(consoleFeatureApis);
1663
+ /**
1664
+ * What serves each feature, built by its factory: over the plugins' APIs the
1665
+ * console assembled, or over a self-hosted server's admin API. A feature
1666
+ * without its plugin, or without a factory for the admin API, has none.
1667
+ */
1668
+ var featureApis = (build) => Object.fromEntries(featureIds.flatMap((feature) => {
1669
+ const api = build(feature);
1670
+ return api === void 0 ? [] : [[feature, api]];
1671
+ }));
1672
+ /**
1673
+ * The console's features and what serves them, for the plugins its config
1674
+ * lists, the plugins the server runs:
1675
+ * - a self-hosted server (`standaloneRepository`) runs them itself; the
1676
+ * console serves what that server's admin API serves of their features,
1677
+ * and nothing that needs the database;
1678
+ * - otherwise the console runs them over the database, as the server does,
1679
+ * and serves their features through `api`, their APIs.
1680
+ */
1681
+ var createConsoleRuntime = (config) => {
1682
+ const { database } = config;
1683
+ const official = new Set(config.plugins.filter(isOfficialPlugin).map((plugin) => plugin.id));
1684
+ if (isRemoteDatabase(database)) {
1685
+ const { fetchAdmin } = database;
1686
+ const features = resolveConsoleFeatures([...official], { remote: true });
1687
+ return {
1688
+ remote: true,
1689
+ features: async () => features,
1690
+ apis: featureApis((feature) => consoleFeatureApis[feature].remote?.(fetchAdmin))
1691
+ };
1692
+ }
1693
+ const api = config.api ?? {};
1694
+ const features = resolveConsoleFeatures([...official], { remote: false });
1695
+ return {
1696
+ remote: false,
1697
+ features: async () => features,
1698
+ apis: featureApis((feature) => {
1699
+ const { plugin } = consoleFeatures[feature];
1700
+ const pluginApi = official.has(plugin) ? api[plugin] : void 0;
1701
+ return pluginApi === void 0 ? void 0 : consoleFeatureApis[feature].local(pluginApi);
1702
+ })
1703
+ };
1704
+ };
1705
+ /**
1706
+ * What serves `feature`. Every feature's server function asks for it first,
1707
+ * so a feature the console does not serve is refused with one error the
1708
+ * client recognizes, before anything is read.
1709
+ */
1710
+ var requireFeature = async (runtime, feature) => {
1711
+ const api = runtime.apis[feature];
1712
+ if (api === void 0 || !(await runtime.features())[feature]) throw new ConsoleFeatureUnavailableError(feature, { remote: runtime.remote });
1713
+ return api;
1714
+ };
1715
+ //#endregion
1716
+ export { createConsoleRuntime, requireFeature };