@solid-stack/builder 1.1.6 → 1.1.7

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/README.md CHANGED
@@ -96,6 +96,28 @@ builder service up test-e2e
96
96
 
97
97
  ---
98
98
 
99
+ ### Export the application environment (`builder service export env [stage]`)
100
+
101
+ ```bash
102
+ # Export all four stages into the service directory
103
+ builder service export env
104
+
105
+ # Export one stage only
106
+ builder service export env dev
107
+ builder service export env prod
108
+ builder service export env test
109
+ builder service export env e2e -C ./services/backend
110
+
111
+ # Match full/integrated development mode
112
+ builder service export env dev --full
113
+ ```
114
+
115
+ The default output names are `env.dev`, `env.prod`, `env.test`, and `env.e2e` (without a leading dot). These snapshots do not replace the `.env.<stage>` input files automatically. If an output file exists, Builder asks whether to overwrite it. Declining prompts for a new filename relative to the service directory; an existing replacement filename also requires confirmation. Existing files require an interactive terminal.
116
+
117
+ Exports use the same stage compilation as service startup, including Compose environment files, overrides, Builder URL templates, and `build.json.envOverrides`. All requested stages are compiled before any files are written. Only the application service's resolved runtime environment is exported, not build arguments, dependencies, or tester settings. E2E runs the application using the production configuration, so `env.e2e` reflects that app environment plus any E2E app overrides; it does not merge the tester's `.env.e2e` into the app.
118
+
119
+ The command requires Docker Compose 2.24 or newer, but does not require a running Docker daemon or start/build containers. Image-only `ENV` defaults and values added by application startup code cannot be determined by configuration simulation and are outside the export. New files use owner-only permissions and contain the actual values. Values follow [Compose dotenv quoting rules](https://docs.docker.com/compose/how-tos/environment-variables/variable-interpolation/) to preserve literal dollars and multiline strings.
120
+
99
121
  ## 🛠️ Options
100
122
 
101
123
  | Flag | Description |
package/dist/bin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { Command } from 'commander';
2
+ import { Command, Argument } from 'commander';
3
3
  import pc22 from 'picocolors';
4
- import fs, { existsSync, readFileSync, unlinkSync, mkdirSync, writeFileSync, statSync } from 'fs';
4
+ import fs, { existsSync, readFileSync, mkdirSync, writeFileSync, unlinkSync, statSync } from 'fs';
5
5
  import path13 from 'path';
6
6
  import { spawnSync, spawn } from 'child_process';
7
7
  import { parseAllDocuments, parse, stringify } from 'yaml';
@@ -10,6 +10,7 @@ import 'crypto';
10
10
  import os from 'os';
11
11
  import net from 'net';
12
12
  import { fileURLToPath } from 'url';
13
+ import { createInterface } from 'readline/promises';
13
14
  import { createRequire } from 'module';
14
15
 
15
16
  // src/errors/ScriptError.ts
@@ -380,7 +381,7 @@ function checkInfra(projectDir = process.cwd()) {
380
381
  checkComposeContract(buildJson, absProjectDir);
381
382
  console.log(pc22.green("\n\u2705 All infrastructure and contract checks passed.\n"));
382
383
  }
383
- function checkDependencies() {
384
+ function checkComposeAvailability() {
384
385
  const composeCheck = spawnSync(
385
386
  "docker",
386
387
  ["compose", "version", "--short"],
@@ -403,6 +404,9 @@ function checkDependencies() {
403
404
  `Error: Docker Compose version >= 2.24.0 is required (found ${rawVersion}). Please upgrade Docker Compose to support optional env_file syntax.`
404
405
  );
405
406
  }
407
+ }
408
+ function checkDependencies() {
409
+ checkComposeAvailability();
406
410
  const daemonCheck = spawnSync("docker", ["info"], {
407
411
  stdio: "pipe",
408
412
  encoding: "utf-8"
@@ -3628,11 +3632,127 @@ Examples:
3628
3632
  }
3629
3633
  );
3630
3634
  };
3635
+ function compileApplicationEnv(stage, projectDir, options = {}) {
3636
+ const dir = resolveProjectDir(projectDir);
3637
+ const yaml = compileEnvironment(stage, dir, options);
3638
+ const result = spawnSync("docker", [
3639
+ "compose",
3640
+ "--project-directory",
3641
+ dir,
3642
+ "-f",
3643
+ "-",
3644
+ "config",
3645
+ "--format",
3646
+ "json"
3647
+ ], { cwd: dir, encoding: "utf-8", input: yaml });
3648
+ if (result.error || result.status !== 0) {
3649
+ throw new ScriptError(`Failed to resolve ${stage} application environment: ${result.error?.message || result.stderr || result.stdout}`);
3650
+ }
3651
+ const config = JSON.parse(result.stdout);
3652
+ if (!config.services?.app) {
3653
+ throw new ScriptError(`The ${stage} configuration has no application service ('app').`);
3654
+ }
3655
+ const environment = {};
3656
+ for (const [key, value] of Object.entries(config.services.app.environment ?? {})) {
3657
+ if (value !== null && value !== void 0) {
3658
+ environment[key] = String(value).replace(/\$\$/g, "$");
3659
+ }
3660
+ }
3661
+ return environment;
3662
+ }
3663
+ function serializeApplicationEnv(environment) {
3664
+ return Object.keys(environment).sort().map((key) => {
3665
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
3666
+ throw new ScriptError(`Cannot export invalid environment variable name: ${key}`);
3667
+ }
3668
+ const value = environment[key];
3669
+ if (value.includes("\0")) throw new ScriptError(`Cannot export a NUL character in ${key}.`);
3670
+ const quoted = /'|\\$|\r/.test(value) ? `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/\$/g, () => "$$")}"` : `'${value}'`;
3671
+ return `${key}=${quoted}`;
3672
+ }).join("\n") + "\n";
3673
+ }
3674
+
3675
+ // src/commands/service/commands/export/handler.ts
3676
+ var STAGES = ["dev", "prod", "test", "e2e"];
3677
+ async function handleExportEnv(rawStage, options = {}) {
3678
+ const stage = rawStage?.toLowerCase();
3679
+ if (stage !== void 0 && !STAGES.includes(stage)) {
3680
+ throw new ScriptError(`Unknown environment stage: "${rawStage}". Supported stages: ${STAGES.join(", ")}`);
3681
+ }
3682
+ const projectDir = resolveProjectDir(options.projectDir);
3683
+ const stages = stage === void 0 ? STAGES : [stage];
3684
+ const snapshots = stages.map((stage2) => ({
3685
+ stage: stage2,
3686
+ content: serializeApplicationEnv(compileApplicationEnv(stage2, projectDir, options))
3687
+ }));
3688
+ let reader;
3689
+ const ask = async (question) => {
3690
+ if (options.prompt) return options.prompt(question);
3691
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
3692
+ throw new ScriptError("An existing export needs confirmation. Run this command in an interactive terminal to overwrite it or choose another filename.");
3693
+ }
3694
+ reader ??= createInterface({ input: process.stdin, output: process.stdout });
3695
+ return reader.question(question);
3696
+ };
3697
+ const files = [];
3698
+ try {
3699
+ for (const snapshot of snapshots) {
3700
+ let filename = path13.join(projectDir, `env.${snapshot.stage}`);
3701
+ while (true) {
3702
+ let overwrite = false;
3703
+ if (existsSync(filename)) {
3704
+ const answer = (await ask(`${filename} already exists. Overwrite? [y/N] `)).trim().toLowerCase();
3705
+ overwrite = answer === "y" || answer === "yes";
3706
+ if (!overwrite) {
3707
+ const name = (await ask(`New filename for ${snapshot.stage} (relative to the service directory): `)).trim();
3708
+ if (!name) continue;
3709
+ filename = path13.resolve(projectDir, name);
3710
+ continue;
3711
+ }
3712
+ }
3713
+ mkdirSync(path13.dirname(filename), { recursive: true });
3714
+ try {
3715
+ writeFileSync(filename, snapshot.content, { encoding: "utf-8", flag: overwrite ? "w" : "wx", mode: 384 });
3716
+ } catch (error) {
3717
+ if (!overwrite && error.code === "EEXIST") continue;
3718
+ throw error;
3719
+ }
3720
+ files.push(filename);
3721
+ console.log(pc22.green(`Exported ${snapshot.stage} application environment to ${filename}`));
3722
+ break;
3723
+ }
3724
+ }
3725
+ } finally {
3726
+ reader?.close();
3727
+ }
3728
+ return files;
3729
+ }
3730
+
3731
+ // src/commands/service/commands/export/command.ts
3732
+ function registerExportCommand(service) {
3733
+ const command = service.command("export").description("Export service configuration");
3734
+ command.command("env").description("Export the application's resolved environment for one or all stages").addArgument(new Argument("[stage]", "Stage to export (defaults to all four)").choices(["dev", "prod", "test", "e2e"])).option("-C, --project-dir <dir>", "Service project directory (defaults to cwd)").option("--full", "Export dev with mock dependencies and integrated infra mode").option("--integrated", "Alias for --full").option("--silence-warnings", "Silence non-critical URL templating warnings").addHelpText("after", `
3735
+ Examples:
3736
+ $ builder service export env
3737
+ $ builder service export env dev
3738
+ $ builder service export env e2e -C ./services/backend
3739
+ $ builder service export env dev --full`).action(async (stage, options) => {
3740
+ await handleExportEnv(stage, {
3741
+ projectDir: options.projectDir,
3742
+ full: Boolean(options.full || options.integrated),
3743
+ silenceWarnings: options.silenceWarnings
3744
+ });
3745
+ });
3746
+ }
3631
3747
 
3632
3748
  // src/commands/service/command.ts
3633
3749
  var registerServiceCommand = (cmd) => {
3634
3750
  const service = cmd.command("service").description("Manage and run services");
3635
3751
  service.hook("preAction", async (_thisCommand, actionCommand) => {
3752
+ if (actionCommand.name() === "env" && actionCommand.parent?.name() === "export") {
3753
+ checkComposeAvailability();
3754
+ return;
3755
+ }
3636
3756
  checkDependencies();
3637
3757
  if (actionCommand.name() === "up") {
3638
3758
  const options = actionCommand.opts();
@@ -3648,6 +3768,7 @@ var registerServiceCommand = (cmd) => {
3648
3768
  });
3649
3769
  registerUpCommand(service);
3650
3770
  registerDownCommand(service);
3771
+ registerExportCommand(service);
3651
3772
  };
3652
3773
  var require2 = createRequire(import.meta.url);
3653
3774
  var pkg = require2("../package.json");