@solidactions/cli 3.24.0 → 3.26.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/README.md CHANGED
@@ -523,6 +523,8 @@ solidactions doc upload logo-v2.png --replace marketing/logo.png
523
523
 
524
524
  **`doc pull` never writes through a link or over bytes it does not own.** It refuses before writing anything when a target is a symbolic link, sits under a linked folder inside the destination, or resolves outside it, with or without `--overwrite`. A local file the destination does not track (or tracks without a recorded hash) is replaced only with `--overwrite`; `-y` only answers the confirmation. A file that already holds exactly the server's bytes is simply adopted. A media doc whose download fails is not tracked over a local file.
525
525
 
526
+ **`doc pull` stops on the first error and records exactly what it wrote.** `doc pull` writes each file through a temp file beside it and renames it into place, in order, and saves the manifest last. If a write fails, or a file you changed in the meantime (or a folder where a doc goes) is in the way, the pull stops there with one line saying how many files were updated: the files before it stay written and are recorded in the manifest with their own checksums, the rest keep their bytes and their earlier entries, and nothing is rolled back or deleted. Pull again and it completes the job; a file that already holds exactly the bytes the pull would write is never treated as a local change. While it runs, a pull keeps one lock file, `.solidactions-docs.json.lock`, in the destination: a second pull into the same destination (or two started together) refuses and changes nothing, so two pulls never write into one folder; run it again when the first has finished. The pull removes its lock when it ends, including on an error or an interrupt. If the process is killed (SIGKILL) while writing, the manifest is the old one, the lock file is left behind, and tracked files are always re-checked by hash, so nothing is overwritten silently: if the line says another pull may be writing but none is running, delete that lock file and pull again. A doc or folder whose name would be `.solidactions-docs.json`, `.solidactions-docs.json.lock` or start with `.sa-write-` is written under a name with a leading `_`, and names that differ only by case or Unicode normalisation always get distinct names. There is no guarantee after a power loss.
527
+
526
528
  You do **not** need `--overwrite` to keep an edited file whose doc was deleted on the server — that case is handled by deletion propagation above, on the default path, and the file is kept with a warning.
527
529
 
528
530
  **Getting a doc id.** `doc upload --replace` accepts a docs path (`marketing/hero.png`), so you rarely need an id. If you want one, `doc pull` records it per file in the destination's `.solidactions-docs.json` sidecar, and `import_outputs` returns the ids it created. Note that `--replace` does not update a pulled directory's manifest. If you replace a tracked image out-of-band and leave the local file untouched, the next `doc push` reports it as **unchanged** and does nothing — the content hash matches, so `push` never asks the server. (Edit the local file too, and the drift guard fires as expected.) Re-pull to resync the manifest.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema_version": 1,
3
3
  "cli_name": "solidactions",
4
- "cli_version": "3.24.0",
4
+ "cli_version": "3.26.0",
5
5
  "global_options": [
6
6
  {
7
7
  "flags": "-V, --version",
@@ -4596,6 +4596,120 @@
4596
4596
  }
4597
4597
  ]
4598
4598
  },
