@fabrika/app 0.9.0-dev.3 → 0.9.0-dev.5

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.
Files changed (115) hide show
  1. package/package.json +14 -9
  2. package/skill/SKILL.md +41 -14
  3. package/skill/references/app-setup.md +43 -12
  4. package/skill/references/dev.md +2 -1
  5. package/skill/references/endpoint.md +30 -24
  6. package/skill/references/errors.md +40 -35
  7. package/skill/references/files.md +4 -2
  8. package/skill/references/jobs.md +21 -4
  9. package/skill/references/table-and-migration.md +19 -2
  10. package/skill/references/tests.md +40 -1
  11. package/skill/references/webhooks-links-connectors.md +1 -1
  12. package/src/build-recipe.ts +198 -0
  13. package/src/build.ts +60 -4
  14. package/src/bun.ts +181 -13
  15. package/src/cloudflare/application.ts +822 -0
  16. package/src/cloudflare/bindings.ts +159 -0
  17. package/src/cloudflare/export.ts +641 -0
  18. package/src/cloudflare/import.ts +1021 -0
  19. package/src/cloudflare/maintenance.ts +518 -0
  20. package/src/cloudflare/names.ts +16 -0
  21. package/src/cloudflare/ops.ts +375 -0
  22. package/src/cloudflare/r2-files.ts +172 -0
  23. package/src/cloudflare/restore.ts +167 -0
  24. package/src/cloudflare/tracker.ts +192 -0
  25. package/src/cloudflare.ts +100 -146
  26. package/src/contract/app-id.ts +5 -0
  27. package/src/contract/artifact-schema.ts +9 -1
  28. package/src/contract/build.ts +40 -2
  29. package/src/contract/compile.ts +1 -0
  30. package/src/contract/context.ts +35 -9
  31. package/src/contract/declaration.ts +2 -0
  32. package/src/contract/defaults.ts +22 -2
  33. package/src/contract/define.ts +29 -3
  34. package/src/contract/kit.ts +4 -1
  35. package/src/contract/platform.ts +3 -2
  36. package/src/contract/vocabulary.ts +26 -8
  37. package/src/dev/launcher.ts +84 -13
  38. package/src/dev/output.ts +13 -3
  39. package/src/disk-assets.ts +8 -3
  40. package/src/files/archive.ts +2 -2
  41. package/src/files/job-names.ts +12 -0
  42. package/src/files/kinds.ts +73 -31
  43. package/src/files/scan.ts +3 -4
  44. package/src/files/streams.ts +3 -1
  45. package/src/implement/anonymous.ts +12 -11
  46. package/src/implement/boot.ts +75 -6
  47. package/src/implement/bounded.ts +21 -2
  48. package/src/implement/capability.ts +15 -3
  49. package/src/implement/dispatch.ts +419 -177
  50. package/src/implement/failures.ts +17 -1
  51. package/src/implement/faults.ts +1 -0
  52. package/src/implement/index.ts +1 -0
  53. package/src/implement/invocation.ts +58 -10
  54. package/src/implement/principal.ts +25 -2
  55. package/src/implement/terminals.ts +93 -0
  56. package/src/implement/workload.ts +42 -16
  57. package/src/jobs/mail.ts +8 -0
  58. package/src/jobs/report.ts +5 -1
  59. package/src/jobs/runner.ts +672 -113
  60. package/src/jobs/schedule.ts +7 -1
  61. package/src/jobs/scrub.ts +14 -1
  62. package/src/jobs/types.ts +6 -0
  63. package/src/spa-fallback.ts +12 -0
  64. package/src/testing/endpoint-access.ts +307 -152
  65. package/src/testing/isolation.ts +8 -1
  66. package/src/testing/kit.ts +80 -2
  67. package/src/testing/proxy.ts +15 -10
  68. package/types/src/build-recipe.d.ts +70 -0
  69. package/types/src/build.d.ts +19 -1
  70. package/types/src/bun.d.ts +34 -1
  71. package/types/src/cloudflare/application.d.ts +73 -0
  72. package/types/src/cloudflare/bindings.d.ts +33 -0
  73. package/types/src/cloudflare/export.d.ts +16 -0
  74. package/types/src/cloudflare/import.d.ts +51 -0
  75. package/types/src/cloudflare/maintenance.d.ts +117 -0
  76. package/types/src/cloudflare/names.d.ts +11 -0
  77. package/types/src/cloudflare/ops.d.ts +81 -0
  78. package/types/src/cloudflare/r2-files.d.ts +9 -0
  79. package/types/src/cloudflare/restore.d.ts +9 -0
  80. package/types/src/cloudflare/tracker.d.ts +29 -0
  81. package/types/src/cloudflare.d.ts +12 -18
  82. package/types/src/contract/app-id.d.ts +2 -0
  83. package/types/src/contract/artifact-schema.d.ts +2 -0
  84. package/types/src/contract/context.d.ts +35 -11
  85. package/types/src/contract/declaration.d.ts +4 -0
  86. package/types/src/contract/defaults.d.ts +19 -1
  87. package/types/src/contract/define.d.ts +20 -3
  88. package/types/src/contract/kit.d.ts +2 -1
  89. package/types/src/contract/platform.d.ts +2 -2
  90. package/types/src/contract/vocabulary.d.ts +9 -7
  91. package/types/src/dev/output.d.ts +8 -2
  92. package/types/src/disk-assets.d.ts +4 -1
  93. package/types/src/files/job-names.d.ts +9 -0
  94. package/types/src/files/kinds.d.ts +21 -14
  95. package/types/src/files/scan.d.ts +1 -3
  96. package/types/src/implement/anonymous.d.ts +2 -4
  97. package/types/src/implement/boot.d.ts +17 -1
  98. package/types/src/implement/bounded.d.ts +11 -1
  99. package/types/src/implement/capability.d.ts +4 -2
  100. package/types/src/implement/dispatch.d.ts +34 -1
  101. package/types/src/implement/failures.d.ts +5 -0
  102. package/types/src/implement/faults.d.ts +1 -0
  103. package/types/src/implement/index.d.ts +1 -0
  104. package/types/src/implement/invocation.d.ts +22 -7
  105. package/types/src/implement/principal.d.ts +6 -1
  106. package/types/src/implement/terminals.d.ts +33 -0
  107. package/types/src/implement/workload.d.ts +5 -0
  108. package/types/src/jobs/runner.d.ts +66 -2
  109. package/types/src/jobs/schedule.d.ts +2 -0
  110. package/types/src/jobs/types.d.ts +6 -0
  111. package/types/src/spa-fallback.d.ts +2 -0
  112. package/types/src/testing/endpoint-access.d.ts +37 -5
  113. package/types/src/testing/isolation.d.ts +1 -1
  114. package/types/src/testing/kit.d.ts +22 -1
  115. package/types/src/testing/proxy.d.ts +4 -4
