@adonisjs/env 7.0.0-next.2 → 7.0.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/build/index.js CHANGED
@@ -1,500 +1,234 @@
1
- import {
2
- EnvLoader,
3
- __export,
4
- debug_default
5
- } from "./chunk-KE5AFOK2.js";
6
-
7
- // src/parser.ts
8
- import { readFile } from "fs/promises";
9
- import dotenv from "dotenv";
10
- import { RuntimeException } from "@poppinss/utils/exception";
11
-
12
- // src/errors.ts
13
- var errors_exports = {};
14
- __export(errors_exports, {
15
- E_IDENTIFIER_ALREADY_DEFINED: () => E_IDENTIFIER_ALREADY_DEFINED,
16
- E_INVALID_ENV_VARIABLES: () => E_INVALID_ENV_VARIABLES
1
+ import { n as debug_default, t as EnvLoader } from "./loader-KsjAiZ3e.js";
2
+ import "node:module";
3
+ import { parseEnv } from "node:util";
4
+ import { readFile } from "node:fs/promises";
5
+ import { Exception, RuntimeException, createError } from "@poppinss/utils/exception";
6
+ import { Secret } from "@poppinss/utils";
7
+ import { schema } from "@poppinss/validator-lite";
8
+ var __defProp = Object.defineProperty;
9
+ var __exportAll = (all, no_symbols) => {
10
+ let target = {};
11
+ for (var name in all) __defProp(target, name, {
12
+ get: all[name],
13
+ enumerable: true
14
+ });
15
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
+ return target;
17
+ };
18
+ var errors_exports = /* @__PURE__ */ __exportAll({
19
+ E_IDENTIFIER_ALREADY_DEFINED: () => E_IDENTIFIER_ALREADY_DEFINED,
20
+ E_INVALID_ENV_VARIABLES: () => E_INVALID_ENV_VARIABLES
17
21
  });
18
- import { createError, Exception } from "@poppinss/utils/exception";
19
- var E_INVALID_ENV_VARIABLES = class EnvValidationException extends Exception {
20
- static message = "Validation failed for one or more environment variables";
21
- static code = "E_INVALID_ENV_VARIABLES";
22
- help = "";
22
+ const E_INVALID_ENV_VARIABLES = class EnvValidationException extends Exception {
23
+ static message = "Validation failed for one or more environment variables";
24
+ static code = "E_INVALID_ENV_VARIABLES";
25
+ help = "";
23
26
  };
24
- var E_IDENTIFIER_ALREADY_DEFINED = createError(
25
- 'The identifier "%s" is already defined',
26
- "E_IDENTIFIER_ALREADY_DEFINED",
27
- 500
28
- );
29
-
30
- // src/parser.ts
31
- var EnvParser = class _EnvParser {
32
- /**
33
- * Raw environment file contents
34
- */
35
- #envContents;
36
- /**
37
- * Application root directory URL
38
- */
39
- #appRoot;
40
- /**
41
- * Whether to prefer process.env values over parsed values
42
- */
43
- #preferProcessEnv = true;
44
- /**
45
- * Static collection of registered identifiers with their callbacks
46
- */
47
- static #identifiers = {
48
- async file(value, key, appRoot) {
49
- const filePath = new URL(value, appRoot);
50
- try {
51
- const contents = await readFile(filePath, "utf-8");
52
- return contents;
53
- } catch (error) {
54
- if (error.code === "ENOENT") {
55
- throw new RuntimeException(
56
- `Cannot process "${key}" env variable. Unable to locate file "${filePath}"`,
57
- {
58
- cause: error
59
- }
60
- );
61
- }
62
- throw error;
63
- }
64
- }
65
- };
66
- /**
67
- * Creates a new EnvParser instance
68
- *
69
- * @param envContents - Raw environment file contents
70
- * @param appRoot - Application root directory URL
71
- * @param options - Parser options
72
- */
73
- constructor(envContents, appRoot, options) {
74
- if (options?.ignoreProcessEnv) {
75
- this.#preferProcessEnv = false;
76
- }
77
- this.#envContents = envContents;
78
- this.#appRoot = appRoot;
79
- }
80
- /**
81
- * Define an identifier for any environment value. The callback is invoked
82
- * when the value match the identifier to modify its interpolation.
83
- *
84
- * @deprecated use `EnvParser.defineIdentifier` instead
85
- */
86
- /**
87
- * Define an identifier for any environment value. The callback is invoked
88
- * when the value match the identifier to modify its interpolation.
89
- *
90
- * @deprecated use `EnvParser.defineIdentifier` instead
91
- * @param name - The identifier name
92
- * @param callback - Callback function to process the identifier value
93
- */
94
- static identifier(name, callback) {
95
- _EnvParser.defineIdentifier(name, callback);
96
- }
97
- /**
98
- * Define an identifier for any environment value. The callback is invoked
99
- * when the value match the identifier to modify its interpolation.
100
- *
101
- * @param name - The identifier name
102
- * @param callback - Callback function to process the identifier value
103
- */
104
- static defineIdentifier(name, callback) {
105
- if (this.#identifiers[name]) {
106
- throw new E_IDENTIFIER_ALREADY_DEFINED([name]);
107
- }
108
- this.#identifiers[name] = callback;
109
- }
110
- /**
111
- * Define an identifier for any environment value, if it's not already defined.
112
- * The callback is invoked when the value match the identifier to modify its
113
- * interpolation.
114
- *
115
- * @param name - The identifier name
116
- * @param callback - Callback function to process the identifier value
117
- */
118
- static defineIdentifierIfMissing(name, callback) {
119
- if (typeof this.#identifiers[name] === "undefined") {
120
- this.#identifiers[name] = callback;
121
- }
122
- }
123
- /**
124
- * Remove an identifier
125
- *
126
- * @param name - The identifier name to remove
127
- */
128
- static removeIdentifier(name) {
129
- delete this.#identifiers[name];
130
- }
131
- /**
132
- * Returns the value from the parsed object
133
- *
134
- * @param key - The environment variable key
135
- * @param parsed - Parsed environment variables object
136
- * @returns The resolved environment variable value
137
- */
138
- #getValue(key, parsed) {
139
- if (this.#preferProcessEnv && process.env[key]) {
140
- return process.env[key];
141
- }
142
- if (parsed[key]) {
143
- return this.#interpolate(parsed[key], parsed);
144
- }
145
- return process.env[key] || "";
146
- }
147
- /**
148
- * Interpolating the token wrapped inside the mustache braces.
149
- *
150
- * @param token - The token to interpolate
151
- * @param parsed - Parsed environment variables object
152
- * @returns Interpolated value
153
- */
154
- #interpolateMustache(token, parsed) {
155
- const closingBrace = token.indexOf("}");
156
- if (closingBrace === -1) {
157
- return token;
158
- }
159
- const varReference = token.slice(1, closingBrace).trim();
160
- return `${this.#getValue(varReference, parsed)}${token.slice(closingBrace + 1)}`;
161
- }
162
- /**
163
- * Interpolating the variable reference starting with a
164
- * `$`. We only capture numbers,letter and underscore.
165
- * For other characters, one can use the mustache
166
- * braces.
167
- *
168
- * @param token - The token to interpolate
169
- * @param parsed - Parsed environment variables object
170
- * @returns Interpolated value
171
- */
172
- #interpolateVariable(token, parsed) {
173
- return token.replace(/[a-zA-Z0-9_]+/, (key) => {
174
- return this.#getValue(key, parsed);
175
- });
176
- }
177
- /**
178
- * Interpolates the referenced values
179
- *
180
- * @param value - The value to interpolate
181
- * @param parsed - Parsed environment variables object
182
- * @returns Interpolated value
183
- */
184
- #interpolate(value, parsed) {
185
- const tokens = value.split("$");
186
- let newValue = "";
187
- let skipNextToken = true;
188
- tokens.forEach((token) => {
189
- if (token === "\\") {
190
- newValue += "$";
191
- skipNextToken = true;
192
- return;
193
- }
194
- if (skipNextToken) {
195
- newValue += token.replace(/\\$/, "$");
196
- if (token.endsWith("\\")) {
197
- return;
198
- }
199
- } else {
200
- if (token.startsWith("{")) {
201
- newValue += this.#interpolateMustache(token, parsed);
202
- return;
203
- }
204
- newValue += this.#interpolateVariable(token, parsed);
205
- }
206
- skipNextToken = false;
207
- });
208
- return newValue;
209
- }
210
- /**
211
- * Parse the env string to an object of environment variables.
212
- *
213
- * @returns Promise resolving to parsed environment variables
214
- */
215
- async parse() {
216
- const envCollection = dotenv.parse(this.#envContents.trim());
217
- const identifiers = Object.keys(_EnvParser.#identifiers);
218
- let result = {};
219
- $keyLoop: for (const key in envCollection) {
220
- const value = this.#getValue(key, envCollection);
221
- if (value.includes(":")) {
222
- for (const identifier of identifiers) {
223
- if (value.startsWith(`${identifier}:`)) {
224
- result[key] = await _EnvParser.#identifiers[identifier](
225
- value.substring(identifier.length + 1),
226
- key,
227
- this.#appRoot
228
- );
229
- continue $keyLoop;
230
- }
231
- if (value.startsWith(`${identifier}\\:`)) {
232
- result[key] = identifier + value.substring(identifier.length + 1);
233
- continue $keyLoop;
234
- }
235
- }
236
- result[key] = value;
237
- } else {
238
- result[key] = value;
239
- }
240
- }
241
- return result;
242
- }
27
+ const E_IDENTIFIER_ALREADY_DEFINED = createError("The identifier \"%s\" is already defined", "E_IDENTIFIER_ALREADY_DEFINED", 500);
28
+ var EnvParser = class EnvParser {
29
+ #envContents;
30
+ #appRoot;
31
+ #preferProcessEnv = true;
32
+ static #identifiers = { async file(value, key, appRoot) {
33
+ const filePath = new URL(value, appRoot);
34
+ try {
35
+ return await readFile(filePath, "utf-8");
36
+ } catch (error) {
37
+ if (error.code === "ENOENT") throw new RuntimeException(`Cannot process "${key}" env variable. Unable to locate file "${filePath}"`, { cause: error });
38
+ throw error;
39
+ }
40
+ } };
41
+ constructor(envContents, appRoot, options) {
42
+ if (options?.ignoreProcessEnv) this.#preferProcessEnv = false;
43
+ this.#envContents = envContents;
44
+ this.#appRoot = appRoot;
45
+ }
46
+ static identifier(name, callback) {
47
+ EnvParser.defineIdentifier(name, callback);
48
+ }
49
+ static defineIdentifier(name, callback) {
50
+ if (this.#identifiers[name]) throw new E_IDENTIFIER_ALREADY_DEFINED([name]);
51
+ this.#identifiers[name] = callback;
52
+ }
53
+ static defineIdentifierIfMissing(name, callback) {
54
+ if (typeof this.#identifiers[name] === "undefined") this.#identifiers[name] = callback;
55
+ }
56
+ static removeIdentifier(name) {
57
+ delete this.#identifiers[name];
58
+ }
59
+ #getValue(key, parsed) {
60
+ if (this.#preferProcessEnv && process.env[key]) return process.env[key];
61
+ if (parsed[key]) return this.#interpolate(parsed[key], parsed);
62
+ return process.env[key] || "";
63
+ }
64
+ #interpolateMustache(token, parsed) {
65
+ const closingBrace = token.indexOf("}");
66
+ if (closingBrace === -1) return token;
67
+ const varReference = token.slice(1, closingBrace).trim();
68
+ return `${this.#getValue(varReference, parsed)}${token.slice(closingBrace + 1)}`;
69
+ }
70
+ #interpolateVariable(token, parsed) {
71
+ return token.replace(/[a-zA-Z0-9_]+/, (key) => {
72
+ return this.#getValue(key, parsed);
73
+ });
74
+ }
75
+ #interpolate(value, parsed) {
76
+ const tokens = value.split("$");
77
+ let newValue = "";
78
+ let skipNextToken = true;
79
+ tokens.forEach((token) => {
80
+ if (token === "\\") {
81
+ newValue += "$";
82
+ skipNextToken = true;
83
+ return;
84
+ }
85
+ if (skipNextToken) {
86
+ newValue += token.replace(/\\$/, "$");
87
+ if (token.endsWith("\\")) return;
88
+ } else {
89
+ if (token.startsWith("{")) {
90
+ newValue += this.#interpolateMustache(token, parsed);
91
+ return;
92
+ }
93
+ newValue += this.#interpolateVariable(token, parsed);
94
+ }
95
+ skipNextToken = false;
96
+ });
97
+ return newValue;
98
+ }
99
+ async parse() {
100
+ const envCollection = parseEnv(this.#envContents.trim());
101
+ const identifiers = Object.keys(EnvParser.#identifiers);
102
+ let result = {};
103
+ $keyLoop: for (const key in envCollection) {
104
+ const value = this.#getValue(key, envCollection);
105
+ if (value.includes(":")) {
106
+ for (const identifier of identifiers) {
107
+ if (value.startsWith(`${identifier}:`)) {
108
+ result[key] = await EnvParser.#identifiers[identifier](value.substring(identifier.length + 1), key, this.#appRoot);
109
+ continue $keyLoop;
110
+ }
111
+ if (value.startsWith(`${identifier}\\:`)) {
112
+ result[key] = identifier + value.substring(identifier.length + 1);
113
+ continue $keyLoop;
114
+ }
115
+ }
116
+ result[key] = value;
117
+ } else result[key] = value;
118
+ }
119
+ return result;
120
+ }
243
121
  };
244
-
245
- // src/validator.ts
246
122
  var EnvValidator = class {
247
- /**
248
- * The validation schema for environment variables
249
- */
250
- #schema;
251
- /**
252
- * The error instance for validation failures
253
- */
254
- #error;
255
- /**
256
- * Creates a new EnvValidator instance
257
- *
258
- * @param schema - The validation schema object
259
- */
260
- constructor(schema2) {
261
- this.#schema = schema2;
262
- this.#error = new E_INVALID_ENV_VARIABLES();
263
- }
264
- /**
265
- * Accepts an object of values to validate against the pre-defined
266
- * schema.
267
- *
268
- * The return value is a merged copy of the original object and the
269
- * values mutated by the schema validator.
270
- *
271
- * @param values - Object of environment variable values to validate
272
- * @returns Validated and transformed environment variables
273
- */
274
- validate(values) {
275
- const help = [];
276
- const validated = Object.keys(this.#schema).reduce(
277
- (result, key) => {
278
- const value = process.env[key] || values[key];
279
- try {
280
- result[key] = this.#schema[key](key, value);
281
- } catch (error) {
282
- help.push(`- ${error.message}`);
283
- }
284
- return result;
285
- },
286
- { ...values }
287
- );
288
- if (help.length) {
289
- this.#error.help = help.join("\n");
290
- throw this.#error;
291
- }
292
- return validated;
293
- }
123
+ #schema;
124
+ #error;
125
+ constructor(schema) {
126
+ this.#schema = schema;
127
+ this.#error = new E_INVALID_ENV_VARIABLES();
128
+ }
129
+ validate(values) {
130
+ const help = [];
131
+ const validated = Object.keys(this.#schema).reduce((result, key) => {
132
+ const value = process.env[key] || values[key];
133
+ try {
134
+ result[key] = this.#schema[key](key, value);
135
+ } catch (error) {
136
+ help.push(`- ${error.message}`);
137
+ }
138
+ return result;
139
+ }, { ...values });
140
+ if (help.length) {
141
+ this.#error.help = help.join("\n");
142
+ throw this.#error;
143
+ }
144
+ return validated;
145
+ }
294
146
  };
