@thisisamank/noenv-cli 0.0.0-stage → 0.2.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/dist/noenv.js ADDED
@@ -0,0 +1,2492 @@
1
+ #!/usr/bin/env node
2
+
3
+ // ../packages/config/src/names.ts
4
+ var IDENTIFIER = /^[A-Za-z0-9_-]+$/;
5
+ var ENV_VAR_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
6
+ var REPO = /^[a-z0-9.-]+(\/[a-z0-9._~-]+)+$/;
7
+
8
+ // src/deployment.ts
9
+ import { homedir } from "node:os";
10
+ import { join } from "node:path";
11
+
12
+ // src/files.ts
13
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
14
+ import { dirname } from "node:path";
15
+ async function readJsonFile(path) {
16
+ try {
17
+ return JSON.parse(await readFile(path, "utf8"));
18
+ } catch (error) {
19
+ if (error.code === "ENOENT") return null;
20
+ throw error;
21
+ }
22
+ }
23
+ async function writeJsonFile(path, value, flag = "w") {
24
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
25
+ await writeFile(path, JSON.stringify(value), { mode: 384, flag });
26
+ }
27
+ async function removeFile(path) {
28
+ await rm(path, { force: true });
29
+ }
30
+
31
+ // src/deployment.ts
32
+ function configDir(env = process.env) {
33
+ return env.NOENV_CONFIG_DIR ?? join(env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "noenv");
34
+ }
35
+ function deploymentAt(value, env = process.env, account) {
36
+ const url = URL.parse(value);
37
+ if (!url || url.protocol !== "https:" && url.protocol !== "http:") {
38
+ throw new Error(`${value} is not an http or https URL`);
39
+ }
40
+ return { url: url.origin, dir: join(configDir(env), url.host.replace(":", "_")), fetch: globalThis.fetch, account };
41
+ }
42
+ async function readAccounts(env = process.env) {
43
+ return await readJsonFile(accountsPath(env)) ?? { accounts: {} };
44
+ }
45
+ async function writeAccounts(accounts, env = process.env) {
46
+ await writeJsonFile(accountsPath(env), accounts);
47
+ }
48
+ function matchAccount(accounts, repo) {
49
+ let best;
50
+ for (const [name2, account] of Object.entries(accounts.accounts)) {
51
+ for (const prefix of account.match) {
52
+ const clean = prefix.toLowerCase().replace(/\/+$/, "");
53
+ if ((repo === clean || repo.startsWith(`${clean}/`)) && clean.length > (best?.length ?? -1)) {
54
+ best = { name: name2, length: clean.length };
55
+ }
56
+ }
57
+ }
58
+ return best?.name;
59
+ }
60
+ async function resolveDeployment(repo, env = process.env) {
61
+ const accounts = await readAccounts(env);
62
+ const name2 = env.NOENV_ACCOUNT || (repo ? matchAccount(accounts, repo) : void 0) || accounts.default;
63
+ if (name2) {
64
+ const account = accounts.accounts[name2];
65
+ if (!account) throw new Error(`there is no account named "${name2}", run \`noenv account list\``);
66
+ return deploymentAt(account.url, env, name2);
67
+ }
68
+ return env.NOENV_URL ? deploymentAt(env.NOENV_URL, env) : null;
69
+ }
70
+ function accountsPath(env) {
71
+ return join(configDir(env), "accounts.json");
72
+ }
73
+
74
+ // src/session.ts
75
+ import { spawn } from "node:child_process";
76
+ import { hostname } from "node:os";
77
+ import { join as join3 } from "node:path";
78
+
79
+ // package.json
80
+ var package_default = {
81
+ name: "@thisisamank/noenv-cli",
82
+ version: "0.2.0",
83
+ description: "Encrypted environment variables that load when you cd into a repo. CLI for noenv.",
84
+ type: "module",
85
+ bin: {
86
+ noenv: "dist/noenv.js"
87
+ },
88
+ files: [
89
+ "dist",
90
+ "CHANGELOG.md"
91
+ ],
92
+ engines: {
93
+ node: ">=22"
94
+ },
95
+ repository: {
96
+ type: "git",
97
+ url: "git+https://github.com/thisisamank/noenv.git",
98
+ directory: "cli"
99
+ },
100
+ homepage: "https://github.com/thisisamank/noenv#readme",
101
+ keywords: [
102
+ "secrets",
103
+ "env",
104
+ "dotenv",
105
+ "cloudflare",
106
+ "cli"
107
+ ],
108
+ scripts: {
109
+ build: "esbuild src/main.ts --bundle --platform=node --format=esm --target=node22 --outfile=dist/noenv.js",
110
+ prepublishOnly: "node ../scripts/check-npm-account.ts && npm run build"
111
+ },
112
+ devDependencies: {
113
+ "@noenv/config": "*",
114
+ "@noenv/crypto": "*",
115
+ "@noenv/dotenv": "*",
116
+ "@noenv/policy": "*",
117
+ "@noenv/worker": "*",
118
+ esbuild: "^0.28.2"
119
+ },
120
+ publishConfig: {
121
+ access: "public"
122
+ }
123
+ };
124
+
125
+ // src/version.ts
126
+ var CLI_VERSION = package_default.version;
127
+
128
+ // src/api.ts
129
+ var TIMEOUT_MS = 1e4;
130
+ var ApiError = class extends Error {
131
+ status;
132
+ constructor(status, message) {
133
+ super(message);
134
+ this.status = status;
135
+ }
136
+ };
137
+ async function api(deployment, method, path, options = {}) {
138
+ const headers = { "X-Noenv-Version": CLI_VERSION };
139
+ if (options.token) headers.Authorization = `Bearer ${options.token}`;
140
+ if (options.body !== void 0) headers["Content-Type"] = "application/json";
141
+ const response = await deployment.fetch(deployment.url + path, {
142
+ method,
143
+ headers,
144
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
145
+ redirect: "manual",
146
+ signal: AbortSignal.timeout(TIMEOUT_MS)
147
+ });
148
+ if (response.status >= 300 && response.status < 400) {
149
+ throw new ApiError(response.status, `${deployment.url} redirected the request, check that Cloudflare Access does not protect /v1`);
150
+ }
151
+ const data = response.status === 204 ? null : await response.json().catch(() => void 0);
152
+ if (data === void 0) {
153
+ throw new ApiError(response.status, `${deployment.url} did not return a noenv API response (status ${response.status})`);
154
+ }
155
+ if (!response.ok) {
156
+ throw new ApiError(response.status, data?.error ?? `request failed with status ${response.status}`);
157
+ }
158
+ return data;
159
+ }
160
+ function repoPath(repo) {
161
+ return `/v1/repos/${encodeURIComponent(repo)}`;
162
+ }
163
+ function environmentPath(repo, environment) {
164
+ return `${repoPath(repo)}/environments/${environment}`;
165
+ }
166
+
167
+ // src/identity.ts
168
+ import { join as join2 } from "node:path";
169
+
170
+ // ../packages/crypto/src/encoding.ts
171
+ var encoder = new TextEncoder();
172
+ var decoder = new TextDecoder();
173
+ function toBytes(text3) {
174
+ return encoder.encode(text3);
175
+ }
176
+ function fromBytes(bytes) {
177
+ return decoder.decode(bytes);
178
+ }
179
+ function toBase64(bytes) {
180
+ let binary = "";
181
+ for (const byte of bytes) binary += String.fromCharCode(byte);
182
+ return btoa(binary);
183
+ }
184
+ function fromBase64(text3) {
185
+ return Uint8Array.from(atob(text3), (char) => char.charCodeAt(0));
186
+ }
187
+
188
+ // ../packages/crypto/src/keys.ts
189
+ var ECDH = { name: "ECDH", namedCurve: "P-256" };
190
+ async function generateKeyPair() {
191
+ return crypto.subtle.generateKey(ECDH, true, ["deriveBits"]);
192
+ }
193
+ async function exportPublicKey(key) {
194
+ return toBase64(new Uint8Array(await crypto.subtle.exportKey("raw", key)));
195
+ }
196
+ async function importPublicKey(text3) {
197
+ return crypto.subtle.importKey("raw", fromBase64(text3), ECDH, true, []);
198
+ }
199
+ async function exportPrivateKey(key) {
200
+ return toBase64(new Uint8Array(await crypto.subtle.exportKey("pkcs8", key)));
201
+ }
202
+ async function importPrivateKey(text3) {
203
+ return crypto.subtle.importKey("pkcs8", fromBase64(text3), ECDH, true, ["deriveBits"]);
204
+ }
205
+
206
+ // ../packages/crypto/src/aead.ts
207
+ var AES_GCM = { name: "AES-GCM", length: 256 };
208
+ var IV_BYTES = 12;
209
+ async function seal(key, plaintext, context) {
210
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
211
+ const ciphertext = await crypto.subtle.encrypt(
212
+ { name: "AES-GCM", iv, additionalData: context },
213
+ key,
214
+ plaintext
215
+ );
216
+ return { iv: toBase64(iv), ciphertext: toBase64(new Uint8Array(ciphertext)) };
217
+ }
218
+ async function open(key, sealed, context) {
219
+ const plaintext = await crypto.subtle.decrypt(
220
+ { name: "AES-GCM", iv: fromBase64(sealed.iv), additionalData: context },
221
+ key,
222
+ fromBase64(sealed.ciphertext)
223
+ );
224
+ return new Uint8Array(plaintext);
225
+ }
226
+
227
+ // ../packages/crypto/src/box.ts
228
+ async function sealTo(recipientPublicKey, plaintext, context) {
229
+ const ephemeral = await generateKeyPair();
230
+ const ephemeralPublicKey = await exportPublicKey(ephemeral.publicKey);
231
+ const key = await deriveKey(ephemeral.privateKey, recipientPublicKey, ephemeralPublicKey, context);
232
+ return { ...await seal(key, plaintext, context), ephemeralPublicKey };
233
+ }
234
+ async function openWith(recipientPrivateKey, sealed, context) {
235
+ const ephemeralKey = await importPublicKey(sealed.ephemeralPublicKey);
236
+ const key = await deriveKey(recipientPrivateKey, ephemeralKey, sealed.ephemeralPublicKey, context);
237
+ return open(key, sealed, context);
238
+ }
239
+ async function deriveKey(privateKey, publicKey, ephemeralPublicKey, context) {
240
+ const shared = await crypto.subtle.deriveBits({ name: "ECDH", public: publicKey }, privateKey, 256);
241
+ const hkdfKey = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
242
+ return crypto.subtle.deriveKey(
243
+ { name: "HKDF", hash: "SHA-256", salt: fromBase64(ephemeralPublicKey), info: context },
244
+ hkdfKey,
245
+ AES_GCM,
246
+ false,
247
+ ["encrypt", "decrypt"]
248
+ );
249
+ }
250
+
251
+ // ../packages/crypto/src/secrets.ts
252
+ async function encryptSecret(environmentPublicKey, value, context) {
253
+ return sealTo(environmentPublicKey, toBytes(value), contextBytes(context));
254
+ }
255
+ async function decryptSecret(environmentPrivateKey, sealed, context) {
256
+ return fromBytes(await openWith(environmentPrivateKey, sealed, contextBytes(context)));
257
+ }
258
+ function contextBytes({ projectId, environment, name: name2 }) {
259
+ return toBytes(`noenv-secret-v1\0${projectId}\0${environment}\0${name2}`);
260
+ }
261
+
262
+ // ../packages/crypto/src/wrap.ts
263
+ var WRAP_CONTEXT = toBytes("noenv-key-wrap-v1");
264
+ async function wrapPrivateKey(privateKey, recipientPublicKey) {
265
+ const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", privateKey));
266
+ return sealTo(recipientPublicKey, pkcs8, WRAP_CONTEXT);
267
+ }
268
+ async function unwrapPrivateKey(wrapped, recipientPrivateKey) {
269
+ const pkcs8 = await openWith(recipientPrivateKey, wrapped, WRAP_CONTEXT);
270
+ return crypto.subtle.importKey("pkcs8", pkcs8, ECDH, true, ["deriveBits"]);
271
+ }
272
+
273
+ // src/identity.ts
274
+ async function loadIdentity(deployment) {
275
+ const stored = await readJsonFile(identityPath(deployment));
276
+ if (!stored) return null;
277
+ return { publicKey: stored.publicKey, privateKey: await importPrivateKey(stored.privateKey) };
278
+ }
279
+ async function ensureIdentity(deployment, token) {
280
+ const local = await loadIdentity(deployment);
281
+ const me = await api(deployment, "GET", "/v1/me", { token });
282
+ if (local && me.publicKey === local.publicKey) return local;
283
+ if (me.publicKey) {
284
+ throw new Error(`your noenv key was registered on another device, copy ${identityPath(deployment)} from that device`);
285
+ }
286
+ const identity = local ?? await createIdentity(deployment);
287
+ await api(deployment, "PUT", "/v1/me/public-key", { token, body: { publicKey: identity.publicKey } });
288
+ return identity;
289
+ }
290
+ async function createIdentity(deployment) {
291
+ const pair = await generateKeyPair();
292
+ const stored = {
293
+ publicKey: await exportPublicKey(pair.publicKey),
294
+ privateKey: await exportPrivateKey(pair.privateKey)
295
+ };
296
+ await writeJsonFile(identityPath(deployment), stored, "wx");
297
+ return { publicKey: stored.publicKey, privateKey: pair.privateKey };
298
+ }
299
+ function identityPath(deployment) {
300
+ return join2(deployment.dir, "identity.json");
301
+ }
302
+
303
+ // src/session.ts
304
+ async function loadSession(deployment) {
305
+ const session = await readJsonFile(sessionPath(deployment));
306
+ if (!session) return null;
307
+ return Date.parse(`${session.expiresAt.replace(" ", "T")}Z`) > Date.now() ? session.token : null;
308
+ }
309
+ async function clearSession(deployment) {
310
+ await removeFile(sessionPath(deployment));
311
+ }
312
+ async function requireSession(deployment) {
313
+ const token = await loadSession(deployment);
314
+ if (!token) {
315
+ throw new Error(`you are not signed in to ${deployment.account ?? deployment.url}, open a new shell or run \`noenv auth${deployment.account ? ` ${deployment.account}` : ""}\``);
316
+ }
317
+ return token;
318
+ }
319
+ async function startSignIn(deployment) {
320
+ const existing = await readJsonFile(pendingPath(deployment));
321
+ if (existing && existing.expiresAt > Date.now()) {
322
+ return { pending: existing, started: false };
323
+ }
324
+ await removeFile(pendingPath(deployment));
325
+ const device = await api(deployment, "POST", "/v1/auth/device");
326
+ if (!device.verificationUriComplete.startsWith(`${deployment.url}/activate`)) {
327
+ throw new Error("the server returned an unexpected sign-in URL");
328
+ }
329
+ const pending = {
330
+ deviceCode: device.deviceCode,
331
+ userCode: device.userCode,
332
+ url: device.verificationUriComplete,
333
+ interval: device.interval,
334
+ expiresAt: Date.now() + device.expiresIn * 1e3
335
+ };
336
+ try {
337
+ await writeJsonFile(pendingPath(deployment), pending, "wx");
338
+ } catch (error) {
339
+ if (error.code !== "EEXIST") throw error;
340
+ return startSignIn(deployment);
341
+ }
342
+ return { pending, started: true };
343
+ }
344
+ async function waitForSignIn(deployment, pending) {
345
+ while (pending.expiresAt > Date.now()) {
346
+ await sleep(pending.interval * 1e3);
347
+ try {
348
+ const session = await api(deployment, "POST", "/v1/auth/token", {
349
+ body: { deviceCode: pending.deviceCode, deviceName: hostname().slice(0, 100) }
350
+ });
351
+ await writeJsonFile(sessionPath(deployment), session);
352
+ await removeFile(pendingPath(deployment));
353
+ await ensureIdentity(deployment, session.token);
354
+ return true;
355
+ } catch (error) {
356
+ if (!(error instanceof ApiError) || error.message !== "authorization_pending") break;
357
+ }
358
+ }
359
+ await removeFile(pendingPath(deployment));
360
+ return await loadSession(deployment) !== null;
361
+ }
362
+ async function readPendingSignIn(deployment) {
363
+ return readJsonFile(pendingPath(deployment));
364
+ }
365
+ function openBrowser(url) {
366
+ const command2 = process.platform === "darwin" ? "open" : "xdg-open";
367
+ spawn(command2, [url], { detached: true, stdio: "ignore" }).on("error", () => {
368
+ }).unref();
369
+ }
370
+ function startBackgroundPoller(deployment) {
371
+ spawn(process.execPath, [...process.execArgv, process.argv[1], "auth", "--wait", deployment.url], {
372
+ detached: true,
373
+ stdio: "ignore"
374
+ }).unref();
375
+ }
376
+ function sessionPath(deployment) {
377
+ return join3(deployment.dir, "session.json");
378
+ }
379
+ function pendingPath(deployment) {
380
+ return join3(deployment.dir, "pending-sign-in.json");
381
+ }
382
+ function sleep(ms) {
383
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
384
+ }
385
+
386
+ // src/commands/account.ts
387
+ var USAGE = "usage: noenv account add NAME URL [REPO_PREFIX...] | list | default NAME | remove NAME";
388
+ var PREFIX = /^[a-z0-9.-]+(\/[a-z0-9._~-]+)*\/?$/;
389
+ async function accountCommand([action, ...args2]) {
390
+ const handlers = {
391
+ add: addAccount,
392
+ list: listAccounts,
393
+ default: setDefault,
394
+ remove: removeAccount
395
+ };
396
+ const handler = handlers[action ?? ""];
397
+ if (!handler) throw new Error(USAGE);
398
+ await handler(args2);
399
+ }
400
+ async function addAccount([name2, url, ...match]) {
401
+ if (!name2 || !url) throw new Error(USAGE);
402
+ if (!IDENTIFIER.test(name2)) throw new Error('the account name must contain only letters, digits, "_" or "-"');
403
+ const deployment = deploymentAt(url);
404
+ const prefixes = match.map((prefix) => prefix.toLowerCase());
405
+ const invalid = prefixes.find((prefix) => !PREFIX.test(prefix));
406
+ if (invalid) throw new Error(`${invalid} is not a repository prefix such as github.com/acme`);
407
+ const accounts = await readAccounts();
408
+ const clash = Object.entries(accounts.accounts).find(([other, account]) => other !== name2 && deploymentAt(account.url).url === deployment.url);
409
+ if (clash) throw new Error(`the account "${clash[0]}" already uses ${deployment.url}`);
410
+ accounts.accounts[name2] = { url: deployment.url, match: prefixes };
411
+ accounts.default ??= name2;
412
+ await writeAccounts(accounts);
413
+ console.log(`Saved account ${name2} (${deployment.url})${accounts.default === name2 ? " as the default" : ""}`);
414
+ if (!await loadSession(deployment)) console.log(`Run \`noenv auth ${name2}\` to sign in`);
415
+ }
416
+ async function listAccounts() {
417
+ const accounts = await readAccounts();
418
+ const entries = Object.entries(accounts.accounts);
419
+ if (entries.length === 0) {
420
+ console.log("No accounts. Add one with `noenv account add NAME URL [REPO_PREFIX...]`");
421
+ return;
422
+ }
423
+ for (const [name2, account] of entries) {
424
+ const signedIn2 = await loadSession(deploymentAt(account.url)) ? "signed in" : "signed out";
425
+ const marker = accounts.default === name2 ? "*" : " ";
426
+ const match = account.match.length > 0 ? ` ${account.match.join(", ")}` : "";
427
+ console.log(`${marker} ${name2} ${account.url} ${signedIn2}${match}`);
428
+ }
429
+ }
430
+ async function setDefault([name2]) {
431
+ const accounts = await readAccounts();
432
+ if (!name2 || !accounts.accounts[name2]) throw new Error(`there is no account named "${name2 ?? ""}"`);
433
+ accounts.default = name2;
434
+ await writeAccounts(accounts);
435
+ console.log(`${name2} is now the default account`);
436
+ }
437
+ async function removeAccount([name2]) {
438
+ const accounts = await readAccounts();
439
+ if (!name2 || !accounts.accounts[name2]) throw new Error(`there is no account named "${name2 ?? ""}"`);
440
+ delete accounts.accounts[name2];
441
+ if (accounts.default === name2) delete accounts.default;
442
+ await writeAccounts(accounts);
443
+ console.log(`Removed account ${name2}. Its key stays on this machine, so adding it again keeps your access.`);
444
+ }
445
+
446
+ // ../packages/config/src/errors.ts
447
+ var ConfigError = class extends Error {
448
+ };
449
+
450
+ // ../node_modules/smol-toml/dist/error.js
451
+ function getLineColFromPtr(string, ptr) {
452
+ let lines = string.slice(0, ptr).split(/\r?\n/);
453
+ return [lines.length, lines.pop().length + 1];
454
+ }
455
+ function makeCodeBlock(string, line, column) {
456
+ let lines = string.split(/\r?\n/);
457
+ let codeblock = "";
458
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
459
+ for (let i = line - 1; i <= line + 1; i++) {
460
+ let l = lines[i - 1];
461
+ if (!l)
462
+ continue;
463
+ codeblock += i.toString().padEnd(numberLen, " ");
464
+ codeblock += ": ";
465
+ codeblock += l;
466
+ codeblock += "\n";
467
+ if (i === line) {
468
+ codeblock += " ".repeat(numberLen + column + 2);
469
+ codeblock += "^\n";
470
+ }
471
+ }
472
+ return codeblock;
473
+ }
474
+ var TomlError = class _TomlError extends Error {
475
+ line;
476
+ column;
477
+ codeblock;
478
+ constructor(message, options) {
479
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
480
+ const codeblock = makeCodeBlock(options.toml, line, column);
481
+ super(`Invalid TOML document: ${message}
482
+
483
+ ${codeblock}`, options);
484
+ this.line = line;
485
+ this.column = column;
486
+ this.codeblock = codeblock;
487
+ }
488
+ /** @internal */
489
+ static x(message, ctx, ptr) {
490
+ throw new _TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });
491
+ }
492
+ };
493
+
494
+ // ../node_modules/smol-toml/dist/primitive.js
495
+ function parseString(ctx) {
496
+ let startPtr = ctx.p;
497
+ let c = ctx.s.charCodeAt(ctx.p++);
498
+ let first = c;
499
+ let isLiteral = c === 39;
500
+ let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
501
+ if (isMultiline) {
502
+ if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
503
+ ctx.p++;
504
+ else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
505
+ ctx.p += 2;
506
+ }
507
+ let parsed = "";
508
+ let sliceStart = ctx.p;
509
+ let state = 0;
510
+ for (; ctx.p < ctx.s.length; ctx.p++) {
511
+ c = ctx.s.charCodeAt(ctx.p);
512
+ if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
513
+ state = state && 3;
514
+ } else if (c < 32 && c !== 9 || c === 127) {
515
+ TomlError.x("control characters are not allowed in strings", ctx);
516
+ } else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
517
+ if (isMultiline) {
518
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
519
+ ctx.p++;
520
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
521
+ ctx.p++;
522
+ }
523
+ if (!state) {
524
+ let s = ctx.s.slice(sliceStart, ctx.p);
525
+ parsed = parsed ? parsed + s : s;
526
+ }
527
+ ctx.p += isMultiline ? 3 : 1;
528
+ return parsed;
529
+ } else if (!state) {
530
+ if (!isLiteral && c === 92) {
531
+ parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
532
+ state = 1;
533
+ }
534
+ } else if (state === 1) {
535
+ if (c === 120 || c === 117 || c === 85) {
536
+ let errPtr = ctx.p++ - 1;
537
+ let value = 0;
538
+ let len = c === 120 ? 2 : c === 117 ? 4 : 8;
539
+ for (let j = 0; j < len; j++, ctx.p++) {
540
+ let hex = ctx.s.charCodeAt(ctx.p);
541
+ let digit = (
542
+ /* 0-9 */
543
+ hex >= 48 && hex <= 57 ? hex - 48 : (
544
+ /* A-F */
545
+ hex >= 65 && hex <= 70 ? hex - 65 + 10 : (
546
+ /* a-f */
547
+ hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1
548
+ )
549
+ )
550
+ );
551
+ if (digit < 0)
552
+ TomlError.x("invalid non-hex character in unicode escape", ctx);
553
+ value = value << 4 | digit;
554
+ }
555
+ if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
556
+ TomlError.x("invalid unicode escape", ctx, errPtr);
557
+ }
558
+ parsed += String.fromCodePoint(value);
559
+ sliceStart = ctx.p--;
560
+ state = 0;
561
+ } else if (isMultiline && (c === 32 || c === 9)) {
562
+ state = 2;
563
+ } else {
564
+ if (c === 98)
565
+ parsed += "\b";
566
+ else if (c === 116)
567
+ parsed += " ";
568
+ else if (c === 110)
569
+ parsed += "\n";
570
+ else if (c === 102)
571
+ parsed += "\f";
572
+ else if (c === 114)
573
+ parsed += "\r";
574
+ else if (c === 101)
575
+ parsed += "\x1B";
576
+ else if (c === 34)
577
+ parsed += '"';
578
+ else if (c === 92)
579
+ parsed += "\\";
580
+ else
581
+ TomlError.x("unrecognised escape sequence", ctx);
582
+ sliceStart = ctx.p + 1;
583
+ state = 0;
584
+ }
585
+ } else if (c !== 32 && c !== 9) {
586
+ if (state === 2)
587
+ TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
588
+ state = !isLiteral && c === 92 ? 1 : 0;
589
+ sliceStart = ctx.p;
590
+ }
591
+ }
592
+ TomlError.x("unfinished string", ctx, startPtr);
593
+ }
594
+
595
+ // ../node_modules/smol-toml/dist/date.js
596
+ var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;
597
+ var TomlDate = class _TomlDate extends Date {
598
+ #hasDate = false;
599
+ #hasTime = false;
600
+ #offset = null;
601
+ constructor(date, fasttype, unsafeDelim) {
602
+ let hasDate = true;
603
+ let hasTime = true;
604
+ let offset = "Z";
605
+ let c;
606
+ if (typeof date === "string") {
607
+ if (fasttype)
608
+ prep: {
609
+ if (fasttype < 3) {
610
+ if (+date.slice(11, 13) > 23) {
611
+ date = "";
612
+ break prep;
613
+ }
614
+ if (fasttype === 2) {
615
+ offset = null;
616
+ date += "Z";
617
+ } else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) {
618
+ offset = date.slice(date.length - 6);
619
+ }
620
+ if (unsafeDelim)
621
+ date = date.slice(0, 10) + "T" + date.slice(11);
622
+ } else if (fasttype === 4) {
623
+ date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
624
+ }
625
+ hasDate = fasttype !== 4;
626
+ hasTime = fasttype !== 3;
627
+ }
628
+ else {
629
+ let match = date.match(DATE_TIME_RE);
630
+ if (match) {
631
+ if (!match[1]) {
632
+ hasDate = false;
633
+ date = `0000-01-01T${date}`;
634
+ }
635
+ hasTime = !!match[2];
636
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
637
+ if (match[2] && +match[2] > 23) {
638
+ date = "";
639
+ } else {
640
+ offset = match[3] || null;
641
+ if (!offset && hasTime)
642
+ date += "Z";
643
+ }
644
+ } else {
645
+ date = "";
646
+ }
647
+ }
648
+ }
649
+ super(date);
650
+ if (!isNaN(this.getTime())) {
651
+ this.#hasDate = hasDate;
652
+ this.#hasTime = hasTime;
653
+ this.#offset = offset;
654
+ }
655
+ }
656
+ isDateTime() {
657
+ return this.#hasDate && this.#hasTime;
658
+ }
659
+ isLocal() {
660
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
661
+ }
662
+ isDate() {
663
+ return this.#hasDate && !this.#hasTime;
664
+ }
665
+ isTime() {
666
+ return this.#hasTime && !this.#hasDate;
667
+ }
668
+ isValid() {
669
+ return this.#hasDate || this.#hasTime;
670
+ }
671
+ toISOString() {
672
+ let iso = super.toISOString();
673
+ if (this.isDate())
674
+ return iso.slice(0, 10);
675
+ if (this.isTime())
676
+ return iso.slice(11, 23);
677
+ if (this.#offset === null)
678
+ return iso.slice(0, -1);
679
+ if (this.#offset === "Z" || this.#offset === "z")
680
+ return iso;
681
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
682
+ offset = this.#offset[0] === "-" ? offset : -offset;
683
+ let offsetDate = new Date(this.getTime() - offset * 6e4);
684
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
685
+ }
686
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
687
+ let date = new _TomlDate(jsDate);
688
+ date.#offset = offset;
689
+ return date;
690
+ }
691
+ static wrapAsLocalDateTime(jsDate) {
692
+ let date = new _TomlDate(jsDate);
693
+ date.#offset = null;
694
+ return date;
695
+ }
696
+ static wrapAsLocalDate(jsDate) {
697
+ let date = new _TomlDate(jsDate);
698
+ date.#hasTime = false;
699
+ date.#offset = null;
700
+ return date;
701
+ }
702
+ static wrapAsLocalTime(jsDate) {
703
+ let date = new _TomlDate(jsDate);
704
+ date.#hasDate = false;
705
+ date.#offset = null;
706
+ return date;
707
+ }
708
+ };
709
+
710
+ // ../node_modules/smol-toml/dist/extract.js
711
+ function isDigit(char, base = 10) {
712
+ return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
713
+ }
714
+ function isEndOfValue(char, delim) {
715
+ return char === 32 || char === 9 || char === 10 || char === 13 || // Structure end or next value delimiter
716
+ delim && (char === delim || char === 44) || // Comment
717
+ char === 35;
718
+ }
719
+ function extractValue(ctx, end) {
720
+ let errPtr = ctx.p;
721
+ let c = ctx.s.charCodeAt(ctx.p);
722
+ if (c === 91 || c === 123) {
723
+ ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
724
+ let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
725
+ ctx.d++;
726
+ return value;
727
+ }
728
+ if (c === 34 || c === 39) {
729
+ return parseString(ctx);
730
+ }
731
+ if (c === 116) {
732
+ if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
733
+ TomlError.x("invalid value", ctx, errPtr);
734
+ return ctx.p++, true;
735
+ }
736
+ if (c === 102) {
737
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 108 || ctx.s.charCodeAt(++ctx.p) !== 115 || ctx.s.charCodeAt(++ctx.p) !== 101)
738
+ TomlError.x("invalid value", ctx, errPtr);
739
+ return ctx.p++, false;
740
+ }
741
+ if (c === 43 || c === 45) {
742
+ return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
743
+ }
744
+ if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) {
745
+ return parseDate(ctx, c, end);
746
+ }
747
+ if (ctx.s.charCodeAt(ctx.p + 2) === 58) {
748
+ return parseTime(ctx, c, end);
749
+ }
750
+ return parseNumber(ctx, ctx.p, c, 0, end);
751
+ }
752
+ function parseNumber(ctx, startPtr, startChr, sign, endChr) {
753
+ let c = startChr;
754
+ let state = 0;
755
+ let hasUnderscores = false;
756
+ if (c === 105) {
757
+ if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102)
758
+ TomlError.x("invalid value", ctx, startPtr);
759
+ return ctx.p++, (sign || 1) / 0;
760
+ }
761
+ if (c === 110) {
762
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110)
763
+ TomlError.x("invalid value", ctx, startPtr);
764
+ return ctx.p++, NaN;
765
+ }
766
+ if (c === 48) {
767
+ if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))
768
+ return ctx.bi === true ? 0n : 0;
769
+ if (!sign) {
770
+ if (c === 120)
771
+ return parseIntegerBaseN(ctx, startPtr, 16, endChr);
772
+ else if (c === 98)
773
+ return parseIntegerBaseN(ctx, startPtr, 2, endChr);
774
+ else if (c === 111)
775
+ return parseIntegerBaseN(ctx, startPtr, 8, endChr);
776
+ }
777
+ if (c === 46)
778
+ state = 2;
779
+ else if (c === 101 || c === 69)
780
+ state = 4;
781
+ else
782
+ TomlError.x("illegal leading zero", ctx, startPtr);
783
+ } else if (!isDigit(c))
784
+ TomlError.x("invalid value", ctx, startPtr);
785
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
786
+ if (!state)
787
+ state = 1;
788
+ if (c === 95) {
789
+ if (!(state & 1))
790
+ TomlError.x("illegal underscore", ctx);
791
+ state += 11;
792
+ hasUnderscores = true;
793
+ } else if (state === 1 && c === 46)
794
+ state = 2;
795
+ else if ((state === 1 || state === 3) && (c === 101 || c === 69))
796
+ state = 4;
797
+ else if (state === 4 && (c === 43 || c === 45)) {
798
+ state = 6;
799
+ } else if (!isDigit(c))
800
+ TomlError.x(`illegal character in numeric literal`, ctx);
801
+ else if (state > 9)
802
+ state -= 11;
803
+ else if (!(state & 1))
804
+ state++;
805
+ }
806
+ if (!state) {
807
+ let val = (startChr - 48) * (sign || 1);
808
+ return ctx.bi === true ? BigInt(val) : val;
809
+ }
810
+ if (!(state & 1))
811
+ TomlError.x("unfinished numeric value", ctx, startPtr);
812
+ let str = ctx.s.slice(startPtr, ctx.p);
813
+ if (hasUnderscores)
814
+ str = str.replaceAll("_", "");
815
+ return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
816
+ }
817
+ function parseIntegerBaseN(ctx, startPtr, base, endChr) {
818
+ let c, underscore = 1;
819
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
820
+ if (c === 95) {
821
+ if (underscore & 1)
822
+ TomlError.x("illegal underscore", ctx);
823
+ underscore = 3;
824
+ } else if (!isDigit(c, base))
825
+ TomlError.x(`illegal character in numeric literal`, ctx);
826
+ else if (underscore & 1)
827
+ underscore--;
828
+ }
829
+ if (underscore & 1)
830
+ TomlError.x("unfinished numeric value", ctx);
831
+ let str = ctx.s.slice(startPtr + 2, ctx.p);
832
+ if (underscore)
833
+ str = str.replaceAll("_", "");
834
+ return parseInteger(ctx, str, base, startPtr);
835
+ }
836
+ function parseInteger(ctx, str, base, startPtr) {
837
+ if (ctx.bi !== true)
838
+ int: {
839
+ let val = parseInt(str, base);
840
+ if (!Number.isSafeInteger(val)) {
841
+ if (ctx.bi)
842
+ break int;
843
+ TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
844
+ }
845
+ return val;
846
+ }
847
+ return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
848
+ }
849
+ function parseDate(ctx, c, endChr) {
850
+ let startPtr = ctx.p++, unsafeSeparator;
851
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) {
852
+ return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
853
+ }
854
+ ctx.p += 5;
855
+ if (!isDigit(ctx.s.charCodeAt(ctx.p++)))
856
+ TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
857
+ if (ctx.p >= ctx.s.length || ((c = ctx.s.charCodeAt(ctx.p)) !== 32 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 84 && c !== 116) {
858
+ let t2 = ctx.s.slice(startPtr, ctx.p);
859
+ return readDate(ctx, t2, 3, false, startPtr);
860
+ }
861
+ if (ctx.s.charCodeAt(ctx.p += 3) !== 58)
862
+ TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
863
+ if (ctx.s.charCodeAt(ctx.p += 3) === 58)
864
+ ctx.p += 3;
865
+ if (ctx.s.charCodeAt(ctx.p) === 46)
866
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
867
+ ;
868
+ if (c = ctx.s.charCodeAt(ctx.p)) {
869
+ if (c === 90 || c === 122) {
870
+ let t2 = ctx.s.slice(startPtr, ++ctx.p);
871
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, "[+00:00]");
872
+ }
873
+ if (c === 43 || c === 45) {
874
+ let t2 = ctx.s.slice(startPtr, ctx.p += 6);
875
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
876
+ }
877
+ }
878
+ let t = ctx.s.slice(startPtr, ctx.p);
879
+ return readDate(ctx, t, 2, unsafeSeparator, startPtr);
880
+ }
881
+ function parseTime(ctx, c, endChr) {
882
+ let start = ctx.p;
883
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {
884
+ return parseNumber(ctx, --ctx.p, c, 0, endChr);
885
+ }
886
+ if (ctx.s.charCodeAt(ctx.p += 4) === 58)
887
+ ctx.p += 3;
888
+ if (ctx.s.charCodeAt(ctx.p) === 46)
889
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
890
+ ;
891
+ let t = ctx.s.slice(start, ctx.p);
892
+ return readDate(ctx, t, 4, false, start);
893
+ }
894
+ function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
895
+ if (ctx.ld) {
896
+ let date = new TomlDate(str, type, unsafeDelim);
897
+ if (!date.isValid())
898
+ TomlError.x("invalid date", ctx, errPtr);
899
+ return date;
900
+ }
901
+ try {
902
+ if (temporalSuffix)
903
+ str += temporalSuffix;
904
+ switch (type) {
905
+ case 1:
906
+ return Temporal.ZonedDateTime.from(str);
907
+ case 2:
908
+ return Temporal.PlainDateTime.from(str);
909
+ case 3:
910
+ return Temporal.PlainDate.from(str);
911
+ case 4:
912
+ return Temporal.PlainTime.from(str);
913
+ }
914
+ } catch (e) {
915
+ TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
916
+ }
917
+ }
918
+
919
+ // ../node_modules/smol-toml/dist/util.js
920
+ function skipComment(ctx) {
921
+ for (; ctx.p < ctx.s.length; ctx.p++) {
922
+ let c = ctx.s.charCodeAt(ctx.p);
923
+ if (c === 10)
924
+ break;
925
+ if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
926
+ ctx.p++;
927
+ break;
928
+ }
929
+ if (c < 32 && c !== 9 || c === 127) {
930
+ TomlError.x("control characters are not allowed in comments", ctx);
931
+ }
932
+ }
933
+ }
934
+ function skipVoid(ctx, banNewLines, banComments) {
935
+ let c;
936
+ while (ctx.p < ctx.s.length) {
937
+ while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 32 || c === 9 || !banNewLines && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)))
938
+ ctx.p++;
939
+ if (banComments || c !== 35)
940
+ break;
941
+ skipComment(ctx);
942
+ }
943
+ }
944
+
945
+ // ../node_modules/smol-toml/dist/struct.js
946
+ function parseKey(ctx, end = 61) {
947
+ let startPtr;
948
+ let state = 0;
949
+ let parsed = [];
950
+ let sliceStart;
951
+ let c = ctx.s.charCodeAt(startPtr = ctx.p);
952
+ do {
953
+ if (c === end) {
954
+ if (!state)
955
+ TomlError.x("unexpected end of key", ctx);
956
+ if (state === 1)
957
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
958
+ return ctx.p++, parsed;
959
+ } else if (c === 46) {
960
+ if (!state)
961
+ TomlError.x("illegal empty bare key", ctx);
962
+ if (state === 1)
963
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
964
+ state = 0;
965
+ } else if (!state && (c === 34 || c === 39)) {
966
+ if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))
967
+ TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
968
+ parsed.push(parseString(ctx));
969
+ state = 2;
970
+ ctx.p--;
971
+ } else if (c === 32 || c === 9) {
972
+ if (state === 1) {
973
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
974
+ state = 2;
975
+ }
976
+ } else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) {
977
+ TomlError.x("illegal character in key", ctx);
978
+ } else if (!state) {
979
+ state = 1;
980
+ sliceStart = ctx.p;
981
+ }
982
+ } while (c = ctx.s.charCodeAt(++ctx.p));
983
+ TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
984
+ }
985
+ function parseInlineTable(ctx) {
986
+ let startPtr = ctx.p++;
987
+ let res = /* @__PURE__ */ Object.create(null);
988
+ let seen = /* @__PURE__ */ new Set();
989
+ let c;
990
+ while (ctx.p < ctx.s.length) {
991
+ skipVoid(ctx);
992
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
993
+ ctx.p++;
994
+ return res;
995
+ }
996
+ let k;
997
+ let t = res;
998
+ let hasOwn = false;
999
+ let errPtr = ctx.p;
1000
+ let key = parseKey(ctx);
1001
+ for (let i = 0; i < key.length; i++) {
1002
+ if (i)
1003
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
1004
+ k = key[i];
1005
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
1006
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
1007
+ }
1008
+ let unsafe = k === "__proto__";
1009
+ if (ctx.uk && (unsafe || k === "constructor")) {
1010
+ t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
1011
+ break;
1012
+ }
1013
+ if (!hasOwn && unsafe) {
1014
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
1015
+ }
1016
+ }
1017
+ if (hasOwn) {
1018
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
1019
+ }
1020
+ skipVoid(ctx, true, true);
1021
+ let value = extractValue(
1022
+ ctx,
1023
+ 125
1024
+ /* } */
1025
+ );
1026
+ if (t && typeof (t[k] = value) === "object")
1027
+ seen.add(value);
1028
+ skipVoid(ctx);
1029
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
1030
+ return res;
1031
+ }
1032
+ if (c !== 44)
1033
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
1034
+ }
1035
+ TomlError.x("unfinished table", ctx, startPtr);
1036
+ }
1037
+ function parseArray(ctx) {
1038
+ let startPtr = ctx.p++;
1039
+ let res = [];
1040
+ let c;
1041
+ while (ctx.p < ctx.s.length) {
1042
+ skipVoid(ctx);
1043
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
1044
+ ctx.p++;
1045
+ return res;
1046
+ }
1047
+ res.push(extractValue(
1048
+ ctx,
1049
+ 93
1050
+ /* ] */
1051
+ ));
1052
+ skipVoid(ctx);
1053
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
1054
+ return res;
1055
+ }
1056
+ if (c !== 44)
1057
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
1058
+ }
1059
+ TomlError.x("unfinished array", ctx, startPtr);
1060
+ }
1061
+
1062
+ // ../node_modules/smol-toml/dist/parse.js
1063
+ function peekTable(ctx, key, table, meta, type) {
1064
+ let t = table;
1065
+ let m = meta;
1066
+ let k;
1067
+ let hasOwn = false;
1068
+ let state;
1069
+ for (let i = 0; i < key.length; i++) {
1070
+ if (i) {
1071
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
1072
+ m = (state = m[k]).c;
1073
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
1074
+ return null;
1075
+ }
1076
+ if (state.t === 2) {
1077
+ let l = t.length - 1;
1078
+ t = t[l];
1079
+ m = m[l].c;
1080
+ }
1081
+ }
1082
+ k = key[i];
1083
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
1084
+ return null;
1085
+ }
1086
+ if (!hasOwn) {
1087
+ let unsafe = k === "__proto__";
1088
+ if (ctx.uk && (unsafe || k === "constructor"))
1089
+ return false;
1090
+ if (unsafe) {
1091
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
1092
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
1093
+ }
1094
+ m[k] = {
1095
+ t: i < key.length - 1 && type === 2 ? 3 : type,
1096
+ d: false,
1097
+ i: 0,
1098
+ c: /* @__PURE__ */ Object.create(null)
1099
+ };
1100
+ }
1101
+ }
1102
+ state = m[k];
1103
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
1104
+ return null;
1105
+ }
1106
+ if (type === 2) {
1107
+ if (!state.d) {
1108
+ state.d = true;
1109
+ t[k] = [];
1110
+ }
1111
+ t[k].push(t = /* @__PURE__ */ Object.create(null));
1112
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: /* @__PURE__ */ Object.create(null) };
1113
+ }
1114
+ if (state.d) {
1115
+ return null;
1116
+ }
1117
+ state.d = true;
1118
+ if (type === 1) {
1119
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
1120
+ } else if (type === 0 && hasOwn) {
1121
+ return null;
1122
+ }
1123
+ return [k, t, state.c];
1124
+ }
1125
+ function validateTablePeek(ctx, peek, ptr) {
1126
+ if (peek === null || ctx.uk === 2)
1127
+ TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
1128
+ }
1129
+ function parse(toml, options = {}) {
1130
+ let ctx = {
1131
+ s: toml,
1132
+ p: 0,
1133
+ d: options.maxDepth ?? 1e3,
1134
+ bi: options.integersAsBigInt ?? false,
1135
+ ld: options.useLegacyDate ?? true,
1136
+ uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
1137
+ };
1138
+ let res = /* @__PURE__ */ Object.create(null);
1139
+ let meta = /* @__PURE__ */ Object.create(null);
1140
+ let tmp;
1141
+ let skipping = false;
1142
+ let tbl = res;
1143
+ let m = meta;
1144
+ if (toml.charCodeAt(0) === 65279)
1145
+ ctx.p++;
1146
+ skipVoid(ctx);
1147
+ while (ctx.p < toml.length) {
1148
+ if (toml.charCodeAt(ctx.p) === 91) {
1149
+ let isTableArray = toml.charCodeAt(++ctx.p) === 91;
1150
+ tmp = ctx.p += +isTableArray;
1151
+ skipping = false;
1152
+ let k = parseKey(
1153
+ ctx,
1154
+ 93
1155
+ /* ] */
1156
+ );
1157
+ if (isTableArray) {
1158
+ if (toml.charCodeAt(ctx.p) !== 93) {
1159
+ TomlError.x("expected end of table array declaration", ctx);
1160
+ }
1161
+ ctx.p++;
1162
+ }
1163
+ let p = peekTable(
1164
+ ctx,
1165
+ k,
1166
+ res,
1167
+ meta,
1168
+ isTableArray ? 2 : 1
1169
+ /* Type.EXPLICIT */
1170
+ );
1171
+ if (!p) {
1172
+ validateTablePeek(ctx, p, tmp);
1173
+ skipping = true;
1174
+ } else {
1175
+ m = p[2];
1176
+ tbl = p[1];
1177
+ }
1178
+ } else {
1179
+ tmp = ctx.p;
1180
+ let k = parseKey(ctx);
1181
+ let p = peekTable(
1182
+ ctx,
1183
+ k,
1184
+ tbl,
1185
+ m,
1186
+ 0
1187
+ /* Type.DOTTED */
1188
+ );
1189
+ if (!p && !skipping)
1190
+ validateTablePeek(ctx, p, tmp);
1191
+ skipVoid(ctx, true, true);
1192
+ let v = extractValue(ctx, void 0);
1193
+ if (p && !skipping)
1194
+ p[1][p[0]] = v;
1195
+ }
1196
+ skipVoid(ctx, true);
1197
+ if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) {
1198
+ TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
1199
+ }
1200
+ skipVoid(ctx);
1201
+ }
1202
+ return res;
1203
+ }
1204
+
1205
+ // ../node_modules/smol-toml/dist/stringify.js
1206
+ var HAS_WELLFORMED = !!"".isWellFormed;
1207
+
1208
+ // ../packages/config/src/parse.ts
1209
+ var DEFAULT_CONFIG = {
1210
+ environment: "development",
1211
+ requiredSecrets: [],
1212
+ wrangler: { secrets: [] }
1213
+ };
1214
+ function parseConfig(text3) {
1215
+ const raw = parse(text3);
1216
+ if (raw.version !== 1) {
1217
+ throw new ConfigError("version must be 1");
1218
+ }
1219
+ const environment = raw.environment ?? DEFAULT_CONFIG.environment;
1220
+ if (typeof environment !== "string" || !IDENTIFIER.test(environment)) {
1221
+ throw new ConfigError('environment must contain only letters, digits, "_" or "-"');
1222
+ }
1223
+ const secrets = raw.secrets ?? {};
1224
+ const required = secrets.required ?? [];
1225
+ if (!Array.isArray(required) || !required.every(isEnvVarName)) {
1226
+ throw new ConfigError("secrets.required must be a list of valid variable names");
1227
+ }
1228
+ return { environment, requiredSecrets: required, wrangler: parseWrangler(raw.wrangler) };
1229
+ }
1230
+ function parseWrangler(value) {
1231
+ const raw = value ?? {};
1232
+ const secrets = raw.secrets ?? [];
1233
+ if (!Array.isArray(secrets) || !secrets.every(isEnvVarName)) {
1234
+ throw new ConfigError("wrangler.secrets must be a list of valid variable names");
1235
+ }
1236
+ const config = { secrets };
1237
+ for (const key of ["environment", "env"]) {
1238
+ const field = raw[key];
1239
+ if (field === void 0) continue;
1240
+ if (typeof field !== "string" || !IDENTIFIER.test(field)) {
1241
+ throw new ConfigError(`wrangler.${key} must contain only letters, digits, "_" or "-"`);
1242
+ }
1243
+ config[key] = field;
1244
+ }
1245
+ return config;
1246
+ }
1247
+ function isEnvVarName(value) {
1248
+ return typeof value === "string" && ENV_VAR_NAME.test(value);
1249
+ }
1250
+
1251
+ // ../packages/config/src/repo.ts
1252
+ var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
1253
+ var SCP_LIKE = /^(?:[^@/]+@)?([^:/]+):(.+)$/;
1254
+ var SUPPORTED_PROTOCOLS = ["https:", "http:", "ssh:", "git:"];
1255
+ function normalizeRemoteUrl(remote) {
1256
+ const [host, path] = splitRemote(remote.trim());
1257
+ const cleanPath = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "");
1258
+ const repo = `${host}/${cleanPath}`.toLowerCase();
1259
+ if (!REPO.test(repo)) {
1260
+ throw new ConfigError("git origin is not a supported remote URL");
1261
+ }
1262
+ return repo;
1263
+ }
1264
+ function splitRemote(remote) {
1265
+ if (URL_SCHEME.test(remote)) {
1266
+ const url = URL.parse(remote);
1267
+ if (!url || !SUPPORTED_PROTOCOLS.includes(url.protocol)) {
1268
+ throw new ConfigError("git origin is not a supported remote URL");
1269
+ }
1270
+ return [url.hostname, decodeURIComponent(url.pathname)];
1271
+ }
1272
+ const scp = remote.match(SCP_LIKE);
1273
+ if (!scp) {
1274
+ throw new ConfigError("git origin is not a supported remote URL");
1275
+ }
1276
+ return [scp[1], scp[2]];
1277
+ }
1278
+
1279
+ // ../packages/config/src/git.ts
1280
+ import { execFile } from "node:child_process";
1281
+ import { promisify } from "node:util";
1282
+ var run = promisify(execFile);
1283
+ async function readGitOrigin(dir) {
1284
+ try {
1285
+ const [root, url] = await Promise.all([git(dir, "rev-parse", "--show-toplevel"), git(dir, "config", "--get", "remote.origin.url")]);
1286
+ return { root, url };
1287
+ } catch {
1288
+ return null;
1289
+ }
1290
+ }
1291
+ async function git(dir, ...args2) {
1292
+ const { stdout } = await run("git", ["-C", dir, ...args2]);
1293
+ return stdout.trim();
1294
+ }
1295
+
1296
+ // ../packages/config/src/find.ts
1297
+ import { readFile as readFile2 } from "node:fs/promises";
1298
+ import { join as join4 } from "node:path";
1299
+ var CONFIG_FILE = ".noenv";
1300
+ async function findProject(startDir) {
1301
+ const origin = await readGitOrigin(startDir);
1302
+ if (!origin) return null;
1303
+ const text3 = await readConfigFile(join4(origin.root, CONFIG_FILE));
1304
+ const config = text3 === null ? DEFAULT_CONFIG : parseConfig(text3);
1305
+ return { root: origin.root, repo: normalizeRemoteUrl(origin.url), hasConfig: text3 !== null, ...config };
1306
+ }
1307
+ async function readConfigFile(path) {
1308
+ try {
1309
+ return await readFile2(path, "utf8");
1310
+ } catch (error) {
1311
+ const code = error.code;
1312
+ if (code === "ENOENT" || code === "EISDIR") return null;
1313
+ throw error;
1314
+ }
1315
+ }
1316
+
1317
+ // src/target.ts
1318
+ async function findTarget(cwd, env) {
1319
+ const project = await findProject(cwd);
1320
+ if (!project) return null;
1321
+ const environment = env.NOENV_ENVIRONMENT || project.environment;
1322
+ if (!IDENTIFIER.test(environment)) {
1323
+ throw new Error('NOENV_ENVIRONMENT must contain only letters, digits, "_" or "-"');
1324
+ }
1325
+ return { ...project, environment };
1326
+ }
1327
+ async function requireTarget(cwd = process.cwd(), env = process.env) {
1328
+ const target = await findTarget(cwd, env);
1329
+ if (!target) {
1330
+ throw new Error("this directory is not inside a git repository with an origin remote");
1331
+ }
1332
+ return target;
1333
+ }
1334
+
1335
+ // src/context.ts
1336
+ async function requireDeployment(repo) {
1337
+ const found = repo ?? (await findTarget(process.cwd(), process.env).catch(() => null))?.repo ?? null;
1338
+ const deployment = await resolveDeployment(found);
1339
+ if (!deployment) {
1340
+ throw new Error("no noenv account is set up, run `noenv account add NAME URL` or set NOENV_URL");
1341
+ }
1342
+ return deployment;
1343
+ }
1344
+ async function signedIn(repo) {
1345
+ const deployment = await requireDeployment(repo);
1346
+ const token = await requireSession(deployment);
1347
+ return { deployment, token, identity: await ensureIdentity(deployment, token) };
1348
+ }
1349
+ async function inProject() {
1350
+ const target = await requireTarget();
1351
+ return { ...await signedIn(target.repo), target };
1352
+ }
1353
+
1354
+ // src/commands/auth.ts
1355
+ async function authCommand(args2) {
1356
+ if (args2[0] === "--wait") {
1357
+ const deployment2 = args2[1] ? deploymentAt(args2[1]) : await requireDeployment();
1358
+ const pending2 = await readPendingSignIn(deployment2);
1359
+ if (pending2) await waitForSignIn(deployment2, pending2);
1360
+ return;
1361
+ }
1362
+ const deployment = await accountOrCurrent(args2[0]);
1363
+ const { pending, started } = await startSignIn(deployment);
1364
+ console.log(`Open ${pending.url} and confirm the code ${pending.userCode}`);
1365
+ if (started) openBrowser(pending.url);
1366
+ if (!await waitForSignIn(deployment, pending)) {
1367
+ throw new Error("sign-in was not completed");
1368
+ }
1369
+ const me = await api(deployment, "GET", "/v1/me", { token: await loadSession(deployment) });
1370
+ console.log(`Signed in to ${label(deployment)} as ${me.email}`);
1371
+ }
1372
+ async function statusCommand() {
1373
+ const target = await findTarget(process.cwd(), process.env);
1374
+ const deployment = await requireDeployment(target?.repo);
1375
+ if (deployment.account) console.log(`Account: ${deployment.account}`);
1376
+ console.log(`Deployment: ${deployment.url}`);
1377
+ const token = await loadSession(deployment);
1378
+ if (!token) {
1379
+ console.log("Signed in: no");
1380
+ return;
1381
+ }
1382
+ const me = await api(deployment, "GET", "/v1/me", { token });
1383
+ console.log(`Signed in: ${me.email}${me.isAdmin ? " (organization admin)" : ""}`);
1384
+ if (!target) {
1385
+ console.log("Project: none (not in a git repository with an origin)");
1386
+ return;
1387
+ }
1388
+ console.log(`Project: ${target.repo}`);
1389
+ console.log(`Environment: ${target.environment}`);
1390
+ try {
1391
+ const path = `${environmentPath(target.repo, target.environment)}/secrets`;
1392
+ const { secrets } = await api(deployment, "GET", path, { token });
1393
+ console.log(`Secrets: ${secrets.length}`);
1394
+ } catch {
1395
+ console.log("Secrets: no access");
1396
+ }
1397
+ }
1398
+ async function accountOrCurrent(name2) {
1399
+ if (!name2) return requireDeployment();
1400
+ return await resolveDeployment(null, { ...process.env, NOENV_ACCOUNT: name2 });
1401
+ }
1402
+ function label(deployment) {
1403
+ return deployment.account ?? deployment.url;
1404
+ }
1405
+
1406
+ // src/commands/exec.ts
1407
+ import { spawn as spawn3 } from "node:child_process";
1408
+ import { constants } from "node:os";
1409
+
1410
+ // src/bundle.ts
1411
+ async function fetchRawBundle(deployment, token, repo, environment) {
1412
+ return api(deployment, "GET", `${environmentPath(repo, environment)}/bundle`, { token });
1413
+ }
1414
+ async function openBundle(raw, privateKey, environment) {
1415
+ const environmentPrivateKey = await unwrapPrivateKey(raw.wrappedKey, privateKey);
1416
+ const secrets = {};
1417
+ for (const { name: name2, sealed } of raw.secrets) {
1418
+ secrets[name2] = await decryptSecret(environmentPrivateKey, sealed, { projectId: raw.projectId, environment, name: name2 });
1419
+ }
1420
+ return {
1421
+ projectId: raw.projectId,
1422
+ revision: raw.revision,
1423
+ policies: raw.policies,
1424
+ environmentPublicKey: await importPublicKey(raw.publicKey),
1425
+ environmentPrivateKey,
1426
+ secrets
1427
+ };
1428
+ }
1429
+ async function fetchBundle(deployment, token, privateKey, repo, environment) {
1430
+ return openBundle(await fetchRawBundle(deployment, token, repo, environment), privateKey, environment);
1431
+ }
1432
+
1433
+ // src/refresh.ts
1434
+ import { createHash as createHash2 } from "node:crypto";
1435
+ import { join as join7 } from "node:path";
1436
+
1437
+ // ../packages/policy/src/defaults.ts
1438
+ var DEFAULT_POLICIES = {
1439
+ dotenv: {
1440
+ mode: "warn",
1441
+ include: [".env", ".env.*"],
1442
+ exclude: [".env.example", ".env.sample", ".env.template", ".env.*.example"]
1443
+ },
1444
+ minCliVersion: null,
1445
+ sessionTtlHours: 168,
1446
+ environmentMinRole: "reader"
1447
+ };
1448
+
1449
+ // ../packages/dotenv/src/policy.ts
1450
+ var DEFAULT_DOTENV_POLICY = DEFAULT_POLICIES.dotenv;
1451
+
1452
+ // ../packages/dotenv/src/find.ts
1453
+ import { opendir } from "node:fs/promises";
1454
+ import { join as join5, matchesGlob } from "node:path";
1455
+ var SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([".git", "node_modules"]);
1456
+ async function findDotenvFiles(root, policy) {
1457
+ const found = [];
1458
+ await walk(root, policy, found);
1459
+ return found.sort();
1460
+ }
1461
+ async function walk(dir, policy, found) {
1462
+ for await (const entry of await opendir(dir)) {
1463
+ const path = join5(dir, entry.name);
1464
+ if (entry.isFile() && matchesPolicy(entry.name, policy)) {
1465
+ found.push(path);
1466
+ } else if (entry.isDirectory() && !SKIPPED_DIRECTORIES.has(entry.name) && !await isGitRepository(path)) {
1467
+ await walk(path, policy, found);
1468
+ }
1469
+ }
1470
+ }
1471
+ function matchesPolicy(name2, { include, exclude }) {
1472
+ return include.some((pattern) => matchesGlob(name2, pattern)) && !exclude.some((pattern) => matchesGlob(name2, pattern));
1473
+ }
1474
+ async function isGitRepository(dir) {
1475
+ for await (const entry of await opendir(dir)) {
1476
+ if (entry.name === ".git") return true;
1477
+ }
1478
+ return false;
1479
+ }
1480
+
1481
+ // ../packages/dotenv/src/file.ts
1482
+ import { lstat, readFile as readFile3, unlink } from "node:fs/promises";
1483
+ import { parseEnv } from "node:util";
1484
+ async function readDotenvFile(path) {
1485
+ await requireRegularFile(path);
1486
+ const content = await readFile3(path, "utf8");
1487
+ const values = parseEnv(content);
1488
+ const invalidNames = Object.keys(values).filter((name2) => !ENV_VAR_NAME.test(name2));
1489
+ return { path, content, values, invalidNames };
1490
+ }
1491
+ async function removeIfUnchanged(file) {
1492
+ await requireRegularFile(file.path);
1493
+ if (await readFile3(file.path, "utf8") !== file.content) return false;
1494
+ await unlink(file.path);
1495
+ return true;
1496
+ }
1497
+ async function requireRegularFile(path) {
1498
+ if (!(await lstat(path)).isFile()) {
1499
+ throw new Error("not a regular file");
1500
+ }
1501
+ }
1502
+
1503
+ // ../packages/dotenv/src/migrate.ts
1504
+ async function migrateDotenvFile(file, store) {
1505
+ const conflicts = [];
1506
+ for (const [name2, value] of Object.entries(file.values)) {
1507
+ const stored = await store.get(name2);
1508
+ if (stored === void 0) {
1509
+ await store.set(name2, value);
1510
+ } else if (stored !== value) {
1511
+ conflicts.push(name2);
1512
+ }
1513
+ }
1514
+ if (conflicts.length > 0) return { verified: false, conflicts };
1515
+ return { verified: await isFullyStored(file, store), conflicts };
1516
+ }
1517
+ async function isFullyStored(file, store) {
1518
+ for (const [name2, value] of Object.entries(file.values)) {
1519
+ if (await store.get(name2) !== value) return false;
1520
+ }
1521
+ return true;
1522
+ }
1523
+
1524
+ // ../packages/dotenv/src/enforce.ts
1525
+ async function enforceDotenvPolicy(root, policy, store) {
1526
+ const paths = await findDotenvFiles(root, policy);
1527
+ if (policy.mode !== "delete") {
1528
+ const files2 = paths.map((path) => ({ path, status: "found", names: [] }));
1529
+ return { blocked: policy.mode !== "warn" && files2.length > 0, files: files2 };
1530
+ }
1531
+ const files = [];
1532
+ for (const path of paths) {
1533
+ files.push(await deleteAfterMigration(path, store));
1534
+ }
1535
+ return { blocked: files.some((file) => file.status !== "deleted"), files };
1536
+ }
1537
+ async function deleteAfterMigration(path, store) {
1538
+ try {
1539
+ const file = await readDotenvFile(path);
1540
+ if (file.invalidNames.length > 0) {
1541
+ return { path, status: "invalid", names: file.invalidNames };
1542
+ }
1543
+ const migration = await migrateDotenvFile(file, store);
1544
+ if (migration.conflicts.length > 0) {
1545
+ return { path, status: "conflict", names: migration.conflicts };
1546
+ }
1547
+ if (!migration.verified) {
1548
+ return { path, status: "failed", names: [] };
1549
+ }
1550
+ return { path, status: await removeIfUnchanged(file) ? "deleted" : "changed", names: [] };
1551
+ } catch {
1552
+ return { path, status: "failed", names: [] };
1553
+ }
1554
+ }
1555
+
1556
+ // src/compliance.ts
1557
+ import { relative } from "node:path";
1558
+ var DESCRIPTIONS = {
1559
+ found: "found",
1560
+ invalid: "kept, it has invalid variable names",
1561
+ conflict: "kept, its values differ from noenv",
1562
+ failed: "kept, it could not be migrated",
1563
+ migrated: "migrated to noenv",
1564
+ changed: "kept, it changed during migration",
1565
+ deleted: "migrated to noenv and deleted"
1566
+ };
1567
+ function describeOutcome(target, outcome) {
1568
+ const names = outcome.names.length > 0 ? ` (${outcome.names.join(", ")})` : "";
1569
+ return `${relative(target.root, outcome.path)}: ${DESCRIPTIONS[outcome.status]}${names}`;
1570
+ }
1571
+ async function reportCompliance(deployment, token, target, result) {
1572
+ await api(deployment, "POST", `${environmentPath(target.repo, target.environment)}/compliance`, {
1573
+ token,
1574
+ body: {
1575
+ compliant: result.files.every((file) => file.status === "deleted"),
1576
+ files: result.files.map((file) => ({ path: relative(target.root, file.path), status: file.status }))
1577
+ }
1578
+ });
1579
+ }
1580
+
1581
+ // src/secret-store.ts
1582
+ function remoteSecretStore(deployment, token, identity, repo, environment, initial = null) {
1583
+ let cached = initial;
1584
+ const bundle = async () => cached ??= await fetchBundle(deployment, token, identity.privateKey, repo, environment);
1585
+ return {
1586
+ async get(name2) {
1587
+ return (await bundle()).secrets[name2];
1588
+ },
1589
+ async set(name2, value) {
1590
+ const { environmentPublicKey, projectId } = await bundle();
1591
+ const sealed = await encryptSecret(environmentPublicKey, value, { projectId, environment, name: name2 });
1592
+ const path = `${environmentPath(repo, environment)}/secrets/${name2}`;
1593
+ const { version } = await api(deployment, "PUT", path, { token, body: sealed });
1594
+ cached = null;
1595
+ return version;
1596
+ }
1597
+ };
1598
+ }
1599
+
1600
+ // src/watch.ts
1601
+ import { spawn as spawn2 } from "node:child_process";
1602
+ import { createHash } from "node:crypto";
1603
+ import { mkdir as mkdir2, readFile as readFile4, writeFile as writeFile2 } from "node:fs/promises";
1604
+ import { join as join6 } from "node:path";
1605
+ var POLL_INTERVAL_MS = 5e3;
1606
+ var IDLE_LIMIT_MS = 60 * 60 * 1e3;
1607
+ var CHANGED = "changed";
1608
+ function markerPath(deployment, repo, environment) {
1609
+ const name2 = createHash("sha256").update(`${repo}\0${environment}`).digest("hex").slice(0, 32);
1610
+ return join6(deployment.dir, "revisions", name2);
1611
+ }
1612
+ async function readMarker(path) {
1613
+ return readFile4(path, "utf8").catch(() => "");
1614
+ }
1615
+ async function writeMarker(path, value) {
1616
+ await mkdir2(join6(path, ".."), { recursive: true, mode: 448 });
1617
+ await writeFile2(path, value, { mode: 384 });
1618
+ }
1619
+ async function markChanged(deployment, repo, environment) {
1620
+ await writeMarker(markerPath(deployment, repo, environment), CHANGED);
1621
+ }
1622
+ async function watchEnvironment(deployment, repo, environment) {
1623
+ const list = await readJsonFile(watchListPath(deployment)) ?? {};
1624
+ list[`${repo}\0${environment}`] = { repo, environment, seenAt: Date.now() };
1625
+ await writeJsonFile(watchListPath(deployment), list);
1626
+ }
1627
+ async function startWatcher(deployment) {
1628
+ if (await isWatcherRunning(deployment)) return;
1629
+ spawn2(process.execPath, [...process.execArgv, process.argv[1], "watch", deployment.url], { detached: true, stdio: "ignore" }).unref();
1630
+ }
1631
+ async function runWatcher(deployment) {
1632
+ try {
1633
+ await writeJsonFile(pidPath(deployment), process.pid, "wx");
1634
+ } catch {
1635
+ if (await isWatcherRunning(deployment)) return;
1636
+ await writeJsonFile(pidPath(deployment), process.pid);
1637
+ }
1638
+ try {
1639
+ while (await checkForUpdates(deployment)) {
1640
+ await new Promise((resolve2) => setTimeout(resolve2, POLL_INTERVAL_MS));
1641
+ }
1642
+ } finally {
1643
+ await removeFile(pidPath(deployment));
1644
+ }
1645
+ }
1646
+ async function checkForUpdates(deployment) {
1647
+ const token = await loadSession(deployment);
1648
+ const list = await readJsonFile(watchListPath(deployment)) ?? {};
1649
+ const active = Object.values(list).filter((entry) => Date.now() - entry.seenAt < IDLE_LIMIT_MS);
1650
+ if (!token || active.length === 0) return false;
1651
+ await refreshMarkers(deployment, token, active).catch(() => {
1652
+ });
1653
+ return true;
1654
+ }
1655
+ async function refreshMarkers(deployment, token, entries) {
1656
+ const { revisions } = await api(deployment, "POST", "/v1/revisions", {
1657
+ token,
1658
+ body: { environments: entries.map(({ repo, environment }) => ({ repo, environment })) }
1659
+ });
1660
+ for (const { repo, environment, revision } of revisions) {
1661
+ const path = markerPath(deployment, repo, environment);
1662
+ const marker = await readMarker(path);
1663
+ if (marker !== CHANGED && marker.split(":")[0] !== String(revision)) await writeMarker(path, CHANGED);
1664
+ }
1665
+ }
1666
+ async function isWatcherRunning(deployment) {
1667
+ const pid = await readJsonFile(pidPath(deployment));
1668
+ if (!pid) return false;
1669
+ try {
1670
+ process.kill(pid, 0);
1671
+ return true;
1672
+ } catch {
1673
+ return false;
1674
+ }
1675
+ }
1676
+ function watchListPath(deployment) {
1677
+ return join6(deployment.dir, "watch.json");
1678
+ }
1679
+ function pidPath(deployment) {
1680
+ return join6(deployment.dir, "watcher.pid");
1681
+ }
1682
+
1683
+ // src/refresh.ts
1684
+ async function readCache(deployment, target) {
1685
+ return readJsonFile(cachePath(deployment, target)).catch(() => null);
1686
+ }
1687
+ async function refresh(deployment, target) {
1688
+ const entry = await fetchEntry(deployment, target);
1689
+ if (!entry) return null;
1690
+ await writeJsonFile(cachePath(deployment, target), entry);
1691
+ await writeMarker(markerPath(deployment, target.repo, target.environment), `${"raw" in entry ? entry.raw.revision : "x"}:${Date.now()}`);
1692
+ return entry;
1693
+ }
1694
+ async function fetchEntry(deployment, target) {
1695
+ try {
1696
+ const token = await loadSession(deployment);
1697
+ if (!token) return { error: "you are not signed in", status: 401 };
1698
+ const identity = await loadIdentity(deployment) ?? await ensureIdentity(deployment, token);
1699
+ let raw = await fetchRawBundle(deployment, token, target.repo, target.environment);
1700
+ const bundle = await openBundle(raw, identity.privateKey, target.environment);
1701
+ const policy = bundle.policies.dotenv;
1702
+ const store = remoteSecretStore(deployment, token, identity, target.repo, target.environment, bundle);
1703
+ const result = await enforceDotenvPolicy(target.root, policy, store);
1704
+ const notes = result.files.map((file) => describeOutcome(target, file));
1705
+ if (result.files.length > 0) {
1706
+ await reportCompliance(deployment, token, target, result).catch(() => notes.push("could not report compliance"));
1707
+ }
1708
+ if (result.blocked) {
1709
+ notes.push(`secrets were not loaded: the "${policy.mode}" policy does not allow .env files, run \`noenv migrate\``);
1710
+ }
1711
+ if (result.files.some((file) => file.status === "deleted")) {
1712
+ raw = await fetchRawBundle(deployment, token, target.repo, target.environment);
1713
+ }
1714
+ return { raw, notes, blocked: result.blocked };
1715
+ } catch (error) {
1716
+ if (!(error instanceof ApiError)) return null;
1717
+ if (error.status === 401) await clearSession(deployment);
1718
+ return { error: error.message, status: error.status };
1719
+ }
1720
+ }
1721
+ function cachePath(deployment, target) {
1722
+ const name2 = createHash2("sha256").update(`${target.repo}\0${target.environment}`).digest("hex").slice(0, 32);
1723
+ return join7(deployment.dir, "bundles", `${name2}.json`);
1724
+ }
1725
+
1726
+ // src/shell.ts
1727
+ var FIND_ROOT = `_noenv_root() {
1728
+ local dir="$PWD"
1729
+ until [[ -e "$dir/.git" || "$dir" == "/" ]]; do dir="\${dir%/*}"; dir="\${dir:-/}"; done
1730
+ if [[ -e "$dir/.git" ]]; then REPLY="$dir"; else REPLY=""; fi
1731
+ }
1732
+ `;
1733
+ var HOOKS = {
1734
+ zsh: `${FIND_ROOT}_noenv_hook() {
1735
+ local revision="" REPLY
1736
+ _noenv_root
1737
+ [[ -n "$_NOENV_REV_FILE" && -r "$_NOENV_REV_FILE" ]] && revision="$(<"$_NOENV_REV_FILE")"
1738
+ if [[ "$REPLY" != "$_NOENV_ROOT" || -n "$_NOENV_RETRY" || "$revision" != "$_NOENV_REV" ]]; then
1739
+ _NOENV_ROOT="$REPLY"
1740
+ if [[ -z "$REPLY" && ( -n "$_NOENV_RESTORE" || -z "$_NOENV_STATE" ) ]]; then
1741
+ eval "$_NOENV_RESTORE"
1742
+ else
1743
+ eval "$(printf '%s' "$_NOENV_STATE" | command noenv hook-env zsh)"
1744
+ fi
1745
+ fi
1746
+ }
1747
+ _noenv_refresh() {
1748
+ local fd
1749
+ exec {fd}< <(command noenv refresh "$@" 2>/dev/null; print)
1750
+ zle -F -w "$fd" _noenv_ready 2>/dev/null || exec {fd}<&-
1751
+ }
1752
+ _noenv_ready() {
1753
+ local fd="$1"
1754
+ zle -F "$fd"
1755
+ exec {fd}<&-
1756
+ zle -I
1757
+ _noenv_hook
1758
+ zle reset-prompt
1759
+ }
1760
+ zle -N _noenv_ready 2>/dev/null
1761
+ typeset -ag precmd_functions chpwd_functions
1762
+ if (( ! \${precmd_functions[(I)_noenv_hook]} )); then precmd_functions=(_noenv_hook $precmd_functions); fi
1763
+ if (( ! \${chpwd_functions[(I)_noenv_hook]} )); then chpwd_functions=(_noenv_hook $chpwd_functions); fi
1764
+ `,
1765
+ bash: `${FIND_ROOT}_noenv_hook() {
1766
+ local previous_exit=$? revision="" REPLY
1767
+ _noenv_root
1768
+ [[ -n "$_NOENV_REV_FILE" && -r "$_NOENV_REV_FILE" ]] && revision="$(<"$_NOENV_REV_FILE")"
1769
+ if [[ "$REPLY" != "$_NOENV_ROOT" || -n "$_NOENV_RETRY" || "$revision" != "$_NOENV_REV" ]]; then
1770
+ _NOENV_ROOT="$REPLY"
1771
+ if [[ -z "$REPLY" && ( -n "$_NOENV_RESTORE" || -z "$_NOENV_STATE" ) ]]; then
1772
+ eval "$_NOENV_RESTORE"
1773
+ else
1774
+ eval "$(printf '%s' "$_NOENV_STATE" | command noenv hook-env bash)"
1775
+ fi
1776
+ fi
1777
+ return $previous_exit
1778
+ }
1779
+ _noenv_refresh() {
1780
+ (command noenv refresh "$@" >/dev/null 2>&1 &)
1781
+ }
1782
+ if [[ ";\${PROMPT_COMMAND:-};" != *";_noenv_hook;"* ]]; then
1783
+ PROMPT_COMMAND="_noenv_hook\${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
1784
+ fi
1785
+ `
1786
+ };
1787
+ function parseShell(value) {
1788
+ if (value !== "zsh" && value !== "bash") {
1789
+ throw new Error("shell must be zsh or bash");
1790
+ }
1791
+ return value;
1792
+ }
1793
+ function hookScript(shell) {
1794
+ return HOOKS[shell];
1795
+ }
1796
+ function quote(value) {
1797
+ return `'${value.replaceAll("'", `'\\''`)}'`;
1798
+ }
1799
+ function exportLine(name2, value) {
1800
+ return `export ${name2}=${quote(value)}`;
1801
+ }
1802
+ function setLine(name2, value) {
1803
+ return `${name2}=${quote(value)}`;
1804
+ }
1805
+ function unsetLine(name2) {
1806
+ return `unset ${name2}`;
1807
+ }
1808
+
1809
+ // src/hook-env.ts
1810
+ var STATE_VARIABLES = ["_NOENV_STATE", "_NOENV_RETRY", "_NOENV_REV_FILE", "_NOENV_REV", "_NOENV_RESTORE"];
1811
+ async function hookEnv(input) {
1812
+ const state = decodeState(input.state);
1813
+ const messages = [];
1814
+ const resolved = await resolve(input, messages);
1815
+ if (!resolved) {
1816
+ return { lines: state ? [...restoreLines(state), ...STATE_VARIABLES.map(unsetLine)] : [], messages };
1817
+ }
1818
+ const { target, deployment } = resolved;
1819
+ const marker = markerPath(deployment, target.repo, target.environment);
1820
+ const revision = await readMarker(marker);
1821
+ const step = await load(input, resolved, state, revision, messages);
1822
+ return {
1823
+ lines: [
1824
+ ...step.lines,
1825
+ exportLine("_NOENV_STATE", encodeState(step.state)),
1826
+ step.state.retry ? setLine("_NOENV_RETRY", "1") : unsetLine("_NOENV_RETRY"),
1827
+ setLine("_NOENV_REV_FILE", marker),
1828
+ setLine("_NOENV_REV", revision),
1829
+ setLine("_NOENV_RESTORE", [...restoreLines(step.state), ...STATE_VARIABLES.map(unsetLine)].join("\n"))
1830
+ ],
1831
+ messages,
1832
+ refresh: step.refresh ? { url: deployment.url, root: target.root, environment: target.environment } : void 0
1833
+ };
1834
+ }
1835
+ async function load(input, resolved, state, revision, messages) {
1836
+ const { target, deployment } = resolved;
1837
+ const entering = state === null || !sameTarget(state, resolved);
1838
+ const empty = { url: deployment.url, repo: target.repo, environment: target.environment, previous: {}, retry: false };
1839
+ const restore = state ? restoreLines(state) : [];
1840
+ if (!await loadSession(deployment)) {
1841
+ return { lines: restore, state: await signIn(input, deployment, empty, state, messages), refresh: false };
1842
+ }
1843
+ const entry = await readCache(deployment, target);
1844
+ const identity = await loadIdentity(deployment);
1845
+ const refresh2 = entering || state.retry || revision === CHANGED || !entry || !identity;
1846
+ if (!entering && !state.retry && (!entry || !identity || "raw" in entry && entry.raw.revision === state.revision)) {
1847
+ return { lines: [], state, refresh: refresh2 };
1848
+ }
1849
+ if (!entry || !identity) {
1850
+ return { lines: restore, state: empty, refresh: refresh2 };
1851
+ }
1852
+ const opened = await openEntry(entry, identity.privateKey, target, messages);
1853
+ if (!opened) {
1854
+ return { lines: restore, state: empty, refresh: refresh2 };
1855
+ }
1856
+ const lines = [...restore];
1857
+ const previous = {};
1858
+ for (const [name2, value] of Object.entries(opened.secrets)) {
1859
+ previous[name2] = state && name2 in state.previous ? state.previous[name2] : input.env[name2] ?? null;
1860
+ lines.push(exportLine(name2, value));
1861
+ }
1862
+ const count = Object.keys(opened.secrets).length;
1863
+ const updated = !entering && state.revision !== void 0;
1864
+ messages.push(`${updated ? "updated" : "loaded"} ${count} secrets for ${target.repo} (${target.environment})`);
1865
+ const missing = target.requiredSecrets.filter((name2) => !(name2 in opened.secrets));
1866
+ if (missing.length > 0) messages.push(`missing required secrets: ${missing.join(", ")}`);
1867
+ await watchEnvironment(deployment, target.repo, target.environment);
1868
+ input.startWatcher(deployment);
1869
+ return { lines, state: { ...empty, previous, revision: opened.revision }, refresh: refresh2 };
1870
+ }
1871
+ async function openEntry(entry, privateKey, target, messages) {
1872
+ if ("error" in entry) {
1873
+ if (!(entry.status === 403 && !target.hasConfig) && entry.status !== 401) {
1874
+ messages.push(`could not load secrets for ${target.repo} (${target.environment}): ${entry.error}`);
1875
+ }
1876
+ return null;
1877
+ }
1878
+ messages.push(...entry.notes);
1879
+ if (entry.blocked) return null;
1880
+ try {
1881
+ const bundle = await openBundle(entry.raw, privateKey, target.environment);
1882
+ return { secrets: bundle.secrets, revision: bundle.revision };
1883
+ } catch (error) {
1884
+ messages.push(`could not decrypt secrets for ${target.repo} (${target.environment}): ${describe(error)}`);
1885
+ return null;
1886
+ }
1887
+ }
1888
+ function sameTarget(state, { target, deployment }) {
1889
+ return state.url === deployment.url && state.repo === target.repo && state.environment === target.environment;
1890
+ }
1891
+ async function signIn(input, deployment, empty, state, messages) {
1892
+ const waiting = await readPendingSignIn(deployment);
1893
+ if (state?.notified && !(waiting && waiting.expiresAt > Date.now())) {
1894
+ messages.push("sign-in was not completed, run `noenv auth` to try again");
1895
+ return empty;
1896
+ }
1897
+ try {
1898
+ const { pending, started } = await startSignIn(deployment);
1899
+ if (started) {
1900
+ input.startPoller(deployment);
1901
+ input.openBrowser(pending.url);
1902
+ }
1903
+ if (started || state?.notified !== pending.userCode) {
1904
+ const account = deployment.account ? ` to ${deployment.account}` : "";
1905
+ messages.push(`sign in${account} to load secrets: open ${pending.url} and confirm the code ${pending.userCode}`);
1906
+ }
1907
+ return { ...empty, retry: true, notified: pending.userCode };
1908
+ } catch (error) {
1909
+ messages.push(`could not start sign-in: ${describe(error)}`);
1910
+ return empty;
1911
+ }
1912
+ }
1913
+ async function resolve(input, messages) {
1914
+ try {
1915
+ const target = await findTarget(input.cwd, input.env);
1916
+ const deployment = target && await input.resolveDeployment(target.repo);
1917
+ return target && deployment ? { target, deployment } : null;
1918
+ } catch (error) {
1919
+ messages.push(describe(error));
1920
+ return null;
1921
+ }
1922
+ }
1923
+ function restoreLines(state) {
1924
+ return Object.entries(state.previous).map(([name2, value]) => value === null ? unsetLine(name2) : exportLine(name2, value));
1925
+ }
1926
+ function encodeState(state) {
1927
+ return Buffer.from(JSON.stringify(state)).toString("base64");
1928
+ }
1929
+ function decodeState(text3) {
1930
+ if (!text3?.trim()) return null;
1931
+ try {
1932
+ return JSON.parse(Buffer.from(text3.trim(), "base64").toString("utf8"));
1933
+ } catch {
1934
+ return null;
1935
+ }
1936
+ }
1937
+ function describe(error) {
1938
+ return error instanceof Error ? error.message : "unknown error";
1939
+ }
1940
+
1941
+ // src/commands/exec.ts
1942
+ var SHELL_STATE = ["_NOENV_STATE", "_NOENV_RETRY", "_NOENV_REV_FILE", "_NOENV_REV", "_NOENV_ROOT"];
1943
+ async function execCommand(args2) {
1944
+ const command2 = args2[0] === "--" ? args2.slice(1) : args2;
1945
+ if (command2.length === 0) throw new Error("usage: noenv exec -- COMMAND [ARGS...]");
1946
+ const env = withoutLoadedSecrets(process.env);
1947
+ const secrets = await projectSecrets(env);
1948
+ const child = spawn3(command2[0], command2.slice(1), { stdio: "inherit", env: { ...env, ...secrets } });
1949
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(signal, () => child.kill(signal));
1950
+ const code = await new Promise((resolve2, reject) => {
1951
+ child.on("error", reject);
1952
+ child.on("exit", (exitCode, signal) => resolve2(exitCode ?? 128 + (signal ? constants.signals[signal] : 0)));
1953
+ });
1954
+ process.exit(code);
1955
+ }
1956
+ function withoutLoadedSecrets(env) {
1957
+ const state = decodeState(env._NOENV_STATE);
1958
+ const clean = { ...env };
1959
+ for (const name2 of SHELL_STATE) delete clean[name2];
1960
+ for (const [name2, value] of Object.entries(state?.previous ?? {})) {
1961
+ if (value === null) delete clean[name2];
1962
+ else clean[name2] = value;
1963
+ }
1964
+ return clean;
1965
+ }
1966
+ async function projectSecrets(env) {
1967
+ const target = await findTarget(process.cwd(), env);
1968
+ if (!target) return note("not in a git repository with an origin, running without secrets");
1969
+ const deployment = await resolveDeployment(target.repo, env);
1970
+ if (!deployment) return note("no account is set up, running without secrets");
1971
+ const token = await requireSession(deployment);
1972
+ const identity = await loadIdentity(deployment) ?? await ensureIdentity(deployment, token);
1973
+ const label2 = `${target.repo} (${target.environment})`;
1974
+ let entry = await refresh(deployment, target);
1975
+ if (!entry) {
1976
+ entry = await readCache(deployment, target);
1977
+ if (!entry) throw new Error(`could not reach ${deployment.url} and there are no cached secrets for ${label2}`);
1978
+ note(`could not reach ${deployment.url}, using cached secrets`);
1979
+ }
1980
+ if ("error" in entry) {
1981
+ if ((entry.status === 403 || entry.status === 404) && !target.hasConfig) {
1982
+ return note(`you have no noenv project for ${target.repo} on ${deployment.account ?? deployment.url}, running without secrets`);
1983
+ }
1984
+ throw new Error(`could not load secrets for ${label2}: ${entry.error}`);
1985
+ }
1986
+ for (const line of entry.notes) note(line);
1987
+ if (entry.blocked) throw new Error(`secrets for ${label2} were not loaded because of the .env policy`);
1988
+ const { secrets } = await openBundle(entry.raw, identity.privateKey, target.environment);
1989
+ note(`loaded ${Object.keys(secrets).length} secrets for ${label2}${deployment.account ? ` from ${deployment.account}` : ""}`);
1990
+ const missing = target.requiredSecrets.filter((name2) => !(name2 in secrets));
1991
+ if (missing.length > 0) note(`missing required secrets: ${missing.join(", ")}`);
1992
+ return secrets;
1993
+ }
1994
+ function note(message) {
1995
+ process.stderr.write(`noenv: ${message}
1996
+ `);
1997
+ return {};
1998
+ }
1999
+
2000
+ // src/prompt.ts
2001
+ import { emitKeypressEvents } from "node:readline";
2002
+ import { createInterface } from "node:readline/promises";
2003
+ import { text } from "node:stream/consumers";
2004
+ async function readSecretValue(label2) {
2005
+ if (!process.stdin.isTTY) {
2006
+ return (await text(process.stdin)).replace(/\r?\n$/, "");
2007
+ }
2008
+ process.stderr.write(label2);
2009
+ process.stdin.setRawMode(true);
2010
+ process.stdin.resume();
2011
+ return new Promise((resolve2) => {
2012
+ let value = "";
2013
+ const onData = (chunk) => {
2014
+ for (const char of chunk.toString("utf8")) {
2015
+ if (char === "\r" || char === "\n") {
2016
+ finish();
2017
+ return resolve2(value);
2018
+ }
2019
+ if (char === "") {
2020
+ finish();
2021
+ process.exit(130);
2022
+ }
2023
+ value = char === "\x7F" ? value.slice(0, -1) : value + char;
2024
+ }
2025
+ };
2026
+ const finish = () => {
2027
+ process.stdin.off("data", onData);
2028
+ process.stdin.setRawMode(false);
2029
+ process.stdin.pause();
2030
+ process.stderr.write("\n");
2031
+ };
2032
+ process.stdin.on("data", onData);
2033
+ });
2034
+ }
2035
+ async function confirm(question) {
2036
+ if (!process.stdin.isTTY) return false;
2037
+ const readline = createInterface({ input: process.stdin, output: process.stderr });
2038
+ const answer = await readline.question(`${question} [y/N] `);
2039
+ readline.close();
2040
+ return answer.trim().toLowerCase() === "y";
2041
+ }
2042
+ async function checklist(title, items, checked) {
2043
+ const input = process.stdin;
2044
+ const output = process.stderr;
2045
+ const selected = new Set([...checked].filter((item) => items.includes(item)));
2046
+ const height = Math.min(items.length, Math.max(5, (output.rows ?? 24) - 3));
2047
+ let cursor = 0;
2048
+ let top = 0;
2049
+ let drawn = 0;
2050
+ const render = () => {
2051
+ top = Math.min(Math.max(top, cursor - height + 1), cursor);
2052
+ const rows = items.slice(top, top + height).map((item, offset) => {
2053
+ const active = top + offset === cursor;
2054
+ const line = `${active ? "\u203A" : " "} ${selected.has(item) ? "[x]" : "[ ]"} ${item}`;
2055
+ return active ? `\x1B[1m${line}\x1B[22m` : line;
2056
+ });
2057
+ const help = `\x1B[2m${selected.size} of ${items.length} selected \xB7 space select \xB7 a all \xB7 enter confirm \xB7 esc cancel\x1B[22m`;
2058
+ const lines = [title, ...rows, help];
2059
+ output.write((drawn > 0 ? `\x1B[${drawn}A` : "") + lines.map((line) => `\x1B[2K${line}
2060
+ `).join(""));
2061
+ drawn = lines.length;
2062
+ };
2063
+ emitKeypressEvents(input);
2064
+ input.setRawMode(true);
2065
+ input.resume();
2066
+ output.write("\x1B[?25l");
2067
+ return new Promise((resolve2) => {
2068
+ const finish = (result) => {
2069
+ input.off("keypress", onKey);
2070
+ input.setRawMode(false);
2071
+ input.pause();
2072
+ output.write("\x1B[?25h");
2073
+ resolve2(result);
2074
+ };
2075
+ const onKey = (_text, key = {}) => {
2076
+ if (key.ctrl && key.name === "c" || key.name === "escape" || key.name === "q") return finish(null);
2077
+ if (key.name === "return") return finish(items.filter((item) => selected.has(item)));
2078
+ if (key.name === "up" || key.name === "k") cursor = (cursor - 1 + items.length) % items.length;
2079
+ if (key.name === "down" || key.name === "j") cursor = (cursor + 1) % items.length;
2080
+ if (key.name === "space") {
2081
+ const item = items[cursor];
2082
+ if (selected.has(item)) selected.delete(item);
2083
+ else selected.add(item);
2084
+ }
2085
+ if (key.name === "a") {
2086
+ const all = items.every((item) => selected.has(item));
2087
+ for (const item of items) all ? selected.delete(item) : selected.add(item);
2088
+ }
2089
+ render();
2090
+ };
2091
+ input.on("keypress", onKey);
2092
+ render();
2093
+ });
2094
+ }
2095
+
2096
+ // src/wrangler.ts
2097
+ import { spawn as spawn4 } from "node:child_process";
2098
+ import { access } from "node:fs/promises";
2099
+ import { dirname as dirname2, join as join8 } from "node:path";
2100
+ function wranglerSource(target) {
2101
+ return target.wrangler.environment ?? target.environment;
2102
+ }
2103
+ async function putWranglerSecrets(target, secrets) {
2104
+ const names = Object.keys(secrets);
2105
+ const env = target.wrangler.env ? ` --env ${target.wrangler.env}` : "";
2106
+ console.log(`Pushing ${names.length} secrets from noenv (${wranglerSource(target)}) to Wrangler${env}: ${names.join(", ")}`);
2107
+ const args2 = ["secret", "bulk", ...target.wrangler.env ? ["--env", target.wrangler.env] : []];
2108
+ const child = spawn4(await findWrangler(target.root), args2, { cwd: target.root, stdio: ["pipe", "inherit", "inherit"] });
2109
+ child.stdin.end(JSON.stringify(secrets));
2110
+ const code = await new Promise((resolve2, reject) => {
2111
+ child.on(
2112
+ "error",
2113
+ (error) => reject(error.code === "ENOENT" ? new Error("wrangler is not installed, run `npm install -D wrangler`") : error)
2114
+ );
2115
+ child.on("exit", (exitCode) => resolve2(exitCode ?? 1));
2116
+ });
2117
+ if (code !== 0) throw new Error(`wrangler secret bulk failed with exit code ${code}`);
2118
+ }
2119
+ async function findWrangler(root) {
2120
+ for (let dir = root; ; dir = dirname2(dir)) {
2121
+ const local = join8(dir, "node_modules", ".bin", "wrangler");
2122
+ if (await access(local).then(() => true, () => false)) return local;
2123
+ if (dirname2(dir) === dir) return "wrangler";
2124
+ }
2125
+ }
2126
+
2127
+ // src/commands/wrangler.ts
2128
+ async function wranglerCommand(args2) {
2129
+ const invalid = args2.find((name2) => !ENV_VAR_NAME.test(name2));
2130
+ if (invalid) throw new Error(`usage: noenv wrangler [KEY...] (${invalid} is not a variable name)`);
2131
+ const { deployment, token, identity, target } = await inProject();
2132
+ const environment = wranglerSource(target);
2133
+ const label2 = `${target.repo} (${environment})`;
2134
+ const { secrets } = await fetchBundle(deployment, token, identity.privateKey, target.repo, environment);
2135
+ const names = Object.keys(secrets).sort();
2136
+ if (names.length === 0) throw new Error(`there are no secrets in ${label2}`);
2137
+ const selected = await choose(args2, names, target.wrangler.secrets, label2);
2138
+ if (!selected) return console.log("Cancelled, nothing was pushed");
2139
+ if (selected.length === 0) return console.log("Nothing selected, nothing was pushed");
2140
+ const missing = selected.filter((name2) => !(name2 in secrets));
2141
+ if (missing.length > 0) throw new Error(`${label2} has no secret named ${missing.join(", ")}`);
2142
+ await putWranglerSecrets(target, Object.fromEntries(selected.map((name2) => [name2, secrets[name2]])));
2143
+ }
2144
+ async function choose(args2, names, configured, label2) {
2145
+ if (args2.length > 0) return args2;
2146
+ if (process.stdin.isTTY && process.stderr.isTTY) {
2147
+ return checklist(`Push secrets from ${label2} to Wrangler`, names, configured);
2148
+ }
2149
+ if (configured.length === 0) {
2150
+ throw new Error("pass the KEY names, or list them under [wrangler] secrets in .noenv");
2151
+ }
2152
+ return configured;
2153
+ }
2154
+
2155
+ // src/commands/migrate.ts
2156
+ import { relative as relative2 } from "node:path";
2157
+ async function migrateCommand() {
2158
+ const { deployment, token, identity, target } = await inProject();
2159
+ const bundle = await fetchBundle(deployment, token, identity.privateKey, target.repo, target.environment);
2160
+ const store = remoteSecretStore(deployment, token, identity, target.repo, target.environment, bundle);
2161
+ const paths = await findDotenvFiles(target.root, bundle.policies.dotenv);
2162
+ const outcomes = [];
2163
+ if (paths.length === 0) {
2164
+ console.log("No .env files found");
2165
+ return;
2166
+ }
2167
+ for (const path of paths) {
2168
+ const name2 = relative2(target.root, path);
2169
+ const file = await readDotenvFile(path);
2170
+ if (file.invalidNames.length > 0) {
2171
+ console.log(`${name2}: skipped, invalid names: ${file.invalidNames.join(", ")}`);
2172
+ outcomes.push({ path, status: "invalid", names: file.invalidNames });
2173
+ continue;
2174
+ }
2175
+ const result = await migrateDotenvFile(file, store);
2176
+ if (result.conflicts.length > 0) {
2177
+ console.log(`${name2}: kept, values differ from noenv for ${result.conflicts.join(", ")}`);
2178
+ outcomes.push({ path, status: "conflict", names: result.conflicts });
2179
+ continue;
2180
+ }
2181
+ if (!result.verified) {
2182
+ console.log(`${name2}: kept, could not verify the upload`);
2183
+ outcomes.push({ path, status: "failed", names: [] });
2184
+ continue;
2185
+ }
2186
+ console.log(`${name2}: ${Object.keys(file.values).length} values are stored in noenv`);
2187
+ if (!await confirm(`Delete ${name2}?`)) {
2188
+ outcomes.push({ path, status: "migrated", names: [] });
2189
+ continue;
2190
+ }
2191
+ const deleted = await removeIfUnchanged(file);
2192
+ console.log(deleted ? `${name2}: deleted` : `${name2}: kept, the file changed`);
2193
+ outcomes.push({ path, status: deleted ? "deleted" : "changed", names: [] });
2194
+ }
2195
+ await markChanged(deployment, target.repo, target.environment);
2196
+ await reportCompliance(deployment, token, target, {
2197
+ blocked: outcomes.some((outcome) => outcome.status !== "deleted"),
2198
+ files: outcomes
2199
+ });
2200
+ }
2201
+
2202
+ // src/commands/project.ts
2203
+ import { writeFile as writeFile3 } from "node:fs/promises";
2204
+ import { basename, join as join9 } from "node:path";
2205
+ var ROLES = ["reader", "editor", "admin"];
2206
+ async function initCommand() {
2207
+ const { deployment, token, identity, target } = await inProject();
2208
+ try {
2209
+ await api(deployment, "POST", "/v1/projects", { token, body: { name: basename(target.root), repo: target.repo } });
2210
+ console.log(`Created project ${target.repo}`);
2211
+ } catch (error) {
2212
+ if (!(error instanceof ApiError && error.status === 409)) throw error;
2213
+ }
2214
+ const environmentKeys = await generateKeyPair();
2215
+ const wrappedKey = await wrapPrivateKey(environmentKeys.privateKey, await importPublicKey(identity.publicKey));
2216
+ try {
2217
+ await api(deployment, "POST", `${repoPath(target.repo)}/environments/${target.environment}`, {
2218
+ token,
2219
+ body: { publicKey: await exportPublicKey(environmentKeys.publicKey), wrappedKey }
2220
+ });
2221
+ console.log(`Created environment ${target.environment}`);
2222
+ } catch (error) {
2223
+ if (!(error instanceof ApiError && error.status === 409)) throw error;
2224
+ console.log(`Environment ${target.environment} already exists`);
2225
+ }
2226
+ try {
2227
+ await writeFile3(join9(target.root, CONFIG_FILE), `version = 1
2228
+ environment = "${target.environment}"
2229
+ `, { flag: "wx" });
2230
+ console.log(`Created ${CONFIG_FILE}, commit it so teammates load this project`);
2231
+ } catch (error) {
2232
+ if (error.code !== "EEXIST") throw error;
2233
+ }
2234
+ }
2235
+ async function inviteCommand([email]) {
2236
+ if (!email) throw new Error("usage: noenv invite EMAIL");
2237
+ const { deployment, token } = await signedIn();
2238
+ const invite = await api(deployment, "POST", "/v1/users", { token, body: { email } });
2239
+ console.log(invite.emailed ? `Invite emailed to ${email}. The link, in case they need it:` : `Invited ${email}. Send them this link:`);
2240
+ console.log(` ${invite.inviteUrl}`);
2241
+ }
2242
+ async function grantCommand([email, role]) {
2243
+ if (!email || !ROLES.includes(role ?? "")) {
2244
+ throw new Error("usage: noenv grant EMAIL reader|editor|admin");
2245
+ }
2246
+ const { deployment, token, identity, target } = await inProject();
2247
+ const user = await findUser(deployment, token, email);
2248
+ await api(deployment, "PUT", `${repoPath(target.repo)}/members/${user.id}`, { token, body: { role } });
2249
+ console.log(`${email} is now ${role} of ${target.repo}`);
2250
+ if (!user.publicKey) {
2251
+ console.log(`${email} has not signed in yet. Run this command again after they sign in to share the key.`);
2252
+ return;
2253
+ }
2254
+ const bundle = await fetchBundle(deployment, token, identity.privateKey, target.repo, target.environment);
2255
+ const wrappedKey = await wrapPrivateKey(bundle.environmentPrivateKey, await importPublicKey(user.publicKey));
2256
+ await api(deployment, "PUT", `${environmentPath(target.repo, target.environment)}/keys/${user.id}`, {
2257
+ token,
2258
+ body: { wrappedKey }
2259
+ });
2260
+ console.log(`Shared the ${target.environment} key with ${email}`);
2261
+ }
2262
+ async function revokeCommand([email]) {
2263
+ if (!email) throw new Error("usage: noenv revoke EMAIL");
2264
+ const { deployment, token, target } = await inProject();
2265
+ const user = await findUser(deployment, token, email);
2266
+ await api(deployment, "DELETE", `${repoPath(target.repo)}/members/${user.id}`, { token });
2267
+ console.log(`Removed ${email} from ${target.repo}. Rotate secrets they could read.`);
2268
+ }
2269
+ async function findUser(deployment, token, email) {
2270
+ return api(deployment, "GET", `/v1/users/lookup?email=${encodeURIComponent(email)}`, { token });
2271
+ }
2272
+
2273
+ // src/commands/secret.ts
2274
+ async function secretCommand([action, ...args2]) {
2275
+ const handlers = {
2276
+ set: setSecret,
2277
+ list: listSecrets,
2278
+ history: secretHistory,
2279
+ rollback: rollbackSecret
2280
+ };
2281
+ const handler = handlers[action ?? ""];
2282
+ if (!handler) {
2283
+ throw new Error("usage: noenv secret set|list|history|rollback");
2284
+ }
2285
+ await handler(args2);
2286
+ }
2287
+ async function setSecret([name2]) {
2288
+ requireName(name2);
2289
+ const { deployment, token, identity, target } = await inProject();
2290
+ const value = await readSecretValue(`Value for ${name2}: `);
2291
+ if (value === "") {
2292
+ throw new Error("the value is empty, nothing was saved");
2293
+ }
2294
+ const store = remoteSecretStore(deployment, token, identity, target.repo, target.environment);
2295
+ const version = await store.set(name2, value);
2296
+ await markChanged(deployment, target.repo, target.environment);
2297
+ console.log(`Saved ${name2} as version ${version} in ${target.repo} (${target.environment})`);
2298
+ await syncToWrangler(target, name2, async () => value);
2299
+ }
2300
+ async function listSecrets() {
2301
+ const { deployment, token, target } = await inProject();
2302
+ const { secrets } = await api(
2303
+ deployment,
2304
+ "GET",
2305
+ `${environmentPath(target.repo, target.environment)}/secrets`,
2306
+ { token }
2307
+ );
2308
+ for (const secret of secrets) {
2309
+ console.log(`${secret.name} v${secret.version} ${secret.updatedAt} ${secret.author}`);
2310
+ }
2311
+ }
2312
+ async function secretHistory([name2]) {
2313
+ requireName(name2);
2314
+ const { deployment, token, target } = await inProject();
2315
+ const { versions } = await api(
2316
+ deployment,
2317
+ "GET",
2318
+ `${environmentPath(target.repo, target.environment)}/secrets/${name2}/versions`,
2319
+ { token }
2320
+ );
2321
+ for (const version of versions) {
2322
+ const restored = version.restoredFrom ? ` restored from v${version.restoredFrom}` : "";
2323
+ console.log(`v${version.version} ${version.createdAt} ${version.author}${restored}`);
2324
+ }
2325
+ }
2326
+ async function rollbackSecret([name2, version]) {
2327
+ requireName(name2);
2328
+ if (!/^\d+$/.test(version ?? "")) {
2329
+ throw new Error("usage: noenv secret rollback KEY VERSION");
2330
+ }
2331
+ const { deployment, token, identity, target } = await inProject();
2332
+ const result = await api(
2333
+ deployment,
2334
+ "POST",
2335
+ `${environmentPath(target.repo, target.environment)}/secrets/${name2}/rollback`,
2336
+ { token, body: { version: Number(version) } }
2337
+ );
2338
+ await markChanged(deployment, target.repo, target.environment);
2339
+ console.log(`Restored ${name2} v${version} as v${result.version}`);
2340
+ await syncToWrangler(target, name2, async () => {
2341
+ const { secrets } = await fetchBundle(deployment, token, identity.privateKey, target.repo, target.environment);
2342
+ return secrets[name2];
2343
+ });
2344
+ }
2345
+ async function syncToWrangler(target, name2, value) {
2346
+ if (!target.wrangler.secrets.includes(name2)) return;
2347
+ if (wranglerSource(target) !== target.environment) {
2348
+ console.log(`Not pushed to Wrangler: .noenv pushes values from ${wranglerSource(target)}, not ${target.environment}`);
2349
+ return;
2350
+ }
2351
+ try {
2352
+ await putWranglerSecrets(target, { [name2]: await value() });
2353
+ } catch (error) {
2354
+ const reason = error instanceof Error ? error.message : "unknown error";
2355
+ throw new Error(`${name2} is saved in noenv, but the Wrangler update failed: ${reason}. Run \`noenv wrangler ${name2}\` to try again`);
2356
+ }
2357
+ }
2358
+ function requireName(name2) {
2359
+ if (!name2 || !ENV_VAR_NAME.test(name2)) {
2360
+ throw new Error("the secret name must be a valid environment variable name");
2361
+ }
2362
+ }
2363
+
2364
+ // src/commands/shell.ts
2365
+ import { text as text2 } from "node:stream/consumers";
2366
+ async function shellCommand([shell]) {
2367
+ process.stdout.write(hookScript(parseShell(shell)));
2368
+ }
2369
+ async function hookEnvCommand([shell]) {
2370
+ parseShell(shell);
2371
+ const state = process.stdin.isTTY ? "" : await text2(process.stdin);
2372
+ const { lines, messages, refresh: job } = await hookEnv({
2373
+ cwd: process.cwd(),
2374
+ env: process.env,
2375
+ state,
2376
+ resolveDeployment: (repo) => resolveDeployment(repo),
2377
+ startPoller: startBackgroundPoller,
2378
+ startWatcher: (deployment) => void startWatcher(deployment),
2379
+ openBrowser
2380
+ });
2381
+ for (const message of messages) process.stderr.write(`noenv: ${message}
2382
+ `);
2383
+ if (job) lines.push(`_noenv_refresh ${quote(job.url)} ${quote(job.root)} ${quote(job.environment)}`);
2384
+ process.stdout.write(lines.join("\n"));
2385
+ }
2386
+ async function refreshCommand([url, root, environment]) {
2387
+ if (!url || !root || !environment) throw new Error("usage: noenv refresh URL ROOT ENVIRONMENT");
2388
+ const target = await findTarget(root, { ...process.env, NOENV_ENVIRONMENT: environment });
2389
+ if (target) await refresh(deploymentAt(url), target);
2390
+ }
2391
+ async function watchCommand([url]) {
2392
+ if (!url) throw new Error("usage: noenv watch URL");
2393
+ await runWatcher(deploymentAt(url));
2394
+ }
2395
+
2396
+ // src/main.ts
2397
+ var USAGE2 = `usage: noenv <command>
2398
+
2399
+ shell zsh|bash print the shell hook for your shell profile
2400
+ account add NAME URL [PREFIX...]
2401
+ add an account, such as work or personal; repos
2402
+ under a PREFIX (github.com/acme) use it
2403
+ account list list accounts, * marks the default
2404
+ account default NAME use NAME where no prefix matches
2405
+ account remove NAME forget an account
2406
+ auth [NAME] sign in to an account (default: the one for this repo)
2407
+ status show the account, user, and project
2408
+ init create the project, the environment, and the .noenv file
2409
+ exec -- COMMAND run COMMAND with this repository's secrets, for agents,
2410
+ scripts, and CI; it picks the account and project from
2411
+ the current directory
2412
+ secret set KEY save a secret (the value is read without echo)
2413
+ secret list list secrets in this environment
2414
+ secret history KEY list the versions of a secret
2415
+ secret rollback KEY VER restore an older version of a secret
2416
+ migrate move .env files of this repository into noenv
2417
+ wrangler [KEY...] push secrets to the Worker with wrangler; without KEY,
2418
+ pick them in a list (keys under [wrangler] secrets in
2419
+ .noenv are checked; without a terminal, push those)
2420
+ invite EMAIL invite a user to this deployment
2421
+ grant EMAIL ROLE give a user access to this project and environment
2422
+ revoke EMAIL remove a user from this project
2423
+ `;
2424
+ var commands = {
2425
+ account: accountCommand,
2426
+ shell: shellCommand,
2427
+ "hook-env": hookEnvCommand,
2428
+ refresh: refreshCommand,
2429
+ exec: execCommand,
2430
+ watch: watchCommand,
2431
+ auth: authCommand,
2432
+ status: statusCommand,
2433
+ init: initCommand,
2434
+ secret: secretCommand,
2435
+ migrate: migrateCommand,
2436
+ wrangler: wranglerCommand,
2437
+ invite: inviteCommand,
2438
+ grant: grantCommand,
2439
+ revoke: revokeCommand
2440
+ };
2441
+ var [name, ...args] = process.argv.slice(2);
2442
+ var command = commands[name ?? ""];
2443
+ if (!command) {
2444
+ process.stdout.write(USAGE2);
2445
+ process.exit(name ? 1 : 0);
2446
+ }
2447
+ try {
2448
+ await command(args);
2449
+ } catch (error) {
2450
+ process.stderr.write(`noenv: ${error instanceof Error ? error.message : "unknown error"}
2451
+ `);
2452
+ process.exit(1);
2453
+ }
2454
+ /*! Bundled license information:
2455
+
2456
+ smol-toml/dist/error.js:
2457
+ smol-toml/dist/primitive.js:
2458
+ smol-toml/dist/date.js:
2459
+ smol-toml/dist/extract.js:
2460
+ smol-toml/dist/util.js:
2461
+ smol-toml/dist/struct.js:
2462
+ smol-toml/dist/parse.js:
2463
+ smol-toml/dist/stringify.js:
2464
+ smol-toml/dist/index.js:
2465
+ (*!
2466
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
2467
+ * SPDX-License-Identifier: BSD-3-Clause
2468
+ *
2469
+ * Redistribution and use in source and binary forms, with or without
2470
+ * modification, are permitted provided that the following conditions are met:
2471
+ *
2472
+ * 1. Redistributions of source code must retain the above copyright notice, this
2473
+ * list of conditions and the following disclaimer.
2474
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
2475
+ * this list of conditions and the following disclaimer in the
2476
+ * documentation and/or other materials provided with the distribution.
2477
+ * 3. Neither the name of the copyright holder nor the names of its contributors
2478
+ * may be used to endorse or promote products derived from this software without
2479
+ * specific prior written permission.
2480
+ *
2481
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
2482
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2483
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2484
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2485
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2486
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2487
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2488
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2489
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2490
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2491
+ *)
2492
+ */