@fabrika/cli 0.3.3 → 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/src/db.ts ADDED
@@ -0,0 +1,296 @@
1
+ import {
2
+ type Finding,
3
+ formatFinding,
4
+ GENERATED_TEST_HEADER,
5
+ type GeneratedTest,
6
+ generatedTests,
7
+ missingEndpointFixtures,
8
+ readApplicationTree,
9
+ scaffoldInputs,
10
+ } from '@fabrika/check'
11
+ import { CodegenError, generateSchema, SCHEMA_FILE } from '@fabrika/db/codegen'
12
+ import { FRAMEWORK_MIGRATION_BUNDLE, FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations'
13
+ import {
14
+ createTestProvisioner,
15
+ DEFAULT_MIGRATION_LOCK_TIMEOUT_MS,
16
+ DEFAULT_MIGRATION_STATEMENT_TIMEOUT_MS,
17
+ definePostgresApplicationMigrations,
18
+ type PostgresApplicationMigrations,
19
+ PostgresMigrationError,
20
+ postgresMigrationResultMessage,
21
+ type TestProvisioner,
22
+ } from '@fabrika/platform-node'
23
+ import { SQL } from 'bun'
24
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
25
+ import { tmpdir } from 'node:os'
26
+ import { dirname, join } from 'node:path'
27
+ import { fileURLToPath } from 'node:url'
28
+ import { readJunitCases } from './junit'
29
+
30
+ /** The checker's `migration-name` contract (`@fabrika/check`, `db/migrations/`). */
31
+ const MIGRATIONS_DIR = 'db/migrations'
32
+ const SLUG = /^[a-z0-9]+(?:_[a-z0-9]+)*$/
33
+
34
+ export const DB_USAGE = `fabrika db — an application's Postgres schema
35
+
36
+ Usage:
37
+ fabrika db new <slug> Write ${MIGRATIONS_DIR}/<UTC YYYYMMDDHHMMSS>_<slug>.sql; the slug is lowercase snake_case.
38
+ fabrika db migrate Apply the framework's tables, then ${MIGRATIONS_DIR}, to the application's schema app_<id>.
39
+ fabrika db codegen [--verify] Write ${SCHEMA_FILE} from the migrated schema; --verify only fails when it is stale.
40
+ fabrika db test-scaffold Write the generated tests: a policy isolation test per table a store reaches, the endpoint access test.
41
+ fabrika db test-isolation [--verbose] Run the generated tests on a throwaway schema; fail unless every case the scaffold wrote passed.
42
+
43
+ Run from the application root. \`migrate\` and \`codegen\` read FABRIKA_APP_ID and FABRIKA_APP_DATABASE_URL from
44
+ the environment only. FABRIKA_APP_DATABASE_URL is the provisioning credential: \`migrate\` uses it only to create
45
+ the application's roles (app_<id> owns the schema, run_<id> gets DML on its tables) and fails when it cannot create
46
+ roles. It applies the files as app_<id>, holds a lock derived from the application id, runs each file in one
47
+ transaction with lock_timeout ${DEFAULT_MIGRATION_LOCK_TIMEOUT_MS} ms and statement_timeout ${DEFAULT_MIGRATION_STATEMENT_TIMEOUT_MS} ms, and fails when a
48
+ file that already ran has changed: an applied migration is immutable, so a change is a new file.
49
+ \`test-scaffold\` reads fabrika.contract.ts and src/db/tables.ts as the checker does, rewrites every generated test and
50
+ deletes a generated one the scaffold no longer writes, printing each path, or that it wrote none; @fabrika/check refuses
51
+ one that is missing, edited or stale.
52
+ \`test-isolation\` is the platform's run of them: with FABRIKA_APP_DATABASE_URL it creates a throwaway provisioner
53
+ (CREATEROLE, CREATE on the database, nothing of any application) that the tests get instead, ignores the application's
54
+ bunfig.toml, and checks the JUnit report against the case names the scaffold wrote.
55
+ `
56
+
57
+ export interface DbCommandDependencies {
58
+ /** The application root. */
59
+ readonly cwd: string
60
+ readonly source: Readonly<Record<string, string | undefined>>
61
+ readonly now: () => Date
62
+ readonly write: (line: string) => void
63
+ }
64
+
65
+ const required = (source: DbCommandDependencies['source'], name: string): string => {
66
+ const value = source[name]
67
+ if (value === undefined || value.trim() === '') throw new Error(`${name} is required`)
68
+ return value.trim()
69
+ }
70
+
71
+ const refuseArguments = (command: string, argv: readonly string[]): void => {
72
+ if (argv.length > 0) throw new Error(`db ${command} takes no argument ${argv[0]}\n\n${DB_USAGE}`)
73
+ }
74
+
75
+ const timestamp = (date: Date): string => date.toISOString().replace(/\.\d{3}Z$/, '').replaceAll(/[-:T]/g, '')
76
+
77
+ const newMigration = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
78
+ const [slug, ...extra] = argv
79
+ if (slug === undefined || slug.startsWith('-')) throw new Error(`db new needs a slug\n\n${DB_USAGE}`)
80
+ refuseArguments('new', extra)
81
+ if (!SLUG.test(slug)) throw new Error(`db new: '${slug}' is not a lowercase snake_case slug (allowed: add_note_tags)`)
82
+ const path = `${MIGRATIONS_DIR}/${timestamp(deps.now())}_${slug}.sql`
83
+ await mkdir(join(deps.cwd, MIGRATIONS_DIR), { recursive: true })
84
+ try {
85
+ await writeFile(join(deps.cwd, path), `-- ${slug}\n`, { flag: 'wx' })
86
+ } catch {
87
+ throw new Error(`db new: ${path} could not be created; if it exists, run fabrika db new again in a second`)
88
+ }
89
+ deps.write(`${path}\n`)
90
+ }
91
+
92
+ /**
93
+ * The runner's own messages name no credential, and neither does a server-reported error. Anything else from the
94
+ * driver (a refused connection, a TLS failure) may quote the URL, so it is replaced.
95
+ */
96
+ const reportable = (error: unknown): Error => {
97
+ if (error instanceof PostgresMigrationError) {
98
+ const server = serverError(error.cause)
99
+ return new Error(server === undefined ? error.message : `${error.message}: ${server}`)
100
+ }
101
+ if (error instanceof CodegenError) return error
102
+ const server = serverError(error)
103
+ if (server !== undefined) return new Error(server)
104
+ return new Error('the database connection failed; check FABRIKA_APP_DATABASE_URL (the driver error is withheld: it may contain the URL)')
105
+ }
106
+
107
+ const serverError = (error: unknown): string | undefined =>
108
+ error instanceof SQL.PostgresError && error.code === 'ERR_POSTGRES_SERVER_ERROR'
109
+ ? `${error.message} (SQLSTATE ${error.errno ?? 'unknown'})`
110
+ : undefined
111
+
112
+ /** The framework's tables, then the application's `db/migrations`, as `migrate` applies them and `codegen` checks them. */
113
+ const applicationMigrations = (appId: string, cwd: string): PostgresApplicationMigrations =>
114
+ definePostgresApplicationMigrations({
115
+ appId,
116
+ directory: join(cwd, MIGRATIONS_DIR),
117
+ framework: { bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: FRAMEWORK_MIGRATIONS },
118
+ })
119
+
120
+ const migrate = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
121
+ refuseArguments('migrate', argv)
122
+ const migrations = applicationMigrations(required(deps.source, 'FABRIKA_APP_ID'), deps.cwd)
123
+ const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
124
+ const files = migrations.read()
125
+ migrations.plan(files)
126
+ try {
127
+ deps.write(`${postgresMigrationResultMessage(await migrations.migrate(url, files))}\n`)
128
+ } catch (error) {
129
+ throw reportable(error)
130
+ }
131
+ }
132
+
133
+ const codegen = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
134
+ const verify = argv.includes('--verify')
135
+ refuseArguments('codegen', argv.filter((arg) => arg !== '--verify'))
136
+ const migrations = applicationMigrations(required(deps.source, 'FABRIKA_APP_ID'), deps.cwd)
137
+ const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
138
+ let source: string
139
+ try {
140
+ // The migrations' manifest: the start check refuses any database object no migration declares.
141
+ source = await generateSchema(url, migrations.schema, migrations.objects())
142
+ } catch (error) {
143
+ throw reportable(error)
144
+ }
145
+ const path = join(deps.cwd, SCHEMA_FILE)
146
+ if (verify) {
147
+ const committed = await readFile(path, 'utf8').catch(() => undefined)
148
+ if (committed !== source) throw new Error(`${SCHEMA_FILE} is stale; run fabrika db codegen and commit the result`)
149
+ deps.write(`${SCHEMA_FILE} is current\n`)
150
+ return
151
+ }
152
+ await mkdir(dirname(path), { recursive: true })
153
+ await writeFile(path, source)
154
+ deps.write(`${SCHEMA_FILE}\n`)
155
+ }
156
+
157
+ const expectedTests = async (
158
+ cwd: string,
159
+ ): Promise<
160
+ { readonly files: ReadonlyMap<string, string>; readonly tests: ReadonlyMap<string, GeneratedTest>; readonly missing: readonly Finding[] }
161
+ > => {
162
+ const { files } = await readApplicationTree(cwd)
163
+ const inputs = scaffoldInputs(files)
164
+ return { files, tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures), missing: missingEndpointFixtures(inputs) }
165
+ }
166
+
167
+ const testScaffold = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
168
+ refuseArguments('test-scaffold', argv)
169
+ const { files, tests, missing } = await expectedTests(deps.cwd)
170
+ for (const [path, text] of files) {
171
+ if (text.startsWith(GENERATED_TEST_HEADER) && !tests.has(path)) {
172
+ await rm(join(deps.cwd, path))
173
+ deps.write(`removed ${path}\n`)
174
+ }
175
+ }
176
+ for (const [path, { text }] of tests) {
177
+ await mkdir(dirname(join(deps.cwd, path)), { recursive: true })
178
+ await writeFile(join(deps.cwd, path), text)
179
+ deps.write(`${path}\n`)
180
+ }
181
+ if (missing.length > 0) {
182
+ throw new Error(`db test-scaffold: the endpoint access tests are incomplete\n${missing.map(formatFinding).join('\n')}`)
183
+ }
184
+ if (tests.size === 0) {
185
+ deps.write('no generated tests: they start with the first table a store reaches, and the application has none; write the first test yourself\n')
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Only what Bun needs to run; the URL arrives as the kit's own variable, and no framework variable is passed on. It is
191
+ * a throwaway provisioner's, never FABRIKA_APP_DATABASE_URL: the generated tests load application code.
192
+ */
193
+ const testEnvironment = (source: DbCommandDependencies['source'], url: string): Record<string, string> => {
194
+ const environment: Record<string, string> = { FABRIKA_TEST_POSTGRES_URL: url, FABRIKA_TEST_POSTGRES_REQUIRED: '1' }
195
+ for (const name of ['PATH', 'HOME', 'TMPDIR']) {
196
+ const value = source[name]
197
+ if (value !== undefined) environment[name] = value
198
+ }
199
+ return environment
200
+ }
201
+
202
+ /**
203
+ * Runs exactly the generated tests, with an empty `bunfig.toml` so that no preload, root or ignore pattern of the
204
+ * application applies, and fails unless every case the scaffold wrote is reported as passed.
205
+ */
206
+ /**
207
+ * Runs exactly the generated tests, with an empty `bunfig.toml` so that no preload, root or ignore pattern of the
208
+ * application applies, and the platform's preload, which captures Bun's test functions before the application loads.
209
+ * Fails unless every case the scaffold wrote is reported as passed with an assertion. The child's output is never
210
+ * printed, because a dependency may write a credential into it; `--verbose`, which the platform never passes, prints it.
211
+ */
212
+ const testIsolation = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
213
+ const verbose = argv.includes('--verbose')
214
+ refuseArguments('test-isolation', argv.filter((arg) => arg !== '--verbose'))
215
+ const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
216
+ const { files, tests, missing } = await expectedTests(deps.cwd)
217
+ if (missing.length > 0) throw new Error(`db test-isolation: the endpoint access tests are incomplete\n${missing.map(formatFinding).join('\n')}`)
218
+ for (const [path, { text }] of tests) {
219
+ if (files.get(path) !== text) throw new Error(`db test-isolation: ${path} is not the test fabrika db test-scaffold writes; run it`)
220
+ }
221
+ if (tests.size === 0) {
222
+ deps.write('no generated tests\n')
223
+ return
224
+ }
225
+ let provisioner: TestProvisioner
226
+ try {
227
+ provisioner = await createTestProvisioner(url)
228
+ } catch (error) {
229
+ throw reportable(error)
230
+ }
231
+ const scratch = await mkdtemp(join(tmpdir(), 'fabrika-test-isolation-'))
232
+ try {
233
+ await writeFile(join(scratch, 'bunfig.toml'), '')
234
+ const report = join(scratch, 'junit.xml')
235
+ const child = Bun.spawn(
236
+ [
237
+ process.execPath,
238
+ `--config=${join(scratch, 'bunfig.toml')}`,
239
+ 'test',
240
+ `--preload=${fileURLToPath(import.meta.resolve('@fabrika/app/testing/preload'))}`,
241
+ ...[...tests.keys()].map((path) => `./${path}`),
242
+ '--reporter=junit',
243
+ `--reporter-outfile=${report}`,
244
+ ],
245
+ { cwd: deps.cwd, env: testEnvironment(deps.source, provisioner.url), stdout: 'pipe', stderr: 'pipe' },
246
+ )
247
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited])
248
+ if (verbose) deps.write(`${stdout}${stderr}\n`)
249
+ const reported = readJunitCases(await readFile(report, 'utf8').catch(() => ''))
250
+ const failed: string[] = []
251
+ let total = 0
252
+ for (const [path, { cases }] of tests) {
253
+ for (const name of cases) {
254
+ total++
255
+ const reportedCase = reported.find((item) => item.file === path && item.name === name)
256
+ const outcome = reportedCase === undefined
257
+ ? 'not run'
258
+ : reportedCase.outcome === 'passed' && reportedCase.assertions === 0
259
+ ? 'no assertion'
260
+ : reportedCase.outcome
261
+ if (outcome !== 'passed') failed.push(`${path}: ${name} (${outcome})`)
262
+ }
263
+ }
264
+ if (code !== 0 || failed.length > 0) {
265
+ const rerun = verbose ? '' : '; rerun with --verbose locally to see the test output'
266
+ throw new Error(
267
+ `db test-isolation: ${total - failed.length} of ${total} generated cases passed (exit ${code})${rerun}${
268
+ failed.map((line) => `\n- ${line}`).join('')
269
+ }`,
270
+ )
271
+ }
272
+ deps.write(`${total} generated cases passed\n`)
273
+ } finally {
274
+ await rm(scratch, { recursive: true, force: true })
275
+ await provisioner.drop().catch((error: unknown) => {
276
+ throw reportable(error)
277
+ })
278
+ }
279
+ }
280
+
281
+ export const runDbCommand = async (command: string | undefined, argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
282
+ if (command === 'new') return newMigration(argv, deps)
283
+ if (command === 'migrate') return migrate(argv, deps)
284
+ if (command === 'codegen') return codegen(argv, deps)
285
+ if (command === 'test-scaffold') return testScaffold(argv, deps)
286
+ if (command === 'test-isolation') return testIsolation(argv, deps)
287
+ throw new Error(`Unknown db command: ${command ?? '(missing)'}\n\n${DB_USAGE}`)
288
+ }
289
+
290
+ export const runDbCli = (command: string | undefined, argv: readonly string[]): Promise<void> =>
291
+ runDbCommand(command, argv, {
292
+ cwd: process.cwd(),
293
+ source: process.env,
294
+ now: () => new Date(),
295
+ write: (line) => process.stdout.write(line),
296
+ })
package/src/index.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
- import { BUILDER_USAGE, runBuilderCli } from '@fabrika/builder'
3
+ import { CONTRACT_FILE, type EntryRuntime, writeGeneratedEntry } from '@fabrika/app/build'
4
4
  import { authoredAppProvider } from '@fabrika/provider-contract'
