@lmnr-ai/lmnr 0.8.44 → 0.8.45

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 (33) hide show
  1. package/dist/cli.cjs +23 -25
  2. package/dist/cli.cjs.map +1 -1
  3. package/dist/cli.d.cts +1 -1
  4. package/dist/cli.d.mts +1 -1
  5. package/dist/cli.mjs +7 -8
  6. package/dist/cli.mjs.map +1 -1
  7. package/dist/{evaluations-RbBZb5yl.d.cts → evaluations-BHEE6fmA.d.cts} +17934 -8631
  8. package/dist/{evaluations-CVo0ms_r.d.mts → evaluations-BbIIQMLr.d.mts} +17934 -8631
  9. package/dist/{file-utils-1olUHMKC.mjs → file-utils-BtzEDUy6.mjs} +2 -2
  10. package/dist/file-utils-BtzEDUy6.mjs.map +1 -0
  11. package/dist/{file-utils-CMO5MuV9.cjs → file-utils-pZG20hHb.cjs} +6 -6
  12. package/dist/file-utils-pZG20hHb.cjs.map +1 -0
  13. package/dist/index.cjs +574 -435
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +1533 -437
  16. package/dist/index.d.mts +1533 -437
  17. package/dist/index.mjs +287 -148
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/opentelemetry-lib/instrumentation/temporal/workflow-interceptors.cjs +159 -62
  20. package/dist/opentelemetry-lib/instrumentation/temporal/workflow-interceptors.cjs.map +1 -1
  21. package/dist/opentelemetry-lib/instrumentation/temporal/workflow-interceptors.d.cts +3388 -250
  22. package/dist/opentelemetry-lib/instrumentation/temporal/workflow-interceptors.d.mts +3388 -250
  23. package/dist/opentelemetry-lib/instrumentation/temporal/workflow-interceptors.mjs +159 -62
  24. package/dist/opentelemetry-lib/instrumentation/temporal/workflow-interceptors.mjs.map +1 -1
  25. package/dist/{dist-BtB31bk1.cjs → utils-CatgN6Pb.cjs} +558 -558
  26. package/dist/utils-CatgN6Pb.cjs.map +1 -0
  27. package/dist/{dist-Cjres0a5.mjs → utils-UmlDPMxe.mjs} +552 -552
  28. package/dist/utils-UmlDPMxe.mjs.map +1 -0
  29. package/package.json +30 -30
  30. package/dist/dist-BtB31bk1.cjs.map +0 -1
  31. package/dist/dist-Cjres0a5.mjs.map +0 -1
  32. package/dist/file-utils-1olUHMKC.mjs.map +0 -1
  33. package/dist/file-utils-CMO5MuV9.cjs.map +0 -1
@@ -1,5 +1,4 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-CVvi-lCc.cjs");
2
- let _opentelemetry_api = require("@opentelemetry/api");
3
2
  let dotenv = require("dotenv");
4
3
  let path = require("path");
5
4
  let path$1 = require_rolldown_runtime.__toESM(path, 1);
@@ -8,8 +7,9 @@ let pino = require("pino");
8
7
  let pino$3 = require_rolldown_runtime.__toESM(pino, 1);
9
8
  pino = require_rolldown_runtime.__toESM(pino);
10
9
  let pino_pretty = require("pino-pretty");
11
- let url = require("url");
12
10
  let uuid = require("uuid");
11
+ let _opentelemetry_api = require("@opentelemetry/api");
12
+ let url = require("url");
13
13
  //#region ../types/dist/index.mjs
14
14
  /** Directory the debug-session file lives in, relative to the working dir. */
15
15
  const DEBUG_SESSION_DIR = ".lmnr";
@@ -30,73 +30,148 @@ let TracingLevel = /* @__PURE__ */ function(TracingLevel) {
30
30
  }({});
31
31
  const errorMessage = (error) => error instanceof Error ? error.message : String(error);
32
32
  //#endregion
