@fabrika/cli 0.9.0-dev.2 → 0.9.0-dev.20

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.2",
3
+ "version": "0.9.0-dev.20",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,24 +26,25 @@
26
26
  }
27
27
  },
28
28
  "scripts": {
29
- "typecheck": "tsc --noEmit",
29
+ "typecheck": "tsrs --build tsconfig.test.json",
30
30
  "test": "bun test"
31
31
  },
32
32
  "dependencies": {
33
33
  "zod": "^3.25.76",
34
- "@fabrika/app": "0.9.0-dev.2",
35
- "@fabrika/auth-core": "0.9.0-dev.2",
36
- "@fabrika/control-contract": "0.9.0-dev.2",
37
- "@fabrika/provider-contract": "0.9.0-dev.2",
38
- "@fabrika/db": "0.9.0-dev.2",
39
- "@fabrika/platform": "0.9.0-dev.2",
40
- "@fabrika/platform-node": "0.9.0-dev.2",
41
- "@fabrika/check": "0.9.0-dev.2"
34
+ "@fabrika/app": "0.9.0-dev.20",
35
+ "@fabrika/auth-core": "0.9.0-dev.20",
36
+ "@fabrika/control-contract": "0.9.0-dev.20",
37
+ "@fabrika/operations-contract": "0.9.0-dev.20",
38
+ "@fabrika/provider-contract": "0.9.0-dev.20",
39
+ "@fabrika/db": "0.9.0-dev.20",
40
+ "@fabrika/platform": "0.9.0-dev.20",
41
+ "@fabrika/platform-node": "0.9.0-dev.20",
42
+ "@fabrika/check": "0.9.0-dev.20"
42
43
  },
43
44
  "peerDependencies": {
44
- "@fabrika/builder": "0.9.0-dev.2",
45
- "@fabrika/provider-cloudflare": "0.9.0-dev.2",
46
- "@fabrika/provider-zerops": "0.9.0-dev.2"
45
+ "@fabrika/builder": "0.9.0-dev.20",
46
+ "@fabrika/provider-cloudflare": "0.9.0-dev.20",
47
+ "@fabrika/provider-zerops": "0.9.0-dev.20"
47
48
  },
