@zerotal/settings 0.0.0-stage → 1.18.1

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 ADDED
@@ -0,0 +1,53 @@
1
+ # Changelog — @zerotal/settings
2
+
3
+ All notable changes to this package are documented here. The format is
4
+ based on [Keep a Changelog](https://keepachangelog.com/); this package
5
+ follows the Zerotal monorepo's unified versioning.
6
+
7
+ **Maturity: `beta`** — reviewed by 1.20.0.
8
+
9
+ ## [Unreleased]
10
+
11
+ ## [1.18.1] — 2026-11-26
12
+
13
+ ### Fixed
14
+
15
+ - **A `validate` check that throws refuses the value.** A check written for the declared shape
16
+ can throw on another one: `setFromText()` on a JSON setting parses `"null"` to `null`, and the
17
+ documented `(v) => (Array.isArray(v.days) ? …)` then threw a `TypeError`, a 500 from the
18
+ settings screen. It is an `InvalidSettingValueError` (422) now, its reason naming the check's
19
+ message.
20
+ - **A settings group works in a running app.** `SettingsProvider` bound `settings` lazily and
21
+ never resolved it, and the typed groups and the `Settings` facade read the binding with
22
+ `makeSync`, which refuses a singleton nothing has resolved. So with the provider registered,
23
+ every `billing.get(…)` in a request threw "Settings are not available: register
24
+ SettingsProvider". `SettingsFake` and the provider's tests used other paths and passed. The
25
+ provider resolves the manager while booting now.
26
+
27
+ ### Added
28
+
29
+ - **`SettingsFake` checks keys and values at compile time when given the group.**
30
+ `SettingsFake.install(billing, { "billing.paymentTermsDays": 7 })` takes only the keys
31
+ `billing` declares, each with its declared type, in the overrides and in every later
32
+ `override()` and `release()` — the way the group's own `get()` and `set()` do. Pass several
33
+ groups as an array. `SettingsFake.install({ … })` without a group still takes any key and
34
+ rejects an unknown one when the test runs.
35
+
36
+ ## [1.18.0] — 2026-11-26
37
+
38
+ ### Added
39
+
40
+ - **`@zerotal/settings`, a per-tenant settings registry.** Declare settings in code with a typed
41
+ default each — `defineSettings({ "billing.paymentTermsDays": setting.number({ default: 30 }) })`
42
+ — and read them typed: `await billing.get("billing.paymentTermsDays")` is a `number`. A read
43
+ takes the user's override, then the tenant's, then the app-wide one, then the default; the
44
+ tenant comes from `TenantContext` and the user from the signed-in request unless the call
45
+ names them. Each definition says which of those levels may override it.
46
+ - **Hidden, never deleted.** `hide()` stops an override applying and keeps its value;
47
+ `unhide()` puts it back. There is no delete on the manager, the typed group or the store.
48
+ - **Every change audited** through `@zerotal/audit` when `AuditProvider` is registered, one
49
+ trail per setting per level, so `history()` for one tenant never returns another's.
50
+ - **A generated settings screen in the admin panel**: every declared setting with its value
51
+ and where it came from, with Change, Hide override and Unhide, gated on `settings.manage`.
52
+ - **`SettingsFake`** pins a setting for a test and runs overrides in memory with no table.
53
+ - **Runs on SQLite, PostgreSQL and MySQL**; the `zerotal_settings` table is created on boot.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zerotal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # @zerotal/settings
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Per-tenant settings: typed defaults in code, overrides per tenant and per user, hidden but never deleted, audited, with an admin screen.
4
+
5
+ Declare each setting once in code, with its default and the levels allowed to override
6
+ it. Reads are typed and take the most specific value that applies — the user's override,
7
+ then the tenant's, then the app-wide one, then the default. Overrides are hidden rather
8
+ than deleted, every change is recorded by `@zerotal/audit` when it is installed, and the
9
+ admin panel gets a settings screen with nothing to write. **Beta** — the API is close to
10
+ final; read the changelog before upgrading. Reviewed by 1.20.0.
11
+
12
+ Part of the [Zerotal](../../README.md) framework. Requires **Bun ≥ 1.3.14**.
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ bun add @zerotal/settings
18
+ ```
19
+
20
+ ## Setup
21
+
22
+ ```ts
23
+ // bootstrap/providers.ts
24
+ import { SettingsProvider } from "@zerotal/settings";
25
+
26
+ export default [
27
+ // …DatabaseProvider, TenancyProvider, AuditProvider (optional)
28
+ SettingsProvider,
29
+ ];
30
+ ```
31
+
32
+ The `zerotal_settings` table is created on boot. No migration.
33
+
34
+ ## Usage
35
+
36
+ ```ts
37
+ // app/settings.ts
38
+ import { defineSettings, setting } from "@zerotal/settings";
39
+
40
+ export const billing = defineSettings({
41
+ "billing.invoicePrefix": setting.string({ default: "INV-", maxLength: 8 }),
42
+ "billing.paymentTermsDays": setting.number({ default: 30, min: 0, max: 120, integer: true }),
43
+ "billing.locale": setting.enum(["en", "fr"], {
44
+ default: "en",
45
+ scopes: ["global", "tenant", "user"],
46
+ }),
47
+ });
48
+ ```
49
+
50
+ ```ts
51
+ const days = await billing.get("billing.paymentTermsDays"); // number, for the current tenant
52
+ await billing.set("billing.paymentTermsDays", 14); // this tenant's override
53
+ await billing.hide("billing.paymentTermsDays"); // stop applying it; the value is kept
54
+ await billing.unhide("billing.paymentTermsDays"); // and back
55
+ ```
56
+
57
+ In a test:
58
+
59
+ ```ts
60
+ import { SettingsFake } from "@zerotal/settings";
61
+
62
+ // Given the group, keys and values are checked against its definitions.
63
+ const settings = SettingsFake.install(billing, { "billing.paymentTermsDays": 7 });
64
+ // …
65
+ settings.restore();
66
+ ```
67
+
68
+ ## Public API
69
+
70
+ | Export | What it is |
71
+ | ----------------------------------------------- | -------------------------------------------------------------------- |
72
+ | `defineSettings`, `setting` | Declare settings; the typed group every read and write goes through. |
73
+ | `SettingsManager`, `Settings` | The `settings` binding, and its facade for code that works by key. |
74
+ | `SettingsProvider`, `SettingsConfig` | Registration and configuration. |
75
+ | `SettingsFake` | Pin settings in a test; overrides in memory. |
76
+ | `DatabaseStore`, `MemoryStore`, `SettingsStore` | Where overrides live. |
77
+ | `SettingsError` and subclasses | Unknown key, duplicate key, invalid value, level not allowed. |
78
+
79
+ ## Documentation
80
+
81
+ Full guide: [Settings](https://zerotal.dev/docs/settings).
82
+
83
+ ## License
84
+
85
+ MIT
package/api-surface.md ADDED
@@ -0,0 +1,260 @@
1
+ # @zerotal/settings — public API surface
2
+
3
+ <!-- AUTO-GENERATED by scripts/api-surface.ts. Do not edit by hand.
4
+ Run `bun run api:surface` to regenerate after an intentional API change. -->
5
+
6
+ > Not a guide — this is a flat, alphabetical snapshot used to detect unintended
7
+ > API changes. For how to use these, read the [documentation](https://zerotal.dev/docs).
8
+
9
+ ## . `(./src/index.ts)`
10
+
11
+ class DatabaseStore = {
12
+ new (table?: string): DatabaseStore
13
+ find: (keys: readonly string[], scopes: readonly string[]) => Promise<StoredSetting[]>
14
+ put: (key: string, scope: ScopeRef, value: string, updatedBy: string | null) => Promise<StoredSetting | null>
15
+ setHidden: (key: string, scope: string, hidden: boolean, updatedBy: string | null) => Promise<StoredSetting | null>
16
+ }
17
+
18
+ class DuplicateSettingError = {
19
+ new (key: string): DuplicateSettingError
20
+ readonly code: string
21
+ readonly context?: Record<string, unknown> | undefined
22
+ readonly status: number
23
+ }
24
+
25
+ class InvalidSettingValueError = {
26
+ new (key: string, reason: string): InvalidSettingValueError
27
+ readonly code: string
28
+ readonly context?: Record<string, unknown> | undefined
29
+ readonly status: number
30
+ }
31
+
32
+ class MemoryStore = {
33
+ new (): MemoryStore
34
+ all: () => StoredSetting[]
35
+ find: (keys: readonly string[], scopes: readonly string[]) => Promise<StoredSetting[]>
36
+ put: (key: string, scope: ScopeRef, value: string, updatedBy: string | null) => Promise<StoredSetting | null>
37
+ setHidden: (key: string, scope: string, hidden: boolean, updatedBy: string | null) => Promise<StoredSetting | null>
38
+ }
39
+
40
+ class SettingScopeError = {
41
+ new (key: string, reason: string): SettingScopeError
42
+ readonly code: string
43
+ readonly context?: Record<string, unknown> | undefined
44
+ readonly status: number
45
+ }
46
+
47
+ class SettingsError = {
48
+ new (message: string, code?: string, status?: number, context?: Record<string, unknown>): SettingsError
49
+ readonly code: string
50
+ readonly context?: Record<string, unknown> | undefined
51
+ readonly status: number
52
+ }
53
+
54
+ class SettingsFake = {
55
+ new <D extends SettingDefinitions = SettingDefinitions>(app: Application, original: RegistryEntry | undefined, store: MemoryStore): SettingsFake<D>
56
+ static install: { <G extends DefinesSettings>(group: G, overrides?: Partial<SettingValues<G['definitions']>> | undefined): SettingsFake<G['definitions']>; <const G extends readonly DefinesSettings[]>(groups: G, overrides?: Partial<SettingValues<MergedDefinitions<G>>> | undefined): SettingsFake<MergedDefinitions<G>>; (overrides?: Record<string, unknown> | undefined): SettingsFake;}
57
+ all: (scope?: SettingsScope) => Promise<ResolvedSetting[]>
58
+ definitions: () => [string, SettingDefinition][]
59
+ get: (key: string, scope?: SettingsScope) => Promise<unknown>
60
+ hide: (key: string, options?: SettingWriteOptions) => Promise<boolean>
61
+ history: (key: string, options?: SettingHistoryOptions) => Promise<SettingHistoryEntry[]>
62
+ override: <K extends keyof D & string>(key: K, value: SettingValue<D[K]>) => SettingsFake<D>
63
+ readonly memory: MemoryStore
64
+ release: <K extends keyof D & string>(key: K) => SettingsFake<D>
65
+ resolve: (key: string, scope?: SettingsScope) => Promise<ResolvedSetting>
66
+ resolveMany: (keys: readonly string[], scope?: SettingsScope) => Promise<ResolvedSetting[]>
67
+ restore: () => void
68
+ set: (key: string, value: unknown, options?: SettingWriteOptions) => Promise<void>
69
+ setFromText: (key: string, text: string, options?: SettingWriteOptions) => Promise<void>
70
+ stored: () => StoredSetting[]
71
+ unhide: (key: string, options?: SettingWriteOptions) => Promise<boolean>
72
+ }
73
+
74
+ class SettingsManager = {
75
+ new (store: SettingsStore, options?: { audit: boolean; }): SettingsManager
76
+ all: (scope?: SettingsScope) => Promise<ResolvedSetting[]>
77
+ definitions: () => [string, SettingDefinition][]
78
+ get: (key: string, scope?: SettingsScope) => Promise<unknown>
79
+ hide: (key: string, options?: SettingWriteOptions) => Promise<boolean>
80
+ history: (key: string, options?: SettingHistoryOptions) => Promise<SettingHistoryEntry[]>
81
+ resolve: (key: string, scope?: SettingsScope) => Promise<ResolvedSetting>
82
+ resolveMany: (keys: readonly string[], scope?: SettingsScope) => Promise<ResolvedSetting[]>
83
+ set: (key: string, value: unknown, options?: SettingWriteOptions) => Promise<void>
84
+ setFromText: (key: string, text: string, options?: SettingWriteOptions) => Promise<void>
85
+ unhide: (key: string, options?: SettingWriteOptions) => Promise<boolean>
86
+ }
87
+
88
+ class SettingsProvider = {
89
+ new (app: Application): SettingsProvider
90
+ static dependsOn?: (new (app: Application) => ServiceProvider)[]
91
+ static environments: AppEnvironment[]
92
+ static priority?: number
93
+ static provides: readonly ['settings']
94
+ devProcesses: () => DevProcessDefinition[]
95
+ doctorChecks: () => DoctorCheck[]
96
+ onBooted: () => Promise<void>
97
+ onBooting: () => Promise<void>
98
+ onRegister: () => void
99
+ onRequestProcessed: (_ctx: HttpContext) => Promise<void>
100
+ onRequestReceived: (_ctx: HttpContext) => Promise<void>
101
+ onResponseSent: (_ctx: HttpContext) => Promise<void>
102
+ onStarted: () => Promise<void>
103
+ onStarting: () => Promise<void>
104
+ onStopped: () => Promise<void>
105
+ onStopping: () => Promise<void>
106
+ replContext: () => Record<string, unknown>
107
+ }
108
+
109
+ class UnknownSettingError = {
110
+ new (key: string): UnknownSettingError
111
+ readonly code: string
112
+ readonly context?: Record<string, unknown> | undefined
113
+ readonly status: number
114
+ }
115
+
116
+ const setting = { string(options: StringSettingOptions): SettingDefinition<string>; number(options: NumberSettingOptions): SettingDefinition<number>; boolean(options: BooleanSettingOptions): SettingDefinition<boolean>; enum<const T extends string>(values: readonly T[], options: EnumSettingOptions<NoInfer<T>>): SettingDefinition<T>; json<T>(options: JsonSettingOptions<T>): SettingDefinition<T>;}
117
+
118
+ const Settings = SettingsManager
119
+
120
+ const SETTINGS_ABILITY = 'settings.manage'
121
+
122
+ function defineSettings = <const D extends SettingDefinitions>(definitions: D) => SettingsGroup<D>
123
+
124
+ function SettingsConfig = (options?: Partial<SettingsConfigShape>) => SettingsConfigShape
125
+
126
+ interface BaseSettingOptions = {
127
+ default: T
128
+ description?: string | undefined
129
+ group?: string | undefined
130
+ label?: string | undefined
131
+ scopes?: readonly SettingScopeKind[] | undefined
132
+ validate?: ((value: T) => string | undefined | void) | undefined
133
+ }
134
+
135
+ interface NumberSettingOptions = {
136
+ default: number
137
+ description?: string | undefined
138
+ group?: string | undefined
139
+ integer?: boolean | undefined
140
+ label?: string | undefined
141
+ max?: number | undefined
142
+ min?: number | undefined
143
+ scopes?: readonly SettingScopeKind[] | undefined
144
+ validate?: ((value: number) => string | undefined | void) | undefined
145
+ }
146
+
147
+ interface ResolvedSetting = {
148
+ default: T
149
+ key: string
150
+ levels: SettingLevel[]
151
+ source: SettingSource
152
+ value: T
153
+ }
154
+
155
+ interface SettingDefinition = {
156
+ parse: (value: unknown, key: string, fromText?: boolean) => T
157
+ readonly default: T
158
+ readonly description: string | undefined
159
+ readonly group: string | undefined
160
+ readonly label: string | undefined
161
+ readonly options: readonly string[] | undefined
162
+ readonly scopes: readonly SettingScopeKind[]
163
+ readonly type: SettingType
164
+ }
165
+
166
+ interface SettingHistoryEntry = {
167
+ actor: number | null
168
+ at: string
169
+ event: string
170
+ from: unknown
171
+ to: unknown
172
+ }
173
+
174
+ interface SettingHistoryOptions = {
175
+ at?: SettingScopeKind | undefined
176
+ limit?: number | undefined
177
+ tenant?: number | null | undefined
178
+ user?: string | number | null | undefined
179
+ }
180
+
181
+ interface SettingLevel = {
182
+ hidden: boolean
183
+ kind: SettingScopeKind
184
+ updatedAt: string | null
185
+ updatedBy: string | null
186
+ value: unknown
187
+ }
188
+
189
+ interface SettingsConfigShape = {
190
+ audit: boolean
191
+ table: string
192
+ }
193
+
194
+ interface SettingsGroup = {
195
+ all: (scope?: SettingsScope) => Promise<SettingValues<D>>
196
+ explain: <K extends keyof D & string>(key: K, scope?: SettingsScope) => Promise<ResolvedSetting<SettingValue<D[K]>>>
197
+ get: <K extends keyof D & string>(key: K, scope?: SettingsScope) => Promise<SettingValue<D[K]>>
198
+ hide: <K extends keyof D & string>(key: K, options?: SettingWriteOptions) => Promise<boolean>
199
+ history: <K extends keyof D & string>(key: K, options?: SettingHistoryOptions) => Promise<SettingHistoryEntry[]>
200
+ readonly definitions: D
201
+ set: <K extends keyof D & string>(key: K, value: SettingValue<D[K]>, options?: SettingWriteOptions) => Promise<void>
202
+ unhide: <K extends keyof D & string>(key: K, options?: SettingWriteOptions) => Promise<boolean>
203
+ }
204
+
205
+ interface SettingsScope = {
206
+ tenant?: number | null | undefined
207
+ user?: string | number | null | undefined
208
+ }
209
+
210
+ interface SettingsStore = {
211
+ find: (keys: readonly string[], scopes: readonly string[]) => Promise<StoredSetting[]>
212
+ put: (key: string, scope: ScopeRef, value: string, updatedBy: string | null) => Promise<StoredSetting | null>
213
+ setHidden: (key: string, scope: string, hidden: boolean, updatedBy: string | null) => Promise<StoredSetting | null>
214
+ }
215
+
216
+ interface SettingWriteOptions = {
217
+ at?: SettingScopeKind | undefined
218
+ tenant?: number | null | undefined
219
+ user?: string | number | null | undefined
220
+ }
221
+
222
+ interface StoredSetting = {
223
+ hidden: boolean
224
+ key: string
225
+ scope: string
226
+ tenantId: number | null
227
+ updatedAt: string | null
228
+ updatedBy: string | null
229
+ userId: string | null
230
+ value: string
231
+ }
232
+
233
+ interface StringSettingOptions = {
234
+ default: string
235
+ description?: string | undefined
236
+ group?: string | undefined
237
+ label?: string | undefined
238
+ maxLength?: number | undefined
239
+ pattern?: RegExp | undefined
240
+ scopes?: readonly SettingScopeKind[] | undefined
241
+ validate?: ((value: string) => string | undefined | void) | undefined
242
+ }
243
+
244
+ type BooleanSettingOptions = BaseSettingOptions<boolean>
245
+
246
+ type EnumSettingOptions = BaseSettingOptions<T>
247
+
248
+ type JsonSettingOptions = BaseSettingOptions<T>
249
+
250
+ type SettingDefinitions = { [x: string]: SettingDefinition<unknown>;}
251
+
252
+ type SettingScopeKind = 'global' | 'tenant' | 'user'
253
+
254
+ type SettingSource = SettingScopeKind | 'default' | 'override'
255
+
256
+ type SettingType = 'string' | 'number' | 'boolean' | 'enum' | 'json'
257
+
258
+ type SettingValue = D extends SettingDefinition<infer T> ? T : never
259
+
260
+ type SettingValues = { [K in keyof D]: SettingValue<D[K]>; }
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@zerotal/settings",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.18.1",
4
+ "license": "MIT",
5
+ "maturity": "beta",
6
+ "maturityReview": "1.20.0",
7
+ "private": false,
8
+ "type": "module",
9
+ "main": "./src/index.ts",
10
+ "types": "./src/index.ts",
11
+ "exports": {
12
+ ".": "./src/index.ts"
13
+ },
14
+ "files": [
15
+ "CHANGELOG.md",
16
+ "api-surface.md",
17
+ "src",
18
+ "!src/**/*.test.ts",
19
+ "!src/**/*.test.tsx",
20
+ "!src/**/*.spec.ts",
21
+ "!src/**/__fixtures__/**"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "engines": {
27
+ "bun": ">=1.3.14"
28
+ },
29
+ "scripts": {
30
+ "test": "bun test",
31
+ "typecheck": "tsc --noEmit"
32
+ },
33
+ "dependencies": {
34
+ "@zerotal/core": "1.18.1",
35
+ "@zerotal/orm": "1.18.1",
36
+ "@zerotal/tenancy": "1.18.1"
37
+ },
38
+ "devDependencies": {
39
+ "@zerotal/audit": "1.18.1",
40
+ "typescript": "^5.8.0"
41
+ },
42
+ "description": "Per-tenant settings for Zerotal: typed defaults in code, overrides per tenant and per user, hidden but never deleted, audited, with an admin screen.",
43
+ "keywords": [
44
+ "zerotal",
45
+ "bun",
46
+ "typescript",
47
+ "framework",
48
+ "settings",
49
+ "tenancy"
50
+ ],
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/zerotaldev/zerotal.git",
54
+ "directory": "packages/settings"
55
+ },
56
+ "homepage": "https://github.com/zerotaldev/zerotal/tree/main/packages/settings#readme",
57
+ "bugs": "https://github.com/zerotaldev/zerotal/issues"
58
+ }
@@ -0,0 +1,151 @@
1
+ import { Application, currentApp } from "@zerotal/core";
2
+ import type { SettingDefinitions, SettingValue, SettingValues } from "./defineSettings.ts";
3
+ import { _definitionOf } from "./registry.ts";
4
+ import { SettingsManager } from "./SettingsManager.ts";
5
+ import type { ResolvedSetting } from "./SettingsManager.ts";
6
+ import type { SettingsScope } from "./scope.ts";
7
+ import { MemoryStore } from "./stores/MemoryStore.ts";
8
+ import type { StoredSetting } from "./stores/SettingsStore.ts";
9
+
10
+ /** One entry of the container's registry, as `install()` saves it and `restore()` puts it back. */
11
+ type RegistryEntry = Application["container"]["registry"] extends Map<unknown, infer B> ? B : never;
12
+
13
+ /**
14
+ * Anything carrying setting definitions: what `defineSettings()` returns, or a
15
+ * plain `{ definitions }`. Structural, so the fake does not depend on the group's
16
+ * methods.
17
+ */
18
+ interface DefinesSettings<D extends SettingDefinitions = SettingDefinitions> {
19
+ readonly definitions: D;
20
+ }
21
+
22
+ /** Every key of several groups, with each key's own type. */
23
+ type MergedDefinitions<G extends readonly DefinesSettings[]> = _Intersect<G[number]["definitions"]>;
24
+
25
+ /** A union of definition sets, as one set holding every key. */
26
+ type _Intersect<U> = (U extends unknown ? (u: U) => void : never) extends (i: infer I) => void
27
+ ? I extends SettingDefinitions
28
+ ? I
29
+ : never
30
+ : never;
31
+
32
+ function _isGroup(value: unknown): value is DefinesSettings {
33
+ return (
34
+ typeof value === "object" &&
35
+ value !== null &&
36
+ !Array.isArray(value) &&
37
+ "definitions" in value &&
38
+ typeof value.definitions === "object" &&
39
+ value.definitions !== null &&
40
+ "get" in value &&
41
+ typeof value.get === "function"
42
+ );
43
+ }
44
+
45
+ /**
46
+ * Settings for a test: an in-memory store in place of the table, and a way to
47
+ * pin a setting to a value whoever reads it.
48
+ *
49
+ * Everything else behaves as it does in the app — tenant and user overrides,
50
+ * hiding, restoring, validation — so a test of those needs no database. A pinned
51
+ * value is checked against its definition, and wins over every level until it is
52
+ * released or the fake is restored.
53
+ *
54
+ * Given the groups `defineSettings()` returned, the fake takes only their keys,
55
+ * and each value as its declared type, the way the groups themselves do. Given
56
+ * none, it takes any key and checks it when the test runs.
57
+ *
58
+ * @example
59
+ * const settings = SettingsFake.install(billing, { "billing.paymentTermsDays": 7 });
60
+ * expect(await billing.get("billing.paymentTermsDays")).toBe(7);
61
+ * settings.override("billing.paymentTermsDays", "7"); // type error: a number
62
+ * settings.restore(); // in afterEach
63
+ */
64
+ export class SettingsFake<
65
+ D extends SettingDefinitions = SettingDefinitions,
66
+ > extends SettingsManager {
67
+ /** The store behind the fake, for asserting on what was written. */
68
+ readonly memory: MemoryStore;
69
+ private readonly _pins = new Map<string, unknown>();
70
+ private readonly _app: Application;
71
+ private readonly _original: RegistryEntry | undefined;
72
+
73
+ private constructor(app: Application, original: RegistryEntry | undefined, store: MemoryStore) {
74
+ super(store, { audit: false });
75
+ this.memory = store;
76
+ this._app = app;
77
+ this._original = original;
78
+ }
79
+
80
+ /**
81
+ * Replace the `settings` binding with a fake, pinning `overrides` from the start.
82
+ *
83
+ * Pass the group `defineSettings()` returned (or several, in an array) first, and
84
+ * the overrides and every later `override()` and `release()` are checked against
85
+ * its keys and value types at compile time. With overrides alone, keys are checked
86
+ * when the test runs.
87
+ */
88
+ static install<G extends DefinesSettings>(
89
+ group: G,
90
+ overrides?: Partial<SettingValues<G["definitions"]>> | undefined,
91
+ ): SettingsFake<G["definitions"]>;
92
+ static install<const G extends readonly DefinesSettings[]>(
93
+ groups: G,
94
+ overrides?: Partial<SettingValues<MergedDefinitions<G>>> | undefined,
95
+ ): SettingsFake<MergedDefinitions<G>>;
96
+ static install(overrides?: Record<string, unknown> | undefined): SettingsFake;
97
+ static install(
98
+ groupsOrOverrides?: DefinesSettings | readonly DefinesSettings[] | Record<string, unknown>,
99
+ overrides?: Record<string, unknown>,
100
+ ): SettingsFake {
101
+ const typed = Array.isArray(groupsOrOverrides) || _isGroup(groupsOrOverrides);
102
+ const pins =
103
+ (typed ? overrides : (groupsOrOverrides as Record<string, unknown> | undefined)) ?? {};
104
+ const app = currentApp();
105
+ const original = app.container.registry.get("settings");
106
+ const fake = new SettingsFake(app, original, new MemoryStore());
107
+ for (const [key, value] of Object.entries(pins)) fake.override(key, value);
108
+ app.container.value("settings", fake);
109
+ return fake;
110
+ }
111
+
112
+ /** Restore the original `settings` binding. Call in afterEach. */
113
+ restore(): void {
114
+ if (this._original !== undefined) {
115
+ this._app.container.registry.set("settings", this._original);
116
+ } else {
117
+ this._app.container.registry.delete("settings");
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Pin a setting to `value` for every reader, above every stored level. The value
123
+ * must fit the setting's definition, so a test cannot pin what the app could
124
+ * never hold.
125
+ */
126
+ override<K extends keyof D & string>(key: K, value: SettingValue<D[K]>): this {
127
+ this._pins.set(key, _definitionOf(key).parse(value, key));
128
+ return this;
129
+ }
130
+
131
+ /** Release a pin, so the setting resolves normally again. */
132
+ release<K extends keyof D & string>(key: K): this {
133
+ this._pins.delete(key);
134
+ return this;
135
+ }
136
+
137
+ /** Every override written through the fake, hidden ones included. */
138
+ stored(): StoredSetting[] {
139
+ return this.memory.all();
140
+ }
141
+
142
+ override async resolveMany(
143
+ keys: readonly string[],
144
+ scope?: SettingsScope,
145
+ ): Promise<ResolvedSetting[]> {
146
+ const resolved = await super.resolveMany(keys, scope);
147
+ return resolved.map((r) =>
148
+ this._pins.has(r.key) ? { ...r, value: this._pins.get(r.key), source: "override" } : r,
149
+ );
150
+ }
151
+ }