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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/package.json +12 -7
  2. package/src/ast.ts +69 -18
  3. package/src/bun-plugin.ts +4 -27
  4. package/src/check.ts +157 -44
  5. package/src/cli.ts +34 -8
  6. package/src/contract.ts +68 -11
  7. package/src/dialect.ts +29 -0
  8. package/src/finding.ts +21 -8
  9. package/src/graph.ts +49 -12
  10. package/src/index.ts +4 -12
  11. package/src/inputs.ts +5 -2
  12. package/src/layout.ts +41 -12
  13. package/src/limits.ts +15 -5
  14. package/src/migration-base.ts +85 -0
  15. package/src/reader/schema.ts +42 -512
  16. package/src/reader/surface.ts +48 -7
  17. package/src/reader/value.ts +41 -8
  18. package/src/references.ts +16 -1
  19. package/src/resolution.ts +2 -2
  20. package/src/rules/cloudflare.ts +59 -0
  21. package/src/rules/compile.ts +32 -0
  22. package/src/rules/contract.ts +3 -2
  23. package/src/rules/framework.ts +2 -2
  24. package/src/rules/identity.ts +6 -9
  25. package/src/rules/literal.ts +42 -9
  26. package/src/rules/migration-history.ts +70 -0
  27. package/src/rules/migrations.ts +248 -9
  28. package/src/rules/modules.ts +9 -3
  29. package/src/rules/platform-migrations.ts +100 -0
  30. package/src/rules/runtime.ts +45 -14
  31. package/src/rules/structure.ts +172 -19
  32. package/src/rules/tests.ts +9 -60
  33. package/src/rules/types.ts +17 -16
  34. package/src/shell-modules.ts +53 -0
  35. package/src/slice.ts +6 -5
  36. package/src/source-maps.ts +2 -0
  37. package/src/trust.ts +8 -4
  38. package/src/vite-plugin.ts +65 -0
  39. package/types/src/ast.d.ts +6 -2
  40. package/types/src/check.d.ts +3 -0
  41. package/types/src/contract.d.ts +13 -1
  42. package/types/src/dialect.d.ts +8 -0
  43. package/types/src/finding.d.ts +7 -6
  44. package/types/src/graph.d.ts +12 -2
  45. package/types/src/index.d.ts +4 -3
  46. package/types/src/layout.d.ts +25 -10
  47. package/types/src/limits.d.ts +14 -4
  48. package/types/src/migration-base.d.ts +9 -0
  49. package/types/src/reader/schema.d.ts +5 -2
  50. package/types/src/reader/value.d.ts +3 -3
  51. package/types/src/references.d.ts +6 -1
  52. package/types/src/rules/cloudflare.d.ts +9 -0
  53. package/types/src/rules/compile.d.ts +7 -0
  54. package/types/src/rules/framework.d.ts +1 -1
  55. package/types/src/rules/literal.d.ts +1 -1
  56. package/types/src/rules/migration-history.d.ts +12 -0
  57. package/types/src/rules/migrations.d.ts +28 -0
  58. package/types/src/rules/platform-migrations.d.ts +15 -0
  59. package/types/src/rules/runtime.d.ts +7 -2
  60. package/types/src/rules/structure.d.ts +18 -4
  61. package/types/src/rules/tests.d.ts +6 -14
  62. package/types/src/rules/types.d.ts +2 -0
  63. package/types/src/shell-modules.d.ts +7 -0
  64. package/types/src/slice.d.ts +8 -2
  65. package/types/src/vite-plugin.d.ts +27 -0
  66. package/src/endpoint-fixtures.ts +0 -221
  67. package/src/rules/crontab.ts +0 -147
  68. package/src/rules/isolation.ts +0 -79
  69. package/src/scaffold-sample.ts +0 -111
  70. package/src/scaffold.ts +0 -650
  71. package/types/src/endpoint-fixtures.d.ts +0 -36
  72. package/types/src/rules/crontab.d.ts +0 -15
  73. package/types/src/rules/isolation.d.ts +0 -18
  74. package/types/src/scaffold-sample.d.ts +0 -8
  75. package/types/src/scaffold.d.ts +0 -28
