@fabrika/check 0.9.0-dev.3 → 0.9.0-dev.31

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 (75) hide show
  1. package/package.json +12 -7
  2. package/src/ast.ts +69 -18
  3. package/src/bun-plugin.ts +4 -27
  4. package/src/check.ts +157 -44
  5. package/src/cli.ts +34 -8
  6. package/src/contract.ts +68 -11
  7. package/src/dialect.ts +29 -0
  8. package/src/finding.ts +21 -8
  9. package/src/graph.ts +49 -12
  10. package/src/index.ts +4 -12
  11. package/src/inputs.ts +5 -2
  12. package/src/layout.ts +41 -12
  13. package/src/limits.ts +15 -5
  14. package/src/migration-base.ts +85 -0
  15. package/src/reader/schema.ts +42 -512
  16. package/src/reader/surface.ts +48 -7
  17. package/src/reader/value.ts +41 -8
  18. package/src/references.ts +16 -1
  19. package/src/resolution.ts +2 -2
  20. package/src/rules/cloudflare.ts +59 -0
  21. package/src/rules/compile.ts +32 -0
  22. package/src/rules/contract.ts +3 -2
  23. package/src/rules/framework.ts +2 -2
  24. package/src/rules/identity.ts +6 -9
  25. package/src/rules/literal.ts +42 -9
  26. package/src/rules/migration-history.ts +70 -0
  27. package/src/rules/migrations.ts +248 -9
  28. package/src/rules/modules.ts +9 -3
  29. package/src/rules/platform-migrations.ts +100 -0
  30. package/src/rules/runtime.ts +45 -14
  31. package/src/rules/structure.ts +172 -19
  32. package/src/rules/tests.ts +9 -60
  33. package/src/rules/types.ts +17 -16
  34. package/src/shell-modules.ts +53 -0
  35. package/src/slice.ts +6 -5
  36. package/src/source-maps.ts +2 -0
  37. package/src/trust.ts +8 -4
  38. package/src/vite-plugin.ts +65 -0
  39. package/types/src/ast.d.ts +6 -2
  40. package/types/src/check.d.ts +3 -0
  41. package/types/src/contract.d.ts +13 -1
  42. package/types/src/dialect.d.ts +8 -0
  43. package/types/src/finding.d.ts +7 -6
  44. package/types/src/graph.d.ts +12 -2
  45. package/types/src/index.d.ts +4 -3
  46. package/types/src/layout.d.ts +25 -10
  47. package/types/src/limits.d.ts +14 -4
  48. package/types/src/migration-base.d.ts +9 -0
  49. package/types/src/reader/schema.d.ts +5 -2
  50. package/types/src/reader/value.d.ts +3 -3
  51. package/types/src/references.d.ts +6 -1
  52. package/types/src/rules/cloudflare.d.ts +9 -0
  53. package/types/src/rules/compile.d.ts +7 -0
  54. package/types/src/rules/framework.d.ts +1 -1
  55. package/types/src/rules/literal.d.ts +1 -1
  56. package/types/src/rules/migration-history.d.ts +12 -0
  57. package/types/src/rules/migrations.d.ts +28 -0
  58. package/types/src/rules/platform-migrations.d.ts +15 -0
  59. package/types/src/rules/runtime.d.ts +7 -2
  60. package/types/src/rules/structure.d.ts +18 -4
  61. package/types/src/rules/tests.d.ts +6 -14
  62. package/types/src/rules/types.d.ts +2 -0
  63. package/types/src/shell-modules.d.ts +7 -0
  64. package/types/src/slice.d.ts +8 -2
  65. package/types/src/vite-plugin.d.ts +27 -0
  66. package/src/endpoint-fixtures.ts +0 -221
  67. package/src/rules/crontab.ts +0 -147
  68. package/src/rules/isolation.ts +0 -79
  69. package/src/scaffold-sample.ts +0 -111
  70. package/src/scaffold.ts +0 -650
  71. package/types/src/endpoint-fixtures.d.ts +0 -36
  72. package/types/src/rules/crontab.d.ts +0 -15
  73. package/types/src/rules/isolation.d.ts +0 -18
  74. package/types/src/scaffold-sample.d.ts +0 -8
  75. package/types/src/scaffold.d.ts +0 -28
package/src/contract.ts CHANGED
@@ -5,20 +5,22 @@
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, nodeCount, nodeDepth, type ParsedModule, utf8Bytes } from './ast'
9
9
  import { type Finding, formatFinding } from './finding'
