@atelier201/cli 0.0.0-stage → 0.4.1

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.
Files changed (90) hide show
  1. package/AGENTS.md +379 -0
  2. package/LICENSE +21 -0
  3. package/README.md +146 -2
  4. package/dist/api-types.generated.js +8 -0
  5. package/dist/api-types.generated.js.map +1 -0
  6. package/dist/commands/api.js +111 -0
  7. package/dist/commands/api.js.map +1 -0
  8. package/dist/commands/auth.js +284 -0
  9. package/dist/commands/auth.js.map +1 -0
  10. package/dist/commands/builds.js +169 -0
  11. package/dist/commands/builds.js.map +1 -0
  12. package/dist/commands/changesets.js +91 -0
  13. package/dist/commands/changesets.js.map +1 -0
  14. package/dist/commands/common.js +89 -0
  15. package/dist/commands/common.js.map +1 -0
  16. package/dist/commands/completion.js +120 -0
  17. package/dist/commands/completion.js.map +1 -0
  18. package/dist/commands/content.js +281 -0
  19. package/dist/commands/content.js.map +1 -0
  20. package/dist/commands/doctor.js +141 -0
  21. package/dist/commands/doctor.js.map +1 -0
  22. package/dist/commands/domains.js +109 -0
  23. package/dist/commands/domains.js.map +1 -0
  24. package/dist/commands/feedback.js +39 -0
  25. package/dist/commands/feedback.js.map +1 -0
  26. package/dist/commands/files.js +286 -0
  27. package/dist/commands/files.js.map +1 -0
  28. package/dist/commands/help-json.js +128 -0
  29. package/dist/commands/help-json.js.map +1 -0
  30. package/dist/commands/history.js +83 -0
  31. package/dist/commands/history.js.map +1 -0
  32. package/dist/commands/mcp.js +129 -0
  33. package/dist/commands/mcp.js.map +1 -0
  34. package/dist/commands/media.js +273 -0
  35. package/dist/commands/media.js.map +1 -0
  36. package/dist/commands/pages.js +33 -0
  37. package/dist/commands/pages.js.map +1 -0
  38. package/dist/commands/previews.js +73 -0
  39. package/dist/commands/previews.js.map +1 -0
  40. package/dist/commands/publish.js +228 -0
  41. package/dist/commands/publish.js.map +1 -0
  42. package/dist/commands/read.js +85 -0
  43. package/dist/commands/read.js.map +1 -0
  44. package/dist/commands/site-guest.js +159 -0
  45. package/dist/commands/site-guest.js.map +1 -0
  46. package/dist/commands/site.js +204 -0
  47. package/dist/commands/site.js.map +1 -0
  48. package/dist/commands/sites.js +168 -0
  49. package/dist/commands/sites.js.map +1 -0
  50. package/dist/commands/skills.js +45 -0
  51. package/dist/commands/skills.js.map +1 -0
  52. package/dist/commands/workspace.js +89 -0
  53. package/dist/commands/workspace.js.map +1 -0
  54. package/dist/credentials.js +151 -0
  55. package/dist/credentials.js.map +1 -0
  56. package/dist/errors.js +166 -0
  57. package/dist/errors.js.map +1 -0
  58. package/dist/exit-codes.js +88 -0
  59. package/dist/exit-codes.js.map +1 -0
  60. package/dist/http.js +275 -0
  61. package/dist/http.js.map +1 -0
  62. package/dist/index.js +184 -0
  63. package/dist/index.js.map +1 -0
  64. package/dist/keychain.js +185 -0
  65. package/dist/keychain.js.map +1 -0
  66. package/dist/oauth/browser.js +33 -0
  67. package/dist/oauth/browser.js.map +1 -0
  68. package/dist/oauth/pkce.js +118 -0
  69. package/dist/oauth/pkce.js.map +1 -0
  70. package/dist/oauth/server.js +276 -0
  71. package/dist/oauth/server.js.map +1 -0
  72. package/dist/output.js +163 -0
  73. package/dist/output.js.map +1 -0
  74. package/dist/project.js +178 -0
  75. package/dist/project.js.map +1 -0
  76. package/dist/refresh-lock.js +84 -0
  77. package/dist/refresh-lock.js.map +1 -0
  78. package/dist/run.js +197 -0
  79. package/dist/run.js.map +1 -0
  80. package/dist/session.js +147 -0
  81. package/dist/session.js.map +1 -0
  82. package/dist/site-link.js +145 -0
  83. package/dist/site-link.js.map +1 -0
  84. package/dist/site-sync.js +191 -0
  85. package/dist/site-sync.js.map +1 -0
  86. package/dist/tar.js +228 -0
  87. package/dist/tar.js.map +1 -0
  88. package/dist/version.js +34 -0
  89. package/dist/version.js.map +1 -0
  90. package/package.json +47 -3
