@guanghechen/env 2.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-present guanghechen (https://github.com/guanghechen)
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,158 @@
1
+ <header>
2
+ <h1 align="center">
3
+ <a href="https://github.com/guanghechen/sora/tree/@guanghechen/env@1.0.0/packages/env#readme">@guanghechen/env</a>
4
+ </h1>
5
+ <div align="center">
6
+ <a href="https://www.npmjs.com/package/@guanghechen/env">
7
+ <img
8
+ alt="Npm Version"
9
+ src="https://img.shields.io/npm/v/@guanghechen/env.svg"
10
+ />
11
+ </a>
12
+ <a href="https://www.npmjs.com/package/@guanghechen/env">
13
+ <img
14
+ alt="Npm Download"
15
+ src="https://img.shields.io/npm/dm/@guanghechen/env.svg"
16
+ />
17
+ </a>
18
+ <a href="https://www.npmjs.com/package/@guanghechen/env">
19
+ <img
20
+ alt="Npm License"
21
+ src="https://img.shields.io/npm/l/@guanghechen/env.svg"
22
+ />
23
+ </a>
24
+ <a href="#install">
25
+ <img
26
+ alt="Module Formats: cjs"
27
+ src="https://img.shields.io/badge/module_formats-cjs-green.svg"
28
+ />
29
+ </a>
30
+ <a href="https://github.com/nodejs/node">
31
+ <img
32
+ alt="Node.js Version"
33
+ src="https://img.shields.io/node/v/@guanghechen/env"
34
+ />
35
+ </a>
36
+ <a href="https://github.com/facebook/jest">
37
+ <img
38
+ alt="Tested with Jest"
39
+ src="https://img.shields.io/badge/tested_with-jest-9c465e.svg"
40
+ />
41
+ </a>
42
+ <a href="https://github.com/prettier/prettier">
43
+ <img
44
+ alt="Code Style: prettier"
45
+ src="https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square"
46
+ />
47
+ </a>
48
+ </div>
49
+ </header>
50
+ <br/>
51
+
52
+ A minimal .env parser with typed value support and variable interpolation. Supports comments,
53
+ `export` prefix, quoted values (single/double), escape sequences, and `${VAR}` interpolation.
54
+
55
+ ## Install
56
+
57
+ - npm
58
+
59
+ ```bash
60
+ npm install --save @guanghechen/env
61
+ ```
62
+
63
+ - yarn
64
+
65
+ ```bash
66
+ yarn add @guanghechen/env
67
+ ```
68
+
69
+ ## Usage
70
+
71
+ ### Parsing .env Content
72
+
73
+ ```typescript
74
+ import { parse } from '@guanghechen/env'
75
+
76
+ const content = `
77
+ # Database configuration
78
+ DB_HOST=localhost
79
+ DB_PORT=5432
80
+ DB_NAME=myapp
81
+
82
+ # With export prefix
83
+ export API_KEY=secret123
84
+
85
+ # Quoted values
86
+ MESSAGE="Hello, World!"
87
+ SINGLE_QUOTED='No interpolation here'
88
+
89
+ # Variable interpolation (double quotes or unquoted)
90
+ DB_URL="postgres://\${DB_HOST}:\${DB_PORT}/\${DB_NAME}"
91
+
92
+ # Escape sequences in double quotes
93
+ MULTILINE="Line1\\nLine2\\nLine3"
94
+ `
95
+
96
+ const env = parse(content)
97
+ console.log(env.DB_HOST) // 'localhost'
98
+ console.log(env.DB_PORT) // '5432'
99
+ console.log(env.DB_URL) // 'postgres://localhost:5432/myapp'
100
+ console.log(env.MULTILINE) // 'Line1\nLine2\nLine3'
101
+ ```
102
+
103
+ ### Stringifying to .env Format
104
+
105
+ ```typescript
106
+ import { stringify } from '@guanghechen/env'
107
+
108
+ const env = {
109
+ DB_HOST: 'localhost',
110
+ DB_PORT: '5432',
111
+ MESSAGE: 'Hello World',
112
+ SECRET: 'my-secret-key',
113
+ }
114
+
115
+ // Basic stringify
116
+ const content = stringify(env)
117
+ // DB_HOST=localhost
118
+ // DB_PORT=5432
119
+ // MESSAGE="Hello World"
120
+ // SECRET=my-secret-key
121
+
122
+ // With exclusion
123
+ const filtered = stringify(env, { exclude: ['SECRET'] })
124
+ // DB_HOST=localhost
125
+ // DB_PORT=5432
126
+ // MESSAGE="Hello World"
127
+ ```
128
+
129
+ ### Supported Syntax
130
+
131
+ ```bash
132
+ # Comments start with #
133
+ KEY=value
134
+
135
+ # Optional export prefix
136
+ export KEY=value
137
+
138
+ # Double-quoted values (with escape sequences and interpolation)
139
+ KEY="value with spaces"
140
+ KEY="Line1\nLine2"
141
+ KEY="Uses ${OTHER_VAR}"
142
+
143
+ # Single-quoted values (literal, no processing)
144
+ KEY='${NOT_INTERPOLATED}'
145
+
146
+ # Inline comments (unquoted values only)
147
+ KEY=value # this is a comment
148
+
149
+ # Empty values
150
+ KEY=
151
+ ```
152
+
153
+ ## Reference
154
+
155
+ - [homepage][homepage]
156
+
157
+ [homepage]:
158
+ https://github.com/guanghechen/sora/tree/@guanghechen/env@1.0.0/packages/env#readme
@@ -0,0 +1,103 @@
1
+ 'use strict';
2
+
3
+ const KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
4
+ function parse(content) {
5
+ const env = {};
6
+ if (!content)
7
+ return env;
8
+ const lines = content.replace(/\r\n?/g, '\n').split('\n');
9
+ for (let lineNum = 0; lineNum < lines.length; lineNum++) {
10
+ const line = lines[lineNum];
11
+ const trimmed = line.trim();
12
+ if (!trimmed || trimmed.startsWith('#'))
13
+ continue;
14
+ const withoutExport = trimmed.startsWith('export ') ? trimmed.slice(7).trim() : trimmed;
15
+ const sepIndex = withoutExport.indexOf('=');
16
+ if (sepIndex === -1)
17
+ continue;
18
+ const key = withoutExport.slice(0, sepIndex);
19
+ if (!key || !KEY_PATTERN.test(key))
20
+ continue;
21
+ let value = withoutExport.slice(sepIndex + 1);
22
+ if (!value) {
23
+ env[key] = '';
24
+ continue;
25
+ }
26
+ const quoteChar = value[0];
27
+ const isDoubleQuote = quoteChar === '"';
28
+ const isSingleQuote = quoteChar === "'";
29
+ if (isDoubleQuote || isSingleQuote) {
30
+ const closeIndex = findClosingQuote(value, quoteChar);
31
+ if (closeIndex === -1) {
32
+ throw new SyntaxError(`Unclosed quote at line ${lineNum + 1}: ${line}`);
33
+ }
34
+ value = value.slice(1, closeIndex);
35
+ if (isDoubleQuote) {
36
+ value = processEscapeSequences(value);
37
+ value = interpolate(value, env);
38
+ }
39
+ }
40
+ else {
41
+ const commentIndex = value.search(/\s+#/);
42
+ if (commentIndex !== -1) {
43
+ value = value.slice(0, commentIndex);
44
+ }
45
+ value = interpolate(value, env);
46
+ }
47
+ env[key] = value;
48
+ }
49
+ return env;
50
+ }
51
+ function findClosingQuote(value, quoteChar) {
52
+ for (let i = 1; i < value.length; i += 1) {
53
+ if (value[i] === '\\' && value[i + 1] === quoteChar) {
54
+ i += 1;
55
+ continue;
56
+ }
57
+ if (value[i] === quoteChar) {
58
+ return i;
59
+ }
60
+ }
61
+ return -1;
62
+ }
63
+ const BACKSLASH_PLACEHOLDER = '\uE000';
64
+ function processEscapeSequences(value) {
65
+ return value
66
+ .replace(/\\\\/g, BACKSLASH_PLACEHOLDER)
67
+ .replace(/\\n/g, '\n')
68
+ .replace(/\\r/g, '\r')
69
+ .replace(/\\t/g, '\t')
70
+ .replace(/\\"/g, '"')
71
+ .replace(new RegExp(BACKSLASH_PLACEHOLDER, 'g'), '\\');
72
+ }
73
+ function interpolate(value, env) {
74
+ return value.replace(/\\?\$\{([^}]+)\}/g, (match, varName) => {
75
+ if (match.startsWith('\\')) {
76
+ return match.slice(1);
77
+ }
78
+ return env[varName] ?? '';
79
+ });
80
+ }
81
+ function stringifyValue(value) {
82
+ const escaped = value
83
+ .replace(/\\/g, '\\\\')
84
+ .replace(/"/g, '\\"')
85
+ .replace(/\n/g, '\\n')
86
+ .replace(/\r/g, '\\r')
87
+ .replace(/\t/g, '\\t');
88
+ const needsQuote = escaped !== value || value.includes(' ') || value.includes("'") || value.includes('#');
89
+ return needsQuote ? `"${escaped}"` : escaped;
90
+ }
91
+ function stringify(env, options) {
92
+ const excludeSet = new Set(options?.exclude ?? []);
93
+ const lines = [];
94
+ for (const [key, value] of Object.entries(env)) {
95
+ if (excludeSet.has(key))
96
+ continue;
97
+ lines.push(`${key}=${stringifyValue(value)}`);
98
+ }
99
+ return lines.length > 0 ? `${lines.join('\n')}\n` : '';
100
+ }
101
+
102
+ exports.parse = parse;
103
+ exports.stringify = stringify;
@@ -0,0 +1,100 @@
1
+ const KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
2
+ function parse(content) {
3
+ const env = {};
4
+ if (!content)
5
+ return env;
6
+ const lines = content.replace(/\r\n?/g, '\n').split('\n');
7
+ for (let lineNum = 0; lineNum < lines.length; lineNum++) {
8
+ const line = lines[lineNum];
9
+ const trimmed = line.trim();
10
+ if (!trimmed || trimmed.startsWith('#'))
11
+ continue;
12
+ const withoutExport = trimmed.startsWith('export ') ? trimmed.slice(7).trim() : trimmed;
13
+ const sepIndex = withoutExport.indexOf('=');
14
+ if (sepIndex === -1)
15
+ continue;
16
+ const key = withoutExport.slice(0, sepIndex);
17
+ if (!key || !KEY_PATTERN.test(key))
18
+ continue;
19
+ let value = withoutExport.slice(sepIndex + 1);
20
+ if (!value) {
21
+ env[key] = '';
22
+ continue;
23
+ }
24
+ const quoteChar = value[0];
25
+ const isDoubleQuote = quoteChar === '"';
26
+ const isSingleQuote = quoteChar === "'";
27
+ if (isDoubleQuote || isSingleQuote) {
28
+ const closeIndex = findClosingQuote(value, quoteChar);
29
+ if (closeIndex === -1) {
30
+ throw new SyntaxError(`Unclosed quote at line ${lineNum + 1}: ${line}`);
31
+ }
32
+ value = value.slice(1, closeIndex);
33
+ if (isDoubleQuote) {
34
+ value = processEscapeSequences(value);
35
+ value = interpolate(value, env);
36
+ }
37
+ }
38
+ else {
39
+ const commentIndex = value.search(/\s+#/);
40
+ if (commentIndex !== -1) {
41
+ value = value.slice(0, commentIndex);
42
+ }
43
+ value = interpolate(value, env);
44
+ }
45
+ env[key] = value;
46
+ }
47
+ return env;
48
+ }
49
+ function findClosingQuote(value, quoteChar) {
50
+ for (let i = 1; i < value.length; i += 1) {
51
+ if (value[i] === '\\' && value[i + 1] === quoteChar) {
52
+ i += 1;
53
+ continue;
54
+ }
55
+ if (value[i] === quoteChar) {
56
+ return i;
57
+ }
58
+ }
59
+ return -1;
60
+ }
61
+ const BACKSLASH_PLACEHOLDER = '\uE000';
62
+ function processEscapeSequences(value) {
63
+ return value
64
+ .replace(/\\\\/g, BACKSLASH_PLACEHOLDER)
65
+ .replace(/\\n/g, '\n')
66
+ .replace(/\\r/g, '\r')
67
+ .replace(/\\t/g, '\t')
68
+ .replace(/\\"/g, '"')
69
+ .replace(new RegExp(BACKSLASH_PLACEHOLDER, 'g'), '\\');
70
+ }
71
+ function interpolate(value, env) {
72
+ return value.replace(/\\?\$\{([^}]+)\}/g, (match, varName) => {
73
+ if (match.startsWith('\\')) {
74
+ return match.slice(1);
75
+ }
76
+ return env[varName] ?? '';
77
+ });
78
+ }
79
+ function stringifyValue(value) {
80
+ const escaped = value
81
+ .replace(/\\/g, '\\\\')
82
+ .replace(/"/g, '\\"')
83
+ .replace(/\n/g, '\\n')
84
+ .replace(/\r/g, '\\r')
85
+ .replace(/\t/g, '\\t');
86
+ const needsQuote = escaped !== value || value.includes(' ') || value.includes("'") || value.includes('#');
87
+ return needsQuote ? `"${escaped}"` : escaped;
88
+ }
89
+ function stringify(env, options) {
90
+ const excludeSet = new Set(options?.exclude ?? []);
91
+ const lines = [];
92
+ for (const [key, value] of Object.entries(env)) {
93
+ if (excludeSet.has(key))
94
+ continue;
95
+ lines.push(`${key}=${stringifyValue(value)}`);
96
+ }
97
+ return lines.length > 0 ? `${lines.join('\n')}\n` : '';
98
+ }
99
+
100
+ export { parse, stringify };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A minimal .env parser with variable interpolation.
3
+ *
4
+ * @module @guanghechen/env
5
+ */
6
+ /** Record of environment variables (always string values) */
7
+ type IEnvRecord = Record<string, string>;
8
+ /** Options for stringify */
9
+ interface IStringifyEnvOptions {
10
+ /** Keys to exclude from output */
11
+ exclude?: string[];
12
+ }
13
+ /**
14
+ * Parse .env content string into an object.
15
+ * Supports comments, export prefix, quoted values, and variable interpolation.
16
+ * @param content - .env file content
17
+ * @returns Parsed environment record
18
+ * @throws {SyntaxError} If unclosed quote is detected
19
+ */
20
+ declare function parse(content: string): IEnvRecord;
21
+ /**
22
+ * Convert environment record to .env format string.
23
+ * Values containing spaces, quotes, newlines, or # are double-quoted.
24
+ * @param env - Environment record to stringify
25
+ * @param options - Stringify options
26
+ * @returns .env format string
27
+ */
28
+ declare function stringify(env: IEnvRecord, options?: IStringifyEnvOptions): string;
29
+
30
+ export { parse, stringify };
31
+ export type { IEnvRecord, IStringifyEnvOptions };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@guanghechen/env",
3
+ "version": "2.0.1",
4
+ "description": "A minimal .env parser with typed value support and variable interpolation.",
5
+ "author": {
6
+ "name": "guanghechen",
7
+ "url": "https://github.com/guanghechen/"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/guanghechen/sora/tree/@guanghechen/env@2.0.0",
12
+ "directory": "packages/env"
13
+ },
14
+ "homepage": "https://github.com/guanghechen/sora/tree/@guanghechen/env@2.0.0/packages/env#readme",
15
+ "keywords": [
16
+ "env",
17
+ "dotenv",
18
+ "parser",
19
+ "environment"
20
+ ],
21
+ "type": "module",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./lib/types/index.d.ts",
25
+ "source": "./src/index.ts",
26
+ "import": "./lib/esm/index.mjs",
27
+ "require": "./lib/cjs/index.cjs"
28
+ }
29
+ },
30
+ "source": "./src/index.ts",
31
+ "main": "./lib/cjs/index.cjs",
32
+ "module": "./lib/esm/index.mjs",
33
+ "types": "./lib/types/index.d.ts",
34
+ "license": "MIT",
35
+ "files": [
36
+ "lib/",
37
+ "!lib/**/*.map",
38
+ "package.json",
39
+ "CHANGELOG.md",
40
+ "LICENSE",
41
+ "README.md"
42
+ ],
43
+ "scripts": {
44
+ "build": "rollup -c ../../rollup.config.mjs",
45
+ "clean": "rimraf lib",
46
+ "test": "vitest run --config ../../vitest.config.ts",
47
+ "test:coverage": "vitest run --config ../../vitest.config.ts --coverage",
48
+ "test:update": "vitest run --config ../../vitest.config.ts -u"
49
+ }
50
+ }