@fabrika/cli 0.9.0-dev.4 → 0.9.0-dev.6

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/cli",
3
- "version": "0.9.0-dev.4",
3
+ "version": "0.9.0-dev.6",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -31,19 +31,19 @@
31
31
  },
32
32
  "dependencies": {
33
33
  "zod": "^3.25.76",
34
- "@fabrika/app": "0.9.0-dev.4",
35
- "@fabrika/auth-core": "0.9.0-dev.4",
36
- "@fabrika/control-contract": "0.9.0-dev.4",
37
- "@fabrika/provider-contract": "0.9.0-dev.4",
38
- "@fabrika/db": "0.9.0-dev.4",
39
- "@fabrika/platform": "0.9.0-dev.4",
40
- "@fabrika/platform-node": "0.9.0-dev.4",
41
- "@fabrika/check": "0.9.0-dev.4"
34
+ "@fabrika/app": "0.9.0-dev.6",
35
+ "@fabrika/auth-core": "0.9.0-dev.6",
36
+ "@fabrika/control-contract": "0.9.0-dev.6",
37
+ "@fabrika/provider-contract": "0.9.0-dev.6",
38
+ "@fabrika/db": "0.9.0-dev.6",
39
+ "@fabrika/platform": "0.9.0-dev.6",
40
+ "@fabrika/platform-node": "0.9.0-dev.6",
41
+ "@fabrika/check": "0.9.0-dev.6"
42
42
  },
43
43
  "peerDependencies": {
44
- "@fabrika/builder": "0.9.0-dev.4",
45
- "@fabrika/provider-cloudflare": "0.9.0-dev.4",
46
- "@fabrika/provider-zerops": "0.9.0-dev.4"
44
+ "@fabrika/builder": "0.9.0-dev.6",
45
+ "@fabrika/provider-cloudflare": "0.9.0-dev.6",
46
+ "@fabrika/provider-zerops": "0.9.0-dev.6"
47
47
  },
48
48
  "peerDependenciesMeta": {
49
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. A seed module fills it through the
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 postgres: TestDatabase | null = null
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
- postgres = await testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
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, postgres)
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 postgres?.close()
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 `postgres` when it has a data layer; its `stop` also drops the schema. The dev
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
- postgres: TestDatabase | null,
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, postgres, outbox, restoreFetch)
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
- postgres: TestDatabase | null,
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
- ...(postgres === null ? {} : { database: postgres.database }),
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 postgres?.close()
578
+ await testDb?.close()
565
579
  }
566
580
  },
567
581
  }
package/src/control.ts CHANGED
@@ -75,6 +75,7 @@ Usage:
75
75
  fabrika control namespaces reconcile --namespace=<id>
76
76
  fabrika control namespaces update --namespace=<id> --proxy-source=current
77
77
  fabrika control namespaces remove --namespace=<id>
78
+ fabrika control namespaces release-claims --namespace=<id> --app=<id> --env=<name>
78
79
  fabrika control deploy --app=<id> --env=<name> [--ref=<ref>]
79
80
  fabrika control runs list [--app=<id>] [--env=<name>] [--limit=<n>]
80
81
  fabrika control runs get --run=<id>
@@ -127,6 +128,11 @@ Namespace placement options, each defaulting to what the preset would choose:
127
128
  SERIOUS is a deliberate choice: a project cannot be downgraded again
128
129
  --public-access=<custom-domain|zerops-subdomain>
129
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
130
136
 
