@bitfab/sdk 0.65.4 → 0.65.5

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 (170) hide show
  1. package/dist/autoTrace-CZu0BXhG.js +270 -0
  2. package/dist/autoTrace-CZu0BXhG.js.map +1 -0
  3. package/dist/autoTrace-KM9pYqk9.cjs +395 -0
  4. package/dist/autoTrace-KM9pYqk9.cjs.map +1 -0
  5. package/dist/autoTrace.cjs +15 -353
  6. package/dist/autoTrace.d.cts +44 -44
  7. package/dist/autoTrace.d.ts +44 -44
  8. package/dist/autoTrace.js +1 -28
  9. package/dist/babelPlugin-C70OxrqA.js +209 -0
  10. package/dist/babelPlugin-C70OxrqA.js.map +1 -0
  11. package/dist/babelPlugin-Nta4-VcL.cjs +232 -0
  12. package/dist/babelPlugin-Nta4-VcL.cjs.map +1 -0
  13. package/dist/http-CG1Irqxx.js +2154 -0
  14. package/dist/http-CG1Irqxx.js.map +1 -0
  15. package/dist/index-BFkAwvuc.d.cts +4410 -0
  16. package/dist/index-BFkAwvuc.d.ts +4410 -0
  17. package/dist/index.cjs +48 -12504
  18. package/dist/index.d.cts +2 -4443
  19. package/dist/index.d.ts +2 -4443
  20. package/dist/index.js +3 -96
  21. package/dist/loaderRuntime-0huddOOP.d.ts +12 -0
  22. package/dist/loaderRuntime-CslfDFO7.d.cts +12 -0
  23. package/dist/node.cjs +56 -12520
  24. package/dist/node.cjs.map +1 -1
  25. package/dist/node.d.cts +2 -1
  26. package/dist/node.d.ts +2 -1
  27. package/dist/node.js +10 -105
  28. package/dist/node.js.map +1 -1
  29. package/dist/registryCommand-Di8x0YoJ.js +1111 -0
  30. package/dist/registryCommand-Di8x0YoJ.js.map +1 -0
  31. package/dist/replayCli.js +49 -87
  32. package/dist/replayCli.js.map +1 -1
  33. package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
  34. package/dist/seedCli.js +10 -24
  35. package/dist/seedCli.js.map +1 -1
  36. package/dist/src-BRKm0P_S.cjs +8434 -0
  37. package/dist/src-BRKm0P_S.cjs.map +1 -0
  38. package/dist/src-CfFkki5l.js +6011 -0
  39. package/dist/src-CfFkki5l.js.map +1 -0
  40. package/dist/transform/babel.cjs +5 -422
  41. package/dist/transform/babel.d.cts +16 -16
  42. package/dist/transform/babel.d.ts +16 -16
  43. package/dist/transform/babel.js +1 -7
  44. package/dist/transform/bun.cjs +9 -478
  45. package/dist/transform/bun.cjs.map +1 -1
  46. package/dist/transform/bun.d.cts +5 -7
  47. package/dist/transform/bun.d.ts +5 -7
  48. package/dist/transform/bun.js +6 -11
  49. package/dist/transform/bun.js.map +1 -1
  50. package/dist/transform/esbuild.cjs +9 -478
  51. package/dist/transform/esbuild.cjs.map +1 -1
  52. package/dist/transform/esbuild.d.cts +5 -7
  53. package/dist/transform/esbuild.d.ts +5 -7
  54. package/dist/transform/esbuild.js +6 -11
  55. package/dist/transform/esbuild.js.map +1 -1
  56. package/dist/transform/loaderRuntime.cjs +85 -532
  57. package/dist/transform/loaderRuntime.cjs.map +1 -1
  58. package/dist/transform/loaderRuntime.d.cts +2 -12
  59. package/dist/transform/loaderRuntime.d.ts +2 -12
  60. package/dist/transform/loaderRuntime.js +56 -98
  61. package/dist/transform/loaderRuntime.js.map +1 -1
  62. package/dist/transform/nest.cjs +12 -481
  63. package/dist/transform/nest.cjs.map +1 -1
  64. package/dist/transform/nest.d.cts +8 -9
  65. package/dist/transform/nest.d.ts +8 -9
  66. package/dist/transform/nest.js +9 -14
  67. package/dist/transform/nest.js.map +1 -1
  68. package/dist/transform/next.cjs +56 -528
  69. package/dist/transform/next.cjs.map +1 -1
  70. package/dist/transform/next.d.cts +25 -25
  71. package/dist/transform/next.d.ts +24 -24
  72. package/dist/transform/next.js +52 -60
  73. package/dist/transform/next.js.map +1 -1
  74. package/dist/transform/nodeLoader.js +260 -506
  75. package/dist/transform/nodeLoader.js.map +1 -1
  76. package/dist/transform/register.js +4 -1
  77. package/dist/transform/register.js.map +1 -1
  78. package/dist/transform/rolldown.cjs +9 -478
  79. package/dist/transform/rolldown.cjs.map +1 -1
  80. package/dist/transform/rolldown.d.cts +5 -7
  81. package/dist/transform/rolldown.d.ts +5 -7
  82. package/dist/transform/rolldown.js +6 -11
  83. package/dist/transform/rolldown.js.map +1 -1
  84. package/dist/transform/rollup.cjs +9 -478
  85. package/dist/transform/rollup.cjs.map +1 -1
  86. package/dist/transform/rollup.d.cts +5 -7
  87. package/dist/transform/rollup.d.ts +5 -7
  88. package/dist/transform/rollup.js +6 -11
  89. package/dist/transform/rollup.js.map +1 -1
  90. package/dist/transform/rsbuild.cjs +9 -478
  91. package/dist/transform/rsbuild.cjs.map +1 -1
  92. package/dist/transform/rsbuild.d.cts +5 -7
  93. package/dist/transform/rsbuild.d.ts +5 -7
  94. package/dist/transform/rsbuild.js +6 -11
  95. package/dist/transform/rsbuild.js.map +1 -1
  96. package/dist/transform/rspack.cjs +9 -478
  97. package/dist/transform/rspack.cjs.map +1 -1
  98. package/dist/transform/rspack.d.cts +5 -7
  99. package/dist/transform/rspack.d.ts +5 -7
  100. package/dist/transform/rspack.js +6 -11
  101. package/dist/transform/rspack.js.map +1 -1
  102. package/dist/transform/swc.cjs +18 -486
  103. package/dist/transform/swc.cjs.map +1 -1
  104. package/dist/transform/swc.d.cts +15 -14
  105. package/dist/transform/swc.d.ts +15 -14
  106. package/dist/transform/swc.js +14 -32
  107. package/dist/transform/swc.js.map +1 -1
  108. package/dist/transform/unplugin.cjs +20 -476
  109. package/dist/transform/unplugin.cjs.map +1 -1
  110. package/dist/transform/unplugin.d.cts +4 -6
  111. package/dist/transform/unplugin.d.ts +4 -6
  112. package/dist/transform/unplugin.js +19 -8
  113. package/dist/transform/unplugin.js.map +1 -1
  114. package/dist/transform/vite.cjs +9 -478
  115. package/dist/transform/vite.cjs.map +1 -1
  116. package/dist/transform/vite.d.cts +5 -7
  117. package/dist/transform/vite.d.ts +5 -7
  118. package/dist/transform/vite.js +6 -11
  119. package/dist/transform/vite.js.map +1 -1
  120. package/dist/transform/webpack.cjs +9 -478
  121. package/dist/transform/webpack.cjs.map +1 -1
  122. package/dist/transform/webpack.d.cts +5 -7
  123. package/dist/transform/webpack.d.ts +5 -7
  124. package/dist/transform/webpack.js +6 -11
  125. package/dist/transform/webpack.js.map +1 -1
  126. package/dist/transform-BcyUocwm.js +36 -0
  127. package/dist/transform-BcyUocwm.js.map +1 -0
  128. package/dist/transform-BjxHGGKc.cjs +47 -0
  129. package/dist/transform-BjxHGGKc.cjs.map +1 -0
  130. package/dist/transformOptions-BsjCELkh.d.cts +11 -0
  131. package/dist/transformOptions-BsjCELkh.d.ts +11 -0
  132. package/package.json +5 -5
  133. package/dist/autoTrace.cjs.map +0 -1
  134. package/dist/autoTrace.js.map +0 -1
  135. package/dist/chunk-27B3UBSS.js +0 -2547
  136. package/dist/chunk-27B3UBSS.js.map +0 -1
  137. package/dist/chunk-B2M4KELA.js +0 -1912
  138. package/dist/chunk-B2M4KELA.js.map +0 -1
  139. package/dist/chunk-I233ERUH.js +0 -2979
  140. package/dist/chunk-I233ERUH.js.map +0 -1
  141. package/dist/chunk-ISU6FQKY.js +0 -6877
  142. package/dist/chunk-ISU6FQKY.js.map +0 -1
  143. package/dist/chunk-MT36GJMW.js +0 -106
  144. package/dist/chunk-MT36GJMW.js.map +0 -1
  145. package/dist/chunk-PTCLRG4E.js +0 -28
  146. package/dist/chunk-PTCLRG4E.js.map +0 -1
  147. package/dist/chunk-QRNHRY7F.js +0 -270
  148. package/dist/chunk-QRNHRY7F.js.map +0 -1
  149. package/dist/chunk-R6M54SPO.js +0 -1176
  150. package/dist/chunk-R6M54SPO.js.map +0 -1
  151. package/dist/chunk-SOP5AFMH.js +0 -2060
  152. package/dist/chunk-SOP5AFMH.js.map +0 -1
  153. package/dist/chunk-YVJAOGHE.js +0 -45
  154. package/dist/chunk-YVJAOGHE.js.map +0 -1
  155. package/dist/chunk-ZG6SHKEF.js +0 -404
  156. package/dist/chunk-ZG6SHKEF.js.map +0 -1
  157. package/dist/http-LL3JD2JE.js +0 -24
  158. package/dist/http-LL3JD2JE.js.map +0 -1
  159. package/dist/http-QZDTQC3C.js +0 -23
  160. package/dist/http-QZDTQC3C.js.map +0 -1
  161. package/dist/index.cjs.map +0 -1
  162. package/dist/index.js.map +0 -1
  163. package/dist/replay-636XZIS2.js +0 -29
  164. package/dist/replay-636XZIS2.js.map +0 -1
  165. package/dist/replay-S4DNF4VR.js +0 -28
  166. package/dist/replay-S4DNF4VR.js.map +0 -1
  167. package/dist/transform/babel.cjs.map +0 -1
  168. package/dist/transform/babel.js.map +0 -1
  169. package/dist/transformOptions-Df2_Chtc.d.cts +0 -10
  170. package/dist/transformOptions-Df2_Chtc.d.ts +0 -10
