bitfab 0.52.4 → 0.52.6

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 (41) hide show
  1. package/README.md +2 -0
  2. package/dist/autoTrace.cjs +84 -34
  3. package/dist/autoTrace.cjs.map +1 -1
  4. package/dist/autoTrace.d.cts +19 -4
  5. package/dist/autoTrace.d.ts +19 -4
  6. package/dist/autoTrace.js +9 -3
  7. package/dist/{chunk-HKTODDFP.js → chunk-5KVK733P.js} +3 -3
  8. package/dist/chunk-5KVK733P.js.map +1 -0
  9. package/dist/{chunk-U2D7ACC4.js → chunk-DRTHTSHO.js} +110 -13
  10. package/dist/chunk-DRTHTSHO.js.map +1 -0
  11. package/dist/{chunk-ZUD7OFYB.js → chunk-E5BLYL5X.js} +81 -34
  12. package/dist/chunk-E5BLYL5X.js.map +1 -0
  13. package/dist/{chunk-IG3CPSRQ.js → chunk-GJKU7VWG.js} +2 -2
  14. package/dist/{chunk-IG3CPSRQ.js.map → chunk-GJKU7VWG.js.map} +1 -1
  15. package/dist/{chunk-34B7PVAM.js → chunk-NXC6NYIY.js} +3 -2
  16. package/dist/{chunk-34B7PVAM.js.map → chunk-NXC6NYIY.js.map} +1 -1
  17. package/dist/{chunk-AUROMI67.js → chunk-P26KVTI5.js} +371 -46
  18. package/dist/chunk-P26KVTI5.js.map +1 -0
  19. package/dist/{http-F3AXLOJT.js → http-ER2NMEKI.js} +2 -2
  20. package/dist/{http-RFNQ7LSU.js → http-MGES3ZVX.js} +2 -2
  21. package/dist/index.cjs +561 -104
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +10 -2
  24. package/dist/index.d.ts +10 -2
  25. package/dist/index.js +4 -4
  26. package/dist/node.cjs +561 -104
  27. package/dist/node.cjs.map +1 -1
  28. package/dist/node.d.cts +1 -1
  29. package/dist/node.d.ts +1 -1
  30. package/dist/node.js +4 -4
  31. package/dist/{replay-ZOTYMBMD.js → replay-5XES2LBL.js} +3 -3
  32. package/dist/replayCli.js +2 -2
  33. package/dist/seedCli.js +2 -2
  34. package/package.json +1 -1
  35. package/dist/chunk-AUROMI67.js.map +0 -1
  36. package/dist/chunk-HKTODDFP.js.map +0 -1
  37. package/dist/chunk-U2D7ACC4.js.map +0 -1
  38. package/dist/chunk-ZUD7OFYB.js.map +0 -1
  39. /package/dist/{http-F3AXLOJT.js.map → http-ER2NMEKI.js.map} +0 -0
  40. /package/dist/{http-RFNQ7LSU.js.map → http-MGES3ZVX.js.map} +0 -0
  41. /package/dist/{replay-ZOTYMBMD.js.map → replay-5XES2LBL.js.map} +0 -0
package/dist/index.cjs CHANGED
@@ -51,7 +51,7 @@ var __version__, __packageName__;
51
51
  var init_version_generated = __esm({
52
52
  "src/version.generated.ts"() {
53
53
  "use strict";
54
- __version__ = "0.52.4";
54
+ __version__ = "0.52.6";
55
55
  __packageName__ = "bitfab";
56
56
  }
57
57
  });
