@cosmicdrift/kumiko-samples 0.406.0 → 0.410.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +31 -4
  3. package/packages/bundled-features/src/account-security/feature.ts +9 -1
  4. package/packages/bundled-features/src/admin-shell/changes.json +6 -0
  5. package/packages/bundled-features/src/admin-shell/feature.ts +4 -1
  6. package/packages/bundled-features/src/agent-tools/agent-manifest.ts +1 -0
  7. package/packages/bundled-features/src/agent-tools/changes.json +6 -0
  8. package/packages/bundled-features/src/agent-tools/tool-catalog.ts +1 -0
  9. package/packages/bundled-features/src/agent-tools/types.ts +4 -0
  10. package/packages/bundled-features/src/audit/event-classification.ts +1 -0
  11. package/packages/bundled-features/src/auth-email-password/bootstrap.ts +1 -0
  12. package/packages/bundled-features/src/auth-email-password/errors.ts +18 -66
  13. package/packages/bundled-features/src/auth-email-password/handlers/login-options.query.ts +1 -1
  14. package/packages/bundled-features/src/auth-email-password/handlers/self-registration-status.query.ts +1 -1
  15. package/packages/bundled-features/src/auth-email-password/web/auth-client.ts +30 -64
  16. package/packages/bundled-features/src/auth-email-password/web/auth-redirect.ts +2 -2
  17. package/packages/bundled-features/src/auth-email-password/web/confirm-account-unlock-screen.tsx +20 -66
  18. package/packages/bundled-features/src/auth-email-password/web/index.ts +1 -0
  19. package/packages/bundled-features/src/auth-email-password/web/read-path-param.ts +8 -0
  20. package/packages/bundled-features/src/auth-email-password/web/return-path.ts +3 -2
  21. package/packages/bundled-features/src/auth-email-password/web/token-confirm-screen.tsx +97 -0
  22. package/packages/bundled-features/src/auth-email-password/web/verify-email-screen.tsx +20 -68
  23. package/packages/bundled-features/src/auth-foundation/boot-checks.ts +22 -15
  24. package/packages/bundled-features/src/auth-foundation/boot-rules.ts +33 -0
  25. package/packages/bundled-features/src/auth-mfa/errors.ts +12 -42
  26. package/packages/bundled-features/src/auth-mfa/feature-exports.ts +6 -45
  27. package/packages/bundled-features/src/auth-mfa/feature.ts +8 -19
  28. package/packages/bundled-features/src/auth-mfa/web/mfa-client.ts +19 -33
  29. package/packages/bundled-features/src/billing-foundation/consumer-protection/termination-notify.ts +1 -0
  30. package/packages/bundled-features/src/billing-foundation/web/plan-price.ts +20 -7
  31. package/packages/bundled-features/src/cap-counter/stock-cap-guard.ts +1 -0
  32. package/packages/bundled-features/src/channel-in-app/changes.json +7 -0
  33. package/packages/bundled-features/src/channel-in-app/feature.ts +2 -0
  34. package/packages/bundled-features/src/channel-in-app/handlers/read-state-by-keys.query.ts +35 -0
  35. package/packages/bundled-features/src/channel-in-app/in-app-channel.ts +1 -0
  36. package/packages/bundled-features/src/channel-in-app/tables.ts +5 -1
  37. package/packages/bundled-features/src/compliance-profiles/handlers/sub-processors.query.ts +4 -1
  38. package/packages/bundled-features/src/contact/challenge.ts +41 -0
  39. package/packages/bundled-features/src/contact/changes.json +33 -0
  40. package/packages/bundled-features/src/contact/client/contact-client-source.ts +203 -0
  41. package/packages/bundled-features/src/contact/client/contact-website-client.ts +29 -0
  42. package/packages/bundled-features/src/contact/client/index.ts +9 -0
  43. package/packages/bundled-features/src/contact/entity.ts +168 -0
  44. package/packages/bundled-features/src/contact/feature.ts +174 -0
  45. package/packages/bundled-features/src/contact/handlers/access.ts +17 -0
  46. package/packages/bundled-features/src/contact/handlers/attempts.ts +76 -0
  47. package/packages/bundled-features/src/contact/handlers/challenge.query.ts +44 -0
  48. package/packages/bundled-features/src/contact/handlers/forward-request.write.ts +98 -0
  49. package/packages/bundled-features/src/contact/handlers/mark-done.write.ts +40 -0
  50. package/packages/bundled-features/src/contact/handlers/notify-reporter-in-app.write.ts +48 -0
  51. package/packages/bundled-features/src/contact/handlers/open-count.query.ts +15 -0
  52. package/packages/bundled-features/src/contact/handlers/open-count.ts +17 -0
  53. package/packages/bundled-features/src/contact/handlers/replies.query.ts +29 -0
  54. package/packages/bundled-features/src/contact/handlers/reply.write.ts +197 -0
  55. package/packages/bundled-features/src/contact/handlers/report.write.ts +126 -0
  56. package/packages/bundled-features/src/contact/handlers/request-delivery.query.ts +143 -0
  57. package/packages/bundled-features/src/contact/handlers/request-detail.query.ts +50 -0
  58. package/packages/bundled-features/src/contact/handlers/request-list.query.ts +14 -0
  59. package/packages/bundled-features/src/contact/handlers/send-reply-mail.write.ts +124 -0
  60. package/packages/bundled-features/src/contact/handlers/send-test.write.ts +45 -0
  61. package/packages/bundled-features/src/contact/handlers/submit.write.ts +194 -0
  62. package/packages/bundled-features/src/contact/handlers/take-over-uploads.ts +47 -0
  63. package/packages/bundled-features/src/contact/i18n.ts +192 -0
  64. package/packages/bundled-features/src/contact/index.ts +29 -0
  65. package/packages/bundled-features/src/contact/lib.ts +176 -0
  66. package/packages/bundled-features/src/contact/mail.ts +401 -0
  67. package/packages/bundled-features/src/contact/options.ts +95 -0
  68. package/packages/bundled-features/src/contact/panels.ts +28 -0
  69. package/packages/bundled-features/src/contact/payloads.ts +106 -0
  70. package/packages/bundled-features/src/contact/pow.ts +22 -0
  71. package/packages/bundled-features/src/contact/screens.ts +507 -0
  72. package/packages/bundled-features/src/contact/subject.ts +13 -0
  73. package/packages/bundled-features/src/contact/user-agent.ts +39 -0
  74. package/packages/bundled-features/src/contact/user-data-hooks.ts +180 -0
  75. package/packages/bundled-features/src/contact/web/constants.ts +160 -0
  76. package/packages/bundled-features/src/contact/web/index.ts +29 -0
  77. package/packages/bundled-features/src/crypto-shredding/handlers/forget-subject.write.ts +5 -16
  78. package/packages/bundled-features/src/data-retention/changes.json +6 -0
  79. package/packages/bundled-features/src/data-retention/feature.ts +16 -2
  80. package/packages/bundled-features/src/data-retention/index.ts +5 -0
  81. package/packages/bundled-features/src/data-retention/run-retention-cleanup.ts +138 -41
  82. package/packages/bundled-features/src/data-retention/tenant-destruction-hold.ts +196 -0
  83. package/packages/bundled-features/src/delivery/address-opt-out.ts +1 -0
  84. package/packages/bundled-features/src/delivery/changes.json +7 -0
  85. package/packages/bundled-features/src/delivery/channel-context.ts +2 -0
  86. package/packages/bundled-features/src/delivery/delivery-service.ts +29 -5
  87. package/packages/bundled-features/src/delivery/events.ts +2 -0
  88. package/packages/bundled-features/src/delivery/feature.ts +3 -2
  89. package/packages/bundled-features/src/delivery/handlers/attempts-by-keys.query.ts +55 -0
  90. package/packages/bundled-features/src/delivery/handlers/log.query.ts +1 -1
  91. package/packages/bundled-features/src/delivery/jobs.ts +5 -0
  92. package/packages/bundled-features/src/delivery/tables.ts +13 -2
  93. package/packages/bundled-features/src/delivery/types.ts +3 -0
  94. package/packages/bundled-features/src/delivery/unsubscribe-page.ts +2 -0
  95. package/packages/bundled-features/src/delivery/web/delivery-channel-cell.tsx +1 -1
  96. package/packages/bundled-features/src/delivery/web/delivery-error-cell.tsx +1 -1
  97. package/packages/bundled-features/src/delivery/web/delivery-status-cell.tsx +1 -1
  98. package/packages/bundled-features/src/delivery/web/delivery-time-cell.tsx +3 -2
  99. package/packages/bundled-features/src/delivery/web/delivery-type-cell.tsx +1 -1
  100. package/packages/bundled-features/src/delivery/web/public-names.ts +1 -0
  101. package/packages/bundled-features/src/document-ingest-foundation/boot-checks.ts +14 -9
  102. package/packages/bundled-features/src/document-ingest-foundation/boot-rules.ts +22 -0
  103. package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
  104. package/packages/bundled-features/src/document-ingest-foundation/events.ts +17 -0
  105. package/packages/bundled-features/src/document-ingest-foundation/feature.ts +39 -1
  106. package/packages/bundled-features/src/document-ingest-foundation/index.ts +10 -0
  107. package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +43 -0
  108. package/packages/bundled-features/src/document-ingest-foundation/tables.ts +43 -0
  109. package/packages/bundled-features/src/file-derivatives/handlers/public-variant-by-file-ref.query.ts +1 -1
  110. package/packages/bundled-features/src/file-derivatives/handlers/public-variant.query.ts +1 -1
  111. package/packages/bundled-features/src/files-tenant-data/changes.json +6 -0
  112. package/packages/bundled-features/src/files-tenant-data/hooks.ts +4 -1
  113. package/packages/bundled-features/src/folders/web/folder-manager.tsx +8 -9
  114. package/packages/bundled-features/src/folders/web/folder-section.tsx +1 -1
  115. package/packages/bundled-features/src/form-draft-user-data/index.ts +2 -0
  116. package/packages/bundled-features/src/inbound-mail-foundation/changes.json +13 -0
  117. package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +2 -0
  118. package/packages/bundled-features/src/inbound-mail-foundation/events.ts +2 -0
  119. package/packages/bundled-features/src/inbound-mail-foundation/feature.ts +6 -6
  120. package/packages/bundled-features/src/inbound-mail-foundation/handlers/attach-message-content.write.ts +7 -0
  121. package/packages/bundled-features/src/inbound-mail-foundation/handlers/ingest-message.write.ts +6 -0
  122. package/packages/bundled-features/src/inbound-mail-foundation/handlers/list-messages.query.ts +6 -2
  123. package/packages/bundled-features/src/inbound-mail-foundation/handlers/message-content.query.ts +3 -0
  124. package/packages/bundled-features/src/inbound-mail-foundation/handlers/message-content.ts +19 -0
  125. package/packages/bundled-features/src/inbound-mail-foundation/projection.ts +2 -0
  126. package/packages/bundled-features/src/inbound-mail-foundation/sanitize-inbound-html.ts +150 -0
  127. package/packages/bundled-features/src/inbound-mail-foundation/types.ts +1 -0
  128. package/packages/bundled-features/src/jobs/job-run-logger.ts +24 -25
  129. package/packages/bundled-features/src/ledger/handlers/reports.query.ts +46 -31
  130. package/packages/bundled-features/src/ledger/recurring.ts +1 -0
  131. package/packages/bundled-features/src/managed-pages/handlers/branding.query.ts +1 -1
  132. package/packages/bundled-features/src/managed-pages/handlers/by-slug.query.ts +1 -1
  133. package/packages/bundled-features/src/managed-pages/handlers/by-tenant-published.query.ts +1 -1
  134. package/packages/bundled-features/src/notes-history/web/notes-section.tsx +3 -1
  135. package/packages/bundled-features/src/personal-access-tokens/feature.ts +9 -17
  136. package/packages/bundled-features/src/personal-access-tokens/handlers/create.write.ts +2 -7
  137. package/packages/bundled-features/src/secrets/changes.json +6 -0
  138. package/packages/bundled-features/src/secrets/handlers/delete.write.ts +8 -4
  139. package/packages/bundled-features/src/secrets/handlers/list.query.ts +6 -3
  140. package/packages/bundled-features/src/secrets/handlers/set.write.ts +9 -4
  141. package/packages/bundled-features/src/secrets/secret-scope.ts +33 -0
  142. package/packages/bundled-features/src/seo/handlers/seo-config.query.ts +1 -1
  143. package/packages/bundled-features/src/sessions/changes.json +6 -0
  144. package/packages/bundled-features/src/sessions/feature.ts +21 -18
  145. package/packages/bundled-features/src/sessions/handlers/last-activity-probe.query.ts +53 -0
  146. package/packages/bundled-features/src/sessions/handlers/last-activity-probe.route.ts +39 -0
  147. package/packages/bundled-features/src/sessions/screens.ts +1 -0
  148. package/packages/bundled-features/src/sessions/session-callbacks.ts +13 -12
  149. package/packages/bundled-features/src/sessions/web/i18n.ts +4 -1
  150. package/packages/bundled-features/src/shared/assert-billing-live.ts +14 -0
  151. package/packages/bundled-features/src/shared/collect-extension-options.ts +12 -0
  152. package/packages/bundled-features/src/shared/index.ts +16 -0
  153. package/packages/bundled-features/src/shared/late-bound-slot.ts +19 -0
  154. package/packages/bundled-features/src/shared/mail-locale-templates.ts +7 -1
  155. package/packages/bundled-features/src/shared/price-env-shape.ts +44 -0
  156. package/packages/bundled-features/src/shared/purge-row-file-refs.ts +1 -1
  157. package/packages/bundled-features/src/shared/read-feature-export-fn.ts +16 -0
  158. package/packages/bundled-features/src/shared/signup-handover.ts +3 -4
  159. package/packages/bundled-features/src/shared/tenant-destruction-hold.ts +49 -0
  160. package/packages/bundled-features/src/shared/unprocessable.ts +19 -0
  161. package/packages/bundled-features/src/shared/web/index.ts +3 -0
  162. package/packages/bundled-features/src/subscription-paddle/checkout-config.query.ts +1 -1
  163. package/packages/bundled-features/src/subscription-paddle/feature.ts +7 -15
  164. package/packages/bundled-features/src/subscription-paddle/runtime.ts +4 -7
  165. package/packages/bundled-features/src/subscription-stripe/feature.ts +7 -15
  166. package/packages/bundled-features/src/subscription-stripe/runtime.ts +4 -7
  167. package/packages/bundled-features/src/tags/entity.ts +1 -0
  168. package/packages/bundled-features/src/tags/web/tag-chip.tsx +14 -0
  169. package/packages/bundled-features/src/tags/web/tag-filter.tsx +4 -5
  170. package/packages/bundled-features/src/tags/web/tag-manager.tsx +1 -1
  171. package/packages/bundled-features/src/tags/web/tag-section.tsx +3 -6
  172. package/packages/bundled-features/src/tags/web/tags-cell.tsx +4 -5
  173. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +27 -15
  174. package/packages/bundled-features/src/template-resolver/handlers/by-slug.query.ts +1 -1
  175. package/packages/bundled-features/src/template-resolver/handlers/by-tenant.query.ts +12 -9
  176. package/packages/bundled-features/src/template-resolver/handlers/discard-draft.write.ts +1 -0
  177. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +1 -0
  178. package/packages/bundled-features/src/template-resolver/handlers/send-test.write.ts +5 -5
  179. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +3 -0
  180. package/packages/bundled-features/src/template-resolver/linked-resources.ts +11 -6
  181. package/packages/bundled-features/src/template-resolver/store-template-resource.ts +15 -12
  182. package/packages/bundled-features/src/template-resolver/web/document-images.ts +6 -6
  183. package/packages/bundled-features/src/template-resolver/web/document-insert-fields.tsx +41 -36
  184. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +11 -12
  185. package/packages/bundled-features/src/template-resolver/web/tiptap-attribute-parse-rule.ts +19 -0
  186. package/packages/bundled-features/src/tenant/i18n.ts +3 -0
  187. package/packages/bundled-features/src/tenant/schema/tenant.ts +1 -0
  188. package/packages/bundled-features/src/tenant/web/member-roles-cell.tsx +1 -1
  189. package/packages/bundled-features/src/tenant/web/member-status-cell.tsx +1 -1
  190. package/packages/bundled-features/src/tenant-inactivity/changes.json +8 -0
  191. package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +260 -0
  192. package/packages/bundled-features/src/tenant-inactivity/constants.ts +12 -0
  193. package/packages/bundled-features/src/tenant-inactivity/email-templates.ts +24 -0
  194. package/packages/bundled-features/src/tenant-inactivity/feature.ts +66 -0
  195. package/packages/bundled-features/src/tenant-inactivity/handlers/inactivity-state.query.ts +49 -0
  196. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +59 -0
  197. package/packages/bundled-features/src/tenant-inactivity/inactivity-plan.ts +187 -0
  198. package/packages/bundled-features/src/tenant-inactivity/index.ts +5 -0
  199. package/packages/bundled-features/src/tenant-inactivity/keep-token.ts +44 -0
  200. package/packages/bundled-features/src/tenant-inactivity/mail-notifications.ts +62 -0
  201. package/packages/bundled-features/src/tenant-inactivity/options.ts +38 -0
  202. package/packages/bundled-features/src/tenant-inactivity/remote-activity.ts +32 -0
  203. package/packages/bundled-features/src/tenant-inactivity/state-store.ts +71 -0
  204. package/packages/bundled-features/src/tenant-inactivity/state-table.ts +50 -0
  205. package/packages/bundled-features/src/tenant-lifecycle/boot-checks.ts +8 -6
  206. package/packages/bundled-features/src/tenant-lifecycle/boot-rules.ts +16 -0
  207. package/packages/bundled-features/src/tenant-lifecycle/changes.json +18 -0
  208. package/packages/bundled-features/src/tenant-lifecycle/feature.ts +24 -1
  209. package/packages/bundled-features/src/tenant-lifecycle/handlers/request-destruction.write.ts +12 -87
  210. package/packages/bundled-features/src/tenant-lifecycle/index.ts +4 -0
  211. package/packages/bundled-features/src/tenant-lifecycle/request-tenant-destruction.ts +108 -0
  212. package/packages/bundled-features/src/tenant-lifecycle/retention-config-destroy-hooks.ts +62 -0
  213. package/packages/bundled-features/src/tenant-lifecycle/run-tenant-destroy.ts +58 -5
  214. package/packages/bundled-features/src/tenant-lifecycle/stages.ts +31 -2
  215. package/packages/bundled-features/src/tenant-lifecycle/testing.ts +1 -1
  216. package/packages/bundled-features/src/tier-engine/caps-for-tier-from-map.ts +16 -0
  217. package/packages/bundled-features/src/tier-engine/changes.json +6 -0
  218. package/packages/bundled-features/src/tier-engine/compose-app.ts +21 -20
  219. package/packages/bundled-features/src/tier-engine/index.ts +1 -0
  220. package/packages/bundled-features/src/user-data-rights/feature.ts +2 -0
  221. package/packages/bundled-features/src/user-data-rights/handlers/confirm-deletion-by-token.write.ts +4 -1
  222. package/packages/bundled-features/src/user-data-rights/handlers/download-by-token.query.ts +1 -0
  223. package/packages/bundled-features/src/user-data-rights/handlers/request-deletion-by-email.write.ts +4 -1
  224. package/packages/bundled-features/src/user-data-rights/run-forget-cleanup.ts +2 -0
  225. package/packages/bundled-features/src/user-data-rights/web/privacy-center-screen.tsx +1 -1
  226. package/packages/bundled-features/src/user-data-rights/zip-path.ts +1 -0
  227. package/packages/bundled-features/src/user-data-rights-defaults/hooks/config-value.userdata-hook.ts +8 -27
  228. package/packages/bundled-features/src/user-data-rights-defaults/hooks/delivery-attempt.userdata-hook.ts +11 -8
  229. package/packages/bundled-features/src/user-data-rights-defaults/hooks/forget-own-rows-delete-hook.ts +42 -0
  230. package/packages/bundled-features/src/user-data-rights-defaults/hooks/notification-preference.userdata-hook.ts +8 -27
  231. package/packages/bundled-features/src/user-profile/handlers/change-email.write.ts +2 -6
  232. package/packages/bundled-features/src/user-profile/web/profile-screen.tsx +2 -3
  233. package/packages/bundled-features/src/waitlist/changes.json +6 -0
  234. package/packages/bundled-features/src/waitlist/handlers/submit.write.ts +1 -2
  235. package/samples/apps/styleguide/src/features/widgets/i18n.ts +6 -0
  236. package/samples/apps/styleguide/src/features/widgets/web/InboxReaderExamples.tsx +158 -0
  237. package/samples/apps/styleguide/src/features/widgets/web/Widgets.tsx +2 -0
  238. package/samples/apps/styleguide/src/features/widgets/web/sample-pdf.ts +28 -0
  239. package/samples/apps/use-all-bundled/feature-manifest.json +113 -2
  240. package/samples/apps/use-all-bundled/kumiko/migrations/0063_contact.rebuild.json +4 -0
  241. package/samples/apps/use-all-bundled/package.json +1 -0
  242. package/samples/apps/use-all-bundled/src/app/client.tsx +3 -0
  243. package/samples/apps/use-all-bundled/src/app/screens-feature.ts +46 -2
  244. package/samples/apps/use-all-bundled/src/run-config.ts +23 -1
  245. package/samples/recipes/anonymous-access/README.md +2 -0
  246. package/samples/recipes/anonymous-access/src/feature.ts +7 -1
  247. package/samples/recipes/contact/README.md +52 -0
  248. package/samples/recipes/contact/package.json +12 -0
  249. package/samples/recipes/contact/src/feature.ts +27 -0
  250. package/samples/recipes/delivery-notifications/src/feature.ts +3 -0
  251. package/samples/recipes/record-detail-layout/src/feature.ts +9 -1
  252. package/samples/recipes/search/README.md +2 -0
  253. package/samples/recipes/search/src/feature.ts +27 -2
  254. package/samples/recipes/secrets-demo/README.md +1 -0
  255. package/samples/recipes/secrets-demo/src/feature.ts +56 -0
  256. package/samples/recipes/tenant-inactivity/README.md +21 -0
  257. package/samples/recipes/tenant-inactivity/package.json +12 -0
