@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,189 @@
1
+ import type { CountDeclarations, CountValues } from "./counts.js";
2
+ import type { JobWindow } from "./windows.js";
3
+
4
+ /** Who did something: pressed Run now, switched a job off. Named, because the card says who. */
5
+ export interface JobActor {
6
+ id: string;
7
+ name: string;
8
+ }
9
+
10
+ /**
11
+ * Who a manual run may sweep.
12
+ *
13
+ * - `tenant` — only the caller's own tenant. Quickie's owners: every signup owns
14
+ * an organisation, so an unscoped Run now would let anyone fire every tenant's
15
+ * automations, emailing other businesses' customers.
16
+ * - `platform` — everything, which only someone with platform authority may ask
17
+ * for. AltEd's administrators: AltEd is single-tenant, so every job is a sweep
18
+ * over shared tables and there is no smaller slice to offer.
19
+ */
20
+ export type RunNowScope = "tenant" | "platform";
21
+
22
+ export interface RunNowRule {
23
+ /**
24
+ * Over whom Run now may sweep: one scope, or both.
25
+ *
26
+ * `["tenant", "platform"]` — Quickie's per-organisation jobs: an owner re-runs
27
+ * their own organisation, and an operator re-runs the sweep over every
28
+ * organisation when the overnight one failed. The two are fenced from each
29
+ * other: each has its own cool-down (a tenant's per tenant), neither starts
30
+ * while the other is in flight, and only the platform run counts for the
31
+ * job's health. Offering both needs `JobStore.latestUnfinishedRun`.
32
+ */
33
+ scope: RunNowScope | readonly RunNowScope[];
34
+ /**
35
+ * How soon the same scope may run it again — per tenant for a tenant run.
36
+ * Default ten minutes. A manual run skips the job's hour gates, so without
37
+ * this a second press sends the whole batch again. `0` turns it off.
38
+ */
39
+ cooldownMs?: number;
40
+ }
41
+
42
+ const SCOPE_ORDER: readonly RunNowScope[] = ["tenant", "platform"];
43
+
44
+ /**
45
+ * The scopes a rule offers, narrowest first, each once: `["tenant"]`,
46
+ * `["platform"]` or `["tenant", "platform"]`. Nothing when Run now is off.
47
+ */
48
+ export function runNowScopes(rule: false | RunNowRule | undefined): RunNowScope[] {
49
+ if (!rule) return [];
50
+ const declared: readonly unknown[] = Array.isArray(rule.scope) ? rule.scope : [rule.scope];
51
+ return SCOPE_ORDER.filter((scope) => declared.includes(scope));
52
+ }
53
+
54
+ /** What a run is handed. */
55
+ export interface JobContext {
56
+ now: Date;
57
+ trigger: "schedule" | "manual";
58
+ /**
59
+ * `null`: sweep every tenant (the schedule, or a platform Run now). A string:
60
+ * sweep **only** this tenant — a tenant-scoped Run now always has one, and the
61
+ * job must pass it down to every query it makes.
62
+ */
63
+ tenantId: string | null;
64
+ /** A manual run: skip the job's own hour gates. It is not a licence to skip a per-recipient throttle. */
65
+ force: boolean;
66
+ windowKey: string;
67
+ /** Who pressed Run now; `null` for the schedule. */
68
+ by: JobActor | null;
69
+ }
70
+
71
+ export interface JobDefinition<C extends CountDeclarations = CountDeclarations> {
72
+ /** Stable, and stored: the ledger's `job` column and the switch's key. Lower-case, `-` between words, ≤ 60. */
73
+ id: string;
74
+ /** What the card calls it: "Payment reminders". */
75
+ label: string;
76
+ /** When it runs, in words: "Daily, from 09:00". The window is the rule; this is how the card says it. */
77
+ cadence: string;
78
+ /**
79
+ * `tick` (the default): the dispatcher runs it from the app's one tick route.
80
+ * `own`: it has its own route and clock — AltEd's harvest every ten minutes,
81
+ * its import runner every minute — which calls `runOwn`. The tick never runs it.
82
+ */
83
+ schedule?: "tick" | "own";
84
+ /** Which window a moment is in, or `null` when not due. Required for `tick`; optional for `own`. */
85
+ window?: JobWindow;
86
+ /**
87
+ * How long without a successful whole run before the card says **Stale**.
88
+ * `null` for a job that runs only when there is work — an import runner idle
89
+ * all week is not stale.
90
+ */
91
+ staleAfterMs: number | null;
92
+ /** How long a run may go unfinished before the card calls it failed. Default 15 minutes. */
93
+ timeoutMs?: number;
94
+ /** Whether an administrator may switch it off. Default `true`. */
95
+ switchable?: boolean;
96
+ /** Whether Run now is offered, and over whom. Default: never. */
97
+ runNow?: false | RunNowRule;
98
+ /** Every number `run` reports, each with its words and kind. See `CountDeclaration`. */
99
+ counts: C;
100
+ run: (context: JobContext) => Promise<CountValues<C>>;
101
+ }
102
+
103
+ /** A job with its count types erased — how the registry holds a list of different ones. */
104
+ export type AnyJob = JobDefinition<CountDeclarations>;
105
+
106
+ /** `R`, with every key `C` does not declare forbidden. */
107
+ type OnlyDeclared<R, C> = R & { [K in Exclude<keyof R, keyof C>]: never };
108
+
109
+ /**
110
+ * A job's definition, checked against its own counts at compile time: `run`
111
+ * must report every count `counts` declares, and nothing it does not — a
112
+ * number with no declaration has no words to be shown in. (At run time an
113
+ * undeclared key is dropped before it is stored, so it cannot reach a screen
114
+ * either way.)
115
+ */
116
+ export function defineJob<const C extends CountDeclarations, R extends CountValues<C>>(
117
+ job: Omit<JobDefinition<C>, "run"> & { run: (context: JobContext) => Promise<OnlyDeclared<R, C>> },
118
+ ): AnyJob {
119
+ return job as unknown as AnyJob;
120
+ }
121
+
122
+ export const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000;
123
+ export const DEFAULT_COOLDOWN_MS = 10 * 60 * 1000;
124
+ export const MAX_JOB_ID = 60;
125
+ export const MAX_WINDOW_KEY = 120;
126
+
127
+ const ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
128
+
129
+ const positive = (value: unknown) => typeof value === "number" && Number.isFinite(value) && value > 0;
130
+
131
+ /**
132
+ * Every way a list of jobs is wrong, as sentences — the same shape as
133
+ * `releaseHistoryProblems`, so a test can assert it is empty and read the
134
+ * failure when it is not.
135
+ */
136
+ export function jobDefinitionProblems(jobs: readonly AnyJob[]): string[] {
137
+ const problems: string[] = [];
138
+ const seen = new Set<string>();
139
+ for (const job of jobs) {
140
+ const name = job.id || "(a job with no id)";
141
+ if (!ID.test(job.id) || job.id.length > MAX_JOB_ID) {
142
+ problems.push(
143
+ `"${name}" is not a job id: lower-case letters and digits, "-" between words, ${MAX_JOB_ID} at most.`,
144
+ );
145
+ }
146
+ if (seen.has(job.id)) problems.push(`"${name}" is declared twice.`);
147
+ seen.add(job.id);
148
+ if (!job.label?.trim()) problems.push(`"${name}" has no label.`);
149
+ if (!job.cadence?.trim()) problems.push(`"${name}" has no cadence — say when it runs, in words.`);
150
+ if ((job.schedule ?? "tick") === "tick" && typeof job.window !== "function") {
151
+ problems.push(`"${name}" runs from the tick but has no window, so it could never be due.`);
152
+ }
153
+ if (job.staleAfterMs !== null && !positive(job.staleAfterMs)) {
154
+ problems.push(
155
+ `"${name}" needs a staleness threshold in milliseconds, or null for a job that runs only on demand.`,
156
+ );
157
+ }
158
+ if (job.timeoutMs !== undefined && !positive(job.timeoutMs))
159
+ problems.push(`"${name}" has a timeout that is not positive.`);
160
+ if (job.runNow) {
161
+ const declared: readonly unknown[] = Array.isArray(job.runNow.scope) ? job.runNow.scope : [job.runNow.scope];
162
+ if (declared.length === 0 || declared.some((scope) => scope !== "tenant" && scope !== "platform")) {
163
+ problems.push(`"${name}" offers Run now without saying over whom — "tenant" or "platform".`);
164
+ } else if (new Set(declared).size !== declared.length) {
165
+ problems.push(`"${name}" offers Run now over the same scope twice.`);
166
+ }
167
+ const cooldown = job.runNow.cooldownMs;
168
+ if (cooldown !== undefined && !(Number.isFinite(cooldown) && cooldown >= 0)) {
169
+ problems.push(`"${name}" has a Run now cool-down that is not zero or more.`);
170
+ }
171
+ }
172
+ for (const [key, count] of Object.entries(job.counts ?? {})) {
173
+ const words =
174
+ typeof count.label === "string" ? count.label : `${count.label?.one ?? ""}${count.label?.other ?? ""}`;
175
+ if (!words.trim()) problems.push(`"${name}" reports "${key}" with no label, which would show as a bare key.`);
176
+ if (count.kind === "money" && !/^[A-Z]{3}$/.test(count.currency ?? "")) {
177
+ problems.push(`"${name}" reports "${key}" as money with no ISO currency code.`);
178
+ }
179
+ }
180
+ }
181
+ return problems;
182
+ }
183
+
184
+ /** The app's job list, checked once, when the module that declares it loads. Throws every problem at once. */
185
+ export function defineJobs(jobs: readonly AnyJob[]): readonly AnyJob[] {
186
+ const problems = jobDefinitionProblems(jobs);
187
+ if (problems.length) throw new Error(`The scheduled jobs are misdeclared:\n- ${problems.join("\n- ")}`);
188
+ return Object.freeze([...jobs]);
189
+ }
@@ -0,0 +1,437 @@
1
+ import { errorMessage } from "../ux/errors.js";
2
+ import { countLines, countsSummary, declaredCounts, type CountFormatOptions, type CountLine } from "./counts.js";
3
+ import { buildJobView, effectiveTimeout, formatWhen, type JobAudience, type JobView } from "./health.js";
4
+ import {
5
+ DEFAULT_COOLDOWN_MS,
6
+ DEFAULT_TIMEOUT_MS,
7
+ MAX_WINDOW_KEY,
8
+ runNowScopes,
9
+ type AnyJob,
10
+ type JobActor,
11
+ type JobContext,
12
+ type RunNowScope,
13
+ } from "./registry.js";
14
+ import type { JobStore, JobSwitchState } from "./store.js";
15
+ import { MANUAL_KEY_PREFIX } from "./windows.js";
16
+
17
+ /** What the tick did with one job. */
18
+ export type TickStatus = "ran" | "failed" | "already-ran" | "not-due" | "paused";
19
+
20
+ export interface TickResult {
21
+ job: string;
22
+ status: TickStatus;
23
+ windowKey?: string;
24
+ counts?: Record<string, number>;
25
+ error?: string;
26
+ /** One sentence, for the route's answer and the log. */
27
+ message: string;
28
+ }
29
+
30
+ export type RunNowRefusal = "unknown" | "not-runnable" | "out-of-scope" | "paused" | "running" | "too-soon";
31
+
32
+ /** `scope` on a run says what it swept — the app's audit entry says "for every organisation" or not by it. */
33
+ export type RunNowOutcome =
34
+ | { status: "ran"; job: string; scope: RunNowScope; windowKey: string; counts: CountLine[]; message: string }
35
+ | { status: "failed"; job: string; scope: RunNowScope; windowKey: string; error: string; message: string }
36
+ | { status: "refused"; job: string; reason: RunNowRefusal; message: string };
37
+
38
+ export type SwitchRefusal = "unknown" | "not-switchable" | "out-of-scope";
39
+
40
+ export type SwitchOutcome =
41
+ | { status: "switched" | "unchanged"; job: string; paused: boolean; message: string }
42
+ | { status: "refused"; job: string; reason: SwitchRefusal; message: string };
43
+
44
+ /** Who pressed Run now, and what they may reach. The app has already checked they are signed in and may use the screen. */
45
+ export interface RunNowCaller extends JobAudience {
46
+ actor: JobActor;
47
+ /**
48
+ * Which Run now was pressed, on a job that offers both — the list hands it
49
+ * to `onRunNow`. Left out, a job with one scope runs over that one (as in
50
+ * 0.11.0), and a job with both runs over the caller's own tenant when they
51
+ * have one, and over every tenant when they do not. It is a request, never
52
+ * an authority: `platform` and `tenantId` still decide whether it is allowed.
53
+ */
54
+ scope?: RunNowScope;
55
+ }
56
+
57
+ export interface SwitchCaller {
58
+ actor: JobActor;
59
+ /** Switching a job off stops it for every tenant, so it takes platform authority. */
60
+ platform: boolean;
61
+ }
62
+
63
+ export interface SchedulerOptions extends CountFormatOptions {
64
+ jobs: readonly AnyJob[];
65
+ store: JobStore;
66
+ /** How long a run may stay unfinished before it reads as failed, for jobs that do not say. Default 15 minutes. */
67
+ timeoutMs?: number;
68
+ /** The clock. Tests pass one; everything else leaves it. */
69
+ clock?: () => Date;
70
+ }
71
+
72
+ export interface Scheduler {
73
+ readonly jobs: readonly AnyJob[];
74
+ /** The tick route's whole body: every `tick` job whose window is open, once per window, one failure isolated. */
75
+ tick(now?: Date): Promise<TickResult[]>;
76
+ /** An own-schedule job's route: the switch, its window if it has one, the ledger. */
77
+ runOwn(jobId: string, now?: Date): Promise<TickResult>;
78
+ /** Run now — refused unless the job offers it, over a scope the caller holds. */
79
+ runNow(jobId: string, caller: RunNowCaller, now?: Date): Promise<RunNowOutcome>;
80
+ /** Switch a job off or on, recording who and when. */
81
+ setPaused(jobId: string, paused: boolean, caller: SwitchCaller, now?: Date): Promise<SwitchOutcome>;
82
+ /** Every job as the health screen draws it, for this viewer. */
83
+ views(audience: JobAudience, now?: Date): Promise<JobView[]>;
84
+ /**
85
+ * Every tick job's window now, without the database: a tick with the same signature as the last one that finished
86
+ * has nothing to do. `idleTick` caches the tick on it.
87
+ */
88
+ signature(now?: Date): string;
89
+ }
90
+
91
+ /** Every tick job's window key at `now` — `-` where it is not due — in declaration order. No database. */
92
+ export function tickSignature(jobs: readonly AnyJob[], now: Date): string {
93
+ return jobs
94
+ .filter((job) => (job.schedule ?? "tick") === "tick")
95
+ .map((job) => `${job.id}=${job.window?.(now) ?? "-"}`)
96
+ .join("|");
97
+ }
98
+
99
+ const MAX_ERROR = 1000;
100
+
101
+ function messageOf(error: unknown): string {
102
+ const message = errorMessage(error, "It failed without saying why.");
103
+ return message.length > MAX_ERROR ? `${message.slice(0, MAX_ERROR - 1)}…` : message;
104
+ }
105
+
106
+ const minutes = (ms: number) => {
107
+ const n = Math.max(1, Math.round(ms / 60_000));
108
+ return `${n} minute${n === 1 ? "" : "s"}`;
109
+ };
110
+
111
+ /**
112
+ * The dispatcher, and everything else that touches the ledger.
113
+ *
114
+ * Declared once in the app beside its jobs and its store adapter; the tick
115
+ * route, the own-schedule routes, the Run now and switch routes and the health
116
+ * page all call this one object.
117
+ */
118
+ export function createScheduler(options: SchedulerOptions): Scheduler {
119
+ const { jobs, store } = options;
120
+ const dual = jobs.filter((job) => runNowScopes(job.runNow).length > 1).map((job) => `"${job.id}"`);
121
+ if (dual.length && typeof store.latestUnfinishedRun !== "function") {
122
+ throw new Error(
123
+ `${dual.join(", ")} ${dual.length === 1 ? "offers" : "offer"} Run now over both scopes, which needs ` +
124
+ "JobStore.latestUnfinishedRun: a run over every tenant must not start while one tenant's is in flight.",
125
+ );
126
+ }
127
+ const clock = options.clock ?? (() => new Date());
128
+ const fallbackTimeout = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
129
+ const format: CountFormatOptions = { locale: options.locale };
130
+ const find = (id: string) => jobs.find((job) => job.id === id);
131
+
132
+ /** Run a claimed job and record the outcome. Never throws. */
133
+ async function execute(job: AnyJob, runId: string, context: JobContext) {
134
+ let counts: Record<string, number> | null = null;
135
+ let error: string | null = null;
136
+ try {
137
+ counts = declaredCounts(job.counts, await job.run(context));
138
+ } catch (thrown) {
139
+ error = messageOf(thrown);
140
+ }
141
+ let unrecorded: string | null = null;
142
+ try {
143
+ await store.finishRun(runId, { finishedAt: clock(), ok: error === null, counts, error });
144
+ } catch (thrown) {
145
+ // The work is done (or failed) either way; the ledger just doesn't know.
146
+ // It will read as "never finished" once the timeout passes, which is true.
147
+ unrecorded = messageOf(thrown);
148
+ }
149
+ return { counts, error, unrecorded };
150
+ }
151
+
152
+ /** The switch, the window, the claim and the run — for one job, with nothing allowed to escape. */
153
+ async function dispatch(
154
+ job: AnyJob,
155
+ now: Date,
156
+ switches: ReadonlyMap<string, JobSwitchState> | Error,
157
+ windowKeyFor: (now: Date) => string | null,
158
+ ): Promise<TickResult> {
159
+ const base = { job: job.id };
160
+ try {
161
+ if (job.switchable ?? true) {
162
+ if (switches instanceof Error) {
163
+ return {
164
+ ...base,
165
+ status: "failed",
166
+ error: switches.message,
167
+ message: `${job.label} didn't start: whether it is switched on couldn't be read (${switches.message}).`,
168
+ };
169
+ }
170
+ const state = switches.get(job.id);
171
+ if (state?.paused) {
172
+ // Its window is not claimed, so switched back on inside the same window it still runs.
173
+ const who = state.by ? ` by ${state.by}` : "";
174
+ const when = state.at ? ` on ${formatWhen(state.at.toISOString())}` : "";
175
+ return { ...base, status: "paused", message: `${job.label} is switched off${who}${when}; not started.` };
176
+ }
177
+ }
178
+
179
+ const windowKey = windowKeyFor(now);
180
+ if (windowKey === null) return { ...base, status: "not-due", message: `${job.label} is not due.` };
181
+ if (windowKey.length > MAX_WINDOW_KEY) {
182
+ throw new Error(`Its window key is longer than ${MAX_WINDOW_KEY} characters.`);
183
+ }
184
+
185
+ const runId = await store.claimRun({ job: job.id, windowKey, tenantId: null, by: null, startedAt: now });
186
+ if (runId === null) {
187
+ return { ...base, windowKey, status: "already-ran", message: `${job.label} has already run in ${windowKey}.` };
188
+ }
189
+
190
+ const context: JobContext = { now, trigger: "schedule", tenantId: null, force: false, windowKey, by: null };
191
+ const { counts, error, unrecorded } = await execute(job, runId, context);
192
+ if (error !== null) {
193
+ return { ...base, windowKey, status: "failed", error, message: `${job.label} failed: ${error}` };
194
+ }
195
+ const summary = countsSummary(countLines(job.counts, counts, format));
196
+ return {
197
+ ...base,
198
+ windowKey,
199
+ status: "ran",
200
+ counts: counts ?? {},
201
+ ...(unrecorded ? { error: unrecorded } : {}),
202
+ message: unrecorded
203
+ ? `${job.label} ran, but its result couldn't be recorded: ${unrecorded}`
204
+ : `${job.label} ran${summary ? `: ${summary}` : ""}.`,
205
+ };
206
+ } catch (thrown) {
207
+ // A store that failed to claim, a window function that threw: this job's
208
+ // problem, reported as this job's result. The next job still runs.
209
+ const error = messageOf(thrown);
210
+ return { ...base, status: "failed", error, message: `${job.label} didn't run: ${error}` };
211
+ }
212
+ }
213
+
214
+ async function readSwitches(): Promise<ReadonlyMap<string, JobSwitchState> | Error> {
215
+ try {
216
+ return await store.readSwitches();
217
+ } catch (thrown) {
218
+ return new Error(messageOf(thrown));
219
+ }
220
+ }
221
+
222
+ return {
223
+ jobs,
224
+
225
+ signature(now = clock()) {
226
+ return tickSignature(jobs, now);
227
+ },
228
+
229
+ async tick(now = clock()) {
230
+ const switches = await readSwitches();
231
+ const results: TickResult[] = [];
232
+ // One at a time, in declaration order: predictable load, and the order the card lists them in.
233
+ for (const job of jobs) {
234
+ if ((job.schedule ?? "tick") !== "tick") continue;
235
+ results.push(await dispatch(job, now, switches, (at) => job.window!(at)));
236
+ }
237
+ return results;
238
+ },
239
+
240
+ async runOwn(jobId, now = clock()) {
241
+ const job = find(jobId);
242
+ if (!job || job.schedule !== "own") {
243
+ throw new Error(`"${jobId}" is not a job with its own schedule.`);
244
+ }
245
+ return dispatch(job, now, await readSwitches(), (at) =>
246
+ job.window ? job.window(at) : `run:${at.toISOString()}`,
247
+ );
248
+ },
249
+
250
+ async runNow(jobId, caller, now = clock()) {
251
+ const job = find(jobId);
252
+ if (!job)
253
+ return { status: "refused", job: jobId, reason: "unknown", message: "There is no scheduled job by that name." };
254
+ const refuse = (reason: RunNowRefusal, message: string): RunNowOutcome => ({
255
+ status: "refused",
256
+ job: job.id,
257
+ reason,
258
+ message,
259
+ });
260
+
261
+ const rule = job.runNow;
262
+ const offered = runNowScopes(rule);
263
+ if (!rule || offered.length === 0) return refuse("not-runnable", `${job.label} runs on its schedule only.`);
264
+ const scope: RunNowScope =
265
+ caller.scope ?? (offered.length === 1 ? offered[0]! : caller.tenantId ? "tenant" : "platform");
266
+ if (!offered.includes(scope)) {
267
+ return refuse(
268
+ "out-of-scope",
269
+ scope === "platform"
270
+ ? `${job.label} can only be run for one organisation at a time, not across every account.`
271
+ : `${job.label} runs across every account only; it can't be run for one organisation.`,
272
+ );
273
+ }
274
+ if (scope === "tenant" && !caller.tenantId) {
275
+ return refuse("out-of-scope", `${job.label} can only be run for your own organisation, and you aren't in one.`);
276
+ }
277
+ if (scope === "platform" && !caller.platform) {
278
+ return refuse(
279
+ "out-of-scope",
280
+ `${job.label} runs across every account, so only a platform administrator can run it.`,
281
+ );
282
+ }
283
+ const tenantId = scope === "tenant" ? caller.tenantId! : null;
284
+
285
+ if ((job.switchable ?? true) && (await store.readSwitches()).get(job.id)?.paused) {
286
+ return refuse("paused", `${job.label} is switched off. Turn it back on to run it.`);
287
+ }
288
+
289
+ // Nothing in flight that this run could overlap: a sweep over every tenant (the schedule's, or a platform
290
+ // Run now) covers this tenant too; and on a job with both scopes, a platform run covers every tenant's.
291
+ const latest =
292
+ tenantId === null && offered.length > 1
293
+ ? await store.latestUnfinishedRun!(job.id)
294
+ : await store.latestRun({ job: job.id, tenants: tenantId === null ? [null] : [null, tenantId] });
295
+ const timeout = effectiveTimeout(job, fallbackTimeout);
296
+ if (latest && !latest.finishedAt && now.getTime() - latest.startedAt.getTime() <= timeout) {
297
+ return refuse(
298
+ "running",
299
+ `${job.label} is running now — it started ${formatWhen(latest.startedAt.toISOString())}.`,
300
+ );
301
+ }
302
+
303
+ const cooldown = rule.cooldownMs ?? DEFAULT_COOLDOWN_MS;
304
+ if (cooldown > 0) {
305
+ const last = await store.latestRun({ job: job.id, tenants: [tenantId], manualOnly: true });
306
+ const since = last ? now.getTime() - last.startedAt.getTime() : Infinity;
307
+ if (since < cooldown) {
308
+ return refuse(
309
+ "too-soon",
310
+ `${job.label} was run ${minutes(since)} ago. It can be run again in ${minutes(cooldown - since)}.`,
311
+ );
312
+ }
313
+ }
314
+
315
+ // Two presses in the same breath share a key, so the index lets one through.
316
+ const at = cooldown > 0 ? new Date(Math.floor(now.getTime() / cooldown) * cooldown) : now;
317
+ const windowKey = `${MANUAL_KEY_PREFIX}${tenantId === null ? "platform" : `tenant:${tenantId}`}:${at.toISOString()}`;
318
+ if (windowKey.length > MAX_WINDOW_KEY) throw new Error(`The Run now key for ${job.id} is too long to store.`);
319
+ const runId = await store.claimRun({ job: job.id, windowKey, tenantId, by: caller.actor.name, startedAt: now });
320
+ if (runId === null) return refuse("too-soon", `${job.label} has just been run.`);
321
+
322
+ const context: JobContext = { now, trigger: "manual", tenantId, force: true, windowKey, by: caller.actor };
323
+ const { counts, error } = await execute(job, runId, context);
324
+ if (error !== null) {
325
+ return { status: "failed", job: job.id, scope, windowKey, error, message: `${job.label} failed: ${error}` };
326
+ }
327
+ const lines = countLines(job.counts, counts, format);
328
+ const summary = countsSummary(lines);
329
+ return {
330
+ status: "ran",
331
+ job: job.id,
332
+ scope,
333
+ windowKey,
334
+ counts: lines,
335
+ message: `Ran ${job.label}${summary ? ` — ${summary}` : ""}.`,
336
+ };
337
+ },
338
+
339
+ async setPaused(jobId, paused, caller, now = clock()) {
340
+ const job = find(jobId);
341
+ if (!job)
342
+ return { status: "refused", job: jobId, reason: "unknown", message: "There is no scheduled job by that name." };
343
+ if (!(job.switchable ?? true)) {
344
+ return {
345
+ status: "refused",
346
+ job: job.id,
347
+ reason: "not-switchable",
348
+ message: `${job.label} can't be switched off.`,
349
+ };
350
+ }
351
+ if (!caller.platform) {
352
+ return {
353
+ status: "refused",
354
+ job: job.id,
355
+ reason: "out-of-scope",
356
+ message: `Switching ${job.label} off stops it for every account, so only a platform administrator can.`,
357
+ };
358
+ }
359
+ const current = (await store.readSwitches()).get(job.id)?.paused ?? false;
360
+ if (current === paused) {
361
+ return {
362
+ status: "unchanged",
363
+ job: job.id,
364
+ paused,
365
+ message: paused ? `${job.label} is already paused.` : `${job.label} is already on.`,
366
+ };
367
+ }
368
+ await store.writeSwitch({ job: job.id, label: job.label, paused, at: now, by: caller.actor });
369
+ return {
370
+ status: "switched",
371
+ job: job.id,
372
+ paused,
373
+ message: paused
374
+ ? `${job.label} is paused. A run already under way finishes; no more start until you turn it back on.`
375
+ : `${job.label} is back on. It runs at its next scheduled time.`,
376
+ };
377
+ },
378
+
379
+ async views(audience, now = clock()) {
380
+ const switches = await store.readSwitches();
381
+ const tenants = audience.tenantId ? [null, audience.tenantId] : [null];
382
+ return Promise.all(
383
+ jobs.map(async (job) => {
384
+ const [latest, lastWholeSuccess, lastVisibleSuccess] = await Promise.all([
385
+ store.latestRun({ job: job.id, tenants }),
386
+ store.latestRun({ job: job.id, tenants: [null], ok: true }),
387
+ tenants.length > 1 ? store.latestRun({ job: job.id, tenants, ok: true }) : null,
388
+ ]);
389
+ return buildJobView(
390
+ job,
391
+ {
392
+ switch: switches.get(job.id) ?? null,
393
+ latest,
394
+ lastWholeSuccess,
395
+ lastVisibleSuccess: tenants.length > 1 ? lastVisibleSuccess : lastWholeSuccess,
396
+ },
397
+ audience,
398
+ { now, timeoutMs: fallbackTimeout, locale: options.locale },
399
+ );
400
+ }),
401
+ );
402
+ },
403
+ };
404
+ }
405
+
406
+ /** The tick in one line: "2 ran, 1 failed, 1 paused, 5 not due". */
407
+ export function summariseTick(results: readonly TickResult[]): string {
408
+ const order: [TickStatus, string][] = [
409
+ ["ran", "ran"],
410
+ ["failed", "failed"],
411
+ ["paused", "paused"],
412
+ ["already-ran", "already ran"],
413
+ ["not-due", "not due"],
414
+ ];
415
+ const parts = order.flatMap(([status, words]) => {
416
+ const n = results.filter((result) => result.status === status).length;
417
+ return n ? [`${n} ${words}`] : [];
418
+ });
419
+ return parts.length ? parts.join(", ") : "No scheduled jobs";
420
+ }
421
+
422
+ /** The HTTP status a refusal maps to, so every app answers the same refusal the same way. */
423
+ export function refusalStatus(reason: RunNowRefusal | SwitchRefusal): 403 | 404 | 409 | 429 {
424
+ switch (reason) {
425
+ case "unknown":
426
+ return 404;
427
+ case "not-runnable":
428
+ case "not-switchable":
429
+ case "out-of-scope":
430
+ return 403;
431
+ case "paused":
432
+ case "running":
433
+ return 409;
434
+ case "too-soon":
435
+ return 429;
436
+ }
437
+ }