bitfab 0.65.11 → 0.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/autoTrace-CQw0qMBt.cjs.map +1 -1
  2. package/dist/autoTrace-O40k8f5M.js.map +1 -1
  3. package/dist/autoTrace.d.cts +2 -0
  4. package/dist/autoTrace.d.ts +2 -0
  5. package/dist/{babelPlugin-C70OxrqA.js → babelPlugin-CBjx6aJe.js} +28 -3
  6. package/dist/babelPlugin-CBjx6aJe.js.map +1 -0
  7. package/dist/{babelPlugin-Nta4-VcL.cjs → babelPlugin-ZR9ilYct.cjs} +28 -3
  8. package/dist/babelPlugin-ZR9ilYct.cjs.map +1 -0
  9. package/dist/{http-DdlELWcL.js → http-CcYPHER5.js} +2 -2
  10. package/dist/http-CcYPHER5.js.map +1 -0
  11. package/dist/{http-CFwCJQyF.cjs → http-CxT_WDAh.cjs} +2 -2
  12. package/dist/http-CxT_WDAh.cjs.map +1 -0
  13. package/dist/{index-CUstKXuW.d.cts → index-BFgtvRni.d.cts} +224 -61
  14. package/dist/{index-CUstKXuW.d.ts → index-BFgtvRni.d.ts} +224 -61
  15. package/dist/index.cjs +3 -2
  16. package/dist/index.d.cts +2 -2
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.js +3 -3
  19. package/dist/node.cjs +3 -2
  20. package/dist/node.d.cts +2 -2
  21. package/dist/node.d.ts +2 -2
  22. package/dist/node.js +3 -3
  23. package/dist/{registryCommand-Cr7m6Vif.js → registryCommand-Dk4Y1ZgW.js} +2 -2
  24. package/dist/registryCommand-Dk4Y1ZgW.js.map +1 -0
  25. package/dist/replayCli.js +1 -1
  26. package/dist/seedCli.js +1 -1
  27. package/dist/{src-lTOsAt47.js → src-CFDoTgXw.js} +180 -55
  28. package/dist/src-CFDoTgXw.js.map +1 -0
  29. package/dist/{src-mV-7DNLd.cjs → src-DXmdXbOL.cjs} +185 -54
  30. package/dist/src-DXmdXbOL.cjs.map +1 -0
  31. package/dist/transform/babel.cjs +1 -1
  32. package/dist/transform/babel.d.cts +1 -0
  33. package/dist/transform/babel.d.ts +1 -0
  34. package/dist/transform/babel.js +1 -1
  35. package/dist/transform/loaderRuntime.cjs +2 -2
  36. package/dist/transform/loaderRuntime.js +2 -2
  37. package/dist/transform/nodeLoader.js +27 -2
  38. package/dist/transform/nodeLoader.js.map +1 -1
  39. package/dist/transform/swc.cjs +1 -1
  40. package/dist/transform/swc.js +1 -1
  41. package/dist/transform/unplugin.cjs +2 -2
  42. package/dist/transform/unplugin.js +2 -2
  43. package/dist/{transform-BcyUocwm.js → transform-DP1qnD8u.js} +2 -2
  44. package/dist/{transform-BcyUocwm.js.map → transform-DP1qnD8u.js.map} +1 -1
  45. package/dist/{transform-BjxHGGKc.cjs → transform-D_pSvPJc.cjs} +2 -2
  46. package/dist/{transform-BjxHGGKc.cjs.map → transform-D_pSvPJc.cjs.map} +1 -1
  47. package/package.json +1 -1
  48. package/dist/babelPlugin-C70OxrqA.js.map +0 -1
  49. package/dist/babelPlugin-Nta4-VcL.cjs.map +0 -1
  50. package/dist/http-CFwCJQyF.cjs.map +0 -1
  51. package/dist/http-DdlELWcL.js.map +0 -1
  52. package/dist/registryCommand-Cr7m6Vif.js.map +0 -1
  53. package/dist/src-lTOsAt47.js.map +0 -1
  54. package/dist/src-mV-7DNLd.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"autoTrace-CQw0qMBt.cjs","names":["target"],"sources":["../src/asyncStorage.ts","../src/captureSuppression.ts","../src/warnOnce.ts","../src/autoTrace.ts"],"sourcesContent":["/**\n * Shared AsyncLocalStorage loader.\n *\n * Provides two ways to initialize AsyncLocalStorage:\n *\n * 1. **Synchronous registration** (preferred for Node.js):\n * `asyncStorageNode.ts` calls `registerAsyncLocalStorageClass()` at module\n * evaluation time, so the class is available immediately - no async gap.\n * The `node.ts` entry point imports it before anything else.\n *\n * 2. **Async dynamic import** (fallback for the default entry point):\n * Loads `node:async_hooks` via a bundler-safe dynamic import. This is used\n * by the default `index.ts` entry point so the SDK works in browsers\n * (where the import silently fails) and in Node.js when imported via the\n * default entry point.\n *\n * ## Why the dynamic import looks like this\n *\n * We need to handle three environments:\n *\n * 1. **Pure Node.js** - `import(\"node:async_hooks\")` works natively.\n * 2. **Webpack/Turbopack (Next.js server)** - The bundler processes\n * `import()` calls at build time. The `webpackIgnore` magic comment tells\n * webpack (and turbopack) to emit a native `import()` call instead of\n * trying to resolve it, so Node.js handles it at runtime.\n * 3. **Browsers / Edge** - The `process.versions?.node` guard prevents\n * execution entirely. If it somehow runs, `.catch(() => {})` swallows\n * the failure.\n */\n\nexport interface AsyncLocalStorageLike<T> {\n getStore(): T | undefined\n run<R>(store: T, fn: () => R): R\n}\n\nlet AsyncLocalStorageClass: (new () => AsyncLocalStorageLike<unknown>) | null =\n null\nlet initDone = false\n\n/**\n * Register the AsyncLocalStorage class synchronously.\n *\n * Called by `asyncStorageNode.ts` at module evaluation time so the class\n * is available before any span is created - no async gap, no race condition.\n *\n * Safe to call multiple times; subsequent calls are no-ops.\n */\nexport function registerAsyncLocalStorageClass(\n cls: new () => AsyncLocalStorageLike<unknown>,\n): void {\n if (!AsyncLocalStorageClass) {\n AsyncLocalStorageClass = cls\n }\n initDone = true\n}\n\n/**\n * Assert that AsyncLocalStorage was registered successfully.\n *\n * Called by `node.ts` after importing `asyncStorageNode.ts` to catch\n * import-order bugs at startup rather than silently degrading to the\n * browser fallback (flat spans with no nesting).\n *\n * This should ONLY be called from the Node.js entry point where we\n * know `node:async_hooks` must be available.\n */\nexport function assertAsyncStorageRegistered(): void {\n if (!AsyncLocalStorageClass) {\n console.warn(\n \"Bitfab: AsyncLocalStorage not available - nested span context will not propagate.\",\n )\n }\n}\n\nexport const asyncStorageReady: Promise<void> = (\n typeof process !== \"undefined\" && process.versions?.node\n ? // The join trick hides \"node:async_hooks\" from static analysis so\n // bundlers that ban Node.js built-ins don't fail at build time.\n // webpackIgnore tells webpack/turbopack to emit a native import()\n // so Node.js can resolve the module at runtime.\n import(\n /* webpackIgnore: true */\n [\"node\", \"async_hooks\"].join(\":\")\n )\n .then(\n (mod: {\n AsyncLocalStorage: new () => AsyncLocalStorageLike<unknown>\n }) => {\n registerAsyncLocalStorageClass(mod.AsyncLocalStorage)\n },\n )\n .catch(() => {})\n : Promise.resolve()\n).then(() => {\n initDone = true\n})\n\nexport function isAsyncStorageInitDone(): boolean {\n return initDone\n}\n\nexport function createAsyncLocalStorage<T>(): AsyncLocalStorageLike<T> | null {\n return AsyncLocalStorageClass\n ? (new AsyncLocalStorageClass() as AsyncLocalStorageLike<T>)\n : null\n}\n","interface CaptureSuppressionState {\n depth: number\n}\n\ninterface CaptureSuppressionGlobal {\n __bitfabCaptureSuppressionV1?: CaptureSuppressionState\n}\n\nconst suppressionGlobal = globalThis as unknown as CaptureSuppressionGlobal\nconst suppressionState: CaptureSuppressionState =\n suppressionGlobal.__bitfabCaptureSuppressionV1 ?? { depth: 0 }\nsuppressionGlobal.__bitfabCaptureSuppressionV1 = suppressionState\n\nexport function isCaptureSuppressed(): boolean {\n return suppressionState.depth > 0\n}\n\nexport function runWithCaptureSuppressed<T>(fn: () => T): T {\n suppressionState.depth += 1\n try {\n return fn()\n } finally {\n suppressionState.depth -= 1\n }\n}\n","/**\n * Emit a `console.warn` at most once per distinct `key` for the life of the\n * process.\n *\n * The SDK must NEVER crash a host app, so every failure on the user's path\n * degrades silently (a span is dropped, a call runs untraced, a payload is\n * stubbed). Silent is safe but undebuggable: a user who suddenly has no traces,\n * or sees `<unserializable>` in a span, has no signal as to why. A one-time\n * warning per distinct issue restores that signal without spamming the console\n * from a hot path.\n *\n * Keys should identify the specific degradation (e.g. include the traced\n * function key) so each distinct issue warns once, not just the first one seen.\n */\nconst warned = new Set<string>()\n\nexport function warn(message: string): void {\n try {\n console.warn(`[bitfab] ${message}`)\n } catch {\n // Logging must never crash the host app (e.g. a closed/replaced console).\n }\n}\n\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n warn(message)\n}\n\nexport function writeOnce(\n key: string,\n line: string,\n write: (line: string) => void = console.warn,\n): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n try {\n write(line)\n } catch {}\n}\n\n/** Test-only: clear the dedup set so a warning can fire again. */\nexport function _resetWarnOnce(): void {\n warned.clear()\n}\n","import {\n type AsyncLocalStorageLike,\n createAsyncLocalStorage,\n} from \"./asyncStorage.js\"\nimport { isCaptureSuppressed } from \"./captureSuppression.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nexport interface AutoTraceFunctionDefinition {\n id: string\n name: string\n file: string\n line: number\n column: number\n async?: boolean\n wrapper?: boolean\n}\n\nexport interface AutoTraceNodeConfiguration {\n functionName: string\n name?: string\n type?: \"llm\" | \"agent\" | \"function\" | \"guardrail\" | \"handoff\" | \"custom\"\n capture: boolean\n experimentId?: string\n /** @deprecated Use experimentId. */\n testRunId?: string\n mockOnReplay?: boolean\n replayReusable?: boolean\n // biome-ignore lint/suspicious/noExplicitAny: node finalizers receive the configured function's result, whose type is owned by the caller\n finalize?: (result: any) => unknown | Promise<unknown>\n}\n\nexport interface NestedTraceLink {\n traceFunctionKey: string\n traceId?: string\n rootSpanId?: string\n}\n\nexport interface SpanDetails {\n contexts: Record<string, unknown>[]\n prompt?: string\n}\n\nexport interface AutoTraceEntry {\n context: AutoTraceContext\n depth: number\n spanStack: unknown\n}\n\nexport interface AutoTraceContext {\n readonly traceFunctionKey: string\n invoke<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n fn: () => T,\n entry: AutoTraceEntry,\n spanDetails: SpanDetails,\n nodeConfiguration?: AutoTraceNodeConfiguration,\n ): T\n invokeNestedRoot<T>(\n name: string,\n functionName: string,\n inputs: unknown[],\n fn: () => T,\n entry: AutoTraceEntry,\n link: NestedTraceLink | undefined,\n spanDetails: SpanDetails,\n ): T\n}\n\ninterface AutoTraceRootFunction {\n name: string\n entering: boolean\n}\n\ninterface AutoTraceScope {\n entries: readonly AutoTraceEntry[]\n nodeConfiguration?: AutoTraceNodeConfiguration\n rootFunction?: AutoTraceRootFunction\n}\n\ninterface AutoTraceState {\n storage: AsyncLocalStorageLike<AutoTraceScope> | null\n browserScope: AutoTraceScope | undefined\n // Older SDK copies read this field when sharing the process-wide V4 state.\n capturePolicies: WeakMap<object, Map<string, ReadonlySet<string>>>\n activeRoots: number\n}\n\ninterface AutoTraceGlobal {\n __bitfabAutoTraceStateV4?: AutoTraceState\n __bitfab_auto_trace_transformed_v1__?: boolean\n}\n\ninterface AutoTraceAsyncGenerator {\n next(value?: unknown): Promise<IteratorResult<unknown, unknown>>\n return(value?: unknown): Promise<IteratorResult<unknown, unknown>>\n throw(error?: unknown): Promise<IteratorResult<unknown, unknown>>\n [Symbol.asyncIterator](): AutoTraceAsyncGenerator\n}\n\nconst autoTraceGlobal = globalThis as unknown as AutoTraceGlobal\nconst autoTraceState: AutoTraceState =\n autoTraceGlobal.__bitfabAutoTraceStateV4 ?? {\n storage: null,\n browserScope: undefined,\n capturePolicies: new WeakMap(),\n activeRoots: 0,\n }\nautoTraceGlobal.__bitfabAutoTraceStateV4 = autoTraceState\n\nfunction initializeAutoTraceStorage(): void {\n autoTraceState.storage ??= createAsyncLocalStorage<AutoTraceScope>()\n}\n\nfunction runWithAutoTraceScope<T>(scope: AutoTraceScope, fn: () => T): T {\n initializeAutoTraceStorage()\n if (autoTraceState.storage) {\n return autoTraceState.storage.run(scope, fn)\n }\n\n const previous = autoTraceState.browserScope\n autoTraceState.browserScope = scope\n try {\n return fn()\n } finally {\n autoTraceState.browserScope = previous\n }\n}\n\nexport function currentAutoTraceEntries(): readonly AutoTraceEntry[] {\n return currentAutoTraceScope()?.entries ?? []\n}\n\nfunction replaceEntry(\n entries: readonly AutoTraceEntry[],\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n): readonly AutoTraceEntry[] {\n return entries.map((entry) => (entry === previous ? updated : entry))\n}\n\nexport function runWithAutoTraceEntry<T>(\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n fn: () => T,\n): T {\n const result = runWithAutoTraceScope(\n { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },\n fn,\n )\n if (isAutoTraceAsyncGenerator(result)) {\n return wrapAutoTraceEntryAsyncGenerator(previous, updated, result) as T\n }\n return result\n}\n\nfunction wrapAutoTraceEntryAsyncGenerator(\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceScope(\n { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },\n () => source[method](value),\n )\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nexport function clearAutoTraceNodeConfiguration<T>(fn: () => T): T {\n return runWithAutoTraceScope({ entries: currentAutoTraceEntries() }, fn)\n}\n\nexport function runWithAutoTraceNodeConfiguration<T>(\n nodeConfiguration: AutoTraceNodeConfiguration,\n fn: () => T,\n): T {\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0) {\n return fn()\n }\n\n const result = runWithAutoTraceScope({ ...scope, nodeConfiguration }, fn)\n if (isAutoTraceAsyncGenerator(result)) {\n return wrapAutoTraceNodeAsyncGenerator(nodeConfiguration, result) as T\n }\n return result\n}\n\nexport function runAsAutoTraceRootFunction<T>(\n functionName: string,\n fn: () => T,\n): T {\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0 || functionName === \"\") {\n return fn()\n }\n const rootFunction: AutoTraceRootFunction = {\n name: functionName,\n entering: true,\n }\n try {\n return runWithAutoTraceScope({ ...scope, rootFunction }, fn)\n } finally {\n rootFunction.entering = false\n }\n}\n\nfunction isRootFunctionEntry(\n scope: AutoTraceScope,\n simpleName: string | undefined,\n): boolean {\n const rootFunction = scope.rootFunction\n if (rootFunction === undefined || !rootFunction.entering) {\n return false\n }\n rootFunction.entering = false\n return rootFunction.name === simpleName\n}\n\nconst SUBTREE_TRACING_DOCS_URL =\n \"https://docs.bitfab.ai/typescript-sdk#experimental-subtree-tracing\"\n\nfunction noteTransformedModule(): void {\n autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ = true\n}\n\nfunction transformInstalled(): boolean {\n return autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ === true\n}\n\nfunction runsOnNode(): boolean {\n return typeof process !== \"undefined\" && Boolean(process.versions?.node)\n}\n\nfunction closeAutoTraceRoot(): void {\n autoTraceState.activeRoots -= 1\n}\n\nfunction settleAutoTraceRoot(context: AutoTraceContext): void {\n closeAutoTraceRoot()\n if (transformInstalled() || !runsOnNode()) {\n return\n }\n warnOnce(\n \"auto-trace-transform-missing\",\n `trace root \"${context.traceFunctionKey}\" recorded only its own span. ` +\n \"No module in this build was compiled by @bitfab/sdk/transform, so calls \" +\n \"beneath the root were not discovered. Add the SDK's transform adapter \" +\n `to the server build: ${SUBTREE_TRACING_DOCS_URL}`,\n )\n}\n\nexport function runWithAutoTraceRootContext<T>(\n context: AutoTraceContext,\n spanStack: unknown,\n fn: () => T,\n): T {\n autoTraceState.activeRoots += 1\n const entries = [\n ...currentAutoTraceEntries(),\n { context, depth: 0, spanStack },\n ]\n let result: T\n try {\n result = runWithAutoTraceScope({ entries }, fn)\n } catch (error) {\n settleAutoTraceRoot(context)\n throw error\n }\n\n if (isAutoTraceAsyncGenerator(result)) {\n closeAutoTraceRoot()\n return wrapAutoTraceAsyncGenerator(context, spanStack, result) as T\n }\n\n if (result instanceof Promise) {\n return result.finally(() => {\n settleAutoTraceRoot(context)\n }) as T\n }\n\n settleAutoTraceRoot(context)\n return result\n}\n\nexport function invokeThroughAutoTraceEntries<T>(\n entries: readonly AutoTraceEntry[],\n step: (entry: AutoTraceEntry, next: () => T) => T,\n fn: () => T,\n): T {\n let run = fn\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const entry = entries[index] as AutoTraceEntry\n const next = run\n run = () => step(entry, next)\n }\n return run()\n}\n\nfunction isAutoTraceAsyncGenerator(\n value: unknown,\n): value is AutoTraceAsyncGenerator {\n if (value === null || typeof value !== \"object\") {\n return false\n }\n const candidate = value as Record<PropertyKey, unknown>\n return (\n typeof candidate.next === \"function\" &&\n typeof candidate.return === \"function\" &&\n typeof candidate.throw === \"function\" &&\n typeof candidate[Symbol.asyncIterator] === \"function\"\n )\n}\n\nfunction wrapAutoTraceAsyncGenerator(\n context: AutoTraceContext,\n spanStack: unknown,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceRootContext(context, spanStack, () => source[method](value))\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nfunction wrapAutoTraceNodeAsyncGenerator(\n nodeConfiguration: AutoTraceNodeConfiguration,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceNodeConfiguration(nodeConfiguration, () =>\n source[method](value),\n )\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nfunction shareFinalize(\n configuration: AutoTraceNodeConfiguration,\n): AutoTraceNodeConfiguration {\n const finalize = configuration.finalize\n if (finalize === undefined) {\n return configuration\n }\n let settled: Promise<unknown> | undefined\n return {\n ...configuration,\n finalize: (result: unknown) => {\n settled ??= Promise.resolve().then(() => finalize(result))\n return settled\n },\n }\n}\n\nexport function __bitfabAutoSpan<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n fn: () => T,\n): T {\n noteTransformedModule()\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0 || isCaptureSuppressed()) {\n return fn()\n }\n const nameParts = definition.name.split(\".\")\n const simpleName = nameParts[nameParts.length - 1]\n if (isRootFunctionEntry(scope, simpleName)) {\n return fn()\n }\n const nodeConfiguration =\n simpleName === scope.nodeConfiguration?.functionName\n ? shareFinalize(scope.nodeConfiguration)\n : undefined\n const spanDetails: SpanDetails = { contexts: [] }\n return invokeThroughAutoTraceEntries(\n scope.entries,\n (entry, next) =>\n entry.context.invoke(\n definition,\n inputs,\n next,\n entry,\n spanDetails,\n nodeConfiguration,\n ),\n fn,\n )\n}\n\n/**\n * Preserve a function's original call arguments for transform cases where\n * parameter bindings discard them, such as destructured arrow parameters.\n *\n * This helper is internal transform/runtime protocol. The proxy preserves the\n * target's callability, arity, async identity, and non-constructibility while\n * only allocating a trace closure beneath an active automatic trace root.\n *\n * @experimental The automatic tracing protocol may change.\n */\nexport function __bitfabAutoWrap<T extends (...args: never[]) => unknown>(\n definition: AutoTraceFunctionDefinition,\n fn: T,\n): T {\n noteTransformedModule()\n if (fn.name === \"\") {\n const nameParts = definition.name.split(\".\")\n const inferredName = nameParts[nameParts.length - 1]\n if (inferredName !== undefined) {\n Object.defineProperty(fn, \"name\", {\n configurable: true,\n value: inferredName,\n })\n }\n }\n\n const target = fn as unknown as (...args: unknown[]) => unknown\n return new Proxy(target, {\n apply(callTarget, thisArg, args) {\n if (!__bitfabAutoTraceActive()) {\n return Reflect.apply(callTarget, thisArg, args)\n }\n return __bitfabAutoSpan(definition, args, () =>\n Reflect.apply(callTarget, thisArg, args),\n )\n },\n }) as unknown as T\n}\n\n/**\n * Return whether the current call is inside an automatic trace root.\n *\n * Build transforms use this before allocating function metadata, captured\n * inputs, or an invocation closure. It is internal transform/runtime protocol,\n * not a supported application API.\n *\n * @experimental The automatic tracing protocol may change.\n */\nexport function __bitfabAutoTraceActive(): boolean {\n if (autoTraceState.activeRoots === 0 || isCaptureSuppressed()) {\n return false\n }\n return currentAutoTraceEntries().length > 0\n}\n\nfunction currentAutoTraceScope(): AutoTraceScope | undefined {\n initializeAutoTraceStorage()\n return autoTraceState.storage?.getStore() ?? autoTraceState.browserScope\n}\n\nexport function _resetAutoTraceTransformDetection(): void {\n autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ = undefined\n}\n"],"mappings":";AAmCA,IAAI,yBACF;AACF,IAAI,WAAW;AAUf,SAAgB,+BACd,KACM;CACN,IAAI,CAAC,wBACH,yBAAyB;CAE3B,WAAW;AACb;AAYA,SAAgB,+BAAqC;CACnD,IAAI,CAAC,wBACH,QAAQ,KACN,mFACF;AAEJ;AAEA,MAAa,qBACX,OAAO,YAAY,eAAe,QAAQ,UAAU;;AAKhD;;CAEE,CAAC,QAAQ,aAAa,CAAC,CAAC,KAAK,GAAG;CACjC,CACE,MACE,QAEK;CACJ,+BAA+B,IAAI,iBAAiB;AACtD,CACF,CAAC,CACA,YAAY,CAAC,CAAC,IACjB,QAAQ,QAAQ,EAAA,CACpB,WAAW;CACX,WAAW;AACb,CAAC;AAED,SAAgB,yBAAkC;CAChD,OAAO;AACT;AAEA,SAAgB,0BAA8D;CAC5E,OAAO,yBACF,IAAI,uBAAuB,IAC5B;AACN;;;ACjGA,MAAM,oBAAoB;AAC1B,MAAM,mBACJ,kBAAkB,gCAAgC,EAAE,OAAO,EAAE;AAC/D,kBAAkB,+BAA+B;AAEjD,SAAgB,sBAA+B;CAC7C,OAAO,iBAAiB,QAAQ;AAClC;AAEA,SAAgB,yBAA4B,IAAgB;CAC1D,iBAAiB,SAAS;CAC1B,IAAI;EACF,OAAO,GAAG;CACZ,UAAU;EACR,iBAAiB,SAAS;CAC5B;AACF;;;ACVA,MAAM,yBAA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AACF;AAYA,SAAgB,iBACd,YACA,IACG;CACH,sBAAsB;CACtB,IAAI,GAAG,SAAS,IAAI;EAClB,MAAM,YAAY,WAAW,KAAK,MAAM,GAAG;EAC3C,MAAM,eAAe,UAAU,UAAU,SAAS;EAClD,IAAI,iBAAiB,KAAA,GACnB,OAAO,eAAe,IAAI,QAAQ;GAChC,cAAc;GACd,OAAO;EACT,CAAC;CAEL;CAGA,OAAO,IAAI,MAAMA,IAAQ,EACvB,MAAM,YAAY,SAAS,MAAM;EAC/B,IAAI,CAAC,wBAAwB,GAC3B,OAAO,QAAQ,MAAM,YAAY,SAAS,IAAI;EAEhD,OAAO,iBAAiB,YAAY,YAClC,QAAQ,MAAM,YAAY,SAAS,IAAI,CACzC;CACF,EACF,CAAC;AACH;AAWA,SAAgB,0BAAmC;CACjD,IAAI,eAAe,gBAAgB,KAAK,oBAAoB,GAC1D,OAAO;CAET,OAAO,wBAAwB,CAAC,CAAC,SAAS;AAC5C;AAEA,SAAS,wBAAoD;CAC3D,2BAA2B;CAC3B,OAAO,eAAe,SAAS,SAAS,KAAK,eAAe;AAC9D;AAEA,SAAgB,oCAA0C;CACxD,gBAAgB,uCAAuC,KAAA;AACzD"}
