@b3os/sdk 0.0.0-stage → 0.1.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 (242) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +233 -2
  3. package/dist/cjs/core/client.d.ts +165 -0
  4. package/dist/cjs/core/client.js +825 -0
  5. package/dist/cjs/core/client.js.map +1 -0
  6. package/dist/cjs/core/errors.d.ts +101 -0
  7. package/dist/cjs/core/errors.js +249 -0
  8. package/dist/cjs/core/errors.js.map +1 -0
  9. package/dist/cjs/core/index.d.ts +12 -0
  10. package/dist/cjs/core/index.js +42 -0
  11. package/dist/cjs/core/index.js.map +1 -0
  12. package/dist/cjs/core/jobs.d.ts +31 -0
  13. package/dist/cjs/core/jobs.js +72 -0
  14. package/dist/cjs/core/jobs.js.map +1 -0
  15. package/dist/cjs/core/namespace.d.ts +7 -0
  16. package/dist/cjs/core/namespace.js +13 -0
  17. package/dist/cjs/core/namespace.js.map +1 -0
  18. package/dist/cjs/core/op.d.ts +47 -0
  19. package/dist/cjs/core/op.js +5 -0
  20. package/dist/cjs/core/op.js.map +1 -0
  21. package/dist/cjs/core/promise.d.ts +106 -0
  22. package/dist/cjs/core/promise.js +200 -0
  23. package/dist/cjs/core/promise.js.map +1 -0
  24. package/dist/cjs/core/response.d.ts +54 -0
  25. package/dist/cjs/core/response.js +92 -0
  26. package/dist/cjs/core/response.js.map +1 -0
  27. package/dist/cjs/core/sse.d.ts +79 -0
  28. package/dist/cjs/core/sse.js +291 -0
  29. package/dist/cjs/core/sse.js.map +1 -0
  30. package/dist/cjs/core/timing.d.ts +20 -0
  31. package/dist/cjs/core/timing.js +96 -0
  32. package/dist/cjs/core/timing.js.map +1 -0
  33. package/dist/cjs/core/transport.d.ts +80 -0
  34. package/dist/cjs/core/transport.js +472 -0
  35. package/dist/cjs/core/transport.js.map +1 -0
  36. package/dist/cjs/core/util.d.ts +25 -0
  37. package/dist/cjs/core/util.js +142 -0
  38. package/dist/cjs/core/util.js.map +1 -0
  39. package/dist/cjs/core/ws.d.ts +52 -0
  40. package/dist/cjs/core/ws.js +181 -0
  41. package/dist/cjs/core/ws.js.map +1 -0
  42. package/dist/cjs/generated/client.d.ts +62 -0
  43. package/dist/cjs/generated/client.js +130 -0
  44. package/dist/cjs/generated/client.js.map +1 -0
  45. package/dist/cjs/generated/errors.d.ts +4 -0
  46. package/dist/cjs/generated/errors.js +160 -0
  47. package/dist/cjs/generated/errors.js.map +1 -0
  48. package/dist/cjs/generated/ids.d.ts +114 -0
  49. package/dist/cjs/generated/ids.js +47 -0
  50. package/dist/cjs/generated/ids.js.map +1 -0
  51. package/dist/cjs/generated/jobs.d.ts +10 -0
  52. package/dist/cjs/generated/jobs.js +24 -0
  53. package/dist/cjs/generated/jobs.js.map +1 -0
  54. package/dist/cjs/generated/ns/actions.d.ts +161 -0
  55. package/dist/cjs/generated/ns/actions.js +304 -0
  56. package/dist/cjs/generated/ns/actions.js.map +1 -0
  57. package/dist/cjs/generated/ns/infer.d.ts +190 -0
  58. package/dist/cjs/generated/ns/infer.js +253 -0
  59. package/dist/cjs/generated/ns/infer.js.map +1 -0
  60. package/dist/cjs/generated/ns/keys.d.ts +76 -0
  61. package/dist/cjs/generated/ns/keys.js +144 -0
  62. package/dist/cjs/generated/ns/keys.js.map +1 -0
  63. package/dist/cjs/generated/ns/limits.d.ts +22 -0
  64. package/dist/cjs/generated/ns/limits.js +32 -0
  65. package/dist/cjs/generated/ns/limits.js.map +1 -0
  66. package/dist/cjs/generated/ns/orgs.d.ts +38 -0
  67. package/dist/cjs/generated/ns/orgs.js +68 -0
  68. package/dist/cjs/generated/ns/orgs.js.map +1 -0
  69. package/dist/cjs/generated/ns/projects.d.ts +57 -0
  70. package/dist/cjs/generated/ns/projects.js +115 -0
  71. package/dist/cjs/generated/ns/projects.js.map +1 -0
  72. package/dist/cjs/generated/ns/render.d.ts +159 -0
  73. package/dist/cjs/generated/ns/render.js +299 -0
  74. package/dist/cjs/generated/ns/render.js.map +1 -0
  75. package/dist/cjs/generated/ns/requests.d.ts +36 -0
  76. package/dist/cjs/generated/ns/requests.js +54 -0
  77. package/dist/cjs/generated/ns/requests.js.map +1 -0
  78. package/dist/cjs/generated/ns/routines.d.ts +212 -0
  79. package/dist/cjs/generated/ns/routines.js +419 -0
  80. package/dist/cjs/generated/ns/routines.js.map +1 -0
  81. package/dist/cjs/generated/ns/sandboxes.d.ts +318 -0
  82. package/dist/cjs/generated/ns/sandboxes.js +549 -0
  83. package/dist/cjs/generated/ns/sandboxes.js.map +1 -0
  84. package/dist/cjs/generated/ns/usage.d.ts +30 -0
  85. package/dist/cjs/generated/ns/usage.js +49 -0
  86. package/dist/cjs/generated/ns/usage.js.map +1 -0
  87. package/dist/cjs/generated/ns/vault.d.ts +69 -0
  88. package/dist/cjs/generated/ns/vault.js +122 -0
  89. package/dist/cjs/generated/ns/vault.js.map +1 -0
  90. package/dist/cjs/generated/ns/vision.d.ts +376 -0
  91. package/dist/cjs/generated/ns/vision.js +736 -0
  92. package/dist/cjs/generated/ns/vision.js.map +1 -0
  93. package/dist/cjs/generated/ns/webhooks.d.ts +50 -0
  94. package/dist/cjs/generated/ns/webhooks.js +91 -0
  95. package/dist/cjs/generated/ns/webhooks.js.map +1 -0
  96. package/dist/cjs/generated/types.d.ts +4613 -0
  97. package/dist/cjs/generated/types.js +4 -0
  98. package/dist/cjs/generated/types.js.map +1 -0
  99. package/dist/cjs/index.d.ts +22 -0
  100. package/dist/cjs/index.js +81 -0
  101. package/dist/cjs/index.js.map +1 -0
  102. package/dist/cjs/package.json +3 -0
  103. package/dist/cjs/webhooks.d.ts +19 -0
  104. package/dist/cjs/webhooks.js +85 -0
  105. package/dist/cjs/webhooks.js.map +1 -0
  106. package/dist/esm/core/client.d.ts +165 -0
  107. package/dist/esm/core/client.js +821 -0
  108. package/dist/esm/core/client.js.map +1 -0
  109. package/dist/esm/core/errors.d.ts +101 -0
  110. package/dist/esm/core/errors.js +239 -0
  111. package/dist/esm/core/errors.js.map +1 -0
  112. package/dist/esm/core/index.d.ts +12 -0
  113. package/dist/esm/core/index.js +15 -0
  114. package/dist/esm/core/index.js.map +1 -0
  115. package/dist/esm/core/jobs.d.ts +31 -0
  116. package/dist/esm/core/jobs.js +66 -0
  117. package/dist/esm/core/jobs.js.map +1 -0
  118. package/dist/esm/core/namespace.d.ts +7 -0
  119. package/dist/esm/core/namespace.js +9 -0
  120. package/dist/esm/core/namespace.js.map +1 -0
  121. package/dist/esm/core/op.d.ts +47 -0
  122. package/dist/esm/core/op.js +4 -0
  123. package/dist/esm/core/op.js.map +1 -0
  124. package/dist/esm/core/promise.d.ts +106 -0
  125. package/dist/esm/core/promise.js +193 -0
  126. package/dist/esm/core/promise.js.map +1 -0
  127. package/dist/esm/core/response.d.ts +54 -0
  128. package/dist/esm/core/response.js +86 -0
  129. package/dist/esm/core/response.js.map +1 -0
  130. package/dist/esm/core/sse.d.ts +79 -0
  131. package/dist/esm/core/sse.js +286 -0
  132. package/dist/esm/core/sse.js.map +1 -0
  133. package/dist/esm/core/timing.d.ts +20 -0
  134. package/dist/esm/core/timing.js +92 -0
  135. package/dist/esm/core/timing.js.map +1 -0
  136. package/dist/esm/core/transport.d.ts +80 -0
  137. package/dist/esm/core/transport.js +465 -0
  138. package/dist/esm/core/transport.js.map +1 -0
  139. package/dist/esm/core/util.d.ts +25 -0
  140. package/dist/esm/core/util.js +128 -0
  141. package/dist/esm/core/util.js.map +1 -0
  142. package/dist/esm/core/ws.d.ts +52 -0
  143. package/dist/esm/core/ws.js +175 -0
  144. package/dist/esm/core/ws.js.map +1 -0
  145. package/dist/esm/generated/client.d.ts +62 -0
  146. package/dist/esm/generated/client.js +126 -0
  147. package/dist/esm/generated/client.js.map +1 -0
  148. package/dist/esm/generated/errors.d.ts +4 -0
  149. package/dist/esm/generated/errors.js +157 -0
  150. package/dist/esm/generated/errors.js.map +1 -0
  151. package/dist/esm/generated/ids.d.ts +114 -0
  152. package/dist/esm/generated/ids.js +42 -0
  153. package/dist/esm/generated/ids.js.map +1 -0
  154. package/dist/esm/generated/jobs.d.ts +10 -0
  155. package/dist/esm/generated/jobs.js +21 -0
  156. package/dist/esm/generated/jobs.js.map +1 -0
  157. package/dist/esm/generated/ns/actions.d.ts +161 -0
  158. package/dist/esm/generated/ns/actions.js +300 -0
  159. package/dist/esm/generated/ns/actions.js.map +1 -0
  160. package/dist/esm/generated/ns/infer.d.ts +190 -0
  161. package/dist/esm/generated/ns/infer.js +249 -0
  162. package/dist/esm/generated/ns/infer.js.map +1 -0
  163. package/dist/esm/generated/ns/keys.d.ts +76 -0
  164. package/dist/esm/generated/ns/keys.js +140 -0
  165. package/dist/esm/generated/ns/keys.js.map +1 -0
  166. package/dist/esm/generated/ns/limits.d.ts +22 -0
  167. package/dist/esm/generated/ns/limits.js +28 -0
  168. package/dist/esm/generated/ns/limits.js.map +1 -0
  169. package/dist/esm/generated/ns/orgs.d.ts +38 -0
  170. package/dist/esm/generated/ns/orgs.js +64 -0
  171. package/dist/esm/generated/ns/orgs.js.map +1 -0
  172. package/dist/esm/generated/ns/projects.d.ts +57 -0
  173. package/dist/esm/generated/ns/projects.js +111 -0
  174. package/dist/esm/generated/ns/projects.js.map +1 -0
  175. package/dist/esm/generated/ns/render.d.ts +159 -0
  176. package/dist/esm/generated/ns/render.js +295 -0
  177. package/dist/esm/generated/ns/render.js.map +1 -0
  178. package/dist/esm/generated/ns/requests.d.ts +36 -0
  179. package/dist/esm/generated/ns/requests.js +50 -0
  180. package/dist/esm/generated/ns/requests.js.map +1 -0
  181. package/dist/esm/generated/ns/routines.d.ts +212 -0
  182. package/dist/esm/generated/ns/routines.js +415 -0
  183. package/dist/esm/generated/ns/routines.js.map +1 -0
  184. package/dist/esm/generated/ns/sandboxes.d.ts +318 -0
  185. package/dist/esm/generated/ns/sandboxes.js +545 -0
  186. package/dist/esm/generated/ns/sandboxes.js.map +1 -0
  187. package/dist/esm/generated/ns/usage.d.ts +30 -0
  188. package/dist/esm/generated/ns/usage.js +45 -0
  189. package/dist/esm/generated/ns/usage.js.map +1 -0
  190. package/dist/esm/generated/ns/vault.d.ts +69 -0
  191. package/dist/esm/generated/ns/vault.js +118 -0
  192. package/dist/esm/generated/ns/vault.js.map +1 -0
  193. package/dist/esm/generated/ns/vision.d.ts +376 -0
  194. package/dist/esm/generated/ns/vision.js +732 -0
  195. package/dist/esm/generated/ns/vision.js.map +1 -0
  196. package/dist/esm/generated/ns/webhooks.d.ts +50 -0
  197. package/dist/esm/generated/ns/webhooks.js +87 -0
  198. package/dist/esm/generated/ns/webhooks.js.map +1 -0
  199. package/dist/esm/generated/types.d.ts +4613 -0
  200. package/dist/esm/generated/types.js +3 -0
  201. package/dist/esm/generated/types.js.map +1 -0
  202. package/dist/esm/index.d.ts +22 -0
  203. package/dist/esm/index.js +28 -0
  204. package/dist/esm/index.js.map +1 -0
  205. package/dist/esm/webhooks.d.ts +19 -0
  206. package/dist/esm/webhooks.js +79 -0
  207. package/dist/esm/webhooks.js.map +1 -0
  208. package/package.json +97 -3
  209. package/src/core/client.ts +1022 -0
  210. package/src/core/errors.ts +296 -0
  211. package/src/core/index.ts +45 -0
  212. package/src/core/jobs.ts +94 -0
  213. package/src/core/namespace.ts +10 -0
  214. package/src/core/op.ts +53 -0
  215. package/src/core/promise.ts +268 -0
  216. package/src/core/response.ts +115 -0
  217. package/src/core/sse.ts +305 -0
  218. package/src/core/timing.ts +106 -0
  219. package/src/core/transport.ts +489 -0
  220. package/src/core/util.ts +138 -0
  221. package/src/core/ws.ts +215 -0
  222. package/src/generated/client.ts +143 -0
  223. package/src/generated/errors.ts +313 -0
  224. package/src/generated/ids.ts +47 -0
  225. package/src/generated/jobs.ts +25 -0
  226. package/src/generated/ns/actions.ts +353 -0
  227. package/src/generated/ns/infer.ts +332 -0
  228. package/src/generated/ns/keys.ts +152 -0
  229. package/src/generated/ns/limits.ts +35 -0
  230. package/src/generated/ns/orgs.ts +77 -0
  231. package/src/generated/ns/projects.ts +122 -0
  232. package/src/generated/ns/render.ts +348 -0
  233. package/src/generated/ns/requests.ts +61 -0
  234. package/src/generated/ns/routines.ts +474 -0
  235. package/src/generated/ns/sandboxes.ts +671 -0
  236. package/src/generated/ns/usage.ts +56 -0
  237. package/src/generated/ns/vault.ts +136 -0
  238. package/src/generated/ns/vision.ts +836 -0
  239. package/src/generated/ns/webhooks.ts +100 -0
  240. package/src/generated/types.ts +5131 -0
  241. package/src/index.ts +30 -0
  242. package/src/webhooks.ts +100 -0