5
5
  import { installationCliFromModule, isInstallationCommand, supportsInstallationCommand } from '@fabrika/provider-contract/installation'
6
- import { resolve } from 'node:path'
7
- import { CONTROL_USAGE, runControlCli } from './control.js'
6
+ import { dirname, join, relative, resolve } from 'node:path'
7
+ import { CONTROL_USAGE, registerCompiledManifest, runControlCli } from './control.js'
8
8
 
9
9
  const USAGE = `fabrika — application platform CLI
10
10
 
@@ -17,13 +17,40 @@ Usage:
17
17
  fabrika platform upgrade --provider=zerops --to=<tag> [<installation>] [--sidecar=<path>|<owner>/<name>]
18
18
  fabrika app deploy [--provider=cloudflare] --env=<env> [--config=<path>] [--dry-run]
19
19
  fabrika app build [--provider=zerops] --env=<env> [--config=<path>] [--output=<path>]
20
+ fabrika app build --provider=cloudflare [--config=<path>]
21
+ fabrika app dev [--port=<n>] [--host=<loopback address>]
22
+ fabrika app register [--provider=zerops] --env=<env> --app=<id> --repo=<url> [--config=<path>]
23
+ [--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>]
24
+ [--namespace=<id>] [--installation-id=<n|none>] [--url=<origin>] [--json]
20
25
  fabrika namespace <plan|create|adopt|reconcile> --provider=zerops [provider options]
21
26
  fabrika control <key|apps|namespaces|register|deploy|runs> [options]
22
27
  fabrika builder <init|next|advance|gate|ensure-daemon|induce|build> [options]
28
+ fabrika db <new|migrate|codegen|test-scaffold|test-isolation> [options]
29
+ fabrika job run <name>
30
+ fabrika connect <add|pull> <app>/<export>@<version> --consumer=<app> --env=<env> [--url=<control origin>]
23
31
 
24
32
  For app commands, the provider is read from the config returned by the selected provider's defineApp().
25
33
  An explicit --provider is required only when no app config is available.
26
34
 
35
+ \`app build\` first writes fabrika/entry.generated.ts for a contract application (one with fabrika.contract.ts next
36
+ to its config); on Cloudflare that is all it does.
37
+
38
+ \`app dev\` serves a contract application through its test kit on a loopback port, to click through its screens.
39
+ Run \`fabrika app dev --help\` for its surface.
40
+
41
+ \`app register\` compiles the manifest in memory, exactly as \`app build\` would, and sends the request
42
+ \`control register --manifest=<path>\` sends for it. It writes no file, CREATES only, and reads the
43
+ control credential from FABRIKA_CONTROL_KEY alone; a changed manifest is \`control apps environments put\`.
44
+
45
+ \`fabrika db\` manages an application's Postgres schema: migration files, applying them (the template's
46
+ \`run.initCommands\`), the generated types and the generated isolation tests. Run \`fabrika db --help\` for its surface.
47
+
48
+ \`fabrika job run <name>\` runs one c.cron job of a contract application: the command each crontab entry runs. Run
49
+ \`fabrika job --help\` for its surface.
50
+
51
+ \`fabrika connect\` vendors another application's export into fabrika/connect/, from the description the owner's
52
+ environment approved, as Control answers it to FABRIKA_CONTROL_KEY. Run \`fabrika connect --help\` for its surface.
53
+
27
54
  \`fabrika control\` is the operator's non-browser client for the control plane (ADR-0033). It is
28
55
  provider-neutral, loads no installation package, and speaks the same typed API the console does. Run
29
56
  \`fabrika control --help\` for its surface.
@@ -104,13 +131,29 @@ const selectedAppProvider = async (parsed: ParsedCommand): Promise<string> => {
104
131
  return provider
105
132
  }
106
133
 
107
- const installationModule = async (provider: string): Promise<unknown> => {
108
- const packageName = provider === 'cloudflare'
134
+ const packageNameOf = (specifier: string): string => specifier.split('/').slice(0, specifier.startsWith('@') ? 2 : 1).join('/')
135
+
136
+ /**
137
+ * The builder and the providers are optional peers: an application installs only the ones its commands load. A
138
+ * command whose package is absent names the package to add, instead of a resolver error.
139
+ */
140
+ const requireInstalled = (specifier: string, command: string): void => {
141
+ try {
142
+ Bun.resolveSync(specifier, import.meta.dir)
143
+ } catch {
144
+ const packageName = packageNameOf(specifier)
145
+ throw new Error(`\`${command}\` needs ${packageName}, which is not installed. Add it: bun add -d ${packageName}`)
146
+ }
147
+ }
148
+
149
+ const installationModule = async (provider: string, command: string): Promise<unknown> => {
150
+ const specifier = provider === 'cloudflare'
109
151
  ? '@fabrika/provider-cloudflare/installation'
110
152
  : provider === 'zerops'
111
153
  ? '@fabrika/provider-zerops/installation'
112
154
  : provider
113
- return import(packageName)
155
+ requireInstalled(specifier, command)
156
+ return import(specifier)
114
157
  }
