@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/src/config.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { deepMerge } from "@zerotal/core";
2
+
3
+ export interface SettingsConfigShape {
4
+ /** The table overrides are stored in. Default: `"zerotal_settings"`. */
5
+ table: string;
6
+ /**
7
+ * Record every change through `@zerotal/audit` when `AuditProvider` is
8
+ * registered: who changed which setting, at which level, from what to what.
9
+ * Default: `true`. Without the audit provider there is nothing to record to,
10
+ * and nothing is.
11
+ */
12
+ audit: boolean;
13
+ }
14
+
15
+ const defaults: SettingsConfigShape = {
16
+ table: "zerotal_settings",
17
+ audit: true,
18
+ };
19
+
20
+ /**
21
+ * Create a typed settings configuration object with defaults.
22
+ *
23
+ * @example
24
+ * // config/settings.ts
25
+ * import { SettingsConfig } from "@zerotal/settings";
26
+ * export default SettingsConfig({ audit: true });
27
+ */
28
+ export function SettingsConfig(options: Partial<SettingsConfigShape> = {}): SettingsConfigShape {
29
+ return deepMerge(defaults, options);
30
+ }
31
+
32
+ // Register this package's config namespace for typed config() dot-paths.
33
+ declare module "@zerotal/core" {
34
+ interface ConfigRegistry {
35
+ settings: SettingsConfigShape;
36
+ }
37
+ }
@@ -0,0 +1,24 @@
1
+ import { currentApp } from "@zerotal/core";
2
+ import type { ContainerBindings } from "@zerotal/core";
3
+
4
+ /**
5
+ * A service another package binds, resolved by name and typed by the slice of it
6
+ * the caller uses — or `undefined` when that package is not registered.
7
+ *
8
+ * This is how settings reaches `@zerotal/audit` and `@zerotal/admin` without
9
+ * depending on either: an app without them pulls in nothing, the binding is
10
+ * simply absent. The key is not in this package's `ContainerBindings`, since the
11
+ * package that binds it declares it there.
12
+ *
13
+ * @internal
14
+ */
15
+ export function _optionalService<T>(name: string): T | undefined {
16
+ const key = name as keyof ContainerBindings;
17
+ try {
18
+ const container = currentApp().container;
19
+ if (!container.bound(key)) return undefined;
20
+ return container.makeSync<T>(key);
21
+ } catch {
22
+ return undefined;
23
+ }
24
+ }
@@ -0,0 +1,108 @@
1
+ import { currentApp } from "@zerotal/core";
2
+ import { SettingsError } from "./errors.ts";
3
+ import { _registerSetting } from "./registry.ts";
4
+ import type { SettingDefinition } from "./setting.ts";
5
+ import type { SettingsScope } from "./scope.ts";
6
+ import type {
7
+ ResolvedSetting,
8
+ SettingHistoryEntry,
9
+ SettingHistoryOptions,
10
+ SettingWriteOptions,
11
+ SettingsManager,
12
+ } from "./SettingsManager.ts";
13
+
14
+ /** A set of setting definitions, keyed by setting name. */
15
+ export type SettingDefinitions = Record<string, SettingDefinition<unknown>>;
16
+
17
+ /** The type a definition's value has. */
18
+ export type SettingValue<D> = D extends SettingDefinition<infer T> ? T : never;
19
+
20
+ /** Every value of a set of definitions, by key. */
21
+ export type SettingValues<D extends SettingDefinitions> = { [K in keyof D]: SettingValue<D[K]> };
22
+
23
+ /**
24
+ * The typed handle `defineSettings()` returns: every read and write takes only
25
+ * the keys it declares, and reads come back as the declared type.
26
+ */
27
+ export interface SettingsGroup<D extends SettingDefinitions> {
28
+ /** The definitions, as declared. */
29
+ readonly definitions: D;
30
+ /** A setting's value for the current tenant and user, or the ones `scope` names. */
31
+ get<K extends keyof D & string>(key: K, scope?: SettingsScope): Promise<SettingValue<D[K]>>;
32
+ /** Every setting in this group, for the current tenant and user. */
33
+ all(scope?: SettingsScope): Promise<SettingValues<D>>;
34
+ /** A value, the level it came from, and every level that applies. */
35
+ explain<K extends keyof D & string>(
36
+ key: K,
37
+ scope?: SettingsScope,
38
+ ): Promise<ResolvedSetting<SettingValue<D[K]>>>;
39
+ /** Override at one level — the tenant's, by default inside a tenant. */
40
+ set<K extends keyof D & string>(
41
+ key: K,
42
+ value: SettingValue<D[K]>,
43
+ options?: SettingWriteOptions,
44
+ ): Promise<void>;
45
+ /** Stop an override applying, keeping it. `false` when there is none at that level. */
46
+ hide<K extends keyof D & string>(key: K, options?: SettingWriteOptions): Promise<boolean>;
47
+ /** Make a hidden override apply again. `false` when there is none at that level. */
48
+ unhide<K extends keyof D & string>(key: K, options?: SettingWriteOptions): Promise<boolean>;
49
+ /** The changes at one level, newest first, from the audit trail. */
50
+ history<K extends keyof D & string>(
51
+ key: K,
52
+ options?: SettingHistoryOptions,
53
+ ): Promise<SettingHistoryEntry[]>;
54
+ }
55
+
56
+ /** The `settings` binding, or an error naming the provider to register. */
57
+ function manager(): SettingsManager {
58
+ try {
59
+ return currentApp().container.makeSync<SettingsManager>("settings");
60
+ } catch {
61
+ throw new SettingsError(
62
+ "Settings are not available: register SettingsProvider from @zerotal/settings.",
63
+ "E_SETTINGS_NOT_REGISTERED",
64
+ );
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Declare settings: a typed default in code for each, and the levels that may
70
+ * override it.
71
+ *
72
+ * Call it once per group, at module scope, and export the result. Every key is
73
+ * registered with the settings screen as the module loads.
74
+ *
75
+ * @example
76
+ * // app/settings.ts
77
+ * import { defineSettings, setting } from "@zerotal/settings";
78
+ *
79
+ * export const billing = defineSettings({
80
+ * "billing.invoicePrefix": setting.string({ default: "INV-", maxLength: 8 }),
81
+ * "billing.paymentTermsDays": setting.number({ default: 30, min: 0, max: 120, integer: true }),
82
+ * });
83
+ *
84
+ * const days = await billing.get("billing.paymentTermsDays"); // number
85
+ */
86
+ export function defineSettings<const D extends SettingDefinitions>(
87
+ definitions: D,
88
+ ): SettingsGroup<D> {
89
+ for (const [key, definition] of Object.entries(definitions)) _registerSetting(key, definition);
90
+
91
+ return {
92
+ definitions,
93
+ async get(key, scope) {
94
+ return (await manager().get(key, scope)) as SettingValue<D[typeof key]>;
95
+ },
96
+ async all(scope) {
97
+ const resolved = await manager().resolveMany(Object.keys(definitions), scope);
98
+ return Object.fromEntries(resolved.map((r) => [r.key, r.value])) as SettingValues<D>;
99
+ },
100
+ async explain(key, scope) {
101
+ return (await manager().resolve(key, scope)) as ResolvedSetting<SettingValue<D[typeof key]>>;
102
+ },
103
+ set: (key, value, options) => manager().set(key, value, options),
104
+ hide: (key, options) => manager().hide(key, options),
105
+ unhide: (key, options) => manager().unhide(key, options),
106
+ history: (key, options) => manager().history(key, options),
107
+ };
108
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,60 @@
1
+ import { ZerotalError } from "@zerotal/core";
2
+
3
+ /** Base class for every `@zerotal/settings` error. */
4
+ export class SettingsError extends ZerotalError {
5
+ constructor(
6
+ message: string,
7
+ code = "E_SETTINGS",
8
+ status = 500,
9
+ context?: Record<string, unknown>,
10
+ ) {
11
+ super(message, code, status, context);
12
+ }
13
+ }
14
+
15
+ /** A key no `defineSettings()` call declared. */
16
+ export class UnknownSettingError extends SettingsError {
17
+ constructor(key: string) {
18
+ super(
19
+ `There is no setting "${key}". Declare it with defineSettings() before reading or writing it.`,
20
+ "E_SETTING_UNKNOWN",
21
+ 500,
22
+ { key },
23
+ );
24
+ }
25
+ }
26
+
27
+ /** Two `defineSettings()` calls declared the same key. */
28
+ export class DuplicateSettingError extends SettingsError {
29
+ constructor(key: string) {
30
+ super(
31
+ `The setting "${key}" is declared twice. Each key belongs to one defineSettings() call.`,
32
+ "E_SETTING_DUPLICATE",
33
+ 500,
34
+ { key },
35
+ );
36
+ }
37
+ }
38
+
39
+ /** A value that is not what the setting's definition accepts. */
40
+ export class InvalidSettingValueError extends SettingsError {
41
+ constructor(key: string, reason: string) {
42
+ super(`Invalid value for the setting "${key}": ${reason}.`, "E_SETTING_INVALID", 422, {
43
+ key,
44
+ reason,
45
+ });
46
+ }
47
+ }
48
+
49
+ /**
50
+ * A write at a level the setting does not allow, or at a level nothing identifies:
51
+ * a tenant override outside any tenant, a user override with no user.
52
+ */
53
+ export class SettingScopeError extends SettingsError {
54
+ constructor(key: string, reason: string) {
55
+ super(`Cannot use the setting "${key}" this way: ${reason}.`, "E_SETTING_SCOPE", 422, {
56
+ key,
57
+ reason,
58
+ });
59
+ }
60
+ }
@@ -0,0 +1,15 @@
1
+ import { createFacade } from "@zerotal/core";
2
+ import type { SettingsManager } from "../SettingsManager.ts";
3
+
4
+ declare module "@zerotal/core" {
5
+ interface ContainerBindings {
6
+ settings: SettingsManager;
7
+ }
8
+ }
9
+
10
+ /**
11
+ * The `settings` binding: every declared setting by its string key. Generic code
12
+ * — a screen that lists them all, a command — uses this; app code reads through
13
+ * the typed group `defineSettings()` returns.
14
+ */
15
+ export const Settings = createFacade("settings");
package/src/index.ts ADDED
@@ -0,0 +1,58 @@
1
+ // @zerotal/settings — public API
2
+
3
+ // Declaring settings
4
+ export { defineSettings } from "./defineSettings.ts";
5
+ export type {
6
+ SettingsGroup,
7
+ SettingDefinitions,
8
+ SettingValue,
9
+ SettingValues,
10
+ } from "./defineSettings.ts";
11
+ export { setting } from "./setting.ts";
12
+ export type {
13
+ SettingDefinition,
14
+ SettingScopeKind,
15
+ SettingType,
16
+ BaseSettingOptions,
17
+ StringSettingOptions,
18
+ NumberSettingOptions,
19
+ BooleanSettingOptions,
20
+ EnumSettingOptions,
21
+ JsonSettingOptions,
22
+ } from "./setting.ts";
23
+
24
+ // Reading and writing
25
+ export { SettingsManager } from "./SettingsManager.ts";
26
+ export type {
27
+ ResolvedSetting,
28
+ SettingLevel,
29
+ SettingSource,
30
+ SettingWriteOptions,
31
+ SettingHistoryEntry,
32
+ SettingHistoryOptions,
33
+ } from "./SettingsManager.ts";
34
+ export type { SettingsScope } from "./scope.ts";
35
+ export { Settings } from "./facades/Settings.ts";
36
+
37
+ // Storage
38
+ export type { SettingsStore, StoredSetting } from "./stores/SettingsStore.ts";
39
+ export { DatabaseStore } from "./stores/DatabaseStore.ts";
40
+ export { MemoryStore } from "./stores/MemoryStore.ts";
41
+
42
+ // Provider, config, admin
43
+ export { SettingsProvider } from "./provider/SettingsProvider.ts";
44
+ export { SettingsConfig } from "./config.ts";
45
+ export type { SettingsConfigShape } from "./config.ts";
46
+ export { SETTINGS_ABILITY } from "./admin.ts";
47
+
48
+ // Testing
49
+ export { SettingsFake } from "./SettingsFake.ts";
50
+
51
+ // Errors
52
+ export {
53
+ SettingsError,
54
+ UnknownSettingError,
55
+ DuplicateSettingError,
56
+ InvalidSettingValueError,
57
+ SettingScopeError,
58
+ } from "./errors.ts";
@@ -0,0 +1,46 @@
1
+ import { ServiceProvider } from "@zerotal/core";
2
+ import type { AppEnvironment } from "@zerotal/core";
3
+ import type { ConfigManager } from "@zerotal/core/config";
4
+ import { _installSettingsAdmin } from "../admin.ts";
5
+ import { SettingsManager } from "../SettingsManager.ts";
6
+ import { settingsSchemaConcern } from "../settingsSchemaConcern.ts";
7
+ import { DatabaseStore } from "../stores/DatabaseStore.ts";
8
+ import "../facades/Settings.ts";
9
+
10
+ /**
11
+ * SettingsProvider — binds `settings`, creates its table on boot, and puts a
12
+ * settings screen in the admin panel when there is one.
13
+ *
14
+ * @example
15
+ * // bootstrap/providers.ts
16
+ * import { SettingsProvider } from "@zerotal/settings";
17
+ *
18
+ * export default [
19
+ * DatabaseProvider,
20
+ * TenancyProvider,
21
+ * AuditProvider, // optional: every change is recorded when it is registered
22
+ * SettingsProvider,
23
+ * ];
24
+ */
25
+ export class SettingsProvider extends ServiceProvider {
26
+ static override provides = ["settings"] as const;
27
+ static override environments: AppEnvironment[] = ["web", "console", "worker", "test", "repl"];
28
+
29
+ override onRegister(): void {
30
+ // No migration to write: the table is created on boot when it is missing.
31
+ this.app.registerConcern?.(settingsSchemaConcern);
32
+
33
+ this.app.container.singleton("settings", () => {
34
+ const config = this.app.container.makeSync("config") as ConfigManager;
35
+ const table = config.get<string>("settings.table", "zerotal_settings");
36
+ const audit = config.get<boolean>("settings.audit", true);
37
+ return new SettingsManager(new DatabaseStore(table), { audit });
38
+ });
39
+ }
40
+
41
+ override async onBooting(): Promise<void> {
42
+ // The panel mounts its routes once booting finishes, so the screen is
43
+ // contributed here rather than in onBooted, which would race the mount.
44
+ _installSettingsAdmin(this.app);
45
+ }
46
+ }
@@ -0,0 +1,37 @@
1
+ import { DuplicateSettingError, UnknownSettingError } from "./errors.ts";
2
+ import type { SettingDefinition } from "./setting.ts";
3
+
4
+ const _definitions = new Map<string, SettingDefinition>();
5
+
6
+ /**
7
+ * Record a setting's definition. A key declared twice with two different
8
+ * definitions is a mistake — two modules would read different defaults for it —
9
+ * so it throws rather than letting the later one win.
10
+ *
11
+ * @internal
12
+ */
13
+ export function _registerSetting(key: string, definition: SettingDefinition): void {
14
+ const existing = _definitions.get(key);
15
+ if (existing && existing !== definition) throw new DuplicateSettingError(key);
16
+ _definitions.set(key, definition);
17
+ }
18
+
19
+ /**
20
+ * The definition of a declared setting.
21
+ *
22
+ * @internal
23
+ */
24
+ export function _definitionOf(key: string): SettingDefinition {
25
+ const definition = _definitions.get(key);
26
+ if (!definition) throw new UnknownSettingError(key);
27
+ return definition;
28
+ }
29
+
30
+ /**
31
+ * Every declared setting, in declaration order.
32
+ *
33
+ * @internal
34
+ */
35
+ export function _allDefinitions(): [string, SettingDefinition][] {
36
+ return [..._definitions.entries()];
37
+ }
package/src/scope.ts ADDED
@@ -0,0 +1,43 @@
1
+ import type { SettingScopeKind } from "./setting.ts";
2
+
3
+ /**
4
+ * Who a read or write is for. Anything left out comes from the context: the
5
+ * tenant from `TenantContext`, the user from the authenticated request.
6
+ */
7
+ export interface SettingsScope {
8
+ /** The tenant (company). `null` reads and writes outside any tenant. */
9
+ tenant?: number | null | undefined;
10
+ /** The user. `null` reads and writes for no particular user. */
11
+ user?: string | number | null | undefined;
12
+ }
13
+
14
+ /** One stored level: the kind, who it belongs to, and the key it is filed under. */
15
+ export interface ScopeRef {
16
+ kind: SettingScopeKind;
17
+ tenant: number | null;
18
+ user: string | null;
19
+ /** `global`, `tenant:7`, `tenant:7:user:42` or `user:42` — unique per setting. */
20
+ id: string;
21
+ }
22
+
23
+ /**
24
+ * The stored level for a kind and an owner.
25
+ *
26
+ * The id is the whole identity of an override and the only thing a read matches
27
+ * on, so a tenant's id can only ever name that tenant's rows — that is what keeps
28
+ * one tenant's override out of another's reads, rather than a `WHERE` someone has
29
+ * to remember. Nulls are spelled out because a unique index treats two NULLs as
30
+ * different, and the global level would otherwise be insertable twice.
31
+ *
32
+ * @internal
33
+ */
34
+ export function _scopeRef(
35
+ kind: SettingScopeKind,
36
+ tenant: number | null,
37
+ user: string | null,
38
+ ): ScopeRef {
39
+ if (kind === "global") return { kind, tenant: null, user: null, id: "global" };
40
+ if (kind === "tenant") return { kind, tenant, user: null, id: `tenant:${String(tenant)}` };
41
+ const id = tenant === null ? `user:${String(user)}` : `tenant:${tenant}:user:${String(user)}`;
42
+ return { kind, tenant, user, id };
43
+ }
package/src/setting.ts ADDED
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Setting definitions: a typed default in code, plus what may override it.
3
+ *
4
+ * setting.number({ default: 30, min: 0, max: 120, label: "Payment terms (days)" })
5
+ *
6
+ * A definition is data. It parses whatever comes back from storage or from an
7
+ * admin form into its type, or throws {@link InvalidSettingValueError}, and the
8
+ * type it parses to is what `settings.get()` returns.
9
+ */
10
+ import { InvalidSettingValueError } from "./errors.ts";
11
+
12
+ /**
13
+ * The levels a setting can be overridden at, most specific first when read:
14
+ *
15
+ * - `user` — one user, inside the current tenant (or app-wide outside tenancy);
16
+ * - `tenant` — one tenant (company);
17
+ * - `global` — the whole app, replacing the default in code without a deploy.
18
+ */
19
+ export type SettingScopeKind = "global" | "tenant" | "user";
20
+
21
+ /** The kinds of value a setting holds; the admin screen picks its input from this. */
22
+ export type SettingType = "string" | "number" | "boolean" | "enum" | "json";
23
+
24
+ /** One declared setting. Build it with {@link setting}. */
25
+ export interface SettingDefinition<T = unknown> {
26
+ readonly type: SettingType;
27
+ /** The value when nothing overrides it. */
28
+ readonly default: T;
29
+ /** Levels this setting may be overridden at. */
30
+ readonly scopes: readonly SettingScopeKind[];
31
+ /** The name on the settings screen. Defaults to the key. */
32
+ readonly label: string | undefined;
33
+ /** A line of help under the label. */
34
+ readonly description: string | undefined;
35
+ /** The heading the setting is listed under. Defaults to the key's first segment. */
36
+ readonly group: string | undefined;
37
+ /** The allowed values, for an `enum` setting. */
38
+ readonly options: readonly string[] | undefined;
39
+ /**
40
+ * Turn a candidate value into this setting's type, or throw
41
+ * {@link InvalidSettingValueError}. `fromText` is true for text typed into a
42
+ * form, where `"42"` means the number and `"true"` the boolean.
43
+ */
44
+ parse(value: unknown, key: string, fromText?: boolean): T;
45
+ }
46
+
47
+ /** What every kind of setting accepts. */
48
+ export interface BaseSettingOptions<T> {
49
+ /** The value when nothing overrides it. */
50
+ default: T;
51
+ /** Levels this setting may be overridden at. Default: `["global", "tenant"]`. */
52
+ scopes?: readonly SettingScopeKind[] | undefined;
53
+ /** The name on the settings screen. Defaults to the key. */
54
+ label?: string | undefined;
55
+ /** A line of help under the label. */
56
+ description?: string | undefined;
57
+ /** The heading the setting is listed under. Defaults to the key's first segment. */
58
+ group?: string | undefined;
59
+ /** A last check of your own: return a reason to refuse the value, or nothing. */
60
+ validate?: ((value: T) => string | undefined | void) | undefined;
61
+ }
62
+
63
+ /** Options for {@link setting.string}. */
64
+ export interface StringSettingOptions extends BaseSettingOptions<string> {
65
+ /** The longest value accepted, in characters. */
66
+ maxLength?: number | undefined;
67
+ /** A pattern the whole value must match. */
68
+ pattern?: RegExp | undefined;
69
+ }
70
+
71
+ /** Options for {@link setting.number}. */
72
+ export interface NumberSettingOptions extends BaseSettingOptions<number> {
73
+ min?: number | undefined;
74
+ max?: number | undefined;
75
+ /** Accept whole numbers only. */
76
+ integer?: boolean | undefined;
77
+ }
78
+
79
+ /** Options for {@link setting.boolean}. */
80
+ export type BooleanSettingOptions = BaseSettingOptions<boolean>;
81
+
82
+ /** Options for {@link setting.enum}. */
83
+ export type EnumSettingOptions<T extends string> = BaseSettingOptions<T>;
84
+
85
+ /** Options for {@link setting.json}. */
86
+ export type JsonSettingOptions<T> = BaseSettingOptions<T>;
87
+
88
+ const DEFAULT_SCOPES: readonly SettingScopeKind[] = ["global", "tenant"];
89
+
90
+ /** Marks a refusal, so a JSON setting whose value has an `invalid` key is not one. */
91
+ const INVALID: unique symbol = Symbol("invalid");
92
+ type Refusal = { [INVALID]: string };
93
+ const invalid = (reason: string): Refusal => ({ [INVALID]: reason });
94
+
95
+ function isRefusal(value: unknown): value is Refusal {
96
+ return typeof value === "object" && value !== null && INVALID in value;
97
+ }
98
+
99
+ function build<T>(
100
+ type: SettingType,
101
+ options: BaseSettingOptions<T>,
102
+ check: (value: unknown, fromText: boolean) => T | Refusal,
103
+ choices?: readonly string[],
104
+ ): SettingDefinition<T> {
105
+ const scopes = options.scopes ?? DEFAULT_SCOPES;
106
+ const definition: SettingDefinition<T> = {
107
+ type,
108
+ default: options.default,
109
+ scopes,
110
+ label: options.label,
111
+ description: options.description,
112
+ group: options.group,
113
+ options: choices,
114
+ parse(value, key, fromText = false) {
115
+ const result = check(value, fromText);
116
+ if (isRefusal(result)) throw new InvalidSettingValueError(key, result[INVALID]);
117
+ const reason = options.validate?.(result);
118
+ if (reason) throw new InvalidSettingValueError(key, reason);
119
+ return result;
120
+ },
121
+ };
122
+ // The default has to pass its own definition, or a reader can be handed a value
123
+ // the screen would refuse to save.
124
+ definition.parse(options.default, "(default)");
125
+ return definition;
126
+ }
127
+
128
+ /** Builders for setting definitions, one per kind of value. */
129
+ export const setting = {
130
+ /** Text. */
131
+ string(options: StringSettingOptions): SettingDefinition<string> {
132
+ return build("string", options, (value) => {
133
+ if (typeof value !== "string") return invalid("expected text");
134
+ if (options.maxLength !== undefined && value.length > options.maxLength) {
135
+ return invalid(`longer than ${options.maxLength} characters`);
136
+ }
137
+ if (options.pattern && !options.pattern.test(value)) {
138
+ return invalid(`does not match ${String(options.pattern)}`);
139
+ }
140
+ return value;
141
+ });
142
+ },
143
+
144
+ /** A number, optionally bounded or whole. */
145
+ number(options: NumberSettingOptions): SettingDefinition<number> {
146
+ return build("number", options, (value, fromText) => {
147
+ const n =
148
+ fromText && typeof value === "string" && value.trim() !== "" ? Number(value) : value;
149
+ if (typeof n !== "number" || !Number.isFinite(n)) return invalid("expected a number");
150
+ if (options.integer && !Number.isInteger(n)) return invalid("expected a whole number");
151
+ if (options.min !== undefined && n < options.min) return invalid(`less than ${options.min}`);
152
+ if (options.max !== undefined && n > options.max) return invalid(`more than ${options.max}`);
153
+ return n;
154
+ });
155
+ },
156
+
157
+ /** On or off. */
158
+ boolean(options: BooleanSettingOptions): SettingDefinition<boolean> {
159
+ return build("boolean", options, (value, fromText) => {
160
+ if (typeof value === "boolean") return value;
161
+ if (fromText && (value === "true" || value === "1" || value === "on")) return true;
162
+ if (fromText && (value === "false" || value === "0" || value === "off")) return false;
163
+ return invalid("expected true or false");
164
+ });
165
+ },
166
+
167
+ /** One of a fixed list of strings. */
168
+ enum<const T extends string>(
169
+ values: readonly T[],
170
+ options: EnumSettingOptions<NoInfer<T>>,
171
+ ): SettingDefinition<T> {
172
+ return build(
173
+ "enum",
174
+ options,
175
+ (value) =>
176
+ typeof value === "string" && (values as readonly string[]).includes(value)
177
+ ? (value as T)
178
+ : invalid(`expected one of ${values.join(", ")}`),
179
+ values,
180
+ );
181
+ },
182
+
183
+ /**
184
+ * Any JSON value. The type parameter is a promise you make about its shape;
185
+ * pass `validate` to hold stored values to it.
186
+ */
187
+ json<T>(options: JsonSettingOptions<T>): SettingDefinition<T> {
188
+ return build("json", options, (value, fromText) => {
189
+ if (fromText && typeof value === "string") {
190
+ try {
191
+ return JSON.parse(value) as T;
192
+ } catch {
193
+ return invalid("expected JSON");
194
+ }
195
+ }
196
+ return value === undefined ? invalid("expected a value") : (value as T);
197
+ });
198
+ },
199
+ };
@@ -0,0 +1,50 @@
1
+ import type { ConcernDescriptor } from "@zerotal/core";
2
+ import type { ConfigManager } from "@zerotal/core/config";
3
+ import { Schema } from "@zerotal/orm";
4
+
5
+ /**
6
+ * Create a settings table, if it is missing, through the ORM's schema builder —
7
+ * so the DDL is right for SQLite, PostgreSQL and MySQL alike.
8
+ *
9
+ * @internal
10
+ */
11
+ export async function _createSettingsTable(table: string): Promise<void> {
12
+ if (await Schema.hasTable(table)) return;
13
+ await Schema.create(table, (blueprint) => {
14
+ blueprint.increments("id");
15
+ blueprint.string("setting_key", 191);
16
+ blueprint.string("scope_key", 191);
17
+ blueprint.integer("tenant_id").nullable();
18
+ blueprint.string("user_id", 191).nullable();
19
+ blueprint.text("value");
20
+ blueprint.boolean("hidden").default(false);
21
+ blueprint.string("updated_by", 191).nullable();
22
+ blueprint.string("created_at", 64).nullable();
23
+ blueprint.string("updated_at", 64).nullable();
24
+ // The identity of an override: one row per setting per level.
25
+ blueprint.unique(["setting_key", "scope_key"], `${table}_key_scope_unique`);
26
+ // A tenant's overrides, for the settings screen.
27
+ blueprint.index(["tenant_id"], `${table}_tenant_index`);
28
+ });
29
+ }
30
+
31
+ /**
32
+ * Provisions the settings table on boot, so an app writes no migration for it.
33
+ * Runs once after model discovery, additively and idempotently: it creates the
34
+ * table only when it is missing. A runtime without a database skips it, and a
35
+ * DDL error never fails boot — the first read reports it instead.
36
+ */
37
+ export const settingsSchemaConcern: ConcernDescriptor = {
38
+ name: "settings-schema",
39
+ order: 70,
40
+ envs: ["web", "worker", "test"],
41
+ async run(ctx) {
42
+ try {
43
+ const config = ctx.resolve<ConfigManager>("config");
44
+ const table = config?.get<string>("settings.table", "zerotal_settings") ?? "zerotal_settings";
45
+ await _createSettingsTable(table);
46
+ } catch {
47
+ // No database (or DDL not permitted) in this runtime — skip silently.
48
+ }
49
+ },
50
+ };