@fabrika/check 0.9.0-dev.2 → 0.9.0-dev.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/ast.ts +69 -6
- package/src/check.ts +135 -32
- package/src/cli.ts +23 -4
- package/src/contract.ts +42 -6
- package/src/dialect.ts +29 -0
- package/src/finding.ts +14 -6
- package/src/index.ts +4 -12
- package/src/inputs.ts +4 -2
- package/src/layout.ts +21 -10
- package/src/limits.ts +13 -3
- package/src/migration-base.ts +85 -0
- package/src/reader/schema.ts +42 -512
- package/src/reader/surface.ts +43 -5
- package/src/reader/value.ts +18 -6
- package/src/resolution.ts +2 -2
- package/src/rules/cloudflare.ts +59 -0
- package/src/rules/compile.ts +32 -0
- package/src/rules/framework.ts +2 -2
- package/src/rules/literal.ts +3 -1
- package/src/rules/migration-history.ts +70 -0
- package/src/rules/migrations.ts +248 -9
- package/src/rules/modules.ts +9 -3
- package/src/rules/platform-migrations.ts +100 -0
- package/src/rules/runtime.ts +45 -14
- package/src/rules/structure.ts +32 -15
- package/src/rules/tests.ts +9 -60
- package/src/trust.ts +8 -4
- package/types/src/ast.d.ts +6 -0
- package/types/src/check.d.ts +3 -0
- package/types/src/contract.d.ts +1 -0
- package/types/src/dialect.d.ts +8 -0
- package/types/src/finding.d.ts +6 -5
- package/types/src/index.d.ts +4 -3
- package/types/src/layout.d.ts +18 -9
- package/types/src/limits.d.ts +12 -2
- package/types/src/migration-base.d.ts +9 -0
- package/types/src/reader/schema.d.ts +5 -2
- package/types/src/reader/value.d.ts +2 -2
- package/types/src/rules/cloudflare.d.ts +9 -0
- package/types/src/rules/compile.d.ts +7 -0
- package/types/src/rules/framework.d.ts +1 -1
- package/types/src/rules/migration-history.d.ts +12 -0
- package/types/src/rules/migrations.d.ts +28 -0
- package/types/src/rules/platform-migrations.d.ts +15 -0
- package/types/src/rules/runtime.d.ts +7 -2
- package/types/src/rules/structure.d.ts +8 -3
- package/types/src/rules/tests.d.ts +6 -14
- package/src/endpoint-fixtures.ts +0 -221
- package/src/rules/isolation.ts +0 -79
- package/src/scaffold-sample.ts +0 -111
- package/src/scaffold.ts +0 -650
- package/types/src/endpoint-fixtures.d.ts +0 -36
- package/types/src/rules/isolation.d.ts +0 -18
- package/types/src/scaffold-sample.d.ts +0 -8
- package/types/src/scaffold.d.ts +0 -28
|
@@ -8,8 +8,11 @@ export interface SourceContext {
|
|
|
8
8
|
readonly rawSql: ReadonlySet<string>;
|
|
9
9
|
/** A module under `src/` that is not a test: it reaches no global object and no `Bun` at all. */
|
|
10
10
|
readonly isServerModule: boolean;
|
|
11
|
-
/**
|
|
12
|
-
|
|
11
|
+
/**
|
|
12
|
+
* A `fetch` of an absolute URL, by its static prefix and, for a template whose first label alone is interpolated, its
|
|
13
|
+
* authority with that label as `*`: refused once the contract shows that no site declares its origin in `egress`.
|
|
14
|
+
*/
|
|
15
|
+
readonly absoluteFetch: (node: AstNode, target: string, labelled: string | undefined) => void;
|
|
13
16
|
/** A `ctx.url('<endpoint id>', …)` with a literal id: refused once the contract shows that it names no procedure. */
|
|
14
17
|
readonly appUrl: (node: AstNode, endpoint: string) => void;
|
|
15
18
|
/** A `<table>.insert(values, { onConflict: { columns } })`: refused once the migrations show no unique index of them. */
|
|
@@ -28,5 +31,7 @@ export declare const crossAppFetchMessage: (target: string) => {
|
|
|
28
31
|
};
|
|
29
32
|
/** Whether an expression reaches a prototype: through `.prototype`, `.__proto__` or `Object.getPrototypeOf(…)`. */
|
|
30
33
|
export declare const touchesPrototype: (node: AstNode | undefined) => boolean;
|
|
34
|
+
/** `key-literal` over a string or a template's text: also the one rule of this module a developer's tool is held to. */
|
|
35
|
+
export declare const checkKeyLiteralNode: (node: AstNode, report: Report) => void;
|
|
31
36
|
/** The rules that read one node at a time, for every source file. */
|
|
32
37
|
export declare const checkRuntimeNode: (node: AstNode, ancestors: readonly AstNode[], context: SourceContext) => void;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { type AstNode } from '../ast';
|
|
2
|
-
import { type Report } from '../finding';
|
|
2
|
+
import { type Finding, type Report } from '../finding';
|
|
3
3
|
import type { ModuleReference } from '../references';
|
|
4
4
|
import { type ImportMappings } from '../resolution';
|
|
5
|
-
/** The rules of the application architecture (docs/reference/application-architecture.md):
|
|
6
|
-
export declare const STRUCTURE_RULE_IDS: readonly ["spa-server-import", "layer-import", "
|
|
5
|
+
/** The rules of the application architecture (docs/reference/application-architecture.md): three refusals and the hints. */
|
|
6
|
+
export declare const STRUCTURE_RULE_IDS: readonly ["spa-server-import", "layer-import", "shared-import", "logic-data-access", "cross-slice-queries", "handler-location", "data-access-location"];
|
|
7
7
|
type SlicePart = 'endpoints' | 'logic' | 'queries';
|
|
8
8
|
/** Where a module sits in the architecture, which decides what it may import and call. */
|
|
9
9
|
export interface StructurePlace {
|
|
@@ -20,6 +20,11 @@ export interface StructureGraph {
|
|
|
20
20
|
readonly mappings: ImportMappings;
|
|
21
21
|
readonly referencesOf: (path: string) => readonly ModuleReference[];
|
|
22
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* A `package.json` under `tools/` makes a tool a package, which a workspace or a `file:` dependency lets the application
|
|
25
|
+
* load by its name, past `tool-import`, which judges the files an import resolves to.
|
|
26
|
+
*/
|
|
27
|
+
export declare const checkToolPackages: (paths: readonly string[]) => Finding[];
|
|
23
28
|
/** The architecture's rules over one module's imports, re-exports and loads, as Bun resolves them for that module. */
|
|
24
29
|
export declare const checkStructureReferences: (graph: StructureGraph, place: StructurePlace, report: Report) => void;
|
|
25
30
|
/** A `<x>.<builder>(…).handle(…)` call: the builder's name, its call (whose arguments hold the options) and `.handle`. */
|
|
@@ -1,22 +1,14 @@
|
|
|
1
|
-
import { type AstNode
|
|
1
|
+
import { type AstNode } from '../ast';
|
|
2
2
|
import type { Finding, Report } from '../finding';
|
|
3
3
|
/** For test files: every test runs, and every test asserts. */
|
|
4
4
|
export declare const checkTestNode: (node: AstNode, ancestors: readonly AstNode[], report: Report) => void;
|
|
5
|
-
/** The first line of a test written by `fabrika db test-scaffold`, followed by the SHA-256 of everything after that line. */
|
|
6
|
-
export declare const GENERATED_TEST_HEADER = "// @generated by fabrika db test-scaffold sha256:";
|
|
7
|
-
/** The header `fabrika db test-scaffold` puts on a generated test with this body. */
|
|
8
|
-
export declare const generatedTestHeader: (body: string) => Promise<string>;
|
|
9
|
-
export declare const checkGeneratedTest: (text: string, comments: readonly Comment[], report: Report) => Promise<void>;
|
|
10
5
|
/**
|
|
11
|
-
* The `bunfig.toml` of an application must not narrow its own suite
|
|
12
|
-
*
|
|
13
|
-
* subset is reported by the trust rules.
|
|
6
|
+
* The `bunfig.toml` of an application must not narrow its own suite, which the platform build runs. A file outside the
|
|
7
|
+
* TOML subset is reported by the trust rules.
|
|
14
8
|
*/
|
|
15
9
|
export declare const checkTestSuiteConfig: (text: string) => Finding[];
|
|
16
|
-
/** Whether `path` is a file the scaffold generates: a policy isolation test, the endpoint access test, or one with the header. */
|
|
17
|
-
export declare const isGeneratedTestPath: (path: string, files: ReadonlyMap<string, string>) => boolean;
|
|
18
10
|
/**
|
|
19
|
-
* `mock.module(…)` of the test runner
|
|
20
|
-
*
|
|
11
|
+
* `mock.module(…)` of the test runner or a framework package would let application code replace what the test kit runs
|
|
12
|
+
* on; a computed specifier could name either. Refused anywhere in the application.
|
|
21
13
|
*/
|
|
22
|
-
export declare const checkMockModule: (node: AstNode,
|
|
14
|
+
export declare const checkMockModule: (node: AstNode, report: Report) => void;
|
package/src/endpoint-fixtures.ts
DELETED
|
@@ -1,221 +0,0 @@
|
|
|
1
|
-
// `src/__tests__/endpoint-access.fixtures.ts`: what an application's author gives the endpoint access tests. `fixtures`
|
|
2
|
-
// are the inputs the scaffold cannot sample (a `regex`); `seeds` are the state of the row an endpoint addresses, which
|
|
3
|
-
// its precondition needs (`deals.reopen` reopens only a won deal: `{ stage: 'won' }`); `members` are the input fields
|
|
4
|
-
// that name a member the handler looks up (`deals.assign`'s `ownerId`), which the kit fills with a real member;
|
|
5
|
-
// `invitations` and `links` the fields that name an invitation the handler cancels or a share link it revokes, which the
|
|
6
|
-
// kit fills with one it holds; `rows` the fields that name a row lying in the endpoint's object (a note's comment), by
|
|
7
|
-
// table, which the kit seeds in each scope's object. Read from source, never executed, within the reader's budget:
|
|
8
|
-
// `export const fixtures = { '<endpoint id>': { … } }`, `export const seeds = { '<endpoint id>': { <column>: <value> } }`,
|
|
9
|
-
// `export const members = { '<endpoint id>': ['<field>'] }` (`invitations`, `links` alike) and
|
|
10
|
-
// `export const rows = { '<endpoint id>': { <field>: '<table>' } }`, plain literals only.
|
|
11
|
-
// Browser-safe.
|
|
12
|
-
|
|
13
|
-
import { type AstNode, child, children, identifierName, nodeDepth, parseModule, positionOf, staticKey, staticString } from './ast'
|
|
14
|
-
import type { Finding } from './finding'
|
|
15
|
-
import { ENDPOINT_FIXTURES_FILE } from './layout'
|
|
16
|
-
import { CONTRACT_LIMITS } from './limits'
|
|
17
|
-
import type { Sample } from './scaffold-sample'
|
|
18
|
-
|
|
19
|
-
export const FIXTURES_EXPORT = 'fixtures'
|
|
20
|
-
export const SEEDS_EXPORT = 'seeds'
|
|
21
|
-
export const MEMBERS_EXPORT = 'members'
|
|
22
|
-
export const INVITATIONS_EXPORT = 'invitations'
|
|
23
|
-
export const LINKS_EXPORT = 'links'
|
|
24
|
-
export const ROWS_EXPORT = 'rows'
|
|
25
|
-
|
|
26
|
-
/** The exports that list, by endpoint id, the input fields the kit fills with something it holds. */
|
|
27
|
-
const FIELD_EXPORTS = [MEMBERS_EXPORT, INVITATIONS_EXPORT, LINKS_EXPORT] as const
|
|
28
|
-
type FieldExport = (typeof FIELD_EXPORTS)[number]
|
|
29
|
-
const isFieldExport = (name: string | undefined): name is FieldExport => FIELD_EXPORTS.some((field) => field === name)
|
|
30
|
-
|
|
31
|
-
const ALLOWED =
|
|
32
|
-
"export const fixtures = { 'api.notes.get': { id: '…' } }, export const seeds = { 'api.deals.reopen': { stage: 'won' } }, export const members = { 'api.deals.assign': ['ownerId'] }, export const invitations = { 'api.members.cancel': ['invitationId'] }, export const links = { 'api.notes.unshare': ['linkId'] } and export const rows = { 'api.notes.editComment': { commentId: 'note_comments' } }: string keys, and strings, numbers, booleans, null, arrays and objects"
|
|
33
|
-
|
|
34
|
-
type ById = Readonly<Record<string, Readonly<Record<string, Sample>>>>
|
|
35
|
-
|
|
36
|
-
export interface EndpointFixtures {
|
|
37
|
-
/** The input each endpoint's cases send, by endpoint id. */
|
|
38
|
-
readonly inputs: ById
|
|
39
|
-
/** The columns of the row each endpoint addresses, as both scopes' rows are seeded, by endpoint id. */
|
|
40
|
-
readonly seeds: ById
|
|
41
|
-
/** The input fields that name a member of the endpoint's member directory, by endpoint id. */
|
|
42
|
-
readonly members: Readonly<Record<string, readonly string[]>>
|
|
43
|
-
/** The input fields that name an invitation the endpoint cancels, by endpoint id. */
|
|
44
|
-
readonly invitations: Readonly<Record<string, readonly string[]>>
|
|
45
|
-
/** The input fields that name a share link the endpoint revokes, by endpoint id. */
|
|
46
|
-
readonly links: Readonly<Record<string, readonly string[]>>
|
|
47
|
-
/** The input fields that name a row lying in the endpoint's object, with that row's table, by endpoint id. */
|
|
48
|
-
readonly rows: Readonly<Record<string, Readonly<Record<string, string>>>>
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export const NO_FIXTURES: EndpointFixtures = { inputs: {}, seeds: {}, members: {}, invitations: {}, links: {}, rows: {} }
|
|
52
|
-
|
|
53
|
-
const finding = (at: AstNode | undefined, message: string): Finding => {
|
|
54
|
-
const { line, column } = at === undefined ? { line: 1, column: 1 } : positionOf(at)
|
|
55
|
-
return { file: ENDPOINT_FIXTURES_FILE, line, column, severity: 'refusal', rule: 'endpoint-fixture', message, allowed: ALLOWED }
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export function isSampleObject(value: Sample): value is { readonly [key: string]: Sample } {
|
|
59
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/** A plain literal value, or the node that is not one. */
|
|
63
|
-
function literal(
|
|
64
|
-
node: AstNode | undefined,
|
|
65
|
-
): { readonly ok: true; readonly value: Sample } | { readonly ok: false; readonly at: AstNode | undefined } {
|
|
66
|
-
if (node === undefined) return { ok: false, at: node }
|
|
67
|
-
if (node.type === 'Literal') {
|
|
68
|
-
const value = node['value']
|
|
69
|
-
if (value === null || typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))) {
|
|
70
|
-
return { ok: true, value }
|
|
71
|
-
}
|
|
72
|
-
return { ok: false, at: node }
|
|
73
|
-
}
|
|
74
|
-
if (node.type === 'TemplateLiteral') {
|
|
75
|
-
const text = staticString(node)
|
|
76
|
-
return text === undefined ? { ok: false, at: node } : { ok: true, value: text }
|
|
77
|
-
}
|
|
78
|
-
if (node.type === 'UnaryExpression' && node['operator'] === '-') {
|
|
79
|
-
const inner = literal(child(node, 'argument'))
|
|
80
|
-
return inner.ok && typeof inner.value === 'number' ? { ok: true, value: -inner.value } : { ok: false, at: node }
|
|
81
|
-
}
|
|
82
|
-
if (node.type === 'ArrayExpression') {
|
|
83
|
-
const items: Sample[] = []
|
|
84
|
-
for (const element of children(node, 'elements')) {
|
|
85
|
-
const item = literal(element ?? undefined)
|
|
86
|
-
if (!item.ok) return item
|
|
87
|
-
items.push(item.value)
|
|
88
|
-
}
|
|
89
|
-
return { ok: true, value: items }
|
|
90
|
-
}
|
|
91
|
-
if (node.type === 'ObjectExpression') {
|
|
92
|
-
const entries: [string, Sample][] = []
|
|
93
|
-
for (const property of children(node, 'properties')) {
|
|
94
|
-
if (property?.type !== 'Property' || property['computed'] === true || property['method'] === true) return { ok: false, at: property ?? node }
|
|
95
|
-
const key = staticKey(property, 'key')
|
|
96
|
-
if (key === undefined || key === '__proto__') return { ok: false, at: property }
|
|
97
|
-
const value = literal(child(property, 'value'))
|
|
98
|
-
if (!value.ok) return value
|
|
99
|
-
entries.push([key, value.value])
|
|
100
|
-
}
|
|
101
|
-
return { ok: true, value: Object.fromEntries(entries) }
|
|
102
|
-
}
|
|
103
|
-
return { ok: false, at: node }
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/** One `export const <name> = { '<endpoint id>': { … } }`, read into an object of objects. */
|
|
107
|
-
function byId(
|
|
108
|
-
declarator: AstNode,
|
|
109
|
-
name: string,
|
|
110
|
-
): { readonly ok: true; readonly value: ById } | { readonly ok: false; readonly findings: readonly Finding[] } {
|
|
111
|
-
const init = child(declarator, 'init')
|
|
112
|
-
const value = literal(init)
|
|
113
|
-
if (!value.ok) return { ok: false, findings: [finding(value.at, 'not a plain literal')] }
|
|
114
|
-
const all = value.value
|
|
115
|
-
if (!isSampleObject(all)) {
|
|
116
|
-
return { ok: false, findings: [finding(init, `the ${name} are an object keyed by endpoint id`)] }
|
|
117
|
-
}
|
|
118
|
-
const entries: Record<string, Readonly<Record<string, Sample>>> = {}
|
|
119
|
-
for (const [id, entry] of Object.entries(all)) {
|
|
120
|
-
if (!isSampleObject(entry)) {
|
|
121
|
-
return { ok: false, findings: [finding(init, `the ${name} of ${id} is not an object of ${name === SEEDS_EXPORT ? 'columns' : 'input fields'}`)] }
|
|
122
|
-
}
|
|
123
|
-
entries[id] = entry
|
|
124
|
-
}
|
|
125
|
-
return { ok: true, value: entries }
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/** `export const <members, invitations or links> = { '<endpoint id>': ['<field>', …] }`, read into field lists. */
|
|
129
|
-
function fieldsById(
|
|
130
|
-
declarator: AstNode,
|
|
131
|
-
name: FieldExport,
|
|
132
|
-
): { readonly ok: true; readonly value: Readonly<Record<string, readonly string[]>> } | {
|
|
133
|
-
readonly ok: false
|
|
134
|
-
readonly findings: readonly Finding[]
|
|
135
|
-
} {
|
|
136
|
-
const init = child(declarator, 'init')
|
|
137
|
-
const value = literal(init)
|
|
138
|
-
if (!value.ok) return { ok: false, findings: [finding(value.at, 'not a plain literal')] }
|
|
139
|
-
if (!isSampleObject(value.value)) {
|
|
140
|
-
return { ok: false, findings: [finding(init, `the ${name} are an object keyed by endpoint id`)] }
|
|
141
|
-
}
|
|
142
|
-
const entries: Record<string, readonly string[]> = {}
|
|
143
|
-
for (const [id, fields] of Object.entries(value.value)) {
|
|
144
|
-
if (!Array.isArray(fields) || fields.length === 0 || !fields.every((field) => typeof field === 'string')) {
|
|
145
|
-
return { ok: false, findings: [finding(init, `the ${name} of ${id} is not a list of input field names`)] }
|
|
146
|
-
}
|
|
147
|
-
entries[id] = fields.filter((field) => typeof field === 'string')
|
|
148
|
-
}
|
|
149
|
-
return { ok: true, value: entries }
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** The fixtures of `files`, by endpoint id; none without the file. */
|
|
153
|
-
export function readEndpointFixtures(
|
|
154
|
-
files: ReadonlyMap<string, string>,
|
|
155
|
-
): { readonly ok: true; readonly fixtures: EndpointFixtures } | { readonly ok: false; readonly findings: readonly Finding[] } {
|
|
156
|
-
const text = files.get(ENDPOINT_FIXTURES_FILE)
|
|
157
|
-
if (text === undefined) return { ok: true, fixtures: NO_FIXTURES }
|
|
158
|
-
if (new TextEncoder().encode(text).byteLength > CONTRACT_LIMITS.sourceBytes) {
|
|
159
|
-
return { ok: false, findings: [finding(undefined, `the fixtures exceed ${CONTRACT_LIMITS.sourceBytes} bytes`)] }
|
|
160
|
-
}
|
|
161
|
-
const parsed = parseModule(ENDPOINT_FIXTURES_FILE, text)
|
|
162
|
-
if (!parsed.ok) return { ok: false, findings: [finding(undefined, parsed.message)] }
|
|
163
|
-
const program = parsed.module.program
|
|
164
|
-
if (nodeDepth(program) > CONTRACT_LIMITS.astDepth) {
|
|
165
|
-
return { ok: false, findings: [finding(undefined, `the fixtures nest deeper than ${CONTRACT_LIMITS.astDepth}`)] }
|
|
166
|
-
}
|
|
167
|
-
const read = new Map<string, ById>()
|
|
168
|
-
const fields = new Map<FieldExport, Readonly<Record<string, readonly string[]>>>()
|
|
169
|
-
for (const statement of children(program, 'body')) {
|
|
170
|
-
const declaration = statement === null ? undefined : child(statement, 'declaration')
|
|
171
|
-
const declarators = declaration?.type === 'VariableDeclaration' && declaration['kind'] === 'const' ? children(declaration, 'declarations') : []
|
|
172
|
-
const declarator = declarators.length === 1 ? declarators[0] : undefined
|
|
173
|
-
const name = declarator === null || declarator === undefined ? undefined : identifierName(child(declarator, 'id'))
|
|
174
|
-
if (
|
|
175
|
-
statement?.type !== 'ExportNamedDeclaration' || declarator === null || declarator === undefined
|
|
176
|
-
|| (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && !isFieldExport(name)) || read.has(name)
|
|
177
|
-
|| (isFieldExport(name) && fields.has(name))
|
|
178
|
-
) {
|
|
179
|
-
return {
|
|
180
|
-
ok: false,
|
|
181
|
-
findings: [
|
|
182
|
-
finding(
|
|
183
|
-
statement ?? undefined,
|
|
184
|
-
`the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT} and ${LINKS_EXPORT} = { … }, each at most once`,
|
|
185
|
-
),
|
|
186
|
-
],
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
if (isFieldExport(name)) {
|
|
190
|
-
const listed = fieldsById(declarator, name)
|
|
191
|
-
if (!listed.ok) return listed
|
|
192
|
-
fields.set(name, listed.value)
|
|
193
|
-
continue
|
|
194
|
-
}
|
|
195
|
-
const value = byId(declarator, name)
|
|
196
|
-
if (!value.ok) return value
|
|
197
|
-
if (name === ROWS_EXPORT) {
|
|
198
|
-
const named = Object.entries(value.value).find(([, fields]) => Object.values(fields).some((table) => typeof table !== 'string'))
|
|
199
|
-
if (named !== undefined) {
|
|
200
|
-
return { ok: false, findings: [finding(child(declarator, 'init'), `the rows of ${named[0]} name each field's table as a string`)] }
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
read.set(name, value.value)
|
|
204
|
-
}
|
|
205
|
-
return {
|
|
206
|
-
ok: true,
|
|
207
|
-
fixtures: {
|
|
208
|
-
inputs: read.get(FIXTURES_EXPORT) ?? {},
|
|
209
|
-
seeds: read.get(SEEDS_EXPORT) ?? {},
|
|
210
|
-
members: fields.get(MEMBERS_EXPORT) ?? {},
|
|
211
|
-
invitations: fields.get(INVITATIONS_EXPORT) ?? {},
|
|
212
|
-
links: fields.get(LINKS_EXPORT) ?? {},
|
|
213
|
-
rows: Object.fromEntries(
|
|
214
|
-
Object.entries(read.get(ROWS_EXPORT) ?? {}).map(([id, named]) => [
|
|
215
|
-
id,
|
|
216
|
-
Object.fromEntries(Object.entries(named).flatMap(([field, table]) => (typeof table === 'string' ? [[field, table]] : []))),
|
|
217
|
-
]),
|
|
218
|
-
),
|
|
219
|
-
},
|
|
220
|
-
}
|
|
221
|
-
}
|
package/src/rules/isolation.ts
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
import { ContractError } from '@fabrika/app/contract'
|
|
2
|
-
import { ContractSourceError } from '../contract'
|
|
3
|
-
import type { Finding } from '../finding'
|
|
4
|
-
import { CONTRACT_FILE } from '../layout'
|
|
5
|
-
import { type GeneratedTest, generatedTests, missingEndpointFixtures, scaffoldInputs } from '../scaffold'
|
|
6
|
-
import { GENERATED_TEST_HEADER, generatedTestHeader } from './tests'
|
|
7
|
-
|
|
8
|
-
const RESCAFFOLD = 'the files fabrika db test-scaffold writes for the current contract and src/db/tables.ts; run it and commit the result'
|
|
9
|
-
|
|
10
|
-
const at = (file: string, message: string): Finding => ({
|
|
11
|
-
file,
|
|
12
|
-
line: 1,
|
|
13
|
-
column: 1,
|
|
14
|
-
severity: 'refusal',
|
|
15
|
-
rule: 'generated-test-hash',
|
|
16
|
-
message,
|
|
17
|
-
allowed: RESCAFFOLD,
|
|
18
|
-
})
|
|
19
|
-
|
|
20
|
-
/** Whether the first line is a generated-test header whose hash fails: `checkGeneratedTest` reports that file already. */
|
|
21
|
-
const failsItsHash = async (text: string): Promise<boolean> => {
|
|
22
|
-
if (!text.startsWith(GENERATED_TEST_HEADER)) return false
|
|
23
|
-
const newline = text.indexOf('\n')
|
|
24
|
-
return newline === -1 || text.slice(0, newline) !== (await generatedTestHeader(text.slice(newline + 1)))
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/** The tests the scaffold writes for these files, or the findings that stop it from reading them. */
|
|
28
|
-
export const expectedGeneratedTests = async (
|
|
29
|
-
files: ReadonlyMap<string, string>,
|
|
30
|
-
): Promise<
|
|
31
|
-
| { readonly ok: true; readonly tests: ReadonlyMap<string, GeneratedTest>; readonly missing: readonly Finding[] }
|
|
32
|
-
| { readonly ok: false; readonly findings: readonly Finding[] }
|
|
33
|
-
> => {
|
|
34
|
-
try {
|
|
35
|
-
const inputs = scaffoldInputs(files)
|
|
36
|
-
return { ok: true, tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures), missing: missingEndpointFixtures(inputs) }
|
|
37
|
-
} catch (error) {
|
|
38
|
-
if (error instanceof ContractSourceError) return { ok: false, findings: error.findings }
|
|
39
|
-
if (error instanceof ContractError) {
|
|
40
|
-
return {
|
|
41
|
-
ok: false,
|
|
42
|
-
findings: error.problems.map((problem): Finding => ({
|
|
43
|
-
file: CONTRACT_FILE,
|
|
44
|
-
line: 1,
|
|
45
|
-
column: 1,
|
|
46
|
-
severity: 'refusal',
|
|
47
|
-
rule: 'contract',
|
|
48
|
-
message: problem,
|
|
49
|
-
allowed: 'a contract that compiles against src/db/tables.ts',
|
|
50
|
-
})),
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
throw error
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Every generated test is byte for byte what the scaffold writes from the current contract and policies: a missing,
|
|
59
|
-
* edited or replaced one is a finding, header or not, and so is a generated test the scaffold no longer writes.
|
|
60
|
-
* `readable` is false while the literal or trust rules report the sources; otherwise what the reader refuses is
|
|
61
|
-
* reported here, so a source it cannot read does not silence the check.
|
|
62
|
-
*/
|
|
63
|
-
export const checkGeneratedTests = async (files: ReadonlyMap<string, string>, readable: boolean): Promise<Finding[]> => {
|
|
64
|
-
if (!readable) return []
|
|
65
|
-
const expected = await expectedGeneratedTests(files)
|
|
66
|
-
if (!expected.ok) return [...expected.findings]
|
|
67
|
-
const findings: Finding[] = [...expected.missing]
|
|
68
|
-
for (const [path, { text }] of expected.tests) {
|
|
69
|
-
const present = files.get(path)
|
|
70
|
-
if (present === undefined) findings.push(at(path, 'this generated test is missing'))
|
|
71
|
-
else if (present !== text && !(await failsItsHash(present))) findings.push(at(path, 'this file is not the generated test the scaffold writes here'))
|
|
72
|
-
}
|
|
73
|
-
for (const [path, text] of files) {
|
|
74
|
-
if (text.startsWith(GENERATED_TEST_HEADER) && !expected.tests.has(path)) {
|
|
75
|
-
findings.push(at(path, 'a generated test the scaffold no longer writes'))
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
return findings
|
|
79
|
-
}
|
package/src/scaffold-sample.ts
DELETED
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
// A fixed input that a schema shape admits, written into a generated test as a literal. Deterministic, so the checker
|
|
2
|
-
// regenerates the same text; `undefined` when the scaffold cannot build one (a pattern, contradictory bounds).
|
|
3
|
-
|
|
4
|
-
import { GENERATED_FILE_PREFIX } from '@fabrika/app/contract'
|
|
5
|
-
import type { NumberShape, SchemaShape, StringShape } from '@fabrika/auth-core'
|
|
6
|
-
|
|
7
|
-
export type Sample = null | boolean | number | string | readonly Sample[] | { readonly [key: string]: Sample }
|
|
8
|
-
|
|
9
|
-
/** What a shape contributes to its object: a value, nothing (an optional field), or no sample at all. */
|
|
10
|
-
type Field = { readonly kind: 'value'; readonly value: Sample } | { readonly kind: 'omit' } | undefined
|
|
11
|
-
|
|
12
|
-
const FORMATS: Readonly<Record<NonNullable<StringShape['format']>, string>> = {
|
|
13
|
-
uuid: '00000000-0000-4000-8000-000000000000',
|
|
14
|
-
email: 'sample@example.test',
|
|
15
|
-
url: 'https://example.test/',
|
|
16
|
-
datetime: '2026-01-01T00:00:00.000Z',
|
|
17
|
-
date: '2026-01-01',
|
|
18
|
-
time: '12:00:00',
|
|
19
|
-
duration: 'PT1H',
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function sampleString(shape: StringShape): string | undefined {
|
|
23
|
-
if (shape.pattern !== null) return undefined
|
|
24
|
-
if (shape.format !== null) return FORMATS[shape.format]
|
|
25
|
-
let value = `${shape.startsWith ?? ''}${shape.includes ?? ''}${shape.endsWith ?? ''}`
|
|
26
|
-
const least = Math.max(shape.minLength ?? 1, 1)
|
|
27
|
-
if (value.length < least) {
|
|
28
|
-
value = `${shape.startsWith ?? ''}${shape.includes ?? ''}${'x'.repeat(least - value.length)}${shape.endsWith ?? ''}`
|
|
29
|
-
}
|
|
30
|
-
return shape.maxLength !== null && value.length > shape.maxLength ? undefined : value
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function admits(shape: NumberShape, value: number): boolean {
|
|
34
|
-
if (shape.int && !Number.isInteger(value)) return false
|
|
35
|
-
if (shape.min !== null && (shape.exclusiveMin ? value <= shape.min : value < shape.min)) return false
|
|
36
|
-
if (shape.max !== null && (shape.exclusiveMax ? value >= shape.max : value > shape.max)) return false
|
|
37
|
-
return shape.multipleOf === null || Number.isInteger(value / shape.multipleOf)
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function sampleNumber(shape: NumberShape): number | undefined {
|
|
41
|
-
const step = shape.multipleOf ?? 1
|
|
42
|
-
const start = shape.min ?? (shape.max === null ? 1 : Math.min(1, shape.max))
|
|
43
|
-
const first = Math.ceil(start / step) * step
|
|
44
|
-
return [first, first + step].find((candidate) => admits(shape, candidate))
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
function field(shape: SchemaShape): Field {
|
|
48
|
-
if (shape.type === 'optional') return { kind: 'omit' }
|
|
49
|
-
const value = sample(shape)
|
|
50
|
-
return value === undefined ? undefined : { kind: 'value', value }
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/** A value `shape` admits, or `undefined`. */
|
|
54
|
-
export function sample(shape: SchemaShape): Sample | undefined {
|
|
55
|
-
switch (shape.type) {
|
|
56
|
-
case 'string':
|
|
57
|
-
return sampleString(shape)
|
|
58
|
-
case 'number':
|
|
59
|
-
return sampleNumber(shape)
|
|
60
|
-
case 'boolean':
|
|
61
|
-
return false
|
|
62
|
-
case 'null':
|
|
63
|
-
return null
|
|
64
|
-
case 'literal':
|
|
65
|
-
return shape.value
|
|
66
|
-
case 'enum':
|
|
67
|
-
return shape.values[0]
|
|
68
|
-
case 'optional':
|
|
69
|
-
return sample(shape.inner)
|
|
70
|
-
case 'nullable':
|
|
71
|
-
return null
|
|
72
|
-
case 'union':
|
|
73
|
-
return shape.options.map(sample).find((value) => value !== undefined)
|
|
74
|
-
case 'record':
|
|
75
|
-
return {}
|
|
76
|
-
case 'array': {
|
|
77
|
-
const count = shape.minItems ?? 0
|
|
78
|
-
const item = count === 0 ? null : sample(shape.items)
|
|
79
|
-
return item === undefined ? undefined : Array.from({ length: count }, () => item)
|
|
80
|
-
}
|
|
81
|
-
case 'tuple': {
|
|
82
|
-
const items = shape.items.map(sample)
|
|
83
|
-
return items.every((item) => item !== undefined) ? items.filter((item) => item !== undefined) : undefined
|
|
84
|
-
}
|
|
85
|
-
case 'file':
|
|
86
|
-
return `${GENERATED_FILE_PREFIX}${shape.kind}`
|
|
87
|
-
case 'object': {
|
|
88
|
-
const entries: [string, Sample][] = []
|
|
89
|
-
for (const [name, inner] of Object.entries(shape.fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
|
|
90
|
-
const result = field(inner)
|
|
91
|
-
if (result === undefined) return undefined
|
|
92
|
-
if (result.kind === 'value') entries.push([name, result.value])
|
|
93
|
-
}
|
|
94
|
-
return Object.fromEntries(entries)
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/
|
|
100
|
-
|
|
101
|
-
const quote = (text: string): string => `'${text.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`
|
|
102
|
-
|
|
103
|
-
/** The literal as dprint writes it: single quotes, bare keys where they are identifiers. */
|
|
104
|
-
export function renderSample(value: Sample): string {
|
|
105
|
-
if (value === null || typeof value === 'boolean' || typeof value === 'number') return String(value)
|
|
106
|
-
if (typeof value === 'string') return quote(value)
|
|
107
|
-
if (Array.isArray(value)) return `[${value.map(renderSample).join(', ')}]`
|
|
108
|
-
const entries = Object.entries(value)
|
|
109
|
-
if (entries.length === 0) return '{}'
|
|
110
|
-
return `{ ${entries.map(([key, item]) => `${IDENTIFIER.test(key) ? key : quote(key)}: ${renderSample(item)}`).join(', ')} }`
|
|
111
|
-
}
|