@env-lane/core 0.1.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/index.cjs ADDED
@@ -0,0 +1,942 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ buildEnvSortPlan: () => buildEnvSortPlan,
34
+ checkDotenvSelector: () => checkDotenvSelector,
35
+ defineConfig: () => defineConfig,
36
+ findWorkspaceRoot: () => findWorkspaceRoot,
37
+ getLogger: () => getLogger,
38
+ isSecretLikeKey: () => isSecretLikeKey,
39
+ listEnvFiles: () => listEnvFiles,
40
+ listEnvFilesForTarget: () => listEnvFilesForTarget,
41
+ listWorkspacePackages: () => listWorkspacePackages,
42
+ listWorkspacePackagesForConfig: () => listWorkspacePackagesForConfig,
43
+ loadEnvLaneConfig: () => loadEnvLaneConfig,
44
+ readPnpmWorkspaceGlobs: () => readPnpmWorkspaceGlobs,
45
+ redactRecord: () => redactRecord,
46
+ redactValue: () => redactValue,
47
+ resolveBuildName: () => resolveBuildName,
48
+ resolveInjectedEnv: () => resolveInjectedEnv,
49
+ resolveTargetPackage: () => resolveTargetPackage,
50
+ resolveTargetPackageFromList: () => resolveTargetPackageFromList,
51
+ runWithInjectedEnv: () => runWithInjectedEnv,
52
+ setLogger: () => setLogger,
53
+ sortEnvFile: () => sortEnvFile,
54
+ sortEnvFilesFromConfig: () => sortEnvFilesFromConfig
55
+ });
56
+ module.exports = __toCommonJS(index_exports);
57
+
58
+ // src/check.ts
59
+ var import_node_fs4 = require("fs");
60
+ var import_node_path4 = __toESM(require("path"), 1);
61
+ var import_dotenv2 = require("dotenv");
62
+ var import_fast_glob2 = __toESM(require("fast-glob"), 1);
63
+
64
+ // src/config.ts
65
+ var import_node_fs = require("fs");
66
+ var import_node_path = __toESM(require("path"), 1);
67
+ var import_c12 = require("c12");
68
+ var import_find_up = require("find-up");
69
+ var import_yaml = __toESM(require("yaml"), 1);
70
+ var import_zod = require("zod");
71
+ var sortTargetSchema = import_zod.z.object({
72
+ baseDir: import_zod.z.string().min(1).optional(),
73
+ file: import_zod.z.string().min(1).optional(),
74
+ template: import_zod.z.string().min(1).optional(),
75
+ files: import_zod.z.record(import_zod.z.string(), import_zod.z.string().min(1)).optional()
76
+ });
77
+ var schema = import_zod.z.object({
78
+ selector: import_zod.z.object({
79
+ envKey: import_zod.z.string().min(1).optional(),
80
+ defaultBuild: import_zod.z.string().min(1).optional(),
81
+ builds: import_zod.z.array(import_zod.z.string().min(1)).optional(),
82
+ forbidInDotenv: import_zod.z.boolean().optional()
83
+ }).optional(),
84
+ workspace: import_zod.z.object({
85
+ packageGlobs: import_zod.z.array(import_zod.z.string().min(1)).optional(),
86
+ aliases: import_zod.z.record(import_zod.z.string(), import_zod.z.string().min(1)).optional(),
87
+ defaultTarget: import_zod.z.string().min(1).optional(),
88
+ includeRoot: import_zod.z.boolean().optional()
89
+ }).optional(),
90
+ dotenv: import_zod.z.object({
91
+ order: import_zod.z.array(import_zod.z.string().min(1)).optional(),
92
+ localBuildName: import_zod.z.string().min(1).optional(),
93
+ localOverrideFile: import_zod.z.string().min(1).optional(),
94
+ requireOverride: import_zod.z.boolean().optional(),
95
+ includeProcessEnv: import_zod.z.boolean().optional()
96
+ }).optional(),
97
+ vault: import_zod.z.object({
98
+ enabled: import_zod.z.boolean().optional(),
99
+ disableUnsafeWarning: import_zod.z.boolean().optional(),
100
+ configFile: import_zod.z.string().min(1).optional()
101
+ }).optional(),
102
+ output: import_zod.z.object({
103
+ format: import_zod.z.enum(["text", "json", "dotenv"]).optional()
104
+ }).optional(),
105
+ sort: import_zod.z.record(import_zod.z.string(), sortTargetSchema).optional()
106
+ }).passthrough();
107
+ function defineConfig(config) {
108
+ return config;
109
+ }
110
+ async function findWorkspaceRoot(cwd = process.cwd()) {
111
+ const marker = await (0, import_find_up.findUp)(["pnpm-workspace.yaml", "package.json", ".git"], {
112
+ cwd,
113
+ type: "file"
114
+ });
115
+ if (!marker) return import_node_path.default.resolve(cwd);
116
+ if (import_node_path.default.basename(marker) === ".git") return import_node_path.default.dirname(marker);
117
+ if (import_node_path.default.basename(marker) === "package.json") {
118
+ const pnpm = await (0, import_find_up.findUp)("pnpm-workspace.yaml", { cwd: import_node_path.default.dirname(marker), type: "file" });
119
+ return pnpm ? import_node_path.default.dirname(pnpm) : import_node_path.default.dirname(marker);
120
+ }
121
+ return import_node_path.default.dirname(marker);
122
+ }
123
+ function readPnpmWorkspaceGlobs(rootDir) {
124
+ const workspaceFile = import_node_path.default.join(rootDir, "pnpm-workspace.yaml");
125
+ if (!(0, import_node_fs.existsSync)(workspaceFile)) return [];
126
+ const doc = import_yaml.default.parse((0, import_node_fs.readFileSync)(workspaceFile, "utf8"));
127
+ return Array.isArray(doc?.packages) ? doc.packages.filter((item) => typeof item === "string") : [];
128
+ }
129
+ async function loadEnvLaneConfig(options = {}) {
130
+ const rootDir = await findWorkspaceRoot(options.cwd);
131
+ const configFileName = options.configFile ? import_node_path.default.relative(rootDir, import_node_path.default.resolve(rootDir, options.configFile)) : void 0;
132
+ const loaded = await (0, import_c12.loadConfig)({
133
+ name: "env-lane",
134
+ cwd: rootDir,
135
+ configFile: configFileName,
136
+ packageJson: false,
137
+ dotenv: false,
138
+ rcFile: false,
139
+ globalRc: false
140
+ });
141
+ const parsed = schema.parse(loaded.config ?? {});
142
+ const workspaceGlobs = parsed.workspace?.packageGlobs ?? readPnpmWorkspaceGlobs(rootDir) ?? [];
143
+ return {
144
+ rootDir,
145
+ selector: {
146
+ envKey: parsed.selector?.envKey ?? "ENV_BUILD",
147
+ defaultBuild: parsed.selector?.defaultBuild ?? "local",
148
+ builds: parsed.selector?.builds ?? [],
149
+ forbidInDotenv: parsed.selector?.forbidInDotenv ?? true
150
+ },
151
+ workspace: {
152
+ packageGlobs: workspaceGlobs.length ? workspaceGlobs : ["packages/*", "apps/*"],
153
+ aliases: parsed.workspace?.aliases ?? {},
154
+ defaultTarget: parsed.workspace?.defaultTarget ?? "",
155
+ includeRoot: parsed.workspace?.includeRoot ?? true
156
+ },
157
+ dotenv: {
158
+ order: parsed.dotenv?.order ?? [".env", ".env.{build}"],
159
+ localBuildName: parsed.dotenv?.localBuildName ?? "local",
160
+ localOverrideFile: parsed.dotenv?.localOverrideFile ?? ".env.local",
161
+ requireOverride: parsed.dotenv?.requireOverride ?? false,
162
+ includeProcessEnv: parsed.dotenv?.includeProcessEnv ?? true
163
+ },
164
+ vault: {
165
+ enabled: parsed.vault?.enabled ?? false,
166
+ disableUnsafeWarning: parsed.vault?.disableUnsafeWarning ?? false,
167
+ configFile: parsed.vault?.configFile ?? "env-lane.vault.json"
168
+ },
169
+ output: {
170
+ format: parsed.output?.format ?? "text"
171
+ },
172
+ sort: parsed.sort
173
+ };
174
+ }
175
+
176
+ // src/dotenv.ts
177
+ var import_node_fs3 = require("fs");
178
+ var import_node_path3 = __toESM(require("path"), 1);
179
+ var import_dotenv = require("dotenv");
180
+
181
+ // src/workspace.ts
182
+ var import_node_fs2 = require("fs");
183
+ var import_node_path2 = __toESM(require("path"), 1);
184
+ var import_fast_glob = __toESM(require("fast-glob"), 1);
185
+ function readPackageName(dir) {
186
+ const file = import_node_path2.default.join(dir, "package.json");
187
+ if (!(0, import_node_fs2.existsSync)(file)) return void 0;
188
+ try {
189
+ const json = JSON.parse((0, import_node_fs2.readFileSync)(file, "utf8"));
190
+ return typeof json.name === "string" ? json.name : void 0;
191
+ } catch {
192
+ return void 0;
193
+ }
194
+ }
195
+ function unique(values) {
196
+ return [...new Set(values)];
197
+ }
198
+ async function listWorkspacePackages(options = {}) {
199
+ const config = options.config ?? await loadEnvLaneConfig(options);
200
+ return listWorkspacePackagesForConfig(config);
201
+ }
202
+ async function listWorkspacePackagesForConfig(config) {
203
+ const entries = await (0, import_fast_glob.default)(config.workspace.packageGlobs, {
204
+ cwd: config.rootDir,
205
+ onlyDirectories: true,
206
+ absolute: true,
207
+ ignore: ["**/node_modules/**", "**/dist/**"]
208
+ });
209
+ const packages = [];
210
+ if (config.workspace.includeRoot) {
211
+ const rootName = readPackageName(config.rootDir);
212
+ packages.push({
213
+ name: rootName,
214
+ dir: config.rootDir,
215
+ relativeDir: ".",
216
+ aliases: unique(["root", ".", rootName].filter(Boolean)),
217
+ isRoot: true
218
+ });
219
+ }
220
+ for (const dir of entries.sort()) {
221
+ const packageJson = import_node_path2.default.join(dir, "package.json");
222
+ if (!(0, import_node_fs2.existsSync)(packageJson)) continue;
223
+ const name = readPackageName(dir);
224
+ const relativeDir = import_node_path2.default.relative(config.rootDir, dir).replaceAll(import_node_path2.default.sep, "/");
225
+ packages.push({
226
+ name,
227
+ dir,
228
+ relativeDir,
229
+ aliases: unique([name, import_node_path2.default.basename(dir), relativeDir].filter(Boolean)),
230
+ isRoot: false
231
+ });
232
+ }
233
+ for (const [alias, target] of Object.entries(config.workspace.aliases)) {
234
+ const matched = packages.find(
235
+ (pkg) => pkg.name === target || pkg.relativeDir === target || import_node_path2.default.basename(pkg.dir) === target
236
+ );
237
+ if (matched && !matched.aliases.includes(alias)) matched.aliases.push(alias);
238
+ }
239
+ const byDir = /* @__PURE__ */ new Map();
240
+ for (const pkg of packages) byDir.set(pkg.dir, pkg);
241
+ return [...byDir.values()];
242
+ }
243
+ function targetMatchesPackage(pkg, value) {
244
+ return pkg.aliases.includes(value) || pkg.name === value || pkg.relativeDir === value;
245
+ }
246
+ function formatAvailableTargets(packages) {
247
+ return unique(packages.flatMap((pkg) => pkg.aliases)).join(", ");
248
+ }
249
+ function resolveTargetPackageFromList(target, config, packages) {
250
+ const value = (target || config.workspace.defaultTarget || "").trim();
251
+ if (!value) {
252
+ const nonRoot = packages.filter((pkg) => !pkg.isRoot);
253
+ if (nonRoot.length === 0) return packages.find((pkg) => pkg.isRoot) ?? packages[0];
254
+ throw new Error(`Missing target. Available targets: ${formatAvailableTargets(packages)}`);
255
+ }
256
+ const matches = packages.filter((pkg) => targetMatchesPackage(pkg, value));
257
+ if (matches.length > 1) {
258
+ throw new Error(
259
+ `Ambiguous target '${value}'. Matches: ${matches.map((pkg) => pkg.name ?? pkg.relativeDir).join(", ")}. Use a package name, relative directory, or configure a unique alias.`
260
+ );
261
+ }
262
+ const matched = matches[0];
263
+ if (!matched) {
264
+ throw new Error(
265
+ `Unknown target '${value}'. Available targets: ${formatAvailableTargets(packages)}`
266
+ );
267
+ }
268
+ return matched;
269
+ }
270
+ async function resolveTargetPackage(target, options = {}) {
271
+ const config = options.config ?? await loadEnvLaneConfig(options);
272
+ const packages = options.packages ?? await listWorkspacePackagesForConfig(config);
273
+ return resolveTargetPackageFromList(target, config, packages);
274
+ }
275
+
276
+ // src/dotenv.ts
277
+ function resolveBuildName(options, envKey, defaultBuild) {
278
+ const raw = String(options.build ?? process.env[envKey] ?? defaultBuild).trim();
279
+ if (!raw) throw new Error("Build name is empty.");
280
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(raw)) throw new Error(`Invalid build name '${raw}'.`);
281
+ return raw;
282
+ }
283
+ function patternToFile(pattern, build, localBuildName, localOverrideFile) {
284
+ if (pattern === ".env.{build}" && build === localBuildName) return localOverrideFile;
285
+ return pattern.replaceAll("{build}", build);
286
+ }
287
+ async function listEnvFiles(options = {}) {
288
+ const config = await loadEnvLaneConfig(options);
289
+ const target = await resolveTargetPackage(options.target, { ...options, config });
290
+ return listEnvFilesForTarget(config, target, options);
291
+ }
292
+ function listEnvFilesForTarget(config, target, options = {}) {
293
+ const build = resolveBuildName(options, config.selector.envKey, config.selector.defaultBuild);
294
+ return config.dotenv.order.map((pattern, index) => {
295
+ const fileName = patternToFile(
296
+ pattern,
297
+ build,
298
+ config.dotenv.localBuildName,
299
+ config.dotenv.localOverrideFile
300
+ );
301
+ const filePath = import_node_path3.default.resolve(target.dir, fileName);
302
+ return {
303
+ kind: index === 0 ? "base" : index === 1 ? "override" : "custom",
304
+ path: filePath,
305
+ relativePath: import_node_path3.default.relative(config.rootDir, filePath).replaceAll(import_node_path3.default.sep, "/"),
306
+ exists: (0, import_node_fs3.existsSync)(filePath),
307
+ required: index > 0 && Boolean(options.requireOverride ?? config.dotenv.requireOverride),
308
+ order: index
309
+ };
310
+ });
311
+ }
312
+ function lineForKey(content, key) {
313
+ const lines = content.split(/\r?\n/);
314
+ const re = new RegExp(`^\\s*(?:export\\s+)?${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*=`);
315
+ const idx = lines.findIndex((line) => re.test(line));
316
+ return idx >= 0 ? idx + 1 : void 0;
317
+ }
318
+ async function resolveInjectedEnv(options = {}) {
319
+ const config = await loadEnvLaneConfig(options);
320
+ const target = await resolveTargetPackage(options.target, { ...options, config });
321
+ const build = resolveBuildName(options, config.selector.envKey, config.selector.defaultBuild);
322
+ const files = listEnvFilesForTarget(config, target, options);
323
+ const values = {};
324
+ const sources = {};
325
+ const missingRequired = files.filter((file) => file.required && !file.exists);
326
+ if (missingRequired.length)
327
+ throw new Error(
328
+ `Missing required env file(s): ${missingRequired.map((file) => file.relativePath).join(", ")}`
329
+ );
330
+ for (const file of files) {
331
+ if (!file.exists) continue;
332
+ const content = (0, import_node_fs3.readFileSync)(file.path, "utf8");
333
+ const parsed = (0, import_dotenv.parse)(content);
334
+ if (config.selector.forbidInDotenv && Object.prototype.hasOwnProperty.call(parsed, config.selector.envKey)) {
335
+ throw new Error(
336
+ `${config.selector.envKey} is a selector and must not be stored in dotenv files (${file.relativePath}).`
337
+ );
338
+ }
339
+ for (const [key, value] of Object.entries(parsed)) {
340
+ values[key] = value;
341
+ sources[key] = {
342
+ source: "dotenv",
343
+ file: file.path,
344
+ relativeFile: file.relativePath,
345
+ line: lineForKey(content, key)
346
+ };
347
+ }
348
+ }
349
+ if (options.includeProcessEnv ?? config.dotenv.includeProcessEnv) {
350
+ for (const [key, value] of Object.entries(process.env)) {
351
+ if (value === void 0) continue;
352
+ if (Object.prototype.hasOwnProperty.call(values, key)) {
353
+ sources[key] = { source: "process", shellOverride: true };
354
+ } else {
355
+ sources[key] = { source: "process" };
356
+ }
357
+ values[key] = value;
358
+ }
359
+ }
360
+ values[config.selector.envKey] = build;
361
+ sources[config.selector.envKey] = {
362
+ source: "selector",
363
+ shellOverride: Object.prototype.hasOwnProperty.call(process.env, config.selector.envKey)
364
+ };
365
+ return {
366
+ rootDir: config.rootDir,
367
+ target,
368
+ build,
369
+ selectorKey: config.selector.envKey,
370
+ files,
371
+ values,
372
+ sources
373
+ };
374
+ }
375
+
376
+ // src/check.ts
377
+ function lineForKey2(content, key) {
378
+ const lines = content.split(/\r?\n/);
379
+ const re = new RegExp(`^\\s*(?:export\\s+)?${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*=`);
380
+ const idx = lines.findIndex((line) => re.test(line));
381
+ return idx >= 0 ? idx + 1 : void 0;
382
+ }
383
+ async function checkDotenvSelector(options = {}) {
384
+ const config = await loadEnvLaneConfig(options);
385
+ const target = options.target && options.target !== "all" ? await resolveTargetPackage(options.target, { ...options, config }) : void 0;
386
+ const scanDir = target?.dir ?? config.rootDir;
387
+ const files = await (0, import_fast_glob2.default)(["**/.env", "**/.env.*", "**/*.env", "**/*.env.*"], {
388
+ cwd: scanDir,
389
+ absolute: true,
390
+ onlyFiles: true,
391
+ ignore: [
392
+ "**/node_modules/**",
393
+ "**/dist/**",
394
+ "**/coverage/**",
395
+ "**/tmp/**",
396
+ "**/.git/**",
397
+ "**/.turbo/**"
398
+ ]
399
+ });
400
+ const violations = [];
401
+ for (const file of files) {
402
+ if (!(0, import_node_fs4.existsSync)(file)) continue;
403
+ const content = (0, import_node_fs4.readFileSync)(file, "utf8");
404
+ const parsed = (0, import_dotenv2.parse)(content);
405
+ if (Object.prototype.hasOwnProperty.call(parsed, config.selector.envKey)) {
406
+ violations.push({
407
+ file,
408
+ relativeFile: import_node_path4.default.relative(config.rootDir, file).replaceAll(import_node_path4.default.sep, "/"),
409
+ line: lineForKey2(content, config.selector.envKey)
410
+ });
411
+ }
412
+ }
413
+ const missingRequired = [];
414
+ if (options.requireOverride ?? config.dotenv.requireOverride) {
415
+ const targets = options.target && options.target !== "all" ? [target ?? await resolveTargetPackage(options.target, { ...options, config })] : await listWorkspacePackagesForConfig(config);
416
+ for (const pkg of targets) {
417
+ const envFiles = listEnvFilesForTarget(config, pkg, {
418
+ target: pkg.relativeDir,
419
+ build: options.build,
420
+ requireOverride: true
421
+ });
422
+ for (const file of envFiles.filter((item) => item.required && !item.exists)) {
423
+ missingRequired.push({
424
+ file: file.path,
425
+ relativeFile: file.relativePath,
426
+ target: pkg.name ?? pkg.relativeDir
427
+ });
428
+ }
429
+ }
430
+ }
431
+ return {
432
+ ok: violations.length === 0 && missingRequired.length === 0,
433
+ selectorKey: config.selector.envKey,
434
+ violations,
435
+ missingRequired
436
+ };
437
+ }
438
+
439
+ // src/logger.ts
440
+ var currentLogger = {
441
+ log: (...args) => console.log(...args),
442
+ info: (...args) => console.info(...args),
443
+ warn: (...args) => console.warn(...args),
444
+ error: (...args) => console.error(...args),
445
+ success: (...args) => console.log(...args),
446
+ debug: (...args) => console.debug(...args),
447
+ write: (msg) => process.stdout.write(msg)
448
+ };
449
+ function setLogger(logger) {
450
+ currentLogger = logger;
451
+ }
452
+ function getLogger() {
453
+ return currentLogger;
454
+ }
455
+
456
+ // src/redaction.ts
457
+ var SECRET_KEY_RE = /(SECRET|PRIVATE|PASSWORD|PASS|TOKEN|API_KEY|ACCESS_KEY|CREDENTIAL|DATABASE_URL|DB_URL|REDIS_URL|REDIS_URI|RPC_URL|(^|_)KEY($|_))/i;
458
+ function isSecretLikeKey(key) {
459
+ return SECRET_KEY_RE.test(key);
460
+ }
461
+ function redactValue(key, value, showSecrets = false) {
462
+ if (showSecrets) return value;
463
+ return isSecretLikeKey(key) ? value ? "<redacted>" : "" : value;
464
+ }
465
+ function redactRecord(values, showSecrets = false) {
466
+ return Object.fromEntries(
467
+ Object.entries(values).map(([key, value]) => [key, redactValue(key, value, showSecrets)])
468
+ );
469
+ }
470
+
471
+ // src/run.ts
472
+ var import_execa = require("execa");
473
+ async function runWithInjectedEnv(options) {
474
+ if (!options.command.length) throw new Error("Missing command.");
475
+ const resolved = await resolveInjectedEnv(options);
476
+ const cwd = options.runCwd === "root" ? resolved.rootDir : !options.runCwd || options.runCwd === "target" ? resolved.target.dir : options.runCwd;
477
+ if (!options.quiet) {
478
+ const loaded = resolved.files.filter((file) => file.exists).map((file) => file.relativePath).join(", ") || "<none>";
479
+ const missing = resolved.files.filter((file) => !file.exists).map((file) => file.relativePath).join(", ");
480
+ const logger = getLogger();
481
+ logger.info(
482
+ `[env-lane] target=${resolved.target.name ?? resolved.target.relativeDir} build=${resolved.build}`
483
+ );
484
+ logger.info(`[env-lane] loaded=${loaded}`);
485
+ if (missing) logger.info(`[env-lane] missing=${missing}`);
486
+ }
487
+ const subprocess = (0, import_execa.execa)(options.command[0], options.command.slice(1), {
488
+ cwd,
489
+ env: resolved.values,
490
+ stdio: "inherit",
491
+ reject: false,
492
+ shell: process.platform === "win32"
493
+ });
494
+ const result = await subprocess;
495
+ return result.exitCode ?? 1;
496
+ }
497
+
498
+ // src/sort.ts
499
+ var import_node_fs5 = require("fs");
500
+ var import_node_path5 = __toESM(require("path"), 1);
501
+ var ENV_ENTRY_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
502
+ var COMMENTED_ENV_ENTRY_RE = /^\s*#\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
503
+ function portable(file) {
504
+ return file.replace(/\\/g, "/").replaceAll(import_node_path5.default.sep, "/");
505
+ }
506
+ async function loadSortConfig(configPath) {
507
+ const abs = import_node_path5.default.resolve(configPath);
508
+ if (!(0, import_node_fs5.existsSync)(abs)) throw new Error(`Sort config does not exist: ${abs}`);
509
+ const config = await loadEnvLaneConfig({ cwd: import_node_path5.default.dirname(abs), configFile: abs });
510
+ const packages = await listWorkspacePackagesForConfig(config);
511
+ const sort = { ...config.sort };
512
+ const handledAliases = /* @__PURE__ */ new Set();
513
+ for (const pkg of packages) {
514
+ for (const alias of pkg.aliases) {
515
+ handledAliases.add(alias);
516
+ const target = sort[alias] ?? {};
517
+ sort[alias] = {
518
+ ...target,
519
+ baseDir: target.baseDir ?? pkg.dir,
520
+ file: target.file ?? ".env",
521
+ template: target.template ?? ".env.example"
522
+ };
523
+ }
524
+ }
525
+ for (const [key, target] of Object.entries(sort)) {
526
+ if (handledAliases.has(key)) continue;
527
+ sort[key] = {
528
+ ...target,
529
+ baseDir: target.baseDir ?? config.rootDir,
530
+ file: target.file ?? ".env",
531
+ template: target.template ?? ".env.example"
532
+ };
533
+ }
534
+ return {
535
+ baseDir: config.rootDir,
536
+ envFiles: [],
537
+ sort,
538
+ dotenv: config.dotenv,
539
+ selector: config.selector,
540
+ packages
541
+ };
542
+ }
543
+ function emitCommandChange(command, payload) {
544
+ getLogger().info(`[env-store-change] ${JSON.stringify({ command, ...payload })}`);
545
+ }
546
+ function createEmptyDocument() {
547
+ return { hasBom: false, eol: "\n", hasFinalNewline: true, lines: [] };
548
+ }
549
+ function createTextDocument(content) {
550
+ const hasBom = content.startsWith("\uFEFF");
551
+ const raw = hasBom ? content.slice(1) : content;
552
+ const eol = raw.includes("\r\n") ? "\r\n" : "\n";
553
+ const hasFinalNewline = raw.length > 0 && /\r?\n$/.test(raw);
554
+ let lines = raw.length > 0 ? raw.split(/\r\n|\n/) : [];
555
+ if (hasFinalNewline && lines.at(-1) === "") lines = lines.slice(0, -1);
556
+ return { hasBom, eol, hasFinalNewline, lines };
557
+ }
558
+ function renderTextDocument(document, lines) {
559
+ const body = lines.join(document.eol);
560
+ const withNewline = lines.length > 0 && document.hasFinalNewline ? `${body}${document.eol}` : body;
561
+ return document.hasBom ? `\uFEFF${withNewline}` : withNewline;
562
+ }
563
+ function parseEnvLine(line) {
564
+ const trimmed = line.trim();
565
+ if (!trimmed) return { kind: "empty", rawLine: line };
566
+ if (trimmed.startsWith("#")) {
567
+ const commentedEntryMatch = line.match(COMMENTED_ENV_ENTRY_RE);
568
+ if (commentedEntryMatch) {
569
+ const eqIdx2 = line.indexOf("=");
570
+ return {
571
+ kind: "commented-entry",
572
+ rawLine: line,
573
+ key: commentedEntryMatch[1],
574
+ prefix: line.slice(0, eqIdx2 + 1),
575
+ rawValue: line.slice(eqIdx2 + 1)
576
+ };
577
+ }
578
+ return { kind: "comment", rawLine: line };
579
+ }
580
+ const eqIdx = line.indexOf("=");
581
+ if (eqIdx < 0) return { kind: "invalid", rawLine: line, reason: "missing equals sign" };
582
+ const match = line.match(ENV_ENTRY_RE);
583
+ if (!match) return { kind: "invalid", rawLine: line, reason: "invalid env key" };
584
+ return {
585
+ kind: "entry",
586
+ rawLine: line,
587
+ key: match[1],
588
+ prefix: line.slice(0, eqIdx + 1),
589
+ rawValue: line.slice(eqIdx + 1)
590
+ };
591
+ }
592
+ function loadEnvDocument(filePath) {
593
+ const fileExists = (0, import_node_fs5.existsSync)(filePath);
594
+ const document = fileExists ? createTextDocument((0, import_node_fs5.readFileSync)(filePath, "utf8")) : createEmptyDocument();
595
+ const parsedLines = document.lines.map((line, index) => ({
596
+ lineNumber: index + 1,
597
+ ...parseEnvLine(line)
598
+ }));
599
+ return { exists: fileExists, document, parsedLines };
600
+ }
601
+ function isEnvEntryLikeLine(line) {
602
+ return line.kind === "entry" || line.kind === "commented-entry";
603
+ }
604
+ function buildEnvSortLayout(envDoc) {
605
+ const blocks = [];
606
+ let preambleLines = [];
607
+ let pendingLines = [];
608
+ let sawEntry = false;
609
+ for (const line of envDoc.parsedLines) {
610
+ if (isEnvEntryLikeLine(line)) {
611
+ if (!sawEntry) {
612
+ preambleLines = pendingLines;
613
+ pendingLines = [];
614
+ sawEntry = true;
615
+ }
616
+ blocks.push({
617
+ key: line.key,
618
+ kind: line.kind,
619
+ rawLine: line.rawLine,
620
+ rawValue: line.rawValue,
621
+ leadingLines: pendingLines,
622
+ lineNumber: line.lineNumber,
623
+ order: blocks.length
624
+ });
625
+ pendingLines = [];
626
+ continue;
627
+ }
628
+ pendingLines.push(line.rawLine);
629
+ }
630
+ if (!sawEntry) {
631
+ preambleLines = pendingLines;
632
+ pendingLines = [];
633
+ }
634
+ return { preambleLines, blocks, suffixLines: pendingLines };
635
+ }
636
+ function hasCommentedEnvValue(block) {
637
+ const trimmed = block.rawValue.trim();
638
+ return trimmed !== "" && !trimmed.startsWith("#");
639
+ }
640
+ function shouldIgnoreEmptyCommentedEnvBlock(block, groupBlocks) {
641
+ if (block.kind !== "commented-entry" || hasCommentedEnvValue(block)) return false;
642
+ return groupBlocks.some(
643
+ (candidate) => candidate !== block && (candidate.kind === "entry" || hasCommentedEnvValue(candidate))
644
+ );
645
+ }
646
+ function isBlankLine(line) {
647
+ return line.trim() === "";
648
+ }
649
+ function normalizeBlankLineRuns(lines) {
650
+ const normalizedLines = [];
651
+ for (const line of lines) {
652
+ if (isBlankLine(line) && normalizedLines.length > 0 && isBlankLine(normalizedLines.at(-1) ?? ""))
653
+ continue;
654
+ normalizedLines.push(line);
655
+ }
656
+ return normalizedLines;
657
+ }
658
+ function buildEnvSortGroups(blocks) {
659
+ const groupedBlocks = /* @__PURE__ */ new Map();
660
+ for (const block of blocks) {
661
+ const groupBlocks = groupedBlocks.get(block.key) ?? [];
662
+ groupBlocks.push(block);
663
+ groupedBlocks.set(block.key, groupBlocks);
664
+ }
665
+ const groups = [];
666
+ for (const [key, groupBlocks] of groupedBlocks) {
667
+ const keptBlocks = groupBlocks.filter(
668
+ (block) => !shouldIgnoreEmptyCommentedEnvBlock(block, groupBlocks)
669
+ );
670
+ if (keptBlocks.length === 0) continue;
671
+ groups.push({
672
+ key,
673
+ order: Math.min(...keptBlocks.map((block) => block.order)),
674
+ blocks: keptBlocks,
675
+ leadingLines: normalizeBlankLineRuns(groupBlocks.flatMap((block) => block.leadingLines)),
676
+ rawLines: keptBlocks.map((block) => block.rawLine)
677
+ });
678
+ }
679
+ groups.sort((left, right) => left.order - right.order);
680
+ return groups;
681
+ }
682
+ function buildCommentLineSet(lines) {
683
+ const normalizedComments = /* @__PURE__ */ new Set();
684
+ for (const line of lines) {
685
+ const parsed = parseEnvLine(line);
686
+ if (parsed.kind === "comment") normalizedComments.add(line.trim());
687
+ }
688
+ return normalizedComments;
689
+ }
690
+ function partitionPreambleLines(templateLines, envLines) {
691
+ const normalizedTemplateLines = normalizeBlankLineRuns(templateLines);
692
+ const normalizedEnvLines = normalizeBlankLineRuns(envLines);
693
+ if (normalizedEnvLines.length === 0) return { matchedTemplateLines: [], extraLines: [] };
694
+ if (normalizedTemplateLines.length === 0) {
695
+ return {
696
+ matchedTemplateLines: [],
697
+ extraLines: normalizedEnvLines.filter((line) => !isBlankLine(line))
698
+ };
699
+ }
700
+ const templateComments = buildCommentLineSet(normalizedTemplateLines);
701
+ const matchedTemplateLines = [];
702
+ const extraLines = [];
703
+ for (const line of normalizedEnvLines) {
704
+ const parsed = parseEnvLine(line);
705
+ if (parsed.kind === "comment" && templateComments.has(line.trim())) {
706
+ matchedTemplateLines.push(line);
707
+ continue;
708
+ }
709
+ if (parsed.kind === "empty") continue;
710
+ extraLines.push(line);
711
+ }
712
+ return {
713
+ matchedTemplateLines: normalizeBlankLineRuns(matchedTemplateLines),
714
+ extraLines: normalizeBlankLineRuns(extraLines)
715
+ };
716
+ }
717
+ function mergeLeadingLines(templateLines, envLines) {
718
+ const normalizedTemplateLines = normalizeBlankLineRuns(templateLines);
719
+ if (normalizedTemplateLines.length === 0) return normalizeBlankLineRuns(envLines);
720
+ const templateComments = buildCommentLineSet(normalizedTemplateLines);
721
+ const unmatchedEnvLines = normalizeBlankLineRuns(
722
+ envLines.filter((line) => {
723
+ const parsed = parseEnvLine(line);
724
+ if (parsed.kind === "empty") return false;
725
+ return parsed.kind !== "comment" || !templateComments.has(line.trim());
726
+ })
727
+ );
728
+ if (unmatchedEnvLines.length === 0) return normalizedTemplateLines;
729
+ const mergedLines = [...normalizedTemplateLines];
730
+ if (!isBlankLine(mergedLines.at(-1) ?? "") && !isBlankLine(unmatchedEnvLines[0]))
731
+ mergedLines.push("");
732
+ mergedLines.push(...unmatchedEnvLines);
733
+ return normalizeBlankLineRuns(mergedLines);
734
+ }
735
+ function commentOutEnvEntryLine(line) {
736
+ const parsed = parseEnvLine(line);
737
+ if (parsed.kind === "commented-entry") return parsed.rawLine;
738
+ if (parsed.kind !== "entry") return `# ${line.trimStart()}`;
739
+ const indent = line.match(/^\s*/)?.[0] ?? "";
740
+ return `${indent}# ${line.slice(indent.length)}`;
741
+ }
742
+ function buildEnvSortPlan(envFilePath, templateFilePath) {
743
+ const resolvedEnvFilePath = import_node_path5.default.resolve(envFilePath);
744
+ const resolvedTemplateFilePath = import_node_path5.default.resolve(templateFilePath);
745
+ if (!(0, import_node_fs5.existsSync)(resolvedTemplateFilePath)) {
746
+ throw new Error(`Template env file does not exist: ${resolvedTemplateFilePath}`);
747
+ }
748
+ const envDoc = loadEnvDocument(resolvedEnvFilePath);
749
+ const templateDoc = loadEnvDocument(resolvedTemplateFilePath);
750
+ const envLayout = buildEnvSortLayout(envDoc);
751
+ const templateLayout = buildEnvSortLayout(templateDoc);
752
+ if (envLayout.blocks.length > 0) {
753
+ const { matchedTemplateLines, extraLines } = partitionPreambleLines(
754
+ templateLayout.preambleLines,
755
+ envLayout.preambleLines
756
+ );
757
+ envLayout.preambleLines = matchedTemplateLines;
758
+ if (extraLines.length > 0) {
759
+ envLayout.blocks[0] = {
760
+ ...envLayout.blocks[0],
761
+ leadingLines: normalizeBlankLineRuns([...extraLines, ...envLayout.blocks[0].leadingLines])
762
+ };
763
+ }
764
+ }
765
+ const envGroups = new Map(buildEnvSortGroups(envLayout.blocks).map((group) => [group.key, group]));
766
+ const templateKeys = new Set(templateLayout.blocks.map((block) => block.key));
767
+ const templateBlocksByKey = [];
768
+ const seenTemplateKeys = /* @__PURE__ */ new Set();
769
+ for (const block of templateLayout.blocks) {
770
+ if (seenTemplateKeys.has(block.key)) continue;
771
+ seenTemplateKeys.add(block.key);
772
+ templateBlocksByKey.push(block);
773
+ }
774
+ const renderedLines = mergeLeadingLines(templateLayout.preambleLines, envLayout.preambleLines);
775
+ const consumedKeys = /* @__PURE__ */ new Set();
776
+ const operations = [];
777
+ let renderedOrder = 0;
778
+ for (const templateBlock of templateBlocksByKey) {
779
+ const envGroup = envGroups.get(templateBlock.key);
780
+ if (envGroup) {
781
+ consumedKeys.add(envGroup.key);
782
+ renderedLines.push(
783
+ ...mergeLeadingLines(templateBlock.leadingLines, envGroup.leadingLines),
784
+ ...envGroup.rawLines
785
+ );
786
+ if (envGroup.order !== renderedOrder) operations.push({ action: "move", key: envGroup.key });
787
+ if (envGroup.blocks.length > 1)
788
+ operations.push({ action: "group-duplicate", key: envGroup.key });
789
+ renderedOrder++;
790
+ continue;
791
+ }
792
+ renderedLines.push(...templateBlock.leadingLines, commentOutEnvEntryLine(templateBlock.rawLine));
793
+ operations.push({ action: "insert-commented", key: templateBlock.key });
794
+ renderedOrder++;
795
+ }
796
+ const leftoverGroups = [...envGroups.values()].filter((group) => !consumedKeys.has(group.key));
797
+ for (const group of leftoverGroups) {
798
+ renderedLines.push(...group.leadingLines, ...group.rawLines);
799
+ operations.push({
800
+ action: templateKeys.has(group.key) ? "append-duplicate" : "append-extra",
801
+ key: group.key
802
+ });
803
+ renderedOrder++;
804
+ }
805
+ renderedLines.push(...mergeLeadingLines(templateLayout.suffixLines, envLayout.suffixLines));
806
+ const renderDocument = envDoc.exists ? envDoc.document : templateDoc.document;
807
+ const currentContent = envDoc.exists ? renderTextDocument(envDoc.document, envDoc.document.lines) : "";
808
+ const nextContent = renderTextDocument(renderDocument, renderedLines);
809
+ const summary = operations.reduce(
810
+ (acc, operation) => {
811
+ if (operation.action === "move") acc.movedCount++;
812
+ else if (operation.action === "insert-commented") acc.insertedCommentedCount++;
813
+ else if (operation.action === "append-extra") acc.appendedExtraCount++;
814
+ else if (operation.action === "append-duplicate") acc.appendedDuplicateCount++;
815
+ else if (operation.action === "group-duplicate") acc.groupedDuplicateCount++;
816
+ return acc;
817
+ },
818
+ {
819
+ movedCount: 0,
820
+ insertedCommentedCount: 0,
821
+ appendedExtraCount: 0,
822
+ appendedDuplicateCount: 0,
823
+ groupedDuplicateCount: 0
824
+ }
825
+ );
826
+ return {
827
+ filePath: resolvedEnvFilePath,
828
+ templateFilePath: resolvedTemplateFilePath,
829
+ changed: currentContent !== nextContent,
830
+ currentContent,
831
+ nextContent,
832
+ operations,
833
+ summary
834
+ };
835
+ }
836
+ async function sortEnvFile(envFilePath, templateFilePath) {
837
+ const plan = buildEnvSortPlan(envFilePath, templateFilePath);
838
+ if (!plan.changed) {
839
+ return {
840
+ applied: false,
841
+ filePath: plan.filePath,
842
+ templateFilePath: plan.templateFilePath,
843
+ ...plan.summary
844
+ };
845
+ }
846
+ (0, import_node_fs5.mkdirSync)(import_node_path5.default.dirname(plan.filePath), { recursive: true });
847
+ (0, import_node_fs5.writeFileSync)(plan.filePath, plan.nextContent, "utf8");
848
+ for (const operation of plan.operations) {
849
+ emitCommandChange("sort", {
850
+ action: operation.action,
851
+ filePath: portable(plan.filePath),
852
+ templateFilePath: portable(plan.templateFilePath),
853
+ key: operation.key
854
+ });
855
+ }
856
+ emitCommandChange("sort", {
857
+ action: "write-file",
858
+ filePath: portable(plan.filePath),
859
+ templateFilePath: portable(plan.templateFilePath)
860
+ });
861
+ return {
862
+ applied: true,
863
+ filePath: plan.filePath,
864
+ templateFilePath: plan.templateFilePath,
865
+ ...plan.summary
866
+ };
867
+ }
868
+ function normalizeSortSelector(value, fallback, fieldName) {
869
+ const normalized = value === void 0 || value === null || value === "" ? fallback : String(value).trim();
870
+ if (!normalized) return fallback;
871
+ if (fieldName === "env-suffix" && normalized === "default") return "";
872
+ return normalized;
873
+ }
874
+ function interpolateSortFilePattern(pattern, envSuffix) {
875
+ return pattern.replaceAll("{env}", envSuffix).replaceAll("{suffix}", envSuffix);
876
+ }
877
+ async function sortEnvFilesFromConfig(configPath, keyArg = "all", envSuffixArg = "all") {
878
+ const config = await loadSortConfig(configPath);
879
+ const keySelector = normalizeSortSelector(keyArg, "all", "key");
880
+ const envSuffixSelector = normalizeSortSelector(envSuffixArg, "all", "env-suffix");
881
+ const selectedTargets = Object.entries(config.sort).filter(
882
+ ([key]) => keySelector === "all" || key === keySelector
883
+ );
884
+ if (selectedTargets.length === 0) throw new Error(`Unknown sort key: ${keySelector}`);
885
+ const results = [];
886
+ for (const [key, target] of selectedTargets) {
887
+ const baseDir = target.baseDir ?? config.baseDir;
888
+ const file = target.file ?? ".env";
889
+ const template = target.template ?? ".env.example";
890
+ const defaultFilePath = import_node_path5.default.resolve(baseDir, file);
891
+ const templateFilePath = import_node_path5.default.resolve(baseDir, template);
892
+ const targetDir = import_node_path5.default.dirname(defaultFilePath);
893
+ const files = /* @__PURE__ */ new Map([["", defaultFilePath]]);
894
+ for (const pattern of config.dotenv.order) {
895
+ if (pattern.includes("{build}")) {
896
+ for (const build of config.selector.builds) {
897
+ files.set(build, import_node_path5.default.resolve(targetDir, pattern.replace("{build}", build)));
898
+ }
899
+ }
900
+ }
901
+ if (target.files) {
902
+ for (const [suffix, file2] of Object.entries(target.files)) {
903
+ if (suffix === "default")
904
+ throw new Error(`config.sort.${key}.files must not use reserved suffix "default".`);
905
+ files.set(suffix, import_node_path5.default.resolve(baseDir, interpolateSortFilePattern(file2, suffix)));
906
+ }
907
+ }
908
+ const jobs = envSuffixSelector === "all" ? [...files.entries()] : [
909
+ [
910
+ envSuffixSelector,
911
+ files.get(envSuffixSelector) ?? import_node_path5.default.resolve(targetDir, `${import_node_path5.default.basename(defaultFilePath)}.${envSuffixSelector}`)
912
+ ]
913
+ ];
914
+ for (const [, file2] of jobs) results.push(await sortEnvFile(file2, templateFilePath));
915
+ }
916
+ return { applied: results.some((result) => result.applied), count: results.length, results };
917
+ }
918
+ // Annotate the CommonJS export names for ESM import in node:
919
+ 0 && (module.exports = {
920
+ buildEnvSortPlan,
921
+ checkDotenvSelector,
922
+ defineConfig,
923
+ findWorkspaceRoot,
924
+ getLogger,
925
+ isSecretLikeKey,
926
+ listEnvFiles,
927
+ listEnvFilesForTarget,
928
+ listWorkspacePackages,
929
+ listWorkspacePackagesForConfig,
930
+ loadEnvLaneConfig,
931
+ readPnpmWorkspaceGlobs,
932
+ redactRecord,
933
+ redactValue,
934
+ resolveBuildName,
935
+ resolveInjectedEnv,
936
+ resolveTargetPackage,
937
+ resolveTargetPackageFromList,
938
+ runWithInjectedEnv,
939
+ setLogger,
940
+ sortEnvFile,
941
+ sortEnvFilesFromConfig
942
+ });