@sublang/spex 4.2.0 → 6.0.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 (100) hide show
  1. package/README.md +438 -89
  2. package/dist/cli.js +80 -42
  3. package/dist/commands/add.d.ts +12 -0
  4. package/dist/commands/add.js +138 -0
  5. package/dist/commands/auth-target.d.ts +12 -0
  6. package/dist/commands/auth-target.js +52 -0
  7. package/dist/commands/environment.d.ts +117 -0
  8. package/dist/commands/environment.js +399 -0
  9. package/dist/commands/export.d.ts +21 -0
  10. package/dist/commands/export.js +663 -0
  11. package/dist/commands/home.d.ts +56 -0
  12. package/dist/commands/home.js +215 -0
  13. package/dist/commands/install.d.ts +2 -0
  14. package/dist/commands/install.js +48 -0
  15. package/dist/commands/list.d.ts +2 -0
  16. package/dist/commands/list.js +87 -0
  17. package/dist/commands/login.d.ts +2 -0
  18. package/dist/commands/login.js +211 -0
  19. package/dist/commands/logout.d.ts +2 -0
  20. package/dist/commands/logout.js +74 -0
  21. package/dist/commands/publish.d.ts +2 -0
  22. package/dist/commands/publish.js +120 -0
  23. package/dist/commands/remove.d.ts +2 -0
  24. package/dist/commands/remove.js +34 -0
  25. package/dist/commands/run.d.ts +50 -0
  26. package/dist/commands/run.js +312 -0
  27. package/dist/commands/search.d.ts +2 -0
  28. package/dist/commands/search.js +34 -0
  29. package/dist/commands/settle.d.ts +124 -0
  30. package/dist/commands/settle.js +475 -0
  31. package/dist/commands/update.d.ts +2 -0
  32. package/dist/commands/update.js +37 -0
  33. package/dist/commands/whoami.d.ts +2 -0
  34. package/dist/commands/whoami.js +71 -0
  35. package/dist/lib/environment/agent-folders.d.ts +14 -0
  36. package/dist/lib/environment/agent-folders.js +11 -0
  37. package/dist/lib/environment/archive.d.ts +39 -0
  38. package/dist/lib/environment/archive.js +122 -0
  39. package/dist/lib/environment/builtins.d.ts +112 -0
  40. package/dist/lib/environment/builtins.js +539 -0
  41. package/dist/lib/environment/citations.d.ts +75 -0
  42. package/dist/lib/environment/citations.js +267 -0
  43. package/dist/lib/environment/exports.d.ts +190 -0
  44. package/dist/lib/environment/exports.js +1029 -0
  45. package/dist/lib/environment/format.d.ts +133 -0
  46. package/dist/lib/environment/format.js +651 -0
  47. package/dist/lib/environment/git-source.d.ts +41 -0
  48. package/dist/lib/environment/git-source.js +159 -0
  49. package/dist/lib/environment/index.d.ts +20 -0
  50. package/dist/lib/environment/index.js +27 -0
  51. package/dist/lib/environment/install.d.ts +140 -0
  52. package/dist/lib/environment/install.js +694 -0
  53. package/dist/lib/environment/layout.d.ts +15 -0
  54. package/dist/lib/environment/layout.js +50 -0
  55. package/dist/lib/environment/lock.d.ts +87 -0
  56. package/dist/lib/environment/lock.js +305 -0
  57. package/dist/lib/environment/marker.d.ts +15 -0
  58. package/dist/lib/environment/marker.js +31 -0
  59. package/dist/lib/environment/own-paths.d.ts +59 -0
  60. package/dist/lib/environment/own-paths.js +174 -0
  61. package/dist/lib/environment/placed-record.d.ts +32 -0
  62. package/dist/lib/environment/placed-record.js +72 -0
  63. package/dist/lib/environment/registries.d.ts +23 -0
  64. package/dist/lib/environment/registries.js +48 -0
  65. package/dist/lib/environment/registry.d.ts +172 -0
  66. package/dist/lib/environment/registry.js +390 -0
  67. package/dist/lib/environment/requests.d.ts +109 -0
  68. package/dist/lib/environment/requests.js +401 -0
  69. package/dist/lib/environment/resolve.d.ts +70 -0
  70. package/dist/lib/environment/resolve.js +451 -0
  71. package/dist/lib/environment/semver.d.ts +30 -0
  72. package/dist/lib/environment/semver.js +130 -0
  73. package/dist/lib/environment/store.d.ts +23 -0
  74. package/dist/lib/environment/store.js +123 -0
  75. package/dist/lib/environment/tar.d.ts +27 -0
  76. package/dist/lib/environment/tar.js +219 -0
  77. package/dist/lib/files.d.ts +66 -0
  78. package/dist/lib/files.js +233 -0
  79. package/dist/lib/git-host.d.ts +579 -0
  80. package/dist/lib/git-host.js +1363 -0
  81. package/dist/lib/home-file.d.ts +124 -0
  82. package/dist/lib/home-file.js +288 -0
  83. package/dist/lib/instance.d.ts +63 -0
  84. package/dist/lib/instance.js +130 -0
  85. package/dist/lib/words.d.ts +32 -0
  86. package/dist/lib/words.js +27 -0
  87. package/dist/lint.js +8 -0
  88. package/dist/testing/index.d.ts +1 -0
  89. package/dist/testing/index.js +7 -0
  90. package/dist/testing/standin-registry.d.ts +94 -0
  91. package/dist/testing/standin-registry.js +449 -0
  92. package/package.json +37 -3
  93. package/dist/attached-cli.d.ts +0 -13
  94. package/dist/attached-cli.js +0 -249
  95. package/dist/attached-client.d.ts +0 -53
  96. package/dist/attached-client.js +0 -237
  97. package/dist/generated-protocol.d.ts +0 -2
  98. package/dist/generated-protocol.js +0 -6
  99. package/dist/package-init.d.ts +0 -21
  100. package/dist/package-init.js +0 -442