115
158
 
116
159
  export type AppCliRunner = (argv: readonly string[]) => Promise<void>
@@ -126,7 +169,8 @@ export const appCliRunnerFromModule = (loaded: unknown, packageName: string, exp
126
169
  return runner
127
170
  }
128
171
 
129
- const appCliRunner = async (packageName: string, exportName: string): Promise<AppCliRunner> => {
172
+ const appCliRunner = async (packageName: string, exportName: string, command: string): Promise<AppCliRunner> => {
173
+ requireInstalled(packageName, command)
130
174
  const loaded: unknown = await import(packageName)
131
175
  return appCliRunnerFromModule(loaded, packageName, exportName)
132
176
  }
@@ -137,20 +181,64 @@ const runPlatform = async (parsed: ParsedCommand): Promise<void> => {
137
181
  }
138
182
  const provider = requireExplicitProvider(parsed)
139
183
  const expectedProvider = provider === 'cloudflare' || provider === 'zerops' ? provider : undefined
140
- const installation = installationCliFromModule(await installationModule(provider), expectedProvider)
184
+ const installation = installationCliFromModule(
185
+ await installationModule(provider, `fabrika platform ${parsed.command} --provider=${provider}`),
186
+ expectedProvider,
187
+ )
141
188
  if (!supportsInstallationCommand(installation, parsed.command)) {
142
189
  throw new Error(`${installation.provider} installation does not support \`platform ${parsed.command}\`\n\n${installation.usage}`)
143
190
  }
144
191
  await installation.run(parsed.command, parsed.rest)
145
192
  }