131
137
  \`namespaces plan\` is a preview and changes nothing. It prints one \`<path>\\t<value>\` row per field of
132
138
  the plan, keyed by its path in \`--json\`; a multi-line value such as the proxy's descriptor file is shown
@@ -139,6 +145,10 @@ the provider resources it stopped tracking. \`namespaces update --proxy-source=c
139
145
  proxy to the source this control plane deploys new placements from — a placement keeps the one it was created
140
146
  with until you do — and queues the reconcile that rebuilds the proxy from it; a \`failed\` placement accepts it.
141
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
+
142
152
  Every command accepts --json, which prints the procedure's result verbatim.
143
153
 
144
154
  The control origin is not a credential and takes either form:
@@ -268,21 +278,85 @@ const secret = (variable: string, env: Readonly<Record<string, string | undefine
268
278
  }
269
279
 
270
280
  /** The console's client with a bearer instead of a cookie, and no SSO bounce: there is no browser to send. */
271
- type ControlClient = InferRpcClient<ControlRpcContract>
281
+ export type ControlClient = InferRpcClient<ControlRpcContract>
282
+
283
+ /** Plain http may carry the key to loopback only: 127.0.0.0/8, [::1], and the names RFC 6761 reserves for it, `localhost` and `*.localhost`. */
284
+ const LOOPBACK_HOST = /^(?:localhost|.+\.localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[::1\])$/
285
+
286
+ /**
287
+ * Control's origin, checked before the key is sent anywhere: https, or http to a loopback host for local development,
288
+ * and nothing but scheme, host and port. A refusal never repeats the value, which may hold userinfo.
289
+ */
290
+ export const controlOrigin = (raw: string | undefined): string => {
291
+ if (raw === undefined || raw.trim() === '') {
292
+ throw new Error('Control origin is required. Pass --url=<origin> or set FABRIKA_CONTROL_URL.')
293
+ }
294
+ let url: URL
295
+ try {
296
+ url = new URL(raw.trim())
297
+ } catch {
298
+ throw new Error('--url or FABRIKA_CONTROL_URL is not a URL')
299
+ }
300
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK_HOST.test(url.hostname))) {
301
+ throw new Error('--url or FABRIKA_CONTROL_URL must be https; plain http only to localhost, *.localhost, 127.0.0.0/8 or [::1]')
302
+ }
303
+ if (url.username !== '' || url.password !== '' || url.pathname !== '/' || url.search !== '' || url.hash !== '' || /[?#]/.test(raw)) {
304
+ throw new Error('--url or FABRIKA_CONTROL_URL must be an origin only: no credentials, path, query or fragment')
305
+ }
306
+ return url.origin
307
+ }
308
+
309
+ const KEY_LABEL = '[FABRIKA_CONTROL_KEY]'
310
+
311
+ /** `text` with the control key cut out: every diagnostic of an area that holds the key passes through it. */
312
+ export const withoutControlKey = (text: string, env: Readonly<Record<string, string | undefined>>): string => {
313
+ const key = env['FABRIKA_CONTROL_KEY']?.trim()
314
+ return key === undefined || key === '' ? text : text.replaceAll(key, KEY_LABEL)
315
+ }
316
+
317
+ /** Whether a JSON body holds `key`, also behind JSON escapes, which a plain search of the text would miss. */
318
+ const carriesKey = (text: string, key: string): boolean => {
319
+ if (text.includes(key)) return true
320
+ try {
321
+ return JSON.stringify(JSON.parse(text)).includes(JSON.stringify(key).slice(1, -1))
322
+ } catch {
323
+ return false
324
+ }
325
+ }
326
+
327
+ /**
328
+ * A JSON answer that carries the key is dropped whole, so no row, `--json` output or error can repeat it. Any other
329
+ * body passes: the RPC client reports a non-JSON answer by its status alone.
330
+ */
331
+ const withoutEchoedKey = async (response: Response, key: string): Promise<Response> => {
332
+ if (!(response.headers.get('content-type') ?? '').includes('application/json')) return response
333
+ const text = await response.text()
334
+ if (carriesKey(text, key)) {
335
+ return Response.json({ error: { type: 'transport', message: `Control's answer carried ${KEY_LABEL}; it was dropped` } }, { status: 502 })
336
+ }
337
+ return new Response(text, { status: response.status, statusText: response.statusText, headers: response.headers })
338
+ }
272
339
 
