saturndocs 0.1.2 → 0.3.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.
Files changed (63) hide show
  1. package/dist/auth-OIEL34E4.js +16 -0
  2. package/dist/{chunk-3V753MRI.js → chunk-32ATWMIS.js} +3 -3
  3. package/dist/{chunk-U7PKMSB3.js → chunk-3EW6ZPL6.js} +5 -5
  4. package/dist/{chunk-GYRVGWDM.js → chunk-3KCCCMQY.js} +408 -36
  5. package/dist/{chunk-SABK3R2P.js → chunk-3X2NBWZN.js} +245 -161
  6. package/dist/chunk-5ZYUBLEH.js +5154 -0
  7. package/dist/{chunk-N7QPZMLP.js → chunk-6EKGBIUR.js} +2 -2
  8. package/dist/{chunk-CMNX5DLQ.js → chunk-BOWRQKXR.js} +12 -6
  9. package/dist/chunk-E3G56DR2.js +949 -0
  10. package/dist/chunk-FUZE54DG.js +905 -0
  11. package/dist/chunk-HBSJ4Z4S.js +53 -0
  12. package/dist/{chunk-5KX4ZK5E.js → chunk-IJOYWJVM.js} +13 -7
  13. package/dist/chunk-IWIVHHZI.js +426 -0
  14. package/dist/{chunk-XO4CUC7V.js → chunk-PU37LVIF.js} +3 -3
  15. package/dist/{chunk-STCCGFKC.js → chunk-RKM7YWPD.js} +25 -6
  16. package/dist/{chunk-KGJESHJC.js → chunk-T3MCJYSF.js} +1 -1
  17. package/dist/chunk-TEYHAN2L.js +90 -0
  18. package/dist/chunk-VDGVERLX.js +87 -0
  19. package/dist/{chunk-S45UWCML.js → chunk-W3FZTCKV.js} +15 -13
  20. package/dist/chunk-WMS6FUKK.js +414 -0
  21. package/dist/chunk-WXLJZ7RD.js +115 -0
  22. package/dist/chunk-YGVC4N4V.js +29 -0
  23. package/dist/chunk-YPWPLIEZ.js +86 -0
  24. package/dist/cli.js +6 -6
  25. package/dist/coverage-SRIA65FT.js +15 -0
  26. package/dist/dist-LJSALT4X.js +150 -0
  27. package/dist/index.d.ts +99 -34
  28. package/dist/index.js +142 -49
  29. package/dist/{init-7T5TEPBH.js → init-Y3GDNDWW.js} +5 -3
  30. package/dist/lint-XM26WIGE.js +13 -0
  31. package/dist/login-HIXLPRUI.js +22 -0
  32. package/dist/{manage-MKH27U3B.js → manage-3HEBB3EQ.js} +6 -2
  33. package/dist/nav-K43WZJ4J.js +14 -0
  34. package/dist/openapiCheck-CL2AH3YC.js +105 -0
  35. package/dist/pages-4VWB7Z4S.js +16 -0
  36. package/dist/{read-DMSJUEDA.js → read-DYGYUOFK.js} +5 -4
  37. package/dist/{read-ZEVUZNNB.js → read-RKT6HUZ7.js} +41 -7
  38. package/dist/requests-CZYE6GI3.js +13 -0
  39. package/dist/{schema-XJUEZSIW.js → schema-QMJMGD5P.js} +3 -3
  40. package/dist/{sites-I4WI2MPG.js → sites-JKS25SEM.js} +5 -4
  41. package/dist/{status-7R3NOI5H.js → status-FM2ALQUJ.js} +4 -4
  42. package/dist/{suggestions-4WFQ3APX.js → suggestions-Z6XIHMFN.js} +13 -7
  43. package/dist/unavailable-DVPNUO3J.js +40 -0
  44. package/dist/validate-X42T4TJ6.js +12 -0
  45. package/package.json +14 -7
  46. package/dist/auth-FRCFGNYT.js +0 -14
  47. package/dist/brokenLinks-TTOBP4P7.js +0 -48
  48. package/dist/build-F5PWGP57.js +0 -39
  49. package/dist/chunk-3P2OFTXR.js +0 -71
  50. package/dist/chunk-I6U4V7B4.js +0 -1552
  51. package/dist/chunk-OEAEX5YW.js +0 -51
  52. package/dist/chunk-OZWTXMO3.js +0 -584
  53. package/dist/chunk-QLFODLVN.js +0 -46
  54. package/dist/chunk-R3X2DPFF.js +0 -568
  55. package/dist/chunk-TKISMN3P.js +0 -39
  56. package/dist/chunk-VNYDYHXM.js +0 -22
  57. package/dist/chunk-VXEUNRVA.js +0 -26
  58. package/dist/deploy-QU7DCKWU.js +0 -11
  59. package/dist/dev-VDSDCBO2.js +0 -43
  60. package/dist/openapiCheck-KGBQJTIQ.js +0 -66
  61. package/dist/pages-HIPXRLSY.js +0 -15
  62. package/dist/requests-H5MIGBIS.js +0 -13
  63. package/dist/validate-VXL4PL42.js +0 -30
