@fabrika/check 0.9.0-dev.1 → 0.9.0-dev.11

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 (74) hide show
  1. package/package.json +12 -11
  2. package/src/check.ts +58 -9
  3. package/src/cli.ts +23 -4
  4. package/src/dialect.ts +29 -0
  5. package/src/endpoint-fixtures.ts +99 -13
  6. package/src/finding.ts +12 -3
  7. package/src/index.ts +4 -1
  8. package/src/layout.ts +16 -1
  9. package/src/migration-base.ts +85 -0
  10. package/src/reader/surface.ts +15 -0
  11. package/src/reader/value.ts +1 -1
  12. package/src/resolution.ts +2 -2
  13. package/src/rules/cloudflare.ts +59 -0
  14. package/src/rules/framework.ts +2 -2
  15. package/src/rules/isolation.ts +5 -1
  16. package/src/rules/migration-history.ts +70 -0
  17. package/src/rules/migrations.ts +63 -0
  18. package/src/rules/modules.ts +3 -3
  19. package/src/rules/platform-migrations.ts +93 -0
  20. package/src/rules/runtime.ts +13 -7
  21. package/src/rules/structure.ts +26 -1
  22. package/src/rules/tests.ts +1 -1
  23. package/src/scaffold.ts +398 -71
  24. package/src/trust.ts +8 -4
  25. package/types/src/ast.d.ts +65 -0
  26. package/types/src/bun-plugin.d.ts +12 -0
  27. package/types/src/check.d.ts +22 -0
  28. package/types/src/cli.d.ts +2 -0
  29. package/types/src/contract.d.ts +58 -0
  30. package/types/src/dialect.d.ts +8 -0
  31. package/types/src/endpoint-fixtures.d.ts +54 -0
  32. package/types/src/finding.d.ts +39 -0
  33. package/types/src/graph.d.ts +68 -0
  34. package/types/src/index.d.ts +9 -0
  35. package/types/src/inputs.d.ts +9 -0
  36. package/types/src/jsonc.d.ts +2 -0
  37. package/types/src/layout.d.ts +76 -0
  38. package/types/src/limits.d.ts +15 -0
  39. package/types/src/lockfile.d.ts +19 -0
  40. package/types/src/migration-base.d.ts +9 -0
  41. package/types/src/packed.d.ts +15 -0
  42. package/types/src/reader/problems.d.ts +7 -0
  43. package/types/src/reader/schema.d.ts +18 -0
  44. package/types/src/reader/surface.d.ts +5 -0
  45. package/types/src/reader/tables.d.ts +6 -0
  46. package/types/src/reader/value.d.ts +113 -0
  47. package/types/src/references.d.ts +15 -0
  48. package/types/src/resolution.d.ts +20 -0
  49. package/types/src/rules/cloudflare.d.ts +9 -0
  50. package/types/src/rules/contract.d.ts +8 -0
  51. package/types/src/rules/crontab.d.ts +15 -0
  52. package/types/src/rules/framework.d.ts +19 -0
  53. package/types/src/rules/identity.d.ts +5 -0
  54. package/types/src/rules/isolation.d.ts +18 -0
  55. package/types/src/rules/json.d.ts +3 -0
  56. package/types/src/rules/literal.d.ts +63 -0
  57. package/types/src/rules/migration-history.d.ts +12 -0
  58. package/types/src/rules/migrations.d.ts +40 -0
  59. package/types/src/rules/modules.d.ts +12 -0
  60. package/types/src/rules/packages.d.ts +7 -0
  61. package/types/src/rules/platform-migrations.d.ts +13 -0
  62. package/types/src/rules/runtime.d.ts +34 -0
  63. package/types/src/rules/structure.d.ts +41 -0
  64. package/types/src/rules/tests.d.ts +22 -0
  65. package/types/src/rules/types.d.ts +4 -0
  66. package/types/src/scaffold-sample.d.ts +8 -0
  67. package/types/src/scaffold.d.ts +36 -0
  68. package/types/src/scope.d.ts +6 -0
  69. package/types/src/slice.d.ts +30 -0
  70. package/types/src/source-maps-cli.d.ts +4 -0
  71. package/types/src/source-maps.d.ts +32 -0
  72. package/types/src/toml.d.ts +30 -0
  73. package/types/src/trust.d.ts +15 -0
  74. package/types/src/version.d.ts +2 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/check",
3
- "version": "0.9.0-dev.1",
3
+ "version": "0.9.0-dev.11",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,27 +16,28 @@
16
16
  },
17
17
  "files": [
18
18
  "src",
19
- "!src/**/__tests__/**"
19
+ "!src/**/__tests__/**",
20
+ "types"
20
21
  ],
21
22
  "exports": {
22
23
  ".": {
23
24
  "bun": "./src/index.ts",
24
- "types": "./src/index.ts",
25
+ "types": "./types/src/index.d.ts",
25
26
  "default": "./src/index.ts"
26
27
  },
27
28
  "./contract": {
28
29
  "bun": "./src/contract.ts",
29
- "types": "./src/contract.ts",
30
+ "types": "./types/src/contract.d.ts",
30
31
  "default": "./src/contract.ts"
31
32
  },
32
33
  "./bun-plugin": {
33
34
  "bun": "./src/bun-plugin.ts",
34
- "types": "./src/bun-plugin.ts",
35
+ "types": "./types/src/bun-plugin.d.ts",
35
36
  "default": "./src/bun-plugin.ts"
36
37
  },
37
38
  "./source-maps": {
38
39
  "bun": "./src/source-maps.ts",
39
- "types": "./src/source-maps.ts",
40
+ "types": "./types/src/source-maps.d.ts",
40
41
  "default": "./src/source-maps.ts"
41
42
  }
42
43
  },
