ramdb2-cli 2.0.0-alpha.3 → 2.0.0-alpha.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # ramdb2-cli
2
2
 
3
+ ## 2.0.0-alpha.5
4
+
5
+ ### Minor Changes
6
+
7
+ - e34f3bd: `generate` and `client` remove the generated classes of a type gone from the schema, and name its extended class in a warning (D61).
8
+
9
+ ## 2.0.0-alpha.4
10
+
11
+ ### Minor Changes
12
+
13
+ - 919e6ae: Permissions by field (D58): `@restricted` in the schema, `permissions.<Type>.fields` in ramdb2-server. A refused field gives `null`; a query on a restricted field only covers the objects whose field the user may read.
14
+ - a26c413: The `see` permission applies to the relations (D57): a list relation is filtered, an object relation the user cannot see gives `null`. `ramdb2-cli generate` serves the object relations as nullable; `ramdb2-cli client` types them `Xxx | null`.
15
+
3
16
  ## 2.0.0-alpha.3
4
17
 
5
18
  ### Minor Changes
package/README.md CHANGED
@@ -42,12 +42,16 @@ Several `--schema` files are read as one schema. In a project created by `ramdb2
42
42
  | `db/generated/<table>.js` | class `XxxBase`: fields, foreign keys, indexes, rules, default values, getters and setters, relations, computed fields, finders, invalidation code | at each generation |
43
43
  | `db/extended/<table>.js` | class `Xxx extends XxxBase`: your business rules, computed fields and methods | never: created when missing |
44
44
  | `db/index.js` | the extended classes, and `classes` for `store.register(...classes)` | at each generation |
45
- | `schema/typeDefs.graphql` | the schema served by the API: without the directives (but `@sensitive`) nor the `@private` fields, with `id` and the foreign keys | at each generation |
45
+ | `schema/typeDefs.graphql` | the schema served by the API: without the directives (but `@sensitive`) nor the `@private` fields, with `id` and the foreign keys; a field that leads to one persistent object is nullable, as the `see` permission may hide it, and so is a `@restricted` field | at each generation |
46
46
  | `schema/operations.graphql` | the `JSON` scalar, and for each type its input (with the `@sensitive` fields, without the `@private` ones), validation, query and list types, its queries and mutations | at each generation |
47
47
 
48
48
  Never edit a generated file: the next generation would erase the change. Everything you write goes in
49
49
  `db/extended`, and in your own schema files (`extend type Query { ... }`).
50
50
 
51
+ When a type leaves the schema, its file in `db/generated/` is removed (`removed` in the output); only a file with
52
+ the header `// Generated by ramdb2-cli` is ever removed. Its file in `db/extended/`, written by you, is kept and
53
+ named in a warning. `client` does the same in its `generated/` and `extended/` folders.
54
+
51
55
  ### The schema: the preTypeDefs
52
56
 
53
57
  ```graphql
@@ -99,6 +103,7 @@ a directive in the wrong place, a missing or badly typed argument is an error.
99
103
  | `@transient` | field | | a field of the API that is not stored |
100
104
  | `@sensitive` | field | | its value is masked in the logs of ramdb2-server (`"[REDACTED]"`) |
101
105
  | `@private` | field | | stored and read by your code, but absent from the API: neither read, written nor queried (a password hash). Not with `!` when it would be required, nor with a FULLTEXT index |
106
+ | `@restricted` | field | | read through the API only when its permission allows it, object by object (`permissions.<Type>.fields` of ramdb2-server); served nullable. On a stored field, an object relation (with its foreign key), a computed or `@transient` field. A computed field that depends on it must be `@restricted` too |
102
107
 
103
108
  ### How the fields are read
104
109
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ramdb2-cli",
3
- "version": "2.0.0-alpha.3",
3
+ "version": "2.0.0-alpha.5",
4
4
  "description": "Code generator and project scaffolding for ramdb2 and ramdb2-server",
5
5
  "type": "module",
6
6
  "exports": "./src/index.js",
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "devDependencies": {
30
30
  "@vitejs/plugin-vue": "^6.0.10",
31
- "ramdb2-core": "^2.0.0-alpha.3",
31
+ "ramdb2-core": "^2.0.0-alpha.5",
32
32
  "vite": "^8.3.5",
33
33
  "vue": "^3.5.44",
34
34
  "vue-router": "^5.4.0"
package/src/cli.js CHANGED
@@ -127,9 +127,10 @@ const commands = {
127
127
  },
128
128
  }
129
129
 
130
- function report({ written, kept, warnings }) {
130
+ function report({ written, kept, removed = [], warnings }) {
131
131
  for (const path of written) console.log(`written ${path}`)
132
132
  for (const path of kept) console.log(`kept ${path} (written by hand)`)
133
+ for (const path of removed) console.log(`removed ${path} (type no longer in the schema)`)
133
134
  for (const warning of warnings) console.log(`warning ${warning}`)
134
135
  }
135
136
 
package/src/directives.js CHANGED
@@ -33,10 +33,13 @@ directive @transient on FIELD_DEFINITION
33
33
  "Field stored and readable in code, but absent from the GraphQL API: neither read, written nor queried (D47)."
34
34
  directive @private on FIELD_DEFINITION
35
35
 
36
+ "Field readable only when the permission of the server allows it, for each object (D58): served nullable."
37
+ directive @restricted on FIELD_DEFINITION
38
+
36
39
  "Value masked in the logs. Kept in the schema served by Apollo: ramdb2-server reads it."
37
40
  directive @sensitive on FIELD_DEFINITION | INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
38
41
  `
