@push.rocks/qenv 6.1.0 → 6.1.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@push.rocks/qenv",
3
- "version": "6.1.0",
3
+ "version": "6.1.1",
4
4
  "private": false,
5
5
  "description": "A module for easily handling environment variables in Node.js projects with support for .yml and .json configuration.",
6
6
  "main": "dist_ts/index.js",
@@ -26,18 +26,17 @@
26
26
  },
27
27
  "homepage": "https://code.foss.global/push.rocks/qenv",
28
28
  "devDependencies": {
29
- "@git.zone/tsbuild": "^2.2.0",
29
+ "@git.zone/tsbuild": "^2.6.4",
30
30
  "@git.zone/tsrun": "^1.3.3",
31
- "@git.zone/tstest": "^1.0.90",
32
- "@push.rocks/tapbundle": "^5.5.0",
33
- "@types/node": "^22.9.1"
31
+ "@git.zone/tstest": "^2.3.2",
32
+ "@types/node": "^22.13.13"
34
33
  },
35
34
  "dependencies": {
36
35
  "@api.global/typedrequest": "^3.1.10",
37
36
  "@configvault.io/interfaces": "^1.0.17",
38
- "@push.rocks/smartfile": "^11.0.21",
39
- "@push.rocks/smartlog": "^3.0.7",
40
- "@push.rocks/smartpath": "^5.0.18"
37
+ "@push.rocks/smartfile": "^11.2.5",
38
+ "@push.rocks/smartlog": "^3.1.8",
39
+ "@push.rocks/smartpath": "^6.0.0"
41
40
  },
