@sentry/server-utils 11.20.0 → 11.22.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 +30 -0
- package/build/cjs/chunks/config.js.map +1 -1
- package/build/cjs/chunks/exports.js +10 -1
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/index.js +381 -16
- package/build/cjs/index.js.map +1 -1
- package/build/esm/ai/tanstack-ai/constants.js +11 -0
- package/build/esm/ai/tanstack-ai/constants.js.map +1 -0
- package/build/esm/ai/tanstack-ai/index.js +206 -0
- package/build/esm/ai/tanstack-ai/index.js.map +1 -0
- package/build/esm/ai/tanstack-ai/utils.js +81 -0
- package/build/esm/ai/tanstack-ai/utils.js.map +1 -0
- package/build/esm/ai/workers-ai/utils.js +4 -1
- package/build/esm/ai/workers-ai/utils.js.map +1 -1
- package/build/esm/index.js +2 -1
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/fastify/instrumentation.js +5 -1
- package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
- package/build/esm/integrations/neon.js +10 -2
- package/build/esm/integrations/neon.js.map +1 -1
- package/build/esm/integrations/pg.js +41 -14
- package/build/esm/integrations/pg.js.map +1 -1
- package/build/esm/integrations/pino.js.map +1 -1
- package/build/esm/integrations/tanstack-ai.js +59 -0
- package/build/esm/integrations/tanstack-ai.js.map +1 -0
- package/build/esm/integrations/vercel-ai/extract.js +2 -3
- package/build/esm/integrations/vercel-ai/extract.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/index.js +2 -0
- package/build/esm/orchestrion/config/index.js.map +1 -1
- package/build/esm/orchestrion/config/prisma.js +2 -0
- package/build/esm/orchestrion/config/prisma.js.map +1 -1
- package/build/esm/orchestrion/config/tanstack-ai.js +19 -0
- package/build/esm/orchestrion/config/tanstack-ai.js.map +1 -0
- package/build/esm/package.json +1 -1
- package/build/esm/tracing-channel.js.map +1 -1
- package/build/types/ai/tanstack-ai/constants.d.ts +8 -0
- package/build/types/ai/tanstack-ai/constants.d.ts.map +1 -0
- package/build/types/ai/tanstack-ai/index.d.ts +18 -0
- package/build/types/ai/tanstack-ai/index.d.ts.map +1 -0
- package/build/types/ai/tanstack-ai/types.d.ts +127 -0
- package/build/types/ai/tanstack-ai/types.d.ts.map +1 -0
- package/build/types/ai/tanstack-ai/utils.d.ts +21 -0
- package/build/types/ai/tanstack-ai/utils.d.ts.map +1 -0
- package/build/types/ai/workers-ai/utils.d.ts.map +1 -1
- package/build/types/index.d.ts +2 -0
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/neon.d.ts.map +1 -1
- package/build/types/integrations/pg.d.ts +6 -1
- package/build/types/integrations/pg.d.ts.map +1 -1
- package/build/types/integrations/pino.d.ts.map +1 -1
- package/build/types/integrations/tanstack-ai.d.ts +18 -0
- package/build/types/integrations/tanstack-ai.d.ts.map +1 -0
- package/build/types/integrations/vercel-ai/extract.d.ts +2 -5
- package/build/types/integrations/vercel-ai/extract.d.ts.map +1 -1
- package/build/types/orchestrion/channels.d.ts +2 -0
- package/build/types/orchestrion/channels.d.ts.map +1 -1
- package/build/types/orchestrion/config/index.d.ts.map +1 -1
- package/build/types/orchestrion/config/prisma.d.ts +2 -1
- package/build/types/orchestrion/config/prisma.d.ts.map +1 -1
- package/build/types/orchestrion/config/tanstack-ai.d.ts +17 -0
- package/build/types/orchestrion/config/tanstack-ai.d.ts.map +1 -0
- package/build/types/tracing-channel.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -4,7 +4,7 @@ import { CHANNELS } from "../orchestrion/channels.js";
|
|
|
4
4
|
import { neonModuleNames } from "../orchestrion/config/neon.js";
|
|
5
5
|
import { invokeOrchestrionInstrumentation } from "../orchestrion/instrumentation.js";
|
|
6
6
|
import { bindTracingChannelToSpan } from "../tracing-channel.js";
|
|
7
|
-
import { bindPgQueryChannel, getConnectionAttributes } from "./pg.js";
|
|
7
|
+
import { bindPgQueryChannel, getConnectionAttributes, setReturnedRows } from "./pg.js";
|
|
8
8
|
import { DB_OPERATION_BATCH_SIZE, DB_OPERATION_NAME, DB_QUERY_SUMMARY, DB_QUERY_TEXT, DB_SYSTEM_NAME, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
9
9
|
import { defineIntegration, getActiveSpan, startInactiveSpan } from "@sentry/core";
|
|
10
10
|
import { DB } from "@sentry/conventions/op";
|
|
@@ -29,7 +29,12 @@ function instrumentNeon() {
|
|
|
29
29
|
const span = startInactiveSpan(httpQuerySpanOptions(data.arguments));
|
|
30
30
|
httpQuerySpans.add(span);
|
|
31
31
|
return span;
|
|
32
|
-
})
|
|
32
|
+
}, { beforeSpanEnd(span, data) {
|
|
33
|
+
if ("error" in data) return;
|
|
34
|
+
const { result } = data;
|
|
35
|
+
const isBatch = Array.isArray(data.arguments[0]);
|
|
36
|
+
setReturnedRows(span, isBatch && Array.isArray(result) ? result.map(toPgResult) : toPgResult(result));
|
|
37
|
+
} });
|
|
33
38
|
tracingChannel(CHANNELS.NEON_RESOLVE_CONNECTION).subscribe({
|
|
34
39
|
start: NOOP,
|
|
35
40
|
end: NOOP,
|
|
@@ -71,6 +76,9 @@ function httpQuerySpanOptions(args) {
|
|
|
71
76
|
attributes
|
|
72
77
|
};
|
|
73
78
|
}
|
|
79
|
+
function toPgResult(result) {
|
|
80
|
+
return Array.isArray(result) ? { rows: result } : result;
|
|
81
|
+
}
|
|
74
82
|
function getBatchOperationName(statements) {
|
|
75
83
|
const operations = new Set(statements.map((s) => s[DB_OPERATION_NAME]?.toUpperCase()));
|
|
76
84
|
const [operation] = operations;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"neon.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/neon.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport {\n DB_OPERATION_BATCH_SIZE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { IntegrationFn, Span, SpanAttributes } from '@sentry/core';\nimport { defineIntegration, getActiveSpan, startInactiveSpan } from '@sentry/core';\nimport { getLowCardinalitySqlSpanName, getSqlQueryAttributes } from '../utils/sql';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { neonModuleNames } from '../orchestrion/config/neon';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { bindPgQueryChannel, getConnectionAttributes } from './pg';\n\nconst INTEGRATION_NAME = 'Neon' as const;\nconst ORIGIN = 'auto.db.neon';\nconst DB_SYSTEM_POSTGRESQL = 'postgresql';\nconst DEFAULT_PORT = 5432;\nconst NOOP = (): void => {};\n\n// `sql.query(text, params)` builds the first shape, a tagged-template call the second.\ntype NeonQueryData = { query: string; params?: unknown[] } | NeonSqlTemplate;\n\ninterface NeonSqlTemplate {\n strings: readonly string[];\n values: unknown[];\n toParameterizedQuery?: () => { query: string };\n}\n\ninterface NeonHttpQueryContext {\n // `[queryData, opts]` for a single query, `[queryData[], opts[]]` for a `transaction()` batch.\n arguments: unknown[];\n}\n\ninterface NeonResolveConnectionContext {\n result?: { resolvedURL?: URL };\n}\n\n// The HTTP query spans this integration started, so the connection-resolver subscriber only\n// enriches those and never a user's own active span.\nconst httpQuerySpans = new WeakSet<Span>();\n\nconst _neonIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, neonModuleNames, instrumentNeon, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentNeon(): void {\n // The WebSocket driver is pg's `Client`, bundled into the package, so its query channel gets\n // the pg span shape.\n bindPgQueryChannel(CHANNELS.NEON_QUERY, { origin: ORIGIN });\n\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<NeonHttpQueryContext>(CHANNELS.NEON_HTTP_QUERY)
|
|
1
|
+
{"version":3,"file":"neon.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/neon.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport {\n DB_OPERATION_BATCH_SIZE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { IntegrationFn, Span, SpanAttributes } from '@sentry/core';\nimport { defineIntegration, getActiveSpan, startInactiveSpan } from '@sentry/core';\nimport { getLowCardinalitySqlSpanName, getSqlQueryAttributes } from '../utils/sql';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { neonModuleNames } from '../orchestrion/config/neon';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { bindPgQueryChannel, getConnectionAttributes, setReturnedRows } from './pg';\n\nconst INTEGRATION_NAME = 'Neon' as const;\nconst ORIGIN = 'auto.db.neon';\nconst DB_SYSTEM_POSTGRESQL = 'postgresql';\nconst DEFAULT_PORT = 5432;\nconst NOOP = (): void => {};\n\n// `sql.query(text, params)` builds the first shape, a tagged-template call the second.\ntype NeonQueryData = { query: string; params?: unknown[] } | NeonSqlTemplate;\n\ninterface NeonSqlTemplate {\n strings: readonly string[];\n values: unknown[];\n toParameterizedQuery?: () => { query: string };\n}\n\ninterface NeonHttpQueryContext {\n // `[queryData, opts]` for a single query, `[queryData[], opts[]]` for a `transaction()` batch.\n arguments: unknown[];\n // Per statement: the rows array, or `{ rowCount, rows, ... }` with `fullResults`. A batch resolves to an array of these.\n result?: unknown;\n}\n\ninterface NeonResolveConnectionContext {\n result?: { resolvedURL?: URL };\n}\n\n// The HTTP query spans this integration started, so the connection-resolver subscriber only\n// enriches those and never a user's own active span.\nconst httpQuerySpans = new WeakSet<Span>();\n\nconst _neonIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, neonModuleNames, instrumentNeon, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentNeon(): void {\n // The WebSocket driver is pg's `Client`, bundled into the package, so its query channel gets\n // the pg span shape.\n bindPgQueryChannel(CHANNELS.NEON_QUERY, { origin: ORIGIN });\n\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<NeonHttpQueryContext>(CHANNELS.NEON_HTTP_QUERY),\n data => {\n const span = startInactiveSpan(httpQuerySpanOptions(data.arguments));\n httpQuerySpans.add(span);\n return span;\n },\n {\n beforeSpanEnd(span, data) {\n if ('error' in data) {\n return;\n }\n const { result } = data;\n const isBatch = Array.isArray(data.arguments[0]);\n setReturnedRows(span, isBatch && Array.isArray(result) ? result.map(toPgResult) : toPgResult(result));\n },\n },\n );\n\n // The connection string is resolved inside the HTTP executor, so the query span is active\n // when this settles. The executor's own context never sees the string.\n diagnosticsChannel.tracingChannel<NeonResolveConnectionContext>(CHANNELS.NEON_RESOLVE_CONNECTION).subscribe({\n start: NOOP,\n end: NOOP,\n asyncStart: NOOP,\n error: NOOP,\n asyncEnd(data) {\n const span = getActiveSpan();\n const url = data.result?.resolvedURL;\n if (!span || !httpQuerySpans.has(span) || !url) {\n return;\n }\n span.setAttributes(\n getConnectionAttributes({\n host: url.hostname,\n port: Number(url.port) || DEFAULT_PORT,\n database: url.pathname.slice(1),\n user: url.username || undefined,\n }),\n );\n },\n });\n}\n\nfunction httpQuerySpanOptions(args: unknown[]): Parameters<typeof startInactiveSpan>[0] {\n const queryData = args[0] as NeonQueryData | NeonQueryData[] | undefined;\n const batchSize = Array.isArray(queryData) ? queryData.length : undefined;\n // A batch gets one span whose text and summary list every statement, in order.\n const statements = (Array.isArray(queryData) ? queryData : [queryData])\n .map(getQueryText)\n .filter((text): text is string => !!text)\n .map(text => getSqlQueryAttributes(text));\n const queryText = joinDefined(statements.map(s => s[DB_QUERY_TEXT]));\n const querySummary = joinDefined(statements.map(s => s[DB_QUERY_SUMMARY]));\n const operationName =\n batchSize === undefined ? statements[0]?.[DB_OPERATION_NAME] : getBatchOperationName(statements);\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_KIND]: 'client',\n [DB_SYSTEM_NAME]: DB_SYSTEM_POSTGRESQL,\n [DB_QUERY_TEXT]: queryText || undefined,\n [DB_QUERY_SUMMARY]: querySummary,\n [DB_OPERATION_NAME]: operationName,\n [DB_OPERATION_BATCH_SIZE]: batchSize,\n };\n\n return { name: getLowCardinalitySqlSpanName(attributes, DB_SYSTEM_POSTGRESQL), onlyIfParent: true, attributes };\n}\n\nfunction toPgResult(result: unknown): unknown {\n return Array.isArray(result) ? { rows: result } : result;\n}\n\n// OTel names a batch `BATCH <op>` when every statement shares one operation, plain `BATCH` otherwise.\nfunction getBatchOperationName(statements: ReturnType<typeof getSqlQueryAttributes>[]): string {\n const operations = new Set(statements.map(s => s[DB_OPERATION_NAME]?.toUpperCase()));\n const [operation] = operations;\n return operations.size === 1 && operation ? `BATCH ${operation}` : 'BATCH';\n}\n\nfunction joinDefined(parts: (string | undefined)[]): string | undefined {\n const defined = parts.filter((part): part is string => !!part);\n return defined.length ? defined.join('; ') : undefined;\n}\n\nfunction getQueryText(data: NeonQueryData | undefined): string | undefined {\n if (!data || typeof data !== 'object') {\n return undefined;\n }\n if ('query' in data && typeof data.query === 'string') {\n return data.query;\n }\n if (!('strings' in data) || !Array.isArray(data.strings)) {\n return undefined;\n }\n if (typeof data.toParameterizedQuery === 'function') {\n try {\n // Neon's own rendering also inlines `sql.unsafe()` fragments and nested templates.\n return data.toParameterizedQuery().query;\n } catch {\n // fall through to the plain placeholder rendering\n }\n }\n return data.strings.reduce((text, part, i) => `${text}$${i}${part}`);\n}\n\n/**\n * Diagnostics-channel-based `@neondatabase/serverless` integration.\n *\n * Subscribes to the channels Sentry's code transform injects into the package's bundled pg\n * `Client.prototype.query` (WebSocket driver) and into the HTTP executor behind `neon()`, so both\n * drivers emit `db` spans with the same shape as the `pg` integration. Requires the Sentry runtime\n * hook or bundler plugin to be active.\n */\nexport const neonIntegration = defineIntegration(_neonIntegration);\n"],"mappings":";;;;;;;;;;;AAqBA,MAAM,mBAAmB;AACzB,MAAM,SAAS;AACf,MAAM,uBAAuB;AAC7B,MAAM,eAAe;AACrB,MAAM,aAAmB,CAAC;AAwB1B,MAAM,iCAAiB,IAAI,QAAc;AAEzC,MAAM,0BAA0B;CAC9B,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,iBAAiB,gBAAgB,CAAC,CAAC;EAC9E;CACF;AACF;AAEA,SAAS,iBAAuB;CAG9B,mBAAmB,SAAS,YAAY,EAAE,QAAQ,OAAO,CAAC;CAE1D,yBACEA,eAAwD,SAAS,eAAe,IAChF,SAAQ;EACN,MAAM,OAAO,kBAAkB,qBAAqB,KAAK,SAAS,CAAC;EACnE,eAAe,IAAI,IAAI;EACvB,OAAO;CACT,GACA,EACE,cAAc,MAAM,MAAM;EACxB,IAAI,WAAW,MACb;EAEF,MAAM,EAAE,WAAW;EACnB,MAAM,UAAU,MAAM,QAAQ,KAAK,UAAU,EAAE;EAC/C,gBAAgB,MAAM,WAAW,MAAM,QAAQ,MAAM,IAAI,OAAO,IAAI,UAAU,IAAI,WAAW,MAAM,CAAC;CACtG,EACF,CACF;CAIAA,eAAgE,SAAS,uBAAuB,CAAC,CAAC,UAAU;EAC1G,OAAO;EACP,KAAK;EACL,YAAY;EACZ,OAAO;EACP,SAAS,MAAM;GACb,MAAM,OAAO,cAAc;GAC3B,MAAM,MAAM,KAAK,QAAQ;GACzB,IAAI,C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cAAc;AACrE;AAEA,SAAS,YAAY,OAAmD;CACtE,MAAM,UAAU,MAAM,QAAQ,SAAyB,CAAC,CAAC,IAAI;CAC7D,OAAO,QAAQ,SAAS,QAAQ,KAAK,IAAI,IAAI,KAAA;AAC/C;AAEA,SAAS,aAAa,MAAqD;CACzE,IAAI,CAAC,QAAQ,OAAO,SAAS,UAC3B;CAEF,IAAI,WAAW,QAAQ,OAAO,KAAK,UAAU,UAC3C,OAAO,KAAK;CAEd,IAAI,EAAE,aAAa,SAAS,CAAC,MAAM,QAAQ,KAAK,OAAO,GACrD;CAEF,IAAI,OAAO,KAAK,yBAAyB,YACvC,IAAI;EAEF,OAAO,KAAK,qBAAqB,CAAC,CAAC;CACrC,QAAQ,CAER;CAEF,OAAO,KAAK,QAAQ,QAAQ,MAAM,MAAM,MAAM,GAAG,KAAK,GAAG,IAAI,MAAM;AACrE;;;;;;;;;AAUA,MAAa,kBAAkB,kBAAkB,gBAAgB"}
|
|
@@ -4,7 +4,7 @@ import { CHANNELS } from "../orchestrion/channels.js";
|
|
|
4
4
|
import { bindTracingChannelToSpan } from "../tracing-channel.js";
|
|
5
5
|
import { pgModuleNames } from "../orchestrion/config/pg.js";
|
|
6
6
|
import { invokeOrchestrionInstrumentation } from "../orchestrion/instrumentation.js";
|
|
7
|
-
import { DB_CONNECTION_STRING, DB_NAMESPACE, DB_SYSTEM_NAME, DB_USER, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SERVER_ADDRESS, SERVER_PORT } from "@sentry/conventions/attributes";
|
|
7
|
+
import { DB_CONNECTION_STRING, DB_NAMESPACE, DB_RESPONSE_RETURNED_ROWS, DB_SYSTEM_NAME, DB_USER, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SERVER_ADDRESS, SERVER_PORT } from "@sentry/conventions/attributes";
|
|
8
8
|
import { bindScopeToEmitter, defineIntegration, getCurrentScope, isObjectLike, startInactiveSpan } from "@sentry/core";
|
|
9
9
|
import { DB } from "@sentry/conventions/op";
|
|
10
10
|
// src/integrations/pg.ts
|
|
@@ -41,15 +41,16 @@ function instrumentPostgres(options) {
|
|
|
41
41
|
* streamable `Submittable` result, so it's the only one that defers span-ending to the emitter.
|
|
42
42
|
*/
|
|
43
43
|
function bindPgQueryChannel(channelName, options) {
|
|
44
|
-
subscribeQueryLikeChannel(channelName, (ctx) => querySpanOptions(ctx, options), {
|
|
44
|
+
subscribeQueryLikeChannel(channelName, (ctx) => querySpanOptions(ctx, options), { isQuery: true });
|
|
45
45
|
}
|
|
46
46
|
/**
|
|
47
47
|
* Subscribe to a pg tracing-channel and manage a span across its lifecycle.
|
|
48
48
|
* Shared by the query/connect/pool-connect channels. They differ only in how
|
|
49
49
|
* the span's name + attributes are built (`getSpanOptions`), and whether the
|
|
50
|
-
* result can be a streamable emitter
|
|
50
|
+
* result is a query result that can be a streamable emitter and carries a row
|
|
51
|
+
* count (`isQuery`).
|
|
51
52
|
*/
|
|
52
|
-
function subscribeQueryLikeChannel(channelName, getSpanOptions, {
|
|
53
|
+
function subscribeQueryLikeChannel(channelName, getSpanOptions, { isQuery = false } = {}) {
|
|
53
54
|
bindTracingChannelToSpan(tracingChannel(channelName), (data) => {
|
|
54
55
|
data._sentryCallerScope = getCurrentScope();
|
|
55
56
|
const spanOptions = getSpanOptions(data);
|
|
@@ -61,15 +62,24 @@ function subscribeQueryLikeChannel(channelName, getSpanOptions, { deferStreamedR
|
|
|
61
62
|
[SENTRY_KIND]: "client"
|
|
62
63
|
}
|
|
63
64
|
});
|
|
64
|
-
},
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
65
|
+
}, isQuery ? {
|
|
66
|
+
beforeSpanEnd(span, data) {
|
|
67
|
+
if ("error" in data || isObjectLike(data.result) && hasOnMethod(data.result)) return;
|
|
68
|
+
setReturnedRows(span, data.result);
|
|
69
|
+
},
|
|
70
|
+
deferSpanEnd({ span, data, end }) {
|
|
71
|
+
const result = data.result;
|
|
72
|
+
if (!result || typeof result !== "object" || !hasOnMethod(result)) return false;
|
|
73
|
+
const callerScope = data._sentryCallerScope;
|
|
74
|
+
if (callerScope) bindScopeToEmitter(result, callerScope);
|
|
75
|
+
result.on("error", (err) => end(err));
|
|
76
|
+
result.on("end", (endResult) => {
|
|
77
|
+
if (!hasReadMethod(result)) setReturnedRows(span, endResult);
|
|
78
|
+
end();
|
|
79
|
+
});
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
} : void 0);
|
|
73
83
|
}
|
|
74
84
|
function querySpanOptions(ctx, { origin, connectionString }) {
|
|
75
85
|
const params = ctx.self?.connectionParameters ?? {};
|
|
@@ -109,6 +119,23 @@ function poolConnectSpanOptions(ctx) {
|
|
|
109
119
|
function hasOnMethod(obj) {
|
|
110
120
|
return "on" in obj && typeof obj.on === "function";
|
|
111
121
|
}
|
|
122
|
+
function hasReadMethod(obj) {
|
|
123
|
+
return "read" in obj && typeof obj.read === "function";
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Sets `db.response.returned_rows` from a pg-style result (`{ rowCount, rows }`), or an array of them
|
|
127
|
+
* (one per statement of a multi-statement query), summed. Sets nothing when no count is known.
|
|
128
|
+
*/
|
|
129
|
+
function setReturnedRows(span, results) {
|
|
130
|
+
const counts = (Array.isArray(results) ? results : [results]).map(getRowCount).filter((count) => count !== void 0);
|
|
131
|
+
if (counts.length) span.setAttribute(DB_RESPONSE_RETURNED_ROWS, counts.reduce((sum, count) => sum + count, 0));
|
|
132
|
+
}
|
|
133
|
+
function getRowCount(result) {
|
|
134
|
+
if (!isObjectLike(result)) return;
|
|
135
|
+
const { rowCount, rows } = result;
|
|
136
|
+
if (typeof rowCount === "number") return rowCount;
|
|
137
|
+
return Array.isArray(rows) ? rows.length : void 0;
|
|
138
|
+
}
|
|
112
139
|
function extractQueryConfig(args) {
|
|
113
140
|
const arg0 = args[0];
|
|
114
141
|
if (typeof arg0 === "string") return { text: arg0 };
|
|
@@ -179,6 +206,6 @@ function getConnectionString(params) {
|
|
|
179
206
|
* hook or bundler plugin to be active.
|
|
180
207
|
*/
|
|
181
208
|
const postgresIntegration = defineIntegration(_postgresIntegration);
|
|
182
|
-
export { bindPgQueryChannel, getConnectionAttributes, postgresIntegration };
|
|
209
|
+
export { bindPgQueryChannel, getConnectionAttributes, postgresIntegration, setReturnedRows };
|
|
183
210
|
|
|
184
211
|
//# sourceMappingURL=pg.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pg.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/pg.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport {\n DB_NAMESPACE,\n DB_SYSTEM_NAME,\n DB_USER,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n DB_CONNECTION_STRING,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { IntegrationFn, Scope, SpanAttributes } from '@sentry/core';\nimport { isObjectLike, bindScopeToEmitter, defineIntegration, getCurrentScope, startInactiveSpan } from '@sentry/core';\nimport { getSqlQueryAttributes, getSqlSpanName } from '../utils/sql';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { pgModuleNames } from '../orchestrion/config/pg';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// NOTE: this uses the same name as the OTel integration by design.\n// When enabled, the OTel 'Postgres' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Postgres' as const;\n\n// Only the query span carries an origin (the connect/pool-connect spans don't,\n// so they default to 'manual').\nconst ORIGIN = 'auto.db.postgres';\n\nconst ATTR_PG_PLAN = 'db.postgresql.plan';\nconst ATTR_PG_IDLE_TIMEOUT = 'db.postgresql.idle.timeout.millis';\nconst ATTR_PG_MAX_CLIENT = 'db.postgresql.max.client';\nconst DB_SYSTEM_POSTGRESQL = 'postgresql';\n\n// We set the `db` op and the SQL description directly here (same as mysql\n// orchestrion) rather than relying on the OTel pipeline's `inferDbSpanData`\n// processor, which only runs in the node SDK, so setting them here is what\n// makes the spans correct on the other runtimes\n//\n// The user-visible span is identical to OTel: query spans are named after the\n// SQL statement; connect/pool-connect spans keep these names.\nconst SPAN_QUERY_FALLBACK = 'pg.query';\nconst SPAN_CONNECT = 'pg.connect';\nconst SPAN_POOL_CONNECT = 'pg-pool.connect';\n\n/**\n * The shape orchestrion's transform attaches to the tracing-channel `context`. Documented here rather\n * than imported because orchestrion's runtime doesn't export it.\n */\ninterface PgChannelContext extends OrchestrionChannelContext {\n // The caller's scope, captured at `start` and replayed onto a streamed `Submittable` emitter (see below).\n _sentryCallerScope?: Scope;\n}\n\nexport interface PgConnectionParams {\n database?: string;\n host?: string;\n port?: number;\n user?: string;\n connectionString?: string;\n}\n\ninterface PgPoolOptions extends PgConnectionParams {\n idleTimeoutMillis?: number;\n // pg-pool stores the max pool size as `max` (defaulting it to 10 in its\n // constructor). The OTel pg instrumentation reads a `maxClient` field that\n // pg-pool never sets, so its `db.postgresql.max.client` attribute is always\n // dropped; we read the real `max` so the attribute is actually populated.\n max?: number;\n}\n\nconst _postgresIntegration = ((options: { ignoreConnectSpans?: boolean } = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, pgModuleNames, instrumentPostgres, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentPostgres(options: { ignoreConnectSpans?: boolean }): void {\n bindPgQueryChannel(CHANNELS.PG_QUERY, { origin: ORIGIN, connectionString: true });\n\n // Connect spans, gated by `ignoreConnectSpans` (same as OTel pg).\n // `Client.prototype.connect` (pg + native)\n // and `Pool.prototype.connect` (pg-pool).\n if (!options.ignoreConnectSpans) {\n subscribeQueryLikeChannel(CHANNELS.PG_CONNECT, connectSpanOptions);\n subscribeQueryLikeChannel(CHANNELS.PGPOOL_CONNECT, poolConnectSpanOptions);\n }\n}\n\nexport interface PgQuerySpanOptions {\n origin: string;\n // `db.connection_string` is deprecated in favor of `server.address`/`server.port`. Only the pg\n // integration keeps emitting it, for parity with its OTel predecessor.\n connectionString?: boolean;\n}\n\n/**\n * Query spans for a channel carrying `pg` `Client.prototype.query` calls, from `pg` itself or from\n * a copy bundled into another driver (`@neondatabase/serverless`). Only this call can return a\n * streamable `Submittable` result, so it's the only one that defers span-ending to the emitter.\n */\nexport function bindPgQueryChannel(channelName: string, options: PgQuerySpanOptions): void {\n subscribeQueryLikeChannel(channelName, ctx => querySpanOptions(ctx, options), { deferStreamedResult: true });\n}\n\n/**\n * Subscribe to a pg tracing-channel and manage a span across its lifecycle.\n * Shared by the query/connect/pool-connect channels. They differ only in how\n * the span's name + attributes are built (`getSpanOptions`), and whether the\n * result can be a streamable emitter (`deferStreamedResult`, query-only).\n */\nfunction subscribeQueryLikeChannel(\n channelName: string,\n getSpanOptions: (ctx: PgChannelContext) => { name: string; attributes: SpanAttributes },\n { deferStreamedResult = false }: { deferStreamedResult?: boolean } = {},\n): void {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<PgChannelContext>(channelName),\n data => {\n // Capture the caller's scope while still synchronously inside the call, for the streamed path:\n // pg dispatches a `Submittable` emitter's events outside the original async scope, so `deferSpanEnd`\n // replays this scope onto that emitter.\n data._sentryCallerScope = getCurrentScope();\n\n // `sentry.kind: 'client'` mirrors the OTel pg instrumentation, so the emitted\n // `sentry.kind` matches across the OTel and diagnostics-channel paths.\n const spanOptions = getSpanOptions(data);\n return startInactiveSpan({\n ...spanOptions,\n onlyIfParent: true,\n attributes: { ...spanOptions.attributes, [SENTRY_KIND]: 'client' },\n });\n },\n // `connect`/`pool-connect` resolve with a persistent `Client` (itself an\n // `EventEmitter`), which is NOT a streamed result. Deferring their span\n // to that emitter's `'end'`/`'error'` would keep it open for the whole\n // connection lifetime, so it never ends in time and is dropped. Only\n // `query` can return a streamable `Submittable`, so only it defers.\n deferStreamedResult\n ? {\n // Streamable `Submittable` (e.g. `client.query(new Query())`)\n // returns an emitter that orchestrion stores on `ctx.result` while\n // firing no async events; the query isn't done until the emitter\n // emits `'end'`/`'error'`. Defer ending to those events for that\n // path; the callback, promise, and sync-throw paths carry no\n // emitter, so the helper ends the span as usual.\n deferSpanEnd({ data, end }) {\n const result = data.result;\n if (!result || typeof result !== 'object' || !hasOnMethod(result)) {\n return false;\n }\n\n // Replay the caller's scope onto the emitter so listeners theu\n // user attaches after the call returns (and any spans they start)\n // nest under the caller, not a fresh root trace.\n const callerScope = data._sentryCallerScope;\n if (callerScope) {\n bindScopeToEmitter(result, callerScope);\n }\n\n result.on('error', err => end(err));\n result.on('end', () => end());\n\n return true;\n },\n }\n : undefined,\n );\n}\n\nfunction querySpanOptions(\n ctx: PgChannelContext,\n { origin, connectionString }: PgQuerySpanOptions,\n): { name: string; attributes: SpanAttributes } {\n const params = (ctx.self as { connectionParameters?: PgConnectionParams } | undefined)?.connectionParameters ?? {};\n const queryConfig = extractQueryConfig(ctx.arguments);\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n ...(connectionString ? getPgConnectionAttributes(params) : getConnectionAttributes(params)),\n [SENTRY_ORIGIN]: origin,\n ...getSqlQueryAttributes(queryConfig?.text),\n [ATTR_PG_PLAN]: typeof queryConfig?.name === 'string' ? queryConfig.name : undefined,\n };\n\n return { name: getSqlSpanName(attributes, SPAN_QUERY_FALLBACK), attributes };\n}\n\nfunction connectSpanOptions(ctx: PgChannelContext): { name: string; attributes: SpanAttributes } {\n const params = (ctx.self as { connectionParameters?: PgConnectionParams } | undefined)?.connectionParameters ?? {};\n // No origin set -> defaults to 'manual'\n return { name: SPAN_CONNECT, attributes: { [SENTRY_OP]: DB, ...getPgConnectionAttributes(params) } };\n}\n\nfunction poolConnectSpanOptions(ctx: PgChannelContext): { name: string; attributes: SpanAttributes } {\n const opts = (ctx.self as { options?: PgPoolOptions } | undefined)?.options ?? {};\n return { name: SPAN_POOL_CONNECT, attributes: { [SENTRY_OP]: DB, ...getPoolConnectionAttributes(opts) } };\n}\n\nfunction hasOnMethod(obj: object): obj is { on: (event: string, listener: (arg?: unknown) => void) => unknown } {\n return 'on' in obj && typeof (obj as { on?: unknown }).on === 'function';\n}\n\n// `client.query(text, cb?)`, `client.query(text, values, cb?)`, and\n// `client.query(configObj, cb?)` are all valid; normalize to `{ text, name }`\n// (the only fields the span needs). Returns undefined for invalid args.\nfunction extractQueryConfig(args: unknown[]): { text: string; name?: unknown } | undefined {\n const arg0 = args[0];\n if (typeof arg0 === 'string') {\n return { text: arg0 };\n }\n if (isObjectLike(arg0) && typeof (arg0 as { text?: unknown }).text === 'string') {\n const obj = arg0 as { text: string; name?: unknown };\n return { text: obj.text, name: obj.name };\n }\n return undefined;\n}\n\n/** The `db.*`/`server.*` attributes for a pg-style set of connection parameters. */\nexport function getConnectionAttributes(params: PgConnectionParams): SpanAttributes {\n return {\n [DB_SYSTEM_NAME]: DB_SYSTEM_POSTGRESQL,\n [DB_NAMESPACE]: params.database,\n [DB_USER]: params.user,\n [SERVER_ADDRESS]: params.host,\n [SERVER_PORT]: Number.isInteger(params.port) ? params.port : undefined,\n };\n}\n\nfunction getPgConnectionAttributes(params: PgConnectionParams): SpanAttributes {\n // oxlint-disable-next-line typescript/no-deprecated -- Preserve the existing attribute name.\n return { ...getConnectionAttributes(params), [DB_CONNECTION_STRING]: getConnectionString(params) };\n}\n\nfunction getPoolConnectionAttributes(opts: PgPoolOptions): SpanAttributes {\n let url: URL | undefined;\n try {\n url = opts.connectionString ? new URL(opts.connectionString) : undefined;\n } catch {\n url = undefined;\n }\n const database = url?.pathname.slice(1) || opts.database;\n const host = url?.hostname || opts.host;\n // Mirror OTel's `getSemanticAttributesFromPoolConnection`: prefer the URL's\n // port, but fall back to an explicit `opts.port` when the connection string\n // omits it (`Number('')` / `Number(undefined)` -> falsy).\n const port = Number(url?.port) || (Number.isInteger(opts.port) ? opts.port : undefined);\n const user = url?.username || opts.user;\n return {\n [DB_SYSTEM_NAME]: DB_SYSTEM_POSTGRESQL,\n // oxlint-disable-next-line typescript/no-deprecated -- Preserve the existing attribute name.\n [DB_CONNECTION_STRING]: getConnectionString(opts),\n [ATTR_PG_IDLE_TIMEOUT]: opts.idleTimeoutMillis,\n [ATTR_PG_MAX_CLIENT]: opts.max,\n [DB_NAMESPACE]: database,\n [SERVER_PORT]: port,\n // these two come from a url parse and slice, can be ''\n [SERVER_ADDRESS]: host || undefined,\n [DB_USER]: user || undefined,\n };\n}\n\n// Builds `postgresql://host:port/database`, masking credentials when a raw\n// connection string was provided.\nfunction getConnectionString(params: PgConnectionParams): string {\n if (params.connectionString) {\n try {\n const url = new URL(params.connectionString);\n url.username = '';\n url.password = '';\n return url.toString();\n } catch {\n return 'postgresql://localhost:5432/';\n }\n }\n const host = params.host || 'localhost';\n const port = params.port || 5432;\n const database = params.database || '';\n return `postgresql://${host}:${port}/${database}`;\n}\n\n/**\n * Diagnostics-channel-based `pg` (node-postgres) integration.\n *\n * Subscribes to the `orchestrion:pg:query`/`:connect` and\n * `orchestrion:pg-pool:connect` diagnostics_channels that Sentry's code\n * transform injects into `pg`'s `Client.prototype.query`/`connect`\n * and `pg-pool`'s `Pool.prototype.connect`. Requires the Sentry runtime\n * hook or bundler plugin to be active.\n */\nexport const postgresIntegration = defineIntegration(_postgresIntegration);\n"],"mappings":";;;;;;;;;;AAwBA,MAAM,mBAAmB;AAIzB,MAAM,SAAS;AAEf,MAAM,eAAe;AACrB,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAS7B,MAAM,sBAAsB;AAC5B,MAAM,eAAe;AACrB,MAAM,oBAAoB;AA4B1B,MAAM,yBAAyB,UAA4C,CAAC,MAAM;CAChF,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,eAAe,oBAAoB,CAAC,OAAO,CAAC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;CACA,MAAM,WAAW,KAAK,SAAS,MAAM,CAAC,KAAK,KAAK;CAChD,MAAM,OAAO,KAAK,YAAY,KAAK;CAInC,MAAM,OAAO,OAAO,KAAK,IAAI,MAAM,OAAO,UAAU,KAAK,IAAI,IAAI,KAAK,OAAO,KAAA;CAC7E,MAAM,OAAO,KAAK,YAAY,KAAK;CACnC,OAAO;GACJ,iBAAiB;GAEjB,uBAAuB,oBAAoB,IAAI;GAC/C,uBAAuB,KAAK;GAC5B,qBAAqB,KAAK;GAC1B,eAAe;GACf,cAAc;GAEd,iBAAiB,QAAQ,KAAA;GACzB,UAAU,QAAQ,KAAA;CACrB;AACF;AAIA,SAAS,oBAAoB,QAAoC;CAC/D,IAAI,OAAO,kBACT,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,OAAO,gBAAgB;EAC3C,IAAI,WAAW;EACf,IAAI,WAAW;EACf,OAAO,IAAI,SAAS;CACtB,QAAQ;EACN,OAAO;CACT;CAKF,OAAO,gBAHM,OAAO,QAAQ,YAGA,GAFf,OAAO,QAAQ,KAEQ,GADnB,OAAO,YAAY;AAEtC;;;;;;;;;;AAWA,MAAa,sBAAsB,kBAAkB,oBAAoB"}
|
|
1
|
+
{"version":3,"file":"pg.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/pg.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport {\n DB_NAMESPACE,\n DB_RESPONSE_RETURNED_ROWS,\n DB_SYSTEM_NAME,\n DB_USER,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n DB_CONNECTION_STRING,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { IntegrationFn, Scope, Span, SpanAttributes } from '@sentry/core';\nimport { isObjectLike, bindScopeToEmitter, defineIntegration, getCurrentScope, startInactiveSpan } from '@sentry/core';\nimport { getSqlQueryAttributes, getSqlSpanName } from '../utils/sql';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { pgModuleNames } from '../orchestrion/config/pg';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// NOTE: this uses the same name as the OTel integration by design.\n// When enabled, the OTel 'Postgres' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Postgres' as const;\n\n// Only the query span carries an origin (the connect/pool-connect spans don't,\n// so they default to 'manual').\nconst ORIGIN = 'auto.db.postgres';\n\nconst ATTR_PG_PLAN = 'db.postgresql.plan';\nconst ATTR_PG_IDLE_TIMEOUT = 'db.postgresql.idle.timeout.millis';\nconst ATTR_PG_MAX_CLIENT = 'db.postgresql.max.client';\nconst DB_SYSTEM_POSTGRESQL = 'postgresql';\n\n// We set the `db` op and the SQL description directly here (same as mysql\n// orchestrion) rather than relying on the OTel pipeline's `inferDbSpanData`\n// processor, which only runs in the node SDK, so setting them here is what\n// makes the spans correct on the other runtimes\n//\n// The user-visible span is identical to OTel: query spans are named after the\n// SQL statement; connect/pool-connect spans keep these names.\nconst SPAN_QUERY_FALLBACK = 'pg.query';\nconst SPAN_CONNECT = 'pg.connect';\nconst SPAN_POOL_CONNECT = 'pg-pool.connect';\n\n/**\n * The shape orchestrion's transform attaches to the tracing-channel `context`. Documented here rather\n * than imported because orchestrion's runtime doesn't export it.\n */\ninterface PgChannelContext extends OrchestrionChannelContext {\n // The caller's scope, captured at `start` and replayed onto a streamed `Submittable` emitter (see below).\n _sentryCallerScope?: Scope;\n}\n\nexport interface PgConnectionParams {\n database?: string;\n host?: string;\n port?: number;\n user?: string;\n connectionString?: string;\n}\n\ninterface PgPoolOptions extends PgConnectionParams {\n idleTimeoutMillis?: number;\n // pg-pool stores the max pool size as `max` (defaulting it to 10 in its\n // constructor). The OTel pg instrumentation reads a `maxClient` field that\n // pg-pool never sets, so its `db.postgresql.max.client` attribute is always\n // dropped; we read the real `max` so the attribute is actually populated.\n max?: number;\n}\n\nconst _postgresIntegration = ((options: { ignoreConnectSpans?: boolean } = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, pgModuleNames, instrumentPostgres, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentPostgres(options: { ignoreConnectSpans?: boolean }): void {\n bindPgQueryChannel(CHANNELS.PG_QUERY, { origin: ORIGIN, connectionString: true });\n\n // Connect spans, gated by `ignoreConnectSpans` (same as OTel pg).\n // `Client.prototype.connect` (pg + native)\n // and `Pool.prototype.connect` (pg-pool).\n if (!options.ignoreConnectSpans) {\n subscribeQueryLikeChannel(CHANNELS.PG_CONNECT, connectSpanOptions);\n subscribeQueryLikeChannel(CHANNELS.PGPOOL_CONNECT, poolConnectSpanOptions);\n }\n}\n\nexport interface PgQuerySpanOptions {\n origin: string;\n // `db.connection_string` is deprecated in favor of `server.address`/`server.port`. Only the pg\n // integration keeps emitting it, for parity with its OTel predecessor.\n connectionString?: boolean;\n}\n\n/**\n * Query spans for a channel carrying `pg` `Client.prototype.query` calls, from `pg` itself or from\n * a copy bundled into another driver (`@neondatabase/serverless`). Only this call can return a\n * streamable `Submittable` result, so it's the only one that defers span-ending to the emitter.\n */\nexport function bindPgQueryChannel(channelName: string, options: PgQuerySpanOptions): void {\n subscribeQueryLikeChannel(channelName, ctx => querySpanOptions(ctx, options), { isQuery: true });\n}\n\n/**\n * Subscribe to a pg tracing-channel and manage a span across its lifecycle.\n * Shared by the query/connect/pool-connect channels. They differ only in how\n * the span's name + attributes are built (`getSpanOptions`), and whether the\n * result is a query result that can be a streamable emitter and carries a row\n * count (`isQuery`).\n */\nfunction subscribeQueryLikeChannel(\n channelName: string,\n getSpanOptions: (ctx: PgChannelContext) => { name: string; attributes: SpanAttributes },\n { isQuery = false }: { isQuery?: boolean } = {},\n): void {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<PgChannelContext>(channelName),\n data => {\n // Capture the caller's scope while still synchronously inside the call, for the streamed path:\n // pg dispatches a `Submittable` emitter's events outside the original async scope, so `deferSpanEnd`\n // replays this scope onto that emitter.\n data._sentryCallerScope = getCurrentScope();\n\n // `sentry.kind: 'client'` mirrors the OTel pg instrumentation, so the emitted\n // `sentry.kind` matches across the OTel and diagnostics-channel paths.\n const spanOptions = getSpanOptions(data);\n return startInactiveSpan({\n ...spanOptions,\n onlyIfParent: true,\n attributes: { ...spanOptions.attributes, [SENTRY_KIND]: 'client' },\n });\n },\n // `connect`/`pool-connect` resolve with a persistent `Client` (itself an\n // `EventEmitter`), which is NOT a streamed result. Deferring their span\n // to that emitter's `'end'`/`'error'` would keep it open for the whole\n // connection lifetime, so it never ends in time and is dropped. Only\n // `query` can return a streamable `Submittable`, so only it defers.\n isQuery\n ? {\n beforeSpanEnd(span, data) {\n // A streamed `Submittable` reports its rows on its own `'end'` event (see `deferSpanEnd`).\n if ('error' in data || (isObjectLike(data.result) && hasOnMethod(data.result))) {\n return;\n }\n setReturnedRows(span, data.result);\n },\n // Streamable `Submittable` (e.g. `client.query(new Query())`)\n // returns an emitter that orchestrion stores on `ctx.result` while\n // firing no async events; the query isn't done until the emitter\n // emits `'end'`/`'error'`. Defer ending to those events for that\n // path; the callback, promise, and sync-throw paths carry no\n // emitter, so the helper ends the span as usual.\n deferSpanEnd({ span, data, end }) {\n const result = data.result;\n if (!result || typeof result !== 'object' || !hasOnMethod(result)) {\n return false;\n }\n\n // Replay the caller's scope onto the emitter so listeners theu\n // user attaches after the call returns (and any spans they start)\n // nest under the caller, not a fresh root trace.\n const callerScope = data._sentryCallerScope;\n if (callerScope) {\n bindScopeToEmitter(result, callerScope);\n }\n\n result.on('error', err => end(err));\n result.on('end', (endResult?: unknown) => {\n // A `Query` ends with its full result(s). A cursor (`pg-cursor`, `pg-query-stream`) is read in\n // batches and ends with only the last batch, so its count would be wrong.\n if (!hasReadMethod(result)) {\n setReturnedRows(span, endResult);\n }\n end();\n });\n\n return true;\n },\n }\n : undefined,\n );\n}\n\nfunction querySpanOptions(\n ctx: PgChannelContext,\n { origin, connectionString }: PgQuerySpanOptions,\n): { name: string; attributes: SpanAttributes } {\n const params = (ctx.self as { connectionParameters?: PgConnectionParams } | undefined)?.connectionParameters ?? {};\n const queryConfig = extractQueryConfig(ctx.arguments);\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n ...(connectionString ? getPgConnectionAttributes(params) : getConnectionAttributes(params)),\n [SENTRY_ORIGIN]: origin,\n ...getSqlQueryAttributes(queryConfig?.text),\n [ATTR_PG_PLAN]: typeof queryConfig?.name === 'string' ? queryConfig.name : undefined,\n };\n\n return { name: getSqlSpanName(attributes, SPAN_QUERY_FALLBACK), attributes };\n}\n\nfunction connectSpanOptions(ctx: PgChannelContext): { name: string; attributes: SpanAttributes } {\n const params = (ctx.self as { connectionParameters?: PgConnectionParams } | undefined)?.connectionParameters ?? {};\n // No origin set -> defaults to 'manual'\n return { name: SPAN_CONNECT, attributes: { [SENTRY_OP]: DB, ...getPgConnectionAttributes(params) } };\n}\n\nfunction poolConnectSpanOptions(ctx: PgChannelContext): { name: string; attributes: SpanAttributes } {\n const opts = (ctx.self as { options?: PgPoolOptions } | undefined)?.options ?? {};\n return { name: SPAN_POOL_CONNECT, attributes: { [SENTRY_OP]: DB, ...getPoolConnectionAttributes(opts) } };\n}\n\nfunction hasOnMethod(obj: object): obj is { on: (event: string, listener: (arg?: unknown) => void) => unknown } {\n return 'on' in obj && typeof (obj as { on?: unknown }).on === 'function';\n}\n\nfunction hasReadMethod(obj: object): boolean {\n return 'read' in obj && typeof (obj as { read?: unknown }).read === 'function';\n}\n\n/**\n * Sets `db.response.returned_rows` from a pg-style result (`{ rowCount, rows }`), or an array of them\n * (one per statement of a multi-statement query), summed. Sets nothing when no count is known.\n */\nexport function setReturnedRows(span: Span, results: unknown): void {\n const counts = (Array.isArray(results) ? results : [results])\n .map(getRowCount)\n .filter((count): count is number => count !== undefined);\n if (counts.length) {\n span.setAttribute(\n DB_RESPONSE_RETURNED_ROWS,\n counts.reduce((sum, count) => sum + count, 0),\n );\n }\n}\n\nfunction getRowCount(result: unknown): number | undefined {\n if (!isObjectLike(result)) {\n return undefined;\n }\n const { rowCount, rows } = result as { rowCount?: unknown; rows?: unknown };\n if (typeof rowCount === 'number') {\n return rowCount;\n }\n return Array.isArray(rows) ? rows.length : undefined;\n}\n\n// `client.query(text, cb?)`, `client.query(text, values, cb?)`, and\n// `client.query(configObj, cb?)` are all valid; normalize to `{ text, name }`\n// (the only fields the span needs). Returns undefined for invalid args.\nfunction extractQueryConfig(args: unknown[]): { text: string; name?: unknown } | undefined {\n const arg0 = args[0];\n if (typeof arg0 === 'string') {\n return { text: arg0 };\n }\n if (isObjectLike(arg0) && typeof (arg0 as { text?: unknown }).text === 'string') {\n const obj = arg0 as { text: string; name?: unknown };\n return { text: obj.text, name: obj.name };\n }\n return undefined;\n}\n\n/** The `db.*`/`server.*` attributes for a pg-style set of connection parameters. */\nexport function getConnectionAttributes(params: PgConnectionParams): SpanAttributes {\n return {\n [DB_SYSTEM_NAME]: DB_SYSTEM_POSTGRESQL,\n [DB_NAMESPACE]: params.database,\n [DB_USER]: params.user,\n [SERVER_ADDRESS]: params.host,\n [SERVER_PORT]: Number.isInteger(params.port) ? params.port : undefined,\n };\n}\n\nfunction getPgConnectionAttributes(params: PgConnectionParams): SpanAttributes {\n // oxlint-disable-next-line typescript/no-deprecated -- Preserve the existing attribute name.\n return { ...getConnectionAttributes(params), [DB_CONNECTION_STRING]: getConnectionString(params) };\n}\n\nfunction getPoolConnectionAttributes(opts: PgPoolOptions): SpanAttributes {\n let url: URL | undefined;\n try {\n url = opts.connectionString ? new URL(opts.connectionString) : undefined;\n } catch {\n url = undefined;\n }\n const database = url?.pathname.slice(1) || opts.database;\n const host = url?.hostname || opts.host;\n // Mirror OTel's `getSemanticAttributesFromPoolConnection`: prefer the URL's\n // port, but fall back to an explicit `opts.port` when the connection string\n // omits it (`Number('')` / `Number(undefined)` -> falsy).\n const port = Number(url?.port) || (Number.isInteger(opts.port) ? opts.port : undefined);\n const user = url?.username || opts.user;\n return {\n [DB_SYSTEM_NAME]: DB_SYSTEM_POSTGRESQL,\n // oxlint-disable-next-line typescript/no-deprecated -- Preserve the existing attribute name.\n [DB_CONNECTION_STRING]: getConnectionString(opts),\n [ATTR_PG_IDLE_TIMEOUT]: opts.idleTimeoutMillis,\n [ATTR_PG_MAX_CLIENT]: opts.max,\n [DB_NAMESPACE]: database,\n [SERVER_PORT]: port,\n // these two come from a url parse and slice, can be ''\n [SERVER_ADDRESS]: host || undefined,\n [DB_USER]: user || undefined,\n };\n}\n\n// Builds `postgresql://host:port/database`, masking credentials when a raw\n// connection string was provided.\nfunction getConnectionString(params: PgConnectionParams): string {\n if (params.connectionString) {\n try {\n const url = new URL(params.connectionString);\n url.username = '';\n url.password = '';\n return url.toString();\n } catch {\n return 'postgresql://localhost:5432/';\n }\n }\n const host = params.host || 'localhost';\n const port = params.port || 5432;\n const database = params.database || '';\n return `postgresql://${host}:${port}/${database}`;\n}\n\n/**\n * Diagnostics-channel-based `pg` (node-postgres) integration.\n *\n * Subscribes to the `orchestrion:pg:query`/`:connect` and\n * `orchestrion:pg-pool:connect` diagnostics_channels that Sentry's code\n * transform injects into `pg`'s `Client.prototype.query`/`connect`\n * and `pg-pool`'s `Pool.prototype.connect`. Requires the Sentry runtime\n * hook or bundler plugin to be active.\n */\nexport const postgresIntegration = defineIntegration(_postgresIntegration);\n"],"mappings":";;;;;;;;;;AAyBA,MAAM,mBAAmB;AAIzB,MAAM,SAAS;AAEf,MAAM,eAAe;AACrB,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAS7B,MAAM,sBAAsB;AAC5B,MAAM,eAAe;AACrB,MAAM,oBAAoB;AA4B1B,MAAM,yBAAyB,UAA4C,CAAC,MAAM;CAChF,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,eAAe,oBAAoB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AM,MAAM,IAAI,IAAI,OAAO,gBAAgB;EAC3C,IAAI,WAAW;EACf,IAAI,WAAW;EACf,OAAO,IAAI,SAAS;CACtB,QAAQ;EACN,OAAO;CACT;CAKF,OAAO,gBAHM,OAAO,QAAQ,YAGA,GAFf,OAAO,QAAQ,KAEQ,GADnB,OAAO,YAAY;AAEtC;;;;;;;;;;AAWA,MAAa,sBAAsB,kBAAkB,oBAAoB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pino.js","names":[],"sources":["../../../src/integrations/pino.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport type { IntegrationFn, LogSeverityLevel } from '@sentry/core';\nimport {\n captureLogEvent,\n addExceptionMechanism,\n captureException,\n captureMessage,\n defineIntegration,\n isObjectLike,\n severityLevelFromString,\n withScope,\n} from '@sentry/core';\nimport { tracingChannel } from '../utils/diagnosticsChannel';\n\nconst SENTRY_TRACK_SYMBOL = Symbol('sentry-track-pino-logger');\n\ntype LevelMapping = {\n // Fortunately pino uses the same levels as Sentry\n labels: { [level: number]: LogSeverityLevel };\n};\n\ntype Pino = {\n [key: symbol]: unknown;\n levels: LevelMapping;\n [SENTRY_TRACK_SYMBOL]?: 'track' | 'ignore';\n};\n\n/**\n * Gets a custom Pino key from a logger instance by searching for the symbol.\n * Pino uses non-global symbols like Symbol('pino.messageKey'): https://github.com/pinojs/pino/blob/8a816c0b1f72de5ae9181f3bb402109b66f7d812/lib/symbols.js\n */\nfunction getPinoKey(logger: Pino, symbolName: string, defaultKey: string): string {\n const symbols = Object.getOwnPropertySymbols(logger);\n const symbolString = `Symbol(${symbolName})`;\n for (const sym of symbols) {\n if (sym.toString() === symbolString) {\n const value = logger[sym];\n return typeof value === 'string' ? value : defaultKey;\n }\n }\n return defaultKey;\n}\n\ntype MergeObject = {\n [key: string]: unknown;\n err?: Error;\n};\n\ntype PinoHookArgs = [MergeObject, string, number];\n\ntype PinoOptions = {\n /**\n * Automatically instrument all Pino loggers.\n *\n * When set to `false`, only loggers marked with `pinoIntegration.trackLogger(logger)` will be captured.\n *\n * @default true\n */\n autoInstrument: boolean;\n /**\n * Options to enable capturing of error events.\n */\n error: {\n /**\n * Levels that trigger capturing of events.\n *\n * @default []\n */\n levels: LogSeverityLevel[];\n /**\n * By default, Sentry will mark captured errors as handled.\n * Set this to `false` if you want to mark them as unhandled instead.\n *\n * @default true\n */\n handled: boolean;\n };\n /**\n * Options to enable capturing of logs.\n */\n log: {\n /**\n * Levels that trigger capturing of logs.\n *\n * @default [\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\"]\n */\n levels: LogSeverityLevel[];\n };\n};\n\nconst DEFAULT_OPTIONS: PinoOptions = {\n autoInstrument: true,\n error: { levels: [], handled: true },\n log: { levels: ['trace', 'debug', 'info', 'warn', 'error', 'fatal'] },\n};\n\ntype DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? Partial<T[P]> : T[P];\n};\n\ntype PinoResult = {\n level?: string;\n time?: string;\n pid?: number;\n hostname?: string;\n} & Record<string, unknown>;\n\nfunction stripIgnoredFields(result: PinoResult): PinoResult {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { level, time, pid, hostname, ...rest } = result;\n return rest;\n}\n\nconst _pinoIntegration = defineIntegration((userOptions: DeepPartial<PinoOptions> = {}) => {\n const options: PinoOptions = {\n autoInstrument: userOptions.autoInstrument !== false,\n error: { ...DEFAULT_OPTIONS.error, ...userOptions.error },\n log: { ...DEFAULT_OPTIONS.log, ...userOptions.log },\n };\n\n function shouldTrackLogger(logger: Pino): boolean {\n const override = logger[SENTRY_TRACK_SYMBOL];\n return override === 'track' || (override !== 'ignore' && options.autoInstrument);\n }\n\n return {\n name: 'Pino',\n setup: () => {\n const integratedChannel = tracingChannel('pino_asJson');\n\n function onPinoStart(self: Pino, args: PinoHookArgs, result: PinoResult): void {\n if (!shouldTrackLogger(self)) {\n return;\n }\n\n const resultObj = stripIgnoredFields(result);\n\n const [captureObj, message, levelNumber] = args;\n const level = self?.levels?.labels?.[levelNumber] || 'info';\n const messageKey = getPinoKey(self, 'pino.messageKey', 'msg');\n const logMessage = message || (resultObj?.[messageKey] as string | undefined) || '';\n\n if (options.log.levels.includes(level)) {\n const attributes: Record<string, unknown> = {\n ...resultObj,\n [SENTRY_ORIGIN]: 'auto.log.pino',\n 'pino.logger.level': levelNumber,\n };\n\n captureLogEvent({ level, message: logMessage, attributes });\n }\n\n if (options.error.levels.includes(level)) {\n const errorKey = getPinoKey(self, 'pino.errorKey', 'err');\n\n // Attach the log message and remaining log fields (e.g. child logger\n // bindings, merge object fields) to the event. The serialized error is\n // excluded since it is captured as the event exception itself.\n const pinoContext: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(resultObj)) {\n if (key !== errorKey && key !== messageKey) {\n pinoContext[key] = value;\n }\n }\n if (logMessage) {\n pinoContext[messageKey] = logMessage;\n }\n\n const captureContext = {\n level: severityLevelFromString(level),\n contexts: { pino: pinoContext },\n };\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n event.logger = 'pino';\n\n addExceptionMechanism(event, {\n handled: options.error.handled,\n type: 'auto.log.pino',\n });\n\n return event;\n });\n\n const error = captureObj[errorKey];\n if (error) {\n captureException(error, captureContext);\n return;\n }\n\n captureMessage(logMessage, captureContext);\n });\n }\n }\n\n integratedChannel.end.subscribe(data => {\n const {\n instance,\n arguments: args,\n result,\n } = data as { instance: Pino; arguments: PinoHookArgs; result: string };\n onPinoStart(instance, args, JSON.parse(result));\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Integration for Pino logging library.\n * Captures Pino logs as Sentry logs and optionally captures some log levels as events.\n *\n * By default, all Pino loggers will be captured. To ignore a specific logger, use `pinoIntegration.untrackLogger(logger)`.\n *\n * If you disable automatic instrumentation with `autoInstrument: false`, you can mark specific loggers to be tracked with `pinoIntegration.trackLogger(logger)`.\n *\n * Requires Pino >=v8.0.0\n */\nexport const pinoIntegration = Object.assign(_pinoIntegration, {\n trackLogger(logger: unknown): void {\n if (isObjectLike(logger) && 'levels' in logger) {\n (logger as Pino)[SENTRY_TRACK_SYMBOL] = 'track';\n }\n },\n untrackLogger(logger: unknown): void {\n if (isObjectLike(logger) && 'levels' in logger) {\n (logger as Pino)[SENTRY_TRACK_SYMBOL] = 'ignore';\n }\n },\n});\n"],"mappings":";;;;AAcA,MAAM,sBAAsB,OAAO,0BAA0B;;;;;AAiB7D,SAAS,WAAW,QAAc,YAAoB,YAA4B;CAChF,MAAM,UAAU,OAAO,sBAAsB,MAAM;CACnD,MAAM,eAAe,UAAU,WAAW;CAC1C,KAAK,MAAM,OAAO,SAChB,IAAI,IAAI,SAAS,MAAM,cAAc;EACnC,MAAM,QAAQ,OAAO;EACrB,OAAO,OAAO,UAAU,WAAW,QAAQ;CAC7C;CAEF,OAAO;AACT;AAiDA,MAAM,kBAA+B;CACnC,gBAAgB;CAChB,OAAO;EAAE,QAAQ,CAAC;EAAG,SAAS;CAAK;CACnC,KAAK,EAAE,QAAQ;EAAC;EAAS;EAAS;EAAQ;EAAQ;EAAS;CAAO,EAAE;AACtE;AAaA,SAAS,mBAAmB,QAAgC;CAE1D,MAAM,EAAE,OAAO,MAAM,KAAK,UAAU,GAAG,SAAS;CAChD,OAAO;AACT;AAEA,MAAM,mBAAmB,mBAAmB,cAAwC,CAAC,MAAM;CACzF,MAAM,UAAuB;EAC3B,gBAAgB,YAAY,mBAAmB;EAC/C,OAAO;GAAE,GAAG,gBAAgB;GAAO,GAAG,YAAY;EAAM;EACxD,KAAK;GAAE,GAAG,gBAAgB;GAAK,GAAG,YAAY;EAAI;CACpD;CAEA,SAAS,kBAAkB,QAAuB;EAChD,MAAM,WAAW,OAAO;EACxB,OAAO,aAAa,WAAY,aAAa,YAAY,QAAQ;CACnE;CAEA,OAAO;EACL,MAAM;EACN,aAAa;GACX,MAAM,oBAAoB,eAAe,aAAa;GAEtD,SAAS,YAAY,MAAY,MAAoB,QAA0B;IAC7E,IAAI,CAAC,kBAAkB,IAAI,GACzB;IAGF,MAAM,YAAY,mBAAmB,MAAM;IAE3C,MAAM,CAAC,YAAY,SAAS,eAAe;IAC3C,MAAM,QAAQ,MAAM,QAAQ,SAAS,gBAAgB;IACrD,MAAM,aAAa,WAAW,MAAM,mBAAmB,KAAK;IAC5D,MAAM,aAAa,WAAY,YAAY,eAAsC;IAEjF,IAAI,QAAQ,IAAI,OAAO,SAAS,KAAK,GAAG;KACtC,MAAM,aAAsC;MAC1C,GAAG;OACF,gBAAgB;MACjB,qBAAqB;KACvB;KAEA,gBAAgB;MAAE;MAAO,SAAS;MAAY;KAAW,CAAC;IAC5D;IAEA,IAAI,QAAQ,MAAM,OAAO,SAAS,KAAK,GAAG;KACxC,MAAM,WAAW,WAAW,MAAM,iBAAiB,KAAK;KAKxD,MAAM,cAAuC,CAAC;KAC9C,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,SAAS,GACjD,IAAI,QAAQ,YAAY,QAAQ,YAC9B,YAAY,OAAO;KAGvB,IAAI,YACF,YAAY,cAAc;KAG5B,MAAM,iBAAiB;MACrB,OAAO,wBAAwB,KAAK;MACpC,UAAU,EAAE,MAAM,YAAY;KAChC;KAEA,WAAU,UAAS;MACjB,MAAM,mBAAkB,UAAS;OAC/B,MAAM,SAAS;OAEf,sBAAsB,OAAO;QAC3B,SAAS,QAAQ,MAAM;QACvB,MAAM;OACR,CAAC;OAED,OAAO;MACT,CAAC;MAED,MAAM,QAAQ,WAAW;MACzB,IAAI,OAAO;
|
|
1
|
+
{"version":3,"file":"pino.js","names":[],"sources":["../../../src/integrations/pino.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport type { IntegrationFn, LogSeverityLevel } from '@sentry/core';\nimport {\n captureLogEvent,\n addExceptionMechanism,\n captureException,\n captureMessage,\n defineIntegration,\n isObjectLike,\n severityLevelFromString,\n withScope,\n} from '@sentry/core';\nimport { tracingChannel } from '../utils/diagnosticsChannel';\n\nconst SENTRY_TRACK_SYMBOL = Symbol('sentry-track-pino-logger');\n\ntype LevelMapping = {\n // Fortunately pino uses the same levels as Sentry\n labels: { [level: number]: LogSeverityLevel };\n};\n\ntype Pino = {\n [key: symbol]: unknown;\n levels: LevelMapping;\n [SENTRY_TRACK_SYMBOL]?: 'track' | 'ignore';\n};\n\n/**\n * Gets a custom Pino key from a logger instance by searching for the symbol.\n * Pino uses non-global symbols like Symbol('pino.messageKey'): https://github.com/pinojs/pino/blob/8a816c0b1f72de5ae9181f3bb402109b66f7d812/lib/symbols.js\n */\nfunction getPinoKey(logger: Pino, symbolName: string, defaultKey: string): string {\n const symbols = Object.getOwnPropertySymbols(logger);\n const symbolString = `Symbol(${symbolName})`;\n for (const sym of symbols) {\n if (sym.toString() === symbolString) {\n const value = logger[sym];\n return typeof value === 'string' ? value : defaultKey;\n }\n }\n return defaultKey;\n}\n\ntype MergeObject = {\n [key: string]: unknown;\n err?: Error;\n};\n\ntype PinoHookArgs = [MergeObject, string, number];\n\ntype PinoOptions = {\n /**\n * Automatically instrument all Pino loggers.\n *\n * When set to `false`, only loggers marked with `pinoIntegration.trackLogger(logger)` will be captured.\n *\n * @default true\n */\n autoInstrument: boolean;\n /**\n * Options to enable capturing of error events.\n */\n error: {\n /**\n * Levels that trigger capturing of events.\n *\n * @default []\n */\n levels: LogSeverityLevel[];\n /**\n * By default, Sentry will mark captured errors as handled.\n * Set this to `false` if you want to mark them as unhandled instead.\n *\n * @default true\n */\n handled: boolean;\n };\n /**\n * Options to enable capturing of logs.\n */\n log: {\n /**\n * Levels that trigger capturing of logs.\n *\n * @default [\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\"]\n */\n levels: LogSeverityLevel[];\n };\n};\n\nconst DEFAULT_OPTIONS: PinoOptions = {\n autoInstrument: true,\n error: { levels: [], handled: true },\n log: { levels: ['trace', 'debug', 'info', 'warn', 'error', 'fatal'] },\n};\n\ntype DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? Partial<T[P]> : T[P];\n};\n\ntype PinoResult = {\n level?: string;\n time?: string;\n pid?: number;\n hostname?: string;\n} & Record<string, unknown>;\n\nfunction stripIgnoredFields(result: PinoResult): PinoResult {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { level, time, pid, hostname, ...rest } = result;\n return rest;\n}\n\nconst _pinoIntegration = defineIntegration((userOptions: DeepPartial<PinoOptions> = {}) => {\n const options: PinoOptions = {\n autoInstrument: userOptions.autoInstrument !== false,\n error: { ...DEFAULT_OPTIONS.error, ...userOptions.error },\n log: { ...DEFAULT_OPTIONS.log, ...userOptions.log },\n };\n\n function shouldTrackLogger(logger: Pino): boolean {\n const override = logger[SENTRY_TRACK_SYMBOL];\n return override === 'track' || (override !== 'ignore' && options.autoInstrument);\n }\n\n return {\n name: 'Pino',\n setup: () => {\n const integratedChannel = tracingChannel('pino_asJson');\n\n function onPinoStart(self: Pino, args: PinoHookArgs, result: PinoResult): void {\n if (!shouldTrackLogger(self)) {\n return;\n }\n\n const resultObj = stripIgnoredFields(result);\n\n const [captureObj, message, levelNumber] = args;\n const level = self?.levels?.labels?.[levelNumber] || 'info';\n const messageKey = getPinoKey(self, 'pino.messageKey', 'msg');\n const logMessage = message || (resultObj?.[messageKey] as string | undefined) || '';\n\n if (options.log.levels.includes(level)) {\n const attributes: Record<string, unknown> = {\n ...resultObj,\n [SENTRY_ORIGIN]: 'auto.log.pino',\n 'pino.logger.level': levelNumber,\n };\n\n captureLogEvent({ level, message: logMessage, attributes });\n }\n\n if (options.error.levels.includes(level)) {\n const errorKey = getPinoKey(self, 'pino.errorKey', 'err');\n\n // Attach the log message and remaining log fields (e.g. child logger\n // bindings, merge object fields) to the event. The serialized error is\n // excluded since it is captured as the event exception itself.\n const pinoContext: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(resultObj)) {\n if (key !== errorKey && key !== messageKey) {\n pinoContext[key] = value;\n }\n }\n if (logMessage) {\n pinoContext[messageKey] = logMessage;\n }\n\n const captureContext = {\n level: severityLevelFromString(level),\n contexts: { pino: pinoContext },\n };\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n event.logger = 'pino';\n\n addExceptionMechanism(event, {\n handled: options.error.handled,\n type: 'auto.log.pino',\n });\n\n return event;\n });\n\n const error = captureObj[errorKey];\n if (error) {\n // oxlint-disable-next-line sdk/require-exception-mechanism -- mechanism is set by the event processor above\n captureException(error, captureContext);\n return;\n }\n\n captureMessage(logMessage, captureContext);\n });\n }\n }\n\n integratedChannel.end.subscribe(data => {\n const {\n instance,\n arguments: args,\n result,\n } = data as { instance: Pino; arguments: PinoHookArgs; result: string };\n onPinoStart(instance, args, JSON.parse(result));\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Integration for Pino logging library.\n * Captures Pino logs as Sentry logs and optionally captures some log levels as events.\n *\n * By default, all Pino loggers will be captured. To ignore a specific logger, use `pinoIntegration.untrackLogger(logger)`.\n *\n * If you disable automatic instrumentation with `autoInstrument: false`, you can mark specific loggers to be tracked with `pinoIntegration.trackLogger(logger)`.\n *\n * Requires Pino >=v8.0.0\n */\nexport const pinoIntegration = Object.assign(_pinoIntegration, {\n trackLogger(logger: unknown): void {\n if (isObjectLike(logger) && 'levels' in logger) {\n (logger as Pino)[SENTRY_TRACK_SYMBOL] = 'track';\n }\n },\n untrackLogger(logger: unknown): void {\n if (isObjectLike(logger) && 'levels' in logger) {\n (logger as Pino)[SENTRY_TRACK_SYMBOL] = 'ignore';\n }\n },\n});\n"],"mappings":";;;;AAcA,MAAM,sBAAsB,OAAO,0BAA0B;;;;;AAiB7D,SAAS,WAAW,QAAc,YAAoB,YAA4B;CAChF,MAAM,UAAU,OAAO,sBAAsB,MAAM;CACnD,MAAM,eAAe,UAAU,WAAW;CAC1C,KAAK,MAAM,OAAO,SAChB,IAAI,IAAI,SAAS,MAAM,cAAc;EACnC,MAAM,QAAQ,OAAO;EACrB,OAAO,OAAO,UAAU,WAAW,QAAQ;CAC7C;CAEF,OAAO;AACT;AAiDA,MAAM,kBAA+B;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AK,UAAU,OAAO,QAAQ,SAAS,GACjD,IAAI,QAAQ,YAAY,QAAQ,YAC9B,YAAY,OAAO;KAGvB,IAAI,YACF,YAAY,cAAc;KAG5B,MAAM,iBAAiB;MACrB,OAAO,wBAAwB,KAAK;MACpC,UAAU,EAAE,MAAM,YAAY;KAChC;KAEA,WAAU,UAAS;MACjB,MAAM,mBAAkB,UAAS;OAC/B,MAAM,SAAS;OAEf,sBAAsB,OAAO;QAC3B,SAAS,QAAQ,MAAM;QACvB,MAAM;OACR,CAAC;OAED,OAAO;MACT,CAAC;MAED,MAAM,QAAQ,WAAW;MACzB,IAAI,OAAO;OAET,iBAAiB,OAAO,cAAc;OACtC;MACF;MAEA,eAAe,YAAY,cAAc;KAC3C,CAAC;IACH;GACF;GAEA,kBAAkB,IAAI,WAAU,SAAQ;IACtC,MAAM,EACJ,UACA,WAAW,MACX,WACE;IACJ,YAAY,UAAU,MAAM,KAAK,MAAM,MAAM,CAAC;GAChD,CAAC;EACH;CACF;AACF,CAAC;;;;;;;;;;;AAYD,MAAa,kBAAkB,OAAO,OAAO,kBAAkB;CAC7D,YAAY,QAAuB;EACjC,IAAI,aAAa,MAAM,KAAK,YAAY,QACrC,OAAgB,uBAAuB;CAE5C;CACA,cAAc,QAAuB;EACnC,IAAI,aAAa,MAAM,KAAK,YAAY,QACrC,OAAgB,uBAAuB;CAE5C;AACF,CAAC"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { tracingChannel } from "../utils/diagnosticsChannel.js";
|
|
2
|
+
import { createTanstackAIMiddleware } from "../ai/tanstack-ai/index.js";
|
|
3
|
+
import { TANSTACK_AI_INTEGRATION_NAME, TANSTACK_AI_MIDDLEWARE_BRAND } from "../ai/tanstack-ai/constants.js";
|
|
4
|
+
import { CHANNELS } from "../orchestrion/channels.js";
|
|
5
|
+
import { tanstackAiModuleNames } from "../orchestrion/config/tanstack-ai.js";
|
|
6
|
+
import { invokeOrchestrionInstrumentation } from "../orchestrion/instrumentation.js";
|
|
7
|
+
import { safeChannelCallback } from "../tracing-channel.js";
|
|
8
|
+
import { consoleSandbox, defineIntegration, isObjectLike } from "@sentry/core";
|
|
9
|
+
// src/integrations/tanstack-ai.ts
|
|
10
|
+
const _tanstackAIIntegration = ((options = {}) => {
|
|
11
|
+
return {
|
|
12
|
+
name: TANSTACK_AI_INTEGRATION_NAME,
|
|
13
|
+
setup(client) {
|
|
14
|
+
invokeOrchestrionInstrumentation(client, tanstackAiModuleNames, instrumentTanstackAI, [options], { requiresTracingChannelBinding: false });
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
});
|
|
18
|
+
let warnedOtelMiddleware = false;
|
|
19
|
+
function instrumentTanstackAI(options) {
|
|
20
|
+
tracingChannel(CHANNELS.TANSTACK_AI_CHAT).start.subscribe((message) => {
|
|
21
|
+
safeChannelCallback(() => {
|
|
22
|
+
const data = message;
|
|
23
|
+
const call = data.arguments[0];
|
|
24
|
+
if (!isObjectLike(call)) return;
|
|
25
|
+
const existing = call.middleware;
|
|
26
|
+
if (existing !== void 0 && !Array.isArray(existing)) return;
|
|
27
|
+
if (existing?.some((entry) => isObjectLike(entry) && entry[TANSTACK_AI_MIDDLEWARE_BRAND])) return;
|
|
28
|
+
if (existing?.some((entry) => isObjectLike(entry) && entry.name === "otel")) warnOtelMiddleware();
|
|
29
|
+
data.arguments[0] = {
|
|
30
|
+
...call,
|
|
31
|
+
middleware: [...existing ?? [], createTanstackAIMiddleware(options, call)]
|
|
32
|
+
};
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
function warnOtelMiddleware() {
|
|
37
|
+
if (warnedOtelMiddleware) return;
|
|
38
|
+
warnedOtelMiddleware = true;
|
|
39
|
+
consoleSandbox(() => {
|
|
40
|
+
console.warn("[Sentry] `tanstackAIIntegration` is active and a `chat()` call also uses TanStack's otelMiddleware, so each run is recorded twice. Remove otelMiddleware to avoid duplicate spans.");
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Traces the `chat()` calls of TanStack AI (`@tanstack/ai` >= 1.0.0 < 2), through the
|
|
45
|
+
* `orchestrion:@tanstack/ai:chat` channel. Each call gets a `gen_ai.invoke_agent` span, with a
|
|
46
|
+
* `gen_ai.chat` span for each model call and a `gen_ai.execute_tool` span for each tool run.
|
|
47
|
+
* Needs the Sentry runtime hook (`--import`) or bundler plugin.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```javascript
|
|
51
|
+
* Sentry.init({
|
|
52
|
+
* integrations: [Sentry.tanstackAIIntegration({ recordInputs: true, recordOutputs: true })],
|
|
53
|
+
* });
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
const tanstackAIIntegration = defineIntegration(_tanstackAIIntegration);
|
|
57
|
+
export { tanstackAIIntegration };
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=tanstack-ai.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tanstack-ai.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/tanstack-ai.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { consoleSandbox, defineIntegration, isObjectLike } from '@sentry/core';\nimport type { TanstackAIOptions } from '../ai/tanstack-ai';\nimport { createTanstackAIMiddleware } from '../ai/tanstack-ai';\nimport { TANSTACK_AI_INTEGRATION_NAME, TANSTACK_AI_MIDDLEWARE_BRAND } from '../ai/tanstack-ai/constants';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { tanstackAiModuleNames } from '../orchestrion/config/tanstack-ai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { safeChannelCallback } from '../tracing-channel';\n\nconst _tanstackAIIntegration = ((options: TanstackAIOptions = {}) => {\n return {\n name: TANSTACK_AI_INTEGRATION_NAME,\n setup(client) {\n // Adding the middleware starts no span, so the subscription does not need the binding.\n invokeOrchestrionInstrumentation(client, tanstackAiModuleNames, instrumentTanstackAI, [options], {\n requiresTracingChannelBinding: false,\n });\n },\n };\n}) satisfies IntegrationFn;\n\nlet warnedOtelMiddleware = false;\n\nfunction instrumentTanstackAI(options: TanstackAIOptions): void {\n diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.TANSTACK_AI_CHAT).start.subscribe(message => {\n safeChannelCallback(() => {\n const data = message as OrchestrionChannelContext;\n const call = data.arguments[0];\n if (!isObjectLike(call)) {\n return;\n }\n const existing = call.middleware;\n // `chat()` throws for middleware that is not an array. Leave that error to it.\n if (existing !== undefined && !Array.isArray(existing)) {\n return;\n }\n if (existing?.some(entry => isObjectLike(entry) && entry[TANSTACK_AI_MIDDLEWARE_BRAND])) {\n return;\n }\n if (existing?.some(entry => isObjectLike(entry) && entry.name === 'otel')) {\n warnOtelMiddleware();\n }\n // Last, so that it records the config and the chunks after the other middleware changed them.\n // A copy, so that options which the app uses again do not collect one middleware per call.\n data.arguments[0] = {\n ...call,\n middleware: [...(existing ?? []), createTanstackAIMiddleware(options, call)],\n };\n });\n });\n}\n\nfunction warnOtelMiddleware(): void {\n if (warnedOtelMiddleware) {\n return;\n }\n warnedOtelMiddleware = true;\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n \"[Sentry] `tanstackAIIntegration` is active and a `chat()` call also uses TanStack's otelMiddleware, so each run is recorded twice. Remove otelMiddleware to avoid duplicate spans.\",\n );\n });\n}\n\n/**\n * Traces the `chat()` calls of TanStack AI (`@tanstack/ai` >= 1.0.0 < 2), through the\n * `orchestrion:@tanstack/ai:chat` channel. Each call gets a `gen_ai.invoke_agent` span, with a\n * `gen_ai.chat` span for each model call and a `gen_ai.execute_tool` span for each tool run.\n * Needs the Sentry runtime hook (`--import`) or bundler plugin.\n *\n * @example\n * ```javascript\n * Sentry.init({\n * integrations: [Sentry.tanstackAIIntegration({ recordInputs: true, recordOutputs: true })],\n * });\n * ```\n */\nexport const tanstackAIIntegration = defineIntegration(_tanstackAIIntegration);\n"],"mappings":";;;;;;;;;AAYA,MAAM,2BAA2B,UAA6B,CAAC,MAAM;CACnE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GAEZ,iCAAiC,QAAQ,uBAAuB,sBAAsB,CAAC,OAAO,GAAG,EAC/F,+BAA+B,MACjC,CAAC;EACH;CACF;AACF;AAEA,IAAI,uBAAuB;AAE3B,SAAS,qBAAqB,SAAkC;CAC9DA,eAA6D,SAAS,gBAAgB,CAAC,CAAC,MAAM,WAAU,YAAW;EACjH,0BAA0B;GACxB,MAAM,OAAO;GACb,MAAM,OAAO,KAAK,UAAU;GAC5B,IAAI,CAAC,aAAa,IAAI,GACpB;GAEF,MAAM,WAAW,KAAK;GAEtB,IAAI,aAAa,KAAA,KAAa,CAAC,MAAM,QAAQ,QAAQ,GACnD;GAEF,IAAI,UAAU,MAAK,UAAS,aAAa,KAAK,KAAK,MAAM,6BAA6B,GACpF;GAEF,IAAI,UAAU,MAAK,UAAS,aAAa,KAAK,KAAK,MAAM,SAAS,MAAM,GACtE,mBAAmB;GAIrB,KAAK,UAAU,KAAK;IAClB,GAAG;IACH,YAAY,CAAC,GAAI,YAAY,CAAC,GAAI,2BAA2B,SAAS,IAAI,CAAC;GAC7E;EACF,CAAC;CACH,CAAC;AACH;AAEA,SAAS,qBAA2B;CAClC,IAAI,sBACF;CAEF,uBAAuB;CACvB,qBAAqB;EAEnB,QAAQ,KACN,oLACF;CACF,CAAC;AACH;;;;;;;;;;;;;;AAeA,MAAa,wBAAwB,kBAAkB,sBAAsB"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { mapObjectValues } from "./util.js";
|
|
1
|
+
import { asNumber, mapObjectValues } from "./util.js";
|
|
2
2
|
import { isObjectLike, stringify } from "@sentry/core";
|
|
3
3
|
// src/integrations/vercel-ai/extract.ts
|
|
4
|
-
/** Maps the AI SDK `experimental_extract` input and output to the Clairic shape of the `gen_ai.extract` schemas. */
|
|
5
4
|
/**
|
|
6
5
|
* Joins the text of the AI SDK state parts into one Clairic `state` string. The gateway does this join on
|
|
7
6
|
* the server and does not show its separator, so this one is our choice. It only makes the recorded text
|
|
@@ -62,7 +61,7 @@ function toExtractAnswers(answers, parts) {
|
|
|
62
61
|
return mapObjectValues(answers, ({ pNull, source, items, ...rest }) => {
|
|
63
62
|
const mapped = {
|
|
64
63
|
...rest,
|
|
65
|
-
p_null: pNull
|
|
64
|
+
p_null: asNumber(pNull)
|
|
66
65
|
};
|
|
67
66
|
const span = toExtractSpan(source, parts);
|
|
68
67
|
if (span) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extract.js","names":[],"sources":["../../../../src/integrations/vercel-ai/extract.ts"],"sourcesContent":["/** Maps the AI SDK `experimental_extract` input and output to the Clairic shape of the `gen_ai.extract` schemas. */\n\nimport { isObjectLike, stringify } from '@sentry/core';\nimport { mapObjectValues } from './util';\n\n/**\n * Joins the text of the AI SDK state parts into one Clairic `state` string. The gateway does this join on\n * the server and does not show its separator, so this one is our choice. It only makes the recorded text\n * easier to read: the answer spans stay correct with any separator, because we add each part's offset.\n */\nconst EXTRACT_STATE_SEPARATOR = '\\n\\n';\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\ninterface ExtractState {\n request:
|
|
1
|
+
{"version":3,"file":"extract.js","names":[],"sources":["../../../../src/integrations/vercel-ai/extract.ts"],"sourcesContent":["/** Maps the AI SDK `experimental_extract` input and output to the Clairic shape of the `gen_ai.extract` schemas. */\n\nimport type { ExtractAnswer, ExtractRequest, ExtractSpan } from '@sentry/conventions/attributes';\nimport { isObjectLike, stringify } from '@sentry/core';\nimport { asNumber, mapObjectValues } from './util';\n\n/**\n * Joins the text of the AI SDK state parts into one Clairic `state` string. The gateway does this join on\n * the server and does not show its separator, so this one is our choice. It only makes the recorded text\n * easier to read: the answer spans stay correct with any separator, because we add each part's offset.\n */\nconst EXTRACT_STATE_SEPARATOR = '\\n\\n';\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\ninterface ExtractState {\n request: Pick<ExtractRequest, 'state' | 'images' | 'documents'>;\n /** For each AI SDK state part, the offset of its text in `request.state`, or `'image'` for an image part. */\n parts: (number | 'image' | undefined)[];\n}\n\n/**\n * Clairic takes the text as one `state` string, with images and PDF documents in their own arrays. The AI SDK\n * also takes a JSON object, or an array of text, JSON and file parts. Join the text of the parts and keep the\n * offset of each part, so that the answer spans point into the joined `state`.\n */\nexport function toExtractState(state: unknown): ExtractState {\n const images: string[] = [];\n const documents: string[] = [];\n // Each text gets a separator in front, which is cut off from the start of `state` at the end.\n let joined = '';\n\n const parts = (Array.isArray(state) ? state : [{ type: 'json', value: state }]).map(part => {\n if (!isObjectLike(part)) {\n return undefined;\n }\n if (part.type === 'file') {\n if (String(part.mediaType).split('/')[0] === 'image') {\n images.push(BLOB_SUBSTITUTE);\n return 'image' as const;\n }\n if (part.mediaType === 'application/pdf') {\n documents.push(BLOB_SUBSTITUTE);\n }\n return undefined;\n }\n const text = part.type === 'text' ? part.text : stringify(part.value);\n if (typeof text !== 'string') {\n return undefined;\n }\n joined += EXTRACT_STATE_SEPARATOR + text;\n return joined.length - text.length - EXTRACT_STATE_SEPARATOR.length;\n });\n\n return {\n request: {\n state: joined ? joined.slice(EXTRACT_STATE_SEPARATOR.length) : undefined,\n images: images.length ? images : undefined,\n documents: documents.length ? documents : undefined,\n },\n parts,\n };\n}\n\n/**\n * The AI SDK also takes JSON or `null` as field `instructions`, but the schema allows only a string.\n */\nexport function toExtractFields(fields: unknown): unknown {\n return isObjectLike(fields)\n ? mapObjectValues(fields, field => ({\n ...field,\n instructions: field.instructions === null ? undefined : stringify(field.instructions),\n }))\n : fields;\n}\n\n/**\n * The AI SDK normalizes the provider's extraction answers. Map them back to the provider shape of\n * `gen_ai.output.messages` on `gen_ai.extract` spans. The AI SDK does not expose `truncated`.\n */\nexport function toExtractAnswers(\n answers: Record<string, unknown>,\n parts: ExtractState['parts'],\n): Record<string, unknown> {\n return mapObjectValues(answers, ({ pNull, source, items, ...rest }) => {\n const mapped: Record<string, unknown> & Partial<ExtractAnswer> = { ...rest, p_null: asNumber(pNull) };\n const span = toExtractSpan(source, parts);\n if (span) {\n mapped.source = 'input';\n mapped.span = span;\n } else if (isObjectLike(source) && parts[Number(source.part)] === 'image') {\n mapped.source = 'image';\n }\n if (Array.isArray(items)) {\n const confidences = items.map(item => (isObjectLike(item) ? item.confidence : undefined));\n if (confidences.every(confidence => typeof confidence === 'number')) {\n mapped.confidences = confidences;\n }\n const spans = items.map(item => toExtractSpan(isObjectLike(item) ? item.source : undefined, parts));\n if (spans.some(Boolean)) {\n mapped.spans = spans;\n }\n }\n return mapped;\n });\n}\n\nfunction toExtractSpan(source: unknown, parts: ExtractState['parts']): ExtractSpan | null {\n if (!isObjectLike(source) || source.type !== 'text') {\n return null;\n }\n const offset = parts[Number(source.part)];\n return typeof offset === 'number' ? [offset + Number(source.start), offset + Number(source.end)] : null;\n}\n"],"mappings":";;;;;;;;AAWA,MAAM,0BAA0B;AAChC,MAAM,kBAAkB;;;;;;AAaxB,SAAgB,eAAe,OAA8B;CAC3D,MAAM,SAAmB,CAAC;CAC1B,MAAM,YAAsB,CAAC;CAE7B,IAAI,SAAS;CAEb,MAAM,SAAS,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC;EAAE,MAAM;EAAQ,OAAO;CAAM,CAAC,EAAA,CAAG,KAAI,SAAQ;EAC1F,IAAI,CAAC,aAAa,IAAI,GACpB;EAEF,IAAI,KAAK,SAAS,QAAQ;GACxB,IAAI,OAAO,KAAK,SAAS,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,SAAS;IACpD,OAAO,KAAK,eAAe;IAC3B,OAAO;GACT;GACA,IAAI,KAAK,cAAc,mBACrB,UAAU,KAAK,eAAe;GAEhC;EACF;EACA,MAAM,OAAO,KAAK,SAAS,SAAS,KAAK,OAAO,UAAU,KAAK,KAAK;EACp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AO;CAET,MAAM,SAAS,MAAM,OAAO,OAAO,IAAI;CACvC,OAAO,OAAO,WAAW,WAAW,CAAC,SAAS,OAAO,OAAO,KAAK,GAAG,SAAS,OAAO,OAAO,GAAG,CAAC,IAAI;AACrG"}
|
|
@@ -38,6 +38,7 @@ import { postgresJsChannels } from "./config/postgres.js";
|
|
|
38
38
|
import { prismaChannels } from "./config/prisma.js";
|
|
39
39
|
import { redisChannels } from "./config/redis.js";
|
|
40
40
|
import { remixChannels } from "./config/remix.js";
|
|
41
|
+
import { tanstackAiChannels } from "./config/tanstack-ai.js";
|
|
41
42
|
import { tediousChannels } from "./config/tedious.js";
|
|
42
43
|
import { togetherAiChannels } from "./config/together-ai.js";
|
|
43
44
|
import { typesafeChannels } from "./config/typesafe.js";
|
|
@@ -100,6 +101,7 @@ const CHANNELS = {
|
|
|
100
101
|
...prismaChannels,
|
|
101
102
|
...redisChannels,
|
|
102
103
|
...remixChannels,
|
|
104
|
+
...tanstackAiChannels,
|
|
103
105
|
...tediousChannels,
|
|
104
106
|
...togetherAiChannels,
|
|
105
107
|
...typesafeChannels,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channels.js","names":[],"sources":["../../../src/orchestrion/channels.ts"],"sourcesContent":["import { amqplibChannels } from './config/amqplib';\nimport { anthropicAiChannels } from './config/anthropic-ai';\nimport { awsSdkChannels } from './config/aws-sdk';\nimport { clickhouseChannels } from './config/clickhouse';\nimport { cronChannels } from './config/cron';\nimport { dataloaderChannels } from './config/dataloader';\nimport { expressChannels } from './config/express';\nimport { firebaseChannels } from './config/firebase';\nimport { genericPoolChannels } from './config/generic-pool';\nimport { googleGenAiChannels } from './config/google-genai';\nimport { graphqlChannels } from './config/graphql';\nimport { groqChannels } from './config/groq';\nimport { hapiChannels } from './config/hapi';\nimport { honoChannels } from './config/hono';\nimport { ioredisChannels } from './config/ioredis';\nimport { kafkajsChannels } from './config/kafkajs';\nimport { knexChannels } from './config/knex';\nimport { koaChannels } from './config/koa';\nimport { langchainChannels } from './config/langchain';\nimport { langgraphChannels } from './config/langgraph';\nimport { lruMemoizerChannels } from './config/lru-memoizer';\nimport { mastraChannels } from './config/mastra';\nimport { mcpServerChannels } from './config/mcp-server';\nimport { mistralChannels } from './config/mistral';\nimport { mongodbChannels } from './config/mongodb';\nimport { mongooseChannels } from './config/mongoose';\nimport { mysql2Channels } from './config/mysql2';\nimport { mysqlChannels } from './config/mysql';\nimport { neonChannels } from './config/neon';\nimport { nestjsChannels } from './config/nestjs';\nimport { nodeCronChannels } from './config/node-cron';\nimport { nodeScheduleChannels } from './config/node-schedule';\nimport { openaiChannels } from './config/openai';\nimport { pgChannels } from './config/pg';\nimport { piAiChannels } from './config/pi-ai';\nimport { piDurableChannels } from './config/pi-durable';\nimport { postgresJsChannels } from './config/postgres';\nimport { prismaChannels } from './config/prisma';\nimport { redisChannels } from './config/redis';\nimport { remixChannels } from './config/remix';\nimport { tediousChannels } from './config/tedious';\nimport { togetherAiChannels } from './config/together-ai';\nimport { typesafeChannels } from './config/typesafe';\nimport { vercelAiChannels } from './config/vercel-ai';\n\n/**\n * Fully-qualified `diagnostics_channel` names that orchestrion publishes to.\n *\n * Orchestrion's transform always prefixes the configured `channelName` with\n * `orchestrion:${module.name}:`. So a config of\n * `{ channelName: 'query', module: { name: 'mysql' } }`\n * publishes to `orchestrion:mysql:query`.\n *\n * Subscribers (`integrations/<lib>/tracing-channel.ts`) consume the full\n * prefixed string from this map; the config files set only the unprefixed\n * suffix in `channelName`. Keeping both pieces in one file is what guarantees\n * they don't drift apart and silently stop firing.\n *\n * Kept sorted alphabetically by module so concurrent additions insert at different\n * points rather than all appending to the end (fewer merge conflicts).\n */\nexport const CHANNELS = {\n ...amqplibChannels,\n ...anthropicAiChannels,\n ...awsSdkChannels,\n ...clickhouseChannels,\n ...cronChannels,\n ...dataloaderChannels,\n ...expressChannels,\n ...firebaseChannels,\n ...genericPoolChannels,\n ...googleGenAiChannels,\n ...graphqlChannels,\n ...groqChannels,\n ...hapiChannels,\n ...honoChannels,\n ...ioredisChannels,\n ...kafkajsChannels,\n ...knexChannels,\n ...koaChannels,\n ...langchainChannels,\n ...langgraphChannels,\n ...lruMemoizerChannels,\n ...mastraChannels,\n ...mcpServerChannels,\n ...mistralChannels,\n ...mongodbChannels,\n ...mongooseChannels,\n ...mysql2Channels,\n ...mysqlChannels,\n ...neonChannels,\n ...nestjsChannels,\n ...nodeCronChannels,\n ...nodeScheduleChannels,\n ...openaiChannels,\n ...pgChannels,\n ...piAiChannels,\n ...piDurableChannels,\n ...postgresJsChannels,\n ...prismaChannels,\n ...redisChannels,\n ...remixChannels,\n ...tediousChannels,\n ...togetherAiChannels,\n ...typesafeChannels,\n ...vercelAiChannels,\n} as const;\n\nexport type ChannelName = (typeof CHANNELS)[keyof typeof CHANNELS];\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"channels.js","names":[],"sources":["../../../src/orchestrion/channels.ts"],"sourcesContent":["import { amqplibChannels } from './config/amqplib';\nimport { anthropicAiChannels } from './config/anthropic-ai';\nimport { awsSdkChannels } from './config/aws-sdk';\nimport { clickhouseChannels } from './config/clickhouse';\nimport { cronChannels } from './config/cron';\nimport { dataloaderChannels } from './config/dataloader';\nimport { expressChannels } from './config/express';\nimport { firebaseChannels } from './config/firebase';\nimport { genericPoolChannels } from './config/generic-pool';\nimport { googleGenAiChannels } from './config/google-genai';\nimport { graphqlChannels } from './config/graphql';\nimport { groqChannels } from './config/groq';\nimport { hapiChannels } from './config/hapi';\nimport { honoChannels } from './config/hono';\nimport { ioredisChannels } from './config/ioredis';\nimport { kafkajsChannels } from './config/kafkajs';\nimport { knexChannels } from './config/knex';\nimport { koaChannels } from './config/koa';\nimport { langchainChannels } from './config/langchain';\nimport { langgraphChannels } from './config/langgraph';\nimport { lruMemoizerChannels } from './config/lru-memoizer';\nimport { mastraChannels } from './config/mastra';\nimport { mcpServerChannels } from './config/mcp-server';\nimport { mistralChannels } from './config/mistral';\nimport { mongodbChannels } from './config/mongodb';\nimport { mongooseChannels } from './config/mongoose';\nimport { mysql2Channels } from './config/mysql2';\nimport { mysqlChannels } from './config/mysql';\nimport { neonChannels } from './config/neon';\nimport { nestjsChannels } from './config/nestjs';\nimport { nodeCronChannels } from './config/node-cron';\nimport { nodeScheduleChannels } from './config/node-schedule';\nimport { openaiChannels } from './config/openai';\nimport { pgChannels } from './config/pg';\nimport { piAiChannels } from './config/pi-ai';\nimport { piDurableChannels } from './config/pi-durable';\nimport { postgresJsChannels } from './config/postgres';\nimport { prismaChannels } from './config/prisma';\nimport { redisChannels } from './config/redis';\nimport { remixChannels } from './config/remix';\nimport { tanstackAiChannels } from './config/tanstack-ai';\nimport { tediousChannels } from './config/tedious';\nimport { togetherAiChannels } from './config/together-ai';\nimport { typesafeChannels } from './config/typesafe';\nimport { vercelAiChannels } from './config/vercel-ai';\n\n/**\n * Fully-qualified `diagnostics_channel` names that orchestrion publishes to.\n *\n * Orchestrion's transform always prefixes the configured `channelName` with\n * `orchestrion:${module.name}:`. So a config of\n * `{ channelName: 'query', module: { name: 'mysql' } }`\n * publishes to `orchestrion:mysql:query`.\n *\n * Subscribers (`integrations/<lib>/tracing-channel.ts`) consume the full\n * prefixed string from this map; the config files set only the unprefixed\n * suffix in `channelName`. Keeping both pieces in one file is what guarantees\n * they don't drift apart and silently stop firing.\n *\n * Kept sorted alphabetically by module so concurrent additions insert at different\n * points rather than all appending to the end (fewer merge conflicts).\n */\nexport const CHANNELS = {\n ...amqplibChannels,\n ...anthropicAiChannels,\n ...awsSdkChannels,\n ...clickhouseChannels,\n ...cronChannels,\n ...dataloaderChannels,\n ...expressChannels,\n ...firebaseChannels,\n ...genericPoolChannels,\n ...googleGenAiChannels,\n ...graphqlChannels,\n ...groqChannels,\n ...hapiChannels,\n ...honoChannels,\n ...ioredisChannels,\n ...kafkajsChannels,\n ...knexChannels,\n ...koaChannels,\n ...langchainChannels,\n ...langgraphChannels,\n ...lruMemoizerChannels,\n ...mastraChannels,\n ...mcpServerChannels,\n ...mistralChannels,\n ...mongodbChannels,\n ...mongooseChannels,\n ...mysql2Channels,\n ...mysqlChannels,\n ...neonChannels,\n ...nestjsChannels,\n ...nodeCronChannels,\n ...nodeScheduleChannels,\n ...openaiChannels,\n ...pgChannels,\n ...piAiChannels,\n ...piDurableChannels,\n ...postgresJsChannels,\n ...prismaChannels,\n ...redisChannels,\n ...remixChannels,\n ...tanstackAiChannels,\n ...tediousChannels,\n ...togetherAiChannels,\n ...typesafeChannels,\n ...vercelAiChannels,\n} as const;\n\nexport type ChannelName = (typeof CHANNELS)[keyof typeof CHANNELS];\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAa,WAAW;CACtB,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL"}
|
|
@@ -41,6 +41,7 @@ import { prismaConfig } from "./prisma.js";
|
|
|
41
41
|
import { redisConfig } from "./redis.js";
|
|
42
42
|
import { remixChannels, remixConfig } from "./remix.js";
|
|
43
43
|
import { remixV3Channels, remixV3Config } from "./remix-v3.js";
|
|
44
|
+
import { tanstackAiConfig } from "./tanstack-ai.js";
|
|
44
45
|
import { tediousConfig } from "./tedious.js";
|
|
45
46
|
import { togetherAiConfig } from "./together-ai.js";
|
|
46
47
|
import { typesafeConfig } from "./typesafe.js";
|
|
@@ -104,6 +105,7 @@ const SENTRY_INSTRUMENTATIONS = [
|
|
|
104
105
|
...redisConfig,
|
|
105
106
|
...remixConfig,
|
|
106
107
|
...remixV3Config,
|
|
108
|
+
...tanstackAiConfig,
|
|
107
109
|
...tediousConfig,
|
|
108
110
|
...togetherAiConfig,
|
|
109
111
|
...typesafeConfig,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/orchestrion/config/index.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\n\nimport { uniq } from '@sentry/core';\n\nimport { awsSdkConfig } from './aws-sdk';\nimport { amqplibConfig } from './amqplib';\nimport { anthropicAiConfig } from './anthropic-ai';\nimport { clickhouseConfig } from './clickhouse';\nimport { cronConfig } from './cron';\nimport { dataloaderConfig } from './dataloader';\nimport { expressConfig } from './express';\nimport { firebaseConfig } from './firebase';\nimport { genericPoolConfig } from './generic-pool';\nimport { googleGenAiConfig } from './google-genai';\nimport { graphqlConfig } from './graphql';\nimport { groqConfig } from './groq';\nimport { hapiConfig } from './hapi';\nimport { honoConfig } from './hono';\nimport { ioredisConfig } from './ioredis';\nimport { kafkajsConfig } from './kafkajs';\nimport { knexConfig } from './knex';\nimport { koaConfig } from './koa';\nimport { langchainConfig } from './langchain';\nimport { langgraphConfig } from './langgraph';\nimport { lruMemoizerConfig } from './lru-memoizer';\nimport { flueConfig } from './flue';\nimport { mastraConfig } from './mastra';\nimport { piAiConfig } from './pi-ai';\nimport { piDurableConfig } from './pi-durable';\nimport { mcpServerConfig } from './mcp-server';\nimport { mistralConfig } from './mistral';\nimport { mongodbConfig } from './mongodb';\nimport { mongooseConfig } from './mongoose';\nimport { mysql2Config } from './mysql2';\nimport { mysqlConfig } from './mysql';\nimport { neonConfig } from './neon';\nimport { nestjsConfig } from './nestjs';\nimport { nitroConfig } from './nitro';\nimport { nodeCronConfig } from './node-cron';\nimport { nodeScheduleConfig } from './node-schedule';\nimport { openaiConfig } from './openai';\nimport { pgConfig } from './pg';\nimport { postgresJsConfig } from './postgres';\nimport { prismaConfig } from './prisma';\nimport { redisConfig } from './redis';\nimport { remixConfig } from './remix';\nimport { remixV3Config } from './remix-v3';\nimport { tediousConfig } from './tedious';\nimport { togetherAiConfig } from './together-ai';\nimport { typesafeConfig } from './typesafe';\nimport { vercelAiConfig } from './vercel-ai';\n// Kept sorted alphabetically by module so concurrent additions insert at different\n// points rather than all appending to the end (fewer merge conflicts).\n\n/**\n * The orchestrion code-transform configs. Every instrumentable library is here\n * so the transform is all-or-nothing: whenever orchestrion is enabled, all of\n * these are injected. The channel LISTENERS may live elsewhere (e.g. the NestJS\n * one lives in `@sentry/nestjs`), but the config that decides what gets\n * transformed is centralized here.\n *\n * This module MUST stay pure, stateless data. It is loaded in more than one realm\n * at once — the build-time bundler plugin inlines it into the server chunk, while\n * `@sentry/server-runtime-injection`'s external `register` loads its own copy from\n * `node_modules` at runtime. Two identical, side-effect-free arrays are harmless;\n * any module-level mutable state here would silently diverge between those copies.\n */\nexport const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [\n ...amqplibConfig,\n ...anthropicAiConfig,\n ...awsSdkConfig,\n ...clickhouseConfig,\n ...cronConfig,\n ...dataloaderConfig,\n ...expressConfig,\n ...firebaseConfig,\n ...genericPoolConfig,\n ...googleGenAiConfig,\n ...graphqlConfig,\n ...groqConfig,\n ...hapiConfig,\n ...honoConfig,\n ...ioredisConfig,\n ...kafkajsConfig,\n ...knexConfig,\n ...koaConfig,\n ...langchainConfig,\n ...langgraphConfig,\n ...lruMemoizerConfig,\n ...flueConfig,\n ...mastraConfig,\n ...mcpServerConfig,\n ...mistralConfig,\n ...mongodbConfig,\n ...mongooseConfig,\n ...mysql2Config,\n ...mysqlConfig,\n ...neonConfig,\n ...nestjsConfig,\n ...nitroConfig,\n ...nodeCronConfig,\n ...nodeScheduleConfig,\n ...openaiConfig,\n ...pgConfig,\n ...piAiConfig,\n ...piDurableConfig,\n ...postgresJsConfig,\n ...prismaConfig,\n ...redisConfig,\n ...remixConfig,\n ...remixV3Config,\n ...tediousConfig,\n ...togetherAiConfig,\n ...typesafeConfig,\n ...vercelAiConfig,\n];\n\n/**\n * The subset of {@link SENTRY_INSTRUMENTATIONS} the RUNTIME loader\n * (`@sentry/server-runtime-injection`'s `register`, reached via `--import` or\n * `Sentry.init()`) can actually apply.\n *\n * Registration-only configs (native-channel libraries such as `ai` v7,\n * `ioredis`, `@redis/client`, `mysql2`, `mongoose`) carry the custom\n * `MODULE_REGISTRATION_TRANSFORM` operator. That operator is wired into the\n * BUNDLER plugins only (see `orchestrion/bundler/moduleInjectedTransform.ts`,\n * applied via `bundler/options.ts`'s `customTransforms`); the runtime loader's\n * `initialize()` receives no custom transforms. Attempting one of these at\n * runtime therefore throws `TypeError: transform is not a function`, which the\n * loader misreports as the always-on \"`@sentry/server-runtime-injection` was\n * bundled ... loads uninstrumented\" warning even though nothing is wrong.\n *\n * Excluding them at runtime is correct, not just a way to silence the warning:\n * these libraries publish their own tracing channels, and their integrations\n * subscribe through `setupOnce()` / `waitForTracingChannelBinding`,\n * independently of the module-injected snippet. That snippet only fires\n * `orchestrion.module-injected`, which drives the `setup()` /\n * `invokeOrchestrionInstrumentation` path; for a native-channel version that\n * path subscribes to the injected `orchestrion:*` channels the library never\n * publishes — a no-op. So running these at runtime would add no spans. The\n * snippet earns its keep only on the BUNDLER path — notably bundler-only SDKs\n * (e.g. `@sentry/cloudflare`) that discover a loaded module via that event to\n * instantiate its integration factory. `@sentry/node` registers its\n * integrations statically, so it does not need it.\n */\nexport const SENTRY_RUNTIME_INSTRUMENTATIONS: InstrumentationConfig[] = SENTRY_INSTRUMENTATIONS.filter(\n config => !config.transform,\n);\n\n/**\n * The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`\n * merged with any caller-provided `instrumentations` (e.g. `['mysql']`).\n *\n * Bundler plugins MUST ensure these are actually bundled rather than\n * externalized: an externalized dependency is resolved from `node_modules` at\n * runtime and never passes through the code transform's `onLoad`, so its\n * diagnostics_channel calls are silently never injected. This includes a\n * plugin's custom `instrumentations`, otherwise those extra packages can stay\n * externalized and their transform never runs.\n */\nexport function instrumentedModuleNames(instrumentations: InstrumentationConfig[] = []): string[] {\n return [\n ...uniq([...SENTRY_INSTRUMENTATIONS, ...instrumentations].map(i => i.module.name)),\n // Additional things that need to be bundled but are not covered by the above\n // Remix needs to bundle this so @remix-run/server-runtime is _also_ bundled\n '@remix-run/node',\n ];\n}\n\n/** The instrumented module names from the default Sentry config, with no custom additions. */\nexport const INSTRUMENTED_MODULE_NAMES: string[] = instrumentedModuleNames();\n\n/**\n * The package names the SDK instruments through the orchestrion module transform (its\n * diagnostics-channel injection). Pass these to a server bundler's \"keep external\" option so the\n * packages load through Node's module loader — the only path the transform can hook — instead of\n * being inlined into the server bundle. A framework that has no Sentry bundler plugin (e.g. eve, via\n * `build.externalDependencies`) is the main caller; a listed package the app doesn't use is simply\n * ignored by the bundler.\n *\n * Unlike {@link INSTRUMENTED_MODULE_NAMES}, this is the plain instrumented set with no bundler-only\n * additions — those force a helper package to be *bundled*, the opposite of keeping it external.\n */\nexport function getInstrumentedModuleNames(): string[] {\n return uniq(SENTRY_INSTRUMENTATIONS.map(instrumentation => instrumentation.module.name));\n}\n\n/**\n * Returns `external` with any instrumented packages removed, so a bundler that\n * uses an \"external\" denylist (esbuild, Bun, Rollup) still bundles — and thus\n * transforms — them. Matches an exact package name (`'mysql'`) or a subpath\n * (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`\n * is returned unchanged.\n *\n * Pass `moduleNames` from `instrumentedModuleNames(options.instrumentations)` so\n * custom instrumentations are stripped too; it defaults to the Sentry config\n * list. (Vite uses an `ssr.noExternal` allowlist instead, so it consumes\n * `instrumentedModuleNames` directly rather than this helper.)\n */\nexport function withoutInstrumentedExternals(\n external: readonly string[] | undefined,\n moduleNames: string[] = INSTRUMENTED_MODULE_NAMES,\n): string[] | undefined {\n if (!external) {\n return undefined;\n }\n return external.filter(entry => !moduleNames.some(name => entry === name || entry.startsWith(`${name}/`)));\n}\n\n// This is exported so that the nestjs package can use it to subscribe to the channels.\nexport { nestjsChannels } from './nestjs';\n// This is exported so that the remix package can use it to subscribe to the channels.\nexport { remixChannels } from './remix';\n// Exported so the remix package can subscribe to the Remix 3 channels, and hand only these configs to\n// the browser transform.\nexport { remixV3Channels, remixV3Config } from './remix-v3';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,MAAa,0BAAmD;CAC9D,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,kCAA2D,wBAAwB,QAC9F,WAAU,CAAC,OAAO,SACpB;;;;;;;;;;;;AAaA,SAAgB,wBAAwB,mBAA4C,CAAC,GAAa;CAChG,OAAO,CACL,GAAG,KAAK,CAAC,GAAG,yBAAyB,GAAG,gBAAgB,CAAC,CAAC,KAAI,MAAK,EAAE,OAAO,IAAI,CAAC,GAGjF,iBACF;AACF;;AAGA,MAAa,4BAAsC,wBAAwB;;;;;;;;;;;;AAa3E,SAAgB,6BAAuC;CACrD,OAAO,KAAK,wBAAwB,KAAI,oBAAmB,gBAAgB,OAAO,IAAI,CAAC;AACzF;;;;;;;;;;;;;AAcA,SAAgB,6BACd,UACA,cAAwB,2BACF;CACtB,IAAI,CAAC,UACH;CAEF,OAAO,SAAS,QAAO,UAAS,CAAC,YAAY,MAAK,SAAQ,UAAU,QAAQ,MAAM,WAAW,GAAG,KAAK,EAAE,CAAC,CAAC;AAC3G"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/orchestrion/config/index.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\n\nimport { uniq } from '@sentry/core';\n\nimport { awsSdkConfig } from './aws-sdk';\nimport { amqplibConfig } from './amqplib';\nimport { anthropicAiConfig } from './anthropic-ai';\nimport { clickhouseConfig } from './clickhouse';\nimport { cronConfig } from './cron';\nimport { dataloaderConfig } from './dataloader';\nimport { expressConfig } from './express';\nimport { firebaseConfig } from './firebase';\nimport { genericPoolConfig } from './generic-pool';\nimport { googleGenAiConfig } from './google-genai';\nimport { graphqlConfig } from './graphql';\nimport { groqConfig } from './groq';\nimport { hapiConfig } from './hapi';\nimport { honoConfig } from './hono';\nimport { ioredisConfig } from './ioredis';\nimport { kafkajsConfig } from './kafkajs';\nimport { knexConfig } from './knex';\nimport { koaConfig } from './koa';\nimport { langchainConfig } from './langchain';\nimport { langgraphConfig } from './langgraph';\nimport { lruMemoizerConfig } from './lru-memoizer';\nimport { flueConfig } from './flue';\nimport { mastraConfig } from './mastra';\nimport { piAiConfig } from './pi-ai';\nimport { piDurableConfig } from './pi-durable';\nimport { mcpServerConfig } from './mcp-server';\nimport { mistralConfig } from './mistral';\nimport { mongodbConfig } from './mongodb';\nimport { mongooseConfig } from './mongoose';\nimport { mysql2Config } from './mysql2';\nimport { mysqlConfig } from './mysql';\nimport { neonConfig } from './neon';\nimport { nestjsConfig } from './nestjs';\nimport { nitroConfig } from './nitro';\nimport { nodeCronConfig } from './node-cron';\nimport { nodeScheduleConfig } from './node-schedule';\nimport { openaiConfig } from './openai';\nimport { pgConfig } from './pg';\nimport { postgresJsConfig } from './postgres';\nimport { prismaConfig } from './prisma';\nimport { redisConfig } from './redis';\nimport { remixConfig } from './remix';\nimport { remixV3Config } from './remix-v3';\nimport { tanstackAiConfig } from './tanstack-ai';\nimport { tediousConfig } from './tedious';\nimport { togetherAiConfig } from './together-ai';\nimport { typesafeConfig } from './typesafe';\nimport { vercelAiConfig } from './vercel-ai';\n// Kept sorted alphabetically by module so concurrent additions insert at different\n// points rather than all appending to the end (fewer merge conflicts).\n\n/**\n * The orchestrion code-transform configs. Every instrumentable library is here\n * so the transform is all-or-nothing: whenever orchestrion is enabled, all of\n * these are injected. The channel LISTENERS may live elsewhere (e.g. the NestJS\n * one lives in `@sentry/nestjs`), but the config that decides what gets\n * transformed is centralized here.\n *\n * This module MUST stay pure, stateless data. It is loaded in more than one realm\n * at once — the build-time bundler plugin inlines it into the server chunk, while\n * `@sentry/server-runtime-injection`'s external `register` loads its own copy from\n * `node_modules` at runtime. Two identical, side-effect-free arrays are harmless;\n * any module-level mutable state here would silently diverge between those copies.\n */\nexport const SENTRY_INSTRUMENTATIONS: InstrumentationConfig[] = [\n ...amqplibConfig,\n ...anthropicAiConfig,\n ...awsSdkConfig,\n ...clickhouseConfig,\n ...cronConfig,\n ...dataloaderConfig,\n ...expressConfig,\n ...firebaseConfig,\n ...genericPoolConfig,\n ...googleGenAiConfig,\n ...graphqlConfig,\n ...groqConfig,\n ...hapiConfig,\n ...honoConfig,\n ...ioredisConfig,\n ...kafkajsConfig,\n ...knexConfig,\n ...koaConfig,\n ...langchainConfig,\n ...langgraphConfig,\n ...lruMemoizerConfig,\n ...flueConfig,\n ...mastraConfig,\n ...mcpServerConfig,\n ...mistralConfig,\n ...mongodbConfig,\n ...mongooseConfig,\n ...mysql2Config,\n ...mysqlConfig,\n ...neonConfig,\n ...nestjsConfig,\n ...nitroConfig,\n ...nodeCronConfig,\n ...nodeScheduleConfig,\n ...openaiConfig,\n ...pgConfig,\n ...piAiConfig,\n ...piDurableConfig,\n ...postgresJsConfig,\n ...prismaConfig,\n ...redisConfig,\n ...remixConfig,\n ...remixV3Config,\n ...tanstackAiConfig,\n ...tediousConfig,\n ...togetherAiConfig,\n ...typesafeConfig,\n ...vercelAiConfig,\n];\n\n/**\n * The subset of {@link SENTRY_INSTRUMENTATIONS} the RUNTIME loader\n * (`@sentry/server-runtime-injection`'s `register`, reached via `--import` or\n * `Sentry.init()`) can actually apply.\n *\n * Registration-only configs (native-channel libraries such as `ai` v7,\n * `ioredis`, `@redis/client`, `mysql2`, `mongoose`) carry the custom\n * `MODULE_REGISTRATION_TRANSFORM` operator. That operator is wired into the\n * BUNDLER plugins only (see `orchestrion/bundler/moduleInjectedTransform.ts`,\n * applied via `bundler/options.ts`'s `customTransforms`); the runtime loader's\n * `initialize()` receives no custom transforms. Attempting one of these at\n * runtime therefore throws `TypeError: transform is not a function`, which the\n * loader misreports as the always-on \"`@sentry/server-runtime-injection` was\n * bundled ... loads uninstrumented\" warning even though nothing is wrong.\n *\n * Excluding them at runtime is correct, not just a way to silence the warning:\n * these libraries publish their own tracing channels, and their integrations\n * subscribe through `setupOnce()` / `waitForTracingChannelBinding`,\n * independently of the module-injected snippet. That snippet only fires\n * `orchestrion.module-injected`, which drives the `setup()` /\n * `invokeOrchestrionInstrumentation` path; for a native-channel version that\n * path subscribes to the injected `orchestrion:*` channels the library never\n * publishes — a no-op. So running these at runtime would add no spans. The\n * snippet earns its keep only on the BUNDLER path — notably bundler-only SDKs\n * (e.g. `@sentry/cloudflare`) that discover a loaded module via that event to\n * instantiate its integration factory. `@sentry/node` registers its\n * integrations statically, so it does not need it.\n */\nexport const SENTRY_RUNTIME_INSTRUMENTATIONS: InstrumentationConfig[] = SENTRY_INSTRUMENTATIONS.filter(\n config => !config.transform,\n);\n\n/**\n * The unique set of package names instrumented by `SENTRY_INSTRUMENTATIONS`\n * merged with any caller-provided `instrumentations` (e.g. `['mysql']`).\n *\n * Bundler plugins MUST ensure these are actually bundled rather than\n * externalized: an externalized dependency is resolved from `node_modules` at\n * runtime and never passes through the code transform's `onLoad`, so its\n * diagnostics_channel calls are silently never injected. This includes a\n * plugin's custom `instrumentations`, otherwise those extra packages can stay\n * externalized and their transform never runs.\n */\nexport function instrumentedModuleNames(instrumentations: InstrumentationConfig[] = []): string[] {\n return [\n ...uniq([...SENTRY_INSTRUMENTATIONS, ...instrumentations].map(i => i.module.name)),\n // Additional things that need to be bundled but are not covered by the above\n // Remix needs to bundle this so @remix-run/server-runtime is _also_ bundled\n '@remix-run/node',\n ];\n}\n\n/** The instrumented module names from the default Sentry config, with no custom additions. */\nexport const INSTRUMENTED_MODULE_NAMES: string[] = instrumentedModuleNames();\n\n/**\n * The package names the SDK instruments through the orchestrion module transform (its\n * diagnostics-channel injection). Pass these to a server bundler's \"keep external\" option so the\n * packages load through Node's module loader — the only path the transform can hook — instead of\n * being inlined into the server bundle. A framework that has no Sentry bundler plugin (e.g. eve, via\n * `build.externalDependencies`) is the main caller; a listed package the app doesn't use is simply\n * ignored by the bundler.\n *\n * Unlike {@link INSTRUMENTED_MODULE_NAMES}, this is the plain instrumented set with no bundler-only\n * additions — those force a helper package to be *bundled*, the opposite of keeping it external.\n */\nexport function getInstrumentedModuleNames(): string[] {\n return uniq(SENTRY_INSTRUMENTATIONS.map(instrumentation => instrumentation.module.name));\n}\n\n/**\n * Returns `external` with any instrumented packages removed, so a bundler that\n * uses an \"external\" denylist (esbuild, Bun, Rollup) still bundles — and thus\n * transforms — them. Matches an exact package name (`'mysql'`) or a subpath\n * (`'mysql/lib/...'`); wildcard/other patterns are left untouched. `undefined`\n * is returned unchanged.\n *\n * Pass `moduleNames` from `instrumentedModuleNames(options.instrumentations)` so\n * custom instrumentations are stripped too; it defaults to the Sentry config\n * list. (Vite uses an `ssr.noExternal` allowlist instead, so it consumes\n * `instrumentedModuleNames` directly rather than this helper.)\n */\nexport function withoutInstrumentedExternals(\n external: readonly string[] | undefined,\n moduleNames: string[] = INSTRUMENTED_MODULE_NAMES,\n): string[] | undefined {\n if (!external) {\n return undefined;\n }\n return external.filter(entry => !moduleNames.some(name => entry === name || entry.startsWith(`${name}/`)));\n}\n\n// This is exported so that the nestjs package can use it to subscribe to the channels.\nexport { nestjsChannels } from './nestjs';\n// This is exported so that the remix package can use it to subscribe to the channels.\nexport { remixChannels } from './remix';\n// Exported so the remix package can subscribe to the Remix 3 channels, and hand only these configs to\n// the browser transform.\nexport { remixV3Channels, remixV3Config } from './remix-v3';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,MAAa,0BAAmD;CAC9D,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,kCAA2D,wBAAwB,QAC9F,WAAU,CAAC,OAAO,SACpB;;;;;;;;;;;;AAaA,SAAgB,wBAAwB,mBAA4C,CAAC,GAAa;CAChG,OAAO,CACL,GAAG,KAAK,CAAC,GAAG,yBAAyB,GAAG,gBAAgB,CAAC,CAAC,KAAI,MAAK,EAAE,OAAO,IAAI,CAAC,GAGjF,iBACF;AACF;;AAGA,MAAa,4BAAsC,wBAAwB;;;;;;;;;;;;AAa3E,SAAgB,6BAAuC;CACrD,OAAO,KAAK,wBAAwB,KAAI,oBAAmB,gBAAgB,OAAO,IAAI,CAAC;AACzF;;;;;;;;;;;;;AAcA,SAAgB,6BACd,UACA,cAAwB,2BACF;CACtB,IAAI,CAAC,UACH;CAEF,OAAO,SAAS,QAAO,UAAS,CAAC,YAAY,MAAK,SAAQ,UAAU,QAAQ,MAAM,WAAW,GAAG,KAAK,EAAE,CAAC,CAAC;AAC3G"}
|
|
@@ -6,6 +6,7 @@ const VERSION_RANGE = ">=8.0.0-rc.15 <9";
|
|
|
6
6
|
const PRISMA_ASYNC_TERMINALS = [
|
|
7
7
|
"aggregate",
|
|
8
8
|
"first",
|
|
9
|
+
"firstOrThrow",
|
|
9
10
|
"create",
|
|
10
11
|
"createAndCount",
|
|
11
12
|
"upsert",
|
|
@@ -40,6 +41,7 @@ const prismaModuleNames = getModuleNames(prismaConfig);
|
|
|
40
41
|
const prismaChannels = {
|
|
41
42
|
PRISMA_AGGREGATE: "orchestrion:@prisma/orm-family-sql:aggregate",
|
|
42
43
|
PRISMA_FIRST: "orchestrion:@prisma/orm-family-sql:first",
|
|
44
|
+
PRISMA_FIRST_OR_THROW: "orchestrion:@prisma/orm-family-sql:firstOrThrow",
|
|
43
45
|
PRISMA_CREATE: "orchestrion:@prisma/orm-family-sql:create",
|
|
44
46
|
PRISMA_CREATE_AND_COUNT: "orchestrion:@prisma/orm-family-sql:createAndCount",
|
|
45
47
|
PRISMA_UPSERT: "orchestrion:@prisma/orm-family-sql:upsert",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prisma.js","names":[],"sources":["../../../../src/orchestrion/config/prisma.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\nimport { getModuleNames } from './module-names';\n\n// Prisma 8 has no tracing surface, so its ORM terminals are wrapped directly. Apps install\n// `@prisma/orm-postgres`, but `CollectionBase` lives in the transitive `@prisma/orm-family-sql`.\nconst MODULE_NAME = '@prisma/orm-family-sql';\nconst ORM_CLIENT_FILE = 'dist/orm-client.mjs';\n\nconst VERSION_RANGE = '>=8.0.0-rc.15 <9';\n\nexport const PRISMA_ASYNC_TERMINALS = [\n 'aggregate',\n 'first',\n 'create',\n 'createAndCount',\n 'upsert',\n 'update',\n 'updateAndCount',\n 'delete',\n 'deleteAndCount',\n] as const;\n\n// These return a single-use thenable whose query runs on consumption. `Sync` on purpose: the `Async`/`Auto`\n// wrapper calls `.then()` on non-native thenables and would consume the result before the app does.\nexport const PRISMA_LAZY_TERMINALS = ['all', 'createAll', 'updateAll', 'deleteAll'] as const;\n\ntype PrismaTerminal = (typeof PRISMA_ASYNC_TERMINALS)[number] | (typeof PRISMA_LAZY_TERMINALS)[number];\n\nfunction terminalConfig(methodName: PrismaTerminal, kind: 'Async' | 'Sync'): InstrumentationConfig {\n return {\n channelName: methodName,\n module: { name: MODULE_NAME, versionRange: VERSION_RANGE, filePath: ORM_CLIENT_FILE },\n functionQuery: { className: 'CollectionBase', methodName, kind },\n };\n}\n\nexport const prismaConfig: InstrumentationConfig[] = [\n ...PRISMA_ASYNC_TERMINALS.map(methodName => terminalConfig(methodName, 'Async')),\n ...PRISMA_LAZY_TERMINALS.map(methodName => terminalConfig(methodName, 'Sync')),\n];\n\nexport const prismaModuleNames = getModuleNames(prismaConfig);\n\nexport const prismaChannels = {\n PRISMA_AGGREGATE: 'orchestrion:@prisma/orm-family-sql:aggregate',\n PRISMA_FIRST: 'orchestrion:@prisma/orm-family-sql:first',\n PRISMA_CREATE: 'orchestrion:@prisma/orm-family-sql:create',\n PRISMA_CREATE_AND_COUNT: 'orchestrion:@prisma/orm-family-sql:createAndCount',\n PRISMA_UPSERT: 'orchestrion:@prisma/orm-family-sql:upsert',\n PRISMA_UPDATE: 'orchestrion:@prisma/orm-family-sql:update',\n PRISMA_UPDATE_AND_COUNT: 'orchestrion:@prisma/orm-family-sql:updateAndCount',\n PRISMA_DELETE: 'orchestrion:@prisma/orm-family-sql:delete',\n PRISMA_DELETE_AND_COUNT: 'orchestrion:@prisma/orm-family-sql:deleteAndCount',\n PRISMA_ALL: 'orchestrion:@prisma/orm-family-sql:all',\n PRISMA_CREATE_ALL: 'orchestrion:@prisma/orm-family-sql:createAll',\n PRISMA_UPDATE_ALL: 'orchestrion:@prisma/orm-family-sql:updateAll',\n PRISMA_DELETE_ALL: 'orchestrion:@prisma/orm-family-sql:deleteAll',\n} as const;\n"],"mappings":";;AAKA,MAAM,cAAc;AACpB,MAAM,kBAAkB;AAExB,MAAM,gBAAgB;AAEtB,MAAa,yBAAyB;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAIA,MAAa,wBAAwB;CAAC;CAAO;CAAa;CAAa;AAAW;AAIlF,SAAS,eAAe,YAA4B,MAA+C;CACjG,OAAO;EACL,aAAa;EACb,QAAQ;GAAE,MAAM;GAAa,cAAc;GAAe,UAAU;EAAgB;EACpF,eAAe;GAAE,WAAW;GAAkB;GAAY;EAAK;CACjE;AACF;AAEA,MAAa,eAAwC,CACnD,GAAG,uBAAuB,KAAI,eAAc,eAAe,YAAY,OAAO,CAAC,GAC/E,GAAG,sBAAsB,KAAI,eAAc,eAAe,YAAY,MAAM,CAAC,CAC/E;AAEA,MAAa,oBAAoB,eAAe,YAAY;AAE5D,MAAa,iBAAiB;CAC5B,kBAAkB;CAClB,cAAc;CACd,eAAe;CACf,yBAAyB;CACzB,eAAe;CACf,eAAe;CACf,yBAAyB;CACzB,eAAe;CACf,yBAAyB;CACzB,YAAY;CACZ,mBAAmB;CACnB,mBAAmB;CACnB,mBAAmB;AACrB"}
|
|
1
|
+
{"version":3,"file":"prisma.js","names":[],"sources":["../../../../src/orchestrion/config/prisma.ts"],"sourcesContent":["import type { InstrumentationConfig } from '../apmTypes';\nimport { getModuleNames } from './module-names';\n\n// Prisma 8 has no tracing surface, so its ORM terminals are wrapped directly. Apps install\n// `@prisma/orm-postgres`, but `CollectionBase` lives in the transitive `@prisma/orm-family-sql`.\nconst MODULE_NAME = '@prisma/orm-family-sql';\nconst ORM_CLIENT_FILE = 'dist/orm-client.mjs';\n\nconst VERSION_RANGE = '>=8.0.0-rc.15 <9';\n\nexport const PRISMA_ASYNC_TERMINALS = [\n 'aggregate',\n 'first',\n // Added in rc.18. orchestrion's range check can't order RC numbers, so older RCs get its constructor fallback:\n // every collection gains an own async `firstOrThrow` that rejects when called, and a custom collection's own\n // `firstOrThrow` is wrapped as async. We only support the latest RC.\n 'firstOrThrow',\n 'create',\n 'createAndCount',\n 'upsert',\n 'update',\n 'updateAndCount',\n 'delete',\n 'deleteAndCount',\n] as const;\n\n// These return a single-use thenable whose query runs on consumption. `Sync` on purpose: the `Async`/`Auto`\n// wrapper calls `.then()` on non-native thenables and would consume the result before the app does.\nexport const PRISMA_LAZY_TERMINALS = ['all', 'createAll', 'updateAll', 'deleteAll'] as const;\n\ntype PrismaTerminal = (typeof PRISMA_ASYNC_TERMINALS)[number] | (typeof PRISMA_LAZY_TERMINALS)[number];\n\nfunction terminalConfig(methodName: PrismaTerminal, kind: 'Async' | 'Sync'): InstrumentationConfig {\n return {\n channelName: methodName,\n module: { name: MODULE_NAME, versionRange: VERSION_RANGE, filePath: ORM_CLIENT_FILE },\n functionQuery: { className: 'CollectionBase', methodName, kind },\n };\n}\n\nexport const prismaConfig: InstrumentationConfig[] = [\n ...PRISMA_ASYNC_TERMINALS.map(methodName => terminalConfig(methodName, 'Async')),\n ...PRISMA_LAZY_TERMINALS.map(methodName => terminalConfig(methodName, 'Sync')),\n];\n\nexport const prismaModuleNames = getModuleNames(prismaConfig);\n\nexport const prismaChannels = {\n PRISMA_AGGREGATE: 'orchestrion:@prisma/orm-family-sql:aggregate',\n PRISMA_FIRST: 'orchestrion:@prisma/orm-family-sql:first',\n PRISMA_FIRST_OR_THROW: 'orchestrion:@prisma/orm-family-sql:firstOrThrow',\n PRISMA_CREATE: 'orchestrion:@prisma/orm-family-sql:create',\n PRISMA_CREATE_AND_COUNT: 'orchestrion:@prisma/orm-family-sql:createAndCount',\n PRISMA_UPSERT: 'orchestrion:@prisma/orm-family-sql:upsert',\n PRISMA_UPDATE: 'orchestrion:@prisma/orm-family-sql:update',\n PRISMA_UPDATE_AND_COUNT: 'orchestrion:@prisma/orm-family-sql:updateAndCount',\n PRISMA_DELETE: 'orchestrion:@prisma/orm-family-sql:delete',\n PRISMA_DELETE_AND_COUNT: 'orchestrion:@prisma/orm-family-sql:deleteAndCount',\n PRISMA_ALL: 'orchestrion:@prisma/orm-family-sql:all',\n PRISMA_CREATE_ALL: 'orchestrion:@prisma/orm-family-sql:createAll',\n PRISMA_UPDATE_ALL: 'orchestrion:@prisma/orm-family-sql:updateAll',\n PRISMA_DELETE_ALL: 'orchestrion:@prisma/orm-family-sql:deleteAll',\n} as const;\n"],"mappings":";;AAKA,MAAM,cAAc;AACpB,MAAM,kBAAkB;AAExB,MAAM,gBAAgB;AAEtB,MAAa,yBAAyB;CACpC;CACA;CAIA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAIA,MAAa,wBAAwB;CAAC;CAAO;CAAa;CAAa;AAAW;AAIlF,SAAS,eAAe,YAA4B,MAA+C;CACjG,OAAO;EACL,aAAa;EACb,QAAQ;GAAE,MAAM;GAAa,cAAc;GAAe,UAAU;EAAgB;EACpF,eAAe;GAAE,WAAW;GAAkB;GAAY;EAAK;CACjE;AACF;AAEA,MAAa,eAAwC,CACnD,GAAG,uBAAuB,KAAI,eAAc,eAAe,YAAY,OAAO,CAAC,GAC/E,GAAG,sBAAsB,KAAI,eAAc,eAAe,YAAY,MAAM,CAAC,CAC/E;AAEA,MAAa,oBAAoB,eAAe,YAAY;AAE5D,MAAa,iBAAiB;CAC5B,kBAAkB;CAClB,cAAc;CACd,uBAAuB;CACvB,eAAe;CACf,yBAAyB;CACzB,eAAe;CACf,eAAe;CACf,yBAAyB;CACzB,eAAe;CACf,yBAAyB;CACzB,YAAY;CACZ,mBAAmB;CACnB,mBAAmB;CACnB,mBAAmB;AACrB"}
|