@prisma/dev 0.23.0 → 0.24.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/dist/state.d.cts CHANGED
@@ -1,214 +1,2 @@
1
- import * as valibot from 'valibot';
2
- import { InferOutput } from 'valibot';
3
-
4
- declare const exportsSchema: valibot.ObjectSchema<{
5
- readonly database: valibot.ObjectSchema<{
6
- readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
7
- readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
8
- readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
9
- }, undefined>;
10
- readonly http: valibot.ObjectSchema<{
11
- readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
12
- }, undefined>;
13
- readonly ppg: valibot.ObjectSchema<{
14
- readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
15
- }, undefined>;
16
- readonly shadowDatabase: valibot.ObjectSchema<{
17
- readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
18
- readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
19
- readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
20
- }, undefined>;
21
- }, undefined>;
22
- type Exports = InferOutput<typeof exportsSchema>;
23
- declare const serverDumpV1Schema: valibot.ObjectSchema<{
24
- readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
25
- readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
26
- readonly database: valibot.ObjectSchema<{
27
- readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
28
- readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
29
- readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
30
- }, undefined>;
31
- readonly http: valibot.ObjectSchema<{
32
- readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
33
- }, undefined>;
34
- readonly ppg: valibot.ObjectSchema<{
35
- readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
36
- }, undefined>;
37
- readonly shadowDatabase: valibot.ObjectSchema<{
38
- readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
39
- readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
40
- readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
41
- }, undefined>;
42
- }, undefined>, undefined>;
43
- readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
44
- readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
45
- readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
46
- readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
47
- readonly version: valibot.LiteralSchema<"1", undefined>;
48
- }, undefined>;
49
- type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
50
- interface ServerOptions {
51
- /**
52
- * Connection timeout in milliseconds for pending database connections.
53
- *
54
- * This option is currently not enforced by the multiplexed
55
- * `@electric-sql/pglite-socket` server used by `@prisma/dev`.
56
- * It is kept for API compatibility until upstream exposes a queue-timeout
57
- * equivalent again.
58
- *
59
- * Default is 1 minute (60,000 milliseconds).
60
- */
61
- databaseConnectTimeoutMillis?: number;
62
- /**
63
- * Idle timeout in milliseconds for open database connections.
64
- *
65
- * Re-starts ticking after each message received on a connection. When exceeded,
66
- * that client connection is closed by the socket server.
67
- *
68
- * Is not applied by default.
69
- *
70
- * Use it with caution, as it may lead to unexpected disconnections. Best used
71
- * with a pool client that can handle disconnections gracefully.
72
- *
73
- * Set it if you suffer from client hanging indefinitely as the active connection
74
- * remain open forever.
75
- */
76
- databaseIdleTimeoutMillis?: number;
77
- /**
78
- * The port the database server will listen on.
79
- *
80
- * Defaults to `51214`.
81
- *
82
- * An error is thrown if the port is already in use.
83
- */
84
- databasePort?: number;
85
- /**
86
- * Whether to enable debug logging.
87
- *
88
- * Defaults to `false`.
89
- */
90
- debug?: boolean;
91
- /**
92
- * Whether to run the server in dry run mode.
93
- *
94
- * Defaults to `false`.
95
- */
96
- dryRun?: boolean;
97
- /**
98
- * The name of the server.
99
- *
100
- * Defaults to `default`.
101
- */
102
- name?: string;
103
- /**
104
- * The persistence mode of the server.
105
- *
106
- * Default is `stateless`.
107
- */
108
- persistenceMode?: PersistenceMode;
109
- /**
110
- * The port the server will listen on.
111
- *
112
- * Defaults to `51213`.
113
- *
114
- * An error is thrown if the port is already in use.
115
- */
116
- port?: number;
117
- /**
118
- * Connection timeout in milliseconds for pending shadow database connections.
119
- *
120
- * Default is {@link databaseConnectTimeoutMillis}.
121
- */
122
- shadowDatabaseConnectTimeoutMillis?: number;
123
- /**
124
- * Idle timeout in milliseconds for active shadow database connections.
125
- *
126
- * Default is {@link databaseIdleTimeoutMillis}.
127
- */
128
- shadowDatabaseIdleTimeoutMillis?: number;
129
- /**
130
- * The port the shadow database server will listen on.
131
- *
132
- * Defaults to `51215`.
133
- *
134
- * An error is thrown if the port is already in use.
135
- */
136
- shadowDatabasePort?: number;
137
- }
138
- type ResolvedServerOptions = Required<ServerOptions>;
139
- type PersistenceMode = "stateless" | "stateful";
140
- interface ScanOptions {
141
- debug?: boolean;
142
- globs?: string[];
143
- onlyMetadata?: boolean;
144
- }
145
- declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
146
- declare abstract class ServerState implements ResolvedServerOptions {
147
- #private;
148
- protected _databasePort: number;
149
- readonly databaseConnectTimeoutMillis: number;
150
- readonly databaseIdleTimeoutMillis: number;
151
- readonly debug: boolean;
152
- readonly dryRun: boolean;
153
- readonly name: string;
154
- readonly persistenceMode: PersistenceMode;
155
- readonly pid: number | undefined;
156
- readonly shadowDatabaseConnectTimeoutMillis: number;
157
- readonly shadowDatabaseIdleTimeoutMillis: number;
158
- protected _port: number;
159
- protected _shadowDatabasePort: number;
160
- protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
161
- persistenceMode: PersistenceMode;
162
- pid?: number | undefined;
163
- });
164
- static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
165
- static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
166
- static scan(options?: ScanOptions): Promise<ServerStatusV1[]>;
167
- abstract get databaseDumpPath(): string;
168
- abstract get pgliteDataDirPath(): string;
169
- abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
170
- abstract close(): Promise<void>;
171
- abstract writeServerDump(exports?: Exports): Promise<void>;
172
- get databasePort(): number;
173
- set databasePort(value: number);
174
- get port(): number;
175
- set port(value: number);
176
- get shadowDatabasePort(): number;
177
- set shadowDatabasePort(value: number);
178
- }
179
- declare class StatefulServerState extends ServerState {
180
- #private;
181
- constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
182
- pid?: number | undefined;
183
- serverDump?: ServerDumpV1;
184
- }) | undefined);
185
- static getServerDumpPath(dataDirPath: string): string;
186
- get databaseDumpPath(): string;
187
- get exports(): Exports | undefined;
188
- get pgliteDataDirPath(): string;
189
- [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
190
- close(): Promise<void>;
191
- writeServerDump(exports?: Exports): Promise<void>;
192
- }
193
- interface ServerStatusV1 extends ServerDumpV1 {
194
- status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
195
- }
196
- declare function deleteServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<void>;
197
- declare function getServerStatus(nameOrState: string | StatefulServerState, options?: ScanOptions): Promise<ServerStatusV1>;
198
- declare function isServerRunning(server: ServerStatusV1): boolean;
199
- declare function killServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<boolean>;
200
- /**
201
- * @deprecated use `ServerAlreadyRunningError` instead. Will be removed in a future version.
202
- */
203
- declare class ServerStateAlreadyExistsError extends Error {
204
- name: string;
205
- constructor(name: string);
206
- }
207
- declare class ServerAlreadyRunningError extends ServerStateAlreadyExistsError {
208
- #private;
209
- name: string;
210
- constructor(server: ServerState);
211
- get server(): Promise<ServerState | null>;
212
- }
213
-
214
- export { type Exports, type PersistenceMode, type ResolvedServerOptions, type ScanOptions, ServerAlreadyRunningError, type ServerDumpV1, type ServerOptions, ServerState, ServerStateAlreadyExistsError, type ServerStatusV1, deleteServer, getServerStatus, isServerRunning, killServer };
1
+ import 'valibot';
2
+ export { a as Exports, P as PersistenceMode, R as ResolvedServerOptions, d as ScanOptions, b as ServerAlreadyRunningError, e as ServerDumpV1, S as ServerOptions, c as ServerState, f as ServerStateAlreadyExistsError, g as ServerStatusV1, h as deleteServer, i as getServerStatus, j as isServerRunning, k as killServer } from './state-DTMxyzXf.cjs';
package/dist/state.d.ts CHANGED
@@ -1,214 +1,2 @@
1
- import * as valibot from 'valibot';
2
- import { InferOutput } from 'valibot';
3
-
4
- declare const exportsSchema: valibot.ObjectSchema<{
5
- readonly database: valibot.ObjectSchema<{
6
- readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
7
- readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
8
- readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
9
- }, undefined>;
10
- readonly http: valibot.ObjectSchema<{
11
- readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
12
- }, undefined>;
13
- readonly ppg: valibot.ObjectSchema<{
14
- readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
15
- }, undefined>;
16
- readonly shadowDatabase: valibot.ObjectSchema<{
17
- readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
18
- readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
19
- readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
20
- }, undefined>;
21
- }, undefined>;
22
- type Exports = InferOutput<typeof exportsSchema>;
23
- declare const serverDumpV1Schema: valibot.ObjectSchema<{
24
- readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
25
- readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
26
- readonly database: valibot.ObjectSchema<{
27
- readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
28
- readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
29
- readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
30
- }, undefined>;
31
- readonly http: valibot.ObjectSchema<{
32
- readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
33
- }, undefined>;
34
- readonly ppg: valibot.ObjectSchema<{
35
- readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
36
- }, undefined>;
37
- readonly shadowDatabase: valibot.ObjectSchema<{
38
- readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
39
- readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
40
- readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
41
- }, undefined>;
42
- }, undefined>, undefined>;
43
- readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
44
- readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
45
- readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
46
- readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
47
- readonly version: valibot.LiteralSchema<"1", undefined>;
48
- }, undefined>;
49
- type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
50
- interface ServerOptions {
51
- /**
52
- * Connection timeout in milliseconds for pending database connections.
53
- *
54
- * This option is currently not enforced by the multiplexed
55
- * `@electric-sql/pglite-socket` server used by `@prisma/dev`.
56
- * It is kept for API compatibility until upstream exposes a queue-timeout
57
- * equivalent again.
58
- *
59
- * Default is 1 minute (60,000 milliseconds).
60
- */
61
- databaseConnectTimeoutMillis?: number;
62
- /**
63
- * Idle timeout in milliseconds for open database connections.
64
- *
65
- * Re-starts ticking after each message received on a connection. When exceeded,
66
- * that client connection is closed by the socket server.
67
- *
68
- * Is not applied by default.
69
- *
70
- * Use it with caution, as it may lead to unexpected disconnections. Best used
71
- * with a pool client that can handle disconnections gracefully.
72
- *
73
- * Set it if you suffer from client hanging indefinitely as the active connection
74
- * remain open forever.
75
- */
76
- databaseIdleTimeoutMillis?: number;
77
- /**
78
- * The port the database server will listen on.
79
- *
80
- * Defaults to `51214`.
81
- *
82
- * An error is thrown if the port is already in use.
83
- */
84
- databasePort?: number;
85
- /**
86
- * Whether to enable debug logging.
87
- *
88
- * Defaults to `false`.
89
- */
90
- debug?: boolean;
91
- /**
92
- * Whether to run the server in dry run mode.
93
- *
94
- * Defaults to `false`.
95
- */
96
- dryRun?: boolean;
97
- /**
98
- * The name of the server.
99
- *
100
- * Defaults to `default`.
101
- */
102
- name?: string;
103
- /**
104
- * The persistence mode of the server.
105
- *
106
- * Default is `stateless`.
107
- */
108
- persistenceMode?: PersistenceMode;
109
- /**
110
- * The port the server will listen on.
111
- *
112
- * Defaults to `51213`.
113
- *
114
- * An error is thrown if the port is already in use.
115
- */
116
- port?: number;
117
- /**
118
- * Connection timeout in milliseconds for pending shadow database connections.
119
- *
120
- * Default is {@link databaseConnectTimeoutMillis}.
121
- */
122
- shadowDatabaseConnectTimeoutMillis?: number;
123
- /**
124
- * Idle timeout in milliseconds for active shadow database connections.
125
- *
126
- * Default is {@link databaseIdleTimeoutMillis}.
127
- */
128
- shadowDatabaseIdleTimeoutMillis?: number;
129
- /**
130
- * The port the shadow database server will listen on.
131
- *
132
- * Defaults to `51215`.
133
- *
134
- * An error is thrown if the port is already in use.
135
- */
136
- shadowDatabasePort?: number;
137
- }
138
- type ResolvedServerOptions = Required<ServerOptions>;
139
- type PersistenceMode = "stateless" | "stateful";
140
- interface ScanOptions {
141
- debug?: boolean;
142
- globs?: string[];
143
- onlyMetadata?: boolean;
144
- }
145
- declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
146
- declare abstract class ServerState implements ResolvedServerOptions {
147
- #private;
148
- protected _databasePort: number;
149
- readonly databaseConnectTimeoutMillis: number;
150
- readonly databaseIdleTimeoutMillis: number;
151
- readonly debug: boolean;
152
- readonly dryRun: boolean;
153
- readonly name: string;
154
- readonly persistenceMode: PersistenceMode;
155
- readonly pid: number | undefined;
156
- readonly shadowDatabaseConnectTimeoutMillis: number;
157
- readonly shadowDatabaseIdleTimeoutMillis: number;
158
- protected _port: number;
159
- protected _shadowDatabasePort: number;
160
- protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
161
- persistenceMode: PersistenceMode;
162
- pid?: number | undefined;
163
- });
164
- static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
165
- static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
166
- static scan(options?: ScanOptions): Promise<ServerStatusV1[]>;
167
- abstract get databaseDumpPath(): string;
168
- abstract get pgliteDataDirPath(): string;
169
- abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
170
- abstract close(): Promise<void>;
171
- abstract writeServerDump(exports?: Exports): Promise<void>;
172
- get databasePort(): number;
173
- set databasePort(value: number);
174
- get port(): number;
175
- set port(value: number);
176
- get shadowDatabasePort(): number;
177
- set shadowDatabasePort(value: number);
178
- }
179
- declare class StatefulServerState extends ServerState {
180
- #private;
181
- constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
182
- pid?: number | undefined;
183
- serverDump?: ServerDumpV1;
184
- }) | undefined);
185
- static getServerDumpPath(dataDirPath: string): string;
186
- get databaseDumpPath(): string;
187
- get exports(): Exports | undefined;
188
- get pgliteDataDirPath(): string;
189
- [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
190
- close(): Promise<void>;
191
- writeServerDump(exports?: Exports): Promise<void>;
192
- }
193
- interface ServerStatusV1 extends ServerDumpV1 {
194
- status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
195
- }
196
- declare function deleteServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<void>;
197
- declare function getServerStatus(nameOrState: string | StatefulServerState, options?: ScanOptions): Promise<ServerStatusV1>;
198
- declare function isServerRunning(server: ServerStatusV1): boolean;
199
- declare function killServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<boolean>;
200
- /**
201
- * @deprecated use `ServerAlreadyRunningError` instead. Will be removed in a future version.
202
- */
203
- declare class ServerStateAlreadyExistsError extends Error {
204
- name: string;
205
- constructor(name: string);
206
- }
207
- declare class ServerAlreadyRunningError extends ServerStateAlreadyExistsError {
208
- #private;
209
- name: string;
210
- constructor(server: ServerState);
211
- get server(): Promise<ServerState | null>;
212
- }
213
-
214
- export { type Exports, type PersistenceMode, type ResolvedServerOptions, type ScanOptions, ServerAlreadyRunningError, type ServerDumpV1, type ServerOptions, ServerState, ServerStateAlreadyExistsError, type ServerStatusV1, deleteServer, getServerStatus, isServerRunning, killServer };
1
+ import 'valibot';
2
+ export { a as Exports, P as PersistenceMode, R as ResolvedServerOptions, d as ScanOptions, b as ServerAlreadyRunningError, e as ServerDumpV1, S as ServerOptions, c as ServerState, f as ServerStateAlreadyExistsError, g as ServerStatusV1, h as deleteServer, i as getServerStatus, j as isServerRunning, k as killServer } from './state-DTMxyzXf.js';
package/dist/state.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g}from"./chunk-FIY24ARL.js";import"./chunk-OTI5SWIV.js";import"./chunk-DGKV2DPF.js";export{g as ServerAlreadyRunningError,a as ServerState,f as ServerStateAlreadyExistsError,b as deleteServer,c as getServerStatus,d as isServerRunning,e as killServer};
1
+ import{e as a,f as b,g as c,h as d,i as e,j as f,k as g}from"./chunk-CC3P7GPW.js";import"./chunk-X3G665AK.js";import"./chunk-DWY47FQV.js";export{g as ServerAlreadyRunningError,a as ServerState,f as ServerStateAlreadyExistsError,b as deleteServer,c as getServerStatus,d as isServerRunning,e as killServer};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/dev",
3
- "version": "0.23.0",
3
+ "version": "0.24.0",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
6
  "author": "Igal Klebanov <igalklebanov@gmail.com> (https://github.com/igalklebanov)",