295
-
296
- // src/processor.ts
297
147
  var EnvProcessor = class {
298
- /**
299
- * App root is needed to load files
300
- */
301
- #appRoot;
302
- /**
303
- * Creates a new EnvProcessor instance
304
- *
305
- * @param appRoot - The application root directory URL
306
- */
307
- constructor(appRoot) {
308
- this.#appRoot = appRoot;
309
- }
310
- /**
311
- * Parse env variables from raw contents
312
- *
313
- * @param envContents - Raw environment file contents
314
- * @param store - Store object to collect parsed variables
315
- * @returns Updated store with parsed variables
316
- */
317
- async #processContents(envContents, store) {
318
- if (!envContents.trim()) {
319
- return store;
320
- }
321
- const parser = new EnvParser(envContents, this.#appRoot);
322
- const values = await parser.parse();
323
- Object.keys(values).forEach((key) => {
324
- let value = process.env[key];
325
- if (!value) {
326
- value = values[key];
327
- process.env[key] = values[key];
328
- }
329
- if (!store[key]) {
330
- store[key] = value;
331
- }
332
- });
333
- return store;
334
- }
335
- /**
336
- * Parse env variables by loading dot files.
337
- *
338
- * @returns Promise resolving to collected environment variables
339
- */
340
- async #loadAndProcessDotFiles() {
341
- const loader = new EnvLoader(this.#appRoot);
342
- const envFiles = await loader.load();
343
- if (debug_default.enabled) {
344
- debug_default(
345
- "processing .env files (priority from top to bottom) %O",
346
- envFiles.map((file) => file.path)
347
- );
348
- }
349
- const envValues = {};
350
- await Promise.all(envFiles.map(({ contents }) => this.#processContents(contents, envValues)));
351
- return envValues;
352
- }
353
- /**
354
- * Process env variables
355
- *
356
- * @returns Promise resolving to processed environment variables
357
- */
358
- async process() {
359
- return this.#loadAndProcessDotFiles();
360
- }
148
+ #appRoot;
149
+ constructor(appRoot) {
150
+ this.#appRoot = appRoot;
151
+ }
152
+ async #processContents(envContents, store) {
153
+ if (!envContents.trim()) return store;
154
+ const values = await new EnvParser(envContents, this.#appRoot).parse();
155
+ Object.keys(values).forEach((key) => {
156
+ let value = process.env[key];
157
+ if (value === void 0) {
158
+ value = values[key];
159
+ process.env[key] = values[key];
160
+ }
161
+ if (key in store === false) store[key] = value;
162
+ });
163
+ return store;
164
+ }
165
+ async #loadAndProcessDotFiles() {
166
+ const envFiles = await new EnvLoader(this.#appRoot).load();
167
+ if (debug_default.enabled) debug_default("processing .env files (priority from top to bottom) %O", envFiles.map((file) => file.path));
168
+ const envValues = {};
169
+ await Promise.all(envFiles.map(({ contents }) => this.#processContents(contents, envValues)));
170
+ return envValues;
171
+ }
172
+ async process() {
173
+ return this.#loadAndProcessDotFiles();
174
+ }
361
175
  };
362
-
363
- // src/schema.ts
364
- import { Secret } from "@poppinss/utils";
365
- import { schema as envSchema } from "@poppinss/validator-lite";
366
176
  function secret(options) {
367
- return function validate(key, value) {
368
- if (!value) {
369
- throw new Error(options?.message ?? `Missing environment variable "${key}"`);
370
- }
371
- return new Secret(value);
372
- };
177
+ return function validate(key, value) {
178
+ if (!value) throw new Error(options?.message ?? `Missing environment variable "${key}"`);
179
+ return new Secret(value);
180
+ };
373
181
  }
374
182
  secret.optional = function optionalString() {
375
- return function validate(_, value) {
376
- if (!value) {
377
- return void 0;
378
- }
379
- return new Secret(value);
380
- };
183
+ return function validate(_, value) {
184
+ if (!value) return;
185
+ return new Secret(value);
186
+ };
381
187
  };
382
188
  secret.optionalWhen = function optionalWhenString(condition, options) {
383
- return function validate(key, value) {
384
- if (typeof condition === "function" ? condition(key, value) : condition) {
385
- return secret.optional()(key, value);
386
- }
387
- return secret(options)(key, value);
388
- };
389
- };
390
- var schema = {
391
- ...envSchema,
392
- secret
189
+ return function validate(key, value) {
190
+ if (typeof condition === "function" ? condition(key, value) : condition) return secret.optional()(key, value);
191
+ return secret(options)(key, value);
192
+ };
393
193
  };
394
-
395
- // src/env.ts
396
- var Env = class _Env {
397
- /**
398
- * A cache of env values
399
- */
400
- #values;
401
- /**
402
- * Creates a new Env instance
403
- *
404
- * @param values - Validated environment values
405
- */
406
- constructor(values) {
407
- this.#values = values;
408
- }
409
- /**
410
- * Create an instance of the env class by validating the
411
- * environment variables. Also, the `.env` files are
412
- * loaded from the appRoot
413
- *
414
- * @param appRoot - The application root directory URL
415
- * @param schema - Validation schema for environment variables
416
- * @returns Promise resolving to an Env instance with validated values
417
- */
418
- static async create(appRoot, schema2) {
419
- const values = await new EnvProcessor(appRoot).process();
420
- const validator = this.rules(schema2);
421
- return new _Env(validator.validate(values));
422
- }
423
- /**
424
- * Define an identifier for any environment value. The callback is invoked
425
- * when the value match the identifier to modify its interpolation.
426
- *
427
- * @deprecated use `Env.defineIdentifier` instead
428
- * @param name - The identifier name
429
- * @param callback - Callback function to process the identifier value
430
- */
431
- static identifier(name, callback) {
432
- return EnvParser.defineIdentifier(name, callback);
433
- }
434
- /**
435
- * Define an identifier for any environment value. The callback is invoked
436
- * when the value match the identifier to modify its interpolation.
437
- *
438
- * @param name - The identifier name
439
- * @param callback - Callback function to process the identifier value
440
- */
441
- static defineIdentifier(name, callback) {
442
- EnvParser.defineIdentifier(name, callback);
443
- }
444
- /**
445
- * Define an identifier for any environment value, if it's not already defined.
446
- * The callback is invoked when the value match the identifier to modify its
447
- * interpolation.
448
- *
449
- * @param name - The identifier name
450
- * @param callback - Callback function to process the identifier value
451
- */
452
- static defineIdentifierIfMissing(name, callback) {
453
- EnvParser.defineIdentifierIfMissing(name, callback);
454
- }
455
- /**
456
- * Remove an identifier
457
- *
458
- * @param name - The identifier name to remove
459
- */
460
- static removeIdentifier(name) {
461
- EnvParser.removeIdentifier(name);
462
- }
463
- /**
464
- * The schema builder for defining validation rules
465
- */
466
- static schema = schema;
467
- /**
468
- * Define the validation rules for validating environment
469
- * variables. The return value is an instance of the
470
- * env validator
471
- *
472
- * @param schema - Validation schema object
473
- * @returns EnvValidator instance
474
- */
475
- static rules(schema2) {
476
- const validator = new EnvValidator(schema2);
477
- return validator;
478
- }
479
- get(key, defaultValue) {
480
- if (this.#values[key] !== void 0) {
481
- return this.#values[key];
482
- }
483
- const envValue = process.env[key];
484
- if (envValue) {
485
- return envValue;
486
- }
487
- return defaultValue;
488
- }
489
- set(key, value) {
490
- this.#values[key] = value;
491
- process.env[key] = value;
492
- }
194
+ const schema$1 = {
195
+ ...schema,
196
+ secret
493
197
  };
494
- export {
495
- Env,
496
- EnvLoader,
497
- EnvParser,
498
- EnvProcessor,
499
- errors_exports as errors
198
+ var Env = class Env {
199
+ #values;
200
+ constructor(values) {
201
+ this.#values = values;
202
+ }
203
+ static async create(appRoot, schema) {
204
+ const values = await new EnvProcessor(appRoot).process();
205
+ return new Env(this.rules(schema).validate(values));
206
+ }
207
+ static identifier(name, callback) {
208
+ return EnvParser.defineIdentifier(name, callback);
209
+ }
210
+ static defineIdentifier(name, callback) {
211
+ EnvParser.defineIdentifier(name, callback);
212
+ }
213
+ static defineIdentifierIfMissing(name, callback) {
214
+ EnvParser.defineIdentifierIfMissing(name, callback);
215
+ }
216
+ static removeIdentifier(name) {
217
+ EnvParser.removeIdentifier(name);
218
+ }
219
+ static schema = schema$1;
220
+ static rules(schema) {
221
+ return new EnvValidator(schema);
222
+ }
223
+ get(key, defaultValue) {
224
+ if (this.#values[key] !== void 0) return this.#values[key];
225
+ const envValue = process.env[key];
226
+ if (envValue) return envValue;
227
+ return defaultValue;
228
+ }
229
+ set(key, value) {
230
+ this.#values[key] = value;
231
+ process.env[key] = value;
232
+ }
500
233
  };
234
+ export { Env, EnvLoader, EnvParser, EnvProcessor, errors_exports as errors };
@@ -0,0 +1,74 @@
1
+ import { debuglog } from "node:util";
2
+ import { readFile } from "node:fs/promises";
3
+ import { fileURLToPath } from "node:url";
4
+ import { isAbsolute, join } from "node:path";
5
+ var debug_default = debuglog("adonisjs:env");
6
+ var EnvLoader = class {
7
+ #appRoot;
8
+ #loadExampleFile;
9
+ constructor(appRoot, loadExampleFile = false) {
10
+ this.#appRoot = typeof appRoot === "string" ? appRoot : fileURLToPath(appRoot);
11
+ this.#loadExampleFile = loadExampleFile;
12
+ }
13
+ async #loadFile(filePath) {
14
+ try {
15
+ return {
16
+ contents: await readFile(filePath, "utf-8"),
17
+ fileExists: true
18
+ };
19
+ } catch (error) {
20
+ /* c8 ignore next 3 */
21
+ if (error.code !== "ENOENT") throw error;
22
+ return {
23
+ contents: "",
24
+ fileExists: false
25
+ };
26
+ }
27
+ }
28
+ async load() {
29
+ const ENV_PATH = process.env.ENV_PATH;
30
+ const NODE_ENV = process.env.NODE_ENV;
31
+ const envFiles = [];
32
+ if (debug_default.enabled) {
33
+ debug_default("ENV_PATH variable is %s", ENV_PATH ? "set" : "not set");
34
+ debug_default("NODE_ENV variable is %s", NODE_ENV ? "set" : "not set");
35
+ }
36
+ const baseEnvPath = ENV_PATH ? isAbsolute(ENV_PATH) ? ENV_PATH : join(this.#appRoot, ENV_PATH) : this.#appRoot;
37
+ if (debug_default.enabled) debug_default("dot-env files base path \"%s\"", baseEnvPath);
38
+ if (NODE_ENV) {
39
+ const nodeEnvLocalFile = join(baseEnvPath, `.env.${NODE_ENV}.local`);
40
+ envFiles.push({
41
+ path: nodeEnvLocalFile,
42
+ ...await this.#loadFile(nodeEnvLocalFile)
43
+ });
44
+ }
45
+ if (!NODE_ENV || !["test", "testing"].includes(NODE_ENV)) {
46
+ const envLocalFile = join(baseEnvPath, ".env.local");
47
+ envFiles.push({
48
+ path: envLocalFile,
49
+ ...await this.#loadFile(envLocalFile)
50
+ });
51
+ }
52
+ if (NODE_ENV) {
53
+ const nodeEnvFile = join(baseEnvPath, `.env.${NODE_ENV}`);
54
+ envFiles.push({
55
+ path: nodeEnvFile,
56
+ ...await this.#loadFile(nodeEnvFile)
57
+ });
58
+ }
59
+ const envFile = join(baseEnvPath, ".env");
60
+ envFiles.push({
61
+ path: envFile,
62
+ ...await this.#loadFile(envFile)
63
+ });
64
+ if (this.#loadExampleFile) {
65
+ const envExampleFile = join(baseEnvPath, ".env.example");
66
+ envFiles.push({
67
+ path: envExampleFile,
68
+ ...await this.#loadFile(envExampleFile)
69
+ });
70
+ }
71
+ return envFiles;
72
+ }
73
+ };
74
+ export { debug_default as n, EnvLoader as t };
@@ -1,2 +1,2 @@
1
- declare const _default: import("util").DebugLogger;
1
+ declare const _default: import("node:util").DebugLogger;
2
2
  export default _default;
@@ -1,103 +1,43 @@
1
- import {
2
- EnvLoader
3
- } from "../chunk-KE5AFOK2.js";
4
-
5
- // src/editor.ts
1
+ import { t as EnvLoader } from "../loader-KsjAiZ3e.js";
2
+ import { writeFile } from "node:fs/promises";
6
3
  import splitLines from "split-lines";
7
4
  import lodash from "@poppinss/utils/lodash";
8
- import { writeFile } from "fs/promises";
9
- var EnvEditor = class _EnvEditor {
10
- /**
11
- * The application root directory URL
12
- */
13
- #appRoot;
14
- /**
15
- * Environment file loader instance
16
- */
17
- #loader;
18
- /**
19
- * Array of loaded environment files with their contents and paths
20
- */
21
- #files = [];
22
- /**
23
- * Creates an instance of env editor and loads .env files
24
- * contents.
25
- *
26
- * @param appRoot - The application root directory URL
27
- * @returns Promise resolving to an EnvEditor instance
28
- */
29
- static async create(appRoot) {
30
- const editor = new _EnvEditor(appRoot);
31
- await editor.load();
32
- return editor;
33
- }
34
- /**
35
- * Constructs a new EnvEditor instance
36
- *
37
- * @param appRoot - The application root directory URL
38
- */
39
- constructor(appRoot) {
40
- this.#appRoot = appRoot;
41
- this.#loader = new EnvLoader(this.#appRoot, true);
42
- }
43
- /**
44
- * Loads .env files for editing. Only ".env" and ".env.example"
45
- * files are picked for editing.
46
- *
47
- * @returns Promise that resolves when files are loaded
48
- */
49
- async load() {
50
- const envFiles = await this.#loader.load();
51
- this.#files = envFiles.filter(
52
- (envFile) => envFile.fileExists && (envFile.path.endsWith(".env") || envFile.path.endsWith(".env.example"))
53
- ).map((envFile) => {
54
- return {
55
- contents: splitLines(envFile.contents.trim()),
56
- path: envFile.path
57
- };
58
- });
59
- }
60
- /**
61
- * Add key-value pair to the dot-env files.
62
- * If `withEmptyExampleValue` is true then the key will be added with an empty value
63
- * to the `.env.example` file.
64
- *
65
- * @param key - The environment variable key
66
- * @param value - The environment variable value
67
- * @param withEmptyExampleValue - Whether to add empty value to .env.example file
68
- */
69
- add(key, value, withEmptyExampleValue = false) {
70
- this.#files.forEach((file) => {
71
- let entryIndex = file.contents.findIndex((line) => line.startsWith(`${key}=`));
72
- entryIndex = entryIndex === -1 ? file.contents.length : entryIndex;
73
- if (withEmptyExampleValue && file.path.endsWith(".env.example")) {
74
- lodash.set(file.contents, entryIndex, `${key}=`);
75
- } else {
76
- lodash.set(file.contents, entryIndex, `${key}=${value}`);
77
- }
78
- });
79
- }
80
- /**
81
- * Returns the loaded files as JSON
82
- *
83
- * @returns Array of file objects with contents and paths
84
- */
85
- toJSON() {
86
- return this.#files;
87
- }
88
- /**
89
- * Save changes to the disk
90
- *
91
- * @returns Promise that resolves when files are saved
92
- */
93
- async save() {
94
- await Promise.all(
95
- this.#files.map((file) => {
96
- return writeFile(file.path, file.contents.join("\n"));
97
- })
98
- );
99
- }
100
- };
101
- export {
102
- EnvEditor
5
+ var EnvEditor = class EnvEditor {
6
+ #appRoot;
7
+ #loader;
8
+ #files = [];
9
+ static async create(appRoot) {
10
+ const editor = new EnvEditor(appRoot);
11
+ await editor.load();
12
+ return editor;
13
+ }
14
+ constructor(appRoot) {
15
+ this.#appRoot = appRoot;
16
+ this.#loader = new EnvLoader(this.#appRoot, true);
17
+ }
18
+ async load() {
19
+ this.#files = (await this.#loader.load()).filter((envFile) => envFile.fileExists && (envFile.path.endsWith(".env") || envFile.path.endsWith(".env.example"))).map((envFile) => {
20
+ return {
21
+ contents: splitLines(envFile.contents.trim()),
22
+ path: envFile.path
23
+ };
24
+ });
25
+ }
26
+ add(key, value, withEmptyExampleValue = false) {
27
+ this.#files.forEach((file) => {
28
+ let entryIndex = file.contents.findIndex((line) => line.startsWith(`${key}=`));
29
+ entryIndex = entryIndex === -1 ? file.contents.length : entryIndex;
30
+ if (withEmptyExampleValue && file.path.endsWith(".env.example")) lodash.set(file.contents, entryIndex, `${key}=`);
31
+ else lodash.set(file.contents, entryIndex, `${key}=${value}`);
32
+ });
33
+ }
34
+ toJSON() {
35
+ return this.#files;
36
+ }
37
+ async save() {
38
+ await Promise.all(this.#files.map((file) => {
39
+ return writeFile(file.path, file.contents.join("\n"));
40
+ }));
41
+ }
103
42
  };