package/dist/http.js ADDED
@@ -0,0 +1,275 @@
1
+ /**
2
+ * The HTTP layer: one authenticated request function, with retries.
3
+ *
4
+ * Two properties matter more than anything else here:
5
+ *
6
+ * 1. **A failure always becomes an `ApiRequestError` carrying the server's own
7
+ * envelope.** Nothing else in the CLI has to know how the API reports
8
+ * errors, and nothing re-words a message the API wrote to be acted on.
9
+ * 2. **429 and 5xx are retried automatically**, honouring `Retry-After` with
10
+ * jittered backoff. An agent hitting the burst ceiling recovers on its own
11
+ * rather than surfacing a transient failure as a real one.
12
+ *
13
+ * `fetch`, `sleep` and the jitter source are injectable so the retry logic can
14
+ * be tested without a network or a wall clock.
15
+ */
16
+ import { ApiRequestError, NetworkError } from "./errors.js";
17
+ import { USER_AGENT } from "./version.js";
18
+ const RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
19
+ /**
20
+ * Idempotent per RFC 9110 §9.2.2: repeating one has the same effect on the
21
+ * server as sending it once, so a retry is free. `POST` and `PATCH` are not on
22
+ * this list and are deliberately excluded below.
23
+ */
24
+ const IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS", "TRACE"]);
25
+ const BASE_BACKOFF_MS = 500;
26
+ const MAX_BACKOFF_MS = 20_000;
27
+ const MAX_RETRY_AFTER_MS = 60_000;
28
+ const DEFAULT_TIMEOUT_MS = 60_000;
29
+ export class ApiClient {
30
+ options;
31
+ noticeSent = false;
32
+ constructor(options) {
33
+ this.options = {
34
+ baseUrl: options.baseUrl.replace(/\/+$/, ""),
35
+ getToken: options.getToken,
36
+ retry: options.retry ?? true,
37
+ maxRetries: options.maxRetries ?? 3,
38
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
39
+ fetchImpl: options.fetchImpl ?? ((input, init) => fetch(input, init)),
40
+ sleep: options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
41
+ random: options.random ?? Math.random,
42
+ onNotice: options.onNotice,
43
+ };
44
+ }
45
+ /** `path` is relative to the versioned base, e.g. `/account`. */
46
+ async request(method, path, options = {}) {
47
+ const url = this.buildUrl(path, options.query);
48
+ const token = options.anonymous ? null : await this.resolveToken(options.authOptional ?? false);
49
+ const headers = {
50
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
51
+ Accept: "application/json",
52
+ "User-Agent": USER_AGENT,
53
+ ...options.headers,
54
+ };
55
+ // FormData passes through untouched, and deliberately without a
56
+ // Content-Type: only fetch can write the multipart boundary, and setting the
57
+ // header by hand produces a body the server cannot parse. This is the only
58
+ // way to send a binary file, which an endpoint that takes uploads cannot accept inline.
59
+ let payload;
60
+ if (options.body instanceof FormData) {
61
+ payload = options.body;
62
+ }
63
+ else if (options.body instanceof Uint8Array) {
64
+ // A raw body (a tar archive, a media file): the caller names its
65
+ // Content-Type in `headers`, and nothing is re-encoded.
66
+ payload = new Uint8Array(options.body);
67
+ }
68
+ else if (options.body !== undefined) {
69
+ payload = JSON.stringify(options.body);
70
+ headers["Content-Type"] = "application/json";
71
+ }
72
+ let attempt = 0;
73
+ // `attempt` counts retries, not tries: 0 is the first call.
74
+ for (;;) {
75
+ const response = await this.send(url, { method, headers, body: payload });
76
+ this.surfaceNotices(response);
77
+ if (response.ok) {
78
+ return options.binary ? this.readBytes(response) : this.readSuccess(response);
79
+ }
80
+ const retryAfterMs = retryAfterFrom(response.headers);
81
+ if (this.shouldRetry(method, response.status, attempt, hasIdempotencyKey(headers))) {
82
+ await this.options.sleep(this.backoffMs(attempt, retryAfterMs));
83
+ attempt += 1;
84
+ continue;
85
+ }
86
+ throw await toApiRequestError(response, retryAfterMs);
87
+ }
88
+ }
89
+ /**
90
+ * When auth is optional, a missing credential is not a failure: the request
91
+ * just goes out without an `Authorization` header. Any other failure while
92
+ * resolving the credential (a broken keychain, a refresh error) still isn't
93
+ * this endpoint's problem to surface, so it degrades the same way.
94
+ */
95
+ async resolveToken(authOptional) {
96
+ if (!authOptional)
97
+ return this.options.getToken();
98
+ try {
99
+ return await this.options.getToken();
100
+ }
101
+ catch {
102
+ return null;
103
+ }
104
+ }
105
+ /**
106
+ * A retry is only safe when repeating the request cannot change the outcome.
107
+ *
108
+ * `429` is safe for every method: a rate-limited request was rejected at the
109
+ * gate, so the server never ran it.
110
+ *
111
+ * `408` and `5xx` are different. A `502` or `504` usually means an
112
+ * intermediary gave up *waiting* for the origin, not that the origin did
113
+ * nothing — the write may well have landed. Repeating a `GET`, `PUT` or
114
+ * `DELETE` in that situation is harmless by definition (RFC 9110 §9.2.2),
115
+ * but repeating a `POST` or `PATCH` can apply the same change twice. So those
116
+ * two verbs surface the failure instead, and the caller decides, unless the
117
+ * request carries an `Idempotency-Key`, which makes the repeat safe.
118
+ */
119
+ shouldRetry(method, status, attempt, keyed) {
120
+ if (!this.options.retry)
121
+ return false;
122
+ if (attempt >= this.options.maxRetries)
123
+ return false;
124
+ if (!RETRYABLE_STATUSES.has(status))
125
+ return false;
126
+ if (status === 429)
127
+ return true;
128
+ // A request that carries an Idempotency-Key is safe to repeat by
129
+ // construction: the server answers a repeat with the first attempt's result.
130
+ return keyed || IDEMPOTENT_METHODS.has(method.toUpperCase());
131
+ }
132
+ /**
133
+ * Full jitter: `random() * min(cap, base * 2^attempt)`. When the server told us
134
+ * how long to wait we honour that instead, because a coordinated backoff beats
135
+ * a clever one.
136
+ */
137
+ backoffMs(attempt, retryAfterMs) {
138
+ if (retryAfterMs !== null)
139
+ return Math.min(retryAfterMs, MAX_RETRY_AFTER_MS);
140
+ const ceiling = Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * 2 ** attempt);
141
+ return Math.round(this.options.random() * ceiling);
142
+ }
143
+ async send(url, init) {
144
+ const controller = new AbortController();
145
+ const timer = setTimeout(() => controller.abort(), this.options.timeoutMs);
146
+ try {
147
+ return await this.options.fetchImpl(url, { ...init, signal: controller.signal });
148
+ }
149
+ catch (error) {
150
+ if (controller.signal.aborted) {
151
+ throw new NetworkError(`The request to ${url} timed out after ${this.options.timeoutMs} ms.`, error);
152
+ }
153
+ throw new NetworkError(`Could not reach ${url}: ${error instanceof Error ? error.message : String(error)}`, error);
154
+ }
155
+ finally {
156
+ clearTimeout(timer);
157
+ }
158
+ }
159
+ async readBytes(response) {
160
+ const bytes = new Uint8Array(await response.arrayBuffer());
161
+ return {
162
+ status: response.status,
163
+ headers: response.headers,
164
+ body: bytes,
165
+ requestId: response.headers.get("x-request-id"),
166
+ };
167
+ }
168
+ async readSuccess(response) {
169
+ const requestId = response.headers.get("x-request-id");
170
+ if (response.status === 204) {
171
+ return { status: response.status, headers: response.headers, body: null, requestId };
172
+ }
173
+ const text = await response.text();
174
+ if (!text) {
175
+ return { status: response.status, headers: response.headers, body: null, requestId };
176
+ }
177
+ try {
178
+ return {
179
+ status: response.status,
180
+ headers: response.headers,
181
+ body: JSON.parse(text),
182
+ requestId,
183
+ };
184
+ }
185
+ catch {
186
+ throw new NetworkError(`The API returned a ${response.status} that was not JSON. First 200 characters: ${text.slice(0, 200)}`);
187
+ }
188
+ }
189
+ surfaceNotices(response) {
190
+ if (this.noticeSent || !this.options.onNotice)
191
+ return;
192
+ const deprecation = response.headers.get("deprecation");
193
+ const sunset = response.headers.get("sunset");
194
+ if (!deprecation)
195
+ return;
196
+ this.noticeSent = true;
197
+ this.options.onNotice(`This CLI version is deprecated by the API${sunset ? ` and stops working on ${sunset}` : ""}. Run 'npm install -g @atelier201/cli' to update.`);
198
+ }
199
+ buildUrl(path, query) {
200
+ const suffix = path.startsWith("/") ? path : `/${path}`;
201
+ const url = new URL(`${this.options.baseUrl}${suffix}`);
202
+ for (const [key, value] of Object.entries(query ?? {})) {
203
+ if (value === undefined || value === null || value === "")
204
+ continue;
205
+ url.searchParams.set(key, String(value));
206
+ }
207
+ return url.toString();
208
+ }
209
+ }
210
+ function hasIdempotencyKey(headers) {
211
+ return Object.entries(headers).some(([name, value]) => name.toLowerCase() === "idempotency-key" && value !== "");
212
+ }
213
+ /** `Retry-After` is either a delay in seconds or an HTTP date. Both are accepted. */
214
+ export function retryAfterFrom(headers) {
215
+ const raw = headers.get("retry-after");
216
+ if (!raw)
217
+ return null;
218
+ const seconds = Number(raw.trim());
219
+ if (Number.isFinite(seconds) && seconds >= 0)
220
+ return Math.round(seconds * 1000);
221
+ const date = Date.parse(raw);
222
+ if (Number.isNaN(date))
223
+ return null;
224
+ return Math.max(0, date - Date.now());
225
+ }
226
+ /** Reads the failure body and, when it is not our envelope, builds an equivalent one. */
227
+ export async function toApiRequestError(response, retryAfterMs) {
228
+ const requestId = response.headers.get("x-request-id");
229
+ let envelope = null;
230
+ let text = "";
231
+ try {
232
+ text = await response.text();
233
+ }
234
+ catch {
235
+ text = "";
236
+ }
237
+ if (text) {
238
+ try {
239
+ const parsed = JSON.parse(text);
240
+ if (isEnvelope(parsed))
241
+ envelope = parsed;
242
+ }
243
+ catch {
244
+ // Not JSON — handled below.
245
+ }
246
+ }
247
+ if (!envelope) {
248
+ envelope = {
249
+ error: {
250
+ type: response.status >= 500 ? "api_error" : "invalid_request_error",
251
+ code: response.status >= 500 ? "internal_error" : "invalid_request",
252
+ message: text.slice(0, 500) ||
253
+ `The API returned HTTP ${response.status} with no body.`,
254
+ docs_url: "https://atelier201.com/docs/api/errors",
255
+ },
256
+ request_id: requestId,
257
+ };
258
+ }
259
+ else if (!envelope.request_id && requestId) {
260
+ envelope.request_id = requestId;
261
+ }
262
+ return new ApiRequestError(response.status, envelope, {
263
+ retryAfterSeconds: retryAfterMs === null ? undefined : Math.ceil(retryAfterMs / 1000),
264
+ });
265
+ }
266
+ function isEnvelope(value) {
267
+ if (typeof value !== "object" || value === null)
268
+ return false;
269
+ const error = value.error;
270
+ return (typeof error === "object" &&
271
+ error !== null &&
272
+ typeof error.code === "string" &&
273
+ typeof error.message === "string");
274
+ }
275
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,eAAe,EAAE,YAAY,EAAyB,MAAM,aAAa,CAAC;AACnF,OAAO,EAAE,UAAU,EAA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BAAiB,EAAE,YAAY,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;KACtF,CAAC,CAAC;AACL,CAAC;AAED,SAAS,UAAU,CAAC,KAAc;IAChC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9D,MAAM,KAAK,GAAI,KAA0B,CAAC,KAAK,CAAC;IAChD,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC9B,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,CAClC,CAAC;AACJ,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,184 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `atelier201` — the CLI.
4
+ *
5
+ * A thin, typed shell over `https://api.atelier201.com/v1`. It runs on the
6
+ * user's machine or in their CI, holds no secret of ours, and never executes
7
+ * inside our infrastructure.
8
+ *
9
+ * WHY THE CLI IS PART OF THE PLATFORM AND NOT A SIDE PROJECT. It is the fastest
10
+ * way for a person to try the API, the easiest thing to put in a CI job, and —
11
+ * increasingly — the surface an AI agent reaches for before it reads a spec.
12
+ * Its `--help` text is therefore product documentation, not developer notes.
13
+ */
14
+ import { Command } from "commander";
15
+ import { registerApi } from "./commands/api.js";
16
+ import { registerAuth } from "./commands/auth.js";
17
+ import { registerCompletion } from "./commands/completion.js";
18
+ import { registerBuilds } from "./commands/builds.js";
19
+ import { registerChangesets } from "./commands/changesets.js";
20
+ import { registerContent } from "./commands/content.js";
21
+ import { registerDomains } from "./commands/domains.js";
22
+ import { registerFiles } from "./commands/files.js";
23
+ import { registerWorkspace } from "./commands/workspace.js";
24
+ import { registerHistory } from "./commands/history.js";
25
+ import { registerMedia } from "./commands/media.js";
26
+ import { registerPages } from "./commands/pages.js";
27
+ import { registerPreviews } from "./commands/previews.js";
28
+ import { registerPublish } from "./commands/publish.js";
29
+ import { registerSite } from "./commands/site.js";
30
+ import { registerSites } from "./commands/sites.js";
31
+ import { registerSkills } from "./commands/skills.js";
32
+ import { registerDoctor } from "./commands/doctor.js";
33
+ import { registerFeedback } from "./commands/feedback.js";
34
+ import { registerHelpJson } from "./commands/help-json.js";
35
+ import { registerMcp } from "./commands/mcp.js";
36
+ import { registerRead } from "./commands/read.js";
37
+ import { toErrorReport, CliError } from "./errors.js";
38
+ import { createPrinter, resolveOutput } from "./output.js";
39
+ import { HAS_OWN_ACTION, OWNS_GLOBAL_OUTPUT_FLAG } from "./run.js";
40
+ import { EXIT } from "./exit-codes.js";
41
+ import { VERSION } from "./version.js";
42
+ export function buildProgram() {
43
+ const program = new Command();
44
+ program
45
+ .name("atelier201")
46
+ .description("Atelier201 from a terminal, a CI job, or an AI agent. Output is JSON automatically when stdout is not a terminal.")
47
+ .version(VERSION, "-v, --version", "Print the CLI version")
48
+ .option("--output <mode>", "json | table | ndjson (json when stdout is not a terminal)")
49
+ .option("--json", "Shorthand for --output json")
50
+ .option("--profile <name>", "Named credential profile (or ATELIER201_PROFILE)")
51
+ .option("--no-retry", "Do not retry on 429 or 5xx")
52
+ .option("--timeout <seconds>", "Give up on a single request after this long (default 60)")
53
+ .showSuggestionAfterError(true)
54
+ .enablePositionalOptions()
55
+ // Commander's own help command would shadow ours, which carries --json.
56
+ .helpCommand(false);
57
+ registerAuth(program);
58
+ registerRead(program);
59
+ registerSites(program);
60
+ registerSite(program);
61
+ registerFiles(program);
62
+ registerWorkspace(program);
63
+ registerHistory(program);
64
+ registerChangesets(program);
65
+ registerBuilds(program);
66
+ registerPages(program);
67
+ registerPreviews(program);
68
+ registerPublish(program);
69
+ registerDomains(program);
70
+ registerContent(program);
71
+ registerMedia(program);
72
+ registerSkills(program);
73
+ registerApi(program);
74
+ registerMcp(program);
75
+ registerDoctor(program);
76
+ registerFeedback(program);
77
+ registerCompletion(program);
78
+ registerHelpJson(program);
79
+ // `atelier201 sites list --json` must work as well as `atelier201 --json sites list`.
80
+ // Nobody remembers which side of the subcommand a global flag belongs on, and an
81
+ // agent that guesses wrong should not get an "unknown option" error.
82
+ applyGlobalOptionsToLeaves(program);
83
+ summarizeLongDescriptions(program);
84
+ // Commander prints its own message before throwing; ours carries the same text
85
+ // inside the envelope, and two copies is one too many for a parser. Every
86
+ // parse failure is then routed through `main`, which exits 2 rather than
87
+ // commander's default 1.
88
+ for (const command of [program, ...allCommands(program)]) {
89
+ command.configureOutput({ outputError: () => { } });
90
+ command.exitOverride();
91
+ }
92
+ return program;
93
+ }
94
+ /** Commander uses exceptions for `--help` and `--version`; neither is a failure. */
95
+ const SUCCESSFUL_COMMANDER_CODES = new Set([
96
+ "commander.help",
97
+ "commander.helpDisplayed",
98
+ "commander.version",
99
+ ]);
100
+ /** Every command in the tree, depth first. */
101
+ function* allCommands(root) {
102
+ for (const child of root.commands) {
103
+ yield child;
104
+ yield* allCommands(child);
105
+ }
106
+ }
107
+ const GLOBAL_LEAF_OPTIONS = [
108
+ ["--output <mode>", "json | table | ndjson (json when stdout is not a terminal)"],
109
+ ["--json", "Shorthand for --output json"],
110
+ ["--profile <name>", "Named credential profile (or ATELIER201_PROFILE)"],
111
+ ["--no-retry", "Do not retry on 429 or 5xx"],
112
+ ["--timeout <seconds>", "Give up on a single request after this long (default 60)"],
113
+ ];
114
+ function applyGlobalOptionsToLeaves(root) {
115
+ OWNS_GLOBAL_OUTPUT_FLAG.add(root);
116
+ for (const command of allCommands(root)) {
117
+ if (command.commands.length && !HAS_OWN_ACTION.has(command))
118
+ continue;
119
+ const existing = new Set(command.options.map((option) => option.long));
120
+ for (const [flags, description] of GLOBAL_LEAF_OPTIONS) {
121
+ const long = flags.split(" ")[0];
122
+ if (existing.has(long))
123
+ continue;
124
+ command.option(flags, description);
125
+ // a command that writes a file may own `--output` as a path, so it is the
126
+ // one leaf that is deliberately left out of this set.
127
+ if (long === "--output")
128
+ OWNS_GLOBAL_OUTPUT_FLAG.add(command);
129
+ }
130
+ }
131
+ }
132
+ /**
133
+ * A command list reads one line per command. The full description, which says
134
+ * what a command costs and whether it changes what visitors see, stays on the
135
+ * command's own `--help`; the list shows its first sentence.
136
+ */
137
+ function summarizeLongDescriptions(root) {
138
+ for (const command of allCommands(root)) {
139
+ const description = command.description();
140
+ if (description.length <= 90 || command.summary())
141
+ continue;
142
+ const firstSentence = description.split(/(?<=[.:])\s/)[0] ?? description;
143
+ command.summary(firstSentence.replace(/[.:]$/, ""));
144
+ }
145
+ }
146
+ export async function main(argv = process.argv) {
147
+ const program = buildProgram();
148
+ try {
149
+ await program.parseAsync(argv);
150
+ }
151
+ catch (error) {
152
+ // Commander's own errors carry a `code` starting with `commander.`.
153
+ const commanderCode = error.code;
154
+ if (typeof commanderCode === "string" && SUCCESSFUL_COMMANDER_CODES.has(commanderCode)) {
155
+ process.exitCode = EXIT.OK;
156
+ return;
157
+ }
158
+ if (typeof commanderCode === "string" && commanderCode.startsWith("commander.")) {
159
+ const message = error.message?.trim().replace(/^error:\s*/i, "");
160
+ const wrapped = new CliError(message || "Invalid command.", {
161
+ exitCode: EXIT.USAGE,
162
+ code: "invalid_request",
163
+ hint: "Run 'atelier201 help --json' for the full command surface.",
164
+ });
165
+ emit(wrapped);
166
+ return;
167
+ }
168
+ emit(error);
169
+ }
170
+ }
171
+ function emit(error) {
172
+ const { envelope, exitCode } = toErrorReport(error);
173
+ // The same printer the commands use, so a parse failure is formatted by the
174
+ // same rule as every other failure rather than by a second, divergent one.
175
+ const printer = createPrinter(resolveOutput({}, { env: process.env, stdoutIsTTY: Boolean(process.stdout.isTTY) }));
176
+ printer.error(envelope);
177
+ process.exitCode = exitCode;
178
+ }
179
+ const invokedDirectly = process.argv[1] !== undefined &&
180
+ /(^|[\\/])(atelier201|index\.(js|ts))$/.test(process.argv[1]);
181
+ if (invokedDirectly) {
182
+ void main();
183
+ }
184
+ //# sourceMappingURL=index.js.map
@@ -0,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AAK,CAAC,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,IAAI,CAAC,KAAc;IAC1B,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;IACpD,4EAA4E;IAC5E,2EAA2E;IAC3E,MAAM,OAAO,GAAG,aAAa,CAC3B,aAAa,CAAC,EAAE,EAAE,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,WAAW,EAAE,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CACpF,CAAC;IACF,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACxB,OAAO,CAAC,QAAQ,GAAG,QAAQ,CAAC;AAC9B,CAAC;AAED,MAAM,eAAe,GACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS;IAC7B,uCAAuC,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAEhE,IAAI,eAAe,EAAE,CAAC;IACpB,KAAK,IAAI,EAAE,CAAC;AACd,CAAC"}
@@ -0,0 +1,185 @@
1
+ /**
2
+ * OS keychain adapters.
3
+ *
4
+ * A credential in the system keychain is protected by the OS login session; the
5
+ * fallback config file is protected only by its 0600 mode. We therefore try the
6
+ * keychain first on every platform and fall back silently when the helper is
7
+ * missing (headless Linux, minimal containers), because failing to log in
8
+ * because `secret-tool` is absent would be absurd.
9
+ *
10
+ * Honest caveat: on macOS and Linux the secret is passed to the helper as a
11
+ * process argument, so it is briefly visible to `ps` for other processes
12
+ * running as the same user. That is the same exposure `security` itself
13
+ * documents, and it is strictly better than a plaintext file at rest.
14
+ */
15
+ import { execFile } from "node:child_process";
16
+ import { promises as fs } from "node:fs";
17
+ import os from "node:os";
18
+ import path from "node:path";
19
+ const SERVICE = "atelier201";
20
+ function run(command, args, stdin) {
21
+ return new Promise((resolve) => {
22
+ const child = execFile(command, args, { maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
23
+ const code = error && typeof error.code === "number"
24
+ ? error.code
25
+ : error
26
+ ? 1
27
+ : 0;
28
+ resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
29
+ });
30
+ if (stdin !== undefined) {
31
+ child.stdin?.end(stdin);
32
+ }
33
+ });
34
+ }
35
+ async function commandExists(command) {
36
+ const probe = process.platform === "win32" ? "where" : "which";
37
+ const result = await run(probe, [command]);
38
+ return result.code === 0 && result.stdout.trim().length > 0;
39
+ }
40
+ // ── macOS ─────────────────────────────────────────────────────────────────────
41
+ const macKeychain = {
42
+ name: "macos-keychain",
43
+ async get(account) {
44
+ const result = await run("security", [
45
+ "find-generic-password",
46
+ "-a",
47
+ account,
48
+ "-s",
49
+ SERVICE,
50
+ "-w",
51
+ ]);
52
+ if (result.code !== 0)
53
+ return null;
54
+ const value = result.stdout.replace(/\n$/, "");
55
+ return value.length ? value : null;
56
+ },
57
+ async set(account, secret) {
58
+ // -U updates in place when the item already exists, instead of erroring.
59
+ const result = await run("security", [
60
+ "add-generic-password",
61
+ "-a",
62
+ account,
63
+ "-s",
64
+ SERVICE,
65
+ "-w",
66
+ secret,
67
+ "-U",
68
+ ]);
69
+ if (result.code !== 0)
70
+ throw new Error(result.stderr.trim() || "security add failed");
71
+ },
72
+ async remove(account) {
73
+ await run("security", ["delete-generic-password", "-a", account, "-s", SERVICE]);
74
+ },
75
+ };
76
+ // ── Linux (libsecret) ─────────────────────────────────────────────────────────
77
+ const secretToolKeychain = {
78
+ name: "libsecret",
79
+ async get(account) {
80
+ const result = await run("secret-tool", ["lookup", "service", SERVICE, "account", account]);
81
+ if (result.code !== 0)
82
+ return null;
83
+ const value = result.stdout.replace(/\n$/, "");
84
+ return value.length ? value : null;
85
+ },
86
+ async set(account, secret) {
87
+ // `secret-tool store` reads the secret from stdin, so it never reaches argv.
88
+ const result = await run("secret-tool", ["store", "--label", `Atelier201 (${account})`, "service", SERVICE, "account", account], secret);
89
+ if (result.code !== 0)
90
+ throw new Error(result.stderr.trim() || "secret-tool store failed");
91
+ },
92
+ async remove(account) {
93
+ await run("secret-tool", ["clear", "service", SERVICE, "account", account]);
94
+ },
95
+ };
96
+ // ── Windows (DPAPI) ───────────────────────────────────────────────────────────
97
+ /**
98
+ * `cmdkey` can *store* a generic credential but gives no way to read the secret
99
+ * back, so it is unusable for us. DPAPI through PowerShell is the equivalent
100
+ * facility: the ciphertext is bound to the current Windows user account and is
101
+ * meaningless to anyone else on the machine.
102
+ */
103
+ function windowsCredentialPath(account) {
104
+ const base = process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming");
105
+ return path.join(base, "atelier201", `${sanitize(account)}.cred`);
106
+ }
107
+ function sanitize(account) {
108
+ return account.replace(/[^a-zA-Z0-9._-]/g, "_");
109
+ }
110
+ const dpapiKeychain = {
111
+ name: "windows-dpapi",
112
+ async get(account) {
113
+ const file = windowsCredentialPath(account);
114
+ let ciphertext;
115
+ try {
116
+ ciphertext = await fs.readFile(file, "utf8");
117
+ }
118
+ catch {
119
+ return null;
120
+ }
121
+ const script = `$s = ConvertTo-SecureString -String $env:ATELIER201_CIPHERTEXT; ` +
122
+ `[Runtime.InteropServices.Marshal]::PtrToStringAuto(` +
123
+ `[Runtime.InteropServices.Marshal]::SecureStringToBSTR($s))`;
124
+ const result = await runPowerShell(script, { ATELIER201_CIPHERTEXT: ciphertext.trim() });
125
+ if (result.code !== 0)
126
+ return null;
127
+ const value = result.stdout.replace(/\r?\n$/, "");
128
+ return value.length ? value : null;
129
+ },
130
+ async set(account, secret) {
131
+ const script = `ConvertTo-SecureString -String $env:ATELIER201_SECRET -AsPlainText -Force | ConvertFrom-SecureString`;
132
+ const result = await runPowerShell(script, { ATELIER201_SECRET: secret });
133
+ if (result.code !== 0)
134
+ throw new Error(result.stderr.trim() || "DPAPI encryption failed");
135
+ const file = windowsCredentialPath(account);
136
+ await fs.mkdir(path.dirname(file), { recursive: true });
137
+ await fs.writeFile(file, result.stdout.trim(), { mode: 0o600 });
138
+ },
139
+ async remove(account) {
140
+ await fs.rm(windowsCredentialPath(account), { force: true });
141
+ },
142
+ };
143
+ function runPowerShell(script, env) {
144
+ return new Promise((resolve) => {
145
+ execFile("powershell", ["-NoProfile", "-NonInteractive", "-Command", script], { env: { ...process.env, ...env }, maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
146
+ resolve({
147
+ code: error ? 1 : 0,
148
+ stdout: String(stdout ?? ""),
149
+ stderr: String(stderr ?? ""),
150
+ });
151
+ });
152
+ });
153
+ }
154
+ // ── Selection ─────────────────────────────────────────────────────────────────
155
+ let cached;
156
+ /**
157
+ * Returns the keychain for this machine, or `null` when there is none (or when
158
+ * `ATELIER201_NO_KEYCHAIN` opts out — useful in CI and in tests).
159
+ */
160
+ export async function detectKeychain() {
161
+ if (cached !== undefined)
162
+ return cached;
163
+ if (process.env.ATELIER201_NO_KEYCHAIN !== undefined) {
164
+ cached = null;
165
+ return cached;
166
+ }
167
+ if (process.platform === "darwin" && (await commandExists("security"))) {
168
+ cached = macKeychain;
169
+ }
170
+ else if (process.platform === "win32") {
171
+ cached = dpapiKeychain;
172
+ }
173
+ else if (await commandExists("secret-tool")) {
174
+ cached = secretToolKeychain;
175
+ }
176
+ else {
177
+ cached = null;
178
+ }
179
+ return cached;
180
+ }
181
+ /** Test seam. */
182
+ export function __setKeychainForTesting(keychain) {
183
+ cached = keychain;
184
+ }
185
+ //# sourceMappingURL=keychain.js.map