@@ -0,0 +1,1363 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ // The Git host client (git-host-1..21, DR-103, DR-114, DR-120): signs a
4
+ // person in as a public client — the browser flow with PKCE on the
5
+ // desktop, the device flow on the server shell — keeps the app token
6
+ // current in `local/credentials.yaml` (storage-19), and reads and writes
7
+ // the host's JSON routes under `/api/v1`: groups, spex repositories and
8
+ // members, with what the host says the person may do and the roles it
9
+ // grants, and the undo writes — a group renamed or deleted, a spex
10
+ // repository moved — and the team servers a person may open a seat on
11
+ // with the tickets that open one (git-host-29). A rate limit the host
12
+ // answers holds a sync step's calls and the host read until the instant
13
+ // it asked for, and refuses every other call meanwhile with the seconds
14
+ // that remain (git-host-21).
15
+ // It composes no reader-facing prose: a failure is a `HostError` carrying
16
+ // its kind and the host's own words, which the core phrases where it
17
+ // speaks (git-host-11). No secret ever enters an error message or a log
18
+ // line.
19
+ import { createHash, randomBytes } from "node:crypto";
20
+ import { createServer } from "node:http";
21
+ import { mkdirSync, readFileSync, rmSync } from "node:fs";
22
+ import { join } from "node:path";
23
+ import { setTimeout as sleep } from "node:timers/promises";
24
+ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
25
+ import { writeApplicationBytes } from "./files.js";
26
+ import { canonicalOrigin } from "./instance.js";
27
+ import { words } from "./words.js";
28
+ export { DEFAULT_HOST_URL, hostUrlFor } from "./instance.js";
29
+ /** The public OAuth client id Spex signs in as. */
30
+ export const CLIENT_ID = "spex";
31
+ /** An access secret this close to expiring is refreshed first (git-host-4). */
32
+ export const REFRESH_MARGIN_MS = 60_000;
33
+ /** A browser sign-in without a callback ends `expired` after this long
34
+ * (git-host-2). */
35
+ export const BROWSER_SIGN_IN_TIMEOUT_MS = 10 * 60_000;
36
+ /** The longest a rate limit holds the calls to the host (git-host-21). */
37
+ export const RATE_LIMIT_HOLD_MAX_MS = 120_000;
38
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
39
+ const SLOW_DOWN_STEP_MS = 5_000;
40
+ const LABEL_MAX = 80;
41
+ /** The longest a server's id or a person's id may be in a device
42
+ * request (git-host-27; the instance's own bound). */
43
+ export const SEAT_ID_MAX = 64;
44
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
45
+ const MONTH = MONTHS.join("|");
46
+ /** The three forms of an HTTP date (RFC 9110 §5.6.7), always GMT. */
47
+ const IMF_FIXDATE = new RegExp(`^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\\d{2}) (${MONTH}) (\\d{4}) (\\d{2}):(\\d{2}):(\\d{2}) GMT$`);
48
+ const RFC850_DATE = new RegExp(`^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\\d{2})-(${MONTH})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}) GMT$`);
49
+ const ASCTIME_DATE = new RegExp(`^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (${MONTH}) ( \\d|\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}) (\\d{4})$`);
50
+ /** An HTTP date as Unix milliseconds, or null where the text is none. */
51
+ function httpDate(text, now) {
52
+ const at = (year, month, day, h, m, s) => {
53
+ const ms = Date.UTC(year, MONTHS.indexOf(month), Number(day), Number(h), Number(m), Number(s));
54
+ return Number.isFinite(ms) ? ms : null;
55
+ };
56
+ let match = IMF_FIXDATE.exec(text);
57
+ if (match)
58
+ return at(Number(match[3]), match[2], match[1], match[4], match[5], match[6]);
59
+ match = RFC850_DATE.exec(text);
60
+ if (match) {
61
+ // A two-digit year more than 50 years ahead is of the past century.
62
+ const thisYear = new Date(now).getUTCFullYear();
63
+ let year = Math.floor(thisYear / 100) * 100 + Number(match[3]);
64
+ if (year > thisYear + 50)
65
+ year -= 100;
66
+ return at(year, match[2], match[1], match[4], match[5], match[6]);
67
+ }
68
+ match = ASCTIME_DATE.exec(text);
69
+ if (match)
70
+ return at(Number(match[6]), match[1], match[2].trim(), match[3], match[4], match[5]);
71
+ return null;
72
+ }
73
+ /**
74
+ * The seconds a host's `Retry-After` asks to wait (git-host-11): its
75
+ * number where it is all digits, the seconds from `now` until its HTTP
76
+ * date — none below zero — and null where it is absent or anything else.
77
+ */
78
+ export function retryAfterSeconds(value, now = Date.now()) {
79
+ if (typeof value !== "string")
80
+ return null;
81
+ const text = value.trim();
82
+ if (/^\d+$/.test(text)) {
83
+ const seconds = Number(text);
84
+ return Number.isSafeInteger(seconds) ? seconds : null;
85
+ }
86
+ const at = httpDate(text, now);
87
+ return at === null ? null : Math.max(0, Math.ceil((at - now) / 1000));
88
+ }
89
+ function trimUrl(url) {
90
+ return url.replace(/\/+$/, "");
91
+ }
92
+ /**
93
+ * A host answer other than success (git-host-11). `words` is the host's
94
+ * own message, kept whole; `retryAfter` the host's `Retry-After` for
95
+ * `rate_limited`, raw, read as seconds by `retryAfterSeconds`; `code`
96
+ * the envelope's `error.code` where one came; and,
97
+ * for a sign-in that ended without an account, `cause` names why.
98
+ */
99
+ export class HostError extends Error {
100
+ kind;
101
+ words;
102
+ retryAfter;
103
+ code;
104
+ status;
105
+ constructor(kind, options = {}) {
106
+ const words = options.words ?? null;
107
+ const code = options.code ?? null;
108
+ const what = options.cause ? `sign-in ${options.cause}` : code ?? kind;
109
+ super(`Git host: ${what}${words ? `: ${words}` : ""}`, options.cause ? { cause: options.cause } : undefined);
110
+ this.name = "HostError";
111
+ this.kind = kind;
112
+ this.words = words;
113
+ this.retryAfter = options.retryAfter ?? null;
114
+ this.code = code;
115
+ this.status = options.status ?? null;
116
+ }
117
+ }
118
+ /** A call's own Stop ended its wait for the host's rate limit before it
119
+ * was sent (git-host-21). Local; not the host's. */
120
+ export class HostWaitStopped extends Error {
121
+ code = "stopped";
122
+ constructor() {
123
+ super("Stopped while waiting for the Git host");
124
+ this.name = "HostWaitStopped";
125
+ }
126
+ }
127
+ /** Only this request's recovery deadline expired, not its ordinary timeout. */
128
+ class ReadRecoveryExpired extends Error {
129
+ }
130
+ /** The pair a step used was no longer the stored one when its answer
131
+ * came (git-host-4, git-host-10, storage-19): nothing was stored or
132
+ * removed, and the step may be made again. Local; not the host's. */
133
+ export class CredentialChanged extends Error {
134
+ code = "changed";
135
+ constructor() {
136
+ super("The stored sign-in changed meanwhile");
137
+ this.name = "CredentialChanged";
138
+ }
139
+ }
140
+ /** A sign-in started while another runs (git-host-2: a second start is
141
+ * `busy`). */
142
+ export class SignInBusyError extends Error {
143
+ code = "busy";
144
+ constructor() {
145
+ super("A sign-in is already running");
146
+ this.name = "SignInBusyError";
147
+ }
148
+ }
149
+ /** Whether two pairs are one, compared in every field. */
150
+ function samePair(a, b) {
151
+ if (a === null || b === null)
152
+ return a === b;
153
+ return a.access === b.access && a.accessExpiresAt === b.accessExpiresAt && a.refresh === b.refresh;
154
+ }
155
+ /** The path of the credentials file under a home. */
156
+ export function credentialsPath(homeDir) {
157
+ return join(homeDir, "local", "credentials.yaml");
158
+ }
159
+ /**
160
+ * The app token of one instance in `local/credentials.yaml`, exactly
161
+ * `{format: 1, hosts: {<origin>: {access, accessExpiresAt, refresh}}}`
162
+ * Space entries keyed by canonical origin; registry entries keyed by
163
+ * `registry:<origin>` (DR-168), with no implicit scope upgrade,
164
+ * written atomically with owner-only permissions under a `local/` made
165
+ * owner-only (storage-19). A file of another format is refused, never
166
+ * guessed at or overwritten, and no refusal or warning repeats the file's
167
+ * content, a secret among it: the format is named only where it is a
168
+ * number. Other instances' entries are kept; removing
169
+ * the last one removes the file. Every access is synchronous, so a
170
+ * replacement's read, comparison and rename leave no await between them.
171
+ */
172
+ export function fileCredentialStore(homeDir, hostUrl, scope = "space") {
173
+ const dir = join(homeDir, "local");
174
+ const file = credentialsPath(homeDir);
175
+ const origin = canonicalOrigin(hostUrl);
176
+ const key = scope === "space" ? origin : `registry:${origin}`;
177
+ function load() {
178
+ let text;
179
+ try {
180
+ text = readFileSync(file, "utf8");
181
+ }
182
+ catch (error) {
183
+ if (error.code === "ENOENT")
184
+ return null;
185
+ throw error;
186
+ }
187
+ let doc;
188
+ try {
189
+ // At "error" the parser emits no warning, each quoting the file,
190
+ // yet still throws where the YAML will not read; "silent" would
191
+ // read it. Its words are never repeated.
192
+ doc = parseYaml(text, { logLevel: "error" });
193
+ }
194
+ catch {
195
+ throw new Error(`${file} is not valid YAML; it is left as it is`);
196
+ }
197
+ if (!isRecord(doc))
198
+ throw new Error(`${file} holds no credentials map; it is left as it is`);
199
+ if (typeof doc.format !== "number") {
200
+ throw new Error(`${file}: ${words().unsupportedUnnamedFormat()}`);
201
+ }
202
+ if (doc.format !== 1) {
203
+ throw new Error(`${file} has format ${JSON.stringify(doc.format ?? null)}, which this version of Spex does not read; it is left as it is`);
204
+ }
205
+ if (!isRecord(doc.hosts))
206
+ throw new Error(`${file} has no hosts map; it is left as it is`);
207
+ return { format: 1, hosts: { ...doc.hosts } };
208
+ }
209
+ function entryOf(doc) {
210
+ const entry = doc?.hosts[key];
211
+ if (entry === undefined)
212
+ return null;
213
+ if (!isRecord(entry) || typeof entry.access !== "string" || typeof entry.refresh !== "string"
214
+ || typeof entry.accessExpiresAt !== "number" || !Number.isFinite(entry.accessExpiresAt)) {
215
+ throw new Error(`${file} holds a malformed entry for ${key}; it is left as it is`);
216
+ }
217
+ return { access: entry.access, accessExpiresAt: entry.accessExpiresAt, refresh: entry.refresh };
218
+ }
219
+ /** Write `doc` with this host's pair set to `next` or removed. */
220
+ function save(doc, next) {
221
+ if (next === null) {
222
+ if (!(key in doc.hosts))
223
+ return true;
224
+ delete doc.hosts[key];
225
+ }
226
+ else {
227
+ doc.hosts[key] = { access: next.access, accessExpiresAt: next.accessExpiresAt, refresh: next.refresh };
228
+ }
229
+ if (Object.keys(doc.hosts).length === 0) {
230
+ rmSync(file, { force: true });
231
+ return true;
232
+ }
233
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
234
+ writeApplicationBytes(file, stringifyYaml({ format: 1, hosts: doc.hosts }));
235
+ return true;
236
+ }
237
+ return {
238
+ read: async () => entryOf(load()),
239
+ replace: (expected, next) => {
240
+ const doc = load() ?? { format: 1, hosts: {} };
241
+ if (!samePair(entryOf(doc), expected))
242
+ return false;
243
+ // The same-pair CAS is also a synchronous, write-free continuity check.
244
+ if (samePair(expected, next))
245
+ return true;
246
+ return save(doc, next);
247
+ },
248
+ removeMalformed: () => {
249
+ const doc = load();
250
+ if (doc === null)
251
+ return true;
252
+ try {
253
+ if (entryOf(doc) !== null)
254
+ return false;
255
+ }
256
+ catch {
257
+ return save(doc, null);
258
+ }
259
+ return true;
260
+ },
261
+ };
262
+ }
263
+ /** The refusal of a sign-in at a listed instance as another person than
264
+ * its entry's account (git-host-2): `words` carries the entry's login. */
265
+ export function anotherAccountError(login) {
266
+ return signInError("account", { words: login });
267
+ }
268
+ /** The refusal of a seat's sign-in as a person other than the one its
269
+ * device request named (git-host-27): `words` carries the login the
270
+ * instance signed in. */
271
+ export function anotherPersonError(login) {
272
+ return signInError("person", { words: login });
273
+ }
274
+ const DEFAULT_PAGES = {
275
+ complete: page("Signed in", "Spex is signed in. You may close this browser window."),
276
+ failed: page("Not signed in", "Spex did not sign in. You may close this browser window and return to Spex."),
277
+ };
278
+ function page(title, text) {
279
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title></head><body><h1>${title}</h1><p>${text}</p></body></html>`;
280
+ }
281
+ const REAUTH_CODES = new Set(["invalid_token", "token_revoked", "reauth_required", "unauthenticated", "token_expired"]);
282
+ /**
283
+ * The client of one Git host. Every call to a host route presents the
284
+ * stored access secret and keeps the app token current (git-host-4);
285
+ * `describe()` alone needs no token.
286
+ */
287
+ export class GitHostClient {
288
+ url;
289
+ scope;
290
+ clientId;
291
+ label;
292
+ credentials;
293
+ fetchImpl;
294
+ now;
295
+ onSignedOut;
296
+ requestTimeoutMs;
297
+ onHold;
298
+ holdMaxMs;
299
+ server;
300
+ refreshing = null;
301
+ signIn = null;
302
+ /** The instant the host's last rate limit asked every call to wait
303
+ * until (git-host-21); 0 where none holds. */
304
+ holdUntil = 0;
305
+ constructor(options) {
306
+ this.url = trimUrl(options.url);
307
+ this.scope = options.scope ?? "space";
308
+ if (this.scope === "registry" && options.server)
309
+ throw new HostError("bad_request", { code: "registry_seat_forbidden" });
310
+ this.clientId = options.clientId ?? CLIENT_ID;
311
+ const label = options.label.trim();
312
+ this.label = (label.length > 0 ? label : "Spex").slice(0, LABEL_MAX);
313
+ this.credentials = options.credentials;
314
+ this.fetchImpl = options.fetch ?? fetch;
315
+ this.now = options.now ?? Date.now;
316
+ this.onSignedOut = options.onSignedOut;
317
+ this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
318
+ this.onHold = options.onHold;
319
+ this.holdMaxMs = options.holdMaxMs ?? RATE_LIMIT_HOLD_MAX_MS;
320
+ if (options.server)
321
+ this.server = { id: options.server.id, personId: options.server.personId };
322
+ }
323
+ /** Whether the host's rate limit holds the calls now (git-host-21). */
324
+ holding() {
325
+ return this.holdUntil > this.now();
326
+ }
327
+ /** `GET /api/v1/host`: the host's display name, the Git origin its
328
+ * credentials are valid for, and the roles it grants (git-host-5). */
329
+ async describe(options = {}) {
330
+ const answer = await this.send("GET", "/api/v1/host", options);
331
+ if (answer.status !== 200)
332
+ throw answerError(answer);
333
+ const body = record(answer.json);
334
+ // A host that lists no roles grants none through Spex.
335
+ const roles = body.roles === undefined || body.roles === null ? [] : list(body.roles).map(roleFrom);
336
+ return { displayName: text(body.display_name), gitOrigin: text(body.git_origin), roles };
337
+ }
338
+ /** Whether this device holds an app token for the host. */
339
+ async signedIn() {
340
+ return (await this.credentials.read()) !== null;
341
+ }
342
+ /** Whether a sign-in is running. */
343
+ signingIn() {
344
+ return this.signIn !== null;
345
+ }
346
+ /**
347
+ * The browser flow with PKCE (git-host-2): a loopback listener on
348
+ * `127.0.0.1` at an OS-assigned port for one callback, an S256
349
+ * challenge, and the host's `/login/app` URL to open.
350
+ */
351
+ async startBrowserSignIn(options = {}) {
352
+ const { slot, expected } = await this.beginSignIn();
353
+ const pages = options.pages ?? DEFAULT_PAGES;
354
+ const server = createServer();
355
+ try {
356
+ await new Promise((resolveListen, rejectListen) => {
357
+ server.once("error", rejectListen);
358
+ server.listen(0, "127.0.0.1", () => {
359
+ server.off("error", rejectListen);
360
+ resolveListen();
361
+ });
362
+ });
363
+ }
364
+ catch (error) {
365
+ this.releaseSignIn(slot);
366
+ throw new HostError("unreachable", { words: error instanceof Error ? error.message : null, cause: "unreachable" });
367
+ }
368
+ const port = server.address().port;
369
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
370
+ const verifier = base64url(randomBytes(32));
371
+ const challenge = base64url(createHash("sha256").update(verifier).digest());
372
+ const state = base64url(randomBytes(32));
373
+ const query = new URLSearchParams({
374
+ client_id: this.clientId,
375
+ scope: this.scope,
376
+ label: this.label,
377
+ redirect_uri: redirectUri,
378
+ code_challenge: challenge,
379
+ code_challenge_method: "S256",
380
+ state,
381
+ });
382
+ const url = `${this.url}/login/app?${query.toString()}`;
383
+ let settled = false;
384
+ let answering = false;
385
+ let resolveDone;
386
+ let rejectDone;
387
+ const done = new Promise((resolveFlow, rejectFlow) => {
388
+ resolveDone = resolveFlow;
389
+ rejectDone = rejectFlow;
390
+ });
391
+ done.catch(() => undefined);
392
+ let closed = false;
393
+ const close = () => {
394
+ if (closed)
395
+ return;
396
+ closed = true;
397
+ server.close();
398
+ server.closeAllConnections();
399
+ };
400
+ const end = (outcome, keepOpen = false) => {
401
+ if (settled)
402
+ return;
403
+ settled = true;
404
+ clearTimeout(timer);
405
+ this.releaseSignIn(slot);
406
+ if (!keepOpen)
407
+ close();
408
+ if ("account" in outcome)
409
+ resolveDone(outcome.account);
410
+ else
411
+ rejectDone(outcome.error);
412
+ };
413
+ const timer = setTimeout(() => end({ error: signInError("expired") }), options.timeoutMs ?? BROWSER_SIGN_IN_TIMEOUT_MS);
414
+ server.on("request", (request, response) => {
415
+ const target = new URL(request.url ?? "/", redirectUri);
416
+ if (request.method !== "GET" || target.pathname !== "/callback" || settled || answering) {
417
+ response.writeHead(404, { "content-type": "text/plain; charset=utf-8", connection: "close" }).end();
418
+ return;
419
+ }
420
+ answering = true;
421
+ clearTimeout(timer);
422
+ void this.answerCallback(target.searchParams, { state, verifier, redirectUri, isSettled: () => settled }).then((answered) => {
423
+ if (settled) {
424
+ respond(response, 410, pages.failed, close);
425
+ return;
426
+ }
427
+ // Stored and ended in one turn: no cancel falls between them.
428
+ const outcome = "issued" in answered ? this.publish(expected, answered.issued, options.admit) : answered;
429
+ // The page goes out before the listener closes, so the browser
430
+ // always sees how the sign-in ended.
431
+ end(outcome, true);
432
+ respond(response, "account" in outcome ? 200 : 400, "account" in outcome ? pages.complete : pages.failed, close);
433
+ });
434
+ });
435
+ return {
436
+ url,
437
+ redirectUri,
438
+ done,
439
+ cancel: () => end({ error: signInError("stopped") }),
440
+ };
441
+ }
442
+ async answerCallback(params, flow) {
443
+ try {
444
+ if (params.get("state") !== flow.state)
445
+ return { error: signInError("state") };
446
+ const error = params.get("error");
447
+ if (error !== null) {
448
+ return { error: signInError(error === "access_denied" ? "denied" : "refused", { code: error, words: params.get("error_description") }) };
449
+ }
450
+ const code = params.get("code");
451
+ if (!code)
452
+ return { error: signInError("refused") };
453
+ const answer = await this.send("POST", "/api/v1/auth/token", {
454
+ body: { scope: this.scope, grant_type: "authorization_code", code, code_verifier: flow.verifier, redirect_uri: flow.redirectUri, client_id: this.clientId },
455
+ });
456
+ if (flow.isSettled())
457
+ return { error: signInError("stopped") };
458
+ if (answer.status !== 200)
459
+ return { error: exchangeError(answer) };
460
+ return { issued: await this.issued(answer) };
461
+ }
462
+ catch (error) {
463
+ return { error: asSignInError(error) };
464
+ }
465
+ }
466
+ /**
467
+ * The device flow (git-host-3): the host's user code and verification
468
+ * URL, completed with the code where the host gives it, then polling the token endpoint at its interval, five seconds
469
+ * slower on each `slow_down`, until the token, a denial or the expiry.
470
+ * On a seat, `ticket` is the one the member's client presented for it,
471
+ * on which the host may grant the code without its page (git-host-27).
472
+ */
473
+ async startDeviceSignIn(options = {}) {
474
+ const { slot, expected } = await this.beginSignIn();
475
+ let start;
476
+ try {
477
+ // A seat names its server and the person it was opened for, both
478
+ // or neither, and the ticket where its start named one; off a seat
479
+ // no ticket is sent (git-host-27).
480
+ const seat = this.server
481
+ ? { server_id: this.server.id, person_id: this.server.personId, ...(options.ticket ? { ticket: options.ticket } : {}) }
482
+ : {};
483
+ const answer = await this.send("POST", "/api/v1/auth/device", { body: { scope: this.scope, client_id: this.clientId, label: this.label, ...seat } });
484
+ if (answer.status !== 200)
485
+ throw answerError(answer);
486
+ const body = record(answer.json);
487
+ start = {
488
+ deviceCode: text(body.device_code),
489
+ userCode: text(body.user_code),
490
+ // The URL completed with the code where the host gives one,
491
+ // so the person never types it (git-host-3).
492
+ verificationUri: optionalText(body.verification_uri_complete) || text(body.verification_uri),
493
+ expiresIn: positive(body.expires_in, 600),
494
+ interval: positive(body.interval, 5),
495
+ };
496
+ }
497
+ catch (error) {
498
+ this.releaseSignIn(slot);
499
+ throw error;
500
+ }
501
+ const expiresAt = this.now() + start.expiresIn * 1000;
502
+ let settled = false;
503
+ let wake = null;
504
+ let sleeper;
505
+ let resolveDone;
506
+ let rejectDone;
507
+ const done = new Promise((resolveFlow, rejectFlow) => {
508
+ resolveDone = resolveFlow;
509
+ rejectDone = rejectFlow;
510
+ });
511
+ done.catch(() => undefined);
512
+ const end = (outcome) => {
513
+ if (settled)
514
+ return;
515
+ settled = true;
516
+ if (sleeper)
517
+ clearTimeout(sleeper);
518
+ wake?.();
519
+ this.releaseSignIn(slot);
520
+ if ("account" in outcome)
521
+ resolveDone(outcome.account);
522
+ else
523
+ rejectDone(outcome.error);
524
+ };
525
+ const wait = (ms) => new Promise((resolveWait) => {
526
+ wake = resolveWait;
527
+ sleeper = setTimeout(resolveWait, ms);
528
+ });
529
+ const poll = async () => {
530
+ let intervalMs = start.interval * 1000;
531
+ while (!settled) {
532
+ await wait(intervalMs);
533
+ if (settled)
534
+ return;
535
+ if (this.now() >= expiresAt) {
536
+ end({ error: signInError("expired") });
537
+ return;
538
+ }
539
+ let answer;
540
+ try {
541
+ answer = await this.send("POST", "/api/v1/auth/token", {
542
+ body: { scope: this.scope, grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: start.deviceCode, client_id: this.clientId },
543
+ });
544
+ }
545
+ catch {
546
+ continue; // no answer: keep polling until the code expires
547
+ }
548
+ if (settled)
549
+ return;
550
+ if (answer.status === 200) {
551
+ let answered;
552
+ try {
553
+ answered = { issued: await this.issued(answer) };
554
+ }
555
+ catch (error) {
556
+ answered = { error: asSignInError(error) };
557
+ }
558
+ if (settled)
559
+ return;
560
+ // Stored and ended in one turn: no cancel falls between them.
561
+ end("issued" in answered ? this.publish(expected, answered.issued, options.admit) : answered);
562
+ return;
563
+ }
564
+ const code = codeOf(answer);
565
+ if (code === "authorization_pending")
566
+ continue;
567
+ if (code === "slow_down") {
568
+ intervalMs += SLOW_DOWN_STEP_MS;
569
+ continue;
570
+ }
571
+ if (code === "access_denied") {
572
+ end({ error: signInError("denied", { code, words: wordsOf(answer) }) });
573
+ return;
574
+ }
575
+ if (code === "expired_token") {
576
+ end({ error: signInError("expired", { code, words: wordsOf(answer) }) });
577
+ return;
578
+ }
579
+ if (answer.status >= 500 || answer.status === 429)
580
+ continue;
581
+ end({ error: exchangeError(answer) });
582
+ return;
583
+ }
584
+ };
585
+ void poll();
586
+ return {
587
+ userCode: start.userCode,
588
+ verificationUri: start.verificationUri,
589
+ expiresAt,
590
+ interval: start.interval,
591
+ done,
592
+ cancel: () => end({ error: signInError("stopped") }),
593
+ };
594
+ }
595
+ /**
596
+ * Sign this device out (git-host-10): revoke it at the host with its
597
+ * app token, tried once, and remove that pair either way, calling
598
+ * `onRemoved` in the same turn as the removal. Where another pair was
599
+ * stored in its place meanwhile, that pair stays, `onRemoved` is not
600
+ * called, and `CredentialChanged` is thrown. A malformed entry, which
601
+ * cannot be read, is removed unless a well-formed pair stands by then.
602
+ */
603
+ async signOut(onRemoved) {
604
+ let credential = null;
605
+ try {
606
+ credential = await this.credentials.read();
607
+ }
608
+ catch (error) {
609
+ if (!this.credentials.removeMalformed)
610
+ throw error;
611
+ if (!this.credentials.removeMalformed())
612
+ throw new CredentialChanged();
613
+ onRemoved?.();
614
+ return;
615
+ }
616
+ if (credential) {
617
+ const stored = credential;
618
+ try {
619
+ // An expired access secret cannot revoke; a fresh one can.
620
+ const fresh = async () => {
621
+ const answer = await this.send("POST", "/api/v1/auth/token", {
622
+ body: { scope: this.scope, grant_type: "refresh_token", refresh_token: stored.refresh, client_id: this.clientId },
623
+ });
624
+ return answer.status === 200 ? tokenFrom(answer, this.now()).access : null;
625
+ };
626
+ let access = stored.access;
627
+ let refreshed = false;
628
+ if (stored.accessExpiresAt - this.now() < REFRESH_MARGIN_MS) {
629
+ access = await fresh();
630
+ refreshed = true;
631
+ }
632
+ if (access !== null) {
633
+ const answer = await this.send("POST", "/api/v1/auth/revoke", { bearer: access, body: { scope: this.scope } });
634
+ if (!refreshed && answer.status === 401 && codeOf(answer) === "token_expired") {
635
+ const next = await fresh();
636
+ if (next !== null)
637
+ await this.send("POST", "/api/v1/auth/revoke", { bearer: next, body: { scope: this.scope } });
638
+ }
639
+ }
640
+ }
641
+ catch {
642
+ // No answer: tried once, and the credential goes either way.
643
+ }
644
+ }
645
+ if (!this.credentials.replace(credential, null))
646
+ throw new CredentialChanged();
647
+ onRemoved?.();
648
+ }
649
+ /** Whether no pair is stored for this host now, read synchronously so
650
+ * a caller acts on it in the same turn. */
651
+ holdsNone() {
652
+ return this.credentials.replace(null, null);
653
+ }
654
+ /** The selected purpose's account; registry identity needs no host API. */
655
+ async me(options = {}) {
656
+ return accountFrom((await this.call("GET", (this.scope === "registry" ? "/api/v1/whoami?scope=registry" : "/api/v1/host/me"), undefined, options)).json);
657
+ }
658
+ /** `GET /api/v1/host/groups`: the person's own group and every group
659
+ * they belong to. */
660
+ async groups(options = {}) {
661
+ const body = record((await this.call("GET", "/api/v1/host/groups", undefined, options)).json);
662
+ return list(body.groups).map(groupFrom);
663
+ }
664
+ /** `GET /api/v1/host/repositories`, every page. */
665
+ async repositories(options = {}) {
666
+ const all = [];
667
+ let cursor = null;
668
+ const seen = new Set();
669
+ do {
670
+ const path = cursor === null ? "/api/v1/host/repositories" : `/api/v1/host/repositories?cursor=${encodeURIComponent(cursor)}`;
671
+ const body = record((await this.call("GET", path, undefined, options)).json);
672
+ all.push(...list(body.repositories).map(repositoryFrom));
673
+ const next = body.next_cursor;
674
+ cursor = typeof next === "string" && next.length > 0 ? next : null;
675
+ if (cursor !== null) {
676
+ if (seen.has(cursor))
677
+ throw new HostError("unreachable", { code: "malformed_answer", words: null });
678
+ seen.add(cursor);
679
+ }
680
+ } while (cursor !== null);
681
+ return all;
682
+ }
683
+ /** `GET /api/v1/host/repositories/:id`, with its read-only state and
684
+ * the `spex` branch's. */
685
+ async repository(id, options = {}) {
686
+ const body = record((await this.call("GET", `/api/v1/host/repositories/${encodeURIComponent(id)}`, undefined, options)).json);
687
+ return detailFrom(body);
688
+ }
689
+ /** `GET /api/v1/host/repositories/:id/members` or
690
+ * `GET /api/v1/host/groups/:id/members` (git-host-8): every member with
691
+ * the host's role name and source. */
692
+ async members(target, options = {}) {
693
+ const body = record((await this.call("GET", membersPath(target), undefined, options)).json);
694
+ return { members: list(body.members).map(memberFrom) };
695
+ }
696
+ /**
697
+ * `POST /api/v1/host/groups` (git-host-15): a private group named
698
+ * `name` at the path `path`, inside the group `parentId` or at the top
699
+ * where it is null. A taken name throws `name_taken`, the host's
700
+ * refusal `host_refused` with its words.
701
+ */
702
+ async createGroup(input) {
703
+ const body = record((await this.call("POST", "/api/v1/host/groups", { name: input.name, path: input.path, parent_id: input.parentId })).json);
704
+ return groupFrom(body.group);
705
+ }
706
+ /**
707
+ * `PATCH /api/v1/host/groups/:id` (git-host-18): give a group of the
708
+ * instance the name, the path segment, or both, given. A path taken
709
+ * there throws `name_taken`, the host's refusal `host_refused` with
710
+ * its words.
711
+ */
712
+ async renameGroup(id, input) {
713
+ const fields = {};
714
+ if (input.name !== undefined)
715
+ fields.name = input.name;
716
+ if (input.path !== undefined)
717
+ fields.path = input.path;
718
+ const body = record((await this.call("PATCH", `/api/v1/host/groups/${encodeURIComponent(id)}`, fields)).json);
719
+ return groupFrom(body.group);
720
+ }
721
+ /** Request normal deletion through the confirmation-aware route
722
+ * (git-host-19). Older deployments are refused, never retried through
723
+ * the legacy route, whose behavior may permanently delete a group. */
724
+ async deleteGroup(id, confirmPath) {
725
+ if (confirmPath === undefined || confirmPath.trim().length === 0)
726
+ throw new HostError("bad_request", { code: "confirmation_required", words: "Confirm the group's path before deleting it." });
727
+ const body = record((await this.call("POST", `/api/v1/host/groups/${encodeURIComponent(id)}/deletion`, { confirm_path: confirmPath })).json);
728
+ if (body.status === "deleted")
729
+ return { status: "deleted" };
730
+ if (body.status === "scheduled") {
731
+ const group = groupFrom(body.group);
732
+ if (group.id === id && group.pendingDeletion && group.deletionRoot)
733
+ return { status: "scheduled", group };
734
+ }
735
+ throw new HostError("unreachable", { code: "malformed_answer" });
736
+ }
737
+ /** Read the Space's current contents, including contents omitted from
738
+ * the records listing. Members are not contents. */
739
+ async inspectGroupDeletion(id) {
740
+ const body = record((await this.call("GET", `/api/v1/host/groups/${encodeURIComponent(id)}/deletion`)).json);
741
+ const group = groupFrom(body.group);
742
+ if (group.id !== id || !Array.isArray(body.contents))
743
+ throw new HostError("unreachable", { code: "malformed_answer" });
744
+ const contents = body.contents.map((value) => {
745
+ const item = record(value);
746
+ if (!["project", "group", "records", "server"].includes(String(item.kind)) || typeof item.name !== "string" || item.name.length === 0)
747
+ throw new HostError("unreachable", { code: "malformed_answer" });
748
+ return { kind: item.kind, name: item.name };
749
+ });
750
+ return { group, contents };
751
+ }
752
+ /** Restore the group's normal scheduled deletion, where the Space
753
+ * permits it; no retention period is inferred by the client. */
754
+ async restoreGroup(id) {
755
+ const body = record((await this.call("POST", `/api/v1/host/groups/${encodeURIComponent(id)}/restore`, {})).json);
756
+ const group = groupFrom(body.group);
757
+ if (group.id !== id || group.pendingDeletion)
758
+ throw new HostError("unreachable", { code: "malformed_answer" });
759
+ return group;
760
+ }
761
+ /**
762
+ * `POST /api/v1/host/repositories/:id/transfer` (git-host-20): move a
763
+ * spex repository into the group `groupId`, or the person's own group
764
+ * where it is null. A name taken there throws `name_taken`, the host's
765
+ * refusal `host_refused` with its words.
766
+ */
767
+ async transferRepository(id, groupId) {
768
+ const body = record((await this.call("POST", `/api/v1/host/repositories/${encodeURIComponent(id)}/transfer`, { group_id: groupId })).json);
769
+ return repositoryFrom(body.repository);
770
+ }
771
+ /**
772
+ * `POST …/members` (git-host-16): add the account the host lists under
773
+ * exactly `login` to the group or repository at the role whose id is
774
+ * `role`. No such account throws `not_found` with the host's words
775
+ * naming the login; a refusal `host_refused` with its words.
776
+ */
777
+ async addMember(target, input) {
778
+ const body = record((await this.call("POST", membersPath(target), { login: input.login, role: input.role })).json);
779
+ return memberFrom(body.member);
780
+ }
781
+ /**
782
+ * `DELETE …/members/:login` (git-host-17): remove the account under
783
+ * `login` from the group's or repository's own members. No account, or
784
+ * no membership of its own there, throws `not_found` with the host's
785
+ * words; a refusal `host_refused` with its words.
786
+ */
787
+ async removeMember(target, login) {
788
+ await this.call("DELETE", `${membersPath(target)}/${encodeURIComponent(login)}`);
789
+ }
790
+ /**
791
+ * `POST /api/v1/host/repositories` (git-host-6): `name` is the whole
792
+ * repository name, `<name>-spex`; `groupId` null means the person's own
793
+ * group. A taken name throws `name_taken`.
794
+ */
795
+ async create(input) {
796
+ const answer = await this.call("POST", "/api/v1/host/repositories", { group_id: input.groupId, name: input.name, description: input.description });
797
+ const body = record(answer.json);
798
+ if (answer.status === 202)
799
+ return { status: "pending", message: pendingWords(body) };
800
+ if (body.status !== "created")
801
+ throw new HostError("unreachable", { code: "malformed_answer", status: answer.status });
802
+ return { status: "created", repository: repositoryFrom(body.repository) };
803
+ }
804
+ /** `POST /api/v1/host/repositories/:id/spex-branch` (git-host-7). */
805
+ async prepareBranch(id, options = {}) {
806
+ const answer = await this.call("POST", `/api/v1/host/repositories/${encodeURIComponent(id)}/spex-branch`, {}, options);
807
+ const body = record(answer.json);
808
+ if (answer.status === 202)
809
+ return { status: "pending", message: pendingWords(body) };
810
+ if (body.status !== "ready")
811
+ throw new HostError("unreachable", { code: "malformed_answer", status: answer.status });
812
+ return { status: "ready" };
813
+ }
814
+ /**
815
+ * `GET /api/v1/host/servers` (git-host-29): the servers the person may
816
+ * open a seat on, as the instance answers them, in its order. The
817
+ * client keeps nothing of the answer.
818
+ */
819
+ async servers(options = {}) {
820
+ const body = record((await this.call("GET", "/api/v1/host/servers", undefined, options)).json);
821
+ return list(body.servers).map(serverFrom);
822
+ }
823
+ /**
824
+ * `POST /api/v1/host/servers/:id/tickets` (git-host-29): a ticket for a
825
+ * seat on the server `id`, as the instance answers it; the client keeps
826
+ * nothing of it. A server the instance does not list for the person
827
+ * throws `not_found`, a membership below the role it needs
828
+ * `host_refused`, each with the instance's words.
829
+ */
830
+ async ticket(id, options = {}) {
831
+ const body = record((await this.call("POST", `/api/v1/host/servers/${encodeURIComponent(id)}/tickets`, {}, options)).json);
832
+ const server = record(body.server);
833
+ return {
834
+ ticket: text(body.ticket),
835
+ expiresIn: positive(body.expires_in, 0),
836
+ server: { id: text(server.id), name: text(server.name), address: text(server.address) },
837
+ };
838
+ }
839
+ /** `POST /api/v1/host/credential` (git-host-9): the Git credential for
840
+ * the host's Git origin, with its expiry in Unix milliseconds. */
841
+ async credential(origin, options = {}) {
842
+ const body = record((await this.call("POST", "/api/v1/host/credential", { origin }, options)).json);
843
+ const expiresAt = Date.parse(text(body.expires_at));
844
+ return { username: text(body.username), secret: text(body.secret), expiresAt: Number.isFinite(expiresAt) ? expiresAt : 0 };
845
+ }
846
+ /**
847
+ * The access secret a call to the host presents now, for a client of
848
+ * the same host outside this one — the registry (environments-12):
849
+ * kept current as every call's is (git-host-4), refreshed first where
850
+ * it is within a minute of expiring; null where this device holds no
851
+ * app token, or the host refused the refresh and so signed it out.
852
+ * An unreachable host or a rate limit is thrown as the host answered.
853
+ */
854
+ async accessSecret() {
855
+ if ((await this.credentials.read()) === null)
856
+ return null;
857
+ try {
858
+ return (await this.current()).access;
859
+ }
860
+ catch (error) {
861
+ if (error instanceof HostError && error.kind === "reauth")
862
+ return null;
863
+ throw error;
864
+ }
865
+ }
866
+ /**
867
+ * A client of the same host outside this one — the registry
868
+ * (environments-12) — was refused `access` with a code that signs the
869
+ * device out: as a refusal of this client's own call does (git-host-4),
870
+ * the pair that presented it is removed and the device signed out of
871
+ * this host alone in one step, `onSignedOut` called; true then. Where
872
+ * it is no longer the stored pair's — a sign-in, a refresh or a
873
+ * sign-out meanwhile — nothing is removed or said, and false comes
874
+ * back: the call stands refused as changed meanwhile.
875
+ */
876
+ async signOutRefused(access) {
877
+ const stored = await this.credentials.read();
878
+ if (stored === null || stored.access !== access)
879
+ return false;
880
+ return !(this.signOutLocally(stored, new HostError("reauth")) instanceof CredentialChanged);
881
+ }
882
+ // -------------------------------------------------------------------------
883
+ claimSignIn() {
884
+ if (this.signIn)
885
+ throw new SignInBusyError();
886
+ const slot = {};
887
+ this.signIn = slot;
888
+ return slot;
889
+ }
890
+ /** Claim the one sign-in, and read the pair it begins over: its token
891
+ * is stored only in that pair's place (git-host-2). */
892
+ async beginSignIn() {
893
+ const slot = this.claimSignIn();
894
+ try {
895
+ return { slot, expected: await this.credentials.read() };
896
+ }
897
+ catch (error) {
898
+ this.releaseSignIn(slot);
899
+ throw error;
900
+ }
901
+ }
902
+ releaseSignIn(slot) {
903
+ if (this.signIn === slot)
904
+ this.signIn = null;
905
+ }
906
+ /** The issued app token and the person read with it, nothing stored
907
+ * yet; a person the host does not return throws (git-host-2). */
908
+ async issued(answer) {
909
+ const credential = tokenFrom(answer, this.now());
910
+ const me = await this.send("GET", (this.scope === "registry" ? "/api/v1/whoami?scope=registry" : "/api/v1/host/me"), { bearer: credential.access });
911
+ if (me.status !== 200)
912
+ throw answerError(me);
913
+ return { credential, account: accountFrom(me.json) };
914
+ }
915
+ /** Store an issued token in place of the pair its sign-in began over;
916
+ * the caller ends the sign-in in the same turn. On a seat, a person
917
+ * bearing another permanent id than the one the request named ends it
918
+ * naming the account signed in (git-host-27); a person `admit` refuses
919
+ * ends it with that refusal; and another pair stored meanwhile ends it
920
+ * `stopped`, that pair kept: each stores nothing (git-host-2). */
921
+ publish(expected, issued, admit) {
922
+ try {
923
+ if (this.server && issued.account.id !== this.server.personId)
924
+ return { error: anotherPersonError(issued.account.login) };
925
+ const refused = admit?.(issued.account);
926
+ if (refused)
927
+ return { error: refused };
928
+ return this.credentials.replace(expected, issued.credential) ? { account: issued.account } : { error: signInError("stopped") };
929
+ }
930
+ catch (error) {
931
+ return { error: asSignInError(error) };
932
+ }
933
+ }
934
+ /** A host route with the bearer kept current (git-host-4). Only a
935
+ * success, `202` included, comes back; everything else throws.
936
+ * `signal` ends the call's wait for the host's rate limit (git-host-21). */
937
+ async call(method, path, body, options = {}) {
938
+ // A call that does not wait is refused while the hold stands before
939
+ // anything is sent for it, a refresh among them (git-host-21).
940
+ const waits = options.signal !== undefined || options.wait === true;
941
+ if (!waits)
942
+ this.refuseWhileHeld();
943
+ let credential = await this.current(waits);
944
+ let refreshed = false;
945
+ let recovery;
946
+ const retryableRead = options.retryRead === true && waits && method === "GET"
947
+ && /^\/api\/v1\/host\/(?:me|groups|repositories(?:\?[^/]*|\/[^/?]+)?)$/.test(path);
948
+ const unchanged = () => {
949
+ if (options.signal?.aborted)
950
+ throw new HostWaitStopped();
951
+ if (!this.credentials.replace(credential, credential))
952
+ throw new CredentialChanged();
953
+ };
954
+ try {
955
+ for (;;) {
956
+ const answer = await this.send(method, path, {
957
+ body, bearer: credential.access, ...options,
958
+ ...(recovery ? { beforeSend: unchanged, recovery } : {}),
959
+ });
960
+ if (!refreshed && answer.status === 401 && codeOf(answer) === "token_expired") {
961
+ if (recovery) {
962
+ unchanged();
963
+ if (recovery.signal.aborted || this.now() >= recovery.until)
964
+ throw new ReadRecoveryExpired();
965
+ const signal = options.signal ? AbortSignal.any([recovery.signal, options.signal]) : recovery.signal;
966
+ let expired;
967
+ try {
968
+ // A shared refresh keeps its own authority; this caller's wait is bounded.
969
+ credential = await Promise.race([this.refresh(credential, waits), new Promise((_resolve, reject) => {
970
+ expired = () => reject(options.signal?.aborted ? new HostWaitStopped() : new ReadRecoveryExpired());
971
+ signal.addEventListener("abort", expired, { once: true });
972
+ if (signal.aborted)
973
+ expired();
974
+ })]);
975
+ }
976
+ finally {
977
+ signal.removeEventListener("abort", expired);
978
+ }
979
+ }
980
+ else
981
+ credential = await this.refresh(credential, waits);
982
+ refreshed = true;
983
+ continue;
984
+ }
985
+ const seconds = answer.status === 429 ? retryAfterSeconds(answer.retryAfter, this.now()) : null;
986
+ if (answer.status === 429 && retryableRead) {
987
+ recovery ??= { until: this.now() + this.holdMaxMs, signal: AbortSignal.timeout(this.holdMaxMs), latest: answer };
988
+ recovery.latest = answer;
989
+ if (seconds !== null && seconds > 0 && seconds * 1000 <= recovery.until - this.now())
990
+ continue;
991
+ }
992
+ if (answer.status === 401 || REAUTH_CODES.has(codeOf(answer) ?? "")) {
993
+ throw this.signOutLocally(credential, new HostError("reauth", { code: codeOf(answer), words: wordsOf(answer), status: answer.status }));
994
+ }
995
+ if (answer.status < 200 || answer.status >= 300)
996
+ throw answerError(answer);
997
+ return answer;
998
+ }
999
+ }
1000
+ catch (error) {
1001
+ if (!(error instanceof ReadRecoveryExpired) || !recovery)
1002
+ throw error;
1003
+ unchanged();
1004
+ throw answerError(recovery.latest);
1005
+ }
1006
+ }
1007
+ /** The pair a call presents, refreshed first near its expiry; the
1008
+ * refresh waits out the host's rate limit where the call does
1009
+ * (git-host-21). */
1010
+ async current(waits = false) {
1011
+ const stored = await this.credentials.read();
1012
+ if (!stored)
1013
+ throw new HostError("reauth", { code: "signed_out" });
1014
+ if (stored.accessExpiresAt - this.now() < REFRESH_MARGIN_MS)
1015
+ return this.refresh(stored, waits);
1016
+ return stored;
1017
+ }
1018
+ /** One refresh at a time: a caller arriving while one runs joins it,
1019
+ * and one arriving after it finds the rotated pair already stored.
1020
+ * Where another pair replaced the refreshed one meanwhile, the answer
1021
+ * stores and removes nothing, and `CredentialChanged` is thrown. */
1022
+ refresh(stale, waits = false) {
1023
+ if (this.refreshing)
1024
+ return this.refreshing;
1025
+ const tracked = this.runRefresh(stale, waits).finally(() => {
1026
+ if (this.refreshing === tracked)
1027
+ this.refreshing = null;
1028
+ });
1029
+ this.refreshing = tracked;
1030
+ return tracked;
1031
+ }
1032
+ async runRefresh(stale, waits) {
1033
+ const latest = await this.credentials.read();
1034
+ if (!latest)
1035
+ throw new HostError("reauth", { code: "signed_out" });
1036
+ if (latest.access !== stale.access && latest.accessExpiresAt - this.now() >= REFRESH_MARGIN_MS)
1037
+ return latest;
1038
+ const answer = await this.send("POST", "/api/v1/auth/token", {
1039
+ body: { scope: this.scope, grant_type: "refresh_token", refresh_token: latest.refresh, client_id: this.clientId },
1040
+ wait: waits,
1041
+ });
1042
+ if (answer.status === 200) {
1043
+ const next = tokenFrom(answer, this.now());
1044
+ if (!this.credentials.replace(latest, next))
1045
+ throw new CredentialChanged();
1046
+ return next;
1047
+ }
1048
+ const error = answerError(answer);
1049
+ if (error.kind === "unreachable" || error.kind === "rate_limited")
1050
+ throw error;
1051
+ throw this.signOutLocally(latest, new HostError("reauth", { code: codeOf(answer), words: wordsOf(answer), status: answer.status }));
1052
+ }
1053
+ /** The host refused `used` (git-host-4): remove it and say the device
1054
+ * is signed out in the same turn, giving back `refusal` to throw;
1055
+ * where another pair is stored in its place, nothing is removed or
1056
+ * said, and `CredentialChanged` comes back instead. */
1057
+ signOutLocally(used, refusal) {
1058
+ if (!this.credentials.replace(used, null))
1059
+ return new CredentialChanged();
1060
+ try {
1061
+ this.onSignedOut?.("reauth");
1062
+ }
1063
+ catch {
1064
+ // The listener's failure is its own.
1065
+ }
1066
+ return refusal;
1067
+ }
1068
+ /** Wait out the host's rate limit (git-host-21): until the instant it
1069
+ * holds, again where a later answer moves it on meanwhile; `signal`
1070
+ * ends the wait. The timer keeps no process alive. */
1071
+ async waitOut(signal, recovery) {
1072
+ for (;;) {
1073
+ if (signal?.aborted)
1074
+ throw new HostWaitStopped();
1075
+ if (recovery && (recovery.signal.aborted || this.now() >= recovery.until))
1076
+ throw new ReadRecoveryExpired();
1077
+ const ms = this.holdUntil - this.now();
1078
+ if (ms <= 0)
1079
+ return;
1080
+ try {
1081
+ const waiting = recovery ? AbortSignal.any([recovery.signal, ...(signal ? [signal] : [])]) : signal;
1082
+ await sleep(ms, undefined, { ref: false, ...(waiting ? { signal: waiting } : {}) });
1083
+ }
1084
+ catch {
1085
+ if (!signal?.aborted && recovery?.signal.aborted)
1086
+ throw new ReadRecoveryExpired();
1087
+ throw new HostWaitStopped();
1088
+ }
1089
+ }
1090
+ }
1091
+ /** An answer of 429 holds the calls until the instant it asks for —
1092
+ * its time plus its seconds, `holdMaxMs` at most — keeping a later
1093
+ * instant already held; none where its seconds are unknown
1094
+ * (git-host-21). */
1095
+ hold(retryAfter, answeredAt) {
1096
+ const seconds = retryAfterSeconds(retryAfter, answeredAt);
1097
+ if (seconds === null || seconds <= 0)
1098
+ return;
1099
+ const until = answeredAt + Math.min(seconds * 1000, this.holdMaxMs);
1100
+ if (until <= this.holdUntil)
1101
+ return;
1102
+ this.holdUntil = until;
1103
+ try {
1104
+ this.onHold?.(until);
1105
+ }
1106
+ catch {
1107
+ // The listener's failure is its own.
1108
+ }
1109
+ }
1110
+ /** A call that does not wait, made while the hold stands, is refused
1111
+ * at once as the host asking to wait the seconds that remain
1112
+ * (git-host-21). */
1113
+ refuseWhileHeld() {
1114
+ const ms = this.holdUntil - this.now();
1115
+ if (ms > 0)
1116
+ throw new HostError("rate_limited", { code: "rate_limited", retryAfter: String(Math.ceil(ms / 1000)) });
1117
+ }
1118
+ /** One request to the host. A call carrying a signal, or asked to
1119
+ * wait, waits out the host's rate limit first; any other is refused
1120
+ * while it holds (git-host-21). */
1121
+ async send(method, path, init) {
1122
+ if (init.signal !== undefined || init.wait === true)
1123
+ await this.waitOut(init.signal, init.recovery);
1124
+ else
1125
+ this.refuseWhileHeld();
1126
+ init.beforeSend?.();
1127
+ const headers = { accept: "application/json" };
1128
+ if (init.body !== undefined)
1129
+ headers["content-type"] = "application/json";
1130
+ if (init.bearer !== undefined)
1131
+ headers.authorization = `Bearer ${init.bearer}`;
1132
+ let response;
1133
+ let raw;
1134
+ const timeout = AbortSignal.timeout(this.requestTimeoutMs);
1135
+ const transport = init.recovery ? AbortSignal.any([timeout, init.recovery.signal]) : timeout;
1136
+ try {
1137
+ response = await this.fetchImpl(`${this.url}${path}`, {
1138
+ method,
1139
+ headers,
1140
+ body: init.body === undefined ? undefined : JSON.stringify(init.body),
1141
+ redirect: "manual",
1142
+ signal: transport,
1143
+ });
1144
+ raw = await response.text();
1145
+ }
1146
+ catch {
1147
+ if (init.recovery?.signal.aborted && transport.reason === init.recovery.signal.reason)
1148
+ throw new ReadRecoveryExpired();
1149
+ throw new HostError("unreachable", { code: null, words: null });
1150
+ }
1151
+ const retryAfter = response.headers.get("retry-after");
1152
+ if (response.status === 429)
1153
+ this.hold(retryAfter, this.now());
1154
+ let json = null;
1155
+ if (raw.length > 0) {
1156
+ try {
1157
+ json = JSON.parse(raw);
1158
+ }
1159
+ catch {
1160
+ json = null;
1161
+ }
1162
+ }
1163
+ return { status: response.status, json, retryAfter };
1164
+ }
1165
+ }
1166
+ // ---------------------------------------------------------------------------
1167
+ // Wire shapes: snake_case in, camelCase out
1168
+ function isRecord(value) {
1169
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1170
+ }
1171
+ function record(value) {
1172
+ if (!isRecord(value))
1173
+ throw new HostError("unreachable", { code: "malformed_answer" });
1174
+ return value;
1175
+ }
1176
+ function list(value) {
1177
+ if (!Array.isArray(value))
1178
+ throw new HostError("unreachable", { code: "malformed_answer" });
1179
+ return value;
1180
+ }
1181
+ function text(value) {
1182
+ if (typeof value === "string")
1183
+ return value;
1184
+ if (typeof value === "number" && Number.isFinite(value))
1185
+ return String(value);
1186
+ throw new HostError("unreachable", { code: "malformed_answer" });
1187
+ }
1188
+ function optionalText(value) {
1189
+ return typeof value === "string" ? value : typeof value === "number" && Number.isFinite(value) ? String(value) : null;
1190
+ }
1191
+ function flag(value) {
1192
+ return value === true;
1193
+ }
1194
+ function optionalFlag(value) {
1195
+ return typeof value === "boolean" ? value : null;
1196
+ }
1197
+ function positive(value, fallback) {
1198
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
1199
+ }
1200
+ function accountFrom(value) {
1201
+ const body = record(value);
1202
+ return { id: text(body.id), login: text(body.login), displayName: optionalText(body.display_name), canCreateGroup: flag(body.can_create_group) };
1203
+ }
1204
+ function groupFrom(value) {
1205
+ const body = record(value);
1206
+ const can = isRecord(body.can) ? body.can : {};
1207
+ return {
1208
+ id: optionalText(body.id),
1209
+ fullPath: text(body.full_path),
1210
+ name: text(body.name),
1211
+ kind: body.kind === "user" ? "user" : "group",
1212
+ can: { createSubgroup: flag(can.create_subgroup), manageMembers: flag(can.manage_members), rename: flag(can.rename), delete: flag(can.delete), ...(can.restore === true ? { restore: true } : {}) },
1213
+ ...(body.pending_deletion === true ? { pendingDeletion: true } : {}),
1214
+ ...(typeof body.deletion_root === "string" ? { deletionRoot: body.deletion_root } : {}),
1215
+ };
1216
+ }
1217
+ function serverFrom(value) {
1218
+ const body = record(value);
1219
+ const { can: _can, ...group } = groupFrom(body.group);
1220
+ return { id: text(body.id), name: text(body.name), group, address: text(body.address) };
1221
+ }
1222
+ function roleFrom(value) {
1223
+ const body = record(value);
1224
+ return { id: text(body.id), name: text(body.name), mayPush: flag(body.may_push) };
1225
+ }
1226
+ /** The members route of a group or a repository at the host. */
1227
+ function membersPath(target) {
1228
+ return `/api/v1/host/${target.kind === "group" ? "groups" : "repositories"}/${encodeURIComponent(target.id)}/members`;
1229
+ }
1230
+ function repositoryFrom(value) {
1231
+ const body = record(value);
1232
+ return {
1233
+ id: text(body.id),
1234
+ name: text(body.name),
1235
+ path: text(body.path),
1236
+ group: groupFrom(body.group),
1237
+ remoteUrl: text(body.remote_url),
1238
+ visibility: text(body.visibility),
1239
+ archived: flag(body.archived),
1240
+ empty: flag(body.empty),
1241
+ lfs: flag(body.lfs),
1242
+ spexBranch: flag(body.spex_branch),
1243
+ project: isRecord(body.project) ? body.project : null,
1244
+ can: { manageMembers: isRecord(body.can) && flag(body.can.manage_members), transfer: isRecord(body.can) && flag(body.can.transfer) },
1245
+ };
1246
+ }
1247
+ function detailFrom(body) {
1248
+ const readOnly = isRecord(body.read_only)
1249
+ ? { reason: body.read_only.reason === "archived" ? "archived" : "access", message: optionalText(body.read_only.message) ?? "" }
1250
+ : null;
1251
+ const branch = isRecord(body.branch) ? body.branch : {};
1252
+ return {
1253
+ ...repositoryFrom(body),
1254
+ readOnly,
1255
+ branch: {
1256
+ present: flag(branch.present),
1257
+ canPush: optionalFlag(branch.can_push),
1258
+ protected: optionalFlag(branch.protected),
1259
+ blocked: flag(branch.blocked),
1260
+ },
1261
+ };
1262
+ }
1263
+ function memberFrom(value) {
1264
+ const body = record(value);
1265
+ return {
1266
+ id: text(body.id),
1267
+ login: text(body.login),
1268
+ displayName: optionalText(body.display_name),
1269
+ role: text(body.role),
1270
+ // A host that says nothing of the source lists the member as the
1271
+ // group's or repository's own.
1272
+ direct: typeof body.direct === "boolean" ? body.direct : true,
1273
+ via: body.direct === false ? optionalText(body.via) : null,
1274
+ };
1275
+ }
1276
+ function tokenFrom(answer, now) {
1277
+ const body = record(answer.json);
1278
+ return {
1279
+ access: text(body.access_token),
1280
+ accessExpiresAt: now + positive(body.expires_in, 3600) * 1000,
1281
+ refresh: text(body.refresh_token),
1282
+ };
1283
+ }
1284
+ function pendingWords(body) {
1285
+ return optionalText(body.message) ?? "";
1286
+ }
1287
+ /** The envelope `{error: {code, message}}`, or OAuth's flat `{error,
1288
+ * error_description}`. */
1289
+ function envelopeOf(answer) {
1290
+ if (!isRecord(answer.json))
1291
+ return { code: null, message: null };
1292
+ const error = answer.json.error;
1293
+ if (isRecord(error))
1294
+ return { code: optionalText(error.code), message: optionalText(error.message) };
1295
+ if (typeof error === "string")
1296
+ return { code: error, message: optionalText(answer.json.error_description) };
1297
+ return { code: null, message: null };
1298
+ }
1299
+ function codeOf(answer) {
1300
+ return envelopeOf(answer).code;
1301
+ }
1302
+ function wordsOf(answer) {
1303
+ return envelopeOf(answer).message;
1304
+ }
1305
+ /** A failure answer as its kind (git-host-4, git-host-11). */
1306
+ function answerError(answer) {
1307
+ const { code, message } = envelopeOf(answer);
1308
+ const base = { code, words: message, status: answer.status };
1309
+ if (answer.status === 429 || code === "rate_limited")
1310
+ return new HostError("rate_limited", { ...base, retryAfter: answer.retryAfter });
1311
+ if (code === "provider_unavailable" || answer.status >= 500)
1312
+ return new HostError("unreachable", base);
1313
+ if (code === "name_taken" || answer.status === 409)
1314
+ return new HostError("name_taken", base);
1315
+ if (code === "not_found" || answer.status === 404)
1316
+ return new HostError("not_found", base);
1317
+ if (code === "host_refused")
1318
+ return new HostError("host_refused", base);
1319
+ if (code !== null && REAUTH_CODES.has(code))
1320
+ return new HostError("reauth", base);
1321
+ if (answer.status === 401)
1322
+ return new HostError("reauth", base);
1323
+ if (code === "bad_request" || answer.status === 400)
1324
+ return new HostError("bad_request", base);
1325
+ return new HostError("host_refused", base);
1326
+ }
1327
+ /** A refused token exchange ends the sign-in `refused` with the host's
1328
+ * words; no answer ends it `unreachable`. */
1329
+ function exchangeError(answer) {
1330
+ const error = answerError(answer);
1331
+ if (error.kind === "unreachable" || error.kind === "rate_limited") {
1332
+ return new HostError("unreachable", { code: error.code, words: error.words, status: error.status, retryAfter: error.retryAfter, cause: "unreachable" });
1333
+ }
1334
+ return signInError("refused", { code: error.code, words: error.words, status: error.status });
1335
+ }
1336
+ function signInError(cause, extra = {}) {
1337
+ return new HostError(cause === "unreachable" ? "unreachable" : "reauth", { ...extra, cause });
1338
+ }
1339
+ function asSignInError(error) {
1340
+ if (error instanceof HostError) {
1341
+ if (error.cause)
1342
+ return error;
1343
+ if (error.kind === "unreachable" || error.kind === "rate_limited") {
1344
+ return new HostError("unreachable", { code: error.code, words: error.words, status: error.status, cause: "unreachable" });
1345
+ }
1346
+ return signInError("refused", { code: error.code, words: error.words, status: error.status });
1347
+ }
1348
+ return new HostError("unreachable", { cause: "unreachable" });
1349
+ }
1350
+ function respond(response, status, body, after) {
1351
+ response.on("finish", after);
1352
+ response.on("close", after);
1353
+ response.writeHead(status, {
1354
+ "content-type": "text/html; charset=utf-8",
1355
+ "cache-control": "no-store",
1356
+ connection: "close",
1357
+ });
1358
+ response.end(body);
1359
+ }
1360
+ function base64url(bytes) {
1361
+ return bytes.toString("base64url");
1362
+ }
1363
+ //# sourceMappingURL=git-host.js.map