@connextar/house 0.23.1 → 0.24.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 (186) hide show
  1. package/README.md +55 -13
  2. package/dist/analytics/browser.d.ts +1 -0
  3. package/dist/analytics/browser.d.ts.map +1 -1
  4. package/dist/analytics/browser.js +22 -5
  5. package/dist/analytics/browser.js.map +1 -1
  6. package/dist/analytics/config.d.ts +5 -0
  7. package/dist/analytics/config.d.ts.map +1 -1
  8. package/dist/analytics/config.js +4 -1
  9. package/dist/analytics/config.js.map +1 -1
  10. package/dist/analytics/posthog-extensions.d.ts +19 -0
  11. package/dist/analytics/posthog-extensions.d.ts.map +1 -0
  12. package/dist/analytics/posthog-extensions.js +19 -0
  13. package/dist/analytics/posthog-extensions.js.map +1 -0
  14. package/dist/analytics/react.d.ts.map +1 -1
  15. package/dist/analytics/react.js +4 -2
  16. package/dist/analytics/react.js.map +1 -1
  17. package/dist/analytics/redact.d.ts.map +1 -1
  18. package/dist/analytics/redact.js +6 -1
  19. package/dist/analytics/redact.js.map +1 -1
  20. package/dist/house.css +19 -0
  21. package/package.json +17 -3
  22. package/src/account/data-contract.ts +112 -0
  23. package/src/account/index.ts +11 -0
  24. package/src/admin/access.ts +267 -0
  25. package/src/admin/audit.ts +238 -0
  26. package/src/admin/bootstrap.ts +220 -0
  27. package/src/admin/client-index.ts +19 -0
  28. package/src/admin/client.tsx +187 -0
  29. package/src/admin/index.ts +91 -0
  30. package/src/admin/proof.ts +155 -0
  31. package/src/admin/second-factor-index.ts +16 -0
  32. package/src/admin/second-factor.ts +403 -0
  33. package/src/admin/testing-index.ts +13 -0
  34. package/src/admin/testing.ts +299 -0
  35. package/src/admin/view-as.ts +511 -0
  36. package/src/ai/config-index.ts +40 -0
  37. package/src/ai/config.ts +176 -0
  38. package/src/ai/images.ts +18 -0
  39. package/src/ai/index.ts +21 -0
  40. package/src/ai/pricing.ts +107 -0
  41. package/src/ai/provider.ts +403 -0
  42. package/src/analytics/browser.ts +400 -0
  43. package/src/analytics/client-index.ts +12 -0
  44. package/src/analytics/config.ts +89 -0
  45. package/src/analytics/index.ts +17 -0
  46. package/src/analytics/ingest.ts +81 -0
  47. package/src/analytics/posthog-extensions.ts +19 -0
  48. package/src/analytics/react-index.ts +16 -0
  49. package/src/analytics/react.tsx +241 -0
  50. package/src/analytics/redact.ts +146 -0
  51. package/src/analytics/server-index.ts +17 -0
  52. package/src/analytics/server.ts +277 -0
  53. package/src/auth/index.ts +30 -0
  54. package/src/auth/second-factor-index.ts +16 -0
  55. package/src/auth/second-factor-next.ts +136 -0
  56. package/src/auth/second-factor-routes.ts +40 -0
  57. package/src/auth/second-factor.ts +226 -0
  58. package/src/auth/step-up-client-index.ts +13 -0
  59. package/src/auth/step-up-client.ts +23 -0
  60. package/src/auth/step-up-index.ts +19 -0
  61. package/src/auth/step-up-routes.ts +99 -0
  62. package/src/auth/step-up.ts +432 -0
  63. package/src/auth/two-factor-policy.ts +112 -0
  64. package/src/changelog/changelog.tsx +367 -0
  65. package/src/changelog/index.ts +12 -0
  66. package/src/editor/block-handle.tsx +312 -0
  67. package/src/editor/blocks.ts +169 -0
  68. package/src/editor/bubble-toolbar.tsx +208 -0
  69. package/src/editor/collapsible.ts +159 -0
  70. package/src/editor/content-index.ts +1 -0
  71. package/src/editor/content.tsx +343 -0
  72. package/src/editor/editor.tsx +333 -0
  73. package/src/editor/emoji-index.ts +1 -0
  74. package/src/editor/emoji-picker.tsx +114 -0
  75. package/src/editor/emoji.ts +436 -0
  76. package/src/editor/index.ts +6 -0
  77. package/src/editor/sections.ts +83 -0
  78. package/src/editor/suggestion-popup.tsx +136 -0
  79. package/src/editor/suggestions.ts +309 -0
  80. package/src/editor/ui.tsx +171 -0
  81. package/src/errors/error-shell.tsx +72 -0
  82. package/src/errors/global-error-shell.tsx +116 -0
  83. package/src/errors/index.ts +2 -0
  84. package/src/grid/columns.ts +48 -0
  85. package/src/grid/compare.ts +35 -0
  86. package/src/grid/hidden-columns.ts +95 -0
  87. package/src/grid/index.ts +27 -0
  88. package/src/grid/use-grid.ts +282 -0
  89. package/src/grid/views.ts +70 -0
  90. package/src/guides/guide-article.tsx +92 -0
  91. package/src/guides/guide-figure-zoom.tsx +533 -0
  92. package/src/guides/guide-figure.tsx +68 -0
  93. package/src/guides/guide-toc.tsx +133 -0
  94. package/src/guides/guides-landing.tsx +57 -0
  95. package/src/guides/guides-search.tsx +160 -0
  96. package/src/guides/guides-shell.tsx +60 -0
  97. package/src/guides/guides-sidebar.tsx +93 -0
  98. package/src/guides/index.ts +28 -0
  99. package/src/guides/library.ts +165 -0
  100. package/src/health/health.ts +115 -0
  101. package/src/health/index.ts +11 -0
  102. package/src/internal/cx.ts +4 -0
  103. package/src/internal/next-link.ts +23 -0
  104. package/src/jobs/counts.ts +151 -0
  105. package/src/jobs/cron-auth.ts +60 -0
  106. package/src/jobs/health.ts +315 -0
  107. package/src/jobs/idle.ts +86 -0
  108. package/src/jobs/index.ts +120 -0
  109. package/src/jobs/job-health-list.tsx +316 -0
  110. package/src/jobs/next-index.ts +4 -0
  111. package/src/jobs/next.ts +65 -0
  112. package/src/jobs/prisma-index.ts +12 -0
  113. package/src/jobs/prisma.ts +170 -0
  114. package/src/jobs/prune.ts +79 -0
  115. package/src/jobs/react-index.ts +35 -0
  116. package/src/jobs/registry.ts +189 -0
  117. package/src/jobs/scheduler.ts +437 -0
  118. package/src/jobs/store.ts +212 -0
  119. package/src/jobs/windows.ts +157 -0
  120. package/src/maintenance/core.ts +270 -0
  121. package/src/maintenance/gate.ts +171 -0
  122. package/src/maintenance/index.ts +40 -0
  123. package/src/maintenance/page.ts +76 -0
  124. package/src/maintenance/proxy.ts +88 -0
  125. package/src/maintenance/react-index.ts +7 -0
  126. package/src/maintenance/react.tsx +190 -0
  127. package/src/maintenance/route.ts +82 -0
  128. package/src/maintenance/unavailable.ts +61 -0
  129. package/src/markdown/figure.tsx +132 -0
  130. package/src/markdown/figures.ts +237 -0
  131. package/src/markdown/guide.tsx +536 -0
  132. package/src/markdown/index.ts +53 -0
  133. package/src/markdown/table-view.tsx +74 -0
  134. package/src/markdown/table.ts +90 -0
  135. package/src/password/common.ts +58 -0
  136. package/src/password/estimate-index.ts +18 -0
  137. package/src/password/estimate.ts +715 -0
  138. package/src/password/index.ts +40 -0
  139. package/src/password/password-input.tsx +116 -0
  140. package/src/password/password-strength.tsx +157 -0
  141. package/src/password/reveal.ts +151 -0
  142. package/src/rate-limit/better-auth.ts +94 -0
  143. package/src/rate-limit/index.ts +32 -0
  144. package/src/rate-limit/keys.ts +110 -0
  145. package/src/rate-limit/limiter.ts +276 -0
  146. package/src/rate-limit/prisma-index.ts +12 -0
  147. package/src/rate-limit/prisma.ts +157 -0
  148. package/src/rate-limit/store.ts +47 -0
  149. package/src/release/changelog.ts +364 -0
  150. package/src/release/index.ts +32 -0
  151. package/src/release/version.ts +64 -0
  152. package/src/setup-guide/bits.tsx +420 -0
  153. package/src/setup-guide/card.tsx +358 -0
  154. package/src/setup-guide/class-names.ts +144 -0
  155. package/src/setup-guide/context.tsx +239 -0
  156. package/src/setup-guide/guide.ts +271 -0
  157. package/src/setup-guide/index.ts +76 -0
  158. package/src/setup-guide/launcher.tsx +207 -0
  159. package/src/setup-guide/strip.tsx +127 -0
  160. package/src/styles/house.css +403 -0
  161. package/src/trail/index.ts +12 -0
  162. package/src/trail/rules.ts +84 -0
  163. package/src/trail/trail.tsx +367 -0
  164. package/src/ux/errors.ts +32 -0
  165. package/src/ux/feedback.tsx +41 -0
  166. package/src/ux/index.ts +44 -0
  167. package/src/ux/navigation-index.ts +16 -0
  168. package/src/ux/navigation-progress.tsx +270 -0
  169. package/src/ux/optimistic.ts +415 -0
  170. package/src/ux/use-action.ts +155 -0
  171. package/src/ux/use-optimistic-list.ts +227 -0
  172. package/src/ux/use-optimistic-value.ts +136 -0
  173. package/src/web-search/index.ts +13 -0
  174. package/src/web-search/providers.ts +177 -0
  175. package/src/web-search/types.ts +98 -0
  176. package/src/whats-new/body.tsx +190 -0
  177. package/src/whats-new/index.ts +43 -0
  178. package/src/whats-new/seen.ts +40 -0
  179. package/src/whats-new/select.ts +230 -0
  180. package/src/whats-new/use-whats-new.ts +109 -0
  181. package/src/wizard/index.ts +61 -0
  182. package/src/wizard/invalid.ts +152 -0
  183. package/src/wizard/react-hook-form-index.ts +11 -0
  184. package/src/wizard/rhf-adapter.ts +67 -0
  185. package/src/wizard/rules.ts +137 -0
  186. package/src/wizard/wizard.tsx +442 -0
