@philiprehberger/config-layer 0.1.5

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 philiprehberger
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # @philiprehberger/config-layer
2
+
3
+ [![CI](https://github.com/philiprehberger/ts-config-layer/actions/workflows/ci.yml/badge.svg)](https://github.com/philiprehberger/ts-config-layer/actions/workflows/ci.yml)
4
+ [![npm version](https://img.shields.io/npm/v/@philiprehberger/config-layer.svg)](https://www.npmjs.com/package/@philiprehberger/config-layer)
5
+ [![License](https://img.shields.io/github/license/philiprehberger/ts-config-layer)](LICENSE)
6
+
7
+ Layered configuration loader with typed output and multiple sources
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @philiprehberger/config-layer
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import { loadConfig, envSource, objectSource } from '@philiprehberger/config-layer';
19
+
20
+ const config = loadConfig({
21
+ port: { type: 'number', default: 3000 },
22
+ dbUrl: { type: 'string', required: true, env: 'DATABASE_URL' },
23
+ debug: { type: 'boolean', default: false },
24
+ }, [
25
+ envSource(),
26
+ objectSource({ port: 8080 }),
27
+ ]);
28
+
29
+ // config.port → 8080 (from objectSource, overrides default)
30
+ // config.dbUrl → from DATABASE_URL env var
31
+ // config.debug → false (default)
32
+ ```
33
+
34
+ ### Sources
35
+
36
+ Sources are applied in order — later sources override earlier ones:
37
+
38
+ ```ts
39
+ const config = loadConfig(schema, [
40
+ envSource(), // Load from process.env
41
+ envSource('APP_'), // Load from env vars with APP_ prefix
42
+ objectSource({ port: 9090 }), // Override with explicit values
43
+ ]);
44
+ ```
45
+
46
+ ### Schema
47
+
48
+ ```ts
49
+ const schema = {
50
+ // Shorthand
51
+ host: 'string',
52
+ port: 'number',
53
+ debug: 'boolean',
54
+
55
+ // Full definition
56
+ dbUrl: {
57
+ type: 'string',
58
+ required: true, // Throws if missing (default: true)
59
+ env: 'DATABASE_URL', // Map to specific env var name
60
+ default: undefined, // Default value if not provided
61
+ },
62
+ };
63
+ ```
64
+
65
+ ## API
66
+
67
+ | Export | Description |
68
+ |--------|-------------|
69
+ | `loadConfig(schema, sources)` | Load and validate config from sources |
70
+ | `envSource(prefix?)` | Read from `process.env`, optionally filtering by prefix |
71
+ | `objectSource(obj)` | Read from a plain object |
72
+
73
+ ### `ConfigFieldDef`
74
+
75
+ | Property | Type | Default | Description |
76
+ |----------|------|---------|-------------|
77
+ | `type` | `'string' \| 'number' \| 'boolean'` | — | Value type (auto-coerced) |
78
+ | `required` | `boolean` | `true` | Throw if missing |
79
+ | `default` | `string \| number \| boolean` | — | Default value |
80
+ | `env` | `string` | — | Override env var name |
81
+
82
+
83
+ ## Development
84
+
85
+ ```bash
86
+ npm install
87
+ npm run build
88
+ npm test
89
+ ```
90
+
91
+ ## License
92
+
93
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,110 @@
1
+ 'use strict';
2
+
3
+ // src/loader.ts
4
+ function normalizeField(field) {
5
+ if (typeof field === "string") {
6
+ return { type: field };
7
+ }
8
+ return field;
9
+ }
10
+ function coerce(value, type) {
11
+ switch (type) {
12
+ case "number": {
13
+ const n = Number(value);
14
+ if (isNaN(n)) throw new Error(`Cannot convert "${value}" to number`);
15
+ return n;
16
+ }
17
+ case "boolean":
18
+ return value === "true" || value === "1" || value === "yes";
19
+ case "string":
20
+ default:
21
+ return value;
22
+ }
23
+ }
24
+ function loadConfig(schema, sources) {
25
+ var _a, _b, _c;
26
+ const merged = {};
27
+ for (const source of sources) {
28
+ const data = source.load();
29
+ for (const [key, value] of Object.entries(data)) {
30
+ if (value !== void 0) {
31
+ merged[key] = value;
32
+ }
33
+ }
34
+ }
35
+ const result = {};
36
+ const errors = [];
37
+ for (const [key, rawField] of Object.entries(schema)) {
38
+ const field = normalizeField(rawField);
39
+ const envKey = (_b = (_a = field.env) == null ? void 0 : _a.toLowerCase()) != null ? _b : key.toLowerCase();
40
+ const raw = (_c = merged[envKey]) != null ? _c : merged[key.toLowerCase()];
41
+ if (raw !== void 0) {
42
+ try {
43
+ result[key] = coerce(raw, field.type);
44
+ } catch (e) {
45
+ errors.push(`${key}: ${e instanceof Error ? e.message : String(e)}`);
46
+ }
47
+ } else if (field.default !== void 0) {
48
+ result[key] = field.default;
49
+ } else if (field.required !== false) {
50
+ errors.push(`${key}: required but not provided`);
51
+ }
52
+ }
53
+ if (errors.length > 0) {
54
+ throw new Error(`Config validation failed:
55
+ ${errors.join("\n ")}`);
56
+ }
57
+ return result;
58
+ }
59
+
60
+ // src/sources.ts
61
+ function envSource(prefix) {
62
+ return {
63
+ name: "env",
64
+ load() {
65
+ const env = {};
66
+ try {
67
+ if (typeof globalThis !== "undefined" && "process" in globalThis) {
68
+ const proc = globalThis.process;
69
+ if (proc.env) {
70
+ if (prefix) {
71
+ const upper = prefix.toUpperCase();
72
+ for (const [key, value] of Object.entries(proc.env)) {
73
+ if (key.startsWith(upper)) {
74
+ const stripped = key.slice(upper.length).replace(/^_/, "");
75
+ env[stripped.toLowerCase()] = value;
76
+ }
77
+ }
78
+ } else {
79
+ for (const [key, value] of Object.entries(proc.env)) {
80
+ env[key.toLowerCase()] = value;
81
+ }
82
+ }
83
+ }
84
+ }
85
+ } catch (e) {
86
+ }
87
+ return env;
88
+ }
89
+ };
90
+ }
91
+ function objectSource(obj) {
92
+ return {
93
+ name: "object",
94
+ load() {
95
+ const result = {};
96
+ for (const [key, value] of Object.entries(obj)) {
97
+ if (value !== void 0 && value !== null) {
98
+ result[key.toLowerCase()] = String(value);
99
+ }
100
+ }
101
+ return result;
102
+ }
103
+ };
104
+ }
105
+
106
+ exports.envSource = envSource;
107
+ exports.loadConfig = loadConfig;
108
+ exports.objectSource = objectSource;
109
+ //# sourceMappingURL=index.cjs.map
110
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/loader.ts","../src/sources.ts"],"names":[],"mappings":";;;AAEA,SAAS,eAAe,KAAA,EAAyD;AAC/E,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,EAAE,MAAM,KAAA,EAAM;AAAA,EACvB;AACA,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,MAAA,CAAO,OAAe,IAAA,EAAkD;AAC/E,EAAA,QAAQ,IAAA;AAAM,IACZ,KAAK,QAAA,EAAU;AACb,MAAA,MAAM,CAAA,GAAI,OAAO,KAAK,CAAA;AACtB,MAAA,IAAI,KAAA,CAAM,CAAC,CAAA,EAAG,MAAM,IAAI,KAAA,CAAM,CAAA,gBAAA,EAAmB,KAAK,CAAA,WAAA,CAAa,CAAA;AACnE,MAAA,OAAO,CAAA;AAAA,IACT;AAAA,IACA,KAAK,SAAA;AACH,MAAA,OAAO,KAAA,KAAU,MAAA,I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AM,CAAA,CAAE,OAAA,CAAQ,MAAM,EAAE,CAAA;AACzD,kBAAA,GAAA,CAAI,QAAA,CAAS,WAAA,EAAa,CAAA,GAAI,KAAA;AAAA,gBAChC;AAAA,cACF;AAAA,YACF,CAAA,MAAO;AACL,cAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,IAAA,CAAK,GAAG,CAAA,EAAG;AACnD,gBAAA,GAAA,CAAI,GAAA,CAAI,WAAA,EAAa,CAAA,GAAI,KAAA;AAAA,cAC3B;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF,CAAA,CAAA,OAAQ,CAAA,EAAA;AAAA,MAA6B;AACrC,MAAA,OAAO,GAAA;AAAA,IACT;AAAA,GACF;AACF;AAEO,SAAS,aAAa,GAAA,EAA4C;AACvE,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,QAAA;AAAA,IACN,IAAA,GAAO;AACL,MAAA,MAAM,SAA6C,EAAC;AACpD,MAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,EAAG;AAC9C,QAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AACzC,UAAA,MAAA,CAAO,GAAA,CAAI,WAAA,EAAa,CAAA,GAAI,OAAO,KAAK,CAAA;AAAA,QAC1C;AAAA,MACF;AACA,MAAA,OAAO,MAAA;AAAA,IACT;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["import type { ConfigSchema, ConfigFieldDef, ConfigSource, ConfigValueType } from './types.js';\n\nfunction normalizeField(field: ConfigFieldDef | ConfigValueType): ConfigFieldDef {\n if (typeof field === 'string') {\n return { type: field };\n }\n return field;\n}\n\nfunction coerce(value: string, type: ConfigValueType): string | number | boolean {\n switch (type) {\n case 'number': {\n const n = Number(value);\n if (isNaN(n)) throw new Error(`Cannot convert \"${value}\" to number`);\n return n;\n }\n case 'boolean':\n return value === 'true' || value === '1' || value === 'yes';\n case 'string':\n default:\n return value;\n }\n}\n\nexport function loadConfig<T extends ConfigSchema>(\n schema: T,\n sources: ConfigSource[],\n): { [K in keyof T]: T[K] extends { type: 'number' } | 'number' ? number : T[K] extends { type: 'boolean' } | 'boolean' ? boolean : string } {\n const merged: Record<string, string | undefined> = {};\n\n for (const source of sources) {\n const data = source.load();\n for (const [key, value] of Object.entries(data)) {\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n }\n\n const result: Record<string, unknown> = {};\n const errors: string[] = [];\n\n for (const [key, rawField] of Object.entries(schema)) {\n const field = normalizeField(rawField);\n const envKey = field.env?.toLowerCase() ?? key.toLowerCase();\n const raw = merged[envKey] ?? merged[key.toLowerCase()];\n\n if (raw !== undefined) {\n try {\n result[key] = coerce(raw, field.type);\n } catch (e) {\n errors.push(`${key}: ${e instanceof Error ? e.message : String(e)}`);\n }\n } else if (field.default !== undefined) {\n result[key] = field.default;\n } else if (field.required !== false) {\n errors.push(`${key}: required but not provided`);\n }\n }\n\n if (errors.length > 0) {\n throw new Error(`Config validation failed:\\n ${errors.join('\\n ')}`);\n }\n\n return result as ReturnType<typeof loadConfig<T>>;\n}\n","import type { ConfigSource } from './types.js';\n\nexport function envSource(prefix?: string): ConfigSource {\n return {\n name: 'env',\n load() {\n const env: Record<string, string | undefined> = {};\n try {\n if (typeof globalThis !== 'undefined' && 'process' in globalThis) {\n const proc = (globalThis as Record<string, unknown>).process as { env?: Record<string, string | undefined> };\n if (proc.env) {\n if (prefix) {\n const upper = prefix.toUpperCase();\n for (const [key, value] of Object.entries(proc.env)) {\n if (key.startsWith(upper)) {\n const stripped = key.slice(upper.length).replace(/^_/, '');\n env[stripped.toLowerCase()] = value;\n }\n }\n } else {\n for (const [key, value] of Object.entries(proc.env)) {\n env[key.toLowerCase()] = value;\n }\n }\n }\n }\n } catch { /* non-node environment */ }\n return env;\n },\n };\n}\n\nexport function objectSource(obj: Record<string, unknown>): ConfigSource {\n return {\n name: 'object',\n load() {\n const result: Record<string, string | undefined> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== undefined && value !== null) {\n result[key.toLowerCase()] = String(value);\n }\n }\n return result;\n },\n };\n}\n"]}
@@ -0,0 +1,34 @@
1
+ type ConfigValueType = 'string' | 'number' | 'boolean';
2
+ interface ConfigFieldDef {
3
+ type: ConfigValueType;
4
+ required?: boolean;
5
+ default?: string | number | boolean;
6
+ env?: string;
7
+ }
8
+ type ConfigSchema = Record<string, ConfigFieldDef | ConfigValueType>;
9
+ type InferConfig<T extends ConfigSchema> = {
10
+ [K in keyof T]: T[K] extends 'string' ? string : T[K] extends 'number' ? number : T[K] extends 'boolean' ? boolean : T[K] extends {
11
+ type: 'string';
12
+ } ? string : T[K] extends {
13
+ type: 'number';
14
+ } ? number : T[K] extends {
15
+ type: 'boolean';
16
+ } ? boolean : never;
17
+ };
18
+ interface ConfigSource {
19
+ name: string;
20
+ load(): Record<string, string | undefined>;
21
+ }
22
+
23
+ declare function loadConfig<T extends ConfigSchema>(schema: T, sources: ConfigSource[]): {
24
+ [K in keyof T]: T[K] extends {
25
+ type: 'number';
26
+ } | 'number' ? number : T[K] extends {
27
+ type: 'boolean';
28
+ } | 'boolean' ? boolean : string;
29
+ };
30
+
31
+ declare function envSource(prefix?: string): ConfigSource;
32
+ declare function objectSource(obj: Record<string, unknown>): ConfigSource;
33
+
34
+ export { type ConfigFieldDef, type ConfigSchema, type ConfigSource, type ConfigValueType, type InferConfig, envSource, loadConfig, objectSource };
@@ -0,0 +1,34 @@
1
+ type ConfigValueType = 'string' | 'number' | 'boolean';
2
+ interface ConfigFieldDef {
3
+ type: ConfigValueType;
4
+ required?: boolean;
5
+ default?: string | number | boolean;
6
+ env?: string;
7
+ }
8
+ type ConfigSchema = Record<string, ConfigFieldDef | ConfigValueType>;
9
+ type InferConfig<T extends ConfigSchema> = {
10
+ [K in keyof T]: T[K] extends 'string' ? string : T[K] extends 'number' ? number : T[K] extends 'boolean' ? boolean : T[K] extends {
11
+ type: 'string';
12
+ } ? string : T[K] extends {
13
+ type: 'number';
14
+ } ? number : T[K] extends {
15
+ type: 'boolean';
16
+ } ? boolean : never;
17
+ };
18
+ interface ConfigSource {
19
+ name: string;
20
+ load(): Record<string, string | undefined>;
21
+ }
22
+
23
+ declare function loadConfig<T extends ConfigSchema>(schema: T, sources: ConfigSource[]): {
24
+ [K in keyof T]: T[K] extends {
25
+ type: 'number';
26
+ } | 'number' ? number : T[K] extends {
27
+ type: 'boolean';
28
+ } | 'boolean' ? boolean : string;
29
+ };
30
+
31
+ declare function envSource(prefix?: string): ConfigSource;
32
+ declare function objectSource(obj: Record<string, unknown>): ConfigSource;
33
+
34
+ export { type ConfigFieldDef, type ConfigSchema, type ConfigSource, type ConfigValueType, type InferConfig, envSource, loadConfig, objectSource };
package/dist/index.js ADDED
@@ -0,0 +1,106 @@
1
+ // src/loader.ts
2
+ function normalizeField(field) {
3
+ if (typeof field === "string") {
4
+ return { type: field };
5
+ }
6
+ return field;
7
+ }
8
+ function coerce(value, type) {
9
+ switch (type) {
10
+ case "number": {
11
+ const n = Number(value);
12
+ if (isNaN(n)) throw new Error(`Cannot convert "${value}" to number`);
13
+ return n;
14
+ }
15
+ case "boolean":
16
+ return value === "true" || value === "1" || value === "yes";
17
+ case "string":
18
+ default:
19
+ return value;
20
+ }
21
+ }
22
+ function loadConfig(schema, sources) {
23
+ var _a, _b, _c;
24
+ const merged = {};
25
+ for (const source of sources) {
26
+ const data = source.load();
27
+ for (const [key, value] of Object.entries(data)) {
28
+ if (value !== void 0) {
29
+ merged[key] = value;
30
+ }
31
+ }
32
+ }
33
+ const result = {};
34
+ const errors = [];
35
+ for (const [key, rawField] of Object.entries(schema)) {
36
+ const field = normalizeField(rawField);
37
+ const envKey = (_b = (_a = field.env) == null ? void 0 : _a.toLowerCase()) != null ? _b : key.toLowerCase();
38
+ const raw = (_c = merged[envKey]) != null ? _c : merged[key.toLowerCase()];
39
+ if (raw !== void 0) {
40
+ try {
41
+ result[key] = coerce(raw, field.type);
42
+ } catch (e) {
43
+ errors.push(`${key}: ${e instanceof Error ? e.message : String(e)}`);
44
+ }
45
+ } else if (field.default !== void 0) {
46
+ result[key] = field.default;
47
+ } else if (field.required !== false) {
48
+ errors.push(`${key}: required but not provided`);
49
+ }
50
+ }
51
+ if (errors.length > 0) {
52
+ throw new Error(`Config validation failed:
53
+ ${errors.join("\n ")}`);
54
+ }
55
+ return result;
56
+ }
57
+
58
+ // src/sources.ts
59
+ function envSource(prefix) {
60
+ return {
61
+ name: "env",
62
+ load() {
63
+ const env = {};
64
+ try {
65
+ if (typeof globalThis !== "undefined" && "process" in globalThis) {
66
+ const proc = globalThis.process;
67
+ if (proc.env) {
68
+ if (prefix) {
69
+ const upper = prefix.toUpperCase();
70
+ for (const [key, value] of Object.entries(proc.env)) {
71
+ if (key.startsWith(upper)) {
72
+ const stripped = key.slice(upper.length).replace(/^_/, "");
73
+ env[stripped.toLowerCase()] = value;
74
+ }
75
+ }
76
+ } else {
77
+ for (const [key, value] of Object.entries(proc.env)) {
78
+ env[key.toLowerCase()] = value;
79
+ }
80
+ }
81
+ }
82
+ }
83
+ } catch (e) {
84
+ }
85
+ return env;
86
+ }
87
+ };
88
+ }
89
+ function objectSource(obj) {
90
+ return {
91
+ name: "object",
92
+ load() {
93
+ const result = {};
94
+ for (const [key, value] of Object.entries(obj)) {
95
+ if (value !== void 0 && value !== null) {
96
+ result[key.toLowerCase()] = String(value);
97
+ }
98
+ }
99
+ return result;
100
+ }
101
+ };
102
+ }
103
+
104
+ export { envSource, loadConfig, objectSource };
105
+ //# sourceMappingURL=index.js.map
106
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/loader.ts","../src/sources.ts"],"names":[],"mappings":";AAEA,SAAS,eAAe,KAAA,EAAyD;AAC/E,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,OAAO,EAAE,MAAM,KAAA,EAAM;AAAA,EACvB;AACA,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AAK,CAAA;AAAA,QAC1C;AAAA,MACF;AACA,MAAA,OAAO,MAAA;AAAA,IACT;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import type { ConfigSchema, ConfigFieldDef, ConfigSource, ConfigValueType } from './types.js';\n\nfunction normalizeField(field: ConfigFieldDef | ConfigValueType): ConfigFieldDef {\n if (typeof field === 'string') {\n return { type: field };\n }\n return field;\n}\n\nfunction coerce(value: string, type: ConfigValueType): string | number | boolean {\n switch (type) {\n case 'number': {\n const n = Number(value);\n if (isNaN(n)) throw new Error(`Cannot convert \"${value}\" to number`);\n return n;\n }\n case 'boolean':\n return value === 'true' || value === '1' || value === 'yes';\n case 'string':\n default:\n return value;\n }\n}\n\nexport function loadConfig<T extends ConfigSchema>(\n schema: T,\n sources: ConfigSource[],\n): { [K in keyof T]: T[K] extends { type: 'number' } | 'number' ? number : T[K] extends { type: 'boolean' } | 'boolean' ? boolean : string } {\n const merged: Record<string, string | undefined> = {};\n\n for (const source of sources) {\n const data = source.load();\n for (const [key, value] of Object.entries(data)) {\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n }\n\n const result: Record<string, unknown> = {};\n const errors: string[] = [];\n\n for (const [key, rawField] of Object.entries(schema)) {\n const field = normalizeField(rawField);\n const envKey = field.env?.toLowerCase() ?? key.toLowerCase();\n const raw = merged[envKey] ?? merged[key.toLowerCase()];\n\n if (raw !== undefined) {\n try {\n result[key] = coerce(raw, field.type);\n } catch (e) {\n errors.push(`${key}: ${e instanceof Error ? e.message : String(e)}`);\n }\n } else if (field.default !== undefined) {\n result[key] = field.default;\n } else if (field.required !== false) {\n errors.push(`${key}: required but not provided`);\n }\n }\n\n if (errors.length > 0) {\n throw new Error(`Config validation failed:\\n ${errors.join('\\n ')}`);\n }\n\n return result as ReturnType<typeof loadConfig<T>>;\n}\n","import type { ConfigSource } from './types.js';\n\nexport function envSource(prefix?: string): ConfigSource {\n return {\n name: 'env',\n load() {\n const env: Record<string, string | undefined> = {};\n try {\n if (typeof globalThis !== 'undefined' && 'process' in globalThis) {\n const proc = (globalThis as Record<string, unknown>).process as { env?: Record<string, string | undefined> };\n if (proc.env) {\n if (prefix) {\n const upper = prefix.toUpperCase();\n for (const [key, value] of Object.entries(proc.env)) {\n if (key.startsWith(upper)) {\n const stripped = key.slice(upper.length).replace(/^_/, '');\n env[stripped.toLowerCase()] = value;\n }\n }\n } else {\n for (const [key, value] of Object.entries(proc.env)) {\n env[key.toLowerCase()] = value;\n }\n }\n }\n }\n } catch { /* non-node environment */ }\n return env;\n },\n };\n}\n\nexport function objectSource(obj: Record<string, unknown>): ConfigSource {\n return {\n name: 'object',\n load() {\n const result: Record<string, string | undefined> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== undefined && value !== null) {\n result[key.toLowerCase()] = String(value);\n }\n }\n return result;\n },\n };\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@philiprehberger/config-layer",
3
+ "version": "0.1.5",
4
+ "description": "Layered configuration loader with typed output and multiple sources",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ }
19
+ }
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "scripts": {
25
+ "build": "tsup",
26
+ "dev": "tsup --watch",
27
+ "typecheck": "tsc --noEmit",
28
+ "prepublishOnly": "npm run build",
29
+ "test": "node --test"
30
+ },
31
+ "devDependencies": {
32
+ "tsup": "^8.0.0",
33
+ "typescript": "^5.0.0"
34
+ },
35
+ "keywords": [
36
+ "config",
37
+ "configuration",
38
+ "environment",
39
+ "typed",
40
+ "layered"
41
+ ],
42
+ "license": "MIT",
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/philiprehberger/ts-config-layer.git"
46
+ },
47
+ "homepage": "https://github.com/philiprehberger/ts-config-layer#readme",
48
+ "bugs": {
49
+ "url": "https://github.com/philiprehberger/ts-config-layer/issues"
50
+ },
51
+ "author": "Philip Rehberger",
52
+ "engines": {
53
+ "node": ">=18.0.0"
54
+ },
55
+ "sideEffects": false
56
+ }