@better-forge/config-as-code 0.0.0-stage → 0.1.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,199 @@
1
+ export type Json = Record<string, unknown>
2
+ export const isObject = (value: unknown): value is Json => !!value && typeof value === 'object' && !Array.isArray(value)
3
+
4
+ export interface ConfigProblem { path: string; message: string }
5
+
6
+ /** The file is not valid; `problems` lists what is wrong with it, not just the first thing. */
7
+ export class ConfigInvalidError extends Error {
8
+ constructor(readonly problems: ConfigProblem[]) {
9
+ super(problems[0] ? `${problems[0].path}: ${problems[0].message}` : 'Invalid configuration')
10
+ }
11
+ }
12
+
13
+ /** Most problems a file reports: the first ones are the ones to fix first. */
14
+ const MAX_PROBLEMS = 100
15
+
16
+ /** Collects what is wrong with a file. */
17
+ export class Problems {
18
+ readonly list: ConfigProblem[] = []
19
+ add = (path: string, message: string) => { if (this.list.length < MAX_PROBLEMS) this.list.push({ path, message }) }
20
+ get any() { return this.list.length > 0 }
21
+ }
22
+
23
+ /** Shortens text that comes from a request before it is repeated in an answer, so an error cannot be made to echo a megabyte. */
24
+ export function clip(value: string, max = 80): string {
25
+ return value.length > max ? `${value.slice(0, max)}…` : value
26
+ }
27
+
28
+ /** Whether `value` nests objects or lists deeper than `max` levels. Checked without recursion, so it cannot overflow the stack. */
29
+ export function nestedDeeperThan(value: unknown, max: number): boolean {
30
+ const pending: Array<[unknown, number]> = [[value, 0]]
31
+ while (pending.length) {
32
+ const [current, depth] = pending.pop()!
33
+ if (!current || typeof current !== 'object') continue
34
+ if (depth >= max) return true
35
+ for (const inner of Object.values(current)) pending.push([inner, depth + 1])
36
+ }
37
+ return false
38
+ }
39
+
40
+ /** The same value written with its keys in a fixed order, so equal settings compare equal whatever their order. */
41
+ export function canonical(value: unknown): string {
42
+ return JSON.stringify(value, (_key, inner) => isObject(inner) ? Object.fromEntries(Object.keys(inner).sort().map((key) => [key, inner[key]])) : inner)
43
+ }
44
+
45
+ /** Orders documents by key. A tie sorts the second one first, which never happens: keys are unique. */
46
+ export const byKey = (a: { key: string }, b: { key: string }) => (a.key < b.key ? -1 : 1)
47
+
48
+ /** Reports every field of `entry` that is not in `allowed`. */
49
+ export function unknownFields(entry: Json, allowed: readonly string[], path: string, problems: Problems): void {
50
+ for (const field of Object.keys(entry)) if (!allowed.includes(field)) problems.add(`${path}.${clip(field)}`, 'is not a known setting')
51
+ }
52
+
53
+ /** Where a name the parser would treat specially (`__proto__`) appears in a document, or null. Walks without recursion. */
54
+ export function forbiddenNameAt(document: unknown, label: string): string | null {
55
+ const pending: Array<[unknown, string]> = [[document, label]]
56
+ while (pending.length) {
57
+ const [value, path] = pending.pop()!
58
+ if (!value || typeof value !== 'object') continue
59
+ if (!Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, '__proto__')) return `${path}.__proto__`
60
+ const entries: Array<[string, unknown]> = Array.isArray(value) ? value.map((item, index) => [`[${index}]`, item]) : Object.entries(value)
61
+ for (const [name, inner] of entries) pending.push([inner, name.startsWith('[') ? `${path}${name}` : `${path}.${clip(name)}`])
62
+ }
63
+ return null
64
+ }
65
+
66
+ /** A dependency cycle among `edges` (key -> keys it depends on), as `a → b → a`, or null. */
67
+ export function findCycle(edges: Map<string, string[]>): string | null {
68
+ const done = new Set<string>()
69
+ const stack: string[] = []
70
+ const visit = (key: string): string | null => {
71
+ const at = stack.indexOf(key)
72
+ if (at >= 0) return [...stack.slice(at), key].join(' → ')
73
+ if (done.has(key)) return null
74
+ stack.push(key)
75
+ for (const next of edges.get(key) ?? []) {
76
+ const cycle = visit(next)
77
+ if (cycle) return cycle
78
+ }
79
+ stack.pop()
80
+ done.add(key)
81
+ return null
82
+ }
83
+ for (const key of edges.keys()) {
84
+ const cycle = visit(key)
85
+ if (cycle) return cycle
86
+ }
87
+ return null
88
+ }
89
+
90
+ // ── References to vault secrets ──────────────────────────────────────────────
91
+
92
+ /** The vaults and secrets of an installation, as far as a file needs to name them. */
93
+ export interface VaultRows {
94
+ vaults: ReadonlyArray<{ id: number; name: string }>
95
+ secrets: ReadonlyArray<{ id: number; vaultId: number; name: string }>
96
+ }
97
+
98
+ /** A vault secret named instead of numbered, so the file means the same on another installation. */
99
+ export interface ConfigVaultRef { vault: string; secret: string; fieldMapping?: Record<string, string> }
100
+
101
+ /** `{ vault: 'Production', secret: 'db-login' }` back to the ids this installation knows them by. */
102
+ export function createVaultResolver(rows: VaultRows) {
103
+ const vaultsByName = new Map<string, number[]>()
104
+ for (const vault of rows.vaults) vaultsByName.set(vault.name, [...(vaultsByName.get(vault.name) ?? []), vault.id])
105
+ const secretId = new Map(rows.secrets.map((secret) => [`${secret.vaultId}:${secret.name}`, secret.id]))
106
+
107
+ return function resolve(value: unknown, path: string, problems: Problems): unknown {
108
+ if (Array.isArray(value)) return value.map((item, index) => resolve(item, `${path}[${index}]`, problems))
109
+ if (!isObject(value)) return value
110
+ return Object.fromEntries(Object.entries(value).map(([key, inner]) => {
111
+ if (key !== 'vault') return [key, resolve(inner, `${path}.${key}`, problems)]
112
+ const at = `${path}.vault`
113
+ if (!isObject(inner) || typeof inner['vault'] !== 'string' || typeof inner['secret'] !== 'string') {
114
+ problems.add(at, 'must name the vault and the secret: { vault: <name>, secret: <name> }')
115
+ return [key, inner]
116
+ }
117
+ if ('vaultId' in inner || 'secretId' in inner) problems.add(at, 'a configuration file names a vault secret, it does not use numeric ids')
118
+ const found = vaultsByName.get(inner['vault']) ?? []
119
+ if (found.length !== 1) {
120
+ problems.add(at, found.length === 0
121
+ ? (inner['vault'].startsWith('(deleted') ? `${clip(inner['vault'])} refers to a vault that no longer exists` : `unknown vault "${clip(inner['vault'])}"`)
122
+ : `more than one vault is named "${clip(inner['vault'])}"; rename one of them`)
123
+ return [key, inner]
124
+ }
125
+ const secret = secretId.get(`${found[0]}:${inner['secret']}`)
126
+ if (secret === undefined) {
127
+ problems.add(at, inner['secret'].startsWith('(deleted') ? `${clip(inner['secret'])} refers to a secret that no longer exists` : `vault "${clip(inner['vault'])}" has no secret "${clip(inner['secret'])}"`)
128
+ return [key, inner]
129
+ }
130
+ return [key, { vaultId: found[0], secretId: secret, ...(isObject(inner['fieldMapping']) ? { fieldMapping: inner['fieldMapping'] } : {}) }]
131
+ }))
132
+ }
133
+ }
134
+
135
+ /** The file would refer to something it cannot name unambiguously, so it could not be read back. */
136
+ export class ConfigExportError extends Error {}
137
+
138
+ const deleted = (what: string, id: unknown) => `(deleted ${what} ${String(id)})`
139
+
140
+ function isVaultRef(value: unknown): value is { vaultId: number; secretId: number; fieldMapping?: unknown } {
141
+ return isObject(value) && typeof value['vaultId'] === 'number' && typeof value['secretId'] === 'number'
142
+ }
143
+
144
+ /** Replaces every `vault: { vaultId, secretId }` reference in a config with the names of the vault and secret. */
145
+ export function createVaultExporter(rows: VaultRows) {
146
+ const nameCount = new Map<string, number>()
147
+ for (const vault of rows.vaults) nameCount.set(vault.name, (nameCount.get(vault.name) ?? 0) + 1)
148
+ const vaultName = new Map(rows.vaults.map((vault) => [vault.id, vault.name]))
149
+ const secret = new Map(rows.secrets.map((row) => [row.id, row]))
150
+
151
+ function exportRef(ref: { vaultId: number; secretId: number; fieldMapping?: unknown }): ConfigVaultRef {
152
+ const vault = vaultName.get(ref.vaultId)
153
+ const found = secret.get(ref.secretId)
154
+ if (vault !== undefined && (nameCount.get(vault) ?? 0) > 1) {
155
+ throw new ConfigExportError(`More than one vault is named "${vault}", so a reference to it cannot be exported. Rename one of them.`)
156
+ }
157
+ return {
158
+ vault: vault ?? deleted('vault', ref.vaultId),
159
+ secret: found && found.vaultId === ref.vaultId ? found.name : deleted('secret', ref.secretId),
160
+ ...(isObject(ref.fieldMapping) ? { fieldMapping: ref.fieldMapping as Record<string, string> } : {}),
161
+ }
162
+ }
163
+
164
+ return function exportRefs(value: unknown): unknown {
165
+ if (Array.isArray(value)) return value.map((item) => exportRefs(item))
166
+ if (!isObject(value)) return value
167
+ return Object.fromEntries(Object.entries(value).map(([key, inner]) =>
168
+ [key, key === 'vault' && isVaultRef(inner) ? exportRef(inner) : exportRefs(inner)]))
169
+ }
170
+ }
171
+
172
+ // ── Fields every kind of document reads the same way ─────────────────────────
173
+
174
+ /** A list of keys (`items: [a, b]`), without repeats; problems are reported at `path`. */
175
+ export function keyList(value: unknown, path: string, problems: Problems, isValidKey: (key: unknown) => boolean): string[] {
176
+ if (value === undefined) return []
177
+ if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) {
178
+ problems.add(path, 'must be a list of keys')
179
+ return []
180
+ }
181
+ for (const key of value) if (!isValidKey(key)) problems.add(path, `"${clip(key)}" is not a valid key`)
182
+ return [...new Set(value as string[])]
183
+ }
184
+
185
+ /** The key of a document, or '' (with a problem) when it has none that is usable; a repeat within `seen` is a problem too. */
186
+ export function documentKey(
187
+ entry: Json, path: string, seen: Set<string>, problems: Problems,
188
+ keys: { isValid: (key: unknown) => boolean; error: string },
189
+ ): string {
190
+ const key = entry['key']
191
+ if (!keys.isValid(key)) {
192
+ problems.add(`${path}.key`, key === undefined ? 'is required' : keys.error)
193
+ return ''
194
+ }
195
+ const text = key as string
196
+ if (seen.has(text)) problems.add(`${path}.key`, `"${clip(text)}" is used by another document`)
197
+ seen.add(text)
198
+ return text
199
+ }
package/src/engine.ts ADDED
@@ -0,0 +1,258 @@
1
+ import { clip, ConfigInvalidError, createVaultExporter, createVaultResolver, forbiddenNameAt, isObject, Problems, type Json, type VaultRows } from './document.js'
2
+
3
+ export type ChangeAction = 'create' | 'update' | 'delete' | 'unchanged'
4
+
5
+ export interface ConfigChange {
6
+ kind: string
7
+ /** The key of the object the document describes. */
8
+ key?: string
9
+ action: ChangeAction
10
+ /** For an update: which settings differ. Never their values, which may be secrets. */
11
+ fields?: string[]
12
+ }
13
+
14
+ export interface ImportResult {
15
+ dryRun: boolean
16
+ /** `delete` is present only for an import with `prune`. */
17
+ summary: Record<'create' | 'update' | 'unchanged', number> & { delete?: number }
18
+ changes: ConfigChange[]
19
+ }
20
+
21
+ /** What one change did, for the audit log. */
22
+ export interface AuditEntry { action: 'create' | 'update' | 'delete'; entity: string; id: number | string; name: string; diff: Json }
23
+
24
+ export interface ImportOptions<Actor> {
25
+ dryRun: boolean
26
+ actor: Actor
27
+ /** Set when the request is made with an API token: what it may do is decided per kind. */
28
+ token?: { scopes: readonly string[] } | undefined
29
+ /** Also delete the objects of the kinds the documents hold that the documents do not mention. Off by default. */
30
+ prune?: boolean
31
+ }
32
+
33
+ /** What a kind sees while it reads the documents of a file. */
34
+ export interface PlanContext<State> {
35
+ state: State
36
+ token: { scopes: readonly string[] } | undefined
37
+ problems: Problems
38
+ /** `{ vault: <name>, secret: <name> }` references in a config, turned into the ids of this installation. */
39
+ resolveVaults: (value: unknown, path: string) => unknown
40
+ /** The documents of a kind the file holds, as that kind parsed them. */
41
+ desired: (kind: string) => unknown[]
42
+ /** The keys of a kind that an import with `prune` deletes: they do not exist afterwards, so nothing may link to them. */
43
+ removed: (kind: string) => ReadonlySet<string>
44
+ }
45
+
46
+ /** What a kind sees while it writes. */
47
+ export interface ApplyContext<State> {
48
+ state: State
49
+ now: number
50
+ /** Ids by key, per kind: the objects that exist now, plus those created so far in this run. */
51
+ ids: (kind: string) => Map<string, number>
52
+ }
53
+
54
+ /**
55
+ * One kind of document. `parse` reads a document of the kind (reporting problems), `plan` compares what the file
56
+ * holds with the installation and says what would change, `apply` writes it, `link` runs after every kind is written
57
+ * (for references to objects that might be created later in the same file), `export` writes the kind out.
58
+ */
59
+ export interface ConfigKind<State, ExportState, Desired = any, Planned = any> { // eslint-disable-line @typescript-eslint/no-explicit-any
60
+ kind: string
61
+ parse: (entry: Json, index: number, seen: Set<string>, problems: Problems) => Desired | null
62
+ plan: (desired: Desired[], ctx: PlanContext<State>) => { planned: Planned; changes: ConfigChange[] }
63
+ /** The ids of the objects of this kind that exist, by key. */
64
+ existingIds: (state: State) => Map<string, number>
65
+ apply: (planned: Planned, ctx: ApplyContext<State>) => Promise<AuditEntry[]>
66
+ link?: (planned: Planned, ctx: ApplyContext<State>) => Promise<void>
67
+ /** Deletes the objects with these keys, and whatever links to them. A kind without it is never pruned. */
68
+ remove?: (keys: string[], ctx: ApplyContext<State>) => Promise<AuditEntry[]>
69
+ /** The documents of this kind, sorted by key. `only` limits them to one key (and nothing else is written out). */
70
+ export: (state: ExportState, ctx: ExportContext) => Json[]
71
+ }
72
+
73
+ export interface ExportContext {
74
+ /** Replaces the vault references of a config with the names of the vault and secret. */
75
+ exportVaultRefs: (value: unknown) => unknown
76
+ /** The rows to write out: all of them, or only the one asked for. */
77
+ wanted: <T extends { key: string }>(rows: T[], kind: string) => T[]
78
+ /** Whether the kind is part of this export (a kind may be left out for a reader who may not see it). */
79
+ included: (kind: string) => boolean
80
+ }
81
+
82
+ export interface ConfigEngineOptions<State, ExportState, Actor> {
83
+ /** The kinds, in the order messages name them. */
84
+ kinds: ReadonlyArray<ConfigKind<State, ExportState>>
85
+ /** The order kinds are planned, written and exported in (kind names); defaults to `kinds`. */
86
+ order?: readonly string[]
87
+ /** Reads what the installation holds. Called inside the transaction when the file is applied. */
88
+ loadState: () => Promise<State>
89
+ /** Reads what an export needs; a kind not in `included` need not be read. */
90
+ loadExportState: (included: ReadonlySet<string>) => Promise<ExportState>
91
+ vaultRows: (state: State) => VaultRows
92
+ exportVaultRows: (state: ExportState) => VaultRows
93
+ /** Runs `work` so that everything it writes happens, or none of it does. */
94
+ transaction: <T>(work: () => Promise<T>) => Promise<T>
95
+ audit: { write: (actor: Actor, action: 'create' | 'update' | 'delete', entity: string, id: number | string | null, name: string, diff?: Json) => Promise<void> }
96
+ /** Runs once after a successful apply that changed something, before the audit entries are written. */
97
+ afterApply?: () => Promise<void>
98
+ /** Entity type of the summary entry written to the audit log. */
99
+ auditEntity?: string
100
+ }
101
+
102
+ /** Makes the installation match the documents, completely or not at all, and writes it out again as documents. */
103
+ export function createConfigEngine<State, ExportState, Actor>(options: ConfigEngineOptions<State, ExportState, Actor>) {
104
+ const kinds = new Map(options.kinds.map((kind) => [kind.kind, kind]))
105
+ const names = options.kinds.map((kind) => kind.kind)
106
+ const order = (options.order ?? names).map((name) => kinds.get(name)!)
107
+
108
+ /** The kinds a list of documents contains, so that the caller can check it may import each. Documents of no known kind are ignored here. */
109
+ function kindsIn(documents: unknown[]): Set<string> {
110
+ const found = new Set<string>()
111
+ for (const document of documents) {
112
+ if (isObject(document) && names.includes(document['kind'] as string)) found.add(document['kind'] as string)
113
+ }
114
+ return found
115
+ }
116
+
117
+ function parseDocuments(documents: unknown[], problems: Problems): Map<string, unknown[]> {
118
+ const desired = new Map<string, unknown[]>(names.map((name) => [name, []]))
119
+ const seenKeys = new Map<string, Set<string>>(names.map((name) => [name, new Set()]))
120
+
121
+ documents.forEach((document, index) => {
122
+ const label = `document ${index + 1}`
123
+ const poisoned = forbiddenNameAt(document, label)
124
+ if (poisoned) { problems.add(poisoned, '"__proto__" is not allowed as a name'); return }
125
+ if (!isObject(document)) { problems.add(label, 'must be an object with a kind'); return }
126
+
127
+ const kind = kinds.get(document['kind'] as string)
128
+ if (!kind) {
129
+ problems.add(`${label}.kind`, document['kind'] === undefined
130
+ ? `is required: one of ${names.join(', ')}`
131
+ : `"${clip(String(document['kind']))}" is not a kind; use one of ${names.join(', ')}`)
132
+ return
133
+ }
134
+ const parsed = kind.parse(document, index, seenKeys.get(kind.kind)!, problems)
135
+ if (parsed) desired.get(kind.kind)!.push(parsed)
136
+ })
137
+ return desired
138
+ }
139
+
140
+ /** The keys to delete, per kind. A kind with no document in the file is left alone, so an empty file prunes nothing. */
141
+ function stale(state: State, desired: Map<string, unknown[]>): Map<string, string[]> {
142
+ const found = new Map<string, string[]>()
143
+ for (const kind of order) {
144
+ const documents = desired.get(kind.kind) ?? []
145
+ if (!kind.remove || documents.length === 0) continue
146
+ const wanted = new Set(documents.map((document) => (document as { key: string }).key))
147
+ const keys = [...kind.existingIds(state).keys()].filter((key) => !wanted.has(key)).sort()
148
+ if (keys.length) found.set(kind.kind, keys)
149
+ }
150
+ return found
151
+ }
152
+
153
+ function plan(state: State, desired: Map<string, unknown[]>, token: ImportOptions<Actor>['token'], prune: boolean) {
154
+ const problems = new Problems()
155
+ const resolve = createVaultResolver(options.vaultRows(state))
156
+ const removals = prune ? stale(state, desired) : new Map<string, string[]>()
157
+ const ctx: PlanContext<State> = {
158
+ state, token, problems,
159
+ resolveVaults: (value, path) => resolve(value, path, problems),
160
+ desired: (kind) => desired.get(kind) ?? [],
161
+ removed: (kind) => new Set(removals.get(kind) ?? []),
162
+ }
163
+ const planned = new Map<string, unknown>()
164
+ const changes: ConfigChange[] = []
165
+ for (const kind of order) {
166
+ const result = kind.plan(desired.get(kind.kind) ?? [], ctx)
167
+ planned.set(kind.kind, result.planned)
168
+ changes.push(...result.changes)
169
+ }
170
+ if (problems.any) throw new ConfigInvalidError(problems.list)
171
+ for (const kind of order) for (const key of removals.get(kind.kind) ?? []) changes.push({ kind: kind.kind, key, action: 'delete' })
172
+ return { planned, changes, removals }
173
+ }
174
+
175
+ async function execute(state: State, planned: Map<string, unknown>, removals: Map<string, string[]>): Promise<AuditEntry[]> {
176
+ const ids = new Map(names.map((name) => [name, kinds.get(name)!.existingIds(state)]))
177
+ const ctx: ApplyContext<State> = { state, now: Date.now(), ids: (kind) => ids.get(kind)! }
178
+ const audit: AuditEntry[] = []
179
+ for (const kind of order) audit.push(...await kind.apply(planned.get(kind.kind), ctx))
180
+ for (const kind of order) await kind.link?.(planned.get(kind.kind), ctx)
181
+ // Last, and in the reverse order, so that what links to a kind is deleted before the kind.
182
+ for (const kind of [...order].reverse()) {
183
+ const keys = removals.get(kind.kind)
184
+ if (keys) audit.push(...await kind.remove!(keys, ctx))
185
+ }
186
+ return audit
187
+ }
188
+
189
+ function summarise(changes: ConfigChange[], prune: boolean): ImportResult['summary'] {
190
+ const summary: Record<ChangeAction, number> = { create: 0, update: 0, delete: 0, unchanged: 0 }
191
+ for (const change of changes) summary[change.action] += 1
192
+ if (!prune) return { create: summary.create, update: summary.update, unchanged: summary.unchanged }
193
+ return summary
194
+ }
195
+
196
+ /**
197
+ * Makes the installation match the documents: an object whose key exists is updated, one whose key does not is created.
198
+ * Nothing is removed unless `prune` is set. Everything is checked before anything is written, and the writes are one transaction, so a
199
+ * stream is applied completely or not at all. With `dryRun` nothing is written and the result says what would happen.
200
+ */
201
+ async function importDocuments(documents: unknown[], importOptions: ImportOptions<Actor>): Promise<ImportResult> {
202
+ const problems = new Problems()
203
+ const desired = parseDocuments(documents, problems)
204
+ if (problems.any) throw new ConfigInvalidError(problems.list)
205
+
206
+ const result = (changes: ConfigChange[]): ImportResult => ({ dryRun: importOptions.dryRun, summary: summarise(changes, !!importOptions.prune), changes })
207
+
208
+ if (importOptions.dryRun) return result(plan(await options.loadState(), desired, importOptions.token, !!importOptions.prune).changes)
209
+
210
+ const { changes, audit } = await options.transaction(async () => {
211
+ const state = await options.loadState()
212
+ const { planned, changes, removals } = plan(state, desired, importOptions.token, !!importOptions.prune)
213
+ const audit = changes.some((change) => change.action !== 'unchanged') ? await execute(state, planned, removals) : []
214
+ return { changes, audit }
215
+ })
216
+
217
+ // The changes are committed. A failure past this point must not turn a successful import into an error (the
218
+ // client would retry, and a second apply is a no-op), so it is logged instead.
219
+ if (audit.length) {
220
+ try {
221
+ await options.afterApply?.()
222
+ for (const entry of audit) await options.audit.write(importOptions.actor, entry.action, entry.entity, entry.id, entry.name, entry.diff)
223
+ const summary = summarise(changes, !!importOptions.prune)
224
+ await options.audit.write(importOptions.actor, 'update', options.auditEntity ?? 'config', null, 'Configuration import', {
225
+ created: summary.create, updated: summary.update, ...(importOptions.prune ? { deleted: summary.delete ?? 0 } : {}), unchanged: summary.unchanged,
226
+ })
227
+ } catch (error) {
228
+ console.error('[config] Imported, but could not finish the follow-up work:', error)
229
+ }
230
+ }
231
+ return result(changes)
232
+ }
233
+
234
+ /**
235
+ * The documents of every kind, in a fixed order that does not depend on this installation's numeric ids. Secrets are
236
+ * masked by the kinds, and runtime state is left out. `only` writes out one document; `included` leaves out kinds.
237
+ */
238
+ async function exportDocuments(only?: { kind: string; key: string }, exportOptions: { included?: ReadonlySet<string> } = {}): Promise<Json[]> {
239
+ const included = exportOptions.included ?? new Set(names)
240
+ const state = await options.loadExportState(included)
241
+ const ctx: ExportContext = {
242
+ exportVaultRefs: createVaultExporter(options.exportVaultRows(state)),
243
+ // Only the rows asked for are written out, so a vault name that is ambiguous for some other object does not matter.
244
+ wanted: (rows, kind) => (only ? rows.filter((row) => only.kind === kind && row.key === only.key) : rows),
245
+ included: (kind) => included.has(kind),
246
+ }
247
+ return order.filter((kind) => included.has(kind.kind)).flatMap((kind) => kind.export(state, ctx))
248
+ }
249
+
250
+ /** The one document of a kind and key, or undefined when there is none. */
251
+ function pickDocument(documents: Json[], kind: string, key: string | undefined): Json | undefined {
252
+ return documents.find((document) => document['kind'] === kind && document['key'] === key)
253
+ }
254
+
255
+ return { kinds: names, kindsIn, importDocuments, exportDocuments, pickDocument }
256
+ }
257
+
258
+ export type ConfigEngine<State, ExportState, Actor> = ReturnType<typeof createConfigEngine<State, ExportState, Actor>>
package/src/index.ts ADDED
@@ -0,0 +1,16 @@
1
+ export {
2
+ backfillKeys, ENTITY_KEY_ERROR, ENTITY_KEY_PATTERN, isValidEntityKey, keyForNew, randomEntityKey, slugifyKey,
3
+ type KeyOwner, type KeyResult,
4
+ } from './keys.js'
5
+ export { MAX_DOCUMENTS, readDocuments, toYaml, toYamlStream } from './yaml.js'
6
+ export {
7
+ byKey, canonical, clip, ConfigExportError, ConfigInvalidError, createVaultExporter, createVaultResolver, documentKey, findCycle, forbiddenNameAt,
8
+ isObject, keyList, nestedDeeperThan, Problems, unknownFields,
9
+ type ConfigProblem, type ConfigVaultRef, type Json, type VaultRows,
10
+ } from './document.js'
11
+ export {
12
+ createConfigEngine,
13
+ type ApplyContext, type AuditEntry, type ChangeAction, type ConfigChange, type ConfigEngine, type ConfigEngineOptions, type ConfigKind,
14
+ type ExportContext, type ImportOptions, type ImportResult, type PlanContext,
15
+ } from './engine.js'
16
+ export { createConfigRoutes, type ConfigCaller, type ConfigRoutesOptions, type KindAccess } from './routes.js'
package/src/keys.ts ADDED
@@ -0,0 +1,64 @@
1
+ import type { DatabaseSync } from 'node:sqlite'
2
+ import { randomBytes } from 'node:crypto'
3
+
4
+ /** Keys appear in config files and URLs: lowercase, digits, `-` and `_`, starting with a letter or digit. */
5
+ export const ENTITY_KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/
6
+ export const ENTITY_KEY_ERROR = 'Key must be 1-64 characters: lowercase letters, digits, "-" or "_", starting with a letter or digit'
7
+
8
+ /** Fallback for rows inserted without a key (the routes derive one from the name instead). */
9
+ export function randomEntityKey(): string {
10
+ return `k-${randomBytes(5).toString('hex')}`
11
+ }
12
+
13
+ export function isValidEntityKey(value: unknown): value is string {
14
+ return typeof value === 'string' && ENTITY_KEY_PATTERN.test(value)
15
+ }
16
+
17
+ export function slugifyKey(name: string): string {
18
+ const slug = name
19
+ .normalize('NFKD')
20
+ .replace(/[̀-ͯ]/g, '')
21
+ .replace(/[łŁ]/g, 'l') // does not decompose into l + diacritic
22
+ .toLowerCase()
23
+ .replace(/[^a-z0-9]+/g, '-')
24
+ .replace(/^-+|-+$/g, '')
25
+ .slice(0, 48)
26
+ .replace(/-+$/, '')
27
+ return slug || 'item'
28
+ }
29
+
30
+ /** Resolves the id of the row holding `key`, if any. */
31
+ export type KeyOwner = (key: string) => Promise<number | undefined>
32
+
33
+ export type KeyResult = { key: string } | { status: 400 | 409; error: string }
34
+
35
+ /** Key for a new row: the requested one when given (validated, must be free), else the first free slug of `name`. */
36
+ export async function keyForNew(name: string, requested: unknown, ownerOf: KeyOwner): Promise<KeyResult> {
37
+ if (requested !== undefined) {
38
+ if (!isValidEntityKey(requested)) return { status: 400, error: ENTITY_KEY_ERROR }
39
+ return (await ownerOf(requested)) === undefined ? { key: requested } : { status: 409, error: `Key "${requested}" is already in use` }
40
+ }
41
+ const base = slugifyKey(name)
42
+ let candidate = base
43
+ for (let n = 2; (await ownerOf(candidate)) !== undefined; n++) candidate = `${base}-${n}`
44
+ return { key: candidate }
45
+ }
46
+
47
+ /**
48
+ * Gives every row of `tables` that has no key yet one made from its name, in id order, the same way `keyForNew` does
49
+ * for a new row (`name`, then `name-2`, `name-3`, ...). The tables need `id`, `name` and `key` columns.
50
+ */
51
+ export function backfillKeys(sqlite: DatabaseSync, tables: readonly string[]): void {
52
+ for (const table of tables) {
53
+ const rows = sqlite.prepare(`SELECT id, name FROM ${table} WHERE key = '' ORDER BY id`).all() as Array<{ id: number; name: string }>
54
+ const taken = new Set((sqlite.prepare(`SELECT key FROM ${table} WHERE key <> ''`).all() as Array<{ key: string }>).map((row) => row.key))
55
+ const assign = sqlite.prepare(`UPDATE ${table} SET key = ? WHERE id = ?`)
56
+ for (const { id, name } of rows) {
57
+ const base = slugifyKey(name)
58
+ let key = base
59
+ for (let n = 2; taken.has(key); n++) key = `${base}-${n}`
60
+ taken.add(key)
61
+ assign.run(key, id)
62
+ }
63
+ }
64
+ }