48
49
  "peerDependenciesMeta": {
49
50
  "@fabrika/builder": {
@@ -3,6 +3,7 @@
3
3
 
4
4
  import type { AnyContract } from '@fabrika/app/contract'
5
5
  import type { DevKit, PersonTestCaller } from '@fabrika/app/testing'
6
+ import { sameOriginTarget } from '@fabrika/auth-core'
6
7
  import { existsSync } from 'node:fs'
7
8
  import { isAbsolute, join } from 'node:path'
8
9
  import { pathToFileURL } from 'node:url'
@@ -53,11 +54,6 @@ const SeedResult = z.strictObject({
53
54
  scopes: z.record(z.string(), z.array(z.strictObject({ value: Text(MAX_SCOPE_VALUE), label: Text(MAX_NAME) })).max(MAX_ENTRIES)).optional(),
54
55
  }).optional()
55
56
 
56
- /** A path of this origin; a link the application issued is one (`/s/#px_…`). */
57
- export function isLocalPath(path: string): boolean {
58
- return path.startsWith('/') && !path.startsWith('//') && !path.startsWith('/\\')
59
- }
60
-
61
57
  /** The seed module's path: `--seed`, relative to the root, or `dev/seed.ts` when it exists; `null` for none. */
62
58
  export function seedPath(root: string, given: string | null): string | null {
63
59
  if (given !== null) {
@@ -102,7 +98,7 @@ export function parseSeeded<C extends AnyContract>(dev: DevKit<C>, answer: unkno
102
98
  return { name: persona.name, description: persona.description ?? null, caller }
103
99
  })
104
100
  const links = (result.links ?? []).map((link, index): SeedLink => {
105
- if (!isLocalPath(link.url)) {
101
+ if (sameOriginTarget(dev.kit.origin, link.url) === null) {
106
102
  throw new SeedProblem(`app dev: link ${index + 1} of the seed is not a path of the application, as ctx.links answers it`)
107
103
  }
108
104
  return { title: link.title, description: link.description ?? null, url: link.url }
package/src/app-dev-ui.ts CHANGED
@@ -252,6 +252,61 @@ const STRINGS: Readonly<Record<Locale, Strings>> = {
252
252
  close: 'Zavřít',
253
253
  back: 'Zpět na výběr',
254
254
  },
255
+ uk: {
256
+ preview: 'Попередній перегляд для розробки',
257
+ choose: 'Виберіть, ким ви є',
258
+ lede:
259
+ 'Кожен варіант визначає, від чийого імені ви звертаєтеся до тестового IAM. Дані зберігаються в тимчасовій схемі й зникають, коли app dev завершується.',
260
+ now: 'Ви',
261
+ nobody: 'Ніхто (анонімно)',
262
+ personas: 'Персони',
263
+ noPersonas: 'Seed не створив жодної персони. Поверніть їх із dev/seed.ts.',
264
+ another: 'Інша роль',
265
+ appWide: 'у всьому застосунку',
266
+ inScope: (dimension) => `в одному значенні ${dimension}`,
267
+ external: 'зовнішній',
268
+ use: 'Використати',
269
+ scopePlaceholder: (dimension) => `значення ${dimension}`,
270
+ anonymous: 'Анонімно',
271
+ anonymousText: 'Сторінка, що потребує входу, поверне вас сюди.',
272
+ anonymousButton: 'Продовжити анонімно',
273
+ links: 'Сторінки за посиланням',
274
+ linksText: 'Кожна відкривається від імені власника посилання, яке видав застосунок.',
275
+ openLink: 'Відкрити як власник посилання',
276
+ mail: 'Пошта',
277
+ mailText: 'Запрошення, які тестовий IAM надіслав би електронною поштою, і листи, які надіслали завдання застосунку.',
278
+ noMail: 'Ще нічого не надіслано.',
279
+ invitation: (role, scope) => `Запрошення: ${role} у ${scope}`,
280
+ accept: 'Прийняти запрошення',
281
+ continueAs: 'Продовжити як ця особа',
282
+ openMessage: 'Відкрити лист',
283
+ status: {
284
+ open: 'очікує',
285
+ accepted: 'прийнято',
286
+ cancelled: 'скасовано',
287
+ expired: 'термін минув',
288
+ sent: 'надіслано',
289
+ not_sent: 'не надіслано',
290
+ unknown: 'можливо, надіслано',
291
+ },
292
+ to: 'Кому',
293
+ subject: 'Тема',
294
+ key: 'Ключ',
295
+ transportKey: 'Ключ транспорту',
296
+ sentAt: 'Надіслано',
297
+ answer: 'Відповідь транспорту',
298
+ fromName: 'Ім’я відправника',
299
+ replyTo: 'Адреса для відповіді',
300
+ text: 'Текст',
301
+ html: 'HTML',
302
+ noHtml: 'Лист не має частини HTML.',
303
+ outbox: 'Скринька розробки',
304
+ outboxText: 'Запити, які застосунок надіслав до скриньки розробки, від найновішого.',
305
+ noOutbox: 'До скриньки розробки ще нічого не надійшло.',
306
+ picker: 'Вибрати інший варіант',
307
+ close: 'Закрити',
308
+ back: 'Назад до вибору',
309
+ },
255
310
  }
256
311
 
257
312
  export const stringsOf = (locale: Locale): Strings => STRINGS[locale]
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,14 +10,17 @@ 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 { sameOriginTarget } from '@fabrika/auth-core'
14
+ import { type ApplicationDialect, applicationDialect, CONFIG_FILE } from '@fabrika/check'
15
+ import { SqliteMigrationError } from '@fabrika/db/sqlite-migrate'
12
16
  import { TEST_POSTGRES_URL, type TestDatabase, testDatabase } from '@fabrika/db/testing'
13
17
  import { PostgresMigrationError } from '@fabrika/platform-node'
14
18
  import { MemoryFileObjects } from '@fabrika/platform/testing'
15
- import { existsSync } from 'node:fs'
19
+ import { existsSync, readFileSync } from 'node:fs'
16
20
  import { join } from 'node:path'
17
21
  import { z } from 'zod/v4'
18
22
  import { DEV_ENV_FILE, DevEnvProblem, type DevOutbox, devOutbox, mailHeadOf, readDevEnv, shownBody } from './app-dev-outside'
19
- import { DEFAULT_SEED, importSeed, isLocalPath, NOTHING_SEEDED, parseSeeded, type Seeded, seedPath, SeedProblem } from './app-dev-seed'
23
+ import { DEFAULT_SEED, importSeed, NOTHING_SEEDED, parseSeeded, type Seeded, seedPath, SeedProblem } from './app-dev-seed'
20
24
  import {
21
25
  type Badge,
22
26
  type CurrentView,
@@ -41,7 +45,8 @@ Usage:
41
45
 
42
46
  Run from the application root. It serves ${IMPLEMENTATION_FILE} through its test kit: the production proxy decision,
43
47
  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.
48
+ and a throwaway schema of the database in ${TEST_POSTGRES_URL}, migrated from db/migrations/ and dropped on exit; an
49
+ application on Cloudflare (its ${CONFIG_FILE} is @fabrika/provider-cloudflare's) gets an in-memory SQLite database instead.
45
50
  The seed module (--seed, or ${DEFAULT_SEED} when it exists) default-exports a DevSeed of @fabrika/app/testing: it
46
51
  receives the kit, writes through the endpoints, and answers the personas, link pages and scope values to offer.
47
52
  Pick who the browser is at /__fabrika/dev; every SPA page shows a toolbar that switches the caller and lists the
@@ -87,7 +92,7 @@ export class AppDevError extends Error {
87
92
  export function startupFailure(error: unknown): Error {
88
93
  if (
89
94
  error instanceof AppDevError || error instanceof SeedProblem || error instanceof DevEnvProblem || error instanceof BootError
90
- || error instanceof PostgresMigrationError
95
+ || error instanceof PostgresMigrationError || error instanceof SqliteMigrationError
91
96
  ) {
92
97
  return new Error(error.message)
93
98
  }
@@ -190,21 +195,31 @@ function addressedHere(request: Request, port: number): boolean {
190
195
  const plain = (status: number, text: string): Response =>
191
196
  new Response(`${text}\n`, { status, headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' } })
192
197
 
198
+ /** The dialect the application's `fabrika.config.ts` names, as the checker reads it. */
199
+ function dialectAt(root: string): ApplicationDialect {
200
+ const path = join(root, CONFIG_FILE)
201
+ return applicationDialect(new Map(existsSync(path) ? [[CONFIG_FILE, readFileSync(path, 'utf8')]] : []))
202
+ }
203
+
193
204
  /** Serves `app` through its test kit on a loopback port until `stop`. */
194
205
  export async function startAppDev(app: ContractImplementation<AnyContract>, options: AppDevOptions): Promise<AppDevServer> {
195
206
  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) {
207
+ let testDb: TestDatabase | null = null
208
+ if (app.database !== null && dialectAt(options.root) === 'sqlite') {
209
+ // The SQLite twin of the kit opens an in-memory database: no URL, and nothing left behind to drop.
210
+ const sqlite = await import('@fabrika/db/testing-sqlite')
211
+ testDb = await sqlite.testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
212
+ } else if (app.database !== null) {
198
213
  if ((options.env[TEST_POSTGRES_URL] ?? '') === '') {
199
214
  throw new AppDevError(`app dev needs ${TEST_POSTGRES_URL}, the database the tests use: it migrates a throwaway schema there`)
200
215
  }
201
- postgres = await testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
216
+ testDb = await testDatabase({ migrations: join(options.root, 'db', 'migrations'), label: 'fabrika app dev' })
202
217
  }
203
218
  try {
204
- return await serveThroughKit(app, options, postgres)
219
+ return await serveThroughKit(app, options, testDb)
205
220
  } catch (error) {
206
221
  // The schema and its roles exist from here on: a failed start drops them as a stop does.
207
- await postgres?.close()
222
+ await testDb?.close()
208
223
  throw error
209
224
  }
210
225
  }
@@ -226,24 +241,24 @@ async function runSeed(dev: DevKit<AnyContract>, outside: DevOutside, path: stri
226
241
  return parseSeeded(dev, answer)
227
242
  }
228
243
 
229
- /** What a job's handler threw, printed whole on the developer's terminal. */
244
+ /** What a request's 5xx or a job attempt threw, printed whole on the developer's terminal. */
230
245
  const printHandlerError = (where: string, error: unknown): void => {
231
246
  console.error(`fabrika app dev: ${where} threw\n${Bun.inspect(error)}`)
232
247
  }
233
248
 
234
249
  /**
235
- * The server over the kit of `app`, on `postgres` when it has a data layer; its `stop` also drops the schema. The dev
250
+ * 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
251
  * outbox captures the process's `fetch` from before the seed runs until `stop`, or until a failed start.
237
252
  */
238
253
  async function serveThroughKit(
239
254
  app: ContractImplementation<AnyContract>,
240
255
  options: AppDevOptions,
241
- postgres: TestDatabase | null,
256
+ testDb: TestDatabase | null,
242
257
  ): Promise<AppDevServer> {
243
258
  const outbox = devOutbox()
244
259
  const restoreFetch = outbox.install()
245
260
  try {
246
- return await serveDevKit(app, options, postgres, outbox, restoreFetch)
261
+ return await serveDevKit(app, options, testDb, outbox, restoreFetch)
247
262
  } catch (error) {
248
263
  restoreFetch()
249
264
  throw error
@@ -253,7 +268,7 @@ async function serveThroughKit(
253
268
  async function serveDevKit(
254
269
  app: ContractImplementation<AnyContract>,
255
270
  options: AppDevOptions,
256
- postgres: TestDatabase | null,
271
+ testDb: TestDatabase | null,
257
272
  outbox: DevOutbox,
258
273
  restoreFetch: () => void,
259
274
  ): Promise<AppDevServer> {
@@ -263,7 +278,7 @@ async function serveDevKit(
263
278
  const dev = devKit(app, {
264
279
  root: options.root,
265
280
  env: { ...applicationVariables(options.env), ...readDevEnv(options.root) },
266
- ...(postgres === null ? {} : { database: postgres.database }),
281
+ ...(testDb === null ? {} : { database: testDb.database }),
267
282
  ...(hasFiles ? { files: new MemoryFileObjects() } : {}),
268
283
  revealHandlerErrors: printHandlerError,
269
284
  })
@@ -280,7 +295,7 @@ async function serveDevKit(
280
295
  const toolbar = toolbarScript(STATE_PATH)
281
296
 
282
297
  /** A path of this origin to go on to; anything else is the first SPA. */
283
- const nextOf = (next: string | null): string => (next !== null && isLocalPath(next) ? next : firstSpa)
298
+ const nextOf = (next: string | null): string => (next !== null && sameOriginTarget(kit.origin, next) !== null ? next : firstSpa)
284
299
 
285
300
  /** The caller a role choice names, made once and kept, so its membership changes last; `null` when it is no grant. */
286
301
  const roleCaller = (role: string, value: string | null): LabelledTestCaller | null => {
@@ -561,7 +576,7 @@ async function serveDevKit(
561
576
  await server.stop(true)
562
577
  } finally {
563
578
  restoreFetch()
564
- await postgres?.close()
579
+ await testDb?.close()
565
580
  }
566
581
  },
567
582
  }