/**
 * Async-local storage context for per-invocation telemetry state. Each top-level
 * SDK method call runs in its own ALS scope (via runWithTelemetryContext), isolating
 * its depth counter and method metadata from concurrent calls.
 */
import { AsyncLocalStorage, } from "node:async_hooks";
// Static import of `AsyncLocalStorage` works in both CJS and ESM tsup bundles
// because tsup converts the import statement directly (to `require()` in CJS,
// kept as native `import` in ESM), bypassing the `__require` shim that
// silently broke the previous `require("node:async_hooks")` pattern in ESM —
// the bug that left ESM consumers (notably the CLI) without a telemetry
// store and dropped nested-call detection on every call.
//
// Browsers can't resolve `node:async_hooks` at bundle time; consumers who
// bundle the SDK for browsers need to mark this module external or polyfill
// it. The try/catch covers any other instantiation failure.
let telemetryStore = null;
try {
    telemetryStore = new AsyncLocalStorage();
}
catch {
    // Non-Node environment (browser, etc.) — telemetry context disabled.
}
export function isTelemetryNested() {
    if (!telemetryStore)
        return true;
    const store = telemetryStore.getStore();
    return store !== undefined && store.depth > 0;
}
export function runWithTelemetryContext(fn) {
    if (!telemetryStore)
        return fn();
    const currentDepth = telemetryStore.getStore()?.depth ?? -1;
    return telemetryStore.run({ depth: currentDepth + 1 }, fn);
}
export function setMethodMetadata(metadata) {
    if (!telemetryStore)
        return;
    const store = telemetryStore.getStore();
    if (!store)
        return;
    store.methodMetadata = { ...store.methodMetadata, ...metadata };
}
export function getMethodMetadata() {
    if (!telemetryStore)
        return undefined;
    return telemetryStore.getStore()?.methodMetadata;
}