@@ -1,7 +1,7 @@
1
1
  # references/table-and-migration.md — the vocabulary, migrations and table policies
2
2
 
3
- The order is fixed: the vocabulary, then the migration, then `fabrika db migrate` and `fabrika db codegen`, then the
4
- table policies, which take the generated `columns`.
3
+ The order is fixed: the vocabulary, then the migration, then `fabrika db migrate` and `fabrika db codegen` (on
4
+ Cloudflare `codegen` only), then the table policies, which take the generated `columns`.
5
5
 
6
6
  ## The vocabulary
7
7
 
@@ -155,6 +155,23 @@ INSERT INTO priorities (code, label, rank) VALUES ('low', 'Low', 1), ('normal',
155
155
  - Never edit, rename or delete a committed migration; add a new one. Change a schema by expand, switch, contract, and
156
156
  ask before you drop or rename anything.
157
157
 
158
+ ## On Cloudflare: SQLite migrations
159
+
160
+ An application on Cloudflare (its `fabrika.config.ts` imports `defineApp` from `@fabrika/provider-cloudflare`) writes
161
+ its migrations in SQLite. Its Durable Object applies them when it boots, each file once in name order, in a transaction
162
+ of its own, so there is no `fabrika db migrate`; `fabrika db codegen` applies them to an in-memory database and needs
163
+ no URL. The rules above for keys, chains, composite foreign keys, `version` and `created_by` hold unchanged, and the
164
+ database enforces foreign keys.
165
+
166
+ - The declared types codegen reads: `TEXT` (a UUID too), `INTEGER`, `REAL`, `BLOB`; `BOOLEAN`, stored as 0 or 1 and
167
+ read as a boolean; `TIMESTAMP`, stored as UTC ISO text and read as a `Date`; `DATE`, `YYYY-MM-DD` text. Any other
168
+ declared type is refused. A `STRICT` table admits only `INTEGER`, `REAL`, `TEXT` and `BLOB`, so a table with a
169
+ `BOOLEAN`, `TIMESTAMP` or `DATE` column is not `STRICT`.
170
+ - SQLite has no `ENUM`: a column with a fixed set of values is `TEXT` with `CHECK (<column> IN ('a', 'b'))`. The
171
+ generated tests write its first value.
172
+ - No transaction control (`BEGIN`, `COMMIT`, `SAVEPOINT`) and no Postgres syntax (`timestamptz`, `::` casts,
173
+ `GENERATED ALWAYS AS IDENTITY`, `CREATE TYPE`).
174
+
158
175
  ## Database code is a declared deviation
159
176
 
160
177
  A function, trigger, view, rule, policy or `DO` block in a migration is allowed. The migration file declares it, and
@@ -12,7 +12,7 @@ longer writes. Commit them; never edit, format or import them (`generated-test-h
12
12
  `app` or `creates` endpoint refuses a holder of its action in one scope only (403) and answers a global holder. An
13
13
  endpoint of several `capabilities` adds a denied case per capability. A public procedure answers anyone without a
14
14
  credential, or, behind a challenge, refuses a caller without a solved one. A file input is sent as a generated file
15
- of its kind; a `GET` procedure's input goes in its URL.
15
+ of its kind, or as the file the fixtures name (`files`, below); a `GET` procedure's input goes in its URL.
16
16
  - Their kit stands in for IAM, as `testKit` does (below): it creates a scope, assigns or invites a member and issues a
17
17
  link under IAM's rules for the caller's grants. A repeated invitation answers the open one, `resend` restarts its
18
18
  7 days, and an organization's address is refused for an external role (`internal_mailbox`). So the caller of an endpoint with the dimension's `members.manage`
@@ -59,6 +59,35 @@ export const members = { 'api.tasks.assign': ['assignee'] }
59
59
  table of the table that owns it, or a table it contains; the checker refuses a row further down
60
60
  (`endpoint-fixture`). Without it they send a sample, the handler
61
61
  finds no row (404), and the case fails.
62
+ - `appRows['<endpoint id>']` gives the rows of application tables (`scope: { app }`) that the endpoint's handler reads
63
+ for the caller's own scope, by table, with the columns they need: `export const appRows = { 'portal.guide': { guides:
64
+ { active: true } } }`. Each of its leak and own-object cases seeds one row of each before it asks and removes them
65
+ once it is over, with every row that refers to them (a download the handler logged), so a handler that reads the
66
+ newest guide answers 200 instead of 404, and no other endpoint's case finds the row. A foreign key from one given row
67
+ to another holds that row's key. A text column may be given; the key, the version, the creator and a file column may
68
+ not (a file column holds a live, scanned file). Only application tables, and only for an endpoint with a leak or an
69
+ own-object case: the checker refuses a table in a scope, which `rows` and `seeds` address (`endpoint-fixture`).
70
+ - `files['<endpoint id>']` names, by file field, a file of the repository that every case of the endpoint sends there
71
+ instead of the generated one, a path from the application's root:
72
+ `export const files = { 'api.skills.publish': { package: 'src/__tests__/fixtures/skill.zip' } }`. Give one when the
73
+ handler inspects the content (a package it unpacks, a document it parses) and answers 400 to the generated file, which
74
+ has only the leading bytes of its type. Commit the file; keep it small and free of real data. The kit sends it with the
75
+ first type of the field's kind its bytes are, and a file it cannot read, or of none of those types, fails the case. The
76
+ checker refuses a field that holds no file and a path that leaves the application, starts with `.` or has characters
77
+ other than letters, digits, `_`, `-`, `.` and `/` (`endpoint-fixture`).
78
+ - `pins['<endpoint id>']` gives text columns of the row the endpoint addresses (the row of the table that owns its
79
+ dimension) a known value instead of the seed's marker: `export const pins = { 'api.skills.publish': { slug:
80
+ 'published-skill' } }`, when the handler ties the column to the input or to the file in `files` (a package whose
81
+ `SKILL.md` names the skill's slug). The own scope's row holds the value, the other scope's `<value>-other`, which a
82
+ leak case still looks for in the own scope's answer. A pin of a column that places the row, or of no text column,
83
+ fails the case; the checker refuses one of an endpoint without an addressed row (`endpoint-fixture`).
84
+ - `refusals['<endpoint id>']` lists the error types of the 400s the endpoint's handler answers with when its rule ties
85
+ the row to the input and the scope is the other one: `export const refusals = { 'api.skills.publish':
86
+ ['skill_frontmatter'] }`, beside the pin above. A leak case asks from the other scope first, whose pinned value the
87
+ package does not name; that request may answer one of them. The own case passes on 200 or one of them, and the
88
+ denial cases still expect 404 or 403. The answer a leak case checks, the own scope's, still fails on it, because an
89
+ answer that holds nothing proves no isolation: pin the row and give the file so that the own scope succeeds. Any
90
+ other 400 fails the case, and the checker refuses `validation`, an input the schema refuses (`endpoint-fixture`).
62
91
  - The endpoint id is `<mount>.<group>.<endpoint>` (`api.tasks.close`).
63
92
  - The seed of the tests fills every text column with a marker and every other required column with a sample of its
64
93
  type: an enum's first label, `1`, `false`, today. A column with a `DEFAULT` keeps it (`status` is `open`). A column
@@ -196,6 +225,9 @@ if (postgres !== null) {
196
225
  `<label> skipped: set FABRIKA_TEST_POSTGRES_URL to run the Postgres-backed tests`, and the file registers no test.
197
226
  A skip proves nothing. To confirm a file ran, run it alone (`bun test --isolate src/tasks`) and check that the pass
198
227
  count is its number of tests, or set `FABRIKA_TEST_POSTGRES_REQUIRED=1`: a missing URL then fails the file.
228
+ - On Cloudflare import `testDatabase` from `@fabrika/db/testing-sqlite` instead, with the same options: it migrates a
229
+ fresh in-memory SQLite database as the Durable Object does, needs no URL and never answers `null`. The generated tests
230
+ already use it.
199
231
  - `statusOf(call)` answers 200 when the call resolves and the status of the application's refusal otherwise; any other
200
232
  failure (no answer, a bug in the test) is rethrown. Import it beside `testKit`; do not write your own.
201
233
  - `kit.testCaller(grants, { kind })` makes a caller: a grant is a role or an action, in one scope or global. A
@@ -290,6 +322,13 @@ if (postgres !== null) {
290
322
  - A mutation that kicks (`kicks`, `ctx.kick`) starts its job in the background of the call. `kit.drain()` waits for
291
323
  those runs, and `kit.runJob` first waits for them; every generated access case drains before it answers. The kicked
292
324
  run may start at once, so arm a fault before the call, never between the call and the run.
325
+ - `await kit.runDueJobs({ within: 3 * 3600000 })` runs every job with a wake due now or within `within` milliseconds
326
+ (0 by default) once, as the Cloudflare object's alarm runs it: a cron job's next fire, a kick, a failed run's retry.
327
+ It answers `[{ job, result }]` for the runs it started, and first waits for the kicked runs. Without it the kit fires
328
+ no wake: a cron job runs only through `runJob` or `runDueJobs`. Only the wakes move, never the clock: a handler's
329
+ `new Date()` and a queue row's due time stay real, so a row due later is not claimed early. A second call does not run
330
+ a cron fire the first one ran early. A failed run of a job with `retries` is due again after its backoff, at most a
331
+ second for the first retry, so `runDueJobs({ within: 2000 })` runs it. It needs the application's data layer.
293
332
  - `kit.mail` is the stand-in for every job's mail transport (`MemoryEmailSender` of `@fabrika/app/testing`), so a test
294
333
  needs no mail variable. `kit.mail.accepted` is what reached the inbox, once per key, and `kit.mail.handoffs` every
295
334
  send with its `answer`. `refuse(code?)`, `unavailable()`, `unreachable()`, `loseAnswers(n)` and `during(hook)`
@@ -89,7 +89,7 @@ export const integrations = app.group({ callers: ['human'] }, (r) => ({
89
89
  that binds it takes an `app` capability: `access: { action, app: true }`, `binds`, and
90
90
  `ctx.webhooks('<webhook>').bind(ctx.app, account)`.
91
91
  - `limits: { maxBytes?, timeoutMs? }`: the body is 1 MiB by default and at most 48 MiB; the handler runs 10 s by
92
- default, at most 60 s. A webhook may declare `kicks`, `signs`, `egress`, `sql` and `unscoped`, and `ctx.files.put`
92
+ default, at most 60 s (25 s on Cloudflare). A webhook may declare `kicks`, `signs`, `egress`, `sql` and `unscoped`, and `ctx.files.put`
93
93
  stores a file a provider sends (an inbound e-mail's attachment) for a file column: raise `limits.maxBytes` to the
94
94
  mail you accept.
95
95
  - Not covered: a provider that validates its URL with a `GET`, or that needs a custom answer body.
@@ -0,0 +1,198 @@
1
+ // The build, init and start of a contract application in a Bun container, as data (ADR-0043): the steps and their
2
+ // order are the platform's, never the repository's. A provider renders the recipe into its own build form, with its own
3
+ // paths, file writes and scheduler. PURE — no network, no filesystem.
4
+ //
5
+ // PLATFORM PROTOCOL, not framework API: the platform renders this with ITS copy for applications of older releases
6
+ // (ADR-0062), so the commands, script names and job names an application must accept change only additively. Never
7
+ // render the application's own copy.
8
+
9
+ import { APPLICATION_SERVER_MAX_HEADER_BYTES, FRAMEWORK_RELEASE_PATTERN } from '@fabrika/auth-core'
10
+ import { CONTRACT_APP_ID_PATTERN } from './contract/app-id.js'
11
+ import { FILE_SCAN_JOB, FILE_SCAN_SCHEDULE, FILE_SWEEP_JOB, FILE_SWEEP_SCHEDULE } from './files/job-names.js'
12
+
13
+ export { CONTRACT_APP_ID_PATTERN } from './contract/app-id.js'
14
+
15
+ export { FILE_SCAN_JOB, FILE_SWEEP_JOB } from './files/job-names.js'
16
+
17
+ /** The TypeScript release of the platform's type check; the application's own `typescript` is not run. */
18
+ export const PLATFORM_TYPESCRIPT_VERSION = '5.9.3'
19
+
20
+ /** The CLI a generated script runs, relative to the application root. */
21
+ const FABRIKA_BIN = './node_modules/.bin/fabrika'
22
+ const MIGRATE_SCRIPT = 'fabrika/migrate.generated.sh'
23
+ const VERIFY_SCRIPT = 'fabrika/verify.generated.sh'
24
+ const START_SCRIPT = 'fabrika/start.generated.sh'
25
+ const SERVE: readonly string[] = ['bun', `--max-http-header-size=${APPLICATION_SERVER_MAX_HEADER_BYTES}`, 'fabrika/entry.generated.ts']
26
+ const MIGRATE: readonly string[] = [FABRIKA_BIN, 'db', 'migrate']
27
+ const PLATFORM_TSCONFIG = 'fabrika/tsconfig.platform.json'
28
+
29
+ /**
30
+ * The compiler options of the platform's type check; the application's own `tsconfig.json` and its `paths` are not read.
31
+ * It covers the SPA under `web/` too: Bun bundles the SPA without checking its types.
32
+ */
33
+ const PLATFORM_TSCONFIG_CONTENTS = JSON.stringify({
34
+ compilerOptions: {
35
+ target: 'ES2022',
36
+ module: 'ESNext',
37
+ moduleResolution: 'bundler',
38
+ lib: ['ES2022', 'DOM', 'DOM.Iterable'],
39
+ jsx: 'react-jsx',
40
+ types: ['bun'],
41
+ strict: true,
42
+ noUncheckedIndexedAccess: true,
43
+ noImplicitOverride: true,
44
+ forceConsistentCasingInFileNames: true,
45
+ skipLibCheck: true,
46
+ resolveJsonModule: true,
47
+ isolatedModules: true,
48
+ noEmit: true,
49
+ },
50
+ include: ['../fabrika.contract.ts', '../src', '../web', 'entry.generated.ts'],
51
+ })
52
+
53
+ const INSTALL = 'bun install --frozen-lockfile --ignore-scripts'
54
+
55
+ /**
56
+ * What `@fabrika/db/testing` prints after the label of a test file it skips without `FABRIKA_TEST_POSTGRES_URL`. Every
57
+ * framework release prints it, so the platform counts it for any application's release.
58
+ */
59
+ const DATABASE_TEST_SKIP_MARKER = ' skipped: set FABRIKA_TEST_POSTGRES_URL to run the Postgres-backed tests'
60
+
61
+ /** The prefix of the line the tests command prints after the test run. */
62
+ const TESTS_REPORT_PREFIX = 'fabrika-tests:'
63
+
64
+ /** One `bun -e "…"` running `script`, which may hold none of the characters a double-quoted shell word expands. */
65
+ const bunEvalCommand = (script: readonly string[]): string => {
66
+ const source = script.join(' ')
67
+ if (/["$`\\!]/.test(source)) throw new Error('a generated bun -e script must not contain a quote, an expansion or a backslash')
68
+ return `bun -e "${source}"`
69
+ }
70
+
71
+ // The build has no database, so every Postgres-backed test file skips and the run still passes. This command runs the
72
+ // tests as before and then says how many files did not run, so a green test step does not read as a tested database.
73
+ const TESTS_COMMAND = bunEvalCommand([
74
+ "const child = Bun.spawn([process.execPath, 'test', '--isolate', '--pass-with-no-tests'], { stdout: 'inherit', stderr: 'pipe' });",
75
+ 'const decoder = new TextDecoder();',
76
+ "let output = '';",
77
+ 'for await (const chunk of child.stderr) { process.stderr.write(chunk); output += decoder.decode(chunk, { stream: true }) }',
78
+ 'const code = await child.exited;',
79
+ `const marker = '${DATABASE_TEST_SKIP_MARKER}';`,
80
+ 'const skipped = output.split(String.fromCharCode(10)).filter((line) => line.includes(marker)).map((line) => line.slice(0, line.indexOf(marker)).trim());',
81
+ `const prefix = '${TESTS_REPORT_PREFIX}';`,
82
+ "console.warn(skipped.length === 0 ? prefix + ' no Postgres-backed test file skipped' : prefix + ' ' + skipped.length + ' Postgres-backed test files did not run, because the build has no database: ' + skipped.join(', '));",
83
+ 'process.exit(code);',
84
+ ])
85
+
86
+ /** A `c.cron` job name, which a crontab line carries unquoted. */
87
+ export const CONTRACT_JOB_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]*$/
88
+ /** Five cron fields of digits and `*`, `/`, `,`, `-` only. */
89
+ export const CRON_SCHEDULE_PATTERN = /^[0-9*/,-]+(?: [0-9*/,-]+){4}$/
90
+
91
+ /** What one contract application's recipe depends on. `contractRecipe` refuses a value that a shell would read as more. */
92
+ export interface ContractRecipeInput {
93
+ readonly appId: string
94
+ /** The `@fabrika/check` release whose reader read the application (ADR-0062). */
95
+ readonly checkRelease: string
96
+ /** The absolute directory the build runs in: the checker reads the source there. */
97
+ readonly sourceRoot: string
98
+ /** The absolute directory the built application runs from: each generated script starts there. */
99
+ readonly runtimeRoot: string
100
+ /** With a database, every container migrates and checks its schema before the server starts. */
101
+ readonly database: boolean
102
+ /** Whether the build uploads its source maps, last and never failing the build. */
103
+ readonly sourceMaps: boolean
104
+ readonly jobs: readonly { readonly name: string; readonly schedule: string }[]
105
+ /** The contract declares a file collection: the sweep of removed files is scheduled. */
106
+ readonly files: boolean
107
+ /** A file collection scans its uploads: the scan pass is scheduled. */
108
+ readonly scan: boolean
109
+ }
110
+
111
+ /** One build step: a command run in the source root, or a generated file written there, line by line. */
112
+ export type ContractBuildStep = { readonly run: string } | { readonly write: string; readonly lines: readonly string[] }
113
+
114
+ /** One check of the build: a command run in the source root that fails the build. */
115
+ export interface ContractCheck {
116
+ readonly name: 'tests' | 'tsc' | 'fabrika-check'
117
+ readonly command: string
118
+ }
119
+
120
+ export interface ContractRecipe {
121
+ /** The steps after the authored SPA commands, in order. */
122
+ readonly build: readonly ContractBuildStep[]
123
+ /** The checks among `build`, in its order. */
124
+ readonly checks: readonly ContractCheck[]
125
+ /** The generated scripts every container runs before `start`, in order; any failure stops the activation. */
126
+ readonly init: readonly string[]
127
+ /** The generated script that starts the server, which only `exec`s it. */
128
+ readonly start: string
129
+ /** The command the start script `exec`s, run from the runtime root. */
130
+ readonly serve: readonly string[]
131
+ /** The command that migrates the application's database, run from the runtime root. */
132
+ readonly migrate: readonly string[]
133
+ /** The jobs to schedule, each on one container; a command runs from the runtime root. */
134
+ readonly jobs: readonly { readonly schedule: string; readonly command: string }[]
135
+ }
136
+
137
+ /**
138
+ * The recipe of one contract application. The application's tests run first: they are authored code, so everything
139
+ * after them is reinstalled, regenerated or checked again. They run `--isolate`, as the application skill runs them: a
140
+ * test file's DOM globals otherwise leak into the next file. `tsc` runs before the checker, as in the skill's loop: the
141
+ * usual quick fix of a type error is a cast or an `any`, which only the checker refuses, so the checker is the last word
142
+ * on the code. The build has no database, so the schema checks run as init scripts, after the migrations and before the
143
+ * readiness window opens.
144
+ */
145
+ export function contractRecipe(input: ContractRecipeInput): ContractRecipe {
146
+ const { appId, checkRelease, sourceRoot, runtimeRoot } = input
147
+ if (!CONTRACT_APP_ID_PATTERN.test(appId)) throw new Error('a contract application id must match [a-z0-9][a-z0-9-]*')
148
+ if (!FRAMEWORK_RELEASE_PATTERN.test(checkRelease)) throw new Error('the checker release must be a release version')
149
+ if (input.jobs.some((job) => !CONTRACT_JOB_NAME_PATTERN.test(job.name) || !CRON_SCHEDULE_PATTERN.test(job.schedule))) {
150
+ throw new Error('a job name or schedule is not one a generated crontab line may carry')
151
+ }
152
+ const script = (lines: readonly string[]): readonly string[] => ['#!/bin/sh', 'set -eu', `cd ${runtimeRoot}`, ...lines]
153
+ const init = input.database
154
+ ? [
155
+ { path: MIGRATE_SCRIPT, lines: script([`FABRIKA_APP_ID=${appId} exec ${MIGRATE.join(' ')}`]) },
156
+ // The committed schema types must match the migrated schema, and every generated isolation test must pass on a
157
+ // throwaway schema.
158
+ {
159
+ path: VERIFY_SCRIPT,
160
+ lines: script([`FABRIKA_APP_ID=${appId} ${FABRIKA_BIN} db codegen --verify`, `FABRIKA_APP_ID=${appId} exec ${FABRIKA_BIN} db test-isolation`]),
161
+ },
162
+ ]
163
+ : []
164
+ const tests: ContractCheck = { name: 'tests', command: TESTS_COMMAND }
165
+ const tsc: ContractCheck = {
166
+ name: 'tsc',
167
+ command: `cd /tmp && bun x --bun -p typescript@${PLATFORM_TYPESCRIPT_VERSION} tsc -p ${sourceRoot}/${PLATFORM_TSCONFIG}`,
168
+ }
169
+ const check: ContractCheck = {
170
+ name: 'fabrika-check',
171
+ command: `cd /tmp && bun x --bun -p @fabrika/check@${checkRelease} fabrika-check ${sourceRoot}`,
172
+ }
173
+ return {
174
+ build: [
175
+ { run: INSTALL },
176
+ { run: tests.command },
177
+ { run: `rm -rf node_modules && ${INSTALL}` },
178
+ { run: `bun -e "await import('@fabrika/app/build').then((build) => build.writeGeneratedEntry('.', 'bun'))"` },
179
+ { write: PLATFORM_TSCONFIG, lines: [PLATFORM_TSCONFIG_CONTENTS] },
180
+ { run: tsc.command },
181
+ { run: check.command },
182
+ ...init.map((generated) => ({ write: generated.path, lines: generated.lines })),
183
+ { write: START_SCRIPT, lines: script([`exec ${SERVE.join(' ')}`]) },
184
+ // After every check, so a map is uploaded only for a build that can deploy; the report line says how it went.
185
+ ...(input.sourceMaps ? [{ run: `cd /tmp && bun x --bun -p @fabrika/check@${checkRelease} fabrika-source-maps ${sourceRoot} || true` }] : []),
186
+ ],
187
+ checks: [tests, tsc, check],
188
+ init: init.map((generated) => generated.path),
189
+ start: START_SCRIPT,
190
+ serve: SERVE,
191
+ migrate: MIGRATE,
192
+ jobs: [
193
+ ...input.jobs.map((job) => ({ schedule: job.schedule, command: `${FABRIKA_BIN} job run ${job.name}` })),
194
+ ...(input.files ? [{ schedule: FILE_SWEEP_SCHEDULE, command: `${FABRIKA_BIN} job run ${FILE_SWEEP_JOB}` }] : []),
195
+ ...(input.scan ? [{ schedule: FILE_SCAN_SCHEDULE, command: `${FABRIKA_BIN} job run ${FILE_SCAN_JOB}` }] : []),
196
+ ],
197
+ }
198
+ }
package/src/build.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // the only module that reads `process.env` and the only caller of `boot`, through the runtime adapter, and it imports
3
3
  // the application only after the adapter took the framework's variables out of the process.
