@connextar/house 0.23.1 → 0.23.3

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 (180) hide show
  1. package/README.md +22 -3
  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 +20 -3
  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/react.d.ts.map +1 -1
  11. package/dist/analytics/react.js +4 -2
  12. package/dist/analytics/react.js.map +1 -1
  13. package/dist/analytics/redact.d.ts.map +1 -1
  14. package/dist/analytics/redact.js +6 -1
  15. package/dist/analytics/redact.js.map +1 -1
  16. package/package.json +5 -2
  17. package/src/account/data-contract.ts +112 -0
  18. package/src/account/index.ts +11 -0
  19. package/src/admin/access.ts +267 -0
  20. package/src/admin/audit.ts +238 -0
  21. package/src/admin/bootstrap.ts +220 -0
  22. package/src/admin/client-index.ts +19 -0
  23. package/src/admin/client.tsx +187 -0
  24. package/src/admin/index.ts +91 -0
  25. package/src/admin/proof.ts +155 -0
  26. package/src/admin/second-factor-index.ts +16 -0
  27. package/src/admin/second-factor.ts +403 -0
  28. package/src/admin/testing-index.ts +13 -0
  29. package/src/admin/testing.ts +299 -0
  30. package/src/admin/view-as.ts +511 -0
  31. package/src/ai/config-index.ts +40 -0
  32. package/src/ai/config.ts +176 -0
  33. package/src/ai/images.ts +18 -0
  34. package/src/ai/index.ts +21 -0
  35. package/src/ai/pricing.ts +107 -0
  36. package/src/ai/provider.ts +403 -0
  37. package/src/analytics/browser.ts +400 -0
  38. package/src/analytics/client-index.ts +12 -0
  39. package/src/analytics/config.ts +89 -0
  40. package/src/analytics/index.ts +17 -0
  41. package/src/analytics/ingest.ts +81 -0
  42. package/src/analytics/react-index.ts +16 -0
  43. package/src/analytics/react.tsx +241 -0
  44. package/src/analytics/redact.ts +146 -0
  45. package/src/analytics/server-index.ts +17 -0
  46. package/src/analytics/server.ts +277 -0
  47. package/src/auth/index.ts +30 -0
  48. package/src/auth/second-factor-index.ts +16 -0
  49. package/src/auth/second-factor-next.ts +136 -0
  50. package/src/auth/second-factor-routes.ts +40 -0
  51. package/src/auth/second-factor.ts +226 -0
  52. package/src/auth/step-up-client-index.ts +13 -0
  53. package/src/auth/step-up-client.ts +23 -0
  54. package/src/auth/step-up-index.ts +19 -0
  55. package/src/auth/step-up-routes.ts +99 -0
  56. package/src/auth/step-up.ts +432 -0
  57. package/src/auth/two-factor-policy.ts +112 -0
  58. package/src/changelog/changelog.tsx +367 -0
  59. package/src/changelog/index.ts +12 -0
  60. package/src/editor/block-handle.tsx +312 -0
  61. package/src/editor/blocks.ts +169 -0
  62. package/src/editor/bubble-toolbar.tsx +208 -0
  63. package/src/editor/collapsible.ts +159 -0
  64. package/src/editor/content-index.ts +1 -0
  65. package/src/editor/content.tsx +343 -0
  66. package/src/editor/editor.tsx +333 -0
  67. package/src/editor/emoji-index.ts +1 -0
  68. package/src/editor/emoji-picker.tsx +114 -0
  69. package/src/editor/emoji.ts +436 -0
  70. package/src/editor/index.ts +6 -0
  71. package/src/editor/sections.ts +83 -0
  72. package/src/editor/suggestion-popup.tsx +136 -0
  73. package/src/editor/suggestions.ts +309 -0
  74. package/src/editor/ui.tsx +171 -0
  75. package/src/errors/error-shell.tsx +72 -0
  76. package/src/errors/global-error-shell.tsx +116 -0
  77. package/src/errors/index.ts +2 -0
  78. package/src/grid/columns.ts +48 -0
  79. package/src/grid/compare.ts +35 -0
  80. package/src/grid/hidden-columns.ts +95 -0
  81. package/src/grid/index.ts +27 -0
  82. package/src/grid/use-grid.ts +282 -0
  83. package/src/grid/views.ts +70 -0
  84. package/src/guides/guide-article.tsx +92 -0
  85. package/src/guides/guide-figure-zoom.tsx +533 -0
  86. package/src/guides/guide-figure.tsx +68 -0
  87. package/src/guides/guide-toc.tsx +133 -0
  88. package/src/guides/guides-landing.tsx +57 -0
  89. package/src/guides/guides-search.tsx +160 -0
  90. package/src/guides/guides-shell.tsx +60 -0
  91. package/src/guides/guides-sidebar.tsx +93 -0
  92. package/src/guides/index.ts +28 -0
  93. package/src/guides/library.ts +165 -0
  94. package/src/health/health.ts +115 -0
  95. package/src/health/index.ts +11 -0
  96. package/src/internal/cx.ts +4 -0
  97. package/src/internal/next-link.ts +23 -0
  98. package/src/jobs/counts.ts +151 -0
  99. package/src/jobs/cron-auth.ts +60 -0
  100. package/src/jobs/health.ts +315 -0
  101. package/src/jobs/idle.ts +86 -0
  102. package/src/jobs/index.ts +120 -0
  103. package/src/jobs/job-health-list.tsx +316 -0
  104. package/src/jobs/next-index.ts +4 -0
  105. package/src/jobs/next.ts +65 -0
  106. package/src/jobs/prisma-index.ts +12 -0
  107. package/src/jobs/prisma.ts +170 -0
  108. package/src/jobs/prune.ts +79 -0
  109. package/src/jobs/react-index.ts +35 -0
  110. package/src/jobs/registry.ts +189 -0
  111. package/src/jobs/scheduler.ts +437 -0
  112. package/src/jobs/store.ts +212 -0
  113. package/src/jobs/windows.ts +157 -0
  114. package/src/maintenance/core.ts +270 -0
  115. package/src/maintenance/gate.ts +171 -0
  116. package/src/maintenance/index.ts +40 -0
  117. package/src/maintenance/page.ts +76 -0
  118. package/src/maintenance/proxy.ts +88 -0
  119. package/src/maintenance/react-index.ts +7 -0
  120. package/src/maintenance/react.tsx +190 -0
  121. package/src/maintenance/route.ts +82 -0
  122. package/src/maintenance/unavailable.ts +61 -0
  123. package/src/markdown/figure.tsx +132 -0
  124. package/src/markdown/figures.ts +237 -0
  125. package/src/markdown/guide.tsx +536 -0
  126. package/src/markdown/index.ts +53 -0
  127. package/src/markdown/table-view.tsx +74 -0
  128. package/src/markdown/table.ts +90 -0
  129. package/src/password/common.ts +58 -0
  130. package/src/password/estimate-index.ts +18 -0
  131. package/src/password/estimate.ts +715 -0
  132. package/src/password/index.ts +40 -0
  133. package/src/password/password-input.tsx +116 -0
  134. package/src/password/password-strength.tsx +157 -0
  135. package/src/password/reveal.ts +151 -0
  136. package/src/rate-limit/better-auth.ts +94 -0
  137. package/src/rate-limit/index.ts +32 -0
  138. package/src/rate-limit/keys.ts +110 -0
  139. package/src/rate-limit/limiter.ts +276 -0
  140. package/src/rate-limit/prisma-index.ts +12 -0
  141. package/src/rate-limit/prisma.ts +157 -0
  142. package/src/rate-limit/store.ts +47 -0
  143. package/src/release/changelog.ts +364 -0
  144. package/src/release/index.ts +32 -0
  145. package/src/release/version.ts +64 -0
  146. package/src/setup-guide/bits.tsx +420 -0
  147. package/src/setup-guide/card.tsx +358 -0
  148. package/src/setup-guide/class-names.ts +144 -0
  149. package/src/setup-guide/context.tsx +239 -0
  150. package/src/setup-guide/guide.ts +271 -0
  151. package/src/setup-guide/index.ts +76 -0
  152. package/src/setup-guide/launcher.tsx +207 -0
  153. package/src/setup-guide/strip.tsx +127 -0
  154. package/src/styles/house.css +384 -0
  155. package/src/trail/index.ts +12 -0
  156. package/src/trail/rules.ts +84 -0
  157. package/src/trail/trail.tsx +367 -0
  158. package/src/ux/errors.ts +32 -0
  159. package/src/ux/feedback.tsx +41 -0
  160. package/src/ux/index.ts +44 -0
  161. package/src/ux/navigation-index.ts +16 -0
  162. package/src/ux/navigation-progress.tsx +270 -0
  163. package/src/ux/optimistic.ts +415 -0
  164. package/src/ux/use-action.ts +155 -0
  165. package/src/ux/use-optimistic-list.ts +227 -0
  166. package/src/ux/use-optimistic-value.ts +136 -0
  167. package/src/web-search/index.ts +13 -0
  168. package/src/web-search/providers.ts +177 -0
  169. package/src/web-search/types.ts +98 -0
  170. package/src/whats-new/body.tsx +190 -0
  171. package/src/whats-new/index.ts +43 -0
  172. package/src/whats-new/seen.ts +40 -0
  173. package/src/whats-new/select.ts +230 -0
  174. package/src/whats-new/use-whats-new.ts +109 -0
  175. package/src/wizard/index.ts +61 -0
  176. package/src/wizard/invalid.ts +152 -0
  177. package/src/wizard/react-hook-form-index.ts +11 -0
  178. package/src/wizard/rhf-adapter.ts +67 -0
  179. package/src/wizard/rules.ts +137 -0
  180. package/src/wizard/wizard.tsx +442 -0
