@zucker-framework/config 1.0.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,382 @@
1
+ import { DatabaseAdapter } from '@zucker-framework/core';
2
+ import { EventEmitter2 } from 'eventemitter2';
3
+ import { DynamicModule, Type, InjectionToken, OptionalFactoryDependency, CanActivate, ExecutionContext } from '@nestjs/common';
4
+ import { FeatureFlagEvaluator } from '@zucker-framework/feature-flags';
5
+ export { FeatureFlagDecisionReason, FeatureFlagEnvironmentReader, FeatureFlagEvaluation, FeatureFlagEvaluator, FlagContext, FlagDefinition, FlagRule, FlagRuleType, defaultFeatureFlagEnvKey } from '@zucker-framework/feature-flags';
6
+ export { DATABASE_ADAPTER } from '@zucker-framework/crud';
7
+
8
+ /**
9
+ * ConfigScopeCustomizer — implement to register custom config scopes.
10
+ *
11
+ * Reference: jetlinks ConfigScopeCustomizer
12
+ */
13
+ interface ConfigScopeCustomizer {
14
+ custom(manager: ConfigScopeManager): void;
15
+ }
16
+ /**
17
+ * ConfigScopeManager — register and retrieve config scopes.
18
+ *
19
+ * Reference: jetlinks ConfigScopeManager + SimpleConfigManager
20
+ */
21
+ declare class ConfigScopeManager {
22
+ private readonly logger;
23
+ private readonly scopes;
24
+ /**
25
+ * Register a fully defined scope.
26
+ */
27
+ register(scope: ConfigScope): void;
28
+ /**
29
+ * Add a scope with separate property definitions — mirrors jetlinks ConfigScopeManager.addScope().
30
+ *
31
+ * Reference: jetlinks ConfigScopeManager.addScope(ConfigScope, List<ConfigPropertyDef>)
32
+ */
33
+ addScope(scopePartial: {
34
+ id: string;
35
+ name: string;
36
+ publicAccess?: boolean;
37
+ }, properties: ConfigPropertyDef[]): void;
38
+ /**
39
+ * Apply customizers — call during module initialization.
40
+ *
41
+ * Reference: jetlinks ConfigScopeProperties.custom()
42
+ */
43
+ applyCustomizers(customizers: ConfigScopeCustomizer[]): void;
44
+ get(scopeId: string): ConfigScope | undefined;
45
+ getAll(): ConfigScope[];
46
+ has(scopeId: string): boolean;
47
+ unregister(scopeId: string): boolean;
48
+ /**
49
+ * Get all scopes marked as public access.
50
+ *
51
+ * Reference: jetlinks SystemConfigManagerController checks isPublicAccess()
52
+ * for unauthenticated access.
53
+ */
54
+ getPublicScopes(): ConfigScope[];
55
+ getProperties(scopeId: string): ConfigPropertyDef[];
56
+ /**
57
+ * Validate a config value against its scope property definition.
58
+ * Returns error messages if invalid.
59
+ */
60
+ validate(scopeId: string, key: string, value: unknown): string[];
61
+ }
62
+
63
+ declare const CONFIG_CHANGED_EVENT = "zucker.config-changed";
64
+ /**
65
+ * TopicEventBus topic for config changes.
66
+ * Uses `/` delimiter to match DefaultTopicEventBus conventions.
67
+ * Subscribers can use wildcards: `system/config/**`
68
+ */
69
+ declare const CONFIG_CHANGED_TOPIC = "system/config/changed";
70
+ /** Optional encryption adapter for encrypting/decrypting sensitive config values */
71
+ declare const CONFIG_ENCRYPTOR = "CONFIG_ENCRYPTOR";
72
+ interface ConfigChangePayload {
73
+ scope: string;
74
+ key: string;
75
+ oldValue: unknown;
76
+ newValue: unknown;
77
+ }
78
+ /**
79
+ * Encryption adapter interface for config values.
80
+ *
81
+ * Reference: jetlinks stores some config values encrypted;
82
+ * this provides a pluggable encryption mechanism.
83
+ */
84
+ interface ConfigEncryptor {
85
+ encrypt(value: string): string | Promise<string>;
86
+ decrypt(value: string): string | Promise<string>;
87
+ }
88
+ /** Minimal TopicEventBus interface to avoid hard dependency on @zucker-framework/event */
89
+ interface TopicEventBusLike$1 {
90
+ publish(topic: string, payload: unknown): Promise<void>;
91
+ }
92
+ declare class ConfigService {
93
+ private readonly db;
94
+ private readonly eventEmitter?;
95
+ private readonly scopeManager?;
96
+ private readonly encryptor?;
97
+ private readonly topicEventBus?;
98
+ private readonly logger;
99
+ private readonly cache;
100
+ private static readonly CACHE_MAX_SIZE;
101
+ constructor(db: DatabaseAdapter, eventEmitter?: EventEmitter2 | undefined, scopeManager?: ConfigScopeManager | undefined, encryptor?: ConfigEncryptor | undefined, topicEventBus?: TopicEventBusLike$1 | undefined);
102
+ /**
103
+ * 获取指定 scope 和 key 的配置值
104
+ * @param scope 配置域
105
+ * @param key 配置键
106
+ * @returns 配置值,不存在时返回 undefined
107
+ */
108
+ get<T = string>(scope: string, key: string): Promise<T | undefined>;
109
+ /**
110
+ * Get a config value with a fallback default.
111
+ * If no stored value exists, checks the scope definition default,
112
+ * then falls back to the provided default.
113
+ *
114
+ * Reference: jetlinks getProperties merges defaults from ConfigPropertyDef.
115
+ */
116
+ getOrDefault<T = string>(scope: string, key: string, defaultValue: T): Promise<T>;
117
+ /**
118
+ * 设置配置值(自动触发变更事件)
119
+ * @param scope 配置域
120
+ * @param key 配置键
121
+ * @param value 配置值
122
+ * @throws ValidationException 校验失败时
123
+ */
124
+ set(scope: string, key: string, value: unknown): Promise<void>;
125
+ /**
126
+ * Set multiple properties at once for a scope.
127
+ * Performs batch validation first, then persists all values and emits
128
+ * a single consolidated event — mirrors jetlinks ConfigManager.setProperties(scope, Map)
129
+ * which does repository.save + cache.evict instead of N individual updates.
130
+ */
131
+ setProperties(scope: string, values: Record<string, unknown>): Promise<void>;
132
+ /**
133
+ * 获取指定 scope 下的所有配置
134
+ * @param scope 配置域
135
+ * @returns 键值对集合(包含默认值)
136
+ */
137
+ getAll(scope: string): Promise<Record<string, unknown>>;
138
+ /**
139
+ * Remove a specific config property.
140
+ */
141
+ remove(scope: string, key: string): Promise<void>;
142
+ /**
143
+ * 监听配置变更事件
144
+ * @param callback 变更回调
145
+ * @returns 订阅句柄,调用 unsubscribe() 取消监听
146
+ */
147
+ onChange(callback: (payload: ConfigChangePayload) => void): {
148
+ unsubscribe: () => void;
149
+ };
150
+ /**
151
+ * 监听指定 scope.key 的配置变更,每次变更时执行回调。
152
+ *
153
+ * @param scope 配置域
154
+ * @param key 配置键(可选,不传则监听整个 scope)
155
+ * @param callback 变更回调
156
+ * @returns 取消监听函数
157
+ */
158
+ watch<T = unknown>(scope: string, key: string | undefined, callback: (newValue: T, oldValue: T | undefined) => void): {
159
+ unsubscribe: () => void;
160
+ };
161
+ /**
162
+ * 清除配置缓存
163
+ * @param scope 可选的配置域,不传则清除所有缓存
164
+ */
165
+ clearCache(scope?: string): void;
166
+ /**
167
+ * 记录配置变更历史(自动版本号递增)
168
+ * 配置版本控制
169
+ */
170
+ private recordHistory;
171
+ /**
172
+ * 查询配置变更历史
173
+ * @param scope 配置域
174
+ * @param key 配置键(可选,不传则查询该 scope 所有变更)
175
+ * @param limit 返回条数(默认 20)
176
+ */
177
+ getHistory(scope: string, key?: string, limit?: number): Promise<Array<{
178
+ scope: string;
179
+ key: string;
180
+ oldValue: unknown;
181
+ newValue: unknown;
182
+ changedAt: Date;
183
+ }>>;
184
+ /**
185
+ * 回滚配置到指定历史版本
186
+ * @param historyId 历史记录 ID
187
+ */
188
+ rollback(historyId: string): Promise<void>;
189
+ /**
190
+ * Check if a property is marked as encrypted in its scope definition.
191
+ */
192
+ private isEncryptedProperty;
193
+ }
194
+
195
+ interface ZuckerConfigModuleOptions {
196
+ /** Optional encryption adapter for sensitive config values */
197
+ encryptor?: ConfigEncryptor;
198
+ /** Optional scope customizers to register scopes during init */
199
+ customizers?: ConfigScopeCustomizer[];
200
+ }
201
+ declare const CONFIG_MODULE_OPTIONS: unique symbol;
202
+ interface ZuckerConfigModuleAsyncOptions {
203
+ imports?: Array<Type | DynamicModule>;
204
+ useFactory?: (...args: unknown[]) => ZuckerConfigModuleOptions | Promise<ZuckerConfigModuleOptions>;
205
+ useClass?: Type<ZuckerConfigModuleOptionsFactory>;
206
+ useExisting?: Type<ZuckerConfigModuleOptionsFactory>;
207
+ inject?: Array<InjectionToken | OptionalFactoryDependency>;
208
+ }
209
+ interface ZuckerConfigModuleOptionsFactory {
210
+ createConfigOptions(): ZuckerConfigModuleOptions | Promise<ZuckerConfigModuleOptions>;
211
+ }
212
+ declare class ZuckerConfigModule {
213
+ static forRoot(options?: ZuckerConfigModuleOptions): DynamicModule;
214
+ static forRootAsync(options: ZuckerConfigModuleAsyncOptions): DynamicModule;
215
+ private static createAsyncProviders;
216
+ }
217
+
218
+ declare const CONFIG_SCOPE_REGISTRY = "CONFIG_SCOPE_REGISTRY";
219
+ interface ConfigScopeEntry {
220
+ name: string;
221
+ publicAccess: boolean;
222
+ }
223
+ /**
224
+ * ConfigGuard — 配置访问守卫
225
+ *
226
+ * 检查请求的 scope 是否标记为 publicAccess,
227
+ * 如果是公开的则跳过认证,否则要求请求已认证。
228
+ */
229
+ declare class ConfigGuard implements CanActivate {
230
+ private readonly scopeRegistry;
231
+ private readonly logger;
232
+ constructor(scopeRegistry: Map<string, ConfigScopeEntry>);
233
+ canActivate(context: ExecutionContext): boolean;
234
+ private isAuthenticated;
235
+ }
236
+
237
+ type ConfigLayer = 'system' | 'tenant' | 'user';
238
+ declare const CONFIG_LAYER_PRIORITY: Record<ConfigLayer, number>;
239
+ declare const LAYERED_CONFIG_CHANGED_EVENT = "zucker.layered-config-changed";
240
+ /**
241
+ * TopicEventBus topic for layered config changes.
242
+ * Uses `/` delimiter to match DefaultTopicEventBus conventions.
243
+ */
244
+ declare const LAYERED_CONFIG_CHANGED_TOPIC = "system/config/layered-changed";
245
+ /** Minimal TopicEventBus interface to avoid hard dependency on @zucker-framework/event */
246
+ interface TopicEventBusLike {
247
+ publish(topic: string, payload: unknown): Promise<void>;
248
+ }
249
+ interface LayeredConfigChangePayload {
250
+ scope: string;
251
+ key: string;
252
+ layer: ConfigLayer;
253
+ oldValue: unknown;
254
+ newValue: unknown;
255
+ }
256
+ interface LayeredConfigContext {
257
+ tenantId?: string;
258
+ userId?: string;
259
+ }
260
+ /**
261
+ * LayeredConfigService — config with layered inheritance: system -> tenant -> user.
262
+ *
263
+ * Higher layers override lower layers. When getting a value, the most specific
264
+ * layer with a value wins.
265
+ */
266
+ declare class LayeredConfigService {
267
+ private readonly db;
268
+ private readonly scopeManager;
269
+ private readonly eventEmitter?;
270
+ private readonly topicEventBus?;
271
+ private readonly logger;
272
+ private readonly cache;
273
+ constructor(db: DatabaseAdapter, scopeManager: ConfigScopeManager, eventEmitter?: EventEmitter2 | undefined, topicEventBus?: TopicEventBusLike | undefined);
274
+ /**
275
+ * Get a config value, resolving through layers (user > tenant > system > default).
276
+ */
277
+ get<T = unknown>(scope: string, key: string, context?: LayeredConfigContext): Promise<T | undefined>;
278
+ /**
279
+ * Set a config value at a specific layer.
280
+ */
281
+ set(scope: string, key: string, value: unknown, layer: ConfigLayer, ownerId?: string): Promise<void>;
282
+ /**
283
+ * Get all values for a scope, merged across layers.
284
+ */
285
+ getAll(scope: string, context?: LayeredConfigContext): Promise<Record<string, unknown>>;
286
+ /**
287
+ * Set multiple properties at a specific layer.
288
+ * Validates all entries first, then persists in batch.
289
+ *
290
+ * Reference: jetlinks ConfigManager.setProperties(scope, Map)
291
+ */
292
+ setProperties(scope: string, values: Record<string, unknown>, layer: ConfigLayer, ownerId?: string): Promise<void>;
293
+ /**
294
+ * Remove a config value at a specific layer.
295
+ */
296
+ remove(scope: string, key: string, layer: ConfigLayer, ownerId?: string): Promise<void>;
297
+ /**
298
+ * Clear the in-memory cache.
299
+ * @param scope Optional — only clear entries for this scope prefix
300
+ */
301
+ clearCache(scope?: string): void;
302
+ private getLayerValue;
303
+ private getLayerRecords;
304
+ private buildLayerKey;
305
+ }
306
+
307
+ declare class FeatureFlagService extends FeatureFlagEvaluator {
308
+ constructor();
309
+ }
310
+
311
+ /**
312
+ * 配置文件热重载监听器 — 对标 Claude Code changeDetector.ts
313
+ *
314
+ * 监听配置文件变化,带写入稳定性检测和删除宽限期。
315
+ *
316
+ * 用法:
317
+ * ```ts
318
+ * const watcher = new ConfigFileWatcher();
319
+ * watcher.watch('/path/to/config.json', () => {
320
+ * configService.clearCache();
321
+ * logger.log('Config reloaded');
322
+ * });
323
+ *
324
+ * // 停止监听
325
+ * watcher.close();
326
+ * ```
327
+ */
328
+ interface ConfigWatcherOptions {
329
+ /** 写入稳定性延迟:文件修改后等待此时间无新修改才触发回调(毫秒) */
330
+ stabilityMs?: number;
331
+ /** 删除宽限期:文件删除后等待此时间,若重建则不触发删除回调 */
332
+ deleteGraceMs?: number;
333
+ }
334
+ declare class ConfigFileWatcher {
335
+ private readonly logger;
336
+ private readonly stabilityMs;
337
+ private readonly deleteGraceMs;
338
+ private readonly watched;
339
+ constructor(options?: ConfigWatcherOptions);
340
+ /**
341
+ * 开始监听文件
342
+ * @returns 取消监听函数
343
+ */
344
+ watch(filePath: string, callback: () => void): () => void;
345
+ /**
346
+ * 停止监听指定文件
347
+ */
348
+ unwatch(filePath: string): void;
349
+ /**
350
+ * 关闭所有监听
351
+ */
352
+ close(): void;
353
+ /**
354
+ * 获取当前监听的文件列表
355
+ */
356
+ getWatchedFiles(): string[];
357
+ private handleEvent;
358
+ private getModifiedTime;
359
+ }
360
+
361
+ interface ConfigPropertyDef {
362
+ key: string;
363
+ name: string;
364
+ type: string;
365
+ defaultValue: unknown;
366
+ description: string;
367
+ readonly: boolean;
368
+ /** Whether this property value should be encrypted at rest */
369
+ encrypted?: boolean;
370
+ /** Sort order for display */
371
+ sortOrder?: number;
372
+ }
373
+ interface ConfigScope {
374
+ id: string;
375
+ name: string;
376
+ isPublic: boolean;
377
+ /** Whether public access is allowed (no auth required) */
378
+ publicAccess: boolean;
379
+ properties: ConfigPropertyDef[];
380
+ }
381
+
382
+ export { CONFIG_CHANGED_EVENT, CONFIG_CHANGED_TOPIC, CONFIG_ENCRYPTOR, CONFIG_LAYER_PRIORITY, CONFIG_MODULE_OPTIONS, CONFIG_SCOPE_REGISTRY, type ConfigChangePayload, type ConfigEncryptor, ConfigFileWatcher, ConfigGuard, type ConfigLayer, type ConfigPropertyDef, type ConfigScope, type ConfigScopeCustomizer, type ConfigScopeEntry, ConfigScopeManager, ConfigService, type ConfigWatcherOptions, FeatureFlagService, LAYERED_CONFIG_CHANGED_EVENT, LAYERED_CONFIG_CHANGED_TOPIC, type LayeredConfigChangePayload, type LayeredConfigContext, LayeredConfigService, ZuckerConfigModule, type ZuckerConfigModuleAsyncOptions, type ZuckerConfigModuleOptions, type ZuckerConfigModuleOptionsFactory };