33
- //#region package.json
34
- var version$1 = "0.8.44";
35
- //#endregion
36
- //#region src/opentelemetry-lib/tracing/attributes.ts
37
- const SPAN_INPUT = "lmnr.span.input";
38
- const SPAN_OUTPUT = "lmnr.span.output";
39
- const SPAN_TYPE = "lmnr.span.type";
40
- const SPAN_PATH = "lmnr.span.path";
41
- const SPAN_IDS_PATH = "lmnr.span.ids_path";
42
- const PARENT_SPAN_PATH = "lmnr.span.parent_path";
43
- const PARENT_SPAN_IDS_PATH = "lmnr.span.parent_ids_path";
44
- const SPAN_INSTRUMENTATION_SOURCE = "lmnr.span.instrumentation_source";
45
- const SPAN_SDK_VERSION = "lmnr.span.sdk_version";
46
- const SPAN_LANGUAGE_VERSION = "lmnr.span.language_version";
47
- const SPAN_INSTRUMENTATION_SCOPE_NAME = "lmnr.span.instrumentation_scope.name";
48
- const SPAN_INSTRUMENTATION_SCOPE_VERSION = "lmnr.span.instrumentation_scope.version";
49
- const TRACE_HAS_BROWSER_SESSION = "lmnr.internal.has_browser_session";
50
- const HUMAN_EVALUATOR_OPTIONS = "lmnr.span.human_evaluator_options";
51
- const ASSOCIATION_PROPERTIES = "lmnr.association.properties";
52
- const SESSION_ID = "lmnr.association.properties.session_id";
53
- const USER_ID = "lmnr.association.properties.user_id";
54
- const TRACE_TYPE = "lmnr.association.properties.trace_type";
55
- const ASSOCIATION_PROPERTIES_OVERRIDES = { "span_type": SPAN_TYPE };
56
- const LaminarAttributes = {
57
- INPUT_TOKEN_COUNT: "gen_ai.usage.input_tokens",
58
- OUTPUT_TOKEN_COUNT: "gen_ai.usage.output_tokens",
59
- TOTAL_TOKEN_COUNT: "llm.usage.total_tokens",
60
- PROVIDER: "gen_ai.system",
61
- REQUEST_MODEL: "gen_ai.request.model",
62
- RESPONSE_MODEL: "gen_ai.response.model",
63
- INPUT_COST: "gen_ai.usage.input_cost",
64
- OUTPUT_COST: "gen_ai.usage.output_cost",
65
- TOTAL_COST: "gen_ai.usage.cost"
33
+ //#region ../client/dist/index.mjs
34
+ var version$1 = "0.8.45";
35
+ function getLangVersion() {
36
+ if (typeof process !== "undefined" && process.versions && process.versions.node) return `node-${process.versions.node}`;
37
+ if (typeof navigator !== "undefined" && navigator.userAgent) return `browser-${navigator.userAgent}`;
38
+ return null;
39
+ }
40
+ var BaseResource = class {
41
+ constructor(baseHttpUrl, auth) {
42
+ this.baseHttpUrl = baseHttpUrl;
43
+ this.auth = auth;
44
+ this.credential = auth.type === "apiKey" ? auth.key : auth.token;
45
+ }
46
+ /** API path prefix: `/v1/cli` for CLI user-token auth, `/v1` otherwise. */
47
+ get apiPrefix() {
48
+ return this.auth.type === "userToken" ? "/v1/cli" : "/v1";
49
+ }
50
+ headers() {
51
+ return {
52
+ Authorization: `Bearer ${this.credential}`,
53
+ "Content-Type": "application/json",
54
+ Accept: "application/json",
55
+ ...this.auth.type === "userToken" ? { "x-lmnr-project-id": this.auth.projectId } : {}
56
+ };
57
+ }
58
+ async handleError(response) {
59
+ const errorMsg = await response.text();
60
+ throw new Error(`${response.status} ${errorMsg}`);
61
+ }
62
+ };
63
+ var BrowserEventsResource = class extends BaseResource {
64
+ constructor(baseHttpUrl, auth) {
65
+ super(baseHttpUrl, auth);
66
+ }
67
+ async send({ sessionId, traceId, events }) {
68
+ const payload = {
69
+ sessionId,
70
+ traceId,
71
+ events,
72
+ source: getLangVersion() ?? "javascript",
73
+ sdkVersion: version$1
74
+ };
75
+ const jsonString = JSON.stringify(payload);
76
+ const compressedStream = new Blob([jsonString], { type: "application/json" }).stream().pipeThrough(new CompressionStream("gzip"));
77
+ const compressedData = await new Response(compressedStream).arrayBuffer();
78
+ const response = await fetch(this.baseHttpUrl + "/v1/browser-sessions/events", {
79
+ method: "POST",
80
+ headers: {
81
+ ...this.headers(),
82
+ "Content-Encoding": "gzip"
83
+ },
84
+ body: compressedData
85
+ });
86
+ if (!response.ok) await this.handleError(response);
87
+ }
88
+ };
89
+ /**
90
+ * Locale-aware, case-insensitive comparator for the project listing. Ordering
91
+ * lives here — the single choke point every CLI surface (the `project list`
92
+ * table + its `--json`, and the interactive picker used by `setup` / `plugin
93
+ * add`) reads from — so the order can't drift between surfaces.
94
+ */
95
+ const projectCollator = new Intl.Collator(void 0, { sensitivity: "base" });
96
+ /** Sort projects by workspace name, then project name (stable, human-scannable). */
97
+ const sortProjects = (projects) => [...projects].sort((a, b) => projectCollator.compare(a.workspaceName ?? "", b.workspaceName ?? "") || projectCollator.compare(a.name ?? "", b.name ?? ""));
98
+ /**
99
+ * User-scoped CLI endpoints that don't target a specific project. Authed by the
100
+ * BetterAuth user JWT (the `credential`); deliberately does NOT send an
101
+ * `x-lmnr-project-id` header (these routes are project discovery, pre-selection).
102
+ *
103
+ * Discovery exception: this resource always hits `/v1/cli/projects` with the
104
+ * bare bearer and overrides `BaseResource.headers()`/`apiPrefix`, so it works
105
+ * even when constructed with a `userToken` auth that has no real project id yet.
106
+ */
107
+ var CliResource = class extends BaseResource {
108
+ constructor(baseHttpUrl, auth) {
109
+ super(baseHttpUrl, auth);
110
+ }
111
+ /** Workspaces + projects the authenticated user can access. */
112
+ async listProjects() {
113
+ const response = await fetch(`${this.baseHttpUrl}/v1/cli/projects`, {
114
+ method: "GET",
115
+ headers: {
116
+ Authorization: `Bearer ${this.credential}`,
117
+ Accept: "application/json"
118
+ }
119
+ });
120
+ if (!response.ok) await this.handleError(response);
121
+ const body = await response.json();
122
+ return Array.isArray(body?.projects) ? sortProjects(body.projects) : [];
123
+ }
124
+ /**
125
+ * Resolve which project a project API key belongs to. Authed by the user JWT
126
+ * (the bearer); the project key travels in the body, NOT in `Authorization`.
127
+ * The server verifies the key and that the authenticated user is a member of
128
+ * the resolved project. Returns a tri-state probe so callers can distinguish a
129
+ * revoked key (401 → `invalid`) from a server/access problem (`unverifiable`).
130
+ */
131
+ async resolveProjectByApiKey(apiKey) {
132
+ let response;
133
+ try {
134
+ response = await fetch(`${this.baseHttpUrl}/v1/cli/project`, {
135
+ method: "POST",
136
+ headers: {
137
+ Authorization: `Bearer ${this.credential}`,
138
+ "Content-Type": "application/json",
139
+ Accept: "application/json"
140
+ },
141
+ body: JSON.stringify({ apiKey })
142
+ });
143
+ } catch {
144
+ return { status: "unverifiable" };
145
+ }
146
+ if (response.status === 401) return { status: "invalid" };
147
+ if (!response.ok) return { status: "unverifiable" };
148
+ const body = await response.json().catch(() => null);
149
+ return body?.projectId ? {
150
+ status: "ok",
151
+ projectId: body.projectId
152
+ } : { status: "unverifiable" };
153
+ }
66
154
  };
67
- //#endregion
68
- //#region src/utils.ts
69
155
  function initializeLogger$1(options) {
70
156
  const colorize = options?.colorize ?? true;
71
157
  const level = options?.level ?? process.env.LMNR_LOG_LEVEL?.toLowerCase()?.trim() ?? "info";
72
- return (0, pino.default)({ level }, (0, pino_pretty.PinoPretty)({
158
+ return (0, pino$3.default)({ level }, (0, pino_pretty.PinoPretty)({
73
159
  colorize,
74
160
  minimumLevel: level
75
161
  }));
76
162
  }
77
- const logger$5 = initializeLogger$1();
163
+ const logger$4 = initializeLogger$1();
78
164
  const isStringUUID$1 = (id) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id);
79
- const NIL_UUID = "00000000-0000-0000-0000-000000000000";
80
165
  const newUUID$1 = () => {
81
166
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
82
167
  else return (0, uuid.v4)();
83
168
  };
84
- const normalizeOtelTraceId = (traceId) => {
85
- let id = traceId.toLowerCase();
86
- if (id.startsWith("0x")) id = id.slice(2);
87
- return id.padStart(32, "0").slice(-32);
88
- };
89
- const normalizeOtelSpanId = (spanId) => {
90
- let id = spanId.toLowerCase();
91
- if (id.startsWith("0x")) id = id.slice(2);
92
- return id.padStart(16, "0").slice(-16);
93
- };
94
169
  const otelSpanIdToUUID$1 = (spanId) => {
95
170
  let id = spanId.toLowerCase();
96
171
  if (id.startsWith("0x")) id = id.slice(2);
97
- if (id.length !== 16) logger$5.warn(`Span ID ${spanId} is not 16 hex chars long. This is not a valid OpenTelemetry span ID.`);
172
+ if (id.length !== 16) logger$4.warn(`Span ID ${spanId} is not 16 hex chars long. This is not a valid OpenTelemetry span ID.`);
98
173
  if (!/^[0-9a-f]+$/.test(id)) {
99
- logger$5.error(`Span ID ${spanId} is not a valid hex string. Generating a random UUID instead.`);
174
+ logger$4.error(`Span ID ${spanId} is not a valid hex string. Generating a random UUID instead.`);
100
175
  return newUUID$1();
101
176
  }
102
177
  return 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");
@@ -104,481 +179,70 @@ const otelSpanIdToUUID$1 = (spanId) => {
104
179
  const otelTraceIdToUUID$1 = (traceId) => {
105
180
  let id = traceId.toLowerCase();
106
181
  if (id.startsWith("0x")) id = id.slice(2);
107
- if (id.length !== 32) logger$5.warn(`Trace ID ${traceId} is not 32 hex chars long. This is not a valid OpenTelemetry trace ID.`);
182
+ if (id.length !== 32) logger$4.warn(`Trace ID ${traceId} is not 32 hex chars long. This is not a valid OpenTelemetry trace ID.`);
108
183
  if (!/^[0-9a-f]+$/.test(id)) {
109
- logger$5.error(`Trace ID ${traceId} is not a valid hex string. Generating a random UUID instead.`);
184
+ logger$4.error(`Trace ID ${traceId} is not a valid hex string. Generating a random UUID instead.`);
110
185
  return newUUID$1();
111
186
  }
112
187
  return 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");
113
188
  };
114
- const uuidToOtelTraceId = (uuid$1) => uuid$1.replace(/-/g, "");
115
- const uuidToOtelSpanId = (uuid$2) => uuid$2.replace(/-/g, "").slice(16);
116
- /**
117
- * This is a simple implementation of a semaphore to replicate
118
- * the behavior of the `asyncio.Semaphore` in Python.
119
- */
120
- var Semaphore = class {
121
- constructor(value = 1) {
122
- this._waiters = [];
123
- if (value < 0) throw new Error("Semaphore value must be >= 0");
124
- this._value = value;
125
- this._waiters = [];
189
+ const slicePayload = (value, length) => {
190
+ if (value === null || value === void 0) return value;
191
+ const str = JSON.stringify(value);
192
+ if (str.length <= length) return value;
193
+ return str.slice(0, length) + "...";
194
+ };
195
+ const loadEnv$1 = (options) => {
196
+ const nodeEnv = process.env.NODE_ENV || "development";
197
+ const envDir = process.cwd();
198
+ const envFiles = [
199
+ ".env",
200
+ ".env.local",
201
+ `.env.${nodeEnv}`,
202
+ `.env.${nodeEnv}.local`
203
+ ];
204
+ const logLevel = process.env.LMNR_LOG_LEVEL ?? "info";
205
+ const verbose = ["debug", "trace"].includes(logLevel.trim().toLowerCase());
206
+ const quiet = options?.quiet ?? !verbose;
207
+ (0, dotenv.config)({
208
+ path: options?.paths ?? envFiles.map((envFile) => path$1.resolve(envDir, envFile)),
209
+ quiet
210
+ });
211
+ };
212
+ const logger$3 = initializeLogger$1();
213
+ const DEFAULT_DATASET_PULL_LIMIT = 100;
214
+ const DEFAULT_DATASET_PUSH_BATCH_SIZE = 100;
215
+ var DatasetsResource = class extends BaseResource {
216
+ constructor(baseHttpUrl, auth) {
217
+ super(baseHttpUrl, auth);
126
218
  }
127
- async acquire() {
128
- if (this._value > 0) {
129
- this._value--;
130
- return;
131
- }
132
- return new Promise((resolve) => {
133
- this._waiters.push(resolve);
219
+ /**
220
+ * List all datasets.
221
+ *
222
+ * @returns {Promise<Dataset[]>} Array of datasets
223
+ */
224
+ async listDatasets() {
225
+ const response = await fetch(this.baseHttpUrl + this.apiPrefix + "/datasets", {
226
+ method: "GET",
227
+ headers: this.headers()
134
228
  });
229
+ if (!response.ok) await this.handleError(response);
230
+ return response.json();
135
231
  }
136
- release() {
137
- if (this._waiters.length > 0) this._waiters.shift()?.();
138
- else this._value++;
139
- }
140
- async using(fn) {
141
- try {
142
- await this.acquire();
143
- return await fn();
144
- } finally {
145
- this.release();
146
- }
147
- }
148
- };
149
- const tryToOtelSpanContext = (spanContext) => {
150
- if (typeof spanContext === "string") try {
151
- return recordToOtelSpanContext(JSON.parse(spanContext));
152
- } catch (e) {
153
- throw new Error(`Failed to parse span context ${spanContext}. The string must be a json representation of a LaminarSpanContext.Error: ${errorMessage(e)}`);
154
- }
155
- else if (isRecord(spanContext)) return recordToOtelSpanContext(spanContext);
156
- else if (typeof spanContext.traceId === "string" && typeof spanContext.spanId === "string" && spanContext.traceId.length === 32 && spanContext.spanId.length === 16) {
157
- logger$5.warn("The span context is already an OpenTelemetry SpanContext. Returning it as is. Please use `LaminarSpanContext` objects instead.");
158
- return spanContext;
159
- } else throw new Error(`Invalid span context ${JSON.stringify(spanContext)}. Must be a LaminarSpanContext or its json representation.`);
160
- };
161
- const recordToOtelSpanContext = (record) => {
162
- if (typeof record.spanId === "string" && typeof record.traceId === "string" || typeof record.span_id === "string" && typeof record.trace_id === "string") return {
163
- spanId: uuidToOtelSpanId(record?.spanId ?? record?.["span_id"]),
164
- traceId: uuidToOtelTraceId(record?.traceId ?? record?.["trace_id"]),
165
- isRemote: record?.isRemote ?? record?.["is_remote"] ?? false,
166
- traceFlags: record?.traceFlags ?? _opentelemetry_api.TraceFlags.SAMPLED
167
- };
168
- else throw new Error(`Invalid span context ${JSON.stringify(record)}. Must be a json representation of a LaminarSpanContext.`);
169
- };
170
- const isRecord = (value) => typeof value === "object" && !Array.isArray(value) && value !== null;
171
- /**
172
- * Deserialize a LaminarSpanContext from a string or record.
173
- * Handles both camelCase and snake_case keys for cross-language compatibility.
174
- *
175
- * @param data - The data to deserialize (string or record)
176
- * @returns The deserialized LaminarSpanContext
177
- * @throws Error if the data is invalid
178
- */
179
- const deserializeLaminarSpanContext = (data) => {
180
- if (typeof data === "string") try {
181
- return deserializeLaminarSpanContext(JSON.parse(data));
182
- } catch (e) {
183
- throw new Error(`Failed to parse LaminarSpanContext: ${errorMessage(e)}`);
184
- }
185
- if (!isRecord(data)) throw new Error("Invalid LaminarSpanContext: must be a string or object");
186
- const traceId = data.traceId ?? data.trace_id;
187
- const spanId = data.spanId ?? data.span_id;
188
- const isRemote = data.isRemote ?? data.is_remote ?? false;
189
- const spanPath = data.spanPath ?? data.span_path;
190
- const spanIdsPath = data.spanIdsPath ?? data.span_ids_path;
191
- const userId = data.userId ?? data.user_id;
192
- const sessionId = data.sessionId ?? data.session_id;
193
- const metadata = data.metadata;
194
- const traceType = data.traceType ?? data.trace_type;
195
- const tracingLevel = data.tracingLevel ?? data.tracing_level;
196
- const debug = data.debug;
197
- if (typeof traceId !== "string" || typeof spanId !== "string") throw new Error("Invalid LaminarSpanContext: traceId and spanId must be strings");
198
- if (!isStringUUID$1(traceId) || !isStringUUID$1(spanId)) throw new Error("Invalid LaminarSpanContext: traceId and spanId must be valid UUIDs");
199
- return {
200
- traceId,
201
- spanId,
202
- isRemote: Boolean(isRemote),
203
- spanPath: Array.isArray(spanPath) ? spanPath : void 0,
204
- spanIdsPath: Array.isArray(spanIdsPath) ? spanIdsPath : void 0,
205
- userId,
206
- sessionId,
207
- metadata,
208
- traceType,
209
- tracingLevel,
210
- debug: isRecord(debug) ? deserializeDebugContext(debug) : void 0
211
- };
212
- };
213
- /**
214
- * Normalize a value to a canonical lowercase UUID string, or undefined.
215
- *
216
- * The debug block's `sessionId` / `replayTraceId` are always full ids; a value
217
- * that isn't UUID-shaped is dropped (treated as absent) rather than thrown, so
218
- * a partially-broken block never breaks span-context parsing.
219
- */
220
- const asString = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
221
- /**
222
- * Parse a debug block, accepting camelCase and snake_case. All ids are kept
223
- * VERBATIM: the producer emits the run's exact session / replay-trace /
224
- * cache-until strings (un-normalized — `LMNR_DEBUG_SESSION_ID` may be an
225
- * arbitrary non-UUID value), so the consumer must round-trip them unchanged or
226
- * a downstream run never joins the run. Keep line-comparable with the Python
227
- * `DebugContext.deserialize`.
228
- */
229
- const deserializeDebugContext = (data) => ({
230
- enabled: data.enabled === true,
231
- sessionId: asString(data.sessionId ?? data.session_id),
232
- replayTraceId: asString(data.replayTraceId ?? data.replay_trace_id),
233
- cacheUntil: asString(data.cacheUntil ?? data.cache_until)
234
- });
235
- const getDirname = () => {
236
- if (typeof __dirname !== "undefined") return __dirname;
237
- if (typeof require("url").pathToFileURL(__filename).href !== "undefined") return path.dirname((0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
238
- return process.cwd();
239
- };
240
- const MAX_MANUAL_SPAN_PAYLOAD_SIZE = 1024 * 1024 * 10;
241
- const TRUNCATION_SUFFIX = "...[Laminar: truncated]";
242
- /**
243
- * Cut an oversized span payload down to the limit rather than dropping it.
244
- *
245
- * Keeping the leading bytes preserves the start of the value, which is the useful part when
246
- * debugging. Mirrors `_truncate_payload` in the Python SDK.
247
- *
248
- * Callers pass the result of `JSON.stringify`, whose TS signature claims `string` but which
249
- * actually returns `undefined` for a top-level `undefined`, function, or symbol. Guard at
250
- * runtime and hand such values straight back: `setAttribute` treats them as a no-op, which is
251
- * the behaviour these payloads had before truncation existed.
252
- */
253
- const truncateSpanPayload = (serialized, kind) => {
254
- if (typeof serialized !== "string") return serialized;
255
- if (serialized.length <= 10485760) return serialized;
256
- logger$5.warn(`Laminar: span ${kind} is ${serialized.length} bytes, which exceeds the ${MAX_MANUAL_SPAN_PAYLOAD_SIZE} byte limit. Truncating to the limit; the recorded value will not be valid JSON.`);
257
- const keep = MAX_MANUAL_SPAN_PAYLOAD_SIZE - 23;
258
- return serialized.slice(0, keep) + TRUNCATION_SUFFIX;
259
- };
260
- const isOtelAttributeValueType = (value) => {
261
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return true;
262
- if (Array.isArray(value)) {
263
- const allStrings = value.every((value) => value == null || typeof value === "string");
264
- const allNumbers = value.every((value) => value == null || typeof value === "number");
265
- const allBooleans = value.every((value) => value == null || typeof value === "boolean");
266
- return allStrings || allNumbers || allBooleans;
267
- }
268
- return false;
269
- };
270
- const metadataToAttributes = (metadata) => Object.fromEntries(Object.entries(metadata).map(([key, value]) => {
271
- if (isOtelAttributeValueType(value)) return [`${ASSOCIATION_PROPERTIES}.metadata.${key}`, value];
272
- else return [`${ASSOCIATION_PROPERTIES}.metadata.${key}`, JSON.stringify(value)];
273
- }));
274
- /**
275
- * Get OTEL environment variable with priority order.
276
- * Checks in order:
277
- * 1. OTEL_EXPORTER_OTLP_TRACES_{varName}
278
- * 2. OTEL_EXPORTER_OTLP_{varName}
279
- * 3. OTEL_{varName}
280
- *
281
- * @param varName - The variable name (e.g., 'ENDPOINT', 'HEADERS', 'PROTOCOL')
282
- * @returns The environment variable value or undefined if not found
283
- */
284
- const getOtelEnvVar = (varName) => {
285
- const candidates = [
286
- `OTEL_EXPORTER_OTLP_TRACES_${varName}`,
287
- `OTEL_EXPORTER_OTLP_${varName}`,
288
- `OTEL_${varName}`
289
- ];
290
- for (const candidate of candidates) {
291
- const value = process?.env?.[candidate];
292
- if (value) return value;
293
- }
294
- };
295
- /**
296
- * Check if OTEL configuration is available.
297
- * @returns true if OTEL endpoint is configured
298
- */
299
- const hasOtelConfig = () => !!getOtelEnvVar("ENDPOINT");
300
- /**
301
- * Parse OTEL headers string into a record object.
302
- * Format: key1=value1,key2=value2
303
- * Values are URL-decoded.
304
- *
305
- * @param headersStr - Headers string in OTEL format
306
- * @returns Parsed headers object
307
- */
308
- const parseOtelHeaders = (headersStr) => {
309
- if (!headersStr) return {};
310
- const headers = {};
311
- for (const pair of headersStr.split(",")) {
312
- const equalIndex = pair.indexOf("=");
313
- if (equalIndex !== -1) {
314
- const key = pair.substring(0, equalIndex).trim();
315
- const value = pair.substring(equalIndex + 1).trim();
316
- headers[key] = decodeURIComponent(value);
317
- }
318
- }
319
- return headers;
320
- };
321
- /**
322
- * Validate that either Laminar API key or OTEL configuration is present.
323
- * Throws an error if neither is configured.
324
- *
325
- * @param apiKey - The Laminar API key (if provided)
326
- * @throws Error if neither API key nor OTEL configuration is present
327
- */
328
- const validateTracingConfig = (apiKey) => {
329
- if (!apiKey && !hasOtelConfig()) throw new Error("Please initialize the Laminar object with your project API key or set the LMNR_PROJECT_API_KEY environment variable, or configure OTEL environment variables (OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, etc.)");
330
- };
331
- const loadEnv$1 = (options) => {
332
- const nodeEnv = process.env.NODE_ENV || "development";
333
- const envDir = process.cwd();
334
- const envFiles = [
335
- ".env",
336
- ".env.local",
337
- `.env.${nodeEnv}`,
338
- `.env.${nodeEnv}.local`
339
- ];
340
- const logLevel = process.env.LMNR_LOG_LEVEL ?? "info";
341
- const verbose = ["debug", "trace"].includes(logLevel.trim().toLowerCase());
342
- const quiet = options?.quiet ?? !verbose;
343
- (0, dotenv.config)({
344
- path: options?.paths ?? envFiles.map((envFile) => path.resolve(envDir, envFile)),
345
- quiet
346
- });
347
- };
348
- /**
349
- * Converts an API base URL to the frontend/web URL.
350
- * - Converts https://api.lmnr.ai to https://www.laminar.sh
351
- * - Removes trailing slashes
352
- * - For localhost/127.0.0.1, ensures a port is specified (defaults to 5667)
353
- *
354
- * @param baseUrl - The API base URL (defaults to "https://api.lmnr.ai")
355
- * @returns The frontend URL
356
- */
357
- const getFrontendUrl = (baseUrl, frontendPort) => {
358
- let url$1 = baseUrl ?? "https://api.lmnr.ai";
359
- if (url$1 === "https://api.lmnr.ai") url$1 = "https://www.laminar.sh";
360
- url$1 = url$1.replace(/\/$/, "");
361
- if (/localhost|127\.0\.0\.1/.test(url$1)) {
362
- const port = frontendPort ?? url$1.match(/:\d{1,5}$/g)?.[0]?.slice(1) ?? 5667;
363
- if (/:(\d{1,5})$/.test(url$1)) url$1 = url$1.replace(/:\d{1,5}$/g, `:${port}`);
364
- else url$1 = `${url$1}:${port}`;
365
- }
366
- return url$1;
367
- };
368
- //#endregion
369
- //#region ../client/dist/index.mjs
370
- var version = "0.8.44";
371
- function getLangVersion() {
372
- if (typeof process !== "undefined" && process.versions && process.versions.node) return `node-${process.versions.node}`;
373
- if (typeof navigator !== "undefined" && navigator.userAgent) return `browser-${navigator.userAgent}`;
374
- return null;
375
- }
376
- var BaseResource = class {
377
- constructor(baseHttpUrl, auth) {
378
- this.baseHttpUrl = baseHttpUrl;
379
- this.auth = auth;
380
- this.credential = auth.type === "apiKey" ? auth.key : auth.token;
381
- }
382
- /** API path prefix: `/v1/cli` for CLI user-token auth, `/v1` otherwise. */
383
- get apiPrefix() {
384
- return this.auth.type === "userToken" ? "/v1/cli" : "/v1";
385
- }
386
- headers() {
387
- return {
388
- Authorization: `Bearer ${this.credential}`,
389
- "Content-Type": "application/json",
390
- Accept: "application/json",
391
- ...this.auth.type === "userToken" ? { "x-lmnr-project-id": this.auth.projectId } : {}
392
- };
393
- }
394
- async handleError(response) {
395
- const errorMsg = await response.text();
396
- throw new Error(`${response.status} ${errorMsg}`);
397
- }
398
- };
399
- var BrowserEventsResource = class extends BaseResource {
400
- constructor(baseHttpUrl, auth) {
401
- super(baseHttpUrl, auth);
402
- }
403
- async send({ sessionId, traceId, events }) {
404
- const payload = {
405
- sessionId,
406
- traceId,
407
- events,
408
- source: getLangVersion() ?? "javascript",
409
- sdkVersion: version
410
- };
411
- const jsonString = JSON.stringify(payload);
412
- const compressedStream = new Blob([jsonString], { type: "application/json" }).stream().pipeThrough(new CompressionStream("gzip"));
413
- const compressedData = await new Response(compressedStream).arrayBuffer();
414
- const response = await fetch(this.baseHttpUrl + "/v1/browser-sessions/events", {
415
- method: "POST",
416
- headers: {
417
- ...this.headers(),
418
- "Content-Encoding": "gzip"
419
- },
420
- body: compressedData
421
- });
422
- if (!response.ok) await this.handleError(response);
423
- }
424
- };
425
- /**
426
- * Locale-aware, case-insensitive comparator for the project listing. Ordering
427
- * lives here — the single choke point every CLI surface (the `project list`
428
- * table + its `--json`, and the interactive picker used by `setup` / `plugin
429
- * add`) reads from — so the order can't drift between surfaces.
430
- */
431
- const projectCollator = new Intl.Collator(void 0, { sensitivity: "base" });
432
- /** Sort projects by workspace name, then project name (stable, human-scannable). */
433
- const sortProjects = (projects) => [...projects].sort((a, b) => projectCollator.compare(a.workspaceName ?? "", b.workspaceName ?? "") || projectCollator.compare(a.name ?? "", b.name ?? ""));
434
- /**
435
- * User-scoped CLI endpoints that don't target a specific project. Authed by the
436
- * BetterAuth user JWT (the `credential`); deliberately does NOT send an
437
- * `x-lmnr-project-id` header (these routes are project discovery, pre-selection).
438
- *
439
- * Discovery exception: this resource always hits `/v1/cli/projects` with the
440
- * bare bearer and overrides `BaseResource.headers()`/`apiPrefix`, so it works
441
- * even when constructed with a `userToken` auth that has no real project id yet.
442
- */
443
- var CliResource = class extends BaseResource {
444
- constructor(baseHttpUrl, auth) {
445
- super(baseHttpUrl, auth);
446
- }
447
- /** Workspaces + projects the authenticated user can access. */
448
- async listProjects() {
449
- const response = await fetch(`${this.baseHttpUrl}/v1/cli/projects`, {
450
- method: "GET",
451
- headers: {
452
- Authorization: `Bearer ${this.credential}`,
453
- Accept: "application/json"
454
- }
455
- });
456
- if (!response.ok) await this.handleError(response);
457
- const body = await response.json();
458
- return Array.isArray(body?.projects) ? sortProjects(body.projects) : [];
459
- }
460
- /**
461
- * Resolve which project a project API key belongs to. Authed by the user JWT
462
- * (the bearer); the project key travels in the body, NOT in `Authorization`.
463
- * The server verifies the key and that the authenticated user is a member of
464
- * the resolved project. Returns a tri-state probe so callers can distinguish a
465
- * revoked key (401 → `invalid`) from a server/access problem (`unverifiable`).
466
- */
467
- async resolveProjectByApiKey(apiKey) {
468
- let response;
469
- try {
470
- response = await fetch(`${this.baseHttpUrl}/v1/cli/project`, {
471
- method: "POST",
472
- headers: {
473
- Authorization: `Bearer ${this.credential}`,
474
- "Content-Type": "application/json",
475
- Accept: "application/json"
476
- },
477
- body: JSON.stringify({ apiKey })
478
- });
479
- } catch {
480
- return { status: "unverifiable" };
481
- }
482
- if (response.status === 401) return { status: "invalid" };
483
- if (!response.ok) return { status: "unverifiable" };
484
- const body = await response.json().catch(() => null);
485
- return body?.projectId ? {
486
- status: "ok",
487
- projectId: body.projectId
488
- } : { status: "unverifiable" };
489
- }
490
- };
491
- function initializeLogger(options) {
492
- const colorize = options?.colorize ?? true;
493
- const level = options?.level ?? process.env.LMNR_LOG_LEVEL?.toLowerCase()?.trim() ?? "info";
494
- return (0, pino$3.default)({ level }, (0, pino_pretty.PinoPretty)({
495
- colorize,
496
- minimumLevel: level
497
- }));
498
- }
499
- const logger$4 = initializeLogger();
500
- const isStringUUID = (id) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id);
501
- const newUUID = () => {
502
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
503
- else return (0, uuid.v4)();
504
- };
505
- const otelSpanIdToUUID = (spanId) => {
506
- let id = spanId.toLowerCase();
507
- if (id.startsWith("0x")) id = id.slice(2);
508
- if (id.length !== 16) logger$4.warn(`Span ID ${spanId} is not 16 hex chars long. This is not a valid OpenTelemetry span ID.`);
509
- if (!/^[0-9a-f]+$/.test(id)) {
510
- logger$4.error(`Span ID ${spanId} is not a valid hex string. Generating a random UUID instead.`);
511
- return newUUID();
512
- }
513
- return 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");
514
- };
515
- const otelTraceIdToUUID = (traceId) => {
516
- let id = traceId.toLowerCase();
517
- if (id.startsWith("0x")) id = id.slice(2);
518
- if (id.length !== 32) logger$4.warn(`Trace ID ${traceId} is not 32 hex chars long. This is not a valid OpenTelemetry trace ID.`);
519
- if (!/^[0-9a-f]+$/.test(id)) {
520
- logger$4.error(`Trace ID ${traceId} is not a valid hex string. Generating a random UUID instead.`);
521
- return newUUID();
522
- }
523
- return 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");
524
- };
525
- const slicePayload = (value, length) => {
526
- if (value === null || value === void 0) return value;
527
- const str = JSON.stringify(value);
528
- if (str.length <= length) return value;
529
- return str.slice(0, length) + "...";
530
- };
531
- const loadEnv = (options) => {
532
- const nodeEnv = process.env.NODE_ENV || "development";
533
- const envDir = process.cwd();
534
- const envFiles = [
535
- ".env",
536
- ".env.local",
537
- `.env.${nodeEnv}`,
538
- `.env.${nodeEnv}.local`
539
- ];
540
- const logLevel = process.env.LMNR_LOG_LEVEL ?? "info";
541
- const verbose = ["debug", "trace"].includes(logLevel.trim().toLowerCase());
542
- const quiet = options?.quiet ?? !verbose;
543
- (0, dotenv.config)({
544
- path: options?.paths ?? envFiles.map((envFile) => path$1.resolve(envDir, envFile)),
545
- quiet
546
- });
547
- };
548
- const logger$3 = initializeLogger();
549
- const DEFAULT_DATASET_PULL_LIMIT = 100;
550
- const DEFAULT_DATASET_PUSH_BATCH_SIZE = 100;
551
- var DatasetsResource = class extends BaseResource {
552
- constructor(baseHttpUrl, auth) {
553
- super(baseHttpUrl, auth);
554
- }
555
- /**
556
- * List all datasets.
557
- *
558
- * @returns {Promise<Dataset[]>} Array of datasets
559
- */
560
- async listDatasets() {
561
- const response = await fetch(this.baseHttpUrl + this.apiPrefix + "/datasets", {
562
- method: "GET",
563
- headers: this.headers()
564
- });
565
- if (!response.ok) await this.handleError(response);
566
- return response.json();
567
- }
568
- /**
569
- * Get a dataset by name.
570
- *
571
- * @param {string} name - Name of the dataset
572
- * @returns {Promise<Dataset[]>} Array of datasets with matching name
573
- */
574
- async getDatasetByName(name) {
575
- const params = new URLSearchParams({ name });
576
- const response = await fetch(this.baseHttpUrl + `${this.apiPrefix}/datasets?${params.toString()}`, {
577
- method: "GET",
578
- headers: this.headers()
579
- });
580
- if (!response.ok) await this.handleError(response);
581
- return response.json();
232
+ /**
233
+ * Get a dataset by name.
234
+ *
235
+ * @param {string} name - Name of the dataset
236
+ * @returns {Promise<Dataset[]>} Array of datasets with matching name
237
+ */
238
+ async getDatasetByName(name) {
239
+ const params = new URLSearchParams({ name });
240
+ const response = await fetch(this.baseHttpUrl + `${this.apiPrefix}/datasets?${params.toString()}`, {
241
+ method: "GET",
242
+ headers: this.headers()
243
+ });
244
+ if (!response.ok) await this.handleError(response);
245
+ return response.json();
582
246
  }
583
247
  /**
584
248
  * Push datapoints to a dataset.
@@ -648,7 +312,7 @@ var DatasetsResource = class extends BaseResource {
648
312
  return response.json();
649
313
  }
650
314
  };
651
- const logger$2 = initializeLogger();
315
+ const logger$2 = initializeLogger$1();
652
316
  const INITIAL_EVALUATION_DATAPOINT_MAX_DATA_LENGTH = 16e6;
653
317
  var EvalsResource = class extends BaseResource {
654
318
  constructor(baseHttpUrl, auth) {
@@ -728,14 +392,14 @@ var EvalsResource = class extends BaseResource {
728
392
  * @returns {Promise<StringUUID>} The datapoint ID
729
393
  */
730
394
  async createDatapoint({ evalId, data, target, metadata, index, traceId }) {
731
- const datapointId = newUUID();
395
+ const datapointId = newUUID$1();
732
396
  const partialDatapoint = {
733
397
  id: datapointId,
734
398
  data,
735
399
  target,
736
400
  index: index ?? 0,
737
- traceId: traceId ?? newUUID(),
738
- executorSpanId: newUUID(),
401
+ traceId: traceId ?? newUUID$1(),
402
+ executorSpanId: newUUID$1(),
739
403
  metadata
740
404
  };
741
405
  await this.saveDatapoints({
@@ -887,14 +551,14 @@ var EvaluatorsResource = class extends BaseResource {
887
551
  metadata,
888
552
  score,
889
553
  source: "Code",
890
- traceId: isStringUUID(options.traceId) ? options.traceId : otelTraceIdToUUID(options.traceId)
554
+ traceId: isStringUUID$1(options.traceId) ? options.traceId : otelTraceIdToUUID$1(options.traceId)
891
555
  };
892
556
  else if ("spanId" in options && options.spanId) payload = {
893
557
  name,
894
558
  metadata,
895
559
  score,
896
560
  source: "Code",
897
- spanId: isStringUUID(options.spanId) ? options.spanId : otelSpanIdToUUID(options.spanId)
561
+ spanId: isStringUUID$1(options.spanId) ? options.spanId : otelSpanIdToUUID$1(options.spanId)
898
562
  };
899
563
  else throw new Error("Either 'traceId' or 'spanId' must be provided.");
900
564
  const response = await fetch(this.baseHttpUrl + "/v1/evaluators/score", {
@@ -905,7 +569,7 @@ var EvaluatorsResource = class extends BaseResource {
905
569
  if (!response.ok) await this.handleError(response);
906
570
  }
907
571
  };
908
- const logger$1 = initializeLogger();
572
+ const logger$1 = initializeLogger$1();
909
573
  /**
910
574
  * Map the opaque HIT `response` payload onto a {@link CachedSpan} the provider
911
575
  * wrappers can replay. The server-side shape of `response` is not yet frozen
@@ -1235,11 +899,11 @@ var TagsResource = class extends BaseResource {
1235
899
  */
1236
900
  async tag(trace_id, tags) {
1237
901
  const traceTags = Array.isArray(tags) ? tags : [tags];
1238
- const formattedTraceId = isStringUUID(trace_id) ? trace_id : otelTraceIdToUUID(trace_id);
902
+ const formattedTraceId = isStringUUID$1(trace_id) ? trace_id : otelTraceIdToUUID$1(trace_id);
1239
903
  const url = this.baseHttpUrl + "/v1/tag";
1240
904
  const payload = {
1241
- "traceId": formattedTraceId,
1242
- "names": traceTags
905
+ traceId: formattedTraceId,
906
+ names: traceTags
1243
907
  };
1244
908
  const response = await fetch(url, {
1245
909
  method: "POST",
@@ -1251,7 +915,7 @@ var TagsResource = class extends BaseResource {
1251
915
  }
1252
916
  };
1253
917
  /** Resource for post-factum operations on existing traces. */
1254
- const logger = initializeLogger();
918
+ const logger$5 = initializeLogger$1();
1255
919
  var TracesResource = class extends BaseResource {
1256
920
  /** Resource for post-factum operations on existing traces. */
1257
921
  constructor(baseHttpUrl, auth) {
@@ -1309,7 +973,7 @@ var TracesResource = class extends BaseResource {
1309
973
  */
1310
974
  async pushMetadata(traceId, metadata, options) {
1311
975
  if (!metadata || Object.keys(metadata).length === 0) throw new Error("metadata must be a non-empty object");
1312
- const formattedTraceId = isStringUUID(traceId) ? traceId : otelTraceIdToUUID(traceId);
976
+ const formattedTraceId = isStringUUID$1(traceId) ? traceId : otelTraceIdToUUID$1(traceId);
1313
977
  const url = this.baseHttpUrl + this.apiPrefix + "/traces/metadata";
1314
978
  const response = await fetch(url, {
1315
979
  method: "POST",
@@ -1322,7 +986,7 @@ var TracesResource = class extends BaseResource {
1322
986
  if (response.status === 404) {
1323
987
  const message = `Trace ${formattedTraceId} not found. The trace may not have been flushed yet — call await Laminar.flush() and retry.`;
1324
988
  if (options?.failOnNotFound) throw new Error(message);
1325
- logger.warn(message);
989
+ logger$5.warn(message);
1326
990
  return;
1327
991
  }
1328
992
  if (!response.ok) await this.handleError(response);
@@ -1330,7 +994,7 @@ var TracesResource = class extends BaseResource {
1330
994
  };
1331
995
  var LaminarClient = class LaminarClient {
1332
996
  constructor({ baseUrl, port, auth, projectApiKey, cliUserProjectId } = {}) {
1333
- loadEnv();
997
+ loadEnv$1();
1334
998
  this.auth = LaminarClient.normalizeAuth(auth, projectApiKey, cliUserProjectId);
1335
999
  const resolvedBaseUrl = baseUrl ?? process.env.LMNR_BASE_URL;
1336
1000
  this.configuredUrl = resolvedBaseUrl;
@@ -1400,33 +1064,369 @@ var LaminarClient = class LaminarClient {
1400
1064
  get browserEvents() {
1401
1065
  return this._browserEvents;
1402
1066
  }
1403
- get cli() {
1404
- return this._cli;
1067
+ get cli() {
1068
+ return this._cli;
1069
+ }
1070
+ get datasets() {
1071
+ return this._datasets;
1072
+ }
1073
+ get evals() {
1074
+ return this._evals;
1075
+ }
1076
+ get evaluators() {
1077
+ return this._evaluators;
1078
+ }
1079
+ get signals() {
1080
+ return this._signals;
1081
+ }
1082
+ get rolloutSessions() {
1083
+ return this._rolloutSessions;
1084
+ }
1085
+ get sql() {
1086
+ return this._sql;
1087
+ }
1088
+ get tags() {
1089
+ return this._tags;
1090
+ }
1091
+ get traces() {
1092
+ return this._traces;
1093
+ }
1094
+ };
1095
+ //#endregion
1096
+ //#region package.json
1097
+ var version = "0.8.45";
1098
+ //#endregion
1099
+ //#region src/opentelemetry-lib/tracing/attributes.ts
1100
+ const SPAN_INPUT = "lmnr.span.input";
1101
+ const SPAN_OUTPUT = "lmnr.span.output";
1102
+ const SPAN_TYPE = "lmnr.span.type";
1103
+ const SPAN_PATH = "lmnr.span.path";
1104
+ const SPAN_IDS_PATH = "lmnr.span.ids_path";
1105
+ const PARENT_SPAN_PATH = "lmnr.span.parent_path";
1106
+ const PARENT_SPAN_IDS_PATH = "lmnr.span.parent_ids_path";
1107
+ const SPAN_INSTRUMENTATION_SOURCE = "lmnr.span.instrumentation_source";
1108
+ const SPAN_SDK_VERSION = "lmnr.span.sdk_version";
1109
+ const SPAN_LANGUAGE_VERSION = "lmnr.span.language_version";
1110
+ const SPAN_INSTRUMENTATION_SCOPE_NAME = "lmnr.span.instrumentation_scope.name";
1111
+ const SPAN_INSTRUMENTATION_SCOPE_VERSION = "lmnr.span.instrumentation_scope.version";
1112
+ const TRACE_HAS_BROWSER_SESSION = "lmnr.internal.has_browser_session";
1113
+ const HUMAN_EVALUATOR_OPTIONS = "lmnr.span.human_evaluator_options";
1114
+ const ASSOCIATION_PROPERTIES = "lmnr.association.properties";
1115
+ const SESSION_ID = "lmnr.association.properties.session_id";
1116
+ const USER_ID = "lmnr.association.properties.user_id";
1117
+ const TRACE_TYPE = "lmnr.association.properties.trace_type";
1118
+ const ASSOCIATION_PROPERTIES_OVERRIDES = { span_type: SPAN_TYPE };
1119
+ const LaminarAttributes = {
1120
+ INPUT_TOKEN_COUNT: "gen_ai.usage.input_tokens",
1121
+ OUTPUT_TOKEN_COUNT: "gen_ai.usage.output_tokens",
1122
+ TOTAL_TOKEN_COUNT: "llm.usage.total_tokens",
1123
+ PROVIDER: "gen_ai.system",
1124
+ REQUEST_MODEL: "gen_ai.request.model",
1125
+ RESPONSE_MODEL: "gen_ai.response.model",
1126
+ INPUT_COST: "gen_ai.usage.input_cost",
1127
+ OUTPUT_COST: "gen_ai.usage.output_cost",
1128
+ TOTAL_COST: "gen_ai.usage.cost"
1129
+ };
1130
+ //#endregion
1131
+ //#region src/utils.ts
1132
+ function initializeLogger(options) {
1133
+ const colorize = options?.colorize ?? true;
1134
+ const level = options?.level ?? process.env.LMNR_LOG_LEVEL?.toLowerCase()?.trim() ?? "info";
1135
+ return (0, pino.default)({ level }, (0, pino_pretty.PinoPretty)({
1136
+ colorize,
1137
+ minimumLevel: level
1138
+ }));
1139
+ }
1140
+ const logger = initializeLogger();
1141
+ const isStringUUID = (id) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id);
1142
+ const NIL_UUID = "00000000-0000-0000-0000-000000000000";
1143
+ const newUUID = () => {
1144
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
1145
+ else return (0, uuid.v4)();
1146
+ };
1147
+ const normalizeOtelTraceId = (traceId) => {
1148
+ let id = traceId.toLowerCase();
1149
+ if (id.startsWith("0x")) id = id.slice(2);
1150
+ return id.padStart(32, "0").slice(-32);
1151
+ };
1152
+ const normalizeOtelSpanId = (spanId) => {
1153
+ let id = spanId.toLowerCase();
1154
+ if (id.startsWith("0x")) id = id.slice(2);
1155
+ return id.padStart(16, "0").slice(-16);
1156
+ };
1157
+ const otelSpanIdToUUID = (spanId) => {
1158
+ let id = spanId.toLowerCase();
1159
+ if (id.startsWith("0x")) id = id.slice(2);
1160
+ if (id.length !== 16) logger.warn(`Span ID ${spanId} is not 16 hex chars long. This is not a valid OpenTelemetry span ID.`);
1161
+ if (!/^[0-9a-f]+$/.test(id)) {
1162
+ logger.error(`Span ID ${spanId} is not a valid hex string. Generating a random UUID instead.`);
1163
+ return newUUID();
1164
+ }
1165
+ return 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");
1166
+ };
1167
+ const otelTraceIdToUUID = (traceId) => {
1168
+ let id = traceId.toLowerCase();
1169
+ if (id.startsWith("0x")) id = id.slice(2);
1170
+ if (id.length !== 32) logger.warn(`Trace ID ${traceId} is not 32 hex chars long. This is not a valid OpenTelemetry trace ID.`);
1171
+ if (!/^[0-9a-f]+$/.test(id)) {
1172
+ logger.error(`Trace ID ${traceId} is not a valid hex string. Generating a random UUID instead.`);
1173
+ return newUUID();
1174
+ }
1175
+ return 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");
1176
+ };
1177
+ const uuidToOtelTraceId = (uuid$1) => uuid$1.replace(/-/g, "");
1178
+ const uuidToOtelSpanId = (uuid$2) => uuid$2.replace(/-/g, "").slice(16);
1179
+ /**
1180
+ * This is a simple implementation of a semaphore to replicate
1181
+ * the behavior of the `asyncio.Semaphore` in Python.
1182
+ */
1183
+ var Semaphore = class {
1184
+ constructor(value = 1) {
1185
+ this._waiters = [];
1186
+ if (value < 0) throw new Error("Semaphore value must be >= 0");
1187
+ this._value = value;
1188
+ this._waiters = [];
1189
+ }
1190
+ async acquire() {
1191
+ if (this._value > 0) {
1192
+ this._value--;
1193
+ return;
1194
+ }
1195
+ return new Promise((resolve) => {
1196
+ this._waiters.push(resolve);
1197
+ });
1405
1198
  }
1406
- get datasets() {
1407
- return this._datasets;
1199
+ release() {
1200
+ if (this._waiters.length > 0) this._waiters.shift()?.();
1201
+ else this._value++;
1408
1202
  }
1409
- get evals() {
1410
- return this._evals;
1203
+ async using(fn) {
1204
+ try {
1205
+ await this.acquire();
1206
+ return await fn();
1207
+ } finally {
1208
+ this.release();
1209
+ }
1411
1210
  }
1412
- get evaluators() {
1413
- return this._evaluators;
1211
+ };
1212
+ const tryToOtelSpanContext = (spanContext) => {
1213
+ if (typeof spanContext === "string") try {
1214
+ return recordToOtelSpanContext(JSON.parse(spanContext));
1215
+ } catch (e) {
1216
+ throw new Error(`Failed to parse span context ${spanContext}. The string must be a json representation of a LaminarSpanContext.Error: ${errorMessage(e)}`);
1414
1217
  }
1415
- get signals() {
1416
- return this._signals;
1218
+ else if (isRecord(spanContext)) return recordToOtelSpanContext(spanContext);
1219
+ else if (typeof spanContext.traceId === "string" && typeof spanContext.spanId === "string" && spanContext.traceId.length === 32 && spanContext.spanId.length === 16) {
1220
+ logger.warn("The span context is already an OpenTelemetry SpanContext. Returning it as is. Please use `LaminarSpanContext` objects instead.");
1221
+ return spanContext;
1222
+ } else throw new Error(`Invalid span context ${JSON.stringify(spanContext)}. Must be a LaminarSpanContext or its json representation.`);
1223
+ };
1224
+ const recordToOtelSpanContext = (record) => {
1225
+ if (typeof record.spanId === "string" && typeof record.traceId === "string" || typeof record.span_id === "string" && typeof record.trace_id === "string") return {
1226
+ spanId: uuidToOtelSpanId(record?.spanId ?? record?.["span_id"]),
1227
+ traceId: uuidToOtelTraceId(record?.traceId ?? record?.["trace_id"]),
1228
+ isRemote: record?.isRemote ?? record?.["is_remote"] ?? false,
1229
+ traceFlags: record?.traceFlags ?? _opentelemetry_api.TraceFlags.SAMPLED
1230
+ };
1231
+ else throw new Error(`Invalid span context ${JSON.stringify(record)}. Must be a json representation of a LaminarSpanContext.`);
1232
+ };
1233
+ const isRecord = (value) => typeof value === "object" && !Array.isArray(value) && value !== null;
1234
+ /**
1235
+ * Deserialize a LaminarSpanContext from a string or record.
1236
+ * Handles both camelCase and snake_case keys for cross-language compatibility.
1237
+ *
1238
+ * @param data - The data to deserialize (string or record)
1239
+ * @returns The deserialized LaminarSpanContext
1240
+ * @throws Error if the data is invalid
1241
+ */
1242
+ const deserializeLaminarSpanContext = (data) => {
1243
+ if (typeof data === "string") try {
1244
+ return deserializeLaminarSpanContext(JSON.parse(data));
1245
+ } catch (e) {
1246
+ throw new Error(`Failed to parse LaminarSpanContext: ${errorMessage(e)}`);
1417
1247
  }
1418
- get rolloutSessions() {
1419
- return this._rolloutSessions;
1248
+ if (!isRecord(data)) throw new Error("Invalid LaminarSpanContext: must be a string or object");
1249
+ const traceId = data.traceId ?? data.trace_id;
1250
+ const spanId = data.spanId ?? data.span_id;
1251
+ const isRemote = data.isRemote ?? data.is_remote ?? false;
1252
+ const spanPath = data.spanPath ?? data.span_path;
1253
+ const spanIdsPath = data.spanIdsPath ?? data.span_ids_path;
1254
+ const userId = data.userId ?? data.user_id;
1255
+ const sessionId = data.sessionId ?? data.session_id;
1256
+ const metadata = data.metadata;
1257
+ const traceType = data.traceType ?? data.trace_type;
1258
+ const tracingLevel = data.tracingLevel ?? data.tracing_level;
1259
+ const debug = data.debug;
1260
+ if (typeof traceId !== "string" || typeof spanId !== "string") throw new Error("Invalid LaminarSpanContext: traceId and spanId must be strings");
1261
+ if (!isStringUUID(traceId) || !isStringUUID(spanId)) throw new Error("Invalid LaminarSpanContext: traceId and spanId must be valid UUIDs");
1262
+ return {
1263
+ traceId,
1264
+ spanId,
1265
+ isRemote: Boolean(isRemote),
1266
+ spanPath: Array.isArray(spanPath) ? spanPath : void 0,
1267
+ spanIdsPath: Array.isArray(spanIdsPath) ? spanIdsPath : void 0,
1268
+ userId,
1269
+ sessionId,
1270
+ metadata,
1271
+ traceType,
1272
+ tracingLevel,
1273
+ debug: isRecord(debug) ? deserializeDebugContext(debug) : void 0
1274
+ };
1275
+ };
1276
+ /**
1277
+ * Normalize a value to a canonical lowercase UUID string, or undefined.
1278
+ *
1279
+ * The debug block's `sessionId` / `replayTraceId` are always full ids; a value
1280
+ * that isn't UUID-shaped is dropped (treated as absent) rather than thrown, so
1281
+ * a partially-broken block never breaks span-context parsing.
1282
+ */
1283
+ const asString = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
1284
+ /**
1285
+ * Parse a debug block, accepting camelCase and snake_case. All ids are kept
1286
+ * VERBATIM: the producer emits the run's exact session / replay-trace /
1287
+ * cache-until strings (un-normalized — `LMNR_DEBUG_SESSION_ID` may be an
1288
+ * arbitrary non-UUID value), so the consumer must round-trip them unchanged or
1289
+ * a downstream run never joins the run. Keep line-comparable with the Python
1290
+ * `DebugContext.deserialize`.
1291
+ */
1292
+ const deserializeDebugContext = (data) => ({
1293
+ enabled: data.enabled === true,
1294
+ sessionId: asString(data.sessionId ?? data.session_id),
1295
+ replayTraceId: asString(data.replayTraceId ?? data.replay_trace_id),
1296
+ cacheUntil: asString(data.cacheUntil ?? data.cache_until)
1297
+ });
1298
+ const getDirname = () => {
1299
+ if (typeof __dirname !== "undefined") return __dirname;
1300
+ if (typeof require("url").pathToFileURL(__filename).href !== "undefined") return path.dirname((0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
1301
+ return process.cwd();
1302
+ };
1303
+ const MAX_MANUAL_SPAN_PAYLOAD_SIZE = 1024 * 1024 * 10;
1304
+ const TRUNCATION_SUFFIX = "...[Laminar: truncated]";
1305
+ /**
1306
+ * Cut an oversized span payload down to the limit rather than dropping it.
1307
+ *
1308
+ * Keeping the leading bytes preserves the start of the value, which is the useful part when
1309
+ * debugging. Mirrors `_truncate_payload` in the Python SDK.
1310
+ *
1311
+ * Callers pass the result of `JSON.stringify`, whose TS signature claims `string` but which
1312
+ * actually returns `undefined` for a top-level `undefined`, function, or symbol. Guard at
1313
+ * runtime and hand such values straight back: `setAttribute` treats them as a no-op, which is
1314
+ * the behaviour these payloads had before truncation existed.
1315
+ */
1316
+ const truncateSpanPayload = (serialized, kind) => {
1317
+ if (typeof serialized !== "string") return serialized;
1318
+ if (serialized.length <= 10485760) return serialized;
1319
+ logger.warn(`Laminar: span ${kind} is ${serialized.length} bytes, which exceeds the ${MAX_MANUAL_SPAN_PAYLOAD_SIZE} byte limit. Truncating to the limit; the recorded value will not be valid JSON.`);
1320
+ const keep = MAX_MANUAL_SPAN_PAYLOAD_SIZE - 23;
1321
+ return serialized.slice(0, keep) + TRUNCATION_SUFFIX;
1322
+ };
1323
+ const isOtelAttributeValueType = (value) => {
1324
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return true;
1325
+ if (Array.isArray(value)) {
1326
+ const allStrings = value.every((value) => value == null || typeof value === "string");
1327
+ const allNumbers = value.every((value) => value == null || typeof value === "number");
1328
+ const allBooleans = value.every((value) => value == null || typeof value === "boolean");
1329
+ return allStrings || allNumbers || allBooleans;
1420
1330
  }
1421
- get sql() {
1422
- return this._sql;
1331
+ return false;
1332
+ };
1333
+ const metadataToAttributes = (metadata) => Object.fromEntries(Object.entries(metadata).map(([key, value]) => {
1334
+ if (isOtelAttributeValueType(value)) return [`${ASSOCIATION_PROPERTIES}.metadata.${key}`, value];
1335
+ else return [`${ASSOCIATION_PROPERTIES}.metadata.${key}`, JSON.stringify(value)];
1336
+ }));
1337
+ /**
1338
+ * Get OTEL environment variable with priority order.
1339
+ * Checks in order:
1340
+ * 1. OTEL_EXPORTER_OTLP_TRACES_{varName}
1341
+ * 2. OTEL_EXPORTER_OTLP_{varName}
1342
+ * 3. OTEL_{varName}
1343
+ *
1344
+ * @param varName - The variable name (e.g., 'ENDPOINT', 'HEADERS', 'PROTOCOL')
1345
+ * @returns The environment variable value or undefined if not found
1346
+ */
1347
+ const getOtelEnvVar = (varName) => {
1348
+ const candidates = [
1349
+ `OTEL_EXPORTER_OTLP_TRACES_${varName}`,
1350
+ `OTEL_EXPORTER_OTLP_${varName}`,
1351
+ `OTEL_${varName}`
1352
+ ];
1353
+ for (const candidate of candidates) {
1354
+ const value = process?.env?.[candidate];
1355
+ if (value) return value;
1423
1356
  }
1424
- get tags() {
1425
- return this._tags;
1357
+ };
1358
+ /**
1359
+ * Check if OTEL configuration is available.
1360
+ * @returns true if OTEL endpoint is configured
1361
+ */
1362
+ const hasOtelConfig = () => !!getOtelEnvVar("ENDPOINT");
1363
+ /**
1364
+ * Parse OTEL headers string into a record object.
1365
+ * Format: key1=value1,key2=value2
1366
+ * Values are URL-decoded.
1367
+ *
1368
+ * @param headersStr - Headers string in OTEL format
1369
+ * @returns Parsed headers object
1370
+ */
1371
+ const parseOtelHeaders = (headersStr) => {
1372
+ if (!headersStr) return {};
1373
+ const headers = {};
1374
+ for (const pair of headersStr.split(",")) {
1375
+ const equalIndex = pair.indexOf("=");
1376
+ if (equalIndex !== -1) {
1377
+ const key = pair.substring(0, equalIndex).trim();
1378
+ const value = pair.substring(equalIndex + 1).trim();
1379
+ headers[key] = decodeURIComponent(value);
1380
+ }
1426
1381
  }
1427
- get traces() {
1428
- return this._traces;
1382
+ return headers;
1383
+ };
1384
+ /**
1385
+ * Validate that either Laminar API key or OTEL configuration is present.
1386
+ * Throws an error if neither is configured.
1387
+ *
1388
+ * @param apiKey - The Laminar API key (if provided)
1389
+ * @throws Error if neither API key nor OTEL configuration is present
1390
+ */
1391
+ const validateTracingConfig = (apiKey) => {
1392
+ if (!apiKey && !hasOtelConfig()) throw new Error("Please initialize the Laminar object with your project API key or set the LMNR_PROJECT_API_KEY environment variable, or configure OTEL environment variables (OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, etc.)");
1393
+ };
1394
+ const loadEnv = (options) => {
1395
+ const nodeEnv = process.env.NODE_ENV || "development";
1396
+ const envDir = process.cwd();
1397
+ const envFiles = [
1398
+ ".env",
1399
+ ".env.local",
1400
+ `.env.${nodeEnv}`,
1401
+ `.env.${nodeEnv}.local`
1402
+ ];
1403
+ const logLevel = process.env.LMNR_LOG_LEVEL ?? "info";
1404
+ const verbose = ["debug", "trace"].includes(logLevel.trim().toLowerCase());
1405
+ const quiet = options?.quiet ?? !verbose;
1406
+ (0, dotenv.config)({
1407
+ path: options?.paths ?? envFiles.map((envFile) => path.resolve(envDir, envFile)),
1408
+ quiet
1409
+ });
1410
+ };
1411
+ /**
1412
+ * Converts an API base URL to the frontend/web URL.
1413
+ * - Converts https://api.lmnr.ai to https://www.laminar.sh
1414
+ * - Removes trailing slashes
1415
+ * - For localhost/127.0.0.1, ensures a port is specified (defaults to 5667)
1416
+ *
1417
+ * @param baseUrl - The API base URL (defaults to "https://api.lmnr.ai")
1418
+ * @returns The frontend URL
1419
+ */
1420
+ const getFrontendUrl = (baseUrl, frontendPort) => {
1421
+ let url$1 = baseUrl ?? "https://api.lmnr.ai";
1422
+ if (url$1 === "https://api.lmnr.ai") url$1 = "https://www.laminar.sh";
1423
+ url$1 = url$1.replace(/\/$/, "");
1424
+ if (/localhost|127\.0\.0\.1/.test(url$1)) {
1425
+ const port = frontendPort ?? url$1.match(/:\d{1,5}$/g)?.[0]?.slice(1) ?? 5667;
1426
+ if (/:(\d{1,5})$/.test(url$1)) url$1 = url$1.replace(/:\d{1,5}$/g, `:${port}`);
1427
+ else url$1 = `${url$1}:${port}`;
1429
1428
  }
1429
+ return url$1;
1430
1430
  };
1431
1431
  //#endregion
1432
1432
  Object.defineProperty(exports, "ASSOCIATION_PROPERTIES", {
@@ -1618,13 +1618,13 @@ Object.defineProperty(exports, "getOtelEnvVar", {
1618
1618
  Object.defineProperty(exports, "initializeLogger", {
1619
1619
  enumerable: true,
1620
1620
  get: function() {
1621
- return initializeLogger$1;
1621
+ return initializeLogger;
1622
1622
  }
1623
1623
  });
1624
1624
  Object.defineProperty(exports, "loadEnv", {
1625
1625
  enumerable: true,
1626
1626
  get: function() {
1627
- return loadEnv$1;
1627
+ return loadEnv;
1628
1628
  }
1629
1629
  });
1630
1630
  Object.defineProperty(exports, "metadataToAttributes", {
@@ -1636,7 +1636,7 @@ Object.defineProperty(exports, "metadataToAttributes", {
1636
1636
  Object.defineProperty(exports, "newUUID", {
1637
1637
  enumerable: true,
1638
1638
  get: function() {
1639
- return newUUID$1;
1639
+ return newUUID;
1640
1640
  }
1641
1641
  });
1642
1642
  Object.defineProperty(exports, "normalizeOtelSpanId", {
@@ -1654,13 +1654,13 @@ Object.defineProperty(exports, "normalizeOtelTraceId", {
1654
1654
  Object.defineProperty(exports, "otelSpanIdToUUID", {
1655
1655
  enumerable: true,
1656
1656
  get: function() {
1657
- return otelSpanIdToUUID$1;
1657
+ return otelSpanIdToUUID;
1658
1658
  }
1659
1659
  });
1660
1660
  Object.defineProperty(exports, "otelTraceIdToUUID", {
1661
1661
  enumerable: true,
1662
1662
  get: function() {
1663
- return otelTraceIdToUUID$1;
1663
+ return otelTraceIdToUUID;
1664
1664
  }
1665
1665
  });
1666
1666
  Object.defineProperty(exports, "parseOtelHeaders", {
@@ -1690,8 +1690,8 @@ Object.defineProperty(exports, "validateTracingConfig", {
1690
1690
  Object.defineProperty(exports, "version", {
1691
1691
  enumerable: true,
1692
1692
  get: function() {
1693
- return version$1;
1693
+ return version;
1694
1694
  }
1695
1695
  });
1696
1696
 
1697
- //# sourceMappingURL=dist-BtB31bk1.cjs.map
1697
+ //# sourceMappingURL=utils-CatgN6Pb.cjs.map