10
10
  import { ModuleGraph } from './graph'
11
- import { CONTRACT_EXPORT, CONTRACT_FILE, isRelativeSpecifier, isSourceFile, resolveRelative, TABLES_FILE } from './layout'
11
+ import { CONTRACT_EXPORT, CONTRACT_FILE, isRelativeSpecifier, isSourceFile, resolveRelative, TABLES_EXPORT, TABLES_FILE } from './layout'
12
12
  import { CONTRACT_LIMITS } from './limits'
13
13
  import { ReaderProblems } from './reader/problems'
14
14
  import { readContractValue } from './reader/surface'
15
15
  import { readTablesValue } from './reader/tables'
16
16
  import { ValueReader } from './reader/value'
17
+ import { importedSpecifiers } from './references'
17
18
  import { checkLiteralGraph } from './rules/literal'
18
- import { parseShellModule } from './slice'
19
+ import { offsets, parseShellModule, type Range } from './slice'
19
20
  import { checkTrustedResolution } from './trust'
20
21
 
21
22
  export { ContractError } from '@fabrika/app/contract'
23
+ export { accessTables } from '@fabrika/db/tables'
22
24
  export { type Finding, formatFinding } from './finding'
23
25
  export { contractReaderInputs } from './inputs'
24
26
  export { CONTRACT_FILE, MIGRATIONS_DIR, TABLES_FILE } from './layout'
@@ -69,6 +71,20 @@ export function readTablesSource(files: ReadonlyMap<string, string>): TablePolic
69
71
  * `src/db/schema.generated.ts`) and the configuration `readContract` names. Throws `ContractSourceError`.
70
72
  */
71
73
  export function readTablesDefinition(files: ReadonlyMap<string, string>): Tables<unknown, unknown> | null {
74
+ return readTablesDeclaration(files)?.tables ?? null
75
+ }
76
+
77
+ /** The policies `readTablesDefinition` reads, and where the `defineTables(…)(…)` call that declares them stands. */
78
+ export interface TablesDeclaration {
79
+ readonly tables: Tables<unknown, unknown>
80
+ /** The module of the call: `src/db/tables.ts`, or the module it re-exports `tables` from. */
81
+ readonly file: string
82
+ /** The call's offsets in that module's text, the same in its shell slice. */
83
+ readonly call: Range
84
+ }
85
+
86
+ /** `readTablesDefinition` with the place of the call; `null` when `files` has no `src/db/tables.ts`. */
87
+ export function readTablesDeclaration(files: ReadonlyMap<string, string>): TablesDeclaration | null {
72
88
  if (!files.has(TABLES_FILE)) {
73
89
  return null
74
90
  }
@@ -94,7 +110,13 @@ export function readTablesDefinition(files: ReadonlyMap<string, string>): Tables
94
110
  if (tables === null || problems.findings.length > 0) {
95
111
  throw new ContractSourceError(problems.findings)
96
112
  }
97
- return tables
113
+ // readTablesValue read the policies from this binding's initializer, so it is a const with one.
114
+ const binding = parsed.graph.exported(module, TABLES_EXPORT)
115
+ const call = binding.kind === 'const' && binding.init !== undefined ? offsets(binding.init) : undefined
116
+ if (binding.kind !== 'const' || call === undefined) {
117
+ throw new Error(`${TABLES_FILE}: the policies were read, but not where their call stands`)
118
+ }
119
+ return { tables, file: binding.module.file, call }
98
120
  }
99
121
 
100
122
  /**
@@ -141,7 +163,7 @@ export function readContractModule(graph: ModuleGraph): ContractRead {
141
163
  return contract === null || problems.findings.length > 0 ? { ok: false, findings: problems.findings } : { ok: true, contract }
142
164
  }
143
165
 
144
- /** The contract module and every module its value imports reach. */
166
+ /** The contract module and every module its value imports and re-exports reach. */
145
167
  export function contractModules(graph: ModuleGraph, entry: ParsedModule): ParsedModule[] {
146
168
  const reached = new Map<string, ParsedModule>()
147
169
  const queue = [entry]
@@ -150,7 +172,7 @@ export function contractModules(graph: ModuleGraph, entry: ParsedModule): Parsed
150
172
  continue
151
173
  }
152
174
  reached.set(module.file, module)