@@ -1130,7 +1130,7 @@ var init_otel = __esm({
1130
1130
  if (this.onDelivered === void 0) {
1131
1131
  return;
1132
1132
  }
1133
- const refs = spans.map((span) => span.ref).filter((ref) => ref !== void 0);
1133
+ const refs = spans.map((span) => span.ref).filter((ref2) => ref2 !== void 0);
1134
1134
  if (refs.length === 0) {
1135
1135
  return;
1136
1136
  }
@@ -1387,9 +1387,9 @@ function parseRetryAfterMs(header) {
1387
1387
  }
1388
1388
  return Math.max(0, at - Date.now());
1389
1389
  }
1390
- function carrierMeta(operation, payload, ref) {
1390
+ function carrierMeta(operation, payload, ref2) {
1391
1391
  return {
1392
- ref,
1392
+ ref: ref2,
1393
1393
  name: carrierName(operation, payload),
1394
1394
  startTime: payloadTimestamp(payload, "started_at"),
1395
1395
  endTime: payloadTimestamp(payload, "ended_at"),
@@ -1634,22 +1634,22 @@ var init_http = __esm({
1634
1634
  return reports;
1635
1635
  }
1636
1636
  /** Build a carrier's meta and record what it adds to its trace's expected set. */
1637
- recordedMeta(operation, payload, ref) {
1638
- this.recordSubmittedCarrier(ref);
1639
- return carrierMeta(operation, payload, ref);
1637
+ recordedMeta(operation, payload, ref2) {
1638
+ this.recordSubmittedCarrier(ref2);
1639
+ return carrierMeta(operation, payload, ref2);
1640
1640
  }
1641
- recordSubmittedCarrier(ref) {
1642
- if (ref === void 0) {
1641
+ recordSubmittedCarrier(ref2) {
1642
+ if (ref2 === void 0) {
1643
1643
  return;
1644
1644
  }
1645
- const delivery = this.traceDeliveries.get(ref.traceId);
1645
+ const delivery = this.traceDeliveries.get(ref2.traceId);
1646
1646
  if (delivery === void 0) {
1647
1647
  return;
1648
1648
  }
1649
- if (ref.spanId === void 0) {
1649
+ if (ref2.spanId === void 0) {
1650
1650
  delivery.closed = true;
1651
1651
  } else {
1652
- delivery.submittedSpanIds.add(ref.spanId);
1652
+ delivery.submittedSpanIds.add(ref2.spanId);
1653
1653
  }
1654
1654
  }
1655
1655
  /**
@@ -1675,15 +1675,15 @@ var init_http = __esm({
1675
1675
  }
1676
1676
  }
1677
1677
  recordDeliveredCarriers(refs) {
1678
- for (const ref of refs) {
1679
- const delivery = this.traceDeliveries.get(ref.traceId);
1678
+ for (const ref2 of refs) {
1679
+ const delivery = this.traceDeliveries.get(ref2.traceId);
1680
1680
  if (delivery === void 0) {
1681
1681
  continue;
1682
1682
  }
1683
- if (ref.spanId === void 0) {
1683
+ if (ref2.spanId === void 0) {
1684
1684
  delivery.closingAcked = true;
1685
1685
  } else {
1686
- delivery.ackedSpanIds.add(ref.spanId);
1686
+ delivery.ackedSpanIds.add(ref2.spanId);
1687
1687
  }
1688
1688
  }
1689
1689
  }
@@ -1713,9 +1713,9 @@ var init_http = __esm({
1713
1713
  */
1714
1714
  async waitForPendingRequests(timeoutMs = DEFAULT_LIFECYCLE_TIMEOUT_MS2) {
1715
1715
  const deadline = Date.now() + Math.max(timeoutMs, 0);
1716
- const settled = await this.settleDeferredWork(timeoutMs);
1716
+ const settled2 = await this.settleDeferredWork(timeoutMs);
1717
1717
  const flushed = await this.traceTransport?.flush(Math.max(0, deadline - Date.now())) ?? true;
1718
- return settled && flushed;
1718
+ return settled2 && flushed;
1719
1719
  }
1720
1720
  /**
1721
1721
  * Flush and permanently close this client's tracing transport. Idempotent:
@@ -1728,14 +1728,14 @@ var init_http = __esm({
1728
1728
  }
1729
1729
  const deadline = Date.now() + Math.max(timeoutMs, 0);
1730
1730
  this.closing = (async () => {
1731
- const settled = await this.settleDeferredWork(
1731
+ const settled2 = await this.settleDeferredWork(
1732
1732
  Math.max(0, deadline - Date.now())
1733
1733
  );
1734
1734
  this.closed = true;
1735
1735
  const transport = this.traceTransport;
1736
1736
  this.traceTransport = void 0;
1737
1737
  const shutdownOk = await transport?.shutdown(Math.max(0, deadline - Date.now())) ?? true;
1738
- return settled && shutdownOk;
1738
+ return settled2 && shutdownOk;
1739
1739
  })();
1740
1740
  return this.closing;
1741
1741
  }
@@ -2346,6 +2346,112 @@ var init_randomUuid = __esm({
2346
2346
  }
2347
2347
  });
2348
2348
 
2349
+ // src/gitCommand.ts
2350
+ function isUnrefable(value) {
2351
+ return typeof value === "object" && value !== null && "unref" in value && typeof value.unref === "function";
2352
+ }
2353
+ function unrefStream(stream) {
2354
+ if (isUnrefable(stream)) {
2355
+ stream.unref();
2356
+ }
2357
+ }
2358
+ function terminate(child) {
2359
+ if (child.pid && process.platform !== "win32") {
2360
+ try {
2361
+ process.kill(-child.pid, "SIGTERM");
2362
+ return;
2363
+ } catch {
2364
+ child.kill("SIGTERM");
2365
+ return;
2366
+ }
2367
+ }
2368
+ child.kill("SIGTERM");
2369
+ }
2370
+ async function gitRunner(options) {
2371
+ let spawn;
2372
+ try {
2373
+ ;
2374
+ ({ spawn } = await import("child_process"));
2375
+ } catch {
2376
+ return null;
2377
+ }
2378
+ return (dir, args) => new Promise((resolve) => {
2379
+ let child;
2380
+ try {
2381
+ child = spawn("git", args, {
2382
+ cwd: dir,
2383
+ detached: process.platform !== "win32",
2384
+ stdio: ["ignore", "pipe", "pipe"]
2385
+ });
2386
+ } catch {
2387
+ resolve(null);
2388
+ return;
2389
+ }
2390
+ const chunks = [];
2391
+ let size = 0;
2392
+ let overflow = false;
2393
+ let exitCode = null;
2394
+ let done = false;
2395
+ const timers = [];
2396
+ const schedule = (callback, ms) => {
2397
+ const timer = setTimeout(callback, ms);
2398
+ if (!options.keepProcessAlive) {
2399
+ timer.unref();
2400
+ }
2401
+ timers.push(timer);
2402
+ };
2403
+ const finish = () => {
2404
+ if (done) {
2405
+ return;
2406
+ }
2407
+ done = true;
2408
+ for (const timer of timers) {
2409
+ clearTimeout(timer);
2410
+ }
2411
+ child.stdout?.destroy();
2412
+ child.stderr?.destroy();
2413
+ resolve(
2414
+ exitCode === 0 && !overflow ? Buffer.concat(chunks).toString("utf8") : null
2415
+ );
2416
+ };
2417
+ child.stdout?.on("data", (chunk) => {
2418
+ size += chunk.length;
2419
+ if (size > options.maxBuffer) {
2420
+ overflow = true;
2421
+ terminate(child);
2422
+ return;
2423
+ }
2424
+ chunks.push(chunk);
2425
+ });
2426
+ child.stderr?.resume();
2427
+ child.on("error", () => {
2428
+ exitCode = null;
2429
+ finish();
2430
+ });
2431
+ child.on("exit", (code) => {
2432
+ exitCode = code;
2433
+ schedule(finish, EXIT_GRACE_MS);
2434
+ });
2435
+ child.on("close", (code) => {
2436
+ exitCode = code ?? exitCode;
2437
+ finish();
2438
+ });
2439
+ schedule(() => terminate(child), options.timeoutMs);
2440
+ if (!options.keepProcessAlive) {
2441
+ child.unref();
2442
+ unrefStream(child.stdout);
2443
+ unrefStream(child.stderr);
2444
+ }
2445
+ });
2446
+ }
2447
+ var EXIT_GRACE_MS;
2448
+ var init_gitCommand = __esm({
2449
+ "src/gitCommand.ts"() {
2450
+ "use strict";
2451
+ EXIT_GRACE_MS = 500;
2452
+ }
2453
+ });
2454
+
2349
2455
  // src/mockOverride.ts
2350
2456
  function resolveMockValue(value, ctx) {
2351
2457
  return typeof value === "function" ? value(ctx) : value;
@@ -2402,37 +2508,33 @@ async function readCodeChangeFile() {
2402
2508
  }
2403
2509
  }
2404
2510
  async function captureCodeChangeFromGit(cwd, label) {
2405
- let execFile;
2406
2511
  let readFile;
2407
2512
  try {
2408
2513
  ;
2409
- ({ execFile } = await import("child_process"));
2410
2514
  ({ readFile } = await import("fs/promises"));
2411
2515
  } catch {
2412
2516
  return null;
2413
2517
  }
2414
- const git = (dir, args) => new Promise((resolve) => {
2415
- execFile(
2416
- "git",
2417
- args,
2418
- // 30s timeout so a hung git (e.g. a network-touching ref op) can't
2419
- // block the whole replay indefinitely.
2420
- { cwd: dir, maxBuffer: 64 * 1024 * 1024, timeout: 3e4 },
2421
- (err, stdout) => resolve(err ? null : stdout)
2422
- );
2518
+ const git = await gitRunner({
2519
+ timeoutMs: 3e4,
2520
+ maxBuffer: 64 * 1024 * 1024,
2521
+ keepProcessAlive: true
2423
2522
  });
2523
+ if (!git) {
2524
+ return null;
2525
+ }
2424
2526
  try {
2425
2527
  const root = (await git(cwd, ["rev-parse", "--show-toplevel"]))?.trim();
2426
2528
  if (!root) {
2427
2529
  return null;
2428
2530
  }
2429
- const resolved = await resolveBase(git, root);
2430
- if (!resolved) {
2531
+ const resolved2 = await resolveBase(git, root);
2532
+ if (!resolved2) {
2431
2533
  return null;
2432
2534
  }
2433
- const { base, fromTrunk } = resolved;
2434
- const blobBytes = async (ref, path) => {
2435
- const out = await git(root, ["cat-file", "-s", `${ref}:${path}`]);
2535
+ const { base, fromTrunk } = resolved2;
2536
+ const blobBytes = async (ref2, path) => {
2537
+ const out = await git(root, ["cat-file", "-s", `${ref2}:${path}`]);
2436
2538
  const n = out ? Number.parseInt(out.trim(), 10) : Number.NaN;
2437
2539
  return Number.isFinite(n) ? n : 0;
2438
2540
  };
@@ -2524,8 +2626,8 @@ async function resolveBase(git, root) {
2524
2626
  }
2525
2627
  return await refExists(git, root, "HEAD") ? { base: "HEAD", fromTrunk: false } : null;
2526
2628
  }
2527
- async function refExists(git, root, ref) {
2528
- return await git(root, ["rev-parse", "--verify", `${ref}^{object}`]) !== null;
2629
+ async function refExists(git, root, ref2) {
2630
+ return await git(root, ["rev-parse", "--verify", `${ref2}^{object}`]) !== null;
2529
2631
  }
2530
2632
  async function readWorkingFile(readFile, root, path) {
2531
2633
  try {
@@ -2560,6 +2662,7 @@ var MAX_FILES, MAX_FILE_BYTES, MAX_TOTAL_BYTES, TRUNK_CANDIDATES, NUL;
2560
2662
  var init_codeChange = __esm({
2561
2663
  "src/codeChange.ts"() {
2562
2664
  "use strict";
2665
+ init_gitCommand();
2563
2666
  MAX_FILES = 60;
2564
2667
  MAX_FILE_BYTES = 5e5;
2565
2668
  MAX_TOTAL_BYTES = 2e6;
@@ -2764,9 +2867,9 @@ async function processItem(httpClient, serverItem, fn, testRunId, mockStrategy,
2764
2867
  const originalSpanId = serverItem.originalSpanId ?? serverItem.sourceSpanId;
2765
2868
  try {
2766
2869
  if (includeDbBranchLease && !lease && !leaseError) {
2767
- let resolved;
2870
+ let resolved2;
2768
2871
  try {
2769
- resolved = await httpClient.resolveDbBranchLease(
2872
+ resolved2 = await httpClient.resolveDbBranchLease(
2770
2873
  testRunId,
2771
2874
  originalTraceId,
2772
2875
  dbBranchSettings,
@@ -2780,10 +2883,10 @@ async function processItem(httpClient, serverItem, fn, testRunId, mockStrategy,
2780
2883
  cause
2781
2884
  );
2782
2885
  }
2783
- lease = resolved.lease ?? void 0;
2784
- leaseError = resolved.leaseError ?? void 0;
2785
- dbSnapshotRef = resolved.dbSnapshotRef ?? dbSnapshotRef;
2786
- dbBranchTimings = resolved.timings ?? dbBranchTimings;
2886
+ lease = resolved2.lease ?? void 0;
2887
+ leaseError = resolved2.leaseError ?? void 0;
2888
+ dbSnapshotRef = resolved2.dbSnapshotRef ?? dbSnapshotRef;
2889
+ dbBranchTimings = resolved2.timings ?? dbBranchTimings;
2787
2890
  }
2788
2891
  if (leaseError) {
2789
2892
  throw new DbBranchReplayError(
@@ -4104,19 +4207,18 @@ init_asyncStorage();
4104
4207
  // src/autoTrace.ts
4105
4208
  init_asyncStorage();
4106
4209
  var autoTraceGlobal = globalThis;
4107
- var autoTraceState = autoTraceGlobal.__bitfabAutoTraceStateV3 ?? {
4210
+ var autoTraceState = autoTraceGlobal.__bitfabAutoTraceStateV4 ?? {
4108
4211
  storage: null,
4109
4212
  browserScope: void 0,
4110
4213
  capturePolicies: /* @__PURE__ */ new WeakMap(),
4111
4214
  activeRoots: 0
4112
4215
  };
4113
- autoTraceGlobal.__bitfabAutoTraceStateV3 = autoTraceState;
4216
+ autoTraceGlobal.__bitfabAutoTraceStateV4 = autoTraceState;
4114
4217
  function initializeAutoTraceStorage() {
4115
4218
  autoTraceState.storage ?? (autoTraceState.storage = createAsyncLocalStorage());
4116
4219
  }
4117
- function runWithAutoTraceContext(context, fn, depth = 0) {
4220
+ function runWithAutoTraceScope(scope, fn) {
4118
4221
  initializeAutoTraceStorage();
4119
- const scope = { context, depth };
4120
4222
  if (autoTraceState.storage) {
4121
4223
  return autoTraceState.storage.run(scope, fn);
4122
4224
  }
@@ -4128,41 +4230,65 @@ function runWithAutoTraceContext(context, fn, depth = 0) {
4128
4230
  autoTraceState.browserScope = previous;
4129
4231
  }
4130
4232
  }
4233
+ function currentAutoTraceEntries() {
4234
+ return currentAutoTraceScope()?.entries ?? [];
4235
+ }
4236
+ function replaceEntry(entries, previous, updated) {
4237
+ return entries.map((entry) => entry === previous ? updated : entry);
4238
+ }
4239
+ function runWithAutoTraceEntry(previous, updated, fn) {
4240
+ const result = runWithAutoTraceScope(
4241
+ { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },
4242
+ fn
4243
+ );
4244
+ if (isAutoTraceAsyncGenerator(result)) {
4245
+ return wrapAutoTraceEntryAsyncGenerator(previous, updated, result);
4246
+ }
4247
+ return result;
4248
+ }
4249
+ function wrapAutoTraceEntryAsyncGenerator(previous, updated, source) {
4250
+ const step = (method, value) => runWithAutoTraceScope(
4251
+ { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },
4252
+ () => source[method](value)
4253
+ );
4254
+ const wrapped = {
4255
+ next: (value) => step("next", value),
4256
+ return: (value) => step("return", value),
4257
+ throw: (error) => step("throw", error),
4258
+ [Symbol.asyncIterator]: () => wrapped
4259
+ };
4260
+ return wrapped;
4261
+ }
4262
+ function clearAutoTraceNodeConfiguration(fn) {
4263
+ return runWithAutoTraceScope({ entries: currentAutoTraceEntries() }, fn);
4264
+ }
4131
4265
  function runWithAutoTraceNodeConfiguration(nodeConfiguration, fn) {
4132
4266
  const scope = currentAutoTraceScope();
4133
- if (!scope) {
4267
+ if (!scope || scope.entries.length === 0) {
4134
4268
  return fn();
4135
4269
  }
4136
- const configuredScope = { ...scope, nodeConfiguration };
4137
- let result;
4138
- if (autoTraceState.storage) {
4139
- result = autoTraceState.storage.run(configuredScope, fn);
4140
- } else {
4141
- const previous = autoTraceState.browserScope;
4142
- autoTraceState.browserScope = configuredScope;
4143
- try {
4144
- result = fn();
4145
- } finally {
4146
- autoTraceState.browserScope = previous;
4147
- }
4148
- }
4270
+ const result = runWithAutoTraceScope({ ...scope, nodeConfiguration }, fn);
4149
4271
  if (isAutoTraceAsyncGenerator(result)) {
4150
4272
  return wrapAutoTraceNodeAsyncGenerator(nodeConfiguration, result);
4151
4273
  }
4152
4274
  return result;
4153
4275
  }
4154
- function runWithAutoTraceRootContext(context, fn) {
4276
+ function runWithAutoTraceRootContext(context, spanStack, fn) {
4155
4277
  autoTraceState.activeRoots += 1;
4278
+ const entries = [
4279
+ ...currentAutoTraceEntries(),
4280
+ { context, depth: 0, spanStack }
4281
+ ];
4156
4282
  let result;
4157
4283
  try {
4158
- result = runWithAutoTraceContext(context, fn);
4284
+ result = runWithAutoTraceScope({ entries }, fn);
4159
4285
  } catch (error) {
4160
4286
  autoTraceState.activeRoots -= 1;
4161
4287
  throw error;
4162
4288
  }
4163
4289
  if (isAutoTraceAsyncGenerator(result)) {
4164
4290
  autoTraceState.activeRoots -= 1;
4165
- return wrapAutoTraceAsyncGenerator(context, result);
4291
+ return wrapAutoTraceAsyncGenerator(context, spanStack, result);
4166
4292
  }
4167
4293
  if (result instanceof Promise) {
4168
4294
  return result.finally(() => {
@@ -4172,6 +4298,15 @@ function runWithAutoTraceRootContext(context, fn) {
4172
4298
  autoTraceState.activeRoots -= 1;
4173
4299
  return result;
4174
4300
  }
4301
+ function invokeThroughAutoTraceEntries(entries, step, fn) {
4302
+ let run = fn;
4303
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
4304
+ const entry = entries[index];
4305
+ const next = run;
4306
+ run = () => step(entry, next);
4307
+ }
4308
+ return run();
4309
+ }
4175
4310
  function isAutoTraceAsyncGenerator(value) {
4176
4311
  if (value === null || typeof value !== "object") {
4177
4312
  return false;
@@ -4179,8 +4314,8 @@ function isAutoTraceAsyncGenerator(value) {
4179
4314
  const candidate = value;
4180
4315
  return typeof candidate.next === "function" && typeof candidate.return === "function" && typeof candidate.throw === "function" && typeof candidate[Symbol.asyncIterator] === "function";
4181
4316
  }
4182
- function wrapAutoTraceAsyncGenerator(context, source) {
4183
- const step = (method, value) => runWithAutoTraceRootContext(context, () => source[method](value));
4317
+ function wrapAutoTraceAsyncGenerator(context, spanStack, source) {
4318
+ const step = (method, value) => runWithAutoTraceRootContext(context, spanStack, () => source[method](value));
4184
4319
  const wrapped = {
4185
4320
  next: (value) => step("next", value),
4186
4321
  return: (value) => step("return", value),
@@ -4206,7 +4341,7 @@ function __bitfabAutoTraceActive() {
4206
4341
  if (autoTraceState.activeRoots === 0) {
4207
4342
  return false;
4208
4343
  }
4209
- return currentAutoTraceScope() !== void 0;
4344
+ return currentAutoTraceEntries().length > 0;
4210
4345
  }
4211
4346
  function currentAutoTraceScope() {
4212
4347
  initializeAutoTraceStorage();
@@ -4559,24 +4694,239 @@ function mixedTracingError(enteredApi, entered, enclosing, traceFunctionKey) {
4559
4694
  `opt-in and opt-out tracing can't be mixed in one call stack: ${enteredApi} (${entered})${subject} was entered inside a ${SURFACE_API[enclosing]} call (${enclosing}). ${MIXED_SURFACE_REMEDY[entered]}`
4560
4695
  );
4561
4696
  }
4562
- function assertSurfacesCompatible(requested, resolved, parentSurface, traceFunctionKey) {
4697
+ function assertSurfacesCompatible(requested, resolved2, parentSurface, traceFunctionKey) {
4563
4698
  if (requested === "inherit" || requested === "neutral") {
4564
4699
  return;
4565
4700
  }
4566
- if (resolved === void 0 || parentSurface === void 0) {
4701
+ if (resolved2 === void 0 || parentSurface === void 0) {
4567
4702
  return;
4568
4703
  }
4569
- if (parentSurface === resolved) {
4704
+ if (parentSurface === resolved2) {
4570
4705
  return;
4571
4706
  }
4572
4707
  throw mixedTracingError(
4573
- SURFACE_API[resolved],
4574
- resolved,
4708
+ SURFACE_API[resolved2],
4709
+ resolved2,
4575
4710
  parentSurface,
4576
4711
  traceFunctionKey
4577
4712
  );
4578
4713
  }
4579
4714
 
4715
+ // src/commitRef.ts
4716
+ init_gitCommand();
4717
+ init_readEnv();
4718
+ var EXPLICIT_SHA_ENV = "BITFAB_COMMIT_SHA";
4719
+ var DISABLE_ENV = "BITFAB_DISABLE_COMMIT_REF";
4720
+ var GIT_TIMEOUT_MS = 2e3;
4721
+ var GIT_MAX_BUFFER = 1024 * 1024;
4722
+ var VERCEL_PROVIDER_HOSTS = {
4723
+ github: "github.com",
4724
+ gitlab: "gitlab.com",
4725
+ bitbucket: "bitbucket.org"
4726
+ };
4727
+ function read(env, name) {
4728
+ if (name === null) {
4729
+ return null;
4730
+ }
4731
+ const value = env(name)?.trim();
4732
+ return value ? value : null;
4733
+ }
4734
+ function remoteFrom(...names) {
4735
+ return (env) => {
4736
+ const parts = names.map((name) => read(env, name));
4737
+ if (parts.some((part) => part === null)) {
4738
+ return null;
4739
+ }
4740
+ return normalizeRemote(parts.join("/"));
4741
+ };
4742
+ }
4743
+ function vercelRemote(env) {
4744
+ const provider = read(env, "VERCEL_GIT_PROVIDER")?.toLowerCase() ?? "";
4745
+ const host = VERCEL_PROVIDER_HOSTS[provider];
4746
+ const owner = read(env, "VERCEL_GIT_REPO_OWNER");
4747
+ const slug = read(env, "VERCEL_GIT_REPO_SLUG");
4748
+ if (!host || !owner || !slug) {
4749
+ return null;
4750
+ }
4751
+ return `${host}/${owner}/${slug}`;
4752
+ }
4753
+ function noRemote() {
4754
+ return null;
4755
+ }
4756
+ var PLATFORM_ENVS = [
4757
+ ["VERCEL_GIT_COMMIT_SHA", "VERCEL_GIT_COMMIT_REF", vercelRemote],
4758
+ [
4759
+ "GITHUB_SHA",
4760
+ "GITHUB_REF_NAME",
4761
+ remoteFrom("GITHUB_SERVER_URL", "GITHUB_REPOSITORY")
4762
+ ],
4763
+ ["RAILWAY_GIT_COMMIT_SHA", "RAILWAY_GIT_BRANCH", noRemote],
4764
+ ["RENDER_GIT_COMMIT", "RENDER_GIT_BRANCH", noRemote],
4765
+ ["SOURCE_VERSION", null, noRemote],
4766
+ ["CF_PAGES_COMMIT_SHA", "CF_PAGES_BRANCH", noRemote],
4767
+ ["CI_COMMIT_SHA", "CI_COMMIT_REF_NAME", remoteFrom("CI_REPOSITORY_URL")],
4768
+ [
4769
+ "BUILD_SOURCEVERSION",
4770
+ "BUILD_SOURCEBRANCHNAME",
4771
+ remoteFrom("BUILD_REPOSITORY_URI")
4772
+ ],
4773
+ ["CIRCLE_SHA1", "CIRCLE_BRANCH", remoteFrom("CIRCLE_REPOSITORY_URL")]
4774
+ ];
4775
+ var COMMIT_REF_ENV_NAMES = [
4776
+ EXPLICIT_SHA_ENV,
4777
+ DISABLE_ENV,
4778
+ ...PLATFORM_ENVS.flatMap(
4779
+ ([sha, branch]) => branch === null ? [sha] : [sha, branch]
4780
+ ),
4781
+ "GITHUB_SERVER_URL",
4782
+ "GITHUB_REPOSITORY",
4783
+ "CI_REPOSITORY_URL",
4784
+ "BUILD_REPOSITORY_URI",
4785
+ "CIRCLE_REPOSITORY_URL",
4786
+ "VERCEL_GIT_PROVIDER",
4787
+ "VERCEL_GIT_REPO_OWNER",
4788
+ "VERCEL_GIT_REPO_SLUG"
4789
+ ];
4790
+ function normalizeRemote(raw) {
4791
+ const value = raw?.trim();
4792
+ if (!value) {
4793
+ return null;
4794
+ }
4795
+ let host = "";
4796
+ let path = value;
4797
+ if (value.includes("://")) {
4798
+ try {
4799
+ const parsed = new URL(value);
4800
+ host = parsed.hostname;
4801
+ path = parsed.pathname;
4802
+ } catch {
4803
+ return null;
4804
+ }
4805
+ } else {
4806
+ const separator = value.indexOf(":");
4807
+ if (separator !== -1) {
4808
+ const head = value.slice(0, separator);
4809
+ host = head.slice(head.lastIndexOf("@") + 1);
4810
+ path = value.slice(separator + 1);
4811
+ }
4812
+ }
4813
+ path = path.replace(/^\/+|\/+$/g, "");
4814
+ if (path.endsWith(".git")) {
4815
+ path = path.slice(0, -".git".length).replace(/\/+$/, "");
4816
+ }
4817
+ if (!host) {
4818
+ return path || null;
4819
+ }
4820
+ return path ? `${host}/${path}` : host;
4821
+ }
4822
+ function resolveCommitRefFromEnv(env) {
4823
+ const explicit = read(env, EXPLICIT_SHA_ENV);
4824
+ const platform = PLATFORM_ENVS.find(([sha]) => read(env, sha) !== null);
4825
+ if (!platform) {
4826
+ if (explicit === null) {
4827
+ return null;
4828
+ }
4829
+ return {
4830
+ sha: explicit,
4831
+ branch: null,
4832
+ dirty: null,
4833
+ remote: null,
4834
+ rootSha: null
4835
+ };
4836
+ }
4837
+ const [shaEnv, branchEnv, readRemote] = platform;
4838
+ return {
4839
+ sha: explicit ?? read(env, shaEnv),
4840
+ branch: read(env, branchEnv),
4841
+ dirty: null,
4842
+ remote: readRemote(env),
4843
+ rootSha: null
4844
+ };
4845
+ }
4846
+ async function resolveCommitRefFromGit(cwd) {
4847
+ const git = await gitRunner({
4848
+ timeoutMs: GIT_TIMEOUT_MS,
4849
+ maxBuffer: GIT_MAX_BUFFER,
4850
+ keepProcessAlive: false
4851
+ });
4852
+ if (!git) {
4853
+ return null;
4854
+ }
4855
+ const run = async (args) => (await git(cwd, args))?.trim() ?? null;
4856
+ const sha = await run(["rev-parse", "HEAD"]);
4857
+ if (!sha) {
4858
+ return null;
4859
+ }
4860
+ const [branch, status, remote, roots] = await Promise.all([
4861
+ run(["symbolic-ref", "--short", "-q", "HEAD"]),
4862
+ run(["status", "--porcelain"]),
4863
+ run(["remote", "get-url", "origin"]),
4864
+ run(["rev-list", "--max-parents=0", "HEAD"])
4865
+ ]);
4866
+ return {
4867
+ sha,
4868
+ branch: branch || null,
4869
+ dirty: status === null ? null : status.length > 0,
4870
+ remote: normalizeRemote(remote),
4871
+ rootSha: roots ? roots.split(/\s+/).sort()[0] ?? null : null
4872
+ };
4873
+ }
4874
+ function commitRefWire(ref2) {
4875
+ return {
4876
+ sha: ref2.sha,
4877
+ branch: ref2.branch,
4878
+ dirty: ref2.dirty,
4879
+ remote: ref2.remote,
4880
+ root_sha: ref2.rootSha
4881
+ };
4882
+ }
4883
+ var resolved = false;
4884
+ var ref = null;
4885
+ var gitStarted = false;
4886
+ var settled = Promise.resolve();
4887
+ function startCommitRefResolution() {
4888
+ if (resolved || gitStarted) {
4889
+ return;
4890
+ }
4891
+ if (read(readEnv, DISABLE_ENV) !== null) {
4892
+ resolved = true;
4893
+ return;
4894
+ }
4895
+ const fromEnv = resolveCommitRefFromEnv(readEnv);
4896
+ if (fromEnv) {
4897
+ ref = fromEnv;
4898
+ resolved = true;
4899
+ return;
4900
+ }
4901
+ gitStarted = true;
4902
+ if (typeof process === "undefined") {
4903
+ resolved = true;
4904
+ return;
4905
+ }
4906
+ let cwd;
4907
+ try {
4908
+ cwd = process.cwd?.() ?? ".";
4909
+ } catch {
4910
+ resolved = true;
4911
+ return;
4912
+ }
4913
+ settled = resolveCommitRefFromGit(cwd).then(
4914
+ (fromGit) => {
4915
+ if (!resolved) {
4916
+ ref = fromGit;
4917
+ resolved = true;
4918
+ }
4919
+ },
4920
+ () => {
4921
+ resolved = true;
4922
+ }
4923
+ );
4924
+ }
4925
+ function currentCommitRef() {
4926
+ startCommitRefResolution();
4927
+ return ref;
4928
+ }
4929
+
4580
4930
  // src/client.ts
4581
4931
  init_constants();
4582
4932
 
@@ -5069,11 +5419,11 @@ var BitfabLangGraphCallbackHandler = class {
5069
5419
  this.invocations.set(invocation.rootRunId, invocation);
5070
5420
  }
5071
5421
  if (!willHide) {
5072
- let resolved = parentSpan;
5073
- while (resolved?.hidden === true) {
5074
- resolved = resolved.parentId ? this.runToSpan.get(resolved.parentId) : void 0;
5422
+ let resolved2 = parentSpan;
5423
+ while (resolved2?.hidden === true) {
5424
+ resolved2 = resolved2.parentId ? this.runToSpan.get(resolved2.parentId) : void 0;
5075
5425
  }
5076
- effectiveParentId = resolved ? resolved.spanId : invocation.activeContext?.spanId ?? null;
5426
+ effectiveParentId = resolved2 ? resolved2.spanId : invocation.activeContext?.spanId ?? null;
5077
5427
  } else {
5078
5428
  effectiveParentId = parentRunId ?? null;
5079
5429
  }
@@ -6573,6 +6923,7 @@ var Bitfab = class {
6573
6923
  validateDbSnapshotConfig(config.dbSnapshot);
6574
6924
  }
6575
6925
  this.dbSnapshot = config.dbSnapshot;
6926
+ startCommitRefResolution();
6576
6927
  this.httpClient = new HttpClient({
6577
6928
  apiKey: () => this.resolveApiKey(),
6578
6929
  serviceUrl: this.serviceUrl,
@@ -6743,11 +7094,15 @@ var Bitfab = class {
6743
7094
  type: options.type ?? "custom",
6744
7095
  surface: "opt-out"
6745
7096
  };
6746
- const tracedRoot = this.withSpan(
7097
+ const rootName = options.name ?? name;
7098
+ const buildTracedRoot = (spanOptions) => this.withSpan(
6747
7099
  traceFunctionKey,
6748
- rootOptions,
7100
+ spanOptions,
6749
7101
  function(...args) {
6750
- const capturePolicy = getAutoTraceCapturePolicy(self, traceFunctionKey);
7102
+ const capturePolicy = getAutoTraceCapturePolicy(
7103
+ self,
7104
+ traceFunctionKey
7105
+ );
6751
7106
  self.refreshAutoTraceCapturePolicy(traceFunctionKey);
6752
7107
  let spansUsed = 0;
6753
7108
  let truncated = false;
@@ -6768,19 +7123,54 @@ var Bitfab = class {
6768
7123
  `"${traceFunctionKey}" hit an automatic subtree capture limit (maxDepth=${maxDepth}, maxSpans=${maxSpans}); its trace is incomplete. Raise the limits or narrow the subtree with exclude.`
6769
7124
  );
6770
7125
  };
7126
+ const spanStackOf = (entry) => entry.spanStack;
7127
+ const openChild = (entry, childOptions, inputs, isAsync, invokeFn) => {
7128
+ const runInside = () => runWithAutoTraceEntry(
7129
+ entry,
7130
+ {
7131
+ context: autoTraceContext,
7132
+ depth: entry.depth + 1,
7133
+ spanStack: getSpanStack()
7134
+ },
7135
+ invokeFn
7136
+ );
7137
+ return runWithSpanStack(spanStackOf(entry), () => {
7138
+ if (isAsync) {
7139
+ const tracedAsyncChild = self.withSpan(
7140
+ traceFunctionKey,
7141
+ childOptions,
7142
+ async (..._inputs) => await runInside()
7143
+ );
7144
+ return tracedAsyncChild(...inputs);
7145
+ }
7146
+ const tracedChild = self.withSpan(
7147
+ traceFunctionKey,
7148
+ childOptions,
7149
+ (..._inputs) => runInside()
7150
+ );
7151
+ return tracedChild(...inputs);
7152
+ });
7153
+ };
7154
+ const overBudget = (entry) => {
7155
+ if (entry.depth < maxDepth && spansUsed < maxSpans) {
7156
+ return false;
7157
+ }
7158
+ runWithSpanStack(spanStackOf(entry), warnTruncated);
7159
+ return true;
7160
+ };
6771
7161
  const autoTraceContext = {
6772
- invoke(definition, inputs, invokeFn, depth, nodeConfiguration) {
7162
+ traceFunctionKey,
7163
+ invoke(definition, inputs, invokeFn, entry, nodeConfiguration) {
6773
7164
  const nameParts = definition.name.split(".");
6774
7165
  const simpleName = nameParts[nameParts.length - 1];
6775
- const invokeWithoutNode = () => nodeConfiguration === void 0 ? invokeFn() : runWithAutoTraceContext(autoTraceContext, invokeFn, depth);
7166
+ const invokeWithoutNode = () => nodeConfiguration === void 0 ? invokeFn() : clearAutoTraceNodeConfiguration(invokeFn);
6776
7167
  if (excluded.has(definition.name) || simpleName !== void 0 && excluded.has(simpleName) || nodeConfiguration === void 0 && definition.wrapper === true && !includeWrappers) {
6777
7168
  return invokeWithoutNode();
6778
7169
  }
6779
7170
  if (nodeConfiguration?.capture === false) {
6780
- return runWithAutoTraceContext(autoTraceContext, invokeFn, depth);
7171
+ return clearAutoTraceNodeConfiguration(invokeFn);
6781
7172
  }
6782
- if (depth >= maxDepth || spansUsed >= maxSpans) {
6783
- warnTruncated();
7173
+ if (overBudget(entry)) {
6784
7174
  return invokeWithoutNode();
6785
7175
  }
6786
7176
  spansUsed += 1;
@@ -6803,34 +7193,81 @@ var Bitfab = class {
6803
7193
  finalize: nodeConfiguration.finalize
6804
7194
  }
6805
7195
  };
6806
- const invokeWithAutoTraceContext = () => runWithAutoTraceContext(autoTraceContext, invokeFn, depth + 1);
6807
- if (definition.async === true) {
6808
- const tracedAsyncChild = self.withSpan(
6809
- traceFunctionKey,
6810
- childOptions,
6811
- async (..._inputs) => await invokeWithAutoTraceContext()
6812
- );
6813
- return tracedAsyncChild(...inputs);
6814
- }
6815
- const tracedChild = self.withSpan(
6816
- traceFunctionKey,
7196
+ return openChild(
7197
+ entry,
6817
7198
  childOptions,
6818
- (..._inputs) => invokeWithAutoTraceContext()
7199
+ inputs,
7200
+ definition.async === true,
7201
+ invokeFn
6819
7202
  );
6820
- return tracedChild(...inputs);
7203
+ },
7204
+ invokeNestedRoot(nestedName, nestedFunctionName, inputs, invokeFn, entry, link) {
7205
+ if (excluded.has(nestedName) || excluded.has(nestedFunctionName) || overBudget(entry)) {
7206
+ return invokeFn();
7207
+ }
7208
+ spansUsed += 1;
7209
+ const childOptions = {
7210
+ name: nestedName,
7211
+ type: "function",
7212
+ captureWhen: "nested",
7213
+ surface: "opt-out",
7214
+ captureContent: true,
7215
+ ...link !== void 0 && { nestedTrace: link }
7216
+ };
7217
+ return openChild(entry, childOptions, inputs, false, invokeFn);
6821
7218
  }
6822
7219
  };
6823
7220
  return runWithAutoTraceRootContext(
6824
7221
  autoTraceContext,
7222
+ getSpanStack(),
6825
7223
  () => fn.apply(this, args)
6826
7224
  );
6827
7225
  }
6828
7226
  );
7227
+ const tracedRoot = buildTracedRoot(rootOptions);
6829
7228
  const autoTraceRoot = function(...args) {
6830
7229
  if (!self.shouldRecord()) {
6831
7230
  return fn.apply(this, args);
6832
7231
  }
6833
- return tracedRoot.apply(this, args);
7232
+ const enclosing = currentAutoTraceEntries();
7233
+ if (enclosing.length === 0) {
7234
+ return tracedRoot.apply(this, args);
7235
+ }
7236
+ const link = getReplayContext() || inSeedScope() ? void 0 : { traceFunctionKey };
7237
+ return invokeThroughAutoTraceEntries(
7238
+ enclosing,
7239
+ (entry, next) => entry.context.invokeNestedRoot(
7240
+ rootName,
7241
+ name,
7242
+ args,
7243
+ next,
7244
+ entry,
7245
+ link
7246
+ ),
7247
+ () => {
7248
+ if (link === void 0) {
7249
+ return fn.apply(this, args);
7250
+ }
7251
+ const innermost = enclosing[enclosing.length - 1];
7252
+ const innermostNow = currentAutoTraceEntries().find(
7253
+ (entry) => entry.context === innermost.context
7254
+ ) ?? innermost;
7255
+ const innermostStack = innermostNow.spanStack;
7256
+ const copy = innermostStack[innermostStack.length - 1];
7257
+ const detachedRoot = buildTracedRoot({
7258
+ ...rootOptions,
7259
+ ...copy !== void 0 && {
7260
+ enclosingTrace: {
7261
+ traceId: copy.traceId,
7262
+ spanId: copy.spanId,
7263
+ traceFunctionKey: innermost.context.traceFunctionKey,
7264
+ link
7265
+ }
7266
+ }
7267
+ });
7268
+ return runWithSpanStack([], () => detachedRoot.apply(this, args));
7269
+ }
7270
+ );
6834
7271
  };
6835
7272
  Object.defineProperty(autoTraceRoot, "_bitfabTraceFunctionKey", {
6836
7273
  value: traceFunctionKey
@@ -7419,6 +7856,10 @@ var Bitfab = class {
7419
7856
  const spanId = randomUuid();
7420
7857
  const parentSpanId = parentContext?.spanId ?? null;
7421
7858
  const isRootSpan = parentSpanId === null;
7859
+ if (options.enclosingTrace !== void 0) {
7860
+ options.enclosingTrace.link.traceId = traceId;
7861
+ options.enclosingTrace.link.rootSpanId = spanId;
7862
+ }
7422
7863
  const requestedSurface = options.surface ?? DEFAULT_SURFACE;
7423
7864
  const surface = resolveSurface(requestedSurface, parentContext?.surface);
7424
7865
  assertSurfacesCompatible(
@@ -7468,7 +7909,9 @@ var Bitfab = class {
7468
7909
  spanType: options.type ?? "custom",
7469
7910
  functionId: options.functionId,
7470
7911
  captureContent: options.captureContent ?? true,
7471
- autoTraceDefinition: options.autoTraceDefinition
7912
+ autoTraceDefinition: options.autoTraceDefinition,
7913
+ nestedTrace: options.nestedTrace,
7914
+ enclosingTrace: options.enclosingTrace
7472
7915
  };
7473
7916
  const sendSpan = async (params) => {
7474
7917
  const replayCtx = getReplayContext();
@@ -7666,15 +8109,15 @@ var Bitfab = class {
7666
8109
  );
7667
8110
  }
7668
8111
  return runWithSpanStack(newStack, async () => {
7669
- const resolved = await resolution;
7670
- if (resolved.matched) {
8112
+ const resolved2 = await resolution;
8113
+ if (resolved2.matched) {
7671
8114
  void sendSpan({
7672
- result: resolved.output,
8115
+ result: resolved2.output,
7673
8116
  mocked: true,
7674
8117
  mockTarget: "output",
7675
8118
  mockSource: "override"
7676
8119
  });
7677
- return resolved.output;
8120
+ return resolved2.output;
7678
8121
  }
7679
8122
  if (shouldMockWithBaseStrategy && !mockSpan) {
7680
8123
  throw new BitfabError(
@@ -7910,6 +8353,10 @@ var Bitfab = class {
7910
8353
  if (params.dbSnapshotRef) {
7911
8354
  rawTrace.db_snapshot_ref = params.dbSnapshotRef;
7912
8355
  }
8356
+ const commitRef = currentCommitRef();
8357
+ if (commitRef) {
8358
+ rawTrace.commit_ref = commitRefWire(commitRef);
8359
+ }
7913
8360
  if (params.ingestionType) {
7914
8361
  rawTrace.ingestion_type = params.ingestionType;
7915
8362
  }
@@ -7974,6 +8421,16 @@ var Bitfab = class {
7974
8421
  function_line: params.autoTraceDefinition.line,
7975
8422
  function_column: params.autoTraceDefinition.column
7976
8423
  },
8424
+ ...params.nestedTrace?.traceId !== void 0 && {
8425
+ nested_trace_id: params.nestedTrace.traceId,
8426
+ nested_trace_function_key: params.nestedTrace.traceFunctionKey,
8427
+ nested_root_span_id: params.nestedTrace.rootSpanId
8428
+ },
8429
+ ...params.enclosingTrace !== void 0 && {
8430
+ enclosing_trace_id: params.enclosingTrace.traceId,
8431
+ enclosing_trace_function_key: params.enclosingTrace.traceFunctionKey,
8432
+ enclosing_span_id: params.enclosingTrace.spanId
8433
+ },
7977
8434
  ...serializedInputs !== void 0 && {
7978
8435
  input: serializedInputs.json,
7979
8436
  ...serializedInputs.meta !== void 0 && {