39
42
 
40
43
  /** Names of the directives above removed from the schema served by Apollo: all but @sensitive. */
41
- export const DIRECTIVE_NAMES = new Set(['persistent', 'group', 'index', 'field', 'onDelete', 'computed', 'pattern', 'transient', 'private'])
44
+ export const DIRECTIVE_NAMES = new Set(['persistent', 'group', 'index', 'field', 'onDelete', 'computed', 'pattern', 'transient', 'private', 'restricted'])
42
45
  export const INTERNAL_TYPES = new Set(['RamdbIndexType', 'RamdbOnDelete'])
@@ -40,6 +40,18 @@ function generatedClass(type, model, code) {
40
40
  lines.push(' // @private: never read, written nor queried through the GraphQL API')
41
41
  lines.push(` static privateFields = [${privateFields.map(quote).join(', ')}]`)
42
42
  }
43
+ if (type.restricted.length > 0) {
44
+ lines.push('')
45
+ lines.push(' // @restricted: read through the API only when permissions.<Type>.fields allows it (D58)')
46
+ lines.push(` static restrictedFields = [${type.restricted.map(quote).join(', ')}]`)
47
+ }
48
+ if (type.children.length > 0) {
49
+ lines.push('')
50
+ lines.push(' // The list relations: the table of their objects and the foreign key that points here')
51
+ lines.push(' static listRelations = {')
52
+ for (const child of type.children) lines.push(` ${child.name}: { table: '${byNameTable(model, child.target)}', key: '${child.fk}' },`)
53
+ lines.push(' }')
54
+ }
43
55
 
44
56
  const foreignKeys = type.parents.map(parent => [parent, onDeleteOf(parent, type, model)])
