@zerotal/settings 0.0.0-stage → 1.18.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/CHANGELOG.md +28 -0
- package/LICENSE +21 -0
- package/README.md +83 -2
- package/api-surface.md +260 -0
- package/package.json +56 -4
- package/src/SettingsFake.ts +89 -0
- package/src/SettingsManager.ts +411 -0
- package/src/admin.ts +269 -0
- package/src/config.ts +37 -0
- package/src/container.ts +24 -0
- package/src/defineSettings.ts +108 -0
- package/src/errors.ts +60 -0
- package/src/facades/Settings.ts +15 -0
- package/src/index.ts +58 -0
- package/src/provider/SettingsProvider.ts +46 -0
- package/src/registry.ts +37 -0
- package/src/scope.ts +43 -0
- package/src/setting.ts +199 -0
- package/src/settingsSchemaConcern.ts +50 -0
- package/src/stores/DatabaseStore.ts +110 -0
- package/src/stores/MemoryStore.ts +62 -0
- package/src/stores/SettingsStore.ts +43 -0
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
import { RequestContext } from "@zerotal/core";
|
|
2
|
+
import { frameworkLog } from "@zerotal/core/logger";
|
|
3
|
+
import { TenantContext } from "@zerotal/tenancy";
|
|
4
|
+
import { _optionalService } from "./container.ts";
|
|
5
|
+
import { SettingScopeError } from "./errors.ts";
|
|
6
|
+
import { _allDefinitions, _definitionOf } from "./registry.ts";
|
|
7
|
+
import { _scopeRef } from "./scope.ts";
|
|
8
|
+
import type { ScopeRef, SettingsScope } from "./scope.ts";
|
|
9
|
+
import type { SettingDefinition, SettingScopeKind } from "./setting.ts";
|
|
10
|
+
import type { SettingsStore, StoredSetting } from "./stores/SettingsStore.ts";
|
|
11
|
+
|
|
12
|
+
/** Where a setting's value came from. `override` is a test pin; see `SettingsFake`. */
|
|
13
|
+
export type SettingSource = SettingScopeKind | "default" | "override";
|
|
14
|
+
|
|
15
|
+
/** One stored level of a setting, as {@link ResolvedSetting.levels} lists it. */
|
|
16
|
+
export interface SettingLevel {
|
|
17
|
+
kind: SettingScopeKind;
|
|
18
|
+
/** The stored value, or `undefined` when it no longer fits the definition. */
|
|
19
|
+
value: unknown;
|
|
20
|
+
hidden: boolean;
|
|
21
|
+
updatedBy: string | null;
|
|
22
|
+
updatedAt: string | null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A setting's value and the reasoning behind it. */
|
|
26
|
+
export interface ResolvedSetting<T = unknown> {
|
|
27
|
+
key: string;
|
|
28
|
+
value: T;
|
|
29
|
+
/** The level the value came from. */
|
|
30
|
+
source: SettingSource;
|
|
31
|
+
/** The value in code. */
|
|
32
|
+
default: T;
|
|
33
|
+
/** Every stored level that applies to this reader, most specific first, hidden ones included. */
|
|
34
|
+
levels: SettingLevel[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Options for a write: the level to write at, and whose it is. */
|
|
38
|
+
export interface SettingWriteOptions extends SettingsScope {
|
|
39
|
+
/**
|
|
40
|
+
* The level to write at. Default: `"tenant"` inside a tenant, otherwise
|
|
41
|
+
* `"global"` (or `"tenant"`, and an error, for a setting with no app-wide level).
|
|
42
|
+
* Never `"global"` inside a tenant, so a tenant's write cannot become app-wide
|
|
43
|
+
* by accident. A user override is always asked for by name.
|
|
44
|
+
*/
|
|
45
|
+
at?: SettingScopeKind | undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** One change to a setting, from the audit trail. */
|
|
49
|
+
export interface SettingHistoryEntry {
|
|
50
|
+
/** `setting.updated`, `setting.hidden` or `setting.unhidden`. */
|
|
51
|
+
event: string;
|
|
52
|
+
from: unknown;
|
|
53
|
+
to: unknown;
|
|
54
|
+
/** The acting user's id, when a user made the change. */
|
|
55
|
+
actor: number | null;
|
|
56
|
+
at: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Options for {@link SettingsManager.history}. */
|
|
60
|
+
export interface SettingHistoryOptions extends SettingWriteOptions {
|
|
61
|
+
/** How many entries, newest first. Default: 25. */
|
|
62
|
+
limit?: number | undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The slice of `@zerotal/audit`'s service this package uses, resolved from the container. */
|
|
66
|
+
interface AuditSink {
|
|
67
|
+
log(
|
|
68
|
+
event: string,
|
|
69
|
+
payload: {
|
|
70
|
+
auditable_type: string;
|
|
71
|
+
auditable_id: string;
|
|
72
|
+
old_values: Record<string, unknown> | null;
|
|
73
|
+
new_values: Record<string, unknown> | null;
|
|
74
|
+
tags: Record<string, unknown>;
|
|
75
|
+
},
|
|
76
|
+
): Promise<void>;
|
|
77
|
+
logs(
|
|
78
|
+
type: string,
|
|
79
|
+
id: string,
|
|
80
|
+
): {
|
|
81
|
+
orderBy(column: string, direction: string): { limit(n: number): { get(): Promise<object[]> } };
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The type the audit trail files setting changes under. */
|
|
86
|
+
const AUDIT_TYPE = "Setting";
|
|
87
|
+
|
|
88
|
+
/** The authenticated user's id, read structurally: this package does not depend on auth. */
|
|
89
|
+
function contextUserId(): string | null {
|
|
90
|
+
const user = (RequestContext.tryGet() as { user?: { id?: unknown } } | undefined)?.user;
|
|
91
|
+
const id = user?.id;
|
|
92
|
+
return id === undefined || id === null ? null : String(id);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function decode(raw: string): unknown {
|
|
96
|
+
return JSON.parse(raw) as unknown;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Settings: typed defaults in code, overridden per tenant, per user or app-wide.
|
|
101
|
+
*
|
|
102
|
+
* Bound as `settings` by {@link SettingsProvider}. Reach it through a group from
|
|
103
|
+
* `defineSettings()`, whose reads are typed, or the `Settings` facade.
|
|
104
|
+
*
|
|
105
|
+
* A read takes the most specific value that applies: the user's override, then
|
|
106
|
+
* the tenant's, then the app-wide one, then the default in code. The tenant and
|
|
107
|
+
* the user come from the context — `TenantContext` and the authenticated request
|
|
108
|
+
* — unless the call names them.
|
|
109
|
+
*/
|
|
110
|
+
export class SettingsManager {
|
|
111
|
+
constructor(
|
|
112
|
+
protected readonly store: SettingsStore,
|
|
113
|
+
protected readonly options: { audit: boolean } = { audit: true },
|
|
114
|
+
) {}
|
|
115
|
+
|
|
116
|
+
// ── Reading ─────────────────────────────────────────────────────────────
|
|
117
|
+
|
|
118
|
+
/** A setting's value for the current tenant and user, or the ones `scope` names. */
|
|
119
|
+
async get(key: string, scope?: SettingsScope): Promise<unknown> {
|
|
120
|
+
return (await this.resolve(key, scope)).value;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** A setting's value, where it came from, and every level that applies. */
|
|
124
|
+
async resolve(key: string, scope?: SettingsScope): Promise<ResolvedSetting> {
|
|
125
|
+
const [resolved] = await this.resolveMany([key], scope);
|
|
126
|
+
return resolved!;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Several settings at once, in one read of the store. */
|
|
130
|
+
async resolveMany(keys: readonly string[], scope?: SettingsScope): Promise<ResolvedSetting[]> {
|
|
131
|
+
const who = this._who(scope, keys.join(", "));
|
|
132
|
+
const plans = keys.map((key) => {
|
|
133
|
+
const definition = _definitionOf(key);
|
|
134
|
+
return { key, definition, refs: this._readLevels(definition, who) };
|
|
135
|
+
});
|
|
136
|
+
const scopeIds = [...new Set(plans.flatMap((p) => p.refs.map((r) => r.id)))];
|
|
137
|
+
const rows = await this.store.find(keys, scopeIds);
|
|
138
|
+
const byId = new Map(rows.map((row) => [`${row.key}\u0000${row.scope}`, row]));
|
|
139
|
+
|
|
140
|
+
return plans.map(({ key, definition, refs }) => {
|
|
141
|
+
const levels: SettingLevel[] = [];
|
|
142
|
+
let found: { value: unknown; source: SettingSource } | undefined;
|
|
143
|
+
for (const ref of refs) {
|
|
144
|
+
const row = byId.get(`${key}\u0000${ref.id}`);
|
|
145
|
+
if (!row) continue;
|
|
146
|
+
const value = this._read(key, definition, row);
|
|
147
|
+
levels.push({
|
|
148
|
+
kind: ref.kind,
|
|
149
|
+
value,
|
|
150
|
+
hidden: row.hidden,
|
|
151
|
+
updatedBy: row.updatedBy,
|
|
152
|
+
updatedAt: row.updatedAt,
|
|
153
|
+
});
|
|
154
|
+
if (!found && !row.hidden && value !== undefined) found = { value, source: ref.kind };
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
key,
|
|
158
|
+
value: found ? found.value : definition.default,
|
|
159
|
+
source: found ? found.source : "default",
|
|
160
|
+
default: definition.default,
|
|
161
|
+
levels,
|
|
162
|
+
};
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Every declared setting, resolved for the current tenant and user. */
|
|
167
|
+
async all(scope?: SettingsScope): Promise<ResolvedSetting[]> {
|
|
168
|
+
return this.resolveMany(
|
|
169
|
+
_allDefinitions().map(([key]) => key),
|
|
170
|
+
scope,
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Every declared setting's key and definition. */
|
|
175
|
+
definitions(): [string, SettingDefinition][] {
|
|
176
|
+
return _allDefinitions();
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ── Writing ─────────────────────────────────────────────────────────────
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Override a setting at one level. The value is checked against the definition
|
|
183
|
+
* first, and a hidden override at that level is made visible again with it.
|
|
184
|
+
*/
|
|
185
|
+
async set(key: string, value: unknown, options: SettingWriteOptions = {}): Promise<void> {
|
|
186
|
+
const definition = _definitionOf(key);
|
|
187
|
+
const parsed = definition.parse(value, key);
|
|
188
|
+
const ref = this._writeLevel(key, definition, options);
|
|
189
|
+
const before = await this.store.put(key, ref, JSON.stringify(parsed), contextUserId());
|
|
190
|
+
await this._audit(
|
|
191
|
+
"setting.updated",
|
|
192
|
+
key,
|
|
193
|
+
ref,
|
|
194
|
+
before ? this._readSafe(key, before) : undefined,
|
|
195
|
+
parsed,
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* {@link set} from text typed into a form: `"42"` for a number setting, `"true"`
|
|
201
|
+
* for a boolean, JSON for a JSON setting.
|
|
202
|
+
*/
|
|
203
|
+
async setFromText(key: string, text: string, options: SettingWriteOptions = {}): Promise<void> {
|
|
204
|
+
const definition = _definitionOf(key);
|
|
205
|
+
await this.set(key, definition.parse(text, key, true), options);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Stop an override applying, so the next level shows through — and keep it.
|
|
210
|
+
*
|
|
211
|
+
* Overrides are never deleted: the value stays stored, its history stays
|
|
212
|
+
* attached to it, and {@link unhide} puts it back. Resolves to `false` when
|
|
213
|
+
* there is no override at that level to hide.
|
|
214
|
+
*/
|
|
215
|
+
async hide(key: string, options: SettingWriteOptions = {}): Promise<boolean> {
|
|
216
|
+
return this._setHidden(key, true, options);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Make a hidden override apply again. `false` when there is none at that level. */
|
|
220
|
+
async unhide(key: string, options: SettingWriteOptions = {}): Promise<boolean> {
|
|
221
|
+
return this._setHidden(key, false, options);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
private async _setHidden(
|
|
225
|
+
key: string,
|
|
226
|
+
hidden: boolean,
|
|
227
|
+
options: SettingWriteOptions,
|
|
228
|
+
): Promise<boolean> {
|
|
229
|
+
const definition = _definitionOf(key);
|
|
230
|
+
const ref = this._writeLevel(key, definition, options);
|
|
231
|
+
const before = await this.store.setHidden(key, ref.id, hidden, contextUserId());
|
|
232
|
+
if (!before) return false;
|
|
233
|
+
if (before.hidden !== hidden) {
|
|
234
|
+
const value = this._readSafe(key, before);
|
|
235
|
+
await this._audit(
|
|
236
|
+
hidden ? "setting.hidden" : "setting.unhidden",
|
|
237
|
+
key,
|
|
238
|
+
ref,
|
|
239
|
+
hidden ? value : undefined,
|
|
240
|
+
hidden ? undefined : value,
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// ── History ─────────────────────────────────────────────────────────────
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* The changes to a setting at one level, newest first, from the audit trail.
|
|
250
|
+
* Empty when `@zerotal/audit` is not registered. Each level has its own trail,
|
|
251
|
+
* so a tenant's history never shows another tenant's changes.
|
|
252
|
+
*/
|
|
253
|
+
async history(key: string, options: SettingHistoryOptions = {}): Promise<SettingHistoryEntry[]> {
|
|
254
|
+
const definition = _definitionOf(key);
|
|
255
|
+
const ref = this._writeLevel(key, definition, options);
|
|
256
|
+
const audit = this._auditSink();
|
|
257
|
+
if (!audit) return [];
|
|
258
|
+
const rows = await audit
|
|
259
|
+
.logs(AUDIT_TYPE, `${key}@${ref.id}`)
|
|
260
|
+
.orderBy("id", "desc")
|
|
261
|
+
.limit(options.limit ?? 25)
|
|
262
|
+
.get();
|
|
263
|
+
return rows.map((row) => {
|
|
264
|
+
const r = row as Record<string, unknown>;
|
|
265
|
+
const field = (camel: string, snake: string): unknown => r[camel] ?? r[snake];
|
|
266
|
+
const values = (v: unknown): Record<string, unknown> | null => {
|
|
267
|
+
if (typeof v === "string") return JSON.parse(v) as Record<string, unknown>;
|
|
268
|
+
return (v as Record<string, unknown> | null) ?? null;
|
|
269
|
+
};
|
|
270
|
+
const at = field("createdAt", "created_at");
|
|
271
|
+
const actor = field("actorId", "actor_id");
|
|
272
|
+
return {
|
|
273
|
+
event: String(r["event"]),
|
|
274
|
+
from: values(field("oldValues", "old_values"))?.["value"],
|
|
275
|
+
to: values(field("newValues", "new_values"))?.["value"],
|
|
276
|
+
actor: actor === null || actor === undefined ? null : Number(actor),
|
|
277
|
+
at: at instanceof Date ? at.toISOString() : String(at ?? ""),
|
|
278
|
+
};
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ── Levels ──────────────────────────────────────────────────────────────
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* The tenant and user a call is for: what it names, else the context.
|
|
286
|
+
*
|
|
287
|
+
* Code running inside one tenant may not name another. Without this, a request in
|
|
288
|
+
* tenant 7 that passed `{ tenant: Number(body.tenantId) }` read, wrote, hid or read
|
|
289
|
+
* the history of tenant 8's settings. Naming a tenant is for code outside every
|
|
290
|
+
* tenant — a central admin console, a command, a job working through tenants.
|
|
291
|
+
*/
|
|
292
|
+
protected _who(scope?: SettingsScope, key = "*"): { tenant: number | null; user: string | null } {
|
|
293
|
+
const active = TenantContext.id();
|
|
294
|
+
if (scope?.tenant !== undefined && active !== null && scope.tenant !== active) {
|
|
295
|
+
throw new SettingScopeError(
|
|
296
|
+
key,
|
|
297
|
+
`this code runs inside tenant ${active}, so it cannot name tenant ${String(scope.tenant)}`,
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
const tenant = scope?.tenant !== undefined ? scope.tenant : active;
|
|
301
|
+
const user = scope?.user !== undefined ? scope.user : contextUserId();
|
|
302
|
+
return { tenant, user: user === null ? null : String(user) };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** The stored levels a read consults for this setting, most specific first. */
|
|
306
|
+
private _readLevels(
|
|
307
|
+
definition: SettingDefinition,
|
|
308
|
+
who: { tenant: number | null; user: string | null },
|
|
309
|
+
): ScopeRef[] {
|
|
310
|
+
const refs: ScopeRef[] = [];
|
|
311
|
+
if (definition.scopes.includes("user") && who.user !== null) {
|
|
312
|
+
refs.push(_scopeRef("user", who.tenant, who.user));
|
|
313
|
+
}
|
|
314
|
+
if (definition.scopes.includes("tenant") && who.tenant !== null) {
|
|
315
|
+
refs.push(_scopeRef("tenant", who.tenant, null));
|
|
316
|
+
}
|
|
317
|
+
if (definition.scopes.includes("global")) refs.push(_scopeRef("global", null, null));
|
|
318
|
+
return refs;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** The one level a write goes to, or a {@link SettingScopeError} saying why it cannot. */
|
|
322
|
+
private _writeLevel(
|
|
323
|
+
key: string,
|
|
324
|
+
definition: SettingDefinition,
|
|
325
|
+
options: SettingWriteOptions,
|
|
326
|
+
): ScopeRef {
|
|
327
|
+
const who = this._who(options, key);
|
|
328
|
+
// Inside a tenant the default is always the tenant's own level: a write there
|
|
329
|
+
// must never quietly become an app-wide one because the setting is global-only.
|
|
330
|
+
const at =
|
|
331
|
+
options.at ??
|
|
332
|
+
(who.tenant !== null || !definition.scopes.includes("global") ? "tenant" : "global");
|
|
333
|
+
// Nor can it become one by asking: an app-wide value applies to every tenant,
|
|
334
|
+
// so it is set from outside them all, never from inside one.
|
|
335
|
+
if (at === "global" && TenantContext.id() !== null) {
|
|
336
|
+
throw new SettingScopeError(
|
|
337
|
+
key,
|
|
338
|
+
"this code runs inside a tenant, and an app-wide value would change it for every tenant",
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
if (!definition.scopes.includes(at)) {
|
|
342
|
+
throw new SettingScopeError(
|
|
343
|
+
key,
|
|
344
|
+
`it cannot be overridden per ${at === "global" ? "app" : at}; ` +
|
|
345
|
+
`its definition allows ${definition.scopes.join(", ") || "no overrides"}`,
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
if (at === "tenant" && who.tenant === null) {
|
|
349
|
+
throw new SettingScopeError(key, "there is no tenant here; name one with { tenant }");
|
|
350
|
+
}
|
|
351
|
+
if (at === "user" && who.user === null) {
|
|
352
|
+
throw new SettingScopeError(key, "there is no signed-in user here; name one with { user }");
|
|
353
|
+
}
|
|
354
|
+
return _scopeRef(at, who.tenant, at === "user" ? who.user : null);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// ── Values ──────────────────────────────────────────────────────────────
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* A stored value, parsed by today's definition. One that no longer fits — the
|
|
361
|
+
* definition tightened after it was saved — is skipped with a warning, so the
|
|
362
|
+
* reader gets the next level rather than a value of the wrong type.
|
|
363
|
+
*/
|
|
364
|
+
private _read(key: string, definition: SettingDefinition, row: StoredSetting): unknown {
|
|
365
|
+
try {
|
|
366
|
+
return definition.parse(decode(row.value), key);
|
|
367
|
+
} catch (error) {
|
|
368
|
+
frameworkLog("settings").warn(
|
|
369
|
+
`Ignoring the stored value of "${key}" at ${row.scope}: it no longer fits its definition`,
|
|
370
|
+
{ key, scope: row.scope },
|
|
371
|
+
error,
|
|
372
|
+
);
|
|
373
|
+
return undefined;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
private _readSafe(key: string, row: StoredSetting): unknown {
|
|
378
|
+
try {
|
|
379
|
+
return decode(row.value);
|
|
380
|
+
} catch {
|
|
381
|
+
return row.value;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// ── Audit ───────────────────────────────────────────────────────────────
|
|
386
|
+
|
|
387
|
+
/** The audit service, when `AuditProvider` is registered and auditing is on. */
|
|
388
|
+
private _auditSink(): AuditSink | undefined {
|
|
389
|
+
return this.options.audit ? _optionalService<AuditSink>("audit") : undefined;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
private async _audit(
|
|
393
|
+
event: string,
|
|
394
|
+
key: string,
|
|
395
|
+
ref: ScopeRef,
|
|
396
|
+
from: unknown,
|
|
397
|
+
to: unknown,
|
|
398
|
+
): Promise<void> {
|
|
399
|
+
const audit = this._auditSink();
|
|
400
|
+
if (!audit) return;
|
|
401
|
+
await audit.log(event, {
|
|
402
|
+
auditable_type: AUDIT_TYPE,
|
|
403
|
+
// One trail per setting per level, so reading a tenant's history is a lookup
|
|
404
|
+
// on its own id and can never return another tenant's entries.
|
|
405
|
+
auditable_id: `${key}@${ref.id}`,
|
|
406
|
+
old_values: from === undefined ? null : { value: from },
|
|
407
|
+
new_values: to === undefined ? null : { value: to },
|
|
408
|
+
tags: { key, level: ref.kind, tenant: ref.tenant, user: ref.user },
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
}
|
package/src/admin.ts
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Settings → admin panel: a generated settings screen.
|
|
3
|
+
*
|
|
4
|
+
* Every declared setting is a row, with its value at the level the panel is
|
|
5
|
+
* looking at — the tenant's, inside a tenant, otherwise the app-wide one — where
|
|
6
|
+
* it came from, and actions to change it, hide the override (keeping it), or
|
|
7
|
+
* unhide it. Nothing is written by hand: a new `defineSettings()` key is a new row.
|
|
8
|
+
*
|
|
9
|
+
* As with the queue's console, the panel is resolved from the container and typed
|
|
10
|
+
* through a local interface, so settings does not depend on `@zerotal/admin` and
|
|
11
|
+
* an app without the panel pulls in nothing.
|
|
12
|
+
*/
|
|
13
|
+
import type { Application } from "@zerotal/core";
|
|
14
|
+
import { TenantContext } from "@zerotal/tenancy";
|
|
15
|
+
import { _optionalService } from "./container.ts";
|
|
16
|
+
import type { SettingDefinition } from "./setting.ts";
|
|
17
|
+
import type { SettingsManager } from "./SettingsManager.ts";
|
|
18
|
+
|
|
19
|
+
type Row = Record<string, unknown>;
|
|
20
|
+
type Tone = "primary" | "success" | "muted" | "destructive" | "default";
|
|
21
|
+
|
|
22
|
+
/** The slice of the admin panel's contribution surface this module uses. */
|
|
23
|
+
interface AdminPanelSink {
|
|
24
|
+
enabled(id: string): boolean;
|
|
25
|
+
console(contribution: ConsoleSpec): void;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface ConsoleSpec {
|
|
29
|
+
slug: string;
|
|
30
|
+
title: string;
|
|
31
|
+
ability: string;
|
|
32
|
+
navigationIcon?: string;
|
|
33
|
+
navigationGroup?: string;
|
|
34
|
+
tabs: Array<{
|
|
35
|
+
key: string;
|
|
36
|
+
label: string;
|
|
37
|
+
description?: string;
|
|
38
|
+
columns: Array<{
|
|
39
|
+
key: string;
|
|
40
|
+
label: string;
|
|
41
|
+
mono?: boolean;
|
|
42
|
+
format?: (value: unknown, row: Row) => string;
|
|
43
|
+
badge?: (value: unknown, row: Row) => Tone | null;
|
|
44
|
+
}>;
|
|
45
|
+
rows: () => Promise<Row[]>;
|
|
46
|
+
rowKey?: string;
|
|
47
|
+
rowActions?: Array<{
|
|
48
|
+
key: string;
|
|
49
|
+
label: string;
|
|
50
|
+
icon?: string;
|
|
51
|
+
danger?: boolean;
|
|
52
|
+
confirm?: string;
|
|
53
|
+
input?: {
|
|
54
|
+
label: string;
|
|
55
|
+
type?: "text" | "number" | "select" | "textarea";
|
|
56
|
+
options?: (row: Row) => string[];
|
|
57
|
+
value?: (row: Row) => string;
|
|
58
|
+
help?: (row: Row) => string | undefined;
|
|
59
|
+
};
|
|
60
|
+
run: (row: Row, input?: string) => Promise<string | void>;
|
|
61
|
+
}>;
|
|
62
|
+
empty?: string;
|
|
63
|
+
badge?: () => Promise<number | null>;
|
|
64
|
+
}>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The ability a user needs to see and change settings in the panel. */
|
|
68
|
+
export const SETTINGS_ABILITY = "settings.manage";
|
|
69
|
+
|
|
70
|
+
const SOURCE_TONE: Record<string, Tone> = {
|
|
71
|
+
default: "muted",
|
|
72
|
+
global: "default",
|
|
73
|
+
tenant: "primary",
|
|
74
|
+
user: "success",
|
|
75
|
+
override: "destructive",
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
/** A value as one line of text: JSON for objects, plain for the rest. */
|
|
79
|
+
function display(value: unknown): string {
|
|
80
|
+
const text = typeof value === "string" ? value : JSON.stringify(value);
|
|
81
|
+
return text.length > 120 ? `${text.slice(0, 117)}…` : text;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The text a form field starts with, which `setFromText` reads back. */
|
|
85
|
+
function asText(value: unknown): string {
|
|
86
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function groupOf(key: string, definition: SettingDefinition): string {
|
|
90
|
+
return definition.group ?? key.split(".")[0] ?? key;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* How the screen reads: for no particular user. The screen edits the tenant's (or the
|
|
95
|
+
* app's) value, so what it shows must be that value, not the signed-in admin's own.
|
|
96
|
+
*/
|
|
97
|
+
const SCREEN_SCOPE = { user: null } as const;
|
|
98
|
+
|
|
99
|
+
/** The level a write from the screen goes to, and so the one its Hidden tab lists. */
|
|
100
|
+
function screenLevel(): "tenant" | "global" {
|
|
101
|
+
return TenantContext.id() !== null ? "tenant" : "global";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The level the panel reads and writes: the tenant's, inside one, else app-wide. */
|
|
105
|
+
function levelLabel(): string {
|
|
106
|
+
const tenant = TenantContext.tryGet();
|
|
107
|
+
return tenant ? `tenant ${tenant.name ?? tenant.slug ?? tenant.id}` : "the whole app";
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The settings screen's description, as data the panel renders.
|
|
112
|
+
*
|
|
113
|
+
* @internal
|
|
114
|
+
*/
|
|
115
|
+
export function _settingsConsole(settings: () => SettingsManager): ConsoleSpec {
|
|
116
|
+
const definitions = (): Map<string, SettingDefinition> => new Map(settings().definitions());
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
slug: "settings",
|
|
120
|
+
title: "Settings",
|
|
121
|
+
ability: SETTINGS_ABILITY,
|
|
122
|
+
navigationIcon: "cog",
|
|
123
|
+
navigationGroup: "Settings",
|
|
124
|
+
tabs: [
|
|
125
|
+
{
|
|
126
|
+
key: "settings",
|
|
127
|
+
label: "Settings",
|
|
128
|
+
description:
|
|
129
|
+
"Each setting's value here, and where it comes from. Hiding an override keeps it, " +
|
|
130
|
+
"so it can be unhidden; nothing is ever deleted.",
|
|
131
|
+
empty: "No settings are declared. Declare them with defineSettings().",
|
|
132
|
+
rowKey: "key",
|
|
133
|
+
columns: [
|
|
134
|
+
{ key: "group", label: "Group", badge: () => "muted" },
|
|
135
|
+
{ key: "label", label: "Setting" },
|
|
136
|
+
{ key: "key", label: "Key", mono: true },
|
|
137
|
+
{ key: "value", label: "Value", mono: true, format: (v) => display(v) },
|
|
138
|
+
{
|
|
139
|
+
key: "source",
|
|
140
|
+
label: "From",
|
|
141
|
+
badge: (v) => SOURCE_TONE[String(v)] ?? "default",
|
|
142
|
+
},
|
|
143
|
+
],
|
|
144
|
+
rows: async () => {
|
|
145
|
+
const defs = definitions();
|
|
146
|
+
// Read for no particular user. Without `user: null` the signed-in admin's own
|
|
147
|
+
// user-level override showed as the row's value, Change opened pre-filled with
|
|
148
|
+
// it, and saving wrote it for the whole tenant.
|
|
149
|
+
return (await settings().all(SCREEN_SCOPE)).map((r) => {
|
|
150
|
+
const definition = defs.get(r.key)!;
|
|
151
|
+
return {
|
|
152
|
+
key: r.key,
|
|
153
|
+
group: groupOf(r.key, definition),
|
|
154
|
+
label: definition.label ?? r.key,
|
|
155
|
+
description: definition.description ?? "",
|
|
156
|
+
value: r.value,
|
|
157
|
+
source: r.source,
|
|
158
|
+
};
|
|
159
|
+
});
|
|
160
|
+
},
|
|
161
|
+
rowActions: [
|
|
162
|
+
{
|
|
163
|
+
key: "change",
|
|
164
|
+
label: "Change",
|
|
165
|
+
icon: "pencil",
|
|
166
|
+
input: {
|
|
167
|
+
label: "New value",
|
|
168
|
+
type: "text",
|
|
169
|
+
value: (row) => asText(row["value"]),
|
|
170
|
+
options: (row) => {
|
|
171
|
+
const definition = definitions().get(String(row["key"]));
|
|
172
|
+
if (definition?.type === "boolean") return ["true", "false"];
|
|
173
|
+
return [...(definition?.options ?? [])];
|
|
174
|
+
},
|
|
175
|
+
help: (row) => String(row["description"] ?? "") || undefined,
|
|
176
|
+
},
|
|
177
|
+
run: async (row, input) => {
|
|
178
|
+
const key = String(row["key"]);
|
|
179
|
+
await settings().setFromText(key, input ?? "");
|
|
180
|
+
return `${key} saved for ${levelLabel()}.`;
|
|
181
|
+
},
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
key: "hide",
|
|
185
|
+
label: "Hide override",
|
|
186
|
+
icon: "eye-off",
|
|
187
|
+
confirm: "Stop this override applying? It is kept, and can be unhidden.",
|
|
188
|
+
run: async (row) => {
|
|
189
|
+
const key = String(row["key"]);
|
|
190
|
+
if (!(await settings().hide(key))) {
|
|
191
|
+
throw new Error(`${key} has no override for ${levelLabel()} to hide.`);
|
|
192
|
+
}
|
|
193
|
+
return `${key} hidden for ${levelLabel()}; the value is kept.`;
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
{
|
|
197
|
+
key: "unhide",
|
|
198
|
+
label: "Unhide",
|
|
199
|
+
icon: "eye",
|
|
200
|
+
run: async (row) => {
|
|
201
|
+
const key = String(row["key"]);
|
|
202
|
+
if (!(await settings().unhide(key))) {
|
|
203
|
+
throw new Error(`${key} has no override for ${levelLabel()} to unhide.`);
|
|
204
|
+
}
|
|
205
|
+
return `${key} applies again for ${levelLabel()}.`;
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
],
|
|
209
|
+
},
|
|
210
|
+
{
|
|
211
|
+
key: "hidden",
|
|
212
|
+
label: "Hidden",
|
|
213
|
+
description: "Overrides that are kept but not applied. Unhide one to apply it again.",
|
|
214
|
+
empty: "Nothing is hidden here.",
|
|
215
|
+
rowKey: "key",
|
|
216
|
+
columns: [
|
|
217
|
+
{ key: "key", label: "Key", mono: true },
|
|
218
|
+
{ key: "level", label: "Level", badge: (v) => SOURCE_TONE[String(v)] ?? "default" },
|
|
219
|
+
{ key: "value", label: "Kept value", mono: true, format: (v) => display(v) },
|
|
220
|
+
{ key: "updatedAt", label: "Hidden", format: (v) => (v ? String(v) : "—") },
|
|
221
|
+
],
|
|
222
|
+
rows: async () => {
|
|
223
|
+
const rows: Row[] = [];
|
|
224
|
+
for (const r of await settings().all(SCREEN_SCOPE)) {
|
|
225
|
+
// The level a write from this screen goes to is the one it can unhide.
|
|
226
|
+
const level = screenLevel();
|
|
227
|
+
const hidden = r.levels.find((l) => l.kind === level && l.hidden);
|
|
228
|
+
if (hidden) {
|
|
229
|
+
rows.push({ key: r.key, level, value: hidden.value, updatedAt: hidden.updatedAt });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return rows;
|
|
233
|
+
},
|
|
234
|
+
// Counted as the tab lists them: hidden at this screen's level only. Counting
|
|
235
|
+
// any hidden level showed "2" over an empty tab.
|
|
236
|
+
badge: async () =>
|
|
237
|
+
(await settings().all(SCREEN_SCOPE)).filter((r) =>
|
|
238
|
+
r.levels.some((l) => l.kind === screenLevel() && l.hidden),
|
|
239
|
+
).length || null,
|
|
240
|
+
rowActions: [
|
|
241
|
+
{
|
|
242
|
+
key: "unhide",
|
|
243
|
+
label: "Unhide",
|
|
244
|
+
icon: "eye",
|
|
245
|
+
run: async (row) => {
|
|
246
|
+
await settings().unhide(String(row["key"]));
|
|
247
|
+
return `${String(row["key"])} applies again for ${levelLabel()}.`;
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
],
|
|
251
|
+
},
|
|
252
|
+
],
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Contribute the settings screen to the admin panel, when one is installed and
|
|
258
|
+
* has not switched it off with `plugins: { settings: false }`.
|
|
259
|
+
*
|
|
260
|
+
* Called from `SettingsProvider.onBooting()`, where the panel's surface is
|
|
261
|
+
* already bound whatever order the providers were registered in.
|
|
262
|
+
*
|
|
263
|
+
* @internal
|
|
264
|
+
*/
|
|
265
|
+
export function _installSettingsAdmin(app: Application): void {
|
|
266
|
+
const panel = _optionalService<AdminPanelSink>("admin.panel");
|
|
267
|
+
if (!panel?.enabled("settings")) return;
|
|
268
|
+
panel.console(_settingsConsole(() => app.container.makeSync("settings")));
|
|
269
|
+
}
|