sedum-cli 0.1.0-alpha.17 → 0.1.0-alpha.20

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.
@@ -41,6 +41,19 @@ function affectedPathIgnored(file, patterns) {
41
41
 
42
42
  // src/config.ts
43
43
  var CONFIG_FILE = "sedum.config.yaml";
44
+ var integrationCredentials = [
45
+ "TYPESAFE_API_KEY",
46
+ "OPENROUTER_API_KEY",
47
+ "OPEN_ROUTER_API_KEY",
48
+ "CLOUDFLARE_ACCOUNT_ID",
49
+ "CLOUDFLARE_AUTH_TOKEN",
50
+ "CLOUDFLARE_API_TOKEN",
51
+ "SEDUM_UPLOAD_TOKEN",
52
+ "SEDUM_READ_TOKEN"
53
+ ];
54
+ function removeIntegrationCredentials(variables) {
55
+ for (const name of integrationCredentials) variables[name] = void 0;
56
+ }
44
57
  var ProjectConfigError = class extends Error {
45
58
  constructor(diagnostics) {
46
59
  super(diagnostics[0]?.message ?? "The Sedum configuration is invalid.");
@@ -62,7 +75,8 @@ var DEFAULTS = {
62
75
  },
63
76
  outputDir: ".sedum/runs",
64
77
  reporterDir: ".sedum/reports",
65
- vision: { enabled: false }
78
+ vision: { enabled: false },
79
+ stepTimeoutMs: 5e3
66
80
  };
67
81
  var DEFAULT_PROVIDER_BASE_URL = "https://api.typesafe.ai";
68
82
  var DEFAULT_PROVIDER_MODEL = "jev-latest";
@@ -81,13 +95,20 @@ var allowed = {
81
95
  "environments",
82
96
  "vision",
83
97
  "provider",
84
- "screenshots"
98
+ "screenshots",
99
+ "stepTimeoutMs"
85
100
  ]),
86
101
  tests: /* @__PURE__ */ new Set(["directory", "include", "exclude"]),
87
102
  affected: /* @__PURE__ */ new Set(["ignore"]),
88
103
  viewport: /* @__PURE__ */ new Set(["width", "height"]),
89
104
  thresholds: /* @__PURE__ */ new Set(["verify", "lowConfidenceBand", "contradiction"]),
90
- environment: /* @__PURE__ */ new Set(["baseUrl", "variables", "provider"]),
105
+ environment: /* @__PURE__ */ new Set([
106
+ "baseUrl",
107
+ "browser",
108
+ "variables",
109
+ "provider",
110
+ "stepTimeoutMs"
111
+ ]),
91
112
  vision: /* @__PURE__ */ new Set(["enabled"]),
92
113
  provider: /* @__PURE__ */ new Set(["name", "model", "apiKeyEnv"])
93
114
  };
@@ -104,6 +125,71 @@ function diagnostic(diagnostics, file, counter, node, key, code, message, fix) {
104
125
  fix
105
126
  });
106
127
  }
