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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/package.json +7 -7
  2. package/src/ast.ts +69 -6
  3. package/src/check.ts +135 -32
  4. package/src/cli.ts +23 -4
  5. package/src/contract.ts +42 -6
  6. package/src/dialect.ts +29 -0
  7. package/src/finding.ts +14 -6
  8. package/src/index.ts +4 -12
  9. package/src/inputs.ts +4 -2
  10. package/src/layout.ts +21 -10
  11. package/src/limits.ts +13 -3
  12. package/src/migration-base.ts +85 -0
  13. package/src/reader/schema.ts +42 -512
  14. package/src/reader/surface.ts +43 -5
  15. package/src/reader/value.ts +18 -6
  16. package/src/resolution.ts +2 -2
  17. package/src/rules/cloudflare.ts +59 -0
  18. package/src/rules/compile.ts +32 -0
  19. package/src/rules/framework.ts +2 -2
  20. package/src/rules/literal.ts +3 -1
  21. package/src/rules/migration-history.ts +70 -0
  22. package/src/rules/migrations.ts +248 -9
  23. package/src/rules/modules.ts +9 -3
  24. package/src/rules/platform-migrations.ts +100 -0
  25. package/src/rules/runtime.ts +45 -14
  26. package/src/rules/structure.ts +32 -15
  27. package/src/rules/tests.ts +9 -60
  28. package/src/trust.ts +8 -4
  29. package/types/src/ast.d.ts +6 -0
  30. package/types/src/check.d.ts +3 -0
  31. package/types/src/contract.d.ts +1 -0
  32. package/types/src/dialect.d.ts +8 -0
  33. package/types/src/finding.d.ts +6 -5
  34. package/types/src/index.d.ts +4 -3
  35. package/types/src/layout.d.ts +18 -9
  36. package/types/src/limits.d.ts +12 -2
  37. package/types/src/migration-base.d.ts +9 -0
  38. package/types/src/reader/schema.d.ts +5 -2
  39. package/types/src/reader/value.d.ts +2 -2
  40. package/types/src/rules/cloudflare.d.ts +9 -0
  41. package/types/src/rules/compile.d.ts +7 -0
  42. package/types/src/rules/framework.d.ts +1 -1
  43. package/types/src/rules/migration-history.d.ts +12 -0
  44. package/types/src/rules/migrations.d.ts +28 -0
  45. package/types/src/rules/platform-migrations.d.ts +15 -0
  46. package/types/src/rules/runtime.d.ts +7 -2
  47. package/types/src/rules/structure.d.ts +8 -3
  48. package/types/src/rules/tests.d.ts +6 -14
  49. package/src/endpoint-fixtures.ts +0 -221
  50. package/src/rules/isolation.ts +0 -79
  51. package/src/scaffold-sample.ts +0 -111
  52. package/src/scaffold.ts +0 -650
  53. package/types/src/endpoint-fixtures.d.ts +0 -36
  54. package/types/src/rules/isolation.d.ts +0 -18
  55. package/types/src/scaffold-sample.d.ts +0 -8
  56. package/types/src/scaffold.d.ts +0 -28
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/check",
3
- "version": "0.9.0-dev.2",
3
+ "version": "0.9.0-dev.20",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,16 +42,16 @@
42
42
  }
43
43
  },
44
44
  "scripts": {
45
- "typecheck": "tsc --noEmit",
45
+ "typecheck": "tsrs --build tsconfig.test.json",
46
46
  "test": "bun test"
47
47
  },
48
48
  "dependencies": {
49
49
  "@babel/parser": "8.0.7",
50
- "@fabrika/app": "0.9.0-dev.2",
51
- "@fabrika/auth-core": "0.9.0-dev.2",
52
- "@fabrika/db": "0.9.0-dev.2",
53
- "@fabrika/operations-contract": "0.9.0-dev.2",
54
- "@fabrika/platform-node": "0.9.0-dev.2",
50
+ "@fabrika/app": "0.9.0-dev.20",
51
+ "@fabrika/auth-core": "0.9.0-dev.20",
52
+ "@fabrika/db": "0.9.0-dev.20",
53
+ "@fabrika/operations-contract": "0.9.0-dev.20",
54
+ "@fabrika/platform-node": "0.9.0-dev.20",
55
55
  "zod": "^3.25.76"
56
56
  }