273
- const controlClient = (flags: Flags, env: Readonly<Record<string, string | undefined>>): ControlClient => {
274
- const base = origin(flags, 'url', 'FABRIKA_CONTROL_URL', env, 'Control')
340
+ /**
341
+ * The one client of Control that `fabrika control` and `fabrika env` share: the origin from `url` or
342
+ * FABRIKA_CONTROL_URL, the key from FABRIKA_CONTROL_KEY in the environment only, no redirect followed.
343
+ */
344
+ export const connectControl = (url: string | undefined, env: Readonly<Record<string, string | undefined>>): ControlClient => {
345
+ const base = controlOrigin(url ?? env['FABRIKA_CONTROL_URL'])
275
346
  const key = secret('FABRIKA_CONTROL_KEY', env)
276
347
  return createRpcClient<ControlRpcContract>({
277
348
  baseUrl: `${base}/api/rpc`,
278
- fetch: (input, init) => {
349
+ fetch: async (input, init) => {
279
350
  const headers = new Headers(init?.headers)
280
351
  headers.set('authorization', `Bearer ${key}`)
281
- return fetch(input, { ...init, headers })
352
+ // A redirect would carry the bearer to wherever it points.
353
+ return await withoutEchoedKey(await fetch(input, { ...init, headers, redirect: 'manual' }), key)
282
354
  },
283
355
  })
284
356
  }
285
357
 
358
+ const controlClient = (flags: Flags, env: Readonly<Record<string, string | undefined>>): ControlClient => connectControl(flags.values.get('url'), env)
359
+
286
360
  const readJsonFile = async (path: string): Promise<JsonValue> => {
287
361
  const file = Bun.file(path)
288
362
  if (!(await file.exists())) {
@@ -839,6 +913,11 @@ const namespacePlan = (flags: Flags): PlanDeploymentNamespaceRequest => {
839
913
  if (project !== undefined) options['projectName'] = project
840
914
  if (corePackage !== undefined) options['corePackage'] = corePackage
841
915
  if (publicAccess !== undefined) options['publicAccess'] = publicAccess
916
+ const postgresType = optional(flags, 'postgres-type')
917
+ const postgresProfile = optional(flags, 'postgres-profile')
918
+ // Together or not at all: a type without a profile gets the platform's default, which for HA is the dedicated ~$72 one.
919
+ if ((postgresType === undefined) !== (postgresProfile === undefined)) throw new Error('--postgres-type and --postgres-profile go together')
920
+ if (postgresType !== undefined && postgresProfile !== undefined) options['postgres'] = { type: postgresType, profile: postgresProfile }
842
921
  return {
843
922
  id: required(flags, 'namespace'),
844
923
  env: required(flags, 'env'),
@@ -884,6 +963,15 @@ const runNamespaces = async (verb: string | undefined, flags: Flags, env: Readon
884
963
  emit(flags, result, () => namespaceLine(result.removed))
885
964
  return
886
965
  }
966
+ if (verb === 'release-claims') {
967
+ const result = await client.namespaces.releaseClaims({
968
+ namespaceId: required(flags, 'namespace'),
969
+ appId: required(flags, 'app'),
970
+ env: required(flags, 'env'),
971
+ })
972
+ emit(flags, result, () => result.released.map((key) => `released\t${key}`).join('\n'))
973
+ return
974
+ }
887
975
  if (verb === 'update') {
888
976
  const namespaceId = required(flags, 'namespace')
889
977
  if (required(flags, 'proxy-source') !== 'current') {
@@ -938,9 +1026,9 @@ export const runControlCli = async (
938
1026
  env: Readonly<Record<string, string | undefined>> = process.env,
939
1027
  input: SecretValueInput = processStdin,
940
1028
  ): Promise<void> => {
941
- const flags = parseControlFlags(argv)
942
- const verb = flags.positional[0]
943
1029
  try {
1030
+ const flags = parseControlFlags(argv)
1031
+ const verb = flags.positional[0]
944
1032
  switch (command) {
945
1033
  case undefined:
946
1034
  console.info(USAGE)
@@ -970,7 +1058,8 @@ export const runControlCli = async (
970
1058
  } catch (error) {
971
1059
  // An RPC denial is an ANSWER, not a transport fault; keep its type so a caller can tell "the
972
1060
  // control plane said no" from "the control plane was unreachable".
973
- throw error instanceof RpcError ? new Error(`${error.type}: ${error.message}`) : error
1061
+ const message = error instanceof RpcError ? `${error.type}: ${error.message}` : error instanceof Error ? error.message : String(error)
1062
+ throw new Error(withoutControlKey(message, env))
974
1063
  }
975
1064
  }
976
1065