@naosystem/cf-workers-status-page 0.0.0-stage → 0.1.2

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 (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +38 -2
  3. package/dist/admin.html +17 -0
  4. package/dist/auth-cloudflare-access.js +304 -0
  5. package/dist/auth-cloudflare-access.js.map +1 -0
  6. package/dist/chunks/monitor-B2u42off.js +79 -0
  7. package/dist/chunks/monitor-B2u42off.js.map +1 -0
  8. package/dist/chunks/notifier-DODVuFhr.js +158 -0
  9. package/dist/chunks/notifier-DODVuFhr.js.map +1 -0
  10. package/dist/chunks/page-templates-DPZcMlic.js +71 -0
  11. package/dist/chunks/page-templates-DPZcMlic.js.map +1 -0
  12. package/dist/chunks/run-check-bbo3LqI7.js +235 -0
  13. package/dist/chunks/run-check-bbo3LqI7.js.map +1 -0
  14. package/dist/chunks/timeline-YJXjehRf.js +1081 -0
  15. package/dist/chunks/timeline-YJXjehRf.js.map +1 -0
  16. package/dist/client/_headers +10 -0
  17. package/dist/client/assets/admin-BBJxKTF6.js +1 -0
  18. package/dist/client/assets/admin-Be4X0WFj.css +1 -0
  19. package/dist/client/assets/index-BgOspfsy.js +2 -0
  20. package/dist/client/assets/index-xpKyzvog.css +1 -0
  21. package/dist/client/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  22. package/dist/client/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  23. package/dist/client/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  24. package/dist/client/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  25. package/dist/client/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  26. package/dist/client/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  27. package/dist/client/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  28. package/dist/client/assets/ja-BT5brvxP.js +1 -0
  29. package/dist/client/assets/ja-DSSblLff.js +1 -0
  30. package/dist/client/assets/noto-sans-jp-0-wght-normal-vN5ykBQF.woff2 +0 -0
  31. package/dist/client/assets/noto-sans-jp-1-wght-normal-N_EDDt8j.woff2 +0 -0
  32. package/dist/client/assets/noto-sans-jp-10-wght-normal-ChuiXes4.woff2 +0 -0
  33. package/dist/client/assets/noto-sans-jp-100-wght-normal-CrE4HD6k.woff2 +0 -0
  34. package/dist/client/assets/noto-sans-jp-101-wght-normal-DOqEZFXR.woff2 +0 -0
  35. package/dist/client/assets/noto-sans-jp-102-wght-normal-2gFz4V6e.woff2 +0 -0
  36. package/dist/client/assets/noto-sans-jp-103-wght-normal-D9RhXU-z.woff2 +0 -0
  37. package/dist/client/assets/noto-sans-jp-104-wght-normal-OIyZ9iQD.woff2 +0 -0
  38. package/dist/client/assets/noto-sans-jp-105-wght-normal-CqRQAfnb.woff2 +0 -0
  39. package/dist/client/assets/noto-sans-jp-106-wght-normal-D-PO3jqS.woff2 +0 -0
  40. package/dist/client/assets/noto-sans-jp-107-wght-normal-DrykTIAp.woff2 +0 -0
  41. package/dist/client/assets/noto-sans-jp-108-wght-normal-DijBe27A.woff2 +0 -0
  42. package/dist/client/assets/noto-sans-jp-109-wght-normal-DaJwqT__.woff2 +0 -0
  43. package/dist/client/assets/noto-sans-jp-11-wght-normal-DdkFqF_o.woff2 +0 -0
  44. package/dist/client/assets/noto-sans-jp-110-wght-normal-bhh2FQQH.woff2 +0 -0
  45. package/dist/client/assets/noto-sans-jp-111-wght-normal-CuGzYIdC.woff2 +0 -0
  46. package/dist/client/assets/noto-sans-jp-112-wght-normal-DdhK_1vk.woff2 +0 -0
  47. package/dist/client/assets/noto-sans-jp-113-wght-normal-hxVHS2d4.woff2 +0 -0
  48. package/dist/client/assets/noto-sans-jp-114-wght-normal-DUzjAsrP.woff2 +0 -0
  49. package/dist/client/assets/noto-sans-jp-115-wght-normal-BiZ4-5rz.woff2 +0 -0
  50. package/dist/client/assets/noto-sans-jp-116-wght-normal-DkZAcxAY.woff2 +0 -0
  51. package/dist/client/assets/noto-sans-jp-117-wght-normal-CLJPD2y0.woff2 +0 -0
  52. package/dist/client/assets/noto-sans-jp-118-wght-normal-D8DI_HXJ.woff2 +0 -0
  53. package/dist/client/assets/noto-sans-jp-119-wght-normal-BAB3pFaH.woff2 +0 -0
  54. package/dist/client/assets/noto-sans-jp-12-wght-normal-K36fA5_o.woff2 +0 -0
  55. package/dist/client/assets/noto-sans-jp-13-wght-normal-BnYizWno.woff2 +0 -0
  56. package/dist/client/assets/noto-sans-jp-14-wght-normal-BP4IgVC-.woff2 +0 -0
  57. package/dist/client/assets/noto-sans-jp-15-wght-normal-DyhWcoYF.woff2 +0 -0
  58. package/dist/client/assets/noto-sans-jp-16-wght-normal-CXsQLI2j.woff2 +0 -0
  59. package/dist/client/assets/noto-sans-jp-17-wght-normal-C8FU1ZJ4.woff2 +0 -0
  60. package/dist/client/assets/noto-sans-jp-18-wght-normal-Cl0IKBVh.woff2 +0 -0
  61. package/dist/client/assets/noto-sans-jp-19-wght-normal-D3D3JUJm.woff2 +0 -0
  62. package/dist/client/assets/noto-sans-jp-2-wght-normal-CGu8NhtQ.woff2 +0 -0
  63. package/dist/client/assets/noto-sans-jp-20-wght-normal-DxsoeWSt.woff2 +0 -0
  64. package/dist/client/assets/noto-sans-jp-21-wght-normal-CuNsexW5.woff2 +0 -0
  65. package/dist/client/assets/noto-sans-jp-22-wght-normal-DVX3OFQM.woff2 +0 -0
  66. package/dist/client/assets/noto-sans-jp-23-wght-normal-BPFuo_yH.woff2 +0 -0
  67. package/dist/client/assets/noto-sans-jp-24-wght-normal-D85Fj66x.woff2 +0 -0
  68. package/dist/client/assets/noto-sans-jp-25-wght-normal-DdOOVuSz.woff2 +0 -0
  69. package/dist/client/assets/noto-sans-jp-26-wght-normal-BRB1GnUq.woff2 +0 -0
  70. package/dist/client/assets/noto-sans-jp-27-wght-normal-BxZFF8JU.woff2 +0 -0
  71. package/dist/client/assets/noto-sans-jp-28-wght-normal-VUlviaYI.woff2 +0 -0
  72. package/dist/client/assets/noto-sans-jp-29-wght-normal-CalQqRwB.woff2 +0 -0
  73. package/dist/client/assets/noto-sans-jp-3-wght-normal-cncaCaM8.woff2 +0 -0
  74. package/dist/client/assets/noto-sans-jp-30-wght-normal-CHLg85G9.woff2 +0 -0
  75. package/dist/client/assets/noto-sans-jp-31-wght-normal-BUoF9dl9.woff2 +0 -0
  76. package/dist/client/assets/noto-sans-jp-32-wght-normal-C5ZTiBNw.woff2 +0 -0
  77. package/dist/client/assets/noto-sans-jp-33-wght-normal-C6XNJsfA.woff2 +0 -0
  78. package/dist/client/assets/noto-sans-jp-34-wght-normal-DHkM837w.woff2 +0 -0
  79. package/dist/client/assets/noto-sans-jp-35-wght-normal-QMtEjDIl.woff2 +0 -0
  80. package/dist/client/assets/noto-sans-jp-36-wght-normal-CUyF0GqZ.woff2 +0 -0
  81. package/dist/client/assets/noto-sans-jp-37-wght-normal-EORmNjxA.woff2 +0 -0
  82. package/dist/client/assets/noto-sans-jp-38-wght-normal-C8ERbMNG.woff2 +0 -0
  83. package/dist/client/assets/noto-sans-jp-39-wght-normal-ChUfpJbl.woff2 +0 -0
  84. package/dist/client/assets/noto-sans-jp-4-wght-normal-DtWqs3EP.woff2 +0 -0
  85. package/dist/client/assets/noto-sans-jp-40-wght-normal-MgP8JEEE.woff2 +0 -0
  86. package/dist/client/assets/noto-sans-jp-41-wght-normal-3ctF9abM.woff2 +0 -0
  87. package/dist/client/assets/noto-sans-jp-42-wght-normal-CQtg6UZe.woff2 +0 -0
  88. package/dist/client/assets/noto-sans-jp-43-wght-normal-D1Pmm9aG.woff2 +0 -0
  89. package/dist/client/assets/noto-sans-jp-44-wght-normal-Cp9dHeXI.woff2 +0 -0
  90. package/dist/client/assets/noto-sans-jp-45-wght-normal-D2b1osBj.woff2 +0 -0
  91. package/dist/client/assets/noto-sans-jp-46-wght-normal-CGIA-Vlo.woff2 +0 -0
  92. package/dist/client/assets/noto-sans-jp-47-wght-normal-C4EEGqDS.woff2 +0 -0
  93. package/dist/client/assets/noto-sans-jp-48-wght-normal-D2iBztXa.woff2 +0 -0
  94. package/dist/client/assets/noto-sans-jp-49-wght-normal-DxqRVik_.woff2 +0 -0
  95. package/dist/client/assets/noto-sans-jp-5-wght-normal-CFiyVtll.woff2 +0 -0
  96. package/dist/client/assets/noto-sans-jp-50-wght-normal-CMseszwo.woff2 +0 -0
  97. package/dist/client/assets/noto-sans-jp-51-wght-normal-Cqc-9wfi.woff2 +0 -0
  98. package/dist/client/assets/noto-sans-jp-52-wght-normal-BVLZTbqC.woff2 +0 -0
  99. package/dist/client/assets/noto-sans-jp-53-wght-normal-DTyNOJaY.woff2 +0 -0
  100. package/dist/client/assets/noto-sans-jp-54-wght-normal-_mxGq_et.woff2 +0 -0
  101. package/dist/client/assets/noto-sans-jp-55-wght-normal-Bvndync8.woff2 +0 -0
  102. package/dist/client/assets/noto-sans-jp-56-wght-normal-0MmMqroR.woff2 +0 -0
  103. package/dist/client/assets/noto-sans-jp-57-wght-normal-BdRnjDYs.woff2 +0 -0
  104. package/dist/client/assets/noto-sans-jp-58-wght-normal-BYGgVeN_.woff2 +0 -0
  105. package/dist/client/assets/noto-sans-jp-59-wght-normal-Bdv8mdje.woff2 +0 -0
  106. package/dist/client/assets/noto-sans-jp-6-wght-normal-M-pWkj3J.woff2 +0 -0
  107. package/dist/client/assets/noto-sans-jp-60-wght-normal-DC6FEqsM.woff2 +0 -0
  108. package/dist/client/assets/noto-sans-jp-61-wght-normal-CYIuK5Lr.woff2 +0 -0
  109. package/dist/client/assets/noto-sans-jp-62-wght-normal-DeHy8p7w.woff2 +0 -0
  110. package/dist/client/assets/noto-sans-jp-63-wght-normal-B4M6eMmD.woff2 +0 -0
  111. package/dist/client/assets/noto-sans-jp-64-wght-normal-DLyOXBrC.woff2 +0 -0
  112. package/dist/client/assets/noto-sans-jp-65-wght-normal-X7SsA1bs.woff2 +0 -0
  113. package/dist/client/assets/noto-sans-jp-66-wght-normal-VScDM-_N.woff2 +0 -0
  114. package/dist/client/assets/noto-sans-jp-67-wght-normal-Dg2D3DZB.woff2 +0 -0
  115. package/dist/client/assets/noto-sans-jp-68-wght-normal-BB0AR8UN.woff2 +0 -0
  116. package/dist/client/assets/noto-sans-jp-69-wght-normal-CucwpUnQ.woff2 +0 -0
  117. package/dist/client/assets/noto-sans-jp-7-wght-normal-DzOz8Ryd.woff2 +0 -0
  118. package/dist/client/assets/noto-sans-jp-70-wght-normal-BZId6-Tb.woff2 +0 -0
  119. package/dist/client/assets/noto-sans-jp-71-wght-normal-CzPU0NF7.woff2 +0 -0
  120. package/dist/client/assets/noto-sans-jp-72-wght-normal-DrNRYXnT.woff2 +0 -0
  121. package/dist/client/assets/noto-sans-jp-73-wght-normal-DF2BdR6a.woff2 +0 -0
  122. package/dist/client/assets/noto-sans-jp-74-wght-normal-BMlOw_5y.woff2 +0 -0
  123. package/dist/client/assets/noto-sans-jp-75-wght-normal-DKq84hLG.woff2 +0 -0
  124. package/dist/client/assets/noto-sans-jp-76-wght-normal-CTb-2MFr.woff2 +0 -0
  125. package/dist/client/assets/noto-sans-jp-77-wght-normal-DfIVi-wf.woff2 +0 -0
  126. package/dist/client/assets/noto-sans-jp-78-wght-normal-_-z1Vrir.woff2 +0 -0
  127. package/dist/client/assets/noto-sans-jp-79-wght-normal-D8kGlXda.woff2 +0 -0
  128. package/dist/client/assets/noto-sans-jp-8-wght-normal-BfWoBb3q.woff2 +0 -0
  129. package/dist/client/assets/noto-sans-jp-80-wght-normal-BOEztZwY.woff2 +0 -0
  130. package/dist/client/assets/noto-sans-jp-81-wght-normal-h5VC8QpU.woff2 +0 -0
  131. package/dist/client/assets/noto-sans-jp-82-wght-normal-DJ4QkvX0.woff2 +0 -0
  132. package/dist/client/assets/noto-sans-jp-83-wght-normal-DANtuAZG.woff2 +0 -0
  133. package/dist/client/assets/noto-sans-jp-84-wght-normal-DjZ8Sp6m.woff2 +0 -0
  134. package/dist/client/assets/noto-sans-jp-85-wght-normal-kpU7kbMF.woff2 +0 -0
  135. package/dist/client/assets/noto-sans-jp-86-wght-normal-DRPTa-bf.woff2 +0 -0
  136. package/dist/client/assets/noto-sans-jp-87-wght-normal-CFM472wD.woff2 +0 -0
  137. package/dist/client/assets/noto-sans-jp-88-wght-normal-2rLLwelj.woff2 +0 -0
  138. package/dist/client/assets/noto-sans-jp-89-wght-normal-DUIF9ybW.woff2 +0 -0
  139. package/dist/client/assets/noto-sans-jp-9-wght-normal-WLs1HgG6.woff2 +0 -0
  140. package/dist/client/assets/noto-sans-jp-90-wght-normal-B0n_tL-y.woff2 +0 -0
  141. package/dist/client/assets/noto-sans-jp-91-wght-normal-BishDeFy.woff2 +0 -0
  142. package/dist/client/assets/noto-sans-jp-92-wght-normal-DoIdukLp.woff2 +0 -0
  143. package/dist/client/assets/noto-sans-jp-93-wght-normal-DMCycan_.woff2 +0 -0
  144. package/dist/client/assets/noto-sans-jp-94-wght-normal-DlyoTk-A.woff2 +0 -0
  145. package/dist/client/assets/noto-sans-jp-95-wght-normal-D0L1aiGf.woff2 +0 -0
  146. package/dist/client/assets/noto-sans-jp-96-wght-normal-CjJ0kYkQ.woff2 +0 -0
  147. package/dist/client/assets/noto-sans-jp-97-wght-normal-CJ8uP04H.woff2 +0 -0
  148. package/dist/client/assets/noto-sans-jp-98-wght-normal-CjEDrQIY.woff2 +0 -0
  149. package/dist/client/assets/noto-sans-jp-99-wght-normal-DaQ3GEVf.woff2 +0 -0
  150. package/dist/client/assets/noto-sans-jp-cyrillic-wght-normal-BbS1Q_ZO.woff2 +0 -0
  151. package/dist/client/assets/noto-sans-jp-latin-ext-wght-normal-IaSo_s9d.woff2 +0 -0
  152. package/dist/client/assets/noto-sans-jp-latin-wght-normal-Bnnzbixe.woff2 +0 -0
  153. package/dist/client/assets/noto-sans-jp-vietnamese-wght-normal-CjvP4Ahz.woff2 +0 -0
  154. package/dist/client/assets/src-BDi4qpij.js +9 -0
  155. package/dist/client/assets/src-C6ZFz-Gu.css +1 -0
  156. package/dist/client/assets/views-CSeX_2-u.css +1 -0
  157. package/dist/client/assets/views-DHTTEaNV.js +1 -0
  158. package/dist/client/index.html +15 -0
  159. package/dist/client/licenses/fonts.txt +104 -0
  160. package/dist/client/licenses/third-party.txt +349 -0
  161. package/dist/index.js +18 -0
  162. package/dist/index.js.map +1 -0
  163. package/dist/notifier-discord.js +153 -0
  164. package/dist/notifier-discord.js.map +1 -0
  165. package/dist/notifier-slack.js +98 -0
  166. package/dist/notifier-slack.js.map +1 -0
  167. package/dist/notifier-webhook.js +215 -0
  168. package/dist/notifier-webhook.js.map +1 -0
  169. package/dist/provider-http.js +177 -0
  170. package/dist/provider-http.js.map +1 -0
  171. package/dist/vite.js +224 -0
  172. package/dist/vite.js.map +1 -0
  173. package/dist/worker.js +8616 -0
  174. package/dist/worker.js.map +1 -0
  175. package/package.json +58 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.js","names":["notFound","HISTORY_BATCH","COLUMNS","truncate","notFound","componentIssues","list","create","get","notFound","patch","remove","list","create","get","notFound","patch","remove","list","notFound","__import_glob__0_0_","__import_glob__0_1_","en","notFound","notFound","pages.me","pages.pages","pages.getPageAppearance","pages.putPageAppearance","pages.uploadImage","incidents.list","incidents.create","incidents.get","incidents.patch","incidents.remove","incidents.postUpdate","incidents.resolve","maintenance.list","maintenance.create","maintenance.get","maintenance.patch","maintenance.remove","monitors.list","monitors.purge","notifications.kinds","notifications.list","notifications.create","notifications.get","notifications.patch","notifications.remove","notifications.test","notifications.deliveries","notifications.reEncrypt","notFound"],"sources":["../../../worker/db/schema.ts","../../../worker/notifications/crypto.ts","../../../worker/runners.ts","../../../worker/config.ts","../../../worker/admin/auth.ts","../../../worker/admin/csrf.ts","../../../worker/admin/http.ts","../../../shared/vocabulary.ts","../../../shared/admin-api.ts","../../../worker/db/common.ts","../../../worker/db/incidents.ts","../../../worker/db/appearance.ts","../../../worker/db/maintenance.ts","../../../worker/latency.ts","../../../worker/check-result.ts","../../../worker/notifications/queue.ts","../../../worker/notifications/events.ts","../../../worker/schedule.ts","../../../worker/storage.ts","../../../worker/monitor.ts","../../../worker/uploads.ts","../../../worker/public/views.ts","../../../worker/notifications/unknown.ts","../../../worker/reconciler.ts","../../../worker/status-page.ts","../../../worker/public/incidents.ts","../../../worker/public/routes.ts","../../../worker/public/index.ts","../../../worker/public-cache.ts","../../../worker/admin/context.ts","../../../worker/admin/list-query.ts","../../../worker/admin/incidents.ts","../../../worker/admin/maintenance.ts","../../../worker/admin/monitors.ts","../../../worker/db/notifications.ts","../../../shared/i18n/locales/en.ts","../../../shared/i18n/locales/ja.ts","../../../shared/i18n/core.ts","../../../shared/i18n/index.ts","../../../worker/public-write.ts","../../../worker/notifications/render.ts","../../../worker/notifications/auto-incidents.ts","../../../worker/notifications/limits.ts","../../../worker/notifications/rules.ts","../../../worker/notifications/targets.ts","../../../worker/notifications/consumer.ts","../../../worker/admin/notifications.ts","../../../worker/admin/pages.ts","../../../worker/admin/index.ts","../../../worker/notifications/cron.ts","../../../worker/cloudflare-runner.ts","../../../worker/index.ts"],"sourcesContent":["/**\n * The D1 database: operational data written from the admin UI, and its schema.\n *\n * ## How the schema is applied\n *\n * The Worker applies migrations itself, the first time an isolate uses the database\n * ({@link ensureSchema}). Neither `wrangler deploy` nor the Deploy to Cloudflare button\n * applies D1 migrations, and the documented alternative, running\n * `wrangler d1 migrations apply DB --remote` in the `deploy` script, cannot run before the\n * first deploy: the database is created by that deploy (automatic provisioning). Applying\n * them at run time also covers `npm run dev` and the tests with no extra step.\n *\n * Each migration runs as one `batch()`, which D1 executes as a transaction: the row that\n * records the migration is inserted first, so when two isolates apply the same migration at\n * once, the second one's insert fails on the primary key and its whole batch rolls back. So\n * applying is idempotent and safe to run concurrently.\n *\n * ## Rules for migrations (as for Durable Object storage)\n *\n * Append only, never edit a released one. Additive only, so that the previous version keeps\n * working during a gradual deployment or after a rollback: add tables, indexes and nullable\n * (or defaulted) columns; never rename, drop or change the meaning of what older code reads\n * or writes; always name columns in INSERT and SELECT. No CHECK constraints (SQLite cannot\n * change one without rebuilding the table); values are validated in code.\n *\n * Times are epoch milliseconds (INTEGER), as in the Durable Objects.\n */\n\nexport interface D1Migration {\n\t/** 1, 2, 3, … in order. Never reused. */\n\treadonly version: number;\n\treadonly name: string;\n\t/** Statements run together in one transaction, without bindings. */\n\treadonly statements: readonly string[];\n}\n\nexport const MIGRATIONS_TABLE = \"schema_migrations\";\n\nexport const D1_MIGRATIONS: readonly D1Migration[] = [\n\t{\n\t\tversion: 1,\n\t\tname: \"incidents, maintenance and page appearance\",\n\t\tstatements: [\n\t\t\t// One row per incident. `started_at` is when the incident began, which an\n\t\t\t// administrator may set in the past (never in the future): history and uptime\n\t\t\t// use it, while `created_at` is when it was written. `stage` is the stage of the\n\t\t\t// latest update, kept here so that lists need no join. `components` is a JSON array of\n\t\t\t// { id, impact }: the affected components of the page and their impact, read and\n\t\t\t// written as a whole. `resolved_at` is NULL while the incident is open.\n\t\t\t// `created_by`/`updated_by` are the administrators (NULL for automation);\n\t\t\t// `auto_created` marks incidents published by `incidents.auto`, and `human_edited_at`\n\t\t\t// the last change by an administrator (set at creation by one), which automation must\n\t\t\t// respect (never auto-resolve those). `version` counts changes to what an editor\n\t\t\t// edits (title, components) for optimistic concurrency.\n\t\t\t`CREATE TABLE incidents (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\tpage_id TEXT NOT NULL,\n\t\t\t\ttitle TEXT NOT NULL,\n\t\t\t\tstage TEXT NOT NULL,\n\t\t\t\tcomponents TEXT NOT NULL,\n\t\t\t\tstarted_at INTEGER NOT NULL,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tresolved_at INTEGER,\n\t\t\t\tcreated_by TEXT,\n\t\t\t\tupdated_by TEXT,\n\t\t\t\tauto_created INTEGER NOT NULL DEFAULT 0,\n\t\t\t\thuman_edited_at INTEGER,\n\t\t\t\tversion INTEGER NOT NULL DEFAULT 1\n\t\t\t)`,\n\t\t\t// A page's incidents by start, newest first: the admin list and the public history.\n\t\t\t\"CREATE INDEX incidents_by_page_start ON incidents (page_id, started_at, id)\",\n\t\t\t// A page's open incidents (resolved_at IS NULL): what the public page shows.\n\t\t\t\"CREATE INDEX incidents_by_page_resolved ON incidents (page_id, resolved_at)\",\n\t\t\t// The timeline: each update has a message and the stage it moved the incident to.\n\t\t\t// `author` is NULL and `automated` 1 for updates posted by automation.\n\t\t\t`CREATE TABLE incident_updates (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\tincident_id TEXT NOT NULL REFERENCES incidents (id) ON DELETE CASCADE,\n\t\t\t\tstage TEXT NOT NULL,\n\t\t\t\tbody TEXT NOT NULL,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tauthor TEXT,\n\t\t\t\tautomated INTEGER NOT NULL DEFAULT 0\n\t\t\t)`,\n\t\t\t\"CREATE INDEX incident_updates_by_incident ON incident_updates (incident_id, created_at)\",\n\t\t\t// Scheduled maintenance (shown on top of the state, never a state itself; suppresses notifications). `components` is a JSON array of component IDs.\n\t\t\t`CREATE TABLE maintenances (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\tpage_id TEXT NOT NULL,\n\t\t\t\ttitle TEXT NOT NULL,\n\t\t\t\tbody TEXT NOT NULL,\n\t\t\t\tcomponents TEXT NOT NULL,\n\t\t\t\tstarts_at INTEGER NOT NULL,\n\t\t\t\tends_at INTEGER NOT NULL,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tcreated_by TEXT,\n\t\t\t\tupdated_by TEXT,\n\t\t\t\tversion INTEGER NOT NULL DEFAULT 1\n\t\t\t)`,\n\t\t\t// A page's maintenance by start, latest first: the admin list.\n\t\t\t\"CREATE INDEX maintenances_by_page_start ON maintenances (page_id, starts_at, id)\",\n\t\t\t// A page's current and upcoming maintenance (ends_at > now): the public page.\n\t\t\t\"CREATE INDEX maintenances_by_page_end ON maintenances (page_id, ends_at)\",\n\t\t\t// Per page, what identifies it to visitors, in one language. Every field is\n\t\t\t// optional; a page without a row uses defaults (version 0). New fields are added as\n\t\t\t// nullable columns.\n\t\t\t`CREATE TABLE page_appearance (\n\t\t\t\tpage_id TEXT PRIMARY KEY,\n\t\t\t\ttitle TEXT,\n\t\t\t\tdescription TEXT,\n\t\t\t\tlogo_url TEXT,\n\t\t\t\twebsite_url TEXT,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tupdated_by TEXT,\n\t\t\t\tversion INTEGER NOT NULL DEFAULT 1\n\t\t\t)`,\n\t\t],\n\t},\n\t{\n\t\tversion: 2,\n\t\tname: \"notification targets, deliveries and automation state\",\n\t\tstatements: [\n\t\t\t// Where notifications go, managed in the admin UI. `options` is a JSON object of\n\t\t\t// the kind's options that are not secret, as entered; `secrets` a JSON object of the\n\t\t\t// secret ones, each encrypted (worker/notifications/crypto.ts). `events` is a JSON\n\t\t\t// array of the events it receives; `monitors` (IDs) and `components` ({ pageId,\n\t\t\t// componentId }) are JSON arrays that select monitors unless `all_monitors`. `admin`\n\t\t\t// marks administrators' targets, which also receive `unknown`.\n\t\t\t`CREATE TABLE notification_targets (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\tname TEXT NOT NULL,\n\t\t\t\tkind TEXT NOT NULL,\n\t\t\t\toptions TEXT NOT NULL,\n\t\t\t\tsecrets TEXT NOT NULL,\n\t\t\t\tadmin INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tenabled INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tevents TEXT NOT NULL,\n\t\t\t\tall_monitors INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tmonitors TEXT NOT NULL,\n\t\t\t\tcomponents TEXT NOT NULL,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tcreated_by TEXT,\n\t\t\t\tupdated_by TEXT,\n\t\t\t\tversion INTEGER NOT NULL DEFAULT 1\n\t\t\t)`,\n\t\t\t// One row per notification × target: checked before sending so that a\n\t\t\t// duplicate queue message is dropped, and listed by the admin UI when `failed`.\n\t\t\t// `status`: sending (claimed until `lease_until`), sent, retrying or failed.\n\t\t\t// WITHOUT ROWID: stored in its primary key, so a write is one row, not two.\n\t\t\t`CREATE TABLE notification_deliveries (\n\t\t\t\tnotification_id TEXT NOT NULL,\n\t\t\t\ttarget_id TEXT NOT NULL,\n\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\tevent TEXT NOT NULL,\n\t\t\t\tmonitor_id TEXT,\n\t\t\t\toccurred_at INTEGER NOT NULL,\n\t\t\t\tattempts INTEGER NOT NULL,\n\t\t\t\tlease_until INTEGER,\n\t\t\t\tlast_error TEXT,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tPRIMARY KEY (notification_id, target_id)\n\t\t\t) WITHOUT ROWID`,\n\t\t\t// Failed deliveries, latest first, for the admin UI; old rows by age, for clean-up.\n\t\t\t\"CREATE INDEX notification_deliveries_by_status ON notification_deliveries (status, updated_at)\",\n\t\t\t// Monitors whose `unknown` administrators were notified of: one row while the\n\t\t\t// monitor stays unknown, so that the every-minute Cron notifies once. Kept in D1 so that\n\t\t\t// it works while Durable Objects cannot write.\n\t\t\t`CREATE TABLE unknown_alerts (\n\t\t\t\tmonitor_id TEXT PRIMARY KEY,\n\t\t\t\tsince INTEGER NOT NULL,\n\t\t\t\treason TEXT NOT NULL,\n\t\t\t\tnotified_at INTEGER NOT NULL\n\t\t\t) WITHOUT ROWID`,\n\t\t\t// A monitor's latest confirmed `down` whose notifications maintenance suppressed: the Cron notifies it when the maintenance ends and the monitor is still down.\n\t\t\t// `event` is the event as JSON.\n\t\t\t`CREATE TABLE suppressed_downs (\n\t\t\t\tmonitor_id TEXT PRIMARY KEY,\n\t\t\t\tsince INTEGER NOT NULL,\n\t\t\t\tevent TEXT NOT NULL,\n\t\t\t\tsuppressed_at INTEGER NOT NULL\n\t\t\t) WITHOUT ROWID`,\n\t\t\t// Automatic incidents (`incidents.auto`), per page × monitor: the start of the\n\t\t\t// latest state applied (`last_since`, so that duplicate and older events are ignored),\n\t\t\t// that state, and the incident its `down` was announced in. `claim` is the token of the\n\t\t\t// event that last changed the row: the incident writes of an event take effect only\n\t\t\t// together with its claim (see worker/notifications/auto-incidents.ts).\n\t\t\t`CREATE TABLE auto_incident_monitors (\n\t\t\t\tpage_id TEXT NOT NULL,\n\t\t\t\tmonitor_id TEXT NOT NULL,\n\t\t\t\tlast_since INTEGER NOT NULL,\n\t\t\t\tlast_state TEXT NOT NULL,\n\t\t\t\tincident_id TEXT,\n\t\t\t\tclaim TEXT NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tPRIMARY KEY (page_id, monitor_id)\n\t\t\t) WITHOUT ROWID`,\n\t\t\t\"CREATE INDEX auto_incident_monitors_by_incident ON auto_incident_monitors (incident_id)\",\n\t\t],\n\t},\n\t{\n\t\tversion: 3,\n\t\tname: \"indexes that bound public reads\",\n\t\tstatements: [\n\t\t\t// A page's resolved incidents by start: the public incident list reads exactly one page\n\t\t\t// of rows, however many unresolved incidents sit between them in incidents_by_page_start.\n\t\t\t\"CREATE INDEX incidents_resolved_by_page_start ON incidents (page_id, started_at, id) WHERE resolved_at IS NOT NULL\",\n\t\t\t// A page's incidents by last change: the history reads only what changed since its last\n\t\t\t// read (worker/status-page.ts), not every incident of its 90 days, every 5 minutes.\n\t\t\t\"CREATE INDEX incidents_by_page_updated ON incidents (page_id, updated_at)\",\n\t\t],\n\t},\n\t{\n\t\tversion: 4,\n\t\tname: \"uploaded images and colours of a page\",\n\t\tstatements: [\n\t\t\t// The IDs of the page's uploaded logo and favicon (random, with the extension), whose bytes are\n\t\t\t// in R2 (`UPLOADS`, worker/uploads.ts). NULL: none.\n\t\t\t\"ALTER TABLE page_appearance ADD COLUMN logo_image TEXT\",\n\t\t\t\"ALTER TABLE page_appearance ADD COLUMN favicon_image TEXT\",\n\t\t\t// The page's colours as JSON ({ light, dark }, each { background, header, accent } of\n\t\t\t// \"#rrggbb\" or null; shared/admin-api.ts). NULL: the template's throughout.\n\t\t\t\"ALTER TABLE page_appearance ADD COLUMN colors TEXT\",\n\t\t],\n\t},\n];\n\nasync function appliedVersion(db: D1Database): Promise<number> {\n\tconst row = await db.prepare(`SELECT max(version) AS version FROM ${MIGRATIONS_TABLE}`).first<{ version: number | null }>();\n\treturn row?.version ?? 0;\n}\n\n/**\n * Applies the migrations that `db` lacks, in order. Idempotent and safe to run from several\n * isolates at once (see the module documentation). When the database is newer than this code\n * (after a rollback), logs a warning and changes nothing. Returns the versions it applied.\n * @throws Error if `migrations` is not numbered 1, 2, 3, …, or a migration fails.\n */\nexport async function migrateD1(db: D1Database, migrations: readonly D1Migration[] = D1_MIGRATIONS): Promise<number[]> {\n\tmigrations.forEach((migration, index) => {\n\t\tif (migration.version !== index + 1) {\n\t\t\tthrow new Error(`D1 migration ${index} has version ${migration.version}; expected ${index + 1}`);\n\t\t}\n\t});\n\tawait db\n\t\t.prepare(\n\t\t\t`CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (\n\t\t\t\tversion INTEGER PRIMARY KEY,\n\t\t\t\tname TEXT NOT NULL,\n\t\t\t\tapplied_at INTEGER NOT NULL\n\t\t\t)`,\n\t\t)\n\t\t.run();\n\tconst current = await appliedVersion(db);\n\tif (current > migrations.length) {\n\t\tconsole.warn(\n\t\t\t`D1 schema version ${current} is newer than this code knows (${migrations.length}), ` +\n\t\t\t\t\"probably after a rollback. Continuing: migrations are additive.\",\n\t\t);\n\t\treturn [];\n\t}\n\tconst applied: number[] = [];\n\tfor (const migration of migrations.slice(current)) {\n\t\ttry {\n\t\t\tawait db.batch([\n\t\t\t\tdb\n\t\t\t\t\t.prepare(`INSERT INTO ${MIGRATIONS_TABLE} (version, name, applied_at) VALUES (?, ?, ?)`)\n\t\t\t\t\t.bind(migration.version, migration.name, Date.now()),\n\t\t\t\t...migration.statements.map((statement) => db.prepare(statement)),\n\t\t\t]);\n\t\t\tapplied.push(migration.version);\n\t\t\tconsole.log(`Applied D1 migration ${migration.version}: ${migration.name}`);\n\t\t} catch (error) {\n\t\t\t// Another isolate applied it first: our batch was rolled back as a whole.\n\t\t\tif ((await appliedVersion(db)) >= migration.version) continue;\n\t\t\tthrow error;\n\t\t}\n\t}\n\treturn applied;\n}\n\nlet schemaReady = false;\n\n/**\n * Resolves once the database has this code's schema. Runs {@link migrateD1} until it has\n * succeeded once in this isolate (two statements and a row or two read when there is\n * nothing to apply). Requests that arrive together each run it, rather than await one\n * in-flight promise: Workers tie I/O to the request that started it. That is safe (see\n * above). Call it\n * before any query, from every place that uses D1 (the admin API now, the public API and\n * notifications later).\n */\nexport async function ensureSchema(db: D1Database): Promise<void> {\n\tif (schemaReady) return;\n\tawait migrateD1(db);\n\tschemaReady = true;\n}\n\n/** Forgets that the schema was applied; for tests that wipe the database. */\nexport function forgetSchema(): void {\n\tschemaReady = false;\n}\n","/**\n * Encryption of notification targets' secret options in D1, with AES-256-GCM\n * (WebCrypto) and keys held in a Worker secret.\n *\n * ## The key secret\n *\n * `NOTIFICATION_KEYS` holds one or more keys, separated by commas, each `<id>:<key>`: the ID is\n * 1-32 letters, digits, `-` or `_`, and the key is 32 random bytes in base64. The first key is\n * the current one: it encrypts every value written. The others only decrypt. Create one with\n *\n * ```sh\n * echo \"k1:$(openssl rand -base64 32)\" | npx wrangler secret put NOTIFICATION_KEYS\n * ```\n *\n * Without the secret (or with a malformed one) secret options can be neither stored nor\n * read: the admin API refuses to save them (503 `encryption_key_missing`), and deliveries to\n * targets with secrets fail until it is set.\n *\n * ## Rotating the key\n *\n * 1. Generate a new key and put it first, keeping the old one after it:\n * `NOTIFICATION_KEYS=k2:<new>,k1:<old>` (`wrangler secret put` deploys it at once).\n * 2. `POST /api/admin/notifications/re-encrypt`: every target's secrets are decrypted and\n * encrypted again with `k2` (also done for a target whenever it is saved).\n * 3. Once that reports no `failed` targets, remove the old key: `NOTIFICATION_KEYS=k2:<new>`.\n *\n * Losing every key means entering the targets' secrets again.\n *\n * ## Format\n *\n * A value is stored as `<format>.<key id>.<iv>.<ciphertext>`, with a random 96-bit IV and\n * base64url parts. The key ID says which key decrypts it. The target's ID and the option's name\n * are authenticated as additional data, so a value copied to another target or option does not\n * decrypt. Format `v2` also authenticates the origin of the target's destination (its `url`,\n * see `destinationOption` in @naosystem/cf-workers-status-page-core): a secret header or signing secret then decrypts\n * only while the target still sends to that origin, so no edit can redirect it elsewhere.\n * `v1` values, written before, are bound to no destination; saving the target or\n * `POST /api/admin/notifications/re-encrypt` binds them.\n */\n\n/** The Worker secret with the keys. */\nexport const KEYS_SECRET = \"NOTIFICATION_KEYS\";\n\n/** Bound to the target and option only (the destination itself, kinds without one, and values written before v2). */\nconst FORMAT = \"v1\";\n/** Also bound to the origin of the target's destination. */\nconst BOUND_FORMAT = \"v2\";\nconst KEY_ID = /^[A-Za-z0-9_-]{1,32}$/;\nconst KEY_BYTES = 32;\nconst IV_BYTES = 12;\n\n/** The key secret is not set, or is malformed. The message never contains key material. */\nexport class EncryptionKeyError extends Error {\n\toverride readonly name = \"EncryptionKeyError\";\n}\n\n/** A stored value cannot be decrypted (unknown key, damaged, or moved to another target or option). */\nexport class DecryptionError extends Error {\n\toverride readonly name = \"DecryptionError\";\n}\n\nexport interface KeyRing {\n\treadonly currentId: string;\n\treadonly keys: ReadonlyMap<string, CryptoKey>;\n}\n\nfunction decodeBase64(value: string): Uint8Array {\n\tconst normalized = value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n\tconst binary = atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, \"=\"));\n\treturn Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n\nfunction encodeBase64Url(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const byte of bytes) binary += String.fromCharCode(byte);\n\treturn btoa(binary).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/, \"\");\n}\n\n/** Parses the secret's value. @throws EncryptionKeyError naming what is wrong, never the key. */\nexport async function parseKeyRing(value: unknown): Promise<KeyRing> {\n\tif (typeof value !== \"string\" || value.trim() === \"\") {\n\t\tthrow new EncryptionKeyError(\n\t\t\t`The ${KEYS_SECRET} secret is not set: set it to encrypt notification targets' secrets (see the README)`,\n\t\t);\n\t}\n\tconst keys = new Map<string, CryptoKey>();\n\tlet currentId: string | undefined;\n\tfor (const [index, entry] of value.split(\",\").entries()) {\n\t\tconst separator = entry.indexOf(\":\");\n\t\tconst id = entry.slice(0, separator).trim();\n\t\tconst material = entry.slice(separator + 1).trim();\n\t\tif (separator === -1 || !KEY_ID.test(id)) {\n\t\t\tthrow new EncryptionKeyError(`${KEYS_SECRET}: entry ${index + 1} must be \"<id>:<base64 key>\", with an ID of letters, digits, \"-\" or \"_\"`);\n\t\t}\n\t\tif (keys.has(id)) throw new EncryptionKeyError(`${KEYS_SECRET}: key ID \"${id}\" is listed twice`);\n\t\tlet bytes: Uint8Array;\n\t\ttry {\n\t\t\tbytes = decodeBase64(material);\n\t\t} catch {\n\t\t\tthrow new EncryptionKeyError(`${KEYS_SECRET}: key \"${id}\" is not base64`);\n\t\t}\n\t\tif (bytes.length !== KEY_BYTES) {\n\t\t\tthrow new EncryptionKeyError(`${KEYS_SECRET}: key \"${id}\" must be ${KEY_BYTES} bytes (openssl rand -base64 32)`);\n\t\t}\n\t\tkeys.set(id, await crypto.subtle.importKey(\"raw\", bytes, \"AES-GCM\", false, [\"encrypt\", \"decrypt\"]));\n\t\tcurrentId ??= id;\n\t}\n\tif (currentId === undefined) throw new EncryptionKeyError(`${KEYS_SECRET} has no key`);\n\treturn { currentId, keys };\n}\n\nlet cached: { readonly value: string; readonly ring: Promise<KeyRing> } | undefined;\n\n/** The key ring from `env`, parsed once per value of the secret in this isolate. */\nexport function keyRing(env: Env): Promise<KeyRing> {\n\tconst value = (env as unknown as Record<string, unknown>)[KEYS_SECRET];\n\tif (typeof value !== \"string\") return parseKeyRing(value);\n\tif (cached?.value !== value) cached = { value, ring: parseKeyRing(value) };\n\treturn cached.ring;\n}\n\n/**\n * Additional authenticated data: binds a value to its target and option and, with a\n * `destination` (an origin), to that too.\n *\n * Changing it makes every saved value impossible to decrypt: the targets' secrets would have to\n * be entered again.\n */\nfunction additionalData(targetId: string, option: string, destination: string | undefined): Uint8Array {\n\treturn new TextEncoder().encode(\n\t\tdestination === undefined\n\t\t\t? `cf-workers-status-page/notification-target/${targetId}/${option}`\n\t\t\t: `cf-workers-status-page/notification-target/v2/${JSON.stringify([targetId, option, destination])}`,\n\t);\n}\n\n/**\n * Encrypts `plaintext` with the current key, bound to `destination` (the origin the target\n * sends to) when one is given.\n */\nexport async function encryptSecret(\n\tring: KeyRing,\n\ttargetId: string,\n\toption: string,\n\tplaintext: string,\n\tdestination?: string,\n): Promise<string> {\n\tconst key = ring.keys.get(ring.currentId) as CryptoKey;\n\tconst iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n\tconst ciphertext = await crypto.subtle.encrypt(\n\t\t{ name: \"AES-GCM\", iv, additionalData: additionalData(targetId, option, destination) },\n\t\tkey,\n\t\tnew TextEncoder().encode(plaintext),\n\t);\n\tconst format = destination === undefined ? FORMAT : BOUND_FORMAT;\n\treturn [format, ring.currentId, encodeBase64Url(iv), encodeBase64Url(new Uint8Array(ciphertext))].join(\".\");\n}\n\n/** The ID of the key that encrypted `stored`, if it is in a known format. */\nexport function storedKeyId(stored: string): string | undefined {\n\tconst [format, id] = stored.split(\".\");\n\treturn format === FORMAT || format === BOUND_FORMAT ? id : undefined;\n}\n\n/** Whether `stored` is bound to a destination origin (format v2). */\nexport function isBoundToDestination(stored: string): boolean {\n\treturn stored.startsWith(`${BOUND_FORMAT}.`);\n}\n\n/**\n * Decrypts a value made by {@link encryptSecret}. A value bound to a destination decrypts only\n * with that same `destination`. @throws DecryptionError\n */\nexport async function decryptSecret(\n\tring: KeyRing,\n\ttargetId: string,\n\toption: string,\n\tstored: string,\n\tdestination?: string,\n): Promise<string> {\n\tconst parts = stored.split(\".\");\n\tif (parts.length !== 4 || (parts[0] !== FORMAT && parts[0] !== BOUND_FORMAT)) {\n\t\tthrow new DecryptionError(`The stored value of \"${option}\" is damaged`);\n\t}\n\tconst bound = parts[0] === BOUND_FORMAT;\n\tif (bound && destination === undefined) {\n\t\tthrow new DecryptionError(`\"${option}\" is bound to the target's destination, which could not be read`);\n\t}\n\tconst [, id, iv, ciphertext] = parts as [string, string, string, string];\n\tconst key = ring.keys.get(id);\n\tif (key === undefined) {\n\t\tthrow new DecryptionError(`\"${option}\" was encrypted with key \"${id}\", which is not in ${KEYS_SECRET}; enter it again`);\n\t}\n\ttry {\n\t\tconst plaintext = await crypto.subtle.decrypt(\n\t\t\t{ name: \"AES-GCM\", iv: decodeBase64(iv), additionalData: additionalData(targetId, option, bound ? destination : undefined) },\n\t\t\tkey,\n\t\t\tdecodeBase64(ciphertext),\n\t\t);\n\t\treturn new TextDecoder().decode(plaintext);\n\t} catch {\n\t\tthrow new DecryptionError(\n\t\t\tbound\n\t\t\t\t? `The stored value of \"${option}\" does not decrypt with key \"${id}\" for the target's destination; enter it again`\n\t\t\t\t: `The stored value of \"${option}\" does not decrypt with key \"${id}\"`,\n\t\t);\n\t}\n}\n","import type { RunnerDeclaration } from \"@naosystem/cf-workers-status-page-core\";\n\n/**\n * The built-in runner: `CloudflareRunner` (worker/cloudflare-runner.ts), a\n * `WorkerEntrypoint` in this Worker that Monitor DOs call through `ctx.exports`. Its\n * implementation must provide every capability declared here, because the configuration is\n * validated against this declaration.\n *\n * `maxTimeoutMs` keeps a check, plus the grace periods below, well inside the 15-minute\n * wall-clock limit of the Durable Object alarm that runs it.\n */\nexport const CLOUDFLARE_RUNNER = {\n\tid: \"cloudflare\",\n\tcapabilities: [\"fetch\"],\n\tmaxTimeoutMs: 5 * 60_000,\n} as const satisfies RunnerDeclaration;\n\n/** Runners available to this hub. The first one checks every monitor for now. */\nexport const RUNNERS: readonly RunnerDeclaration[] = [CLOUDFLARE_RUNNER];\n\n/**\n * Sent with every request the built-in runner makes, unless the monitor sets its own\n * `User-Agent` header. Follows the usual convention for monitoring bots so that firewalls\n * can recognise and allow it.\n */\nexport const USER_AGENT = \"Mozilla/5.0 (compatible; cf-workers-status-page; +https://github.com/naosystem-jp/cf-workers-status-page)\";\n\n/**\n * How the timeouts combine, from the inside out:\n *\n * 1. The monitor's `timeout` bounds the check itself. `runCheck` aborts the provider when it\n * passes and records `down` (\"No response within …\"): the target was too slow.\n * 2. The runner gives up `RUNNER_GRACE_MS` later, in case something other than the provider\n * hangs (for example, resolving secrets). That produces no result (an error, not `down`):\n * the runner, not the target, failed.\n * 3. The Monitor DO stops waiting for the runner `RUNNER_GRACE_MS` after that, in case the\n * call to the runner itself is lost. That is also recorded as an error without a state.\n *\n * The monitor's timeout is validated against `CLOUDFLARE_RUNNER.maxTimeoutMs` when the\n * configuration loads, so no layer silently shortens it.\n */\nexport const RUNNER_GRACE_MS = 5_000;\n","import {\n\ttype LocationHint,\n\ttype ResolvedMonitor,\n\ttype ResolvedPage,\n\tresolveConfig,\n} from \"@naosystem/cf-workers-status-page-core\";\nimport userConfig from \"../status.config\";\nimport { KEYS_SECRET } from \"./notifications/crypto\";\nimport { RUNNERS } from \"./runners\";\n\n/** The Worker's own secrets: no `secret()` in status.config.ts may name them (they would leave the Worker). */\nexport const RESERVED_SECRETS: readonly string[] = [KEYS_SECRET];\n\n/**\n * The validated configuration. Resolved when the Worker module loads, so an invalid\n * status.config.ts fails `wrangler deploy`, `npm run dev` and the tests.\n */\nexport const config = resolveConfig(userConfig, { runners: RUNNERS, reservedSecrets: RESERVED_SECRETS });\n\nconst monitorsById: ReadonlyMap<string, ResolvedMonitor> = new Map(\n\tconfig.monitors.map((monitor) => [monitor.id, monitor]),\n);\n\n/** The configured monitor with this ID, if any. */\nexport function findMonitor(id: string): ResolvedMonitor | undefined {\n\treturn monitorsById.get(id);\n}\n\nconst pagesById: ReadonlyMap<string, ResolvedPage> = new Map(config.pages.map((page) => [page.id, page]));\n\n/** The page with this ID in status.config.ts, if any. */\nexport function findPage(id: string): ResolvedPage | undefined {\n\treturn pagesById.get(id);\n}\n\n/** The monitors a page shows through its components, each once, in the order the components list them. */\nexport function pageMonitors(page: ResolvedPage): ResolvedMonitor[] {\n\tconst ids = new Set(page.components.flatMap((component) => component.monitors));\n\treturn [...ids].flatMap((id) => {\n\t\tconst monitor = monitorsById.get(id);\n\t\treturn monitor === undefined ? [] : [monitor];\n\t});\n}\n\n// Core keeps its own copy of the Durable Object location hints so that it does not\n// depend on Cloudflare runtime types. Fail type-checking when the two lists diverge\n// (for example after `npm run cf-typegen` picks up a new hint).\ntype Equals<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;\ntrue satisfies Equals<LocationHint, DurableObjectLocationHint>;\n","/**\n * Who may use the admin UI and the admin API.\n *\n * Every admin request is authenticated here, before its path is looked at, by the `auth`\n * provider of status.config.ts. Without one, every admin request is rejected: a\n * missing setting must not leave the admin API open.\n *\n * ## Local-development bypass\n *\n * For working on the admin UI without Cloudflare Access, `npm run dev` can let requests\n * through as the administrator `local-dev`. It applies only when both hold:\n *\n * 1. It was compiled in: `__ADMIN_DEV_BYPASS__` is `true` only under Vite's dev server, and\n * only when the developer opted in with `ADMIN_DEV_BYPASS=1` (in `.env.development.local`\n * or the shell). vite.admin.ts decides it from Vite's command, so every build (`vite\n * build`, which every deploy runs) compiles the constant `false`, whatever the mode,\n * `NODE_ENV` or variables. A Worker bundled without Vite has no such constant: `false`.\n * 2. The request's host name is a loopback name (`localhost`, `127.x.x.x`, `[::1]`), taken\n * from the URL the runtime received, not from a header. Under the dev server, Vite also\n * rejects host names it does not allow.\n *\n * No request header can switch it on. Caveat: started with `vite --host`, the dev server is\n * reachable from the network, and a client there can send `Host: localhost`; do not opt in\n * while exposing the dev server.\n *\n * ## Host names\n *\n * With `adminHosts` in status.config.ts, a request for any other host name (from the URL the\n * runtime received) is rejected like a failed sign-in, before the provider sees it. That keeps\n * the admin out of reach on a `*.workers.dev` URL that Cloudflare Access does not protect,\n * where a leaked or revoked Access token would otherwise still be accepted until it expires.\n */\nimport type { AdminIdentity, AuthProvider } from \"@naosystem/cf-workers-status-page-core\";\nimport { config } from \"../config\";\n\n/** Whether the bypass is compiled in (see the module documentation). Always `false` in a build. */\nexport const DEV_BYPASS_ENABLED: boolean = typeof __ADMIN_DEV_BYPASS__ === \"boolean\" && __ADMIN_DEV_BYPASS__;\n\n/** The administrator the bypass signs in as. */\nexport const DEV_IDENTITY: AdminIdentity = { id: \"local-dev\" };\n\nfunction isLoopback(hostname: string): boolean {\n\treturn hostname === \"localhost\" || hostname === \"[::1]\" || /^127(?:\\.\\d{1,3}){3}$/.test(hostname);\n}\n\n/** Whether the local-development bypass lets `request` through, when it is `enabled`. */\nexport function devBypassApplies(request: Request, enabled: boolean): boolean {\n\t// The URL the runtime received the request for, not a Host or Forwarded header.\n\treturn enabled && isLoopback(new URL(request.url).hostname);\n}\n\nexport interface AdminAuthOptions {\n\t/** The configured provider; `undefined` rejects every request. */\n\treadonly auth: AuthProvider | undefined;\n\t/** Whether the local-development bypass is compiled in. */\n\treadonly devBypass: boolean;\n\t/** Hosts (`URL.host`, lowercase) the admin answers on; `null` or omitted for any (`adminHosts`). */\n\treadonly hosts?: readonly string[] | null;\n}\n\nexport const ADMIN_AUTH: AdminAuthOptions = { auth: config.auth, devBypass: DEV_BYPASS_ENABLED, hosts: config.adminHosts };\n\n/** Whether `request` is for a host the admin answers on (see the module documentation). */\nexport function adminHostAllowed(request: Request, hosts: readonly string[] | null | undefined): boolean {\n\treturn hosts === null || hosts === undefined || hosts.includes(new URL(request.url).host.toLowerCase());\n}\n\nlet warnedNoAuth = false;\nlet warnedBypass = false;\nlet warnedHost = false;\n\n/**\n * The administrator making `request`, or `null` to reject it. Never throws: a provider that\n * throws rejects the request.\n */\nexport async function authenticateAdmin(\n\trequest: Request,\n\tenv: Env,\n\tctx: ExecutionContext,\n\toptions: AdminAuthOptions = ADMIN_AUTH,\n): Promise<AdminIdentity | null> {\n\tif (devBypassApplies(request, options.devBypass)) {\n\t\tif (!warnedBypass) {\n\t\t\twarnedBypass = true;\n\t\t\tconsole.warn(\"Admin authentication is bypassed for local development (ADMIN_DEV_BYPASS=1).\");\n\t\t}\n\t\treturn DEV_IDENTITY;\n\t}\n\tif (!adminHostAllowed(request, options.hosts)) {\n\t\tif (!warnedHost) {\n\t\t\twarnedHost = true;\n\t\t\tconsole.warn(\"Admin request rejected: its host name is not in `adminHosts` of status.config.ts.\");\n\t\t}\n\t\treturn null;\n\t}\n\tif (options.auth === undefined) {\n\t\tif (!warnedNoAuth) {\n\t\t\twarnedNoAuth = true;\n\t\t\tconsole.warn(\"Admin request rejected: status.config.ts has no `auth`, so the admin UI and admin API are closed.\");\n\t\t}\n\t\treturn null;\n\t}\n\ttry {\n\t\treturn await options.auth.authenticate(request, {\n\t\t\tenv: env as unknown as Readonly<Record<string, unknown>>,\n\t\t\t// Called as a method of the context, the global fetch would lose its `this`.\n\t\t\tfetch: (input, init) => fetch(input, init),\n\t\t\twaitUntil: (promise) => ctx.waitUntil(promise),\n\t\t});\n\t} catch (error) {\n\t\tconsole.error(`Admin authentication failed (${options.auth.type})`, error);\n\t\treturn null;\n\t}\n}\n\n/** How an administrator is recorded as author: the email address, else the identity's ID. */\nexport function authorName(identity: AdminIdentity): string {\n\treturn identity.email ?? identity.id;\n}\n","/**\n * Cross-site request forgery protection for the admin API.\n *\n * Cloudflare Access keeps the session in the `CF_Authorization` cookie, whose SameSite\n * attribute is the Access administrator's choice and defaults to `None`, so browsers send it\n * with requests from other sites, and Access lets them through. The Worker therefore rejects\n * cross-site requests itself:\n *\n * - `Sec-Fetch-Site` (sent by current browsers) must be `same-origin`, or `none` (typed in\n * the address bar) for reads;\n * - `Origin`, when present, must be the Worker's own origin;\n * - requests with a body must be `Content-Type: application/json`, which an HTML form cannot\n * send and a cross-origin `fetch` cannot send without a CORS preflight, which this API\n * never approves (it sends no CORS headers). See {@link isJsonRequest}.\n *\n * Requests with neither header come from outside a browser (curl, an Access service token)\n * and are allowed: browsers send at least one of them on every cross-site request that\n * could change something.\n */\n\nconst SAFE_METHODS: ReadonlySet<string> = new Set([\"GET\", \"HEAD\"]);\n\n/** Why `request` looks cross-site, or `null` when it does not. */\nexport function crossSiteReason(request: Request): string | null {\n\tconst safe = SAFE_METHODS.has(request.method);\n\tconst site = request.headers.get(\"Sec-Fetch-Site\");\n\tif (site !== null && site !== \"same-origin\" && !(safe && site === \"none\")) return `Sec-Fetch-Site is ${site}`;\n\tconst origin = request.headers.get(\"Origin\");\n\tif (origin !== null && origin !== new URL(request.url).origin) return \"Origin is another site\";\n\treturn null;\n}\n\n/** Whether the request declares a JSON body (`application/json`, with or without parameters). */\nexport function isJsonRequest(request: Request): boolean {\n\tconst type = request.headers.get(\"Content-Type\");\n\treturn type !== null && type.split(\";\")[0]?.trim().toLowerCase() === \"application/json\";\n}\n","/** JSON responses, errors and request parsing for the admin API. */\nimport * as z from \"zod\";\nimport type { ApiError, ApiIssue, EditConflict } from \"../../shared/admin-api\";\nimport { isJsonRequest } from \"./csrf\";\n\n/** Largest request body accepted. Incident texts are limited well below this (shared/admin-api.ts). */\nexport const MAX_BODY_BYTES = 64 * 1024;\n\n/** On every admin API response: never cached, never sniffed. */\nconst API_HEADERS = {\n\t\"Cache-Control\": \"no-store\",\n\t\"X-Content-Type-Options\": \"nosniff\",\n} as const;\n\nexport function json(body: unknown, status = 200): Response {\n\treturn Response.json(body, { status, headers: API_HEADERS });\n}\n\nexport function noContent(): Response {\n\treturn new Response(null, { status: 204, headers: API_HEADERS });\n}\n\nexport function apiError(\n\tstatus: number,\n\terror: string,\n\tmessage: string,\n\toptions: { readonly issues?: readonly ApiIssue[]; readonly reason?: string | undefined; readonly headers?: Record<string, string> } = {},\n): Response {\n\tconst body: ApiError = {\n\t\terror,\n\t\tmessage,\n\t\t...(options.issues === undefined ? {} : { issues: options.issues }),\n\t\t...(options.reason === undefined ? {} : { reason: options.reason }),\n\t};\n\treturn Response.json(body, { status, headers: { ...API_HEADERS, ...options.headers } });\n}\n\n/**\n * The one response to every admin request that fails authentication, whatever its method\n * and path, so that it reveals nothing about what exists.\n */\nexport function forbidden(): Response {\n\treturn apiError(403, \"forbidden\", \"Sign in as an administrator to use the admin API\");\n}\n\nexport function notFound(what = \"resource\"): Response {\n\treturn apiError(404, \"not_found\", `No such ${what}`);\n}\n\n/** 409 for an edit that started from an older version, with the current state. */\nexport function editConflict<T>(current: T): Response {\n\tconst body: EditConflict<T> = {\n\t\terror: \"edit_conflict\",\n\t\tmessage: \"Someone else saved a change after you started editing. Nothing was saved: review the current version and make your change again.\",\n\t\tcurrent,\n\t};\n\treturn Response.json(body, { status: 409, headers: API_HEADERS });\n}\n\nexport function validationFailed(issues: readonly ApiIssue[]): Response {\n\treturn apiError(400, \"validation_failed\", \"The request is invalid\", { issues });\n}\n\nconst ENGLISH = z.locales.en();\n\n/** Values a client can put in a message. */\nfunction scalars(values: Readonly<Record<string, unknown>>): Record<string, string | number> {\n\treturn Object.fromEntries(\n\t\tObject.entries(values).flatMap(([name, value]) =>\n\t\t\ttypeof value === \"string\" || typeof value === \"number\" ? [[name, value]] : typeof value === \"bigint\" ? [[name, Number(value)]] : [],\n\t\t),\n\t);\n}\n\n/**\n * A code for a client to say a Zod issue in its own language ({@link ApiIssue}): Zod's code and\n * values for its own checks, the API's for its refinements (`params.code`). None when a schema\n * wrote its own message (a notifier kind's check, say), which then stands as written.\n */\nexport function issueCode(issue: z.core.$ZodIssue): Pick<ApiIssue, \"code\" | \"params\"> {\n\tif (issue.code === \"custom\") {\n\t\tconst params = issue.params ?? {};\n\t\treturn typeof params[\"code\"] === \"string\" ? { code: params[\"code\"], params: scalars(params) } : {};\n\t}\n\tconst generic = ENGLISH.localeError(issue as Parameters<typeof ENGLISH.localeError>[0]);\n\tif ((typeof generic === \"string\" ? generic : generic?.message) !== issue.message) return {};\n\tswitch (issue.code) {\n\t\tcase \"too_small\":\n\t\t\treturn { code: issue.code, params: { origin: String(issue.origin), minimum: Number(issue.minimum) } };\n\t\tcase \"too_big\":\n\t\t\treturn { code: issue.code, params: { origin: String(issue.origin), maximum: Number(issue.maximum) } };\n\t\tcase \"invalid_format\":\n\t\t\treturn { code: issue.code, params: { format: issue.format } };\n\t\tcase \"invalid_value\":\n\t\t\treturn { code: issue.code, params: { values: issue.values.map(String).join(\", \") } };\n\t\tcase \"invalid_type\":\n\t\t\treturn { code: issue.code, params: { expected: issue.expected } };\n\t\tcase \"unrecognized_keys\":\n\t\t\treturn { code: issue.code, params: { keys: issue.keys.join(\", \") } };\n\t\tdefault:\n\t\t\treturn { code: issue.code };\n\t}\n}\n\n/** Zod issues as JSON-friendly {@link ApiIssue}s, with codes for clients to translate. */\nexport function toIssues(error: z.ZodError): ApiIssue[] {\n\treturn error.issues.map((issue) => ({\n\t\tpath: issue.path.map((segment) => (typeof segment === \"number\" ? segment : String(segment))),\n\t\tmessage: issue.message,\n\t\t...issueCode(issue),\n\t}));\n}\n\nexport type Parsed<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly response: Response };\n\n/**\n * Reads the body, stopping as soon as it exceeds `limit` bytes, so that a request without\n * (or with a false) Content-Length is never buffered beyond the limit. `null` when too large.\n */\nexport async function readCapped(request: Request, limit: number): Promise<Uint8Array | null> {\n\tif (Number(request.headers.get(\"Content-Length\") ?? \"0\") > limit) return null;\n\tif (request.body === null) return new Uint8Array();\n\tconst reader = request.body.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet size = 0;\n\tfor (;;) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\tsize += value.byteLength;\n\t\tif (size > limit) {\n\t\t\tawait reader.cancel();\n\t\t\treturn null;\n\t\t}\n\t\tchunks.push(value);\n\t}\n\tconst bytes = new Uint8Array(size);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbytes.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\treturn bytes;\n}\n\n/**\n * Reads a JSON body and validates it with `schema`: 415 without a JSON content type, 413\n * when too large, 400 when it is not JSON or not valid.\n */\nexport async function readBody<T>(request: Request, schema: z.ZodType<T>): Promise<Parsed<T>> {\n\tif (!isJsonRequest(request)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tresponse: apiError(415, \"unsupported_media_type\", \"Send the request body as Content-Type: application/json\"),\n\t\t};\n\t}\n\tconst bytes = await readCapped(request, MAX_BODY_BYTES);\n\tif (bytes === null) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tresponse: apiError(413, \"payload_too_large\", `The request body must be at most ${MAX_BODY_BYTES} bytes`),\n\t\t};\n\t}\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(new TextDecoder().decode(bytes));\n\t} catch {\n\t\treturn { ok: false, response: apiError(400, \"invalid_json\", \"The request body is not valid JSON\") };\n\t}\n\treturn validate(schema, value);\n}\n\n/** Validates `value` with `schema`; 400 with the Zod issues when it is invalid. */\nexport function validate<T>(schema: z.ZodType<T>, value: unknown, base: readonly (string | number)[] = []): Parsed<T> {\n\tconst result = schema.safeParse(value);\n\tif (result.success) return { ok: true, value: result.data };\n\treturn {\n\t\tok: false,\n\t\tresponse: validationFailed(toIssues(result.error).map((issue) => ({ ...issue, path: [...base, ...issue.path] }))),\n\t};\n}\n","/**\n * The admin API's vocabulary and limits, without Zod: shared/admin-api.ts builds its schemas\n * from these and re-exports them, and the admin UI imports them from here so that its bundle\n * does not carry the schemas (the Worker validates every request).\n */\nimport type { NotificationEvent } from \"@naosystem/cf-workers-status-page-core\";\n\nexport { NOTIFICATION_EVENTS, type NotificationEvent } from \"@naosystem/cf-workers-status-page-core\";\n\n/** 調査中 → 原因特定 → 経過観察 → 解決. Any order is allowed; `resolved` closes the incident. */\nexport const INCIDENT_STAGES = [\"investigating\", \"identified\", \"monitoring\", \"resolved\"] as const;\nexport type IncidentStage = (typeof INCIDENT_STAGES)[number];\n\n/**\n * Impact of an incident on a component. While the incident is open, the page shows the\n * worse of this and the component's monitored state. `none` lists the component as\n * affected without changing its state, for example while monitoring a fix.\n */\nexport const IMPACTS = [\"none\", \"degraded\", \"down\"] as const;\nexport type Impact = (typeof IMPACTS)[number];\n\nexport const LIMITS = {\n\ttitle: 200,\n\tbody: 20_000,\n\tcomponents: 100,\n\tappearanceTitle: 100,\n\tappearanceDescription: 1_000,\n\turl: 2_000,\n\t/** Largest page size of a list. */\n\tpageSize: 100,\n\ttargetName: 100,\n\ttargetMonitors: 500,\n\ttargetComponents: 500,\n\t/** Largest image an administrator can upload (a logo or a favicon), in bytes. */\n\timageBytes: 512 * 1024,\n} as const;\n\n/**\n * Images an administrator can upload, by media type, and the extension each is stored with.\n * Raster formats only: an SVG can carry scripts, and the images are served from the status\n * page's own origin. Two names for ICO, as browsers report either.\n */\nexport const IMAGE_TYPES = {\n\t\"image/png\": \"png\",\n\t\"image/jpeg\": \"jpg\",\n\t\"image/gif\": \"gif\",\n\t\"image/webp\": \"webp\",\n\t\"image/x-icon\": \"ico\",\n\t\"image/vnd.microsoft.icon\": \"ico\",\n} as const;\nexport type ImageExtension = (typeof IMAGE_TYPES)[keyof typeof IMAGE_TYPES];\n\n/** The media type an image is served with, by its extension. */\nexport const IMAGE_CONTENT_TYPES: Readonly<Record<ImageExtension, string>> = {\n\tpng: \"image/png\",\n\tjpg: \"image/jpeg\",\n\tgif: \"image/gif\",\n\twebp: \"image/webp\",\n\tico: \"image/x-icon\",\n};\n\n/**\n * An uploaded image's ID: 128 random bits (hex) and its extension. A new one for every upload,\n * even of the same file, so that an ID is never reused: what it serves never changes, and an\n * image that is being deleted can never be uploaded again under its ID (worker/uploads.ts).\n */\nexport const IMAGE_ID = /^[0-9a-f]{32}\\.(?:png|jpg|gif|webp|ico)$/;\n\n/** Where an uploaded image is served: the public API's image route (worker/public/routes.ts). */\nexport function imagePath(pageId: string, imageId: string): string {\n\treturn `/api/pages/${encodeURIComponent(pageId)}/images/${imageId}`;\n}\n\n/** Light and dark: each colour of a page is set for both, or left to the template's. */\nexport const COLOR_SCHEMES = [\"light\", \"dark\"] as const;\nexport type ColorScheme = (typeof COLOR_SCHEMES)[number];\n\n/**\n * The colours of a page an administrator can set: the page's background, the header bar (the\n * modern template; its text turns dark on a light colour), and links and focus outlines.\n */\nexport const COLOR_ROLES = [\"background\", \"header\", \"accent\"] as const;\nexport type ColorRole = (typeof COLOR_ROLES)[number];\n\n/** A colour as `#rrggbb`, lower case. */\nexport const HEX_COLOR = /^#[0-9a-f]{6}$/;\n\n/** One colour scheme's colours (`#rrggbb`); `null` for the template's. */\nexport type ThemeColors = { readonly [Role in ColorRole]: string | null };\n\n/** A page's colours, per colour scheme. */\nexport type AppearanceColors = { readonly [Scheme in ColorScheme]: ThemeColors };\n\n/** The template's colours throughout: what a page has until an administrator sets one. */\nexport const NO_COLORS: AppearanceColors = {\n\tlight: { background: null, header: null, accent: null },\n\tdark: { background: null, header: null, accent: null },\n};\n\n/** How far in the future an incident's `startedAt` may be, for clocks that run a little fast. It is then stored as now. */\nexport const START_TIME_TOLERANCE_MS = 60_000;\n\n/** Events a target receives when it does not say: `down` and recovery; administrators' targets also `unknown`. */\nexport const DEFAULT_TARGET_EVENTS: readonly NotificationEvent[] = [\"down\", \"recovered\"];\n","/**\n * Request schemas and response types of the admin API (`/api/admin/*`), shared by the\n * Worker and the admin UI. The UI can validate forms with the same Zod schemas before\n * sending; the Worker validates again, and also checks what only it knows (that pages and\n * components exist in status.config.ts).\n *\n * Conventions:\n * - Times are epoch milliseconds (integers), as everywhere else in the hub.\n * - Objects are strict: unknown keys are rejected, so a misspelt field is an error.\n * - Text is trimmed.\n * - Edits are optimistic: an incident, a maintenance and a page's\n * appearance have a `version`, which an edit sends back as it was when the editor started.\n * When someone else saved in between, the edit is refused with 409 `edit_conflict` and the\n * current state ({@link EditConflict}). Posting a timeline update never conflicts.\n */\nimport type { CheckState, LocationHint, PageTemplate, SchedulePeriod, StateRecord } from \"@naosystem/cf-workers-status-page-core\";\nimport * as z from \"zod\";\nimport {\n\ttype AppearanceColors,\n\ttype ColorRole,\n\ttype ColorScheme,\n\tHEX_COLOR,\n\tIMAGE_ID,\n\tIMPACTS,\n\tINCIDENT_STAGES,\n\ttype IncidentStage,\n\tLIMITS,\n\tNOTIFICATION_EVENTS,\n\ttype NotificationEvent,\n} from \"./vocabulary\";\n\n// The vocabulary and limits live in a module without Zod, for the admin UI (see vocabulary.ts).\nexport {\n\ttype AppearanceColors,\n\tCOLOR_ROLES,\n\tCOLOR_SCHEMES,\n\ttype ColorRole,\n\ttype ColorScheme,\n\tDEFAULT_TARGET_EVENTS,\n\tHEX_COLOR,\n\tIMAGE_CONTENT_TYPES,\n\tIMAGE_ID,\n\tIMAGE_TYPES,\n\ttype ImageExtension,\n\timagePath,\n\tIMPACTS,\n\ttype Impact,\n\tINCIDENT_STAGES,\n\ttype IncidentStage,\n\tLIMITS,\n\tNO_COLORS,\n\tNOTIFICATION_EVENTS,\n\ttype NotificationEvent,\n\tSTART_TIME_TOLERANCE_MS,\n\ttype ThemeColors,\n} from \"./vocabulary\";\n\n// ---------------------------------------------------------------------------\n// Request bodies\n// ---------------------------------------------------------------------------\n\n/** Epoch milliseconds, within the range of `Date`. */\nexport const timestampSchema = z.int().min(0).max(8_640_000_000_000_000);\n\n/** A refinement's message, with a code the admin UI translates (see {@link ApiIssue}). */\nconst NOTHING_TO_CHANGE = { message: \"Nothing to change\", params: { code: \"nothing_to_change\" } };\n\n/** The `version` an edit started from (see the module documentation). */\nconst versionSchema = z.int().min(0);\n\nconst idSchema = z.string().min(1).max(64);\nconst titleSchema = z.string().trim().min(1).max(LIMITS.title);\nconst bodySchema = z.string().trim().min(1).max(LIMITS.body);\n\nfunction uniqueBy<T>(key: (item: T) => string) {\n\treturn (items: readonly T[], ctx: z.core.$RefinementCtx<T[]>) => {\n\t\tconst seen = new Set<string>();\n\t\titems.forEach((item, index) => {\n\t\t\tconst value = key(item);\n\t\t\tif (seen.has(value)) {\n\t\t\t\tctx.addIssue({ code: \"custom\", message: `\"${value}\" is listed twice`, path: [index], params: { code: \"duplicate\", value } });\n\t\t\t}\n\t\t\tseen.add(value);\n\t\t});\n\t};\n}\n\nexport const affectedComponentSchema = z.strictObject({\n\t/** A component ID of the incident's page. */\n\tid: idSchema,\n\timpact: z.enum(IMPACTS),\n});\nexport type AffectedComponent = z.infer<typeof affectedComponentSchema>;\n\nconst affectedComponentsSchema = z\n\t.array(affectedComponentSchema)\n\t.max(LIMITS.components)\n\t.superRefine(uniqueBy((component: AffectedComponent) => component.id));\n\nexport const createIncidentSchema = z.strictObject({\n\tpageId: idSchema,\n\ttitle: titleSchema,\n\t/**\n\t * When the incident began, if earlier than now: the outage started at 10:00 and the\n\t * incident is written at 10:20. Not in the future. Default: now.\n\t */\n\tstartedAt: timestampSchema.optional(),\n\t/** Stage of the first update. */\n\tstage: z.enum(INCIDENT_STAGES).default(\"investigating\"),\n\t/** Message of the first update. */\n\tbody: bodySchema,\n\tcomponents: affectedComponentsSchema.default([]),\n});\nexport type CreateIncident = z.input<typeof createIncidentSchema>;\n\n/** Changes the incident itself. The stage changes only by posting an update. */\nexport const patchIncidentSchema = z\n\t.strictObject({\n\t\t/** The incident's `version` when the editor started. */\n\t\tversion: versionSchema,\n\t\ttitle: titleSchema.optional(),\n\t\t/** Replaces the affected components. */\n\t\tcomponents: affectedComponentsSchema.optional(),\n\t})\n\t.refine((value) => value.title !== undefined || value.components !== undefined, NOTHING_TO_CHANGE);\nexport type PatchIncident = z.input<typeof patchIncidentSchema>;\n\n/**\n * A timeline entry. Posting a stage other than `resolved` to a resolved incident reopens it.\n * Never conflicts, unless it sends `version`; with `components`, it counts as a change to them\n * (the `version` goes up).\n */\nexport const postIncidentUpdateSchema = z.strictObject({\n\tstage: z.enum(INCIDENT_STAGES),\n\tbody: bodySchema,\n\t/** Also replaces the affected components, in the same change. */\n\tcomponents: affectedComponentsSchema.optional(),\n\t/**\n\t * Optional, with `components`: the incident's `version` the components were read at. When\n\t * someone changed the incident since, nothing is posted (409 `edit_conflict`), so that an\n\t * update cannot silently undo their change of the components.\n\t */\n\tversion: versionSchema.optional(),\n});\nexport type PostIncidentUpdate = z.input<typeof postIncidentUpdateSchema>;\n\n/** Shorthand for posting a `resolved` update. */\nexport const resolveIncidentSchema = z.strictObject({ body: bodySchema });\nexport type ResolveIncident = z.input<typeof resolveIncidentSchema>;\n\nconst maintenanceComponentsSchema = z\n\t.array(idSchema)\n\t.min(1)\n\t.max(LIMITS.components)\n\t.superRefine(uniqueBy((id: string) => id));\n\nconst maintenanceFields = {\n\ttitle: titleSchema,\n\tbody: z.string().trim().max(LIMITS.body),\n\tstartsAt: timestampSchema,\n\tendsAt: timestampSchema,\n\t/** Component IDs of the page under maintenance. */\n\tcomponents: maintenanceComponentsSchema,\n};\n\nfunction endsAfterStart(value: { startsAt?: number | undefined; endsAt?: number | undefined }, ctx: z.core.$RefinementCtx) {\n\tif (value.startsAt !== undefined && value.endsAt !== undefined && value.endsAt <= value.startsAt) {\n\t\tctx.addIssue({ code: \"custom\", message: \"Must be later than startsAt\", path: [\"endsAt\"], params: { code: \"ends_before_start\" } });\n\t}\n}\n\nexport const createMaintenanceSchema = z\n\t.strictObject({\n\t\tpageId: idSchema,\n\t\t...maintenanceFields,\n\t\tbody: maintenanceFields.body.default(\"\"),\n\t})\n\t.superRefine(endsAfterStart);\nexport type CreateMaintenance = z.input<typeof createMaintenanceSchema>;\n\n/** Changes some fields. The merged result must still end after it starts. */\nexport const patchMaintenanceSchema = z\n\t.strictObject({\n\t\t/** The maintenance's `version` when the editor started. */\n\t\tversion: versionSchema,\n\t\ttitle: maintenanceFields.title.optional(),\n\t\tbody: maintenanceFields.body.optional(),\n\t\tstartsAt: maintenanceFields.startsAt.optional(),\n\t\tendsAt: maintenanceFields.endsAt.optional(),\n\t\tcomponents: maintenanceFields.components.optional(),\n\t})\n\t.refine(\n\t\t(value) => Object.entries(value).some(([key, field]) => key !== \"version\" && field !== undefined),\n\t\tNOTHING_TO_CHANGE,\n\t)\n\t.superRefine(endsAfterStart);\nexport type PatchMaintenance = z.input<typeof patchMaintenanceSchema>;\n\nconst httpUrlSchema = z.httpUrl().max(LIMITS.url);\n/**\n * An image the public page loads from another site: https only, so that it is never mixed\n * content and the page's Content-Security-Policy can allow https images only.\n */\nconst httpsUrlSchema = httpUrlSchema.refine((value) => value.startsWith(\"https://\"), {\n\tmessage: \"must be an https URL\",\n\tparams: { code: \"https_required\" },\n});\n\n/** An image uploaded with `POST /api/admin/pages/:pageId/images` ({@link UploadedImage}`.id`). */\nconst imageIdSchema = z.string().regex(IMAGE_ID);\n\n/** `#rrggbb`, in either case; stored in lower case. */\nconst hexColorSchema = z\n\t.string()\n\t.trim()\n\t.toLowerCase()\n\t.refine((value) => HEX_COLOR.test(value), { message: \"must be a colour as #rrggbb\", params: { code: \"hex_color\" } });\n\n/** One colour scheme's colours; `null` keeps the template's. */\nconst themeColorsSchema = z.strictObject({\n\tbackground: hexColorSchema.nullable(),\n\theader: hexColorSchema.nullable(),\n\taccent: hexColorSchema.nullable(),\n} satisfies Record<ColorRole, unknown>);\n\n/** The page's colours in light and in dark mode, each set separately (see `COLOR_ROLES`). */\nexport const appearanceColorsSchema = z.strictObject({\n\tlight: themeColorsSchema,\n\tdark: themeColorsSchema,\n} satisfies Record<ColorScheme, unknown>);\n\n/**\n * Replaces the page's appearance. `null` falls back to the default. The fields added after the\n * first four (`logoImage`, `faviconImage`, `colors`) may be left out: they then keep their\n * current values, so that clients written before them keep working.\n */\nexport const pageAppearanceSchema = z.strictObject({\n\t/** The appearance's `version` when the editor started; `0` while the page uses the defaults. */\n\tversion: versionSchema,\n\t/** Heading and document title. Default: the page ID. */\n\ttitle: z.string().trim().min(1).max(LIMITS.appearanceTitle).nullable(),\n\t/** A line under the heading. */\n\tdescription: z.string().trim().min(1).max(LIMITS.appearanceDescription).nullable(),\n\t/** Image shown instead of the title text (https). An uploaded `logoImage` takes its place. */\n\tlogoUrl: httpsUrlSchema.nullable(),\n\t/** Where the heading links to, such as the organisation's website (http or https). */\n\twebsiteUrl: httpUrlSchema.nullable(),\n\t/** An uploaded image shown instead of the title text, before `logoUrl`. */\n\tlogoImage: imageIdSchema.nullable().optional(),\n\t/** An uploaded image for the browser tab and bookmarks. */\n\tfaviconImage: imageIdSchema.nullable().optional(),\n\t/** `null` for the template's colours throughout. */\n\tcolors: appearanceColorsSchema.nullable().optional(),\n});\nexport type PageAppearanceInput = z.input<typeof pageAppearanceSchema>;\nexport type AppearanceColorsInput = z.input<typeof appearanceColorsSchema>;\n\n// ---------------------------------------------------------------------------\n// Notification targets\n// ---------------------------------------------------------------------------\n\n/** A component of a page, as a target's selection names it. */\nexport const componentRefSchema = z.strictObject({ pageId: idSchema, componentId: idSchema });\nexport type ComponentRef = z.infer<typeof componentRefSchema>;\n\nconst targetNameSchema = z.string().trim().min(1).max(LIMITS.targetName);\nconst targetEventsSchema = z\n\t.array(z.enum(NOTIFICATION_EVENTS))\n\t.max(NOTIFICATION_EVENTS.length)\n\t.superRefine(uniqueBy((event: string) => event));\nconst targetMonitorsSchema = z\n\t.array(idSchema)\n\t.max(LIMITS.targetMonitors)\n\t.superRefine(uniqueBy((id: string) => id));\nconst targetComponentsSchema = z\n\t.array(componentRefSchema)\n\t.max(LIMITS.targetComponents)\n\t.superRefine(uniqueBy((ref: ComponentRef) => `${ref.pageId}/${ref.componentId}`));\n/**\n * A target's options as an object, validated by the Worker against the kind's schema (see\n * `GET /api/admin/notifications/kinds`). Secret options may be sent but are never returned.\n */\nconst targetOptionsSchema = z.record(z.string(), z.unknown());\n\nfunction unknownNeedsAdmin(value: { admin?: boolean | undefined; events?: readonly string[] | undefined }, ctx: z.core.$RefinementCtx) {\n\tif (value.admin === false && value.events?.includes(\"unknown\")) {\n\t\tctx.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: \"Only administrators' targets receive unknown\",\n\t\t\tpath: [\"events\"],\n\t\t\tparams: { code: \"unknown_needs_admin\" },\n\t\t});\n\t}\n}\n\n/**\n * A new target. Which monitors it covers: every monitor with `allMonitors` (the default),\n * otherwise those listed in `monitors` and those shown by the listed `components`.\n */\nexport const createNotificationTargetSchema = z\n\t.strictObject({\n\t\tname: targetNameSchema,\n\t\t/** A notifier kind registered in status.config.ts, such as `slack`. Cannot change later. */\n\t\tkind: idSchema,\n\t\toptions: targetOptionsSchema,\n\t\t/** An administrators' target: it receives `unknown` and links to the admin UI. */\n\t\tadmin: z.boolean().default(false),\n\t\tenabled: z.boolean().default(true),\n\t\t/** Default: {@link DEFAULT_TARGET_EVENTS}, plus `unknown` for an administrators' target. */\n\t\tevents: targetEventsSchema.optional(),\n\t\tallMonitors: z.boolean().default(true),\n\t\tmonitors: targetMonitorsSchema.default([]),\n\t\tcomponents: targetComponentsSchema.default([]),\n\t})\n\t.superRefine(unknownNeedsAdmin);\nexport type CreateNotificationTarget = z.input<typeof createNotificationTargetSchema>;\n\n/**\n * Changes a target. `options` holds only the options to change: others, secret ones included,\n * keep their value; `null` removes an optional one. The kind never changes.\n */\nexport const patchNotificationTargetSchema = z\n\t.strictObject({\n\t\t/** The target's `version` when the editor started. */\n\t\tversion: versionSchema,\n\t\tname: targetNameSchema.optional(),\n\t\toptions: targetOptionsSchema.optional(),\n\t\tadmin: z.boolean().optional(),\n\t\tenabled: z.boolean().optional(),\n\t\tevents: targetEventsSchema.optional(),\n\t\tallMonitors: z.boolean().optional(),\n\t\tmonitors: targetMonitorsSchema.optional(),\n\t\tcomponents: targetComponentsSchema.optional(),\n\t})\n\t.refine(\n\t\t(value) => Object.entries(value).some(([key, field]) => key !== \"version\" && field !== undefined),\n\t\tNOTHING_TO_CHANGE,\n\t);\nexport type PatchNotificationTarget = z.input<typeof patchNotificationTargetSchema>;\n\n// ---------------------------------------------------------------------------\n// Responses\n// ---------------------------------------------------------------------------\n\nexport interface IncidentUpdate {\n\treadonly id: string;\n\treadonly stage: IncidentStage;\n\treadonly body: string;\n\treadonly createdAt: number;\n\t/** Who posted it; `null` for automation. */\n\treadonly author: string | null;\n\treadonly automated: boolean;\n}\n\nexport interface Incident {\n\treadonly id: string;\n\treadonly pageId: string;\n\treadonly title: string;\n\t/** Stage of the latest update. */\n\treadonly stage: IncidentStage;\n\treadonly components: readonly AffectedComponent[];\n\t/** When the incident began: history and uptime use this. At or before `createdAt`. */\n\treadonly startedAt: number;\n\t/** When it was written. */\n\treadonly createdAt: number;\n\treadonly updatedAt: number;\n\t/** `null` while open. */\n\treadonly resolvedAt: number | null;\n\t/** Who created it; `null` when automation did (`incidents.auto`). */\n\treadonly createdBy: string | null;\n\treadonly updatedBy: string | null;\n\treadonly autoCreated: boolean;\n\t/** Last change by an administrator. Automation never resolves an incident with one. */\n\treadonly humanEditedAt: number | null;\n\t/** Send it back with an edit (see the module documentation). */\n\treadonly version: number;\n}\n\nexport interface IncidentWithUpdates extends Incident {\n\t/** Oldest first. */\n\treadonly updates: readonly IncidentUpdate[];\n}\n\nexport interface Maintenance {\n\treadonly id: string;\n\treadonly pageId: string;\n\treadonly title: string;\n\treadonly body: string;\n\treadonly components: readonly string[];\n\treadonly startsAt: number;\n\treadonly endsAt: number;\n\treadonly createdAt: number;\n\treadonly updatedAt: number;\n\treadonly createdBy: string | null;\n\treadonly updatedBy: string | null;\n\t/** Send it back with an edit. */\n\treadonly version: number;\n}\n\nexport interface PageAppearance {\n\treadonly pageId: string;\n\treadonly title: string | null;\n\treadonly description: string | null;\n\treadonly logoUrl: string | null;\n\treadonly websiteUrl: string | null;\n\t/** The uploaded logo's ID, or `null`; shown instead of `logoUrl`. */\n\treadonly logoImage: string | null;\n\t/** The uploaded favicon's ID, or `null`. */\n\treadonly faviconImage: string | null;\n\t/** Every scheme and role, `null` where the template's colour applies. */\n\treadonly colors: AppearanceColors;\n\t/** `null` while the page uses the defaults. */\n\treadonly updatedAt: number | null;\n\treadonly updatedBy: string | null;\n\t/** Send it back with an edit; `0` while the page uses the defaults. */\n\treadonly version: number;\n}\n\n/** A page of a list, latest first. Pass `nextCursor` as `cursor` for the next page. */\nexport interface ListPage<T> {\n\treadonly items: readonly T[];\n\treadonly nextCursor: string | null;\n}\n\n/** A validation problem, located like Zod locates it, for showing next to a form field. */\nexport interface ApiIssue {\n\treadonly path: readonly (string | number)[];\n\t/** In English. */\n\treadonly message: string;\n\t/**\n\t * What the problem is, for a client to say in its own language (with `params`): Zod's codes\n\t * for its own checks (`too_small`, `too_big`, `invalid_format`, `invalid_value`,\n\t * `invalid_type`, `unrecognized_keys`), and the API's (`duplicate`, `nothing_to_change`,\n\t * `ends_before_start`, `start_in_future`, `unknown_needs_admin`, `unknown_page`, `page_removed`,\n\t * `unknown_component`, `unknown_monitor`, `unknown_kind`, `kind_removed`). Absent when the\n\t * message is particular (a notifier kind's own check, say): show the message.\n\t */\n\treadonly code?: string;\n\treadonly params?: Readonly<Record<string, string | number>>;\n}\n\n/** The body of every error response. */\nexport interface ApiError {\n\t/** Machine-readable, such as `validation_failed` or `not_found`. */\n\treadonly error: string;\n\t/** In English. */\n\treadonly message: string;\n\treadonly issues?: readonly ApiIssue[];\n\t/**\n\t * Why, for some errors, machine-readable: for `purge_refused`, `configured` (the monitor is in\n\t * status.config.ts), `running` (it still runs) or `deploying` (a deploy is in progress).\n\t */\n\treadonly reason?: string;\n}\n\n/** 409 `edit_conflict`: someone else saved first. `current` is what they saved. */\nexport interface EditConflict<T> extends ApiError {\n\treadonly error: \"edit_conflict\";\n\treadonly current: T;\n}\n\n/** A notifier kind registered in status.config.ts, for the admin UI's target form. */\nexport interface NotifierKindInfo {\n\treadonly type: string;\n\treadonly name: string;\n\t/** Options that are encrypted and never returned. Also marked `writeOnly` in `optionsSchema`. */\n\treadonly secretOptions: readonly string[];\n\t/** The options as JSON Schema (draft 2020-12), for what an administrator enters. */\n\treadonly optionsSchema: Record<string, unknown>;\n\t/**\n\t * Texts for the form by language (`{}` when the kind has none): `\"$kind\"` its name,\n\t * `\"<option>.title\"` and `\"<option>.description\"` (see `NotifierKind.messages` in core).\n\t */\n\treadonly messages: Readonly<Record<string, Readonly<Record<string, string>>>>;\n}\n\nexport interface NotifierKindsResponse {\n\treadonly kinds: readonly NotifierKindInfo[];\n\t/**\n\t * Whether the encryption key for secret options is set (the `NOTIFICATION_KEYS` Worker\n\t * secret), and the ID of the key that encrypts new values. Without it, targets with secret\n\t * options cannot be saved.\n\t */\n\treadonly encryption: { readonly configured: boolean; readonly currentKeyId: string | null; readonly error: string | null };\n}\n\nexport interface NotificationTarget {\n\treadonly id: string;\n\treadonly name: string;\n\treadonly kind: string;\n\t/** Options that are not secret. */\n\treadonly options: Readonly<Record<string, unknown>>;\n\t/** For each secret option of the kind, whether it has a value. Values are never returned. */\n\treadonly secrets: Readonly<Record<string, boolean>>;\n\treadonly admin: boolean;\n\treadonly enabled: boolean;\n\treadonly events: readonly NotificationEvent[];\n\treadonly allMonitors: boolean;\n\treadonly monitors: readonly string[];\n\treadonly components: readonly ComponentRef[];\n\treadonly createdAt: number;\n\treadonly updatedAt: number;\n\treadonly createdBy: string | null;\n\treadonly updatedBy: string | null;\n\t/** Send it back with an edit. */\n\treadonly version: number;\n}\n\n/** Status of a notification to one target: being sent, sent, waiting for a retry, or given up. */\nexport type DeliveryStatus = \"sending\" | \"sent\" | \"retrying\" | \"failed\";\n\n/** One notification to one target: the admin UI lists those that failed. */\nexport interface NotificationDelivery {\n\treadonly notificationId: string;\n\treadonly targetId: string;\n\t/** `null` when the target was deleted since. */\n\treadonly targetName: string | null;\n\treadonly event: NotificationEvent;\n\treadonly monitorId: string | null;\n\t/** When the event happened. */\n\treadonly occurredAt: number;\n\treadonly status: DeliveryStatus;\n\treadonly attempts: number;\n\t/** The last error, with secret options removed. */\n\treadonly lastError: string | null;\n\treadonly createdAt: number;\n\treadonly updatedAt: number;\n}\n\n/** The outcome of `POST /api/admin/notifications/targets/:id/test`. */\nexport interface TestNotificationResult {\n\treadonly ok: boolean;\n\t/** Why it failed, with secret options removed. */\n\treadonly error: string | null;\n}\n\n/** The outcome of `POST /api/admin/notifications/re-encrypt`. */\nexport interface ReEncryptResult {\n\t/** The key every secret option is now encrypted with. */\n\treadonly currentKeyId: string;\n\treadonly reEncrypted: number;\n\treadonly unchanged: number;\n\t/** Targets whose secrets could not be decrypted (their key is no longer in `NOTIFICATION_KEYS`). */\n\treadonly failed: readonly { readonly id: string; readonly name: string; readonly error: string }[];\n}\n\n/** `GET /api/admin/me`: the signed-in administrator. */\nexport interface AdminMe {\n\treadonly identity: { readonly id: string; readonly email?: string };\n\t/** How changes are attributed (`createdBy`, `updatedBy`). */\n\treadonly author: string | null;\n}\n\n/** A component of a page in status.config.ts. */\nexport interface AdminComponent {\n\treadonly id: string;\n\treadonly name: string;\n\t/** IDs of the monitors that set its state; empty for a component that only incidents set. */\n\treadonly monitors: readonly string[];\n}\n\n/** A page in status.config.ts, for the admin UI's forms. */\nexport interface AdminPage {\n\treadonly id: string;\n\t/** How the page is shown (status.config.ts): the admin UI previews its colours in it. */\n\treadonly template: PageTemplate;\n\treadonly incidents: {\n\t\treadonly auto: boolean;\n\t\treadonly templates: Readonly<Record<string, string | undefined>>;\n\t\t/** `incidents.reopenWithin`: how long after automation resolved an incident a new `down` reopens it; 0 for never. */\n\t\treadonly reopenWithinMs: number;\n\t};\n\treadonly components: readonly AdminComponent[];\n}\n\n/** `GET /api/admin/pages` */\nexport interface AdminPagesResponse {\n\treadonly pages: readonly AdminPage[];\n\t/** Whether images can be uploaded: the Worker has its R2 bucket (`UPLOADS`). */\n\treadonly uploads: boolean;\n}\n\n/** `POST /api/admin/pages/:pageId/images`: an image stored for the page, to name in its appearance. */\nexport interface UploadedImage {\n\t/** Random, and new for every upload (uploading the same file again gives another ID), with the extension. */\n\treadonly id: string;\n\t/** Where the public page loads it from (a path on this site). */\n\treadonly url: string;\n\treadonly contentType: string;\n\treadonly size: number;\n}\n\n/** A monitor's latest check of any outcome. */\nexport interface AdminLastCheck {\n\treadonly at: number;\n\treadonly runner: string;\n\t/** `null` when the check produced no result (a missing secret, a runner failure). */\n\treadonly state: CheckState | null;\n\treadonly latencyMs: number | null;\n\treadonly message: string | null;\n}\n\n/** What a monitor's Durable Object reports about itself (worker/monitor.ts `MonitorSnapshot`). */\nexport interface AdminMonitorSnapshot {\n\treadonly monitorId: string;\n\treadonly configured: boolean;\n\treadonly startedAt: number | null;\n\treadonly period: SchedulePeriod | null;\n\t/** The latest state record: the confirmed state, `unconfirmed`, or `stopped`. */\n\treadonly current: StateRecord | null;\n\treadonly recentSince: number | null;\n\treadonly lastCheck: AdminLastCheck | null;\n\treadonly lastResultAt: number | null;\n}\n\n/** A monitor as `GET /api/admin/monitors` lists it: configured, or removed with its data kept. */\nexport interface AdminMonitor {\n\treadonly id: string;\n\t/** Whether this version's status.config.ts has it. */\n\treadonly configured: boolean;\n\t/** Its settings in status.config.ts; `null` when it is not configured. */\n\treadonly config: {\n\t\treadonly name: string;\n\t\treadonly type: string;\n\t\treadonly intervalMs: number;\n\t\treadonly timeoutMs: number;\n\t\treadonly location: LocationHint | null;\n\t} | null;\n\t/** Components that show it, per page. */\n\treadonly components: readonly ComponentRef[];\n\t/** The registry's entry; `null` until the monitor first started. A `removed` monitor's data stays until purged. */\n\treadonly registry: {\n\t\treadonly id: string;\n\t\treadonly status: \"active\" | \"removed\";\n\t\treadonly location: LocationHint | null;\n\t\treadonly firstSeenAt: number;\n\t\treadonly statusChangedAt: number;\n\t} | null;\n\t/** Its current state from its Durable Object; `null` when that could not be read (see `snapshotError`). */\n\treadonly snapshot: AdminMonitorSnapshot | null;\n\treadonly snapshotError: string | null;\n}\n\n/** `GET /api/admin/monitors` */\nexport interface AdminMonitorsResponse {\n\treadonly monitors: readonly AdminMonitor[];\n}\n","/** Helpers shared by the D1 data modules. */\n\n/**\n * Who makes a change: an administrator (recorded by name), or automation such as\n * `incidents.auto`, recorded as `NULL`.\n */\nexport type Actor = { readonly kind: \"admin\"; readonly name: string } | { readonly kind: \"automation\" };\n\n/** The name stored for `actor`: `NULL` for automation. */\nexport function actorName(actor: Actor): string | null {\n\treturn actor.kind === \"admin\" ? actor.name : null;\n}\n\n/** The outcome of an edit made from a `version` (optimistic concurrency). */\nexport type EditResult<T> =\n\t| { readonly status: \"updated\"; readonly value: T }\n\t| { readonly status: \"not-found\" }\n\t/** Someone else changed it since that version: nothing was written. */\n\t| { readonly status: \"conflict\"; readonly current: T };\n\n/** A position in a list ordered by (time, id), latest first. */\nexport interface Cursor {\n\treadonly at: number;\n\treadonly id: string;\n}\n\nconst CURSOR = /^(\\d{1,16}):([A-Za-z0-9-]{1,64})$/;\n\nexport function encodeCursor(cursor: Cursor): string {\n\treturn `${cursor.at}:${cursor.id}`;\n}\n\n/** `undefined` when `value` is not a cursor this module made. */\nexport function decodeCursor(value: string): Cursor | undefined {\n\tconst match = CURSOR.exec(value);\n\tif (match === null) return undefined;\n\treturn { at: Number(match[1]), id: match[2] as string };\n}\n\n/**\n * Splits `limit + 1` rows into a page and the cursor for the next one (the caller asks for\n * one row more than it shows, to know whether there is a next page).\n */\nexport function toPage<Row, Item>(\n\trows: readonly Row[],\n\tlimit: number,\n\ttoItem: (row: Row) => Item,\n\tcursorOf: (row: Row) => Cursor,\n): { items: Item[]; nextCursor: string | null } {\n\tconst shown = rows.slice(0, limit);\n\tconst last = shown.at(-1);\n\treturn {\n\t\titems: shown.map(toItem),\n\t\tnextCursor: rows.length > limit && last !== undefined ? encodeCursor(cursorOf(last)) : null,\n\t};\n}\n\n/** Parses a JSON column written by this code; logs and falls back if it is damaged. */\nexport function parseJsonColumn<T>(value: string, fallback: T, where: string): T {\n\ttry {\n\t\treturn JSON.parse(value) as T;\n\t} catch {\n\t\tconsole.warn(`Damaged JSON in ${where}; using ${JSON.stringify(fallback)}`);\n\t\treturn fallback;\n\t}\n}\n","/**\n * Incidents in D1: what the admin API writes, and what the public API and\n * automatic incidents (`incidents.auto`) build on. Validation of the input, and of\n * pages and components against the configuration, is the caller's job.\n */\nimport type {\n\tAffectedComponent,\n\tIncident,\n\tIncidentStage,\n\tIncidentUpdate,\n\tIncidentWithUpdates,\n\tListPage,\n} from \"../../shared/admin-api\";\nimport { type Actor, actorName, type Cursor, type EditResult, parseJsonColumn, toPage } from \"./common\";\n\ntype IncidentRow = {\n\tid: string;\n\tpage_id: string;\n\ttitle: string;\n\tstage: string;\n\tcomponents: string;\n\tstarted_at: number;\n\tcreated_at: number;\n\tupdated_at: number;\n\tresolved_at: number | null;\n\tcreated_by: string | null;\n\tupdated_by: string | null;\n\tauto_created: number;\n\thuman_edited_at: number | null;\n\tversion: number;\n};\n\ntype UpdateRow = {\n\tid: string;\n\tstage: string;\n\tbody: string;\n\tcreated_at: number;\n\tauthor: string | null;\n\tautomated: number;\n};\n\nconst INCIDENT_COLUMNS =\n\t\"id, page_id, title, stage, components, started_at, created_at, updated_at, resolved_at, created_by, updated_by, auto_created, human_edited_at, version\";\nconst UPDATE_COLUMNS = \"id, stage, body, created_at, author, automated\";\n\nfunction toIncident(row: IncidentRow): Incident {\n\treturn {\n\t\tid: row.id,\n\t\tpageId: row.page_id,\n\t\ttitle: row.title,\n\t\tstage: row.stage as IncidentStage,\n\t\tcomponents: parseJsonColumn<AffectedComponent[]>(row.components, [], `incident ${row.id}`),\n\t\tstartedAt: row.started_at,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\tresolvedAt: row.resolved_at,\n\t\tcreatedBy: row.created_by,\n\t\tupdatedBy: row.updated_by,\n\t\tautoCreated: row.auto_created !== 0,\n\t\thumanEditedAt: row.human_edited_at,\n\t\tversion: row.version,\n\t};\n}\n\nfunction toUpdate(row: UpdateRow): IncidentUpdate {\n\treturn {\n\t\tid: row.id,\n\t\tstage: row.stage as IncidentStage,\n\t\tbody: row.body,\n\t\tcreatedAt: row.created_at,\n\t\tauthor: row.author,\n\t\tautomated: row.automated !== 0,\n\t};\n}\n\nfunction selectUpdates(db: D1Database, incidentId: string): D1PreparedStatement {\n\treturn db\n\t\t.prepare(`SELECT ${UPDATE_COLUMNS} FROM incident_updates WHERE incident_id = ? ORDER BY created_at, rowid`)\n\t\t.bind(incidentId);\n}\n\nexport interface NewIncident {\n\treadonly pageId: string;\n\treadonly title: string;\n\t/** When it began; at most `now` (the caller checks it is not in the future). */\n\treadonly startedAt: number;\n\treadonly stage: IncidentStage;\n\t/** Message of the first update. */\n\treadonly body: string;\n\treadonly components: readonly AffectedComponent[];\n}\n\n/** Creates an incident with its first update. */\nexport async function createIncident(\n\tdb: D1Database,\n\tinput: NewIncident,\n\tactor: Actor,\n\tnow = Date.now(),\n): Promise<IncidentWithUpdates> {\n\tconst name = actorName(actor);\n\tconst human = actor.kind === \"admin\";\n\tconst incident: Incident = {\n\t\tid: crypto.randomUUID(),\n\t\tpageId: input.pageId,\n\t\ttitle: input.title,\n\t\tstage: input.stage,\n\t\tcomponents: input.components,\n\t\tstartedAt: Math.min(input.startedAt, now),\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tresolvedAt: input.stage === \"resolved\" ? now : null,\n\t\tcreatedBy: name,\n\t\tupdatedBy: name,\n\t\tautoCreated: !human,\n\t\thumanEditedAt: human ? now : null,\n\t\tversion: 1,\n\t};\n\tconst update: IncidentUpdate = {\n\t\tid: crypto.randomUUID(),\n\t\tstage: input.stage,\n\t\tbody: input.body,\n\t\tcreatedAt: now,\n\t\tauthor: name,\n\t\tautomated: !human,\n\t};\n\tawait db.batch([\n\t\tdb\n\t\t\t.prepare(`INSERT INTO incidents (${INCIDENT_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t.bind(\n\t\t\t\tincident.id,\n\t\t\t\tincident.pageId,\n\t\t\t\tincident.title,\n\t\t\t\tincident.stage,\n\t\t\t\tJSON.stringify(incident.components),\n\t\t\t\tincident.startedAt,\n\t\t\t\tincident.createdAt,\n\t\t\t\tincident.updatedAt,\n\t\t\t\tincident.resolvedAt,\n\t\t\t\tincident.createdBy,\n\t\t\t\tincident.updatedBy,\n\t\t\t\tincident.autoCreated ? 1 : 0,\n\t\t\t\tincident.humanEditedAt,\n\t\t\t\tincident.version,\n\t\t\t),\n\t\tdb\n\t\t\t.prepare(`INSERT INTO incident_updates (${UPDATE_COLUMNS}, incident_id) VALUES (?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t.bind(update.id, update.stage, update.body, update.createdAt, update.author, update.automated ? 1 : 0, incident.id),\n\t]);\n\treturn { ...incident, updates: [update] };\n}\n\nexport async function getIncident(db: D1Database, id: string): Promise<Incident | null> {\n\tconst row = await db.prepare(`SELECT ${INCIDENT_COLUMNS} FROM incidents WHERE id = ?`).bind(id).first<IncidentRow>();\n\treturn row === null ? null : toIncident(row);\n}\n\n/** The incident and its timeline, read together. */\nexport async function getIncidentWithUpdates(db: D1Database, id: string): Promise<IncidentWithUpdates | null> {\n\tconst [incident, updates] = await db.batch([\n\t\tdb.prepare(`SELECT ${INCIDENT_COLUMNS} FROM incidents WHERE id = ?`).bind(id),\n\t\tselectUpdates(db, id),\n\t]);\n\tconst row = (incident?.results as IncidentRow[] | undefined)?.[0];\n\tif (row === undefined) return null;\n\treturn { ...toIncident(row), updates: ((updates?.results ?? []) as UpdateRow[]).map(toUpdate) };\n}\n\nexport interface IncidentQuery {\n\treadonly pageId: string;\n\t/** `open`: not resolved yet. */\n\treadonly status?: \"open\" | \"resolved\" | undefined;\n\treadonly limit: number;\n\t/** Continue after this position (exclusive). */\n\treadonly after?: Cursor | undefined;\n}\n\n/** A page's incidents, latest start first, without their timelines. */\nexport async function listIncidents(db: D1Database, query: IncidentQuery): Promise<ListPage<Incident>> {\n\tconst conditions = [\"page_id = ?\"];\n\tconst bindings: unknown[] = [query.pageId];\n\tif (query.status === \"open\") conditions.push(\"resolved_at IS NULL\");\n\tif (query.status === \"resolved\") conditions.push(\"resolved_at IS NOT NULL\");\n\tif (query.after !== undefined) {\n\t\t// A row value, so that the index is entered at the cursor instead of read from the top.\n\t\tconditions.push(\"(started_at, id) < (?, ?)\");\n\t\tbindings.push(query.after.at, query.after.id);\n\t}\n\t// Walks incidents_by_page_start (page_id, started_at, id).\n\tconst { results } = await db\n\t\t.prepare(\n\t\t\t`SELECT ${INCIDENT_COLUMNS} FROM incidents WHERE ${conditions.join(\" AND \")}\n\t\t\tORDER BY started_at DESC, id DESC LIMIT ?`,\n\t\t)\n\t\t.bind(...bindings, query.limit + 1)\n\t\t.all<IncidentRow>();\n\treturn toPage(results, query.limit, toIncident, (row) => ({ at: row.started_at, id: row.id }));\n}\n\nexport interface IncidentChanges {\n\treadonly title?: string | undefined;\n\t/** Replaces the affected components. */\n\treadonly components?: readonly AffectedComponent[] | undefined;\n}\n\n/**\n * Changes the title or the affected components, if the incident is still at `version`\n * (checked in the same statement as the write).\n */\nexport async function patchIncident(\n\tdb: D1Database,\n\tid: string,\n\tversion: number,\n\tchanges: IncidentChanges,\n\tactor: Actor,\n\tnow = Date.now(),\n): Promise<EditResult<Incident>> {\n\tconst human = actor.kind === \"admin\";\n\tconst row = await db\n\t\t.prepare(\n\t\t\t`UPDATE incidents SET\n\t\t\t\ttitle = coalesce(?, title),\n\t\t\t\tcomponents = coalesce(?, components),\n\t\t\t\tupdated_at = max(updated_at, ?),\n\t\t\t\tupdated_by = ?,\n\t\t\t\thuman_edited_at = CASE WHEN ? THEN ? ELSE human_edited_at END,\n\t\t\t\tversion = version + 1\n\t\t\tWHERE id = ? AND version = ?\n\t\t\tRETURNING ${INCIDENT_COLUMNS}`,\n\t\t)\n\t\t.bind(\n\t\t\tchanges.title ?? null,\n\t\t\tchanges.components === undefined ? null : JSON.stringify(changes.components),\n\t\t\tnow,\n\t\t\tactorName(actor),\n\t\t\thuman ? 1 : 0,\n\t\t\tnow,\n\t\t\tid,\n\t\t\tversion,\n\t\t)\n\t\t.first<IncidentRow>();\n\tif (row !== null) return { status: \"updated\", value: toIncident(row) };\n\tconst current = await getIncident(db, id);\n\treturn current === null ? { status: \"not-found\" } : { status: \"conflict\", current };\n}\n\nexport interface NewIncidentUpdate {\n\treadonly stage: IncidentStage;\n\treadonly body: string;\n\t/** Also replaces the affected components. */\n\treadonly components?: readonly AffectedComponent[] | undefined;\n\t/**\n\t * The incident's version the editor started from: when given and the incident has another,\n\t * nothing is posted (`null`), so that replacing `components` cannot undo someone else's edit.\n\t */\n\treadonly version?: number | undefined;\n}\n\n/**\n * Adds a timeline entry. The incident's stage becomes the stage of its latest update\n * (computed in the same transaction, so concurrent posts cannot leave it behind), and the\n * incident is resolved when that stage is `resolved`, reopened otherwise. Never conflicts\n * unless `version` is given; new `components` count as an edit of them, so the version\n * goes up. `null` when the incident does not exist, or no longer has `version`.\n */\nexport async function postIncidentUpdate(\n\tdb: D1Database,\n\tincidentId: string,\n\tinput: NewIncidentUpdate,\n\tactor: Actor,\n\tnow = Date.now(),\n): Promise<IncidentWithUpdates | null> {\n\tconst name = actorName(actor);\n\tconst human = actor.kind === \"admin\";\n\tconst latestStage =\n\t\t\"(SELECT stage FROM incident_updates WHERE incident_id = ?1 ORDER BY created_at DESC, rowid DESC LIMIT 1)\";\n\tconst version = input.version ?? null;\n\tconst [inserted, updated, updates] = await db.batch([\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t`INSERT INTO incident_updates (${UPDATE_COLUMNS}, incident_id)\n\t\t\t\tSELECT ?, ?, ?, ?, ?, ?, ? WHERE EXISTS (SELECT 1 FROM incidents WHERE id = ? AND (? IS NULL OR version = ?))`,\n\t\t\t)\n\t\t\t.bind(crypto.randomUUID(), input.stage, input.body, now, name, human ? 0 : 1, incidentId, incidentId, version, version),\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t`UPDATE incidents SET\n\t\t\t\t\tstage = ${latestStage},\n\t\t\t\t\tresolved_at = CASE WHEN ${latestStage} = 'resolved' THEN coalesce(resolved_at, ?2) ELSE NULL END,\n\t\t\t\t\tcomponents = coalesce(?3, components),\n\t\t\t\t\tupdated_at = max(updated_at, ?2),\n\t\t\t\t\tupdated_by = ?4,\n\t\t\t\t\thuman_edited_at = CASE WHEN ?5 THEN ?2 ELSE human_edited_at END,\n\t\t\t\t\tversion = version + CASE WHEN ?3 IS NULL THEN 0 ELSE 1 END\n\t\t\t\tWHERE id = ?1 AND (?6 IS NULL OR version = ?6)\n\t\t\t\tRETURNING ${INCIDENT_COLUMNS}`,\n\t\t\t)\n\t\t\t.bind(\n\t\t\t\tincidentId,\n\t\t\t\tnow,\n\t\t\t\tinput.components === undefined ? null : JSON.stringify(input.components),\n\t\t\t\tname,\n\t\t\t\thuman ? 1 : 0,\n\t\t\t\tversion,\n\t\t\t),\n\t\tselectUpdates(db, incidentId),\n\t]);\n\tconst row = (updated?.results as IncidentRow[] | undefined)?.[0];\n\tif ((inserted?.meta.changes ?? 0) === 0 || row === undefined) return null;\n\treturn { ...toIncident(row), updates: ((updates?.results ?? []) as UpdateRow[]).map(toUpdate) };\n}\n\n/** What a public cursor of a page's incident list must match: the incident it names. */\nexport interface IncidentPosition {\n\treadonly pageId: string;\n\treadonly startedAt: number;\n\treadonly resolved: boolean;\n}\n\n/** Where incident `id` is in its page's lists, or `null` when it does not exist (one primary-key read). */\nexport async function incidentPosition(db: D1Database, id: string): Promise<IncidentPosition | null> {\n\tconst row = await db\n\t\t.prepare(\"SELECT page_id, started_at, resolved_at FROM incidents WHERE id = ?\")\n\t\t.bind(id)\n\t\t.first<{ page_id: string; started_at: number; resolved_at: number | null }>();\n\treturn row === null ? null : { pageId: row.page_id, startedAt: row.started_at, resolved: row.resolved_at !== null };\n}\n\n/** An incident with one page of its timeline (oldest first), for the public incident page. */\nexport interface IncidentWithUpdatePage extends IncidentWithUpdates {\n\t/** Whether older updates exist. */\n\treadonly olderUpdates: boolean;\n\t/** The position before the oldest update shown, to read the previous page; `null` without older ones. */\n\treadonly olderCursor: Cursor | null;\n}\n\n/** An update's position in its incident's timeline, or `null` when it does not exist (one primary-key read). */\nexport async function updatePosition(db: D1Database, id: string): Promise<{ incidentId: string; createdAt: number; rowid: number } | null> {\n\tconst row = await db\n\t\t.prepare(\"SELECT incident_id, created_at, rowid FROM incident_updates WHERE id = ?\")\n\t\t.bind(id)\n\t\t.first<{ incident_id: string; created_at: number; rowid: number }>();\n\treturn row === null ? null : { incidentId: row.incident_id, createdAt: row.created_at, rowid: row.rowid };\n}\n\n/**\n * The incident and its latest `limit` updates before `before` (an update's position, exclusive;\n * `null` for the latest), oldest first: at most `limit + 2` rows, however long the timeline.\n */\nexport async function getIncidentWithUpdatePage(\n\tdb: D1Database,\n\tid: string,\n\tlimit: number,\n\tbefore: { readonly createdAt: number; readonly rowid: number } | null,\n): Promise<IncidentWithUpdatePage | null> {\n\tconst [incident, updates] = await db.batch([\n\t\tdb.prepare(`SELECT ${INCIDENT_COLUMNS} FROM incidents WHERE id = ?`).bind(id),\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t// A row value, so that incident_updates_by_incident is entered at `before`.\n\t\t\t\t`SELECT ${UPDATE_COLUMNS} FROM incident_updates WHERE incident_id = ?1\n\t\t\t\t${before === null ? \"\" : \"AND (created_at, rowid) < (?2, ?3)\"}\n\t\t\t\tORDER BY created_at DESC, rowid DESC LIMIT ?4`,\n\t\t\t)\n\t\t\t.bind(id, before?.createdAt ?? 0, before?.rowid ?? 0, limit + 1),\n\t]);\n\tconst row = (incident?.results as IncidentRow[] | undefined)?.[0];\n\tif (row === undefined) return null;\n\tconst latest = ((updates?.results ?? []) as UpdateRow[]).map(toUpdate);\n\tconst shown = latest.slice(0, limit).reverse();\n\tconst oldest = shown[0];\n\tconst olderUpdates = latest.length > limit;\n\treturn {\n\t\t...toIncident(row),\n\t\tupdates: shown,\n\t\tolderUpdates,\n\t\tolderCursor: olderUpdates && oldest !== undefined ? { at: oldest.createdAt, id: oldest.id } : null,\n\t};\n}\n\n/**\n * A page's incidents changed (created, edited, updated or resolved) at or after `since`, by\n * `incidents_by_page_updated`; `null` when more than `cap` changed (read them all instead).\n */\nexport async function listIncidentsChangedSince(db: D1Database, pageId: string, since: number, cap = 500): Promise<Incident[] | null> {\n\tconst { results } = await db\n\t\t.prepare(`SELECT ${INCIDENT_COLUMNS} FROM incidents WHERE page_id = ? AND updated_at >= ? ORDER BY updated_at LIMIT ?`)\n\t\t.bind(pageId, since, cap + 1)\n\t\t.all<IncidentRow>();\n\treturn results.length > cap ? null : results.map(toIncident);\n}\n\n/** Deletes an incident and its timeline. `false` when it does not exist. */\nexport async function deleteIncident(db: D1Database, id: string): Promise<boolean> {\n\tconst [, deleted] = await db.batch([\n\t\tdb.prepare(\"DELETE FROM incident_updates WHERE incident_id = ?\").bind(id),\n\t\tdb.prepare(\"DELETE FROM incidents WHERE id = ?\").bind(id),\n\t]);\n\treturn (deleted?.meta.changes ?? 0) > 0;\n}\n\n// ---------------------------------------------------------------------------\n// Reads for the public API\n// ---------------------------------------------------------------------------\n\n/** Most unresolved incidents a page shows; more than this many at once is a mistake to clean up. */\nexport const MAX_OPEN_INCIDENTS = 100;\n/** Rows read per query when collecting the incidents of the history's window. */\nconst HISTORY_BATCH = 500;\n/** Most incidents the history marks over its window; beyond it, a warning (older ones are left out). */\nexport const MAX_HISTORY_INCIDENTS = 10_000;\n\n/** An unresolved incident with its latest updates. */\nexport interface IncidentWithLatestUpdates extends IncidentWithUpdates {\n\t/** Whether older updates were left out (the incident itself has them all). */\n\treadonly olderUpdates: boolean;\n}\n\n/**\n * A page's unresolved incidents, latest start first, each with its latest `updatesPerIncident`\n * updates (oldest first). Reads the open incidents through `incidents_by_page_resolved` and\n * then, in one batch, per incident at most `updatesPerIncident + 1` updates in the order of\n * `incident_updates_by_incident` (whose entries end with the rowid), so a long timeline does\n * not add to every read.\n */\nexport async function listOpenIncidentsWithUpdates(\n\tdb: D1Database,\n\tpageId: string,\n\tupdatesPerIncident: number,\n): Promise<IncidentWithLatestUpdates[]> {\n\tconst { results: incidents } = await db\n\t\t.prepare(\n\t\t\t`SELECT ${INCIDENT_COLUMNS} FROM incidents WHERE page_id = ? AND resolved_at IS NULL\n\t\t\tORDER BY started_at DESC, id DESC LIMIT ?`,\n\t\t)\n\t\t.bind(pageId, MAX_OPEN_INCIDENTS)\n\t\t.all<IncidentRow>();\n\tif (incidents.length === 0) return [];\n\tconst updates = await db.batch(\n\t\tincidents.map((incident) =>\n\t\t\tdb\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT ${UPDATE_COLUMNS} FROM incident_updates WHERE incident_id = ?\n\t\t\t\t\tORDER BY created_at DESC, rowid DESC LIMIT ?`,\n\t\t\t\t)\n\t\t\t\t.bind(incident.id, updatesPerIncident + 1),\n\t\t),\n\t);\n\treturn incidents.map((row, index) => {\n\t\tconst latest = ((updates[index]?.results ?? []) as UpdateRow[]).map(toUpdate).reverse();\n\t\treturn {\n\t\t\t...toIncident(row),\n\t\t\tupdates: latest.slice(-updatesPerIncident),\n\t\t\tolderUpdates: latest.length > updatesPerIncident,\n\t\t};\n\t});\n}\n\n/**\n * A page's incidents that were unresolved at some time since `from`: those still open and\n * those resolved since then, for the history's markers. Both walk\n * `incidents_by_page_resolved`: the open ones latest start first, the resolved ones latest\n * resolution first, in batches, so that the whole window is covered up to `cap` incidents,\n * and beyond it the most recent are kept (with a warning).\n */\nexport async function listIncidentsSince(\n\tdb: D1Database,\n\tpageId: string,\n\tfrom: number,\n\tcap = MAX_HISTORY_INCIDENTS,\n): Promise<Incident[]> {\n\tconst { results: open } = await db\n\t\t.prepare(\n\t\t\t`SELECT ${INCIDENT_COLUMNS} FROM incidents WHERE page_id = ? AND resolved_at IS NULL\n\t\t\tORDER BY started_at DESC, id DESC LIMIT ?`,\n\t\t)\n\t\t.bind(pageId, Math.min(MAX_OPEN_INCIDENTS, cap))\n\t\t.all<IncidentRow>();\n\tconst incidents = open.map(toIncident);\n\tlet before = null as { at: number; id: string } | null;\n\tlet more = false;\n\tfor (;;) {\n\t\tconst want = Math.min(HISTORY_BATCH, cap - incidents.length);\n\t\t// Each batch enters the index where the last one stopped (a row value), not at the top.\n\t\tconst { results }: { results: IncidentRow[] } = await db\n\t\t\t.prepare(\n\t\t\t\t`SELECT ${INCIDENT_COLUMNS} FROM incidents WHERE page_id = ?1 AND resolved_at >= ?2\n\t\t\t\t${before === null ? \"\" : \"AND (resolved_at, id) < (?3, ?4)\"}\n\t\t\t\tORDER BY resolved_at DESC, id DESC LIMIT ?5`,\n\t\t\t)\n\t\t\t.bind(pageId, from, before?.at ?? 0, before?.id ?? \"\", want + 1)\n\t\t\t.all<IncidentRow>();\n\t\tconst kept = results.slice(0, want);\n\t\tincidents.push(...kept.map(toIncident));\n\t\tif (results.length <= want) break;\n\t\tif (incidents.length >= cap) {\n\t\t\tmore = true;\n\t\t\tbreak;\n\t\t}\n\t\tconst last = kept.at(-1) as IncidentRow;\n\t\tbefore = { at: last.resolved_at as number, id: last.id };\n\t}\n\tif (more) console.warn(`Page \"${pageId}\" has more than ${cap} incidents in the history's window; showing the most recent ${cap}`);\n\treturn incidents;\n}\n","/** Per-page appearance in D1 (one language). One row per page that has been customised. */\nimport { type AppearanceColors, appearanceColorsSchema, NO_COLORS, type PageAppearance } from \"../../shared/admin-api\";\nimport { type Actor, actorName, type EditResult } from \"./common\";\n\ntype AppearanceRow = {\n\tpage_id: string;\n\ttitle: string | null;\n\tdescription: string | null;\n\tlogo_url: string | null;\n\twebsite_url: string | null;\n\tlogo_image: string | null;\n\tfavicon_image: string | null;\n\tcolors: string | null;\n\tupdated_at: number;\n\tupdated_by: string | null;\n\tversion: number;\n};\n\nconst COLUMNS =\n\t\"page_id, title, description, logo_url, website_url, logo_image, favicon_image, colors, updated_at, updated_by, version\";\n\n/** The fields an edit replaces. The optional ones keep their current values when `undefined`. */\nexport type AppearanceFields = Pick<PageAppearance, \"title\" | \"description\" | \"logoUrl\" | \"websiteUrl\"> & {\n\treadonly logoImage?: string | null | undefined;\n\treadonly faviconImage?: string | null | undefined;\n\t/** `null`: the template's colours throughout. */\n\treadonly colors?: AppearanceColors | null | undefined;\n};\n\n/** Whether no colour is set. */\nfunction noColorSet(colors: AppearanceColors): boolean {\n\treturn Object.values(colors).every((scheme) => Object.values(scheme).every((color) => color === null));\n}\n\n/** The column's value: NULL when every colour is the template's. */\nfunction colorsColumn(colors: AppearanceColors | null): string | null {\n\treturn colors === null || noColorSet(colors) ? null : JSON.stringify(colors);\n}\n\n/** The colours of a row; the template's when the column is empty or not valid (written by a newer version, say). */\nfunction parseColors(text: string | null): AppearanceColors {\n\tif (text === null) return NO_COLORS;\n\ttry {\n\t\tconst parsed = appearanceColorsSchema.safeParse(JSON.parse(text));\n\t\tif (parsed.success) return parsed.data;\n\t} catch {\n\t\t// Not JSON: fall through.\n\t}\n\tconsole.warn(\"A page's colours could not be read; showing the template's\");\n\treturn NO_COLORS;\n}\n\nfunction toAppearance(row: AppearanceRow): PageAppearance {\n\treturn {\n\t\tpageId: row.page_id,\n\t\ttitle: row.title,\n\t\tdescription: row.description,\n\t\tlogoUrl: row.logo_url,\n\t\twebsiteUrl: row.website_url,\n\t\tlogoImage: row.logo_image,\n\t\tfaviconImage: row.favicon_image,\n\t\tcolors: parseColors(row.colors),\n\t\tupdatedAt: row.updated_at,\n\t\tupdatedBy: row.updated_by,\n\t\tversion: row.version,\n\t};\n}\n\n/** A page's appearance before it was ever customised: every field the default, version 0. */\nexport function defaultAppearance(pageId: string): PageAppearance {\n\treturn {\n\t\tpageId,\n\t\ttitle: null,\n\t\tdescription: null,\n\t\tlogoUrl: null,\n\t\twebsiteUrl: null,\n\t\tlogoImage: null,\n\t\tfaviconImage: null,\n\t\tcolors: NO_COLORS,\n\t\tupdatedAt: null,\n\t\tupdatedBy: null,\n\t\tversion: 0,\n\t};\n}\n\n/** The page's appearance; every field `null` (the defaults) and version 0 when it was never customised. */\nexport async function getAppearance(db: D1Database, pageId: string): Promise<PageAppearance> {\n\tconst row = await db.prepare(`SELECT ${COLUMNS} FROM page_appearance WHERE page_id = ?`).bind(pageId).first<AppearanceRow>();\n\treturn row === null ? defaultAppearance(pageId) : toAppearance(row);\n}\n\n/**\n * Replaces the page's appearance, if it is still at `version` (0: never customised),\n * checked in the same statement as the write. Optional fields left `undefined` keep their\n * values (on a first save: the defaults).\n */\nexport async function putAppearance(\n\tdb: D1Database,\n\tpageId: string,\n\tversion: number,\n\tfields: AppearanceFields,\n\tactor: Actor,\n\tnow = Date.now(),\n): Promise<EditResult<PageAppearance>> {\n\tconst columns: [string, string | null][] = [\n\t\t[\"title\", fields.title],\n\t\t[\"description\", fields.description],\n\t\t[\"logo_url\", fields.logoUrl],\n\t\t[\"website_url\", fields.websiteUrl],\n\t];\n\tconst optional: [string, string | null | undefined][] = [\n\t\t[\"logo_image\", fields.logoImage],\n\t\t[\"favicon_image\", fields.faviconImage],\n\t\t[\"colors\", fields.colors === undefined ? undefined : colorsColumn(fields.colors)],\n\t];\n\tlet statement: D1PreparedStatement;\n\tif (version === 0) {\n\t\tconst values = [...columns, ...optional].map(([, value]) => value ?? null);\n\t\tstatement = db\n\t\t\t.prepare(\n\t\t\t\t`INSERT INTO page_appearance (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)\n\t\t\t\tON CONFLICT (page_id) DO NOTHING\n\t\t\t\tRETURNING ${COLUMNS}`,\n\t\t\t)\n\t\t\t.bind(pageId, ...values, now, actorName(actor));\n\t} else {\n\t\tconst set = [...columns, ...optional.filter(([, value]) => value !== undefined)] as [string, string | null][];\n\t\tstatement = db\n\t\t\t.prepare(\n\t\t\t\t`UPDATE page_appearance SET ${set.map(([column]) => `${column} = ?`).join(\", \")},\n\t\t\t\t\tupdated_at = ?, updated_by = ?, version = version + 1\n\t\t\t\tWHERE page_id = ? AND version = ?\n\t\t\t\tRETURNING ${COLUMNS}`,\n\t\t\t)\n\t\t\t.bind(...set.map(([, value]) => value), now, actorName(actor), pageId, version);\n\t}\n\tconst row = await statement.first<AppearanceRow>();\n\tif (row !== null) return { status: \"updated\", value: toAppearance(row) };\n\t// A page always has an appearance (the defaults at version 0), so a mismatch is a conflict.\n\treturn { status: \"conflict\", current: await getAppearance(db, pageId) };\n}\n\n/** The title of every page that has one, for the public list of pages. Reads one row per customised page. */\nexport async function listAppearanceTitles(db: D1Database): Promise<Map<string, string>> {\n\tconst { results } = await db\n\t\t.prepare(\"SELECT page_id, title FROM page_appearance WHERE title IS NOT NULL\")\n\t\t.all<{ page_id: string; title: string }>();\n\treturn new Map(results.map((row) => [row.page_id, row.title]));\n}\n","/**\n * Scheduled maintenance in D1: written from the admin API, read by the public\n * API and by notifications, which it suppresses. Validation, including that\n * a maintenance ends after it starts and that its components exist, is the caller's job.\n */\nimport type { ListPage, Maintenance } from \"../../shared/admin-api\";\nimport { type Actor, actorName, type Cursor, type EditResult, parseJsonColumn, toPage } from \"./common\";\n\ntype MaintenanceRow = {\n\tid: string;\n\tpage_id: string;\n\ttitle: string;\n\tbody: string;\n\tcomponents: string;\n\tstarts_at: number;\n\tends_at: number;\n\tcreated_at: number;\n\tupdated_at: number;\n\tcreated_by: string | null;\n\tupdated_by: string | null;\n\tversion: number;\n};\n\nconst COLUMNS =\n\t\"id, page_id, title, body, components, starts_at, ends_at, created_at, updated_at, created_by, updated_by, version\";\n\nfunction toMaintenance(row: MaintenanceRow): Maintenance {\n\treturn {\n\t\tid: row.id,\n\t\tpageId: row.page_id,\n\t\ttitle: row.title,\n\t\tbody: row.body,\n\t\tcomponents: parseJsonColumn<string[]>(row.components, [], `maintenance ${row.id}`),\n\t\tstartsAt: row.starts_at,\n\t\tendsAt: row.ends_at,\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\tcreatedBy: row.created_by,\n\t\tupdatedBy: row.updated_by,\n\t\tversion: row.version,\n\t};\n}\n\n/** The editable fields of a maintenance. */\nexport interface MaintenanceFields {\n\treadonly title: string;\n\treadonly body: string;\n\treadonly startsAt: number;\n\treadonly endsAt: number;\n\treadonly components: readonly string[];\n}\n\nexport async function createMaintenance(\n\tdb: D1Database,\n\tpageId: string,\n\tfields: MaintenanceFields,\n\tactor: Actor,\n\tnow = Date.now(),\n): Promise<Maintenance> {\n\tconst name = actorName(actor);\n\tconst maintenance: Maintenance = {\n\t\tid: crypto.randomUUID(),\n\t\tpageId,\n\t\t...fields,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tcreatedBy: name,\n\t\tupdatedBy: name,\n\t\tversion: 1,\n\t};\n\tawait db\n\t\t.prepare(`INSERT INTO maintenances (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t.bind(\n\t\t\tmaintenance.id,\n\t\t\tpageId,\n\t\t\tfields.title,\n\t\t\tfields.body,\n\t\t\tJSON.stringify(fields.components),\n\t\t\tfields.startsAt,\n\t\t\tfields.endsAt,\n\t\t\tnow,\n\t\t\tnow,\n\t\t\tname,\n\t\t\tname,\n\t\t\tmaintenance.version,\n\t\t)\n\t\t.run();\n\treturn maintenance;\n}\n\nexport async function getMaintenance(db: D1Database, id: string): Promise<Maintenance | null> {\n\tconst row = await db.prepare(`SELECT ${COLUMNS} FROM maintenances WHERE id = ?`).bind(id).first<MaintenanceRow>();\n\treturn row === null ? null : toMaintenance(row);\n}\n\nexport interface MaintenanceQuery {\n\treadonly pageId: string;\n\treadonly limit: number;\n\t/** Continue after this position (exclusive). */\n\treadonly after?: Cursor | undefined;\n}\n\n/** A page's maintenance, latest start first. */\nexport async function listMaintenance(db: D1Database, query: MaintenanceQuery): Promise<ListPage<Maintenance>> {\n\tconst conditions = [\"page_id = ?\"];\n\tconst bindings: unknown[] = [query.pageId];\n\tif (query.after !== undefined) {\n\t\tconditions.push(\"(starts_at < ? OR (starts_at = ? AND id < ?))\");\n\t\tbindings.push(query.after.at, query.after.at, query.after.id);\n\t}\n\t// Walks maintenances_by_page_start (page_id, starts_at, id).\n\tconst { results } = await db\n\t\t.prepare(\n\t\t\t`SELECT ${COLUMNS} FROM maintenances WHERE ${conditions.join(\" AND \")}\n\t\t\tORDER BY starts_at DESC, id DESC LIMIT ?`,\n\t\t)\n\t\t.bind(...bindings, query.limit + 1)\n\t\t.all<MaintenanceRow>();\n\treturn toPage(results, query.limit, toMaintenance, (row) => ({ at: row.starts_at, id: row.id }));\n}\n\n/** Replaces the editable fields, if the maintenance is still at `version` (checked in the same statement). */\nexport async function updateMaintenance(\n\tdb: D1Database,\n\tid: string,\n\tversion: number,\n\tfields: MaintenanceFields,\n\tactor: Actor,\n\tnow = Date.now(),\n): Promise<EditResult<Maintenance>> {\n\tconst row = await db\n\t\t.prepare(\n\t\t\t`UPDATE maintenances SET title = ?, body = ?, components = ?, starts_at = ?, ends_at = ?,\n\t\t\t\tupdated_at = max(updated_at, ?), updated_by = ?, version = version + 1\n\t\t\tWHERE id = ? AND version = ?\n\t\t\tRETURNING ${COLUMNS}`,\n\t\t)\n\t\t.bind(\n\t\t\tfields.title,\n\t\t\tfields.body,\n\t\t\tJSON.stringify(fields.components),\n\t\t\tfields.startsAt,\n\t\t\tfields.endsAt,\n\t\t\tnow,\n\t\t\tactorName(actor),\n\t\t\tid,\n\t\t\tversion,\n\t\t)\n\t\t.first<MaintenanceRow>();\n\tif (row !== null) return { status: \"updated\", value: toMaintenance(row) };\n\tconst current = await getMaintenance(db, id);\n\treturn current === null ? { status: \"not-found\" } : { status: \"conflict\", current };\n}\n\n/** `false` when it does not exist. */\nexport async function deleteMaintenance(db: D1Database, id: string): Promise<boolean> {\n\tconst result = await db.prepare(\"DELETE FROM maintenances WHERE id = ?\").bind(id).run();\n\treturn result.meta.changes > 0;\n}\n\n/** Most current and upcoming maintenance a page's status lists, earliest start first. */\nexport const MAX_PUBLIC_MAINTENANCE = 200;\n/** Rows read per query when collecting the maintenance of the history's window. */\nconst HISTORY_BATCH = 500;\n/** Most maintenance the history takes into account; beyond it, a warning. */\nexport const MAX_HISTORY_MAINTENANCE = 10_000;\n\n/**\n * A page's maintenance that ends after `from` and starts before `to`, earliest start first,\n * at most {@link MAX_PUBLIC_MAINTENANCE}: the current and upcoming maintenance a status\n * shows (with `to` far ahead). Walks `maintenances_by_page_end`, so it reads the maintenance\n * ending after `from` only.\n */\nexport async function listMaintenanceBetween(\n\tdb: D1Database,\n\tpageId: string,\n\tfrom: number,\n\tto: number,\n): Promise<Maintenance[]> {\n\tconst { results } = await db\n\t\t.prepare(\n\t\t\t`SELECT ${COLUMNS} FROM maintenances WHERE page_id = ? AND ends_at > ? AND starts_at < ?\n\t\t\tORDER BY starts_at, id LIMIT ?`,\n\t\t)\n\t\t.bind(pageId, from, to, MAX_PUBLIC_MAINTENANCE)\n\t\t.all<MaintenanceRow>();\n\treturn results.map(toMaintenance);\n}\n\n/**\n * Every maintenance of a page that overlaps `[from, to)`, latest end first, for the history\n * (it is left out of uptime, so none may be missed). Walks `maintenances_by_page_end`\n * backwards in batches, up to `cap` windows; beyond it, the most recent are kept (with a\n * warning).\n */\nexport async function listMaintenanceOverlapping(\n\tdb: D1Database,\n\tpageId: string,\n\tfrom: number,\n\tto: number,\n\tcap = MAX_HISTORY_MAINTENANCE,\n): Promise<Maintenance[]> {\n\tconst found: Maintenance[] = [];\n\tlet before = null as { at: number; id: string } | null;\n\tlet more = false;\n\tfor (;;) {\n\t\tconst { results }: { results: MaintenanceRow[] } = await db\n\t\t\t.prepare(\n\t\t\t\t`SELECT ${COLUMNS} FROM maintenances WHERE page_id = ?1 AND ends_at > ?2\n\t\t\t\tAND (?3 IS NULL OR ends_at < ?3 OR (ends_at = ?3 AND id < ?4))\n\t\t\t\tORDER BY ends_at DESC, id DESC LIMIT ?5`,\n\t\t\t)\n\t\t\t.bind(pageId, from, before?.at ?? null, before?.id ?? \"\", HISTORY_BATCH)\n\t\t\t.all<MaintenanceRow>();\n\t\tfor (const row of results) {\n\t\t\tif (row.starts_at >= to) continue;\n\t\t\tif (found.length >= cap) {\n\t\t\t\tmore = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfound.push(toMaintenance(row));\n\t\t}\n\t\tconst last = results.at(-1);\n\t\tif (more || results.length < HISTORY_BATCH || last === undefined) break;\n\t\tbefore = { at: last.ends_at, id: last.id };\n\t}\n\tif (more) console.warn(`Page \"${pageId}\" has more than ${cap} maintenance windows in the history's window; using the most recent ${cap}`);\n\treturn found;\n}\n","/**\n * Response times for status pages (`components[].latency`).\n *\n * The Monitor DO sums them into 15-minute buckets (count, total and a histogram) from the result\n * rows it reads anyway when a page reads its history (`getTimeline`), so publishing them costs\n * no extra row read and no extra Durable Object request. The page keeps the buckets with its\n * cached days (a cache that can be rebuilt from the results) and turns them into series of\n * 24 hours, 7 days and 30 days. Nothing is aggregated or stored when a check runs.\n *\n * Only scheduled checks that got a response count: re-checks come in bursts after failures and\n * would weigh bad minutes more, and checks that timed out or failed to connect have no response\n * time. Buckets start at multiples of their length since the epoch, so every 15-minute bucket\n * falls in one 2-hour and one 6-hour bucket, and in one local day of any time zone (all offsets\n * in use are whole quarters of an hour).\n */\nimport type { LatencySeries } from \"../shared/public-api\";\n\n/** Length of the buckets the Monitor DO returns and pages keep. */\nexport const LATENCY_BUCKET_MS = 15 * 60_000;\n\n/** The series a page publishes: bucket length and number of buckets. */\nexport const LATENCY_RANGES = {\n\tday: { bucketMs: LATENCY_BUCKET_MS, count: 96 },\n\tweek: { bucketMs: 2 * 3_600_000, count: 84 },\n\tmonth: { bucketMs: 6 * 3_600_000, count: 120 },\n} as const;\n\n/** The 95th percentile, as published. */\nconst PERCENTILE = 0.95;\n\n/**\n * Histogram bins grow by this ratio, so a value read back from its bin (the bin's geometric\n * middle) is within about 5% of what was measured, at any scale: 100 ms ± 5 ms, 3 s ± 150 ms.\n * Measured response times fall in a few dozen bins at most (60 seconds is bin 115).\n */\nconst BIN_RATIO = 1.1;\nconst LOG_RATIO = Math.log(BIN_RATIO);\n\nexport function latencyBin(ms: number): number {\n\treturn Math.max(0, Math.round(Math.log1p(Math.max(0, ms)) / LOG_RATIO));\n}\n\n/** The response time a bin stands for. */\nexport function binValue(bin: number): number {\n\treturn Math.expm1(bin * LOG_RATIO);\n}\n\nexport interface LatencyBucket {\n\t/** A multiple of {@link LATENCY_BUCKET_MS}. */\n\treadonly from: number;\n\treadonly count: number;\n\treadonly sumMs: number;\n\t/** The histogram as `[bin, count]` pairs, flattened, by bin. */\n\treadonly bins: readonly number[];\n}\n\n/** When the published series begin: the start of the 30-day series' first bucket. Older data is not kept. */\nexport function latencySince(now: number): number {\n\tconst { bucketMs, count } = LATENCY_RANGES.month;\n\treturn Math.floor(now / bucketMs) * bucketMs - (count - 1) * bucketMs;\n}\n\n/** Response times (`[checked at, milliseconds]`) summed into 15-minute buckets, oldest first. */\nexport function aggregateLatency(samples: Iterable<readonly [at: number, ms: number]>): LatencyBucket[] {\n\tconst buckets = new Map<number, { count: number; sumMs: number; bins: Map<number, number> }>();\n\tfor (const [at, ms] of samples) {\n\t\tconst from = Math.floor(at / LATENCY_BUCKET_MS) * LATENCY_BUCKET_MS;\n\t\tlet bucket = buckets.get(from);\n\t\tif (bucket === undefined) {\n\t\t\tbucket = { count: 0, sumMs: 0, bins: new Map() };\n\t\t\tbuckets.set(from, bucket);\n\t\t}\n\t\tbucket.count++;\n\t\tbucket.sumMs += ms;\n\t\tconst bin = latencyBin(ms);\n\t\tbucket.bins.set(bin, (bucket.bins.get(bin) ?? 0) + 1);\n\t}\n\treturn [...buckets.entries()]\n\t\t.sort(([a], [b]) => a - b)\n\t\t.map(([from, bucket]) => ({ from, count: bucket.count, sumMs: bucket.sumMs, bins: flatten(bucket.bins) }));\n}\n\nfunction flatten(bins: ReadonlyMap<number, number>): number[] {\n\treturn [...bins.entries()].sort(([a], [b]) => a - b).flat();\n}\n\n/**\n * Buckets of the same time (the monitors of one component) summed into one, oldest first.\n */\nexport function mergeLatency(lists: Iterable<readonly LatencyBucket[]>): LatencyBucket[] {\n\tconst merged = new Map<number, { count: number; sumMs: number; bins: Map<number, number> }>();\n\tfor (const list of lists) {\n\t\tfor (const bucket of list) {\n\t\t\tlet into = merged.get(bucket.from);\n\t\t\tif (into === undefined) {\n\t\t\t\tinto = { count: 0, sumMs: 0, bins: new Map() };\n\t\t\t\tmerged.set(bucket.from, into);\n\t\t\t}\n\t\t\tinto.count += bucket.count;\n\t\t\tinto.sumMs += bucket.sumMs;\n\t\t\tfor (let index = 0; index + 1 < bucket.bins.length; index += 2) {\n\t\t\t\tconst bin = bucket.bins[index] as number;\n\t\t\t\tinto.bins.set(bin, (into.bins.get(bin) ?? 0) + (bucket.bins[index + 1] as number));\n\t\t\t}\n\t\t}\n\t}\n\treturn [...merged.entries()]\n\t\t.sort(([a], [b]) => a - b)\n\t\t.map(([from, bucket]) => ({ from, count: bucket.count, sumMs: bucket.sumMs, bins: flatten(bucket.bins) }));\n}\n\n/**\n * A series of `count` buckets of `bucketMs`, the last one containing `now` (so far), from\n * 15-minute buckets.\n */\nexport function latencySeries(buckets: readonly LatencyBucket[], now: number, bucketMs: number, count: number): LatencySeries {\n\tconst last = Math.floor(now / bucketMs) * bucketMs;\n\tconst from = last - (count - 1) * bucketMs;\n\tconst sums = Array.from({ length: count }, () => 0);\n\tconst counts = Array.from({ length: count }, () => 0);\n\tconst histogram = new Map<number, number>();\n\tlet total = 0;\n\tlet sum = 0;\n\tfor (const bucket of buckets) {\n\t\tif (bucket.from < from || bucket.from >= last + bucketMs || bucket.count === 0) continue;\n\t\tconst index = Math.floor((bucket.from - from) / bucketMs);\n\t\tsums[index] = (sums[index] as number) + bucket.sumMs;\n\t\tcounts[index] = (counts[index] as number) + bucket.count;\n\t\ttotal += bucket.count;\n\t\tsum += bucket.sumMs;\n\t\tfor (let position = 0; position + 1 < bucket.bins.length; position += 2) {\n\t\t\tconst bin = bucket.bins[position] as number;\n\t\t\thistogram.set(bin, (histogram.get(bin) ?? 0) + (bucket.bins[position + 1] as number));\n\t\t}\n\t}\n\treturn {\n\t\tfrom,\n\t\tbucketMs,\n\t\tvalues: counts.map((n, index) => (n > 0 ? Math.round((sums[index] as number) / n) : null)),\n\t\taverageMs: total > 0 ? Math.round(sum / total) : null,\n\t\tp95Ms: percentile(histogram, total, PERCENTILE),\n\t};\n}\n\n/** The nearest-rank percentile `q` of a histogram of `total` values. */\nexport function percentile(histogram: ReadonlyMap<number, number>, total: number, q: number): number | null {\n\tif (total <= 0) return null;\n\tconst rank = Math.max(1, Math.ceil(q * total));\n\tlet seen = 0;\n\tfor (const bin of [...histogram.keys()].sort((a, b) => a - b)) {\n\t\tseen += histogram.get(bin) as number;\n\t\tif (seen >= rank) return Math.round(binValue(bin));\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------\n// Packed form, kept in memory by status pages\n// ---------------------------------------------------------------------------\n\n/**\n * Buckets packed into one typed array, as the page keeps a day's segments: per bucket `from`,\n * `count`, `sumMs`, the number of bins, then `[bin, count]` pairs.\n */\nexport type PackedLatency = Float64Array;\n\nexport const NO_LATENCY: PackedLatency = new Float64Array();\n\nexport function packLatency(buckets: readonly LatencyBucket[]): PackedLatency {\n\tconst size = buckets.reduce((total, bucket) => total + 4 + bucket.bins.length, 0);\n\tconst packed = new Float64Array(size);\n\tlet at = 0;\n\tfor (const bucket of buckets) {\n\t\tpacked[at++] = bucket.from;\n\t\tpacked[at++] = bucket.count;\n\t\tpacked[at++] = bucket.sumMs;\n\t\tpacked[at++] = bucket.bins.length / 2;\n\t\tpacked.set(bucket.bins, at);\n\t\tat += bucket.bins.length;\n\t}\n\treturn packed;\n}\n\nexport function unpackLatency(packed: PackedLatency): LatencyBucket[] {\n\tconst buckets: LatencyBucket[] = [];\n\tlet at = 0;\n\twhile (at + 3 < packed.length) {\n\t\tconst pairs = packed[at + 3] as number;\n\t\tbuckets.push({\n\t\t\tfrom: packed[at] as number,\n\t\t\tcount: packed[at + 1] as number,\n\t\t\tsumMs: packed[at + 2] as number,\n\t\t\tbins: Array.from(packed.subarray(at + 4, at + 4 + 2 * pairs)),\n\t\t});\n\t\tat += 4 + 2 * pairs;\n\t}\n\treturn buckets;\n}\n\n/** `a` followed by `b`: buckets of consecutive stretches of time. */\nexport function concatLatency(a: PackedLatency, b: PackedLatency): PackedLatency {\n\tif (b.length === 0) return a;\n\tif (a.length === 0) return b;\n\tconst joined = new Float64Array(a.length + b.length);\n\tjoined.set(a);\n\tjoined.set(b, a.length);\n\treturn joined;\n}\n\ntype StoredBucket = [from: number, count: number, sumMs: number, bins: number[]];\n\n/** As stored in a page's SQLite (`monitor_days.latency`). */\nexport function encodeLatency(packed: PackedLatency): string {\n\treturn JSON.stringify(unpackLatency(packed).map((bucket): StoredBucket => [bucket.from, bucket.count, bucket.sumMs, [...bucket.bins]]));\n}\n\nexport function decodeLatency(text: string): PackedLatency {\n\ttry {\n\t\tconst stored = JSON.parse(text) as StoredBucket[];\n\t\treturn packLatency(stored.map(([from, count, sumMs, bins]) => ({ from, count, sumMs, bins })));\n\t} catch {\n\t\treturn NO_LATENCY;\n\t}\n}\n","import type { CheckResult, CheckState } from \"@naosystem/cf-workers-status-page-core\";\n\n/**\n * What a runner sends back to the Monitor DO for one check. Plain data, so that it\n * crosses RPC (and, later, the network from external runners) unchanged.\n */\nexport type CheckOutcome =\n\t| { readonly ok: true; readonly result: StoredResult }\n\t| { readonly ok: false; readonly error: CheckError };\n\n/** A check that produced a state, normalised for storage. */\nexport interface StoredResult {\n\treadonly state: CheckState;\n\treadonly latencyMs: number | null;\n\treadonly message: string | null;\n\t/** The provider's `details` as JSON text, or `null`. */\n\treadonly details: string | null;\n}\n\n/**\n * A check that produced no result: a missing secret, a provider exception, a runner that\n * gave up. Recorded without a state, so it neither confirms a state nor breaks a run,\n * and does not count as a result for coverage.\n */\nexport interface CheckError {\n\t/** Error class, such as `\"MissingSecretError\"`. */\n\treadonly name: string;\n\treadonly message: string;\n}\n\nexport const MAX_MESSAGE_LENGTH = 1_000;\nexport const MAX_DETAILS_LENGTH = 4_000;\n\nconst STATES: ReadonlySet<string> = new Set<CheckState>([\"up\", \"degraded\", \"down\"]);\n\nfunction truncate(text: string, max: number): string {\n\treturn text.length <= max ? text : `${text.slice(0, max - 1)}…`;\n}\n\nexport function checkError(error: unknown, fallbackName = \"Error\"): CheckError {\n\tif (error instanceof Error) {\n\t\treturn { name: error.name || fallbackName, message: truncate(error.message, MAX_MESSAGE_LENGTH) };\n\t}\n\treturn { name: fallbackName, message: truncate(String(error), MAX_MESSAGE_LENGTH) };\n}\n\n/**\n * Validates what a provider returned and bounds its size before it is stored. Providers\n * are third-party code: a result with an invalid state becomes an error rather than a\n * state, and oversized messages or details are cut down.\n */\nexport function normalizeResult(result: CheckResult): CheckOutcome {\n\tif (typeof result !== \"object\" || result === null || !STATES.has(result.state)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: {\n\t\t\t\tname: \"InvalidResultError\",\n\t\t\t\tmessage: `The provider returned an invalid state: ${JSON.stringify((result as { state?: unknown } | null)?.state)}`,\n\t\t\t},\n\t\t};\n\t}\n\tconst latency = result.latencyMs;\n\tlet details: string | null = null;\n\tif (result.details !== undefined) {\n\t\ttry {\n\t\t\tconst json = JSON.stringify(result.details);\n\t\t\tdetails = json.length <= MAX_DETAILS_LENGTH ? json : JSON.stringify({ truncated: true });\n\t\t} catch {\n\t\t\tdetails = JSON.stringify({ unserializable: true });\n\t\t}\n\t}\n\treturn {\n\t\tok: true,\n\t\tresult: {\n\t\t\tstate: result.state,\n\t\t\tlatencyMs: typeof latency === \"number\" && Number.isFinite(latency) && latency >= 0 ? Math.round(latency) : null,\n\t\t\tmessage: typeof result.message === \"string\" ? truncate(result.message, MAX_MESSAGE_LENGTH) : null,\n\t\t\tdetails,\n\t\t},\n\t};\n}\n","/** Sending to the notification queue. Kept apart so that the Monitor DO imports nothing else of notifications. */\nimport type { QueueBody } from \"./events\";\n\n/**\n * Queues limits (https://developers.cloudflare.com/queues/platform/limits/): 100 messages and\n * 256 KB per `sendBatch`, 128 KB per message, each message carrying about 100 bytes of\n * metadata. Batches stay below these with a margin.\n */\nexport const BATCH_MESSAGES = 100;\nexport const BATCH_BYTES = 192 * 1024;\nconst MESSAGE_OVERHEAD_BYTES = 200;\n\nconst encoder = new TextEncoder();\n\n/** `bodies` in batches of at most {@link BATCH_MESSAGES} messages and {@link BATCH_BYTES} bytes of JSON. */\nexport function batches(bodies: readonly QueueBody[]): QueueBody[][] {\n\tconst result: QueueBody[][] = [];\n\tlet current: QueueBody[] = [];\n\tlet bytes = 0;\n\tfor (const body of bodies) {\n\t\tconst size = encoder.encode(JSON.stringify(body)).byteLength + MESSAGE_OVERHEAD_BYTES;\n\t\tif (current.length > 0 && (current.length === BATCH_MESSAGES || bytes + size > BATCH_BYTES)) {\n\t\t\tresult.push(current);\n\t\t\tcurrent = [];\n\t\t\tbytes = 0;\n\t\t}\n\t\tcurrent.push(body);\n\t\tbytes += size;\n\t}\n\tif (current.length > 0) result.push(current);\n\treturn result;\n}\n\n/** Queues `bodies` as JSON, in batches within the limits. Resolves once Queues has stored them. */\nexport async function enqueue(env: Env, bodies: readonly QueueBody[]): Promise<void> {\n\tfor (const batch of batches(bodies)) {\n\t\tawait env.NOTIFICATIONS.sendBatch(batch.map((body) => ({ body, contentType: \"json\" as const })));\n\t}\n}\n","/**\n * Notification events and the queue messages that carry them.\n *\n * An event is something about one monitor that targets may be notified of. The Monitor DO\n * derives `down`, `recovered`, `degraded` and `degraded_recovered` from its confirmed state\n * changes ({@link eventsFromTransitions}), and `stopped` when a monitor leaves the configuration\n * while down (for automatic incidents only; no target receives it); the every-minute Cron emits\n * `unknown` and the `down` that maintenance held back once it ends. Every event has a\n * stable ID, derived from what it is about, so that sending it again (an alarm retrying after a\n * failed queue send, a duplicate queue delivery) is recognised downstream.\n *\n * A recovery (`recovered`, `degraded_recovered`) answers the event that began the state it\n * ends, whose ID {@link pairedEventIds} gives: it goes to the targets that event went to.\n *\n * The queue carries two kinds of message ({@link QueueBody}):\n * - `event`: one per event, sent by the Monitor DO or the Cron. The consumer applies\n * automatic incidents, decides whether maintenance suppresses it, and fans it out;\n * - `delivery`: one per event × target (one target's failure must not affect others).\n */\nimport {\n\tisCheckState,\n\ttype CheckState,\n\ttype NotificationEvent,\n\ttype NotificationState,\n\ttype StateRecord,\n} from \"@naosystem/cf-workers-status-page-core\";\n\n/** What an event is about: a notification event, or `stopped` (automatic incidents only). */\nexport type MonitorEventType = NotificationEvent | \"stopped\";\n\n/** Why a monitor is `unknown`: results late, never confirming a state, or its Durable Object not answering. */\nexport type UnknownReason = \"late\" | \"unconfirmed\" | \"unreachable\";\n\nexport interface MonitorEvent {\n\t/** Stable: the same each time this event is sent. */\n\treadonly id: string;\n\treadonly event: MonitorEventType;\n\treadonly monitorId: string;\n\t/** The state the event is about (for `recovered`, the state the monitor is in now). */\n\treadonly state: NotificationState;\n\treadonly previousState: NotificationState | null;\n\t/** When the state began: what notifications show as the time it happened. */\n\treadonly since: number;\n\t/**\n\t * When the event was detected: the confirmation of the state, or the Cron's run. Maintenance\n\t * suppresses an event when it covers this moment.\n\t */\n\treadonly detectedAt: number;\n\t/** When the previous state began, for how long it lasted; `null` when unknown. */\n\treadonly previousSince: number | null;\n\t/** The latest check's message at the time, such as \"HTTP 503\". */\n\treadonly message: string | null;\n\t/** Set on the `down` notified when maintenance that suppressed it ended. */\n\treadonly afterMaintenance?: true;\n\t/** For `unknown`: why, and the latest result (or the start of the schedule) it is late from. */\n\treadonly unknown?: { readonly reason: UnknownReason; readonly lastAt: number };\n}\n\n/** Longest check message carried by an event, so that queue messages stay small. */\nconst MAX_EVENT_MESSAGE = 500;\n\n/** A queue message (JSON). `v` is the format version, for messages queued by an older version during a deploy. */\nexport type QueueBody =\n\t| { readonly type: \"event\"; readonly v: 1; readonly event: MonitorEvent }\n\t| { readonly type: \"delivery\"; readonly v: 1; readonly event: MonitorEvent; readonly targetId: string };\n\nconst EVENTS: ReadonlySet<string> = new Set<MonitorEventType>([\n\t\"down\",\n\t\"recovered\",\n\t\"degraded\",\n\t\"degraded_recovered\",\n\t\"unknown\",\n\t\"stopped\",\n]);\n\nfunction isEvent(value: unknown): value is MonitorEvent {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst event = value as Record<string, unknown>;\n\treturn (\n\t\ttypeof event[\"id\"] === \"string\" &&\n\t\ttypeof event[\"monitorId\"] === \"string\" &&\n\t\ttypeof event[\"event\"] === \"string\" &&\n\t\tEVENTS.has(event[\"event\"]) &&\n\t\ttypeof event[\"since\"] === \"number\" &&\n\t\ttypeof event[\"detectedAt\"] === \"number\"\n\t);\n}\n\n/** The body if it is a message this version understands, else `null` (it is then dropped and logged). */\nexport function parseQueueBody(body: unknown): QueueBody | null {\n\tif (typeof body !== \"object\" || body === null) return null;\n\tconst message = body as Record<string, unknown>;\n\tif (message[\"v\"] !== 1 || !isEvent(message[\"event\"])) return null;\n\tif (message[\"type\"] === \"event\") return body as QueueBody;\n\tif (message[\"type\"] === \"delivery\" && typeof message[\"targetId\"] === \"string\") return body as QueueBody;\n\treturn null;\n}\n\n/**\n * The event a change of state makes, or `null`:\n * - to `down`: `down`, unless the record before was already `down`;\n * - from `down` to `up` or `degraded`: `recovered` (a partial one to `degraded`);\n * - to `degraded` from `up` or from no confirmed state: `degraded`;\n * - from `degraded` to `up`: `degraded_recovered`;\n * - to `stopped` (the monitor left the configuration) from `down` or `degraded`: `stopped`.\n *\n * `previous` is the record just before. For a recovery, `lastConfirmed` (the latest `up`,\n * `degraded` or `down` before it, looking past `unconfirmed` and `stopped`) stands in for it,\n * so that a monitor that stopped or resumed while down still reports its recovery. A first\n * `up` with no confirmed state before is not an event; a first `down` is.\n */\nexport function classifyChange(previous: string | null, next: string, lastConfirmed: string | null = previous): MonitorEventType | null {\n\tconst before: CheckState | null = previous !== null && isCheckState(previous) ? previous : null;\n\t// While degraded after a partial recovery, the monitor may still be announced in an incident.\n\tif (next === \"stopped\") return before === \"down\" || before === \"degraded\" ? \"stopped\" : null;\n\tif (!isCheckState(next)) return null;\n\tif (next === \"down\") return before === \"down\" ? null : \"down\";\n\tconst base: CheckState | null = before ?? (lastConfirmed !== null && isCheckState(lastConfirmed) ? lastConfirmed : null);\n\tif (base === next) return null;\n\tif (base === \"down\") return \"recovered\";\n\tif (next === \"degraded\") return \"degraded\";\n\tif (base === \"degraded\") return \"degraded_recovered\";\n\treturn null;\n}\n\n/** The ID of the event of the state record that began at `since`. */\nexport function transitionEventId(monitorId: string, since: number): string {\n\treturn `${monitorId}:${since}`;\n}\n\n/**\n * The IDs under which the event that a recovery answers may have been sent: the change that\n * began the state it ends, and the same `down` notified once maintenance ended.\n * Empty for other events.\n */\nexport function pairedEventIds(event: Pick<MonitorEvent, \"event\" | \"monitorId\" | \"previousSince\">): string[] {\n\tif ((event.event !== \"recovered\" && event.event !== \"degraded_recovered\") || event.previousSince === null) return [];\n\tconst id = transitionEventId(event.monitorId, event.previousSince);\n\treturn event.event === \"recovered\" ? [id, `${id}:after-maintenance`] : [id];\n}\n\nfunction truncate(message: string | null): string | null {\n\treturn message === null || message.length <= MAX_EVENT_MESSAGE ? message : `${message.slice(0, MAX_EVENT_MESSAGE - 1)}…`;\n}\n\n/**\n * The events of state records not notified yet (`pending`, oldest first), each compared with\n * the record before it: `before` for the first (the latest record already notified), with\n * `lastConfirmed` the latest confirmed record (`up`, `degraded` or `down`) at or before it.\n * `messageAt` gives the latest check's message when a record was confirmed.\n */\nexport function eventsFromTransitions(\n\tmonitorId: string,\n\tbefore: StateRecord | null,\n\tpending: readonly StateRecord[],\n\tmessageAt: (record: StateRecord) => string | null,\n\tlastConfirmed: StateRecord | null = before !== null && isCheckState(before.state) ? before : null,\n): MonitorEvent[] {\n\tconst events: MonitorEvent[] = [];\n\tlet previous = before;\n\tlet confirmed = lastConfirmed;\n\tfor (const record of pending) {\n\t\tconst event = classifyChange(previous?.state ?? null, record.state, confirmed?.state ?? null);\n\t\tif (event !== null) {\n\t\t\t// A recovery is about the confirmed state it ends, even across a stop.\n\t\t\tconst from = event === \"recovered\" || event === \"degraded_recovered\" ? confirmed : previous;\n\t\t\tevents.push({\n\t\t\t\tid: transitionEventId(monitorId, record.since),\n\t\t\t\tevent,\n\t\t\t\tmonitorId,\n\t\t\t\t// A stopped monitor shows as unknown.\n\t\t\t\tstate: event === \"stopped\" ? \"unknown\" : (record.state as CheckState),\n\t\t\t\tpreviousState: from !== null && isCheckState(from.state) ? from.state : null,\n\t\t\t\tsince: record.since,\n\t\t\t\tdetectedAt: record.confirmedAt,\n\t\t\t\tpreviousSince: from?.since ?? null,\n\t\t\t\tmessage: truncate(messageAt(record)),\n\t\t\t});\n\t\t}\n\t\tprevious = record;\n\t\tif (isCheckState(record.state)) confirmed = record;\n\t}\n\treturn events;\n}\n\n/** The `down` notified when the maintenance that suppressed `event` has ended, detected at `now`. */\nexport function afterMaintenanceEvent(event: MonitorEvent, now: number): MonitorEvent {\n\tconst id = event.afterMaintenance ? event.id : `${event.id}:after-maintenance`;\n\treturn { ...event, id, detectedAt: now, afterMaintenance: true };\n}\n","/**\n * Scheduling for the Monitor DO's single alarm, and the arithmetic of its schedule\n * periods. Pure functions, so they are tested without a Durable Object.\n */\n\nimport type { SchedulePeriod, TimeRange } from \"@naosystem/cf-workers-status-page-core\";\n\n// Defined in core, which the status pages' history computation shares.\nexport type { SchedulePeriod, TimeRange };\n\n/**\n * How early a check may start and still count for its slot. Alarms fire at or after the\n * time they were set for; this only absorbs clock adjustments when a Durable Object moves.\n */\nconst SLOT_TOLERANCE_MS = 1_000;\n\n/**\n * Scheduled checks run on a fixed grid, `anchor + k × interval`, where `anchor` is the start\n * of the current schedule period. Anchoring to the grid rather than to the end of the\n * previous check keeps the schedule from drifting by the length of each check and of each\n * alarm delay.\n *\n * Returns the slot after the one that the last scheduled check (`lastScheduledAt`) belongs\n * to. That can be in the past after downtime: the check then runs once, now, and belongs to\n * the current slot, so missed slots are not made up one by one.\n *\n * With no scheduled check recorded in this period, it returns `anchor` while the period is\n * younger than one interval (its first check), and otherwise the grid's next slot from\n * `now`: the period's results may have been deleted, and the grid, not the missing rows,\n * decides when to check.\n */\nexport function nextScheduledCheck(\n\tanchor: number,\n\tintervalMs: number,\n\tlastScheduledAt: number | null,\n\tnow: number,\n): number {\n\tif (lastScheduledAt === null || lastScheduledAt < anchor - SLOT_TOLERANCE_MS) {\n\t\tif (now - anchor < intervalMs) return anchor;\n\t\treturn anchor + Math.ceil((now - anchor) / intervalMs) * intervalMs;\n\t}\n\tconst tolerance = Math.min(SLOT_TOLERANCE_MS, intervalMs / 10);\n\tconst slot = Math.floor((lastScheduledAt - anchor + tolerance) / intervalMs);\n\treturn anchor + (slot + 1) * intervalMs;\n}\n\n/** Number of slots of the grid `anchor + k × interval` in `[from, to)`, counting none before `anchor`. */\nexport function slotsBetween(anchor: number, intervalMs: number, from: number, to: number): number {\n\tconst start = Math.max(from, anchor);\n\tif (to <= start) return 0;\n\tconst first = Math.ceil((start - anchor) / intervalMs);\n\tconst last = Math.ceil((to - anchor) / intervalMs);\n\treturn last - first;\n}\n\n/** The part of each active period inside `range`, oldest first. */\nexport function activeParts(periods: readonly SchedulePeriod[], range: TimeRange): TimeRange[] {\n\tconst parts: TimeRange[] = [];\n\tfor (const period of periods) {\n\t\tif (period.status !== \"active\") continue;\n\t\tconst from = Math.max(range.from, period.from);\n\t\tconst to = Math.min(range.to, period.to ?? Number.POSITIVE_INFINITY);\n\t\tif (from < to) parts.push({ from, to });\n\t}\n\treturn parts;\n}\n\n/**\n * Scheduled checks expected in `range`: the slots of each active period's\n * grid that fall inside the range. Stopped periods expect none.\n */\nexport function expectedChecks(periods: readonly SchedulePeriod[], range: TimeRange): number {\n\tlet count = 0;\n\tfor (const period of periods) {\n\t\tif (period.status !== \"active\" || period.intervalMs === null) continue;\n\t\tconst to = Math.min(range.to, period.to ?? Number.POSITIVE_INFINITY);\n\t\tcount += slotsBetween(period.from, period.intervalMs, Math.max(range.from, period.from), to);\n\t}\n\treturn count;\n}\n\n/** `ranges` intersected with `within` (both sorted and non-overlapping). */\nexport function intersect(ranges: readonly TimeRange[], within: readonly TimeRange[]): TimeRange[] {\n\tconst result: TimeRange[] = [];\n\tfor (const range of ranges) {\n\t\tfor (const part of within) {\n\t\t\tconst from = Math.max(range.from, part.from);\n\t\t\tconst to = Math.min(range.to, part.to);\n\t\t\tif (from < to) result.push({ from, to });\n\t\t}\n\t}\n\treturn result;\n}\n","/**\n * Helpers for a Durable Object's SQLite storage: versioned schema migrations, and counters\n * of the rows each operation reads and writes (the unit Durable Objects bill by).\n */\n\n/** One schema change. Versions start at 1 and never change once released. */\nexport interface Migration {\n\treadonly version: number;\n\treadonly description: string;\n\t/** Runs in the migration's transaction; `storage` also gives the key-value API. */\n\treadonly up: (sql: SqlStorage, storage: DurableObjectStorage) => void;\n}\n\n/** Where the schema version is kept (key-value storage). */\nexport const SCHEMA_VERSION_KEY = \"schema.version\";\n\n/**\n * Applies the migrations newer than the stored schema version, each in its own\n * transaction together with the new version number. Run it in the constructor inside\n * `blockConcurrencyWhile`, so that no request sees a half-migrated schema.\n *\n * Migrations must be additive, so that a rollback to older code keeps working on the newer\n * schema: add tables and nullable (or defaulted) columns; never rename, drop or change the\n * meaning of what older code reads or writes; always name columns in INSERT and SELECT.\n * When the stored version is newer than the code knows, this logs a warning and leaves the\n * schema as it is.\n *\n * The version is kept in the synchronous KV API, because Durable Objects do not allow\n * `PRAGMA user_version`. Returns the number of migrations applied.\n *\n * @throws Error if `migrations` is not numbered 1, 2, 3, …\n */\nexport function migrate(storage: DurableObjectStorage, migrations: readonly Migration[]): number {\n\tmigrations.forEach((migration, index) => {\n\t\tif (migration.version !== index + 1) {\n\t\t\tthrow new Error(`Migration ${index} has version ${migration.version}; expected ${index + 1}`);\n\t\t}\n\t});\n\tconst current = schemaVersion(storage) ?? 0;\n\tif (current > migrations.length) {\n\t\tconsole.warn(\n\t\t\t`Storage schema version ${current} is newer than this code knows (${migrations.length}), ` +\n\t\t\t\t\"probably after a rollback. Continuing: migrations are additive.\",\n\t\t);\n\t\treturn 0;\n\t}\n\tconst pending = migrations.slice(current);\n\tfor (const migration of pending) {\n\t\tstorage.transactionSync(() => {\n\t\t\tmigration.up(storage.sql, storage);\n\t\t\tstorage.kv.put(SCHEMA_VERSION_KEY, migration.version);\n\t\t});\n\t}\n\treturn pending.length;\n}\n\n/**\n * The stored schema version, or `undefined` when the object has never been migrated. Reading\n * it does not create storage, so an object can check whether it has data without bringing\n * an empty database into existence.\n */\nexport function schemaVersion(storage: DurableObjectStorage): number | undefined {\n\treturn storage.kv.get<number>(SCHEMA_VERSION_KEY);\n}\n\n/** Rows read and written, as reported by SQL cursors, plus key-value and alarm writes. */\nexport interface StorageUsage {\n\trowsRead: number;\n\trowsWritten: number;\n}\n\n/**\n * Key under which a Durable Object exposes its {@link StorageUsage} to tests. A symbol, so\n * that it is not reachable over RPC.\n */\nexport const STORAGE_USAGE: unique symbol = Symbol(\"storageUsage\");\n\n/**\n * Thin wrapper around `ctx.storage` that counts rows. SQL counts come from each cursor's\n * `rowsRead`/`rowsWritten` (which include index updates). Each `setAlarm()`,\n * `deleteAlarm()` and key-value `put()` is counted as one written row.\n */\nexport class MeteredStorage {\n\treadonly usage: StorageUsage = { rowsRead: 0, rowsWritten: 0 };\n\treadonly storage: DurableObjectStorage;\n\n\tconstructor(storage: DurableObjectStorage) {\n\t\tthis.storage = storage;\n\t}\n\n\t/** Runs a statement and returns all rows. */\n\tall<T extends Record<string, SqlStorageValue>>(query: string, ...bindings: unknown[]): T[] {\n\t\tconst cursor = this.storage.sql.exec<T>(query, ...bindings);\n\t\tconst rows = cursor.toArray();\n\t\tthis.usage.rowsRead += cursor.rowsRead;\n\t\tthis.usage.rowsWritten += cursor.rowsWritten;\n\t\treturn rows;\n\t}\n\n\t/** Runs a statement and returns its first row, if any. */\n\tfirst<T extends Record<string, SqlStorageValue>>(query: string, ...bindings: unknown[]): T | undefined {\n\t\treturn this.all<T>(query, ...bindings)[0];\n\t}\n\n\t/** Runs a statement that returns no rows, and returns the rows it wrote. */\n\trun(query: string, ...bindings: unknown[]): number {\n\t\tconst before = this.usage.rowsWritten;\n\t\tthis.all(query, ...bindings);\n\t\treturn this.usage.rowsWritten - before;\n\t}\n\n\tkvGet<T>(key: string): T | undefined {\n\t\tthis.usage.rowsRead += 1;\n\t\treturn this.storage.kv.get<T>(key);\n\t}\n\n\tkvPut(key: string, value: unknown): void {\n\t\tthis.usage.rowsWritten += 1;\n\t\tthis.storage.kv.put(key, value);\n\t}\n\n\ttransaction<T>(closure: () => T): T {\n\t\treturn this.storage.transactionSync(closure);\n\t}\n\n\tgetAlarm(): Promise<number | null> {\n\t\treturn this.storage.getAlarm();\n\t}\n\n\tasync setAlarm(at: number): Promise<void> {\n\t\tthis.usage.rowsWritten += 1;\n\t\tawait this.storage.setAlarm(at);\n\t}\n\n\tasync deleteAlarm(): Promise<void> {\n\t\tthis.usage.rowsWritten += 1;\n\t\tawait this.storage.deleteAlarm();\n\t}\n}\n","import { DurableObject } from \"cloudflare:workers\";\nimport {\n\ttype CheckState,\n\ttype Confirmation,\n\tisCheckState,\n\ttype ConfirmedState,\n\tconfirmState,\n\ttype LocationHint,\n\tmonitorTimeline,\n\ttype Observation,\n\tobservationsNeeded,\n\ttype RecordedState,\n\ttype ResolvedMonitor,\n\tLATE_GRACE_MS,\n\ttype Segment,\n\ttype StateRecord,\n\tstaleAfterMs,\n} from \"@naosystem/cf-workers-status-page-core\";\nimport { type CheckOutcome, checkError } from \"./check-result\";\nimport { aggregateLatency, type LatencyBucket } from \"./latency\";\nimport { config, findMonitor } from \"./config\";\nimport { enqueue } from \"./notifications/queue\";\nimport { eventsFromTransitions } from \"./notifications/events\";\nimport { RUNNER_GRACE_MS } from \"./runners\";\nimport {\n\tactiveParts,\n\texpectedChecks,\n\tintersect,\n\tnextScheduledCheck,\n\ttype SchedulePeriod,\n\ttype TimeRange,\n} from \"./schedule\";\nimport { MeteredStorage, type Migration, migrate, STORAGE_USAGE, type StorageUsage, schemaVersion } from \"./storage\";\n\nexport type { SchedulePeriod, TimeRange } from \"./schedule\";\n\n// ---------------------------------------------------------------------------\n// RPC types, for the Reconciler, the admin API, status pages and notifications\n// ---------------------------------------------------------------------------\n\n// The state history's types are defined in core, which computes timelines from them.\nexport type { RecordedState, StateRecord } from \"@naosystem/cf-workers-status-page-core\";\n\nexport interface SyncRequest {\n\t/** The location hint the caller passed to `getByName()` (see {@link monitorStub}). */\n\treadonly location: LocationHint | null;\n}\n\nexport interface SyncResult {\n\t/**\n\t * What the object did to match the configuration of the version it runs:\n\t * - `started`: started for the first time; `resumed`: was stopped, is back in the configuration;\n\t * - `running`: was already running (an interval change was applied, if any);\n\t * - `stopped`: not in the configuration, so its checks are stopped (its data is kept);\n\t * - `absent`: not in the configuration and has no data, so nothing was stored.\n\t */\n\treadonly status: \"started\" | \"resumed\" | \"running\" | \"stopped\" | \"absent\";\n\t/** Whether the monitor is in the configuration of the version this object runs. */\n\treadonly configured: boolean;\n\t/** Version of the Worker this object runs (`CF_VERSION_METADATA.id`). */\n\treadonly versionId: string;\n\t/** When the alarm is set for; `null` while the alarm is running or when stopped. */\n\treadonly nextAlarmAt: number | null;\n\t/** The location hint the object was created with, once it has started. */\n\treadonly location: LocationHint | null;\n\t/** Present when the configured location differs from the one the object was created with. */\n\treadonly locationMismatch?: { readonly created: LocationHint | null; readonly configured: LocationHint | null };\n\t/**\n\t * The current state, as `getSnapshot()` returns it, for a configured monitor; `null`\n\t * otherwise. The Reconciler uses it to know when the monitor could next become `unknown`, so that its sweeps save it reading the monitor again.\n\t */\n\treadonly snapshot: MonitorSnapshot | null;\n}\n\nexport interface PurgeRequest {\n\t/** The version the caller runs: the purge is refused while this object runs another one. */\n\treadonly versionId: string;\n}\n\n/** Why a purge was refused, for clients to say in their language (`reason` is English). */\nexport type PurgeRefusal = \"configured\" | \"running\" | \"deploying\";\n\nexport type PurgeResult =\n\t| { readonly status: \"purged\" }\n\t| { readonly status: \"refused\"; readonly reason: string; readonly code?: PurgeRefusal };\n\n/** The latest check of any outcome. */\nexport interface LastCheck {\n\treadonly at: number;\n\treadonly runner: string;\n\t/** `null` when the check produced no result (see `CheckError`). */\n\treadonly state: CheckState | null;\n\treadonly latencyMs: number | null;\n\treadonly message: string | null;\n}\n\nexport interface MonitorSnapshot {\n\treadonly monitorId: string;\n\t/** Whether the monitor is in the configuration of the version this object runs. */\n\treadonly configured: boolean;\n\t/** When the monitor first started, or `null` if it never has (and nothing is stored). */\n\treadonly startedAt: number | null;\n\t/** The current schedule period: `active` with its interval, or `stopped`. */\n\treadonly period: SchedulePeriod | null;\n\t/** The latest state record: the confirmed state, or `stopped`. */\n\treadonly current: StateRecord | null;\n\t/**\n\t * `lastCheck` and `lastResultAt` look back to here only: a few intervals, and never before\n\t * the monitor last resumed. So reading them costs a few rows however long a monitor has\n\t * failed to produce results. `null` with no data.\n\t */\n\treadonly recentSince: number | null;\n\t/** The latest check since `recentSince`, of any outcome. */\n\treadonly lastCheck: LastCheck | null;\n\t/**\n\t * Start of the latest check since `recentSince` that produced a state; `null` when none\n\t * did. `unknown` is derived from this and the period's interval at display time;\n\t * checks that keep failing to produce a result (a missing secret) make a monitor\n\t * `unknown`, not `down`.\n\t */\n\treadonly lastResultAt: number | null;\n}\n\nexport interface TransitionHistory {\n\t/** The record in effect at `range.from` (its `since` is at or before `from`). */\n\treadonly atStart: StateRecord | null;\n\t/** Records with `since` inside `(from, to)`, oldest first. */\n\treadonly changes: StateRecord[];\n}\n\nexport interface ResultCounts extends TimeRange {\n\t/** Scheduled checks the schedule periods expected in the range: the denominator of coverage. */\n\treadonly expected: number;\n\t/** Scheduled checks that produced a state: the numerator of coverage. */\n\treadonly scheduled: number;\n\t/** Scheduled checks that produced no result. */\n\treadonly scheduledErrors: number;\n\t/** Re-checks after a failure, of any outcome. Not part of coverage. */\n\treadonly rechecks: number;\n}\n\nexport interface TimelineRequest {\n\t/**\n\t * Ranges to describe, not overlapping, most wanted first. Each is cut at the object's\n\t * current time.\n\t */\n\treadonly ranges: readonly TimeRange[];\n\t/** The monitor's `timeout`, for the lateness threshold (`staleAfterMs`). */\n\treadonly timeoutMs: number;\n\t/**\n\t * Once this many rows have been read, the remaining ranges are skipped (`null`). The first\n\t * range is always described, so a call reads at most this plus one range's rows.\n\t */\n\treadonly maxRows: number;\n\t/**\n\t * Response times of the results from this time on are summed into each slice's `latency`\n\t * (see latency.ts), from the rows read anyway. `null` or absent: none.\n\t */\n\treadonly latencySince?: number | null;\n}\n\n/** What one range of {@link TimelineRequest} looks like: the input of a status page's history. */\nexport interface TimelineSlice extends TimeRange {\n\t/** Scheduled checks the schedule expected in the range: the denominator of coverage. */\n\treadonly expected: number;\n\t/** Scheduled checks in the range that produced a state: the numerator of coverage. */\n\treadonly obtained: number;\n\t/** The display state over the range (see `monitorTimeline` in core); no segment where the monitor did not run. */\n\treadonly segments: readonly Segment[];\n\t/** Response times of the range's scheduled checks since `latencySince`, in 15-minute buckets; empty without it. */\n\treadonly latency: readonly LatencyBucket[];\n}\n\nexport interface TimelineResponse {\n\t/**\n\t * When the monitor first started; `null` when it has no data (never started, or purged).\n\t * Status pages key their cached days by it: a purged monitor that starts again is a new\n\t * history.\n\t */\n\treadonly startedAt: number | null;\n\t/**\n\t * One per requested range, in order; `null` for those skipped for `maxRows`. `to` is where\n\t * the description ends (at most now).\n\t */\n\treadonly slices: readonly (TimelineSlice | null)[];\n}\n\nexport interface RecentTransitionsRequest extends TimeRange {\n\t/** Records to return at most, newest first. */\n\treadonly limit: number;\n\t/**\n\t * Only records with `since` after this (the newest one the caller has), instead of all\n\t * of the range: a status page keeps the list and asks for what is new.\n\t */\n\treadonly after?: number | null;\n}\n\n/** What a status page reads from a monitor in one call (one billed request) for all its views. */\nexport interface PageReadRequest {\n\t/** The monitor's `timeout`, for the lateness threshold. */\n\treadonly timeoutMs: number;\n\t/** Whether to return the current state (as `getSnapshot`). */\n\treadonly snapshot: boolean;\n\t/** History stretches, as `getTimeline`; empty for none. */\n\treadonly ranges: readonly TimeRange[];\n\treadonly maxRows: number;\n\t/** As `getTimeline`'s. */\n\treadonly latencySince?: number | null;\n\t/** State records for the stoppage history, as `getRecentTransitions`; `null` for none. */\n\treadonly transitions: RecentTransitionsRequest | null;\n}\n\nexport interface PageReadResponse extends TimelineResponse {\n\treadonly snapshot: MonitorSnapshot | null;\n\treadonly transitions: RecentTransitions | null;\n}\n\nexport interface RecentTransitions {\n\t/** The record in effect at `from`; `null` when there is none or when `truncated`. */\n\treadonly atStart: StateRecord | null;\n\t/** Records with `since` inside `(from, to)`, oldest first: the newest `limit` of them. */\n\treadonly changes: readonly StateRecord[];\n\t/** Whether older records inside the range were left out. */\n\treadonly truncated: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Storage\n// ---------------------------------------------------------------------------\n\n/**\n * Schema. Every write counts towards the Durable Object's written rows, and each index\n * adds a row per insert and delete, so there are no secondary indexes. There are no\n * CHECK constraints either: SQLite cannot change one without rebuilding the table, and\n * later phases may add states or kinds. Values are validated in code.\n *\n * - `results`: every check, re-checks included, keyed by start time × runner. A `WITHOUT\n * ROWID` table is stored in its primary key, so an insert writes exactly one row and time\n * ranges are read in key order. `state` is NULL for a check that produced no result.\n * - `transitions`: the state history, keyed by when each state began: confirmed states, and\n * `stopped` while the monitor was not configured. The latest row is the current state, so\n * no row is rewritten per check.\n * - `schedule_periods`: one row per change of schedule (start, interval change, stop,\n * resume). Each period lasts until the next one starts.\n *\n * Migrations are additive (see `migrate`): later phases add tables and never change these.\n *\n * Notifications add no table: a state record newer than the `notify.sent`\n * watermark (key-value storage) is the \"unsent\" marker. It is written in the same\n * transaction as the state change, by the state record itself, and cleared by moving the\n * watermark once the event is in the queue (see `flushNotifications`).\n */\nexport const MONITOR_MIGRATIONS: readonly Migration[] = [\n\t{\n\t\tversion: 1,\n\t\tdescription: \"results, state history and schedule periods\",\n\t\tup(sql) {\n\t\t\tsql.exec(`\n\t\t\t\tCREATE TABLE results (\n\t\t\t\t\tchecked_at INTEGER NOT NULL,\n\t\t\t\t\trunner TEXT NOT NULL,\n\t\t\t\t\tkind TEXT NOT NULL,\n\t\t\t\t\tstate TEXT,\n\t\t\t\t\tlatency_ms INTEGER,\n\t\t\t\t\tmessage TEXT,\n\t\t\t\t\tdetails TEXT,\n\t\t\t\t\tPRIMARY KEY (checked_at, runner)\n\t\t\t\t) WITHOUT ROWID\n\t\t\t`);\n\t\t\tsql.exec(`\n\t\t\t\tCREATE TABLE transitions (\n\t\t\t\t\tsince INTEGER PRIMARY KEY,\n\t\t\t\t\tstate TEXT NOT NULL,\n\t\t\t\t\tconfirmed_at INTEGER NOT NULL\n\t\t\t\t)\n\t\t\t`);\n\t\t\tsql.exec(`\n\t\t\t\tCREATE TABLE schedule_periods (\n\t\t\t\t\tstart INTEGER PRIMARY KEY,\n\t\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\t\tinterval_ms INTEGER\n\t\t\t\t)\n\t\t\t`);\n\t\t},\n\t},\n\t{\n\t\tversion: 2,\n\t\tdescription: \"notification watermark\",\n\t\tup(sql, storage) {\n\t\t\t// State changes recorded before notifications existed count as notified: an upgraded\n\t\t\t// monitor must not replay its history (and open or resolve old automatic incidents).\n\t\t\tconst latest = sql.exec<{ since: number | null }>(\"SELECT max(since) AS since FROM transitions\").one();\n\t\t\tstorage.kv.put(NOTIFIED_KEY, latest.since ?? 0);\n\t\t},\n\t},\n];\n\n/** `kind` of a result row. */\ntype CheckKind = \"scheduled\" | \"recheck\";\n\n/** Written once, when the monitor first starts. */\ninterface StartRecord {\n\treadonly startedAt: number;\n\t/** The location hint the object was created with. A Durable Object never moves. */\n\treadonly location: LocationHint | null;\n}\n\n/** Progress of deleting old results, within the current day's budget. */\ninterface RetentionState {\n\t/** Start of the current budget day. */\n\treadonly dayStart: number;\n\t/** Rows deleted since `dayStart`. */\n\treadonly deleted: number;\n\t/** Whether old results may remain (the last run stopped at its batch or the budget). */\n\treadonly backlog: boolean;\n\treadonly ranAt: number;\n}\n\nconst START_KEY = \"monitor.start\";\nconst RETENTION_KEY = \"retention.state\";\n/** `since` of the latest state record whose events are in the queue: newer records are unsent. */\nexport const NOTIFIED_KEY = \"notify.sent\";\n/** State records turned into events per flush; a longer backlog takes several. */\nconst NOTIFY_BATCH = 50;\n/** Retrying notifications that could not be queued: 30 seconds, then twice as long each time, up to 10 minutes. */\nconst NOTIFY_RETRY = { kind: \"notify\", failureBackoffMs: 30_000, maxFailureBackoffMs: 10 * 60_000 } as const;\n\nconst DAY_MS = 24 * 3_600_000;\n/**\n * Reads behind \"the latest check\" look back this many intervals (plus the confirmation\n * rule's needs), so that their cost does not grow with a monitor's history.\n */\nconst LOOKBACK_CHECKS = 10;\n/** A re-check that produced no result is retried up to this many times. */\nconst MAX_RECHECK_RETRIES = 2;\n/**\n * Old results deleted per day, per scheduled check of the day. Once retention is in\n * steady state, each check's result is deleted once, one row per check. A backlog (after\n * retention was shortened) is drained with at most half a row per check more, so the account's\n * daily write limit sized for the steady state is not exceeded by much; the backlog shrinks by\n * half a row per check, so it clears in about twice the time it took to build up.\n */\nconst RETENTION_DELETES_PER_CHECK = 1.5;\n/** Rows deleted per alarm; more batches follow `RETENTION_CONTINUE_MS` apart, within the day's budget. */\nconst RETENTION_BATCH = 1_000;\nconst RETENTION_CONTINUE_MS = 1_000;\n/** Minimum delay of the next alarm after one ran. */\nconst MIN_ALARM_DELAY_MS = 1_000;\n/** An alarm overdue by more than this has stopped firing; `sync()` sets it again. */\nconst OVERDUE_ALARM_MS = 60_000;\n\ntype ResultRow = {\n\tchecked_at: number;\n\trunner: string;\n\tstate: CheckState | null;\n\tlatency_ms: number | null;\n\tmessage: string | null;\n};\ntype TransitionRow = { since: number; state: RecordedState; confirmed_at: number };\ntype PeriodRow = { start: number; status: SchedulePeriod[\"status\"]; interval_ms: number | null };\n\nfunction toRecord(row: TransitionRow): StateRecord {\n\treturn { state: row.state, since: row.since, confirmedAt: row.confirmed_at };\n}\n\n/** Periods from rows ordered by start; each ends where the next begins. */\nfunction toPeriods(rows: readonly PeriodRow[]): SchedulePeriod[] {\n\treturn rows.map((row, index) => ({\n\t\tfrom: row.start,\n\t\tto: rows[index + 1]?.start ?? null,\n\t\tstatus: row.status,\n\t\tintervalMs: row.interval_ms,\n\t}));\n}\n\n/**\n * Something the single alarm wakes up for. The alarm is set to the earliest `next()`\n * of all of them. Each derives its deadline from durable state, so nothing is rewritten to\n * remember a deadline, and a restart, eviction or retried alarm recomputes the same plan.\n *\n * `notify` re-sends notifications that could not be queued. Later phases add\n * deadlines for results from external runners here.\n */\ninterface Work {\n\treadonly kind: \"check\" | \"retention\" | \"notify\";\n\t/** When this work is next due, or `null` when it has nothing to do. */\n\tnext(now: number): number | null;\n\trun(now: number): Promise<void>;\n\t/**\n\t * After `run` fails, the work waits at least this long, so that a persistent failure cannot\n\t * spin; with `maxFailureBackoffMs`, twice as long after each further failure, up to that.\n\t */\n\treadonly failureBackoffMs: number;\n\treadonly maxFailureBackoffMs?: number;\n}\n\n/** When the next check is due: the next slot on the schedule, or sooner to re-check a failure. */\ninterface CheckPlan {\n\treadonly scheduledAt: number;\n\treadonly recheckAt: number | null;\n}\n\n/**\n * Stub for a monitor's Durable Object. Always use this, never `getByName()` directly: only\n * the first `get()` of an object applies the location hint, so every caller must pass it.\n */\nexport function monitorStub(env: Env, monitor: { readonly id: string; readonly location?: LocationHint | null }) {\n\treturn env.MONITOR.getByName(monitor.id, monitor.location ? { locationHint: monitor.location } : {});\n}\n\n/**\n * How far back a snapshot looks for the latest result: `LOOKBACK_CHECKS` intervals, and at\n * least the lateness threshold (`staleAfterMs`, which is under 3 intervals plus\n * `LATE_GRACE_MS` since a timeout is shorter than the interval), so that a result recent\n * enough to keep a monitor from being late is always found, however short the interval.\n */\nexport function recentLookbackMs(intervalMs: number): number {\n\treturn Math.max(LOOKBACK_CHECKS * intervalMs, 3 * intervalMs + LATE_GRACE_MS);\n}\n\n/** Margin on top of {@link settledAfterMs}, for alarm delays and clocks of different objects. */\nconst SETTLE_MARGIN_MS = 60_000;\n\n/**\n * How long after a moment a monitor's data about it can still change, so that a status page\n * may cache what it read about older moments. Results are recorded when a check ends\n * (its timeout plus the runners' grace after its start), and a confirmed state's `since`\n * reaches back to the start of the run that confirmed it: at most the confirmation rule's\n * observations plus `LOOKBACK_CHECKS` intervals (see `evaluate`). With the defaults, a\n * 1-minute interval and a 10-second timeout, 14 minutes 20 seconds.\n */\nexport function settledAfterMs(monitor: Pick<ResolvedMonitor, \"intervalMs\" | \"timeoutMs\" | \"confirmation\">): number {\n\treturn (\n\t\t(observationsNeeded(monitor.confirmation) + LOOKBACK_CHECKS) * monitor.intervalMs +\n\t\tmonitor.timeoutMs +\n\t\t2 * RUNNER_GRACE_MS +\n\t\tSETTLE_MARGIN_MS\n\t);\n}\n\n/**\n * One instance per monitor, named by the monitor ID and created with the monitor's location\n * as its `locationHint`. It schedules checks with its alarm, calls the runner, stores\n * every result per monitor × runner, applies the confirmation rule and keeps the state\n * history and schedule periods.\n *\n * The configuration comes from the version of the Worker the object runs. When the monitor\n * leaves it, the object stops checking but keeps its data; when it returns, the\n * object resumes with its history. Only `purge()` deletes the data.\n *\n * The read methods use stored data only, so they also answer for a removed monitor.\n */\nexport class Monitor extends DurableObject<Env> {\n\tprivate readonly store: MeteredStorage;\n\tprivate schemaReady = false;\n\tprivate alarmRunning = false;\n\t/** Per kind of work, after a failure. In memory only: an eviction just ends the backoff early. */\n\tprivate readonly backoffUntil = new Map<Work[\"kind\"], number>();\n\t/** Consecutive failures per kind of work, for growing backoffs. */\n\tprivate readonly failures = new Map<Work[\"kind\"], number>();\n\t/** Whether state records newer than the watermark exist; `undefined` until read. */\n\tprivate notifyPending: boolean | undefined;\n\t/** The flush in progress, so that flushes run one at a time. */\n\tprivate flushing: Promise<void> = Promise.resolve();\n\tprivate retentionResumeAt = 0;\n\tprivate locationWarned = false;\n\n\tconstructor(ctx: DurableObjectState, env: Env) {\n\t\tsuper(ctx, env);\n\t\tthis.store = new MeteredStorage(ctx.storage);\n\t\tctx.blockConcurrencyWhile(async () => {\n\t\t\tthis.open();\n\t\t});\n\t}\n\n\t/** Rows read and written by this instance; for tests. */\n\tget [STORAGE_USAGE](): StorageUsage {\n\t\treturn this.store.usage;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// RPC: lifecycle\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Brings the object in line with the configuration of the version it runs: starts or\n\t * resumes a configured monitor, applies an interval change, and makes sure its alarm is\n\t * set; stops a monitor that is no longer configured, keeping its data. Idempotent: when\n\t * nothing changed it writes nothing.\n\t */\n\tasync sync(request: SyncRequest): Promise<SyncResult> {\n\t\tconst versionId = this.env.CF_VERSION_METADATA.id;\n\t\tconst now = Date.now();\n\t\tconst monitor = this.configuredMonitor();\n\t\tif (monitor === undefined) {\n\t\t\tif (!this.open()) {\n\t\t\t\treturn { status: \"absent\", configured: false, versionId, nextAlarmAt: null, location: null, snapshot: null };\n\t\t\t}\n\t\t\tawait this.stop(now);\n\t\t\treturn {\n\t\t\t\tstatus: \"stopped\",\n\t\t\t\tconfigured: false,\n\t\t\t\tversionId,\n\t\t\t\tnextAlarmAt: null,\n\t\t\t\tlocation: this.startRecord()?.location ?? null,\n\t\t\t\tsnapshot: null,\n\t\t\t};\n\t\t}\n\t\tthis.open();\n\n\t\tlet start = this.startRecord();\n\t\tlet status: SyncResult[\"status\"] = \"running\";\n\t\tif (start === undefined) {\n\t\t\tconst record: StartRecord = { startedAt: now, location: request.location };\n\t\t\tthis.store.transaction(() => {\n\t\t\t\tthis.store.kvPut(START_KEY, record);\n\t\t\t\tthis.insertPeriod(now, \"active\", monitor.intervalMs);\n\t\t\t});\n\t\t\tstart = record;\n\t\t\tstatus = \"started\";\n\t\t} else if (this.syncSchedule(monitor, now) === \"resumed\") {\n\t\t\tstatus = \"resumed\";\n\t\t}\n\n\t\tconst configured = monitor.location ?? null;\n\t\tconst locationMismatch = start.location === configured ? undefined : { created: start.location, configured };\n\t\tif (locationMismatch !== undefined && !this.locationWarned) {\n\t\t\tthis.locationWarned = true;\n\t\t\tconsole.warn(\n\t\t\t\t`Monitor \"${monitor.id}\" is configured for location ${JSON.stringify(configured)}, but its Durable ` +\n\t\t\t\t\t`Object was created with ${JSON.stringify(start.location)} and cannot move. It keeps running where ` +\n\t\t\t\t\t\"it is. To check from the new location, give the monitor a new ID (its history starts over).\",\n\t\t\t);\n\t\t}\n\n\t\t// While the alarm runs, it sets the next alarm itself when it finishes.\n\t\tconst nextAlarmAt = this.alarmRunning ? null : await this.schedule(monitor, now, \"if-earlier\");\n\t\treturn {\n\t\t\tstatus,\n\t\t\tconfigured: true,\n\t\t\tversionId,\n\t\t\tnextAlarmAt,\n\t\t\tlocation: start.location,\n\t\t\t...(locationMismatch ? { locationMismatch } : {}),\n\t\t\tsnapshot: this.getSnapshot(),\n\t\t};\n\t}\n\n\t/**\n\t * Deletes all of a removed monitor's data (only on an administrator's request).\n\t * Refuses while the monitor is in the configuration of the version this object runs, and\n\t * while this object runs another version than the caller: during a deploy it may still\n\t * run code from before the monitor was added back.\n\t */\n\tasync purge(request: PurgeRequest): Promise<PurgeResult> {\n\t\tconst versionId = this.env.CF_VERSION_METADATA.id;\n\t\tif (request.versionId !== versionId) {\n\t\t\treturn {\n\t\t\t\tstatus: \"refused\",\n\t\t\t\treason: `The monitor's Durable Object runs another version (${versionId}); try again once the deploy has finished`,\n\t\t\t\tcode: \"deploying\",\n\t\t\t};\n\t\t}\n\t\tif (this.configuredMonitor() !== undefined) {\n\t\t\treturn { status: \"refused\", reason: \"The monitor is in the configuration; remove it from status.config.ts first\", code: \"configured\" };\n\t\t}\n\t\t// Also deletes the alarm (compatibility date 2026-02-24 and later).\n\t\tawait this.ctx.storage.deleteAll();\n\t\tthis.schemaReady = false;\n\t\tthis.notifyPending = undefined;\n\t\tconsole.log(`Monitor \"${this.monitorId()}\": deleted all its data`);\n\t\treturn { status: \"purged\" };\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// RPC: reads. They use stored data only, never the configuration.\n\t// -------------------------------------------------------------------------\n\n\t/** The current state, for status pages and `unknown` detection. Reads a few rows. */\n\tgetSnapshot(): MonitorSnapshot {\n\t\tconst monitorId = this.monitorId();\n\t\tconst configured = this.configuredMonitor() !== undefined;\n\t\tconst empty: MonitorSnapshot = {\n\t\t\tmonitorId,\n\t\t\tconfigured,\n\t\t\tstartedAt: null,\n\t\t\tperiod: null,\n\t\t\tcurrent: null,\n\t\t\trecentSince: null,\n\t\t\tlastCheck: null,\n\t\t\tlastResultAt: null,\n\t\t};\n\t\tif (!this.open()) return empty;\n\t\tconst period = this.currentPeriod();\n\t\tif (period === null) return empty;\n\n\t\tconst recentSince = this.recentFloor(period, Date.now());\n\t\tconst last = this.store.first<ResultRow>(\n\t\t\t`SELECT checked_at, runner, state, latency_ms, message FROM results\n\t\t\tWHERE checked_at >= ? ORDER BY checked_at DESC LIMIT 1`,\n\t\t\trecentSince,\n\t\t);\n\t\tconst lastResultAt =\n\t\t\tlast === undefined\n\t\t\t\t? null\n\t\t\t\t: last.state !== null\n\t\t\t\t\t? last.checked_at\n\t\t\t\t\t: (this.store.first<{ checked_at: number }>(\n\t\t\t\t\t\t\t`SELECT checked_at FROM results WHERE checked_at >= ? AND state IS NOT NULL\n\t\t\t\t\t\t\tORDER BY checked_at DESC LIMIT 1`,\n\t\t\t\t\t\t\trecentSince,\n\t\t\t\t\t\t)?.checked_at ?? null);\n\t\treturn {\n\t\t\tmonitorId,\n\t\t\tconfigured,\n\t\t\tstartedAt: this.startRecord()?.startedAt ?? null,\n\t\t\tperiod,\n\t\t\tcurrent: this.currentState(),\n\t\t\trecentSince,\n\t\t\tlastCheck: last\n\t\t\t\t? {\n\t\t\t\t\t\tat: last.checked_at,\n\t\t\t\t\t\trunner: last.runner,\n\t\t\t\t\t\tstate: last.state,\n\t\t\t\t\t\tlatencyMs: last.latency_ms,\n\t\t\t\t\t\tmessage: last.message,\n\t\t\t\t\t}\n\t\t\t\t: null,\n\t\t\tlastResultAt,\n\t\t};\n\t}\n\n\t/**\n\t * The state history over a time range, for uptime and the stoppage history and\n\t * notifications. `stopped` records mark where the monitor was not configured: that\n\t * time is neither uptime nor downtime. Reads one row per record, plus one.\n\t */\n\tgetTransitions(range: TimeRange): TransitionHistory {\n\t\tif (!this.open()) return { atStart: null, changes: [] };\n\t\tconst atStart = this.store.first<TransitionRow>(\n\t\t\t\"SELECT since, state, confirmed_at FROM transitions WHERE since <= ? ORDER BY since DESC LIMIT 1\",\n\t\t\trange.from,\n\t\t);\n\t\tconst changes = this.store.all<TransitionRow>(\n\t\t\t\"SELECT since, state, confirmed_at FROM transitions WHERE since > ? AND since < ? ORDER BY since\",\n\t\t\trange.from,\n\t\t\trange.to,\n\t\t);\n\t\treturn { atStart: atStart ? toRecord(atStart) : null, changes: changes.map(toRecord) };\n\t}\n\n\t/** The schedule periods that overlap `range`, oldest first. */\n\tgetSchedule(range: TimeRange): SchedulePeriod[] {\n\t\tif (!this.open()) return [];\n\t\treturn this.periodsOverlapping(range);\n\t}\n\n\t/**\n\t * Result counts per time range for coverage, with the number of checks the schedule\n\t * expected. Reads every result in the ranges, so callers should count past days once and\n\t * cache them.\n\t */\n\tcountResults(ranges: readonly TimeRange[]): ResultCounts[] {\n\t\tconst available = this.open();\n\t\treturn ranges.map((range) => {\n\t\t\tconst counts = { ...range, expected: 0, scheduled: 0, scheduledErrors: 0, rechecks: 0 };\n\t\t\tif (!available) return counts;\n\t\t\tcounts.expected = expectedChecks(this.periodsOverlapping(range), range);\n\t\t\tconst rows = this.store.all<{ kind: string; has_state: number; n: number }>(\n\t\t\t\t`SELECT kind, state IS NOT NULL AS has_state, count(*) AS n FROM results\n\t\t\t\tWHERE checked_at >= ? AND checked_at < ?\n\t\t\t\tGROUP BY kind, has_state`,\n\t\t\t\trange.from,\n\t\t\t\trange.to,\n\t\t\t);\n\t\t\tfor (const row of rows) {\n\t\t\t\tif (row.kind === \"scheduled\") {\n\t\t\t\t\tif (row.has_state) counts.scheduled += row.n;\n\t\t\t\t\telse counts.scheduledErrors += row.n;\n\t\t\t\t} else {\n\t\t\t\t\tcounts.rechecks += row.n;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn counts;\n\t\t});\n\t}\n\n\t/**\n\t * Where results are missing, for excluding `unknown` time from uptime: the stretches\n\t * inside `range` (up to now) and inside active schedule periods with no check that\n\t * produced a state for more than `minGapMs`. Each gap runs from the result before it (or\n\t * the start of the active time) to the result after it (or the end of the range). Reads\n\t * every result in the range.\n\t */\n\tgetResultGaps(range: TimeRange, minGapMs: number): TimeRange[] {\n\t\tif (!this.open()) return [];\n\t\tconst end = Math.min(range.to, Date.now());\n\t\tif (end <= range.from) return [];\n\t\tconst active = activeParts(this.periodsOverlapping(range), { from: range.from, to: end });\n\t\tconst gaps: TimeRange[] = [];\n\t\tfor (const part of active) {\n\t\t\tconst bounds = this.store.first<{ first: number | null; last: number | null }>(\n\t\t\t\t`SELECT min(checked_at) AS first, max(checked_at) AS last FROM results\n\t\t\t\tWHERE checked_at >= ? AND checked_at < ? AND state IS NOT NULL`,\n\t\t\t\tpart.from,\n\t\t\t\tpart.to,\n\t\t\t);\n\t\t\tif (bounds === undefined || bounds.first === null || bounds.last === null) {\n\t\t\t\tif (part.to - part.from > minGapMs) gaps.push(part);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (bounds.first - part.from > minGapMs) gaps.push({ from: part.from, to: bounds.first });\n\t\t\tconst inner = this.store.all<{ previous: number; checked_at: number }>(\n\t\t\t\t`SELECT previous, checked_at FROM (\n\t\t\t\t\tSELECT checked_at, lag(checked_at) OVER (ORDER BY checked_at) AS previous FROM results\n\t\t\t\t\tWHERE checked_at >= ? AND checked_at < ? AND state IS NOT NULL\n\t\t\t\t) WHERE checked_at - previous > ?`,\n\t\t\t\tpart.from,\n\t\t\t\tpart.to,\n\t\t\t\tminGapMs,\n\t\t\t);\n\t\t\tgaps.push(...inner.map((gap) => ({ from: gap.previous, to: gap.checked_at })));\n\t\t\tif (part.to - bounds.last > minGapMs) gaps.push({ from: bounds.last, to: part.to });\n\t\t}\n\t\treturn intersect(gaps, active);\n\t}\n\n\t/**\n\t * The display state over each range, with coverage counts, for a status page's history. Reads the schedule periods and state records of each range, and every result from\n\t * a little before it (the lateness threshold, to judge its start) to its end: a status\n\t * page asks for the stretches it has not cached yet, which keeps that small, and\n\t * `maxRows` bounds a call that fills many missing days.\n\t */\n\tgetTimeline(request: TimelineRequest): TimelineResponse {\n\t\tif (!this.open()) return { startedAt: null, slices: [] };\n\t\tconst startedAt = this.startRecord()?.startedAt ?? null;\n\t\tif (startedAt === null) return { startedAt: null, slices: [] };\n\t\tconst now = Date.now();\n\t\tconst staleAfter = (intervalMs: number) => staleAfterMs(intervalMs, request.timeoutMs);\n\t\tconst readBefore = this.store.usage.rowsRead;\n\t\tconst slices = request.ranges.map((requested, index): TimelineSlice | null => {\n\t\t\tif (index > 0 && this.store.usage.rowsRead - readBefore >= request.maxRows) return null;\n\t\t\tconst range = { from: requested.from, to: Math.max(requested.from, Math.min(requested.to, now)) };\n\t\t\tconst empty: TimelineSlice = { ...range, expected: 0, obtained: 0, segments: [], latency: [] };\n\t\t\tif (range.to <= range.from || range.to <= startedAt) return empty;\n\t\t\tconst periods = this.periodsOverlapping(range);\n\t\t\tconst intervals = periods.flatMap((period) => (period.status === \"active\" && period.intervalMs !== null ? [period.intervalMs] : []));\n\t\t\tif (intervals.length === 0) return empty;\n\n\t\t\tconst lookback = staleAfter(Math.max(...intervals));\n\t\t\tconst rows = this.store.all<{ checked_at: number; kind: string; has_state: number; latency_ms: number | null }>(\n\t\t\t\t`SELECT checked_at, kind, state IS NOT NULL AS has_state, latency_ms FROM results\n\t\t\t\tWHERE checked_at >= ? AND checked_at < ? ORDER BY checked_at`,\n\t\t\t\trange.from - lookback,\n\t\t\t\trange.to,\n\t\t\t);\n\t\t\t// Checks of the last few seconds may still be running: coverage counts the slots\n\t\t\t// whose results can be in, so that today's coverage does not dip while a check runs.\n\t\t\tconst countTo = Math.max(range.from, Math.min(range.to, now - request.timeoutMs - 2 * RUNNER_GRACE_MS));\n\t\t\tconst latencyFrom = request.latencySince == null ? Number.POSITIVE_INFINITY : Math.max(range.from, request.latencySince);\n\t\t\tlet obtained = 0;\n\t\t\tconst resultTimes: number[] = [];\n\t\t\tconst latencies: [number, number][] = [];\n\t\t\tfor (const row of rows) {\n\t\t\t\tif (!row.has_state) continue;\n\t\t\t\tresultTimes.push(row.checked_at);\n\t\t\t\tif (row.kind !== \"scheduled\") continue;\n\t\t\t\tif (row.checked_at >= range.from && row.checked_at < countTo) obtained++;\n\t\t\t\tif (row.latency_ms !== null && row.checked_at >= latencyFrom) latencies.push([row.checked_at, row.latency_ms]);\n\t\t\t}\n\t\t\tconst { atStart, changes } = this.getTransitions(range);\n\t\t\treturn {\n\t\t\t\t...range,\n\t\t\t\texpected: expectedChecks(periods, { from: range.from, to: countTo }),\n\t\t\t\tobtained,\n\t\t\t\tsegments: monitorTimeline(range, { periods, atStart, changes, resultTimes }, staleAfter),\n\t\t\t\tlatency: aggregateLatency(latencies),\n\t\t\t};\n\t\t});\n\t\treturn { startedAt, slices };\n\t}\n\n\t/**\n\t * The newest state records in a range, for the stoppage history. Reads at most\n\t * `limit + 2` rows, however long the history.\n\t */\n\tgetRecentTransitions(request: RecentTransitionsRequest): RecentTransitions {\n\t\tif (!this.open()) return { atStart: null, changes: [], truncated: false };\n\t\tconst after = request.after ?? null;\n\t\tconst rows = this.store.all<TransitionRow>(\n\t\t\t\"SELECT since, state, confirmed_at FROM transitions WHERE since > ? AND since < ? ORDER BY since DESC LIMIT ?\",\n\t\t\tMath.max(request.from, after ?? request.from),\n\t\t\trequest.to,\n\t\t\trequest.limit + 1,\n\t\t);\n\t\tconst truncated = rows.length > request.limit;\n\t\tconst changes = rows.slice(0, request.limit).reverse().map(toRecord);\n\t\tif (truncated || after !== null) return { atStart: null, changes, truncated };\n\t\tconst atStart = this.store.first<TransitionRow>(\n\t\t\t\"SELECT since, state, confirmed_at FROM transitions WHERE since <= ? ORDER BY since DESC LIMIT 1\",\n\t\t\trequest.from,\n\t\t);\n\t\treturn { atStart: atStart ? toRecord(atStart) : null, changes, truncated };\n\t}\n\n\t/**\n\t * Everything a status page needs from this monitor, in one call: each Durable Object call\n\t * is a billed request (and counts towards the Free plan's daily limit), so a page reads\n\t * its current state, history stretches and new state records together.\n\t */\n\treadForPage(request: PageReadRequest): PageReadResponse {\n\t\tconst timeline =\n\t\t\trequest.ranges.length > 0\n\t\t\t\t? this.getTimeline({\n\t\t\t\t\t\tranges: request.ranges,\n\t\t\t\t\t\ttimeoutMs: request.timeoutMs,\n\t\t\t\t\t\tmaxRows: request.maxRows,\n\t\t\t\t\t\tlatencySince: request.latencySince ?? null,\n\t\t\t\t\t})\n\t\t\t\t: { startedAt: this.open() ? (this.startRecord()?.startedAt ?? null) : null, slices: [] };\n\t\treturn {\n\t\t\t...timeline,\n\t\t\tsnapshot: request.snapshot ? this.getSnapshot() : null,\n\t\t\ttransitions: request.transitions === null ? null : this.getRecentTransitions(request.transitions),\n\t\t};\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Alarm\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Runs whatever is due (a check or re-check, deleting old results), then sets the alarm\n\t * to the earliest next deadline. Work is derived from stored results, so a retried or\n\t * duplicate alarm finds the check it already recorded and does not run it again.\n\t */\n\toverride async alarm(): Promise<void> {\n\t\tconst monitor = this.configuredMonitor();\n\t\tif (monitor === undefined) {\n\t\t\tif (this.open()) await this.stop(Date.now());\n\t\t\treturn;\n\t\t}\n\t\tthis.open();\n\t\t// An alarm before sync() cannot happen; if it does, the next sweep starts the monitor.\n\t\tif (this.startRecord() === undefined) return;\n\n\t\tconst now = Date.now();\n\t\tthis.syncSchedule(monitor, now);\n\t\tthis.alarmRunning = true;\n\t\ttry {\n\t\t\tfor (const work of this.works(monitor)) {\n\t\t\t\tconst due = this.nextOf(work, now);\n\t\t\t\tif (due === null || due > now) continue;\n\t\t\t\ttry {\n\t\t\t\t\tawait work.run(now);\n\t\t\t\t\tthis.failures.delete(work.kind);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.backOff(work);\n\t\t\t\t\tconsole.error(`Monitor \"${monitor.id}\": ${work.kind} failed`, error);\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.alarmRunning = false;\n\t\t}\n\t\t// If storage itself fails here, the alarm throws and the runtime retries it.\n\t\tawait this.schedule(monitor, Date.now(), \"after-alarm\");\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Internals\n\t// -------------------------------------------------------------------------\n\n\tprivate monitorId(): string {\n\t\tconst id = this.ctx.id.name;\n\t\t// Every caller uses monitorStub(); an object reached by `idFromString()` has no name.\n\t\tif (id === undefined) throw new Error(\"Monitor Durable Objects must be addressed by monitor ID\");\n\t\treturn id;\n\t}\n\n\tprivate configuredMonitor(): ResolvedMonitor | undefined {\n\t\treturn findMonitor(this.monitorId());\n\t}\n\n\t/**\n\t * Prepares the schema when the monitor is configured or the object already has data, and\n\t * returns whether storage is available. An object with no data whose monitor is not\n\t * configured stays empty: reading it must not create a database.\n\t */\n\tprivate open(): boolean {\n\t\tif (!this.schemaReady && (this.configuredMonitor() !== undefined || schemaVersion(this.ctx.storage) !== undefined)) {\n\t\t\tmigrate(this.ctx.storage, MONITOR_MIGRATIONS);\n\t\t\tthis.schemaReady = true;\n\t\t}\n\t\treturn this.schemaReady;\n\t}\n\n\tprivate startRecord(): StartRecord | undefined {\n\t\treturn this.store.kvGet<StartRecord>(START_KEY);\n\t}\n\n\t/** Results are stored per monitor × runner. Monitors have a single runner for now. */\n\tprivate runnerOf(monitor: ResolvedMonitor): string {\n\t\tconst runner = monitor.runners[0];\n\t\tif (runner === undefined) throw new Error(`Monitor \"${monitor.id}\" has no runner`);\n\t\treturn runner;\n\t}\n\n\t// ---- Schedule periods\n\n\tprivate currentPeriod(): SchedulePeriod | null {\n\t\tconst row = this.store.first<PeriodRow>(\n\t\t\t\"SELECT start, status, interval_ms FROM schedule_periods ORDER BY start DESC LIMIT 1\",\n\t\t);\n\t\treturn row ? { from: row.start, to: null, status: row.status, intervalMs: row.interval_ms } : null;\n\t}\n\n\t/** Periods that overlap `range`: the one in effect at `range.from` and those starting inside. */\n\tprivate periodsOverlapping(range: TimeRange): SchedulePeriod[] {\n\t\tconst first = this.store.first<{ start: number }>(\n\t\t\t\"SELECT start FROM schedule_periods WHERE start <= ? ORDER BY start DESC LIMIT 1\",\n\t\t\trange.from,\n\t\t);\n\t\tconst rows = this.store.all<PeriodRow>(\n\t\t\t\"SELECT start, status, interval_ms FROM schedule_periods WHERE start >= ? ORDER BY start\",\n\t\t\tfirst?.start ?? range.from,\n\t\t);\n\t\treturn toPeriods(rows).filter((period) => period.from < range.to);\n\t}\n\n\t/**\n\t * Start of the current run of active periods: results from before the monitor was last\n\t * stopped do not count towards its state after it resumed.\n\t */\n\tprivate activeSince(): number {\n\t\tconst stopped = this.store.first<{ start: number }>(\n\t\t\t\"SELECT start FROM schedule_periods WHERE status = 'stopped' ORDER BY start DESC LIMIT 1\",\n\t\t);\n\t\tif (stopped === undefined) return Number.NEGATIVE_INFINITY;\n\t\tconst resumed = this.store.first<{ start: number }>(\n\t\t\t\"SELECT start FROM schedule_periods WHERE start > ? ORDER BY start LIMIT 1\",\n\t\t\tstopped.start,\n\t\t);\n\t\treturn resumed?.start ?? Number.POSITIVE_INFINITY;\n\t}\n\n\t/** The interval of the latest active period, for bounding reads of a stopped monitor. */\n\tprivate lastInterval(period: SchedulePeriod): number {\n\t\tif (period.intervalMs !== null) return period.intervalMs;\n\t\treturn (\n\t\t\tthis.store.first<{ interval_ms: number }>(\n\t\t\t\t\"SELECT interval_ms FROM schedule_periods WHERE status = 'active' ORDER BY start DESC LIMIT 1\",\n\t\t\t)?.interval_ms ?? DAY_MS\n\t\t);\n\t}\n\n\t/**\n\t * How far back \"recent\" reads go (see {@link recentLookbackMs}) before now (or before the\n\t * stop), and for a running monitor never before it last resumed.\n\t */\n\tprivate recentFloor(period: SchedulePeriod, now: number): number {\n\t\tconst lookback = recentLookbackMs(this.lastInterval(period));\n\t\tif (period.status !== \"active\") return period.from - lookback;\n\t\treturn Math.max(this.activeSince(), now - lookback);\n\t}\n\n\tprivate insertPeriod(start: number, status: SchedulePeriod[\"status\"], intervalMs: number | null): void {\n\t\tthis.store.run(\"INSERT INTO schedule_periods (start, status, interval_ms) VALUES (?, ?, ?)\", start, status, intervalMs);\n\t}\n\n\t/**\n\t * Starts a new active period when the monitor resumes or its interval changed. Writes one\n\t * row then (two on resuming, which also ends the `stopped` state), and nothing otherwise.\n\t * The new period's grid starts now, so the first check of a resumed monitor or of a new\n\t * interval runs right away.\n\t */\n\tprivate syncSchedule(monitor: ResolvedMonitor, now: number): \"unchanged\" | \"resumed\" | \"changed\" {\n\t\tconst period = this.currentPeriod();\n\t\tif (period === null) {\n\t\t\tthis.insertPeriod(now, \"active\", monitor.intervalMs);\n\t\t\treturn \"changed\";\n\t\t}\n\t\tif (period.status === \"active\" && period.intervalMs === monitor.intervalMs) return \"unchanged\";\n\t\tconst start = Math.max(now, period.from + 1);\n\t\tif (period.status === \"stopped\") {\n\t\t\tthis.store.transaction(() => {\n\t\t\t\tthis.insertPeriod(start, \"active\", monitor.intervalMs);\n\t\t\t\t// Results from before the stop do not count; no state is confirmed yet.\n\t\t\t\tthis.insertState({ state: \"unconfirmed\", since: start, confirmedAt: start });\n\t\t\t});\n\t\t\tconsole.log(`Monitor \"${monitor.id}\" is back in status.config.ts: resuming with its history`);\n\t\t\treturn \"resumed\";\n\t\t}\n\t\tthis.insertPeriod(start, \"active\", monitor.intervalMs);\n\t\treturn \"changed\";\n\t}\n\n\t/**\n\t * Stops a monitor that left the configuration: records a stopped period and a\n\t * `stopped` state, and deletes the alarm once its notifications are queued. Keeps every\n\t * result. Idempotent.\n\t */\n\tprivate async stop(now: number): Promise<void> {\n\t\tconst period = this.currentPeriod();\n\t\tif (period?.status === \"active\") {\n\t\t\tconst at = Math.max(now, period.from + 1);\n\t\t\tthis.store.transaction(() => {\n\t\t\t\tthis.insertPeriod(at, \"stopped\", null);\n\t\t\t\tthis.insertState({ state: \"stopped\", since: at, confirmedAt: at });\n\t\t\t});\n\t\t\tconsole.log(\n\t\t\t\t`Monitor \"${this.monitorId()}\" is no longer in status.config.ts: stopped its checks. ` +\n\t\t\t\t\t\"Its data is kept until an administrator deletes it.\",\n\t\t\t);\n\t\t}\n\t\t// Events not queued yet, such as the `stopped` that resolves the monitor's automatic\n\t\t// incidents: while the queue refuses them, the alarm stays, for them only (no checks:\n\t\t// `alarm()` comes back here for a monitor that is not configured).\n\t\tif (this.hasUnsentNotifications()) {\n\t\t\ttry {\n\t\t\t\tawait this.flushNotifications(this.monitorId());\n\t\t\t\tthis.failures.delete(\"notify\");\n\t\t\t} catch (error) {\n\t\t\t\tthis.backOff(NOTIFY_RETRY);\n\t\t\t\tconst retryAt = this.backoffUntil.get(\"notify\") as number;\n\t\t\t\tconsole.error(`Monitor \"${this.monitorId()}\": could not queue notifications after stopping; retrying`, error);\n\t\t\t\tif ((await this.store.getAlarm()) !== retryAt) await this.store.setAlarm(retryAt);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t// While the alarm runs, getAlarm() is null and the alarm simply does not set another.\n\t\tif ((await this.store.getAlarm()) !== null) await this.store.deleteAlarm();\n\t}\n\n\t// ---- Alarm\n\n\tprivate works(monitor: ResolvedMonitor): Work[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: \"check\",\n\t\t\t\tnext: (now) => {\n\t\t\t\t\tconst plan = this.planCheck(monitor, now);\n\t\t\t\t\tif (plan === null) return null;\n\t\t\t\t\treturn plan.recheckAt === null ? plan.scheduledAt : Math.min(plan.scheduledAt, plan.recheckAt);\n\t\t\t\t},\n\t\t\t\trun: (now) => this.check(monitor, now),\n\t\t\t\tfailureBackoffMs: 30_000,\n\t\t\t},\n\t\t\t{\n\t\t\t\tkind: \"retention\",\n\t\t\t\tnext: (now) => this.retentionDue(now),\n\t\t\t\trun: (now) => this.deleteOldResults(monitor, now),\n\t\t\t\tfailureBackoffMs: 3_600_000,\n\t\t\t},\n\t\t\t{\n\t\t\t\t// Notifications whose queue send failed: due as soon as any are unsent.\n\t\t\t\t...NOTIFY_RETRY,\n\t\t\t\tnext: (now) => (this.hasUnsentNotifications() ? now : null),\n\t\t\t\trun: () => this.flushNotifications(monitor.id),\n\t\t\t},\n\t\t];\n\t}\n\n\t/** Records a failure of `work` and when it may run again. */\n\tprivate backOff(work: Pick<Work, \"kind\" | \"failureBackoffMs\" | \"maxFailureBackoffMs\">): void {\n\t\tconst failures = (this.failures.get(work.kind) ?? 0) + 1;\n\t\tthis.failures.set(work.kind, failures);\n\t\tconst delay = Math.min(work.failureBackoffMs * 2 ** (failures - 1), work.maxFailureBackoffMs ?? work.failureBackoffMs);\n\t\tthis.backoffUntil.set(work.kind, Date.now() + delay);\n\t}\n\n\tprivate nextOf(work: Work, now: number): number | null {\n\t\tconst at = work.next(now);\n\t\treturn at === null ? null : Math.max(at, this.backoffUntil.get(work.kind) ?? 0);\n\t}\n\n\t/**\n\t * Sets the alarm to the earliest deadline. Skips the write when nothing would change; in\n\t * `if-earlier` mode it also keeps a later alarm, unless that one is overdue (it stopped\n\t * firing).\n\t */\n\tprivate async schedule(\n\t\tmonitor: ResolvedMonitor,\n\t\tnow: number,\n\t\tmode: \"after-alarm\" | \"if-earlier\",\n\t): Promise<number | null> {\n\t\tlet next: number | null = null;\n\t\tfor (const work of this.works(monitor)) {\n\t\t\tconst at = this.nextOf(work, now);\n\t\t\tif (at !== null && (next === null || at < next)) next = at;\n\t\t}\n\t\tif (next === null) return null;\n\t\tif (mode === \"after-alarm\") next = Math.max(next, now + MIN_ALARM_DELAY_MS);\n\n\t\tconst current = await this.store.getAlarm();\n\t\tconst overdue = current !== null && current < now - OVERDUE_ALARM_MS;\n\t\tif (current !== null && !overdue && (current === next || (mode === \"if-earlier\" && current <= next))) {\n\t\t\treturn current;\n\t\t}\n\t\tawait this.store.setAlarm(next);\n\t\treturn next;\n\t}\n\n\t// ---- Checks\n\n\tprivate planCheck(monitor: ResolvedMonitor, now: number): CheckPlan | null {\n\t\tconst period = this.currentPeriod();\n\t\tif (period === null || period.status !== \"active\" || period.intervalMs === null) return null;\n\t\tconst runner = this.runnerOf(monitor);\n\t\t// Stops at the latest scheduled check: past it, only the few re-checks after it are read.\n\t\tconst lastScheduled = this.store.first<{ checked_at: number }>(\n\t\t\t`SELECT checked_at FROM results WHERE checked_at >= ? AND runner = ? AND kind = 'scheduled'\n\t\t\tORDER BY checked_at DESC LIMIT 1`,\n\t\t\tperiod.from,\n\t\t\trunner,\n\t\t);\n\t\tconst scheduledAt = nextScheduledCheck(period.from, period.intervalMs, lastScheduled?.checked_at ?? null, now);\n\t\tconst floor = Math.max(period.from, now - LOOKBACK_CHECKS * period.intervalMs);\n\n\t\t// Re-check soon while the latest result failed and its state is not confirmed yet. Once it is confirmed, checks return to the schedule. When the re-check itself\n\t\t// produces no result, it is retried up to MAX_RECHECK_RETRIES times.\n\t\tconst latest = this.store.all<{ checked_at: number; state: CheckState | null }>(\n\t\t\t`SELECT checked_at, state FROM results WHERE checked_at >= ? AND runner = ?\n\t\t\tORDER BY checked_at DESC LIMIT ?`,\n\t\t\tfloor,\n\t\t\trunner,\n\t\t\tMAX_RECHECK_RETRIES + 2,\n\t\t);\n\t\tconst errors = latest.findIndex((row) => row.state !== null);\n\t\tconst lastWithState = errors === -1 ? undefined : latest[errors];\n\t\tlet recheckAt: number | null = null;\n\t\tif (lastWithState !== undefined && lastWithState.state !== \"up\" && errors <= MAX_RECHECK_RETRIES) {\n\t\t\tconst { pending } = this.evaluate(monitor, runner, now);\n\t\t\tif (pending !== null && pending !== \"up\") {\n\t\t\t\trecheckAt = (latest[0] as { checked_at: number }).checked_at + monitor.confirmation.recheckIntervalMs;\n\t\t\t}\n\t\t}\n\t\treturn { scheduledAt, recheckAt };\n\t}\n\n\tprivate async check(monitor: ResolvedMonitor, now: number): Promise<void> {\n\t\tconst plan = this.planCheck(monitor, now);\n\t\tif (plan === null) return;\n\t\t// A due scheduled check also serves as the re-check.\n\t\tconst kind: CheckKind = plan.scheduledAt <= now ? \"scheduled\" : \"recheck\";\n\t\tconst runner = this.runnerOf(monitor);\n\t\tconst startedAt = Date.now();\n\t\tconst outcome = await this.callRunner(monitor);\n\t\tif (this.record(monitor, runner, startedAt, kind, outcome)) {\n\t\t\t// Queue the notification now; if that fails, the `notify` work retries it.\n\t\t\ttry {\n\t\t\t\tawait this.flushNotifications(monitor.id);\n\t\t\t\tthis.failures.delete(\"notify\");\n\t\t\t} catch (error) {\n\t\t\t\tthis.backOff(NOTIFY_RETRY);\n\t\t\t\tconsole.error(`Monitor \"${monitor.id}\": could not queue notifications; retrying`, error);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Runs the check on the built-in runner, giving up after the timeouts in `RUNNER_GRACE_MS`. */\n\tprivate async callRunner(monitor: ResolvedMonitor): Promise<CheckOutcome> {\n\t\tconst limitMs = monitor.timeoutMs + 2 * RUNNER_GRACE_MS;\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst timeout = new Promise<CheckOutcome>((resolve) => {\n\t\t\ttimer = setTimeout(\n\t\t\t\t() =>\n\t\t\t\t\tresolve({\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: { name: \"RunnerTimeoutError\", message: `The runner did not answer within ${limitMs} ms` },\n\t\t\t\t\t}),\n\t\t\t\tlimitMs,\n\t\t\t);\n\t\t});\n\t\ttry {\n\t\t\tconst call = this.ctx.exports.CloudflareRunner.run({ monitorId: monitor.id }) as Promise<CheckOutcome>;\n\t\t\treturn await Promise.race([call, timeout]);\n\t\t} catch (error) {\n\t\t\treturn { ok: false, error: checkError(error, \"RunnerError\") };\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t}\n\t}\n\n\t/**\n\t * Stores one check and applies the confirmation rule, in one transaction. A routine check\n\t * writes one row here; a check that confirms a new state writes two. The new state record\n\t * is also the \"unsent notification\" marker. Returns whether a state was confirmed.\n\t */\n\tprivate record(\n\t\tmonitor: ResolvedMonitor,\n\t\trunner: string,\n\t\tstartedAt: number,\n\t\tkind: CheckKind,\n\t\toutcome: CheckOutcome,\n\t): boolean {\n\t\tif (!outcome.ok) {\n\t\t\tconsole.warn(`Monitor \"${monitor.id}\": the check produced no result. ${outcome.error.name}: ${outcome.error.message}`);\n\t\t}\n\t\treturn this.store.transaction(() => {\n\t\t\t// Keep start times strictly increasing per runner, even if the clock goes back.\n\t\t\t// Reads one row (or one per runner, once there are several).\n\t\t\tconst previous = this.store.first<{ checked_at: number }>(\n\t\t\t\t\"SELECT checked_at FROM results WHERE runner = ? ORDER BY checked_at DESC LIMIT 1\",\n\t\t\t\trunner,\n\t\t\t);\n\t\t\tconst at = previous === undefined ? startedAt : Math.max(startedAt, previous.checked_at + 1);\n\t\t\tconst result = outcome.ok ? outcome.result : null;\n\t\t\tthis.store.run(\n\t\t\t\t`INSERT INTO results (checked_at, runner, kind, state, latency_ms, message, details)\n\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t\tat,\n\t\t\t\trunner,\n\t\t\t\tkind,\n\t\t\t\tresult?.state ?? null,\n\t\t\t\tresult?.latencyMs ?? null,\n\t\t\t\tresult ? result.message : outcome.ok ? null : outcome.error.message,\n\t\t\t\tresult ? result.details : outcome.ok ? null : JSON.stringify({ error: outcome.error.name }),\n\t\t\t);\n\t\t\tif (result === null) return false;\n\n\t\t\tconst confirmation = this.evaluate(monitor, runner, at);\n\t\t\tif (!confirmation.changed || confirmation.current === null) return false;\n\t\t\tthis.insertState(confirmation.current);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\t/**\n\t * The confirmation rule applied to the stored results. Checks without a state are\n\t * skipped, and so are results from before the monitor was last stopped. Reads at most the\n\t * results of the last few intervals.\n\t */\n\tprivate evaluate(monitor: ResolvedMonitor, runner: string, now: number): Confirmation {\n\t\tconst needed = observationsNeeded(monitor.confirmation);\n\t\tconst floor = Math.max(this.activeSince(), now - (needed + LOOKBACK_CHECKS) * monitor.intervalMs);\n\t\tconst recent = this.store\n\t\t\t.all<{ checked_at: number; state: CheckState }>(\n\t\t\t\t`SELECT checked_at, state FROM results WHERE checked_at >= ? AND runner = ? AND state IS NOT NULL\n\t\t\t\tORDER BY checked_at DESC LIMIT ?`,\n\t\t\t\tfloor,\n\t\t\t\trunner,\n\t\t\t\tneeded,\n\t\t\t)\n\t\t\t.reverse()\n\t\t\t.map((row): Observation => ({ state: row.state, at: row.checked_at }));\n\t\tconst current = this.currentState();\n\t\t// After a stop, the state is confirmed afresh.\n\t\tconst previous: ConfirmedState | null =\n\t\t\tcurrent === null || current.state === \"stopped\" || current.state === \"unconfirmed\"\n\t\t\t\t? null\n\t\t\t\t: { ...current, state: current.state };\n\t\treturn confirmState(previous, recent, monitor.confirmation);\n\t}\n\n\tprivate currentState(): StateRecord | null {\n\t\tconst row = this.store.first<TransitionRow>(\"SELECT since, state, confirmed_at FROM transitions ORDER BY since DESC LIMIT 1\");\n\t\treturn row ? toRecord(row) : null;\n\t}\n\n\t/** Appends to the state history, keeping `since` strictly increasing (it is the key). */\n\tprivate insertState(record: StateRecord): void {\n\t\tconst latest = this.currentState();\n\t\tconst since = latest === null ? record.since : Math.max(record.since, latest.since + 1);\n\t\tthis.store.run(\n\t\t\t\"INSERT INTO transitions (since, state, confirmed_at) VALUES (?, ?, ?)\",\n\t\t\tsince,\n\t\t\trecord.state,\n\t\t\trecord.confirmedAt,\n\t\t);\n\t\tthis.notifyPending = true;\n\t}\n\n\t// ---- Notifications\n\n\t/** Whether state records exist that are newer than the watermark. Reads two rows once per instance. */\n\tprivate hasUnsentNotifications(): boolean {\n\t\tif (this.notifyPending === undefined) {\n\t\t\tthis.notifyPending = (this.currentState()?.since ?? Number.NEGATIVE_INFINITY) > this.notifiedThrough();\n\t\t}\n\t\treturn this.notifyPending;\n\t}\n\n\t/**\n\t * The watermark. Migration 2 sets it; should it be missing anyway, the history so far\n\t * counts as notified (never replayed), and the watermark is written.\n\t */\n\tprivate notifiedThrough(): number {\n\t\tconst sent = this.store.kvGet<number>(NOTIFIED_KEY);\n\t\tif (sent !== undefined) return sent;\n\t\tconst latest = this.currentState()?.since ?? 0;\n\t\tconsole.warn(`Monitor \"${this.monitorId()}\": notification watermark missing; not replaying earlier state changes`);\n\t\tthis.store.kvPut(NOTIFIED_KEY, latest);\n\t\treturn latest;\n\t}\n\n\t/**\n\t * Queues the events of the state records newer than the watermark, then moves the watermark\n\t * past them (one written row). Throws when the queue refuses them: the watermark stays, and\n\t * the alarm's `notify` work tries again. One flush at a time; a duplicate send (after a\n\t * crash between sending and moving the watermark) is dropped downstream by event ID.\n\t */\n\tprivate flushNotifications(monitorId: string): Promise<void> {\n\t\tconst run = this.flushing.then(() => this.flushOnce(monitorId));\n\t\tthis.flushing = run.catch(() => {});\n\t\treturn run;\n\t}\n\n\tprivate async flushOnce(monitorId: string): Promise<void> {\n\t\tconst sent = this.notifiedThrough();\n\t\tconst pending = this.store\n\t\t\t.all<TransitionRow>(\n\t\t\t\t\"SELECT since, state, confirmed_at FROM transitions WHERE since > ? ORDER BY since LIMIT ?\",\n\t\t\t\tsent,\n\t\t\t\tNOTIFY_BATCH,\n\t\t\t)\n\t\t\t.map(toRecord);\n\t\tconst last = pending.at(-1);\n\t\tif (last === undefined) {\n\t\t\tthis.notifyPending = false;\n\t\t\treturn;\n\t\t}\n\t\tconst before = this.store.first<TransitionRow>(\n\t\t\t\"SELECT since, state, confirmed_at FROM transitions WHERE since <= ? ORDER BY since DESC LIMIT 1\",\n\t\t\tsent,\n\t\t);\n\t\t// The latest confirmed state before them, past a stop and a resume, so that a recovery\n\t\t// after the monitor resumed answers the `down` notified before it stopped.\n\t\tconst confirmed =\n\t\t\tbefore === undefined || isCheckState(before.state)\n\t\t\t\t? before\n\t\t\t\t: this.store.first<TransitionRow>(\n\t\t\t\t\t\t\"SELECT since, state, confirmed_at FROM transitions WHERE since <= ? AND state IN ('up', 'degraded', 'down') ORDER BY since DESC LIMIT 1\",\n\t\t\t\t\t\tsent,\n\t\t\t\t\t);\n\t\tconst events = eventsFromTransitions(\n\t\t\tmonitorId,\n\t\t\tbefore ? toRecord(before) : null,\n\t\t\tpending,\n\t\t\t(record) => this.messageAt(record.confirmedAt),\n\t\t\tconfirmed ? toRecord(confirmed) : null,\n\t\t);\n\t\tif (events.length > 0) await enqueue(this.env, events.map((event) => ({ type: \"event\", v: 1, event })));\n\t\tthis.store.kvPut(NOTIFIED_KEY, last.since);\n\t\tthis.notifyPending = pending.length === NOTIFY_BATCH;\n\t}\n\n\t/** The message of the latest check with a state at or before `at`, such as \"HTTP 503\". */\n\tprivate messageAt(at: number): string | null {\n\t\treturn (\n\t\t\tthis.store.first<{ message: string | null }>(\n\t\t\t\t\"SELECT message FROM results WHERE checked_at <= ? AND state IS NOT NULL ORDER BY checked_at DESC LIMIT 1\",\n\t\t\t\tat,\n\t\t\t)?.message ?? null\n\t\t);\n\t}\n\n\t// ---- Retention\n\n\tprivate retentionDue(now: number): number | null {\n\t\tif (config.retentionMs === null) return null;\n\t\tconst state = this.store.kvGet<RetentionState>(RETENTION_KEY);\n\t\tif (state === undefined) return now;\n\t\tconst resume = Math.max(state.ranAt + RETENTION_CONTINUE_MS, this.retentionResumeAt);\n\t\treturn state.backlog && state.deleted < this.dailyDeleteBudget() ? resume : state.dayStart + DAY_MS;\n\t}\n\n\t/** Rows of old results this monitor may delete per day, tied to its own write rate. */\n\tprivate dailyDeleteBudget(): number {\n\t\tconst period = this.currentPeriod();\n\t\tconst interval = period === null ? DAY_MS : this.lastInterval(period);\n\t\treturn Math.max(1, Math.ceil(RETENTION_DELETES_PER_CHECK * Math.ceil(DAY_MS / interval)));\n\t}\n\n\t/**\n\t * Deletes the oldest results beyond the retention period, at most `RETENTION_BATCH` rows\n\t * per run and the daily budget per day, because deletes count as written rows and a\n\t * shortened retention can leave a large backlog. What remains carries over to the next\n\t * day. Once the backlog is gone, older state records and schedule periods are trimmed\n\t * too, keeping the ones in effect at the cutoff.\n\t */\n\tprivate async deleteOldResults(monitor: ResolvedMonitor, now: number): Promise<void> {\n\t\tconst { retentionMs } = config;\n\t\tif (retentionMs === null) return;\n\t\tconst cutoff = now - retentionMs;\n\t\tconst budget = this.dailyDeleteBudget();\n\t\tlet state = this.store.kvGet<RetentionState>(RETENTION_KEY);\n\t\tif (state === undefined || now >= state.dayStart + DAY_MS) {\n\t\t\tstate = { dayStart: now, deleted: 0, backlog: true, ranAt: now };\n\t\t}\n\t\tconst limit = Math.min(RETENTION_BATCH, budget - state.deleted);\n\t\tif (limit <= 0) return;\n\n\t\tconst deleted = this.store.run(\n\t\t\t`DELETE FROM results WHERE (checked_at, runner) IN (\n\t\t\t\tSELECT checked_at, runner FROM results WHERE checked_at < ? ORDER BY checked_at LIMIT ?\n\t\t\t)`,\n\t\t\tcutoff,\n\t\t\tlimit,\n\t\t);\n\t\tconst backlog = deleted >= limit;\n\t\tthis.store.transaction(() => {\n\t\t\tif (!backlog) {\n\t\t\t\tfor (const table of [\n\t\t\t\t\t{ name: \"transitions\", key: \"since\" },\n\t\t\t\t\t{ name: \"schedule_periods\", key: \"start\" },\n\t\t\t\t]) {\n\t\t\t\t\tconst inEffect = this.store.first<{ key: number }>(\n\t\t\t\t\t\t`SELECT ${table.key} AS key FROM ${table.name} WHERE ${table.key} <= ? ORDER BY ${table.key} DESC LIMIT 1`,\n\t\t\t\t\t\tcutoff,\n\t\t\t\t\t);\n\t\t\t\t\tif (inEffect !== undefined) this.store.run(`DELETE FROM ${table.name} WHERE ${table.key} < ?`, inEffect.key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.store.kvPut(RETENTION_KEY, {\n\t\t\t\tdayStart: state.dayStart,\n\t\t\t\tdeleted: state.deleted + deleted,\n\t\t\t\tbacklog,\n\t\t\t\tranAt: now,\n\t\t\t} satisfies RetentionState);\n\t\t});\n\t\tthis.retentionResumeAt = backlog ? now + RETENTION_CONTINUE_MS : 0;\n\t\tif (backlog && state.deleted + deleted >= budget) {\n\t\t\tconsole.log(`Monitor \"${monitor.id}\": deleted ${budget} old results today; continuing tomorrow`);\n\t\t}\n\t}\n}\n","/**\n * Images administrators upload for a page: its logo and favicon, in R2\n * (the `UPLOADS` binding).\n *\n * - **Optional.** Without the binding (R2 not enabled on the account, or a deployment from the\n * package that does not name a bucket) nothing else changes: uploads are refused, and the\n * page shows its logo URL or its title, never a broken image.\n * - **Never-reused IDs.** An image's ID is random, new for every upload, under its page\n * (`pages/<pageId>/images/<id>`), so a served image never changes and browsers keep it for a\n * year (`immutable`): visitors fetch it once, and it costs no D1 read at all. Uploading the\n * same file again gives another ID rather than the old one: an image whose deletion has been\n * decided can never be uploaded again under its ID and named by a save meanwhile.\n * - **Upload first, then save.** The admin UI uploads a file as soon as it is chosen and names\n * it in the appearance when the form is saved, with the appearance's `version` like every\n * other field. Images that no saved appearance names are deleted a\n * day after their upload, when the page's appearance is next saved\n * ({@link removeUnusedImages}), so that an edit left unsaved for a while can still be saved.\n * What remains: a save that names, through the API, an older image the appearance has just\n * stopped naming can still lose it, if it lands during that deletion. The admin UI never\n * does that (it names only images it has just uploaded, or the ones already saved), and\n * uploading the file again repairs it.\n * - **Raster images only**, checked by their first bytes, and served with `nosniff` and a\n * sandboxing Content-Security-Policy: an image opened on its own runs nothing.\n */\nimport {\n\tIMAGE_CONTENT_TYPES,\n\tIMAGE_ID,\n\tIMAGE_TYPES,\n\ttype ImageExtension,\n\timagePath,\n\tLIMITS,\n\ttype UploadedImage,\n} from \"../shared/admin-api\";\n\nexport { imagePath };\n\n/** The bucket, or `undefined` when the Worker has none (see the module documentation). */\nexport function uploadsBucket(env: Env): R2Bucket | undefined {\n\treturn (env as Partial<Pick<Env, \"UPLOADS\">>).UPLOADS;\n}\n\n/** Where a page's images are in the bucket. */\nexport function imagePrefix(pageId: string): string {\n\treturn `pages/${pageId}/images/`;\n}\n\nexport function imageKey(pageId: string, imageId: string): string {\n\treturn `${imagePrefix(pageId)}${imageId}`;\n}\n\nexport function isImageId(value: string): boolean {\n\treturn IMAGE_ID.test(value);\n}\n\n/** The extension of an accepted media type (`Content-Type`, parameters ignored), or `null`. */\nexport function extensionOf(contentType: string | null): ImageExtension | null {\n\tconst type = contentType?.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n\treturn Object.hasOwn(IMAGE_TYPES, type) ? IMAGE_TYPES[type as keyof typeof IMAGE_TYPES] : null;\n}\n\nfunction startsWith(bytes: Uint8Array, prefix: readonly number[], offset = 0): boolean {\n\treturn bytes.length >= offset + prefix.length && prefix.every((byte, index) => bytes[offset + index] === byte);\n}\n\nconst ascii = (text: string) => [...text].map((char) => char.charCodeAt(0));\n\n/** The format of an image by its first bytes, or `null` when it is none of the accepted ones. */\nexport function sniffImage(bytes: Uint8Array): ImageExtension | null {\n\tif (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return \"png\";\n\tif (startsWith(bytes, [0xff, 0xd8, 0xff])) return \"jpg\";\n\tif (startsWith(bytes, ascii(\"GIF87a\")) || startsWith(bytes, ascii(\"GIF89a\"))) return \"gif\";\n\tif (startsWith(bytes, ascii(\"RIFF\")) && startsWith(bytes, ascii(\"WEBP\"), 8)) return \"webp\";\n\t// An icon (type 1, not a cursor) with at least one image.\n\tif (startsWith(bytes, [0x00, 0x00, 0x01, 0x00]) && bytes.length >= 6 && (bytes[4] ?? 0) + (bytes[5] ?? 0) > 0) return \"ico\";\n\treturn null;\n}\n\nfunction hex(bytes: Uint8Array): string {\n\treturn [...bytes].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/** A new image ID: 128 random bits. */\nexport function newImageId(extension: ImageExtension): string {\n\treturn `${hex(crypto.getRandomValues(new Uint8Array(16)))}.${extension}`;\n}\n\nexport type ImageCheck =\n\t| { readonly ok: true; readonly extension: ImageExtension }\n\t| { readonly ok: false; readonly reason: \"empty\" | \"too_large\" | \"not_an_image\" | \"type_mismatch\" };\n\n/** Whether `bytes` are an image of the declared extension, within the size limit. */\nexport function checkImage(bytes: Uint8Array, declared: ImageExtension): ImageCheck {\n\tif (bytes.byteLength === 0) return { ok: false, reason: \"empty\" };\n\tif (bytes.byteLength > LIMITS.imageBytes) return { ok: false, reason: \"too_large\" };\n\tconst actual = sniffImage(bytes);\n\tif (actual === null) return { ok: false, reason: \"not_an_image\" };\n\tif (actual !== declared) return { ok: false, reason: \"type_mismatch\" };\n\treturn { ok: true, extension: actual };\n}\n\n/** Stores an image (checked with {@link checkImage}) for the page, under a new ID. */\nexport async function storeImage(bucket: R2Bucket, pageId: string, bytes: Uint8Array, extension: ImageExtension): Promise<UploadedImage> {\n\tconst id = newImageId(extension);\n\tconst contentType = IMAGE_CONTENT_TYPES[extension];\n\t// R2 checks the bytes it stores against their SHA-256.\n\tconst sha256 = hex(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes)));\n\tawait bucket.put(imageKey(pageId, id), bytes, { httpMetadata: { contentType }, sha256 });\n\treturn { id, url: imagePath(pageId, id), contentType, size: bytes.byteLength };\n}\n\nexport async function imageExists(bucket: R2Bucket, pageId: string, imageId: string): Promise<boolean> {\n\treturn (await bucket.head(imageKey(pageId, imageId))) !== null;\n}\n\n/** How long an image no appearance names is kept after its upload: an editor may still be about to save it. */\nexport const UNUSED_IMAGE_GRACE_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Deletes the page's images that are not in `keep` (what its appearance names now) and were\n * uploaded more than {@link UNUSED_IMAGE_GRACE_MS} ago. Returns the IDs deleted.\n */\nexport async function removeUnusedImages(bucket: R2Bucket, pageId: string, keep: ReadonlySet<string>, now = Date.now()): Promise<string[]> {\n\tconst prefix = imagePrefix(pageId);\n\tconst unused: string[] = [];\n\tlet cursor: string | undefined;\n\tdo {\n\t\tconst listed = await bucket.list({ prefix, ...(cursor === undefined ? {} : { cursor }) });\n\t\tfor (const object of listed.objects) {\n\t\t\tconst id = object.key.slice(prefix.length);\n\t\t\tif (!keep.has(id) && object.uploaded.getTime() <= now - UNUSED_IMAGE_GRACE_MS) unused.push(id);\n\t\t}\n\t\tcursor = listed.truncated ? listed.cursor : undefined;\n\t} while (cursor !== undefined);\n\t// At most 1,000 keys per call.\n\tfor (let start = 0; start < unused.length; start += 1000) {\n\t\tawait bucket.delete(unused.slice(start, start + 1000).map((id) => imageKey(pageId, id)));\n\t}\n\treturn unused;\n}\n\n/** A year: an image's URL names its bytes, so it never changes. */\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n/**\n * Headers of every image response: never sniffed, and run as nothing when opened on its own\n * (a raster image runs nothing anyway; this holds should a stored file ever be something else).\n */\nconst IMAGE_HEADERS = {\n\t\"X-Content-Type-Options\": \"nosniff\",\n\t\"Content-Security-Policy\": \"default-src 'none'; sandbox\",\n\t\"Cross-Origin-Resource-Policy\": \"cross-origin\",\n} as const;\n\nfunction notFound(): Response {\n\treturn Response.json(\n\t\t{ error: \"not_found\", message: \"No such image\" },\n\t\t{ status: 404, headers: { \"Cache-Control\": \"no-store\", \"X-Content-Type-Options\": \"nosniff\" } },\n\t);\n}\n\n/**\n * `GET /api/pages/:pageId/images/:imageId`: the image from R2, cached for a year, with\n * `ETag` and conditional requests (304). 404 without the bucket or the image.\n */\nexport async function serveImage(env: Env, pageId: string, imageId: string, request: Request): Promise<Response> {\n\tconst bucket = uploadsBucket(env);\n\tif (bucket === undefined || !isImageId(imageId)) return notFound();\n\tconst object = await bucket.get(imageKey(pageId, imageId), { onlyIf: request.headers });\n\tif (object === null) return notFound();\n\tconst extension = imageId.slice(imageId.lastIndexOf(\".\") + 1) as ImageExtension;\n\tconst headers = new Headers({\n\t\t...IMAGE_HEADERS,\n\t\t\"Content-Type\": IMAGE_CONTENT_TYPES[extension],\n\t\t\"Cache-Control\": IMMUTABLE,\n\t\tETag: object.httpEtag,\n\t});\n\t// The condition held (If-None-Match matched): R2 returns the object without its body.\n\tif (!(\"body\" in object)) return new Response(null, { status: 304, headers });\n\theaders.set(\"Content-Length\", String(object.size));\n\tif (request.method !== \"HEAD\") return new Response(object.body, { headers });\n\tawait object.body.cancel();\n\treturn new Response(null, { headers });\n}\n","/**\n * What the public API shows of the admin's data: incidents, maintenance and appearance\n * reduced to what visitors see. Administrator names, versions and automation flags stay\n * internal, and only components that are on the page are listed.\n */\nimport type { ResolvedPage } from \"@naosystem/cf-workers-status-page-core\";\nimport type { Impact, Incident, IncidentUpdate, Maintenance, PageAppearance } from \"../../shared/admin-api\";\nimport type {\n\tAffectedComponent,\n\tComponentRef,\n\tPublicAppearance,\n\tPublicIncident,\n\tPublicIncidentUpdate,\n\tPublicIncidentWithUpdates,\n\tPublicMaintenance,\n} from \"../../shared/public-api\";\nimport { imagePath } from \"../uploads\";\n\nconst IMPACT_RANK: Readonly<Record<Impact, number>> = { none: 0, degraded: 1, down: 2 };\n\nfunction componentNames(page: ResolvedPage): ReadonlyMap<string, string> {\n\treturn new Map(page.components.map((component) => [component.id, component.name]));\n}\n\nexport function publicIncident(incident: Incident, page: ResolvedPage): PublicIncident {\n\tconst names = componentNames(page);\n\tconst components: AffectedComponent[] = incident.components.flatMap((affected) => {\n\t\tconst name = names.get(affected.id);\n\t\treturn name === undefined ? [] : [{ id: affected.id, name, impact: affected.impact }];\n\t});\n\tconst impact = components.reduce<Impact>(\n\t\t(highest, component) => (IMPACT_RANK[component.impact] > IMPACT_RANK[highest] ? component.impact : highest),\n\t\t\"none\",\n\t);\n\treturn {\n\t\tid: incident.id,\n\t\ttitle: incident.title,\n\t\tstage: incident.stage,\n\t\timpact,\n\t\tcomponents,\n\t\tstartedAt: incident.startedAt,\n\t\tupdatedAt: incident.updatedAt,\n\t\tresolvedAt: incident.resolvedAt,\n\t};\n}\n\nexport function publicUpdate(update: IncidentUpdate): PublicIncidentUpdate {\n\treturn { stage: update.stage, body: update.body, createdAt: update.createdAt };\n}\n\nexport function publicIncidentWithUpdates(\n\tincident: Incident & { readonly updates: readonly IncidentUpdate[]; readonly olderUpdates?: boolean },\n\tpage: ResolvedPage,\n): PublicIncidentWithUpdates {\n\treturn {\n\t\t...publicIncident(incident, page),\n\t\tupdates: incident.updates.map(publicUpdate),\n\t\tolderUpdates: incident.olderUpdates ?? false,\n\t};\n}\n\nexport function publicMaintenance(maintenance: Maintenance, page: ResolvedPage): PublicMaintenance {\n\tconst names = componentNames(page);\n\tconst components: ComponentRef[] = maintenance.components.flatMap((id) => {\n\t\tconst name = names.get(id);\n\t\treturn name === undefined ? [] : [{ id, name }];\n\t});\n\treturn {\n\t\tid: maintenance.id,\n\t\ttitle: maintenance.title,\n\t\tbody: maintenance.body,\n\t\tstartsAt: maintenance.startsAt,\n\t\tendsAt: maintenance.endsAt,\n\t\tcomponents,\n\t};\n}\n\n/**\n * The appearance as visitors get it. `uploads`: whether the Worker has its R2 bucket; without\n * it, uploaded images are left out (they could not be served), and the logo URL shows instead.\n */\nexport function publicAppearance(appearance: PageAppearance, uploads: boolean): PublicAppearance {\n\tconst image = (id: string | null) => (uploads && id !== null ? imagePath(appearance.pageId, id) : null);\n\treturn {\n\t\ttitle: appearance.title,\n\t\tdescription: appearance.description,\n\t\t// https only (the page's Content-Security-Policy blocks others); one saved before that rule is left out.\n\t\tlogoUrl: image(appearance.logoImage) ?? (appearance.logoUrl?.startsWith(\"https://\") === true ? appearance.logoUrl : null),\n\t\twebsiteUrl: appearance.websiteUrl,\n\t\tfaviconUrl: image(appearance.faviconImage),\n\t\tcolors: appearance.colors,\n\t};\n}\n","/**\n * `unknown` notifications from the every-minute Cron: when to notify\n * administrators, and when a monitor needs to be read again.\n */\nimport type { UnknownReason } from \"./events\";\nimport {\n\ttype DisplayState,\n\ttype DisplayStateResult,\n\tdisplayState,\n\ttype MonitorReading,\n\ttype RecordedState,\n\tstaleAfterMs,\n} from \"@naosystem/cf-workers-status-page-core\";\n\n/** A {@link MonitorReading} whose state record has its start, as a Monitor DO's snapshot does. */\nexport interface UnknownReading extends MonitorReading {\n\treadonly current: { readonly state: RecordedState; readonly since: number } | null;\n\t/**\n\t * How far back the snapshot looked for `lastResultAt` (`MonitorSnapshot.recentSince`): a\n\t * `null` `lastResultAt` means only that no result came after this.\n\t */\n\treadonly recentSince?: number | null;\n}\n\n/** What administrators are told about. */\nexport interface UnknownAlert {\n\t/**\n\t * `late`: results stopped arriving; `unconfirmed`: results arrive but confirm no state;\n\t * `unreachable`: the monitor's Durable Object does not answer.\n\t */\n\treadonly reason: UnknownReason;\n\t/** When the monitor became unknown for this reason: the notification's time, and part of its ID. */\n\treadonly since: number;\n\t/** The latest result (or the start of the schedule) it is late from; for `unconfirmed`, when the unconfirmed run began. */\n\treadonly lastAt: number;\n}\n\nexport interface UnknownEvaluation extends DisplayStateResult {\n\t/** Whether administrators should know: `null` while the monitor is fine, stopped, or only briefly unconfirmed. */\n\treadonly alert: UnknownAlert | null;\n\t/**\n\t * The earliest time this monitor's evaluation can turn into an alert without a new result:\n\t * until then, reading the monitor again cannot find it unknown, so the Cron skips it.\n\t * `now` while it is unknown (to notice when it recovers).\n\t */\n\treadonly checkAgainAt: number;\n}\n\n/** A stopped monitor (or one not started yet) is looked at again after this; a sweep refreshes it sooner. */\nexport const STOPPED_RECHECK_MS = 10 * 60_000;\n\n/**\n * Evaluates a monitor's snapshot with {@link displayState}, the rule the status page uses.\n *\n * - `late` (no result for longer than `staleAfterMs`): alert at once.\n * - `unconfirmed`: alert only once it has lasted `staleAfterMs` too. Every monitor is\n * unconfirmed for a check or two after it starts or resumes, which is not worth a\n * notification; a monitor whose results never confirm a state (checks that alternate\n * between success and failure) is.\n * - `stopped` (not configured, not started): never; the monitor is not supposed to run.\n */\nexport function evaluateUnknown(reading: UnknownReading, timeoutMs: number, now: number): UnknownEvaluation {\n\tconst result = displayState(reading, timeoutMs, now);\n\tconst { period } = reading;\n\tif (result.unknownReason === \"stopped\" || period === null || period.intervalMs === null) {\n\t\treturn { ...result, alert: null, checkAgainAt: now + STOPPED_RECHECK_MS };\n\t}\n\tconst staleAfter = staleAfterMs(period.intervalMs, timeoutMs);\n\tconst anchor = Math.max(reading.lastResultAt ?? Number.NEGATIVE_INFINITY, period.from);\n\tconst lateAt = anchor + staleAfter;\n\tif (result.unknownReason === \"late\") {\n\t\t// Without a recent result, all that is known is that none came after the snapshot's window\n\t\t// (a Monitor DO reads a few intervals back only).\n\t\tconst known = reading.lastResultAt ?? Math.max(period.from, reading.recentSince ?? period.from);\n\t\treturn { ...result, alert: { reason: \"late\", since: known + staleAfter, lastAt: known }, checkAgainAt: now };\n\t}\n\tif (result.unknownReason === \"unconfirmed\") {\n\t\tconst unconfirmedSince = reading.current?.state === \"unconfirmed\" ? Math.max(reading.current.since, period.from) : period.from;\n\t\tconst alertAt = unconfirmedSince + staleAfter;\n\t\tif (now >= alertAt) {\n\t\t\treturn { ...result, alert: { reason: \"unconfirmed\", since: alertAt, lastAt: unconfirmedSince }, checkAgainAt: now };\n\t\t}\n\t\treturn { ...result, alert: null, checkAgainAt: Math.min(lateAt, alertAt) };\n\t}\n\treturn { ...result, alert: null, checkAgainAt: lateAt };\n}\n\n/** What the Cron does about a monitor, given whether administrators were already told it is unknown. */\nexport function unknownAction(\n\tevaluation: Pick<UnknownEvaluation, \"alert\" | \"state\" | \"unknownReason\">,\n\tnotified: boolean,\n): \"notify\" | \"clear\" | \"none\" {\n\tif (!notified) return evaluation.alert === null ? \"none\" : \"notify\";\n\t// Notified once per stretch of `unknown`: the record goes when the monitor leaves it.\n\tconst left: boolean = evaluation.state !== (\"unknown\" satisfies DisplayState) || evaluation.unknownReason === \"stopped\";\n\treturn left ? \"clear\" : \"none\";\n}\n\n/** The ID of the `unknown` event of `monitorId` that began at `since`. */\nexport function unknownEventId(monitorId: string, since: number): string {\n\treturn `unknown:${monitorId}:${since}`;\n}\n\n/**\n * Whether the Cron run for `scheduledTime` looks for `unknown` monitors: every run with the\n * default 1-minute interval, otherwise the runs on multiples of the interval.\n */\nexport function unknownCheckDue(scheduledTime: number, intervalMs: number): boolean {\n\tconst minute = Math.floor(scheduledTime / 60_000);\n\treturn minute % Math.max(1, Math.round(intervalMs / 60_000)) === 0;\n}\n","import { DurableObject } from \"cloudflare:workers\";\nimport type { LocationHint } from \"@naosystem/cf-workers-status-page-core\";\nimport { config } from \"./config\";\nimport { ensureSchema } from \"./db/schema\";\nimport { type MonitorSnapshot, monitorStub, type PurgeRefusal, type SyncResult } from \"./monitor\";\nimport { evaluateUnknown } from \"./notifications/unknown\";\nimport { type Migration, migrate } from \"./storage\";\n\n/**\n * Starting and stopping Monitor DOs after a deploy, and the registry of\n * every monitor the hub has run.\n *\n * Workers have no hook that runs once per deploy, so the hub compares the running version\n * (`CF_VERSION_METADATA.id`) with the versions it has reconciled. For a new version it asks\n * every Monitor DO to `sync()` with its configuration: configured monitors start (or resume,\n * or pick up a new interval), and monitors that left the configuration stop, keeping their\n * data. This runs from the every-minute Cron and, in the background, on requests.\n *\n * State lives in this small singleton Durable Object:\n * - it survives isolate restarts, unlike a module variable; D1 belongs to the admin API's\n * schema, and KV is eventually consistent;\n * - work for one version is serialised and shared, so the many isolates that see a new\n * version at once after a deploy trigger a single sweep;\n * - the registry of monitors (including removed ones, whose data stays until an\n * administrator purges it) is the list the admin API shows.\n *\n * The Reconciler does not use its own configuration: callers send the monitor list of the\n * version they run, and each Monitor DO decides by the version *it* runs. So during a\n * gradual deployment both versions reconcile at once, each with its own list, and nothing\n * waits for the rollout to finish. Cloudflare keeps each Durable Object on one version for\n * the length of a deployment, so a monitor's object does not flip between configurations;\n * an object that runs the other version answers for that version, and the sweep retries it\n * with backoff until it runs the caller's.\n *\n * The every-minute Cron calls {@link Reconciler.cron}, which also reads the monitors the\n * `unknown` check needs: only those that could have become late since they were\n * last read (see `cron`), so that the check does not cost a Durable Object request per\n * monitor per minute.\n */\n\n/** Name of the single Reconciler object. */\nconst RECONCILER_NAME = \"hub\";\n/**\n * After a complete sweep, the Cron sweeps every monitor again this often. `sync()` writes\n * nothing when a monitor is running, so this is cheap, and it restarts a monitor whose alarm\n * chain broke (for example, when storage writes failed for longer than the alarm's retries,\n * such as at the Free plan's daily write limit).\n */\nexport const SWEEP_INTERVAL_MS = 10 * 60_000;\n/** Monitors that failed are retried after 1, 2, 4 … minutes, at most `SWEEP_INTERVAL_MS` apart. */\nconst RETRY_BASE_MS = 60_000;\n/** Monitor DOs called at once during a sweep. */\nconst SWEEP_CONCURRENCY = 8;\n/** Sweep records kept, newest first: the current version and the ones before it. */\nconst SWEEPS_KEPT = 3;\n\nexport interface MonitorEntry {\n\treadonly id: string;\n\t/** The monitor's location hint in the caller's configuration. */\n\treadonly location: LocationHint | null;\n\t/** The monitor's `timeout` in the caller's configuration, for the lateness threshold. */\n\treadonly timeoutMs: number;\n}\n\nexport interface ReconcileRequest {\n\t/** The version the caller runs. */\n\treadonly versionId: string;\n\t/** The monitors in that version's configuration. */\n\treadonly monitors: readonly MonitorEntry[];\n\t/** From the Cron: also sweep every monitor when the last sweep is older than {@link SWEEP_INTERVAL_MS}. */\n\treadonly periodic: boolean;\n}\n\nexport interface SweepFailure {\n\treadonly monitorId: string;\n\treadonly reason: string;\n}\n\nexport interface CronRequest extends Omit<ReconcileRequest, \"periodic\"> {\n\t/** Whether this run looks for `unknown` monitors (`notifications.unknownCheckInterval`). */\n\treadonly unknownCheck: boolean;\n\t/**\n\t * Monitors to read whatever their deadline: those administrators were told are unknown (to\n\t * see them recover), and those with a `down` held back by maintenance.\n\t */\n\treadonly alwaysRead: readonly string[];\n}\n\nexport interface CronReport {\n\treadonly reconcile: ReconcileReport;\n\t/**\n\t * Snapshots of the configured monitors read during this call, by the sweep or for the\n\t * `unknown` check. A configured monitor without one could not have become late since it\n\t * was last read.\n\t */\n\treadonly snapshots: readonly MonitorSnapshot[];\n\t/** Monitor DOs called for snapshots (not counting the sweep's syncs). */\n\treadonly reads: number;\n\treadonly readFailures: readonly SweepFailure[];\n\t/**\n\t * Monitors whose Durable Object could not be read although it could have become `unknown`\n\t * by now (its deadline has passed, or, with none known, reads failed {@link UNREACHABLE_AFTER}\n\t * times in a row): `unknown` too, since it cannot be checked. `since` is the deadline,\n\t * or the first failure; it stays the same while reads keep failing.\n\t */\n\treadonly unreachable: readonly { readonly monitorId: string; readonly since: number }[];\n}\n\n/** Failed reads in a row after which a monitor whose deadline is not known counts as unreachable. */\nexport const UNREACHABLE_AFTER = 3;\n\nexport type ReconcileReport =\n\t/** This version is reconciled, and no sweep is due. */\n\t| { readonly status: \"up-to-date\" }\n\t/** Some monitors failed earlier; they are retried at `nextAttemptAt`, not before. */\n\t| { readonly status: \"waiting\"; readonly nextAttemptAt: number }\n\t| {\n\t\t\t/** `incomplete`: some monitors failed and are retried at `nextAttemptAt`. */\n\t\t\treadonly status: \"reconciled\" | \"incomplete\";\n\t\t\treadonly versionId: string;\n\t\t\t/** Monitors synced by this sweep. */\n\t\t\treadonly synced: number;\n\t\t\treadonly started: string[];\n\t\t\treadonly stopped: string[];\n\t\t\treadonly failures: SweepFailure[];\n\t\t\treadonly nextAttemptAt: number | null;\n\t };\n\n/** A monitor the hub has run. Removed monitors stay listed until purged. */\nexport interface RegisteredMonitor {\n\treadonly id: string;\n\t/** `active`: its object runs checks. `removed`: it left the configuration; its data is kept. */\n\treadonly status: \"active\" | \"removed\";\n\t/** The location hint its object was created with. */\n\treadonly location: LocationHint | null;\n\treadonly firstSeenAt: number;\n\treadonly statusChangedAt: number;\n}\n\nexport interface PurgeMonitorRequest {\n\treadonly id: string;\n\t/** The version the caller (the admin API) runs. */\n\treadonly versionId: string;\n\t/** The monitor IDs in that version's configuration. */\n\treadonly configuredIds: readonly string[];\n}\n\nexport type PurgeMonitorResult =\n\t| { readonly status: \"purged\" }\n\t| { readonly status: \"not-found\" }\n\t| { readonly status: \"refused\"; readonly reason: string; readonly code?: PurgeRefusal };\n\nconst RECONCILER_MIGRATIONS: readonly Migration[] = [\n\t{\n\t\tversion: 1,\n\t\tdescription: \"monitor registry and sweep progress\",\n\t\tup(sql) {\n\t\t\t// WITHOUT ROWID: a TEXT primary key would otherwise add an index, and a row per write.\n\t\t\tsql.exec(`\n\t\t\t\tCREATE TABLE monitors (\n\t\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\t\tstatus TEXT NOT NULL,\n\t\t\t\t\tlocation TEXT,\n\t\t\t\t\tfirst_seen_at INTEGER NOT NULL,\n\t\t\t\t\tstatus_changed_at INTEGER NOT NULL\n\t\t\t\t) WITHOUT ROWID\n\t\t\t`);\n\t\t\t// One row per version: monitors still to sync and when to try them again, and when\n\t\t\t// every monitor was last swept.\n\t\t\tsql.exec(`\n\t\t\t\tCREATE TABLE sweeps (\n\t\t\t\t\tversion_id TEXT PRIMARY KEY,\n\t\t\t\t\tpending TEXT NOT NULL,\n\t\t\t\t\tattempts INTEGER NOT NULL,\n\t\t\t\t\tnext_attempt_at INTEGER NOT NULL,\n\t\t\t\t\tfull_sweep_at INTEGER NOT NULL,\n\t\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t\t) WITHOUT ROWID\n\t\t\t`);\n\t\t},\n\t},\n];\n\ntype RegistryRow = {\n\tid: string;\n\tstatus: RegisteredMonitor[\"status\"];\n\tlocation: LocationHint | null;\n\tfirst_seen_at: number;\n\tstatus_changed_at: number;\n};\ntype SweepRow = {\n\tversion_id: string;\n\tpending: string;\n\tattempts: number;\n\tnext_attempt_at: number;\n\tfull_sweep_at: number;\n};\n\n/** Runs `task` for each item, at most `limit` at a time. */\nexport async function forEachLimited<T, R>(\n\titems: readonly T[],\n\tlimit: number,\n\ttask: (item: T) => Promise<R>,\n): Promise<PromiseSettledResult<R>[]> {\n\tconst results: PromiseSettledResult<R>[] = [];\n\tlet next = 0;\n\tconst worker = async () => {\n\t\twhile (next < items.length) {\n\t\t\tconst index = next++;\n\t\t\ttry {\n\t\t\t\tresults[index] = { status: \"fulfilled\", value: await task(items[index] as T) };\n\t\t\t} catch (reason) {\n\t\t\t\tresults[index] = { status: \"rejected\", reason };\n\t\t\t}\n\t\t}\n\t};\n\tawait Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n\treturn results;\n}\n\n/** Keeps the registry of monitors and reconciles Monitor DOs with each deployed version. */\nexport class Reconciler extends DurableObject<Env> {\n\t/** Sweeps in progress, per version. */\n\tprivate readonly sweeps = new Map<string, Promise<ReconcileReport>>();\n\t/** Per monitor ID: the tail of the operations (a sync and its registry update, or a purge) queued for it. */\n\tprivate readonly locks = new Map<string, Promise<void>>();\n\t/**\n\t * Per monitor ID: the earliest time it can become `unknown` without a new result, from its\n\t * latest snapshot (`evaluateUnknown`). In memory only: after a restart every monitor is\n\t * read once. Writing it would cost rows on every read.\n\t */\n\tprivate readonly checkAgainAt = new Map<string, number>();\n\t/** Per monitor ID: failed reads in a row, and when the first of them happened. */\n\tprivate readonly readFailureRuns = new Map<string, { readonly count: number; readonly since: number }>();\n\t/** Snapshots the sweeps got from `sync()`, with when, for the `cron` call that triggered them. */\n\tprivate readonly swept = new Map<string, { readonly snapshot: MonitorSnapshot; readonly at: number }>();\n\n\tconstructor(ctx: DurableObjectState, env: Env) {\n\t\tsuper(ctx, env);\n\t\tctx.blockConcurrencyWhile(async () => {\n\t\t\tmigrate(ctx.storage, RECONCILER_MIGRATIONS);\n\t\t});\n\t}\n\n\t/**\n\t * Syncs the Monitor DOs that this version has not synced yet: every monitor the first\n\t * time the version calls, then only those that failed, with backoff. Independently of\n\t * that, the Cron sweeps every monitor every {@link SWEEP_INTERVAL_MS}, even while some\n\t * stay pending, so that a monitor whose alarm chain broke is restarted. Concurrent calls\n\t * for a version share the sweep in progress, so the number of callers does not multiply\n\t * the work.\n\t */\n\tasync reconcile(request: ReconcileRequest): Promise<ReconcileReport> {\n\t\tconst inProgress = this.sweeps.get(request.versionId);\n\t\tif (inProgress !== undefined) return inProgress;\n\n\t\tconst now = Date.now();\n\t\tconst sweep = this.sql\n\t\t\t.exec<SweepRow>(\n\t\t\t\t\"SELECT version_id, pending, attempts, next_attempt_at, full_sweep_at FROM sweeps WHERE version_id = ?\",\n\t\t\t\trequest.versionId,\n\t\t\t)\n\t\t\t.toArray()[0];\n\t\tlet targets: string[];\n\t\tlet full: boolean;\n\t\tif (sweep === undefined || (request.periodic && now - sweep.full_sweep_at >= SWEEP_INTERVAL_MS)) {\n\t\t\ttargets = this.everyMonitor(request);\n\t\t\tfull = true;\n\t\t} else {\n\t\t\tconst pending = JSON.parse(sweep.pending) as string[];\n\t\t\tif (pending.length === 0) return { status: \"up-to-date\" };\n\t\t\tif (now < sweep.next_attempt_at) return { status: \"waiting\", nextAttemptAt: sweep.next_attempt_at };\n\t\t\ttargets = pending;\n\t\t\tfull = false;\n\t\t}\n\n\t\tconst run = this.sweep(request, targets, full, sweep).finally(() => {\n\t\t\tthis.sweeps.delete(request.versionId);\n\t\t});\n\t\tthis.sweeps.set(request.versionId, run);\n\t\treturn run;\n\t}\n\n\t/**\n\t * The every-minute Cron: reconciles (as `reconcile` with `periodic`), then reads the\n\t * snapshots the `unknown` check needs: the monitors in `alwaysRead`, and, when\n\t * `unknownCheck`, every configured monitor whose deadline has passed. A monitor's deadline is\n\t * the earliest time it could become late or stay unconfirmed too long, from its latest\n\t * snapshot, so a monitor that is not read cannot have become unknown meanwhile; a healthy\n\t * monitor checked every minute is read about every three minutes, and the sweep's syncs\n\t * (every 10 minutes) refresh deadlines at no extra cost.\n\t */\n\tasync cron(request: CronRequest): Promise<CronReport> {\n\t\tconst startedAt = Date.now();\n\t\tconst report = await this.reconcile({ ...request, periodic: true });\n\t\tconst configured = new Map(request.monitors.map((monitor) => [monitor.id, monitor]));\n\t\tfor (const id of this.checkAgainAt.keys()) if (!configured.has(id)) this.checkAgainAt.delete(id);\n\n\t\tconst snapshots = new Map<string, MonitorSnapshot>();\n\t\tfor (const [id, entry] of this.swept) {\n\t\t\tif (entry.at >= startedAt && configured.has(id)) snapshots.set(id, entry.snapshot);\n\t\t}\n\t\tthis.swept.clear();\n\n\t\tconst now = Date.now();\n\t\tconst always = new Set(request.alwaysRead);\n\t\tconst due = request.monitors.filter(\n\t\t\t(monitor) =>\n\t\t\t\t!snapshots.has(monitor.id) &&\n\t\t\t\t(always.has(monitor.id) ||\n\t\t\t\t\t(request.unknownCheck && (this.checkAgainAt.get(monitor.id) ?? Number.NEGATIVE_INFINITY) <= now)),\n\t\t);\n\t\tconst settled = await forEachLimited(due, SWEEP_CONCURRENCY, async (monitor) => {\n\t\t\tconst snapshot = (await monitorStub(this.env, monitor).getSnapshot()) as MonitorSnapshot;\n\t\t\tthis.remember(monitor, snapshot);\n\t\t\treturn snapshot;\n\t\t});\n\t\tconst readFailures: SweepFailure[] = [];\n\t\tconst unreachable: { monitorId: string; since: number }[] = [];\n\t\tsettled.forEach((outcome, index) => {\n\t\t\tconst monitorId = (due[index] as MonitorEntry).id;\n\t\t\tif (outcome.status === \"fulfilled\") {\n\t\t\t\tsnapshots.set(monitorId, outcome.value);\n\t\t\t\tthis.readFailureRuns.delete(monitorId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treadFailures.push({ monitorId, reason: String(outcome.reason) });\n\t\t\tconst previous = this.readFailureRuns.get(monitorId);\n\t\t\tconst run = { count: (previous?.count ?? 0) + 1, since: previous?.since ?? now };\n\t\t\tthis.readFailureRuns.set(monitorId, run);\n\t\t\tconst deadline = this.checkAgainAt.get(monitorId);\n\t\t\tif (deadline !== undefined ? deadline <= now : run.count >= UNREACHABLE_AFTER) {\n\t\t\t\tunreachable.push({ monitorId, since: deadline ?? run.since });\n\t\t\t}\n\t\t});\n\t\tfor (const id of snapshots.keys()) this.readFailureRuns.delete(id);\n\t\tfor (const id of this.readFailureRuns.keys()) if (!configured.has(id)) this.readFailureRuns.delete(id);\n\t\treturn { reconcile: report, snapshots: [...snapshots.values()], reads: due.length, readFailures, unreachable };\n\t}\n\n\t/** Keeps when `monitor` next needs reading, from a snapshot just read. */\n\tprivate remember(monitor: MonitorEntry, snapshot: MonitorSnapshot): void {\n\t\tthis.checkAgainAt.set(monitor.id, evaluateUnknown(snapshot, monitor.timeoutMs, Date.now()).checkAgainAt);\n\t}\n\n\t/** Every monitor the hub knows of, removed ones included, for the admin API. */\n\tlistMonitors(): RegisteredMonitor[] {\n\t\treturn this.sql\n\t\t\t.exec<RegistryRow>(\"SELECT id, status, location, first_seen_at, status_changed_at FROM monitors ORDER BY id\")\n\t\t\t.toArray()\n\t\t\t.map((row) => ({\n\t\t\t\tid: row.id,\n\t\t\t\tstatus: row.status,\n\t\t\t\tlocation: row.location,\n\t\t\t\tfirstSeenAt: row.first_seen_at,\n\t\t\t\tstatusChangedAt: row.status_changed_at,\n\t\t\t}));\n\t}\n\n\t/**\n\t * Deletes a removed monitor's data and its registry entry, on an administrator's request. Refused when the caller's configuration has the monitor, when the registry lists\n\t * it as active, and by the Monitor DO when it runs another version than the caller (a\n\t * deploy in progress) or has the monitor in its configuration. Runs one at a time with\n\t * the syncs of the same monitor, so that a sweep cannot change its entry meanwhile.\n\t */\n\tpurgeMonitor(request: PurgeMonitorRequest): Promise<PurgeMonitorResult> {\n\t\tconst { id } = request;\n\t\treturn this.exclusive(id, async (): Promise<PurgeMonitorResult> => {\n\t\t\tif (request.configuredIds.includes(id)) {\n\t\t\t\treturn { status: \"refused\", reason: \"The monitor is in status.config.ts; remove it and deploy first\", code: \"configured\" };\n\t\t\t}\n\t\t\tconst row = this.registryRow(id);\n\t\t\tif (row === undefined) return { status: \"not-found\" };\n\t\t\tif (row.status !== \"removed\") {\n\t\t\t\treturn { status: \"refused\", reason: \"The monitor is still running; wait for the deploy to finish\", code: \"running\" };\n\t\t\t}\n\t\t\tconst result = await monitorStub(this.env, { id, location: row.location }).purge({\n\t\t\t\tversionId: request.versionId,\n\t\t\t});\n\t\t\tif (result.status === \"refused\") return result;\n\t\t\tthis.sql.exec(\"DELETE FROM monitors WHERE id = ?\", id);\n\t\t\tawait forgetMonitorInD1(this.env, id);\n\t\t\treturn { status: \"purged\" };\n\t\t});\n\t}\n\n\t/** Runs `task` after the operations already queued for monitor `id`, and before later ones. */\n\tprivate async exclusive<T>(id: string, task: () => Promise<T>): Promise<T> {\n\t\tconst previous = this.locks.get(id) ?? Promise.resolve();\n\t\tlet release = () => {};\n\t\tconst done = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tconst tail = previous.then(() => done);\n\t\tthis.locks.set(id, tail);\n\t\ttry {\n\t\t\tawait previous;\n\t\t\treturn await task();\n\t\t} finally {\n\t\t\trelease();\n\t\t\tif (this.locks.get(id) === tail) this.locks.delete(id);\n\t\t}\n\t}\n\n\tprivate get sql(): SqlStorage {\n\t\treturn this.ctx.storage.sql;\n\t}\n\n\t/** The caller's monitors, plus those the registry has as active that the caller lacks (to stop them). */\n\tprivate everyMonitor(request: ReconcileRequest): string[] {\n\t\tconst listed = new Set(request.monitors.map((monitor) => monitor.id));\n\t\tconst active = this.sql\n\t\t\t.exec<{ id: string }>(\"SELECT id FROM monitors WHERE status = 'active'\")\n\t\t\t.toArray()\n\t\t\t.map((row) => row.id)\n\t\t\t.filter((id) => !listed.has(id));\n\t\treturn [...listed, ...active];\n\t}\n\n\tprivate registryRow(id: string): RegistryRow | undefined {\n\t\treturn this.sql\n\t\t\t.exec<RegistryRow>(\"SELECT id, status, location, first_seen_at, status_changed_at FROM monitors WHERE id = ?\", id)\n\t\t\t.toArray()[0];\n\t}\n\n\tprivate setStatus(row: RegistryRow, status: RegistryRow[\"status\"], now: number): void {\n\t\tif (row.status === status) return;\n\t\tthis.sql.exec(\"UPDATE monitors SET status = ?, status_changed_at = ? WHERE id = ?\", status, now, row.id);\n\t}\n\n\t/** Updates the registry from a Monitor DO's own answer: it, not the caller, knows its configuration. Writes only on change. */\n\tprivate record(id: string, result: SyncResult, now: number): void {\n\t\tconst row = this.registryRow(id);\n\t\tconst status = result.configured ? \"active\" : \"removed\";\n\t\tif (row === undefined) {\n\t\t\tif (result.status === \"absent\") return;\n\t\t\tthis.sql.exec(\n\t\t\t\t\"INSERT INTO monitors (id, status, location, first_seen_at, status_changed_at) VALUES (?, ?, ?, ?, ?)\",\n\t\t\t\tid,\n\t\t\t\tstatus,\n\t\t\t\tresult.location,\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t);\n\t\t} else {\n\t\t\tthis.setStatus(row, status, now);\n\t\t}\n\t}\n\n\tprivate async sweep(\n\t\trequest: ReconcileRequest,\n\t\ttargets: readonly string[],\n\t\tfull: boolean,\n\t\tprevious: SweepRow | undefined,\n\t) {\n\t\tconst listed = new Map(request.monitors.map((monitor) => [monitor.id, monitor.location]));\n\t\t// Each sync and the registry update from its answer run together, apart from a purge.\n\t\tconst settled = await forEachLimited(targets, SWEEP_CONCURRENCY, (id) =>\n\t\t\tthis.exclusive(id, async () => {\n\t\t\t\tconst location = listed.has(id) ? (listed.get(id) ?? null) : (this.registryRow(id)?.location ?? null);\n\t\t\t\tconst result = await monitorStub(this.env, { id, location }).sync({ location });\n\t\t\t\tconst wasActive = this.registryRow(id)?.status === \"active\";\n\t\t\t\tthis.record(id, result, Date.now());\n\t\t\t\tconst entry = request.monitors.find((monitor) => monitor.id === id);\n\t\t\t\tif (result.snapshot !== null && entry !== undefined && result.versionId === request.versionId) {\n\t\t\t\t\t// A sync is as good as a read for the `unknown` check (see `cron`).\n\t\t\t\t\tthis.remember(entry, result.snapshot);\n\t\t\t\t\tthis.swept.set(id, { snapshot: result.snapshot, at: Date.now() });\n\t\t\t\t}\n\t\t\t\treturn { result, wasActive };\n\t\t\t}),\n\t\t);\n\n\t\tconst now = Date.now();\n\t\tconst started: string[] = [];\n\t\tconst stopped: string[] = [];\n\t\tconst failures: SweepFailure[] = [];\n\t\tsettled.forEach((outcome, index) => {\n\t\t\tconst monitorId = targets[index] as string;\n\t\t\tif (outcome.status === \"rejected\") {\n\t\t\t\tfailures.push({ monitorId, reason: String(outcome.reason) });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst { result, wasActive } = outcome.value;\n\t\t\tif (result.versionId !== request.versionId) {\n\t\t\t\t// The object runs another version (a rollout in progress, or an active object that\n\t\t\t\t// has not adopted new code yet); it answered for that version. Try again later.\n\t\t\t\tfailures.push({ monitorId, reason: `its Durable Object runs version ${result.versionId}` });\n\t\t\t} else if (result.configured !== listed.has(monitorId)) {\n\t\t\t\tfailures.push({ monitorId, reason: \"its Durable Object disagrees about whether it is configured\" });\n\t\t\t} else if (result.status === \"started\" || result.status === \"resumed\") {\n\t\t\t\tstarted.push(monitorId);\n\t\t\t} else if (result.status === \"stopped\" && wasActive) {\n\t\t\t\tstopped.push(monitorId);\n\t\t\t}\n\t\t});\n\n\t\tconst attempts = failures.length === 0 ? 0 : (previous?.attempts ?? 0) + 1;\n\t\tconst nextAttemptAt =\n\t\t\tfailures.length === 0 ? null : now + Math.min(SWEEP_INTERVAL_MS, RETRY_BASE_MS * 2 ** (attempts - 1));\n\t\tthis.sql.exec(\n\t\t\t`INSERT INTO sweeps (version_id, pending, attempts, next_attempt_at, full_sweep_at, updated_at)\n\t\t\tVALUES (?, ?, ?, ?, ?, ?)\n\t\t\tON CONFLICT (version_id) DO UPDATE SET pending = excluded.pending, attempts = excluded.attempts,\n\t\t\t\tnext_attempt_at = excluded.next_attempt_at, full_sweep_at = excluded.full_sweep_at,\n\t\t\t\tupdated_at = excluded.updated_at`,\n\t\t\trequest.versionId,\n\t\t\tJSON.stringify(failures.map((failure) => failure.monitorId)),\n\t\t\tattempts,\n\t\t\tnextAttemptAt ?? now,\n\t\t\tfull ? now : (previous?.full_sweep_at ?? now),\n\t\t\tnow,\n\t\t);\n\t\tthis.sql.exec(\n\t\t\t`DELETE FROM sweeps WHERE version_id NOT IN (\n\t\t\t\tSELECT version_id FROM sweeps ORDER BY updated_at DESC LIMIT ?\n\t\t\t)`,\n\t\t\tSWEEPS_KEPT,\n\t\t);\n\n\t\tif (started.length > 0) console.log(`Started monitors: ${started.join(\", \")}`);\n\t\tif (stopped.length > 0) console.log(`Stopped monitors no longer in status.config.ts: ${stopped.join(\", \")}`);\n\t\tfor (const failure of failures) {\n\t\t\tconsole.warn(`Could not sync monitor \"${failure.monitorId}\": ${failure.reason}`);\n\t\t}\n\t\treturn {\n\t\t\tstatus: failures.length === 0 ? \"reconciled\" : \"incomplete\",\n\t\t\tversionId: request.versionId,\n\t\t\tsynced: targets.length,\n\t\t\tstarted,\n\t\t\tstopped,\n\t\t\tfailures,\n\t\t\tnextAttemptAt,\n\t\t} satisfies ReconcileReport;\n\t}\n}\n\n/**\n * Deletes what notifications and automatic incidents keep in D1 about a purged monitor:\n * its automatic incident state, `unknown` alert and held-back `down`. Its incidents and\n * delivery records stay (they are the history; deliveries expire). A failure is logged: the\n * monitor's data is gone anyway, and the rows only matter if a monitor with the same ID returns.\n */\nasync function forgetMonitorInD1(env: Env, monitorId: string): Promise<void> {\n\ttry {\n\t\tawait ensureSchema(env.DB);\n\t\tawait env.DB.batch(\n\t\t\t[\"auto_incident_monitors\", \"unknown_alerts\", \"suppressed_downs\"].map((table) =>\n\t\t\t\tenv.DB.prepare(`DELETE FROM ${table} WHERE monitor_id = ?`).bind(monitorId),\n\t\t\t),\n\t\t);\n\t} catch (error) {\n\t\tconsole.warn(`Monitor \"${monitorId}\" was purged, but its rows in D1 could not be deleted`, error);\n\t}\n}\n\n/** The Reconciler, for the Worker and the admin API (`listMonitors`, `purgeMonitor`). */\nexport function reconcilerStub(env: Env) {\n\treturn env.RECONCILER.getByName(RECONCILER_NAME);\n}\n\n/**\n * Asks the Reconciler to delete a removed monitor's data, on behalf of the version the\n * caller runs. For the admin API (`DELETE /api/admin/monitors/:id`).\n */\nexport function purgeMonitor(env: Env, id: string): Promise<PurgeMonitorResult> {\n\treturn reconcilerStub(env).purgeMonitor({\n\t\tid,\n\t\tversionId: env.CF_VERSION_METADATA.id,\n\t\tconfiguredIds: config.monitors.map((monitor) => monitor.id),\n\t});\n}\n\n/** The monitors of the version the caller runs, as the Reconciler takes them. */\nexport function configuredMonitors(): MonitorEntry[] {\n\treturn config.monitors.map((monitor) => ({\n\t\tid: monitor.id,\n\t\tlocation: monitor.location ?? null,\n\t\ttimeoutMs: monitor.timeoutMs,\n\t}));\n}\n\n/** Asks the Reconciler to reconcile the version the caller runs, with that version's monitors. */\nexport function reconcile(env: Env, trigger: \"cron\" | \"request\"): Promise<ReconcileReport> {\n\treturn reconcilerStub(env).reconcile({\n\t\tversionId: env.CF_VERSION_METADATA.id,\n\t\tmonitors: configuredMonitors(),\n\t\tperiodic: trigger === \"cron\",\n\t});\n}\n\n/** After a failed attempt, requests wait this long before asking again. */\nconst REQUEST_RETRY_MS = 60_000;\n\n/**\n * Reconciles on incoming requests without adding latency: the call runs in\n * `waitUntil`, and once the running version is reconciled, this isolate stops asking (the\n * version cannot change within an isolate). While a sweep is incomplete it asks again only\n * when the Reconciler's next attempt is due; the Reconciler itself limits the work.\n */\nexport class RequestReconciler {\n\tprivate doneVersion: string | undefined;\n\tprivate inFlight = false;\n\tprivate retryAt = 0;\n\tprivate readonly run: typeof reconcile;\n\n\tconstructor(run: typeof reconcile = reconcile) {\n\t\tthis.run = run;\n\t}\n\n\ttrigger(env: Env, ctx: ExecutionContext): void {\n\t\tconst versionId = env.CF_VERSION_METADATA.id;\n\t\tif (this.doneVersion === versionId || this.inFlight || Date.now() < this.retryAt) return;\n\t\tthis.inFlight = true;\n\t\tctx.waitUntil(\n\t\t\tthis.run(env, \"request\")\n\t\t\t\t.then((report) => {\n\t\t\t\t\tif (report.status === \"up-to-date\" || report.status === \"reconciled\") {\n\t\t\t\t\t\tthis.doneVersion = versionId;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.retryAt = report.nextAttemptAt ?? Date.now() + REQUEST_RETRY_MS;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\tthis.retryAt = Date.now() + REQUEST_RETRY_MS;\n\t\t\t\t\tconsole.error(\"Reconciliation failed\", error);\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tthis.inFlight = false;\n\t\t\t\t}),\n\t\t);\n\t}\n}\n","import { DurableObject } from \"cloudflare:workers\";\nimport {\n\ttype CalendarDay,\n\tcombineTimelines,\n\tcomponentState,\n\tconcatSegments,\n\tcoverageRatio,\n\ttype DisplayState,\n\ttype DownPeriod,\n\tdisplayState,\n\tdownPeriods,\n\texcludeWindows,\n\tmergeDownPeriods,\n\ttype ResolvedMonitor,\n\ttype ResolvedPage,\n\trecentDays,\n\ttype Segment,\n\ttype StateRecord,\n\tstaleAfterMs,\n\tsummarize,\n\ttype TimeRange,\n\tuptimeRatio,\n\tworstState,\n} from \"@naosystem/cf-workers-status-page-core\";\nimport type {\n\tComponentHistory,\n\tComponentLatency,\n\tComponentStatus,\n\tHistoryDay,\n\tHistoryMarker,\n\tPageHistoryResponse,\n\tPageLatencyResponse,\n\tPageStatusResponse,\n\tStoppage,\n\tStoppagesResponse,\n} from \"../shared/public-api\";\nimport { config, findPage, pageMonitors } from \"./config\";\nimport { defaultAppearance, getAppearance } from \"./db/appearance\";\nimport type { Incident, Maintenance, PageAppearance } from \"../shared/admin-api\";\nimport {\n\ttype IncidentWithLatestUpdates,\n\tlistIncidentsChangedSince,\n\tlistIncidentsSince,\n\tlistOpenIncidentsWithUpdates,\n\tMAX_HISTORY_INCIDENTS,\n} from \"./db/incidents\";\nimport { listMaintenanceBetween, listMaintenanceOverlapping } from \"./db/maintenance\";\nimport { ensureSchema } from \"./db/schema\";\nimport {\n\tconcatLatency,\n\tdecodeLatency,\n\tencodeLatency,\n\tLATENCY_RANGES,\n\tlatencySeries,\n\tlatencySince,\n\tmergeLatency,\n\tNO_LATENCY,\n\ttype PackedLatency,\n\tpackLatency,\n\tunpackLatency,\n} from \"./latency\";\nimport {\n\ttype MonitorSnapshot,\n\tmonitorStub,\n\ttype PageReadResponse,\n\tsettledAfterMs,\n\ttype TimelineSlice,\n} from \"./monitor\";\nimport type { PageViewRoute } from \"./public/routes\";\nimport { publicAppearance, publicIncidentWithUpdates, publicMaintenance } from \"./public/views\";\nimport { forEachLimited } from \"./reconciler\";\nimport { MeteredStorage, type Migration, migrate, STORAGE_USAGE, type StorageUsage } from \"./storage\";\nimport { uploadsBucket } from \"./uploads\";\n\n/** Days of history a page shows, today included. */\nexport const HISTORY_DAYS = 90;\n/**\n * Monitor DOs read at once. Durable Object calls are not among the connections limited to\n * six per invocation (fetch, KV, Cache, R2, Queues, sockets:\n * https://developers.cloudflare.com/workers/platform/limits/#simultaneous-open-connections);\n * this only bounds the results held at once.\n */\nconst MONITOR_CONCURRENCY = 32;\n/**\n * Result rows one read may take from each Monitor DO (about 7 days of a monitor checked every\n * minute; `maxRows` of its `getTimeline`). The newest stretches come first, and at least one\n * is read, so a history missing many days (after the time zone changed, say) fills in over a\n * few reads; its days are `pending` meanwhile, and the history is computed again after\n * {@link PENDING_TTL_MS}.\n */\nexport const FILL_ROWS_PER_MONITOR = 10_000;\n/** A day's cached data grows in steps of this, so that the cache is written at most hourly per monitor. */\nconst CACHE_STEP_MS = 3_600_000;\n/** Most stoppages listed. */\nexport const STOPPAGE_LIMIT = 100;\n/**\n * How long a computed status is used (about 30 seconds): the current state is\n * what visitors come for. Monitors whose state cannot have changed since they were last read\n * (no check has ended since) are not read again, so this costs about one Durable Object\n * request per monitor per check, at most two per minute.\n */\nexport const STATUS_TTL_MS = 30_000;\n/**\n * How long a computed history and stoppage list are used. They describe past days and past\n * outages: today's bar and a new stoppage may lag by up to 5 minutes, while the current\n * state is in the status (30 seconds). Reading today's stretch of every monitor costs about\n * an hour of results each; doing it every 5 minutes instead of every 30 seconds reads ten\n * times fewer rows. An administrator's change still shows at once.\n */\nexport const HISTORY_TTL_MS = 5 * 60_000;\nexport const STOPPAGES_TTL_MS = 5 * 60_000;\n/** For a history whose missing days are being filled in (bounded by {@link FILL_ROWS_PER_MONITOR} per read). */\nexport const PENDING_TTL_MS = 5_000;\n/**\n * The history's incidents are read in full at most this often (and after an incident is\n * deleted); in between, only those changed since the last read (`incidents_by_page_updated`),\n * so that a page with thousands of incidents in its window does not read them all every 5\n * minutes (D1's rows read are limited per day on the Free plan, notifications included).\n */\nexport const INCIDENTS_FULL_READ_MS = 6 * 3_600_000;\n/** Changes are read from this long before the last read, for writers' clocks and transactions that commit late. */\nexport const INCIDENTS_OVERLAP_MS = 5 * 60_000;\n/**\n * How long a status or history is used when D1 could not be read (its incidents, maintenance\n * and appearance are then as last read): short, so that the page recovers soon after D1 does,\n * and the edge never keeps it longer than this.\n */\nexport const OUTDATED_TTL_MS = 10_000;\n/** Updates of each unresolved incident in a page's status; an incident's own URL has its whole timeline. */\nexport const STATUS_UPDATES_PER_INCIDENT = 10;\n/**\n * How long an announced change (see {@link StatusPage.beginChange}) keeps responses from\n * being cached when its end is never reported (the write was refused or failed, say). A D1\n * write takes well under this.\n */\nexport const CHANGE_WINDOW_MS = 15_000;\n/**\n * What cached days were computed with. A different value discards them all (they are\n * recomputed from the monitors' data): the format and the code's rules (this number), the\n * time zone, and the lateness and settling rules, by their values at a few points.\n */\nconst DAYS_FORMAT = 3;\nconst DAYS_BASIS_KEY = \"days.basis\";\n\n/**\n * With `latency`, the page has components that publish response times, and its cached days\n * carry them (for every monitor of the page, so that turning them on for one more component\n * needs no new reads); days cached without them are discarded when it changes.\n */\nexport function daysBasis(timezone: string, latency = false): string {\n\tconst settle = (intervalMs: number, timeoutMs: number) =>\n\t\tsettledAfterMs({ intervalMs, timeoutMs, confirmation: { failureThreshold: 1, successThreshold: 1, recheckIntervalMs: 1 } });\n\treturn [\n\t\tDAYS_FORMAT,\n\t\ttimezone,\n\t\tstaleAfterMs(0, 0),\n\t\tstaleAfterMs(1, 0),\n\t\tstaleAfterMs(0, 1),\n\t\tsettle(0, 0),\n\t\tsettle(1, 0),\n\t\tsettle(0, 1),\n\t\t...(latency ? [\"latency\"] : []),\n\t].join(\" \");\n}\n\n/** Whether the page publishes response times (`components[].latency`). */\nfunction hasLatency(page: ResolvedPage): boolean {\n\treturn page.components.some((component) => component.latency);\n}\n\n/**\n * Schema. As in the Monitor DO, tables are `WITHOUT ROWID` and have no secondary index, so\n * each insert or update writes one row.\n *\n * - `monitor_days`: the daily values cache. Per monitor and local day, its display\n * timeline (segments as JSON) and coverage counts for `[day_from, covered_to)`. Past days\n * are complete; today's grows hourly, behind what the monitor may still change (see\n * `settledAfterMs`). Monitor-level, not component-level, so maintenance and component\n * membership apply when a response is built and never invalidate it. Loaded into memory\n * once per instance.\n * - `monitor_sources`: per monitor, the `startedAt` its cached days came from (`NULL`: it had\n * no data). A different `startedAt` means the monitor was purged and started again, so its\n * cached days are discarded.\n * - `monitor_days.latency` (version 2): the day's response times in 15-minute buckets (see\n * latency.ts), for days within the last 30, on pages that publish them; `[]` otherwise.\n *\n * The first scaffold's `monitors` table is dropped: nothing reads it any more, and the scaffold's\n * code, after a rollback, would create it again.\n */\nconst STATUS_PAGE_MIGRATIONS: readonly Migration[] = [\n\t{\n\t\tversion: 1,\n\t\tdescription: \"daily values cache\",\n\t\tup(sql) {\n\t\t\tsql.exec(\"DROP TABLE IF EXISTS monitors\");\n\t\t\tsql.exec(`\n\t\t\t\tCREATE TABLE monitor_days (\n\t\t\t\t\tmonitor_id TEXT NOT NULL,\n\t\t\t\t\tday TEXT NOT NULL,\n\t\t\t\t\tday_from INTEGER NOT NULL,\n\t\t\t\t\tday_to INTEGER NOT NULL,\n\t\t\t\t\tcovered_to INTEGER NOT NULL,\n\t\t\t\t\texpected INTEGER NOT NULL,\n\t\t\t\t\tobtained INTEGER NOT NULL,\n\t\t\t\t\tsegments TEXT NOT NULL,\n\t\t\t\t\tPRIMARY KEY (monitor_id, day)\n\t\t\t\t) WITHOUT ROWID\n\t\t\t`);\n\t\t\tsql.exec(`\n\t\t\t\tCREATE TABLE monitor_sources (\n\t\t\t\t\tmonitor_id TEXT PRIMARY KEY,\n\t\t\t\t\tstarted_at INTEGER\n\t\t\t\t) WITHOUT ROWID\n\t\t\t`);\n\t\t},\n\t},\n\t{\n\t\tversion: 2,\n\t\tdescription: \"response times in the daily values cache\",\n\t\tup(sql) {\n\t\t\t// Days cached before have none: the new days basis discards them.\n\t\t\tsql.exec(\"ALTER TABLE monitor_days ADD COLUMN latency TEXT NOT NULL DEFAULT '[]'\");\n\t\t},\n\t},\n];\n\n/**\n * Segments packed as `[from, to, state code]` triples in one typed array: 24 bytes each\n * instead of an object, so that the days kept in memory stay small even for a monitor that\n * flaps all day. Unpacked only while a response is computed.\n */\ntype PackedSegments = Float64Array;\n\nconst STATE_CODES: readonly DisplayState[] = [\"up\", \"unknown\", \"degraded\", \"down\"];\nconst CODE_OF: Readonly<Record<DisplayState, number>> = { up: 0, unknown: 1, degraded: 2, down: 3 };\n\nfunction pack(segments: readonly Segment[]): PackedSegments {\n\tconst packed = new Float64Array(segments.length * 3);\n\tsegments.forEach((segment, index) => {\n\t\tpacked[index * 3] = segment.from;\n\t\tpacked[index * 3 + 1] = segment.to;\n\t\tpacked[index * 3 + 2] = CODE_OF[segment.state];\n\t});\n\treturn packed;\n}\n\nfunction unpack(packed: PackedSegments): Segment[] {\n\tconst segments: Segment[] = [];\n\tfor (let index = 0; index + 2 < packed.length; index += 3) {\n\t\tsegments.push({\n\t\t\tfrom: packed[index] as number,\n\t\t\tto: packed[index + 1] as number,\n\t\t\tstate: STATE_CODES[packed[index + 2] as number] ?? \"unknown\",\n\t\t});\n\t}\n\treturn segments;\n}\n\n/** A monitor's data for (part of) a local day. */\ninterface DayData extends TimeRange {\n\t/** The data covers `[from, coveredTo)`. */\n\treadonly coveredTo: number;\n\treadonly expected: number;\n\treadonly obtained: number;\n\treadonly segments: PackedSegments;\n\t/** Response times; empty for days older than the published series, and on pages without them. */\n\treadonly latency: PackedLatency;\n}\n\n/** A monitor's day: its data, or `pending` when it is not computed yet. Days without data are absent. */\ntype MonitorDay = DayData | \"pending\";\n\ntype DayRow = {\n\tmonitor_id: string;\n\tday: string;\n\tday_from: number;\n\tday_to: number;\n\tcovered_to: number;\n\texpected: number;\n\tobtained: number;\n\tsegments: string;\n\tlatency: string;\n};\n\ntype StoredSegment = [from: number, to: number, state: DisplayState];\n\nfunction encodeSegments(segments: PackedSegments): string {\n\treturn JSON.stringify(unpack(segments).map((segment): StoredSegment => [segment.from, segment.to, segment.state]));\n}\n\nfunction decodeSegments(text: string): PackedSegments {\n\ttry {\n\t\treturn pack((JSON.parse(text) as StoredSegment[]).map(([from, to, state]) => ({ from, to, state })));\n\t} catch {\n\t\treturn new Float64Array();\n\t}\n}\n\n/**\n * Where a day's data may be cached up to: whole steps from the day's start, behind what the\n * monitor may still change (`settleMs` before now).\n */\nexport function storableEnd(day: TimeRange, now: number, settleMs: number): number {\n\tconst settled = now - settleMs;\n\tif (settled >= day.to) return day.to;\n\tif (settled <= day.from) return day.from;\n\treturn day.from + Math.floor((settled - day.from) / CACHE_STEP_MS) * CACHE_STEP_MS;\n}\n\n/**\n * Until when a monitor's snapshot read at `readAt` still holds: its state, results and state\n * records change only when a check ends. So it holds until the next slot of its schedule,\n * or the re-check that may follow a result that was not `up`, or one configured interval\n * (in case a deploy shortened it), whichever comes first;\n * and not at all while the current slot's check has not been recorded yet, or while the\n * monitor is not running. Lateness, which grows without any check, is derived at display\n * time and needs no read.\n */\nexport function snapshotValidUntil(\n\tsnapshot: MonitorSnapshot,\n\tmonitor: { readonly intervalMs: number; readonly confirmation: { readonly recheckIntervalMs: number } },\n\treadAt: number,\n): number {\n\tconst recheckIntervalMs = monitor.confirmation.recheckIntervalMs;\n\t// Views asked for together (a visitor's page loads all three) share a read in any case.\n\tconst floor = readAt + REREAD_AFTER_MS;\n\tconst { period, lastCheck } = snapshot;\n\tif (period === null || period.status !== \"active\" || period.intervalMs === null) return floor;\n\tconst slot = period.from + Math.floor((readAt - period.from) / period.intervalMs) * period.intervalMs;\n\tif (lastCheck === null || lastCheck.at < slot) return floor;\n\t// After a deploy that shortened the interval, the monitor checks at the new one as soon as\n\t// it runs the new version, before its recorded period says so.\n\tlet until = Math.min(slot + period.intervalMs, readAt + monitor.intervalMs);\n\tif (lastCheck.state !== \"up\") until = Math.min(until, lastCheck.at + recheckIntervalMs);\n\treturn Math.max(floor, until);\n}\n\n/** A monitor read this recently is not read again, whatever may have changed. */\nconst REREAD_AFTER_MS = 10_000;\n\nfunction emptyDay(day: TimeRange): DayData {\n\treturn { from: day.from, to: day.to, coveredTo: day.from, expected: 0, obtained: 0, segments: new Float64Array(), latency: NO_LATENCY };\n}\n\n/** `data` extended by `slice`, which must start where `data` ends. */\nfunction extend(data: DayData, slice: TimelineSlice): DayData {\n\treturn {\n\t\tfrom: data.from,\n\t\tto: data.to,\n\t\tcoveredTo: slice.to,\n\t\texpected: data.expected + slice.expected,\n\t\tobtained: data.obtained + slice.obtained,\n\t\tsegments: pack(concatSegments(unpack(data.segments), slice.segments)),\n\t\tlatency: concatLatency(data.latency, packLatency(slice.latency ?? [])),\n\t};\n}\n\nfunction overlaps(day: TimeRange, from: number, to: number | null): boolean {\n\treturn from < day.to && (to === null || to > day.from);\n}\n\n/** A computed response of the page, serialized once. */\nexport interface ViewResult {\n\treadonly status: 200 | 400 | 404;\n\t/** The response body, as JSON text. */\n\treadonly json: string;\n\treadonly generatedAt: number;\n\t/** Fresh until `generatedAt + ttlMs`. */\n\treadonly ttlMs: number;\n\t/**\n\t * `false` when an administrator changed the page while it was computed: serve it to the\n\t * request that asked, but cache it nowhere, so that it cannot outlive the change.\n\t */\n\treadonly cacheable: boolean;\n}\n\ntype Computed = Omit<ViewResult, \"cacheable\">;\n\nfunction view(body: unknown, generatedAt: number, ttlMs: number, status: 200 | 404 = 200): Computed {\n\treturn { status, json: JSON.stringify(body), generatedAt, ttlMs };\n}\n\n/**\n * Computed responses, reused while fresh and dropped when an administrator changes the page.\n * A response being computed is shared, so concurrent requests compute it once.\n *\n * A response is cacheable only if no change of the page overlapped its computation: the\n * generation did not move meanwhile ({@link Views.invalidate} after a change, and\n * {@link Views.beginChange} before it, both move it), and no announced change is still in\n * progress when it ends (its data may predate the write that is about to commit). Such a\n * response is served to the request that asked, and kept nowhere.\n */\nclass Views {\n\tprivate generation = 0;\n\t/** Ends of the announced changes in progress, oldest first; each expires on its own. */\n\tprivate changes: number[] = [];\n\tprivate readonly entries = new Map<string, { readonly at: number; readonly value: Promise<ViewResult>; ttl?: number }>();\n\n\tget(key: string, compute: () => Promise<Computed>): Promise<ViewResult> {\n\t\tconst now = Date.now();\n\t\tconst entry = this.entries.get(key);\n\t\tif (entry !== undefined && now >= entry.at && (entry.ttl === undefined || now - entry.at < entry.ttl)) {\n\t\t\treturn entry.value;\n\t\t}\n\t\tconst generation = this.generation;\n\t\tconst fresh: { readonly at: number; readonly value: Promise<ViewResult>; ttl?: number } = {\n\t\t\tat: now,\n\t\t\tvalue: compute().then((computed) => ({\n\t\t\t\t...computed,\n\t\t\t\tcacheable: generation === this.generation && !this.changing(Date.now()),\n\t\t\t})),\n\t\t};\n\t\tthis.entries.set(key, fresh);\n\t\tfresh.value.then(\n\t\t\t(value) => {\n\t\t\t\tfresh.ttl = value.cacheable ? value.ttlMs : 0;\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tif (this.entries.get(key) === fresh) this.entries.delete(key);\n\t\t\t},\n\t\t);\n\t\treturn fresh.value;\n\t}\n\n\t/** A change is about to be written: nothing computed until it is reported done is cached. */\n\tbeginChange(now = Date.now()): void {\n\t\tthis.changes.push(now + CHANGE_WINDOW_MS);\n\t\tthis.generation++;\n\t\tthis.entries.clear();\n\t}\n\n\t/** A change was written (it ends the oldest announced one, if any). */\n\tinvalidate(now = Date.now()): void {\n\t\tthis.changing(now);\n\t\tthis.changes.shift();\n\t\tthis.generation++;\n\t\tthis.entries.clear();\n\t}\n\n\tprivate changing(now: number): boolean {\n\t\tthis.changes = this.changes.filter((end) => end > now);\n\t\treturn this.changes.length > 0;\n\t}\n}\n\n/** What the page last read from a monitor. */\ninterface SnapshotEntry {\n\treadonly value: MonitorSnapshot;\n\treadonly validUntil: number;\n}\n\ninterface TransitionsEntry {\n\treadonly atStart: StateRecord | null;\n\t/** Oldest first; at most `2 × STOPPAGE_LIMIT`. */\n\treadonly records: readonly StateRecord[];\n\treadonly truncated: boolean;\n}\n\ninterface HistoryEntry {\n\treadonly readAt: number;\n\t/** The local date that was today when it was read. */\n\treadonly today: string;\n\treadonly days: ReadonlyMap<string, MonitorDay>;\n\t/** Some stretches were left for later (`maxRows`): the history is still being filled in. */\n\treadonly filling: boolean;\n}\n\ninterface Want {\n\treadonly snapshot: boolean;\n\treadonly history: boolean;\n}\n\n/** Counters for tests and measurements. A symbol, so that it is not reachable over RPC. */\nexport const PAGE_METRICS: unique symbol = Symbol(\"pageMetrics\");\n\nexport interface PageMetrics {\n\t/** Views asked for (each a billed Durable Object request to this object). */\n\tviewRequests: number;\n\t/** Monitor DO calls made (each a billed Durable Object request). */\n\tmonitorReads: number;\n}\n\n/**\n * One instance per status page (`pages[].id`), answering its public API. It pulls\n * from the Monitor DOs of its components when a response is built, never the other\n * way round, and reads incidents, maintenance and appearance from D1. Monitors that are in\n * none of its components are never read, and responses carry component-level data only.\n *\n * Costs per page, whatever the number of visitors (each Durable Object call is a billed\n * request, and on the Free plan they share a daily limit with the monitors' own alarms):\n *\n * - One `readForPage` call per monitor serves all views: its current state, new state records\n * and, when the history is due, today's stretch. A monitor whose state cannot have changed\n * since its last read ({@link snapshotValidUntil}) is not read.\n * - Computed responses are reused ({@link STATUS_TTL_MS}, {@link HISTORY_TTL_MS},\n * {@link STOPPAGES_TTL_MS}) and dropped by {@link invalidate} when\n * an administrator changes the page; in front of them, the Worker keeps them too.\n * - Past days of the history are cached in SQLite and, decoded, in memory.\n *\n * The configuration is the one of the version this object runs, like the Monitor DOs'.\n */\nexport class StatusPage extends DurableObject<Env> {\n\tprivate readonly store: MeteredStorage;\n\tprivate readonly views = new Views();\n\tprivate readonly metrics: PageMetrics = { viewRequests: 0, monitorReads: 0 };\n\tprivate readonly snapshots = new Map<string, SnapshotEntry>();\n\tprivate readonly transitions = new Map<string, TransitionsEntry>();\n\tprivate readonly histories = new Map<string, HistoryEntry>();\n\t/** The daily values cache, decoded: per monitor, its settled days. Loaded once. */\n\tprivate days: Map<string, Map<string, DayData>> | null = null;\n\t/** Per monitor, the `startedAt` of the cached days (`null`: no data). */\n\tprivate readonly sources = new Map<string, number | null>();\n\t/** When the history was last asked for: today's stretches are then read with the states. */\n\tprivate historyAskedAt = Number.NEGATIVE_INFINITY;\n\tprivate reading: Promise<void> | null = null;\n\t/** The history window's incidents as last read, by ID (see {@link INCIDENTS_FULL_READ_MS}). */\n\tprivate incidents: { readonly byId: ReadonlyMap<string, Incident>; readonly from: number; readonly syncedAt: number; readonly loadedAt: number } | null =\n\t\tnull;\n\t/** Moved when incidents are deleted: a read that spans it is not kept. */\n\tprivate incidentGeneration = 0;\n\t/**\n\t * What the status and the history last read from D1, used when D1 cannot be read (the Free\n\t * plan's daily limit, an outage): the monitors' states are still worth showing.\n\t */\n\tprivate lastStatusData: {\n\t\treadonly incidents: readonly IncidentWithLatestUpdates[];\n\t\treadonly maintenance: readonly Maintenance[];\n\t\treadonly appearance: PageAppearance;\n\t} | null = null;\n\tprivate lastHistoryData: { readonly incidents: readonly Incident[]; readonly maintenance: readonly Maintenance[] } | null = null;\n\n\tconstructor(ctx: DurableObjectState, env: Env) {\n\t\tsuper(ctx, env);\n\t\tthis.store = new MeteredStorage(ctx.storage);\n\t\tctx.blockConcurrencyWhile(async () => {\n\t\t\tmigrate(ctx.storage, STATUS_PAGE_MIGRATIONS);\n\t\t});\n\t}\n\n\t/** Rows read and written by this instance; for tests. */\n\tget [STORAGE_USAGE](): StorageUsage {\n\t\treturn this.store.usage;\n\t}\n\n\tget [PAGE_METRICS](): PageMetrics {\n\t\treturn this.metrics;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// RPC\n\t// -------------------------------------------------------------------------\n\n\t/** The status, history or stoppages, serialized. Incidents are read from D1 by the Worker. */\n\tgetView(route: PageViewRoute): Promise<ViewResult> {\n\t\tthis.metrics.viewRequests++;\n\t\tconst page = this.page();\n\t\tswitch (route.kind) {\n\t\t\tcase \"status\":\n\t\t\t\treturn this.views.get(\"status\", () => this.buildStatus(page));\n\t\t\tcase \"history\":\n\t\t\t\treturn this.views.get(\"history\", () => this.buildHistory(page));\n\t\t\tcase \"stoppages\":\n\t\t\t\treturn this.views.get(\"stoppages\", () => this.buildStoppages(page));\n\t\t\tcase \"latency\":\n\t\t\t\treturn this.views.get(\"latency\", () => this.buildLatency(page));\n\t\t}\n\t}\n\n\t/** The current status, parsed (for tests and tools; the public API uses {@link getView}). */\n\tasync getStatus(): Promise<PageStatusResponse> {\n\t\treturn JSON.parse((await this.getView({ kind: \"status\", pageId: this.page().id })).json) as PageStatusResponse;\n\t}\n\n\tasync getHistory(): Promise<PageHistoryResponse> {\n\t\treturn JSON.parse((await this.getView({ kind: \"history\", pageId: this.page().id })).json) as PageHistoryResponse;\n\t}\n\n\tasync getStoppages(): Promise<StoppagesResponse> {\n\t\treturn JSON.parse((await this.getView({ kind: \"stoppages\", pageId: this.page().id })).json) as StoppagesResponse;\n\t}\n\n\tasync getLatency(): Promise<PageLatencyResponse> {\n\t\treturn JSON.parse((await this.getView({ kind: \"latency\", pageId: this.page().id })).json) as PageLatencyResponse;\n\t}\n\n\t/**\n\t * An administrator (or automation) is about to change what the page shows: until\n\t * {@link invalidate} reports the change written (or {@link CHANGE_WINDOW_MS} passes), no\n\t * response computed here is cacheable, since it may have read the data before the write.\n\t */\n\tbeginChange(): void {\n\t\tthis.views.beginChange();\n\t}\n\n\t/**\n\t * Drops the computed responses, after an administrator changed what the page shows.\n\t * Responses being computed meanwhile are marked not cacheable. With `incidentsDeleted`, the\n\t * history's incidents are read in full next time (reading changes cannot see a deletion).\n\t */\n\tinvalidate(options: { readonly incidentsDeleted?: boolean } = {}): void {\n\t\tif (options.incidentsDeleted === true) {\n\t\t\tthis.incidentGeneration++;\n\t\t\tthis.incidents = null;\n\t\t}\n\t\tthis.views.invalidate();\n\t}\n\n\t/** Reads of D1 for the history's incidents so far: full and incremental (for tests). */\n\treadonly incidentReads = { full: 0, changes: 0 };\n\n\t/**\n\t * The page's incidents that were unresolved at some time since `from`, for the history:\n\t * read in full at most every {@link INCIDENTS_FULL_READ_MS}, else only those changed since\n\t * the last read (with {@link INCIDENTS_OVERLAP_MS} of overlap), merged into what was read.\n\t */\n\tprivate async historyIncidents(pageId: string, from: number): Promise<Incident[]> {\n\t\tconst generation = this.incidentGeneration;\n\t\tconst startedAt = Date.now();\n\t\tconst cached = this.incidents;\n\t\tlet byId: Map<string, Incident> | null = null;\n\t\tlet loadedAt = startedAt;\n\t\tif (cached !== null && startedAt - cached.loadedAt < INCIDENTS_FULL_READ_MS && from >= cached.from) {\n\t\t\tthis.incidentReads.changes++;\n\t\t\tconst changed = await listIncidentsChangedSince(this.env.DB, pageId, cached.syncedAt - INCIDENTS_OVERLAP_MS);\n\t\t\tif (changed !== null) {\n\t\t\t\tbyId = new Map(cached.byId);\n\t\t\t\tfor (const incident of changed) byId.set(incident.id, incident);\n\t\t\t\tloadedAt = cached.loadedAt;\n\t\t\t}\n\t\t}\n\t\tif (byId === null) {\n\t\t\tthis.incidentReads.full++;\n\t\t\tbyId = new Map((await listIncidentsSince(this.env.DB, pageId, from)).map((incident) => [incident.id, incident]));\n\t\t}\n\t\tfor (const [id, incident] of byId) {\n\t\t\tif (incident.resolvedAt !== null && incident.resolvedAt < from) byId.delete(id);\n\t\t}\n\t\t// Kept unless incidents were deleted meanwhile, or there are more than a full read keeps.\n\t\tif (generation === this.incidentGeneration) {\n\t\t\tthis.incidents = byId.size <= MAX_HISTORY_INCIDENTS ? { byId, from, syncedAt: startedAt, loadedAt } : null;\n\t\t}\n\t\treturn [...byId.values()];\n\t}\n\n\tprivate page(): ResolvedPage {\n\t\tconst name = this.ctx.id.name;\n\t\tconst page = name === undefined ? undefined : findPage(name);\n\t\tif (page === undefined) throw new Error(`No page \"${name}\" in the configuration of this version`);\n\t\treturn page;\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Reading monitors\n\t// -------------------------------------------------------------------------\n\n\tprivate snapshotStale(monitor: ResolvedMonitor, now: number): boolean {\n\t\tconst entry = this.snapshots.get(monitor.id);\n\t\treturn entry === undefined || entry.validUntil <= now || !this.transitions.has(monitor.id);\n\t}\n\n\t/** Whether the monitor's history entry is older than `maxAge`, of another day, or being filled in. */\n\tprivate historyStale(monitor: ResolvedMonitor, now: number, today: string, maxAge: number): boolean {\n\t\tconst entry = this.histories.get(monitor.id);\n\t\tif (entry === undefined || entry.today !== today) return true;\n\t\treturn now - entry.readAt >= (entry.filling ? Math.min(maxAge, PENDING_TTL_MS) : maxAge);\n\t}\n\n\t/**\n\t * Reads what `want` says each monitor needs, one call per monitor. A read in progress is\n\t * awaited first and what it brought is taken into account, so views asked for together\n\t * share one read.\n\t */\n\tprivate async ensureMonitors(page: ResolvedPage, want: (monitor: ResolvedMonitor, now: number) => Want): Promise<void> {\n\t\twhile (this.reading !== null) await this.reading.catch(() => {});\n\t\tconst now = Date.now();\n\t\tconst wanted = pageMonitors(page).flatMap((monitor) => {\n\t\t\tconst needs = want(monitor, now);\n\t\t\treturn needs.snapshot || needs.history ? [{ monitor, needs }] : [];\n\t\t});\n\t\tif (wanted.length === 0) return;\n\t\tthis.reading = this.readMonitors(page, now, wanted).finally(() => {\n\t\t\tthis.reading = null;\n\t\t});\n\t\tawait this.reading;\n\t}\n\n\tprivate visibleDays(now: number): CalendarDay[] {\n\t\tconst cutoff = config.retentionMs === null ? Number.NEGATIVE_INFINITY : now - config.retentionMs;\n\t\treturn recentDays(now, config.timezone, HISTORY_DAYS).filter((day) => day.from >= cutoff);\n\t}\n\n\t/** The daily values cache, loaded (once) and pruned of what the page no longer needs. */\n\tprivate dayCache(page: ResolvedPage, days: readonly CalendarDay[]): Map<string, Map<string, DayData>> {\n\t\tconst since = latencySince(Date.now());\n\t\tif (this.days === null) {\n\t\t\tconst basis = daysBasis(config.timezone, hasLatency(page));\n\t\t\tif (this.store.kvGet<string>(DAYS_BASIS_KEY) !== basis) {\n\t\t\t\tthis.store.transaction(() => {\n\t\t\t\t\tthis.store.run(\"DELETE FROM monitor_days\");\n\t\t\t\t\tthis.store.run(\"DELETE FROM monitor_sources\");\n\t\t\t\t\tthis.store.kvPut(DAYS_BASIS_KEY, basis);\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (const row of this.store.all<{ monitor_id: string; started_at: number | null }>(\n\t\t\t\t\"SELECT monitor_id, started_at FROM monitor_sources\",\n\t\t\t)) {\n\t\t\t\tthis.sources.set(row.monitor_id, row.started_at);\n\t\t\t}\n\t\t\tthis.days = new Map();\n\t\t\tfor (const row of this.store.all<DayRow>(\n\t\t\t\t\"SELECT monitor_id, day, day_from, day_to, covered_to, expected, obtained, segments, latency FROM monitor_days\",\n\t\t\t)) {\n\t\t\t\tconst byDay = this.days.get(row.monitor_id) ?? new Map<string, DayData>();\n\t\t\t\tbyDay.set(row.day, {\n\t\t\t\t\tfrom: row.day_from,\n\t\t\t\t\tto: row.day_to,\n\t\t\t\t\tcoveredTo: row.covered_to,\n\t\t\t\t\texpected: row.expected,\n\t\t\t\t\tobtained: row.obtained,\n\t\t\t\t\tsegments: decodeSegments(row.segments),\n\t\t\t\t\tlatency: row.day_to > since ? decodeLatency(row.latency) : NO_LATENCY,\n\t\t\t\t});\n\t\t\t\tthis.days.set(row.monitor_id, byDay);\n\t\t\t}\n\t\t}\n\t\t// Days out of the window or past retention, monitors no longer on the page, days of\n\t\t// monitors without a source, and (defensively) days whose bounds no longer match.\n\t\tconst wanted = new Map(days.map((day) => [day.date, day]));\n\t\tconst onPage = new Set(pageMonitors(page).map((monitor) => monitor.id));\n\t\tconst obsolete: [string, string | null][] = [];\n\t\tfor (const [id, byDay] of this.days) {\n\t\t\tif (!onPage.has(id) || !this.sources.has(id)) {\n\t\t\t\tobsolete.push([id, null]);\n\t\t\t\tthis.days.delete(id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const [date, data] of byDay) {\n\t\t\t\tconst day = wanted.get(date);\n\t\t\t\tif (day === undefined || day.from !== data.from || day.to !== data.to) {\n\t\t\t\t\tobsolete.push([id, date]);\n\t\t\t\t\tbyDay.delete(date);\n\t\t\t\t} else if (data.latency.length > 0 && data.to <= since) {\n\t\t\t\t\t// Older than the published series: not needed in memory any more.\n\t\t\t\t\tbyDay.set(date, { ...data, latency: NO_LATENCY });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst gone = [...this.sources.keys()].filter((id) => !onPage.has(id));\n\t\tif (obsolete.length > 0 || gone.length > 0) {\n\t\t\tthis.store.transaction(() => {\n\t\t\t\tfor (const [id, date] of obsolete) {\n\t\t\t\t\tif (date === null) this.store.run(\"DELETE FROM monitor_days WHERE monitor_id = ?\", id);\n\t\t\t\t\telse this.store.run(\"DELETE FROM monitor_days WHERE monitor_id = ? AND day = ?\", id, date);\n\t\t\t\t}\n\t\t\t\tfor (const id of gone) {\n\t\t\t\t\tthis.store.run(\"DELETE FROM monitor_sources WHERE monitor_id = ?\", id);\n\t\t\t\t\tthis.sources.delete(id);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn this.days;\n\t}\n\n\t/**\n\t * The history stretches to read from a monitor, newest day first: per day, what is not\n\t * cached yet, split into what has settled (cached once read) and the rest (read each time).\n\t */\n\tprivate planHistory(\n\t\tmonitor: ResolvedMonitor,\n\t\tdays: readonly CalendarDay[],\n\t\tcache: ReadonlyMap<string, ReadonlyMap<string, DayData>>,\n\t\tnow: number,\n\t): { readonly date: string; readonly kind: \"stored\" | \"live\"; readonly range: TimeRange }[] {\n\t\tconst startedAt = this.sources.get(monitor.id);\n\t\tconst entries: { date: string; kind: \"stored\" | \"live\"; range: TimeRange }[] = [];\n\t\tfor (const day of [...days].reverse()) {\n\t\t\t// A monitor without data: only today is asked for, to notice when it starts.\n\t\t\tif (startedAt === null && day.to <= now) continue;\n\t\t\tif (typeof startedAt === \"number\" && day.to <= startedAt) continue;\n\t\t\tconst end = Math.min(day.to, now);\n\t\t\tconst have = cache.get(monitor.id)?.get(day.date)?.coveredTo ?? day.from;\n\t\t\tif (have >= end) continue;\n\t\t\tconst storeEnd = Math.max(have, storableEnd(day, now, settledAfterMs(monitor)));\n\t\t\tif (storeEnd > have) entries.push({ date: day.date, kind: \"stored\", range: { from: have, to: storeEnd } });\n\t\t\tif (end > storeEnd) entries.push({ date: day.date, kind: \"live\", range: { from: storeEnd, to: end } });\n\t\t}\n\t\treturn entries;\n\t}\n\n\tprivate async readMonitors(\n\t\tpage: ResolvedPage,\n\t\tnow: number,\n\t\twanted: readonly { readonly monitor: ResolvedMonitor; readonly needs: Want }[],\n\t): Promise<void> {\n\t\tconst days = this.visibleDays(now);\n\t\tconst today = days.at(-1)?.date ?? \"\";\n\t\tconst windowFrom = days[0]?.from ?? now;\n\t\tconst cache = this.dayCache(page, days);\n\t\tconst latency = hasLatency(page);\n\t\tconst requests = wanted.map(({ monitor, needs }) => {\n\t\t\tconst plan = needs.history ? this.planHistory(monitor, days, cache, now) : [];\n\t\t\tconst known = this.transitions.get(monitor.id);\n\t\t\tconst after = known === undefined ? null : (known.records.at(-1)?.since ?? known.atStart?.since ?? null);\n\t\t\treturn {\n\t\t\t\tmonitor,\n\t\t\t\tneeds,\n\t\t\t\tplan,\n\t\t\t\tafter,\n\t\t\t\trequest: {\n\t\t\t\t\ttimeoutMs: monitor.timeoutMs,\n\t\t\t\t\tsnapshot: needs.snapshot,\n\t\t\t\t\tranges: plan.map((entry) => entry.range),\n\t\t\t\t\tmaxRows: FILL_ROWS_PER_MONITOR,\n\t\t\t\t\tlatencySince: latency ? latencySince(now) : null,\n\t\t\t\t\ttransitions: needs.snapshot\n\t\t\t\t\t\t? { from: windowFrom, to: now + 1, limit: 2 * STOPPAGE_LIMIT, after: after !== null && after >= windowFrom ? after : null }\n\t\t\t\t\t\t: null,\n\t\t\t\t},\n\t\t\t};\n\t\t});\n\t\tthis.metrics.monitorReads += requests.length;\n\t\tconst outcomes = await forEachLimited(\n\t\t\trequests,\n\t\t\tMONITOR_CONCURRENCY,\n\t\t\t({ monitor, request }) => monitorStub(this.env, monitor).readForPage(request) as Promise<PageReadResponse>,\n\t\t);\n\n\t\tconst writes: DayRow[] = [];\n\t\tconst sourceWrites: { readonly id: string; readonly startedAt: number | null }[] = [];\n\t\tconst dropped = new Set<string>();\n\t\trequests.forEach(({ monitor, needs, plan, request }, index) => {\n\t\t\tconst outcome = outcomes[index];\n\t\t\tlet response: PageReadResponse | null = null;\n\t\t\tif (outcome?.status === \"fulfilled\") {\n\t\t\t\tresponse = outcome.value;\n\t\t\t} else {\n\t\t\t\t// Cached days still show; the days it had to read stay pending.\n\t\t\t\tconsole.warn(`Page \"${page.id}\": could not read monitor \"${monitor.id}\"`, outcome?.reason);\n\t\t\t}\n\n\t\t\tlet startedAt = this.sources.get(monitor.id);\n\t\t\tconst incremental = request.transitions !== null && request.transitions.after != null;\n\t\t\t// The plan relied on cached days of another history: read again soon, as when filling.\n\t\t\tlet replanned = false;\n\t\t\tif (response !== null && (!this.sources.has(monitor.id) || startedAt !== response.startedAt)) {\n\t\t\t\treplanned = cache.has(monitor.id);\n\t\t\t\t// First seen, started, purged, or purged and started again: cached days (if any)\n\t\t\t\t// describe another history, and so do state records read as new ones.\n\t\t\t\tif (cache.has(monitor.id)) dropped.add(monitor.id);\n\t\t\t\tcache.delete(monitor.id);\n\t\t\t\tif (incremental) this.transitions.delete(monitor.id);\n\t\t\t\tstartedAt = response.startedAt;\n\t\t\t\tthis.sources.set(monitor.id, startedAt);\n\t\t\t\tsourceWrites.push({ id: monitor.id, startedAt });\n\t\t\t}\n\t\t\tif (response?.transitions && !(incremental && !this.transitions.has(monitor.id))) {\n\t\t\t\tconst fresh = response.transitions;\n\t\t\t\tconst known = this.transitions.get(monitor.id);\n\t\t\t\tif (!incremental || known === undefined || fresh.truncated) {\n\t\t\t\t\tthis.transitions.set(monitor.id, fresh.truncated ? { atStart: null, records: fresh.changes, truncated: true } : {\n\t\t\t\t\t\tatStart: fresh.atStart,\n\t\t\t\t\t\trecords: fresh.changes,\n\t\t\t\t\t\ttruncated: false,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tconst records = [...known.records, ...fresh.changes];\n\t\t\t\t\tconst kept = records.slice(-2 * STOPPAGE_LIMIT);\n\t\t\t\t\tthis.transitions.set(monitor.id, {\n\t\t\t\t\t\tatStart: kept.length < records.length ? null : known.atStart,\n\t\t\t\t\t\trecords: kept,\n\t\t\t\t\t\ttruncated: known.truncated || kept.length < records.length,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (response?.snapshot) {\n\t\t\t\tthis.snapshots.set(monitor.id, {\n\t\t\t\t\tvalue: response.snapshot,\n\t\t\t\t\tvalidUntil: snapshotValidUntil(response.snapshot, monitor, now),\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (!needs.history) return;\n\n\t\t\t// The history: cached days, extended by the slices just read.\n\t\t\tconst slices = new Map<string, { stored?: TimelineSlice; live?: TimelineSlice }>();\n\t\t\tconst plannedByDay = new Map<string, { stored?: TimeRange; live?: TimeRange }>();\n\t\t\tlet filling = replanned;\n\t\t\tplan.forEach((entry, position) => {\n\t\t\t\tconst forPlan = plannedByDay.get(entry.date) ?? {};\n\t\t\t\tforPlan[entry.kind] = entry.range;\n\t\t\t\tplannedByDay.set(entry.date, forPlan);\n\t\t\t\tif (response === null) return;\n\t\t\t\tconst slice = response.slices[position];\n\t\t\t\t// Skipped for maxRows (null): the day stays pending, and is read again soon.\n\t\t\t\tif (slice === null) filling = true;\n\t\t\t\tif (slice === undefined || slice === null) return;\n\t\t\t\tconst forDay = slices.get(entry.date) ?? {};\n\t\t\t\tforDay[entry.kind] = slice;\n\t\t\t\tslices.set(entry.date, forDay);\n\t\t\t});\n\t\t\tconst byDay = new Map<string, MonitorDay>();\n\t\t\tif (startedAt !== null) {\n\t\t\t\tfor (const day of days) {\n\t\t\t\t\tif (typeof startedAt === \"number\" && day.to <= startedAt) continue;\n\t\t\t\t\tlet data = cache.get(monitor.id)?.get(day.date) ?? emptyDay(day);\n\t\t\t\t\tconst planned = plannedByDay.get(day.date);\n\t\t\t\t\tconst read = slices.get(day.date);\n\t\t\t\t\tlet complete = data.coveredTo >= Math.min(day.to, now);\n\t\t\t\t\tfor (const kind of [\"stored\", \"live\"] as const) {\n\t\t\t\t\t\tconst wantedRange = planned?.[kind];\n\t\t\t\t\t\tif (wantedRange === undefined) continue;\n\t\t\t\t\t\tconst slice = read?.[kind];\n\t\t\t\t\t\tcomplete = slice !== undefined && slice.from === data.coveredTo;\n\t\t\t\t\t\tif (!complete || slice === undefined) break;\n\t\t\t\t\t\tdata = extend(data, slice);\n\t\t\t\t\t\t// Cache what has settled, unless the Monitor DO's clock cut the slice short.\n\t\t\t\t\t\tif (kind === \"stored\" && slice.to === wantedRange.to) {\n\t\t\t\t\t\t\tconst settled = cache.get(monitor.id) ?? new Map<string, DayData>();\n\t\t\t\t\t\t\tsettled.set(day.date, data);\n\t\t\t\t\t\t\tcache.set(monitor.id, settled);\n\t\t\t\t\t\t\twrites.push({\n\t\t\t\t\t\t\t\tmonitor_id: monitor.id,\n\t\t\t\t\t\t\t\tday: day.date,\n\t\t\t\t\t\t\t\tday_from: day.from,\n\t\t\t\t\t\t\t\tday_to: day.to,\n\t\t\t\t\t\t\t\tcovered_to: data.coveredTo,\n\t\t\t\t\t\t\t\texpected: data.expected,\n\t\t\t\t\t\t\t\tobtained: data.obtained,\n\t\t\t\t\t\t\t\tsegments: encodeSegments(data.segments),\n\t\t\t\t\t\t\t\tlatency: encodeLatency(data.latency),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbyDay.set(day.date, complete ? data : \"pending\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.histories.set(monitor.id, { readAt: now, today, days: byDay, filling });\n\t\t});\n\n\t\tif (writes.length > 0 || sourceWrites.length > 0 || dropped.size > 0) {\n\t\t\tthis.store.transaction(() => {\n\t\t\t\tfor (const id of dropped) this.store.run(\"DELETE FROM monitor_days WHERE monitor_id = ?\", id);\n\t\t\t\tfor (const source of sourceWrites) {\n\t\t\t\t\tthis.store.run(\n\t\t\t\t\t\t`INSERT INTO monitor_sources (monitor_id, started_at) VALUES (?, ?)\n\t\t\t\t\t\tON CONFLICT (monitor_id) DO UPDATE SET started_at = excluded.started_at`,\n\t\t\t\t\t\tsource.id,\n\t\t\t\t\t\tsource.startedAt,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tfor (const row of writes) {\n\t\t\t\t\tthis.store.run(\n\t\t\t\t\t\t`INSERT INTO monitor_days (monitor_id, day, day_from, day_to, covered_to, expected, obtained, segments, latency)\n\t\t\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n\t\t\t\t\t\tON CONFLICT (monitor_id, day) DO UPDATE SET day_from = excluded.day_from, day_to = excluded.day_to,\n\t\t\t\t\t\t\tcovered_to = excluded.covered_to, expected = excluded.expected, obtained = excluded.obtained,\n\t\t\t\t\t\t\tsegments = excluded.segments, latency = excluded.latency`,\n\t\t\t\t\t\trow.monitor_id,\n\t\t\t\t\t\trow.day,\n\t\t\t\t\t\trow.day_from,\n\t\t\t\t\t\trow.day_to,\n\t\t\t\t\t\trow.covered_to,\n\t\t\t\t\t\trow.expected,\n\t\t\t\t\t\trow.obtained,\n\t\t\t\t\t\trow.segments,\n\t\t\t\t\t\trow.latency,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Status\n\t// -------------------------------------------------------------------------\n\n\tprivate async buildStatus(page: ResolvedPage): Promise<Computed> {\n\t\tconst historyWanted = Date.now() - this.historyAskedAt < 2 * HISTORY_TTL_MS;\n\t\tawait this.ensureMonitors(page, (monitor, now) => {\n\t\t\tconst snapshot = this.snapshotStale(monitor, now);\n\t\t\t// Monitors read anyway also bring today's stretch when the history will want it soon.\n\t\t\tconst today = this.visibleDays(now).at(-1)?.date ?? \"\";\n\t\t\tconst history = snapshot && historyWanted && this.historyStale(monitor, now, today, HISTORY_TTL_MS - STATUS_TTL_MS);\n\t\t\treturn { snapshot, history };\n\t\t});\n\t\tconst now = Date.now();\n\t\tlet outdated = false;\n\t\tlet data = this.lastStatusData;\n\t\ttry {\n\t\t\tawait ensureSchema(this.env.DB);\n\t\t\tconst [incidents, maintenance, appearance] = await Promise.all([\n\t\t\t\tlistOpenIncidentsWithUpdates(this.env.DB, page.id, STATUS_UPDATES_PER_INCIDENT),\n\t\t\t\tlistMaintenanceBetween(this.env.DB, page.id, now, Number.MAX_SAFE_INTEGER),\n\t\t\t\tgetAppearance(this.env.DB, page.id),\n\t\t\t]);\n\t\t\tdata = { incidents, maintenance, appearance };\n\t\t\tthis.lastStatusData = data;\n\t\t} catch (error) {\n\t\t\tconsole.warn(`Page \"${page.id}\": could not read incidents, maintenance and appearance; showing them as last read`, error);\n\t\t\toutdated = true;\n\t\t}\n\t\tconst incidents = data?.incidents ?? [];\n\t\t// As last read, some windows may have ended since.\n\t\tconst maintenance = (data?.maintenance ?? []).filter((window) => window.endsAt > now);\n\t\tconst appearance = data?.appearance ?? defaultAppearance(page.id);\n\n\t\tconst active = maintenance.filter((window) => window.startsAt <= now);\n\t\tconst monitors = new Map(pageMonitors(page).map((monitor) => [monitor.id, monitor]));\n\t\tconst components = page.components.map((component): ComponentStatus => {\n\t\t\tconst impacts = incidents.flatMap((incident) =>\n\t\t\t\tincident.components.filter((affected) => affected.id === component.id).map((affected) => affected.impact),\n\t\t\t);\n\t\t\tconst states = component.monitors.map((id): DisplayState => {\n\t\t\t\tconst monitor = monitors.get(id);\n\t\t\t\tconst snapshot = this.snapshots.get(id)?.value;\n\t\t\t\treturn monitor === undefined || snapshot === undefined ? \"unknown\" : displayState(snapshot, monitor.timeoutMs, now).state;\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tid: component.id,\n\t\t\t\tname: component.name,\n\t\t\t\tstate: componentState(states, impacts),\n\t\t\t\tmonitored: component.monitors.length > 0,\n\t\t\t\tmaintenance: active.some((window) => window.components.includes(component.id)),\n\t\t\t\tlatency: component.latency,\n\t\t\t};\n\t\t});\n\t\tconst body: PageStatusResponse = {\n\t\t\tpageId: page.id,\n\t\t\tappearance: publicAppearance(appearance, uploadsBucket(this.env) !== undefined),\n\t\t\ttemplate: page.template,\n\t\t\treportUrl: page.reportUrl,\n\t\t\toverall: worstState(\n\t\t\t\tcomponents.map((component) => component.state),\n\t\t\t\t\"unknown\",\n\t\t\t),\n\t\t\tcomponents,\n\t\t\tgroups: page.groups.map((group) => ({ id: group.id, name: group.name, components: [...group.components] })),\n\t\t\tincidents: incidents.map((incident) => publicIncidentWithUpdates(incident, page)),\n\t\t\tmaintenance: {\n\t\t\t\tactive: active.map((window) => publicMaintenance(window, page)),\n\t\t\t\tupcoming: maintenance.filter((window) => window.startsAt > now).map((window) => publicMaintenance(window, page)),\n\t\t\t},\n\t\t\tincidentsOutdated: outdated,\n\t\t\tgeneratedAt: now,\n\t\t};\n\t\treturn view(body, now, outdated ? OUTDATED_TTL_MS : STATUS_TTL_MS);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// History\n\t// -------------------------------------------------------------------------\n\n\tprivate async buildHistory(page: ResolvedPage): Promise<Computed> {\n\t\tthis.historyAskedAt = Date.now();\n\t\tawait this.ensureMonitors(page, (monitor, now) => {\n\t\t\tconst today = this.visibleDays(now).at(-1)?.date ?? \"\";\n\t\t\tconst history = this.historyStale(monitor, now, today, HISTORY_TTL_MS);\n\t\t\treturn { history, snapshot: history && this.snapshotStale(monitor, now) };\n\t\t});\n\t\tconst now = Date.now();\n\t\tconst days = recentDays(now, config.timezone, HISTORY_DAYS);\n\t\tconst first = days[0] as CalendarDay;\n\t\tconst last = days.at(-1) as CalendarDay;\n\t\tconst visible = new Set(this.visibleDays(now).map((day) => day.date));\n\t\tlet outdated = false;\n\t\tlet data = this.lastHistoryData;\n\t\ttry {\n\t\t\tawait ensureSchema(this.env.DB);\n\t\t\tconst [read, windows] = await Promise.all([\n\t\t\t\tthis.historyIncidents(page.id, first.from),\n\t\t\t\tlistMaintenanceOverlapping(this.env.DB, page.id, first.from, last.to),\n\t\t\t]);\n\t\t\tdata = { incidents: read, maintenance: windows };\n\t\t\tthis.lastHistoryData = data;\n\t\t} catch (error) {\n\t\t\tconsole.warn(`Page \"${page.id}\": could not read the history's incidents and maintenance; using them as last read`, error);\n\t\t\toutdated = true;\n\t\t}\n\t\tconst incidents = data?.incidents ?? [];\n\t\tconst maintenance = data?.maintenance ?? [];\n\n\t\tconst referencedIncidents = new Set<string>();\n\t\tconst referencedMaintenance = new Set<string>();\n\t\tlet complete = true;\n\t\tconst components = page.components.map((component): ComponentHistory => {\n\t\t\tconst monitored = component.monitors.length > 0;\n\t\t\tconst affecting = incidents.filter((incident) => incident.components.some((affected) => affected.id === component.id));\n\t\t\tconst windows = maintenance.filter((window) => window.components.includes(component.id));\n\t\t\tconst cuts = windows.map((window) => ({ from: window.startsAt, to: window.endsAt }));\n\t\t\tconst totals = { upMs: 0, downMs: 0, expected: 0, obtained: 0 };\n\t\t\tconst starts = component.monitors.map((id) => this.sources.get(id)).filter((start): start is number => typeof start === \"number\");\n\n\t\t\tconst history = days.map((day): HistoryDay => {\n\t\t\t\tconst incidentIds = affecting\n\t\t\t\t\t.filter((incident) => overlaps(day, incident.startedAt, incident.resolvedAt))\n\t\t\t\t\t.map((incident) => incident.id);\n\t\t\t\tconst maintenanceIds = windows\n\t\t\t\t\t.filter((window) => overlaps(day, window.startsAt, window.endsAt))\n\t\t\t\t\t.map((window) => window.id);\n\t\t\t\tfor (const id of incidentIds) referencedIncidents.add(id);\n\t\t\t\tfor (const id of maintenanceIds) referencedMaintenance.add(id);\n\t\t\t\tconst base = { date: day.date, from: day.from, to: day.to, incidents: incidentIds, maintenance: maintenanceIds };\n\t\t\t\tconst none = {\n\t\t\t\t\t...base,\n\t\t\t\t\tuptime: null,\n\t\t\t\t\tcoverage: null,\n\t\t\t\t\tdowntimeMs: null,\n\t\t\t\t\tdegradedMs: null,\n\t\t\t\t\tobservedMs: null,\n\t\t\t\t\tchecks: null,\n\t\t\t\t\tworst: null,\n\t\t\t\t\tpending: false,\n\t\t\t\t};\n\t\t\t\tif (!monitored || !visible.has(day.date)) return none;\n\n\t\t\t\tconst parts = component.monitors.map((id) => {\n\t\t\t\t\tconst entry = this.histories.get(id);\n\t\t\t\t\t// Not read yet (its read failed): pending.\n\t\t\t\t\treturn entry === undefined ? \"pending\" : entry.days.get(day.date);\n\t\t\t\t});\n\t\t\t\tif (parts.includes(\"pending\")) {\n\t\t\t\t\tcomplete = false;\n\t\t\t\t\treturn { ...none, pending: true };\n\t\t\t\t}\n\t\t\t\tconst data = parts.filter((part): part is DayData => part !== undefined && part !== \"pending\");\n\t\t\t\tconst segments = excludeWindows(\n\t\t\t\t\tcombineTimelines(data.map((part) => unpack(part.segments))),\n\t\t\t\t\tcuts,\n\t\t\t\t);\n\t\t\t\tconst summary = summarize(segments);\n\t\t\t\tconst expected = data.reduce((sum, part) => sum + part.expected, 0);\n\t\t\t\tconst obtained = data.reduce((sum, part) => sum + part.obtained, 0);\n\t\t\t\ttotals.upMs += summary.upMs;\n\t\t\t\ttotals.downMs += summary.downMs;\n\t\t\t\ttotals.expected += expected;\n\t\t\t\ttotals.obtained += obtained;\n\t\t\t\tconst uptime = uptimeRatio(summary.upMs, summary.downMs);\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\tuptime,\n\t\t\t\t\tcoverage: coverageRatio(obtained, expected),\n\t\t\t\t\tdowntimeMs: uptime === null ? null : summary.downMs,\n\t\t\t\t\tdegradedMs: uptime === null ? null : summary.degradedMs,\n\t\t\t\t\tobservedMs: summary.upMs + summary.downMs,\n\t\t\t\t\tchecks: { expected, obtained },\n\t\t\t\t\tworst: summary.worst,\n\t\t\t\t\tpending: false,\n\t\t\t\t};\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tid: component.id,\n\t\t\t\tname: component.name,\n\t\t\t\tmonitored,\n\t\t\t\tuptime: monitored ? uptimeRatio(totals.upMs, totals.downMs) : null,\n\t\t\t\tcoverage: monitored ? coverageRatio(totals.obtained, totals.expected) : null,\n\t\t\t\tobservedMs: monitored ? totals.upMs + totals.downMs : null,\n\t\t\t\tobservedFrom: starts.length === 0 ? null : Math.min(...starts),\n\t\t\t\tdays: history,\n\t\t\t};\n\t\t});\n\n\t\tconst marker = (id: string, title: string, from: number, to: number | null): HistoryMarker => ({ id, title, from, to });\n\t\tconst body: PageHistoryResponse = {\n\t\t\ttimezone: config.timezone,\n\t\t\tfrom: first.from,\n\t\t\tcomponents,\n\t\t\tincidents: incidents\n\t\t\t\t.filter((incident) => referencedIncidents.has(incident.id))\n\t\t\t\t.sort((a, b) => a.startedAt - b.startedAt)\n\t\t\t\t.map((incident) => marker(incident.id, incident.title, incident.startedAt, incident.resolvedAt)),\n\t\t\tmaintenance: maintenance\n\t\t\t\t.filter((window) => referencedMaintenance.has(window.id))\n\t\t\t\t.sort((a, b) => a.startsAt - b.startsAt)\n\t\t\t\t.map((window) => marker(window.id, window.title, window.startsAt, window.endsAt)),\n\t\t\tcomplete,\n\t\t\tincidentsOutdated: outdated,\n\t\t\tgeneratedAt: now,\n\t\t};\n\t\t// Short while missing days are being filled in, or D1 could not be read; a monitor that\n\t\t// failed to answer is asked again with the rest, not more often (it may be failing for load).\n\t\tconst filling = pageMonitors(page).some((monitor) => this.histories.get(monitor.id)?.filling === true);\n\t\treturn view(body, now, filling ? PENDING_TTL_MS : outdated ? OUTDATED_TTL_MS : HISTORY_TTL_MS);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Response times (latency.ts)\n\t// -------------------------------------------------------------------------\n\n\t/**\n\t * Response times of the components that publish them, from the days the history reads (one\n\t * read serves both, at the history's pace): today's latest stretch is read with the history,\n\t * the rest comes from the cached days.\n\t */\n\tprivate async buildLatency(page: ResolvedPage): Promise<Computed> {\n\t\tconst shown = page.components.filter((component) => component.latency);\n\t\tif (shown.length > 0) {\n\t\t\tthis.historyAskedAt = Date.now();\n\t\t\tawait this.ensureMonitors(page, (monitor, now) => {\n\t\t\t\tconst today = this.visibleDays(now).at(-1)?.date ?? \"\";\n\t\t\t\tconst history = this.historyStale(monitor, now, today, HISTORY_TTL_MS);\n\t\t\t\treturn { history, snapshot: history && this.snapshotStale(monitor, now) };\n\t\t\t});\n\t\t}\n\t\tconst now = Date.now();\n\t\tconst since = latencySince(now);\n\t\tconst days = this.visibleDays(now).filter((day) => day.to > since);\n\t\tlet complete = true;\n\t\tconst components = shown.map((component): ComponentLatency => {\n\t\t\tconst lists: ReturnType<typeof unpackLatency>[] = [];\n\t\t\tconst latest: { at: number; ms: number }[] = [];\n\t\t\tfor (const id of component.monitors) {\n\t\t\t\tconst entry = this.histories.get(id);\n\t\t\t\tif (entry === undefined) complete = false;\n\t\t\t\tfor (const day of entry === undefined ? [] : days) {\n\t\t\t\t\tconst data = entry?.days.get(day.date);\n\t\t\t\t\tif (data === \"pending\") complete = false;\n\t\t\t\t\telse if (data !== undefined && data.latency.length > 0) lists.push(unpackLatency(data.latency));\n\t\t\t\t}\n\t\t\t\tconst check = this.snapshots.get(id)?.value.lastCheck ?? null;\n\t\t\t\tif (check !== null && check.latencyMs !== null) latest.push({ at: check.at, ms: check.latencyMs });\n\t\t\t}\n\t\t\tconst buckets = mergeLatency(lists);\n\t\t\tconst series = (range: { readonly bucketMs: number; readonly count: number }) =>\n\t\t\t\tlatencySeries(buckets, now, range.bucketMs, range.count);\n\t\t\treturn {\n\t\t\t\tid: component.id,\n\t\t\t\tname: component.name,\n\t\t\t\tlatest:\n\t\t\t\t\tlatest.length === 0\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tat: Math.max(...latest.map((entry) => entry.at)),\n\t\t\t\t\t\t\t\tms: Math.round(latest.reduce((sum, entry) => sum + entry.ms, 0) / latest.length),\n\t\t\t\t\t\t\t},\n\t\t\t\tday: series(LATENCY_RANGES.day),\n\t\t\t\tweek: series(LATENCY_RANGES.week),\n\t\t\t\tmonth: series(LATENCY_RANGES.month),\n\t\t\t};\n\t\t});\n\t\tconst body: PageLatencyResponse = { components, complete, generatedAt: now };\n\t\tconst filling = pageMonitors(page).some((monitor) => this.histories.get(monitor.id)?.filling === true);\n\t\treturn view(body, now, filling || !complete ? PENDING_TTL_MS : HISTORY_TTL_MS);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Stoppage history\n\t// -------------------------------------------------------------------------\n\n\tprivate async buildStoppages(page: ResolvedPage): Promise<Computed> {\n\t\tawait this.ensureMonitors(page, (monitor, now) => ({ snapshot: this.snapshotStale(monitor, now), history: false }));\n\t\tconst now = Date.now();\n\t\tconst from = this.visibleDays(now)[0]?.from ?? now;\n\t\tlet truncated = false;\n\t\tconst periods = new Map<string, DownPeriod[]>();\n\t\tfor (const monitor of pageMonitors(page)) {\n\t\t\tconst entry = this.transitions.get(monitor.id);\n\t\t\tif (entry === undefined) continue;\n\t\t\ttruncated ||= entry.truncated;\n\t\t\tconst records: StateRecord[] = entry.atStart === null ? [...entry.records] : [entry.atStart, ...entry.records];\n\t\t\tperiods.set(\n\t\t\t\tmonitor.id,\n\t\t\t\tdownPeriods(records).filter((period) => period.to === null || period.to > from),\n\t\t\t);\n\t\t}\n\t\tconst stoppages: Stoppage[] = page.components\n\t\t\t.flatMap((component) =>\n\t\t\t\tmergeDownPeriods(component.monitors.flatMap((id) => periods.get(id) ?? [])).map((period) => ({\n\t\t\t\t\tcomponentId: component.id,\n\t\t\t\t\tfrom: period.from,\n\t\t\t\t\tto: period.to,\n\t\t\t\t})),\n\t\t\t)\n\t\t\t.sort((a, b) => b.from - a.from || a.componentId.localeCompare(b.componentId));\n\t\tconst body: StoppagesResponse = {\n\t\t\tfrom,\n\t\t\tstoppages: stoppages.slice(0, STOPPAGE_LIMIT),\n\t\t\ttruncated: truncated || stoppages.length > STOPPAGE_LIMIT,\n\t\t\tgeneratedAt: now,\n\t\t};\n\t\treturn view(body, now, STOPPAGES_TTL_MS);\n\t}\n}\n\n/** The page's Durable Object. Only for pages in the configuration: any other name would create an object. */\nexport function statusPageStub(env: Env, pageId: string) {\n\treturn env.STATUS_PAGE.getByName(pageId);\n}\n","/**\n * The incident list and incident pages of the public API, read from D1 by the Worker,\n * not by the page's Durable Object: a visitor, or a script, asking for many incident IDs or\n * cursors then costs D1 reads and Worker requests, never the Durable Object requests that\n * monitoring depends on (the Free plan's daily limit is shared with them).\n *\n * D1's rows read are limited too (on the Free plan, for the whole account: past the limit,\n * every D1 query fails until 00:00 UTC, notifications included), so what a client makes up\n * costs one primary-key read: a cursor must name an incident (or update) of the page at the\n * position it claims, or it is refused before any list is read. Valid cursors are as many as\n * the page's incidents (or the incident's updates), like incident pages themselves, so their\n * responses are kept like those (`main` in index.ts). A list page reads its own rows only, and\n * an incident page at most {@link UPDATES_PER_PAGE} updates, however long its timeline.\n */\nimport type { ResolvedPage } from \"@naosystem/cf-workers-status-page-core\";\nimport type { IncidentListResponse, PublicApiError, PublicIncidentPage } from \"../../shared/public-api\";\nimport { type Cursor, encodeCursor } from \"../db/common\";\nimport { getIncidentWithUpdatePage, incidentPosition, listIncidents, MAX_OPEN_INCIDENTS, updatePosition } from \"../db/incidents\";\nimport { ensureSchema } from \"../db/schema\";\nimport type { ViewResult } from \"../status-page\";\nimport { publicIncident, publicIncidentWithUpdates } from \"./views\";\n\n/** How long incident lists and pages are kept. */\nexport const INCIDENTS_TTL_MS = 30_000;\n/** Updates on one incident page; `olderUpdatesCursor` reads the previous ones. */\nexport const UPDATES_PER_PAGE = 50;\n\nfunction result(body: unknown, status: 200 | 400 | 404, now: number): ViewResult {\n\treturn { status, json: JSON.stringify(body), generatedAt: now, ttlMs: INCIDENTS_TTL_MS, cacheable: true };\n}\n\nfunction badCursor(name: \"cursor\" | \"before\", now: number): ViewResult {\n\tconst body: PublicApiError = { error: \"invalid_query\", message: `\\`${name}\\` is not from a previous page` };\n\treturn result(body, 400, now);\n}\n\n/**\n * Unresolved incidents (first page only, at most {@link MAX_OPEN_INCIDENTS}), then resolved\n * ones by page: at most `MAX_OPEN_INCIDENTS + limit + 1` rows, whatever the cursor says.\n */\nexport async function incidentsView(env: Env, page: ResolvedPage, limit: number, cursor: Cursor | null): Promise<ViewResult> {\n\tconst now = Date.now();\n\tawait ensureSchema(env.DB);\n\tif (cursor !== null) {\n\t\t// One primary-key read: a resolved incident of this page, where the cursor says it is.\n\t\tconst position = await incidentPosition(env.DB, cursor.id);\n\t\tif (position === null || position.pageId !== page.id || !position.resolved || position.startedAt !== cursor.at) {\n\t\t\treturn badCursor(\"cursor\", now);\n\t\t}\n\t}\n\tconst [unresolved, resolved] = await Promise.all([\n\t\tcursor === null\n\t\t\t? listIncidents(env.DB, { pageId: page.id, status: \"open\", limit: MAX_OPEN_INCIDENTS })\n\t\t\t: Promise.resolve({ items: [], nextCursor: null }),\n\t\tlistIncidents(env.DB, { pageId: page.id, status: \"resolved\", limit, after: cursor ?? undefined }),\n\t]);\n\tconst body: IncidentListResponse = {\n\t\tunresolved: unresolved.items.map((incident) => publicIncident(incident, page)),\n\t\tresolved: resolved.items.map((incident) => publicIncident(incident, page)),\n\t\tnextCursor: resolved.nextCursor,\n\t};\n\treturn result(body, 200, now);\n}\n\n/**\n * An incident with its latest {@link UPDATES_PER_PAGE} updates before `before` (an update's\n * position from `olderUpdatesCursor`; `null` for the latest). An unknown ID costs one\n * primary-key lookup, and so does a made-up `before`.\n */\nexport async function incidentView(env: Env, page: ResolvedPage, incidentId: string, before: Cursor | null = null): Promise<ViewResult> {\n\tconst now = Date.now();\n\tawait ensureSchema(env.DB);\n\tlet position: { readonly createdAt: number; readonly rowid: number } | null = null;\n\tif (before !== null) {\n\t\tconst update = await updatePosition(env.DB, before.id);\n\t\tif (update === null || update.incidentId !== incidentId || update.createdAt !== before.at) return badCursor(\"before\", now);\n\t\tposition = update;\n\t}\n\tconst incident = await getIncidentWithUpdatePage(env.DB, incidentId, UPDATES_PER_PAGE, position);\n\t// Another page's incident does not exist here.\n\tif (incident === null || incident.pageId !== page.id) {\n\t\tconst body: PublicApiError = { error: \"not_found\", message: \"No such incident\" };\n\t\treturn result(body, 404, now);\n\t}\n\tconst body: PublicIncidentPage = {\n\t\t...publicIncidentWithUpdates(incident, page),\n\t\tolderUpdatesCursor: incident.olderCursor === null ? null : encodeCursor(incident.olderCursor),\n\t};\n\treturn result(body, 200, now);\n}\n","/**\n * Routes of the public API, and their canonical form. The gateway (the Worker's\n * default entrypoint) parses a request, rejects what does not exist, and passes the\n * canonical URL to the cached `PublicApi` entrypoint, so that a cache entry exists per\n * resource and per page only: unknown query parameters, their order and the host never make\n * a new one (they would otherwise let anyone bypass the cache and reach the Durable Objects).\n */\nimport * as z from \"zod\";\nimport { config, findPage } from \"../config\";\nimport { IMAGE_ID } from \"../../shared/admin-api\";\nimport { type Cursor, decodeCursor, encodeCursor } from \"../db/common\";\n\nexport type PublicRoute =\n\t| { readonly kind: \"pages\" }\n\t| { readonly kind: \"status\"; readonly pageId: string }\n\t| { readonly kind: \"history\"; readonly pageId: string }\n\t| { readonly kind: \"stoppages\"; readonly pageId: string }\n\t| { readonly kind: \"latency\"; readonly pageId: string }\n\t| { readonly kind: \"incidents\"; readonly pageId: string; readonly limit: IncidentPageSize; readonly cursor: Cursor | null }\n\t| { readonly kind: \"incident\"; readonly pageId: string; readonly incidentId: string; readonly before: Cursor | null }\n\t/** An uploaded image (a logo or favicon), from R2: served by the gateway itself, never memoized or cached as a view. */\n\t| { readonly kind: \"image\"; readonly pageId: string; readonly imageId: string };\n\n/** A route of one page. */\nexport type PageRoute = Exclude<PublicRoute, { readonly kind: \"pages\" }>;\n\n/** A route whose response is JSON (every route but images). */\nexport type ViewRoute = Exclude<PublicRoute, { readonly kind: \"image\" }>;\n\n/** A route answered by the page's StatusPage DO (incidents are read from D1 by the Worker). */\nexport type PageViewRoute = Extract<PublicRoute, { readonly kind: \"status\" | \"history\" | \"stoppages\" | \"latency\" }>;\n\nexport type ParsedRoute =\n\t| { readonly ok: true; readonly route: PublicRoute }\n\t| { readonly ok: false; readonly status: 400 | 404; readonly error: string; readonly message: string };\n\n/**\n * The page sizes of the incident list. Any other `limit` from 1 to 50 is served as the next\n * size up, so that a client cannot make up many sizes, each a separate response to compute.\n */\nexport const INCIDENT_PAGE_SIZES = [10, 20, 50] as const;\nexport type IncidentPageSize = (typeof INCIDENT_PAGE_SIZES)[number];\nexport const DEFAULT_INCIDENT_PAGE_SIZE: IncidentPageSize = 20;\nexport const MAX_INCIDENT_PAGE_SIZE: IncidentPageSize = 50;\n\n/** The page size served for a requested `limit` from 1 to {@link MAX_INCIDENT_PAGE_SIZE}. */\nexport function incidentPageSize(limit: number): IncidentPageSize {\n\treturn INCIDENT_PAGE_SIZES.find((size) => size >= limit) ?? MAX_INCIDENT_PAGE_SIZE;\n}\n\n/** The paths the public API answers: `/api/pages…` and the compatibility alias `/api/status`. */\nexport function isPublicApiPath(pathname: string): boolean {\n\treturn pathname === \"/api/status\" || pathname === \"/api/pages\" || pathname.startsWith(\"/api/pages/\");\n}\n\n/** Incident IDs are UUIDs (`crypto.randomUUID()`): anything else cannot exist, and costs nothing to reject. */\nconst INCIDENT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\n\nconst incidentQuery = z.object({\n\tlimit: z.coerce.number().int().min(1).max(MAX_INCIDENT_PAGE_SIZE).default(DEFAULT_INCIDENT_PAGE_SIZE),\n\tcursor: z.string().max(100).optional(),\n});\n\nconst cursorQuery = z.string().max(100).optional();\n\nconst notFound = (what: string): ParsedRoute => ({ ok: false, status: 404, error: \"not_found\", message: `No such ${what}` });\n\n/** Parses a public API URL. Only pages in this version's configuration exist. */\nexport function parsePublicRoute(url: URL): ParsedRoute {\n\tif (url.pathname === \"/api/status\") {\n\t\t// Before multiple pages, `/api/status` was the status page: it stays the first page's status.\n\t\tconst first = config.pages[0];\n\t\treturn first === undefined ? notFound(\"page\") : { ok: true, route: { kind: \"status\", pageId: first.id } };\n\t}\n\tlet segments: string[];\n\ttry {\n\t\tsegments = url.pathname\n\t\t\t.split(\"/\")\n\t\t\t.filter((segment) => segment !== \"\")\n\t\t\t.map(decodeURIComponent);\n\t} catch {\n\t\treturn notFound(\"resource\");\n\t}\n\tconst [api, pages, pageId, resource, id, ...rest] = segments;\n\tif (api !== \"api\" || pages !== \"pages\" || rest.length > 0) return notFound(\"resource\");\n\tif (pageId === undefined) return resource === undefined ? { ok: true, route: { kind: \"pages\" } } : notFound(\"resource\");\n\tif (findPage(pageId) === undefined) return notFound(\"page\");\n\n\tswitch (resource) {\n\t\tcase \"status\":\n\t\tcase \"history\":\n\t\tcase \"stoppages\":\n\t\tcase \"latency\":\n\t\t\treturn id === undefined ? { ok: true, route: { kind: resource, pageId } } : notFound(\"resource\");\n\t\tcase \"incidents\": {\n\t\t\tif (id !== undefined) {\n\t\t\t\tif (!INCIDENT_ID.test(id)) return notFound(\"incident\");\n\t\t\t\t// `before`: an update's position from `olderUpdatesCursor`, for the previous page of the timeline.\n\t\t\t\tconst before = cursorQuery.safeParse(url.searchParams.get(\"before\") ?? undefined);\n\t\t\t\tconst position = !before.success ? undefined : before.data === undefined ? null : decodeCursor(before.data);\n\t\t\t\tif (position === undefined) {\n\t\t\t\t\treturn { ok: false, status: 400, error: \"invalid_query\", message: \"`before` is not from a previous page\" };\n\t\t\t\t}\n\t\t\t\treturn { ok: true, route: { kind: \"incident\", pageId, incidentId: id, before: position } };\n\t\t\t}\n\t\t\tconst query = incidentQuery.safeParse({\n\t\t\t\tlimit: url.searchParams.get(\"limit\") ?? undefined,\n\t\t\t\tcursor: url.searchParams.get(\"cursor\") ?? undefined,\n\t\t\t});\n\t\t\tif (!query.success) return { ok: false, status: 400, error: \"invalid_query\", message: \"Invalid `limit` or `cursor`\" };\n\t\t\tconst cursor = query.data.cursor === undefined ? null : decodeCursor(query.data.cursor);\n\t\t\tif (cursor === undefined) {\n\t\t\t\treturn { ok: false, status: 400, error: \"invalid_query\", message: \"`cursor` is not from a previous page\" };\n\t\t\t}\n\t\t\treturn { ok: true, route: { kind: \"incidents\", pageId, limit: incidentPageSize(query.data.limit), cursor } };\n\t\t}\n\t\tcase \"images\":\n\t\t\t// Content-addressed IDs only: anything else cannot exist, and costs nothing to reject.\n\t\t\treturn id !== undefined && IMAGE_ID.test(id) ? { ok: true, route: { kind: \"image\", pageId, imageId: id } } : notFound(\"image\");\n\t\tdefault:\n\t\t\treturn notFound(\"resource\");\n\t}\n}\n\n/** The one URL path (and query) of a route: what the cache keys and what `PublicApi` parses again. */\nexport function canonicalPath(route: PublicRoute): string {\n\tconst page = (pageId: string) => `/api/pages/${encodeURIComponent(pageId)}`;\n\tswitch (route.kind) {\n\t\tcase \"pages\":\n\t\t\treturn \"/api/pages\";\n\t\tcase \"status\":\n\t\tcase \"history\":\n\t\tcase \"stoppages\":\n\t\tcase \"latency\":\n\t\t\treturn `${page(route.pageId)}/${route.kind}`;\n\t\tcase \"incidents\": {\n\t\t\tconst query = new URLSearchParams();\n\t\t\tif (route.limit !== DEFAULT_INCIDENT_PAGE_SIZE) query.set(\"limit\", String(route.limit));\n\t\t\tif (route.cursor !== null) query.set(\"cursor\", encodeCursor(route.cursor));\n\t\t\tconst search = query.toString();\n\t\t\treturn `${page(route.pageId)}/incidents${search === \"\" ? \"\" : `?${search}`}`;\n\t\t}\n\t\tcase \"incident\": {\n\t\t\tconst path = `${page(route.pageId)}/incidents/${encodeURIComponent(route.incidentId)}`;\n\t\t\treturn route.before === null ? path : `${path}?${new URLSearchParams({ before: encodeCursor(route.before) })}`;\n\t\t}\n\t\tcase \"image\":\n\t\t\treturn `${page(route.pageId)}/images/${route.imageId}`;\n\t}\n}\n\n/** Cache tags of a page's responses, for purging them together. Tags are case-insensitive ASCII. */\nexport function pageTag(pageId: string): string {\n\treturn `page:${pageId}`;\n}\n\n/** Tag of the list of pages, which shows every page's title. */\nexport const PAGES_TAG = \"pages\";\n","/**\n * The public API: what status pages show, for anyone, read-only. Routes are documented\n * in the README; response types are in shared/public-api.ts.\n *\n * ## Caching\n *\n * Each page's StatusPage DO computes its status, history and stoppages at most once per time\n * to live (30 seconds for the status; 5 minutes for the history and stoppages) for all data\n * centres, reads each monitor once for all of them, and drops them when an administrator\n * changes the page. The list of pages and incidents are read from D1 by the Worker\n * (incidents.ts), so that no client-chosen ID or cursor reaches a Durable Object. In front:\n *\n * - **Each isolate of the Worker** keeps responses ({@link ResponseMemo}) for what is left of\n * their time to live, at most 30 seconds, so that repeated requests (a visitor polling, or\n * hammering) do not reach the Durable Object: each one is a billed request, and on the\n * Free plan they share a daily limit with the monitors' alarms. The isolate that handles\n * an administrator's change forgets the page at once; others within 30 seconds.\n * - **`publicApi.cache`** in status.config.ts chooses the rest:\n * - `\"durable-object\"` (default): nothing more. Browsers are told `private, no-cache`: they\n * ask again on every poll, and see an administrator's change on their next request.\n * - `\"workers-cache\"`: [Workers Cache](https://developers.cloudflare.com/workers/cache/).\n * The default entrypoint stays an uncached gateway that calls the `PublicApi` entrypoint\n * through `ctx.exports` with the canonical URL; caching is enabled for `PublicApi` only\n * (`exports` in wrangler.jsonc), so admin routes never touch it, and in the default mode\n * `PublicApi` is never invoked. The edge and browsers keep a response for what is left of\n * its time to live, at most 30 seconds, with `stale-if-error=0`: without it, Workers\n * Cache serves a stale response indefinitely when the Worker fails, and a page would show\n * its last \"all up\" through an outage. A `Cache-Tag` per page lets\n * `ctx.cache.purge()` remove a page's entries everywhere (see public-cache.ts).\n *\n * Responses never depend on the request's headers (language included: see\n * shared/public-api.ts), so one entry per URL is correct. CORS headers\n * (`publicApi.allowedOrigins`) are added by the gateway per request, after every cache, so a\n * cached response never carries another origin's. A response whose computation spanned an\n * administrator's change is served with `no-store` and kept nowhere.\n */\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport type { PublicApiCache, ResolvedPublicApi } from \"@naosystem/cf-workers-status-page-core\";\nimport type { PageListResponse, PublicApiError } from \"../../shared/public-api\";\nimport { config, findPage } from \"../config\";\nimport { listAppearanceTitles } from \"../db/appearance\";\nimport { ensureSchema } from \"../db/schema\";\nimport { statusPageStub, type ViewResult } from \"../status-page\";\nimport { incidentView, incidentsView } from \"./incidents\";\nimport { serveImage } from \"../uploads\";\nimport { canonicalPath, PAGES_TAG, type PublicRoute, pageTag, parsePublicRoute, type ViewRoute } from \"./routes\";\n\nexport { isPublicApiPath } from \"./routes\";\n\nconst SECURITY_HEADERS = { \"X-Content-Type-Options\": \"nosniff\" } as const;\n/** Longest time a response is kept by an isolate's memo, and by browsers: the staleness accepted after a change. */\nexport const SHORT_CACHE_MS = 30_000;\n/** Time to live of the list of pages. */\nconst PAGES_TTL_MS = 30_000;\n\nfunction errorResponse(status: number, error: string, message: string, headers: Record<string, string> = {}): Response {\n\tconst body: PublicApiError = { error, message };\n\treturn Response.json(body, { status, headers: { \"Cache-Control\": \"no-store\", ...SECURITY_HEADERS, ...headers } });\n}\n\n/** Seconds left of `ttlMs` for data read at `generatedAt`. */\nexport function maxAgeSeconds(generatedAt: number, ttlMs: number, now = Date.now()): number {\n\treturn Math.max(0, Math.floor((generatedAt + ttlMs - now) / 1000));\n}\n\n/**\n * Response headers for caching, per mode (see the module documentation). With Workers Cache,\n * the edge and browsers keep a response for what is left of its time to live but at most\n * {@link SHORT_CACHE_MS}, whatever the view (the page's object recomputes its history every\n * 5 minutes, but that is internal and an administrator's change clears it directly), so that\n * a purge that is refused or lost leaves an old response for 30 seconds at most.\n */\nexport function cacheHeaders(mode: PublicApiCache, result: ViewResult, tags: readonly string[]): Record<string, string> {\n\tif (!result.cacheable) return { \"Cache-Control\": \"no-store\" };\n\tif (mode === \"durable-object\") return { \"Cache-Control\": \"private, no-cache\" };\n\tconst maxAge = Math.min(maxAgeSeconds(result.generatedAt, result.ttlMs), SHORT_CACHE_MS / 1000);\n\tif (maxAge <= 0) return { \"Cache-Control\": \"no-store\" };\n\treturn { \"Cache-Control\": `public, max-age=${maxAge}, stale-if-error=0`, \"Cache-Tag\": tags.join(\",\") };\n}\n\nfunction viewResponse(result: ViewResult, mode: PublicApiCache, tags: readonly string[]): Response {\n\treturn new Response(result.json, {\n\t\tstatus: result.status,\n\t\theaders: { \"Content-Type\": \"application/json\", ...cacheHeaders(mode, result, tags), ...SECURITY_HEADERS },\n\t});\n}\n\n/** The list of pages and their titles (D1; not one page's, so not a StatusPage DO's). */\nasync function pagesView(env: Env): Promise<ViewResult> {\n\tawait ensureSchema(env.DB);\n\tconst titles = await listAppearanceTitles(env.DB);\n\tconst body: PageListResponse = {\n\t\tpages: config.pages.map((page) => ({ id: page.id, title: titles.get(page.id) ?? null })),\n\t};\n\treturn { status: 200, json: JSON.stringify(body), generatedAt: Date.now(), ttlMs: PAGES_TTL_MS, cacheable: true };\n}\n\n/**\n * A route's response from its source: the page's StatusPage DO for its status, history and\n * stoppages; D1 for the list of pages and for incidents (see incidents.ts).\n */\nasync function source(env: Env, route: ViewRoute): Promise<{ readonly result: ViewResult; readonly tags: string[] }> {\n\tswitch (route.kind) {\n\t\tcase \"pages\":\n\t\t\treturn { result: await pagesView(env), tags: [PAGES_TAG] };\n\t\tcase \"incidents\":\n\t\tcase \"incident\": {\n\t\t\tconst page = findPage(route.pageId);\n\t\t\tif (page === undefined) throw new Error(`No page \"${route.pageId}\"`);\n\t\t\tconst result =\n\t\t\t\troute.kind === \"incident\"\n\t\t\t\t\t? await incidentView(env, page, route.incidentId, route.before)\n\t\t\t\t\t: await incidentsView(env, page, route.limit, route.cursor);\n\t\t\treturn { result, tags: [pageTag(route.pageId)] };\n\t\t}\n\t\tdefault:\n\t\t\treturn { result: await statusPageStub(env, route.pageId).getView(route), tags: [pageTag(route.pageId)] };\n\t}\n}\n\nasync function respond(env: Env, route: ViewRoute, mode: PublicApiCache): Promise<Response> {\n\tconst { result, tags } = await source(env, route);\n\treturn viewResponse(result, mode, tags);\n}\n\nexport interface PurgeRequest {\n\treadonly tags: readonly string[];\n}\n\nexport type PurgeOutcome =\n\t| { readonly status: \"purged\" }\n\t/** No Workers Cache here (local development and tests, or caching turned off): nothing to purge. */\n\t| { readonly status: \"unavailable\" }\n\t/** Refused, for example by the purge rate limit; entries expire on their own. */\n\t| { readonly status: \"failed\"; readonly errors: readonly string[] };\n\n/** Purges by tag with `cache` (an entrypoint's `ctx.cache`, when Workers Cache is on for it). */\nexport async function purgeTags(cache: CacheContext | undefined, tags: readonly string[]): Promise<PurgeOutcome> {\n\tif (cache === undefined) return { status: \"unavailable\" };\n\tconst result = await cache.purge({ tags: [...tags] });\n\tif (result.success) return { status: \"purged\" };\n\treturn { status: \"failed\", errors: result.errors.map((error) => `${error.code}: ${error.message}`) };\n}\n\n/**\n * The cached entrypoint of the `workers-cache` mode (see the module documentation). Reached\n * only through the gateway: named entrypoints have no route from the internet.\n */\nexport class PublicApi extends WorkerEntrypoint<Env> {\n\toverride async fetch(request: Request): Promise<Response> {\n\t\tconst parsed = parsePublicRoute(new URL(request.url));\n\t\tif (!parsed.ok) return errorResponse(parsed.status, parsed.error, parsed.message);\n\t\ttry {\n\t\t\t// Not reached through the gateway, which serves images itself; answered alike all the same.\n\t\t\tif (parsed.route.kind === \"image\") return await serveImage(this.env, parsed.route.pageId, parsed.route.imageId, request);\n\t\t\treturn await respond(this.env, parsed.route, \"workers-cache\");\n\t\t} catch (error) {\n\t\t\tconsole.error(`Public API ${new URL(request.url).pathname} failed`, error);\n\t\t\treturn errorResponse(500, \"internal_error\", \"Something went wrong\");\n\t\t}\n\t}\n\n\t/**\n\t * Purges cached responses by tag. Purges apply to the entrypoint that calls them, so the\n\t * admin API asks this one (after every change to what a page shows).\n\t */\n\tasync purge(request: PurgeRequest): Promise<PurgeOutcome> {\n\t\treturn purgeTags(this.ctx.cache, request.tags);\n\t}\n}\n\ninterface MemoEntry {\n\treadonly expiresAt: number;\n\treadonly status: number;\n\treadonly body: string;\n\treadonly headers: readonly (readonly [string, string])[];\n}\n\n/**\n * Where a response is kept. `main`: successful responses, whose number the page's data bounds\n * (a page's status, history and stoppages; its incident list at each valid cursor and page\n * size; its incidents at each page of their timelines: routes.ts and incidents.ts accept only\n * cursors that name existing rows, and three page sizes). `side`: errors, whose keys a client\n * chooses freely (unknown incidents, made-up cursors), in a small set of their own, so that\n * asking for many of them cannot push the others out.\n */\nexport type MemoBucket = \"main\" | \"side\";\n\n/** Least recently used out beyond `limit`. */\nclass LruMap<K, V> {\n\treadonly entries = new Map<K, V>();\n\treadonly limit: number;\n\n\tconstructor(limit: number) {\n\t\tthis.limit = limit;\n\t}\n\n\tget(key: K): V | undefined {\n\t\tconst value = this.entries.get(key);\n\t\tif (value !== undefined) {\n\t\t\tthis.entries.delete(key);\n\t\t\tthis.entries.set(key, value);\n\t\t}\n\t\treturn value;\n\t}\n\n\tset(key: K, value: V): void {\n\t\tthis.entries.delete(key);\n\t\tthis.entries.set(key, value);\n\t\tfor (const old of this.entries.keys()) {\n\t\t\tif (this.entries.size <= this.limit) break;\n\t\t\tthis.entries.delete(old);\n\t\t}\n\t}\n}\n\n/**\n * Responses kept by one isolate, keyed by mode and canonical URL (one entry per page, view\n * and query), in two bounded buckets ({@link MemoBucket}). Only cacheable responses are\n * kept, for what is left of their time to live and at most {@link SHORT_CACHE_MS}. A kept\n * response is sent with its freshness recomputed: `max-age` is what is left of the entry, and\n * `Age` is dropped, so that a browser does not keep it longer than the isolate would.\n */\nexport class ResponseMemo {\n\tprivate readonly buckets: Readonly<Record<MemoBucket, LruMap<string, MemoEntry>>>;\n\n\tconstructor(mainEntries = 256, sideEntries = 32) {\n\t\tthis.buckets = { main: new LruMap(mainEntries), side: new LruMap(sideEntries) };\n\t}\n\n\tget(key: string, now = Date.now()): Response | null {\n\t\tfor (const bucket of Object.values(this.buckets)) {\n\t\t\tconst entry = bucket.get(key);\n\t\t\tif (entry === undefined) continue;\n\t\t\tif (now >= entry.expiresAt) {\n\t\t\t\tbucket.entries.delete(key);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst response = new Response(entry.body, { status: entry.status, headers: [...entry.headers] });\n\t\t\tconst cacheControl = response.headers.get(\"Cache-Control\");\n\t\t\tif (cacheControl !== null && /max-age=\\d+/.test(cacheControl)) {\n\t\t\t\tconst left = Math.max(0, Math.floor((entry.expiresAt - now) / 1000));\n\t\t\t\tresponse.headers.set(\"Cache-Control\", cacheControl.replace(/max-age=\\d+/, `max-age=${left}`));\n\t\t\t}\n\t\t\tresponse.headers.delete(\"Age\");\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** Keeps `response` (read into memory) until `expiresAt`; returns a copy to send. */\n\tasync put(key: string, response: Response, expiresAt: number, bucket: MemoBucket = \"main\", now = Date.now()): Promise<Response> {\n\t\tconst body = await response.text();\n\t\tconst copy = new Response(body, response);\n\t\tif (expiresAt > now) {\n\t\t\tfor (const other of Object.values(this.buckets)) other.entries.delete(key);\n\t\t\tthis.buckets[bucket].set(key, { expiresAt, status: response.status, body, headers: [...response.headers] });\n\t\t}\n\t\treturn copy;\n\t}\n\n\t/** Forgets a page's responses and the list of pages (after an administrator's change, in this isolate). */\n\tforgetPage(pageId: string): void {\n\t\tconst prefix = `/api/pages/${encodeURIComponent(pageId)}/`;\n\t\tfor (const bucket of Object.values(this.buckets)) {\n\t\t\tfor (const key of bucket.entries.keys()) {\n\t\t\t\tconst path = key.slice(key.indexOf(\" \") + 1);\n\t\t\t\tif (path.startsWith(prefix) || path === \"/api/pages\") bucket.entries.delete(key);\n\t\t\t}\n\t\t}\n\t}\n\n\tclear(): void {\n\t\tfor (const bucket of Object.values(this.buckets)) bucket.entries.clear();\n\t}\n\n\t/** Entries kept, per bucket. */\n\tsizes(): Record<MemoBucket, number> {\n\t\treturn { main: this.buckets.main.entries.size, side: this.buckets.side.entries.size };\n\t}\n\n\tget size(): number {\n\t\treturn this.buckets.main.entries.size + this.buckets.side.entries.size;\n\t}\n}\n\n/** The bucket for a route's response (see {@link MemoBucket}). */\nexport function memoBucket(_route: PublicRoute, status: number): MemoBucket {\n\treturn status === 200 ? \"main\" : \"side\";\n}\n\n/** This isolate's memo of public responses. */\nexport const responseMemo = new ResponseMemo();\n\n/** When a view may be kept until by an isolate: what is left of its time to live, at most {@link SHORT_CACHE_MS}. */\nfunction viewKeepUntil(result: ViewResult, now: number): number {\n\tif (!result.cacheable) return now;\n\treturn Math.min(result.generatedAt + result.ttlMs, now + SHORT_CACHE_MS);\n}\n\n/** When a response of the cached entrypoint may be kept until, from its caching headers. */\nfunction keepUntil(response: Response, now: number): number {\n\tif (response.status !== 200 && response.status !== 404) return now;\n\tconst cacheControl = response.headers.get(\"Cache-Control\") ?? \"\";\n\tif (/no-store/.test(cacheControl)) return now;\n\tconst maxAge = /max-age=(\\d+)/.exec(cacheControl);\n\tconst age = Number(response.headers.get(\"Age\") ?? \"0\");\n\tconst seconds = maxAge === null ? 0 : Math.max(0, Number(maxAge[1]) - age);\n\treturn now + Math.min(seconds * 1000, SHORT_CACHE_MS);\n}\n\n/** The `Access-Control-Allow-Origin` value for a request from `origin`, or `null` when it is not allowed. */\nexport function allowedOrigin(allowed: ResolvedPublicApi[\"allowedOrigins\"], origin: string | null): string | null {\n\tif (allowed === \"*\") return \"*\";\n\treturn origin !== null && allowed.includes(origin) ? origin : null;\n}\n\n/**\n * CORS headers for a response to `request` (`publicApi.allowedOrigins`). With a list of\n * origins the answer depends on `Origin`, so it says `Vary: Origin`; with `\"*\"` it does not.\n * Never credentials: the public API has none.\n */\nfunction corsHeaders(allowed: ResolvedPublicApi[\"allowedOrigins\"], request: Request): Headers {\n\tconst headers = new Headers();\n\tconst origin = allowedOrigin(allowed, request.headers.get(\"Origin\"));\n\tif (origin !== null) headers.set(\"Access-Control-Allow-Origin\", origin);\n\tif (Array.isArray(allowed) && allowed.length > 0) headers.set(\"Vary\", \"Origin\");\n\treturn headers;\n}\n\nfunction withHeaders(response: Response, extra: Headers, head: boolean): Response {\n\tconst result = new Response(head ? null : response.body, response);\n\tfor (const [name, value] of extra) {\n\t\tif (name === \"vary\") result.headers.append(name, value);\n\t\telse result.headers.set(name, value);\n\t}\n\treturn result;\n}\n\n/** A CORS preflight. Only reached when CORS is on: the API takes simple GETs, so browsers rarely send one. */\nfunction preflight(request: Request, allowed: ResolvedPublicApi[\"allowedOrigins\"]): Response {\n\tconst headers = corsHeaders(allowed, request);\n\theaders.set(\"Allow\", \"GET, HEAD, OPTIONS\");\n\theaders.set(\"Cache-Control\", \"no-store\");\n\tif (headers.has(\"Access-Control-Allow-Origin\")) {\n\t\theaders.set(\"Access-Control-Allow-Methods\", \"GET, HEAD\");\n\t\t// The API ignores request headers, so whatever a client sends is harmless.\n\t\tconst requested = request.headers.get(\"Access-Control-Request-Headers\");\n\t\tif (requested !== null) {\n\t\t\theaders.set(\"Access-Control-Allow-Headers\", requested);\n\t\t\theaders.append(\"Vary\", \"Access-Control-Request-Headers\");\n\t\t}\n\t\theaders.set(\"Access-Control-Max-Age\", \"86400\");\n\t}\n\treturn new Response(null, { status: 204, headers });\n}\n\n/**\n * An uploaded image, straight from R2: its URL names its bytes, so browsers keep it for a year\n * and none of the caches above is needed (see worker/uploads.ts).\n */\nasync function image(env: Env, route: Extract<PublicRoute, { readonly kind: \"image\" }>, request: Request): Promise<Response> {\n\ttry {\n\t\treturn await serveImage(env, route.pageId, route.imageId, request);\n\t} catch (error) {\n\t\tconsole.error(`Public API image ${route.pageId}/${route.imageId} failed`, error);\n\t\treturn errorResponse(500, \"internal_error\", \"Something went wrong\");\n\t}\n}\n\n/** How the public API is served: `publicApi` in status.config.ts. */\nexport const PUBLIC_API: ResolvedPublicApi = config.publicApi;\n\n/**\n * The public API for `/api/status` and `/api/pages/*`, in the uncached default entrypoint:\n * rejects what does not exist (uncached), answers from this isolate's memo, or else from the\n * page's Durable Object or, with `workers-cache`, from the cached `PublicApi` entrypoint\n * with the canonical URL. Adds CORS headers last, per request.\n */\nexport async function handlePublicApi(\n\trequest: Request,\n\tenv: Env,\n\tctx: ExecutionContext,\n\toptions: ResolvedPublicApi = PUBLIC_API,\n\tmemo: ResponseMemo = responseMemo,\n): Promise<Response> {\n\tconst cors = corsHeaders(options.allowedOrigins, request);\n\tconst corsOn = options.allowedOrigins === \"*\" || options.allowedOrigins.length > 0;\n\tif (request.method === \"OPTIONS\" && corsOn) return preflight(request, options.allowedOrigins);\n\tconst head = request.method === \"HEAD\";\n\tif (request.method !== \"GET\" && !head) {\n\t\tconst allow = corsOn ? \"GET, HEAD, OPTIONS\" : \"GET, HEAD\";\n\t\treturn withHeaders(errorResponse(405, \"method_not_allowed\", \"Use GET or HEAD\", { Allow: allow }), cors, false);\n\t}\n\tconst url = new URL(request.url);\n\tconst parsed = parsePublicRoute(url);\n\tif (!parsed.ok) return withHeaders(errorResponse(parsed.status, parsed.error, parsed.message), cors, head);\n\tif (parsed.route.kind === \"image\") return withHeaders(await image(env, parsed.route, request), cors, head);\n\n\tconst path = canonicalPath(parsed.route);\n\tconst key = `${options.cache} ${path}`;\n\tlet response = memo.get(key);\n\tif (response === null) {\n\t\tlet fresh: Response;\n\t\tlet expiresAt = 0;\n\t\ttry {\n\t\t\tif (options.cache === \"workers-cache\") {\n\t\t\t\t// A fresh request: none of the visitor's headers reach the cached entrypoint.\n\t\t\t\tfresh = await ctx.exports.PublicApi.fetch(new Request(new URL(path, url.origin)));\n\t\t\t\texpiresAt = keepUntil(fresh, Date.now());\n\t\t\t} else {\n\t\t\t\tconst { result, tags } = await source(env, parsed.route);\n\t\t\t\tfresh = viewResponse(result, \"durable-object\", tags);\n\t\t\t\texpiresAt = viewKeepUntil(result, Date.now());\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(`Public API ${url.pathname} failed`, error);\n\t\t\tfresh = errorResponse(500, \"internal_error\", \"Something went wrong\");\n\t\t}\n\t\tresponse = await memo.put(key, fresh, expiresAt, memoBucket(parsed.route, fresh.status));\n\t}\n\tconst result = withHeaders(response, cors, head);\n\t// Internal to the edge: Cloudflare strips it; other callers do not need it either.\n\tresult.headers.delete(\"Cache-Tag\");\n\treturn result;\n}\n","/**\n * Clearing a page's cached public responses when an administrator\n * publishes or changes something it shows. The admin API calls {@link purgePublicPage} after\n * every such write (incidents, their updates, maintenance, appearance), before it responds.\n * See worker/public/index.ts for the caching modes.\n */\nimport type { PublicApiCache } from \"@naosystem/cf-workers-status-page-core\";\nimport { config, findPage } from \"./config\";\nimport { type ResponseMemo, responseMemo } from \"./public\";\nimport { PAGES_TAG, pageTag } from \"./public/routes\";\nimport { statusPageStub } from \"./status-page\";\n\nexport interface PurgeTarget {\n\treadonly env: Env;\n\treadonly ctx: ExecutionContext;\n\t/** The page whose public responses changed. */\n\treadonly pageId: string;\n\t/** Incidents were deleted: the page's history reads its incidents in full again. */\n\treadonly incidentsDeleted?: boolean;\n}\n\n/**\n * Call before a write that changes what a public page shows (the admin API does; so must\n * automation such as `incidents.auto`), and {@link purgePublicPage} after it. Until then (or\n * for `CHANGE_WINDOW_MS` if it never comes), the page's Durable Object marks every response\n * it computes as not cacheable: one that read the data before the write commits must not be\n * kept by the Worker's or Cloudflare's cache after the purge. Never throws: if it fails, the\n * change still shows, at worst after 30 seconds.\n */\nexport async function announcePublicPageChange(target: PurgeTarget): Promise<void> {\n\tconst { env, pageId } = target;\n\t// A page no longer configured has no object (and naming one would create it).\n\tif (findPage(pageId) === undefined) return;\n\ttry {\n\t\tawait statusPageStub(env, pageId).beginChange();\n\t} catch (error) {\n\t\tconsole.warn(`Could not announce a change of page \"${pageId}\" to its Durable Object`, error);\n\t}\n}\n\n/**\n * A token bucket for Workers Cache purges. Cloudflare limits them per account like zone\n * purges on the Free plan, whatever the plan: 5 per minute, in bursts of up to 25\n * ([Workers Cache: purge rate limits](https://developers.cloudflare.com/workers/cache/limitations/#purge-rate-limits),\n * [purge limits](https://developers.cloudflare.com/cache/how-to/purge-cache/#availability-and-limits)).\n * This one counts the purges of one isolate, so that a burst of administrator writes does\n * not send purges that Cloudflare would refuse; Cloudflare's own limit, shared with other\n * isolates and Workers of the account, still decides, and its refusals are handled the same.\n */\nexport class PurgeLimiter {\n\tprivate tokens: number;\n\tprivate updatedAt: number;\n\tprivate readonly burst: number;\n\tprivate readonly perMinute: number;\n\n\tconstructor(burst = 25, perMinute = 5, now = Date.now()) {\n\t\tthis.burst = burst;\n\t\tthis.perMinute = perMinute;\n\t\tthis.tokens = burst;\n\t\tthis.updatedAt = now;\n\t}\n\n\t/** Takes a token if one is left. */\n\ttake(now = Date.now()): boolean {\n\t\tconst elapsed = Math.max(0, now - this.updatedAt);\n\t\tthis.tokens = Math.min(this.burst, this.tokens + (elapsed * this.perMinute) / 60_000);\n\t\tthis.updatedAt = Math.max(this.updatedAt, now);\n\t\tif (this.tokens < 1) return false;\n\t\tthis.tokens -= 1;\n\t\treturn true;\n\t}\n}\n\nconst isolateLimiter = new PurgeLimiter();\n\n/** What {@link purgePublicPage} did. */\nexport interface PurgeReport {\n\t/** The page's Durable Object: its computed responses were dropped (`skipped`: the page is not configured). */\n\treadonly page: \"cleared\" | \"skipped\" | \"failed\";\n\t/**\n\t * Workers Cache: `not-used` in the `durable-object` mode; `rate-limited` when no purge was\n\t * left (not sent; entries expire within 30 seconds); `failed` when Cloudflare refused it\n\t * (its rate limit, say) or it threw; `unavailable` without Workers Cache (local development).\n\t */\n\treadonly cache: \"not-used\" | \"purged\" | \"rate-limited\" | \"failed\" | \"unavailable\";\n}\n\nexport interface PurgeOptions {\n\treadonly cache: PublicApiCache;\n\treadonly limiter: PurgeLimiter;\n\treadonly memo: ResponseMemo;\n}\n\n/**\n * Drops the page's computed responses in its StatusPage DO (immediately, for every data\n * centre), then forgets them in this isolate's memo and, in the `workers-cache` mode, purges\n * its entries and the list of pages from Workers Cache. In that order: a response computed\n * before the change is then either dropped by the purge or marked not cacheable by the\n * object (its computation spanned the change), so it cannot be cached after the purge. Never\n * throws: the administrator's write has happened, and whatever could not be cleared expires\n * within 30 seconds. Problems are logged.\n */\nexport async function purgePublicPage(\n\ttarget: PurgeTarget,\n\toptions: PurgeOptions = { cache: config.publicApi.cache, limiter: isolateLimiter, memo: responseMemo },\n): Promise<PurgeReport> {\n\tconst { env, ctx, pageId } = target;\n\tconst clearPage = async (): Promise<PurgeReport[\"page\"]> => {\n\t\t// A page no longer configured has no object to clear (and naming one would create it).\n\t\tif (findPage(pageId) === undefined) return \"skipped\";\n\t\ttry {\n\t\t\tawait statusPageStub(env, pageId).invalidate({ incidentsDeleted: target.incidentsDeleted === true });\n\t\t\treturn \"cleared\";\n\t\t} catch (error) {\n\t\t\tconsole.warn(`Could not clear the computed responses of page \"${pageId}\"`, error);\n\t\t\treturn \"failed\";\n\t\t}\n\t};\n\tconst purgeCache = async (): Promise<PurgeReport[\"cache\"]> => {\n\t\tif (options.cache !== \"workers-cache\") return \"not-used\";\n\t\tif (!options.limiter.take()) {\n\t\t\tconsole.warn(`Workers Cache purge for page \"${pageId}\" skipped: purge rate limit reached; entries expire within 30 seconds`);\n\t\t\treturn \"rate-limited\";\n\t\t}\n\t\ttry {\n\t\t\tconst outcome = await ctx.exports.PublicApi.purge({ tags: [pageTag(pageId), PAGES_TAG] });\n\t\t\tif (outcome.status === \"failed\") {\n\t\t\t\tconsole.warn(`Workers Cache purge for page \"${pageId}\" refused: ${outcome.errors.join(\"; \")}; entries expire within 30 seconds`);\n\t\t\t}\n\t\t\treturn outcome.status;\n\t\t} catch (error) {\n\t\t\tconsole.warn(`Workers Cache purge for page \"${pageId}\" failed; entries expire within 30 seconds`, error);\n\t\t\treturn \"failed\";\n\t\t}\n\t};\n\tconst page = await clearPage();\n\toptions.memo.forgetPage(pageId);\n\tconst cache = await purgeCache();\n\treturn { page, cache };\n}\n","import type { AdminIdentity, ResolvedPage } from \"@naosystem/cf-workers-status-page-core\";\nimport type { ApiIssue } from \"../../shared/admin-api\";\nimport { findPage } from \"../config\";\nimport type { Actor } from \"../db/common\";\nimport { announcePublicPageChange, purgePublicPage } from \"../public-cache\";\n\n/** What an admin API handler gets. */\nexport interface AdminContext {\n\treadonly request: Request;\n\treadonly url: URL;\n\treadonly env: Env;\n\treadonly ctx: ExecutionContext;\n\t/** Path parameters, such as `id` in `incidents/:id`. */\n\treadonly params: Readonly<Record<string, string>>;\n\treadonly identity: AdminIdentity;\n\t/** The identity as the author of changes. */\n\treadonly actor: Actor;\n}\n\nexport { findPage };\n\n/**\n * Issues for component IDs that `page` does not have (incidents and maintenance refer\n * to components by ID). `path(index)` locates each one in the request body.\n */\nexport function unknownComponents(\n\tpage: ResolvedPage,\n\tids: readonly string[],\n\tpath: (index: number) => (string | number)[],\n): ApiIssue[] {\n\tconst known = new Set(page.components.map((component) => component.id));\n\treturn ids.flatMap((id, index) =>\n\t\tknown.has(id)\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t{\n\t\t\t\t\t\tpath: path(index),\n\t\t\t\t\t\tmessage: `Page \"${page.id}\" has no component \"${id}\"`,\n\t\t\t\t\t\tcode: \"unknown_component\",\n\t\t\t\t\t\tparams: { page: page.id, component: id },\n\t\t\t\t\t},\n\t\t\t\t],\n\t);\n}\n\n/**\n * Call before a write that changes what a public page shows, and {@link publicPageChanged}\n * after it (nothing computed in between is cached). Never fails the request.\n */\nexport async function publicPageChanging(admin: AdminContext, pageId: string): Promise<void> {\n\tawait announcePublicPageChange({ env: admin.env, ctx: admin.ctx, pageId });\n}\n\n/**\n * Call after a write that changes what a public page shows: clears the page's cached public\n * responses. Never fails the request: the write happened, and what could not\n * be cleared expires within 30 seconds (`purgePublicPage` logs it).\n */\nexport async function publicPageChanged(\n\tadmin: AdminContext,\n\tpageId: string,\n\toptions: { readonly incidentsDeleted?: boolean } = {},\n): Promise<void> {\n\ttry {\n\t\tawait purgePublicPage({ env: admin.env, ctx: admin.ctx, pageId, incidentsDeleted: options.incidentsDeleted === true });\n\t} catch (error) {\n\t\tconsole.warn(`Could not purge the cached public responses of page \"${pageId}\"`, error);\n\t}\n}\n","import * as z from \"zod\";\nimport { LIMITS } from \"../../shared/admin-api\";\nimport { decodeCursor } from \"../db/common\";\n\n/**\n * Query parameters of list endpoints: `?page=<page ID>&limit=<1-100>&cursor=<nextCursor>`.\n * `page` is required (lists are per page, and walk a per-page index); it may be a page no\n * longer in status.config.ts. Other parameters are ignored.\n */\nexport const listQuerySchema = z.object({\n\tpage: z.string({ error: \"Required: the ID of the page\" }).min(1).max(64),\n\tlimit: z.coerce.number().int().min(1).max(LIMITS.pageSize).default(50),\n\tcursor: z\n\t\t.string()\n\t\t.transform((value, ctx) => {\n\t\t\tconst cursor = decodeCursor(value);\n\t\t\tif (cursor === undefined) {\n\t\t\t\tctx.addIssue({ code: \"custom\", message: \"Not a cursor from a previous page\" });\n\t\t\t\treturn z.NEVER;\n\t\t\t}\n\t\t\treturn cursor;\n\t\t})\n\t\t.optional(),\n});\n","/** `/api/admin/incidents`: incidents and their timelines. */\nimport * as z from \"zod\";\nimport {\n\ttype AffectedComponent,\n\tcreateIncidentSchema,\n\tpatchIncidentSchema,\n\tpostIncidentUpdateSchema,\n\tresolveIncidentSchema,\n\tSTART_TIME_TOLERANCE_MS,\n} from \"../../shared/admin-api\";\nimport {\n\tcreateIncident,\n\tdeleteIncident,\n\tgetIncident,\n\tgetIncidentWithUpdates,\n\tlistIncidents,\n\tpatchIncident,\n\tpostIncidentUpdate,\n} from \"../db/incidents\";\nimport { type AdminContext, findPage, publicPageChanged, publicPageChanging, unknownComponents } from \"./context\";\nimport { apiError, editConflict, json, noContent, notFound, readBody, validate, validationFailed } from \"./http\";\nimport { listQuerySchema } from \"./list-query\";\n\nconst incidentListQuerySchema = listQuerySchema.extend({\n\t/** `open`: not resolved yet. */\n\tstatus: z.enum([\"open\", \"resolved\"]).optional(),\n});\n\n/** Issues for affected components the incident's page does not have (or for a page no longer configured). */\nfunction componentIssues(pageId: string, components: readonly AffectedComponent[] | undefined) {\n\tif (components === undefined) return [];\n\tconst page = findPage(pageId);\n\tif (page === undefined) {\n\t\treturn [{ path: [\"components\"], message: `Page \"${pageId}\" is no longer in status.config.ts`, code: \"page_removed\", params: { page: pageId } }];\n\t}\n\treturn unknownComponents(\n\t\tpage,\n\t\tcomponents.map((component) => component.id),\n\t\t(index) => [\"components\", index, \"id\"],\n\t);\n}\n\nexport async function list(admin: AdminContext): Promise<Response> {\n\tconst query = validate(incidentListQuerySchema, Object.fromEntries(admin.url.searchParams));\n\tif (!query.ok) return query.response;\n\tconst { page, status, limit, cursor } = query.value;\n\treturn json(await listIncidents(admin.env.DB, { pageId: page, status, limit, after: cursor }));\n}\n\nexport async function create(admin: AdminContext): Promise<Response> {\n\tconst body = await readBody(admin.request, createIncidentSchema);\n\tif (!body.ok) return body.response;\n\tconst input = body.value;\n\tconst now = Date.now();\n\tif (findPage(input.pageId) === undefined) {\n\t\treturn validationFailed([\n\t\t\t{ path: [\"pageId\"], message: `No page \"${input.pageId}\" in status.config.ts`, code: \"unknown_page\", params: { page: input.pageId } },\n\t\t]);\n\t}\n\t// In the past is fine; a little ahead is a fast clock, and is stored as now.\n\tif (input.startedAt !== undefined && input.startedAt > now + START_TIME_TOLERANCE_MS) {\n\t\treturn validationFailed([{ path: [\"startedAt\"], message: \"Must not be in the future\", code: \"start_in_future\" }]);\n\t}\n\tconst issues = componentIssues(input.pageId, input.components);\n\tif (issues.length > 0) return validationFailed(issues);\n\tawait publicPageChanging(admin, input.pageId);\n\tconst incident = await createIncident(admin.env.DB, { ...input, startedAt: input.startedAt ?? now }, admin.actor, now);\n\tawait publicPageChanged(admin, incident.pageId);\n\treturn json(incident, 201);\n}\n\nexport async function get(admin: AdminContext): Promise<Response> {\n\tconst incident = await getIncidentWithUpdates(admin.env.DB, admin.params[\"id\"] ?? \"\");\n\treturn incident === null ? notFound(\"incident\") : json(incident);\n}\n\nexport async function patch(admin: AdminContext): Promise<Response> {\n\tconst body = await readBody(admin.request, patchIncidentSchema);\n\tif (!body.ok) return body.response;\n\tconst { version, ...changes } = body.value;\n\tconst existing = await getIncident(admin.env.DB, admin.params[\"id\"] ?? \"\");\n\tif (existing === null) return notFound(\"incident\");\n\tif (existing.version !== version) return editConflict(existing);\n\tconst issues = componentIssues(existing.pageId, changes.components);\n\tif (issues.length > 0) return validationFailed(issues);\n\tawait publicPageChanging(admin, existing.pageId);\n\tconst result = await patchIncident(admin.env.DB, existing.id, version, changes, admin.actor);\n\tswitch (result.status) {\n\t\tcase \"not-found\":\n\t\t\treturn notFound(\"incident\");\n\t\tcase \"conflict\":\n\t\t\treturn editConflict(result.current);\n\t\tcase \"updated\":\n\t\t\tawait publicPageChanged(admin, result.value.pageId);\n\t\t\treturn json(result.value);\n\t}\n}\n\nexport async function remove(admin: AdminContext): Promise<Response> {\n\tconst existing = await getIncident(admin.env.DB, admin.params[\"id\"] ?? \"\");\n\tif (existing === null) return notFound(\"incident\");\n\tawait publicPageChanging(admin, existing.pageId);\n\tif (!(await deleteIncident(admin.env.DB, existing.id))) return notFound(\"incident\");\n\tawait publicPageChanged(admin, existing.pageId, { incidentsDeleted: true });\n\treturn noContent();\n}\n\nexport async function postUpdate(admin: AdminContext): Promise<Response> {\n\tconst body = await readBody(admin.request, postIncidentUpdateSchema);\n\tif (!body.ok) return body.response;\n\tconst existing = await getIncident(admin.env.DB, admin.params[\"id\"] ?? \"\");\n\tif (existing === null) return notFound(\"incident\");\n\tconst issues = componentIssues(existing.pageId, body.value.components);\n\tif (issues.length > 0) return validationFailed(issues);\n\tif (body.value.version !== undefined && body.value.version !== existing.version) return editConflict(existing);\n\tawait publicPageChanging(admin, existing.pageId);\n\tconst incident = await postIncidentUpdate(admin.env.DB, existing.id, body.value, admin.actor);\n\tif (incident === null) {\n\t\t// Changed (or deleted) between the check above and the write.\n\t\tconst current = await getIncident(admin.env.DB, existing.id);\n\t\treturn current === null ? notFound(\"incident\") : editConflict(current);\n\t}\n\tawait publicPageChanged(admin, incident.pageId);\n\treturn json(incident, 201);\n}\n\nexport async function resolve(admin: AdminContext): Promise<Response> {\n\tconst body = await readBody(admin.request, resolveIncidentSchema);\n\tif (!body.ok) return body.response;\n\tconst existing = await getIncident(admin.env.DB, admin.params[\"id\"] ?? \"\");\n\tif (existing === null) return notFound(\"incident\");\n\tif (existing.resolvedAt !== null) {\n\t\treturn apiError(409, \"already_resolved\", \"The incident is already resolved; post an update to add to it\");\n\t}\n\tawait publicPageChanging(admin, existing.pageId);\n\tconst incident = await postIncidentUpdate(\n\t\tadmin.env.DB,\n\t\texisting.id,\n\t\t{ stage: \"resolved\", body: body.value.body },\n\t\tadmin.actor,\n\t);\n\tif (incident === null) return notFound(\"incident\");\n\tawait publicPageChanged(admin, incident.pageId);\n\treturn json(incident, 201);\n}\n","/** `/api/admin/maintenance`: scheduled maintenance. */\nimport { createMaintenanceSchema, patchMaintenanceSchema } from \"../../shared/admin-api\";\nimport {\n\tcreateMaintenance,\n\tdeleteMaintenance,\n\tgetMaintenance,\n\tlistMaintenance,\n\ttype MaintenanceFields,\n\tupdateMaintenance,\n} from \"../db/maintenance\";\nimport { type AdminContext, findPage, publicPageChanged, publicPageChanging, unknownComponents } from \"./context\";\nimport { editConflict, json, noContent, notFound, readBody, validate, validationFailed } from \"./http\";\nimport { listQuerySchema } from \"./list-query\";\n\n/** Issues for components the page does not have (or for a page no longer configured). */\nfunction componentIssues(pageId: string, components: readonly string[]) {\n\tconst page = findPage(pageId);\n\tif (page === undefined) {\n\t\treturn [{ path: [\"components\"], message: `Page \"${pageId}\" is no longer in status.config.ts`, code: \"page_removed\", params: { page: pageId } }];\n\t}\n\treturn unknownComponents(page, components, (index) => [\"components\", index]);\n}\n\nexport async function list(admin: AdminContext): Promise<Response> {\n\tconst query = validate(listQuerySchema, Object.fromEntries(admin.url.searchParams));\n\tif (!query.ok) return query.response;\n\tconst { page, limit, cursor } = query.value;\n\treturn json(await listMaintenance(admin.env.DB, { pageId: page, limit, after: cursor }));\n}\n\nexport async function create(admin: AdminContext): Promise<Response> {\n\tconst body = await readBody(admin.request, createMaintenanceSchema);\n\tif (!body.ok) return body.response;\n\tconst { pageId, ...fields } = body.value;\n\tif (findPage(pageId) === undefined) {\n\t\treturn validationFailed([{ path: [\"pageId\"], message: `No page \"${pageId}\" in status.config.ts`, code: \"unknown_page\", params: { page: pageId } }]);\n\t}\n\tconst issues = componentIssues(pageId, fields.components);\n\tif (issues.length > 0) return validationFailed(issues);\n\tawait publicPageChanging(admin, pageId);\n\tconst maintenance = await createMaintenance(admin.env.DB, pageId, fields, admin.actor);\n\tawait publicPageChanged(admin, pageId);\n\treturn json(maintenance, 201);\n}\n\nexport async function get(admin: AdminContext): Promise<Response> {\n\tconst maintenance = await getMaintenance(admin.env.DB, admin.params[\"id\"] ?? \"\");\n\treturn maintenance === null ? notFound(\"maintenance\") : json(maintenance);\n}\n\nexport async function patch(admin: AdminContext): Promise<Response> {\n\tconst body = await readBody(admin.request, patchMaintenanceSchema);\n\tif (!body.ok) return body.response;\n\tconst { version, ...changes } = body.value;\n\tconst existing = await getMaintenance(admin.env.DB, admin.params[\"id\"] ?? \"\");\n\tif (existing === null) return notFound(\"maintenance\");\n\t// The changes apply to the version the editor saw, not to someone else's newer one.\n\tif (existing.version !== version) return editConflict(existing);\n\tconst fields: MaintenanceFields = {\n\t\ttitle: changes.title ?? existing.title,\n\t\tbody: changes.body ?? existing.body,\n\t\tstartsAt: changes.startsAt ?? existing.startsAt,\n\t\tendsAt: changes.endsAt ?? existing.endsAt,\n\t\tcomponents: changes.components ?? existing.components,\n\t};\n\tif (fields.endsAt <= fields.startsAt) {\n\t\treturn validationFailed([\n\t\t\t{\n\t\t\t\tpath: [changes.endsAt === undefined ? \"startsAt\" : \"endsAt\"],\n\t\t\t\tmessage: \"The maintenance must end after it starts\",\n\t\t\t\tcode: \"ends_before_start\",\n\t\t\t},\n\t\t]);\n\t}\n\tif (changes.components !== undefined) {\n\t\tconst issues = componentIssues(existing.pageId, changes.components);\n\t\tif (issues.length > 0) return validationFailed(issues);\n\t}\n\tawait publicPageChanging(admin, existing.pageId);\n\tconst result = await updateMaintenance(admin.env.DB, existing.id, version, fields, admin.actor);\n\tswitch (result.status) {\n\t\tcase \"not-found\":\n\t\t\treturn notFound(\"maintenance\");\n\t\tcase \"conflict\":\n\t\t\treturn editConflict(result.current);\n\t\tcase \"updated\":\n\t\t\tawait publicPageChanged(admin, result.value.pageId);\n\t\t\treturn json(result.value);\n\t}\n}\n\nexport async function remove(admin: AdminContext): Promise<Response> {\n\tconst existing = await getMaintenance(admin.env.DB, admin.params[\"id\"] ?? \"\");\n\tif (existing === null) return notFound(\"maintenance\");\n\tawait publicPageChanging(admin, existing.pageId);\n\tif (!(await deleteMaintenance(admin.env.DB, existing.id))) return notFound(\"maintenance\");\n\tawait publicPageChanged(admin, existing.pageId);\n\treturn noContent();\n}\n","/**\n * `/api/admin/monitors`: monitors are defined in status.config.ts, so the admin API only\n * shows them, together with the monitors that left the configuration but whose data\n * is kept, and deletes those on request.\n */\nimport type { AdminMonitor, AdminMonitorsResponse } from \"../../shared/admin-api\";\nimport { config } from \"../config\";\nimport { type MonitorSnapshot, monitorStub } from \"../monitor\";\nimport { forEachLimited, purgeMonitor, reconcilerStub } from \"../reconciler\";\nimport type { AdminContext } from \"./context\";\nimport { apiError, json, noContent, notFound } from \"./http\";\n\nexport type { AdminMonitor };\n\n/** Monitor DOs asked for their snapshot at once. */\nconst SNAPSHOT_CONCURRENCY = 8;\n/** Same rule as monitor IDs in status.config.ts: anything else cannot exist. */\nconst MONITOR_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\n/** Configured monitors and every monitor in the registry, sorted by ID, each with its current snapshot. */\nexport async function list(admin: AdminContext): Promise<Response> {\n\tconst registry = await reconcilerStub(admin.env).listMonitors();\n\tconst registered = new Map(registry.map((entry) => [entry.id, entry]));\n\tconst configured = new Map(config.monitors.map((monitor) => [monitor.id, monitor]));\n\tconst ids = [...new Set([...configured.keys(), ...registered.keys()])].sort();\n\n\tconst snapshots = await forEachLimited(ids, SNAPSHOT_CONCURRENCY, (id) => {\n\t\t// The configured location first: a monitor not started yet is created where it belongs.\n\t\tconst location = configured.get(id)?.location ?? registered.get(id)?.location ?? null;\n\t\treturn monitorStub(admin.env, { id, location }).getSnapshot() as Promise<MonitorSnapshot>;\n\t});\n\n\tconst monitors = ids.map((id, index): AdminMonitor => {\n\t\tconst monitor = configured.get(id);\n\t\tconst outcome = snapshots[index];\n\t\treturn {\n\t\t\tid,\n\t\t\tconfigured: monitor !== undefined,\n\t\t\tconfig:\n\t\t\t\tmonitor === undefined\n\t\t\t\t\t? null\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tname: monitor.name,\n\t\t\t\t\t\t\ttype: monitor.provider.type,\n\t\t\t\t\t\t\tintervalMs: monitor.intervalMs,\n\t\t\t\t\t\t\ttimeoutMs: monitor.timeoutMs,\n\t\t\t\t\t\t\tlocation: monitor.location ?? null,\n\t\t\t\t\t\t},\n\t\t\tcomponents: config.pages.flatMap((page) =>\n\t\t\t\tpage.components\n\t\t\t\t\t.filter((component) => component.monitors.includes(id))\n\t\t\t\t\t.map((component) => ({ pageId: page.id, componentId: component.id })),\n\t\t\t),\n\t\t\tregistry: registered.get(id) ?? null,\n\t\t\tsnapshot: outcome?.status === \"fulfilled\" ? outcome.value : null,\n\t\t\tsnapshotError: outcome?.status === \"rejected\" ? String(outcome.reason) : null,\n\t\t};\n\t});\n\treturn json({ monitors } satisfies AdminMonitorsResponse);\n}\n\n/**\n * Deletes a removed monitor's results and history. Refused (409, with the reason)\n * while status.config.ts has it, while it is still running, or during a deploy.\n */\nexport async function purge(admin: AdminContext): Promise<Response> {\n\tconst id = admin.params[\"id\"] ?? \"\";\n\tif (!MONITOR_ID.test(id)) return notFound(\"monitor\");\n\tconst result = await purgeMonitor(admin.env, id);\n\tswitch (result.status) {\n\t\tcase \"purged\":\n\t\t\treturn noContent();\n\t\tcase \"not-found\":\n\t\t\treturn notFound(\"monitor\");\n\t\tcase \"refused\":\n\t\t\treturn apiError(409, \"purge_refused\", result.reason, { reason: result.code });\n\t}\n}\n","/**\n * Notification data in D1: targets (with encrypted secret options), the record of\n * each notification × target delivery, `unknown` alerts, and `down` events held back by\n * maintenance. Validation, encryption and configuration checks are the callers' job.\n */\nimport type {\n\tComponentRef,\n\tDeliveryStatus,\n\tListPage,\n\tNotificationDelivery,\n\tNotificationEvent,\n} from \"../../shared/admin-api\";\nimport type { MonitorEvent } from \"../notifications/events\";\nimport type { MaintenanceWindow } from \"../notifications/rules\";\nimport { type Actor, actorName, type EditResult, parseJsonColumn } from \"./common\";\n\n// ---------------------------------------------------------------------------\n// Targets\n// ---------------------------------------------------------------------------\n\n/** A target as stored: secret options are encrypted (`secrets`), never plain text. */\nexport interface TargetRecord {\n\treadonly id: string;\n\treadonly name: string;\n\treadonly kind: string;\n\t/** Options that are not secret, as entered. */\n\treadonly options: Readonly<Record<string, unknown>>;\n\t/** Secret options, each encrypted (worker/notifications/crypto.ts). */\n\treadonly secrets: Readonly<Record<string, string>>;\n\treadonly admin: boolean;\n\treadonly enabled: boolean;\n\treadonly events: readonly NotificationEvent[];\n\treadonly allMonitors: boolean;\n\treadonly monitors: readonly string[];\n\treadonly components: readonly ComponentRef[];\n\treadonly createdAt: number;\n\treadonly updatedAt: number;\n\treadonly createdBy: string | null;\n\treadonly updatedBy: string | null;\n\treadonly version: number;\n}\n\n/** What an edit sets: everything but the identity, the kind and the bookkeeping. */\nexport type TargetFields = Pick<\n\tTargetRecord,\n\t\"name\" | \"options\" | \"secrets\" | \"admin\" | \"enabled\" | \"events\" | \"allMonitors\" | \"monitors\" | \"components\"\n>;\n\n/** An edit: `secrets` (and `options`) only when the options changed, so that an edit of other fields cannot write back secrets encrypted with an older key over a re-encryption (see `replaceSecrets`). */\nexport type TargetChanges = Omit<TargetFields, \"options\" | \"secrets\"> & {\n\treadonly options?: TargetFields[\"options\"] | undefined;\n\treadonly secrets?: TargetFields[\"secrets\"] | undefined;\n};\n\ntype TargetRow = {\n\tid: string;\n\tname: string;\n\tkind: string;\n\toptions: string;\n\tsecrets: string;\n\tadmin: number;\n\tenabled: number;\n\tevents: string;\n\tall_monitors: number;\n\tmonitors: string;\n\tcomponents: string;\n\tcreated_at: number;\n\tupdated_at: number;\n\tcreated_by: string | null;\n\tupdated_by: string | null;\n\tversion: number;\n};\n\nconst TARGET_COLUMNS =\n\t\"id, name, kind, options, secrets, admin, enabled, events, all_monitors, monitors, components, created_at, updated_at, created_by, updated_by, version\";\n\n/** Most targets read at once. A hub with more is misconfigured; the admin list and fan-out stop there. */\nexport const MAX_TARGETS = 500;\n\nfunction toTarget(row: TargetRow): TargetRecord {\n\tconst where = `notification target ${row.id}`;\n\treturn {\n\t\tid: row.id,\n\t\tname: row.name,\n\t\tkind: row.kind,\n\t\toptions: parseJsonColumn<Record<string, unknown>>(row.options, {}, where),\n\t\tsecrets: parseJsonColumn<Record<string, string>>(row.secrets, {}, where),\n\t\tadmin: row.admin !== 0,\n\t\tenabled: row.enabled !== 0,\n\t\tevents: parseJsonColumn<NotificationEvent[]>(row.events, [], where),\n\t\tallMonitors: row.all_monitors !== 0,\n\t\tmonitors: parseJsonColumn<string[]>(row.monitors, [], where),\n\t\tcomponents: parseJsonColumn<ComponentRef[]>(row.components, [], where),\n\t\tcreatedAt: row.created_at,\n\t\tupdatedAt: row.updated_at,\n\t\tcreatedBy: row.created_by,\n\t\tupdatedBy: row.updated_by,\n\t\tversion: row.version,\n\t};\n}\n\nfunction fieldValues(fields: TargetFields): unknown[] {\n\treturn [\n\t\tfields.name,\n\t\tJSON.stringify(fields.options),\n\t\tJSON.stringify(fields.secrets),\n\t\tfields.admin ? 1 : 0,\n\t\tfields.enabled ? 1 : 0,\n\t\tJSON.stringify(fields.events),\n\t\tfields.allMonitors ? 1 : 0,\n\t\tJSON.stringify(fields.monitors),\n\t\tJSON.stringify(fields.components),\n\t];\n}\n\n/** Stores a new target. `id` is chosen by the caller, because secrets are encrypted for it first. */\nexport async function insertTarget(\n\tdb: D1Database,\n\tid: string,\n\tkind: string,\n\tfields: TargetFields,\n\tactor: Actor,\n\tnow = Date.now(),\n): Promise<TargetRecord> {\n\tconst name = actorName(actor);\n\tconst row = await db\n\t\t.prepare(\n\t\t\t`INSERT INTO notification_targets (${TARGET_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)\n\t\t\tRETURNING ${TARGET_COLUMNS}`,\n\t\t)\n\t\t.bind(id, fields.name, kind, ...fieldValues(fields).slice(1), now, now, name, name)\n\t\t.first<TargetRow>();\n\tif (row === null) throw new Error(`Could not insert notification target ${id}`);\n\treturn toTarget(row);\n}\n\nexport async function getTarget(db: D1Database, id: string): Promise<TargetRecord | null> {\n\tconst row = await db.prepare(`SELECT ${TARGET_COLUMNS} FROM notification_targets WHERE id = ?`).bind(id).first<TargetRow>();\n\treturn row === null ? null : toTarget(row);\n}\n\n/** Every target (at most {@link MAX_TARGETS}), by name; only enabled ones with `enabledOnly`. */\nexport async function listTargets(db: D1Database, options: { readonly enabledOnly?: boolean } = {}): Promise<TargetRecord[]> {\n\tconst { results } = await db\n\t\t.prepare(\n\t\t\t`SELECT ${TARGET_COLUMNS} FROM notification_targets ${options.enabledOnly ? \"WHERE enabled = 1\" : \"\"}\n\t\t\tORDER BY name, id LIMIT ?`,\n\t\t)\n\t\t.bind(MAX_TARGETS)\n\t\t.all<TargetRow>();\n\treturn results.map(toTarget);\n}\n\n/** Replaces a target's fields if it is still at `version` (checked in the same statement). */\nexport async function updateTarget(\n\tdb: D1Database,\n\tid: string,\n\tversion: number,\n\tfields: TargetChanges,\n\tactor: Actor,\n\tnow = Date.now(),\n): Promise<EditResult<TargetRecord>> {\n\tconst row = await db\n\t\t.prepare(\n\t\t\t`UPDATE notification_targets SET name = ?, options = coalesce(?, options), secrets = coalesce(?, secrets), admin = ?,\n\t\t\t\tenabled = ?, events = ?, all_monitors = ?, monitors = ?, components = ?, updated_at = max(updated_at, ?),\n\t\t\t\tupdated_by = ?, version = version + 1\n\t\t\tWHERE id = ? AND version = ?\n\t\t\tRETURNING ${TARGET_COLUMNS}`,\n\t\t)\n\t\t.bind(\n\t\t\tfields.name,\n\t\t\tfields.options === undefined ? null : JSON.stringify(fields.options),\n\t\t\tfields.secrets === undefined ? null : JSON.stringify(fields.secrets),\n\t\t\tfields.admin ? 1 : 0,\n\t\t\tfields.enabled ? 1 : 0,\n\t\t\tJSON.stringify(fields.events),\n\t\t\tfields.allMonitors ? 1 : 0,\n\t\t\tJSON.stringify(fields.monitors),\n\t\t\tJSON.stringify(fields.components),\n\t\t\tnow,\n\t\t\tactorName(actor),\n\t\t\tid,\n\t\t\tversion,\n\t\t)\n\t\t.first<TargetRow>();\n\tif (row !== null) return { status: \"updated\", value: toTarget(row) };\n\tconst current = await getTarget(db, id);\n\treturn current === null ? { status: \"not-found\" } : { status: \"conflict\", current };\n}\n\n/**\n * Replaces a target's encrypted secrets with the same values under another key, if they have\n * not changed meanwhile. Not an edit: the version stays, so editors are not interrupted.\n */\nexport async function replaceSecrets(\n\tdb: D1Database,\n\tid: string,\n\tprevious: Readonly<Record<string, string>>,\n\tsecrets: Readonly<Record<string, string>>,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.prepare(\"UPDATE notification_targets SET secrets = ? WHERE id = ? AND secrets = ?\")\n\t\t.bind(JSON.stringify(secrets), id, JSON.stringify(previous))\n\t\t.run();\n\treturn result.meta.changes > 0;\n}\n\n/** `false` when it does not exist. Its delivery records stay (they expire). */\nexport async function deleteTarget(db: D1Database, id: string): Promise<boolean> {\n\tconst result = await db.prepare(\"DELETE FROM notification_targets WHERE id = ?\").bind(id).run();\n\treturn result.meta.changes > 0;\n}\n\n// ---------------------------------------------------------------------------\n// Deliveries: one record per notification × target\n// ---------------------------------------------------------------------------\n\nexport interface DeliveryKey {\n\treadonly notificationId: string;\n\treadonly targetId: string;\n}\n\nexport interface DeliveryInfo extends DeliveryKey {\n\treadonly event: NotificationEvent;\n\treadonly monitorId: string | null;\n\treadonly occurredAt: number;\n}\n\n/**\n * Statuses as stored: those the admin API shows ({@link DeliveryStatus}), and\n * - `queued`: written when the event is fanned out, before its delivery message is queued, so\n * that a recovery processed before that message still finds the target;\n * - `fanned_out` / `suppressed`: on the row of target {@link FAN_OUT_TARGET}, the event itself\n * was fanned out, or held back by maintenance (a recovery answering it can then go ahead);\n * - `pending`: on that row, the event was queued but not fanned out yet (the `down` the Cron\n * queues when a maintenance ends): a recovery answering it waits for it.\n */\nexport type StoredDeliveryStatus = DeliveryStatus | \"queued\" | \"fanned_out\" | \"suppressed\" | \"pending\";\n\n/** `target_id` of an event's own row: its fan-out marker, or its failure when it could not be fanned out. */\nexport const FAN_OUT_TARGET = \"*\";\n\nexport type Claim =\n\t/** This delivery may send now (`attempts` counts this one). */\n\t| { readonly claimed: true; readonly attempts: number }\n\t/** Another delivery of the same message sent it, or is sending it until `leaseUntil`. */\n\t| { readonly claimed: false; readonly status: StoredDeliveryStatus; readonly leaseUntil: number | null };\n\ntype DeliveryRow = {\n\tnotification_id: string;\n\ttarget_id: string;\n\tstatus: DeliveryStatus;\n\tevent: NotificationEvent;\n\tmonitor_id: string | null;\n\toccurred_at: number;\n\tattempts: number;\n\tlease_until: number | null;\n\tlast_error: string | null;\n\tcreated_at: number;\n\tupdated_at: number;\n};\n\n/**\n * Claims a delivery before sending: the duplicate check.\n * Succeeds unless it was sent, or another delivery of the same message holds it (it is\n * `sending` and its lease has not expired); a lease outlives a crashed consumer only until\n * `leaseUntil`. A `queued` row (written by the fan-out) is claimed like a missing one. One\n * statement, so two deliveries cannot both claim it.\n */\nexport async function claimDelivery(db: D1Database, info: DeliveryInfo, now: number, leaseMs: number): Promise<Claim> {\n\tconst row = await db\n\t\t.prepare(\n\t\t\t`INSERT INTO notification_deliveries (notification_id, target_id, status, event, monitor_id, occurred_at,\n\t\t\t\tattempts, lease_until, last_error, created_at, updated_at)\n\t\t\tVALUES (?1, ?2, 'sending', ?3, ?4, ?5, 1, ?6, NULL, ?7, ?7)\n\t\t\tON CONFLICT (notification_id, target_id) DO UPDATE SET status = 'sending', attempts = attempts + 1,\n\t\t\t\tlease_until = excluded.lease_until, updated_at = excluded.updated_at\n\t\t\tWHERE notification_deliveries.status IN ('queued', 'retrying', 'failed')\n\t\t\t\tOR (notification_deliveries.status = 'sending' AND notification_deliveries.lease_until <= excluded.updated_at)\n\t\t\tRETURNING attempts`,\n\t\t)\n\t\t.bind(info.notificationId, info.targetId, info.event, info.monitorId, info.occurredAt, now + leaseMs, now)\n\t\t.first<{ attempts: number }>();\n\tif (row !== null) return { claimed: true, attempts: row.attempts };\n\tconst existing = await db\n\t\t.prepare(\"SELECT status, lease_until FROM notification_deliveries WHERE notification_id = ? AND target_id = ?\")\n\t\t.bind(info.notificationId, info.targetId)\n\t\t.first<{ status: StoredDeliveryStatus; lease_until: number | null }>();\n\treturn { claimed: false, status: existing?.status ?? \"sending\", leaseUntil: existing?.lease_until ?? null };\n}\n\n/** Records the outcome of a claimed delivery. `error` must already be free of secrets. */\nexport async function finishDelivery(\n\tdb: D1Database,\n\tkey: DeliveryKey,\n\tstatus: \"sent\" | \"retrying\" | \"failed\",\n\terror: string | null,\n\tnow: number,\n): Promise<void> {\n\tawait db\n\t\t.prepare(\n\t\t\t`UPDATE notification_deliveries SET status = ?, last_error = coalesce(?, last_error), lease_until = NULL, updated_at = ?\n\t\t\tWHERE notification_id = ? AND target_id = ? AND status != 'sent'`,\n\t\t)\n\t\t.bind(status, error, now, key.notificationId, key.targetId)\n\t\t.run();\n}\n\n/**\n * Records that a delivery was given up: its message reached the dead letter queue after the\n * queue's last retry. Keeps the last error recorded by the attempts; never overrides\n * `sent` (a duplicate message that reached the dead letter queue after another was sent).\n */\nexport async function recordDeadLetter(db: D1Database, info: DeliveryInfo, attempts: number, now: number): Promise<void> {\n\tawait db\n\t\t.prepare(\n\t\t\t`INSERT INTO notification_deliveries (notification_id, target_id, status, event, monitor_id, occurred_at,\n\t\t\t\tattempts, lease_until, last_error, created_at, updated_at)\n\t\t\tVALUES (?1, ?2, 'failed', ?3, ?4, ?5, ?6, NULL, ?7, ?8, ?8)\n\t\t\tON CONFLICT (notification_id, target_id) DO UPDATE SET status = 'failed', lease_until = NULL,\n\t\t\t\tlast_error = coalesce(notification_deliveries.last_error, excluded.last_error),\n\t\t\t\tattempts = max(notification_deliveries.attempts, excluded.attempts), updated_at = excluded.updated_at\n\t\t\tWHERE notification_deliveries.status != 'sent'`,\n\t\t)\n\t\t.bind(\n\t\t\tinfo.notificationId,\n\t\t\tinfo.targetId,\n\t\t\tinfo.event,\n\t\t\tinfo.monitorId,\n\t\t\tinfo.occurredAt,\n\t\t\tattempts,\n\t\t\t\"Gave up after the queue's last retry\",\n\t\t\tnow,\n\t\t)\n\t\t.run();\n}\n\nexport interface DeliveryQuery {\n\treadonly status: DeliveryStatus;\n\treadonly limit: number;\n\t/** `nextCursor` of the previous page. */\n\treadonly after?: DeliveryCursor | undefined;\n}\n\n/** A position in the list of deliveries: last change, then notification and target. */\nexport interface DeliveryCursor {\n\treadonly at: number;\n\treadonly key: string;\n}\n\nconst DELIVERY_CURSOR = /^(\\d{1,16})\\.([0-9a-f]{2,1024})$/;\n\nfunction deliveryKey(notificationId: string, targetId: string): string {\n\treturn `${notificationId}/${targetId}`;\n}\n\nexport function encodeDeliveryCursor(cursor: DeliveryCursor): string {\n\tconst hex = [...new TextEncoder().encode(cursor.key)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\treturn `${cursor.at}.${hex}`;\n}\n\n/** `undefined` when `value` is not a cursor made by {@link encodeDeliveryCursor}. */\nexport function decodeDeliveryCursor(value: string): DeliveryCursor | undefined {\n\tconst match = DELIVERY_CURSOR.exec(value);\n\tif (match === null || (match[2] as string).length % 2 !== 0) return undefined;\n\tconst bytes = Uint8Array.from((match[2] as string).match(/../g) ?? [], (pair) => Number.parseInt(pair, 16));\n\treturn { at: Number(match[1]), key: new TextDecoder().decode(bytes) };\n}\n\n/** Deliveries with a status, latest change first, with the target's name. Walks `notification_deliveries_by_status`. */\nexport async function listDeliveries(db: D1Database, query: DeliveryQuery): Promise<ListPage<NotificationDelivery>> {\n\tconst after = query.after;\n\tconst { results } = await db\n\t\t.prepare(\n\t\t\t`SELECT d.notification_id, d.target_id, d.status, d.event, d.monitor_id, d.occurred_at, d.attempts, d.lease_until,\n\t\t\t\td.last_error, d.created_at, d.updated_at, t.name AS target_name\n\t\t\tFROM notification_deliveries AS d LEFT JOIN notification_targets AS t ON t.id = d.target_id\n\t\t\tWHERE d.status = ?1\n\t\t\t\tAND (?2 IS NULL OR d.updated_at < ?2 OR (d.updated_at = ?2 AND d.notification_id || '/' || d.target_id < ?3))\n\t\t\tORDER BY d.updated_at DESC, d.notification_id || '/' || d.target_id DESC LIMIT ?4`,\n\t\t)\n\t\t.bind(query.status, after?.at ?? null, after?.key ?? \"\", query.limit + 1)\n\t\t.all<DeliveryRow & { target_name: string | null }>();\n\tconst shown = results.slice(0, query.limit);\n\tconst last = shown.at(-1);\n\treturn {\n\t\titems: shown.map(\n\t\t\t(row): NotificationDelivery => ({\n\t\t\t\tnotificationId: row.notification_id,\n\t\t\t\ttargetId: row.target_id,\n\t\t\t\ttargetName: row.target_name,\n\t\t\t\tevent: row.event,\n\t\t\t\tmonitorId: row.monitor_id,\n\t\t\t\toccurredAt: row.occurred_at,\n\t\t\t\tstatus: row.status,\n\t\t\t\tattempts: row.attempts,\n\t\t\t\tlastError: row.last_error,\n\t\t\t\tcreatedAt: row.created_at,\n\t\t\t\tupdatedAt: row.updated_at,\n\t\t\t}),\n\t\t),\n\t\tnextCursor:\n\t\t\tresults.length > query.limit && last !== undefined\n\t\t\t\t? encodeDeliveryCursor({ at: last.updated_at, key: deliveryKey(last.notification_id, last.target_id) })\n\t\t\t\t: null,\n\t};\n}\n\n/**\n * Records the fan-out of `event` before its delivery messages are queued: a `queued` row per\n * target, and the event's own row (`fanned_out`, or `suppressed` when maintenance held it back\n * and no target gets it; either replaces `pending`). Idempotent: a retried fan-out leaves\n * existing rows as they are.\n */\nexport async function recordFanOut(\n\tdb: D1Database,\n\tevent: { readonly id: string; readonly event: string; readonly monitorId: string; readonly since: number },\n\ttargetIds: readonly string[],\n\toutcome: \"fanned_out\" | \"suppressed\",\n\tnow: number,\n): Promise<void> {\n\tconst marker = db\n\t\t.prepare(\n\t\t\t`INSERT INTO notification_deliveries (notification_id, target_id, status, event, monitor_id, occurred_at,\n\t\t\t\tattempts, lease_until, last_error, created_at, updated_at)\n\t\t\tVALUES (?, ?, ?, ?, ?, ?, 0, NULL, NULL, ?, ?)\n\t\t\tON CONFLICT (notification_id, target_id) DO UPDATE SET status = excluded.status, updated_at = excluded.updated_at\n\t\t\tWHERE notification_deliveries.status = 'pending'`,\n\t\t)\n\t\t.bind(event.id, FAN_OUT_TARGET, outcome, event.event, event.monitorId, event.since, now, now);\n\tconst insert = (targetId: string) =>\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t`INSERT INTO notification_deliveries (notification_id, target_id, status, event, monitor_id, occurred_at,\n\t\t\t\t\tattempts, lease_until, last_error, created_at, updated_at)\n\t\t\t\tVALUES (?, ?, 'queued', ?, ?, ?, 0, NULL, NULL, ?, ?) ON CONFLICT DO NOTHING`,\n\t\t\t)\n\t\t\t.bind(event.id, targetId, event.event, event.monitorId, event.since, now, now);\n\tconst statements = [marker, ...targetIds.map((targetId) => insert(targetId))];\n\tfor (let start = 0; start < statements.length; start += 100) await db.batch(statements.slice(start, start + 100));\n}\n\n/**\n * Records that `event` is about to be queued but is not fanned out yet (`pending` on its own\n * row), so that a recovery answering it waits for its fan-out instead of finding an earlier\n * event it pairs with (the held-back `down`) and going ahead without it. Idempotent.\n */\nexport async function recordPendingEvent(\n\tdb: D1Database,\n\tevent: { readonly id: string; readonly event: string; readonly monitorId: string; readonly since: number },\n\tnow: number,\n): Promise<void> {\n\tawait db\n\t\t.prepare(\n\t\t\t`INSERT INTO notification_deliveries (notification_id, target_id, status, event, monitor_id, occurred_at,\n\t\t\t\tattempts, lease_until, last_error, created_at, updated_at)\n\t\t\tVALUES (?, ?, 'pending', ?, ?, ?, 0, NULL, NULL, ?, ?) ON CONFLICT DO NOTHING`,\n\t\t)\n\t\t.bind(event.id, FAN_OUT_TARGET, event.event, event.monitorId, event.since, now, now)\n\t\t.run();\n}\n\nexport interface PairedTargets {\n\t/** Targets the answered event went to or is going to (any row but `failed`). */\n\treadonly targets: Set<string>;\n\t/**\n\t * Whether the answered event was processed at all (fanned out, held back, or given up on),\n\t * and none of the events it may be (`notificationIds`) is still `pending`.\n\t */\n\treadonly processed: boolean;\n}\n\n/**\n * For a recovery: the targets that the event it answers (one of `notificationIds`) went to,\n * and whether that event was processed yet. Reads the primary key's prefix of each ID.\n */\nexport async function pairedTargets(db: D1Database, notificationIds: readonly string[]): Promise<PairedTargets> {\n\tif (notificationIds.length === 0) return { targets: new Set(), processed: true };\n\tconst results = await db.batch(\n\t\tnotificationIds.map((id) =>\n\t\t\tdb.prepare(\"SELECT target_id, status FROM notification_deliveries WHERE notification_id = ?\").bind(id),\n\t\t),\n\t);\n\tconst rows = results.flatMap((result) => (result.results ?? []) as { target_id: string; status: StoredDeliveryStatus }[]);\n\treturn {\n\t\ttargets: new Set(rows.filter((row) => row.target_id !== FAN_OUT_TARGET && row.status !== \"failed\").map((row) => row.target_id)),\n\t\t// Rows of targets also mean it was processed (an event fanned out by an earlier version has no own row).\n\t\t// A `pending` one is queued and will be fanned out: e.g. the `down` queued when a maintenance\n\t\t// ended, while the `down` that maintenance held back already has its (`suppressed`) row.\n\t\tprocessed: rows.length > 0 && !rows.some((row) => row.target_id === FAN_OUT_TARGET && row.status === \"pending\"),\n\t};\n}\n\n/** Deletes delivery records last changed before `before`; returns how many. */\nexport async function purgeDeliveries(db: D1Database, before: number): Promise<number> {\n\tlet deleted = 0;\n\tfor (const status of [\"sent\", \"failed\", \"retrying\", \"sending\", \"queued\", \"fanned_out\", \"suppressed\", \"pending\"] satisfies StoredDeliveryStatus[]) {\n\t\tconst result = await db\n\t\t\t.prepare(\"DELETE FROM notification_deliveries WHERE status = ? AND updated_at < ?\")\n\t\t\t.bind(status, before)\n\t\t\t.run();\n\t\tdeleted += result.meta.changes;\n\t}\n\treturn deleted;\n}\n\n// ---------------------------------------------------------------------------\n// The Cron's records: `unknown` alerts and `down` events held back by maintenance\n// ---------------------------------------------------------------------------\n\nexport interface UnknownAlertRecord {\n\treadonly monitorId: string;\n\treadonly since: number;\n\treadonly reason: string;\n}\n\nexport interface SuppressedDown {\n\treadonly monitorId: string;\n\treadonly since: number;\n\treadonly event: MonitorEvent;\n}\n\n/** Both of the Cron's lists, in one round trip. Each is usually empty. */\nexport async function readCronRecords(\n\tdb: D1Database,\n): Promise<{ alerts: Map<string, UnknownAlertRecord>; suppressed: SuppressedDown[] }> {\n\tconst [alerts, suppressed] = await db.batch([\n\t\tdb.prepare(\"SELECT monitor_id, since, reason FROM unknown_alerts\"),\n\t\tdb.prepare(\"SELECT monitor_id, since, event FROM suppressed_downs\"),\n\t]);\n\treturn {\n\t\talerts: new Map(\n\t\t\t((alerts?.results ?? []) as { monitor_id: string; since: number; reason: string }[]).map((row) => [\n\t\t\t\trow.monitor_id,\n\t\t\t\t{ monitorId: row.monitor_id, since: row.since, reason: row.reason },\n\t\t\t]),\n\t\t),\n\t\tsuppressed: ((suppressed?.results ?? []) as { monitor_id: string; since: number; event: string }[]).flatMap((row) => {\n\t\t\tconst event = parseJsonColumn<MonitorEvent | null>(row.event, null, `suppressed_downs ${row.monitor_id}`);\n\t\t\treturn event === null ? [] : [{ monitorId: row.monitor_id, since: row.since, event }];\n\t\t}),\n\t};\n}\n\n/** Remembers that administrators were told `monitorId` is unknown. `false` if it already was. */\nexport async function insertUnknownAlert(db: D1Database, alert: UnknownAlertRecord, now: number): Promise<boolean> {\n\tconst result = await db\n\t\t.prepare(\"INSERT INTO unknown_alerts (monitor_id, since, reason, notified_at) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING\")\n\t\t.bind(alert.monitorId, alert.since, alert.reason, now)\n\t\t.run();\n\treturn result.meta.changes > 0;\n}\n\nexport async function deleteUnknownAlerts(db: D1Database, monitorIds: readonly string[]): Promise<void> {\n\tif (monitorIds.length === 0) return;\n\tawait db.batch(monitorIds.map((id) => db.prepare(\"DELETE FROM unknown_alerts WHERE monitor_id = ?\").bind(id)));\n}\n\n/** Remembers a `down` that maintenance held back, unless a later one of the same monitor is already remembered. */\nexport async function recordSuppressedDown(db: D1Database, event: MonitorEvent, now: number): Promise<void> {\n\tawait db\n\t\t.prepare(\n\t\t\t`INSERT INTO suppressed_downs (monitor_id, since, event, suppressed_at) VALUES (?, ?, ?, ?)\n\t\t\tON CONFLICT (monitor_id) DO UPDATE SET since = excluded.since, event = excluded.event, suppressed_at = excluded.suppressed_at\n\t\t\tWHERE excluded.since > suppressed_downs.since`,\n\t\t)\n\t\t.bind(event.monitorId, event.since, JSON.stringify(event), now)\n\t\t.run();\n}\n\n/** Forgets a held-back `down` (it was notified, or no longer matters), unless a later one replaced it. */\nexport async function deleteSuppressedDown(db: D1Database, monitorId: string, since: number): Promise<void> {\n\tawait db.prepare(\"DELETE FROM suppressed_downs WHERE monitor_id = ? AND since = ?\").bind(monitorId, since).run();\n}\n\n// ---------------------------------------------------------------------------\n// Maintenance, for suppression\n// ---------------------------------------------------------------------------\n\n/** Most maintenance windows read per page and moment. */\nconst MAX_WINDOWS = 200;\n\n/**\n * The maintenance of `pageIds` that covers `at`. Walks `maintenances_by_page_end`: per page,\n * the maintenance ending after `at`.\n */\nexport async function maintenanceAt(db: D1Database, pageIds: readonly string[], at: number): Promise<MaintenanceWindow[]> {\n\tif (pageIds.length === 0) return [];\n\tconst results = await db.batch(\n\t\tpageIds.map((pageId) =>\n\t\t\tdb\n\t\t\t\t.prepare(\n\t\t\t\t\t\"SELECT page_id, components, starts_at, ends_at FROM maintenances WHERE page_id = ? AND ends_at > ? AND starts_at <= ? LIMIT ?\",\n\t\t\t\t)\n\t\t\t\t.bind(pageId, at, at, MAX_WINDOWS),\n\t\t),\n\t);\n\treturn results.flatMap((result) =>\n\t\t((result.results ?? []) as { page_id: string; components: string; starts_at: number; ends_at: number }[]).map((row) => ({\n\t\t\tpageId: row.page_id,\n\t\t\tcomponents: parseJsonColumn<string[]>(row.components, [], `maintenance of page ${row.page_id}`),\n\t\t\tstartsAt: row.starts_at,\n\t\t\tendsAt: row.ends_at,\n\t\t})),\n\t);\n}\n","/**\n * English: the reference translation. Every message is defined here; other languages may\n * leave messages out, which then show in English. `{name}` is replaced with a value.\n */\nexport default {\n\t\"state.up\": \"up\",\n\t\"state.degraded\": \"degraded\",\n\t\"state.down\": \"down\",\n\t\"state.unknown\": \"unknown\",\n\n\t\"notification.down.title\": \"{monitor} is down\",\n\t\"notification.down.text\": \"{monitor} has been down since {time}.\",\n\t\"notification.down.afterMaintenance\": \"Maintenance has ended and {monitor} is still down. It has been down since {time}.\",\n\t\"notification.recovered.title\": \"{monitor} has recovered\",\n\t\"notification.recovered.text\": \"{monitor} is {state} again since {time}, after being down for {duration}.\",\n\t\"notification.recovered.partial.title\": \"{monitor} has partially recovered\",\n\t\"notification.recovered.partial.text\": \"{monitor} is no longer down but degraded since {time}, after being down for {duration}.\",\n\t\"notification.degraded.title\": \"{monitor} is degraded\",\n\t\"notification.degraded.text\": \"{monitor} has been degraded since {time}.\",\n\t\"notification.degraded_recovered.title\": \"{monitor} is no longer degraded\",\n\t\"notification.degraded_recovered.text\": \"{monitor} is up again since {time}, after being degraded for {duration}.\",\n\t\"notification.unknown.title\": \"{monitor}: no recent results\",\n\t\"notification.unknown.late\":\n\t\t\"No check of {monitor} has produced a result since {last}, so its state is unknown since {time}. Check that monitoring is running: the Worker's logs, and Cloudflare's daily limits on the Free plan.\",\n\t\"notification.unknown.unconfirmed\":\n\t\t\"{monitor} has produced results since {last}, but none confirmed a state, so its state is unknown since {time}. Its checks may alternate between success and failure.\",\n\t\"notification.unknown.unreachable\":\n\t\t\"The state of {monitor} cannot be read since {time}: its Durable Object does not answer. Check the Worker's logs.\",\n\t\"notification.lastCheck\": \"Last check: {message}\",\n\t\"notification.test.title\": \"Test notification from cf-workers-status-page\",\n\t\"notification.test.text\": 'The notification target \"{target}\" works. Sent at {time}.',\n\t\"notification.link.createIncident\": \"Create an incident on page {page}\",\n\n\t\"incident.auto.title\": \"{components}: service disruption\",\n\t\"incident.auto.investigating\": \"Monitoring detected that {components} is down since {time}. We are investigating.\",\n\t\"incident.auto.update\": \"Monitoring detected that {components} is also down since {time}.\",\n\t\"incident.auto.stopped\": \"Monitoring of {components} stopped at {time}, so this incident was resolved automatically.\",\n\t\"incident.auto.resolved\": \"{components} recovered at {time}. This incident was resolved automatically.\",\n\t\"incident.auto.reopened\": \"Monitoring detected that {components} is down again since {time}, so this incident was reopened.\",\n\t\"incident.auto.partial\": \"{components} is no longer down since {time}, but still degraded.\",\n\n\t// -------------------------------------------------------------------------------------\n\t// The status page and the admin UI (src/). The language is the browser's.\n\t// -------------------------------------------------------------------------------------\n\n\t\"ui.language\": \"Language\",\n\t\"ui.loading\": \"Loading…\",\n\t\"ui.skipToContent\": \"Skip to content\",\n\n\t\"stage.investigating\": \"Investigating\",\n\t\"stage.identified\": \"Identified\",\n\t\"stage.monitoring\": \"Monitoring\",\n\t\"stage.resolved\": \"Resolved\",\n\n\t\"impact.none\": \"No impact\",\n\t\"impact.degraded\": \"Degraded performance\",\n\t\"impact.down\": \"Outage\",\n\n\t\"public.defaultTitle\": \"Status\",\n\t\"public.header.website\": \"opens the website\",\n\t\"public.footer.timeZone\": \"Times are shown in your time zone ({timeZone}).\",\n\n\t\"public.state.up\": \"Operational\",\n\t\"public.state.degraded\": \"Degraded\",\n\t\"public.state.down\": \"Down\",\n\t\"public.state.unknown\": \"Unknown\",\n\n\t\"public.overall.up\": \"All systems operational\",\n\t\"public.overall.degraded\": \"Some systems are degraded\",\n\t\"public.overall.down\": \"Some systems are down\",\n\t\"public.overall.unknown\": \"Status unknown\",\n\t\"public.overall.unknownDetail\": \"Recent monitoring results are missing for some systems.\",\n\t\"public.overall.empty\": \"No systems are listed on this page yet\",\n\t\"public.overall.maintenance\": \"Maintenance is in progress.\",\n\t\"public.overall.stale\": \"This status may be out of date\",\n\t\"public.overall.staleDetail\": \"The page could not be refreshed. Last known: “{state}”, {time}.\",\n\n\t\"public.freshness.updated\": \"Updated {time}\",\n\t\"public.freshness.age\": \"last refreshed {age}\",\n\t\"public.freshness.failed\": \"Could not refresh ({reason}).\",\n\t\"public.freshness.retrying\": \"Trying again…\",\n\t\"public.freshness.retryAt\": \"Trying again {time}.\",\n\t\"public.freshness.retryNow\": \"Retry now\",\n\t\"public.freshness.incidentsOutdated\":\n\t\t\"Incident and maintenance information may be out of date: it could not be loaded just now. The states of the systems are current.\",\n\n\t\"public.error.network\": \"no connection to the server\",\n\t\"public.error.http\": \"server error {status}\",\n\t\"public.error.unknown\": \"unexpected error\",\n\n\t\"public.unavailable.title\": \"The status cannot be shown right now\",\n\t\"public.unavailable.detail\": \"Loading the status failed ({reason}). It is not known whether systems are working.\",\n\n\t\"public.notFound.title\": \"Not found\",\n\t\"public.notFound.page\": \"There is no status page at this address.\",\n\t\"public.notFound.incident\": \"There is no such incident on this status page.\",\n\t\"public.notFound.path\": \"There is nothing at this address.\",\n\t\"public.notFound.home\": \"Go to the status page\",\n\n\t\"public.incidents.heading\": \"Current incidents\",\n\t\"public.incident.affects\": \"Affects {components}\",\n\t\"public.incident.started\": \"Started {time}\",\n\t\"public.incident.ongoingSince\": \"Ongoing since {time}\",\n\t\"public.incident.lasted\": \"{from}, lasted {duration}\",\n\t\"public.incident.olderUpdates\": \"Earlier updates are not shown: see the whole timeline\",\n\t\"public.incident.earlierUpdates\": \"Show earlier updates\",\n\t\"public.incident.earlierFailed\": \"Earlier updates could not be loaded ({reason}).\",\n\t\"public.incident.back\": \"Current status\",\n\n\t\"public.maintenance.activeHeading\": \"Maintenance in progress\",\n\t\"public.maintenance.upcomingHeading\": \"Scheduled maintenance\",\n\t\"public.maintenance.until\": \"In progress until {to}\",\n\t\"public.maintenance.window\": \"{from} to {to}\",\n\t\"public.maintenance.components\": \"Affects {components}\",\n\n\t\"public.components.heading\": \"Systems\",\n\t\"public.components.stale\": \"These are the last known states.\",\n\t\"public.components.historyFailed\": \"The daily history could not be loaded; trying again.\",\n\t\"public.component.maintenance\": \"Maintenance\",\n\t\"public.component.uptime\": \"{uptime} uptime over the last {period}\",\n\t\"public.component.coverage\": \"coverage {coverage}\",\n\t\"public.component.noUptime\": \"No uptime for these days: no results outside maintenance\",\n\t\"public.component.notMonitored\": \"Not monitored: its state comes from incidents only\",\n\n\t\"public.bars.label\": \"{component}: one bar per day, last {period}\",\n\t\"public.bars.today\": \"Today\",\n\n\t\"public.day.pending\": \"Still being calculated\",\n\t\"public.day.unmonitored\": \"Not monitored\",\n\t\"public.day.noData\": \"No data\",\n\t\"public.day.uptime\": \"{uptime} uptime\",\n\t\"public.day.downtime\": \"Down for {duration}\",\n\t\"public.day.degraded\": \"Degraded at times\",\n\t\"public.day.coverage\": \"Coverage {coverage}\",\n\t\"public.day.incidents\": \"Incidents: {titles}\",\n\t\"public.day.maintenance\": \"Maintenance: {titles}\",\n\n\t\"public.legend.up\": \"Operational\",\n\t\"public.legend.degraded\": \"Degraded\",\n\t\"public.legend.down\": \"Down\",\n\t\"public.legend.noData\": \"No data\",\n\t\"public.legend.incident\": \"Incident\",\n\t\"public.legend.maintenance\": \"Maintenance\",\n\t\"public.legend.uptime\":\n\t\t\"Uptime counts monitoring results only: maintenance and periods without results are left out. Coverage is the share of scheduled checks that produced a result.\",\n\n\t\"public.history.heading\": \"Past incidents\",\n\t\"public.history.none\": \"No past incidents.\",\n\t\"public.history.more\": \"Show older incidents\",\n\t\"public.history.failed\": \"Past incidents could not be loaded ({reason}).\",\n\n\t\"public.stoppages.heading\": \"Outages detected by monitoring\",\n\t\"public.stoppages.intro\": \"Periods when monitoring confirmed a system was down, whether or not an incident was published.\",\n\t\"public.stoppages.none\": \"No outages detected in the last {period}.\",\n\t\"public.stoppages.period\": \"{from}, for {duration}\",\n\t\"public.stoppages.ongoing\": \"Since {from} (ongoing, {duration} so far)\",\n\t\"public.stoppages.all\": \"Show all ({count})\",\n\t\"public.stoppages.fewer\": \"Show fewer\",\n\t\"public.stoppages.truncated\": \"Older outages in this period are not listed.\",\n\t\"public.stoppages.failed\": \"Outages could not be loaded; trying again.\",\n\t\"public.component.uptimeSince\": \"{uptime} uptime since {date}\",\n\t\"public.component.notEnoughData\": \"Not enough data yet for uptime ({duration} of results)\",\n\t\"public.component.notMonitoredYet\": \"Not monitored yet\",\n\t\"public.components.historyStale\": \"The daily history could not be refreshed ({reason}); it is as of {time}.\",\n\t\"public.day.notYet\": \"Not monitored yet\",\n\t\"public.legend.notMonitored\": \"Not monitored (yet)\",\n\t// The \"modern\" template (pages[].template in status.config.ts).\n\t\"public.modern.report\": \"Report a problem\",\n\t\"public.modern.updated\": \"Last updated {time}\",\n\t\"public.modern.theme\": \"Theme\",\n\t\"public.modern.theme.light\": \"Light\",\n\t\"public.modern.theme.dark\": \"Dark\",\n\t\"public.modern.incident.meta\": \"Started {time} · Affects {components}\",\n\t\"public.modern.incident.started\": \"Started {time}\",\n\t\"public.modern.maintenance.badge\": \"Maintenance in progress\",\n\t\"public.modern.maintenance.scheduled\": \"Scheduled maintenance\",\n\t\"public.modern.maintenance.window\": \"{from} to {to} (scheduled)\",\n\t\"public.modern.maintenance.progress\": \"{elapsed} elapsed of {total}\",\n\t\"public.modern.components.label\": \"Components and their uptime\",\n\t\"public.modern.group.count\": \"{count} components\",\n\t\"public.modern.group.one\": \"1 component\",\n\t\"public.modern.uptime\": \"{uptime} uptime\",\n\t\"public.modern.uptime.noData\": \"No data\",\n\t\"public.modern.uptime.notEnough\": \"Not enough data\",\n\t\"public.modern.uptime.notMonitored\": \"Not monitored\",\n\t\"public.modern.uptime.notYet\": \"Not monitored yet\",\n\t\"public.modern.day.noIssues\": \"No issues\",\n\t\"public.modern.day.degraded\": \"Degraded for {duration}\",\n\t\"public.modern.day.maintenance\": \"Maintenance for {duration}\",\n\t\"public.modern.day.timeline\": \"The day from 0:00 to 24:00 in {timezone}\",\n\t\"public.modern.event.incident\": \"Incident\",\n\t\"public.modern.event.maintenance\": \"Maintenance\",\n\t\"public.modern.event.stoppage\": \"Down (detected by monitoring)\",\n\t\"public.modern.legend.maintenance\": \"Maintenance\",\n\t\"public.modern.latency.toggle\": \"Response times of {component}\",\n\t\"public.modern.latency.value\": \"{ms} ms\",\n\t\"public.modern.latency.latest\": \"Latest\",\n\t\"public.modern.latency.average\": \"Average\",\n\t\"public.modern.latency.p95\": \"95th percentile\",\n\t\"public.modern.latency.period\": \"Period\",\n\t\"public.modern.latency.day\": \"24 hours\",\n\t\"public.modern.latency.week\": \"7 days\",\n\t\"public.modern.latency.month\": \"30 days\",\n\t\"public.modern.latency.now\": \"Now\",\n\t\"public.modern.latency.chart\": \"Response time of {component} over {period}: average {average}, 95th percentile {p95}\",\n\t\"public.modern.latency.none\": \"No response times in this period yet.\",\n\t\"public.modern.latency.loading\": \"Loading response times…\",\n\t\"public.modern.latency.failed\": \"Response times could not be loaded ({reason}).\",\n\t\"public.modern.notices.heading\": \"Recent incidents (past 7 days)\",\n\t\"public.modern.notices.none\": \"No incidents in the past 7 days.\",\n\t\"public.modern.notices.history\": \"History\",\n\t\"public.modern.notices.all\": \"View all past incidents\",\n\t\"public.modern.notices.resolved\": \"Resolved\",\n\t\"public.modern.notices.period\": \"{from} to {to}\",\n\t\"public.modern.notices.show\": \"Show updates\",\n\t\"public.modern.notices.hide\": \"Hide updates\",\n\t\"public.modern.history.title\": \"Incident history\",\n} as const;\n","import type { Translation } from \"../index\";\n\n/** Japanese. */\nexport default {\n\t\"state.up\": \"正常\",\n\t\"state.degraded\": \"性能低下\",\n\t\"state.down\": \"停止\",\n\t\"state.unknown\": \"不明\",\n\n\t\"notification.down.title\": \"{monitor} が停止しています\",\n\t\"notification.down.text\": \"{monitor} は {time} から停止しています。\",\n\t\"notification.down.afterMaintenance\": \"メンテナンスが終了しましたが、{monitor} は停止したままです。{time} から停止しています。\",\n\t\"notification.recovered.title\": \"{monitor} が復旧しました\",\n\t\"notification.recovered.text\": \"{monitor} は {time} に「{state}」に戻りました。停止していた時間: {duration}\",\n\t\"notification.recovered.partial.title\": \"{monitor} が一部復旧しました\",\n\t\"notification.recovered.partial.text\": \"{monitor} は {time} から停止ではなく性能低下の状態です。停止していた時間: {duration}\",\n\t\"notification.degraded.title\": \"{monitor} の性能が低下しています\",\n\t\"notification.degraded.text\": \"{monitor} は {time} から性能が低下しています。\",\n\t\"notification.degraded_recovered.title\": \"{monitor} の性能低下が解消しました\",\n\t\"notification.degraded_recovered.text\": \"{monitor} は {time} に正常に戻りました。性能が低下していた時間: {duration}\",\n\t\"notification.unknown.title\": \"{monitor}: 最近の結果がありません\",\n\t\"notification.unknown.late\":\n\t\t\"{monitor} のチェック結果が {last} から届いていないため、{time} から状態が不明です。監視が動いているか、Worker のログと、Free プランでは Cloudflare の1日あたりの上限を確認してください。\",\n\t\"notification.unknown.unconfirmed\":\n\t\t\"{monitor} は {last} から結果が届いていますが、状態を確定できていないため、{time} から状態が不明です。チェックの成功と失敗が交互に起きている可能性があります。\",\n\t\"notification.unknown.unreachable\":\n\t\t\"{time} から {monitor} の状態を読み取れません。Durable Object が応答しません。Worker のログを確認してください。\",\n\t\"notification.lastCheck\": \"最後のチェック: {message}\",\n\t\"notification.test.title\": \"cf-workers-status-page からのテスト通知\",\n\t\"notification.test.text\": \"通知先「{target}」に送信できました。送信時刻: {time}\",\n\t\"notification.link.createIncident\": \"ページ {page} に障害告知を作成\",\n\n\t\"incident.auto.title\": \"{components} の障害\",\n\t\"incident.auto.investigating\": \"{time} から {components} が停止していることを検知しました。調査しています。\",\n\t\"incident.auto.update\": \"{time} から {components} も停止していることを検知しました。\",\n\t\"incident.auto.stopped\": \"{time} に {components} の監視が止まったため、この告知は自動で解決されました。\",\n\t\"incident.auto.resolved\": \"{time} に {components} が復旧しました。この告知は自動で解決されました。\",\n\t\"incident.auto.reopened\": \"{time} から {components} が再び停止していることを検知したため、この告知を再開しました。\",\n\t\"incident.auto.partial\": \"{time} から {components} の停止は解消しましたが、性能低下が続いています。\",\n\n\t// -------------------------------------------------------------------------------------\n\t// ステータスページと管理画面(src/)。言語はブラウザの設定で選ぶ。\n\t// -------------------------------------------------------------------------------------\n\n\t\"ui.language\": \"言語\",\n\t\"ui.loading\": \"読み込み中…\",\n\t\"ui.skipToContent\": \"本文へ移動\",\n\n\t\"stage.investigating\": \"調査中\",\n\t\"stage.identified\": \"原因特定\",\n\t\"stage.monitoring\": \"経過観察\",\n\t\"stage.resolved\": \"解決\",\n\n\t\"impact.none\": \"影響なし\",\n\t\"impact.degraded\": \"性能低下\",\n\t\"impact.down\": \"停止\",\n\n\t\"public.defaultTitle\": \"ステータス\",\n\t\"public.header.website\": \"Web サイトを開く\",\n\t\"public.footer.timeZone\": \"時刻はお使いのタイムゾーン({timeZone})で表示しています。\",\n\n\t\"public.state.up\": \"正常\",\n\t\"public.state.degraded\": \"性能低下\",\n\t\"public.state.down\": \"停止\",\n\t\"public.state.unknown\": \"不明\",\n\n\t\"public.overall.up\": \"すべてのシステムが正常に稼働しています\",\n\t\"public.overall.degraded\": \"一部のシステムで性能が低下しています\",\n\t\"public.overall.down\": \"一部のシステムが停止しています\",\n\t\"public.overall.unknown\": \"状態が不明です\",\n\t\"public.overall.unknownDetail\": \"一部のシステムで最近の監視結果が得られていません。\",\n\t\"public.overall.empty\": \"このページにはまだシステムが登録されていません\",\n\t\"public.overall.maintenance\": \"メンテナンスを実施しています。\",\n\t\"public.overall.stale\": \"この表示は最新ではない可能性があります\",\n\t\"public.overall.staleDetail\": \"ページを更新できませんでした。最後に確認できた状態:「{state}」({time})\",\n\n\t\"public.freshness.updated\": \"{time} 更新\",\n\t\"public.freshness.age\": \"最終更新 {age}\",\n\t\"public.freshness.failed\": \"更新できませんでした({reason})。\",\n\t\"public.freshness.retrying\": \"再試行しています…\",\n\t\"public.freshness.retryAt\": \"{time}に再試行します。\",\n\t\"public.freshness.retryNow\": \"今すぐ再試行\",\n\t\"public.freshness.incidentsOutdated\": \"障害告知とメンテナンスの情報を今は読み込めないため、古い可能性があります。各システムの状態は最新です。\",\n\n\t\"public.error.network\": \"サーバーに接続できません\",\n\t\"public.error.http\": \"サーバーエラー {status}\",\n\t\"public.error.unknown\": \"予期しないエラー\",\n\n\t\"public.unavailable.title\": \"現在、状態を表示できません\",\n\t\"public.unavailable.detail\": \"状態を読み込めませんでした({reason})。システムが稼働しているかどうかは分かりません。\",\n\n\t\"public.notFound.title\": \"見つかりません\",\n\t\"public.notFound.page\": \"このアドレスにステータスページはありません。\",\n\t\"public.notFound.incident\": \"このステータスページにその障害告知はありません。\",\n\t\"public.notFound.path\": \"このアドレスには何もありません。\",\n\t\"public.notFound.home\": \"ステータスページへ\",\n\n\t\"public.incidents.heading\": \"発生中の障害\",\n\t\"public.incident.affects\": \"影響: {components}\",\n\t\"public.incident.started\": \"{time} 発生\",\n\t\"public.incident.ongoingSince\": \"{time} から継続中\",\n\t\"public.incident.lasted\": \"{from} から {duration}\",\n\t\"public.incident.olderUpdates\": \"以前の更新は省略しています。すべての経過を見る\",\n\t\"public.incident.earlierUpdates\": \"以前の更新を表示\",\n\t\"public.incident.earlierFailed\": \"以前の更新を読み込めませんでした({reason})。\",\n\t\"public.incident.back\": \"現在の状態\",\n\n\t\"public.maintenance.activeHeading\": \"実施中のメンテナンス\",\n\t\"public.maintenance.upcomingHeading\": \"予定されているメンテナンス\",\n\t\"public.maintenance.until\": \"{to} まで実施中\",\n\t\"public.maintenance.window\": \"{from} 〜 {to}\",\n\t\"public.maintenance.components\": \"対象: {components}\",\n\n\t\"public.components.heading\": \"システム\",\n\t\"public.components.stale\": \"最後に確認できた状態を表示しています。\",\n\t\"public.components.historyFailed\": \"日ごとの履歴を読み込めませんでした。再試行しています。\",\n\t\"public.component.maintenance\": \"メンテナンス中\",\n\t\"public.component.uptime\": \"過去 {period}の稼働率 {uptime}\",\n\t\"public.component.coverage\": \"網羅率 {coverage}\",\n\t\"public.component.noUptime\": \"この期間の稼働率なし: メンテナンス以外の時間に結果がありません\",\n\t\"public.component.notMonitored\": \"監視なし: 状態は障害告知だけで決まります\",\n\n\t\"public.bars.label\": \"{component}: 過去 {period}、1日1本\",\n\t\"public.bars.today\": \"今日\",\n\n\t\"public.day.pending\": \"計算中\",\n\t\"public.day.unmonitored\": \"監視なし\",\n\t\"public.day.noData\": \"データなし\",\n\t\"public.day.uptime\": \"稼働率 {uptime}\",\n\t\"public.day.downtime\": \"停止 {duration}\",\n\t\"public.day.degraded\": \"一時的に性能低下\",\n\t\"public.day.coverage\": \"網羅率 {coverage}\",\n\t\"public.day.incidents\": \"障害告知: {titles}\",\n\t\"public.day.maintenance\": \"メンテナンス: {titles}\",\n\n\t\"public.legend.up\": \"正常\",\n\t\"public.legend.degraded\": \"性能低下\",\n\t\"public.legend.down\": \"停止\",\n\t\"public.legend.noData\": \"データなし\",\n\t\"public.legend.incident\": \"障害告知\",\n\t\"public.legend.maintenance\": \"メンテナンス\",\n\t\"public.legend.uptime\":\n\t\t\"稼働率は監視結果だけから計算し、メンテナンス中と結果のない時間は除きます。網羅率は、予定したチェックのうち結果が得られた割合です。\",\n\n\t\"public.history.heading\": \"過去の障害\",\n\t\"public.history.none\": \"過去の障害はありません。\",\n\t\"public.history.more\": \"さらに表示\",\n\t\"public.history.failed\": \"過去の障害を読み込めませんでした({reason})。\",\n\n\t\"public.stoppages.heading\": \"監視で検知した停止\",\n\t\"public.stoppages.intro\": \"障害告知の有無にかかわらず、監視で停止が確定した期間です。\",\n\t\"public.stoppages.none\": \"過去 {period}に検知した停止はありません。\",\n\t\"public.stoppages.period\": \"{from} から {duration}\",\n\t\"public.stoppages.ongoing\": \"{from} から継続中(現在 {duration})\",\n\t\"public.stoppages.all\": \"すべて表示({count} 件)\",\n\t\"public.stoppages.fewer\": \"折りたたむ\",\n\t\"public.stoppages.truncated\": \"この期間のより古い停止は表示していません。\",\n\t\"public.stoppages.failed\": \"停止の履歴を読み込めませんでした。再試行しています。\",\n\t\"public.component.uptimeSince\": \"{date} からの稼働率 {uptime}\",\n\t\"public.component.notEnoughData\": \"稼働率を出すにはデータが足りません(結果 {duration})\",\n\t\"public.component.notMonitoredYet\": \"まだ監視していません\",\n\t\"public.components.historyStale\": \"日ごとの履歴を更新できませんでした({reason})。{time} 時点の内容です。\",\n\t\"public.day.notYet\": \"まだ監視していません\",\n\t\"public.legend.notMonitored\": \"監視なし(または監視前)\",\n\t// モダンテンプレート(status.config.ts の pages[].template)。\n\t\"public.modern.report\": \"問題を報告\",\n\t\"public.modern.updated\": \"最終更新 {time}\",\n\t\"public.modern.theme\": \"表示テーマ\",\n\t\"public.modern.theme.light\": \"ライト\",\n\t\"public.modern.theme.dark\": \"ダーク\",\n\t\"public.modern.incident.meta\": \"{time} に発生 · 影響: {components}\",\n\t\"public.modern.incident.started\": \"{time} に発生\",\n\t\"public.modern.maintenance.badge\": \"メンテナンス中\",\n\t\"public.modern.maintenance.scheduled\": \"予定メンテナンス\",\n\t\"public.modern.maintenance.window\": \"{from} 〜 {to}(予定)\",\n\t\"public.modern.maintenance.progress\": \"{elapsed}経過 / 予定 {total}\",\n\t\"public.modern.components.label\": \"コンポーネントの稼働状況\",\n\t\"public.modern.group.count\": \"{count} コンポーネント\",\n\t\"public.modern.group.one\": \"1 コンポーネント\",\n\t\"public.modern.uptime\": \"{uptime} 稼働\",\n\t\"public.modern.uptime.noData\": \"データなし\",\n\t\"public.modern.uptime.notEnough\": \"データ不足\",\n\t\"public.modern.uptime.notMonitored\": \"監視なし\",\n\t\"public.modern.uptime.notYet\": \"監視前\",\n\t\"public.modern.day.noIssues\": \"障害の報告なし\",\n\t\"public.modern.day.degraded\": \"性能低下 {duration}\",\n\t\"public.modern.day.maintenance\": \"メンテナンス {duration}\",\n\t\"public.modern.day.timeline\": \"{timezone} の0時から24時まで\",\n\t\"public.modern.event.incident\": \"障害告知\",\n\t\"public.modern.event.maintenance\": \"メンテナンス\",\n\t\"public.modern.event.stoppage\": \"停止(監視で検知)\",\n\t\"public.modern.legend.maintenance\": \"メンテナンス\",\n\t\"public.modern.latency.toggle\": \"{component} の応答時間\",\n\t\"public.modern.latency.value\": \"{ms} ms\",\n\t\"public.modern.latency.latest\": \"現在\",\n\t\"public.modern.latency.average\": \"平均\",\n\t\"public.modern.latency.p95\": \"95パーセンタイル\",\n\t\"public.modern.latency.period\": \"表示期間\",\n\t\"public.modern.latency.day\": \"24時間\",\n\t\"public.modern.latency.week\": \"7日間\",\n\t\"public.modern.latency.month\": \"30日間\",\n\t\"public.modern.latency.now\": \"現在\",\n\t\"public.modern.latency.chart\": \"{component} の応答時間({period})。平均 {average}、95パーセンタイル {p95}\",\n\t\"public.modern.latency.none\": \"この期間の応答時間はまだありません。\",\n\t\"public.modern.latency.loading\": \"応答時間を読み込み中…\",\n\t\"public.modern.latency.failed\": \"応答時間を読み込めませんでした({reason})。\",\n\t\"public.modern.notices.heading\": \"最近のお知らせ(過去7日間)\",\n\t\"public.modern.notices.none\": \"過去7日間のお知らせはありません。\",\n\t\"public.modern.notices.history\": \"履歴を見る\",\n\t\"public.modern.notices.all\": \"お知らせの履歴をすべて表示\",\n\t\"public.modern.notices.resolved\": \"解決済み\",\n\t\"public.modern.notices.period\": \"{from} 〜 {to}\",\n\t\"public.modern.notices.show\": \"これまでの経過\",\n\t\"public.modern.notices.hide\": \"経過を閉じる\",\n\t\"public.modern.history.title\": \"お知らせの履歴\",\n} satisfies Translation;\n","/**\n * The translation mechanism without the translations: matching a requested\n * language to the bundled ones, interpolation, and formatting. `index.ts` loads every\n * translation at once, for the Worker; the React app loads only the visitor's language\n * (src/i18n/catalog.ts). Both find the files with Vite's `import.meta.glob`.\n */\nimport type adminEn from \"./admin/en\";\nimport type en from \"./locales/en\";\n\n/** The messages, keyed by identifier, in the reference language (English). */\nexport type Messages = typeof en;\nexport type MessageKey = keyof Messages;\n/** A language's messages: any of them; missing ones fall back to English. */\nexport type Translation = Partial<Record<MessageKey, string>>;\n\n/**\n * The admin UI's own messages (`admin/<tag>.ts`), apart from the status page's so that visitors\n * never download them. The admin UI uses both sets.\n */\nexport type AdminMessages = typeof adminEn;\nexport type AdminMessageKey = keyof AdminMessages;\nexport type AdminTranslation = Partial<Record<AdminMessageKey, string>>;\n\nexport const DEFAULT_LOCALE = \"en\";\n\n/** The canonical form of a BCP 47 tag (`pt-br` → `pt-BR`), or `undefined` when it is not one. */\nexport function canonicalLocale(tag: string): string | undefined {\n\ttry {\n\t\treturn Intl.getCanonicalLocales(tag)[0];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** The language of a translation file, from its name (`./locales/pt-BR.ts` → `pt-BR`). */\nexport function localeOfFile(path: string): string | undefined {\n\tconst tag = /\\/([^/]+)\\.ts$/.exec(path)?.[1];\n\treturn tag === undefined ? undefined : canonicalLocale(tag);\n}\n\n/**\n * The language of `available` that best matches `requested` (a tag, or a list in order of\n * preference such as `navigator.languages`): an exact match, else the same language without\n * region or script (`ja-JP` → `ja`), else a regional variant of it (`pt` → `pt-BR`), else\n * English.\n */\nexport function matchLocale(requested: string | readonly string[] | null | undefined, available: readonly string[]): string {\n\tconst tags = requested === null || requested === undefined ? [] : typeof requested === \"string\" ? [requested] : requested;\n\tconst sorted = [...available].sort();\n\tconst byLowerCase = new Map(sorted.map((tag) => [tag.toLowerCase(), tag]));\n\tfor (const tag of tags) {\n\t\tconst wanted = canonicalLocale(tag)?.toLowerCase();\n\t\tif (wanted === undefined) continue;\n\t\tconst exact = byLowerCase.get(wanted);\n\t\tif (exact !== undefined) return exact;\n\t\tconst language = wanted.split(\"-\")[0] as string;\n\t\tconst base = byLowerCase.get(language);\n\t\tif (base !== undefined) return base;\n\t\tconst variant = sorted.find((candidate) => candidate.toLowerCase().startsWith(`${language}-`));\n\t\tif (variant !== undefined) return variant;\n\t}\n\treturn DEFAULT_LOCALE;\n}\n\nexport type MessageParams = Readonly<Record<string, string | number>>;\n\n/** Replaces each `{name}` with `params[name]`; placeholders without a value are left as they are. */\nexport function interpolate(template: string, params: MessageParams = {}): string {\n\treturn template.replace(/\\{([^{}]+)\\}/g, (placeholder, name: string) =>\n\t\tObject.hasOwn(params, name) ? String(params[name]) : placeholder,\n\t);\n}\n\n/** Placeholder names in a message, in order of appearance, without duplicates. */\nexport function placeholders(template: string): string[] {\n\treturn [...new Set([...template.matchAll(/\\{([^{}]+)\\}/g)].map((match) => match[1] as string))];\n}\n\nexport type Translate<K extends string = MessageKey> = (key: K, params?: MessageParams) => string;\n\nconst reported = new Set<string>();\n\n/**\n * Messages from `messages`, falling back to `reference` (English) message by message. A key that\n * no message has (a state or stage newer than this code, sent by a newer API) shows as the key\n * itself, and is logged once, rather than failing the page.\n */\nexport function makeTranslator<K extends string>(\n\tmessages: Partial<Record<K, string>>,\n\treference: Readonly<Record<K, string>>,\n): Translate<K> {\n\treturn (key, params) => {\n\t\tconst template = messages[key] ?? reference[key];\n\t\tif (typeof template === \"string\") return interpolate(template, params);\n\t\tif (!reported.has(key)) {\n\t\t\treported.add(key);\n\t\t\tconsole.warn(`No message \"${key}\"`);\n\t\t}\n\t\treturn key;\n\t};\n}\n\n/** A duration in at most two units, such as \"1 hour, 5 minutes\" or \"45 seconds\", in the language `tag`. */\nexport function durationText(ms: number, tag: string): string {\n\tconst seconds = Math.max(0, Math.round(ms / 1_000));\n\tconst units: [Intl.NumberFormatOptions[\"unit\"] & string, number][] = [\n\t\t[\"day\", Math.floor(seconds / 86_400)],\n\t\t[\"hour\", Math.floor((seconds % 86_400) / 3_600)],\n\t\t[\"minute\", Math.floor((seconds % 3_600) / 60)],\n\t\t[\"second\", seconds % 60],\n\t];\n\tconst first = units.findIndex(([, value]) => value > 0);\n\tif (first === -1) return new Intl.NumberFormat(tag, { style: \"unit\", unit: \"second\", unitDisplay: \"long\" }).format(0);\n\tconst parts = units\n\t\t.slice(first, first + 2)\n\t\t.filter(([, value]) => value > 0)\n\t\t.map(([unit, value]) => new Intl.NumberFormat(tag, { style: \"unit\", unit, unitDisplay: \"long\" }).format(value));\n\treturn new Intl.ListFormat(tag, { style: \"long\", type: \"unit\" }).format(parts);\n}\n","/**\n * Translations, shared by the Worker (notifications and automatic incidents,\n * in the `locale` of status.config.ts) and the React app (the browser's language).\n *\n * ## Adding a language\n *\n * Copy `locales/en.ts` to `locales/<tag>.ts` (notifications and the status page) and\n * `admin/en.ts` to `admin/<tag>.ts` (the admin UI), where `<tag>` is a BCP 47 language tag such\n * as `fr` or `pt-BR`, and translate the messages; type them `satisfies Translation` and\n * `satisfies AdminTranslation`. Nothing else needs to change: the files are found when the app\n * is built (Vite's `import.meta.glob`). Messages left out show in English, so a partial\n * translation works, but the tests ask for every message (and every `{name}` placeholder of the\n * English message) in the bundled languages.\n *\n * This module loads every language of `locales/` at once, for the Worker (the admin UI's\n * messages are not part of it). The status page loads only the language it shows, the admin UI\n * that language's two files (src/i18n/catalog.ts, src/admin/messages.ts); all use `core.ts`.\n */\nimport { durationText, localeOfFile, makeTranslator, matchLocale, type Translate, type Translation } from \"./core\";\nimport en from \"./locales/en\";\n\nexport {\n\tDEFAULT_LOCALE,\n\tinterpolate,\n\ttype MessageKey,\n\ttype MessageParams,\n\ttype Messages,\n\tplaceholders,\n\ttype Translate,\n\ttype Translation,\n} from \"./core\";\n\nconst files = import.meta.glob<Translation>(\"./locales/*.ts\", { eager: true, import: \"default\" });\n\n/** Every bundled language, by its canonical tag (from the file name). */\nexport const TRANSLATIONS: ReadonlyMap<string, Translation> = new Map(\n\tObject.entries(files).flatMap(([path, messages]) => {\n\t\tconst tag = localeOfFile(path);\n\t\tif (tag === undefined) {\n\t\t\tconsole.warn(`Ignoring translation file ${path}: its name is not a language tag`);\n\t\t\treturn [];\n\t\t}\n\t\treturn [[tag, messages] as const];\n\t}),\n);\n\n/** Canonical tags of the bundled languages, sorted. */\nexport const LOCALES: readonly string[] = [...TRANSLATIONS.keys()].sort();\n\n/**\n * The bundled language that best matches `requested` (a tag, or a list in order of\n * preference such as `navigator.languages`): an exact match, else the same language without\n * region or script (`ja-JP` → `ja`), else a regional variant of it (`pt` → `pt-BR`), else\n * English.\n */\nexport function resolveLocale(requested: string | readonly string[] | null | undefined): string {\n\treturn matchLocale(requested, LOCALES);\n}\n\n/** Messages in `locale` (resolved with {@link resolveLocale}), falling back to English message by message. */\nexport function translator(locale: string): Translate {\n\treturn makeTranslator(TRANSLATIONS.get(resolveLocale(locale)) ?? {}, en);\n}\n\n/** A moment as people read it in `locale`, in `timeZone`, with the zone: \"Jan 1, 2100, 9:00:00 AM GMT+9\". */\nexport function formatTime(at: number, locale: string, timeZone: string): string {\n\treturn new Intl.DateTimeFormat(resolveLocale(locale), { dateStyle: \"medium\", timeStyle: \"long\", timeZone }).format(at);\n}\n\n/** A duration in at most two units, such as \"1 hour, 5 minutes\" or \"45 seconds\". */\nexport function formatDuration(ms: number, locale: string): string {\n\treturn durationText(ms, resolveLocale(locale));\n}\n","/**\n * Writes of what a public page shows, made by automation (automatic incidents), go\n * through {@link writePublicPageContent}: one place that runs what must happen before the write\n * and clears the page's cached public responses after it.\n */\nimport { announcePublicPageChange, type PurgeTarget, purgePublicPage } from \"./public-cache\";\n\n/**\n * Announces the change to the page (so nothing computed across it is cached), runs `write`,\n * then clears `target.pageId`'s cached public responses. Neither step ever fails the write:\n * what could not be cleared expires within 30 seconds (both functions log their failures).\n * Returns what `write` returns.\n */\nexport async function writePublicPageContent<T>(target: PurgeTarget, write: () => Promise<T>): Promise<T> {\n\tawait announcePublicPageChange(target);\n\tconst result = await write();\n\ttry {\n\t\tawait purgePublicPage(target);\n\t} catch (error) {\n\t\tconsole.warn(`Could not purge the cached public responses of page \"${target.pageId}\"`, error);\n\t}\n\treturn result;\n}\n","/**\n * Notification texts and the texts of automatic incidents, from the translations\n * in `locale`, with times in `timezone` of status.config.ts. Pure functions.\n */\nimport type {\n\tNotification,\n\tNotificationEvent,\n\tNotificationLink,\n\tNotificationSeverity,\n\tResolvedPage,\n} from \"@naosystem/cf-workers-status-page-core\";\nimport {\n\tformatDuration,\n\tformatTime,\n\tinterpolate,\n\ttype MessageKey,\n\ttype MessageParams,\n\tresolveLocale,\n\ttype Translate,\n\ttranslator,\n} from \"../../shared/i18n\";\nimport type { ComponentRef } from \"../../shared/admin-api\";\nimport type { MonitorEvent } from \"./events\";\n\nexport interface RenderContext {\n\treadonly locale: string;\n\treadonly timeZone: string;\n\treadonly monitorName: string;\n\treadonly links: readonly NotificationLink[];\n}\n\nconst SEVERITY: Readonly<Record<NotificationEvent, NotificationSeverity>> = {\n\tdown: \"critical\",\n\trecovered: \"ok\",\n\tdegraded: \"warning\",\n\tdegraded_recovered: \"ok\",\n\tunknown: \"warning\",\n};\n\n/** A monitor event that targets receive (not `stopped`). */\nexport type NotifiedEvent = MonitorEvent & { readonly event: NotificationEvent };\n\n/** The notification of `event`, in `context.locale`. Its ID is the event's. */\nexport function renderEvent(event: NotifiedEvent, context: RenderContext): Notification {\n\t// The language the texts are in: the configured one, or English without a translation.\n\tconst locale = resolveLocale(context.locale);\n\tconst t = translator(locale);\n\tconst time = (at: number) => formatTime(at, locale, context.timeZone);\n\tconst duration = (from: number | null) => formatDuration(from === null ? 0 : event.since - from, locale);\n\tconst params: MessageParams = {\n\t\tmonitor: context.monitorName,\n\t\ttime: time(event.since),\n\t\tstate: t(`state.${event.state}` as MessageKey),\n\t};\n\tconst lines: string[] = [];\n\tswitch (event.event) {\n\t\tcase \"down\":\n\t\t\tlines.push(t(event.afterMaintenance ? \"notification.down.afterMaintenance\" : \"notification.down.text\", params));\n\t\t\tbreak;\n\t\tcase \"recovered\":\n\t\t\t// To `degraded`, it is a partial recovery.\n\t\t\tlines.push(\n\t\t\t\tt(event.state === \"degraded\" ? \"notification.recovered.partial.text\" : \"notification.recovered.text\", {\n\t\t\t\t\t...params,\n\t\t\t\t\tduration: duration(event.previousSince),\n\t\t\t\t}),\n\t\t\t);\n\t\t\tbreak;\n\t\tcase \"degraded\":\n\t\t\tlines.push(t(\"notification.degraded.text\", params));\n\t\t\tbreak;\n\t\tcase \"degraded_recovered\":\n\t\t\tlines.push(t(\"notification.degraded_recovered.text\", { ...params, duration: duration(event.previousSince) }));\n\t\t\tbreak;\n\t\tcase \"unknown\": {\n\t\t\tconst reason = event.unknown?.reason ?? \"late\";\n\t\t\tconst last = time(event.unknown?.lastAt ?? event.since);\n\t\t\tlines.push(t(`notification.unknown.${reason}`, { ...params, last }));\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst title =\n\t\tevent.event === \"recovered\" && event.state === \"degraded\"\n\t\t\t? t(\"notification.recovered.partial.title\", params)\n\t\t\t: t(`notification.${event.event}.title` as MessageKey, params);\n\tif (event.message !== null && event.message !== \"\" && event.event !== \"unknown\") {\n\t\tlines.push(t(\"notification.lastCheck\", { message: event.message }));\n\t}\n\treturn {\n\t\tid: event.id,\n\t\tevent: event.event,\n\t\tseverity: event.event === \"recovered\" && event.state === \"degraded\" ? \"warning\" : SEVERITY[event.event],\n\t\ttitle,\n\t\ttext: lines.join(\"\\n\"),\n\t\toccurredAt: event.since,\n\t\tmonitor: { id: event.monitorId, name: context.monitorName },\n\t\tstate: event.state,\n\t\tpreviousState: event.previousState,\n\t\tlinks: context.links,\n\t\tlocale,\n\t};\n}\n\n/** A test notification for the target `targetName`, sent at `now`. */\nexport function renderTest(targetName: string, now: number, configured: string, timeZone: string): Notification {\n\tconst locale = resolveLocale(configured);\n\tconst t = translator(locale);\n\treturn {\n\t\tid: `test:${crypto.randomUUID()}`,\n\t\tevent: \"test\",\n\t\tseverity: \"info\",\n\t\ttitle: t(\"notification.test.title\"),\n\t\ttext: t(\"notification.test.text\", { target: targetName, time: formatTime(now, locale, timeZone) }),\n\t\toccurredAt: now,\n\t\tmonitor: null,\n\t\tstate: null,\n\t\tpreviousState: null,\n\t\tlinks: [],\n\t\tlocale,\n\t};\n}\n\n/** The components of each page that show `monitorId`. */\nexport function monitorComponents(pages: readonly ResolvedPage[], monitorId: string): ComponentRef[] {\n\treturn pages.flatMap((page) =>\n\t\tpage.components\n\t\t\t.filter((component) => component.monitors.includes(monitorId))\n\t\t\t.map((component) => ({ pageId: page.id, componentId: component.id })),\n\t);\n}\n\n/**\n * \"Create an incident\" links to the admin UI, pre-filled with the page and the components that\n * show the monitor, for each page without `incidents.auto`. None without `baseUrl`.\n */\nexport function createIncidentLinks(\n\tpages: readonly ResolvedPage[],\n\tmonitorId: string,\n\tbaseUrl: string | null,\n\tt: Translate,\n): NotificationLink[] {\n\tif (baseUrl === null) return [];\n\treturn pages.flatMap((page) => {\n\t\tif (page.incidents.auto) return [];\n\t\tconst components = page.components.filter((component) => component.monitors.includes(monitorId));\n\t\tif (components.length === 0) return [];\n\t\tconst query = new URLSearchParams({ page: page.id, components: components.map((component) => component.id).join(\",\") });\n\t\treturn [{ label: t(\"notification.link.createIncident\", { page: page.id }), url: `${baseUrl}/admin/incidents/new?${query}` }];\n\t});\n}\n\nexport interface IncidentTexts {\n\treadonly title: string;\n\treadonly investigating: string;\n\treadonly update: string;\n\treadonly resolved: string;\n\treadonly stopped: string;\n\treadonly reopened: string;\n\treadonly partial: string;\n}\n\n/**\n * The texts of an automatic incident on `page`: the page's templates from\n * status.config.ts, else the translations. `components` are the names of the components.\n */\nexport function incidentTexts(\n\tpage: Pick<ResolvedPage, \"incidents\">,\n\tvalues: { readonly components: readonly string[]; readonly monitor: string; readonly at: number },\n\tconfigured: string,\n\ttimeZone: string,\n): IncidentTexts {\n\tconst locale = resolveLocale(configured);\n\tconst t = translator(locale);\n\tconst params: MessageParams = {\n\t\tcomponents: new Intl.ListFormat(locale, { style: \"long\", type: \"conjunction\" }).format(values.components),\n\t\tmonitor: values.monitor,\n\t\ttime: formatTime(values.at, locale, timeZone),\n\t};\n\tconst { templates } = page.incidents;\n\tconst text = (key: keyof IncidentTexts) => {\n\t\tconst template = templates[key];\n\t\treturn template === undefined ? t(`incident.auto.${key}`, params) : interpolate(template, params);\n\t};\n\treturn {\n\t\ttitle: text(\"title\"),\n\t\tinvestigating: text(\"investigating\"),\n\t\tupdate: text(\"update\"),\n\t\tresolved: text(\"resolved\"),\n\t\tstopped: text(\"stopped\"),\n\t\treopened: text(\"reopened\"),\n\t\tpartial: text(\"partial\"),\n\t};\n}\n","/**\n * Automatic incidents (`incidents.auto`).\n *\n * For each page with `incidents.auto` that shows the monitor:\n * - on a confirmed `down`, an incident at stage \"investigating\" is published for the page's\n * components that show the monitor, with the page's template texts; when an unresolved\n * incident of one of those components exists (whoever wrote it), an automated update is\n * added to it instead, and the missing components are added to it; when none exists but\n * automation resolved an incident of one of those components less than `reopenWithin` before\n * the `down` began (and no administrator ever edited it), that incident is reopened with an\n * update instead, so that a flapping service does not fill the page with incidents;\n * - on a partial recovery (from `down` to `degraded`), the incident the `down` was announced\n * in gets an automated update, and if automation created it, nobody edited it and no other\n * monitor in it is still down, its components' impact goes from `down` to `degraded`;\n * - on recovery to `up` (from `down`, or from `degraded` after a partial recovery), and when\n * the monitor leaves the configuration while down or degraded (`stopped`), that incident is\n * resolved, if automation created it, no administrator has edited it, and no other monitor\n * announced in it is still down or degraded. An administrator's incident is never resolved\n * automatically.\n *\n * Queue delivery is at least once and in no particular order, so each page × monitor\n * keeps the start (`since`) of the latest state applied (`auto_incident_monitors`): an event\n * that is not newer is a duplicate, or arrived after a later one (a recovery before its\n * `down`), and is ignored. Applying an event is one D1 batch (a transaction) that first\n * claims the row with a token, conditional on the row being as it was read, and then makes\n * the incident writes, each conditional on that claim: if another consumer applied an event\n * of the same monitor meanwhile, nothing is written and the event is evaluated again.\n *\n * What other monitors' events may change at the same time is decided inside the transaction,\n * not from what was read before it: whether an unresolved incident of the components exists\n * (create one, reopen one, or add to it), which recently resolved incident may be reopened,\n * and whether another monitor announced in an incident is still down (resolve it or not). Guards also re-check what an administrator may have changed since\n * the read (an incident resolved or edited meanwhile is neither added to nor resolved).\n */\nimport type { ResolvedMonitor, ResolvedPage } from \"@naosystem/cf-workers-status-page-core\";\nimport type { AffectedComponent, IncidentStage } from \"../../shared/admin-api\";\nimport { config } from \"../config\";\nimport { parseJsonColumn } from \"../db/common\";\nimport { writePublicPageContent } from \"../public-write\";\nimport type { MonitorEvent } from \"./events\";\nimport { incidentTexts } from \"./render\";\n\n/** What is stored per page × monitor. */\nexport interface AutoState {\n\treadonly lastSince: number;\n\treadonly lastState: string;\n\treadonly incidentId: string | null;\n\treadonly claim: string;\n}\n\n/** An unresolved incident of the page, as the decision needs it. */\nexport interface OpenIncident {\n\treadonly id: string;\n\treadonly components: readonly AffectedComponent[];\n\treadonly stage: IncidentStage;\n\treadonly autoCreated: boolean;\n\treadonly humanEditedAt: number | null;\n\treadonly version: number;\n}\n\nexport type AutoDecision =\n\t/** Not newer than the latest event applied: a duplicate, or one that arrived late. */\n\t| { readonly kind: \"ignore\" }\n\t/**\n\t * A `down`: publish an incident, unless the transaction finds an unresolved one of the\n\t * components, which then gets an update. `existing` is the one the read found, and\n\t * `components` its list with the missing components added (`null` when none were missing).\n\t */\n\t| { readonly kind: \"down\"; readonly existing: OpenIncident | null; readonly components: readonly AffectedComponent[] | null }\n\t/** Resolve the incident the `down` was announced in, if the transaction finds it may. */\n\t| { readonly kind: \"resolve\"; readonly incidentId: string }\n\t/** A partial recovery: an update to the incident the `down` was announced in, which stays open. */\n\t| { readonly kind: \"partial\"; readonly incidentId: string }\n\t/** Record the new state; no incident changes. */\n\t| { readonly kind: \"record\" };\n\n/** The events automatic incidents act on. */\nexport type AutoEvent = \"down\" | \"recovered\" | \"degraded_recovered\" | \"stopped\";\n\nexport interface AutoInput {\n\treadonly event: AutoEvent;\n\t/** The monitor's state after the event (`degraded` for a partial recovery). */\n\treadonly nextState?: string;\n\treadonly since: number;\n\treadonly state: AutoState | null;\n\t/** The page's components that show the monitor. */\n\treadonly componentIds: readonly string[];\n\t/** The page's unresolved incidents, latest first. */\n\treadonly openIncidents: readonly OpenIncident[];\n}\n\n/** What to do with one event on one page (pure; see the module documentation). */\nexport function decideAutoIncident(input: AutoInput): AutoDecision {\n\tif (input.state !== null && input.since <= input.state.lastSince) return { kind: \"ignore\" };\n\tif (input.event === \"down\") {\n\t\tconst existing =\n\t\t\tinput.openIncidents.find((incident) =>\n\t\t\t\tincident.components.some((component) => input.componentIds.includes(component.id)),\n\t\t\t) ?? null;\n\t\tconst missing =\n\t\t\texisting === null\n\t\t\t\t? []\n\t\t\t\t: input.componentIds.filter((id) => !existing.components.some((component) => component.id === id));\n\t\treturn {\n\t\t\tkind: \"down\",\n\t\t\texisting,\n\t\t\tcomponents:\n\t\t\t\texisting === null || missing.length === 0\n\t\t\t\t\t? null\n\t\t\t\t\t: [...existing.components, ...missing.map((id) => ({ id, impact: \"down\" as const }))],\n\t\t};\n\t}\n\tconst attached = input.state?.incidentId ?? null;\n\tconst announced = attached !== null && (input.state?.lastState === \"down\" || input.state?.lastState === \"degraded\");\n\tif (!announced) return { kind: \"record\" };\n\tif (input.event === \"recovered\" && input.state?.lastState === \"down\" && input.nextState === \"degraded\") {\n\t\treturn { kind: \"partial\", incidentId: attached };\n\t}\n\treturn { kind: \"resolve\", incidentId: attached };\n}\n\ntype IncidentRow = {\n\tid: string;\n\tcomponents: string;\n\tstage: IncidentStage;\n\tauto_created: number;\n\thuman_edited_at: number | null;\n\tversion: number;\n};\n\n/** Most unresolved incidents considered per page (as the public page shows). */\nconst MAX_OPEN = 100;\n/** Attempts when other events of the same monitor are applied at the same time. */\nconst MAX_ATTEMPTS = 5;\n\nasync function readState(db: D1Database, pageId: string, monitorId: string) {\n\tconst [state, open] = await db.batch([\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t\"SELECT last_since, last_state, incident_id, claim FROM auto_incident_monitors WHERE page_id = ? AND monitor_id = ?\",\n\t\t\t)\n\t\t\t.bind(pageId, monitorId),\n\t\tdb\n\t\t\t.prepare(\n\t\t\t\t`SELECT id, components, stage, auto_created, human_edited_at, version FROM incidents\n\t\t\t\tWHERE page_id = ? AND resolved_at IS NULL ORDER BY started_at DESC, id DESC LIMIT ?`,\n\t\t\t)\n\t\t\t.bind(pageId, MAX_OPEN),\n\t]);\n\tconst row = (\n\t\t(state?.results ?? []) as { last_since: number; last_state: string; incident_id: string | null; claim: string }[]\n\t)[0];\n\treturn {\n\t\tstate:\n\t\t\trow === undefined\n\t\t\t\t? null\n\t\t\t\t: { lastSince: row.last_since, lastState: row.last_state, incidentId: row.incident_id, claim: row.claim },\n\t\topenIncidents: ((open?.results ?? []) as IncidentRow[]).map(\n\t\t\t(incident): OpenIncident => ({\n\t\t\t\tid: incident.id,\n\t\t\t\tcomponents: parseJsonColumn<AffectedComponent[]>(incident.components, [], `incident ${incident.id}`),\n\t\t\t\tstage: incident.stage,\n\t\t\t\tautoCreated: incident.auto_created !== 0,\n\t\t\t\thumanEditedAt: incident.human_edited_at,\n\t\t\t\tversion: incident.version,\n\t\t\t}),\n\t\t),\n\t};\n}\n\n/** Pages where `monitorId`'s latest applied state is a `down` (or the `degraded` after it) announced in an incident. */\nexport async function autoIncidentPagesOf(db: D1Database, monitorId: string): Promise<string[]> {\n\t// Scans the table (one row per page × monitor that ever had an automatic incident event).\n\tconst { results } = await db\n\t\t.prepare(\n\t\t\t\"SELECT page_id FROM auto_incident_monitors WHERE monitor_id = ? AND last_state IN ('down', 'degraded') AND incident_id IS NOT NULL\",\n\t\t)\n\t\t.bind(monitorId)\n\t\t.all<{ page_id: string }>();\n\treturn results.map((row) => row.page_id);\n}\n\n/** A recently resolved automatic incident that a `down` may reopen, as read before the transaction. */\ninterface ReopenCandidate {\n\treadonly id: string;\n\treadonly components: readonly AffectedComponent[];\n\treadonly version: number;\n}\n\n/** Whether the incident of page `?P` aliased `r` may be reopened (SQL; see the module documentation). */\nfunction reopenable(page: string, resolvedSince: string, componentsJson: string): string {\n\treturn `r.page_id = ${page} AND r.auto_created = 1 AND r.human_edited_at IS NULL AND r.resolved_at IS NOT NULL\n\t\tAND r.resolved_at >= ${resolvedSince} AND EXISTS (\n\t\t\tSELECT 1 FROM json_each(r.components) AS c WHERE json_extract(c.value, '$.id') IN (SELECT value FROM json_each(${componentsJson}))\n\t\t)`;\n}\n\n/** The incident the transaction would reopen, if nothing changes meanwhile (for adding missing components). */\nasync function readReopenCandidate(\n\tdb: D1Database,\n\tpageId: string,\n\tcomponentIds: readonly string[],\n\tresolvedSince: number,\n): Promise<ReopenCandidate | null> {\n\tconst row = await db\n\t\t.prepare(\n\t\t\t`SELECT r.id, r.components, r.version FROM incidents AS r WHERE ${reopenable(\"?1\", \"?2\", \"?3\")}\n\t\t\tORDER BY r.resolved_at DESC, r.id DESC LIMIT 1`,\n\t\t)\n\t\t.bind(pageId, resolvedSince, JSON.stringify(componentIds))\n\t\t.first<{ id: string; components: string; version: number }>();\n\treturn row === null\n\t\t? null\n\t\t: { id: row.id, components: parseJsonColumn<AffectedComponent[]>(row.components, [], `incident ${row.id}`), version: row.version };\n}\n\nexport interface AutoContext {\n\treadonly env: Env;\n\treadonly ctx: ExecutionContext;\n\treadonly now: number;\n}\n\n/** What {@link applyAutoIncident} did on a page. */\nexport type AutoOutcome = \"ignore\" | \"create\" | \"append\" | \"reopen\" | \"partial\" | \"resolve\" | \"record\";\n\n/**\n * Applies a `down`, `recovered` or `stopped` event to `page`, which has `incidents.auto` and\n * shows the monitor (or showed it, for `stopped`). Idempotent: applying the same event again,\n * or an older one, changes nothing.\n */\nexport async function applyAutoIncident(\n\tcontext: AutoContext,\n\tpage: ResolvedPage,\n\tmonitor: Pick<ResolvedMonitor, \"id\" | \"name\">,\n\tevent: MonitorEvent & { readonly event: AutoEvent },\n): Promise<AutoOutcome> {\n\tconst db = context.env.DB;\n\tconst componentIds = page.components.filter((component) => component.monitors.includes(monitor.id)).map((component) => component.id);\n\tfor (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n\t\tconst { state, openIncidents } = await readState(db, page.id, monitor.id);\n\t\tconst decision = decideAutoIncident({\n\t\t\tevent: event.event,\n\t\t\tnextState: event.state,\n\t\t\tsince: event.since,\n\t\t\tstate,\n\t\t\tcomponentIds,\n\t\t\topenIncidents,\n\t\t});\n\t\tif (decision.kind === \"ignore\") return \"ignore\";\n\n\t\tconst reopenWithinMs = page.incidents.reopenWithinMs;\n\t\tconst candidate =\n\t\t\tdecision.kind === \"down\" && decision.existing === null && reopenWithinMs > 0\n\t\t\t\t? await readReopenCandidate(db, page.id, componentIds, event.since - reopenWithinMs)\n\t\t\t\t: null;\n\t\tconst plan = buildStatements(db, context.now, page, monitor, event, state, decision, componentIds, openIncidents, candidate);\n\t\tconst run = () => db.batch(plan.statements);\n\t\tconst results =\n\t\t\tdecision.kind === \"record\"\n\t\t\t\t? await run()\n\t\t\t\t: await writePublicPageContent({ env: context.env, ctx: context.ctx, pageId: page.id }, run);\n\t\tif ((results[0]?.meta.changes ?? 0) === 0) continue; // Another event of this monitor came first: again.\n\t\tconst outcome = plan.outcome(results);\n\t\tif (outcome !== \"record\") {\n\t\t\tconsole.log(`Automatic incident on page \"${page.id}\" for monitor \"${monitor.id}\": ${outcome} (event ${event.id})`);\n\t\t}\n\t\treturn outcome;\n\t}\n\tthrow new Error(`Could not apply event ${event.id} to page \"${page.id}\": too many concurrent changes`);\n}\n\n/** Whether an unresolved incident of page `?P` affects one of the components in the JSON array `?C` (SQL, on alias `i`). */\nfunction openOfComponents(page: string, componentsJson: string): string {\n\treturn `i.page_id = ${page} AND i.resolved_at IS NULL AND EXISTS (\n\t\tSELECT 1 FROM json_each(i.components) AS c WHERE json_extract(c.value, '$.id') IN (SELECT value FROM json_each(${componentsJson}))\n\t)`;\n}\n\ninterface Plan {\n\treadonly statements: D1PreparedStatement[];\n\t/** What the batch did, from its results (the claim succeeded). */\n\toutcome(results: readonly D1Result[]): AutoOutcome;\n}\n\nfunction buildStatements(\n\tdb: D1Database,\n\tnow: number,\n\tpage: ResolvedPage,\n\tmonitor: Pick<ResolvedMonitor, \"id\" | \"name\">,\n\tevent: MonitorEvent,\n\tstate: AutoState | null,\n\tdecision: Exclude<AutoDecision, { kind: \"ignore\" }>,\n\tcomponentIds: readonly string[],\n\topenIncidents: readonly OpenIncident[],\n\tcandidate: ReopenCandidate | null,\n): Plan {\n\tconst token = crypto.randomUUID();\n\tconst lastState = event.event === \"stopped\" ? \"stopped\" : event.state;\n\t// After a partial recovery the monitor stays announced in its incident (it is degraded).\n\tconst keptIncident = decision.kind === \"partial\" ? decision.incidentId : null;\n\t// The claim: first, so that every other statement can depend on it.\n\tconst claim =\n\t\tstate === null\n\t\t\t? db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`INSERT INTO auto_incident_monitors (page_id, monitor_id, last_since, last_state, incident_id, claim, updated_at)\n\t\t\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(page.id, monitor.id, event.since, lastState, keptIncident, token, now)\n\t\t\t: db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`UPDATE auto_incident_monitors SET last_since = ?, last_state = ?, incident_id = ?, claim = ?, updated_at = ?\n\t\t\t\t\t\tWHERE page_id = ? AND monitor_id = ? AND last_since = ? AND claim = ?`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(event.since, lastState, keptIncident, token, now, page.id, monitor.id, state.lastSince, state.claim);\n\tconst claimed = (pageParam: string, monitorParam: string, tokenParam: string) =>\n\t\t`EXISTS (SELECT 1 FROM auto_incident_monitors WHERE page_id = ${pageParam} AND monitor_id = ${monitorParam} AND claim = ${tokenParam})`;\n\n\tconst nameOf = (id: string) => page.components.find((component) => component.id === id)?.name ?? id;\n\tconst textsFor = (ids: readonly string[]) =>\n\t\tincidentTexts(page, { components: ids.map(nameOf), monitor: monitor.name, at: event.since }, config.locale, config.timezone);\n\n\tswitch (decision.kind) {\n\t\tcase \"record\":\n\t\t\treturn { statements: [claim], outcome: () => \"record\" };\n\t\tcase \"resolve\": {\n\t\t\tconst incident = openIncidents.find((candidate) => candidate.id === decision.incidentId);\n\t\t\tconst texts = textsFor(incident?.components.map((component) => component.id) ?? componentIds);\n\t\t\tconst updateId = crypto.randomUUID();\n\t\t\treturn {\n\t\t\t\tstatements: [\n\t\t\t\t\tclaim,\n\t\t\t\t\t// Whether another monitor announced in it is still down is decided here, inside the\n\t\t\t\t\t// transaction: two monitors recovering at once both see the other as recovered or not.\n\t\t\t\t\tdb\n\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t`INSERT INTO incident_updates (id, stage, body, created_at, author, automated, incident_id)\n\t\t\t\t\t\t\tSELECT ?1, 'resolved', ?2, ?3, NULL, 1, i.id FROM incidents AS i\n\t\t\t\t\t\t\tWHERE i.id = ?4 AND i.resolved_at IS NULL AND i.auto_created = 1 AND i.human_edited_at IS NULL\n\t\t\t\t\t\t\tAND ${claimed(\"?5\", \"?6\", \"?7\")}\n\t\t\t\t\t\t\tAND NOT EXISTS (SELECT 1 FROM auto_incident_monitors WHERE incident_id = ?4 AND last_state IN ('down', 'degraded'))`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.bind(updateId, event.event === \"stopped\" ? texts.stopped : texts.resolved, now, decision.incidentId, page.id, monitor.id, token),\n\t\t\t\t\tdb\n\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t`UPDATE incidents SET stage = 'resolved', resolved_at = ?2, updated_at = max(updated_at, ?2), updated_by = NULL\n\t\t\t\t\t\t\tWHERE id = ?1 AND resolved_at IS NULL AND EXISTS (SELECT 1 FROM incident_updates WHERE id = ?3)`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.bind(decision.incidentId, now, updateId),\n\t\t\t\t],\n\t\t\t\toutcome: (results) => ((results[1]?.meta.changes ?? 0) > 0 ? \"resolve\" : \"record\"),\n\t\t\t};\n\t\t}\n\t\tcase \"partial\": {\n\t\t\tconst incident = openIncidents.find((candidate) => candidate.id === decision.incidentId);\n\t\t\tconst texts = textsFor(incident?.components.map((component) => component.id) ?? componentIds);\n\t\t\tconst updateId = crypto.randomUUID();\n\t\t\tconst statements = [\n\t\t\t\tclaim,\n\t\t\t\t// At the incident's current stage; it stays open while the monitor is degraded.\n\t\t\t\tdb\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`INSERT INTO incident_updates (id, stage, body, created_at, author, automated, incident_id)\n\t\t\t\t\t\tSELECT ?1, i.stage, ?2, ?3, NULL, 1, i.id FROM incidents AS i\n\t\t\t\t\t\tWHERE i.id = ?4 AND i.resolved_at IS NULL AND ${claimed(\"?5\", \"?6\", \"?7\")}`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(updateId, texts.partial, now, decision.incidentId, page.id, monitor.id, token),\n\t\t\t\tdb\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`UPDATE incidents SET updated_at = max(updated_at, ?1), updated_by = NULL\n\t\t\t\t\t\tWHERE id = (SELECT incident_id FROM incident_updates WHERE id = ?2)`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(now, updateId),\n\t\t\t];\n\t\t\tif (incident !== undefined && incident.components.some((component) => component.impact === \"down\")) {\n\t\t\t\t// Its own incident shows the component degraded now, unless another monitor in it is\n\t\t\t\t// still down; never an administrator's (optimistic on the version read).\n\t\t\t\tconst lowered = incident.components.map((component) =>\n\t\t\t\t\tcomponent.impact === \"down\" ? { ...component, impact: \"degraded\" as const } : component,\n\t\t\t\t);\n\t\t\t\tstatements.push(\n\t\t\t\t\tdb\n\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t`UPDATE incidents SET components = ?1, version = version + 1\n\t\t\t\t\t\t\tWHERE id = ?2 AND version = ?3 AND resolved_at IS NULL AND auto_created = 1 AND human_edited_at IS NULL\n\t\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM incident_updates WHERE id = ?4)\n\t\t\t\t\t\t\tAND NOT EXISTS (SELECT 1 FROM auto_incident_monitors WHERE incident_id = ?2 AND last_state = 'down')`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.bind(JSON.stringify(lowered), incident.id, incident.version, updateId),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn { statements, outcome: (results) => ((results[1]?.meta.changes ?? 0) > 0 ? \"partial\" : \"record\") };\n\t\t}\n\t\tcase \"down\": {\n\t\t\tconst texts = textsFor(componentIds);\n\t\t\tconst newId = crypto.randomUUID();\n\t\t\tconst appendId = crypto.randomUUID();\n\t\t\tconst reopenId = crypto.randomUUID();\n\t\t\tconst ids = JSON.stringify(componentIds);\n\t\t\tconst reopenWithinMs = page.incidents.reopenWithinMs;\n\t\t\tconst statements = [claim];\n\t\t\tlet reopenAt = -1;\n\t\t\tif (reopenWithinMs > 0) {\n\t\t\t\t// Reopen the latest incident automation resolved for these components within the\n\t\t\t\t// window, unless one of them has an unresolved incident now (then it is added to).\n\t\t\t\treopenAt = statements.length;\n\t\t\t\tstatements.push(\n\t\t\t\t\tdb\n\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t`INSERT INTO incident_updates (id, stage, body, created_at, author, automated, incident_id)\n\t\t\t\t\t\t\tSELECT ?1, 'investigating', ?2, ?3, NULL, 1, r.id FROM incidents AS r\n\t\t\t\t\t\t\tWHERE ${claimed(\"?4\", \"?5\", \"?6\")} AND NOT EXISTS (SELECT 1 FROM incidents AS i WHERE ${openOfComponents(\"?4\", \"?8\")})\n\t\t\t\t\t\t\tAND ${reopenable(\"?4\", \"?7\", \"?8\")}\n\t\t\t\t\t\t\tORDER BY r.resolved_at DESC, r.id DESC LIMIT 1`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.bind(reopenId, texts.reopened, now, page.id, monitor.id, token, event.since - reopenWithinMs, ids),\n\t\t\t\t\tdb\n\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t`UPDATE incidents SET stage = 'investigating', resolved_at = NULL, updated_at = max(updated_at, ?1), updated_by = NULL\n\t\t\t\t\t\t\tWHERE id = (SELECT incident_id FROM incident_updates WHERE id = ?2)`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.bind(now, reopenId),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst createAt = statements.length;\n\t\t\tstatements.push(\n\t\t\t\t// A new incident, unless one of the components has an unresolved incident now\n\t\t\t\t// (including one just reopened).\n\t\t\t\tdb\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`INSERT INTO incidents (id, page_id, title, stage, components, started_at, created_at, updated_at, resolved_at,\n\t\t\t\t\t\t\tcreated_by, updated_by, auto_created, human_edited_at, version)\n\t\t\t\t\t\tSELECT ?1, ?2, ?3, 'investigating', ?4, ?5, ?6, ?6, NULL, NULL, NULL, 1, NULL, 1\n\t\t\t\t\t\tWHERE ${claimed(\"?2\", \"?7\", \"?8\")} AND NOT EXISTS (SELECT 1 FROM incidents AS i WHERE ${openOfComponents(\"?2\", \"?9\")})`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\tnewId,\n\t\t\t\t\t\tpage.id,\n\t\t\t\t\t\ttexts.title,\n\t\t\t\t\t\tJSON.stringify(componentIds.map((id) => ({ id, impact: \"down\" }))),\n\t\t\t\t\t\tMath.min(event.since, now),\n\t\t\t\t\t\tnow,\n\t\t\t\t\t\tmonitor.id,\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tids,\n\t\t\t\t\t),\n\t\t\t\tdb\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`INSERT INTO incident_updates (id, stage, body, created_at, author, automated, incident_id)\n\t\t\t\t\t\tSELECT ?1, 'investigating', ?2, ?3, NULL, 1, ?4 WHERE EXISTS (SELECT 1 FROM incidents WHERE id = ?4)`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(crypto.randomUUID(), texts.investigating, now, newId),\n\t\t\t);\n\t\t\tconst appendAt = statements.length;\n\t\t\tstatements.push(\n\t\t\t\t// Otherwise an update to the latest unresolved incident of the components, at its\n\t\t\t\t// current stage: an automated note must not move a person's stage back.\n\t\t\t\tdb\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`INSERT INTO incident_updates (id, stage, body, created_at, author, automated, incident_id)\n\t\t\t\t\t\tSELECT ?1, i.stage, ?2, ?3, NULL, 1, i.id FROM incidents AS i\n\t\t\t\t\t\tWHERE ${claimed(\"?4\", \"?5\", \"?6\")} AND NOT EXISTS (SELECT 1 FROM incidents WHERE id = ?7)\n\t\t\t\t\t\tAND NOT EXISTS (SELECT 1 FROM incident_updates WHERE id = ?9)\n\t\t\t\t\t\tAND ${openOfComponents(\"?4\", \"?8\")}\n\t\t\t\t\t\tORDER BY i.started_at DESC, i.id DESC LIMIT 1`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(appendId, texts.update, now, page.id, monitor.id, token, newId, ids, reopenId),\n\t\t\t\tdb\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`UPDATE incidents SET updated_at = max(updated_at, ?1), updated_by = NULL\n\t\t\t\t\t\tWHERE id = (SELECT incident_id FROM incident_updates WHERE id = ?2)`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(now, appendId),\n\t\t\t);\n\t\t\t// The missing components, if the update went to the incident that was read and nobody\n\t\t\t// changed its list since (optimistic): one added to, or one reopened.\n\t\t\tconst extend = (incident: { readonly id: string; readonly version: number }, components: readonly AffectedComponent[], updateId: string) =>\n\t\t\t\tdb\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`UPDATE incidents SET components = ?1, version = version + 1\n\t\t\t\t\t\tWHERE id = ?2 AND version = ?3 AND resolved_at IS NULL\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM incident_updates WHERE id = ?4 AND incident_id = ?2)`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(JSON.stringify(components), incident.id, incident.version, updateId);\n\t\t\tif (decision.existing !== null && decision.components !== null) {\n\t\t\t\tstatements.push(extend(decision.existing, decision.components, appendId));\n\t\t\t}\n\t\t\tconst reopenMissing = candidate === null ? [] : componentIds.filter((id) => !candidate.components.some((component) => component.id === id));\n\t\t\tif (candidate !== null && reopenMissing.length > 0) {\n\t\t\t\tstatements.push(extend(candidate, [...candidate.components, ...reopenMissing.map((id) => ({ id, impact: \"down\" as const }))], reopenId));\n\t\t\t}\n\t\t\t// The incident this `down` was announced in, for its recovery.\n\t\t\tstatements.push(\n\t\t\t\tdb\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`UPDATE auto_incident_monitors\n\t\t\t\t\t\tSET incident_id = coalesce(\n\t\t\t\t\t\t\t(SELECT id FROM incidents WHERE id = ?1),\n\t\t\t\t\t\t\t(SELECT incident_id FROM incident_updates WHERE id = ?2),\n\t\t\t\t\t\t\t(SELECT incident_id FROM incident_updates WHERE id = ?6)\n\t\t\t\t\t\t)\n\t\t\t\t\t\tWHERE page_id = ?3 AND monitor_id = ?4 AND claim = ?5`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(newId, appendId, page.id, monitor.id, token, reopenId),\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tstatements,\n\t\t\t\toutcome: (results) =>\n\t\t\t\t\treopenAt >= 0 && (results[reopenAt]?.meta.changes ?? 0) > 0\n\t\t\t\t\t\t? \"reopen\"\n\t\t\t\t\t\t: (results[createAt]?.meta.changes ?? 0) > 0\n\t\t\t\t\t\t\t? \"create\"\n\t\t\t\t\t\t\t: (results[appendAt]?.meta.changes ?? 0) > 0\n\t\t\t\t\t\t\t\t? \"append\"\n\t\t\t\t\t\t\t\t: \"record\",\n\t\t\t};\n\t\t}\n\t}\n}\n","/**\n * Delivery limits shared with wrangler.jsonc. Kept free of imports so that the Node.js build\n * test can read it and check it against the queue consumer's `max_retries`.\n */\n\n/**\n * The notification queue's `max_retries` in wrangler.jsonc. With retries 30 s, 1, 2, 4, 8, 16\n * minutes and then every 30 minutes apart, the last attempt comes about 8 hours after the\n * first, so a delivery survives an outage of the receiving service of several hours.\n */\nexport const MAX_RETRIES = 20;\n\n/** Attempts of a message: the first and its retries. The last one records a failure itself. */\nexport const MAX_DELIVERY_ATTEMPTS = MAX_RETRIES + 1;\n\n/** Retries wait 30 s, then twice as long each time, at most 30 minutes (or what the service asked for, at most that). */\nexport const RETRY_BASE_S = 30;\nexport const MAX_RETRY_DELAY_S = 30 * 60;\n","/** Who receives an event, and when maintenance holds it back. Pure functions. */\nimport type { ComponentRef, NotificationEvent } from \"../../shared/admin-api\";\nimport type { MonitorEvent } from \"./events\";\n\n/** What {@link targetReceives} needs from a target. */\nexport interface TargetSelection {\n\treadonly enabled: boolean;\n\treadonly admin: boolean;\n\treadonly events: readonly NotificationEvent[];\n\treadonly allMonitors: boolean;\n\treadonly monitors: readonly string[];\n\treadonly components: readonly ComponentRef[];\n}\n\n/**\n * Whether a target receives `event`: it is enabled, it chose the event (`unknown` only\n * for administrators' targets), and it covers the monitor: all monitors, the monitor by ID,\n * or a component that shows it (`refs`: the components that show the monitor).\n */\nexport function targetReceives(target: TargetSelection, event: Pick<MonitorEvent, \"event\" | \"monitorId\">, refs: readonly ComponentRef[]): boolean {\n\tif (event.event === \"stopped\") return false;\n\tif (!target.enabled || !target.events.includes(event.event)) return false;\n\tif (event.event === \"unknown\" && !target.admin) return false;\n\tif (target.allMonitors || target.monitors.includes(event.monitorId)) return true;\n\treturn target.components.some((selected) =>\n\t\trefs.some((ref) => ref.pageId === selected.pageId && ref.componentId === selected.componentId),\n\t);\n}\n\n/** A maintenance window, as suppression needs it. */\nexport interface MaintenanceWindow {\n\treadonly pageId: string;\n\treadonly components: readonly string[];\n\treadonly startsAt: number;\n\treadonly endsAt: number;\n}\n\n/**\n * Whether maintenance suppresses a monitor's notifications at `at`: some component that\n * shows the monitor (`refs`) is under maintenance then, from `startsAt` (inclusive) to\n * `endsAt` (exclusive), as the status page shows it.\n */\nexport function suppressedByMaintenance(refs: readonly ComponentRef[], windows: readonly MaintenanceWindow[], at: number): boolean {\n\treturn windows.some(\n\t\t(window) =>\n\t\t\twindow.startsAt <= at &&\n\t\t\tat < window.endsAt &&\n\t\t\trefs.some((ref) => ref.pageId === window.pageId && window.components.includes(ref.componentId)),\n\t);\n}\n\n/**\n * Whether maintenance applies to `event` at all: to the start of a problem (`down`,\n * `degraded`). A recovery goes to the targets that heard of the problem, whatever the\n * maintenance (see `pairedEventIds`), and `unknown` is about monitoring itself (results stopped\n * arriving at the hub), not about the service under maintenance, so administrators hear about\n * it even then.\n */\nexport function maintenanceApplies(event: Pick<MonitorEvent, \"event\">): boolean {\n\treturn event.event === \"down\" || event.event === \"degraded\";\n}\n","/**\n * A target's options: split into plain and secret ones, the secret ones encrypted for storage\n * and decrypted for sending. Secret values never leave the Worker: the admin API returns\n * only whether each one is set ({@link publicTarget}).\n */\nimport { destinationOptionOf, isPublicHostname, type NotifierKind } from \"@naosystem/cf-workers-status-page-core\";\nimport type { NotificationTarget } from \"../../shared/admin-api\";\nimport type { TargetRecord } from \"../db/notifications\";\nimport { DecryptionError, decryptSecret, encryptSecret, isBoundToDestination, type KeyRing, keyRing, storedKeyId } from \"./crypto\";\n\n/** The secret options of a kind; for a kind no longer registered, those the target has. */\nfunction secretKeys(target: Pick<TargetRecord, \"secrets\">, kind: NotifierKind | undefined): string[] {\n\treturn kind === undefined ? Object.keys(target.secrets) : [...kind.secretOptions];\n}\n\n/** The target as the admin API shows it: secret values replaced by whether they are set. */\nexport function publicTarget(target: TargetRecord, kind: NotifierKind | undefined): NotificationTarget {\n\tconst { secrets, ...rest } = target;\n\treturn {\n\t\t...rest,\n\t\tsecrets: Object.fromEntries(secretKeys(target, kind).map((key) => [key, Object.hasOwn(secrets, key)])),\n\t};\n}\n\n/**\n * The option that says where `target` sends (`destinationOption` in @naosystem/cf-workers-status-page-core): its\n * kind's, or `url` for a kind no longer registered that has one.\n */\nexport function destinationOption(\n\ttarget: Pick<TargetRecord, \"options\" | \"secrets\">,\n\tkind: NotifierKind | undefined,\n): string | undefined {\n\tif (kind !== undefined) return destinationOptionOf(kind);\n\treturn Object.hasOwn(target.secrets, \"url\") || Object.hasOwn(target.options, \"url\") ? \"url\" : undefined;\n}\n\n/** The origin of a destination URL, or `undefined` when `value` is not one. */\nexport function destinationOrigin(value: unknown): string | undefined {\n\tif (typeof value !== \"string\" || !URL.canParse(value)) return undefined;\n\tconst { origin } = new URL(value);\n\treturn origin === \"null\" ? undefined : origin;\n}\n\n/**\n * Why `options[destination]` may not be sent to, or `null`: it must name a public host, not an\n * IP address or an internal name, whatever the kind's own schema says.\n */\nexport function destinationProblem(kind: NotifierKind, options: Readonly<Record<string, unknown>>): string | null {\n\tconst option = destinationOptionOf(kind);\n\tconst value = option === undefined ? undefined : options[option];\n\tif (typeof value !== \"string\" || !URL.canParse(value)) return null;\n\treturn isPublicHostname(new URL(value).hostname)\n\t\t? null\n\t\t: \"must name a public host: IP addresses and internal names such as localhost or *.internal are not allowed\";\n}\n\n/**\n * Splits validated `options` into plain ones and encrypted secret ones, for target `targetId`.\n * Secret options other than the destination are bound to the destination's origin.\n */\nexport async function splitOptions(\n\tenv: Env,\n\ttargetId: string,\n\tkind: NotifierKind,\n\toptions: Readonly<Record<string, unknown>>,\n): Promise<{ options: Record<string, unknown>; secrets: Record<string, string> }> {\n\tconst plain: Record<string, unknown> = {};\n\tconst secret: [string, unknown][] = [];\n\tfor (const [key, value] of Object.entries(options)) {\n\t\tif (value === undefined) continue;\n\t\tif (kind.secretOptions.includes(key)) secret.push([key, value]);\n\t\telse plain[key] = value;\n\t}\n\tif (secret.length === 0) return { options: plain, secrets: {} };\n\t// Throws EncryptionKeyError without the key: secrets are never stored in plain text.\n\tconst ring = await keyRing(env);\n\tconst destination = destinationOptionOf(kind);\n\tconst origin = destination === undefined ? undefined : destinationOrigin(options[destination]);\n\tconst secrets: Record<string, string> = {};\n\tfor (const [key, value] of secret) {\n\t\tsecrets[key] = await encryptSecret(ring, targetId, key, JSON.stringify(value), key === destination ? undefined : origin);\n\t}\n\treturn { options: plain, secrets };\n}\n\nexport interface ReadSecrets {\n\t/** The target's options, with every secret that could be decrypted. */\n\treadonly options: Record<string, unknown>;\n\t/** Secrets that could not be decrypted (their key is gone, or they belong to another destination), by option. */\n\treadonly errors: ReadonlyMap<string, DecryptionError>;\n}\n\n/**\n * Decrypts the target's secrets with `ring`: the destination first, then the others for its\n * origin. Never throws a {@link DecryptionError}; see `errors`.\n */\nexport async function readSecrets(\n\tring: KeyRing,\n\ttarget: Pick<TargetRecord, \"id\" | \"options\" | \"secrets\">,\n\tkind: NotifierKind | undefined,\n): Promise<ReadSecrets> {\n\tconst options: Record<string, unknown> = { ...target.options };\n\tconst errors = new Map<string, DecryptionError>();\n\tconst destination = destinationOption(target, kind);\n\tconst keys = Object.keys(target.secrets).sort((a, b) => Number(b === destination) - Number(a === destination));\n\tlet origin = destination === undefined ? undefined : destinationOrigin(options[destination]);\n\tfor (const key of keys) {\n\t\ttry {\n\t\t\toptions[key] = await decryptOption(ring, target.id, key, target.secrets[key] as string, key === destination ? undefined : origin);\n\t\t\tif (key === destination) origin = destinationOrigin(options[key]);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof DecryptionError)) throw error;\n\t\t\terrors.set(key, error);\n\t\t}\n\t}\n\treturn { options, errors };\n}\n\n/**\n * The target's options with its secrets decrypted, as entered. Needs the key only when the\n * target has secrets. @throws EncryptionKeyError, DecryptionError\n */\nexport async function decryptOptions(\n\tenv: Env,\n\ttarget: Pick<TargetRecord, \"id\" | \"options\" | \"secrets\">,\n\tkind: NotifierKind | undefined,\n): Promise<Record<string, unknown>> {\n\tif (Object.keys(target.secrets).length === 0) return { ...target.options };\n\tconst { options, errors } = await readSecrets(await keyRing(env), target, kind);\n\tconst [first] = errors.values();\n\tif (first !== undefined) throw first;\n\treturn options;\n}\n\n/**\n * Whether the target's secrets are all encrypted with the current key and, but for the\n * destination itself, bound to the destination (what `re-encrypt` brings them to).\n */\nexport function secretsUpToDate(ring: KeyRing, target: Pick<TargetRecord, \"options\" | \"secrets\">, kind: NotifierKind | undefined): boolean {\n\tconst destination = destinationOption(target, kind);\n\treturn Object.entries(target.secrets).every(\n\t\t([key, stored]) =>\n\t\t\tstoredKeyId(stored) === ring.currentId && (destination === undefined || key === destination || isBoundToDestination(stored)),\n\t);\n}\n\n/** One secret option's value. @throws DecryptionError, whose message never contains the value. */\nexport async function decryptOption(\n\tring: KeyRing,\n\ttargetId: string,\n\toption: string,\n\tstored: string,\n\tdestination?: string,\n): Promise<unknown> {\n\tconst plaintext = await decryptSecret(ring, targetId, option, stored, destination);\n\ttry {\n\t\treturn JSON.parse(plaintext) as unknown;\n\t} catch {\n\t\t// A JSON error would quote the value.\n\t\tthrow new DecryptionError(`The stored value of \"${option}\" is damaged`);\n\t}\n}\n\n/** Shortest fragment of a secret URL redacted on its own (a token in a path or query). */\nconst MIN_FRAGMENT = 8;\n\n/**\n * The strings to redact from errors: every string in the secret options and, for URLs, their\n * path segments and query values, which a service's error message might echo.\n */\nexport function secretValues(target: Pick<TargetRecord, \"secrets\">, options: Readonly<Record<string, unknown>>): string[] {\n\tconst values: string[] = [];\n\tconst visit = (value: unknown): void => {\n\t\tif (typeof value === \"string\") {\n\t\t\tvalues.push(value);\n\t\t\tif (URL.canParse(value)) {\n\t\t\t\tconst url = new URL(value);\n\t\t\t\tfor (const part of [...url.pathname.split(\"/\"), ...url.searchParams.values()]) {\n\t\t\t\t\tif (part.length >= MIN_FRAGMENT) values.push(part);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (Array.isArray(value)) value.forEach(visit);\n\t\telse if (typeof value === \"object\" && value !== null) Object.values(value).forEach(visit);\n\t};\n\tfor (const key of Object.keys(target.secrets)) visit(options[key]);\n\treturn values;\n}\n","/**\n * The notification queue's consumer, for both the queue and its dead letter queue.\n *\n * - `event` messages: maintenance suppression is decided, the event is fanned out to\n * one `delivery` message per target that receives it, and automatic incidents are applied. Every step is idempotent, so a failed event message is simply retried.\n * A recovery (`recovered`, `degraded_recovered`) goes to exactly the targets that the event\n * it answers went to (`pairedEventIds`), whatever the maintenance and the targets' current\n * selection of monitors; so a `down` that maintenance held back has no recovery either.\n * `stopped` (a monitor left the configuration while down) only resolves automatic incidents.\n * - `delivery` messages: the delivery record in D1 is claimed (a duplicate message that finds it\n * sent is dropped; one that finds it claimed and not finished waits for the claim's lease to\n * end, as that claim may be its own earlier attempt that lost D1), the target's secrets are\n * decrypted, the notification is rendered in `locale` and sent; the record then says\n * `sent`, or `retrying` with the error and the message is retried with backoff, or `failed`\n * when retrying cannot help or this was the last attempt ({@link MAX_DELIVERY_ATTEMPTS}).\n * - On the dead letter queue (a message whose consumer failed on its last attempt): the\n * delivery is recorded as `failed`, which the admin UI lists. The dead letter queue is\n * recognised by its name, which must end in `-dlq` (wrangler.jsonc).\n */\nimport {\n\ttype NotificationEvent,\n\ttype NotifierKind,\n\tNotifierError,\n\tredactSecrets,\n} from \"@naosystem/cf-workers-status-page-core\";\nimport { translator } from \"../../shared/i18n\";\nimport { config, findMonitor, findPage } from \"../config\";\nimport {\n\tclaimDelivery,\n\tfinishDelivery,\n\tgetTarget,\n\tlistTargets,\n\tmaintenanceAt,\n\tFAN_OUT_TARGET,\n\tpairedTargets,\n\trecordFanOut,\n\trecordDeadLetter,\n\trecordSuppressedDown,\n\ttype TargetRecord,\n} from \"../db/notifications\";\nimport { ensureSchema } from \"../db/schema\";\nimport { USER_AGENT } from \"../runners\";\nimport { applyAutoIncident, type AutoEvent, autoIncidentPagesOf } from \"./auto-incidents\";\nimport { DecryptionError, EncryptionKeyError } from \"./crypto\";\nimport { type MonitorEvent, pairedEventIds, parseQueueBody, type QueueBody } from \"./events\";\nimport { MAX_DELIVERY_ATTEMPTS, MAX_RETRY_DELAY_S, RETRY_BASE_S } from \"./limits\";\nimport { createIncidentLinks, monitorComponents, type NotifiedEvent, renderEvent } from \"./render\";\nimport { maintenanceApplies, suppressedByMaintenance, targetReceives } from \"./rules\";\nimport { enqueue } from \"./queue\";\nimport { decryptOptions, destinationProblem, secretValues } from \"./targets\";\n\n/** How long one notification may take to send. */\nexport const SEND_TIMEOUT_MS = 15_000;\n/** A claimed delivery is someone else's to send for this long; then it may be claimed again (a consumer that crashed). */\nexport const LEASE_MS = 60_000;\n/** The dead letter queue's name ends with this (wrangler.jsonc). */\nconst DEAD_LETTER_SUFFIX = \"-dlq\";\nexport { FAN_OUT_TARGET };\n/**\n * A recovery whose answered event has not been processed yet (Queues keeps no order) waits for\n * it this many attempts, {@link PAIRING_WAIT_S} apart, then goes to the targets known by then.\n */\nexport const PAIRING_ATTEMPTS = 5;\nexport const PAIRING_WAIT_S = 60;\n/** On the dead letter queue, retries wait 1 minute, then twice as long each time, up to an hour. */\nconst DEAD_LETTER_RETRY_BASE_S = 60;\nconst DEAD_LETTER_MAX_RETRY_S = 3_600;\n\n/** The event a recovery answers was not processed yet: the recovery waits for it. */\nexport class PairingPending extends Error {\n\toverride readonly name = \"PairingPending\";\n}\n\n/** Whether a batch comes from the dead letter queue: by its name, `<queue>-dlq` in wrangler.jsonc. */\nexport function isDeadLetterQueue(queue: string): boolean {\n\treturn queue.endsWith(DEAD_LETTER_SUFFIX);\n}\n\n/** Seconds until a delivery claimed until `leaseUntil` may be claimed again (a second after its lease ends). */\nexport function leaseWaitSeconds(leaseUntil: number | null, now: number): number {\n\tconst remaining = Math.max(0, (leaseUntil ?? now + LEASE_MS) - now);\n\treturn Math.ceil(remaining / 1_000) + 1;\n}\n\n/** Seconds before retrying a message after its `attempts`-th attempt (see limits.ts). */\nexport function retryDelaySeconds(attempts: number, retryAfterMs?: number): number {\n\tconst backoff = RETRY_BASE_S * 2 ** Math.max(0, attempts - 1);\n\tconst asked = retryAfterMs === undefined ? 0 : Math.ceil(retryAfterMs / 1_000);\n\treturn Math.min(MAX_RETRY_DELAY_S, Math.max(backoff, asked));\n}\n\n/** The fetch notifier kinds use: the global fetch with the hub's User-Agent. */\nexport function notifierFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n\tconst request = new Request(input, init);\n\tif (!request.headers.has(\"User-Agent\")) request.headers.set(\"User-Agent\", USER_AGENT);\n\t// Looked up at call time, so that tests can replace the global fetch.\n\treturn globalThis.fetch(request);\n}\n\nexport interface Failure {\n\treadonly message: string;\n\treadonly retryable: boolean;\n\treadonly retryAfterMs?: number | undefined;\n}\n\n/** What went wrong, with secret values removed from the message. */\nexport function describeFailure(error: unknown, secrets: readonly string[]): Failure {\n\tconst redact = (message: string) => redactSecrets(message, secrets);\n\tif (error instanceof NotifierError) {\n\t\treturn { message: redact(error.message), retryable: error.retryable, retryAfterMs: error.retryAfterMs };\n\t}\n\tif (error instanceof EncryptionKeyError) return { message: error.message, retryable: true };\n\tif (error instanceof DecryptionError) return { message: error.message, retryable: false };\n\tif (error instanceof Error && (error.name === \"TimeoutError\" || error.name === \"AbortError\")) {\n\t\treturn { message: `No answer within ${SEND_TIMEOUT_MS / 1_000} seconds`, retryable: true };\n\t}\n\treturn { message: redact(error instanceof Error ? `${error.name}: ${error.message}` : String(error)), retryable: true };\n}\n\n/**\n * Sends `notification` with `kind`, giving up after {@link SEND_TIMEOUT_MS} even if the kind\n * ignores the signal.\n */\nexport async function sendWithTimeout(\n\tkind: NotifierKind,\n\tnotification: Parameters<NotifierKind[\"send\"]>[0],\n\toptions: unknown,\n): Promise<void> {\n\tconst signal = AbortSignal.timeout(SEND_TIMEOUT_MS);\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst timeout = new Promise<never>((_, reject) => {\n\t\ttimer = setTimeout(() => reject(new DOMException(\"timed out\", \"TimeoutError\")), SEND_TIMEOUT_MS + 1_000);\n\t});\n\ttry {\n\t\tawait Promise.race([kind.send(notification, options, { fetch: notifierFetch as typeof fetch, signal }), timeout]);\n\t} finally {\n\t\tif (timer !== undefined) clearTimeout(timer);\n\t}\n}\n\n/** Seconds before retrying a message of the dead letter queue after its `attempts`-th attempt. */\nexport function deadLetterRetryDelaySeconds(attempts: number): number {\n\treturn Math.min(DEAD_LETTER_MAX_RETRY_S, DEAD_LETTER_RETRY_BASE_S * 2 ** Math.max(0, attempts - 1));\n}\n\n/**\n * Handles a batch from the notification queue or its dead letter queue. Never throws: every\n * message is acknowledged or retried with a delay, so that a failure of D1 (an outage, the Free\n * plan's daily limit) backs off instead of using up the retries at once; on the dead letter\n * queue, messages wait for D1 for up to `max_retries` hours (wrangler.jsonc), so that their\n * failure is recorded once it is back.\n */\nexport async function handleNotificationBatch(batch: MessageBatch<unknown>, env: Env, ctx: ExecutionContext): Promise<void> {\n\tconst deadLetter = isDeadLetterQueue(batch.queue);\n\tconst delayOf = (attempts: number) => (deadLetter ? deadLetterRetryDelaySeconds(attempts) : retryDelaySeconds(attempts));\n\ttry {\n\t\tawait ensureSchema(env.DB);\n\t} catch (error) {\n\t\tconsole.error(`Notifications: D1 is unavailable; retrying ${batch.messages.length} messages later`, error);\n\t\tfor (const message of batch.messages) message.retry({ delaySeconds: delayOf(message.attempts) });\n\t\treturn;\n\t}\n\tawait Promise.all(\n\t\tbatch.messages.map(async (message) => {\n\t\t\tconst body = parseQueueBody(message.body);\n\t\t\tif (body === null) {\n\t\t\t\tconsole.warn(`Dropping a notification message this version does not understand (${message.id})`);\n\t\t\t\tmessage.ack();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tif (deadLetter) await handleDeadLetter(env, body);\n\t\t\t\telse if (body.type === \"event\") await handleEvent(env, ctx, body.event, message.attempts);\n\t\t\t\telse {\n\t\t\t\t\tawait handleDelivery(env, body.event, body.targetId, message);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tmessage.ack();\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof PairingPending) {\n\t\t\t\t\tconsole.log(`Notification message ${message.id}: ${error.message}; waiting`);\n\t\t\t\t\tmessage.retry({ delaySeconds: PAIRING_WAIT_S });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconsole.error(`Notification message ${message.id} (${body.type} ${body.event.id}) failed; retrying`, error);\n\t\t\t\tmessage.retry({ delaySeconds: delayOf(message.attempts) });\n\t\t\t}\n\t\t}),\n\t);\n}\n\n/**\n * Suppression, fan-out and automatic incidents for one event. `attempts` is the message's\n * attempt: a recovery whose answered event is not processed yet waits for it (throws\n * {@link PairingPending}) during the first {@link PAIRING_ATTEMPTS}.\n */\nexport async function handleEvent(env: Env, ctx: ExecutionContext, event: MonitorEvent, attempts = PAIRING_ATTEMPTS): Promise<void> {\n\tconst now = Date.now();\n\tif (event.event === \"stopped\") {\n\t\tawait applyStopped(env, ctx, event, now);\n\t\treturn;\n\t}\n\tconst monitor = findMonitor(event.monitorId);\n\tif (monitor === undefined) {\n\t\tconsole.warn(`Dropping event ${event.id}: monitor \"${event.monitorId}\" is no longer in status.config.ts`);\n\t\treturn;\n\t}\n\tconst refs = monitorComponents(config.pages, monitor.id);\n\tif (maintenanceApplies(event) && refs.length > 0) {\n\t\tconst pages = [...new Set(refs.map((ref) => ref.pageId))];\n\t\tconst windows = await maintenanceAt(env.DB, pages, event.detectedAt);\n\t\tif (suppressedByMaintenance(refs, windows, event.detectedAt)) {\n\t\t\t// Held back. A `down` is notified when the maintenance ends, if still down (see cron.ts).\n\t\t\tif (event.event === \"down\") await recordSuppressedDown(env.DB, event, now);\n\t\t\t// Its recovery then goes to no target.\n\t\t\tawait recordFanOut(env.DB, event, [], \"suppressed\", now);\n\t\t\tconsole.log(`Event ${event.id} (${event.event}) not notified: maintenance`);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tconst enabled = await listTargets(env.DB, { enabledOnly: true });\n\tconst paired = pairedEventIds(event);\n\tlet targets: TargetRecord[];\n\tif (paired.length > 0) {\n\t\t// A recovery: to the targets that heard of what it ends, if they still take recoveries.\n\t\tconst answered = await pairedTargets(env.DB, paired);\n\t\tif (!answered.processed && attempts < PAIRING_ATTEMPTS) {\n\t\t\tthrow new PairingPending(`event ${event.id} answers ${paired[0]}, which is not processed yet`);\n\t\t}\n\t\ttargets = enabled.filter((target) => answered.targets.has(target.id) && target.events.includes(event.event as NotificationEvent));\n\t} else {\n\t\ttargets = enabled.filter((target) => targetReceives(target, event, refs));\n\t}\n\t// Recorded before the messages are queued, so that a recovery processed before them finds them.\n\tawait recordFanOut(\n\t\tenv.DB,\n\t\tevent,\n\t\ttargets.map((target) => target.id),\n\t\t\"fanned_out\",\n\t\tnow,\n\t);\n\tawait enqueue(\n\t\tenv,\n\t\ttargets.map((target) => ({ type: \"delivery\", v: 1, event, targetId: target.id })),\n\t);\n\tawait applyAutoIncidents(env, ctx, event, monitor, now);\n}\n\nasync function applyAutoIncidents(\n\tenv: Env,\n\tctx: ExecutionContext,\n\tevent: MonitorEvent,\n\tmonitor: { readonly id: string; readonly name: string },\n\tnow: number,\n): Promise<void> {\n\tif (event.event !== \"down\" && event.event !== \"recovered\" && event.event !== \"degraded_recovered\") return;\n\tconst typed = event as MonitorEvent & { readonly event: AutoEvent };\n\tfor (const page of config.pages) {\n\t\tif (!page.incidents.auto || !page.components.some((component) => component.monitors.includes(monitor.id))) continue;\n\t\tawait applyAutoIncident({ env, ctx, now }, page, monitor, typed);\n\t}\n}\n\n/**\n * A monitor left the configuration while down: the automatic incidents its `down` opened are\n * resolved (\"monitoring stopped\"), unless an administrator edited them or another monitor in\n * them is still down. The monitor is on no page any more, so its pages come from D1.\n */\nasync function applyStopped(env: Env, ctx: ExecutionContext, event: MonitorEvent, now: number): Promise<void> {\n\tconst typed = event as MonitorEvent & { readonly event: \"stopped\" };\n\tfor (const pageId of await autoIncidentPagesOf(env.DB, event.monitorId)) {\n\t\tconst page = findPage(pageId);\n\t\tif (page === undefined) continue;\n\t\tawait applyAutoIncident({ env, ctx, now }, page, { id: event.monitorId, name: event.monitorId }, typed);\n\t}\n}\n\n/** Sends one notification to one target, at most once (see the module documentation). */\nasync function handleDelivery(env: Env, body: MonitorEvent, targetId: string, message: Message<unknown>): Promise<void> {\n\tif (body.event === \"stopped\") {\n\t\t// Never fanned out; a message like this did not come from this hub.\n\t\tmessage.ack();\n\t\treturn;\n\t}\n\tconst event = body as NotifiedEvent;\n\tconst key = { notificationId: event.id, targetId };\n\tconst claim = await claimDelivery(\n\t\tenv.DB,\n\t\t{ ...key, event: event.event, monitorId: event.monitorId, occurredAt: event.since },\n\t\tDate.now(),\n\t\tLEASE_MS,\n\t);\n\tif (!claim.claimed) {\n\t\tif (claim.status === \"sending\") {\n\t\t\t// Claimed and not finished: by another copy of this message, or by an earlier attempt of\n\t\t\t// this very message whose consumer then lost D1 or died before recording an outcome. In\n\t\t\t// the second case no other message is left to finish the delivery, so this one must not\n\t\t\t// be dropped: it waits for the lease, then claims the delivery or finds it sent.\n\t\t\tmessage.retry({ delaySeconds: leaseWaitSeconds(claim.leaseUntil, Date.now()) });\n\t\t\treturn;\n\t\t}\n\t\t// Sent already: a duplicate.\n\t\tmessage.ack();\n\t\treturn;\n\t}\n\n\tlet secrets: string[] = [];\n\ttry {\n\t\tconst target = await getTarget(env.DB, targetId);\n\t\tif (target === null || !target.enabled) {\n\t\t\t// Deleted or disabled after the fan-out: nothing to send.\n\t\t\tawait finishDelivery(env.DB, key, \"failed\", target === null ? \"The target was deleted\" : \"The target was disabled\", Date.now());\n\t\t\tmessage.ack();\n\t\t\treturn;\n\t\t}\n\t\tconst options = await decryptOptions(env, target, config.notifiers.find((kind) => kind.type === target.kind));\n\t\tsecrets = secretValues(target, options);\n\t\tawait sendToTarget(target, options, event);\n\t\tawait finishDelivery(env.DB, key, \"sent\", null, Date.now());\n\t\tmessage.ack();\n\t} catch (error) {\n\t\tconst failure = describeFailure(error, secrets);\n\t\t// The last attempt records the failure itself, instead of leaving it to the dead letter queue.\n\t\tconst retry = failure.retryable && message.attempts < MAX_DELIVERY_ATTEMPTS;\n\t\tif (retry) {\n\t\t\tawait finishDelivery(env.DB, key, \"retrying\", failure.message, Date.now());\n\t\t\tmessage.retry({ delaySeconds: retryDelaySeconds(message.attempts, failure.retryAfterMs) });\n\t\t} else {\n\t\t\tawait finishDelivery(env.DB, key, \"failed\", failure.message, Date.now());\n\t\t\tmessage.ack();\n\t\t}\n\t\tconsole.warn(`Notification ${event.id} to target ${targetId}: ${failure.message}${retry ? \" (retrying)\" : \"\"}`);\n\t}\n}\n\n/** The registered kind of `target`. @throws NotifierError (not retryable) when it is no longer registered. */\nexport function kindOf(target: Pick<TargetRecord, \"kind\">): NotifierKind {\n\tconst kind = config.notifiers.find((candidate) => candidate.type === target.kind);\n\tif (kind === undefined) {\n\t\tthrow new NotifierError(`Notifier kind \"${target.kind}\" is not in status.config.ts`, { retryable: false });\n\t}\n\treturn kind;\n}\n\n/** Validates the target's options against its kind and sends the event's notification. */\nasync function sendToTarget(target: TargetRecord, options: Record<string, unknown>, event: NotifiedEvent): Promise<void> {\n\tconst kind = kindOf(target);\n\tconst parsed = kind.options.safeParse(options);\n\tif (!parsed.success) {\n\t\tthrow new NotifierError(`The target's options are no longer valid for \"${kind.type}\"; edit the target`, { retryable: false });\n\t}\n\tif (destinationProblem(kind, options) !== null) {\n\t\tthrow new NotifierError(\"The target's destination is not a public host; edit the target\", { retryable: false });\n\t}\n\tconst monitor = findMonitor(event.monitorId);\n\tconst links =\n\t\ttarget.admin && event.event === \"down\"\n\t\t\t? createIncidentLinks(config.pages, event.monitorId, config.baseUrl, translator(config.locale))\n\t\t\t: [];\n\tconst notification = renderEvent(event, {\n\t\tlocale: config.locale,\n\t\ttimeZone: config.timezone,\n\t\tmonitorName: monitor?.name ?? event.monitorId,\n\t\tlinks,\n\t});\n\tawait sendWithTimeout(kind, notification, parsed.data);\n}\n\n/** Records a message the queue gave up on (shown as failed in the admin UI). */\nasync function handleDeadLetter(env: Env, body: QueueBody): Promise<void> {\n\tconst { event } = body;\n\tif (event.event === \"stopped\") {\n\t\tconsole.error(`Event ${event.id} (stopped) failed for good: automatic incidents of monitor \"${event.monitorId}\" stay as they are`);\n\t\treturn;\n\t}\n\tconst targetId = body.type === \"delivery\" ? body.targetId : FAN_OUT_TARGET;\n\tawait recordDeadLetter(\n\t\tenv.DB,\n\t\t{ notificationId: event.id, targetId, event: event.event, monitorId: event.monitorId, occurredAt: event.since },\n\t\t// The attempts recorded by the deliveries count; the dead letter queue's own do not.\n\t\t0,\n\t\tDate.now(),\n\t);\n\tconsole.error(`Notification ${event.id} ${body.type === \"delivery\" ? `to target ${targetId}` : \"(fan-out)\"} failed for good`);\n}\n","/**\n * `/api/admin/notifications/*`: notifier kinds, notification targets, failed deliveries and\n * re-encryption of secrets.\n *\n * Secret options are write-only: they are accepted on create and edit, encrypted before they\n * are stored, and never returned or logged; responses say only whether each one is set.\n * Saving a target with secret options needs the `NOTIFICATION_KEYS` secret (503\n * `encryption_key_missing` without it).\n */\nimport type { NotifierKind } from \"@naosystem/cf-workers-status-page-core\";\nimport * as z from \"zod\";\nimport {\n\ttype ApiIssue,\n\ttype ComponentRef,\n\tcreateNotificationTargetSchema,\n\tDEFAULT_TARGET_EVENTS,\n\tLIMITS,\n\ttype NotificationEvent,\n\ttype NotifierKindInfo,\n\ttype NotifierKindsResponse,\n\tpatchNotificationTargetSchema,\n\ttype ReEncryptResult,\n\ttype TestNotificationResult,\n} from \"../../shared/admin-api\";\nimport { config, findMonitor, findPage } from \"../config\";\nimport {\n\tdecodeDeliveryCursor,\n\tdeleteTarget,\n\tgetTarget,\n\tinsertTarget,\n\tlistDeliveries,\n\tlistTargets,\n\treplaceSecrets,\n\ttype TargetChanges,\n\ttype TargetFields,\n\tupdateTarget,\n} from \"../db/notifications\";\nimport { describeFailure, sendWithTimeout } from \"../notifications/consumer\";\nimport { EncryptionKeyError, encryptSecret, keyRing } from \"../notifications/crypto\";\nimport { renderTest } from \"../notifications/render\";\nimport {\n\tdecryptOptions,\n\tdestinationOption,\n\tdestinationOrigin,\n\tdestinationProblem,\n\tpublicTarget,\n\treadSecrets,\n\tsecretsUpToDate,\n\tsecretValues,\n\tsplitOptions,\n} from \"../notifications/targets\";\nimport type { AdminContext } from \"./context\";\nimport { apiError, editConflict, json, noContent, notFound, readBody, toIssues, validate, validationFailed } from \"./http\";\n\nfunction kindNamed(type: string): NotifierKind | undefined {\n\treturn config.notifiers.find((kind) => kind.type === type);\n}\n\nconst schemas = new Map<string, Record<string, unknown>>();\n\n/** The kind's options as JSON Schema (what an administrator enters), secret ones marked `writeOnly`. */\nexport function optionsJsonSchema(kind: NotifierKind): Record<string, unknown> {\n\tconst cached = schemas.get(kind.type);\n\tif (cached !== undefined) return cached;\n\tconst schema = z.toJSONSchema(kind.options, { io: \"input\", unrepresentable: \"any\" }) as Record<string, unknown>;\n\tconst properties = schema[\"properties\"] as Record<string, Record<string, unknown>> | undefined;\n\tfor (const key of kind.secretOptions) {\n\t\tconst property = properties?.[key];\n\t\tif (properties !== undefined && property !== undefined) properties[key] = { ...property, writeOnly: true };\n\t}\n\tschemas.set(kind.type, schema);\n\treturn schema;\n}\n\nfunction encryptionUnavailable(error: EncryptionKeyError): Response {\n\treturn apiError(503, \"encryption_key_missing\", `${error.message}. Secret options cannot be saved until it is set.`);\n}\n\n/** Issues for monitors and components that status.config.ts does not have. */\nfunction selectionIssues(monitors: readonly string[] | undefined, components: readonly ComponentRef[] | undefined): ApiIssue[] {\n\tconst issues: ApiIssue[] = [];\n\tmonitors?.forEach((id, index) => {\n\t\tif (findMonitor(id) === undefined) {\n\t\t\tissues.push({ path: [\"monitors\", index], message: `No monitor \"${id}\" in status.config.ts`, code: \"unknown_monitor\", params: { monitor: id } });\n\t\t}\n\t});\n\tcomponents?.forEach((ref, index) => {\n\t\tconst page = findPage(ref.pageId);\n\t\tif (page === undefined) {\n\t\t\tissues.push({\n\t\t\t\tpath: [\"components\", index, \"pageId\"],\n\t\t\t\tmessage: `No page \"${ref.pageId}\" in status.config.ts`,\n\t\t\t\tcode: \"unknown_page\",\n\t\t\t\tparams: { page: ref.pageId },\n\t\t\t});\n\t\t} else if (!page.components.some((component) => component.id === ref.componentId)) {\n\t\t\tissues.push({\n\t\t\t\tpath: [\"components\", index, \"componentId\"],\n\t\t\t\tmessage: `Page \"${ref.pageId}\" has no component \"${ref.componentId}\"`,\n\t\t\t\tcode: \"unknown_component\",\n\t\t\t\tparams: { page: ref.pageId, component: ref.componentId },\n\t\t\t});\n\t\t}\n\t});\n\treturn issues;\n}\n\n/** Validates options against the kind, and that its destination is a public host; issues are located under `options`. */\nfunction validateOptions(kind: NotifierKind, options: Record<string, unknown>): ApiIssue[] {\n\tconst result = kind.options.safeParse(options);\n\tconst issues = result.success ? [] : toIssues(result.error).map((issue) => ({ ...issue, path: [\"options\", ...issue.path] }));\n\tconst problem = destinationProblem(kind, options);\n\tconst destination = destinationOption({ options, secrets: {} }, kind);\n\tif (problem !== null && destination !== undefined) {\n\t\tissues.push({ path: [\"options\", destination], message: problem, code: \"destination_not_public\" });\n\t}\n\treturn issues;\n}\n\n/**\n * Issues for a change of destination: when an edit moves a target to another origin (or\n * its current destination cannot be read), every other secret option it has must be entered\n * again or cleared (`null`), so that no secret it holds is sent to the new destination.\n */\nfunction destinationChangeIssues(\n\tkind: NotifierKind,\n\texisting: { readonly options: Readonly<Record<string, unknown>>; readonly secrets: Readonly<Record<string, string>> },\n\treadable: Readonly<Record<string, unknown>>,\n\tunreadable: readonly string[],\n\tchanges: Readonly<Record<string, unknown>>,\n): ApiIssue[] {\n\tconst destination = destinationOption(existing, kind);\n\tif (destination === undefined || !Object.hasOwn(changes, destination)) return [];\n\tconst before = unreadable.includes(destination) ? undefined : destinationOrigin(readable[destination]);\n\tconst after = destinationOrigin(changes[destination]);\n\tif (before !== undefined && before === after) return [];\n\tconst stored = [...kind.secretOptions, ...Object.keys(existing.secrets)].filter(\n\t\t(key, index, keys) => keys.indexOf(key) === index && Object.hasOwn(existing.secrets, key),\n\t);\n\treturn stored\n\t\t.filter((key) => key !== destination && !Object.hasOwn(changes, key))\n\t\t.map((key) => ({\n\t\t\tpath: [\"options\", key],\n\t\t\tmessage: `The destination changed: enter \"${key}\" again, or set it to null to remove it. Secrets are never sent to a new destination.`,\n\t\t\tcode: \"secret_reentry_required\",\n\t\t\tparams: { option: key, destination },\n\t\t}));\n}\n\nfunction unknownIssue(admin: boolean, events: readonly NotificationEvent[]): ApiIssue[] {\n\treturn !admin && events.includes(\"unknown\")\n\t\t? [{ path: [\"events\"], message: \"Only administrators' targets receive unknown\", code: \"unknown_needs_admin\" }]\n\t\t: [];\n}\n\n/** `GET notifications/kinds`: the kinds registered in status.config.ts, and whether secrets can be encrypted. */\nexport async function kinds(admin: AdminContext): Promise<Response> {\n\tlet encryption: NotifierKindsResponse[\"encryption\"];\n\ttry {\n\t\tconst ring = await keyRing(admin.env);\n\t\tencryption = { configured: true, currentKeyId: ring.currentId, error: null };\n\t} catch (error) {\n\t\tif (!(error instanceof EncryptionKeyError)) throw error;\n\t\tencryption = { configured: false, currentKeyId: null, error: error.message };\n\t}\n\tconst body: NotifierKindsResponse = {\n\t\tkinds: config.notifiers.map(\n\t\t\t(kind): NotifierKindInfo => ({\n\t\t\t\ttype: kind.type,\n\t\t\t\tname: kind.name,\n\t\t\t\tsecretOptions: kind.secretOptions,\n\t\t\t\toptionsSchema: optionsJsonSchema(kind),\n\t\t\t\tmessages: kind.messages ?? {},\n\t\t\t}),\n\t\t),\n\t\tencryption,\n\t};\n\treturn json(body);\n}\n\n/** `GET notifications/targets`: every target, by name. */\nexport async function list(admin: AdminContext): Promise<Response> {\n\tconst targets = await listTargets(admin.env.DB);\n\treturn json({ items: targets.map((target) => publicTarget(target, kindNamed(target.kind))), nextCursor: null });\n}\n\nexport async function get(admin: AdminContext): Promise<Response> {\n\tconst target = await getTarget(admin.env.DB, admin.params[\"id\"] ?? \"\");\n\treturn target === null ? notFound(\"notification target\") : json(publicTarget(target, kindNamed(target.kind)));\n}\n\nexport async function create(admin: AdminContext): Promise<Response> {\n\tconst body = await readBody(admin.request, createNotificationTargetSchema);\n\tif (!body.ok) return body.response;\n\tconst input = body.value;\n\tconst kind = kindNamed(input.kind);\n\tif (kind === undefined) {\n\t\treturn validationFailed([\n\t\t\t{ path: [\"kind\"], message: `No notifier kind \"${input.kind}\" in status.config.ts`, code: \"unknown_kind\", params: { kind: input.kind } },\n\t\t]);\n\t}\n\tconst issues = [...validateOptions(kind, input.options), ...selectionIssues(input.monitors, input.components)];\n\tif (issues.length > 0) return validationFailed(issues);\n\tconst id = crypto.randomUUID();\n\tlet split: Awaited<ReturnType<typeof splitOptions>>;\n\ttry {\n\t\tsplit = await splitOptions(admin.env, id, kind, input.options);\n\t} catch (error) {\n\t\tif (error instanceof EncryptionKeyError) return encryptionUnavailable(error);\n\t\tthrow error;\n\t}\n\tconst fields: TargetFields = {\n\t\tname: input.name,\n\t\t...split,\n\t\tadmin: input.admin,\n\t\tenabled: input.enabled,\n\t\tevents: input.events ?? (input.admin ? [...DEFAULT_TARGET_EVENTS, \"unknown\"] : DEFAULT_TARGET_EVENTS),\n\t\tallMonitors: input.allMonitors,\n\t\tmonitors: input.monitors,\n\t\tcomponents: input.components,\n\t};\n\tconst target = await insertTarget(admin.env.DB, id, kind.type, fields, admin.actor);\n\treturn json(publicTarget(target, kind), 201);\n}\n\nexport async function patch(admin: AdminContext): Promise<Response> {\n\tconst body = await readBody(admin.request, patchNotificationTargetSchema);\n\tif (!body.ok) return body.response;\n\tconst { version, ...changes } = body.value;\n\tconst existing = await getTarget(admin.env.DB, admin.params[\"id\"] ?? \"\");\n\tif (existing === null) return notFound(\"notification target\");\n\tconst current = () => publicTarget(existing, kindNamed(existing.kind));\n\tif (existing.version !== version) return editConflict(current());\n\n\t// Written only when the options change (then all secrets are encrypted with the current key):\n\t// writing back what was read could undo a re-encryption that ran meanwhile.\n\tlet options: TargetChanges[\"options\"];\n\tlet secrets: TargetChanges[\"secrets\"];\n\tconst issues: ApiIssue[] = [];\n\tif (changes.options !== undefined) {\n\t\tconst kind = kindNamed(existing.kind);\n\t\tif (kind === undefined) {\n\t\t\treturn validationFailed([\n\t\t\t\t{\n\t\t\t\t\tpath: [\"options\"],\n\t\t\t\t\tmessage: `Notifier kind \"${existing.kind}\" is no longer in status.config.ts`,\n\t\t\t\t\tcode: \"kind_removed\",\n\t\t\t\t\tparams: { kind: existing.kind },\n\t\t\t\t},\n\t\t\t]);\n\t\t}\n\t\ttry {\n\t\t\tconst readable =\n\t\t\t\tObject.keys(existing.secrets).length === 0\n\t\t\t\t\t? { options: { ...existing.options }, errors: new Map() }\n\t\t\t\t\t: await readSecrets(await keyRing(admin.env), existing, kind);\n\t\t\tconst unreadable = [...readable.errors.keys()];\n\t\t\tconst merged = { ...readable.options };\n\t\t\tfor (const key of unreadable) {\n\t\t\t\t// Undecryptable (its key was removed, or it belongs to another destination): it must be entered again.\n\t\t\t\tif (!Object.hasOwn(changes.options, key)) delete merged[key];\n\t\t\t}\n\t\t\tfor (const [key, value] of Object.entries(changes.options)) {\n\t\t\t\tif (value === null) delete merged[key];\n\t\t\t\telse merged[key] = value;\n\t\t\t}\n\t\t\tissues.push(...destinationChangeIssues(kind, existing, readable.options, unreadable, changes.options));\n\t\t\tissues.push(...validateOptions(kind, merged));\n\t\t\tif (issues.length === 0) ({ options, secrets } = await splitOptions(admin.env, existing.id, kind, merged));\n\t\t} catch (error) {\n\t\t\tif (error instanceof EncryptionKeyError) return encryptionUnavailable(error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\tconst fields: TargetChanges = {\n\t\tname: changes.name ?? existing.name,\n\t\toptions,\n\t\tsecrets,\n\t\tadmin: changes.admin ?? existing.admin,\n\t\tenabled: changes.enabled ?? existing.enabled,\n\t\tevents: changes.events ?? existing.events,\n\t\tallMonitors: changes.allMonitors ?? existing.allMonitors,\n\t\tmonitors: changes.monitors ?? existing.monitors,\n\t\tcomponents: changes.components ?? existing.components,\n\t};\n\tissues.push(...unknownIssue(fields.admin, fields.events), ...selectionIssues(changes.monitors, changes.components));\n\tif (issues.length > 0) return validationFailed(issues);\n\tconst result = await updateTarget(admin.env.DB, existing.id, version, fields, admin.actor);\n\tswitch (result.status) {\n\t\tcase \"not-found\":\n\t\t\treturn notFound(\"notification target\");\n\t\tcase \"conflict\":\n\t\t\treturn editConflict(publicTarget(result.current, kindNamed(result.current.kind)));\n\t\tcase \"updated\":\n\t\t\treturn json(publicTarget(result.value, kindNamed(result.value.kind)));\n\t}\n}\n\nexport async function remove(admin: AdminContext): Promise<Response> {\n\treturn (await deleteTarget(admin.env.DB, admin.params[\"id\"] ?? \"\")) ? noContent() : notFound(\"notification target\");\n}\n\n/** `POST notifications/targets/:id/test`: sends a test notification now, and says whether it worked. */\nexport async function test(admin: AdminContext): Promise<Response> {\n\tconst target = await getTarget(admin.env.DB, admin.params[\"id\"] ?? \"\");\n\tif (target === null) return notFound(\"notification target\");\n\tconst kind = kindNamed(target.kind);\n\tif (kind === undefined) {\n\t\treturn apiError(409, \"kind_not_registered\", `Notifier kind \"${target.kind}\" is no longer in status.config.ts`);\n\t}\n\tlet secrets: string[] = [];\n\tlet result: TestNotificationResult;\n\ttry {\n\t\tconst options = await decryptOptions(admin.env, target, kind);\n\t\tsecrets = secretValues(target, options);\n\t\tconst parsed = kind.options.safeParse(options);\n\t\tif (!parsed.success) {\n\t\t\tresult = { ok: false, error: \"The target's options are no longer valid; edit the target\" };\n\t\t} else if (destinationProblem(kind, options) !== null) {\n\t\t\tresult = { ok: false, error: \"The target's destination is not a public host; edit the target\" };\n\t\t} else {\n\t\t\tawait sendWithTimeout(kind, renderTest(target.name, Date.now(), config.locale, config.timezone), parsed.data);\n\t\t\tresult = { ok: true, error: null };\n\t\t}\n\t} catch (error) {\n\t\tresult = { ok: false, error: describeFailure(error, secrets).message };\n\t}\n\treturn json(result);\n}\n\nconst deliveryQuerySchema = z.object({\n\tstatus: z.enum([\"failed\", \"retrying\", \"sending\", \"sent\"]).default(\"failed\"),\n\tlimit: z.coerce.number().int().min(1).max(LIMITS.pageSize).default(50),\n\tcursor: z\n\t\t.string()\n\t\t.transform((value, ctx) => {\n\t\t\tconst cursor = decodeDeliveryCursor(value);\n\t\t\tif (cursor === undefined) {\n\t\t\t\tctx.addIssue({ code: \"custom\", message: \"Not a cursor from a previous page\" });\n\t\t\t\treturn z.NEVER;\n\t\t\t}\n\t\t\treturn cursor;\n\t\t})\n\t\t.optional(),\n});\n\n/** `GET notifications/deliveries?status=failed`: deliveries by status (default: failed), latest change first. */\nexport async function deliveries(admin: AdminContext): Promise<Response> {\n\tconst query = validate(deliveryQuerySchema, Object.fromEntries(admin.url.searchParams));\n\tif (!query.ok) return query.response;\n\tconst { status, limit, cursor } = query.value;\n\treturn json(await listDeliveries(admin.env.DB, { status, limit, after: cursor }));\n}\n\n/**\n * `POST notifications/re-encrypt`: encrypts every target's secrets with the current key (the\n * first in `NOTIFICATION_KEYS`), for rotating keys (see worker/notifications/crypto.ts), and\n * binds secrets stored before destinations were bound to their target's destination.\n */\nexport async function reEncrypt(admin: AdminContext): Promise<Response> {\n\tlet ring: Awaited<ReturnType<typeof keyRing>>;\n\ttry {\n\t\tring = await keyRing(admin.env);\n\t} catch (error) {\n\t\tif (error instanceof EncryptionKeyError) return encryptionUnavailable(error);\n\t\tthrow error;\n\t}\n\tconst result: { -readonly [K in keyof ReEncryptResult]: ReEncryptResult[K] } & { failed: ReEncryptResult[\"failed\"][number][] } = {\n\t\tcurrentKeyId: ring.currentId,\n\t\treEncrypted: 0,\n\t\tunchanged: 0,\n\t\tfailed: [],\n\t};\n\tfor (const target of await listTargets(admin.env.DB)) {\n\t\tconst kind = kindNamed(target.kind);\n\t\t// Up to date: the current key, and bound to the destination (values from before are not).\n\t\tif (secretsUpToDate(ring, target, kind)) {\n\t\t\tresult.unchanged++;\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst { options, errors } = await readSecrets(ring, target, kind);\n\t\t\tconst [failure] = errors.values();\n\t\t\tif (failure !== undefined) throw failure;\n\t\t\tconst destination = destinationOption(target, kind);\n\t\t\tconst origin = destination === undefined ? undefined : destinationOrigin(options[destination]);\n\t\t\tconst secrets: Record<string, string> = {};\n\t\t\tfor (const key of Object.keys(target.secrets)) {\n\t\t\t\tsecrets[key] = await encryptSecret(ring, target.id, key, JSON.stringify(options[key]), key === destination ? undefined : origin);\n\t\t\t}\n\t\t\tif (await replaceSecrets(admin.env.DB, target.id, target.secrets, secrets)) result.reEncrypted++;\n\t\t\t// Otherwise it was saved meanwhile, which encrypted it with the current key.\n\t\t\telse result.unchanged++;\n\t\t} catch (error) {\n\t\t\tresult.failed.push({ id: target.id, name: target.name, error: error instanceof Error ? error.message : String(error) });\n\t\t}\n\t}\n\tconsole.log(`Re-encrypted the secrets of ${result.reEncrypted} notification targets with key \"${ring.currentId}\"`);\n\treturn json(result satisfies ReEncryptResult);\n}\n","/** `/api/admin/me`, `/api/admin/pages`, page appearance and its images. */\nimport {\n\ttype AdminMe,\n\ttype AdminPagesResponse,\n\ttype ApiIssue,\n\tIMAGE_TYPES,\n\tLIMITS,\n\ttype PageAppearance,\n\tpageAppearanceSchema,\n} from \"../../shared/admin-api\";\nimport { config } from \"../config\";\nimport { getAppearance, putAppearance } from \"../db/appearance\";\nimport { checkImage, extensionOf, imageExists, removeUnusedImages, storeImage, uploadsBucket } from \"../uploads\";\nimport { type AdminContext, findPage, publicPageChanged, publicPageChanging } from \"./context\";\nimport { apiError, editConflict, json, notFound, readBody, readCapped, validationFailed } from \"./http\";\n\n/** The signed-in administrator, as the admin UI shows it. */\nexport async function me(admin: AdminContext): Promise<Response> {\n\treturn json({ identity: admin.identity, author: admin.actor.kind === \"admin\" ? admin.actor.name : null } satisfies AdminMe);\n}\n\n/** The pages and components of status.config.ts, for the admin UI's forms. */\nexport async function pages(admin: AdminContext): Promise<Response> {\n\treturn json({\n\t\tpages: config.pages.map((page) => ({\n\t\t\tid: page.id,\n\t\t\ttemplate: page.template,\n\t\t\tincidents: page.incidents,\n\t\t\tcomponents: page.components.map((component) => ({\n\t\t\t\tid: component.id,\n\t\t\t\tname: component.name,\n\t\t\t\tmonitors: component.monitors,\n\t\t\t})),\n\t\t})),\n\t\tuploads: uploadsBucket(admin.env) !== undefined,\n\t} satisfies AdminPagesResponse);\n}\n\nexport async function getPageAppearance(admin: AdminContext): Promise<Response> {\n\tconst page = findPage(admin.params[\"pageId\"] ?? \"\");\n\tif (page === undefined) return notFound(\"page\");\n\treturn json(await getAppearance(admin.env.DB, page.id));\n}\n\nfunction uploadsUnavailable(): Response {\n\treturn apiError(501, \"uploads_unavailable\", \"Images cannot be uploaded: the Worker has no R2 bucket (UPLOADS binding)\");\n}\n\n/**\n * Problems with the images an edit names. An image the appearance names now (in either field)\n * is accepted as it is, even without the bucket, so that the other fields can still be saved\n * after the binding was removed. Any other must be in the bucket.\n */\nasync function imageIssues(\n\tenv: Env,\n\tcurrent: PageAppearance,\n\timages: Readonly<Record<\"logoImage\" | \"faviconImage\", string | null | undefined>>,\n): Promise<ApiIssue[]> {\n\tconst saved = new Set([current.logoImage, current.faviconImage]);\n\tconst named = Object.entries(images).filter(\n\t\t(entry): entry is [string, string] => typeof entry[1] === \"string\" && !saved.has(entry[1]),\n\t);\n\tif (named.length === 0) return [];\n\tconst bucket = uploadsBucket(env);\n\tconst found = await Promise.all(named.map(([, id]) => (bucket === undefined ? false : imageExists(bucket, current.pageId, id))));\n\treturn named.flatMap(([field, id], index) =>\n\t\tfound[index]\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\tbucket === undefined\n\t\t\t\t\t\t? { path: [field], message: \"Images cannot be used: the Worker has no R2 bucket\", code: \"uploads_unavailable\" }\n\t\t\t\t\t\t: { path: [field], message: `No uploaded image \"${id}\"; upload it again`, code: \"unknown_image\" },\n\t\t\t\t],\n\t);\n}\n\nexport async function putPageAppearance(admin: AdminContext): Promise<Response> {\n\tconst page = findPage(admin.params[\"pageId\"] ?? \"\");\n\tif (page === undefined) return notFound(\"page\");\n\tconst body = await readBody(admin.request, pageAppearanceSchema);\n\tif (!body.ok) return body.response;\n\tconst { version, ...fields } = body.value;\n\t// Images are checked against the version the edit replaces; the write below is conditional on it.\n\tconst current = await getAppearance(admin.env.DB, page.id);\n\tif (current.version !== version) return editConflict(current);\n\tconst issues = await imageIssues(admin.env, current, { logoImage: fields.logoImage, faviconImage: fields.faviconImage });\n\tif (issues.length > 0) return validationFailed(issues);\n\tawait publicPageChanging(admin, page.id);\n\tconst result = await putAppearance(admin.env.DB, page.id, version, fields, admin.actor);\n\tif (result.status !== \"updated\") {\n\t\treturn result.status === \"conflict\" ? editConflict(result.current) : notFound(\"page\");\n\t}\n\tawait publicPageChanged(admin, page.id);\n\tconst bucket = uploadsBucket(admin.env);\n\tif (bucket !== undefined) admin.ctx.waitUntil(removeUnused(admin.env.DB, bucket, page.id));\n\treturn json(result.value);\n}\n\n/**\n * Deletes the page's images that its appearance no longer names (see `removeUnusedImages`).\n * The appearance is read again first, which keeps the images of a save made before then; one\n * made during the deletion is the case worker/uploads.ts describes. Never fails.\n */\nasync function removeUnused(db: D1Database, bucket: R2Bucket, pageId: string): Promise<void> {\n\ttry {\n\t\tconst current = await getAppearance(db, pageId);\n\t\tconst keep = new Set([current.logoImage, current.faviconImage].filter((id) => id !== null));\n\t\tawait removeUnusedImages(bucket, pageId, keep);\n\t} catch (error) {\n\t\tconsole.warn(`Could not delete the unused images of page \"${pageId}\"`, error);\n\t}\n}\n\n/**\n * `POST /api/admin/pages/:pageId/images`: stores the request body, an image of the type its\n * `Content-Type` names, and answers with its ID ({@link UploadedImage}), which the appearance\n * then names. Only image types are accepted, which an HTML form cannot send and a cross-site\n * script cannot send without a CORS preflight, as for JSON bodies (see csrf.ts).\n */\nexport async function uploadImage(admin: AdminContext): Promise<Response> {\n\tconst page = findPage(admin.params[\"pageId\"] ?? \"\");\n\tif (page === undefined) return notFound(\"page\");\n\tconst bucket = uploadsBucket(admin.env);\n\tif (bucket === undefined) return uploadsUnavailable();\n\tconst declared = extensionOf(admin.request.headers.get(\"Content-Type\"));\n\tif (declared === null) {\n\t\treturn apiError(415, \"unsupported_media_type\", `Send the image as its own Content-Type: one of ${Object.keys(IMAGE_TYPES).join(\", \")}`);\n\t}\n\tconst bytes = await readCapped(admin.request, LIMITS.imageBytes);\n\tif (bytes === null) {\n\t\treturn apiError(413, \"payload_too_large\", `The image must be at most ${LIMITS.imageBytes} bytes`);\n\t}\n\tconst check = checkImage(bytes, declared);\n\tif (!check.ok) {\n\t\treturn apiError(400, \"invalid_image\", `The file is not a valid image of the declared type (${check.reason})`, { reason: check.reason });\n\t}\n\treturn json(await storeImage(bucket, page.id, bytes, check.extension), 201);\n}\n","/**\n * The admin API (`/api/admin/*`) and the gate in front of the admin UI (`/admin`,\n * `/admin/*`). Routes are listed in {@link ROUTES} and documented in the README.\n *\n * Every request is authenticated first, whatever its method and path, and a failure gets\n * the same 403 everywhere, so unauthenticated callers learn nothing about what exists. Then cross-site requests are rejected (see csrf.ts), and the schema of\n * the D1 database is brought up to date before the first query.\n */\nimport adminHtml from \"virtual:cf-workers-status-page/admin-html\";\nimport { ensureSchema } from \"../db/schema\";\nimport { ADMIN_AUTH, type AdminAuthOptions, authenticateAdmin, authorName } from \"./auth\";\nimport type { AdminContext } from \"./context\";\nimport { crossSiteReason } from \"./csrf\";\nimport { apiError, forbidden, notFound } from \"./http\";\nimport * as incidents from \"./incidents\";\nimport * as maintenance from \"./maintenance\";\nimport * as monitors from \"./monitors\";\nimport * as notifications from \"./notifications\";\nimport * as pages from \"./pages\";\n\ntype Handler = (admin: AdminContext) => Promise<Response>;\n\ninterface Route {\n\treadonly method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\t/** Path segments after `/api/admin/`; `:name` matches one segment as a parameter. */\n\treadonly path: string;\n\treadonly handler: Handler;\n\t/** Whether the handler uses D1. */\n\treadonly db: boolean;\n}\n\nexport const ROUTES: readonly Route[] = [\n\t{ method: \"GET\", path: \"me\", handler: pages.me, db: false },\n\t{ method: \"GET\", path: \"pages\", handler: pages.pages, db: false },\n\t{ method: \"GET\", path: \"pages/:pageId/appearance\", handler: pages.getPageAppearance, db: true },\n\t{ method: \"PUT\", path: \"pages/:pageId/appearance\", handler: pages.putPageAppearance, db: true },\n\t{ method: \"POST\", path: \"pages/:pageId/images\", handler: pages.uploadImage, db: false },\n\t{ method: \"GET\", path: \"incidents\", handler: incidents.list, db: true },\n\t{ method: \"POST\", path: \"incidents\", handler: incidents.create, db: true },\n\t{ method: \"GET\", path: \"incidents/:id\", handler: incidents.get, db: true },\n\t{ method: \"PATCH\", path: \"incidents/:id\", handler: incidents.patch, db: true },\n\t{ method: \"DELETE\", path: \"incidents/:id\", handler: incidents.remove, db: true },\n\t{ method: \"POST\", path: \"incidents/:id/updates\", handler: incidents.postUpdate, db: true },\n\t{ method: \"POST\", path: \"incidents/:id/resolve\", handler: incidents.resolve, db: true },\n\t{ method: \"GET\", path: \"maintenance\", handler: maintenance.list, db: true },\n\t{ method: \"POST\", path: \"maintenance\", handler: maintenance.create, db: true },\n\t{ method: \"GET\", path: \"maintenance/:id\", handler: maintenance.get, db: true },\n\t{ method: \"PATCH\", path: \"maintenance/:id\", handler: maintenance.patch, db: true },\n\t{ method: \"DELETE\", path: \"maintenance/:id\", handler: maintenance.remove, db: true },\n\t{ method: \"GET\", path: \"monitors\", handler: monitors.list, db: false },\n\t{ method: \"DELETE\", path: \"monitors/:id\", handler: monitors.purge, db: false },\n\t{ method: \"GET\", path: \"notifications/kinds\", handler: notifications.kinds, db: false },\n\t{ method: \"GET\", path: \"notifications/targets\", handler: notifications.list, db: true },\n\t{ method: \"POST\", path: \"notifications/targets\", handler: notifications.create, db: true },\n\t{ method: \"GET\", path: \"notifications/targets/:id\", handler: notifications.get, db: true },\n\t{ method: \"PATCH\", path: \"notifications/targets/:id\", handler: notifications.patch, db: true },\n\t{ method: \"DELETE\", path: \"notifications/targets/:id\", handler: notifications.remove, db: true },\n\t{ method: \"POST\", path: \"notifications/targets/:id/test\", handler: notifications.test, db: true },\n\t{ method: \"GET\", path: \"notifications/deliveries\", handler: notifications.deliveries, db: true },\n\t{ method: \"POST\", path: \"notifications/re-encrypt\", handler: notifications.reEncrypt, db: true },\n];\n\nconst API_PREFIX = \"/api/admin\";\n\nexport function isAdminApiPath(pathname: string): boolean {\n\treturn pathname === API_PREFIX || pathname.startsWith(`${API_PREFIX}/`);\n}\n\n/** The admin UI's paths: they go through the Worker (`run_worker_first` in wrangler.jsonc). */\nexport function isAdminUiPath(pathname: string): boolean {\n\treturn pathname === \"/admin\" || pathname.startsWith(\"/admin/\");\n}\n\nfunction match(pattern: string, segments: readonly string[]): Record<string, string> | undefined {\n\tconst parts = pattern.split(\"/\");\n\tif (parts.length !== segments.length) return undefined;\n\tconst params: Record<string, string> = {};\n\tfor (const [index, part] of parts.entries()) {\n\t\tconst segment = segments[index] as string;\n\t\tif (part.startsWith(\":\")) params[part.slice(1)] = segment;\n\t\telse if (part !== segment) return undefined;\n\t}\n\treturn params;\n}\n\n/** Path segments after the prefix, decoded; `undefined` when one cannot be decoded. */\nfunction segmentsOf(pathname: string): string[] | undefined {\n\ttry {\n\t\treturn pathname\n\t\t\t.slice(API_PREFIX.length)\n\t\t\t.split(\"/\")\n\t\t\t.filter((segment) => segment !== \"\")\n\t\t\t.map(decodeURIComponent);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Handles a request under `/api/admin`. */\nexport async function handleAdminApi(\n\trequest: Request,\n\tenv: Env,\n\tctx: ExecutionContext,\n\toptions: AdminAuthOptions = ADMIN_AUTH,\n): Promise<Response> {\n\tconst identity = await authenticateAdmin(request, env, ctx, options);\n\tif (identity === null) return forbidden();\n\tif (crossSiteReason(request) !== null) {\n\t\treturn apiError(403, \"cross_site_request\", \"Requests from other sites are not accepted\");\n\t}\n\n\tconst url = new URL(request.url);\n\tconst segments = segmentsOf(url.pathname);\n\tif (segments === undefined) return notFound();\n\tconst matching = ROUTES.flatMap((route) => {\n\t\tconst params = match(route.path, segments);\n\t\treturn params === undefined ? [] : [{ route, params }];\n\t});\n\tif (matching.length === 0) return notFound();\n\t// HEAD is GET without the body.\n\tconst head = request.method === \"HEAD\";\n\tconst method = head ? \"GET\" : request.method;\n\tconst found = matching.find(({ route }) => route.method === method);\n\tif (found === undefined) {\n\t\tconst methods = matching.map(({ route }) => route.method);\n\t\tconst allow = (methods.includes(\"GET\") ? [...methods, \"HEAD\"] : methods).join(\", \");\n\t\treturn apiError(405, \"method_not_allowed\", `Use ${allow}`, { headers: { Allow: allow } });\n\t}\n\n\tlet response: Response;\n\ttry {\n\t\tif (found.route.db) await ensureSchema(env.DB);\n\t\tresponse = await found.route.handler({\n\t\t\trequest,\n\t\t\turl,\n\t\t\tenv,\n\t\t\tctx,\n\t\t\tparams: found.params,\n\t\t\tidentity,\n\t\t\tactor: { kind: \"admin\", name: authorName(identity) },\n\t\t});\n\t} catch (error) {\n\t\tconsole.error(`Admin API ${request.method} ${url.pathname} failed`, error);\n\t\tresponse = apiError(500, \"internal_error\", \"Something went wrong; see the Worker's logs\");\n\t}\n\treturn head ? new Response(null, response) : response;\n}\n\n/**\n * The directory of the admin UI's HTML entry under the dev server (`ADMIN_HTML` in\n * vite.admin.ts); the asset handling redirects `…/index.html` to it.\n */\nconst ADMIN_HTML_DEV_PATH = \"/src/admin/\";\n\n/** On the admin UI's responses: not cached, not framed (clickjacking), not indexed. */\nconst ADMIN_UI_HEADERS = {\n\t\"Cache-Control\": \"no-store\",\n\t\"X-Frame-Options\": \"DENY\",\n\t\"Content-Security-Policy\": \"frame-ancestors 'none'\",\n\t\"X-Robots-Tag\": \"noindex\",\n\t\"X-Content-Type-Options\": \"nosniff\",\n\t\"Referrer-Policy\": \"same-origin\",\n} as const;\n\n/**\n * The admin UI's Content-Security-Policy in a build: its own scripts, styles and API only, so\n * that an injected script (from text an administrator or a notified service wrote) cannot run.\n * Not under the dev server, whose HTML has inline scripts (Vite's client, React refresh); there\n * only `frame-ancestors` applies.\n */\nexport const ADMIN_CSP =\n\t\"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; \" +\n\t\"object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'\";\n\n/**\n * Serves the admin UI to administrators only. It is its own entry, separate from the public\n * SPA, and in a build its HTML is part of the Worker, not a static asset (see vite.admin.ts),\n * so this is the only way to get it. Its scripts and styles under `/assets/` are public\n * static files, like the public SPA's: they are the open-source code of the UI and hold no\n * data; everything the admin UI shows comes from the admin API.\n */\nexport async function serveAdminUi(\n\trequest: Request,\n\tenv: Env,\n\tctx: ExecutionContext,\n\toptions: AdminAuthOptions = ADMIN_AUTH,\n\thtml: string | null = adminHtml,\n): Promise<Response> {\n\tconst identity = await authenticateAdmin(request, env, ctx, options);\n\tif (identity === null) {\n\t\treturn new Response(\"Forbidden: sign in as an administrator to open the admin UI.\\n\", {\n\t\t\tstatus: 403,\n\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\", ...ADMIN_UI_HEADERS },\n\t\t});\n\t}\n\tif (request.method !== \"GET\" && request.method !== \"HEAD\") {\n\t\treturn new Response(\"Method Not Allowed\\n\", {\n\t\t\tstatus: 405,\n\t\t\theaders: { Allow: \"GET, HEAD\", \"Content-Type\": \"text/plain; charset=utf-8\", ...ADMIN_UI_HEADERS },\n\t\t});\n\t}\n\t// Every path under /admin gets the same page; the admin UI routes on the client.\n\tlet response: Response;\n\tif (html !== null) {\n\t\tresponse = new Response(request.method === \"HEAD\" ? null : html, {\n\t\t\theaders: { \"Content-Type\": \"text/html; charset=utf-8\" },\n\t\t});\n\t} else {\n\t\t// Under the dev server: Vite serves the entry with its dev transforms.\n\t\tconst asset = await env.ASSETS.fetch(new Request(new URL(ADMIN_HTML_DEV_PATH, request.url), request));\n\t\tresponse = new Response(asset.body, asset);\n\t}\n\tfor (const [name, value] of Object.entries(ADMIN_UI_HEADERS)) response.headers.set(name, value);\n\tif (html !== null) response.headers.set(\"Content-Security-Policy\", ADMIN_CSP);\n\treturn response;\n}\n","/**\n * The every-minute Cron: reconciliation, `unknown` notifications, and the `down`\n * notifications that maintenance held back.\n *\n * 1. One D1 batch reads the `unknown` alerts already sent and the held-back `down` events\n * (both usually empty).\n * 2. One call to the Reconciler reconciles and reads the snapshots needed: those monitors,\n * and, on runs of `notifications.unknownCheckInterval`, every monitor that could have\n * become late since it was last read (see `Reconciler.cron`).\n * 3. `unknown`: a monitor that is late, or unconfirmed for too long, is notified to\n * administrators' targets once; the D1 record keeps it from being notified again while it\n * stays unknown, and goes when the monitor leaves `unknown`.\n * 4. Maintenance: a held-back `down` is notified once no maintenance covers the monitor,\n * if the monitor is still in that `down`; otherwise it is forgotten.\n * 5. Hourly, old delivery records are deleted.\n *\n * Reconciliation does not depend on D1: if the batch in step 1 fails, the Reconciler is\n * still called, without the `unknown` check.\n */\nimport type { ResolvedMonitor } from \"@naosystem/cf-workers-status-page-core\";\nimport { config, findMonitor } from \"../config\";\nimport {\n\tdeleteSuppressedDown,\n\tdeleteUnknownAlerts,\n\tinsertUnknownAlert,\n\tmaintenanceAt,\n\tpurgeDeliveries,\n\treadCronRecords,\n\trecordPendingEvent,\n\ttype SuppressedDown,\n\ttype UnknownAlertRecord,\n} from \"../db/notifications\";\nimport { ensureSchema } from \"../db/schema\";\nimport type { MonitorSnapshot } from \"../monitor\";\nimport { configuredMonitors, type CronReport, reconcilerStub } from \"../reconciler\";\nimport { afterMaintenanceEvent, type MonitorEvent } from \"./events\";\nimport { enqueue } from \"./queue\";\nimport { monitorComponents } from \"./render\";\nimport { suppressedByMaintenance } from \"./rules\";\nimport { evaluateUnknown, type UnknownAlert, unknownAction, unknownCheckDue, unknownEventId } from \"./unknown\";\n\n/** Delivery records are kept this long: duplicates arrive within hours, and failures stay listed this long. */\nexport const DELIVERY_RETENTION_MS = 30 * 24 * 3_600_000;\nconst HOUR_MS = 3_600_000;\n\nexport interface CronOutcome {\n\treadonly report: CronReport;\n\treadonly unknownNotified: readonly string[];\n\treadonly unknownCleared: readonly string[];\n\treadonly maintenanceNotified: readonly string[];\n}\n\n/** Runs the Cron's work for the run scheduled at `scheduledTime`. */\nexport async function runCron(env: Env, scheduledTime: number): Promise<CronOutcome> {\n\tlet records: Awaited<ReturnType<typeof readCronRecords>> | null = null;\n\ttry {\n\t\tawait ensureSchema(env.DB);\n\t\trecords = await readCronRecords(env.DB);\n\t} catch (error) {\n\t\tconsole.error(\"Notifications: could not read D1; skipping this run's unknown and maintenance checks\", error);\n\t}\n\tconst unknownCheck = records !== null && unknownCheckDue(scheduledTime, config.notifications.unknownCheckIntervalMs);\n\tconst alwaysRead = records === null ? [] : [...(unknownCheck ? records.alerts.keys() : []), ...records.suppressed.map((down) => down.monitorId)];\n\n\tconst report = await reconcilerStub(env).cron({\n\t\tversionId: env.CF_VERSION_METADATA.id,\n\t\tmonitors: configuredMonitors(),\n\t\tunknownCheck,\n\t\talwaysRead: [...new Set(alwaysRead)].filter((id) => findMonitor(id) !== undefined),\n\t});\n\tfor (const failure of report.readFailures) console.warn(`Could not read monitor \"${failure.monitorId}\": ${failure.reason}`);\n\tconst outcome = { report, unknownNotified: [] as string[], unknownCleared: [] as string[], maintenanceNotified: [] as string[] };\n\tif (records === null) return outcome;\n\n\tconst snapshots = new Map(report.snapshots.map((snapshot) => [snapshot.monitorId, snapshot]));\n\tconst now = Date.now();\n\tconst tasks: Promise<void>[] = [];\n\tif (unknownCheck) tasks.push(checkUnknown(env, records.alerts, snapshots, report.unreachable, now, outcome));\n\ttasks.push(followUpMaintenance(env, records.suppressed, snapshots, now, outcome.maintenanceNotified));\n\tif (scheduledTime % HOUR_MS < 60_000) {\n\t\ttasks.push(\n\t\t\tpurgeDeliveries(env.DB, now - DELIVERY_RETENTION_MS).then((deleted) => {\n\t\t\t\tif (deleted > 0) console.log(`Notifications: deleted ${deleted} delivery records older than 30 days`);\n\t\t\t}),\n\t\t);\n\t}\n\tconst settled = await Promise.allSettled(tasks);\n\tfor (const result of settled) if (result.status === \"rejected\") console.error(\"Notifications: Cron task failed\", result.reason);\n\treturn outcome;\n}\n\n/** The `unknown` event for `monitor`, as administrators' targets receive it; without a snapshot when its object does not answer. */\nexport function unknownEvent(monitor: ResolvedMonitor, snapshot: MonitorSnapshot | null, alert: UnknownAlert, now: number): MonitorEvent {\n\tconst previous = snapshot?.current?.state;\n\treturn {\n\t\tid: unknownEventId(monitor.id, alert.since),\n\t\tevent: \"unknown\",\n\t\tmonitorId: monitor.id,\n\t\tstate: \"unknown\",\n\t\tpreviousState: previous === \"up\" || previous === \"degraded\" || previous === \"down\" ? previous : null,\n\t\tsince: alert.since,\n\t\tdetectedAt: now,\n\t\tpreviousSince: snapshot?.current?.since ?? null,\n\t\tmessage: snapshot?.lastCheck?.message?.slice(0, 500) ?? null,\n\t\tunknown: { reason: alert.reason, lastAt: alert.lastAt },\n\t};\n}\n\nasync function checkUnknown(\n\tenv: Env,\n\talerts: ReadonlyMap<string, UnknownAlertRecord>,\n\tsnapshots: ReadonlyMap<string, MonitorSnapshot>,\n\tunreachable: CronReport[\"unreachable\"],\n\tnow: number,\n\toutcome: { unknownNotified: string[]; unknownCleared: string[] },\n): Promise<void> {\n\tconst clear: string[] = [];\n\t// Records of monitors no longer configured go: they are not supposed to run.\n\tfor (const id of alerts.keys()) if (findMonitor(id) === undefined) clear.push(id);\n\tconst unreachableSince = new Map(unreachable.map((entry) => [entry.monitorId, entry.since]));\n\n\tfor (const monitor of config.monitors) {\n\t\tconst snapshot = snapshots.get(monitor.id) ?? null;\n\t\tconst since = unreachableSince.get(monitor.id);\n\t\tlet alert: UnknownAlert | null;\n\t\tif (snapshot !== null) {\n\t\t\tconst evaluation = evaluateUnknown(snapshot, monitor.timeoutMs, now);\n\t\t\tconst action = unknownAction(evaluation, alerts.has(monitor.id));\n\t\t\tif (action === \"clear\") clear.push(monitor.id);\n\t\t\talert = action === \"notify\" ? evaluation.alert : null;\n\t\t} else if (since !== undefined && !alerts.has(monitor.id)) {\n\t\t\t// Its object does not answer although it could be late by now: unknown, as it cannot be checked.\n\t\t\talert = { reason: \"unreachable\", since, lastAt: since };\n\t\t} else {\n\t\t\t// Not read this run: it cannot have become unknown since it was last read (see Reconciler.cron).\n\t\t\tcontinue;\n\t\t}\n\t\tif (alert === null) continue;\n\t\t// Queue first, then record: if recording fails, the next run queues the same event ID\n\t\t// again, which deliveries drop as a duplicate.\n\t\tawait enqueue(env, [{ type: \"event\", v: 1, event: unknownEvent(monitor, snapshot, alert, now) }]);\n\t\tawait insertUnknownAlert(env.DB, { monitorId: monitor.id, since: alert.since, reason: alert.reason }, now);\n\t\toutcome.unknownNotified.push(monitor.id);\n\t\tconsole.warn(`Monitor \"${monitor.id}\" is unknown (${alert.reason}); notified administrators`);\n\t}\n\tawait deleteUnknownAlerts(env.DB, clear);\n\toutcome.unknownCleared.push(...clear);\n}\n\nasync function followUpMaintenance(\n\tenv: Env,\n\tsuppressed: readonly SuppressedDown[],\n\tsnapshots: ReadonlyMap<string, MonitorSnapshot>,\n\tnow: number,\n\tnotified: string[],\n): Promise<void> {\n\tfor (const down of suppressed) {\n\t\tconst monitor = findMonitor(down.monitorId);\n\t\tif (monitor === undefined) {\n\t\t\tawait deleteSuppressedDown(env.DB, down.monitorId, down.since);\n\t\t\tcontinue;\n\t\t}\n\t\tconst snapshot = snapshots.get(monitor.id);\n\t\tif (snapshot === undefined) continue; // Not read this run (it failed): next run.\n\t\tconst current = snapshot.current;\n\t\tif (current?.state !== \"down\" || current.since !== down.since) {\n\t\t\t// It recovered, or changed state, during the maintenance: nothing to notify.\n\t\t\tawait deleteSuppressedDown(env.DB, down.monitorId, down.since);\n\t\t\tcontinue;\n\t\t}\n\t\tconst refs = monitorComponents(config.pages, monitor.id);\n\t\tconst windows = await maintenanceAt(env.DB, [...new Set(refs.map((ref) => ref.pageId))], now);\n\t\tif (suppressedByMaintenance(refs, windows, now)) continue; // Still under maintenance.\n\t\tconst followUp = afterMaintenanceEvent(down.event, now);\n\t\t// Before it is queued: a recovery handed over by the queue before it must wait for it.\n\t\tawait recordPendingEvent(env.DB, followUp, now);\n\t\tawait enqueue(env, [{ type: \"event\", v: 1, event: followUp }]);\n\t\tawait deleteSuppressedDown(env.DB, down.monitorId, down.since);\n\t\tnotified.push(monitor.id);\n\t\tconsole.log(`Monitor \"${monitor.id}\" is still down after maintenance; notifying`);\n\t}\n}\n","import { WorkerEntrypoint } from \"cloudflare:workers\";\nimport { runCheck } from \"@naosystem/cf-workers-status-page-core\";\nimport { type CheckOutcome, checkError, normalizeResult } from \"./check-result\";\nimport { config, RESERVED_SECRETS } from \"./config\";\nimport { CLOUDFLARE_RUNNER, RUNNER_GRACE_MS, USER_AGENT } from \"./runners\";\n\nexport interface RunRequest {\n\t/** The monitor to check, as configured in the version of the Worker this runner runs. */\n\treadonly monitorId: string;\n}\n\n/** The runner's fetch: the global fetch with the runner's User-Agent applied. */\nexport function runnerFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n\tconst request = new Request(input, init);\n\tif (!request.headers.has(\"User-Agent\")) request.headers.set(\"User-Agent\", USER_AGENT);\n\t// Looked up at call time, so that tests can replace the global fetch.\n\treturn globalThis.fetch(request);\n}\n\n/**\n * The built-in runner: runs checks from the Cloudflare network, inside this\n * Worker. Monitor DOs call it through `this.ctx.exports.CloudflareRunner`, so it needs no\n * binding and is deployed with the hub by one Deploy button.\n *\n * It provides the `fetch` capability declared in `CLOUDFLARE_RUNNER`, applies its\n * User-Agent, resolves `secret()` references from the Worker's secrets (`env`) and runs the\n * check with `runCheck` from core. See `RUNNER_GRACE_MS` for how timeouts combine.\n */\nexport class CloudflareRunner extends WorkerEntrypoint<Env> {\n\tasync run(request: RunRequest): Promise<CheckOutcome> {\n\t\tconst monitor = config.monitors.find((candidate) => candidate.id === request.monitorId);\n\t\tif (monitor === undefined) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: { name: \"UnknownMonitorError\", message: `Monitor \"${request.monitorId}\" is not configured` },\n\t\t\t};\n\t\t}\n\t\tconst timeoutMs = Math.min(monitor.timeoutMs, CLOUDFLARE_RUNNER.maxTimeoutMs);\n\t\tconst env: Readonly<Record<string, unknown>> = this.env as unknown as Record<string, unknown>;\n\t\ttry {\n\t\t\tconst result = await runCheck(\n\t\t\t\t{ provider: monitor.provider, options: monitor.options, timeoutMs },\n\t\t\t\t{\n\t\t\t\t\tfetch: runnerFetch as typeof fetch,\n\t\t\t\t\tsignal: AbortSignal.timeout(timeoutMs + RUNNER_GRACE_MS),\n\t\t\t\t\tsecret: (name) => {\n\t\t\t\t\t\t// Also refused when the configuration is loaded; never handed to a check.\n\t\t\t\t\t\tif (RESERVED_SECRETS.includes(name)) return undefined;\n\t\t\t\t\t\tconst value = env[name];\n\t\t\t\t\t\treturn typeof value === \"string\" ? value : undefined;\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t\treturn normalizeResult(result);\n\t\t} catch (error) {\n\t\t\treturn { ok: false, error: checkError(error) };\n\t\t}\n\t}\n}\n","import { handleAdminApi, isAdminApiPath, isAdminUiPath, serveAdminUi } from \"./admin\";\nimport { handleNotificationBatch } from \"./notifications/consumer\";\nimport { runCron } from \"./notifications/cron\";\nimport { handlePublicApi, isPublicApiPath } from \"./public\";\nimport { RequestReconciler } from \"./reconciler\";\n\nexport { CloudflareRunner } from \"./cloudflare-runner\";\nexport { Monitor } from \"./monitor\";\nexport { PublicApi } from \"./public\";\nexport { Reconciler } from \"./reconciler\";\nexport { StatusPage } from \"./status-page\";\n\nconst requestReconciler = new RequestReconciler();\n\n/** For the health check and errors: browsers and proxies must not keep them. (Workers Cache is off for this entrypoint.) */\nconst NO_STORE = { \"Cache-Control\": \"no-store\" } as const;\n\nexport default {\n\tasync fetch(request, env, ctx): Promise<Response> {\n\t\t// Starts new Monitor DOs after a deploy, in the background.\n\t\trequestReconciler.trigger(env, ctx);\n\n\t\tconst url = new URL(request.url);\n\n\t\t// Admin API and admin UI: administrators only.\n\t\tif (isAdminApiPath(url.pathname)) return handleAdminApi(request, env, ctx);\n\t\tif (isAdminUiPath(url.pathname)) return serveAdminUi(request, env, ctx);\n\n\t\t// Public API: through the cached `PublicApi` entrypoint.\n\t\tif (isPublicApiPath(url.pathname)) return handlePublicApi(request, env, ctx);\n\n\t\tif (request.method === \"GET\" && url.pathname === \"/api/health\") {\n\t\t\treturn Response.json({ ok: true }, { headers: NO_STORE });\n\t\t}\n\n\t\tif (url.pathname.startsWith(\"/api/\")) {\n\t\t\treturn Response.json({ error: \"not_found\", message: \"No such resource\" }, { status: 404, headers: NO_STORE });\n\t\t}\n\n\t\t// Only paths in `run_worker_first` reach the Worker (see `assets` in wrangler.jsonc).\n\t\treturn new Response(\"Not Found\", { status: 404, headers: NO_STORE });\n\t},\n\n\t// Runs every minute (`triggers.crons` in wrangler.jsonc): starts and stops Monitor DOs after\n\t// a deploy, and periodically re-checks that every monitor is running; notifies\n\t// `unknown` monitors and the `down` that maintenance held back.\n\tasync scheduled(controller, env) {\n\t\tconst { report } = await runCron(env, controller.scheduledTime);\n\t\tif (report.reconcile.status === \"incomplete\") {\n\t\t\tconsole.warn(`Reconciliation incomplete: ${report.reconcile.failures.length} of ${report.reconcile.synced} monitors`);\n\t\t}\n\t},\n\n\t// Consumer of the notification queue and of its dead letter queue.\n\tasync queue(batch, env, ctx) {\n\t\tawait handleNotificationBatch(batch, env, ctx);\n\t},\n} satisfies ExportedHandler<Env>;\n"],"mappings":";;;;;;;;AAoCA,IAAa,mBAAmB;AAEhC,IAAa,gBAAwC;CACpD;EACC,SAAS;EACT,MAAM;EACN,YAAY;GAYX;;;;;;;;;;;;;;;;GAiBA;GAEA;GAGA;;;;;;;;;GASA;GAEA;;;;;;;;;;;;;;GAeA;GAEA;GAIA;;;;;;;;;;EAUD;C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