ramdb2-cli 0.0.0-stage → 2.0.0-alpha.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/LICENSE +21 -0
- package/README.md +369 -2
- package/package.json +33 -4
- package/src/cli.js +124 -0
- package/src/convert.js +90 -0
- package/src/directives.js +42 -0
- package/src/generate/classes.js +292 -0
- package/src/generate/client.js +146 -0
- package/src/generate/invalidation.js +102 -0
- package/src/generate/operations.js +98 -0
- package/src/generate/typeDefs.js +39 -0
- package/src/generate.js +51 -0
- package/src/index.js +8 -0
- package/src/model.js +420 -0
- package/src/new.js +619 -0
- package/src/plantuml.js +71 -0
- package/src/query.js +159 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { lowerFirst } from '../model.js'
|
|
2
|
+
|
|
3
|
+
// The schema of the standard operations of each persistent type (spec section 13). ramdb2-server builds
|
|
4
|
+
// their resolvers at startup from the classes, with the same names: see operationNames in ramdb2-server.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Names of the GraphQL operations and types of a persistent type.
|
|
8
|
+
* @param {string} typeName e.g. Task
|
|
9
|
+
*/
|
|
10
|
+
export function operationNames(typeName) {
|
|
11
|
+
const name = lowerFirst(typeName)
|
|
12
|
+
return {
|
|
13
|
+
list: `${name}s`,
|
|
14
|
+
byId: `${name}ById`,
|
|
15
|
+
dataCheck: `${name}DataCheck`,
|
|
16
|
+
default: `${name}Default`,
|
|
17
|
+
create: `${name}Create`,
|
|
18
|
+
update: `${name}Update`,
|
|
19
|
+
delete: `${name}Delete`,
|
|
20
|
+
argument: name,
|
|
21
|
+
input: `${typeName}Input`,
|
|
22
|
+
validation: `${typeName}Validation`,
|
|
23
|
+
query: `${typeName}Query`,
|
|
24
|
+
result: `${typeName}List`,
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {import('../model.js').Model} model
|
|
30
|
+
* @returns {{path: string, content: string, overwrite: boolean}}
|
|
31
|
+
*/
|
|
32
|
+
export function operationsFile(model) {
|
|
33
|
+
const lines = [
|
|
34
|
+
'# Generated by ramdb2-cli from the schema: do not edit, this file is rewritten at each generation.',
|
|
35
|
+
'# The resolvers of these operations are built by ramdb2-server. A project adds its own with "extend type Query".',
|
|
36
|
+
'',
|
|
37
|
+
'"Any JSON value: the where, aggregates and having of a query (MongoDB syntax)."',
|
|
38
|
+
'scalar JSON',
|
|
39
|
+
]
|
|
40
|
+
for (const type of model.types) {
|
|
41
|
+
const names = operationNames(type.name)
|
|
42
|
+
// Every field is optional: an update changes only the fields it gives
|
|
43
|
+
// @private fields are absent from the API
|
|
44
|
+
const inputs = [...type.parents.map(p => [p.fk, 'Int']), ...type.fields.filter(f => !f.private).map(f => [f.name, f.gqlType, f.sensitive])]
|
|
45
|
+
lines.push('')
|
|
46
|
+
lines.push(`"Values of a ${type.name} to create or modify: an update changes only the fields given."`)
|
|
47
|
+
lines.push(`input ${names.input} {`)
|
|
48
|
+
// @sensitive: the value is masked in the logs of ramdb2-server (spec section 14)
|
|
49
|
+
for (const [field, gqlType, sensitive] of inputs) lines.push(` ${field}: ${gqlType}${sensitive ? ' @sensitive' : ''}`)
|
|
50
|
+
lines.push('}')
|
|
51
|
+
lines.push('')
|
|
52
|
+
lines.push(`"One message per field, empty when the value is valid."`)
|
|
53
|
+
lines.push(`type ${names.validation} {`)
|
|
54
|
+
for (const [field] of inputs) lines.push(` ${field}: String!`)
|
|
55
|
+
lines.push('}')
|
|
56
|
+
lines.push('')
|
|
57
|
+
lines.push(`"A query on ${type.name} (spec section 10)."`)
|
|
58
|
+
lines.push(`input ${names.query} {`)
|
|
59
|
+
lines.push(' where: JSON')
|
|
60
|
+
lines.push(' orderBy: [JSON!]')
|
|
61
|
+
lines.push(' limit: Int')
|
|
62
|
+
lines.push(' offset: Int')
|
|
63
|
+
lines.push(' groupBy: [String!]')
|
|
64
|
+
lines.push(' aggregates: JSON')
|
|
65
|
+
lines.push(' having: JSON')
|
|
66
|
+
lines.push('}')
|
|
67
|
+
lines.push('')
|
|
68
|
+
lines.push(`"Result of a query on ${type.name}: items, or groups with a groupBy."`)
|
|
69
|
+
lines.push(`type ${names.result} {`)
|
|
70
|
+
lines.push(` items: [${type.name}!]`)
|
|
71
|
+
lines.push(' "Number of items, or of groups, before pagination."')
|
|
72
|
+
lines.push(' total: Int!')
|
|
73
|
+
lines.push(' aggregates: JSON')
|
|
74
|
+
lines.push(' groups: [JSON!]')
|
|
75
|
+
lines.push('}')
|
|
76
|
+
}
|
|
77
|
+
lines.push('')
|
|
78
|
+
lines.push('type Query {')
|
|
79
|
+
for (const type of model.types) {
|
|
80
|
+
const n = operationNames(type.name)
|
|
81
|
+
lines.push(` ${n.list}(query: ${n.query}): ${n.result}!`)
|
|
82
|
+
lines.push(` ${n.byId}(id: Int!): ${type.name}!`)
|
|
83
|
+
lines.push(` ${n.dataCheck}(${n.argument}: ${n.input}!, id: Int): ${n.validation}!`)
|
|
84
|
+
lines.push(` ${n.default}: ${type.name}!`)
|
|
85
|
+
}
|
|
86
|
+
lines.push('}')
|
|
87
|
+
lines.push('')
|
|
88
|
+
lines.push('type Mutation {')
|
|
89
|
+
for (const type of model.types) {
|
|
90
|
+
const n = operationNames(type.name)
|
|
91
|
+
lines.push(` ${n.create}(${n.argument}: ${n.input}!): ${type.name}!`)
|
|
92
|
+
// expected: the values read by the client, CONFLICT when one has changed (D45)
|
|
93
|
+
lines.push(` ${n.update}(id: Int!, ${n.argument}: ${n.input}!, expected: ${n.input}): ${type.name}!`)
|
|
94
|
+
lines.push(` ${n.delete}(id: Int!): ${type.name}!`)
|
|
95
|
+
}
|
|
96
|
+
lines.push('}')
|
|
97
|
+
return { path: 'schema/operations.graphql', content: lines.join('\n') + '\n', overwrite: true }
|
|
98
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Kind, parse, print, visit } from 'graphql'
|
|
2
|
+
import { DIRECTIVE_NAMES } from '../directives.js'
|
|
3
|
+
|
|
4
|
+
// The schema served by Apollo (spec section 3): the preTypeDefs without the directives of ramdb2-cli,
|
|
5
|
+
// descriptions kept, with the id and the foreign keys of the persistent types.
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @param {import('../model.js').Model} model
|
|
9
|
+
* @returns {{path: string, content: string, overwrite: boolean}}
|
|
10
|
+
*/
|
|
11
|
+
export function typeDefsFile(model) {
|
|
12
|
+
const document = visit(model.document, {
|
|
13
|
+
Directive(node) {
|
|
14
|
+
if (DIRECTIVE_NAMES.has(node.name.value)) return null
|
|
15
|
+
},
|
|
16
|
+
ObjectTypeDefinition(node) {
|
|
17
|
+
const type = model.byName.get(node.name.value)
|
|
18
|
+
if (type === undefined) return undefined
|
|
19
|
+
const fields = []
|
|
20
|
+
if (!node.fields.some(field => field.name.value === 'id')) fields.push(fieldNode('id: Int!'))
|
|
21
|
+
for (const field of node.fields) {
|
|
22
|
+
// @private: stored, never in the API
|
|
23
|
+
if (field.directives?.some(directive => directive.name.value === 'private')) continue
|
|
24
|
+
const parent = type.parents.find(p => p.name === field.name.value)
|
|
25
|
+
// The foreign key, before its relation: what a client sends to create or modify the object
|
|
26
|
+
if (parent !== undefined) fields.push(fieldNode(`${parent.fk}: Int!`))
|
|
27
|
+
fields.push(field)
|
|
28
|
+
}
|
|
29
|
+
return { ...node, fields }
|
|
30
|
+
},
|
|
31
|
+
})
|
|
32
|
+
const header = '# Generated by ramdb2-cli from the schema: do not edit, this file is rewritten at each generation.\n\n'
|
|
33
|
+
return { path: 'schema/typeDefs.graphql', content: header + print(document) + '\n', overwrite: true }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function fieldNode(source) {
|
|
37
|
+
const field = parse(`type T { ${source} }`, { noLocation: true }).definitions[0].fields[0]
|
|
38
|
+
return field.kind === Kind.FIELD_DEFINITION ? field : undefined
|
|
39
|
+
}
|
package/src/generate.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { dirname, join } from 'node:path'
|
|
3
|
+
import { readSchema } from './model.js'
|
|
4
|
+
import { classFiles } from './generate/classes.js'
|
|
5
|
+
import { clientFiles } from './generate/client.js'
|
|
6
|
+
import { typeDefsFile } from './generate/typeDefs.js'
|
|
7
|
+
import { operationsFile } from './generate/operations.js'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Generates the database layer of a project from its preTypeDefs (spec section 12).
|
|
11
|
+
* Generated files are rewritten; files written by hand (extended classes) are created only when missing.
|
|
12
|
+
* @param {{schema: string | string[], dest: string}} options schema file(s), destination folder
|
|
13
|
+
* @returns {{written: string[], kept: string[], warnings: string[]}} paths relative to dest
|
|
14
|
+
*/
|
|
15
|
+
export function generate({ schema, dest }) {
|
|
16
|
+
const model = readSchemaFiles(schema)
|
|
17
|
+
return { ...writeFiles([...classFiles(model), typeDefsFile(model), operationsFile(model)], dest), warnings: model.warnings }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Generates the classes of a ramdb2-client application from the preTypeDefs of its server (spec section 12, D49):
|
|
22
|
+
* generated/<table>.js (rewritten), extended/<table>.js (created once) and index.js, in dest.
|
|
23
|
+
* @param {{schema: string | string[], dest: string}} options schema file(s), destination folder
|
|
24
|
+
* @returns {{written: string[], kept: string[], warnings: string[]}} paths relative to dest
|
|
25
|
+
*/
|
|
26
|
+
export function generateClient({ schema, dest }) {
|
|
27
|
+
const model = readSchemaFiles(schema)
|
|
28
|
+
const { files, warnings } = clientFiles(model)
|
|
29
|
+
return { ...writeFiles(files, dest), warnings: [...model.warnings, ...warnings] }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function readSchemaFiles(schema) {
|
|
33
|
+
const sources = (Array.isArray(schema) ? schema : [schema]).map(path => readFileSync(path, 'utf8'))
|
|
34
|
+
return readSchema(sources.join('\n'))
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function writeFiles(files, dest) {
|
|
38
|
+
const written = []
|
|
39
|
+
const kept = []
|
|
40
|
+
for (const file of files) {
|
|
41
|
+
const path = join(dest, file.path)
|
|
42
|
+
if (!file.overwrite && existsSync(path)) {
|
|
43
|
+
kept.push(file.path)
|
|
44
|
+
continue
|
|
45
|
+
}
|
|
46
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
47
|
+
writeFileSync(path, file.content)
|
|
48
|
+
written.push(file.path)
|
|
49
|
+
}
|
|
50
|
+
return { written, kept }
|
|
51
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { generate, generateClient } from './generate.js'
|
|
2
|
+
export { convert } from './convert.js'
|
|
3
|
+
export { newProject } from './new.js'
|
|
4
|
+
export { plantuml, diagram } from './plantuml.js'
|
|
5
|
+
export { query, expiryOf } from './query.js'
|
|
6
|
+
export { readSchema, SchemaError } from './model.js'
|
|
7
|
+
export { DIRECTIVES } from './directives.js'
|
|
8
|
+
export { operationNames } from './generate/operations.js'
|
package/src/model.js
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildASTSchema, getDirectiveValues, getNamedType, isEnumType, isLeafType, isListType, isNonNullType, isObjectType,
|
|
3
|
+
isScalarType, Kind, parse, specifiedScalarTypes, visit,
|
|
4
|
+
} from 'graphql'
|
|
5
|
+
import { DIRECTIVES } from './directives.js'
|
|
6
|
+
|
|
7
|
+
// Reads a preTypeDefs into the model the generators use, and checks it (spec section 3).
|
|
8
|
+
// Every error is collected: the generation stops on a SchemaError that lists them all.
|
|
9
|
+
|
|
10
|
+
const BUILT_IN = { Int: 'number', Float: 'number', String: 'string', ID: 'string', Boolean: 'boolean' }
|
|
11
|
+
const DEFAULTS = { Int: '0', Float: '0', String: "''", ID: "''", Boolean: 'false' }
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Thrown when the schema is invalid. `errors` lists every problem found.
|
|
15
|
+
*/
|
|
16
|
+
export class SchemaError extends Error {
|
|
17
|
+
name = 'SchemaError'
|
|
18
|
+
|
|
19
|
+
/** @param {string[]} errors */
|
|
20
|
+
constructor(errors) {
|
|
21
|
+
super('Invalid schema:\n' + errors.map(error => ' - ' + error).join('\n'))
|
|
22
|
+
this.errors = errors
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @typedef {object} Field a persistent scalar, enum or custom scalar field
|
|
28
|
+
* @property {string} name
|
|
29
|
+
* @property {string} gqlType named GraphQL type
|
|
30
|
+
* @property {boolean} nonNull
|
|
31
|
+
* @property {string} jsType for the JSDoc
|
|
32
|
+
* @property {string} defaultValue JavaScript code
|
|
33
|
+
* @property {string | undefined} description
|
|
34
|
+
* @property {{regex: string, message?: string} | undefined} pattern
|
|
35
|
+
* @property {string[] | undefined} enumValues
|
|
36
|
+
* @property {boolean} sensitive @sensitive: masked in the logs
|
|
37
|
+
* @property {boolean} private @private: absent from the GraphQL API
|
|
38
|
+
*
|
|
39
|
+
* @typedef {object} Parent an object relation: this type holds the foreign key
|
|
40
|
+
* @property {string} name relation, e.g. project
|
|
41
|
+
* @property {string} fk foreign key, e.g. idProject
|
|
42
|
+
* @property {string} target type name
|
|
43
|
+
* @property {boolean} required
|
|
44
|
+
* @property {string | undefined} description
|
|
45
|
+
*
|
|
46
|
+
* @typedef {object} Child a list relation: the other type holds the foreign key
|
|
47
|
+
* @property {string} name relation, e.g. taskRoles
|
|
48
|
+
* @property {string} fk foreign key in the target type
|
|
49
|
+
* @property {string} target type name
|
|
50
|
+
* @property {string | undefined} onDelete explicit @onDelete
|
|
51
|
+
* @property {string | undefined} description
|
|
52
|
+
*
|
|
53
|
+
* @typedef {object} Computed
|
|
54
|
+
* @property {string} name
|
|
55
|
+
* @property {string[]} depends
|
|
56
|
+
* @property {string} jsType
|
|
57
|
+
* @property {string} display GraphQL type, e.g. Float!
|
|
58
|
+
* @property {string | undefined} description
|
|
59
|
+
*
|
|
60
|
+
* @typedef {object} Transient a @transient field: resolved by the project, not stored
|
|
61
|
+
* @property {string} name
|
|
62
|
+
* @property {string} display GraphQL type, e.g. String!
|
|
63
|
+
* @property {string} jsType
|
|
64
|
+
* @property {string | undefined} description
|
|
65
|
+
* @property {boolean} scalar scalar, enum, custom scalar or a list of them (a type of another layer is a scalar)
|
|
66
|
+
* @property {string[]} requiredArgs arguments without a default value
|
|
67
|
+
*
|
|
68
|
+
* @typedef {object} Index
|
|
69
|
+
* @property {string} name
|
|
70
|
+
* @property {string[]} fields
|
|
71
|
+
* @property {'map' | 'btree' | 'fulltext'} type
|
|
72
|
+
* @property {boolean} [unique] MAP only: no two objects with the same values
|
|
73
|
+
*
|
|
74
|
+
* @typedef {object} Type a persistent type: one ramdb2 table
|
|
75
|
+
* @property {string} name
|
|
76
|
+
* @property {string} table
|
|
77
|
+
* @property {string | undefined} description
|
|
78
|
+
* @property {string | undefined} group
|
|
79
|
+
* @property {Field[]} fields without id
|
|
80
|
+
* @property {Parent[]} parents
|
|
81
|
+
* @property {Child[]} children
|
|
82
|
+
* @property {Computed[]} computed
|
|
83
|
+
* @property {Transient[]} transient fields resolved by the project on the server
|
|
84
|
+
* @property {Index[]} indexes declared with @index (the inverse indexes of the foreign keys are automatic)
|
|
85
|
+
*
|
|
86
|
+
* @typedef {object} Model
|
|
87
|
+
* @property {Type[]} types
|
|
88
|
+
* @property {Map<string, Type>} byName
|
|
89
|
+
* @property {import('graphql').DocumentNode} document the preTypeDefs, without the directive declarations
|
|
90
|
+
* @property {string[]} warnings
|
|
91
|
+
*/
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* @param {string} source the preTypeDefs (one or several files concatenated)
|
|
95
|
+
* @returns {Model}
|
|
96
|
+
*/
|
|
97
|
+
export function readSchema(source) {
|
|
98
|
+
let document
|
|
99
|
+
let schema
|
|
100
|
+
const warnings = []
|
|
101
|
+
try {
|
|
102
|
+
document = parse(source)
|
|
103
|
+
// Types defined elsewhere (by the server layer, or in a file not given) become placeholder scalars
|
|
104
|
+
const missing = undefinedTypes(document)
|
|
105
|
+
for (const name of missing) warnings.push(`${name} is not defined in the schema: read as a scalar`)
|
|
106
|
+
const placeholders = missing.map(name => `scalar ${name}`).join('\n')
|
|
107
|
+
schema = buildASTSchema(parse(DIRECTIVES + '\n' + placeholders + '\n' + source))
|
|
108
|
+
} catch (error) {
|
|
109
|
+
throw new SchemaError([error.message])
|
|
110
|
+
}
|
|
111
|
+
const errors = []
|
|
112
|
+
const directive = name => schema.getDirective(name)
|
|
113
|
+
// buildASTSchema does not check the values of the directive arguments: getDirectiveValues does
|
|
114
|
+
const values = (name, node) => {
|
|
115
|
+
try {
|
|
116
|
+
return getDirectiveValues(directive(name), node) ?? undefined
|
|
117
|
+
} catch (error) {
|
|
118
|
+
errors.push(`${node.name.value}: @${name}: ${error.message}`)
|
|
119
|
+
return undefined
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const types = []
|
|
124
|
+
const byName = new Map()
|
|
125
|
+
for (const gqlType of Object.values(schema.getTypeMap())) {
|
|
126
|
+
if (!isObjectType(gqlType) || gqlType.astNode === undefined) continue
|
|
127
|
+
if (values('persistent', gqlType.astNode) === undefined) continue
|
|
128
|
+
const type = {
|
|
129
|
+
name: gqlType.name,
|
|
130
|
+
table: lowerFirst(gqlType.name),
|
|
131
|
+
description: gqlType.description ?? undefined,
|
|
132
|
+
group: values('group', gqlType.astNode)?.name,
|
|
133
|
+
fields: [],
|
|
134
|
+
parents: [],
|
|
135
|
+
children: [],
|
|
136
|
+
computed: [],
|
|
137
|
+
transient: [],
|
|
138
|
+
indexes: [],
|
|
139
|
+
_gql: gqlType,
|
|
140
|
+
}
|
|
141
|
+
types.push(type)
|
|
142
|
+
byName.set(type.name, type)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const isPersistent = gqlType => byName.has(gqlType.name)
|
|
146
|
+
|
|
147
|
+
// Fields and relations
|
|
148
|
+
for (const type of types) {
|
|
149
|
+
const at = field => `${type.name}.${field}`
|
|
150
|
+
for (const gqlField of Object.values(type._gql.getFields())) {
|
|
151
|
+
const node = gqlField.astNode
|
|
152
|
+
const name = gqlField.name
|
|
153
|
+
const named = getNamedType(gqlField.type)
|
|
154
|
+
const nonNull = isNonNullType(gqlField.type)
|
|
155
|
+
const list = isListType(isNonNullType(gqlField.type) ? gqlField.type.ofType : gqlField.type)
|
|
156
|
+
const description = gqlField.description ?? undefined
|
|
157
|
+
const computed = values('computed', node)
|
|
158
|
+
const transient = values('transient', node) !== undefined
|
|
159
|
+
const pattern = values('pattern', node)
|
|
160
|
+
const onDelete = values('onDelete', node)
|
|
161
|
+
const field = values('field', node)
|
|
162
|
+
const isPrivate = values('private', node) !== undefined
|
|
163
|
+
if (isPrivate && (computed !== undefined || transient || name === 'id' || isObjectType(named) || list)) {
|
|
164
|
+
errors.push(`${at(name)}: @private only goes on a stored scalar field`)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (computed !== undefined && transient) errors.push(`${at(name)}: @computed and @transient exclude each other`)
|
|
168
|
+
if (computed !== undefined) {
|
|
169
|
+
type.computed.push({ name, depends: computed.depends, jsType: jsType(gqlField.type, byName), display: String(gqlField.type), description })
|
|
170
|
+
continue
|
|
171
|
+
}
|
|
172
|
+
if (transient) {
|
|
173
|
+
type.transient.push({
|
|
174
|
+
name,
|
|
175
|
+
display: String(gqlField.type),
|
|
176
|
+
jsType: jsType(gqlField.type, byName),
|
|
177
|
+
description,
|
|
178
|
+
scalar: isLeafType(named),
|
|
179
|
+
requiredArgs: gqlField.args.filter(arg => isNonNullType(arg.type) && arg.defaultValue === undefined).map(arg => arg.name),
|
|
180
|
+
})
|
|
181
|
+
continue
|
|
182
|
+
}
|
|
183
|
+
if (name === 'id') {
|
|
184
|
+
if (named.name !== 'Int' || list) errors.push(`${at('id')} must be an Int`)
|
|
185
|
+
continue
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (isObjectType(named)) {
|
|
189
|
+
if (!isPersistent(named)) {
|
|
190
|
+
errors.push(`${at(name)}: ${named.name} is not @persistent: add @transient or @computed`)
|
|
191
|
+
} else if (list) {
|
|
192
|
+
if (field === undefined) errors.push(`${at(name)}: a list relation needs @field(name:)`)
|
|
193
|
+
else type.children.push({ name, fk: field.name, target: named.name, onDelete: onDelete?.action, description })
|
|
194
|
+
} else {
|
|
195
|
+
type.parents.push({ name, fk: 'id' + upperFirst(name), target: named.name, required: nonNull, description })
|
|
196
|
+
}
|
|
197
|
+
if (field !== undefined && !list) errors.push(`${at(name)}: @field only goes on a list relation`)
|
|
198
|
+
if (onDelete !== undefined && !list) errors.push(`${at(name)}: @onDelete only goes on a list relation`)
|
|
199
|
+
if (pattern !== undefined) errors.push(`${at(name)}: @pattern only goes on a scalar field`)
|
|
200
|
+
continue
|
|
201
|
+
}
|
|
202
|
+
if (list) {
|
|
203
|
+
errors.push(`${at(name)}: a list of scalars cannot be persistent: add @transient or @computed`)
|
|
204
|
+
continue
|
|
205
|
+
}
|
|
206
|
+
for (const [directiveName, value] of [['field', field], ['onDelete', onDelete]]) {
|
|
207
|
+
if (value !== undefined) errors.push(`${at(name)}: @${directiveName} only goes on a list relation`)
|
|
208
|
+
}
|
|
209
|
+
if (pattern !== undefined) {
|
|
210
|
+
try {
|
|
211
|
+
new RegExp(pattern.regex)
|
|
212
|
+
} catch (error) {
|
|
213
|
+
errors.push(`${at(name)}: invalid @pattern regex: ${error.message}`)
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
const enumValues = isEnumType(named) ? named.getValues().map(value => value.name) : undefined
|
|
217
|
+
// A required private field: the API could never create the object
|
|
218
|
+
if (isPrivate && nonNull && (named.name === 'String' || named.name === 'ID' || defaultValue(named, nonNull) === 'null')) {
|
|
219
|
+
errors.push(`${at(name)}: a @private field cannot be required (no "!"): the API could not create the object`)
|
|
220
|
+
}
|
|
221
|
+
type.fields.push({
|
|
222
|
+
name,
|
|
223
|
+
gqlType: named.name,
|
|
224
|
+
nonNull,
|
|
225
|
+
jsType: jsType(gqlField.type, byName),
|
|
226
|
+
defaultValue: defaultValue(named, nonNull),
|
|
227
|
+
description,
|
|
228
|
+
pattern,
|
|
229
|
+
enumValues,
|
|
230
|
+
sensitive: values('sensitive', node) !== undefined,
|
|
231
|
+
private: isPrivate,
|
|
232
|
+
})
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
checkRelations(types, byName, errors)
|
|
237
|
+
for (const type of types) readIndexes(type, values, errors)
|
|
238
|
+
for (const type of types) checkComputed(type, byName, errors)
|
|
239
|
+
|
|
240
|
+
if (errors.length > 0) throw new SchemaError(errors)
|
|
241
|
+
for (const type of types) delete type._gql
|
|
242
|
+
return { types, byName, document, warnings }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function undefinedTypes(document) {
|
|
246
|
+
const defined = new Set([...specifiedScalarTypes.map(type => type.name), 'RamdbIndexType', 'RamdbOnDelete'])
|
|
247
|
+
for (const definition of document.definitions) {
|
|
248
|
+
if (definition.name !== undefined && !definition.kind.endsWith('Extension')) defined.add(definition.name.value)
|
|
249
|
+
}
|
|
250
|
+
const missing = new Set()
|
|
251
|
+
visit(document, {
|
|
252
|
+
NamedType(node) {
|
|
253
|
+
if (!defined.has(node.name.value)) missing.add(node.name.value)
|
|
254
|
+
},
|
|
255
|
+
})
|
|
256
|
+
return [...missing]
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Every list relation must match an object relation of the other type pointing back here
|
|
260
|
+
function checkRelations(types, byName, errors) {
|
|
261
|
+
for (const type of types) {
|
|
262
|
+
const names = new Set()
|
|
263
|
+
for (const name of [...type.fields.map(f => f.name), ...type.parents.map(p => p.fk)]) {
|
|
264
|
+
if (names.has(name)) errors.push(`${type.name}.${name} is declared twice (an object relation adds its foreign key)`)
|
|
265
|
+
names.add(name)
|
|
266
|
+
}
|
|
267
|
+
for (const child of type.children) {
|
|
268
|
+
const parent = byName.get(child.target).parents.find(p => p.fk === child.fk)
|
|
269
|
+
if (parent === undefined || parent.target !== type.name) {
|
|
270
|
+
errors.push(`${type.name}.${child.name}: @field(name: "${child.fk}") needs an object relation ` +
|
|
271
|
+
`${lowerFirst(child.fk.slice(2))}: ${type.name} in ${child.target}`)
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function readIndexes(type, values, errors) {
|
|
278
|
+
const add = (index, where) => {
|
|
279
|
+
if (type.indexes.some(other => other.name === index.name)) {
|
|
280
|
+
errors.push(`${where}: two indexes are named ${index.name}: give one a name:`)
|
|
281
|
+
}
|
|
282
|
+
type.indexes.push(index)
|
|
283
|
+
}
|
|
284
|
+
const fullText = []
|
|
285
|
+
const node = type._gql.astNode
|
|
286
|
+
// A repeatable directive: getDirectiveValues reads only the first one
|
|
287
|
+
for (const directiveNode of node.directives.filter(d => d.name.value === 'index')) {
|
|
288
|
+
const args = argumentsOf(directiveNode)
|
|
289
|
+
if (args.fields === undefined || args.fields.length < 2) {
|
|
290
|
+
errors.push(`${type.name}: @index on a type needs fields: [...] with at least two fields`)
|
|
291
|
+
continue
|
|
292
|
+
}
|
|
293
|
+
if ((args.type ?? 'MAP') !== 'MAP') errors.push(`${type.name}: @index on a type is a MAP index`)
|
|
294
|
+
const unique = args.unique === true
|
|
295
|
+
for (const field of args.fields) {
|
|
296
|
+
if (field !== 'id' && !type.fields.some(f => f.name === field) && !type.parents.some(p => p.fk === field)) {
|
|
297
|
+
errors.push(`${type.name}: @index(fields:) names the unknown field ${field}`)
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
add({ name: args.name ?? args.fields.join('_'), fields: args.fields, type: 'map', ...(unique && { unique }) }, type.name)
|
|
301
|
+
}
|
|
302
|
+
for (const gqlField of Object.values(type._gql.getFields())) {
|
|
303
|
+
for (const directiveNode of gqlField.astNode.directives.filter(d => d.name.value === 'index')) {
|
|
304
|
+
const args = argumentsOf(directiveNode)
|
|
305
|
+
const where = `${type.name}.${gqlField.name}`
|
|
306
|
+
if (args.fields !== undefined) errors.push(`${where}: fields: only goes on an @index of a type`)
|
|
307
|
+
if (!type.fields.some(f => f.name === gqlField.name)) {
|
|
308
|
+
errors.push(`${where}: @index only goes on a persistent scalar field`)
|
|
309
|
+
continue
|
|
310
|
+
}
|
|
311
|
+
const kind = (args.type ?? 'MAP').toLowerCase()
|
|
312
|
+
const unique = args.unique === true
|
|
313
|
+
if (unique && kind !== 'map') errors.push(`${where}: only a MAP index can be unique`)
|
|
314
|
+
// $text searches every full-text field: a private one could be found by its content
|
|
315
|
+
if (kind === 'fulltext' && type.fields.find(f => f.name === gqlField.name).private) {
|
|
316
|
+
errors.push(`${where}: a @private field cannot have a FULLTEXT index`)
|
|
317
|
+
}
|
|
318
|
+
if (kind === 'fulltext') fullText.push(gqlField.name)
|
|
319
|
+
else add({ name: args.name ?? gqlField.name, fields: [gqlField.name], type: kind, ...(unique && { unique }) }, where)
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
// One full-text index per table, over all its FULLTEXT fields (D21)
|
|
323
|
+
if (fullText.length > 0) add({ name: 'fullText', fields: fullText, type: 'fulltext' }, type.name)
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function argumentsOf(directiveNode) {
|
|
327
|
+
const args = {}
|
|
328
|
+
for (const argument of directiveNode.arguments) {
|
|
329
|
+
const value = argument.value
|
|
330
|
+
args[argument.name.value] = value.kind === 'ListValue' ? value.values.map(v => v.value) : value.value
|
|
331
|
+
}
|
|
332
|
+
return args
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Each path goes through relations and ends on a persistent field, a foreign key, a relation or a computed field.
|
|
336
|
+
// Only cycles on the same object are refused: through a relation, a tree is fine (D12).
|
|
337
|
+
function checkComputed(type, byName, errors) {
|
|
338
|
+
for (const computed of type.computed) {
|
|
339
|
+
for (const path of computed.depends) {
|
|
340
|
+
const problem = resolvePath(type, path.split('.'), byName).error
|
|
341
|
+
if (problem !== undefined) errors.push(`${type.name}.${computed.name}: depends "${path}": ${problem}`)
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
const local = new Map(type.computed.map(c => [c.name, c.depends.filter(path => !path.includes('.'))]))
|
|
345
|
+
const visiting = new Set()
|
|
346
|
+
const done = new Set()
|
|
347
|
+
const visit = (name, chain) => {
|
|
348
|
+
if (done.has(name)) return
|
|
349
|
+
if (visiting.has(name)) {
|
|
350
|
+
errors.push(`${type.name}: computed fields depend on each other in a cycle: ${[...chain, name].join(' -> ')}`)
|
|
351
|
+
return
|
|
352
|
+
}
|
|
353
|
+
visiting.add(name)
|
|
354
|
+
for (const next of local.get(name) ?? []) if (local.has(next)) visit(next, [...chain, name])
|
|
355
|
+
visiting.delete(name)
|
|
356
|
+
done.add(name)
|
|
357
|
+
}
|
|
358
|
+
for (const name of local.keys()) visit(name, [])
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Follows a dependency path from a type.
|
|
363
|
+
* @returns {{steps?: {relation: Parent | Child, kind: 'parent' | 'child', from: Type, to: Type}[], end?: Type, last?: string, error?: string}}
|
|
364
|
+
*/
|
|
365
|
+
export function resolvePath(type, segments, byName) {
|
|
366
|
+
const steps = []
|
|
367
|
+
let current = type
|
|
368
|
+
for (let i = 0; i < segments.length; i++) {
|
|
369
|
+
const segment = segments[i]
|
|
370
|
+
const isLast = i === segments.length - 1
|
|
371
|
+
const parent = current.parents.find(p => p.name === segment)
|
|
372
|
+
const child = current.children.find(c => c.name === segment)
|
|
373
|
+
if (parent !== undefined || child !== undefined) {
|
|
374
|
+
const relation = parent ?? child
|
|
375
|
+
const to = byName.get(relation.target)
|
|
376
|
+
steps.push({ relation, kind: parent !== undefined ? 'parent' : 'child', from: current, to })
|
|
377
|
+
current = to
|
|
378
|
+
if (isLast) return { steps, end: current, last: undefined }
|
|
379
|
+
continue
|
|
380
|
+
}
|
|
381
|
+
if (!isLast) return { error: `${segment} is not a relation of ${current.name}` }
|
|
382
|
+
const known = segment === 'id' || current.fields.some(f => f.name === segment) ||
|
|
383
|
+
current.parents.some(p => p.fk === segment) || current.computed.some(c => c.name === segment)
|
|
384
|
+
if (!known) return { error: `${segment} is not a field of ${current.name}` }
|
|
385
|
+
return { steps, end: current, last: segment }
|
|
386
|
+
}
|
|
387
|
+
return { error: 'empty path' }
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function jsType(gqlType, byName) {
|
|
391
|
+
const nonNull = isNonNullType(gqlType)
|
|
392
|
+
const inner = nonNull ? gqlType.ofType : gqlType
|
|
393
|
+
if (isListType(inner)) {
|
|
394
|
+
const item = jsType(inner.ofType, byName)
|
|
395
|
+
return `${item.includes(' | ') ? `(${item})` : item}[]${nonNull ? '' : ' | null'}`
|
|
396
|
+
}
|
|
397
|
+
const named = getNamedType(inner)
|
|
398
|
+
let base
|
|
399
|
+
if (BUILT_IN[named.name] !== undefined) base = BUILT_IN[named.name]
|
|
400
|
+
else if (isEnumType(named)) base = named.getValues().map(v => `'${v.name}'`).join(' | ')
|
|
401
|
+
else if (isObjectType(named)) base = byName.has(named.name) ? named.name : 'object'
|
|
402
|
+
else base = 'any'
|
|
403
|
+
return nonNull ? base : `${base} | null`
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// Same defaults as the v1 whatever the nullability; an enum starts on its first value
|
|
407
|
+
function defaultValue(named, nonNull) {
|
|
408
|
+
if (DEFAULTS[named.name] !== undefined) return DEFAULTS[named.name]
|
|
409
|
+
if (isEnumType(named)) return nonNull ? `'${named.getValues()[0].name}'` : 'null'
|
|
410
|
+
if (isScalarType(named)) return 'null'
|
|
411
|
+
return 'null'
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export function lowerFirst(string) {
|
|
415
|
+
return string.charAt(0).toLowerCase() + string.slice(1)
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
export function upperFirst(string) {
|
|
419
|
+
return string.charAt(0).toUpperCase() + string.slice(1)
|
|
420
|
+
}
|