153
- for (const imported of graph.index(module).imports.values()) {
175
+ for (const imported of graph.links(module)) {
154
176
  const target = graph.resolve(module.file, imported.specifier)
155
177
  if (target !== undefined) {
156
178
  queue.push(target)
@@ -160,21 +182,34 @@ export function contractModules(graph: ModuleGraph, entry: ParsedModule): Parsed
160
182
  return [...reached.values()]
161
183
  }
162
184
 
163
- /** The source and syntax-depth limits of `CONTRACT_LIMITS` over the modules of one entry (the contract or the tables). */
185
+ /** The source and syntax limits of `CONTRACT_LIMITS` over the modules of one entry (the contract or the tables). */
164
186
  function sourceBudget(modules: readonly ParsedModule[], entry = CONTRACT_FILE): Finding[] {
165
187
  const findings: Finding[] = []
166
188
  const bytes = modules.reduce((total, module) => total + module.bytes, 0)
167
189
  if (bytes > CONTRACT_LIMITS.sourceBytes) {
168
190
  findings.push(overBudget(entry, `${entry} and its modules are ${bytes} bytes, over ${CONTRACT_LIMITS.sourceBytes}`))
169
191
  }
192
+ let nodes = 0
170
193
  for (const module of modules) {
194
+ if (module.bytes > CONTRACT_LIMITS.moduleBytes) {
195
+ findings.push(overBudget(module.file, moduleTooLarge(module.bytes)))
196
+ }
171
197
  if (nodeDepth(module.program) > CONTRACT_LIMITS.astDepth) {
172
198
  findings.push(overBudget(module.file, `the syntax nests deeper than ${CONTRACT_LIMITS.astDepth} levels`))
173
199
  }
200
+ nodes += heldNodes(module)
201
+ }
202
+ if (nodes > CONTRACT_LIMITS.astNodes) {
203
+ findings.push(overBudget(entry, `${entry} and its modules hold ${nodes} syntax nodes, over the budget of ${CONTRACT_LIMITS.astNodes}`))
174
204
  }
175
205
  return findings
176
206
  }
177
207
 
208
+ const moduleTooLarge = (bytes: number): string => `the module is ${bytes} bytes, over ${CONTRACT_LIMITS.moduleBytes} for one module`
209
+
210
+ /** The syntax nodes the reader holds of a module: all but its top-level type declarations. */
211
+ const heldNodes = (module: ParsedModule): number => nodeCount(withoutTypeDeclarations(module).program)
212
+
178
213
  function overBudget(file: string, message: string): Finding {
179
214
  return {
180
215
  file,
@@ -192,8 +227,8 @@ type ParsedGraph = { readonly ok: true; readonly graph: ModuleGraph } | { readon
192
227
  /**
193
228
  * Parses `entry` (`fabrika.contract.ts` or `src/db/tables.ts`) and the modules its imports reach among `files`, and
194
229
  * 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.
230
+ * import; the byte limits hold before a module is parsed, and the depth and node limits right after, before any
231
+ * recursive rule walks it.
197
232
  */
198
233
  function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): ParsedGraph {
199
234
  const modules = new Map<string, ParsedModule>()
@@ -202,13 +237,18 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
202
237
  return { ok: false, findings: [missingFile(entry)] }
203
238
  }
204
239
  let bytes = 0
240
+ let nodes = 0
205
241
  const queue = [entry]
206
242
  for (let path = queue.shift(); path !== undefined; path = queue.shift()) {
207
243
  const text = files.get(path)
208
244
  if (modules.has(path) || text === undefined || !isSourceFile(path)) {
209
245
  continue
210
246
  }
211
- bytes += utf8Bytes(text)
247
+ const moduleBytes = utf8Bytes(text)
248
+ if (moduleBytes > CONTRACT_LIMITS.moduleBytes) {
249
+ return { ok: false, findings: [overBudget(path, moduleTooLarge(moduleBytes))] }
250
+ }
251
+ bytes += moduleBytes
212
252
  if (bytes > CONTRACT_LIMITS.sourceBytes) {
213
253
  return { ok: false, findings: [overBudget(path, `${entry} and its modules are over ${CONTRACT_LIMITS.sourceBytes} bytes`)] }
214
254
  }
@@ -228,7 +268,12 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
228
268
  if (nodeDepth(parsed.module.program) > CONTRACT_LIMITS.astDepth) {
229
269
  return { ok: false, findings: [overBudget(path, `the syntax nests deeper than ${CONTRACT_LIMITS.astDepth} levels`)] }
230
270
  }
231
- modules.set(path, parsed.module)
271
+ const held = withoutTypeDeclarations(parsed.module)
272
+ nodes += nodeCount(held.program)
273
+ if (nodes > CONTRACT_LIMITS.astNodes) {
274
+ return { ok: false, findings: [overBudget(path, `${entry} and its modules hold over ${CONTRACT_LIMITS.astNodes} syntax nodes`)] }
275
+ }
276
+ modules.set(path, held)
232
277
  for (const specifier of importedSpecifiers(parsed.module)) {
233
278
  const resolution = isRelativeSpecifier(specifier) ? resolveRelative((candidate) => files.has(candidate), path, specifier) : undefined
234
279
  if (resolution?.kind === 'file') {
@@ -241,6 +286,18 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
241
286
  return findings.length > 0 ? { ok: false, findings } : { ok: true, graph: new ModuleGraph(modules) }
242
287
  }
243
288
 
289
+ /** Top-level type declarations: the module index binds no name to them, and the literal rule passes over them. */
290
+ const TYPE_DECLARATIONS = new Set(['TSTypeAliasDeclaration', 'TSInterfaceDeclaration'])
291
+
292
+ /** The module without its top-level type declarations, which the reader would otherwise hold until it is done. */
293
+ function withoutTypeDeclarations(module: ParsedModule): ParsedModule {
294
+ const body = children(module.program, 'body').filter((statement) => {
295
+ const declaration = statement?.type === 'ExportNamedDeclaration' ? child(statement, 'declaration') : statement
296
+ return declaration === null || declaration === undefined || !TYPE_DECLARATIONS.has(declaration.type)
297
+ })
298
+ return { ...module, program: { ...module.program, body } }
299
+ }
300
+
244
301
  function missingFile(file: string): Finding {
245
302
  return {
246
303
  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
+ }
package/src/finding.ts CHANGED
@@ -22,34 +22,47 @@ export const REFUSAL_RULE_IDS = [
22
22
  'cross-app-fetch',
23
23
  'url-endpoint',
24
24
  'on-conflict-index',
25
+ 'access-view-key',
25
26
  'key-literal',
26
27
  'client-identity',
27
28
  'sensitive-log',
28
29
  'unsafe-html',
29
30
  'dynamic-code',
30
31
  'migration-name',
32
+ 'migration-refused',
33
+ 'backup-schema',
34
+ 'migration-edited',
31
35
  'file-column-migration',
32
- 'crontab',
33
36
  'package-replacement',
34
37
  'skipped-test',
35
38
  'test-without-assertion',
36
- 'generated-test-hash',
37
39
  'mock-module',
38
- 'endpoint-fixture',
39
40
  'spa-server-import',
40
41
  'layer-import',
41
- 'generated-test-import',
42
42
  'shared-import',
43
+ 'tool-import',
44
+ 'cloudflare-scan',
45
+ 'cloudflare-job-segment',
46
+ 'cloudflare-current-timestamp',
47
+ 'cloudflare-framework-name',
48
+ 'cloudflare-view-trigger',
43
49
  ] as const
44
50
 
45
51
  /** Rules that report a step out of the application architecture. */
46
- export const STRUCTURE_HINT_RULE_IDS = ['logic-data-access', 'cross-slice-queries', 'handler-location', 'data-access-location'] as const
52
+ export const STRUCTURE_HINT_RULE_IDS = [
53
+ 'logic-data-access',
54
+ 'cross-slice-queries',
55
+ 'single-slice-queries',
56
+ 'handler-location',
57
+ 'data-access-location',
58
+ ] as const
47
59
 
48
60
  /**
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.
61
+ * Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, a
62
+ * `{ member: true }` endpoint of a contract whose external role admits people from outside the organization, and a
63
+ * Cloudflare mutation that waits for an outside call inside the object's transaction.
51
64
  */
52
- export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external'] as const
65
+ export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external', 'cloudflare-held-call'] as const
53
66
 
54
67
  export const RULE_IDS = [...REFUSAL_RULE_IDS, ...HINT_RULE_IDS] as const
55
68
 
package/src/graph.ts CHANGED
@@ -41,6 +41,8 @@ interface ModuleIndex {
41
41
  readonly imports: ReadonlyMap<string, ImportBinding>
42
42
  /** Exported name → the local name it exports, or the default export's expression. */
43
43
  readonly exports: ReadonlyMap<string, string | AstNode>
44
+ /** `export { x as y } from './m'`: the exported name (`local`) → the module and the name it takes from it. */
45
+ readonly reexports: ReadonlyMap<string, ImportBinding>
44
46
  }
45
47
 
46
48
  const importedName = (specifier: AstNode): string => {
@@ -55,6 +57,7 @@ const indexModule = (module: ParsedModule): ModuleIndex => {
55
57
  const others = new Set<string>()
56
58
  const imports = new Map<string, ImportBinding>()
57
59
  const exports = new Map<string, string | AstNode>()
60
+ const reexports = new Map<string, ImportBinding>()
58
61
  for (const statement of children(module.program, 'body')) {
59
62
  if (statement === null) continue
60
63
  if (statement.type === 'ImportDeclaration') {
@@ -73,13 +76,17 @@ const indexModule = (module: ParsedModule): ModuleIndex => {
73
76
  continue
74
77
  }
75
78
  const isExport = statement.type === 'ExportNamedDeclaration'
76
- if (isExport && child(statement, 'source') === undefined && stringField(statement, 'exportKind') !== 'type') {
79
+ const source = isExport ? staticString(child(statement, 'source')) : undefined
80
+ if (isExport && stringField(statement, 'exportKind') !== 'type') {
77
81
  for (const item of children(statement, 'specifiers')) {
78
82
  if (item === null || stringField(item, 'exportKind') === 'type') continue
79
- const local = identifierName(child(item, 'local'))
83
+ const localNode = child(item, 'local')
84
+ const local = identifierName(localNode) ?? staticString(localNode)
80
85
  const exported = child(item, 'exported')
81
86
  const name = identifierName(exported) ?? staticString(exported)
82
- if (local !== undefined && name !== undefined) exports.set(name, local)
87
+ if (local === undefined || name === undefined) continue
88
+ if (source === undefined) exports.set(name, local)
89
+ else reexports.set(name, { local: name, specifier: source, imported: local, node: item })
83
90
  }
84
91
  }
85
92
  const declaration = isExport ? child(statement, 'declaration') : statement
@@ -103,7 +110,7 @@ const indexModule = (module: ParsedModule): ModuleIndex => {
103
110
  }
104
111
  if (isExport) { for (const name of declared) exports.set(name, name) }
105
112
  }
106
- return { consts, others, imports, exports }
113
+ return { consts, others, imports, exports, reexports }
107
114
  }
108
115
 
109
116
  /** Erased wrappers: `x satisfies T`, `x as const`, parentheses. */
@@ -143,6 +150,12 @@ export class ModuleGraph {
143
150
  return resolveRelative((path) => this.#modules.has(path), from, specifier)
144
151
  }
145
152
 
153
+ /** What a module loads by name: its value imports and its re-exports. */
154
+ links(module: ParsedModule): readonly ImportBinding[] {
155
+ const index = this.index(module)
156
+ return [...index.imports.values(), ...index.reexports.values()]
157
+ }
158
+
146
159
  /** The checked module a relative specifier names; none when two candidates compete, the index of a directory import. */
147
160
  resolve(from: string, specifier: string): ParsedModule | undefined {
148
161
  if (!isRelativeSpecifier(specifier)) return undefined
@@ -169,7 +182,17 @@ export class ModuleGraph {
169
182
 
170
183
  /** What an exported name of `module` denotes. */
171
184
  exported(module: ParsedModule, name: string, seen: ReadonlySet<string> = new Set()): Binding {
172
- const exported = this.index(module).exports.get(name)
185
+ const index = this.index(module)
186
+ const reexported = index.reexports.get(name)
187
+ if (reexported !== undefined) {
188
+ const key = `${module.file}#export ${name}`
189
+ if (seen.has(key)) return { kind: 'unresolved', reason: `'${name}' is re-exported in a cycle` }
190
+ if (!isRelativeSpecifier(reexported.specifier)) return { kind: 'package', specifier: reexported.specifier, imported: reexported.imported }
191
+ const target = this.resolve(module.file, reexported.specifier)
192
+ if (target === undefined) return { kind: 'unresolved', reason: `unresolved module '${reexported.specifier}'` }
193
+ return this.exported(target, reexported.imported, new Set([...seen, key]))
194
+ }
195
+ const exported = index.exports.get(name)
173
196
  if (exported === undefined) return { kind: 'unresolved', reason: `'${module.file}' does not export '${name}'` }
174
197
  if (typeof exported !== 'string') return { kind: 'default', module, expression: exported }
175
198
  return this.binding(module, exported, seen)
@@ -194,13 +217,27 @@ export class ModuleGraph {
194
217
  }
195
218
  }
196
219
 
197
- /** The value of `key` in an object literal, read statically; spreads and computed keys are not followed. */
198
- export const propertyValue = (located: Located, key: string): Located | undefined => {
199
- if (located.node.type !== 'ObjectExpression') return undefined
220
+ /**
221
+ * The entries of an object literal by key, in the order the object holds them, as evaluating it would build them: a
222
+ * spread of a value that resolves to an object literal contributes its entries, and a later key overrides an earlier
223
+ * one. A computed key, a method and a spread of anything else are not followed.
224
+ */
225
+ export const objectEntries = (graph: ModuleGraph, located: Located, depth = 0): ReadonlyMap<string, Located> => {
226
+ const entries = new Map<string, Located>()
227
+ if (located.node.type !== 'ObjectExpression' || depth > 32) return entries
200
228
  for (const property of children(located.node, 'properties')) {
201
- if (property?.type !== 'Property' || staticKey(property, 'key') !== key) continue
202
- const value = child(property, 'value')
203
- return value === undefined ? undefined : { module: located.module, node: value }
229
+ if (property?.type === 'SpreadElement') {
230
+ const argument = child(property, 'argument')
231
+ const spread = argument === undefined ? undefined : graph.resolveValue({ module: located.module, node: argument })
232
+ if (spread !== undefined) { for (const [key, value] of objectEntries(graph, spread, depth + 1)) entries.set(key, value) }
233
+ continue
234
+ }
235
+ const key = property?.type === 'Property' && property['computed'] !== true ? staticKey(property, 'key') : undefined
236
+ const value = property === null || key === undefined ? undefined : child(property, 'value')
237
+ if (key !== undefined && value !== undefined) entries.set(key, { module: located.module, node: value })
204
238
  }
205
- return undefined
239
+ return entries
206
240
  }
241
+
242
+ /** The value of `key` in an object literal, read statically through `objectEntries`. */
243
+ export const propertyValue = (graph: ModuleGraph, located: Located, key: string): Located | undefined => objectEntries(graph, located).get(key)
package/src/index.ts CHANGED
@@ -1,15 +1,7 @@
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 } from './layout'
5
+ export { readMigrationBase } from './migration-base'
4
6
  export { type PackedSet, type PackedTarball, readPackedSet } from './packed'
5
- export { GENERATED_TEST_HEADER, generatedTestHeader } from './rules/tests'
6
- export {
7
- ENDPOINT_ACCESS_TEST,
8
- ENDPOINT_FIXTURES_FILE,
9
- type GeneratedTest,
10
- generatedTests,
11
- missingEndpointFixtures,
12
- POLICY_TESTS_DIR,
13
- policyTestPath,
14
- scaffoldInputs,
15
- } from './scaffold'
7
+ export type { MigrationBase } from './rules/migration-history'
package/src/inputs.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  // Which files of an application the static reader needs. Control reads a commit file by file, and the reader cannot
2
2
  // tell a missing file from one it was not given, so the caller asks here until nothing is missing. Worker-safe.
3
3
 
4
- import { importedSpecifiers } from './ast'
4
+ import { utf8Bytes } from './ast'
5
5
  import { parseJsonc } from './jsonc'
6
6
  import { CONTRACT_FILE, isRelativeSpecifier, isSourceFile, joinRelative, resolveRelative, TABLES_FILE } from './layout'
7
+ import { CONTRACT_LIMITS } from './limits'
8
+ import { importedSpecifiers } from './references'
7
9
  import { parseShellModule } from './slice'
8
10
  import { BUNFIG_FILE } from './trust'
9
11
 
@@ -49,7 +51,8 @@ export function contractReaderInputs(files: ReadonlyMap<string, string>, exists:
49
51
  want(path)
50
52
  continue
51
53
  }
52
- const parsed = isSourceFile(path) ? parseShellModule(path, text).parsed : undefined
54
+ // A module over the limit is not parsed here: the reader refuses it, and its own parse would be the peak.
55
+ const parsed = isSourceFile(path) && utf8Bytes(text) <= CONTRACT_LIMITS.moduleBytes ? parseShellModule(path, text).parsed : undefined
53
56
  if (parsed?.ok !== true) continue
54
57
  for (const specifier of importedSpecifiers(parsed.module)) {
55
58
  if (!isRelativeSpecifier(specifier)) continue
package/src/layout.ts CHANGED
@@ -1,20 +1,18 @@
1
+ import { children, type ParsedModule, positionOf } from './ast'
2
+
1
3
  /** Where an application keeps what the checker reads. Paths are relative to the application root. */
2
4
  export const CONTRACT_FILE = 'fabrika.contract.ts'
5
+ /** The provider-authored application config, whose `defineApp` names the provider. */
6
+ export const CONFIG_FILE = 'fabrika.config.ts'
3
7
  /** The named export of the contract module that holds `defineContract(…)`. */
4
8
  export const CONTRACT_EXPORT = 'contract'
5
9
  export const TABLES_FILE = 'src/db/tables.ts'
6
10
  /** The named export of the tables module that holds `defineTables(…)(…)`. */
7
11
  export const TABLES_EXPORT = 'tables'
8
12
  export const GENERATED_ENTRY_FILE = 'fabrika/entry.generated.ts'
13
+ /** Where a Cloudflare deploy stages the SPA mounts' built files (`@fabrika/provider-cloudflare`): build output, never source. */
14
+ export const STAGED_ASSETS_DIR = 'fabrika/assets/'
9
15
  export const MIGRATIONS_DIR = 'db/migrations/'
10
- /** Where `fabrika db test-scaffold` writes the policy isolation tests, `<table>.policy-isolation.test.ts`. */
11
- export const POLICY_TESTS_DIR = 'src/db/__tests__/'
12
- export const POLICY_TEST_SUFFIX = '.policy-isolation.test.ts'
13
- /** The generated endpoint access tests; they import `src/app.ts`, whose default export they boot. */
14
- export const ENDPOINT_ACCESS_TEST = 'src/__tests__/endpoint-access.test.ts'
15
- /** The inputs the author gives the endpoint access tests where the scaffold cannot sample one; read, never run. */
16
- export const ENDPOINT_FIXTURES_FILE = 'src/__tests__/endpoint-access.fixtures.ts'
17
- export const ZEROPS_FILES = ['zerops.yaml', 'zerops.yml'] as const
18
16
 
19
17
  /** The application architecture (docs/reference/application-architecture.md): where each layer's code lives. */
20
18
  export const VOCABULARY_FILE = 'src/vocabulary.ts'
@@ -22,9 +20,12 @@ export const APP_KIT_FILE = 'src/app-kit.ts'
22
20
  /** The shared zod schemas the shell and the SPA import: one module, or a directory of them once it grows. */
23
21
  export const SCHEMAS_FILE = 'src/schemas.ts'
24
22
  export const SCHEMAS_DIR = 'src/schemas/'
25
- /** Pure code the SPA and every slice may import: it loads nothing but `zod/v4` and other modules of its own directory. */
23
+ /**
24
+ * Pure code the SPA and every slice may import: it loads nothing but `zod/v4`, `@fabrika/app/schema` and other modules of
25
+ * its own directory.
26
+ */
26
27
  export const SHARED_DIR = 'src/shared/'
27
- /** `src/db/`: the tables, the generated schema and their generated tests; never a slice. */
28
+ /** `src/db/`: the tables and the generated schema; never a slice. */
28
29
  export const DATABASE_DIR = 'src/db/'
29
30
  /** A slice is a directory `src/<slice>/` that holds these modules, each optional. */
30
31
  export const SLICE_ENDPOINTS_FILE = 'endpoints.ts'
@@ -33,6 +34,11 @@ export const SLICE_QUERIES_FILE = 'queries.ts'
33
34
  export const SPA_DIR = 'web/'
34
35
  /** The server half of an application: its modules run in the application's process. */
35
36
  export const SERVER_DIR = 'src/'
37
+ /**
38
+ * A developer's tools, such as a command line over the contract: code that runs on a developer's machine and never in
39
+ * the application, so the rules for code that runs there do not apply, and no module outside it may load one.
40
+ */
41
+ export const TOOLS_DIR = 'tools/'
36
42
 
37
43
  const SOURCE_EXTENSION = /\.(?:[mc]?[jt]s|[jt]sx)$/
38
44
  const TEST_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[mc]?[jt]sx?$/
@@ -40,6 +46,9 @@ const TEST_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[mc]?[jt]sx?$/
40
46
  /** Build output, installed packages and tool state are not application source and are never read. */
41
47
  export const isIgnoredSegment = (segment: string): boolean => segment === 'node_modules' || segment === 'dist' || segment.startsWith('.')
42
48
 
49
+ /** Whether the checker skips `path` (relative to the root): under a skipped segment, or the staged SPA files. */
50
+ export const isSkippedPath = (path: string): boolean => path.split('/').some(isIgnoredSegment) || path.startsWith(STAGED_ASSETS_DIR)
51
+
43
52
  export const isSourceFile = (path: string): boolean => SOURCE_EXTENSION.test(path)
44
53
 
45
54
  export const isTestFile = (path: string): boolean => TEST_FILE.test(path)
@@ -47,14 +56,34 @@ export const isTestFile = (path: string): boolean => TEST_FILE.test(path)
47
56
  /** A module that runs in the application's server process: under `src/`, not a test. */
48
57
  export const isServerModule = (path: string): boolean => path.startsWith(SERVER_DIR) && !isTestFile(path)
49
58
 
59
+ /** A module under `tools/`, tests included. */
60
+ export const isToolModule = (path: string): boolean => path.startsWith(TOOLS_DIR)
61
+
50
62
  export const isJsonFile = (path: string): boolean => path.endsWith('.json')
51
63
 
64
+ const GENERATED_NAME = /\.(?:gen|generated)\.(?:[mc]?[jt]s|[jt]sx)$/
65
+ const GENERATED_MARKER = /@generated|auto-generated/i
66
+
67
+ /**
68
+ * A module a generator writes: named `<name>.gen.<ext>` or `<name>.generated.<ext>`, opening with a comment on its first
69
+ * line, before any statement, that says so (`@generated` or `auto-generated`, in any case). The rules about how source
70
+ * is written do not apply to it; every rule about what it does still does.
71
+ */
72
+ export const isGeneratedModule = (path: string, module: Pick<ParsedModule, 'program' | 'comments'>): boolean => {
73
+ const [header] = module.comments
74
+ if (!GENERATED_NAME.test(path) || header === undefined || header.position.line !== 1 || !GENERATED_MARKER.test(header.text)) return false
75
+ const [statement] = children(module.program, 'body')
76
+ if (statement === undefined || statement === null) return true
77
+ const start = positionOf(statement)
78
+ return header.position.line < start.line || (header.position.line === start.line && header.position.column < start.column)
79
+ }
80
+
52
81
  /** Whether the checker reads this file at all. */
53
82
  export const isCheckedFile = (path: string): boolean => {
54
83
  // The registry configuration and the lockfile decide what a trusted package name installs.
55
84
  if (path === '.npmrc' || path === 'bun.lock') return true
56
- if (path.split('/').some(isIgnoredSegment)) return false
57
- return isSourceFile(path) || isJsonFile(path) || path.startsWith(MIGRATIONS_DIR) || ZEROPS_FILES.some((name) => name === path)
85
+ if (isSkippedPath(path)) return false
86
+ return isSourceFile(path) || isJsonFile(path) || path.startsWith(MIGRATIONS_DIR)
58
87
  || path === 'bunfig.toml'
59
88
  }
60
89
 
package/src/limits.ts CHANGED
@@ -4,12 +4,22 @@
4
4
  * step runs.
5
5
  */
6
6
  export const CONTRACT_LIMITS = {
7
- /** UTF-8 bytes of `fabrika.contract.ts` and every module it imports, together. */
8
- sourceBytes: 512 * 1024,
7
+ /**
8
+ * UTF-8 bytes of `fabrika.contract.ts` and every module it imports, together. Control reads them in a Cloudflare
9
+ * Worker, whose isolate has 128 MB; handler bodies are sliced out before the parse, so they cost bytes, not nodes.
10
+ */
11
+ sourceBytes: 4 * 1024 * 1024,
12
+ /** UTF-8 bytes of one module: its own parse is the peak while it is read, and a dense one needs up to 340 times it. */
13
+ moduleBytes: 512 * 1024,
14
+ /**
15
+ * Syntax nodes the reader holds over each graph (the contract's, the tables'), top-level type declarations left out.
16
+ * At this, `sourceBytes` and `schemaNodes` together, Control's read needs a 95 MB heap of its 128 MB isolate.
17
+ */
18
+ astNodes: 400_000,
9
19
  /** Nesting of syntax nodes in one module; the contracts in this repository reach 25. */
10
20
  astDepth: 128,
11
21
  /** Schema nodes once every shared schema is expanded where the contract uses it, over the whole contract. */
12
- schemaNodes: 20_000,
13
- /** Nesting of one schema: objects, arrays, unions and wrappers. */
14
- schemaDepth: 32,
22
+ schemaNodes: 60_000,
23
+ /** Nesting of one schema: objects, arrays, unions and wrappers; it bounds the recursion of compiling and diffing one. */
24
+ schemaDepth: 64,
15
25
  } as const
@@ -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
+ }