@@ -1,2547 +0,0 @@
1
- // src/traceCompletion.ts
2
- var TraceCompletion = class {
3
- constructor() {
4
- this.traces = /* @__PURE__ */ new Map();
5
- this.closed = /* @__PURE__ */ new Map();
6
- }
7
- state(traceId) {
8
- let state = this.traces.get(traceId);
9
- if (state === void 0) {
10
- state = { spanIds: /* @__PURE__ */ new Set(), active: /* @__PURE__ */ new Set() };
11
- this.traces.set(traceId, state);
12
- }
13
- return state;
14
- }
15
- start(traceId, spanId) {
16
- if (this.closed.has(traceId)) {
17
- return;
18
- }
19
- const state = this.state(traceId);
20
- state.spanIds.add(spanId);
21
- state.active.add(spanId);
22
- }
23
- open(traceId) {
24
- if (!this.closed.has(traceId)) {
25
- this.state(traceId);
26
- }
27
- }
28
- hold(traceId, key) {
29
- this.state(traceId).active.add(key);
30
- }
31
- record(traceId, spanId) {
32
- if (!this.closed.has(traceId)) {
33
- this.state(traceId).spanIds.add(spanId);
34
- }
35
- }
36
- end(traceId, spanId) {
37
- const state = this.traces.get(traceId);
38
- if (state !== void 0) {
39
- state.active.delete(spanId);
40
- this.drain(traceId, state);
41
- }
42
- }
43
- abort(traceId, spanId) {
44
- const state = this.traces.get(traceId);
45
- if (state === void 0) {
46
- return;
47
- }
48
- state.active.delete(spanId);
49
- state.spanIds.delete(spanId);
50
- if (state.active.size === 0 && state.spanIds.size === 0 && state.complete === void 0) {
51
- this.traces.delete(traceId);
52
- return;
53
- }
54
- this.drain(traceId, state);
55
- }
56
- close(traceId, complete, dropped = false) {
57
- const count = this.closed.get(traceId);
58
- if (count !== void 0) {
59
- complete(count);
60
- return;
61
- }
62
- const state = this.traces.get(traceId);
63
- if (state === void 0) {
64
- return;
65
- }
66
- state.complete = complete;
67
- if (dropped) {
68
- state.active.clear();
69
- }
70
- this.drain(traceId, state);
71
- }
72
- drain(traceId, state) {
73
- if (state.active.size !== 0 || state.complete === void 0) {
74
- return;
75
- }
76
- this.traces.delete(traceId);
77
- this.closed.set(traceId, state.spanIds.size);
78
- if (this.closed.size > 1024) {
79
- const oldest = this.closed.keys().next().value;
80
- if (oldest !== void 0) {
81
- this.closed.delete(oldest);
82
- }
83
- }
84
- state.complete(state.spanIds.size);
85
- }
86
- };
87
-
88
- // src/readEnv.ts
89
- function readEnv(name) {
90
- if (typeof process !== "undefined" && process.env) {
91
- return process.env[name];
92
- }
93
- return void 0;
94
- }
95
-
96
- // src/compress.ts
97
- var DISABLE_COMPRESSION_ENV = "BITFAB_DISABLE_COMPRESSION";
98
- var MIN_COMPRESSED_BYTES = 8192;
99
- var gzipNode;
100
- var _nodeGzipReady = (typeof process !== "undefined" && process.versions?.node ? (
101
- // The join trick hides "node:zlib" from static analysis so bundlers that
102
- // ban Node.js built-ins don't fail at build time. webpackIgnore tells
103
- // webpack/turbopack to emit a native import() so Node.js can resolve the
104
- // module at runtime. Same pattern as `asyncStorage.ts`.
105
- import(
106
- /* webpackIgnore: true */
107
- ["node", "zlib"].join(":")
108
- ).then(({ gzip }) => {
109
- gzipNode = (data) => new Promise((resolve, reject) => {
110
- gzip(data, (error, result) => {
111
- if (error) {
112
- reject(error);
113
- } else {
114
- resolve(result);
115
- }
116
- });
117
- });
118
- }).catch(() => {
119
- })
120
- ) : Promise.resolve()).then(() => {
121
- });
122
- function toArrayBuffer(view) {
123
- return view.buffer.slice(
124
- view.byteOffset,
125
- view.byteOffset + view.byteLength
126
- );
127
- }
128
- function compressedRequest(body, rawBytes, compressed) {
129
- if (compressed.byteLength >= rawBytes) {
130
- return { body, rawBytes, wireBytes: rawBytes };
131
- }
132
- return {
133
- body: compressed instanceof Uint8Array ? toArrayBuffer(compressed) : compressed,
134
- contentEncoding: "gzip",
135
- rawBytes,
136
- wireBytes: compressed.byteLength
137
- };
138
- }
139
- async function gzipViaStream(bytes) {
140
- const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream("gzip"));
141
- return await new Response(stream).arrayBuffer();
142
- }
143
- function encodeRequestBody(body) {
144
- if (readEnv(DISABLE_COMPRESSION_ENV)) {
145
- const rawBytes = new TextEncoder().encode(body).byteLength;
146
- return { body, rawBytes, wireBytes: rawBytes };
147
- }
148
- const bytes = new TextEncoder().encode(body);
149
- if (bytes.byteLength < MIN_COMPRESSED_BYTES) {
150
- return {
151
- body,
152
- rawBytes: bytes.byteLength,
153
- wireBytes: bytes.byteLength
154
- };
155
- }
156
- if (gzipNode) {
157
- return gzipNode(bytes).then(
158
- (compressed) => compressedRequest(body, bytes.byteLength, compressed),
159
- () => ({
160
- body,
161
- rawBytes: bytes.byteLength,
162
- wireBytes: bytes.byteLength
163
- })
164
- );
165
- }
166
- if (typeof CompressionStream === "undefined") {
167
- return {
168
- body,
169
- rawBytes: bytes.byteLength,
170
- wireBytes: bytes.byteLength
171
- };
172
- }
173
- return gzipViaStream(bytes).then(
174
- (compressed) => compressedRequest(body, bytes.byteLength, compressed),
175
- () => ({
176
- body,
177
- rawBytes: bytes.byteLength,
178
- wireBytes: bytes.byteLength
179
- })
180
- );
181
- }
182
-
183
- // src/version.generated.ts
184
- var __version__ = "0.65.4";
185
- var __packageName__ = "@bitfab/sdk";
186
-
187
- // src/errors.ts
188
- var BitfabError = class extends Error {
189
- constructor(message, url, status, retryAfterMs) {
190
- super(message);
191
- this.url = url;
192
- this.status = status;
193
- this.retryAfterMs = retryAfterMs;
194
- this.name = "BitfabError";
195
- }
196
- };
197
-
198
- // src/gitCommand.ts
199
- var EXIT_GRACE_MS = 500;
200
- function isUnrefable(value) {
201
- return typeof value === "object" && value !== null && "unref" in value && typeof value.unref === "function";
202
- }
203
- function unrefStream(stream) {
204
- if (isUnrefable(stream)) {
205
- stream.unref();
206
- }
207
- }
208
- function terminate(child) {
209
- if (child.pid && process.platform !== "win32") {
210
- try {
211
- process.kill(-child.pid, "SIGTERM");
212
- return;
213
- } catch {
214
- child.kill("SIGTERM");
215
- return;
216
- }
217
- }
218
- child.kill("SIGTERM");
219
- }
220
- async function gitRunner(options) {
221
- let spawn;
222
- try {
223
- ;
224
- ({ spawn } = await import("child_process"));
225
- } catch {
226
- return null;
227
- }
228
- return (dir, args, env) => new Promise((resolve) => {
229
- let child;
230
- try {
231
- child = spawn("git", args, {
232
- cwd: dir,
233
- detached: process.platform !== "win32",
234
- stdio: ["ignore", "pipe", "pipe"],
235
- ...env ? { env: { ...process.env, ...env } } : {}
236
- });
237
- } catch {
238
- resolve(null);
239
- return;
240
- }
241
- const chunks = [];
242
- let size = 0;
243
- let overflow = false;
244
- let exitCode = null;
245
- let done = false;
246
- const timers = [];
247
- const schedule = (callback, ms) => {
248
- const timer = setTimeout(callback, ms);
249
- if (!options.keepProcessAlive) {
250
- timer.unref();
251
- }
252
- timers.push(timer);
253
- };
254
- const finish = () => {
255
- if (done) {
256
- return;
257
- }
258
- done = true;
259
- for (const timer of timers) {
260
- clearTimeout(timer);
261
- }
262
- child.stdout?.destroy();
263
- child.stderr?.destroy();
264
- resolve(
265
- exitCode === 0 && !overflow ? Buffer.concat(chunks).toString("utf8") : null
266
- );
267
- };
268
- child.stdout?.on("data", (chunk) => {
269
- size += chunk.length;
270
- if (size > options.maxBuffer) {
271
- overflow = true;
272
- terminate(child);
273
- return;
274
- }
275
- chunks.push(chunk);
276
- });
277
- child.stderr?.resume();
278
- child.on("error", () => {
279
- exitCode = null;
280
- finish();
281
- });
282
- child.on("exit", (code) => {
283
- exitCode = code;
284
- schedule(finish, EXIT_GRACE_MS);
285
- });
286
- child.on("close", (code) => {
287
- exitCode = code ?? exitCode;
288
- finish();
289
- });
290
- schedule(() => terminate(child), options.timeoutMs);
291
- if (!options.keepProcessAlive) {
292
- child.unref();
293
- unrefStream(child.stdout);
294
- unrefStream(child.stderr);
295
- }
296
- });
297
- }
298
-
299
- // src/gitState.ts
300
- var GIT_TIMEOUT_MS = 3e4;
301
- var GIT_MAX_BUFFER = 1024 * 1024;
302
- var DISABLE_ENV = "BITFAB_DISABLE_GIT_STATE";
303
- var SHA_PATTERN = /^[0-9a-f]{40}$/;
304
- function sha(value) {
305
- const trimmed = value?.trim();
306
- return trimmed && SHA_PATTERN.test(trimmed) ? trimmed : null;
307
- }
308
- function text(value) {
309
- const trimmed = value?.trim();
310
- return trimmed ? trimmed : null;
311
- }
312
- function isEmptyGitState(state) {
313
- return Object.values(state).every((value) => value === null);
314
- }
315
- async function resolveGitState(cwd) {
316
- const git = await gitRunner({
317
- timeoutMs: GIT_TIMEOUT_MS,
318
- maxBuffer: GIT_MAX_BUFFER,
319
- keepProcessAlive: true
320
- });
321
- if (!git) {
322
- return null;
323
- }
324
- const run = async (args, env) => (await git(cwd, args, env))?.trim() ?? null;
325
- const [refs, email, branch] = await Promise.all([
326
- run(["rev-parse", "--show-toplevel", "HEAD", "HEAD^{tree}"]),
327
- run(["config", "user.email"]),
328
- run(["symbolic-ref", "--short", "-q", "HEAD"])
329
- ]);
330
- const [root, commitSha, baseSha] = (refs ?? "").split("\n");
331
- if (!root) {
332
- return null;
333
- }
334
- const state = {
335
- githubEmail: text(email),
336
- branch: text(branch),
337
- commitSha: sha(commitSha),
338
- baseSha: sha(baseSha),
339
- experimentSha: await resolveWorkingTreeSha(run, root.trim())
340
- };
341
- return isEmptyGitState(state) ? null : state;
342
- }
343
- async function resolveWorkingTreeSha(run, root) {
344
- let indexPath;
345
- let cleanup;
346
- try {
347
- const { mkdtemp, rm } = await import("fs/promises");
348
- const { join } = await import("path");
349
- const { tmpdir } = await import("os");
350
- const dir = await mkdtemp(join(tmpdir(), "bitfab-git-"));
351
- indexPath = join(dir, "index");
352
- cleanup = () => rm(dir, { recursive: true, force: true });
353
- } catch {
354
- return null;
355
- }
356
- try {
357
- const env = { GIT_INDEX_FILE: indexPath };
358
- if (await run(["read-tree", "HEAD"], env) === null) {
359
- return null;
360
- }
361
- if (await run(["add", "-A", "--", root], env) === null) {
362
- return null;
363
- }
364
- return sha(await run(["write-tree"], env));
365
- } catch {
366
- return null;
367
- } finally {
368
- await cleanup().catch(() => {
369
- });
370
- }
371
- }
372
- function resolvedGitState() {
373
- if (typeof process === "undefined" || process.env?.[DISABLE_ENV]) {
374
- return Promise.resolve(null);
375
- }
376
- let cwd;
377
- try {
378
- cwd = process.cwd?.() ?? ".";
379
- } catch {
380
- return Promise.resolve(null);
381
- }
382
- return resolveGitState(cwd).catch(() => null);
383
- }
384
-
385
- // src/asyncStorage.ts
386
- var AsyncLocalStorageClass = null;
387
- var initDone = false;
388
- function registerAsyncLocalStorageClass(cls) {
389
- if (!AsyncLocalStorageClass) {
390
- AsyncLocalStorageClass = cls;
391
- }
392
- initDone = true;
393
- }
394
- var asyncStorageReady = (typeof process !== "undefined" && process.versions?.node ? (
395
- // The join trick hides "node:async_hooks" from static analysis so
396
- // bundlers that ban Node.js built-ins don't fail at build time.
397
- // webpackIgnore tells webpack/turbopack to emit a native import()
398
- // so Node.js can resolve the module at runtime.
399
- import(
400
- /* webpackIgnore: true */
401
- ["node", "async_hooks"].join(":")
402
- ).then(
403
- (mod) => {
404
- registerAsyncLocalStorageClass(mod.AsyncLocalStorage);
405
- }
406
- ).catch(() => {
407
- })
408
- ) : Promise.resolve()).then(() => {
409
- initDone = true;
410
- });
411
- function createAsyncLocalStorage() {
412
- return AsyncLocalStorageClass ? new AsyncLocalStorageClass() : null;
413
- }
414
-
415
- // src/replayContext.ts
416
- var replayContextStorage = null;
417
- var REPLAY_CONTEXT_STORAGE_SYMBOL = /* @__PURE__ */ Symbol.for("bitfab.replayContextStorage");
418
- var replayContextReady = asyncStorageReady.then(() => {
419
- const shared = globalThis;
420
- const existing = shared[REPLAY_CONTEXT_STORAGE_SYMBOL];
421
- if (existing) {
422
- replayContextStorage = existing;
423
- return;
424
- }
425
- const created = createAsyncLocalStorage();
426
- if (created) {
427
- shared[REPLAY_CONTEXT_STORAGE_SYMBOL] = created;
428
- replayContextStorage = created;
429
- }
430
- });
431
- function runWithReplayContext(ctx, fn) {
432
- if (replayContextStorage) {
433
- return replayContextStorage.run(ctx, fn);
434
- }
435
- return fn();
436
- }
437
-
438
- // src/captureSuppression.ts
439
- var suppressionGlobal = globalThis;
440
- var suppressionState = suppressionGlobal.__bitfabCaptureSuppressionV1 ?? { depth: 0 };
441
- suppressionGlobal.__bitfabCaptureSuppressionV1 = suppressionState;
442
- function runWithCaptureSuppressed(fn) {
443
- suppressionState.depth += 1;
444
- try {
445
- return fn();
446
- } finally {
447
- suppressionState.depth -= 1;
448
- }
449
- }
450
-
451
- // src/payloadBudget.ts
452
- var MAX_SPAN_CARRIER_BYTES = 28e5;
453
- var MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES = 78e5;
454
- var textEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
455
- function byteLength(value) {
456
- return textEncoder ? textEncoder.encode(value).length : value.length;
457
- }
458
- function carrierByteLength(body) {
459
- return carrierBytesOf(textEncoder ? textEncoder.encode(body) : null, body);
460
- }
461
- function carrierBytesOf(encoded, body) {
462
- if (!encoded) {
463
- return body.length + 2;
464
- }
465
- let extra = 2;
466
- for (let i = 0; i < encoded.length; i++) {
467
- const byte = encoded[i];
468
- if (byte === 34 || byte === 92) {
469
- extra += 1;
470
- } else if (byte < 32) {
471
- extra += byte === 8 || byte === 9 || byte === 10 || byte === 12 || byte === 13 ? 1 : 5;
472
- }
473
- }
474
- return encoded.length + extra;
475
- }
476
- var MAX_BYTES_PER_UNIT = 3;
477
- function fitsCarrierBudget(body, maxBytes = MAX_SPAN_CARRIER_BYTES) {
478
- const units = body.length;
479
- if (units * MAX_BYTES_PER_UNIT + 2 <= maxBytes) {
480
- return true;
481
- }
482
- if (units + 2 > maxBytes) {
483
- return false;
484
- }
485
- return carrierByteLength(body) <= maxBytes;
486
- }
487
- var STRUCTURAL_SPAN_KEYS = /* @__PURE__ */ new Set([
488
- "name",
489
- "type",
490
- "function_name",
491
- "error_source"
492
- ]);
493
- function asRecord(value) {
494
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
495
- }
496
- function cloneTrimmable(payload) {
497
- const copy = { ...payload };
498
- const containers = [];
499
- const spanData = asRecord(copy.span_data);
500
- if (spanData) {
501
- const clone = { ...spanData };
502
- copy.span_data = clone;
503
- containers.push(clone);
504
- }
505
- const rawSpan = asRecord(copy.rawSpan);
506
- const rawSpanData = rawSpan && asRecord(rawSpan.span_data);
507
- if (rawSpan && rawSpanData) {
508
- const clone = { ...rawSpanData };
509
- copy.rawSpan = { ...rawSpan, span_data: clone };
510
- containers.push(clone);
511
- }
512
- if (containers.length === 0) {
513
- containers.push(copy);
514
- }
515
- return { copy, containers };
516
- }
517
- function collectCandidates(containers) {
518
- const candidates = [];
519
- for (const container of containers) {
520
- for (const [key, value] of Object.entries(container)) {
521
- if (STRUCTURAL_SPAN_KEYS.has(key) || value == null) {
522
- continue;
523
- }
524
- let size;
525
- try {
526
- size = byteLength(JSON.stringify(value) ?? "");
527
- } catch {
528
- continue;
529
- }
530
- candidates.push({ container, key, size });
531
- }
532
- }
533
- return candidates.sort((a, b) => b.size - a.size);
534
- }
535
- function trimPayloadToBudget(payload, encode, maxBytes = MAX_SPAN_CARRIER_BYTES) {
536
- const { copy, containers } = cloneTrimmable(payload);
537
- const candidates = collectCandidates(containers);
538
- if (candidates.length === 0) {
539
- return void 0;
540
- }
541
- const trimmed = [];
542
- for (const candidate of candidates) {
543
- candidate.container[candidate.key] = `<unserializable: too_large_${candidate.size}_bytes>`;
544
- trimmed.push(candidate.key);
545
- let body;
546
- try {
547
- body = encode(copy);
548
- } catch {
549
- return void 0;
550
- }
551
- if (fitsCarrierBudget(body, maxBytes)) {
552
- return { value: copy, trimmed };
553
- }
554
- }
555
- return void 0;
556
- }
557
- function markPayloadTrimmed(value, trimmed, maxBytes = MAX_SPAN_CARRIER_BYTES) {
558
- const existing = Array.isArray(value.errors) ? value.errors : [];
559
- value.errors = [
560
- ...existing,
561
- {
562
- source: "sdk",
563
- step: "payload_budget",
564
- error: `trimmed oversized field(s) to fit the ${maxBytes}-byte span carrier budget: ${[
565
- ...new Set(trimmed)
566
- ].join(", ")}`
567
- }
568
- ];
569
- }
570
-
571
- // src/warnOnce.ts
572
- var warned = /* @__PURE__ */ new Set();
573
- function warn(message) {
574
- try {
575
- console.warn(`[bitfab] ${message}`);
576
- } catch {
577
- }
578
- }
579
- function warnOnce(key, message) {
580
- if (warned.has(key)) {
581
- return;
582
- }
583
- warned.add(key);
584
- warn(message);
585
- }
586
- function writeOnce(key, line, write = console.warn) {
587
- if (warned.has(key)) {
588
- return;
589
- }
590
- warned.add(key);
591
- try {
592
- write(line);
593
- } catch {
594
- }
595
- }
596
-
597
- // src/serializePayload.ts
598
- function serializePayloadBody(payload, maxCarrierBytes = MAX_SPAN_CARRIER_BYTES) {
599
- return runWithCaptureSuppressed(
600
- () => encodeWithinBudget(payload, maxCarrierBytes)
601
- );
602
- }
603
- function encodeWithinBudget(payload, maxCarrierBytes) {
604
- const encoded = encodePayloadBody(payload);
605
- if (fitsCarrierBudget(encoded.body, maxCarrierBytes)) {
606
- return { body: encoded.body, dropped: encoded.dropped };
607
- }
608
- return applyPayloadBudget(encoded, maxCarrierBytes);
609
- }
610
- function applyPayloadBudget(encoded, maxCarrierBytes) {
611
- const result = encoded.value ? trimPayloadToBudget(
612
- encoded.value,
613
- (value) => encodePayloadBody(value).body,
614
- maxCarrierBytes
615
- ) : void 0;
616
- if (!result) {
617
- return { body: encoded.body, dropped: encoded.dropped };
618
- }
619
- warnOnce(
620
- "payload:over-budget",
621
- `a span payload exceeded the ${maxCarrierBytes}-byte carrier budget; its largest field(s) (${[
622
- ...new Set(result.trimmed)
623
- ].join(
624
- ", "
625
- )}) were replaced with placeholders so the span still ships. The span is incomplete and may not be replayable.`
626
- );
627
- markPayloadTrimmed(result.value, result.trimmed, maxCarrierBytes);
628
- return {
629
- body: encodePayloadBody(result.value).body,
630
- dropped: encoded.dropped
631
- };
632
- }
633
- function encodePayloadBody(payload) {
634
- try {
635
- return { body: JSON.stringify(payload), dropped: [], value: payload };
636
- } catch {
637
- const dropped = [];
638
- const sanitize = (value, seen) => {
639
- const t = typeof value;
640
- if (value === null || t === "string" || t === "number" || t === "boolean") {
641
- return value;
642
- }
643
- if (t === "bigint") {
644
- dropped.push("BigInt");
645
- return "<unserializable: BigInt>";
646
- }
647
- if (t === "function") {
648
- const name = value.name || "Function";
649
- dropped.push(name);
650
- return `<unserializable: ${name}>`;
651
- }
652
- if (t === "symbol") {
653
- dropped.push("Symbol");
654
- return "<unserializable: Symbol>";
655
- }
656
- if (t !== "object") {
657
- return void 0;
658
- }
659
- const obj = value;
660
- const className = obj.constructor?.name || "object";
661
- if (seen.has(obj)) {
662
- dropped.push(className);
663
- return `<cycle: ${className}>`;
664
- }
665
- seen.add(obj);
666
- let result;
667
- if (Array.isArray(obj)) {
668
- result = obj.map((item) => sanitize(item, seen));
669
- } else if (typeof obj.toJSON === "function") {
670
- try {
671
- result = sanitize(obj.toJSON(), seen);
672
- } catch {
673
- dropped.push(className);
674
- result = `<unserializable: ${className}>`;
675
- }
676
- } else {
677
- try {
678
- const out = {};
679
- for (const [k, v] of Object.entries(obj)) {
680
- out[k] = sanitize(v, seen);
681
- }
682
- result = out;
683
- } catch {
684
- warnOnce(
685
- "payload:field-getter-threw",
686
- "a value with a throwing getter/proxy could not be serialized into a span payload; it was replaced with a placeholder. The span still ships with its other fields intact."
687
- );
688
- dropped.push(className);
689
- result = `<unserializable: ${className}>`;
690
- }
691
- }
692
- seen.delete(obj);
693
- return result;
694
- };
695
- let sanitized;
696
- try {
697
- sanitized = sanitize(payload, /* @__PURE__ */ new WeakSet());
698
- } catch (error) {
699
- const message = error instanceof Error ? error.message : String(error);
700
- const marker = { error: `payload_serialize_failed: ${message}` };
701
- return { body: JSON.stringify(marker), dropped, value: marker };
702
- }
703
- const isRecord = typeof sanitized === "object" && sanitized !== null && !Array.isArray(sanitized);
704
- if (dropped.length > 0 && isRecord) {
705
- const obj = sanitized;
706
- const existing = Array.isArray(obj.errors) ? obj.errors : [];
707
- obj.errors = [
708
- ...existing,
709
- {
710
- source: "sdk",
711
- step: "json_serialize",
712
- error: `stubbed non-serializable value(s): ${[
713
- ...new Set(dropped)
714
- ].join(", ")}`
715
- }
716
- ];
717
- }
718
- return {
719
- body: JSON.stringify(sanitized),
720
- dropped,
721
- value: isRecord ? sanitized : void 0
722
- };
723
- }
724
- }
725
-
726
- // src/spanOrigin.ts
727
- var FRAMEWORK_INSTRUMENTATIONS = [
728
- "openai-agents",
729
- "langgraph",
730
- "claude-agent-sdk",
731
- "vercel-ai",
732
- "rivet"
733
- ];
734
- var FRAMEWORK_INSTRUMENTATION_SET = new Set(
735
- FRAMEWORK_INSTRUMENTATIONS
736
- );
737
-
738
- // src/simulationPlan.ts
739
- var SIMULATION_PLAN_READ_TIMEOUT_MS = 5e3;
740
- var NO_API_KEY_FOR_SIMULATION_PLAN = "no API key is set";
741
- var ROOT_TRACE_FUNCTION_KEY_FIELD = "rootTraceFunctionKey";
742
- var DECLARED_NODE_FIELD = "declaredNode";
743
- function planWaitSliceMs(timeoutMs) {
744
- return Math.min(SIMULATION_PLAN_READ_TIMEOUT_MS, Math.max(timeoutMs, 0) / 2);
745
- }
746
-
747
- // src/traceMetadata.ts
748
- var activeRecords = /* @__PURE__ */ new Map();
749
- var completedRecords = /* @__PURE__ */ new Map();
750
- function findRecord(traceId) {
751
- return activeRecords.get(traceId) ?? completedRecords.get(traceId);
752
- }
753
- function warnAboutShadowedKeys(traceId, record) {
754
- const shadowed = Object.keys(record.derived).filter(
755
- (key) => key in record.caller && record.caller[key] !== record.derived[key] && !record.warnedKeys.has(key)
756
- ).sort();
757
- if (shadowed.length === 0) {
758
- return;
759
- }
760
- for (const key of shadowed) {
761
- record.warnedKeys.add(key);
762
- }
763
- warn(
764
- `trace metadata key(s) ${shadowed.join(", ")} on trace ${traceId} were set both by the caller and by an integration's own trace export; the caller's value is the one kept on the trace.`
765
- );
766
- }
767
- function mergeCallerMetadataIntoTracePayload(payload) {
768
- const externalTrace = payload.externalTrace;
769
- if (typeof externalTrace !== "object" || externalTrace === null) {
770
- return payload;
771
- }
772
- const external = externalTrace;
773
- const traceId = typeof payload.id === "string" && payload.id !== "" ? payload.id : external.id;
774
- if (typeof traceId !== "string" || traceId === "") {
775
- return payload;
776
- }
777
- const record = findRecord(traceId);
778
- if (!record || Object.keys(record.caller).length === 0) {
779
- return payload;
780
- }
781
- const exported = external.metadata;
782
- if (typeof exported === "object" && exported !== null) {
783
- Object.assign(record.derived, exported);
784
- }
785
- warnAboutShadowedKeys(traceId, record);
786
- return {
787
- ...payload,
788
- externalTrace: {
789
- ...external,
790
- metadata: { ...record.derived, ...record.caller }
791
- }
792
- };
793
- }
794
-
795
- // src/otel.ts
796
- import { SpanStatusCode } from "@opentelemetry/api";
797
- import {
798
- ExportResultCode
799
- } from "@opentelemetry/core";
800
- import { resourceFromAttributes } from "@opentelemetry/resources";
801
- import {
802
- AlwaysOnSampler,
803
- BasicTracerProvider,
804
- BatchSpanProcessor
805
- } from "@opentelemetry/sdk-trace-base";
806
-
807
- // src/transportTypes.ts
808
- var DeliveryError = class extends Error {
809
- constructor(message, options = {}) {
810
- super(message);
811
- this.name = "DeliveryError";
812
- this.retryable = options.retryable ?? false;
813
- this.oversized = options.oversized ?? false;
814
- this.retryAfterMs = options.retryAfterMs;
815
- }
816
- };
817
-
818
- // src/unrefTimer.ts
819
- function unrefTimer(timer) {
820
- const handle = timer;
821
- if (typeof handle.unref === "function") {
822
- handle.unref();
823
- }
824
- }
825
-
826
- // src/otel.ts
827
- var OPERATION_ATTRIBUTE = "bitfab.operation";
828
- var PAYLOAD_ATTRIBUTE = "bitfab.payload";
829
- var MAX_EXPORT_REQUEST_BYTES = 3e6;
830
- var MAX_DECOMPRESSED_REQUEST_BYTES = 8e6;
831
- var MAX_REQUEST_BYTES_ENV = "BITFAB_OTEL_MAX_REQUEST_BYTES";
832
- var EXPORT_CONCURRENCY_ENV = "BITFAB_OTEL_EXPORT_CONCURRENCY";
833
- var MAX_QUEUE_SIZE = 16384;
834
- var DIRECT_MAX_EXPORT_BATCH_SIZE = 512;
835
- var DIRECT_MAX_REQUEST_BATCH_SIZE = 256;
836
- var DEFAULT_EXPORT_CONCURRENCY = 32;
837
- var MAX_EXPORT_CONCURRENCY = 64;
838
- var SCHEDULE_DELAY_MILLIS = 5e3;
839
- var EXPORT_TIMEOUT_MILLIS = 3e4;
840
- var RETRY_BASE_DELAY_MILLIS = 100;
841
- var RETRY_BACKOFF_CEILING_MILLIS = 5e3;
842
- var MAX_SEND_ATTEMPTS = 3;
843
- var DEFAULT_LIFECYCLE_TIMEOUT_MS = 3e4;
844
- var liveTransports = /* @__PURE__ */ new Set();
845
- var carrierRefs = /* @__PURE__ */ new WeakMap();
846
- function readBoundedIntEnv(name, max, fallback, warnKey) {
847
- const raw = readEnv(name);
848
- if (raw === void 0) {
849
- return fallback;
850
- }
851
- const value = Number(raw);
852
- if (Number.isInteger(value) && value > 0 && value <= max) {
853
- return value;
854
- }
855
- warnOnce(
856
- warnKey,
857
- `${name} must be a positive integer no greater than ${max}; using ${fallback}`
858
- );
859
- return fallback;
860
- }
861
- function logError(message, error) {
862
- try {
863
- if (error === void 0) {
864
- console.error(`[bitfab] ${message}`);
865
- } else {
866
- console.error(`[bitfab] ${message}`, error);
867
- }
868
- } catch {
869
- }
870
- }
871
- function otlpValue(value) {
872
- if (typeof value === "boolean") {
873
- return { boolValue: value };
874
- }
875
- if (typeof value === "number") {
876
- return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };
877
- }
878
- if (typeof value === "string") {
879
- return { stringValue: value };
880
- }
881
- if (Array.isArray(value)) {
882
- return { arrayValue: { values: value.map(otlpValue) } };
883
- }
884
- return { stringValue: String(value) };
885
- }
886
- function otlpAttributes(attributes) {
887
- if (!attributes) {
888
- return [];
889
- }
890
- return Object.entries(attributes).filter(([, value]) => value !== void 0).map(([key, value]) => ({ key, value: otlpValue(value) }));
891
- }
892
- function hrTimeToNanoString(time) {
893
- if (!time) {
894
- return "0";
895
- }
896
- return `${time[0]}${String(time[1]).padStart(9, "0")}`;
897
- }
898
- function spanToOtlp(span) {
899
- const spanContext = span.spanContext();
900
- const result = {
901
- traceId: spanContext.traceId,
902
- spanId: spanContext.spanId,
903
- name: span.name,
904
- kind: span.kind + 1,
905
- startTimeUnixNano: hrTimeToNanoString(span.startTime),
906
- endTimeUnixNano: hrTimeToNanoString(span.endTime),
907
- attributes: otlpAttributes(span.attributes),
908
- droppedAttributesCount: span.droppedAttributesCount,
909
- droppedEventsCount: span.droppedEventsCount,
910
- droppedLinksCount: span.droppedLinksCount,
911
- status: {
912
- code: span.status.code,
913
- ...span.status.message ? { message: span.status.message } : {}
914
- },
915
- flags: spanContext.traceFlags
916
- };
917
- const parentSpanId = span.parentSpanContext?.spanId;
918
- if (parentSpanId) {
919
- result.parentSpanId = parentSpanId;
920
- }
921
- if (spanContext.traceState) {
922
- result.traceState = spanContext.traceState.serialize();
923
- }
924
- return result;
925
- }
926
- var SPAN_SEPARATOR_BYTES = 1;
927
- function encodeSpan(span) {
928
- const json = JSON.stringify(spanToOtlp(span));
929
- return {
930
- json,
931
- size: byteLength(json),
932
- ref: carrierRefs.get(span)
933
- };
934
- }
935
- function trimEncodedSpan(span) {
936
- try {
937
- const carrier = JSON.parse(span.json);
938
- const attribute = carrier.attributes?.find(
939
- (entry) => entry.key === PAYLOAD_ATTRIBUTE
940
- );
941
- const payloadBody = attribute?.value?.stringValue;
942
- if (!attribute?.value || payloadBody === void 0) {
943
- return void 0;
944
- }
945
- const payload = JSON.parse(payloadBody);
946
- attribute.value.stringValue = serializePayloadBody(
947
- payload,
948
- MAX_SPAN_CARRIER_BYTES
949
- ).body;
950
- const json = JSON.stringify(carrier);
951
- return { json, size: byteLength(json) };
952
- } catch {
953
- return void 0;
954
- }
955
- }
956
- async function prepareRequest(body) {
957
- const prepared = encodeRequestBody(body);
958
- return prepared instanceof Promise ? await prepared : prepared;
959
- }
960
- function requestEnvelope(first) {
961
- const scope = first.instrumentationScope;
962
- const resource = JSON.stringify({
963
- attributes: otlpAttributes(
964
- first.resource.attributes
965
- )
966
- });
967
- const scopeJson = JSON.stringify({
968
- name: scope.name,
969
- version: scope.version ?? ""
970
- });
971
- const head = `{"resourceSpans":[{"resource":${resource},"scopeSpans":[{"scope":${scopeJson},"spans":[`;
972
- const tail = "]}]}]}";
973
- return { head, tail, size: byteLength(head) + byteLength(tail) };
974
- }
975
- function encodeRequest(envelope, spans) {
976
- return envelope.head + spans.map((span) => span.json).join(",") + envelope.tail;
977
- }
978
- function delay(ms) {
979
- return new Promise((resolve) => {
980
- const timer = setTimeout(resolve, ms);
981
- unrefTimer(timer);
982
- });
983
- }
984
- async function withDeadline(work, timeoutMs) {
985
- let timer;
986
- try {
987
- return await Promise.race([
988
- work,
989
- new Promise((resolve) => {
990
- timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));
991
- unrefTimer(timer);
992
- })
993
- ]);
994
- } finally {
995
- if (timer) {
996
- clearTimeout(timer);
997
- }
998
- }
999
- }
1000
- async function mapWithConcurrency(items, limit, task) {
1001
- const results = new Array(items.length);
1002
- let next = 0;
1003
- const workers = Array.from(
1004
- { length: Math.min(Math.max(limit, 1), items.length) },
1005
- async () => {
1006
- while (next < items.length) {
1007
- const index = next;
1008
- next += 1;
1009
- results[index] = await task(items[index]);
1010
- }
1011
- }
1012
- );
1013
- await Promise.all(workers);
1014
- return results;
1015
- }
1016
- function isRetryable(error) {
1017
- return error instanceof DeliveryError && error.retryable;
1018
- }
1019
- function isOversized(error) {
1020
- return error instanceof DeliveryError && error.oversized;
1021
- }
1022
- function retryWaitMillis(error, attempt, remainingMillis) {
1023
- const requested = error instanceof DeliveryError ? error.retryAfterMs : void 0;
1024
- const affordable = remainingMillis / 2;
1025
- if (requested !== void 0) {
1026
- return requested < affordable ? requested : null;
1027
- }
1028
- const backoff = Math.min(
1029
- RETRY_BASE_DELAY_MILLIS * 2 ** attempt,
1030
- RETRY_BACKOFF_CEILING_MILLIS
1031
- );
1032
- const jittered = backoff / 2 + Math.random() * (backoff / 2);
1033
- return jittered < affordable ? jittered : null;
1034
- }
1035
- var BitfabSpanExporter = class {
1036
- constructor(directSender, maxRequestBytes, maxRequestBatchSize, exportConcurrency, onDelivered, exportTimeoutMillis = EXPORT_TIMEOUT_MILLIS) {
1037
- this.directSender = directSender;
1038
- this.maxRequestBytes = maxRequestBytes;
1039
- this.maxRequestBatchSize = maxRequestBatchSize;
1040
- this.exportConcurrency = exportConcurrency;
1041
- this.onDelivered = onDelivered;
1042
- this.exportTimeoutMillis = exportTimeoutMillis;
1043
- /** Epoch ms until which the server has asked this exporter to stay away. */
1044
- this.throttledUntil = 0;
1045
- }
1046
- export(spans, resultCallback) {
1047
- void this.exportAsync(spans).then(
1048
- (succeeded) => {
1049
- resultCallback({
1050
- code: succeeded ? ExportResultCode.SUCCESS : ExportResultCode.FAILED
1051
- });
1052
- },
1053
- (error) => {
1054
- resultCallback({ code: ExportResultCode.FAILED, error });
1055
- }
1056
- );
1057
- }
1058
- async exportAsync(spans) {
1059
- if (spans.length === 0) {
1060
- return true;
1061
- }
1062
- let encoded;
1063
- let envelope;
1064
- try {
1065
- encoded = spans.map(encodeSpan);
1066
- envelope = requestEnvelope(spans[0]);
1067
- } catch (error) {
1068
- logError("failed to encode an OpenTelemetry span batch", error);
1069
- return false;
1070
- }
1071
- const batches = this.buildRequestBatches(envelope, encoded);
1072
- const results = await mapWithConcurrency(
1073
- batches,
1074
- this.exportConcurrency,
1075
- (batch) => this.send(envelope, batch)
1076
- );
1077
- return results.every(Boolean);
1078
- }
1079
- buildRequestBatches(envelope, spans) {
1080
- const batches = [];
1081
- let current = [];
1082
- let size = envelope.size;
1083
- for (const span of spans) {
1084
- const addition = span.size + (current.length > 0 ? SPAN_SEPARATOR_BYTES : 0);
1085
- if (current.length > 0 && (current.length >= this.maxRequestBatchSize || size + addition > this.maxRequestBytes)) {
1086
- batches.push({ spans: current, size });
1087
- current = [];
1088
- size = envelope.size;
1089
- }
1090
- current.push(span);
1091
- size += span.size + (current.length > 1 ? SPAN_SEPARATOR_BYTES : 0);
1092
- }
1093
- if (current.length > 0) {
1094
- batches.push({ spans: current, size });
1095
- }
1096
- return batches;
1097
- }
1098
- async send(envelope, batch) {
1099
- try {
1100
- let requestSpans = batch.spans;
1101
- let requestRawBytes = batch.size;
1102
- let alreadyTrimmed = false;
1103
- while (true) {
1104
- if (requestRawBytes <= MAX_DECOMPRESSED_REQUEST_BYTES) {
1105
- const prepared = await prepareRequest(
1106
- encodeRequest(envelope, requestSpans)
1107
- );
1108
- if (prepared.wireBytes <= this.maxRequestBytes) {
1109
- await this.sendWithRetries(prepared);
1110
- this.reportDelivered(batch.spans);
1111
- return true;
1112
- }
1113
- }
1114
- if (batch.spans.length !== 1) {
1115
- logError(
1116
- "an OpenTelemetry span batch exceeded the configured request-size target and could not be exported"
1117
- );
1118
- return false;
1119
- }
1120
- if (alreadyTrimmed) {
1121
- logError(
1122
- "a single OpenTelemetry span exceeded the configured request-size target after trimming"
1123
- );
1124
- return false;
1125
- }
1126
- const trimmed = trimEncodedSpan(batch.spans[0]);
1127
- if (!trimmed) {
1128
- logError(
1129
- "a single OpenTelemetry span exceeded the configured request-size target and could not be trimmed"
1130
- );
1131
- return false;
1132
- }
1133
- requestSpans = [trimmed];
1134
- requestRawBytes = envelope.size + trimmed.size;
1135
- alreadyTrimmed = true;
1136
- }
1137
- } catch (error) {
1138
- if (isOversized(error)) {
1139
- logError(
1140
- batch.spans.length === 1 ? "a single OpenTelemetry span exceeded the ingestion request limit and could not be exported" : "an OpenTelemetry span batch exceeded the ingestion request limit and could not be exported"
1141
- );
1142
- return false;
1143
- }
1144
- logError("failed to export an OpenTelemetry span batch", error);
1145
- return false;
1146
- }
1147
- }
1148
- /**
1149
- * Retries transient failures. Span and trace-completion carriers are safe to
1150
- * retry: the server keys them idempotently on `sourceSpanId`/`sourceTraceId`,
1151
- * so a duplicate delivery cannot create a duplicate row.
1152
- *
1153
- * KNOWN LIMITATION: an `internal_trace` (a `call()` BAML trace) carries no
1154
- * such key, so retrying a batch that holds one can create a duplicate trace -
1155
- * including when a request times out client-side but the server goes on to
1156
- * persist it. Accepted deliberately for now, matching the other SDKs, rather
1157
- * than skipping retries for a whole batch or inventing an idempotency scheme
1158
- * the server does not yet understand. The fix is a client-supplied
1159
- * idempotency key that ingestion dedupes on.
1160
- */
1161
- /**
1162
- * Remember a throttle the server asked for, so the requests fanned out
1163
- * alongside this one respect it too. Delaying only the request that was
1164
- * refused leaves the other seven in the window hitting a server that just
1165
- * asked for room.
1166
- */
1167
- recordThrottle(error) {
1168
- const requested = error instanceof DeliveryError ? error.retryAfterMs : void 0;
1169
- if (requested !== void 0) {
1170
- this.throttledUntil = Math.max(
1171
- this.throttledUntil,
1172
- Date.now() + requested
1173
- );
1174
- }
1175
- }
1176
- /**
1177
- * Waits out an active throttle, or reports the batch undeliverable when the
1178
- * throttle outlasts what we are willing to hold it for. Either way nothing is
1179
- * sent while the server has asked us to stay away.
1180
- */
1181
- async awaitThrottle(deadline) {
1182
- const remaining = this.throttledUntil - Date.now();
1183
- if (remaining <= 0) {
1184
- return;
1185
- }
1186
- if (remaining >= (deadline - Date.now()) / 2) {
1187
- throw new DeliveryError(
1188
- `OTLP ingestion is throttled for another ${remaining}ms, longer than the export budget`
1189
- );
1190
- }
1191
- await delay(remaining);
1192
- }
1193
- async sendWithRetries(request) {
1194
- const deadline = Date.now() + this.exportTimeoutMillis;
1195
- for (let attempt = 0; attempt < MAX_SEND_ATTEMPTS; attempt += 1) {
1196
- try {
1197
- await this.awaitThrottle(deadline);
1198
- await this.directSender(request, Math.max(0, deadline - Date.now()));
1199
- return;
1200
- } catch (error) {
1201
- if (isOversized(error)) {
1202
- throw error;
1203
- }
1204
- this.recordThrottle(error);
1205
- if (attempt === MAX_SEND_ATTEMPTS - 1 || !isRetryable(error)) {
1206
- throw error;
1207
- }
1208
- const wait = retryWaitMillis(error, attempt, deadline - Date.now());
1209
- if (wait === null) {
1210
- throw error;
1211
- }
1212
- await delay(wait);
1213
- }
1214
- }
1215
- }
1216
- /**
1217
- * Announce the carriers a request delivered. Wrapped because a listener that
1218
- * throws must never turn a delivered batch into a failed export.
1219
- */
1220
- reportDelivered(spans) {
1221
- if (this.onDelivered === void 0) {
1222
- return;
1223
- }
1224
- const refs = spans.map((span) => span.ref).filter((ref) => ref !== void 0);
1225
- if (refs.length === 0) {
1226
- return;
1227
- }
1228
- try {
1229
- this.onDelivered(refs);
1230
- } catch (error) {
1231
- logError("a delivery listener threw", error);
1232
- }
1233
- }
1234
- async shutdown() {
1235
- }
1236
- async forceFlush() {
1237
- }
1238
- };
1239
- var DeliveryTrackingExporter = class {
1240
- constructor(exporter) {
1241
- this.exporter = exporter;
1242
- // Deliberately unscoped, matching the Python SDK. An export can outlive
1243
- // OTel's export timeout and report failure after the flush that was waiting
1244
- // on it already returned, so that failure surfaces on the NEXT flush instead.
1245
- // That over-reports: a good flush can inherit an older failure. The
1246
- // alternative - discarding failures from completed flush windows - under-
1247
- // reports, and `BatchSpanProcessor` also runs scheduled exports that belong
1248
- // to no flush at all, so their failures would vanish entirely. For a
1249
- // telemetry SDK a false "flush failed" is investigable; a false "flush
1250
- // succeeded" silently loses traces. We take the noisy direction on purpose.
1251
- this.failedExports = 0;
1252
- }
1253
- export(spans, resultCallback) {
1254
- try {
1255
- this.exporter.export(spans, (result) => {
1256
- if (result.code !== ExportResultCode.SUCCESS) {
1257
- this.failedExports += 1;
1258
- }
1259
- resultCallback(result);
1260
- });
1261
- } catch (error) {
1262
- this.failedExports += 1;
1263
- resultCallback({ code: ExportResultCode.FAILED, error });
1264
- }
1265
- }
1266
- takeFailedExports() {
1267
- const failed = this.failedExports;
1268
- this.failedExports = 0;
1269
- return failed;
1270
- }
1271
- shutdown() {
1272
- return this.exporter.shutdown();
1273
- }
1274
- forceFlush() {
1275
- return this.exporter.forceFlush?.() ?? Promise.resolve();
1276
- }
1277
- };
1278
- var OtelBatchTransport = class {
1279
- constructor(options) {
1280
- this.closed = false;
1281
- const maxRequestBytes = options.maxRequestBytes ?? MAX_EXPORT_REQUEST_BYTES;
1282
- const maxRequestBatchSize = options.maxRequestBatchSize ?? DIRECT_MAX_REQUEST_BATCH_SIZE;
1283
- if (maxRequestBatchSize <= 0) {
1284
- throw new BitfabError("maxRequestBatchSize must be a positive integer");
1285
- }
1286
- this.deliveryTracker = new DeliveryTrackingExporter(
1287
- new BitfabSpanExporter(
1288
- options.directSender,
1289
- maxRequestBytes,
1290
- maxRequestBatchSize,
1291
- options.exportConcurrency ?? DEFAULT_EXPORT_CONCURRENCY,
1292
- options.onDelivered,
1293
- options.exportTimeoutMillis ?? EXPORT_TIMEOUT_MILLIS
1294
- )
1295
- );
1296
- this.processor = new BatchSpanProcessor(this.deliveryTracker, {
1297
- maxQueueSize: options.maxQueueSize ?? MAX_QUEUE_SIZE,
1298
- maxExportBatchSize: options.maxExportBatchSize ?? DIRECT_MAX_EXPORT_BATCH_SIZE,
1299
- scheduledDelayMillis: SCHEDULE_DELAY_MILLIS,
1300
- exportTimeoutMillis: options.exportTimeoutMillis ?? EXPORT_TIMEOUT_MILLIS
1301
- });
1302
- this.provider = new BasicTracerProvider({
1303
- sampler: new AlwaysOnSampler(),
1304
- resource: resourceFromAttributes({
1305
- "service.name": "bitfab-typescript-sdk",
1306
- "service.version": __version__
1307
- }),
1308
- spanLimits: {
1309
- attributeCountLimit: 2,
1310
- attributeValueLengthLimit: Number.POSITIVE_INFINITY
1311
- },
1312
- spanProcessors: [this.processor]
1313
- });
1314
- this.tracer = this.provider.getTracer("bitfab", __version__);
1315
- liveTransports.add(this);
1316
- }
1317
- submit(operation, payload, meta = {}) {
1318
- if (this.closed) {
1319
- warnOnce(
1320
- "otel-submit-after-shutdown",
1321
- "OpenTelemetry transport is shut down; dropping spans"
1322
- );
1323
- return;
1324
- }
1325
- try {
1326
- const { body, dropped } = serializePayloadBody(
1327
- payload,
1328
- MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES
1329
- );
1330
- if (dropped.length > 0) {
1331
- warnOnce(
1332
- "otel-carrier-payload-stubbed",
1333
- `a span payload held non-serializable value(s) (${[
1334
- ...new Set(dropped)
1335
- ].join(", ")}); they were stubbed so the span still ships, but the trace may be incomplete or not replayable.`
1336
- );
1337
- }
1338
- const span = this.tracer.startSpan(meta.name ?? `bitfab.${operation}`, {
1339
- attributes: {
1340
- [OPERATION_ATTRIBUTE]: operation,
1341
- [PAYLOAD_ATTRIBUTE]: body
1342
- },
1343
- startTime: meta.startTime
1344
- });
1345
- if (meta.ref !== void 0) {
1346
- carrierRefs.set(span, meta.ref);
1347
- }
1348
- if (meta.errored === true) {
1349
- span.setStatus({ code: SpanStatusCode.ERROR });
1350
- }
1351
- endSpan(span, meta.endTime);
1352
- } catch (error) {
1353
- logError("failed to queue an OpenTelemetry span", error);
1354
- }
1355
- }
1356
- async flush(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS) {
1357
- const pending = (this.pendingFlush ?? Promise.resolve(true)).then(
1358
- () => this.forceFlushOnce()
1359
- );
1360
- this.pendingFlush = pending.catch(() => false);
1361
- return withDeadline(pending, timeoutMs);
1362
- }
1363
- async forceFlushOnce() {
1364
- try {
1365
- await this.processor.forceFlush();
1366
- } catch (error) {
1367
- logError("failed to flush OpenTelemetry spans", error);
1368
- this.deliveryTracker.takeFailedExports();
1369
- return false;
1370
- }
1371
- return this.deliveryTracker.takeFailedExports() === 0;
1372
- }
1373
- async shutdown(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS) {
1374
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1375
- this.closed = true;
1376
- const flushed = await this.flush(Math.max(0, deadline - Date.now()));
1377
- liveTransports.delete(this);
1378
- const shutdownCompleted = await withDeadline(
1379
- this.provider.shutdown().then(() => true).catch((error) => {
1380
- logError("failed to shut down the OpenTelemetry transport", error);
1381
- return false;
1382
- }),
1383
- Math.max(0, deadline - Date.now())
1384
- );
1385
- return flushed && shutdownCompleted;
1386
- }
1387
- };
1388
- function endSpan(span, endTime) {
1389
- span.end(endTime);
1390
- }
1391
- function createOtelTransport(options) {
1392
- return new OtelBatchTransport({
1393
- ...options,
1394
- exportConcurrency: readBoundedIntEnv(
1395
- EXPORT_CONCURRENCY_ENV,
1396
- MAX_EXPORT_CONCURRENCY,
1397
- DEFAULT_EXPORT_CONCURRENCY,
1398
- "otel-export-concurrency-invalid"
1399
- ),
1400
- maxRequestBytes: readBoundedIntEnv(
1401
- MAX_REQUEST_BYTES_ENV,
1402
- MAX_EXPORT_REQUEST_BYTES,
1403
- MAX_EXPORT_REQUEST_BYTES,
1404
- "otel-max-request-bytes-invalid"
1405
- )
1406
- });
1407
- }
1408
- async function forEachLiveTransport(timeoutMs, run) {
1409
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1410
- let succeeded = true;
1411
- for (const transport of [...liveTransports]) {
1412
- succeeded = await run(transport, Math.max(0, deadline - Date.now())) && succeeded;
1413
- }
1414
- return succeeded;
1415
- }
1416
- function flushOtelTransports(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS) {
1417
- return forEachLiveTransport(
1418
- timeoutMs,
1419
- (transport, remaining) => transport.flush(remaining)
1420
- );
1421
- }
1422
- function shutdownOtelTransports(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS) {
1423
- return forEachLiveTransport(
1424
- timeoutMs,
1425
- (transport, remaining) => transport.shutdown(remaining)
1426
- );
1427
- }
1428
-
1429
- // src/transport.ts
1430
- function createTraceTransport(options) {
1431
- return createOtelTransport(options);
1432
- }
1433
- function flushTraceTransports(timeoutMs) {
1434
- return flushOtelTransports(timeoutMs);
1435
- }
1436
- function shutdownTraceTransports(timeoutMs) {
1437
- return shutdownOtelTransports(timeoutMs);
1438
- }
1439
-
1440
- // src/http.ts
1441
- var REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS = 3e5;
1442
- var REPLAY_COMPLETE_REQUEST_TIMEOUT_MS = 12e4;
1443
- var REPLAY_INTERRUPT_REQUEST_TIMEOUT_MS = 5e3;
1444
- var REPLAY_HEARTBEAT_REQUEST_TIMEOUT_MS = 5e3;
1445
- var OTLP_TRACES_ENDPOINT = "/api/sdk/otel/v1/traces";
1446
- var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
1447
- var EXIT_FLUSH_TIMEOUT_MS = 5e3;
1448
- var DEFAULT_LIFECYCLE_TIMEOUT_MS2 = 3e4;
1449
- var pendingTracePromises = /* @__PURE__ */ new Set();
1450
- var liveHttpClients = /* @__PURE__ */ new Set();
1451
- async function releaseHeldExternalSpans(timeoutMs) {
1452
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1453
- let released = true;
1454
- for (const client of [...liveHttpClients]) {
1455
- const result = await client.releaseHeldExternalSpans?.(
1456
- Math.max(0, deadline - Date.now())
1457
- );
1458
- released = result !== false && released;
1459
- }
1460
- return released;
1461
- }
1462
- function stopSimulationPlans() {
1463
- for (const client of [...liveHttpClients]) {
1464
- client.stopSimulationPlan?.();
1465
- }
1466
- }
1467
- function awaitOnExit(promise) {
1468
- pendingTracePromises.add(promise);
1469
- void promise.finally(() => {
1470
- pendingTracePromises.delete(promise);
1471
- }).catch(() => {
1472
- });
1473
- return promise;
1474
- }
1475
- async function flushTraces(timeoutMs = 5e3) {
1476
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1477
- const released = await releaseHeldExternalSpans(planWaitSliceMs(timeoutMs));
1478
- const requestsFlushed = await awaitPendingRequests(
1479
- Math.max(0, deadline - Date.now())
1480
- );
1481
- const releasedAfterDeferred = await releaseHeldExternalSpans(0);
1482
- const transportsFlushed = await flushTraceTransports(
1483
- Math.max(0, deadline - Date.now())
1484
- );
1485
- return released && releasedAfterDeferred && requestsFlushed && transportsFlushed;
1486
- }
1487
- async function awaitPendingRequests(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS2) {
1488
- await replayContextReady.catch(() => {
1489
- });
1490
- return waitForPromises(Array.from(pendingTracePromises), timeoutMs);
1491
- }
1492
- async function waitForPromises(promises, timeoutMs) {
1493
- if (promises.length === 0) {
1494
- return true;
1495
- }
1496
- let timer;
1497
- try {
1498
- return await Promise.race([
1499
- Promise.allSettled(promises).then(() => true),
1500
- new Promise((resolve) => {
1501
- timer = setTimeout(() => resolve(false), timeoutMs);
1502
- unrefTimer(timer);
1503
- })
1504
- ]);
1505
- } finally {
1506
- if (timer) {
1507
- clearTimeout(timer);
1508
- }
1509
- }
1510
- }
1511
- if (typeof process !== "undefined" && process.versions != null && process.versions.node != null) {
1512
- let isFlushing = false;
1513
- process.on("beforeExit", () => {
1514
- if (isFlushing) {
1515
- return;
1516
- }
1517
- isFlushing = true;
1518
- const planWaitMs = SIMULATION_PLAN_READ_TIMEOUT_MS;
1519
- const stopFlushing = () => {
1520
- isFlushing = false;
1521
- };
1522
- const deadline = setTimeout(
1523
- stopFlushing,
1524
- EXIT_FLUSH_TIMEOUT_MS + planWaitMs
1525
- );
1526
- unrefTimer(deadline);
1527
- void releaseHeldExternalSpans(planWaitMs).catch(() => {
1528
- }).then(() => {
1529
- stopSimulationPlans();
1530
- }).then(
1531
- () => Promise.allSettled([
1532
- ...Array.from(pendingTracePromises).map((p) => p.catch(() => {
1533
- })),
1534
- shutdownTraceTransports(EXIT_FLUSH_TIMEOUT_MS).catch(() => false)
1535
- ])
1536
- ).then(() => {
1537
- clearTimeout(deadline);
1538
- stopFlushing();
1539
- });
1540
- });
1541
- }
1542
- var SPAN_TYPES = [
1543
- "llm",
1544
- "agent",
1545
- "function",
1546
- "guardrail",
1547
- "handoff",
1548
- "custom"
1549
- ];
1550
- function readHeader(response, name) {
1551
- try {
1552
- return response.headers?.get(name) ?? null;
1553
- } catch {
1554
- return null;
1555
- }
1556
- }
1557
- function parseRetryAfterMs(header) {
1558
- const value = header?.trim();
1559
- if (!value) {
1560
- return void 0;
1561
- }
1562
- const seconds = Number(value);
1563
- if (Number.isFinite(seconds)) {
1564
- return seconds >= 0 ? seconds * 1e3 : void 0;
1565
- }
1566
- const at = Date.parse(value);
1567
- if (Number.isNaN(at)) {
1568
- return void 0;
1569
- }
1570
- return Math.max(0, at - Date.now());
1571
- }
1572
- function carrierMeta(operation, payload, ref) {
1573
- return {
1574
- ref,
1575
- name: carrierName(operation, payload),
1576
- startTime: payloadTimestamp(payload, "started_at"),
1577
- endTime: payloadTimestamp(payload, "ended_at"),
1578
- errored: payloadHasError(payload)
1579
- };
1580
- }
1581
- function carrierName(operation, payload) {
1582
- if (operation === "external_span") {
1583
- const spanData = asPayloadRecord(
1584
- asPayloadRecord(payload.rawSpan)?.span_data
1585
- );
1586
- if (typeof spanData?.name === "string") {
1587
- return spanData.name;
1588
- }
1589
- }
1590
- if (typeof payload.traceFunctionKey === "string") {
1591
- return payload.traceFunctionKey;
1592
- }
1593
- return `bitfab.${operation}`;
1594
- }
1595
- function payloadTimestamp(payload, field) {
1596
- const rawSpan = asPayloadRecord(payload.rawSpan);
1597
- const rawTrace = asPayloadRecord(payload.externalTrace) ?? asPayloadRecord(payload.rawTrace);
1598
- const raw = rawSpan?.[field] ?? rawTrace?.[field];
1599
- if (typeof raw !== "string") {
1600
- return void 0;
1601
- }
1602
- const parsed = Date.parse(raw);
1603
- return Number.isNaN(parsed) ? void 0 : parsed;
1604
- }
1605
- function payloadHasError(payload) {
1606
- const spanData = asPayloadRecord(asPayloadRecord(payload.rawSpan)?.span_data);
1607
- if (spanData?.error != null) {
1608
- return true;
1609
- }
1610
- const errors = payload.errors;
1611
- return Array.isArray(errors) ? errors.length > 0 : Boolean(errors);
1612
- }
1613
- function asPayloadRecord(value) {
1614
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1615
- }
1616
- function carrierRef(payload) {
1617
- const traceId = sourceTraceIdOf(payload);
1618
- if (traceId === void 0) {
1619
- return void 0;
1620
- }
1621
- const rawSpan = payload.rawSpan;
1622
- if (rawSpan === void 0) {
1623
- return { traceId };
1624
- }
1625
- const spanId = rawSpan?.id;
1626
- return {
1627
- traceId,
1628
- spanId: typeof spanId === "string" ? spanId : `submission-${++carrierSeq}`
1629
- };
1630
- }
1631
- function sourceTraceIdOf(payload) {
1632
- if (typeof payload.sourceTraceId === "string") {
1633
- return payload.sourceTraceId;
1634
- }
1635
- const rawTrace = payload.externalTrace ?? payload.rawTrace;
1636
- const id = rawTrace?.id;
1637
- return typeof id === "string" ? id : void 0;
1638
- }
1639
- var carrierSeq = 0;
1640
- function describeError(error) {
1641
- return error instanceof Error ? error.message : String(error);
1642
- }
1643
- function warnDroppedExternalSpan(error) {
1644
- warnOnce(
1645
- "external-span-dropped",
1646
- `a span was dropped because the send step failed: ${describeError(error)}`
1647
- );
1648
- }
1649
- function warnDroppedExternalTrace(error) {
1650
- warnOnce(
1651
- "external-trace-dropped",
1652
- `a trace was dropped because the send step failed: ${describeError(error)}`
1653
- );
1654
- }
1655
- var HttpClient = class {
1656
- constructor(config) {
1657
- // Only traces a caller asked about are tracked, so ordinary tracing stores
1658
- // nothing here.
1659
- this.traceDeliveries = /* @__PURE__ */ new Map();
1660
- // Deferred span work owned by THIS client. The module-global set backs the
1661
- // process-wide `flushTraces()` and the exit hook, but per-client lifecycle
1662
- // must not wait on another client's slow finalize: a false `close()` failure
1663
- // caused by unrelated work is worse than no signal at all.
1664
- this.deferredWork = /* @__PURE__ */ new Set();
1665
- this.traceCompletion = new TraceCompletion();
1666
- this.closed = false;
1667
- this.apiKey = config.apiKey;
1668
- this.serviceUrl = config.serviceUrl;
1669
- this.timeout = config.timeout ?? 12e4;
1670
- liveHttpClients.add(this);
1671
- }
1672
- /**
1673
- * Resolve the API key at the moment it is needed (request time), invoking
1674
- * the function form if one was supplied. Never read at construction.
1675
- */
1676
- resolveApiKey() {
1677
- return typeof this.apiKey === "function" ? this.apiKey() : this.apiKey;
1678
- }
1679
- /** @internal Whether this client currently has credentials for trace delivery. */
1680
- hasApiKey() {
1681
- try {
1682
- const apiKey = this.resolveApiKey();
1683
- return apiKey !== void 0 && apiKey.trim() !== "";
1684
- } catch {
1685
- return false;
1686
- }
1687
- }
1688
- /**
1689
- * This client's span transport, built on first use.
1690
- *
1691
- * Lazy on purpose: a client that never sends a span must never start a batch
1692
- * worker. Every framework integration created from a `Bitfab` client shares
1693
- * the owning client's `HttpClient`, so handlers reuse this one worker instead
1694
- * of each spinning up their own.
1695
- */
1696
- getTraceTransport() {
1697
- if (this.closed) {
1698
- warnOnce(
1699
- "http-client-closed",
1700
- "the Bitfab client is closed; dropping spans"
1701
- );
1702
- return void 0;
1703
- }
1704
- if (!this.traceTransport) {
1705
- this.traceTransport = createTraceTransport({
1706
- directSender: (request, timeoutMs) => this.deliverCarriers(request, timeoutMs),
1707
- onDelivered: (refs) => this.recordDeliveredCarriers(refs)
1708
- });
1709
- }
1710
- return this.traceTransport;
1711
- }
1712
- /**
1713
- * Post one encoded batch and decide what the server's answer means, so the
1714
- * transport never reads a response. Rejections and permanent statuses come
1715
- * back as a non-retryable {@link DeliveryError}; anything the server might
1716
- * still accept on a second try comes back retryable.
1717
- */
1718
- async deliverCarriers(request, timeoutMs) {
1719
- let response;
1720
- try {
1721
- response = await this.sendPrepared(
1722
- OTLP_TRACES_ENDPOINT,
1723
- request,
1724
- { timeout: timeoutMs }
1725
- );
1726
- } catch (error) {
1727
- const status = error instanceof BitfabError ? error.status : void 0;
1728
- if (status === void 0) {
1729
- throw new DeliveryError(`OTLP ingestion failed: ${String(error)}`, {
1730
- retryable: true
1731
- });
1732
- }
1733
- throw new DeliveryError(`OTLP ingestion failed with HTTP ${status}`, {
1734
- retryable: RETRYABLE_STATUSES.has(status),
1735
- oversized: status === 413,
1736
- ...error instanceof BitfabError && error.retryAfterMs !== void 0 ? { retryAfterMs: error.retryAfterMs } : {}
1737
- });
1738
- }
1739
- const serverTraceIds = asPayloadRecord(response?.traceIds);
1740
- if (serverTraceIds !== void 0) {
1741
- this.recordServerTraceIds(serverTraceIds);
1742
- }
1743
- const partialSuccess = asPayloadRecord(response?.partialSuccess);
1744
- const rejected = partialSuccess?.rejectedSpans;
1745
- if (rejected !== void 0 && rejected !== "0" && rejected !== 0) {
1746
- throw new DeliveryError(
1747
- `OTLP ingestion rejected ${rejected} span(s): ${partialSuccess?.errorMessage ?? "no reason provided"}`
1748
- );
1749
- }
1750
- }
1751
- /**
1752
- * Start tracking delivery for `traceIds`. Nothing is recorded for a trace
1753
- * that was never tracked, so ordinary tracing costs no bookkeeping at all.
1754
- */
1755
- trackTraceDeliveries(traceIds) {
1756
- for (const traceId of traceIds) {
1757
- if (!this.traceDeliveries.has(traceId)) {
1758
- this.traceDeliveries.set(traceId, {
1759
- submittedSpanIds: /* @__PURE__ */ new Set(),
1760
- ackedSpanIds: /* @__PURE__ */ new Set(),
1761
- closed: false,
1762
- closingAcked: false
1763
- });
1764
- }
1765
- }
1766
- }
1767
- /**
1768
- * The server's assigned `traces.id` for a tracked trace if it has already
1769
- * been read back off an ingest response, without stopping tracking. Lets a
1770
- * replay surface the id mid-run for items whose spans already landed.
1771
- */
1772
- peekServerTraceId(traceId) {
1773
- return this.traceDeliveries.get(traceId)?.serverTraceId;
1774
- }
1775
- /** Whether any tracked trace has had its closing carrier submitted. */
1776
- hasClosedDeliveries(traceIds) {
1777
- return traceIds.some((traceId) => this.traceDeliveries.get(traceId)?.closed);
1778
- }
1779
- /**
1780
- * Report what each tracked trace submitted and whether the server confirmed
1781
- * it, and stop tracking them. Every id passed is freed, so a caller cannot
1782
- * leak a record for a trace that never closed.
1783
- *
1784
- * `delivered` is only meaningful once a flush has settled: acks land before
1785
- * an export resolves, so a flush that reported success has already collected
1786
- * every ack it is going to collect.
1787
- */
1788
- takeTraceDeliveries(traceIds) {
1789
- const reports = {};
1790
- for (const traceId of traceIds) {
1791
- const delivery = this.traceDeliveries.get(traceId);
1792
- if (delivery === void 0) {
1793
- continue;
1794
- }
1795
- this.traceDeliveries.delete(traceId);
1796
- reports[traceId] = {
1797
- spanCount: delivery.submittedSpanIds.size,
1798
- closed: delivery.closed,
1799
- delivered: delivery.closingAcked && [...delivery.submittedSpanIds].every(
1800
- (spanId) => delivery.ackedSpanIds.has(spanId)
1801
- ),
1802
- serverTraceId: delivery.serverTraceId
1803
- };
1804
- }
1805
- return reports;
1806
- }
1807
- /** Build a carrier's meta and record what it adds to its trace's expected set. */
1808
- recordedMeta(operation, payload, ref) {
1809
- this.recordSubmittedCarrier(ref);
1810
- return carrierMeta(operation, payload, ref);
1811
- }
1812
- recordSubmittedCarrier(ref) {
1813
- if (ref === void 0) {
1814
- return;
1815
- }
1816
- const delivery = this.traceDeliveries.get(ref.traceId);
1817
- if (delivery === void 0) {
1818
- return;
1819
- }
1820
- if (ref.spanId === void 0) {
1821
- delivery.closed = true;
1822
- } else {
1823
- delivery.submittedSpanIds.add(ref.spanId);
1824
- }
1825
- }
1826
- /**
1827
- * Ingestion commits every carrier in a request before it answers, so a
1828
- * delivered ref is proof its row exists: the same fact the replay status
1829
- * endpoint would report, already in hand.
1830
- */
1831
- /**
1832
- * Record the server's assigned `traces.id` for each tracked source trace,
1833
- * read back from the OTLP ingest response. Keyed by source trace id, the same
1834
- * key the delivery ledger uses. Untracked ids are ignored.
1835
- */
1836
- recordServerTraceIds(map) {
1837
- for (const [sourceTraceId, serverTraceId] of Object.entries(map)) {
1838
- if (typeof serverTraceId !== "string") {
1839
- continue;
1840
- }
1841
- const delivery = this.traceDeliveries.get(sourceTraceId);
1842
- if (delivery === void 0) {
1843
- continue;
1844
- }
1845
- delivery.serverTraceId = serverTraceId;
1846
- }
1847
- }
1848
- recordDeliveredCarriers(refs) {
1849
- for (const ref of refs) {
1850
- const delivery = this.traceDeliveries.get(ref.traceId);
1851
- if (delivery === void 0) {
1852
- continue;
1853
- }
1854
- if (ref.spanId === void 0) {
1855
- delivery.closingAcked = true;
1856
- } else {
1857
- delivery.ackedSpanIds.add(ref.spanId);
1858
- }
1859
- }
1860
- }
1861
- /**
1862
- * Track deferred span work so this client's own lifecycle waits for it, and
1863
- * so the process-wide flush and exit hook do too.
1864
- */
1865
- trackDeferred(promise) {
1866
- this.deferredWork.add(promise);
1867
- void promise.finally(() => this.deferredWork.delete(promise)).catch(() => {
1868
- });
1869
- return awaitOnExit(promise);
1870
- }
1871
- /**
1872
- * Settle only THIS client's deferred span work. Scoped deliberately: the
1873
- * global set can contain another client's long-running finalize, and
1874
- * attributing its timeout here would fail a client whose own work succeeded.
1875
- */
1876
- async settleDeferredWork(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS2) {
1877
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1878
- const released = await this.releaseHeldExternalSpans?.(
1879
- planWaitSliceMs(timeoutMs)
1880
- );
1881
- await replayContextReady.catch(() => {
1882
- });
1883
- const settled = await waitForPromises(
1884
- Array.from(this.deferredWork),
1885
- Math.max(0, deadline - Date.now())
1886
- );
1887
- const releasedAfterDeferred = await this.releaseHeldExternalSpans?.(0);
1888
- return released !== false && releasedAfterDeferred !== false && settled;
1889
- }
1890
- /**
1891
- * Wait for spans queued by this client to be delivered, within one deadline.
1892
- * Returns false on delivery failure or timeout.
1893
- */
1894
- async waitForPendingRequests(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS2) {
1895
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1896
- const settled = await this.settleDeferredWork(
1897
- Math.max(0, deadline - Date.now())
1898
- );
1899
- const flushed = await this.traceTransport?.flush(Math.max(0, deadline - Date.now())) ?? true;
1900
- return settled && flushed;
1901
- }
1902
- /**
1903
- * Flush and permanently close this client's tracing transport. Idempotent:
1904
- * a second call joins the first rather than tearing down a pipeline the
1905
- * first call already owns.
1906
- */
1907
- close(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS2) {
1908
- if (this.closing) {
1909
- return this.closing;
1910
- }
1911
- const deadline = Date.now() + Math.max(timeoutMs, 0);
1912
- this.closing = (async () => {
1913
- liveHttpClients.delete(this);
1914
- const settled = await this.settleDeferredWork(
1915
- Math.max(0, deadline - Date.now())
1916
- );
1917
- this.stopSimulationPlan?.();
1918
- this.closed = true;
1919
- this.externalSpanTransform = void 0;
1920
- this.externalTraceTransform = void 0;
1921
- this.releaseHeldExternalSpans = void 0;
1922
- this.stopSimulationPlan = void 0;
1923
- const transport = this.traceTransport;
1924
- this.traceTransport = void 0;
1925
- const shutdownOk = await transport?.shutdown(Math.max(0, deadline - Date.now())) ?? true;
1926
- return settled && shutdownOk;
1927
- })();
1928
- return this.closing;
1929
- }
1930
- /**
1931
- * Make an HTTP request to the Bitfab API. Defaults to POST; pass
1932
- * `options.method` to use a different verb (e.g. "PATCH").
1933
- *
1934
- * @param endpoint - The API endpoint (without base URL)
1935
- * @param payload - The request body
1936
- * @param options - Optional request options
1937
- * @returns The parsed JSON response
1938
- * @throws {BitfabError} If the request fails
1939
- */
1940
- async request(endpoint, payload, options) {
1941
- const { body, dropped } = serializePayloadBody(payload);
1942
- if (dropped.length > 0) {
1943
- try {
1944
- console.warn(
1945
- `Bitfab: request body to ${endpoint} held ${dropped.length} non-serializable value(s) (${[...new Set(dropped)].join(", ")}); they were stubbed so the span still sends, but the trace may be incomplete or not replayable. Capture a JSON-safe projection of this input to make it replayable.`
1946
- );
1947
- } catch {
1948
- }
1949
- }
1950
- return this.sendEncoded(endpoint, body, options);
1951
- }
1952
- /**
1953
- * POST an already-encoded body. The span transport encodes its own batches,
1954
- * so routing them back through {@link HttpClient.request} would encode the
1955
- * same data twice.
1956
- */
1957
- async sendEncoded(endpoint, body, options) {
1958
- const prepared = encodeRequestBody(body);
1959
- const encoded = prepared instanceof Promise ? await prepared : prepared;
1960
- return this.sendPrepared(endpoint, encoded, options);
1961
- }
1962
- async sendPrepared(endpoint, encoded, options) {
1963
- const url = `${this.serviceUrl}${endpoint}`;
1964
- const timeout = options?.timeout ?? this.timeout;
1965
- const method = options?.method ?? "POST";
1966
- const controller = new AbortController();
1967
- const timeoutId = setTimeout(() => controller.abort(), timeout);
1968
- const headers = {
1969
- "Content-Type": "application/json",
1970
- Authorization: `Bearer ${this.resolveApiKey() ?? ""}`
1971
- };
1972
- if (encoded.contentEncoding) {
1973
- headers["Content-Encoding"] = encoded.contentEncoding;
1974
- }
1975
- try {
1976
- const response = await fetch(url, {
1977
- method,
1978
- headers,
1979
- body: encoded.body,
1980
- signal: controller.signal
1981
- });
1982
- if (!response.ok) {
1983
- const errorText = await response.text();
1984
- throw new BitfabError(
1985
- `HTTP ${response.status}: ${errorText.slice(0, 500)}`,
1986
- void 0,
1987
- response.status,
1988
- parseRetryAfterMs(readHeader(response, "retry-after"))
1989
- );
1990
- }
1991
- const result = await response.json();
1992
- if (result.error) {
1993
- if (result.url) {
1994
- throw new BitfabError(
1995
- `${result.error} Configure it at: ${this.serviceUrl}${result.url}`,
1996
- result.url
1997
- );
1998
- }
1999
- throw new BitfabError(result.error);
2000
- }
2001
- return result;
2002
- } catch (error) {
2003
- if (error instanceof BitfabError) {
2004
- throw error;
2005
- }
2006
- if (error instanceof Error) {
2007
- if (error.name === "AbortError") {
2008
- throw new BitfabError(`Request timed out after ${timeout}ms`);
2009
- }
2010
- throw new BitfabError(error.message);
2011
- }
2012
- throw new BitfabError("Unknown error occurred");
2013
- } finally {
2014
- clearTimeout(timeoutId);
2015
- }
2016
- }
2017
- /**
2018
- * Look up a function by name.
2019
- * Blocks until complete - needed for function execution.
2020
- */
2021
- async lookupFunction(name) {
2022
- return this.request("/api/sdk/functions/lookup", { name });
2023
- }
2024
- async getSimulationPlan() {
2025
- if (!this.hasApiKey()) {
2026
- throw new BitfabError(NO_API_KEY_FOR_SIMULATION_PLAN);
2027
- }
2028
- return this.get(
2029
- "/api/sdk/sim-plan",
2030
- SIMULATION_PLAN_READ_TIMEOUT_MS
2031
- );
2032
- }
2033
- async getTraceSpan(traceId, lookup) {
2034
- const searchParams = new URLSearchParams();
2035
- if (lookup.id !== void 0) {
2036
- searchParams.set("id", lookup.id);
2037
- } else {
2038
- if (lookup.name !== void 0) {
2039
- searchParams.set("name", lookup.name);
2040
- }
2041
- if (lookup.type !== void 0) {
2042
- searchParams.set("type", lookup.type);
2043
- }
2044
- searchParams.set("occurrence", String(lookup.occurrence ?? "last"));
2045
- }
2046
- const endpoint = `/api/sdk/traces/${encodeURIComponent(traceId)}/span?${searchParams.toString()}`;
2047
- const response = await this.get(endpoint);
2048
- return response.span;
2049
- }
2050
- async getSpan(spanId) {
2051
- const response = await this.get(
2052
- `/api/sdk/spans/${encodeURIComponent(spanId)}`
2053
- );
2054
- return response.span;
2055
- }
2056
- /**
2057
- * GET a JSON endpoint on the service with the client's API key. Throws a
2058
- * `BitfabError` carrying the status text for any non-2xx response.
2059
- */
2060
- async get(endpoint, timeoutMs, extraHeaders) {
2061
- const url = `${this.serviceUrl}${endpoint}`;
2062
- const timeout = timeoutMs ?? this.timeout;
2063
- const controller = new AbortController();
2064
- const timeoutId = setTimeout(() => controller.abort(), timeout);
2065
- try {
2066
- const response = await fetch(url, {
2067
- method: "GET",
2068
- headers: {
2069
- Authorization: `Bearer ${this.resolveApiKey() ?? ""}`,
2070
- ...extraHeaders
2071
- },
2072
- signal: controller.signal
2073
- });
2074
- if (!response.ok) {
2075
- const errorText = await response.text();
2076
- throw new BitfabError(
2077
- `HTTP ${response.status}: ${errorText.slice(0, 500)}`,
2078
- void 0,
2079
- response.status,
2080
- parseRetryAfterMs(readHeader(response, "retry-after"))
2081
- );
2082
- }
2083
- return await response.json();
2084
- } catch (error) {
2085
- if (error instanceof BitfabError) {
2086
- throw error;
2087
- }
2088
- if (error instanceof Error) {
2089
- if (error.name === "AbortError") {
2090
- throw new BitfabError(`Request timed out after ${timeout}ms`);
2091
- }
2092
- throw new BitfabError(error.message);
2093
- }
2094
- throw new BitfabError("Unknown error occurred");
2095
- } finally {
2096
- clearTimeout(timeoutId);
2097
- }
2098
- }
2099
- /**
2100
- * Queue an internal trace (from local BAML execution via `call()`) onto this
2101
- * client's batching transport. `functionId` moves into the payload because
2102
- * the OTLP carrier has no path to carry it.
2103
- */
2104
- sendInternalTrace(functionId, payload) {
2105
- const body = {
2106
- ...payload,
2107
- functionId,
2108
- sdkPackage: __packageName__,
2109
- sdkVersion: __version__
2110
- };
2111
- this.getTraceTransport()?.submit(
2112
- "internal_trace",
2113
- body,
2114
- carrierMeta("internal_trace", body, void 0)
2115
- );
2116
- }
2117
- sendExternalSpan(payload) {
2118
- const ref = carrierRef(payload);
2119
- if (ref?.spanId !== void 0) {
2120
- this.traceCompletion.record(ref.traceId, ref.spanId);
2121
- }
2122
- const drop = () => {
2123
- if (ref?.spanId !== void 0) {
2124
- this.traceCompletion.abort(ref.traceId, ref.spanId);
2125
- }
2126
- };
2127
- const gate = this.externalSpanTransform;
2128
- if (gate === void 0) {
2129
- this.submitExternalSpan(payload);
2130
- return;
2131
- }
2132
- try {
2133
- gate(payload, (ready) => this.submitExternalSpan(ready), drop);
2134
- } catch (error) {
2135
- drop();
2136
- warnDroppedExternalSpan(error);
2137
- }
2138
- }
2139
- submitExternalSpan(payload) {
2140
- const body = {
2141
- ...payload,
2142
- sdkVersion: __version__
2143
- };
2144
- delete body[ROOT_TRACE_FUNCTION_KEY_FIELD];
2145
- delete body[DECLARED_NODE_FIELD];
2146
- this.getTraceTransport()?.submit(
2147
- "external_span",
2148
- body,
2149
- this.recordedMeta("external_span", payload, carrierRef(payload))
2150
- );
2151
- }
2152
- /**
2153
- * Queue an external trace completion (from OpenAI tracing) onto this
2154
- * client's batching transport. Fire-and-forget for the same reason as
2155
- * {@link HttpClient.sendExternalSpan}; replay confirms persistence with the
2156
- * server-authoritative barrier in `replay.ts`, not by awaiting this call.
2157
- */
2158
- sendExternalTrace(rawPayload) {
2159
- const payload = mergeCallerMetadataIntoTracePayload(rawPayload);
2160
- const traceId = sourceTraceIdOf(payload);
2161
- if (payload.completed === true && traceId !== void 0) {
2162
- this.traceCompletion.close(
2163
- traceId,
2164
- (expectedSpanCount) => this.sendCountedExternalTrace({ ...payload, expectedSpanCount }),
2165
- payload.dropped === true
2166
- );
2167
- return;
2168
- }
2169
- if (traceId !== void 0) {
2170
- this.traceCompletion.open(traceId);
2171
- }
2172
- this.sendCountedExternalTrace(payload);
2173
- }
2174
- sendCountedExternalTrace(payload) {
2175
- try {
2176
- const gate = this.externalTraceTransform;
2177
- if (gate === void 0) {
2178
- this.submitExternalTrace(payload);
2179
- } else {
2180
- gate(payload, (ready) => this.submitExternalTrace(ready));
2181
- }
2182
- } catch (error) {
2183
- warnDroppedExternalTrace(error);
2184
- }
2185
- }
2186
- submitExternalTrace(payload) {
2187
- this.getTraceTransport()?.submit(
2188
- "external_trace",
2189
- {
2190
- ...payload,
2191
- sdkPackage: __packageName__,
2192
- sdkVersion: __version__
2193
- },
2194
- this.recordedMeta(
2195
- "external_trace",
2196
- payload,
2197
- payload.completed === true ? carrierRef(payload) : void 0
2198
- )
2199
- );
2200
- }
2201
- /**
2202
- * Partial update of an existing trace identified by its Bitfab trace ID.
2203
- * Used by the detached `client.getTrace(id)` handle.
2204
- *
2205
- * Blocking, like the other trace-API calls: it resolves once the server has
2206
- * applied the change and rejects if the server refused it. A patch targets a
2207
- * trace that is already closed, so there is no batch for it to ride along
2208
- * with and no later signal that would reveal a silent failure.
2209
- */
2210
- async patchTrace(traceId, payload) {
2211
- const endpoint = `/api/sdk/traces/${encodeURIComponent(traceId)}`;
2212
- await this.request(endpoint, payload, { method: "PATCH" });
2213
- }
2214
- /**
2215
- * Start a replay session by fetching historical traces.
2216
- * Blocking call - creates an experiment and returns lightweight item references.
2217
- */
2218
- async startReplay(traceFunctionKey, limit, traceIds, name, codeChangeDescription, codeChangeFiles, includeDbBranchLease, experimentGroupId, datasetIds, graderIds, dbBranchSettings, attempts, includeOriginalMetadata, onlyWithAssertions, skipAssertionJudging, experimentalSelectiveReplay, notes, metadata, dryRun, experimentGroupName, invocation) {
2219
- const payload = { traceFunctionKey };
2220
- if (experimentalSelectiveReplay !== void 0) {
2221
- payload.experimentalSelectiveReplay = experimentalSelectiveReplay;
2222
- }
2223
- if (limit !== void 0) {
2224
- payload.limit = limit;
2225
- }
2226
- if (traceIds) {
2227
- payload.traceIds = traceIds;
2228
- }
2229
- if (name !== void 0) {
2230
- payload.name = name;
2231
- }
2232
- if (notes !== void 0) {
2233
- payload.notes = notes;
2234
- }
2235
- if (metadata !== void 0) {
2236
- payload.metadata = metadata;
2237
- }
2238
- if (codeChangeDescription !== void 0) {
2239
- payload.codeChangeDescription = codeChangeDescription;
2240
- }
2241
- if (codeChangeFiles !== void 0) {
2242
- payload.codeChangeFiles = codeChangeFiles;
2243
- }
2244
- if (includeDbBranchLease) {
2245
- payload.includeDbBranchLease = true;
2246
- payload.lazyDbBranchLease = true;
2247
- }
2248
- if (experimentGroupId !== void 0) {
2249
- payload.experimentGroupId = experimentGroupId;
2250
- }
2251
- if (experimentGroupName !== void 0) {
2252
- payload.experimentGroupName = experimentGroupName;
2253
- }
2254
- if (datasetIds !== void 0) {
2255
- if (datasetIds.length === 1) {
2256
- payload.datasetId = datasetIds[0];
2257
- } else {
2258
- payload.datasetIds = datasetIds;
2259
- }
2260
- }
2261
- if (graderIds !== void 0) {
2262
- payload.graderIds = graderIds;
2263
- }
2264
- if (dbBranchSettings !== void 0) {
2265
- payload.dbBranchSettings = dbBranchSettings;
2266
- }
2267
- if (attempts !== void 0 && attempts > 1) {
2268
- payload.attempts = attempts;
2269
- }
2270
- if (includeOriginalMetadata) {
2271
- payload.includeOriginalMetadata = true;
2272
- }
2273
- if (onlyWithAssertions) {
2274
- payload.onlyWithAssertions = true;
2275
- }
2276
- if (skipAssertionJudging !== true) {
2277
- payload.judgeAssertions = true;
2278
- }
2279
- if (dryRun) {
2280
- payload.dryRun = true;
2281
- }
2282
- if (invocation !== void 0) {
2283
- payload.invocation = invocation;
2284
- }
2285
- const git = await resolvedGitState();
2286
- if (git && !isEmptyGitState(git)) {
2287
- payload.git = git;
2288
- }
2289
- const timeout = includeDbBranchLease ? REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS : 3e4;
2290
- const response = await this.request(
2291
- "/api/sdk/replay/start",
2292
- payload,
2293
- { timeout }
2294
- );
2295
- const { testRunId, testRunUrl, ...rest } = response;
2296
- const experimentId = response.experimentId ?? testRunId;
2297
- const experimentUrl = response.experimentUrl ?? testRunUrl;
2298
- if (dryRun && response.experimentId === null) {
2299
- return { ...rest, experimentId: null, experimentUrl: null };
2300
- }
2301
- if (experimentId === void 0 || experimentId === null || experimentUrl === void 0 || experimentUrl === null) {
2302
- throw new BitfabError(
2303
- "Replay start response is missing the experiment ID or URL."
2304
- );
2305
- }
2306
- return { ...rest, experimentId, experimentUrl };
2307
- }
2308
- async resumeReplay(experimentId, traceFunctionKey, codeChangeFiles, force) {
2309
- const payload = {
2310
- experimentId,
2311
- traceFunctionKey,
2312
- lazyDbBranchLease: true
2313
- };
2314
- if (force === true) {
2315
- payload.force = true;
2316
- }
2317
- if (codeChangeFiles !== void 0) {
2318
- payload.codeChangeFiles = codeChangeFiles;
2319
- }
2320
- const git = await resolvedGitState();
2321
- if (git && !isEmptyGitState(git)) {
2322
- payload.git = git;
2323
- }
2324
- const response = await this.request(
2325
- "/api/sdk/replay/resume",
2326
- payload,
2327
- { timeout: REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS }
2328
- );
2329
- const { testRunId, testRunUrl, ...rest } = response;
2330
- const resumedExperimentId = response.experimentId ?? testRunId;
2331
- const experimentUrl = response.experimentUrl ?? testRunUrl;
2332
- if (resumedExperimentId === void 0 || experimentUrl === void 0) {
2333
- throw new BitfabError(
2334
- "Replay resume response is missing the experiment ID or URL."
2335
- );
2336
- }
2337
- return {
2338
- ...rest,
2339
- experimentId: resumedExperimentId,
2340
- experimentUrl,
2341
- work: rest.work ?? [],
2342
- finished: rest.finished ?? [],
2343
- skippedOriginalTraceIds: rest.skippedOriginalTraceIds ?? [],
2344
- includeDbBranchLease: rest.includeDbBranchLease ?? false,
2345
- dbBranchSettings: rest.dbBranchSettings ?? null
2346
- };
2347
- }
2348
- /**
2349
- * Fetch an external span by ID.
2350
- * Blocking GET request.
2351
- * The replay view limits rawData to input/output serialization fields.
2352
- */
2353
- async getExternalSpan(spanId, options) {
2354
- const query = options?.view === "replay" ? "?view=replay" : "";
2355
- const url = `${this.serviceUrl}/api/sdk/externalSpans/${spanId}${query}`;
2356
- const controller = new AbortController();
2357
- const timeoutId = setTimeout(() => controller.abort(), 3e4);
2358
- try {
2359
- const response = await fetch(url, {
2360
- method: "GET",
2361
- headers: { Authorization: `Bearer ${this.resolveApiKey() ?? ""}` },
2362
- signal: controller.signal
2363
- });
2364
- if (!response.ok) {
2365
- const errorText = await response.text();
2366
- throw new BitfabError(
2367
- `HTTP ${response.status}: ${errorText.slice(0, 500)}`
2368
- );
2369
- }
2370
- return await response.json();
2371
- } catch (error) {
2372
- if (error instanceof BitfabError) {
2373
- throw error;
2374
- }
2375
- if (error instanceof Error) {
2376
- if (error.name === "AbortError") {
2377
- throw new BitfabError("Request timed out after 30000ms");
2378
- }
2379
- throw new BitfabError(error.message);
2380
- }
2381
- throw new BitfabError("Unknown error occurred");
2382
- } finally {
2383
- clearTimeout(timeoutId);
2384
- }
2385
- }
2386
- /**
2387
- * Fetch the span tree for a root span.
2388
- * Blocking GET request.
2389
- *
2390
- * Pass `includeOutputs: false` for a payload-free tree (structure +
2391
- * `externalSpanId` only), so recorded outputs are fetched lazily per mocked
2392
- * span instead of all up front. Omit it (default eager) for `mock: "all"`.
2393
- * Pass `includeRootOutput: false` when the root was already fetched.
2394
- */
2395
- async getSpanTree(externalSpanId, options) {
2396
- const searchParams = new URLSearchParams();
2397
- if (options?.includeOutputs === false) {
2398
- searchParams.set("includeOutputs", "false");
2399
- }
2400
- if (options?.includeRootOutput === false) {
2401
- searchParams.set("includeRootOutput", "false");
2402
- }
2403
- const encodedQuery = searchParams.toString();
2404
- const query = encodedQuery ? `?${encodedQuery}` : "";
2405
- const url = `${this.serviceUrl}/api/sdk/replay/spanTree/${externalSpanId}${query}`;
2406
- const controller = new AbortController();
2407
- const timeoutId = setTimeout(() => controller.abort(), 3e4);
2408
- try {
2409
- const response = await fetch(url, {
2410
- method: "GET",
2411
- headers: { Authorization: `Bearer ${this.resolveApiKey() ?? ""}` },
2412
- signal: controller.signal
2413
- });
2414
- if (!response.ok) {
2415
- const errorText = await response.text();
2416
- throw new BitfabError(
2417
- `HTTP ${response.status}: ${errorText.slice(0, 500)}`
2418
- );
2419
- }
2420
- return await response.json();
2421
- } catch (error) {
2422
- if (error instanceof BitfabError) {
2423
- throw error;
2424
- }
2425
- if (error instanceof Error) {
2426
- if (error.name === "AbortError") {
2427
- throw new BitfabError("Request timed out after 30000ms");
2428
- }
2429
- throw new BitfabError(error.message);
2430
- }
2431
- throw new BitfabError("Unknown error occurred");
2432
- } finally {
2433
- clearTimeout(timeoutId);
2434
- }
2435
- }
2436
- /**
2437
- * Read which of a replay run's traces the server has fully persisted.
2438
- *
2439
- * With `expectedSpanCounts`, a trace appears in the response only once it
2440
- * has a final status AND at least that many persisted spans, which is what
2441
- * makes this a real barrier rather than a "the row exists" check.
2442
- */
2443
- async getReplayStatus(experimentId, expectedSpanCounts) {
2444
- return this.request(
2445
- "/api/sdk/replay/status",
2446
- { ...experimentIdWireFields(experimentId), expectedSpanCounts },
2447
- { timeout: 3e4 }
2448
- );
2449
- }
2450
- /**
2451
- * Mark a replay experiment as completed.
2452
- * Blocking call.
2453
- */
2454
- async completeReplay(experimentId) {
2455
- return this.request(
2456
- "/api/sdk/replay/complete",
2457
- experimentIdWireFields(experimentId),
2458
- { timeout: REPLAY_COMPLETE_REQUEST_TIMEOUT_MS }
2459
- );
2460
- }
2461
- async interruptReplay(experimentId) {
2462
- try {
2463
- await this.request(
2464
- "/api/sdk/replay/interrupt",
2465
- experimentIdWireFields(experimentId),
2466
- { timeout: REPLAY_INTERRUPT_REQUEST_TIMEOUT_MS }
2467
- );
2468
- return true;
2469
- } catch {
2470
- return false;
2471
- }
2472
- }
2473
- async heartbeatReplay(experimentId) {
2474
- try {
2475
- await this.request(
2476
- "/api/sdk/replay/heartbeat",
2477
- experimentIdWireFields(experimentId),
2478
- { timeout: REPLAY_HEARTBEAT_REQUEST_TIMEOUT_MS }
2479
- );
2480
- } catch {
2481
- }
2482
- }
2483
- async getReseedSource(traceId) {
2484
- return this.get(
2485
- `/api/sdk/traces/${encodeURIComponent(traceId)}/reseedSource`
2486
- );
2487
- }
2488
- async reseedTrace(traceId, runTraceId) {
2489
- return this.request(
2490
- `/api/sdk/traces/${encodeURIComponent(traceId)}/reseed`,
2491
- { runTraceId },
2492
- { timeout: 3e4 }
2493
- );
2494
- }
2495
- /**
2496
- * Ask the server to materialize a per-trace DB branch lease from a
2497
- * captured `dbSnapshotRef`. Blocking - the resolver creates a Neon
2498
- * snapshot + preview branch and polls operations to readiness, which
2499
- * can take seconds.
2500
- */
2501
- async resolveDbBranchLease(experimentId, traceId, dbBranchSettings, attempt) {
2502
- return this.request(
2503
- "/api/sdk/replay/resolveDbBranchLease",
2504
- {
2505
- ...experimentIdWireFields(experimentId),
2506
- traceId,
2507
- dbBranchSettings,
2508
- ...attempt !== void 0 && attempt > 0 ? { attempt } : {}
2509
- },
2510
- { timeout: REPLAY_DB_BRANCH_REQUEST_TIMEOUT_MS }
2511
- );
2512
- }
2513
- /** Release a previously-resolved DB branch by deleting its Neon branch. Idempotent server-side. */
2514
- async releaseDbBranchLease(neonBranchId) {
2515
- await this.request(
2516
- "/api/sdk/replay/releaseDbBranchLease",
2517
- { neonBranchId },
2518
- { timeout: 3e4 }
2519
- );
2520
- }
2521
- };
2522
- function experimentIdWireFields(experimentId) {
2523
- return { experimentId, testRunId: experimentId };
2524
- }
2525
-
2526
- export {
2527
- BitfabError,
2528
- gitRunner,
2529
- readEnv,
2530
- __version__,
2531
- asyncStorageReady,
2532
- createAsyncLocalStorage,
2533
- replayContextReady,
2534
- runWithReplayContext,
2535
- warnOnce,
2536
- writeOnce,
2537
- serializePayloadBody,
2538
- unrefTimer,
2539
- awaitOnExit,
2540
- flushTraces,
2541
- awaitPendingRequests,
2542
- SPAN_TYPES,
2543
- parseRetryAfterMs,
2544
- HttpClient,
2545
- experimentIdWireFields
2546
- };
2547
- //# sourceMappingURL=chunk-27B3UBSS.js.map