43
+ export { EnvEditor };
@@ -1,4 +1,3 @@
1
- import { type DotenvParseOutput } from 'dotenv';
2
1
  /**
3
2
  * Env parser parses the environment variables from a string formatted
4
3
  * as a key-value pair seperated using an `=`. For example:
@@ -94,5 +93,5 @@ export declare class EnvParser {
94
93
  *
95
94
  * @returns Promise resolving to parsed environment variables
96
95
  */
97
- parse(): Promise<DotenvParseOutput>;
96
+ parse(): Promise<NodeJS.Dict<string>>;
98
97
  }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adonisjs/env",
3
- "version": "7.0.0-next.2",
3
+ "version": "7.0.0",
4
4
  "description": "Environment variable manager for Node.js",
5
5
  "main": "build/index.js",
6
6
  "type": "module",
@@ -20,13 +20,13 @@
20
20
  },
21
21
  "scripts": {
22
22
  "pretest": "npm run lint",
23
- "test": "cross-env NODE_DEBUG=adonisjs:env c8 npm run quick:test",
23
+ "test": "cross-env NODE_DEBUG=adonisjs:env npm run quick:test",
24
24
  "lint": "eslint .",
25
25
  "format": "prettier --write .",
26
26
  "typecheck": "tsc --noEmit",
27
27
  "precompile": "npm run lint && npm run clean",
28
28
  "clean": "del-cli build",
29
- "compile": "tsup-node && tsc --emitDeclarationOnly --declaration",
29
+ "compile": "tsdown && tsc --emitDeclarationOnly --declaration",
30
30
  "build": "npm run compile",
31
31
  "release": "release-it",
32
32
  "version": "npm run build",
@@ -34,30 +34,29 @@
34
34
  "quick:test": "node --import=@poppinss/ts-exec --enable-source-maps bin/test.ts"
35
35
  },
