@fabrika/cli 0.8.1 → 0.9.0-cloudflare.1
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 +15 -14
- package/src/app-dev.ts +29 -15
- package/src/control.ts +38 -1
- package/src/db.ts +72 -16
- package/src/index.ts +42 -55
- package/src/namespace.ts +55 -178
- package/types/src/app-dev-outside.d.ts +27 -0
- package/types/src/app-dev-seed.d.ts +37 -0
- package/types/src/app-dev-ui.d.ts +146 -0
- package/types/src/app-dev.d.ts +45 -0
- package/types/src/connect.d.ts +17 -0
- package/types/src/control.d.ts +40 -0
- package/types/src/db.d.ts +12 -0
- package/types/src/index.d.ts +11 -0
- package/types/src/job.d.ts +15 -0
- package/types/src/junit.d.ts +10 -0
- package/types/src/namespace.d.ts +12 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0-cloudflare.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -15,12 +15,13 @@
|
|
|
15
15
|
},
|
|
16
16
|
"files": [
|
|
17
17
|
"src",
|
|
18
|
-
"!src/**/__tests__/**"
|
|
18
|
+
"!src/**/__tests__/**",
|
|
19
|
+
"types"
|
|
19
20
|
],
|
|
20
21
|
"exports": {
|
|
21
22
|
".": {
|
|
22
23
|
"bun": "./src/index.ts",
|
|
23
|
-
"types": "./src/index.ts",
|
|
24
|
+
"types": "./types/src/index.d.ts",
|
|
24
25
|
"default": "./src/index.ts"
|
|
25
26
|
}
|
|
26
27
|
},
|
|
@@ -30,19 +31,19 @@
|
|
|
30
31
|
},
|
|
31
32
|
"dependencies": {
|
|
32
33
|
"zod": "^3.25.76",
|
|
33
|
-
"@fabrika/app": "0.
|
|
34
|
-
"@fabrika/auth-core": "0.
|
|
35
|
-
"@fabrika/control-contract": "0.
|
|
36
|
-
"@fabrika/provider-contract": "0.
|
|
37
|
-
"@fabrika/db": "0.
|
|
38
|
-
"@fabrika/platform": "0.
|
|
39
|
-
"@fabrika/platform-node": "0.
|
|
40
|
-
"@fabrika/check": "0.
|
|
34
|
+
"@fabrika/app": "0.9.0-cloudflare.1",
|
|
35
|
+
"@fabrika/auth-core": "0.9.0-cloudflare.1",
|
|
36
|
+
"@fabrika/control-contract": "0.9.0-cloudflare.1",
|
|
37
|
+
"@fabrika/provider-contract": "0.9.0-cloudflare.1",
|
|
38
|
+
"@fabrika/db": "0.9.0-cloudflare.1",
|
|
39
|
+
"@fabrika/platform": "0.9.0-cloudflare.1",
|
|
40
|
+
"@fabrika/platform-node": "0.9.0-cloudflare.1",
|
|
41
|
+
"@fabrika/check": "0.9.0-cloudflare.1"
|
|
41
42
|
},
|
|
42
43
|
"peerDependencies": {
|
|
43
|
-
"@fabrika/builder": "0.
|
|
44
|
-
"@fabrika/provider-cloudflare": "0.
|
|
45
|
-
"@fabrika/provider-zerops": "0.
|
|
44
|
+
"@fabrika/builder": "0.9.0-cloudflare.1",
|
|
45
|
+
"@fabrika/provider-cloudflare": "0.9.0-cloudflare.1",
|
|
46
|
+
"@fabrika/provider-zerops": "0.9.0-cloudflare.1"
|
|
46
47
|
},
|
|
47
48
|
"peerDependenciesMeta": {
|
|
48
49
|
"@fabrika/builder": {
|
package/src/app-dev.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// `fabrika app dev`: a contract application served through its test kit on a loopback port, to click through its
|
|
2
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
|
|
3
|
+
// their build directories; Postgres is a throwaway schema of the tests' database, SQLite (Cloudflare) an in-memory
|
|
4
|
+
// database. A seed module fills it through the
|
|
4
5
|
// endpoints first. A caller picker chooses who the browser is; a cookie keeps the choice, and the kit's own session
|
|
5
6
|
// never leaves the process. Every SPA page gets the dev toolbar, which switches the caller without leaving the page.
|
|
6
7
|
|
|
@@ -9,10 +10,12 @@ import { implementationAt } from '@fabrika/app/bun'
|
|
|
9
10
|
import type { AnyContract } from '@fabrika/app/contract'
|
|
10
11
|
import { BootError, type ContractImplementation } from '@fabrika/app/implement'
|
|
11
12
|
import { DEV_OUTBOX_ORIGIN, type DevKit, devKit, type DevOutside, type LabelledTestCaller, type TestCaller } from '@fabrika/app/testing'
|
|
13
|
+
import { type ApplicationDialect, applicationDialect, CONFIG_FILE } from '@fabrika/check'
|
|
14
|
+
import { SqliteMigrationError } from '@fabrika/db/sqlite-migrate'
|
|
12
15
|
import { TEST_POSTGRES_URL, type TestDatabase, testDatabase } from '@fabrika/db/testing'
|
|
13
16
|
import { PostgresMigrationError } from '@fabrika/platform-node'
|
|
14
17
|
import { MemoryFileObjects } from '@fabrika/platform/testing'
|
|
15
|
-
import { existsSync } from 'node:fs'
|
|
18
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
16
19
|
import { join } from 'node:path'
|
|
17
20
|
import { z } from 'zod/v4'
|
|
18
21
|
import { DEV_ENV_FILE, DevEnvProblem, type DevOutbox, devOutbox, mailHeadOf, readDevEnv, shownBody } from './app-dev-outside'
|
|
@@ -41,7 +44,8 @@ Usage:
|
|
|
41
44
|
|
|
42
45
|
Run from the application root. It serves ${IMPLEMENTATION_FILE} through its test kit: the production proxy decision,
|
|
43
46
|
the kit's stand-in IAM, each SPA from its built directory (run the SPA build first; an unbuilt one is an empty page),
|
|
44
|
-
and a throwaway schema of the database in ${TEST_POSTGRES_URL}, migrated from db/migrations/ and dropped on exit
|
|
47
|
+
and a throwaway schema of the database in ${TEST_POSTGRES_URL}, migrated from db/migrations/ and dropped on exit; an
|
|
48
|
+
application on Cloudflare (its ${CONFIG_FILE} is @fabrika/provider-cloudflare's) gets an in-memory SQLite database instead.
|
|
45
49
|
The seed module (--seed, or ${DEFAULT_SEED} when it exists) default-exports a DevSeed of @fabrika/app/testing: it
|
|
46
50
|
receives the kit, writes through the endpoints, and answers the personas, link pages and scope values to offer.
|
|
47
51
|
Pick who the browser is at /__fabrika/dev; every SPA page shows a toolbar that switches the caller and lists the
|
|
@@ -87,7 +91,7 @@ export class AppDevError extends Error {
|
|
|
87
91
|
export function startupFailure(error: unknown): Error {
|
|
88
92
|
if (
|
|
89
93
|
error instanceof AppDevError || error instanceof SeedProblem || error instanceof DevEnvProblem || error instanceof BootError
|
|
90
|
-
|| error instanceof PostgresMigrationError
|
|
94
|
+
|| error instanceof PostgresMigrationError || error instanceof SqliteMigrationError
|
|
91
95
|
) {
|
|
92
96
|
return new Error(error.message)
|
|
93
97
|
}
|
|
@@ -190,21 +194,31 @@ function addressedHere(request: Request, port: number): boolean {
|
|
|
190
194
|
const plain = (status: number, text: string): Response =>
|
|
191
195
|
new Response(`${text}\n`, { status, headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' } })
|
|
192
196
|
|
|
197
|
+
/** The dialect the application's `fabrika.config.ts` names, as the checker reads it. */
|
|
198
|
+
function dialectAt(root: string): ApplicationDialect {
|
|
199
|
+
const path = join(root, CONFIG_FILE)
|
|
200
|
+
return applicationDialect(new Map(existsSync(path) ? [[CONFIG_FILE, readFileSync(path, 'utf8')]] : []))
|
|
201
|
+
}
|
|
202
|
+
|
|
193
203
|
/** Serves `app` through its test kit on a loopback port until `stop`. */
|
|
194
204
|
export async function startAppDev(app: ContractImplementation<AnyContract>, options: AppDevOptions): Promise<AppDevServer> {
|
|
195
205
|
if (!LOOPBACK.has(options.host)) throw new AppDevError(`app dev serves this machine only, not ${options.host}`)
|
|
196
|
-
let
|
|
197
|
-
if (app.database !== null) {
|
|
206
|
+
let testDb: TestDatabase | null = null
|
|
207
|
+
if (app.database !== null && dialectAt(options.root) === 'sqlite') {
|
|
208
|
+
// The SQLite twin of the kit opens an in-memory database: no URL, and nothing left behind to drop.
|
|
209
|
+
const sqlite = await import('@fabrika/db/testing-sqlite')
|
|
210
|
+
testDb = await sqlite.testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
|
|
211
|
+
} else if (app.database !== null) {
|
|
198
212
|
if ((options.env[TEST_POSTGRES_URL] ?? '') === '') {
|
|
199
213
|
throw new AppDevError(`app dev needs ${TEST_POSTGRES_URL}, the database the tests use: it migrates a throwaway schema there`)
|
|
200
214
|
}
|
|
201
|
-
|
|
215
|
+
testDb = await testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
|
|
202
216
|
}
|
|
203
217
|
try {
|
|
204
|
-
return await serveThroughKit(app, options,
|
|
218
|
+
return await serveThroughKit(app, options, testDb)
|
|
205
219
|
} catch (error) {
|
|
206
220
|
// The schema and its roles exist from here on: a failed start drops them as a stop does.
|
|
207
|
-
await
|
|
221
|
+
await testDb?.close()
|
|
208
222
|
throw error
|
|
209
223
|
}
|
|
210
224
|
}
|
|
@@ -232,18 +246,18 @@ const printHandlerError = (where: string, error: unknown): void => {
|
|
|
232
246
|
}
|
|
233
247
|
|
|
234
248
|
/**
|
|
235
|
-
* The server over the kit of `app`, on `
|
|
249
|
+
* The server over the kit of `app`, on `testDb` when it has a data layer; its `stop` also drops a Postgres schema. The dev
|
|
236
250
|
* outbox captures the process's `fetch` from before the seed runs until `stop`, or until a failed start.
|
|
237
251
|
*/
|
|
238
252
|
async function serveThroughKit(
|
|
239
253
|
app: ContractImplementation<AnyContract>,
|
|
240
254
|
options: AppDevOptions,
|
|
241
|
-
|
|
255
|
+
testDb: TestDatabase | null,
|
|
242
256
|
): Promise<AppDevServer> {
|
|
243
257
|
const outbox = devOutbox()
|
|
244
258
|
const restoreFetch = outbox.install()
|
|
245
259
|
try {
|
|
246
|
-
return await serveDevKit(app, options,
|
|
260
|
+
return await serveDevKit(app, options, testDb, outbox, restoreFetch)
|
|
247
261
|
} catch (error) {
|
|
248
262
|
restoreFetch()
|
|
249
263
|
throw error
|
|
@@ -253,7 +267,7 @@ async function serveThroughKit(
|
|
|
253
267
|
async function serveDevKit(
|
|
254
268
|
app: ContractImplementation<AnyContract>,
|
|
255
269
|
options: AppDevOptions,
|
|
256
|
-
|
|
270
|
+
testDb: TestDatabase | null,
|
|
257
271
|
outbox: DevOutbox,
|
|
258
272
|
restoreFetch: () => void,
|
|
259
273
|
): Promise<AppDevServer> {
|
|
@@ -263,7 +277,7 @@ async function serveDevKit(
|
|
|
263
277
|
const dev = devKit(app, {
|
|
264
278
|
root: options.root,
|
|
265
279
|
env: { ...applicationVariables(options.env), ...readDevEnv(options.root) },
|
|
266
|
-
...(
|
|
280
|
+
...(testDb === null ? {} : { database: testDb.database }),
|
|
267
281
|
...(hasFiles ? { files: new MemoryFileObjects() } : {}),
|
|
268
282
|
revealHandlerErrors: printHandlerError,
|
|
269
283
|
})
|
|
@@ -561,7 +575,7 @@ async function serveDevKit(
|
|
|
561
575
|
await server.stop(true)
|
|
562
576
|
} finally {
|
|
563
577
|
restoreFetch()
|
|
564
|
-
await
|
|
578
|
+
await testDb?.close()
|
|
565
579
|
}
|
|
566
580
|
},
|
|
567
581
|
}
|
package/src/control.ts
CHANGED
|
@@ -11,9 +11,11 @@
|
|
|
11
11
|
|
|
12
12
|
import { createRpcClient, type InferRpcClient, RpcError } from '@fabrika/app'
|
|
13
13
|
import { type IssueKeyInput, type IssueKeyResult, MAX_KEY_LIFETIME_SECONDS } from '@fabrika/auth-core'
|
|
14
|
+
import { APP_ENV_KINDS } from '@fabrika/control-contract'
|
|
14
15
|
import type {
|
|
15
16
|
AppDto,
|
|
16
17
|
AppEnvDto,
|
|
18
|
+
AppEnvKind,
|
|
17
19
|
AppSecretDto,
|
|
18
20
|
ControlRpcContract,
|
|
19
21
|
DeploymentNamespaceDetailDto,
|
|
@@ -56,7 +58,7 @@ Usage:
|
|
|
56
58
|
fabrika control apps environments list --app=<id>
|
|
57
59
|
fabrika control apps environments put --provider=<name> --app=<id> --env=<name> --manifest=<path>
|
|
58
60
|
[--domain=<host>] [--public-origin=<url>] [--trigger-ref=<ref>] [--namespace=<id>]
|
|
59
|
-
[--cross-origin=<origin> ...]
|
|
61
|
+
[--cross-origin=<origin> ...] [--kind=standard|dev]
|
|
60
62
|
fabrika control apps variables list --app=<id>
|
|
61
63
|
fabrika control apps variables put --app=<id> --name=<name> --value=<text> [--env=<name>]
|
|
62
64
|
fabrika control apps variables delete --app=<id> --name=<name> [--env=<name>]
|
|
@@ -73,6 +75,7 @@ Usage:
|
|
|
73
75
|
fabrika control namespaces reconcile --namespace=<id>
|
|
74
76
|
fabrika control namespaces update --namespace=<id> --proxy-source=current
|
|
75
77
|
fabrika control namespaces remove --namespace=<id>
|
|
78
|
+
fabrika control namespaces release-claims --namespace=<id> --app=<id> --env=<name>
|
|
76
79
|
fabrika control deploy --app=<id> --env=<name> [--ref=<ref>]
|
|
77
80
|
fabrika control runs list [--app=<id>] [--env=<name>] [--limit=<n>]
|
|
78
81
|
fabrika control runs get --run=<id>
|
|
@@ -125,6 +128,11 @@ Namespace placement options, each defaulting to what the preset would choose:
|
|
|
125
128
|
SERIOUS is a deliberate choice: a project cannot be downgraded again
|
|
126
129
|
--public-access=<custom-domain|zerops-subdomain>
|
|
127
130
|
--exclusive-app=<id> required by, and only by, the \`full\` preset
|
|
131
|
+
--postgres-type=<type> the \`cheap\` preset's shared PostgreSQL; on Zerops postgresql:single@18
|
|
132
|
+
(default) or postgresql:ha@18, which keeps its data through a node loss.
|
|
133
|
+
Fixed once created
|
|
134
|
+
--postgres-profile=<profile> its profile, given together with --postgres-type: oltp-hobby for single,
|
|
135
|
+
oltp-staging (about $11) or oltp-production (about $72) for HA
|
|
128
136
|
|
|
129
137
|
\`namespaces plan\` is a preview and changes nothing. It prints one \`<path>\\t<value>\` row per field of
|
|
130
138
|
the plan, keyed by its path in \`--json\`; a multi-line value such as the proxy's descriptor file is shown
|
|
@@ -137,6 +145,10 @@ the provider resources it stopped tracking. \`namespaces update --proxy-source=c
|
|
|
137
145
|
proxy to the source this control plane deploys new placements from — a placement keeps the one it was created
|
|
138
146
|
with until you do — and queues the reconcile that rebuilds the proxy from it; a \`failed\` placement accepts it.
|
|
139
147
|
|
|
148
|
+
\`namespaces release-claims\` frees the resource names one app environment holds in a placement, which an
|
|
149
|
+
environment or app delete otherwise refuses over. Delete those resources at the provider first: the release
|
|
150
|
+
reads each one back and refuses, naming it, while any still exists. It prints one released key per line.
|
|
151
|
+
|
|
140
152
|
Every command accepts --json, which prints the procedure's result verbatim.
|
|
141
153
|
|
|
142
154
|
The control origin is not a credential and takes either form:
|
|
@@ -577,6 +589,7 @@ const runEnvironments = async (
|
|
|
577
589
|
const origins = crossOrigins(flags)
|
|
578
590
|
const triggerRef = optional(flags, 'trigger-ref')
|
|
579
591
|
const namespaceId = optional(flags, 'namespace')
|
|
592
|
+
const kind = environmentKind(flags)
|
|
580
593
|
const environment: PutAppEnvRequest = {
|
|
581
594
|
// The same empty placeholder `register` sends: the target is DISCOVERED from the manifest.
|
|
582
595
|
target: { provider, version, payload: {} },
|
|
@@ -586,6 +599,7 @@ const runEnvironments = async (
|
|
|
586
599
|
...(origins === undefined ? {} : { crossOrigins: origins }),
|
|
587
600
|
...(triggerRef === undefined ? {} : { triggerRef }),
|
|
588
601
|
...(namespaceId === undefined ? {} : { namespaceId }),
|
|
602
|
+
...(kind === undefined ? {} : { kind }),
|
|
589
603
|
}
|
|
590
604
|
const result = await client.apps.environments.put({ appId: required(flags, 'app'), env: required(flags, 'env'), environment })
|
|
591
605
|
emit(flags, result, () => `${result.appId}\t${result.env}\t${result.provider}`)
|
|
@@ -594,6 +608,15 @@ const runEnvironments = async (
|
|
|
594
608
|
throw new Error(`Unknown \`control apps environments\` verb: ${verb ?? '(missing)'}`)
|
|
595
609
|
}
|
|
596
610
|
|
|
611
|
+
/** `--kind`, set only when the environment is created: a `dev` environment follows one workspace (ADR-0049). */
|
|
612
|
+
const environmentKind = (flags: Flags): AppEnvKind | undefined => {
|
|
613
|
+
const kind = optional(flags, 'kind')
|
|
614
|
+
if (kind === undefined) return undefined
|
|
615
|
+
const known = APP_ENV_KINDS.find((candidate) => candidate === kind)
|
|
616
|
+
if (known === undefined) throw new Error(`--kind must be one of ${APP_ENV_KINDS.join(', ')}`)
|
|
617
|
+
return known
|
|
618
|
+
}
|
|
619
|
+
|
|
597
620
|
/** One environment per line; the cross origins are comma-joined, `-` when it lists none (a Control older than the field included). */
|
|
598
621
|
export const environmentLine = (item: Pick<AppEnvDto, 'appId' | 'env' | 'provider' | 'domain'> & Partial<Pick<AppEnvDto, 'crossOrigins'>>): string =>
|
|
599
622
|
`${item.appId}\t${item.env}\t${item.provider}\t${item.domain ?? '-'}\t${
|
|
@@ -826,6 +849,11 @@ const namespacePlan = (flags: Flags): PlanDeploymentNamespaceRequest => {
|
|
|
826
849
|
if (project !== undefined) options['projectName'] = project
|
|
827
850
|
if (corePackage !== undefined) options['corePackage'] = corePackage
|
|
828
851
|
if (publicAccess !== undefined) options['publicAccess'] = publicAccess
|
|
852
|
+
const postgresType = optional(flags, 'postgres-type')
|
|
853
|
+
const postgresProfile = optional(flags, 'postgres-profile')
|
|
854
|
+
// Together or not at all: a type without a profile gets the platform's default, which for HA is the dedicated ~$72 one.
|
|
855
|
+
if ((postgresType === undefined) !== (postgresProfile === undefined)) throw new Error('--postgres-type and --postgres-profile go together')
|
|
856
|
+
if (postgresType !== undefined && postgresProfile !== undefined) options['postgres'] = { type: postgresType, profile: postgresProfile }
|
|
829
857
|
return {
|
|
830
858
|
id: required(flags, 'namespace'),
|
|
831
859
|
env: required(flags, 'env'),
|
|
@@ -871,6 +899,15 @@ const runNamespaces = async (verb: string | undefined, flags: Flags, env: Readon
|
|
|
871
899
|
emit(flags, result, () => namespaceLine(result.removed))
|
|
872
900
|
return
|
|
873
901
|
}
|
|
902
|
+
if (verb === 'release-claims') {
|
|
903
|
+
const result = await client.namespaces.releaseClaims({
|
|
904
|
+
namespaceId: required(flags, 'namespace'),
|
|
905
|
+
appId: required(flags, 'app'),
|
|
906
|
+
env: required(flags, 'env'),
|
|
907
|
+
})
|
|
908
|
+
emit(flags, result, () => result.released.map((key) => `released\t${key}`).join('\n'))
|
|
909
|
+
return
|
|
910
|
+
}
|
|
874
911
|
if (verb === 'update') {
|
|
875
912
|
const namespaceId = required(flags, 'namespace')
|
|
876
913
|
if (required(flags, 'proxy-source') !== 'current') {
|
package/src/db.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
+
import { applicationMigrations as sqliteApplicationMigrations } from '@fabrika/app/build'
|
|
1
2
|
import {
|
|
3
|
+
type ApplicationDialect,
|
|
4
|
+
applicationDialect,
|
|
5
|
+
CONFIG_FILE,
|
|
2
6
|
type Finding,
|
|
3
7
|
formatFinding,
|
|
4
8
|
GENERATED_TEST_HEADER,
|
|
@@ -9,8 +13,11 @@ import {
|
|
|
9
13
|
scaffoldInputs,
|
|
10
14
|
} from '@fabrika/check'
|
|
11
15
|
import { CodegenError, generateSchema, SCHEMA_FILE } from '@fabrika/db/codegen'
|
|
16
|
+
import { generateSqliteSchema } from '@fabrika/db/codegen-sqlite'
|
|
12
17
|
import { FRAMEWORK_MIGRATION_BUNDLE, FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations'
|
|
18
|
+
import { SQLITE_FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations-sqlite'
|
|
13
19
|
import {
|
|
20
|
+
APPLICATION_MIGRATION_BUNDLE,
|
|
14
21
|
CONNECTION_CAPACITY_MESSAGE,
|
|
15
22
|
ConnectionCapacityError,
|
|
16
23
|
createTestProvisioner,
|
|
@@ -35,7 +42,7 @@ import { readJunitCases } from './junit'
|
|
|
35
42
|
const MIGRATIONS_DIR = 'db/migrations'
|
|
36
43
|
const SLUG = /^[a-z0-9]+(?:_[a-z0-9]+)*$/
|
|
37
44
|
|
|
38
|
-
export const DB_USAGE = `fabrika db — an application's Postgres
|
|
45
|
+
export const DB_USAGE = `fabrika db — an application's database schema: Postgres, or SQLite on Cloudflare
|
|
39
46
|
|
|
40
47
|
Usage:
|
|
41
48
|
fabrika db new <slug> Write ${MIGRATIONS_DIR}/<UTC YYYYMMDDHHMMSS>_<slug>.sql; the slug is lowercase snake_case.
|
|
@@ -59,6 +66,10 @@ bunfig.toml, and checks the JUnit report against the case names the scaffold wro
|
|
|
59
66
|
that killed runs left behind: expired, and without a session of their own or of a role they created. A database at its
|
|
60
67
|
connection limit (SQLSTATE ${TOO_MANY_CONNECTIONS}) is waited for; one that never frees a slot fails the run saying so,
|
|
61
68
|
never as failed cases.
|
|
69
|
+
|
|
70
|
+
An application whose ${CONFIG_FILE} default-exports @fabrika/provider-cloudflare's defineApp runs on SQLite in its
|
|
71
|
+
Durable Object, which applies the migrations itself when it boots: \`migrate\` refuses, \`codegen\` applies them to an
|
|
72
|
+
in-memory database, and the generated tests run on @fabrika/db/testing-sqlite; none of them needs a database URL.
|
|
62
73
|
`
|
|
63
74
|
|
|
64
75
|
export interface DbCommandDependencies {
|
|
@@ -79,6 +90,12 @@ const refuseArguments = (command: string, argv: readonly string[]): void => {
|
|
|
79
90
|
if (argv.length > 0) throw new Error(`db ${command} takes no argument ${argv[0]}\n\n${DB_USAGE}`)
|
|
80
91
|
}
|
|
81
92
|
|
|
93
|
+
/** The dialect `fabrika.config.ts` names, read as the checker reads it; Postgres without a config. */
|
|
94
|
+
const dialectAt = async (cwd: string): Promise<ApplicationDialect> => {
|
|
95
|
+
const config = await readFile(join(cwd, CONFIG_FILE), 'utf8').catch(() => undefined)
|
|
96
|
+
return applicationDialect(new Map(config === undefined ? [] : [[CONFIG_FILE, config]]))
|
|
97
|
+
}
|
|
98
|
+
|
|
82
99
|
const timestamp = (date: Date): string => date.toISOString().replace(/\.\d{3}Z$/, '').replaceAll(/[-:T]/g, '')
|
|
83
100
|
|
|
84
101
|
const newMigration = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
@@ -126,6 +143,11 @@ const applicationMigrations = (appId: string, cwd: string): PostgresApplicationM
|
|
|
126
143
|
|
|
127
144
|
const migrate = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
128
145
|
refuseArguments('migrate', argv)
|
|
146
|
+
if ((await dialectAt(deps.cwd)) === 'sqlite') {
|
|
147
|
+
throw new Error(
|
|
148
|
+
'db migrate: an application on Cloudflare migrates its own SQLite database when its Durable Object boots (ADR-0065); there is nothing to run',
|
|
149
|
+
)
|
|
150
|
+
}
|
|
129
151
|
const migrations = applicationMigrations(required(deps.source, 'FABRIKA_APP_ID'), deps.cwd)
|
|
130
152
|
const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
|
|
131
153
|
const files = migrations.read()
|
|
@@ -137,18 +159,29 @@ const migrate = async (argv: readonly string[], deps: DbCommandDependencies): Pr
|
|
|
137
159
|
}
|
|
138
160
|
}
|
|
139
161
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
refuseArguments('codegen', argv.filter((arg) => arg !== '--verify'))
|
|
162
|
+
/** The schema module of the migrated application schema, read with the provisioning credential. */
|
|
163
|
+
const postgresSchema = async (deps: DbCommandDependencies): Promise<string> => {
|
|
143
164
|
const migrations = applicationMigrations(required(deps.source, 'FABRIKA_APP_ID'), deps.cwd)
|
|
144
165
|
const url = required(deps.source, 'FABRIKA_APP_DATABASE_URL')
|
|
145
|
-
let source: string
|
|
146
166
|
try {
|
|
147
167
|
// The migrations' manifest: the start check refuses any database object no migration declares.
|
|
148
|
-
|
|
168
|
+
return await generateSchema(url, migrations.schema, migrations.objects())
|
|
149
169
|
} catch (error) {
|
|
150
170
|
throw reportable(error)
|
|
151
171
|
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The schema module of the bundles the Durable Object applies, in its order, run in an in-memory database. */
|
|
175
|
+
const sqliteSchema = async (cwd: string): Promise<string> =>
|
|
176
|
+
generateSqliteSchema([
|
|
177
|
+
{ bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: SQLITE_FRAMEWORK_MIGRATIONS },
|
|
178
|
+
{ bundle: APPLICATION_MIGRATION_BUNDLE, migrations: await sqliteApplicationMigrations(cwd) },
|
|
179
|
+
])
|
|
180
|
+
|
|
181
|
+
const codegen = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
182
|
+
const verify = argv.includes('--verify')
|
|
183
|
+
refuseArguments('codegen', argv.filter((arg) => arg !== '--verify'))
|
|
184
|
+
const source = (await dialectAt(deps.cwd)) === 'sqlite' ? await sqliteSchema(deps.cwd) : await postgresSchema(deps)
|
|
152
185
|
const path = join(deps.cwd, SCHEMA_FILE)
|
|
153
186
|
if (verify) {
|
|
154
187
|
const committed = await readFile(path, 'utf8').catch(() => undefined)
|
|
@@ -168,7 +201,11 @@ const expectedTests = async (
|
|
|
168
201
|
> => {
|
|
169
202
|
const { files } = await readApplicationTree(cwd)
|
|
170
203
|
const inputs = scaffoldInputs(files)
|
|
171
|
-
return {
|
|
204
|
+
return {
|
|
205
|
+
files,
|
|
206
|
+
tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures, inputs.dialect),
|
|
207
|
+
missing: missingEndpointFixtures(inputs),
|
|
208
|
+
}
|
|
172
209
|
}
|
|
173
210
|
|
|
174
211
|
const testScaffold = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
@@ -194,11 +231,12 @@ const testScaffold = async (argv: readonly string[], deps: DbCommandDependencies
|
|
|
194
231
|
}
|
|
195
232
|
|
|
196
233
|
/**
|
|
197
|
-
* Only what Bun needs to run; the URL arrives as the kit's own variable, and no framework variable is passed
|
|
198
|
-
* a throwaway provisioner's, never FABRIKA_APP_DATABASE_URL: the generated tests load application code.
|
|
234
|
+
* Only what Bun needs to run; on Postgres the URL arrives as the kit's own variable, and no framework variable is passed
|
|
235
|
+
* on. It is a throwaway provisioner's, never FABRIKA_APP_DATABASE_URL: the generated tests load application code. The
|
|
236
|
+
* SQLite kit opens an in-memory database and needs none.
|
|
199
237
|
*/
|
|
200
|
-
const testEnvironment = (source: DbCommandDependencies['source'], url: string): Record<string, string> => {
|
|
201
|
-
const environment: Record<string, string> = { FABRIKA_TEST_POSTGRES_URL: url, FABRIKA_TEST_POSTGRES_REQUIRED: '1' }
|
|
238
|
+
const testEnvironment = (source: DbCommandDependencies['source'], url: string | undefined): Record<string, string> => {
|
|
239
|
+
const environment: Record<string, string> = url === undefined ? {} : { FABRIKA_TEST_POSTGRES_URL: url, FABRIKA_TEST_POSTGRES_REQUIRED: '1' }
|
|
202
240
|
for (const name of ['PATH', 'HOME', 'TMPDIR']) {
|
|
203
241
|
const value = source[name]
|
|
204
242
|
if (value !== undefined) environment[name] = value
|
|
@@ -226,11 +264,13 @@ export const reportsExhaustedConnections = (output: string): boolean => EXHAUSTE
|
|
|
226
264
|
* application applies, and the platform's preload, which captures Bun's test functions before the application loads.
|
|
227
265
|
* Fails unless every case the scaffold wrote is reported as passed with an assertion. The child's output is never
|
|
228
266
|
* printed, because a dependency may write a credential into it; `--verbose`, which the platform never passes, prints it.
|
|
267
|
+
* On Postgres they run as a throwaway provisioner, dropped afterwards; on SQLite with no database URL at all.
|
|
229
268
|
*/
|
|
230
269
|
const testIsolation = async (argv: readonly string[], deps: DbCommandDependencies): Promise<void> => {
|
|
231
270
|
const verbose = argv.includes('--verbose')
|
|
232
271
|
refuseArguments('test-isolation', argv.filter((arg) => arg !== '--verbose'))
|
|
233
|
-
const
|
|
272
|
+
const sqlite = (await dialectAt(deps.cwd)) === 'sqlite'
|
|
273
|
+
const url = sqlite ? undefined : required(deps.source, 'FABRIKA_APP_DATABASE_URL')
|
|
234
274
|
const { files, tests, missing } = await expectedTests(deps.cwd)
|
|
235
275
|
if (missing.length > 0) throw new Error(`db test-isolation: the endpoint access tests are incomplete\n${missing.map(formatFinding).join('\n')}`)
|
|
236
276
|
for (const [path, { text }] of tests) {
|
|
@@ -240,6 +280,10 @@ const testIsolation = async (argv: readonly string[], deps: DbCommandDependencie
|
|
|
240
280
|
deps.write('no generated tests\n')
|
|
241
281
|
return
|
|
242
282
|
}
|
|
283
|
+
if (url === undefined) {
|
|
284
|
+
await runGeneratedTests(tests, verbose, testEnvironment(deps.source, undefined), deps)
|
|
285
|
+
return
|
|
286
|
+
}
|
|
243
287
|
let provisioner: TestProvisioner
|
|
244
288
|
try {
|
|
245
289
|
provisioner = await withConnectionCapacity(() => createTestProvisioner(url))
|
|
@@ -247,6 +291,21 @@ const testIsolation = async (argv: readonly string[], deps: DbCommandDependencie
|
|
|
247
291
|
throw reportable(error)
|
|
248
292
|
}
|
|
249
293
|
if (provisioner.swept.length > 0) deps.write(`dropped the test provisioners earlier runs left behind: ${provisioner.swept.join(', ')}\n`)
|
|
294
|
+
try {
|
|
295
|
+
await runGeneratedTests(tests, verbose, testEnvironment(deps.source, provisioner.url), deps)
|
|
296
|
+
} finally {
|
|
297
|
+
await withConnectionCapacity(() => provisioner.drop()).catch((error: unknown) => {
|
|
298
|
+
throw reportable(error)
|
|
299
|
+
})
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const runGeneratedTests = async (
|
|
304
|
+
tests: ReadonlyMap<string, GeneratedTest>,
|
|
305
|
+
verbose: boolean,
|
|
306
|
+
env: Record<string, string>,
|
|
307
|
+
deps: DbCommandDependencies,
|
|
308
|
+
): Promise<void> => {
|
|
250
309
|
const scratch = await mkdtemp(join(tmpdir(), 'fabrika-test-isolation-'))
|
|
251
310
|
try {
|
|
252
311
|
await writeFile(join(scratch, 'bunfig.toml'), '')
|
|
@@ -261,7 +320,7 @@ const testIsolation = async (argv: readonly string[], deps: DbCommandDependencie
|
|
|
261
320
|
'--reporter=junit',
|
|
262
321
|
`--reporter-outfile=${report}`,
|
|
263
322
|
],
|
|
264
|
-
{ cwd: deps.cwd, env
|
|
323
|
+
{ cwd: deps.cwd, env, stdout: 'pipe', stderr: 'pipe' },
|
|
265
324
|
)
|
|
266
325
|
const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited])
|
|
267
326
|
if (verbose) deps.write(`${stdout}${stderr}\n`)
|
|
@@ -296,9 +355,6 @@ const testIsolation = async (argv: readonly string[], deps: DbCommandDependencie
|
|
|
296
355
|
deps.write(`${total} generated cases passed\n`)
|
|
297
356
|
} finally {
|
|
298
357
|
await rm(scratch, { recursive: true, force: true })
|
|
299
|
-
await withConnectionCapacity(() => provisioner.drop()).catch((error: unknown) => {
|
|
300
|
-
throw reportable(error)
|
|
301
|
-
})
|
|
302
358
|
}
|
|
303
359
|
}
|
|
304
360
|
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { CONTRACT_FILE, type EntryRuntime, writeGeneratedEntry } from '@fabrika/app/build'
|
|
4
4
|
import { authoredAppProvider } from '@fabrika/provider-contract'
|
|
5
|
+
import { type AppCli, appCliFromModule, type NamespaceCli } from '@fabrika/provider-contract/app-cli'
|
|
5
6
|
import { installationCliFromModule, isInstallationCommand, supportsInstallationCommand } from '@fabrika/provider-contract/installation'
|
|
6
7
|
import { dirname, join, relative, resolve } from 'node:path'
|
|
7
8
|
import { CONTROL_USAGE, registerCompiledManifest, runControlCli } from './control.js'
|
|
@@ -152,41 +153,33 @@ const requireInstalled = (specifier: string, command: string): void => {
|
|
|
152
153
|
}
|
|
153
154
|
}
|
|
154
155
|
|
|
156
|
+
/** A provider id names its package, `@fabrika/provider-<id>`; anything else is a module specifier of its own. */
|
|
157
|
+
const PROVIDER_ID = /^[a-z][a-z0-9-]*$/
|
|
158
|
+
|
|
159
|
+
const installationSpecifier = (provider: string): string => PROVIDER_ID.test(provider) ? `@fabrika/provider-${provider}/installation` : provider
|
|
160
|
+
|
|
155
161
|
const installationModule = async (provider: string, command: string): Promise<unknown> => {
|
|
156
|
-
const specifier = provider
|
|
157
|
-
? '@fabrika/provider-cloudflare/installation'
|
|
158
|
-
: provider === 'zerops'
|
|
159
|
-
? '@fabrika/provider-zerops/installation'
|
|
160
|
-
: provider
|
|
162
|
+
const specifier = installationSpecifier(provider)
|
|
161
163
|
requireInstalled(specifier, command)
|
|
162
164
|
return import(specifier)
|
|
163
165
|
}
|
|
164
166
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
const runner = Reflect.get(loaded, exportName)
|
|
172
|
-
if (typeof runner !== 'function') {
|
|
173
|
-
throw new Error(`${packageName} must export \`${exportName}\` as a function`)
|
|
174
|
-
}
|
|
175
|
-
return runner
|
|
167
|
+
/** App and namespace commands take a provider id only: the module's `appCli` must name the same one. */
|
|
168
|
+
const providerAppCli = async (provider: string, command: string): Promise<AppCli> => {
|
|
169
|
+
if (!PROVIDER_ID.test(provider)) throw new Error(`\`${command}\` takes a provider id ([a-z][a-z0-9-]*), not "${provider}"`)
|
|
170
|
+
const specifier = `@fabrika/provider-${provider}/cli`
|
|
171
|
+
requireInstalled(specifier, command)
|
|
172
|
+
return appCliFromModule(await import(specifier), provider, specifier)
|
|
176
173
|
}
|
|
177
174
|
|
|
178
|
-
const
|
|
179
|
-
requireInstalled(packageName, command)
|
|
180
|
-
const loaded: unknown = await import(packageName)
|
|
181
|
-
return appCliRunnerFromModule(loaded, packageName, exportName)
|
|
182
|
-
}
|
|
175
|
+
const unsupported = (provider: string, command: string): Error => new Error(`${provider} app tooling does not support \`${command}\``)
|
|
183
176
|
|
|
184
177
|
const runPlatform = async (parsed: ParsedCommand): Promise<void> => {
|
|
185
178
|
if (!isInstallationCommand(parsed.command)) {
|
|
186
179
|
throw new Error(`Unknown platform command: ${parsed.command ?? '(missing)'}`)
|
|
187
180
|
}
|
|
188
181
|
const provider = requireExplicitProvider(parsed)
|
|
189
|
-
const expectedProvider = provider
|
|
182
|
+
const expectedProvider = PROVIDER_ID.test(provider) ? provider : undefined
|
|
190
183
|
const installation = installationCliFromModule(
|
|
191
184
|
await installationModule(provider, `fabrika platform ${parsed.command} --provider=${provider}`),
|
|
192
185
|
expectedProvider,
|
|
@@ -202,17 +195,12 @@ const runAppRegister = async (parsed: ParsedCommand): Promise<void> => {
|
|
|
202
195
|
const config = configPath(parsed.rest)
|
|
203
196
|
await registerCompiledManifest(parsed.rest, async (env) => {
|
|
204
197
|
const provider = await selectedAppProvider(parsed)
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
}
|
|
208
|
-
requireInstalled('@fabrika/provider-zerops/cli', 'fabrika app register')
|
|
209
|
-
const { buildZeropsManifestText } = await import('@fabrika/provider-zerops/cli')
|
|
210
|
-
return { provider, text: await buildZeropsManifestText({ config, env }) }
|
|
198
|
+
const cli = await providerAppCli(provider, 'fabrika app register')
|
|
199
|
+
if (cli.registrationManifest === undefined) throw unsupported(provider, 'app register')
|
|
200
|
+
return { provider, text: await cli.registrationManifest({ config, env }) }
|
|
211
201
|
})
|
|
212
202
|
}
|
|
213
203
|
|
|
214
|
-
const ENTRY_RUNTIMES: Readonly<Record<string, EntryRuntime>> = { cloudflare: 'cloudflare', zerops: 'bun' }
|
|
215
|
-
|
|
216
204
|
/** A contract application gets its generated entrypoint before the provider builds it. False when it is none. */
|
|
217
205
|
const writeContractEntry = async (argv: readonly string[], runtime: EntryRuntime): Promise<boolean> => {
|
|
218
206
|
const root = dirname(resolve(process.cwd(), configPath(argv)))
|
|
@@ -235,41 +223,37 @@ const runApp = async (parsed: ParsedCommand): Promise<void> => {
|
|
|
235
223
|
return
|
|
236
224
|
}
|
|
237
225
|
const provider = await selectedAppProvider(parsed)
|
|
238
|
-
const
|
|
239
|
-
const
|
|
240
|
-
if (
|
|
241
|
-
|
|
242
|
-
return
|
|
243
|
-
}
|
|
244
|
-
if (parsed.command !== 'deploy') {
|
|
245
|
-
throw new Error(`Cloudflare app tooling does not support \`app ${parsed.command ?? '(missing)'}\``)
|
|
246
|
-
}
|
|
247
|
-
const runCloudflareCli = await appCliRunner('@fabrika/provider-cloudflare/cli', 'runCloudflareCli', 'fabrika app deploy')
|
|
248
|
-
await runCloudflareCli(['deploy', ...parsed.rest])
|
|
226
|
+
const command = `app ${parsed.command ?? '(missing)'}`
|
|
227
|
+
const cli = await providerAppCli(provider, `fabrika ${command}`)
|
|
228
|
+
if (parsed.command === 'build' && cli.build !== undefined) {
|
|
229
|
+
await cli.build(parsed.rest, { contract: await writeContractEntry(parsed.rest, cli.entryRuntime) })
|
|
249
230
|
return
|
|
250
231
|
}
|
|
251
|
-
if (
|
|
252
|
-
|
|
253
|
-
throw new Error(`Zerops app tooling does not support \`app ${parsed.command ?? '(missing)'}\``)
|
|
254
|
-
}
|
|
255
|
-
const runZeropsCli = await appCliRunner('@fabrika/provider-zerops/cli', 'runZeropsCli', 'fabrika app build')
|
|
256
|
-
await runZeropsCli(['build', ...parsed.rest])
|
|
232
|
+
if (parsed.command === 'deploy' && cli.deploy !== undefined) {
|
|
233
|
+
await cli.deploy(parsed.rest)
|
|
257
234
|
return
|
|
258
235
|
}
|
|
259
|
-
throw
|
|
236
|
+
throw unsupported(provider, command)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const namespaceCli = async (provider: string): Promise<NamespaceCli> => {
|
|
240
|
+
const cli = await providerAppCli(provider, 'fabrika namespace')
|
|
241
|
+
if (cli.namespaces === undefined) throw new Error(`Provider ${provider} does not expose deployment namespaces`)
|
|
242
|
+
return cli.namespaces
|
|
260
243
|
}
|
|
261
244
|
|
|
262
245
|
const runNamespace = async (parsed: ParsedCommand): Promise<void> => {
|
|
263
246
|
const provider = requireExplicitProvider(parsed)
|
|
264
|
-
|
|
265
|
-
throw new Error(`Provider ${provider} does not expose deployment namespaces`)
|
|
266
|
-
}
|
|
247
|
+
const cli = await namespaceCli(provider)
|
|
267
248
|
if (parsed.command === undefined) {
|
|
268
249
|
throw new Error('Namespace command is required')
|
|
269
250
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
251
|
+
const { runNamespaceCommand } = await import('./namespace.js')
|
|
252
|
+
await runNamespaceCommand(cli, parsed.command, parsed.rest, {
|
|
253
|
+
source: process.env,
|
|
254
|
+
fetch: globalThis.fetch,
|
|
255
|
+
write: (value) => console.info(value.trimEnd()),
|
|
256
|
+
})
|
|
273
257
|
}
|
|
274
258
|
|
|
275
259
|
export const runCli = async (argv: readonly string[]): Promise<void> => {
|
|
@@ -285,7 +269,10 @@ export const runCli = async (argv: readonly string[]): Promise<void> => {
|
|
|
285
269
|
return
|
|
286
270
|
}
|
|
287
271
|
if (parsed.help && parsed.area === 'namespace') {
|
|
288
|
-
|
|
272
|
+
if (parsed.provider !== undefined && parsed.provider !== '') {
|
|
273
|
+
console.info((await namespaceCli(parsed.provider)).usage)
|
|
274
|
+
return
|
|
275
|
+
}
|
|
289
276
|
const { NAMESPACE_USAGE } = await import('./namespace.js')
|
|
290
277
|
console.info(NAMESPACE_USAGE)
|
|
291
278
|
return
|