@auditstream/prisma 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 auditstream
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,130 @@
1
- # Temporary Holding Version
1
+ # @auditstream/prisma
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
+ Prisma 7 SQL comments plugin and transaction-local `set_config` fallback for [Auditstream](https://github.com/auditstream/auditstream).
4
+
5
+ `@auditstream/prisma` reads the active actor from `@auditstream/node` and sends it to PostgreSQL triggers without altering your Prisma schema.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ pnpm add @auditstream/prisma @auditstream/node @prisma/client
11
+ ```
12
+
13
+ Install the `prisma` CLI as a dev dependency if needed. The `prisma` CLI is never a peer dependency.
14
+
15
+ ## Supported versions
16
+
17
+ | Dependency | Supported in v0.1 |
18
+ | --- | --- |
19
+ | Node.js | `22.12` or newer (CI tests `22`, `24`, and `26`) |
20
+ | PostgreSQL | `15` to `19` |
21
+ | Prisma | `@prisma/client` `7.1` or newer within `7.x` (tested on `7.10.1`) |
22
+ | Drizzle | `0.45` and `1.x` (via `@auditstream/drizzle`) |
23
+ | Runtimes | Node.js (reference), Bun and Deno (tested in CI), Cloudflare Workers (`nodejs_als` flag or compatibility date `2026-08-04` or later) |
24
+
25
+ Prisma 6 is not supported. Prisma 8 support follows its stable release. The `prisma` CLI is never a peer dependency.
26
+
27
+ ## Quick start
28
+
29
+ ### SQL comments plugin (`auditstream`)
30
+
31
+ Register `auditstream()` in your Prisma 7 client `comments` array. Every write inside `audit.as()` receives one trailing `auditstream` tag.
32
+
33
+ ```ts
34
+ import { audit } from "@auditstream/node";
35
+ import {
36
+ auditstream,
37
+ PACKAGE_NAME,
38
+ type SqlCommenterContext,
39
+ type SqlCommenterPlugin,
40
+ type SqlCommenterTags,
41
+ } from "@auditstream/prisma";
42
+
43
+ const plugin: SqlCommenterPlugin = auditstream();
44
+ const ctx: SqlCommenterContext = { sql: "UPDATE invoice SET status = $1 WHERE id = $2" };
45
+
46
+ const tags: SqlCommenterTags = await audit.as({ type: "user", id: "usr_42" }, () => plugin(ctx));
47
+ void [tags, PACKAGE_NAME];
48
+ ```
49
+
50
+ Pass the plugin when constructing `PrismaClient`:
51
+
52
+ ```ts
53
+ import { audit } from "@auditstream/node";
54
+ import { auditstream } from "@auditstream/prisma";
55
+ import { PrismaPg } from "@prisma/adapter-pg";
56
+ import pg from "pg";
57
+
58
+ interface AppPrismaClient {
59
+ invoice: { update(args: { where: { id: number }; data: { status: string } }): Promise<unknown> };
60
+ }
61
+
62
+ function createClient(
63
+ PrismaClientCtor: new (options: {
64
+ adapter: PrismaPg;
65
+ comments: ReturnType<typeof auditstream>[];
66
+ }) => AppPrismaClient,
67
+ connectionString: string,
68
+ ): AppPrismaClient {
69
+ const pool = new pg.Pool({ connectionString });
70
+ const adapter = new PrismaPg(pool);
71
+ return new PrismaClientCtor({ adapter, comments: [auditstream()] });
72
+ }
73
+
74
+ async function markPaid(prisma: AppPrismaClient): Promise<void> {
75
+ await audit.as({ type: "user", id: "usr_42" }, () =>
76
+ prisma.invoice.update({ where: { id: 1 }, data: { status: "paid" } }),
77
+ );
78
+ }
79
+
80
+ void [createClient, markPaid];
81
+ ```
82
+
83
+ ### Transaction fallback (`auditTransaction`)
84
+
85
+ Use `auditTransaction()` when SQL comments are unavailable, such as under Prisma Accelerate. It sets `auditstream.actor` with `set_config(..., true)` inside the transaction.
86
+
87
+ ```ts
88
+ import { audit } from "@auditstream/node";
89
+ import {
90
+ auditTransaction,
91
+ type PrismaRawExecutor,
92
+ type PrismaTransactionRunner,
93
+ } from "@auditstream/prisma";
94
+
95
+ interface TxClient extends PrismaRawExecutor {
96
+ markPaid(id: number): Promise<void>;
97
+ }
98
+
99
+ async function updateWithFallback(
100
+ prisma: PrismaTransactionRunner<TxClient, { timeout?: number }>,
101
+ ): Promise<void> {
102
+ await audit.as({ type: "user", id: "usr_42" }, () =>
103
+ auditTransaction(
104
+ prisma,
105
+ async (tx) => {
106
+ await tx.markPaid(1);
107
+ },
108
+ { timeout: 5000 },
109
+ ),
110
+ );
111
+ }
112
+
113
+ void updateWithFallback;
114
+ ```
115
+
116
+ ## Context and limits
117
+
118
+ - **Unawaited lazy queries:** Prisma queries execute only when awaited. Always await them inside `audit.as()`, which awaits your callback before closing the scope.
119
+ - **Next.js `proxy`:** `AsyncLocalStorage` does not cross Next.js `proxy`. Pass actor data through headers, cookies, rewrites, redirects, or URLs, and wrap handlers with `@auditstream/node/next`.
120
+ - **Background jobs:** Code running outside a request has no active actor. Open a scope with a `service` or `system` actor.
121
+ - **Prisma Accelerate:** Comment plugins do not receive the SQL under Accelerate. Use `auditTransaction()` there instead.
122
+ - **AWS RDS Proxy:** Trailing comments are the default transport because `set_config(..., true)` pins RDS Proxy sessions.
123
+
124
+ ## Links
125
+
126
+ - [Auditstream engine repository](https://github.com/auditstream/auditstream)
127
+ - [Engineering handbook](https://github.com/auditstream/auditstream/tree/main/docs/handbook)
128
+ - [Adapters design](https://github.com/auditstream/auditstream/blob/main/docs/handbook/adapters.md)
129
+ - [Transport specification](https://github.com/auditstream/auditstream/blob/main/spec/transport.md)
130
+ - [Supported versions](https://github.com/auditstream/auditstream/blob/main/docs/handbook/releases.md#supported-versions)
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Interactive transaction client capable of executing parameterized tagged SQL via `$executeRaw`.
3
+ */
4
+ interface PrismaRawExecutor {
5
+ /** Executes a parameterized SQL template string on the active transaction connection. */
6
+ $executeRaw(query: TemplateStringsArray, ...values: unknown[]): Promise<number>;
7
+ }
8
+ /**
9
+ * Structural shape of a Prisma client supporting interactive `$transaction(fn, options?)`.
10
+ */
11
+ interface PrismaTransactionRunner<TTx extends PrismaRawExecutor, TOptions = unknown> {
12
+ /** Runs `fn` inside an interactive database transaction with optional Prisma transaction options. */
13
+ $transaction<TResult>(fn: (tx: TTx) => Promise<TResult>, options?: TOptions): Promise<TResult>;
14
+ }
15
+ /**
16
+ * Runs `fn` inside a Prisma interactive transaction (`prisma.$transaction`) and, when an
17
+ * `audit.as()` scope is active at call time, executes
18
+ * `SELECT set_config('auditstream.actor', $1, true)` as the transaction's first statement
19
+ * using a bound parameter from `setConfigValue()`.
20
+ *
21
+ * - **When to use:** Use `auditTransaction()` when SQL comments cannot reach PostgreSQL
22
+ * (notably under Prisma Accelerate, where comment plugins do not receive SQL and comment
23
+ * delivery is undocumented).
24
+ * - **Precedence & isolation:** `set_config('auditstream.actor', $1, true)` is transaction-local
25
+ * (`is_local = true`), wins over any SQL comment on the same statement, and resets to an empty
26
+ * string once the transaction commits or rolls back so actors cannot leak across pooled
27
+ * connections.
28
+ * - **RDS Proxy note:** `set_config` pins connections on AWS RDS Proxy; keep the `auditstream()`
29
+ * SQL comments plugin as the default transport there.
30
+ * - **Outside a scope:** When `audit.current()` is `undefined`, `auditTransaction()` runs `fn`
31
+ * inside `prisma.$transaction` without issuing `set_config`.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * import { audit } from "@auditstream/node";
36
+ * import { auditTransaction } from "@auditstream/prisma";
37
+ *
38
+ * const updated = await audit.as({ type: "user", id: "usr_1" }, () =>
39
+ * auditTransaction(
40
+ * prisma,
41
+ * async (tx) => tx.invoice.update({ where: { id: 1 }, data: { status: "paid" } }),
42
+ * { timeout: 10_000 },
43
+ * ),
44
+ * );
45
+ * ```
46
+ */
47
+ export declare function auditTransaction<TTx extends PrismaRawExecutor, TResult, TOptions = unknown>(prisma: PrismaTransactionRunner<TTx, TOptions>, fn: (tx: TTx) => Promise<TResult>, options?: TOptions): Promise<TResult>;
48
+ /** Package identifier exported by `@auditstream/prisma`. */
49
+ export declare const PACKAGE_NAME: "@auditstream/prisma";
50
+ /**
51
+ * Key-value map returned by a Prisma SQL comments plugin.
52
+ * Keys with an `undefined` value are omitted by Prisma when building the trailing comment.
53
+ */
54
+ export type SqlCommenterTags = {
55
+ readonly [key: string]: string | undefined;
56
+ };
57
+ /**
58
+ * Query metadata passed by Prisma to SQL comments plugins.
59
+ *
60
+ * Declared structurally so `@auditstream/prisma` carries no dependency on `@prisma/sqlcommenter`
61
+ * and stays assignable across `@prisma/client` 7.1.0 through 7.x.
62
+ */
63
+ export interface SqlCommenterContext {
64
+ /** Metadata about the single or compacted Prisma query being executed. */
65
+ readonly query?: unknown;
66
+ /** Rendered SQL statement when available (omitted under Prisma Accelerate). */
67
+ readonly sql?: string;
68
+ }
69
+ /**
70
+ * Prisma 7 SQL comments plugin compatible with `new PrismaClient({ comments: [auditstream()] })`.
71
+ */
72
+ export type SqlCommenterPlugin = (context?: SqlCommenterContext) => SqlCommenterTags;
73
+ /**
74
+ * Creates a Prisma 7 SQL comments plugin that attaches the active `audit.as()` actor and
75
+ * context as an `auditstream` sqlcommenter tag.
76
+ *
77
+ * - **Supported versions:** Requires `@prisma/client` 7.1.0 or newer within Prisma 7.x
78
+ * (`>=7.1.0 <8`). Prisma 6 is not supported.
79
+ * - **Empty outside scope:** Outside an active `audit.as()` scope, the plugin returns `{}`
80
+ * so no `auditstream` key is emitted.
81
+ * - **Prisma Accelerate limit:** Under Prisma Accelerate, SQL comments plugins do not receive
82
+ * rendered SQL and comment delivery to PostgreSQL is undocumented. Use
83
+ * {@link auditTransaction} (`set_config` fallback) for Accelerate workloads.
84
+ * - **`statementNameGenerator` rule:** Never configure `PrismaPg`'s optional
85
+ * `statementNameGenerator` alongside SQL comments. Per-actor comments paired with named
86
+ * prepared statements grow `node-postgres`'s prepared-statement cache unboundedly and
87
+ * violate `spec/transport.md`.
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * import { PrismaPg } from "@prisma/adapter-pg";
92
+ * import { audit } from "@auditstream/node";
93
+ * import { auditstream } from "@auditstream/prisma";
94
+ * import { PrismaClient } from "./generated/prisma/client";
95
+ *
96
+ * const prisma = new PrismaClient({
97
+ * adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
98
+ * comments: [auditstream()],
99
+ * });
100
+ *
101
+ * await audit.as({ type: "user", id: "usr_1" }, () =>
102
+ * prisma.invoice.update({ where: { id: 1 }, data: { status: "paid" } }),
103
+ * );
104
+ * ```
105
+ */
106
+ export declare function auditstream(): SqlCommenterPlugin;
107
+ export type { PrismaRawExecutor, PrismaTransactionRunner };
package/dist/index.mjs ADDED
@@ -0,0 +1,88 @@
1
+ import { audit, encodeScope, setConfigValue } from "@auditstream/node";
2
+ // src/fallback.ts
3
+ /**
4
+ * Runs `fn` inside a Prisma interactive transaction (`prisma.$transaction`) and, when an
5
+ * `audit.as()` scope is active at call time, executes
6
+ * `SELECT set_config('auditstream.actor', $1, true)` as the transaction's first statement
7
+ * using a bound parameter from `setConfigValue()`.
8
+ *
9
+ * - **When to use:** Use `auditTransaction()` when SQL comments cannot reach PostgreSQL
10
+ * (notably under Prisma Accelerate, where comment plugins do not receive SQL and comment
11
+ * delivery is undocumented).
12
+ * - **Precedence & isolation:** `set_config('auditstream.actor', $1, true)` is transaction-local
13
+ * (`is_local = true`), wins over any SQL comment on the same statement, and resets to an empty
14
+ * string once the transaction commits or rolls back so actors cannot leak across pooled
15
+ * connections.
16
+ * - **RDS Proxy note:** `set_config` pins connections on AWS RDS Proxy; keep the `auditstream()`
17
+ * SQL comments plugin as the default transport there.
18
+ * - **Outside a scope:** When `audit.current()` is `undefined`, `auditTransaction()` runs `fn`
19
+ * inside `prisma.$transaction` without issuing `set_config`.
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * import { audit } from "@auditstream/node";
24
+ * import { auditTransaction } from "@auditstream/prisma";
25
+ *
26
+ * const updated = await audit.as({ type: "user", id: "usr_1" }, () =>
27
+ * auditTransaction(
28
+ * prisma,
29
+ * async (tx) => tx.invoice.update({ where: { id: 1 }, data: { status: "paid" } }),
30
+ * { timeout: 10_000 },
31
+ * ),
32
+ * );
33
+ * ```
34
+ */
35
+ async function auditTransaction(prisma, fn, options) {
36
+ const scope = audit.current();
37
+ const payload = scope ? setConfigValue(scope) : void 0;
38
+ const callback = async (tx) => {
39
+ if (payload !== void 0) await tx.$executeRaw`SELECT set_config('auditstream.actor', ${payload}, true)`;
40
+ return await fn(tx);
41
+ };
42
+ if (options !== void 0) return await prisma.$transaction(callback, options);
43
+ return await prisma.$transaction(callback);
44
+ }
45
+ // src/index.ts
46
+ /** Package identifier exported by `@auditstream/prisma`. */
47
+ const PACKAGE_NAME = "@auditstream/prisma";
48
+ /**
49
+ * Creates a Prisma 7 SQL comments plugin that attaches the active `audit.as()` actor and
50
+ * context as an `auditstream` sqlcommenter tag.
51
+ *
52
+ * - **Supported versions:** Requires `@prisma/client` 7.1.0 or newer within Prisma 7.x
53
+ * (`>=7.1.0 <8`). Prisma 6 is not supported.
54
+ * - **Empty outside scope:** Outside an active `audit.as()` scope, the plugin returns `{}`
55
+ * so no `auditstream` key is emitted.
56
+ * - **Prisma Accelerate limit:** Under Prisma Accelerate, SQL comments plugins do not receive
57
+ * rendered SQL and comment delivery to PostgreSQL is undocumented. Use
58
+ * {@link auditTransaction} (`set_config` fallback) for Accelerate workloads.
59
+ * - **`statementNameGenerator` rule:** Never configure `PrismaPg`'s optional
60
+ * `statementNameGenerator` alongside SQL comments. Per-actor comments paired with named
61
+ * prepared statements grow `node-postgres`'s prepared-statement cache unboundedly and
62
+ * violate `spec/transport.md`.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * import { PrismaPg } from "@prisma/adapter-pg";
67
+ * import { audit } from "@auditstream/node";
68
+ * import { auditstream } from "@auditstream/prisma";
69
+ * import { PrismaClient } from "./generated/prisma/client";
70
+ *
71
+ * const prisma = new PrismaClient({
72
+ * adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
73
+ * comments: [auditstream()],
74
+ * });
75
+ *
76
+ * await audit.as({ type: "user", id: "usr_1" }, () =>
77
+ * prisma.invoice.update({ where: { id: 1 }, data: { status: "paid" } }),
78
+ * );
79
+ * ```
80
+ */
81
+ function auditstream() {
82
+ return () => {
83
+ const scope = audit.current();
84
+ if (!scope) return {};
85
+ return { auditstream: encodeScope(scope) };
86
+ };
87
+ }
88
+ export { PACKAGE_NAME, auditTransaction, auditstream };
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@auditstream/prisma",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Prisma 7 SQL comments plugin and set_config fallback for Auditstream",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/auditstream/auditstream-js.git",
10
+ "directory": "packages/prisma"
11
+ },
12
+ "engines": {
13
+ "node": ">=22.12"
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "sideEffects": false,
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.mts",
25
+ "default": "./dist/index.mjs"
26
+ }
27
+ },
28
+ "peerDependencies": {
29
+ "@auditstream/node": ">=0.1.0 <1.0.0",
30
+ "@prisma/client": ">=7.1.0 <8"
31
+ },
32
+ "devDependencies": {
33
+ "@auditstream/node": "0.2.0",
34
+ "@auditstream/test-utils": "0.1.0",
35
+ "@neondatabase/serverless": "1.2.1",
36
+ "@prisma/adapter-neon": "7.10.1",
37
+ "@prisma/adapter-pg": "7.10.1",
38
+ "@prisma/client": "7.10.1",
39
+ "@prisma/sqlcommenter": "7.10.1",
40
+ "@types/node": "^22.20.5",
41
+ "@types/pg": "8.23.1",
42
+ "pg": "8.23.1",
43
+ "prisma": "7.10.1",
44
+ "tsdown": "0.23.7",
45
+ "typescript": "~6.0.3",
46
+ "vitest": "^5.1.1"
47
+ },
48
+ "scripts": {
49
+ "build": "tsdown",
50
+ "typecheck": "tsc --noEmit",
51
+ "test": "vitest run --config ../../vitest.config.ts",
52
+ "test:integration": "prisma generate --config test/integration/prisma.config.ts && vitest run --config vitest.integration.config.ts"
53
+ }
6
54
  }