146
193
 
194
+ /** Provider inference imports the app config, so it belongs to the compile phase `app register` reports. */
195
+ const runAppRegister = async (parsed: ParsedCommand): Promise<void> => {
196
+ const config = configPath(parsed.rest)
197
+ await registerCompiledManifest(parsed.rest, async (env) => {
198
+ const provider = await selectedAppProvider(parsed)
199
+ if (provider !== 'zerops') {
200
+ throw new Error(`${provider} app tooling does not support \`app register\``)
201
+ }
202
+ requireInstalled('@fabrika/provider-zerops/cli', 'fabrika app register')
203
+ const { buildZeropsManifestText } = await import('@fabrika/provider-zerops/cli')
204
+ return { provider, text: await buildZeropsManifestText({ config, env }) }
205
+ })
206
+ }
207
+
208
+ const ENTRY_RUNTIMES: Readonly<Record<string, EntryRuntime>> = { cloudflare: 'cloudflare', zerops: 'bun' }
209
+
210
+ /** A contract application gets its generated entrypoint before the provider builds it. False when it is none. */
211
+ const writeContractEntry = async (argv: readonly string[], runtime: EntryRuntime): Promise<boolean> => {
212
+ const root = dirname(resolve(process.cwd(), configPath(argv)))
213
+ if (!(await Bun.file(join(root, CONTRACT_FILE)).exists())) {
214
+ return false
215
+ }
216
+ const written = await writeGeneratedEntry(root, runtime)
217
+ console.error(`fabrika: wrote ${relative(process.cwd(), written)}`)
218
+ return true
219
+ }
220
+
147
221
  const runApp = async (parsed: ParsedCommand): Promise<void> => {
222
+ if (parsed.command === 'dev') {
223
+ const { runAppDevCli } = await import('./app-dev.js')
224
+ await runAppDevCli(parsed.rest)
225
+ return
226
+ }
227
+ if (parsed.command === 'register') {
228
+ await runAppRegister(parsed)
229
+ return
230
+ }
148
231
  const provider = await selectedAppProvider(parsed)
232
+ const runtime = ENTRY_RUNTIMES[provider]
233
+ const contract = parsed.command === 'build' && runtime !== undefined && (await writeContractEntry(parsed.rest, runtime))
149
234
  if (provider === 'cloudflare') {
235
+ if (contract) {
236
+ return
237
+ }
150
238
  if (parsed.command !== 'deploy') {
151
239
  throw new Error(`Cloudflare app tooling does not support \`app ${parsed.command ?? '(missing)'}\``)
152
240
  }
153
- const runCloudflareCli = await appCliRunner('@fabrika/provider-cloudflare/cli', 'runCloudflareCli')
241
+ const runCloudflareCli = await appCliRunner('@fabrika/provider-cloudflare/cli', 'runCloudflareCli', 'fabrika app deploy')
154
242
  await runCloudflareCli(['deploy', ...parsed.rest])
155
243
  return
156
244
  }
@@ -158,7 +246,7 @@ const runApp = async (parsed: ParsedCommand): Promise<void> => {
158
246
  if (parsed.command !== 'build') {
159
247
  throw new Error(`Zerops app tooling does not support \`app ${parsed.command ?? '(missing)'}\``)
160
248
  }
161
- const runZeropsCli = await appCliRunner('@fabrika/provider-zerops/cli', 'runZeropsCli')
249
+ const runZeropsCli = await appCliRunner('@fabrika/provider-zerops/cli', 'runZeropsCli', 'fabrika app build')
162
250
  await runZeropsCli(['build', ...parsed.rest])
163
251
  return
164
252
  }
@@ -173,6 +261,7 @@ const runNamespace = async (parsed: ParsedCommand): Promise<void> => {
173
261
  if (parsed.command === undefined) {
174
262
  throw new Error('Namespace command is required')
175
263
  }
264
+ requireInstalled('@fabrika/provider-zerops', 'fabrika namespace')
176
265
  const { runZeropsNamespaceCli } = await import('./namespace.js')
177
266
  await runZeropsNamespaceCli(parsed.command, parsed.rest)
178
267
  }
@@ -182,7 +271,7 @@ export const runCli = async (argv: readonly string[]): Promise<void> => {
182
271
  if (parsed.help && parsed.area === 'platform' && parsed.provider !== undefined && parsed.provider !== '') {
183
272
  // A platform command's real surface is the installation's, not this router's — and on Zerops that
184
273
  // text is what backlog 62 generates the operator's workflow from, so `--help` must reach it.
185
- console.info(installationCliFromModule(await installationModule(parsed.provider)).usage)
274
+ console.info(installationCliFromModule(await installationModule(parsed.provider, `fabrika platform --provider=${parsed.provider}`)).usage)
186
275
  return
187
276
  }
188
277
  if (parsed.help && parsed.area === 'control') {
@@ -190,11 +279,34 @@ export const runCli = async (argv: readonly string[]): Promise<void> => {
190
279
  return
191
280
  }
192
281
  if (parsed.help && parsed.area === 'namespace') {
282
+ requireInstalled('@fabrika/provider-zerops', 'fabrika namespace')
193
283
  const { NAMESPACE_USAGE } = await import('./namespace.js')
194
284
  console.info(NAMESPACE_USAGE)
195
285
  return
196
286
  }
287
+ if (parsed.help && parsed.area === 'app' && parsed.command === 'dev') {
288
+ const { APP_DEV_USAGE } = await import('./app-dev.js')
289
+ console.info(APP_DEV_USAGE)
290
+ return
291
+ }
292
+ if (parsed.help && parsed.area === 'db') {
293
+ const { DB_USAGE } = await import('./db.js')
294
+ console.info(DB_USAGE)
295
+ return
296
+ }
297
+ if (parsed.help && parsed.area === 'job') {
298
+ const { JOB_USAGE } = await import('./job.js')
299
+ console.info(JOB_USAGE)
300
+ return
301
+ }
302
+ if (parsed.help && parsed.area === 'connect') {
303
+ const { CONNECT_USAGE } = await import('./connect.js')
304
+ console.info(CONNECT_USAGE)
305
+ return
306
+ }
197
307
  if (parsed.help && parsed.area === 'builder') {
308
+ requireInstalled('@fabrika/builder', 'fabrika builder')
309
+ const { BUILDER_USAGE } = await import('@fabrika/builder')
198
310
  console.info(BUILDER_USAGE)
199
311
  return
200
312
  }
@@ -218,7 +330,24 @@ export const runCli = async (argv: readonly string[]): Promise<void> => {
218
330
  await runControlCli(parsed.command, parsed.rest, parsed.provider)
219
331
  return
220
332
  }
333
+ if (parsed.area === 'db') {
334
+ const { runDbCli } = await import('./db.js')
335
+ await runDbCli(parsed.command, parsed.rest)
336
+ return
337
+ }
338
+ if (parsed.area === 'job') {
339
+ const { runJobCli } = await import('./job.js')
340
+ await runJobCli(parsed.command, parsed.rest)
341
+ return
342
+ }
343
+ if (parsed.area === 'connect') {
344
+ const { runConnectCli } = await import('./connect.js')
345
+ await runConnectCli(parsed.command, parsed.rest)
346
+ return
347
+ }
221
348
  if (parsed.area === 'builder') {
349
+ requireInstalled('@fabrika/builder', 'fabrika builder')
350
+ const { runBuilderCli } = await import('@fabrika/builder')
222
351
  const exitCode = await runBuilderCli(parsed.command === undefined ? [] : [parsed.command, ...parsed.rest])
223
352
  if (exitCode !== 0) process.exitCode = exitCode
224
353
  return
package/src/job.ts ADDED
@@ -0,0 +1,81 @@
1
+ import { CONTRACT_FILE, IMPLEMENTATION_FILE } from '@fabrika/app/build'
2
+ import { implementationAt, type ImplementationLoader, runContractJob } from '@fabrika/app/bun'
3
+ import { BootError, JobError, type JobRunResult } from '@fabrika/app/implement'
4
+ import { join } from 'node:path'
5
+
6
+ export const JOB_USAGE = `fabrika job — an application's c.cron jobs
7
+
8
+ Usage:
9
+ fabrika job run <name> Run the job <name> of ${CONTRACT_FILE} once: the command every crontab entry runs.
10
+ The framework's own fabrika-file-scan scans the uploads of scan: true file collections,
11
+ and fabrika-file-sweep deletes the objects of removed and orphaned files.
12
+
13
+ Run from the application root. The job boots like the server: the framework variables (FABRIKA_APP_ID,
14
+ FABRIKA_APP_DATABASE_URL, FABRIKA_IAM_*, FABRIKA_CONTRACT_DIGEST, FABRIKA_PROXY_SECRET, FABRIKA_OPERATIONS_DSN)
15
+ come from the environment only and leave the process before ${IMPLEMENTATION_FILE} loads; the run itself happens in a
16
+ process started again with the runtime role's credential in place of FABRIKA_APP_DATABASE_URL. A run takes the job's lease
17
+ or does not start. It exits 1 when the job failed, and 0 when it succeeded or a previous run still holds the lease.
18
+ A failure is named by a fixed code (timeout, lease_lost, handler_failed, query_refused, capability_refused,
19
+ driver_failed, crashed, unauthorized, iam_unavailable, boot_failed), never by the application's error; a refusal adds
20
+ its catalog reason (query_refused: undeclared_reach).
21
+ `
22
+
23
+ export interface JobCommandDependencies {
24
+ /** The application root. */
25
+ readonly cwd: string
26
+ readonly source: Readonly<Record<string, string | undefined>>
27
+ readonly write: (line: string) => void
28
+ readonly fileExists: (path: string) => Promise<boolean>
29
+ readonly run: (load: ImplementationLoader, env: Readonly<Record<string, string | undefined>>, name: string) => Promise<JobRunResult>
30
+ }
31
+
32
+ /**
33
+ * The framework's own errors keep their message; anything else (an error importing or booting the application, a
34
+ * driver error) is `boot_failed`, because its name and message may carry a secret or the database URL.
35
+ */
36
+ const reportable = (error: unknown): Error =>
37
+ error instanceof BootError || error instanceof JobError ? error : new Error('the job could not run: boot_failed')
38
+
39
+ const plural = (attempts: number): string => `${attempts} attempt${attempts === 1 ? '' : 's'}`
40
+
41
+ const summary = (name: string, result: JobRunResult): string => {
42
+ switch (result.status) {
43
+ case 'succeeded':
44
+ return `job ${name} succeeded after ${plural(result.attempts)}`
45
+ case 'failed':
46
+ return `job ${name} failed after ${plural(result.attempts)}: ${result.code}${result.reason === undefined ? '' : `: ${result.reason}`}`
47
+ case 'skipped':
48
+ return `job ${name} did not start: a previous run still holds its lease`
49
+ }
50
+ }
51
+
52
+ /** Runs one job and answers the process exit code. */
53
+ export const runJobCommand = async (command: string | undefined, argv: readonly string[], deps: JobCommandDependencies): Promise<number> => {
54
+ if (command !== 'run') throw new Error(`Unknown job command: ${command ?? '(missing)'}\n\n${JOB_USAGE}`)
55
+ const [name, ...extra] = argv
56
+ if (name === undefined || name.startsWith('-')) throw new Error(`job run needs the name of a job\n\n${JOB_USAGE}`)
57
+ if (extra.length > 0) throw new Error(`job run takes no argument ${extra[0]}\n\n${JOB_USAGE}`)
58
+ if (!(await deps.fileExists(join(deps.cwd, CONTRACT_FILE)))) {
59
+ throw new Error(`job run: no ${CONTRACT_FILE} in ${deps.cwd}; run it from the application root`)
60
+ }
61
+ let result: JobRunResult
62
+ try {
63
+ result = await deps.run(implementationAt(join(deps.cwd, IMPLEMENTATION_FILE)), deps.source, name)
64
+ } catch (error) {
65
+ throw reportable(error)
66
+ }
67
+ deps.write(`${summary(name, result)}\n`)
68
+ return result.status === 'failed' ? 1 : 0
69
+ }
70
+
71
+ /** The process ends with the run, so nothing a handler left running outlives it. */
72
+ export const runJobCli = async (command: string | undefined, argv: readonly string[]): Promise<never> => {
73
+ const code = await runJobCommand(command, argv, {
74
+ cwd: process.cwd(),
75
+ source: process.env,
76
+ write: (line) => process.stdout.write(line),
77
+ fileExists: (path) => Bun.file(path).exists(),
78
+ run: (load, env, name) => runContractJob(load, env, name),
79
+ })
80
+ process.exit(code)
81
+ }
package/src/junit.ts ADDED
@@ -0,0 +1,37 @@
1
+ // The test cases of a `bun test --reporter=junit` report: which ran, and how each ended. Only what `fabrika db
2
+ // test-isolation` needs to tell a passed case from a skipped, failed or missing one.
3
+
4
+ export type CaseOutcome = 'passed' | 'failed' | 'skipped'
5
+
6
+ export interface ReportedCase {
7
+ /** The test file, relative to the directory `bun test` ran in. */
8
+ readonly file: string
9
+ readonly name: string
10
+ readonly outcome: CaseOutcome
11
+ /** The `expect` calls the case ran, as Bun reports them; `null` when the report does not say. */
12
+ readonly assertions: number | null
13
+ }
14
+
15
+ const ENTITIES: Readonly<Record<string, string>> = { quot: '"', apos: "'", lt: '<', gt: '>', amp: '&' }
16
+
17
+ const unescape = (text: string): string => text.replace(/&(quot|apos|lt|gt|amp);/g, (_, name: string) => ENTITIES[name] ?? '')
18
+
19
+ const attribute = (attributes: string, name: string): string | undefined => {
20
+ const match = new RegExp(`\\s${name}="([^"]*)"`).exec(attributes)
21
+ return match?.[1] === undefined ? undefined : unescape(match[1])
22
+ }
23
+
24
+ export function readJunitCases(xml: string): ReportedCase[] {
25
+ const cases: ReportedCase[] = []
26
+ for (const match of xml.matchAll(/<testcase\b([^>]*?)(\/>|>([\s\S]*?)<\/testcase>)/g)) {
27
+ const attributes = match[1] ?? ''
28
+ const content = match[3] ?? ''
29
+ const file = attribute(attributes, 'file')
30
+ const name = attribute(attributes, 'name')
31
+ if (file === undefined || name === undefined) continue
32
+ const outcome: CaseOutcome = /<(failure|error)\b/.test(content) ? 'failed' : /<skipped\b/.test(content) ? 'skipped' : 'passed'
33
+ const assertions = attribute(attributes, 'assertions')
34
+ cases.push({ file: file.replace(/^\.\//, ''), name, outcome, assertions: assertions === undefined ? null : Number(assertions) })
35
+ }
36
+ return cases
37
+ }