128
+ function isBrowserKind(value) {
129
+ return value === "chrome" || value === "chromium";
130
+ }
131
+ function browserSetting(settings) {
132
+ const name = settings.environmentName;
133
+ const candidates = [
134
+ { value: settings.flag, source: "--browser", origin: "<command line>" },
135
+ {
136
+ value: settings.host?.trim() || void 0,
137
+ source: "SEDUM_BROWSER",
138
+ origin: "<process environment>"
139
+ },
140
+ {
141
+ value: settings.file?.trim() || void 0,
142
+ source: "SEDUM_BROWSER",
143
+ origin: ".env"
144
+ },
145
+ {
146
+ value: typeof name === "string" ? settings.environment : void 0,
147
+ source: `environments.${String(name)}.browser`,
148
+ origin: null
149
+ },
150
+ { value: settings.root, source: "browser", origin: null }
151
+ ];
152
+ return candidates.find((candidate) => candidate.value !== void 0) ?? {
153
+ value: DEFAULTS.browser,
154
+ source: "default",
155
+ origin: null
156
+ };
157
+ }
158
+ function reportInvalidConfigBrowsers(raw, sink) {
159
+ const layers = [["browser", raw.browser]];
160
+ for (const [name, value] of Object.entries(environmentMap(raw)))
161
+ if (object(value))
162
+ layers.push([`environments.${name}.browser`, value.browser]);
163
+ for (const [key, value] of layers)
164
+ if (value !== void 0 && !isBrowserKind(value))
165
+ reportInvalidBrowser(sink, sink.file, sink.node(key), key);
166
+ }
167
+ function reportInvalidBrowser(sink, file, node, key) {
168
+ diagnostic(
169
+ sink.diagnostics,
170
+ file,
171
+ sink.counter,
172
+ node,
173
+ key,
174
+ "invalid_config_browser",
175
+ `\`${key}\` must be \`chrome\` or \`chromium\`.`,
176
+ "Choose one of the supported browser names."
177
+ );
178
+ }
179
+ function resolveBrowser(raw, settings, sink, environmentFile) {
180
+ reportInvalidConfigBrowsers(raw, sink);
181
+ const setting = browserSetting(settings);
182
+ if (isBrowserKind(setting.value))
183
+ return { browser: setting.value, source: setting.source };
184
+ if (setting.origin)
185
+ reportInvalidBrowser(
186
+ sink,
187
+ setting.origin === ".env" ? environmentFile : setting.origin,
188
+ void 0,
189
+ setting.source
190
+ );
191
+ return { browser: DEFAULTS.browser, source: setting.source };
192
+ }
107
193
  var REMOVED_KEYS = {
108
194
  "vision.model": "Vision fallback now uses the TypeSafe provider's image model.",
109
195
  "vision.timeoutMs": "Vision fallback now uses the TypeSafe provider's request deadline.",
@@ -182,14 +268,7 @@ function scalarVariables(value, key, diagnostics, file, counter, node) {
182
268
  }
183
269
  const result = {};
184
270
  for (const [name, item] of Object.entries(value)) {
185
- if ([
186
- "TYPESAFE_API_KEY",
187
- "OPENROUTER_API_KEY",
188
- "OPEN_ROUTER_API_KEY",
189
- "CLOUDFLARE_ACCOUNT_ID",
190
- "CLOUDFLARE_AUTH_TOKEN",
191
- "CLOUDFLARE_API_TOKEN"
192
- ].includes(name)) {
271
+ if (integrationCredentials.includes(name)) {
193
272
  diagnostic(
194
273
  diagnostics,
195
274
  file,
@@ -284,6 +363,69 @@ function positiveInteger(value, fallback, key, diagnostics, file, counter, node)
284
363
  }
285
364
  return value;
286
365
  }
366
+ function validStepTimeout(value) {
367
+ if (!Number.isSafeInteger(value)) return false;
368
+ return value >= 0 && value <= 12e4;
369
+ }
370
+ function reportNonMappingSections(raw, sink) {
371
+ const { diagnostics, file, counter, node } = sink;
372
+ if (raw.tests !== void 0 && !object(raw.tests))
373
+ diagnostic(
374
+ diagnostics,
375
+ file,
376
+ counter,
377
+ node("tests"),
378
+ "tests",
379
+ "invalid_config_type",
380
+ "Configuration key `tests` must be a mapping.",
381
+ "Use `tests: { directory: tests }`."
382
+ );
383
+ for (const [key, value] of [
384
+ ["affected", raw.affected],
385
+ ["viewport", raw.viewport],
386
+ ["thresholds", raw.thresholds],
387
+ ["environments", raw.environments],
388
+ ["vision", raw.vision],
389
+ ["provider", raw.provider]
390
+ ])
391
+ if (value !== void 0 && !object(value))
392
+ diagnostic(
393
+ diagnostics,
394
+ file,
395
+ counter,
396
+ node(key),
397
+ key,
398
+ "invalid_config_type",
399
+ `Configuration key \`${key}\` must be a mapping.`,
400
+ `Write \`${key}: {}\` and add its documented child keys.`
401
+ );
402
+ }
403
+ function reportInvalidStepTimeouts(raw, environments, sink) {
404
+ const layers = [["stepTimeoutMs", raw.stepTimeoutMs]];
405
+ for (const [name, value] of Object.entries(environments))
406
+ if (object(value))
407
+ layers.push([`environments.${name}.stepTimeoutMs`, value.stepTimeoutMs]);
408
+ for (const [key, value] of layers) {
409
+ if (value === void 0 || validStepTimeout(value)) continue;
410
+ diagnostic(
411
+ sink.diagnostics,
412
+ sink.file,
413
+ sink.counter,
414
+ sink.node(key),
415
+ key,
416
+ "invalid_config_step_timeout",
417
+ `Configuration key \`${key}\` must be a whole number of milliseconds from 0 to 120000.`,
418
+ "Use a value such as 30000 for 30 seconds, or 0 to judge each step once."
419
+ );
420
+ }
421
+ }
422
+ function resolveStepTimeout(raw, environment, sink) {
423
+ reportInvalidStepTimeouts(raw, environmentMap(raw), sink);
424
+ return [environment.stepTimeoutMs, raw.stepTimeoutMs].find(validStepTimeout) ?? DEFAULTS.stepTimeoutMs;
425
+ }
426
+ function environmentMap(raw) {
427
+ return object(raw.environments) ? raw.environments : {};
428
+ }
287
429
  function stringList(value, fallback, key, diagnostics, file, counter, node) {
288
430
  if (value === void 0) return [...fallback];
289
431
  if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || !item)) {
@@ -383,159 +525,132 @@ function freeze(config) {
383
525
  Object.freeze(config.credentialValues);
384
526
  return Object.freeze(config);
385
527
  }
386
- async function loadProjectConfig(start = process.cwd(), hostEnvironment = process.env, overrides = {}, loadOptions = {}) {
387
- const found = await findConfig(start);
388
- const file = found.file ?? path.join(found.root, CONFIG_FILE);
389
- const counter = new LineCounter();
390
- const diagnostics = [];
528
+ async function readConfigDocument(file, counter, diagnostics) {
391
529
  let raw = {};
392
- let document = null;
393
- if (found.file) {
394
- const contents = await readFile(found.file, "utf8");
395
- document = parseDocument(contents, {
396
- lineCounter: counter,
397
- strict: true,
398
- uniqueKeys: true
399
- });
400
- for (const error of document.errors)
530
+ const contents = await readFile(file, "utf8");
531
+ const document = parseDocument(contents, {
532
+ lineCounter: counter,
533
+ strict: true,
534
+ uniqueKeys: true
535
+ });
536
+ for (const error of document.errors)
537
+ diagnostic(
538
+ diagnostics,
539
+ file,
540
+ counter,
541
+ void 0,
542
+ "<yaml>",
543
+ "invalid_config_yaml",
544
+ `Could not parse ${CONFIG_FILE}: ${error.message}`,
545
+ "Correct the YAML syntax and duplicate keys."
546
+ );
547
+ let unsafeYaml = false;
548
+ visit(document, {
549
+ Alias(_key, alias) {
550
+ unsafeYaml = true;
401
551
  diagnostic(
402
552
  diagnostics,
403
553
  file,
404
554
  counter,
405
- void 0,
555
+ alias,
406
556
  "<yaml>",
407
- "invalid_config_yaml",
408
- `Could not parse ${CONFIG_FILE}: ${error.message}`,
409
- "Correct the YAML syntax and duplicate keys."
557
+ "unsupported_config_alias",
558
+ "YAML aliases are not supported in sedum.config.yaml.",
559
+ "Write the value explicitly instead of using an anchor or alias."
410
560
  );
411
- let unsafeYaml = false;
412
- visit(document, {
413
- Alias(_key, alias) {
561
+ },
562
+ Node(_key, value2) {
563
+ if ("tag" in value2 && value2.tag) {
414
564
  unsafeYaml = true;
415
565
  diagnostic(
416
566
  diagnostics,
417
567
  file,
418
568
  counter,
419
- alias,
569
+ value2,
420
570
  "<yaml>",
421
- "unsupported_config_alias",
422
- "YAML aliases are not supported in sedum.config.yaml.",
423
- "Write the value explicitly instead of using an anchor or alias."
571
+ "unsupported_config_tag",
572
+ "YAML tags are not supported in sedum.config.yaml.",
573
+ "Use ordinary YAML scalar, mapping, and sequence values."
424
574
  );
425
- },
426
- Node(_key, value2) {
427
- if ("tag" in value2 && value2.tag) {
428
- unsafeYaml = true;
429
- diagnostic(
430
- diagnostics,
431
- file,
432
- counter,
433
- value2,
434
- "<yaml>",
435
- "unsupported_config_tag",
436
- "YAML tags are not supported in sedum.config.yaml.",
437
- "Use ordinary YAML scalar, mapping, and sequence values."
438
- );
439
- }
440
575
  }
441
- });
442
- let value = {};
443
- if (!unsafeYaml)
444
- try {
445
- value = document.toJS({ maxAliasCount: 0 });
446
- } catch {
447
- diagnostic(
448
- diagnostics,
449
- file,
450
- counter,
451
- document.contents,
452
- "<yaml>",
453
- "invalid_config_yaml",
454
- `Could not safely decode ${CONFIG_FILE}.`,
455
- "Remove aliases, tags, or recursive YAML structures."
456
- );
457
- }
458
- if (value !== null && !object(value))
576
+ }
577
+ });
578
+ let value = {};
579
+ if (!unsafeYaml)
580
+ try {
581
+ value = document.toJS({ maxAliasCount: 0 });
582
+ } catch {
459
583
  diagnostic(
460
584
  diagnostics,
461
585
  file,
462
586
  counter,
463
587
  document.contents,
464
- "<root>",
465
- "invalid_config_root",
466
- `${CONFIG_FILE} must contain a YAML mapping.`,
467
- "Write configuration as key/value pairs."
588
+ "<yaml>",
589
+ "invalid_config_yaml",
590
+ `Could not safely decode ${CONFIG_FILE}.`,
591
+ "Remove aliases, tags, or recursive YAML structures."
468
592
  );
469
- else raw = value ?? {};
470
- mapUnknownKeys(
593
+ }
594
+ if (value !== null && !object(value))
595
+ diagnostic(
596
+ diagnostics,
597
+ file,
598
+ counter,
471
599
  document.contents,
472
- allowed.root,
473
- "",
600
+ "<root>",
601
+ "invalid_config_root",
602
+ `${CONFIG_FILE} must contain a YAML mapping.`,
603
+ "Write configuration as key/value pairs."
604
+ );
605
+ else raw = value ?? {};
606
+ mapUnknownKeys(
607
+ document.contents,
608
+ allowed.root,
609
+ "",
610
+ file,
611
+ counter,
612
+ diagnostics
613
+ );
614
+ const maps = [
615
+ ["tests", allowed.tests],
616
+ ["affected", allowed.affected],
617
+ ["viewport", allowed.viewport],
618
+ ["thresholds", allowed.thresholds],
619
+ ["vision", allowed.vision],
620
+ ["provider", allowed.provider]
621
+ ];
622
+ for (const [key, names] of maps)
623
+ mapUnknownKeys(
624
+ document.get(key, true),
625
+ names,
626
+ key,
474
627
  file,
475
628
  counter,
476
629
  diagnostics
477
630
  );
478
- const maps = [
479
- ["tests", allowed.tests],
480
- ["affected", allowed.affected],
481
- ["viewport", allowed.viewport],
482
- ["thresholds", allowed.thresholds],
483
- ["vision", allowed.vision],
484
- ["provider", allowed.provider]
485
- ];
486
- for (const [key, names] of maps)
631
+ const environmentNode = document.get("environments", true);
632
+ if (isMap(environmentNode))
633
+ for (const pair of environmentNode.items)
487
634
  mapUnknownKeys(
488
- document.get(key, true),
489
- names,
490
- key,
635
+ pair.value,
636
+ allowed.environment,
637
+ `environments.${String(pair.key)}`,
491
638
  file,
492
639
  counter,
493
640
  diagnostics
494
641
  );
495
- const environmentNode = document.get("environments", true);
496
- if (isMap(environmentNode))
497
- for (const pair of environmentNode.items)
498
- mapUnknownKeys(
499
- pair.value,
500
- allowed.environment,
501
- `environments.${String(pair.key)}`,
502
- file,
503
- counter,
504
- diagnostics
505
- );
506
- }
642
+ return { raw, document };
643
+ }
644
+ async function loadProjectConfig(start = process.cwd(), hostEnvironment = process.env, overrides = {}, loadOptions = {}) {
645
+ const found = await findConfig(start);
646
+ const file = found.file ?? path.join(found.root, CONFIG_FILE);
647
+ const counter = new LineCounter();
648
+ const diagnostics = [];
649
+ const { raw, document } = found.file ? await readConfigDocument(found.file, counter, diagnostics) : { raw: {}, document: null };
507
650
  const node = (key) => document?.getIn(key.split("."), true);
651
+ const sink = { diagnostics, file, counter, node };
652
+ reportNonMappingSections(raw, sink);
508
653
  const tests = object(raw.tests) ? raw.tests : {};
509
- if (raw.tests !== void 0 && !object(raw.tests))
510
- diagnostic(
511
- diagnostics,
512
- file,
513
- counter,
514
- node("tests"),
515
- "tests",
516
- "invalid_config_type",
517
- "Configuration key `tests` must be a mapping.",
518
- "Use `tests: { directory: tests }`."
519
- );
520
- for (const [key, value] of [
521
- ["affected", raw.affected],
522
- ["viewport", raw.viewport],
523
- ["thresholds", raw.thresholds],
524
- ["environments", raw.environments],
525
- ["vision", raw.vision],
526
- ["provider", raw.provider]
527
- ])
528
- if (value !== void 0 && !object(value))
529
- diagnostic(
530
- diagnostics,
531
- file,
532
- counter,
533
- node(key),
534
- key,
535
- "invalid_config_type",
536
- `Configuration key \`${key}\` must be a mapping.`,
537
- `Write \`${key}: {}\` and add its documented child keys.`
538
- );
539
654
  const viewport = object(raw.viewport) ? raw.viewport : {};
540
655
  const affected = object(raw.affected) ? raw.affected : {};
541
656
  const affectedIgnore = stringList(
@@ -650,19 +765,6 @@ async function loadProjectConfig(start = process.cwd(), hostEnvironment = proces
650
765
  }
651
766
  const selectedProvider = object(environment.provider) ? environment.provider : {};
652
767
  const apiKeyEnv = selectedProvider.apiKeyEnv ?? provider.apiKeyEnv;
653
- const browserValue = overrides.browser ?? raw.browser ?? DEFAULTS.browser;
654
- const browser = browserValue === "chrome" || browserValue === "chromium" ? browserValue : DEFAULTS.browser;
655
- if (browserValue !== "chrome" && browserValue !== "chromium")
656
- diagnostic(
657
- diagnostics,
658
- file,
659
- counter,
660
- node("browser"),
661
- "browser",
662
- "invalid_config_browser",
663
- "Configuration key `browser` must be `chrome` or `chromium`.",
664
- "Choose one of the supported browser names."
665
- );
666
768
  const verify = probability(
667
769
  overrides.thresholds?.minP ?? thresholds.verify,
668
770
  DEFAULTS.thresholds.minP,
@@ -731,7 +833,7 @@ async function loadProjectConfig(start = process.cwd(), hostEnvironment = proces
731
833
  const environmentFile = path.join(found.root, ".env");
732
834
  try {
733
835
  if (loadOptions.readEnvironmentFile !== false)
734
- fileEnvironment = parseEnv(await readFile(environmentFile, "utf8"));
836
+ fileEnvironment = await readProjectEnvironment(found.root);
735
837
  } catch (error) {
736
838
  if (error.code !== "ENOENT")
737
839
  diagnostic(
@@ -745,6 +847,20 @@ async function loadProjectConfig(start = process.cwd(), hostEnvironment = proces
745
847
  "Correct its dotenv syntax and permissions, or remove it."
746
848
  );
747
849
  }
850
+ const browserChoice = resolveBrowser(
851
+ raw,
852
+ {
853
+ flag: overrides.browser,
854
+ host: hostEnvironment.SEDUM_BROWSER,
855
+ file: fileEnvironment.SEDUM_BROWSER,
856
+ environment: environment.browser,
857
+ environmentName: selected,
858
+ root: raw.browser
859
+ },
860
+ sink,
861
+ environmentFile
862
+ );
863
+ const browser = browserChoice.browser;
748
864
  const include = stringList(
749
865
  tests.include,
750
866
  DEFAULTS.include,
@@ -895,11 +1011,7 @@ async function loadProjectConfig(start = process.cwd(), hostEnvironment = proces
895
1011
  );
896
1012
  }
897
1013
  }
898
- variables["OPENROUTER_API_KEY"] = void 0;
899
- variables.OPEN_ROUTER_API_KEY = void 0;
900
- variables.CLOUDFLARE_ACCOUNT_ID = void 0;
901
- variables.CLOUDFLARE_AUTH_TOKEN = void 0;
902
- variables.CLOUDFLARE_API_TOKEN = void 0;
1014
+ removeIntegrationCredentials(variables);
903
1015
  const visionEnabledValue = overrides.vision?.enabled ?? vision.enabled;
904
1016
  const visionEnabled = visionEnabledValue ?? DEFAULTS.vision.enabled;
905
1017
  if (typeof visionEnabled !== "boolean")
@@ -974,6 +1086,7 @@ async function loadProjectConfig(start = process.cwd(), hostEnvironment = proces
974
1086
  counter,
975
1087
  node("viewport.height")
976
1088
  );
1089
+ const stepTimeoutMs = resolveStepTimeout(raw, environment, sink);
977
1090
  if (diagnostics.length) throw new ProjectConfigError(diagnostics);
978
1091
  return freeze({
979
1092
  projectRoot: found.root,
@@ -984,6 +1097,7 @@ async function loadProjectConfig(start = process.cwd(), hostEnvironment = proces
984
1097
  exclude,
985
1098
  affected: { ignore: affectedIgnore },
986
1099
  browser,
1100
+ browserSource: browserChoice.source,
987
1101
  viewport: { width, height },
988
1102
  thresholds: { minP: verify, band, contradictionCutoff },
989
1103
  outputDir,
@@ -998,7 +1112,8 @@ async function loadProjectConfig(start = process.cwd(), hostEnvironment = proces
998
1112
  providerBaseUrl,
999
1113
  providerModel,
1000
1114
  vision: { enabled: visionEnabled === true },
1001
- screenshots: screenshots && providerName !== "clef"
1115
+ screenshots: screenshots && providerName !== "clef",
1116
+ stepTimeoutMs
1002
1117
  });
1003
1118
  }
1004
1119
  async function discoverConfiguredTests(config) {
@@ -0,0 +1,109 @@
1
+ // src/auth-api.ts
2
+ import { z } from "zod";
3
+ var AuthError = class extends Error {
4
+ };
5
+ function cloudOrigin(value) {
6
+ try {
7
+ const url = new URL(value);
8
+ if ([url.username, url.password, url.search, url.hash].some(Boolean))
9
+ throw new Error();
10
+ if (!["/", ""].includes(url.pathname)) throw new Error();
11
+ if (!secureProtocol(url)) throw new Error();
12
+ return url.origin;
13
+ } catch {
14
+ throw new AuthError(
15
+ "Cloud URL must be an HTTPS origin (HTTP is allowed only on loopback), without credentials, path, query or fragment."
16
+ );
17
+ }
18
+ }
19
+ function secureProtocol(url) {
20
+ if (url.protocol === "https:") return true;
21
+ return url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
22
+ }
23
+ var tokensSchema = z.object({
24
+ token_type: z.literal("Bearer"),
25
+ access_token: z.string().min(1),
26
+ refresh_token: z.string().min(1),
27
+ expires_in: z.number().positive().finite()
28
+ });
29
+ var membershipSchema = z.object({
30
+ user: z.object({
31
+ id: z.string(),
32
+ name: z.string().nullable(),
33
+ email: z.string().nullable()
34
+ }),
35
+ organizations: z.array(
36
+ z.object({
37
+ id: z.string(),
38
+ name: z.string(),
39
+ role: z.string(),
40
+ projects: z.array(z.object({ id: z.string(), name: z.string() }))
41
+ })
42
+ )
43
+ });
44
+ async function request(origin, endpoint, signal, options = {}) {
45
+ try {
46
+ const response = await fetch(`${origin}${endpoint}`, {
47
+ redirect: "error",
48
+ signal: AbortSignal.any([signal, AbortSignal.timeout(15e3)]),
49
+ ...requestOptions(options)
50
+ });
51
+ const body = await responseBody(response, endpoint);
52
+ return {
53
+ ok: response.ok,
54
+ status: response.status,
55
+ body,
56
+ retryMs: retryDelay(response.headers.get("retry-after"))
57
+ };
58
+ } catch {
59
+ throw new AuthError(
60
+ signal.aborted ? "Authentication cancelled." : "Cloud request failed or timed out. Check the instance URL and connection; redirects are not allowed."
61
+ );
62
+ }
63
+ }
64
+ async function responseBody(response, endpoint) {
65
+ const readBody = response.ok && endpoint !== "/api/oauth/revoke" || response.status === 400 && endpoint === "/api/oauth/token";
66
+ if (readBody) return response.json();
67
+ await response.body?.cancel().catch(() => {
68
+ });
69
+ return {};
70
+ }
71
+ function requestOptions({
72
+ form,
73
+ access
74
+ }) {
75
+ const headers = {};
76
+ if (access) headers.authorization = `Bearer ${access}`;
77
+ if (!form) return { method: "GET", headers };
78
+ headers["content-type"] = "application/x-www-form-urlencoded";
79
+ return {
80
+ method: "POST",
81
+ headers,
82
+ body: new URLSearchParams({ client_id: "sedum-cli", ...form })
83
+ };
84
+ }
85
+ function retryDelay(retry) {
86
+ if (!retry) return 0;
87
+ const delay = /^\d+$/.test(retry) ? Number(retry) * 1e3 : Math.max(0, Date.parse(retry) - Date.now());
88
+ return Number.isFinite(delay) ? delay : 0;
89
+ }
90
+ function parse(schema, value) {
91
+ const result = schema.safeParse(value);
92
+ if (!result.success)
93
+ throw new AuthError("Cloud returned an invalid authentication response.");
94
+ return result.data;
95
+ }
96
+ function tokenResult(body) {
97
+ const tokens = parse(tokensSchema, body);
98
+ return { ...tokens, expiresAt: Date.now() + tokens.expires_in * 1e3 };
99
+ }
100
+
101
+ export {
102
+ AuthError,
103
+ cloudOrigin,
104
+ tokensSchema,
105
+ membershipSchema,
106
+ request,
107
+ parse,
108
+ tokenResult
109
+ };