@@ -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
- }
@@ -1,147 +0,0 @@
1
- import { z } from 'zod/v4'
2
- import { type AstNode, child, children, type ParsedModule, staticKey, walk } from '../ast'
3
- import type { Finding } from '../finding'
4
- import { type Located, type ModuleGraph, unwrapValue } from '../graph'
5
-
6
- export interface ContractJob {
7
- readonly name: string
8
- /** `undefined` when the contract's schedule is not a static string. */
9
- readonly schedule: string | undefined
10
- }
11
-
12
- /**
13
- * Every `<name>: c.cron('<schedule>', { … })` in the contract, and every `<name>` there that names a const of the
14
- * kit's `app.cron('<schedule>', { … })`; the schedule is resolved through literal consts.
15
- */
16
- export const contractJobs = (contract: ParsedModule, graph: ModuleGraph): readonly ContractJob[] => {
17
- const jobs: ContractJob[] = []
18
- const cronSchedule = (located: Located): string | undefined => {
19
- const first = children(located.node, 'arguments')[0]
20
- return first ? graph.resolveString({ module: located.module, node: first }) : undefined
21
- }
22
- walk(contract.program, (node, ancestors) => {
23
- if (node.type === 'Property') {
24
- const value = child(node, 'value')
25
- const name = staticKey(node, 'key')
26
- const resolved = value !== undefined && unwrapValue(value).type === 'Identifier'
27
- ? graph.resolveValue({ module: contract, node: value })
28
- : undefined
29
- if (name !== undefined && resolved !== undefined && isCronCall(resolved.node)) jobs.push({ name, schedule: cronSchedule(resolved) })
30
- return
31
- }
32
- if (!isCronCall(node)) return
33
- const property = [...ancestors].reverse().find((ancestor) => {
34
- const value = ancestor.type === 'Property' ? child(ancestor, 'value') : undefined
35
- return value !== undefined && unwrapValue(value) === node
36
- })
37
- const name = property === undefined ? undefined : staticKey(property, 'key')
38
- if (name !== undefined) jobs.push({ name, schedule: cronSchedule({ module: contract, node }) })
39
- })
40
- return jobs
41
- }
42
-
43
- const isCronCall = (node: AstNode): boolean => {
44
- const callee = node.type === 'CallExpression' ? child(node, 'callee') : undefined
45
- return callee?.type === 'MemberExpression' && staticKey(callee, 'property') === 'cron'
46
- }
47
-
48
- const crontabEntrySchema = z.object({
49
- timing: z.string().optional(),
50
- command: z.string().optional(),
51
- allContainers: z.boolean().optional(),
52
- })
53
-
54
- const zeropsYamlSchema = z.object({
55
- zerops: z.array(
56
- z.object({
57
- setup: z.string(),
58
- run: z.object({ start: z.string().optional(), crontab: z.array(crontabEntrySchema).optional() }).optional(),
59
- }),
60
- ),
61
- })
62
-
63
- const JOB_COMMAND = /^fabrika job run (\S+)$/
64
- /** A lone `&`, `nohup`, `setsid` or `disown` starts a process beside the server, outside every job rule. */
65
- const BACKGROUND_PROCESS = /(?:^|[^&])&(?:[^&]|$)|\b(?:nohup|setsid|disown)\b/
66
-
67
- /** The line of the first occurrence of `needle`, or 1. */
68
- const lineOf = (text: string, needle: string, after = 0): number => {
69
- const index = text.indexOf(needle, after)
70
- return index === -1 ? 1 : text.slice(0, index).split('\n').length
71
- }
72
-
73
- /** Each setup that runs the application carries exactly the contract's jobs as crontab entries, and nothing else. */
74
- export const checkCrontab = (file: string, text: string, jobs: readonly ContractJob[]): Finding[] => {
75
- const findings: Finding[] = []
76
- const finding = (line: number, message: string, allowed: string) =>
77
- findings.push({ file, line, column: 1, severity: 'refusal', rule: 'crontab', message, allowed })
78
- let document: unknown
79
- try {
80
- document = Bun.YAML.parse(text)
81
- } catch {
82
- finding(1, `${file} is not valid YAML`, 'a zerops.yaml that parses')
83
- return findings
84
- }
85
- const parsed = zeropsYamlSchema.safeParse(document)
86
- if (!parsed.success) {
87
- const issue = parsed.error.issues[0]
88
- finding(
89
- 1,
90
- `${file} does not have the zerops.yaml shape at '${issue?.path.join('.') ?? ''}'`,
91
- 'zerops: [{ setup, run: { start, crontab: [{ timing, command, allContainers }] } }]',
92
- )
93
- return findings
94
- }
95
- const byName = new Map(jobs.map((job) => [job.name, job]))
96
- for (const setup of parsed.data.zerops) {
97
- const { run } = setup
98
- if (run === undefined) continue
99
- const setupLine = lineOf(text, `setup: ${setup.setup}`)
100
- const crontabLine = lineOf(text, 'crontab:', text.indexOf(`setup: ${setup.setup}`))
101
- if (run.start !== undefined && BACKGROUND_PROCESS.test(run.start)) {
102
- finding(
103
- lineOf(text, run.start),
104
- `run.start of '${setup.setup}' starts a background process`,
105
- 'one server process in run.start; background work is a job in the contract (c.cron)',
106
- )
107
- }
108
- const scheduled = new Set<string>()
109
- for (const entry of run.crontab ?? []) {
110
- const line = entry.command === undefined ? crontabLine : lineOf(text, entry.command)
111
- const name = JOB_COMMAND.exec(entry.command ?? '')?.[1]
112
- const job = name === undefined ? undefined : byName.get(name)
113
- if (job === undefined) {
114
- finding(
115
- line,
116
- `crontab entry '${entry.command ?? ''}' is not a job of the contract`,
117
- 'fabrika job run <name> for a c.cron job declared in fabrika.contract.ts',
118
- )
119
- continue
120
- }
121
- if (scheduled.has(job.name)) finding(line, `job '${job.name}' has a second crontab entry`, 'one crontab entry per job')
122
- scheduled.add(job.name)
123
- if (job.schedule === undefined) {
124
- finding(line, `the contract's schedule of job '${job.name}' is not a static string`, `c.cron('<cron expression>', { … }) in fabrika.contract.ts`)
125
- } else if (entry.timing !== job.schedule) {
126
- finding(
127
- line,
128
- `crontab timing '${entry.timing ?? ''}' of job '${job.name}' differs from the contract's '${job.schedule}'`,
129
- `timing: '${job.schedule}'`,
130
- )
131
- }
132
- if (entry.allContainers !== false) {
133
- finding(line, `crontab entry of job '${job.name}' does not set allContainers: false`, 'allContainers: false, written explicitly')
134
- }
135
- }
136
- for (const job of jobs) {
137
- if (!scheduled.has(job.name)) {
138
- finding(
139
- run.crontab === undefined ? setupLine : crontabLine,
140
- `job '${job.name}' has no crontab entry in '${setup.setup}'`,
141
- `{ timing: '${job.schedule ?? ''}', command: 'fabrika job run ${job.name}', allContainers: false }`,
142
- )
143
- }
144
- }
145
- }
146
- return findings
147
- }
@@ -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
- }
@@ -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
- }