@fabrika/check 0.9.0-dev.7 → 0.9.0-dev.9

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/check",
3
- "version": "0.9.0-dev.7",
3
+ "version": "0.9.0-dev.9",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -47,11 +47,11 @@
47
47
  },
48
48
  "dependencies": {
49
49
  "@babel/parser": "8.0.7",
50
- "@fabrika/app": "0.9.0-dev.7",
51
- "@fabrika/auth-core": "0.9.0-dev.7",
52
- "@fabrika/db": "0.9.0-dev.7",
53
- "@fabrika/operations-contract": "0.9.0-dev.7",
54
- "@fabrika/platform-node": "0.9.0-dev.7",
50
+ "@fabrika/app": "0.9.0-dev.9",
51
+ "@fabrika/auth-core": "0.9.0-dev.9",
52
+ "@fabrika/db": "0.9.0-dev.9",
53
+ "@fabrika/operations-contract": "0.9.0-dev.9",
54
+ "@fabrika/platform-node": "0.9.0-dev.9",
55
55
  "zod": "^3.25.76"
56
56
  }
57
57
  }
package/src/check.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  isServerModule,
18
18
  isSourceFile,
19
19
  isTestFile,
20
+ isToolModule,
20
21
  TABLES_FILE,
21
22
  ZEROPS_FILES,
22
23
  } from './layout'
@@ -33,6 +34,7 @@ import { checkClientIdentity } from './rules/identity'
33
34
  import { checkGeneratedTests } from './rules/isolation'
34
35
  import { checkJsonStrings } from './rules/json'
35
36
  import { checkLiteralGraph } from './rules/literal'
