@sentry/server-utils 11.15.0 → 11.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/chunks/config.js +60 -0
- package/build/cjs/chunks/config.js.map +1 -1
- package/build/cjs/chunks/exports.js +194 -58
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/chunks/moduleInjectedTransform.js +8 -0
- package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
- package/build/cjs/index.js +299 -168
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/index.request-handler.js +1 -0
- package/build/cjs/index.request-handler.js.map +1 -1
- package/build/esm/ai/flue/utils.js +1 -0
- package/build/esm/ai/flue/utils.js.map +1 -1
- package/build/esm/ai/google-genai/decisions.js +29 -1
- package/build/esm/ai/google-genai/decisions.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +23 -8
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +41 -30
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +6 -2
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +5 -1
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +4 -1
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/openai/mapping.js +48 -1
- package/build/esm/ai/openai/mapping.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +10 -13
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js +6 -5
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +21 -17
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/index.js +3 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/clickhouse-sql.js +31 -0
- package/build/esm/integrations/clickhouse-sql.js.map +1 -0
- package/build/esm/integrations/clickhouse.js +88 -0
- package/build/esm/integrations/clickhouse.js.map +1 -0
- package/build/esm/integrations/express/instrumentation.js +1 -0
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/fastify/instrumentation.js +3 -1
- package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
- package/build/esm/integrations/hapi/index.js +15 -1
- package/build/esm/integrations/hapi/index.js.map +1 -1
- package/build/esm/integrations/index.js +2 -0
- package/build/esm/integrations/index.js.map +1 -1
- package/build/esm/integrations/langchain.js +10 -3
- package/build/esm/integrations/langchain.js.map +1 -1
- package/build/esm/orchestrion/channels.js +2 -0
- package/build/esm/orchestrion/channels.js.map +1 -1
- package/build/esm/orchestrion/config/channel-integration-definitions.js +8 -0
- package/build/esm/orchestrion/config/channel-integration-definitions.js.map +1 -1
- package/build/esm/orchestrion/config/clickhouse.js +51 -0
- package/build/esm/orchestrion/config/clickhouse.js.map +1 -0
- package/build/esm/orchestrion/config/index.js +2 -0
- package/build/esm/orchestrion/config/index.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/utils/sql.js +37 -16
- package/build/esm/utils/sql.js.map +1 -1
- package/build/esm/utils/wrapServerRequestHandler.js +2 -1
- package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
- package/build/types/ai/flue/utils.d.ts.map +1 -1
- package/build/types/ai/google-genai/decisions.d.ts.map +1 -1
- package/build/types/ai/langchain/embeddings.d.ts +2 -2
- package/build/types/ai/langchain/embeddings.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/langchain/types.d.ts +8 -4
- package/build/types/ai/langchain/types.d.ts.map +1 -1
- package/build/types/ai/langgraph/agent-span.d.ts +5 -2
- package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
- package/build/types/ai/langgraph/index.d.ts.map +1 -1
- package/build/types/ai/langgraph/stream.d.ts.map +1 -1
- package/build/types/ai/langgraph/types.d.ts +10 -2
- package/build/types/ai/langgraph/types.d.ts.map +1 -1
- package/build/types/ai/openai/mapping.d.ts.map +1 -1
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/runs.d.ts +4 -2
- package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
- package/build/types/ai/pi-durable/tools.d.ts +4 -6
- package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +10 -1
- package/build/types/ai/pi-durable/types.d.ts.map +1 -1
- package/build/types/ai/types.d.ts +1 -1
- package/build/types/ai/types.d.ts.map +1 -1
- package/build/types/index.d.ts +2 -1
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/clickhouse-sql.d.ts +8 -0
- package/build/types/integrations/clickhouse-sql.d.ts.map +1 -0
- package/build/types/integrations/clickhouse.d.ts +11 -0
- package/build/types/integrations/clickhouse.d.ts.map +1 -0
- package/build/types/integrations/express/types.d.ts +1 -0
- package/build/types/integrations/express/types.d.ts.map +1 -1
- package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/hapi/index.d.ts +12 -0
- package/build/types/integrations/hapi/index.d.ts.map +1 -1
- package/build/types/integrations/index.d.ts.map +1 -1
- package/build/types/integrations/langchain.d.ts.map +1 -1
- package/build/types/orchestrion/channels.d.ts +12 -0
- package/build/types/orchestrion/channels.d.ts.map +1 -1
- package/build/types/orchestrion/config/channel-integration-definitions.d.ts +3 -0
- package/build/types/orchestrion/config/channel-integration-definitions.d.ts.map +1 -1
- package/build/types/orchestrion/config/clickhouse.d.ts +18 -0
- package/build/types/orchestrion/config/clickhouse.d.ts.map +1 -0
- package/build/types/orchestrion/config/index.d.ts.map +1 -1
- package/build/types/utils/sql.d.ts +28 -3
- package/build/types/utils/sql.d.ts.map +1 -1
- package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
- package/package.json +4 -4
package/build/esm/utils/sql.js
CHANGED
|
@@ -5,7 +5,7 @@ const MAX_SUMMARY_LENGTH = 255;
|
|
|
5
5
|
const IDENTIFIER = "(?:\"[^\"]*\"|'[^']*'|`[^`]*`|[^\\s(,;).'\"`]+)";
|
|
6
6
|
const TABLE_NAME = `${IDENTIFIER}(?:\\.${IDENTIFIER})*`;
|
|
7
7
|
const DDL_RE = new RegExp(`^\\s*(?<operation>(?:CREATE|DROP)\\s+(?:TABLE|INDEX)|ALTER\\s+TABLE)(?:\\s+IF\\s+(?:NOT\\s+)?EXISTS)?\\s+(?<table>${TABLE_NAME})`, "i");
|
|
8
|
-
const INSERT_RE = new RegExp(`^\\s*(?<operation>INSERT|REPLACE)(?:\\s+OR\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\s+INTO
|
|
8
|
+
const INSERT_RE = new RegExp(`^\\s*(?<operation>INSERT|REPLACE)(?:\\s+OR\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\s+INTO(?:\\s+TABLE)?\\s+(?<table>${TABLE_NAME})`, "i");
|
|
9
9
|
const UPDATE_RE = new RegExp(`^\\s*(?<operation>UPDATE)(?:\\s+OR\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\s+(?<table>${TABLE_NAME})`, "i");
|
|
10
10
|
const DELETE_RE = new RegExp(`^\\s*(?<operation>DELETE)\\s+FROM\\s+(?<table>${TABLE_NAME})`, "i");
|
|
11
11
|
const SELECT_RE = /^\s*(?:\(\s*)?(?<operation>SELECT)\b/i;
|
|
@@ -148,6 +148,7 @@ function toSqlDialect(system) {
|
|
|
148
148
|
if (system === "mssql" || system === "sqlserver" || system === "microsoft.sql_server") return "mssql";
|
|
149
149
|
return "standard";
|
|
150
150
|
}
|
|
151
|
+
const NO_RULES = {};
|
|
151
152
|
const DOLLAR_QUOTE_RE = /\$(?:[A-Za-z_]\w*)?\$/y;
|
|
152
153
|
/**
|
|
153
154
|
* Returns the index just past the run's closing `delimiter`, or -1 if the run never closes. The
|
|
@@ -168,6 +169,18 @@ function findQuotedRunEnd(sql, start, delimiter, backslashEscapes) {
|
|
|
168
169
|
}
|
|
169
170
|
return -1;
|
|
170
171
|
}
|
|
172
|
+
function findBlockCommentEnd(sql, start, nested) {
|
|
173
|
+
let depth = 1;
|
|
174
|
+
let i = start + 2;
|
|
175
|
+
while (i < sql.length && depth > 0) if (sql[i] === "*" && sql[i + 1] === "/") {
|
|
176
|
+
depth--;
|
|
177
|
+
i += 2;
|
|
178
|
+
} else if (nested && sql[i] === "/" && sql[i + 1] === "*") {
|
|
179
|
+
depth++;
|
|
180
|
+
i += 2;
|
|
181
|
+
} else i++;
|
|
182
|
+
return i;
|
|
183
|
+
}
|
|
171
184
|
/**
|
|
172
185
|
* Replaces every string literal with `?` and drops every comment, in one pass.
|
|
173
186
|
*
|
|
@@ -180,24 +193,25 @@ function findQuotedRunEnd(sql, start, delimiter, backslashEscapes) {
|
|
|
180
193
|
* built from.
|
|
181
194
|
*/
|
|
182
195
|
function stripLiteralsAndComments(sql, dialect) {
|
|
183
|
-
const
|
|
196
|
+
const [base, rules] = typeof dialect === "string" ? [dialect, NO_RULES] : ["standard", dialect];
|
|
197
|
+
const isMysql = base === "mysql";
|
|
198
|
+
const backslashEscapes = !!rules.backslashEscapes;
|
|
184
199
|
const out = [];
|
|
185
200
|
let i = 0;
|
|
186
201
|
while (i < sql.length) {
|
|
187
202
|
const char = sql[i];
|
|
188
203
|
const next = sql[i + 1];
|
|
189
|
-
if (char === "-" && next === "-" || isMysql && char === "#") {
|
|
204
|
+
if (char === "-" && next === "-" || (isMysql || rules.hashComments) && char === "#") {
|
|
190
205
|
const lineEnd = sql.indexOf("\n", i);
|
|
191
206
|
i = lineEnd === -1 ? sql.length : lineEnd;
|
|
192
207
|
continue;
|
|
193
208
|
}
|
|
194
209
|
if (char === "/" && next === "*") {
|
|
195
|
-
|
|
196
|
-
i = commentEnd === -1 ? sql.length : commentEnd + 2;
|
|
210
|
+
i = findBlockCommentEnd(sql, i, !!rules.nestedComments);
|
|
197
211
|
continue;
|
|
198
212
|
}
|
|
199
|
-
if (
|
|
200
|
-
const tag = matchDollarQuoteTag(sql, i);
|
|
213
|
+
if (base === "standard" && char === "$" && !isIdentifierChar(sql[i - 1])) {
|
|
214
|
+
const tag = matchDollarQuoteTag(sql, i, rules.dollarQuote);
|
|
201
215
|
if (tag) {
|
|
202
216
|
const bodyEnd = sql.indexOf(tag, i + tag.length);
|
|
203
217
|
i = bodyEnd === -1 ? sql.length : bodyEnd + tag.length;
|
|
@@ -205,21 +219,28 @@ function stripLiteralsAndComments(sql, dialect) {
|
|
|
205
219
|
continue;
|
|
206
220
|
}
|
|
207
221
|
}
|
|
208
|
-
const identifierCloser = getIdentifierCloser(char,
|
|
222
|
+
const identifierCloser = getIdentifierCloser(char, base);
|
|
209
223
|
if (identifierCloser) {
|
|
210
|
-
const runEnd = findQuotedRunEnd(sql, i, identifierCloser,
|
|
224
|
+
const runEnd = findQuotedRunEnd(sql, i, identifierCloser, backslashEscapes);
|
|
211
225
|
out.push(runEnd === -1 ? "?" : sql.slice(i, runEnd));
|
|
212
226
|
i = runEnd === -1 ? sql.length : runEnd;
|
|
213
227
|
continue;
|
|
214
228
|
}
|
|
215
229
|
if (char === "'" || char === "\"" && isMysql) {
|
|
216
|
-
const prefix = char === "'" ? getLiteralPrefix(out,
|
|
230
|
+
const prefix = char === "'" ? getLiteralPrefix(out, base) : void 0;
|
|
217
231
|
if (prefix) out.pop();
|
|
218
|
-
const runEnd = findQuotedRunEnd(sql, i, char, isMysql || prefix === "E");
|
|
232
|
+
const runEnd = findQuotedRunEnd(sql, i, char, isMysql || backslashEscapes || prefix === "E");
|
|
219
233
|
i = runEnd === -1 ? sql.length : runEnd;
|
|
220
234
|
out.push("?");
|
|
221
235
|
continue;
|
|
222
236
|
}
|
|
237
|
+
const literalLength = rules.matchLiteral?.(sql, i);
|
|
238
|
+
if (literalLength) {
|
|
239
|
+
out.push("?");
|
|
240
|
+
i += literalLength;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
if (rules.isInlineData?.(sql, i, out)) break;
|
|
223
244
|
out.push(char);
|
|
224
245
|
i++;
|
|
225
246
|
}
|
|
@@ -240,9 +261,9 @@ function isIdentifierChar(char) {
|
|
|
240
261
|
return char !== void 0 && /[\w$]/.test(char);
|
|
241
262
|
}
|
|
242
263
|
/** Returns the opening dollar-quote tag at `start` (`$$` or `$tag$`), or undefined if there is none. */
|
|
243
|
-
function matchDollarQuoteTag(sql, start) {
|
|
244
|
-
|
|
245
|
-
return
|
|
264
|
+
function matchDollarQuoteTag(sql, start, pattern = DOLLAR_QUOTE_RE) {
|
|
265
|
+
pattern.lastIndex = start;
|
|
266
|
+
return pattern.exec(sql)?.[0];
|
|
246
267
|
}
|
|
247
268
|
/**
|
|
248
269
|
* Returns the literal-prefix character immediately before a `'`, if there is one: `X`/`B` for
|
|
@@ -265,7 +286,7 @@ function getLiteralPrefix(out, dialect) {
|
|
|
265
286
|
* booleans) are sanitized.
|
|
266
287
|
*
|
|
267
288
|
* Pass `dialect` when the statement comes from a driver whose literals are not standard-quoted;
|
|
268
|
-
* see {@link SqlDialect}.
|
|
289
|
+
* see {@link SqlDialect} and {@link SqlLexerRules}.
|
|
269
290
|
*/
|
|
270
291
|
function sanitizeSqlQuery(sqlQuery, dialect = "standard") {
|
|
271
292
|
if (!sqlQuery) return "Unknown SQL Query";
|
|
@@ -307,6 +328,6 @@ function getSqlSpanName(attributes, fallback) {
|
|
|
307
328
|
function toSpanName(value, fallback) {
|
|
308
329
|
return typeof value === "string" && value ? value : fallback;
|
|
309
330
|
}
|
|
310
|
-
export { getLowCardinalitySqlSpanName, getSqlOperationName, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, sanitizeSqlQuery, toSqlDialect };
|
|
331
|
+
export { getLowCardinalitySqlSpanName, getSqlOperationName, getSqlQueryAttributes, getSqlQuerySummary, getSqlSpanName, isIdentifierChar, sanitizeSqlQuery, toSqlDialect };
|
|
311
332
|
|
|
312
333
|
//# sourceMappingURL=sql.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sql.js","names":[],"sources":["../../../src/utils/sql.ts"],"sourcesContent":["import {\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n} from '@sentry/conventions/attributes';\nimport type { SpanAttributes } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled } from '@sentry/core';\n\nconst MAX_SUMMARY_LENGTH = 255;\n\n// A single identifier: quoted (`\"...\"`, `'...'`, or MySQL backticks) or bare. The quoted forms have\n// to be matched as a unit, otherwise an identifier containing a space or a dot is cut in half.\nconst IDENTIFIER = '(?:\"[^\"]*\"|\\'[^\\']*\\'|`[^`]*`|[^\\\\s(,;).\\'\"`]+)';\n\n// A table reference can be schema-qualified (`\"public\".\"User\"`, `db.schema.table`), with each part\n// quoted independently. The whole qualified name is the summary target, since the schema is what\n// distinguishes two same-named tables.\nconst TABLE_NAME = `${IDENTIFIER}(?:\\\\.${IDENTIFIER})*`;\n\nconst DDL_RE = new RegExp(\n `^\\\\s*(?<operation>(?:CREATE|DROP)\\\\s+(?:TABLE|INDEX)|ALTER\\\\s+TABLE)(?:\\\\s+IF\\\\s+(?:NOT\\\\s+)?EXISTS)?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\n\n// SQLite upserts insert an optional conflict clause between operation and INTO\n// (`INSERT OR REPLACE INTO`, https://sqlite.org/lang_insert.html), with `REPLACE INTO` as the\n// standalone shorthand. The clause is filler like INTO — stripping it keeps upserts on the same\n// low-cardinality summary as plain inserts.\nconst INSERT_RE = new RegExp(\n `^\\\\s*(?<operation>INSERT|REPLACE)(?:\\\\s+OR\\\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\\\s+INTO\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\nconst UPDATE_RE = new RegExp(\n `^\\\\s*(?<operation>UPDATE)(?:\\\\s+OR\\\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\nconst DELETE_RE = new RegExp(`^\\\\s*(?<operation>DELETE)\\\\s+FROM\\\\s+(?<table>${TABLE_NAME})`, 'i');\n\nconst SELECT_RE = /^\\s*(?:\\(\\s*)?(?<operation>SELECT)\\b/i;\n\nconst PRAGMA_RE = /^\\s*(?<operation>PRAGMA)\\s+(?<command>\\S+)/i;\n\nconst TOKEN_RE = /\\b(?:FROM|JOIN)\\s+|\\(\\s*(SELECT)\\b|\\b(?:UNION|INTERSECT|EXCEPT|MINUS)\\s+(?:ALL\\s+)?(SELECT)\\b/gi;\nconst TABLE_REF_RE = new RegExp(`^${TABLE_NAME}`);\nconst COMMA_TABLE_RE = new RegExp(`^\\\\s*,\\\\s*(${TABLE_NAME})`);\nconst SUBQUERY_SELECT_RE = /^\\(\\s*(SELECT)\\b/i;\n\n/**\n * Derives a low-cardinality summary from a SQL query for use as `db.query.summary`.\n *\n * Conforms to the OTEL semantic convention for generating query summaries:\n * - Preserves original case of operations and identifiers (no normalization)\n * - Uses format: `{operation} {target1} {target2} ...`\n * - Strips filler words (INTO, FROM) from the operation\n * - Captures multiple table targets (JOINs)\n * - Handles INSERT...SELECT with both targets\n * - Truncates to 255 characters without splitting mid-value\n *\n * @see https://opentelemetry.io/docs/specs/semconv/database/database-spans/#generating-a-summary-of-the-query\n */\nexport function getSqlQuerySummary(query: string | undefined): string | undefined {\n if (!query) {\n return undefined;\n }\n\n const pragmaMatch = PRAGMA_RE.exec(query);\n if (pragmaMatch?.groups?.['operation'] && pragmaMatch.groups['command']) {\n const operation = pragmaMatch.groups['operation'];\n const command = pragmaMatch.groups['command'];\n const parenIdx = command.indexOf('(');\n return truncate(`${operation} ${parenIdx >= 0 ? command.substring(0, parenIdx) : command}`);\n }\n\n const ddlMatch = DDL_RE.exec(query);\n if (ddlMatch?.groups?.['operation'] && ddlMatch.groups['table']) {\n return truncate(`${ddlMatch.groups['operation']} ${ddlMatch.groups['table']}`);\n }\n\n const insertMatch = INSERT_RE.exec(query);\n if (insertMatch?.groups?.['operation'] && insertMatch.groups['table']) {\n const parts = [insertMatch.groups['operation'], insertMatch.groups['table']];\n const rest = query.slice(insertMatch[0].length);\n const subSelect = /\\b(SELECT)\\b/i.exec(rest);\n if (subSelect?.[1]) {\n parts.push(subSelect[1]);\n const selectTables = extractTableNames(rest.slice(subSelect.index));\n parts.push(...selectTables);\n }\n return truncate(parts.join(' '));\n }\n\n const updateMatch = UPDATE_RE.exec(query);\n if (updateMatch?.groups?.['operation'] && updateMatch.groups['table']) {\n return truncate(`${updateMatch.groups['operation']} ${updateMatch.groups['table']}`);\n }\n\n const deleteMatch = DELETE_RE.exec(query);\n if (deleteMatch?.groups?.['operation'] && deleteMatch.groups['table']) {\n return truncate(`${deleteMatch.groups['operation']} ${deleteMatch.groups['table']}`);\n }\n\n const selectMatch = SELECT_RE.exec(query);\n if (selectMatch?.groups?.['operation']) {\n const tables = extractTableNames(query.slice(selectMatch[0].length));\n if (tables.length > 0) {\n return truncate(`${selectMatch.groups['operation']} ${tables.join(' ')}`);\n }\n return selectMatch.groups['operation'];\n }\n\n return truncate(query.trim().split(/\\s+/)[0] ?? query);\n}\n\nconst LEADING_KEYWORD_RE = /^\\s*(?:\\(\\s*)*([A-Za-z]+)\\b/;\nconst CTE_MAIN_STATEMENT_RE = /\\(|\\)|\\b(SELECT|INSERT|UPDATE|DELETE|MERGE|VALUES|TABLE)\\b/gi;\n\n/**\n * Derives `db.operation.name` from a SQL query: the first operation keyword, in its original case.\n *\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/db/#db-operation-name\n */\nexport function getSqlOperationName(query: string | undefined): string | undefined {\n const match = query ? LEADING_KEYWORD_RE.exec(query) : null;\n const keyword = match?.[1];\n if (!query || !match || !keyword) {\n return undefined;\n }\n // Scanned from after `WITH`, so parentheses wrapping the whole query don't shift the depth.\n return keyword.toUpperCase() === 'WITH' ? getCteMainOperationName(query.slice(match[0].length)) : keyword;\n}\n\n/**\n * The operation of a `WITH` query is its main statement: the first operation keyword outside the\n * CTE bodies, which are all parenthesized. Counting parentheses is safe on a sanitized query, which\n * has no literals or comments left.\n */\nfunction getCteMainOperationName(query: string): string | undefined {\n let depth = 0;\n for (const match of query.matchAll(CTE_MAIN_STATEMENT_RE)) {\n if (match[0] === '(') {\n depth++;\n } else if (match[0] === ')') {\n depth--;\n } else if (depth === 0) {\n return match[1];\n }\n }\n return undefined;\n}\n\nfunction extractTableNames(sql: string): string[] {\n const tables: string[] = [];\n TOKEN_RE.lastIndex = 0;\n let match: RegExpExecArray | null;\n\n while ((match = TOKEN_RE.exec(sql)) !== null) {\n if (match[1] || match[2]) {\n tables.push((match[1] || match[2])!);\n continue;\n }\n\n const rest = sql.slice(match.index + match[0].length);\n\n const subqueryMatch = SUBQUERY_SELECT_RE.exec(rest);\n if (subqueryMatch?.[1]) {\n tables.push(subqueryMatch[1]);\n TOKEN_RE.lastIndex = match.index + match[0].length + subqueryMatch[0].length;\n continue;\n }\n\n const tableMatch = TABLE_REF_RE.exec(rest);\n if (!tableMatch) continue;\n tables.push(tableMatch[0]);\n\n let afterTable = rest.slice(tableMatch[0].length);\n let commaMatch: RegExpExecArray | null;\n while ((commaMatch = COMMA_TABLE_RE.exec(afterTable)) !== null) {\n if (!commaMatch[1]) break;\n tables.push(commaMatch[1]);\n afterTable = afterTable.slice(commaMatch[0].length);\n }\n }\n\n return tables;\n}\n\nfunction truncate(summary: string): string {\n if (summary.length <= MAX_SUMMARY_LENGTH) {\n return summary;\n }\n const truncated = summary.substring(0, MAX_SUMMARY_LENGTH);\n const lastSpace = truncated.lastIndexOf(' ');\n return lastSpace > 0 ? truncated.substring(0, lastSpace) : truncated;\n}\n\nlet integerLiteralRE: RegExp | undefined;\nlet mssqlIntegerLiteralRE: RegExp | undefined;\n\n/**\n * The lookbehind keeps `$n` and `?n` parameter placeholders out of the match. T-SQL has neither,\n * and `$1000` there is a money literal, so `$` only guards a placeholder outside `mssql`.\n *\n * Lazy init: constructing a lookbehind at module scope evaluates it on import and crashes\n * Safari <16.4 browser bundles that reach this file via the core barrel.\n */\nfunction getIntegerLiteralRE(dialect: SqlDialect): RegExp {\n if (dialect === 'mssql') {\n if (!mssqlIntegerLiteralRE) {\n mssqlIntegerLiteralRE = new RegExp('(?<!\\\\?)-?\\\\b\\\\d+\\\\b', 'g');\n }\n return mssqlIntegerLiteralRE;\n }\n if (!integerLiteralRE) {\n integerLiteralRE = new RegExp('(?<![$?])-?\\\\b\\\\d+\\\\b', 'g');\n }\n return integerLiteralRE;\n}\n\n/**\n * SQL dialect variants that matter for finding the end of a string literal:\n * - `standard` (PostgreSQL, SQLite): `\"` quotes identifiers, `''` is the only in-string escape,\n * and PostgreSQL's `$$…$$` dollar quoting opens a literal.\n * - `mysql`: `\"` quotes a string literal unless `ANSI_QUOTES` is set, and `\\` escapes the next\n * character unless `NO_BACKSLASH_ESCAPES` is set. Both default to off, and mysql/mysql2 escape\n * inlined values with backslashes, so this is the mode their statements arrive in.\n * - `mssql`: `[...]` quotes an identifier, so a `'` inside one is part of the name. `\"` quotes\n * one too, unless the connection sets `QUOTED_IDENTIFIER OFF`, which tedious leaves on.\n */\nexport type SqlDialect = 'standard' | 'mysql' | 'mssql';\n\n/**\n * Maps a driver or `db.system.name` value to the dialect its statements are written in. Callers\n * report different spellings for one engine: knex uses the driver name, Prisma the provider name,\n * and OTel the semantic-convention name. An engine we do not know about is lexed as `standard`.\n */\nexport function toSqlDialect(system: unknown): SqlDialect {\n if (system === 'mysql' || system === 'mysql2' || system === 'mariadb') {\n return 'mysql';\n }\n if (system === 'mssql' || system === 'sqlserver' || system === 'microsoft.sql_server') {\n return 'mssql';\n }\n return 'standard';\n}\n\n// Sticky, so the scanner can test one position without slicing the query on every `$`.\nconst DOLLAR_QUOTE_RE = /\\$(?:[A-Za-z_]\\w*)?\\$/y;\n\n/**\n * Returns the index just past the run's closing `delimiter`, or -1 if the run never closes. The\n * caller cannot derive that from the index alone: a query ending in `[a]]` consumed a doubled\n * delimiter, not a closing one.\n *\n * A doubled delimiter (`''`) escapes itself in every dialect; backslash escapes are dialect- and\n * context-dependent, so the caller decides.\n */\nfunction findQuotedRunEnd(sql: string, start: number, delimiter: string, backslashEscapes: boolean): number {\n for (let i = start + 1; i < sql.length; i++) {\n const char = sql[i];\n if (backslashEscapes && char === '\\\\') {\n i++;\n } else if (char === delimiter) {\n if (sql[i + 1] !== delimiter) {\n return i + 1;\n }\n i++;\n }\n }\n return -1;\n}\n\n/**\n * Replaces every string literal with `?` and drops every comment, in one pass.\n *\n * Doing this by scanning rather than by regex is what keeps quote state and comment state from\n * being decided independently: a regex for `'...'` cannot see that the quote it stopped at was\n * backslash-escaped, and a regex for `--...` cannot see that the `--` sits inside a literal. Both\n * mistakes end with user data surviving into `db.query.text` and `db.query.summary`.\n *\n * Quoted identifiers are preserved — they are the table and column names the query summary is\n * built from.\n */\nfunction stripLiteralsAndComments(sql: string, dialect: SqlDialect): string {\n const isMysql = dialect === 'mysql';\n const out: string[] = [];\n let i = 0;\n\n while (i < sql.length) {\n const char = sql[i]!;\n const next = sql[i + 1];\n\n if ((char === '-' && next === '-') || (isMysql && char === '#')) {\n const lineEnd = sql.indexOf('\\n', i);\n i = lineEnd === -1 ? sql.length : lineEnd;\n continue;\n }\n\n if (char === '/' && next === '*') {\n const commentEnd = sql.indexOf('*/', i + 2);\n i = commentEnd === -1 ? sql.length : commentEnd + 2;\n continue;\n }\n\n // In a dollar-quoted body (`$$body$$`, `$tag$body$tag$`) nothing has syntax meaning. Read the\n // previous character from the query, not from `out`, where a dropped comment would leave `$$`\n // looking like part of an identifier. Of the `standard` engines only PostgreSQL has dollar\n // quoting. SQLite `$name` parameters do not match the tag pattern, apart from the rare `$a$b`.\n if (dialect === 'standard' && char === '$' && !isIdentifierChar(sql[i - 1])) {\n const tag = matchDollarQuoteTag(sql, i);\n if (tag) {\n const bodyEnd = sql.indexOf(tag, i + tag.length);\n i = bodyEnd === -1 ? sql.length : bodyEnd + tag.length;\n out.push('?');\n continue;\n }\n }\n\n const identifierCloser = getIdentifierCloser(char, dialect);\n if (identifierCloser) {\n const runEnd = findQuotedRunEnd(sql, i, identifierCloser, false);\n // A run that never closes is not an identifier, so it collapses instead of being copied out.\n // Copying would carry every literal in the rest of the statement through unlexed.\n out.push(runEnd === -1 ? '?' : sql.slice(i, runEnd));\n i = runEnd === -1 ? sql.length : runEnd;\n continue;\n }\n\n if (char === \"'\" || (char === '\"' && isMysql)) {\n // A prefix like `X'1A'`, `B'01'`, `N'…'` or PostgreSQL's `E'a\\nb'` is part of the literal, so it has\n // to collapse into the same `?` instead of being left behind as a bare identifier.\n const prefix = char === \"'\" ? getLiteralPrefix(out, dialect) : undefined;\n if (prefix) {\n out.pop();\n }\n const runEnd = findQuotedRunEnd(sql, i, char, isMysql || prefix === 'E');\n i = runEnd === -1 ? sql.length : runEnd;\n out.push('?');\n continue;\n }\n\n out.push(char);\n i++;\n }\n\n return out.join('');\n}\n\n/**\n * Returns the character that closes an identifier opened by `char`, or undefined if `char` opens\n * none. SQL Server brackets close on `]`, and `]]` escapes a `]` inside the name, which is the same\n * doubling rule `findQuotedRunEnd` applies to quotes.\n */\nfunction getIdentifierCloser(char: string, dialect: SqlDialect): string | undefined {\n if (char === '`') {\n return '`';\n }\n if (char === '\"' && dialect !== 'mysql') {\n return '\"';\n }\n return char === '[' && dialect === 'mssql' ? ']' : undefined;\n}\n\n/** Whether `char` can appear inside an identifier. `undefined` (start of query) counts as a break. */\nfunction isIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[\\w$]/.test(char);\n}\n\n/** Returns the opening dollar-quote tag at `start` (`$$` or `$tag$`), or undefined if there is none. */\nfunction matchDollarQuoteTag(sql: string, start: number): string | undefined {\n DOLLAR_QUOTE_RE.lastIndex = start;\n return DOLLAR_QUOTE_RE.exec(sql)?.[0];\n}\n\n/**\n * Returns the literal-prefix character immediately before a `'`, if there is one: `X`/`B` for\n * hex/binary literals, `N` for a national-character literal (SQL Server, MySQL), or `E` for a\n * PostgreSQL escape string (which honors backslash escapes).\n */\nfunction getLiteralPrefix(out: string[], dialect: SqlDialect): 'X' | 'B' | 'N' | 'E' | undefined {\n const last = out[out.length - 1];\n // A prefix only counts when it stands alone — the `X` in `MAX'...'` belongs to the identifier\n if (last?.length !== 1 || isIdentifierChar(out[out.length - 2]?.slice(-1))) {\n return undefined;\n }\n\n const prefix = last.toUpperCase();\n if (prefix === 'X' || prefix === 'B' || prefix === 'N') {\n return prefix;\n }\n return prefix === 'E' && dialect === 'standard' ? 'E' : undefined;\n}\n\n/**\n * Sanitize SQL query as per the OTEL semantic conventions\n * https://opentelemetry.io/docs/specs/semconv/database/database-spans/#sanitization-of-dbquerytext\n *\n * Parameter placeholders survive: PostgreSQL `$n`, SQLite `?n`, and named forms like `:name` and\n * `@name`. Per the OTEL spec they mark a parameterized query, so only values (strings, numbers,\n * booleans) are sanitized.\n *\n * Pass `dialect` when the statement comes from a driver whose literals are not standard-quoted;\n * see {@link SqlDialect}.\n */\nexport function sanitizeSqlQuery(sqlQuery: string | undefined, dialect: SqlDialect = 'standard'): string {\n if (!sqlQuery) {\n return 'Unknown SQL Query';\n }\n\n return (\n // Strip comments and string literals first: everything below is a regex that cannot tell\n // whether it is looking at SQL syntax or at a user-supplied value.\n stripLiteralsAndComments(sqlQuery, dialect)\n .replace(/;\\s*$/, '') // Remove trailing semicolons\n .replace(/^[\\s;]+/, '') // Remove leading semicolons (T-SQL's `;WITH`)\n // Collapse whitespace to a single space (after removing comments)\n .replace(/\\s+/g, ' ')\n .trim() // Remove extra spaces and trim\n // Sanitize hex numbers\n .replace(/\\b0x[0-9A-Fa-f]+/gi, '?')\n // Sanitize boolean literals\n .replace(/\\b(?:TRUE|FALSE)\\b/gi, '?')\n // Sanitize numeric literals (preserve $n placeholders via negative lookbehind)\n .replace(/-?\\b\\d+\\.?\\d*[eE][+-]?\\d+\\b/g, '?') // Scientific notation\n .replace(/-?\\b\\d+\\.\\d+\\b/g, '?') // Decimals\n .replace(/-?\\.\\d+\\b/g, '?') // Decimals starting with dot\n .replace(getIntegerLiteralRE(dialect), '?') // Integers (NOT parameter placeholders)\n // Collapse IN clauses for cardinality (both ? and $n variants)\n .replace(/\\bIN\\b\\s*\\(\\s*\\?(?:\\s*,\\s*\\?)*\\s*\\)/gi, 'IN (?)')\n .replace(/\\bIN\\b\\s*\\(\\s*\\$\\d+(?:\\s*,\\s*\\$\\d+)*\\s*\\)/gi, 'IN ($?)')\n );\n}\n\nexport interface SqlQueryAttributes {\n [DB_QUERY_TEXT]: string | undefined;\n [DB_QUERY_SUMMARY]: string | undefined;\n [DB_OPERATION_NAME]: string | undefined;\n}\n\n/**\n * Sanitizes a collected SQL statement into the query attributes the SQL integrations attach to\n * their spans: `db.query.text`, `db.query.summary` and `db.operation.name`. All are `undefined`\n * when there is no statement, so an empty query omits the attributes instead of reporting the\n * sanitizer's fallback text.\n */\nexport function getSqlQueryAttributes(sqlQuery: string | undefined, dialect?: SqlDialect): SqlQueryAttributes {\n const queryText = (sqlQuery && sanitizeSqlQuery(sqlQuery, dialect)) || undefined;\n return {\n [DB_QUERY_TEXT]: queryText,\n [DB_QUERY_SUMMARY]: getSqlQuerySummary(queryText),\n [DB_OPERATION_NAME]: getSqlOperationName(queryText),\n };\n}\n\n/**\n * Names a SQL span with a low-cardinality name: `db.query.summary`, falling back to `db.namespace`\n * and then `db.system.name`. `fallback` is the integration's name for a span with none of those.\n *\n * New SQL integrations should name their spans with this regardless of span streaming.\n */\nexport function getLowCardinalitySqlSpanName(attributes: SpanAttributes, fallback: string): string {\n return toSpanName(attributes[DB_QUERY_SUMMARY] || attributes[DB_NAMESPACE] || attributes[DB_SYSTEM_NAME], fallback);\n}\n\n/**\n * Names a SQL span from its attributes. Streamed span names have to be low cardinality (see\n * {@link getLowCardinalitySqlSpanName}); otherwise the sanitized `db.query.text` is used, which\n * existing integrations keep for spans that aren't streamed.\n */\nexport function getSqlSpanName(attributes: SpanAttributes, fallback: string): string {\n const client = getClient();\n if (client && hasSpanStreamingEnabled(client)) {\n return getLowCardinalitySqlSpanName(attributes, fallback);\n }\n return toSpanName(attributes[DB_QUERY_TEXT], fallback);\n}\n\nfunction toSpanName(value: unknown, fallback: string): string {\n return typeof value === 'string' && value ? value : fallback;\n}\n"],"mappings":";;;AAUA,MAAM,qBAAqB;AAI3B,MAAM,aAAa;AAKnB,MAAM,aAAa,GAAG,WAAW,QAAQ,WAAW;AAEpD,MAAM,SAAS,IAAI,OACjB,qHAAqH,WAAW,IAChI,GACF;AAMA,MAAM,YAAY,IAAI,OACpB,8GAA8G,WAAW,IACzH,GACF;AACA,MAAM,YAAY,IAAI,OACpB,8FAA8F,WAAW,IACzG,GACF;AACA,MAAM,YAAY,IAAI,OAAO,iDAAiD,WAAW,IAAI,GAAG;AAEhG,MAAM,YAAY;AAElB,MAAM,YAAY;AAElB,MAAM,WAAW;AACjB,MAAM,eAAe,IAAI,OAAO,IAAI,YAAY;AAChD,MAAM,iBAAiB,IAAI,OAAO,cAAc,WAAW,EAAE;AAC7D,MAAM,qBAAqB;;;;;;;;;;;;;;AAe3B,SAAgB,mBAAmB,OAA+C;CAChF,IAAI,CAAC,OACH;CAGF,MAAM,cAAc,UAAU,KAAK,KAAK;CACxC,IAAI,aAAa,SAAS,gBAAgB,YAAY,OAAO,YAAY;EACvE,MAAM,YAAY,YAAY,OAAO;EACrC,MAAM,UAAU,YAAY,OAAO;EACnC,MAAM,WAAW,QAAQ,QAAQ,GAAG;EACpC,OAAO,SAAS,GAAG,UAAU,GAAG,YAAY,IAAI,QAAQ,UAAU,GAAG,QAAQ,IAAI,SAAS;CAC5F;CAEA,MAAM,WAAW,OAAO,KAAK,KAAK;CAClC,IAAI,UAAU,SAAS,gBAAgB,SAAS,OAAO,UACrD,OAAO,SAAS,GAAG,SAAS,OAAO,aAAa,GAAG,SAAS,OAAO,UAAU;CAG/E,MAAM,cAAc,UAAU,KAAK,KAAK;CACxC,IAAI,aA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SAAS,UAAU;CACzB,IAAI,UAAU,wBAAwB,MAAM,GAC1C,OAAO,6BAA6B,YAAY,QAAQ;CAE1D,OAAO,WAAW,WAAW,gBAAgB,QAAQ;AACvD;AAEA,SAAS,WAAW,OAAgB,UAA0B;CAC5D,OAAO,OAAO,UAAU,YAAY,QAAQ,QAAQ;AACtD"}
|
|
1
|
+
{"version":3,"file":"sql.js","names":[],"sources":["../../../src/utils/sql.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport {\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n} from '@sentry/conventions/attributes';\nimport type { SpanAttributes } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled } from '@sentry/core';\n\nconst MAX_SUMMARY_LENGTH = 255;\n\n// A single identifier: quoted (`\"...\"`, `'...'`, or MySQL backticks) or bare. The quoted forms have\n// to be matched as a unit, otherwise an identifier containing a space or a dot is cut in half.\nconst IDENTIFIER = '(?:\"[^\"]*\"|\\'[^\\']*\\'|`[^`]*`|[^\\\\s(,;).\\'\"`]+)';\n\n// A table reference can be schema-qualified (`\"public\".\"User\"`, `db.schema.table`), with each part\n// quoted independently. The whole qualified name is the summary target, since the schema is what\n// distinguishes two same-named tables.\nconst TABLE_NAME = `${IDENTIFIER}(?:\\\\.${IDENTIFIER})*`;\n\nconst DDL_RE = new RegExp(\n `^\\\\s*(?<operation>(?:CREATE|DROP)\\\\s+(?:TABLE|INDEX)|ALTER\\\\s+TABLE)(?:\\\\s+IF\\\\s+(?:NOT\\\\s+)?EXISTS)?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\n\n// SQLite upserts insert an optional conflict clause between operation and INTO\n// (`INSERT OR REPLACE INTO`, https://sqlite.org/lang_insert.html), with `REPLACE INTO` as the\n// standalone shorthand. The clause is filler like INTO — stripping it keeps upserts on the same\n// low-cardinality summary as plain inserts.\nconst INSERT_RE = new RegExp(\n `^\\\\s*(?<operation>INSERT|REPLACE)(?:\\\\s+OR\\\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\\\s+INTO(?:\\\\s+TABLE)?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\nconst UPDATE_RE = new RegExp(\n `^\\\\s*(?<operation>UPDATE)(?:\\\\s+OR\\\\s+(?:ROLLBACK|ABORT|FAIL|IGNORE|REPLACE))?\\\\s+(?<table>${TABLE_NAME})`,\n 'i',\n);\nconst DELETE_RE = new RegExp(`^\\\\s*(?<operation>DELETE)\\\\s+FROM\\\\s+(?<table>${TABLE_NAME})`, 'i');\n\nconst SELECT_RE = /^\\s*(?:\\(\\s*)?(?<operation>SELECT)\\b/i;\n\nconst PRAGMA_RE = /^\\s*(?<operation>PRAGMA)\\s+(?<command>\\S+)/i;\n\nconst TOKEN_RE = /\\b(?:FROM|JOIN)\\s+|\\(\\s*(SELECT)\\b|\\b(?:UNION|INTERSECT|EXCEPT|MINUS)\\s+(?:ALL\\s+)?(SELECT)\\b/gi;\nconst TABLE_REF_RE = new RegExp(`^${TABLE_NAME}`);\nconst COMMA_TABLE_RE = new RegExp(`^\\\\s*,\\\\s*(${TABLE_NAME})`);\nconst SUBQUERY_SELECT_RE = /^\\(\\s*(SELECT)\\b/i;\n\n/**\n * Derives a low-cardinality summary from a SQL query for use as `db.query.summary`.\n *\n * Conforms to the OTEL semantic convention for generating query summaries:\n * - Preserves original case of operations and identifiers (no normalization)\n * - Uses format: `{operation} {target1} {target2} ...`\n * - Strips filler words (INTO, FROM) from the operation\n * - Captures multiple table targets (JOINs)\n * - Handles INSERT...SELECT with both targets\n * - Truncates to 255 characters without splitting mid-value\n *\n * @see https://opentelemetry.io/docs/specs/semconv/database/database-spans/#generating-a-summary-of-the-query\n */\nexport function getSqlQuerySummary(query: string | undefined): string | undefined {\n if (!query) {\n return undefined;\n }\n\n const pragmaMatch = PRAGMA_RE.exec(query);\n if (pragmaMatch?.groups?.['operation'] && pragmaMatch.groups['command']) {\n const operation = pragmaMatch.groups['operation'];\n const command = pragmaMatch.groups['command'];\n const parenIdx = command.indexOf('(');\n return truncate(`${operation} ${parenIdx >= 0 ? command.substring(0, parenIdx) : command}`);\n }\n\n const ddlMatch = DDL_RE.exec(query);\n if (ddlMatch?.groups?.['operation'] && ddlMatch.groups['table']) {\n return truncate(`${ddlMatch.groups['operation']} ${ddlMatch.groups['table']}`);\n }\n\n const insertMatch = INSERT_RE.exec(query);\n if (insertMatch?.groups?.['operation'] && insertMatch.groups['table']) {\n const parts = [insertMatch.groups['operation'], insertMatch.groups['table']];\n const rest = query.slice(insertMatch[0].length);\n const subSelect = /\\b(SELECT)\\b/i.exec(rest);\n if (subSelect?.[1]) {\n parts.push(subSelect[1]);\n const selectTables = extractTableNames(rest.slice(subSelect.index));\n parts.push(...selectTables);\n }\n return truncate(parts.join(' '));\n }\n\n const updateMatch = UPDATE_RE.exec(query);\n if (updateMatch?.groups?.['operation'] && updateMatch.groups['table']) {\n return truncate(`${updateMatch.groups['operation']} ${updateMatch.groups['table']}`);\n }\n\n const deleteMatch = DELETE_RE.exec(query);\n if (deleteMatch?.groups?.['operation'] && deleteMatch.groups['table']) {\n return truncate(`${deleteMatch.groups['operation']} ${deleteMatch.groups['table']}`);\n }\n\n const selectMatch = SELECT_RE.exec(query);\n if (selectMatch?.groups?.['operation']) {\n const tables = extractTableNames(query.slice(selectMatch[0].length));\n if (tables.length > 0) {\n return truncate(`${selectMatch.groups['operation']} ${tables.join(' ')}`);\n }\n return selectMatch.groups['operation'];\n }\n\n return truncate(query.trim().split(/\\s+/)[0] ?? query);\n}\n\nconst LEADING_KEYWORD_RE = /^\\s*(?:\\(\\s*)*([A-Za-z]+)\\b/;\nconst CTE_MAIN_STATEMENT_RE = /\\(|\\)|\\b(SELECT|INSERT|UPDATE|DELETE|MERGE|VALUES|TABLE)\\b/gi;\n\n/**\n * Derives `db.operation.name` from a SQL query: the first operation keyword, in its original case.\n *\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/db/#db-operation-name\n */\nexport function getSqlOperationName(query: string | undefined): string | undefined {\n const match = query ? LEADING_KEYWORD_RE.exec(query) : null;\n const keyword = match?.[1];\n if (!query || !match || !keyword) {\n return undefined;\n }\n // Scanned from after `WITH`, so parentheses wrapping the whole query don't shift the depth.\n return keyword.toUpperCase() === 'WITH' ? getCteMainOperationName(query.slice(match[0].length)) : keyword;\n}\n\n/**\n * The operation of a `WITH` query is its main statement: the first operation keyword outside the\n * CTE bodies, which are all parenthesized. Counting parentheses is safe on a sanitized query, which\n * has no literals or comments left.\n */\nfunction getCteMainOperationName(query: string): string | undefined {\n let depth = 0;\n for (const match of query.matchAll(CTE_MAIN_STATEMENT_RE)) {\n if (match[0] === '(') {\n depth++;\n } else if (match[0] === ')') {\n depth--;\n } else if (depth === 0) {\n return match[1];\n }\n }\n return undefined;\n}\n\nfunction extractTableNames(sql: string): string[] {\n const tables: string[] = [];\n TOKEN_RE.lastIndex = 0;\n let match: RegExpExecArray | null;\n\n while ((match = TOKEN_RE.exec(sql)) !== null) {\n if (match[1] || match[2]) {\n tables.push((match[1] || match[2])!);\n continue;\n }\n\n const rest = sql.slice(match.index + match[0].length);\n\n const subqueryMatch = SUBQUERY_SELECT_RE.exec(rest);\n if (subqueryMatch?.[1]) {\n tables.push(subqueryMatch[1]);\n TOKEN_RE.lastIndex = match.index + match[0].length + subqueryMatch[0].length;\n continue;\n }\n\n const tableMatch = TABLE_REF_RE.exec(rest);\n if (!tableMatch) continue;\n tables.push(tableMatch[0]);\n\n let afterTable = rest.slice(tableMatch[0].length);\n let commaMatch: RegExpExecArray | null;\n while ((commaMatch = COMMA_TABLE_RE.exec(afterTable)) !== null) {\n if (!commaMatch[1]) break;\n tables.push(commaMatch[1]);\n afterTable = afterTable.slice(commaMatch[0].length);\n }\n }\n\n return tables;\n}\n\nfunction truncate(summary: string): string {\n if (summary.length <= MAX_SUMMARY_LENGTH) {\n return summary;\n }\n const truncated = summary.substring(0, MAX_SUMMARY_LENGTH);\n const lastSpace = truncated.lastIndexOf(' ');\n return lastSpace > 0 ? truncated.substring(0, lastSpace) : truncated;\n}\n\nlet integerLiteralRE: RegExp | undefined;\nlet mssqlIntegerLiteralRE: RegExp | undefined;\n\n/**\n * The lookbehind keeps `$n` and `?n` parameter placeholders out of the match. T-SQL has neither,\n * and `$1000` there is a money literal, so `$` only guards a placeholder outside `mssql`.\n *\n * Lazy init: constructing a lookbehind at module scope evaluates it on import and crashes\n * Safari <16.4 browser bundles that reach this file via the core barrel.\n */\nfunction getIntegerLiteralRE(dialect: SqlDialect | SqlLexerRules): RegExp {\n if (dialect === 'mssql') {\n if (!mssqlIntegerLiteralRE) {\n mssqlIntegerLiteralRE = new RegExp('(?<!\\\\?)-?\\\\b\\\\d+\\\\b', 'g');\n }\n return mssqlIntegerLiteralRE;\n }\n if (!integerLiteralRE) {\n integerLiteralRE = new RegExp('(?<![$?])-?\\\\b\\\\d+\\\\b', 'g');\n }\n return integerLiteralRE;\n}\n\n/**\n * SQL dialect variants that matter for finding the end of a string literal:\n * - `standard` (PostgreSQL, SQLite): `\"` quotes identifiers, `''` is the only in-string escape,\n * and PostgreSQL's `$$…$$` dollar quoting opens a literal.\n * - `mysql`: `\"` quotes a string literal unless `ANSI_QUOTES` is set, and `\\` escapes the next\n * character unless `NO_BACKSLASH_ESCAPES` is set. Both default to off, and mysql/mysql2 escape\n * inlined values with backslashes, so this is the mode their statements arrive in.\n * - `mssql`: `[...]` quotes an identifier, so a `'` inside one is part of the name. `\"` quotes\n * one too, unless the connection sets `QUOTED_IDENTIFIER OFF`, which tedious leaves on.\n *\n * An engine with other rules passes {@link SqlLexerRules} instead.\n */\nexport type SqlDialect = 'standard' | 'mysql' | 'mssql';\n\n/**\n * Lexer rules for an engine that no {@link SqlDialect} covers. They apply on top of `standard`. The\n * integration of that engine defines them, so a bundle without that integration does not contain them.\n */\nexport interface SqlLexerRules {\n /** Whether `#` starts a line comment. */\n hashComments?: boolean;\n /** Whether a block comment can contain other block comments. */\n nestedComments?: boolean;\n /** Whether `\\` escapes the next character in a string literal or a quoted identifier. */\n backslashEscapes?: boolean;\n /** Sticky pattern for the opening tag of a dollar-quoted literal. Defaults to the PostgreSQL tag. */\n dollarQuote?: RegExp;\n /** Returns the length of the engine-specific literal at `start`, which the lexer replaces with `?`. */\n matchLiteral?: (sql: string, start: number) => number;\n /**\n * Returns true when inline data starts at `start`. The lexer drops the query text from `start` to the\n * end, because data cannot be sanitized as SQL. `out` holds the sanitized text before `start`.\n */\n isInlineData?: (sql: string, start: number, out: string[]) => boolean;\n}\n\n/**\n * Maps a driver or `db.system.name` value to the dialect its statements are written in. Callers\n * report different spellings for one engine: knex uses the driver name, Prisma the provider name,\n * and OTel the semantic-convention name. An engine we do not know about is lexed as `standard`.\n */\nexport function toSqlDialect(system: unknown): SqlDialect {\n if (system === 'mysql' || system === 'mysql2' || system === 'mariadb') {\n return 'mysql';\n }\n if (system === 'mssql' || system === 'sqlserver' || system === 'microsoft.sql_server') {\n return 'mssql';\n }\n return 'standard';\n}\n\nconst NO_RULES: SqlLexerRules = {};\n\n// Sticky, so the scanner can test one position without slicing the query on every `$`.\nconst DOLLAR_QUOTE_RE = /\\$(?:[A-Za-z_]\\w*)?\\$/y;\n\n/**\n * Returns the index just past the run's closing `delimiter`, or -1 if the run never closes. The\n * caller cannot derive that from the index alone: a query ending in `[a]]` consumed a doubled\n * delimiter, not a closing one.\n *\n * A doubled delimiter (`''`) escapes itself in every dialect; backslash escapes are dialect- and\n * context-dependent, so the caller decides.\n */\nfunction findQuotedRunEnd(sql: string, start: number, delimiter: string, backslashEscapes: boolean): number {\n for (let i = start + 1; i < sql.length; i++) {\n const char = sql[i];\n if (backslashEscapes && char === '\\\\') {\n i++;\n } else if (char === delimiter) {\n if (sql[i + 1] !== delimiter) {\n return i + 1;\n }\n i++;\n }\n }\n return -1;\n}\n\n// An unterminated comment consumes the rest of the query.\nfunction findBlockCommentEnd(sql: string, start: number, nested: boolean): number {\n let depth = 1;\n let i = start + 2;\n while (i < sql.length && depth > 0) {\n if (sql[i] === '*' && sql[i + 1] === '/') {\n depth--;\n i += 2;\n } else if (nested && sql[i] === '/' && sql[i + 1] === '*') {\n depth++;\n i += 2;\n } else {\n i++;\n }\n }\n return i;\n}\n\n/**\n * Replaces every string literal with `?` and drops every comment, in one pass.\n *\n * Doing this by scanning rather than by regex is what keeps quote state and comment state from\n * being decided independently: a regex for `'...'` cannot see that the quote it stopped at was\n * backslash-escaped, and a regex for `--...` cannot see that the `--` sits inside a literal. Both\n * mistakes end with user data surviving into `db.query.text` and `db.query.summary`.\n *\n * Quoted identifiers are preserved — they are the table and column names the query summary is\n * built from.\n */\nfunction stripLiteralsAndComments(sql: string, dialect: SqlDialect | SqlLexerRules): string {\n const [base, rules]: [SqlDialect, SqlLexerRules] =\n typeof dialect === 'string' ? [dialect, NO_RULES] : ['standard', dialect];\n const isMysql = base === 'mysql';\n const backslashEscapes = !!rules.backslashEscapes;\n const out: string[] = [];\n let i = 0;\n\n while (i < sql.length) {\n const char = sql[i]!;\n const next = sql[i + 1];\n\n if ((char === '-' && next === '-') || ((isMysql || rules.hashComments) && char === '#')) {\n const lineEnd = sql.indexOf('\\n', i);\n i = lineEnd === -1 ? sql.length : lineEnd;\n continue;\n }\n\n if (char === '/' && next === '*') {\n i = findBlockCommentEnd(sql, i, !!rules.nestedComments);\n continue;\n }\n\n // In a dollar-quoted body (`$$body$$`, `$tag$body$tag$`) nothing has syntax meaning. Read the\n // previous character from the query, not from `out`, where a dropped comment would leave `$$`\n // looking like part of an identifier. Of the `standard` engines only PostgreSQL has dollar\n // quoting. SQLite `$name` parameters do not match the tag pattern, apart from the rare `$a$b`.\n if (base === 'standard' && char === '$' && !isIdentifierChar(sql[i - 1])) {\n const tag = matchDollarQuoteTag(sql, i, rules.dollarQuote);\n if (tag) {\n const bodyEnd = sql.indexOf(tag, i + tag.length);\n i = bodyEnd === -1 ? sql.length : bodyEnd + tag.length;\n out.push('?');\n continue;\n }\n }\n\n const identifierCloser = getIdentifierCloser(char, base);\n if (identifierCloser) {\n const runEnd = findQuotedRunEnd(sql, i, identifierCloser, backslashEscapes);\n // A run that never closes is not an identifier, so it collapses instead of being copied out.\n // Copying would carry every literal in the rest of the statement through unlexed.\n out.push(runEnd === -1 ? '?' : sql.slice(i, runEnd));\n i = runEnd === -1 ? sql.length : runEnd;\n continue;\n }\n\n if (char === \"'\" || (char === '\"' && isMysql)) {\n // A prefix like `X'1A'`, `B'01'`, `N'…'` or PostgreSQL's `E'a\\nb'` is part of the literal, so it has\n // to collapse into the same `?` instead of being left behind as a bare identifier.\n const prefix = char === \"'\" ? getLiteralPrefix(out, base) : undefined;\n if (prefix) {\n out.pop();\n }\n const runEnd = findQuotedRunEnd(sql, i, char, isMysql || backslashEscapes || prefix === 'E');\n i = runEnd === -1 ? sql.length : runEnd;\n out.push('?');\n continue;\n }\n\n const literalLength = rules.matchLiteral?.(sql, i);\n if (literalLength) {\n out.push('?');\n i += literalLength;\n continue;\n }\n if (rules.isInlineData?.(sql, i, out)) {\n break;\n }\n out.push(char);\n i++;\n }\n\n return out.join('');\n}\n\n/**\n * Returns the character that closes an identifier opened by `char`, or undefined if `char` opens\n * none. SQL Server brackets close on `]`, and `]]` escapes a `]` inside the name, which is the same\n * doubling rule `findQuotedRunEnd` applies to quotes.\n */\nfunction getIdentifierCloser(char: string, dialect: SqlDialect): string | undefined {\n if (char === '`') {\n return '`';\n }\n if (char === '\"' && dialect !== 'mysql') {\n return '\"';\n }\n return char === '[' && dialect === 'mssql' ? ']' : undefined;\n}\n\n/** Whether `char` can appear inside an identifier. `undefined` (start of query) counts as a break. */\nexport function isIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && /[\\w$]/.test(char);\n}\n\n/** Returns the opening dollar-quote tag at `start` (`$$` or `$tag$`), or undefined if there is none. */\nfunction matchDollarQuoteTag(sql: string, start: number, pattern = DOLLAR_QUOTE_RE): string | undefined {\n pattern.lastIndex = start;\n return pattern.exec(sql)?.[0];\n}\n\n/**\n * Returns the literal-prefix character immediately before a `'`, if there is one: `X`/`B` for\n * hex/binary literals, `N` for a national-character literal (SQL Server, MySQL), or `E` for a\n * PostgreSQL escape string (which honors backslash escapes).\n */\nfunction getLiteralPrefix(out: string[], dialect: SqlDialect): 'X' | 'B' | 'N' | 'E' | undefined {\n const last = out[out.length - 1];\n // A prefix only counts when it stands alone — the `X` in `MAX'...'` belongs to the identifier\n if (last?.length !== 1 || isIdentifierChar(out[out.length - 2]?.slice(-1))) {\n return undefined;\n }\n\n const prefix = last.toUpperCase();\n if (prefix === 'X' || prefix === 'B' || prefix === 'N') {\n return prefix;\n }\n return prefix === 'E' && dialect === 'standard' ? 'E' : undefined;\n}\n\n/**\n * Sanitize SQL query as per the OTEL semantic conventions\n * https://opentelemetry.io/docs/specs/semconv/database/database-spans/#sanitization-of-dbquerytext\n *\n * Parameter placeholders survive: PostgreSQL `$n`, SQLite `?n`, and named forms like `:name` and\n * `@name`. Per the OTEL spec they mark a parameterized query, so only values (strings, numbers,\n * booleans) are sanitized.\n *\n * Pass `dialect` when the statement comes from a driver whose literals are not standard-quoted;\n * see {@link SqlDialect} and {@link SqlLexerRules}.\n */\nexport function sanitizeSqlQuery(\n sqlQuery: string | undefined,\n dialect: SqlDialect | SqlLexerRules = 'standard',\n): string {\n if (!sqlQuery) {\n return 'Unknown SQL Query';\n }\n\n return (\n // Strip comments and string literals first: everything below is a regex that cannot tell\n // whether it is looking at SQL syntax or at a user-supplied value.\n stripLiteralsAndComments(sqlQuery, dialect)\n .replace(/;\\s*$/, '') // Remove trailing semicolons\n .replace(/^[\\s;]+/, '') // Remove leading semicolons (T-SQL's `;WITH`)\n // Collapse whitespace to a single space (after removing comments)\n .replace(/\\s+/g, ' ')\n .trim() // Remove extra spaces and trim\n // Sanitize hex numbers\n .replace(/\\b0x[0-9A-Fa-f]+/gi, '?')\n // Sanitize boolean literals\n .replace(/\\b(?:TRUE|FALSE)\\b/gi, '?')\n // Sanitize numeric literals (preserve $n placeholders via negative lookbehind)\n .replace(/-?\\b\\d+\\.?\\d*[eE][+-]?\\d+\\b/g, '?') // Scientific notation\n .replace(/-?\\b\\d+\\.\\d+\\b/g, '?') // Decimals\n .replace(/-?\\.\\d+\\b/g, '?') // Decimals starting with dot\n .replace(getIntegerLiteralRE(dialect), '?') // Integers (NOT parameter placeholders)\n // Collapse IN clauses for cardinality (both ? and $n variants)\n .replace(/\\bIN\\b\\s*\\(\\s*\\?(?:\\s*,\\s*\\?)*\\s*\\)/gi, 'IN (?)')\n .replace(/\\bIN\\b\\s*\\(\\s*\\$\\d+(?:\\s*,\\s*\\$\\d+)*\\s*\\)/gi, 'IN ($?)')\n );\n}\n\nexport interface SqlQueryAttributes {\n [DB_QUERY_TEXT]: string | undefined;\n [DB_QUERY_SUMMARY]: string | undefined;\n [DB_OPERATION_NAME]: string | undefined;\n}\n\n/**\n * Sanitizes a collected SQL statement into the query attributes the SQL integrations attach to\n * their spans: `db.query.text`, `db.query.summary` and `db.operation.name`. All are `undefined`\n * when there is no statement, so an empty query omits the attributes instead of reporting the\n * sanitizer's fallback text.\n */\nexport function getSqlQueryAttributes(\n sqlQuery: string | undefined,\n dialect?: SqlDialect | SqlLexerRules,\n): SqlQueryAttributes {\n const queryText = (sqlQuery && sanitizeSqlQuery(sqlQuery, dialect)) || undefined;\n return {\n [DB_QUERY_TEXT]: queryText,\n [DB_QUERY_SUMMARY]: getSqlQuerySummary(queryText),\n [DB_OPERATION_NAME]: getSqlOperationName(queryText),\n };\n}\n\n/**\n * Names a SQL span with a low-cardinality name: `db.query.summary`, falling back to `db.namespace`\n * and then `db.system.name`. `fallback` is the integration's name for a span with none of those.\n *\n * New SQL integrations should name their spans with this regardless of span streaming.\n */\nexport function getLowCardinalitySqlSpanName(attributes: SpanAttributes, fallback: string): string {\n return toSpanName(attributes[DB_QUERY_SUMMARY] || attributes[DB_NAMESPACE] || attributes[DB_SYSTEM_NAME], fallback);\n}\n\n/**\n * Names a SQL span from its attributes. Streamed span names have to be low cardinality (see\n * {@link getLowCardinalitySqlSpanName}); otherwise the sanitized `db.query.text` is used, which\n * existing integrations keep for spans that aren't streamed.\n */\nexport function getSqlSpanName(attributes: SpanAttributes, fallback: string): string {\n const client = getClient();\n if (client && hasSpanStreamingEnabled(client)) {\n return getLowCardinalitySqlSpanName(attributes, fallback);\n }\n return toSpanName(attributes[DB_QUERY_TEXT], fallback);\n}\n\nfunction toSpanName(value: unknown, fallback: string): string {\n return typeof value === 'string' && value ? value : fallback;\n}\n"],"mappings":";;;AAWA,MAAM,qBAAqB;AAI3B,MAAM,aAAa;AAKnB,MAAM,aAAa,GAAG,WAAW,QAAQ,WAAW;AAEpD,MAAM,SAAS,IAAI,OACjB,qHAAqH,WAAW,IAChI,GACF;AAMA,MAAM,YAAY,IAAI,OACpB,4HAA4H,WAAW,IACvI,GACF;AACA,MAAM,YAAY,IAAI,OACpB,8FAA8F,WAAW,IACzG,GACF;AACA,MAAM,YAAY,IAAI,OAAO,iDAAiD,WAAW,IAAI,GAAG;AAEhG,MAAM,YAAY;AAElB,MAAM,YAAY;AAElB,MAAM,WAAW;AACjB,MAAM,eAAe,IAAI,OAAO,IAAI,YAAY;AAChD,MAAM,iBAAiB,IAAI,OAAO,cAAc,WAAW,EAAE;AAC7D,MAAM,qBAAqB;;;;;;;;;;;;;;AAe3B,SAAgB,mBAAmB,OAA+C;CAChF,IAAI,CAAC,OACH;CAGF,MAAM,cAAc,UAAU,KAAK,KAAK;CACxC,IAAI,aAAa,SAAS,gBAAgB,YAAY,OAAO,YAAY;EACvE,MAAM,YAAY,YAAY,OAAO;EACrC,MAAM,UAAU,YAAY,OAAO;EACnC,MAAM,WAAW,QAAQ,QAAQ,GAAG;EACpC,OAAO,SAAS,GAAG,UAAU,GAAG,YAAY,IAAI,QAAQ,UAAU,GAAG,QAAQ,IAAI,SAAS;CAC5F;CAEA,MAAM,WAAW,OAAO,KAAK,KAAK;CAClC,IAAI,UAAU,SAAS,gBAAgB,SAAS,OAAO,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,QAAQ,WAAW,EAAE,CAAC,CAEtB,QAAQ,QAAQ,GAAG,CAAC,CACpB,KAAK,CAAC,CAEN,QAAQ,sBAAsB,GAAG,CAAC,CAElC,QAAQ,wBAAwB,GAAG,CAAC,CAEpC,QAAQ,gCAAgC,GAAG,CAAC,CAC5C,QAAQ,mBAAmB,GAAG,CAAC,CAC/B,QAAQ,cAAc,GAAG,CAAC,CAC1B,QAAQ,oBAAoB,OAAO,GAAG,GAAG,CAAC,CAE1C,QAAQ,yCAAyC,QAAQ,CAAC,CAC1D,QAAQ,+CAA+C,SAAS;AAEvE;;;;;;;AAcA,SAAgB,sBACd,UACA,SACoB;CACpB,MAAM,YAAa,YAAY,iBAAiB,UAAU,OAAO,KAAM,KAAA;CACvE,OAAO;GACJ,gBAAgB;GAChB,mBAAmB,mBAAmB,SAAS;GAC/C,oBAAoB,oBAAoB,SAAS;CACpD;AACF;;;;;;;AAQA,SAAgB,6BAA6B,YAA4B,UAA0B;CACjG,OAAO,WAAW,WAAW,qBAAqB,WAAW,iBAAiB,WAAW,iBAAiB,QAAQ;AACpH;;;;;;AAOA,SAAgB,eAAe,YAA4B,UAA0B;CACnF,MAAM,SAAS,UAAU;CACzB,IAAI,UAAU,wBAAwB,MAAM,GAC1C,OAAO,6BAA6B,YAAY,QAAQ;CAE1D,OAAO,WAAW,WAAW,gBAAgB,QAAQ;AACvD;AAEA,SAAS,WAAW,OAAgB,UAA0B;CAC5D,OAAO,OAAO,UAAU,YAAY,QAAQ,QAAQ;AACtD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DEBUG_BUILD } from "../debug-build.js";
|
|
2
2
|
import { monitorStream } from "./monitorStream.js";
|
|
3
|
-
import { CLIENT_ADDRESS, CLIENT_PORT, HTTP_REQUEST_BODY_SIZE, NETWORK_PROTOCOL_NAME, SENTRY_OP, SENTRY_SEGMENT_NAME_SOURCE, USER_AGENT_ORIGINAL } from "@sentry/conventions/attributes";
|
|
3
|
+
import { CLIENT_ADDRESS, CLIENT_PORT, HTTP_REQUEST_BODY_SIZE, NETWORK_PROTOCOL_NAME, SENTRY_KIND, SENTRY_OP, SENTRY_SEGMENT_NAME_SOURCE, USER_AGENT_ORIGINAL } from "@sentry/conventions/attributes";
|
|
4
4
|
import { HTTP_SPAN_NAME_FALLBACK, SPAN_STATUS_ERROR, captureBodyFromWinterCGRequest, captureException, continueTrace, getCurrentScope, getHttpSpanDetailsFromUrlObject, hasSpanStreamingEnabled, hasSpansEnabled, httpHeadersToSpanAttributes, parseStringToURLObject, safeCallback, setHttpStatus, startSpanManual, winterCGHeadersToDict, winterCGRequestToRequestData, withIsolationScope, withScope } from "@sentry/core";
|
|
5
5
|
import { HTTP_SERVER } from "@sentry/conventions/op";
|
|
6
6
|
import { _INTERNAL_isServedTunnelRequest, classifyResponseStreaming, getClientIPAddress, isStaticAssetRequest, startRequestSession } from "@sentry/core/server";
|
|
@@ -112,6 +112,7 @@ async function wrapServerRequestHandler(config, handler) {
|
|
|
112
112
|
Object.assign(attributes, httpHeadersToSpanAttributes(headers, dataCollection));
|
|
113
113
|
Object.assign(attributes, config.attributes);
|
|
114
114
|
attributes[SENTRY_OP] = HTTP_SERVER;
|
|
115
|
+
attributes[SENTRY_KIND] = "server";
|
|
115
116
|
return startSpanManual({
|
|
116
117
|
name,
|
|
117
118
|
attributes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wrapServerRequestHandler.js","names":["isServedTunnelRequest"],"sources":["../../../src/utils/wrapServerRequestHandler.ts"],"sourcesContent":["import {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_REQUEST_BODY_SIZE,\n NETWORK_PROTOCOL_NAME,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport type { Client, Mechanism, Scope, SpanAttributes } from '@sentry/core';\nimport {\n captureBodyFromWinterCGRequest,\n captureException,\n continueTrace,\n getCurrentScope,\n getHttpSpanDetailsFromUrlObject,\n hasSpansEnabled,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n safeCallback,\n setHttpStatus,\n SPAN_STATUS_ERROR,\n startSpanManual,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { ServerRequestOptions } from '@sentry/core/server';\nimport {\n _INTERNAL_isServedTunnelRequest as isServedTunnelRequest,\n classifyResponseStreaming,\n getClientIPAddress,\n isStaticAssetRequest,\n startRequestSession,\n} from '@sentry/core/server';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { monitorStream } from './monitorStream';\n\nexport interface ServerRequestHandlerConfig {\n request: Request;\n client: Client;\n /** The isolation scope of this request. */\n isolationScope: Scope;\n /** The options of the runtime's integration for incoming requests. */\n options: ServerRequestOptions<Request, Response> | undefined;\n /** Origin of the span, e.g. `auto.http.deno`. */\n origin: string;\n /** Mechanism of errors that the handler or the response stream throws. Omit to not capture them. */\n mechanism?: Mechanism;\n /** The address and port of the socket, if the runtime knows them. */\n getSocketAddress?: () => { address: string; port?: number } | undefined;\n /** The matched route of the server framework, e.g. `/users/:id`. Sets `http.route` and the span name. */\n routeName?: string;\n /** Span attributes that only the runtime knows, e.g. the route parameters. */\n attributes?: SpanAttributes;\n /**\n * Called in the scope of the continued trace, before the span starts. Lets the runtime continue\n * its own trace, e.g. the trace that Cloudflare exports for the invocation.\n */\n onTraceContinued?: () => void;\n /** Whether the response streams. Return `undefined` to use the default classification. */\n isStreamingResponse?: (response: Response) => boolean | undefined;\n /**\n * Called once when the request is done: when the response is returned, when a streamed body\n * finishes, or when the handler throws (then without a response).\n */\n onDone?: (response: Response | undefined) => void;\n}\n\n/**\n * Wraps a handler of a web `Request`, as used by `Deno.serve`, `Bun.serve` and Cloudflare Workers.\n *\n * It records the request session, attaches the request data and body, continues the incoming\n * trace, creates the `http.server` span, and captures errors that the handler throws. The rules\n * follow core's `node:http` server code:\n *\n * - `OPTIONS` and `HEAD` requests get no span and no body capture.\n * - The static asset filter applies only to `GET`.\n * - The span and the session of a streamed response end when the stream finishes.\n *\n * The handler can return no response, as Bun's `fetch` does after a WebSocket upgrade.\n */\nexport async function wrapServerRequestHandler<R extends Response | undefined = Response>(\n config: ServerRequestHandlerConfig,\n handler: () => R | Promise<R>,\n): Promise<R> {\n const { request, client, isolationScope, options, mechanism } = config;\n\n const method = request.method.toUpperCase();\n const captureError = (error: unknown): void => {\n if (mechanism) {\n captureException(error, { mechanism });\n }\n };\n\n const socketAddress = config.getSocketAddress?.();\n // Without `AsyncLocalStorage`, all requests share one isolation scope, so clear what an earlier\n // request left on it: the merge keeps its body, and its response context would stay set.\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: { ...winterCGRequestToRequestData(request), data: undefined },\n ipAddress: socketAddress?.address,\n });\n isolationScope.setContext('response', null);\n\n // Tunnel requests get no session, body or span, whether the SDK or the app answers them. The app answers them with\n // `intercept: false`, from its own code, so its errors are still captured.\n if (isServedTunnelRequest(request, client)) {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n config.onDone?.(response);\n }\n }\n\n const endSession = options?.sessions\n ? startRequestSession(client, {\n requestIsolationScope: isolationScope,\n sessionFlushingDelayMS: options.sessionFlushingDelayMS,\n })\n : undefined;\n const finish = (response: Response | undefined): void => {\n endSession?.();\n config.onDone?.(response);\n };\n const isStreamingResponse = (response: Response): boolean => {\n const classification = config.isStreamingResponse?.(response);\n return typeof classification === 'boolean' ? classification : classifyResponseStreaming(response).isStreaming;\n };\n\n if (method === 'OPTIONS' || method === 'HEAD') {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n finish(response);\n }\n }\n\n const dataCollection = client.getDataCollectionOptions();\n const effectiveBodySize =\n options?.maxRequestBodySize ?? (dataCollection.httpBodies.includes('incomingRequest') ? 'medium' : 'none');\n const ignoreRequestBody = options?.ignoreRequestBody;\n if (\n method !== 'GET' &&\n effectiveBodySize !== 'none' &&\n // If the filter throws, skip the body so it cannot leak data the filter was meant to hide.\n !(\n ignoreRequestBody &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreRequestBody`, skipping the body:' : '',\n () => ignoreRequestBody(request.url, request),\n () => true,\n )\n )\n ) {\n await captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);\n }\n\n const urlObject = parseStringToURLObject(request.url);\n const urlPath = urlObject ? `${urlObject.pathname}${urlObject.search}` : '/';\n const createSpan = shouldCreateSpan(client, options, request, urlPath);\n\n return continueTrace(\n {\n sentryTrace: request.headers.get('sentry-trace') || '',\n baggage: request.headers.get('baggage'),\n },\n async () => {\n config.onTraceContinued?.();\n\n if (!createSpan) {\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n captureError(e);\n finish(undefined);\n throw e;\n }\n if (response) {\n isolationScope.setContext('response', { status_code: response.status });\n }\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => finish(response)),\n inRequestScope(captureError),\n );\n }\n\n const [rawName, attributes] = getHttpSpanDetailsFromUrlObject(\n urlObject,\n 'server',\n config.origin,\n request,\n config.routeName,\n client,\n );\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // A `route` source means the name already is (e.g. the `/` path), so it is kept as-is.\n const name =\n attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' || !hasSpanStreamingEnabled(client)\n ? rawName\n : method || HTTP_SPAN_NAME_FALLBACK;\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes[HTTP_REQUEST_BODY_SIZE] = parseInt(contentLength, 10);\n }\n const userAgent = request.headers.get('user-agent');\n if (userAgent) {\n attributes[USER_AGENT_ORIGINAL] = userAgent;\n }\n\n const headers = winterCGHeadersToDict(request.headers);\n if (dataCollection.userInfo) {\n // `client.address` is the originating client, so a forwarding header wins over the socket, which\n // behind a proxy holds the proxy's address. The socket port is the proxy's too, so `client.port`\n // stays unset then.\n const forwardedAddress = getClientIPAddress(headers);\n if (forwardedAddress) {\n attributes[CLIENT_ADDRESS] = forwardedAddress;\n } else if (socketAddress) {\n attributes[CLIENT_ADDRESS] = socketAddress.address;\n if (socketAddress.port !== undefined) {\n attributes[CLIENT_PORT] = socketAddress.port;\n }\n }\n }\n\n // describes the OSI application-layer protocol (http), not the scheme (might be https)\n attributes[NETWORK_PROTOCOL_NAME] = 'http';\n Object.assign(attributes, httpHeadersToSpanAttributes(headers, dataCollection));\n Object.assign(attributes, config.attributes);\n attributes[SENTRY_OP] = HTTP_SERVER;\n\n return startSpanManual({ name, attributes }, async span => {\n const { onSpanCreated, onSpanEnd } = options ?? {};\n if (onSpanCreated) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanCreated`:' : '',\n () => onSpanCreated(span, request),\n () => undefined,\n );\n }\n\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n captureError(e);\n finish(undefined);\n throw e;\n }\n\n if (response) {\n setHttpStatus(span, response.status);\n isolationScope.setContext('response', { status_code: response.status });\n span.setAttributes(\n httpHeadersToSpanAttributes(responseHeadersToDict(response.headers), dataCollection, 'response'),\n );\n }\n\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => {\n if (onSpanEnd && response) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanEnd`:' : '',\n () => onSpanEnd(span, request, response),\n () => undefined,\n );\n }\n span.end();\n finish(response);\n }),\n inRequestScope((error: unknown) => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureError(error);\n }),\n );\n });\n },\n );\n}\n\n/**\n * Returns a function that binds a callback to the request's isolation scope and the current scope.\n *\n * A streamed body finishes after the handler returns. Without `AsyncLocalStorage` (Cloudflare\n * Workers without `nodejs_compat`), its callbacks then run outside the request's scopes, where\n * `getClient()` finds no client: the segment span would be sent as a transaction, and a captured\n * error would not update the request session.\n */\nfunction bindToRequestScope(\n isolationScope: Scope,\n): <A extends unknown[]>(fn: (...args: A) => void) => (...args: A) => void {\n const scope = getCurrentScope();\n return fn =>\n (...args) =>\n withIsolationScope(isolationScope, () => withScope(scope, () => fn(...args)));\n}\n\nfunction shouldCreateSpan(\n client: Client,\n options: ServerRequestOptions<Request, Response> | undefined,\n request: Request,\n urlPath: string,\n): boolean {\n if (!(options?.spans ?? hasSpansEnabled(client.getOptions()))) {\n return false;\n }\n if (options?.ignoreStaticAssets && request.method.toUpperCase() === 'GET' && isStaticAssetRequest(urlPath)) {\n return false;\n }\n const ignoreIncomingRequests = options?.ignoreIncomingRequests;\n return !(\n ignoreIncomingRequests &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreIncomingRequests`, creating the span:' : '',\n () => ignoreIncomingRequests(urlPath, request),\n () => false,\n )\n );\n}\n\n/**\n * Calls `onDone` when the response is done: at once, or when a streamed body finishes.\n * Returns the response to send.\n */\nfunction onResponseDone<R extends Response | undefined>(\n response: R,\n isStreaming: boolean,\n onDone: () => void,\n onStreamError: (error: unknown) => void,\n): R {\n if (isStreaming && response?.body && !response.body.locked) {\n try {\n // Passing the original response as the init keeps its status, status text and headers, and\n // on Cloudflare also `encodeBody: 'manual'`, so workerd does not compress a compressed body again.\n return new Response(monitorStream(response.body, onDone, onStreamError), response) as R;\n } catch {\n // Workers with a compatibility date before 2022-11-30 and without the\n // `streams_enable_constructors` flag cannot construct a `ReadableStream`, so end at once.\n }\n }\n onDone();\n return response;\n}\n\n// `Headers.forEach` lists each `Set-Cookie` header on its own, so a plain dict keeps only the last one.\nfunction responseHeadersToDict(headers: Headers): Record<string, string | string[]> {\n const dict: Record<string, string | string[]> = winterCGHeadersToDict(headers);\n const setCookie = typeof headers.getSetC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,CAAC;IACrE,aAAa,KAAK;GACpB,CAAC,CACH;EACF,CAAC;CACH,CACF;AACF;;;;;;;;;AAUA,SAAS,mBACP,gBACyE;CACzE,MAAM,QAAQ,gBAAgB;CAC9B,QAAO,QACJ,GAAG,SACF,mBAAmB,sBAAsB,UAAU,aAAa,GAAG,GAAG,IAAI,CAAC,CAAC;AAClF;AAEA,SAAS,iBACP,QACA,SACA,SACA,SACS;CACT,IAAI,EAAE,SAAS,SAAS,gBAAgB,OAAO,WAAW,CAAC,IACzD,OAAO;CAET,IAAI,SAAS,sBAAsB,QAAQ,OAAO,YAAY,MAAM,SAAS,qBAAqB,OAAO,GACvG,OAAO;CAET,MAAM,yBAAyB,SAAS;CACxC,OAAO,EACL,0BACA,aACE,cAAc,0DAA0D,UAClE,uBAAuB,SAAS,OAAO,SACvC,KACR;AAEJ;;;;;AAMA,SAAS,eACP,UACA,aACA,QACA,eACG;CACH,IAAI,eAAe,UAAU,QAAQ,CAAC,SAAS,KAAK,QAClD,IAAI;EAGF,OAAO,IAAI,SAAS,cAAc,SAAS,MAAM,QAAQ,aAAa,GAAG,QAAQ;CACnF,QAAQ,CAGR;CAEF,OAAO;CACP,OAAO;AACT;AAGA,SAAS,sBAAsB,SAAqD;CAClF,MAAM,OAA0C,sBAAsB,OAAO;CAC7E,MAAM,YAAY,OAAO,QAAQ,iBAAiB,aAAa,QAAQ,aAAa,IAAI,CAAC;CACzF,IAAI,UAAU,QACZ,KAAK,gBAAgB;CAEvB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"wrapServerRequestHandler.js","names":["isServedTunnelRequest"],"sources":["../../../src/utils/wrapServerRequestHandler.ts"],"sourcesContent":["import {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_REQUEST_BODY_SIZE,\n NETWORK_PROTOCOL_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport type { Client, Mechanism, Scope, SpanAttributes } from '@sentry/core';\nimport {\n captureBodyFromWinterCGRequest,\n captureException,\n continueTrace,\n getCurrentScope,\n getHttpSpanDetailsFromUrlObject,\n hasSpansEnabled,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n safeCallback,\n setHttpStatus,\n SPAN_STATUS_ERROR,\n startSpanManual,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type { ServerRequestOptions } from '@sentry/core/server';\nimport {\n _INTERNAL_isServedTunnelRequest as isServedTunnelRequest,\n classifyResponseStreaming,\n getClientIPAddress,\n isStaticAssetRequest,\n startRequestSession,\n} from '@sentry/core/server';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { monitorStream } from './monitorStream';\n\nexport interface ServerRequestHandlerConfig {\n request: Request;\n client: Client;\n /** The isolation scope of this request. */\n isolationScope: Scope;\n /** The options of the runtime's integration for incoming requests. */\n options: ServerRequestOptions<Request, Response> | undefined;\n /** Origin of the span, e.g. `auto.http.deno`. */\n origin: string;\n /** Mechanism of errors that the handler or the response stream throws. Omit to not capture them. */\n mechanism?: Mechanism;\n /** The address and port of the socket, if the runtime knows them. */\n getSocketAddress?: () => { address: string; port?: number } | undefined;\n /** The matched route of the server framework, e.g. `/users/:id`. Sets `http.route` and the span name. */\n routeName?: string;\n /** Span attributes that only the runtime knows, e.g. the route parameters. */\n attributes?: SpanAttributes;\n /**\n * Called in the scope of the continued trace, before the span starts. Lets the runtime continue\n * its own trace, e.g. the trace that Cloudflare exports for the invocation.\n */\n onTraceContinued?: () => void;\n /** Whether the response streams. Return `undefined` to use the default classification. */\n isStreamingResponse?: (response: Response) => boolean | undefined;\n /**\n * Called once when the request is done: when the response is returned, when a streamed body\n * finishes, or when the handler throws (then without a response).\n */\n onDone?: (response: Response | undefined) => void;\n}\n\n/**\n * Wraps a handler of a web `Request`, as used by `Deno.serve`, `Bun.serve` and Cloudflare Workers.\n *\n * It records the request session, attaches the request data and body, continues the incoming\n * trace, creates the `http.server` span, and captures errors that the handler throws. The rules\n * follow core's `node:http` server code:\n *\n * - `OPTIONS` and `HEAD` requests get no span and no body capture.\n * - The static asset filter applies only to `GET`.\n * - The span and the session of a streamed response end when the stream finishes.\n *\n * The handler can return no response, as Bun's `fetch` does after a WebSocket upgrade.\n */\nexport async function wrapServerRequestHandler<R extends Response | undefined = Response>(\n config: ServerRequestHandlerConfig,\n handler: () => R | Promise<R>,\n): Promise<R> {\n const { request, client, isolationScope, options, mechanism } = config;\n\n const method = request.method.toUpperCase();\n const captureError = (error: unknown): void => {\n if (mechanism) {\n captureException(error, { mechanism });\n }\n };\n\n const socketAddress = config.getSocketAddress?.();\n // Without `AsyncLocalStorage`, all requests share one isolation scope, so clear what an earlier\n // request left on it: the merge keeps its body, and its response context would stay set.\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: { ...winterCGRequestToRequestData(request), data: undefined },\n ipAddress: socketAddress?.address,\n });\n isolationScope.setContext('response', null);\n\n // Tunnel requests get no session, body or span, whether the SDK or the app answers them. The app answers them with\n // `intercept: false`, from its own code, so its errors are still captured.\n if (isServedTunnelRequest(request, client)) {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n config.onDone?.(response);\n }\n }\n\n const endSession = options?.sessions\n ? startRequestSession(client, {\n requestIsolationScope: isolationScope,\n sessionFlushingDelayMS: options.sessionFlushingDelayMS,\n })\n : undefined;\n const finish = (response: Response | undefined): void => {\n endSession?.();\n config.onDone?.(response);\n };\n const isStreamingResponse = (response: Response): boolean => {\n const classification = config.isStreamingResponse?.(response);\n return typeof classification === 'boolean' ? classification : classifyResponseStreaming(response).isStreaming;\n };\n\n if (method === 'OPTIONS' || method === 'HEAD') {\n let response: R | undefined;\n try {\n response = await handler();\n return response;\n } catch (e) {\n captureError(e);\n throw e;\n } finally {\n finish(response);\n }\n }\n\n const dataCollection = client.getDataCollectionOptions();\n const effectiveBodySize =\n options?.maxRequestBodySize ?? (dataCollection.httpBodies.includes('incomingRequest') ? 'medium' : 'none');\n const ignoreRequestBody = options?.ignoreRequestBody;\n if (\n method !== 'GET' &&\n effectiveBodySize !== 'none' &&\n // If the filter throws, skip the body so it cannot leak data the filter was meant to hide.\n !(\n ignoreRequestBody &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreRequestBody`, skipping the body:' : '',\n () => ignoreRequestBody(request.url, request),\n () => true,\n )\n )\n ) {\n await captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);\n }\n\n const urlObject = parseStringToURLObject(request.url);\n const urlPath = urlObject ? `${urlObject.pathname}${urlObject.search}` : '/';\n const createSpan = shouldCreateSpan(client, options, request, urlPath);\n\n return continueTrace(\n {\n sentryTrace: request.headers.get('sentry-trace') || '',\n baggage: request.headers.get('baggage'),\n },\n async () => {\n config.onTraceContinued?.();\n\n if (!createSpan) {\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n captureError(e);\n finish(undefined);\n throw e;\n }\n if (response) {\n isolationScope.setContext('response', { status_code: response.status });\n }\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => finish(response)),\n inRequestScope(captureError),\n );\n }\n\n const [rawName, attributes] = getHttpSpanDetailsFromUrlObject(\n urlObject,\n 'server',\n config.origin,\n request,\n config.routeName,\n client,\n );\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // A `route` source means the name already is (e.g. the `/` path), so it is kept as-is.\n const name =\n attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' || !hasSpanStreamingEnabled(client)\n ? rawName\n : method || HTTP_SPAN_NAME_FALLBACK;\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes[HTTP_REQUEST_BODY_SIZE] = parseInt(contentLength, 10);\n }\n const userAgent = request.headers.get('user-agent');\n if (userAgent) {\n attributes[USER_AGENT_ORIGINAL] = userAgent;\n }\n\n const headers = winterCGHeadersToDict(request.headers);\n if (dataCollection.userInfo) {\n // `client.address` is the originating client, so a forwarding header wins over the socket, which\n // behind a proxy holds the proxy's address. The socket port is the proxy's too, so `client.port`\n // stays unset then.\n const forwardedAddress = getClientIPAddress(headers);\n if (forwardedAddress) {\n attributes[CLIENT_ADDRESS] = forwardedAddress;\n } else if (socketAddress) {\n attributes[CLIENT_ADDRESS] = socketAddress.address;\n if (socketAddress.port !== undefined) {\n attributes[CLIENT_PORT] = socketAddress.port;\n }\n }\n }\n\n // describes the OSI application-layer protocol (http), not the scheme (might be https)\n attributes[NETWORK_PROTOCOL_NAME] = 'http';\n Object.assign(attributes, httpHeadersToSpanAttributes(headers, dataCollection));\n Object.assign(attributes, config.attributes);\n attributes[SENTRY_OP] = HTTP_SERVER;\n attributes[SENTRY_KIND] = 'server';\n\n return startSpanManual({ name, attributes }, async span => {\n const { onSpanCreated, onSpanEnd } = options ?? {};\n if (onSpanCreated) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanCreated`:' : '',\n () => onSpanCreated(span, request),\n () => undefined,\n );\n }\n\n let response: R;\n try {\n response = await handler();\n } catch (e) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n captureError(e);\n finish(undefined);\n throw e;\n }\n\n if (response) {\n setHttpStatus(span, response.status);\n isolationScope.setContext('response', { status_code: response.status });\n span.setAttributes(\n httpHeadersToSpanAttributes(responseHeadersToDict(response.headers), dataCollection, 'response'),\n );\n }\n\n const inRequestScope = bindToRequestScope(isolationScope);\n return onResponseDone(\n response,\n !!response && isStreamingResponse(response),\n inRequestScope(() => {\n if (onSpanEnd && response) {\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanEnd`:' : '',\n () => onSpanEnd(span, request, response),\n () => undefined,\n );\n }\n span.end();\n finish(response);\n }),\n inRequestScope((error: unknown) => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureError(error);\n }),\n );\n });\n },\n );\n}\n\n/**\n * Returns a function that binds a callback to the request's isolation scope and the current scope.\n *\n * A streamed body finishes after the handler returns. Without `AsyncLocalStorage` (Cloudflare\n * Workers without `nodejs_compat`), its callbacks then run outside the request's scopes, where\n * `getClient()` finds no client: the segment span would be sent as a transaction, and a captured\n * error would not update the request session.\n */\nfunction bindToRequestScope(\n isolationScope: Scope,\n): <A extends unknown[]>(fn: (...args: A) => void) => (...args: A) => void {\n const scope = getCurrentScope();\n return fn =>\n (...args) =>\n withIsolationScope(isolationScope, () => withScope(scope, () => fn(...args)));\n}\n\nfunction shouldCreateSpan(\n client: Client,\n options: ServerRequestOptions<Request, Response> | undefined,\n request: Request,\n urlPath: string,\n): boolean {\n if (!(options?.spans ?? hasSpansEnabled(client.getOptions()))) {\n return false;\n }\n if (options?.ignoreStaticAssets && request.method.toUpperCase() === 'GET' && isStaticAssetRequest(urlPath)) {\n return false;\n }\n const ignoreIncomingRequests = options?.ignoreIncomingRequests;\n return !(\n ignoreIncomingRequests &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreIncomingRequests`, creating the span:' : '',\n () => ignoreIncomingRequests(urlPath, request),\n () => false,\n )\n );\n}\n\n/**\n * Calls `onDone` when the response is done: at once, or when a streamed body finishes.\n * Returns the response to send.\n */\nfunction onResponseDone<R extends Response | undefined>(\n response: R,\n isStreaming: boolean,\n onDone: () => void,\n onStreamError: (error: unknown) => void,\n): R {\n if (isStreaming && response?.body && !response.body.locked) {\n try {\n // Passing the original response as the init keeps its status, status text and headers, and\n // on Cloudflare also `encodeBody: 'manual'`, so workerd does not compress a compressed body again.\n return new Response(monitorStream(response.body, onDone, onStreamError), response) as R;\n } catch {\n // Workers with a compatibility date before 2022-11-30 and without the\n // `streams_enable_constructors` flag cannot construct a `ReadableStream`, so end at once.\n }\n }\n onDone();\n return response;\n}\n\n// `Headers.forEach` lists each `Set-Cookie` header on its own, so a plain dict keeps only the last one.\nfunction responseHeadersToDict(headers: Headers): Record<string, string | string[]> {\n const dict: Record<string, string | string[]> = winterCGHeadersToDict(headers);\n const setCookie = typeof headers.getSetCookie === 'function' ? headers.getSetCookie() : [];\n if (setCookie.length) {\n dict['set-cookie'] = setCookie;\n }\n return dict;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuFA,eAAsB,yBACpB,QACA,SACY;CACZ,MAAM,EAAE,SAAS,QAAQ,gBAAgB,SAAS,cAAc;CAEhE,MAAM,SAAS,QAAQ,OAAO,YAAY;CAC1C,MAAM,gBAAgB,UAAyB;EAC7C,IAAI,WACF,iBAAiB,OAAO,EAAE,UAAU,CAAC;CAEzC;CAEA,MAAM,gBAAgB,OAAO,mBAAmB;CAGhD,eAAe,yBAAyB;EACtC,mBAAmB;GAAE,GAAG,6BAA6B,OAAO;GAAG,MAAM,KAAA;EAAU;EAC/E,WAAW,eAAe;CAC5B,CAAC;CACD,eAAe,WAAW,YAAY,IAAI;CAI1C,IAAIA,gCAAsB,SAAS,MAAM,GAAG;EAC1C,IAAI;EACJ,IAAI;GACF,WAAW,MAAM,QAAQ;GACzB,OAAO;EACT,SAAS,GAAG;GACV,aAAa,CAAC;GACd,MAAM;EACR,UAAU;GACR,OAAO,SAAS,QAAQ;EAC1B;CACF;CAEA,MAAM,aAAa,SAAS,WACxB,oBAAoB,QAAQ;EAC1B,uBAAuB;EACvB,wBAAwB,QAAQ;CAClC,CAAC,IACD,KAAA;CACJ,MAAM,UAAU,aAAyC;EACvD,aAAa;EACb,OAAO,SAAS,QAAQ;CAC1B;CACA,MAAM,uBAAuB,aAAgC;EAC3D,MAAM,iBAAiB,OAAO,sBAAsB,QAAQ;EAC5D,OAAO,OAAO,mBAAmB,YAAY,iBAAiB,0BAA0B,QAAQ,CAAC,CAAC;CACpG;CAEA,IAAI,WAAW,aAAa,WAAW,QAAQ;EAC7C,IAAI;EACJ,IAAI;GACF,WAAW,MAAM,QAAQ;GACz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AAE,WAAW,GAAG,IAAI,CAqBtF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decisions.d.ts","sourceRoot":"","sources":["../../../../src/ai/google-genai/decisions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"decisions.d.ts","sourceRoot":"","sources":["../../../../src/ai/google-genai/decisions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAKzC;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,GAAG,SAAS,CAE5F;AAwBD,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,aAAa,EAAE,OAAO,GAAG,IAAI,CAqBzG"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import type { SpanAttributeValue } from '@sentry/core';
|
|
2
|
-
import type { LangChainOptions } from './types';
|
|
2
|
+
import type { LangChainEmbeddingsCallInfo, LangChainOptions } from './types';
|
|
3
3
|
/**
|
|
4
4
|
* Builds the span options for a LangChain embedding call from the embeddings instance and input.
|
|
5
5
|
*
|
|
6
6
|
* @internal Exported so the diagnostics-channel (orchestrion) instrumentation can build the same
|
|
7
7
|
* span as the prototype-patching path below.
|
|
8
8
|
*/
|
|
9
|
-
export declare function _INTERNAL_getLangChainEmbeddingsSpanOptions(instance: unknown,
|
|
9
|
+
export declare function _INTERNAL_getLangChainEmbeddingsSpanOptions(instance: unknown, call: LangChainEmbeddingsCallInfo, options?: LangChainOptions): {
|
|
10
10
|
name: string;
|
|
11
11
|
attributes: Record<string, SpanAttributeValue>;
|
|
12
12
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"embeddings.d.ts","sourceRoot":"","sources":["../../../../src/ai/langchain/embeddings.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"embeddings.d.ts","sourceRoot":"","sources":["../../../../src/ai/langchain/embeddings.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAiBvD,OAAO,KAAK,EAAE,2BAA2B,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AA0C7E;;;;;GAKG;AACH,wBAAgB,2CAA2C,CACzD,QAAQ,EAAE,OAAO,EACjB,IAAI,EAAE,2BAA2B,EACjC,OAAO,GAAE,gBAAqB,GAC7B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAA;CAAE,CAmBlE;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,CACvC,cAAc,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,EACxD,OAAO,GAAE,gBAAqB,GAC7B,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAmB1C;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,6BAA6B,CAAC,CAAC,SAAS,MAAM,EAAE,QAAQ,EAAE,CAAC,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,CAAC,CAkB1G"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/ai/langchain/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/ai/langchain/index.ts"],"names":[],"mappings":"AAyCA,OAAO,KAAK,EACV,wBAAwB,EAIxB,gBAAgB,EAEjB,MAAM,SAAS,CAAC;AAwBjB;;;;;GAKG;AACH,wBAAgB,8BAA8B,CAAC,OAAO,GAAE,gBAAqB,GAAG,wBAAwB,CAydvG;AAED,OAAO,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { GenAiSpanHooks } from '../core/span-hooks';
|
|
1
2
|
import type { GenAiCallOptions } from '../core/utils';
|
|
2
3
|
/** What LangChain passes to every start callback of a run, besides the component's input. */
|
|
3
4
|
interface LangChainRunCallInfo {
|
|
@@ -31,21 +32,24 @@ interface LangChainToolCallInfo extends LangChainRunCallInfo {
|
|
|
31
32
|
input: string;
|
|
32
33
|
}
|
|
33
34
|
/** `embedQuery`/`embedDocuments` */
|
|
34
|
-
interface LangChainEmbeddingsCallInfo {
|
|
35
|
+
export interface LangChainEmbeddingsCallInfo {
|
|
35
36
|
operation: 'embeddings';
|
|
36
37
|
input: unknown;
|
|
37
38
|
}
|
|
38
39
|
/**
|
|
39
|
-
* The call that `recordInputs`/`recordOutputs` decide on: the gen_ai operation and the
|
|
40
|
-
* start callback as passed, or the argument of `embedQuery`/`embedDocuments`.
|
|
40
|
+
* The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get: the gen_ai operation and the
|
|
41
|
+
* arguments of the LangChain start callback as passed, or the argument of `embedQuery`/`embedDocuments`.
|
|
41
42
|
*/
|
|
42
43
|
export type LangChainCallInfo = LangChainChatModelCallInfo | LangChainLLMCallInfo | LangChainChainCallInfo | LangChainToolCallInfo | LangChainEmbeddingsCallInfo;
|
|
43
44
|
/**
|
|
44
45
|
* Options for the LangChain integration. The handler decides in each start callback, which LangChain awaits
|
|
45
46
|
* inline in the async context of the call that started the run. Runs inside a LangGraph graph use the
|
|
46
47
|
* decision of the graph's `invoke()`/`stream()` call instead.
|
|
48
|
+
*
|
|
49
|
+
* `onSpanEnd` gets the output of the run's end callback as LangChain passed it, such as the `LLMResult` of a
|
|
50
|
+
* chat model or the output of a tool, or the vectors that `embedQuery`/`embedDocuments` resolved with.
|
|
47
51
|
*/
|
|
48
|
-
export type LangChainOptions = GenAiCallOptions<LangChainCallInfo>;
|
|
52
|
+
export type LangChainOptions = GenAiCallOptions<LangChainCallInfo> & GenAiSpanHooks<LangChainCallInfo>;
|
|
49
53
|
/**
|
|
50
54
|
* LangChain Serialized type (compatible with @langchain/core)
|
|
51
55
|
* Uses general types to be compatible with LangChain's Serialized interface.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/ai/langchain/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEtD,6FAA6F;AAC7F,UAAU,oBAAoB;IAC5B,wFAAwF;IACxF,UAAU,EAAE,mBAAmB,CAAC;IAChC,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC;AAED,6BAA6B;AAC7B,UAAU,0BAA2B,SAAQ,oBAAoB;IAC/D,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,gBAAgB,EAAE,EAAE,CAAC;IAC/B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED,uBAAuB;AACvB,UAAU,oBAAqB,SAAQ,oBAAoB;IACzD,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAED,yBAAyB;AACzB,UAAU,sBAAuB,SAAQ,oBAAoB;IAC3D,SAAS,EAAE,cAAc,GAAG,QAAQ,CAAC;IACrC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AAED,wBAAwB;AACxB,UAAU,qBAAsB,SAAQ,oBAAoB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O,CAAC,CAAA;KAAE,KAC1C,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IAChC,eAAe,CAAC,EAAE,CAChB,IAAI,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,EACvB,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,WAAW,CAAC,EAAE,MAAM,EACpB,IAAI,CAAC,EAAE,MAAM,EAAE,EACf,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClC,OAAO,CAAC,EAAE,MAAM,KACb,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IAChC,aAAa,CAAC,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IACtH,eAAe,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IAGrH,IAAI,IAAI,OAAO,CAAC;IAChB,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,oBAAoB,IAAI,OAAO,CAAC;CACjC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Span, SpanAttributes } from '@sentry/core';
|
|
2
2
|
import type { GenAiOptions } from '../core/utils';
|
|
3
3
|
import type { BaseChatModel, LangChainMessage } from '../langchain/types';
|
|
4
|
-
import type { CompiledGraph, LangGraphOptions } from './types';
|
|
4
|
+
import type { CompiledGraph, LangGraphCallInfo, LangGraphOptions } from './types';
|
|
5
5
|
/** Runs the original invoke() of `graph`, so its internal stream() call can be recognised. */
|
|
6
6
|
export declare function callInvoke<T>(graph: object, invoke: () => T): T;
|
|
7
7
|
/** Whether this stream() call on `graph` is the one its invoke() makes internally. */
|
|
@@ -12,7 +12,10 @@ export declare function getAgentSpanOptions(args: unknown[], extraAttributes?: S
|
|
|
12
12
|
attributes: SpanAttributes;
|
|
13
13
|
};
|
|
14
14
|
/** Decides for one `invoke()`/`stream()` call, from its arguments as passed. */
|
|
15
|
-
export declare function resolveGraphCallRecording(options: LangGraphOptions, args: unknown[]):
|
|
15
|
+
export declare function resolveGraphCallRecording(options: LangGraphOptions, args: unknown[]): {
|
|
16
|
+
call: LangGraphCallInfo;
|
|
17
|
+
recording: Required<GenAiOptions>;
|
|
18
|
+
};
|
|
16
19
|
/** Sets the request attributes on an agent span and injects the callback handler into the call's config. */
|
|
17
20
|
export declare function prepareAgentSpan(span: Span, args: unknown[], graphInstance: CompiledGraph, compileOptions: Record<string, unknown>, recording: Required<GenAiOptions>, llm: BaseChatModel | null | undefined, sentryCallbackHandler: unknown): LangChainMessage[] | null;
|
|
18
21
|
//# sourceMappingURL=agent-span.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-span.d.ts","sourceRoot":"","sources":["../../../../src/ai/langgraph/agent-span.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAczD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAS1E,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-span.d.ts","sourceRoot":"","sources":["../../../../src/ai/langgraph/agent-span.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAczD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAS1E,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAOlF,8FAA8F;AAC9F,wBAAgB,UAAU,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,CAQ/D;AAED,sFAAsF;AACtF,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAE7D;AAED,4EAA4E;AAC5E,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,OAAO,EAAE,EACf,eAAe,CAAC,EAAE,cAAc,GAC/B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,cAAc,CAAA;CAAE,CAa9C;AAED,gFAAgF;AAChF,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,gBAAgB,EACzB,IAAI,EAAE,OAAO,EAAE,GACd;IAAE,IAAI,EAAE,iBAAiB,CAAC;IAAC,SAAS,EAAE,QAAQ,CAAC,YAAY,CAAC,CAAA;CAAE,CAOhE;AAED,4GAA4G;AAC5G,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,IAAI,EACV,IAAI,EAAE,OAAO,EAAE,EACf,aAAa,EAAE,aAAa,EAC5B,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACvC,SAAS,EAAE,QAAQ,CAAC,YAAY,CAAC,EACjC,GAAG,EAAE,aAAa,GAAG,IAAI,GAAG,SAAS,EACrC,qBAAqB,EAAE,OAAO,GAC7B,gBAAgB,EAAE,GAAG,IAAI,CAqE3B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/ai/langgraph/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../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;;;;;;;;;;;;;;;;GAsBG;AAEH,wBAAgB,oBAAoB,CAAC,CAAC,SAAS;IAAE,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAA;CAAE,EACjF,UAAU,EAAE,CAAC,EACb,OAAO,GAAE,gBAAqB,GAC7B,CAAC,CAIH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../../../src/ai/langgraph/stream.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../../../src/ai/langgraph/stream.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAoB,MAAM,oBAAoB,CAAC;AAG1E,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAG/D;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAC3C,cAAc,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,EACxD,aAAa,EAAE,aAAa,EAC5B,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACvC,OAAO,EAAE,gBAAgB,EACzB,GAAG,CAAC,EAAE,aAAa,GAAG,IAAI,EAC1B,qBAAqB,CAAC,EAAE,OAAO,GAC9B,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CA6F1C"}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
import type { GenAiSpanHooks } from '../core/span-hooks';
|
|
1
2
|
import type { GenAiCallOptions } from '../core/utils';
|
|
2
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* The call that `recordInputs`/`recordOutputs` decide on, and that the span hooks get: an `invoke()` or `stream()`
|
|
5
|
+
* call of a compiled graph.
|
|
6
|
+
*/
|
|
3
7
|
export interface LangGraphCallInfo {
|
|
4
8
|
operation: 'invoke_agent';
|
|
5
9
|
/** The graph input, the first argument of `invoke()`/`stream()` as passed. */
|
|
@@ -10,8 +14,12 @@ export interface LangGraphCallInfo {
|
|
|
10
14
|
/**
|
|
11
15
|
* Options for the LangGraph integration. Each `invoke()`/`stream()` call decides once, and the decision covers the
|
|
12
16
|
* whole graph run, including its chat model and tool spans.
|
|
17
|
+
*
|
|
18
|
+
* The span hooks only run for the `invoke_agent` span of the call. `onSpanEnd` gets the final graph state: what
|
|
19
|
+
* `invoke()` resolved with, or the output of the run for `stream()`, which is `undefined` when the caller stopped
|
|
20
|
+
* reading early.
|
|
13
21
|
*/
|
|
14
|
-
export type LangGraphOptions = GenAiCallOptions<LangGraphCallInfo>;
|
|
22
|
+
export type LangGraphOptions = GenAiCallOptions<LangGraphCallInfo> & GenAiSpanHooks<LangGraphCallInfo>;
|
|
15
23
|
/**
|
|
16
24
|
* LangGraph Tool definition from lc_kwargs
|
|
17
25
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/ai/langgraph/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEtD
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/ai/langgraph/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEtD;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,SAAS,EAAE,cAAc,CAAC;IAC1B,8EAA8E;IAC9E,KAAK,EAAE,OAAO,CAAC;IACf,8EAA8E;IAC9E,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAAC;CAC7C;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,gBAAgB,GAAG,gBAAgB,CAAC,iB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AE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IAClD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE;QACV,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,EAAE,MAAM,CAAC;KACf,CAAC;IACF,OAAO,CAAC,EAAE,iBAAiB,CAAC;CAC7B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mapping.d.ts","sourceRoot":"","sources":["../../../../src/ai/openai/mapping.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"mapping.d.ts","sourceRoot":"","sources":["../../../../src/ai/openai/mapping.ts"],"names":[],"mappings":"AAQA;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,GAAG,SAAS,CAG5F;AA6CD,0FAA0F;AAC1F,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,MAAM,GAAG,SAAS,CAEhF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/ai/pi-durable/index.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEtD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAKzD,OAAO,KAAK,EACV,iBAAiB,EAEjB,gBAAgB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/ai/pi-durable/index.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEtD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAKzD,OAAO,KAAK,EACV,iBAAiB,EAEjB,gBAAgB,EAQhB,qBAAqB,EACtB,MAAM,SAAS,CAAC;AAIjB;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,GAAG,gBAAgB,CAAC,iBAAiB,CAAC,GAChE,cAAc,CAAC,iBAAiB,EAAE,kBAAkB,GAAG,qBAAqB,CAAC,CAAC;AAKhF;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,iCAAiC,CAAC,CAAC,SAAS,gBAAgB,EAC1E,cAAc,EAAE,CAAC,EACjB,OAAO,GAAE,gBAAqB,GAC7B,CAAC,CAmBH;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,cAAc,EAAE,gBAAgB,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CAsBvF"}
|