1
+ {"version":3,"file":"autoTrace-CQw0qMBt.cjs","names":["target"],"sources":["../src/asyncStorage.ts","../src/captureSuppression.ts","../src/warnOnce.ts","../src/autoTrace.ts"],"sourcesContent":["/**\n * Shared AsyncLocalStorage loader.\n *\n * Provides two ways to initialize AsyncLocalStorage:\n *\n * 1. **Synchronous registration** (preferred for Node.js):\n * `asyncStorageNode.ts` calls `registerAsyncLocalStorageClass()` at module\n * evaluation time, so the class is available immediately - no async gap.\n * The `node.ts` entry point imports it before anything else.\n *\n * 2. **Async dynamic import** (fallback for the default entry point):\n * Loads `node:async_hooks` via a bundler-safe dynamic import. This is used\n * by the default `index.ts` entry point so the SDK works in browsers\n * (where the import silently fails) and in Node.js when imported via the\n * default entry point.\n *\n * ## Why the dynamic import looks like this\n *\n * We need to handle three environments:\n *\n * 1. **Pure Node.js** - `import(\"node:async_hooks\")` works natively.\n * 2. **Webpack/Turbopack (Next.js server)** - The bundler processes\n * `import()` calls at build time. The `webpackIgnore` magic comment tells\n * webpack (and turbopack) to emit a native `import()` call instead of\n * trying to resolve it, so Node.js handles it at runtime.\n * 3. **Browsers / Edge** - The `process.versions?.node` guard prevents\n * execution entirely. If it somehow runs, `.catch(() => {})` swallows\n * the failure.\n */\n\nexport interface AsyncLocalStorageLike<T> {\n getStore(): T | undefined\n run<R>(store: T, fn: () => R): R\n}\n\nlet AsyncLocalStorageClass: (new () => AsyncLocalStorageLike<unknown>) | null =\n null\nlet initDone = false\n\n/**\n * Register the AsyncLocalStorage class synchronously.\n *\n * Called by `asyncStorageNode.ts` at module evaluation time so the class\n * is available before any span is created - no async gap, no race condition.\n *\n * Safe to call multiple times; subsequent calls are no-ops.\n */\nexport function registerAsyncLocalStorageClass(\n cls: new () => AsyncLocalStorageLike<unknown>,\n): void {\n if (!AsyncLocalStorageClass) {\n AsyncLocalStorageClass = cls\n }\n initDone = true\n}\n\n/**\n * Assert that AsyncLocalStorage was registered successfully.\n *\n * Called by `node.ts` after importing `asyncStorageNode.ts` to catch\n * import-order bugs at startup rather than silently degrading to the\n * browser fallback (flat spans with no nesting).\n *\n * This should ONLY be called from the Node.js entry point where we\n * know `node:async_hooks` must be available.\n */\nexport function assertAsyncStorageRegistered(): void {\n if (!AsyncLocalStorageClass) {\n console.warn(\n \"Bitfab: AsyncLocalStorage not available - nested span context will not propagate.\",\n )\n }\n}\n\nexport const asyncStorageReady: Promise<void> = (\n typeof process !== \"undefined\" && process.versions?.node\n ? // The join trick hides \"node:async_hooks\" from static analysis so\n // bundlers that ban Node.js built-ins don't fail at build time.\n // webpackIgnore tells webpack/turbopack to emit a native import()\n // so Node.js can resolve the module at runtime.\n import(\n /* webpackIgnore: true */\n [\"node\", \"async_hooks\"].join(\":\")\n )\n .then(\n (mod: {\n AsyncLocalStorage: new () => AsyncLocalStorageLike<unknown>\n }) => {\n registerAsyncLocalStorageClass(mod.AsyncLocalStorage)\n },\n )\n .catch(() => {})\n : Promise.resolve()\n).then(() => {\n initDone = true\n})\n\nexport function isAsyncStorageInitDone(): boolean {\n return initDone\n}\n\nexport function createAsyncLocalStorage<T>(): AsyncLocalStorageLike<T> | null {\n return AsyncLocalStorageClass\n ? (new AsyncLocalStorageClass() as AsyncLocalStorageLike<T>)\n : null\n}\n","interface CaptureSuppressionState {\n depth: number\n}\n\ninterface CaptureSuppressionGlobal {\n __bitfabCaptureSuppressionV1?: CaptureSuppressionState\n}\n\nconst suppressionGlobal = globalThis as unknown as CaptureSuppressionGlobal\nconst suppressionState: CaptureSuppressionState =\n suppressionGlobal.__bitfabCaptureSuppressionV1 ?? { depth: 0 }\nsuppressionGlobal.__bitfabCaptureSuppressionV1 = suppressionState\n\nexport function isCaptureSuppressed(): boolean {\n return suppressionState.depth > 0\n}\n\nexport function runWithCaptureSuppressed<T>(fn: () => T): T {\n suppressionState.depth += 1\n try {\n return fn()\n } finally {\n suppressionState.depth -= 1\n }\n}\n","/**\n * Emit a `console.warn` at most once per distinct `key` for the life of the\n * process.\n *\n * The SDK must NEVER crash a host app, so every failure on the user's path\n * degrades silently (a span is dropped, a call runs untraced, a payload is\n * stubbed). Silent is safe but undebuggable: a user who suddenly has no traces,\n * or sees `<unserializable>` in a span, has no signal as to why. A one-time\n * warning per distinct issue restores that signal without spamming the console\n * from a hot path.\n *\n * Keys should identify the specific degradation (e.g. include the traced\n * function key) so each distinct issue warns once, not just the first one seen.\n */\nconst warned = new Set<string>()\n\nexport function warn(message: string): void {\n try {\n console.warn(`[bitfab] ${message}`)\n } catch {\n // Logging must never crash the host app (e.g. a closed/replaced console).\n }\n}\n\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n warn(message)\n}\n\nexport function writeOnce(\n key: string,\n line: string,\n write: (line: string) => void = console.warn,\n): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n try {\n write(line)\n } catch {}\n}\n\n/** Test-only: clear the dedup set so a warning can fire again. */\nexport function _resetWarnOnce(): void {\n warned.clear()\n}\n","import {\n type AsyncLocalStorageLike,\n createAsyncLocalStorage,\n} from \"./asyncStorage.js\"\nimport { isCaptureSuppressed } from \"./captureSuppression.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nexport interface AutoTraceFunctionDefinition {\n id: string\n name: string\n file: string\n line: number\n column: number\n async?: boolean\n wrapper?: boolean\n baml?: boolean\n}\n\nexport interface AutoTraceNodeConfiguration {\n functionName: string\n name?: string\n type?: \"llm\" | \"agent\" | \"function\" | \"guardrail\" | \"handoff\" | \"custom\"\n defaultType?: boolean\n capture: boolean\n experimentId?: string\n /** @deprecated Use experimentId. */\n testRunId?: string\n mockOnReplay?: boolean\n replayReusable?: boolean\n // biome-ignore lint/suspicious/noExplicitAny: node finalizers receive the configured function's result, whose type is owned by the caller\n finalize?: (result: any) => unknown | Promise<unknown>\n}\n\nexport interface NestedTraceLink {\n traceFunctionKey: string\n traceId?: string\n rootSpanId?: string\n}\n\nexport interface SpanDetails {\n contexts: Record<string, unknown>[]\n prompt?: string\n}\n\nexport interface AutoTraceEntry {\n context: AutoTraceContext\n depth: number\n spanStack: unknown\n}\n\nexport interface AutoTraceContext {\n readonly traceFunctionKey: string\n invoke<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n fn: () => T,\n entry: AutoTraceEntry,\n spanDetails: SpanDetails,\n nodeConfiguration?: AutoTraceNodeConfiguration,\n ): T\n invokeNestedRoot<T>(\n name: string,\n functionName: string,\n inputs: unknown[],\n fn: () => T,\n entry: AutoTraceEntry,\n link: NestedTraceLink | undefined,\n spanDetails: SpanDetails,\n ): T\n}\n\ninterface AutoTraceRootFunction {\n name: string\n entering: boolean\n}\n\ninterface AutoTraceScope {\n entries: readonly AutoTraceEntry[]\n nodeConfiguration?: AutoTraceNodeConfiguration\n rootFunction?: AutoTraceRootFunction\n}\n\ninterface AutoTraceState {\n storage: AsyncLocalStorageLike<AutoTraceScope> | null\n browserScope: AutoTraceScope | undefined\n // Older SDK copies read this field when sharing the process-wide V4 state.\n capturePolicies: WeakMap<object, Map<string, ReadonlySet<string>>>\n activeRoots: number\n}\n\ninterface AutoTraceGlobal {\n __bitfabAutoTraceStateV4?: AutoTraceState\n __bitfab_auto_trace_transformed_v1__?: boolean\n}\n\ninterface AutoTraceAsyncGenerator {\n next(value?: unknown): Promise<IteratorResult<unknown, unknown>>\n return(value?: unknown): Promise<IteratorResult<unknown, unknown>>\n throw(error?: unknown): Promise<IteratorResult<unknown, unknown>>\n [Symbol.asyncIterator](): AutoTraceAsyncGenerator\n}\n\nconst autoTraceGlobal = globalThis as unknown as AutoTraceGlobal\nconst autoTraceState: AutoTraceState =\n autoTraceGlobal.__bitfabAutoTraceStateV4 ?? {\n storage: null,\n browserScope: undefined,\n capturePolicies: new WeakMap(),\n activeRoots: 0,\n }\nautoTraceGlobal.__bitfabAutoTraceStateV4 = autoTraceState\n\nfunction initializeAutoTraceStorage(): void {\n autoTraceState.storage ??= createAsyncLocalStorage<AutoTraceScope>()\n}\n\nfunction runWithAutoTraceScope<T>(scope: AutoTraceScope, fn: () => T): T {\n initializeAutoTraceStorage()\n if (autoTraceState.storage) {\n return autoTraceState.storage.run(scope, fn)\n }\n\n const previous = autoTraceState.browserScope\n autoTraceState.browserScope = scope\n try {\n return fn()\n } finally {\n autoTraceState.browserScope = previous\n }\n}\n\nexport function currentAutoTraceEntries(): readonly AutoTraceEntry[] {\n return currentAutoTraceScope()?.entries ?? []\n}\n\nfunction replaceEntry(\n entries: readonly AutoTraceEntry[],\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n): readonly AutoTraceEntry[] {\n return entries.map((entry) => (entry === previous ? updated : entry))\n}\n\nexport function runWithAutoTraceEntry<T>(\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n fn: () => T,\n): T {\n const result = runWithAutoTraceScope(\n { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },\n fn,\n )\n if (isAutoTraceAsyncGenerator(result)) {\n return wrapAutoTraceEntryAsyncGenerator(previous, updated, result) as T\n }\n return result\n}\n\nfunction wrapAutoTraceEntryAsyncGenerator(\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceScope(\n { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },\n () => source[method](value),\n )\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nexport function clearAutoTraceNodeConfiguration<T>(fn: () => T): T {\n return runWithAutoTraceScope({ entries: currentAutoTraceEntries() }, fn)\n}\n\nexport function runWithAutoTraceNodeConfiguration<T>(\n nodeConfiguration: AutoTraceNodeConfiguration,\n fn: () => T,\n): T {\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0) {\n return fn()\n }\n\n const result = runWithAutoTraceScope({ ...scope, nodeConfiguration }, fn)\n if (isAutoTraceAsyncGenerator(result)) {\n return wrapAutoTraceNodeAsyncGenerator(nodeConfiguration, result) as T\n }\n return result\n}\n\nexport function runAsAutoTraceRootFunction<T>(\n functionName: string,\n fn: () => T,\n): T {\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0 || functionName === \"\") {\n return fn()\n }\n const rootFunction: AutoTraceRootFunction = {\n name: functionName,\n entering: true,\n }\n try {\n return runWithAutoTraceScope({ ...scope, rootFunction }, fn)\n } finally {\n rootFunction.entering = false\n }\n}\n\nfunction isRootFunctionEntry(\n scope: AutoTraceScope,\n simpleName: string | undefined,\n): boolean {\n const rootFunction = scope.rootFunction\n if (rootFunction === undefined || !rootFunction.entering) {\n return false\n }\n rootFunction.entering = false\n return rootFunction.name === simpleName\n}\n\nconst SUBTREE_TRACING_DOCS_URL =\n \"https://docs.bitfab.ai/typescript-sdk#experimental-subtree-tracing\"\n\nfunction noteTransformedModule(): void {\n autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ = true\n}\n\nfunction transformInstalled(): boolean {\n return autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ === true\n}\n\nfunction runsOnNode(): boolean {\n return typeof process !== \"undefined\" && Boolean(process.versions?.node)\n}\n\nfunction closeAutoTraceRoot(): void {\n autoTraceState.activeRoots -= 1\n}\n\nfunction settleAutoTraceRoot(context: AutoTraceContext): void {\n closeAutoTraceRoot()\n if (transformInstalled() || !runsOnNode()) {\n return\n }\n warnOnce(\n \"auto-trace-transform-missing\",\n `trace root \"${context.traceFunctionKey}\" recorded only its own span. ` +\n \"No module in this build was compiled by @bitfab/sdk/transform, so calls \" +\n \"beneath the root were not discovered. Add the SDK's transform adapter \" +\n `to the server build: ${SUBTREE_TRACING_DOCS_URL}`,\n )\n}\n\nexport function runWithAutoTraceRootContext<T>(\n context: AutoTraceContext,\n spanStack: unknown,\n fn: () => T,\n): T {\n autoTraceState.activeRoots += 1\n const entries = [\n ...currentAutoTraceEntries(),\n { context, depth: 0, spanStack },\n ]\n let result: T\n try {\n result = runWithAutoTraceScope({ entries }, fn)\n } catch (error) {\n settleAutoTraceRoot(context)\n throw error\n }\n\n if (isAutoTraceAsyncGenerator(result)) {\n closeAutoTraceRoot()\n return wrapAutoTraceAsyncGenerator(context, spanStack, result) as T\n }\n\n if (result instanceof Promise) {\n return result.finally(() => {\n settleAutoTraceRoot(context)\n }) as T\n }\n\n settleAutoTraceRoot(context)\n return result\n}\n\nexport function invokeThroughAutoTraceEntries<T>(\n entries: readonly AutoTraceEntry[],\n step: (entry: AutoTraceEntry, next: () => T) => T,\n fn: () => T,\n): T {\n let run = fn\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const entry = entries[index] as AutoTraceEntry\n const next = run\n run = () => step(entry, next)\n }\n return run()\n}\n\nfunction isAutoTraceAsyncGenerator(\n value: unknown,\n): value is AutoTraceAsyncGenerator {\n if (value === null || typeof value !== \"object\") {\n return false\n }\n const candidate = value as Record<PropertyKey, unknown>\n return (\n typeof candidate.next === \"function\" &&\n typeof candidate.return === \"function\" &&\n typeof candidate.throw === \"function\" &&\n typeof candidate[Symbol.asyncIterator] === \"function\"\n )\n}\n\nfunction wrapAutoTraceAsyncGenerator(\n context: AutoTraceContext,\n spanStack: unknown,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceRootContext(context, spanStack, () => source[method](value))\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nfunction wrapAutoTraceNodeAsyncGenerator(\n nodeConfiguration: AutoTraceNodeConfiguration,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceNodeConfiguration(nodeConfiguration, () =>\n source[method](value),\n )\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nfunction shareFinalize(\n configuration: AutoTraceNodeConfiguration,\n): AutoTraceNodeConfiguration {\n const finalize = configuration.finalize\n if (finalize === undefined) {\n return configuration\n }\n let settled: Promise<unknown> | undefined\n return {\n ...configuration,\n finalize: (result: unknown) => {\n settled ??= Promise.resolve().then(() => finalize(result))\n return settled\n },\n }\n}\n\nexport function __bitfabAutoSpan<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n fn: () => T,\n): T {\n noteTransformedModule()\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0 || isCaptureSuppressed()) {\n return fn()\n }\n const nameParts = definition.name.split(\".\")\n const simpleName = nameParts[nameParts.length - 1]\n if (isRootFunctionEntry(scope, simpleName)) {\n return fn()\n }\n const nodeConfiguration =\n simpleName === scope.nodeConfiguration?.functionName\n ? shareFinalize(scope.nodeConfiguration)\n : undefined\n const spanDetails: SpanDetails = { contexts: [] }\n return invokeThroughAutoTraceEntries(\n scope.entries,\n (entry, next) =>\n entry.context.invoke(\n definition,\n inputs,\n next,\n entry,\n spanDetails,\n nodeConfiguration,\n ),\n fn,\n )\n}\n\n/**\n * Preserve a function's original call arguments for transform cases where\n * parameter bindings discard them, such as destructured arrow parameters.\n *\n * This helper is internal transform/runtime protocol. The proxy preserves the\n * target's callability, arity, async identity, and non-constructibility while\n * only allocating a trace closure beneath an active automatic trace root.\n *\n * @experimental The automatic tracing protocol may change.\n */\nexport function __bitfabAutoWrap<T extends (...args: never[]) => unknown>(\n definition: AutoTraceFunctionDefinition,\n fn: T,\n): T {\n noteTransformedModule()\n if (fn.name === \"\") {\n const nameParts = definition.name.split(\".\")\n const inferredName = nameParts[nameParts.length - 1]\n if (inferredName !== undefined) {\n Object.defineProperty(fn, \"name\", {\n configurable: true,\n value: inferredName,\n })\n }\n }\n\n const target = fn as unknown as (...args: unknown[]) => unknown\n return new Proxy(target, {\n apply(callTarget, thisArg, args) {\n if (!__bitfabAutoTraceActive()) {\n return Reflect.apply(callTarget, thisArg, args)\n }\n return __bitfabAutoSpan(definition, args, () =>\n Reflect.apply(callTarget, thisArg, args),\n )\n },\n }) as unknown as T\n}\n\n/**\n * Return whether the current call is inside an automatic trace root.\n *\n * Build transforms use this before allocating function metadata, captured\n * inputs, or an invocation closure. It is internal transform/runtime protocol,\n * not a supported application API.\n *\n * @experimental The automatic tracing protocol may change.\n */\nexport function __bitfabAutoTraceActive(): boolean {\n if (autoTraceState.activeRoots === 0 || isCaptureSuppressed()) {\n return false\n }\n return currentAutoTraceEntries().length > 0\n}\n\nfunction currentAutoTraceScope(): AutoTraceScope | undefined {\n initializeAutoTraceStorage()\n return autoTraceState.storage?.getStore() ?? autoTraceState.browserScope\n}\n\nexport function _resetAutoTraceTransformDetection(): void {\n autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ = undefined\n}\n"],"mappings":";AAmCA,IAAI,yBACF;AACF,IAAI,WAAW;AAUf,SAAgB,+BACd,KACM;CACN,IAAI,CAAC,wBACH,yBAAyB;CAE3B,WAAW;AACb;AAYA,SAAgB,+BAAqC;CACnD,IAAI,CAAC,wBACH,QAAQ,KACN,mFACF;AAEJ;AAEA,MAAa,qBACX,OAAO,YAAY,eAAe,QAAQ,UAAU;;AAKhD;;CAEE,CAAC,QAAQ,aAAa,CAAC,CAAC,KAAK,GAAG;CACjC,CACE,MACE,QAEK;CACJ,+BAA+B,IAAI,iBAAiB;AACtD,CACF,CAAC,CACA,YAAY,CAAC,CAAC,IACjB,QAAQ,QAAQ,EAAA,CACpB,WAAW;CACX,WAAW;AACb,CAAC;AAED,SAAgB,yBAAkC;CAChD,OAAO;AACT;AAEA,SAAgB,0BAA8D;CAC5E,OAAO,yBACF,IAAI,uBAAuB,IAC5B;AACN;;;ACjGA,MAAM,oBAAoB;AAC1B,MAAM,mBACJ,kBAAkB,gCAAgC,EAAE,OAAO,EAAE;AAC/D,kBAAkB,+BAA+B;AAEjD,SAAgB,sBAA+B;CAC7C,OAAO,iBAAiB,QAAQ;AAClC;AAEA,SAAgB,yBAA4B,IAAgB;CAC1D,iBAAiB,SAAS;CAC1B,IAAI;EACF,OAAO,GAAG;CACZ,UAAU;EACR,iBAAiB,SAAS;CAC5B;AACF;;;ACVA,MAAM,yBAAS,IAAI,IAAY;AAE/B,SAAgB,KAAK,SAAuB;CAC1C,IAAI;EACF,QAAQ,KAAK,YAAY,SAAS;CACpC,QAAQ,CAER;AACF;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AAM,GAAG;EAC3C,MAAM,eAAe,UAAU,UAAU,SAAS;EAClD,IAAI,iBAAiB,KAAA,GACnB,OAAO,eAAe,IAAI,QAAQ;GAChC,cAAc;GACd,OAAO;EACT,CAAC;CAEL;CAGA,OAAO,IAAI,MAAMA,IAAQ,EACvB,MAAM,YAAY,SAAS,MAAM;EAC/B,IAAI,CAAC,wBAAwB,GAC3B,OAAO,QAAQ,MAAM,YAAY,SAAS,IAAI;EAEhD,OAAO,iBAAiB,YAAY,YAClC,QAAQ,MAAM,YAAY,SAAS,IAAI,CACzC;CACF,EACF,CAAC;AACH;AAWA,SAAgB,0BAAmC;CACjD,IAAI,eAAe,gBAAgB,KAAK,oBAAoB,GAC1D,OAAO;CAET,OAAO,wBAAwB,CAAC,CAAC,SAAS;AAC5C;AAEA,SAAS,wBAAoD;CAC3D,2BAA2B;CAC3B,OAAO,eAAe,SAAS,SAAS,KAAK,eAAe;AAC9D;AAEA,SAAgB,oCAA0C;CACxD,gBAAgB,uCAAuC,KAAA;AACzD"}
@@ -1 +1 @@
1
- {"version":3,"file":"autoTrace-O40k8f5M.js","names":["target"],"sources":["../src/asyncStorage.ts","../src/captureSuppression.ts","../src/warnOnce.ts","../src/autoTrace.ts"],"sourcesContent":["/**\n * Shared AsyncLocalStorage loader.\n *\n * Provides two ways to initialize AsyncLocalStorage:\n *\n * 1. **Synchronous registration** (preferred for Node.js):\n * `asyncStorageNode.ts` calls `registerAsyncLocalStorageClass()` at module\n * evaluation time, so the class is available immediately - no async gap.\n * The `node.ts` entry point imports it before anything else.\n *\n * 2. **Async dynamic import** (fallback for the default entry point):\n * Loads `node:async_hooks` via a bundler-safe dynamic import. This is used\n * by the default `index.ts` entry point so the SDK works in browsers\n * (where the import silently fails) and in Node.js when imported via the\n * default entry point.\n *\n * ## Why the dynamic import looks like this\n *\n * We need to handle three environments:\n *\n * 1. **Pure Node.js** - `import(\"node:async_hooks\")` works natively.\n * 2. **Webpack/Turbopack (Next.js server)** - The bundler processes\n * `import()` calls at build time. The `webpackIgnore` magic comment tells\n * webpack (and turbopack) to emit a native `import()` call instead of\n * trying to resolve it, so Node.js handles it at runtime.\n * 3. **Browsers / Edge** - The `process.versions?.node` guard prevents\n * execution entirely. If it somehow runs, `.catch(() => {})` swallows\n * the failure.\n */\n\nexport interface AsyncLocalStorageLike<T> {\n getStore(): T | undefined\n run<R>(store: T, fn: () => R): R\n}\n\nlet AsyncLocalStorageClass: (new () => AsyncLocalStorageLike<unknown>) | null =\n null\nlet initDone = false\n\n/**\n * Register the AsyncLocalStorage class synchronously.\n *\n * Called by `asyncStorageNode.ts` at module evaluation time so the class\n * is available before any span is created - no async gap, no race condition.\n *\n * Safe to call multiple times; subsequent calls are no-ops.\n */\nexport function registerAsyncLocalStorageClass(\n cls: new () => AsyncLocalStorageLike<unknown>,\n): void {\n if (!AsyncLocalStorageClass) {\n AsyncLocalStorageClass = cls\n }\n initDone = true\n}\n\n/**\n * Assert that AsyncLocalStorage was registered successfully.\n *\n * Called by `node.ts` after importing `asyncStorageNode.ts` to catch\n * import-order bugs at startup rather than silently degrading to the\n * browser fallback (flat spans with no nesting).\n *\n * This should ONLY be called from the Node.js entry point where we\n * know `node:async_hooks` must be available.\n */\nexport function assertAsyncStorageRegistered(): void {\n if (!AsyncLocalStorageClass) {\n console.warn(\n \"Bitfab: AsyncLocalStorage not available - nested span context will not propagate.\",\n )\n }\n}\n\nexport const asyncStorageReady: Promise<void> = (\n typeof process !== \"undefined\" && process.versions?.node\n ? // The join trick hides \"node:async_hooks\" from static analysis so\n // bundlers that ban Node.js built-ins don't fail at build time.\n // webpackIgnore tells webpack/turbopack to emit a native import()\n // so Node.js can resolve the module at runtime.\n import(\n /* webpackIgnore: true */\n [\"node\", \"async_hooks\"].join(\":\")\n )\n .then(\n (mod: {\n AsyncLocalStorage: new () => AsyncLocalStorageLike<unknown>\n }) => {\n registerAsyncLocalStorageClass(mod.AsyncLocalStorage)\n },\n )\n .catch(() => {})\n : Promise.resolve()\n).then(() => {\n initDone = true\n})\n\nexport function isAsyncStorageInitDone(): boolean {\n return initDone\n}\n\nexport function createAsyncLocalStorage<T>(): AsyncLocalStorageLike<T> | null {\n return AsyncLocalStorageClass\n ? (new AsyncLocalStorageClass() as AsyncLocalStorageLike<T>)\n : null\n}\n","interface CaptureSuppressionState {\n depth: number\n}\n\ninterface CaptureSuppressionGlobal {\n __bitfabCaptureSuppressionV1?: CaptureSuppressionState\n}\n\nconst suppressionGlobal = globalThis as unknown as CaptureSuppressionGlobal\nconst suppressionState: CaptureSuppressionState =\n suppressionGlobal.__bitfabCaptureSuppressionV1 ?? { depth: 0 }\nsuppressionGlobal.__bitfabCaptureSuppressionV1 = suppressionState\n\nexport function isCaptureSuppressed(): boolean {\n return suppressionState.depth > 0\n}\n\nexport function runWithCaptureSuppressed<T>(fn: () => T): T {\n suppressionState.depth += 1\n try {\n return fn()\n } finally {\n suppressionState.depth -= 1\n }\n}\n","/**\n * Emit a `console.warn` at most once per distinct `key` for the life of the\n * process.\n *\n * The SDK must NEVER crash a host app, so every failure on the user's path\n * degrades silently (a span is dropped, a call runs untraced, a payload is\n * stubbed). Silent is safe but undebuggable: a user who suddenly has no traces,\n * or sees `<unserializable>` in a span, has no signal as to why. A one-time\n * warning per distinct issue restores that signal without spamming the console\n * from a hot path.\n *\n * Keys should identify the specific degradation (e.g. include the traced\n * function key) so each distinct issue warns once, not just the first one seen.\n */\nconst warned = new Set<string>()\n\nexport function warn(message: string): void {\n try {\n console.warn(`[bitfab] ${message}`)\n } catch {\n // Logging must never crash the host app (e.g. a closed/replaced console).\n }\n}\n\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n warn(message)\n}\n\nexport function writeOnce(\n key: string,\n line: string,\n write: (line: string) => void = console.warn,\n): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n try {\n write(line)\n } catch {}\n}\n\n/** Test-only: clear the dedup set so a warning can fire again. */\nexport function _resetWarnOnce(): void {\n warned.clear()\n}\n","import {\n type AsyncLocalStorageLike,\n createAsyncLocalStorage,\n} from \"./asyncStorage.js\"\nimport { isCaptureSuppressed } from \"./captureSuppression.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nexport interface AutoTraceFunctionDefinition {\n id: string\n name: string\n file: string\n line: number\n column: number\n async?: boolean\n wrapper?: boolean\n}\n\nexport interface AutoTraceNodeConfiguration {\n functionName: string\n name?: string\n type?: \"llm\" | \"agent\" | \"function\" | \"guardrail\" | \"handoff\" | \"custom\"\n capture: boolean\n experimentId?: string\n /** @deprecated Use experimentId. */\n testRunId?: string\n mockOnReplay?: boolean\n replayReusable?: boolean\n // biome-ignore lint/suspicious/noExplicitAny: node finalizers receive the configured function's result, whose type is owned by the caller\n finalize?: (result: any) => unknown | Promise<unknown>\n}\n\nexport interface NestedTraceLink {\n traceFunctionKey: string\n traceId?: string\n rootSpanId?: string\n}\n\nexport interface SpanDetails {\n contexts: Record<string, unknown>[]\n prompt?: string\n}\n\nexport interface AutoTraceEntry {\n context: AutoTraceContext\n depth: number\n spanStack: unknown\n}\n\nexport interface AutoTraceContext {\n readonly traceFunctionKey: string\n invoke<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n fn: () => T,\n entry: AutoTraceEntry,\n spanDetails: SpanDetails,\n nodeConfiguration?: AutoTraceNodeConfiguration,\n ): T\n invokeNestedRoot<T>(\n name: string,\n functionName: string,\n inputs: unknown[],\n fn: () => T,\n entry: AutoTraceEntry,\n link: NestedTraceLink | undefined,\n spanDetails: SpanDetails,\n ): T\n}\n\ninterface AutoTraceRootFunction {\n name: string\n entering: boolean\n}\n\ninterface AutoTraceScope {\n entries: readonly AutoTraceEntry[]\n nodeConfiguration?: AutoTraceNodeConfiguration\n rootFunction?: AutoTraceRootFunction\n}\n\ninterface AutoTraceState {\n storage: AsyncLocalStorageLike<AutoTraceScope> | null\n browserScope: AutoTraceScope | undefined\n // Older SDK copies read this field when sharing the process-wide V4 state.\n capturePolicies: WeakMap<object, Map<string, ReadonlySet<string>>>\n activeRoots: number\n}\n\ninterface AutoTraceGlobal {\n __bitfabAutoTraceStateV4?: AutoTraceState\n __bitfab_auto_trace_transformed_v1__?: boolean\n}\n\ninterface AutoTraceAsyncGenerator {\n next(value?: unknown): Promise<IteratorResult<unknown, unknown>>\n return(value?: unknown): Promise<IteratorResult<unknown, unknown>>\n throw(error?: unknown): Promise<IteratorResult<unknown, unknown>>\n [Symbol.asyncIterator](): AutoTraceAsyncGenerator\n}\n\nconst autoTraceGlobal = globalThis as unknown as AutoTraceGlobal\nconst autoTraceState: AutoTraceState =\n autoTraceGlobal.__bitfabAutoTraceStateV4 ?? {\n storage: null,\n browserScope: undefined,\n capturePolicies: new WeakMap(),\n activeRoots: 0,\n }\nautoTraceGlobal.__bitfabAutoTraceStateV4 = autoTraceState\n\nfunction initializeAutoTraceStorage(): void {\n autoTraceState.storage ??= createAsyncLocalStorage<AutoTraceScope>()\n}\n\nfunction runWithAutoTraceScope<T>(scope: AutoTraceScope, fn: () => T): T {\n initializeAutoTraceStorage()\n if (autoTraceState.storage) {\n return autoTraceState.storage.run(scope, fn)\n }\n\n const previous = autoTraceState.browserScope\n autoTraceState.browserScope = scope\n try {\n return fn()\n } finally {\n autoTraceState.browserScope = previous\n }\n}\n\nexport function currentAutoTraceEntries(): readonly AutoTraceEntry[] {\n return currentAutoTraceScope()?.entries ?? []\n}\n\nfunction replaceEntry(\n entries: readonly AutoTraceEntry[],\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n): readonly AutoTraceEntry[] {\n return entries.map((entry) => (entry === previous ? updated : entry))\n}\n\nexport function runWithAutoTraceEntry<T>(\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n fn: () => T,\n): T {\n const result = runWithAutoTraceScope(\n { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },\n fn,\n )\n if (isAutoTraceAsyncGenerator(result)) {\n return wrapAutoTraceEntryAsyncGenerator(previous, updated, result) as T\n }\n return result\n}\n\nfunction wrapAutoTraceEntryAsyncGenerator(\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceScope(\n { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },\n () => source[method](value),\n )\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nexport function clearAutoTraceNodeConfiguration<T>(fn: () => T): T {\n return runWithAutoTraceScope({ entries: currentAutoTraceEntries() }, fn)\n}\n\nexport function runWithAutoTraceNodeConfiguration<T>(\n nodeConfiguration: AutoTraceNodeConfiguration,\n fn: () => T,\n): T {\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0) {\n return fn()\n }\n\n const result = runWithAutoTraceScope({ ...scope, nodeConfiguration }, fn)\n if (isAutoTraceAsyncGenerator(result)) {\n return wrapAutoTraceNodeAsyncGenerator(nodeConfiguration, result) as T\n }\n return result\n}\n\nexport function runAsAutoTraceRootFunction<T>(\n functionName: string,\n fn: () => T,\n): T {\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0 || functionName === \"\") {\n return fn()\n }\n const rootFunction: AutoTraceRootFunction = {\n name: functionName,\n entering: true,\n }\n try {\n return runWithAutoTraceScope({ ...scope, rootFunction }, fn)\n } finally {\n rootFunction.entering = false\n }\n}\n\nfunction isRootFunctionEntry(\n scope: AutoTraceScope,\n simpleName: string | undefined,\n): boolean {\n const rootFunction = scope.rootFunction\n if (rootFunction === undefined || !rootFunction.entering) {\n return false\n }\n rootFunction.entering = false\n return rootFunction.name === simpleName\n}\n\nconst SUBTREE_TRACING_DOCS_URL =\n \"https://docs.bitfab.ai/typescript-sdk#experimental-subtree-tracing\"\n\nfunction noteTransformedModule(): void {\n autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ = true\n}\n\nfunction transformInstalled(): boolean {\n return autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ === true\n}\n\nfunction runsOnNode(): boolean {\n return typeof process !== \"undefined\" && Boolean(process.versions?.node)\n}\n\nfunction closeAutoTraceRoot(): void {\n autoTraceState.activeRoots -= 1\n}\n\nfunction settleAutoTraceRoot(context: AutoTraceContext): void {\n closeAutoTraceRoot()\n if (transformInstalled() || !runsOnNode()) {\n return\n }\n warnOnce(\n \"auto-trace-transform-missing\",\n `trace root \"${context.traceFunctionKey}\" recorded only its own span. ` +\n \"No module in this build was compiled by @bitfab/sdk/transform, so calls \" +\n \"beneath the root were not discovered. Add the SDK's transform adapter \" +\n `to the server build: ${SUBTREE_TRACING_DOCS_URL}`,\n )\n}\n\nexport function runWithAutoTraceRootContext<T>(\n context: AutoTraceContext,\n spanStack: unknown,\n fn: () => T,\n): T {\n autoTraceState.activeRoots += 1\n const entries = [\n ...currentAutoTraceEntries(),\n { context, depth: 0, spanStack },\n ]\n let result: T\n try {\n result = runWithAutoTraceScope({ entries }, fn)\n } catch (error) {\n settleAutoTraceRoot(context)\n throw error\n }\n\n if (isAutoTraceAsyncGenerator(result)) {\n closeAutoTraceRoot()\n return wrapAutoTraceAsyncGenerator(context, spanStack, result) as T\n }\n\n if (result instanceof Promise) {\n return result.finally(() => {\n settleAutoTraceRoot(context)\n }) as T\n }\n\n settleAutoTraceRoot(context)\n return result\n}\n\nexport function invokeThroughAutoTraceEntries<T>(\n entries: readonly AutoTraceEntry[],\n step: (entry: AutoTraceEntry, next: () => T) => T,\n fn: () => T,\n): T {\n let run = fn\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const entry = entries[index] as AutoTraceEntry\n const next = run\n run = () => step(entry, next)\n }\n return run()\n}\n\nfunction isAutoTraceAsyncGenerator(\n value: unknown,\n): value is AutoTraceAsyncGenerator {\n if (value === null || typeof value !== \"object\") {\n return false\n }\n const candidate = value as Record<PropertyKey, unknown>\n return (\n typeof candidate.next === \"function\" &&\n typeof candidate.return === \"function\" &&\n typeof candidate.throw === \"function\" &&\n typeof candidate[Symbol.asyncIterator] === \"function\"\n )\n}\n\nfunction wrapAutoTraceAsyncGenerator(\n context: AutoTraceContext,\n spanStack: unknown,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceRootContext(context, spanStack, () => source[method](value))\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nfunction wrapAutoTraceNodeAsyncGenerator(\n nodeConfiguration: AutoTraceNodeConfiguration,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceNodeConfiguration(nodeConfiguration, () =>\n source[method](value),\n )\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nfunction shareFinalize(\n configuration: AutoTraceNodeConfiguration,\n): AutoTraceNodeConfiguration {\n const finalize = configuration.finalize\n if (finalize === undefined) {\n return configuration\n }\n let settled: Promise<unknown> | undefined\n return {\n ...configuration,\n finalize: (result: unknown) => {\n settled ??= Promise.resolve().then(() => finalize(result))\n return settled\n },\n }\n}\n\nexport function __bitfabAutoSpan<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n fn: () => T,\n): T {\n noteTransformedModule()\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0 || isCaptureSuppressed()) {\n return fn()\n }\n const nameParts = definition.name.split(\".\")\n const simpleName = nameParts[nameParts.length - 1]\n if (isRootFunctionEntry(scope, simpleName)) {\n return fn()\n }\n const nodeConfiguration =\n simpleName === scope.nodeConfiguration?.functionName\n ? shareFinalize(scope.nodeConfiguration)\n : undefined\n const spanDetails: SpanDetails = { contexts: [] }\n return invokeThroughAutoTraceEntries(\n scope.entries,\n (entry, next) =>\n entry.context.invoke(\n definition,\n inputs,\n next,\n entry,\n spanDetails,\n nodeConfiguration,\n ),\n fn,\n )\n}\n\n/**\n * Preserve a function's original call arguments for transform cases where\n * parameter bindings discard them, such as destructured arrow parameters.\n *\n * This helper is internal transform/runtime protocol. The proxy preserves the\n * target's callability, arity, async identity, and non-constructibility while\n * only allocating a trace closure beneath an active automatic trace root.\n *\n * @experimental The automatic tracing protocol may change.\n */\nexport function __bitfabAutoWrap<T extends (...args: never[]) => unknown>(\n definition: AutoTraceFunctionDefinition,\n fn: T,\n): T {\n noteTransformedModule()\n if (fn.name === \"\") {\n const nameParts = definition.name.split(\".\")\n const inferredName = nameParts[nameParts.length - 1]\n if (inferredName !== undefined) {\n Object.defineProperty(fn, \"name\", {\n configurable: true,\n value: inferredName,\n })\n }\n }\n\n const target = fn as unknown as (...args: unknown[]) => unknown\n return new Proxy(target, {\n apply(callTarget, thisArg, args) {\n if (!__bitfabAutoTraceActive()) {\n return Reflect.apply(callTarget, thisArg, args)\n }\n return __bitfabAutoSpan(definition, args, () =>\n Reflect.apply(callTarget, thisArg, args),\n )\n },\n }) as unknown as T\n}\n\n/**\n * Return whether the current call is inside an automatic trace root.\n *\n * Build transforms use this before allocating function metadata, captured\n * inputs, or an invocation closure. It is internal transform/runtime protocol,\n * not a supported application API.\n *\n * @experimental The automatic tracing protocol may change.\n */\nexport function __bitfabAutoTraceActive(): boolean {\n if (autoTraceState.activeRoots === 0 || isCaptureSuppressed()) {\n return false\n }\n return currentAutoTraceEntries().length > 0\n}\n\nfunction currentAutoTraceScope(): AutoTraceScope | undefined {\n initializeAutoTraceStorage()\n return autoTraceState.storage?.getStore() ?? autoTraceState.browserScope\n}\n\nexport function _resetAutoTraceTransformDetection(): void {\n autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ = undefined\n}\n"],"mappings":";AAmCA,IAAI,yBACF;AACF,IAAI,WAAW;AAUf,SAAgB,+BACd,KACM;CACN,IAAI,CAAC,wBACH,yBAAyB;CAE3B,WAAW;AACb;AAYA,SAAgB,+BAAqC;CACnD,IAAI,CAAC,wBACH,QAAQ,KACN,mFACF;AAEJ;AAEA,MAAa,qBACX,OAAO,YAAY,eAAe,QAAQ,UAAU;;AAKhD;;CAEE,CAAC,QAAQ,aAAa,CAAC,CAAC,KAAK,GAAG;CACjC,CACE,MACE,QAEK;CACJ,+BAA+B,IAAI,iBAAiB;AACtD,CACF,CAAC,CACA,YAAY,CAAC,CAAC,IACjB,QAAQ,QAAQ,EAAA,CACpB,WAAW;CACX,WAAW;AACb,CAAC;AAED,SAAgB,yBAAkC;CAChD,OAAO;AACT;AAEA,SAAgB,0BAA8D;CAC5E,OAAO,yBACF,IAAI,uBAAuB,IAC5B;AACN;;;ACjGA,MAAM,oBAAoB;AAC1B,MAAM,mBACJ,kBAAkB,gCAAgC,EAAE,OAAO,EAAE;AAC/D,kBAAkB,+BAA+B;AAEjD,SAAgB,sBAA+B;CAC7C,OAAO,iBAAiB,QAAQ;AAClC;AAEA,SAAgB,yBAA4B,IAAgB;CAC1D,iBAAiB,SAAS;CAC1B,IAAI;EACF,OAAO,GAAG;CACZ,UAAU;EACR,iBAAiB,SAAS;CAC5B;AACF;;;ACVA,MAAM,yBAAS,IAAI,IAAY;AAE/B,SAAgB,KAAK,SAAuB;CAC1C,IAAI;EACF,QAAQ,KAAK,YAAY,SAAS;CACpC,QAAQ,CAER;AACF;AAEA,SAAgB,SAAS,KAAa,SAAuB;CAC3D,IAAI,OAAO,IAAI,GAAG,GAChB;CAEF,OAAO,IAAI,GAAG;CACd,KAAK,OAAO;AACd;AAEA,S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OAAO;EACT,CAAC;CAEL;CAGA,OAAO,IAAI,MAAMA,IAAQ,EACvB,MAAM,YAAY,SAAS,MAAM;EAC/B,IAAI,CAAC,wBAAwB,GAC3B,OAAO,QAAQ,MAAM,YAAY,SAAS,IAAI;EAEhD,OAAO,iBAAiB,YAAY,YAClC,QAAQ,MAAM,YAAY,SAAS,IAAI,CACzC;CACF,EACF,CAAC;AACH;AAWA,SAAgB,0BAAmC;CACjD,IAAI,eAAe,gBAAgB,KAAK,oBAAoB,GAC1D,OAAO;CAET,OAAO,wBAAwB,CAAC,CAAC,SAAS;AAC5C;AAEA,SAAS,wBAAoD;CAC3D,2BAA2B;CAC3B,OAAO,eAAe,SAAS,SAAS,KAAK,eAAe;AAC9D;AAEA,SAAgB,oCAA0C;CACxD,gBAAgB,uCAAuC,KAAA;AACzD"}
1
+ {"version":3,"file":"autoTrace-O40k8f5M.js","names":["target"],"sources":["../src/asyncStorage.ts","../src/captureSuppression.ts","../src/warnOnce.ts","../src/autoTrace.ts"],"sourcesContent":["/**\n * Shared AsyncLocalStorage loader.\n *\n * Provides two ways to initialize AsyncLocalStorage:\n *\n * 1. **Synchronous registration** (preferred for Node.js):\n * `asyncStorageNode.ts` calls `registerAsyncLocalStorageClass()` at module\n * evaluation time, so the class is available immediately - no async gap.\n * The `node.ts` entry point imports it before anything else.\n *\n * 2. **Async dynamic import** (fallback for the default entry point):\n * Loads `node:async_hooks` via a bundler-safe dynamic import. This is used\n * by the default `index.ts` entry point so the SDK works in browsers\n * (where the import silently fails) and in Node.js when imported via the\n * default entry point.\n *\n * ## Why the dynamic import looks like this\n *\n * We need to handle three environments:\n *\n * 1. **Pure Node.js** - `import(\"node:async_hooks\")` works natively.\n * 2. **Webpack/Turbopack (Next.js server)** - The bundler processes\n * `import()` calls at build time. The `webpackIgnore` magic comment tells\n * webpack (and turbopack) to emit a native `import()` call instead of\n * trying to resolve it, so Node.js handles it at runtime.\n * 3. **Browsers / Edge** - The `process.versions?.node` guard prevents\n * execution entirely. If it somehow runs, `.catch(() => {})` swallows\n * the failure.\n */\n\nexport interface AsyncLocalStorageLike<T> {\n getStore(): T | undefined\n run<R>(store: T, fn: () => R): R\n}\n\nlet AsyncLocalStorageClass: (new () => AsyncLocalStorageLike<unknown>) | null =\n null\nlet initDone = false\n\n/**\n * Register the AsyncLocalStorage class synchronously.\n *\n * Called by `asyncStorageNode.ts` at module evaluation time so the class\n * is available before any span is created - no async gap, no race condition.\n *\n * Safe to call multiple times; subsequent calls are no-ops.\n */\nexport function registerAsyncLocalStorageClass(\n cls: new () => AsyncLocalStorageLike<unknown>,\n): void {\n if (!AsyncLocalStorageClass) {\n AsyncLocalStorageClass = cls\n }\n initDone = true\n}\n\n/**\n * Assert that AsyncLocalStorage was registered successfully.\n *\n * Called by `node.ts` after importing `asyncStorageNode.ts` to catch\n * import-order bugs at startup rather than silently degrading to the\n * browser fallback (flat spans with no nesting).\n *\n * This should ONLY be called from the Node.js entry point where we\n * know `node:async_hooks` must be available.\n */\nexport function assertAsyncStorageRegistered(): void {\n if (!AsyncLocalStorageClass) {\n console.warn(\n \"Bitfab: AsyncLocalStorage not available - nested span context will not propagate.\",\n )\n }\n}\n\nexport const asyncStorageReady: Promise<void> = (\n typeof process !== \"undefined\" && process.versions?.node\n ? // The join trick hides \"node:async_hooks\" from static analysis so\n // bundlers that ban Node.js built-ins don't fail at build time.\n // webpackIgnore tells webpack/turbopack to emit a native import()\n // so Node.js can resolve the module at runtime.\n import(\n /* webpackIgnore: true */\n [\"node\", \"async_hooks\"].join(\":\")\n )\n .then(\n (mod: {\n AsyncLocalStorage: new () => AsyncLocalStorageLike<unknown>\n }) => {\n registerAsyncLocalStorageClass(mod.AsyncLocalStorage)\n },\n )\n .catch(() => {})\n : Promise.resolve()\n).then(() => {\n initDone = true\n})\n\nexport function isAsyncStorageInitDone(): boolean {\n return initDone\n}\n\nexport function createAsyncLocalStorage<T>(): AsyncLocalStorageLike<T> | null {\n return AsyncLocalStorageClass\n ? (new AsyncLocalStorageClass() as AsyncLocalStorageLike<T>)\n : null\n}\n","interface CaptureSuppressionState {\n depth: number\n}\n\ninterface CaptureSuppressionGlobal {\n __bitfabCaptureSuppressionV1?: CaptureSuppressionState\n}\n\nconst suppressionGlobal = globalThis as unknown as CaptureSuppressionGlobal\nconst suppressionState: CaptureSuppressionState =\n suppressionGlobal.__bitfabCaptureSuppressionV1 ?? { depth: 0 }\nsuppressionGlobal.__bitfabCaptureSuppressionV1 = suppressionState\n\nexport function isCaptureSuppressed(): boolean {\n return suppressionState.depth > 0\n}\n\nexport function runWithCaptureSuppressed<T>(fn: () => T): T {\n suppressionState.depth += 1\n try {\n return fn()\n } finally {\n suppressionState.depth -= 1\n }\n}\n","/**\n * Emit a `console.warn` at most once per distinct `key` for the life of the\n * process.\n *\n * The SDK must NEVER crash a host app, so every failure on the user's path\n * degrades silently (a span is dropped, a call runs untraced, a payload is\n * stubbed). Silent is safe but undebuggable: a user who suddenly has no traces,\n * or sees `<unserializable>` in a span, has no signal as to why. A one-time\n * warning per distinct issue restores that signal without spamming the console\n * from a hot path.\n *\n * Keys should identify the specific degradation (e.g. include the traced\n * function key) so each distinct issue warns once, not just the first one seen.\n */\nconst warned = new Set<string>()\n\nexport function warn(message: string): void {\n try {\n console.warn(`[bitfab] ${message}`)\n } catch {\n // Logging must never crash the host app (e.g. a closed/replaced console).\n }\n}\n\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n warn(message)\n}\n\nexport function writeOnce(\n key: string,\n line: string,\n write: (line: string) => void = console.warn,\n): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n try {\n write(line)\n } catch {}\n}\n\n/** Test-only: clear the dedup set so a warning can fire again. */\nexport function _resetWarnOnce(): void {\n warned.clear()\n}\n","import {\n type AsyncLocalStorageLike,\n createAsyncLocalStorage,\n} from \"./asyncStorage.js\"\nimport { isCaptureSuppressed } from \"./captureSuppression.js\"\nimport { warnOnce } from \"./warnOnce.js\"\n\nexport interface AutoTraceFunctionDefinition {\n id: string\n name: string\n file: string\n line: number\n column: number\n async?: boolean\n wrapper?: boolean\n baml?: boolean\n}\n\nexport interface AutoTraceNodeConfiguration {\n functionName: string\n name?: string\n type?: \"llm\" | \"agent\" | \"function\" | \"guardrail\" | \"handoff\" | \"custom\"\n defaultType?: boolean\n capture: boolean\n experimentId?: string\n /** @deprecated Use experimentId. */\n testRunId?: string\n mockOnReplay?: boolean\n replayReusable?: boolean\n // biome-ignore lint/suspicious/noExplicitAny: node finalizers receive the configured function's result, whose type is owned by the caller\n finalize?: (result: any) => unknown | Promise<unknown>\n}\n\nexport interface NestedTraceLink {\n traceFunctionKey: string\n traceId?: string\n rootSpanId?: string\n}\n\nexport interface SpanDetails {\n contexts: Record<string, unknown>[]\n prompt?: string\n}\n\nexport interface AutoTraceEntry {\n context: AutoTraceContext\n depth: number\n spanStack: unknown\n}\n\nexport interface AutoTraceContext {\n readonly traceFunctionKey: string\n invoke<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n fn: () => T,\n entry: AutoTraceEntry,\n spanDetails: SpanDetails,\n nodeConfiguration?: AutoTraceNodeConfiguration,\n ): T\n invokeNestedRoot<T>(\n name: string,\n functionName: string,\n inputs: unknown[],\n fn: () => T,\n entry: AutoTraceEntry,\n link: NestedTraceLink | undefined,\n spanDetails: SpanDetails,\n ): T\n}\n\ninterface AutoTraceRootFunction {\n name: string\n entering: boolean\n}\n\ninterface AutoTraceScope {\n entries: readonly AutoTraceEntry[]\n nodeConfiguration?: AutoTraceNodeConfiguration\n rootFunction?: AutoTraceRootFunction\n}\n\ninterface AutoTraceState {\n storage: AsyncLocalStorageLike<AutoTraceScope> | null\n browserScope: AutoTraceScope | undefined\n // Older SDK copies read this field when sharing the process-wide V4 state.\n capturePolicies: WeakMap<object, Map<string, ReadonlySet<string>>>\n activeRoots: number\n}\n\ninterface AutoTraceGlobal {\n __bitfabAutoTraceStateV4?: AutoTraceState\n __bitfab_auto_trace_transformed_v1__?: boolean\n}\n\ninterface AutoTraceAsyncGenerator {\n next(value?: unknown): Promise<IteratorResult<unknown, unknown>>\n return(value?: unknown): Promise<IteratorResult<unknown, unknown>>\n throw(error?: unknown): Promise<IteratorResult<unknown, unknown>>\n [Symbol.asyncIterator](): AutoTraceAsyncGenerator\n}\n\nconst autoTraceGlobal = globalThis as unknown as AutoTraceGlobal\nconst autoTraceState: AutoTraceState =\n autoTraceGlobal.__bitfabAutoTraceStateV4 ?? {\n storage: null,\n browserScope: undefined,\n capturePolicies: new WeakMap(),\n activeRoots: 0,\n }\nautoTraceGlobal.__bitfabAutoTraceStateV4 = autoTraceState\n\nfunction initializeAutoTraceStorage(): void {\n autoTraceState.storage ??= createAsyncLocalStorage<AutoTraceScope>()\n}\n\nfunction runWithAutoTraceScope<T>(scope: AutoTraceScope, fn: () => T): T {\n initializeAutoTraceStorage()\n if (autoTraceState.storage) {\n return autoTraceState.storage.run(scope, fn)\n }\n\n const previous = autoTraceState.browserScope\n autoTraceState.browserScope = scope\n try {\n return fn()\n } finally {\n autoTraceState.browserScope = previous\n }\n}\n\nexport function currentAutoTraceEntries(): readonly AutoTraceEntry[] {\n return currentAutoTraceScope()?.entries ?? []\n}\n\nfunction replaceEntry(\n entries: readonly AutoTraceEntry[],\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n): readonly AutoTraceEntry[] {\n return entries.map((entry) => (entry === previous ? updated : entry))\n}\n\nexport function runWithAutoTraceEntry<T>(\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n fn: () => T,\n): T {\n const result = runWithAutoTraceScope(\n { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },\n fn,\n )\n if (isAutoTraceAsyncGenerator(result)) {\n return wrapAutoTraceEntryAsyncGenerator(previous, updated, result) as T\n }\n return result\n}\n\nfunction wrapAutoTraceEntryAsyncGenerator(\n previous: AutoTraceEntry,\n updated: AutoTraceEntry,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceScope(\n { entries: replaceEntry(currentAutoTraceEntries(), previous, updated) },\n () => source[method](value),\n )\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nexport function clearAutoTraceNodeConfiguration<T>(fn: () => T): T {\n return runWithAutoTraceScope({ entries: currentAutoTraceEntries() }, fn)\n}\n\nexport function runWithAutoTraceNodeConfiguration<T>(\n nodeConfiguration: AutoTraceNodeConfiguration,\n fn: () => T,\n): T {\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0) {\n return fn()\n }\n\n const result = runWithAutoTraceScope({ ...scope, nodeConfiguration }, fn)\n if (isAutoTraceAsyncGenerator(result)) {\n return wrapAutoTraceNodeAsyncGenerator(nodeConfiguration, result) as T\n }\n return result\n}\n\nexport function runAsAutoTraceRootFunction<T>(\n functionName: string,\n fn: () => T,\n): T {\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0 || functionName === \"\") {\n return fn()\n }\n const rootFunction: AutoTraceRootFunction = {\n name: functionName,\n entering: true,\n }\n try {\n return runWithAutoTraceScope({ ...scope, rootFunction }, fn)\n } finally {\n rootFunction.entering = false\n }\n}\n\nfunction isRootFunctionEntry(\n scope: AutoTraceScope,\n simpleName: string | undefined,\n): boolean {\n const rootFunction = scope.rootFunction\n if (rootFunction === undefined || !rootFunction.entering) {\n return false\n }\n rootFunction.entering = false\n return rootFunction.name === simpleName\n}\n\nconst SUBTREE_TRACING_DOCS_URL =\n \"https://docs.bitfab.ai/typescript-sdk#experimental-subtree-tracing\"\n\nfunction noteTransformedModule(): void {\n autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ = true\n}\n\nfunction transformInstalled(): boolean {\n return autoTraceGlobal.__bitfab_auto_trace_transformed_v1__ === true\n}\n\nfunction runsOnNode(): boolean {\n return typeof process !== \"undefined\" && Boolean(process.versions?.node)\n}\n\nfunction closeAutoTraceRoot(): void {\n autoTraceState.activeRoots -= 1\n}\n\nfunction settleAutoTraceRoot(context: AutoTraceContext): void {\n closeAutoTraceRoot()\n if (transformInstalled() || !runsOnNode()) {\n return\n }\n warnOnce(\n \"auto-trace-transform-missing\",\n `trace root \"${context.traceFunctionKey}\" recorded only its own span. ` +\n \"No module in this build was compiled by @bitfab/sdk/transform, so calls \" +\n \"beneath the root were not discovered. Add the SDK's transform adapter \" +\n `to the server build: ${SUBTREE_TRACING_DOCS_URL}`,\n )\n}\n\nexport function runWithAutoTraceRootContext<T>(\n context: AutoTraceContext,\n spanStack: unknown,\n fn: () => T,\n): T {\n autoTraceState.activeRoots += 1\n const entries = [\n ...currentAutoTraceEntries(),\n { context, depth: 0, spanStack },\n ]\n let result: T\n try {\n result = runWithAutoTraceScope({ entries }, fn)\n } catch (error) {\n settleAutoTraceRoot(context)\n throw error\n }\n\n if (isAutoTraceAsyncGenerator(result)) {\n closeAutoTraceRoot()\n return wrapAutoTraceAsyncGenerator(context, spanStack, result) as T\n }\n\n if (result instanceof Promise) {\n return result.finally(() => {\n settleAutoTraceRoot(context)\n }) as T\n }\n\n settleAutoTraceRoot(context)\n return result\n}\n\nexport function invokeThroughAutoTraceEntries<T>(\n entries: readonly AutoTraceEntry[],\n step: (entry: AutoTraceEntry, next: () => T) => T,\n fn: () => T,\n): T {\n let run = fn\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const entry = entries[index] as AutoTraceEntry\n const next = run\n run = () => step(entry, next)\n }\n return run()\n}\n\nfunction isAutoTraceAsyncGenerator(\n value: unknown,\n): value is AutoTraceAsyncGenerator {\n if (value === null || typeof value !== \"object\") {\n return false\n }\n const candidate = value as Record<PropertyKey, unknown>\n return (\n typeof candidate.next === \"function\" &&\n typeof candidate.return === \"function\" &&\n typeof candidate.throw === \"function\" &&\n typeof candidate[Symbol.asyncIterator] === \"function\"\n )\n}\n\nfunction wrapAutoTraceAsyncGenerator(\n context: AutoTraceContext,\n spanStack: unknown,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceRootContext(context, spanStack, () => source[method](value))\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nfunction wrapAutoTraceNodeAsyncGenerator(\n nodeConfiguration: AutoTraceNodeConfiguration,\n source: AutoTraceAsyncGenerator,\n): AutoTraceAsyncGenerator {\n const step = (\n method: \"next\" | \"return\" | \"throw\",\n value?: unknown,\n ): Promise<IteratorResult<unknown, unknown>> =>\n runWithAutoTraceNodeConfiguration(nodeConfiguration, () =>\n source[method](value),\n )\n const wrapped: AutoTraceAsyncGenerator = {\n next: (value) => step(\"next\", value),\n return: (value) => step(\"return\", value),\n throw: (error) => step(\"throw\", error),\n [Symbol.asyncIterator]: () => wrapped,\n }\n return wrapped\n}\n\nfunction shareFinalize(\n configuration: AutoTraceNodeConfiguration,\n): AutoTraceNodeConfiguration {\n const finalize = configuration.finalize\n if (finalize === undefined) {\n return configuration\n }\n let settled: Promise<unknown> | undefined\n return {\n ...configuration,\n finalize: (result: unknown) => {\n settled ??= Promise.resolve().then(() => finalize(result))\n return settled\n },\n }\n}\n\nexport function __bitfabAutoSpan<T>(\n definition: AutoTraceFunctionDefinition,\n inputs: unknown[],\n fn: () => T,\n): T {\n noteTransformedModule()\n const scope = currentAutoTraceScope()\n if (!scope || scope.entries.length === 0 || isCaptureSuppressed()) {\n return fn()\n }\n const nameParts = definition.name.split(\".\")\n const simpleName = nameParts[nameParts.length - 1]\n if (isRootFunctionEntry(scope, simpleName)) {\n return fn()\n }\n const nodeConfiguration =\n simpleName === scope.nodeConfiguration?.functionName\n ? shareFinalize(scope.nodeConfiguration)\n : undefined\n const spanDetails: SpanDetails = { contexts: [] }\n return invokeThroughAutoTraceEntries(\n scope.entries,\n (entry, next) =>\n entry.context.invoke(\n definition,\n inputs,\n next,\n entry,\n spanDetails,\n nodeConfiguration,\n ),\n fn,\n )\n}\n\n/**\n * Preserve a function's original call arguments for transform cases where\n * parameter bindings discard them, such as destructured arrow parameters.\n *\n * This helper is internal transform/runtime protocol. The proxy preserves the\n * target's callability, arity, async identity, and non-constructibility while\n * only allocating a trace closure beneath an active automatic trace root.\n *\n * @experimental The automatic tracing protocol may change.\n */\nexport function __bitfabAutoWrap<T extends (...args: never[]) => unknown>(\n definition: AutoTraceFunctionDefinition,\n fn: T,\n): T {\n noteTransformedModule()\n if (fn.name === \"\") {\n const nameParts = definition.name.split(\".\")\n const inferredName = nameParts[nameParts.length - 1]\n if (inferredName !== undefined) {\n Object.defineProperty(fn, \"name\", {\n configurable: true,\n value: inferredName,\n })\n }\n }\n\n const target = fn as unknown as (...args: unknown[]) => unknown\n return new Proxy(target, {\n apply(callTarget, thisArg, args) {\n if (!__bitfabAutoTraceActive()) {\n return Reflect.apply(callTarget, thisArg, args)\n }\n return __bitfabAutoSpan(definition, args, () =>\n Reflect.apply(callTarget, thisArg, args),\n )\n },\n }) as unknown as T\n}\n\n/**\n * Return whether the current call is inside an automatic trace root.\n *\n * Build transforms use this before allocating function metadata, captured\n * inputs, or an invocation closure. It is internal transform/runtime protocol,\n * not a supported application API.\n *\n * @experimental The automatic tracing protocol may change.\n */\nexport function __bitfabAutoTraceActive(): boolean {\n if (autoTraceState.activeRoots === 0 || isCaptureSuppressed()) {\n return false\n }\n return currentAutoTraceEntries().length > 0\n}\n\nfunction currentAutoTraceScope(): AutoTraceScope | undefined {\n initializeAutoTraceStorage()\n return autoTraceState.storage?.getStore() ?? autoTraceState.browserScope\n}\n\nexport function _resetAutoTraceTransformDetection(): void {\n autoTraceGlobal.__bit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,GAC3B,OAAO,QAAQ,MAAM,YAAY,SAAS,IAAI;EAEhD,OAAO,iBAAiB,YAAY,YAClC,QAAQ,MAAM,YAAY,SAAS,IAAI,CACzC;CACF,EACF,CAAC;AACH;AAWA,SAAgB,0BAAmC;CACjD,IAAI,eAAe,gBAAgB,KAAK,oBAAoB,GAC1D,OAAO;CAET,OAAO,wBAAwB,CAAC,CAAC,SAAS;AAC5C;AAEA,SAAS,wBAAoD;CAC3D,2BAA2B;CAC3B,OAAO,eAAe,SAAS,SAAS,KAAK,eAAe;AAC9D;AAEA,SAAgB,oCAA0C;CACxD,gBAAgB,uCAAuC,KAAA;AACzD"}
@@ -7,11 +7,13 @@ export interface AutoTraceFunctionDefinition {
7
7
  column: number;
8
8
  async?: boolean;
9
9
  wrapper?: boolean;
10
+ baml?: boolean;
10
11
  }
11
12
  export interface AutoTraceNodeConfiguration {
12
13
  functionName: string;
13
14
  name?: string;
14
15
  type?: "llm" | "agent" | "function" | "guardrail" | "handoff" | "custom";
16
+ defaultType?: boolean;
15
17
  capture: boolean;
16
18
  experimentId?: string;
17
19
  /** @deprecated Use experimentId. */
@@ -7,11 +7,13 @@ export interface AutoTraceFunctionDefinition {
7
7
  column: number;
8
8
  async?: boolean;
9
9
  wrapper?: boolean;
10
+ baml?: boolean;
10
11
  }
11
12
  export interface AutoTraceNodeConfiguration {
12
13
  functionName: string;
13
14
  name?: string;
14
15
  type?: "llm" | "agent" | "function" | "guardrail" | "handoff" | "custom";
16
+ defaultType?: boolean;
15
17
  capture: boolean;
16
18
  experimentId?: string;
17
19
  /** @deprecated Use experimentId. */
@@ -105,6 +105,24 @@ function withNodeFunctionName(path, types) {
105
105
  if (types.isFunctionExpression(fn) && fn.id) return fn.id.name;
106
106
  return null;
107
107
  }
108
+ const BAML_GENERATED_HEADER = "This file was generated by BAML";
109
+ const BAML_CLIENT_CLASSES = /* @__PURE__ */ new Set(["BamlAsyncClient", "BamlSyncClient"]);
110
+ const BAML_OPTIONS_PARAMETER = "__baml_options__";
111
+ function isBamlGeneratedSource(code) {
112
+ return code.slice(0, 4096).includes(BAML_GENERATED_HEADER);
113
+ }
114
+ function isBamlClientMethod(path, types) {
115
+ const node = path.node;
116
+ if (!types.isClassMethod(node) || node.kind !== "method" || node.static) return false;
117
+ const classPath = path.parentPath?.parentPath;
118
+ if (!classPath || !(classPath.isClassDeclaration() || classPath.isClassExpression()) || !classPath.node.id || !BAML_CLIENT_CLASSES.has(classPath.node.id.name)) return false;
119
+ const parameters = runtimeParameters(node, types);
120
+ const last = parameters[parameters.length - 1];
121
+ return types.isIdentifier(last, { name: BAML_OPTIONS_PARAMETER });
122
+ }
123
+ function bamlOptionsDeclaration(callerOptions, withCollector, types) {
124
+ return types.variableDeclaration("const", [types.variableDeclarator(types.identifier(BAML_OPTIONS_PARAMETER), types.conditionalExpression(types.binaryExpression("===", types.cloneNode(withCollector), types.identifier("undefined")), types.cloneNode(callerOptions), types.callExpression(types.cloneNode(withCollector), [types.cloneNode(callerOptions), types.memberExpression(types.thisExpression(), types.identifier("bamlOptions"))])))]);
125
+ }
108
126
  function runtimeParameters(node, types) {
109
127
  return node.params.filter((parameter) => !types.isIdentifier(parameter, { name: "this" }));
110
128
  }
@@ -139,6 +157,7 @@ function bitfabBabelPlugin(api) {
139
157
  state.runtimeIdentifier = path.scope.generateUidIdentifier("bitfabAutoSpan");
140
158
  state.activeIdentifier = path.scope.generateUidIdentifier("bitfabAutoTraceActive");
141
159
  state.wrapperIdentifier = path.scope.generateUidIdentifier("bitfabAutoWrap");
160
+ state.bamlGenerated = isBamlGeneratedSource(state.file.code ?? "");
142
161
  state.definitions = [];
143
162
  state.usedRuntime = false;
144
163
  state.usedWrapper = false;
@@ -167,6 +186,8 @@ function bitfabBabelPlugin(api) {
167
186
  Function: { exit(path, state) {
168
187
  const node = path.node;
169
188
  if (state.skipFile || node._bitfabInstrumented || !isInstrumentableFunction(node, types) || isTraceDecoratorRoot(path, types) || !state.runtimeIdentifier || !state.activeIdentifier || !state.wrapperIdentifier) return;
189
+ const bamlMethod = state.bamlGenerated === true && isBamlClientMethod(path, types);
190
+ if (state.bamlGenerated && !bamlMethod) return;
170
191
  const name = qualifiedFunctionName(path, types);
171
192
  if (name.startsWith("anonymous-")) return;
172
193
  const normalizedFilename = autoTraceFilename(state.file.opts.filename ?? "unknown", state.opts.cwd ?? state.file.opts.cwd ?? process.cwd());
@@ -178,6 +199,7 @@ function bitfabBabelPlugin(api) {
178
199
  types.objectProperty(types.identifier("line"), types.numericLiteral(line)),
179
200
  types.objectProperty(types.identifier("column"), types.numericLiteral(column)),
180
201
  ...node.async ? [types.objectProperty(types.identifier("async"), types.booleanLiteral(true))] : [],
202
+ ...bamlMethod ? [types.objectProperty(types.identifier("baml"), types.booleanLiteral(true))] : [],
181
203
  ...isRestWrapper(path, types) ? [types.objectProperty(types.identifier("wrapper"), types.booleanLiteral(true))] : []
182
204
  ]);
183
205
  const definitionIdentifier = path.scope.getProgramParent().generateUidIdentifier("bitfabAutoDefinition");
@@ -192,10 +214,13 @@ function bitfabBabelPlugin(api) {
192
214
  const originalBody = types.isBlockStatement(node.body) ? node.body : types.blockStatement([types.returnStatement(node.body)]);
193
215
  const directives = originalBody.directives;
194
216
  originalBody.directives = [];
195
- node.body = types.blockStatement([types.ifStatement(types.callExpression(types.cloneNode(state.activeIdentifier), []), types.blockStatement([types.returnStatement(types.callExpression(types.cloneNode(state.runtimeIdentifier), [
217
+ const callerOptions = bamlMethod ? path.scope.generateUidIdentifier("bitfabBamlOptions") : void 0;
218
+ const withCollector = bamlMethod ? path.scope.generateUidIdentifier("bitfabBamlWithCollector") : void 0;
219
+ const tracedBody = callerOptions && withCollector ? types.blockStatement([bamlOptionsDeclaration(callerOptions, withCollector, types), ...types.cloneNode(originalBody, true).body], []) : types.cloneNode(originalBody, true);
220
+ node.body = types.blockStatement([types.ifStatement(types.callExpression(types.cloneNode(state.activeIdentifier), []), types.blockStatement([...callerOptions ? [types.variableDeclaration("const", [types.variableDeclarator(callerOptions, types.identifier(BAML_OPTIONS_PARAMETER))])] : [], types.returnStatement(types.callExpression(types.cloneNode(state.runtimeIdentifier), [
196
221
  types.cloneNode(definitionIdentifier),
197
222
  parameterInputs(path, types),
198
- types.arrowFunctionExpression([], types.cloneNode(originalBody, true), node.async ?? false)
223
+ types.arrowFunctionExpression(withCollector ? [types.cloneNode(withCollector)] : [], tracedBody, node.async ?? false)
199
224
  ]))])), ...originalBody.body], directives);
200
225
  node._bitfabInstrumented = true;
201
226
  state.usedRuntime = true;
@@ -206,4 +231,4 @@ function bitfabBabelPlugin(api) {
206
231
  //#endregion
207
232
  export { sourceFilename as i, AUTO_TRACE_TRANSFORM_MARKER as n, shouldTransformBitfabFile as r, bitfabBabelPlugin as t };
208
233
 
209
- //# sourceMappingURL=babelPlugin-C70OxrqA.js.map
234
+ //# sourceMappingURL=babelPlugin-CBjx6aJe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"babelPlugin-CBjx6aJe.js","names":[],"sources":["../../bitfab-typescript-transform/src/transformOptions.ts","../../bitfab-typescript-transform/src/babelPlugin.ts"],"sourcesContent":["export interface BitfabTransformOptions {\n /** Module that exports the automatic span runtime. */\n runtimeModule?: string\n /** Working directory removed from generated function IDs. */\n cwd?: string\n /** Return false to leave a file unchanged. */\n include?: (filename: string) => boolean\n}\n\nconst AUTO_TRACE_FUNCTION_ID_VERSION = \"ts-auto-v1\"\nexport const AUTO_TRACE_TRANSFORM_MARKER =\n \"__bitfab_auto_trace_transformed_v1__\"\n\nexport function autoTraceFunctionId(file: string, name: string): string {\n return `${AUTO_TRACE_FUNCTION_ID_VERSION}:${file}#${name}`\n}\n\nexport function sourceFilename(filename: string): string {\n return filename.replace(/\\\\/g, \"/\").split(/[?#]/, 1)[0] ?? \"\"\n}\n\nexport function autoTraceFilename(filename: string, cwd: string): string {\n const normalized = sourceFilename(filename)\n const normalizedCwd = cwd.replace(/\\\\/g, \"/\").replace(/\\/$/, \"\")\n return normalized.startsWith(`${normalizedCwd}/`)\n ? normalized.slice(normalizedCwd.length + 1)\n : normalized\n}\n\nexport function shouldTransformBitfabFile(\n filename: string,\n options: BitfabTransformOptions,\n): boolean {\n if (!filename) {\n return false\n }\n if (options.include && !options.include(filename)) {\n return false\n }\n\n const normalized = sourceFilename(filename)\n const normalizedCwd = options.cwd?.replace(/\\\\/g, \"/\").replace(/\\/$/, \"\")\n const isAbsolute =\n normalized.startsWith(\"/\") || /^[A-Za-z]:\\//.test(normalized)\n if (\n normalizedCwd &&\n isAbsolute &&\n normalized !== normalizedCwd &&\n !normalized.startsWith(`${normalizedCwd}/`)\n ) {\n return false\n }\n return (\n !normalized.includes(\"/node_modules/\") &&\n !normalized.endsWith(\".d.ts\") &&\n /\\.[cm]?[jt]sx?$/.test(normalized)\n )\n}\n","import type { NodePath, PluginObject, PluginPass } from \"@babel/core\"\nimport type * as BabelTypes from \"@babel/types\"\nimport type { BitfabTransformOptions } from \"./transformOptions.js\"\nimport {\n AUTO_TRACE_TRANSFORM_MARKER,\n autoTraceFilename,\n autoTraceFunctionId,\n shouldTransformBitfabFile,\n} from \"./transformOptions.js\"\n\ntype BabelTypesApi = typeof BabelTypes\n\ntype BitfabPluginOptions = BitfabTransformOptions\n\ninterface BitfabPluginState extends PluginPass {\n opts: BitfabPluginOptions\n runtimeIdentifier?: ReturnType<BabelTypesApi[\"identifier\"]>\n activeIdentifier?: ReturnType<BabelTypesApi[\"identifier\"]>\n wrapperIdentifier?: ReturnType<BabelTypesApi[\"identifier\"]>\n definitions?: Array<ReturnType<BabelTypesApi[\"variableDeclaration\"]>>\n skipFile?: boolean\n bamlGenerated?: boolean\n usedRuntime?: boolean\n usedWrapper?: boolean\n}\n\ninterface InstrumentedFunction {\n _bitfabInstrumented?: boolean\n}\n\nfunction propertyName(\n node: BabelTypes.Node | null | undefined,\n types: BabelTypesApi,\n): string | null {\n if (types.isIdentifier(node)) {\n return node.name\n }\n if (types.isStringLiteral(node)) {\n return node.value\n }\n return null\n}\n\nfunction functionName(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): string {\n const node = path.node\n if (types.isFunctionDeclaration(node) || types.isFunctionExpression(node)) {\n if (node.id) {\n return node.id.name\n }\n }\n\n if (\n (types.isClassMethod(node) || types.isObjectMethod(node)) &&\n !node.computed &&\n types.isIdentifier(node.key)\n ) {\n return node.key.name\n }\n\n const parent = path.parentPath?.node\n if (types.isVariableDeclarator(parent)) {\n return propertyName(parent.id, types) ?? \"anonymous\"\n }\n if (types.isObjectProperty(parent) && !parent.computed) {\n return propertyName(parent.key, types) ?? \"anonymous\"\n }\n if (types.isClassProperty(parent) && !parent.computed) {\n const name = propertyName(parent.key, types)\n if (name) {\n return name\n }\n }\n\n const { line, column } = sourcePosition(path)\n return `anonymous-${line}-${column}`\n}\n\nfunction isInstrumentableFunction(\n node: BabelTypes.Function,\n types: BabelTypesApi,\n): boolean {\n if (node.generator || types.isClassPrivateMethod(node)) {\n return false\n }\n return (\n !(types.isClassMethod(node) || types.isObjectMethod(node)) ||\n node.kind === \"method\"\n )\n}\n\nfunction sourcePosition(path: NodePath<BabelTypes.Function>): {\n line: number\n column: number\n} {\n const exportDeclaration = path.parentPath?.isExportDeclaration()\n ? path.parentPath.node\n : undefined\n const start = (exportDeclaration ?? path.node).loc?.start\n return { line: start?.line ?? 0, column: start?.column ?? 0 }\n}\n\nfunction qualifiedFunctionName(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): string {\n const ownName = functionName(path, types)\n if (ownName.startsWith(\"anonymous-\")) {\n return ownName\n }\n const scopes: string[] = []\n let ancestor: NodePath | null = path.parentPath\n while (ancestor) {\n if (ancestor.isFunction()) {\n if (!isInstrumentableFunction(ancestor.node, types)) {\n ancestor = ancestor.parentPath\n continue\n }\n const name = functionName(\n ancestor as NodePath<BabelTypes.Function>,\n types,\n )\n if (!name.startsWith(\"anonymous-\")) {\n scopes.unshift(name)\n }\n } else if (\n (ancestor.isClassDeclaration() || ancestor.isClassExpression()) &&\n ancestor.node.id\n ) {\n scopes.unshift(ancestor.node.id.name)\n } else if (ancestor.isObjectExpression()) {\n const parent = ancestor.parentPath?.node\n if (types.isVariableDeclarator(parent)) {\n const name = propertyName(parent.id, types)\n if (name) {\n scopes.unshift(name)\n }\n } else if (types.isObjectProperty(parent) && !parent.computed) {\n const name = propertyName(parent.key, types)\n if (name) {\n scopes.unshift(name)\n }\n }\n }\n ancestor = ancestor.parentPath\n }\n return [...scopes, ownName].join(\".\")\n}\n\nfunction isTraceDecoratorRoot(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): boolean {\n const node = path.node\n const parent = path.parentPath?.node\n const decorated =\n types.isClassMethod(node) || types.isClassPrivateMethod(node)\n ? node\n : types.isClassProperty(parent) && parent.value === node\n ? parent\n : null\n if (!decorated) {\n return false\n }\n\n return (\n decorated.decorators?.some((decorator) => {\n const expression = decorator.expression\n if (!types.isCallExpression(expression)) {\n return false\n }\n const callee = expression.callee\n return (\n types.isMemberExpression(callee) &&\n !callee.computed &&\n types.isIdentifier(callee.property, { name: \"trace\" })\n )\n }) ?? false\n )\n}\n\nfunction withNodeFunctionName(\n path: NodePath<BabelTypes.CallExpression>,\n types: BabelTypesApi,\n): string | null {\n if (path.node.arguments.length > 2) {\n return null\n }\n const callee = path.node.callee\n if (\n !types.isMemberExpression(callee) ||\n callee.computed ||\n !types.isIdentifier(callee.property, { name: \"withNode\" })\n ) {\n return null\n }\n const fn = path.node.arguments[path.node.arguments.length - 1]\n if (types.isIdentifier(fn)) {\n return fn.name\n }\n if (types.isMemberExpression(fn) && !fn.computed) {\n return propertyName(fn.property, types)\n }\n if (types.isFunctionExpression(fn) && fn.id) {\n return fn.id.name\n }\n return null\n}\n\nconst BAML_GENERATED_HEADER = \"This file was generated by BAML\"\nconst BAML_CLIENT_CLASSES = new Set([\"BamlAsyncClient\", \"BamlSyncClient\"])\nconst BAML_OPTIONS_PARAMETER = \"__baml_options__\"\n\nfunction isBamlGeneratedSource(code: string): boolean {\n return code.slice(0, 4096).includes(BAML_GENERATED_HEADER)\n}\n\nfunction isBamlClientMethod(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): boolean {\n const node = path.node\n if (!types.isClassMethod(node) || node.kind !== \"method\" || node.static) {\n return false\n }\n const classPath = path.parentPath?.parentPath\n if (\n !classPath ||\n !(classPath.isClassDeclaration() || classPath.isClassExpression()) ||\n !classPath.node.id ||\n !BAML_CLIENT_CLASSES.has(classPath.node.id.name)\n ) {\n return false\n }\n const parameters = runtimeParameters(node, types)\n const last = parameters[parameters.length - 1]\n return types.isIdentifier(last, { name: BAML_OPTIONS_PARAMETER })\n}\n\nfunction bamlOptionsDeclaration(\n callerOptions: BabelTypes.Identifier,\n withCollector: BabelTypes.Identifier,\n types: BabelTypesApi,\n): BabelTypes.VariableDeclaration {\n return types.variableDeclaration(\"const\", [\n types.variableDeclarator(\n types.identifier(BAML_OPTIONS_PARAMETER),\n types.conditionalExpression(\n types.binaryExpression(\n \"===\",\n types.cloneNode(withCollector),\n types.identifier(\"undefined\"),\n ),\n types.cloneNode(callerOptions),\n types.callExpression(types.cloneNode(withCollector), [\n types.cloneNode(callerOptions),\n types.memberExpression(\n types.thisExpression(),\n types.identifier(\"bamlOptions\"),\n ),\n ]),\n ),\n ),\n ])\n}\n\nfunction runtimeParameters(\n node: BabelTypes.Function,\n types: BabelTypesApi,\n): BabelTypes.Function[\"params\"] {\n return node.params.filter(\n (parameter) => !types.isIdentifier(parameter, { name: \"this\" }),\n )\n}\n\nfunction parameterInputs(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): ReturnType<BabelTypesApi[\"arrayExpression\"]> {\n const elements: Array<BabelTypes.Expression | BabelTypes.SpreadElement> = []\n\n for (const [index, parameter] of runtimeParameters(\n path.node,\n types,\n ).entries()) {\n if (!types.isArrowFunctionExpression(path.node)) {\n if (types.isRestElement(parameter)) {\n elements.push(\n types.spreadElement(\n types.callExpression(\n types.memberExpression(\n types.arrayExpression([\n types.spreadElement(types.identifier(\"arguments\")),\n ]),\n types.identifier(\"slice\"),\n ),\n [types.numericLiteral(index)],\n ),\n ),\n )\n } else {\n elements.push(\n types.memberExpression(\n types.identifier(\"arguments\"),\n types.numericLiteral(index),\n true,\n ),\n )\n }\n continue\n }\n\n if (types.isIdentifier(parameter)) {\n elements.push(types.identifier(parameter.name))\n } else if (\n types.isRestElement(parameter) &&\n types.isIdentifier(parameter.argument)\n ) {\n elements.push(\n types.spreadElement(types.identifier(parameter.argument.name)),\n )\n }\n }\n\n return types.arrayExpression(elements)\n}\n\nfunction needsArgumentWrapper(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): boolean {\n return (\n types.isArrowFunctionExpression(path.node) &&\n path.node.params.some(\n (parameter) =>\n !types.isIdentifier(parameter) &&\n !(\n types.isRestElement(parameter) &&\n types.isIdentifier(parameter.argument)\n ),\n )\n )\n}\n\nfunction isRestWrapper(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): boolean {\n const parameters = runtimeParameters(path.node, types)\n return parameters.length === 1 && types.isRestElement(parameters[0])\n}\n\n/**\n * Babel adapter for Bitfab's experimental automatic call-span runtime.\n *\n * @experimental The transform protocol and generated function identities may\n * change before the feature is stable.\n */\nexport default function bitfabBabelPlugin(api: {\n types: BabelTypesApi\n}): PluginObject<BitfabPluginState> {\n const { types } = api\n\n return {\n name: \"bitfab-auto-trace\",\n visitor: {\n Program: {\n enter(path: NodePath<BabelTypes.Program>, state: BitfabPluginState) {\n const filename = state.file.opts.filename ?? \"unknown\"\n state.skipFile =\n !shouldTransformBitfabFile(filename, state.opts) ||\n path.scope.hasBinding(AUTO_TRACE_TRANSFORM_MARKER) ||\n path.node.directives.some(\n (directive) => directive.value.value === \"use client\",\n )\n state.runtimeIdentifier =\n path.scope.generateUidIdentifier(\"bitfabAutoSpan\")\n state.activeIdentifier = path.scope.generateUidIdentifier(\n \"bitfabAutoTraceActive\",\n )\n state.wrapperIdentifier =\n path.scope.generateUidIdentifier(\"bitfabAutoWrap\")\n state.bamlGenerated = isBamlGeneratedSource(state.file.code ?? \"\")\n state.definitions = []\n state.usedRuntime = false\n state.usedWrapper = false\n },\n exit(path: NodePath<BabelTypes.Program>, state: BitfabPluginState) {\n if (\n state.skipFile ||\n !state.usedRuntime ||\n !state.runtimeIdentifier ||\n !state.activeIdentifier ||\n !state.wrapperIdentifier\n ) {\n return\n }\n\n state.file.metadata[AUTO_TRACE_TRANSFORM_MARKER] = true\n path.unshiftContainer(\"body\", [\n types.importDeclaration(\n [\n types.importSpecifier(\n state.runtimeIdentifier,\n types.identifier(\"__bitfabAutoSpan\"),\n ),\n types.importSpecifier(\n state.activeIdentifier,\n types.identifier(\"__bitfabAutoTraceActive\"),\n ),\n ...(state.usedWrapper\n ? [\n types.importSpecifier(\n state.wrapperIdentifier,\n types.identifier(\"__bitfabAutoWrap\"),\n ),\n ]\n : []),\n ],\n types.stringLiteral(\n state.opts.runtimeModule ?? \"bitfab/auto\",\n ),\n ),\n types.variableDeclaration(\"const\", [\n types.variableDeclarator(\n types.identifier(AUTO_TRACE_TRANSFORM_MARKER),\n types.assignmentExpression(\n \"=\",\n types.memberExpression(\n types.identifier(\"globalThis\"),\n types.identifier(AUTO_TRACE_TRANSFORM_MARKER),\n ),\n types.booleanLiteral(true),\n ),\n ),\n ]),\n ...(state.definitions ?? []),\n ])\n },\n },\n CallExpression: {\n exit(\n path: NodePath<BabelTypes.CallExpression>,\n state: BitfabPluginState,\n ) {\n if (state.skipFile) {\n return\n }\n const configuredName = withNodeFunctionName(path, types)\n if (configuredName === null) {\n return\n }\n if (path.node.arguments.length === 1) {\n path.node.arguments.push(types.identifier(\"undefined\"))\n }\n path.node.arguments.push(types.stringLiteral(configuredName))\n },\n },\n Function: {\n exit(path: NodePath<BabelTypes.Function>, state: BitfabPluginState) {\n const node = path.node as typeof path.node & InstrumentedFunction\n if (\n state.skipFile ||\n node._bitfabInstrumented ||\n !isInstrumentableFunction(node, types) ||\n isTraceDecoratorRoot(path, types) ||\n !state.runtimeIdentifier ||\n !state.activeIdentifier ||\n !state.wrapperIdentifier\n ) {\n return\n }\n const bamlMethod =\n state.bamlGenerated === true && isBamlClientMethod(path, types)\n if (state.bamlGenerated && !bamlMethod) {\n return\n }\n const name = qualifiedFunctionName(path, types)\n if (name.startsWith(\"anonymous-\")) {\n return\n }\n const normalizedFilename = autoTraceFilename(\n state.file.opts.filename ?? \"unknown\",\n state.opts.cwd ?? state.file.opts.cwd ?? process.cwd(),\n )\n const { line, column } = sourcePosition(path)\n const definition = types.objectExpression([\n types.objectProperty(\n types.identifier(\"id\"),\n types.stringLiteral(\n autoTraceFunctionId(normalizedFilename, name),\n ),\n ),\n types.objectProperty(\n types.identifier(\"name\"),\n types.stringLiteral(name),\n ),\n types.objectProperty(\n types.identifier(\"file\"),\n types.stringLiteral(normalizedFilename),\n ),\n types.objectProperty(\n types.identifier(\"line\"),\n types.numericLiteral(line),\n ),\n types.objectProperty(\n types.identifier(\"column\"),\n types.numericLiteral(column),\n ),\n ...(node.async\n ? [\n types.objectProperty(\n types.identifier(\"async\"),\n types.booleanLiteral(true),\n ),\n ]\n : []),\n ...(bamlMethod\n ? [\n types.objectProperty(\n types.identifier(\"baml\"),\n types.booleanLiteral(true),\n ),\n ]\n : []),\n ...(isRestWrapper(path, types)\n ? [\n types.objectProperty(\n types.identifier(\"wrapper\"),\n types.booleanLiteral(true),\n ),\n ]\n : []),\n ])\n const definitionIdentifier = path.scope\n .getProgramParent()\n .generateUidIdentifier(\"bitfabAutoDefinition\")\n state.definitions?.push(\n types.variableDeclaration(\"const\", [\n types.variableDeclarator(definitionIdentifier, definition),\n ]),\n )\n\n if (needsArgumentWrapper(path, types)) {\n node._bitfabInstrumented = true\n path.replaceWith(\n types.callExpression(types.cloneNode(state.wrapperIdentifier), [\n types.cloneNode(definitionIdentifier),\n node as BabelTypes.ArrowFunctionExpression,\n ]),\n )\n state.usedRuntime = true\n state.usedWrapper = true\n return\n }\n\n const originalBody = types.isBlockStatement(node.body)\n ? node.body\n : types.blockStatement([types.returnStatement(node.body)])\n const directives = originalBody.directives\n originalBody.directives = []\n\n const callerOptions = bamlMethod\n ? path.scope.generateUidIdentifier(\"bitfabBamlOptions\")\n : undefined\n const withCollector = bamlMethod\n ? path.scope.generateUidIdentifier(\"bitfabBamlWithCollector\")\n : undefined\n const tracedBody =\n callerOptions && withCollector\n ? types.blockStatement(\n [\n bamlOptionsDeclaration(callerOptions, withCollector, types),\n ...types.cloneNode(originalBody, true).body,\n ],\n [],\n )\n : types.cloneNode(originalBody, true)\n const body = types.blockStatement(\n [\n types.ifStatement(\n types.callExpression(\n types.cloneNode(state.activeIdentifier),\n [],\n ),\n types.blockStatement([\n ...(callerOptions\n ? [\n types.variableDeclaration(\"const\", [\n types.variableDeclarator(\n callerOptions,\n types.identifier(BAML_OPTIONS_PARAMETER),\n ),\n ]),\n ]\n : []),\n types.returnStatement(\n types.callExpression(\n types.cloneNode(state.runtimeIdentifier),\n [\n types.cloneNode(definitionIdentifier),\n parameterInputs(path, types),\n types.arrowFunctionExpression(\n withCollector ? [types.cloneNode(withCollector)] : [],\n tracedBody,\n node.async ?? false,\n ),\n ],\n ),\n ),\n ]),\n ),\n ...originalBody.body,\n ],\n directives,\n )\n node.body = body\n node._bitfabInstrumented = true\n state.usedRuntime = true\n },\n },\n },\n }\n}\n"],"mappings":";AASA,MAAM,iCAAiC;AACvC,MAAa,8BACX;AAEF,SAAgB,oBAAoB,MAAc,MAAsB;CACtE,OAAO,GAAG,+BAA+B,GAAG,KAAK,GAAG;AACtD;AAEA,SAAgB,eAAe,UAA0B;CACvD,OAAO,SAAS,QAAQ,OAAO,GAAG,CAAC,CAAC,MAAM,QAAQ,CAAC,CAAC,CAAC,MAAM;AAC7D;AAEA,SAAgB,kBAAkB,UAAkB,KAAqB;CACvE,MAAM,aAAa,eAAe,QAAQ;CAC1C,MAAM,gBAAgB,IAAI,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,EAAE;CAC/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AAsB,CACzC,CACF,CAAC,CACH,IACA,CAAC,GACL,MAAM,gBACJ,MAAM,eACJ,MAAM,UAAU,MAAM,iBAAiB,GACvC;KACE,MAAM,UAAU,oBAAoB;KACpC,gBAAgB,MAAM,KAAK;KAC3B,MAAM,wBACJ,gBAAgB,CAAC,MAAM,UAAU,aAAa,CAAC,IAAI,CAAC,GACpD,YACA,KAAK,SAAS,KAChB;IACF,CACF,CACF,CACF,CAAC,CACH,GACA,GAAG,aAAa,IAClB,GACA,UAEa;IACf,KAAK,sBAAsB;IAC3B,MAAM,cAAc;GACtB,EACF;EACF;CACF;AACF"}
@@ -105,6 +105,24 @@ function withNodeFunctionName(path, types) {
105
105
  if (types.isFunctionExpression(fn) && fn.id) return fn.id.name;
106
106
  return null;
107
107
  }
108
+ const BAML_GENERATED_HEADER = "This file was generated by BAML";
109
+ const BAML_CLIENT_CLASSES = /* @__PURE__ */ new Set(["BamlAsyncClient", "BamlSyncClient"]);
110
+ const BAML_OPTIONS_PARAMETER = "__baml_options__";
111
+ function isBamlGeneratedSource(code) {
112
+ return code.slice(0, 4096).includes(BAML_GENERATED_HEADER);
113
+ }
114
+ function isBamlClientMethod(path, types) {
115
+ const node = path.node;
116
+ if (!types.isClassMethod(node) || node.kind !== "method" || node.static) return false;
117
+ const classPath = path.parentPath?.parentPath;
118
+ if (!classPath || !(classPath.isClassDeclaration() || classPath.isClassExpression()) || !classPath.node.id || !BAML_CLIENT_CLASSES.has(classPath.node.id.name)) return false;
119
+ const parameters = runtimeParameters(node, types);
120
+ const last = parameters[parameters.length - 1];
121
+ return types.isIdentifier(last, { name: BAML_OPTIONS_PARAMETER });
122
+ }
123
+ function bamlOptionsDeclaration(callerOptions, withCollector, types) {
124
+ return types.variableDeclaration("const", [types.variableDeclarator(types.identifier(BAML_OPTIONS_PARAMETER), types.conditionalExpression(types.binaryExpression("===", types.cloneNode(withCollector), types.identifier("undefined")), types.cloneNode(callerOptions), types.callExpression(types.cloneNode(withCollector), [types.cloneNode(callerOptions), types.memberExpression(types.thisExpression(), types.identifier("bamlOptions"))])))]);
125
+ }
108
126
  function runtimeParameters(node, types) {
109
127
  return node.params.filter((parameter) => !types.isIdentifier(parameter, { name: "this" }));
110
128
  }
@@ -139,6 +157,7 @@ function bitfabBabelPlugin(api) {
139
157
  state.runtimeIdentifier = path.scope.generateUidIdentifier("bitfabAutoSpan");
140
158
  state.activeIdentifier = path.scope.generateUidIdentifier("bitfabAutoTraceActive");
141
159
  state.wrapperIdentifier = path.scope.generateUidIdentifier("bitfabAutoWrap");
160
+ state.bamlGenerated = isBamlGeneratedSource(state.file.code ?? "");
142
161
  state.definitions = [];
143
162
  state.usedRuntime = false;
144
163
  state.usedWrapper = false;
@@ -167,6 +186,8 @@ function bitfabBabelPlugin(api) {
167
186
  Function: { exit(path, state) {
168
187
  const node = path.node;
169
188
  if (state.skipFile || node._bitfabInstrumented || !isInstrumentableFunction(node, types) || isTraceDecoratorRoot(path, types) || !state.runtimeIdentifier || !state.activeIdentifier || !state.wrapperIdentifier) return;
189
+ const bamlMethod = state.bamlGenerated === true && isBamlClientMethod(path, types);
190
+ if (state.bamlGenerated && !bamlMethod) return;
170
191
  const name = qualifiedFunctionName(path, types);
171
192
  if (name.startsWith("anonymous-")) return;
172
193
  const normalizedFilename = autoTraceFilename(state.file.opts.filename ?? "unknown", state.opts.cwd ?? state.file.opts.cwd ?? process.cwd());
@@ -178,6 +199,7 @@ function bitfabBabelPlugin(api) {
178
199
  types.objectProperty(types.identifier("line"), types.numericLiteral(line)),
179
200
  types.objectProperty(types.identifier("column"), types.numericLiteral(column)),
180
201
  ...node.async ? [types.objectProperty(types.identifier("async"), types.booleanLiteral(true))] : [],
202
+ ...bamlMethod ? [types.objectProperty(types.identifier("baml"), types.booleanLiteral(true))] : [],
181
203
  ...isRestWrapper(path, types) ? [types.objectProperty(types.identifier("wrapper"), types.booleanLiteral(true))] : []
182
204
  ]);
183
205
  const definitionIdentifier = path.scope.getProgramParent().generateUidIdentifier("bitfabAutoDefinition");
@@ -192,10 +214,13 @@ function bitfabBabelPlugin(api) {
192
214
  const originalBody = types.isBlockStatement(node.body) ? node.body : types.blockStatement([types.returnStatement(node.body)]);
193
215
  const directives = originalBody.directives;
194
216
  originalBody.directives = [];
195
- node.body = types.blockStatement([types.ifStatement(types.callExpression(types.cloneNode(state.activeIdentifier), []), types.blockStatement([types.returnStatement(types.callExpression(types.cloneNode(state.runtimeIdentifier), [
217
+ const callerOptions = bamlMethod ? path.scope.generateUidIdentifier("bitfabBamlOptions") : void 0;
218
+ const withCollector = bamlMethod ? path.scope.generateUidIdentifier("bitfabBamlWithCollector") : void 0;
219
+ const tracedBody = callerOptions && withCollector ? types.blockStatement([bamlOptionsDeclaration(callerOptions, withCollector, types), ...types.cloneNode(originalBody, true).body], []) : types.cloneNode(originalBody, true);
220
+ node.body = types.blockStatement([types.ifStatement(types.callExpression(types.cloneNode(state.activeIdentifier), []), types.blockStatement([...callerOptions ? [types.variableDeclaration("const", [types.variableDeclarator(callerOptions, types.identifier(BAML_OPTIONS_PARAMETER))])] : [], types.returnStatement(types.callExpression(types.cloneNode(state.runtimeIdentifier), [
196
221
  types.cloneNode(definitionIdentifier),
197
222
  parameterInputs(path, types),
198
- types.arrowFunctionExpression([], types.cloneNode(originalBody, true), node.async ?? false)
223
+ types.arrowFunctionExpression(withCollector ? [types.cloneNode(withCollector)] : [], tracedBody, node.async ?? false)
199
224
  ]))])), ...originalBody.body], directives);
200
225
  node._bitfabInstrumented = true;
201
226
  state.usedRuntime = true;
@@ -229,4 +254,4 @@ Object.defineProperty(exports, "sourceFilename", {
229
254
  }
230
255
  });
231
256
 
232
- //# sourceMappingURL=babelPlugin-Nta4-VcL.cjs.map
257
+ //# sourceMappingURL=babelPlugin-ZR9ilYct.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"babelPlugin-ZR9ilYct.cjs","names":[],"sources":["../../bitfab-typescript-transform/src/transformOptions.ts","../../bitfab-typescript-transform/src/babelPlugin.ts"],"sourcesContent":["export interface BitfabTransformOptions {\n /** Module that exports the automatic span runtime. */\n runtimeModule?: string\n /** Working directory removed from generated function IDs. */\n cwd?: string\n /** Return false to leave a file unchanged. */\n include?: (filename: string) => boolean\n}\n\nconst AUTO_TRACE_FUNCTION_ID_VERSION = \"ts-auto-v1\"\nexport const AUTO_TRACE_TRANSFORM_MARKER =\n \"__bitfab_auto_trace_transformed_v1__\"\n\nexport function autoTraceFunctionId(file: string, name: string): string {\n return `${AUTO_TRACE_FUNCTION_ID_VERSION}:${file}#${name}`\n}\n\nexport function sourceFilename(filename: string): string {\n return filename.replace(/\\\\/g, \"/\").split(/[?#]/, 1)[0] ?? \"\"\n}\n\nexport function autoTraceFilename(filename: string, cwd: string): string {\n const normalized = sourceFilename(filename)\n const normalizedCwd = cwd.replace(/\\\\/g, \"/\").replace(/\\/$/, \"\")\n return normalized.startsWith(`${normalizedCwd}/`)\n ? normalized.slice(normalizedCwd.length + 1)\n : normalized\n}\n\nexport function shouldTransformBitfabFile(\n filename: string,\n options: BitfabTransformOptions,\n): boolean {\n if (!filename) {\n return false\n }\n if (options.include && !options.include(filename)) {\n return false\n }\n\n const normalized = sourceFilename(filename)\n const normalizedCwd = options.cwd?.replace(/\\\\/g, \"/\").replace(/\\/$/, \"\")\n const isAbsolute =\n normalized.startsWith(\"/\") || /^[A-Za-z]:\\//.test(normalized)\n if (\n normalizedCwd &&\n isAbsolute &&\n normalized !== normalizedCwd &&\n !normalized.startsWith(`${normalizedCwd}/`)\n ) {\n return false\n }\n return (\n !normalized.includes(\"/node_modules/\") &&\n !normalized.endsWith(\".d.ts\") &&\n /\\.[cm]?[jt]sx?$/.test(normalized)\n )\n}\n","import type { NodePath, PluginObject, PluginPass } from \"@babel/core\"\nimport type * as BabelTypes from \"@babel/types\"\nimport type { BitfabTransformOptions } from \"./transformOptions.js\"\nimport {\n AUTO_TRACE_TRANSFORM_MARKER,\n autoTraceFilename,\n autoTraceFunctionId,\n shouldTransformBitfabFile,\n} from \"./transformOptions.js\"\n\ntype BabelTypesApi = typeof BabelTypes\n\ntype BitfabPluginOptions = BitfabTransformOptions\n\ninterface BitfabPluginState extends PluginPass {\n opts: BitfabPluginOptions\n runtimeIdentifier?: ReturnType<BabelTypesApi[\"identifier\"]>\n activeIdentifier?: ReturnType<BabelTypesApi[\"identifier\"]>\n wrapperIdentifier?: ReturnType<BabelTypesApi[\"identifier\"]>\n definitions?: Array<ReturnType<BabelTypesApi[\"variableDeclaration\"]>>\n skipFile?: boolean\n bamlGenerated?: boolean\n usedRuntime?: boolean\n usedWrapper?: boolean\n}\n\ninterface InstrumentedFunction {\n _bitfabInstrumented?: boolean\n}\n\nfunction propertyName(\n node: BabelTypes.Node | null | undefined,\n types: BabelTypesApi,\n): string | null {\n if (types.isIdentifier(node)) {\n return node.name\n }\n if (types.isStringLiteral(node)) {\n return node.value\n }\n return null\n}\n\nfunction functionName(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): string {\n const node = path.node\n if (types.isFunctionDeclaration(node) || types.isFunctionExpression(node)) {\n if (node.id) {\n return node.id.name\n }\n }\n\n if (\n (types.isClassMethod(node) || types.isObjectMethod(node)) &&\n !node.computed &&\n types.isIdentifier(node.key)\n ) {\n return node.key.name\n }\n\n const parent = path.parentPath?.node\n if (types.isVariableDeclarator(parent)) {\n return propertyName(parent.id, types) ?? \"anonymous\"\n }\n if (types.isObjectProperty(parent) && !parent.computed) {\n return propertyName(parent.key, types) ?? \"anonymous\"\n }\n if (types.isClassProperty(parent) && !parent.computed) {\n const name = propertyName(parent.key, types)\n if (name) {\n return name\n }\n }\n\n const { line, column } = sourcePosition(path)\n return `anonymous-${line}-${column}`\n}\n\nfunction isInstrumentableFunction(\n node: BabelTypes.Function,\n types: BabelTypesApi,\n): boolean {\n if (node.generator || types.isClassPrivateMethod(node)) {\n return false\n }\n return (\n !(types.isClassMethod(node) || types.isObjectMethod(node)) ||\n node.kind === \"method\"\n )\n}\n\nfunction sourcePosition(path: NodePath<BabelTypes.Function>): {\n line: number\n column: number\n} {\n const exportDeclaration = path.parentPath?.isExportDeclaration()\n ? path.parentPath.node\n : undefined\n const start = (exportDeclaration ?? path.node).loc?.start\n return { line: start?.line ?? 0, column: start?.column ?? 0 }\n}\n\nfunction qualifiedFunctionName(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): string {\n const ownName = functionName(path, types)\n if (ownName.startsWith(\"anonymous-\")) {\n return ownName\n }\n const scopes: string[] = []\n let ancestor: NodePath | null = path.parentPath\n while (ancestor) {\n if (ancestor.isFunction()) {\n if (!isInstrumentableFunction(ancestor.node, types)) {\n ancestor = ancestor.parentPath\n continue\n }\n const name = functionName(\n ancestor as NodePath<BabelTypes.Function>,\n types,\n )\n if (!name.startsWith(\"anonymous-\")) {\n scopes.unshift(name)\n }\n } else if (\n (ancestor.isClassDeclaration() || ancestor.isClassExpression()) &&\n ancestor.node.id\n ) {\n scopes.unshift(ancestor.node.id.name)\n } else if (ancestor.isObjectExpression()) {\n const parent = ancestor.parentPath?.node\n if (types.isVariableDeclarator(parent)) {\n const name = propertyName(parent.id, types)\n if (name) {\n scopes.unshift(name)\n }\n } else if (types.isObjectProperty(parent) && !parent.computed) {\n const name = propertyName(parent.key, types)\n if (name) {\n scopes.unshift(name)\n }\n }\n }\n ancestor = ancestor.parentPath\n }\n return [...scopes, ownName].join(\".\")\n}\n\nfunction isTraceDecoratorRoot(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): boolean {\n const node = path.node\n const parent = path.parentPath?.node\n const decorated =\n types.isClassMethod(node) || types.isClassPrivateMethod(node)\n ? node\n : types.isClassProperty(parent) && parent.value === node\n ? parent\n : null\n if (!decorated) {\n return false\n }\n\n return (\n decorated.decorators?.some((decorator) => {\n const expression = decorator.expression\n if (!types.isCallExpression(expression)) {\n return false\n }\n const callee = expression.callee\n return (\n types.isMemberExpression(callee) &&\n !callee.computed &&\n types.isIdentifier(callee.property, { name: \"trace\" })\n )\n }) ?? false\n )\n}\n\nfunction withNodeFunctionName(\n path: NodePath<BabelTypes.CallExpression>,\n types: BabelTypesApi,\n): string | null {\n if (path.node.arguments.length > 2) {\n return null\n }\n const callee = path.node.callee\n if (\n !types.isMemberExpression(callee) ||\n callee.computed ||\n !types.isIdentifier(callee.property, { name: \"withNode\" })\n ) {\n return null\n }\n const fn = path.node.arguments[path.node.arguments.length - 1]\n if (types.isIdentifier(fn)) {\n return fn.name\n }\n if (types.isMemberExpression(fn) && !fn.computed) {\n return propertyName(fn.property, types)\n }\n if (types.isFunctionExpression(fn) && fn.id) {\n return fn.id.name\n }\n return null\n}\n\nconst BAML_GENERATED_HEADER = \"This file was generated by BAML\"\nconst BAML_CLIENT_CLASSES = new Set([\"BamlAsyncClient\", \"BamlSyncClient\"])\nconst BAML_OPTIONS_PARAMETER = \"__baml_options__\"\n\nfunction isBamlGeneratedSource(code: string): boolean {\n return code.slice(0, 4096).includes(BAML_GENERATED_HEADER)\n}\n\nfunction isBamlClientMethod(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): boolean {\n const node = path.node\n if (!types.isClassMethod(node) || node.kind !== \"method\" || node.static) {\n return false\n }\n const classPath = path.parentPath?.parentPath\n if (\n !classPath ||\n !(classPath.isClassDeclaration() || classPath.isClassExpression()) ||\n !classPath.node.id ||\n !BAML_CLIENT_CLASSES.has(classPath.node.id.name)\n ) {\n return false\n }\n const parameters = runtimeParameters(node, types)\n const last = parameters[parameters.length - 1]\n return types.isIdentifier(last, { name: BAML_OPTIONS_PARAMETER })\n}\n\nfunction bamlOptionsDeclaration(\n callerOptions: BabelTypes.Identifier,\n withCollector: BabelTypes.Identifier,\n types: BabelTypesApi,\n): BabelTypes.VariableDeclaration {\n return types.variableDeclaration(\"const\", [\n types.variableDeclarator(\n types.identifier(BAML_OPTIONS_PARAMETER),\n types.conditionalExpression(\n types.binaryExpression(\n \"===\",\n types.cloneNode(withCollector),\n types.identifier(\"undefined\"),\n ),\n types.cloneNode(callerOptions),\n types.callExpression(types.cloneNode(withCollector), [\n types.cloneNode(callerOptions),\n types.memberExpression(\n types.thisExpression(),\n types.identifier(\"bamlOptions\"),\n ),\n ]),\n ),\n ),\n ])\n}\n\nfunction runtimeParameters(\n node: BabelTypes.Function,\n types: BabelTypesApi,\n): BabelTypes.Function[\"params\"] {\n return node.params.filter(\n (parameter) => !types.isIdentifier(parameter, { name: \"this\" }),\n )\n}\n\nfunction parameterInputs(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): ReturnType<BabelTypesApi[\"arrayExpression\"]> {\n const elements: Array<BabelTypes.Expression | BabelTypes.SpreadElement> = []\n\n for (const [index, parameter] of runtimeParameters(\n path.node,\n types,\n ).entries()) {\n if (!types.isArrowFunctionExpression(path.node)) {\n if (types.isRestElement(parameter)) {\n elements.push(\n types.spreadElement(\n types.callExpression(\n types.memberExpression(\n types.arrayExpression([\n types.spreadElement(types.identifier(\"arguments\")),\n ]),\n types.identifier(\"slice\"),\n ),\n [types.numericLiteral(index)],\n ),\n ),\n )\n } else {\n elements.push(\n types.memberExpression(\n types.identifier(\"arguments\"),\n types.numericLiteral(index),\n true,\n ),\n )\n }\n continue\n }\n\n if (types.isIdentifier(parameter)) {\n elements.push(types.identifier(parameter.name))\n } else if (\n types.isRestElement(parameter) &&\n types.isIdentifier(parameter.argument)\n ) {\n elements.push(\n types.spreadElement(types.identifier(parameter.argument.name)),\n )\n }\n }\n\n return types.arrayExpression(elements)\n}\n\nfunction needsArgumentWrapper(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): boolean {\n return (\n types.isArrowFunctionExpression(path.node) &&\n path.node.params.some(\n (parameter) =>\n !types.isIdentifier(parameter) &&\n !(\n types.isRestElement(parameter) &&\n types.isIdentifier(parameter.argument)\n ),\n )\n )\n}\n\nfunction isRestWrapper(\n path: NodePath<BabelTypes.Function>,\n types: BabelTypesApi,\n): boolean {\n const parameters = runtimeParameters(path.node, types)\n return parameters.length === 1 && types.isRestElement(parameters[0])\n}\n\n/**\n * Babel adapter for Bitfab's experimental automatic call-span runtime.\n *\n * @experimental The transform protocol and generated function identities may\n * change before the feature is stable.\n */\nexport default function bitfabBabelPlugin(api: {\n types: BabelTypesApi\n}): PluginObject<BitfabPluginState> {\n const { types } = api\n\n return {\n name: \"bitfab-auto-trace\",\n visitor: {\n Program: {\n enter(path: NodePath<BabelTypes.Program>, state: BitfabPluginState) {\n const filename = state.file.opts.filename ?? \"unknown\"\n state.skipFile =\n !shouldTransformBitfabFile(filename, state.opts) ||\n path.scope.hasBinding(AUTO_TRACE_TRANSFORM_MARKER) ||\n path.node.directives.some(\n (directive) => directive.value.value === \"use client\",\n )\n state.runtimeIdentifier =\n path.scope.generateUidIdentifier(\"bitfabAutoSpan\")\n state.activeIdentifier = path.scope.generateUidIdentifier(\n \"bitfabAutoTraceActive\",\n )\n state.wrapperIdentifier =\n path.scope.generateUidIdentifier(\"bitfabAutoWrap\")\n state.bamlGenerated = isBamlGeneratedSource(state.file.code ?? \"\")\n state.definitions = []\n state.usedRuntime = false\n state.usedWrapper = false\n },\n exit(path: NodePath<BabelTypes.Program>, state: BitfabPluginState) {\n if (\n state.skipFile ||\n !state.usedRuntime ||\n !state.runtimeIdentifier ||\n !state.activeIdentifier ||\n !state.wrapperIdentifier\n ) {\n return\n }\n\n state.file.metadata[AUTO_TRACE_TRANSFORM_MARKER] = true\n path.unshiftContainer(\"body\", [\n types.importDeclaration(\n [\n types.importSpecifier(\n state.runtimeIdentifier,\n types.identifier(\"__bitfabAutoSpan\"),\n ),\n types.importSpecifier(\n state.activeIdentifier,\n types.identifier(\"__bitfabAutoTraceActive\"),\n ),\n ...(state.usedWrapper\n ? [\n types.importSpecifier(\n state.wrapperIdentifier,\n types.identifier(\"__bitfabAutoWrap\"),\n ),\n ]\n : []),\n ],\n types.stringLiteral(\n state.opts.runtimeModule ?? \"bitfab/auto\",\n ),\n ),\n types.variableDeclaration(\"const\", [\n types.variableDeclarator(\n types.identifier(AUTO_TRACE_TRANSFORM_MARKER),\n types.assignmentExpression(\n \"=\",\n types.memberExpression(\n types.identifier(\"globalThis\"),\n types.identifier(AUTO_TRACE_TRANSFORM_MARKER),\n ),\n types.booleanLiteral(true),\n ),\n ),\n ]),\n ...(state.definitions ?? []),\n ])\n },\n },\n CallExpression: {\n exit(\n path: NodePath<BabelTypes.CallExpression>,\n state: BitfabPluginState,\n ) {\n if (state.skipFile) {\n return\n }\n const configuredName = withNodeFunctionName(path, types)\n if (configuredName === null) {\n return\n }\n if (path.node.arguments.length === 1) {\n path.node.arguments.push(types.identifier(\"undefined\"))\n }\n path.node.arguments.push(types.stringLiteral(configuredName))\n },\n },\n Function: {\n exit(path: NodePath<BabelTypes.Function>, state: BitfabPluginState) {\n const node = path.node as typeof path.node & InstrumentedFunction\n if (\n state.skipFile ||\n node._bitfabInstrumented ||\n !isInstrumentableFunction(node, types) ||\n isTraceDecoratorRoot(path, types) ||\n !state.runtimeIdentifier ||\n !state.activeIdentifier ||\n !state.wrapperIdentifier\n ) {\n return\n }\n const bamlMethod =\n state.bamlGenerated === true && isBamlClientMethod(path, types)\n if (state.bamlGenerated && !bamlMethod) {\n return\n }\n const name = qualifiedFunctionName(path, types)\n if (name.startsWith(\"anonymous-\")) {\n return\n }\n const normalizedFilename = autoTraceFilename(\n state.file.opts.filename ?? \"unknown\",\n state.opts.cwd ?? state.file.opts.cwd ?? process.cwd(),\n )\n const { line, column } = sourcePosition(path)\n const definition = types.objectExpression([\n types.objectProperty(\n types.identifier(\"id\"),\n types.stringLiteral(\n autoTraceFunctionId(normalizedFilename, name),\n ),\n ),\n types.objectProperty(\n types.identifier(\"name\"),\n types.stringLiteral(name),\n ),\n types.objectProperty(\n types.identifier(\"file\"),\n types.stringLiteral(normalizedFilename),\n ),\n types.objectProperty(\n types.identifier(\"line\"),\n types.numericLiteral(line),\n ),\n types.objectProperty(\n types.identifier(\"column\"),\n types.numericLiteral(column),\n ),\n ...(node.async\n ? [\n types.objectProperty(\n types.identifier(\"async\"),\n types.booleanLiteral(true),\n ),\n ]\n : []),\n ...(bamlMethod\n ? [\n types.objectProperty(\n types.identifier(\"baml\"),\n types.booleanLiteral(true),\n ),\n ]\n : []),\n ...(isRestWrapper(path, types)\n ? [\n types.objectProperty(\n types.identifier(\"wrapper\"),\n types.booleanLiteral(true),\n ),\n ]\n : []),\n ])\n const definitionIdentifier = path.scope\n .getProgramParent()\n .generateUidIdentifier(\"bitfabAutoDefinition\")\n state.definitions?.push(\n types.variableDeclaration(\"const\", [\n types.variableDeclarator(definitionIdentifier, definition),\n ]),\n )\n\n if (needsArgumentWrapper(path, types)) {\n node._bitfabInstrumented = true\n path.replaceWith(\n types.callExpression(types.cloneNode(state.wrapperIdentifier), [\n types.cloneNode(definitionIdentifier),\n node as BabelTypes.ArrowFunctionExpression,\n ]),\n )\n state.usedRuntime = true\n state.usedWrapper = true\n return\n }\n\n const originalBody = types.isBlockStatement(node.body)\n ? node.body\n : types.blockStatement([types.returnStatement(node.body)])\n const directives = originalBody.directives\n originalBody.directives = []\n\n const callerOptions = bamlMethod\n ? path.scope.generateUidIdentifier(\"bitfabBamlOptions\")\n : undefined\n const withCollector = bamlMethod\n ? path.scope.generateUidIdentifier(\"bitfabBamlWithCollector\")\n : undefined\n const tracedBody =\n callerOptions && withCollector\n ? types.blockStatement(\n [\n bamlOptionsDeclaration(callerOptions, withCollector, types),\n ...types.cloneNode(originalBody, true).body,\n ],\n [],\n )\n : types.cloneNode(originalBody, true)\n const body = types.blockStatement(\n [\n types.ifStatement(\n types.callExpression(\n types.cloneNode(state.activeIdentifier),\n [],\n ),\n types.blockStatement([\n ...(callerOptions\n ? [\n types.variableDeclaration(\"const\", [\n types.variableDeclarator(\n callerOptions,\n types.identifier(BAML_OPTIONS_PARAMETER),\n ),\n ]),\n ]\n : []),\n types.returnStatement(\n types.callExpression(\n types.cloneNode(state.runtimeIdentifier),\n [\n types.cloneNode(definitionIdentifier),\n parameterInputs(path, types),\n types.arrowFunctionExpression(\n withCollector ? [types.cloneNode(withCollector)] : [],\n tracedBody,\n node.async ?? false,\n ),\n ],\n ),\n ),\n ]),\n ),\n ...originalBody.body,\n ],\n directives,\n )\n node.body = body\n node._bitfabInstrumented = true\n state.usedRuntime = true\n },\n },\n },\n }\n}\n"],"mappings":";AASA,MAAM,iCAAiC;AACvC,MAAa,8BACX;AAEF,SAAgB,oBAAoB,MAAc,MAAsB;CACtE,OAAO,GAAG,+BAA+B,GAAG,KAAK,GAAG;AACtD;AAEA,SAAgB,eAAe,UAA0B;CACvD,OAAO,SAAS,QAAQ,OAAO,GAAG,CAAC,CAAC,MAAM,QAAQ,CAAC,CAAC,CAAC,MAAM;AAC7D;AAEA,SAAgB,kBAAkB,UAAkB,KAAqB;CACvE,MAAM,aAAa,eAAe,QAAQ;CAC1C,MAAM,gBAAgB,IAAI,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,EAAE;CAC/D,OAAO,WAAW,WAAW,GAAG,cAAc,EAAE,IAC5C,WAAW,MAAM,cAAc,SAAS,CAAC,IACzC;AACN;AAEA,SAAgB,0BACd,UACA,SACS;CACT,IAAI,CAAC,UACH,OAAO;CAET,IAAI,QAAQ,WAAW,CAAC,QAAQ,QAAQ,QAAQ,GAC9C,OAAO;CAGT,MAAM,aAAa,eAAe,QAAQ;CAC1C,MAAM,gBAAgB,QAAQ,KAAK,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,EAAE;CACxE,MAAM,aACJ,WAAW,WAAW,GAAG,KAAK,eAAe,KAAK,UAAU;CAC9D,IACE,iBACA,cACA,eAAe,iBACf,CAAC,WAAW,WAAW,GAAG,cAAc,EAAE,GAE1C,OAAO;CAET,OACE,CAAC,WAAW,SAAS,gBAAgB,KACrC,CAAC,WAAW,SAAS,OAAO,KAC5B,kBAAkB,KAAK,UAAU;AAErC;;;AC3BA,SAAS,aACP,MACA,OACe;CACf,IAAI,MAAM,aAAa,IAAI,GACzB,OAAO,KAAK;CAEd,IAAI,MAAM,gBAAgB,IA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M,aAAa,aAAa;IAChC,aAAa,aAAa,CAAC;IAE3B,MAAM,gBAAgB,aAClB,KAAK,MAAM,sBAAsB,mBAAmB,IACpD,KAAA;IACJ,MAAM,gBAAgB,aAClB,KAAK,MAAM,sBAAsB,yBAAyB,IAC1D,KAAA;IACJ,MAAM,aACJ,iBAAiB,gBACb,MAAM,eACJ,CACE,uBAAuB,eAAe,eAAe,KAAK,GAC1D,GAAG,MAAM,UAAU,cAAc,IAAI,CAAC,CAAC,IACzC,GACA,CAAC,CACH,IACA,MAAM,UAAU,cAAc,IAAI;IAuCxC,KAAK,OAtCQ,MAAM,eACjB,CACE,MAAM,YACJ,MAAM,eACJ,MAAM,UAAU,MAAM,gBAAgB,GACtC,CAAC,CACH,GACA,MAAM,eAAe,CACnB,GAAI,gBACA,CACE,MAAM,oBAAoB,SAAS,CACjC,MAAM,mBACJ,eACA,MAAM,WAAW,sBAAsB,CACzC,CACF,CAAC,CACH,IACA,CAAC,GACL,MAAM,gBACJ,MAAM,eACJ,MAAM,UAAU,MAAM,iBAAiB,GACvC;KACE,MAAM,UAAU,oBAAoB;KACpC,gBAAgB,MAAM,KAAK;KAC3B,MAAM,wBACJ,gBAAgB,CAAC,MAAM,UAAU,aAAa,CAAC,IAAI,CAAC,GACpD,YACA,KAAK,SAAS,KAChB;IACF,CACF,CACF,CACF,CAAC,CACH,GACA,GAAG,aAAa,IAClB,GACA,UAEa;IACf,KAAK,sBAAsB;IAC3B,MAAM,cAAc;GACtB,EACF;EACF;CACF;AACF"}
@@ -5,7 +5,7 @@ import { ExportResultCode } from "@opentelemetry/core";
5
5
  import { resourceFromAttributes } from "@opentelemetry/resources";
6
6
  import { AlwaysOnSampler, BasicTracerProvider, BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
7
7
  //#region src/version.generated.ts
8
- const __version__ = "0.65.11";
8
+ const __version__ = "0.67.0";
9
9
  const __packageName__ = "bitfab";
10
10
  //#endregion
11
11
  //#region src/traceCompletion.ts
@@ -2160,4 +2160,4 @@ function experimentIdWireFields(experimentId) {
2160
2160
  //#endregion
2161
2161
  export { readEnv as C, MixedTracingError as S, getReplayContext as _, http_exports as a, gitRunner as b, recordCallerTraceMetadata as c, DECLARED_NODE_FIELD as d, ROOT_TRACE_FUNCTION_KEY_FIELD as f, MAX_COMPRESSIBLE_SPAN_CARRIER_BYTES as g, makeSpanOrigin as h, flushTraces as i, retireTraceMetadata as l, isFrameworkInstrumentation as m, SPAN_TYPES as n, unrefTimer as o, SimulationPlan as p, experimentIdWireFields as r, callerTraceMetadata as s, HttpClient as t, CONTENT_OFF_KEY as u, replayContextReady as v, __version__ as w, BitfabError as x, runWithReplayContext as y };
2162
2162
 
2163
- //# sourceMappingURL=http-DdlELWcL.js.map
2163
+ //# sourceMappingURL=http-CcYPHER5.js.map