@sssb/kit 0.0.0-stage → 0.2.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 (214) 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 +209 -3
  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 +312 -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 +270 -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 +94 -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 +115 -0
  28. package/src/adapters/real/accept-invite-form.tsx +77 -0
  29. package/src/adapters/real/analytics.ts +28 -0
  30. package/src/adapters/real/auth.ts +216 -0
  31. package/src/adapters/real/contract-data-api.ts +104 -0
  32. package/src/adapters/real/contract-postgres.ts +167 -0
  33. package/src/adapters/real/database-transport.ts +34 -0
  34. package/src/adapters/real/db-data-api.ts +61 -0
  35. package/src/adapters/real/db.ts +88 -0
  36. package/src/adapters/real/email.ts +22 -0
  37. package/src/adapters/real/index.ts +89 -0
  38. package/src/adapters/real/jobs.ts +32 -0
  39. package/src/adapters/real/llm.ts +108 -0
  40. package/src/adapters/real/migrate-handler.ts +66 -0
  41. package/src/adapters/real/providers.tsx +12 -0
  42. package/src/adapters/real/rds-data-codec.ts +508 -0
  43. package/src/adapters/real/rds-data-dialect.ts +470 -0
  44. package/src/adapters/real/rds-data-emulator.ts +351 -0
  45. package/src/adapters/real/s3-storage.ts +233 -0
  46. package/src/adapters/real/sign-in-form.tsx +59 -0
  47. package/src/adapters/real/storage.ts +10 -0
  48. package/src/adapters/sentry/baseline.ts +90 -0
  49. package/src/adapters/sentry/client.ts +17 -0
  50. package/src/adapters/sentry/init.ts +17 -0
  51. package/src/authz/app-exemptions.ts +226 -0
  52. package/src/authz/authorize.ts +214 -0
  53. package/src/authz/route-policy.ts +153 -0
  54. package/src/authz/route-scan.ts +1516 -0
  55. package/src/components/agreements/acceptances-section.tsx +55 -0
  56. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  57. package/src/components/agreements/agreement-body.tsx +34 -0
  58. package/src/components/agreements/agreement-gate.tsx +45 -0
  59. package/src/components/app-header.tsx +45 -0
  60. package/src/components/auth/accept-invite-screen.tsx +126 -0
  61. package/src/components/auth/auth-icons.tsx +68 -0
  62. package/src/components/auth/org-switcher.tsx +76 -0
  63. package/src/components/auth/people-picker.tsx +50 -0
  64. package/src/components/auth/preview-row.tsx +64 -0
  65. package/src/components/auth/sign-in-screen.tsx +24 -0
  66. package/src/components/auth/user-menu.tsx +64 -0
  67. package/src/components/demo-badge.tsx +20 -0
  68. package/src/components/demo-banner.tsx +14 -0
  69. package/src/components/gates/gate-interstitial.tsx +23 -0
  70. package/src/components/job-timeline.tsx +64 -0
  71. package/src/components/notifications/notification-bell.tsx +120 -0
  72. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  73. package/src/components/org-screen.tsx +197 -0
  74. package/src/components/profile-screen.tsx +100 -0
  75. package/src/components/simulator/actor-runtime.ts +180 -0
  76. package/src/components/simulator/actor-shell.tsx +275 -0
  77. package/src/components/simulator/actors-app.tsx +119 -0
  78. package/src/components/simulator/errors-app.tsx +84 -0
  79. package/src/components/simulator/events-app.tsx +210 -0
  80. package/src/components/simulator/format-when.ts +20 -0
  81. package/src/components/simulator/hooks-app.tsx +319 -0
  82. package/src/components/simulator/inbound-app.tsx +210 -0
  83. package/src/components/simulator/jobs-app.tsx +471 -0
  84. package/src/components/simulator/mail-app.tsx +290 -0
  85. package/src/components/simulator/messages-app.tsx +64 -0
  86. package/src/components/simulator/people-app.tsx +140 -0
  87. package/src/components/simulator/people-dimensions.ts +16 -0
  88. package/src/components/simulator/simulator-panel.tsx +716 -0
  89. package/src/components/simulator/snapshots-app.tsx +398 -0
  90. package/src/components/simulator/tab-mount.ts +25 -0
  91. package/src/components/simulator/tours-app.tsx +105 -0
  92. package/src/components/webhook-endpoints-card.tsx +172 -0
  93. package/src/core/abilities.ts +459 -0
  94. package/src/core/agreements.ts +139 -0
  95. package/src/core/gates.ts +157 -0
  96. package/src/core/greeting.ts +11 -0
  97. package/src/core/inbound-email.ts +129 -0
  98. package/src/core/jobs.ts +51 -0
  99. package/src/core/keyset.ts +227 -0
  100. package/src/core/llm-models.ts +10 -0
  101. package/src/core/locale.ts +3 -0
  102. package/src/core/notifications.ts +182 -0
  103. package/src/core/presets.ts +456 -0
  104. package/src/core/roles.ts +47 -0
  105. package/src/core/schedules.ts +147 -0
  106. package/src/core/standard-schema.ts +56 -0
  107. package/src/core/state-machine.ts +43 -0
  108. package/src/core/webhook-events.ts +86 -0
  109. package/src/core/webhook-hmac.ts +248 -0
  110. package/src/core/webhook-signing.ts +27 -0
  111. package/src/cutover/rows.json +101 -0
  112. package/src/db/agreements.ts +176 -0
  113. package/src/db/app-roles.ts +197 -0
  114. package/src/db/audit.ts +356 -0
  115. package/src/db/inbound-email.ts +145 -0
  116. package/src/db/jobs.ts +300 -0
  117. package/src/db/jsonb.ts +18 -0
  118. package/src/db/keyset.ts +179 -0
  119. package/src/db/migrate.ts +73 -0
  120. package/src/db/migrations/0001_tenants.ts +25 -0
  121. package/src/db/migrations/0003_organizations.ts +27 -0
  122. package/src/db/migrations/0004_jobs.ts +64 -0
  123. package/src/db/migrations/0005_service_keys.ts +33 -0
  124. package/src/db/migrations/0008_audit_events.ts +51 -0
  125. package/src/db/migrations/0009_job_schedules.ts +52 -0
  126. package/src/db/migrations/0010_webhooks.ts +100 -0
  127. package/src/db/migrations/0011_notifications.ts +98 -0
  128. package/src/db/migrations/0012_inbound_email.ts +74 -0
  129. package/src/db/migrations/0013_agreements.ts +98 -0
  130. package/src/db/migrations/0014_audit_credential.ts +29 -0
  131. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  132. package/src/db/migrations/0016_audit_detail.ts +26 -0
  133. package/src/db/migrations/index.ts +49 -0
  134. package/src/db/notifications.ts +185 -0
  135. package/src/db/org-lookup.ts +104 -0
  136. package/src/db/owner-pass.ts +252 -0
  137. package/src/db/rls-coverage.ts +259 -0
  138. package/src/db/rls-proof-runner.ts +94 -0
  139. package/src/db/rls-proofs.ts +1176 -0
  140. package/src/db/schedules.ts +187 -0
  141. package/src/db/schema.ts +235 -0
  142. package/src/db/seed.ts +176 -0
  143. package/src/db/service-keys.ts +50 -0
  144. package/src/db/tenant-lookup.ts +13 -0
  145. package/src/db/webhooks.ts +483 -0
  146. package/src/db/with-tenant.ts +26 -0
  147. package/src/demo-static/actor-drivers.ts +161 -0
  148. package/src/demo-static/assistant-replay.ts +61 -0
  149. package/src/demo-static/contracts.ts +282 -0
  150. package/src/demo-static/email-html.ts +58 -0
  151. package/src/demo-static/hash-route.ts +24 -0
  152. package/src/demo-static/rows.ts +105 -0
  153. package/src/demo-static/shell.tsx +440 -0
  154. package/src/demo-static/tour/contracts.ts +97 -0
  155. package/src/demo-static/tour/driver.ts +320 -0
  156. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  157. package/src/demo-static/tour/use-tours.tsx +394 -0
  158. package/src/demo-static/world.ts +1479 -0
  159. package/src/email/send.ts +12 -0
  160. package/src/email/templates/digest-email.tsx +61 -0
  161. package/src/email/templates/invite-email.tsx +57 -0
  162. package/src/email/templates/notification-email.tsx +39 -0
  163. package/src/guide.md +118 -0
  164. package/src/i18n/messages/en.json +373 -0
  165. package/src/i18n/messages/es.json +373 -0
  166. package/src/i18n/messages.ts +34 -0
  167. package/src/i18n/namespaces.ts +32 -0
  168. package/src/i18n/request.ts +34 -0
  169. package/src/i18n/routing.ts +7 -0
  170. package/src/inbound-email/handlers.ts +67 -0
  171. package/src/inbound-email/intake.ts +180 -0
  172. package/src/jobs/digest-email.ts +97 -0
  173. package/src/observability/scrub.ts +42 -0
  174. package/src/ports/README.md +8 -0
  175. package/src/ports/analytics.ts +8 -0
  176. package/src/ports/auth.ts +87 -0
  177. package/src/ports/db.ts +27 -0
  178. package/src/ports/email.ts +14 -0
  179. package/src/ports/errors.ts +46 -0
  180. package/src/ports/jobs.ts +48 -0
  181. package/src/ports/llm.ts +85 -0
  182. package/src/ports/storage.ts +132 -0
  183. package/src/seed/contracts.ts +129 -0
  184. package/src/server-lib/assistant.ts +45 -0
  185. package/src/server-lib/defer.ts +53 -0
  186. package/src/server-lib/demo-presets.ts +85 -0
  187. package/src/server-lib/invite.ts +92 -0
  188. package/src/server-lib/notify-deps.ts +15 -0
  189. package/src/server-lib/notify.ts +252 -0
  190. package/src/server-lib/preset-operations.ts +121 -0
  191. package/src/server-lib/scheduled-tick.ts +38 -0
  192. package/src/server-lib/sms.ts +43 -0
  193. package/src/server-lib/webhook-dispatch.ts +75 -0
  194. package/src/service-auth/mailgun.ts +70 -0
  195. package/src/service-auth/verify.ts +73 -0
  196. package/src/service-auth/webhook.ts +60 -0
  197. package/src/testing/checks.json +103 -0
  198. package/src/testing/conformance/authz.ts +46 -0
  199. package/src/testing/conformance/db.ts +258 -0
  200. package/src/testing/conformance/demo-presets.ts +295 -0
  201. package/src/testing/conformance/i18n.ts +80 -0
  202. package/src/testing/conformance/register.ts +200 -0
  203. package/src/testing/conformance/seam-map.ts +205 -0
  204. package/src/testing/conformance/suite.ts +59 -0
  205. package/src/testing/conformance/types.ts +18 -0
  206. package/src/testing/contract.ts +200 -0
  207. package/src/testing/e2e.ts +15 -0
  208. package/src/testing/index.ts +6 -0
  209. package/src/testing/seam-specifiers.json +22 -0
  210. package/src/testing/tmp-dir-marker.d.mts +4 -0
  211. package/src/testing/tmp-dir-marker.mjs +5 -0
  212. package/src/testing/tmp-dir.ts +182 -0
  213. package/src/theme.ts +28 -0
  214. package/README.md +0 -3
