@sssb/kit 0.0.0 → 0.3.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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +212 -5
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +313 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +248 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +93 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +142 -0
  28. package/src/adapters/lazy-jobs.ts +25 -0
  29. package/src/adapters/proxy.ts +34 -0
  30. package/src/adapters/real/absent.ts +41 -0
  31. package/src/adapters/real/accept-invite-form.tsx +77 -0
  32. package/src/adapters/real/analytics.ts +28 -0
  33. package/src/adapters/real/auth.ts +216 -0
  34. package/src/adapters/real/clerk-proxy.ts +111 -0
  35. package/src/adapters/real/contract-data-api.ts +104 -0
  36. package/src/adapters/real/contract-postgres.ts +167 -0
  37. package/src/adapters/real/database-transport.ts +34 -0
  38. package/src/adapters/real/db-data-api.ts +61 -0
  39. package/src/adapters/real/db-port.ts +26 -0
  40. package/src/adapters/real/db.ts +69 -0
  41. package/src/adapters/real/email.ts +22 -0
  42. package/src/adapters/real/index.ts +139 -0
  43. package/src/adapters/real/jobs-in-process.ts +118 -0
  44. package/src/adapters/real/jobs.ts +33 -0
  45. package/src/adapters/real/llm.ts +108 -0
  46. package/src/adapters/real/migrate-handler.ts +66 -0
  47. package/src/adapters/real/optional-ports.ts +78 -0
  48. package/src/adapters/real/providers.tsx +12 -0
  49. package/src/adapters/real/rds-data-codec.ts +508 -0
  50. package/src/adapters/real/rds-data-dialect.ts +470 -0
  51. package/src/adapters/real/rds-data-emulator.ts +351 -0
  52. package/src/adapters/real/s3-storage.ts +233 -0
  53. package/src/adapters/real/sign-in-form.tsx +59 -0
  54. package/src/adapters/real/storage.ts +10 -0
  55. package/src/adapters/run-mode.ts +11 -0
  56. package/src/adapters/sentry/baseline.ts +90 -0
  57. package/src/adapters/sentry/client.ts +17 -0
  58. package/src/adapters/sentry/init.ts +17 -0
  59. package/src/authz/app-exemptions.ts +226 -0
  60. package/src/authz/authorize.ts +214 -0
  61. package/src/authz/route-policy.ts +153 -0
  62. package/src/authz/route-scan.ts +1516 -0
  63. package/src/components/agreements/acceptances-section.tsx +55 -0
  64. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  65. package/src/components/agreements/agreement-body.tsx +34 -0
  66. package/src/components/agreements/agreement-gate.tsx +45 -0
  67. package/src/components/app-header.tsx +45 -0
  68. package/src/components/auth/accept-invite-screen.tsx +126 -0
  69. package/src/components/auth/auth-icons.tsx +68 -0
  70. package/src/components/auth/org-switcher.tsx +76 -0
  71. package/src/components/auth/people-picker.tsx +50 -0
  72. package/src/components/auth/preview-row.tsx +64 -0
  73. package/src/components/auth/sign-in-screen.tsx +24 -0
  74. package/src/components/auth/user-menu.tsx +64 -0
  75. package/src/components/demo-badge.tsx +20 -0
  76. package/src/components/demo-banner.tsx +14 -0
  77. package/src/components/gates/gate-interstitial.tsx +23 -0
  78. package/src/components/job-timeline.tsx +64 -0
  79. package/src/components/notifications/notification-bell.tsx +120 -0
  80. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  81. package/src/components/org-screen.tsx +197 -0
  82. package/src/components/profile-screen.tsx +100 -0
  83. package/src/components/simulator/actor-runtime.ts +180 -0
  84. package/src/components/simulator/actor-shell.tsx +275 -0
  85. package/src/components/simulator/actors-app.tsx +119 -0
  86. package/src/components/simulator/errors-app.tsx +84 -0
  87. package/src/components/simulator/events-app.tsx +210 -0
  88. package/src/components/simulator/format-when.ts +20 -0
  89. package/src/components/simulator/hooks-app.tsx +319 -0
  90. package/src/components/simulator/inbound-app.tsx +210 -0
  91. package/src/components/simulator/jobs-app.tsx +471 -0
  92. package/src/components/simulator/mail-app.tsx +290 -0
  93. package/src/components/simulator/messages-app.tsx +64 -0
  94. package/src/components/simulator/people-app.tsx +140 -0
  95. package/src/components/simulator/people-dimensions.ts +16 -0
  96. package/src/components/simulator/simulator-host.tsx +335 -0
  97. package/src/components/simulator/simulator-panel.tsx +704 -0
  98. package/src/components/simulator/snapshots-app.tsx +398 -0
  99. package/src/components/simulator/tab-mount.ts +25 -0
  100. package/src/components/simulator/tours-app.tsx +105 -0
  101. package/src/components/webhook-endpoints-card.tsx +172 -0
  102. package/src/core/abilities.ts +464 -0
  103. package/src/core/agreements.ts +139 -0
  104. package/src/core/gates.ts +157 -0
  105. package/src/core/greeting.ts +11 -0
  106. package/src/core/inbound-email.ts +129 -0
  107. package/src/core/jobs.ts +51 -0
  108. package/src/core/keyset.ts +227 -0
  109. package/src/core/llm-models.ts +10 -0
  110. package/src/core/locale.ts +3 -0
  111. package/src/core/notifications.ts +182 -0
  112. package/src/core/presets.ts +456 -0
  113. package/src/core/roles.ts +47 -0
  114. package/src/core/same-origin-path.ts +20 -0
  115. package/src/core/schedules.ts +147 -0
  116. package/src/core/standard-schema.ts +56 -0
  117. package/src/core/state-machine.ts +43 -0
  118. package/src/core/webhook-events.ts +86 -0
  119. package/src/core/webhook-hmac.ts +248 -0
  120. package/src/core/webhook-signing.ts +27 -0
  121. package/src/cutover/rows.json +101 -0
  122. package/src/db/agreements.ts +176 -0
  123. package/src/db/app-roles.ts +197 -0
  124. package/src/db/audit.ts +356 -0
  125. package/src/db/inbound-email.ts +145 -0
  126. package/src/db/jobs.ts +300 -0
  127. package/src/db/jsonb.ts +18 -0
  128. package/src/db/keyset.ts +179 -0
  129. package/src/db/migrate.ts +73 -0
  130. package/src/db/migrations/0001_tenants.ts +25 -0
  131. package/src/db/migrations/0003_organizations.ts +27 -0
  132. package/src/db/migrations/0004_jobs.ts +64 -0
  133. package/src/db/migrations/0005_service_keys.ts +33 -0
  134. package/src/db/migrations/0008_audit_events.ts +51 -0
  135. package/src/db/migrations/0009_job_schedules.ts +52 -0
  136. package/src/db/migrations/0010_webhooks.ts +100 -0
  137. package/src/db/migrations/0011_notifications.ts +98 -0
  138. package/src/db/migrations/0012_inbound_email.ts +74 -0
  139. package/src/db/migrations/0013_agreements.ts +98 -0
  140. package/src/db/migrations/0014_audit_credential.ts +29 -0
  141. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  142. package/src/db/migrations/0016_audit_detail.ts +26 -0
  143. package/src/db/migrations/index.ts +49 -0
  144. package/src/db/notifications.ts +185 -0
  145. package/src/db/org-lookup.ts +104 -0
  146. package/src/db/owner-pass.ts +252 -0
  147. package/src/db/rls-coverage.ts +259 -0
  148. package/src/db/rls-proof-runner.ts +94 -0
  149. package/src/db/rls-proofs.ts +1176 -0
  150. package/src/db/schedules.ts +187 -0
  151. package/src/db/schema.ts +235 -0
  152. package/src/db/seed.ts +176 -0
  153. package/src/db/service-keys.ts +50 -0
  154. package/src/db/tenant-lookup.ts +13 -0
  155. package/src/db/webhooks.ts +483 -0
  156. package/src/db/with-tenant.ts +26 -0
  157. package/src/demo-static/actor-drivers.ts +161 -0
  158. package/src/demo-static/assistant-replay.ts +61 -0
  159. package/src/demo-static/contracts.ts +282 -0
  160. package/src/demo-static/email-html.ts +58 -0
  161. package/src/demo-static/hash-route.ts +24 -0
  162. package/src/demo-static/rows.ts +105 -0
  163. package/src/demo-static/shell.tsx +440 -0
  164. package/src/demo-static/tour/contracts.ts +97 -0
  165. package/src/demo-static/tour/driver.ts +320 -0
  166. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  167. package/src/demo-static/tour/use-tours.tsx +394 -0
  168. package/src/demo-static/world.ts +1480 -0
  169. package/src/email/send.ts +12 -0
  170. package/src/email/templates/digest-email.tsx +61 -0
  171. package/src/email/templates/invite-email.tsx +57 -0
  172. package/src/email/templates/notification-email.tsx +39 -0
  173. package/src/guide.md +132 -0
  174. package/src/i18n/messages/en.json +373 -0
  175. package/src/i18n/messages/es.json +373 -0
  176. package/src/i18n/messages.ts +34 -0
  177. package/src/i18n/namespaces.ts +32 -0
  178. package/src/i18n/request.ts +34 -0
  179. package/src/i18n/routing.ts +7 -0
  180. package/src/inbound-email/handlers.ts +67 -0
  181. package/src/inbound-email/intake.ts +180 -0
  182. package/src/jobs/digest-email.ts +112 -0
  183. package/src/jobs/run-in-process.ts +82 -0
  184. package/src/observability/scrub.ts +44 -0
  185. package/src/ports/README.md +8 -0
  186. package/src/ports/analytics.ts +8 -0
  187. package/src/ports/auth.ts +87 -0
  188. package/src/ports/db.ts +27 -0
  189. package/src/ports/email.ts +14 -0
  190. package/src/ports/errors.ts +46 -0
  191. package/src/ports/jobs.ts +69 -0
  192. package/src/ports/llm.ts +85 -0
  193. package/src/ports/storage.ts +132 -0
  194. package/src/seed/contracts.ts +129 -0
  195. package/src/server-lib/assistant.ts +45 -0
  196. package/src/server-lib/defer.ts +57 -0
  197. package/src/server-lib/demo-presets.ts +85 -0
  198. package/src/server-lib/invite.ts +92 -0
  199. package/src/server-lib/notify-deps.ts +15 -0
  200. package/src/server-lib/notify.ts +252 -0
  201. package/src/server-lib/preset-operations.ts +121 -0
  202. package/src/server-lib/scheduled-tick.ts +48 -0
  203. package/src/server-lib/simulator-api.ts +311 -0
  204. package/src/server-lib/sms.ts +43 -0
  205. package/src/server-lib/webhook-dispatch.ts +75 -0
  206. package/src/service-auth/credential.ts +20 -0
  207. package/src/service-auth/mailgun.ts +70 -0
  208. package/src/service-auth/verify.ts +80 -0
  209. package/src/service-auth/webhook.ts +69 -0
  210. package/src/testing/checks.json +103 -0
  211. package/src/testing/conformance/authz.ts +46 -0
  212. package/src/testing/conformance/db.ts +258 -0
  213. package/src/testing/conformance/demo-presets.ts +295 -0
  214. package/src/testing/conformance/i18n.ts +80 -0
  215. package/src/testing/conformance/register.ts +200 -0
  216. package/src/testing/conformance/seam-map.ts +205 -0
  217. package/src/testing/conformance/suite.ts +59 -0
  218. package/src/testing/conformance/types.ts +18 -0
  219. package/src/testing/contract.ts +200 -0
  220. package/src/testing/e2e.ts +15 -0
  221. package/src/testing/index.ts +6 -0
  222. package/src/testing/seam-specifiers.json +22 -0
  223. package/src/testing/tmp-dir-marker.d.mts +4 -0
  224. package/src/testing/tmp-dir-marker.mjs +5 -0
  225. package/src/testing/tmp-dir.ts +182 -0
  226. package/src/theme.ts +28 -0
  227. package/README.md +0 -3
