bdy 1.25.39-stage → 1.25.41-dev

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.
@@ -7,28 +7,23 @@ const utils_1 = require("../../../utils");
7
7
  const texts_1 = require("../../../texts");
8
8
  const input_1 = __importDefault(require("../../../input"));
9
9
  const output_1 = __importDefault(require("../../../output"));
10
- const cliError_1 = __importDefault(require("../../../cliError"));
11
- const distro_1 = require("../../../types/distro");
10
+ const scope_1 = require("../scope");
12
11
  const commandDistroRouteOpen = (0, utils_1.newCommand)('open', texts_1.DESC_COMMAND_RESOURCE_OPEN, {
13
12
  requiredScopes: [utils_1.REST_API_SCOPE.DISTRIBUTION_READ],
14
13
  examples: [{ description: 'Open a distribution route in Buddy', command: 'bdy distro route open my-distro 123' }],
15
14
  });
16
15
  commandDistroRouteOpen.option('-w, --workspace <domain>', texts_1.OPTION_REST_API_WORKSPACE);
17
16
  commandDistroRouteOpen.option('-p, --project <name>', texts_1.OPTION_REST_API_PROJECT);
18
- commandDistroRouteOpen.option('--scope <scope>', texts_1.OPT_COMMAND_SCOPE);
17
+ commandDistroRouteOpen.option('--environment <identifier>', texts_1.OPTION_DISTRO_ENVIRONMENT);
18
+ commandDistroRouteOpen.option('--scope <scope>', texts_1.OPT_COMMAND_SCOPE_ENVIRONMENT);
19
19
  commandDistroRouteOpen.option('--format <text|json>', texts_1.OPTION_FORMAT);
20
20
  commandDistroRouteOpen.argument('<identifier>', texts_1.OPT_COMMAND_DISTRO_IDENTIFIER);
21
21
  commandDistroRouteOpen.argument('<route-id>', texts_1.OPT_COMMAND_ROUTE_ID);
22
22
  commandDistroRouteOpen.action(async (identifier, routeId, options) => {
23
23
  const workspace = input_1.default.restApiWorkspace(options.workspace);
24
- const project = input_1.default.restApiProject(options.project, true);
25
- const scope = input_1.default.scope(project, options.scope);
26
- const scopedProject = scope === distro_1.SCOPE.PROJECT ? project : null;
27
24
  const client = input_1.default.restApiTokenClient();
28
- const data = await client.getDistributionByIdentifier(workspace, scopedProject, identifier);
29
- if (!data?.distribution_id)
30
- throw new cliError_1.default('not_found', texts_1.ERR_COMMAND_DISTRO_NOT_FOUND, texts_1.HINT_DISTRO_LIST);
31
- const route = await client.getRoute(workspace, scopedProject, data.distribution_id, routeId);
25
+ const ctx = await (0, scope_1.resolveDistroContext)(client, workspace, options, identifier);
26
+ const route = await client.getRoute(workspace, ctx.api, ctx.distributionId, routeId);
32
27
  await output_1.default.openUrl(route.html_url, options.format === 'json');
33
28
  });
34
29
  exports.default = commandDistroRouteOpen;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const utils_1 = require("../../../utils");