@@ -46,11 +47,11 @@
46
47
  },
47
48
  "dependencies": {
48
49
  "@babel/parser": "8.0.7",
49
- "@fabrika/app": "0.9.0-dev.1",
50
- "@fabrika/auth-core": "0.9.0-dev.1",
51
- "@fabrika/db": "0.9.0-dev.1",
52
- "@fabrika/operations-contract": "0.9.0-dev.1",
53
- "@fabrika/platform-node": "0.9.0-dev.1",
50
+ "@fabrika/app": "0.9.0-dev.11",
51
+ "@fabrika/auth-core": "0.9.0-dev.11",
52
+ "@fabrika/db": "0.9.0-dev.11",
53
+ "@fabrika/operations-contract": "0.9.0-dev.11",
54
+ "@fabrika/platform-node": "0.9.0-dev.11",
54
55
  "zod": "^3.25.76"
55
56
  }
56
57
  }
package/src/check.ts CHANGED
@@ -5,6 +5,7 @@ import { readdir, readFile } from 'node:fs/promises'
5
5
  import { join } from 'node:path'
6
6
  import { type AstNode, type ParsedModule, parseModule, walk } from './ast'
7
7
  import { contractModules, readContractModule } from './contract'
8
+ import { applicationDialect } from './dialect'
8
9
  import { compareFindings, type Finding, reporter } from './finding'
9
10
  import { ModuleGraph } from './graph'
