@maroonedsoftware/appconfig 1.4.0 → 1.5.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/README.md
CHANGED
|
@@ -27,11 +27,12 @@ import { AppConfig } from '@maroonedsoftware/appconfig';
|
|
|
27
27
|
const config = new AppConfig({
|
|
28
28
|
database: { host: 'localhost', port: 5432 },
|
|
29
29
|
api: { timeout: 5000 },
|
|
30
|
+
port: '3000',
|
|
30
31
|
});
|
|
31
32
|
|
|
32
|
-
const
|
|
33
|
-
const port = config.getNumber('port');
|
|
34
|
-
const db = config.getAs<{ host: string }>('database');
|
|
33
|
+
const database = config.get('database'); // Type-safe access
|
|
34
|
+
const port = config.getNumber('port'); // Returns 3000 as number
|
|
35
|
+
const db = config.getAs<{ host: string }>('database'); // Cast to interface
|
|
35
36
|
```
|
|
36
37
|
|
|
37
38
|
### Using the Builder
|
|
@@ -309,10 +310,10 @@ const provider = new AppConfigProviderGcpSecrets('my-project-id');
|
|
|
309
310
|
const provider = new AppConfigProviderGcpSecrets('my-project-id', /\$\{secret:([^}]+)\}/g);
|
|
310
311
|
```
|
|
311
312
|
|
|
312
|
-
| Parameter | Type | Description
|
|
313
|
-
| ----------- | ------------------ |
|
|
314
|
-
| `projectId` | `string` | The GCP project ID where secrets are stored
|
|
315
|
-
| `prefix` | `string \| RegExp` | Optional
|
|
313
|
+
| Parameter | Type | Description |
|
|
314
|
+
| ----------- | ------------------ | -------------------------------------------------------------------------------------------- |
|
|
315
|
+
| `projectId` | `string` | The GCP project ID where secrets are stored |
|
|
316
|
+
| `prefix` | `string \| RegExp` | Optional pattern to match secret references. Default: `/\$\{gcp:(.+)\}/g` (matches `${gcp:NAME}`) |
|
|
316
317
|
|
|
317
318
|
The provider:
|
|
318
319
|
|
|
@@ -369,20 +370,22 @@ class MyCustomSource implements AppConfigSource {
|
|
|
369
370
|
### Creating a Custom Provider
|
|
370
371
|
|
|
371
372
|
```typescript
|
|
372
|
-
import { AppConfigProvider
|
|
373
|
+
import { AppConfigProvider } from '@maroonedsoftware/appconfig';
|
|
373
374
|
|
|
374
375
|
class MyCustomProvider implements AppConfigProvider {
|
|
375
376
|
canParse(value: string): boolean {
|
|
376
377
|
return value.startsWith('custom:');
|
|
377
378
|
}
|
|
378
379
|
|
|
379
|
-
async parse(value: string, meta
|
|
380
|
+
async parse(value: string, meta): Promise<void> {
|
|
380
381
|
const transformed = value.replace('custom:', '');
|
|
381
382
|
(meta.owner as Record<string, unknown>)[meta.propertyPath] = transformed;
|
|
382
383
|
}
|
|
383
384
|
}
|
|
384
385
|
```
|
|
385
386
|
|
|
387
|
+
The `meta` parameter is an `ObjectVisitorMeta` describing where the value lives in the configuration object (`owner`, `propertyPath`, `arrayIndex`, etc.). Mutate `meta.owner[meta.propertyPath]` (or `meta.owner[meta.arrayIndex]` for array entries) to write the transformed value back.
|
|
388
|
+
|
|
386
389
|
## Configuration Merging
|
|
387
390
|
|
|
388
391
|
When using multiple sources, configurations are deep-merged in the order they are added. Later sources override earlier ones:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.config.builder.d.ts","sourceRoot":"","sources":["../src/app.config.builder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAGzD;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAyB;IACjD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA2B;IAErD;;;;;;;;;;;;;;;OAeG;IACH,SAAS,CAAC,MAAM,EAAE,eAAe;IAKjC;;;;;;;;;;;;;OAaG;IACH,WAAW,CAAC,QAAQ,EAAE,iBAAiB;IAKvC;;;;;;;;;;;;;;;;;OAiBG;IACG,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"app.config.builder.d.ts","sourceRoot":"","sources":["../src/app.config.builder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAGzD;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAyB;IACjD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA2B;IAErD;;;;;;;;;;;;;;;OAeG;IACH,SAAS,CAAC,MAAM,EAAE,eAAe;IAKjC;;;;;;;;;;;;;OAaG;IACH,WAAW,CAAC,QAAQ,EAAE,iBAAiB;IAKvC;;;;;;;;;;;;;;;;;OAiBG;IACG,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;CAuBlE"}
|
package/dist/index.js
CHANGED
|
@@ -245,7 +245,7 @@ var AppConfigBuilder = class {
|
|
|
245
245
|
*/
|
|
246
246
|
async build() {
|
|
247
247
|
const sourceTasks = await Promise.all(this.sources.map((x) => x.load()));
|
|
248
|
-
const mergedConfig = deepmerge(...sourceTasks);
|
|
248
|
+
const mergedConfig = sourceTasks.length === 0 ? {} : deepmerge(...sourceTasks);
|
|
249
249
|
const tasks = [];
|
|
250
250
|
const parse = /* @__PURE__ */ __name((value, meta) => {
|
|
251
251
|
if (typeof value === "string") {
|
|
@@ -506,6 +506,7 @@ var AppConfigProviderDotenv = class {
|
|
|
506
506
|
// src/providers/app.config.provider.gcp.secrets.ts
|
|
507
507
|
import { Injectable } from "injectkit";
|
|
508
508
|
import { SecretManagerServiceClient } from "@google-cloud/secret-manager";
|
|
509
|
+
import { ServerkitError } from "@maroonedsoftware/errors";
|
|
509
510
|
function _ts_decorate(decorators, target, key, desc) {
|
|
510
511
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
511
512
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
@@ -553,14 +554,18 @@ var AppConfigProviderGcpSecrets = class {
|
|
|
553
554
|
* @returns `true` if the value matches the provider's regex pattern, `false` otherwise.
|
|
554
555
|
*/
|
|
555
556
|
canParse(value) {
|
|
557
|
+
this.prefix.lastIndex = 0;
|
|
556
558
|
return this.prefix.test(value);
|
|
557
559
|
}
|
|
558
560
|
/**
|
|
559
561
|
* Fetches a secret from GCP Secret Manager.
|
|
560
562
|
*
|
|
561
563
|
* @param secretId - The name of the secret to fetch.
|
|
562
|
-
* @returns A promise that resolves to the secret value
|
|
563
|
-
*
|
|
564
|
+
* @returns A promise that resolves to the secret value.
|
|
565
|
+
* @throws {ServerkitError} When Secret Manager rejects the access request (e.g. missing
|
|
566
|
+
* secret, IAM denial, network failure). The original error is attached via `withCause`
|
|
567
|
+
* and the failing `secretId` / `projectId` are recorded in `internalDetails`. Surfacing
|
|
568
|
+
* the failure prevents callers booting with an empty password / API key.
|
|
564
569
|
* @internal
|
|
565
570
|
*/
|
|
566
571
|
async getSecret(secretId) {
|
|
@@ -570,8 +575,10 @@ var AppConfigProviderGcpSecrets = class {
|
|
|
570
575
|
});
|
|
571
576
|
return secret.payload?.data?.toString() ?? "";
|
|
572
577
|
} catch (error) {
|
|
573
|
-
|
|
574
|
-
|
|
578
|
+
throw new ServerkitError(`AppConfigProviderGcpSecrets: failed to resolve secret "${secretId}" in project "${this.projectId}"`).withCause(error).withInternalDetails({
|
|
579
|
+
secretId,
|
|
580
|
+
projectId: this.projectId
|
|
581
|
+
});
|
|
575
582
|
}
|
|
576
583
|
}
|
|
577
584
|
/**
|
|
@@ -587,6 +594,8 @@ var AppConfigProviderGcpSecrets = class {
|
|
|
587
594
|
* @param meta - Metadata about the value's location in the configuration object.
|
|
588
595
|
* @returns A promise that resolves when all secrets have been fetched and the
|
|
589
596
|
* transformation is complete.
|
|
597
|
+
* @throws {ServerkitError} Propagated from {@link getSecret} when any referenced secret
|
|
598
|
+
* cannot be resolved. The build call site is expected to fail loud and stop boot.
|
|
590
599
|
*
|
|
591
600
|
* @example
|
|
592
601
|
* ```typescript
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/app.config.ts","../src/app.config.builder.ts","../src/object.visitor.ts","../src/helpers.ts","../src/sources/app.config.source.dotenv.ts","../src/sources/app.config.source.json.ts","../src/sources/app.config.source.yaml.ts","../src/providers/app.config.provider.dotenv.ts","../src/providers/app.config.provider.gcp.secrets.ts"],"sourcesContent":["/**\n * Configuration container that provides type-safe access to configuration values.\n *\n * @template T - The type of the configuration object. Defaults to `Record<string, unknown>`.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({\n * database: { host: 'localhost', port: 5432 },\n * api: { timeout: 5000 }\n * });\n *\n * const host = config.get('database').host; // Type-safe access\n * ```\n */\nexport class AppConfig<T = Record<string, unknown>> {\n /**\n * Creates a new AppConfig instance with the provided configuration.\n *\n * @param config - The configuration object to wrap.\n */\n constructor(private readonly config: T) {}\n\n /**\n * Retrieves a configuration value by key.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value for the given key.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ port: 3000, host: 'localhost' });\n * const port = config.get('port'); // Returns 3000, typed as number\n * ```\n */\n get(key: keyof T): T[keyof T] {\n return this.config[key];\n }\n\n /**\n * Retrieves a configuration value cast to a specific type.\n *\n * Unlike `get()`, which returns `T[keyof T]`, this method lets you cast the\n * value to an arbitrary type `U`. Use this when the TypeScript type of the\n * stored value differs from what you need at the call site — for example,\n * when reading a nested object as a typed interface.\n *\n * @template U - The type to cast the value to.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value cast to `U`.\n *\n * @example\n * ```typescript\n * interface DbConfig { host: string; port: number }\n *\n * const config = new AppConfig({ database: { host: 'localhost', port: 5432 } });\n * const db = config.getAs<DbConfig>('database');\n * console.log(db.host); // 'localhost'\n * ```\n */\n getAs<U>(key: keyof T): U {\n return this.config[key] as U;\n }\n\n /**\n * Retrieves a configuration value as a string.\n *\n * The value is converted to a string using `String()`. This is useful when\n * you need to ensure a value is a string regardless of its original type.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value converted to a string.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ port: 3000, enabled: true });\n * const portStr = config.getString('port'); // Returns \"3000\"\n * const enabledStr = config.getString('enabled'); // Returns \"true\"\n * ```\n */\n getString(key: keyof T): string {\n return String(this.get(key));\n }\n\n /**\n * Retrieves a configuration value as a number.\n *\n * The value is converted to a number using `Number()`. This is useful when\n * you need to ensure a value is a number regardless of its original type.\n * Note: Invalid conversions will result in `NaN`.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value converted to a number.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ port: '3000', timeout: '5000' });\n * const port = config.getNumber('port'); // Returns 3000\n * const timeout = config.getNumber('timeout'); // Returns 5000\n * ```\n */\n getNumber(key: keyof T): number {\n return Number(this.config[key]);\n }\n\n /**\n * Retrieves a configuration value as a boolean.\n *\n * The value is converted to a boolean using `Boolean()`. This is useful when\n * you need to ensure a value is a boolean regardless of its original type.\n * Note: Only falsy values (false, 0, '', null, undefined, NaN) become false.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value converted to a boolean.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ enabled: 'true', debug: 1 });\n * const enabled = config.getBoolean('enabled'); // Returns true\n * const debug = config.getBoolean('debug'); // Returns true\n * ```\n */\n getBoolean(key: keyof T): boolean {\n return Boolean(this.config[key]);\n }\n\n /**\n * Retrieves a configuration value as an object.\n *\n * The value is cast to an object type. This is useful when you know a value\n * is an object and want to access it with object methods.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value cast as an object.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({\n * database: { host: 'localhost', port: 5432 }\n * });\n * const db = config.getObject('database'); // Returns { host: 'localhost', port: 5432 }\n * ```\n */\n getObject(key: keyof T): object {\n return this.config[key] as object;\n }\n}\n","import { deepmerge } from 'deepmerge-ts';\nimport { AppConfig } from './app.config.js';\nimport { AppConfigProvider } from './app.config.provider.js';\nimport { AppConfigSource } from './app.config.source.js';\nimport { objectVisitor, ObjectVisitorMeta } from './object.visitor.js';\n\n/**\n * Builder for constructing AppConfig instances from multiple sources with value transformation.\n *\n * The builder allows you to:\n * - Load configuration from multiple sources (files, environment variables, etc.)\n * - Merge configurations with later sources overriding earlier ones\n * - Transform string values using providers (e.g., resolving environment variable references)\n *\n * @example\n * ```typescript\n * const config = await new AppConfigBuilder()\n * .addSource(new AppConfigSourceJson('./config.json'))\n * .addSource(new AppConfigSourceDotenv())\n * .addProvider(new AppConfigProviderDotenv())\n * .build();\n * ```\n */\nexport class AppConfigBuilder {\n private readonly sources: AppConfigSource[] = [];\n private readonly providers: AppConfigProvider[] = [];\n\n /**\n * Adds a configuration source to the builder.\n *\n * Sources are loaded in the order they are added, and later sources override earlier ones\n * when merging configurations.\n *\n * @param source - The configuration source to add.\n * @returns The builder instance for method chaining.\n *\n * @example\n * ```typescript\n * builder\n * .addSource(new AppConfigSourceJson('./default.json'))\n * .addSource(new AppConfigSourceJson('./local.json'));\n * ```\n */\n addSource(source: AppConfigSource) {\n this.sources.push(source);\n return this;\n }\n\n /**\n * Adds a provider to transform string values during configuration building.\n *\n * Providers are applied to all string values found in the merged configuration.\n * The first provider that can parse a value will be used to transform it.\n *\n * @param provider - The provider to add.\n * @returns The builder instance for method chaining.\n *\n * @example\n * ```typescript\n * builder.addProvider(new AppConfigProviderDotenv());\n * ```\n */\n addProvider(provider: AppConfigProvider) {\n this.providers.push(provider);\n return this;\n }\n\n /**\n * Builds the AppConfig instance by loading all sources, merging them, and applying providers.\n *\n * The build process:\n * 1. Loads all sources in parallel\n * 2. Merges configurations (later sources override earlier ones)\n * 3. Traverses the merged configuration and applies providers to string values\n * 4. Returns the final AppConfig instance\n *\n * @template T - The type of the configuration object. Defaults to `Record<string, unknown>`.\n * @returns A promise that resolves to the built AppConfig instance.\n *\n * @example\n * ```typescript\n * const config = await builder.build<MyConfigType>();\n * const value = config.get('someKey');\n * ```\n */\n async build<T = Record<string, unknown>>(): Promise<AppConfig<T>> {\n const sourceTasks = await Promise.all(this.sources.map(x => x.load()));\n const mergedConfig = deepmerge(...sourceTasks) as T;\n\n const tasks: Promise<void>[] = [];\n const parse = (value: unknown, meta: ObjectVisitorMeta) => {\n if (typeof value === 'string') {\n const provider = this.providers.find(x => x.canParse(value));\n if (provider) {\n tasks.push(provider.parse(value, meta));\n }\n }\n };\n\n objectVisitor(mergedConfig, parse);\n await Promise.all(tasks);\n\n return new AppConfig<T>(mergedConfig);\n }\n}\n","/**\n * Metadata about a value's location within an object structure.\n */\nexport type ObjectVisitorMeta = {\n /** The full path to the value (e.g., \"database.host\" or \"items[0]\"). */\n path: string;\n /** The object that owns this property. */\n owner: object;\n /** The property name or array index path (e.g., \"host\" or \"items[0]\"). */\n propertyPath: string;\n /** The type of the property value. */\n propertyType: 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function';\n /** The array index if the value is in an array, undefined otherwise. */\n arrayIndex?: number;\n};\n\n/**\n * Callback function invoked for each primitive value found during object traversal.\n *\n * @param value - The primitive value found.\n * @param meta - Metadata about the value's location in the object structure.\n */\nexport type ObjectVisitorCallback = (value: unknown, meta: ObjectVisitorMeta) => void;\n\n/**\n * Traverses an object structure and invokes a callback for each primitive value found.\n *\n * The visitor recursively traverses objects and arrays, calling the callback for each\n * primitive value (string, number, boolean, bigint) encountered. It skips functions,\n * symbols, null, and undefined values.\n *\n * @param obj - The object to traverse. Can be any value.\n * @param callback - The callback function to invoke for each primitive value.\n *\n * @example\n * ```typescript\n * const config = {\n * database: { host: 'localhost', port: 5432 },\n * items: ['a', 'b', 'c']\n * };\n *\n * objectVisitor(config, (value, meta) => {\n * console.log(`${meta.path} = ${value}`);\n * });\n * // Output:\n * // database.host = localhost\n * // database.port = 5432\n * // items[0] = a\n * // items[1] = b\n * // items[2] = c\n * ```\n */\nexport const objectVisitor = (obj: unknown, callback: ObjectVisitorCallback): void => {\n const visit = (\n obj: unknown,\n callback: ObjectVisitorCallback,\n path: string = '',\n owner: object = {},\n propertyPath: string = '',\n arrayIndex?: number,\n ): void => {\n if (!obj) {\n return;\n }\n\n switch (typeof obj) {\n case 'object':\n if (Array.isArray(obj)) {\n obj.forEach((item, index) => {\n visit(item, callback, path + `[${index}]`, obj, propertyPath + `[${index}]`, index);\n });\n } else {\n const entries = Object.entries(obj);\n for (const entry of entries) {\n visit(entry[1], callback, path + (path.length > 0 ? '.' : '') + entry[0], obj, entry[0]);\n }\n }\n break;\n case 'function':\n case 'symbol':\n case 'undefined':\n break;\n default:\n callback(obj, {\n owner,\n propertyPath,\n path,\n propertyType: typeof obj,\n arrayIndex,\n });\n break;\n }\n };\n\n visit(obj, callback);\n};\n","/**\n * Attempts to parse a string as JSON, returning the original string if parsing fails.\n *\n * @param text - The text to parse.\n * @returns The parsed JSON value, or the original text if parsing fails.\n */\nexport function tryParseJson(text: string): unknown {\n try {\n return JSON.parse(text, (_, value) => value);\n } catch {\n return text;\n }\n}\n\n/**\n * Transforms a flat key/value record into a nested object by splitting keys on a\n * separator string.\n *\n * Each key is split into path segments. Intermediate objects are created as needed.\n * If a path segment collides with an existing non-object value it is replaced by the\n * new object. Keys that do not contain the separator are passed through unchanged.\n *\n * Supports arbitrary nesting depth — a key with N separators produces N+1 levels.\n *\n * @param record - The flat key/value record to transform.\n * @param separator - The string used to delimit path segments (e.g. `'__'`).\n * @returns A new nested object.\n *\n * @example\n * ```typescript\n * nestKeys(\n * {\n * WEBHOOK__secret: 'abc',\n * WEBHOOK__header: 'X-Sig',\n * DATABASE_URL: 'postgres://localhost/db',\n * },\n * '__',\n * );\n * // → { WEBHOOK: { secret: 'abc', header: 'X-Sig' }, DATABASE_URL: 'postgres://localhost/db' }\n * ```\n */\nexport function nestKeys(record: Record<string, unknown>, separator: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(record)) {\n const parts = key.split(separator);\n\n if (parts.length === 1) {\n result[key] = value;\n } else {\n let current = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (typeof current[part] !== 'object' || current[part] === null) {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]!] = value;\n }\n }\n\n return result;\n}\n","import { AppConfigSource } from '../app.config.source.js';\nimport { nestKeys } from '../helpers.js';\nimport dotenv from 'dotenv';\n\n/**\n * Options for {@link AppConfigSourceDotenv}.\n */\nexport interface AppConfigSourceDotenvOptions {\n /**\n * When set, keys containing this separator are split into nested objects.\n *\n * For example, with `groupSeparator: '__'` the key `WEBHOOK__secret` becomes\n * `{ WEBHOOK: { secret: '...' } }`. Supports arbitrary nesting depth.\n *\n * @example\n * ```typescript\n * // .env\n * // WEBHOOK__secret=abc\n * // WEBHOOK__header=X-Sig\n * // DATABASE_URL=postgres://localhost/db\n *\n * const source = new AppConfigSourceDotenv('./.env', { groupSeparator: '__' });\n * await source.load();\n * // → { WEBHOOK: { secret: 'abc', header: 'X-Sig' }, DATABASE_URL: 'postgres://localhost/db' }\n * ```\n */\n groupSeparator?: string;\n}\n\n/**\n * Configuration source that loads environment variables from a `.env` file.\n *\n * This source uses the `dotenv` package to load environment variables from a `.env` file.\n * If no file path is provided, it will look for a `.env` file in the current working directory.\n * All values are strings as provided by the environment file.\n *\n * When the `groupSeparator` option is set, keys that contain the separator are automatically\n * collapsed into nested objects. This is useful for grouping related env vars under a shared\n * prefix (e.g. `WEBHOOK__secret` and `WEBHOOK__header` → `{ WEBHOOK: { secret, header } }`).\n *\n * @example\n * ```typescript\n * // Load from default .env file\n * const source1 = new AppConfigSourceDotenv();\n * const config1 = await source1.load();\n *\n * // Load from custom path\n * const source2 = new AppConfigSourceDotenv('./config/.env.local');\n * const config2 = await source2.load();\n *\n * // Group keys with __ separator into nested objects\n * const source3 = new AppConfigSourceDotenv('./.env', { groupSeparator: '__' });\n * const config3 = await source3.load();\n * ```\n */\nexport class AppConfigSourceDotenv implements AppConfigSource {\n /**\n * Creates a new AppConfigSourceDotenv instance.\n *\n * @param filePath - Optional path to the `.env` file. If not provided, `dotenv` will\n * look for a `.env` file in the current working directory.\n * @param options - Optional configuration options.\n */\n constructor(\n private readonly filePath?: string,\n private readonly options?: AppConfigSourceDotenvOptions,\n ) {}\n\n /**\n * Loads environment variables from the `.env` file.\n *\n * Uses `dotenv.config()` to parse the file and load variables into the returned object.\n * If `options.groupSeparator` is set the flat keys are transformed into a nested object\n * before being returned.\n *\n * @returns A promise that resolves to an object containing the parsed environment variables.\n * @throws {Error} If there's an error reading or parsing the `.env` file.\n */\n async load(): Promise<Record<string, unknown>> {\n const result = dotenv.config({ path: this.filePath, quiet: true });\n if (result.error) {\n throw result.error;\n }\n const parsed = result.parsed ?? {};\n\n if (this.options?.groupSeparator) {\n return nestKeys(parsed, this.options.groupSeparator);\n }\n\n return parsed;\n }\n}\n","import { existsSync } from 'node:fs';\nimport { AppConfigSource } from '../app.config.source.js';\nimport { readFile } from 'node:fs/promises';\nimport { AppConfigSourceFileOptions } from '../app.config.source.options.js';\n\n/**\n * Configuration source that loads configuration from a JSON file.\n *\n * This source reads a JSON file from the filesystem and parses it as a configuration object.\n * By default, it will return an empty object if the file doesn't exist instead of throwing an error.\n *\n * @example\n * ```typescript\n * // Load from JSON file, ignore if missing\n * const source1 = new AppConfigSourceJson('./config.json');\n *\n * // Load from JSON file, throw error if missing\n * const source2 = new AppConfigSourceJson('./config.json', {\n * ignoreMissingFile: false\n * });\n *\n * // Load with custom encoding\n * const source3 = new AppConfigSourceJson('./config.json', {\n * encoding: 'utf16le'\n * });\n * ```\n */\nexport class AppConfigSourceJson implements AppConfigSource {\n private readonly options: AppConfigSourceFileOptions;\n\n /**\n * Creates a new AppConfigSourceJson instance.\n *\n * @param filePath - The path to the JSON file to load.\n * @param options - Optional configuration for the source behavior.\n */\n constructor(\n private readonly filePath: string,\n options?: AppConfigSourceFileOptions,\n ) {\n this.options = {\n ignoreMissingFile: true,\n encoding: 'utf8',\n ...(options ?? {}),\n };\n }\n\n /**\n * Loads configuration from the JSON file.\n *\n * If the file doesn't exist and `ignoreMissingFile` is `true`, returns an empty object.\n * Otherwise, reads and parses the JSON file.\n *\n * @returns A promise that resolves to the parsed JSON configuration object.\n * @throws {Error} If the file doesn't exist and `ignoreMissingFile` is `false`,\n * or if the file contains invalid JSON.\n */\n async load(): Promise<Record<string, unknown>> {\n if (!existsSync(this.filePath) && this.options.ignoreMissingFile) {\n return {};\n }\n\n const file = await readFile(this.filePath, {\n encoding: this.options.encoding,\n });\n return JSON.parse(file.toString());\n }\n}\n","import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport YAML from 'yaml';\nimport { AppConfigSource } from '../app.config.source.js';\nimport { AppConfigSourceFileOptions } from '../app.config.source.options.js';\n\n/**\n * Configuration source that loads configuration from a YAML file.\n *\n * This source reads a YAML file from the filesystem and parses it as a configuration object.\n * By default, it will return an empty object if the file doesn't exist instead of throwing an error.\n * Supports both `.yaml` and `.yml` file extensions.\n *\n * @example\n * ```typescript\n * // Load from YAML file, ignore if missing\n * const source1 = new AppConfigSourceYaml('./config.yaml');\n *\n * // Load from YAML file, throw error if missing\n * const source2 = new AppConfigSourceYaml('./config.yaml', {\n * ignoreMissingFile: false\n * });\n *\n * // Load with custom encoding\n * const source3 = new AppConfigSourceYaml('./config.yaml', {\n * encoding: 'utf16le'\n * });\n * ```\n */\nexport class AppConfigSourceYaml implements AppConfigSource {\n private readonly options: AppConfigSourceFileOptions;\n\n /**\n * Creates a new AppConfigSourceYaml instance.\n *\n * @param filePath - The path to the YAML file to load.\n * @param options - Optional configuration for the source behavior.\n */\n constructor(\n private readonly filePath: string,\n options?: AppConfigSourceFileOptions,\n ) {\n this.options = {\n ignoreMissingFile: true,\n encoding: 'utf8',\n ...(options ?? {}),\n };\n }\n\n /**\n * Loads configuration from the YAML file.\n *\n * If the file doesn't exist and `ignoreMissingFile` is `true`, returns an empty object.\n * Otherwise, reads and parses the YAML file.\n *\n * @returns A promise that resolves to the parsed YAML configuration object.\n * @throws {Error} If the file doesn't exist and `ignoreMissingFile` is `false`,\n * or if the file contains invalid YAML.\n */\n async load(): Promise<Record<string, unknown>> {\n if (!existsSync(this.filePath) && this.options.ignoreMissingFile) {\n return {};\n }\n\n const file = await readFile(this.filePath, {\n encoding: this.options.encoding,\n });\n return YAML.parse(file.toString());\n }\n}\n","import { AppConfigProvider } from '../app.config.provider.js';\nimport { ObjectVisitorMeta } from '../object.visitor.js';\nimport { tryParseJson } from '../helpers.js';\n\n/**\n * Provider that resolves environment variable references in configuration values.\n *\n * This provider matches string values using a regex pattern and replaces them with\n * values from `process.env`. The default pattern matches `${env:KEY}` and extracts\n * the key part to look up in the environment.\n *\n * After replacement, the result is attempted to be parsed as JSON. If parsing succeeds,\n * the parsed value is used; otherwise, the string value is used.\n *\n * @example\n * ```typescript\n * // With default pattern /\\$\\{env:(.+)\\}/g\n * // Value: \"${env:DATABASE_URL}\"\n * // Looks up: process.env.DATABASE_URL\n *\n * // Custom pattern\n * const provider = new AppConfigProviderDotenv(/\\$\\{([^}]+)\\}/g);\n * // Value: \"${DATABASE_URL}\"\n * // Looks up: process.env.DATABASE_URL\n * ```\n */\nexport class AppConfigProviderDotenv implements AppConfigProvider {\n private readonly prefix: RegExp;\n\n /**\n * Creates a new AppConfigProviderDotenv instance.\n *\n * @param prefix - A regex pattern or string to match environment variable references.\n * If a string is provided, it will be converted to a RegExp. The regex must have\n * at least one capture group that extracts the environment variable key.\n * Defaults to `/\\$\\{env:(.+)\\}/g` which matches `${env:KEY}` patterns.\n *\n * @example\n * ```typescript\n * // Default pattern\n * const provider1 = new AppConfigProviderDotenv();\n *\n * // Custom regex pattern\n * const provider2 = new AppConfigProviderDotenv(/\\$\\{([^}]+)\\}/g);\n *\n * // String pattern (converted to RegExp)\n * const provider3 = new AppConfigProviderDotenv('env:');\n * ```\n */\n constructor(prefix: string | RegExp = /\\$\\{env:(.+)\\}/g) {\n this.prefix = typeof prefix === 'string' ? new RegExp(prefix) : prefix;\n }\n\n /**\n * Checks if this provider can parse the given value.\n *\n * @param value - The string value to check.\n * @returns `true` if the value matches the provider's regex pattern, `false` otherwise.\n */\n canParse(value: string): boolean {\n this.prefix.lastIndex = 0;\n return this.prefix.test(value);\n }\n\n /**\n * Parses the value by replacing environment variable references with actual values.\n *\n * The method:\n * 1. Finds all matches of the regex pattern in the value\n * 2. Replaces each match with the corresponding value from `process.env`\n * 3. Attempts to parse the result as JSON\n * 4. Updates the configuration object with the final value\n *\n * @param value - The string value containing environment variable references.\n * @param meta - Metadata about the value's location in the configuration object.\n * @returns A promise that resolves when the transformation is complete.\n *\n * @example\n * ```typescript\n * // If process.env.DATABASE_URL = \"postgres://localhost/db\"\n * // Value: \"${env:DATABASE_URL}\"\n * // Result: \"postgres://localhost/db\"\n *\n * // If process.env.PORT = \"3000\"\n * // Value: \"${env:PORT}\"\n * // Result: 3000 (parsed as JSON number)\n * ```\n */\n async parse(value: string, meta: ObjectVisitorMeta): Promise<void> {\n const matches = value.matchAll(this.prefix);\n\n let result = value;\n for (const [found, key] of matches) {\n result = result.replaceAll(found, process.env[key!] ?? '');\n }\n\n if (meta.arrayIndex !== undefined && Array.isArray(meta.owner)) {\n meta.owner[meta.arrayIndex] = tryParseJson(result ?? '');\n } else {\n (meta.owner as Record<string, unknown>)[meta.propertyPath] = tryParseJson(result ?? '');\n }\n }\n}\n","import { Injectable } from 'injectkit';\nimport { AppConfigProvider } from '../app.config.provider.js';\nimport { ObjectVisitorMeta } from '../object.visitor.js';\nimport { SecretManagerServiceClient } from '@google-cloud/secret-manager';\nimport { tryParseJson } from '../helpers.js';\n\n/**\n * Provider that resolves Google Cloud Platform Secret Manager references in configuration values.\n *\n * This provider matches string values using a regex pattern and replaces them with\n * secrets fetched from GCP Secret Manager. The default pattern matches `${gcp:SECRET_NAME}`\n * and extracts the secret name to look up in Secret Manager.\n *\n * After retrieval, the secret value is attempted to be parsed as JSON. If parsing succeeds,\n * the parsed value is used; otherwise, the string value is used.\n *\n * @remarks\n * This provider requires valid GCP credentials to be configured. It uses the\n * `@google-cloud/secret-manager` package and will use Application Default Credentials (ADC).\n *\n * @example\n * ```typescript\n * // With default pattern /\\$\\{gcp:(.+)\\}/g\n * // Value: \"${gcp:DATABASE_PASSWORD}\"\n * // Fetches: projects/{projectId}/secrets/DATABASE_PASSWORD/versions/latest\n *\n * const config = await new AppConfigBuilder()\n * .addSource(new AppConfigSourceJson('./config.json'))\n * .addProvider(new AppConfigProviderGcpSecrets('my-gcp-project'))\n * .build();\n * ```\n */\n@Injectable()\nexport class AppConfigProviderGcpSecrets implements AppConfigProvider {\n private readonly secretmanagerClient = new SecretManagerServiceClient();\n private readonly prefix: RegExp;\n\n /**\n * Creates a new AppConfigProviderGcpSecrets instance.\n *\n * @param projectId - The GCP project ID where secrets are stored.\n * @param prefix - A regex pattern or string to match secret references.\n * If a string is provided, it will be converted to a RegExp. The regex must have\n * at least one capture group that extracts the secret name.\n * Defaults to `/\\$\\{gcp:(.+)\\}/g` which matches `${gcp:SECRET_NAME}` patterns.\n *\n * @example\n * ```typescript\n * // Default pattern\n * const provider1 = new AppConfigProviderGcpSecrets('my-project');\n *\n * // Custom regex pattern\n * const provider2 = new AppConfigProviderGcpSecrets('my-project', /\\$\\{secret:([^}]+)\\}/g);\n * ```\n */\n constructor(\n private readonly projectId: string,\n prefix: string | RegExp = /\\$\\{gcp:(.+)\\}/g,\n ) {\n this.prefix = typeof prefix === 'string' ? new RegExp(prefix) : prefix;\n }\n\n /**\n * Checks if this provider can parse the given value.\n *\n * @param value - The string value to check.\n * @returns `true` if the value matches the provider's regex pattern, `false` otherwise.\n */\n canParse(value: string): boolean {\n return this.prefix.test(value);\n }\n\n /**\n * Fetches a secret from GCP Secret Manager.\n *\n * @param secretId - The name of the secret to fetch.\n * @returns A promise that resolves to the secret value, or an empty string if the secret\n * couldn't be fetched.\n * @internal\n */\n private async getSecret(secretId: string): Promise<string> {\n try {\n const [secret] = await this.secretmanagerClient.accessSecretVersion({\n name: `projects/${this.projectId}/secrets/${secretId}/versions/latest`,\n });\n return secret.payload?.data?.toString() ?? '';\n } catch (error) {\n console.error(error);\n return '';\n }\n }\n\n /**\n * Parses the value by replacing GCP secret references with actual secret values.\n *\n * The method:\n * 1. Finds all matches of the regex pattern in the value\n * 2. Fetches each secret from GCP Secret Manager in parallel\n * 3. Attempts to parse each result as JSON\n * 4. Updates the configuration object with the final value\n *\n * @param value - The string value containing GCP secret references.\n * @param meta - Metadata about the value's location in the configuration object.\n * @returns A promise that resolves when all secrets have been fetched and the\n * transformation is complete.\n *\n * @example\n * ```typescript\n * // If GCP secret \"API_KEY\" contains \"sk-abc123\"\n * // Value: \"${gcp:API_KEY}\"\n * // Result: \"sk-abc123\"\n *\n * // If GCP secret \"CONFIG\" contains '{\"retries\": 3}'\n * // Value: \"${gcp:CONFIG}\"\n * // Result: { retries: 3 } (parsed as JSON object)\n * ```\n */\n async parse(value: string, meta: ObjectVisitorMeta): Promise<void> {\n const tasks: Promise<void>[] = [];\n const matches = value.matchAll(this.prefix);\n\n for (const [, key] of matches) {\n const task = this.getSecret(key!).then(value => {\n if (meta.arrayIndex !== undefined && Array.isArray(meta.owner)) {\n meta.owner[meta.arrayIndex] = tryParseJson(value);\n } else {\n (meta.owner as Record<string, un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,OAAea,MAAwC;AACjE,UAAMC,QAAyB,CAAA;AAC/B,UAAMC,UAAUf,MAAMgB,SAAS,KAAKpB,MAAM;AAE1C,eAAW,CAAA,EAAGqB,GAAAA,KAAQF,SAAS;AAC7B,YAAMG,OAAO,KAAKhB,UAAUe,GAAAA,EAAME,KAAKnB,CAAAA,WAAAA;AACrC,YAAIa,KAAKO,eAAeC,UAAaC,MAAMC,QAAQV,KAAKW,KAAK,GAAG;AAC9DX,eAAKW,MAAMX,KAAKO,UAAU,IAAIK,aAAazB,MAAAA;QAC7C,OAAO;AACJa,eAAKW,MAAkCX,KAAKa,YAAY,IAAID,aAAazB,MAAAA;QAC5E;MACF,CAAA;AACAc,YAAMa,KAAKT,IAAAA;IACb;AAEA,UAAMU,QAAQC,IAAIf,KAAAA;EACpB;AACF;;;;;;;;;","names":["AppConfig","config","get","key","getAs","getString","String","getNumber","Number","getBoolean","Boolean","getObject","deepmerge","objectVisitor","obj","callback","visit","path","owner","propertyPath","arrayIndex","Array","isArray","forEach","item","index","entries","Object","entry","length","propertyType","AppConfigBuilder","sources","providers","addSource","source","push","addProvider","provider","build","sourceTasks","Promise","all","map","x","load","mergedConfig","deepmerge","tasks","parse","value","meta","find","canParse","objectVisitor","AppConfig","tryParseJson","text","JSON","parse","_","value","nestKeys","record","separator","result","key","Object","entries","parts","split","length","current","i","part","dotenv","AppConfigSourceDotenv","filePath","options","load","result","dotenv","config","path","quiet","error","parsed","groupSeparator","nestKeys","existsSync","readFile","AppConfigSourceJson","options","filePath","ignoreMissingFile","encoding","load","existsSync","file","readFile","JSON","parse","toString","existsSync","readFile","YAML","AppConfigSourceYaml","options","filePath","ignoreMissingFile","encoding","load","existsSync","file","readFile","YAML","parse","toString","AppConfigProviderDotenv","prefix","RegExp","canParse","value","lastIndex","test","parse","meta","matches","matchAll","result","found","key","replaceAll","process","env","arrayIndex","undefined","Array","isArray","owner","tryParseJson","propertyPath","Injectable","SecretManagerServiceClient","AppConfigProviderGcpSecrets","secretmanagerClient","SecretManagerServiceClient","prefix","projectId","RegExp","canParse","value","test","getSecret","secretId","secret","accessSecretVersion","name","payload","data","toString","error","console","parse","meta","tasks","matches","matchAll","key","task","then","arrayIndex","undefined","Array","isArray","owner","tryParseJson","propertyPath","push","Promise","all"]}
|
|
1
|
+
{"version":3,"sources":["../src/app.config.ts","../src/app.config.builder.ts","../src/object.visitor.ts","../src/helpers.ts","../src/sources/app.config.source.dotenv.ts","../src/sources/app.config.source.json.ts","../src/sources/app.config.source.yaml.ts","../src/providers/app.config.provider.dotenv.ts","../src/providers/app.config.provider.gcp.secrets.ts"],"sourcesContent":["/**\n * Configuration container that provides type-safe access to configuration values.\n *\n * @template T - The type of the configuration object. Defaults to `Record<string, unknown>`.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({\n * database: { host: 'localhost', port: 5432 },\n * api: { timeout: 5000 }\n * });\n *\n * const host = config.get('database').host; // Type-safe access\n * ```\n */\nexport class AppConfig<T = Record<string, unknown>> {\n /**\n * Creates a new AppConfig instance with the provided configuration.\n *\n * @param config - The configuration object to wrap.\n */\n constructor(private readonly config: T) {}\n\n /**\n * Retrieves a configuration value by key.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value for the given key.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ port: 3000, host: 'localhost' });\n * const port = config.get('port'); // Returns 3000, typed as number\n * ```\n */\n get(key: keyof T): T[keyof T] {\n return this.config[key];\n }\n\n /**\n * Retrieves a configuration value cast to a specific type.\n *\n * Unlike `get()`, which returns `T[keyof T]`, this method lets you cast the\n * value to an arbitrary type `U`. Use this when the TypeScript type of the\n * stored value differs from what you need at the call site — for example,\n * when reading a nested object as a typed interface.\n *\n * @template U - The type to cast the value to.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value cast to `U`.\n *\n * @example\n * ```typescript\n * interface DbConfig { host: string; port: number }\n *\n * const config = new AppConfig({ database: { host: 'localhost', port: 5432 } });\n * const db = config.getAs<DbConfig>('database');\n * console.log(db.host); // 'localhost'\n * ```\n */\n getAs<U>(key: keyof T): U {\n return this.config[key] as U;\n }\n\n /**\n * Retrieves a configuration value as a string.\n *\n * The value is converted to a string using `String()`. This is useful when\n * you need to ensure a value is a string regardless of its original type.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value converted to a string.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ port: 3000, enabled: true });\n * const portStr = config.getString('port'); // Returns \"3000\"\n * const enabledStr = config.getString('enabled'); // Returns \"true\"\n * ```\n */\n getString(key: keyof T): string {\n return String(this.get(key));\n }\n\n /**\n * Retrieves a configuration value as a number.\n *\n * The value is converted to a number using `Number()`. This is useful when\n * you need to ensure a value is a number regardless of its original type.\n * Note: Invalid conversions will result in `NaN`.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value converted to a number.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ port: '3000', timeout: '5000' });\n * const port = config.getNumber('port'); // Returns 3000\n * const timeout = config.getNumber('timeout'); // Returns 5000\n * ```\n */\n getNumber(key: keyof T): number {\n return Number(this.config[key]);\n }\n\n /**\n * Retrieves a configuration value as a boolean.\n *\n * The value is converted to a boolean using `Boolean()`. This is useful when\n * you need to ensure a value is a boolean regardless of its original type.\n * Note: Only falsy values (false, 0, '', null, undefined, NaN) become false.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value converted to a boolean.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({ enabled: 'true', debug: 1 });\n * const enabled = config.getBoolean('enabled'); // Returns true\n * const debug = config.getBoolean('debug'); // Returns true\n * ```\n */\n getBoolean(key: keyof T): boolean {\n return Boolean(this.config[key]);\n }\n\n /**\n * Retrieves a configuration value as an object.\n *\n * The value is cast to an object type. This is useful when you know a value\n * is an object and want to access it with object methods.\n *\n * @template K - The key type, must be a key of T.\n * @param key - The configuration key to retrieve.\n * @returns The configuration value cast as an object.\n *\n * @example\n * ```typescript\n * const config = new AppConfig({\n * database: { host: 'localhost', port: 5432 }\n * });\n * const db = config.getObject('database'); // Returns { host: 'localhost', port: 5432 }\n * ```\n */\n getObject(key: keyof T): object {\n return this.config[key] as object;\n }\n}\n","import { deepmerge } from 'deepmerge-ts';\nimport { AppConfig } from './app.config.js';\nimport { AppConfigProvider } from './app.config.provider.js';\nimport { AppConfigSource } from './app.config.source.js';\nimport { objectVisitor, ObjectVisitorMeta } from './object.visitor.js';\n\n/**\n * Builder for constructing AppConfig instances from multiple sources with value transformation.\n *\n * The builder allows you to:\n * - Load configuration from multiple sources (files, environment variables, etc.)\n * - Merge configurations with later sources overriding earlier ones\n * - Transform string values using providers (e.g., resolving environment variable references)\n *\n * @example\n * ```typescript\n * const config = await new AppConfigBuilder()\n * .addSource(new AppConfigSourceJson('./config.json'))\n * .addSource(new AppConfigSourceDotenv())\n * .addProvider(new AppConfigProviderDotenv())\n * .build();\n * ```\n */\nexport class AppConfigBuilder {\n private readonly sources: AppConfigSource[] = [];\n private readonly providers: AppConfigProvider[] = [];\n\n /**\n * Adds a configuration source to the builder.\n *\n * Sources are loaded in the order they are added, and later sources override earlier ones\n * when merging configurations.\n *\n * @param source - The configuration source to add.\n * @returns The builder instance for method chaining.\n *\n * @example\n * ```typescript\n * builder\n * .addSource(new AppConfigSourceJson('./default.json'))\n * .addSource(new AppConfigSourceJson('./local.json'));\n * ```\n */\n addSource(source: AppConfigSource) {\n this.sources.push(source);\n return this;\n }\n\n /**\n * Adds a provider to transform string values during configuration building.\n *\n * Providers are applied to all string values found in the merged configuration.\n * The first provider that can parse a value will be used to transform it.\n *\n * @param provider - The provider to add.\n * @returns The builder instance for method chaining.\n *\n * @example\n * ```typescript\n * builder.addProvider(new AppConfigProviderDotenv());\n * ```\n */\n addProvider(provider: AppConfigProvider) {\n this.providers.push(provider);\n return this;\n }\n\n /**\n * Builds the AppConfig instance by loading all sources, merging them, and applying providers.\n *\n * The build process:\n * 1. Loads all sources in parallel\n * 2. Merges configurations (later sources override earlier ones)\n * 3. Traverses the merged configuration and applies providers to string values\n * 4. Returns the final AppConfig instance\n *\n * @template T - The type of the configuration object. Defaults to `Record<string, unknown>`.\n * @returns A promise that resolves to the built AppConfig instance.\n *\n * @example\n * ```typescript\n * const config = await builder.build<MyConfigType>();\n * const value = config.get('someKey');\n * ```\n */\n async build<T = Record<string, unknown>>(): Promise<AppConfig<T>> {\n const sourceTasks = await Promise.all(this.sources.map(x => x.load()));\n // `deepmerge` with zero arguments returns `undefined`, which would crash\n // every downstream consumer with an opaque \"cannot read property of\n // undefined\". A misconfigured builder should still yield a usable empty\n // config object so the error surfaces at the missing-key call site.\n const mergedConfig = (sourceTasks.length === 0 ? {} : deepmerge(...sourceTasks)) as T;\n\n const tasks: Promise<void>[] = [];\n const parse = (value: unknown, meta: ObjectVisitorMeta) => {\n if (typeof value === 'string') {\n const provider = this.providers.find(x => x.canParse(value));\n if (provider) {\n tasks.push(provider.parse(value, meta));\n }\n }\n };\n\n objectVisitor(mergedConfig, parse);\n await Promise.all(tasks);\n\n return new AppConfig<T>(mergedConfig);\n }\n}\n","/**\n * Metadata about a value's location within an object structure.\n */\nexport type ObjectVisitorMeta = {\n /** The full path to the value (e.g., \"database.host\" or \"items[0]\"). */\n path: string;\n /** The object that owns this property. */\n owner: object;\n /** The property name or array index path (e.g., \"host\" or \"items[0]\"). */\n propertyPath: string;\n /** The type of the property value. */\n propertyType: 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function';\n /** The array index if the value is in an array, undefined otherwise. */\n arrayIndex?: number;\n};\n\n/**\n * Callback function invoked for each primitive value found during object traversal.\n *\n * @param value - The primitive value found.\n * @param meta - Metadata about the value's location in the object structure.\n */\nexport type ObjectVisitorCallback = (value: unknown, meta: ObjectVisitorMeta) => void;\n\n/**\n * Traverses an object structure and invokes a callback for each primitive value found.\n *\n * The visitor recursively traverses objects and arrays, calling the callback for each\n * primitive value (string, number, boolean, bigint) encountered. It skips functions,\n * symbols, null, and undefined values.\n *\n * @param obj - The object to traverse. Can be any value.\n * @param callback - The callback function to invoke for each primitive value.\n *\n * @example\n * ```typescript\n * const config = {\n * database: { host: 'localhost', port: 5432 },\n * items: ['a', 'b', 'c']\n * };\n *\n * objectVisitor(config, (value, meta) => {\n * console.log(`${meta.path} = ${value}`);\n * });\n * // Output:\n * // database.host = localhost\n * // database.port = 5432\n * // items[0] = a\n * // items[1] = b\n * // items[2] = c\n * ```\n */\nexport const objectVisitor = (obj: unknown, callback: ObjectVisitorCallback): void => {\n const visit = (\n obj: unknown,\n callback: ObjectVisitorCallback,\n path: string = '',\n owner: object = {},\n propertyPath: string = '',\n arrayIndex?: number,\n ): void => {\n if (!obj) {\n return;\n }\n\n switch (typeof obj) {\n case 'object':\n if (Array.isArray(obj)) {\n obj.forEach((item, index) => {\n visit(item, callback, path + `[${index}]`, obj, propertyPath + `[${index}]`, index);\n });\n } else {\n const entries = Object.entries(obj);\n for (const entry of entries) {\n visit(entry[1], callback, path + (path.length > 0 ? '.' : '') + entry[0], obj, entry[0]);\n }\n }\n break;\n case 'function':\n case 'symbol':\n case 'undefined':\n break;\n default:\n callback(obj, {\n owner,\n propertyPath,\n path,\n propertyType: typeof obj,\n arrayIndex,\n });\n break;\n }\n };\n\n visit(obj, callback);\n};\n","/**\n * Attempts to parse a string as JSON, returning the original string if parsing fails.\n *\n * @param text - The text to parse.\n * @returns The parsed JSON value, or the original text if parsing fails.\n */\nexport function tryParseJson(text: string): unknown {\n try {\n return JSON.parse(text, (_, value) => value);\n } catch {\n return text;\n }\n}\n\n/**\n * Transforms a flat key/value record into a nested object by splitting keys on a\n * separator string.\n *\n * Each key is split into path segments. Intermediate objects are created as needed.\n * If a path segment collides with an existing non-object value it is replaced by the\n * new object. Keys that do not contain the separator are passed through unchanged.\n *\n * Supports arbitrary nesting depth — a key with N separators produces N+1 levels.\n *\n * @param record - The flat key/value record to transform.\n * @param separator - The string used to delimit path segments (e.g. `'__'`).\n * @returns A new nested object.\n *\n * @example\n * ```typescript\n * nestKeys(\n * {\n * WEBHOOK__secret: 'abc',\n * WEBHOOK__header: 'X-Sig',\n * DATABASE_URL: 'postgres://localhost/db',\n * },\n * '__',\n * );\n * // → { WEBHOOK: { secret: 'abc', header: 'X-Sig' }, DATABASE_URL: 'postgres://localhost/db' }\n * ```\n */\nexport function nestKeys(record: Record<string, unknown>, separator: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(record)) {\n const parts = key.split(separator);\n\n if (parts.length === 1) {\n result[key] = value;\n } else {\n let current = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i]!;\n if (typeof current[part] !== 'object' || current[part] === null) {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]!] = value;\n }\n }\n\n return result;\n}\n","import { AppConfigSource } from '../app.config.source.js';\nimport { nestKeys } from '../helpers.js';\nimport dotenv from 'dotenv';\n\n/**\n * Options for {@link AppConfigSourceDotenv}.\n */\nexport interface AppConfigSourceDotenvOptions {\n /**\n * When set, keys containing this separator are split into nested objects.\n *\n * For example, with `groupSeparator: '__'` the key `WEBHOOK__secret` becomes\n * `{ WEBHOOK: { secret: '...' } }`. Supports arbitrary nesting depth.\n *\n * @example\n * ```typescript\n * // .env\n * // WEBHOOK__secret=abc\n * // WEBHOOK__header=X-Sig\n * // DATABASE_URL=postgres://localhost/db\n *\n * const source = new AppConfigSourceDotenv('./.env', { groupSeparator: '__' });\n * await source.load();\n * // → { WEBHOOK: { secret: 'abc', header: 'X-Sig' }, DATABASE_URL: 'postgres://localhost/db' }\n * ```\n */\n groupSeparator?: string;\n}\n\n/**\n * Configuration source that loads environment variables from a `.env` file.\n *\n * This source uses the `dotenv` package to load environment variables from a `.env` file.\n * If no file path is provided, it will look for a `.env` file in the current working directory.\n * All values are strings as provided by the environment file.\n *\n * When the `groupSeparator` option is set, keys that contain the separator are automatically\n * collapsed into nested objects. This is useful for grouping related env vars under a shared\n * prefix (e.g. `WEBHOOK__secret` and `WEBHOOK__header` → `{ WEBHOOK: { secret, header } }`).\n *\n * @example\n * ```typescript\n * // Load from default .env file\n * const source1 = new AppConfigSourceDotenv();\n * const config1 = await source1.load();\n *\n * // Load from custom path\n * const source2 = new AppConfigSourceDotenv('./config/.env.local');\n * const config2 = await source2.load();\n *\n * // Group keys with __ separator into nested objects\n * const source3 = new AppConfigSourceDotenv('./.env', { groupSeparator: '__' });\n * const config3 = await source3.load();\n * ```\n */\nexport class AppConfigSourceDotenv implements AppConfigSource {\n /**\n * Creates a new AppConfigSourceDotenv instance.\n *\n * @param filePath - Optional path to the `.env` file. If not provided, `dotenv` will\n * look for a `.env` file in the current working directory.\n * @param options - Optional configuration options.\n */\n constructor(\n private readonly filePath?: string,\n private readonly options?: AppConfigSourceDotenvOptions,\n ) {}\n\n /**\n * Loads environment variables from the `.env` file.\n *\n * Uses `dotenv.config()` to parse the file and load variables into the returned object.\n * If `options.groupSeparator` is set the flat keys are transformed into a nested object\n * before being returned.\n *\n * @returns A promise that resolves to an object containing the parsed environment variables.\n * @throws {Error} If there's an error reading or parsing the `.env` file.\n */\n async load(): Promise<Record<string, unknown>> {\n const result = dotenv.config({ path: this.filePath, quiet: true });\n if (result.error) {\n throw result.error;\n }\n const parsed = result.parsed ?? {};\n\n if (this.options?.groupSeparator) {\n return nestKeys(parsed, this.options.groupSeparator);\n }\n\n return parsed;\n }\n}\n","import { existsSync } from 'node:fs';\nimport { AppConfigSource } from '../app.config.source.js';\nimport { readFile } from 'node:fs/promises';\nimport { AppConfigSourceFileOptions } from '../app.config.source.options.js';\n\n/**\n * Configuration source that loads configuration from a JSON file.\n *\n * This source reads a JSON file from the filesystem and parses it as a configuration object.\n * By default, it will return an empty object if the file doesn't exist instead of throwing an error.\n *\n * @example\n * ```typescript\n * // Load from JSON file, ignore if missing\n * const source1 = new AppConfigSourceJson('./config.json');\n *\n * // Load from JSON file, throw error if missing\n * const source2 = new AppConfigSourceJson('./config.json', {\n * ignoreMissingFile: false\n * });\n *\n * // Load with custom encoding\n * const source3 = new AppConfigSourceJson('./config.json', {\n * encoding: 'utf16le'\n * });\n * ```\n */\nexport class AppConfigSourceJson implements AppConfigSource {\n private readonly options: AppConfigSourceFileOptions;\n\n /**\n * Creates a new AppConfigSourceJson instance.\n *\n * @param filePath - The path to the JSON file to load.\n * @param options - Optional configuration for the source behavior.\n */\n constructor(\n private readonly filePath: string,\n options?: AppConfigSourceFileOptions,\n ) {\n this.options = {\n ignoreMissingFile: true,\n encoding: 'utf8',\n ...(options ?? {}),\n };\n }\n\n /**\n * Loads configuration from the JSON file.\n *\n * If the file doesn't exist and `ignoreMissingFile` is `true`, returns an empty object.\n * Otherwise, reads and parses the JSON file.\n *\n * @returns A promise that resolves to the parsed JSON configuration object.\n * @throws {Error} If the file doesn't exist and `ignoreMissingFile` is `false`,\n * or if the file contains invalid JSON.\n */\n async load(): Promise<Record<string, unknown>> {\n if (!existsSync(this.filePath) && this.options.ignoreMissingFile) {\n return {};\n }\n\n const file = await readFile(this.filePath, {\n encoding: this.options.encoding,\n });\n return JSON.parse(file.toString());\n }\n}\n","import { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport YAML from 'yaml';\nimport { AppConfigSource } from '../app.config.source.js';\nimport { AppConfigSourceFileOptions } from '../app.config.source.options.js';\n\n/**\n * Configuration source that loads configuration from a YAML file.\n *\n * This source reads a YAML file from the filesystem and parses it as a configuration object.\n * By default, it will return an empty object if the file doesn't exist instead of throwing an error.\n * Supports both `.yaml` and `.yml` file extensions.\n *\n * @example\n * ```typescript\n * // Load from YAML file, ignore if missing\n * const source1 = new AppConfigSourceYaml('./config.yaml');\n *\n * // Load from YAML file, throw error if missing\n * const source2 = new AppConfigSourceYaml('./config.yaml', {\n * ignoreMissingFile: false\n * });\n *\n * // Load with custom encoding\n * const source3 = new AppConfigSourceYaml('./config.yaml', {\n * encoding: 'utf16le'\n * });\n * ```\n */\nexport class AppConfigSourceYaml implements AppConfigSource {\n private readonly options: AppConfigSourceFileOptions;\n\n /**\n * Creates a new AppConfigSourceYaml instance.\n *\n * @param filePath - The path to the YAML file to load.\n * @param options - Optional configuration for the source behavior.\n */\n constructor(\n private readonly filePath: string,\n options?: AppConfigSourceFileOptions,\n ) {\n this.options = {\n ignoreMissingFile: true,\n encoding: 'utf8',\n ...(options ?? {}),\n };\n }\n\n /**\n * Loads configuration from the YAML file.\n *\n * If the file doesn't exist and `ignoreMissingFile` is `true`, returns an empty object.\n * Otherwise, reads and parses the YAML file.\n *\n * @returns A promise that resolves to the parsed YAML configuration object.\n * @throws {Error} If the file doesn't exist and `ignoreMissingFile` is `false`,\n * or if the file contains invalid YAML.\n */\n async load(): Promise<Record<string, unknown>> {\n if (!existsSync(this.filePath) && this.options.ignoreMissingFile) {\n return {};\n }\n\n const file = await readFile(this.filePath, {\n encoding: this.options.encoding,\n });\n return YAML.parse(file.toString());\n }\n}\n","import { AppConfigProvider } from '../app.config.provider.js';\nimport { ObjectVisitorMeta } from '../object.visitor.js';\nimport { tryParseJson } from '../helpers.js';\n\n/**\n * Provider that resolves environment variable references in configuration values.\n *\n * This provider matches string values using a regex pattern and replaces them with\n * values from `process.env`. The default pattern matches `${env:KEY}` and extracts\n * the key part to look up in the environment.\n *\n * After replacement, the result is attempted to be parsed as JSON. If parsing succeeds,\n * the parsed value is used; otherwise, the string value is used.\n *\n * @example\n * ```typescript\n * // With default pattern /\\$\\{env:(.+)\\}/g\n * // Value: \"${env:DATABASE_URL}\"\n * // Looks up: process.env.DATABASE_URL\n *\n * // Custom pattern\n * const provider = new AppConfigProviderDotenv(/\\$\\{([^}]+)\\}/g);\n * // Value: \"${DATABASE_URL}\"\n * // Looks up: process.env.DATABASE_URL\n * ```\n */\nexport class AppConfigProviderDotenv implements AppConfigProvider {\n private readonly prefix: RegExp;\n\n /**\n * Creates a new AppConfigProviderDotenv instance.\n *\n * @param prefix - A regex pattern or string to match environment variable references.\n * If a string is provided, it will be converted to a RegExp. The regex must have\n * at least one capture group that extracts the environment variable key.\n * Defaults to `/\\$\\{env:(.+)\\}/g` which matches `${env:KEY}` patterns.\n *\n * @example\n * ```typescript\n * // Default pattern\n * const provider1 = new AppConfigProviderDotenv();\n *\n * // Custom regex pattern\n * const provider2 = new AppConfigProviderDotenv(/\\$\\{([^}]+)\\}/g);\n *\n * // String pattern (converted to RegExp)\n * const provider3 = new AppConfigProviderDotenv('env:');\n * ```\n */\n constructor(prefix: string | RegExp = /\\$\\{env:(.+)\\}/g) {\n this.prefix = typeof prefix === 'string' ? new RegExp(prefix) : prefix;\n }\n\n /**\n * Checks if this provider can parse the given value.\n *\n * @param value - The string value to check.\n * @returns `true` if the value matches the provider's regex pattern, `false` otherwise.\n */\n canParse(value: string): boolean {\n this.prefix.lastIndex = 0;\n return this.prefix.test(value);\n }\n\n /**\n * Parses the value by replacing environment variable references with actual values.\n *\n * The method:\n * 1. Finds all matches of the regex pattern in the value\n * 2. Replaces each match with the corresponding value from `process.env`\n * 3. Attempts to parse the result as JSON\n * 4. Updates the configuration object with the final value\n *\n * @param value - The string value containing environment variable references.\n * @param meta - Metadata about the value's location in the configuration object.\n * @returns A promise that resolves when the transformation is complete.\n *\n * @example\n * ```typescript\n * // If process.env.DATABASE_URL = \"postgres://localhost/db\"\n * // Value: \"${env:DATABASE_URL}\"\n * // Result: \"postgres://localhost/db\"\n *\n * // If process.env.PORT = \"3000\"\n * // Value: \"${env:PORT}\"\n * // Result: 3000 (parsed as JSON number)\n * ```\n */\n async parse(value: string, meta: ObjectVisitorMeta): Promise<void> {\n const matches = value.matchAll(this.prefix);\n\n let result = value;\n for (const [found, key] of matches) {\n result = result.replaceAll(found, process.env[key!] ?? '');\n }\n\n if (meta.arrayIndex !== undefined && Array.isArray(meta.owner)) {\n meta.owner[meta.arrayIndex] = tryParseJson(result ?? '');\n } else {\n (meta.owner as Record<string, unknown>)[meta.propertyPath] = tryParseJson(result ?? '');\n }\n }\n}\n","import { Injectable } from 'injectkit';\nimport { AppConfigProvider } from '../app.config.provider.js';\nimport { ObjectVisitorMeta } from '../object.visitor.js';\nimport { SecretManagerServiceClient } from '@google-cloud/secret-manager';\nimport { ServerkitError } from '@maroonedsoftware/errors';\nimport { tryParseJson } from '../helpers.js';\n\n/**\n * Provider that resolves Google Cloud Platform Secret Manager references in configuration values.\n *\n * This provider matches string values using a regex pattern and replaces them with\n * secrets fetched from GCP Secret Manager. The default pattern matches `${gcp:SECRET_NAME}`\n * and extracts the secret name to look up in Secret Manager.\n *\n * After retrieval, the secret value is attempted to be parsed as JSON. If parsing succeeds,\n * the parsed value is used; otherwise, the string value is used.\n *\n * @remarks\n * This provider requires valid GCP credentials to be configured. It uses the\n * `@google-cloud/secret-manager` package and will use Application Default Credentials (ADC).\n *\n * @example\n * ```typescript\n * // With default pattern /\\$\\{gcp:(.+)\\}/g\n * // Value: \"${gcp:DATABASE_PASSWORD}\"\n * // Fetches: projects/{projectId}/secrets/DATABASE_PASSWORD/versions/latest\n *\n * const config = await new AppConfigBuilder()\n * .addSource(new AppConfigSourceJson('./config.json'))\n * .addProvider(new AppConfigProviderGcpSecrets('my-gcp-project'))\n * .build();\n * ```\n */\n@Injectable()\nexport class AppConfigProviderGcpSecrets implements AppConfigProvider {\n private readonly secretmanagerClient = new SecretManagerServiceClient();\n private readonly prefix: RegExp;\n\n /**\n * Creates a new AppConfigProviderGcpSecrets instance.\n *\n * @param projectId - The GCP project ID where secrets are stored.\n * @param prefix - A regex pattern or string to match secret references.\n * If a string is provided, it will be converted to a RegExp. The regex must have\n * at least one capture group that extracts the secret name.\n * Defaults to `/\\$\\{gcp:(.+)\\}/g` which matches `${gcp:SECRET_NAME}` patterns.\n *\n * @example\n * ```typescript\n * // Default pattern\n * const provider1 = new AppConfigProviderGcpSecrets('my-project');\n *\n * // Custom regex pattern\n * const provider2 = new AppConfigProviderGcpSecrets('my-project', /\\$\\{secret:([^}]+)\\}/g);\n * ```\n */\n constructor(\n private readonly projectId: string,\n prefix: string | RegExp = /\\$\\{gcp:(.+)\\}/g,\n ) {\n this.prefix = typeof prefix === 'string' ? new RegExp(prefix) : prefix;\n }\n\n /**\n * Checks if this provider can parse the given value.\n *\n * @param value - The string value to check.\n * @returns `true` if the value matches the provider's regex pattern, `false` otherwise.\n */\n canParse(value: string): boolean {\n // `.test()` with a `/g`-flagged regex advances `lastIndex`, which can cause a\n // false negative on a subsequent call against the same string. Reset before\n // testing so behavior is independent of call order.\n this.prefix.lastIndex = 0;\n return this.prefix.test(value);\n }\n\n /**\n * Fetches a secret from GCP Secret Manager.\n *\n * @param secretId - The name of the secret to fetch.\n * @returns A promise that resolves to the secret value.\n * @throws {ServerkitError} When Secret Manager rejects the access request (e.g. missing\n * secret, IAM denial, network failure). The original error is attached via `withCause`\n * and the failing `secretId` / `projectId` are recorded in `internalDetails`. Surfacing\n * the failure prevents callers booting with an empty password / API key.\n * @internal\n */\n private async getSecret(secretId: string): Promise<string> {\n try {\n const [secret] = await this.secretmanagerClient.accessSecretVersion({\n name: `projects/${this.projectId}/secrets/${secretId}/versions/latest`,\n });\n return secret.payload?.data?.toString() ?? '';\n } catch (error) {\n // Surface failures loudly: silently returning `''` lets services boot with\n // an empty password / API key, which is far worse than a hard failure here.\n throw new ServerkitError(`AppConfigProviderGcpSecrets: failed to resolve secret \"${secretId}\" in project \"${this.projectId}\"`)\n .withCause(error as Error)\n .withInternalDetails({ secretId, projectId: this.projectId });\n }\n }\n\n /**\n * Parses the value by replacing GCP secret references with actual secret values.\n *\n * The method:\n * 1. Finds all matches of the regex pattern in the value\n * 2. Fetches each secret from GCP Secret Manager in parallel\n * 3. Attempts to parse each result as JSON\n * 4. Updates the configuration object with the final value\n *\n * @param value - The string value containing GCP secret references.\n * @param meta - Metadata about the value's location in the configuration object.\n * @returns A promise that resolves when all secrets have been fetched and the\n * transformation is complete.\n * @throws {ServerkitError} Propagated from {@link getSecret} when any referenced secret\n * cannot be resolved. The build call site is expected to fail loud and stop boot.\n *\n * @example\n * ```typescript\n * // If GCP secret \"API_KEY\" contains \"sk-abc123\"\n * // Value: \"${gcp:API_KEY}\"\n * // Result: \"sk-abc123\"\n *\n * // If GCP secret \"CONFIG\" contains '{\"retries\": 3}'\n * // Value: \"${gcp:CONFIG}\"\n * // Result: { retries: 3 } (parsed as JSON object)\n * ```\n */\n async parse(value: string, meta: ObjectVisitorMeta): Promise<void> {\n const tasks: Promise<void>[] = [];\n const matches = value.matchAll(this.prefix);\n\n for (const [, key] of matches) {\n const task = this.getSecret(key!).then(value => {\n if (meta.arrayIndex !== undefined && Array.isArray(meta.owner)) {\n meta.owner[meta.arrayIndex] = tryParseJson(value);\n } else {\n (meta.owner as Record<string, unknown>)[meta.propertyPath] = tryParseJson(value);\n }\n });\n tasks.push(task);\n }\n\n await Promise.all(tasks);\n }\n}\n"],"mappings":";;;;AAeO,IAAMA,YAAN,MAAMA;EAfb,OAeaA;;;;;;;;;EAMX,YAA6BC,QAAW;SAAXA,SAAAA;EAAY;;;;;;;;;;;;;;EAezCC,IAAIC,KAA0B;AAC5B,WAAO,KAAKF,OAAOE,GAAAA;EACrB;;;;;;;;;;;;;;;;;;;;;;EAuBAC,MAASD,KAAiB;AACxB,WAAO,KAAKF,OAAOE,GAAAA;EACrB;;;;;;;;;;;;;;;;;;EAmBAE,UAAUF,KAAsB;AAC9B,WAAOG,OAAO,KAAKJ,IAAIC,GAAAA,CAAAA;EACzB;;;;;;;;;;;;;;;;;;;EAoBAI,UAAUJ,KAAsB;AAC9B,WAAOK,OAAO,KAAKP,OAAOE,GAAAA,CAAI;EAChC;;;;;;;;;;;;;;;;;;;EAoBAM,WAAWN,KAAuB;AAChC,WAAOO,QAAQ,KAAKT,OAAOE,GAAAA,CAAI;EACjC;;;;;;;;;;;;;;;;;;;EAoBAQ,UAAUR,KAAsB;AAC9B,WAAO,KAAKF,OAAOE,GAAAA;EACrB;AACF;;;ACvJA,SAASS,iBAAiB;;;ACoDnB,IAAMC,gBAAgB,wBAACC,K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AA;AAGjB,SAAKD,SAAS,OAAOA,WAAW,WAAW,IAAIE,OAAOF,MAAAA,IAAUA;EAClE;;;;;;;EAQAG,SAASC,OAAwB;AAI/B,SAAKJ,OAAOK,YAAY;AACxB,WAAO,KAAKL,OAAOM,KAAKF,KAAAA;EAC1B;;;;;;;;;;;;EAaA,MAAcG,UAAUC,UAAmC;AACzD,QAAI;AACF,YAAM,CAACC,MAAAA,IAAU,MAAM,KAAKX,oBAAoBY,oBAAoB;QAClEC,MAAM,YAAY,KAAKV,SAAS,YAAYO,QAAAA;MAC9C,CAAA;AACA,aAAOC,OAAOG,SAASC,MAAMC,SAAAA,KAAc;IAC7C,SAASC,OAAO;AAGd,YAAM,IAAIC,eAAe,0DAA0DR,QAAAA,iBAAyB,KAAKP,SAAS,GAAG,EAC1HgB,UAAUF,KAAAA,EACVG,oBAAoB;QAAEV;QAAUP,WAAW,KAAKA;MAAU,CAAA;IAC/D;EACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6BA,MAAMkB,MAAMf,OAAegB,MAAwC;AACjE,UAAMC,QAAyB,CAAA;AAC/B,UAAMC,UAAUlB,MAAMmB,SAAS,KAAKvB,MAAM;AAE1C,eAAW,CAAA,EAAGwB,GAAAA,KAAQF,SAAS;AAC7B,YAAMG,OAAO,KAAKlB,UAAUiB,GAAAA,EAAME,KAAKtB,CAAAA,WAAAA;AACrC,YAAIgB,KAAKO,eAAeC,UAAaC,MAAMC,QAAQV,KAAKW,KAAK,GAAG;AAC9DX,eAAKW,MAAMX,KAAKO,UAAU,IAAIK,aAAa5B,MAAAA;QAC7C,OAAO;AACJgB,eAAKW,MAAkCX,KAAKa,YAAY,IAAID,aAAa5B,MAAAA;QAC5E;MACF,CAAA;AACAiB,YAAMa,KAAKT,IAAAA;IACb;AAEA,UAAMU,QAAQC,IAAIf,KAAAA;EACpB;AACF;;;;;;;;;","names":["AppConfig","config","get","key","getAs","getString","String","getNumber","Number","getBoolean","Boolean","getObject","deepmerge","objectVisitor","obj","callback","visit","path","owner","propertyPath","arrayIndex","Array","isArray","forEach","item","index","entries","Object","entry","length","propertyType","AppConfigBuilder","sources","providers","addSource","source","push","addProvider","provider","build","sourceTasks","Promise","all","map","x","load","mergedConfig","length","deepmerge","tasks","parse","value","meta","find","canParse","objectVisitor","AppConfig","tryParseJson","text","JSON","parse","_","value","nestKeys","record","separator","result","key","Object","entries","parts","split","length","current","i","part","dotenv","AppConfigSourceDotenv","filePath","options","load","result","dotenv","config","path","quiet","error","parsed","groupSeparator","nestKeys","existsSync","readFile","AppConfigSourceJson","options","filePath","ignoreMissingFile","encoding","load","existsSync","file","readFile","JSON","parse","toString","existsSync","readFile","YAML","AppConfigSourceYaml","options","filePath","ignoreMissingFile","encoding","load","existsSync","file","readFile","YAML","parse","toString","AppConfigProviderDotenv","prefix","RegExp","canParse","value","lastIndex","test","parse","meta","matches","matchAll","result","found","key","replaceAll","process","env","arrayIndex","undefined","Array","isArray","owner","tryParseJson","propertyPath","Injectable","SecretManagerServiceClient","ServerkitError","AppConfigProviderGcpSecrets","secretmanagerClient","SecretManagerServiceClient","prefix","projectId","RegExp","canParse","value","lastIndex","test","getSecret","secretId","secret","accessSecretVersion","name","payload","data","toString","error","ServerkitError","withCause","withInternalDetails","parse","meta","tasks","matches","matchAll","key","task","then","arrayIndex","undefined","Array","isArray","owner","tryParseJson","propertyPath","push","Promise","all"]}
|
|
@@ -60,8 +60,11 @@ export declare class AppConfigProviderGcpSecrets implements AppConfigProvider {
|
|
|
60
60
|
* Fetches a secret from GCP Secret Manager.
|
|
61
61
|
*
|
|
62
62
|
* @param secretId - The name of the secret to fetch.
|
|
63
|
-
* @returns A promise that resolves to the secret value
|
|
64
|
-
*
|
|
63
|
+
* @returns A promise that resolves to the secret value.
|
|
64
|
+
* @throws {ServerkitError} When Secret Manager rejects the access request (e.g. missing
|
|
65
|
+
* secret, IAM denial, network failure). The original error is attached via `withCause`
|
|
66
|
+
* and the failing `secretId` / `projectId` are recorded in `internalDetails`. Surfacing
|
|
67
|
+
* the failure prevents callers booting with an empty password / API key.
|
|
65
68
|
* @internal
|
|
66
69
|
*/
|
|
67
70
|
private getSecret;
|
|
@@ -78,6 +81,8 @@ export declare class AppConfigProviderGcpSecrets implements AppConfigProvider {
|
|
|
78
81
|
* @param meta - Metadata about the value's location in the configuration object.
|
|
79
82
|
* @returns A promise that resolves when all secrets have been fetched and the
|
|
80
83
|
* transformation is complete.
|
|
84
|
+
* @throws {ServerkitError} Propagated from {@link getSecret} when any referenced secret
|
|
85
|
+
* cannot be resolved. The build call site is expected to fail loud and stop boot.
|
|
81
86
|
*
|
|
82
87
|
* @example
|
|
83
88
|
* ```typescript
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.config.provider.gcp.secrets.d.ts","sourceRoot":"","sources":["../../src/providers/app.config.provider.gcp.secrets.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"app.config.provider.gcp.secrets.d.ts","sourceRoot":"","sources":["../../src/providers/app.config.provider.gcp.secrets.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAKzD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,qBACa,2BAA4B,YAAW,iBAAiB;IAuBjE,OAAO,CAAC,QAAQ,CAAC,SAAS;IAtB5B,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAoC;IACxE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAEhC;;;;;;;;;;;;;;;;;OAiBG;gBAEgB,SAAS,EAAE,MAAM,EAClC,MAAM,GAAE,MAAM,GAAG,MAA0B;IAK7C;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO;IAQhC;;;;;;;;;;OAUG;YACW,SAAS;IAevB;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;IACG,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;CAiBnE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maroonedsoftware/appconfig",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "A flexible, type-safe configuration management library with support for multiple sources and value transformation.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Marooned Software",
|
|
@@ -31,13 +31,14 @@
|
|
|
31
31
|
],
|
|
32
32
|
"dependencies": {
|
|
33
33
|
"deepmerge-ts": "^7.1.5",
|
|
34
|
-
"dotenv": "^17.
|
|
35
|
-
"injectkit": "^1.
|
|
34
|
+
"dotenv": "^17.4.2",
|
|
35
|
+
"injectkit": "^1.2.0",
|
|
36
|
+
"@maroonedsoftware/errors": "1.7.0"
|
|
36
37
|
},
|
|
37
38
|
"devDependencies": {
|
|
38
|
-
"@google-cloud/secret-manager": "^6.1.
|
|
39
|
-
"yaml": "^2.8.
|
|
40
|
-
"@repo/config-eslint": "0.2.
|
|
39
|
+
"@google-cloud/secret-manager": "^6.1.2",
|
|
40
|
+
"yaml": "^2.8.4",
|
|
41
|
+
"@repo/config-eslint": "0.2.1",
|
|
41
42
|
"@repo/config-typescript": "0.1.0"
|
|
42
43
|
},
|
|
43
44
|
"peerDependencies": {
|