7
+ const texts_1 = require("../../../texts");
8
+ const input_1 = __importDefault(require("../../../input"));
9
+ const output_1 = __importDefault(require("../../../output"));
10
+ const scope_1 = require("../scope");
11
+ // --path repeats instead of taking a list: a variadic option would swallow the
12
+ // positional arguments that follow it
13
+ const collect = (value, previous = []) => [...previous, value];
14
+ const commandDistroRoutePurge = (0, utils_1.newCommand)('purge', texts_1.DESC_COMMAND_ROUTE_PURGE, {
15
+ requiredScopes: [utils_1.REST_API_SCOPE.DISTRIBUTION_WRITE],
16
+ examples: texts_1.EXAMPLE_ROUTE_PURGE,
17
+ });
18
+ commandDistroRoutePurge.option('-w, --workspace <domain>', texts_1.OPTION_REST_API_WORKSPACE);
19
+ commandDistroRoutePurge.option('-p, --project <name>', texts_1.OPTION_REST_API_PROJECT);
20
+ commandDistroRoutePurge.option('--environment <identifier>', texts_1.OPTION_DISTRO_ENVIRONMENT);
21
+ commandDistroRoutePurge.option('--scope <scope>', texts_1.OPT_COMMAND_SCOPE_ENVIRONMENT);
22
+ commandDistroRoutePurge.option('--all', texts_1.OPT_COMMAND_ROUTE_PURGE_ALL);
23
+ commandDistroRoutePurge.option('--path <path>', texts_1.OPT_COMMAND_ROUTE_PURGE_PATH, collect);
24
+ commandDistroRoutePurge.option('--format <text|json>', texts_1.OPTION_FORMAT);
25
+ commandDistroRoutePurge.argument('<identifier>', texts_1.OPT_COMMAND_DISTRO_IDENTIFIER);
26
+ commandDistroRoutePurge.argument('<route-id>', texts_1.OPT_COMMAND_ROUTE_ID);
27
+ commandDistroRoutePurge.action(async (identifier, routeId, options) => {
28
+ const paths = options.path || [];
29
+ // one or the other: --all already covers every path
30
+ if (!!options.all === paths.length > 0) {
31
+ output_1.default.exitError(texts_1.ERR_COMMAND_ROUTE_PURGE_WHAT);
32
+ }
33
+ const workspace = input_1.default.restApiWorkspace(options.workspace);
34
+ const client = input_1.default.restApiTokenClient();
35
+ const ctx = await (0, scope_1.resolveDistroContext)(client, workspace, options, identifier);
36
+ const body = { purge_all: !!options.all };
37
+ if (paths.length)
38
+ body.purge_paths = paths;
39
+ await client.purgeRouteCache(workspace, ctx.api, ctx.distributionId, routeId, body);
40
+ output_1.default.exitResult(options.format === 'json', { purged: routeId, ...body }, texts_1.TXT_COMMAND_ROUTE_PURGED);
41
+ });
42
+ exports.default = commandDistroRoutePurge;
@@ -3,20 +3,20 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- const cliError_1 = __importDefault(require("../../../cliError"));
7
6
  const utils_1 = require("../../../utils");
8
7
  const texts_1 = require("../../../texts");
9
8
  const input_1 = __importDefault(require("../../../input"));
10
9
  const output_1 = __importDefault(require("../../../output"));
11
- const distro_1 = require("../../../types/distro");
10
+ const scope_1 = require("../scope");
12
11
  const commandDistroRouteUpdate = (0, utils_1.newCommand)('update', texts_1.DESC_COMMAND_ROUTE_UPDATE, {
13
12
  requiredScopes: [utils_1.REST_API_SCOPE.DISTRIBUTION_WRITE],
14
13
  examples: texts_1.EXAMPLE_ROUTE_UPDATE,
15
14
  });
16
15
  commandDistroRouteUpdate.alias('edit');
17
16
  commandDistroRouteUpdate.option('-w, --workspace <domain>', texts_1.OPTION_REST_API_WORKSPACE);
18
- commandDistroRouteUpdate.option('--scope <scope>', texts_1.OPT_COMMAND_SCOPE);
17
+ commandDistroRouteUpdate.option('--scope <scope>', texts_1.OPT_COMMAND_SCOPE_ENVIRONMENT);
19
18
  commandDistroRouteUpdate.option('-p, --project <name>', texts_1.OPTION_REST_API_PROJECT);
19
+ commandDistroRouteUpdate.option('--environment <identifier>', texts_1.OPTION_DISTRO_ENVIRONMENT);
20
20
  commandDistroRouteUpdate.option('-t, --type <type>', texts_1.OPT_COMMAND_ROUTE_TYPE);
21
21
  commandDistroRouteUpdate.option('-s, --subdomain <subdomain>', texts_1.OPT_COMMAND_ROUTE_SUBDOMAIN);
22
22
  commandDistroRouteUpdate.option('-d, --domain <domain>', texts_1.OPT_COMMAND_ROUTE_DOMAIN);
@@ -29,17 +29,10 @@ commandDistroRouteUpdate.argument('<route-id>', texts_1.OPT_COMMAND_ROUTE_ID);
29
29
  commandDistroRouteUpdate.option('--format <text|json>', texts_1.OPTION_FORMAT);