10
11
  import {
@@ -16,6 +17,7 @@ import {
16
17
  isServerModule,
17
18
  isSourceFile,
18
19
  isTestFile,
20
+ isToolModule,
19
21
  TABLES_FILE,
20
22
  ZEROPS_FILES,
21
23
  } from './layout'
@@ -24,6 +26,7 @@ import { ReaderProblems } from './reader/problems'
24
26
  import { readTablesValue } from './reader/tables'
25
27
  import { type ModuleReference, moduleReferences } from './references'
26
28
  import { type ImportMappings, readImportMappings } from './resolution'
29
+ import { checkCloudflareContract } from './rules/cloudflare'
27
30
  import { checkContractRead } from './rules/contract'
28
31
  import { checkCrontab, contractJobs } from './rules/crontab'
29
32
  import { checkFrameworkWrite, trustedBindings } from './rules/framework'
@@ -31,11 +34,21 @@ import { checkClientIdentity } from './rules/identity'
31
34
  import { checkGeneratedTests } from './rules/isolation'
32
35
  import { checkJsonStrings } from './rules/json'
33
36
  import { checkLiteralGraph } from './rules/literal'
34
- import { checkConflictIndexes, checkFileColumnMigrations, checkMigrationNames, type ConflictInsert, type FileColumn } from './rules/migrations'
37
+ import { checkMigrationHistory, type MigrationBase } from './rules/migration-history'
38
+ import {
39
+ checkConflictIndexes,
40
+ checkCurrentTimestampDefaults,
41
+ checkFileColumnMigrations,
42
+ checkMigrationNames,
43
+ checkSqliteFrameworkNames,
44
+ type ConflictInsert,
45
+ type FileColumn,
46
+ } from './rules/migrations'
35
47
  import { checkModuleReferences } from './rules/modules'
36
48
  import { checkAmbientModule, checkPackageReplacement } from './rules/packages'
37
- import { checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
38
- import { checkStructureNode, checkStructureReferences, structurePlace } from './rules/structure'
49
+ import { checkBackupPlan, checkMigrationClassification } from './rules/platform-migrations'
50
+ import { checkKeyLiteralNode, checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
51
+ import { checkStructureNode, checkStructureReferences, checkToolPackages, structurePlace } from './rules/structure'
39
52
  import { checkGeneratedTest, checkMockModule, checkTestNode, checkTestSuiteConfig } from './rules/tests'
40
53
  import { checkComments, checkTypeNode } from './rules/types'
41
54
  import { moduleSlice, sliceFinding } from './slice'
@@ -52,6 +65,8 @@ export interface CheckInput {
52
65
  readonly files?: ReadonlyMap<string, string>
53
66
  /** A local pack whose tarballs `package-replacement` accepts (`fabrika-check --packed`); a deploy build gives none. */
54
67
  readonly packed?: PackedSet
68
+ /** The migrations of a shared branch the tree must still hold unchanged (`fabrika-check`, from git); a deploy build gives none. */
69
+ readonly migrationBase?: MigrationBase
55
70
  }
56
71
 
57
72
  export interface ApplicationTree {
@@ -88,6 +103,26 @@ interface ContractDependent {
88
103
  readonly inserts: ConflictInsert[]
89
104
  }
90
105
 
106
+ /**
107
+ * A module under `tools/` runs on a developer's machine, never in the application: it is held to how its source is
108
+ * written (`type-assertion`, `any-type`, `capability-widening`, `suppression-comment`), `key-literal`, a `declare
109
+ * module` of a trusted package and the rules of its tests. Every other module rule guards code that runs in the
110
+ * application. `generated-test-import` reaches it through `checkStructureReferences`, as every module.
111
+ */
112
+ const checkToolModule = async (module: ParsedModule, text: string, files: ReadonlyMap<string, string>, findings: Finding[]): Promise<void> => {
113
+ const report = reporter(module.file, findings)
114
+ const isTest = isTestFile(module.file)
115
+ walk(module.program, (node, ancestors) => {
116
+ checkKeyLiteralNode(node, report)
117
+ checkTypeNode(node, report)
118
+ checkAmbientModule(node, report)
119
+ if (isTest) checkTestNode(node, ancestors, report)
120
+ checkMockModule(node, module.file, files, report)
121
+ })
122
+ checkComments(module.comments, report)
123
+ await checkGeneratedTest(text, module.comments, report)
124
+ }
125
+
91
126
  const checkSourceModule = async (
92
127
  module: ParsedModule,
93
128
  references: readonly ModuleReference[],
@@ -157,15 +192,18 @@ interface CompiledReach {
157
192
  readonly origins: readonly string[]
158
193
  }
159
194
 
160
- /** The contract's procedures and origins, or `null` when it does not compile, which its own rule reports. */
161
- const compiledReach = (contract: AnyContract, tables: Tables<unknown, unknown> | null): CompiledReach | null => {
162
- let artifact: ContractArtifact
195
+ /** The contract's artifact, or `null` when it does not compile, which its own rule reports. */
196
+ const compiledArtifact = (contract: AnyContract, tables: Tables<unknown, unknown> | null): ContractArtifact | null => {
163
197
  try {
164
- artifact = compileContract(contract, tables ?? {})
198
+ return compileContract(contract, tables ?? {})
165
199
  } catch (error) {
166
200
  if (error instanceof ContractError) return null
167
201
  throw error
168
202
  }
203
+ }
204
+
205
+ /** The contract's procedures and origins. */
206
+ const compiledReach = (artifact: ContractArtifact): CompiledReach => {
169
207
  const procedures = artifact.endpoints.filter((row) =>
170
208
  (row.kind === 'query' || row.kind === 'mutation' || row.kind === 'public') && row.source.kind === 'mount'
171
209
  )
@@ -226,7 +264,8 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
226
264
  modules.set(path, parsed.module)
227
265
  const referencesOfModule = moduleReferences(parsed.module.program)
228
266
  references.set(path, referencesOfModule)
229
- await checkSourceModule(parsed.module, referencesOfModule, text, mappings, tree.files, findings, dependent)
267
+ if (isToolModule(path)) await checkToolModule(parsed.module, text, tree.files, findings)
268
+ else await checkSourceModule(parsed.module, referencesOfModule, text, mappings, tree.files, findings, dependent)
230
269
  }
231
270
  const structure = { files: tree.files, mappings, referencesOf: (path: string) => references.get(path) ?? [] }
232
271
  for (const path of modules.keys()) {
@@ -252,9 +291,19 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
252
291
  for (const module of contract === undefined ? [] : contractModules(graph, contract)) findings.push(...checkClientIdentity(module, graph))
253
292
  findings.push(...(await checkGeneratedTests(tree.files, literal.length === 0 && trust.length === 0 && contractRead.length === 0)))
254
293
  findings.push(...checkMigrationNames(checkedPaths))
294
+ if (input.migrationBase !== undefined) findings.push(...checkMigrationHistory(tree.files, input.migrationBase))
295
+ findings.push(...checkToolPackages(checkedPaths))
255
296
  const read = contract !== undefined && literal.length === 0 && contractRead.length === 0 ? readContractModule(graph) : undefined
256
297
  const declaredTables = tables !== undefined && literal.length === 0 ? readTablesValue(graph, tables, new ReaderProblems()) : null
257
- findings.push(...contractDependentFindings(dependent, read?.ok === true ? compiledReach(read.contract, declaredTables) : null))
298
+ const artifact = read?.ok === true ? compiledArtifact(read.contract, declaredTables) : null
299
+ findings.push(...contractDependentFindings(dependent, artifact === null ? null : compiledReach(artifact)))
300
+ if (artifact !== null) findings.push(...checkMigrationClassification(tree.files, artifact.app))
301
+ if (applicationDialect(tree.files) === 'sqlite') {
302
+ if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
303
+ findings.push(...checkCurrentTimestampDefaults(tree.files))
304
+ findings.push(...checkSqliteFrameworkNames(tree.files))
305
+ findings.push(...(await checkBackupPlan(tree.files)))
306
+ }
258
307
  if (declaredTables !== null) {
259
308
  const policies = tablePolicies(declaredTables)
260
309
  findings.push(...checkFileColumnMigrations(tree.files, fileColumns(policies)))
package/src/cli.ts CHANGED
@@ -4,12 +4,14 @@ import { readFile } from 'node:fs/promises'
4
4
  import { resolve } from 'node:path'
5
5
  import { checkApplication } from './check'
6
6
  import { type Finding, formatFinding } from './finding'
7
+ import { readMigrationBase } from './migration-base'
7
8
  import { type PackedSet, readPackedSet } from './packed'
9
+ import type { MigrationBase } from './rules/migration-history'
8
10
 
9
11
  const USAGE = `fabrika-check — the application checker
10
12
 
11
13
  Usage:
12
- fabrika-check [--packed <release-manifest.json>] [<root>]
14
+ fabrika-check [--packed <release-manifest.json>] [--base <ref>] [<root>]
13
15
 
14
16
  Checks the application in <root> (default: the current directory) and prints one line per finding:
15
17
  <file>:<line>:<column> <rule> <message> (allowed form: <what to write instead>)
@@ -18,6 +20,10 @@ Checks the application in <root> (default: the current directory) and prints one
18
20
  file: specifiers and overrides of its @fabrika/* packages, and their lockfile entries, when each tarball's bytes
19
21
  match the sha512 the manifest records. Only a local or dogfood setup passes it; the platform build never does.
20
22
 
23
+ In a git work tree, every migration of db/migrations at the merge base of HEAD and the remote's default branch
24
+ (origin/HEAD, else origin/main or origin/master) must be in the tree unchanged: a deploy refuses a migration that
25
+ changed after it was applied. --base names another ref to compare with.
26
+
21
27
  A refusal fails the check. A hint, printed under its own heading after the refusals, reports a step out of the
22
28
  application architecture and does not fail it.
23
29
 
@@ -32,20 +38,24 @@ const count = (amount: number, noun: string): string => `${amount} ${noun}${amou
32
38
  interface Arguments {
33
39
  readonly root: string | undefined
34
40
  readonly packed: string | undefined
41
+ readonly base: string | undefined
35
42
  }
36
43
 
37
- /** The root and the `--packed` manifest, or the first argument the checker does not take. */
44
+ /** The root, the `--packed` manifest and the `--base` ref, or the first argument the checker does not take. */
38
45
  const parseArguments = (argv: readonly string[]): Arguments | { readonly unexpected: string } => {
39
46
  let root: string | undefined
40
47
  let packed: string | undefined
48
+ let base: string | undefined
41
49
  for (let index = 0; index < argv.length; index++) {
42
50
  const argument = argv[index] ?? ''
43
51
  if (argument === '--packed' && packed === undefined && argv[index + 1] !== undefined) packed = argv[++index]
44
52
  else if (argument.startsWith('--packed=') && packed === undefined) packed = argument.slice('--packed='.length)
53
+ else if (argument === '--base' && base === undefined && argv[index + 1] !== undefined) base = argv[++index]
54
+ else if (argument.startsWith('--base=') && base === undefined && argument.length > '--base='.length) base = argument.slice('--base='.length)
45
55
  else if (argument.startsWith('-') || root !== undefined) return { unexpected: argument }
46
56
  else root = argument
47
57
  }
48
- return { root, packed }
58
+ return { root, packed, base }
49
59
  }
50
60
 
51
61
  const main = async (argv: readonly string[]): Promise<number> => {
@@ -69,9 +79,18 @@ const main = async (argv: readonly string[]): Promise<number> => {
69
79
  }
70
80
  console.error(`fabrika-check: accepting the tarballs of the local pack ${packed.version}, which no deploy build does`)
71
81
  }
82
+ const read = await readMigrationBase(root, parsed.base)
83
+ let migrationBase: MigrationBase | undefined
84
+ if (read !== null && !('skipped' in read)) migrationBase = read
85
+ else if (parsed.base !== undefined) {
86
+ console.error(
87
+ `fabrika-check: cannot compare the migrations with ${parsed.base}: ${read === null ? `${root} is in no git work tree` : read.skipped}`,
88
+ )
89
+ return 2
90
+ } else if (read !== null) console.error(`fabrika-check: migration-edited did not run: ${read.skipped}`)
72
91
  let findings: Finding[]
73
92
  try {
74
- findings = await checkApplication({ root, packed })
93
+ findings = await checkApplication({ root, packed, migrationBase })
75
94
  } catch (error) {
76
95
  console.error(`fabrika-check: cannot read ${root}: ${error instanceof Error ? error.message : 'unknown error'}`)
77
96
  return 2
package/src/dialect.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { child, identifierName, parseModule } from './ast'
2
+ import { ModuleGraph, unwrapValue } from './graph'
3
+ import { CONFIG_FILE } from './layout'
4
+
5
+ /** The database an application's data layer runs on: SQLite in its Durable Object on Cloudflare (ADR-0065), else Postgres. */
6
+ export type ApplicationDialect = 'postgres' | 'sqlite'
7
+
8
+ const CLOUDFLARE_PROVIDER = '@fabrika/provider-cloudflare'
9
+
10
+ /**
11
+ * Read statically from `fabrika.config.ts`: SQLite when its default export is a call of the `defineApp` that
12
+ * `@fabrika/provider-cloudflare` exports, the config every Cloudflare application writes. Postgres otherwise,
13
+ * including without a config or when the call's origin is not static.
14
+ */
15
+ export const applicationDialect = (files: ReadonlyMap<string, string>): ApplicationDialect => {
16
+ const text = files.get(CONFIG_FILE)
17
+ if (text === undefined) return 'postgres'
18
+ const parsed = parseModule(CONFIG_FILE, text)
19
+ if (!parsed.ok) return 'postgres'
20
+ const graph = new ModuleGraph(new Map([[CONFIG_FILE, parsed.module]]))
21
+ const exported = graph.exported(parsed.module, 'default')
22
+ if (exported.kind !== 'default') return 'postgres'
23
+ const call = unwrapValue(exported.expression)
24
+ if (call.type !== 'CallExpression') return 'postgres'
25
+ const callee = identifierName(child(call, 'callee'))
26
+ if (callee === undefined) return 'postgres'
27
+ const binding = graph.binding(parsed.module, callee)
28
+ return binding.kind === 'package' && binding.specifier === CLOUDFLARE_PROVIDER && binding.imported === 'defineApp' ? 'sqlite' : 'postgres'
29
+ }
@@ -4,10 +4,19 @@
4
4
  // that name a member the handler looks up (`deals.assign`'s `ownerId`), which the kit fills with a real member;
5
5
  // `invitations` and `links` the fields that name an invitation the handler cancels or a share link it revokes, which the
6
6
  // kit fills with one it holds; `rows` the fields that name a row lying in the endpoint's object (a note's comment), by
7
- // table, which the kit seeds in each scope's object. Read from source, never executed, within the reader's budget:
8
- // `export const fixtures = { '<endpoint id>': { … } }`, `export const seeds = { '<endpoint id>': { <column>: <value> } }`,
9
- // `export const members = { '<endpoint id>': ['<field>'] }` (`invitations`, `links` alike) and
10
- // `export const rows = { '<endpoint id>': { <field>: '<table>' } }`, plain literals only.
7
+ // table, which the kit seeds in each scope's object; `appRows` the rows of application tables an endpoint's own case
8
+ // reads (the guide a link holder downloads), by table, with their columns, which the kit seeds before each leak or own
9
+ // case asks and removes once it is over; `files` the file of the repository each generated case sends in a file field
10
+ // (a package a handler inspects), by input field, relative to the application's root; `refusals` the error types of the
11
+ // 400s an endpoint's handler answers its own object with when no fixture can meet its domain rule, which the kit then
12
+ // counts as the handler's answer; `pins` known values of text columns of the row an endpoint addresses (a skill's slug a
13
+ // package must name), the own scope's, which the kit writes there instead of a marker.
14
+ // Read from source, never executed, within the reader's budget: `export const fixtures = { '<endpoint id>': { … } }`,
15
+ // `export const seeds = { '<endpoint id>': { <column>: <value> } }`, `export const members = { '<endpoint id>':
16
+ // ['<field>'] }` (`invitations`, `links` alike), `export const rows = { '<endpoint id>': { <field>: '<table>' } }` and
17
+ // `export const appRows = { '<endpoint id>': { <table>: { <column>: <value> } } }`, `export const files = { '<endpoint
18
+ // id>': { <field>: '<path>' } }`, `export const refusals = { '<endpoint id>': ['<error type>'] }` and `export const pins
19
+ // = { '<endpoint id>': { <column>: '<value>' } }`, plain literals only.
11
20
  // Browser-safe.
12
21
 
13
22
  import { type AstNode, child, children, identifierName, nodeDepth, parseModule, positionOf, staticKey, staticString } from './ast'
@@ -22,14 +31,18 @@ export const MEMBERS_EXPORT = 'members'
22
31
  export const INVITATIONS_EXPORT = 'invitations'
23
32
  export const LINKS_EXPORT = 'links'
24
33
  export const ROWS_EXPORT = 'rows'
34
+ export const APP_ROWS_EXPORT = 'appRows'
35
+ export const FILES_EXPORT = 'files'
36
+ export const REFUSALS_EXPORT = 'refusals'
37
+ export const PINS_EXPORT = 'pins'
25
38
 
26
- /** The exports that list, by endpoint id, the input fields the kit fills with something it holds. */
27
- const FIELD_EXPORTS = [MEMBERS_EXPORT, INVITATIONS_EXPORT, LINKS_EXPORT] as const
39
+ /** The exports that list strings by endpoint id: the input fields the kit fills with something it holds, and the refusals. */
40
+ const FIELD_EXPORTS = [MEMBERS_EXPORT, INVITATIONS_EXPORT, LINKS_EXPORT, REFUSALS_EXPORT] as const
28
41
  type FieldExport = (typeof FIELD_EXPORTS)[number]
29
42
  const isFieldExport = (name: string | undefined): name is FieldExport => FIELD_EXPORTS.some((field) => field === name)
30
43
 
31
44
  const ALLOWED =
32
- "export const fixtures = { 'api.notes.get': { id: '…' } }, export const seeds = { 'api.deals.reopen': { stage: 'won' } }, export const members = { 'api.deals.assign': ['ownerId'] }, export const invitations = { 'api.members.cancel': ['invitationId'] }, export const links = { 'api.notes.unshare': ['linkId'] } and export const rows = { 'api.notes.editComment': { commentId: 'note_comments' } }: string keys, and strings, numbers, booleans, null, arrays and objects"
45
+ "export const fixtures = { 'api.notes.get': { id: '…' } }, export const seeds = { 'api.deals.reopen': { stage: 'won' } }, export const members = { 'api.deals.assign': ['ownerId'] }, export const invitations = { 'api.members.cancel': ['invitationId'] }, export const links = { 'api.notes.unshare': ['linkId'] }, export const rows = { 'api.notes.editComment': { commentId: 'note_comments' } }, export const appRows = { 'portal.guide': { guides: { active: true } } }, export const files = { 'api.skills.publish': { package: 'src/__tests__/fixtures/skill.zip' } }, export const refusals = { 'api.skills.publish': ['skill_frontmatter'] } and export const pins = { 'api.skills.publish': { slug: 'sample-skill' } }: string keys, and strings, numbers, booleans, null, arrays and objects"
33
46
 
34
47
  type ById = Readonly<Record<string, Readonly<Record<string, Sample>>>>
35
48
 
@@ -46,9 +59,35 @@ export interface EndpointFixtures {
46
59
  readonly links: Readonly<Record<string, readonly string[]>>
47
60
  /** The input fields that name a row lying in the endpoint's object, with that row's table, by endpoint id. */
48
61
  readonly rows: Readonly<Record<string, Readonly<Record<string, string>>>>
62
+ /** The rows of application tables the endpoint's own case reads, by table, each with its columns, by endpoint id. */
63
+ readonly appRows: Readonly<Record<string, Readonly<Record<string, Readonly<Record<string, Sample>>>>>>
64
+ /** The file each case sends in a file field, a path relative to the application's root, by input field, by endpoint id. */
65
+ readonly files: Readonly<Record<string, Readonly<Record<string, string>>>>
66
+ /** The error types of the 400s an endpoint's handler may answer its own object with, by endpoint id. */
67
+ readonly refusals: Readonly<Record<string, readonly string[]>>
68
+ /** The own scope's value of each pinned text column of the row the endpoint addresses, by endpoint id. */
69
+ readonly pins: Readonly<Record<string, Readonly<Record<string, string>>>>
49
70
  }
50
71
 
51
- export const NO_FIXTURES: EndpointFixtures = { inputs: {}, seeds: {}, members: {}, invitations: {}, links: {}, rows: {} }
72
+ export const NO_FIXTURES: EndpointFixtures = {
73
+ inputs: {},
74
+ seeds: {},
75
+ members: {},
76
+ invitations: {},
77
+ links: {},
78
+ rows: {},
79
+ appRows: {},
80
+ files: {},
81
+ refusals: {},
82
+ pins: {},
83
+ }
84
+
85
+ /**
86
+ * Whether `path` may name a file fixture: relative to the application's root, `/`-separated, and each segment of
87
+ * letters, digits, `_`, `-` and `.` that starts with neither `.` nor `-`, so it never leaves the root, names no dotfile and
88
+ * reads the same as a URL path.
89
+ */
90
+ export const isFixtureFilePath = (path: string): boolean => /^[A-Za-z0-9_][A-Za-z0-9._-]*(\/[A-Za-z0-9_][A-Za-z0-9._-]*)*$/.test(path)
52
91
 
53
92
  const finding = (at: AstNode | undefined, message: string): Finding => {
54
93
  const { line, column } = at === undefined ? { line: 1, column: 1 } : positionOf(at)
@@ -118,14 +157,15 @@ function byId(
118
157
  const entries: Record<string, Readonly<Record<string, Sample>>> = {}
119
158
  for (const [id, entry] of Object.entries(all)) {
120
159
  if (!isSampleObject(entry)) {
121
- return { ok: false, findings: [finding(init, `the ${name} of ${id} is not an object of ${name === SEEDS_EXPORT ? 'columns' : 'input fields'}`)] }
160
+ const of = name === SEEDS_EXPORT ? 'columns' : name === APP_ROWS_EXPORT ? 'tables' : 'input fields'
161
+ return { ok: false, findings: [finding(init, `the ${name} of ${id} is not an object of ${of}`)] }
122
162
  }
123
163
  entries[id] = entry
124
164
  }
125
165
  return { ok: true, value: entries }
126
166
  }
127
167
 
128
- /** `export const <members, invitations or links> = { '<endpoint id>': ['<field>', …] }`, read into field lists. */
168
+ /** `export const <members, invitations, links or refusals> = { '<endpoint id>': ['<field>', …] }`, read into lists. */
129
169
  function fieldsById(
130
170
  declarator: AstNode,
131
171
  name: FieldExport,
@@ -142,13 +182,23 @@ function fieldsById(
142
182
  const entries: Record<string, readonly string[]> = {}
143
183
  for (const [id, fields] of Object.entries(value.value)) {
144
184
  if (!Array.isArray(fields) || fields.length === 0 || !fields.every((field) => typeof field === 'string')) {
145
- return { ok: false, findings: [finding(init, `the ${name} of ${id} is not a list of input field names`)] }
185
+ const of = name === REFUSALS_EXPORT ? 'error types' : 'input field names'
186
+ return { ok: false, findings: [finding(init, `the ${name} of ${id} is not a list of ${of}`)] }
146
187
  }
147
188
  entries[id] = fields.filter((field) => typeof field === 'string')
148
189
  }
149
190
  return { ok: true, value: entries }
150
191
  }
151
192
 
193
+ /** Each entry's string values, by endpoint id: what `rows`, `files` and `pins` hold once checked. */
194
+ const stringsById = (byIdValue: ById): Readonly<Record<string, Readonly<Record<string, string>>>> =>
195
+ Object.fromEntries(
196
+ Object.entries(byIdValue).map(([id, named]) => [
197
+ id,
198
+ Object.fromEntries(Object.entries(named).flatMap(([key, item]) => (typeof item === 'string' ? [[key, item]] : []))),
199
+ ]),
200
+ )
201
+
152
202
  /** The fixtures of `files`, by endpoint id; none without the file. */
153
203
  export function readEndpointFixtures(
154
204
  files: ReadonlyMap<string, string>,
@@ -173,7 +223,9 @@ export function readEndpointFixtures(
173
223
  const name = declarator === null || declarator === undefined ? undefined : identifierName(child(declarator, 'id'))
174
224
  if (
175
225
  statement?.type !== 'ExportNamedDeclaration' || declarator === null || declarator === undefined
176
- || (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && !isFieldExport(name)) || read.has(name)
226
+ || (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && name !== APP_ROWS_EXPORT && name !== FILES_EXPORT
227
+ && name !== PINS_EXPORT && !isFieldExport(name))
228
+ || read.has(name)
177
229
  || (isFieldExport(name) && fields.has(name))
178
230
  ) {
179
231
  return {
@@ -181,7 +233,7 @@ export function readEndpointFixtures(
181
233
  findings: [
182
234
  finding(
183
235
  statement ?? undefined,
184
- `the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT} and ${LINKS_EXPORT} = { … }, each at most once`,
236
+ `the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT}, ${LINKS_EXPORT}, ${ROWS_EXPORT}, ${APP_ROWS_EXPORT}, ${FILES_EXPORT}, ${REFUSALS_EXPORT} and ${PINS_EXPORT} = { … }, each at most once`,
185
237
  ),
186
238
  ],
187
239
  }
@@ -200,6 +252,26 @@ export function readEndpointFixtures(
200
252
  return { ok: false, findings: [finding(child(declarator, 'init'), `the rows of ${named[0]} name each field's table as a string`)] }
201
253
  }
202
254
  }
255
+ if (name === FILES_EXPORT) {
256
+ const named = Object.entries(value.value).find(([, fields]) => Object.values(fields).some((path) => typeof path !== 'string'))
257
+ if (named !== undefined) {
258
+ return { ok: false, findings: [finding(child(declarator, 'init'), `the files of ${named[0]} name each field's file as a path string`)] }
259
+ }
260
+ }
261
+ if (name === PINS_EXPORT) {
262
+ const named = Object.entries(value.value).find(([, columns]) =>
263
+ Object.values(columns).some((pinned) => typeof pinned !== 'string' || pinned === '')
264
+ )
265
+ if (named !== undefined) {
266
+ return { ok: false, findings: [finding(child(declarator, 'init'), `the pins of ${named[0]} give each column a non-empty string`)] }
267
+ }
268
+ }
269
+ if (name === APP_ROWS_EXPORT) {
270
+ const named = Object.entries(value.value).find(([, tables]) => Object.values(tables).some((columns) => !isSampleObject(columns)))
271
+ if (named !== undefined) {
272
+ return { ok: false, findings: [finding(child(declarator, 'init'), `the appRows of ${named[0]} give each table's row as an object of columns`)] }
273
+ }
274
+ }
203
275
  read.set(name, value.value)
204
276
  }
205
277
  return {
@@ -210,12 +282,26 @@ export function readEndpointFixtures(
210
282
  members: fields.get(MEMBERS_EXPORT) ?? {},
211
283
  invitations: fields.get(INVITATIONS_EXPORT) ?? {},
212
284
  links: fields.get(LINKS_EXPORT) ?? {},
285
+ refusals: fields.get(REFUSALS_EXPORT) ?? {},
213
286
  rows: Object.fromEntries(
214
287
  Object.entries(read.get(ROWS_EXPORT) ?? {}).map(([id, named]) => [
215
288
  id,
216
289
  Object.fromEntries(Object.entries(named).flatMap(([field, table]) => (typeof table === 'string' ? [[field, table]] : []))),
217
290
  ]),
218
291
  ),
292
+ appRows: Object.fromEntries(
293
+ Object.entries(read.get(APP_ROWS_EXPORT) ?? {}).map(([id, tables]) => [
294
+ id,
295
+ Object.fromEntries(Object.entries(tables).flatMap(([table, columns]) => (isSampleObject(columns) ? [[table, columns]] : []))),
296
+ ]),
297
+ ),
298
+ pins: stringsById(read.get(PINS_EXPORT) ?? {}),
299
+ files: Object.fromEntries(
300
+ Object.entries(read.get(FILES_EXPORT) ?? {}).map(([id, named]) => [
301
+ id,
302
+ Object.fromEntries(Object.entries(named).flatMap(([field, path]) => (typeof path === 'string' ? [[field, path]] : []))),
303
+ ]),
304
+ ),
219
305
  },
220
306
  }
221
307
  }
package/src/finding.ts CHANGED
@@ -28,6 +28,9 @@ export const REFUSAL_RULE_IDS = [
28
28
  'unsafe-html',
29
29
  'dynamic-code',
30
30
  'migration-name',
31
+ 'migration-refused',
32
+ 'backup-schema',
33
+ 'migration-edited',
31
34
  'file-column-migration',
32
35
  'crontab',
33
36
  'package-replacement',
@@ -40,16 +43,22 @@ export const REFUSAL_RULE_IDS = [
40
43
  'layer-import',
41
44
  'generated-test-import',
42
45
  'shared-import',
46
+ 'tool-import',
47
+ 'cloudflare-scan',
48
+ 'cloudflare-job-segment',
49
+ 'cloudflare-current-timestamp',
50
+ 'cloudflare-framework-name',
43
51
  ] as const
44
52
 
45
53
  /** Rules that report a step out of the application architecture. */
46
54
  export const STRUCTURE_HINT_RULE_IDS = ['logic-data-access', 'cross-slice-queries', 'handler-location', 'data-access-location'] as const
47
55
 
48
56
  /**
49
- * Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, and a
50
- * `{ member: true }` endpoint of a contract whose external role admits people from outside the organization.
57
+ * Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, a
58
+ * `{ member: true }` endpoint of a contract whose external role admits people from outside the organization, and a
59
+ * Cloudflare mutation that waits for an outside call inside the object's transaction.
51
60
  */
52
- export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external'] as const
61
+ export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external', 'cloudflare-held-call'] as const
53
62
 
54
63
  export const RULE_IDS = [...REFUSAL_RULE_IDS, ...HINT_RULE_IDS] as const
55
64
 
package/src/index.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  export { type ApplicationTree, checkApplication, type CheckInput, readApplicationTree } from './check'
2
+ export { type ApplicationDialect, applicationDialect } from './dialect'
2
3
  export { type Finding, formatFinding, RULE_IDS, type RuleId } from './finding'
3
- export { CONTRACT_FILE, GENERATED_ENTRY_FILE, MIGRATIONS_DIR, TABLES_FILE, ZEROPS_FILES } from './layout'
4
+ export { CONFIG_FILE, CONTRACT_FILE, GENERATED_ENTRY_FILE, MIGRATIONS_DIR, TABLES_FILE, ZEROPS_FILES } from './layout'
5
+ export { readMigrationBase } from './migration-base'
4
6
  export { type PackedSet, type PackedTarball, readPackedSet } from './packed'
7
+ export type { MigrationBase } from './rules/migration-history'
5
8
  export { GENERATED_TEST_HEADER, generatedTestHeader } from './rules/tests'
6
9
  export {
7
10
  ENDPOINT_ACCESS_TEST,
package/src/layout.ts CHANGED
@@ -1,11 +1,15 @@
1
1
  /** Where an application keeps what the checker reads. Paths are relative to the application root. */
2
2
  export const CONTRACT_FILE = 'fabrika.contract.ts'
3
+ /** The provider-authored application config, whose `defineApp` names the provider. */
4
+ export const CONFIG_FILE = 'fabrika.config.ts'
3
5
  /** The named export of the contract module that holds `defineContract(…)`. */
4
6
  export const CONTRACT_EXPORT = 'contract'
5
7
  export const TABLES_FILE = 'src/db/tables.ts'
6
8
  /** The named export of the tables module that holds `defineTables(…)(…)`. */
7
9
  export const TABLES_EXPORT = 'tables'
8
10
  export const GENERATED_ENTRY_FILE = 'fabrika/entry.generated.ts'
11
+ /** Where a Cloudflare deploy stages the SPA mounts' built files (`@fabrika/provider-cloudflare`): build output, never source. */
12
+ export const STAGED_ASSETS_DIR = 'fabrika/assets/'
9
13
  export const MIGRATIONS_DIR = 'db/migrations/'
10
14
  /** Where `fabrika db test-scaffold` writes the policy isolation tests, `<table>.policy-isolation.test.ts`. */
11
15
  export const POLICY_TESTS_DIR = 'src/db/__tests__/'
@@ -33,6 +37,11 @@ export const SLICE_QUERIES_FILE = 'queries.ts'
33
37
  export const SPA_DIR = 'web/'
34
38
  /** The server half of an application: its modules run in the application's process. */
35
39
  export const SERVER_DIR = 'src/'
40
+ /**
41
+ * A developer's tools, such as a command line over the contract: code that runs on a developer's machine and never in
42
+ * the application, so the rules for code that runs there do not apply, and no module outside it may load one.
43
+ */
44
+ export const TOOLS_DIR = 'tools/'
36
45
 
37
46
  const SOURCE_EXTENSION = /\.(?:[mc]?[jt]s|[jt]sx)$/
38
47
  const TEST_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[mc]?[jt]sx?$/
@@ -40,6 +49,9 @@ const TEST_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[mc]?[jt]sx?$/
40
49
  /** Build output, installed packages and tool state are not application source and are never read. */
41
50
  export const isIgnoredSegment = (segment: string): boolean => segment === 'node_modules' || segment === 'dist' || segment.startsWith('.')
42
51
 
52
+ /** Whether the checker skips `path` (relative to the root): under a skipped segment, or the staged SPA files. */
53
+ export const isSkippedPath = (path: string): boolean => path.split('/').some(isIgnoredSegment) || path.startsWith(STAGED_ASSETS_DIR)
54
+
43
55
  export const isSourceFile = (path: string): boolean => SOURCE_EXTENSION.test(path)
44
56
 
45
57
  export const isTestFile = (path: string): boolean => TEST_FILE.test(path)
@@ -47,13 +59,16 @@ export const isTestFile = (path: string): boolean => TEST_FILE.test(path)
47
59
  /** A module that runs in the application's server process: under `src/`, not a test. */
48
60
  export const isServerModule = (path: string): boolean => path.startsWith(SERVER_DIR) && !isTestFile(path)
49
61
 
62
+ /** A module under `tools/`, tests included. */
63
+ export const isToolModule = (path: string): boolean => path.startsWith(TOOLS_DIR)
64
+
50
65
  export const isJsonFile = (path: string): boolean => path.endsWith('.json')
51
66
 
52
67
  /** Whether the checker reads this file at all. */
53
68
  export const isCheckedFile = (path: string): boolean => {
54
69
  // The registry configuration and the lockfile decide what a trusted package name installs.
55
70
  if (path === '.npmrc' || path === 'bun.lock') return true
56
- if (path.split('/').some(isIgnoredSegment)) return false
71
+ if (isSkippedPath(path)) return false
57
72
  return isSourceFile(path) || isJsonFile(path) || path.startsWith(MIGRATIONS_DIR) || ZEROPS_FILES.some((name) => name === path)
58
73
  || path === 'bunfig.toml'
59
74
  }