@@ -81,9 +81,9 @@
81
81
  "@electric-sql/pglite-socket": "0.1.1",
82
82
  "@electric-sql/pglite-tools": "0.3.1",
83
83
  "@hono/node-server": "1.19.11",
84
- "@mrleebo/prisma-ast": "0.15.0",
85
84
  "@prisma/get-platform": "7.2.0",
86
85
  "@prisma/query-plan-executor": "7.2.0",
86
+ "@prisma/streams-local": "0.1.1",
87
87
  "foreground-child": "3.3.1",
88
88
  "get-port-please": "3.2.0",
89
89
  "hono": "^4.12.8",
@@ -96,12 +96,12 @@
96
96
  "zeptomatch": "2.1.0"
97
97
  },
98
98
  "scripts": {
99
- "build": "tsup && node ./scripts/generate-bun-runtime-assets.mjs --dist",
99
+ "build": "node ./scripts/generate-bun-runtime-assets.mjs && tsup && node ./scripts/generate-bun-runtime-assets.mjs --dist",
100
100
  "check:exports": "attw . --pack --profile node16",
101
- "dev": "tsup --watch",
101
+ "dev": "node ./scripts/generate-bun-runtime-assets.mjs && tsup --watch",
102
+ "init": "node ./scripts/generate-bun-runtime-assets.mjs",
102
103
  "lint": "eslint --fix .",
103
- "postinstall": "node -e \"const { existsSync } = require('fs'); const { execFileSync } = require('child_process'); if (existsSync('./scripts/generate-bun-runtime-assets.mjs')) { execFileSync(process.execPath, ['./scripts/generate-bun-runtime-assets.mjs'], { stdio: 'inherit' }); }\"",
104
104
  "test": "node ./scripts/generate-bun-runtime-assets.mjs && vitest run",
105
- "typecheck": "tsc --noEmit"
105
+ "typecheck": "node ./scripts/generate-bun-runtime-assets.mjs && tsc --noEmit"
106
106
  }
