@sssb/create 0.2.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.
package/src/generate.js CHANGED
@@ -25,7 +25,7 @@ import { holdSignals, releaseSignals } from './signals.js'
25
25
  import { filesUnder, fromStored, GUIDE_FILE, readTemplate } from './template.js'
26
26
 
27
27
  /** The @sssb packages the workspace installs (the seam, @sssb/app-config, is the app's own and never installed). */
28
- const SSSB_PACKAGES = ['kit', 'tools', 'eslint-plugin', 'cdk']
28
+ export const SSSB_PACKAGES = ['kit', 'tools', 'eslint-plugin', 'cdk']
29
29
 
30
30
  const SEAM = '@sssb/app-config'
31
31
 
@@ -214,13 +214,13 @@ function asCreateError(error) {
214
214
  * @param {string} slug
215
215
  * @param {import('./template.js').TemplateMeta} meta
216
216
  */
217
- function checkPackageNames(slug, meta) {
217
+ export function checkPackageNames(slug, meta) {
218
218
  const names = new Set(meta.dependencyNames)
219
219
  for (const pkg of [slug, `${slug}-infra`, `${slug}-workspace`]) {
220
220
  if (names.has(pkg)) {
221
221
  throw new CreateError(
222
222
  `the slug "${slug}" would name a package "${pkg}", which is also a dependency the workspace installs ` +
223
- `(npm's ${pkg}): pnpm mistakes one for the other. Pass another --slug`,
223
+ `(npm's ${pkg}): pnpm mistakes one for the other. Pick another slug`,
224
224
  )
225
225
  }
226
226
  }
@@ -248,7 +248,7 @@ const occupants = (dir, also) => readdirSync(dir).filter((entry) => !LEFT_ALONE.
248
248
  * failure part-way, or a SIGINT, SIGTERM or SIGHUP (signals.js), leaves nothing behind: the stage and whatever was
249
249
  * moved up are removed, and the target and its parents too when this run created them (and they are empty).
250
250
  * @param {GenerateOptions} options
251
- * @returns {{ root: string, appDir: string, files: string[], workflowRef: string, tarballs: Record<string, string> | null }}
251
+ * @returns {{ root: string, appDir: string, files: string[], workflowRef: string, tarballs: Record<string, string> | null, port: { name: string, default: number } }}
252
252
  */
253
253
  export function generate({
254
254
  templateDir,
@@ -318,7 +318,14 @@ export function generate({
318
318
  }
319
319
  rmdirSync(made.stage)
320
320
  made.stage = ''
321
- return { root, appDir: path.join(root, 'apps', slug), files, workflowRef: ref, tarballs }
321
+ return {
322
+ root,
323
+ appDir: path.join(root, 'apps', slug),
324
+ files,
325
+ workflowRef: ref,
326
+ tarballs,
327
+ port: firstAppSlot(slug),
328
+ }
322
329
  } catch (error) {
323
330
  undo()
324
331
  throw asCreateError(error)
@@ -336,100 +343,14 @@ export function generate({
336
343
  */
337
344
  function writeWorkspace(root, c, templateDir) {
338
345
  const { slug, name, meta, sssbSpec: spec } = c
339
- const appDir = path.join(root, 'apps', slug)
340
- const inApp = (/** @type {string} */ relative) => path.join(appDir, relative)
341
-
342
- // The template, copied: the app, and the generic workspace files.
343
- for (const [from, to] of /** @type {const} */ ([
344
- ['app', appDir],
345
- ['root', root],
346
- ])) {
347
- for (const stored of filesUnder(path.join(templateDir, from))) {
348
- const file = path.join(to, fromStored(stored))
349
- mkdirSync(path.dirname(file), { recursive: true })
350
- cpSync(path.join(templateDir, from, stored), file)
351
- }
352
- }
353
-
354
- // THE APP'S IDENTITY: its slug (config/app.ts, which everything mechanical derives from), its package names, and
355
- // its display name in its catalogs and titles. Each edit must find what it replaces exactly once, so a template
356
- // that moved its identity elsewhere fails here instead of shipping half-renamed.
357
- const slugLine = /export const APP_SLUG = '([^']+)'/.exec(readFileSync(inApp('config/app.ts'), 'utf8'))
358
- if (!slugLine?.[1]) throw new CreateError("the template's config/app.ts declares no APP_SLUG")
359
- const oldSlug = slugLine[1]
360
- const oldName = readJson(inApp('messages/en.json'))?.welcome?.appName
361
- if (typeof oldName !== 'string') throw new CreateError("the template's messages/en.json has no welcome.appName")
362
- replaceOnce(inApp('config/app.ts'), `export const APP_SLUG = '${oldSlug}'`, `export const APP_SLUG = '${slug}'`)
363
- replaceOnce(inApp('config/app.ts'), `\`${oldSlug}_session\``, `\`${slug}_session\``)
364
- for (const locale of ['en', 'es']) {
365
- for (const key of ['appName', 'title'])
366
- replaceOnce(
367
- inApp(`messages/${locale}.json`),
368
- `"${key}": ${JSON.stringify(oldName)}`,
369
- `"${key}": ${JSON.stringify(name)}`,
370
- )
371
- }
372
- replaceOnce(inApp('src/app/[locale]/layout.tsx'), `title: ${tsString(oldName)}`, `title: ${tsString(name)}`)
373
- replaceOnce(inApp('src/demo-static/index.html'), `<title>${oldName} `, `<title>${htmlText(name)} `)
374
- // Prettier wraps an HTML line past the print width, so the title line must fit (displayName caps the name; `&`
375
- // grows as it is escaped).
376
- const titleLine = readFileSync(inApp('src/demo-static/index.html'), 'utf8')
377
- .split('\n')
378
- .find((line) => line.includes('<title>'))
379
- if (titleLine && columns(titleLine) > 120)
380
- throw new CreateError(`--name "${name}" is too long for the static demo's <title> line: shorten it`)
381
-
382
- // The app's manifest: its name, the @sssb packages it installs, the seam linked as a package of the app's own
383
- // (ADR-0014 part 1), and the lint fences' plugin and ESLint beside it. No `license`: the packages are private, and
384
- // which licence the workspace takes (a LICENSE at its root) is the adopter's to choose, not the starter's to claim.
385
- const manifest = readJson(inApp('package.json'))
386
- manifest.name = slug
387
- delete manifest.license
388
- manifest.description = `${name}: the app.`
389
- pinSssb(manifest, spec)
390
- manifest.dependencies = sorted({ ...manifest.dependencies, [SEAM]: `workspace:${seamPackage(slug)}@*` })
391
- manifest.devDependencies = sorted({
392
- ...manifest.devDependencies,
393
- '@sssb/eslint-plugin': spec('eslint-plugin'),
394
- eslint: /** @type {string} */ (meta.ranges['eslint']),
395
- })
396
- writeFileSync(inApp('package.json'), packageJson(manifest))
397
- const budget = /sssb check-demo-size (\d+)/.exec(manifest.scripts?.['check:demo-size'] ?? '')?.[1]
398
- if (!budget) throw new CreateError("the template's package.json has no `sssb check-demo-size <bytes>` script")
399
-
400
- const infra = readJson(inApp('infra/package.json'))
401
- infra.name = `${slug}-infra`
402
- delete infra.license
403
- pinSssb(infra, spec)
404
- writeFileSync(inApp('infra/package.json'), packageJson(infra))
405
346
 
406
- // The seam package (ADR-0014 part 1, option C): the app's src/app-config, a workspace package of the app's own name
407
- // that the app takes under the name the framework imports (`@sssb/app-config`: `workspace:<slug>-app-config@*`),
408
- // with an export for every module the framework imports. A workspace package, not a `link:`, because pnpm's
409
- // partial installs for the app (`add <pkg>`, `remove`, `update <pkg>`) drop a `link:` dependency as the provider of
410
- // @sssb/kit's peer (the 2026-11-18 addendum to ADR-0014). It takes the app's module `type`, because a nested package.json resets it for everything
411
- // below it.
412
- const seamDir = inApp('src/app-config')
413
- /** @type {Record<string, unknown>} */
414
- const seam = { name: seamPackage(slug), private: true }
415
- if (manifest.type) seam['type'] = manifest.type
416
- seam['exports'] = seamExports(seamDir, meta.seamSpecifiers)
417
- writeFileSync(path.join(seamDir, 'package.json'), packageJson(seam))
418
-
419
- // The app's tsconfig, on @sssb/tools' base: in SSSB's repository the starter's also sends @sssb/kit and the seam to
420
- // source and compiles the framework's own tree (it is the framework's falsifier there). Here resolution goes
421
- // through the installed packages and the seam link, so only the app's own `@/` alias stays.
422
- const tsconfig = readJson(inApp('tsconfig.json'))
423
- if (tsconfig.extends !== '@sssb/tools/tsconfig.base.json')
424
- throw new CreateError(`the template's tsconfig.json extends ${tsconfig.extends}, not @sssb/tools' base`)
425
- const own = (/** @type {string} */ entry) => !entry.startsWith('../')
426
- tsconfig.compilerOptions.paths = { '@/*': tsconfig.compilerOptions.paths['@/*'] }
427
- tsconfig.include = tsconfig.include.filter(own)
428
- tsconfig.exclude = tsconfig.exclude.filter(own)
429
- writeFileSync(inApp('tsconfig.json'), formatJson(tsconfig))
430
-
431
- writeFileSync(inApp('eslint.config.mjs'), files.APP_ESLINT)
432
- writeFileSync(inApp('DEMO-SIZE.md'), files.demoSizeMd(Number(budget)))
347
+ // The template, copied: the generic workspace files, and the app.
348
+ copyTemplate(path.join(templateDir, 'root'), root)
349
+ writeApp(
350
+ path.join(root, 'apps', slug),
351
+ { slug, name, meta, spec, eslint: /** @type {string} */ (meta.ranges['eslint']), port: firstAppSlot(slug) },
352
+ templateDir,
353
+ )
433
354
 
434
355
  // The workspace around it.
435
356
  /** @type {Record<string, string>} */
@@ -441,8 +362,8 @@ function writeWorkspace(root, c, templateDir) {
441
362
  'lint-staged.config.mjs': files.LINT_STAGED,
442
363
  'eslint.config.mjs': files.ROOT_ESLINT,
443
364
  'tsconfig.json': files.ROOT_TSCONFIG,
444
- 'vitest.config.ts': files.vitestConfig(c),
445
- 'vitest.contract.config.ts': files.vitestContractConfig(c),
365
+ 'vitest.config.ts': files.VITEST_CONFIG,
366
+ 'vitest.contract.config.ts': files.VITEST_CONTRACT_CONFIG,
446
367
  'knip.json': files.knipJson(c),
447
368
  '.jscpd.json': files.JSCPD,
448
369
  '.gitleaks.toml': files.GITLEAKS,
@@ -515,3 +436,177 @@ function writeWorkspace(root, c, templateDir) {
515
436
  }
516
437
  return all
517
438
  }
439
+
440
+ /**
441
+ * Every file of a template directory (`app/` or `root/`), copied under `to` with its stored name restored.
442
+ * @param {string} from
443
+ * @param {string} to
444
+ */
445
+ function copyTemplate(from, to) {
446
+ for (const stored of filesUnder(from)) {
447
+ const file = path.join(to, fromStored(stored))
448
+ mkdirSync(path.dirname(file), { recursive: true })
449
+ cpSync(path.join(from, stored), file)
450
+ }
451
+ }
452
+
453
+ /**
454
+ * The port slot names `@sssb/tools` keeps for itself, by the `<NAME>_PORT` variable each reads: a slot of the app's own
455
+ * may not read one of them. A copy of `@sssb/tools`' ports.js (SERVICES), because the generator depends on no SSSB
456
+ * package; tests/tooling/create-generate.test.ts holds the copy to the original by trying every choice on it.
457
+ */
458
+ const BUILT_IN_PORT_VARIABLES = new Set(['SHOWCASE_PORT', 'STARTER_PORT', 'LADLE_PORT', 'CONTRACT_PG_PORT'])
459
+
460
+ /** What a slot's name may be (`@sssb/tools`' ports.js, CUSTOM_NAME and MAX_CUSTOM_NAME_LENGTH): it names a variable. */
461
+ const SLOT_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/
462
+ const MAX_SLOT_NAME = 32
463
+
464
+ /** The main-checkout port a generated app's slot takes: the first `sssb add-app` offers, so a second app takes 3800. */
465
+ export const FIRST_APP_PORT = 3700
466
+
467
+ /**
468
+ * The port slot a new workspace's app declares: a slot of its own, named for its slug as `sssb add-app` names one, so
469
+ * nothing in the app says `starter` (SSSB's reference app's slot). A slug a slot cannot be named for (one longer than a
470
+ * slot name may be, with a doubled or trailing dash, or reading a built-in's variable, as `showcase` would) gives the
471
+ * `sssb-app` (`SSSB_APP_PORT`: a bare `APP_PORT` is a variable many shells already hold for something else).
472
+ * @param {string} slug
473
+ * @returns {{ name: string, default: number }}
474
+ */
475
+ export function firstAppSlot(slug) {
476
+ const variable = `${slug.toUpperCase().replaceAll('-', '_')}_PORT`
477
+ const fits = SLOT_NAME.test(slug) && slug.length <= MAX_SLOT_NAME && !BUILT_IN_PORT_VARIABLES.has(variable)
478
+ return { name: fits ? slug : 'sssb-app', default: FIRST_APP_PORT }
479
+ }
480
+
481
+ /**
482
+ * The app's port slot, renamed where it lives: the starter declares SSSB's built-in `starter` slot in its package.json
483
+ * and nowhere else (its scripts and Playwright config read the declaration: `sssb dev-tick`, `sssb tick`,
484
+ * `originForApp(__dirname)`), so the app takes a slot of its own in that one place. Fails on a template that names the
485
+ * slot anywhere else in its scripts or Playwright configs, which would then bind another app's port.
486
+ * @param {string} appDir
487
+ * @param {Record<string, any>} manifest the app's package.json, changed in place
488
+ * @param {{ name: string, default: number }} port
489
+ */
490
+ function ownPortSlot(appDir, manifest, port) {
491
+ if (manifest.sssb?.port !== 'starter')
492
+ throw new CreateError(
493
+ `the template's package.json declares the port ${JSON.stringify(manifest.sssb?.port)}, not "starter"`,
494
+ )
495
+ manifest.sssb = { ...manifest.sssb, port }
496
+ for (const [script, text] of Object.entries(manifest.scripts ?? {})) {
497
+ // `_` counts as a letter of a word to `\b`, so `STARTER_PORT` would pass it: any `starter` not inside a longer word.
498
+ if (/(?<![a-z])starter(?![a-z])/i.test(String(text)))
499
+ throw new CreateError(`the template's ${script} script names the starter's port slot`)
500
+ }
501
+ for (const file of readdirSync(appDir).filter((entry) => /^playwright.*\.config\.[cm]?[jt]s$/.test(entry))) {
502
+ if (/(?<![a-z])starter(?![a-z])/i.test(readFileSync(path.join(appDir, file), 'utf8')))
503
+ throw new CreateError(`the template's ${file} names the starter's port slot`)
504
+ }
505
+ }
506
+
507
+ /**
508
+ * @typedef {{
509
+ * slug: string,
510
+ * name: string,
511
+ * meta: import('./template.js').TemplateMeta,
512
+ * spec: (pkg: string, manifest: 'app' | 'infra') => string,
513
+ * eslint: string,
514
+ * port: { name: string, default: number },
515
+ * }} AppContext what an app is written with: its identity, the template's meta, what each of its manifests (the
516
+ * app's, its infra's) takes each @sssb package as, the range of ESLint beside the lint fences' plugin, and its port
517
+ * slot of its own (a new workspace's first app's, `firstAppSlot`; one `sssb add-app` chose for an app it adds)
518
+ */
519
+
520
+ /**
521
+ * THE APP: the template's app copied into `appDir` (which must not exist) and renamed where its identity lives. What
522
+ * `generate` writes as a new workspace's first app, and what `addApp` (add-app.js) writes into an existing one.
523
+ * @param {string} appDir
524
+ * @param {AppContext} a
525
+ * @param {string} templateDir
526
+ */
527
+ export function writeApp(appDir, a, templateDir) {
528
+ const { slug, name, meta } = a
529
+ const inApp = (/** @type {string} */ relative) => path.join(appDir, relative)
530
+ copyTemplate(path.join(templateDir, 'app'), appDir)
531
+
532
+ // THE APP'S IDENTITY: its slug (config/app.ts, which everything mechanical derives from), its package names, and
533
+ // its display name in its catalogs and titles. Each edit must find what it replaces exactly once, so a template
534
+ // that moved its identity elsewhere fails here instead of shipping half-renamed.
535
+ const slugLine = /export const APP_SLUG = '([^']+)'/.exec(readFileSync(inApp('config/app.ts'), 'utf8'))
536
+ if (!slugLine?.[1]) throw new CreateError("the template's config/app.ts declares no APP_SLUG")
537
+ const oldSlug = slugLine[1]
538
+ const oldName = readJson(inApp('messages/en.json'))?.welcome?.appName
539
+ if (typeof oldName !== 'string') throw new CreateError("the template's messages/en.json has no welcome.appName")
540
+ replaceOnce(inApp('config/app.ts'), `export const APP_SLUG = '${oldSlug}'`, `export const APP_SLUG = '${slug}'`)
541
+ replaceOnce(inApp('config/app.ts'), `\`${oldSlug}_session\``, `\`${slug}_session\``)
542
+ for (const locale of ['en', 'es']) {
543
+ for (const key of ['appName', 'title'])
544
+ replaceOnce(
545
+ inApp(`messages/${locale}.json`),
546
+ `"${key}": ${JSON.stringify(oldName)}`,
547
+ `"${key}": ${JSON.stringify(name)}`,
548
+ )
549
+ }
550
+ replaceOnce(inApp('src/app/[locale]/layout.tsx'), `title: ${tsString(oldName)}`, `title: ${tsString(name)}`)
551
+ replaceOnce(inApp('src/demo-static/index.html'), `<title>${oldName} `, `<title>${htmlText(name)} `)
552
+ // Prettier wraps an HTML line past the print width, so the title line must fit (displayName caps the name; `&`
553
+ // grows as it is escaped).
554
+ const titleLine = readFileSync(inApp('src/demo-static/index.html'), 'utf8')
555
+ .split('\n')
556
+ .find((line) => line.includes('<title>'))
557
+ if (titleLine && columns(titleLine) > 120)
558
+ throw new CreateError(`--name "${name}" is too long for the static demo's <title> line: shorten it`)
559
+
560
+ // The app's manifest: its name, the @sssb packages it installs, the seam linked as a package of the app's own
561
+ // (ADR-0014 part 1), and the lint fences' plugin and ESLint beside it. No `license`: the packages are private, and
562
+ // which licence the workspace takes (a LICENSE at its root) is the adopter's to choose, not the starter's to claim.
563
+ const manifest = readJson(inApp('package.json'))
564
+ manifest.name = slug
565
+ delete manifest.license
566
+ manifest.description = `${name}: the app.`
567
+ pinSssb(manifest, (pkg) => a.spec(pkg, 'app'))
568
+ manifest.dependencies = sorted({ ...manifest.dependencies, [SEAM]: `workspace:${seamPackage(slug)}@*` })
569
+ manifest.devDependencies = sorted({
570
+ ...manifest.devDependencies,
571
+ '@sssb/eslint-plugin': a.spec('eslint-plugin', 'app'),
572
+ eslint: a.eslint,
573
+ })
574
+ ownPortSlot(appDir, manifest, a.port)
575
+ writeFileSync(inApp('package.json'), packageJson(manifest))
576
+ const budget = /sssb check-demo-size (\d+)/.exec(manifest.scripts?.['check:demo-size'] ?? '')?.[1]
577
+ if (!budget) throw new CreateError("the template's package.json has no `sssb check-demo-size <bytes>` script")
578
+
579
+ const infra = readJson(inApp('infra/package.json'))
580
+ infra.name = `${slug}-infra`
581
+ delete infra.license
582
+ pinSssb(infra, (pkg) => a.spec(pkg, 'infra'))
583
+ writeFileSync(inApp('infra/package.json'), packageJson(infra))
584
+
585
+ // The seam package (ADR-0014 part 1, option C): the app's src/app-config, a workspace package of the app's own name
586
+ // that the app takes under the name the framework imports (`@sssb/app-config`: `workspace:<slug>-app-config@*`),
587
+ // with an export for every module the framework imports. A workspace package, not a `link:`, because pnpm's
588
+ // partial installs for the app (`add <pkg>`, `remove`, `update <pkg>`) drop a `link:` dependency as the provider of
589
+ // @sssb/kit's peer (the 2026-11-18 addendum to ADR-0014). It takes the app's module `type`, because a nested package.json resets it for everything
590
+ // below it.
591
+ const seamDir = inApp('src/app-config')
592
+ /** @type {Record<string, unknown>} */
593
+ const seam = { name: seamPackage(slug), private: true }
594
+ if (manifest.type) seam['type'] = manifest.type
595
+ seam['exports'] = seamExports(seamDir, meta.seamSpecifiers)
596
+ writeFileSync(path.join(seamDir, 'package.json'), packageJson(seam))
597
+
598
+ // The app's tsconfig, on @sssb/tools' base: in SSSB's repository the starter's also sends @sssb/kit and the seam to
599
+ // source and compiles the framework's own tree (it is the framework's falsifier there). Here resolution goes
600
+ // through the installed packages and the seam link, so only the app's own `@/` alias stays.
601
+ const tsconfig = readJson(inApp('tsconfig.json'))
602
+ if (tsconfig.extends !== '@sssb/tools/tsconfig.base.json')
603
+ throw new CreateError(`the template's tsconfig.json extends ${tsconfig.extends}, not @sssb/tools' base`)
604
+ const own = (/** @type {string} */ entry) => !entry.startsWith('../')
605
+ tsconfig.compilerOptions.paths = { '@/*': tsconfig.compilerOptions.paths['@/*'] }
606
+ tsconfig.include = tsconfig.include.filter(own)
607
+ tsconfig.exclude = tsconfig.exclude.filter(own)
608
+ writeFileSync(inApp('tsconfig.json'), formatJson(tsconfig))
609
+
610
+ writeFileSync(inApp('eslint.config.mjs'), files.APP_ESLINT)
611
+ writeFileSync(inApp('DEMO-SIZE.md'), files.demoSizeMd(Number(budget)))
612
+ }
@@ -38,6 +38,21 @@ export const params = {
38
38
  // the RDS Data API from a Lambda outside any VPC, with no NAT (ADR-0002, addendum 2026-11-16).
39
39
  transport: 'pg' as 'pg' | 'data-api',
40
40
  },
41
+ ports: {
42
+ // Which of SSSB's optional ports this app uses in a deployment; infra/ (SssbApp) sets LLM_PROVIDER,
43
+ // EMAIL_PROVIDER, INBOUND_EMAIL_PROVIDER and JOBS_RUNNER from it. `none` leaves the port absent: real mode
44
+ // requires none of its settings (and its cutover row does not apply), and a call through it fails naming the
45
+ // switch. Never fill an unused port's settings with placeholder values instead.
46
+ // No model calls: set 'anthropic' when the app adds one (cutover: llm-key)
47
+ llm: 'none' as 'anthropic' | 'none',
48
+ // cutover: email-outbound — invitations, notifications, digests
49
+ email: 'mailgun' as 'mailgun' | 'none',
50
+ // No inbound email route: set 'mailgun' when the app adds /api/webhooks/email (cutover: email-inbound)
51
+ inboundEmail: 'none' as 'mailgun' | 'none',
52
+ // Each job's handler runs in the server, within its time limit, so no CodeBuild project is needed; 'codebuild'
53
+ // (cutover: job-runner) runs each job as a build instead, completed through a jobs webhook route
54
+ jobs: 'in-process' as 'codebuild' | 'in-process' | 'none',
55
+ },
41
56
  clerk: {
42
57
  // cutover: auth-dev (development instance), auth-prod (production instance)
43
58
  publishableKeyName: 'PLACEHOLDER_CLERK_PUBLISHABLE_KEY_NAME',
@@ -18,6 +18,12 @@ its own there.
18
18
 
19
19
  - `pnpm synth` in this directory is the verification bar: green, offline, zero credentials
20
20
  (environment-agnostic stack, no lookups). CI runs it for every app.
21
+ - **Region.** The distribution runs a Lambda@Edge function on each request to the server (it adds the body's hash a
22
+ `POST` needs to reach the Function URL), and Lambda@Edge lives in us-east-1. While the stack is
23
+ environment-agnostic it deploys to us-east-1 only: elsewhere the deploy fails after the database is created, and a
24
+ production stack's retained database and buckets may outlive the rollback. Give the stack an explicit `env` (account
25
+ and region) before deploying anywhere else: the construct then puts that function in a us-east-1 stack of its own,
26
+ with this stack's tags, so bootstrap us-east-1 too and deploy by naming this stack (or with `--all`).
21
27
  - **Nothing here deploys until** (see `docs/cutover-checklist.md`): `cloud-accounts` fills
22
28
  `../config/params.ts` · `recurring-cost` — Aurora, the NAT gateway (on the `pg` shape), and CloudFront need
23
29
  explicit approval. Not a checklist row, but do it first: if your organisation ships its own CDK construct
@@ -71,7 +77,8 @@ the database's security group admits nothing.
71
77
  because the deploy pipeline is the piece most tied to an organisation's accounts and approval gates.
72
78
  The shape this stack assumes: a pipeline that uploads the standalone build zip the `Server` function
73
79
  expects (the construct's placeholder asset is a `run.sh` that execs `node server.js`) and invokes the
74
- `Migrator` before shifting traffic. Cutover row `deploy-pipeline` is where that gets built.
80
+ `Migrator` before shifting traffic. The construct sets the server's `HOSTNAME` to `0.0.0.0`: a `run.sh` that sets
81
+ another value breaks requests through the auth provider's proxy, so leave it out of yours. Cutover row `deploy-pipeline` is where that gets built.
75
82
 
76
83
  Nothing in this directory may depend on app source beyond `config/app.ts` and `config/params.ts`, which is
77
84
  what makes moving it mechanical. `pnpm typecheck` covers it, through the app's own `typecheck` (`tsc --noEmit -p infra`,
@@ -15,6 +15,7 @@
15
15
  "empty": "No items in this team yet.",
16
16
  "addLabel": "New item",
17
17
  "addButton": "Add item",
18
- "readOnlyHint": "You have read-only access to items in this team."
18
+ "readOnlyHint": "You have read-only access to items in this team.",
19
+ "loadMore": "Show older items"
19
20
  }
20
21
  }
@@ -15,6 +15,7 @@
15
15
  "empty": "Aún no hay elementos en este equipo.",
16
16
  "addLabel": "Nuevo elemento",
17
17
  "addButton": "Añadir elemento",
18
- "readOnlyHint": "Tienes acceso de solo lectura a los elementos de este equipo."
18
+ "readOnlyHint": "Tienes acceso de solo lectura a los elementos de este equipo.",
19
+ "loadMore": "Ver elementos anteriores"
19
20
  }
20
21
  }
@@ -5,8 +5,8 @@
5
5
  "license": "MIT",
6
6
  "description": "The starter app: the minimum an adopter keeps — one entity, one card, and an otherwise empty seam (ADR-0007, ADR-0012).",
7
7
  "scripts": {
8
- "dev": "NEXT_TELEMETRY_DISABLED=1 APP_MODE=simulated sssb dev-tick starter -- next dev --port \"$(sssb port)\"",
9
- "tick": "sssb tick starter",
8
+ "dev": "NEXT_TELEMETRY_DISABLED=1 APP_MODE=simulated sssb dev-tick -- next dev --port \"$(sssb port)\"",
9
+ "tick": "sssb tick",
10
10
  "build": "NEXT_TELEMETRY_DISABLED=1 next build",
11
11
  "start": "next start --port \"$(sssb port)\"",
12
12
  "typecheck": "next typegen && tsc --noEmit && tsc --noEmit -p infra",
@@ -1,5 +1,5 @@
1
1
  import { defineConfig, devices } from '@playwright/test'
2
- import { originFor } from '@sssb/tools/ports'
2
+ import { originForApp } from '@sssb/tools/ports'
3
3
  import { assertNoLiveDevTicker } from '@sssb/tools/ticker-marker'
4
4
 
5
5
  // A dev server started with `DEV_TICK_SECONDS` set would be ADOPTED by `reuseExistingServer` below and tick under the
@@ -15,20 +15,20 @@ assertNoLiveDevTicker()
15
15
  * guarantee ACROSS checkouts: a linked worktree gets its own pair, so two agent sessions running e2e
16
16
  * at once no longer collide either. `pnpm dev` derives the identical number from the same function.
17
17
  */
18
- const BASE_URL = originFor('starter')
18
+ const BASE_URL = originForApp(__dirname)
19
19
 
20
20
  export default defineConfig({
21
21
  testDir: './tests/e2e',
22
22
  fullyParallel: true,
23
- // This app's whole suite is ONE spec, so it always starts against a cold dev server and pays a
24
- // full Next compile on every route it touches — sign-in, dashboard, the items route. The default
23
+ // This app's whole suite is two short specs, so the first always starts against a cold dev server and pays a
24
+ // full Next compile on every route it touches — sign-in, dashboard, the items route, the Simulator's. The default
25
25
  // 30s is marginal for that (it timed out on the first run and passed on retry), and there is no
26
26
  // warm-up pass to inherit, so the budget is raised rather than left to flake.
27
27
  timeout: 60_000,
28
28
  expect: { timeout: 15_000 },
29
29
  forbidOnly: !!process.env['CI'],
30
30
  retries: process.env['CI'] ? 2 : 1,
31
- // One worker, on CI too — this app's whole suite is one spec, so parallelism buys nothing here,
31
+ // One worker, on CI too — this app's whole suite is two short specs, so parallelism buys little here,
32
32
  // and more workers against one shared world (one `.data` behind one dev server) cost reliability rather than
33
33
  // saving time.
34
34
  workers: 1,
@@ -4,22 +4,46 @@ import { useEffect, useState } from 'react'
4
4
  import { DashboardScreen, type DashboardUser } from '@/components/dashboard-screen'
5
5
  import { ItemsCard, type Item } from '@/components/items-card'
6
6
 
7
+ /** One page of items; no cursor is the first page. Null when the request failed, so a flaky network is a page that does not grow, not an unhandled rejection. */
8
+ async function fetchItemsPage(after: string | null): Promise<{ items: Item[]; nextCursor: string | null } | null> {
9
+ try {
10
+ const response = await fetch(after === null ? '/api/items' : `/api/items?cursor=${encodeURIComponent(after)}`)
11
+ return response.ok ? ((await response.json()) as { items: Item[]; nextCursor: string | null }) : null
12
+ } catch {
13
+ return null
14
+ }
15
+ }
16
+
7
17
  export function DashboardGlue({ user, canCreateItem }: { user: DashboardUser; canCreateItem: boolean }) {
8
18
  const [items, setItems] = useState<Item[]>([])
19
+ // The cursor for the NEXT page, or null at the end. The glue owns fetching; the card stays a plain list.
20
+ const [cursor, setCursor] = useState<string | null>(null)
9
21
 
10
22
  useEffect(() => {
11
23
  // Sets state only once the response lands — the legitimate "sync with an external system"
12
24
  // case, so the react-hooks set-state-in-effect rule does not fire here.
13
- void fetch('/api/items')
14
- .then((response) => (response.ok ? response.json() : { items: [] }))
15
- .then((data: { items: Item[] }) => setItems(data.items))
25
+ void fetchItemsPage(null).then((page) => {
26
+ if (!page) return
27
+ setItems(page.items)
28
+ setCursor(page.nextCursor)
29
+ })
16
30
  }, [])
17
31
 
32
+ /** "Show older items" APPENDS the next page, so what the reader has scrolled past stays put. */
33
+ async function loadMore() {
34
+ const page = await fetchItemsPage(cursor)
35
+ if (!page) return
36
+ setItems((previous) => [...previous, ...page.items])
37
+ setCursor(page.nextCursor)
38
+ }
39
+
18
40
  return (
19
41
  <DashboardScreen user={user}>
20
42
  <ItemsCard
21
43
  items={items}
22
44
  canCreate={canCreateItem}
45
+ hasMore={cursor !== null}
46
+ onLoadMore={loadMore}
23
47
  onAdd={async (title) => {
24
48
  const response = await fetch('/api/items', {
25
49
  method: 'POST',
@@ -6,12 +6,20 @@ import { hasLocale, NextIntlClientProvider } from 'next-intl'
6
6
  import { setRequestLocale } from 'next-intl/server'
7
7
  import { notFound } from 'next/navigation'
8
8
  import type { ReactNode } from 'react'
9
- import { auth, isDemoMode } from '@sssb/kit/adapters/index'
9
+ import { auth, isDemoMode, isSimulated } from '@sssb/kit/adapters/index'
10
10
  import { DemoBadge } from '@sssb/kit/components/demo-badge'
11
11
  import { routing } from '@sssb/kit/i18n/routing'
12
12
  import { getTenantTheme } from '@sssb/kit/theme'
13
13
  import { tenants } from '@/seed'
14
14
 
15
+ // The Simulator panel, in simulated mode only: a real build never renders it, so no page there loads its client code.
16
+ // Its server side is `src/app/api/simulator/[...path]/route.ts`.
17
+ async function SimulatorChrome({ locale, children }: { locale: string; children: ReactNode }) {
18
+ if (!isSimulated) return children
19
+ const { SimulatorHost } = await import('@sssb/kit/components/simulator/simulator-host')
20
+ return <SimulatorHost locale={locale}>{children}</SimulatorHost>
21
+ }
22
+
15
23
  export const metadata = {
16
24
  title: 'Starter',
17
25
  }
@@ -45,7 +53,7 @@ export default async function LocaleLayout({
45
53
  <body>
46
54
  <NextIntlClientProvider>
47
55
  <MantineProvider theme={theme}>
48
- {children}
56
+ <SimulatorChrome locale={locale}>{children}</SimulatorChrome>
49
57
  {isDemoMode ? <DemoBadge /> : null}
50
58
  </MantineProvider>
51
59
  </NextIntlClientProvider>
@@ -1,30 +1,37 @@
1
1
  import { auth, db } from '@sssb/kit/adapters/index'
2
2
  import { authorize } from '@sssb/kit/authz/authorize'
3
+ import { clampKeysetLimit } from '@sssb/kit/core/keyset'
4
+ import { parseDbKeysetCursor } from '@sssb/kit/db/keyset'
3
5
  import { orgIdForSlug } from '@sssb/kit/db/org-lookup'
4
6
  import { tenantIdForSlug } from '@sssb/kit/db/tenant-lookup'
7
+ import { listItems } from '@/domain/db/items'
5
8
  import { withPortErrors } from '../respond'
6
9
 
7
10
  /**
8
11
  * The app's only product route. Items are tenant-scoped by RLS (the hostile-isolation boundary) AND
9
12
  * filtered to the active org (the team boundary — an app-level WHERE, since org membership is enforced
10
13
  * at the auth port; ADR-0004). Every query runs inside withTenant.
14
+ *
15
+ * GET lists ONE PAGE (`?cursor=<opaque>&limit=<n>`); both parameters are untrusted input. An unreadable
16
+ * cursor is a 400, never a silent first page, and the page size is clamped on the server: the query
17
+ * string may ask, it does not decide. A cursor carries no scope, since the tenant and the org are
18
+ * resolved from the session on every page.
11
19
  */
12
- export async function GET(): Promise<Response> {
20
+ export async function GET(request: Request): Promise<Response> {
13
21
  return withPortErrors(async () => {
14
22
  const user = await auth.requireUser()
23
+ const params = new URL(request.url).searchParams
24
+ const cursor = parseDbKeysetCursor(params.get('cursor'))
25
+ if (cursor.kind === 'invalid') return Response.json({ error: 'invalid-cursor' }, { status: 400 })
15
26
  const tenantId = await tenantIdForSlug(db, user.tenantSlug)
16
27
  if (!tenantId) return Response.json({ error: 'unknown tenant' }, { status: 404 })
17
28
  const orgId = await orgIdForSlug(db, tenantId, user.orgSlug)
18
29
  if (!orgId) return Response.json({ error: 'unknown org' }, { status: 404 })
19
- const items = await db.withTenant(tenantId, (trx) =>
20
- trx
21
- .selectFrom('items')
22
- .select(['id', 'title'])
23
- .where('org_id', '=', orgId)
24
- .orderBy('created_at', 'desc')
25
- .execute(),
26
- )
27
- return Response.json({ items })
30
+ const { items, nextCursor } = await listItems(db, tenantId, orgId, {
31
+ after: cursor.position ?? null,
32
+ limit: clampKeysetLimit(params.get('limit')),
33
+ })
34
+ return Response.json({ items, nextCursor })
28
35
  })
29
36
  }
30
37
 
@@ -0,0 +1,23 @@
1
+ import { isSimulated } from '@sssb/kit/adapters/index'
2
+ import type { SimulatorRouteContext } from '@sssb/kit/server-lib/simulator-api'
3
+
4
+ /**
5
+ * The Simulator panel's server side on this app's own `pnpm dev`: every `/api/simulator/<path>` call the panel makes
6
+ * lands here and is answered by SSSB's `simulatorApi` (People, Mail, and Jobs with the world clock). A route file of
7
+ * this app's own beside it, `api/simulator/<name>/route.ts`, still wins for its path.
8
+ *
9
+ * Each handler opens with the simulated-mode 404 and loads SSSB's handler only after it, so a real build never loads
10
+ * it. That first line is also the gate the authorization scan checks: these handlers are
11
+ * exempt from `authorize(...)` as a simulated-world surface, and only while each one opens with it.
12
+ */
13
+ export async function GET(request: Request, context: SimulatorRouteContext): Promise<Response> {
14
+ if (!isSimulated) return new Response(null, { status: 404 })
15
+ const { simulatorApi } = await import('@sssb/kit/server-lib/simulator-api')
16
+ return simulatorApi(request, context)
17
+ }
18
+
19
+ export async function POST(request: Request, context: SimulatorRouteContext): Promise<Response> {
20
+ if (!isSimulated) return new Response(null, { status: 404 })
21
+ const { simulatorApi } = await import('@sssb/kit/server-lib/simulator-api')
22
+ return simulatorApi(request, context)
23
+ }
@@ -2,11 +2,12 @@ import { runScheduledTick } from '@sssb/kit/server-lib/scheduled-tick'
2
2
  import { withWebhookSecret } from '@sssb/kit/service-auth/webhook'
3
3
 
4
4
  /**
5
- * The scheduled-work tick (cutover row `scheduled-tick`). A scheduler POSTs here on a fixed cadence with
6
- * `Authorization: Bearer $WEBHOOK_SECRET`; a request without that secret is an opaque 401 before anything runs.
5
+ * The scheduled-work tick (cutover row `scheduled-tick`). A scheduler POSTs here on a fixed cadence with the shared
6
+ * secret in `x-sssb-webhook-secret` (or `Authorization: Bearer`, which a deployment's CloudFront does not pass on); a
7
+ * request without that secret is an opaque 401 before anything runs.
7
8
  * The body is ignored and the whole job is SSSB's `runScheduledTick`: drain the due schedules and the due webhook
8
- * deliveries. This app has no Simulator routes, so without this route nothing ticks SSSB's scheduler there,
9
- * in a deployment or in `pnpm dev`.
9
+ * deliveries. The Simulator's Jobs tab runs what is due only when asked, so without this route nothing ticks SSSB's
10
+ * scheduler on its own, in a deployment or in `pnpm dev`.
10
11
  *
11
12
  * Authorization is the shared-secret guard, and the handler has to BE it: the authorize() scan exempts a
12
13
  * `webhooks/` handler (a machine caller, not a user session) only if that verb's export is a call to an imported