@@ -0,0 +1,316 @@
1
+ "use client";
2
+
3
+ import {
4
+ CircleCheck,
5
+ CirclePause,
6
+ CircleX,
7
+ Clock,
8
+ LoaderCircle,
9
+ Play,
10
+ TriangleAlert,
11
+ type LucideIcon,
12
+ } from "lucide-react";
13
+ import * as React from "react";
14
+
15
+ import { cx } from "../internal/cx.js";
16
+ import { useKeyedAction, type KeyedAction } from "../ux/use-action.js";
17
+ import { useOptimisticValue } from "../ux/use-optimistic-value.js";
18
+ import { countsSummary } from "./counts.js";
19
+ import {
20
+ describeHealth,
21
+ describeRun,
22
+ describeSwitch,
23
+ type HealthWords,
24
+ type JobHealth,
25
+ type JobView,
26
+ type WhenOptions,
27
+ } from "./health.js";
28
+ import type { RunNowScope } from "./registry.js";
29
+
30
+ /** Every element the list draws. Each value replaces the default for that part. */
31
+ export interface JobHealthClassNames {
32
+ list: string;
33
+ empty: string;
34
+ row: string;
35
+ body: string;
36
+ heading: string;
37
+ label: string;
38
+ badge: string;
39
+ badgeGood: string;
40
+ badgeNeutral: string;
41
+ badgeWarning: string;
42
+ badgeBad: string;
43
+ meta: string;
44
+ detail: string;
45
+ error: string;
46
+ counts: string;
47
+ switched: string;
48
+ actions: string;
49
+ runNow: string;
50
+ switch: string;
51
+ switchOn: string;
52
+ switchOff: string;
53
+ thumb: string;
54
+ thumbOn: string;
55
+ thumbOff: string;
56
+ }
57
+
58
+ /** The house look, on the shared theme tokens. */
59
+ export const JOB_HEALTH_CLASS_NAMES: JobHealthClassNames = {
60
+ list: "flex flex-col divide-y divide-border",
61
+ empty: "text-sm text-muted-foreground",
62
+ row: "flex flex-wrap items-start justify-between gap-3 py-3 first:pt-0 last:pb-0",
63
+ body: "flex min-w-0 flex-1 flex-col gap-1",
64
+ heading: "flex flex-wrap items-center gap-2",
65
+ label: "text-sm font-medium text-foreground",
66
+ badge: "inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-medium [&_svg]:size-3",
67
+ badgeGood: "border-primary/30 bg-primary/10 text-primary",
68
+ badgeNeutral: "border-border text-muted-foreground",
69
+ badgeWarning: "border-destructive/40 text-destructive",
70
+ badgeBad: "border-destructive/40 bg-destructive/10 text-destructive",
71
+ meta: "text-xs text-muted-foreground",
72
+ detail: "text-xs text-muted-foreground",
73
+ error: "text-xs text-destructive",
74
+ counts: "text-xs text-muted-foreground tabular-nums",
75
+ switched: "text-xs text-muted-foreground",
76
+ actions: "flex shrink-0 items-center gap-3",
77
+ runNow:
78
+ "inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs font-medium text-foreground transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:pointer-events-none disabled:opacity-60 [&_svg]:size-3.5",
79
+ switch:
80
+ "relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
81
+ switchOn: "bg-primary",
82
+ switchOff: "bg-muted-foreground/30",
83
+ thumb: "pointer-events-none block size-4 rounded-full bg-card shadow transition-transform",
84
+ thumbOn: "translate-x-4",
85
+ thumbOff: "translate-x-0",
86
+ };
87
+
88
+ const ICONS: Record<JobHealth["state"], LucideIcon> = {
89
+ paused: CirclePause,
90
+ "never-run": Clock,
91
+ running: LoaderCircle,
92
+ failed: CircleX,
93
+ stale: TriangleAlert,
94
+ healthy: CircleCheck,
95
+ };
96
+
97
+ export interface JobHealthListProps extends WhenOptions {
98
+ /** From `scheduler.views(audience)` on the server. */
99
+ jobs: readonly JobView[];
100
+ /**
101
+ * Switch a job. **Throw to refuse**, with the reason as the message — the
102
+ * switch goes back where it was and the reason is reported through the
103
+ * `ActionFeedbackProvider`. Without it no switch is drawn.
104
+ */
105
+ onSwitch?: (jobId: string, on: boolean) => Promise<void>;
106
+ /**
107
+ * Run a job now, over `scope` — the button pressed. Resolve with the route's
108
+ * `message` to have it said; throw to refuse. Send the scope to the route and
109
+ * on to `scheduler.runNow` as the caller's `scope`: on a job that offers both,
110
+ * it is what tells the two buttons apart.
111
+ */
112
+ onRunNow?: (jobId: string, scope: RunNowScope) => Promise<{ message?: string } | void>;
113
+ /**
114
+ * What each Run now sweeps, in the app's words, for a row that offers this
115
+ * viewer both — "Run for every organisation", "Run for yours". A row with one
116
+ * says only "Run now". Default "every account" and "your account".
117
+ */
118
+ runNowWords?: Partial<Record<RunNowScope, string>>;
119
+ /** After a switch lands or a run finishes — usually `router.refresh()`. */
120
+ onSettled?: () => void;
121
+ /** Anything of the app's own under a row: AltEd's link to the harvest's screen. */
122
+ extra?: (job: JobView) => React.ReactNode;
123
+ emptyText?: React.ReactNode;
124
+ className?: string;
125
+ classNames?: Partial<JobHealthClassNames>;
126
+ }
127
+
128
+ /**
129
+ * The health screen's list: each job's schedule, last run, what it did in
130
+ * words, its health, and — for whoever may — its switch and Run now.
131
+ *
132
+ * The switch is an optimistic value: it moves on the click, the badge with it,
133
+ * and a refusal puts both back and says why. AltEd's switch did not move until
134
+ * the server answered, and greyed out every other switch on the screen while it
135
+ * waited.
136
+ *
137
+ * Draws plain elements on the theme tokens, like the wizard; there is still no
138
+ * `Button` in this package. The app wraps it in its own card and heading.
139
+ */
140
+ export function JobHealthList({
141
+ jobs,
142
+ onSwitch,
143
+ onRunNow,
144
+ onSettled,
145
+ runNowWords,
146
+ extra,
147
+ emptyText = "No scheduled jobs.",
148
+ className,
149
+ classNames,
150
+ locale,
151
+ timeZone,
152
+ }: JobHealthListProps) {
153
+ const c: JobHealthClassNames = { ...JOB_HEALTH_CLASS_NAMES, ...classNames };
154
+ const actions = useKeyedAction();
155
+ if (jobs.length === 0) return <p className={c.empty}>{emptyText}</p>;
156
+ return (
157
+ <ul className={cx(c.list, className)}>
158
+ {jobs.map((job) => (
159
+ <JobRow
160
+ key={job.id}
161
+ job={job}
162
+ c={c}
163
+ actions={actions}
164
+ onSwitch={onSwitch}
165
+ onRunNow={onRunNow}
166
+ onSettled={onSettled}
167
+ scopeWords={{ ...RUN_NOW_WORDS, ...runNowWords }}
168
+ extra={extra}
169
+ when={{ locale, timeZone }}
170
+ />
171
+ ))}
172
+ </ul>
173
+ );
174
+ }
175
+
176
+ const RUN_NOW_WORDS: Record<RunNowScope, string> = { tenant: "your account", platform: "every account" };
177
+
178
+ function toneClass(c: JobHealthClassNames, words: HealthWords): string {
179
+ switch (words.tone) {
180
+ case "good":
181
+ return c.badgeGood;
182
+ case "warning":
183
+ return c.badgeWarning;
184
+ case "bad":
185
+ return c.badgeBad;
186
+ default:
187
+ return c.badgeNeutral;
188
+ }
189
+ }
190
+
191
+ function JobRow({
192
+ job,
193
+ c,
194
+ actions,
195
+ onSwitch,
196
+ onRunNow,
197
+ onSettled,
198
+ scopeWords,
199
+ extra,
200
+ when,
201
+ }: {
202
+ job: JobView;
203
+ c: JobHealthClassNames;
204
+ actions: KeyedAction;
205
+ onSwitch?: JobHealthListProps["onSwitch"];
206
+ onRunNow?: JobHealthListProps["onRunNow"];
207
+ onSettled?: () => void;
208
+ scopeWords: Record<RunNowScope, string>;
209
+ extra?: JobHealthListProps["extra"];
210
+ when: WhenOptions;
211
+ }) {
212
+ const on = useOptimisticValue(!job.paused, { onSettled });
213
+
214
+ // Health with the switch as the screen shows it, not as the server last said.
215
+ const health: JobHealth = on.value ? job.healthIfOn : { state: "paused" };
216
+ const words = describeHealth(health, when);
217
+ const Icon = ICONS[health.state];
218
+
219
+ const run = job.lastRun;
220
+ const success = job.lastSuccess;
221
+ const countsLine =
222
+ run?.ok && run.counts.length
223
+ ? countsSummary(run.counts)
224
+ : success && !run?.ok
225
+ ? [describeRun(success, "Last success", when), countsSummary(success.counts)].filter(Boolean).join(": ")
226
+ : null;
227
+
228
+ const detail = health.state === "running" ? null : words.detail;
229
+ const switchLine = on.pending ? (on.value ? "Turning back on…" : "Pausing…") : describeSwitch(job, when);
230
+
231
+ const toggle = () => {
232
+ if (!onSwitch) return;
233
+ const next = !on.value;
234
+ void on.set(
235
+ next,
236
+ async () => {
237
+ await onSwitch(job.id, next);
238
+ },
239
+ { error: next ? `Couldn't turn ${job.label} back on` : `Couldn't pause ${job.label}` },
240
+ );
241
+ };
242
+
243
+ const runNow = (scope: RunNowScope) => {
244
+ if (!onRunNow) return;
245
+ // Keyed on the job, not the scope: while one of its runs is under way, neither button starts another.
246
+ void actions.run(job.id, () => onRunNow(job.id, scope), {
247
+ success: (result) => (result && result.message) || `Ran ${job.label}.`,
248
+ error: `Couldn't run ${job.label}`,
249
+ // A failed run is on the ledger too, so the screen has something new to show either way.
250
+ onSuccess: () => onSettled?.(),
251
+ onError: () => onSettled?.(),
252
+ });
253
+ };
254
+
255
+ const running = actions.isPending(job.id);
256
+ const showSwitch = job.canSwitch && Boolean(onSwitch);
257
+ // `runNow` null is the last word: a view an app narrowed by hand offers nothing.
258
+ const scopes: RunNowScope[] =
259
+ !onRunNow || job.runNow === null ? [] : job.runNowScopes.length ? job.runNowScopes : [job.runNow];
260
+ const showRunNow = scopes.length > 0;
261
+
262
+ return (
263
+ <li className={c.row} data-job={job.id} data-health={health.state}>
264
+ <div className={c.body}>
265
+ <div className={c.heading}>
266
+ <span className={c.label}>{job.label}</span>
267
+ <span className={cx(c.badge, toneClass(c, words))}>
268
+ <Icon aria-hidden="true" />
269
+ {words.label}
270
+ </span>
271
+ </div>
272
+ <p className={c.meta}>
273
+ {job.cadence}
274
+ {run ? ` · ${describeRun(run, "Last run", when)}` : ""}
275
+ </p>
276
+ {detail ? <p className={health.state === "failed" ? c.error : c.detail}>{detail}</p> : null}
277
+ {countsLine ? <p className={c.counts}>{countsLine}</p> : null}
278
+ {switchLine ? <p className={c.switched}>{switchLine}</p> : null}
279
+ {extra?.(job)}
280
+ </div>
281
+ {showSwitch || showRunNow ? (
282
+ <div className={c.actions}>
283
+ {scopes.map((scope) => (
284
+ <button
285
+ key={scope}
286
+ type="button"
287
+ className={c.runNow}
288
+ onClick={() => runNow(scope)}
289
+ disabled={running || !on.value}
290
+ title={on.value ? undefined : "Switched off — turn it back on to run it"}
291
+ data-busy={running ? "true" : undefined}
292
+ data-scope={scope}
293
+ aria-label={scopes.length > 1 ? `Run ${job.label} now for ${scopeWords[scope]}` : `Run ${job.label} now`}
294
+ >
295
+ <Play aria-hidden="true" />
296
+ {scopes.length > 1 ? `Run for ${scopeWords[scope]}` : "Run now"}
297
+ </button>
298
+ ))}
299
+ {showSwitch ? (
300
+ <button
301
+ type="button"
302
+ role="switch"
303
+ aria-checked={on.value}
304
+ aria-label={job.label}
305
+ aria-busy={on.pending || undefined}
306
+ className={cx(c.switch, on.value ? c.switchOn : c.switchOff)}
307
+ onClick={toggle}
308
+ >
309
+ <span className={cx(c.thumb, on.value ? c.thumbOn : c.thumbOff)} />
310
+ </button>
311
+ ) : null}
312
+ </div>
313
+ ) : null}
314
+ </li>
315
+ );
316
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * `@connextar/house/jobs/next` — the idle tick's memo over Next's data cache. The only jobs entry that imports Next.
3
+ */
4
+ export { DEFAULT_TICK_TAG, expireIdleTick, nextTickMemo, type NextTickMemoOptions } from "./next.js";
@@ -0,0 +1,65 @@
1
+ import { revalidateTag, unstable_cache } from "next/cache.js";
2
+
3
+ import type { TickMemo } from "./idle.js";
4
+ import type { TickResult } from "./scheduler.js";
5
+
6
+ /**
7
+ * `TickMemo` over Next's shared data cache, for `idleTick`: the first call with a signature runs the tick, and every
8
+ * other call in those windows — on any instance — answers from the cache without touching the database.
9
+ *
10
+ * Each call builds its own cached function, closing over its own `fresh` flag. Next keys `unstable_cache` on the
11
+ * function's source, the key parts and the arguments, never on the closure, so every call shares one entry while each
12
+ * knows for itself whether it ran. Quickie's single module-level flag was shared by concurrent calls on one instance.
13
+ *
14
+ * Outside Next's runtime (a test calling the route handler) there is no data cache, and the tick simply runs.
15
+ */
16
+
17
+ export const DEFAULT_TICK_TAG = "cron-tick";
18
+
19
+ export interface NextTickMemoOptions {
20
+ /** The cache tag, to expire with `expireIdleTick`. Default `cron-tick`. */
21
+ tag?: string;
22
+ /** Read afresh at least this often, in seconds, whatever the signature. Default an hour. */
23
+ revalidateSeconds?: number;
24
+ }
25
+
26
+ const missingCache = (error: unknown) => error instanceof Error && /incrementalCache missing/i.test(error.message);
27
+
28
+ export function nextTickMemo(options: NextTickMemoOptions = {}): TickMemo {
29
+ const tag = options.tag ?? DEFAULT_TICK_TAG;
30
+ const revalidate = options.revalidateSeconds ?? 60 * 60;
31
+ if (!Number.isFinite(revalidate) || revalidate <= 0) {
32
+ throw new Error("[jobs] nextTickMemo's revalidateSeconds must be more than 0.");
33
+ }
34
+ return async (signature, run) => {
35
+ let fresh = false;
36
+ const cached = unstable_cache(
37
+ // The signature is the cache key: an argument so Next keys on it, unused in the body.
38
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
39
+ async (_signature: string): Promise<TickResult[]> => {
40
+ fresh = true;
41
+ return run();
42
+ },
43
+ ["house-jobs-tick", tag],
44
+ { tags: [tag], revalidate },
45
+ );
46
+ try {
47
+ return { results: await cached(signature), fresh };
48
+ } catch (error) {
49
+ if (!fresh && missingCache(error)) return { results: await run(), fresh: true };
50
+ throw error;
51
+ }
52
+ };
53
+ }
54
+
55
+ /**
56
+ * Expire the remembered tick, so the next call runs the scheduler: call it where something the signature cannot see
57
+ * changes — a job switched back on inside its window. Outside a request there is nothing cached to expire.
58
+ */
59
+ export function expireIdleTick(tag: string = DEFAULT_TICK_TAG): void {
60
+ try {
61
+ revalidateTag(tag, { expire: 0 });
62
+ } catch {
63
+ // No request scope: nothing cached here to expire.
64
+ }
65
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@connextar/house/jobs/prisma` — the reference `JobStore` over the reference `CronRun` model, claiming a window
3
+ * with `INSERT … ON CONFLICT DO NOTHING`. Imports nothing: the Prisma client is passed in.
4
+ */
5
+ export {
6
+ prismaJobStore,
7
+ pruneRunsSql,
8
+ type CronRunDelegate,
9
+ type CronRunRow,
10
+ type PrismaJobStoreOptions,
11
+ type RawSql,
12
+ } from "./prisma.js";
@@ -0,0 +1,170 @@
1
+ import type { JobRunRecord, JobStore } from "./store.js";
2
+ import { MANUAL_KEY_PREFIX } from "./windows.js";
3
+
4
+ /**
5
+ * The reference `JobStore` over the reference `CronRun` model (the README's), for any app on Prisma and Postgres.
6
+ *
7
+ * AltEd, Quickie and senco each wrote this adapter from the README, and two of the three still claim a window the way
8
+ * the README used to say: a plain insert, with the unique index's refusal caught as P2002. Postgres raises and logs
9
+ * that refusal as an error and rolls the statement back, every time — AltEd's server counted 127 of them a night
10
+ * before v0.173.4 moved to `INSERT … ON CONFLICT DO NOTHING`, which Prisma writes as `createManyAndReturn` with
11
+ * `skipDuplicates`: a second claim comes back empty, "already ran", and nothing is logged. This is that adapter.
12
+ *
13
+ * Typed structurally, so the package imports no Prisma: pass `prisma.cronRun` as `runs` and `prisma` as `sql`. An app
14
+ * whose Prisma types object passes them through `as never`; the shape is checked by the tests here, not by Prisma.
15
+ *
16
+ * The switches stay the app's (`readSwitches`, `writeSwitch`): AltEd keeps them in a settings table it shares with a
17
+ * screen of its own, Quickie in `cron_switch`, senco as a log in `cron_switch_change`, and the audit entry has to be
18
+ * written in the app's own transaction.
19
+ */
20
+
21
+ /** A row of the reference `CronRun` model, as Prisma answers it. */
22
+ export interface CronRunRow {
23
+ id: string;
24
+ job: string;
25
+ windowKey: string;
26
+ tenantId: string | null;
27
+ triggeredBy: string | null;
28
+ startedAt: Date;
29
+ finishedAt: Date | null;
30
+ ok: boolean;
31
+ counts: unknown;
32
+ error: string | null;
33
+ }
34
+
35
+ /** The part of `prisma.cronRun` the store calls. `createManyAndReturn` needs Prisma 5.14 or later, on Postgres. */
36
+ export interface CronRunDelegate {
37
+ createManyAndReturn(args: {
38
+ data: {
39
+ job: string;
40
+ windowKey: string;
41
+ tenantId: string | null;
42
+ triggeredBy: string | null;
43
+ startedAt: Date;
44
+ }[];
45
+ skipDuplicates: true;
46
+ select: { id: true };
47
+ }): Promise<{ id: string }[]>;
48
+ update(args: { where: { id: string }; data: Record<string, unknown> }): Promise<unknown>;
49
+ findFirst(args: {
50
+ where: Record<string, unknown>;
51
+ orderBy: Record<string, "asc" | "desc">[];
52
+ }): Promise<CronRunRow | null>;
53
+ }
54
+
55
+ /** `prisma` itself, for the one statement Prisma's query API cannot say: pruning by window function. */
56
+ export interface RawSql {
57
+ $executeRawUnsafe(query: string, ...values: unknown[]): Promise<number>;
58
+ }
59
+
60
+ export interface PrismaJobStoreOptions {
61
+ /** `prisma.cronRun`. */
62
+ runs: CronRunDelegate;
63
+ /** `prisma` — needed only for `pruneRuns`; without it, `pruneJobRuns` says so by name. */
64
+ sql?: RawSql;
65
+ /** The table and columns as they are in the database, for `pruneRuns`. Default: the reference model's. */
66
+ table?: string;
67
+ columns?: Partial<Record<"id" | "job" | "tenantId" | "ok" | "startedAt" | "finishedAt", string>>;
68
+ readSwitches: JobStore["readSwitches"];
69
+ writeSwitch: JobStore["writeSwitch"];
70
+ }
71
+
72
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
73
+
74
+ function quoted(name: string): string {
75
+ if (!IDENTIFIER.test(name)) throw new Error(`[jobs] "${name}" is not a plain SQL identifier.`);
76
+ return `"${name}"`;
77
+ }
78
+
79
+ const record = (row: CronRunRow): JobRunRecord => ({
80
+ id: row.id,
81
+ job: row.job,
82
+ windowKey: row.windowKey,
83
+ tenantId: row.tenantId,
84
+ by: row.triggeredBy,
85
+ startedAt: row.startedAt,
86
+ finishedAt: row.finishedAt,
87
+ ok: row.ok,
88
+ counts: row.counts,
89
+ error: row.error,
90
+ });
91
+
92
+ /** One statement, at most `limit` rows, oldest first, never a run under way, a job's latest run or its latest success. */
93
+ export function pruneRunsSql(table = "cron_run", columns: PrismaJobStoreOptions["columns"] = {}): string {
94
+ const c = {
95
+ id: quoted(columns.id ?? "id"),
96
+ job: quoted(columns.job ?? "job"),
97
+ tenantId: quoted(columns.tenantId ?? "tenant_id"),
98
+ ok: quoted(columns.ok ?? "ok"),
99
+ startedAt: quoted(columns.startedAt ?? "started_at"),
100
+ finishedAt: quoted(columns.finishedAt ?? "finished_at"),
101
+ };
102
+ const t = quoted(table);
103
+ // `PARTITION BY` groups every NULL tenant together, which is exactly "the runs over every tenant".
104
+ return `DELETE FROM ${t} WHERE ${c.id} IN (
105
+ SELECT ${c.id} FROM (
106
+ SELECT ${c.id}, ${c.ok}, ${c.startedAt}, ${c.finishedAt},
107
+ ROW_NUMBER() OVER (PARTITION BY ${c.job}, ${c.tenantId} ORDER BY ${c.startedAt} DESC, ${c.id} DESC) AS "nth",
108
+ ROW_NUMBER() OVER (PARTITION BY ${c.job}, ${c.tenantId}, ${c.ok} ORDER BY ${c.startedAt} DESC, ${c.id} DESC) AS "nth_of_kind"
109
+ FROM ${t}
110
+ ) AS "ranked"
111
+ WHERE ${c.startedAt} < $1
112
+ AND ${c.finishedAt} IS NOT NULL
113
+ AND "nth" > 1
114
+ AND NOT (${c.ok} AND "nth_of_kind" = 1)
115
+ ORDER BY ${c.startedAt}, ${c.id}
116
+ LIMIT $2
117
+ )`;
118
+ }
119
+
120
+ export function prismaJobStore(options: PrismaJobStoreOptions): Required<JobStore> {
121
+ const { runs, sql } = options;
122
+ const prune = pruneRunsSql(options.table, options.columns);
123
+ const latestOrder: Record<string, "desc">[] = [{ startedAt: "desc" }, { id: "desc" }];
124
+
125
+ return {
126
+ async claimRun({ job, windowKey, tenantId, by, startedAt }) {
127
+ // INSERT … ON CONFLICT DO NOTHING: a window already claimed comes back empty, and Postgres raises nothing.
128
+ const rows = await runs.createManyAndReturn({
129
+ data: [{ job, windowKey, tenantId, triggeredBy: by, startedAt }],
130
+ skipDuplicates: true,
131
+ select: { id: true },
132
+ });
133
+ return rows[0]?.id ?? null;
134
+ },
135
+
136
+ async finishRun(id, { finishedAt, ok, counts, error }) {
137
+ await runs.update({ where: { id }, data: { finishedAt, ok, error, ...(counts ? { counts } : {}) } });
138
+ },
139
+
140
+ async latestRun({ job, tenants, ok, manualOnly }) {
141
+ const row = await runs.findFirst({
142
+ where: {
143
+ job,
144
+ // `{ tenantId: null }` matches the runs over every tenant.
145
+ OR: tenants.map((tenantId) => ({ tenantId })),
146
+ ...(ok ? { ok: true } : {}),
147
+ ...(manualOnly ? { windowKey: { startsWith: MANUAL_KEY_PREFIX } } : {}),
148
+ },
149
+ // `id` breaks a tie the way `pruneRuns` does, so the row read as latest is the row pruning keeps.
150
+ orderBy: latestOrder,
151
+ });
152
+ return row ? record(row) : null;
153
+ },
154
+
155
+ async latestUnfinishedRun(job) {
156
+ const row = await runs.findFirst({ where: { job, finishedAt: null }, orderBy: latestOrder });
157
+ return row ? record(row) : null;
158
+ },
159
+
160
+ async pruneRuns({ startedBefore, limit }) {
161
+ if (!sql) {
162
+ throw new Error("[jobs] prismaJobStore needs `sql` (the Prisma client) to prune the ledger.");
163
+ }
164
+ return sql.$executeRawUnsafe(prune, startedBefore, limit);
165
+ },
166
+
167
+ readSwitches: () => options.readSwitches(),
168
+ writeSwitch: (change) => options.writeSwitch(change),
169
+ };
170
+ }
@@ -0,0 +1,79 @@
1
+ import type { CountDeclarations, CountValues } from "./counts.js";
2
+ import type { JobStore } from "./store.js";
3
+
4
+ /**
5
+ * Pruning the ledger — from the app's own housekeeping job, a bounded batch a
6
+ * day.
7
+ *
8
+ * The ledger grows without end (AltEd writes about 150 rows a day), and a Run
9
+ * now row keeps the name of whoever pressed it. Old rows are history, not
10
+ * state — with two exceptions, which are the whole of the care here. Health is
11
+ * read from the latest run and the latest successful run of each job (and, for
12
+ * a tenant's own Run now, of each job for that tenant). Delete those and a
13
+ * monthly job that last ran 120 days ago reads **Never run**; delete an
14
+ * unfinished one and a run under way loses its row. So those are never
15
+ * deleted, however old, and everything else past the retention period is.
16
+ */
17
+
18
+ const DAY = 24 * 60 * 60 * 1000;
19
+
20
+ /** How long a run is kept, unless it is one health reads. */
21
+ export const DEFAULT_JOB_RUN_RETENTION_DAYS = 90;
22
+
23
+ /** At most this many rows a call, so one housekeeping run never holds the table for long. */
24
+ export const DEFAULT_JOB_RUN_PRUNE_BATCH = 1000;
25
+
26
+ /**
27
+ * What `pruneJobRuns` reports, declared so it reads "12 old job runs removed".
28
+ * Spread it into the housekeeping job's `counts`, and the result into what its
29
+ * `run` returns.
30
+ */
31
+ export const JOB_RUN_PRUNE_COUNTS = {
32
+ jobRunsPruned: { label: { one: "old job run removed", other: "old job runs removed" } },
33
+ } as const satisfies CountDeclarations;
34
+
35
+ export type JobRunPruneCounts = CountValues<typeof JOB_RUN_PRUNE_COUNTS>;
36
+
37
+ export interface PruneJobRunsOptions {
38
+ /** The clock. The housekeeping job passes its `now`. */
39
+ now?: Date;
40
+ /**
41
+ * Keep every run for this many days. Default 90. At least 1 — a day, not a
42
+ * millisecond count, so `90` cannot be mistaken for 90 ms and empty the ledger.
43
+ */
44
+ retentionDays?: number;
45
+ /** Delete at most this many rows in the call. Default 1000. Whatever is left goes next time. */
46
+ batchLimit?: number;
47
+ }
48
+
49
+ /**
50
+ * Delete runs older than the retention period — never the latest run or the
51
+ * latest successful run of a job (per tenant, for tenants' own runs, and once
52
+ * for the runs over every tenant), and never one that has not finished — at
53
+ * most `batchLimit` of them, oldest first. Running it again straight away
54
+ * deletes only what the first call's limit left.
55
+ *
56
+ * ```ts
57
+ * counts: { windowsPruned: { label: "…" }, ...JOB_RUN_PRUNE_COUNTS },
58
+ * run: async ({ now }) => ({ windowsPruned: await pruneRateLimits(), ...(await pruneJobRuns(jobStore, { now })) }),
59
+ * ```
60
+ */
61
+ export async function pruneJobRuns(store: JobStore, options: PruneJobRunsOptions = {}): Promise<JobRunPruneCounts> {
62
+ const retentionDays = options.retentionDays ?? DEFAULT_JOB_RUN_RETENTION_DAYS;
63
+ const limit = options.batchLimit ?? DEFAULT_JOB_RUN_PRUNE_BATCH;
64
+ if (!(Number.isFinite(retentionDays) && retentionDays >= 1)) {
65
+ throw new RangeError(`The job run retention is a number of days, at least 1 (got ${retentionDays}).`);
66
+ }
67
+ if (!(Number.isInteger(limit) && limit >= 1)) {
68
+ throw new RangeError(`The job run prune batch is a whole number of rows, at least 1 (got ${limit}).`);
69
+ }
70
+ if (typeof store.pruneRuns !== "function") {
71
+ throw new Error("This JobStore can't prune old runs: add pruneRuns to the adapter (the README has it).");
72
+ }
73
+ const now = options.now ?? new Date();
74
+ const deleted = await store.pruneRuns({ startedBefore: new Date(now.getTime() - retentionDays * DAY), limit });
75
+ if (!(Number.isInteger(deleted) && deleted >= 0)) {
76
+ throw new Error(`The JobStore's pruneRuns didn't say how many runs it deleted (got ${String(deleted)}).`);
77
+ }
78
+ return { jobRunsPruned: deleted };
79
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * `@connextar/house/jobs/react` — the health screen's list, and the words it
3
+ * uses.
4
+ *
5
+ * Its own entry point because `@connextar/house/jobs` is server code: it
6
+ * checks the scheduler's secret with `node:crypto`, which no client bundle can
7
+ * load. Everything a client component needs — the list, the health and count
8
+ * wording, the view types — is here, and `entry-points.test.ts` follows the
9
+ * emitted imports to keep `node:` out of it.
10
+ *
11
+ * The switch and Run now go through `@connextar/house/ux` (`useOptimisticValue`,
12
+ * `useKeyedAction`), so a refusal is reported to the app's
13
+ * `ActionFeedbackProvider` and this module imports no toast library.
14
+ */
15
+ export { countsSummary, describeSpan, formatDuration, formatMoney, type CountKind, type CountLine } from "./counts.js";
16
+ export {
17
+ describeHealth,
18
+ describeRun,
19
+ describeSwitch,
20
+ formatDay,
21
+ formatWhen,
22
+ type HealthWords,
23
+ type JobHealth,
24
+ type JobHealthState,
25
+ type JobRunView,
26
+ type JobView,
27
+ type WhenOptions,
28
+ } from "./health.js";
29
+ export {
30
+ JOB_HEALTH_CLASS_NAMES,
31
+ JobHealthList,
32
+ type JobHealthClassNames,
33
+ type JobHealthListProps,
34
+ } from "./job-health-list.js";
35
+ export type { RunNowScope } from "./registry.js";