36
36
  "devDependencies": {
37
- "@adonisjs/eslint-config": "^3.0.0-next.1",
37
+ "@adonisjs/eslint-config": "^3.0.0",
38
38
  "@adonisjs/prettier-config": "^1.4.5",
39
- "@adonisjs/tsconfig": "^2.0.0-next.0",
40
- "@japa/assert": "^4.1.1",
41
- "@japa/expect-type": "^2.0.3",
42
- "@japa/file-system": "^2.3.2",
43
- "@japa/runner": "^4.4.0",
44
- "@poppinss/ts-exec": "^1.4.1",
45
- "@release-it/conventional-changelog": "^10.0.1",
46
- "@types/node": "^24.3.1",
47
- "c8": "^10.1.3",
48
- "cross-env": "^10.0.0",
49
- "del-cli": "^6.0.0",
50
- "eslint": "^9.35.0",
51
- "prettier": "^3.6.2",
52
- "release-it": "^19.0.4",
53
- "tsup": "^8.5.0",
54
- "typedoc": "^0.28.12",
55
- "typescript": "^5.9.2"
39
+ "@adonisjs/tsconfig": "^2.0.0",
40
+ "@japa/assert": "^4.2.0",
41
+ "@japa/expect-type": "^2.0.4",
42
+ "@japa/file-system": "^3.0.0",
43
+ "@japa/runner": "^5.3.0",
44
+ "@poppinss/ts-exec": "^1.4.4",
45
+ "@release-it/conventional-changelog": "^10.0.5",
46
+ "@types/node": "^25.3.0",
47
+ "c8": "^11.0.0",
48
+ "cross-env": "^10.1.0",
49
+ "del-cli": "^7.0.0",
50
+ "eslint": "^10.0.2",
51
+ "prettier": "^3.8.1",
52
+ "release-it": "^19.2.4",
53
+ "tsdown": "^0.20.3",
54
+ "typedoc": "^0.28.17",
55
+ "typescript": "^5.9.3"
56
56
  },