@@ -0,0 +1,440 @@
1
+ import { findOrg, findTenant, type SeedPerson } from '@sssb/app-config/seed'
2
+ import { presets } from '@sssb/app-config/presets'
3
+ import { Badge, Group } from '@mantine/core'
4
+ import { useTranslations } from 'next-intl'
5
+ import { type ReactNode, useRef, useState } from 'react'
6
+ import { AcceptancesSection } from '../components/agreements/acceptances-section'
7
+ import { AgreementAdvisoryBanner } from '../components/agreements/agreement-advisory-banner'
8
+ import { AgreementGate } from '../components/agreements/agreement-gate'
9
+ import { AppHeader } from '../components/app-header'
10
+ import { AcceptInviteScreen, type AcceptInviteState } from '../components/auth/accept-invite-screen'
11
+ import { OrgSwitcher } from '../components/auth/org-switcher'
12
+ import { PeoplePicker } from '../components/auth/people-picker'
13
+ import { SignInScreen } from '../components/auth/sign-in-screen'
14
+ import { UserMenu } from '../components/auth/user-menu'
15
+ import { SimulatorPanel, type SimulatorExtraTab } from '../components/simulator/simulator-panel'
16
+ import type { ScrubResult } from '../components/simulator/errors-app'
17
+ import type { HookDeliveryRow, HookEndpointRow } from '../components/simulator/hooks-app'
18
+ import { DemoBanner } from '../components/demo-banner'
19
+ import { NotificationBell } from '../components/notifications/notification-bell'
20
+ import { NotificationPrefsSection } from '../components/notifications/notification-prefs-section'
21
+ import { OrgScreen, type OrgMember } from '../components/org-screen'
22
+ import { ProfileScreen } from '../components/profile-screen'
23
+ import { WebhookEndpointsCard } from '../components/webhook-endpoints-card'
24
+ import { type Locale, LOCALES } from '../core/locale'
25
+ import { unreadCount } from '../core/notifications'
26
+ import { resolveWorldStart } from '../core/presets'
27
+ import { canManageOrg, isAssignableRole, ROLES } from '../core/roles'
28
+ import { WEBHOOK_EVENT_KINDS } from '../core/webhook-events'
29
+ import { scrubEvent } from '../observability/scrub'
30
+ import { go } from './hash-route'
31
+ import { useTours } from './tour/use-tours'
32
+ import type { DemoWorld } from './contracts'
33
+
34
+ /**
35
+ * The static demo's SHELL: the frame every app-on-SSSB gets for free from `file://` — the header, the
36
+ * framework's own screens (sign-in, accept-invite, profile, team, the blocking access gate), the
37
+ * Simulator panel wired to the whole simulated world, the tour engine that can drive all of it
38
+ * (./tour/), and the routing between them.
39
+ *
40
+ * An app's composition root supplies only the parts that are its own: its landing screen, its nav, its
41
+ * dashboard, and its Simulator tabs. Everything else here is the same code the server host renders —
42
+ * these screens are router-agnostic precisely so this file can exist (ADR-0006).
43
+ */
44
+
45
+ async function runServerErrorScenario(): Promise<ScrubResult> {
46
+ // Mirrors /api/dev/error's synthetic payload — the static shell has no server, so the
47
+ // "server" scenario just scrubs the same shape entirely in the browser.
48
+ const base = {
49
+ message: 'Test error (server) from Simulator',
50
+ request: {
51
+ headers: {
52
+ cookie: 'session=SECRET_COOKIE_VALUE',
53
+ authorization: 'Bearer SECRET_TOKEN',
54
+ 'x-api-key': 'SECRET_API_KEY',
55
+ 'user-agent': 'DevErrorsDemo/1.0',
56
+ },
57
+ cookies: { session: 'SECRET_COOKIE_VALUE' },
58
+ query_string: 'token=SECRET_QUERY',
59
+ },
60
+ user: { id: 'user_123', email: 'user@example.com', ip_address: '203.0.113.7' },
61
+ }
62
+ return { raw: structuredClone(base), scrubbed: scrubEvent(structuredClone(base)) }
63
+ }
64
+
65
+ export interface DemoShellProps {
66
+ world: DemoWorld
67
+ locale: Locale
68
+ onLocaleChange: (locale: Locale) => void
69
+ /** The app's signed-out landing screen — the welcome route, and the fallback for anything unknown. */
70
+ welcome: ReactNode
71
+ /** The app's primary nav, slotted into the framework header. */
72
+ nav: ReactNode
73
+ /** The app's dashboard. Called ONLY once a person is signed in and no gate blocks them, so it
74
+ * gets a non-null person rather than having to re-check what the shell already decided. */
75
+ dashboard: (person: SeedPerson) => ReactNode
76
+ /** App-registered Simulator tabs (@sssb/app-config/simulator), composed by the app. */
77
+ extraTabs: SimulatorExtraTab[]
78
+ /** The product's display name for the header. REQUIRED, and passed straight to AppHeader — see the
79
+ * note there on why the framework catalog no longer carries a default for it. */
80
+ appName: ReactNode
81
+ }
82
+
83
+ export function DemoShell({
84
+ world,
85
+ locale,
86
+ onLocaleChange,
87
+ welcome,
88
+ nav,
89
+ dashboard,
90
+ extraTabs,
91
+ appName,
92
+ }: DemoShellProps) {
93
+ const t = useTranslations('shell')
94
+ const { person, tenant, org, activeOrgSlug, name, route } = world
95
+ // Scripted walkthroughs. The engine reads the app's registered tours off the seam itself, so an
96
+ // app gets the Tours tab (and the ghost cursor) by registering a tour and nothing else. This host
97
+ // can start a tour from `'reset'` or from any registered demo preset — both are in-memory and
98
+ // instant, so unlike the server host the tour never has to survive a reload to start. A SAVED
99
+ // snapshot lives in a server's `.data/`, which this host does not have: answering false records the
100
+ // tour's start as a miss, so a tour that only works on a server fails the `file://` walkthrough gate.
101
+ // The preset a load is replaying for. Static replays run one step per commit, so a load takes several
102
+ // renders; while it does, the Snapshots tab disables the other world rewrites, as the server host does.
103
+ const [busyPreset, setBusyPreset] = useState<string | null>(null)
104
+ // Only the LATEST load may clear it: a second load (or a tour starting from a preset) resets the
105
+ // world, which settles the first load's promise — and that settle must not mark the world idle while
106
+ // the second one is still replaying.
107
+ const loadSeq = useRef(0)
108
+ function loadPreset(id: string): Promise<boolean> {
109
+ const mine = (loadSeq.current += 1)
110
+ setBusyPreset(id)
111
+ return world.applyPreset(id).finally(() => {
112
+ if (loadSeq.current === mine) setBusyPreset(null)
113
+ })
114
+ }
115
+
116
+ const tours = useTours({
117
+ onSnapshot: async (snapshot) => {
118
+ const start = resolveWorldStart(snapshot, presets)
119
+ if (start.kind === 'reset') world.resetWorld()
120
+ if (start.kind === 'preset') return loadPreset(start.preset.id)
121
+ return start.kind === 'reset'
122
+ },
123
+ })
124
+
125
+ const signInScreen = (
126
+ <SignInScreen
127
+ body={
128
+ <PeoplePicker
129
+ people={world.allPeople.map((p) => ({
130
+ id: p.id,
131
+ name: p.name,
132
+ role: p.memberships[0]?.role ?? '',
133
+ tenantName: findTenant(p.tenantSlug)?.name ?? p.tenantSlug,
134
+ }))}
135
+ onPick={world.signIn}
136
+ />
137
+ }
138
+ />
139
+ )
140
+
141
+ const screen = (() => {
142
+ if (route === '') return welcome
143
+
144
+ if (route.startsWith('accept-invite/')) {
145
+ const inviteId = route.slice('accept-invite/'.length)
146
+ const invite = world.invites.find((i) => i.id === inviteId)
147
+ const inviteOrg = invite ? findOrg(invite.orgSlug) : undefined
148
+ const state: AcceptInviteState =
149
+ invite && inviteOrg
150
+ ? {
151
+ kind: 'valid',
152
+ inviteId: invite.id,
153
+ orgName: inviteOrg.name,
154
+ role: invite.role,
155
+ email: invite.email,
156
+ }
157
+ : { kind: 'invalid' }
158
+ return (
159
+ <AcceptInviteScreen
160
+ state={state}
161
+ error={null}
162
+ onAccept={async ({ name: acceptedName }) => {
163
+ if (state.kind !== 'valid') return
164
+ world.acceptInvite(state.inviteId, acceptedName)
165
+ }}
166
+ onSignIn={() => go('')}
167
+ />
168
+ )
169
+ }
170
+
171
+ if (!person) return signInScreen
172
+ // A blocking access gate replaces the app with its resolution flow — the same interstitial the
173
+ // real protected layout renders instead of children.
174
+ if (world.blockingAgreement) {
175
+ const gated = world.blockingAgreement
176
+ return (
177
+ <AgreementGate
178
+ agreement={gated}
179
+ onAccept={async () => {
180
+ world.acceptAgreement(gated.id)
181
+ }}
182
+ />
183
+ )
184
+ }
185
+ switch (route) {
186
+ case 'signin':
187
+ return welcome
188
+ case 'dashboard':
189
+ return dashboard(person)
190
+ case 'profile':
191
+ return (
192
+ <ProfileScreen
193
+ initial={{ name, locale }}
194
+ email={person.email}
195
+ locales={[...LOCALES]}
196
+ onSave={async (values) => {
197
+ world.saveProfile({ name: values.name })
198
+ onLocaleChange(values.locale as Locale)
199
+ }}
200
+ extraSection={
201
+ <>
202
+ <NotificationPrefsSection
203
+ prefs={world.notifPrefs[`${person.id}:${activeOrgSlug}`] ?? []}
204
+ onToggle={async (kind, channel, enabled) =>
205
+ world.toggleNotifPref(kind, channel, enabled)
206
+ }
207
+ />
208
+ <AcceptancesSection
209
+ acceptances={world.acceptances
210
+ .filter((x) => x.userId === person.id)
211
+ .map((x) => {
212
+ const a = world.agreements.find((ag) => ag.id === x.agreementId)
213
+ return {
214
+ agreementId: x.agreementId,
215
+ title: a?.title ?? x.agreementId,
216
+ kind: a?.kind ?? '',
217
+ version: x.version,
218
+ acceptedAt: x.acceptedAt,
219
+ }
220
+ })
221
+ .sort((a, b) => b.acceptedAt.localeCompare(a.acceptedAt))}
222
+ />
223
+ </>
224
+ }
225
+ />
226
+ )
227
+ case 'org': {
228
+ const canManage = canManageOrg(world.roleInOrg(person, activeOrgSlug))
229
+ const members: OrgMember[] = world.allPeople
230
+ .filter((p) => p.memberships.some((m) => m.orgSlug === activeOrgSlug))
231
+ .map((p) => ({
232
+ id: p.id,
233
+ name: p.name,
234
+ email: p.email,
235
+ role: world.roleInOrg(p, activeOrgSlug),
236
+ status: 'active',
237
+ }))
238
+ const invitedMembers: OrgMember[] = world.invites
239
+ .filter((invite) => invite.orgSlug === activeOrgSlug)
240
+ .map((invite) => ({
241
+ id: invite.id,
242
+ name: null,
243
+ email: invite.email,
244
+ role: invite.role,
245
+ status: 'invited' as const,
246
+ }))
247
+ return (
248
+ <OrgScreen
249
+ orgName={org.name}
250
+ members={[...members, ...invitedMembers]}
251
+ roles={ROLES.filter(isAssignableRole)}
252
+ canManage={canManage}
253
+ error={world.inviteError}
254
+ onInvite={world.sendInvite}
255
+ >
256
+ {canManage ? (
257
+ <WebhookEndpointsCard
258
+ endpoints={world.endpoints
259
+ .filter((e) => e.tenantSlug === tenant.slug && e.orgSlug === activeOrgSlug)
260
+ .map((e) => ({
261
+ id: e.id,
262
+ url: e.url,
263
+ eventKinds: e.eventKinds,
264
+ enabled: e.enabled,
265
+ createdAt: '',
266
+ }))}
267
+ eventKindOptions={[...WEBHOOK_EVENT_KINDS]}
268
+ newSecret={world.newWebhookSecret}
269
+ onDismissSecret={world.dismissNewWebhookSecret}
270
+ onCreate={async (input) => world.createEndpoint(input)}
271
+ onToggle={async (id, enabled) => world.toggleEndpoint(id, enabled)}
272
+ onDelete={async (id) => world.deleteEndpoint(id)}
273
+ />
274
+ ) : null}
275
+ </OrgScreen>
276
+ )
277
+ }
278
+ default:
279
+ return welcome
280
+ }
281
+ })()
282
+
283
+ return (
284
+ <div style={{ display: 'flex', minHeight: '100vh', alignItems: 'stretch' }}>
285
+ <div style={{ flex: 1, minWidth: 0 }}>
286
+ {person ? (
287
+ <AppHeader
288
+ tenantName={tenant.name}
289
+ appName={appName}
290
+ bell={
291
+ <NotificationBell
292
+ items={world.notifications
293
+ .filter((n) => n.recipientPersonId === person.id)
294
+ .map((n) => ({
295
+ id: n.id,
296
+ kind: n.kind,
297
+ payload: n.payload,
298
+ readAt: n.readAt,
299
+ createdAt: n.createdAt,
300
+ }))}
301
+ unread={unreadCount(
302
+ world.notifications
303
+ .filter((n) => n.recipientPersonId === person.id)
304
+ .map((n) => ({ readAt: n.readAt })),
305
+ )}
306
+ onOpen={world.markNotificationsRead}
307
+ />
308
+ }
309
+ nav={nav}
310
+ controls={
311
+ <>
312
+ <OrgSwitcher
313
+ orgs={world.orgsForActivePerson.map((o) => ({ slug: o.slug, name: o.name }))}
314
+ activeSlug={activeOrgSlug}
315
+ onSwitch={world.setActiveOrgSlug}
316
+ />
317
+ <UserMenu
318
+ user={{ name, email: person.email }}
319
+ onProfile={() => go('profile')}
320
+ onSignOut={world.signOut}
321
+ />
322
+ </>
323
+ }
324
+ />
325
+ ) : null}
326
+ {world.demoBannerOn ? <DemoBanner /> : null}
327
+ {person && !world.blockingAgreement && world.advisoryAgreements.length > 0 ? (
328
+ <AgreementAdvisoryBanner agreements={world.advisoryAgreements} />
329
+ ) : null}
330
+ {screen}
331
+ <Group justify="center" py="sm">
332
+ <Badge color="orange" variant="filled" radius="sm" data-testid="demo-badge">
333
+ {t('staticDemoBadge')}
334
+ </Badge>
335
+ </Group>
336
+ </div>
337
+ <SimulatorPanel
338
+ people={world.people}
339
+ viewpoint={world.viewpoint}
340
+ signedIn={!!person}
341
+ onSelect={world.selectPerson}
342
+ onLocaleChange={(next) => onLocaleChange(next as Locale)}
343
+ notices={world.notices}
344
+ mail={{
345
+ emails: world.mail.scoped,
346
+ scope: world.mail.scope,
347
+ onScopeChange: world.mail.setScope,
348
+ personEmail: world.personEmail,
349
+ mailSeenAt: world.mail.seenAt,
350
+ allCount: world.mail.allCount,
351
+ onOpenLink: world.mail.openLink,
352
+ onSeen: world.mail.markSeen,
353
+ onClear: world.mail.clear,
354
+ onCopyLink: world.mail.copyLink,
355
+ }}
356
+ inbound={{
357
+ inbound: world.inbound,
358
+ orgs: world.inboundOrgs,
359
+ people: world.allPeople.map((p) => ({ email: p.email, name: p.name })),
360
+ handlers: world.inboundHandlerSlugs,
361
+ domain: world.inboundDomain,
362
+ onCompose: world.composeInbound,
363
+ }}
364
+ messages={world.smsMessages}
365
+ events={world.events}
366
+ audit={world.auditEntries}
367
+ jobs={{
368
+ jobs: world.jobs,
369
+ held: world.jobsHeld,
370
+ onRunPending: world.runPendingJobs,
371
+ schedules: world.schedules,
372
+ clock: {
373
+ offsetMs: world.clock.offsetMs,
374
+ worldNow: world.clock.worldNowIso,
375
+ onAdvance: world.clock.advance,
376
+ onReset: world.clock.reset,
377
+ onRunDue: world.clock.runDue,
378
+ },
379
+ }}
380
+ hooks={{
381
+ endpoints: world.endpoints.map((e): HookEndpointRow => ({
382
+ id: e.id,
383
+ url: e.url,
384
+ eventKinds: e.eventKinds,
385
+ enabled: e.enabled,
386
+ tenantSlug: e.tenantSlug,
387
+ orgSlug: e.orgSlug,
388
+ })),
389
+ deliveries: world.deliveries.map((d): HookDeliveryRow => {
390
+ const endpoint = world.endpoints.find((e) => e.id === d.endpointId)
391
+ return {
392
+ id: d.id,
393
+ endpointUrl: endpoint?.url ?? '',
394
+ eventKind: d.eventKind,
395
+ status: d.status,
396
+ attemptCount: d.attemptCount,
397
+ nextAttemptAt: new Date(d.nextAttemptAtMs).toISOString(),
398
+ lastError: d.lastError,
399
+ createdAt: new Date(d.createdAtMs).toISOString(),
400
+ deliveredAt: d.deliveredAtMs ? new Date(d.deliveredAtMs).toISOString() : null,
401
+ tenantSlug: d.tenantSlug,
402
+ orgSlug: d.orgSlug,
403
+ signature: d.signature,
404
+ body: d.body,
405
+ }
406
+ }),
407
+ failingEndpointIds: world.failingEndpointIds,
408
+ onToggleFail: world.toggleEndpointFailure,
409
+ onRunDue: world.runDueDeliveriesNow,
410
+ }}
411
+ extraTabs={extraTabs}
412
+ runServerErrorScenario={runServerErrorScenario}
413
+ snapshots={{
414
+ snapshots: undefined,
415
+ onReset: world.resetWorld,
416
+ flags: world.featureFlags,
417
+ onToggleFlag: world.setFeatureFlag,
418
+ agreements: world.agreements.map((a) => ({
419
+ id: a.id,
420
+ tenantSlug: a.tenantSlug,
421
+ kind: a.kind,
422
+ title: a.title,
423
+ version: a.version,
424
+ gating: a.gating,
425
+ currentAcceptances: world.acceptances.filter(
426
+ (x) => x.agreementId === a.id && x.version >= a.version,
427
+ ).length,
428
+ totalAcceptances: world.acceptances.filter((x) => x.agreementId === a.id).length,
429
+ })),
430
+ onBumpAgreement: world.bumpAgreement,
431
+ busyAgreement: null,
432
+ onLoadPreset: (id) => void loadPreset(id),
433
+ busyPreset,
434
+ }}
435
+ tours={tours.tab}
436
+ />
437
+ {tours.overlay}
438
+ </div>
439
+ )
440
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * The CONTRACT an app's tours are written against (ADR-0012 seam, `@sssb/app-config/tours`).
3
+ *
4
+ * A **snapshot** snapshots world STATE; a **tour** is its temporal sibling — a scripted walkthrough that
5
+ * drives the running app for a watcher, with narration. A tour declares the snapshot it starts from, the
6
+ * framework restores it, and then the ghost cursor drives real controls: real clicks, real typing, real
7
+ * navigation. Nothing here is app vocabulary: a tour is selectors, i18n keys and timing, so SSSB can
8
+ * host tours for any app without learning what a ticket is.
9
+ *
10
+ * Kept as its own module for the same reason ../contracts.ts is: it is the surface a second app codes
11
+ * against, and it should read end to end without scrolling through an implementation.
12
+ */
13
+
14
+ /**
15
+ * One action in a tour's script. A tuple rather than an object because a script is read as a
16
+ * storyboard — twenty lines you can scan — and the driver (./driver.ts) is the only thing that
17
+ * executes them.
18
+ *
19
+ * SELECTOR CONVENTION: any CSS selector resolves, but prefer a role-named hook that survives a
20
+ * restyle. Existing `data-testid` attributes ARE such hooks and are reused rather than duplicated;
21
+ * `data-tour="..."` is added only where a screen has no stable hook (see docs/recipes or /sssb:new-tour).
22
+ */
23
+ export type TourAction =
24
+ /** Glide the ghost cursor to an element (scrolls it into view first). */
25
+ | ['move', string]
26
+ /** Move, ripple, pause, then fire a REAL click — React handles it exactly like a user's. */
27
+ | ['click', string]
28
+ /** Move, focus, hide the cursor, and type character by character (native setter + input event, so
29
+ * controlled components update). */
30
+ | ['type', string, string]
31
+ /** Set a NATIVE `<select>` and fire `change`. Mantine's combobox is not a native select — open and
32
+ * pick it with two `click`s instead, which is also the better thing to watch. */
33
+ | ['select', string, string]
34
+ /**
35
+ * Drive the Simulator panel to a tab through its OWN controls: expand it if collapsed, then click
36
+ * the tab. Idempotent, so a tour never has to know how the viewer left the panel. With no argument
37
+ * it collapses the panel instead (ending on the product).
38
+ */
39
+ | ['panel', string?]
40
+ /** Assert an element is on screen, waiting for it. A miss fails the tour (and CI). */
41
+ | ['expect', string]
42
+ /** Assert an element CONTAINS text, waiting for it. The needle is tour-local simulated content
43
+ * (a subject the tour itself typed), never UI copy — UI copy is translated, this is not. */
44
+ | ['expectText', string, string]
45
+ /** Smooth-scroll an element into view without touching it. */
46
+ | ['scrollTo', string]
47
+ /** Scroll the page back to the top. */
48
+ | ['scrollTop']
49
+ /** Wait, in milliseconds (scaled by the speed control). */
50
+ | ['pause', number]
51
+
52
+ /** One beat of the story: what the viewer reads, and what the cursor does while they read it. */
53
+ export interface TourStep {
54
+ /**
55
+ * Fully-qualified key into the APP's catalog (`namespace.key`), resolved with the root translator —
56
+ * the same shape an app-registered Simulator flag's `labelKey` uses, and for the same reason: a tour
57
+ * is app vocabulary, so its narration ships in the app's messages, not SSSB's. `<b>` is supported
58
+ * (next-intl rich text) for the one term that matters.
59
+ */
60
+ textKey: string
61
+ /** Runs on ENTRY to the step, while the viewer reads the narration. */
62
+ script?: TourAction[]
63
+ /**
64
+ * Runs when the viewer presses Next, BEFORE the story moves on. **Every submit belongs here** —
65
+ * that is what keeps a tour watchable rather than a video: nothing mutates the world until the
66
+ * person watching decides it is time.
67
+ */
68
+ advance?: TourAction[]
69
+ /** A selector to vignette: the page dims and the target haloes. One target per step, at most. */
70
+ spotlight?: string
71
+ }
72
+
73
+ /** A registered tour — what the Simulator Tours tab lists, and what Start runs. */
74
+ export interface TourDefinition {
75
+ /** Stable id: the tab's testids and the resume marker are built from it. */
76
+ id: string
77
+ /** Fully-qualified keys into the APP's catalog (see TourStep.textKey). */
78
+ titleKey: string
79
+ summaryKey: string
80
+ /**
81
+ * The world state this tour assumes, restored before step 1. `'reset'` (the seeded world) and the id
82
+ * of any registered demo preset (`@sssb/app-config/presets`, @sssb/kit/core/presets.ts) work on
83
+ * EVERY host; a saved snapshot name works only on a server host, and the `file://` walkthrough gate
84
+ * records it as a miss. Omit for a tour that runs from wherever the viewer happens to be.
85
+ */
86
+ snapshot?: string
87
+ steps: TourStep[]
88
+ }
89
+
90
+ /** Something a script asked for and did not get. Surfaced in the bar while a tour runs, counted in its
91
+ * end-of-run report, and asserted to be zero by the CI walkthrough — this is what stops tours rotting. */
92
+ export interface TourMiss {
93
+ /** The action that missed, e.g. `click`. */
94
+ action: string
95
+ /** The selector (or, for `expectText`, `selector — needle`) that never resolved. */
96
+ target: string
97
+ }