@@ -0,0 +1,260 @@
1
+ import { fetchOne } from "@cosmicdrift/kumiko-framework/db";
2
+ import type { JobContext, TenantId } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { hasMailTranslations, mailT } from "@cosmicdrift/kumiko-framework/i18n";
4
+ import { parseRoles } from "@cosmicdrift/kumiko-framework/utils";
5
+ import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
6
+ import {
7
+ decryptTenantNames,
8
+ type TenantLifecycleStatus,
9
+ tenantMembershipsTable,
10
+ tenantTable,
11
+ } from "../tenant/index.ts";
12
+ import { requestTenantDestruction } from "../tenant-lifecycle/index.ts";
13
+ import { userTable } from "../user/index.ts";
14
+ import { TENANT_OWNER_ROLE } from "./constants.ts";
15
+ import { formatInactivityMailDate } from "./email-templates.ts";
16
+ import {
17
+ activityBase,
18
+ decideInactivityAction,
19
+ foldActivity,
20
+ type InactivityRule,
21
+ resetWarnings,
22
+ } from "./inactivity-plan.ts";
23
+ import { signKeepAccountToken } from "./keep-token.ts";
24
+ import {
25
+ InactivityWarningNotificationType,
26
+ inactivityMailTemplateLocale,
27
+ } from "./mail-notifications.ts";
28
+ import { resolveInactivityRule, type TenantInactivityOptions } from "./options.ts";
29
+ import {
30
+ loadInactivityState,
31
+ loadNewestSessionActivity,
32
+ type StoredInactivityState,
33
+ saveInactivityState,
34
+ } from "./state-store.ts";
35
+
36
+ // Links outlive the deadline a little so a late click still counts as a reaction.
37
+ const KEEP_LINK_GRACE_MINUTES = 14 * 24 * 60;
38
+ const MS_PER_MINUTE = 60_000;
39
+
40
+ function emptyState(now: Temporal.Instant): StoredInactivityState {
41
+ return {
42
+ cycleId: crypto.randomUUID(),
43
+ firstSeenAt: now,
44
+ lastActivityAt: null,
45
+ lastExemptAt: null,
46
+ lastWarnedAt: null,
47
+ postponedDueAt: null,
48
+ warningsSent: 0,
49
+ };
50
+ }
51
+
52
+ function startNewCycle(state: StoredInactivityState): StoredInactivityState {
53
+ return { ...resetWarnings(state), cycleId: crypto.randomUUID() };
54
+ }
55
+
56
+ function latestOf(instants: readonly (Temporal.Instant | null)[]): Temporal.Instant | null {
57
+ let latest: Temporal.Instant | null = null;
58
+ for (const instant of instants) {
59
+ if (instant !== null && (latest === null || Temporal.Instant.compare(instant, latest) > 0)) {
60
+ latest = instant;
61
+ }
62
+ }
63
+ return latest;
64
+ }
65
+
66
+ async function newestExternalActivity(
67
+ options: TenantInactivityOptions,
68
+ tenantId: TenantId,
69
+ now: Temporal.Instant,
70
+ ): Promise<Temporal.Instant | null> {
71
+ const found = await Promise.all(
72
+ (options.activitySources ?? []).map((source) => source({ tenantId, now })),
73
+ );
74
+ return latestOf(found);
75
+ }
76
+
77
+ function isNewerThanBase(
78
+ activity: Temporal.Instant | null,
79
+ state: StoredInactivityState,
80
+ ): activity is Temporal.Instant {
81
+ return activity !== null && Temporal.Instant.compare(activity, activityBase(state)) > 0;
82
+ }
83
+
84
+ type OwnerRecipient = { readonly userId: string; readonly locale: string | null };
85
+
86
+ async function loadOwners(ctx: JobContext): Promise<readonly OwnerRecipient[]> {
87
+ const memberships = await ctx.db.selectMany<{ userId: string; roles: unknown }>(
88
+ tenantMembershipsTable,
89
+ {},
90
+ );
91
+ const owners: OwnerRecipient[] = [];
92
+ for (const membership of memberships) {
93
+ if (!parseRoles(membership.roles).includes(TENANT_OWNER_ROLE)) continue;
94
+ const user = await ctx.db
95
+ .global(userTable)
96
+ .fetchOne<{ locale: string | null }>({ id: membership.userId });
97
+ owners.push({ userId: membership.userId, locale: user?.locale ?? null });
98
+ }
99
+ return owners;
100
+ }
101
+
102
+ function mailLocaleFor(userLocale: string | null): string {
103
+ const root = userLocale?.toLowerCase().split("-")[0];
104
+ const preferred = root !== undefined && hasMailTranslations(root) ? root : "en";
105
+ return inactivityMailTemplateLocale(InactivityWarningNotificationType, preferred);
106
+ }
107
+
108
+ async function readTenantName(ctx: JobContext, tenantId: TenantId): Promise<string> {
109
+ const row = await fetchOne<{ name?: unknown }>(ctx.db.unsafeRaw(), tenantTable, {
110
+ id: tenantId,
111
+ });
112
+ const [named] = await decryptTenantNames(row ? [row] : [], tenantId);
113
+ return typeof named?.name === "string" ? named.name : tenantId;
114
+ }
115
+
116
+ function keepLinkFor(args: {
117
+ readonly options: TenantInactivityOptions;
118
+ readonly tenantId: TenantId;
119
+ readonly state: StoredInactivityState;
120
+ readonly deadline: Temporal.Instant;
121
+ readonly now: Temporal.Instant;
122
+ }): string {
123
+ const { options, tenantId, state, deadline, now } = args;
124
+ if (options.keepAccountTokenSecret === undefined) return options.keepAccountUrl;
125
+ const untilDeadline = Math.ceil(
126
+ (deadline.epochMilliseconds - now.epochMilliseconds) / MS_PER_MINUTE,
127
+ );
128
+ const token = signKeepAccountToken({
129
+ tenantId,
130
+ cycleId: state.cycleId,
131
+ ttlMinutes: Math.max(0, untilDeadline) + KEEP_LINK_GRACE_MINUTES,
132
+ secret: options.keepAccountTokenSecret,
133
+ now,
134
+ });
135
+ return `${options.keepAccountUrl}#token=${token}`;
136
+ }
137
+
138
+ // True when at least one owner got the mail. A failed delivery must not count as a sent warning,
139
+ // or the deletion request would follow without the owner ever having been told.
140
+ async function sendWarningMails(args: {
141
+ readonly ctx: JobContext;
142
+ readonly options: TenantInactivityOptions;
143
+ readonly tenantId: TenantId;
144
+ readonly state: StoredInactivityState;
145
+ readonly deadline: Temporal.Instant;
146
+ readonly now: Temporal.Instant;
147
+ }): Promise<boolean> {
148
+ const { ctx, options, tenantId, deadline } = args;
149
+ if (!ctx.notify) throw new Error("tenant-inactivity: ctx.notify missing, mount delivery");
150
+ const tenantName = await readTenantName(ctx, tenantId);
151
+ const keepUrl = keepLinkFor(args);
152
+
153
+ let delivered = false;
154
+ for (const owner of await loadOwners(ctx)) {
155
+ const locale = mailLocaleFor(owner.locale);
156
+ // immediate: the keep-account token must not land in a delivery job payload.
157
+ const result = await ctx.notify(InactivityWarningNotificationType, {
158
+ to: owner.userId,
159
+ locale,
160
+ immediate: true,
161
+ data: {
162
+ app: options.appName ?? mailT(locale, "gdpr.mail.appNameDefault"),
163
+ tenant: tenantName,
164
+ when: formatInactivityMailDate(deadline),
165
+ keepUrl,
166
+ },
167
+ });
168
+ if (result.deliveries.some((delivery) => delivery.status !== "failed")) delivered = true;
169
+ }
170
+ return delivered;
171
+ }
172
+
173
+ async function evaluate(
174
+ ctx: JobContext,
175
+ options: TenantInactivityOptions,
176
+ tenantId: TenantId,
177
+ rule: InactivityRule,
178
+ stored: StoredInactivityState | null,
179
+ now: Temporal.Instant,
180
+ ): Promise<StoredInactivityState> {
181
+ const initial = stored ?? emptyState(now);
182
+ const folded = foldActivity(initial, await loadNewestSessionActivity(ctx.db));
183
+ const merged: StoredInactivityState = { ...initial, ...folded.state };
184
+ const state = folded.newCycle ? startNewCycle(merged) : merged;
185
+
186
+ const decision = decideInactivityAction(state, rule, now);
187
+ if (decision.kind === "none") return state;
188
+
189
+ // Steps with consequences ask other apps first: activity there counts too.
190
+ const external = await newestExternalActivity(options, tenantId, now);
191
+ if (isNewerThanBase(external, state)) {
192
+ return startNewCycle({ ...state, lastActivityAt: external });
193
+ }
194
+
195
+ if (decision.kind === "warn") {
196
+ const delivered = await sendWarningMails({
197
+ ctx,
198
+ options,
199
+ tenantId,
200
+ state,
201
+ deadline: decision.deadline,
202
+ now,
203
+ });
204
+ if (!delivered) return state;
205
+ return {
206
+ ...state,
207
+ warningsSent: decision.warningsSentAfter,
208
+ lastWarnedAt: now,
209
+ postponedDueAt: decision.postponedDueAt ?? state.postponedDueAt,
210
+ };
211
+ }
212
+
213
+ if (!ctx.registry) throw new Error("tenant-inactivity: ctx.registry required");
214
+ const result = await requestTenantDestruction({
215
+ tenantId,
216
+ actor: ctx.systemUser,
217
+ now,
218
+ db: ctx.db,
219
+ runner: ctx.db.unsafeRaw(),
220
+ registry: ctx.registry,
221
+ revokeSessions: true,
222
+ });
223
+ if (!result.isSuccess) {
224
+ throw new Error(`tenant-inactivity: destruction request for ${tenantId} failed`);
225
+ }
226
+ // If the owner cancels the request, a fresh cycle starts instead of an instant second request.
227
+ return startNewCycle({ ...state, lastActivityAt: now });
228
+ }
229
+
230
+ export async function checkTenantInactivity(
231
+ ctx: JobContext,
232
+ options: TenantInactivityOptions,
233
+ ): Promise<void> {
234
+ const tenantId = ctx.systemUser.tenantId ?? ctx._tenantId;
235
+ // skip: a job without a tenant scope has nothing to evaluate
236
+ if (tenantId === undefined) return;
237
+ const now = ctx.tz.now();
238
+ const tenant = await fetchOne<{ status: TenantLifecycleStatus }>(
239
+ ctx.db.unsafeRaw(),
240
+ tenantTable,
241
+ { id: tenantId },
242
+ );
243
+ // skip: only active tenants are evaluated; others are already in a lifecycle step
244
+ if (tenant?.status !== "active") return;
245
+
246
+ const rule = await resolveInactivityRule(options, ctx.db);
247
+ const stored = await loadInactivityState(ctx.db);
248
+ if (rule === null) {
249
+ const state = stored ?? emptyState(now);
250
+ // A tier change back to a rule starts its period at the last exempt run.
251
+ const exempt = state.warningsSent > 0 ? startNewCycle(state) : state;
252
+ await saveInactivityState(ctx.db, stored, { ...exempt, lastExemptAt: now });
253
+ } else {
254
+ await saveInactivityState(
255
+ ctx.db,
256
+ stored,
257
+ await evaluate(ctx, options, tenantId, rule, stored, now),
258
+ );
259
+ }
260
+ }
@@ -0,0 +1,12 @@
1
+ export const TENANT_INACTIVITY_FEATURE = "tenant-inactivity";
2
+ export const TENANT_INACTIVITY_STATE_ENTITY = "tenant-inactivity-state";
3
+ export const TENANT_OWNER_ROLE = "TenantOwner";
4
+
5
+ export const TenantInactivityJobs = {
6
+ check: `${TENANT_INACTIVITY_FEATURE}:job:check-inactive-tenants`,
7
+ } as const;
8
+
9
+ export const TenantInactivityHandlers = {
10
+ keepAccount: `${TENANT_INACTIVITY_FEATURE}:write:keep-account`,
11
+ state: `${TENANT_INACTIVITY_FEATURE}:query:state`,
12
+ } as const;
@@ -0,0 +1,24 @@
1
+ // English defaults of the inactivity warning mail; other languages register through
2
+ // @cosmicdrift/kumiko-locale-* (same pattern as the GDPR mails).
3
+
4
+ import { registerMailTranslations } from "@cosmicdrift/kumiko-framework/i18n";
5
+ import type { Temporal } from "@cosmicdrift/kumiko-types/temporal";
6
+
7
+ export const INACTIVITY_MAIL_EN: Readonly<Record<string, string>> = {
8
+ "inactivity.mail.warning.subject": "{app}: Deletion request for your account {account} on {when}",
9
+ "inactivity.mail.warning.intro":
10
+ "nobody has signed in to your {app} account {account} for a long time. If that does not change, we will request deletion of the account and all its data on {when}.",
11
+ "inactivity.mail.warning.keep":
12
+ "To keep the account, sign in or click the button. The period then starts over.",
13
+ "inactivity.mail.warning.button": "Keep account",
14
+ "inactivity.mail.warning.after":
15
+ "Even after the deletion request you can cancel it in the account settings until the waiting period ends.",
16
+ };
17
+
18
+ registerMailTranslations("en", INACTIVITY_MAIL_EN);
19
+
20
+ export function formatInactivityMailDate(instant: Temporal.Instant): string {
21
+ const zoned = instant.toZonedDateTimeISO("UTC");
22
+ const pad = (value: number) => String(value).padStart(2, "0");
23
+ return `${zoned.year}-${pad(zoned.month)}-${pad(zoned.day)}`;
24
+ }
@@ -0,0 +1,66 @@
1
+ import { deleteMany, deriveEntityTableMeta } from "@cosmicdrift/kumiko-framework/db";
2
+ import {
3
+ defineFeature,
4
+ EXT_TENANT_DATA,
5
+ type FeatureDefinition,
6
+ type TenantDataDestroyHook,
7
+ } from "@cosmicdrift/kumiko-framework/engine";
8
+ import { checkTenantInactivity } from "./check-inactive-tenants.ts";
9
+ import { TENANT_INACTIVITY_FEATURE, TENANT_INACTIVITY_STATE_ENTITY } from "./constants.ts";
10
+ import { createInactivityStateQuery } from "./handlers/inactivity-state.query.ts";
11
+ import { createKeepAccountHandler } from "./handlers/keep-account.write.ts";
12
+ import { registerInactivityMails } from "./mail-notifications.ts";
13
+ import type { TenantInactivityOptions } from "./options.ts";
14
+ import { tenantInactivityStateEntity, tenantInactivityStateTable } from "./state-table.ts";
15
+
16
+ const CHECK_JOB_ESCAPE_HATCH_REASON =
17
+ "reads the tenant's lifecycle status on the system tenant and files the deletion request through the shared tenant-lifecycle core, which writes the tenant row and its event stream with a raw runner";
18
+
19
+ const tenantInactivityStateDestroyHook: TenantDataDestroyHook = async (ctx) => {
20
+ await deleteMany(ctx.db, tenantInactivityStateTable, { tenantId: ctx.tenantId });
21
+ };
22
+
23
+ /**
24
+ * Opt-in by mounting. Free accounts without activity get warning mails, then a normal deletion
25
+ * request through tenant-lifecycle; paid tiers are exempt. The option value carries functions
26
+ * (rules per tier, activity sources), so the feature is never deduplicated by options.
27
+ */
28
+ export function createTenantInactivityFeature<TTier extends string = string>(
29
+ options: TenantInactivityOptions<TTier>,
30
+ ): FeatureDefinition {
31
+ return defineFeature(TENANT_INACTIVITY_FEATURE, (r) => {
32
+ r.describe(
33
+ "Deletes abandoned free accounts: warns the tenant owners before the deadline, then files the regular tenant-lifecycle deletion request. Activity or the keep-account link restarts the period; tiers without a rule are exempt.",
34
+ );
35
+ r.uiHints({
36
+ displayLabel: "Tenant Inactivity · Deletion",
37
+ category: "compliance",
38
+ recommended: false,
39
+ });
40
+ r.requires({ features: ["sessions", "tenant", "tenant-lifecycle", "delivery"] });
41
+
42
+ r.storeTable(
43
+ deriveEntityTableMeta(TENANT_INACTIVITY_STATE_ENTITY, tenantInactivityStateEntity, {
44
+ source: "unmanaged",
45
+ }),
46
+ { reason: "read_side.tenant_inactivity_state_direct_write" },
47
+ );
48
+ r.useExtension(EXT_TENANT_DATA, TENANT_INACTIVITY_STATE_ENTITY, {
49
+ destroy: tenantInactivityStateDestroyHook,
50
+ });
51
+
52
+ registerInactivityMails(r);
53
+
54
+ r.job({
55
+ name: "check-inactive-tenants",
56
+ trigger: { maintenance: true, wakesSleepingApp: false },
57
+ perTenant: true,
58
+ concurrency: "skip",
59
+ escapeHatch: { grants: ["unsafeRaw"], reason: CHECK_JOB_ESCAPE_HATCH_REASON },
60
+ handler: async (_payload, ctx) => checkTenantInactivity(ctx, options),
61
+ });
62
+
63
+ r.writeHandler(createKeepAccountHandler(options));
64
+ r.queryHandler(createInactivityStateQuery(options));
65
+ });
66
+ }
@@ -0,0 +1,49 @@
1
+ import { createTenantDb, type TenantDb } from "@cosmicdrift/kumiko-framework/db";
2
+ import { defineQueryHandler, parseTenantId } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { AccessDeniedError, UnprocessableError } from "@cosmicdrift/kumiko-framework/errors";
4
+ import * as z from "zod";
5
+ import { describeOutlook, foldActivity } from "../inactivity-plan.ts";
6
+ import { resolveInactivityRule, type TenantInactivityOptions } from "../options.ts";
7
+ import { loadInactivityState, loadNewestSessionActivity } from "../state-store.ts";
8
+
9
+ const STATE_QUERY_ESCAPE_HATCH_REASON =
10
+ "a SystemAdmin reads the inactivity state of any tenant through a database handle pinned to that tenant";
11
+
12
+ // Folds the sessions' newest activity in like the daily job does, so a login shows up before
13
+ // the next job run.
14
+ export function createInactivityStateQuery<TTier extends string>(
15
+ options: TenantInactivityOptions<TTier>,
16
+ ) {
17
+ return defineQueryHandler({
18
+ name: "state",
19
+ schema: z.object({ tenantIdOverride: z.string().min(1).max(36).optional() }),
20
+ access: { roles: ["TenantOwner", "TenantAdmin", "SystemAdmin"] },
21
+ escapeHatch: { grants: ["unsafeRaw"], reason: STATE_QUERY_ESCAPE_HATCH_REASON },
22
+ description:
23
+ "Returns whether the tenant is exempt from inactivity deletion, its last activity, the warnings already sent and the next step with its date; owners and admins see their own tenant, a SystemAdmin any tenant.",
24
+ handler: async (query, ctx) => {
25
+ const requested = query.payload.tenantIdOverride;
26
+ const isOtherTenant = requested !== undefined && requested !== query.user.tenantId;
27
+ let db: TenantDb = ctx.db;
28
+ if (isOtherTenant) {
29
+ if (!query.user.roles.includes("SystemAdmin")) throw new AccessDeniedError();
30
+ const tenantId = parseTenantId(requested);
31
+ if (tenantId === null) throw new UnprocessableError("invalid_tenant_id");
32
+ db = createTenantDb({ db: ctx.db.unsafeRaw(), tenantId });
33
+ }
34
+ const rule = await resolveInactivityRule(options, db);
35
+ const stored = await loadInactivityState(db);
36
+ const folded = stored
37
+ ? foldActivity(stored, await loadNewestSessionActivity(db)).state
38
+ : null;
39
+ const outlook = describeOutlook(folded, rule);
40
+ return {
41
+ exempt: outlook.exempt,
42
+ lastActivityAt: outlook.lastActivityAt?.toString() ?? null,
43
+ warningsSent: outlook.warningsSent,
44
+ nextStep: outlook.nextStep,
45
+ nextStepAt: outlook.nextStepAt?.toString() ?? null,
46
+ };
47
+ },
48
+ });
49
+ }
@@ -0,0 +1,59 @@
1
+ import { fetchOne, updateMany } from "@cosmicdrift/kumiko-framework/db";
2
+ import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { UnprocessableError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
4
+ import * as z from "zod";
5
+ import { redeemKeepAccountToken } from "../keep-token.ts";
6
+ import { tenantInactivityStateTable } from "../state-table.ts";
7
+
8
+ const KEEP_ACCOUNT_ESCAPE_HATCH_REASON =
9
+ "the anonymous link holder has no tenant scope; the tenant comes from the signed token and every statement filters by that tenantId";
10
+
11
+ export function createKeepAccountHandler(opts: { readonly keepAccountTokenSecret?: string }) {
12
+ return defineWriteHandler({
13
+ name: "keep-account",
14
+ schema: z.object({ token: z.string().min(1) }),
15
+ access: {
16
+ roles: ["anonymous", "Member", "User", "TenantAdmin", "TenantOwner", "SystemAdmin"],
17
+ anySignedIn: true,
18
+ },
19
+ escapeHatch: { grants: ["unsafeRaw"], reason: KEEP_ACCOUNT_ESCAPE_HATCH_REASON },
20
+ agent: { expose: false },
21
+ rateLimit: { per: "ip+handler", limit: 10, windowSeconds: 60 },
22
+ description:
23
+ "Redeems the keep-account link from an inactivity warning mail: counts as activity, resets the warning cycle and invalidates every earlier link.",
24
+ handler: async (event, ctx) => {
25
+ const runner = ctx.db.unsafeRaw();
26
+ const now = ctx.tz.now();
27
+ const redeemed = await redeemKeepAccountToken({
28
+ token: event.payload.token,
29
+ secret: opts.keepAccountTokenSecret,
30
+ now,
31
+ // The tenant id comes from the not-yet-verified token; a malformed value must end in the
32
+ // generic 422, so the lookup error is swallowed by the grant's anchor-lookup guard.
33
+ loadCycleId: async (tenantId) => {
34
+ const row = await fetchOne<{ cycleId: string }>(runner, tenantInactivityStateTable, {
35
+ tenantId,
36
+ });
37
+ return row?.cycleId ?? null;
38
+ },
39
+ commitKeep: async (tenantId, cycleId) => {
40
+ const updated = await updateMany(
41
+ runner,
42
+ tenantInactivityStateTable,
43
+ {
44
+ lastActivityAt: now,
45
+ warningsSent: 0,
46
+ lastWarnedAt: null,
47
+ postponedDueAt: null,
48
+ cycleId: crypto.randomUUID(),
49
+ },
50
+ { tenantId, cycleId },
51
+ );
52
+ return updated.length === 1;
53
+ },
54
+ });
55
+ if (!redeemed.ok) return writeFailure(new UnprocessableError("invalid_or_expired_token"));
56
+ return { isSuccess: true as const, data: { kept: true } };
57
+ },
58
+ });
59
+ }
@@ -0,0 +1,187 @@
1
+ import {
2
+ addDurationSpec,
3
+ type DurationSpec,
4
+ type RetentionSpec,
5
+ } from "@cosmicdrift/kumiko-framework/compliance";
6
+ import { Temporal } from "@cosmicdrift/kumiko-types/temporal";
7
+
8
+ type Instant = Temporal.Instant;
9
+
10
+ export type InactivityRule = {
11
+ readonly after: RetentionSpec;
12
+ // Lead times before the deadline, in any order.
13
+ readonly warnings: readonly DurationSpec[];
14
+ };
15
+
16
+ export type InactivityState = {
17
+ readonly firstSeenAt: Instant;
18
+ readonly lastActivityAt: Instant | null;
19
+ readonly lastExemptAt: Instant | null;
20
+ readonly warningsSent: number;
21
+ readonly lastWarnedAt: Instant | null;
22
+ // Set when a deadline passed without all warnings out: the last warning is sent late and
23
+ // the deletion request moves behind it.
24
+ readonly postponedDueAt: Instant | null;
25
+ };
26
+
27
+ export type InactivityStep = "warning" | "destructionRequest";
28
+
29
+ export type InactivityPlan = {
30
+ readonly step: InactivityStep;
31
+ readonly at: Instant;
32
+ };
33
+
34
+ export type InactivityDecision =
35
+ | { readonly kind: "none" }
36
+ | {
37
+ readonly kind: "warn";
38
+ readonly warningsSentAfter: number;
39
+ readonly deadline: Instant;
40
+ readonly postponedDueAt: Instant | null;
41
+ }
42
+ | { readonly kind: "destroy" };
43
+
44
+ const EPOCH = Temporal.Instant.fromEpochMilliseconds(0);
45
+
46
+ export function addRetentionSpec(from: Instant, spec: RetentionSpec): Instant {
47
+ if ("months" in spec) {
48
+ return from.toZonedDateTimeISO("UTC").add({ months: spec.months }).toInstant();
49
+ }
50
+ if ("years" in spec) {
51
+ return from.toZonedDateTimeISO("UTC").add({ years: spec.years }).toInstant();
52
+ }
53
+ return addDurationSpec(from, spec);
54
+ }
55
+
56
+ function leadMs(spec: DurationSpec): number {
57
+ return addDurationSpec(EPOCH, spec).epochMilliseconds;
58
+ }
59
+
60
+ // Longest lead first, so index 0 is the earliest warning.
61
+ export function sortedWarnings(rule: InactivityRule): readonly DurationSpec[] {
62
+ return [...rule.warnings].sort((a, b) => leadMs(b) - leadMs(a));
63
+ }
64
+
65
+ function laterOf(instants: readonly (Instant | null)[]): Instant | null {
66
+ let latest: Instant | null = null;
67
+ for (const instant of instants) {
68
+ if (instant !== null && (latest === null || Temporal.Instant.compare(instant, latest) > 0)) {
69
+ latest = instant;
70
+ }
71
+ }
72
+ return latest;
73
+ }
74
+
75
+ export function activityBase(state: InactivityState): Instant {
76
+ return (
77
+ laterOf([state.firstSeenAt, state.lastActivityAt, state.lastExemptAt]) ?? state.firstSeenAt
78
+ );
79
+ }
80
+
81
+ // Activity after the last warning starts a new cycle.
82
+ export function isNewCycle(state: InactivityState): boolean {
83
+ return (
84
+ state.warningsSent > 0 &&
85
+ state.lastWarnedAt !== null &&
86
+ Temporal.Instant.compare(activityBase(state), state.lastWarnedAt) > 0
87
+ );
88
+ }
89
+
90
+ export function resetWarnings(state: InactivityState): InactivityState {
91
+ return { ...state, warningsSent: 0, lastWarnedAt: null, postponedDueAt: null };
92
+ }
93
+
94
+ export function dueAt(state: InactivityState, rule: InactivityRule): Instant {
95
+ const regular = addRetentionSpec(activityBase(state), rule.after);
96
+ return laterOf([regular, state.postponedDueAt]) ?? regular;
97
+ }
98
+
99
+ // Expects a state that already went through the new-cycle reset.
100
+ export function planNextStep(state: InactivityState, rule: InactivityRule): InactivityPlan {
101
+ const due = dueAt(state, rule);
102
+ const warnings = sortedWarnings(rule);
103
+ const nextWarning = warnings[state.warningsSent];
104
+ if (nextWarning === undefined) return { step: "destructionRequest", at: due };
105
+ const warnAt = Temporal.Instant.fromEpochMilliseconds(
106
+ due.epochMilliseconds - leadMs(nextWarning),
107
+ );
108
+ return { step: "warning", at: warnAt };
109
+ }
110
+
111
+ // At most one warning per run: the latest one that is due. A deadline that passed with warnings
112
+ // missing sends the final warning late and moves the deletion request behind it.
113
+ export function decideInactivityAction(
114
+ state: InactivityState,
115
+ rule: InactivityRule,
116
+ now: Instant,
117
+ ): InactivityDecision {
118
+ const due = dueAt(state, rule);
119
+ const warnings = sortedWarnings(rule);
120
+ const total = warnings.length;
121
+ if (state.warningsSent >= total) {
122
+ return Temporal.Instant.compare(now, due) >= 0 ? { kind: "destroy" } : { kind: "none" };
123
+ }
124
+ const finalLead = warnings[total - 1];
125
+ if (finalLead !== undefined && Temporal.Instant.compare(now, due) >= 0) {
126
+ const postponedDueAt = addDurationSpec(now, finalLead);
127
+ return {
128
+ kind: "warn",
129
+ warningsSentAfter: total,
130
+ deadline: postponedDueAt,
131
+ postponedDueAt,
132
+ };
133
+ }
134
+ let lastDue = -1;
135
+ for (let index = state.warningsSent; index < total; index++) {
136
+ const lead = warnings[index];
137
+ if (lead !== undefined && now.epochMilliseconds >= due.epochMilliseconds - leadMs(lead)) {
138
+ lastDue = index;
139
+ }
140
+ }
141
+ if (lastDue < 0) return { kind: "none" };
142
+ return { kind: "warn", warningsSentAfter: lastDue + 1, deadline: due, postponedDueAt: null };
143
+ }
144
+
145
+ // Raises lastActivityAt to the newest known activity; activity after the last warning starts a
146
+ // new cycle, which also drops a postponed deadline.
147
+ export function foldActivity(
148
+ state: InactivityState,
149
+ newest: Instant | null,
150
+ ): { readonly state: InactivityState; readonly newCycle: boolean } {
151
+ const lastActivityAt = laterOf([state.lastActivityAt, newest]);
152
+ const raised: InactivityState = { ...state, lastActivityAt };
153
+ if (!isNewCycle(raised)) return { state: raised, newCycle: false };
154
+ return { state: resetWarnings(raised), newCycle: true };
155
+ }
156
+
157
+ export type InactivityOutlook = {
158
+ readonly exempt: boolean;
159
+ readonly lastActivityAt: Instant | null;
160
+ readonly warningsSent: number;
161
+ readonly nextStep: InactivityStep | null;
162
+ readonly nextStepAt: Instant | null;
163
+ };
164
+
165
+ // Shared by the daily job and the state query so both name the same next step.
166
+ export function describeOutlook(
167
+ state: InactivityState | null,
168
+ rule: InactivityRule | null,
169
+ ): InactivityOutlook {
170
+ if (rule === null || state === null) {
171
+ return {
172
+ exempt: rule === null,
173
+ lastActivityAt: state?.lastActivityAt ?? null,
174
+ warningsSent: state?.warningsSent ?? 0,
175
+ nextStep: null,
176
+ nextStepAt: null,
177
+ };
178
+ }
179
+ const plan = planNextStep(state, rule);
180
+ return {
181
+ exempt: false,
182
+ lastActivityAt: state.lastActivityAt,
183
+ warningsSent: state.warningsSent,
184
+ nextStep: plan.step,
185
+ nextStepAt: plan.at,
186
+ };
187
+ }
@@ -0,0 +1,5 @@
1
+ export { TenantInactivityHandlers, TenantInactivityJobs } from "./constants.ts";
2
+ export { createTenantInactivityFeature } from "./feature.ts";
3
+ export type { InactivityRule } from "./inactivity-plan.ts";
4
+ export type { TenantActivitySource, TenantInactivityOptions } from "./options.ts";
5
+ export { fetchRemoteAppLastActivity } from "./remote-activity.ts";