37
+ import { checkMigrationHistory, type MigrationBase } from './rules/migration-history'
36
38
  import {
37
39
  checkConflictIndexes,
38
40
  checkCurrentTimestampDefaults,
@@ -44,8 +46,9 @@ import {
44
46
  } from './rules/migrations'
45
47
  import { checkModuleReferences } from './rules/modules'
46
48
  import { checkAmbientModule, checkPackageReplacement } from './rules/packages'
47
- import { checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
48
- 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'
49
52
  import { checkGeneratedTest, checkMockModule, checkTestNode, checkTestSuiteConfig } from './rules/tests'
50
53
  import { checkComments, checkTypeNode } from './rules/types'
51
54
  import { moduleSlice, sliceFinding } from './slice'
@@ -62,6 +65,8 @@ export interface CheckInput {
62
65
  readonly files?: ReadonlyMap<string, string>
63
66
  /** A local pack whose tarballs `package-replacement` accepts (`fabrika-check --packed`); a deploy build gives none. */
64
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
65
70
  }
66
71
 
67
72
  export interface ApplicationTree {
@@ -98,6 +103,26 @@ interface ContractDependent {
98
103
  readonly inserts: ConflictInsert[]
99
104
  }
100
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
+
101
126
  const checkSourceModule = async (
102
127
  module: ParsedModule,
103
128
  references: readonly ModuleReference[],
@@ -239,7 +264,8 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
239
264
  modules.set(path, parsed.module)
240
265
  const referencesOfModule = moduleReferences(parsed.module.program)
241
266
  references.set(path, referencesOfModule)
242
- 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)
243
269
  }
244
270
  const structure = { files: tree.files, mappings, referencesOf: (path: string) => references.get(path) ?? [] }
245
271
  for (const path of modules.keys()) {
@@ -265,14 +291,18 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
265
291
  for (const module of contract === undefined ? [] : contractModules(graph, contract)) findings.push(...checkClientIdentity(module, graph))
266
292
  findings.push(...(await checkGeneratedTests(tree.files, literal.length === 0 && trust.length === 0 && contractRead.length === 0)))
267
293
  findings.push(...checkMigrationNames(checkedPaths))
294
+ if (input.migrationBase !== undefined) findings.push(...checkMigrationHistory(tree.files, input.migrationBase))
295
+ findings.push(...checkToolPackages(checkedPaths))
268
296
  const read = contract !== undefined && literal.length === 0 && contractRead.length === 0 ? readContractModule(graph) : undefined
269
297
  const declaredTables = tables !== undefined && literal.length === 0 ? readTablesValue(graph, tables, new ReaderProblems()) : null
270
298
  const artifact = read?.ok === true ? compiledArtifact(read.contract, declaredTables) : null
271
299
  findings.push(...contractDependentFindings(dependent, artifact === null ? null : compiledReach(artifact)))
300
+ if (artifact !== null) findings.push(...checkMigrationClassification(tree.files, artifact.app))
272
301
  if (applicationDialect(tree.files) === 'sqlite') {
273
302
  if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
274
303
  findings.push(...checkCurrentTimestampDefaults(tree.files))
275
304
  findings.push(...checkSqliteFrameworkNames(tree.files))
305
+ findings.push(...(await checkBackupPlan(tree.files)))
276
306
  }
277
307
  if (declaredTables !== null) {
278
308
  const policies = tablePolicies(declaredTables)
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/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,6 +43,7 @@ export const REFUSAL_RULE_IDS = [
40
43
  'layer-import',
41
44
  'generated-test-import',
42
45
  'shared-import',
46
+ 'tool-import',
43
47
  'cloudflare-scan',
44
48
  'cloudflare-job-segment',
45
49
  'cloudflare-current-timestamp',
package/src/index.ts CHANGED
@@ -2,7 +2,9 @@ export { type ApplicationTree, checkApplication, type CheckInput, readApplicatio
2
2
  export { type ApplicationDialect, applicationDialect } from './dialect'
3
3
  export { type Finding, formatFinding, RULE_IDS, type RuleId } from './finding'
4
4
  export { CONFIG_FILE, CONTRACT_FILE, GENERATED_ENTRY_FILE, MIGRATIONS_DIR, TABLES_FILE, ZEROPS_FILES } from './layout'
5
+ export { readMigrationBase } from './migration-base'
5
6
  export { type PackedSet, type PackedTarball, readPackedSet } from './packed'
7
+ export type { MigrationBase } from './rules/migration-history'
6
8
  export { GENERATED_TEST_HEADER, generatedTestHeader } from './rules/tests'
7
9
  export {
8
10
  ENDPOINT_ACCESS_TEST,
package/src/layout.ts CHANGED
@@ -37,6 +37,11 @@ export const SLICE_QUERIES_FILE = 'queries.ts'
37
37
  export const SPA_DIR = 'web/'
38
38
  /** The server half of an application: its modules run in the application's process. */
39
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/'
40
45
 
41
46
  const SOURCE_EXTENSION = /\.(?:[mc]?[jt]s|[jt]sx)$/
42
47
  const TEST_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[mc]?[jt]sx?$/
@@ -54,6 +59,9 @@ export const isTestFile = (path: string): boolean => TEST_FILE.test(path)
54
59
  /** A module that runs in the application's server process: under `src/`, not a test. */
55
60
  export const isServerModule = (path: string): boolean => path.startsWith(SERVER_DIR) && !isTestFile(path)
56
61
 
62
+ /** A module under `tools/`, tests included. */
63
+ export const isToolModule = (path: string): boolean => path.startsWith(TOOLS_DIR)
64
+
57
65
  export const isJsonFile = (path: string): boolean => path.endsWith('.json')
58
66
 
59
67
  /** Whether the checker reads this file at all. */
@@ -0,0 +1,85 @@
1
+ // The migrations `migration-edited` compares the tree with: those of the merge base of HEAD and the remote's default
2
+ // branch, read with git. Only the bin reads them; a caller with the files of a commit (Control, a deploy build) has no
3
+ // history to compare with, and the runner's checksum stays the real check.
4
+
5
+ import { MIGRATIONS_DIR } from './layout'
6
+ import type { MigrationBase } from './rules/migration-history'
7
+
8
+ /** What the default base is looked up as, in order, when the bin is given no `--base`. */
9
+ const DEFAULT_REFS = ['origin/main', 'origin/master']
10
+
11
+ interface GitResult {
12
+ readonly ok: boolean
13
+ readonly stdout: Uint8Array
14
+ }
15
+
16
+ const git = async (root: string, args: readonly string[], stdin?: string): Promise<GitResult> => {
17
+ const input = stdin === undefined ? 'ignore' : new TextEncoder().encode(stdin)
18
+ const child = Bun.spawn(['git', '-C', root, ...args], { stdin: input, stdout: 'pipe', stderr: 'ignore' })
19
+ const [code, stdout] = await Promise.all([child.exited, new Response(child.stdout).arrayBuffer()])
20
+ return { ok: code === 0, stdout: new Uint8Array(stdout) }
21
+ }
22
+
23
+ const text = (bytes: Uint8Array): string => new TextDecoder().decode(bytes).trim()
24
+
25
+ /** The remote's default branch: `origin/HEAD` where the clone recorded it, else the first of `DEFAULT_REFS` that exists. */
26
+ const defaultRef = async (root: string): Promise<string | null> => {
27
+ const head = await git(root, ['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD'])
28
+ if (head.ok && text(head.stdout) !== '') return text(head.stdout)
29
+ for (const ref of DEFAULT_REFS) {
30
+ if ((await git(root, ['rev-parse', '--verify', '-q', `${ref}^{commit}`])).ok) return ref
31
+ }
32
+ return null
33
+ }
34
+
35
+ /** Each regular file directly in `db/migrations/` at `commit`, by its blob id. */
36
+ const migrationBlobs = async (root: string, commit: string): Promise<Map<string, string> | null> => {
37
+ const listed = await git(root, ['ls-tree', '-z', commit, '--', MIGRATIONS_DIR])
38
+ if (!listed.ok) return null
39
+ const blobs = new Map<string, string>()
40
+ for (const entry of new TextDecoder().decode(listed.stdout).split('\0')) {
41
+ const match = /^(100644|100755) blob ([0-9a-f]+)\t(.+)$/.exec(entry)
42
+ if (match?.[2] !== undefined && match[3] !== undefined && match[3].endsWith('.sql')) blobs.set(match[3], match[2])
43
+ }
44
+ return blobs
45
+ }
46
+
47
+ /** The blobs' texts, through one `git cat-file --batch`: each answer is `<id> blob <size>\n<bytes>\n`. */
48
+ const blobTexts = async (root: string, blobs: ReadonlyMap<string, string>): Promise<Map<string, string> | null> => {
49
+ if (blobs.size === 0) return new Map()
50
+ const ids = [...blobs.values()]
51
+ const batch = await git(root, ['cat-file', '--batch'], ids.map((id) => `${id}\n`).join(''))
52
+ if (!batch.ok) return null
53
+ const decoder = new TextDecoder()
54
+ const texts = new Map<string, string>()
55
+ let offset = 0
56
+ for (const id of ids) {
57
+ const end = batch.stdout.indexOf(10, offset)
58
+ const header = /^([0-9a-f]+) blob (\d+)$/.exec(decoder.decode(batch.stdout.subarray(offset, end)))
59
+ if (end < 0 || header?.[1] !== id || header[2] === undefined) return null
60
+ const size = Number(header[2])
61
+ texts.set(id, decoder.decode(batch.stdout.subarray(end + 1, end + 1 + size)))
62
+ offset = end + 1 + size + 1
63
+ }
64
+ return new Map([...blobs].map(([path, id]) => [path, texts.get(id) ?? '']))
65
+ }
66
+
67
+ /**
68
+ * The migrations at the merge base of HEAD and `ref` (the remote's default branch when omitted), compared against
69
+ * the merge base so that migrations the default branch added since the branch forked are not read as deleted.
70
+ * `null` when `root` is in no git work tree; `{ skipped }` when it is but the base cannot be read.
71
+ */
72
+ export const readMigrationBase = async (root: string, ref?: string): Promise<MigrationBase | { readonly skipped: string } | null> => {
73
+ if (!(await git(root, ['rev-parse', '--is-inside-work-tree'])).ok) return null
74
+ const named = ref ?? (await defaultRef(root))
75
+ if (named === null) return { skipped: `no origin/HEAD, ${DEFAULT_REFS.join(' or ')} to compare the migrations with; pass --base <ref>` }
76
+ if (named.startsWith('-') || !(await git(root, ['rev-parse', '--verify', '-q', `${named}^{commit}`])).ok) {
77
+ return { skipped: `${named} names no commit` }
78
+ }
79
+ const mergeBase = await git(root, ['merge-base', 'HEAD', named])
80
+ if (!mergeBase.ok) return { skipped: `HEAD and ${named} share no commit this clone holds` }
81
+ const blobs = await migrationBlobs(root, text(mergeBase.stdout))
82
+ const files = blobs === null ? null : await blobTexts(root, blobs)
83
+ if (files === null) return { skipped: `the migrations of ${named} cannot be read` }
84
+ return { ref: named, files }
85
+ }
@@ -0,0 +1,70 @@
1
+ // A migration that a shared branch already holds, edited, renamed or deleted in the tree being checked. Every runner
2
+ // keeps the SHA-256 of each applied file and refuses a deploy whose file changed after it ran (ADR-0017), and Control
3
+ // and the deploy see one commit, not its history: the checker is where the edit can be named before the push.
4
+
5
+ import type { Finding } from '../finding'
6
+ import { MIGRATIONS_DIR } from '../layout'
7
+
8
+ /** The migrations of `db/migrations` at the commit the tree is compared with, by path relative to the root. */
9
+ export interface MigrationBase {
10
+ /** How the commit is named to the author, such as `origin/main`. */
11
+ readonly ref: string
12
+ readonly files: ReadonlyMap<string, string>
13
+ }
14
+
15
+ const ALLOWED = 'the file as it is there, and the change as a new migration (bunx fabrika db new <slug>)'
16
+
17
+ const isMigration = (path: string): boolean => {
18
+ const name = path.slice(MIGRATIONS_DIR.length)
19
+ return path.startsWith(MIGRATIONS_DIR) && name.endsWith('.sql') && !name.includes('/')
20
+ }
21
+
22
+ /** Lines without a trailing carriage return: a Windows checkout's line ends are not an edit of the committed file. */
23
+ const linesOf = (sql: string): string[] => sql.split('\n').map((line) => (line.endsWith('\r') ? line.slice(0, -1) : line))
24
+
25
+ /** The first line where `current` leaves `base`, or its last line when it only lost lines at the end. */
26
+ const firstChangedLine = (base: readonly string[], current: readonly string[]): number | null => {
27
+ const length = Math.max(base.length, current.length)
28
+ for (let index = 0; index < length; index++) {
29
+ if (base[index] !== current[index]) return Math.min(index, current.length - 1) + 1
30
+ }
31
+ return null
32
+ }
33
+
34
+ /**
35
+ * Each migration of `base` that the tree changed (at its first changed line) or no longer holds. A file renamed is one
36
+ * removed and one new, and the new one would run again where the old one ran, so the removal is what is reported.
37
+ */
38
+ export const checkMigrationHistory = (files: ReadonlyMap<string, string>, base: MigrationBase): Finding[] => {
39
+ const findings: Finding[] = []
40
+ for (const [path, committed] of base.files) {
41
+ if (!isMigration(path)) continue
42
+ const name = path.slice(MIGRATIONS_DIR.length)
43
+ const current = files.get(path)
44
+ if (current === undefined) {
45
+ findings.push({
46
+ file: path,
47
+ line: 1,
48
+ column: 1,
49
+ severity: 'refusal',
50
+ rule: 'migration-edited',
51
+ message:
52
+ `'${name}' is in ${base.ref} and was deleted or renamed: an environment that applied it keeps its changes, and a renamed file runs again there`,
53
+ allowed: ALLOWED,
54
+ })
55
+ continue
56
+ }
57
+ const line = firstChangedLine(linesOf(committed), linesOf(current))
58
+ if (line === null) continue
59
+ findings.push({
60
+ file: path,
61
+ line,
62
+ column: 1,
63
+ severity: 'refusal',
64
+ rule: 'migration-edited',
65
+ message: `'${name}' differs from ${base.ref}: a deploy refuses a migration that changed after it was applied, even in a comment`,
66
+ allowed: ALLOWED,
67
+ })
68
+ }
69
+ return findings
70
+ }
@@ -0,0 +1,93 @@
1
+ // What the platform refuses of an application's migrations, found before the push instead of in a deploy's run log:
2
+ // the classifier Control runs on every snapshot, and on Cloudflare the backup's plan of the migrated schema, which every
3
+ // migration deploy takes first.
4
+
5
+ import { describeOpsDumpSchema, planOpsDump } from '@fabrika/auth-core'
6
+ import { withMigratedSqlite } from '@fabrika/db/codegen-sqlite'
7
+ import { FRAMEWORK_MIGRATION_BUNDLE } from '@fabrika/db/migrations'
8
+ import { SQLITE_FRAMEWORK_MIGRATIONS } from '@fabrika/db/migrations-sqlite'
9
+ import { applicationDatabaseSchema, classifyMigrations } from '@fabrika/platform-node/sql'
10
+ import type { Finding } from '../finding'
11
+ import { MIGRATIONS_DIR } from '../layout'
12
+
13
+ interface MigrationText {
14
+ readonly path: string
15
+ readonly name: string
16
+ readonly sql: string
17
+ }
18
+
19
+ /** The files of `db/migrations` itself, by name: the order the runner and Control read them in. */
20
+ const migrationTexts = (files: ReadonlyMap<string, string>): MigrationText[] =>
21
+ [...files].flatMap(([path, sql]) => {
22
+ const name = path.slice(MIGRATIONS_DIR.length)
23
+ return path.startsWith(MIGRATIONS_DIR) && name.endsWith('.sql') && !name.includes('/') ? [{ path, name, sql }] : []
24
+ }).sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
25
+
26
+ /**
27
+ * Every statement Control's classifier refuses, at its file and line. Control refuses a deploy whose new migration holds
28
+ * one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
29
+ * checked, applied or not: the checker does not know which an environment holds.
30
+ */
31
+ export const checkMigrationClassification = (files: ReadonlyMap<string, string>, appId: string): Finding[] => {
32
+ const texts = migrationTexts(files)
33
+ if (texts.length === 0) return []
34
+ const paths = new Map(texts.map((text) => [text.name, text.path]))
35
+ return classifyMigrations(texts.map(({ name, sql }) => ({ name, sql })), applicationDatabaseSchema(appId)).files.flatMap((file) =>
36
+ file.refused.map((refusal): Finding => ({
37
+ file: paths.get(refusal.file) ?? `${MIGRATIONS_DIR}${refusal.file}`,
38
+ line: refusal.line,
39
+ column: 1,
40
+ severity: 'refusal',
41
+ rule: 'migration-refused',
42
+ message: `${refusal.reason} is not allowed: Control refuses the deploy that brings this migration`,
43
+ allowed: 'the statements, functions and objects the migration classifier admits (application-runtime reference, "Migrations")',
44
+ }))
45
+ )
46
+ }
47
+
48
+ /**
49
+ * On Cloudflare, the backup's refusal of the migrated schema (`planOpsDump`), at the newest migration that names the
50
+ * table. Every migration deploy backs the environment up first, so a schema the backup refuses blocks every migration
51
+ * after the one that made it. A migration set that does not apply is codegen's to report, so it finds nothing here.
52
+ */
53
+ export const checkBackupPlan = async (files: ReadonlyMap<string, string>): Promise<Finding[]> => {
54
+ const texts = migrationTexts(files)
55
+ if (texts.length === 0) return []
56
+ let refused: { readonly table: string | null } | null
57
+ try {
58
+ refused = await withMigratedSqlite([
59
+ { bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: SQLITE_FRAMEWORK_MIGRATIONS },
60
+ { bundle: 'app', migrations: texts.map(({ name, sql }) => ({ name, sql })) },
61
+ ], (db) => {
62
+ const plan = planOpsDump(describeOpsDumpSchema((query, ...bindings) => db.query<Record<string, unknown>, string[]>(query).all(...bindings)))
63
+ return 'refused' in plan ? plan : null
64
+ })
65
+ } catch {
66
+ return []
67
+ }
68
+ if (refused === null) return []
69
+ const at = refused.table === null ? undefined : newestNaming(texts, refused.table)
70
+ const last = texts[texts.length - 1]
71
+ return [{
72
+ file: at?.path ?? last?.path ?? MIGRATIONS_DIR,
73
+ line: at?.line ?? 1,
74
+ column: 1,
75
+ severity: 'refusal',
76
+ rule: 'backup-schema',
77
+ message: refused.table === null
78
+ ? 'the migrated schema cannot be backed up (a table name the data layer does not admit, or two tables of one name)'
79
+ : `table ${refused.table} cannot be backed up, and every migration deploy takes a backup first`,
80
+ allowed:
81
+ "a foreign key inside its table's cycle that is nullable, outside the primary key, referenced by no other key and named by no CHECK (ADR-0070 section 2); or no such key",
82
+ }]
83
+ }
84
+
85
+ /** The newest migration that names `table`, and the first line there that does. */
86
+ const newestNaming = (texts: readonly MigrationText[], table: string): { path: string; line: number } | undefined => {
87
+ const word = new RegExp(`(^|[^A-Za-z0-9_$])["\`[]?${table.replace(/[$]/g, '\\$&')}["\`\\]]?($|[^A-Za-z0-9_$])`, 'i')
88
+ for (const text of [...texts].reverse()) {
89
+ const index = text.sql.split('\n').findIndex((line) => word.test(line))
90
+ if (index >= 0) return { path: text.path, line: index + 1 }
91
+ }
92
+ return undefined
93
+ }
@@ -482,9 +482,9 @@ const checkPrototypeWrite = (node: AstNode, context: SourceContext): void => {
482
482
 
483
483
  const KEY_PREFIX = 'px_'
484
484
 
485
- const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[], context: SourceContext): void => {
485
+ const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[], report: Report): void => {
486
486
  if (texts.some((text) => text?.includes(KEY_PREFIX))) {
487
- context.report(
487
+ report(
488
488
  node,
489
489
  'key-literal',
490
490
  `'${KEY_PREFIX}' in a literal: a key or a session cookie name in source`,
@@ -493,6 +493,15 @@ const checkStringContent = (node: AstNode, texts: readonly (string | undefined)[
493
493
  }
494
494
  }
495
495
 
496
+ /** `key-literal` over a string or a template's text: also the one rule of this module a developer's tool is held to. */
497
+ export const checkKeyLiteralNode = (node: AstNode, report: Report): void => {
498
+ if (node.type === 'Literal') checkStringContent(node, [staticString(node)], report)
499
+ else if (node.type === 'TemplateElement') {
500
+ const { raw, cooked } = templateText(node)
501
+ checkStringContent(node, [raw, cooked], report)
502
+ }
503
+ }
504
+
496
505
  const isTypeOnlyImport = (specifier: AstNode, parent: AstNode | undefined): boolean =>
497
506
  stringField(specifier, 'importKind') === 'type' || (parent !== undefined && stringField(parent, 'importKind') === 'type')
498
507
 
@@ -536,11 +545,8 @@ export const checkRuntimeNode = (node: AstNode, ancestors: readonly AstNode[], c
536
545
  return
537
546
  }
538
547
  case 'Literal':
539
- return checkStringContent(node, [staticString(node)], context)
540
- case 'TemplateElement': {
541
- const { raw, cooked } = templateText(node)
542
- return checkStringContent(node, [raw, cooked], context)
543
- }
548
+ case 'TemplateElement':
549
+ return checkKeyLiteralNode(node, context.report)
544
550
  case 'JSXAttribute': {
545
551
  const name = child(node, 'name')
546
552
  if (name?.type === 'JSXIdentifier' && stringField(name, 'name') === 'dangerouslySetInnerHTML') {
@@ -1,12 +1,13 @@
1
1
  import { isBuiltin } from 'node:module'
2
2
  import { type AstNode, child, identifierName, staticKey } from '../ast'
3
- import { type Report, STRUCTURE_HINT_RULE_IDS } from '../finding'
3
+ import { type Finding, type Report, STRUCTURE_HINT_RULE_IDS } from '../finding'
4
4
  import {
5
5
  CONTRACT_FILE,
6
6
  DATABASE_DIR,
7
7
  isRelativeSpecifier,
8
8
  isSourceFile,
9
9
  isTestFile,
10
+ isToolModule,
10
11
  resolveRelative,
11
12
  SCHEMAS_DIR,
12
13
  SCHEMAS_FILE,
@@ -221,6 +222,21 @@ const checkSliceReference = (place: StructurePlace, reference: ModuleReference,
221
222
  )
222
223
  }
223
224
 
225
+ /**
226
+ * A `package.json` under `tools/` makes a tool a package, which a workspace or a `file:` dependency lets the application
227
+ * load by its name, past `tool-import`, which judges the files an import resolves to.
228
+ */
229
+ export const checkToolPackages = (paths: readonly string[]): Finding[] =>
230
+ paths.filter((path) => isToolModule(path) && path.endsWith('/package.json')).map((path) => ({
231
+ file: path,
232
+ line: 1,
233
+ column: 1,
234
+ severity: 'refusal',
235
+ rule: 'tool-import',
236
+ message: `'${path}' makes a developer's tool a package, which the application could load by its name`,
237
+ allowed: "tools/ without a package.json: a tool's dependencies go in the root package.json",
238
+ }))
239
+
224
240
  /** The architecture's rules over one module's imports, re-exports and loads, as Bun resolves them for that module. */
225
241
  export const checkStructureReferences = (graph: StructureGraph, place: StructurePlace, report: Report): void => {
226
242
  for (const reference of graph.referencesOf(place.file)) {
@@ -234,6 +250,15 @@ export const checkStructureReferences = (graph: StructureGraph, place: Structure
234
250
  )
235
251
  }
236
252
  if (reference.typeOnly) continue
253
+ const tool = isToolModule(place.file) ? undefined : targets.files.find(isToolModule)
254
+ if (tool !== undefined) {
255
+ report(
256
+ reference.node,
257
+ 'tool-import',
258
+ `'${reference.specifier}' loads ${tool}, a developer's tool, which nothing outside tools/ loads`,
259
+ 'what the application and a tool share under src/ (pure code in src/shared/), imported by the tool',
260
+ )
261
+ }
237
262
  if (place.file.startsWith(SPA_DIR) && !place.exempt) checkSpaReference(graph, reference, targets, report)
238
263
  if (isSharedModule(place.file) && !place.exempt) checkSharedReference(reference, targets, report)
239
264
  if (isLayerModule(place.file)) checkLayerReference(graph, place, reference, targets, report)
package/src/trust.ts CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import type { Finding } from './finding'
6
6
  import { parseJsonc } from './jsonc'
7
- import { isIgnoredSegment, isRelativeSpecifier, isSourceFile, joinRelative } from './layout'
7
+ import { isIgnoredSegment, isRelativeSpecifier, isSourceFile, isToolModule, joinRelative } from './layout'
8
8
  import { isKey, parseToml } from './toml'
9
9
 
10
10
  /** Packages whose exports the reader trusts by name, and the packages they rely on. */
@@ -141,11 +141,15 @@ function checkTsconfig(path: string, text: string, files: ReadonlyMap<string, st
141
141
  }
142
142
  }
143
143
 
144
- /** A test preload must be a checked application file: a skipped or generated one runs unchecked during the build. */
144
+ /**
145
+ * A test preload must be a checked application file: a skipped or generated one runs unchecked during the build, and a
146
+ * developer's tool is not checked as application code.
147
+ */
145
148
  const isCheckedTestPreload = (target: string): boolean => {
146
149
  if (!target.startsWith('./')) return false
147
150
  const segments = target.slice(2).split('/')
148
- return segments[0] !== 'fabrika' && segments.every((segment) => segment !== '' && segment !== '..' && !isIgnoredSegment(segment))
151
+ return segments[0] !== 'fabrika' && !isToolModule(target.slice(2))
152
+ && segments.every((segment) => segment !== '' && segment !== '..' && !isIgnoredSegment(segment))
149
153
  && isSourceFile(target)
150
154
  }
151
155
 
@@ -180,7 +184,7 @@ function checkBunfig(text: string, report: (needle: string, message: string, all
180
184
  report(
181
185
  at(entry.line),
182
186
  'a test preload outside the checked application files runs unchecked in the platform build',
183
- "'./<path>' of a source file the checker reads, outside fabrika/, dist/, node_modules/ and dot directories",
187
+ "'./<path>' of a source file the checker reads, outside fabrika/, tools/, dist/, node_modules/ and dot directories",
184
188
  )
185
189
  }
186
190
  }
@@ -1,5 +1,6 @@
1
1
  import { type Finding } from './finding';
2
2
  import type { PackedSet } from './packed';
3
+ import { type MigrationBase } from './rules/migration-history';
3
4
  export interface CheckInput {
4
5
  /** The application's root directory. */
5
6
  readonly root: string;
@@ -7,6 +8,8 @@ export interface CheckInput {
7
8
  readonly files?: ReadonlyMap<string, string>;
8
9
  /** A local pack whose tarballs `package-replacement` accepts (`fabrika-check --packed`); a deploy build gives none. */
9
10
  readonly packed?: PackedSet;
11
+ /** The migrations of a shared branch the tree must still hold unchanged (`fabrika-check`, from git); a deploy build gives none. */
12
+ readonly migrationBase?: MigrationBase;
10
13
  }
11
14
  export interface ApplicationTree {
12
15
  readonly files: ReadonlyMap<string, string>;
@@ -1,6 +1,6 @@
1
1
  import type { AstNode, Position } from './ast';
2
2
  /** Rules whose finding fails the check: the framework's forms and platform integrity. */
3
- export declare const REFUSAL_RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "file-column-migration", "crontab", "package-replacement", "skipped-test", "test-without-assertion", "generated-test-hash", "mock-module", "endpoint-fixture", "spa-server-import", "layer-import", "generated-test-import", "shared-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name"];
3
+ export declare const REFUSAL_RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "migration-refused", "backup-schema", "migration-edited", "file-column-migration", "crontab", "package-replacement", "skipped-test", "test-without-assertion", "generated-test-hash", "mock-module", "endpoint-fixture", "spa-server-import", "layer-import", "generated-test-import", "shared-import", "tool-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name"];
4
4
  /** Rules that report a step out of the application architecture. */
5
5
  export declare const STRUCTURE_HINT_RULE_IDS: readonly ["logic-data-access", "cross-slice-queries", "handler-location", "data-access-location"];
6
6
  /**
@@ -9,7 +9,7 @@ export declare const STRUCTURE_HINT_RULE_IDS: readonly ["logic-data-access", "cr
9
9
  * Cloudflare mutation that waits for an outside call inside the object's transaction.
10
10
  */
11
11
  export declare const HINT_RULE_IDS: readonly ["logic-data-access", "cross-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
12
- export declare const RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "file-column-migration", "crontab", "package-replacement", "skipped-test", "test-without-assertion", "generated-test-hash", "mock-module", "endpoint-fixture", "spa-server-import", "layer-import", "generated-test-import", "shared-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name", "logic-data-access", "cross-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
12
+ export declare const RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "migration-refused", "backup-schema", "migration-edited", "file-column-migration", "crontab", "package-replacement", "skipped-test", "test-without-assertion", "generated-test-hash", "mock-module", "endpoint-fixture", "spa-server-import", "layer-import", "generated-test-import", "shared-import", "tool-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name", "logic-data-access", "cross-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
13
13
  export type RefusalRuleId = (typeof REFUSAL_RULE_IDS)[number];
14
14
  export type HintRuleId = (typeof HINT_RULE_IDS)[number];
15
15
  export type RuleId = (typeof RULE_IDS)[number];
@@ -2,6 +2,8 @@ export { type ApplicationTree, checkApplication, type CheckInput, readApplicatio
2
2
  export { type ApplicationDialect, applicationDialect } from './dialect';
3
3
  export { type Finding, formatFinding, RULE_IDS, type RuleId } from './finding';
4
4
  export { CONFIG_FILE, CONTRACT_FILE, GENERATED_ENTRY_FILE, MIGRATIONS_DIR, TABLES_FILE, ZEROPS_FILES } from './layout';
5
+ export { readMigrationBase } from './migration-base';
5
6
  export { type PackedSet, type PackedTarball, readPackedSet } from './packed';
7
+ export type { MigrationBase } from './rules/migration-history';
6
8
  export { GENERATED_TEST_HEADER, generatedTestHeader } from './rules/tests';
7
9
  export { ENDPOINT_ACCESS_TEST, ENDPOINT_FIXTURES_FILE, type GeneratedTest, generatedTests, missingEndpointFixtures, POLICY_TESTS_DIR, policyTestPath, scaffoldInputs, } from './scaffold';
@@ -36,6 +36,11 @@ export declare const SLICE_QUERIES_FILE = "queries.ts";
36
36
  export declare const SPA_DIR = "web/";
37
37
  /** The server half of an application: its modules run in the application's process. */
38
38
  export declare const SERVER_DIR = "src/";
39
+ /**
40
+ * A developer's tools, such as a command line over the contract: code that runs on a developer's machine and never in
41
+ * the application, so the rules for code that runs there do not apply, and no module outside it may load one.
42
+ */
43
+ export declare const TOOLS_DIR = "tools/";
39
44
  /** Build output, installed packages and tool state are not application source and are never read. */
40
45
  export declare const isIgnoredSegment: (segment: string) => boolean;
41
46
  /** Whether the checker skips `path` (relative to the root): under a skipped segment, or the staged SPA files. */
@@ -44,6 +49,8 @@ export declare const isSourceFile: (path: string) => boolean;
44
49
  export declare const isTestFile: (path: string) => boolean;
45
50
  /** A module that runs in the application's server process: under `src/`, not a test. */
46
51
  export declare const isServerModule: (path: string) => boolean;
52
+ /** A module under `tools/`, tests included. */
53
+ export declare const isToolModule: (path: string) => boolean;
47
54
  export declare const isJsonFile: (path: string) => boolean;
48
55
  /** Whether the checker reads this file at all. */
49
56
  export declare const isCheckedFile: (path: string) => boolean;
@@ -0,0 +1,9 @@
1
+ import type { MigrationBase } from './rules/migration-history';
2
+ /**
3
+ * The migrations at the merge base of HEAD and `ref` (the remote's default branch when omitted), compared against
4
+ * the merge base so that migrations the default branch added since the branch forked are not read as deleted.
5
+ * `null` when `root` is in no git work tree; `{ skipped }` when it is but the base cannot be read.
6
+ */
7
+ export declare const readMigrationBase: (root: string, ref?: string) => Promise<MigrationBase | {
8
+ readonly skipped: string;
9
+ } | null>;
@@ -0,0 +1,12 @@
1
+ import type { Finding } from '../finding';
2
+ /** The migrations of `db/migrations` at the commit the tree is compared with, by path relative to the root. */
3
+ export interface MigrationBase {
4
+ /** How the commit is named to the author, such as `origin/main`. */
5
+ readonly ref: string;
6
+ readonly files: ReadonlyMap<string, string>;
7
+ }
8
+ /**
9
+ * Each migration of `base` that the tree changed (at its first changed line) or no longer holds. A file renamed is one
10
+ * removed and one new, and the new one would run again where the old one ran, so the removal is what is reported.
11
+ */
12
+ export declare const checkMigrationHistory: (files: ReadonlyMap<string, string>, base: MigrationBase) => Finding[];
@@ -0,0 +1,13 @@
1
+ import type { Finding } from '../finding';
2
+ /**
3
+ * Every statement Control's classifier refuses, at its file and line. Control refuses a deploy whose new migration holds
4
+ * one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
5
+ * checked, applied or not: the checker does not know which an environment holds.
6
+ */
7
+ export declare const checkMigrationClassification: (files: ReadonlyMap<string, string>, appId: string) => Finding[];
8
+ /**
9
+ * On Cloudflare, the backup's refusal of the migrated schema (`planOpsDump`), at the newest migration that names the
10
+ * table. Every migration deploy backs the environment up first, so a schema the backup refuses blocks every migration
11
+ * after the one that made it. A migration set that does not apply is codegen's to report, so it finds nothing here.
12
+ */
13
+ export declare const checkBackupPlan: (files: ReadonlyMap<string, string>) => Promise<Finding[]>;
@@ -28,5 +28,7 @@ export declare const crossAppFetchMessage: (target: string) => {
28
28
  };
29
29
  /** Whether an expression reaches a prototype: through `.prototype`, `.__proto__` or `Object.getPrototypeOf(…)`. */
30
30
  export declare const touchesPrototype: (node: AstNode | undefined) => boolean;
31
+ /** `key-literal` over a string or a template's text: also the one rule of this module a developer's tool is held to. */
32
+ export declare const checkKeyLiteralNode: (node: AstNode, report: Report) => void;
31
33
  /** The rules that read one node at a time, for every source file. */
32
34
  export declare const checkRuntimeNode: (node: AstNode, ancestors: readonly AstNode[], context: SourceContext) => void;
@@ -1,5 +1,5 @@
1
1
  import { type AstNode } from '../ast';
2
- import { type Report } from '../finding';
2
+ import { type Finding, type Report } from '../finding';
3
3
  import type { ModuleReference } from '../references';
4
4
  import { type ImportMappings } from '../resolution';
5
5
  /** The rules of the application architecture (docs/reference/application-architecture.md): four refusals and the hints. */
@@ -20,6 +20,11 @@ export interface StructureGraph {
20
20
  readonly mappings: ImportMappings;
21
21
  readonly referencesOf: (path: string) => readonly ModuleReference[];
22
22
  }
23
+ /**
24
+ * A `package.json` under `tools/` makes a tool a package, which a workspace or a `file:` dependency lets the application
25
+ * load by its name, past `tool-import`, which judges the files an import resolves to.
26
+ */
27
+ export declare const checkToolPackages: (paths: readonly string[]) => Finding[];
23
28
  /** The architecture's rules over one module's imports, re-exports and loads, as Bun resolves them for that module. */
24
29
  export declare const checkStructureReferences: (graph: StructureGraph, place: StructurePlace, report: Report) => void;
25
30
  /** A `<x>.<builder>(…).handle(…)` call: the builder's name, its call (whose arguments hold the options) and `.handle`. */