@@ -0,0 +1,335 @@
1
+ 'use client'
2
+
3
+ import { useTranslations } from 'next-intl'
4
+ import type { ReactNode } from 'react'
5
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
6
+ import type { SimulatorJobs, SimulatorMail, SimulatorSchedules, SimulatorSummary } from '../../server-lib/simulator-api'
7
+ import { sameOriginPath } from '../../core/same-origin-path'
8
+ import { SimulatorPanel, type SimulatorNotice } from './simulator-panel'
9
+
10
+ const EMPTY_SUMMARY: SimulatorSummary = { viewpoint: null, signedIn: false, people: [] }
11
+ const EMPTY_MAIL: SimulatorMail = { emails: [], mailSeenAt: null, allCount: 0 }
12
+ const EMPTY_JOBS: SimulatorJobs = { jobs: [], held: false }
13
+ const EMPTY_SCHEDULES: SimulatorSchedules = { schedules: [], clockOffsetMs: 0, worldNow: new Date(0).toISOString() }
14
+ const EXPANDED_POLL_MS = 4_000
15
+ const COLLAPSED_POLL_MS = 15_000
16
+ const NOTICE_MS = 6_000
17
+ const MAIL_SCOPE_KEY = 'app-simulator-mail-scope'
18
+ const API = '/api/simulator'
19
+
20
+ /** A POST to the server host. Always JSON, even with no body: the server refuses any other content type. */
21
+ function post(path: string, body: unknown = {}): Promise<Response> {
22
+ return fetch(`${API}/${path}`, {
23
+ method: 'POST',
24
+ headers: { 'content-type': 'application/json' },
25
+ body: JSON.stringify(body),
26
+ })
27
+ }
28
+
29
+ async function getJson<T>(path: string): Promise<T | null> {
30
+ const response = await fetch(`${API}/${path}`)
31
+ return response.ok ? ((await response.json()) as T) : null
32
+ }
33
+
34
+ /**
35
+ * Polls overlap, and their answers can arrive out of order: each fetch takes a ticket, and its answer is applied only
36
+ * when no later ticket's answer has been. A slow answer is never shown over a newer one, and, unlike "only the latest
37
+ * request's answer", answers slower than the poll still land.
38
+ */
39
+ function useTickets() {
40
+ const counts = useRef({ issued: 0, applied: 0 })
41
+ return useMemo(
42
+ () => ({
43
+ take: () => (counts.current.issued += 1),
44
+ fresh: (ticket: number) => {
45
+ if (ticket <= counts.current.applied) return false
46
+ counts.current.applied = ticket
47
+ return true
48
+ },
49
+ }),
50
+ [],
51
+ )
52
+ }
53
+
54
+ function readStoredScope(): 'person' | 'all' | null {
55
+ try {
56
+ const stored = window.localStorage.getItem(MAIL_SCOPE_KEY)
57
+ return stored === 'person' || stored === 'all' ? stored : null
58
+ } catch {
59
+ return null
60
+ }
61
+ }
62
+
63
+ /**
64
+ * The Simulator on an app's own `pnpm dev`: the panel, fed by the kit's server host
65
+ * (`@sssb/kit/server-lib/simulator-api`, which the app mounts at `src/app/api/simulator/[...path]/route.ts`). The app's
66
+ * locale layout renders it around the page, in simulated mode only and through a dynamic import, so no page of a real
67
+ * build loads it.
68
+ *
69
+ * It wires the tabs that host serves: People (switch to anyone, signed in or not), Mail (each person's inbox, or all
70
+ * of it) and Jobs with the world clock (run what is queued, move the clock, run what is due). The panel leaves out
71
+ * every tab it is not given; the rest, the app's own tabs, presets and tours included, are later stages of the same
72
+ * host. An app that needs one of them today keeps a glue of its own instead of this component.
73
+ *
74
+ * Polling, never a stream: the summary (the pill's unread badge) on a slow beat while the panel is collapsed, and
75
+ * the open tab's data on a faster one while it is expanded. Every acknowledgement is a notice inside the panel,
76
+ * never the app's own toast.
77
+ */
78
+ export function SimulatorHost({ locale, children }: { locale: string; children: ReactNode }) {
79
+ const t = useTranslations('simulator')
80
+ const [summary, setSummary] = useState<SimulatorSummary>(EMPTY_SUMMARY)
81
+ const [expanded, setExpanded] = useState(false)
82
+ const [activeTab, setActiveTab] = useState('people')
83
+ const [mailScope, setMailScope] = useState<'person' | 'all'>('person')
84
+ const [mail, setMail] = useState<SimulatorMail>(EMPTY_MAIL)
85
+ const [jobsData, setJobsData] = useState<SimulatorJobs>(EMPTY_JOBS)
86
+ const [schedulesData, setSchedulesData] = useState<SimulatorSchedules>(EMPTY_SCHEDULES)
87
+ const [notices, setNotices] = useState<SimulatorNotice[]>([])
88
+ const noticeSeq = useRef(0)
89
+ const prevUnread = useRef<Map<string, number> | null>(null)
90
+ const summaryTickets = useTickets()
91
+ const mailTickets = useTickets()
92
+ const jobsTickets = useTickets()
93
+
94
+ const personEmail = summary.people.find((person) => person.key === summary.viewpoint)?.email ?? null
95
+ // Signed out, or no viewpoint yet: there is no one's own inbox to show, so the scope is every inbox.
96
+ const effectiveMailScope: 'person' | 'all' = personEmail ? mailScope : 'all'
97
+ const mailQuery = effectiveMailScope === 'all' ? 'all=1' : `person=${encodeURIComponent(summary.viewpoint ?? '')}`
98
+ // The scope this render shows. An answer for another scope is dropped even when it is the newest to arrive: the
99
+ // summary's first answer turns "all" into one person's inbox, and an action's callback can hold an older render's
100
+ // fetch.
101
+ const shownMailQuery = useRef(mailQuery)
102
+ useEffect(() => {
103
+ shownMailQuery.current = mailQuery
104
+ }, [mailQuery])
105
+
106
+ const pushNotice = useCallback((text: string) => {
107
+ const id = (noticeSeq.current += 1)
108
+ setNotices((prev) => [...prev, { id, text }])
109
+ setTimeout(() => setNotices((prev) => prev.filter((notice) => notice.id !== id)), NOTICE_MS)
110
+ }, [])
111
+
112
+ const refresh = useCallback(async () => {
113
+ const ticket = summaryTickets.take()
114
+ const next = await getJson<SimulatorSummary>('summary')
115
+ if (!next || !summaryTickets.fresh(ticket)) return
116
+ setSummary(next)
117
+ // New mail since the last poll gets a notice; the first load has nothing "new".
118
+ if (prevUnread.current) {
119
+ for (const person of next.people) {
120
+ const before = prevUnread.current.get(person.key) ?? 0
121
+ if (person.unreadMail > before) pushNotice(t('noticeNewMail', { email: person.email }))
122
+ }
123
+ }
124
+ prevUnread.current = new Map(next.people.map((person) => [person.key, person.unreadMail]))
125
+ }, [pushNotice, t, summaryTickets])
126
+
127
+ const refreshMail = useCallback(async () => {
128
+ const ticket = mailTickets.take()
129
+ const next = await getJson<SimulatorMail>(`mail?${mailQuery}`)
130
+ if (next && mailQuery === shownMailQuery.current && mailTickets.fresh(ticket)) setMail(next)
131
+ }, [mailQuery, mailTickets])
132
+
133
+ const refreshJobs = useCallback(async () => {
134
+ const ticket = jobsTickets.take()
135
+ const [nextJobs, nextSchedules] = await Promise.all([
136
+ getJson<SimulatorJobs>('jobs'),
137
+ getJson<SimulatorSchedules>('schedules'),
138
+ ])
139
+ if (!nextJobs || !nextSchedules || !jobsTickets.fresh(ticket)) return
140
+ setJobsData(nextJobs)
141
+ setSchedulesData(nextSchedules)
142
+ }, [jobsTickets])
143
+
144
+ /** The open tab's own data, when the panel is expanded. */
145
+ const refreshOpenTab = useCallback(() => {
146
+ if (!expanded) return
147
+ if (activeTab === 'mail') void refreshMail()
148
+ if (activeTab === 'jobs') void refreshJobs()
149
+ }, [expanded, activeTab, refreshMail, refreshJobs])
150
+
151
+ useEffect(() => {
152
+ // Fetch on mount, and restore the remembered mail scope: syncing with external systems (the server, the
153
+ // browser's storage), which is what setting state from an effect is for.
154
+ // eslint-disable-next-line react-hooks/set-state-in-effect
155
+ void refresh()
156
+ const storedScope = readStoredScope()
157
+ if (storedScope) setMailScope(storedScope)
158
+ // Mount-only.
159
+ // eslint-disable-next-line react-hooks/exhaustive-deps
160
+ }, [])
161
+
162
+ useEffect(() => {
163
+ const id = setInterval(
164
+ () => {
165
+ void refresh()
166
+ refreshOpenTab()
167
+ },
168
+ expanded ? EXPANDED_POLL_MS : COLLAPSED_POLL_MS,
169
+ )
170
+ return () => clearInterval(id)
171
+ }, [expanded, refresh, refreshOpenTab])
172
+
173
+ useEffect(() => {
174
+ // A tab that opens (or a mail scope that changes) fetches at once rather than on the next poll: the state is
175
+ // set when the server answers, the same external-system sync as the mount effect.
176
+ // eslint-disable-next-line react-hooks/set-state-in-effect
177
+ refreshOpenTab()
178
+ }, [refreshOpenTab])
179
+
180
+ function handleSelect(person: string) {
181
+ void post('viewpoint', { person, locale }).then(async (response) => {
182
+ if (!response.ok) return
183
+ const { redirectTo } = (await response.json()) as { redirectTo: unknown }
184
+ // A full reload: the theme and the header are per-user server output. Only ever to a path on this origin:
185
+ // the server answers no other, and this is the client's own check.
186
+ const path = sameOriginPath(redirectTo)
187
+ if (path) window.location.assign(path)
188
+ })
189
+ }
190
+
191
+ function handleMailSeen() {
192
+ if (!summary.viewpoint) return
193
+ void post('mail/seen', { person: summary.viewpoint }).then((response) => {
194
+ if (response.ok) void refresh()
195
+ })
196
+ }
197
+
198
+ function handleScopeChange(scope: 'person' | 'all') {
199
+ setMailScope(scope)
200
+ try {
201
+ window.localStorage.setItem(MAIL_SCOPE_KEY, scope)
202
+ } catch {
203
+ // No storage (a private window, say): the scope lasts for this page only.
204
+ }
205
+ }
206
+
207
+ function handleOpenLink(href: string) {
208
+ // Same origin only, and never silently. A path is followed; so is an absolute URL on this origin, since a real
209
+ // email carries one. Both go through `sameOriginPath`, which refuses what a browser would read as another
210
+ // origin (`/\host`, a tab inside). A protocol-relative `//host` link is resolved against this page, so it is
211
+ // judged by its host like any absolute URL; one with no origin at all (`mailto:`) is unusable here.
212
+ const path = sameOriginPath(href)
213
+ if (path) {
214
+ window.location.assign(path)
215
+ return
216
+ }
217
+ try {
218
+ const url = href.startsWith('//') ? new URL(href, window.location.href) : new URL(href)
219
+ const local =
220
+ url.origin === window.location.origin ? sameOriginPath(url.pathname + url.search + url.hash) : null
221
+ if (local) {
222
+ window.location.assign(local)
223
+ return
224
+ }
225
+ if (url.origin === window.location.origin || url.origin === 'null') {
226
+ pushNotice(t('noticeLinkUnusable', { href }))
227
+ } else {
228
+ pushNotice(t('noticeLinkOrigin', { origin: url.origin }))
229
+ }
230
+ } catch {
231
+ pushNotice(t('noticeLinkUnusable', { href }))
232
+ }
233
+ }
234
+
235
+ function handleCopyLink(href: string) {
236
+ void navigator.clipboard
237
+ .writeText(href)
238
+ .then(() => pushNotice(t('noticeLinkCopied')))
239
+ .catch(() => pushNotice(t('noticeLinkCopyFailed')))
240
+ }
241
+
242
+ function handleClearMail() {
243
+ void post('mail/clear').then((response) => {
244
+ if (!response.ok) return
245
+ void refreshMail()
246
+ void refresh()
247
+ pushNotice(t('noticeMailCleared'))
248
+ })
249
+ }
250
+
251
+ async function handleRunPending() {
252
+ const response = await post('jobs/run-pending')
253
+ if (!response.ok) return
254
+ const { ran } = (await response.json()) as { ran: number }
255
+ await refreshJobs()
256
+ pushNotice(t('noticeJobsRan', { count: ran }))
257
+ }
258
+
259
+ /** After the clock moved or due work ran: the schedules, the jobs a schedule spawned, and any mail they sent. */
260
+ async function afterSchedulesChanged(response: Response, moved: 'advanced' | 'reset' | null) {
261
+ if (!response.ok) return
262
+ const { spawned } = (await response.json()) as { spawned: number }
263
+ await Promise.all([refreshJobs(), refresh()])
264
+ if (spawned > 0) pushNotice(t('noticeScheduleFired', { count: spawned }))
265
+ else if (moved === 'advanced') pushNotice(t('noticeClockAdvanced'))
266
+ else if (moved === 'reset') pushNotice(t('noticeClockReset'))
267
+ else pushNotice(t('noticeNoDue'))
268
+ }
269
+
270
+ async function handleAdvanceClock(deltaMs: number) {
271
+ await afterSchedulesChanged(await post('clock', { action: 'advance', deltaMs }), 'advanced')
272
+ }
273
+
274
+ async function handleResetClock() {
275
+ await afterSchedulesChanged(await post('clock', { action: 'reset' }), 'reset')
276
+ }
277
+
278
+ async function handleRunDue() {
279
+ await afterSchedulesChanged(await post('schedules/run-due'), null)
280
+ }
281
+
282
+ function handleLocaleChange(next: string) {
283
+ if (next === locale) return
284
+ // Swap the leading /<locale> segment and reload the same page: the theme and the header are per-request
285
+ // server output, so a client navigation would not re-render them.
286
+ const { pathname, search, hash } = window.location
287
+ const swapped = pathname.replace(new RegExp(`^/${locale}(?=/|$)`), `/${next}`) + search + hash
288
+ window.location.assign(sameOriginPath(swapped) ?? `/${next}`)
289
+ }
290
+
291
+ return (
292
+ <div style={{ display: 'flex', minHeight: '100vh', alignItems: 'stretch' }}>
293
+ <div style={{ flex: 1, minWidth: 0 }}>{children}</div>
294
+ <SimulatorPanel
295
+ people={summary.people}
296
+ viewpoint={summary.viewpoint}
297
+ signedIn={summary.signedIn}
298
+ onSelect={handleSelect}
299
+ onRefresh={refresh}
300
+ onExpandedChange={(value) => {
301
+ setExpanded(value)
302
+ if (value) void refresh()
303
+ }}
304
+ onTabChange={setActiveTab}
305
+ onLocaleChange={handleLocaleChange}
306
+ notices={notices}
307
+ mail={{
308
+ emails: mail.emails,
309
+ scope: effectiveMailScope,
310
+ onScopeChange: handleScopeChange,
311
+ personEmail,
312
+ mailSeenAt: mail.mailSeenAt,
313
+ allCount: mail.allCount,
314
+ onOpenLink: handleOpenLink,
315
+ onSeen: handleMailSeen,
316
+ onClear: handleClearMail,
317
+ onCopyLink: handleCopyLink,
318
+ }}
319
+ jobs={{
320
+ jobs: jobsData.jobs,
321
+ held: jobsData.held,
322
+ onRunPending: handleRunPending,
323
+ schedules: schedulesData.schedules,
324
+ clock: {
325
+ offsetMs: schedulesData.clockOffsetMs,
326
+ worldNow: schedulesData.worldNow,
327
+ onAdvance: handleAdvanceClock,
328
+ onReset: handleResetClock,
329
+ onRunDue: handleRunDue,
330
+ },
331
+ }}
332
+ />
333
+ </div>
334
+ )
335
+ }