@sssb/create 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 (91) hide show
  1. package/LICENSE +21 -0
  2. package/bin/create.js +136 -0
  3. package/package.json +26 -5
  4. package/src/add-app.js +165 -0
  5. package/src/args.js +270 -0
  6. package/src/files.js +677 -0
  7. package/src/generate.js +612 -0
  8. package/src/json.js +60 -0
  9. package/src/signals.js +72 -0
  10. package/src/template.js +496 -0
  11. package/src/yaml.js +17 -0
  12. package/template/app/DEMO-SIZE.md +55 -0
  13. package/template/app/config/app.ts +17 -0
  14. package/template/app/config/params.ts +85 -0
  15. package/template/app/infra/README.md +85 -0
  16. package/template/app/infra/app.ts +45 -0
  17. package/template/app/infra/cdk.json +9 -0
  18. package/template/app/infra/lib/tags.ts +35 -0
  19. package/template/app/infra/package.json +20 -0
  20. package/template/app/infra/tsconfig.json +13 -0
  21. package/template/app/messages/en.json +21 -0
  22. package/template/app/messages/es.json +21 -0
  23. package/template/app/next.config.ts +9 -0
  24. package/template/app/package.json +40 -0
  25. package/template/app/playwright.config.ts +50 -0
  26. package/template/app/playwright.demo.config.ts +10 -0
  27. package/template/app/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx +61 -0
  28. package/template/app/src/app/[locale]/(protected)/dashboard/page.tsx +21 -0
  29. package/template/app/src/app/[locale]/(protected)/header-glue.tsx +59 -0
  30. package/template/app/src/app/[locale]/(protected)/layout.tsx +43 -0
  31. package/template/app/src/app/[locale]/layout.tsx +63 -0
  32. package/template/app/src/app/[locale]/page.tsx +9 -0
  33. package/template/app/src/app/[locale]/signin/page.tsx +55 -0
  34. package/template/app/src/app/[locale]/signin/picker-glue.tsx +21 -0
  35. package/template/app/src/app/api/auth/dev-signin/route.ts +12 -0
  36. package/template/app/src/app/api/auth/org/route.ts +10 -0
  37. package/template/app/src/app/api/auth/signout/route.ts +9 -0
  38. package/template/app/src/app/api/items/route.ts +59 -0
  39. package/template/app/src/app/api/respond.ts +13 -0
  40. package/template/app/src/app/api/simulator/[...path]/route.ts +23 -0
  41. package/template/app/src/app/api/webhooks/cron/route.test.ts +59 -0
  42. package/template/app/src/app/api/webhooks/cron/route.ts +16 -0
  43. package/template/app/src/app/layout.tsx +7 -0
  44. package/template/app/src/app-config/abilities.ts +86 -0
  45. package/template/app/src/app-config/actors.ts +13 -0
  46. package/template/app/src/app-config/audit.ts +9 -0
  47. package/template/app/src/app-config/db/migrations/1001_items.ts +37 -0
  48. package/template/app/src/app-config/db/migrations/1002_items_keyset_index.ts +29 -0
  49. package/template/app/src/app-config/db/migrations/index.ts +13 -0
  50. package/template/app/src/app-config/db/rls-proofs.ts +186 -0
  51. package/template/app/src/app-config/db/schema.ts +23 -0
  52. package/template/app/src/app-config/digest.ts +10 -0
  53. package/template/app/src/app-config/identity.ts +8 -0
  54. package/template/app/src/app-config/inbound-email.ts +10 -0
  55. package/template/app/src/app-config/jobs.ts +28 -0
  56. package/template/app/src/app-config/messages.ts +18 -0
  57. package/template/app/src/app-config/notifications.ts +31 -0
  58. package/template/app/src/app-config/preset-operations.ts +9 -0
  59. package/template/app/src/app-config/presets.ts +18 -0
  60. package/template/app/src/app-config/seed.ts +7 -0
  61. package/template/app/src/app-config/simulator.ts +17 -0
  62. package/template/app/src/app-config/tours.ts +14 -0
  63. package/template/app/src/app-config/webhooks.ts +13 -0
  64. package/template/app/src/components/dashboard-screen.tsx +26 -0
  65. package/template/app/src/components/items-card.tsx +106 -0
  66. package/template/app/src/components/welcome-screen.tsx +20 -0
  67. package/template/app/src/demo-static/app.tsx +77 -0
  68. package/template/app/src/demo-static/index.html +12 -0
  69. package/template/app/src/demo-static/main.tsx +40 -0
  70. package/template/app/src/domain/db/items.ts +37 -0
  71. package/template/app/src/proxy.test.ts +44 -0
  72. package/template/app/src/proxy.ts +18 -0
  73. package/template/app/src/seed/index.ts +93 -0
  74. package/template/app/src/sssb.conformance.test.ts +7 -0
  75. package/template/app/src/styles/index.css +1 -0
  76. package/template/app/tests/catalog.ts +15 -0
  77. package/template/app/tests/contract/rls-contract.test.ts +14 -0
  78. package/template/app/tests/demo-static/static-shell.spec.ts +32 -0
  79. package/template/app/tests/e2e/items.spec.ts +102 -0
  80. package/template/app/tests/e2e/simulator.spec.ts +40 -0
  81. package/template/app/tsconfig.json +29 -0
  82. package/template/app/vite.demo.config.ts +8 -0
  83. package/template/guide.md +132 -0
  84. package/template/meta.json +633 -0
  85. package/template/root/_dot_editorconfig +12 -0
  86. package/template/root/_dot_husky/commit-msg +1 -0
  87. package/template/root/_dot_husky/pre-commit +1 -0
  88. package/template/root/_dot_nvmrc +1 -0
  89. package/template/root/_dot_prettierrc.json +5 -0
  90. package/template/root/commitlint.config.mjs +1 -0
  91. package/README.md +0 -3
