-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig-usage.ts
More file actions
454 lines (373 loc) · 12.3 KB
/
config-usage.ts
File metadata and controls
454 lines (373 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/**
* Config plugin usage examples for @tegmentum/wasi-polyfill
*
* This example demonstrates how to use the config plugin with
* different sources: static values, remote URLs, layered configs,
* manifests, and environment variable bridging.
*/
import { createDevPolyfill, Polyfill } from '@tegmentum/wasi-polyfill'
import {
configRuntimePlugin,
configStorePlugin,
configPlugins,
runtimeConfigImplementation,
remoteConfigImplementation,
layeredConfigImplementation,
manifestConfigImplementation,
envBridgeConfigImplementation,
fixedConfigImplementation,
MutableConfigStore,
createRemoteConfigSource,
createLayeredConfig,
createSimpleLayeredConfig,
ManifestConfigSource,
createManifestSource,
EnvBridgeConfigSource,
createEnvBridgeSource,
envMapping,
envPrefix,
createFixedConfig,
emptyFixedConfig,
mergeFixedConfigs,
} from '@tegmentum/wasi-polyfill/plugins/config'
// ============================================================================
// Example 1: Static Runtime Config
// ============================================================================
async function staticConfigUsage() {
const polyfill = createDevPolyfill()
// Register config plugin with static values
polyfill.registerPlugin(configRuntimePlugin, {
implementation: 'runtime',
// Static configuration values
values: {
'app.name': 'My Application',
'app.version': '1.0.0',
'feature.dark-mode': 'true',
'api.endpoint': 'https://api.example.com',
'api.timeout': '30000',
},
})
const result = await polyfill.forInterfaces([
'wasi:config/runtime@0.2.0-draft',
])
console.log('Static config loaded')
// Access the config functions
const imports = result.imports['wasi:config/runtime@0.2.0-draft']
const get = imports['get'] as (
key: string
) => { tag: 'ok'; val: string } | { tag: 'err'; val: unknown }
// Get a config value
const appName = get('app.name')
if (appName.tag === 'ok') {
console.log('App name:', appName.val)
}
polyfill.destroy()
}
// ============================================================================
// Example 2: Mutable Config Store
// ============================================================================
async function mutableConfigUsage() {
const polyfill = createDevPolyfill()
// Create a mutable store that can be updated at runtime
const store = new MutableConfigStore({
'debug.enabled': 'false',
'feature.flags': 'feature-a,feature-b',
})
polyfill.registerPlugin(configRuntimePlugin, {
implementation: 'runtime',
store,
})
const result = await polyfill.forInterfaces([
'wasi:config/runtime@0.2.0-draft',
])
// Update config at runtime (e.g., from admin panel)
store.set('debug.enabled', 'true')
store.set('new.key', 'new-value')
// Delete a config key
store.delete('feature.flags')
// Get all keys
const keys = store.keys()
console.log('Config keys:', keys)
polyfill.destroy()
}
// ============================================================================
// Example 3: Remote Config from URL
// ============================================================================
async function remoteConfigUsage() {
const polyfill = createDevPolyfill()
// Create a remote config source
const remoteSource = createRemoteConfigSource({
url: 'https://config.example.com/app-config.json',
format: 'json', // 'json' | 'env' | 'properties'
// Refresh interval (optional)
refreshIntervalMs: 60000, // Refresh every minute
// Authentication (optional)
headers: {
Authorization: 'Bearer config-token',
},
// Fallback values if remote fails
fallback: {
'app.name': 'Default App',
},
})
polyfill.registerPlugin(configRuntimePlugin, {
implementation: 'remote',
source: remoteSource,
})
const result = await polyfill.forInterfaces([
'wasi:config/runtime@0.2.0-draft',
])
console.log('Remote config loaded')
// The config is automatically refreshed in the background
// Use remoteSource.refresh() to manually trigger a refresh
polyfill.destroy()
}
// ============================================================================
// Example 4: Layered Config (Multiple Sources)
// ============================================================================
async function layeredConfigUsage() {
const polyfill = createDevPolyfill()
// Create a layered config with multiple sources (higher priority last)
const layeredConfig = createLayeredConfig([
// Layer 0: Default values (lowest priority)
{
name: 'defaults',
values: {
'log.level': 'info',
'cache.enabled': 'true',
'cache.ttl': '3600',
},
},
// Layer 1: Remote config (medium priority)
{
name: 'remote',
source: createRemoteConfigSource({
url: 'https://config.example.com/config.json',
}),
},
// Layer 2: Local overrides (highest priority)
{
name: 'overrides',
values: {
'log.level': 'debug', // Override remote/default
},
},
])
polyfill.registerPlugin(configRuntimePlugin, {
implementation: 'layered',
config: layeredConfig,
})
const result = await polyfill.forInterfaces([
'wasi:config/runtime@0.2.0-draft',
])
console.log('Layered config loaded')
// Config resolution order (last wins):
// 1. defaults
// 2. remote
// 3. overrides
polyfill.destroy()
}
// ============================================================================
// Example 5: Simple Layered Config Helper
// ============================================================================
async function simpleLayeredConfigUsage() {
const polyfill = createDevPolyfill()
// Simple helper for common pattern: defaults + remote + overrides
const layeredConfig = createSimpleLayeredConfig({
defaults: {
'app.mode': 'production',
'api.retries': '3',
},
remoteUrl: 'https://config.example.com/config.json',
overrides: {
'app.mode': 'development', // Override for local dev
},
})
polyfill.registerPlugin(configRuntimePlugin, {
implementation: 'layered',
config: layeredConfig,
})
const result = await polyfill.forInterfaces([
'wasi:config/runtime@0.2.0-draft',
])
console.log('Simple layered config loaded')
polyfill.destroy()
}
// ============================================================================
// Example 6: Manifest-Based Config (TOML/YAML/JSON)
// ============================================================================
async function manifestConfigUsage() {
const polyfill = createDevPolyfill()
// Load config from a manifest file
const manifestSource = createManifestSource({
// Can be a URL or inline content
url: '/config/app-config.toml',
format: 'toml', // 'json' | 'yaml' | 'toml'
// Key path to extract (dot-separated)
rootPath: 'app.settings',
// Variable interpolation
interpolation: {
env: {
NODE_ENV: 'production',
API_KEY: 'secret-key',
},
},
})
polyfill.registerPlugin(configRuntimePlugin, {
implementation: 'manifest',
source: manifestSource,
})
const result = await polyfill.forInterfaces([
'wasi:config/runtime@0.2.0-draft',
])
console.log('Manifest config loaded')
// Example TOML file:
// [app.settings]
// name = "My App"
// version = "1.0.0"
// api_key = "${API_KEY}"
// mode = "${NODE_ENV}"
polyfill.destroy()
}
// ============================================================================
// Example 7: Environment Variable Bridge
// ============================================================================
async function envBridgeConfigUsage() {
const polyfill = createDevPolyfill()
// Bridge environment variables to WASI config
const envSource = createEnvBridgeSource({
// Explicit mappings: env var -> config key
mappings: [
envMapping('DATABASE_URL', 'db.connection-string'),
envMapping('API_KEY', 'api.key'),
envMapping('LOG_LEVEL', 'log.level', 'info'), // with default
],
// Prefix-based mappings
prefixes: [
envPrefix('APP_', 'app.'), // APP_NAME -> app.name
envPrefix('FEATURE_', 'feature.'), // FEATURE_DARK_MODE -> feature.dark-mode
],
// Transform function for keys (optional)
keyTransform: (key) => key.toLowerCase().replace(/_/g, '-'),
})
polyfill.registerPlugin(configRuntimePlugin, {
implementation: 'env-bridge',
source: envSource,
})
const result = await polyfill.forInterfaces([
'wasi:config/runtime@0.2.0-draft',
])
console.log('Env bridge config loaded')
// This bridges environment variables to WASI config interface
// Useful for 12-factor apps and container deployments
polyfill.destroy()
}
// ============================================================================
// Example 8: Fixed Config (Immutable Snapshot)
// ============================================================================
async function fixedConfigUsage() {
const polyfill = createDevPolyfill()
// Create an immutable config snapshot
const fixedConfig = createFixedConfig({
'app.name': 'Production App',
'app.version': '2.0.0',
'feature.enabled': 'true',
})
polyfill.registerPlugin(configRuntimePlugin, {
implementation: 'fixed',
config: fixedConfig,
})
const result = await polyfill.forInterfaces([
'wasi:config/runtime@0.2.0-draft',
])
console.log('Fixed config loaded')
// Merge multiple fixed configs
const base = createFixedConfig({ 'a': '1', 'b': '2' })
const overrides = createFixedConfig({ 'b': '3', 'c': '4' })
const merged = mergeFixedConfigs(base, overrides)
// Result: { a: '1', b: '3', c: '4' }
polyfill.destroy()
}
// ============================================================================
// Example 9: Config Store (Key-Value Style)
// ============================================================================
async function configStoreUsage() {
const polyfill = createDevPolyfill()
// Register config store plugin (different interface than runtime)
polyfill.registerPlugin(configStorePlugin, {
implementation: 'runtime',
values: {
'namespace:key1': 'value1',
'namespace:key2': 'value2',
'other:key1': 'value3',
},
})
const result = await polyfill.forInterfaces(['wasi:config/store@0.2.0-draft'])
console.log('Config store loaded')
// The store interface provides:
// - open(name: string) -> result<bucket, error>
// - bucket.get(key: string) -> result<option<string>, error>
// - bucket.set(key: string, value: string) -> result<_, error>
// - bucket.delete(key: string) -> result<_, error>
// - bucket.exists(key: string) -> result<bool, error>
// - bucket.get-keys() -> result<list<string>, error>
polyfill.destroy()
}
// ============================================================================
// Example 10: Development vs Production Config
// ============================================================================
async function envSpecificConfigUsage() {
const isDev = process.env.NODE_ENV !== 'production'
const polyfill = createDevPolyfill()
if (isDev) {
// Development: use local config with verbose logging
polyfill.registerPlugin(configRuntimePlugin, {
implementation: 'runtime',
values: {
'log.level': 'debug',
'api.endpoint': 'http://localhost:3000',
'cache.enabled': 'false',
'mock.data': 'true',
},
})
} else {
// Production: use remote config with fallbacks
const layered = createLayeredConfig([
{
name: 'defaults',
values: {
'log.level': 'warn',
'cache.enabled': 'true',
},
},
{
name: 'remote',
source: createRemoteConfigSource({
url: process.env.CONFIG_URL || 'https://config.example.com/prod.json',
}),
},
])
polyfill.registerPlugin(configRuntimePlugin, {
implementation: 'layered',
config: layered,
})
}
const result = await polyfill.forInterfaces([
'wasi:config/runtime@0.2.0-draft',
])
console.log('Environment-specific config loaded')
polyfill.destroy()
}
// Run examples
export {
staticConfigUsage,
mutableConfigUsage,
remoteConfigUsage,
layeredConfigUsage,
simpleLayeredConfigUsage,
manifestConfigUsage,
envBridgeConfigUsage,
fixedConfigUsage,
configStoreUsage,
envSpecificConfigUsage,
}