@@ -0,0 +1,821 @@
1
+ // The core client: configuration, routing between beta-api.b3os.org and the same-host fast paths, the request
2
+ // pipeline (idempotency keys, retries with jittered backoff, timeouts, typed errors, Server-Timing), and the job
3
+ // and stream plumbing the generated namespaces call. It knows no product; src/generated/ns/* do.
4
+ import { B3OSAbortError, B3OSConnectionError, B3OSError, B3OSJobError, B3OSTimeoutError, NEVER_REACHED_STATUSES, parseErrorBody, } from "./errors.js";
5
+ import { APIPromise, JobEventStream, JobPromise, ListPromise, TERMINAL_JOB_EVENTS, TERMINAL_JOB_STATUSES, } from "./promise.js";
6
+ import { ResponseInfo, remember } from "./response.js";
7
+ import { EventStream } from "./sse.js";
8
+ import { FetchTransport, NodeHttpTransport, socketExists, TransportTimeout, } from "./transport.js";
9
+ import { backoffMs, env, isObject, parseRetryAfter, runtime, runtimeLabel, SDK_VERSION, sleep, uuid } from "./util.js";
10
+ export const DEFAULT_BASE_URL = "https://beta-api.b3os.org";
11
+ /** b3osd's Unix socket on a B3OS node (ARCHITECTURE §1). */
12
+ export const DEFAULT_SOCKET_PATH = "/run/b3os/b3osd/b3osd.sock";
13
+ const JSON_CT = /^application\/(?:[\w.+-]+\+)?json\b/i;
14
+ const NO_RETRY_TIMEOUT_CODES = new Set(["request_timeout", "upstream_timeout", "scrape_timeout", "job_timed_out"]);
15
+ /**
16
+ * Codes that reject a request before any work, so even non-idempotent calls may be retried. They count only when
17
+ * B3OS said so in the error body, or when the status alone proves the request never got in (NEVER_REACHED_STATUSES):
18
+ * an intermediary's 502 or 503 page may come after the origin already ran the request.
19
+ */
20
+ const REJECTED_BEFORE_WORK = new Set([
21
+ "rate_limited",
22
+ "concurrency_limited",
23
+ "ticket_limit",
24
+ "node_unavailable",
25
+ "product_unavailable",
26
+ "capacity_unavailable",
27
+ "auth_unavailable",
28
+ "idempotency_request_in_progress",
29
+ ]);
30
+ function trimSlash(s) {
31
+ return s.endsWith("/") ? s.replace(/\/+$/, "") : s;
32
+ }
33
+ /** Percent-encodes what a request target cannot carry, leaving URL syntax (and existing escapes) alone. */
34
+ function encodeWildcard(v) {
35
+ const hash = v.indexOf("#");
36
+ const s = hash >= 0 ? v.slice(0, hash) : v;
37
+ return s.replace(/[^A-Za-z0-9\-._~:/?\[\]@!$&'()*+,;=%]/g, (c) => Array.from(new TextEncoder().encode(c), (b) => `%${b.toString(16).toUpperCase().padStart(2, "0")}`).join(""));
38
+ }
39
+ /** `.` or `..`, also percent-encoded (`%2e`, `.%2E`): URL parsers (WHATWG, httpx) resolve these segments. */
40
+ const DOT_SEGMENT = /^(?:\.|%2e){1,2}$/i;
41
+ /** `scheme://authority` + path + query of an absolute URL given as a wildcard value (vision.readUrl). */
42
+ const ABSOLUTE_URL = /^([A-Za-z][A-Za-z0-9+.-]*:\/\/[^/?#]*)([^?#]*)(.*)$/s;
43
+ function hasDotSegment(path) {
44
+ return path.split("/").some((seg) => DOT_SEGMENT.test(seg));
45
+ }
46
+ /** RFC 3986 §5.2.4 remove_dot_segments on an absolute path, treating `%2e` as `.` as WHATWG URL parsing does. */
47
+ function removeDotSegments(path) {
48
+ const segs = path.split("/");
49
+ const out = [];
50
+ for (let i = 0; i < segs.length; i++) {
51
+ const seg = segs[i];
52
+ const last = i === segs.length - 1;
53
+ if (i > 0 && DOT_SEGMENT.test(seg)) {
54
+ if (seg.replace(/%2e/gi, ".") === ".." && out.length > 1)
55
+ out.pop();
56
+ if (last)
57
+ out.push("");
58
+ }
59
+ else {
60
+ out.push(seg);
61
+ }
62
+ }
63
+ return out.join("/");
64
+ }
65
+ /**
66
+ * A wildcard path value (a target URL, a model id that contains `/`) with dot segments resolved inside it, so
67
+ * they can never climb out of the operation's own path: `/v1/vision/r/https://x/../../../v1/keys` would
68
+ * otherwise reach `GET /v1/keys` with the API key. An absolute URL is normalized the way the target server
69
+ * would see it anyway; any other value with a dot segment is refused.
70
+ */
71
+ function safeWildcard(op, name, v) {
72
+ const hash = v.indexOf("#");
73
+ let s = hash >= 0 ? v.slice(0, hash) : v;
74
+ const q = s.indexOf("?");
75
+ if (hasDotSegment(q >= 0 ? s.slice(0, q) : s)) {
76
+ const m = ABSOLUTE_URL.exec(s);
77
+ if (m)
78
+ s = `${m[1]}${removeDotSegments(m[2])}${m[3]}`;
79
+ const q2 = s.indexOf("?");
80
+ if (hasDotSegment(q2 >= 0 ? s.slice(0, q2) : s)) {
81
+ throw new TypeError(`@b3os/sdk: ${op.id}: the path parameter ${name} must not contain "." or ".." segments`);
82
+ }
83
+ }
84
+ return encodeWildcard(s);
85
+ }
86
+ /** Account paths `request()` sends to the API host unless told otherwise. */
87
+ const EDGE_PATHS = /^\/v1\/(keys|usage|limits|orgs|projects|auth|actions\/registry)(\/|$)/;
88
+ function buildPath(op, values) {
89
+ if (!op.path.includes("{"))
90
+ return op.path;
91
+ const names = op.params ?? [];
92
+ let i = 0;
93
+ return op.path.replace(/\{([^}]+)\}/g, (_, name) => {
94
+ const idx = names.indexOf(name);
95
+ const v = values?.[idx >= 0 ? idx : i];
96
+ i++;
97
+ if (v === undefined || v === null || v === "") {
98
+ throw new TypeError(`@b3os/sdk: ${op.id} needs the path parameter ${name}`);
99
+ }
100
+ const s = String(v);
101
+ if (name === op.wildcard)
102
+ return safeWildcard(op, name, s);
103
+ if (s === "." || s === "..") {
104
+ // encodeURIComponent keeps dots, and a lone ".." segment would move the request to the parent path.
105
+ throw new TypeError(`@b3os/sdk: ${op.id}: the path parameter ${name} cannot be "${s}"`);
106
+ }
107
+ return encodeURIComponent(s);
108
+ });
109
+ }
110
+ function buildQuery(query, extra) {
111
+ let sp;
112
+ if (query) {
113
+ for (const [k, v] of Object.entries(query)) {
114
+ if (v === undefined || v === null)
115
+ continue;
116
+ sp ??= new URLSearchParams();
117
+ if (Array.isArray(v))
118
+ for (const x of v)
119
+ sp.append(k, String(x));
120
+ else if (v instanceof Date)
121
+ sp.append(k, v.toISOString());
122
+ else
123
+ sp.append(k, String(v));
124
+ }
125
+ }
126
+ if (extra) {
127
+ sp ??= new URLSearchParams();
128
+ for (const [k, v] of Object.entries(extra))
129
+ sp.set(k, v);
130
+ }
131
+ const s = sp ? sp.toString() : "";
132
+ return s ? `?${s}` : "";
133
+ }
134
+ function isTerminalJob(j) {
135
+ return isObject(j) && typeof j.status === "string" && TERMINAL_JOB_STATUSES.has(j.status);
136
+ }
137
+ function jobIdOf(j) {
138
+ if (typeof j === "string")
139
+ return j;
140
+ if (isObject(j) && typeof j.id === "string")
141
+ return j.id;
142
+ throw new TypeError("@b3os/sdk: expected a job object or a job id");
143
+ }
144
+ function eventType(ev) {
145
+ return isObject(ev) && typeof ev.type === "string" ? ev.type : undefined;
146
+ }
147
+ function connectRefused(err) {
148
+ const code = err?.code;
149
+ return code === "ENOENT" || code === "ECONNREFUSED" || code === "EACCES" || code === "EPERM";
150
+ }
151
+ function describeErr(err) {
152
+ if (err instanceof Error) {
153
+ const cause = err.cause;
154
+ const code = err.code ?? cause?.code;
155
+ const msg = cause?.message && cause.message !== err.message ? `${err.message} (${cause.message})` : err.message;
156
+ return code && !msg.includes(code) ? `${code}: ${msg}` : msg;
157
+ }
158
+ return String(err);
159
+ }
160
+ export class B3OSCore {
161
+ apiKey;
162
+ baseUrl;
163
+ maxRetries;
164
+ maxRetryDelayMs;
165
+ timeoutMs;
166
+ edge;
167
+ node;
168
+ headers;
169
+ onResponse;
170
+ constructor(options = {}) {
171
+ this.apiKey = options.apiKey !== undefined ? options.apiKey : (env("B3OS_API_KEY") ?? null);
172
+ const explicitBase = options.baseUrl ?? env("B3OS_BASE_URL");
173
+ this.baseUrl = trimSlash(explicitBase ?? DEFAULT_BASE_URL);
174
+ this.maxRetries = options.maxRetries ?? 2;
175
+ this.maxRetryDelayMs = options.maxRetryDelayMs ?? 60_000;
176
+ this.timeoutMs = options.timeoutMs;
177
+ this.onResponse = options.onResponse;
178
+ const headers = {};
179
+ const rt = runtime();
180
+ if (rt === "node" || rt === "bun" || rt === "deno" || rt === "workerd") {
181
+ headers["user-agent"] = `b3os-sdk-ts/${SDK_VERSION} ${runtimeLabel()}`;
182
+ }
183
+ for (const [k, v] of Object.entries(options.headers ?? {}))
184
+ headers[k.toLowerCase()] = v;
185
+ this.headers = headers;
186
+ const fetchT = new FetchTransport(this.baseUrl, options.fetch);
187
+ this.edge = { kind: "edge", transport: fetchT, base: this.baseUrl, auth: true, auto: false };
188
+ const pref = options.transport ?? env("B3OS_TRANSPORT") ?? "auto";
189
+ const sockEnv = env("B3OS_SOCKET");
190
+ const sockDisabled = options.socketPath === false || sockEnv === "0" || sockEnv === "off";
191
+ const nodeUrl = options.nodeUrl !== undefined ? options.nodeUrl : (env("B3OS_API_URL") ?? null);
192
+ let node = this.edge;
193
+ if (pref !== "http") {
194
+ const explicitSock = typeof options.socketPath === "string" ? options.socketPath : sockDisabled ? undefined : sockEnv;
195
+ if (explicitSock) {
196
+ node = this.udsRoute(explicitSock, false, options.fetch);
197
+ }
198
+ else if (nodeUrl) {
199
+ const base = trimSlash(nodeUrl);
200
+ // Plain HTTP to the node (inside a sandbox) goes through node:http keep-alive on Node, unless the caller
201
+ // supplied its own fetch.
202
+ const useNodeHttp = !options.fetch && base.startsWith("http:") && NodeHttpTransport.available();
203
+ node = {
204
+ kind: "node-http",
205
+ transport: useNodeHttp ? new NodeHttpTransport({ baseUrl: base }) : new FetchTransport(base, options.fetch),
206
+ base,
207
+ auth: false,
208
+ auto: false,
209
+ };
210
+ }
211
+ else if (!this.apiKey &&
212
+ !explicitBase &&
213
+ !sockDisabled &&
214
+ options.socketPath !== null &&
215
+ socketExists(DEFAULT_SOCKET_PATH)) {
216
+ // Only without a key: the socket acts as the uid's principal, and silently mixing it with the key's
217
+ // principal (whoami says org A, listSandboxes shows org B) is worse than the network hop.
218
+ node = this.udsRoute(DEFAULT_SOCKET_PATH, true, options.fetch);
219
+ }
220
+ }
221
+ this.node = node;
222
+ }
223
+ udsRoute(path, auto, fetchFn) {
224
+ const rt = runtime();
225
+ if (rt === "bun") {
226
+ return {
227
+ kind: "uds",
228
+ transport: new FetchTransport("http://b3osd", fetchFn, path),
229
+ base: "http://b3osd",
230
+ auth: false,
231
+ auto,
232
+ };
233
+ }
234
+ if (!NodeHttpTransport.available()) {
235
+ throw new Error(`@b3os/sdk: the Unix socket ${path} needs Node or Bun; set B3OS_TRANSPORT=http on ${rt}`);
236
+ }
237
+ return {
238
+ kind: "uds",
239
+ transport: new NodeHttpTransport({ socketPath: path }),
240
+ base: "http://b3osd",
241
+ auth: false,
242
+ auto,
243
+ };
244
+ }
245
+ /** Where node-served and edge-served operations go (`unix:/run/b3os/b3osd/b3osd.sock`, a URL). */
246
+ get routes() {
247
+ return { node: this.node.transport.label, edge: this.edge.transport.label, nodeKind: this.node.kind };
248
+ }
249
+ /** Closes pooled connections (the Unix socket agent). Optional; idle sockets do not keep the process alive. */
250
+ close() {
251
+ this.node.transport.close?.();
252
+ if (this.edge !== this.node)
253
+ this.edge.transport.close?.();
254
+ }
255
+ // ------------------------------------------------------------------------------------------------------------
256
+ // The request pipeline
257
+ headersFor(route, op, o, accept) {
258
+ const h = { ...this.headers, accept };
259
+ if (route.auth && this.apiKey)
260
+ h.authorization = `Bearer ${this.apiKey}`;
261
+ if (o.traceparent)
262
+ h.traceparent = o.traceparent;
263
+ if (o.headers)
264
+ for (const [k, v] of Object.entries(o.headers))
265
+ h[k.toLowerCase()] = v;
266
+ void op;
267
+ return h;
268
+ }
269
+ encodeBody(op, args, h) {
270
+ const b = args.body;
271
+ if (b === undefined)
272
+ return undefined;
273
+ const kind = args.bodyType ?? op.body ?? "json";
274
+ if (kind === "json") {
275
+ h["content-type"] ??= "application/json";
276
+ return JSON.stringify(b);
277
+ }
278
+ if (kind === "yaml") {
279
+ h["content-type"] ??= "application/yaml";
280
+ return String(b);
281
+ }
282
+ if (kind === "form") {
283
+ h["content-type"] ??= "application/x-www-form-urlencoded";
284
+ return new URLSearchParams(b).toString();
285
+ }
286
+ if (h["content-type"] === undefined) {
287
+ h["content-type"] =
288
+ op.contentType ??
289
+ (typeof Blob !== "undefined" && b instanceof Blob && b.type ? b.type : "application/octet-stream");
290
+ }
291
+ if (typeof b === "string" || b instanceof Uint8Array || b instanceof ArrayBuffer)
292
+ return b;
293
+ if (typeof Blob !== "undefined" && b instanceof Blob)
294
+ return b;
295
+ if (typeof ReadableStream !== "undefined" && b instanceof ReadableStream)
296
+ return b;
297
+ if (ArrayBuffer.isView(b))
298
+ return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
299
+ throw new TypeError(`@b3os/sdk: ${op.id} takes a string, Uint8Array, ArrayBuffer, Blob or ReadableStream body`);
300
+ }
301
+ hint(route, op, err) {
302
+ if (err.code === "edge_only") {
303
+ return this.apiKey
304
+ ? `${op.id} is served by ${this.baseUrl}`
305
+ : `${op.id} is served by ${this.baseUrl}; set B3OS_API_KEY (or pass apiKey) so the SDK can send it there`;
306
+ }
307
+ if (err.status === 401 && route.auth && !this.apiKey) {
308
+ return "No API key is configured: set B3OS_API_KEY or pass apiKey";
309
+ }
310
+ if (err.status === 403 && err.reason === "scope" && route.kind === "uds") {
311
+ return ("Over the node's Unix socket this process acts as the local principal its uid maps to in b3osd.toml " +
312
+ "([auth.local_peers], else the read-only [auth.local_default]); set B3OS_TRANSPORT=http to use your API key");
313
+ }
314
+ return undefined;
315
+ }
316
+ /** Sends one operation with retries. Resolves with a 2xx (or 101) response whose body is still unread. */
317
+ async send(op, args, o, x) {
318
+ const method = op.method;
319
+ const pathStr = buildPath(op, args.path);
320
+ const query = buildQuery(args.query, x.extraQuery);
321
+ let idemKey = o.idempotencyKey;
322
+ if (!idemKey && op.idem && method !== "GET")
323
+ idemKey = uuid();
324
+ const streamBody = typeof ReadableStream !== "undefined" && args.body instanceof ReadableStream;
325
+ const retrySafe = !streamBody && (method === "GET" || method === "HEAD" || method === "PUT" || method === "DELETE" || !!idemKey);
326
+ const maxRetries = streamBody ? 0 : (o.maxRetries ?? this.maxRetries);
327
+ const perAttempt = o.timeoutMs ?? this.timeoutMs ?? (x.sse ? 30_000 : Math.min(op.timeoutMs, 65_000) + 5_000);
328
+ let route = op.edge ? this.edge : this.node;
329
+ let attempt = 0;
330
+ for (;;) {
331
+ const headers = this.headersFor(route, op, o, x.accept);
332
+ if (idemKey)
333
+ headers["idempotency-key"] = idemKey;
334
+ if (op.headerParams && args.headerParams) {
335
+ for (const [k, name] of Object.entries(op.headerParams)) {
336
+ const v = args.headerParams[k];
337
+ if (v !== undefined && v !== null)
338
+ headers[name.toLowerCase()] = String(v);
339
+ }
340
+ }
341
+ const body = this.encodeBody(op, args, headers);
342
+ const path = pathStr + query;
343
+ const url = route.base + path;
344
+ if (o.signal?.aborted)
345
+ throw new B3OSAbortError({ operationId: op.id, cause: o.signal.reason });
346
+ const t0 = performance.now();
347
+ let res;
348
+ try {
349
+ // The transport enforces the per-attempt timeout (for streams: until the response head) and the signal.
350
+ res = await route.transport.send({
351
+ method,
352
+ url,
353
+ path,
354
+ headers,
355
+ body,
356
+ signal: o.signal,
357
+ timeoutMs: perAttempt,
358
+ stream: !!x.sse,
359
+ });
360
+ }
361
+ catch (cause) {
362
+ if (o.signal?.aborted)
363
+ throw new B3OSAbortError({ operationId: op.id, cause });
364
+ const timedOut = cause instanceof TransportTimeout;
365
+ if (route.auto && connectRefused(cause) && !timedOut) {
366
+ // The node socket exists but refuses us (permissions, stale socket): use the API from now on.
367
+ this.node = this.edge;
368
+ route = this.edge;
369
+ continue;
370
+ }
371
+ const err = timedOut
372
+ ? new B3OSTimeoutError({
373
+ detail: `${op.id} did not answer within ${perAttempt} ms (${route.transport.label})`,
374
+ operationId: op.id,
375
+ cause,
376
+ })
377
+ : new B3OSConnectionError({
378
+ detail: `Could not reach ${route.transport.label}: ${describeErr(cause)}`,
379
+ operationId: op.id,
380
+ cause,
381
+ });
382
+ // Timeouts are not retried: the budget is spent. A refused connection never reached the server.
383
+ if (!timedOut && attempt < maxRetries && (retrySafe || connectRefused(cause))) {
384
+ await sleep(backoffMs(attempt), o.signal).catch(() => { });
385
+ attempt++;
386
+ continue;
387
+ }
388
+ throw err;
389
+ }
390
+ const elapsed = performance.now() - t0;
391
+ const info = new ResponseInfo({
392
+ operationId: op.id,
393
+ method,
394
+ url: route.kind === "uds" ? `${route.transport.label}${path}` : url,
395
+ status: res.status,
396
+ headers: res.headers,
397
+ transport: route.transport.kind,
398
+ attempts: attempt + 1,
399
+ elapsedMs: elapsed,
400
+ idempotencyKey: idemKey,
401
+ });
402
+ try {
403
+ this.onResponse?.(info);
404
+ }
405
+ catch {
406
+ // A logging hook must never break the call.
407
+ }
408
+ if ((res.status >= 200 && res.status < 300) || res.status === 101) {
409
+ return { res, info };
410
+ }
411
+ // An error answer: read it, decide whether to retry.
412
+ let text = "";
413
+ try {
414
+ text = await res.text();
415
+ }
416
+ catch {
417
+ text = "";
418
+ }
419
+ const ct = res.headers.get("content-type");
420
+ const parsed = parseErrorBody(res.status, ct, text);
421
+ const retryAfterMs = parseRetryAfter(res.headers.get("retry-after")) ??
422
+ (parsed.retryAfterS !== undefined ? parsed.retryAfterS * 1000 : null);
423
+ const err0 = new B3OSError({
424
+ code: parsed.code,
425
+ status: res.status,
426
+ title: parsed.title,
427
+ detail: parsed.detail,
428
+ type: parsed.type,
429
+ requestId: parsed.instance ?? res.headers.get("x-request-id"),
430
+ errors: parsed.errors,
431
+ problem: parsed.problem,
432
+ headers: res.headers,
433
+ timing: info.timing,
434
+ retryAfterMs,
435
+ operationId: op.id,
436
+ });
437
+ const hint = this.hint(route, op, err0);
438
+ const err = hint
439
+ ? new B3OSError({
440
+ code: err0.code,
441
+ status: err0.status,
442
+ title: err0.title,
443
+ detail: err0.detail,
444
+ type: err0.type,
445
+ requestId: err0.requestId,
446
+ errors: err0.errors,
447
+ problem: err0.problem,
448
+ headers: err0.headers,
449
+ timing: err0.timing,
450
+ retryAfterMs,
451
+ operationId: op.id,
452
+ hint,
453
+ })
454
+ : err0;
455
+ const rejectedBeforeWork = REJECTED_BEFORE_WORK.has(err.code) && (!parsed.codeFromStatus || NEVER_REACHED_STATUSES.has(res.status));
456
+ const retryable = rejectedBeforeWork ||
457
+ (retrySafe && err.retryable && (err.status ?? 0) >= 500 && !NO_RETRY_TIMEOUT_CODES.has(err.code));
458
+ if (attempt < maxRetries && retryable) {
459
+ const delay = retryAfterMs ?? backoffMs(attempt);
460
+ if (delay <= this.maxRetryDelayMs) {
461
+ await sleep(delay + Math.random() * Math.min(250, delay * 0.1), o.signal).catch(() => { });
462
+ if (o.signal?.aborted)
463
+ throw new B3OSAbortError({ operationId: op.id });
464
+ attempt++;
465
+ continue;
466
+ }
467
+ }
468
+ throw err;
469
+ }
470
+ }
471
+ async readBody(sent, op, expect, signal) {
472
+ const { res } = sent;
473
+ try {
474
+ if (res.status === 204 || res.status === 101 || op.method === "HEAD") {
475
+ res.cancel();
476
+ return undefined;
477
+ }
478
+ const ct = res.headers.get("content-type") ?? "";
479
+ const isJson = JSON_CT.test(ct);
480
+ if (expect === "bytes" || (expect === "auto" && !isJson && !ct.startsWith("text/"))) {
481
+ return await res.bytes();
482
+ }
483
+ const text = await res.text();
484
+ if (expect === "text" || (expect === "auto" && !isJson))
485
+ return text;
486
+ if (text === "")
487
+ return undefined;
488
+ try {
489
+ return JSON.parse(text);
490
+ }
491
+ catch (cause) {
492
+ throw new B3OSError({
493
+ code: "invalid_response",
494
+ status: res.status,
495
+ detail: `${op.id} answered ${res.status} with a body that is not JSON (${ct || "no content type"})`,
496
+ requestId: res.headers.get("x-request-id"),
497
+ headers: res.headers,
498
+ operationId: op.id,
499
+ cause,
500
+ });
501
+ }
502
+ }
503
+ catch (e) {
504
+ if (e instanceof B3OSError)
505
+ throw e;
506
+ if (e instanceof TransportTimeout) {
507
+ throw new B3OSTimeoutError({
508
+ detail: `${op.id}: the response body did not arrive in time`,
509
+ operationId: op.id,
510
+ cause: e,
511
+ });
512
+ }
513
+ if (signal?.aborted)
514
+ throw new B3OSAbortError({ operationId: op.id, cause: e });
515
+ throw new B3OSConnectionError({
516
+ detail: `The response body of ${op.id} broke: ${describeErr(e)}`,
517
+ operationId: op.id,
518
+ cause: e,
519
+ });
520
+ }
521
+ }
522
+ async exec(op, args, o, accept = "application/json", expect = "auto", extraQuery) {
523
+ const sent = await this.send(op, args, o, { accept, extraQuery });
524
+ const data = (await this.readBody(sent, op, expect, o.signal));
525
+ remember(data, sent.info);
526
+ return { data, response: sent.info };
527
+ }
528
+ // ------------------------------------------------------------------------------------------------------------
529
+ // What the generated namespaces call
530
+ /** @internal One request, parsed by content type. */
531
+ _call(op, args, options = {}, accept, expect = "auto") {
532
+ return new APIPromise(this.exec(op, args, options, accept ?? "application/json", expect));
533
+ }
534
+ /** @internal A list operation (cursor pagination). */
535
+ _list(op, args, options = {}) {
536
+ const next = (cursor) => this._call(op, { ...args, query: { ...(args.query ?? {}), cursor } }, options);
537
+ return new ListPromise(this.exec(op, args, options), next);
538
+ }
539
+ /** @internal A GET event stream (job events, logs), resumed with Last-Event-ID. */
540
+ _stream(op, args, options = {}, behavior = {}) {
541
+ return new EventStream(this.streamOptions(op, args, options, behavior));
542
+ }
543
+ streamOptions(op, args, options, behavior) {
544
+ return {
545
+ operationId: op.id,
546
+ resumable: true,
547
+ reconnectOnEnd: behavior.reconnectOnEnd ?? false,
548
+ idleTimeoutMs: options.idleTimeoutMs,
549
+ maxReconnects: options.maxReconnects,
550
+ signal: options.signal,
551
+ isTerminal: behavior.terminal ? (ev) => behavior.terminal?.(ev) ?? false : undefined,
552
+ open: async (ctx) => {
553
+ const lastId = ctx.lastEventId ?? (ctx.attempt === 0 ? options.lastEventId : undefined);
554
+ const headers = { ...(options.headers ?? {}) };
555
+ if (lastId !== undefined)
556
+ headers["last-event-id"] = lastId;
557
+ const sent = await this.send(op, args, { ...options, headers, signal: ctx.signal, maxRetries: ctx.attempt === 0 ? options.maxRetries : 0 }, { accept: "text/event-stream", sse: true });
558
+ return this.expectEventStream(sent, op);
559
+ },
560
+ };
561
+ }
562
+ expectEventStream(sent, op) {
563
+ const res = sent.res;
564
+ const ct = res.headers.get("content-type") ?? "";
565
+ if (!ct.startsWith("text/event-stream")) {
566
+ res.cancel();
567
+ throw new B3OSError({
568
+ code: "invalid_response",
569
+ status: res.status,
570
+ detail: `${op.id} answered ${res.status} with ${ct || "no content type"} instead of an event stream`,
571
+ requestId: sent.info.requestId,
572
+ operationId: op.id,
573
+ });
574
+ }
575
+ return res;
576
+ }
577
+ /** @internal An SSE response to a POST (exec output, chat chunks): not resumable. */
578
+ _postStream(op, args, options = {}, behavior = {}) {
579
+ return new EventStream({
580
+ operationId: op.id,
581
+ resumable: false,
582
+ doneSentinel: behavior.doneSentinel,
583
+ idleTimeoutMs: options.idleTimeoutMs,
584
+ signal: options.signal,
585
+ isTerminal: behavior.terminal ? (ev) => behavior.terminal?.(ev) ?? false : undefined,
586
+ open: async (ctx) => {
587
+ const sent = await this.send(op, args, { ...options, signal: ctx.signal }, { accept: "text/event-stream", sse: true, extraQuery: behavior.extraQuery });
588
+ return this.expectEventStream(sent, op);
589
+ },
590
+ });
591
+ }
592
+ /** @internal A job-creating operation (`x-b3os-job`). */
593
+ _job(op, args, options = {}) {
594
+ const ops = op.job;
595
+ if (!ops)
596
+ throw new Error(`@b3os/sdk: ${op.id} is not a job operation`);
597
+ // One idempotency key for every request that creates this job, whatever the mode.
598
+ const o = op.idem ? { ...options, idempotencyKey: options.idempotencyKey ?? uuid() } : options;
599
+ const runner = {
600
+ create: () => this.exec(op, args, o),
601
+ createAndWait: async (w) => {
602
+ const deadline = Date.now() + (w.timeoutMs ?? ops.events.timeoutMs);
603
+ const waitS = Math.max(0, Math.min(60, Math.floor((deadline - Date.now()) / 1000)));
604
+ const first = await this.exec(op, args, { ...o, signal: w.signal ?? o.signal }, "application/json", "auto", {
605
+ wait: String(waitS),
606
+ });
607
+ const data = await this.waitJob(ops, first.data, { ...w, timeoutMs: deadline - Date.now() });
608
+ return { data, response: first.response };
609
+ },
610
+ createAndStream: (so) => this.createStream(op, args, o, so),
611
+ waitFor: (job, w) => this.waitJob(ops, job, w),
612
+ eventsFor: (created, so) => this.jobEventStream(ops, created, so),
613
+ };
614
+ return new JobPromise(runner);
615
+ }
616
+ createStream(op, args, o, so) {
617
+ const ops = op.job;
618
+ return new JobEventStream({
619
+ operationId: op.id,
620
+ resumable: true,
621
+ reconnectOnEnd: true,
622
+ idleTimeoutMs: so.idleTimeoutMs,
623
+ maxReconnects: so.maxReconnects,
624
+ signal: so.signal ?? o.signal,
625
+ isTerminal: (ev) => TERMINAL_JOB_EVENTS.has(eventType(ev) ?? ""),
626
+ open: async (ctx) => {
627
+ if (ctx.attempt === 0) {
628
+ const sent = await this.send(op, args, { ...o, headers: { ...o.headers, ...so.headers }, signal: ctx.signal }, {
629
+ accept: "text/event-stream",
630
+ sse: true,
631
+ });
632
+ return this.expectEventStream(sent, op);
633
+ }
634
+ const jobId = isObject(ctx.lastEvent) && typeof ctx.lastEvent.job_id === "string" ? ctx.lastEvent.job_id : null;
635
+ if (!jobId) {
636
+ throw new B3OSError({
637
+ code: "stream_interrupted",
638
+ detail: `${op.id}: the stream broke before the first event, so the job id is unknown`,
639
+ operationId: op.id,
640
+ });
641
+ }
642
+ const headers = { ...(so.headers ?? {}) };
643
+ if (ctx.lastEventId !== undefined)
644
+ headers["last-event-id"] = ctx.lastEventId;
645
+ const sent = await this.send(ops.events, { path: [jobId] }, { headers, signal: ctx.signal, maxRetries: 0 }, { accept: "text/event-stream", sse: true });
646
+ return this.expectEventStream(sent, ops.events);
647
+ },
648
+ }, (terminal) => this.finalJobFromEvent(ops, terminal));
649
+ }
650
+ async finalJobFromEvent(ops, ev) {
651
+ if (isObject(ev) && isObject(ev.job) && isTerminalJob(ev.job))
652
+ return ev.job;
653
+ const id = isObject(ev) && typeof ev.job_id === "string" ? ev.job_id : undefined;
654
+ if (!id)
655
+ throw new Error("@b3os/sdk: terminal event without a job");
656
+ return (await this.exec(ops.get, { path: [id] }, {})).data;
657
+ }
658
+ jobEventStream(ops, jobOrId, so) {
659
+ return new JobEventStream({
660
+ operationId: ops.events.id,
661
+ resumable: true,
662
+ reconnectOnEnd: true,
663
+ idleTimeoutMs: so.idleTimeoutMs,
664
+ maxReconnects: so.maxReconnects,
665
+ signal: so.signal,
666
+ isTerminal: (ev) => TERMINAL_JOB_EVENTS.has(eventType(ev) ?? ""),
667
+ open: async (ctx) => {
668
+ const id = jobIdOf(await jobOrId);
669
+ const headers = { ...(so.headers ?? {}) };
670
+ const lastId = ctx.lastEventId ?? (ctx.attempt === 0 ? so.lastEventId : undefined);
671
+ if (lastId !== undefined)
672
+ headers["last-event-id"] = lastId;
673
+ const sent = await this.send(ops.events, { path: [id] }, { headers, signal: ctx.signal, maxRetries: ctx.attempt === 0 ? undefined : 0 }, { accept: "text/event-stream", sse: true });
674
+ return this.expectEventStream(sent, ops.events);
675
+ },
676
+ }, (terminal) => this.finalJobFromEvent(ops, terminal));
677
+ }
678
+ finishJob(job, w) {
679
+ const j = job;
680
+ if (j.status === "succeeded" || w.throwOnFailure === false)
681
+ return job;
682
+ const e = isObject(j.error) ? j.error : {};
683
+ const code = typeof e.code === "string" ? e.code : j.status === "canceled" ? "job_canceled" : "internal";
684
+ throw new B3OSJobError(job, {
685
+ code,
686
+ status: typeof e.status === "number" ? e.status : null,
687
+ title: typeof e.title === "string" ? e.title : undefined,
688
+ detail: typeof e.detail === "string" ? e.detail : `${j.object} ${j.id} ${j.status}`,
689
+ requestId: typeof e.instance === "string" ? e.instance : null,
690
+ problem: isObject(j.error) ? j.error : null,
691
+ });
692
+ }
693
+ /** @internal Waits until a job is terminal: its event stream first, polling as the fallback. */
694
+ async waitJob(ops, jobOrId, w = {}) {
695
+ if (typeof jobOrId !== "string" && isTerminalJob(jobOrId))
696
+ return this.finishJob(jobOrId, w);
697
+ const id = jobIdOf(jobOrId);
698
+ const deadline = Date.now() + (w.timeoutMs ?? ops.events.timeoutMs);
699
+ const ac = new AbortController();
700
+ const onAbort = () => ac.abort(w.signal?.reason);
701
+ w.signal?.addEventListener("abort", onAbort, { once: true });
702
+ const timer = setTimeout(() => ac.abort(new Error("deadline")), Math.max(0, deadline - Date.now()));
703
+ let polling = false;
704
+ let pollAttempt = 0;
705
+ try {
706
+ for (;;) {
707
+ if (w.signal?.aborted)
708
+ throw new B3OSAbortError({ operationId: ops.get.id });
709
+ if (Date.now() >= deadline)
710
+ break;
711
+ if (!polling) {
712
+ try {
713
+ const stream = this.jobEventStream(ops, id, { signal: ac.signal });
714
+ for await (const ev of stream) {
715
+ w.onEvent?.(ev);
716
+ if (TERMINAL_JOB_EVENTS.has(eventType(ev) ?? "")) {
717
+ return this.finishJob(await this.finalJobFromEvent(ops, ev), w);
718
+ }
719
+ }
720
+ }
721
+ catch (e) {
722
+ if (w.signal?.aborted)
723
+ throw new B3OSAbortError({ operationId: ops.events.id, cause: e });
724
+ if (ac.signal.aborted)
725
+ break;
726
+ if (!(e instanceof B3OSError))
727
+ throw e;
728
+ if (e.code === "route_not_found" ||
729
+ e.code === "not_implemented" ||
730
+ e.code === "invalid_response" ||
731
+ e.status === 405 ||
732
+ e.status === 406) {
733
+ // No usable events operation on this deployment: poll the job instead.
734
+ polling = true;
735
+ }
736
+ else if (e.status === 401 || e.status === 403 || e.status === 404 || e.status === 410) {
737
+ throw e;
738
+ }
739
+ else if (!e.retryable && e.code !== "stream_interrupted") {
740
+ throw e;
741
+ }
742
+ // Otherwise transient: check the job, then reconnect.
743
+ }
744
+ }
745
+ const cur = await this.exec(ops.get, { path: [id] }, { signal: ac.signal }).catch((e) => {
746
+ if (ac.signal.aborted && !w.signal?.aborted)
747
+ return null;
748
+ throw e;
749
+ });
750
+ if (cur === null)
751
+ break;
752
+ if (isTerminalJob(cur.data))
753
+ return this.finishJob(cur.data, w);
754
+ const ra = parseRetryAfter(cur.response.headers.get("retry-after"));
755
+ await sleep(Math.min(Math.max(0, deadline - Date.now()), ra ?? backoffMs(pollAttempt++, 1000, 5000)), ac.signal).catch(() => { });
756
+ }
757
+ }
758
+ finally {
759
+ clearTimeout(timer);
760
+ w.signal?.removeEventListener("abort", onAbort);
761
+ }
762
+ if (w.signal?.aborted)
763
+ throw new B3OSAbortError({ operationId: ops.get.id });
764
+ throw new B3OSTimeoutError({
765
+ detail: `${id} was not finished after ${w.timeoutMs ?? ops.events.timeoutMs} ms; it keeps running on the server`,
766
+ operationId: ops.get.id,
767
+ });
768
+ }
769
+ /** @internal Events of an existing job. */
770
+ _jobEvents(ops, job, so = {}) {
771
+ return this.jobEventStream(ops, job, so);
772
+ }
773
+ /** @internal Raw send for helpers that need the response (WebSocket tickets, downloads). */
774
+ _send(op, args, options, accept) {
775
+ return this.send(op, args, options, { accept });
776
+ }
777
+ /** @internal The route an operation would use (helpers that open WebSockets need the base URL). */
778
+ _routeFor(op) {
779
+ const r = op.edge ? this.edge : this.node;
780
+ return { base: r.base, kind: r.kind, auth: r.auth };
781
+ }
782
+ /** @internal Whether a WebSocket can take the operation's route (not over the Unix socket). */
783
+ _wsRoute(op) {
784
+ const r = op.edge ? this.edge : this.node;
785
+ if (r.kind !== "uds")
786
+ return { base: r.base, kind: r.kind };
787
+ if (this.apiKey)
788
+ return { base: this.edge.base, kind: "edge" };
789
+ throw new B3OSError({
790
+ code: "unsupported_transport",
791
+ detail: `${op.id} opens a WebSocket, which the SDK cannot carry over the Unix socket`,
792
+ hint: "Set B3OS_API_KEY so it goes through beta-api.b3os.org, or B3OS_API_URL to a node URL",
793
+ operationId: op.id,
794
+ });
795
+ }
796
+ // ------------------------------------------------------------------------------------------------------------
797
+ // Public escape hatch
798
+ /**
799
+ * Calls any operation by method and path, for endpoints the namespaces do not wrap (device login) or newer than
800
+ * this SDK. Account paths (`/v1/keys`, `/v1/auth`, …) go to the edge unless `edge` says otherwise.
801
+ */
802
+ request(req, options = {}) {
803
+ const op = {
804
+ id: `${req.method} ${req.path}`,
805
+ method: req.method,
806
+ path: req.path.includes("{") ? req.path.replace(/[{}]/g, "") : req.path,
807
+ edge: req.edge ?? EDGE_PATHS.test(req.path),
808
+ timeoutMs: req.timeoutMs ?? 65_000,
809
+ errorFormat: req.errorFormat,
810
+ scope: "unknown",
811
+ };
812
+ const args = { query: req.query, body: req.body, bodyType: req.bodyType };
813
+ const o = req.headers ? { ...options, headers: { ...req.headers, ...options.headers } } : options;
814
+ return new APIPromise(this.exec(op, args, o));
815
+ }
816
+ /** @internal SSE parse helper for namespaces. */
817
+ static parseJsonEvent(msg) {
818
+ return JSON.parse(msg.data);
819
+ }
820
+ }
821
+ //# sourceMappingURL=client.js.map