@lmnr-ai/lmnr 0.8.27 → 0.8.28
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.
- package/dist/chunk-BN4qSVkS.cjs +50 -0
- package/dist/cli.cjs +7 -6
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.d.cts +1 -1
- package/dist/cli.d.mts +1 -1
- package/dist/cli.mjs +3 -3
- package/dist/consts-Cx9iKRmq.cjs +23 -0
- package/dist/consts-Cx9iKRmq.cjs.map +1 -0
- package/dist/consts-ivIFfgfN.mjs +12 -0
- package/dist/consts-ivIFfgfN.mjs.map +1 -0
- package/dist/{dist-NGq4u898.cjs → dist-BWFjum5L.cjs} +85 -6
- package/dist/dist-BWFjum5L.cjs.map +1 -0
- package/dist/{dist-xQn-Qurn.mjs → dist-K0otr9Ia.mjs} +82 -4
- package/dist/dist-K0otr9Ia.mjs.map +1 -0
- package/dist/{evaluations-DaLDCsj5.d.mts → evaluations-Cs-tqViJ.d.mts} +129 -3
- package/dist/{evaluations-53vcYI1f.d.cts → evaluations-Db2jWbjf.d.cts} +129 -3
- package/dist/{file-utils-g9E9zyDK.mjs → file-utils-CHgYB_Ei.mjs} +2 -2
- package/dist/{file-utils-g9E9zyDK.mjs.map → file-utils-CHgYB_Ei.mjs.map} +1 -1
- package/dist/{file-utils-D_KglJSl.cjs → file-utils-Cysp1Ym1.cjs} +8 -7
- package/dist/{file-utils-D_KglJSl.cjs.map → file-utils-Cysp1Ym1.cjs.map} +1 -1
- package/dist/index.cjs +1742 -815
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +209 -2
- package/dist/index.d.mts +209 -2
- package/dist/index.mjs +1729 -810
- package/dist/index.mjs.map +1 -1
- package/dist/opentelemetry-lib/instrumentation/temporal/workflow-interceptors.cjs +8037 -0
- package/dist/opentelemetry-lib/instrumentation/temporal/workflow-interceptors.cjs.map +1 -0
- package/dist/opentelemetry-lib/instrumentation/temporal/workflow-interceptors.d.cts +113173 -0
- package/dist/opentelemetry-lib/instrumentation/temporal/workflow-interceptors.d.mts +113173 -0
- package/dist/opentelemetry-lib/instrumentation/temporal/workflow-interceptors.mjs +8036 -0
- package/dist/opentelemetry-lib/instrumentation/temporal/workflow-interceptors.mjs.map +1 -0
- package/dist/{utils-ZnY1kHzq.mjs → utils-Bdv7YZH7.mjs} +26 -2
- package/dist/utils-Bdv7YZH7.mjs.map +1 -0
- package/dist/{utils-DyFz8xv4.cjs → utils-C_Pf3r64.cjs} +29 -54
- package/dist/utils-C_Pf3r64.cjs.map +1 -0
- package/package.json +13 -3
- package/dist/dist-NGq4u898.cjs.map +0 -1
- package/dist/dist-xQn-Qurn.mjs.map +0 -1
- package/dist/utils-DyFz8xv4.cjs.map +0 -1
- package/dist/utils-ZnY1kHzq.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dist-K0otr9Ia.mjs","names":[],"sources":["../package.json","../../client/dist/index.mjs"],"sourcesContent":["","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.28\";\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, projectApiKey) {\n\t\tthis.baseHttpUrl = baseHttpUrl;\n\t\tthis.projectApiKey = projectApiKey;\n\t}\n\theaders() {\n\t\treturn {\n\t\t\tAuthorization: `Bearer ${this.projectApiKey}`,\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tAccept: \"application/json\"\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, projectApiKey) {\n\t\tsuper(baseHttpUrl, projectApiKey);\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/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, projectApiKey) {\n\t\tsuper(baseHttpUrl, projectApiKey);\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 + \"/v1/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/**\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 + `/v1/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 + \"/v1/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 + `/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 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, projectApiKey) {\n\t\tsuper(baseHttpUrl, projectApiKey);\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* 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>} 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, projectApiKey) {\n\t\tsuper(baseHttpUrl, projectApiKey);\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/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, projectApiKey) {\n\t\tsuper(baseHttpUrl, projectApiKey);\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}/v1/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}/v1/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* 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}/v1/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}/v1/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/sql.ts\nvar SqlResource = class extends BaseResource {\n\tconstructor(baseHttpUrl, projectApiKey) {\n\t\tsuper(baseHttpUrl, projectApiKey);\n\t}\n\tasync query(sql, parameters = {}) {\n\t\tconst response = await fetch(`${this.baseHttpUrl}/v1/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};\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, projectApiKey) {\n\t\tsuper(baseHttpUrl, projectApiKey);\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\t\"traceId\": formattedTraceId,\n\t\t\t\"names\": 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, projectApiKey) {\n\t\tsuper(baseHttpUrl, projectApiKey);\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 + \"/v1/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 {\n\tconstructor({ baseUrl, projectApiKey, port } = {}) {\n\t\tloadEnv();\n\t\tthis.projectApiKey = projectApiKey ?? process.env.LMNR_PROJECT_API_KEY;\n\t\tconst httpPort = port ?? (baseUrl?.match(/:\\d{1,5}$/g) ? parseInt(baseUrl.match(/:\\d{1,5}$/g)[0].slice(1)) : 443);\n\t\tconst baseUrlNoPort = (baseUrl ?? process.env.LMNR_BASE_URL)?.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.projectApiKey);\n\t\tthis._datasets = new DatasetsResource(this.baseUrl, this.projectApiKey);\n\t\tthis._evals = new EvalsResource(this.baseUrl, this.projectApiKey);\n\t\tthis._evaluators = new EvaluatorsResource(this.baseUrl, this.projectApiKey);\n\t\tthis._rolloutSessions = new RolloutSessionsResource(this.baseUrl, this.projectApiKey);\n\t\tthis._sql = new SqlResource(this.baseUrl, this.projectApiKey);\n\t\tthis._tags = new TagsResource(this.baseUrl, this.projectApiKey);\n\t\tthis._traces = new TracesResource(this.baseUrl, this.projectApiKey);\n\t}\n\tget browserEvents() {\n\t\treturn this._browserEvents;\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 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"],"mappings":";;;;;;;;;;ACOA,IAAI,UAAU;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;;AAIR,IAAI,eAAe,MAAM;CACxB,YAAY,aAAa,eAAe;EACvC,KAAK,cAAc;EACnB,KAAK,gBAAgB;;CAEtB,UAAU;EACT,OAAO;GACN,eAAe,UAAU,KAAK;GAC9B,gBAAgB;GAChB,QAAQ;GACR;;CAEF,MAAM,YAAY,UAAU;EAC3B,MAAM,WAAW,MAAM,SAAS,M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1G,KAAK,UAAU,GAAG,iBAAiB,sBAAsB,GAAG;EAC5D,KAAK,iBAAiB,IAAI,sBAAsB,KAAK,SAAS,KAAK,cAAc;EACjF,KAAK,YAAY,IAAI,iBAAiB,KAAK,SAAS,KAAK,cAAc;EACvE,KAAK,SAAS,IAAI,cAAc,KAAK,SAAS,KAAK,cAAc;EACjE,KAAK,cAAc,IAAI,mBAAmB,KAAK,SAAS,KAAK,cAAc;EAC3E,KAAK,mBAAmB,IAAI,wBAAwB,KAAK,SAAS,KAAK,cAAc;EACrF,KAAK,OAAO,IAAI,YAAY,KAAK,SAAS,KAAK,cAAc;EAC7D,KAAK,QAAQ,IAAI,aAAa,KAAK,SAAS,KAAK,cAAc;EAC/D,KAAK,UAAU,IAAI,eAAe,KAAK,SAAS,KAAK,cAAc;;CAEpE,IAAI,gBAAgB;EACnB,OAAO,KAAK;;CAEb,IAAI,WAAW;EACd,OAAO,KAAK;;CAEb,IAAI,QAAQ;EACX,OAAO,KAAK;;CAEb,IAAI,aAAa;EAChB,OAAO,KAAK;;CAEb,IAAI,kBAAkB;EACrB,OAAO,KAAK;;CAEb,IAAI,MAAM;EACT,OAAO,KAAK;;CAEb,IAAI,OAAO;EACV,OAAO,KAAK;;CAEb,IAAI,SAAS;EACZ,OAAO,KAAK"}
|
|
@@ -31,8 +31,20 @@ interface SessionRecordingOptions {
|
|
|
31
31
|
} //#endregion
|
|
32
32
|
//#region src/debug.d.ts
|
|
33
33
|
/**
|
|
34
|
-
* A single cached LLM
|
|
35
|
-
*
|
|
34
|
+
* A single cached LLM response served by a debug-replay cache HIT. The provider
|
|
35
|
+
* wrappers consume `output` (a JSON string) and `attributes` to reconstruct the
|
|
36
|
+
* call result; `name`/`input` are unused by replay.
|
|
37
|
+
*/
|
|
38
|
+
interface CachedSpan {
|
|
39
|
+
name: string;
|
|
40
|
+
input: string;
|
|
41
|
+
output: string;
|
|
42
|
+
attributes: Record<string, any>;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The debug-run pointer (§5). Emitted once at process shutdown as a console line
|
|
46
|
+
* and to `${CWD}/.lmnr/last-run.json`. Key order is part of the cross-language
|
|
47
|
+
* parity contract with the Python SDK.
|
|
36
48
|
*/
|
|
37
49
|
//#endregion
|
|
38
50
|
//#region src/utils.d.ts
|
|
@@ -108,6 +120,27 @@ declare enum TracingLevel {
|
|
|
108
120
|
META_ONLY = "meta_only",
|
|
109
121
|
ALL = "all"
|
|
110
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* Debugger context propagated as ONE nested block of a LaminarSpanContext.
|
|
125
|
+
*
|
|
126
|
+
* Carries the debug-replay v2 coordinates a downstream run needs to consult the
|
|
127
|
+
* same server-side cache window as the run that produced this context. Laminar
|
|
128
|
+
* is the only producer; a hand-forged or `enabled: false` block is treated as
|
|
129
|
+
* absent by the consumer (behaviour is explicitly undefined).
|
|
130
|
+
*
|
|
131
|
+
* enabled - armed flag — only `true` blocks are ever constructed by us.
|
|
132
|
+
* sessionId - the run's session id, a hyphenated UUID (undefined when absent).
|
|
133
|
+
* replayTraceId - the source trace to replay, a hyphenated UUID (undefined when
|
|
134
|
+
* absent).
|
|
135
|
+
* cacheUntil - the cache-window span-id needle, kept VERBATIM (hyphenated or
|
|
136
|
+
* not, full UUID or short suffix) — the server resolves it.
|
|
137
|
+
*/
|
|
138
|
+
type DebugContext = {
|
|
139
|
+
enabled: boolean;
|
|
140
|
+
sessionId?: string;
|
|
141
|
+
replayTraceId?: string;
|
|
142
|
+
cacheUntil?: string;
|
|
143
|
+
};
|
|
111
144
|
/**
|
|
112
145
|
* Laminar representation of an OpenTelemetry span context.
|
|
113
146
|
*
|
|
@@ -116,6 +149,7 @@ declare enum TracingLevel {
|
|
|
116
149
|
* isRemote - Whether the span is remote.
|
|
117
150
|
* spanPath - The span path (span names) leading to this span.
|
|
118
151
|
* spanIdsPath - The span IDs path leading to this span.
|
|
152
|
+
* debug - Propagated debugger context, if any (debug-replay v2).
|
|
119
153
|
*/
|
|
120
154
|
type LaminarSpanContext = {
|
|
121
155
|
spanId: StringUUID$1;
|
|
@@ -128,6 +162,7 @@ type LaminarSpanContext = {
|
|
|
128
162
|
metadata?: Record<string, any>;
|
|
129
163
|
traceType?: TraceType;
|
|
130
164
|
tracingLevel?: TracingLevel;
|
|
165
|
+
debug?: DebugContext;
|
|
131
166
|
};
|
|
132
167
|
type Event = {
|
|
133
168
|
id: StringUUID$1;
|
|
@@ -390,6 +425,24 @@ declare class EvaluatorsResource extends BaseResource {
|
|
|
390
425
|
score(options: ScoreOptions): Promise<void>;
|
|
391
426
|
} //#endregion
|
|
392
427
|
//#region src/resources/rollout-sessions.d.ts
|
|
428
|
+
/**
|
|
429
|
+
* Result of a debug-replay cache lookup (debug-replay v2).
|
|
430
|
+
*
|
|
431
|
+
* - `hit` — the server served a cached response for this input hash; replay it
|
|
432
|
+
* and mark the span CACHED.
|
|
433
|
+
* - `miss` — no cache entry; the caller latches process-wide live mode and runs
|
|
434
|
+
* every subsequent call live.
|
|
435
|
+
* - `live` — run THIS call live without latching (server COLD warmup-timeout
|
|
436
|
+
* degrade, or any non-OK / transport error here).
|
|
437
|
+
*/
|
|
438
|
+
type CacheOutcome = {
|
|
439
|
+
kind: "hit";
|
|
440
|
+
cached: CachedSpan;
|
|
441
|
+
} | {
|
|
442
|
+
kind: "miss";
|
|
443
|
+
} | {
|
|
444
|
+
kind: "live";
|
|
445
|
+
};
|
|
393
446
|
declare class RolloutSessionsResource extends BaseResource {
|
|
394
447
|
constructor(baseHttpUrl: string, projectApiKey: string);
|
|
395
448
|
/**
|
|
@@ -420,6 +473,31 @@ declare class RolloutSessionsResource extends BaseResource {
|
|
|
420
473
|
sessionId: string;
|
|
421
474
|
name: string;
|
|
422
475
|
}): Promise<void>;
|
|
476
|
+
/**
|
|
477
|
+
* Look up the debug-replay cache for a single LLM call (debug-replay v2).
|
|
478
|
+
*
|
|
479
|
+
* The server is keyed by `inputHash` (hex blake3 of the canonicalized,
|
|
480
|
+
* system-stripped input messages). It returns one of three outcomes:
|
|
481
|
+
* - `{ outcome: "hit", response }` — a cached response to replay.
|
|
482
|
+
* - `{ outcome: "miss" }` — no entry; caller latches live mode.
|
|
483
|
+
* - `{ outcome: "live" }` — run this call live (COLD degrade).
|
|
484
|
+
*
|
|
485
|
+
* Error posture: a non-OK response or a transport error degrades to
|
|
486
|
+
* `{ kind: "live" }` for THIS call only — it never throws and never latches
|
|
487
|
+
* the process-wide live flag (only a real MISS does that). This keeps a flaky
|
|
488
|
+
* cache backend from turning a replay into a crash.
|
|
489
|
+
*/
|
|
490
|
+
cache({
|
|
491
|
+
sessionId,
|
|
492
|
+
replayTraceId,
|
|
493
|
+
cacheUntil,
|
|
494
|
+
inputHash
|
|
495
|
+
}: {
|
|
496
|
+
sessionId: string;
|
|
497
|
+
replayTraceId: string;
|
|
498
|
+
cacheUntil: string;
|
|
499
|
+
inputHash: string;
|
|
500
|
+
}): Promise<CacheOutcome>;
|
|
423
501
|
delete({
|
|
424
502
|
sessionId
|
|
425
503
|
}: {
|
|
@@ -30772,6 +30850,54 @@ interface InitializeOptions {
|
|
|
30772
30850
|
* ```
|
|
30773
30851
|
*/
|
|
30774
30852
|
openAIAgents?: any;
|
|
30853
|
+
/**
|
|
30854
|
+
* Auto-patch Temporal Worker and Client so that every `Worker.create()` and
|
|
30855
|
+
* `new Client()` call automatically includes Laminar's interceptors for
|
|
30856
|
+
* distributed trace context propagation.
|
|
30857
|
+
*
|
|
30858
|
+
* Pass the `@temporalio/worker` module as `worker` and the `Client` class
|
|
30859
|
+
* from `@temporalio/client` as `Client`. Both are optional — omit one to
|
|
30860
|
+
* skip patching that side.
|
|
30861
|
+
*
|
|
30862
|
+
* @example
|
|
30863
|
+
* ```typescript
|
|
30864
|
+
* import * as temporalWorker from '@temporalio/worker';
|
|
30865
|
+
* import * as temporalClient from '@temporalio/client';
|
|
30866
|
+
* import { Laminar } from '@lmnr-ai/lmnr';
|
|
30867
|
+
*
|
|
30868
|
+
* Laminar.initialize({
|
|
30869
|
+
* instrumentModules: {
|
|
30870
|
+
* temporal: { worker: temporalWorker, client: temporalClient },
|
|
30871
|
+
* },
|
|
30872
|
+
* });
|
|
30873
|
+
*
|
|
30874
|
+
* // Now every Worker.create() and new temporalClient.Client() include
|
|
30875
|
+
* // Laminar interceptors.
|
|
30876
|
+
* const worker = await temporalWorker.Worker.create({ ... });
|
|
30877
|
+
* const client = new temporalClient.Client({ ... });
|
|
30878
|
+
* ```
|
|
30879
|
+
*/
|
|
30880
|
+
temporal?: {
|
|
30881
|
+
/** The `@temporalio/worker` module (import * as temporalWorker from '@temporalio/worker') */worker?: any; /** The `@temporalio/client` module (import * as temporalClient from '@temporalio/client') */
|
|
30882
|
+
client?: any;
|
|
30883
|
+
/**
|
|
30884
|
+
* If true (default), wrap each activity execution in a Laminar span.
|
|
30885
|
+
* Set to false to only restore the parent context.
|
|
30886
|
+
*/
|
|
30887
|
+
createActivitySpan?: boolean;
|
|
30888
|
+
/**
|
|
30889
|
+
* If true (default), record activity arguments as the activity span
|
|
30890
|
+
* input. Set to false to omit them. Ignored when `createActivitySpan`
|
|
30891
|
+
* is false.
|
|
30892
|
+
*/
|
|
30893
|
+
recordActivityArgs?: boolean;
|
|
30894
|
+
/**
|
|
30895
|
+
* If true (default), record the activity return value as the activity
|
|
30896
|
+
* span output. Set to false to omit it. Ignored when
|
|
30897
|
+
* `createActivitySpan` is false.
|
|
30898
|
+
*/
|
|
30899
|
+
recordActivityOutput?: boolean;
|
|
30900
|
+
};
|
|
30775
30901
|
};
|
|
30776
30902
|
/**
|
|
30777
30903
|
* Whether to silence the initialization message. Optional.
|
|
@@ -31033,4 +31159,4 @@ declare function evaluate<D, T, O>({
|
|
|
31033
31159
|
}: EvaluationConstructorProps<D, T, O>): Promise<EvaluationRunResult | undefined>;
|
|
31034
31160
|
//#endregion
|
|
31035
31161
|
export { TracingLevel as S, MaskInputOptions as _, HumanEvaluator as a, SpanType as b, InitializeOptions as c, LaminarClient as d, Dataset as f, LaminarSpanContext as g, Event as h, EvaluatorFunctionReturn as i, EvaluationDataset as l, EvaluationDatapointDatasetLink as m, Evaluation as n, evaluate as o, EvaluationDatapoint as p, EvaluatorFunction as r, StringUUID as s, Datapoint as t, LaminarDataset as u, PushDatapointsResponse as v, TraceType as x, SessionRecordingOptions as y };
|
|
31036
|
-
//# sourceMappingURL=evaluations-
|
|
31162
|
+
//# sourceMappingURL=evaluations-Cs-tqViJ.d.mts.map
|
|
@@ -30,8 +30,20 @@ interface SessionRecordingOptions {
|
|
|
30
30
|
} //#endregion
|
|
31
31
|
//#region src/debug.d.ts
|
|
32
32
|
/**
|
|
33
|
-
* A single cached LLM
|
|
34
|
-
*
|
|
33
|
+
* A single cached LLM response served by a debug-replay cache HIT. The provider
|
|
34
|
+
* wrappers consume `output` (a JSON string) and `attributes` to reconstruct the
|
|
35
|
+
* call result; `name`/`input` are unused by replay.
|
|
36
|
+
*/
|
|
37
|
+
interface CachedSpan {
|
|
38
|
+
name: string;
|
|
39
|
+
input: string;
|
|
40
|
+
output: string;
|
|
41
|
+
attributes: Record<string, any>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The debug-run pointer (§5). Emitted once at process shutdown as a console line
|
|
45
|
+
* and to `${CWD}/.lmnr/last-run.json`. Key order is part of the cross-language
|
|
46
|
+
* parity contract with the Python SDK.
|
|
35
47
|
*/
|
|
36
48
|
//#endregion
|
|
37
49
|
//#region src/utils.d.ts
|
|
@@ -107,6 +119,27 @@ declare enum TracingLevel {
|
|
|
107
119
|
META_ONLY = "meta_only",
|
|
108
120
|
ALL = "all"
|
|
109
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* Debugger context propagated as ONE nested block of a LaminarSpanContext.
|
|
124
|
+
*
|
|
125
|
+
* Carries the debug-replay v2 coordinates a downstream run needs to consult the
|
|
126
|
+
* same server-side cache window as the run that produced this context. Laminar
|
|
127
|
+
* is the only producer; a hand-forged or `enabled: false` block is treated as
|
|
128
|
+
* absent by the consumer (behaviour is explicitly undefined).
|
|
129
|
+
*
|
|
130
|
+
* enabled - armed flag — only `true` blocks are ever constructed by us.
|
|
131
|
+
* sessionId - the run's session id, a hyphenated UUID (undefined when absent).
|
|
132
|
+
* replayTraceId - the source trace to replay, a hyphenated UUID (undefined when
|
|
133
|
+
* absent).
|
|
134
|
+
* cacheUntil - the cache-window span-id needle, kept VERBATIM (hyphenated or
|
|
135
|
+
* not, full UUID or short suffix) — the server resolves it.
|
|
136
|
+
*/
|
|
137
|
+
type DebugContext = {
|
|
138
|
+
enabled: boolean;
|
|
139
|
+
sessionId?: string;
|
|
140
|
+
replayTraceId?: string;
|
|
141
|
+
cacheUntil?: string;
|
|
142
|
+
};
|
|
110
143
|
/**
|
|
111
144
|
* Laminar representation of an OpenTelemetry span context.
|
|
112
145
|
*
|
|
@@ -115,6 +148,7 @@ declare enum TracingLevel {
|
|
|
115
148
|
* isRemote - Whether the span is remote.
|
|
116
149
|
* spanPath - The span path (span names) leading to this span.
|
|
117
150
|
* spanIdsPath - The span IDs path leading to this span.
|
|
151
|
+
* debug - Propagated debugger context, if any (debug-replay v2).
|
|
118
152
|
*/
|
|
119
153
|
type LaminarSpanContext = {
|
|
120
154
|
spanId: StringUUID$1;
|
|
@@ -127,6 +161,7 @@ type LaminarSpanContext = {
|
|
|
127
161
|
metadata?: Record<string, any>;
|
|
128
162
|
traceType?: TraceType;
|
|
129
163
|
tracingLevel?: TracingLevel;
|
|
164
|
+
debug?: DebugContext;
|
|
130
165
|
};
|
|
131
166
|
type Event = {
|
|
132
167
|
id: StringUUID$1;
|
|
@@ -389,6 +424,24 @@ declare class EvaluatorsResource extends BaseResource {
|
|
|
389
424
|
score(options: ScoreOptions): Promise<void>;
|
|
390
425
|
} //#endregion
|
|
391
426
|
//#region src/resources/rollout-sessions.d.ts
|
|
427
|
+
/**
|
|
428
|
+
* Result of a debug-replay cache lookup (debug-replay v2).
|
|
429
|
+
*
|
|
430
|
+
* - `hit` — the server served a cached response for this input hash; replay it
|
|
431
|
+
* and mark the span CACHED.
|
|
432
|
+
* - `miss` — no cache entry; the caller latches process-wide live mode and runs
|
|
433
|
+
* every subsequent call live.
|
|
434
|
+
* - `live` — run THIS call live without latching (server COLD warmup-timeout
|
|
435
|
+
* degrade, or any non-OK / transport error here).
|
|
436
|
+
*/
|
|
437
|
+
type CacheOutcome = {
|
|
438
|
+
kind: "hit";
|
|
439
|
+
cached: CachedSpan;
|
|
440
|
+
} | {
|
|
441
|
+
kind: "miss";
|
|
442
|
+
} | {
|
|
443
|
+
kind: "live";
|
|
444
|
+
};
|
|
392
445
|
declare class RolloutSessionsResource extends BaseResource {
|
|
393
446
|
constructor(baseHttpUrl: string, projectApiKey: string);
|
|
394
447
|
/**
|
|
@@ -419,6 +472,31 @@ declare class RolloutSessionsResource extends BaseResource {
|
|
|
419
472
|
sessionId: string;
|
|
420
473
|
name: string;
|
|
421
474
|
}): Promise<void>;
|
|
475
|
+
/**
|
|
476
|
+
* Look up the debug-replay cache for a single LLM call (debug-replay v2).
|
|
477
|
+
*
|
|
478
|
+
* The server is keyed by `inputHash` (hex blake3 of the canonicalized,
|
|
479
|
+
* system-stripped input messages). It returns one of three outcomes:
|
|
480
|
+
* - `{ outcome: "hit", response }` — a cached response to replay.
|
|
481
|
+
* - `{ outcome: "miss" }` — no entry; caller latches live mode.
|
|
482
|
+
* - `{ outcome: "live" }` — run this call live (COLD degrade).
|
|
483
|
+
*
|
|
484
|
+
* Error posture: a non-OK response or a transport error degrades to
|
|
485
|
+
* `{ kind: "live" }` for THIS call only — it never throws and never latches
|
|
486
|
+
* the process-wide live flag (only a real MISS does that). This keeps a flaky
|
|
487
|
+
* cache backend from turning a replay into a crash.
|
|
488
|
+
*/
|
|
489
|
+
cache({
|
|
490
|
+
sessionId,
|
|
491
|
+
replayTraceId,
|
|
492
|
+
cacheUntil,
|
|
493
|
+
inputHash
|
|
494
|
+
}: {
|
|
495
|
+
sessionId: string;
|
|
496
|
+
replayTraceId: string;
|
|
497
|
+
cacheUntil: string;
|
|
498
|
+
inputHash: string;
|
|
499
|
+
}): Promise<CacheOutcome>;
|
|
422
500
|
delete({
|
|
423
501
|
sessionId
|
|
424
502
|
}: {
|
|
@@ -30771,6 +30849,54 @@ interface InitializeOptions {
|
|
|
30771
30849
|
* ```
|
|
30772
30850
|
*/
|
|
30773
30851
|
openAIAgents?: any;
|
|
30852
|
+
/**
|
|
30853
|
+
* Auto-patch Temporal Worker and Client so that every `Worker.create()` and
|
|
30854
|
+
* `new Client()` call automatically includes Laminar's interceptors for
|
|
30855
|
+
* distributed trace context propagation.
|
|
30856
|
+
*
|
|
30857
|
+
* Pass the `@temporalio/worker` module as `worker` and the `Client` class
|
|
30858
|
+
* from `@temporalio/client` as `Client`. Both are optional — omit one to
|
|
30859
|
+
* skip patching that side.
|
|
30860
|
+
*
|
|
30861
|
+
* @example
|
|
30862
|
+
* ```typescript
|
|
30863
|
+
* import * as temporalWorker from '@temporalio/worker';
|
|
30864
|
+
* import * as temporalClient from '@temporalio/client';
|
|
30865
|
+
* import { Laminar } from '@lmnr-ai/lmnr';
|
|
30866
|
+
*
|
|
30867
|
+
* Laminar.initialize({
|
|
30868
|
+
* instrumentModules: {
|
|
30869
|
+
* temporal: { worker: temporalWorker, client: temporalClient },
|
|
30870
|
+
* },
|
|
30871
|
+
* });
|
|
30872
|
+
*
|
|
30873
|
+
* // Now every Worker.create() and new temporalClient.Client() include
|
|
30874
|
+
* // Laminar interceptors.
|
|
30875
|
+
* const worker = await temporalWorker.Worker.create({ ... });
|
|
30876
|
+
* const client = new temporalClient.Client({ ... });
|
|
30877
|
+
* ```
|
|
30878
|
+
*/
|
|
30879
|
+
temporal?: {
|
|
30880
|
+
/** The `@temporalio/worker` module (import * as temporalWorker from '@temporalio/worker') */worker?: any; /** The `@temporalio/client` module (import * as temporalClient from '@temporalio/client') */
|
|
30881
|
+
client?: any;
|
|
30882
|
+
/**
|
|
30883
|
+
* If true (default), wrap each activity execution in a Laminar span.
|
|
30884
|
+
* Set to false to only restore the parent context.
|
|
30885
|
+
*/
|
|
30886
|
+
createActivitySpan?: boolean;
|
|
30887
|
+
/**
|
|
30888
|
+
* If true (default), record activity arguments as the activity span
|
|
30889
|
+
* input. Set to false to omit them. Ignored when `createActivitySpan`
|
|
30890
|
+
* is false.
|
|
30891
|
+
*/
|
|
30892
|
+
recordActivityArgs?: boolean;
|
|
30893
|
+
/**
|
|
30894
|
+
* If true (default), record the activity return value as the activity
|
|
30895
|
+
* span output. Set to false to omit it. Ignored when
|
|
30896
|
+
* `createActivitySpan` is false.
|
|
30897
|
+
*/
|
|
30898
|
+
recordActivityOutput?: boolean;
|
|
30899
|
+
};
|
|
30774
30900
|
};
|
|
30775
30901
|
/**
|
|
30776
30902
|
* Whether to silence the initialization message. Optional.
|
|
@@ -31032,4 +31158,4 @@ declare function evaluate<D, T, O>({
|
|
|
31032
31158
|
}: EvaluationConstructorProps<D, T, O>): Promise<EvaluationRunResult | undefined>;
|
|
31033
31159
|
//#endregion
|
|
31034
31160
|
export { __exportAll as C, TracingLevel as S, MaskInputOptions as _, HumanEvaluator as a, SpanType as b, InitializeOptions as c, LaminarClient as d, Dataset as f, LaminarSpanContext as g, Event as h, EvaluatorFunctionReturn as i, EvaluationDataset as l, EvaluationDatapointDatasetLink as m, Evaluation as n, evaluate as o, EvaluationDatapoint as p, EvaluatorFunction as r, StringUUID as s, Datapoint as t, LaminarDataset as u, PushDatapointsResponse as v, TraceType as x, SessionRecordingOptions as y };
|
|
31035
|
-
//# sourceMappingURL=evaluations-
|
|
31161
|
+
//# sourceMappingURL=evaluations-Db2jWbjf.d.cts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { i as __toESM, n as __exportAll, r as __require, t as __commonJSMin } from "./chunk-hT5z_Zn9.mjs";
|
|
2
|
-
import { L as errorMessage, s as initializeLogger } from "./utils-
|
|
2
|
+
import { L as errorMessage, s as initializeLogger } from "./utils-Bdv7YZH7.mjs";
|
|
3
3
|
import * as path from "path";
|
|
4
4
|
import { createReadStream } from "fs";
|
|
5
5
|
import * as fs from "fs/promises";
|
|
@@ -514,4 +514,4 @@ const printToConsole = (data, format = "json") => {
|
|
|
514
514
|
//#endregion
|
|
515
515
|
export { writeToFile as i, loadFromPaths as n, printToConsole as r, file_utils_exports as t };
|
|
516
516
|
|
|
517
|
-
//# sourceMappingURL=file-utils-
|
|
517
|
+
//# sourceMappingURL=file-utils-CHgYB_Ei.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-utils-g9E9zyDK.mjs","names":["asString","generateCsv","mkConfig"],"sources":["../../../node_modules/.pnpm/csv-parser@3.2.1/node_modules/csv-parser/index.js","../../../node_modules/.pnpm/export-to-csv@1.4.0/node_modules/export-to-csv/output/index.js","../src/cli/file-utils.ts"],"sourcesContent":["const { Transform } = require('stream')\n\nconst [cr] = Buffer.from('\\r')\nconst [nl] = Buffer.from('\\n')\nconst defaults = {\n escape: '\"',\n headers: null,\n mapHeaders: ({ header }) => header,\n mapValues: ({ value }) => value,\n newline: '\\n',\n quote: '\"',\n raw: false,\n separator: ',',\n skipComments: false,\n skipLines: null,\n maxRowBytes: Number.MAX_SAFE_INTEGER,\n strict: false,\n outputByteOffset: false\n}\n\nconst DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype'])\n\nfunction sanitizeHeader(header) {\n if (typeof header !== 'string') {\n return null\n }\n\n if (DANGEROUS_KEYS.has(header)) {\n return null\n }\n\n return header\n}\n\nclass CsvParser extends Transform {\n constructor (opts = {}) {\n super({ objectMode: true, highWaterMark: 16 })\n\n if (Array.isArray(opts)) opts = { headers: opts }\n\n const options = Object.assign({}, defaults, opts)\n\n options.customNewline = options.newline !== defaults.newline\n\n for (const key of ['newline', 'quote', 'separator']) {\n if (typeof options[key] !== 'undefined') {\n ([options[key]] = Buffer.from(options[key]))\n }\n }\n\n // if escape is not defined on the passed options, use the end value of quote\n options.escape = (opts || {}).escape ? Buffer.from(options.escape)[0] : options.quote\n\n this.state = {\n empty: options.raw ? Buffer.alloc(0) : '',\n escaped: false,\n first: true,\n lineNumber: 0,\n previousEnd: 0,\n rowLength: 0,\n quoted: false\n }\n\n this._prev = null\n\n if (options.headers === false) {\n // enforce, as the column length check will fail if headers:false\n options.strict = false\n }\n\n if (options.headers || options.headers === false) {\n this.state.first = false\n }\n\n this.options = options\n this.headers = options.headers\n this.bytesRead = 0\n }\n\n parseCell (buffer, start, end) {\n const { escape, quote } = this.options\n // remove quotes from quoted cells\n if (buffer[start] === quote && buffer[end - 1] === quote) {\n start++\n end--\n }\n\n let y = start\n\n for (let i = start; i < end; i++) {\n // check for escape characters and skip them\n if (buffer[i] === escape && i + 1 < end && buffer[i + 1] === quote) {\n i++\n }\n\n if (y !== i) {\n buffer[y] = buffer[i]\n }\n y++\n }\n\n return this.parseValue(buffer, start, y)\n }\n\n parseLine (buffer, start, end) {\n const { customNewline, escape, mapHeaders, mapValues, quote, separator, skipComments, skipLines } = this.options\n\n end-- // trim newline\n if (!customNewline && buffer.length && buffer[end - 1] === cr) {\n end--\n }\n\n const comma = separator\n const cells = []\n let isQuoted = false\n let offset = start\n\n if (skipComments) {\n const char = typeof skipComments === 'string' ? skipComments : '#'\n if (buffer[start] === Buffer.from(char)[0]) {\n return\n }\n }\n\n const mapValue = (value) => {\n if (this.state.first) {\n return value\n }\n\n const index = cells.length\n const header = this.headers[index]\n\n return mapValues({ header, index, value })\n }\n\n for (let i = start; i < end; i++) {\n const isStartingQuote = !isQuoted && buffer[i] === quote\n const isEndingQuote = isQuoted && buffer[i] === quote && i + 1 <= end && buffer[i + 1] === comma\n const isEscape = isQuoted && buffer[i] === escape && i + 1 < end && buffer[i + 1] === quote\n\n if (isStartingQuote || isEndingQuote) {\n isQuoted = !isQuoted\n continue\n } else if (isEscape) {\n i++\n continue\n }\n\n if (buffer[i] === comma && !isQuoted) {\n let value = this.parseCell(buffer, offset, i)\n value = mapValue(value)\n cells.push(value)\n offset = i + 1\n }\n }\n\n if (offset < end) {\n let value = this.parseCell(buffer, offset, end)\n value = mapValue(value)\n cells.push(value)\n }\n\n if (buffer[end - 1] === comma) {\n cells.push(mapValue(this.state.empty))\n }\n\n const skip = skipLines && skipLines > this.state.lineNumber\n this.state.lineNumber++\n\n if (this.state.first && !skip) {\n this.state.first = false\n this.headers = cells.map((header, index) => {\n const mapped = mapHeaders({ header, index })\n\n if (mapped === null) {\n return null\n }\n\n return sanitizeHeader(mapped)\n })\n\n this.emit('headers', this.headers)\n return\n }\n\n if (!skip && this.options.strict && cells.length !== this.headers.length) {\n const e = new RangeError('Row length does not match headers')\n this.emit('error', e)\n } else {\n if (!skip) {\n const byteOffset = this.bytesRead - buffer.length + start\n this.writeRow(cells, byteOffset)\n }\n }\n }\n\n parseValue (buffer, start, end) {\n if (this.options.raw) {\n return buffer.slice(start, end)\n }\n\n return buffer.toString('utf-8', start, end)\n }\n\n writeRow (cells, byteOffset) {\n const headers = (this.headers === false) ? cells.map((value, index) => index) : this.headers\n\n const row = cells.reduce((o, cell, index) => {\n const header = headers[index]\n if (header === null) return o // skip columns\n if (header !== undefined) {\n o[header] = cell\n } else {\n o[`_${index}`] = cell\n }\n return o\n }, {})\n\n if (this.options.outputByteOffset) {\n this.push({ row, byteOffset })\n } else {\n this.push(row)\n }\n }\n\n _flush (cb) {\n if (this.state.escaped || !this._prev) return cb()\n this.parseLine(this._prev, this.state.previousEnd, this._prev.length + 1) // plus since online -1s\n cb()\n }\n\n _transform (data, enc, cb) {\n if (typeof data === 'string') {\n data = Buffer.from(data)\n }\n\n const { escape, quote } = this.options\n let start = 0\n let buffer = data\n this.bytesRead += data.byteLength\n\n if (this._prev) {\n start = this._prev.length\n buffer = Buffer.concat([this._prev, data])\n this._prev = null\n }\n\n const bufferLength = buffer.length\n\n for (let i = start; i < bufferLength; i++) {\n const chr = buffer[i]\n const nextChr = i + 1 < bufferLength ? buffer[i + 1] : null\n\n this.state.rowLength++\n if (this.state.rowLength > this.options.maxRowBytes) {\n return cb(new Error('Row exceeds the maximum size'))\n }\n\n if (!this.state.escaped && chr === escape && nextChr === quote && i !== start) {\n this.state.escaped = true\n continue\n } else if (chr === quote) {\n if (this.state.escaped) {\n this.state.escaped = false\n // non-escaped quote (quoting the cell)\n } else {\n this.state.quoted = !this.state.quoted\n }\n continue\n }\n\n if (!this.state.quoted) {\n if (this.state.first && !this.options.customNewline) {\n if (chr === nl) {\n this.options.newline = nl\n } else if (chr === cr) {\n if (nextChr !== nl) {\n this.options.newline = cr\n }\n }\n }\n\n if (chr === this.options.newline) {\n this.parseLine(buffer, this.state.previousEnd, i + 1)\n this.state.previousEnd = i + 1\n this.state.rowLength = 0\n }\n }\n }\n\n if (this.state.previousEnd === bufferLength) {\n this.state.previousEnd = 0\n return cb()\n }\n\n if (bufferLength - this.state.previousEnd < data.length) {\n this._prev = data\n this.state.previousEnd -= (bufferLength - data.length)\n return cb()\n }\n\n this._prev = buffer\n cb()\n }\n}\n\nmodule.exports = (opts) => new CsvParser(opts)\n","var q;(function(x){x[\"csv\"]=\"text/csv\";x[\"tsv\"]=\"text/tab-separated-values\";x[\"plain\"]=\"text/plain\"})(q||(q={}));var X=(W)=>W,z=(W)=>W,Z=X,_=X,Y=X,N=X,V=X;var h={fieldSeparator:\",\",decimalSeparator:\".\",quoteStrings:!0,quoteCharacter:'\"',showTitle:!1,title:\"My Generated Report\",filename:\"generated\",showColumnHeaders:!0,useTextFile:!1,fileExtension:\"csv\",mediaType:q.csv,useBom:!0,columnHeaders:[],useKeysAsHeaders:!1,boolDisplay:{true:\"TRUE\",false:\"FALSE\"},replaceUndefinedWith:\"\"},F=\"\\r\\n\",R=\"\\uFEFF\",G=(W)=>Object.assign({},h,W);class K extends Error{constructor(W){super(W);this.name=\"CsvGenerationError\"}}class B extends Error{constructor(W){super(W);this.name=\"EmptyHeadersError\"}}class L extends Error{constructor(W){super(W);this.name=\"CsvDownloadEnvironmentError\"}}class P extends Error{constructor(W){super(W);this.name=\"UnsupportedDataFormatError\"}}var s=function(W,$){if($=='\"'&&W.indexOf('\"')>-1)return W.replace(/\"/g,'\"\"');return W},w=(W)=>typeof W===\"object\"?N(W.key):N(W),y=(W)=>typeof W===\"object\"?V(W.displayLabel):V(W),T=(W,...$)=>$.reduce((j,x)=>x(j),W),E=(W)=>($)=>W.useBom?_(z($)+R):$,M=(W)=>($)=>W.showTitle?S(_(z($)+W.title))(Y(\"\")):$,S=(W)=>($)=>_(z(W)+z($)+F),O=(W)=>($,j)=>l(W)(Y(z($)+z(j))),l=(W)=>($)=>X(z($)+W.fieldSeparator),b=(W,$)=>(j)=>{if(!W.showColumnHeaders)return j;if($.length<1)throw new B(\"Option to show headers but none supplied. Make sure there are keys in your collection or that you've supplied headers through the config options.\");let x=Y(\"\");for(let A=0;A<$.length;A++){const J=y($[A]);x=O(W)(x,v(W,z(J)))}return x=Y(z(x).slice(0,-1)),S(j)(x)},C=(W,$,j)=>(x)=>{let A=x;for(var J=0;J<j.length;J++){let I=Y(\"\");for(let U=0;U<$.length;U++){const H=w($[U]),D=j[J][z(H)];I=O(W)(I,v(W,D))}I=Y(z(I).slice(0,-1)),A=S(A)(I)}return A},k=z,m=(W)=>+W===W&&(!isFinite(W)||Boolean(W%1)),p=(W,$)=>{if(m($)){if(W.decimalSeparator===\"locale\")return Z($.toLocaleString());if(W.decimalSeparator)return Z($.toString().replace(\".\",W.decimalSeparator))}return Z($.toString())},Q=(W,$)=>{let j=$;if(W.quoteStrings||W.fieldSeparator&&$.indexOf(W.fieldSeparator)>-1||W.quoteCharacter&&$.indexOf(W.quoteCharacter)>-1||$.indexOf(\"\\n\")>-1||$.indexOf(\"\\r\")>-1)j=W.quoteCharacter+s($,W.quoteCharacter)+W.quoteCharacter;return Z(j)},g=(W,$)=>{const j=$?\"true\":\"false\";return Z(W.boolDisplay[j])},r=(W,$)=>{if(typeof $===\"undefined\"&&W.replaceUndefinedWith!==void 0)return Q(W,W.replaceUndefinedWith+\"\");if($===null)return Q(W,\"null\");return Q(W,\"\")},v=(W,$)=>{if(typeof $===\"number\")return p(W,$);if(typeof $===\"string\")return Q(W,$);if(typeof $===\"boolean\"&&W.boolDisplay)return g(W,$);if($===null||typeof $===\"undefined\")return r(W,$);throw new P(`\n typeof ${typeof $} isn't supported. Only number, string, boolean, null and undefined are supported.\n Please convert the data in your object to one of those before generating the CSV.\n `)};var BW=(W)=>($)=>{const j=G(W),x=j.useKeysAsHeaders?Object.keys($[0]):j.columnHeaders;let A=T(_(\"\"),E(j),M(j),b(j,x),C(j,x,$));if(z(A).length<1)throw new K(\"Output is empty. Is your data formatted correctly?\");return A},f=(W)=>($)=>{const j=G(W),x=z($),A=j.useTextFile?\"text/plain\":j.mediaType;return new Blob([x],{type:`${A};charset=utf8;`})},LW=(W)=>($)=>{if(!window)throw new L(\"Downloading only supported in a browser environment.\");const j=f(W)($),x=G(W),A=x.useTextFile?\"txt\":x.fileExtension,J=`${x.filename}.${A}`,I=document.createElement(\"a\");I.download=J,I.href=URL.createObjectURL(j),I.setAttribute(\"visibility\",\"hidden\"),document.body.appendChild(I),I.click(),document.body.removeChild(I)};export{G as mkConfig,BW as generateCsv,LW as download,k as asString,f as asBlob,q as MediaType};\n","import { errorMessage } from '@lmnr-ai/types';\nimport csv from 'csv-parser';\nimport { asString, generateCsv, mkConfig } from 'export-to-csv';\nimport { createReadStream } from 'fs';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\n\nimport { Datapoint } from '../evaluations';\nimport { initializeLogger } from '../utils';\n\nconst logger = initializeLogger();\n\n/**\n * Check if a file has a supported extension.\n */\nconst isSupportedFile = (file: string): boolean => {\n const ext = path.extname(file).toLowerCase();\n return ['.json', '.csv', '.jsonl'].includes(ext);\n};\n\n/**\n * Collect all supported files from the given paths.\n * Handles both files and directories.\n */\nexport const collectFiles = async (\n paths: string[],\n recursive: boolean = false,\n): Promise<string[]> => {\n const collectedFiles: string[] = [];\n\n for (const filepath of paths) {\n try {\n const stats = await fs.stat(filepath);\n\n if (stats.isFile()) {\n if (isSupportedFile(filepath)) {\n collectedFiles.push(filepath);\n } else {\n logger.warn(`Skipping unsupported file type: ${filepath}`);\n }\n } else if (stats.isDirectory()) {\n const entries = await fs.readdir(filepath);\n\n for (const entry of entries) {\n const fullPath = path.join(filepath, entry);\n const entryStats = await fs.stat(fullPath);\n\n if (entryStats.isFile() && isSupportedFile(fullPath)) {\n collectedFiles.push(fullPath);\n } else if (recursive && entryStats.isDirectory()) {\n const subFiles = await collectFiles([fullPath], true);\n collectedFiles.push(...subFiles);\n }\n }\n }\n } catch (error) {\n logger.warn(\n `Path does not exist or is not accessible: ${filepath}. `\n + `Error: ${errorMessage(error)}`,\n );\n }\n }\n\n return collectedFiles;\n};\n\n/**\n * Read a JSON file and return its contents.\n */\nconst readJsonFile = async (filepath: string): Promise<any[]> => {\n const content = await fs.readFile(filepath, 'utf-8');\n const parsed = JSON.parse(content);\n return Array.isArray(parsed) ? parsed : [parsed];\n};\n\n/**\n * Try to parse a string as JSON. If it fails, return the original string.\n */\nconst tryParseJson = (content: string): any => {\n // Don't try to parse if it's not a string or doesn't look like JSON\n if (typeof content !== 'string') {\n return content;\n }\n\n // If it doesn't start with { or [, it's probably not JSON\n const trimmed = content.trim();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {\n return content;\n }\n\n try {\n return JSON.parse(content);\n } catch (error) {\n logger.debug(\n `Error parsing JSON: ${errorMessage(error)}`,\n );\n return content;\n }\n};\n\n/**\n * Parse each field in a CSV row, attempting to convert JSON strings back to objects.\n */\nconst parseCsvRow = (row: Record<string, string>): any => {\n const parsed: any = {};\n for (const [key, value] of Object.entries(row)) {\n parsed[key] = tryParseJson(value);\n }\n return parsed;\n};\n\n/**\n * Read a CSV file and return its contents as an array of objects.\n */\nconst readCsvFile = async (filepath: string): Promise<any[]> => new Promise((resolve, reject) => {\n const results: any[] = [];\n createReadStream(filepath)\n .pipe(csv())\n .on('data', (data) => results.push(parseCsvRow(data)))\n .on('end', () => resolve(results))\n .on('error', reject);\n});\n\n/**\n * Read a JSONL file and return its contents as an array of objects.\n */\nasync function readJsonlFile(filepath: string): Promise<any[]> {\n const content = await fs.readFile(filepath, 'utf-8');\n const lines = content.split('\\n').filter((line) => line.trim());\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return lines.map((line) => JSON.parse(line));\n}\n\n/**\n * Read a single file and return its contents.\n */\nasync function readFile(filepath: string): Promise<any[]> {\n const ext = path.extname(filepath).toLowerCase();\n\n if (ext === '.json') {\n return readJsonFile(filepath);\n } else if (ext === '.csv') {\n return readCsvFile(filepath);\n } else if (ext === '.jsonl') {\n return readJsonlFile(filepath);\n } else {\n throw new Error(`Unsupported file type: ${ext}`);\n }\n}\n\n/**\n * Load data from all files in the specified paths.\n */\nexport const loadFromPaths = async <D = any, T = any>(\n paths: string[],\n recursive: boolean = false,\n): Promise<Datapoint<D, T>[]> => {\n const files = await collectFiles(paths, recursive);\n\n if (files.length === 0) {\n logger.warn('No supported files found in the specified paths');\n return [];\n }\n\n logger.info(`Found ${files.length} file(s) to read`);\n\n const result: Datapoint<D, T>[] = [];\n\n for (const file of files) {\n try {\n const data = await readFile(file);\n result.push(...data);\n logger.info(`Read ${data.length} record(s) from ${file}`);\n } catch (error) {\n logger.error(\n `Error reading file ${file}: ${errorMessage(error)}`,\n );\n throw error;\n }\n }\n\n return result;\n};\n\n/**\n * Write data to a JSON file.\n */\nconst writeJsonFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n): Promise<void> => {\n const content = JSON.stringify(data, null, 2);\n await fs.writeFile(filepath, content, 'utf-8');\n};\n\n/**\n * Write data to a CSV file.\n */\nconst writeCsvFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n): Promise<void> => {\n if (data.length === 0) {\n throw new Error('No data to write to CSV');\n }\n\n const formattedData = data.map(item =>\n Object.fromEntries(Object.entries(item).map(([key, value]) => [key, stringifyForCsv(value)]),\n ));\n\n const csvConfig = mkConfig({ useKeysAsHeaders: true });\n\n const csvOutput = generateCsv(csvConfig)(formattedData);\n const csvString = asString(csvOutput);\n\n await fs.writeFile(filepath, csvString, 'utf-8');\n};\n\n/**\n * Write data to a JSONL file.\n */\nconst writeJsonlFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n): Promise<void> => {\n const lines = data.map((item) => JSON.stringify(item)).join('\\n');\n await fs.writeFile(filepath, lines + '\\n', 'utf-8');\n};\n\n/**\n * Write data to a file based on the file extension.\n */\nexport const writeToFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n format?: 'json' | 'csv' | 'jsonl',\n): Promise<void> => {\n // Create parent directories if they don't exist\n const dir = path.dirname(filepath);\n await fs.mkdir(dir, { recursive: true });\n\n // Determine the format\n const ext = format ?? path.extname(filepath).slice(1);\n\n if (format && format !== path.extname(filepath).slice(1)) {\n logger.warn(\n `Output format ${format} does not match file extension ${path.extname(filepath).slice(1)}`,\n );\n }\n\n if (ext === 'json') {\n await writeJsonFile(filepath, data);\n } else if (ext === 'csv') {\n await writeCsvFile(filepath, data);\n } else if (ext === 'jsonl') {\n await writeJsonlFile(filepath, data);\n } else {\n throw new Error(`Unsupported output format: ${ext}`);\n }\n};\n\n/**\n * Convert a value to a CSV-safe string.\n * - Strings and numbers pass through\n * - null/undefined become empty strings\n * - Objects and arrays are stringified to JSON\n */\nconst stringifyForCsv = (value: any): string => {\n if (value === null || value === undefined) {\n return '';\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n // For objects and arrays, stringify to JSON\n return JSON.stringify(value);\n};\n\n/**\n * Print data to console in the specified format.\n */\nexport const printToConsole = <D, T>(\n data: Datapoint<D, T>[],\n format: 'json' | 'csv' | 'jsonl' = 'json',\n) => {\n if (format === 'json') {\n console.log(JSON.stringify(data, null, 2));\n } else if (format === 'csv') {\n if (data.length === 0) {\n logger.error('No data to print');\n return;\n }\n\n const formattedData = data.map(item =>\n Object.fromEntries(Object.entries(item).map(([key, value]) => [key, stringifyForCsv(value)]),\n ));\n\n const csvConfig = mkConfig({ useKeysAsHeaders: true });\n\n const csvOutput = generateCsv(csvConfig)(formattedData);\n const csvString = asString(csvOutput);\n console.log(csvString);\n } else if (format === 'jsonl') {\n data.forEach((item) => console.log(JSON.stringify(item)));\n } else {\n throw new Error(\n `Unsupported output format: ${String(format)}. `\n + \"(supported formats: json, csv, jsonl)\",\n );\n }\n};\n\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;;;;CAAA,MAAM,EAAE,cAAA,UAAsB,SAAS;CAEvC,MAAM,CAAC,MAAM,OAAO,KAAK,KAAK;CAC9B,MAAM,CAAC,MAAM,OAAO,KAAK,KAAK;CAC9B,MAAM,WAAW;EACf,QAAQ;EACR,SAAS;EACT,aAAa,EAAE,aAAa;EAC5B,YAAY,EAAE,YAAY;EAC1B,SAAS;EACT,OAAO;EACP,KAAK;EACL,WAAW;EACX,cAAc;EACd,WAAW;EACX,aAAa,OAAO;EACpB,QAAQ;EACR,kBAAkB;EACnB;CAED,MAAM,iBAAiB,IAAI,IAAI;EAAC;EAAa;EAAe;EAAY,CAAC;CAEzE,SAAS,eAAe,QAAQ;EAC9B,IAAI,OAAO,WAAW,UACpB,OAAO;EAGT,IAAI,eAAe,IAAI,OAAO,EAC5B,OAAO;EAGT,OAAO;;CAGT,IAAM,YAAN,cAAwB,UAAU;EAChC,YAAa,OAAO,EAAE,EAAE;GACtB,MAAM;IAAE,YAAY;IAAM,eAAe;IAAI,CAAC;GAE9C,IAAI,MAAM,QAAQ,KAAK,EAAE,OAAO,EAAE,SAAS,MAAM;GAEjD,MAAM,UAAU,OAAO,OAAO,EAAE,EAAE,UAAU,KAAK;GAEjD,QAAQ,gBAAgB,QAAQ,YAAY,SAAS;GAErD,KAAK,MAAM,OAAO;IAAC;IAAW;IAAS;IAAY,EACjD,IAAI,OAAO,QAAQ,SAAS,aAC1B,CAAE,QAAQ,QAAQ,OAAO,KAAK,QAAQ,KAAK;GAK/C,QAAQ,UAAU,QAAQ,EAAE,EAAE,SAAS,O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CAAC,yCAE9C"}
|
|
1
|
+
{"version":3,"file":"file-utils-CHgYB_Ei.mjs","names":["asString","generateCsv","mkConfig"],"sources":["../../../node_modules/.pnpm/csv-parser@3.2.1/node_modules/csv-parser/index.js","../../../node_modules/.pnpm/export-to-csv@1.4.0/node_modules/export-to-csv/output/index.js","../src/cli/file-utils.ts"],"sourcesContent":["const { Transform } = require('stream')\n\nconst [cr] = Buffer.from('\\r')\nconst [nl] = Buffer.from('\\n')\nconst defaults = {\n escape: '\"',\n headers: null,\n mapHeaders: ({ header }) => header,\n mapValues: ({ value }) => value,\n newline: '\\n',\n quote: '\"',\n raw: false,\n separator: ',',\n skipComments: false,\n skipLines: null,\n maxRowBytes: Number.MAX_SAFE_INTEGER,\n strict: false,\n outputByteOffset: false\n}\n\nconst DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype'])\n\nfunction sanitizeHeader(header) {\n if (typeof header !== 'string') {\n return null\n }\n\n if (DANGEROUS_KEYS.has(header)) {\n return null\n }\n\n return header\n}\n\nclass CsvParser extends Transform {\n constructor (opts = {}) {\n super({ objectMode: true, highWaterMark: 16 })\n\n if (Array.isArray(opts)) opts = { headers: opts }\n\n const options = Object.assign({}, defaults, opts)\n\n options.customNewline = options.newline !== defaults.newline\n\n for (const key of ['newline', 'quote', 'separator']) {\n if (typeof options[key] !== 'undefined') {\n ([options[key]] = Buffer.from(options[key]))\n }\n }\n\n // if escape is not defined on the passed options, use the end value of quote\n options.escape = (opts || {}).escape ? Buffer.from(options.escape)[0] : options.quote\n\n this.state = {\n empty: options.raw ? Buffer.alloc(0) : '',\n escaped: false,\n first: true,\n lineNumber: 0,\n previousEnd: 0,\n rowLength: 0,\n quoted: false\n }\n\n this._prev = null\n\n if (options.headers === false) {\n // enforce, as the column length check will fail if headers:false\n options.strict = false\n }\n\n if (options.headers || options.headers === false) {\n this.state.first = false\n }\n\n this.options = options\n this.headers = options.headers\n this.bytesRead = 0\n }\n\n parseCell (buffer, start, end) {\n const { escape, quote } = this.options\n // remove quotes from quoted cells\n if (buffer[start] === quote && buffer[end - 1] === quote) {\n start++\n end--\n }\n\n let y = start\n\n for (let i = start; i < end; i++) {\n // check for escape characters and skip them\n if (buffer[i] === escape && i + 1 < end && buffer[i + 1] === quote) {\n i++\n }\n\n if (y !== i) {\n buffer[y] = buffer[i]\n }\n y++\n }\n\n return this.parseValue(buffer, start, y)\n }\n\n parseLine (buffer, start, end) {\n const { customNewline, escape, mapHeaders, mapValues, quote, separator, skipComments, skipLines } = this.options\n\n end-- // trim newline\n if (!customNewline && buffer.length && buffer[end - 1] === cr) {\n end--\n }\n\n const comma = separator\n const cells = []\n let isQuoted = false\n let offset = start\n\n if (skipComments) {\n const char = typeof skipComments === 'string' ? skipComments : '#'\n if (buffer[start] === Buffer.from(char)[0]) {\n return\n }\n }\n\n const mapValue = (value) => {\n if (this.state.first) {\n return value\n }\n\n const index = cells.length\n const header = this.headers[index]\n\n return mapValues({ header, index, value })\n }\n\n for (let i = start; i < end; i++) {\n const isStartingQuote = !isQuoted && buffer[i] === quote\n const isEndingQuote = isQuoted && buffer[i] === quote && i + 1 <= end && buffer[i + 1] === comma\n const isEscape = isQuoted && buffer[i] === escape && i + 1 < end && buffer[i + 1] === quote\n\n if (isStartingQuote || isEndingQuote) {\n isQuoted = !isQuoted\n continue\n } else if (isEscape) {\n i++\n continue\n }\n\n if (buffer[i] === comma && !isQuoted) {\n let value = this.parseCell(buffer, offset, i)\n value = mapValue(value)\n cells.push(value)\n offset = i + 1\n }\n }\n\n if (offset < end) {\n let value = this.parseCell(buffer, offset, end)\n value = mapValue(value)\n cells.push(value)\n }\n\n if (buffer[end - 1] === comma) {\n cells.push(mapValue(this.state.empty))\n }\n\n const skip = skipLines && skipLines > this.state.lineNumber\n this.state.lineNumber++\n\n if (this.state.first && !skip) {\n this.state.first = false\n this.headers = cells.map((header, index) => {\n const mapped = mapHeaders({ header, index })\n\n if (mapped === null) {\n return null\n }\n\n return sanitizeHeader(mapped)\n })\n\n this.emit('headers', this.headers)\n return\n }\n\n if (!skip && this.options.strict && cells.length !== this.headers.length) {\n const e = new RangeError('Row length does not match headers')\n this.emit('error', e)\n } else {\n if (!skip) {\n const byteOffset = this.bytesRead - buffer.length + start\n this.writeRow(cells, byteOffset)\n }\n }\n }\n\n parseValue (buffer, start, end) {\n if (this.options.raw) {\n return buffer.slice(start, end)\n }\n\n return buffer.toString('utf-8', start, end)\n }\n\n writeRow (cells, byteOffset) {\n const headers = (this.headers === false) ? cells.map((value, index) => index) : this.headers\n\n const row = cells.reduce((o, cell, index) => {\n const header = headers[index]\n if (header === null) return o // skip columns\n if (header !== undefined) {\n o[header] = cell\n } else {\n o[`_${index}`] = cell\n }\n return o\n }, {})\n\n if (this.options.outputByteOffset) {\n this.push({ row, byteOffset })\n } else {\n this.push(row)\n }\n }\n\n _flush (cb) {\n if (this.state.escaped || !this._prev) return cb()\n this.parseLine(this._prev, this.state.previousEnd, this._prev.length + 1) // plus since online -1s\n cb()\n }\n\n _transform (data, enc, cb) {\n if (typeof data === 'string') {\n data = Buffer.from(data)\n }\n\n const { escape, quote } = this.options\n let start = 0\n let buffer = data\n this.bytesRead += data.byteLength\n\n if (this._prev) {\n start = this._prev.length\n buffer = Buffer.concat([this._prev, data])\n this._prev = null\n }\n\n const bufferLength = buffer.length\n\n for (let i = start; i < bufferLength; i++) {\n const chr = buffer[i]\n const nextChr = i + 1 < bufferLength ? buffer[i + 1] : null\n\n this.state.rowLength++\n if (this.state.rowLength > this.options.maxRowBytes) {\n return cb(new Error('Row exceeds the maximum size'))\n }\n\n if (!this.state.escaped && chr === escape && nextChr === quote && i !== start) {\n this.state.escaped = true\n continue\n } else if (chr === quote) {\n if (this.state.escaped) {\n this.state.escaped = false\n // non-escaped quote (quoting the cell)\n } else {\n this.state.quoted = !this.state.quoted\n }\n continue\n }\n\n if (!this.state.quoted) {\n if (this.state.first && !this.options.customNewline) {\n if (chr === nl) {\n this.options.newline = nl\n } else if (chr === cr) {\n if (nextChr !== nl) {\n this.options.newline = cr\n }\n }\n }\n\n if (chr === this.options.newline) {\n this.parseLine(buffer, this.state.previousEnd, i + 1)\n this.state.previousEnd = i + 1\n this.state.rowLength = 0\n }\n }\n }\n\n if (this.state.previousEnd === bufferLength) {\n this.state.previousEnd = 0\n return cb()\n }\n\n if (bufferLength - this.state.previousEnd < data.length) {\n this._prev = data\n this.state.previousEnd -= (bufferLength - data.length)\n return cb()\n }\n\n this._prev = buffer\n cb()\n }\n}\n\nmodule.exports = (opts) => new CsvParser(opts)\n","var q;(function(x){x[\"csv\"]=\"text/csv\";x[\"tsv\"]=\"text/tab-separated-values\";x[\"plain\"]=\"text/plain\"})(q||(q={}));var X=(W)=>W,z=(W)=>W,Z=X,_=X,Y=X,N=X,V=X;var h={fieldSeparator:\",\",decimalSeparator:\".\",quoteStrings:!0,quoteCharacter:'\"',showTitle:!1,title:\"My Generated Report\",filename:\"generated\",showColumnHeaders:!0,useTextFile:!1,fileExtension:\"csv\",mediaType:q.csv,useBom:!0,columnHeaders:[],useKeysAsHeaders:!1,boolDisplay:{true:\"TRUE\",false:\"FALSE\"},replaceUndefinedWith:\"\"},F=\"\\r\\n\",R=\"\\uFEFF\",G=(W)=>Object.assign({},h,W);class K extends Error{constructor(W){super(W);this.name=\"CsvGenerationError\"}}class B extends Error{constructor(W){super(W);this.name=\"EmptyHeadersError\"}}class L extends Error{constructor(W){super(W);this.name=\"CsvDownloadEnvironmentError\"}}class P extends Error{constructor(W){super(W);this.name=\"UnsupportedDataFormatError\"}}var s=function(W,$){if($=='\"'&&W.indexOf('\"')>-1)return W.replace(/\"/g,'\"\"');return W},w=(W)=>typeof W===\"object\"?N(W.key):N(W),y=(W)=>typeof W===\"object\"?V(W.displayLabel):V(W),T=(W,...$)=>$.reduce((j,x)=>x(j),W),E=(W)=>($)=>W.useBom?_(z($)+R):$,M=(W)=>($)=>W.showTitle?S(_(z($)+W.title))(Y(\"\")):$,S=(W)=>($)=>_(z(W)+z($)+F),O=(W)=>($,j)=>l(W)(Y(z($)+z(j))),l=(W)=>($)=>X(z($)+W.fieldSeparator),b=(W,$)=>(j)=>{if(!W.showColumnHeaders)return j;if($.length<1)throw new B(\"Option to show headers but none supplied. Make sure there are keys in your collection or that you've supplied headers through the config options.\");let x=Y(\"\");for(let A=0;A<$.length;A++){const J=y($[A]);x=O(W)(x,v(W,z(J)))}return x=Y(z(x).slice(0,-1)),S(j)(x)},C=(W,$,j)=>(x)=>{let A=x;for(var J=0;J<j.length;J++){let I=Y(\"\");for(let U=0;U<$.length;U++){const H=w($[U]),D=j[J][z(H)];I=O(W)(I,v(W,D))}I=Y(z(I).slice(0,-1)),A=S(A)(I)}return A},k=z,m=(W)=>+W===W&&(!isFinite(W)||Boolean(W%1)),p=(W,$)=>{if(m($)){if(W.decimalSeparator===\"locale\")return Z($.toLocaleString());if(W.decimalSeparator)return Z($.toString().replace(\".\",W.decimalSeparator))}return Z($.toString())},Q=(W,$)=>{let j=$;if(W.quoteStrings||W.fieldSeparator&&$.indexOf(W.fieldSeparator)>-1||W.quoteCharacter&&$.indexOf(W.quoteCharacter)>-1||$.indexOf(\"\\n\")>-1||$.indexOf(\"\\r\")>-1)j=W.quoteCharacter+s($,W.quoteCharacter)+W.quoteCharacter;return Z(j)},g=(W,$)=>{const j=$?\"true\":\"false\";return Z(W.boolDisplay[j])},r=(W,$)=>{if(typeof $===\"undefined\"&&W.replaceUndefinedWith!==void 0)return Q(W,W.replaceUndefinedWith+\"\");if($===null)return Q(W,\"null\");return Q(W,\"\")},v=(W,$)=>{if(typeof $===\"number\")return p(W,$);if(typeof $===\"string\")return Q(W,$);if(typeof $===\"boolean\"&&W.boolDisplay)return g(W,$);if($===null||typeof $===\"undefined\")return r(W,$);throw new P(`\n typeof ${typeof $} isn't supported. Only number, string, boolean, null and undefined are supported.\n Please convert the data in your object to one of those before generating the CSV.\n `)};var BW=(W)=>($)=>{const j=G(W),x=j.useKeysAsHeaders?Object.keys($[0]):j.columnHeaders;let A=T(_(\"\"),E(j),M(j),b(j,x),C(j,x,$));if(z(A).length<1)throw new K(\"Output is empty. Is your data formatted correctly?\");return A},f=(W)=>($)=>{const j=G(W),x=z($),A=j.useTextFile?\"text/plain\":j.mediaType;return new Blob([x],{type:`${A};charset=utf8;`})},LW=(W)=>($)=>{if(!window)throw new L(\"Downloading only supported in a browser environment.\");const j=f(W)($),x=G(W),A=x.useTextFile?\"txt\":x.fileExtension,J=`${x.filename}.${A}`,I=document.createElement(\"a\");I.download=J,I.href=URL.createObjectURL(j),I.setAttribute(\"visibility\",\"hidden\"),document.body.appendChild(I),I.click(),document.body.removeChild(I)};export{G as mkConfig,BW as generateCsv,LW as download,k as asString,f as asBlob,q as MediaType};\n","import { errorMessage } from '@lmnr-ai/types';\nimport csv from 'csv-parser';\nimport { asString, generateCsv, mkConfig } from 'export-to-csv';\nimport { createReadStream } from 'fs';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\n\nimport { Datapoint } from '../evaluations';\nimport { initializeLogger } from '../utils';\n\nconst logger = initializeLogger();\n\n/**\n * Check if a file has a supported extension.\n */\nconst isSupportedFile = (file: string): boolean => {\n const ext = path.extname(file).toLowerCase();\n return ['.json', '.csv', '.jsonl'].includes(ext);\n};\n\n/**\n * Collect all supported files from the given paths.\n * Handles both files and directories.\n */\nexport const collectFiles = async (\n paths: string[],\n recursive: boolean = false,\n): Promise<string[]> => {\n const collectedFiles: string[] = [];\n\n for (const filepath of paths) {\n try {\n const stats = await fs.stat(filepath);\n\n if (stats.isFile()) {\n if (isSupportedFile(filepath)) {\n collectedFiles.push(filepath);\n } else {\n logger.warn(`Skipping unsupported file type: ${filepath}`);\n }\n } else if (stats.isDirectory()) {\n const entries = await fs.readdir(filepath);\n\n for (const entry of entries) {\n const fullPath = path.join(filepath, entry);\n const entryStats = await fs.stat(fullPath);\n\n if (entryStats.isFile() && isSupportedFile(fullPath)) {\n collectedFiles.push(fullPath);\n } else if (recursive && entryStats.isDirectory()) {\n const subFiles = await collectFiles([fullPath], true);\n collectedFiles.push(...subFiles);\n }\n }\n }\n } catch (error) {\n logger.warn(\n `Path does not exist or is not accessible: ${filepath}. `\n + `Error: ${errorMessage(error)}`,\n );\n }\n }\n\n return collectedFiles;\n};\n\n/**\n * Read a JSON file and return its contents.\n */\nconst readJsonFile = async (filepath: string): Promise<any[]> => {\n const content = await fs.readFile(filepath, 'utf-8');\n const parsed = JSON.parse(content);\n return Array.isArray(parsed) ? parsed : [parsed];\n};\n\n/**\n * Try to parse a string as JSON. If it fails, return the original string.\n */\nconst tryParseJson = (content: string): any => {\n // Don't try to parse if it's not a string or doesn't look like JSON\n if (typeof content !== 'string') {\n return content;\n }\n\n // If it doesn't start with { or [, it's probably not JSON\n const trimmed = content.trim();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {\n return content;\n }\n\n try {\n return JSON.parse(content);\n } catch (error) {\n logger.debug(\n `Error parsing JSON: ${errorMessage(error)}`,\n );\n return content;\n }\n};\n\n/**\n * Parse each field in a CSV row, attempting to convert JSON strings back to objects.\n */\nconst parseCsvRow = (row: Record<string, string>): any => {\n const parsed: any = {};\n for (const [key, value] of Object.entries(row)) {\n parsed[key] = tryParseJson(value);\n }\n return parsed;\n};\n\n/**\n * Read a CSV file and return its contents as an array of objects.\n */\nconst readCsvFile = async (filepath: string): Promise<any[]> => new Promise((resolve, reject) => {\n const results: any[] = [];\n createReadStream(filepath)\n .pipe(csv())\n .on('data', (data) => results.push(parseCsvRow(data)))\n .on('end', () => resolve(results))\n .on('error', reject);\n});\n\n/**\n * Read a JSONL file and return its contents as an array of objects.\n */\nasync function readJsonlFile(filepath: string): Promise<any[]> {\n const content = await fs.readFile(filepath, 'utf-8');\n const lines = content.split('\\n').filter((line) => line.trim());\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return lines.map((line) => JSON.parse(line));\n}\n\n/**\n * Read a single file and return its contents.\n */\nasync function readFile(filepath: string): Promise<any[]> {\n const ext = path.extname(filepath).toLowerCase();\n\n if (ext === '.json') {\n return readJsonFile(filepath);\n } else if (ext === '.csv') {\n return readCsvFile(filepath);\n } else if (ext === '.jsonl') {\n return readJsonlFile(filepath);\n } else {\n throw new Error(`Unsupported file type: ${ext}`);\n }\n}\n\n/**\n * Load data from all files in the specified paths.\n */\nexport const loadFromPaths = async <D = any, T = any>(\n paths: string[],\n recursive: boolean = false,\n): Promise<Datapoint<D, T>[]> => {\n const files = await collectFiles(paths, recursive);\n\n if (files.length === 0) {\n logger.warn('No supported files found in the specified paths');\n return [];\n }\n\n logger.info(`Found ${files.length} file(s) to read`);\n\n const result: Datapoint<D, T>[] = [];\n\n for (const file of files) {\n try {\n const data = await readFile(file);\n result.push(...data);\n logger.info(`Read ${data.length} record(s) from ${file}`);\n } catch (error) {\n logger.error(\n `Error reading file ${file}: ${errorMessage(error)}`,\n );\n throw error;\n }\n }\n\n return result;\n};\n\n/**\n * Write data to a JSON file.\n */\nconst writeJsonFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n): Promise<void> => {\n const content = JSON.stringify(data, null, 2);\n await fs.writeFile(filepath, content, 'utf-8');\n};\n\n/**\n * Write data to a CSV file.\n */\nconst writeCsvFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n): Promise<void> => {\n if (data.length === 0) {\n throw new Error('No data to write to CSV');\n }\n\n const formattedData = data.map(item =>\n Object.fromEntries(Object.entries(item).map(([key, value]) => [key, stringifyForCsv(value)]),\n ));\n\n const csvConfig = mkConfig({ useKeysAsHeaders: true });\n\n const csvOutput = generateCsv(csvConfig)(formattedData);\n const csvString = asString(csvOutput);\n\n await fs.writeFile(filepath, csvString, 'utf-8');\n};\n\n/**\n * Write data to a JSONL file.\n */\nconst writeJsonlFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n): Promise<void> => {\n const lines = data.map((item) => JSON.stringify(item)).join('\\n');\n await fs.writeFile(filepath, lines + '\\n', 'utf-8');\n};\n\n/**\n * Write data to a file based on the file extension.\n */\nexport const writeToFile = async <D, T>(\n filepath: string,\n data: Datapoint<D, T>[],\n format?: 'json' | 'csv' | 'jsonl',\n): Promise<void> => {\n // Create parent directories if they don't exist\n const dir = path.dirname(filepath);\n await fs.mkdir(dir, { recursive: true });\n\n // Determine the format\n const ext = format ?? path.extname(filepath).slice(1);\n\n if (format && format !== path.extname(filepath).slice(1)) {\n logger.warn(\n `Output format ${format} does not match file extension ${path.extname(filepath).slice(1)}`,\n );\n }\n\n if (ext === 'json') {\n await writeJsonFile(filepath, data);\n } else if (ext === 'csv') {\n await writeCsvFile(filepath, data);\n } else if (ext === 'jsonl') {\n await writeJsonlFile(filepath, data);\n } else {\n throw new Error(`Unsupported output format: ${ext}`);\n }\n};\n\n/**\n * Convert a value to a CSV-safe string.\n * - Strings and numbers pass through\n * - null/undefined become empty strings\n * - Objects and arrays are stringified to JSON\n */\nconst stringifyForCsv = (value: any): string => {\n if (value === null || value === undefined) {\n return '';\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n // For objects and arrays, stringify to JSON\n return JSON.stringify(value);\n};\n\n/**\n * Print data to console in the specified format.\n */\nexport const printToConsole = <D, T>(\n data: Datapoint<D, T>[],\n format: 'json' | 'csv' | 'jsonl' = 'json',\n) => {\n if (format === 'json') {\n console.log(JSON.stringify(data, null, 2));\n } else if (format === 'csv') {\n if (data.length === 0) {\n logger.error('No data to print');\n return;\n }\n\n const formattedData = data.map(item =>\n Object.fromEntries(Object.entries(item).map(([key, value]) => [key, stringifyForCsv(value)]),\n ));\n\n const csvConfig = mkConfig({ useKeysAsHeaders: true });\n\n const csvOutput = generateCsv(csvConfig)(formattedData);\n const csvString = asString(csvOutput);\n console.log(csvString);\n } else if (format === 'jsonl') {\n data.forEach((item) => console.log(JSON.stringify(item)));\n } else {\n throw new Error(\n `Unsupported output format: ${String(format)}. `\n + \"(supported formats: json, csv, jsonl)\",\n );\n }\n};\n\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;;;;CAAA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