57
57
  }
package/src/ast.ts CHANGED
@@ -167,17 +167,61 @@ export const isValueReference = (node: AstNode, parent: AstNode | undefined): bo
167
167
  }
168
168
  }
169
169
 
170
+ /**
171
+ * A node's line and column (from 1), as the parser counts them, for a tree `parseModule` returns: its `loc` is the
172
+ * start of its line (`lineLocations`). A tree parsed any other way has no such `loc` and reads as 1:1.
173
+ */
170
174
  export const positionOf = (node: AstNode): Position => {
171
175
  const loc = node['loc']
172
- if (isRecord(loc)) {
173
- const start = loc['start']
174
- if (isRecord(start) && typeof start['line'] === 'number' && typeof start['column'] === 'number') {
175
- return { line: start['line'], column: start['column'] + 1 }
176
- }
176
+ const start = node['start']
177
+ if (isRecord(loc) && typeof loc['line'] === 'number' && typeof loc['offset'] === 'number' && typeof start === 'number') {
178
+ return { line: loc['line'], column: start - loc['offset'] + 1 }
177
179
  }
178
180
  return { line: 1, column: 1 }
179
181
  }
180
182
 
183
+ /** Where a line starts: a line break is the parser's (`\r\n`, `\n`, `\r`, U+2028, U+2029). */
184
+ interface LineStart {
185
+ readonly line: number
186
+ readonly offset: number
187
+ }
188
+
189
+ const LINE_BREAK = /\r\n|[\n\r\u2028\u2029]/g
190
+
191
+ const isMutableNode = (value: unknown): value is Record<string, unknown> =>
192
+ typeof value === 'object' && value !== null && !Array.isArray(value) && 'type' in value && typeof value.type === 'string'
193
+
194
+ /**
195
+ * Replaces the parser's location of every node below `roots` (an object and two positions per node) with the start of
196
+ * the node's line, one object per line, which `positionOf` reads with the node's offset. The syntax trees of a
197
+ * contract are most of the memory its reader holds, and these locations were the largest part of them.
198
+ */
199
+ function lineLocations(text: string, roots: readonly unknown[]): void {
200
+ const lines: LineStart[] = [{ line: 1, offset: 0 }]
201
+ for (const match of text.matchAll(LINE_BREAK)) lines.push({ line: lines.length + 1, offset: match.index + match[0].length })
202
+ const lineAt = (offset: number): LineStart | undefined => {
203
+ let low = 0
204
+ let high = lines.length - 1
205
+ while (low < high) {
206
+ const middle = (low + high + 1) >> 1
207
+ if ((lines[middle]?.offset ?? 0) <= offset) low = middle
208
+ else high = middle - 1
209
+ }
210
+ return lines[low]
211
+ }
212
+ const pending: unknown[] = [...roots]
213
+ while (pending.length > 0) {
214
+ const value = pending.pop()
215
+ if (Array.isArray(value)) {
216
+ for (const item of value) pending.push(item)
217
+ } else if (isMutableNode(value)) {
218
+ const start = value['start']
219
+ value['loc'] = typeof start === 'number' ? lineAt(start) : undefined
220
+ for (const [key, child] of Object.entries(value)) if (!NON_CHILD_KEYS.has(key) && typeof child === 'object') pending.push(child)
221
+ }
222
+ }
223
+ }
224
+
181
225
  /** Visits every node below `root`, depth first, with the chain of its ancestors (nearest last); `'skip'` prunes a subtree. */
182
226
  export const walk = (root: AstNode, visit: (node: AstNode, ancestors: readonly AstNode[]) => 'skip' | undefined | void): void => {
183
227
  const ancestors: AstNode[] = []
@@ -243,11 +287,30 @@ export const nodeDepth = (root: AstNode): number => {
243
287
  return deepest
244
288
  }
245
289
 
290
+ /** The number of syntax nodes in the tree below `root`, `root` included, counted without recursion. */
291
+ export const nodeCount = (root: AstNode): number => {
292
+ let count = 0
293
+ const pending: AstNode[] = [root]
294
+ for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
295
+ count++
296
+ for (const [key, value] of Object.entries(node)) {
297
+ if (NON_CHILD_KEYS.has(key)) continue
298
+ if (isNode(value)) pending.push(value)
299
+ else if (Array.isArray(value)) {
300
+ for (const item of value) if (isNode(item)) pending.push(item)
301
+ }
302
+ }
303
+ }
304
+ return count
305
+ }
306
+
246
307
  export const parseModule = (file: string, text: string): ParseResult => {
247
308
  try {
248
- const ast = parse(text, { sourceType: 'module', sourceFilename: file, plugins: pluginsFor(file) })
309
+ // Nothing reads a comment from the node it is attached to; `ast.comments` lists them all.
310
+ const ast = parse(text, { sourceType: 'module', sourceFilename: file, plugins: pluginsFor(file), attachComment: false })
249
311
  const program: unknown = ast.program
250
312
  if (!isNode(program)) return { ok: false, message: 'the parser returned no program', position: { line: 1, column: 1 } }
313
+ lineLocations(text, [program, ast.comments])
251
314
  return { ok: true, module: { file, program, comments: readComments(ast.comments), bytes: utf8Bytes(text) } }
252
315
  } catch (error) {
253
316
  const message = error instanceof Error ? (error.message.split('\n')[0] ?? error.message) : 'unparseable source'
package/src/check.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { type AnyContract, compileContract, ContractError } from '@fabrika/app/contract'
2
- import type { ContractArtifact } from '@fabrika/auth-core'
3
- import { type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
2
+ import { type ContractArtifact, egressAdmits, type EgressEntry, parseEgressEntry, PUBLIC_EGRESS, publicEgressRefusal } from '@fabrika/auth-core'
3
+ import { accessTables, type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
4
4
  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,23 +26,46 @@ 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'
30
+ import { checkContractCompiles } from './rules/compile'
27
31
  import { checkContractRead } from './rules/contract'
28
32
  import { checkCrontab, contractJobs } from './rules/crontab'
29
33
  import { checkFrameworkWrite, trustedBindings } from './rules/framework'
30
34
  import { checkClientIdentity } from './rules/identity'
31
- 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
+ type AccessKey,
40
+ checkAccessViewKeys,
41
+ checkConflictIndexes,
42
+ checkCurrentTimestampDefaults,
43
+ checkFileColumnMigrations,
44
+ checkMigrationNames,
45
+ checkSqliteFrameworkNames,
46
+ checkSqliteViewTriggers,
47
+ type ConflictInsert,
48
+ type FileColumn,
49
+ } from './rules/migrations'
35
50
  import { checkModuleReferences } from './rules/modules'
36
51
  import { checkAmbientModule, checkPackageReplacement } from './rules/packages'
37
- import { checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
38
- import { checkStructureNode, checkStructureReferences, structurePlace } from './rules/structure'
39
- import { checkGeneratedTest, checkMockModule, checkTestNode, checkTestSuiteConfig } from './rules/tests'
52
+ import { checkBackupPlan, checkMigrationClassification } from './rules/platform-migrations'
53
+ import { checkKeyLiteralNode, checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
54
+ import { checkStructureNode, checkStructureReferences, checkToolPackages, structurePlace } from './rules/structure'
55
+ import { checkMockModule, checkTestNode, checkTestSuiteConfig } from './rules/tests'
40
56
  import { checkComments, checkTypeNode } from './rules/types'
41
57
  import { moduleSlice, sliceFinding } from './slice'
42
58
  import { BUNFIG_FILE, checkTrustedResolution } from './trust'
43
59
 
60
+ /** Every table that names an access view, with its key (ADR-0076). */
61
+ const accessKeys = (policies: TablePolicies): AccessKey[] =>
62
+ Object.entries(policies).flatMap(([table, policy]) => {
63
+ const views = Object.values(policy.access ?? {}).map((access) => access.view)
64
+ const scope = policy.scope
65
+ const key = scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app' ? scope.key : undefined
66
+ return views.length === 0 || key === undefined ? [] : [{ table, key, views: [...new Set(views)].sort() }]
67
+ })
68
+
44
69
  /** Every file column the table policies declare, with its kind. */
45
70
  const fileColumns = (policies: TablePolicies): FileColumn[] =>
46
71
  Object.entries(policies).flatMap(([table, policy]) => Object.entries(policy.files ?? {}).map(([column, kind]) => ({ table, column, kind })))
@@ -52,6 +77,8 @@ export interface CheckInput {
52
77
  readonly files?: ReadonlyMap<string, string>
53
78
  /** A local pack whose tarballs `package-replacement` accepts (`fabrika-check --packed`); a deploy build gives none. */
54
79
  readonly packed?: PackedSet
80
+ /** The migrations of a shared branch the tree must still hold unchanged (`fabrika-check`, from git); a deploy build gives none. */
81
+ readonly migrationBase?: MigrationBase
55
82
  }
56
83
 
57
84
  export interface ApplicationTree {
@@ -80,23 +107,41 @@ export const readApplicationTree = async (root: string): Promise<ApplicationTree
80
107
 
81
108
  /** The findings a module rule leaves until the contract is read: they depend on what it declares. */
82
109
  interface ContractDependent {
83
- /** Each `fetch` of an absolute URL, with its static prefix. */
84
- readonly fetches: { readonly target: string; readonly finding: Finding }[]
110
+ /** Each `fetch` of an absolute URL, with its static prefix and its labelled authority (`absoluteFetch`). */
111
+ readonly fetches: { readonly target: string; readonly labelled: string | undefined; readonly finding: Finding }[]
85
112
  /** Each `ctx.url` with a literal endpoint id. */
86
113
  readonly urls: { readonly endpoint: string; readonly finding: Finding }[]
87
114
  /** Each insert with literal `onConflict.columns`, checked against the migrations' unique indexes. */
88
115
  readonly inserts: ConflictInsert[]
89
116
  }
90
117
 
91
- const checkSourceModule = async (
118
+ /**
119
+ * A module under `tools/` runs on a developer's machine, never in the application: it is held to how its source is
120
+ * written (`type-assertion`, `any-type`, `capability-widening`, `suppression-comment`), `key-literal`, a `declare
121
+ * module` of a trusted package and the rules of its tests. Every other module rule guards code that runs in the
122
+ * application.
123
+ */
124
+ const checkToolModule = (module: ParsedModule, findings: Finding[]): void => {
125
+ const report = reporter(module.file, findings)
126
+ const isTest = isTestFile(module.file)
127
+ walk(module.program, (node, ancestors) => {
128
+ checkKeyLiteralNode(node, report)
129
+ checkTypeNode(node, report)
130
+ checkAmbientModule(node, report)
131
+ if (isTest) checkTestNode(node, ancestors, report)
132
+ checkMockModule(node, report)
133
+ })
134
+ checkComments(module.comments, report)
135
+ }
136
+
137
+ const checkSourceModule = (
92
138
  module: ParsedModule,
93
139
  references: readonly ModuleReference[],
94
- text: string,
95
140
  mappings: ImportMappings,
96
141
  files: ReadonlyMap<string, string>,
97
142
  findings: Finding[],
98
143
  dependent: ContractDependent,
99
- ): Promise<void> => {
144
+ ): void => {
100
145
  const exists = (path: string): boolean => files.has(path)
101
146
  const report = reporter(module.file, findings)
102
147
  const isGeneratedEntry = module.file === GENERATED_ENTRY_FILE
@@ -111,9 +156,9 @@ const checkSourceModule = async (
111
156
  isGeneratedEntry,
112
157
  rawSql: rawSqlBindings(module.program),
113
158
  isServerModule: isServerModule(module.file),
114
- absoluteFetch: (node: AstNode, target: string) => {
159
+ absoluteFetch: (node: AstNode, target: string, labelled: string | undefined) => {
115
160
  const { message, allowed } = crossAppFetchMessage(target)
116
- for (const finding of deferred(node, 'cross-app-fetch', message, allowed)) dependent.fetches.push({ target, finding })
161
+ for (const finding of deferred(node, 'cross-app-fetch', message, allowed)) dependent.fetches.push({ target, labelled, finding })
117
162
  },
118
163
  appUrl: (node: AstNode, endpoint: string) => {
119
164
  const message = `ctx.url names '${endpoint}', which is no procedure of the contract`
@@ -133,12 +178,11 @@ const checkSourceModule = async (
133
178
  checkTypeNode(node, report)
134
179
  checkAmbientModule(node, report)
135
180
  if (isTest) checkTestNode(node, ancestors, report)
136
- checkMockModule(node, module.file, files, report)
181
+ checkMockModule(node, report)
137
182
  checkStructureNode(place, node, report)
138
183
  })
139
184
  checkComments(module.comments, report)
140
185
  checkModuleReferences(module.file, references, mappings, exists, report, isGeneratedEntry, isTest)
141
- await checkGeneratedTest(text, module.comments, report)
142
186
  }
143
187
 
144
188
  /** `module` as its shell slice (itself when it holds no colocated handler), and the `.handle(…)` forms it refused. */
@@ -154,41 +198,84 @@ const URL_ENDPOINT_ALLOWED = "the id of a procedure of the contract: ctx.url('<m
154
198
  /** What the module rules that wait for the contract compare against: its procedure ids and every declared origin. */
155
199
  interface CompiledReach {
156
200
  readonly procedures: ReadonlySet<string>
157
- readonly origins: readonly string[]
201
+ readonly egress: readonly EgressEntry[]
202
+ /** Some cron job declares `egress: 'public'`. */
203
+ readonly publicEgress: boolean
158
204
  }
159
205
 
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
206
+ /** The contract's artifact, or `null` when it does not compile, which its own rule reports. */
207
+ const compiledArtifact = (contract: AnyContract, tables: Tables<unknown, unknown> | null): ContractArtifact | null => {
163
208
  try {
164
- artifact = compileContract(contract, tables ?? {})
209
+ return compileContract(contract, tables ?? {})
165
210
  } catch (error) {
166
211
  if (error instanceof ContractError) return null
167
212
  throw error
168
213
  }
214
+ }
215
+
216
+ /** The contract's procedures and origins. */
217
+ const compiledReach = (artifact: ContractArtifact): CompiledReach => {
169
218
  const procedures = artifact.endpoints.filter((row) =>
170
219
  (row.kind === 'query' || row.kind === 'mutation' || row.kind === 'public') && row.source.kind === 'mount'
171
220
  )
172
221
  return {
173
222
  procedures: new Set(procedures.map((row) => row.id)),
174
- origins: Object.values(artifact.declared ?? {}).flatMap((reach) => reach.egress ?? []),
223
+ egress: Object.values(artifact.declared ?? {}).flatMap((reach) =>
224
+ (reach.egress === undefined || reach.egress === PUBLIC_EGRESS ? [] : reach.egress).flatMap((value) => {
225
+ const parsed = parseEgressEntry(value)
226
+ return parsed.ok ? [parsed.entry] : []
227
+ })
228
+ ),
229
+ publicEgress: Object.values(artifact.declared ?? {}).some((reach) => reach.egress === PUBLIC_EGRESS),
175
230
  }
176
231
  }
177
232
 
178
233
  /**
179
234
  * A `fetch` of an absolute URL stands when no site declares its origin (a static prefix that ends inside the host is
180
- * not accepted), and every one stands when the contract does not compile. A `ctx.url` stands when the contract
181
- * compiles and names no such procedure. The runtime guard on `fetch` still checks the site that runs.
235
+ * not accepted, nor an interpolated label a pattern does not cover) and, where a cron job declares `egress: 'public'`,
236
+ * when public egress would refuse it: another scheme, or a host its URL alone refuses (an IP address, a local or
237
+ * internal name, a port). A prefix that ends inside the host is then the runtime's to judge. Every one stands when the
238
+ * contract does not compile. A `ctx.url` stands when the contract compiles and names no such procedure. The runtime
239
+ * guard on `fetch` still checks the site that runs.
182
240
  */
183
241
  const contractDependentFindings = (dependent: ContractDependent, reach: CompiledReach | null): Finding[] => [
184
- ...dependent.fetches.filter(({ target }) => reach === null || !reach.origins.some((origin) => isWithinOrigin(target, origin))).map(({ finding }) =>
185
- finding
186
- ),
242
+ ...dependent.fetches.filter((fetch) =>
243
+ reach === null || (!isDeclaredFetch(fetch, reach.egress) && !(reach.publicEgress && isPublicTarget(fetch.target)))
244
+ ).map(({ finding }) => finding),
187
245
  ...(reach === null ? [] : dependent.urls.filter(({ endpoint }) => !reach.procedures.has(endpoint)).map(({ finding }) => finding)),
188
246
  ]
189
247
 
190
- const isWithinOrigin = (target: string, origin: string): boolean =>
191
- target.startsWith(`${origin}/`) || target.startsWith(`${origin}?`) || target.startsWith(`${origin}#`)
248
+ /** The static prefix names its whole authority, which an entry admits, or the labelled authority is a pattern's own. */
249
+ const isDeclaredFetch = (fetch: { readonly target: string; readonly labelled: string | undefined }, egress: readonly EgressEntry[]): boolean => {
250
+ const authority = /^https:\/\/[^/?#]+[/?#]/.exec(fetch.target)?.[0]
251
+ const url = authority === undefined ? null : urlOf(authority)
252
+ if (url !== null && egressAdmits(egress, url)) return true
253
+ // The interpolated label as a placeholder one, so the authority normalizes as the runtime's URL will; exact
254
+ // origins stay out, as no literal label is known.
255
+ const labelled = fetch.labelled === undefined ? null : urlOf(`https://${fetch.labelled.replace('*', 'label')}/`)
256
+ return labelled !== null && egressAdmits(egress.filter((entry) => entry.kind === 'pattern'), labelled)
257
+ }
258
+
259
+ const urlOf = (value: string): URL | null => {
260
+ try {
261
+ return new URL(value)
262
+ } catch {
263
+ return null
264
+ }
265
+ }
266
+
267
+ /** A static prefix public egress may reach: http(s), and a host that is not yet complete or that its URL admits. */
268
+ const isPublicTarget = (target: string): boolean => {
269
+ const scheme = /^(https?):\/\//i.exec(target)
270
+ if (scheme === null) return false
271
+ const rest = target.slice(scheme[0].length)
272
+ if (!/[/?#]/.test(rest)) return true
273
+ try {
274
+ return publicEgressRefusal(new URL(target)) === null
275
+ } catch {
276
+ return false
277
+ }
278
+ }
192
279
 
193
280
  /** Runs every rule over one application and returns the findings in file, line and column order. */
194
281
  export const checkApplication = async (input: CheckInput): Promise<Finding[]> => {
@@ -226,7 +313,8 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
226
313
  modules.set(path, parsed.module)
227
314
  const referencesOfModule = moduleReferences(parsed.module.program)
228
315
  references.set(path, referencesOfModule)
229
- await checkSourceModule(parsed.module, referencesOfModule, text, mappings, tree.files, findings, dependent)
316
+ if (isToolModule(path)) checkToolModule(parsed.module, findings)
317
+ else checkSourceModule(parsed.module, referencesOfModule, mappings, tree.files, findings, dependent)
230
318
  }
231
319
  const structure = { files: tree.files, mappings, referencesOf: (path: string) => references.get(path) ?? [] }
232
320
  for (const path of modules.keys()) {
@@ -250,15 +338,30 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
250
338
  const contractRead = contract !== undefined && literal.length === 0 ? checkContractRead(graph) : []
251
339
  findings.push(...contractRead)
252
340
  for (const module of contract === undefined ? [] : contractModules(graph, contract)) findings.push(...checkClientIdentity(module, graph))
253
- findings.push(...(await checkGeneratedTests(tree.files, literal.length === 0 && trust.length === 0 && contractRead.length === 0)))
341
+ findings.push(...checkContractCompiles(tree.files, literal.length === 0 && trust.length === 0 && contractRead.length === 0))
254
342
  findings.push(...checkMigrationNames(checkedPaths))
343
+ if (input.migrationBase !== undefined) findings.push(...checkMigrationHistory(tree.files, input.migrationBase))
344
+ findings.push(...checkToolPackages(checkedPaths))
255
345
  const read = contract !== undefined && literal.length === 0 && contractRead.length === 0 ? readContractModule(graph) : undefined
256
346
  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))
347
+ const artifact = read?.ok === true ? compiledArtifact(read.contract, declaredTables) : null
348
+ findings.push(...contractDependentFindings(dependent, artifact === null ? null : compiledReach(artifact)))
349
+ const dialect = applicationDialect(tree.files)
350
+ if (artifact !== null) {
351
+ findings.push(...checkMigrationClassification(tree.files, artifact.app, declaredTables === null ? [] : accessTables(declaredTables), dialect))
352
+ }
353
+ if (dialect === 'sqlite') {
354
+ if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
355
+ findings.push(...checkCurrentTimestampDefaults(tree.files))
356
+ findings.push(...checkSqliteFrameworkNames(tree.files))
357
+ findings.push(...checkSqliteViewTriggers(tree.files))
358
+ findings.push(...(await checkBackupPlan(tree.files)))
359
+ }
258
360
  if (declaredTables !== null) {
259
361
  const policies = tablePolicies(declaredTables)
260
362
  findings.push(...checkFileColumnMigrations(tree.files, fileColumns(policies)))
261
363
  findings.push(...checkConflictIndexes(tree.files, new Set(Object.keys(policies)), dependent.inserts))
364
+ findings.push(...checkAccessViewKeys(tree.files, accessKeys(policies)))
262
365
  }
263
366
  const bunfig = tree.files.get(BUNFIG_FILE)
264
367
  if (bunfig !== undefined) findings.push(...checkTestSuiteConfig(bunfig))
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/contract.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  import { type AnyContract, compileContract } from '@fabrika/app/contract'
6
6
  import type { ContractArtifact, TablePolicyArtifact } from '@fabrika/auth-core'
7
7
  import { type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
8
- import { importedSpecifiers, nodeDepth, type ParsedModule, utf8Bytes } from './ast'
8
+ import { child, children, importedSpecifiers, nodeCount, nodeDepth, type ParsedModule, utf8Bytes } from './ast'
9
9
  import { type Finding, formatFinding } from './finding'
10
10
  import { ModuleGraph } from './graph'
11
11
  import { CONTRACT_EXPORT, CONTRACT_FILE, isRelativeSpecifier, isSourceFile, resolveRelative, TABLES_FILE } from './layout'
@@ -19,6 +19,7 @@ import { parseShellModule } from './slice'
19
19
  import { checkTrustedResolution } from './trust'
20
20
 
21
21
  export { ContractError } from '@fabrika/app/contract'
22
+ export { accessTables } from '@fabrika/db/tables'
22
23
  export { type Finding, formatFinding } from './finding'
23
24
  export { contractReaderInputs } from './inputs'
24
25
  export { CONTRACT_FILE, MIGRATIONS_DIR, TABLES_FILE } from './layout'
@@ -160,21 +161,34 @@ export function contractModules(graph: ModuleGraph, entry: ParsedModule): Parsed
160
161
  return [...reached.values()]
161
162
  }
162
163
 
163
- /** The source and syntax-depth limits of `CONTRACT_LIMITS` over the modules of one entry (the contract or the tables). */
164
+ /** The source and syntax limits of `CONTRACT_LIMITS` over the modules of one entry (the contract or the tables). */
164
165
  function sourceBudget(modules: readonly ParsedModule[], entry = CONTRACT_FILE): Finding[] {
165
166
  const findings: Finding[] = []
166
167
  const bytes = modules.reduce((total, module) => total + module.bytes, 0)
167
168
  if (bytes > CONTRACT_LIMITS.sourceBytes) {
168
169
  findings.push(overBudget(entry, `${entry} and its modules are ${bytes} bytes, over ${CONTRACT_LIMITS.sourceBytes}`))
169
170
  }
171
+ let nodes = 0
170
172
  for (const module of modules) {
173
+ if (module.bytes > CONTRACT_LIMITS.moduleBytes) {
174
+ findings.push(overBudget(module.file, moduleTooLarge(module.bytes)))
175
+ }
171
176
  if (nodeDepth(module.program) > CONTRACT_LIMITS.astDepth) {
172
177
  findings.push(overBudget(module.file, `the syntax nests deeper than ${CONTRACT_LIMITS.astDepth} levels`))
173
178
  }
179
+ nodes += heldNodes(module)
180
+ }
181
+ if (nodes > CONTRACT_LIMITS.astNodes) {
182
+ findings.push(overBudget(entry, `${entry} and its modules hold ${nodes} syntax nodes, over the budget of ${CONTRACT_LIMITS.astNodes}`))
174
183
  }
175
184
  return findings
176
185
  }
177
186
 
187
+ const moduleTooLarge = (bytes: number): string => `the module is ${bytes} bytes, over ${CONTRACT_LIMITS.moduleBytes} for one module`
188
+
189
+ /** The syntax nodes the reader holds of a module: all but its top-level type declarations. */
190
+ const heldNodes = (module: ParsedModule): number => nodeCount(withoutTypeDeclarations(module).program)
191
+
178
192
  function overBudget(file: string, message: string): Finding {
179
193
  return {
180
194
  file,
@@ -192,8 +206,8 @@ type ParsedGraph = { readonly ok: true; readonly graph: ModuleGraph } | { readon
192
206
  /**
193
207
  * Parses `entry` (`fabrika.contract.ts` or `src/db/tables.ts`) and the modules its imports reach among `files`, and
194
208
  * nothing else; each module as its shell slice, so an import only a handler uses is never followed. Every candidate of an import is parsed, so that `rules/literal.ts` sees an ambiguous or directory
195
- * import; the size limit holds before a module is parsed and the depth limit right after, before any recursive rule
196
- * walks it.
209
+ * import; the byte limits hold before a module is parsed, and the depth and node limits right after, before any
210
+ * recursive rule walks it.
197
211
  */
198
212
  function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): ParsedGraph {
199
213
  const modules = new Map<string, ParsedModule>()
@@ -202,13 +216,18 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
202
216
  return { ok: false, findings: [missingFile(entry)] }
203
217
  }
204
218
  let bytes = 0
219
+ let nodes = 0
205
220
  const queue = [entry]
206
221
  for (let path = queue.shift(); path !== undefined; path = queue.shift()) {
207
222
  const text = files.get(path)
208
223
  if (modules.has(path) || text === undefined || !isSourceFile(path)) {
209
224
  continue
210
225
  }
211
- bytes += utf8Bytes(text)
226
+ const moduleBytes = utf8Bytes(text)
227
+ if (moduleBytes > CONTRACT_LIMITS.moduleBytes) {
228
+ return { ok: false, findings: [overBudget(path, moduleTooLarge(moduleBytes))] }
229
+ }
230
+ bytes += moduleBytes
212
231
  if (bytes > CONTRACT_LIMITS.sourceBytes) {
213
232
  return { ok: false, findings: [overBudget(path, `${entry} and its modules are over ${CONTRACT_LIMITS.sourceBytes} bytes`)] }
214
233
  }
@@ -228,7 +247,12 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
228
247
  if (nodeDepth(parsed.module.program) > CONTRACT_LIMITS.astDepth) {
229
248
  return { ok: false, findings: [overBudget(path, `the syntax nests deeper than ${CONTRACT_LIMITS.astDepth} levels`)] }
230
249
  }
231
- modules.set(path, parsed.module)
250
+ const held = withoutTypeDeclarations(parsed.module)
251
+ nodes += nodeCount(held.program)
252
+ if (nodes > CONTRACT_LIMITS.astNodes) {
253
+ return { ok: false, findings: [overBudget(path, `${entry} and its modules hold over ${CONTRACT_LIMITS.astNodes} syntax nodes`)] }
254
+ }
255
+ modules.set(path, held)
232
256
  for (const specifier of importedSpecifiers(parsed.module)) {
233
257
  const resolution = isRelativeSpecifier(specifier) ? resolveRelative((candidate) => files.has(candidate), path, specifier) : undefined
234
258
  if (resolution?.kind === 'file') {
@@ -241,6 +265,18 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
241
265
  return findings.length > 0 ? { ok: false, findings } : { ok: true, graph: new ModuleGraph(modules) }
242
266
  }
243
267
 
268
+ /** Top-level type declarations: the module index binds no name to them, and the literal rule passes over them. */
269
+ const TYPE_DECLARATIONS = new Set(['TSTypeAliasDeclaration', 'TSInterfaceDeclaration'])
270
+
271
+ /** The module without its top-level type declarations, which the reader would otherwise hold until it is done. */
272
+ function withoutTypeDeclarations(module: ParsedModule): ParsedModule {
273
+ const body = children(module.program, 'body').filter((statement) => {
274
+ const declaration = statement?.type === 'ExportNamedDeclaration' ? child(statement, 'declaration') : statement
275
+ return declaration === null || declaration === undefined || !TYPE_DECLARATIONS.has(declaration.type)
276
+ })
277
+ return { ...module, program: { ...module.program, body } }
278
+ }
279
+
244
280
  function missingFile(file: string): Finding {
245
281
  return {
246
282
  file,
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
+ }