4
4
 
5
- import { mkdir, writeFile } from 'node:fs/promises'
5
+ import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'
6
6
  import { dirname, join } from 'node:path'
7
7
 
8
8
  /** An application root with this file is a contract application. The paths equal `@fabrika/check`'s layout. */
@@ -14,8 +14,24 @@ export const GENERATED_ENTRY_FILE = 'fabrika/entry.generated.ts'
14
14
  /** The module whose default export is `serve(contract, …)`, relative to the application root. */
15
15
  export const IMPLEMENTATION_FILE = 'src/app.ts'
16
16
 
17
+ /** The application's migrations as a module, relative to the application root: a Worker reads no file system. */
18
+ export const GENERATED_MIGRATIONS_FILE = 'fabrika/migrations.generated.ts'
19
+
20
+ /** Where an application keeps its migrations, relative to its root; `fabrika db new` writes there. */
21
+ export const MIGRATIONS_DIRECTORY = 'db/migrations'
22
+
17
23
  export type EntryRuntime = 'bun' | 'cloudflare'
18
24
 
25
+ export * from './build-recipe.js'
26
+
27
+ // In a module of their own, which the Worker imports without this one's file system.
28
+ export {
29
+ CLOUDFLARE_APPLICATION_BINDING,
30
+ CLOUDFLARE_APPLICATION_CLASS,
31
+ CLOUDFLARE_ASSETS_BINDING,
32
+ CLOUDFLARE_FILES_BINDING,
33
+ } from './cloudflare/names.js'
34
+
19
35
  const HEADER = '// @generated by `fabrika app build` from src/app.ts. Do not edit: every build rewrites it.'
