@tejasdev/prisma-otel-middleware 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ritwikcp-ctrl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,225 @@
1
- # Temporary Holding Version
1
+ # @tejasdev/prisma-otel-middleware
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Production-ready OpenTelemetry tracing middleware for **Prisma 8**, built exclusively on Prisma 8's public `CrossFamilyMiddleware` SPI (`@prisma/orm-framework/components/runtime`) and the ADR 271 activity lifecycle (`activityStarted`, `activityEnded`, `activityFinalized`).
4
+
5
+ Prisma 8 deliberately removed `@prisma/instrumentation` and legacy `$on` / `$use` event hooks in favor of composable runtime middleware. `@tejasdev/prisma-otel-middleware` fills that observability gap with zero private APIs, zero monkey-patching, and leak-free span tracking across **SQLite**, **PostgreSQL**, **MySQL**, **MariaDB**, and **MongoDB**.
6
+
7
+ ---
8
+
9
+ ## Features
10
+
11
+ - **100% Public Prisma 8 SPI** — Plain `CrossFamilyMiddleware` object using `activityStarted`, `activityEnded`, and `activityFinalized` (ADR 271 & ADR 291 compliant).
12
+ - **Cross-Database by Default** — Works out of the box with `@prisma/orm-sqlite`, `@prisma/orm-postgres`, and `@prisma/orm-mongo` (`familyId` omitted unless explicitly configured).
13
+ - **Accurate Span Nesting** — Reconstructs the Prisma activity tree (`transaction` -> `orm-call` -> `statement`, plus custom `<client-kind>` activities) and nests root Prisma spans under active HTTP / Sentry OpenTelemetry contexts.
14
+ - **Leak-Free Span Registry** — Atomic `take()` removal on `activityEnded` plus defensive cleanup in `activityFinalized` guarantees zero leaked spans even on abrupt cancellation or query failure.
15
+ - **No PII in Spans** — Parameter values are never read or attached; `db.statement` is only populated when a pre-lowered SQL template string is already present on the activity.
16
+ - **Sampling & Custom Attributes** — Filter noisy activities (`shouldTrace`) before span creation and attach custom span attributes (`customAttributes`).
17
+ - **Strict TypeScript** — Built with `strict: true`, `exactOptionalPropertyTypes: true`, and full `.d.ts` declarations.
18
+
19
+ ---
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ npm install @tejasdev/prisma-otel-middleware @opentelemetry/api
25
+ ```
26
+
27
+ ### Peer Dependencies
28
+
29
+ | Package | Version | Notes |
30
+ | --- | --- | --- |
31
+ | `@opentelemetry/api` | `^1.9.0` | Required OpenTelemetry API |
32
+ | `@prisma/orm-framework` | `^8.0.0-rc.28` | Included automatically via `@prisma/orm-sqlite`, `@prisma/orm-postgres`, or `@prisma/orm-mongo` |
33
+
34
+ ---
35
+
36
+ ## Quick Start & Registration
37
+
38
+ Register `createOtelMiddleware(...)` **last** in your client's `middleware` array:
39
+ 1. Root Prisma spans automatically nest beneath any active HTTP or Sentry span (`useActiveParentForRoot: true`, the default).
40
+ 2. Upstream middleware (such as `@prisma/orm-extension-middleware-cache`, `lints()`, and `budgets()`) run first, while `activityEnded` still observes cache hits (`prisma.activity.source = 'middleware'`).
41
+
42
+ ### SQLite (`@prisma/orm-sqlite/runtime`)
43
+
44
+ ```typescript
45
+ import sqlite from '@prisma/orm-sqlite/runtime';
46
+ import { contractFromJson } from '@prisma/orm-sqlite/static';
47
+ import { createOtelMiddleware } from '@tejasdev/prisma-otel-middleware';
48
+ import type { Contract } from './contract.d.js';
49
+ import contractJson from './contract.json' with { type: 'json' };
50
+
51
+ export const contract = contractFromJson<Contract>(contractJson);
52
+
53
+ export const db = sqlite({
54
+ contract,
55
+ path: process.env['DATABASE_PATH'] ?? './dev.db',
56
+ middleware: [
57
+ createOtelMiddleware({
58
+ serviceName: 'my-app',
59
+ }),
60
+ ],
61
+ });
62
+ ```
63
+
64
+ ### PostgreSQL (`@prisma/orm-postgres/runtime`)
65
+
66
+ ```typescript
67
+ import postgres from '@prisma/orm-postgres/runtime';
68
+ import { contractFromJson } from '@prisma/orm-postgres/static';
69
+ import { budgets, lints } from '@prisma/orm-postgres/family-runtime';
70
+ import { createOtelMiddleware } from '@tejasdev/prisma-otel-middleware';
71
+ import type { Contract } from './contract.d.js';
72
+ import contractJson from './contract.json' with { type: 'json' };
73
+
74
+ export const contract = contractFromJson<Contract>(contractJson);
75
+
76
+ export const db = postgres({
77
+ contract,
78
+ url: process.env['DATABASE_URL']!,
79
+ middleware: [
80
+ lints(),
81
+ budgets({ maxRows: 10_000 }),
82
+ createOtelMiddleware({
83
+ serviceName: 'orders-service',
84
+ }),
85
+ ],
86
+ });
87
+ ```
88
+
89
+ ### MongoDB (`@prisma/orm-mongo/runtime`)
90
+
91
+ Because `createOtelMiddleware()` omits `familyId` by default, it satisfies `CrossFamilyMiddleware` and attaches to MongoDB clients without triggering `RUNTIME.MIDDLEWARE_FAMILY_MISMATCH`:
92
+
93
+ ```typescript
94
+ import mongo from '@prisma/orm-mongo/runtime';
95
+ import { contractFromJson } from '@prisma/orm-mongo/static';
96
+ import { createOtelMiddleware } from '@tejasdev/prisma-otel-middleware';
97
+ import type { Contract } from './contract.d.js';
98
+ import contractJson from './contract.json' with { type: 'json' };
99
+
100
+ export const contract = contractFromJson<Contract>(contractJson);
101
+
102
+ export const db = mongo({
103
+ contract,
104
+ url: process.env['DATABASE_URL']!,
105
+ middleware: [
106
+ createOtelMiddleware({
107
+ serviceName: 'catalog-service',
108
+ }),
109
+ ],
110
+ });
111
+ ```
112
+
113
+ ---
114
+
115
+ ## Configuration Options
116
+
117
+ ```typescript
118
+ import { createOtelMiddleware } from '@tejasdev/prisma-otel-middleware';
119
+
120
+ const otelMiddleware = createOtelMiddleware({
121
+ name: 'opentelemetry-tracing',
122
+ serviceName: 'orders-service',
123
+ useActiveParentForRoot: true,
124
+ shouldTrace: (activity) => activity.kind !== 'orm-call',
125
+ customAttributes: (activity, ctx) => ({
126
+ 'prisma.scope': ctx.scope,
127
+ 'prisma.in_transaction': ctx.inTransaction(),
128
+ }),
129
+ });
130
+ ```
131
+
132
+ | Option | Type | Default | Description |
133
+ | --- | --- | --- | --- |
134
+ | `name` | `string` | `'opentelemetry-tracing'` | Descriptive middleware label surfaced in Prisma error messages. |
135
+ | `serviceName` | `string` | `'prisma'` | Prefix for span names (`${serviceName}.${activity.kind}`) and tracer scope (`${serviceName}-otel-middleware`). |
136
+ | `familyId` | `'sql' \| 'mongo'` | `undefined` | Optional family restriction. Omit for database-agnostic `CrossFamilyMiddleware`. Setting a mismatched family throws `RUNTIME.MIDDLEWARE_FAMILY_MISMATCH` at startup. |
137
+ | `dbSystem` | `DbSystem` | Auto-detected from `ctx.contract.target` | Sets `db.system` (`'postgresql'`, `'sqlite'`, `'mongodb'`, `'mysql'`, `'mariadb'`). |
138
+ | `useActiveParentForRoot` | `boolean` | `true` | When no Prisma parent exists, nests under `context.active()`. Set `false` to always start a new root trace (`ROOT_CONTEXT`). |
139
+ | `shouldTrace` | `(activity, ctx) => boolean` | `undefined` | Sampling/filtering predicate evaluated before span creation. Child activities still nest beneath the nearest traced ancestor. |
140
+ | `customAttributes` | `(activity, ctx) => Attributes` | `undefined` | Attaches custom span attributes on start. Base `prisma.*` and `db.*` attributes take precedence. |
141
+ | `tracerProvider` | `TracerProvider` | Global `trace` API | Optional OpenTelemetry `TracerProvider` override (useful for isolated test suites). |
142
+
143
+ ---
144
+
145
+ ## Span Model & Attributes
146
+
147
+ | Activity Kind | Span Name | Attributes |
148
+ | --- | --- | --- |
149
+ | `transaction` | `${serviceName}.transaction` | `prisma.activity.kind`, `prisma.activity.id`, `db.system` |
150
+ | `orm-call` | `${serviceName}.orm-call` | `prisma.activity.kind`, `prisma.activity.id`, `db.system` |
151
+ | `statement` | `${serviceName}.statement` | `prisma.activity.kind`, `prisma.activity.id`, `db.system`, `prisma.statement.returns`, optional `db.statement` (template metadata only) |
152
+ | `<client-kind>` | `${serviceName}.<client-kind>` | `prisma.activity.kind`, `prisma.activity.id`, `db.system` |
153
+
154
+ ### End & Finalization Attributes
155
+
156
+ - `prisma.activity.outcome` — `'succeeded' | 'failed' | 'stopped'`
157
+ - `prisma.activity.latency_ms` — execution latency in ms (from `result.latencyMs`, when present)
158
+ - `prisma.activity.row_count` — returned row count (from `result.rowCount`, when present)
159
+ - `prisma.activity.affected_rows` — affected row count (from `result.stats.affectedRows`, when present)
160
+ - `prisma.activity.source` — `'driver' | 'middleware' | 'client'` (when present)
161
+ - `prisma.activity.stopped` — `true` when `outcome === 'stopped'` (span status stays `UNSET`)
162
+ - `prisma.activity.finalized_outcome` — `'committed' | 'rolled-back' | 'unknown'` (recorded if `activityFinalized` performs defensive cleanup)
163
+
164
+ ### Span Status Semantics
165
+
166
+ - `succeeded` -> `SpanStatusCode.OK`
167
+ - `failed` -> `SpanStatusCode.ERROR` (plus `span.recordException(result.error)` if an error payload is attached)
168
+ - `stopped` -> `SpanStatusCode.UNSET` with `prisma.activity.stopped = true`
169
+
170
+ ### PII Safety
171
+
172
+ Parameter values (`params`, `values`) are **never** inspected or emitted onto spans. `db.statement` is only attached if a pre-lowered SQL template string already exists on `activity.plan.sql`; pre-lowering AST plans are never reconstructed into SQL strings. Value-level redaction belongs to dedicated audit middleware.
173
+
174
+ ---
175
+
176
+ ## Graceful Shutdown
177
+
178
+ Applications are responsible for shutting down the OpenTelemetry `BasicTracerProvider` (and closing the Prisma client) on `SIGTERM` / `SIGINT` so buffered spans are flushed before process exit:
179
+
180
+ ```typescript
181
+ import { trace } from '@opentelemetry/api';
182
+ import {
183
+ BasicTracerProvider,
184
+ BatchSpanProcessor,
185
+ } from '@opentelemetry/sdk-trace-base';
186
+ import { db } from './prisma/db.js';
187
+
188
+ const provider = new BasicTracerProvider({
189
+ spanProcessors: [new BatchSpanProcessor(exporter)],
190
+ });
191
+ trace.setGlobalTracerProvider(provider);
192
+
193
+ async function shutdown(signal: string): Promise<void> {
194
+ console.log(`Received ${signal}, flushing telemetry and closing database...`);
195
+ await db.close();
196
+ await provider.shutdown();
197
+ process.exit(0);
198
+ }
199
+
200
+ process.once('SIGTERM', () => void shutdown('SIGTERM'));
201
+ process.once('SIGINT', () => void shutdown('SIGINT'));
202
+ ```
203
+
204
+ ---
205
+
206
+ ## Development & Verification
207
+
208
+ ```bash
209
+ # Build TypeScript + declarations
210
+ npm run build
211
+
212
+ # Typecheck
213
+ npm run typecheck
214
+
215
+ # Run SQLite & PostgreSQL (PGlite) integration suites
216
+ npm test
217
+ ```
218
+
219
+ > **Note on SQLite Tests:** `@prisma/orm-sqlite` uses Node.js's built-in `node:sqlite` (`DatabaseSync`), which requires Node.js `>=22.13` / `>=24` to execute `test:sqlite`.
220
+
221
+ ---
222
+
223
+ ## License
224
+
225
+ [MIT](./LICENSE)
@@ -0,0 +1,3 @@
1
+ export { createOtelMiddleware } from './middleware.js';
2
+ export type { DbSystem, FamilyId, OtelCrossFamilyMiddleware, OtelFamilyMiddleware, OtelMiddleware, OtelMiddlewareOptions, } from './types.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACvD,YAAY,EACV,QAAQ,EACR,QAAQ,EACR,yBAAyB,EACzB,oBAAoB,EACpB,cAAc,EACd,qBAAqB,GACtB,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { createOtelMiddleware } from './middleware.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { OtelMiddleware, OtelMiddlewareOptions } from './types.js';
2
+ export declare function createOtelMiddleware<const TOptions extends OtelMiddlewareOptions | undefined = undefined>(options?: TOptions): OtelMiddleware<TOptions>;
3
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAGV,cAAc,EACd,qBAAqB,EACtB,MAAM,YAAY,CAAC;AAGpB,wBAAgB,oBAAoB,CAClC,KAAK,CAAC,QAAQ,SAAS,qBAAqB,GAAG,SAAS,GAAG,SAAS,EACpE,OAAO,CAAC,EAAE,QAAQ,GAAG,cAAc,CAAC,QAAQ,CAAC,CAoF9C"}
@@ -0,0 +1,60 @@
1
+ import { ROOT_CONTEXT, context, trace, } from '@opentelemetry/api';
2
+ import { SpanRegistry } from './registry.js';
3
+ import { DEFAULT_MIDDLEWARE_NAME, DEFAULT_SERVICE_NAME, PACKAGE_VERSION, buildStartAttributes, finalizeSpanOnEnded, formatSpanName, formatTracerName, } from './spans.js';
4
+ export function createOtelMiddleware(options) {
5
+ const middlewareName = options?.name ?? DEFAULT_MIDDLEWARE_NAME;
6
+ const serviceName = options?.serviceName ?? DEFAULT_SERVICE_NAME;
7
+ const useActiveParentForRoot = options?.useActiveParentForRoot ?? true;
8
+ const tracerName = formatTracerName(serviceName);
9
+ const registry = new SpanRegistry();
10
+ const getTracer = () => {
11
+ const provider = options?.tracerProvider;
12
+ return provider !== undefined
13
+ ? provider.getTracer(tracerName, PACKAGE_VERSION)
14
+ : trace.getTracer(tracerName, PACKAGE_VERSION);
15
+ };
16
+ const resolveRootContext = () => useActiveParentForRoot ? context.active() : ROOT_CONTEXT;
17
+ const baseMiddleware = {
18
+ name: middlewareName,
19
+ async activityStarted(activity, ctx) {
20
+ if (options?.shouldTrace !== undefined && !options.shouldTrace(activity, ctx)) {
21
+ return;
22
+ }
23
+ const parentContext = ctx.parent !== undefined
24
+ ? (registry.resolveParentContext(ctx.parent) ?? resolveRootContext())
25
+ : resolveRootContext();
26
+ const attributes = buildStartAttributes(activity, ctx, options?.dbSystem, options?.customAttributes);
27
+ const spanName = formatSpanName(serviceName, activity);
28
+ const span = getTracer().startSpan(spanName, { attributes }, parentContext);
29
+ const spanContext = trace.setSpan(parentContext, span);
30
+ registry.set(activity.id, ctx, { span, context: spanContext });
31
+ },
32
+ async activityEnded(activity, result, _ctx) {
33
+ const entry = registry.take(activity.id);
34
+ if (entry === undefined) {
35
+ return;
36
+ }
37
+ finalizeSpanOnEnded(entry.span, result);
38
+ },
39
+ async activityFinalized(activity, result, _ctx) {
40
+ const entry = registry.take(activity.id);
41
+ if (entry === undefined) {
42
+ return;
43
+ }
44
+ entry.span.setAttribute('prisma.activity.finalized_outcome', result.outcome);
45
+ entry.span.end();
46
+ },
47
+ registrySize() {
48
+ return registry.size;
49
+ },
50
+ };
51
+ if (options?.familyId !== undefined) {
52
+ const familyMiddleware = {
53
+ ...baseMiddleware,
54
+ familyId: options.familyId,
55
+ };
56
+ return familyMiddleware;
57
+ }
58
+ return baseMiddleware;
59
+ }
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AAC,EAAE,CAAC,CAAC;YACzC,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;gBACxB,OAAO;YACT,CAAC;YAED,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,mCAAmC,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;YAC7E,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;QACnB,CAAC;QAED,YAAY;YACV,OAAO,QAAQ,CAAC,IAAI,CAAC;QACvB,CAAC;KACF,CAAC;IAEF,IAAI,OAAO,EAAE,QAAQ,KAAK,SAAS,EAAE,CAAC;QACpC,MAAM,gBAAgB,GAAyB;YAC7C,GAAG,cAAc;YACjB,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC;QACF,OAAO,gBAA4C,CAAC;IACtD,CAAC;IAED,OAAO,cAA0C,CAAC;AACpD,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { Context, Span } from '@opentelemetry/api';
2
+ import type { ActivityContext } from '@prisma/orm-framework/components/runtime';
3
+ export interface SpanEntry {
4
+ readonly span: Span;
5
+ readonly context: Context;
6
+ }
7
+ export declare class SpanRegistry {
8
+ private readonly entries;
9
+ private readonly contextIds;
10
+ set(activityId: string, ctx: ActivityContext, entry: SpanEntry): void;
11
+ resolveParentContext(parentCtx: ActivityContext | undefined): Context | undefined;
12
+ take(activityId: string): SpanEntry | undefined;
13
+ get size(): number;
14
+ }
15
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAKhF,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC;IACpB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B;AAUD,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAgC;IACxD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA0C;IAMrE,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,eAAe,EAAE,KAAK,EAAE,SAAS,GAAG,IAAI;IAUrE,oBAAoB,CAAC,SAAS,EAAE,eAAe,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS;IAmBjF,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS;IAW/C,IAAI,IAAI,IAAI,MAAM,CAEjB;CACF"}
@@ -0,0 +1,53 @@
1
+ /*
2
+ * Leak-safe registry correlating Prisma 8 activities (`activity.id` and
3
+ * `ActivityContext` references) with their active OpenTelemetry spans.
4
+ *
5
+ * Primary leak prevention uses {@link take} in `activityEnded`, backed by
6
+ * defensive cleanup in `activityFinalized`. Parent lookup uses a `WeakMap` keyed
7
+ * by `ActivityContext` so context references never prevent garbage collection.
8
+ */
9
+ export class SpanRegistry {
10
+ entries = new Map();
11
+ contextIds = new WeakMap();
12
+ /*
13
+ * Registers a started span for `activityId` and indexes `ctx` so child
14
+ * activities can resolve this span via `ctx.parent`.
15
+ */
16
+ set(activityId, ctx, entry) {
17
+ this.entries.set(activityId, entry);
18
+ this.contextIds.set(ctx, activityId);
19
+ }
20
+ /*
21
+ * Walks up the `ctx.parent` chain to find the nearest enclosing traced
22
+ * activity's OpenTelemetry `Context`. Walking past untraced ancestors keeps
23
+ * span nesting intact when `shouldTrace` skips an intermediate activity.
24
+ */
25
+ resolveParentContext(parentCtx) {
26
+ let cursor = parentCtx;
27
+ while (cursor !== undefined) {
28
+ const parentId = this.contextIds.get(cursor);
29
+ if (parentId !== undefined) {
30
+ const entry = this.entries.get(parentId);
31
+ if (entry !== undefined) {
32
+ return entry.context;
33
+ }
34
+ }
35
+ cursor = cursor.parent;
36
+ }
37
+ return undefined;
38
+ }
39
+ // Atomically retrieves and removes the entry for `activityId`.
40
+ // Returns `undefined` if the activity was already taken or never traced.
41
+ take(activityId) {
42
+ const entry = this.entries.get(activityId);
43
+ if (entry !== undefined) {
44
+ this.entries.delete(activityId);
45
+ }
46
+ return entry;
47
+ }
48
+ //Number of active spans currently held in the registry.
49
+ get size() {
50
+ return this.entries.size;
51
+ }
52
+ }
53
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.js","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAWA;;;;;;;GAOG;AACH,MAAM,OAAO,YAAY;IACN,OAAO,GAAG,IAAI,GAAG,EAAqB,CAAC;IACvC,UAAU,GAAG,IAAI,OAAO,EAA2B,CAAC;IAErE;;;OAGG;IACH,GAAG,CAAC,UAAkB,EAAE,GAAoB,EAAE,KAAgB;QAC5D,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;QACpC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;IACvC,CAAC;IAED;;;;OAIG;IACH,oBAAoB,CAAC,SAAsC;QACzD,IAAI,MAAM,GAAG,SAAS,CAAC;QACvB,OAAO,MAAM,KAAK,SAAS,EAAE,CAAC;YAC5B,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YAC7C,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;gBAC3B,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;gBACzC,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;oBACxB,OAAO,KAAK,CAAC,OAAO,CAAC;gBACvB,CAAC;YACH,CAAC;YACD,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;QACzB,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAGA,+DAA+D;IAChE,yEAAyE;IAEzE,IAAI,CAAC,UAAkB;QACrB,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAC3C,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QAClC,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAGA,wDAAwD;IAEzD,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IAC3B,CAAC;CACF"}
@@ -0,0 +1,28 @@
1
+ import { type Attributes, type Span } from '@opentelemetry/api';
2
+ import type { Activity, ActivityContext, ActivityEndedResult } from '@prisma/orm-framework/components/runtime';
3
+ import type { DbSystem } from './types.js';
4
+ export declare const PACKAGE_VERSION = "0.1.1";
5
+ export declare const DEFAULT_SERVICE_NAME = "prisma";
6
+ export declare const DEFAULT_MIDDLEWARE_NAME = "opentelemetry-tracing";
7
+ /**
8
+ * Formats the OpenTelemetry tracer scope name (`${serviceName}-otel-middleware`).
9
+ */
10
+ export declare function formatTracerName(serviceName: string): string;
11
+ /**
12
+ * Maps a Prisma 8 activity to its OpenTelemetry span name (`${serviceName}.${activity.kind}`).
13
+ */
14
+ export declare function formatSpanName(serviceName: string, activity: Activity): string;
15
+ export declare function resolveDbSystem(explicitDbSystem: DbSystem | undefined, activity: Activity, ctx: ActivityContext): DbSystem;
16
+ /**
17
+ * Builds initial span attributes for `activityStarted`.
18
+ *
19
+ * Strictly avoids reading parameter values or reconstructing SQL text from ASTs:
20
+ * `db.statement` is attached only if a pre-lowered SQL template string is
21
+ * already present on `activity.plan.sql`.
22
+ */
23
+ export declare function buildStartAttributes(activity: Activity, ctx: ActivityContext, explicitDbSystem: DbSystem | undefined, customAttributes?: ((activity: Activity, ctx: ActivityContext) => Attributes) | undefined): Attributes;
24
+ /**
25
+ * Applies outcome, timing, row-count, and status semantics to a span on `activityEnded`.
26
+ */
27
+ export declare function finalizeSpanOnEnded(span: Span, result: ActivityEndedResult): void;
28
+ //# sourceMappingURL=spans.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spans.d.ts","sourceRoot":"","sources":["../src/spans.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,UAAU,EAEf,KAAK,IAAI,EACV,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EACV,QAAQ,EACR,eAAe,EACf,mBAAmB,EACpB,MAAM,0CAA0C,CAAC;AAClD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C,eAAO,MAAM,eAAe,UAAU,CAAC;AACvC,eAAO,MAAM,oBAAoB,WAAW,CAAC;AAC7C,eAAO,MAAM,uBAAuB,0BAA0B,CAAC;AAY/D;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,MAAM,CAE9E;AAKD,wBAAgB,eAAe,CAC7B,gBAAgB,EAAE,QAAQ,GAAG,SAAS,EACtC,QAAQ,EAAE,QAAQ,EAClB,GAAG,EAAE,eAAe,GACnB,QAAQ,CAkCV;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,QAAQ,EAClB,GAAG,EAAE,eAAe,EACpB,gBAAgB,EAAE,QAAQ,GAAG,SAAS,EACtC,gBAAgB,CAAC,EAAE,CAAC,CAAC,QAAQ,EAAE,QAAQ,EAAE,GAAG,EAAE,eAAe,KAAK,UAAU,CAAC,GAAG,SAAS,GACxF,UAAU,CAmBZ;AAYD;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAiDjF"}
package/dist/spans.js ADDED
@@ -0,0 +1,128 @@
1
+ import { SpanStatusCode, } from '@opentelemetry/api';
2
+ export const PACKAGE_VERSION = '0.1.1';
3
+ export const DEFAULT_SERVICE_NAME = 'prisma';
4
+ export const DEFAULT_MIDDLEWARE_NAME = 'opentelemetry-tracing';
5
+ const TARGET_TO_DB_SYSTEM = {
6
+ postgres: 'postgresql',
7
+ postgresql: 'postgresql',
8
+ sqlite: 'sqlite',
9
+ mongo: 'mongodb',
10
+ mongodb: 'mongodb',
11
+ mysql: 'mysql',
12
+ mariadb: 'mariadb',
13
+ };
14
+ /**
15
+ * Formats the OpenTelemetry tracer scope name (`${serviceName}-otel-middleware`).
16
+ */
17
+ export function formatTracerName(serviceName) {
18
+ return `${serviceName}-otel-middleware`;
19
+ }
20
+ /**
21
+ * Maps a Prisma 8 activity to its OpenTelemetry span name (`${serviceName}.${activity.kind}`).
22
+ */
23
+ export function formatSpanName(serviceName, activity) {
24
+ return `${serviceName}.${activity.kind}`;
25
+ }
26
+ /*
27
+ * Resolves `db.system` from explicit option, `ctx.contract`, or `plan.meta`.
28
+ */
29
+ export function resolveDbSystem(explicitDbSystem, activity, ctx) {
30
+ if (explicitDbSystem !== undefined && explicitDbSystem.length > 0) {
31
+ return explicitDbSystem;
32
+ }
33
+ const contract = ctx.contract;
34
+ const contractTarget = typeof contract?.target === 'string' ? contract.target.toLowerCase() : undefined;
35
+ if (contractTarget !== undefined && contractTarget.length > 0) {
36
+ return TARGET_TO_DB_SYSTEM[contractTarget] ?? contractTarget;
37
+ }
38
+ if (activity.kind === 'statement') {
39
+ const planMeta = activity.plan?.meta;
40
+ const planTarget = typeof planMeta?.target === 'string' ? planMeta.target.toLowerCase() : undefined;
41
+ if (planTarget !== undefined && planTarget.length > 0) {
42
+ return TARGET_TO_DB_SYSTEM[planTarget] ?? planTarget;
43
+ }
44
+ }
45
+ const contractFamily = typeof contract?.targetFamily === 'string'
46
+ ? contract.targetFamily.toLowerCase()
47
+ : undefined;
48
+ if (contractFamily !== undefined && contractFamily.length > 0) {
49
+ return TARGET_TO_DB_SYSTEM[contractFamily] ?? contractFamily;
50
+ }
51
+ return 'unknown';
52
+ }
53
+ /**
54
+ * Builds initial span attributes for `activityStarted`.
55
+ *
56
+ * Strictly avoids reading parameter values or reconstructing SQL text from ASTs:
57
+ * `db.statement` is attached only if a pre-lowered SQL template string is
58
+ * already present on `activity.plan.sql`.
59
+ */
60
+ export function buildStartAttributes(activity, ctx, explicitDbSystem, customAttributes) {
61
+ const custom = customAttributes?.(activity, ctx);
62
+ const attributes = custom !== undefined ? { ...custom } : {};
63
+ attributes['prisma.activity.kind'] = activity.kind;
64
+ attributes['prisma.activity.id'] = activity.id;
65
+ attributes['db.system'] = resolveDbSystem(explicitDbSystem, activity, ctx);
66
+ if (activity.kind === 'statement') {
67
+ const planWithSql = activity.plan;
68
+ if (typeof planWithSql?.sql === 'string' && planWithSql.sql.length > 0) {
69
+ attributes['db.statement'] = planWithSql.sql;
70
+ }
71
+ if (typeof activity.returns === 'string') {
72
+ attributes['prisma.statement.returns'] = activity.returns;
73
+ }
74
+ }
75
+ return attributes;
76
+ }
77
+ function isRecordExceptionInput(value) {
78
+ if (value instanceof Error || typeof value === 'string') {
79
+ return true;
80
+ }
81
+ if (typeof value !== 'object' || value === null) {
82
+ return false;
83
+ }
84
+ return 'message' in value || 'name' in value || 'code' in value;
85
+ }
86
+ /**
87
+ * Applies outcome, timing, row-count, and status semantics to a span on `activityEnded`.
88
+ */
89
+ export function finalizeSpanOnEnded(span, result) {
90
+ span.setAttribute('prisma.activity.outcome', result.outcome);
91
+ if ('latencyMs' in result && typeof result.latencyMs === 'number') {
92
+ span.setAttribute('prisma.activity.latency_ms', result.latencyMs);
93
+ }
94
+ if ('rowCount' in result && typeof result.rowCount === 'number') {
95
+ span.setAttribute('prisma.activity.row_count', result.rowCount);
96
+ }
97
+ if ('stats' in result &&
98
+ result.stats !== undefined &&
99
+ typeof result.stats.affectedRows === 'number') {
100
+ span.setAttribute('prisma.activity.affected_rows', result.stats.affectedRows);
101
+ }
102
+ if ('source' in result && typeof result.source === 'string') {
103
+ span.setAttribute('prisma.activity.source', result.source);
104
+ }
105
+ if (result.outcome === 'failed') {
106
+ const maybeError = result.error;
107
+ if (maybeError !== undefined && maybeError !== null) {
108
+ span.recordException(isRecordExceptionInput(maybeError) ? maybeError : String(maybeError));
109
+ }
110
+ const message = maybeError instanceof Error
111
+ ? maybeError.message
112
+ : typeof maybeError === 'string'
113
+ ? maybeError
114
+ : undefined;
115
+ span.setStatus(message !== undefined
116
+ ? { code: SpanStatusCode.ERROR, message }
117
+ : { code: SpanStatusCode.ERROR });
118
+ }
119
+ else if (result.outcome === 'stopped') {
120
+ span.setAttribute('prisma.activity.stopped', true);
121
+ // Intentionally leave span status UNSET when the caller stopped reading early.
122
+ }
123
+ else if (result.outcome === 'succeeded') {
124
+ span.setStatus({ code: SpanStatusCode.OK });
125
+ }
126
+ span.end();
127
+ }
128
+ //# sourceMappingURL=spans.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spans.js","sourceRoot":"","sources":["../src/spans.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,GAIf,MAAM,oBAAoB,CAAC;AAQ5B,MAAM,CAAC,MAAM,eAAe,GAAG,OAAO,CAAC;AACvC,MAAM,CAAC,MAAM,oBAAoB,GAAG,QAAQ,CAAC;AAC7C,MAAM,CAAC,MAAM,uBAAuB,GAAG,uBAAuB,CAAC;AAE/D,MAAM,mBAAmB,GAA6B;IACpD,QAAQ,EAAE,YAAY;IACtB,UAAU,EAAE,YAAY;IACxB,MAAM,EAAE,QAAQ;IAChB,KAAK,EAAE,SAAS;IAChB,OAAO,EAAE,SAAS;IAClB,KAAK,EAAE,OAAO;IACd,OAAO,EAAE,SAAS;CACnB,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,gBAAgB,CAAC,WAAmB;IAClD,OAAO,GAAG,WAAW,kBAAkB,CAAC;AAC1C,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,cAAc,CAAC,WAAmB,EAAE,QAAkB;IACpE,OAAO,GAAG,WAAW,IAAI,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AI,UAAU,KAAK,IAAI,EAAE,CAAC;YACpD,IAAI,CAAC,eAAe,CAClB,sBAAsB,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CACrE,CAAC;QACJ,CAAC;QACD,MAAM,OAAO,GACX,UAAU,YAAY,KAAK;YACzB,CAAC,CAAC,UAAU,CAAC,OAAO;YACpB,CAAC,CAAC,OAAO,UAAU,KAAK,QAAQ;gBAC9B,CAAC,CAAC,UAAU;gBACZ,CAAC,CAAC,SAAS,CAAC;QAClB,IAAI,CAAC,SAAS,CACZ,OAAO,KAAK,SAAS;YACnB,CAAC,CAAC,EAAE,IAAI,EAAE,cAAc,CAAC,KAAK,EAAE,OAAO,EAAE;YACzC,CAAC,CAAC,EAAE,IAAI,EAAE,cAAc,CAAC,KAAK,EAAE,CACnC,CAAC;IACJ,CAAC;SAAM,IAAI,MAAM,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;QACxC,IAAI,CAAC,YAAY,CAAC,yBAAyB,EAAE,IAAI,CAAC,CAAC;QACnD,+EAA+E;IACjF,CAAC;SAAM,IAAI,MAAM,CAAC,OAAO,KAAK,WAAW,EAAE,CAAC;QAC1C,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,cAAc,CAAC,EAAE,EAAE,CAAC,CAAC;IAC9C,CAAC;IAED,IAAI,CAAC,GAAG,EAAE,CAAC;AACb,CAAC"}
@@ -0,0 +1,98 @@
1
+ import type { Attributes, TracerProvider } from '@opentelemetry/api';
2
+ import type { Activity, ActivityContext, CrossFamilyMiddleware, RuntimeMiddleware } from '@prisma/orm-framework/components/runtime';
3
+ /**
4
+ * Prisma 8 database family identifier.
5
+ *
6
+ * Leave `familyId` unset when authoring database-agnostic middleware so it can
7
+ * be attached to SQLite, PostgreSQL, MySQL, MariaDB, and MongoDB clients alike.
8
+ * Setting `'sql'` or `'mongo'` restricts the middleware to that family and causes
9
+ * `RUNTIME.MIDDLEWARE_FAMILY_MISMATCH` if attached to another family's runtime.
10
+ */
11
+ export type FamilyId = 'sql' | 'mongo';
12
+ /**
13
+ * OpenTelemetry `db.system` semantic convention values for Prisma 8 targets.
14
+ */
15
+ export type DbSystem = 'postgresql' | 'sqlite' | 'mongodb' | 'mysql' | 'mariadb' | (string & {});
16
+ /**
17
+ * Configuration options for {@link createOtelMiddleware}.
18
+ */
19
+ export interface OtelMiddlewareOptions {
20
+ /**
21
+ * Descriptive middleware name surfaced in Prisma error envelopes and logs.
22
+ * Uniqueness is not enforced by Prisma 8.
23
+ *
24
+ * @default 'opentelemetry-tracing'
25
+ */
26
+ readonly name?: string;
27
+ /**
28
+ * Prefix used for span names (`${serviceName}.${activity.kind}`) and tracer
29
+ * instrumentation scope (`${serviceName}-otel-middleware`).
30
+ *
31
+ * @default 'prisma'
32
+ */
33
+ readonly serviceName?: string;
34
+ /**
35
+ * Explicit database family restriction (`'sql'` or `'mongo'`).
36
+ * Omit for database-agnostic {@link CrossFamilyMiddleware}.
37
+ */
38
+ readonly familyId?: FamilyId;
39
+ /**
40
+ * Explicit `db.system` attribute value. When omitted, the middleware infers it
41
+ * from `ctx.contract.target` (e.g., `'postgres'` -> `'postgresql'`,
42
+ * `'sqlite'` -> `'sqlite'`, `'mongo'` -> `'mongodb'`).
43
+ */
44
+ readonly dbSystem?: DbSystem;
45
+ /**
46
+ * When `true` and an activity has no Prisma parent (`ctx.parent === undefined`),
47
+ * the span nests beneath `context.active()` (e.g., an active HTTP or Sentry span).
48
+ * When `false`, root activities always start a fresh root trace (`ROOT_CONTEXT`).
49
+ *
50
+ * @default true
51
+ */
52
+ readonly useActiveParentForRoot?: boolean;
53
+ /**
54
+ * Optional sampling/filtering predicate invoked in `activityStarted` before any
55
+ * span is created. Return `false` to skip tracing noisy activities.
56
+ */
57
+ readonly shouldTrace?: (activity: Activity, ctx: ActivityContext) => boolean;
58
+ /**
59
+ * Optional callback to attach custom OpenTelemetry attributes when a span starts.
60
+ * Base `prisma.*` and `db.*` attributes take precedence over conflicting keys.
61
+ */
62
+ readonly customAttributes?: (activity: Activity, ctx: ActivityContext) => Attributes;
63
+ /**
64
+ * Optional OpenTelemetry `TracerProvider` override. Defaults to the global
65
+ * provider registered via `@opentelemetry/api` `trace.setGlobalTracerProvider`.
66
+ */
67
+ readonly tracerProvider?: TracerProvider;
68
+ }
69
+ /**
70
+ * Cross-family OpenTelemetry middleware instance returned by {@link createOtelMiddleware}.
71
+ */
72
+ export interface OtelCrossFamilyMiddleware extends CrossFamilyMiddleware {
73
+ /**
74
+ * Returns the number of currently active (unended) spans held in the internal
75
+ * registry. Exposed for leak verification in tests.
76
+ */
77
+ registrySize(): number;
78
+ }
79
+ /**
80
+ * Family-restricted OpenTelemetry middleware instance returned when `familyId`
81
+ * is explicitly configured.
82
+ */
83
+ export interface OtelFamilyMiddleware extends RuntimeMiddleware {
84
+ readonly familyId: FamilyId;
85
+ /**
86
+ * Returns the number of currently active (unended) spans held in the internal
87
+ * registry. Exposed for leak verification in tests.
88
+ */
89
+ registrySize(): number;
90
+ }
91
+ /**
92
+ * Resolves the returned middleware contract type based on whether `familyId`
93
+ * is specified in options.
94
+ */
95
+ export type OtelMiddleware<TOptions extends OtelMiddlewareOptions | undefined = undefined> = TOptions extends {
96
+ readonly familyId: FamilyId;
97
+ } ? OtelFamilyMiddleware : OtelCrossFamilyMiddleware;
98
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACrE,OAAO,KAAK,EACV,QAAQ,EACR,eAAe,EACf,qBAAqB,EACrB,iBAAiB,EAClB,MAAM,0CAA0C,CAAC;AAElD;;;;;;;GAOG;AACH,MAAM,MAAM,QAAQ,GAAG,KAAK,GAAG,OAAO,CAAC;AAEvC;;GAEG;AACH,MAAM,MAAM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yB,CAAC"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "@tejasdev/prisma-otel-middleware",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Production-ready OpenTelemetry tracing middleware for Prisma 8 built on CrossFamilyMiddleware SPI and ADR 271 activity lifecycle",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/Ritwikcp-ctrl/prisma-OpenTel-middleware.git",
25
+ "directory": "prisma-otel-middleware"
26
+ },
27
+ "homepage": "https://github.com/Ritwikcp-ctrl/prisma-OpenTel-middleware#readme",
28
+ "bugs": {
29
+ "url": "https://github.com/Ritwikcp-ctrl/prisma-OpenTel-middleware/issues"
30
+ },
31
+ "author": "Ritwikcp-ctrl <su30rai213@gmail.com>",
32
+ "engines": {
33
+ "node": ">=20.0.0"
34
+ },
35
+ "scripts": {
36
+ "build": "tsc -p tsconfig.json",
37
+ "typecheck": "tsc --noEmit -p tsconfig.json",
38
+ "prepublishOnly": "npm run build",
39
+ "test": "vitest run",
40
+ "test:sqlite": "vitest run test/sqlite.integration.test.ts",
41
+ "test:postgres": "vitest run test/postgres.integration.test.ts"
42
+ },
43
+ "peerDependencies": {
44
+ "@opentelemetry/api": "^1.9.0",
45
+ "@prisma/orm-framework": "^8.0.0-rc.28"
46
+ },
47
+ "devDependencies": {
48
+ "@electric-sql/pglite": "^0.6.1",
49
+ "@opentelemetry/api": "~1.9.0",
50
+ "@opentelemetry/sdk-trace-base": "^2.12.0",
51
+ "@prisma/orm-family-sql": "8.0.0-rc.28",
52
+ "@prisma/orm-framework": "8.0.0-rc.28",
53
+ "@prisma/orm-postgres": "8.0.0-rc.28",
54
+ "@prisma/orm-sqlite": "8.0.0-rc.28",
55
+ "@prisma/orm-target-postgres": "8.0.0-rc.28",
56
+ "@prisma/orm-target-sqlite": "8.0.0-rc.28",
57
+ "@prisma/orm-toolchain": "8.0.0-rc.28",
58
+ "@types/node": "^22.0.0",
59
+ "@types/pg": "^8.20.0",
60
+ "pg": "^8.22.0",
61
+ "temporal-polyfill": "^1.0.8",
62
+ "typescript": "^5.9.3",
63
+ "vitest": "^5.1.2"
64
+ },
65
+ "keywords": [
66
+ "prisma",
67
+ "prisma-8",
68
+ "opentelemetry",
69
+ "otel",
70
+ "tracing",
71
+ "middleware",
72
+ "observability"
73
+ ],
74
+ "license": "MIT"
75
+ }