42
41
  "files": [
43
42
  "ts/**/*",
package/readme.md CHANGED
@@ -1,109 +1,347 @@
1
- # @push.rocks/qenv
2
- easy promised environments
1
+ # @push.rocks/qenv 🔐
2
+ **Smart Environment Variable Management for Node.js**
3
3
 
4
- ## Install
5
- To install `@push.rocks/qenv`, you need to have Node.js installed on your system. Once Node.js is installed, you can add `@push.rocks/qenv` to your project by running the following command in your project's root directory:
4
+ > Never hardcode secrets again. Load environment variables from multiple sources with ease and confidence.
5
+
6
+ ## 🚀 Features
7
+
8
+ ✅ **Multi-source Loading** - Automatically loads from environment variables, config files, and Docker secrets
9
+ ✅ **Type-Safe** - Full TypeScript support with comprehensive type definitions
10
+ ✅ **Flexible Formats** - Supports `.yml`, `.yaml`, and `.json` configuration files
11
+ ✅ **Docker Ready** - Built-in support for Docker secrets and secret.json files
12
+ ✅ **Async & Sync** - Both synchronous and asynchronous variable retrieval
13
+ ✅ **Strict Mode** - Optional strict mode that throws errors for missing variables
14
+ ✅ **Base64 Objects** - Handle complex configuration objects with automatic encoding/decoding
15
+ ✅ **Dynamic Resolution** - Support for async functions as environment variable sources
16
+
17
+ ## 📦 Installation
6
18
 
7
19
  ```bash
20
+ # Using npm
8
21
  npm install @push.rocks/qenv --save
9
- ```
10
22
 
11
- This command will add `@push.rocks/qenv` as a dependency to your project, and you will be ready to use it in your application.
23
+ # Using pnpm (recommended)
24
+ pnpm add @push.rocks/qenv
12
25
 
13
- ## Usage
14
- `@push.rocks/qenv` provides a convenient way to manage and access environment variables in your Node.js projects, especially when dealing with different environments like development, testing, and production. Its primary use is to load environment-specific variables in an easy and organized manner. Below is an extensive guide on how to use this module effectively in various scenarios, ensuring you can handle environment variables efficiently in your projects.
15
-
16
- ### Getting Started
17
- First, ensure you have TypeScript configured in your project. `@push.rocks/qenv` is fully typed, providing excellent IntelliSense support when working in editors that support TypeScript, such as Visual Studio Code.
26
+ # Using yarn
27
+ yarn add @push.rocks/qenv
28
+ ```
18
29
 
19
- #### Importing Qenv
20
- To get started, import the `Qenv` class from `@push.rocks/qenv`:
30
+ ## 🎯 Quick Start
21
31
 
22
32
  ```typescript
23
33
  import { Qenv } from '@push.rocks/qenv';
34
+
35
+ // Create a new Qenv instance
36
+ const qenv = new Qenv('./', './', true);
37
+
38
+ // Access environment variables
39
+ const dbHost = await qenv.getEnvVarOnDemand('DB_HOST');
40
+ const apiKey = await qenv.getEnvVarOnDemand('API_KEY');
41
+
42
+ // Use strict mode to ensure variables exist
43
+ const criticalVar = await qenv.getEnvVarOnDemandStrict('CRITICAL_CONFIG');
44
+ // Throws error if CRITICAL_CONFIG is not set!
24
45
  ```
25
46
 
26
- #### Basic Configuration
27
- `@push.rocks/qenv` works with two main files: `qenv.yml` for specifying required environment variables, and `env.yml` for specifying values for these variables. These files should be placed in your project directory.
47
+ ## 📖 Configuration
48
+
49
+ ### Setting Up Your Environment Files
28
50
 
29
- ##### qenv.yml
30
- This file specifies the environment variables that are required by your application. An example `qenv.yml` might look like this:
51
+ #### 1. Define Required Variables (`qenv.yml`)
52
+
53
+ Create a `qenv.yml` file to specify which environment variables your application needs:
31
54
 
32
55
  ```yaml
33
56
  required:
34
57
  - DB_HOST
35
58
  - DB_USER
36
- - DB_PASS
59
+ - DB_PASSWORD
60
+ - API_KEY
61
+ - LOG_LEVEL
37
62
  ```
38
63
 
39
- ##### env.yml
40
- This file contains the actual values for the environment variables in a development or testing environment. An example `env.yml` could be:
64
+ #### 2. Provide Values (`env.yml` or `env.json`)
65
+
66
+ For local development, create an `env.yml` or `env.json` file:
41
67
 
68
+ **env.yml:**
42
69
  ```yaml
43
70
  DB_HOST: localhost
44
- DB_USER: user
45
- DB_PASS: pass
71
+ DB_USER: developer
72
+ DB_PASSWORD: supersecret123
73
+ API_KEY: dev-key-12345
74
+ LOG_LEVEL: debug
46
75
  ```
47
76
 
48
- #### Instantiating Qenv
49
- Create an instance of `Qenv` by providing paths to the directories containing the `qenv.yml` and `env.yml` files, respectively:
77
+ **env.json:**
78
+ ```json
79
+ {
80
+ "DB_HOST": "localhost",
81
+ "DB_USER": "developer",
82
+ "DB_PASSWORD": "supersecret123",
83
+ "API_KEY": "dev-key-12345",
84
+ "LOG_LEVEL": "debug"
85
+ }
86
+ ```
87
+
88
+ > 💡 **Pro Tip:** Add `env.yml` and `env.json` to your `.gitignore` to keep secrets out of version control!
89
+
90
+ ## 🔥 Advanced Usage
91
+
92
+ ### Loading Priority
93
+
94
+ Qenv loads variables in this order (first found wins):
95
+ 1. **Process environment variables** - Already set in `process.env`
96
+ 2. **Configuration files** - From `env.yml` or `env.json`
97
+ 3. **Docker secrets** - From `/run/secrets/`
98
+ 4. **Docker secret JSON** - From `/run/secrets/secret.json`
99
+
100
+ ### Handling Complex Objects
101
+
102
+ Store and retrieve complex configuration objects:
50
103
 
51
104
  ```typescript
52
- const myQenv = new Qenv('./path/to/dir/with/qenv', './path/to/dir/with/env');
105
+ // In env.yml
106
+ const config = {
107
+ database: {
108
+ host: 'localhost',
109
+ port: 5432,
110
+ options: {
111
+ ssl: true,
112
+ poolSize: 10
113
+ }
114
+ }
115
+ };
116
+
117
+ // Qenv automatically handles base64 encoding
118
+ const dbConfig = await qenv.getEnvVarOnDemandAsObject('DATABASE_CONFIG');
119
+ console.log(dbConfig.database.options.poolSize); // 10
53
120
  ```
54
121
 
55
- If the `env.yml` file is in the same directory as `qenv.yml`, you can omit the second argument:
122
+ ### Dynamic Environment Variables
123
+
124
+ Load variables from external sources dynamically:
56
125
 
57
126
  ```typescript
58
- const myQenv = new Qenv('./path/to/dir/with/both');
127
+ const qenv = new Qenv();
128
+
129
+ // Define an async function to fetch configuration
130
+ const fetchFromVault = async () => {
131
+ const response = await fetch('https://vault.example.com/api/secret');
132
+ const data = await response.json();
133
+ return data.secret;
134
+ };
135
+
136
+ // Use the function as an environment variable source
137
+ const secret = await qenv.getEnvVarOnDemand(fetchFromVault);
138
+ ```
139
+
140
+ ### Working with Docker
141
+
142
+ Qenv seamlessly integrates with Docker secrets:
143
+
144
+ ```dockerfile
145
+ # docker-compose.yml
146
+ version: '3.7'
147
+ services:
148
+ app:
149
+ image: your-app
150
+ secrets:
151
+ - db_password
152
+ - api_key
153
+
154
+ secrets:
155
+ db_password:
156
+ external: true
157
+ api_key:
158
+ external: true
59
159
  ```
60
160
 
61
- #### Accessing Environment Variables
62
- After instantiating `Qenv`, you can access the loaded environment variables directly from `process.env` in Node.js or through the `myQenv` instance for more complex scenarios like asynchronous variable resolution:
161
+ Your application automatically reads from `/run/secrets/`:
63
162
 
64
163
  ```typescript
65
- // Accessing directly via process.env
66
- console.log(process.env.DB_HOST); // 'localhost' in development environment
164
+ const qenv = new Qenv();
165
+ // Automatically loads from /run/secrets/db_password
166
+ const dbPassword = await qenv.getEnvVarOnDemand('db_password');
167
+ ```
67
168
 
68
- // Accessing via Qenv instance for more advanced scenarios
69
- (async () => {
70
- const dbHost = await myQenv.getEnvVarOnDemand('DB_HOST');
71
- console.log(dbHost); // 'localhost'
72
- })();
169
+ ### Handling Missing Variables
170
+
171
+ Control how your application handles missing environment variables:
172
+
173
+ ```typescript
174
+ // Fail fast (default behavior)
175
+ const qenvStrict = new Qenv('./', './', true);
176
+ // Application exits if required variables are missing
177
+
178
+ // Graceful handling
179
+ const qenvRelaxed = new Qenv('./', './', false);
180
+ // Application continues, you handle missing variables
181
+
182
+ // Check what's missing
183
+ if (qenvRelaxed.missingEnvVars.length > 0) {
184
+ console.warn('Missing variables:', qenvRelaxed.missingEnvVars);
185
+ // Implement fallback logic
186
+ }
73
187
  ```
74
188
 
75
- ### Advanced Usage
76
- #### Handling Missing Variables
77
- By default, `Qenv` will throw an error and exit if any of the required environment variables specified in `qenv.yml` are missing. You can disable this behavior by passing `false` as the third argument to the constructor, which allows your application to handle missing variables gracefully:
189
+ ### Strict Mode for Critical Variables
190
+
191
+ Use the new strict getter when you absolutely need a variable:
78
192
 
79
193
  ```typescript
80
- const myQenv = new Qenv('./path/to/dir/with/qenv', './path/to/dir/with/env', false);
194
+ try {
195
+ // This will throw if TOKEN is not set
196
+ const token = await qenv.getEnvVarOnDemandStrict('TOKEN');
197
+
198
+ // You can also check multiple fallback names
199
+ const db = await qenv.getEnvVarOnDemandStrict(['DATABASE_URL', 'DB_CONNECTION']);
200
+ } catch (error) {
201
+ console.error('Critical configuration missing:', error.message);
202
+ process.exit(1);
203
+ }
81
204
  ```
82
205
 
83
- #### Dynamic Environment Variables
84
- For dynamic or computed environment variables, you can define functions that resolve these variables asynchronously. This is particularly useful for variables that require fetching from an external source:
206
+ ## 🏗️ CI/CD Integration
207
+
208
+ ### GitHub Actions
209
+
210
+ ```yaml
211
+ name: Deploy
212
+ on: [push]
213
+ jobs:
214
+ deploy:
215
+ runs-on: ubuntu-latest
216
+ steps:
217
+ - uses: actions/checkout@v2
218
+ - name: Deploy with secrets
219
+ env:
220
+ API_KEY: ${{ secrets.API_KEY }}
221
+ DB_PASSWORD: ${{ secrets.DB_PASSWORD }}
222
+ run: |
223
+ npm install
224
+ npm run deploy
225
+ ```
226
+
227
+ ### GitLab CI
228
+
229
+ ```yaml
230
+ deploy:
231
+ stage: deploy
232
+ script:
233
+ - npm install
234
+ - npm run deploy
235
+ variables:
236
+ API_KEY: $CI_API_KEY
237
+ DB_PASSWORD: $CI_DB_PASSWORD
238
+ ```
239
+
240
+ ## 🎭 Testing
241
+
242
+ For testing, create a separate `test/assets/env.yml`:
85
243
 
86
244
  ```typescript
87
- // Define a function to fetch a variable
88
- const fetchDbHost = async () => {
89
- // Logic to fetch DB_HOST from an external service
90
- return 'dynamic.host';
91
- };
245
+ import { Qenv } from '@push.rocks/qenv';
92
246
 
93
- // Use the function with getEnvVarOnDemand
94
- (async () => {
95
- const dbHost = await myQenv.getEnvVarOnDemand(fetchDbHost);
96
- console.log(dbHost); // 'dynamic.host'
97
- })();
247
+ describe('MyApp', () => {
248
+ let qenv: Qenv;
249
+
250
+ beforeEach(() => {
251
+ qenv = new Qenv('./test/assets', './test/assets', false);
252
+ });
253
+
254
+ it('should load test configuration', async () => {
255
+ const testVar = await qenv.getEnvVarOnDemand('TEST_VAR');
256
+ expect(testVar).toBe('test-value');
257
+ });
258
+ });
98
259
  ```
99
260
 
100
- #### Reading Variables from Docker Secrets or Other Sources
101
- Internally, `@push.rocks/qenv` supports reading from Docker secrets, providing flexibility for applications deployed in Docker environments. The module attempts to read each required variable from the process environment, a provided `env.yml` file, Docker secrets, or any custom source you integrate.
261
+ ## 🔍 Debugging
262
+
263
+ Enable detailed logging to troubleshoot environment variable loading:
264
+
265
+ ```typescript
266
+ const qenv = new Qenv();
267
+
268
+ // Check what's loaded
269
+ console.log('Required vars:', qenv.requiredEnvVars);
270
+ console.log('Available vars:', qenv.availableEnvVars);
271
+ console.log('Missing vars:', qenv.missingEnvVars);
272
+
273
+ // Access the logger
274
+ qenv.logger.log('info', 'Custom log message');
275
+ ```
276
+
277
+ ## 📊 Real-World Example
278
+
279
+ Here's how you might use qenv in a production Node.js application:
280
+
281
+ ```typescript
282
+ import { Qenv } from '@push.rocks/qenv';
283
+ import { createServer } from './server';
284
+ import { connectDatabase } from './database';
285
+
286
+ async function bootstrap() {
287
+ // Initialize environment
288
+ const qenv = new Qenv();
289
+
290
+ // Load critical configuration
291
+ const config = {
292
+ port: await qenv.getEnvVarOnDemand('PORT') || '3000',
293
+ dbUrl: await qenv.getEnvVarOnDemandStrict('DATABASE_URL'),
294
+ apiKey: await qenv.getEnvVarOnDemandStrict('API_KEY'),
295
+ logLevel: await qenv.getEnvVarOnDemand('LOG_LEVEL') || 'info',
296
+ features: await qenv.getEnvVarOnDemandAsObject('FEATURE_FLAGS')
297
+ };
298
+
299
+ // Connect to database
300
+ await connectDatabase(config.dbUrl);
301
+
302
+ // Start server
303
+ const server = createServer(config);
304
+ server.listen(config.port, () => {
305
+ console.log(`🚀 Server running on port ${config.port}`);
306
+ });
307
+ }
308
+
309
+ bootstrap().catch(error => {
310
+ console.error('Failed to start application:', error);
311
+ process.exit(1);
312
+ });
313
+ ```
314
+
315
+ ## 🤝 API Reference
316
+
317
+ ### Class: `Qenv`
318
+
319
+ #### Constructor
320
+ ```typescript
321
+ new Qenv(
322
+ qenvFileBasePathArg?: string, // Path to qenv.yml (default: process.cwd())
323
+ envFileBasePathArg?: string, // Path to env.yml/json (default: same as qenv)
324
+ failOnMissing?: boolean // Exit on missing vars (default: true)
325
+ )
326
+ ```
327
+
328
+ #### Methods
329
+
330
+ | Method | Description | Returns |
331
+ |--------|-------------|---------|
332
+ | `getEnvVarOnDemand(name)` | Get environment variable value | `Promise<string \| undefined>` |
333
+ | `getEnvVarOnDemandStrict(name)` | Get variable or throw error | `Promise<string>` |
334
+ | `getEnvVarOnDemandSync(name)` | Synchronously get variable | `string \| undefined` |
335
+ | `getEnvVarOnDemandAsObject(name)` | Get variable as decoded object | `Promise<any>` |
102
336
 
103
- ### Conclusion
104
- `@push.rocks/qenv` simplifies handling environment variables across different environments, making your application's configuration more manageable and secure. By separating variable definitions from their values and providing support for dynamic resolution, `@push.rocks/qenv` offers a robust solution for managing configuration in Node.js projects. Whether you're working in a local development environment, CI/CD pipelines, or production, `@push.rocks/qenv` ensures that you have the correct configuration for the task at hand.
337
+ #### Properties
105
338
 
106
- Note: Due to the complexity and depth of `@push.rocks/qenv`, this documentation aims to cover general and advanced usage comprehensively. Please refer to the module's official documentation and typed definitions for further details on specific features or configuration options.
339
+ | Property | Type | Description |
340
+ |----------|------|-------------|
341
+ | `requiredEnvVars` | `string[]` | List of required variable names |
342
+ | `availableEnvVars` | `string[]` | List of found variable names |
343
+ | `missingEnvVars` | `string[]` | List of missing variable names |
344
+ | `keyValueObject` | `object` | All loaded variables as key-value pairs |
107
345
 
108
346
  ## License and Legal Information
109
347
 
@@ -122,4 +360,4 @@ Registered at District court Bremen HRB 35230 HB, Germany
122
360
 
123
361
  For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
124
362
 
125
- By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
363
+ By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@push.rocks/qenv',
6
- version: '6.1.0',
6
+ version: '6.1.1',
7
7
  description: 'A module for easily handling environment variables in Node.js projects with support for .yml and .json configuration.'
8
8
  }