@fabrika/check 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +48 -5
- package/src/ast.ts +268 -0
- package/src/bun-plugin.ts +63 -0
- package/src/check.ts +183 -0
- package/src/cli.ts +88 -0
- package/src/contract.ts +254 -0
- package/src/endpoint-fixtures.ts +221 -0
- package/src/finding.ts +88 -0
- package/src/graph.ts +206 -0
- package/src/index.ts +15 -0
- package/src/inputs.ts +88 -0
- package/src/jsonc.ts +63 -0
- package/src/layout.ts +115 -0
- package/src/limits.ts +15 -0
- package/src/packed.ts +66 -0
- package/src/reader/problems.ts +11 -0
- package/src/reader/schema.ts +551 -0
- package/src/reader/surface.ts +1087 -0
- package/src/reader/tables.ts +116 -0
- package/src/reader/value.ts +644 -0
- package/src/references.ts +95 -0
- package/src/resolution.ts +178 -0
- package/src/rules/contract.ts +78 -0
- package/src/rules/crontab.ts +147 -0
- package/src/rules/framework.ts +177 -0
- package/src/rules/identity.ts +80 -0
- package/src/rules/isolation.ts +79 -0
- package/src/rules/json.ts +28 -0
- package/src/rules/literal.ts +736 -0
- package/src/rules/migrations.ts +87 -0
- package/src/rules/modules.ts +226 -0
- package/src/rules/packages.ts +168 -0
- package/src/rules/runtime.ts +507 -0
- package/src/rules/structure.ts +299 -0
- package/src/rules/tests.ts +208 -0
- package/src/rules/types.ts +62 -0
- package/src/scaffold-sample.ts +108 -0
- package/src/scaffold.ts +605 -0
- package/src/scope.ts +108 -0
- package/src/slice.ts +339 -0
- package/src/toml.ts +159 -0
- package/src/trust.ts +189 -0
- package/src/version.ts +4 -0
- package/README.md +0 -3
package/src/graph.ts
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AstNode,
|
|
3
|
+
child,
|
|
4
|
+
children,
|
|
5
|
+
identifierName,
|
|
6
|
+
isConstAssertion,
|
|
7
|
+
type ParsedModule,
|
|
8
|
+
staticKey,
|
|
9
|
+
staticString,
|
|
10
|
+
stringField,
|
|
11
|
+
unwrap,
|
|
12
|
+
} from './ast'
|
|
13
|
+
import { isRelativeSpecifier, type Resolution, resolveRelative } from './layout'
|
|
14
|
+
|
|
15
|
+
export interface Located {
|
|
16
|
+
readonly module: ParsedModule
|
|
17
|
+
readonly node: AstNode
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ImportBinding {
|
|
21
|
+
readonly local: string
|
|
22
|
+
readonly specifier: string
|
|
23
|
+
/** `default`, `*` or the imported name. */
|
|
24
|
+
readonly imported: string
|
|
25
|
+
/** The specifier node, where a finding about this import is reported. */
|
|
26
|
+
readonly node: AstNode
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** What a name denotes, followed through imports and exports to its declaration. */
|
|
30
|
+
export type Binding =
|
|
31
|
+
| { readonly kind: 'const'; readonly module: ParsedModule; readonly name: string; readonly init: AstNode | undefined }
|
|
32
|
+
| { readonly kind: 'default'; readonly module: ParsedModule; readonly expression: AstNode }
|
|
33
|
+
| { readonly kind: 'package'; readonly specifier: string; readonly imported: string }
|
|
34
|
+
| { readonly kind: 'other'; readonly module: ParsedModule; readonly name: string }
|
|
35
|
+
| { readonly kind: 'unresolved'; readonly reason: string }
|
|
36
|
+
|
|
37
|
+
interface ModuleIndex {
|
|
38
|
+
readonly consts: ReadonlyMap<string, AstNode | undefined>
|
|
39
|
+
/** Top-level names that are not consts: `let`, `var`, functions, classes. */
|
|
40
|
+
readonly others: ReadonlySet<string>
|
|
41
|
+
readonly imports: ReadonlyMap<string, ImportBinding>
|
|
42
|
+
/** Exported name → the local name it exports, or the default export's expression. */
|
|
43
|
+
readonly exports: ReadonlyMap<string, string | AstNode>
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const importedName = (specifier: AstNode): string => {
|
|
47
|
+
if (specifier.type === 'ImportDefaultSpecifier') return 'default'
|
|
48
|
+
if (specifier.type === 'ImportNamespaceSpecifier') return '*'
|
|
49
|
+
const imported = child(specifier, 'imported')
|
|
50
|
+
return identifierName(imported) ?? staticString(imported) ?? ''
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const indexModule = (module: ParsedModule): ModuleIndex => {
|
|
54
|
+
const consts = new Map<string, AstNode | undefined>()
|
|
55
|
+
const others = new Set<string>()
|
|
56
|
+
const imports = new Map<string, ImportBinding>()
|
|
57
|
+
const exports = new Map<string, string | AstNode>()
|
|
58
|
+
for (const statement of children(module.program, 'body')) {
|
|
59
|
+
if (statement === null) continue
|
|
60
|
+
if (statement.type === 'ImportDeclaration') {
|
|
61
|
+
const specifier = staticString(child(statement, 'source')) ?? ''
|
|
62
|
+
if (stringField(statement, 'importKind') === 'type') continue
|
|
63
|
+
for (const item of children(statement, 'specifiers')) {
|
|
64
|
+
const local = item ? identifierName(child(item, 'local')) : undefined
|
|
65
|
+
if (item === null || local === undefined || stringField(item, 'importKind') === 'type') continue
|
|
66
|
+
imports.set(local, { local, specifier, imported: importedName(item), node: item })
|
|
67
|
+
}
|
|
68
|
+
continue
|
|
69
|
+
}
|
|
70
|
+
if (statement.type === 'ExportDefaultDeclaration') {
|
|
71
|
+
const declaration = child(statement, 'declaration')
|
|
72
|
+
if (declaration !== undefined) exports.set('default', declaration)
|
|
73
|
+
continue
|
|
74
|
+
}
|
|
75
|
+
const isExport = statement.type === 'ExportNamedDeclaration'
|
|
76
|
+
if (isExport && child(statement, 'source') === undefined && stringField(statement, 'exportKind') !== 'type') {
|
|
77
|
+
for (const item of children(statement, 'specifiers')) {
|
|
78
|
+
if (item === null || stringField(item, 'exportKind') === 'type') continue
|
|
79
|
+
const local = identifierName(child(item, 'local'))
|
|
80
|
+
const exported = child(item, 'exported')
|
|
81
|
+
const name = identifierName(exported) ?? staticString(exported)
|
|
82
|
+
if (local !== undefined && name !== undefined) exports.set(name, local)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const declaration = isExport ? child(statement, 'declaration') : statement
|
|
86
|
+
if (declaration === undefined) continue
|
|
87
|
+
const declared: string[] = []
|
|
88
|
+
if (declaration.type === 'VariableDeclaration') {
|
|
89
|
+
const isConst = stringField(declaration, 'kind') === 'const'
|
|
90
|
+
for (const declarator of children(declaration, 'declarations')) {
|
|
91
|
+
const name = declarator ? identifierName(child(declarator, 'id')) : undefined
|
|
92
|
+
if (declarator === null || name === undefined) continue
|
|
93
|
+
declared.push(name)
|
|
94
|
+
if (isConst) consts.set(name, child(declarator, 'init'))
|
|
95
|
+
else others.add(name)
|
|
96
|
+
}
|
|
97
|
+
} else {
|
|
98
|
+
const name = identifierName(child(declaration, 'id'))
|
|
99
|
+
if (name !== undefined && !declaration.type.startsWith('TS')) {
|
|
100
|
+
declared.push(name)
|
|
101
|
+
others.add(name)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (isExport) { for (const name of declared) exports.set(name, name) }
|
|
105
|
+
}
|
|
106
|
+
return { consts, others, imports, exports }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Erased wrappers: `x satisfies T`, `x as const`, parentheses. */
|
|
110
|
+
export const unwrapValue = (node: AstNode): AstNode => {
|
|
111
|
+
let current = unwrap(node)
|
|
112
|
+
while (current.type === 'TSSatisfiesExpression' || (current.type === 'TSAsExpression' && isConstAssertion(current))) {
|
|
113
|
+
const inner = child(current, 'expression')
|
|
114
|
+
if (inner === undefined) break
|
|
115
|
+
current = unwrap(inner)
|
|
116
|
+
}
|
|
117
|
+
return current
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The application's modules, read statically: what each name denotes, without executing anything. */
|
|
121
|
+
export class ModuleGraph {
|
|
122
|
+
readonly #modules: ReadonlyMap<string, ParsedModule>
|
|
123
|
+
readonly #indexes = new Map<string, ModuleIndex>()
|
|
124
|
+
|
|
125
|
+
constructor(modules: ReadonlyMap<string, ParsedModule>) {
|
|
126
|
+
this.#modules = modules
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
module(file: string): ParsedModule | undefined {
|
|
130
|
+
return this.#modules.get(file)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
index(module: ParsedModule): ModuleIndex {
|
|
134
|
+
const cached = this.#indexes.get(module.file)
|
|
135
|
+
if (cached !== undefined) return cached
|
|
136
|
+
const index = indexModule(module)
|
|
137
|
+
this.#indexes.set(module.file, index)
|
|
138
|
+
return index
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** How a relative specifier resolves among the checked modules. */
|
|
142
|
+
resolution(from: string, specifier: string): Resolution {
|
|
143
|
+
return resolveRelative((path) => this.#modules.has(path), from, specifier)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The checked module a relative specifier names; none when two candidates compete, the index of a directory import. */
|
|
147
|
+
resolve(from: string, specifier: string): ParsedModule | undefined {
|
|
148
|
+
if (!isRelativeSpecifier(specifier)) return undefined
|
|
149
|
+
const resolution = this.resolution(from, specifier)
|
|
150
|
+
if (resolution.kind === 'file') return this.#modules.get(resolution.path)
|
|
151
|
+
if (resolution.kind === 'directory') return resolution.paths.map((path) => this.#modules.get(path)).find((module) => module !== undefined)
|
|
152
|
+
return undefined
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** What `name` denotes in `module`; an import is followed to the exporting module's declaration. */
|
|
156
|
+
binding(module: ParsedModule, name: string, seen: ReadonlySet<string> = new Set()): Binding {
|
|
157
|
+
const key = `${module.file}#${name}`
|
|
158
|
+
if (seen.has(key)) return { kind: 'unresolved', reason: `'${name}' is imported in a cycle` }
|
|
159
|
+
const index = this.index(module)
|
|
160
|
+
if (index.consts.has(name)) return { kind: 'const', module, name, init: index.consts.get(name) }
|
|
161
|
+
if (index.others.has(name)) return { kind: 'other', module, name }
|
|
162
|
+
const imported = index.imports.get(name)
|
|
163
|
+
if (imported === undefined) return { kind: 'unresolved', reason: `'${name}' is not declared` }
|
|
164
|
+
if (!isRelativeSpecifier(imported.specifier)) return { kind: 'package', specifier: imported.specifier, imported: imported.imported }
|
|
165
|
+
const target = this.resolve(module.file, imported.specifier)
|
|
166
|
+
if (target === undefined) return { kind: 'unresolved', reason: `unresolved module '${imported.specifier}'` }
|
|
167
|
+
return this.exported(target, imported.imported, new Set([...seen, key]))
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** What an exported name of `module` denotes. */
|
|
171
|
+
exported(module: ParsedModule, name: string, seen: ReadonlySet<string> = new Set()): Binding {
|
|
172
|
+
const exported = this.index(module).exports.get(name)
|
|
173
|
+
if (exported === undefined) return { kind: 'unresolved', reason: `'${module.file}' does not export '${name}'` }
|
|
174
|
+
if (typeof exported !== 'string') return { kind: 'default', module, expression: exported }
|
|
175
|
+
return this.binding(module, exported, seen)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Follows identifiers and erased wrappers to the expression a value is written as; `undefined` when it is not static. */
|
|
179
|
+
resolveValue(located: Located, depth = 0): Located | undefined {
|
|
180
|
+
const node = unwrapValue(located.node)
|
|
181
|
+
const name = identifierName(node)
|
|
182
|
+
if (name === undefined) return { module: located.module, node }
|
|
183
|
+
if (depth > 32) return undefined
|
|
184
|
+
const binding = this.binding(located.module, name)
|
|
185
|
+
if (binding.kind === 'const' && binding.init !== undefined) return this.resolveValue({ module: binding.module, node: binding.init }, depth + 1)
|
|
186
|
+
if (binding.kind === 'default') return this.resolveValue({ module: binding.module, node: binding.expression }, depth + 1)
|
|
187
|
+
return undefined
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** The fixed string a value resolves to. */
|
|
191
|
+
resolveString(located: Located): string | undefined {
|
|
192
|
+
const value = this.resolveValue(located)
|
|
193
|
+
return value === undefined ? undefined : staticString(value.node)
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
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
|
|
200
|
+
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 }
|
|
204
|
+
}
|
|
205
|
+
return undefined
|
|
206
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export { type ApplicationTree, checkApplication, type CheckInput, readApplicationTree } from './check'
|
|
2
|
+
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 { 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'
|
package/src/inputs.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Which files of an application the static reader needs. Control reads a commit file by file, and the reader cannot
|
|
2
|
+
// tell a missing file from one it was not given, so the caller asks here until nothing is missing. Worker-safe.
|
|
3
|
+
|
|
4
|
+
import { importedSpecifiers } from './ast'
|
|
5
|
+
import { parseJsonc } from './jsonc'
|
|
6
|
+
import { CONTRACT_FILE, isRelativeSpecifier, isSourceFile, joinRelative, resolveRelative, TABLES_FILE } from './layout'
|
|
7
|
+
import { parseShellModule } from './slice'
|
|
8
|
+
import { BUNFIG_FILE } from './trust'
|
|
9
|
+
|
|
10
|
+
const RESOLUTION_CONFIGS = ['package.json', 'tsconfig.json', 'jsconfig.json']
|
|
11
|
+
const TSCONFIG_NAMES = ['tsconfig.json', 'jsconfig.json']
|
|
12
|
+
|
|
13
|
+
const baseName = (path: string): string => path.slice(path.lastIndexOf('/') + 1)
|
|
14
|
+
|
|
15
|
+
const inDirectory = (directory: string, name: string): string => (directory === '' ? name : `${directory}/${name}`)
|
|
16
|
+
|
|
17
|
+
/** The root and every directory above the file, outermost first. */
|
|
18
|
+
const directoriesOf = (path: string): string[] => {
|
|
19
|
+
const segments = path.split('/').slice(0, -1)
|
|
20
|
+
return ['', ...segments.map((_, index) => segments.slice(0, index + 1).join('/'))]
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> => typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The paths `readContractSource` reads that `files` does not hold yet, among the paths that `exists` at the commit:
|
|
27
|
+
* `fabrika.contract.ts` and `src/db/tables.ts`, every module the shell slice of each imports (an import only a
|
|
28
|
+
* colocated handler uses is never followed) with every candidate of an import, the
|
|
29
|
+
* `package.json`, `tsconfig.json` and `jsconfig.json` of each such module's directories, a root `bunfig.toml`, and the
|
|
30
|
+
* files a `tsconfig.json` extends. A module is followed only once its text is in `files`, so the caller reads the answer,
|
|
31
|
+
* adds it to `files` and asks again until the answer is empty.
|
|
32
|
+
*/
|
|
33
|
+
export function contractReaderInputs(files: ReadonlyMap<string, string>, exists: (path: string) => boolean): string[] {
|
|
34
|
+
const needed = new Set<string>()
|
|
35
|
+
const want = (path: string): void => {
|
|
36
|
+
if (exists(path) && !files.has(path)) needed.add(path)
|
|
37
|
+
}
|
|
38
|
+
want(BUNFIG_FILE)
|
|
39
|
+
const visited = new Set<string>()
|
|
40
|
+
const queue = [CONTRACT_FILE, TABLES_FILE].filter(exists)
|
|
41
|
+
for (let path = queue.shift(); path !== undefined; path = queue.shift()) {
|
|
42
|
+
if (visited.has(path)) continue
|
|
43
|
+
visited.add(path)
|
|
44
|
+
for (const directory of directoriesOf(path)) {
|
|
45
|
+
for (const name of RESOLUTION_CONFIGS) want(inDirectory(directory, name))
|
|
46
|
+
}
|
|
47
|
+
const text = files.get(path)
|
|
48
|
+
if (text === undefined) {
|
|
49
|
+
want(path)
|
|
50
|
+
continue
|
|
51
|
+
}
|
|
52
|
+
const parsed = isSourceFile(path) ? parseShellModule(path, text).parsed : undefined
|
|
53
|
+
if (parsed?.ok !== true) continue
|
|
54
|
+
for (const specifier of importedSpecifiers(parsed.module)) {
|
|
55
|
+
if (!isRelativeSpecifier(specifier)) continue
|
|
56
|
+
const resolution = resolveRelative(exists, path, specifier)
|
|
57
|
+
const targets = resolution.kind === 'file' ? [resolution.path] : resolution.kind === 'missing' ? [] : resolution.paths
|
|
58
|
+
for (const target of targets) {
|
|
59
|
+
if (isSourceFile(target)) queue.push(target)
|
|
60
|
+
else want(target)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
for (const extended of extendedConfigs(files)) want(extended)
|
|
65
|
+
return [...needed].sort()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Every candidate of a relative `extends`, followed from each `tsconfig.json` and `jsconfig.json` in `files`. */
|
|
69
|
+
function extendedConfigs(files: ReadonlyMap<string, string>): string[] {
|
|
70
|
+
const candidates: string[] = []
|
|
71
|
+
const visited = new Set<string>()
|
|
72
|
+
const queue = [...files.keys()].filter((path) => TSCONFIG_NAMES.includes(baseName(path)))
|
|
73
|
+
for (let path = queue.shift(); path !== undefined; path = queue.shift()) {
|
|
74
|
+
const text = files.get(path)
|
|
75
|
+
if (visited.has(path) || text === undefined) continue
|
|
76
|
+
visited.add(path)
|
|
77
|
+
const config = parseJsonc(text)
|
|
78
|
+
const extended = isRecord(config) ? config['extends'] : undefined
|
|
79
|
+
const targets = typeof extended === 'string' ? [extended] : Array.isArray(extended) ? extended : []
|
|
80
|
+
for (const target of targets) {
|
|
81
|
+
const base = typeof target === 'string' && isRelativeSpecifier(target) ? joinRelative(path, target) : undefined
|
|
82
|
+
if (base === undefined) continue
|
|
83
|
+
candidates.push(base, `${base}.json`)
|
|
84
|
+
queue.push(base, `${base}.json`)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return candidates
|
|
88
|
+
}
|
package/src/jsonc.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// JSON with comments and trailing commas, as `tsconfig.json` allows it. Plain JavaScript, so the reader can run it in a
|
|
2
|
+
// Worker, where `Bun.JSONC` does not exist.
|
|
3
|
+
|
|
4
|
+
/** The parsed value, or `undefined` when the text is not JSON with comments. */
|
|
5
|
+
export function parseJsonc(text: string): unknown {
|
|
6
|
+
try {
|
|
7
|
+
return JSON.parse(stripJsonc(text))
|
|
8
|
+
} catch {
|
|
9
|
+
return undefined
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The text without comments and without a comma before `}` or `]`; strings are copied unchanged. */
|
|
14
|
+
function stripJsonc(text: string): string {
|
|
15
|
+
let output = ''
|
|
16
|
+
/** Where the last comma outside a string landed in `output`, while only whitespace and comments follow it. */
|
|
17
|
+
let pendingComma = -1
|
|
18
|
+
let index = 0
|
|
19
|
+
while (index < text.length) {
|
|
20
|
+
const char = text[index] ?? ''
|
|
21
|
+
const next = text[index + 1] ?? ''
|
|
22
|
+
if (char === '"') {
|
|
23
|
+
const end = stringEnd(text, index)
|
|
24
|
+
output += text.slice(index, end)
|
|
25
|
+
pendingComma = -1
|
|
26
|
+
index = end
|
|
27
|
+
} else if (char === '/' && next === '/') {
|
|
28
|
+
const end = text.indexOf('\n', index)
|
|
29
|
+
index = end === -1 ? text.length : end
|
|
30
|
+
} else if (char === '/' && next === '*') {
|
|
31
|
+
const end = text.indexOf('*/', index + 2)
|
|
32
|
+
index = end === -1 ? text.length : end + 2
|
|
33
|
+
} else {
|
|
34
|
+
if ((char === '}' || char === ']') && pendingComma !== -1) {
|
|
35
|
+
output = output.slice(0, pendingComma) + output.slice(pendingComma + 1)
|
|
36
|
+
}
|
|
37
|
+
if (char === ',') {
|
|
38
|
+
pendingComma = output.length
|
|
39
|
+
} else if (!/\s/.test(char)) {
|
|
40
|
+
pendingComma = -1
|
|
41
|
+
}
|
|
42
|
+
output += char
|
|
43
|
+
index++
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return output
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The index after the closing quote of the string that starts at `start`. */
|
|
50
|
+
function stringEnd(text: string, start: number): number {
|
|
51
|
+
let index = start + 1
|
|
52
|
+
while (index < text.length) {
|
|
53
|
+
const char = text[index]
|
|
54
|
+
if (char === '\\') {
|
|
55
|
+
index += 2
|
|
56
|
+
} else if (char === '"') {
|
|
57
|
+
return index + 1
|
|
58
|
+
} else {
|
|
59
|
+
index++
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return text.length
|
|
63
|
+
}
|
package/src/layout.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/** Where an application keeps what the checker reads. Paths are relative to the application root. */
|
|
2
|
+
export const CONTRACT_FILE = 'fabrika.contract.ts'
|
|
3
|
+
/** The named export of the contract module that holds `defineContract(…)`. */
|
|
4
|
+
export const CONTRACT_EXPORT = 'contract'
|
|
5
|
+
export const TABLES_FILE = 'src/db/tables.ts'
|
|
6
|
+
/** The named export of the tables module that holds `defineTables(…)(…)`. */
|
|
7
|
+
export const TABLES_EXPORT = 'tables'
|
|
8
|
+
export const GENERATED_ENTRY_FILE = 'fabrika/entry.generated.ts'
|
|
9
|
+
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
|
+
|
|
19
|
+
/** The application architecture (docs/reference/application-architecture.md): where each layer's code lives. */
|
|
20
|
+
export const VOCABULARY_FILE = 'src/vocabulary.ts'
|
|
21
|
+
export const APP_KIT_FILE = 'src/app-kit.ts'
|
|
22
|
+
/** The shared zod schemas the shell and the SPA import: one module, or a directory of them once it grows. */
|
|
23
|
+
export const SCHEMAS_FILE = 'src/schemas.ts'
|
|
24
|
+
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. */
|
|
26
|
+
export const SHARED_DIR = 'src/shared/'
|
|
27
|
+
/** `src/db/`: the tables, the generated schema and their generated tests; never a slice. */
|
|
28
|
+
export const DATABASE_DIR = 'src/db/'
|
|
29
|
+
/** A slice is a directory `src/<slice>/` that holds these modules, each optional. */
|
|
30
|
+
export const SLICE_ENDPOINTS_FILE = 'endpoints.ts'
|
|
31
|
+
export const SLICE_LOGIC_FILE = 'logic.ts'
|
|
32
|
+
export const SLICE_QUERIES_FILE = 'queries.ts'
|
|
33
|
+
export const SPA_DIR = 'web/'
|
|
34
|
+
/** The server half of an application: its modules run in the application's process. */
|
|
35
|
+
export const SERVER_DIR = 'src/'
|
|
36
|
+
|
|
37
|
+
const SOURCE_EXTENSION = /\.(?:[mc]?[jt]s|[jt]sx)$/
|
|
38
|
+
const TEST_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[mc]?[jt]sx?$/
|
|
39
|
+
|
|
40
|
+
/** Build output, installed packages and tool state are not application source and are never read. */
|
|
41
|
+
export const isIgnoredSegment = (segment: string): boolean => segment === 'node_modules' || segment === 'dist' || segment.startsWith('.')
|
|
42
|
+
|
|
43
|
+
export const isSourceFile = (path: string): boolean => SOURCE_EXTENSION.test(path)
|
|
44
|
+
|
|
45
|
+
export const isTestFile = (path: string): boolean => TEST_FILE.test(path)
|
|
46
|
+
|
|
47
|
+
/** A module that runs in the application's server process: under `src/`, not a test. */
|
|
48
|
+
export const isServerModule = (path: string): boolean => path.startsWith(SERVER_DIR) && !isTestFile(path)
|
|
49
|
+
|
|
50
|
+
export const isJsonFile = (path: string): boolean => path.endsWith('.json')
|
|
51
|
+
|
|
52
|
+
/** Whether the checker reads this file at all. */
|
|
53
|
+
export const isCheckedFile = (path: string): boolean => {
|
|
54
|
+
// The registry configuration and the lockfile decide what a trusted package name installs.
|
|
55
|
+
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)
|
|
58
|
+
|| path === 'bunfig.toml'
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Joins a relative specifier onto the importing file's directory; `undefined` when it climbs above the root. */
|
|
62
|
+
export const joinRelative = (fromFile: string, specifier: string): string | undefined => {
|
|
63
|
+
const segments = fromFile.split('/').slice(0, -1)
|
|
64
|
+
for (const part of specifier.split('/')) {
|
|
65
|
+
if (part === '.' || part === '') continue
|
|
66
|
+
if (part === '..') {
|
|
67
|
+
if (segments.length === 0) return undefined
|
|
68
|
+
segments.pop()
|
|
69
|
+
} else segments.push(part)
|
|
70
|
+
}
|
|
71
|
+
return segments.join('/')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const SOURCE_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs']
|
|
75
|
+
const SCRIPT_TO_SOURCE: Readonly<Record<string, string>> = { '.js': '.ts', '.jsx': '.tsx', '.mjs': '.mts', '.cjs': '.cts' }
|
|
76
|
+
|
|
77
|
+
/** The files Bun tries for a relative import of `base` after the name itself: each source extension, a script's source. */
|
|
78
|
+
const fileCandidates = (base: string): readonly string[] => {
|
|
79
|
+
const candidates = SOURCE_EXTENSIONS.map((extension) => `${base}${extension}`)
|
|
80
|
+
for (const [script, source] of Object.entries(SCRIPT_TO_SOURCE)) {
|
|
81
|
+
if (base.endsWith(script)) candidates.push(`${base.slice(0, -script.length)}${source}`)
|
|
82
|
+
}
|
|
83
|
+
return candidates
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** What makes `base` a directory import: an index file, or a `package.json` whose entry point Bun would follow. */
|
|
87
|
+
const directoryCandidates = (base: string): readonly string[] => [
|
|
88
|
+
...SOURCE_EXTENSIONS.map((extension) => `${base}/index${extension}`),
|
|
89
|
+
`${base}/package.json`,
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* How a relative import resolves among the files that exist. Only an exact name, or exactly one extension candidate,
|
|
94
|
+
* is a `file`: with two candidates (`m.ts` and `m.tsx`) or a directory, Bun's choice is not one the checker repeats.
|
|
95
|
+
*/
|
|
96
|
+
export type Resolution =
|
|
97
|
+
| { readonly kind: 'file'; readonly path: string }
|
|
98
|
+
| { readonly kind: 'ambiguous'; readonly paths: readonly string[] }
|
|
99
|
+
| { readonly kind: 'directory'; readonly paths: readonly string[] }
|
|
100
|
+
| { readonly kind: 'missing' }
|
|
101
|
+
|
|
102
|
+
export const resolveRelative = (exists: (path: string) => boolean, fromFile: string, specifier: string): Resolution => {
|
|
103
|
+
const base = joinRelative(fromFile, specifier)
|
|
104
|
+
if (base === undefined) return { kind: 'missing' }
|
|
105
|
+
if (base !== '' && exists(base)) return { kind: 'file', path: base }
|
|
106
|
+
const files = fileCandidates(base).filter(exists)
|
|
107
|
+
const [only, ...more] = files
|
|
108
|
+
if (only !== undefined && more.length === 0) return { kind: 'file', path: only }
|
|
109
|
+
if (only !== undefined) return { kind: 'ambiguous', paths: files }
|
|
110
|
+
const directory = directoryCandidates(base).filter(exists)
|
|
111
|
+
return directory.length === 0 ? { kind: 'missing' } : { kind: 'directory', paths: directory }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export const isRelativeSpecifier = (specifier: string): boolean =>
|
|
115
|
+
specifier === '.' || specifier === '..' || specifier.startsWith('./') || specifier.startsWith('../')
|
package/src/limits.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The resource budget of reading a contract from source. Control reads an application's commit, so a contract may
|
|
3
|
+
* not make the reader or `compileContract` do unbounded work; each limit is enforced while reading, before the next
|
|
4
|
+
* step runs.
|
|
5
|
+
*/
|
|
6
|
+
export const CONTRACT_LIMITS = {
|
|
7
|
+
/** UTF-8 bytes of `fabrika.contract.ts` and every module it imports, together. */
|
|
8
|
+
sourceBytes: 512 * 1024,
|
|
9
|
+
/** Nesting of syntax nodes in one module; the contracts in this repository reach 25. */
|
|
10
|
+
astDepth: 128,
|
|
11
|
+
/** 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,
|
|
15
|
+
} as const
|
package/src/packed.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// A local pack the operator names explicitly (`fabrika-check --packed <release-manifest.json>`): the
|
|
2
|
+
// package-replacement rule then accepts its tarballs, byte for byte, where it otherwise wants registry versions. The
|
|
3
|
+
// platform build never names one, so a deployed application still installs from the registry (ADR-0043).
|
|
4
|
+
|
|
5
|
+
import { createHash } from 'node:crypto'
|
|
6
|
+
import { readdir, readFile } from 'node:fs/promises'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { z } from 'zod/v4'
|
|
9
|
+
import { isIgnoredSegment } from './layout'
|
|
10
|
+
|
|
11
|
+
/** One package of the set: the tarball `release:pack` wrote and the sha512 integrity of its bytes. */
|
|
12
|
+
export interface PackedTarball {
|
|
13
|
+
readonly filename: string
|
|
14
|
+
readonly integrity: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface PackedSet {
|
|
18
|
+
/** The version the pack gave every package of the set. */
|
|
19
|
+
readonly version: string
|
|
20
|
+
/** Each package's tarball, by package name. */
|
|
21
|
+
readonly packages: ReadonlyMap<string, PackedTarball>
|
|
22
|
+
/** The sha512 integrity of every file under the root named like one of the tarballs, by path relative to the root. */
|
|
23
|
+
readonly tarballs: ReadonlyMap<string, string>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const releaseManifestSchema = z.object({
|
|
27
|
+
version: z.string().min(1),
|
|
28
|
+
packages: z.array(z.object({
|
|
29
|
+
name: z.string().startsWith('@fabrika/'),
|
|
30
|
+
filename: z.string().regex(/^[A-Za-z0-9._-]+\.tgz$/),
|
|
31
|
+
integrity: z.string().startsWith('sha512-'),
|
|
32
|
+
})),
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
const integrityOf = (bytes: Uint8Array): string => `sha512-${createHash('sha512').update(bytes).digest('base64')}`
|
|
36
|
+
|
|
37
|
+
/** The tarball files under `root` named in `filenames`, hashed; the checker's skipped directories are skipped here too. */
|
|
38
|
+
const hashTarballs = async (root: string, filenames: ReadonlySet<string>): Promise<Map<string, string>> => {
|
|
39
|
+
const tarballs = new Map<string, string>()
|
|
40
|
+
const visit = async (relativeDirectory: string): Promise<void> => {
|
|
41
|
+
const entries = await readdir(join(root, relativeDirectory), { withFileTypes: true })
|
|
42
|
+
for (const entry of entries) {
|
|
43
|
+
if (isIgnoredSegment(entry.name)) continue
|
|
44
|
+
const path = relativeDirectory === '' ? entry.name : `${relativeDirectory}/${entry.name}`
|
|
45
|
+
if (entry.isDirectory()) await visit(path)
|
|
46
|
+
else if (entry.isFile() && filenames.has(entry.name)) tarballs.set(path, integrityOf(await readFile(join(root, path))))
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
await visit('')
|
|
50
|
+
return tarballs
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The packed set `manifestText` (a `release-manifest.json`) describes, with the tarballs found under `root`. */
|
|
54
|
+
export const readPackedSet = async (root: string, manifestText: string): Promise<PackedSet> => {
|
|
55
|
+
let json: unknown
|
|
56
|
+
try {
|
|
57
|
+
json = JSON.parse(manifestText)
|
|
58
|
+
} catch {
|
|
59
|
+
throw new Error('the release manifest is not JSON')
|
|
60
|
+
}
|
|
61
|
+
const parsed = releaseManifestSchema.safeParse(json)
|
|
62
|
+
if (!parsed.success) throw new Error('the release manifest does not name each package with its tarball and sha512 integrity')
|
|
63
|
+
const packages = new Map(parsed.data.packages.map(({ name, filename, integrity }) => [name, { filename, integrity }]))
|
|
64
|
+
const tarballs = await hashTarballs(root, new Set([...packages.values()].map((item) => item.filename)))
|
|
65
|
+
return { version: parsed.data.version, packages, tarballs }
|
|
66
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type Finding, reporter } from '../finding'
|
|
2
|
+
import type { Located } from '../graph'
|
|
3
|
+
|
|
4
|
+
/** Every form the reader refuses, as findings of the `contract` rule with where it is and the allowed form. */
|
|
5
|
+
export class ReaderProblems {
|
|
6
|
+
readonly findings: Finding[] = []
|
|
7
|
+
|
|
8
|
+
add(at: Located, message: string, allowed: string): void {
|
|
9
|
+
reporter(at.module.file, this.findings)(at.node, 'contract', message, allowed)
|
|
10
|
+
}
|
|
11
|
+
}
|