4599
+ {
4600
+ "path": [
4601
+ "connection",
4602
+ "connect"
4603
+ ],
4604
+ "name": "connect",
4605
+ "aliases": [],
4606
+ "description": "Mint a connect link a person clicks to connect an app, then print it and the wait command",
4607
+ "hidden": false,
4608
+ "arguments": [
4609
+ {
4610
+ "name": "platform",
4611
+ "required": false,
4612
+ "variadic": false,
4613
+ "description": ""
4614
+ }
4615
+ ],
4616
+ "options": [
4617
+ {
4618
+ "flags": "--name <name>",
4619
+ "long": "--name",
4620
+ "short": null,
4621
+ "description": "Name of the new connection",
4622
+ "required": false,
4623
+ "value_required": true,
4624
+ "value_optional": false,
4625
+ "variadic": false,
4626
+ "negated": false,
4627
+ "hidden": false
4628
+ },
4629
+ {
4630
+ "flags": "--reconnect <name>",
4631
+ "long": "--reconnect",
4632
+ "short": null,
4633
+ "description": "Refresh an existing connection instead (its platform is looked up when omitted)",
4634
+ "required": false,
4635
+ "value_required": true,
4636
+ "value_optional": false,
4637
+ "variadic": false,
4638
+ "negated": false,
4639
+ "hidden": false
4640
+ },
4641
+ {
4642
+ "flags": "--bind <project:var>",
4643
+ "long": "--bind",
4644
+ "short": null,
4645
+ "description": "Bind a project variable to the connection once it is connected (repeatable, up to 10)",
4646
+ "required": false,
4647
+ "value_required": true,
4648
+ "value_optional": false,
4649
+ "variadic": false,
4650
+ "negated": false,
4651
+ "hidden": false,
4652
+ "default": []
4653
+ },
4654
+ {
4655
+ "flags": "-h, --help",
4656
+ "long": "--help",
4657
+ "short": "-h",
4658
+ "description": "display help for command",
4659
+ "required": false,
4660
+ "value_required": false,
4661
+ "value_optional": false,
4662
+ "variadic": false,
4663
+ "negated": false,
4664
+ "hidden": false
4665
+ }
4666
+ ]
4667
+ },
4668
+ {
4669
+ "path": [
4670
+ "connection",
4671
+ "wait"
4672
+ ],
4673
+ "name": "wait",
4674
+ "aliases": [],
4675
+ "description": "Wait until a connect link is used: exit 0 connected, 1 expired, cancelled or failed, 2 still open at --timeout, 130 on Ctrl-C",
4676
+ "hidden": false,
4677
+ "arguments": [
4678
+ {
4679
+ "name": "request-id",
4680
+ "required": true,
4681
+ "variadic": false,
4682
+ "description": ""
4683
+ }
4684
+ ],
4685
+ "options": [
4686
+ {
4687
+ "flags": "--timeout <duration>",
4688
+ "long": "--timeout",
4689
+ "short": null,
4690
+ "description": "How long to wait, e.g. 30s, 15m, 1h",
4691
+ "required": false,
4692
+ "value_required": true,
4693
+ "value_optional": false,
4694
+ "variadic": false,
4695
+ "negated": false,
4696
+ "hidden": false,
4697
+ "default": "15m"
4698
+ },
4699
+ {
4700
+ "flags": "-h, --help",
4701
+ "long": "--help",
4702
+ "short": "-h",
4703
+ "description": "display help for command",
4704
+ "required": false,
4705
+ "value_required": false,
4706
+ "value_optional": false,
4707
+ "variadic": false,
4708
+ "negated": false,
4709
+ "hidden": false
4710
+ }
4711
+ ]
4712
+ },
4599
4713
  {
4600
4714
  "path": [
4601
4715
  "connection",
@@ -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.connectionConnect = connectionConnect;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const chalk_1 = __importDefault(require("chalk"));
9
+ const api_1 = require("../utils/api");
10
+ const output_1 = require("../utils/output");
11
+ const connect_link_1 = require("../utils/connect-link");
12
+ function fail(line) {
13
+ (0, output_1.err)(line, chalk_1.default.red);
14
+ process.exit(1);
15
+ }
16
+ async function connectionConnect(platform, options) {
17
+ if (options.name !== undefined && options.reconnect !== undefined) {
18
+ fail('connection connect: give --name NAME for a new connection or --reconnect NAME for an existing one, not both.');
19
+ }
20
+ const reconnect = options.reconnect !== undefined;
21
+ const name = (reconnect ? options.reconnect : options.name)?.trim() ?? '';
22
+ if (reconnect && name === '') {
23
+ fail('connection connect: --reconnect NAME needs a connection name.');
24
+ }
25
+ if (name === '') {
26
+ fail('connection connect: --name NAME is required (or --reconnect NAME to refresh an existing connection).');
27
+ }
28
+ let resolvedPlatform = platform?.trim() ?? '';
29
+ if (!reconnect && resolvedPlatform === '') {
30
+ fail('connection connect: give the platform, e.g. solidactions connection connect gmail --name gmail-main (solidactions oauth-action platforms lists them).');
31
+ }
32
+ const rawBindings = options.bind ?? [];
33
+ if (rawBindings.length > connect_link_1.CONNECT_LINK_MAX_BINDINGS) {
34
+ fail(`connection connect: at most ${connect_link_1.CONNECT_LINK_MAX_BINDINGS} --bind options.`);
35
+ }
36
+ let bindings = [];
37
+ try {
38
+ bindings = rawBindings.map(connect_link_1.parseBinding);
39
+ }
40
+ catch (error) {
41
+ fail(`connection connect: ${error.message}`);
42
+ }
43
+ const config = await (0, api_1.requireConfigWithWorkspace)();
44
+ if (resolvedPlatform === '') {
45
+ let connections = [];
46
+ try {
47
+ const response = await axios_1.default.get(`${config.host}/api/v1/connections`, { headers: (0, api_1.getApiHeaders)(config) });
48
+ connections = Array.isArray(response.data?.data) ? response.data.data : [];
49
+ }
50
+ catch (error) {
51
+ fail(`${(0, connect_link_1.connectLinkFailureLine)(error, config.host)} (looking up ${name}'s platform; give it to skip the lookup: solidactions connection connect ${(0, connect_link_1.shellArg)('<platform>')} --reconnect ${(0, connect_link_1.shellArg)(name)})`);
52
+ }
53
+ const match = connections.find((connection) => typeof connection === 'object' && connection !== null && typeof connection.name === 'string' && connection.name === name);
54
+ if (!match?.provider) {
55
+ fail(`No connection named ${name} in this workspace; solidactions connection list shows the names.`);
56
+ }
57
+ resolvedPlatform = match.provider;
58
+ }
59
+ let link;
60
+ try {
61
+ const response = await axios_1.default.post(`${config.host}/api/v1/connections/requests`, { platform: resolvedPlatform, name, mode: reconnect ? 'reconnect' : 'connect', bindings }, { headers: (0, api_1.getApiHeaders)(config, 'application/json') });
62
+ link = response.data;
63
+ }
64
+ catch (error) {
65
+ fail((0, connect_link_1.connectLinkFailureLine)(error, config.host));
66
+ }
67
+ if (typeof link?.id !== 'string' || typeof link?.url !== 'string') {
68
+ fail('Failed: the server answered without a connect link.');
69
+ }
70
+ const expiry = typeof link.expires_at === 'string' ? ` (expires ${(0, connect_link_1.formatExpiry)(link.expires_at)})` : '';
71
+ const text = typeof link.text === 'string' && link.text.trim() !== ''
72
+ ? link.text
73
+ : `Connect link: ${link.url}\nRequest id: ${link.id}${expiry}.`;
74
+ (0, output_1.out)(text);
75
+ (0, output_1.out)('When it is done, run:');
76
+ (0, output_1.out)(` ${(0, connect_link_1.waitCommandLine)((0, connect_link_1.plainText)(link.id))}`);
77
+ }
@@ -7,15 +7,24 @@ exports.connectionList = connectionList;
7
7
  const axios_1 = __importDefault(require("axios"));
8
8
  const chalk_1 = __importDefault(require("chalk"));
9
9
  const api_1 = require("../utils/api");
10
+ const connect_link_1 = require("../utils/connect-link");
11
+ const output_1 = require("../utils/output");
10
12
  const table_1 = require("../utils/table");
11
13
  const ERROR_SNIPPET_WIDTH = 40;
12
14
  function connectionStatus(connection) {
13
- const status = connection.status || '?';
15
+ const status = (0, connect_link_1.plainText)(connection.status || '?');
14
16
  const error = connection.error_message?.trim();
15
17
  if (!error) {
16
18
  return status;
17
19
  }
18
- return `${status} — ${(0, table_1.truncateCell)((0, table_1.sanitizeCell)(error), ERROR_SNIPPET_WIDTH)}`;
20
+ return `${status} — ${(0, table_1.truncateCell)((0, table_1.sanitizeCell)((0, connect_link_1.plainText)(error)), ERROR_SNIPPET_WIDTH)}`;
21
+ }
22
+ function sourceUse(connection) {
23
+ if (connection.allow_source_use === true)
24
+ return 'yes';
25
+ if (connection.allow_source_use === false)
26
+ return 'no';
27
+ return '-';
19
28
  }
20
29
  async function connectionList() {
21
30
  const config = await (0, api_1.requireConfigWithWorkspace)();
@@ -25,36 +34,37 @@ async function connectionList() {
25
34
  });
26
35
  const connections = response.data.data || [];
27
36
  if (connections.length === 0) {
28
- console.log(chalk_1.default.gray('No connections found.'));
37
+ (0, output_1.out)('No connections found.', chalk_1.default.gray);
29
38
  return;
30
39
  }
31
- console.log(chalk_1.default.blue('Connections:\n'));
40
+ (0, output_1.out)('Connections:\n', chalk_1.default.blue);
32
41
  const rows = connections.map((connection) => [
33
- connection.name || '?',
34
- connection.provider || '?',
42
+ (0, connect_link_1.plainText)(connection.name || '?'),
43
+ (0, connect_link_1.plainText)(connection.provider || '?'),
35
44
  connectionStatus(connection),
36
- connection.last_used_at || '-',
45
+ (0, connect_link_1.plainText)(connection.last_used_at || '-'),
46
+ sourceUse(connection),
37
47
  ]);
38
- const lines = (0, table_1.renderTable)(['NAME', 'PROVIDER', 'STATUS', 'LAST USED'], rows, {
48
+ const lines = (0, table_1.renderTable)(['NAME', 'PROVIDER', 'STATUS', 'LAST USED', 'DATA SOURCE'], rows, {
39
49
  minWidths: [24, 14, 20],
40
50
  });
41
- console.log(chalk_1.default.gray(lines[0]));
42
- console.log(chalk_1.default.gray(lines[1]));
51
+ (0, output_1.out)(lines[0], chalk_1.default.gray);
52
+ (0, output_1.out)(lines[1], chalk_1.default.gray);
43
53
  for (const line of lines.slice(2)) {
44
- console.log(line);
54
+ (0, output_1.out)(line);
45
55
  }
46
- console.log('');
47
- console.log(chalk_1.default.gray(`${connections.length} connection(s)`));
56
+ (0, output_1.out)('');
57
+ (0, output_1.out)(`${connections.length} connection(s)`, chalk_1.default.gray);
48
58
  }
49
59
  catch (error) {
50
60
  if (error.response?.status === 401) {
51
- console.error(chalk_1.default.red((0, api_1.authFailedLine)(config.host)));
61
+ (0, output_1.err)((0, api_1.authFailedLine)(config.host), chalk_1.default.red);
52
62
  }
53
63
  else if (error.response) {
54
- console.error(chalk_1.default.red((0, api_1.formatApiFailure)(error.response.status, error.response.data)));
64
+ (0, output_1.err)((0, api_1.formatApiFailure)(error.response.status, error.response.data), chalk_1.default.red);
55
65
  }
56
66
  else {
57
- console.error(chalk_1.default.red('Connection failed:'), error.message);
67
+ (0, output_1.err)(`Connection failed: ${error.message}`, chalk_1.default.red);
58
68
  }
59
69
  process.exit(1);
60
70
  }
@@ -0,0 +1,234 @@
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.WAIT_EXIT_INTERRUPTED = exports.WAIT_EXIT_TIMEOUT = exports.WAIT_MAX_FAILED_CHECKS = exports.WAIT_DEFAULT_TIMEOUT = exports.WAIT_POLL_INTERVAL_MS = void 0;
7
+ exports.parseWaitTimeout = parseWaitTimeout;
8
+ exports.connectionWait = connectionWait;
9
+ const axios_1 = __importDefault(require("axios"));
10
+ const chalk_1 = __importDefault(require("chalk"));
11
+ const api_1 = require("../utils/api");
12
+ const connect_link_1 = require("../utils/connect-link");
13
+ const output_1 = require("../utils/output");
14
+ exports.WAIT_POLL_INTERVAL_MS = 5_000;
15
+ exports.WAIT_DEFAULT_TIMEOUT = '15m';
16
+ exports.WAIT_MAX_FAILED_CHECKS = 5;
17
+ exports.WAIT_EXIT_TIMEOUT = 2;
18
+ exports.WAIT_EXIT_INTERRUPTED = 130;
19
+ const UNIT_MS = { s: 1_000, m: 60_000, h: 3_600_000 };
20
+ const MAX_TIMEOUT_MS = 24 * 3_600_000;
21
+ function parseWaitTimeout(value) {
22
+ const match = /^(\d+)([smh]?)$/.exec(value.trim());
23
+ if (!match) {
24
+ throw new Error(`--timeout must look like 30s, 15m or 1h (got "${value}").`);
25
+ }
26
+ const ms = Number(match[1]) * UNIT_MS[match[2] || 's'];
27
+ if (ms < 1_000 || ms > MAX_TIMEOUT_MS) {
28
+ throw new Error('--timeout must be between 1s and 24h.');
29
+ }
30
+ return ms;
31
+ }
32
+ function pollIntervalMs(env = process.env) {
33
+ if (env.SOLIDACTIONS_TEST_HOOKS === '1') {
34
+ const override = Number(env.SOLIDACTIONS_CONNECTION_WAIT_INTERVAL_MS);
35
+ if (Number.isInteger(override) && override > 0)
36
+ return override;
37
+ }
38
+ return exports.WAIT_POLL_INTERVAL_MS;
39
+ }
40
+ function isTransient(error) {
41
+ const status = error?.response?.status;
42
+ return status === undefined || status === 429 || status >= 500;
43
+ }
44
+ /** True for the abort our own deadline timer fires (axios rejects with a CanceledError). */
45
+ function isDeadlineAbort(error) {
46
+ return error?.code === 'ERR_CANCELED' || error?.name === 'CanceledError';
47
+ }
48
+ /**
49
+ * True only for a usable status payload: a non-null object with a string
50
+ * `status`, plus the fields each status prints (`name`, `platform_name`,
51
+ * `expires_at` for requested/opened; `name`, `platform`, `mode` for expired,
52
+ * feeding the retry command; `name`, `platform_name` for connected, feeding
53
+ * the `Connected:` line). Anything else is answered with the one-line
54
+ * unusable-status failure, never a retry.
55
+ */
56
+ function hasUsableStatus(body) {
57
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) {
58
+ return false;
59
+ }
60
+ const link = body;
61
+ if (typeof link.status !== 'string') {
62
+ return false;
63
+ }
64
+ if (link.status === 'requested' || link.status === 'opened') {
65
+ return typeof link.name === 'string' && typeof link.platform_name === 'string' && typeof link.expires_at === 'string';
66
+ }
67
+ if (link.status === 'expired') {
68
+ return typeof link.name === 'string' && typeof link.platform === 'string' && typeof link.mode === 'string';
69
+ }
70
+ if (link.status === 'connected') {
71
+ return typeof link.name === 'string' && typeof link.platform_name === 'string';
72
+ }
73
+ return true;
74
+ }
75
+ /**
76
+ * The `connected`-payload fields `printConnected` consumes, checked before
77
+ * anything is printed: `bindings` (missing means none) must be an array of
78
+ * objects with string `project`/`var`; `connection`/`connected_by` must be
79
+ * null or objects. Returns the one failure line, or null when usable.
80
+ */
81
+ function connectedPayloadProblem(link) {
82
+ const id = typeof link.id === 'string' ? link.id : 'unknown';
83
+ if (link.bindings !== undefined && link.bindings !== null) {
84
+ if (!Array.isArray(link.bindings)) {
85
+ return `Failed: connect link ${id} answered connected with unusable bindings.`;
86
+ }
87
+ for (const binding of link.bindings) {
88
+ if (typeof binding !== 'object' || binding === null || typeof binding.project !== 'string' || typeof binding.var !== 'string') {
89
+ return `Failed: connect link ${id} answered connected with unusable bindings.`;
90
+ }
91
+ }
92
+ }
93
+ for (const key of ['connection', 'connected_by']) {
94
+ const value = link[key];
95
+ if (value !== undefined && value !== null && (typeof value !== 'object' || Array.isArray(value))) {
96
+ return `Failed: connect link ${id} answered connected with an unusable ${key}.`;
97
+ }
98
+ }
99
+ return null;
100
+ }
101
+ function fail(line, code = 1) {
102
+ (0, output_1.err)(line, chalk_1.default.red);
103
+ process.exit(code);
104
+ }
105
+ function sleep(ms) {
106
+ return new Promise((resolve) => setTimeout(resolve, ms));
107
+ }
108
+ function retryCommand(link) {
109
+ const flag = link.mode === 'reconnect' ? '--reconnect' : '--name';
110
+ return `solidactions connection connect ${(0, connect_link_1.shellArg)(link.platform)} ${flag} ${(0, connect_link_1.shellArg)(link.name)}`;
111
+ }
112
+ function printConnected(link) {
113
+ const name = link.connection?.name ?? link.name;
114
+ const by = link.connected_by?.name ? `, by ${link.connected_by.name}` : '';
115
+ (0, output_1.out)(`Connected: ${name} (${link.platform_name})${by}.`);
116
+ if (!link.bindings || link.bindings.length === 0) {
117
+ (0, output_1.out)('Bindings: none.');
118
+ return;
119
+ }
120
+ for (const binding of link.bindings) {
121
+ (0, output_1.out)(` project ${binding.project} uses it as ${binding.var}`);
122
+ }
123
+ }
124
+ async function connectionWait(requestId, options) {
125
+ const timeoutText = (options.timeout ?? exports.WAIT_DEFAULT_TIMEOUT).trim();
126
+ let timeoutMs = 0;
127
+ try {
128
+ timeoutMs = parseWaitTimeout(timeoutText);
129
+ }
130
+ catch (error) {
131
+ fail(`connection wait: ${error.message}`);
132
+ }
133
+ const config = await (0, api_1.requireConfigWithWorkspace)();
134
+ // Ctrl-C: the link stays open on the server; say how to pick the wait up again.
135
+ process.once('SIGINT', () => {
136
+ (0, output_1.err)(`Still waiting: resume with ${(0, connect_link_1.waitCommandLine)(requestId)}`, chalk_1.default.gray);
137
+ process.exit(exports.WAIT_EXIT_INTERRUPTED);
138
+ });
139
+ const interval = pollIntervalMs();
140
+ const deadline = Date.now() + timeoutMs;
141
+ let failedChecks = 0;
142
+ let last = null;
143
+ let announced = false;
144
+ function failTimeout() {
145
+ const state = last ? `is ${last.status}` : 'status unknown (last check failed)';
146
+ const expires = last?.expires_at ? ` (link expires ${(0, connect_link_1.formatExpiry)(last.expires_at)})` : '';
147
+ fail(`Still waiting after ${timeoutText}: connect link ${requestId} ${state}${expires}. Run ${(0, connect_link_1.waitCommandLine)(requestId)} again to keep waiting.`, exports.WAIT_EXIT_TIMEOUT);
148
+ }
149
+ while (true) {
150
+ // Admission: never send a request once the deadline has passed. The
151
+ // sleep below wakes at the deadline at the latest, so reaching here
152
+ // past it means the budget is spent without another GET.
153
+ if (Date.now() >= deadline) {
154
+ failTimeout();
155
+ }
156
+ const remaining = deadline - Date.now();
157
+ const controller = new AbortController();
158
+ const abortTimer = setTimeout(() => controller.abort(), remaining);
159
+ let statusResponse;
160
+ try {
161
+ // Transport only: this catch counts failed CHECKS (network, 429,
162
+ // 5xx) and handles the abort/timeout path. Interpreting the 200
163
+ // below runs outside this catch, so a payload that cannot be used
164
+ // can never be counted as a transient failure.
165
+ statusResponse = await axios_1.default.get(`${config.host}/api/v1/connections/requests/${encodeURIComponent(requestId)}`, {
166
+ headers: (0, api_1.getApiHeaders)(config),
167
+ signal: controller.signal,
168
+ });
169
+ }
170
+ catch (error) {
171
+ clearTimeout(abortTimer);
172
+ // Our own deadline abort is the timeout, not a transient failure:
173
+ // the link may still be open, so keep the exit-2 resume behavior.
174
+ if (isDeadlineAbort(error)) {
175
+ failTimeout();
176
+ }
177
+ if (!isTransient(error)) {
178
+ fail((0, connect_link_1.connectLinkFailureLine)(error, config.host));
179
+ }
180
+ failedChecks += 1;
181
+ if (failedChecks >= exports.WAIT_MAX_FAILED_CHECKS) {
182
+ fail(`${(0, connect_link_1.connectLinkFailureLine)(error, config.host)} (gave up after ${exports.WAIT_MAX_FAILED_CHECKS} failed checks in a row)`);
183
+ }
184
+ const after = deadline - Date.now();
185
+ if (after <= 0) {
186
+ failTimeout();
187
+ }
188
+ await sleep(Math.min(interval, after));
189
+ continue;
190
+ }
191
+ clearTimeout(abortTimer);
192
+ try {
193
+ if (!hasUsableStatus(statusResponse.data)) {
194
+ fail(`Failed: connect link ${requestId}: the server's answer has no usable status.`);
195
+ }
196
+ last = statusResponse.data;
197
+ switch (last.status) {
198
+ case 'connected': {
199
+ const problem = connectedPayloadProblem(last);
200
+ if (problem !== null) {
201
+ fail(problem);
202
+ }
203
+ printConnected(last);
204
+ return;
205
+ }
206
+ case 'expired':
207
+ fail(`Connect link ${last.id} expired before anyone connected ${last.name}. Ask for a new one: ${retryCommand(last)}`);
208
+ case 'cancelled':
209
+ fail(`Connect link ${last.id} for ${last.name} was cancelled.`);
210
+ case 'requested':
211
+ case 'opened':
212
+ if (!announced) {
213
+ (0, output_1.out)(`Waiting for someone to connect ${last.platform_name} as ${last.name} (request ${last.id}, link expires ${(0, connect_link_1.formatExpiry)(last.expires_at)}).`);
214
+ announced = true;
215
+ }
216
+ break;
217
+ default:
218
+ fail(`Failed: connect link ${requestId} has an unknown status "${String(last.status)}".`);
219
+ }
220
+ }
221
+ catch {
222
+ // Interpreting a 200 never retries and never exits 2: any failure
223
+ // to use the payload is the same one-line answer as I2.
224
+ fail(`Failed: connect link ${requestId}: the server's answer has no usable status.`);
225
+ }
226
+ // Only a fully interpreted 200 resets the consecutive-failure count.
227
+ failedChecks = 0;
228
+ const after = deadline - Date.now();
229
+ if (after <= 0) {
230
+ failTimeout();
231
+ }
232
+ await sleep(Math.min(interval, after));
233
+ }
234
+ }
@@ -25,6 +25,11 @@ const CLI_OAUTH_CLIENT_ID = '9f1b6e2a-9c1e-4b6e-8f0a-6c9f2b1e7d4c';
25
25
  // added at consent time, because the device code's scope set is frozen when
26
26
  // the code is created (#1252).
27
27
  const CLI_SCOPES_WITH_REVEAL = 'env env:reveal deploy runs docs databases';
28
+ // `connections:request` (cli#219, connect links) is granted with the token
29
+ // like the other CLI scopes. It comes first; a server that has not
30
+ // registered it rejects the whole request with `invalid_scope`, and the
31
+ // next list is tried.
32
+ const CLI_SCOPES_WITH_CONNECT_LINKS = 'env env:reveal deploy runs docs databases connections:request';
28
33
  // Pre-#1252 scope list, kept as the fallback for servers that haven't
29
34
  // registered `env:reveal` yet (older production, a lagging staging, a
30
35
  // self-hosted install). Passport rejects the entire device-code request with
@@ -32,30 +37,33 @@ const CLI_SCOPES_WITH_REVEAL = 'env env:reveal deploy runs docs databases';
32
37
  // `env:reveal` unconditionally would hard-break device login everywhere
33
38
  // until every server picks up the companion change.
34
39
  const CLI_SCOPES_LEGACY = 'env deploy runs docs databases';
40
+ // Tried in order; each retry only on 400 `invalid_scope`.
41
+ const CLI_SCOPE_LISTS = [CLI_SCOPES_WITH_CONNECT_LINKS, CLI_SCOPES_WITH_REVEAL, CLI_SCOPES_LEGACY];
35
42
  /**
36
- * Request a device code with the full (env:reveal-including) scope list. If
37
- * the server doesn't yet recognize `env:reveal` it rejects the whole request
38
- * with 400 `invalid_scope` — retry once with the legacy scope list so login
39
- * still succeeds. Any other rejection (e.g. a bad client_id) still fails
40
- * loudly; only this specific, detectable condition is swallowed.
43
+ * Request a device code with the full scope list (`connections:request` and
44
+ * `env:reveal` included). If the server doesn't yet recognize a scope it
45
+ * rejects the whole request with 400 `invalid_scope` — retry with the next,
46
+ * shorter list (without `connections:request`, then the legacy list without
47
+ * `env:reveal`) so login still succeeds: at most 3 requests. Any other
48
+ * rejection (e.g. a bad client_id) still fails loudly; only this specific,
49
+ * detectable condition is swallowed.
41
50
  */
42
51
  async function requestDeviceCode(host) {
43
- try {
44
- const response = await axios_1.default.post(`${host}/oauth/device/code`, {
45
- client_id: CLI_OAUTH_CLIENT_ID,
46
- scope: CLI_SCOPES_WITH_REVEAL,
47
- });
48
- return response.data;
49
- }
50
- catch (e) {
51
- if (e?.response?.status === 400 && e.response.data?.error === 'invalid_scope') {
52
+ for (let i = 0;; i++) {
53
+ try {
52
54
  const response = await axios_1.default.post(`${host}/oauth/device/code`, {
53
55
  client_id: CLI_OAUTH_CLIENT_ID,
54
- scope: CLI_SCOPES_LEGACY,
56
+ scope: CLI_SCOPE_LISTS[i],
55
57
  });
56
58
  return response.data;
57
59
  }
58
- throw e;
60
+ catch (e) {
61
+ const invalidScope = e?.response?.status === 400 && e.response.data?.error === 'invalid_scope';
62
+ if (invalidScope && i < CLI_SCOPE_LISTS.length - 1) {
63
+ continue;
64
+ }
65
+ throw e;
66
+ }
59
67
  }
60
68
  }
61
69
  function sleep(ms) {