@labsbit/esr 0.0.0-stage → 1.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/LICENSE +21 -0
- package/README.md +85 -2
- package/dist/agent.d.ts +36 -0
- package/dist/agent.js +175 -0
- package/dist/core.d.ts +18 -0
- package/dist/core.js +272 -0
- package/dist/fields.d.ts +77 -0
- package/dist/fields.js +98 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/settings.d.ts +38 -0
- package/dist/settings.js +270 -0
- package/package.json +36 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 labsbit
|
|
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
CHANGED
|
@@ -1,3 +1,86 @@
|
|
|
1
|
-
#
|
|
1
|
+
# esr for TypeScript and JavaScript
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Typed settings from env-plane. The library asks the local `esr` agent for the
|
|
4
|
+
values of your project and version, lets `.env` and the process environment
|
|
5
|
+
override them, and fails fast with one error that names every problem.
|
|
6
|
+
|
|
7
|
+
Node.js 20+, ESM, no runtime dependencies. Types need TypeScript 5.4+.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
npm install @labsbit/esr
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Coding agents
|
|
16
|
+
|
|
17
|
+
`esr skill install` (in the project's repository) installs the env-plane
|
|
18
|
+
skill for Claude Code, Cursor and Codex. It teaches the agent how to onboard
|
|
19
|
+
the project: find the values it reads, upload them with `esr vars`, declare
|
|
20
|
+
them with this library and wire `esr run` into tools, Docker and
|
|
21
|
+
deployments, without writing secrets into files or transcripts.
|
|
22
|
+
`esr skill` prints it.
|
|
23
|
+
|
|
24
|
+
## Use
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { bool, list, loadSettings, str } from '@labsbit/esr';
|
|
28
|
+
|
|
29
|
+
const settings = await loadSettings({ project: 'shop', version: 'main' }, {
|
|
30
|
+
databaseUrl: str(), // DATABASE_URL, required
|
|
31
|
+
debug: bool({ default: false }), // DEBUG, optional
|
|
32
|
+
hosts: list(str(), { default: [] }), // HOSTS: "a,b" or a JSON array
|
|
33
|
+
token: str({ variable: 'SERVICE_TOKEN' }), // explicit variable name
|
|
34
|
+
});
|
|
35
|
+
settings.debug; // boolean — the type derives from the declaration
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Run `esr login` once a day, then start the app. In a deployment start it with
|
|
39
|
+
`esr run -- <command>`. Tests and CI without an agent set `ESR_OFFLINE=1` and
|
|
40
|
+
provide values through the environment or `.env`.
|
|
41
|
+
|
|
42
|
+
## Behaviour
|
|
43
|
+
|
|
44
|
+
- **Project and version are in the code**, the environment never is: it is
|
|
45
|
+
the agent's (`development` after login, `esr env use <name>` to switch, or
|
|
46
|
+
the deployment token's).
|
|
47
|
+
- **Variable of a field:** its name in upper snake case (`databaseUrl` →
|
|
48
|
+
`DATABASE_URL`, `myAPIKey` → `MY_API_KEY`), or `{ variable: '…' }`.
|
|
49
|
+
Lookups are case-sensitive.
|
|
50
|
+
- **Sources, first hit wins:** process environment, `.env`, agent, default.
|
|
51
|
+
An empty string is a value. Defaults are used as declared.
|
|
52
|
+
- **`.env`:** `.env` in the working directory, or `envFile` in the
|
|
53
|
+
declaration, or `ESR_ENV_FILE` (empty = no file). No interpolation; invalid
|
|
54
|
+
lines are skipped with a warning that names the line number only.
|
|
55
|
+
- **Types:** `str()`, `int()` (within ±(2^53−1)), `float()`, `bool()`
|
|
56
|
+
(`1 true t yes y on` / `0 false f no n off`), `list(str() | int() | float()
|
|
57
|
+
| bool())` (`a,b` or a JSON array), `json<T>()` (any JSON value; `T` is not
|
|
58
|
+
checked). A `default` of another type widens the field's type
|
|
59
|
+
(`str({ default: null })` is `string | null`).
|
|
60
|
+
- **Errors:** one `SettingsError` with `code` (`agent_unavailable`,
|
|
61
|
+
`not_signed_in`, `forbidden`, `not_found`, `version_mismatch`,
|
|
62
|
+
`server_unreachable`, `agent_error`, `invalid_settings`) and, for
|
|
63
|
+
`invalid_settings`, the sorted variable names in `missing` and `invalid`.
|
|
64
|
+
The message says what to do (`esr login`, …). A wrong declaration throws a
|
|
65
|
+
`TypeError`.
|
|
66
|
+
- **Secret overrides:** when `.env` or the environment replaces a secret or a
|
|
67
|
+
proxy token with a different value, the library prints
|
|
68
|
+
`esr: warning: secret NAME is overridden by .env` to stderr and reports the
|
|
69
|
+
name to the agent. Overrides are always allowed.
|
|
70
|
+
- **Values are never printed**: not in messages, warnings or reports. The
|
|
71
|
+
settings object is frozen.
|
|
72
|
+
- **Finding the agent:** `ESR_AGENT_SOCK`, else `ESR_AGENT_URL` with
|
|
73
|
+
`ESR_AGENT_TOKEN` (Docker Compose, see `esr link`), else
|
|
74
|
+
`~/.esr/agent.sock`. 2 s to connect, 30 s for the answer.
|
|
75
|
+
|
|
76
|
+
The fixtures in `conformance/` hold all three libraries to the same rules.
|
|
77
|
+
|
|
78
|
+
## Development
|
|
79
|
+
|
|
80
|
+
```
|
|
81
|
+
npm ci && npm test # build, type-level test, conformance and integration tests
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The only development dependency is `typescript`, pinned exactly; `.npmrc`
|
|
85
|
+
sets `ignore-scripts=true`. `src/node.d.ts` declares the few Node.js APIs the
|
|
86
|
+
library uses, so `@types/node` is not needed.
|
package/dist/agent.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export declare const CONNECT_TIMEOUT = 2000;
|
|
2
|
+
export declare const RESPONSE_TIMEOUT = 30000;
|
|
3
|
+
export declare const REPORT_TIMEOUT = 2000;
|
|
4
|
+
/** No connection to the agent. The reason is short and has no values in it. */
|
|
5
|
+
export declare class ConnectError extends Error {
|
|
6
|
+
/** Set when the agent's address itself is unusable. */
|
|
7
|
+
agent?: Agent;
|
|
8
|
+
}
|
|
9
|
+
/** Connected, but no usable HTTP answer (timeout, hang-up, garbage). */
|
|
10
|
+
export declare class ProtocolError extends Error {
|
|
11
|
+
}
|
|
12
|
+
/** Where the agent listens: `sock` (Unix socket) or host and port (TCP). */
|
|
13
|
+
export interface Agent {
|
|
14
|
+
readonly sock?: string;
|
|
15
|
+
readonly host?: string;
|
|
16
|
+
readonly port?: number;
|
|
17
|
+
/** Path prefix of ESR_AGENT_URL, without trailing slash. */
|
|
18
|
+
readonly prefix: string;
|
|
19
|
+
readonly token?: string;
|
|
20
|
+
/** The socket path or the URL, for messages. */
|
|
21
|
+
readonly address: string;
|
|
22
|
+
}
|
|
23
|
+
export type Environ = Readonly<Record<string, string | undefined>>;
|
|
24
|
+
/**
|
|
25
|
+
* §7.1: ESR_AGENT_SOCK, then ESR_AGENT_URL (with ESR_AGENT_TOKEN), then
|
|
26
|
+
* $HOME/.esr/agent.sock. Empty variables count as unset. Throws ConnectError
|
|
27
|
+
* (with `agent` set) for an unusable ESR_AGENT_URL.
|
|
28
|
+
*/
|
|
29
|
+
export declare function findAgent(environ: Environ): Agent;
|
|
30
|
+
export interface AgentResponse {
|
|
31
|
+
status: number;
|
|
32
|
+
/** The decoded JSON body; undefined if the body is not JSON. */
|
|
33
|
+
body: unknown;
|
|
34
|
+
}
|
|
35
|
+
/** Sends one request. Rejects with ConnectError or ProtocolError. */
|
|
36
|
+
export declare function request(agent: Agent, method: string, path: string, body?: unknown, responseTimeout?: number): Promise<AgentResponse>;
|
package/dist/agent.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// Client of the local channel (docs/contracts.md §7.1, §7.2): HTTP/1.1 with
|
|
2
|
+
// JSON bodies over the agent's Unix socket or, for containers, over TCP with
|
|
3
|
+
// a link token. node:http only.
|
|
4
|
+
import { request as httpRequest } from 'node:http';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { clearTimeout, setTimeout } from 'node:timers';
|
|
8
|
+
import { URL } from 'node:url';
|
|
9
|
+
import { TextDecoder } from 'node:util';
|
|
10
|
+
export const CONNECT_TIMEOUT = 2_000; // ms to connect
|
|
11
|
+
export const RESPONSE_TIMEOUT = 30_000; // ms for the response
|
|
12
|
+
export const REPORT_TIMEOUT = 2_000; // override report and status lookup: best effort
|
|
13
|
+
const MAX_BODY = 64 * 1024 * 1024;
|
|
14
|
+
const USER_AGENT = 'esr-typescript/1';
|
|
15
|
+
/** No connection to the agent. The reason is short and has no values in it. */
|
|
16
|
+
export class ConnectError extends Error {
|
|
17
|
+
/** Set when the agent's address itself is unusable. */
|
|
18
|
+
agent;
|
|
19
|
+
}
|
|
20
|
+
/** Connected, but no usable HTTP answer (timeout, hang-up, garbage). */
|
|
21
|
+
export class ProtocolError extends Error {
|
|
22
|
+
}
|
|
23
|
+
const BAD_URL = 'ESR_AGENT_URL must look like http://host:port';
|
|
24
|
+
/**
|
|
25
|
+
* §7.1: ESR_AGENT_SOCK, then ESR_AGENT_URL (with ESR_AGENT_TOKEN), then
|
|
26
|
+
* $HOME/.esr/agent.sock. Empty variables count as unset. Throws ConnectError
|
|
27
|
+
* (with `agent` set) for an unusable ESR_AGENT_URL.
|
|
28
|
+
*/
|
|
29
|
+
export function findAgent(environ) {
|
|
30
|
+
const sock = environ['ESR_AGENT_SOCK'];
|
|
31
|
+
if (sock)
|
|
32
|
+
return { sock, prefix: '', address: sock };
|
|
33
|
+
const raw = environ['ESR_AGENT_URL'];
|
|
34
|
+
if (raw) {
|
|
35
|
+
const bad = () => {
|
|
36
|
+
const e = new ConnectError(BAD_URL);
|
|
37
|
+
e.agent = { host: '', prefix: '', address: raw };
|
|
38
|
+
return e;
|
|
39
|
+
};
|
|
40
|
+
let url;
|
|
41
|
+
try {
|
|
42
|
+
url = new URL(raw);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
throw bad();
|
|
46
|
+
}
|
|
47
|
+
if (url.protocol !== 'http:' || url.hostname === '' || url.search !== '' || url.hash !== '' || url.username !== '' || url.password !== '') {
|
|
48
|
+
throw bad();
|
|
49
|
+
}
|
|
50
|
+
const host = url.hostname.replace(/^\[(.*)\]$/, '$1'); // IPv6 literal
|
|
51
|
+
const port = url.port === '' ? 80 : Number(url.port);
|
|
52
|
+
const prefix = url.pathname.replace(/\/+$/, '');
|
|
53
|
+
const token = environ['ESR_AGENT_TOKEN'];
|
|
54
|
+
return {
|
|
55
|
+
host,
|
|
56
|
+
port,
|
|
57
|
+
prefix,
|
|
58
|
+
address: raw.replace(/\/+$/, ''),
|
|
59
|
+
...(token ? { token } : {}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const home = environ['HOME'] || environ['USERPROFILE'] || homedir();
|
|
63
|
+
const path = join(home, '.esr', 'agent.sock');
|
|
64
|
+
return { sock: path, prefix: '', address: path };
|
|
65
|
+
}
|
|
66
|
+
function connectReason(code) {
|
|
67
|
+
switch (code) {
|
|
68
|
+
case 'ENOENT':
|
|
69
|
+
return 'no socket there';
|
|
70
|
+
case 'ECONNREFUSED':
|
|
71
|
+
return 'nothing is listening';
|
|
72
|
+
case 'EACCES':
|
|
73
|
+
case 'EPERM':
|
|
74
|
+
return 'permission denied';
|
|
75
|
+
case 'ENOTFOUND':
|
|
76
|
+
case 'EAI_AGAIN':
|
|
77
|
+
return 'host name not found';
|
|
78
|
+
default:
|
|
79
|
+
return 'connection failed';
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** Sends one request. Rejects with ConnectError or ProtocolError. */
|
|
83
|
+
export function request(agent, method, path, body, responseTimeout = RESPONSE_TIMEOUT) {
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
const headers = { Accept: 'application/json', 'User-Agent': USER_AGENT, Connection: 'close' };
|
|
86
|
+
let payload;
|
|
87
|
+
if (body !== undefined) {
|
|
88
|
+
payload = JSON.stringify(body);
|
|
89
|
+
headers['Content-Type'] = 'application/json';
|
|
90
|
+
}
|
|
91
|
+
const options = { path: agent.prefix + path, method, headers, agent: false };
|
|
92
|
+
if (agent.sock !== undefined) {
|
|
93
|
+
options.socketPath = agent.sock;
|
|
94
|
+
headers['Host'] = 'esr-agent'; // host name used over the socket (§7.1)
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
options.host = agent.host;
|
|
98
|
+
options.port = agent.port;
|
|
99
|
+
if (agent.token)
|
|
100
|
+
headers['Authorization'] = `Bearer ${agent.token}`;
|
|
101
|
+
}
|
|
102
|
+
let settled = false;
|
|
103
|
+
let connected = false;
|
|
104
|
+
const broke = () => new ProtocolError('the connection broke before a complete answer arrived');
|
|
105
|
+
const settle = (act) => {
|
|
106
|
+
if (settled)
|
|
107
|
+
return;
|
|
108
|
+
settled = true;
|
|
109
|
+
clearTimeout(timer);
|
|
110
|
+
act();
|
|
111
|
+
};
|
|
112
|
+
let timer = setTimeout(() => {
|
|
113
|
+
settle(() => reject(new ConnectError(`no connection within ${CONNECT_TIMEOUT / 1000} seconds`)));
|
|
114
|
+
req.destroy();
|
|
115
|
+
}, CONNECT_TIMEOUT);
|
|
116
|
+
const req = httpRequest(options, (res) => {
|
|
117
|
+
const chunks = [];
|
|
118
|
+
let size = 0;
|
|
119
|
+
res.on('data', (chunk) => {
|
|
120
|
+
size += chunk.length;
|
|
121
|
+
if (size > MAX_BODY) {
|
|
122
|
+
settle(() => reject(new ProtocolError('the answer is too large')));
|
|
123
|
+
req.destroy();
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
chunks.push(chunk);
|
|
127
|
+
});
|
|
128
|
+
res.on('error', () => settle(() => reject(broke())));
|
|
129
|
+
res.on('close', () => {
|
|
130
|
+
if (!res.complete)
|
|
131
|
+
settle(() => reject(broke()));
|
|
132
|
+
});
|
|
133
|
+
res.on('end', () => {
|
|
134
|
+
if (!res.complete) {
|
|
135
|
+
settle(() => reject(broke()));
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const raw = new Uint8Array(size);
|
|
139
|
+
let offset = 0;
|
|
140
|
+
for (const chunk of chunks) {
|
|
141
|
+
raw.set(chunk, offset);
|
|
142
|
+
offset += chunk.length;
|
|
143
|
+
}
|
|
144
|
+
let decoded;
|
|
145
|
+
try {
|
|
146
|
+
decoded = size === 0 ? undefined : JSON.parse(new TextDecoder('utf-8').decode(raw));
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
decoded = undefined;
|
|
150
|
+
}
|
|
151
|
+
settle(() => resolve({ status: res.statusCode ?? 0, body: decoded }));
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
req.on('socket', (socket) => {
|
|
155
|
+
const onConnect = () => {
|
|
156
|
+
if (settled)
|
|
157
|
+
return;
|
|
158
|
+
connected = true;
|
|
159
|
+
clearTimeout(timer);
|
|
160
|
+
timer = setTimeout(() => {
|
|
161
|
+
settle(() => reject(new ProtocolError(`no answer within ${responseTimeout / 1000} seconds`)));
|
|
162
|
+
req.destroy();
|
|
163
|
+
}, responseTimeout);
|
|
164
|
+
};
|
|
165
|
+
if (socket.connecting)
|
|
166
|
+
socket.once('connect', onConnect);
|
|
167
|
+
else
|
|
168
|
+
onConnect();
|
|
169
|
+
});
|
|
170
|
+
req.on('error', (err) => {
|
|
171
|
+
settle(() => reject(connected ? broke() : new ConnectError(connectReason(err.code))));
|
|
172
|
+
});
|
|
173
|
+
req.end(payload);
|
|
174
|
+
});
|
|
175
|
+
}
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `database_url`, `databaseUrl` and `DatabaseURL` are all `DATABASE_URL`.
|
|
3
|
+
* Only ASCII letters take part in word splitting and upper-casing; anything
|
|
4
|
+
* else is kept as it is (give such fields an explicit variable name).
|
|
5
|
+
*/
|
|
6
|
+
export declare function variableName(field: string): string;
|
|
7
|
+
export interface Dotenv {
|
|
8
|
+
values: Map<string, string>;
|
|
9
|
+
/** 1-based numbers of the invalid lines. */
|
|
10
|
+
invalidLines: number[];
|
|
11
|
+
}
|
|
12
|
+
export declare function parseDotenv(input: string): Dotenv;
|
|
13
|
+
export type ScalarType = 'str' | 'int' | 'float' | 'bool';
|
|
14
|
+
export type FieldType = ScalarType | `list[${ScalarType}]` | 'json';
|
|
15
|
+
/** Returned by coerce when the string does not fit the type. */
|
|
16
|
+
export declare const INVALID: unique symbol;
|
|
17
|
+
/** Coerces the string to the type; returns INVALID if it does not fit. */
|
|
18
|
+
export declare function coerce(type: FieldType, s: string): unknown;
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// Pure rules of docs/contracts.md §8: variable names (§8.1), the .env format
|
|
2
|
+
// (§8.3) and type coercion (§8.4). No I/O. The fixtures in sdk/conformance
|
|
3
|
+
// decide what is right; the other libraries implement exactly the same rules.
|
|
4
|
+
// ---------------------------------------------------------------- names (§8.1)
|
|
5
|
+
const isUpper = (c) => c !== undefined && c >= 'A' && c <= 'Z';
|
|
6
|
+
const isLower = (c) => c !== undefined && c >= 'a' && c <= 'z';
|
|
7
|
+
const isDigit = (c) => c !== undefined && c >= '0' && c <= '9';
|
|
8
|
+
/**
|
|
9
|
+
* `database_url`, `databaseUrl` and `DatabaseURL` are all `DATABASE_URL`.
|
|
10
|
+
* Only ASCII letters take part in word splitting and upper-casing; anything
|
|
11
|
+
* else is kept as it is (give such fields an explicit variable name).
|
|
12
|
+
*/
|
|
13
|
+
export function variableName(field) {
|
|
14
|
+
const words = [];
|
|
15
|
+
let cur = '';
|
|
16
|
+
for (let i = 0; i < field.length; i++) {
|
|
17
|
+
let c = field[i];
|
|
18
|
+
if (c === '_' || c === '-') {
|
|
19
|
+
if (cur !== '') {
|
|
20
|
+
words.push(cur);
|
|
21
|
+
cur = '';
|
|
22
|
+
}
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
if (cur !== '' && isUpper(c)) {
|
|
26
|
+
const prev = field[i - 1];
|
|
27
|
+
if (isLower(prev) || isDigit(prev) || (isUpper(prev) && isLower(field[i + 1]))) {
|
|
28
|
+
words.push(cur);
|
|
29
|
+
cur = '';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
if (isLower(c))
|
|
33
|
+
c = String.fromCharCode(c.charCodeAt(0) - 32);
|
|
34
|
+
cur += c;
|
|
35
|
+
}
|
|
36
|
+
if (cur !== '')
|
|
37
|
+
words.push(cur);
|
|
38
|
+
return words.join('_');
|
|
39
|
+
}
|
|
40
|
+
// ---------------------------------------------------------------- .env (§8.3)
|
|
41
|
+
const isBlank = (c) => c === ' ' || c === '\t';
|
|
42
|
+
function stripLeft(s) {
|
|
43
|
+
let i = 0;
|
|
44
|
+
while (isBlank(s[i]))
|
|
45
|
+
i++;
|
|
46
|
+
return s.slice(i);
|
|
47
|
+
}
|
|
48
|
+
function stripBlanks(s) {
|
|
49
|
+
let start = 0;
|
|
50
|
+
let end = s.length;
|
|
51
|
+
while (start < end && isBlank(s[start]))
|
|
52
|
+
start++;
|
|
53
|
+
while (end > start && isBlank(s[end - 1]))
|
|
54
|
+
end--;
|
|
55
|
+
return s.slice(start, end);
|
|
56
|
+
}
|
|
57
|
+
const KEY = /^[A-Za-z_][A-Za-z0-9_]*/;
|
|
58
|
+
const EXPORT = /^export[ \t]+/;
|
|
59
|
+
const ESCAPES = { n: '\n', r: '\r', t: '\t', '\\': '\\', '"': '"' };
|
|
60
|
+
export function parseDotenv(input) {
|
|
61
|
+
let text = input;
|
|
62
|
+
if (text.startsWith('\ufeff'))
|
|
63
|
+
text = text.slice(1);
|
|
64
|
+
text = text.replaceAll('\r\n', '\n');
|
|
65
|
+
const lines = text.split('\n');
|
|
66
|
+
const starts = [];
|
|
67
|
+
let pos = 0;
|
|
68
|
+
for (const line of lines) {
|
|
69
|
+
starts.push(pos);
|
|
70
|
+
pos += line.length + 1;
|
|
71
|
+
}
|
|
72
|
+
const values = new Map();
|
|
73
|
+
const invalidLines = [];
|
|
74
|
+
let i = 0;
|
|
75
|
+
while (i < lines.length) {
|
|
76
|
+
const line = lines[i];
|
|
77
|
+
const lineno = i + 1;
|
|
78
|
+
let s = stripLeft(line);
|
|
79
|
+
if (s === '' || s.startsWith('#')) {
|
|
80
|
+
i++;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
s = s.replace(EXPORT, '');
|
|
84
|
+
const m = KEY.exec(s);
|
|
85
|
+
if (m === null) {
|
|
86
|
+
invalidLines.push(lineno);
|
|
87
|
+
i++;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const key = m[0];
|
|
91
|
+
let rest = stripLeft(s.slice(key.length));
|
|
92
|
+
if (!rest.startsWith('=')) {
|
|
93
|
+
invalidLines.push(lineno);
|
|
94
|
+
i++;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
rest = rest.slice(1);
|
|
98
|
+
const stripped = stripLeft(rest);
|
|
99
|
+
const quote = stripped[0];
|
|
100
|
+
if (quote === '"' || quote === "'") {
|
|
101
|
+
// Offset in `text` of the character behind the opening quote.
|
|
102
|
+
let j = starts[i] + (line.length - stripped.length) + 1;
|
|
103
|
+
let out = '';
|
|
104
|
+
let closed = false;
|
|
105
|
+
while (j < text.length) {
|
|
106
|
+
const c = text[j];
|
|
107
|
+
if (quote === '"' && c === '\\' && j + 1 < text.length) {
|
|
108
|
+
const n = text[j + 1];
|
|
109
|
+
out += Object.hasOwn(ESCAPES, n) ? ESCAPES[n] : '\\' + n;
|
|
110
|
+
j += 2;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (c === quote) {
|
|
114
|
+
closed = true;
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
out += c;
|
|
118
|
+
j++;
|
|
119
|
+
}
|
|
120
|
+
if (!closed) {
|
|
121
|
+
invalidLines.push(lineno);
|
|
122
|
+
i++;
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
let eol = text.indexOf('\n', j);
|
|
126
|
+
if (eol === -1)
|
|
127
|
+
eol = text.length;
|
|
128
|
+
const tail = stripLeft(text.slice(j + 1, eol));
|
|
129
|
+
if (tail !== '' && !tail.startsWith('#')) {
|
|
130
|
+
invalidLines.push(lineno);
|
|
131
|
+
i++;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
values.set(key, out);
|
|
135
|
+
let breaks = 0; // the line after the closing quote
|
|
136
|
+
for (let k = text.indexOf('\n'); k !== -1 && k < j; k = text.indexOf('\n', k + 1))
|
|
137
|
+
breaks++;
|
|
138
|
+
i = breaks + 1;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
let cut = rest.length;
|
|
142
|
+
for (let k = 1; k < rest.length; k++) {
|
|
143
|
+
if (rest[k] === '#' && isBlank(rest[k - 1])) {
|
|
144
|
+
cut = k;
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
values.set(key, stripBlanks(rest.slice(0, cut)));
|
|
149
|
+
i++;
|
|
150
|
+
}
|
|
151
|
+
return { values, invalidLines };
|
|
152
|
+
}
|
|
153
|
+
/** Returned by coerce when the string does not fit the type. */
|
|
154
|
+
export const INVALID = Symbol('invalid');
|
|
155
|
+
const INT = /^[+-]?[0-9]+$/;
|
|
156
|
+
const FLOAT = /^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$/;
|
|
157
|
+
const TRUE = new Set(['1', 'true', 't', 'yes', 'y', 'on']);
|
|
158
|
+
const FALSE = new Set(['0', 'false', 'f', 'no', 'n', 'off']);
|
|
159
|
+
/** Removes space, tab, CR and LF at both ends (not what String.trim removes). */
|
|
160
|
+
function trim(s) {
|
|
161
|
+
const ws = (c) => c === ' ' || c === '\t' || c === '\n' || c === '\r';
|
|
162
|
+
let start = 0;
|
|
163
|
+
let end = s.length;
|
|
164
|
+
while (start < end && ws(s[start]))
|
|
165
|
+
start++;
|
|
166
|
+
while (end > start && ws(s[end - 1]))
|
|
167
|
+
end--;
|
|
168
|
+
return s.slice(start, end);
|
|
169
|
+
}
|
|
170
|
+
function coerceInt(s) {
|
|
171
|
+
const t = trim(s);
|
|
172
|
+
if (!INT.test(t))
|
|
173
|
+
return INVALID;
|
|
174
|
+
const n = Number(t);
|
|
175
|
+
// JavaScript numbers are exact only up to ±(2^53−1); beyond that is invalid here.
|
|
176
|
+
if (!Number.isSafeInteger(n))
|
|
177
|
+
return INVALID;
|
|
178
|
+
return n === 0 ? 0 : n; // no negative zero
|
|
179
|
+
}
|
|
180
|
+
function coerceFloat(s) {
|
|
181
|
+
const t = trim(s);
|
|
182
|
+
if (!FLOAT.test(t))
|
|
183
|
+
return INVALID;
|
|
184
|
+
const n = Number(t);
|
|
185
|
+
return Number.isFinite(n) ? n : INVALID;
|
|
186
|
+
}
|
|
187
|
+
function coerceBool(s) {
|
|
188
|
+
const t = trim(s).toLowerCase();
|
|
189
|
+
if (TRUE.has(t))
|
|
190
|
+
return true;
|
|
191
|
+
if (FALSE.has(t))
|
|
192
|
+
return false;
|
|
193
|
+
return INVALID;
|
|
194
|
+
}
|
|
195
|
+
function allFinite(v) {
|
|
196
|
+
if (typeof v === 'number')
|
|
197
|
+
return Number.isFinite(v);
|
|
198
|
+
if (Array.isArray(v))
|
|
199
|
+
return v.every(allFinite);
|
|
200
|
+
if (typeof v === 'object' && v !== null)
|
|
201
|
+
return Object.values(v).every(allFinite);
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
/** Strict JSON; numbers that do not fit a double are invalid. */
|
|
205
|
+
function parseJson(t) {
|
|
206
|
+
try {
|
|
207
|
+
const v = JSON.parse(t);
|
|
208
|
+
return allFinite(v) ? v : INVALID;
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
return INVALID; // SyntaxError, or RangeError on absurd nesting
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
function coerceScalar(type, s) {
|
|
215
|
+
switch (type) {
|
|
216
|
+
case 'str':
|
|
217
|
+
return s;
|
|
218
|
+
case 'int':
|
|
219
|
+
return coerceInt(s);
|
|
220
|
+
case 'float':
|
|
221
|
+
return coerceFloat(s);
|
|
222
|
+
case 'bool':
|
|
223
|
+
return coerceBool(s);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
function coerceJsonElement(el, x) {
|
|
227
|
+
if (typeof x === 'string')
|
|
228
|
+
return coerceScalar(el, x);
|
|
229
|
+
if (typeof x === 'boolean')
|
|
230
|
+
return el === 'bool' ? x : INVALID;
|
|
231
|
+
if (typeof x === 'number') {
|
|
232
|
+
if (el === 'float')
|
|
233
|
+
return x; // finite: parseJson checked
|
|
234
|
+
if (el === 'int' && Number.isSafeInteger(x))
|
|
235
|
+
return x === 0 ? 0 : x;
|
|
236
|
+
}
|
|
237
|
+
return INVALID;
|
|
238
|
+
}
|
|
239
|
+
/** Coerces the string to the type; returns INVALID if it does not fit. */
|
|
240
|
+
export function coerce(type, s) {
|
|
241
|
+
switch (type) {
|
|
242
|
+
case 'str':
|
|
243
|
+
case 'int':
|
|
244
|
+
case 'float':
|
|
245
|
+
case 'bool':
|
|
246
|
+
return coerceScalar(type, s);
|
|
247
|
+
case 'json':
|
|
248
|
+
return parseJson(trim(s));
|
|
249
|
+
case 'list[str]':
|
|
250
|
+
case 'list[int]':
|
|
251
|
+
case 'list[float]':
|
|
252
|
+
case 'list[bool]': {
|
|
253
|
+
const el = type.slice(5, -1);
|
|
254
|
+
const t = trim(s);
|
|
255
|
+
if (t === '')
|
|
256
|
+
return [];
|
|
257
|
+
let out;
|
|
258
|
+
if (t.startsWith('[')) {
|
|
259
|
+
const arr = parseJson(t);
|
|
260
|
+
if (!Array.isArray(arr))
|
|
261
|
+
return INVALID;
|
|
262
|
+
out = arr.map((x) => coerceJsonElement(el, x));
|
|
263
|
+
}
|
|
264
|
+
else {
|
|
265
|
+
out = t.split(',').map((part) => coerceScalar(el, trim(part)));
|
|
266
|
+
}
|
|
267
|
+
return out.includes(INVALID) ? INVALID : out;
|
|
268
|
+
}
|
|
269
|
+
default:
|
|
270
|
+
throw new TypeError(`esr: unknown field type ${String(type)}`);
|
|
271
|
+
}
|
|
272
|
+
}
|
package/dist/fields.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { type FieldType } from './core.js';
|
|
2
|
+
import { type FieldSpec } from './settings.js';
|
|
3
|
+
declare const FIELD: unique symbol;
|
|
4
|
+
/** A declared field delivering a `T`. Made by str(), int(), float(), bool(), list() and json(). */
|
|
5
|
+
export interface Field<T> {
|
|
6
|
+
readonly type: FieldType;
|
|
7
|
+
readonly variable?: string;
|
|
8
|
+
readonly hasDefault: boolean;
|
|
9
|
+
readonly default?: unknown;
|
|
10
|
+
/** Type-level only: what the field delivers. */
|
|
11
|
+
readonly _value?: T;
|
|
12
|
+
readonly [FIELD]: true;
|
|
13
|
+
}
|
|
14
|
+
export interface FieldOptions<D = never> {
|
|
15
|
+
/** The variable to read instead of the one derived from the field name. */
|
|
16
|
+
variable?: string;
|
|
17
|
+
/** Used, as declared, when no source has the variable. Makes the field optional. */
|
|
18
|
+
default?: D;
|
|
19
|
+
}
|
|
20
|
+
/** A string, taken as it is. */
|
|
21
|
+
export declare function str<D = never>(options?: FieldOptions<D>): Field<string | NoInfer<D>>;
|
|
22
|
+
/** An integer (`[+-]?[0-9]+`, within ±(2^53−1)). */
|
|
23
|
+
export declare function int<D = never>(options?: FieldOptions<D>): Field<number | NoInfer<D>>;
|
|
24
|
+
/** A finite decimal number. */
|
|
25
|
+
export declare function float<D = never>(options?: FieldOptions<D>): Field<number | NoInfer<D>>;
|
|
26
|
+
/** `1 true t yes y on` / `0 false f no n off`, in any case. */
|
|
27
|
+
export declare function bool<D = never>(options?: FieldOptions<D>): Field<boolean | NoInfer<D>>;
|
|
28
|
+
/**
|
|
29
|
+
* A list of str, int, float or bool: `a,b,c` or a JSON array.
|
|
30
|
+
*
|
|
31
|
+
* hosts: list(str(), { default: [] })
|
|
32
|
+
*/
|
|
33
|
+
export declare function list<T>(element: Field<T>, options?: {
|
|
34
|
+
variable?: string;
|
|
35
|
+
default?: readonly T[];
|
|
36
|
+
}): Field<T[]>;
|
|
37
|
+
export declare function list<T>(element: Field<T>, options: {
|
|
38
|
+
variable?: string;
|
|
39
|
+
default: null;
|
|
40
|
+
}): Field<T[] | null>;
|
|
41
|
+
/**
|
|
42
|
+
* Any JSON value. The type parameter says what the application expects; it is
|
|
43
|
+
* not checked.
|
|
44
|
+
*
|
|
45
|
+
* flags: json<{ beta: boolean }>()
|
|
46
|
+
*/
|
|
47
|
+
export declare function json<T = unknown>(options?: FieldOptions<T>): Field<T>;
|
|
48
|
+
/** Project and version are constants in the code; the environment never is. */
|
|
49
|
+
export interface Declaration {
|
|
50
|
+
/** Project slug. */
|
|
51
|
+
project: string;
|
|
52
|
+
/** Version name. */
|
|
53
|
+
version: string;
|
|
54
|
+
/** Path of the .env file instead of `.env` in the working directory. ESR_ENV_FILE still wins. */
|
|
55
|
+
envFile?: string;
|
|
56
|
+
}
|
|
57
|
+
export type Fields = Readonly<Record<string, Field<unknown>>>;
|
|
58
|
+
/** The settings object a set of field declarations loads into. */
|
|
59
|
+
export type SettingsOf<F extends Fields> = {
|
|
60
|
+
readonly [K in keyof F]: F[K] extends Field<infer T> ? T : never;
|
|
61
|
+
};
|
|
62
|
+
/** Turns a declaration into what the loader works with; throws TypeError if it is wrong. */
|
|
63
|
+
export declare function specsOf(fields: Fields): FieldSpec[];
|
|
64
|
+
/**
|
|
65
|
+
* Loads the settings once, at start. Values come, per field, from the first
|
|
66
|
+
* source that has its variable: the process environment, the .env file, the
|
|
67
|
+
* esr agent, the default. Rejects with one SettingsError naming every problem
|
|
68
|
+
* and saying what to do.
|
|
69
|
+
*
|
|
70
|
+
* const settings = await loadSettings({ project: 'shop', version: 'main' }, {
|
|
71
|
+
* databaseUrl: str(),
|
|
72
|
+
* debug: bool({ default: false }),
|
|
73
|
+
* token: str({ variable: 'SERVICE_TOKEN' }),
|
|
74
|
+
* });
|
|
75
|
+
*/
|
|
76
|
+
export declare function loadSettings<const F extends Fields>(declaration: Declaration, fields: F): Promise<SettingsOf<F>>;
|
|
77
|
+
export {};
|
package/dist/fields.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// The declaration idiom (docs/contracts.md §8.1): field builders whose types
|
|
2
|
+
// make up the type of the loaded settings object.
|
|
3
|
+
import { variableName } from './core.js';
|
|
4
|
+
import { load } from './settings.js';
|
|
5
|
+
const FIELD = Symbol('esr.field');
|
|
6
|
+
function make(type, options) {
|
|
7
|
+
if (options !== undefined && (typeof options !== 'object' || options === null)) {
|
|
8
|
+
throw new TypeError('esr: field options must be an object like { default: …, variable: "…" }');
|
|
9
|
+
}
|
|
10
|
+
const variable = options?.variable;
|
|
11
|
+
if (variable !== undefined && (typeof variable !== 'string' || variable === '')) {
|
|
12
|
+
throw new TypeError('esr: the variable of a field must be a non-empty string');
|
|
13
|
+
}
|
|
14
|
+
const hasDefault = options !== undefined && Object.hasOwn(options, 'default');
|
|
15
|
+
return Object.freeze({
|
|
16
|
+
type,
|
|
17
|
+
hasDefault,
|
|
18
|
+
...(variable !== undefined ? { variable } : {}),
|
|
19
|
+
...(hasDefault ? { default: options.default } : {}),
|
|
20
|
+
[FIELD]: true,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/** A string, taken as it is. */
|
|
24
|
+
export function str(options) {
|
|
25
|
+
return make('str', options);
|
|
26
|
+
}
|
|
27
|
+
/** An integer (`[+-]?[0-9]+`, within ±(2^53−1)). */
|
|
28
|
+
export function int(options) {
|
|
29
|
+
return make('int', options);
|
|
30
|
+
}
|
|
31
|
+
/** A finite decimal number. */
|
|
32
|
+
export function float(options) {
|
|
33
|
+
return make('float', options);
|
|
34
|
+
}
|
|
35
|
+
/** `1 true t yes y on` / `0 false f no n off`, in any case. */
|
|
36
|
+
export function bool(options) {
|
|
37
|
+
return make('bool', options);
|
|
38
|
+
}
|
|
39
|
+
export function list(element, options) {
|
|
40
|
+
if (!isField(element) || element.type.startsWith('list') || element.type === 'json' || element.hasDefault || element.variable !== undefined) {
|
|
41
|
+
throw new TypeError('esr: list() takes a plain element type: list(str()), list(int()), list(float()) or list(bool())');
|
|
42
|
+
}
|
|
43
|
+
return make(`list[${element.type}]`, options);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Any JSON value. The type parameter says what the application expects; it is
|
|
47
|
+
* not checked.
|
|
48
|
+
*
|
|
49
|
+
* flags: json<{ beta: boolean }>()
|
|
50
|
+
*/
|
|
51
|
+
export function json(options) {
|
|
52
|
+
return make('json', options);
|
|
53
|
+
}
|
|
54
|
+
function isField(v) {
|
|
55
|
+
return typeof v === 'object' && v !== null && v[FIELD] === true;
|
|
56
|
+
}
|
|
57
|
+
/** Turns a declaration into what the loader works with; throws TypeError if it is wrong. */
|
|
58
|
+
export function specsOf(fields) {
|
|
59
|
+
if (typeof fields !== 'object' || fields === null)
|
|
60
|
+
throw new TypeError('esr: loadSettings needs an object of fields');
|
|
61
|
+
return Object.entries(fields).map(([name, field]) => {
|
|
62
|
+
if (!isField(field)) {
|
|
63
|
+
throw new TypeError(`esr: field ${name} must be declared with str(), int(), float(), bool(), list() or json()`);
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
name,
|
|
67
|
+
type: field.type,
|
|
68
|
+
variable: field.variable ?? variableName(name),
|
|
69
|
+
hasDefault: field.hasDefault,
|
|
70
|
+
...(field.hasDefault ? { default: field.default } : {}),
|
|
71
|
+
};
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Loads the settings once, at start. Values come, per field, from the first
|
|
76
|
+
* source that has its variable: the process environment, the .env file, the
|
|
77
|
+
* esr agent, the default. Rejects with one SettingsError naming every problem
|
|
78
|
+
* and saying what to do.
|
|
79
|
+
*
|
|
80
|
+
* const settings = await loadSettings({ project: 'shop', version: 'main' }, {
|
|
81
|
+
* databaseUrl: str(),
|
|
82
|
+
* debug: bool({ default: false }),
|
|
83
|
+
* token: str({ variable: 'SERVICE_TOKEN' }),
|
|
84
|
+
* });
|
|
85
|
+
*/
|
|
86
|
+
export async function loadSettings(declaration, fields) {
|
|
87
|
+
if (typeof declaration !== 'object' || declaration === null) {
|
|
88
|
+
throw new TypeError('esr: loadSettings needs { project, version } as its first argument');
|
|
89
|
+
}
|
|
90
|
+
const { project, version, envFile } = declaration;
|
|
91
|
+
if (typeof project !== 'string' || project === '' || typeof version !== 'string' || version === '') {
|
|
92
|
+
throw new TypeError('esr: the declaration must name its project and version: { project: "…", version: "…" }');
|
|
93
|
+
}
|
|
94
|
+
if (envFile !== undefined && typeof envFile !== 'string')
|
|
95
|
+
throw new TypeError('esr: envFile must be a string');
|
|
96
|
+
const values = await load({ project, version, envFile, fields: specsOf(fields) });
|
|
97
|
+
return Object.freeze({ ...values });
|
|
98
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { bool, float, int, json, list, loadSettings, str } from './fields.js';
|
|
2
|
+
export type { Declaration, Field, FieldOptions, Fields, SettingsOf } from './fields.js';
|
|
3
|
+
export { SettingsError } from './settings.js';
|
|
4
|
+
export type { SettingsErrorCode } from './settings.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// env-plane settings for TypeScript and JavaScript: typed settings from the
|
|
2
|
+
// local esr agent. No runtime dependencies. See README.md and
|
|
3
|
+
// docs/contracts.md §8.
|
|
4
|
+
export { bool, float, int, json, list, loadSettings, str } from './fields.js';
|
|
5
|
+
export { SettingsError } from './settings.js';
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type Environ } from './agent.js';
|
|
2
|
+
import { type FieldType } from './core.js';
|
|
3
|
+
export type SettingsErrorCode = 'agent_unavailable' | 'not_signed_in' | 'forbidden' | 'not_found' | 'version_mismatch' | 'server_unreachable' | 'agent_error' | 'invalid_settings';
|
|
4
|
+
/**
|
|
5
|
+
* Settings could not be loaded. The message says what to do and never
|
|
6
|
+
* contains a value. For `invalid_settings`, `missing` and `invalid` hold the
|
|
7
|
+
* variable names, sorted.
|
|
8
|
+
*/
|
|
9
|
+
export declare class SettingsError extends Error {
|
|
10
|
+
readonly code: SettingsErrorCode;
|
|
11
|
+
readonly missing: readonly string[];
|
|
12
|
+
readonly invalid: readonly string[];
|
|
13
|
+
constructor(code: SettingsErrorCode, message: string, missing?: readonly string[], invalid?: readonly string[]);
|
|
14
|
+
}
|
|
15
|
+
/** One declared field, as the loader sees it. */
|
|
16
|
+
export interface FieldSpec {
|
|
17
|
+
readonly name: string;
|
|
18
|
+
readonly type: FieldType;
|
|
19
|
+
readonly variable: string;
|
|
20
|
+
readonly hasDefault: boolean;
|
|
21
|
+
readonly default?: unknown;
|
|
22
|
+
}
|
|
23
|
+
export interface DeclarationSpec {
|
|
24
|
+
readonly project: string;
|
|
25
|
+
readonly version: string;
|
|
26
|
+
/** Path of the .env file instead of `.env` in the working directory. */
|
|
27
|
+
readonly envFile?: string | undefined;
|
|
28
|
+
readonly fields: readonly FieldSpec[];
|
|
29
|
+
}
|
|
30
|
+
/** The process as the loader sees it; tests substitute it. */
|
|
31
|
+
export interface Runtime {
|
|
32
|
+
readonly environ: Environ;
|
|
33
|
+
readonly warn: (line: string) => void;
|
|
34
|
+
readonly cwd: string;
|
|
35
|
+
}
|
|
36
|
+
export declare function processRuntime(): Runtime;
|
|
37
|
+
/** Loads the declared fields; resolves to the values by field name or rejects with a SettingsError. */
|
|
38
|
+
export declare function load(decl: DeclarationSpec, rt?: Runtime): Promise<Record<string, unknown>>;
|
package/dist/settings.js
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// Loading (docs/contracts.md §8.2) and errors (§8.5), independent of how the
|
|
2
|
+
// settings were declared.
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { resolve as resolvePath } from 'node:path';
|
|
5
|
+
import process from 'node:process';
|
|
6
|
+
import { TextDecoder } from 'node:util';
|
|
7
|
+
import { ConnectError, findAgent, ProtocolError, REPORT_TIMEOUT, request } from './agent.js';
|
|
8
|
+
import { coerce, INVALID, parseDotenv } from './core.js';
|
|
9
|
+
/**
|
|
10
|
+
* Settings could not be loaded. The message says what to do and never
|
|
11
|
+
* contains a value. For `invalid_settings`, `missing` and `invalid` hold the
|
|
12
|
+
* variable names, sorted.
|
|
13
|
+
*/
|
|
14
|
+
export class SettingsError extends Error {
|
|
15
|
+
code;
|
|
16
|
+
missing;
|
|
17
|
+
invalid;
|
|
18
|
+
constructor(code, message, missing = [], invalid = []) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = 'SettingsError';
|
|
21
|
+
this.code = code;
|
|
22
|
+
this.missing = missing;
|
|
23
|
+
this.invalid = invalid;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export function processRuntime() {
|
|
27
|
+
return {
|
|
28
|
+
environ: process.env,
|
|
29
|
+
warn: (line) => {
|
|
30
|
+
try {
|
|
31
|
+
process.stderr.write(line + '\n');
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// stderr is gone; nothing to do
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
cwd: process.cwd(),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
41
|
+
/** Agent-supplied text for a message: one line, printable, bounded. */
|
|
42
|
+
function clip(text, limit = 200) {
|
|
43
|
+
if (typeof text !== 'string')
|
|
44
|
+
return '';
|
|
45
|
+
const chars = Array.from(text.replace(/[\p{C}\p{Z}]/gu, ' ').trim());
|
|
46
|
+
return chars.length > limit ? chars.slice(0, limit).join('') + '…' : chars.join('');
|
|
47
|
+
}
|
|
48
|
+
function unavailable(agent, reason) {
|
|
49
|
+
if (agent !== undefined && agent.sock === undefined) {
|
|
50
|
+
return new SettingsError('agent_unavailable', `esr: cannot reach the esr agent at ${agent.address} (ESR_AGENT_URL): ${reason}. ` +
|
|
51
|
+
'On the host, run `esr login` and then `esr link`, and put the ESR_AGENT_URL and ESR_AGENT_TOKEN it ' +
|
|
52
|
+
"prints into the container's environment. For tests and CI without an agent, set ESR_OFFLINE=1.");
|
|
53
|
+
}
|
|
54
|
+
const where = agent !== undefined ? ` at ${agent.address}` : '';
|
|
55
|
+
return new SettingsError('agent_unavailable', `esr: cannot reach the esr agent${where}: ${reason}. ` +
|
|
56
|
+
'Run `esr login` to start it and sign in, then start the app again. In a deployment, start the app with ' +
|
|
57
|
+
'`esr run -- <command>`. For tests and CI without an agent, set ESR_OFFLINE=1.');
|
|
58
|
+
}
|
|
59
|
+
/** The agent's current environment, for the `forbidden` message. */
|
|
60
|
+
async function environmentOf(agent) {
|
|
61
|
+
try {
|
|
62
|
+
const { status, body } = await request(agent, 'GET', '/v1/status', undefined, REPORT_TIMEOUT);
|
|
63
|
+
return status === 200 && isRecord(body) ? clip(body['environment'], 100) : '';
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return '';
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async function agentFailure(decl, agent, status, body) {
|
|
70
|
+
const err = isRecord(body) && isRecord(body['error']) ? body['error'] : undefined;
|
|
71
|
+
const code = err !== undefined && typeof err['code'] === 'string' ? err['code'] : undefined;
|
|
72
|
+
const message = err !== undefined ? clip(err['message']) : '';
|
|
73
|
+
const p = decl.project;
|
|
74
|
+
const v = decl.version;
|
|
75
|
+
if (status !== 200) {
|
|
76
|
+
switch (code) {
|
|
77
|
+
case 'not_signed_in':
|
|
78
|
+
return new SettingsError('not_signed_in', 'esr: the esr agent is not signed in. Run `esr login`, then start the app again.');
|
|
79
|
+
case 'session_expired':
|
|
80
|
+
return new SettingsError('not_signed_in', 'esr: your esr session has expired. Run `esr login`, then start the app again.');
|
|
81
|
+
case 'forbidden': {
|
|
82
|
+
const env = await environmentOf(agent);
|
|
83
|
+
const where = env !== '' ? `environment "${env}"` : "the agent's current environment (see `esr status`)";
|
|
84
|
+
return new SettingsError('forbidden', `esr: no access to project "${p}", version "${v}" in ${where}. Ask an admin of your organisation for ` +
|
|
85
|
+
'access to this project and environment, or switch to an environment you may use with ' +
|
|
86
|
+
'`esr env use <name>`.');
|
|
87
|
+
}
|
|
88
|
+
case 'not_found':
|
|
89
|
+
return new SettingsError('not_found', `esr: project "${p}" or its version "${v}" does not exist (or you may not see it). Check project and ` +
|
|
90
|
+
'version in the settings declaration in the code, and the organisation in `esr status`.');
|
|
91
|
+
case 'version_mismatch':
|
|
92
|
+
return new SettingsError('version_mismatch', `esr: the deployment token is not for project "${p}", version "${v}" (or not for this environment). ` +
|
|
93
|
+
'Use the token of this deployment (ESR_TOKEN), or fix project and version in the settings declaration.');
|
|
94
|
+
case 'server_unreachable':
|
|
95
|
+
return new SettingsError('server_unreachable', 'esr: the esr agent cannot reach the env-plane server and has no values it may serve. Check the ' +
|
|
96
|
+
'network connection and start the app again.');
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
let detail = message;
|
|
100
|
+
let hint = 'Update esr with `esr update` and try again.';
|
|
101
|
+
if (status === 200) {
|
|
102
|
+
detail = 'the answer is not a valid resolve response';
|
|
103
|
+
}
|
|
104
|
+
else if (code === 'invalid_link_token') {
|
|
105
|
+
hint = "Check ESR_AGENT_TOKEN: the link token dies with the agent's session; run `esr link` on the host to get the current one.";
|
|
106
|
+
}
|
|
107
|
+
else if (code === 'bad_request') {
|
|
108
|
+
hint = 'The agent did not understand the request (internal error): update esr with `esr update`.';
|
|
109
|
+
}
|
|
110
|
+
const shown = code ? `"${clip(code, 60)}"` : 'none';
|
|
111
|
+
return new SettingsError('agent_error', `esr: unexpected answer from the esr agent at ${agent.address} (status ${status}, code ${shown})` + (detail !== '' ? `: ${detail}` : '') + `. ${hint}`);
|
|
112
|
+
}
|
|
113
|
+
function invalidSettings(decl, missing, invalid, userValues) {
|
|
114
|
+
const plain = missing.filter((n) => !userValues.has(n));
|
|
115
|
+
const own = missing.filter((n) => userValues.has(n));
|
|
116
|
+
const names = [...invalid.keys()].sort(byCodeUnit);
|
|
117
|
+
const lines = [`esr: the settings of project "${decl.project}", version "${decl.version}" cannot be loaded.`];
|
|
118
|
+
if (plain.length > 0)
|
|
119
|
+
lines.push(' missing: ' + plain.join(', '));
|
|
120
|
+
if (own.length > 0)
|
|
121
|
+
lines.push(' missing, your own value is needed: ' + own.join(', '));
|
|
122
|
+
if (names.length > 0)
|
|
123
|
+
lines.push(' invalid: ' + names.map((n) => `${n} (expected ${invalid.get(n)})`).join(', '));
|
|
124
|
+
if (plain.length > 0) {
|
|
125
|
+
lines.push('Missing values: set them in env-plane for this project, version and environment, or locally in .env or the process environment.');
|
|
126
|
+
}
|
|
127
|
+
if (own.length > 0)
|
|
128
|
+
lines.push('User-specific secrets: every user must set their own value in env-plane (or locally in .env).');
|
|
129
|
+
if (names.length > 0)
|
|
130
|
+
lines.push('Invalid values: correct them where they are set (the process environment, .env or env-plane).');
|
|
131
|
+
return new SettingsError('invalid_settings', lines.join('\n'), missing, names);
|
|
132
|
+
}
|
|
133
|
+
/** Sorts like the other libraries: by code point (equal to code unit order for the names that occur). */
|
|
134
|
+
function byCodeUnit(a, b) {
|
|
135
|
+
const x = Array.from(a);
|
|
136
|
+
const y = Array.from(b);
|
|
137
|
+
for (let i = 0; i < x.length && i < y.length; i++) {
|
|
138
|
+
const d = x[i].codePointAt(0) - y[i].codePointAt(0);
|
|
139
|
+
if (d !== 0)
|
|
140
|
+
return d;
|
|
141
|
+
}
|
|
142
|
+
return x.length - y.length;
|
|
143
|
+
}
|
|
144
|
+
/** The values of a LocalResolveResponse, or undefined if it is malformed. */
|
|
145
|
+
function parseResolve(body) {
|
|
146
|
+
if (!isRecord(body) || !Array.isArray(body['values']))
|
|
147
|
+
return undefined;
|
|
148
|
+
const values = new Map();
|
|
149
|
+
for (const v of body['values']) {
|
|
150
|
+
if (!isRecord(v))
|
|
151
|
+
return undefined;
|
|
152
|
+
const { name, value, kind } = v;
|
|
153
|
+
if (typeof name !== 'string' || typeof value !== 'string' || typeof kind !== 'string')
|
|
154
|
+
return undefined;
|
|
155
|
+
values.set(name, { value, kind });
|
|
156
|
+
}
|
|
157
|
+
const user = body['missing_user_values'] ?? [];
|
|
158
|
+
if (!Array.isArray(user) || !user.every((x) => typeof x === 'string'))
|
|
159
|
+
return undefined;
|
|
160
|
+
return { values, userValues: new Set(user) };
|
|
161
|
+
}
|
|
162
|
+
function readDotenv(decl, rt) {
|
|
163
|
+
let path = rt.environ['ESR_ENV_FILE'];
|
|
164
|
+
if (path === undefined)
|
|
165
|
+
path = decl.envFile ?? '.env';
|
|
166
|
+
if (path === '')
|
|
167
|
+
return new Map();
|
|
168
|
+
path = resolvePath(rt.cwd, path);
|
|
169
|
+
let data;
|
|
170
|
+
try {
|
|
171
|
+
data = readFileSync(path);
|
|
172
|
+
}
|
|
173
|
+
catch (e) {
|
|
174
|
+
const code = e.code;
|
|
175
|
+
if (code !== 'ENOENT' && code !== 'ENOTDIR')
|
|
176
|
+
rt.warn(`esr: warning: .env file ${path} could not be read and was ignored`);
|
|
177
|
+
return new Map();
|
|
178
|
+
}
|
|
179
|
+
const { values, invalidLines } = parseDotenv(new TextDecoder('utf-8', { ignoreBOM: true }).decode(data));
|
|
180
|
+
for (const n of invalidLines)
|
|
181
|
+
rt.warn(`esr: warning: .env line ${n} is not valid and was ignored`);
|
|
182
|
+
return values;
|
|
183
|
+
}
|
|
184
|
+
/** Loads the declared fields; resolves to the values by field name or rejects with a SettingsError. */
|
|
185
|
+
export async function load(decl, rt = processRuntime()) {
|
|
186
|
+
const has = (name) => Object.hasOwn(rt.environ, name) && rt.environ[name] !== undefined;
|
|
187
|
+
// 1. The agent, unless ESR_OFFLINE is exactly "1". Any failure stops here.
|
|
188
|
+
let agent;
|
|
189
|
+
let agentValues = new Map();
|
|
190
|
+
let userValues = new Set();
|
|
191
|
+
if (rt.environ['ESR_OFFLINE'] !== '1') {
|
|
192
|
+
let answer;
|
|
193
|
+
try {
|
|
194
|
+
agent = findAgent(rt.environ);
|
|
195
|
+
answer = await request(agent, 'POST', '/v1/resolve', { project: decl.project, version: decl.version });
|
|
196
|
+
}
|
|
197
|
+
catch (e) {
|
|
198
|
+
if (e instanceof ConnectError)
|
|
199
|
+
throw unavailable(e.agent ?? agent, e.message);
|
|
200
|
+
if (e instanceof ProtocolError) {
|
|
201
|
+
throw new SettingsError('agent_error', `esr: no usable answer from the esr agent at ${agent?.address ?? '?'} (status none, code none): ${e.message}. ` +
|
|
202
|
+
'Check `esr status`; update esr with `esr update` if this persists.');
|
|
203
|
+
}
|
|
204
|
+
throw e;
|
|
205
|
+
}
|
|
206
|
+
const parsed = answer.status === 200 ? parseResolve(answer.body) : undefined;
|
|
207
|
+
if (parsed === undefined)
|
|
208
|
+
throw await agentFailure(decl, agent, answer.status, answer.body);
|
|
209
|
+
agentValues = parsed.values;
|
|
210
|
+
userValues = parsed.userValues;
|
|
211
|
+
}
|
|
212
|
+
// 2. The .env file.
|
|
213
|
+
const dotenv = readDotenv(decl, rt);
|
|
214
|
+
// 3.–5. First source that has the variable; coerce; collect every problem.
|
|
215
|
+
const values = Object.create(null);
|
|
216
|
+
const missing = new Set();
|
|
217
|
+
const invalid = new Map();
|
|
218
|
+
const overrides = new Map(); // variable -> "the environment" | ".env"
|
|
219
|
+
for (const f of decl.fields) {
|
|
220
|
+
const name = f.variable;
|
|
221
|
+
let raw;
|
|
222
|
+
let source = '';
|
|
223
|
+
const fromAgent = agentValues.get(name);
|
|
224
|
+
if (has(name)) {
|
|
225
|
+
raw = rt.environ[name];
|
|
226
|
+
source = 'the environment';
|
|
227
|
+
}
|
|
228
|
+
else if (dotenv.has(name)) {
|
|
229
|
+
raw = dotenv.get(name);
|
|
230
|
+
source = '.env';
|
|
231
|
+
}
|
|
232
|
+
else if (fromAgent !== undefined) {
|
|
233
|
+
raw = fromAgent.value;
|
|
234
|
+
}
|
|
235
|
+
else if (f.hasDefault) {
|
|
236
|
+
values[f.name] = f.default;
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
missing.add(name);
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
if (source !== '' && fromAgent !== undefined && (fromAgent.kind === 'secret' || fromAgent.kind === 'provider_token') && fromAgent.value !== raw) {
|
|
244
|
+
overrides.set(name, source);
|
|
245
|
+
}
|
|
246
|
+
const value = coerce(f.type, raw);
|
|
247
|
+
if (value === INVALID)
|
|
248
|
+
invalid.set(name, f.type);
|
|
249
|
+
else
|
|
250
|
+
values[f.name] = value;
|
|
251
|
+
}
|
|
252
|
+
if (missing.size > 0 || invalid.size > 0) {
|
|
253
|
+
throw invalidSettings(decl, [...missing].sort(byCodeUnit), invalid, userValues);
|
|
254
|
+
}
|
|
255
|
+
// 6. Secret overrides: warn and report names. Never a value.
|
|
256
|
+
if (overrides.size > 0) {
|
|
257
|
+
const names = [...overrides.keys()].sort(byCodeUnit);
|
|
258
|
+
for (const name of names)
|
|
259
|
+
rt.warn(`esr: warning: secret ${name} is overridden by ${overrides.get(name)}`);
|
|
260
|
+
if (agent !== undefined) {
|
|
261
|
+
try {
|
|
262
|
+
await request(agent, 'POST', '/v1/overrides', { project: decl.project, version: decl.version, fields: names }, REPORT_TIMEOUT);
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
// best effort
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return values;
|
|
270
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@labsbit/esr",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "env-plane settings: typed configuration and secrets from the local esr agent",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/labsbit/esr-sdk.git",
|
|
8
|
+
"directory": "typescript"
|
|
9
|
+
},
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"type": "module",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=20"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "tsc -p tsconfig.json",
|
|
28
|
+
"typecheck": "tsc -p test/tsconfig.json",
|
|
29
|
+
"test": "npm run build && npm run typecheck && node --test test/*.test.mjs"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"typescript": "6.0.3"
|
|
33
|
+
},
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"access": "public",
|
|
36
|
+
"provenance": true
|
|
37
|
+
}
|
|
38
|
+
}
|