import { startSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, addBreadcrumb, SPAN_STATUS_ERROR } from '@sentry/core'; const patchedStatement = /* @__PURE__ */ new WeakSet(); function instrumentD1PreparedStatementQueries(statement, query) { if (patchedStatement.has(statement)) { return statement; } statement.first = new Proxy(statement.first, { apply(target, thisArg, args) { return startSpan(createStartSpanOptions(query, "first"), async () => { const res = await Reflect.apply(target, thisArg, args); createD1Breadcrumb(query, "first"); return res; }); } }); statement.run = new Proxy(statement.run, { apply(target, thisArg, args) { return startSpan(createStartSpanOptions(query, "run"), async (span) => { const d1Response = await Reflect.apply(target, thisArg, args); applyD1ReturnObjectToSpan(span, d1Response); createD1Breadcrumb(query, "run", d1Response); return d1Response; }); } }); statement.all = new Proxy(statement.all, { apply(target, thisArg, args) { return startSpan(createStartSpanOptions(query, "all"), async (span) => { const d1Result = await Reflect.apply(target, thisArg, args); applyD1ReturnObjectToSpan(span, d1Result); createD1Breadcrumb(query, "all", d1Result); return d1Result; }); } }); statement.raw = new Proxy(statement.raw, { apply(target, thisArg, args) { return startSpan(createStartSpanOptions(query, "raw"), async () => { const res = await Reflect.apply(target, thisArg, args); createD1Breadcrumb(query, "raw"); return res; }); } }); patchedStatement.add(statement); return statement; } function instrumentD1PreparedStatement(statement, query) { statement.bind = new Proxy(statement.bind, { apply(target, thisArg, args) { return instrumentD1PreparedStatementQueries(Reflect.apply(target, thisArg, args), query); } }); return instrumentD1PreparedStatementQueries(statement, query); } function applyD1ReturnObjectToSpan(span, d1Result) { if (!d1Result.success) { span.setStatus({ code: SPAN_STATUS_ERROR }); } span.setAttributes(getAttributesFromD1Response(d1Result)); } function getAttributesFromD1Response(d1Result) { return { "cloudflare.d1.duration": d1Result.meta.duration, "cloudflare.d1.rows_read": d1Result.meta.rows_read, "cloudflare.d1.rows_written": d1Result.meta.rows_written }; } function createD1Breadcrumb(query, type, d1Result) { addBreadcrumb({ category: "query", message: query, data: { ...d1Result ? getAttributesFromD1Response(d1Result) : {}, "cloudflare.d1.query_type": type } }); } function createStartSpanOptions(query, type) { return { op: "db.query", name: query, attributes: { "cloudflare.d1.query_type": type, [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.db.cloudflare.d1" } }; } function instrumentD1WithSentry(db) { db.prepare = new Proxy(db.prepare, { apply(target, thisArg, args) { const [query] = args; return instrumentD1PreparedStatement(Reflect.apply(target, thisArg, args), query); } }); return db; } export { instrumentD1WithSentry }; //# sourceMappingURL=instrumentD1.js.map