@@ -0,0 +1,905 @@
1
+ import {
2
+ interruptSignal
3
+ } from "./chunk-T3MCJYSF.js";
4
+ import {
5
+ CliError,
6
+ createClient,
7
+ interrupted,
8
+ invalidInput2 as invalidInput,
9
+ isManagementError,
10
+ parseOrigin
11
+ } from "./chunk-3KCCCMQY.js";
12
+
13
+ // src/lib/credentials.ts
14
+ import { execFile } from "child_process";
15
+ import { randomBytes } from "crypto";
16
+ import { promises as fs, constants as fsConstants } from "fs";
17
+ import { homedir, hostname, userInfo } from "os";
18
+ import { dirname, join, parse as parsePath } from "path";
19
+ import { deflateRawSync, inflateRawSync } from "zlib";
20
+ import { z } from "zod";
21
+ var KEYCHAIN_SERVICE = "saturndocs-cli";
22
+ var STORE_VARIABLE = "SATURNDOCS_CREDENTIAL_STORE";
23
+ var CONFIG_DIR_VARIABLE = "SATURNDOCS_CONFIG_DIR";
24
+ var KEYCHAIN_LOCK_DIR_VARIABLE = "SATURNDOCS_KEYCHAIN_LOCK_DIR";
25
+ var SavedGrant = z.object({
26
+ site_id: z.string().min(1),
27
+ scope: z.array(z.string().min(1)),
28
+ access_token: z.string().min(1),
29
+ access_expires_at: z.string().min(1),
30
+ refresh_token: z.string().min(1),
31
+ /** Set, durably, before a refresh token is sent; cleared when the answer is known. */
32
+ rotating_since: z.string().nullable()
33
+ });
34
+ var PendingLogin = z.object({
35
+ device_code: z.string().min(1),
36
+ user_code: z.string().min(1),
37
+ verification_uri: z.string().min(1),
38
+ verification_uri_complete: z.string().min(1),
39
+ interval: z.number().int().positive(),
40
+ expires_at: z.string().min(1),
41
+ site: z.string().nullable(),
42
+ new_site: z.string().nullable(),
43
+ scope: z.array(z.string()).nullable()
44
+ });
45
+ var CredentialRecord = z.object({
46
+ version: z.literal(1),
47
+ origin: z.string().min(1),
48
+ /** Higher wins when the keychain and the file disagree, so a stale copy can never be read over a newer one. */
49
+ generation: z.number().int().nonnegative(),
50
+ default_site: z.string().nullable(),
51
+ grants: z.record(z.string(), SavedGrant),
52
+ pending: PendingLogin.nullable()
53
+ });
54
+ var CredentialFile = z.object({ version: z.literal(1), logins: z.record(z.string(), CredentialRecord) });
55
+ var MAX_FILE_BYTES = 1024 * 1024;
56
+ var MAX_SECURITY_COMMAND_BYTES = 3800;
57
+ function storeSetting(env, name) {
58
+ const value = env[name] ?? process.env[name];
59
+ return value === void 0 || value === "" ? void 0 : value;
60
+ }
61
+ function emptyRecord(origin) {
62
+ return { version: 1, origin, generation: 0, default_site: null, grants: {}, pending: null };
63
+ }
64
+ function isEmptyRecord(record) {
65
+ return Object.keys(record.grants).length === 0 && record.pending === null;
66
+ }
67
+ var StoreUnavailable = class extends Error {
68
+ constructor(message) {
69
+ super(message);
70
+ this.name = "StoreUnavailable";
71
+ }
72
+ };
73
+ var RUN_TIMEOUT_MS = 1e4;
74
+ var defaultRunner = (file, args, input) => new Promise((resolve) => {
75
+ try {
76
+ const child = execFile(file, [...args], { timeout: RUN_TIMEOUT_MS, maxBuffer: 1024 * 1024, windowsHide: true }, (error, stdout, stderr) => {
77
+ const failure = error;
78
+ resolve({
79
+ code: failure === null ? 0 : typeof failure.code === "number" ? failure.code : null,
80
+ stdout: String(stdout),
81
+ stderr: String(stderr),
82
+ timedOut: failure?.killed === true,
83
+ missing: failure?.code === "ENOENT"
84
+ });
85
+ });
86
+ child.stdin?.on("error", () => void 0);
87
+ child.stdin?.end(input ?? "");
88
+ } catch {
89
+ resolve({ code: null, stdout: "", stderr: "", timedOut: false, missing: false });
90
+ }
91
+ });
92
+ function encode(secret) {
93
+ return deflateRawSync(Buffer.from(secret, "utf8")).toString("base64");
94
+ }
95
+ function decode(stored) {
96
+ try {
97
+ return inflateRawSync(Buffer.from(stored.trim(), "base64")).toString("utf8");
98
+ } catch {
99
+ throw new StoreUnavailable("The keychain returned a saved login this CLI cannot read.");
100
+ }
101
+ }
102
+ async function attempt(run, file, args, input) {
103
+ try {
104
+ return await run(file, args, input);
105
+ } catch {
106
+ return { code: null, stdout: "", stderr: "", timedOut: false, missing: false };
107
+ }
108
+ }
109
+ function macosKeychain(run = defaultRunner) {
110
+ const security = "/usr/bin/security";
111
+ const store = {
112
+ kind: "keychain-macos",
113
+ label: "macOS Keychain",
114
+ async read(origin) {
115
+ const result = await attempt(run, security, ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-a", origin, "-w"]);
116
+ if (result.code === 0) return decode(result.stdout);
117
+ if (result.code === 44) return null;
118
+ throw new StoreUnavailable(result.timedOut ? "The macOS Keychain did not answer in time." : "The macOS Keychain did not answer.");
119
+ },
120
+ async write(origin, secret) {
121
+ const command = `add-generic-password -U -s ${KEYCHAIN_SERVICE} -a ${origin} -l SaturnDocs-CLI -w ${encode(secret)}
122
+ `;
123
+ if (Buffer.byteLength(command) > MAX_SECURITY_COMMAND_BYTES) {
124
+ throw invalidInput("Too many saved logins to keep in the macOS Keychain. Run saturndocs logout --site <site> for a site you no longer use.");
125
+ }
126
+ const result = await attempt(run, security, ["-i"], command);
127
+ if (result.code !== 0 || await store.read(origin) !== secret) throw new StoreUnavailable("The macOS Keychain did not save the login.");
128
+ },
129
+ async remove(origin) {
130
+ const result = await attempt(run, security, ["delete-generic-password", "-s", KEYCHAIN_SERVICE, "-a", origin]);
131
+ if (result.code !== 0 && result.code !== 44) throw new StoreUnavailable("The macOS Keychain did not delete the login.");
132
+ }
133
+ };
134
+ return store;
135
+ }
136
+ function configDir(env) {
137
+ const override = storeSetting(env, CONFIG_DIR_VARIABLE);
138
+ if (override !== void 0) return override;
139
+ const xdg = env.XDG_CONFIG_HOME;
140
+ return join(xdg !== void 0 && xdg !== "" ? xdg : join(homedir(), ".config"), "saturndocs");
141
+ }
142
+ function currentUid() {
143
+ return typeof process.getuid === "function" ? process.getuid() : null;
144
+ }
145
+ var OVERFLOW_UID = 65534;
146
+ async function assertTrustedAncestry(real, stat = (path) => fs.stat(path)) {
147
+ const uid = currentUid();
148
+ const root = parsePath(real).root;
149
+ for (let current = dirname(real); current !== root; current = dirname(current)) {
150
+ const info = await stat(current);
151
+ const owned = uid === null || info.uid === 0 || info.uid === uid || info.uid === OVERFLOW_UID;
152
+ const shared = (info.mode & 18) !== 0 && (info.mode & 512) === 0;
153
+ if (!owned || shared) throw invalidInput(`${current} can be changed by another account, so a saved login is not kept under it. Set ${CONFIG_DIR_VARIABLE} to a private directory.`);
154
+ }
155
+ }
156
+ async function privateDirectory(dir, create) {
157
+ if (create) await fs.mkdir(dir, { recursive: true, mode: 448 });
158
+ let info;
159
+ try {
160
+ info = await fs.lstat(dir);
161
+ } catch (error) {
162
+ if (!create && error.code === "ENOENT") return null;
163
+ throw error;
164
+ }
165
+ if (!info.isDirectory()) throw invalidInput(`${dir} is not a directory, so a saved login is not kept there.`);
166
+ const uid = currentUid();
167
+ if (uid !== null && info.uid !== uid) throw invalidInput(`${dir} belongs to another user, so a saved login is not kept there.`);
168
+ const real = await fs.realpath(dir);
169
+ await assertTrustedAncestry(real);
170
+ if ((info.mode & 63) !== 0) await fs.chmod(real, 448);
171
+ return real;
172
+ }
173
+ function windowsUnsupported() {
174
+ return invalidInput("Saved logins are not available on Windows yet. Set SATURNDOCS_MANAGEMENT_TOKEN to a management credential instead.");
175
+ }
176
+ function fileStore(env) {
177
+ const dir = configDir(env);
178
+ const path = join(dir, "credentials.json");
179
+ async function load() {
180
+ const real = await privateDirectory(dir, false);
181
+ if (real === null) return { version: 1, logins: {} };
182
+ const target = join(real, "credentials.json");
183
+ let handle;
184
+ try {
185
+ handle = await fs.open(target, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
186
+ } catch (error) {
187
+ const code = error.code;
188
+ if (code === "ENOENT") return { version: 1, logins: {} };
189
+ if (code === "ELOOP") throw invalidInput(`${path} is a symbolic link, so the saved login was not read.`);
190
+ throw error;
191
+ }
192
+ try {
193
+ const info = await handle.stat();
194
+ const uid = currentUid();
195
+ if (!info.isFile()) throw invalidInput(`${path} is not a regular file, so the saved login was not read.`);
196
+ if (uid !== null && info.uid !== uid) throw invalidInput(`${path} belongs to another user, so the saved login was not read.`);
197
+ if ((info.mode & 63) !== 0) throw invalidInput(`${path} can be read by other users, so the saved login was not used. Delete it, then run saturndocs login.`);
198
+ if (info.size > MAX_FILE_BYTES) throw invalidInput(`${path} is larger than a saved login can be, so it was not read.`);
199
+ let value;
200
+ try {
201
+ value = JSON.parse(await handle.readFile("utf8"));
202
+ } catch {
203
+ throw invalidInput(`${path} is not a saved login this CLI can read. Delete it, then run saturndocs login.`);
204
+ }
205
+ const parsed = CredentialFile.safeParse(value);
206
+ if (!parsed.success) throw invalidInput(`${path} is not a saved login this CLI can read. Delete it, then run saturndocs login.`);
207
+ return parsed.data;
208
+ } finally {
209
+ await handle.close();
210
+ }
211
+ }
212
+ async function save(file) {
213
+ const real = await privateDirectory(dir, true);
214
+ const target = join(real, "credentials.json");
215
+ if (Object.keys(file.logins).length === 0) {
216
+ await fs.rm(target, { force: true });
217
+ await syncDirectory(real);
218
+ return;
219
+ }
220
+ const serialized = `${JSON.stringify(file)}
221
+ `;
222
+ if (Buffer.byteLength(serialized) > MAX_FILE_BYTES) throw invalidInput("Too many saved logins to keep in one file. Run saturndocs logout --site <site> for a site you no longer use.");
223
+ const temporary = join(real, `.credentials.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
224
+ try {
225
+ const handle = await fs.open(temporary, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW, 384);
226
+ try {
227
+ await handle.writeFile(serialized, "utf8");
228
+ await handle.sync();
229
+ } finally {
230
+ await handle.close();
231
+ }
232
+ await fs.rename(temporary, target);
233
+ } catch (error) {
234
+ await fs.rm(temporary, { force: true });
235
+ throw error;
236
+ }
237
+ await syncDirectory(real);
238
+ }
239
+ return {
240
+ kind: "file",
241
+ path,
242
+ dir,
243
+ label: `file ${path}`,
244
+ async read(origin) {
245
+ const record = (await load()).logins[origin];
246
+ return record === void 0 ? null : JSON.stringify(record);
247
+ },
248
+ async write(origin, secret) {
249
+ const file = await load();
250
+ file.logins[origin] = CredentialRecord.parse(JSON.parse(secret));
251
+ await save(file);
252
+ },
253
+ async remove(origin) {
254
+ const file = await load();
255
+ if (!(origin in file.logins)) return;
256
+ delete file.logins[origin];
257
+ await save(file);
258
+ }
259
+ };
260
+ }
261
+ async function syncDirectory(dir) {
262
+ const handle = await fs.open(dir, fsConstants.O_RDONLY);
263
+ try {
264
+ await handle.sync();
265
+ } catch (error) {
266
+ const code = error.code;
267
+ if (code !== "EINVAL" && code !== "ENOTSUP" && code !== "EISDIR") throw error;
268
+ } finally {
269
+ await handle.close();
270
+ }
271
+ }
272
+ function credentialStores(options = {}) {
273
+ const env = options.env ?? process.env;
274
+ const platform = options.platform ?? process.platform;
275
+ const run = options.run ?? defaultRunner;
276
+ const setting = storeSetting(env, STORE_VARIABLE);
277
+ if (setting !== void 0 && setting !== "file" && setting !== "keychain") throw invalidInput(`${STORE_VARIABLE} must be file or keychain.`);
278
+ const forced = setting === void 0 ? null : setting;
279
+ const keychainLockDir2 = storeSetting(env, KEYCHAIN_LOCK_DIR_VARIABLE) ?? null;
280
+ if (platform === "win32") return { primary: null, file: null, forced, keychainLockDir: keychainLockDir2 };
281
+ const keychain = platform === "darwin" ? macosKeychain(run) : null;
282
+ if (forced === "keychain" && keychain === null) throw invalidInput(`${STORE_VARIABLE}=keychain has no keychain to use on this system.`);
283
+ return {
284
+ primary: forced === "file" ? null : keychain,
285
+ file: forced === "keychain" ? null : fileStore(env),
286
+ forced,
287
+ keychainLockDir: keychainLockDir2
288
+ };
289
+ }
290
+ function hasAnyStore(choice) {
291
+ return choice.primary !== null || choice.file !== null;
292
+ }
293
+ function parseRecord(text, store, origin) {
294
+ let value;
295
+ try {
296
+ value = JSON.parse(text);
297
+ } catch {
298
+ throw invalidInput(`The saved login in the ${store.label} is not readable. Run saturndocs logout --all, then saturndocs login.`);
299
+ }
300
+ const parsed = CredentialRecord.safeParse(value);
301
+ const consistent = parsed.success && parsed.data.origin === origin && Object.entries(parsed.data.grants).every(([site, grant]) => grant.site_id === site);
302
+ if (!parsed.success || !consistent) throw invalidInput(`The saved login in the ${store.label} is not one this CLI can read. Run saturndocs logout --all, then saturndocs login.`);
303
+ return parsed.data;
304
+ }
305
+ function unavailable(error) {
306
+ if (!(error instanceof StoreUnavailable)) return error;
307
+ return new CliError("service_unavailable", `${error.message} Set ${STORE_VARIABLE}=file to keep the login in a file only you can read.`, { cause: error });
308
+ }
309
+ async function selectStore(choice, origin) {
310
+ if (!hasAnyStore(choice)) return null;
311
+ let keychainAnswered = false;
312
+ if (choice.primary !== null) {
313
+ try {
314
+ const text = await choice.primary.read(origin);
315
+ keychainAnswered = true;
316
+ if (text !== null) return { store: choice.primary, record: parseRecord(text, choice.primary, origin) };
317
+ } catch (error) {
318
+ if (choice.forced === "keychain" || !(error instanceof StoreUnavailable)) throw unavailable(error);
319
+ }
320
+ }
321
+ if (choice.file !== null) {
322
+ const text = await choice.file.read(origin);
323
+ if (text !== null) return { store: choice.file, record: parseRecord(text, choice.file, origin) };
324
+ }
325
+ if (keychainAnswered && choice.primary !== null) return { store: choice.primary, record: null };
326
+ if (choice.file !== null) return { store: choice.file, record: null };
327
+ return null;
328
+ }
329
+ async function readStoredRecord(store, origin) {
330
+ const text = await store.read(origin);
331
+ return text === null ? null : parseRecord(text, store, origin);
332
+ }
333
+ async function loadRecord(choice, origin) {
334
+ const selection = await selectStore(choice, origin);
335
+ return selection === null || selection.record === null ? null : { store: selection.store, record: selection.record };
336
+ }
337
+ async function saveRecord(store, record) {
338
+ const next = { ...record, generation: record.generation + 1 };
339
+ try {
340
+ if (isEmptyRecord(next)) await store.remove(next.origin);
341
+ else await store.write(next.origin, JSON.stringify(next));
342
+ } catch (error) {
343
+ throw unavailable(error);
344
+ }
345
+ return store;
346
+ }
347
+ var LOCK_WAIT_MS = 45e3;
348
+ function alive(pid) {
349
+ try {
350
+ process.kill(pid, 0);
351
+ return true;
352
+ } catch (error) {
353
+ return error.code === "EPERM";
354
+ }
355
+ }
356
+ async function lockOwner(lockDir) {
357
+ try {
358
+ const owner = JSON.parse(await fs.readFile(join(lockDir, "owner"), "utf8"));
359
+ return { pid: typeof owner.pid === "number" ? owner.pid : null, host: typeof owner.host === "string" ? owner.host : null };
360
+ } catch {
361
+ return { pid: null, host: null };
362
+ }
363
+ }
364
+ async function acquireLock(dir, name, waitMs) {
365
+ const real = await privateDirectory(dir, true);
366
+ const lockDir = join(real, `${name}.lock`);
367
+ const nonce = randomBytes(12).toString("hex");
368
+ const deadline = Date.now() + waitMs;
369
+ for (; ; ) {
370
+ try {
371
+ await fs.mkdir(lockDir, { mode: 448 });
372
+ await fs.writeFile(join(lockDir, "owner"), JSON.stringify({ pid: process.pid, host: hostname(), nonce }), { mode: 384, flag: "wx" });
373
+ break;
374
+ } catch (error) {
375
+ if (error.code !== "EEXIST") throw error;
376
+ const owner = await lockOwner(lockDir);
377
+ const dead = owner.host === hostname() && owner.pid !== null && !alive(owner.pid);
378
+ const unknown = owner.pid === null;
379
+ if (dead || Date.now() >= deadline) {
380
+ const holder = owner.pid === null ? "an unknown process" : `process ${owner.pid} on ${owner.host ?? "an unknown host"}`;
381
+ throw new CliError("service_unavailable", dead ? `A saturndocs process (${holder}) stopped while it held the saved-login lock. If no saturndocs command is running, delete ${lockDir} and try again.` : `The saved-login lock is held by ${holder}. Try again when it finishes; if it is not running, delete ${lockDir}.`, { data: { lock: dead ? "abandoned" : unknown ? "unknown" : "busy", path: lockDir } });
382
+ }
383
+ await new Promise((resolve) => setTimeout(resolve, 100 + Math.floor(Math.random() * 150)));
384
+ }
385
+ }
386
+ return async () => {
387
+ try {
388
+ const owner = JSON.parse(await fs.readFile(join(lockDir, "owner"), "utf8"));
389
+ if (owner.nonce !== nonce) return;
390
+ await fs.rm(lockDir, { recursive: true, force: true });
391
+ } catch {
392
+ }
393
+ };
394
+ }
395
+ function keychainLockDir(choice) {
396
+ return choice.keychainLockDir ?? join(userInfo().homedir, ".config", "saturndocs");
397
+ }
398
+ function lockDirFor(store, choice) {
399
+ return store === choice.file && choice.file !== null ? choice.file.dir : keychainLockDir(choice);
400
+ }
401
+ async function withCredentialLock(choice, work, options = {}) {
402
+ if (!hasAnyStore(choice)) throw windowsUnsupported();
403
+ const waitMs = options.waitMs ?? LOCK_WAIT_MS;
404
+ const releases = [];
405
+ try {
406
+ if (choice.primary !== null) releases.push(await acquireLock(keychainLockDir(choice), "keychain", waitMs));
407
+ if (choice.file !== null) releases.push(await acquireLock(choice.file.dir, "credentials", waitMs));
408
+ return await work();
409
+ } finally {
410
+ for (const release of releases.reverse()) await release();
411
+ }
412
+ }
413
+ async function withPollLock(choice, store, key, work) {
414
+ let release;
415
+ try {
416
+ release = await acquireLock(lockDirFor(store, choice), `poll-${key}`, 0);
417
+ } catch (error) {
418
+ if (error instanceof CliError && error.data?.lock === "busy") {
419
+ throw new CliError("conflict", "Another saturndocs process is already waiting for this approval.");
420
+ }
421
+ throw error;
422
+ }
423
+ try {
424
+ return await work();
425
+ } finally {
426
+ await release();
427
+ }
428
+ }
429
+ async function allRecords(choice, origin) {
430
+ const loaded = [];
431
+ const unreadable = [];
432
+ for (const store of [choice.primary, choice.file]) {
433
+ if (store === null) continue;
434
+ try {
435
+ const text = await store.read(origin);
436
+ if (text !== null) loaded.push({ store, record: parseRecord(text, store, origin) });
437
+ } catch (error) {
438
+ unreadable.push({ store, reason: error instanceof Error ? error.message : String(error) });
439
+ }
440
+ }
441
+ return { loaded, unreadable };
442
+ }
443
+
444
+ // src/lib/device-flow.ts
445
+ import { z as z2 } from "zod";
446
+ var CLIENT_ID = "saturndocs-cli";
447
+ var GRANT_PERMISSIONS = ["read", "draft", "build", "publish"];
448
+ var DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
449
+ var REQUEST_DEADLINE_MS = 3e4;
450
+ var MAX_BODY_BYTES = 64 * 1024;
451
+ var MAX_POLL_INTERVAL_MS = 6e4;
452
+ var PRE_ROTATION_ERRORS = /* @__PURE__ */ new Set(["invalid_request", "invalid_scope", "unsupported_grant_type"]);
453
+ var SITE_SLUG = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
454
+ var OAUTH_ERRORS = /* @__PURE__ */ new Set([
455
+ "invalid_request",
456
+ "invalid_client",
457
+ "invalid_grant",
458
+ "invalid_scope",
459
+ "unauthorized_client",
460
+ "unsupported_grant_type",
461
+ "authorization_pending",
462
+ "slow_down",
463
+ "access_denied",
464
+ "expired_token",
465
+ "temporarily_unavailable",
466
+ "invalid_token"
467
+ ]);
468
+ var NOT_SENT_CAUSES = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT"]);
469
+ var DeviceStart = z2.object({
470
+ device_code: z2.string().min(1).max(512),
471
+ user_code: z2.string().min(1).max(64),
472
+ verification_uri: z2.string().url(),
473
+ verification_uri_complete: z2.string().url(),
474
+ expires_in: z2.number().int().positive().max(3600),
475
+ interval: z2.number().int().positive().max(60)
476
+ });
477
+ var TokenPair = z2.object({
478
+ access_token: z2.string().regex(/^sdga1\.[a-f0-9]{64}$/u),
479
+ token_type: z2.string().regex(/^bearer$/iu),
480
+ expires_in: z2.number().int().positive().max(86400),
481
+ refresh_token: z2.string().regex(/^sdgr1\.[a-f0-9]{64}$/u),
482
+ scope: z2.string().min(1).max(64),
483
+ site_id: z2.string().min(1).max(128)
484
+ });
485
+ var GrantStatus = z2.object({
486
+ kind: z2.literal("agent_grant"),
487
+ grant_id: z2.string(),
488
+ client_id: z2.string(),
489
+ site_id: z2.string(),
490
+ primary_host: z2.string().nullable(),
491
+ repo_connected: z2.boolean().optional(),
492
+ capabilities: z2.array(z2.string()),
493
+ access_expires_at: z2.string(),
494
+ idle_expires_at: z2.string(),
495
+ approval_expires_at: z2.string()
496
+ });
497
+ var RequestFailure = class extends CliError {
498
+ sent;
499
+ constructor(message, sent, code = "transport_failure") {
500
+ super(code, message, { mutation: sent ? "unknown" : "not_submitted" });
501
+ this.sent = sent;
502
+ }
503
+ };
504
+ function normalizeScope(value) {
505
+ if (value === void 0) return null;
506
+ const requested = value.split(/[\s,]+/u).filter((part) => part !== "");
507
+ if (requested.length === 0) throw invalidInput("--scope needs at least one of read, draft, build, publish.");
508
+ for (const permission of requested) {
509
+ if (!GRANT_PERMISSIONS.includes(permission)) throw invalidInput("--scope accepts only read, draft, build, and publish.");
510
+ }
511
+ return GRANT_PERMISSIONS.filter((permission) => requested.includes(permission));
512
+ }
513
+ function validateNewSite(value) {
514
+ if (!SITE_SLUG.test(value) || value === "local") {
515
+ throw invalidInput("--new-site takes a lowercase address of letters, digits, and hyphens, up to 63 characters, such as acme-docs.");
516
+ }
517
+ return value;
518
+ }
519
+ function parseRetryAfter(value, now) {
520
+ if (value === null || value.trim() === "") return null;
521
+ const trimmed = value.trim();
522
+ if (/^\d+$/u.test(trimmed)) return Number(trimmed);
523
+ const at = Date.parse(trimmed);
524
+ return Number.isNaN(at) ? null : Math.max(0, Math.ceil((at - now) / 1e3));
525
+ }
526
+ var defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
527
+ if (signal?.aborted) {
528
+ reject(interrupted());
529
+ return;
530
+ }
531
+ const timer = setTimeout(() => {
532
+ signal?.removeEventListener("abort", onAbort);
533
+ resolve();
534
+ }, ms);
535
+ const onAbort = () => {
536
+ clearTimeout(timer);
537
+ reject(interrupted());
538
+ };
539
+ signal?.addEventListener("abort", onAbort, { once: true });
540
+ });
541
+ async function readBody(response) {
542
+ const reader = response.body?.getReader();
543
+ if (reader === void 0) return null;
544
+ const chunks = [];
545
+ let total = 0;
546
+ for (; ; ) {
547
+ const { done, value } = await reader.read();
548
+ if (done) break;
549
+ total += value.byteLength;
550
+ if (total > MAX_BODY_BYTES) {
551
+ await reader.cancel().catch(() => void 0);
552
+ throw new RequestFailure("The sign-in service sent an answer larger than this client accepts.", true);
553
+ }
554
+ chunks.push(value);
555
+ }
556
+ const text = Buffer.concat(chunks).toString("utf8");
557
+ if (text === "") return null;
558
+ try {
559
+ return JSON.parse(text);
560
+ } catch {
561
+ return null;
562
+ }
563
+ }
564
+ function notSent(error) {
565
+ const cause = error?.cause;
566
+ return typeof cause?.code === "string" && NOT_SENT_CAUSES.has(cause.code);
567
+ }
568
+ async function send(ctx, path, init, deadlineAt = null) {
569
+ const now = ctx.now ?? Date.now;
570
+ const url = new URL(path, ctx.origin);
571
+ const headers = new Headers({ accept: "application/json" });
572
+ let body;
573
+ if (init.form !== void 0) {
574
+ const form = new URLSearchParams();
575
+ for (const [key, value] of Object.entries(init.form)) if (value !== void 0 && value !== "") form.set(key, value);
576
+ body = form.toString();
577
+ headers.set("content-type", "application/x-www-form-urlencoded");
578
+ }
579
+ if (init.bearer !== void 0) headers.set("authorization", `Bearer ${init.bearer}`);
580
+ const budget = Math.min(REQUEST_DEADLINE_MS, deadlineAt === null ? REQUEST_DEADLINE_MS : deadlineAt - now());
581
+ if (budget <= 0) throw new RequestFailure("The time allowed for this command ran out before the request was sent.", false);
582
+ const timeout = AbortSignal.timeout(budget);
583
+ const signal = ctx.signal === void 0 ? timeout : AbortSignal.any([timeout, ctx.signal]);
584
+ const fetchImpl = ctx.fetchImpl;
585
+ let response;
586
+ try {
587
+ response = await fetchImpl(url, { method: init.method, headers, body, redirect: "manual", signal });
588
+ } catch (error) {
589
+ if (ctx.signal?.aborted) throw new RequestFailure("Interrupted before the sign-in service answered.", true, "interrupted");
590
+ if (timeout.aborted) throw new RequestFailure(`The sign-in service did not answer within ${Math.ceil(budget / 1e3)} seconds.`, true);
591
+ throw new RequestFailure("The request to the sign-in service did not complete.", !notSent(error));
592
+ }
593
+ if (response.status >= 300 && response.status < 400) {
594
+ await response.body?.cancel().catch(() => void 0);
595
+ throw new RequestFailure("The sign-in service answered with a redirect, which this client does not follow.", true);
596
+ }
597
+ try {
598
+ return { status: response.status, body: await readBody(response), retryAfter: parseRetryAfter(response.headers.get("retry-after"), now()) };
599
+ } catch (error) {
600
+ if (error instanceof RequestFailure) throw error;
601
+ if (ctx.signal?.aborted) throw new RequestFailure("Interrupted while the sign-in service was answering.", true, "interrupted");
602
+ throw new RequestFailure("The sign-in service's answer was cut off.", true);
603
+ }
604
+ }
605
+ function oauthError(answer) {
606
+ const value = answer.body?.error;
607
+ if (typeof value !== "string") return null;
608
+ return OAUTH_ERRORS.has(value) ? value : "unrecognized";
609
+ }
610
+ function serviceError(answer) {
611
+ const server = { status: answer.status, code: oauthError(answer), message: null, retry_after: answer.retryAfter, correlation_id: null };
612
+ if (answer.status === 429) return new CliError("rate_limited", "The sign-in service asked this client to slow down.", { server });
613
+ return new CliError("service_unavailable", `The sign-in service could not answer (HTTP ${answer.status}).`, { server });
614
+ }
615
+ function assertSameOrigin(origin, value, field) {
616
+ let url;
617
+ try {
618
+ url = new URL(value);
619
+ } catch {
620
+ throw new CliError("transport_failure", `The sign-in service sent a ${field} that is not a URL; it was not shown.`);
621
+ }
622
+ if (url.protocol !== "https:" || url.host !== origin.host) {
623
+ throw new CliError("transport_failure", `The sign-in service sent a ${field} on another host; it was not shown.`);
624
+ }
625
+ }
626
+ async function startDevice(ctx, request, deadlineAt = null) {
627
+ const answer = await send(ctx, "/v1/auth/device", {
628
+ method: "POST",
629
+ form: { client_id: CLIENT_ID, site: request.site ?? void 0, new_site: request.newSite ?? void 0, scope: request.scope?.join(" ") }
630
+ }, deadlineAt);
631
+ if (answer.status === 200) {
632
+ const parsed = DeviceStart.safeParse(answer.body);
633
+ if (!parsed.success) throw new CliError("transport_failure", "The sign-in service answered in a shape this client does not understand.");
634
+ assertSameOrigin(ctx.origin, parsed.data.verification_uri, "verification link");
635
+ assertSameOrigin(ctx.origin, parsed.data.verification_uri_complete, "verification link");
636
+ return parsed.data;
637
+ }
638
+ const code = oauthError(answer);
639
+ if (answer.status === 400 && (code === "invalid_request" || code === "invalid_scope")) {
640
+ throw invalidInput(code === "invalid_scope" ? "The sign-in service refused the requested permissions." : "The sign-in service refused the request. Check --site, --new-site, and --scope.");
641
+ }
642
+ throw serviceError(answer);
643
+ }
644
+ async function pollDevice(ctx, pending, deadlineAt, onInterval = async () => void 0) {
645
+ const sleep = ctx.sleep ?? defaultSleep;
646
+ const now = ctx.now ?? Date.now;
647
+ const expiresAt = Date.parse(pending.expires_at);
648
+ let interval = pending.interval * 1e3;
649
+ for (; ; ) {
650
+ if (now() + interval > expiresAt + 6e4) return { kind: "expired" };
651
+ if (deadlineAt !== null && now() + interval > deadlineAt) return { kind: "timeout" };
652
+ await sleep(interval, ctx.signal);
653
+ const answer = await send(ctx, "/v1/auth/token", { method: "POST", form: { grant_type: DEVICE_GRANT, client_id: CLIENT_ID, device_code: pending.device_code } }, deadlineAt);
654
+ if (answer.status === 200) {
655
+ const parsed = TokenPair.safeParse(answer.body);
656
+ if (!parsed.success) throw new CliError("transport_failure", "The sign-in service issued tokens in a shape this client does not understand.");
657
+ return { kind: "approved", tokens: parsed.data };
658
+ }
659
+ const code = oauthError(answer);
660
+ if (code === "authorization_pending") continue;
661
+ if (code === "slow_down") {
662
+ interval = Math.min(interval + 5e3, MAX_POLL_INTERVAL_MS);
663
+ await onInterval(interval / 1e3);
664
+ continue;
665
+ }
666
+ if (code === "access_denied") return { kind: "denied" };
667
+ if (code === "expired_token") return { kind: "expired" };
668
+ if (code === "invalid_grant") return { kind: "consumed" };
669
+ if (answer.status === 429 || answer.status === 503) {
670
+ interval = answer.retryAfter === null ? Math.min(interval + 5e3, MAX_POLL_INTERVAL_MS) : Math.max(interval, answer.retryAfter * 1e3);
671
+ continue;
672
+ }
673
+ throw serviceError(answer);
674
+ }
675
+ }
676
+ async function refreshTokens(ctx, refreshToken, deadlineAt) {
677
+ const sleep = ctx.sleep ?? defaultSleep;
678
+ const now = ctx.now ?? Date.now;
679
+ for (; ; ) {
680
+ let answer;
681
+ try {
682
+ answer = await send(ctx, "/v1/auth/token", { method: "POST", form: { grant_type: "refresh_token", client_id: CLIENT_ID, refresh_token: refreshToken } }, deadlineAt);
683
+ } catch (error) {
684
+ if (error instanceof RequestFailure) return error.sent ? { kind: "ambiguous", error } : { kind: "not_rotated", error };
685
+ throw error;
686
+ }
687
+ if (answer.status === 200) {
688
+ const parsed = TokenPair.safeParse(answer.body);
689
+ if (!parsed.success) return { kind: "ambiguous", error: new CliError("transport_failure", "The sign-in service refreshed the login in a shape this client does not understand.") };
690
+ return { kind: "refreshed", tokens: parsed.data };
691
+ }
692
+ const code = oauthError(answer);
693
+ if (answer.status === 400 && code === "invalid_grant") return { kind: "rejected" };
694
+ const limited = (answer.status === 429 || answer.status === 503) && answer.retryAfter !== null;
695
+ if (limited && now() + answer.retryAfter * 1e3 < deadlineAt) {
696
+ await sleep(answer.retryAfter * 1e3, ctx.signal);
697
+ continue;
698
+ }
699
+ if (limited) return { kind: "not_rotated", error: serviceError(answer) };
700
+ if (answer.status === 400 && code !== null && PRE_ROTATION_ERRORS.has(code)) {
701
+ return { kind: "not_rotated", error: new CliError("invalid_input", "The sign-in service refused the refresh request as malformed. The saved login is unchanged.", { server: { status: 400, code, message: null, retry_after: null, correlation_id: null } }) };
702
+ }
703
+ return { kind: "ambiguous", error: serviceError(answer) };
704
+ }
705
+ }
706
+ async function revokeToken(ctx, token) {
707
+ const answer = await send(ctx, "/v1/auth/revoke", { method: "POST", form: { client_id: CLIENT_ID, token, token_type_hint: "refresh_token" } });
708
+ if (answer.status !== 200) throw serviceError(answer);
709
+ }
710
+ async function grantStatus(ctx, accessToken, deadlineAt = null) {
711
+ const answer = await send(ctx, "/v1/auth/status", { method: "GET", bearer: accessToken }, deadlineAt);
712
+ if (answer.status === 401) return null;
713
+ if (answer.status !== 200) throw serviceError(answer);
714
+ const parsed = GrantStatus.safeParse(answer.body);
715
+ if (!parsed.success) throw new CliError("transport_failure", "The sign-in service described the login in a shape this client does not understand.");
716
+ return parsed.data;
717
+ }
718
+ function scopeList(scope) {
719
+ return scope.split(/\s+/u).filter((part) => part !== "");
720
+ }
721
+
722
+ // src/lib/saved-login.ts
723
+ var REFRESH_MARGIN_MS = 6e4;
724
+ var REFRESH_DEADLINE_MS = 3e4;
725
+ function storesFor(environment) {
726
+ return credentialStores({ env: environment.env, ...environment.platform === void 0 ? {} : { platform: environment.platform }, ...environment.run === void 0 ? {} : { run: environment.run } });
727
+ }
728
+ function flowContext(origin, environment) {
729
+ return {
730
+ origin,
731
+ fetchImpl: environment.fetchImpl,
732
+ ...environment.signal === void 0 ? {} : { signal: environment.signal },
733
+ ...environment.sleep === void 0 ? {} : { sleep: environment.sleep },
734
+ ...environment.now === void 0 ? {} : { now: environment.now }
735
+ };
736
+ }
737
+ function lockOptions(environment) {
738
+ return environment.lockWaitMs === void 0 ? {} : { waitMs: environment.lockWaitMs };
739
+ }
740
+ function grantFromTokens(tokens, now) {
741
+ return {
742
+ site_id: tokens.site_id,
743
+ scope: scopeList(tokens.scope),
744
+ access_token: tokens.access_token,
745
+ access_expires_at: new Date(now + tokens.expires_in * 1e3).toISOString(),
746
+ refresh_token: tokens.refresh_token,
747
+ rotating_since: null
748
+ };
749
+ }
750
+ function chooseSite(record, site) {
751
+ if (site !== null) return site;
752
+ if (record.default_site !== null && record.default_site in record.grants) return record.default_site;
753
+ const sites = Object.keys(record.grants);
754
+ if (sites.length === 1) return sites[0];
755
+ if (sites.length === 0) return null;
756
+ throw invalidInput(`Several sites have saved logins (${sites.join(", ")}). Pass --site to choose one.`);
757
+ }
758
+ function fresh(grant, now) {
759
+ return grant.rotating_since === null && Date.parse(grant.access_expires_at) - now > REFRESH_MARGIN_MS;
760
+ }
761
+ function loginAgainRecovery(site) {
762
+ return {
763
+ command: `saturndocs login --site ${site}`,
764
+ replay: null,
765
+ message: `Ask the person to approve this agent for ${site} again.`
766
+ };
767
+ }
768
+ function withoutGrant(record, site) {
769
+ const grants = { ...record.grants };
770
+ delete grants[site];
771
+ const defaultSite = record.default_site !== null && record.default_site in grants ? record.default_site : Object.keys(grants)[0] ?? null;
772
+ return { ...record, grants, default_site: defaultSite };
773
+ }
774
+ function withGrant(record, grant) {
775
+ return { ...record, grants: { ...record.grants, [grant.site_id]: grant } };
776
+ }
777
+ async function resolveSavedLogin(origin, site, environment) {
778
+ const now = environment.now ?? Date.now;
779
+ const choice = storesFor(environment);
780
+ if (!hasAnyStore(choice)) return null;
781
+ const loaded = await loadRecord(choice, origin.origin);
782
+ if (loaded === null) return null;
783
+ const siteId = chooseSite(loaded.record, site);
784
+ if (siteId === null) return null;
785
+ const saved = loaded.record.grants[siteId];
786
+ if (saved === void 0) throw invalidInput(`No saved login for ${siteId}. Run saturndocs login --site ${siteId}.`, { recovery: loginAgainRecovery(siteId) });
787
+ if (fresh(saved, now())) return { token: saved.access_token, grant: saved, store: loaded.store };
788
+ return withCredentialLock(choice, async () => {
789
+ const current = await loadRecord(choice, origin.origin);
790
+ const grant = current?.record.grants[siteId];
791
+ if (current === null || grant === void 0) throw invalidInput(`No saved login for ${siteId}. Run saturndocs login --site ${siteId}.`, { recovery: loginAgainRecovery(siteId) });
792
+ if (fresh(grant, now())) return { token: grant.access_token, grant, store: current.store };
793
+ const ctx = flowContext(origin, environment);
794
+ if (grant.rotating_since !== null) {
795
+ const confirmed = await revokeToken(ctx, grant.refresh_token).then(() => true, () => false);
796
+ const deleted = await saveRecord(current.store, withoutGrant(current.record, siteId)).then(() => null, (error) => error instanceof Error ? error.message : String(error));
797
+ const notes = [
798
+ confirmed ? "" : " The server did not confirm the revocation; a person can revoke the grant from the dashboard.",
799
+ deleted === null ? "" : ` The saved login could not be deleted from the ${current.store.label} (${deleted}); run saturndocs logout --site ${siteId}.`
800
+ ].join("");
801
+ throw new CliError("unauthorized", `An earlier refresh of the saved login for ${siteId} did not finish, so the login was ended to keep its token from being presented twice.${notes} Run saturndocs login --site ${siteId}.`, { recovery: loginAgainRecovery(siteId), mutation: confirmed && deleted === null ? "known" : "unknown" });
802
+ }
803
+ const marked = withGrant(current.record, { ...grant, rotating_since: new Date(now()).toISOString() });
804
+ const store = await saveRecord(current.store, marked);
805
+ const markedRecord = { ...marked, generation: marked.generation + 1 };
806
+ const outcome = await refreshTokens(ctx, grant.refresh_token, now() + REFRESH_DEADLINE_MS);
807
+ if (outcome.kind === "rejected") {
808
+ await saveRecord(store, withoutGrant(markedRecord, siteId));
809
+ throw new CliError("unauthorized", `The saved login for ${siteId} no longer works and was removed. Run saturndocs login --site ${siteId}.`, { recovery: loginAgainRecovery(siteId) });
810
+ }
811
+ if (outcome.kind === "not_rotated") {
812
+ await saveRecord(store, withGrant(markedRecord, grant));
813
+ throw outcome.error;
814
+ }
815
+ if (outcome.kind === "ambiguous") {
816
+ throw new CliError(outcome.error.code, `${outcome.error.message} The refresh may have gone through, so the next command will end this login and ask for a new one.`, { mutation: "unknown", recovery: loginAgainRecovery(siteId) });
817
+ }
818
+ if (outcome.tokens.site_id !== siteId) {
819
+ throw new CliError("transport_failure", `The sign-in service refreshed the login for ${siteId} as another site; the answer was not saved.`, { mutation: "unknown" });
820
+ }
821
+ const refreshed = grantFromTokens(outcome.tokens, now());
822
+ await saveRecord(store, withGrant(markedRecord, refreshed));
823
+ return { token: refreshed.access_token, grant: refreshed, store };
824
+ }, lockOptions(environment));
825
+ }
826
+
827
+ // src/adapter/client.ts
828
+ var TOKEN_VARIABLE = "SATURNDOCS_MANAGEMENT_TOKEN";
829
+ var savedLoginSite = null;
830
+ function environmentToken(env) {
831
+ const value = env[TOKEN_VARIABLE];
832
+ return value === void 0 || value === "" ? void 0 : value;
833
+ }
834
+ function loginEnvironment(environment = {}) {
835
+ const signal = environment.signal ?? interruptSignal() ?? void 0;
836
+ return {
837
+ env: environment.env ?? process.env,
838
+ fetchImpl: environment.fetchImpl ?? fetch,
839
+ ...signal === void 0 ? {} : { signal },
840
+ ...environment.login
841
+ };
842
+ }
843
+ function clientFor(globals, environment = {}) {
844
+ const env = environment.env ?? process.env;
845
+ const signal = environment.signal ?? interruptSignal() ?? void 0;
846
+ const token = environmentToken(env);
847
+ const origin = parseOrigin(globals.api ?? void 0);
848
+ const config = {
849
+ ...token !== void 0 ? { token } : {
850
+ tokenProvider: async () => {
851
+ const login = await resolveSavedLogin(origin, globals.site, loginEnvironment(environment));
852
+ savedLoginSite = login?.grant.site_id ?? null;
853
+ return login?.token;
854
+ }
855
+ },
856
+ ...globals.api === null ? {} : { origin: globals.api },
857
+ ...environment.fetchImpl === void 0 ? {} : { fetchImpl: environment.fetchImpl },
858
+ ...signal === void 0 ? {} : { signal },
859
+ ...globals.timeout === null ? {} : { deadlineMs: globals.timeout * 1e3 }
860
+ };
861
+ return createClient(config);
862
+ }
863
+ function asCliError(error) {
864
+ if (!isManagementError(error)) return error;
865
+ const refused = error.detail.code === "unauthorized" || error.detail.code === "forbidden";
866
+ return new CliError(error.detail.code, error.detail.message, {
867
+ server: error.detail.server,
868
+ retryable: error.detail.retryable,
869
+ mutation: error.detail.mutation,
870
+ exit: error.detail.exit,
871
+ cause: error,
872
+ ...refused && savedLoginSite !== null ? { recovery: loginAgainRecovery(savedLoginSite) } : {}
873
+ });
874
+ }
875
+
876
+ export {
877
+ emptyRecord,
878
+ windowsUnsupported,
879
+ hasAnyStore,
880
+ selectStore,
881
+ readStoredRecord,
882
+ loadRecord,
883
+ saveRecord,
884
+ withCredentialLock,
885
+ withPollLock,
886
+ allRecords,
887
+ normalizeScope,
888
+ validateNewSite,
889
+ assertSameOrigin,
890
+ startDevice,
891
+ pollDevice,
892
+ revokeToken,
893
+ grantStatus,
894
+ storesFor,
895
+ flowContext,
896
+ lockOptions,
897
+ grantFromTokens,
898
+ loginAgainRecovery,
899
+ resolveSavedLogin,
900
+ TOKEN_VARIABLE,
901
+ environmentToken,
902
+ loginEnvironment,
903
+ clientFor,
904
+ asCliError
905
+ };