configate 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,215 @@
1
+ # Configate
2
+
3
+ Configuration helper for TypeScript applications.
4
+
5
+ It acts as a gateway to your configuration, allowing it to be defined in various ways but used only in a single, type-safe manner.
6
+
7
+ No dependencies, ESM only.
8
+
9
+ ## Overview
10
+
11
+ Configate supports:
12
+ - defining type-safe configuration files in TypeScript
13
+ - loading configuration files in `ts`, `js` and `json` formats
14
+ - merging default configuration with environment-specific one based on `NODE_ENV` environment variable (or the provided environment name)
15
+ - merging configs from multiple directories
16
+ - merging objects deeply. Arrays are always replaced, not merged.
17
+ - reading environment variables and treating them as part of configuration - should always be used for secrets
18
+ - easy and type-safe access to configuration properties - it throws error when accessing undefined properties
19
+ - configuration immutability - it freezes the configuration object to prevent modifications
20
+ - EcmaScript Modules (ESM) - it works **only** in ESM applications
21
+ - but config files can be in CommonJS format if really necessary
22
+
23
+ ## Installation
24
+
25
+ To install Configate, use your preferred package manager:
26
+
27
+ ```sh
28
+ npm install configate
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ ### Using Configate in your application
34
+
35
+ Use the `loadConfig` function once, to load and merge configurations from specified directories.
36
+ With parameters you can define:
37
+ - `configDirs`: (Default: `['${current-working-directory}/config']`) An array of directories to load configurations from
38
+ - `environment`: (Default: `process.env.NODE_ENV`) The environment to load specific configurations for
39
+ - `fileExtensions`: (Default: `['ts', 'js']`) An array of file extensions to load configurations from
40
+ - `throwOnUndefinedProp`: (Default: `true`) If true, throws an error when accessing undefined properties
41
+ - `freezeConfig`: (Default: `true`) If true, freezes the configuration object to make it immutable
42
+
43
+ ```ts
44
+ // src/config.ts
45
+ import { loadConfig } from 'configate';
46
+
47
+ export const { config } = await loadConfig<YourConfigStructure>();
48
+
49
+ export type YourConfigStructure = {
50
+ database: {
51
+ host: string;
52
+ port: number;
53
+ password: string
54
+ };
55
+ };
56
+ ```
57
+
58
+ Use this `src/config.ts` anywhere in your application to access the configuration object just like this:
59
+ ```ts
60
+ // src/app.ts
61
+ import { config } from './config.ts';
62
+
63
+ const database = dbClient({
64
+ host: config.database.host,
65
+ port: config.database.port,
66
+ password: config.database.password,
67
+ });
68
+ ```
69
+
70
+ ### Defining configuration files
71
+
72
+ 1. Create a `config` directory in your project.
73
+ 2. Create `default.ts` file in `config` directory and export a `config` object with default values.
74
+
75
+ ```ts
76
+ // config/default.ts
77
+ import type { YourConfigStructure } from '../src/config.ts';
78
+
79
+ export const config: YourConfigStructure = {
80
+ database: {
81
+ host: 'localhost',
82
+ port: 5432,
83
+ password: ''
84
+ },
85
+ };
86
+ ```
87
+
88
+ That's it 🎉
89
+
90
+ ### Defining environment-specific configuration files
91
+
92
+ Environments can be named for example `development`, `staging`, `production` but you can use any names you want.
93
+
94
+ Create for example `production.ts` file in `config` directory and export a `config` object.
95
+ - you can use the `DeepPartial` type to allow partial configuration, since usually you just want to override some properties.
96
+ - this file will be merged with the default configuration if the `NODE_ENV` environment variable is set to `production`.
97
+
98
+ ```ts
99
+ // config/production.ts
100
+ import type { DeepPartial } from 'configate';
101
+ import type { YourConfigStructure } from '../src/config.ts';
102
+
103
+ export const config: DeepPartial<YourConfigStructure> = {
104
+ database: {
105
+ host: 'database-production-server.com',
106
+ },
107
+ };
108
+ ```
109
+
110
+ Do the same for other environments if you need to override more properties for them.
111
+
112
+ ### Using environment variables
113
+
114
+ When you need to define secrets in configuration, they should be defined via environment variables.
115
+
116
+ Create `custom-environment-variables.ts` file in `config` directory and export a `config` object.
117
+ - use `process.env` to read environment variables and assign to property in your configuration
118
+ - this file will be merged with other configs as last one so environment variables always have priority
119
+
120
+ ```ts
121
+ // config/custom-environment-variables.ts
122
+ import type { DeepPartial } from 'configate';
123
+ import type { YourConfigStructure } from '../src/config.ts';
124
+
125
+ export const config: DeepPartial<YourConfigStructure> = {
126
+ database: {
127
+ password: process.env.DATABASE_PASSWORD,
128
+ },
129
+ };
130
+ ```
131
+
132
+ ### Defining local configuration files
133
+
134
+ Local configuration files are not committed to the repository and are used for local development only.
135
+ Use them to override some configuration when running the application locally.
136
+
137
+ Supported variants:
138
+ - `local.ts` - always loaded
139
+ - `local-{environment}.ts` - local, environment-specific config. Example: `local-development.ts`
140
+ - loaded when `NODE_ENV` is set or `environment` parameter is provided to `loadConfig` function
141
+
142
+ Add this to `.gitignore` to prevent committing local configuration files:
143
+ ```txt
144
+ **/config/local*
145
+ ```
146
+
147
+ ### Order of loading configuration files
148
+
149
+ ```
150
+ default.ext
151
+ {environment}.ext
152
+ local.ext
153
+ local-{environment}.ext
154
+ custom-environment-variables.ext
155
+ ```
156
+
157
+ ### Using unsecure config
158
+
159
+ Sometimes you may need to use configuration which doesn't throw on undefined properties,
160
+ for example when you want to pass part of it to some external module and it will try to read unknown properties.
161
+ But you shouldn't set `throwOnUndefinedProp: false` to just handle this case.
162
+
163
+ For this reason, the `unsecureConfig` object is also returned from `loadConfig` function, alongside the `config` object.
164
+
165
+ ```ts
166
+ // src/config.ts
167
+ import { loadConfig } from 'configate';
168
+
169
+ export const { config, unsecureConfig } = await loadConfig();
170
+
171
+ someExternalModule(unsecureConfig.database); // It won't throw error if external module tries to read e.g. `unsecureConfig.database.user` property
172
+ ```
173
+
174
+ ### Alias for config file
175
+
176
+ If you want to import `src/config.ts` with absolute path, define:
177
+ ```json5
178
+ // package.json
179
+ {
180
+ "imports": {
181
+ "#config": "./src/config.ts"
182
+ }
183
+ }
184
+ ```
185
+ and
186
+ ```json5
187
+ // tsconfig.json
188
+ {
189
+ "compilerOptions": {
190
+ "paths": { "#config": ["./src/config.ts"] }
191
+ }
192
+ }
193
+ ```
194
+ and then import it like this:
195
+ ```ts
196
+ import { config } from '#config';
197
+
198
+ const host = config.database.host;
199
+ ```
200
+
201
+ ### Examples
202
+
203
+ #### Loading configurations from multiple directories
204
+
205
+ ```ts
206
+ import { loadConfig } from 'configate';
207
+
208
+ export const { config } = await loadConfig<TestConfig>({
209
+ configDirs: [
210
+ `${import.meta.dirname}/../../someParentConfigDirectory`,
211
+ `${import.meta.dirname}/../config`,
212
+ ],
213
+ });
214
+ ```
215
+
@@ -0,0 +1,7 @@
1
+ export type DefaultConfig = Record<string, any>;
2
+ export type Environment = 'development' | 'staging' | 'production' | 'test' | string;
3
+ export type FileExtension = 'ts' | 'mts' | 'js' | 'mjs' | 'cjs' | 'json';
4
+ export type DeepPartial<T> = T extends object ? {
5
+ [P in keyof T]?: DeepPartial<T[P]>;
6
+ } : T | undefined;
7
+ export declare function isObject(item: unknown): item is object;
package/dist/common.js ADDED
@@ -0,0 +1,3 @@
1
+ export function isObject(item) {
2
+ return item !== null && typeof item === 'object' && !Array.isArray(item);
3
+ }
@@ -0,0 +1,5 @@
1
+ import { type DefaultConfig } from './common.ts';
2
+ /**
3
+ * Use Object.freeze to make the config object immutable
4
+ */
5
+ export declare function deepFreezeConfig<T extends DefaultConfig>(config: T): T;
@@ -0,0 +1,12 @@
1
+ import { isObject } from "./common.js";
2
+ /**
3
+ * Use Object.freeze to make the config object immutable
4
+ */
5
+ export function deepFreezeConfig(config) {
6
+ for (const key in config) {
7
+ if (isObject(config[key])) {
8
+ config[key] = deepFreezeConfig(config[key]);
9
+ }
10
+ }
11
+ return Object.freeze(config);
12
+ }
@@ -0,0 +1,9 @@
1
+ import { type DefaultConfig } from './common.ts';
2
+ /**
3
+ * Custom implementation of deepMerge to avoid using an external dependency
4
+ *
5
+ * - it merges objects deeply
6
+ * - it overrides array, doesn't merge array elements
7
+ * - it ignores properties with `undefined` values
8
+ */
9
+ export declare function deepMerge<T extends DefaultConfig>(target: T, ...sources: Array<Partial<T>>): T;
@@ -0,0 +1,31 @@
1
+ import { isObject } from "./common.js";
2
+ /**
3
+ * Custom implementation of deepMerge to avoid using an external dependency
4
+ *
5
+ * - it merges objects deeply
6
+ * - it overrides array, doesn't merge array elements
7
+ * - it ignores properties with `undefined` values
8
+ */
9
+ export function deepMerge(target, ...sources) {
10
+ if (!sources.length) {
11
+ return target;
12
+ }
13
+ const source = sources.shift();
14
+ if (isObject(target) && isObject(source)) {
15
+ for (const key in source) {
16
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
17
+ if (key === '__proto__' || key === 'constructor') {
18
+ continue;
19
+ }
20
+ const sourceValue = source[key];
21
+ if (isObject(sourceValue) && isObject(target[key])) {
22
+ target[key] = deepMerge(target[key], sourceValue);
23
+ }
24
+ else if (sourceValue !== undefined) {
25
+ target[key] = sourceValue;
26
+ }
27
+ }
28
+ }
29
+ }
30
+ return deepMerge(target, ...sources);
31
+ }
@@ -0,0 +1,39 @@
1
+ import type { DefaultConfig, Environment, FileExtension } from './common.ts';
2
+ /**
3
+ * Config library to load configuration files based on the environment
4
+ *
5
+ * Features:
6
+ * - Load config files in order:
7
+ * 1. default.ext
8
+ * 2. {environment}.ext
9
+ * 4. local.ext
10
+ * 3. local-{environment}.ext
11
+ * 5. custom-environment-variables.ext (only for .ts and .js files)
12
+ * - Throw an error if a property is accessed that is not defined in the config
13
+ * - Freeze the config object to prevent modifications
14
+ * - Supported config file formats: TypeScript (.ts, .mts), JavaScript (.js, .mjs), JSON (.json)
15
+ * - Config file can `export default {}` or `export const config: Config = { ... }`.
16
+ * - named export is recommended in TS for type safety of the config object
17
+ *
18
+ * @param configDirs - paths to directories where the config files are located. Relative or absolute. Directories are merged in the array order. Default: ['${current-working-directory}/config']
19
+ * @param environment - the environment to load the config for. Default: process.env.NODE_ENV
20
+ * @param fileExtensions - an array of file extensions to use when looking for config files. Configs are loaded in this order. Default: ['ts', 'js']
21
+ * @param throwOnUndefinedProp - throw an error if a property is accessed that is not defined in the config. Default: true
22
+ * @param freezeConfig - freeze the config object to prevent modifications. Default: true
23
+ *
24
+ * @returns a promise that resolves to an object with 2 properties:
25
+ * - `config` - a secure, frozen object with the loaded config. Throws an error if an undefined property is accessed
26
+ * - `unsecureConfig` - an unsecure config. May be needed if config is passed directly to some module that wants to read undefined props or modify it
27
+ */
28
+ export declare function defineConfig<Config extends DefaultConfig>({ configDirs, environment, fileExtensions, throwOnUndefinedProp, freezeConfig, }: DefineConfigOptions): Promise<{
29
+ config: Config;
30
+ unsecureConfig: Config;
31
+ }>;
32
+ type DefineConfigOptions = {
33
+ configDirs?: string[];
34
+ environment?: Environment;
35
+ fileExtensions?: FileExtension[];
36
+ throwOnUndefinedProp?: boolean;
37
+ freezeConfig?: boolean;
38
+ };
39
+ export {};
@@ -0,0 +1,52 @@
1
+ import { deepFreezeConfig } from "./deepFreezeConfig.js";
2
+ import { deepMerge } from "./deepMerge.js";
3
+ import { importConfigFiles } from "./importConfigFiles.js";
4
+ import { makeSecureDeepProxy } from "./makeSecureDeepProxy.js";
5
+ /**
6
+ * Config library to load configuration files based on the environment
7
+ *
8
+ * Features:
9
+ * - Load config files in order:
10
+ * 1. default.ext
11
+ * 2. {environment}.ext
12
+ * 4. local.ext
13
+ * 3. local-{environment}.ext
14
+ * 5. custom-environment-variables.ext (only for .ts and .js files)
15
+ * - Throw an error if a property is accessed that is not defined in the config
16
+ * - Freeze the config object to prevent modifications
17
+ * - Supported config file formats: TypeScript (.ts, .mts), JavaScript (.js, .mjs), JSON (.json)
18
+ * - Config file can `export default {}` or `export const config: Config = { ... }`.
19
+ * - named export is recommended in TS for type safety of the config object
20
+ *
21
+ * @param configDirs - paths to directories where the config files are located. Relative or absolute. Directories are merged in the array order. Default: ['${current-working-directory}/config']
22
+ * @param environment - the environment to load the config for. Default: process.env.NODE_ENV
23
+ * @param fileExtensions - an array of file extensions to use when looking for config files. Configs are loaded in this order. Default: ['ts', 'js']
24
+ * @param throwOnUndefinedProp - throw an error if a property is accessed that is not defined in the config. Default: true
25
+ * @param freezeConfig - freeze the config object to prevent modifications. Default: true
26
+ *
27
+ * @returns a promise that resolves to an object with 2 properties:
28
+ * - `config` - a secure, frozen object with the loaded config. Throws an error if an undefined property is accessed
29
+ * - `unsecureConfig` - an unsecure config. May be needed if config is passed directly to some module that wants to read undefined props or modify it
30
+ */
31
+ export async function defineConfig({ configDirs = [`${process.cwd()}/config`], environment = process.env.NODE_ENV, fileExtensions = ['ts', 'js'], throwOnUndefinedProp = true, freezeConfig = true, }) {
32
+ let mergedConfig = {};
33
+ for (const configDir of configDirs) {
34
+ const config = await importConfigFiles({
35
+ configDir,
36
+ environment,
37
+ fileExtensions,
38
+ });
39
+ mergedConfig = deepMerge(mergedConfig, config);
40
+ }
41
+ const unsecureConfig = structuredClone(mergedConfig);
42
+ if (throwOnUndefinedProp) {
43
+ mergedConfig = makeSecureDeepProxy(mergedConfig);
44
+ }
45
+ if (freezeConfig) {
46
+ mergedConfig = deepFreezeConfig(mergedConfig);
47
+ }
48
+ return {
49
+ config: mergedConfig,
50
+ unsecureConfig: unsecureConfig,
51
+ };
52
+ }
@@ -0,0 +1,6 @@
1
+ import type { DefaultConfig, FileExtension } from './common.ts';
2
+ export declare function importConfigFile<Config extends DefaultConfig>({ filePath, fileExtensions, shouldThrowError, }: {
3
+ filePath: string;
4
+ fileExtensions: FileExtension[];
5
+ shouldThrowError?: boolean;
6
+ }): Promise<Config>;
@@ -0,0 +1,45 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import fs from 'node:fs/promises';
10
+ export async function importConfigFile({ filePath, fileExtensions, shouldThrowError = false, }) {
11
+ let selectedExtension;
12
+ for (const ext of fileExtensions) {
13
+ try {
14
+ // Quickly check if the file exists to avoid unnecessary parsing in import()
15
+ await fs.access(`${filePath}.${ext}`, fs.constants.R_OK);
16
+ selectedExtension = ext;
17
+ break;
18
+ }
19
+ catch (_error) { }
20
+ }
21
+ if (!selectedExtension) {
22
+ if (shouldThrowError) {
23
+ throw new Error(`Config file "${filePath}" not found with any extension: ${fileExtensions.join(', ')}`);
24
+ }
25
+ return {};
26
+ }
27
+ const importOptions = selectedExtension === 'json' ? { with: { type: 'json' } } : undefined;
28
+ try {
29
+ const configFile = await import(__rewriteRelativeImportExtension(`${filePath}.${selectedExtension}`), importOptions);
30
+ // Named export of `config` variable is preferred over default export
31
+ if (configFile.config) {
32
+ return configFile.config;
33
+ }
34
+ if (configFile.default) {
35
+ return configFile.default;
36
+ }
37
+ throw new Error(`Config file "${filePath}" has no default export and does not have export "config"`);
38
+ }
39
+ catch (error) {
40
+ if (shouldThrowError) {
41
+ throw error;
42
+ }
43
+ return {};
44
+ }
45
+ }
@@ -0,0 +1,8 @@
1
+ import type { DefaultConfig, Environment, FileExtension } from './common.ts';
2
+ export declare function importConfigFiles<Config extends DefaultConfig>({ configDir, environment, fileExtensions, }: ImportConfigFilesOptions): Promise<DefaultConfig>;
3
+ type ImportConfigFilesOptions = {
4
+ configDir: string;
5
+ environment?: Environment;
6
+ fileExtensions: FileExtension[];
7
+ };
8
+ export {};
@@ -0,0 +1,37 @@
1
+ import { deepMerge } from "./deepMerge.js";
2
+ import { importConfigFile } from "./importConfigFile.js";
3
+ export async function importConfigFiles({ configDir, environment, fileExtensions, }) {
4
+ const defaultConfig = await importConfigFile({
5
+ filePath: `${configDir}/default`,
6
+ fileExtensions,
7
+ shouldThrowError: true,
8
+ });
9
+ let envConfig;
10
+ if (environment) {
11
+ try {
12
+ envConfig = await importConfigFile({
13
+ filePath: `${configDir}/${environment}`,
14
+ fileExtensions,
15
+ shouldThrowError: true,
16
+ });
17
+ }
18
+ catch (_error) {
19
+ console.warn(`Environment ${environment} defined but no config file found`);
20
+ }
21
+ }
22
+ const localConfig = await importConfigFile({
23
+ filePath: `${configDir}/local`,
24
+ fileExtensions,
25
+ });
26
+ const localEnvConfig = environment
27
+ ? await importConfigFile({
28
+ filePath: `${configDir}/local-${environment}`,
29
+ fileExtensions,
30
+ })
31
+ : {};
32
+ const customEnvVarsConfig = await importConfigFile({
33
+ filePath: `${configDir}/custom-environment-variables`,
34
+ fileExtensions: fileExtensions.filter((ext) => ext !== 'json'), // JSON not supported because it cannot use `process.env`
35
+ });
36
+ return deepMerge(structuredClone(defaultConfig), structuredClone(envConfig ?? {}), structuredClone(localConfig), structuredClone(localEnvConfig), structuredClone(customEnvVarsConfig));
37
+ }
@@ -0,0 +1,2 @@
1
+ export { defineConfig } from './defineConfig.ts';
2
+ export type { DeepPartial, Environment, FileExtension } from './common.ts';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { defineConfig } from "./defineConfig.js";
@@ -0,0 +1,6 @@
1
+ import { type DefaultConfig } from './common.ts';
2
+ /**
3
+ * Use Proxy to add custom behavior when accessing properties of the config object
4
+ * Throw an error if the property is not defined in the config
5
+ */
6
+ export declare function makeSecureDeepProxy<T extends DefaultConfig>(config: T): T;
@@ -0,0 +1,35 @@
1
+ import { isObject } from "./common.js";
2
+ /**
3
+ * Use Proxy to add custom behavior when accessing properties of the config object
4
+ * Throw an error if the property is not defined in the config
5
+ */
6
+ export function makeSecureDeepProxy(config) {
7
+ for (const prop in config) {
8
+ if (isObject(config[prop])) {
9
+ // If it's an object, recursively wrap it
10
+ config[prop] = makeSecureDeepProxy(config[prop]);
11
+ }
12
+ else if (Array.isArray(config[prop])) {
13
+ // If it's an array, wrap each element and the array itself
14
+ config[prop] = makeSecureProxy(config[prop].map((item) => isObject(item) || Array.isArray(item)
15
+ ? makeSecureDeepProxy(item)
16
+ : item));
17
+ }
18
+ }
19
+ return makeSecureProxy(config);
20
+ }
21
+ function makeSecureProxy(targetObject) {
22
+ return new Proxy(targetObject, {
23
+ get(target, prop) {
24
+ // Handle Symbol.toStringTag and Array properties
25
+ if (prop === Symbol.toStringTag ||
26
+ (Array.isArray(target) && Number.isNaN(Number(prop)))) {
27
+ return Reflect.get(target, prop);
28
+ }
29
+ if (!(prop in target)) {
30
+ throw new Error(`Property ${String(prop)} is not defined in the config`);
31
+ }
32
+ return Reflect.get(target, prop);
33
+ },
34
+ });
35
+ }
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "configate",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Configuration helper for TypeScript applications",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "default": "./dist/index.js",
12
+ "import": "./dist/index.js",
13
+ "types": "./dist/index.d.ts"
14
+ }
15
+ },
16
+ "scripts": {
17
+ "build": "tsc",
18
+ "ci": "node --run test && npm run typecheck && node --run lint",
19
+ "lint": "biome check",
20
+ "test": "node --test-isolation=none --test-reporter=spec --experimental-test-coverage --test-coverage-exclude='src/{testConfigDirs/**/*,**/*.test.ts}' --test 'src/**/*.test.ts'",
21
+ "typecheck": "tsc --noEmit"
22
+ },
23
+ "files": ["dist"],
24
+ "engines": {
25
+ "node": ">= 20"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/mdrobny/configate.git"
30
+ },
31
+ "keywords": ["config"],
32
+ "author": "Michal Drobniak",
33
+ "license": "Apache-2.0",
34
+ "bugs": {
35
+ "url": "https://github.com/mdrobny/configate/issues"
36
+ },
37
+ "homepage": "https://github.com/mdrobny/configate#readme",
38
+ "devDependencies": {
39
+ "@biomejs/biome": "1.9.4",
40
+ "@types/node": "^22.10.6",
41
+ "typescript": "^5.7.3"
42
+ }
43
+ }