30
30
  commandDistroRouteUpdate.action(async (identifier, routeId, options) => {
31
31
  const workspace = input_1.default.restApiWorkspace(options.workspace);
32
- const project = input_1.default.restApiProject(options.project, true);
33
- const scope = input_1.default.scope(project, options.scope);
34
32
  const client = input_1.default.restApiTokenClient();
35
- const data = await client.getDistributionByIdentifier(workspace, scope === distro_1.SCOPE.PROJECT ? project : null, identifier);
36
- if (!data?.domain) {
37
- output_1.default.exitError(new cliError_1.default('not_found', texts_1.ERR_WORKSPACE_NOT_FOUND, texts_1.HINT_WORKSPACE_LIST));
38
- }
39
- if (!data?.distribution_id) {
40
- output_1.default.exitError(new cliError_1.default('not_found', texts_1.ERR_COMMAND_DISTRO_NOT_FOUND, texts_1.HINT_DISTRO_LIST));
41
- }
42
- const route = await client.getRoute(workspace, scope === distro_1.SCOPE.PROJECT ? project : null, data.distribution_id, routeId);
33
+ const ctx = await (0, scope_1.resolveDistroContext)(client, workspace, options, identifier);
34
+ const distributionId = ctx.distributionId;
35
+ const route = await client.getRoute(workspace, ctx.api, distributionId, routeId);
43
36
  let changed = false;
44
37
  // This endpoint is a full replace: whatever the body omits is cleared. The
45
38
  // PATCH route exists but validates the body as a complete route too, so it
@@ -77,13 +70,13 @@ commandDistroRouteUpdate.action(async (identifier, routeId, options) => {
77
70
  changed = true;
78
71
  }
79
72
  if (options.target && options.target.length > 0) {
80
- body.targets = await input_1.default.routeTarget(client, workspace, scope === distro_1.SCOPE.PROJECT ? project : null, options.target);
73
+ body.targets = await input_1.default.routeTarget(client, workspace, ctx, options.target);
81
74
  changed = true;
82
75
  }
83
76
  if (!changed) {
84
77
  output_1.default.exitError(texts_1.ERR_COMMAND_NO_UPDATE);
85
78
  }
86
- const result = await client.updateRoute(workspace, scope === distro_1.SCOPE.PROJECT ? project : null, data.distribution_id, routeId, body);
79
+ const result = await client.updateRoute(workspace, ctx.api, distributionId, routeId, body);
87
80
  if (options.format === 'json') {
88
81
  output_1.default.json(result);
89
82
  output_1.default.exitNormal();
@@ -11,6 +11,7 @@ const get_1 = __importDefault(require("./route/get"));
11
11
  const delete_1 = __importDefault(require("./route/delete"));
12
12
  const update_1 = __importDefault(require("./route/update"));
13
13
  const open_1 = __importDefault(require("./route/open"));
14
+ const purge_1 = __importDefault(require("./route/purge"));
14
15
  const commandDistroRoute = (0, utils_1.newCommand)('route', texts_1.DESC_COMMAND_ROUTE, {
15
16
  examples: [
16
17
  ...texts_1.EXAMPLE_ROUTE_CREATE,
@@ -18,6 +19,7 @@ const commandDistroRoute = (0, utils_1.newCommand)('route', texts_1.DESC_COMMAND
18
19
  ...texts_1.EXAMPLE_ROUTE_LIST,
19
20
  ...texts_1.EXAMPLE_ROUTE_GET,
20
21
  ...texts_1.EXAMPLE_ROUTE_DELETE,
22
+ ...texts_1.EXAMPLE_ROUTE_PURGE,
21
23
  ],
22
24
  });
23
25
  commandDistroRoute.addCommand(create_1.default);
@@ -26,4 +28,5 @@ commandDistroRoute.addCommand(list_1.default);
26
28
  commandDistroRoute.addCommand(get_1.default);
27
29
  commandDistroRoute.addCommand(open_1.default);
28
30
  commandDistroRoute.addCommand(delete_1.default);
31
+ commandDistroRoute.addCommand(purge_1.default);
29
32
  exports.default = commandDistroRoute;
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.resolveDistroContext = void 0;
7
+ const texts_1 = require("../../texts");
8
+ const output_1 = __importDefault(require("../../output"));
9
+ const cliError_1 = __importDefault(require("../../cliError"));
10
+ const input_1 = __importDefault(require("../../input"));
11
+ const distro_1 = require("../../types/distro");
12
+ // Shared resolve preamble of the distro and route commands: flags/env ->
13
+ // scope -> /identifiers -> hash ids, exiting on a miss.
14
+ //
15
+ // Environments exist in projects and in the workspace. An explicit --project
16
+ // is a statement "the environment of this project", so it never falls back;
17
+ // a project implied by BUDDY_PROJECT or a linked directory only narrows the
18
+ // first lookup, and a workspace environment of that identifier is used when
19
+ // the project has none - otherwise a workspace environment's distributions
20
+ // would be unreachable from inside a linked project.
21
+ const resolveDistroContext = async (client, workspace, options, distribution) => {
22
+ const project = input_1.default.restApiProject(options.project, true);
23
+ const scope = input_1.default.scope(project, options.scope || '', options.environment, true);
24
+ if (options.environment && scope !== distro_1.SCOPE.ENVIRONMENT) {
25
+ output_1.default.exitError(texts_1.ERR_COMMAND_DISTRO_ENVIRONMENT_SCOPE);
26
+ }
27
+ const ctx = {
28
+ scope,
29
+ project: scope === distro_1.SCOPE.WORKSPACE ? null : project,
30
+ environment: null,
31
+ environmentId: null,
32
+ api: {},
33
+ distributionId: null,
34
+ };
35
+ let resolved = null;
36
+ if (scope === distro_1.SCOPE.ENVIRONMENT) {
37
+ const environment = options.environment;
38
+ resolved = await client.getResourceByIdentifier(workspace, {
39
+ project: project || undefined,
40
+ environment,
41
+ distribution,
42
+ });
43
+ if (resolved.domain && !resolved.environment_id && project && !options.project) {
44
+ ctx.project = null;
45
+ resolved = await client.getResourceByIdentifier(workspace, {
46
+ environment,
47
+ distribution,
48
+ });
49
+ }
50
+ if (!resolved.domain) {
51
+ output_1.default.exitError(new cliError_1.default('not_found', texts_1.ERR_WORKSPACE_NOT_FOUND, texts_1.HINT_WORKSPACE_LIST));
52
+ }
53
+ if (!resolved.environment_id) {
54
+ output_1.default.exitError(new cliError_1.default('not_found', texts_1.ERR_ENVIRONMENT_NOT_FOUND, texts_1.HINT_ENVIRONMENT_LIST));
55
+ }
56
+ ctx.environment = environment;
57
+ ctx.environmentId = resolved.environment_id;
58
+ ctx.api = { environmentId: ctx.environmentId };
59
+ }
60
+ else {
61
+ ctx.api = { project: ctx.project };
62
+ if (distribution) {
63
+ resolved = await client.getDistributionByIdentifier(workspace, { project: ctx.project }, distribution);
64
+ if (!resolved.domain) {
65
+ output_1.default.exitError(new cliError_1.default('not_found', texts_1.ERR_WORKSPACE_NOT_FOUND, texts_1.HINT_WORKSPACE_LIST));
66
+ }
67
+ }
68
+ }
69
+ if (distribution) {
70
+ if (!resolved?.distribution_id) {
71
+ output_1.default.exitError(new cliError_1.default('not_found', texts_1.ERR_COMMAND_DISTRO_NOT_FOUND, texts_1.HINT_DISTRO_LIST));
72
+ }
73
+ ctx.distributionId = resolved.distribution_id;
74
+ }
75
+ return ctx;
76
+ };
77
+ exports.resolveDistroContext = resolveDistroContext;
@@ -3,20 +3,20 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- const cliError_1 = __importDefault(require("../../cliError"));
7
6
  const utils_1 = require("../../utils");
8
7
  const texts_1 = require("../../texts");
9
8
  const input_1 = __importDefault(require("../../input"));
10
9
  const output_1 = __importDefault(require("../../output"));
11
- const distro_1 = require("../../types/distro");
10
+ const scope_1 = require("./scope");
12
11
  const commandDistroUpdate = (0, utils_1.newCommand)('update', texts_1.DESC_COMMAND_DISTRO_UPDATE, {
13
12
  requiredScopes: [utils_1.REST_API_SCOPE.DISTRIBUTION_WRITE],
14
13
  examples: texts_1.EXAMPLE_DISTRO_UPDATE,
15
14
  });
16
15
  commandDistroUpdate.alias('edit');
17
16
  commandDistroUpdate.option('-w, --workspace <domain>', texts_1.OPTION_REST_API_WORKSPACE);
18
- commandDistroUpdate.option('--scope <scope>', texts_1.OPT_COMMAND_SCOPE);
17
+ commandDistroUpdate.option('--scope <scope>', texts_1.OPT_COMMAND_SCOPE_ENVIRONMENT);
19
18
  commandDistroUpdate.option('-p, --project <name>', texts_1.OPTION_REST_API_PROJECT);
19
+ commandDistroUpdate.option('--environment <identifier>', texts_1.OPTION_DISTRO_ENVIRONMENT);
20
20
  commandDistroUpdate.option('-n, --name <name>', texts_1.OPT_COMMAND_DISTRO_NAME);
21
21
  commandDistroUpdate.option('--note <note>', texts_1.OPT_COMMAND_DISTRO_NOTE);
22
22
  commandDistroUpdate.option('--agent-note <note>', texts_1.OPT_COMMAND_DISTRO_AGENT_NOTE);
@@ -29,8 +29,6 @@ commandDistroUpdate.action(async (identifier, options) => {
29
29
  output_1.default.exitError(texts_1.ERR_COMMAND_DISTRO_ENABLE_DISABLE);
30
30
  }
31
31
  const workspace = input_1.default.restApiWorkspace(options.workspace);
32
- const project = input_1.default.restApiProject(options.project, true);
33
- const scope = input_1.default.scope(project, options.scope);
34
32
  const body = {};
35
33
  let changed = false;
36
34
  if (options.name) {
@@ -53,14 +51,8 @@ commandDistroUpdate.action(async (identifier, options) => {
53
51
  output_1.default.exitError(texts_1.ERR_COMMAND_NO_UPDATE);
54
52
  }
55
53
  const client = input_1.default.restApiTokenClient();
56
- const data = await client.getDistributionByIdentifier(workspace, scope === distro_1.SCOPE.PROJECT ? project : null, identifier);
57
- if (!data || !data.domain) {
58
- output_1.default.exitError(new cliError_1.default('not_found', texts_1.ERR_WORKSPACE_NOT_FOUND, texts_1.HINT_WORKSPACE_LIST));
59
- }
60
- if (!data || !data.distribution_id) {
61
- output_1.default.exitError(new cliError_1.default('not_found', texts_1.ERR_COMMAND_DISTRO_NOT_FOUND, texts_1.HINT_DISTRO_LIST));
62
- }
63
- const result = await client.updateDistribution(workspace, scope === distro_1.SCOPE.PROJECT ? project : null, data.distribution_id, body);
54
+ const ctx = await (0, scope_1.resolveDistroContext)(client, workspace, options, identifier);
55
+ const result = await client.updateDistribution(workspace, ctx.api, ctx.distributionId, body);
64
56
  if (options.format === 'json') {
65
57
  output_1.default.json(result);
66
58
  output_1.default.exitNormal();
@@ -24,6 +24,7 @@ const commandDistro = (0, utils_1.newCommand)('distro', texts_1.DESC_COMMAND_DIS
24
24
  ...texts_1.EXAMPLE_ROUTE_LIST,
25
25
  ...texts_1.EXAMPLE_ROUTE_GET,
26
26
  ...texts_1.EXAMPLE_ROUTE_DELETE,
27
+ ...texts_1.EXAMPLE_ROUTE_PURGE,
27
28
  ],
28
29
  });
29
30
  commandDistro.addCommand(create_1.default);
@@ -0,0 +1,218 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const node_os_1 = require("node:os");
7
+ const node_fs_1 = require("node:fs");
8
+ const promises_1 = require("node:stream/promises");
9
+ const utils_1 = require("../../utils");
10
+ const texts_1 = require("../../texts");
11
+ const output_1 = __importDefault(require("../../output"));
12
+ const input_1 = __importDefault(require("../../input"));
13
+ const cliError_1 = __importDefault(require("../../cliError"));
14
+ const distro_1 = require("../../types/distro");
15
+ const injection_1 = require("./injection");
16
+ const secretMask_1 = __importDefault(require("./secretMask"));
17
+ const collect = (value, previous = []) => [...previous, value];
18
+ // After the command exits its output may still be on the way: in the pipes,
19
+ // in the masking, in our own stdout. And a process the command left in the
20
+ // background (`sh -c 'daemon & ...'`) inherited the pipes and keeps them open
21
+ // for as long as it lives, writing or silent. bdy is the only reader of those
22
+ // pipes, so it stays until they close - leaving earlier would cut the
23
+ // daemon's output and, on its next write, kill it with SIGPIPE. --wait
24
+ // (seconds, 0 = no limit) bounds that: past it bdy gives up and exits with 1.
25
+ // The time is counted only over checks that came on time: a write to a slow
26
+ // reader (`| less`) blocks bdy (stdout is in blocking mode, index.ts), and
27
+ // output held up that way is not the command's fault - it is never cut.
28
+ const OUTPUT_CHECK_MS = 100;
29
+ const DEFAULT_WAIT_SECONDS = 300;
30
+ const parseWait = (value) => {
31
+ if (!/^\d+$/.test(value)) {
32
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_VARIABLE_INJECT_WAIT)(value));
33
+ }
34
+ return Number(value);
35
+ };
36
+ // true when all the output got through, false when --wait ran out first
37
+ const waitForOutput = (masks, done, waitSeconds) => new Promise((resolve) => {
38
+ // a destroyed stdout (reader gone) never empties - nothing to wait for
39
+ const unflushed = (stream) => !stream.destroyed && (stream.writableNeedDrain || stream.writableLength > 0);
40
+ const busy = () => unflushed(process.stdout) ||
41
+ unflushed(process.stderr) ||
42
+ masks.some((mask) => mask.writableLength > 0 || mask.readableLength > 0);
43
+ let ended = false;
44
+ let waitedMs = 0;
45
+ let last = Date.now();
46
+ const finish = (complete) => {
47
+ clearInterval(check);
48
+ resolve(complete);
49
+ };
50
+ const check = setInterval(() => {
51
+ const now = Date.now();
52
+ const elapsed = now - last;
53
+ last = now;
54
+ const held = busy();
55
+ // the pipes closed and our own buffers are empty
56
+ if (ended && !held)
57
+ return finish(true);
58
+ if (held || elapsed > OUTPUT_CHECK_MS * 2)
59
+ return;
60
+ waitedMs += elapsed;
61
+ if (waitSeconds && waitedMs >= waitSeconds * 1000)
62
+ finish(false);
63
+ }, OUTPUT_CHECK_MS);
64
+ void done.then(() => {
65
+ ended = true;
66
+ if (!busy())
67
+ finish(true);
68
+ });
69
+ });
70
+ // Files written by --var-file. Removed on every way out of the process that
71
+ // runs JavaScript - the command's end, an error, a forwarded signal - as all
72
+ // of them go through process.exit. Only a SIGKILL of bdy leaves them behind.
73
+ const written = [];
74
+ const removeWritten = () => {
75
+ for (const path of written.splice(0)) {
76
+ try {
77
+ (0, node_fs_1.unlinkSync)(path);
78
+ }
79
+ catch {
80
+ // already gone - the command may have removed it itself
81
+ }
82
+ }
83
+ };
84
+ const writeSecretFile = (path, content) => {
85
+ try {
86
+ // wx: never take a file that exists - deleting it afterwards would
87
+ // destroy something of the user's (an ~/.ssh/id_rsa)
88
+ (0, node_fs_1.writeFileSync)(path, content, { flag: 'wx', mode: 0o600 });
89
+ }
90
+ catch (err) {
91
+ const { code, message } = err;
92
+ if (code === 'EEXIST') {
93
+ throw new cliError_1.default('usage_error', (0, texts_1.ERR_VARIABLE_INJECT_FILE_EXISTS)(path));
94
+ }
95
+ throw new cliError_1.default('command_failed', (0, texts_1.ERR_VARIABLE_INJECT_FILE_WRITE)(path, message));
96
+ }
97
+ written.push(path);
98
+ };
99
+ // Without --scope the lookup of the other environment commands: the project
100
+ // of the context first (-p, BUDDY_PROJECT, linked), then the workspace. With
101
+ // --scope exactly one of them, no fallback - the variables injected must not
102
+ // come from an environment of the same name the user did not mean.
103
+ const resolveEnvironment = async (client, workspace, options) => {
104
+ if (!options.scope) {
105
+ return {
106
+ environmentId: await input_1.default.environmentId(client, workspace, options.environment, options),
107
+ projectIdentifier: null,
108
+ };
109
+ }
110
+ const project = input_1.default.restApiProject(options.project, true);
111
+ const scope = input_1.default.scope(project, options.scope);
112
+ const resolved = await client.getEnvironmentByIdentifier(workspace, options.environment, scope === distro_1.SCOPE.PROJECT ? project : null);
113
+ if (!resolved.environment_id) {
114
+ throw new cliError_1.default('not_found', texts_1.ERR_ENVIRONMENT_NOT_FOUND, texts_1.HINT_ENVIRONMENT_LIST);
115
+ }
116
+ return {
117
+ environmentId: resolved.environment_id,
118
+ projectIdentifier: scope === distro_1.SCOPE.PROJECT ? (resolved.project_identifier ?? null) : null,
119
+ };
120
+ };
121
+ const commandVariableInject = (0, utils_1.newCommand)('inject', texts_1.DESC_COMMAND_VARIABLE_INJECT, {
122
+ requiredScopes: [
123
+ utils_1.REST_API_SCOPE.VARIABLE_READ,
124
+ utils_1.REST_API_SCOPE.ENVIRONMENT_READ,
125
+ utils_1.REST_API_SCOPE.MASKED_VARIABLE_VALUE_DECRYPTED,
126
+ ],
127
+ examples: texts_1.EXAMPLE_VARIABLE_INJECT,
128
+ });
129
+ commandVariableInject.aliases(['exec', 'run']);
130
+ commandVariableInject.option('-w, --workspace <domain>', texts_1.OPTION_REST_API_WORKSPACE);
131
+ commandVariableInject.option('-p, --project <name>', texts_1.OPTION_REST_API_PROJECT);
132
+ commandVariableInject.option('--scope <scope>', texts_1.OPT_COMMAND_SCOPE);
133
+ commandVariableInject.requiredOption('--environment <identifier>', texts_1.OPTION_VARIABLE_INJECT_ENVIRONMENT);
134
+ commandVariableInject.option('--var <key>', texts_1.OPTION_VARIABLE_INJECT_VAR, collect);
135
+ commandVariableInject.option('--var-file <key:path>', texts_1.OPTION_VARIABLE_INJECT_VAR_FILE, collect);
136
+ commandVariableInject.option('--no-masking', texts_1.OPTION_VARIABLE_INJECT_NO_MASKING);
137
+ commandVariableInject.option('--wait <seconds>', texts_1.OPTION_VARIABLE_INJECT_WAIT, parseWait, DEFAULT_WAIT_SECONDS);
138
+ commandVariableInject.argument('<command...>', texts_1.OPTION_VARIABLE_INJECT_COMMAND);
139
+ // everything after the first argument is the command's, even when it looks
140
+ // like an option of ours (`bdy var exec --environment x ls --var`)
141
+ commandVariableInject.passThroughOptions();
142
+ commandVariableInject.action(async (command, options) => {
143
+ const workspace = input_1.default.restApiWorkspace(options.workspace);
144
+ const varFiles = (options.varFile ?? []).map(injection_1.parseVarFile);
145
+ const client = input_1.default.restApiTokenClient();
146
+ const { environmentId, projectIdentifier } = await resolveEnvironment(client, workspace, options);
147
+ const [result, environment] = await Promise.all([
148
+ client.getVariables(workspace, { environmentId }),
149
+ client.getEnvironment(workspace, environmentId),
150
+ ]);
151
+ // --scope PROJECT is a statement "the environment of this project": the
152
+ // API is asked along the project line, and the answer verified once more
153
+ if (projectIdentifier && environment.project?.name !== projectIdentifier) {
154
+ throw new cliError_1.default('not_found', texts_1.ERR_ENVIRONMENT_NOT_FOUND, texts_1.HINT_ENVIRONMENT_LIST);
155
+ }
156
+ const injection = (0, injection_1.buildInjection)(result.variables ?? [], environment, options.var ?? [], varFiles);
157
+ process.on('exit', removeWritten);
158
+ for (const { path, content } of injection.files)
159
+ writeSecretFile(path, content);
160
+ // Masking needs the output through bdy, which takes the terminal away from
161
+ // the command. Without anything to mask it keeps the terminal.
162
+ const masking = options.masking !== false && injection.secrets.length > 0;
163
+ if (options.masking !== false && injection.unmasked.length) {
164
+ output_1.default.noteWarning((0, texts_1.WARN_VARIABLE_INJECT_NOT_MASKED)(injection.unmasked));
165
+ }
166
+ const { spawn } = require('cross-spawn');
167
+ const child = spawn(command[0], command.slice(1), {
168
+ env: { ...process.env, ...injection.env },
169
+ stdio: masking ? ['inherit', 'pipe', 'pipe'] : 'inherit',
170
+ });
171
+ // The terminal sends Ctrl+C and Ctrl+\ to the whole foreground group, the
172
+ // command included: let it decide, and end when it ends - passing it on as
173
+ // well would be a second interrupt, which terraform, docker compose or npm
174
+ // take as "force quit now". bdy is on a terminal when any of its stdio is
175
+ // (`echo yes | bdy ...` still is; with masking only the command's output
176
+ // goes through bdy). Without one (a supervisor, `timeout -s INT`) such a
177
+ // signal is meant for bdy alone and is passed on, like SIGTERM and SIGHUP
178
+ // always are, so the command is not left running and the files are
179
+ // removed when it exits. SIGTSTP (Ctrl+Z) keeps its default: bdy stops
180
+ // together with the command, so the shell sees the job stopped and gives
181
+ // the prompt back.
182
+ const onTerminal = process.stdin.isTTY || process.stdout.isTTY || process.stderr.isTTY;
183
+ for (const signal of ['SIGINT', 'SIGQUIT']) {
184
+ process.on(signal, () => {
185
+ if (!onTerminal)
186
+ child.kill(signal);
187
+ });
188
+ }
189
+ for (const signal of ['SIGTERM', 'SIGHUP']) {
190
+ process.on(signal, () => child.kill(signal));
191
+ }
192
+ const masks = masking
193
+ ? [new secretMask_1.default(injection.secrets), new secretMask_1.default(injection.secrets)]
194
+ : [];
195
+ const streams = masks.map((mask, i) => (0, promises_1.pipeline)((i ? child.stderr : child.stdout), mask, (i ? process.stderr : process.stdout), { end: false }).catch(() => {
196
+ // our stdout closed by its reader (`| head`): the command gets
197
+ // EPIPE/SIGPIPE on its next write, as it would without bdy
198
+ }));
199
+ const exitCode = await new Promise((resolve, reject) => {
200
+ child.on('error', (err) => reject(err.code === 'ENOENT'
201
+ ? new cliError_1.default('command_failed', (0, texts_1.ERR_VARIABLE_INJECT_COMMAND_NOT_FOUND)(command[0]))
202
+ : err));
203
+ // exit, not close: close waits for every copy of the stdio pipes, and a
204
+ // process the command left in the background may hold them for as long
205
+ // as it lives - bdy would hang with the secret files still on disk
206
+ child.on('exit', (code, signal) => {
207
+ // the shell convention for a command killed by a signal
208
+ resolve(signal ? 128 + (node_os_1.constants.signals[signal] ?? 0) : (code ?? 1));
209
+ });
210
+ });
211
+ removeWritten();
212
+ if (!(await waitForOutput(masks, Promise.all(streams), options.wait))) {
213
+ output_1.default.noteWarning((0, texts_1.WARN_VARIABLE_INJECT_WAIT_EXCEEDED)(options.wait));
214
+ output_1.default.exitCode(1);
215
+ }
216
+ output_1.default.exitCode(exitCode);
217
+ });
218
+ exports.default = commandVariableInject;