@fabrika/check 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,299 @@
1
+ import { isBuiltin } from 'node:module'
2
+ import { type AstNode, child, identifierName, staticKey } from '../ast'
3
+ import { type Report, STRUCTURE_HINT_RULE_IDS } from '../finding'
4
+ import {
5
+ CONTRACT_FILE,
6
+ DATABASE_DIR,
7
+ isRelativeSpecifier,
8
+ isSourceFile,
9
+ isTestFile,
10
+ resolveRelative,
11
+ SCHEMAS_DIR,
12
+ SCHEMAS_FILE,
13
+ SHARED_DIR,
14
+ SLICE_ENDPOINTS_FILE,
15
+ SLICE_LOGIC_FILE,
16
+ SLICE_QUERIES_FILE,
17
+ SPA_DIR,
18
+ } from '../layout'
19
+ import type { ModuleReference } from '../references'
20
+ import { type ImportMappings, mappedTargets } from '../resolution'
21
+ import { isTestKit } from './modules'
22
+ import { isGeneratedTestPath } from './tests'
23
+
24
+ /** The rules of the application architecture (docs/reference/application-architecture.md): four refusals and the hints. */
25
+ export const STRUCTURE_RULE_IDS = ['spa-server-import', 'layer-import', 'generated-test-import', 'shared-import', ...STRUCTURE_HINT_RULE_IDS] as const
26
+
27
+ type SlicePart = 'endpoints' | 'logic' | 'queries'
28
+
29
+ const SLICE_PARTS: ReadonlyMap<string, SlicePart> = new Map([
30
+ [SLICE_ENDPOINTS_FILE, 'endpoints'],
31
+ [SLICE_LOGIC_FILE, 'logic'],
32
+ [SLICE_QUERIES_FILE, 'queries'],
33
+ ])
34
+
35
+ /** Directories under `src/` the layout gives another role; every other `src/<name>/` is the slice `<name>`. */
36
+ const NOT_SLICES: ReadonlySet<string> = new Set([DATABASE_DIR, SCHEMAS_DIR, SHARED_DIR, 'src/__tests__/'])
37
+
38
+ /** The slice a file lies in: the directory `src/<slice>/` it is under. */
39
+ const sliceOf = (path: string): string | undefined => {
40
+ const [root, name, ...rest] = path.split('/')
41
+ if (root !== 'src' || name === undefined || rest.length === 0 || NOT_SLICES.has(`src/${name}/`)) return undefined
42
+ return name
43
+ }
44
+
45
+ /** Which slice module a file is: `src/<slice>/endpoints.ts`, `logic.ts` or `queries.ts`. */
46
+ const slicePart = (path: string): SlicePart | undefined => {
47
+ const segments = path.split('/')
48
+ const name = segments[2]
49
+ if (segments.length !== 3 || name === undefined || sliceOf(path) === undefined) return undefined
50
+ return SLICE_PARTS.get(name)
51
+ }
52
+
53
+ /** Where a module sits in the architecture, which decides what it may import and call. */
54
+ export interface StructurePlace {
55
+ readonly file: string
56
+ readonly slice: string | undefined
57
+ readonly part: SlicePart | undefined
58
+ /** A test or the generated entrypoint: the structure hints do not apply to it. */
59
+ readonly exempt: boolean
60
+ }
61
+
62
+ export const structurePlace = (file: string, isGeneratedEntry: boolean): StructurePlace => ({
63
+ file,
64
+ slice: sliceOf(file),
65
+ part: slicePart(file),
66
+ exempt: isGeneratedEntry || isTestFile(file),
67
+ })
68
+
69
+ /** What the structure rules read beyond one module: every module's references, and how Bun resolves them. */
70
+ export interface StructureGraph {
71
+ readonly files: ReadonlyMap<string, string>
72
+ readonly mappings: ImportMappings
73
+ readonly referencesOf: (path: string) => readonly ModuleReference[]
74
+ }
75
+
76
+ interface Targets {
77
+ /** Application files the reference may load, relative to the root. */
78
+ readonly files: readonly string[]
79
+ /** Package specifiers it loads, after the application's import mappings. */
80
+ readonly packages: readonly string[]
81
+ }
82
+
83
+ const resolvedFiles = (exists: (path: string) => boolean, fromFile: string, specifier: string): readonly string[] => {
84
+ const resolution = resolveRelative(exists, fromFile, specifier)
85
+ if (resolution.kind === 'file') return [resolution.path]
86
+ return resolution.kind === 'missing' ? [] : resolution.paths
87
+ }
88
+
89
+ /** What a reference loads. An absolute or out-of-tree target is `unchecked-import`'s finding, so it loads nothing here. */
90
+ const referenceTargets = (graph: StructureGraph, file: string, specifier: string): Targets => {
91
+ const exists = (path: string): boolean => graph.files.has(path)
92
+ if (isRelativeSpecifier(specifier)) return { files: resolvedFiles(exists, file, specifier), packages: [] }
93
+ if (specifier.startsWith('/') || /^file:/i.test(specifier)) return { files: [], packages: [] }
94
+ const mapped = mappedTargets(graph.mappings, file, specifier)
95
+ if (mapped === undefined) return { files: [], packages: [specifier] }
96
+ // Mapped targets are relative to the root.
97
+ const files = mapped.filter(isRelativeSpecifier).flatMap((target) => resolvedFiles(exists, 'package.json', target))
98
+ const packages = mapped.filter((target) => !isRelativeSpecifier(target) && !target.startsWith('/'))
99
+ return { files, packages }
100
+ }
101
+
102
+ /**
103
+ * Everything a reference loads at runtime: its targets, and what the local modules among them load in turn, through
104
+ * imports, re-exports and literal loads. Only modules `descend` accepts are followed; each is read once.
105
+ */
106
+ const runtimeClosure = (graph: StructureGraph, start: Targets, descend: (path: string) => boolean): Targets => {
107
+ const files = new Set(start.files)
108
+ const packages = new Set(start.packages)
109
+ const pending = start.files.filter(descend)
110
+ const followed = new Set(pending)
111
+ for (let path = pending.pop(); path !== undefined; path = pending.pop()) {
112
+ for (const reference of graph.referencesOf(path)) {
113
+ if (reference.typeOnly) continue
114
+ const targets = referenceTargets(graph, path, reference.specifier)
115
+ for (const target of targets.packages) packages.add(target)
116
+ for (const target of targets.files) {
117
+ files.add(target)
118
+ if (!followed.has(target) && descend(target)) {
119
+ followed.add(target)
120
+ pending.push(target)
121
+ }
122
+ }
123
+ }
124
+ }
125
+ return { files: [...files], packages: [...packages] }
126
+ }
127
+
128
+ const isDataPackage = (specifier: string): boolean => specifier === '@fabrika/db' || specifier.startsWith('@fabrika/db/')
129
+
130
+ /** The framework modules logic and queries may import; the rest of `@fabrika/*` is the framework's own composition. */
131
+ const LAYER_PACKAGES: ReadonlySet<string> = new Set(['@fabrika/app', '@fabrika/db'])
132
+
133
+ /** The framework modules an SPA loads: the typed client, its React hooks and the component kit. */
134
+ const SPA_PACKAGES: ReadonlySet<string> = new Set([
135
+ '@fabrika/app/client',
136
+ '@fabrika/app/react',
137
+ '@fabrika/ui',
138
+ '@fabrika/ui/styles.css',
139
+ '@fabrika/ui/theme.css',
140
+ ])
141
+
142
+ const SPA_ALLOWED =
143
+ '@fabrika/app/client, @fabrika/app/react, @fabrika/ui, fabrika.contract.ts, src/schemas.ts, modules under src/shared/ and modules under web/; a type-only import of anything else'
144
+
145
+ const isSchemaModule = (path: string): boolean => path === SCHEMAS_FILE || path.startsWith(SCHEMAS_DIR)
146
+
147
+ const isSharedModule = (path: string): boolean => path.startsWith(SHARED_DIR)
148
+
149
+ /**
150
+ * The application modules a bundle of the SPA may load; `fabrika.contract.ts` is loaded without its handlers. A shared
151
+ * module is checked on its own (`checkSharedReference`), so it is not followed.
152
+ */
153
+ const isSpaModule = (path: string): boolean =>
154
+ path.startsWith(SPA_DIR) || path === CONTRACT_FILE || isSchemaModule(path) || isSharedModule(path) || !isSourceFile(path)
155
+
156
+ /** A runtime package the browser has not: the framework's server side, Bun, and Node's builtins in either spelling. */
157
+ const isServerPackage = (specifier: string): boolean => specifier.startsWith('@fabrika/') ? !SPA_PACKAGES.has(specifier) : isBuiltin(specifier)
158
+
159
+ /** Names what `reference` loads, directly or through the local modules it loads. */
160
+ const viaMessage = (reference: ModuleReference, loaded: string, what: string, into: string): string =>
161
+ loaded === reference.specifier ? `'${loaded}' is ${what}, imported by ${into}` : `'${reference.specifier}' loads ${what} ('${loaded}') into ${into}`
162
+
163
+ /** The SPA's own modules are checked one by one; a schema module it loads is followed, since nothing else checks it. */
164
+ const checkSpaReference = (graph: StructureGraph, reference: ModuleReference, targets: Targets, report: Report): void => {
165
+ const reached = runtimeClosure(graph, targets, isSchemaModule)
166
+ const server = reached.packages.find(isServerPackage) ?? reached.files.find((path) => !isSpaModule(path))
167
+ if (server !== undefined) report(reference.node, 'spa-server-import', viaMessage(reference, server, 'server code', 'the SPA'), SPA_ALLOWED)
168
+ }
169
+
170
+ /** The one package shared code loads; everything else it needs is in other modules of `src/shared/`. */
171
+ const SHARED_PACKAGE = 'zod/v4'
172
+
173
+ /** A shared module runs in the SPA and in every slice, so it loads nothing either side lacks. */
174
+ const checkSharedReference = (reference: ModuleReference, targets: Targets, report: Report): void => {
175
+ const outside = targets.packages.find((specifier) => specifier !== SHARED_PACKAGE) ?? targets.files.find((path) => !isSharedModule(path))
176
+ if (outside === undefined) return
177
+ report(
178
+ reference.node,
179
+ 'shared-import',
180
+ viaMessage(reference, outside, 'outside src/shared/', 'shared code'),
181
+ 'zod/v4 and other modules under src/shared/; a type-only import of anything else',
182
+ )
183
+ }
184
+
185
+ const isLayerModule = (path: string): boolean => {
186
+ const part = slicePart(path)
187
+ return part === 'logic' || part === 'queries'
188
+ }
189
+
190
+ /** Another logic or queries module is checked on its own; every other local module is followed with this one's rule. */
191
+ const checkLayerReference = (graph: StructureGraph, place: StructurePlace, reference: ModuleReference, targets: Targets, report: Report): void => {
192
+ const reached = runtimeClosure(graph, targets, (path) => !isLayerModule(path))
193
+ // The test kits are `test-only-import`'s finding everywhere outside a test file.
194
+ const internal = reached.packages.find((specifier) => specifier.startsWith('@fabrika/') && !LAYER_PACKAGES.has(specifier) && !isTestKit(specifier))
195
+ if (internal === undefined) return
196
+ report(
197
+ reference.node,
198
+ 'layer-import',
199
+ viaMessage(reference, internal, 'a framework module', place.part === 'logic' ? 'logic' : 'queries'),
200
+ '@fabrika/app (its errors) and @fabrika/db only, also through a helper module; the handler in endpoints.ts uses the rest',
201
+ )
202
+ }
203
+
204
+ const LOGIC_ALLOWED = 'logic over plain values: the handler in endpoints.ts reads through ctx.db or a function of queries.ts and passes the values in'
205
+
206
+ const checkLogicReference = (reference: ModuleReference, targets: Targets, report: Report): void => {
207
+ const data = targets.packages.some(isDataPackage)
208
+ || targets.files.some((path) => path.startsWith(DATABASE_DIR) || slicePart(path) === 'queries')
209
+ if (data) report(reference.node, 'logic-data-access', `'${reference.specifier}' is data access, imported by logic`, LOGIC_ALLOWED)
210
+ }
211
+
212
+ const checkSliceReference = (place: StructurePlace, reference: ModuleReference, targets: Targets, report: Report): void => {
213
+ const other = targets.files.find((path) => slicePart(path) === 'queries' && sliceOf(path) !== place.slice)
214
+ if (other === undefined) return
215
+ report(
216
+ reference.node,
217
+ 'cross-slice-queries',
218
+ `'${reference.specifier}' is the queries module of the slice '${sliceOf(other)}'`,
219
+ "a function in this slice's own queries.ts; share a rule through the other slice's logic.ts",
220
+ )
221
+ }
222
+
223
+ /** The architecture's rules over one module's imports, re-exports and loads, as Bun resolves them for that module. */
224
+ export const checkStructureReferences = (graph: StructureGraph, place: StructurePlace, report: Report): void => {
225
+ for (const reference of graph.referencesOf(place.file)) {
226
+ const targets = referenceTargets(graph, place.file, reference.specifier)
227
+ if (targets.files.some((path) => isGeneratedTestPath(path, graph.files))) {
228
+ report(
229
+ reference.node,
230
+ 'generated-test-import',
231
+ `'${reference.specifier}' is a generated test, which no module imports`,
232
+ 'a helper module of your own; fabrika db test-scaffold rewrites the generated tests',
233
+ )
234
+ }
235
+ if (reference.typeOnly) continue
236
+ if (place.file.startsWith(SPA_DIR) && !place.exempt) checkSpaReference(graph, reference, targets, report)
237
+ if (isSharedModule(place.file) && !place.exempt) checkSharedReference(reference, targets, report)
238
+ if (isLayerModule(place.file)) checkLayerReference(graph, place, reference, targets, report)
239
+ if (place.exempt) continue
240
+ if (place.part === 'logic') checkLogicReference(reference, targets, report)
241
+ else if (place.slice !== undefined) checkSliceReference(place, reference, targets, report)
242
+ }
243
+ }
244
+
245
+ /** The builders whose procedure takes a handler: `r.query(…).handle(…)`. */
246
+ const PROCEDURE_BUILDERS: ReadonlySet<string> = new Set(['query', 'mutation', 'cron', 'webhook', 'export'])
247
+
248
+ /** A `<x>.<builder>(…).handle(…)` call: the builder's name, its call (whose arguments hold the options) and `.handle`. */
249
+ export interface HandledProcedure {
250
+ readonly builder: string
251
+ readonly procedure: AstNode
252
+ /** The `handle` property node, where a finding points. */
253
+ readonly handle: AstNode
254
+ }
255
+
256
+ /** The procedure `node` hands a handler to, when `node` is `<x>.<builder>(…).handle(…)`. */
257
+ export const handledProcedure = (node: AstNode): HandledProcedure | undefined => {
258
+ if (node.type !== 'CallExpression') return undefined
259
+ const callee = child(node, 'callee')
260
+ if (callee?.type !== 'MemberExpression' || staticKey(callee, 'property') !== 'handle') return undefined
261
+ const procedure = child(callee, 'object')
262
+ const builder = procedure?.type === 'CallExpression' ? child(procedure, 'callee') : undefined
263
+ if (procedure === undefined || builder?.type !== 'MemberExpression') return undefined
264
+ const name = staticKey(builder, 'property')
265
+ const handle = child(callee, 'property')
266
+ return name !== undefined && PROCEDURE_BUILDERS.has(name) && handle !== undefined ? { builder: name, procedure, handle } : undefined
267
+ }
268
+
269
+ /** `ctx.db` or `ctx.sql`: the handles a handler reaches data through. */
270
+ const dataAccess = (node: AstNode): string | undefined => {
271
+ if (node.type !== 'MemberExpression' || identifierName(child(node, 'object')) !== 'ctx') return undefined
272
+ const property = staticKey(node, 'property')
273
+ return property === 'db' || property === 'sql' ? property : undefined
274
+ }
275
+
276
+ /** The architecture's hints at one node: a handler outside `endpoints.ts`, data access outside `endpoints.ts`/`queries.ts`. */
277
+ export const checkStructureNode = (place: StructurePlace, node: AstNode, report: Report): void => {
278
+ if (place.exempt) return
279
+ const handle = handledProcedure(node)?.handle
280
+ if (handle !== undefined && place.part !== 'endpoints') {
281
+ report(
282
+ handle,
283
+ 'handler-location',
284
+ "a handler outside a slice's endpoints.ts",
285
+ '.handle(…) in src/<slice>/endpoints.ts, whose group fabrika.contract.ts composes',
286
+ )
287
+ }
288
+ const handleName = dataAccess(node)
289
+ if (handleName === undefined || place.part === 'endpoints' || place.part === 'queries') return
290
+ if (place.part === 'logic') report(node, 'logic-data-access', `ctx.${handleName} in logic`, LOGIC_ALLOWED)
291
+ else {
292
+ report(
293
+ node,
294
+ 'data-access-location',
295
+ "data access outside a slice's endpoints.ts and queries.ts",
296
+ 'ctx.db and ctx.sql in a handler of src/<slice>/endpoints.ts; reusable data access in src/<slice>/queries.ts, over the handle the handler passes in',
297
+ )
298
+ }
299
+ }
@@ -0,0 +1,208 @@
1
+ import { type AstNode, child, children, type Comment, identifierName, memberPath, memberSuffix, staticString, walk } from '../ast'
2
+ import type { Finding, Report } from '../finding'
3
+ import { ENDPOINT_ACCESS_TEST, isRelativeSpecifier, joinRelative, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR, resolveRelative } from '../layout'
4
+ import { declaringScope } from '../scope'
5
+ import { isKey, parseToml } from '../toml'
6
+ import { BUNFIG_FILE } from '../trust'
7
+
8
+ const TEST_ROOTS = new Set(['test', 'it', 'describe', 'bench'])
9
+ const NOT_RUN = new Set(['skip', 'only', 'todo', 'skipIf', 'if', 'todoIf', 'failing'])
10
+ const NOT_RUN_ALIASES = new Set(['xit', 'xtest', 'xdescribe', 'fit', 'fdescribe'])
11
+ /** Modifiers that still register a test that runs: `test.concurrent(…)`, `test.each(table)(…)`. */
12
+ const RUNNING_MODIFIERS = new Set(['concurrent', 'serial', 'each'])
13
+ const ASSERTION_NAME = /^(?:expect|assert)/
14
+ const FUNCTION_TYPES = new Set(['ArrowFunctionExpression', 'FunctionExpression', 'FunctionDeclaration'])
15
+
16
+ const isFunction = (node: AstNode | null | undefined): node is AstNode => node !== null && node !== undefined && FUNCTION_TYPES.has(node.type)
17
+
18
+ /** `expect(x).toBe(y)`, `expect(x).not.toThrow()`: a matcher called on the result of `expect(…)`. */
19
+ const isMatcherCall = (callee: AstNode): boolean => {
20
+ let current = child(callee, 'object')
21
+ while (current?.type === 'MemberExpression') current = child(current, 'object')
22
+ return current?.type === 'CallExpression' && identifierName(child(current, 'callee')) === 'expect'
23
+ }
24
+
25
+ /** A matcher on `expect(…)`, or a call of an assertion helper: `assert(…)`, `assert.equal(…)`, `harness.expectDenied(…)`. */
26
+ const isAssertionCall = (node: AstNode): boolean => {
27
+ const callee = node.type === 'CallExpression' ? child(node, 'callee') : undefined
28
+ if (callee === undefined) return false
29
+ const name = identifierName(callee)
30
+ if (name !== undefined) return name !== 'expect' && ASSERTION_NAME.test(name)
31
+ if (callee.type !== 'MemberExpression') return false
32
+ if (isMatcherCall(callee)) return true
33
+ const path = memberPath(callee)
34
+ const [root] = path ?? []
35
+ const last = path?.[path.length - 1]
36
+ return root !== undefined && root !== 'expect' && (/^assert/.test(root) || (last !== undefined && ASSERTION_NAME.test(last)))
37
+ }
38
+
39
+ /** Whether a test body runs an assertion; a nested function counts only where it is called or passed to a call. */
40
+ const hasAssertion = (body: AstNode): boolean => {
41
+ let found = false
42
+ walk(body, (node, ancestors) => {
43
+ if (found) return 'skip'
44
+ if (node !== body && FUNCTION_TYPES.has(node.type)) {
45
+ const parent = ancestors[ancestors.length - 1]
46
+ const isInvoked = parent?.type === 'CallExpression' && (parent['callee'] === node || children(parent, 'arguments').includes(node))
47
+ if (!isInvoked) return 'skip'
48
+ }
49
+ if (isAssertionCall(node)) found = true
50
+ })
51
+ return found
52
+ }
53
+
54
+ /** The path a registration is called through: `test.concurrent(…)` → `test.concurrent`; `test.each(t)(…)` → `test.each`. */
55
+ const registrationPath = (node: AstNode): readonly string[] | undefined => {
56
+ const callee = child(node, 'callee')
57
+ if (callee?.type !== 'CallExpression') return callee === undefined ? undefined : memberPath(callee)
58
+ const inner = child(callee, 'callee')
59
+ const path = inner === undefined ? undefined : memberPath(inner)
60
+ return path?.[path.length - 1] === 'each' ? path : undefined
61
+ }
62
+
63
+ /** The name of `bun:test`'s export a module's own `local` binding imports, if it imports one. */
64
+ const bunTestImport = (program: AstNode, local: string): string | undefined => {
65
+ for (const statement of children(program, 'body')) {
66
+ if (statement?.type !== 'ImportDeclaration' || staticString(child(statement, 'source')) !== 'bun:test') continue
67
+ for (const specifier of children(statement, 'specifiers')) {
68
+ if (specifier?.type === 'ImportSpecifier' && identifierName(child(specifier, 'local')) === local) {
69
+ return identifierName(child(specifier, 'imported')) ?? staticString(child(specifier, 'imported'))
70
+ }
71
+ }
72
+ }
73
+ return undefined
74
+ }
75
+
76
+ /** What a call rooted at `root` reaches: the global, `bun:test`'s export it imports, or nothing for the module's own binding. */
77
+ const runnerName = (root: string, ancestors: readonly AstNode[]): string | undefined => {
78
+ const scope = declaringScope(root, ancestors)
79
+ if (scope === undefined) return root
80
+ return scope.type === 'Program' ? bunTestImport(scope, root) : undefined
81
+ }
82
+
83
+ /** For test files: every test runs, and every test asserts. */
84
+ export const checkTestNode = (node: AstNode, ancestors: readonly AstNode[], report: Report): void => {
85
+ if (node.type !== 'CallExpression') return
86
+ const path = registrationPath(node)
87
+ if (path === undefined) return
88
+ const [root, ...modifiers] = path
89
+ if (root === undefined) return
90
+ const notRun = TEST_ROOTS.has(root) ? modifiers.find((modifier) => NOT_RUN.has(modifier)) : undefined
91
+ const isAlias = modifiers.length === 0 && NOT_RUN_ALIASES.has(root) && NOT_RUN_ALIASES.has(runnerName(root, ancestors) ?? '')
92
+ if (notRun !== undefined || isAlias) {
93
+ if (child(node, 'callee')?.type !== 'CallExpression') {
94
+ report(node, 'skipped-test', `${path.join('.')} leaves tests out of the run`, 'a test that runs, or no test at all')
95
+ }
96
+ return
97
+ }
98
+ if ((root !== 'test' && root !== 'it') || !modifiers.every((modifier) => RUNNING_MODIFIERS.has(modifier))) return
99
+ const body = children(node, 'arguments').find(isFunction)
100
+ if (body !== undefined && !hasAssertion(body)) {
101
+ report(
102
+ node,
103
+ 'test-without-assertion',
104
+ `this ${path.join('.')}() asserts nothing, so it passes whatever the code does`,
105
+ 'a matcher on expect(…), such as expect(x).toBe(y), or a call of a helper named expect…/assert…',
106
+ )
107
+ }
108
+ }
109
+
110
+ /** The first line of a test written by `fabrika db test-scaffold`, followed by the SHA-256 of everything after that line. */
111
+ export const GENERATED_TEST_HEADER = '// @generated by fabrika db test-scaffold sha256:'
112
+ const GENERATED_TEST_MARKER = '// @generated by fabrika db test-scaffold'
113
+
114
+ const sha256 = async (text: string): Promise<string> => {
115
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
116
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')
117
+ }
118
+
119
+ /** The header `fabrika db test-scaffold` puts on a generated test with this body. */
120
+ export const generatedTestHeader = async (body: string): Promise<string> => `${GENERATED_TEST_HEADER}${await sha256(body)}`
121
+
122
+ export const checkGeneratedTest = async (text: string, comments: readonly Comment[], report: Report): Promise<void> => {
123
+ if (!text.startsWith(GENERATED_TEST_MARKER)) {
124
+ const misplaced = comments.find((comment) => comment.text.includes(GENERATED_TEST_MARKER.slice('// '.length)))
125
+ if (misplaced !== undefined) {
126
+ report(
127
+ misplaced.position,
128
+ 'generated-test-hash',
129
+ 'the generated-test header is not the first line of the file',
130
+ 'the file as fabrika db test-scaffold wrote it',
131
+ )
132
+ }
133
+ return
134
+ }
135
+ const newline = text.indexOf('\n')
136
+ const header = newline === -1 ? text : text.slice(0, newline)
137
+ const body = newline === -1 ? '' : text.slice(newline + 1)
138
+ if (header === (await generatedTestHeader(body))) return
139
+ report(
140
+ { line: 1, column: 1 },
141
+ 'generated-test-hash',
142
+ 'this generated test differs from what fabrika db test-scaffold wrote',
143
+ 'the file as generated; rerun fabrika db test-scaffold after a table change',
144
+ )
145
+ }
146
+
147
+ /** `[test]` keys that pick other test files, skip some, or let a failing test pass on a later attempt. */
148
+ const SUITE_NARROWING_TEST_KEYS = ['root', 'pathIgnorePatterns', 'retry'] as const
149
+
150
+ /**
151
+ * The `bunfig.toml` of an application must not narrow its own suite. The platform's run of the generated tests ignores
152
+ * the file (`fabrika db test-isolation`); this keeps the application's own run whole too. A file outside the TOML
153
+ * subset is reported by the trust rules.
154
+ */
155
+ export const checkTestSuiteConfig = (text: string): Finding[] => {
156
+ const document = parseToml(text)
157
+ if (!document.ok) return []
158
+ const findings: Finding[] = []
159
+ for (const entry of document.entries) {
160
+ for (const key of SUITE_NARROWING_TEST_KEYS) {
161
+ if (isKey(entry, 'test', key)) {
162
+ findings.push({
163
+ file: BUNFIG_FILE,
164
+ line: entry.line,
165
+ column: 1,
166
+ severity: 'refusal',
167
+ rule: 'skipped-test',
168
+ message: `[test] ${key} changes which tests run or whether a failure counts`,
169
+ allowed: 'no [test] root, pathIgnorePatterns or retry in bunfig.toml',
170
+ })
171
+ }
172
+ }
173
+ }
174
+ return findings
175
+ }
176
+
177
+ /** Whether `path` is a file the scaffold generates: a policy isolation test, the endpoint access test, or one with the header. */
178
+ export const isGeneratedTestPath = (path: string, files: ReadonlyMap<string, string>): boolean =>
179
+ path === ENDPOINT_ACCESS_TEST || (path.startsWith(POLICY_TESTS_DIR) && path.endsWith(POLICY_TEST_SUFFIX))
180
+ || (files.get(path)?.startsWith(GENERATED_TEST_MARKER) ?? false)
181
+
182
+ /**
183
+ * `mock.module(…)` of the test runner, a framework package or a generated test would let application code replace what
184
+ * the generated tests run on; a computed specifier could name any of them. Refused anywhere in the application.
185
+ */
186
+ export const checkMockModule = (node: AstNode, file: string, files: ReadonlyMap<string, string>, report: Report): void => {
187
+ if (node.type !== 'CallExpression') return
188
+ const callee = child(node, 'callee')
189
+ if (callee === undefined || callee.type !== 'MemberExpression') return
190
+ const suffix = memberPath(callee) ?? memberSuffix(callee)
191
+ if (suffix.length < 2 || suffix[suffix.length - 1] !== 'module' || suffix[suffix.length - 2] !== 'mock') return
192
+ const allowed = 'mock.module of an application module that no generated test is, with a literal specifier'
193
+ const specifier = staticString(children(node, 'arguments')[0] ?? undefined)
194
+ if (specifier === undefined) {
195
+ report(node, 'mock-module', 'mock.module with a computed specifier could replace the test runner or the framework', allowed)
196
+ return
197
+ }
198
+ if (specifier === 'bun:test' || specifier.startsWith('@fabrika/')) {
199
+ report(node, 'mock-module', `mock.module('${specifier}') replaces what the generated tests run on`, allowed)
200
+ return
201
+ }
202
+ if (!isRelativeSpecifier(specifier)) return
203
+ const resolved = resolveRelative((path) => files.has(path), file, specifier)
204
+ const targets = resolved.kind === 'file' ? [resolved.path] : resolved.kind === 'missing' ? [joinRelative(file, specifier) ?? ''] : resolved.paths
205
+ if (targets.some((target) => isGeneratedTestPath(target, files))) {
206
+ report(node, 'mock-module', `mock.module('${specifier}') replaces a generated test`, allowed)
207
+ }
208
+ }
@@ -0,0 +1,62 @@
1
+ import { type AstNode, child, children, type Comment, identifierName, isConstAssertion } from '../ast'
2
+ import type { Report } from '../finding'
3
+
4
+ const CAPABILITIES = new Set(['Ref', 'Within'])
5
+ const TYPE_COMBINATIONS = new Set(['TSUnionType', 'TSIntersectionType'])
6
+
7
+ /** `string`, or a union that has `string` as a branch: either way any dimension or action fits. */
8
+ const admitsAnyString = (type: AstNode): boolean => {
9
+ if (type.type === 'TSStringKeyword') return true
10
+ if (type.type === 'TSParenthesizedType') {
11
+ const inner = child(type, 'typeAnnotation')
12
+ return inner !== undefined && admitsAnyString(inner)
13
+ }
14
+ return TYPE_COMBINATIONS.has(type.type) && children(type, 'types').some((branch) => branch !== null && admitsAnyString(branch))
15
+ }
16
+
17
+ const referencedName = (typeName: AstNode | undefined): string | undefined =>
18
+ typeName?.type === 'TSQualifiedName' ? identifierName(child(typeName, 'right')) : identifierName(typeName)
19
+
20
+ export const checkTypeNode = (node: AstNode, report: Report): void => {
21
+ switch (node.type) {
22
+ case 'TSAsExpression':
23
+ case 'TSTypeAssertion':
24
+ if (!isConstAssertion(node)) {
25
+ report(node, 'type-assertion', 'a type assertion tells the compiler to stop checking', 'a value of the right type, `satisfies T`, or `as const`')
26
+ }
27
+ return
28
+ case 'TSAnyKeyword':
29
+ report(node, 'any-type', '`any` switches type checking off', 'the concrete type, or `unknown` narrowed by a check')
30
+ return
31
+ case 'TSTypeReference': {
32
+ const name = referencedName(child(node, 'typeName'))
33
+ if (name === undefined || !CAPABILITIES.has(name)) return
34
+ const typeArguments = child(node, 'typeArguments')
35
+ const parameters = typeArguments === undefined ? [] : children(typeArguments, 'params')
36
+ if (parameters.some((parameter) => parameter !== null && admitsAnyString(parameter))) {
37
+ report(
38
+ node,
39
+ 'capability-widening',
40
+ `${name}<string, …> widens a capability to any dimension or action`,
41
+ `${name}<'<dimension>', '<action>'> with literal names`,
42
+ )
43
+ }
44
+ return
45
+ }
46
+ }
47
+ }
48
+
49
+ const SUPPRESSIONS = /@ts-ignore|@ts-expect-error|@ts-nocheck|biome-ignore|eslint-disable|oxlint-disable/
50
+
51
+ export const checkComments = (comments: readonly Comment[], report: Report): void => {
52
+ for (const comment of comments) {
53
+ const found = SUPPRESSIONS.exec(comment.text)
54
+ if (found === null) continue
55
+ report(
56
+ comment.position,
57
+ 'suppression-comment',
58
+ `'${found[0]}' suppresses a check, and this checker recognises no suppression either`,
59
+ 'code that passes the check',
60
+ )
61
+ }
62
+ }