{"version":3,"file":"utils-D8kgcFxb.cjs","names":["version","initializeLogger","isStringUUID","newUUID","otelSpanIdToUUID","otelTraceIdToUUID","loadEnv","path","logger","uuid","TraceFlags","url"],"sources":["../../types/dist/index.mjs","../../client/dist/index.mjs","../package.json","../src/opentelemetry-lib/tracing/attributes.ts","../src/utils.ts"],"sourcesContent":["//#region src/debug-session.ts\n/** Directory the debug-session file lives in, relative to the working dir. */\nconst DEBUG_SESSION_DIR = \".lmnr\";\n/** Filename of the debug-session file inside {@link DEBUG_SESSION_DIR}. */\nconst DEBUG_SESSION_FILE = \"debug-session.json\";\n//#endregion\n//#region src/tracing.ts\n/**\n* Tracing levels to conditionally disable tracing.\n*\n* OFF - No tracing is sent.\n* META_ONLY - Only metadata is sent (e.g. tokens, costs, etc.).\n* ALL - All data is sent.\n*/\nlet TracingLevel = /* @__PURE__ */ function(TracingLevel) {\n\tTracingLevel[\"OFF\"] = \"off\";\n\tTracingLevel[\"META_ONLY\"] = \"meta_only\";\n\tTracingLevel[\"ALL\"] = \"all\";\n\treturn TracingLevel;\n}({});\n//#endregion\n//#region src/utils.ts\nconst errorMessage = (error) => error instanceof Error ? error.message : String(error);\n//#endregion\nexport { DEBUG_SESSION_DIR, DEBUG_SESSION_FILE, TracingLevel, errorMessage };\n\n//# sourceMappingURL=index.mjs.map","import { config } from \"dotenv\";\nimport * as path from \"path\";\nimport pino from \"pino\";\nimport { PinoPretty } from \"pino-pretty\";\nimport { v4 } from \"uuid\";\nimport { errorMessage } from \"@lmnr-ai/types\";\n//#region package.json\nvar version = \"0.8.49\";\n//#endregion\n//#region src/version.ts\nfunction getLangVersion() {\n\tif (typeof process !== \"undefined\" && process.versions && process.versions.node) return `node-${process.versions.node}`;\n\tif (typeof navigator !== \"undefined\" && navigator.userAgent) return `browser-${navigator.userAgent}`;\n\treturn null;\n}\n//#endregion\n//#region src/resources/index.ts\nvar BaseResource = class {\n\tconstructor(baseHttpUrl, auth) {\n\t\tthis.baseHttpUrl = baseHttpUrl;\n\t\tthis.auth = auth;\n\t\tthis.credential = auth.type === \"apiKey\" ? auth.key : auth.token;\n\t}\n\t/** API path prefix: `/v1/cli` for CLI user-token auth, `/v1` otherwise. */\n\tget apiPrefix() {\n\t\treturn this.auth.type === \"userToken\" ? \"/v1/cli\" : \"/v1\";\n\t}\n\theaders() {\n\t\treturn {\n\t\t\tAuthorization: `Bearer ${this.credential}`,\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tAccept: \"application/json\",\n\t\t\t...this.auth.type === \"userToken\" ? { \"x-lmnr-project-id\": this.auth.projectId } : {}\n\t\t};\n\t}\n\tasync handleError(response) {\n\t\tconst errorMsg = await response.text();\n\t\tthrow new Error(`${response.status} ${errorMsg}`);\n\t}\n};\n//#endregion\n//#region src/resources/browser-events.ts\nvar BrowserEventsResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\tasync send({ sessionId, traceId, events }) {\n\t\tconst payload = {\n\t\t\tsessionId,\n\t\t\ttraceId,\n\t\t\tevents,\n\t\t\tsource: getLangVersion() ?? \"javascript\",\n\t\t\tsdkVersion: version\n\t\t};\n\t\tconst jsonString = JSON.stringify(payload);\n\t\tconst compressedStream = new Blob([jsonString], { type: \"application/json\" }).stream().pipeThrough(new CompressionStream(\"gzip\"));\n\t\tconst compressedData = await new Response(compressedStream).arrayBuffer();\n\t\tconst response = await fetch(this.baseHttpUrl + \"/v1/browser-sessions/events\", {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t...this.headers(),\n\t\t\t\t\"Content-Encoding\": \"gzip\"\n\t\t\t},\n\t\t\tbody: compressedData\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n};\n//#endregion\n//#region src/resources/cli.ts\n/**\n* Locale-aware, case-insensitive comparator for the project listing. Ordering\n* lives here — the single choke point every CLI surface (the `project list`\n* table + its `--json`, and the interactive picker used by `setup` / `plugin\n* add`) reads from — so the order can't drift between surfaces.\n*/\nconst projectCollator = new Intl.Collator(void 0, { sensitivity: \"base\" });\n/** Sort projects by workspace name, then project name (stable, human-scannable). */\nconst sortProjects = (projects) => [...projects].sort((a, b) => projectCollator.compare(a.workspaceName ?? \"\", b.workspaceName ?? \"\") || projectCollator.compare(a.name ?? \"\", b.name ?? \"\"));\n/**\n* User-scoped CLI endpoints that don't target a specific project. Authed by the\n* BetterAuth user JWT (the `credential`); deliberately does NOT send an\n* `x-lmnr-project-id` header (these routes are project discovery, pre-selection).\n*\n* Discovery exception: this resource always hits `/v1/cli/projects` with the\n* bare bearer and overrides `BaseResource.headers()`/`apiPrefix`, so it works\n* even when constructed with a `userToken` auth that has no real project id yet.\n*/\nvar CliResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/** Workspaces + projects the authenticated user can access. */\n\tasync listProjects() {\n\t\tconst response = await fetch(`${this.baseHttpUrl}/v1/cli/projects`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${this.credential}`,\n\t\t\t\tAccept: \"application/json\"\n\t\t\t}\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\tconst body = await response.json();\n\t\treturn Array.isArray(body?.projects) ? sortProjects(body.projects) : [];\n\t}\n\t/**\n\t* Resolve which project a project API key belongs to. Authed by the user JWT\n\t* (the bearer); the project key travels in the body, NOT in `Authorization`.\n\t* The server verifies the key and that the authenticated user is a member of\n\t* the resolved project. Returns a tri-state probe so callers can distinguish a\n\t* revoked key (401 → `invalid`) from a server/access problem (`unverifiable`).\n\t*/\n\tasync resolveProjectByApiKey(apiKey) {\n\t\tlet response;\n\t\ttry {\n\t\t\tresponse = await fetch(`${this.baseHttpUrl}/v1/cli/project`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${this.credential}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tAccept: \"application/json\"\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({ apiKey })\n\t\t\t});\n\t\t} catch {\n\t\t\treturn { status: \"unverifiable\" };\n\t\t}\n\t\tif (response.status === 401) return { status: \"invalid\" };\n\t\tif (!response.ok) return { status: \"unverifiable\" };\n\t\tconst body = await response.json().catch(() => null);\n\t\treturn body?.projectId ? {\n\t\t\tstatus: \"ok\",\n\t\t\tprojectId: body.projectId\n\t\t} : { status: \"unverifiable\" };\n\t}\n};\n//#endregion\n//#region src/utils.ts\nfunction initializeLogger(options) {\n\tconst colorize = options?.colorize ?? true;\n\tconst level = options?.level ?? process.env.LMNR_LOG_LEVEL?.toLowerCase()?.trim() ?? \"info\";\n\treturn pino({ level }, PinoPretty({\n\t\tcolorize,\n\t\tminimumLevel: level\n\t}));\n}\nconst logger$4 = initializeLogger();\nconst isStringUUID = (id) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id);\nconst newUUID = () => {\n\tif (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") return crypto.randomUUID();\n\telse return v4();\n};\nconst otelSpanIdToUUID = (spanId) => {\n\tlet id = spanId.toLowerCase();\n\tif (id.startsWith(\"0x\")) id = id.slice(2);\n\tif (id.length !== 16) logger$4.warn(`Span ID ${spanId} is not 16 hex chars long. This is not a valid OpenTelemetry span ID.`);\n\tif (!/^[0-9a-f]+$/.test(id)) {\n\t\tlogger$4.error(`Span ID ${spanId} is not a valid hex string. Generating a random UUID instead.`);\n\t\treturn newUUID();\n\t}\n\treturn id.padStart(32, \"0\").replace(/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/, \"$1-$2-$3-$4-$5\");\n};\nconst otelTraceIdToUUID = (traceId) => {\n\tlet id = traceId.toLowerCase();\n\tif (id.startsWith(\"0x\")) id = id.slice(2);\n\tif (id.length !== 32) logger$4.warn(`Trace ID ${traceId} is not 32 hex chars long. This is not a valid OpenTelemetry trace ID.`);\n\tif (!/^[0-9a-f]+$/.test(id)) {\n\t\tlogger$4.error(`Trace ID ${traceId} is not a valid hex string. Generating a random UUID instead.`);\n\t\treturn newUUID();\n\t}\n\treturn id.replace(/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/, \"$1-$2-$3-$4-$5\");\n};\nconst slicePayload = (value, length) => {\n\tif (value === null || value === void 0) return value;\n\tconst str = JSON.stringify(value);\n\tif (str.length <= length) return value;\n\treturn str.slice(0, length) + \"...\";\n};\nconst loadEnv = (options) => {\n\tconst nodeEnv = process.env.NODE_ENV || \"development\";\n\tconst envDir = process.cwd();\n\tconst envFiles = [\n\t\t\".env\",\n\t\t\".env.local\",\n\t\t`.env.${nodeEnv}`,\n\t\t`.env.${nodeEnv}.local`\n\t];\n\tconst logLevel = process.env.LMNR_LOG_LEVEL ?? \"info\";\n\tconst verbose = [\"debug\", \"trace\"].includes(logLevel.trim().toLowerCase());\n\tconst quiet = options?.quiet ?? !verbose;\n\tconfig({\n\t\tpath: options?.paths ?? envFiles.map((envFile) => path.resolve(envDir, envFile)),\n\t\tquiet\n\t});\n};\n//#endregion\n//#region src/resources/datasets.ts\nconst logger$3 = initializeLogger();\nconst DEFAULT_DATASET_PULL_LIMIT = 100;\nconst DEFAULT_DATASET_PUSH_BATCH_SIZE = 100;\nvar DatasetsResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* List all datasets.\n\t*\n\t* @returns {Promise<Dataset[]>} Array of datasets\n\t*/\n\tasync listDatasets() {\n\t\tconst response = await fetch(this.baseHttpUrl + this.apiPrefix + \"/datasets\", {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n\t/** Create an empty dataset. */\n\tasync create(name) {\n\t\tconst response = await fetch(this.baseHttpUrl + this.apiPrefix + \"/datasets\", {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({ name })\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n\t/** Get a dataset by its canonical UUID. */\n\tasync getById(datasetId) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/datasets/${datasetId}`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n\t/** Rename a dataset. */\n\tasync update(datasetId, name) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/datasets/${datasetId}`, {\n\t\t\tmethod: \"PATCH\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({ name })\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n\t/** Delete a dataset and its datapoints. */\n\tasync delete(datasetId) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/datasets/${datasetId}`, {\n\t\t\tmethod: \"DELETE\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n\t/**\n\t* Get a dataset by name.\n\t*\n\t* @param {string} name - Name of the dataset\n\t* @returns {Promise<Dataset[]>} Array of datasets with matching name\n\t*/\n\tasync getDatasetByName(name) {\n\t\tconst params = new URLSearchParams({ name });\n\t\tconst response = await fetch(this.baseHttpUrl + `${this.apiPrefix}/datasets?${params.toString()}`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n\t/**\n\t* Push datapoints to a dataset.\n\t*\n\t* @param {Object} options - Push options\n\t* @param {Datapoint<D, T>[]} options.points - Datapoints to push\n\t* @param {string} [options.name] - Name of the dataset (either name or id must be provided)\n\t* @param {StringUUID} [options.id] - ID of the dataset (either name or id must be provided)\n\t* @param {number} [options.batchSize] - Batch size for pushing (default: 100)\n\t* @param {boolean} [options.createDataset] - Whether to create the dataset if it doesn't exist\n\t* @returns {Promise<PushDatapointsResponse | undefined>}\n\t*/\n\tasync push({ points, name, id, batchSize = DEFAULT_DATASET_PUSH_BATCH_SIZE, createDataset = false }) {\n\t\tif (!name && !id) throw new Error(\"Either name or id must be provided\");\n\t\tif (name && id) throw new Error(\"Only one of name or id must be provided\");\n\t\tif (createDataset && !name) throw new Error(\"Name must be provided when creating a new dataset\");\n\t\tconst identifier = name ? { name } : { datasetId: id };\n\t\tconst totalBatches = Math.ceil(points.length / batchSize);\n\t\tlet response;\n\t\tfor (let i = 0; i < points.length; i += batchSize) {\n\t\t\tconst batchNum = Math.floor(i / batchSize) + 1;\n\t\t\tlogger$3.debug(`Pushing batch ${batchNum} of ${totalBatches}`);\n\t\t\tconst batch = points.slice(i, i + batchSize);\n\t\t\tconst fetchResponse = await fetch(this.baseHttpUrl + this.apiPrefix + \"/datasets/datapoints\", {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: this.headers(),\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\t...identifier,\n\t\t\t\t\tdatapoints: batch.map((point) => ({\n\t\t\t\t\t\tdata: point.data,\n\t\t\t\t\t\ttarget: point.target ?? {},\n\t\t\t\t\t\tmetadata: point.metadata ?? {}\n\t\t\t\t\t})),\n\t\t\t\t\tcreateDataset\n\t\t\t\t})\n\t\t\t});\n\t\t\tif (fetchResponse.status !== 200 && fetchResponse.status !== 201) await this.handleError(fetchResponse);\n\t\t\tresponse = await fetchResponse.json();\n\t\t}\n\t\treturn response;\n\t}\n\t/**\n\t* Pull datapoints from a dataset.\n\t*\n\t* @param {Object} options - Pull options\n\t* @param {string} [options.name] - Name of the dataset (either name or id must be provided)\n\t* @param {StringUUID} [options.id] - ID of the dataset (either name or id must be provided)\n\t* @param {number} [options.limit] - Maximum number of datapoints to return (default: 100)\n\t* @param {number} [options.offset] - Offset for pagination (default: 0)\n\t* @returns {Promise<GetDatapointsResponse<D, T>>}\n\t*/\n\tasync pull({ name, id, limit = DEFAULT_DATASET_PULL_LIMIT, offset = 0 }) {\n\t\tif (!name && !id) throw new Error(\"Either name or id must be provided\");\n\t\tif (name && id) throw new Error(\"Only one of name or id must be provided\");\n\t\tconst paramsObj = {\n\t\t\toffset: offset.toString(),\n\t\t\tlimit: limit.toString()\n\t\t};\n\t\tif (name) paramsObj.name = name;\n\t\telse paramsObj.datasetId = id;\n\t\tconst params = new URLSearchParams(paramsObj);\n\t\tconst response = await fetch(this.baseHttpUrl + `${this.apiPrefix}/datasets/datapoints?${params.toString()}`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n};\n//#endregion\n//#region src/resources/evals.ts\nconst logger$2 = initializeLogger();\nconst INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH = 16e6;\nvar EvalsResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* Initialize an evaluation.\n\t*\n\t* @param {string} name - Name of the evaluation\n\t* @param {string} groupName - Group name of the evaluation\n\t* @param {Record<string, any>} metadata - Optional metadata\n\t* @returns {Promise<InitEvaluationResponse>} Response from the evaluation initialization\n\t*/\n\tasync init(name, groupName, metadata) {\n\t\tconst response = await fetch(this.baseHttpUrl + \"/v1/evals\", {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({\n\t\t\t\tname: name ?? null,\n\t\t\t\tgroupName: groupName ?? null,\n\t\t\t\tmetadata: metadata ?? null\n\t\t\t})\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n\t/**\n\t* Create a new evaluation and return its ID.\n\t*\n\t* @param {string} [name] - Optional name of the evaluation\n\t* @param {string} [groupName] - An identifier to group evaluations\n\t* @param {Record<string, any>} [metadata] - Optional metadata\n\t* @returns {Promise<StringUUID>} The evaluation ID\n\t*/\n\tasync create(args) {\n\t\treturn (await this.init(args?.name, args?.groupName, args?.metadata)).id;\n\t}\n\t/**\n\t* Update an evaluation's name and/or metadata. The group ID is immutable.\n\t* Fields left undefined are kept unchanged.\n\t*\n\t* @param {Object} options - Update evaluation options\n\t* @param {string} options.evalId - The evaluation ID\n\t* @param {string} [options.name] - New name of the evaluation\n\t* @param {Record<string, any>} [options.metadata] - New metadata for the evaluation\n\t* @returns {Promise<InitEvaluationResponse>} The updated evaluation\n\t*/\n\tasync update({ evalId, name, metadata }) {\n\t\tconst response = await fetch(this.baseHttpUrl + `/v1/evals/${evalId}`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({\n\t\t\t\tname: name ?? null,\n\t\t\t\tmetadata: metadata ?? null\n\t\t\t})\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n\t/**\n\t* Create a new evaluation and return its ID.\n\t* @deprecated use `create` instead.\n\t*/\n\tasync createEvaluation(name, groupName, metadata) {\n\t\treturn (await this.init(name, groupName, metadata)).id;\n\t}\n\t/**\n\t* Create a datapoint for an evaluation.\n\t*\n\t* @param {Object} options - Create datapoint options\n\t* @param {string} options.evalId - The evaluation ID\n\t* @param {D} options.data - The input data for the executor\n\t* @param {T} [options.target] - The target/expected output for evaluators\n\t* @param {Record<string, any>} [options.metadata] - Optional metadata\n\t* @param {number} [options.index] - Optional index of the datapoint\n\t* @param {string} [options.traceId] - Optional trace ID\n\t* @returns {Promise<StringUUID>} The datapoint ID\n\t*/\n\tasync createDatapoint({ evalId, data, target, metadata, index, traceId }) {\n\t\tconst datapointId = newUUID();\n\t\tconst partialDatapoint = {\n\t\t\tid: datapointId,\n\t\t\tdata,\n\t\t\ttarget,\n\t\t\tindex: index ?? 0,\n\t\t\ttraceId: traceId ?? newUUID(),\n\t\t\texecutorSpanId: newUUID(),\n\t\t\tmetadata\n\t\t};\n\t\tawait this.saveDatapoints({\n\t\t\tevalId,\n\t\t\tdatapoints: [partialDatapoint]\n\t\t});\n\t\treturn datapointId;\n\t}\n\t/**\n\t* Update a datapoint with evaluation results.\n\t*\n\t* @param {Object} options - Update datapoint options\n\t* @param {string} options.evalId - The evaluation ID\n\t* @param {string} options.datapointId - The datapoint ID\n\t* @param {Record<string, number | null>} options.scores - The scores\n\t* @param {O} [options.executorOutput] - The executor output\n\t* @returns {Promise<void>}\n\t*/\n\tasync updateDatapoint({ evalId, datapointId, scores, executorOutput }) {\n\t\tconst response = await fetch(this.baseHttpUrl + `/v1/evals/${evalId}/datapoints/${datapointId}`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({\n\t\t\t\texecutorOutput,\n\t\t\t\tscores\n\t\t\t})\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n\t/**\n\t* Save evaluation datapoints.\n\t*\n\t* @param {Object} options - Save datapoints options\n\t* @param {string} options.evalId - ID of the evaluation\n\t* @param {EvaluationDatapoint<D, T, O>[]} options.datapoints - Datapoint to add\n\t* @param {string} [options.groupName] - Group name of the evaluation\n\t* @returns {Promise<void>} Response from the datapoint addition\n\t*/\n\tasync saveDatapoints({ evalId, datapoints, groupName }) {\n\t\tconst response = await fetch(this.baseHttpUrl + `/v1/evals/${evalId}/datapoints`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({\n\t\t\t\tpoints: datapoints.map((d) => ({\n\t\t\t\t\t...d,\n\t\t\t\t\tdata: slicePayload(d.data, INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH),\n\t\t\t\t\ttarget: slicePayload(d.target, INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH),\n\t\t\t\t\texecutorOutput: slicePayload(d.executorOutput, INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH)\n\t\t\t\t})),\n\t\t\t\tgroupName: groupName ?? null\n\t\t\t})\n\t\t});\n\t\tif (response.status === 413) return await this.retrySaveDatapoints({\n\t\t\tevalId,\n\t\t\tdatapoints,\n\t\t\tgroupName\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n\t/**\n\t* Get evaluation datapoints.\n\t*\n\t* @deprecated Use `client.datasets.pull()` instead.\n\t* @param {Object} options - Get datapoints options\n\t* @param {string} options.datasetName - Name of the dataset\n\t* @param {number} options.offset - Offset at which to start the query\n\t* @param {number} options.limit - Maximum number of datapoints to return\n\t* @returns {Promise<GetDatapointsResponse>} Response from the datapoint retrieval\n\t*/\n\tasync getDatapoints({ datasetName, offset, limit }) {\n\t\tlogger$2.warn(\"evals.getDatapoints() is deprecated. Use client.datasets.pull() instead.\");\n\t\tconst params = new URLSearchParams({\n\t\t\tname: datasetName,\n\t\t\toffset: offset.toString(),\n\t\t\tlimit: limit.toString()\n\t\t});\n\t\tconst response = await fetch(this.baseHttpUrl + `/v1/datasets/datapoints?${params.toString()}`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn await response.json();\n\t}\n\tasync retrySaveDatapoints({ evalId, datapoints, groupName, maxRetries = 25, initialLength = INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH }) {\n\t\tlet length = initialLength;\n\t\tlet lastResponse = null;\n\t\tfor (let i = 0; i < maxRetries; i++) {\n\t\t\tlogger$2.debug(`Retrying save datapoints... ${i + 1} of ${maxRetries}, length: ${length}`);\n\t\t\tconst response = await fetch(this.baseHttpUrl + `/v1/evals/${evalId}/datapoints`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: this.headers(),\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tpoints: datapoints.map((d) => ({\n\t\t\t\t\t\t...d,\n\t\t\t\t\t\tdata: slicePayload(d.data, length),\n\t\t\t\t\t\ttarget: slicePayload(d.target, length),\n\t\t\t\t\t\texecutorOutput: slicePayload(d.executorOutput, length)\n\t\t\t\t\t})),\n\t\t\t\t\tgroupName: groupName ?? null\n\t\t\t\t})\n\t\t\t});\n\t\t\tlastResponse = response;\n\t\t\tlength = Math.floor(length / 2);\n\t\t\tif (response.status !== 413) break;\n\t\t}\n\t\tif (lastResponse && !lastResponse.ok) await this.handleError(lastResponse);\n\t}\n};\n//#endregion\n//#region src/resources/evaluators.ts\n/**\n* Resource for creating evaluator scores\n*/\nvar EvaluatorsResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* Create a score for a span or trace\n\t*\n\t* @param {ScoreOptions} options - Score creation options\n\t* @param {string} options.name - Name of the score\n\t* @param {string} [options.traceId] - The trace ID to score (will be attached to top-level span)\n\t* @param {string} [options.spanId] - The span ID to score\n\t* @param {Record<string, any>} [options.metadata] - Additional metadata\n\t* @param {number} options.score - The score value (float)\n\t* @returns {Promise<void>}\n\t*\n\t* @example\n\t* // Score by trace ID (will attach to root span)\n\t* await evaluators.score({\n\t*   name: \"quality\",\n\t*   traceId: \"trace-id-here\",\n\t*   score: 0.95,\n\t*   metadata: { model: \"gpt-4\" }\n\t* });\n\t*\n\t* @example\n\t* // Score by span ID\n\t* await evaluators.score({\n\t*   name: \"relevance\",\n\t*   spanId: \"span-id-here\",\n\t*   score: 0.87\n\t* });\n\t*/\n\tasync score(options) {\n\t\tconst { name, metadata, score } = options;\n\t\tlet payload;\n\t\tif (\"traceId\" in options && options.traceId) payload = {\n\t\t\tname,\n\t\t\tmetadata,\n\t\t\tscore,\n\t\t\tsource: \"Code\",\n\t\t\ttraceId: isStringUUID(options.traceId) ? options.traceId : otelTraceIdToUUID(options.traceId)\n\t\t};\n\t\telse if (\"spanId\" in options && options.spanId) payload = {\n\t\t\tname,\n\t\t\tmetadata,\n\t\t\tscore,\n\t\t\tsource: \"Code\",\n\t\t\tspanId: isStringUUID(options.spanId) ? options.spanId : otelSpanIdToUUID(options.spanId)\n\t\t};\n\t\telse throw new Error(\"Either 'traceId' or 'spanId' must be provided.\");\n\t\tconst response = await fetch(this.baseHttpUrl + \"/v1/evaluators/score\", {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify(payload)\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n};\n//#endregion\n//#region src/resources/llm-profiles.ts\n/**\n* Workspace LLM profile CRUD over the CLI user-token surface\n* (`/v1/cli/llm-profiles`). Validation is entirely server-side; error messages\n* come back user-ready. Self-hosted only: on Laminar Cloud every route 404s\n* with `{error: \"LLM profiles are not available on this deployment\"}`.\n*/\nvar LlmProfilesResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* Errors come back as `{error: string}` (matches the signals surface) with\n\t* user-facing text, so unwrap the envelope before raising rather than\n\t* showing the raw JSON body.\n\t*/\n\tasync raiseLlmProfileError(response) {\n\t\tconst body = await response.text();\n\t\tlet message = body;\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(body);\n\t\t\tif (typeof parsed?.error === \"string\" && parsed.error.length > 0) message = parsed.error;\n\t\t} catch {}\n\t\tthrow new Error(`${response.status} ${message}`);\n\t}\n\tasync request(method, path, body) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/llm-profiles${path}`, {\n\t\t\tmethod,\n\t\t\theaders: this.headers(),\n\t\t\t...body !== void 0 ? { body: JSON.stringify(body) } : {}\n\t\t});\n\t\tif (!response.ok) await this.raiseLlmProfileError(response);\n\t\treturn response;\n\t}\n\t/**\n\t* Every workspace LLM profile visible to the caller, ordered\n\t* case-insensitively by name. Empty array on a workspace with no profiles.\n\t*/\n\tasync list() {\n\t\tconst body = await (await this.request(\"GET\", \"\")).json();\n\t\treturn Array.isArray(body?.llmProfiles) ? body.llmProfiles : [];\n\t}\n\tasync get(profileId) {\n\t\treturn (await this.request(\"GET\", `/${profileId}`)).json();\n\t}\n\tasync create(options) {\n\t\treturn (await this.request(\"POST\", \"\", options)).json();\n\t}\n\tasync update(profileId, options) {\n\t\treturn (await this.request(\"PATCH\", `/${profileId}`, options)).json();\n\t}\n\t/**\n\t* Deletes the profile and returns it. The server refuses (409) when any\n\t* signal still routes through the profile.\n\t*/\n\tasync delete(profileId) {\n\t\treturn (await this.request(\"DELETE\", `/${profileId}`)).json();\n\t}\n};\n//#endregion\n//#region src/resources/rollout-sessions.ts\nconst logger$1 = initializeLogger();\n/**\n* Map the opaque HIT `response` payload onto a {@link CachedSpan} the provider\n* wrappers can replay. The server-side shape of `response` is not yet frozen\n* (app-server plan 01 leaves it as a `serde_json::Value`), so this stays\n* deliberately tolerant: the whole payload is serialized into `output` (the only\n* field the AI SDK wrapper's `parseCachedSpan` actually reads, via\n* `JSON.parse`), and a `finishReason` is surfaced into `attributes` when the\n* payload carries one. `name`/`input` are irrelevant to replay and left empty.\n*/\nconst toCachedSpan = (response) => {\n\tconst output = typeof response === \"string\" ? response : JSON.stringify(response ?? null);\n\tconst attributes = {};\n\tif (response !== null && typeof response === \"object\" && typeof response.finishReason === \"string\") attributes[\"ai.response.finishReason\"] = response.finishReason;\n\treturn {\n\t\tname: \"\",\n\t\tinput: \"\",\n\t\toutput,\n\t\tattributes\n\t};\n};\nvar RolloutSessionsResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* Idempotently register (upsert) a debug session on the backend, keyed on the\n\t* SDK-supplied session id. The backend stores the row so the session is\n\t* visible in the UI; a null/omitted name never clobbers a name set elsewhere.\n\t*\n\t* Returns the backend-resolved `projectId` (derived from the API key) so the\n\t* caller can build the debugger URL; null if the body can't be parsed.\n\t*/\n\tasync register({ sessionId, name }) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/rollouts/${sessionId}`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({ name })\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\ttry {\n\t\t\treturn (await response.json()).projectId ?? null;\n\t\t} catch (e) {\n\t\t\tlogger$1.warn(`Failed to parse rollout register response: ${errorMessage(e)}`);\n\t\t\treturn null;\n\t\t}\n\t}\n\t/**\n\t* Rename an existing debug session. Update-only: the backend returns 404 (and\n\t* this throws) when the session id is unknown for the project, so a mistyped\n\t* id surfaces as an error rather than silently creating a session. Creation\n\t* stays the SDK's job via {@link register}.\n\t*/\n\tasync setName({ sessionId, name }) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/rollouts/${sessionId}/name`, {\n\t\t\tmethod: \"PATCH\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({ name })\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n\t/**\n\t* Append a block to a debug session (debugger session blocks).\n\t*\n\t* A debug session renders as an ordered list of blocks; this writes one to the\n\t* backend keyed by session id. The CLI uses it for `text` blocks — standalone\n\t* agent notes attached post-factum via `lmnr-cli debug session add-note` — so\n\t* a note is tied to the SESSION, not to a specific trace / evaluation (those\n\t* blocks are written at ingest from `rollout.session_id` metadata).\n\t*\n\t* A 404 (the session is unknown for the project) is logged and swallowed\n\t* unless `failOnNotFound` is set — CLI callers pass it so an exit 0 means the\n\t* block actually landed. Any other non-OK status throws.\n\t*\n\t* Returns the created block id, or null when the response body can't be parsed.\n\t*/\n\tasync addBlock({ sessionId, type, content, failOnNotFound, signal }) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/rollouts/${sessionId}/blocks`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({\n\t\t\t\ttype,\n\t\t\t\tcontent\n\t\t\t}),\n\t\t\tsignal\n\t\t});\n\t\tif (response.status === 404) {\n\t\t\tconst message = `Could not add a note: HTTP 404 for session ${sessionId}. Either the session isn't registered in this project (mint one with \\`lmnr-cli debug session new\\`, or run under LMNR_DEBUG=1), or this Laminar server doesn't expose the session-blocks write endpoint (POST /v1/rollouts/{sessionId}/blocks) yet.`;\n\t\t\tif (failOnNotFound) throw new Error(message);\n\t\t\tlogger$1.warn(message);\n\t\t\treturn null;\n\t\t}\n\t\tif (!response.ok) await this.handleError(response);\n\t\ttry {\n\t\t\treturn (await response.json()).id ?? null;\n\t\t} catch (e) {\n\t\t\tlogger$1.warn(`Failed to parse add-block response: ${errorMessage(e)}`);\n\t\t\treturn null;\n\t\t}\n\t}\n\t/**\n\t* List a debug session's blocks in creation order.\n\t*\n\t* Returns every `trace` / `evaluation` / `text` block on the session — the\n\t* same data the debugger UI renders. Used by `lmnr-cli debug session summary`\n\t* to print a chronological digest of the session. Returns an empty array when\n\t* the session has no blocks or the body can't be parsed.\n\t*/\n\tasync listBlocks({ sessionId }) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/rollouts/${sessionId}/blocks`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\ttry {\n\t\t\tconst body = await response.json();\n\t\t\treturn (Array.isArray(body) ? body : body.blocks) ?? [];\n\t\t} catch (e) {\n\t\t\tlogger$1.warn(`Failed to parse list-blocks response: ${errorMessage(e)}`);\n\t\t\treturn [];\n\t\t}\n\t}\n\t/**\n\t* Look up the debug-replay cache for a single LLM call (debug-replay v2).\n\t*\n\t* The server is keyed by `inputHash` (hex blake3 of the canonicalized,\n\t* system-stripped input messages). It returns one of three outcomes:\n\t*   - `{ outcome: \"hit\", response }` — a cached response to replay.\n\t*   - `{ outcome: \"miss\" }`          — no entry; caller latches live mode.\n\t*   - `{ outcome: \"live\" }`          — run this call live (COLD degrade).\n\t*\n\t* Error posture: a non-OK response or a transport error degrades to\n\t* `{ kind: \"live\" }` for THIS call only — it never throws and never latches\n\t* the process-wide live flag (only a real MISS does that). This keeps a flaky\n\t* cache backend from turning a replay into a crash.\n\t*/\n\tasync cache({ sessionId, replayTraceId, cacheUntil, inputHash }) {\n\t\tlet response;\n\t\ttry {\n\t\t\tresponse = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/rollouts/${sessionId}/cache`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: this.headers(),\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\treplayTraceId,\n\t\t\t\t\tcacheUntil,\n\t\t\t\t\tinputHash\n\t\t\t\t})\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tlogger$1.warn(`Debug cache lookup failed, running live: ${errorMessage(e)}`);\n\t\t\treturn { kind: \"live\" };\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tlogger$1.warn(`Debug cache lookup returned ${response.status}, running live`);\n\t\t\treturn { kind: \"live\" };\n\t\t}\n\t\tlet body;\n\t\ttry {\n\t\t\tbody = await response.json();\n\t\t} catch (e) {\n\t\t\tlogger$1.warn(`Failed to parse debug cache response, running live: ${errorMessage(e)}`);\n\t\t\treturn { kind: \"live\" };\n\t\t}\n\t\tswitch (body.outcome) {\n\t\t\tcase \"hit\":\n\t\t\t\tif (body.response === null || body.response === void 0) {\n\t\t\t\t\tlogger$1.warn(\"Debug cache HIT had no response payload, running live\");\n\t\t\t\t\treturn { kind: \"live\" };\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"hit\",\n\t\t\t\t\tcached: toCachedSpan(body.response)\n\t\t\t\t};\n\t\t\tcase \"miss\": return { kind: \"miss\" };\n\t\t\tcase \"live\": return { kind: \"live\" };\n\t\t\tdefault:\n\t\t\t\tlogger$1.warn(`Unknown debug cache outcome \"${body.outcome}\", running live`);\n\t\t\t\treturn { kind: \"live\" };\n\t\t}\n\t}\n\tasync delete({ sessionId }) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/rollouts/${sessionId}`, {\n\t\t\tmethod: \"DELETE\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n};\n//#endregion\n//#region src/resources/signals.ts\n/** Signals CRUD over the CLI user-token surface (`/v1/cli/signals`). */\nvar SignalsResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* Every signal route answers errors as `{ error: \"<message>\" }`, and those\n\t* messages are written to be shown to the user verbatim (e.g. \"A signal named\n\t* X already exists in this project\"). The shared `handleError` would surface\n\t* the raw JSON body, so unwrap the envelope here and fall back to it when the\n\t* body isn't the expected shape.\n\t*/\n\tasync raiseSignalError(response) {\n\t\tconst body = await response.text();\n\t\tlet message = body;\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(body);\n\t\t\tif (typeof parsed?.error === \"string\" && parsed.error.length > 0) message = parsed.error;\n\t\t} catch {}\n\t\tthrow new Error(`${response.status} ${message}`);\n\t}\n\tasync list(name) {\n\t\tconst query = name ? `?${new URLSearchParams({ name }).toString()}` : \"\";\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/signals${query}`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.raiseSignalError(response);\n\t\tconst body = await response.json();\n\t\treturn Array.isArray(body?.signals) ? body.signals : [];\n\t}\n\tasync get(signalId) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/signals/${signalId}`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.raiseSignalError(response);\n\t\treturn response.json();\n\t}\n\t/**\n\t* Historical judge definitions for `signalId`, oldest first. Distinct from\n\t* `GET /signals/{id}`'s `version` field, which is only the current pointer.\n\t* 404 if that id isn't in this project; an empty list only if the signal\n\t* exists with no version rows.\n\t*/\n\tasync listVersions(signalId) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/signals/${signalId}/versions`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.raiseSignalError(response);\n\t\tconst body = await response.json();\n\t\treturn Array.isArray(body?.versions) ? body.versions : [];\n\t}\n\tasync create(options) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/signals`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify(options)\n\t\t});\n\t\tif (!response.ok) await this.raiseSignalError(response);\n\t\treturn response.json();\n\t}\n\t/**\n\t* PATCH, not PUT: only the keys present in `options` are sent, so the server\n\t* leaves everything else as stored. An explicit `null` on `sampleRate` must\n\t* survive serialization (it means \"clear\"), so nulls are NOT stripped here.\n\t*/\n\tasync update(signalId, options) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/signals/${signalId}`, {\n\t\t\tmethod: \"PATCH\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify(options)\n\t\t});\n\t\tif (!response.ok) await this.raiseSignalError(response);\n\t\treturn response.json();\n\t}\n\t/** Deletes the signal, its triggers, its alerts, and its ClickHouse events. */\n\tasync delete(signalId) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/signals/${signalId}`, {\n\t\t\tmethod: \"DELETE\",\n\t\t\theaders: this.headers()\n\t\t});\n\t\tif (!response.ok) await this.raiseSignalError(response);\n\t\treturn response.json();\n\t}\n};\n//#endregion\n//#region src/resources/sql.ts\nvar SqlResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\tasync query(sql, parameters = {}) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/sql/query`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { ...this.headers() },\n\t\t\tbody: JSON.stringify({\n\t\t\t\tquery: sql,\n\t\t\t\tparameters\n\t\t\t})\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn (await response.json()).data;\n\t}\n\t/**\n\t* Fetch the queryable tables, columns, and enums. Server-rendered from\n\t* app-server's `query_engine::schema`, so it is the same source that backs\n\t* the MCP `query_laminar_sql` tool description — never a client-side copy.\n\t*/\n\tasync schema() {\n\t\tconst response = await fetch(`${this.baseHttpUrl}${this.apiPrefix}/sql/schema`, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: { ...this.headers() }\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn await response.json();\n\t}\n};\n//#endregion\n//#region src/resources/tags.ts\n/** Resource for tagging traces. */\nvar TagsResource = class extends BaseResource {\n\t/** Resource for tagging traces. */\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* Tag a trace with a list of tags. Note that the trace must be ended before\n\t* tagging it. You may want to call `await Laminar.flush()` after the trace\n\t* that you want to tag.\n\t*\n\t* @param {string | StringUUID} trace_id - The trace id to tag.\n\t* @param {string[] | string} tags - The tag or list of tags to add to the trace.\n\t* @returns {Promise<any>} The response from the server.\n\t* @example\n\t* ```javascript\n\t* import { Laminar, observe, LaminarClient } from \"@lmnr-ai/lmnr\";\n\t* Laminar.initialize();\n\t* const client = new LaminarClient();\n\t* let traceId: StringUUID | null = null;\n\t* // Make sure this is called outside of traced context.\n\t* await observe(\n\t*   {\n\t*     name: \"my-trace\",\n\t*   },\n\t*   async () => {\n\t*     traceId = await Laminar.getTraceId();\n\t*     await foo();\n\t*   },\n\t* );\n\t*\n\t* // or make sure the trace is ended by this point.\n\t* await Laminar.flush();\n\t* if (traceId) {\n\t*   await client.tags.tag(traceId, [\"tag1\", \"tag2\"]);\n\t* }\n\t* ```\n\t*/\n\tasync tag(trace_id, tags) {\n\t\tconst traceTags = Array.isArray(tags) ? tags : [tags];\n\t\tconst formattedTraceId = isStringUUID(trace_id) ? trace_id : otelTraceIdToUUID(trace_id);\n\t\tconst url = this.baseHttpUrl + \"/v1/tag\";\n\t\tconst payload = {\n\t\t\ttraceId: formattedTraceId,\n\t\t\tnames: traceTags\n\t\t};\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify(payload)\n\t\t});\n\t\tif (!response.ok) await this.handleError(response);\n\t\treturn response.json();\n\t}\n};\n//#endregion\n//#region src/resources/traces.ts\n/** Resource for post-factum operations on existing traces. */\nconst logger = initializeLogger();\nvar TracesResource = class extends BaseResource {\n\t/** Resource for post-factum operations on existing traces. */\n\tconstructor(baseHttpUrl, auth) {\n\t\tsuper(baseHttpUrl, auth);\n\t}\n\t/**\n\t* Push a metadata patch to an existing trace.\n\t*\n\t* The patch is shallow-merged server-side into the trace's existing metadata\n\t* (`existing || patch`, last-write-wins per top-level key). Useful for\n\t* attaching post-factum signals — quality scores, human edits, triage labels —\n\t* to a trace that has already finished. The patch does NOT extend `endTime`\n\t* or change tokens / cost / top span / tags / span names. `numSpans` is\n\t* incremented by 1 (paid by the virtual span that carried the patch through\n\t* the ingestion queue) so the new ClickHouse row beats the prior version on\n\t* `ReplacingMergeTree(numSpans)`. No row is added to the `spans` table.\n\t*\n\t* Compared to `Laminar.setTraceMetadata` (which sets metadata on the\n\t* currently in-flight trace via OpenTelemetry attributes), this method\n\t* operates on a finished trace by trace id, so it must be called after the\n\t* trace has been flushed.\n\t*\n\t* A 404 response (the trace was not found in the project — typically because\n\t* it has not been flushed yet) is logged as a warning and the call returns\n\t* without throwing, since the 404 may be expected when pushing too soon\n\t* after the trace run. Pass `failOnNotFound: true` to throw instead (e.g.\n\t* CLI callers that must report the failure). Any other non-OK status throws.\n\t*\n\t* @param traceId - The trace id to push metadata to. Accepts a UUID string\n\t*   or a 32-char OTel hex trace id.\n\t* @param metadata - The metadata patch. Top-level keys are merged into the\n\t*   trace's existing metadata. Must be non-empty (the server rejects empty\n\t*   patches with 400).\n\t* @param options - `failOnNotFound`: throw on 404 instead of warn-and-return.\n\t* @example\n\t* ```typescript\n\t* import { Laminar, observe, LaminarClient } from \"@lmnr-ai/lmnr\";\n\t* Laminar.initialize();\n\t* const client = new LaminarClient();\n\t*\n\t* let traceId: string | null = null;\n\t* await observe({ name: \"generate\" }, async () => {\n\t*   traceId = await Laminar.getTraceId();\n\t* });\n\t* await Laminar.flush();\n\t*\n\t* if (traceId) {\n\t*   await client.traces.pushMetadata(traceId, {\n\t*     score: 0.85,\n\t*     reviewer: \"alice\",\n\t*     needsReview: false,\n\t*   });\n\t* }\n\t* ```\n\t*/\n\tasync pushMetadata(traceId, metadata, options) {\n\t\tif (!metadata || Object.keys(metadata).length === 0) throw new Error(\"metadata must be a non-empty object\");\n\t\tconst formattedTraceId = isStringUUID(traceId) ? traceId : otelTraceIdToUUID(traceId);\n\t\tconst url = this.baseHttpUrl + this.apiPrefix + \"/traces/metadata\";\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: this.headers(),\n\t\t\tbody: JSON.stringify({\n\t\t\t\ttraceId: formattedTraceId,\n\t\t\t\tmetadata\n\t\t\t})\n\t\t});\n\t\tif (response.status === 404) {\n\t\t\tconst message = `Trace ${formattedTraceId} not found. The trace may not have been flushed yet — call await Laminar.flush() and retry.`;\n\t\t\tif (options?.failOnNotFound) throw new Error(message);\n\t\t\tlogger.warn(message);\n\t\t\treturn;\n\t\t}\n\t\tif (!response.ok) await this.handleError(response);\n\t}\n};\n//#endregion\n//#region src/index.ts\nvar LaminarClient = class LaminarClient {\n\tconstructor({ baseUrl, port, auth, projectApiKey, cliUserProjectId } = {}) {\n\t\tloadEnv();\n\t\tthis.auth = LaminarClient.normalizeAuth(auth, projectApiKey, cliUserProjectId);\n\t\tconst resolvedBaseUrl = baseUrl ?? process.env.LMNR_BASE_URL;\n\t\tthis.configuredUrl = resolvedBaseUrl;\n\t\tconst httpPort = port ?? (resolvedBaseUrl?.match(/:\\d{1,5}$/g) ? parseInt(resolvedBaseUrl.match(/:\\d{1,5}$/g)[0].slice(1)) : 443);\n\t\tconst baseUrlNoPort = resolvedBaseUrl?.replace(/\\/$/, \"\").replace(/:\\d{1,5}$/g, \"\");\n\t\tthis.baseUrl = `${baseUrlNoPort ?? \"https://api.lmnr.ai\"}:${httpPort}`;\n\t\tthis._browserEvents = new BrowserEventsResource(this.baseUrl, this.auth);\n\t\tthis._cli = new CliResource(this.baseUrl, this.auth);\n\t\tthis._datasets = new DatasetsResource(this.baseUrl, this.auth);\n\t\tthis._evals = new EvalsResource(this.baseUrl, this.auth);\n\t\tthis._evaluators = new EvaluatorsResource(this.baseUrl, this.auth);\n\t\tthis._llmProfiles = new LlmProfilesResource(this.baseUrl, this.auth);\n\t\tthis._rolloutSessions = new RolloutSessionsResource(this.baseUrl, this.auth);\n\t\tthis._signals = new SignalsResource(this.baseUrl, this.auth);\n\t\tthis._sql = new SqlResource(this.baseUrl, this.auth);\n\t\tthis._tags = new TagsResource(this.baseUrl, this.auth);\n\t\tthis._traces = new TracesResource(this.baseUrl, this.auth);\n\t}\n\t/**\n\t* The fully-resolved API origin every resource fetches from, e.g.\n\t* `http://localhost:8000`. Already normalized: trailing slash removed, any\n\t* port embedded in `baseUrl` stripped, and the effective port appended.\n\t*\n\t* Exposed so callers can name the real address in diagnostics instead of\n\t* rebuilding it from `baseUrl` + `port` — that reconstruction drifts from\n\t* this normalization and prints things like `http://host:8000:9000`.\n\t*/\n\tget apiBaseUrl() {\n\t\treturn this.baseUrl;\n\t}\n\t/**\n\t* Normalize the constructor's auth inputs into a {@link LaminarAuth} union.\n\t* Precedence: an explicit `auth` wins; otherwise the legacy\n\t* `projectApiKey` (+ optional `cliUserProjectId`) is mapped — a present\n\t* `cliUserProjectId` selects the user-token surface, otherwise the project\n\t* key surface. Falls back to `LMNR_PROJECT_API_KEY` as a project key.\n\t*/\n\tstatic normalizeAuth(auth, projectApiKey, cliUserProjectId) {\n\t\tif (auth) return auth;\n\t\tconst key = projectApiKey ?? process.env.LMNR_PROJECT_API_KEY;\n\t\tif (cliUserProjectId) return {\n\t\t\ttype: \"userToken\",\n\t\t\ttoken: key,\n\t\t\tprojectId: cliUserProjectId\n\t\t};\n\t\treturn {\n\t\t\ttype: \"apiKey\",\n\t\t\tkey\n\t\t};\n\t}\n\t/**\n\t* The base URL this client was configured with (constructor arg or\n\t* `LMNR_BASE_URL`), before port normalization; `undefined` when the client\n\t* fell back to the default Laminar Cloud URL. Lets integrations that accept\n\t* a pre-constructed client derive companion transports (e.g. a span\n\t* exporter) from the same connection settings.\n\t*/\n\tget configuredBaseUrl() {\n\t\treturn this.configuredUrl;\n\t}\n\t/**\n\t* The project API key this client authenticates with, or `undefined` when\n\t* it uses user-token auth.\n\t*/\n\tget apiKey() {\n\t\treturn this.auth.type === \"apiKey\" ? this.auth.key : void 0;\n\t}\n\tget browserEvents() {\n\t\treturn this._browserEvents;\n\t}\n\tget cli() {\n\t\treturn this._cli;\n\t}\n\tget datasets() {\n\t\treturn this._datasets;\n\t}\n\tget evals() {\n\t\treturn this._evals;\n\t}\n\tget evaluators() {\n\t\treturn this._evaluators;\n\t}\n\tget llmProfiles() {\n\t\treturn this._llmProfiles;\n\t}\n\tget signals() {\n\t\treturn this._signals;\n\t}\n\tget rolloutSessions() {\n\t\treturn this._rolloutSessions;\n\t}\n\tget sql() {\n\t\treturn this._sql;\n\t}\n\tget tags() {\n\t\treturn this._tags;\n\t}\n\tget traces() {\n\t\treturn this._traces;\n\t}\n};\n//#endregion\nexport { LaminarClient, RolloutSessionsResource };\n\n//# sourceMappingURL=index.mjs.map","","export const SPAN_INPUT = \"lmnr.span.input\";\nexport const SPAN_OUTPUT = \"lmnr.span.output\";\nexport const SPAN_TYPE = \"lmnr.span.type\";\nexport const SPAN_PATH = \"lmnr.span.path\";\nexport const SPAN_IDS_PATH = \"lmnr.span.ids_path\";\nexport const PARENT_SPAN_PATH = \"lmnr.span.parent_path\";\nexport const PARENT_SPAN_IDS_PATH = \"lmnr.span.parent_ids_path\";\nexport const SPAN_INSTRUMENTATION_SOURCE = \"lmnr.span.instrumentation_source\";\nexport const SPAN_SDK_VERSION = \"lmnr.span.sdk_version\";\nexport const SPAN_LANGUAGE_VERSION = \"lmnr.span.language_version\";\nexport const SPAN_INSTRUMENTATION_SCOPE_NAME =\n  \"lmnr.span.instrumentation_scope.name\";\nexport const SPAN_INSTRUMENTATION_SCOPE_VERSION =\n  \"lmnr.span.instrumentation_scope.version\";\nexport const OVERRIDE_PARENT_SPAN = \"lmnr.internal.override_parent_span\";\nexport const TRACE_HAS_BROWSER_SESSION = \"lmnr.internal.has_browser_session\";\nexport const EXTRACTED_FROM_NEXT_JS = \"lmnr.span.extracted_from.next_js\";\nexport const HUMAN_EVALUATOR_OPTIONS = \"lmnr.span.human_evaluator_options\";\nexport const ASSOCIATION_PROPERTIES = \"lmnr.association.properties\";\nexport const SESSION_ID = \"lmnr.association.properties.session_id\";\nexport const USER_ID = \"lmnr.association.properties.user_id\";\nexport const TRACE_TYPE = \"lmnr.association.properties.trace_type\";\n\nexport const ASSOCIATION_PROPERTIES_OVERRIDES: Record<string, string> = {\n  span_type: SPAN_TYPE,\n};\n\nexport const LaminarAttributes = {\n  // == This is the minimum set of attributes for a proper LLM span ==\n  //\n  INPUT_TOKEN_COUNT: \"gen_ai.usage.input_tokens\",\n  OUTPUT_TOKEN_COUNT: \"gen_ai.usage.output_tokens\",\n  TOTAL_TOKEN_COUNT: \"llm.usage.total_tokens\",\n  // TODO: Update to gen_ai.provider.name\n  PROVIDER: \"gen_ai.system\",\n  REQUEST_MODEL: \"gen_ai.request.model\",\n  RESPONSE_MODEL: \"gen_ai.response.model\",\n  //\n  // == End of minimum set ==\n  // == Additional attributes ==\n  //\n  INPUT_COST: \"gen_ai.usage.input_cost\",\n  OUTPUT_COST: \"gen_ai.usage.output_cost\",\n  TOTAL_COST: \"gen_ai.usage.cost\",\n  //\n  // == End of additional attributes ==\n};\n","import {\n  DebugContext,\n  errorMessage,\n  LaminarSpanContext,\n  TraceType,\n  TracingLevel,\n} from \"@lmnr-ai/types\";\nimport { AttributeValue, SpanContext, TraceFlags } from \"@opentelemetry/api\";\nimport { config } from \"dotenv\";\nimport * as path from \"path\";\nimport pino, { Level } from \"pino\";\nimport { PinoPretty } from \"pino-pretty\";\nimport { fileURLToPath } from \"url\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { ASSOCIATION_PROPERTIES } from \"./opentelemetry-lib/tracing/attributes\";\n\nexport function initializeLogger(options?: {\n  colorize?: boolean;\n  level?: Level;\n}) {\n  const colorize = options?.colorize ?? true;\n  const level =\n    options?.level ??\n    (process.env.LMNR_LOG_LEVEL?.toLowerCase()?.trim() as Level) ??\n    \"info\";\n\n  return pino(\n    {\n      level,\n    },\n    PinoPretty({\n      colorize,\n      minimumLevel: level,\n    }),\n  );\n}\n\nconst logger = initializeLogger();\n\nexport type StringUUID = `${string}-${string}-${string}-${string}-${string}`;\n\nexport const isStringUUID = (id: string): id is StringUUID =>\n  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id);\n\nexport const NIL_UUID: StringUUID = \"00000000-0000-0000-0000-000000000000\";\n\nexport const newUUID = (): StringUUID => {\n  // crypto.randomUUID is available in most of the modern browsers and node,\n  // but is not available in \"insecure\" contexts, e.g. not https, not localhost\n  // so we fallback to uuidv4 in those cases, which is less secure, but works\n  // just fine.\n  if (\n    typeof crypto !== \"undefined\" &&\n    typeof crypto.randomUUID === \"function\"\n  ) {\n    return crypto.randomUUID();\n  } else {\n    return uuidv4() as `${string}-${string}-${string}-${string}-${string}`;\n  }\n};\n\n// Coerce a hex trace id to the 32-char raw form an OTel `SpanContext`\n// requires. Unlike `otelTraceIdToUUID`, this returns plain hex (no dashes)\n// and truncates (`slice(-32)`) rather than producing invalid output for\n// longer-than-32-char inputs — callers passing ids from upstream frameworks\n// (e.g. Mastra) that occasionally emit non-canonical ids rely on that\n// truncation to stay within OTel's spec.\nexport const normalizeOtelTraceId = (traceId: string): string => {\n  let id = traceId.toLowerCase();\n  if (id.startsWith(\"0x\")) {\n    id = id.slice(2);\n  }\n  return id.padStart(32, \"0\").slice(-32);\n};\n\n// Raw-hex counterpart of `normalizeOtelTraceId` for 16-char span ids.\nexport const normalizeOtelSpanId = (spanId: string): string => {\n  let id = spanId.toLowerCase();\n  if (id.startsWith(\"0x\")) {\n    id = id.slice(2);\n  }\n  return id.padStart(16, \"0\").slice(-16);\n};\n\nexport const otelSpanIdToUUID = (spanId: string): string => {\n  let id = spanId.toLowerCase();\n  if (id.startsWith(\"0x\")) {\n    id = id.slice(2);\n  }\n  if (id.length !== 16) {\n    logger.warn(\n      `Span ID ${spanId} is not 16 hex chars long. ` +\n        \"This is not a valid OpenTelemetry span ID.\",\n    );\n  }\n\n  if (!/^[0-9a-f]+$/.test(id)) {\n    logger.error(\n      `Span ID ${spanId} is not a valid hex string. ` +\n        \"Generating a random UUID instead.\",\n    );\n    return newUUID();\n  }\n\n  return id\n    .padStart(32, \"0\")\n    .replace(\n      /^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/,\n      \"$1-$2-$3-$4-$5\",\n    );\n};\n\nexport const otelTraceIdToUUID = (traceId: string): StringUUID => {\n  let id = traceId.toLowerCase();\n  if (id.startsWith(\"0x\")) {\n    id = id.slice(2);\n  }\n  if (id.length !== 32) {\n    logger.warn(\n      `Trace ID ${traceId} is not 32 hex chars long. ` +\n        \"This is not a valid OpenTelemetry trace ID.\",\n    );\n  }\n  if (!/^[0-9a-f]+$/.test(id)) {\n    logger.error(\n      `Trace ID ${traceId} is not a valid hex string. ` +\n        \"Generating a random UUID instead.\",\n    );\n    return newUUID();\n  }\n\n  return id.replace(\n    /^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{12})$/,\n    \"$1-$2-$3-$4-$5\",\n  ) as StringUUID;\n};\n\nexport const uuidToOtelTraceId = (uuid: string): string =>\n  uuid.replace(/-/g, \"\");\nexport const uuidToOtelSpanId = (uuid: string): string =>\n  uuid.replace(/-/g, \"\").slice(16);\n\n/**\n * This is a simple implementation of a semaphore to replicate\n * the behavior of the `asyncio.Semaphore` in Python.\n */\nexport class Semaphore {\n  /**\n   * Number of permits available.\n   */\n  private _value: number;\n  /**\n   * List of promises that will be resolved when a permit becomes available.\n   */\n  private _waiters: ((...args: any[]) => any)[] = [];\n\n  constructor(value = 1) {\n    if (value < 0) {\n      throw new Error(\"Semaphore value must be >= 0\");\n    }\n    this._value = value;\n    this._waiters = [];\n  }\n\n  async acquire() {\n    if (this._value > 0) {\n      this._value--;\n      return;\n    }\n\n    // Create a promise that will be resolved when a permit becomes available\n    return new Promise((resolve) => {\n      this._waiters.push(resolve);\n    });\n  }\n\n  release() {\n    if (this._waiters.length > 0) {\n      // If there are waiters, wake up the first one\n      const resolve = this._waiters.shift();\n      resolve?.();\n    } else {\n      this._value++;\n    }\n  }\n\n  // Python-like context manager functionality\n  async using<T>(fn: (...args: any[]) => Promise<T>) {\n    try {\n      await this.acquire();\n      return await fn();\n    } finally {\n      this.release();\n    }\n  }\n}\n\nexport const tryToOtelSpanContext = (\n  spanContext:\n    | LaminarSpanContext\n    | Record<string, unknown>\n    | string\n    | SpanContext,\n): SpanContext => {\n  if (typeof spanContext === \"string\") {\n    try {\n      const record = JSON.parse(spanContext) as Record<string, unknown>;\n      return recordToOtelSpanContext(record);\n    } catch (e) {\n      throw new Error(\n        `Failed to parse span context ${spanContext}. ` +\n          \"The string must be a json representation of a LaminarSpanContext.\" +\n          `Error: ${errorMessage(e)}`,\n      );\n    }\n  } else if (isRecord(spanContext)) {\n    // This covers the `LaminarSpanContext` case too.\n    return recordToOtelSpanContext(spanContext);\n  } else if (\n    typeof spanContext.traceId === \"string\" &&\n    typeof spanContext.spanId === \"string\" &&\n    spanContext.traceId.length === 32 &&\n    spanContext.spanId.length === 16\n  ) {\n    logger.warn(\n      \"The span context is already an OpenTelemetry SpanContext. \" +\n        \"Returning it as is. Please use `LaminarSpanContext` objects instead.\",\n    );\n    return spanContext;\n  } else {\n    throw new Error(\n      `Invalid span context ${JSON.stringify(spanContext)}. ` +\n        \"Must be a LaminarSpanContext or its json representation.\",\n    );\n  }\n};\n\nconst recordToOtelSpanContext = (\n  record: Record<string, unknown>,\n): SpanContext => {\n  if (\n    (typeof record.spanId === \"string\" && typeof record.traceId === \"string\") ||\n    (typeof record.span_id === \"string\" && typeof record.trace_id === \"string\")\n  ) {\n    return {\n      spanId: uuidToOtelSpanId(\n        (record?.spanId as string) ?? (record?.[\"span_id\"] as string),\n      ),\n      traceId: uuidToOtelTraceId(\n        (record?.traceId as string) ?? (record?.[\"trace_id\"] as string),\n      ),\n      isRemote: record?.isRemote ?? record?.[\"is_remote\"] ?? false,\n      traceFlags: record?.traceFlags ?? TraceFlags.SAMPLED,\n    } as SpanContext;\n  } else {\n    throw new Error(\n      `Invalid span context ${JSON.stringify(record)}. ` +\n        \"Must be a json representation of a LaminarSpanContext.\",\n    );\n  }\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n  typeof value === \"object\" && !Array.isArray(value) && value !== null;\n\n/**\n * Deserialize a LaminarSpanContext from a string or record.\n * Handles both camelCase and snake_case keys for cross-language compatibility.\n *\n * @param data - The data to deserialize (string or record)\n * @returns The deserialized LaminarSpanContext\n * @throws Error if the data is invalid\n */\nexport const deserializeLaminarSpanContext = (\n  data: Record<string, unknown> | string,\n): LaminarSpanContext => {\n  if (typeof data === \"string\") {\n    try {\n      const record = JSON.parse(data) as Record<string, unknown>;\n      return deserializeLaminarSpanContext(record);\n    } catch (e) {\n      throw new Error(`Failed to parse LaminarSpanContext: ${errorMessage(e)}`);\n    }\n  }\n\n  if (!isRecord(data)) {\n    throw new Error(\"Invalid LaminarSpanContext: must be a string or object\");\n  }\n\n  // Handle both camelCase and snake_case for all fields\n  const traceId = data.traceId ?? data.trace_id;\n  const spanId = data.spanId ?? data.span_id;\n  const isRemote = data.isRemote ?? data.is_remote ?? false;\n  const spanPath = data.spanPath ?? data.span_path;\n  const spanIdsPath = data.spanIdsPath ?? data.span_ids_path;\n  const userId = data.userId ?? data.user_id;\n  const sessionId = data.sessionId ?? data.session_id;\n  const metadata = data.metadata;\n  const traceType = data.traceType ?? data.trace_type;\n  const tracingLevel = data.tracingLevel ?? data.tracing_level;\n  const debug = data.debug;\n\n  if (typeof traceId !== \"string\" || typeof spanId !== \"string\") {\n    throw new Error(\n      \"Invalid LaminarSpanContext: traceId and spanId must be strings\",\n    );\n  }\n\n  // Validate UUID format\n  if (!isStringUUID(traceId) || !isStringUUID(spanId)) {\n    throw new Error(\n      \"Invalid LaminarSpanContext: traceId and spanId must be valid UUIDs\",\n    );\n  }\n\n  return {\n    traceId: traceId,\n    spanId: spanId,\n    isRemote: Boolean(isRemote),\n    spanPath: Array.isArray(spanPath) ? (spanPath as string[]) : undefined,\n    spanIdsPath: Array.isArray(spanIdsPath)\n      ? (spanIdsPath as StringUUID[])\n      : undefined,\n    userId: userId as string | undefined,\n    sessionId: sessionId as string | undefined,\n    metadata: metadata as Record<string, unknown> | undefined,\n    traceType: traceType as TraceType | undefined,\n    tracingLevel: tracingLevel as TracingLevel | undefined,\n    debug: isRecord(debug) ? deserializeDebugContext(debug) : undefined,\n  };\n};\n\n/**\n * Normalize a value to a canonical lowercase UUID string, or undefined.\n *\n * The debug block's `sessionId` / `replayTraceId` are always full ids; a value\n * that isn't UUID-shaped is dropped (treated as absent) rather than thrown, so\n * a partially-broken block never breaks span-context parsing.\n */\nconst asString = (value: unknown): string | undefined =>\n  typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/**\n * Parse a debug block, accepting camelCase and snake_case. All ids are kept\n * VERBATIM: the producer emits the run's exact session / replay-trace /\n * cache-until strings (un-normalized — `LMNR_DEBUG_SESSION_ID` may be an\n * arbitrary non-UUID value), so the consumer must round-trip them unchanged or\n * a downstream run never joins the run. Keep line-comparable with the Python\n * `DebugContext.deserialize`.\n */\nconst deserializeDebugContext = (\n  data: Record<string, unknown>,\n): DebugContext => ({\n  // Strict `=== true`, NOT Boolean(...): the producer always emits a real\n  // boolean, so anything else (e.g. the string \"false\", which is truthy) is a\n  // malformed/forged block and must NOT arm a downstream runtime.\n  enabled: data.enabled === true,\n  sessionId: asString(data.sessionId ?? data.session_id),\n  replayTraceId: asString(data.replayTraceId ?? data.replay_trace_id),\n  cacheUntil: asString(data.cacheUntil ?? data.cache_until),\n});\n\nexport const getDirname = () => {\n  if (typeof __dirname !== \"undefined\") {\n    return __dirname;\n  }\n\n  if (typeof import.meta?.url !== \"undefined\") {\n    return path.dirname(fileURLToPath(import.meta.url));\n  }\n\n  return process.cwd();\n};\n\nexport const MAX_MANUAL_SPAN_PAYLOAD_SIZE = 1024 * 1024 * 10; // 10MB\nexport const TRUNCATION_SUFFIX = \"...[Laminar: truncated]\";\n\n/**\n * Cut an oversized span payload down to the limit rather than dropping it.\n *\n * Keeping the leading bytes preserves the start of the value, which is the useful part when\n * debugging. Mirrors `_truncate_payload` in the Python SDK.\n *\n * Callers pass the result of `JSON.stringify`, whose TS signature claims `string` but which\n * actually returns `undefined` for a top-level `undefined`, function, or symbol. Guard at\n * runtime and hand such values straight back: `setAttribute` treats them as a no-op, which is\n * the behaviour these payloads had before truncation existed.\n */\nexport const truncateSpanPayload = (\n  serialized: string,\n  kind: \"input\" | \"output\",\n): string => {\n  if (typeof serialized !== \"string\") {\n    return serialized;\n  }\n  if (serialized.length <= MAX_MANUAL_SPAN_PAYLOAD_SIZE) {\n    return serialized;\n  }\n  logger.warn(\n    `Laminar: span ${kind} is ${serialized.length} bytes, which exceeds the ` +\n      `${MAX_MANUAL_SPAN_PAYLOAD_SIZE} byte limit. Truncating to the limit; ` +\n      `the recorded value will not be valid JSON.`,\n  );\n  const keep = MAX_MANUAL_SPAN_PAYLOAD_SIZE - TRUNCATION_SUFFIX.length;\n  return serialized.slice(0, keep) + TRUNCATION_SUFFIX;\n};\n\nexport const slicePayload = <T>(value: T, length: number) => {\n  if (value === null || value === undefined) {\n    return value;\n  }\n\n  const str = JSON.stringify(value);\n  if (str.length <= length) {\n    return value;\n  }\n\n  return str.slice(0, length) + \"...\";\n};\n\nexport const isOtelAttributeValueType = (\n  value: unknown,\n): value is AttributeValue => {\n  if (\n    typeof value === \"string\" ||\n    typeof value === \"number\" ||\n    typeof value === \"boolean\"\n  ) {\n    return true;\n  }\n\n  if (Array.isArray(value)) {\n    const allStrings = value.every(\n      (value) => value == null || typeof value === \"string\",\n    );\n    const allNumbers = value.every(\n      (value) => value == null || typeof value === \"number\",\n    );\n    const allBooleans = value.every(\n      (value) => value == null || typeof value === \"boolean\",\n    );\n    return allStrings || allNumbers || allBooleans;\n  }\n  return false;\n};\n\nexport const metadataToAttributes = (\n  metadata: Record<string, unknown>,\n): Record<string, AttributeValue> =>\n  Object.fromEntries(\n    Object.entries(metadata).map(([key, value]) => {\n      if (isOtelAttributeValueType(value)) {\n        return [`${ASSOCIATION_PROPERTIES}.metadata.${key}`, value];\n      } else {\n        return [\n          `${ASSOCIATION_PROPERTIES}.metadata.${key}`,\n          JSON.stringify(value),\n        ];\n      }\n    }),\n  );\n\n/**\n * Get OTEL environment variable with priority order.\n * Checks in order:\n * 1. OTEL_EXPORTER_OTLP_TRACES_{varName}\n * 2. OTEL_EXPORTER_OTLP_{varName}\n * 3. OTEL_{varName}\n *\n * @param varName - The variable name (e.g., 'ENDPOINT', 'HEADERS', 'PROTOCOL')\n * @returns The environment variable value or undefined if not found\n */\nexport const getOtelEnvVar = (varName: string): string | undefined => {\n  const candidates = [\n    `OTEL_EXPORTER_OTLP_TRACES_${varName}`,\n    `OTEL_EXPORTER_OTLP_${varName}`,\n    `OTEL_${varName}`,\n  ];\n\n  for (const candidate of candidates) {\n    const value = process?.env?.[candidate];\n    if (value) {\n      return value;\n    }\n  }\n  return undefined;\n};\n\n/**\n * Check if OTEL configuration is available.\n * @returns true if OTEL endpoint is configured\n */\nexport const hasOtelConfig = (): boolean => !!getOtelEnvVar(\"ENDPOINT\");\n\n/**\n * Parse OTEL headers string into a record object.\n * Format: key1=value1,key2=value2\n * Values are URL-decoded.\n *\n * @param headersStr - Headers string in OTEL format\n * @returns Parsed headers object\n */\nexport const parseOtelHeaders = (\n  headersStr: string | undefined,\n): Record<string, string> => {\n  if (!headersStr) {\n    return {};\n  }\n\n  const headers: Record<string, string> = {};\n  for (const pair of headersStr.split(\",\")) {\n    const equalIndex = pair.indexOf(\"=\");\n    if (equalIndex !== -1) {\n      // Manually split instead of .split('=', 2) because\n      // the latter only returns the first 2 elements of the array after the split\n      const key = pair.substring(0, equalIndex).trim();\n      const value = pair.substring(equalIndex + 1).trim();\n      headers[key] = decodeURIComponent(value);\n    }\n  }\n  return headers;\n};\n\n/**\n * Validate that either Laminar API key or OTEL configuration is present.\n * Throws an error if neither is configured.\n *\n * @param apiKey - The Laminar API key (if provided)\n * @throws Error if neither API key nor OTEL configuration is present\n */\nexport const validateTracingConfig = (apiKey?: string): void => {\n  if (!apiKey && !hasOtelConfig()) {\n    throw new Error(\n      \"Please initialize the Laminar object with your project API key \" +\n        \"or set the LMNR_PROJECT_API_KEY environment variable, \" +\n        \"or configure OTEL environment variables (OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, etc.)\",\n    );\n  }\n};\n\nexport const loadEnv = (options?: {\n  quiet?: boolean;\n  paths?: string[];\n}): void => {\n  const nodeEnv = process.env.NODE_ENV || \"development\";\n  const envDir = process.cwd();\n\n  // Files to load in order (lowest to highest priority)\n  // Later files override earlier ones\n  const envFiles = [\n    \".env\",\n    \".env.local\",\n    `.env.${nodeEnv}`,\n    `.env.${nodeEnv}.local`,\n  ];\n\n  const logLevel = process.env.LMNR_LOG_LEVEL ?? \"info\";\n  const verbose = [\"debug\", \"trace\"].includes(logLevel.trim().toLowerCase());\n\n  const quiet = options?.quiet ?? !verbose;\n\n  config({\n    path:\n      options?.paths ??\n      envFiles.map((envFile) => path.resolve(envDir, envFile)),\n    quiet,\n  });\n};\n\n/**\n * Converts an API base URL to the frontend/web URL.\n * - Converts https://api.lmnr.ai to https://www.laminar.sh\n * - Removes trailing slashes\n * - For localhost/127.0.0.1, ensures a port is specified (defaults to 5667)\n *\n * @param baseUrl - The API base URL (defaults to \"https://api.lmnr.ai\")\n * @returns The frontend URL\n */\nexport const getFrontendUrl = (\n  baseUrl?: string,\n  frontendPort?: number,\n): string => {\n  let url = baseUrl ?? \"https://api.lmnr.ai\";\n  if (url === \"https://api.lmnr.ai\") {\n    url = \"https://www.laminar.sh\";\n  }\n  url = url.replace(/\\/$/, \"\");\n\n  if (/localhost|127\\.0\\.0\\.1/.test(url)) {\n    const port = frontendPort ?? url.match(/:\\d{1,5}$/g)?.[0]?.slice(1) ?? 5667;\n    if (/:(\\d{1,5})$/.test(url)) {\n      // URL has a port, replace it\n      url = url.replace(/:\\d{1,5}$/g, `:${port}`);\n    } else {\n      // URL has no port, append it\n      url = `${url}:${port}`;\n    }\n  }\n  return url;\n};\n"],"mappings":";;;;;;;;;;;;;;AAEA,MAAM,oBAAoB;;AAE1B,MAAM,qBAAqB;;;;;;;;AAU3B,IAAI,eAA+B,yBAAS,cAAc;CACzD,aAAa,SAAS;CACtB,aAAa,eAAe;CAC5B,aAAa,SAAS;CACtB,OAAO;AACR,EAAE,CAAC,CAAC;AAGJ,MAAM,gBAAgB,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;;;ACfrF,IAAIA,YAAU;AAGd,SAAS,iBAAiB;CACzB,IAAI,OAAO,YAAY,eAAe,QAAQ,YAAY,QAAQ,SAAS,MAAM,OAAO,QAAQ,QAAQ,SAAS;CACjH,IAAI,OAAO,cAAc,eAAe,UAAU,WAAW,OAAO,WAAW,UAAU;CACzF,OAAO;AACR;AAGA,IAAI,eAAe,MAAM;CACxB,YAAY,aAAa,MAAM;EAC9B,KAAK,cAAc;EACnB,KAAK,OAAO;EACZ,KAAK,aAA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