107
107
  }
@@ -1 +0,0 @@
1
- import{b as i,d as x,e as d}from"./chunk-6ORCLJD5.js";import"./chunk-DGKV2DPF.js";import{HTTPException as re}from"hono/http-exception";import{Hono as ae}from"hono/tiny";import{validator as c}from"hono/validator";import{array as L,literal as k,minLength as B,object as U,pipe as N,safeParse as D,string as F,union as Q}from"valibot";var X=U({tags:Q([N(L(F()),B(1)),k("all")])});async function E(e){let{output:n,success:t}=D(X,await e.req.json(),{abortEarly:!0});return t?n:e.text("Invalid input",400)}import{parseDuration as v,parseSize as Y,Server as z}from"@prisma/query-plan-executor";import{version as P}from"@prisma/query-plan-executor";var T;async function O(e){return T===void 0&&(T=await z.create({databaseUrl:e.get("db").connectionString,maxResponseSize:Y("128 MiB"),queryTimeout:v("PT5M"),maxTransactionTimeout:v("PT5M"),maxTransactionWaitTime:v("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.get("debug")?"debug":"off"}})),T}import{Buffer as I}from"buffer";import{getSchema as G,printSchema as W}from"@mrleebo/prisma-ast";var l=new Map;async function H(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}function C(e){let n=e.req.param("schemaHash"),t=l.get(n);return t==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:n,schemas:t}}async function R(e,n,t){let r=I.from(e,"base64").toString("utf8"),a=G(r),o=a.list.find(f=>f.type==="datasource");if(!o)throw new Error("No datasource block found in schema.");let s=o.assignments.find(f=>f.type==="assignment"&&f.key==="url");s?s.value=`"${n.toString()}"`:o.assignments.push({key:"url",type:"assignment",value:`"${n.toString()}"`});let m=W(a);t&&console.log("[Accelerate] schema with override:",m);let S=await H(m);return{base64Override:I.from(m,"utf8").toString("base64"),overrideHash:S}}function g(e){let{req:n}=e;return{traceparent:n.header("traceparent"),"X-capture-telemetry":n.header("X-capture-telemetry")}}import{integer as q,looseObject as K,minValue as A,number as w,object as J,optional as Z,pipe as _,safeParse as M,string as $,union as ee}from"valibot";var te=J({isolation_level:Z($()),max_wait:_(w(),q(),A(0)),timeout:_(w(),q(),A(0))});async function V(e){let{issues:n,output:t,success:r}=M(te,await e.req.json(),{abortEarly:!0});return r?t:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:n}},400)}var ne=K({id:ee([$(),w()])});function j(e,n){let{output:t,success:r}=M(ne,e);return r?t:n.json({EngineMalfunction:{}},500)}var y=new ae;y.post("/invalidate",c("header",i),async e=>{let n=await E(e);return n instanceof Response?n:e.body(null)});var oe="/:clientVersion/:schemaHash",h=y.basePath(oe);y.route("/",h);var se=["/graphql","/itx/:transactionId/graphql"];h.on("POST",[...se],c("header",i),async e=>{let{req:n}=e;try{let t=await b(e);if(t instanceof Response)return t;let r=await n.text(),a=n.param("transactionId"),o=await t.request(r,{...g(e),"X-transaction-id":a});return e.text(o)}catch(t){return d(t,e)}});h.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],c("header",i),async e=>{let{req:n}=e;try{let t=await b(e);if(t instanceof Response)return t;let a=`${n.routePath.split("/").filter(Boolean).at(-1)}Transaction`,o=n.param("transactionId"),s=await t[a](o,g(e));return e.json(s)}catch(t){return d(t,e)}});h.put("/schema",c("header",i),async e=>{let{req:n}=e,t=await n.text();if(!t)return e.text("Missing schema",400);let r=n.param("schemaHash"),a=l.get(r);if(a==null){if(r!==await H(t))return e.text("Schema hash mismatch",400);let o=await R(t,e.get("db").prismaORMConnectionString,e.get("debug"));return l.set(r,{base64Original:t,...o}),e.text(r)}return t!==a.base64Original?e.text("Schema mismatch",400):e.text(r)});h.post("/transaction/start",c("header",i),async e=>{let{req:n}=e,t=await V(e);if(t instanceof Response)return t;try{let r=await b(e);if(r instanceof Response)return r;let a=await r.startTransaction(t,g(e)),o=j(a,e);if(o instanceof Response)return o;let{id:s}=o,m=n.param("clientVersion"),S=n.param("schemaHash");return e.json({...a,"data-proxy":{endpoint:`${new URL(n.url).origin}/${m}/${S}/itx/${s}`}})}catch(r){return d(r,e)}});async function b(e){let{req:n}=e,t=C(e);if(t instanceof Response)return t;let{base64Override:r,overrideHash:a}=t.schemas;return await x.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||n.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:a})}var ie=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[e,n]of ie)y.on(n,e,c("header",i),async t=>{let r=t.req.header("prisma-engine-hash");if(r!=="0.0.0"&&r!==P)throw new re(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${r} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${P}.`});return await(await O(t)).fetch(t.req.raw)});export{y as accelerateRoute};
@@ -1,3 +0,0 @@
1
- import{d as h,e as f,f as y}from"./chunk-OTI5SWIV.js";import{b as l,f as O,g as V,h as N,i as C}from"./chunk-DGKV2DPF.js";import{writeFile as Q}from"fs/promises";import{join as c}from"pathe";import{check as W,lock as X,unlock as ee}from"proper-lockfile";import{process as j}from"std-env";import{integer as F,literal as te,minLength as re,minValue as q,number as H,object as v,optional as g,parseJson as se,pipe as m,safeParse as ae,string as w,url as oe}from"valibot";import{setTimeout as z}from"timers/promises";import{process as P}from"std-env";function x(r,e){if(r==null)return!1;try{return P.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}async function A(r,e){if(!P.kill)return!1;try{P.kill(r,"SIGTERM")}catch(s){return e&&console.error(`Error killing process with PID ${r}:`,s),!1}let t=0;do{if(!x(r,e))return!0;await z(100)}while(++t<50);try{return P.kill(r,"SIGKILL")}catch(s){return e&&console.error(`Error forcefully killing process with PID ${r}:`,s),!1}}var _=m(w(),oe()),L=v({connectionString:_,prismaORMConnectionString:g(_),terminalCommand:g(w())}),J=v({url:_}),M=m(H(),F(),q(1)),ie=v({database:L,http:J,ppg:J,shadowDatabase:L}),ne=v({databasePort:M,exports:g(ie),name:m(w(),re(1)),pid:g(m(H(),F(),q(0))),port:M,shadowDatabasePort:M,version:te("1")}),E=Symbol("initialize"),k="default",u=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??f,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??k,this.persistenceMode=e.persistenceMode,this.pid=e.pid??j.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??f,this._shadowDatabasePort=e.shadowDatabasePort??f}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new p(e):new I(e);return await t[E](),t}static async fromServerDump(e){let{debug:t,name:s=k}=e??{},o=l(s),i=p.getServerDumpPath(o),a=await O(i);if(a==null)return t&&console.debug(`[State] No server dump file found at: ${i}`),null;t&&(console.debug(`[State] server dump file found at "${i}":`),console.debug(a));let{issues:n,output:d,success:b}=ae(m(w(),se(),ne),a);if(!b)throw t&&console.debug(`[State] Invalid server dump file at "${i}":
2
- ${JSON.stringify(n,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new p({databasePort:d.databasePort,debug:t,dryRun:!1,name:s,pid:d.pid,port:d.port,serverDump:d,shadowDatabasePort:d.shadowDatabasePort})}static async scan(e){let{debug:t,globs:s}=e??{},o=c(l(k),"..");t&&console.debug(`[State] scanning for server states in: ${o}`);let i=await N(o,s);return t&&console.debug(`[State] found server names: ${JSON.stringify(i)}`),await Promise.all(i.map(a=>K(a,e)))}get databasePort(){return this._databasePort}set databasePort(e){this.#t("databasePort",e)}get port(){return this._port}set port(e){this.#t("port",e)}get shadowDatabasePort(){return this._shadowDatabasePort}set shadowDatabasePort(e){this.#t("shadowDatabasePort",e)}#t(e,t){if(t<0||!Number.isInteger(t))throw new Error(`Invalid port number: ${t}`);let s=`_${e}`;if(this[s]!==h&&this[s]!==t)throw new Error(`\`${e}\` is already set to ${this[s]}, cannot change it to ${t}`);this[s]=t}},I=class extends u{constructor(e){super({...e,databasePort:e?.databasePort||h,persistenceMode:"stateless",port:e?.port||h,shadowDatabasePort:e?.shadowDatabasePort||h})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[E](){let e;try{e=await u.scan({debug:this.debug,onlyMetadata:!0})}catch(s){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",s),e=[]}let t=await y({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort}async close(){}async writeServerDump(){}},p=class r extends u{#t;#e;#s;#o;#i;#a;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#a=!1,this.#e=l(this.name),this.#t=c(this.#e,"db_dump.bak"),this.#s=c(this.#e,".lock"),this.#o=c(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#i=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return c(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[E](){await V(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await X(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await u.scan({debug:this.debug,onlyMetadata:!0}),t=await y({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new T(this):e}}async close(){if(!this.#a)try{await ee(this.#e,{lockfilePath:this.#s}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:j.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await Q(this.#i,`${JSON.stringify(this.#r,null,2)}
3
- `,{encoding:"utf-8"})}};async function Se(r,e){await de(r,e);let t=l(typeof r=="string"?r:r.name);await C(t)}async function K(r,e){let{debug:t,onlyMetadata:s}=e||{},o=typeof r=="string"?r:r.name,i=typeof r!="string"?r:void 0,a={databasePort:i?.databasePort??-1,exports:i?.exports,name:o,pid:i?.pid,port:i?.port??-1,shadowDatabasePort:i?.shadowDatabasePort??-1,version:"1"};try{let n=i||await u.fromServerDump({debug:t,name:o});if(!n)return t&&console.debug(`[State] no server state found for name: ${o}`),{...a,status:"no_such_server"};a.databasePort=n.databasePort,a.exports=n.exports,a.pid=n.pid,a.port=n.port,a.shadowDatabasePort=n.shadowDatabasePort;let{exports:d,pid:b}=n;if(s)return{...a,status:"unknown"};if(!x(b,t))return t&&console.debug(`[State] server state for "${o}" has no running process with PID: ${b}`),{...a,status:"not_running"};let R=l(o);try{if(!await W(R,{lockfilePath:c(R,".lock")}))return t&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(G){t&&console.error(`[State] server state for "${o}" failed to check lock:`,G)}if(!d)return{...a,status:"starting_up"};let{http:Y}=d,{hc:B}=await import("hono/client"),D=await B(Y.url).health.$get();if(!D.ok)return t&&console.debug(`[State] server state for "${o}" is not live: ${JSON.stringify(D)}`),{...a,status:"not_running"};let S=await D.json();return S.name!==r?(t&&console.debug(`[State] server state for "${o}" has mismatched health response: ${JSON.stringify(S)}`),{...a,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(S)}`),{...a,status:"running"})}catch(n){return t&&console.error(`[State] failed to get server status for "${o}":`,n),{...a,status:"error"}}}function ue(r){let{status:e}=r;return e==="running"||e==="starting_up"}async function de(r,e){let{pid:t,...s}=typeof r=="string"?await K(r,{debug:e}):r;if(!ue(s))return!1;let o=await u.fromServerDump({debug:e,name:s.name});if(t==null){e&&console.debug(`[State] No PID found for server "${s.name}" to kill.`);try{await o?.close()}catch{}return!1}let i=await A(t,e);try{await o?.close()}catch{}return i}var $=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},T=class extends ${#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return u.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{u as a,Se as b,K as c,ue as d,de as e,$ as f,T as g};
@@ -1 +0,0 @@
1
- import{d as v}from"./chunk-ZSBTZQZ3.js";import{a as E}from"./chunk-FIY24ARL.js";import{g as p}from"./chunk-OTI5SWIV.js";import{a as S,c as d,d as f}from"./chunk-6ORCLJD5.js";import{createServer as b}from"http";import{promisify as D}from"util";import A from"@prisma/get-platform";async function h(o,e){let{port:r}=e;if(e.dryRun)return P(r,null);let t=await W(o,e),{promise:n,reject:m,resolve:s}=d(),{serve:a}=await import("@hono/node-server"),i=a({createServer:b,fetch:t.fetch,overrideGlobalObjects:!1,port:r},s);i.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return m(new p(r));console.error("[Accelerate]",c)});let{port:l}=await n;return e.port=l,P(l,i)}function P(o,e){return{async close(){e&&await Promise.allSettled([D(e.close.bind(e))(),f.stopAll()])},port:o,url:`http://localhost:${o}`}}async function W(o,e){let{debug:r}=e,[{Hono:t},{accelerateRoute:n},{utilityRoute:m}]=await Promise.all([import("hono/tiny"),import("./accelerate-HABH6RJU.js"),import("./utility-Q5A254LJ.js")]),s=new t,a=await A.getPlatformInfo();if(r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(a)),r){let{logger:l}=await import("hono/logger");s.use("*",l((...c)=>console.log("[Accelerate]",...c)))}s.use("*",async(l,c)=>(l.set("databaseDumpPath",e.databaseDumpPath),l.set("db",o),l.set("debug",!!r),l.set("name",e.name),l.set("platform",a),l.set("shadowDBPort",e.shadowDatabasePort),await c()));let i=new t;return i.route("/",n),i.route("/",m),s.route("/",i),s}async function w(o){let e=await E.createExclusively(o),r=null,t=null,n=null;try{[r,n]=await Promise.all([v("database",e),v("shadow_database",e)]);let m=await r.attachWalEventBridge();t=await h(r,e);let s=R(r,n,t,e);await e.writeServerDump(s);let a=B(m),i=r,l=n,c=t,u=async()=>{a.close(),await x(e,[c,i,l])};return{close:u,dbServer:r,httpServer:t,server:{...s,close:u,experimental:{wal:a.api},name:e.name},serverState:e,shadowDbServer:n,walBridge:m}}catch(m){return await T(e,[t,r,n],m)}}function R(o,e,r,t){let n=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:S({databaseUrl:o.prismaORMConnectionString,name:t.name,shadowDatabaseUrl:e.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:o.connectionString,prismaORMConnectionString:o.prismaORMConnectionString,terminalCommand:o.terminalCommand},http:{url:r.url},ppg:{url:n},shadowDatabase:{connectionString:e.prismaORMConnectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand}}}async function x(o,e){let t=(await Promise.allSettled(e.map(n=>n.close()))).filter(n=>n.status==="rejected").map(n=>new Error(n.reason));try{await o.close()}catch(n){t.push(n)}if(t.length>0)throw new AggregateError(t,"Failed to close some servers")}async function T(o,e,r){try{await x(o,e.filter(t=>t!==null))}catch(t){throw new AggregateError([r,t],"Failed to start Prisma Dev server cleanly")}throw r}function B(o){let e=new Set;return{api:{stream:()=>{let r=()=>{},t=C(o,()=>{e.delete(r)});return r=()=>t.close(),e.add(r),t.stream},subscribe:r=>o.subscribe(r)},close:()=>{for(let r of[...e])r();e.clear()}}}function C(o,e){let r=[],t=!1,n=null,m=o.subscribe(a=>{if(!t){if(n){let i=n;n=null,i.resolve({done:!1,value:a});return}r.push(a)}}),s=()=>{if(!t&&(t=!0,m(),r.length=0,e(),n)){let a=n;n=null,a.resolve({done:!0,value:void 0})}};return{close:s,stream:{[Symbol.asyncIterator](){return this},next(){return r.length>0?Promise.resolve({done:!1,value:r.shift()}):t?Promise.resolve({done:!0,value:void 0}):new Promise((a,i)=>{n={reject:i,resolve:a}})},return(){return s(),Promise.resolve({done:!0,value:void 0})},throw(a){let i=n;return s(),i&&i.reject(a),Promise.reject(a instanceof Error?a:new Error(String(a)))}}}}async function O(o){let{server:e}=await w(o);return e}async function re(o){return await O(o)}export{O as a,re as b};
@@ -1 +0,0 @@
1
- import{checkPort as w,getPort as m,isUnsafePort as O}from"get-port-please";import{difference as T,range as $}from"remeda";var v=51214,h=51213,S=51215,p=65535,k=0,P=-1/0;async function E(o){let{debug:t,name:r,requestedPorts:n,servers:u}=o,{portsUsedByOtherServers:e,portsUsedByThisServerLastTime:a}=B(r,u);t&&(console.debug(`ports used by other servers: ${Object.keys(e).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let i={databasePort:P,port:P,shadowDatabasePort:P},s=["port","databasePort","shadowDatabasePort"];for(let c of s){let d=await x({debug:t,portKey:c,portsUsedByOtherServers:e,portsUsedByThisServerLastTime:a,requestedPorts:n})??await U({debug:t,pickedPorts:i,portKey:c,portsUsedByOtherServers:e,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${c}": ${d}`),i[c]=d}return t&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function x(o){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:u,requestedPorts:e}=o,{[r]:a,...i}=e;if(g(a))return await R({debug:t,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let s=u?.[r]??P;if(!g(s))return t&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let c=s in n;return c||Object.values(i).includes(s)?(t&&console.debug(`Port ${s} that was used last time for this server, ${c?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await w(s)===!1?(t&&console.debug(`Port ${s}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(t&&console.debug(`Using port ${s} for "${r}" as it was used last time and is available.`),s)}async function U(o){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:u,portsUsedByThisServerLastTime:e}=o,a=Math.max(v,h,S)+1,i=[...Object.values(r),...Object.keys(u).map(Number),...Object.values(e||{})],s=Math.min(Math.max(a,...i)+100,p),c=T($(a,s),i),d={port:h,databasePort:v,shadowDatabasePort:S}[n];try{return await m({port:d in u||Object.values(r).includes(d)||Object.values(e||{}).includes(d)?void 0:d,ports:c})}catch(b){if(b instanceof Error&&b.name==="GetPortError"&&s+1<=p)return t&&console.debug(`Expanding port lookup to range [${s+1}, ${p}].`),await m({portRange:[s+1,p]});throw b}}function g(o){return Number.isFinite(o)&&o>=0}function B(o,t){let r={},n;for(let u of t){let{databasePort:e,port:a,shadowDatabasePort:i}=u;if(u.name===o){n={databasePort:e,port:a,shadowDatabasePort:i};continue}r[e]=!0,r[a]=!0,r[i]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}async function R(o){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:u,requestedPort:e}=o;if(e!==k){if(e in u)throw t&&console.error(`Port ${e} was requested for "${n}", but is already used by another server.`),new y(e);if(Object.values(r).includes(e))throw t&&console.error(`Port ${e} was requested for "${n}", but also for another key.`),new l(e);if(O(e))throw t&&console.error(`Port ${e} was requested for "${n}", but is unsafe.`),new f(e);if(await w(e)===!1)throw t&&console.error(`Port ${e} was requested for "${n}", but is not available.`),new f(e)}}var f=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},l=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},y=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};export{v as a,h as b,S as c,k as d,P as e,E as f,f as g};
@@ -1,84 +0,0 @@
1
- import{c as P}from"./chunk-62DM64XC.js";import{g as _}from"./chunk-OTI5SWIV.js";import{e as b}from"./chunk-DGKV2DPF.js";import{filename as X}from"pathe/utils";import{protocol as D}from"@electric-sql/pglite";var d="_prisma_dev_wal",T="events",v="install_all_triggers",A="capture_event",L="prisma_dev_wal_capture",g=new WeakMap,F=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function S(e,t){let s=g.get(e);if(s&&!s.closed)return s.bridge;let r=e.execProtocolRaw.bind(e),n=e.execProtocolRawStream.bind(e),o={bridge:{close:async()=>{o.closed||(o.closed=!0,o.subscribers.clear(),e.execProtocolRaw===m&&(e.execProtocolRaw=r),e.execProtocolRawStream===c&&(e.execProtocolRawStream=n),await o.pollPromise,g.delete(e))},poll:async()=>{await w(o,e)},subscribe:a=>(o.subscribers.add(a),()=>{o.subscribers.delete(a)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},m=async(a,E)=>{let l=await r(a,E);return!o.closed&&o.suppressDepth===0&&y(l)&&w(o,e),l},c=async(a,E)=>{let l=[],u=new D.Parser,p=E?.onRawData;await n(a,{...E,onRawData:N=>{u.parse(N,W=>{l.push(W)}),p?.(N)}}),!o.closed&&o.suppressDepth===0&&R(l)&&w(o,e)};return e.execProtocolRaw=m,e.execProtocolRawStream=c,g.set(e,o),await I(o,e),o.bridge}async function O(e){let t=g.get(e);t&&await t.bridge.close()}function R(e){for(let t of e){if(t.name!=="commandComplete"||typeof t.text!="string")continue;let s=t.text.split(/\s+/,1)[0]?.toUpperCase();if(s&&F.has(s))return!0}return!1}function y(e){if(e.length===0)return!1;let t=[];return new D.Parser().parse(e,r=>{t.push(r)}),R(t)}async function I(e,t){e.ensureInfrastructurePromise??=f(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${d}"`),await t.exec(`
2
- CREATE TABLE IF NOT EXISTS "${d}"."${T}" (
3
- id BIGSERIAL PRIMARY KEY,
4
- txid BIGINT NOT NULL DEFAULT txid_current(),
5
- schema_name TEXT NOT NULL,
6
- table_name TEXT NOT NULL,
7
- op TEXT NOT NULL,
8
- row_data JSONB,
9
- old_row_data JSONB,
10
- created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
11
- )
12
- `),await t.exec(`
13
- CREATE OR REPLACE FUNCTION "${d}"."${A}"()
14
- RETURNS trigger
15
- LANGUAGE plpgsql
16
- AS $$
17
- BEGIN
18
- IF TG_TABLE_SCHEMA = '${d}' THEN
19
- RETURN COALESCE(NEW, OLD);
20
- END IF;
21
-
22
- INSERT INTO "${d}"."${T}" (
23
- txid,
24
- schema_name,
25
- table_name,
26
- op,
27
- row_data,
28
- old_row_data
29
- )
30
- VALUES (
31
- txid_current(),
32
- TG_TABLE_SCHEMA,
33
- TG_TABLE_NAME,
34
- lower(TG_OP),
35
- CASE WHEN TG_OP IN ('INSERT', 'UPDATE') THEN to_jsonb(NEW) ELSE NULL END,
36
- CASE WHEN TG_OP IN ('UPDATE', 'DELETE') THEN to_jsonb(OLD) ELSE NULL END
37
- );
38
-
39
- RETURN COALESCE(NEW, OLD);
40
- END;
41
- $$;
42
- `),await t.exec(`
43
- CREATE OR REPLACE FUNCTION "${d}"."${v}"()
44
- RETURNS void
45
- LANGUAGE plpgsql
46
- AS $$
47
- DECLARE
48
- target REGCLASS;
49
- BEGIN
50
- FOR target IN
51
- SELECT c.oid::regclass
52
- FROM pg_class AS c
53
- JOIN pg_namespace AS n ON n.oid = c.relnamespace
54
- WHERE c.relkind IN ('r', 'p')
55
- AND n.nspname NOT IN ('${d}', 'information_schema', 'pg_catalog')
56
- AND n.nspname NOT LIKE 'pg_temp_%'
57
- AND n.nspname NOT LIKE 'pg_toast%'
58
- LOOP
59
- IF EXISTS (
60
- SELECT 1
61
- FROM pg_trigger
62
- WHERE tgrelid = target
63
- AND tgname = '${L}'
64
- ) THEN
65
- CONTINUE;
66
- END IF;
67
-
68
- EXECUTE format(
69
- 'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${d}"."${A}"()',
70
- '${L}',
71
- target::text
72
- );
73
- END LOOP;
74
- END;
75
- $$;
76
- `),await h(e,t)}),await e.ensureInfrastructurePromise}async function h(e,t){await f(e,t,async()=>{await t.query(`SELECT "${d}"."${v}"()`)})}async function k(e,t){await I(e,t),await h(e,t);let s=await f(e,t,async()=>await t.query(`
77
- WITH drained AS (
78
- DELETE FROM "${d}"."${T}"
79
- RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id
80
- )
81
- SELECT txid, schema_name, table_name, op, row_data, old_row_data
82
- FROM drained
83
- ORDER BY id
84
- `));if(s.rows.length===0||e.subscribers.size===0)return;let r=s.rows.map(H);for(let n of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(n))try{n(r)}catch(o){console.error("[WAL bridge] subscriber failed",o)}})}async function w(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await k(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function f(e,t,s){e.suppressDepth+=1;try{return await s()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&g.get(t)!==e&&(e.closed=!0)}}function H(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:q(e.op)}}function q(e){switch(e.toLowerCase()){case"delete":return"delete";case"insert":return"insert";case"update":return"update";default:throw new Error(`Unsupported WAL bridge operation: ${e}`)}}var Y=10,i={connectionLimit:Y,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Q=`postgres://${i.username}:${i.password}@localhost`,$=new URLSearchParams({sslmode:i.sslMode}),J=new URLSearchParams({...Object.fromEntries($.entries()),connection_limit:String(i.connectionLimit),connect_timeout:String(i.connectTimeout),max_idle_connection_lifetime:String(i.maxIdleConnectionLifetime),pool_timeout:String(i.poolTimeout),socket_timeout:String(i.socketTimeout)});async function C(e){let{rows:t}=await e.query("SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = 'postgres') AS exists");t[0]?.exists?await e.exec(`ALTER ROLE ${i.username} WITH LOGIN SUPERUSER PASSWORD '${i.password}'`):await e.exec(`CREATE ROLE ${i.username} WITH LOGIN SUPERUSER PASSWORD '${i.password}'`),await e.exec(`SET ROLE ${i.username}`)}async function ae(e,t){let s=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return x(e,t,{db:null,port:s,server:null});let{debug:r}=t,o=await(e==="shadow_database"?j:G)(t.pgliteDataDirPath,r);r&&o.onNotification((l,u)=>{console.debug(`[${e}][${l}] ${u}`)});let{PGLiteSocketServer:m}=await import("@electric-sql/pglite-socket"),c=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis,a=new m({db:o,debug:r,idleTimeout:Number.isFinite(c)?c:0,inspect:r,maxConnections:i.connectionLimit,port:s});r&&(a.addEventListener("listening",l=>{let{detail:u}=l;console.debug(`[${e}] server listening on ${JSON.stringify(u)}`)}),a.addEventListener("connection",l=>{let{clientAddress:u,clientPort:p}=l.detail;console.debug(`[${e}] client connected from ${u}:${p}`)}),a.addEventListener("error",l=>{let{detail:u}=l;console.error(`[${e}] server error:`,u)}));try{await a.start()}catch(l){throw l instanceof Error&&"code"in l&&l.code==="EADDRINUSE"?new _(s):l}let E=Number(a.getServerConn().split(":").at(1));return t[e==="database"?"databasePort":"shadowDatabasePort"]=E,x(e,t,{db:o,port:E,server:a})}function x(e,t,s){let{debug:r}=t,{db:n,port:o,server:m}=s||{};return r&&console.debug(`[${e}] server started on port ${o}`),{...i,attachWalEventBridge:async()=>{if(e!=="database"||!n)throw new Error("WAL bridge is only available for the primary database server");return await S(n)},close:async()=>{let c=[];try{await m?.stop(),r&&console.debug(`[${e}] server stopped on port ${o}`)}catch(a){console.error(`[${e}] server stop error`,a),c.push(a)}if(e==="database"){try{n&&await O(n),r&&console.debug(`[${e}] closed WAL bridge`)}catch(a){console.error(`[${e}] WAL bridge close error`,a),c.push(a)}try{await n?.syncToFs(),r&&console.debug(`[${e}] synced to filesystem`)}catch(a){console.error(`[${e}] sync error`,a),c.push(a)}}try{await n?.close(),r&&console.debug(`[${e}] closed`)}catch(a){console.error(`[${e}] close error`,a),c.push(a)}if(c.length>0)throw new AggregateError(c,`Failed to close ${e} properly`)},connectionString:B(o,$),dump:async c=>{e==="shadow_database"||!n||await K({db:n,debug:r,destinationPath:c})},port:o,prismaORMConnectionString:B(o,J),terminalCommand:`PGPASSWORD=${i.password} PGSSLMODE=${i.sslMode} psql -h localhost -p ${o} -U ${i.username} -d ${i.database}`}}function B(e,t){return`${Q}:${e}/${i.database}?${t.toString()}`}async function G(e,t){let{PGlite:s}=await import("@electric-sql/pglite"),r=await P(),n=await s.create({database:i.database,dataDir:e,debug:t?5:void 0,extensions:r.extensions,fsBundle:r.fsBundle,relaxedDurability:!1,wasmModule:r.wasmModule});return await C(n),n}async function j(e,t){let{PGlite:s}=await import("@electric-sql/pglite"),r=await P(),n=await s.create({database:i.database,dataDir:"memory://",debug:t?5:void 0,extensions:r.extensions,fsBundle:r.fsBundle,relaxedDurability:!1,wasmModule:r.wasmModule});return await C(n),n}async function K(e){let{dataDir:t,db:s,debug:r,destinationPath:n}=e,o=s||await G(t,r),{pgDump:m}=await import("@electric-sql/pglite-tools/pg_dump"),c=await m({args:["--schema-only","--no-owner"],fileName:n?X(n):void 0,pg:await o.clone()});return n?(r&&console.debug(`[DB] Dumping database to ${n}`),await b(c,n)):(r&&console.debug("[DB] Dumping database to memory"),await c.text())}export{S as a,R as b,y as c,ae as d,K as e};