@coffre/client 0.4.1 → 0.4.2

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.
@@ -14,7 +14,7 @@ type Api = {
14
14
  isRootAdmin: boolean;
15
15
  canReadAudit: boolean;
16
16
  features: {
17
- mcp: boolean;
17
+ mcp: string | null;
18
18
  workloads: boolean;
19
19
  };
20
20
  environments: {
@@ -445,7 +445,7 @@ type Api = {
445
445
  name: string;
446
446
  host: string | null;
447
447
  registration: "cimd" | "dcr";
448
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
448
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
449
449
  createdAt: string;
450
450
  lastUsedAt: string | null;
451
451
  lastUsedIp: string | null;
@@ -521,7 +521,7 @@ type Api = {
521
521
  name: string;
522
522
  host: string | null;
523
523
  registration: "cimd" | "dcr";
524
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
524
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
525
525
  createdAt: string;
526
526
  lastUsedAt: string | null;
527
527
  lastUsedIp: string | null;
@@ -754,8 +754,8 @@ type Api = {
754
754
  };
755
755
  redirectHost: string;
756
756
  loopbackOnly: boolean;
757
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
758
- connections: ("browse" | "manage-access" | "read-values" | "write")[][];
757
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
758
+ connections: ("manage-access" | "read" | "reveal" | "write")[][];
759
759
  days: number;
760
760
  };
761
761
  };
@@ -786,7 +786,7 @@ type Api = {
786
786
  name: string;
787
787
  host: string | null;
788
788
  registration: "cimd" | "dcr";
789
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
789
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
790
790
  createdAt: string;
791
791
  lastUsedAt: string | null;
792
792
  lastUsedIp: string | null;
@@ -1041,8 +1041,8 @@ type AuthorizationView = {
1041
1041
  };
1042
1042
  redirectHost: string;
1043
1043
  loopbackOnly: boolean;
1044
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
1045
- connections: ("browse" | "manage-access" | "read-values" | "write")[][];
1044
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
1045
+ connections: ("manage-access" | "read" | "reveal" | "write")[][];
1046
1046
  days: number;
1047
1047
  };
1048
1048
  type BindingPlan = {
@@ -1075,7 +1075,7 @@ type ConnectedApp = {
1075
1075
  name: string;
1076
1076
  host: string | null;
1077
1077
  registration: "cimd" | "dcr";
1078
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
1078
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
1079
1079
  createdAt: string;
1080
1080
  lastUsedAt: string | null;
1081
1081
  lastUsedIp: string | null;
@@ -1181,7 +1181,7 @@ type Me = {
1181
1181
  isRootAdmin: boolean;
1182
1182
  canReadAudit: boolean;
1183
1183
  features: {
1184
- mcp: boolean;
1184
+ mcp: string | null;
1185
1185
  workloads: boolean;
1186
1186
  };
1187
1187
  environments: {
@@ -1249,7 +1249,7 @@ type OffboardingReport = {
1249
1249
  name: string;
1250
1250
  host: string | null;
1251
1251
  registration: "cimd" | "dcr";
1252
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
1252
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
1253
1253
  createdAt: string;
1254
1254
  lastUsedAt: string | null;
1255
1255
  lastUsedIp: string | null;
@@ -1406,6 +1406,25 @@ declare function apiMember(member: string): string;
1406
1406
  /** A service account's name alone, from any of its forms: `deploy`, `service:deploy` or `token:deploy`. */
1407
1407
  declare function serviceName(member: string): string;
1408
1408
  //#endregion
1409
+ //#region src/reach.d.ts
1410
+ /**
1411
+ * Why an instance could not be reached, from what `fetch` threw. Node's
1412
+ * `fetch` says only `fetch failed`: what happened is in its `cause`, Node's
1413
+ * own error, with a code (`ENOTFOUND`, `ECONNREFUSED`, a certificate's) and
1414
+ * often the address it tried. A browser's says nothing more, and has no cause.
1415
+ */
1416
+ /**
1417
+ * `could not reach <origin>: <why>`, and what to try when the cause is a
1418
+ * common one: `could not reach https://x: getaddrinfo ENOTFOUND x; the name
1419
+ * does not resolve here: …`.
1420
+ */
1421
+ declare function unreachable(origin: string, error: unknown): string;
1422
+ /** A request that never reached the instance: its message says why, `cause` is what `fetch` threw. */
1423
+ declare class Unreachable extends Error {
1424
+ readonly origin: string;
1425
+ constructor(origin: string, error: unknown);
1426
+ }
1427
+ //#endregion
1409
1428
  //#region src/index.d.ts
1410
1429
  type RouteKey = keyof Api;
1411
1430
  /** What a caller sends: the body, or the query string for a GET. */
@@ -1448,7 +1467,7 @@ declare function createClient(options: ClientOptions): {
1448
1467
  isRootAdmin: boolean;
1449
1468
  canReadAudit: boolean;
1450
1469
  features: {
1451
- mcp: boolean;
1470
+ mcp: string | null;
1452
1471
  workloads: boolean;
1453
1472
  };
1454
1473
  environments: {
@@ -1782,7 +1801,7 @@ declare function createClient(options: ClientOptions): {
1782
1801
  name: string;
1783
1802
  host: string | null;
1784
1803
  registration: "cimd" | "dcr";
1785
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
1804
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
1786
1805
  createdAt: string;
1787
1806
  lastUsedAt: string | null;
1788
1807
  lastUsedIp: string | null;
@@ -1851,7 +1870,7 @@ declare function createClient(options: ClientOptions): {
1851
1870
  name: string;
1852
1871
  host: string | null;
1853
1872
  registration: "cimd" | "dcr";
1854
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
1873
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
1855
1874
  createdAt: string;
1856
1875
  lastUsedAt: string | null;
1857
1876
  lastUsedIp: string | null;
@@ -2041,8 +2060,8 @@ declare function createClient(options: ClientOptions): {
2041
2060
  };
2042
2061
  redirectHost: string;
2043
2062
  loopbackOnly: boolean;
2044
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
2045
- connections: ("browse" | "manage-access" | "read-values" | "write")[][];
2063
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
2064
+ connections: ("manage-access" | "read" | "reveal" | "write")[][];
2046
2065
  days: number;
2047
2066
  }>;
2048
2067
  decide: (input: RouteInput<"POST /oauth/authorizations">) => Promise<{
@@ -2110,7 +2129,7 @@ declare function createClient(options: ClientOptions): {
2110
2129
  name: string;
2111
2130
  host: string | null;
2112
2131
  registration: "cimd" | "dcr";
2113
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
2132
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
2114
2133
  createdAt: string;
2115
2134
  lastUsedAt: string | null;
2116
2135
  lastUsedIp: string | null;
@@ -2214,4 +2233,4 @@ declare function planImport(coffre: CoffreClient, path: string, entries: readonl
2214
2233
  changes: Record<string, string>;
2215
2234
  }>;
2216
2235
  //#endregion
2217
- export { DryRunOutcome as A, ReferenceView as B, BindingPlan as C, Deletion as D, Decision as E, Me as F, SessionRow as G, SecretKey as H, Member as I, SetResult as K, MissingKey as L, IdentityRow as M, InheritedGrant as N, DeletionResult as O, ListedReference as P, OffboardingReport as R, AuthorizationView as S, ConnectedApp as T, SecretVersion as U, RemovedMember as V, ServiceTokenRow as W, AccessValue as _, Params as a, AuditEntryView as b, RouteOutput as c, planImport as d, apiMember as f, foldersOf as g, byFolder as h, ImportAction as i, DryRunResult as j, DismissedKey as k, Transport as l, shownMember as m, CoffreClient as n, RouteInput as o, serviceName as p, WorkloadIds as q, CoffreError as r, RouteKey as s, ClientOptions as t, createClient as u, Api as v, BindingView as w, AuthInfo as x, ApprovalView as y, ProjectSummary as z };
2236
+ export { DeletionResult as A, OffboardingReport as B, AuthInfo as C, ConnectedApp as D, BindingView as E, InheritedGrant as F, SecretVersion as G, ReferenceView as H, ListedReference as I, SetResult as J, ServiceTokenRow as K, Me as L, DryRunOutcome as M, DryRunResult as N, Decision as O, IdentityRow as P, Member as R, AuditEntryView as S, BindingPlan as T, RemovedMember as U, ProjectSummary as V, SecretKey as W, WorkloadIds as Y, byFolder as _, Params as a, Api as b, RouteOutput as c, planImport as d, Unreachable as f, shownMember as g, serviceName as h, ImportAction as i, DismissedKey as j, Deletion as k, Transport as l, apiMember as m, CoffreClient as n, RouteInput as o, unreachable as p, SessionRow as q, CoffreError as r, RouteKey as s, ClientOptions as t, createClient as u, foldersOf as v, AuthorizationView as w, ApprovalView as x, AccessValue as y, MissingKey as z };
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as DryRunOutcome, B as ReferenceView, C as BindingPlan, D as Deletion, E as Decision, F as Me, G as SessionRow, H as SecretKey, I as Member, K as SetResult, L as MissingKey, M as IdentityRow, N as InheritedGrant, O as DeletionResult, P as ListedReference, R as OffboardingReport, S as AuthorizationView, T as ConnectedApp, U as SecretVersion, V as RemovedMember, W as ServiceTokenRow, _ as AccessValue, a as Params, b as AuditEntryView, c as RouteOutput, d as planImport, f as apiMember, g as foldersOf, h as byFolder, i as ImportAction, j as DryRunResult, k as DismissedKey, l as Transport, m as shownMember, n as CoffreClient, o as RouteInput, p as serviceName, q as WorkloadIds, r as CoffreError, s as RouteKey, t as ClientOptions, u as createClient, v as Api, w as BindingView, x as AuthInfo, y as ApprovalView, z as ProjectSummary } from "./index-B3rPquWt.js";
2
- export { type AccessValue, type Api, type ApprovalView, type AuditEntryView, type AuthInfo, type AuthorizationView, type BindingPlan, type BindingView, ClientOptions, CoffreClient, CoffreError, type ConnectedApp, type Decision, type Deletion, type DeletionResult, type DismissedKey, type DryRunOutcome, type DryRunResult, type IdentityRow, ImportAction, type InheritedGrant, type ListedReference, type Me, type Member, type MissingKey, type OffboardingReport, Params, type ProjectSummary, type ReferenceView, type RemovedMember, RouteInput, RouteKey, RouteOutput, type SecretKey, type SecretVersion, type ServiceTokenRow, type SessionRow, type SetResult, Transport, type WorkloadIds, apiMember, byFolder, createClient, foldersOf, planImport, serviceName, shownMember };
1
+ import { A as DeletionResult, B as OffboardingReport, C as AuthInfo, D as ConnectedApp, E as BindingView, F as InheritedGrant, G as SecretVersion, H as ReferenceView, I as ListedReference, J as SetResult, K as ServiceTokenRow, L as Me, M as DryRunOutcome, N as DryRunResult, O as Decision, P as IdentityRow, R as Member, S as AuditEntryView, T as BindingPlan, U as RemovedMember, V as ProjectSummary, W as SecretKey, Y as WorkloadIds, _ as byFolder, a as Params, b as Api, c as RouteOutput, d as planImport, f as Unreachable, g as shownMember, h as serviceName, i as ImportAction, j as DismissedKey, k as Deletion, l as Transport, m as apiMember, n as CoffreClient, o as RouteInput, p as unreachable, q as SessionRow, r as CoffreError, s as RouteKey, t as ClientOptions, u as createClient, v as foldersOf, w as AuthorizationView, x as ApprovalView, y as AccessValue, z as MissingKey } from "./index-ZGDlpCwB.js";
2
+ export { type AccessValue, type Api, type ApprovalView, type AuditEntryView, type AuthInfo, type AuthorizationView, type BindingPlan, type BindingView, ClientOptions, CoffreClient, CoffreError, type ConnectedApp, type Decision, type Deletion, type DeletionResult, type DismissedKey, type DryRunOutcome, type DryRunResult, type IdentityRow, ImportAction, type InheritedGrant, type ListedReference, type Me, type Member, type MissingKey, type OffboardingReport, Params, type ProjectSummary, type ReferenceView, type RemovedMember, RouteInput, RouteKey, RouteOutput, type SecretKey, type SecretVersion, type ServiceTokenRow, type SessionRow, type SetResult, Transport, Unreachable, type WorkloadIds, apiMember, byFolder, createClient, foldersOf, planImport, serviceName, shownMember, unreachable };
package/dist/index.js CHANGED
@@ -1,3 +1,51 @@
1
+ //#region src/reach.ts
2
+ /** Two colons or more, in hex: an IPv6 address, as `::1` or `2001:db8::1:443` with its port. */
3
+ const IPV6 = /[0-9a-f]*:[0-9a-f]*:[0-9a-f:]*/i;
4
+ const TIMEOUT_OR_REFUSAL = /* @__PURE__ */ new Set([
5
+ "ECONNREFUSED",
6
+ "ETIMEDOUT",
7
+ "UND_ERR_CONNECT_TIMEOUT",
8
+ "ENETUNREACH",
9
+ "EHOSTUNREACH"
10
+ ]);
11
+ /** What to try for the common causes; null for the others. */
12
+ function hint(cause) {
13
+ const code = cause.code ?? "";
14
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "the name does not resolve here: check the address, or flush this machine's DNS cache";
15
+ const tried = [cause, ...cause.errors ?? []].flatMap((each) => [each.address ?? "", each.message]);
16
+ if (TIMEOUT_OR_REFUSAL.has(code) && tried.some((each) => IPV6.test(each))) return "it was tried over IPv6, which this network may not carry: try NODE_OPTIONS=--dns-result-order=ipv4first";
17
+ if (/CERT|UNABLE_TO_VERIFY|SELF_SIGNED/.test(code)) return "something between you and the instance, such as a proxy or a network filter, presents its own certificate";
18
+ return null;
19
+ }
20
+ /** The cause's own words, with its code and address when they don't already say them. */
21
+ function described(cause) {
22
+ const said = cause.message || (cause.errors ?? []).map((each) => each.message).join(", ");
23
+ const address = cause.address === void 0 ? void 0 : cause.port === void 0 ? cause.address : `${cause.address}:${cause.port}`;
24
+ const more = [cause.code, address].filter((each) => each !== void 0 && !said.includes(each));
25
+ if (said === "") return more.join(" ") || cause.name;
26
+ return more.length === 0 ? said : `${said} (${more.join(", ")})`;
27
+ }
28
+ /**
29
+ * `could not reach <origin>: <why>`, and what to try when the cause is a
30
+ * common one: `could not reach https://x: getaddrinfo ENOTFOUND x; the name
31
+ * does not resolve here: …`.
32
+ */
33
+ function unreachable(origin, error) {
34
+ const cause = error instanceof Error && error.cause instanceof Error ? error.cause : null;
35
+ if (cause === null) return `could not reach ${origin}: ${error instanceof Error ? error.message : String(error)}`;
36
+ const then = hint(cause);
37
+ return `could not reach ${origin}: ${described(cause)}${then === null ? "" : `; ${then}`}`;
38
+ }
39
+ /** A request that never reached the instance: its message says why, `cause` is what `fetch` threw. */
40
+ var Unreachable = class extends Error {
41
+ origin;
42
+ constructor(origin, error) {
43
+ super(unreachable(origin, error), { cause: error });
44
+ this.name = "Unreachable";
45
+ this.origin = origin;
46
+ }
47
+ };
48
+ //#endregion
1
49
  //#region src/folders.ts
2
50
  /**
3
51
  * Rows grouped by folder, as every list shows them: those in no folder
@@ -63,7 +111,13 @@ function place(path) {
63
111
  }
64
112
  function createClient(options) {
65
113
  const origin = options.url.replace(/\/+$/, "");
66
- const transport = options.transport ?? ((request) => fetch(request));
114
+ const transport = options.transport ?? (async (request) => {
115
+ try {
116
+ return await fetch(request);
117
+ } catch (error) {
118
+ throw new Unreachable(origin, error);
119
+ }
120
+ });
67
121
  async function send(method, path, input) {
68
122
  const url = new URL(`${origin}/api${path}`);
69
123
  const headers = new Headers(await options.headers?.());
@@ -303,4 +357,4 @@ async function planImport(coffre, path, entries) {
303
357
  };
304
358
  }
305
359
  //#endregion
306
- export { CoffreError, apiMember, byFolder, createClient, foldersOf, planImport, serviceName, shownMember };
360
+ export { CoffreError, Unreachable, apiMember, byFolder, createClient, foldersOf, planImport, serviceName, shownMember, unreachable };
package/dist/routes.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as Params, o as RouteInput, s as RouteKey } from "./index-B3rPquWt.js";
1
+ import { a as Params, o as RouteInput, s as RouteKey } from "./index-ZGDlpCwB.js";
2
2
  //#region src/routes.d.ts
3
3
  export type GetKey = Extract<RouteKey, `GET ${string}`>;
4
4
  /** Each GET route, with what to ask it. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coffre/client",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "description": "The coffre API as typed function calls.",
5
5
  "license": "MIT",
6
6
  "repository": {
package/src/api.ts CHANGED
@@ -17,7 +17,7 @@ export type Api = {
17
17
  isRootAdmin: boolean;
18
18
  canReadAudit: boolean;
19
19
  features: {
20
- mcp: boolean;
20
+ mcp: string | null;
21
21
  workloads: boolean;
22
22
  };
23
23
  environments: {
@@ -448,7 +448,7 @@ export type Api = {
448
448
  name: string;
449
449
  host: string | null;
450
450
  registration: "cimd" | "dcr";
451
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
451
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
452
452
  createdAt: string;
453
453
  lastUsedAt: string | null;
454
454
  lastUsedIp: string | null;
@@ -524,7 +524,7 @@ export type Api = {
524
524
  name: string;
525
525
  host: string | null;
526
526
  registration: "cimd" | "dcr";
527
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
527
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
528
528
  createdAt: string;
529
529
  lastUsedAt: string | null;
530
530
  lastUsedIp: string | null;
@@ -757,8 +757,8 @@ export type Api = {
757
757
  };
758
758
  redirectHost: string;
759
759
  loopbackOnly: boolean;
760
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
761
- connections: ("browse" | "manage-access" | "read-values" | "write")[][];
760
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
761
+ connections: ("manage-access" | "read" | "reveal" | "write")[][];
762
762
  days: number;
763
763
  };
764
764
  };
@@ -789,7 +789,7 @@ export type Api = {
789
789
  name: string;
790
790
  host: string | null;
791
791
  registration: "cimd" | "dcr";
792
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
792
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
793
793
  createdAt: string;
794
794
  lastUsedAt: string | null;
795
795
  lastUsedIp: string | null;
@@ -1049,8 +1049,8 @@ export type AuthorizationView = {
1049
1049
  };
1050
1050
  redirectHost: string;
1051
1051
  loopbackOnly: boolean;
1052
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
1053
- connections: ("browse" | "manage-access" | "read-values" | "write")[][];
1052
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
1053
+ connections: ("manage-access" | "read" | "reveal" | "write")[][];
1054
1054
  days: number;
1055
1055
  };
1056
1056
 
@@ -1086,7 +1086,7 @@ export type ConnectedApp = {
1086
1086
  name: string;
1087
1087
  host: string | null;
1088
1088
  registration: "cimd" | "dcr";
1089
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
1089
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
1090
1090
  createdAt: string;
1091
1091
  lastUsedAt: string | null;
1092
1092
  lastUsedIp: string | null;
@@ -1202,7 +1202,7 @@ export type Me = {
1202
1202
  isRootAdmin: boolean;
1203
1203
  canReadAudit: boolean;
1204
1204
  features: {
1205
- mcp: boolean;
1205
+ mcp: string | null;
1206
1206
  workloads: boolean;
1207
1207
  };
1208
1208
  environments: {
@@ -1273,7 +1273,7 @@ export type OffboardingReport = {
1273
1273
  name: string;
1274
1274
  host: string | null;
1275
1275
  registration: "cimd" | "dcr";
1276
- scopes: ("browse" | "manage-access" | "read-values" | "write")[];
1276
+ scopes: ("manage-access" | "read" | "reveal" | "write")[];
1277
1277
  createdAt: string;
1278
1278
  lastUsedAt: string | null;
1279
1279
  lastUsedIp: string | null;
package/src/index.ts CHANGED
@@ -7,9 +7,11 @@
7
7
  *
8
8
  * Every call is one `fetch`. Pass a `transport` to send requests somewhere
9
9
  * else: the web app hands requests straight to its router, and the CLI adds
10
- * its own handling of Cloudflare Access redirects.
10
+ * its own handling of Cloudflare Access redirects. A request that never
11
+ * reaches the instance throws `Unreachable`, which says why.
11
12
  */
12
13
  import type { Api, AuthInfo, BindingPlan, BindingView, DeletionResult, DryRunOutcome, DryRunResult, SetResult } from './api.ts';
14
+ import { Unreachable } from './reach.ts';
13
15
 
14
16
  export type {
15
17
  AccessValue,
@@ -47,6 +49,7 @@ export type {
47
49
 
48
50
  export { byFolder, foldersOf } from './folders.ts';
49
51
  export { apiMember, serviceName, shownMember } from './members.ts';
52
+ export { unreachable, Unreachable } from './reach.ts';
50
53
 
51
54
  export type RouteKey = keyof Api;
52
55
  /** What a caller sends: the body, or the query string for a GET. */
@@ -104,7 +107,15 @@ function place(path: string): { project: string; environment: string; key: strin
104
107
 
105
108
  export function createClient(options: ClientOptions) {
106
109
  const origin = options.url.replace(/\/+$/, '');
107
- const transport = options.transport ?? ((request: Request) => fetch(request));
110
+ const transport =
111
+ options.transport ??
112
+ (async (request: Request) => {
113
+ try {
114
+ return await fetch(request);
115
+ } catch (error) {
116
+ throw new Unreachable(origin, error);
117
+ }
118
+ });
108
119
 
109
120
  async function send(method: string, path: string, input: unknown): Promise<unknown> {
110
121
  const url = new URL(`${origin}/api${path}`);
package/src/reach.ts ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Why an instance could not be reached, from what `fetch` threw. Node's
3
+ * `fetch` says only `fetch failed`: what happened is in its `cause`, Node's
4
+ * own error, with a code (`ENOTFOUND`, `ECONNREFUSED`, a certificate's) and
5
+ * often the address it tried. A browser's says nothing more, and has no cause.
6
+ */
7
+
8
+ /** Node's error under a failed `fetch`; an AggregateError, with no message, when every address failed. */
9
+ type Cause = Error & { code?: string; address?: string; port?: number; hostname?: string; errors?: Cause[] };
10
+
11
+ /** Two colons or more, in hex: an IPv6 address, as `::1` or `2001:db8::1:443` with its port. */
12
+ const IPV6 = /[0-9a-f]*:[0-9a-f]*:[0-9a-f:]*/i;
13
+
14
+ const TIMEOUT_OR_REFUSAL = new Set(['ECONNREFUSED', 'ETIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT', 'ENETUNREACH', 'EHOSTUNREACH']);
15
+
16
+ /** What to try for the common causes; null for the others. */
17
+ function hint(cause: Cause): string | null {
18
+ const code = cause.code ?? '';
19
+ if (code === 'ENOTFOUND' || code === 'EAI_AGAIN') {
20
+ return "the name does not resolve here: check the address, or flush this machine's DNS cache";
21
+ }
22
+ const tried = [cause, ...(cause.errors ?? [])].flatMap((each) => [each.address ?? '', each.message]);
23
+ if (TIMEOUT_OR_REFUSAL.has(code) && tried.some((each) => IPV6.test(each))) {
24
+ return "it was tried over IPv6, which this network may not carry: try NODE_OPTIONS=--dns-result-order=ipv4first";
25
+ }
26
+ if (/CERT|UNABLE_TO_VERIFY|SELF_SIGNED/.test(code)) {
27
+ return 'something between you and the instance, such as a proxy or a network filter, presents its own certificate';
28
+ }
29
+ return null;
30
+ }
31
+
32
+ /** The cause's own words, with its code and address when they don't already say them. */
33
+ function described(cause: Cause): string {
34
+ const said = cause.message || (cause.errors ?? []).map((each) => each.message).join(', ');
35
+ const address = cause.address === undefined ? undefined : cause.port === undefined ? cause.address : `${cause.address}:${cause.port}`;
36
+ const more = [cause.code, address].filter((each): each is string => each !== undefined && !said.includes(each));
37
+ if (said === '') return more.join(' ') || cause.name;
38
+ return more.length === 0 ? said : `${said} (${more.join(', ')})`;
39
+ }
40
+
41
+ /**
42
+ * `could not reach <origin>: <why>`, and what to try when the cause is a
43
+ * common one: `could not reach https://x: getaddrinfo ENOTFOUND x; the name
44
+ * does not resolve here: …`.
45
+ */
46
+ export function unreachable(origin: string, error: unknown): string {
47
+ const cause = error instanceof Error && error.cause instanceof Error ? (error.cause as Cause) : null;
48
+ if (cause === null) return `could not reach ${origin}: ${error instanceof Error ? error.message : String(error)}`;
49
+ const then = hint(cause);
50
+ return `could not reach ${origin}: ${described(cause)}${then === null ? '' : `; ${then}`}`;
51
+ }
52
+
53
+ /** A request that never reached the instance: its message says why, `cause` is what `fetch` threw. */
54
+ export class Unreachable extends Error {
55
+ readonly origin: string;
56
+
57
+ constructor(origin: string, error: unknown) {
58
+ super(unreachable(origin, error), { cause: error });
59
+ this.name = 'Unreachable';
60
+ this.origin = origin;
61
+ }
62
+ }