20
36
 
21
37
  /** The entrypoint source for one runtime. */
@@ -35,19 +51,59 @@ export function generatedEntry(runtime: EntryRuntime): string {
35
51
  return [
36
52
  HEADER,
37
53
  "import { createContractWorker, markProductionProcess } from '@fabrika/app/cloudflare'",
54
+ "import { migrations } from './migrations.generated'",
38
55
  '',
39
- '// The test kits refuse to load from here on; the application is imported only after the framework took its variables.',
56
+ "export { FabrikaApplication } from '@fabrika/app/cloudflare'",
57
+ '',
58
+ '// The test kits refuse to load from here on; the object imports the application only after the framework took its variables.',
40
59
  'markProductionProcess()',
41
- "export default createContractWorker(() => import('../src/app'))",
60
+ "export default createContractWorker(() => import('../src/app'), { migrations })",
42
61
  '',
43
62
  ].join('\n')
44
63
  }
45
64
  }
46
65
 
47
- /** Writes the entrypoint under `root` and returns its path. */
66
+ /** Writes the entrypoint under `root` and returns its path; the Cloudflare one also writes the migrations module it imports. */
48
67
  export async function writeGeneratedEntry(root: string, runtime: EntryRuntime): Promise<string> {
49
68
  const path = join(root, GENERATED_ENTRY_FILE)
50
69
  await mkdir(dirname(path), { recursive: true })
51
70
  await writeFile(path, generatedEntry(runtime))
71
+ if (runtime === 'cloudflare') {
72
+ await writeGeneratedMigrations(root)
73
+ }
74
+ return path
75
+ }
76
+
77
+ /** The application's migrations under `root`, every `.sql` file of `db/migrations` by name; none without the directory. */
78
+ export async function applicationMigrations(root: string): Promise<readonly { readonly name: string; readonly sql: string }[]> {
79
+ const directory = join(root, MIGRATIONS_DIRECTORY)
80
+ let names: string[]
81
+ try {
82
+ names = await readdir(directory)
83
+ } catch (error) {
84
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
85
+ return []
86
+ }
87
+ throw error
88
+ }
89
+ const files = names.filter((name) => name.endsWith('.sql')).sort((left, right) => left < right ? -1 : left > right ? 1 : 0)
90
+ return await Promise.all(files.map(async (name) => ({ name, sql: await readFile(join(directory, name), 'utf8') })))
91
+ }
92
+
93
+ /** The migrations module source: the files' names and texts, verbatim, so their checksums stay the files'. */
94
+ export function generatedMigrations(migrations: readonly { readonly name: string; readonly sql: string }[]): string {
95
+ return [
96
+ `// @generated by \`fabrika app build\` from ${MIGRATIONS_DIRECTORY}. Do not edit: every build rewrites it.`,
97
+ '',
98
+ `export const migrations: readonly { readonly name: string; readonly sql: string }[] = ${JSON.stringify(migrations, null, '\t')}`,
99
+ '',
100
+ ].join('\n')
101
+ }
102
+
103
+ /** Writes the migrations module under `root` and returns its path. */
104
+ export async function writeGeneratedMigrations(root: string): Promise<string> {
105
+ const path = join(root, GENERATED_MIGRATIONS_FILE)
106
+ await mkdir(dirname(path), { recursive: true })
107
+ await writeFile(path, generatedMigrations(await applicationMigrations(root)))
52
108
  return path
53
109
  }