@fabrika/check 0.9.0-dev.17 → 0.9.0-dev.19

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.
@@ -1,316 +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; `appRows` the rows of application tables an endpoint's own case
8
- // reads (the guide a link holder downloads), by table, with their columns, which the kit seeds before each leak or own
9
- // case asks and removes once it is over; `files` the file of the repository each generated case sends in a file field
10
- // (a package a handler inspects), by input field, relative to the application's root; `refusals` the error types of the
11
- // 400s an endpoint's handler answers its own object with when no fixture can meet its domain rule, which the kit then
12
- // counts as the handler's answer; `pins` known values of text columns of the row an endpoint addresses (a skill's slug a
13
- // package must name), the own scope's, which the kit writes there instead of a marker; `callerRows` the rows of
14
- // application tables the caller of every global case holds (a person's card bound to the account), by table, a column
15
- // valued `fabrika:caller` getting the caller's id, which the kit seeds before each global case asks.
16
- // Read from source, never executed, within the reader's budget: `export const fixtures = { '<endpoint id>': { … } }`,
17
- // `export const seeds = { '<endpoint id>': { <column>: <value> } }`, `export const members = { '<endpoint id>':
18
- // ['<field>'] }` (`invitations`, `links` alike), `export const rows = { '<endpoint id>': { <field>: '<table>' } }` and
19
- // `export const appRows = { '<endpoint id>': { <table>: { <column>: <value> } } }`, `export const files = { '<endpoint
20
- // id>': { <field>: '<path>' } }`, `export const refusals = { '<endpoint id>': ['<error type>'] }` and `export const pins
21
- // = { '<endpoint id>': { <column>: '<value>' } }`, and `export const callerRows = { <table>: { <column>: <value> } }`,
22
- // plain literals only.
23
- // Browser-safe.
24
-
25
- import { type AstNode, child, children, identifierName, nodeDepth, parseModule, positionOf, staticKey, staticString } from './ast'
26
- import type { Finding } from './finding'
27
- import { ENDPOINT_FIXTURES_FILE } from './layout'
28
- import { CONTRACT_LIMITS } from './limits'
29
- import type { Sample } from './scaffold-sample'
30
-
31
- export const FIXTURES_EXPORT = 'fixtures'
32
- export const SEEDS_EXPORT = 'seeds'
33
- export const MEMBERS_EXPORT = 'members'
34
- export const INVITATIONS_EXPORT = 'invitations'
35
- export const LINKS_EXPORT = 'links'
36
- export const ROWS_EXPORT = 'rows'
37
- export const APP_ROWS_EXPORT = 'appRows'
38
- export const FILES_EXPORT = 'files'
39
- export const REFUSALS_EXPORT = 'refusals'
40
- export const PINS_EXPORT = 'pins'
41
- export const CALLER_ROWS_EXPORT = 'callerRows'
42
-
43
- /** The exports that list strings by endpoint id: the input fields the kit fills with something it holds, and the refusals. */
44
- const FIELD_EXPORTS = [MEMBERS_EXPORT, INVITATIONS_EXPORT, LINKS_EXPORT, REFUSALS_EXPORT] as const
45
- type FieldExport = (typeof FIELD_EXPORTS)[number]
46
- const isFieldExport = (name: string | undefined): name is FieldExport => FIELD_EXPORTS.some((field) => field === name)
47
-
48
- const ALLOWED =
49
- "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'] }, export const rows = { 'api.notes.editComment': { commentId: 'note_comments' } }, export const appRows = { 'portal.guide': { guides: { active: true } } }, export const files = { 'api.skills.publish': { package: 'src/__tests__/fixtures/skill.zip' } }, export const refusals = { 'api.skills.publish': ['skill_frontmatter'] } and export const pins = { 'api.skills.publish': { slug: 'sample-skill' } } and export const callerRows = { people: { principal_id: 'fabrika:caller' } }: string keys, and strings, numbers, booleans, null, arrays and objects"
50
-
51
- type ById = Readonly<Record<string, Readonly<Record<string, Sample>>>>
52
-
53
- export interface EndpointFixtures {
54
- /** The input each endpoint's cases send, by endpoint id. */
55
- readonly inputs: ById
56
- /** The columns of the row each endpoint addresses, as both scopes' rows are seeded, by endpoint id. */
57
- readonly seeds: ById
58
- /** The input fields that name a member of the endpoint's member directory, by endpoint id. */
59
- readonly members: Readonly<Record<string, readonly string[]>>
60
- /** The input fields that name an invitation the endpoint cancels, by endpoint id. */
61
- readonly invitations: Readonly<Record<string, readonly string[]>>
62
- /** The input fields that name a share link the endpoint revokes, by endpoint id. */
63
- readonly links: Readonly<Record<string, readonly string[]>>
64
- /** The input fields that name a row lying in the endpoint's object, with that row's table, by endpoint id. */
65
- readonly rows: Readonly<Record<string, Readonly<Record<string, string>>>>
66
- /** The rows of application tables the endpoint's own case reads, by table, each with its columns, by endpoint id. */
67
- readonly appRows: Readonly<Record<string, Readonly<Record<string, Readonly<Record<string, Sample>>>>>>
68
- /** The file each case sends in a file field, a path relative to the application's root, by input field, by endpoint id. */
69
- readonly files: Readonly<Record<string, Readonly<Record<string, string>>>>
70
- /** The error types of the 400s an endpoint's handler may answer its own object with, by endpoint id. */
71
- readonly refusals: Readonly<Record<string, readonly string[]>>
72
- /** The own scope's value of each pinned text column of the row the endpoint addresses, by endpoint id. */
73
- readonly pins: Readonly<Record<string, Readonly<Record<string, string>>>>
74
- /** The rows of application tables the caller of every global case holds, by table, each with its columns. */
75
- readonly callerRows: Readonly<Record<string, Readonly<Record<string, Sample>>>>
76
- }
77
-
78
- export const NO_FIXTURES: EndpointFixtures = {
79
- inputs: {},
80
- seeds: {},
81
- members: {},
82
- invitations: {},
83
- links: {},
84
- rows: {},
85
- appRows: {},
86
- files: {},
87
- refusals: {},
88
- pins: {},
89
- callerRows: {},
90
- }
91
-
92
- /**
93
- * Whether `path` may name a file fixture: relative to the application's root, `/`-separated, and each segment of
94
- * letters, digits, `_`, `-` and `.` that starts with neither `.` nor `-`, so it never leaves the root, names no dotfile and
95
- * reads the same as a URL path.
96
- */
97
- export const isFixtureFilePath = (path: string): boolean => /^[A-Za-z0-9_][A-Za-z0-9._-]*(\/[A-Za-z0-9_][A-Za-z0-9._-]*)*$/.test(path)
98
-
99
- const finding = (at: AstNode | undefined, message: string): Finding => {
100
- const { line, column } = at === undefined ? { line: 1, column: 1 } : positionOf(at)
101
- return { file: ENDPOINT_FIXTURES_FILE, line, column, severity: 'refusal', rule: 'endpoint-fixture', message, allowed: ALLOWED }
102
- }
103
-
104
- export function isSampleObject(value: Sample): value is { readonly [key: string]: Sample } {
105
- return typeof value === 'object' && value !== null && !Array.isArray(value)
106
- }
107
-
108
- /** A plain literal value, or the node that is not one. */
109
- function literal(
110
- node: AstNode | undefined,
111
- ): { readonly ok: true; readonly value: Sample } | { readonly ok: false; readonly at: AstNode | undefined } {
112
- if (node === undefined) return { ok: false, at: node }
113
- if (node.type === 'Literal') {
114
- const value = node['value']
115
- if (value === null || typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))) {
116
- return { ok: true, value }
117
- }
118
- return { ok: false, at: node }
119
- }
120
- if (node.type === 'TemplateLiteral') {
121
- const text = staticString(node)
122
- return text === undefined ? { ok: false, at: node } : { ok: true, value: text }
123
- }
124
- if (node.type === 'UnaryExpression' && node['operator'] === '-') {
125
- const inner = literal(child(node, 'argument'))
126
- return inner.ok && typeof inner.value === 'number' ? { ok: true, value: -inner.value } : { ok: false, at: node }
127
- }
128
- if (node.type === 'ArrayExpression') {
129
- const items: Sample[] = []
130
- for (const element of children(node, 'elements')) {
131
- const item = literal(element ?? undefined)
132
- if (!item.ok) return item
133
- items.push(item.value)
134
- }
135
- return { ok: true, value: items }
136
- }
137
- if (node.type === 'ObjectExpression') {
138
- const entries: [string, Sample][] = []
139
- for (const property of children(node, 'properties')) {
140
- if (property?.type !== 'Property' || property['computed'] === true || property['method'] === true) return { ok: false, at: property ?? node }
141
- const key = staticKey(property, 'key')
142
- if (key === undefined || key === '__proto__') return { ok: false, at: property }
143
- const value = literal(child(property, 'value'))
144
- if (!value.ok) return value
145
- entries.push([key, value.value])
146
- }
147
- return { ok: true, value: Object.fromEntries(entries) }
148
- }
149
- return { ok: false, at: node }
150
- }
151
-
152
- /** One `export const <name> = { '<endpoint id>': { … } }`, read into an object of objects. */
153
- function byId(
154
- declarator: AstNode,
155
- name: string,
156
- ): { readonly ok: true; readonly value: ById } | { readonly ok: false; readonly findings: readonly Finding[] } {
157
- const init = child(declarator, 'init')
158
- const value = literal(init)
159
- if (!value.ok) return { ok: false, findings: [finding(value.at, 'not a plain literal')] }
160
- const all = value.value
161
- const keyed = name === CALLER_ROWS_EXPORT ? 'table' : 'endpoint id'
162
- if (!isSampleObject(all)) {
163
- return { ok: false, findings: [finding(init, `the ${name} are an object keyed by ${keyed}`)] }
164
- }
165
- const entries: Record<string, Readonly<Record<string, Sample>>> = {}
166
- for (const [id, entry] of Object.entries(all)) {
167
- if (!isSampleObject(entry)) {
168
- const of = name === SEEDS_EXPORT || name === CALLER_ROWS_EXPORT ? 'columns' : name === APP_ROWS_EXPORT ? 'tables' : 'input fields'
169
- return { ok: false, findings: [finding(init, `the ${name} of ${id} is not an object of ${of}`)] }
170
- }
171
- entries[id] = entry
172
- }
173
- return { ok: true, value: entries }
174
- }
175
-
176
- /** `export const <members, invitations, links or refusals> = { '<endpoint id>': ['<field>', …] }`, read into lists. */
177
- function fieldsById(
178
- declarator: AstNode,
179
- name: FieldExport,
180
- ): { readonly ok: true; readonly value: Readonly<Record<string, readonly string[]>> } | {
181
- readonly ok: false
182
- readonly findings: readonly Finding[]
183
- } {
184
- const init = child(declarator, 'init')
185
- const value = literal(init)
186
- if (!value.ok) return { ok: false, findings: [finding(value.at, 'not a plain literal')] }
187
- if (!isSampleObject(value.value)) {
188
- return { ok: false, findings: [finding(init, `the ${name} are an object keyed by endpoint id`)] }
189
- }
190
- const entries: Record<string, readonly string[]> = {}
191
- for (const [id, fields] of Object.entries(value.value)) {
192
- if (!Array.isArray(fields) || fields.length === 0 || !fields.every((field) => typeof field === 'string')) {
193
- const of = name === REFUSALS_EXPORT ? 'error types' : 'input field names'
194
- return { ok: false, findings: [finding(init, `the ${name} of ${id} is not a list of ${of}`)] }
195
- }
196
- entries[id] = fields.filter((field) => typeof field === 'string')
197
- }
198
- return { ok: true, value: entries }
199
- }
200
-
201
- /** Each entry's string values, by endpoint id: what `rows`, `files` and `pins` hold once checked. */
202
- const stringsById = (byIdValue: ById): Readonly<Record<string, Readonly<Record<string, string>>>> =>
203
- Object.fromEntries(
204
- Object.entries(byIdValue).map(([id, named]) => [
205
- id,
206
- Object.fromEntries(Object.entries(named).flatMap(([key, item]) => (typeof item === 'string' ? [[key, item]] : []))),
207
- ]),
208
- )
209
-
210
- /** The fixtures of `files`, by endpoint id; none without the file. */
211
- export function readEndpointFixtures(
212
- files: ReadonlyMap<string, string>,
213
- ): { readonly ok: true; readonly fixtures: EndpointFixtures } | { readonly ok: false; readonly findings: readonly Finding[] } {
214
- const text = files.get(ENDPOINT_FIXTURES_FILE)
215
- if (text === undefined) return { ok: true, fixtures: NO_FIXTURES }
216
- if (new TextEncoder().encode(text).byteLength > CONTRACT_LIMITS.sourceBytes) {
217
- return { ok: false, findings: [finding(undefined, `the fixtures exceed ${CONTRACT_LIMITS.sourceBytes} bytes`)] }
218
- }
219
- const parsed = parseModule(ENDPOINT_FIXTURES_FILE, text)
220
- if (!parsed.ok) return { ok: false, findings: [finding(undefined, parsed.message)] }
221
- const program = parsed.module.program
222
- if (nodeDepth(program) > CONTRACT_LIMITS.astDepth) {
223
- return { ok: false, findings: [finding(undefined, `the fixtures nest deeper than ${CONTRACT_LIMITS.astDepth}`)] }
224
- }
225
- const read = new Map<string, ById>()
226
- const fields = new Map<FieldExport, Readonly<Record<string, readonly string[]>>>()
227
- for (const statement of children(program, 'body')) {
228
- const declaration = statement === null ? undefined : child(statement, 'declaration')
229
- const declarators = declaration?.type === 'VariableDeclaration' && declaration['kind'] === 'const' ? children(declaration, 'declarations') : []
230
- const declarator = declarators.length === 1 ? declarators[0] : undefined
231
- const name = declarator === null || declarator === undefined ? undefined : identifierName(child(declarator, 'id'))
232
- if (
233
- statement?.type !== 'ExportNamedDeclaration' || declarator === null || declarator === undefined
234
- || (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && name !== APP_ROWS_EXPORT && name !== FILES_EXPORT
235
- && name !== PINS_EXPORT && name !== CALLER_ROWS_EXPORT && !isFieldExport(name))
236
- || read.has(name)
237
- || (isFieldExport(name) && fields.has(name))
238
- ) {
239
- return {
240
- ok: false,
241
- findings: [
242
- finding(
243
- statement ?? undefined,
244
- `the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT}, ${LINKS_EXPORT}, ${ROWS_EXPORT}, ${APP_ROWS_EXPORT}, ${FILES_EXPORT}, ${REFUSALS_EXPORT}, ${PINS_EXPORT} and ${CALLER_ROWS_EXPORT} = { … }, each at most once`,
245
- ),
246
- ],
247
- }
248
- }
249
- if (isFieldExport(name)) {
250
- const listed = fieldsById(declarator, name)
251
- if (!listed.ok) return listed
252
- fields.set(name, listed.value)
253
- continue
254
- }
255
- const value = byId(declarator, name)
256
- if (!value.ok) return value
257
- if (name === ROWS_EXPORT) {
258
- const named = Object.entries(value.value).find(([, fields]) => Object.values(fields).some((table) => typeof table !== 'string'))
259
- if (named !== undefined) {
260
- return { ok: false, findings: [finding(child(declarator, 'init'), `the rows of ${named[0]} name each field's table as a string`)] }
261
- }
262
- }
263
- if (name === FILES_EXPORT) {
264
- const named = Object.entries(value.value).find(([, fields]) => Object.values(fields).some((path) => typeof path !== 'string'))
265
- if (named !== undefined) {
266
- return { ok: false, findings: [finding(child(declarator, 'init'), `the files of ${named[0]} name each field's file as a path string`)] }
267
- }
268
- }
269
- if (name === PINS_EXPORT) {
270
- const named = Object.entries(value.value).find(([, columns]) =>
271
- Object.values(columns).some((pinned) => typeof pinned !== 'string' || pinned === '')
272
- )
273
- if (named !== undefined) {
274
- return { ok: false, findings: [finding(child(declarator, 'init'), `the pins of ${named[0]} give each column a non-empty string`)] }
275
- }
276
- }
277
- if (name === APP_ROWS_EXPORT) {
278
- const named = Object.entries(value.value).find(([, tables]) => Object.values(tables).some((columns) => !isSampleObject(columns)))
279
- if (named !== undefined) {
280
- return { ok: false, findings: [finding(child(declarator, 'init'), `the appRows of ${named[0]} give each table's row as an object of columns`)] }
281
- }
282
- }
283
- read.set(name, value.value)
284
- }
285
- return {
286
- ok: true,
287
- fixtures: {
288
- inputs: read.get(FIXTURES_EXPORT) ?? {},
289
- seeds: read.get(SEEDS_EXPORT) ?? {},
290
- members: fields.get(MEMBERS_EXPORT) ?? {},
291
- invitations: fields.get(INVITATIONS_EXPORT) ?? {},
292
- links: fields.get(LINKS_EXPORT) ?? {},
293
- refusals: fields.get(REFUSALS_EXPORT) ?? {},
294
- rows: Object.fromEntries(
295
- Object.entries(read.get(ROWS_EXPORT) ?? {}).map(([id, named]) => [
296
- id,
297
- Object.fromEntries(Object.entries(named).flatMap(([field, table]) => (typeof table === 'string' ? [[field, table]] : []))),
298
- ]),
299
- ),
300
- appRows: Object.fromEntries(
301
- Object.entries(read.get(APP_ROWS_EXPORT) ?? {}).map(([id, tables]) => [
302
- id,
303
- Object.fromEntries(Object.entries(tables).flatMap(([table, columns]) => (isSampleObject(columns) ? [[table, columns]] : []))),
304
- ]),
305
- ),
306
- pins: stringsById(read.get(PINS_EXPORT) ?? {}),
307
- callerRows: read.get(CALLER_ROWS_EXPORT) ?? {},
308
- files: Object.fromEntries(
309
- Object.entries(read.get(FILES_EXPORT) ?? {}).map(([id, named]) => [
310
- id,
311
- Object.fromEntries(Object.entries(named).flatMap(([field, path]) => (typeof path === 'string' ? [[field, path]] : []))),
312
- ]),
313
- ),
314
- },
315
- }
316
- }
@@ -1,83 +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 {
37
- ok: true,
38
- tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures, inputs.dialect),
39
- missing: missingEndpointFixtures(inputs),
40
- }
41
- } catch (error) {
42
- if (error instanceof ContractSourceError) return { ok: false, findings: error.findings }
43
- if (error instanceof ContractError) {
44
- return {
45
- ok: false,
46
- findings: error.problems.map((problem): Finding => ({
47
- file: CONTRACT_FILE,
48
- line: 1,
49
- column: 1,
50
- severity: 'refusal',
51
- rule: 'contract',
52
- message: problem,
53
- allowed: 'a contract that compiles against src/db/tables.ts',
54
- })),
55
- }
56
- }
57
- throw error
58
- }
59
- }
60
-
61
- /**
62
- * Every generated test is byte for byte what the scaffold writes from the current contract and policies: a missing,
63
- * edited or replaced one is a finding, header or not, and so is a generated test the scaffold no longer writes.
64
- * `readable` is false while the literal or trust rules report the sources; otherwise what the reader refuses is
65
- * reported here, so a source it cannot read does not silence the check.
66
- */
67
- export const checkGeneratedTests = async (files: ReadonlyMap<string, string>, readable: boolean): Promise<Finding[]> => {
68
- if (!readable) return []
69
- const expected = await expectedGeneratedTests(files)
70
- if (!expected.ok) return [...expected.findings]
71
- const findings: Finding[] = [...expected.missing]
72
- for (const [path, { text }] of expected.tests) {
73
- const present = files.get(path)
74
- if (present === undefined) findings.push(at(path, 'this generated test is missing'))
75
- else if (present !== text && !(await failsItsHash(present))) findings.push(at(path, 'this file is not the generated test the scaffold writes here'))
76
- }
77
- for (const [path, text] of files) {
78
- if (text.startsWith(GENERATED_TEST_HEADER) && !expected.tests.has(path)) {
79
- findings.push(at(path, 'a generated test the scaffold no longer writes'))
80
- }
81
- }
82
- return findings
83
- }
@@ -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
- }