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.
@@ -0,0 +1,71 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { readSchema } from './model.js'
3
+ import { onDeleteOf } from './generate/classes.js'
4
+
5
+ // ramdb2-cli plantuml: the entity-relationship diagram of the persistent types, in PlantUML (spec section 12).
6
+ // One package per @group, one entity per table, one association per foreign key, with its deletion policy.
7
+
8
+ /**
9
+ * @param {string | string[]} schema schema file(s)
10
+ * @returns {string} the PlantUML source
11
+ */
12
+ export function plantuml(schema) {
13
+ const sources = (Array.isArray(schema) ? schema : [schema]).map(path => readFileSync(path, 'utf8'))
14
+ return diagram(readSchema(sources.join('\n')))
15
+ }
16
+
17
+ /**
18
+ * @param {import('./model.js').Model} model
19
+ * @returns {string}
20
+ */
21
+ export function diagram(model) {
22
+ const lines = [
23
+ '@startuml',
24
+ "' Generated by ramdb2-cli plantuml from the schema",
25
+ 'hide circle',
26
+ 'hide methods',
27
+ 'skinparam class {',
28
+ ' BackgroundColor<<table>> #FFF4E0',
29
+ ' BorderColor<<table>> #B07020',
30
+ '}',
31
+ '',
32
+ ]
33
+ // Types without @group first, then one package per group, in alphabetical order
34
+ const groups = new Map()
35
+ for (const type of model.types) {
36
+ const group = type.group ?? ''
37
+ if (!groups.has(group)) groups.set(group, [])
38
+ groups.get(group).push(type)
39
+ }
40
+ for (const group of [...groups.keys()].sort()) {
41
+ const indent = group === '' ? '' : ' '
42
+ if (group !== '') lines.push(`package "${group}" {`)
43
+ for (const type of groups.get(group)) lines.push(...entity(type, model).map(line => line === '' ? '' : indent + line))
44
+ if (group !== '') lines.push('}', '')
45
+ }
46
+ for (const type of model.types) {
47
+ for (const parent of type.parents) {
48
+ const target = model.byName.get(parent.target)
49
+ const policy = onDeleteOf(parent, type, model)
50
+ // One target, required or not; any number of objects pointing to it
51
+ lines.push(`${target.table} ${parent.required ? '||' : '|o'}--o{ ${type.table} : ${parent.fk}${policy === 'NOTHING' ? '' : ` (${policy})`}`)
52
+ }
53
+ }
54
+ lines.push('@enduml')
55
+ return lines.join('\n') + '\n'
56
+ }
57
+
58
+ function entity(type, model) {
59
+ const lines = [`entity ${type.table} <<table>> {`, ' <b>id</b> : Int', ' --']
60
+ for (const parent of type.parents) {
61
+ lines.push(` <i>${parent.fk}</i> : Int → ${model.byName.get(parent.target).table}${parent.required ? '' : ' (0 = none)'}`)
62
+ }
63
+ for (const field of type.fields) lines.push(` ${field.name} : ${field.gqlType}${field.nonNull ? '!' : ''}`)
64
+ if (type.computed.length > 0 || type.transient.length > 0) {
65
+ lines.push(' .. not stored ..')
66
+ for (const computed of type.computed) lines.push(` <color:#606060>${computed.name} : ${computed.display} (computed)</color>`)
67
+ for (const field of type.transient) lines.push(` <color:#606060>${field.name} : ${field.display}</color>`)
68
+ }
69
+ lines.push('}', '')
70
+ return lines
71
+ }
package/src/query.js ADDED
@@ -0,0 +1,159 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { join } from 'node:path'
4
+
5
+ // ramdb2-cli query <profile> '<graphql>' (D41): sends a GraphQL query to a server, with an authentication token
6
+ // obtained when needed and kept on disk until it expires. The password is never stored: it comes from
7
+ // RAMDB2_CLI_PASSWORD or is asked on the terminal.
8
+ //
9
+ // Profile, ~/.config/ramdb2-cli/<profile>.json:
10
+ // { "url": "http://localhost:4000", "login": "manu",
11
+ // "auth": { "query": "query($login: String!, $password: String!) { newToken(login: $login, password: $password) }",
12
+ // "header": "authorization", "prefix": "" } }
13
+ // Without "auth", the query is sent without token.
14
+
15
+ const EXPIRY_MARGIN = 30_000 // a token about to expire is renewed
16
+
17
+ /**
18
+ * @typedef {object} QueryOptions
19
+ * @property {string} profile name of the profile
20
+ * @property {string} query GraphQL query
21
+ * @property {object} [variables]
22
+ * @property {() => Promise<string>} [password] asks the password, when a token is needed
23
+ * @property {string} [configDir] ~/.config/ramdb2-cli by default
24
+ * @property {string} [cacheDir] ~/.cache/ramdb2-cli by default
25
+ */
26
+
27
+ /**
28
+ * @param {QueryOptions} options
29
+ * @returns {Promise<{status: number, body: any}>} the HTTP status and the JSON response
30
+ */
31
+ export async function query(options) {
32
+ const { configDir = defaultDir('XDG_CONFIG_HOME', '.config'), cacheDir = defaultDir('XDG_CACHE_HOME', '.cache') } = options
33
+ const profile = readProfile(configDir, options.profile)
34
+ const tokenFile = join(cacheDir, `${options.profile}.token`)
35
+ const send = token => post(profile, { query: options.query, variables: options.variables }, token)
36
+
37
+ if (profile.auth === undefined) return send(undefined)
38
+ let token = readToken(tokenFile)
39
+ let fresh = false
40
+ if (token === undefined) {
41
+ token = await newToken(profile, options.password, tokenFile)
42
+ fresh = true
43
+ }
44
+ const response = await send(token)
45
+ // A token refused by the server (revoked, server restarted with another key): one new try
46
+ if (!fresh && isUnauthenticated(response)) {
47
+ rmSync(tokenFile, { force: true })
48
+ return send(await newToken(profile, options.password, tokenFile))
49
+ }
50
+ return response
51
+ }
52
+
53
+ function defaultDir(variable, fallback) {
54
+ return join(process.env[variable] ?? join(homedir(), fallback), 'ramdb2-cli')
55
+ }
56
+
57
+ function readProfile(configDir, name) {
58
+ if (!/^[A-Za-z0-9_.-]+$/.test(name)) throw new Error(`Invalid profile name ${name}`)
59
+ const path = join(configDir, `${name}.json`)
60
+ if (!existsSync(path)) throw new Error(`No profile ${name}: create ${path} with { "url": ..., "login": ..., "auth": { "query": ... } }`)
61
+ const profile = JSON.parse(readFileSync(path, 'utf8'))
62
+ if (typeof profile.url !== 'string') throw new Error(`${path}: "url" is missing`)
63
+ if (profile.auth !== undefined && typeof profile.auth.query !== 'string') throw new Error(`${path}: "auth.query" is missing`)
64
+ return profile
65
+ }
66
+
67
+ // The cached token, if it is not expired
68
+ function readToken(file) {
69
+ if (!existsSync(file)) return undefined
70
+ const token = readFileSync(file, 'utf8').trim()
71
+ const expiry = expiryOf(token)
72
+ if (token === '' || (expiry !== undefined && expiry < Date.now() + EXPIRY_MARGIN)) return undefined
73
+ return token
74
+ }
75
+
76
+ /**
77
+ * Expiry of a JWT, in milliseconds: the standard `exp` (seconds), or `expiration` (milliseconds, ilife).
78
+ * Undefined when the token says nothing: it is then used until the server refuses it.
79
+ * @param {string} token
80
+ * @returns {number | undefined}
81
+ */
82
+ export function expiryOf(token) {
83
+ try {
84
+ const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'))
85
+ if (typeof payload.exp === 'number') return payload.exp * 1000
86
+ if (typeof payload.expiration === 'number') return payload.expiration
87
+ } catch {
88
+ // not a JWT
89
+ }
90
+ return undefined
91
+ }
92
+
93
+ async function newToken(profile, askPassword = promptPassword, file) {
94
+ const password = process.env.RAMDB2_CLI_PASSWORD ?? await askPassword()
95
+ const { status, body } = await post(profile, { query: profile.auth.query, variables: { login: profile.login, password } })
96
+ if (body?.errors !== undefined || body?.data == null) {
97
+ throw new Error(`Login refused (HTTP ${status}): ${body?.errors?.map(e => e.message).join(', ') ?? 'no data'}`)
98
+ }
99
+ // The token is the only value of the response: { data: { newToken: "..." } }
100
+ const token = Object.values(body.data)[0]
101
+ if (typeof token !== 'string' || token === '') throw new Error('The login query did not return a token')
102
+ const dir = join(file, '..')
103
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
104
+ writeFileSync(file, token, { mode: 0o600 })
105
+ chmodSync(file, 0o600)
106
+ return token
107
+ }
108
+
109
+ async function post(profile, payload, token) {
110
+ const headers = { 'content-type': 'application/json' }
111
+ if (token !== undefined) headers[profile.auth.header ?? 'authorization'] = (profile.auth.prefix ?? '') + token
112
+ const response = await fetch(profile.url, { method: 'POST', headers, body: JSON.stringify(payload) })
113
+ const text = await response.text()
114
+ let body
115
+ try {
116
+ body = JSON.parse(text)
117
+ } catch {
118
+ body = text
119
+ }
120
+ return { status: response.status, body }
121
+ }
122
+
123
+ function isUnauthenticated({ status, body }) {
124
+ return status === 401 || (Array.isArray(body?.errors) && body.errors.some(e => e.extensions?.code === 'UNAUTHENTICATED'))
125
+ }
126
+
127
+ // Asks the password on the terminal, without echoing it
128
+ function promptPassword() {
129
+ const input = process.stdin
130
+ if (!input.isTTY) return Promise.reject(new Error('A password is needed: set RAMDB2_CLI_PASSWORD, or run in a terminal'))
131
+ process.stderr.write('Password: ')
132
+ input.setRawMode(true)
133
+ input.resume()
134
+ input.setEncoding('utf8')
135
+ return new Promise((resolve, reject) => {
136
+ let password = ''
137
+ const onData = chunk => {
138
+ for (const char of chunk) {
139
+ if (char === '\r' || char === '\n') {
140
+ done()
141
+ return resolve(password)
142
+ }
143
+ if (char === '\u0003') {
144
+ done()
145
+ return reject(new Error('Cancelled'))
146
+ }
147
+ if (char === '\u007f') password = password.slice(0, -1)
148
+ else password += char
149
+ }
150
+ }
151
+ const done = () => {
152
+ input.off('data', onData)
153
+ input.setRawMode(false)
154
+ input.pause()
155
+ process.stderr.write('\n')
156
+ }
157
+ input.on('data', onData)
158
+ })
159
+ }