@@ -0,0 +1,212 @@
1
+ import type { JobActor } from "./registry.js";
2
+ import { isManualKey } from "./windows.js";
3
+
4
+ /**
5
+ * Where runs and switches are kept — the app's, behind this interface.
6
+ *
7
+ * The package owns no schema. Both apps already have a `cron_run` table with
8
+ * the same eight columns, and AltEd keeps its switches in a settings table it
9
+ * shares with the harvest's own screen; a package migration would fight both.
10
+ * The README carries a reference Prisma model and adapter that both existing
11
+ * tables map onto, adding two nullable columns and losing nothing.
12
+ */
13
+
14
+ /** A ledger row as the app stores it. `counts` is whatever JSON is there; it is read through the job's declarations. */
15
+ export interface JobRunRecord {
16
+ id: string;
17
+ job: string;
18
+ windowKey: string;
19
+ /** `null`: a run over every tenant. Otherwise the one tenant a Run now swept. */
20
+ tenantId: string | null;
21
+ /** Who pressed Run now, by name; `null` for the schedule. */
22
+ by: string | null;
23
+ startedAt: Date;
24
+ finishedAt: Date | null;
25
+ ok: boolean;
26
+ counts: unknown;
27
+ error: string | null;
28
+ }
29
+
30
+ export interface JobRunClaim {
31
+ job: string;
32
+ windowKey: string;
33
+ tenantId: string | null;
34
+ by: string | null;
35
+ startedAt: Date;
36
+ }
37
+
38
+ export interface JobRunOutcome {
39
+ finishedAt: Date;
40
+ ok: boolean;
41
+ counts: Record<string, number> | null;
42
+ error: string | null;
43
+ }
44
+
45
+ /** "The most recent run of this job, among these tenants" — `null` in the list meaning runs over every tenant. */
46
+ export interface JobRunQuery {
47
+ job: string;
48
+ tenants: readonly (string | null)[];
49
+ /** Successful runs only. */
50
+ ok?: true;
51
+ /** Run now runs only (their key starts `manual:`). */
52
+ manualOnly?: true;
53
+ }
54
+
55
+ /**
56
+ * Old runs to delete: finished ones that started before `startedBefore`,
57
+ * oldest first, at most `limit` of them — **never** one that is the latest
58
+ * run, or the latest successful run, of its job for its tenant (`null`, the
59
+ * runs over every tenant, counting as one tenant of its own). Health is read
60
+ * from exactly those rows, so a monthly job last run 120 days ago keeps its
61
+ * last run and its last success and does not turn into "never run".
62
+ */
63
+ export interface JobRunPrune {
64
+ startedBefore: Date;
65
+ limit: number;
66
+ }
67
+
68
+ /** Whether a job is switched off, and the latest change. No entry means on. */
69
+ export interface JobSwitchState {
70
+ paused: boolean;
71
+ at: Date | null;
72
+ by: string | null;
73
+ }
74
+
75
+ export interface JobSwitchChange {
76
+ job: string;
77
+ label: string;
78
+ paused: boolean;
79
+ at: Date;
80
+ by: JobActor;
81
+ }
82
+
83
+ export interface JobStore {
84
+ /**
85
+ * Insert the run row, claiming `(job, windowKey)`. Resolve with its id, or
86
+ * with `null` when the pair already exists — the unique index refusing it is
87
+ * the idempotency, so that refusal is an answer, not an error. Anything else
88
+ * throws.
89
+ */
90
+ claimRun(claim: JobRunClaim): Promise<string | null>;
91
+ finishRun(id: string, outcome: JobRunOutcome): Promise<void>;
92
+ latestRun(query: JobRunQuery): Promise<JobRunRecord | null>;
93
+ /**
94
+ * The most recently started run of this job **over any tenant** that has not
95
+ * finished, or `null`. Only a job whose Run now offers both scopes needs it —
96
+ * a platform run must not start while one tenant's run is in flight — and
97
+ * `createScheduler` refuses such a job on a store without it.
98
+ */
99
+ latestUnfinishedRun?(job: string): Promise<JobRunRecord | null>;
100
+ /**
101
+ * Delete old runs by the rules of `JobRunPrune`, in one bounded statement, and
102
+ * resolve with how many were deleted. Only `pruneJobRuns` calls it — from the
103
+ * app's own housekeeping job — and it throws on a store without it.
104
+ */
105
+ pruneRuns?(prune: JobRunPrune): Promise<number>;
106
+ readSwitches(): Promise<ReadonlyMap<string, JobSwitchState>>;
107
+ /**
108
+ * Record a switch. **Write the audit entry here too, in the same
109
+ * transaction:** the switch keeps only the latest change, and a job paused and
110
+ * forgotten — billing reminders, say — is found by asking who, and when.
111
+ */
112
+ writeSwitch(change: JobSwitchChange): Promise<void>;
113
+ }
114
+
115
+ /**
116
+ * A stored switch value, read the way AltEd learnt to: a row that exists but
117
+ * does not read as `{ paused: boolean }` is **paused**. Somebody stored it, and a
118
+ * switch nobody can read should not send a job out spending.
119
+ */
120
+ export function pausedFromStored(value: unknown): boolean {
121
+ if (value && typeof value === "object" && typeof (value as { paused?: unknown }).paused === "boolean") {
122
+ return (value as { paused: boolean }).paused;
123
+ }
124
+ return true;
125
+ }
126
+
127
+ /**
128
+ * The whole contract in memory — for tests, the app's included. It keeps the
129
+ * unique `(job, windowKey)` rule exactly as the database would.
130
+ */
131
+ export function createMemoryJobStore(): Required<JobStore> & {
132
+ runs: JobRunRecord[];
133
+ switches: Map<string, JobSwitchState>;
134
+ switchLog: JobSwitchChange[];
135
+ } {
136
+ const runs: JobRunRecord[] = [];
137
+ const switches = new Map<string, JobSwitchState>();
138
+ const switchLog: JobSwitchChange[] = [];
139
+ let next = 0;
140
+
141
+ return {
142
+ runs,
143
+ switches,
144
+ switchLog,
145
+ async claimRun(claim) {
146
+ if (runs.some((run) => run.job === claim.job && run.windowKey === claim.windowKey)) return null;
147
+ const id = `run-${++next}`;
148
+ runs.push({ id, ...claim, finishedAt: null, ok: false, counts: null, error: null });
149
+ return id;
150
+ },
151
+ async finishRun(id, outcome) {
152
+ const run = runs.find((row) => row.id === id);
153
+ if (!run) throw new Error(`No run ${id}`);
154
+ Object.assign(run, outcome);
155
+ },
156
+ async latestRun(query) {
157
+ return latestOf(
158
+ runs.filter(
159
+ (run) =>
160
+ run.job === query.job &&
161
+ query.tenants.includes(run.tenantId) &&
162
+ (!query.ok || run.ok) &&
163
+ (!query.manualOnly || isManualKey(run.windowKey)),
164
+ ),
165
+ );
166
+ },
167
+ async latestUnfinishedRun(job) {
168
+ return latestOf(runs.filter((run) => run.job === job && run.finishedAt === null));
169
+ },
170
+ async pruneRuns({ startedBefore, limit }) {
171
+ // What health reads: per job and tenant, the latest run and the latest success.
172
+ const kept = new Set<string>();
173
+ const groups = new Map<string, JobRunRecord[]>();
174
+ for (const run of runs) {
175
+ const key = JSON.stringify([run.job, run.tenantId]);
176
+ groups.set(key, [...(groups.get(key) ?? []), run]);
177
+ }
178
+ for (const group of groups.values()) {
179
+ for (const latest of [latestOf(group), latestOf(group.filter((run) => run.ok))]) {
180
+ if (latest) kept.add(latest.id);
181
+ }
182
+ }
183
+ const doomed = runs
184
+ .map((run, index) => ({ run, index }))
185
+ .filter(
186
+ ({ run }) =>
187
+ run.finishedAt !== null && run.startedAt.getTime() < startedBefore.getTime() && !kept.has(run.id),
188
+ )
189
+ .sort((a, b) => a.run.startedAt.getTime() - b.run.startedAt.getTime() || a.index - b.index)
190
+ .slice(0, limit)
191
+ .map(({ run }) => run.id);
192
+ const gone = new Set(doomed);
193
+ for (let i = runs.length - 1; i >= 0; i--) if (gone.has(runs[i]!.id)) runs.splice(i, 1);
194
+ return gone.size;
195
+ },
196
+ async readSwitches() {
197
+ return new Map(switches);
198
+ },
199
+ async writeSwitch(change) {
200
+ switches.set(change.job, { paused: change.paused, at: change.at, by: change.by.name });
201
+ switchLog.push(change);
202
+ },
203
+ };
204
+ }
205
+
206
+ /** Latest by start; on a tie, the one inserted last — what a database's `ORDER BY started_at DESC, id DESC` gives. */
207
+ function latestOf(runs: readonly JobRunRecord[]): JobRunRecord | null {
208
+ return runs.reduce<JobRunRecord | null>(
209
+ (latest, run) => (!latest || run.startedAt.getTime() >= latest.startedAt.getTime() ? run : latest),
210
+ null,
211
+ );
212
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Run windows: which window a moment falls in, or none.
3
+ *
4
+ * A window is a function from "now" to a key, or `null` when the job is not due
5
+ * at all. The key is what the ledger's unique index is on, together with the
6
+ * job, so **one run per job per key** is the whole of idempotency: a second tick
7
+ * in the same window finds the key taken and does nothing.
8
+ *
9
+ * Both apps wrote this as two functions — `attempt(now)` and `windowKey(now)` —
10
+ * which could disagree. One function cannot.
11
+ *
12
+ * The helpers carry one lesson each:
13
+ *
14
+ * - **A day is a day somewhere.** AltEd keyed its tracker job on the UTC date
15
+ * while the job took "yesterday" from the UK calendar; in summer a tick after
16
+ * 23:00 UTC and the next at 00:00 UTC fell in different windows but the same
17
+ * UK day, so that day's misses were sent twice and the next day's never. Every
18
+ * calendar helper takes the `timeZone` the job's own idea of a day comes from.
19
+ * - **Not before a civil hour.** `from` keeps a morning email out of midnight —
20
+ * AltEd's weekly digest waits for 07:00 "so nobody's phone lights up".
21
+ * - **A missed start is caught up, not lost.** Quickie's monthly report ran only
22
+ * on the 1st, so a day of failed ticks on the 1st lost the month. `weekly` and
23
+ * `monthly` stay open from their start to the end of their period (after
24
+ * `from` each day), and the key keeps it to one run.
25
+ *
26
+ * Keys match what both apps already store (`2026-09-30`, `2026-09-30T14`,
27
+ * `2026-09-30Q2`, `month:2026-09`), so moving a job onto a helper does not run
28
+ * it a second time in the window it moves in.
29
+ */
30
+
31
+ export type JobWindow = (now: Date) => string | null;
32
+
33
+ interface ZonedDate {
34
+ year: number;
35
+ month: number;
36
+ day: number;
37
+ hour: number;
38
+ /** 1 = Monday … 7 = Sunday. */
39
+ weekday: number;
40
+ }
41
+
42
+ const WEEKDAYS: Record<string, number> = { Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6, Sun: 7 };
43
+
44
+ const formatters = new Map<string, Intl.DateTimeFormat>();
45
+
46
+ function zoned(now: Date, timeZone: string): ZonedDate {
47
+ let format = formatters.get(timeZone);
48
+ if (!format) {
49
+ format = new Intl.DateTimeFormat("en-US", {
50
+ timeZone,
51
+ year: "numeric",
52
+ month: "2-digit",
53
+ day: "2-digit",
54
+ hour: "2-digit",
55
+ hourCycle: "h23",
56
+ weekday: "short",
57
+ });
58
+ formatters.set(timeZone, format);
59
+ }
60
+ const parts = Object.fromEntries(format.formatToParts(now).map((part) => [part.type, part.value]));
61
+ return {
62
+ year: Number(parts.year),
63
+ month: Number(parts.month),
64
+ day: Number(parts.day),
65
+ hour: Number(parts.hour),
66
+ weekday: WEEKDAYS[parts.weekday ?? ""] ?? 1,
67
+ };
68
+ }
69
+
70
+ const pad = (value: number, width = 2) => String(value).padStart(width, "0");
71
+
72
+ /** `YYYY-MM-DD` for a calendar date, moved by whole days without touching a clock. */
73
+ function dateKey(year: number, month: number, day: number, plusDays = 0): string {
74
+ const date = new Date(Date.UTC(year, month - 1, day + plusDays));
75
+ return `${pad(date.getUTCFullYear(), 4)}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;
76
+ }
77
+
78
+ function checkHour(from: number): void {
79
+ if (!Number.isInteger(from) || from < 0 || from > 23)
80
+ throw new RangeError(`"from" must be an hour, 0–23 (got ${from}).`);
81
+ }
82
+
83
+ export interface CalendarWindowOptions {
84
+ /** The first hour of the day the window is open, in `timeZone`. Default 0. */
85
+ from?: number;
86
+ /** Whose calendar. Default `UTC`. A job that reasons about "today" in the UK says `Europe/London`. */
87
+ timeZone?: string;
88
+ }
89
+
90
+ /** Once an hour. Key `2026-09-30T14` (UTC) — Quickie's hourly key. */
91
+ export function hourly(): JobWindow {
92
+ return (now) => `${now.toISOString().slice(0, 13)}`;
93
+ }
94
+
95
+ /**
96
+ * Once every `hours` hours, in blocks from UTC midnight. Key `2026-09-30Q2` —
97
+ * with 6, exactly Quickie's four-a-day bank feed key.
98
+ */
99
+ export function everyHours(hours: number): JobWindow {
100
+ if (!Number.isInteger(hours) || hours < 1 || 24 % hours !== 0) {
101
+ throw new RangeError(`everyHours takes a whole number of hours that divides the day (got ${hours}).`);
102
+ }
103
+ return (now) => `${now.toISOString().slice(0, 10)}Q${Math.floor(now.getUTCHours() / hours)}`;
104
+ }
105
+
106
+ /** Once a day, from `from` o'clock to midnight in `timeZone`. Key `2026-09-30`, the date there. */
107
+ export function daily(options: CalendarWindowOptions = {}): JobWindow {
108
+ const { from = 0, timeZone = "UTC" } = options;
109
+ checkHour(from);
110
+ return (now) => {
111
+ const at = zoned(now, timeZone);
112
+ return at.hour >= from ? dateKey(at.year, at.month, at.day) : null;
113
+ };
114
+ }
115
+
116
+ /**
117
+ * Once a week, opening on `weekday` (1 = Monday) at `from` and staying open —
118
+ * from `from` each day — until the next one opens. Key `week:2026-09-28`, the
119
+ * date it opened.
120
+ */
121
+ export function weekly(options: CalendarWindowOptions & { weekday?: number } = {}): JobWindow {
122
+ const { weekday = 1, from = 0, timeZone = "UTC" } = options;
123
+ checkHour(from);
124
+ if (!Number.isInteger(weekday) || weekday < 1 || weekday > 7) {
125
+ throw new RangeError(`weekday is 1 (Monday) to 7 (Sunday) (got ${weekday}).`);
126
+ }
127
+ return (now) => {
128
+ const at = zoned(now, timeZone);
129
+ if (at.hour < from) return null;
130
+ const since = (at.weekday - weekday + 7) % 7;
131
+ return `week:${dateKey(at.year, at.month, at.day, -since)}`;
132
+ };
133
+ }
134
+
135
+ /**
136
+ * Once a month, opening on `day` at `from` and staying open — from `from` each
137
+ * day — to the month's end. Key `month:2026-09` — Quickie's monthly key.
138
+ * `day` is 1–28, so the window opens in February too.
139
+ */
140
+ export function monthly(options: CalendarWindowOptions & { day?: number } = {}): JobWindow {
141
+ const { day = 1, from = 0, timeZone = "UTC" } = options;
142
+ checkHour(from);
143
+ if (!Number.isInteger(day) || day < 1 || day > 28) throw new RangeError(`day is 1–28 (got ${day}).`);
144
+ return (now) => {
145
+ const at = zoned(now, timeZone);
146
+ if (at.day < day || at.hour < from) return null;
147
+ return `month:${pad(at.year, 4)}-${pad(at.month)}`;
148
+ };
149
+ }
150
+
151
+ /** The prefix every Run now key starts with, in both apps' existing rows and in this module's. */
152
+ export const MANUAL_KEY_PREFIX = "manual:";
153
+
154
+ /** Whether a stored window key was a Run now rather than the schedule. */
155
+ export function isManualKey(windowKey: string): boolean {
156
+ return windowKey.startsWith(MANUAL_KEY_PREFIX);
157
+ }
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Planned maintenance: what a database server says about its downtime, and what
3
+ * an app should do about it now.
4
+ *
5
+ * Each server publishes `GET /maintenance.json` (the contract is in
6
+ * docs/Maintenance.md §2). This module reads that document and decides, from
7
+ * the window times alone, whether the app is in a window, has one coming, or
8
+ * neither. It decides from the times — not from the `state` the server worked
9
+ * out when it served the document — because an app keeps its last copy and must
10
+ * reach the right answer at 23:00 when the server it would ask is the thing
11
+ * that's down.
12
+ *
13
+ * Pure: no I/O, no clock of its own, no framework.
14
+ */
15
+
16
+ /** The feed version this module understands. A different one is ignored, never guessed at. */
17
+ export const MAINTENANCE_FEED_VERSION = 1;
18
+
19
+ export type MaintenanceWindowKind = "reboot" | "maintenance";
20
+
21
+ /** One window, as an app holds it. Times are ISO strings in UTC. */
22
+ export interface MaintenanceWindow {
23
+ id: string;
24
+ /** `reboot`: booked by the server itself (an update). `maintenance`: booked by hand. */
25
+ kind: MaintenanceWindowKind;
26
+ startsAt: string;
27
+ /** The latest it should be over. After it, the app serves again whatever the server says. */
28
+ endsBy: string;
29
+ /** The honest estimate of the downtime, which is what people are told. */
30
+ expectedMinutes: number;
31
+ /** Set when the work finished — usually well before `endsBy`. */
32
+ endedAt: string | null;
33
+ cancelled: boolean;
34
+ /** What is unavailable meanwhile: `postgres`, `objects`. */
35
+ affects: string[];
36
+ /** Public text from whoever booked it. */
37
+ message: string | null;
38
+ /** The server that published it. */
39
+ server: string;
40
+ }
41
+
42
+ export interface MaintenanceFeed {
43
+ server: string;
44
+ generatedAt: string | null;
45
+ windows: MaintenanceWindow[];
46
+ }
47
+
48
+ const KINDS = new Set<MaintenanceWindowKind>(["reboot", "maintenance"]);
49
+ const MESSAGE_MAX = 280;
50
+
51
+ function isRecord(value: unknown): value is Record<string, unknown> {
52
+ return typeof value === "object" && value !== null && !Array.isArray(value);
53
+ }
54
+
55
+ function time(value: unknown): number | null {
56
+ if (typeof value !== "string" || value === "") return null;
57
+ const ms = Date.parse(value);
58
+ return Number.isNaN(ms) ? null : ms;
59
+ }
60
+
61
+ function iso(ms: number): string {
62
+ return new Date(ms).toISOString();
63
+ }
64
+
65
+ /**
66
+ * The feed, or null when it isn't one this module understands. Malformed
67
+ * windows are dropped one by one rather than failing the whole document, and
68
+ * nothing beyond the contract's fields is kept.
69
+ */
70
+ export function parseMaintenanceFeed(input: unknown): MaintenanceFeed | null {
71
+ if (!isRecord(input) || input.version !== MAINTENANCE_FEED_VERSION || !Array.isArray(input.windows)) return null;
72
+ const server = typeof input.server === "string" && input.server ? input.server.slice(0, 100) : "server";
73
+ const windows: MaintenanceWindow[] = [];
74
+ for (const raw of input.windows) {
75
+ if (!isRecord(raw) || typeof raw.id !== "string" || !raw.id) continue;
76
+ const startsAt = time(raw.starts_at);
77
+ const endsBy = time(raw.ends_by);
78
+ if (startsAt === null || endsBy === null || endsBy <= startsAt) continue;
79
+ const endedAt = time(raw.ended_at);
80
+ const expected = typeof raw.expected_minutes === "number" && raw.expected_minutes > 0 ? raw.expected_minutes : null;
81
+ windows.push({
82
+ id: raw.id.slice(0, 100),
83
+ kind: KINDS.has(raw.kind as MaintenanceWindowKind) ? (raw.kind as MaintenanceWindowKind) : "maintenance",
84
+ startsAt: iso(startsAt),
85
+ endsBy: iso(endsBy),
86
+ expectedMinutes: Math.ceil(expected ?? (endsBy - startsAt) / 60_000),
87
+ endedAt: endedAt === null ? null : iso(endedAt),
88
+ cancelled: raw.state === "cancelled",
89
+ affects: Array.isArray(raw.affects)
90
+ ? raw.affects.filter((a): a is string => typeof a === "string").slice(0, 10)
91
+ : [],
92
+ message: typeof raw.message === "string" && raw.message.trim() ? raw.message.trim().slice(0, MESSAGE_MAX) : null,
93
+ server,
94
+ });
95
+ }
96
+ return { server, generatedAt: typeof input.generated_at === "string" ? input.generated_at : null, windows };
97
+ }
98
+
99
+ export type MaintenancePhase = "none" | "upcoming" | "active";
100
+
101
+ export interface MaintenanceState {
102
+ phase: MaintenancePhase;
103
+ /** The window the phase is about: the active one, or the next one coming. */
104
+ window: MaintenanceWindow | null;
105
+ /** While active: seconds until the window's `endsBy`, for a `Retry-After` header. */
106
+ retryAfterSeconds: number | null;
107
+ }
108
+
109
+ export interface MaintenanceTiming {
110
+ /**
111
+ * How long before the start an app stops serving: requests in flight finish
112
+ * before Postgres terminates their connections. Default 60 seconds.
113
+ */
114
+ leadSeconds?: number;
115
+ /** How far ahead a window is announced. Default 7 days. */
116
+ announceHours?: number;
117
+ }
118
+
119
+ export const NO_MAINTENANCE: MaintenanceState = Object.freeze({ phase: "none", window: null, retryAfterSeconds: null });
120
+
121
+ /**
122
+ * The phase now, from the windows' times:
123
+ *
124
+ * - **active** from `leadSeconds` before a window starts until it ended
125
+ * (`endedAt`) or ran out (`endsBy`), unless it was cancelled;
126
+ * - **upcoming** when a window starts within `announceHours`;
127
+ * - **none** otherwise.
128
+ *
129
+ * Of several active windows the one ending last wins; of several coming, the
130
+ * soonest.
131
+ */
132
+ export function maintenanceState(
133
+ windows: readonly MaintenanceWindow[],
134
+ now: Date,
135
+ timing: MaintenanceTiming = {},
136
+ ): MaintenanceState {
137
+ const t = now.getTime();
138
+ const lead = (timing.leadSeconds ?? 60) * 1000;
139
+ const announce = (timing.announceHours ?? 168) * 3_600_000;
140
+ let active: MaintenanceWindow | null = null;
141
+ let upcoming: MaintenanceWindow | null = null;
142
+ for (const w of windows) {
143
+ if (w.cancelled) continue;
144
+ const ended = time(w.endedAt);
145
+ if (ended !== null && ended <= t) continue;
146
+ const start = Date.parse(w.startsAt);
147
+ const end = Date.parse(w.endsBy);
148
+ if (t >= end) continue;
149
+ if (t >= start - lead) {
150
+ if (!active || end > Date.parse(active.endsBy)) active = w;
151
+ } else if (start - t <= announce) {
152
+ if (!upcoming || start < Date.parse(upcoming.startsAt)) upcoming = w;
153
+ }
154
+ }
155
+ if (active)
156
+ return {
157
+ phase: "active",
158
+ window: active,
159
+ retryAfterSeconds: Math.max(1, Math.ceil((Date.parse(active.endsBy) - t) / 1000)),
160
+ };
161
+ if (upcoming) return { phase: "upcoming", window: upcoming, retryAfterSeconds: null };
162
+ return NO_MAINTENANCE;
163
+ }
164
+
165
+ /** A window standing in for `HOUSE_MAINTENANCE=on`: from now, for an hour, renewed on every read. */
166
+ export function overrideWindow(now: Date): MaintenanceWindow {
167
+ return {
168
+ id: "override",
169
+ kind: "maintenance",
170
+ startsAt: iso(now.getTime()),
171
+ endsBy: iso(now.getTime() + 3_600_000),
172
+ expectedMinutes: 60,
173
+ endedAt: null,
174
+ cancelled: false,
175
+ affects: ["postgres"],
176
+ message: null,
177
+ server: "app",
178
+ };
179
+ }
180
+
181
+ // ─── Words ─────────────────────────────────────────────────────────────────────────
182
+
183
+ export interface WindowWording {
184
+ timeZone?: string;
185
+ locale?: string;
186
+ }
187
+
188
+ /** Minutes a zone is ahead of UTC at a moment, from the wall-clock time it shows. */
189
+ export function offsetMinutes(ms: number, timeZone: string): number {
190
+ const p = Object.fromEntries(
191
+ new Intl.DateTimeFormat("en-US", {
192
+ timeZone,
193
+ year: "numeric",
194
+ month: "numeric",
195
+ day: "numeric",
196
+ hour: "numeric",
197
+ minute: "numeric",
198
+ hourCycle: "h23",
199
+ })
200
+ .formatToParts(new Date(ms))
201
+ .map((x) => [x.type, Number(x.value)]),
202
+ );
203
+ const wall = Date.UTC(p.year!, p.month! - 1, p.day!, p.hour!, p.minute!);
204
+ return Math.round((wall - Math.floor(ms / 60_000) * 60_000) / 60_000);
205
+ }
206
+
207
+ /**
208
+ * The zone's short name. For London, GMT or BST from the offset itself: browsers' time-zone data disagree on what to
209
+ * call it (Chromium has answered "GMT+0", Node "GMT"), and "GMT+1" for summer time would read as wrong to anyone here.
210
+ */
211
+ export function zoneName(ms: number, timeZone: string, given: string | undefined): string {
212
+ if (timeZone === "Europe/London") return offsetMinutes(ms, timeZone) === 0 ? "GMT" : "BST";
213
+ return given ?? "";
214
+ }
215
+
216
+ function parts(ms: number, timeZone: string, locale: string): Record<string, string> {
217
+ return Object.fromEntries(
218
+ new Intl.DateTimeFormat(locale, {
219
+ timeZone,
220
+ weekday: "short",
221
+ day: "numeric",
222
+ month: "short",
223
+ hour: "2-digit",
224
+ minute: "2-digit",
225
+ hourCycle: "h23",
226
+ timeZoneName: "short",
227
+ })
228
+ .formatToParts(new Date(ms))
229
+ .map((p) => [p.type, p.value]),
230
+ );
231
+ }
232
+
233
+ export interface DescribedWindow {
234
+ /** "Wed 4 Nov" */
235
+ day: string;
236
+ /** "23:00" */
237
+ start: string;
238
+ /** "23:15" */
239
+ end: string;
240
+ /** "GMT" or "BST" */
241
+ zone: string;
242
+ /** "Wed 4 Nov, 23:00–23:15 GMT", or both days when it crosses midnight. */
243
+ text: string;
244
+ /** "a few minutes", "about 30 minutes", "about 2 hours" */
245
+ expected: string;
246
+ }
247
+
248
+ /** A window in words, in the app's time zone (Europe/London unless said otherwise). */
249
+ export function describeWindow(
250
+ window: MaintenanceWindow,
251
+ { timeZone = "Europe/London", locale = "en-GB" }: WindowWording = {},
252
+ ): DescribedWindow {
253
+ const s = parts(Date.parse(window.startsAt), timeZone, locale);
254
+ const e = parts(Date.parse(window.endsBy), timeZone, locale);
255
+ const day = `${s.weekday} ${s.day} ${s.month}`;
256
+ const endDay = `${e.weekday} ${e.day} ${e.month}`;
257
+ const start = `${s.hour}:${s.minute}`;
258
+ const end = `${e.hour}:${e.minute}`;
259
+ const zone = zoneName(Date.parse(window.endsBy), timeZone, e.timeZoneName);
260
+ const text = day === endDay ? `${day}, ${start}–${end} ${zone}` : `${day} ${start} – ${endDay} ${end} ${zone}`;
261
+ return { day, start, end, zone, text, expected: expectedText(window.expectedMinutes) };
262
+ }
263
+
264
+ export function expectedText(minutes: number): string {
265
+ const m = Math.max(1, Math.ceil(minutes));
266
+ if (m <= 5) return "a few minutes";
267
+ if (m < 90) return `about ${m} minutes`;
268
+ const hours = Math.round(m / 30) / 2;
269
+ return `about ${hours} hour${hours === 1 ? "" : "s"}`;
270
+ }