@fabrika/cli 0.3.2 → 0.4.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/package.json +25 -8
- package/src/app-dev-seed.ts +119 -0
- package/src/app-dev-ui.ts +582 -0
- package/src/app-dev.ts +533 -0
- package/src/connect.ts +249 -0
- package/src/control.ts +106 -22
- package/src/db.ts +296 -0
- package/src/index.ts +140 -11
- package/src/job.ts +81 -0
- package/src/junit.ts +37 -0
package/src/app-dev.ts
ADDED
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
// `fabrika app dev`: a contract application served through its test kit on a loopback port, to click through its
|
|
2
|
+
// screens. The kit is the whole server: production's proxy decision, the stand-in IAM, the real `boot`, the SPAs from
|
|
3
|
+
// their build directories; Postgres is a throwaway schema of the tests' database. A seed module fills it through the
|
|
4
|
+
// endpoints first. A caller picker chooses who the browser is; a cookie keeps the choice, and the kit's own session
|
|
5
|
+
// never leaves the process. Every SPA page gets the dev toolbar, which switches the caller without leaving the page.
|
|
6
|
+
|
|
7
|
+
import { CONTRACT_FILE, IMPLEMENTATION_FILE } from '@fabrika/app/build'
|
|
8
|
+
import { implementationAt } from '@fabrika/app/bun'
|
|
9
|
+
import type { AnyContract } from '@fabrika/app/contract'
|
|
10
|
+
import { BootError, type ContractImplementation } from '@fabrika/app/implement'
|
|
11
|
+
import { type DevKit, devKit, type LabelledTestCaller, type TestCaller } from '@fabrika/app/testing'
|
|
12
|
+
import { TEST_POSTGRES_URL, type TestDatabase, testDatabase } from '@fabrika/db/testing'
|
|
13
|
+
import { PostgresMigrationError } from '@fabrika/platform-node'
|
|
14
|
+
import { MemoryFileObjects } from '@fabrika/platform/testing'
|
|
15
|
+
import { existsSync } from 'node:fs'
|
|
16
|
+
import { join } from 'node:path'
|
|
17
|
+
import { z } from 'zod/v4'
|
|
18
|
+
import { DEFAULT_SEED, importSeed, isLocalPath, NOTHING_SEEDED, parseSeeded, type Seeded, seedPath, SeedProblem } from './app-dev-seed'
|
|
19
|
+
import {
|
|
20
|
+
type Badge,
|
|
21
|
+
type CurrentView,
|
|
22
|
+
type DevView,
|
|
23
|
+
noticePage,
|
|
24
|
+
pickerPage,
|
|
25
|
+
type RoleView,
|
|
26
|
+
stringsOf,
|
|
27
|
+
toolbarScript,
|
|
28
|
+
toolbarState,
|
|
29
|
+
withToolbar,
|
|
30
|
+
} from './app-dev-ui'
|
|
31
|
+
|
|
32
|
+
export const APP_DEV_USAGE = `fabrika app dev — the application on a local port, to click through its screens
|
|
33
|
+
|
|
34
|
+
Usage:
|
|
35
|
+
fabrika app dev [--port=<n>] [--host=<loopback address>] [--seed=<module>]
|
|
36
|
+
|
|
37
|
+
Run from the application root. It serves ${IMPLEMENTATION_FILE} through its test kit: the production proxy decision,
|
|
38
|
+
the kit's stand-in IAM, each SPA from its built directory (run the SPA build first; an unbuilt one is an empty page),
|
|
39
|
+
and a throwaway schema of the database in ${TEST_POSTGRES_URL}, migrated from db/migrations/ and dropped on exit.
|
|
40
|
+
The seed module (--seed, or ${DEFAULT_SEED} when it exists) default-exports a DevSeed of @fabrika/app/testing: it
|
|
41
|
+
receives the kit, writes through the endpoints, and answers the personas, link pages and scope values to offer.
|
|
42
|
+
Pick who the browser is at /__fabrika/dev; every SPA page shows a toolbar that switches the caller and lists the
|
|
43
|
+
mail IAM sent. The application's own variables come from the environment. It listens on 127.0.0.1 (or ::1,
|
|
44
|
+
localhost) only, port 3000 unless --port says otherwise (0 picks a free one), and prints the address it serves.
|
|
45
|
+
`
|
|
46
|
+
|
|
47
|
+
const LOOPBACK: ReadonlySet<string> = new Set(['127.0.0.1', '::1', 'localhost'])
|
|
48
|
+
const LOOPBACK_HOSTNAMES: ReadonlySet<string> = new Set(['127.0.0.1', '[::1]', 'localhost'])
|
|
49
|
+
const PICKER_PATH = '/__fabrika/dev'
|
|
50
|
+
const CHOOSE_PATH = '/__fabrika/dev/as'
|
|
51
|
+
const ACCEPT_PATH = '/__fabrika/dev/accept'
|
|
52
|
+
const STATE_PATH = '/__fabrika/dev/state'
|
|
53
|
+
const TOOLBAR_PATH = '/__fabrika/dev/toolbar.js'
|
|
54
|
+
const CHOICE_COOKIE = 'fabrika-dev-as'
|
|
55
|
+
const MAX_SCOPE_VALUE = 200
|
|
56
|
+
|
|
57
|
+
/** What `app dev`'s own pages answer with: nothing runs there but the toolbar, which is a separate response. */
|
|
58
|
+
const PAGE_HEADERS = {
|
|
59
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
60
|
+
'Cache-Control': 'no-store',
|
|
61
|
+
'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
|
|
62
|
+
'X-Content-Type-Options': 'nosniff',
|
|
63
|
+
'Referrer-Policy': 'no-referrer',
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A refusal of `app dev` itself, whose message names nothing of the environment. */
|
|
67
|
+
export class AppDevError extends Error {
|
|
68
|
+
override readonly name = 'AppDevError'
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* What of a startup failure reaches the terminal: the message of `app dev`'s own refusal, of the seed's answer, of the
|
|
73
|
+
* framework's boot and of the migration runner, which name no value of the environment; anything else (an application
|
|
74
|
+
* module, the seed's own code, a driver, a dependency `deps` built) may carry a credential, so it is a fixed code.
|
|
75
|
+
*/
|
|
76
|
+
export function startupFailure(error: unknown): Error {
|
|
77
|
+
if (error instanceof AppDevError || error instanceof SeedProblem || error instanceof BootError || error instanceof PostgresMigrationError) {
|
|
78
|
+
return new Error(error.message)
|
|
79
|
+
}
|
|
80
|
+
return new Error('app dev could not start: start_failed (the error is withheld: it may contain a credential)')
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface AppDevOptions {
|
|
84
|
+
/** The application root. */
|
|
85
|
+
readonly root: string
|
|
86
|
+
readonly port: number
|
|
87
|
+
readonly host: string
|
|
88
|
+
/** The environment: the test database URL, and the application's own variables. */
|
|
89
|
+
readonly env: Readonly<Record<string, string | undefined>>
|
|
90
|
+
/** The seed module's absolute path, or `null` to serve the empty application. */
|
|
91
|
+
readonly seed: string | null
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface AppDevServer {
|
|
95
|
+
/** The address it serves, `http://<host>:<port>/`. */
|
|
96
|
+
readonly url: string
|
|
97
|
+
/** How many personas and link pages the seed offered. */
|
|
98
|
+
readonly seeded: { readonly personas: number; readonly links: number }
|
|
99
|
+
/** Stops serving and drops the throwaway schema. */
|
|
100
|
+
stop(): Promise<void>
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Who the browser is: a persona of the seed, a role of the vocabulary in a scope value, or who accepted an invitation. */
|
|
104
|
+
const Choice = z.union([
|
|
105
|
+
z.strictObject({ persona: z.string().min(1).max(200) }),
|
|
106
|
+
z.strictObject({ role: z.string().min(1), value: z.string().min(1).max(MAX_SCOPE_VALUE).nullable() }),
|
|
107
|
+
z.strictObject({ invitation: z.string().min(1).max(200) }),
|
|
108
|
+
])
|
|
109
|
+
type Choice = z.infer<typeof Choice>
|
|
110
|
+
|
|
111
|
+
/** The proxy's sign-in answer to a fetch, whose `loginUrl` names the kit's IAM. */
|
|
112
|
+
const LoginRequired = z.object({ error: z.looseObject({ loginUrl: z.string() }) })
|
|
113
|
+
|
|
114
|
+
export interface AppDevArgs {
|
|
115
|
+
readonly port: number
|
|
116
|
+
readonly host: string
|
|
117
|
+
readonly seed: string | null
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function parseAppDevArgs(argv: readonly string[]): AppDevArgs {
|
|
121
|
+
let port = 3000
|
|
122
|
+
let host = '127.0.0.1'
|
|
123
|
+
let seed: string | null = null
|
|
124
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
125
|
+
const arg = argv[index] ?? ''
|
|
126
|
+
if (arg.startsWith('--port=')) {
|
|
127
|
+
const parsed = Number(arg.slice('--port='.length))
|
|
128
|
+
if (!Number.isInteger(parsed) || parsed < 0 || parsed > 65535) throw new Error(`app dev: --port is 0 to 65535, not ${arg.slice(7)}`)
|
|
129
|
+
port = parsed
|
|
130
|
+
} else if (arg.startsWith('--host=')) {
|
|
131
|
+
host = arg.slice('--host='.length)
|
|
132
|
+
} else if (arg.startsWith('--seed=') || arg === '--seed') {
|
|
133
|
+
const value = arg === '--seed' ? argv[index += 1] : arg.slice('--seed='.length)
|
|
134
|
+
if (value === undefined || value === '') throw new Error(`app dev: --seed names a module, e.g. --seed=${DEFAULT_SEED}`)
|
|
135
|
+
seed = value
|
|
136
|
+
} else {
|
|
137
|
+
throw new Error(`app dev takes no argument ${arg}\n\n${APP_DEV_USAGE}`)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (!LOOPBACK.has(host)) {
|
|
141
|
+
throw new Error(`app dev serves this machine only: --host is 127.0.0.1, ::1 or localhost, not ${host}`)
|
|
142
|
+
}
|
|
143
|
+
return { port, host, seed }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The application's own variables: the environment without the framework's and the tests' `FABRIKA_*` names. */
|
|
147
|
+
function applicationVariables(env: Readonly<Record<string, string | undefined>>): Record<string, string> {
|
|
148
|
+
return Object.fromEntries(
|
|
149
|
+
Object.entries(env).flatMap(([name, value]) => (name.startsWith('FABRIKA_') || value === undefined ? [] : [[name, value]])),
|
|
150
|
+
)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function cookieOf(request: Request, name: string): string | undefined {
|
|
154
|
+
for (const part of (request.headers.get('Cookie') ?? '').split(';')) {
|
|
155
|
+
const [key, ...value] = part.trim().split('=')
|
|
156
|
+
if (key === name) return value.join('=')
|
|
157
|
+
}
|
|
158
|
+
return undefined
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The request's cookies without the picker's own, which the application never sees. */
|
|
162
|
+
function withoutChoice(cookies: string | null): string | null {
|
|
163
|
+
if (cookies === null) return null
|
|
164
|
+
const kept = cookies.split(';').map((part) => part.trim()).filter((part) => part !== '' && !part.startsWith(`${CHOICE_COOKIE}=`))
|
|
165
|
+
return kept.length === 0 ? null : kept.join('; ')
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The request is addressed to this server by a loopback name: a page of another site rebound to 127.0.0.1 is not. */
|
|
169
|
+
function addressedHere(request: Request, port: number): boolean {
|
|
170
|
+
const host = request.headers.get('Host')
|
|
171
|
+
if (host === null) return false
|
|
172
|
+
const at = host.lastIndexOf(':')
|
|
173
|
+
return at > 0 && LOOPBACK_HOSTNAMES.has(host.slice(0, at)) && host.slice(at + 1) === String(port)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const plain = (status: number, text: string): Response =>
|
|
177
|
+
new Response(`${text}\n`, { status, headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' } })
|
|
178
|
+
|
|
179
|
+
/** Serves `app` through its test kit on a loopback port until `stop`. */
|
|
180
|
+
export async function startAppDev(app: ContractImplementation<AnyContract>, options: AppDevOptions): Promise<AppDevServer> {
|
|
181
|
+
if (!LOOPBACK.has(options.host)) throw new AppDevError(`app dev serves this machine only, not ${options.host}`)
|
|
182
|
+
let postgres: TestDatabase | null = null
|
|
183
|
+
if (app.database !== null) {
|
|
184
|
+
if ((options.env[TEST_POSTGRES_URL] ?? '') === '') {
|
|
185
|
+
throw new AppDevError(`app dev needs ${TEST_POSTGRES_URL}, the database the tests use: it migrates a throwaway schema there`)
|
|
186
|
+
}
|
|
187
|
+
postgres = await testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
return await serveThroughKit(app, options, postgres)
|
|
191
|
+
} catch (error) {
|
|
192
|
+
// The schema and its roles exist from here on: a failed start drops them as a stop does.
|
|
193
|
+
await postgres?.close()
|
|
194
|
+
throw error
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** The seed's answer; its own code may throw anything, which is withheld, and its answer's problems are named. */
|
|
199
|
+
async function runSeed(dev: DevKit<AnyContract>, path: string | null): Promise<Seeded> {
|
|
200
|
+
if (path === null) return NOTHING_SEEDED
|
|
201
|
+
let answer: unknown
|
|
202
|
+
try {
|
|
203
|
+
const seed = await importSeed(path)
|
|
204
|
+
answer = await seed(dev.kit)
|
|
205
|
+
} catch (error) {
|
|
206
|
+
if (error instanceof SeedProblem) throw error
|
|
207
|
+
throw new AppDevError('app dev could not seed: seed_failed (the error is withheld: it may contain a credential; run the same calls in a test)')
|
|
208
|
+
}
|
|
209
|
+
return parseSeeded(dev, answer)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The server over the kit of `app`, on `postgres` when it has a data layer; its `stop` also drops the schema. */
|
|
213
|
+
async function serveThroughKit(
|
|
214
|
+
app: ContractImplementation<AnyContract>,
|
|
215
|
+
options: AppDevOptions,
|
|
216
|
+
postgres: TestDatabase | null,
|
|
217
|
+
): Promise<AppDevServer> {
|
|
218
|
+
const contract = app.contract
|
|
219
|
+
const vocabulary = contract.vocabulary
|
|
220
|
+
const hasFiles = Object.keys(contract.surface.files ?? {}).length > 0
|
|
221
|
+
const dev = devKit(app, {
|
|
222
|
+
root: options.root,
|
|
223
|
+
env: applicationVariables(options.env),
|
|
224
|
+
...(postgres === null ? {} : { database: postgres.database }),
|
|
225
|
+
...(hasFiles ? { files: new MemoryFileObjects() } : {}),
|
|
226
|
+
})
|
|
227
|
+
const kit = dev.kit
|
|
228
|
+
const seeded = await runSeed(dev, options.seed)
|
|
229
|
+
const text = stringsOf(vocabulary.locale ?? 'en')
|
|
230
|
+
const title = vocabulary.displayName ?? vocabulary.app
|
|
231
|
+
const mounts = Object.values(kit.artifact.mounts)
|
|
232
|
+
const firstSpa = mounts.find((mount) => mount.kind === 'spa')?.prefix ?? '/'
|
|
233
|
+
const pagePrefixes = mounts.flatMap((mount) => (mount.kind === 'spa' || mount.kind === 'link' ? [mount.prefix] : []))
|
|
234
|
+
const callers = new Map<string, LabelledTestCaller>()
|
|
235
|
+
const invitees = new Map<string, LabelledTestCaller>()
|
|
236
|
+
const toolbar = toolbarScript(STATE_PATH)
|
|
237
|
+
|
|
238
|
+
/** A path of this origin to go on to; anything else is the first SPA. */
|
|
239
|
+
const nextOf = (next: string | null): string => (next !== null && isLocalPath(next) ? next : firstSpa)
|
|
240
|
+
|
|
241
|
+
/** The caller a role choice names, made once and kept, so its membership changes last; `null` when it is no grant. */
|
|
242
|
+
const roleCaller = (role: string, value: string | null): LabelledTestCaller | null => {
|
|
243
|
+
const declared = Object.hasOwn(vocabulary.roles, role) ? vocabulary.roles[role] : undefined
|
|
244
|
+
if (declared === undefined || (declared.member !== undefined) !== (value !== null)) return null
|
|
245
|
+
const key = JSON.stringify([role, value])
|
|
246
|
+
const known = callers.get(key)
|
|
247
|
+
if (known !== undefined) return known
|
|
248
|
+
const grant = declared.member === undefined || value === null ? { role } : { role, scope: { type: declared.member.scope, value } }
|
|
249
|
+
const made = kit.testCaller([grant], { label: `${role}${value === null ? '' : `@${value}`}` })
|
|
250
|
+
callers.set(key, made)
|
|
251
|
+
return made
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const callerOf = (choice: Choice): LabelledTestCaller | null => {
|
|
255
|
+
if ('persona' in choice) return seeded.personas.find((persona) => persona.name === choice.persona)?.caller ?? null
|
|
256
|
+
if ('invitation' in choice) return invitees.get(choice.invitation) ?? null
|
|
257
|
+
return roleCaller(choice.role, choice.value)
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const choiceOf = (request: Request): Choice | null => {
|
|
261
|
+
const raw = cookieOf(request, CHOICE_COOKIE)
|
|
262
|
+
if (raw === undefined) return null
|
|
263
|
+
try {
|
|
264
|
+
const parsed = Choice.safeParse(JSON.parse(decodeURIComponent(raw)))
|
|
265
|
+
return parsed.success ? parsed.data : null
|
|
266
|
+
} catch {
|
|
267
|
+
return null
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const scopeLabel = (type: string, value: string): string => seeded.scopes.get(type)?.find((known) => known.value === value)?.label ?? value
|
|
272
|
+
|
|
273
|
+
const externalBadge: Badge = { text: text.external, tone: 'external' }
|
|
274
|
+
const badgesOf = (caller: TestCaller): Badge[] => [
|
|
275
|
+
...dev.membershipsOf(caller).map((held): Badge => ({
|
|
276
|
+
text: held.scope === null ? held.role : `${held.role} · ${scopeLabel(held.scope.type, held.scope.value)}`,
|
|
277
|
+
tone: 'role',
|
|
278
|
+
})),
|
|
279
|
+
...(caller.affiliation === 'external' ? [externalBadge] : []),
|
|
280
|
+
]
|
|
281
|
+
|
|
282
|
+
const currentOf = (choice: Choice | null): CurrentView | null => {
|
|
283
|
+
const caller = choice === null ? null : callerOf(choice)
|
|
284
|
+
if (choice === null || caller === null) return null
|
|
285
|
+
if ('persona' in choice) return { name: choice.persona, badges: badgesOf(caller) }
|
|
286
|
+
return { name: caller.email ?? caller.label, badges: badgesOf(caller) }
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const chooseHref = (params: Record<string, string>, next: string): string => `${CHOOSE_PATH}?${new URLSearchParams({ ...params, next }).toString()}`
|
|
290
|
+
|
|
291
|
+
/** The values a membership role is offered in: the seed's, then those its personas hold. */
|
|
292
|
+
const valuesOf = (dimension: string): { readonly value: string; readonly label: string }[] => {
|
|
293
|
+
const values = [...(seeded.scopes.get(dimension) ?? [])]
|
|
294
|
+
for (const persona of seeded.personas) {
|
|
295
|
+
for (const held of dev.membershipsOf(persona.caller)) {
|
|
296
|
+
if (held.scope?.type === dimension && !values.some((known) => known.value === held.scope?.value)) {
|
|
297
|
+
values.push({ value: held.scope.value, label: held.scope.value })
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return values
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const viewOf = (choice: Choice | null, next: string): DevView => ({
|
|
305
|
+
locale: vocabulary.locale ?? 'en',
|
|
306
|
+
title,
|
|
307
|
+
current: currentOf(choice),
|
|
308
|
+
personas: seeded.personas.map((persona) => ({
|
|
309
|
+
name: persona.name,
|
|
310
|
+
description: persona.description,
|
|
311
|
+
email: persona.caller.email,
|
|
312
|
+
badges: badgesOf(persona.caller),
|
|
313
|
+
href: chooseHref({ persona: persona.name }, next),
|
|
314
|
+
current: choice !== null && 'persona' in choice && choice.persona === persona.name,
|
|
315
|
+
})),
|
|
316
|
+
roles: Object.entries(vocabulary.roles).map(([role, declared]): RoleView => ({
|
|
317
|
+
role,
|
|
318
|
+
grants: declared.grants,
|
|
319
|
+
external: declared.external === true,
|
|
320
|
+
choose: declared.member === undefined
|
|
321
|
+
? { kind: 'app', href: chooseHref({ role }, next) }
|
|
322
|
+
: { kind: 'member', action: CHOOSE_PATH, next, dimension: declared.member.scope, values: valuesOf(declared.member.scope) },
|
|
323
|
+
})),
|
|
324
|
+
anonymousHref: chooseHref({ anonymous: '1' }, next),
|
|
325
|
+
links: seeded.links.map((link) => ({ title: link.title, description: link.description, href: link.url })),
|
|
326
|
+
mail: dev.invitations().map((invitation) => ({
|
|
327
|
+
to: invitation.email,
|
|
328
|
+
subject: text.invitation(invitation.role, scopeLabel(invitation.scope.type, invitation.scope.value)),
|
|
329
|
+
status: invitation.status,
|
|
330
|
+
action: invitation.status === 'open'
|
|
331
|
+
? { label: text.accept, href: `${ACCEPT_PATH}?${new URLSearchParams({ invitation: invitation.id, next }).toString()}` }
|
|
332
|
+
: invitation.status === 'accepted' && invitees.has(invitation.id)
|
|
333
|
+
? { label: text.continueAs, href: chooseHref({ invitation: invitation.id }, next) }
|
|
334
|
+
: null,
|
|
335
|
+
})),
|
|
336
|
+
pickerHref: `${PICKER_PATH}?${new URLSearchParams({ next }).toString()}`,
|
|
337
|
+
})
|
|
338
|
+
|
|
339
|
+
const choosing = (choice: Choice | null, next: string): Response => {
|
|
340
|
+
const cookie = choice === null
|
|
341
|
+
? `${CHOICE_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`
|
|
342
|
+
: `${CHOICE_COOKIE}=${encodeURIComponent(JSON.stringify(choice))}; Path=/; HttpOnly; SameSite=Lax`
|
|
343
|
+
return new Response(null, { status: 303, headers: { Location: next, 'Set-Cookie': cookie, 'Cache-Control': 'no-store' } })
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const choose = (url: URL): Response => {
|
|
347
|
+
const next = nextOf(url.searchParams.get('next'))
|
|
348
|
+
const persona = url.searchParams.get('persona')
|
|
349
|
+
const invitation = url.searchParams.get('invitation')
|
|
350
|
+
if (url.searchParams.has('anonymous')) return choosing(null, next)
|
|
351
|
+
if (persona !== null) {
|
|
352
|
+
const choice = Choice.safeParse({ persona })
|
|
353
|
+
if (!choice.success || callerOf(choice.data) === null) return plain(400, 'no such persona: the seed answered none by that name')
|
|
354
|
+
return choosing(choice.data, next)
|
|
355
|
+
}
|
|
356
|
+
if (invitation !== null) {
|
|
357
|
+
const choice = Choice.safeParse({ invitation })
|
|
358
|
+
if (!choice.success || callerOf(choice.data) === null) return plain(400, 'no such invitee: nobody accepted that invitation here')
|
|
359
|
+
return choosing(choice.data, next)
|
|
360
|
+
}
|
|
361
|
+
const role = url.searchParams.get('role') ?? ''
|
|
362
|
+
const scope = (url.searchParams.get('scope') ?? '').trim()
|
|
363
|
+
const choice = Choice.safeParse({ role, value: scope === '' ? null : scope })
|
|
364
|
+
if (!choice.success || callerOf(choice.data) === null) {
|
|
365
|
+
return plain(400, 'no such caller: a role of the vocabulary, with a scope value exactly when it is a membership role')
|
|
366
|
+
}
|
|
367
|
+
return choosing(choice.data, next)
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** The addressee of an open invitation accepts it, as IAM's onboarding does, and the browser is that person from now on. */
|
|
371
|
+
const accept = (request: Request, url: URL): Response => {
|
|
372
|
+
const next = nextOf(url.searchParams.get('next'))
|
|
373
|
+
const id = url.searchParams.get('invitation') ?? ''
|
|
374
|
+
try {
|
|
375
|
+
invitees.set(id, kit.acceptInvitation(id))
|
|
376
|
+
} catch (error) {
|
|
377
|
+
const view = viewOf(choiceOf(request), next)
|
|
378
|
+
// The kit's refusal names the invitation and the role, never a credential.
|
|
379
|
+
return new Response(noticePage(view, text.accept, error instanceof Error ? error.message : 'not_allowed'), { status: 409, headers: PAGE_HEADERS })
|
|
380
|
+
}
|
|
381
|
+
return choosing({ invitation: id }, next)
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** The request as it reaches the kit's origin; the page's `Origin` and `Referer` name the kit's origin instead. */
|
|
385
|
+
const toKit = async (request: Request, url: URL): Promise<Request> => {
|
|
386
|
+
const headers = new Headers(request.headers)
|
|
387
|
+
headers.delete('Host')
|
|
388
|
+
headers.delete('Referer')
|
|
389
|
+
const cookies = withoutChoice(headers.get('Cookie'))
|
|
390
|
+
if (cookies === null) headers.delete('Cookie')
|
|
391
|
+
else headers.set('Cookie', cookies)
|
|
392
|
+
if (headers.has('Origin')) headers.set('Origin', kit.origin)
|
|
393
|
+
const body = request.method === 'GET' || request.method === 'HEAD' ? undefined : await request.arrayBuffer()
|
|
394
|
+
return new Request(new URL(`${url.pathname}${url.search}`, kit.origin), { method: request.method, headers, body, redirect: 'manual' })
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* A redirect within the kit's origin stays a local path; a sign-in, a redirect to the kit's IAM or a 401's `loginUrl`,
|
|
399
|
+
* goes to the picker instead.
|
|
400
|
+
*/
|
|
401
|
+
const fromKit = async (response: Response, url: URL): Promise<Response> => {
|
|
402
|
+
const picker = `${PICKER_PATH}?next=${encodeURIComponent(`${url.pathname}${url.search}`)}`
|
|
403
|
+
const headers = new Headers(response.headers)
|
|
404
|
+
const location = response.headers.get('Location')
|
|
405
|
+
if (location !== null && response.status >= 300 && response.status < 400) {
|
|
406
|
+
const target = new URL(location, kit.origin)
|
|
407
|
+
headers.set('Location', target.origin === kit.origin ? `${target.pathname}${target.search}` : picker)
|
|
408
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers })
|
|
409
|
+
}
|
|
410
|
+
if (response.status === 401 && (response.headers.get('Content-Type') ?? '').startsWith('application/json')) {
|
|
411
|
+
const login = LoginRequired.safeParse(await response.clone().json())
|
|
412
|
+
if (login.success) {
|
|
413
|
+
headers.delete('Content-Length')
|
|
414
|
+
const body = { error: { ...login.data.error, loginUrl: picker } }
|
|
415
|
+
return new Response(JSON.stringify(body), { status: 401, statusText: response.statusText, headers })
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
return response
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const isPage = (path: string): boolean =>
|
|
422
|
+
pagePrefixes.some((prefix) => prefix === '/' || path === prefix || path.startsWith(prefix.endsWith('/') ? prefix : `${prefix}/`))
|
|
423
|
+
|
|
424
|
+
/** An SPA page with the toolbar's script tag; the kit's policy (`script-src 'self'`) already admits that script. */
|
|
425
|
+
const withDevToolbar = async (request: Request, response: Response, url: URL): Promise<Response> => {
|
|
426
|
+
if (
|
|
427
|
+
request.method !== 'GET' || response.status !== 200 || !(response.headers.get('Content-Type') ?? '').startsWith('text/html')
|
|
428
|
+
|| !isPage(url.pathname)
|
|
429
|
+
) {
|
|
430
|
+
return response
|
|
431
|
+
}
|
|
432
|
+
const headers = new Headers(response.headers)
|
|
433
|
+
headers.delete('Content-Length')
|
|
434
|
+
headers.delete('ETag')
|
|
435
|
+
return new Response(withToolbar(await response.text(), TOOLBAR_PATH), { status: 200, statusText: response.statusText, headers })
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const devRoute = (request: Request, url: URL): Response | null => {
|
|
439
|
+
if (request.method !== 'GET') return null
|
|
440
|
+
switch (url.pathname) {
|
|
441
|
+
case PICKER_PATH:
|
|
442
|
+
return new Response(pickerPage(viewOf(choiceOf(request), nextOf(url.searchParams.get('next')))), { headers: PAGE_HEADERS })
|
|
443
|
+
case CHOOSE_PATH:
|
|
444
|
+
return choose(url)
|
|
445
|
+
case ACCEPT_PATH:
|
|
446
|
+
return accept(request, url)
|
|
447
|
+
case STATE_PATH:
|
|
448
|
+
return Response.json(toolbarState(viewOf(choiceOf(request), nextOf(url.searchParams.get('next')))), {
|
|
449
|
+
headers: { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
|
|
450
|
+
})
|
|
451
|
+
case TOOLBAR_PATH:
|
|
452
|
+
return new Response(toolbar, {
|
|
453
|
+
headers: { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' },
|
|
454
|
+
})
|
|
455
|
+
default:
|
|
456
|
+
return null
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
let port = options.port
|
|
461
|
+
const server = listen({
|
|
462
|
+
hostname: options.host,
|
|
463
|
+
port: options.port,
|
|
464
|
+
async fetch(request) {
|
|
465
|
+
if (!addressedHere(request, port)) return plain(421, 'app dev answers only requests addressed to its loopback address')
|
|
466
|
+
const url = new URL(request.url)
|
|
467
|
+
const own = devRoute(request, url)
|
|
468
|
+
if (own !== null) return own
|
|
469
|
+
const choice = choiceOf(request)
|
|
470
|
+
const caller = choice === null ? null : callerOf(choice)
|
|
471
|
+
const fetch = caller === null ? kit.browser() : kit.browser(caller)
|
|
472
|
+
return await withDevToolbar(request, await fromKit(await fetch(await toKit(request, url)), url), url)
|
|
473
|
+
},
|
|
474
|
+
// The kit answers the application's own failures; anything thrown here is answered without its detail.
|
|
475
|
+
error: () => plain(500, 'app dev could not serve the request'),
|
|
476
|
+
})
|
|
477
|
+
port = server.port ?? options.port
|
|
478
|
+
const host = options.host.includes(':') ? `[${options.host}]` : options.host
|
|
479
|
+
return {
|
|
480
|
+
url: `http://${host}:${port}/`,
|
|
481
|
+
seeded: { personas: seeded.personas.length, links: seeded.links.length },
|
|
482
|
+
async stop() {
|
|
483
|
+
try {
|
|
484
|
+
await server.stop(true)
|
|
485
|
+
} finally {
|
|
486
|
+
await postgres?.close()
|
|
487
|
+
}
|
|
488
|
+
},
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** `Bun.serve`, with a port another process holds named as such. */
|
|
493
|
+
function listen(serving: Parameters<typeof Bun.serve>[0]): ReturnType<typeof Bun.serve> {
|
|
494
|
+
try {
|
|
495
|
+
return Bun.serve(serving)
|
|
496
|
+
} catch (error) {
|
|
497
|
+
if (error instanceof Error && 'code' in error && error.code === 'EADDRINUSE') {
|
|
498
|
+
throw new AppDevError(
|
|
499
|
+
`app dev: port ${String(serving.port)} on ${String(serving.hostname)} is in use; pass --port=<n>, or --port=0 for a free one`,
|
|
500
|
+
)
|
|
501
|
+
}
|
|
502
|
+
throw error
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** `fabrika app dev`: serves until the process is stopped, then drops the throwaway schema. */
|
|
507
|
+
export const runAppDevCli = async (argv: readonly string[]): Promise<void> => {
|
|
508
|
+
const { port, host, seed: given } = parseAppDevArgs(argv)
|
|
509
|
+
const root = process.cwd()
|
|
510
|
+
if (!existsSync(join(root, CONTRACT_FILE))) {
|
|
511
|
+
throw new Error(`app dev: no ${CONTRACT_FILE} in ${root}; run it from the application root`)
|
|
512
|
+
}
|
|
513
|
+
let server: AppDevServer
|
|
514
|
+
try {
|
|
515
|
+
const seed = seedPath(root, given)
|
|
516
|
+
const { default: app } = await implementationAt(join(root, IMPLEMENTATION_FILE))()
|
|
517
|
+
server = await startAppDev(app, { root, port, host, env: process.env, seed })
|
|
518
|
+
} catch (error) {
|
|
519
|
+
throw startupFailure(error)
|
|
520
|
+
}
|
|
521
|
+
console.info(server.url)
|
|
522
|
+
const { personas, links } = server.seeded
|
|
523
|
+
console.error(
|
|
524
|
+
`fabrika app dev: seeded personas: ${personas}, link pages: ${links}; pick a caller at ${server.url}${PICKER_PATH.slice(1)}; stop with Ctrl-C`,
|
|
525
|
+
)
|
|
526
|
+
await new Promise<void>((resolve) => {
|
|
527
|
+
const stop = () => {
|
|
528
|
+
void server.stop().finally(resolve)
|
|
529
|
+
}
|
|
530
|
+
process.once('SIGINT', stop)
|
|
531
|
+
process.once('SIGTERM', stop)
|
|
532
|
+
})
|
|
533
|
+
}
|