@@ -0,0 +1,40 @@
1
+ import '@mantine/core/styles.css'
2
+ import '../styles/index.css'
3
+
4
+ import { MantineProvider } from '@mantine/core'
5
+ import { NextIntlClientProvider } from 'next-intl'
6
+ import { StrictMode, useState } from 'react'
7
+ import { createRoot } from 'react-dom/client'
8
+ import type { Locale } from '@sssb/kit/core/locale'
9
+ import { mergeMessages, type MessageTree } from '@sssb/kit/i18n/messages'
10
+ import enFramework from '@sssb/kit/i18n/messages/en.json'
11
+ import esFramework from '@sssb/kit/i18n/messages/es.json'
12
+ import { getTenantTheme } from '@sssb/kit/theme'
13
+ import enApp from '../../messages/en.json'
14
+ import esApp from '../../messages/es.json'
15
+ import { tenants } from '../seed'
16
+ import { StaticDemoApp } from './app'
17
+
18
+ // The catalogs are physically split (ADR-0012), so the static shell composes both halves exactly like
19
+ // the server's request config does — statically imported, since a file:// bundle inlines everything.
20
+ const MESSAGES: Record<Locale, MessageTree> = {
21
+ en: mergeMessages(enFramework, enApp),
22
+ es: mergeMessages(esFramework, esApp),
23
+ }
24
+
25
+ function Root() {
26
+ const [locale, setLocale] = useState<Locale>('en')
27
+ return (
28
+ <NextIntlClientProvider locale={locale} messages={MESSAGES[locale]}>
29
+ <MantineProvider theme={getTenantTheme(tenants[0]!.slug)}>
30
+ <StaticDemoApp locale={locale} onLocaleChange={setLocale} />
31
+ </MantineProvider>
32
+ </NextIntlClientProvider>
33
+ )
34
+ }
35
+
36
+ createRoot(document.getElementById('root')!).render(
37
+ <StrictMode>
38
+ <Root />
39
+ </StrictMode>,
40
+ )
@@ -0,0 +1,37 @@
1
+ import type { KeysetPosition } from '@sssb/kit/core/keyset'
2
+ import { keysetPage } from '@sssb/kit/db/keyset'
3
+ import type { DbPort } from '@sssb/kit/ports/db'
4
+
5
+ /** An item as its owning team sees it in the list. */
6
+ interface ItemView {
7
+ id: string
8
+ title: string
9
+ }
10
+
11
+ /** One page of a team's items, plus the token that fetches the next one (null at the end). */
12
+ export interface ItemPage {
13
+ items: ItemView[]
14
+ nextCursor: string | null
15
+ }
16
+
17
+ /**
18
+ * Lists ONE PAGE of a team's items, newest first. Tenant-scoped by RLS AND filtered to the org: the same
19
+ * two boundaries as every list (ADR-0004).
20
+ *
21
+ * A list that can grow pages through the framework primitive (`@sssb/kit/db/keyset`), never a hand-rolled
22
+ * `LIMIT`/`OFFSET`. The callback is THE query, run once per page with the cursor added as one more
23
+ * conjunct, so page 7 is scoped by construction: there is no second code path that could forget the org.
24
+ * The order is fixed here (the primitive's default, `created_at` then `id`, newest first), never taken
25
+ * from a request, because a cursor does not say which column it was minted under.
26
+ */
27
+ export async function listItems(
28
+ db: DbPort,
29
+ tenantId: string,
30
+ orgId: string,
31
+ page: { after: KeysetPosition | null; limit: number },
32
+ ): Promise<ItemPage> {
33
+ const result = await keysetPage(db, { tenantId, after: page.after, limit: page.limit }, (trx) =>
34
+ trx.selectFrom('items').select(['id', 'title']).where('org_id', '=', orgId),
35
+ )
36
+ return { items: result.rows.map(({ id, title }) => ({ id, title })), nextCursor: result.nextCursor }
37
+ }
@@ -0,0 +1,44 @@
1
+ // @vitest-environment node
2
+ import { NextRequest, NextResponse, type NextFetchEvent } from 'next/server'
3
+ import { unstable_doesMiddlewareMatch } from 'next/experimental/testing/server'
4
+ import { describe, expect, it, vi } from 'vitest'
5
+ import proxy, { config } from './proxy'
6
+
7
+ // next-intl's middleware does not load under Vitest (its ESM imports `next/server` without an extension), so a
8
+ // stand-in marks the requests it is handed.
9
+ vi.mock('next-intl/middleware', () => ({
10
+ default: () => (request: NextRequest) =>
11
+ NextResponse.redirect(new URL(`/en${request.nextUrl.pathname}`, request.url)),
12
+ }))
13
+
14
+ // The proxy as Next runs it, in simulated mode (the test's run mode): which paths reach it, and what it does there.
15
+ // In real mode the same proxy runs inside the auth provider's middleware, which must see every page and API route.
16
+ function run(path: string) {
17
+ const request = new NextRequest(`http://localhost:3100${path}`)
18
+ return proxy(request, { waitUntil: () => {} } as unknown as NextFetchEvent)
19
+ }
20
+
21
+ describe('the proxy', () => {
22
+ it.each(['/', '/en/projects', '/es', '/api', '/api/projects', '/api/webhooks/cron', '/api/projects/report.csv'])(
23
+ 'is run on %s',
24
+ (path) => {
25
+ expect(unstable_doesMiddlewareMatch({ config, url: path })).toBe(true)
26
+ },
27
+ )
28
+
29
+ it.each(['/_next/static/chunk.js', '/favicon.ico', '/_vercel/insights', '/apiary'])('is not run on %s', (path) => {
30
+ expect(unstable_doesMiddlewareMatch({ config, url: path })).toBe(false)
31
+ })
32
+
33
+ it('hands a page to the locale routing', async () => {
34
+ const response = await run('/projects')
35
+ expect(response?.headers.get('location')).toBe('http://localhost:3100/en/projects')
36
+ })
37
+
38
+ it('passes an API route through untouched', async () => {
39
+ const response = await run('/api/projects')
40
+ expect(response?.headers.get('x-middleware-next')).toBe('1')
41
+ expect(response?.headers.get('location')).toBeNull()
42
+ expect(response?.headers.get('x-middleware-rewrite')).toBeNull()
43
+ })
44
+ })
@@ -0,0 +1,18 @@
1
+ import createMiddleware from 'next-intl/middleware'
2
+ import { NextResponse } from 'next/server'
3
+ import { withAuthProxy } from '@sssb/kit/adapters/proxy'
4
+ import { routing } from '@sssb/kit/i18n/routing'
5
+
6
+ // Next 16 renamed middleware.ts -> proxy.ts. next-intl negotiates the locale on pages; an API route passes through.
7
+ // withAuthProxy runs this inside the auth provider's middleware in real mode, which SSSB's auth adapter needs.
8
+ const locales = createMiddleware(routing)
9
+
10
+ export default withAuthProxy((request) =>
11
+ request.nextUrl.pathname.startsWith('/api') ? NextResponse.next() : locales(request),
12
+ )
13
+
14
+ export const config = {
15
+ // Pages for the locale routing, and every API route, since the auth provider's middleware must see those too.
16
+ // Outside `/api`, a path with a dot in it (a static file) is left out, as are `/_next` and `/_vercel`.
17
+ matcher: ['/((?!api|_next|_vercel|.*\\..*).*)', '/api/:path*'],
18
+ }
@@ -0,0 +1,93 @@
1
+ import type { SeedAgreement, SeedJobSchedule, SeedOrg, SeedPerson, SeedTenant } from '@sssb/kit/seed/contracts'
2
+
3
+ /**
4
+ * This app's seed world — two tenants, two teams, three people.
5
+ *
6
+ * WHY IT LIVES INSIDE THE APP (and not in a `packages/*-seed` workspace like SSSB's reference
7
+ * app's `@app/seed`): the seed IS app content. The framework never imports it directly — it reads
8
+ * `@sssb/app-config/seed`, which re-exports this file — so its location is entirely the app's choice, and
9
+ * an app-local module is one fewer workspace package to keep. It also
10
+ * proves `@sssb/kit/seed/contracts` is a real published surface rather than a private arrangement with one
11
+ * package: this world fills the same contracts with no `@app/seed` anywhere in sight.
12
+ *
13
+ * Deliberately smaller than SSSB's reference app's: two tenants (the minimum that makes tenant isolation
14
+ * observable), one team each, and the roles the framework's own screens need to stay interesting —
15
+ * an admin who can invite, a plain member, and a restricted member whose authoring surface is
16
+ * reduced. `preAcceptedByAllInTenant` is unused because this app seeds no agreements.
17
+ *
18
+ * This content came with the generated app, and every sign-in picker lists all of it. Replace it with
19
+ * your own world rather than adding yours beside it (SSSB's adoption guide says what else the generated
20
+ * app still shows).
21
+ */
22
+
23
+ export type {
24
+ PersonRole,
25
+ SeedAgreement,
26
+ SeedAgreementGating,
27
+ SeedAgreementKind,
28
+ SeedJobSchedule,
29
+ SeedMembership,
30
+ SeedOrg,
31
+ SeedPerson,
32
+ SeedScheduleSpec,
33
+ SeedTenant,
34
+ } from '@sssb/kit/seed/contracts'
35
+
36
+ export const tenants: SeedTenant[] = [
37
+ { slug: 'northwind', name: 'Northwind', themePrimaryColor: 'teal', themeRadius: 'sm' },
38
+ { slug: 'westgate', name: 'Westgate', themePrimaryColor: 'grape', themeRadius: 'xl' },
39
+ ]
40
+
41
+ /**
42
+ * One team per tenant. `ops` doubles as the operator org (see `staffOrgSlug` in
43
+ * ../app-config/abilities.ts): the two slugs must agree, and this is the whole of that agreement.
44
+ */
45
+ export const organizations: SeedOrg[] = [
46
+ { slug: 'ops', name: 'Operations', tenantSlug: 'northwind' },
47
+ { slug: 'field', name: 'Field Team', tenantSlug: 'westgate' },
48
+ ]
49
+
50
+ export const people: SeedPerson[] = [
51
+ {
52
+ id: 'person-owner',
53
+ name: 'Nadia Owner',
54
+ email: 'nadia.owner@example.test',
55
+ locale: 'en',
56
+ tenantSlug: 'northwind',
57
+ memberships: [{ orgSlug: 'ops', role: 'admin' }],
58
+ restricted: false,
59
+ },
60
+ {
61
+ id: 'person-teammate',
62
+ name: 'Tomás Compañero',
63
+ email: 'tomas.companero@example.test',
64
+ locale: 'es',
65
+ tenantSlug: 'northwind',
66
+ memberships: [{ orgSlug: 'ops', role: 'member' }],
67
+ restricted: false,
68
+ },
69
+ {
70
+ // The other tenant, and the star of the tenancy e2e: whatever Nadia writes, Wes cannot see.
71
+ id: 'person-other-tenant',
72
+ name: 'Wes Westgate',
73
+ email: 'wes.westgate@example.test',
74
+ locale: 'en',
75
+ tenantSlug: 'westgate',
76
+ memberships: [{ orgSlug: 'field', role: 'admin' }],
77
+ restricted: false,
78
+ },
79
+ ]
80
+
81
+ /** No agreements: the access-gate capability is registered-but-empty, like most of this app's seam. */
82
+ export const agreements: SeedAgreement[] = []
83
+
84
+ /** No recurring work: this app registers no job kinds, so nothing is scheduled. */
85
+ export const jobSchedules: SeedJobSchedule[] = []
86
+
87
+ export function findTenant(slug: string): SeedTenant | undefined {
88
+ return tenants.find((t) => t.slug === slug)
89
+ }
90
+
91
+ export function findOrg(slug: string): SeedOrg | undefined {
92
+ return organizations.find((o) => o.slug === slug)
93
+ }
@@ -0,0 +1,7 @@
1
+ import path from 'node:path'
2
+ import { conformanceSuite } from '@sssb/kit/testing'
3
+
4
+ // SSSB's conformance suite, run against THIS app's seam and route tree (ADR-0014 part 3). Keep this file in the app's
5
+ // own tree: that is what makes the checks run by default. Leaving a check out takes a named opt-out with a reason,
6
+ // `optOut: { '<check id>': '<why>' }`; the ids are in @sssb/kit/testing/checks.json.
7
+ conformanceSuite({ appDir: path.resolve(import.meta.dirname, '..'), optOut: {} })
@@ -0,0 +1 @@
1
+ @layer reset, base, tokens, recipes, utilities;
@@ -0,0 +1,15 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ /**
5
+ * This app's own message catalog, read from disk at test time.
6
+ *
7
+ * Specs assert against THIS rather than against the product name as a literal, because the product name
8
+ * is the one thing an adopter is guaranteed to change (`pnpm create @sssb` names it). A spec that hard-codes it
9
+ * turns the rename into a broken gate.
10
+ */
11
+ export function welcome(locale: string): { readonly title: string; readonly [key: string]: string } {
12
+ const file = path.resolve(__dirname, `../messages/${locale}.json`)
13
+ const catalog = JSON.parse(readFileSync(file, 'utf8')) as { welcome: { title: string; [key: string]: string } }
14
+ return catalog.welcome
15
+ }
@@ -0,0 +1,14 @@
1
+ import { contractSuite } from '@sssb/kit/testing/contract'
2
+ import { portFor } from '@sssb/tools/ports'
3
+
4
+ /**
5
+ * The "fakes can't drift" job for this app: the SAME migrations + RLS proof suite that runs on pglite in unit
6
+ * tests, executed against REAL Postgres, in a database of this app's own (`<slug>_contract`), by a non-superuser
7
+ * owner, by a superuser, and over the RDS Data API transport through its emulator. Everything is the contract
8
+ * runner's (`@sssb/kit/testing/contract`), which reads the app through its seam; this file only says where the
9
+ * embedded Postgres listens and which checks, if any, the app leaves out (`optOut: { '<check id>': '<why>' }`).
10
+ *
11
+ * Run via `pnpm test:contract` — deliberately not part of the fast unit suite. Locally that's embedded-postgres
12
+ * binaries (no docker on the dev VM); in CI, CONTRACT_DATABASE_URL names a postgres service container.
13
+ */
14
+ contractSuite({ port: portFor('contractPg'), optOut: {} })
@@ -0,0 +1,32 @@
1
+ import path from 'node:path'
2
+ import { expect, test } from '@playwright/test'
3
+ import { welcome } from '../catalog'
4
+
5
+ const indexUrl = `file://${path.resolve(__dirname, '../../dist-demo/index.html')}`
6
+
7
+ test('the static shell signs in and lists an item, with the framework panel intact', async ({ page }) => {
8
+ await page.goto(indexUrl)
9
+ // Asserted against the catalog, not the product name — `pnpm create @sssb` renames the app, and this
10
+ // spec is the first thing that would have broken if it hard-coded the title.
11
+ await expect(page.getByRole('heading', { level: 1 })).toContainText(welcome('en').title)
12
+
13
+ await page.getByTestId('dashboard-link').click()
14
+ await page.getByTestId('person-person-owner').click()
15
+ await expect(page.getByTestId('signed-in-as')).toContainText('Nadia Owner')
16
+
17
+ await page.getByTestId('item-input').fill('write the first item')
18
+ await page.getByTestId('item-add').click()
19
+ await expect(page.getByTestId('items-list')).toContainText('write the first item')
20
+
21
+ // The whole Simulator panel comes from the package: an app that registers no tabs still gets the
22
+ // framework's, and switching people still works.
23
+ await page.getByTestId('simulator-pill').click()
24
+ await expect(page.getByTestId('simulator-panel')).toBeVisible()
25
+ await page.getByTestId('people-person-teammate').click()
26
+ await expect(page.getByTestId('signed-in-as')).toContainText('Tomás Compañero')
27
+
28
+ // The tours off-switch: this app registers `tours: []` (src/app-config/tours.ts), so the Tours tab
29
+ // does not exist at all — an adopter who wants no scripted walkthrough pays nothing for the one
30
+ // SSSB's reference app ships.
31
+ await expect(page.getByTestId('simulator-tab-tours')).toHaveCount(0)
32
+ })
@@ -0,0 +1,102 @@
1
+ import { expect, test, type Page } from '@playwright/test'
2
+
3
+ /**
4
+ * The claim this app exists to prove: an item written in one tenant is invisible from the other, through the
5
+ * entire stack (UI → route → withTenant → RLS on pglite).
6
+ *
7
+ * Crossing tenants is done the way a real user would, not through the Simulator panel: sign out, sign in
8
+ * as somebody whose home tenant differs.
9
+ */
10
+
11
+ async function signInAs(page: Page, personId: string) {
12
+ await page.goto('/en/signin')
13
+ await page.getByTestId(`person-${personId}`).click()
14
+ await page.waitForURL('**/dashboard')
15
+ }
16
+
17
+ async function signOut(page: Page) {
18
+ await page.getByTestId('user-menu').click()
19
+ await page.getByTestId('menu-signout').click()
20
+ await page.waitForURL(/\/en\/?$/)
21
+ }
22
+
23
+ /** Hydration-safe entry: right after a navigation, filling the controlled input can beat React
24
+ * hydration, so the DOM has the text but state does not and the button stays disabled. */
25
+ async function addItem(page: Page, title: string) {
26
+ await expect(async () => {
27
+ await page.getByTestId('item-input').fill(title)
28
+ await expect(page.getByTestId('item-add')).toBeEnabled({ timeout: 1_000 })
29
+ }).toPass()
30
+ await page.getByTestId('item-add').click()
31
+ await expect(page.getByTestId('items-list')).toContainText(title)
32
+ }
33
+
34
+ test('an item created in one tenant is invisible from the other', async ({ page }) => {
35
+ const secret = `northwind-item-${Date.now()}`
36
+
37
+ // Nadia's home tenant is northwind.
38
+ await signInAs(page, 'person-owner')
39
+ await expect(page.getByTestId('active-tenant')).toHaveText('Northwind')
40
+ await addItem(page, secret)
41
+
42
+ // Reload proves the row survived a round trip through Postgres rather than living in React state.
43
+ await page.reload()
44
+ await expect(page.getByTestId('items-list')).toContainText(secret)
45
+
46
+ // Cross to the other tenant: Wes must not see it, and his own view starts empty.
47
+ await signOut(page)
48
+ await signInAs(page, 'person-other-tenant')
49
+ await expect(page.getByTestId('active-tenant')).toHaveText('Westgate')
50
+ await expect(page.getByTestId('items-card')).toBeVisible()
51
+ await expect(page.getByTestId('items-card')).not.toContainText(secret)
52
+
53
+ // ...and back again: Nadia's item is still there.
54
+ await signOut(page)
55
+ await signInAs(page, 'person-owner')
56
+ await expect(page.getByTestId('items-list')).toContainText(secret)
57
+ })
58
+
59
+ test('the items list pages, and the endpoint refuses a cursor it cannot read', async ({ page }) => {
60
+ await signInAs(page, 'person-owner')
61
+ await expect(page.getByTestId('items-card')).toBeVisible()
62
+
63
+ // The default page is 20, so 22 more items guarantee the list is longer than one page whatever else this
64
+ // run has already written. Written through the route, the way the card's own add button does.
65
+ const stamp = Date.now()
66
+ for (let index = 0; index < 22; index++) {
67
+ const response = await page.request.post('/api/items', { data: { title: `paged-${stamp}-${index}` } })
68
+ expect(response.ok()).toBe(true)
69
+ }
70
+ await page.reload()
71
+ const rows = page.getByTestId('item-row')
72
+ await expect(rows).toHaveCount(20)
73
+ await expect(page.getByTestId('items-load-more')).toBeVisible()
74
+
75
+ // "Show older items" APPENDS: what is on screen stays, in the same order, and the button goes away at the
76
+ // end of the list. Walked with a guard rather than one click, because this world keeps its rows between
77
+ // runs and the list can be longer than two pages.
78
+ let previous = await rows.allTextContents()
79
+ for (let click = 0; click < 20; click++) {
80
+ if (!(await page.getByTestId('items-load-more').isVisible())) break
81
+ await page.getByTestId('items-load-more').click()
82
+ await expect(rows).not.toHaveCount(previous.length)
83
+ const current = await rows.allTextContents()
84
+ expect(current.slice(0, previous.length)).toEqual(previous)
85
+ previous = current
86
+ }
87
+ await expect(page.getByTestId('items-load-more')).toHaveCount(0)
88
+ expect(previous.length).toBeGreaterThan(20)
89
+ expect(new Set(previous).size).toBe(previous.length)
90
+
91
+ // A malformed cursor is a 400, never a silent first page; the server also caps the page size itself.
92
+ const bad = await page.request.get('/api/items?cursor=not-a-cursor')
93
+ expect(bad.status()).toBe(400)
94
+ expect(await bad.json()).toEqual({ error: 'invalid-cursor' })
95
+ const single = await page.request.get('/api/items?limit=1')
96
+ const onePage = (await single.json()) as { items: unknown[]; nextCursor: string | null }
97
+ expect(onePage.items.length).toBe(1)
98
+ expect(onePage.nextCursor).not.toBeNull()
99
+ const greedy = await page.request.get('/api/items?limit=1000000')
100
+ expect(greedy.status()).toBe(200)
101
+ expect(((await greedy.json()) as { items: unknown[] }).items.length).toBeLessThanOrEqual(100)
102
+ })
@@ -0,0 +1,40 @@
1
+ import { expect, test, type Page } from '@playwright/test'
2
+
3
+ /**
4
+ * The Simulator panel on this app's own server: SSSB's panel, fed through `src/app/api/simulator/[...path]/route.ts`.
5
+ * One walk through the tabs it serves (People, Mail, Jobs), with a GET and a POST on each side of a sign-in.
6
+ */
7
+
8
+ /** The pill renders before React attaches its click handler; the panel stamps `data-hydrated` once it has. */
9
+ async function openPanel(page: Page) {
10
+ const panel = page.getByTestId('simulator-panel')
11
+ await expect(async () => {
12
+ if (await panel.isVisible()) return
13
+ await page.locator('[data-testid="simulator-pill"][data-hydrated]').click({ timeout: 2_000 })
14
+ await expect(panel).toBeVisible({ timeout: 2_000 })
15
+ }).toPass({ timeout: 30_000 })
16
+ }
17
+
18
+ test('the Simulator signs you in as anyone, and serves its mail and jobs tabs', async ({ page }) => {
19
+ // Signed out: the panel is there anyway, and picking a person signs this browser in as them.
20
+ await page.goto('/en/signin')
21
+ await openPanel(page)
22
+ await page.getByTestId('people-person-other-tenant').click()
23
+ await page.waitForURL('**/dashboard')
24
+ await expect(page.getByTestId('active-tenant')).toHaveText('Westgate')
25
+
26
+ // The panel remembers it was open across that reload. It shows the tabs its server serves, and no others.
27
+ await expect(page.getByTestId('simulator-panel')).toBeVisible()
28
+ await expect(page.getByTestId('simulator-tab-mail')).toBeVisible()
29
+ await expect(page.getByTestId('simulator-tab-hooks')).toHaveCount(0)
30
+
31
+ await page.getByTestId('simulator-tab-mail').click()
32
+ await expect(page.getByTestId('simulator-mail')).toBeVisible()
33
+
34
+ // Running what is due answers with a notice inside the panel.
35
+ await page.getByTestId('simulator-tab-jobs').click()
36
+ await expect(page.getByTestId('simulator-clock-now')).toBeVisible()
37
+ await page.getByTestId('simulator-clock-run-due').click()
38
+ // Its notice, not a new-mail one (which names an address) that happened to arrive at the same moment.
39
+ await expect(page.getByTestId('simulator-notice').filter({ hasNotText: '@' })).toBeVisible()
40
+ })
@@ -0,0 +1,29 @@
1
+ {
2
+ "extends": "@sssb/tools/tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "incremental": true,
5
+ "paths": {
6
+ "@/*": ["./src/*"],
7
+ "@sssb/app-config/*": ["./src/app-config/*"],
8
+ "@sssb/kit/*": ["../../packages/kit/src/*"]
9
+ }
10
+ },
11
+ "include": [
12
+ "next-env.d.ts",
13
+ "src/**/*.ts",
14
+ "src/**/*.tsx",
15
+ "tests/**/*.ts",
16
+ ".next/types/**/*.ts",
17
+ "*.ts",
18
+ "config/**/*.ts",
19
+ ".next/dev/types/**/*.ts",
20
+ "../../packages/kit/src/**/*.ts",
21
+ "../../packages/kit/src/**/*.tsx"
22
+ ],
23
+ "exclude": [
24
+ "node_modules",
25
+ "../../packages/kit/src/**/*.test.ts",
26
+ "../../packages/kit/src/**/*.test.tsx",
27
+ "../../packages/kit/src/**/*.stories.tsx"
28
+ ]
29
+ }
@@ -0,0 +1,8 @@
1
+ import { staticDemoConfig } from '@sssb/tools/vite'
2
+
3
+ /**
4
+ * Builds the hash-routed static demo shell (src/demo-static) that runs from file://, as one file. The preset
5
+ * (@sssb/tools/vite) passes this app's own seam explicitly, which is what makes the framework bundle resolve against
6
+ * this app's registrations rather than any other app's.
7
+ */
8
+ export default staticDemoConfig({ appDir: __dirname })
@@ -0,0 +1,132 @@
1
+ # SSSB app guide
2
+
3
+ The rules for an app built on SSSB (`@sssb/kit`). Paths are relative to the app's own directory, the package that
4
+ depends on `@sssb/kit`. `pnpm exec sssb guide` copies this file into your repository under a hash stamp: edit nothing in
5
+ the copy, rerun the command after an upgrade, and review the diff. Most rules are enforced by the `@sssb/eslint-plugin`
6
+ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
7
+
8
+ ## The seam
9
+
10
+ - The app extends the framework only through the `@sssb/app-config/*` seam, the modules in `src/app-config/`.
11
+ Register new subjects, jobs, event kinds, tables and migrations there. Never edit or patch a framework base union or
12
+ registry.
13
+ - Import `@sssb/kit` only by a published subpath, a key of its `exports` map. Everything else in the package is
14
+ internal.
15
+
16
+ ## Vendors, environment and parameters
17
+
18
+ - Vendor SDKs (`@clerk/*`, `@aws-sdk/*`, `@anthropic-ai/*`, `@sentry/*`, `posthog-*`, `mailgun.js`, `pg`) are
19
+ imported only in an app's real adapters, `adapters/real/` (and in what runs outside the request path: `next.config.*`
20
+ for the Sentry build plugin, the contract tests in `tests/contract/`, the deployment in `infra/`). Everything else
21
+ codes against a port: `@sssb/kit/ports/*`, or a port the app owns. SSSB's own real adapters
22
+ (`@sssb/kit/adapters/real/*`) load their SDK too, so every module of the app outside `adapters/real/` (which may
23
+ build on one) and the vendor carve-outs above, tests, stories and scripts included, reaches one only with `import()`
24
+ when `!isSimulated`, never by an import declaration (re-exports included; a type-only `import type` or
25
+ `export type`, which loads nothing, is allowed).
26
+ - A vendor SSSB has no port for gets a port the app owns, under `src`: the port module (`ports/<name>.ts`), a registry
27
+ (`adapters/index.ts`) that takes the run mode from SSSB's `isSimulated` (`@sssb/kit/adapters/index`) and loads the
28
+ real adapter only with `import()`, a fake, and the real adapter in `adapters/real/`, the one directory that imports
29
+ the SDK. Nothing imports `adapters/real/` statically, and a fake never imports it at all. Add the SDK to the ban in
30
+ the app's own `package.json`: `"sssb": { "vendors": ["stripe", "stripe/*"] }`.
31
+ - Read `process.env` only in `adapters/real/` (and never the run mode there), in Next's instrumentation hooks, in
32
+ tests and in the app-root tool configs (Playwright, Vite). Every other module imports the resolved value: deployment
33
+ parameters from `config/params.ts`, the run mode from `isSimulated`.
34
+ - Deployment and service parameters exist only in `config/params.ts`. Secret values never enter the repository.
35
+ - Declare which of SSSB's optional ports the app uses in `config/params.ts`'s `ports` (`llm`, `email`, `inboundEmail`,
36
+ `jobs`). A port the app does not use is `none`, never configured with placeholder values.
37
+ - A job handler never reads the seed (`@sssb/app-config/seed`), which a deployment does not have: it finds people with
38
+ `ctx.auth.listMembers(orgSlug)`, and a person's locale with `ctx.resolveLocale`, where the runner provides one.
39
+ - `pnpm dev` stays hermetic: no docker, no credentials, no network. Never add `next/font/google`, telemetry, or
40
+ anything that phones home.
41
+ - Anything that needs real credentials, accounts or money is a row in the workspace's cutover checklist, never a
42
+ blocker: the app boots, and is tested, without it.
43
+ - `src/proxy.ts` default-exports the app's proxy wrapped in `withAuthProxy` from `@sssb/kit/adapters/proxy`, and its
44
+ `config.matcher` sends it every page and every `/api` route: in real mode SSSB's auth adapter needs its provider's
45
+ middleware to have seen the request, and `withAuthProxy` runs that middleware around your proxy (loading none of it
46
+ in simulated mode). Never import the provider's middleware yourself. A page path has no dot in it (the generated
47
+ matcher leaves those out, as static files), and Next buffers at most `proxyClientMaxBodySize` (10MB by default) of a
48
+ body the proxy sees, so an upload limit above it raises
49
+ `experimental.proxyClientMaxBodySize` in `next.config.ts` too.
50
+
51
+ ## Data
52
+
53
+ - Tenant-scoped queries run only inside `db.withTenant()`. `getDb()` is banned in every module under `src`
54
+ (`sssb/no-raw-db-handle`); tests are exempt, except a route's or a screen's. A module that truly needs the raw
55
+ client is a named entry, with its reason, in the app's `lint-exceptions.mjs`: a path relative to the app, one
56
+ existing file per entry, never a glob or a directory.
57
+ - A list that can grow pages through `@sssb/kit/db/keyset`, never a hand-rolled `LIMIT`/`OFFSET`. Parse the cursor
58
+ with `parseDbKeysetCursor` and answer 400 when it is `invalid`; clamp the page size on the server; fix the
59
+ `orderBy` column per route, never from the client.
60
+ - App migrations live in `src/app-config/db/migrations/`, numbered 1001 and up (0001–0999 are the framework's), and
61
+ are listed in `src/app-config/db/migrations/index.ts`. A new tenant table copies the RLS pattern of
62
+ `src/app-config/db/migrations/1001_items.ts`, the generated app's first migration (once you have removed it, read it
63
+ in SSSB's repository at your release), and its isolation proofs go in `src/app-config/db/rls-proofs.ts`.
64
+ - A role is cluster-wide, so a migration that creates one of the app's own creates it only where it does not exist
65
+ yet: a `DO` block that runs `CREATE ROLE reviewer NOLOGIN` only when
66
+ `NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'reviewer')`. Keep it an ordinary role, before and after every
67
+ migration: NOLOGIN, never CREATEDB, CREATEROLE, SUPERUSER, BYPASSRLS or REPLICATION, granted no privilege on a server
68
+ parameter (`GRANT ... ON PARAMETER`), the owner of no database or tablespace, and a member of no role (at any depth)
69
+ but `app_user` and the app's other named roles (`GRANT reviewer TO app_user` is fine;
70
+ `GRANT pg_read_all_data TO reviewer` is not). Leave the framework's `app_user` ordinary too, since every later owner
71
+ gets ADMIN on it as well: never change its attributes, give it no parameter privilege, database or tablespace, and grant it only
72
+ the app's named roles, never a `pg_*` one. Name your role in `appRoles`, exported beside `appMigrations` from
73
+ `src/app-config/db/migrations/index.ts`: `export const appRoles = ['reviewer'] as const`. The contract tests' owner
74
+ pass grants a later database owner ADMIN on exactly those roles and `app_user`, as Aurora's master user holds on a
75
+ role it created, and refuses a role that is not ordinary; the conformance suite's `app-roles` check fails a role the
76
+ migrations create and `appRoles` does not name, a name they do not create, and a named role or `app_user` they leave
77
+ more than ordinary. Never name `app_user` or a `pg_*` or `rds_*` role.
78
+ - After any migration or database change, run the contract tests on real Postgres (`pnpm test:contract` from the
79
+ workspace root). After renumbering or renaming a migration, wipe
80
+ the local `.data` first.
81
+
82
+ ## Authorization
83
+
84
+ - Every exported mutating route handler (POST, PUT, PATCH, DELETE) in a `route.ts` anywhere under `src/app`, not only
85
+ under `src/app/api`, calls `authorize(...)` from `@sssb/kit/authz/authorize` on its own path, as
86
+ `src/app/api/items/route.ts` does (the generated app's; once you have removed it, read it in SSSB's repository at your
87
+ release). The conformance suite's `authz-mutations` check reads each handler: a string, a
88
+ comment, a dead branch or a helper in another module does not count. Neither does a call whose denial cannot stop
89
+ the handler: in an `async` helper or a callback whose promise the handler neither awaits nor returns, in a callback
90
+ handed to a function the route file defines, or in a `try` whose `catch` does not rethrow. `await` the helper that
91
+ authorizes, and let `withPortErrors` answer the 403.
92
+ - An exemption is an entry in the app's `authz-exemptions.mjs` (`{ files, prefixes }`, keys relative to
93
+ `src/app/api`), with a reason and a `mustMatch` gate. A mutating route outside `src/app/api` can match no
94
+ exemption.
95
+
96
+ ## UI
97
+
98
+ - No hard-coded UI strings: all copy goes through next-intl, accessible names, placeholders, titles and alt text
99
+ included (`sssb/no-jsx-literals`, `sssb/no-literal-a11y-copy`). The app's namespaces live in `messages/en.json` and
100
+ `messages/es.json`; the framework ships its own catalog, and the two are deep-merged wherever messages load. The
101
+ merged catalogs stay key- and placeholder-identical.
102
+ - Screens are router-agnostic: they live in `src/components`, and the files under `src/app` are thin wrappers with no
103
+ logic, so the `file://` static demo still builds.
104
+
105
+ ## Tests
106
+
107
+ - Keep `src/sssb.conformance.test.ts` (SSSB's conformance suite) and `tests/contract/rls-contract.test.ts` (the
108
+ contract runner on real Postgres). Leave a check out only by a named opt-out with its reason,
109
+ `optOut: { '<check id>': '<why>' }`. `sssb doctor` fails when the Vitest config does not run them.
110
+ - A test that needs a scratch directory calls `makeTestTmpDir()` or `makeTestTmpDirAsync()` from
111
+ `@sssb/tools/testing/tmp-dir`, never `mkdtemp` directly. A script that runs Vitest as a gate goes through
112
+ `sssb check-tmpdir-leak`.
113
+ - E2E specs live in `tests/e2e/` and reach the framework only through `@sssb/kit/testing/e2e` (`sssb check-e2e`).
114
+ Playwright's `workers` stays 1: every worker shares one `.data` behind one dev server.
115
+ - Dead code fails `knip`. Never silence a finding with a broad ignore; add the narrowest entry, with its reason.
116
+
117
+ ## The dev loop
118
+
119
+ - Scheduled work runs in dev only when something ticks it: the app's `pnpm tick` calls the running dev server's cron
120
+ route once, and `DEV_TICK_SECONDS=<n> pnpm dev` ticks it every n seconds. The ticker is off by default and stays off
121
+ under e2e. The cron route (`src/app/api/webhooks/cron/route.ts`) stays behind `withWebhookSecret`: never add a
122
+ bypass for the ticker.
123
+ - The Simulator panel on `pnpm dev` is SSSB's: `src/app/api/simulator/[...path]/route.ts` serves it and the locale
124
+ layout renders it, both in simulated mode only. Each handler in that route file opens with the simulated-mode 404 and
125
+ imports SSSB's handler after it; that first line is what exempts the route from `authorize(...)`.
126
+ - In a linked git worktree the app's ports are derived per checkout, so parallel sessions never adopt each other's dev
127
+ server; `pnpm exec sssb port`, run from the app, prints its port. An app declares its port slot in its package.json,
128
+ `"sssb": { "port": { "name": "ledger", "default": 3800 } }`, and reads its override from `LEDGER_PORT`; its scripts and
129
+ Playwright config name no slot (`sssb tick`, `sssb dev-tick`, `originForApp(__dirname)`), so they read it. Every app of
130
+ a workspace needs a slot of its own, which `sssb doctor` checks: `pnpm exec sssb add-app <slug>` gives a new app one.
131
+ - Before finishing a change, run `pnpm verify` from the workspace root. Format with `pnpm lint:fix`, never by hand.
132
+ Commit messages are conventional commits; the commit-msg hook runs commitlint.