45
57
  if (foreignKeys.length > 0) {
@@ -290,3 +302,7 @@ export function jsdoc(description, indent, extra = []) {
290
302
  export function quote(string) {
291
303
  return `'${string}'`
292
304
  }
305
+
306
+ function byNameTable(model, name) {
307
+ return model.byName.get(name).table
308
+ }
@@ -89,34 +89,39 @@ function generatedClass(type, model) {
89
89
  lines.push(' }')
90
90
  }
91
91
 
92
+ // A @restricted field may be hidden by its permission on the server (D58): null
93
+ const orNull = (name, jsType) => type.restricted.includes(name) && !/\bnull\b/.test(jsType) ? `${jsType} | null` : jsType
92
94
  for (const parent of type.parents) {
93
95
  lines.push('')
94
- lines.push(` /** @returns {number} foreign key of ${parent.name}, 0 = none */`)
96
+ lines.push(` /** @returns {${orNull(parent.fk, 'number')}} foreign key of ${parent.name}, 0 = none */`)
95
97
  lines.push(` get ${parent.fk}() { return this._f.${parent.fk} }`)
96
98
  }
97
99
  for (const field of fields) {
98
100
  lines.push('')
99
- lines.push(jsdoc(field.description, ' ', [`@returns {${field.jsType}}`]))
101
+ lines.push(jsdoc(field.description, ' ', [`@returns {${orNull(field.name, field.jsType)}}`]))
100
102
  lines.push(` get ${field.name}() { return this._f.${field.name} }`)
101
103
  }
102
104
  for (const relation of [...type.parents, ...type.children]) {
103
105
  const target = model.byName.get(relation.target)
104
- const list = type.children.includes(relation) ? '[]' : ''
106
+ // An object relation may be hidden by the permission see of the server (D57): null
107
+ const returns = type.children.includes(relation) ? '[]' : ' | null'
105
108
  lines.push('')
106
109
  lines.push(jsdoc(relation.description, ' ', [
107
110
  `Loaded with include: ['${relation.name}'].`,
108
- `@returns {import('../extended/${target.table}.js').default${list}}`,
111
+ `@returns {import('../extended/${target.table}.js').default${returns}}`,
109
112
  ]))
110
113
  lines.push(` get ${relation.name}() { return this._relation('${relation.name}') }`)
111
114
  }
112
115
  for (const computed of type.computed) {
113
116
  lines.push('')
114
- lines.push(jsdoc(computed.description, ' ', ['Computed by the server.', `@returns {${computed.jsType}}`]))
117
+ // Served nullable when it leads to one persistent object (D57)
118
+ const served = /^\w+!$/.test(computed.display) && model.byName.has(computed.display.slice(0, -1)) ? `${computed.jsType} | null` : computed.jsType
119
+ lines.push(jsdoc(computed.description, ' ', ['Computed by the server.', `@returns {${orNull(computed.name, served)}}`]))
115
120
  lines.push(` get ${computed.name}() { return this._c.${computed.name} }`)
116
121
  }
117
122
  for (const field of transient) {
118
123
  lines.push('')
119
- lines.push(jsdoc(field.description, ' ', ['Resolved by the project on the server.', `@returns {${field.jsType}}`]))
124
+ lines.push(jsdoc(field.description, ' ', ['Resolved by the project on the server.', `@returns {${orNull(field.name, field.jsType)}}`]))
120
125
  lines.push(` get ${field.name}() { return this._c.${field.name} }`)
121
126
  }
122
127
  lines.push('}')
@@ -3,6 +3,8 @@ import { DIRECTIVE_NAMES } from '../directives.js'
3
3
 
4
4
  // The schema served by Apollo (spec section 3): the preTypeDefs without the directives of ramdb2-cli,
5
5
  // descriptions kept, with the id and the foreign keys of the persistent types.
6
+ // A field that leads to one persistent object is served nullable (D57): the permission `see` may hide it.
7
+ // A @restricted field, and the foreign key of a @restricted relation, too (D58): its permission may hide it.
6
8
 
7
9
  /**
8
10
  * @param {import('../model.js').Model} model
@@ -23,8 +25,9 @@ export function typeDefsFile(model) {
23
25
  if (field.directives?.some(directive => directive.name.value === 'private')) continue
24
26
  const parent = type.parents.find(p => p.name === field.name.value)
25
27
  // 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
+ const restricted = type.restricted.includes(field.name.value)
29
+ if (parent !== undefined) fields.push(fieldNode(`${parent.fk}: Int${restricted ? '' : '!'}`))
30
+ fields.push(restricted ? nullable(field) : nullableObject(field, model))
28
31
  }
29
32
  return { ...node, fields }
30
33
  },
@@ -33,6 +36,17 @@ export function typeDefsFile(model) {
33
36
  return { path: 'schema/typeDefs.graphql', content: header + print(document) + '\n', overwrite: true }
34
37
  }
35
38
 
39
+ // `project: Project!` → `project: Project`: the ! keeps its meaning of required foreign key in the model only
40
+ function nullableObject(field, model) {
41
+ const type = field.type
42
+ if (type.kind !== Kind.NON_NULL_TYPE || type.type.kind !== Kind.NAMED_TYPE || !model.byName.has(type.type.name.value)) return field
43
+ return { ...field, type: type.type }
44
+ }
45
+
46
+ function nullable(field) {
47
+ return field.type.kind === Kind.NON_NULL_TYPE ? { ...field, type: field.type.type } : field
48
+ }
49
+
36
50
  function fieldNode(source) {
37
51
  const field = parse(`type T { ${source} }`, { noLocation: true }).definitions[0].fields[0]
38
52
  return field.kind === Kind.FIELD_DEFINITION ? field : undefined
package/src/generate.js CHANGED
@@ -1,5 +1,5 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
- import { dirname, join } from 'node:path'
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { dirname, join, posix } from 'node:path'
3
3
  import { readSchema } from './model.js'
4
4
  import { classFiles } from './generate/classes.js'
5
5
  import { clientFiles } from './generate/client.js'
@@ -9,24 +9,29 @@ import { operationsFile } from './generate/operations.js'
9
9
  /**
10
10
  * Generates the database layer of a project from its preTypeDefs (spec section 12).
11
11
  * Generated files are rewritten; files written by hand (extended classes) are created only when missing.
12
+ * The generated classes of a type gone from the schema are removed, its extended class is named in a warning.
12
13
  * @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
+ * @returns {{written: string[], kept: string[], removed: string[], warnings: string[]}} paths relative to dest
14
15
  */
15
16
  export function generate({ schema, dest }) {
16
17
  const model = readSchemaFiles(schema)
17
- return { ...writeFiles([...classFiles(model), typeDefsFile(model), operationsFile(model)], dest), warnings: model.warnings }
18
+ const files = [...classFiles(model), typeDefsFile(model), operationsFile(model)]
19
+ const { removed, warnings } = removeOrphans(files, dest)
20
+ return { ...writeFiles(files, dest), removed, warnings: [...model.warnings, ...warnings] }
18
21
  }
19
22
 
20
23
  /**
21
24
  * 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.
25
+ * generated/<table>.js (rewritten), extended/<table>.js (created once) and index.js, in dest. Orphans are handled
26
+ * as by generate.
23
27
  * @param {{schema: string | string[], dest: string}} options schema file(s), destination folder
24
- * @returns {{written: string[], kept: string[], warnings: string[]}} paths relative to dest
28
+ * @returns {{written: string[], kept: string[], removed: string[], warnings: string[]}} paths relative to dest
25
29
  */
26
30
  export function generateClient({ schema, dest }) {
27
31
  const model = readSchemaFiles(schema)
28
32
  const { files, warnings } = clientFiles(model)
29
- return { ...writeFiles(files, dest), warnings: [...model.warnings, ...warnings] }
33
+ const orphans = removeOrphans(files, dest)
34
+ return { ...writeFiles(files, dest), removed: orphans.removed, warnings: [...model.warnings, ...warnings, ...orphans.warnings] }
30
35
  }
31
36
 
32
37
  function readSchemaFiles(schema) {
@@ -49,3 +54,36 @@ function writeFiles(files, dest) {
49
54
  }
50
55
  return { written, kept }
51
56
  }
57
+
58
+ // The marker of a file written by ramdb2-cli: only such a file is ever removed
59
+ const GENERATED = '// Generated by ramdb2-cli'
60
+
61
+ // The classes of a type removed from the schema (D61): in each folder of generated classes, a generated file that
62
+ // this generation does not write is removed; in each folder of extended classes, a file without its generated
63
+ // class is only named in a warning, since it was written by hand.
64
+ function removeOrphans(files, dest) {
65
+ const removed = []
66
+ const warnings = []
67
+ const folders = new Map()
68
+ for (const file of files) {
69
+ const folder = posix.dirname(file.path)
70
+ if (!['generated', 'extended'].includes(posix.basename(folder))) continue
71
+ if (!folders.has(folder)) folders.set(folder, new Set())
72
+ folders.get(folder).add(posix.basename(file.path))
73
+ }
74
+ for (const [folder, names] of folders) {
75
+ const path = join(dest, folder)
76
+ if (!existsSync(path)) continue
77
+ for (const entry of readdirSync(path, { withFileTypes: true })) {
78
+ if (!entry.isFile() || !entry.name.endsWith('.js') || names.has(entry.name)) continue
79
+ const relative = posix.join(folder, entry.name)
80
+ if (posix.basename(folder) === 'extended') {
81
+ warnings.push(`${relative}: its type is no longer in the schema, remove it by hand if it is not used`)
82
+ } else if (readFileSync(join(path, entry.name), 'utf8').startsWith(GENERATED)) {
83
+ rmSync(join(path, entry.name))
84
+ removed.push(relative)
85
+ }
86
+ }
87
+ }
88
+ return { removed, warnings }
89
+ }
package/src/model.js CHANGED
@@ -82,6 +82,8 @@ export class SchemaError extends Error {
82
82
  * @property {Computed[]} computed
83
83
  * @property {Transient[]} transient fields resolved by the project on the server
84
84
  * @property {Index[]} indexes declared with @index (the inverse indexes of the foreign keys are automatic)
85
+ * @property {string[]} restricted @restricted fields (D58): stored fields, relations with their foreign key,
86
+ * computed and @transient fields
85
87
  *
86
88
  * @typedef {object} Model
87
89
  * @property {Type[]} types
@@ -136,6 +138,7 @@ export function readSchema(source) {
136
138
  computed: [],
137
139
  transient: [],
138
140
  indexes: [],
141
+ restricted: [],
139
142
  _gql: gqlType,
140
143
  }
141
144
  types.push(type)
@@ -163,6 +166,15 @@ export function readSchema(source) {
163
166
  if (isPrivate && (computed !== undefined || transient || name === 'id' || isObjectType(named) || list)) {
164
167
  errors.push(`${at(name)}: @private only goes on a stored scalar field`)
165
168
  }
169
+ if (values('restricted', node) !== undefined) {
170
+ if (name === 'id') errors.push(`${at(name)}: the id cannot be @restricted`)
171
+ else if (isPrivate) errors.push(`${at(name)}: @private and @restricted exclude each other`)
172
+ else if (list && isPersistent(named)) errors.push(`${at(name)}: a list relation cannot be @restricted: restrict the object relation of the other type`)
173
+ else {
174
+ type.restricted.push(name)
175
+ if (isPersistent(named) && computed === undefined && !transient) type.restricted.push('id' + upperFirst(name))
176
+ }
177
+ }
166
178
 
167
179
  if (computed !== undefined && transient) errors.push(`${at(name)}: @computed and @transient exclude each other`)
168
180
  if (computed !== undefined) {
@@ -236,6 +248,7 @@ export function readSchema(source) {
236
248
  checkRelations(types, byName, errors)
237
249
  for (const type of types) readIndexes(type, values, errors)
238
250
  for (const type of types) checkComputed(type, byName, errors)
251
+ for (const type of types) checkRestrictedDependencies(type, byName, errors)
239
252
 
240
253
  if (errors.length > 0) throw new SchemaError(errors)
241
254
  for (const type of types) delete type._gql
@@ -358,6 +371,25 @@ function checkComputed(type, byName, errors) {
358
371
  for (const name of local.keys()) visit(name, [])
359
372
  }
360
373
 
374
+ // A computed field that depends on a @restricted field would reveal it: it must be @restricted too (D58).
375
+ // A path is restricted when it ends on a restricted field, goes through a restricted relation, or goes through a
376
+ // list relation whose foreign key is restricted (the list tells which objects point here).
377
+ function checkRestrictedDependencies(type, byName, errors) {
378
+ for (const computed of type.computed) {
379
+ if (type.restricted.includes(computed.name)) continue
380
+ for (const path of computed.depends) {
381
+ const { steps, end, last, error } = resolvePath(type, path.split('.'), byName)
382
+ if (error !== undefined) continue
383
+ const through = steps.some(step => step.kind === 'parent'
384
+ ? step.from.restricted.includes(step.relation.name)
385
+ : step.to.restricted.includes(step.relation.fk))
386
+ if (through || (last !== undefined && end.restricted.includes(last))) {
387
+ errors.push(`${type.name}.${computed.name}: depends on "${path}", which is @restricted: add @restricted to ${computed.name}`)
388
+ }
389
+ }
390
+ }
391
+ }
392
+
361
393
  /**
362
394
  * Follows a dependency path from a type.
363
395
  * @returns {{steps?: {relation: Parent | Child, kind: 'parent' | 'child', from: Type, to: Type}[], end?: Type, last?: string, error?: string}}