57
57
  "dependencies": {
58
- "@poppinss/utils": "^7.0.0-next.3",
58
+ "@poppinss/utils": "^7.0.0",
59
59
  "@poppinss/validator-lite": "^2.1.2",
60
- "dotenv": "^17.2.2",
61
60
  "split-lines": "^3.0.0"
62
61
  },
63
62
  "homepage": "https://github.com/adonisjs/env#readme",
@@ -82,7 +81,7 @@
82
81
  "access": "public",
83
82
  "provenance": true
84
83
  },
85
- "tsup": {
84
+ "tsdown": {
86
85
  "entry": [
87
86
  "./index.ts",
88
87
  "./src/types.ts",
@@ -91,8 +90,11 @@
91
90
  "outDir": "./build",
92
91
  "clean": true,
93
92
  "format": "esm",
93
+ "minify": "dce-only",
94
+ "fixedExtension": false,
94
95
  "dts": false,
95
- "sourcemap": false,
96
+ "treeshake": false,
97
+ "sourcemaps": false,
96
98
  "target": "esnext"
97
99
  },
98
100
  "release-it": {
@@ -1,112 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __export = (target, all) => {
3
- for (var name in all)
4
- __defProp(target, name, { get: all[name], enumerable: true });
5
- };
6
-
7
- // src/loader.ts
8
- import { fileURLToPath } from "url";
9
- import { readFile } from "fs/promises";
10
- import { isAbsolute, join } from "path";
11
-
12
- // src/debug.ts
13
- import { debuglog } from "util";
14
- var debug_default = debuglog("adonisjs:env");
15
-
16
- // src/loader.ts
17
- var EnvLoader = class {
18
- /**
19
- * The application root directory path
20
- */
21
- #appRoot;
22
- /**
23
- * Whether to load the .env.example file
24
- */
25
- #loadExampleFile;
26
- /**
27
- * Creates a new EnvLoader instance
28
- *
29
- * @param appRoot - The application root directory as string or URL
30
- * @param loadExampleFile - Whether to load .env.example file
31
- */
32
- constructor(appRoot, loadExampleFile = false) {
33
- this.#appRoot = typeof appRoot === "string" ? appRoot : fileURLToPath(appRoot);
34
- this.#loadExampleFile = loadExampleFile;
35
- }
36
- /**
37
- * Optionally read a file from the disk
38
- *
39
- * @param filePath - Path to the file to read
40
- * @returns Promise resolving to file existence status and contents
41
- */
42
- async #loadFile(filePath) {
43
- try {
44
- const contents = await readFile(filePath, "utf-8");
45
- return { contents, fileExists: true };
46
- } catch (error) {
47
- if (error.code !== "ENOENT") {
48
- throw error;
49
- }
50
- return { contents: "", fileExists: false };
51
- }
52
- }
53
- /**
54
- * Load contents of the main dot-env file and the current
55
- * environment dot-env file
56
- *
57
- * @returns Promise resolving to array of loaded environment files
58
- */
59
- async load() {
60
- const ENV_PATH = process.env.ENV_PATH;
61
- const NODE_ENV = process.env.NODE_ENV;
62
- const envFiles = [];
63
- if (debug_default.enabled) {
64
- debug_default("ENV_PATH variable is %s", ENV_PATH ? "set" : "not set");
65
- debug_default("NODE_ENV variable is %s", NODE_ENV ? "set" : "not set");
66
- }
67
- const baseEnvPath = ENV_PATH ? isAbsolute(ENV_PATH) ? ENV_PATH : join(this.#appRoot, ENV_PATH) : this.#appRoot;
68
- if (debug_default.enabled) {
69
- debug_default('dot-env files base path "%s"', baseEnvPath);
70
- }
71
- if (NODE_ENV) {
72
- const nodeEnvLocalFile = join(baseEnvPath, `.env.${NODE_ENV}.local`);
73
- envFiles.push({
74
- path: nodeEnvLocalFile,
75
- ...await this.#loadFile(nodeEnvLocalFile)
76
- });
77
- }
78
- if (!NODE_ENV || !["test", "testing"].includes(NODE_ENV)) {
79
- const envLocalFile = join(baseEnvPath, ".env.local");
80
- envFiles.push({
81
- path: envLocalFile,
82
- ...await this.#loadFile(envLocalFile)
83
- });
84
- }
85
- if (NODE_ENV) {
86
- const nodeEnvFile = join(baseEnvPath, `.env.${NODE_ENV}`);
87
- envFiles.push({
88
- path: nodeEnvFile,
89
- ...await this.#loadFile(nodeEnvFile)
90
- });
91
- }
92
- const envFile = join(baseEnvPath, ".env");
93
- envFiles.push({
94
- path: envFile,
95
- ...await this.#loadFile(envFile)
96
- });
97
- if (this.#loadExampleFile) {
98
- const envExampleFile = join(baseEnvPath, ".env.example");
99
- envFiles.push({
100
- path: envExampleFile,
101
- ...await this.#loadFile(envExampleFile)
102
- });
103
- }
104
- return envFiles;
105
- }
106
- };
107
-
108
- export {
109
- __export,
110
- debug_default,
111
- EnvLoader
112
- };