@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.
@@ -0,0 +1,235 @@
1
+ import * as valibot from 'valibot';
2
+ import { InferOutput } from 'valibot';
3
+
4
+ interface ExperimentalStreams {
5
+ readonly serverUrl: string;
6
+ readonly sqlitePath: string;
7
+ readonly streamName: string;
8
+ readonly url: string;
9
+ }
10
+ interface ExperimentalServerMetadata {
11
+ readonly streams?: ExperimentalStreams;
12
+ }
13
+
14
+ declare const exportsSchema: valibot.ObjectSchema<{
15
+ readonly database: valibot.ObjectSchema<{
16
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
17
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
18
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
19
+ }, undefined>;
20
+ readonly http: valibot.ObjectSchema<{
21
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
22
+ }, undefined>;
23
+ readonly ppg: valibot.ObjectSchema<{
24
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
25
+ }, undefined>;
26
+ readonly shadowDatabase: 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
+ }, undefined>;
32
+ type Exports = InferOutput<typeof exportsSchema>;
33
+ declare const serverDumpV1Schema: valibot.ObjectSchema<{
34
+ readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
35
+ readonly experimental: valibot.OptionalSchema<valibot.ObjectSchema<{
36
+ readonly streams: valibot.OptionalSchema<valibot.ObjectSchema<{
37
+ readonly serverUrl: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
38
+ readonly sqlitePath: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
39
+ readonly streamName: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
40
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
41
+ }, undefined>, undefined>;
42
+ }, undefined>, undefined>;
43
+ readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
44
+ readonly database: valibot.ObjectSchema<{
45
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
46
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
47
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
48
+ }, undefined>;
49
+ readonly http: valibot.ObjectSchema<{
50
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
51
+ }, undefined>;
52
+ readonly ppg: valibot.ObjectSchema<{
53
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
54
+ }, undefined>;
55
+ readonly shadowDatabase: valibot.ObjectSchema<{
56
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
57
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
58
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
59
+ }, undefined>;
60
+ }, undefined>, undefined>;
61
+ readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
62
+ readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
63
+ readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
64
+ readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
65
+ readonly version: valibot.LiteralSchema<"1", undefined>;
66
+ }, undefined>;
67
+ type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
68
+ interface ServerOptions {
69
+ /**
70
+ * Connection timeout in milliseconds for pending database connections.
71
+ *
72
+ * This option is currently not enforced by the multiplexed
73
+ * `@electric-sql/pglite-socket` server used by `@prisma/dev`.
74
+ * It is kept for API compatibility until upstream exposes a queue-timeout
75
+ * equivalent again.
76
+ *
77
+ * Default is 1 minute (60,000 milliseconds).
78
+ */
79
+ databaseConnectTimeoutMillis?: number;
80
+ /**
81
+ * Idle timeout in milliseconds for open database connections.
82
+ *
83
+ * Re-starts ticking after each message received on a connection. When exceeded,
84
+ * that client connection is closed by the socket server.
85
+ *
86
+ * Is not applied by default.
87
+ *
88
+ * Use it with caution, as it may lead to unexpected disconnections. Best used
89
+ * with a pool client that can handle disconnections gracefully.
90
+ *
91
+ * Set it if you suffer from client hanging indefinitely as the active connection
92
+ * remain open forever.
93
+ */
94
+ databaseIdleTimeoutMillis?: number;
95
+ /**
96
+ * The port the database server will listen on.
97
+ *
98
+ * Defaults to `51214`.
99
+ *
100
+ * An error is thrown if the port is already in use.
101
+ */
102
+ databasePort?: number;
103
+ /**
104
+ * Whether to enable debug logging.
105
+ *
106
+ * Defaults to `false`.
107
+ */
108
+ debug?: boolean;
109
+ /**
110
+ * Whether to run the server in dry run mode.
111
+ *
112
+ * Defaults to `false`.
113
+ */
114
+ dryRun?: boolean;
115
+ /**
116
+ * The name of the server.
117
+ *
118
+ * Defaults to `default`.
119
+ */
120
+ name?: string;
121
+ /**
122
+ * The persistence mode of the server.
123
+ *
124
+ * Default is `stateless`.
125
+ */
126
+ persistenceMode?: PersistenceMode;
127
+ /**
128
+ * The port the server will listen on.
129
+ *
130
+ * Defaults to `51213`.
131
+ *
132
+ * An error is thrown if the port is already in use.
133
+ */
134
+ port?: number;
135
+ /**
136
+ * Connection timeout in milliseconds for pending shadow database connections.
137
+ *
138
+ * Default is {@link databaseConnectTimeoutMillis}.
139
+ */
140
+ shadowDatabaseConnectTimeoutMillis?: number;
141
+ /**
142
+ * Idle timeout in milliseconds for active shadow database connections.
143
+ *
144
+ * Default is {@link databaseIdleTimeoutMillis}.
145
+ */
146
+ shadowDatabaseIdleTimeoutMillis?: number;
147
+ /**
148
+ * The port the shadow database server will listen on.
149
+ *
150
+ * Defaults to `51215`.
151
+ *
152
+ * An error is thrown if the port is already in use.
153
+ */
154
+ shadowDatabasePort?: number;
155
+ }
156
+ type ResolvedServerOptions = Required<ServerOptions>;
157
+ type PersistenceMode = "stateless" | "stateful";
158
+ interface ScanOptions {
159
+ debug?: boolean;
160
+ globs?: string[];
161
+ onlyMetadata?: boolean;
162
+ }
163
+ declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
164
+ declare abstract class ServerState implements ResolvedServerOptions {
165
+ #private;
166
+ protected _databasePort: number;
167
+ readonly databaseConnectTimeoutMillis: number;
168
+ readonly databaseIdleTimeoutMillis: number;
169
+ readonly debug: boolean;
170
+ readonly dryRun: boolean;
171
+ readonly name: string;
172
+ readonly persistenceMode: PersistenceMode;
173
+ readonly pid: number | undefined;
174
+ readonly shadowDatabaseConnectTimeoutMillis: number;
175
+ readonly shadowDatabaseIdleTimeoutMillis: number;
176
+ protected _port: number;
177
+ protected _shadowDatabasePort: number;
178
+ protected _streamsPort: number;
179
+ protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
180
+ persistenceMode: PersistenceMode;
181
+ pid?: number | undefined;
182
+ });
183
+ static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
184
+ static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
185
+ static scan(options?: ScanOptions): Promise<ServerStatusV1[]>;
186
+ abstract get databaseDumpPath(): string;
187
+ abstract get pgliteDataDirPath(): string;
188
+ abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
189
+ abstract close(): Promise<void>;
190
+ abstract writeServerDump(exports?: Exports, experimental?: ExperimentalServerMetadata): Promise<void>;
191
+ get databasePort(): number;
192
+ set databasePort(value: number);
193
+ get port(): number;
194
+ set port(value: number);
195
+ get shadowDatabasePort(): number;
196
+ get streamsPort(): number;
197
+ set shadowDatabasePort(value: number);
198
+ }
199
+ declare class StatefulServerState extends ServerState {
200
+ #private;
201
+ constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
202
+ pid?: number | undefined;
203
+ serverDump?: ServerDumpV1;
204
+ }) | undefined);
205
+ static getServerDumpPath(dataDirPath: string): string;
206
+ get databaseDumpPath(): string;
207
+ get exports(): Exports | undefined;
208
+ get experimental(): ExperimentalServerMetadata | undefined;
209
+ get pgliteDataDirPath(): string;
210
+ [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
211
+ close(): Promise<void>;
212
+ writeServerDump(exports?: Exports, experimental?: ExperimentalServerMetadata): Promise<void>;
213
+ }
214
+ interface ServerStatusV1 extends ServerDumpV1 {
215
+ status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
216
+ }
217
+ declare function deleteServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<void>;
218
+ declare function getServerStatus(nameOrState: string | StatefulServerState, options?: ScanOptions): Promise<ServerStatusV1>;
219
+ declare function isServerRunning(server: ServerStatusV1): boolean;
220
+ declare function killServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<boolean>;
221
+ /**
222
+ * @deprecated use `ServerAlreadyRunningError` instead. Will be removed in a future version.
223
+ */
224
+ declare class ServerStateAlreadyExistsError extends Error {
225
+ name: string;
226
+ constructor(name: string);
227
+ }
228
+ declare class ServerAlreadyRunningError extends ServerStateAlreadyExistsError {
229
+ #private;
230
+ name: string;
231
+ constructor(server: ServerState);
232
+ get server(): Promise<ServerState | null>;
233
+ }
234
+
235
+ export { type ExperimentalStreams as E, type PersistenceMode as P, type ResolvedServerOptions as R, type ServerOptions as S, type Exports as a, ServerAlreadyRunningError as b, ServerState as c, type ScanOptions as d, type ServerDumpV1 as e, ServerStateAlreadyExistsError as f, type ServerStatusV1 as g, deleteServer as h, getServerStatus as i, isServerRunning as j, killServer as k };
@@ -0,0 +1,235 @@
1
+ import * as valibot from 'valibot';
2
+ import { InferOutput } from 'valibot';
3
+
4
+ interface ExperimentalStreams {
5
+ readonly serverUrl: string;
6
+ readonly sqlitePath: string;
7
+ readonly streamName: string;
8
+ readonly url: string;
9
+ }
10
+ interface ExperimentalServerMetadata {
11
+ readonly streams?: ExperimentalStreams;
12
+ }
13
+
14
+ declare const exportsSchema: valibot.ObjectSchema<{
15
+ readonly database: valibot.ObjectSchema<{
16
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
17
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
18
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
19
+ }, undefined>;
20
+ readonly http: valibot.ObjectSchema<{
21
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
22
+ }, undefined>;
23
+ readonly ppg: valibot.ObjectSchema<{
24
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
25
+ }, undefined>;
26
+ readonly shadowDatabase: 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
+ }, undefined>;
32
+ type Exports = InferOutput<typeof exportsSchema>;
33
+ declare const serverDumpV1Schema: valibot.ObjectSchema<{
34
+ readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
35
+ readonly experimental: valibot.OptionalSchema<valibot.ObjectSchema<{
36
+ readonly streams: valibot.OptionalSchema<valibot.ObjectSchema<{
37
+ readonly serverUrl: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
38
+ readonly sqlitePath: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
39
+ readonly streamName: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
40
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
41
+ }, undefined>, undefined>;
42
+ }, undefined>, undefined>;
43
+ readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
44
+ readonly database: valibot.ObjectSchema<{
45
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
46
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
47
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
48
+ }, undefined>;
49
+ readonly http: valibot.ObjectSchema<{
50
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
51
+ }, undefined>;
52
+ readonly ppg: valibot.ObjectSchema<{
53
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
54
+ }, undefined>;
55
+ readonly shadowDatabase: valibot.ObjectSchema<{
56
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
57
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
58
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
59
+ }, undefined>;
60
+ }, undefined>, undefined>;
61
+ readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
62
+ readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
63
+ readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
64
+ readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
65
+ readonly version: valibot.LiteralSchema<"1", undefined>;
66
+ }, undefined>;
67
+ type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
68
+ interface ServerOptions {
69
+ /**
70
+ * Connection timeout in milliseconds for pending database connections.
71
+ *
72
+ * This option is currently not enforced by the multiplexed
73
+ * `@electric-sql/pglite-socket` server used by `@prisma/dev`.
74
+ * It is kept for API compatibility until upstream exposes a queue-timeout
75
+ * equivalent again.
76
+ *
77
+ * Default is 1 minute (60,000 milliseconds).
78
+ */
79
+ databaseConnectTimeoutMillis?: number;
80
+ /**
81
+ * Idle timeout in milliseconds for open database connections.
82
+ *
83
+ * Re-starts ticking after each message received on a connection. When exceeded,
84
+ * that client connection is closed by the socket server.
85
+ *
86
+ * Is not applied by default.
87
+ *
88
+ * Use it with caution, as it may lead to unexpected disconnections. Best used
89
+ * with a pool client that can handle disconnections gracefully.
90
+ *
91
+ * Set it if you suffer from client hanging indefinitely as the active connection
92
+ * remain open forever.
93
+ */
94
+ databaseIdleTimeoutMillis?: number;
95
+ /**
96
+ * The port the database server will listen on.
97
+ *
98
+ * Defaults to `51214`.
99
+ *
100
+ * An error is thrown if the port is already in use.
101
+ */
102
+ databasePort?: number;
103
+ /**
104
+ * Whether to enable debug logging.
105
+ *
106
+ * Defaults to `false`.
107
+ */
108
+ debug?: boolean;
109
+ /**
110
+ * Whether to run the server in dry run mode.
111
+ *
112
+ * Defaults to `false`.
113
+ */
114
+ dryRun?: boolean;
115
+ /**
116
+ * The name of the server.
117
+ *
118
+ * Defaults to `default`.
119
+ */
120
+ name?: string;
121
+ /**
122
+ * The persistence mode of the server.
123
+ *
124
+ * Default is `stateless`.
125
+ */
126
+ persistenceMode?: PersistenceMode;
127
+ /**
128
+ * The port the server will listen on.
129
+ *
130
+ * Defaults to `51213`.
131
+ *
132
+ * An error is thrown if the port is already in use.
133
+ */
134
+ port?: number;
135
+ /**
136
+ * Connection timeout in milliseconds for pending shadow database connections.
137
+ *
138
+ * Default is {@link databaseConnectTimeoutMillis}.
139
+ */
140
+ shadowDatabaseConnectTimeoutMillis?: number;
141
+ /**
142
+ * Idle timeout in milliseconds for active shadow database connections.
143
+ *
144
+ * Default is {@link databaseIdleTimeoutMillis}.
145
+ */
146
+ shadowDatabaseIdleTimeoutMillis?: number;
147
+ /**
148
+ * The port the shadow database server will listen on.
149
+ *
150
+ * Defaults to `51215`.
151
+ *
152
+ * An error is thrown if the port is already in use.
153
+ */
154
+ shadowDatabasePort?: number;
155
+ }
156
+ type ResolvedServerOptions = Required<ServerOptions>;
157
+ type PersistenceMode = "stateless" | "stateful";
158
+ interface ScanOptions {
159
+ debug?: boolean;
160
+ globs?: string[];
161
+ onlyMetadata?: boolean;
162
+ }
163
+ declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
164
+ declare abstract class ServerState implements ResolvedServerOptions {
165
+ #private;
166
+ protected _databasePort: number;
167
+ readonly databaseConnectTimeoutMillis: number;
168
+ readonly databaseIdleTimeoutMillis: number;
169
+ readonly debug: boolean;
170
+ readonly dryRun: boolean;
171
+ readonly name: string;
172
+ readonly persistenceMode: PersistenceMode;
173
+ readonly pid: number | undefined;
174
+ readonly shadowDatabaseConnectTimeoutMillis: number;
175
+ readonly shadowDatabaseIdleTimeoutMillis: number;
176
+ protected _port: number;
177
+ protected _shadowDatabasePort: number;
178
+ protected _streamsPort: number;
179
+ protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
180
+ persistenceMode: PersistenceMode;
181
+ pid?: number | undefined;
182
+ });
183
+ static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
184
+ static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
185
+ static scan(options?: ScanOptions): Promise<ServerStatusV1[]>;
186
+ abstract get databaseDumpPath(): string;
187
+ abstract get pgliteDataDirPath(): string;
188
+ abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
189
+ abstract close(): Promise<void>;
190
+ abstract writeServerDump(exports?: Exports, experimental?: ExperimentalServerMetadata): Promise<void>;
191
+ get databasePort(): number;
192
+ set databasePort(value: number);
193
+ get port(): number;
194
+ set port(value: number);
195
+ get shadowDatabasePort(): number;
196
+ get streamsPort(): number;
197
+ set shadowDatabasePort(value: number);
198
+ }
199
+ declare class StatefulServerState extends ServerState {
200
+ #private;
201
+ constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
202
+ pid?: number | undefined;
203
+ serverDump?: ServerDumpV1;
204
+ }) | undefined);
205
+ static getServerDumpPath(dataDirPath: string): string;
206
+ get databaseDumpPath(): string;
207
+ get exports(): Exports | undefined;
208
+ get experimental(): ExperimentalServerMetadata | undefined;
209
+ get pgliteDataDirPath(): string;
210
+ [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
211
+ close(): Promise<void>;
212
+ writeServerDump(exports?: Exports, experimental?: ExperimentalServerMetadata): Promise<void>;
213
+ }
214
+ interface ServerStatusV1 extends ServerDumpV1 {
215
+ status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
216
+ }
217
+ declare function deleteServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<void>;
218
+ declare function getServerStatus(nameOrState: string | StatefulServerState, options?: ScanOptions): Promise<ServerStatusV1>;
219
+ declare function isServerRunning(server: ServerStatusV1): boolean;
220
+ declare function killServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<boolean>;
221
+ /**
222
+ * @deprecated use `ServerAlreadyRunningError` instead. Will be removed in a future version.
223
+ */
224
+ declare class ServerStateAlreadyExistsError extends Error {
225
+ name: string;
226
+ constructor(name: string);
227
+ }
228
+ declare class ServerAlreadyRunningError extends ServerStateAlreadyExistsError {
229
+ #private;
230
+ name: string;
231
+ constructor(server: ServerState);
232
+ get server(): Promise<ServerState | null>;
233
+ }
234
+
235
+ export { type ExperimentalStreams as E, type PersistenceMode as P, type ResolvedServerOptions as R, type ServerOptions as S, type Exports as a, ServerAlreadyRunningError as b, ServerState as c, type ScanOptions as d, type ServerDumpV1 as e, ServerStateAlreadyExistsError as f, type ServerStatusV1 as g, deleteServer as h, getServerStatus as i, isServerRunning as j, killServer as k };
package/dist/state.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var ve=Object.create;var O=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var De=Object.getPrototypeOf,xe=Object.prototype.hasOwnProperty;var Te=(t,e)=>{for(var r in e)O(t,r,{get:e[r],enumerable:!0})},z=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Se(e))!xe.call(t,a)&&a!==r&&O(t,a,{get:()=>e[a],enumerable:!(s=we(e,a))||s.enumerable});return t};var x=(t,e,r)=>(r=t!=null?ve(De(t)):{},z(e||!t||!t.__esModule?O(r,"default",{value:t,enumerable:!0}):r,t)),$e=t=>z(O({},"__esModule",{value:!0}),t);var Ue={};Te(Ue,{ServerAlreadyRunningError:()=>I,ServerState:()=>f,ServerStateAlreadyExistsError:()=>R,deleteServer:()=>Le,getServerStatus:()=>Y,isServerRunning:()=>be,killServer:()=>Pe});module.exports=$e(Ue);var me=require("fs/promises"),g=require("pathe"),S=require("proper-lockfile"),W=require("std-env"),i=require("valibot");var Z=require("fs"),p=require("fs/promises"),Q=require("util"),ee=require("zlib");var d=x(require("path"),1),L=x(require("os"),1),k=x(require("process"),1),m=L.default.homedir(),U=L.default.tmpdir(),{env:y}=k.default,Oe=t=>{let e=d.default.join(m,"Library");return{data:d.default.join(e,"Application Support",t),config:d.default.join(e,"Preferences",t),cache:d.default.join(e,"Caches",t),log:d.default.join(e,"Logs",t),temp:d.default.join(U,t)}},ke=t=>{let e=y.APPDATA||d.default.join(m,"AppData","Roaming"),r=y.LOCALAPPDATA||d.default.join(m,"AppData","Local");return{data:d.default.join(r,t,"Data"),config:d.default.join(e,t,"Config"),cache:d.default.join(r,t,"Cache"),log:d.default.join(r,t,"Log"),temp:d.default.join(U,t)}},_e=t=>{let e=d.default.basename(m);return{data:d.default.join(y.XDG_DATA_HOME||d.default.join(m,".local","share"),t),config:d.default.join(y.XDG_CONFIG_HOME||d.default.join(m,".config"),t),cache:d.default.join(y.XDG_CACHE_HOME||d.default.join(m,".cache"),t),log:d.default.join(y.XDG_STATE_HOME||d.default.join(m,".local","state"),t),temp:d.default.join(U,e,t)}};function B(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),k.default.platform==="darwin"?Oe(t):k.default.platform==="win32"?ke(t):_e(t)}var te=x(require("zeptomatch"),1),Ee=B("prisma-dev"),Fe=(0,Q.promisify)(ee.unzip);function v(t){return`${Ee.data}/${t}`}function re(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function se(t){try{return await(0,p.readFile)(t,{encoding:"utf-8"})}catch(e){if(re(e))return null;throw e}}async function oe(t){await(0,p.mkdir)(t,{recursive:!0})}async function ae(t,e){try{return(await(0,p.readdir)(t,{withFileTypes:!0})).reduce((s,a)=>(a.isDirectory()&&!a.name.startsWith(".")&&(!e||(0,te.default)(e,a.name))&&s.push(a.name),s),[])}catch(r){if(re(r))return[];throw r}}async function ie(t){await(0,p.rm)(t,{force:!0,recursive:!0})}var ne=require("timers/promises"),T=require("std-env");function C(t,e){if(t==null)return!1;try{return T.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}async function ue(t,e){if(!T.process.kill)return!1;try{T.process.kill(t,"SIGTERM")}catch(s){return e&&console.error(`Error killing process with PID ${t}:`,s),!1}let r=0;do{if(!C(t,e))return!0;await(0,ne.setTimeout)(100)}while(++r<50);try{return T.process.kill(t,"SIGKILL")}catch(s){return e&&console.error(`Error forcefully killing process with PID ${t}:`,s),!1}}var P=require("get-port-please"),A=require("remeda"),ce=51214,de=51213,le=51215,E=65535,w=0,b=-1/0;async function F(t){let{debug:e,name:r,requestedPorts:s,servers:a}=t,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n}=Re(r,a);e&&(console.debug(`ports used by other servers: ${Object.keys(o).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(n)}`));let u={databasePort:b,port:b,shadowDatabasePort:b},c=["port","databasePort","shadowDatabasePort"];for(let l of c){let h=await Me({debug:e,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s})??await Ae({debug:e,pickedPorts:u,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n});e&&console.debug(`Got port for "${l}": ${h}`),u[l]=h}return e&&console.debug(`Picked ports: ${JSON.stringify(u)}`),u}async function Me(t){let{debug:e,portKey:r,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o}=t,{[r]:n,...u}=o;if(pe(n))return await Ie({debug:e,otherRequestedPorts:u,portKey:r,portsUsedByOtherServers:s,requestedPort:n}),n;let c=a?.[r]??b;if(!pe(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=c in s;return l||Object.values(u).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,P.checkPort)(c)===!1?(e&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function Ae(t){let{debug:e,pickedPorts:r,portKey:s,portsUsedByOtherServers:a,portsUsedByThisServerLastTime:o}=t,n=Math.max(ce,de,le)+1,u=[...Object.values(r),...Object.keys(a).map(Number),...Object.values(o||{})],c=Math.min(Math.max(n,...u)+100,E),l=(0,A.difference)((0,A.range)(n,c),u),h={port:de,databasePort:ce,shadowDatabasePort:le}[s];try{return await(0,P.getPort)({port:h in a||Object.values(r).includes(h)||Object.values(o||{}).includes(h)?void 0:h,ports:l})}catch(D){if(D instanceof Error&&D.name==="GetPortError"&&c+1<=E)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${E}].`),await(0,P.getPort)({portRange:[c+1,E]});throw D}}function pe(t){return Number.isFinite(t)&&t>=0}function Re(t,e){let r={},s;for(let a of e){let{databasePort:o,port:n,shadowDatabasePort:u}=a;if(a.name===t){s={databasePort:o,port:n,shadowDatabasePort:u};continue}r[o]=!0,r[n]=!0,r[u]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:s}}async function Ie(t){let{debug:e,otherRequestedPorts:r,portKey:s,portsUsedByOtherServers:a,requestedPort:o}=t;if(o!==w){if(o in a)throw e&&console.error(`Port ${o} was requested for "${s}", but is already used by another server.`),new q(o);if(Object.values(r).includes(o))throw e&&console.error(`Port ${o} was requested for "${s}", but also for another key.`),new V(o);if((0,P.isUnsafePort)(o))throw e&&console.error(`Port ${o} was requested for "${s}", but is unsafe.`),new M(o);if(await(0,P.checkPort)(o)===!1)throw e&&console.error(`Port ${o} was requested for "${s}", but is not available.`),new M(o)}}var M=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},V=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"},q=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"};var H=(0,i.pipe)((0,i.string)(),(0,i.url)()),he=(0,i.object)({connectionString:H,prismaORMConnectionString:(0,i.optional)(H),terminalCommand:(0,i.optional)((0,i.string)())}),fe=(0,i.object)({url:H}),K=(0,i.pipe)((0,i.number)(),(0,i.integer)(),(0,i.minValue)(1)),je=(0,i.object)({database:he,http:fe,ppg:fe,shadowDatabase:he}),Ne=(0,i.object)({databasePort:K,exports:(0,i.optional)(je),name:(0,i.pipe)((0,i.string)(),(0,i.minLength)(1)),pid:(0,i.optional)((0,i.pipe)((0,i.number)(),(0,i.integer)(),(0,i.minValue)(0))),port:K,shadowDatabasePort:K,version:(0,i.literal)("1")}),X=Symbol("initialize"),G="default",f=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??b,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??G,this.persistenceMode=e.persistenceMode,this.pid=e.pid??W.process.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??b,this._shadowDatabasePort=e.shadowDatabasePort??b}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new $(e):new J(e);return await r[X](),r}static async fromServerDump(e){let{debug:r,name:s=G}=e??{},a=v(s),o=$.getServerDumpPath(a),n=await se(o);if(n==null)return r&&console.debug(`[State] No server dump file found at: ${o}`),null;r&&(console.debug(`[State] server dump file found at "${o}":`),console.debug(n));let{issues:u,output:c,success:l}=(0,i.safeParse)((0,i.pipe)((0,i.string)(),(0,i.parseJson)(),Ne),n);if(!l)throw r&&console.debug(`[State] Invalid server dump file at "${o}":
2
- ${JSON.stringify(u,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new $({databasePort:c.databasePort,debug:r,dryRun:!1,name:s,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r,globs:s}=e??{},a=(0,g.join)(v(G),"..");r&&console.debug(`[State] scanning for server states in: ${a}`);let o=await ae(a,s);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(n=>Y(n,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,r){if(r<0||!Number.isInteger(r))throw new Error(`Invalid port number: ${r}`);let s=`_${e}`;if(this[s]!==w&&this[s]!==r)throw new Error(`\`${e}\` is already set to ${this[s]}, cannot change it to ${r}`);this[s]=r}},J=class extends f{constructor(e){super({...e,databasePort:e?.databasePort||w,persistenceMode:"stateless",port:e?.port||w,shadowDatabasePort:e?.shadowDatabasePort||w})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[X](){let e;try{e=await f.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 r=await F({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort}async close(){}async writeServerDump(){}},$=class t extends f{#t;#e;#s;#a;#i;#o;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#o=!1,this.#e=v(this.name),this.#t=(0,g.join)(this.#e,"db_dump.bak"),this.#s=(0,g.join)(this.#e,".lock"),this.#a=(0,g.join)(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#i=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,g.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#a}async[X](){await oe(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,S.lock)(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await f.scan({debug:this.debug,onlyMetadata:!0}),r=await F({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new I(this):e}}async close(){if(!this.#o)try{await(0,S.unlock)(this.#e,{lockfilePath:this.#s}),this.#o=!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:W.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,me.writeFile)(this.#i,`${JSON.stringify(this.#r,null,2)}
3
- `,{encoding:"utf-8"})}};async function Le(t,e){await Pe(t,e);let r=v(typeof t=="string"?t:t.name);await ie(r)}async function Y(t,e){let{debug:r,onlyMetadata:s}=e||{},a=typeof t=="string"?t:t.name,o=typeof t!="string"?t:void 0,n={databasePort:o?.databasePort??-1,exports:o?.exports,name:a,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let u=o||await f.fromServerDump({debug:r,name:a});if(!u)return r&&console.debug(`[State] no server state found for name: ${a}`),{...n,status:"no_such_server"};n.databasePort=u.databasePort,n.exports=u.exports,n.pid=u.pid,n.port=u.port,n.shadowDatabasePort=u.shadowDatabasePort;let{exports:c,pid:l}=u;if(s)return{...n,status:"unknown"};if(!C(l,r))return r&&console.debug(`[State] server state for "${a}" has no running process with PID: ${l}`),{...n,status:"not_running"};let h=v(a);try{if(!await(0,S.check)(h,{lockfilePath:(0,g.join)(h,".lock")}))return r&&console.debug(`[State] server state for "${a}" is not locked, indicating it is not running.`),{...n,status:"starting_up"}}catch(ye){r&&console.error(`[State] server state for "${a}" failed to check lock:`,ye)}if(!c)return{...n,status:"starting_up"};let{http:D}=c,{hc:ge}=await import("hono/client"),j=await ge(D.url).health.$get();if(!j.ok)return r&&console.debug(`[State] server state for "${a}" is not live: ${JSON.stringify(j)}`),{...n,status:"not_running"};let N=await j.json();return N.name!==t?(r&&console.debug(`[State] server state for "${a}" has mismatched health response: ${JSON.stringify(N)}`),{...n,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(N)}`),{...n,status:"running"})}catch(u){return r&&console.error(`[State] failed to get server status for "${a}":`,u),{...n,status:"error"}}}function be(t){let{status:e}=t;return e==="running"||e==="starting_up"}async function Pe(t,e){let{pid:r,...s}=typeof t=="string"?await Y(t,{debug:e}):t;if(!be(s))return!1;let a=await f.fromServerDump({debug:e,name:s.name});if(r==null){e&&console.debug(`[State] No PID found for server "${s.name}" to kill.`);try{await a?.close()}catch{}return!1}let o=await ue(r,e);try{await a?.close()}catch{}return o}var R=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},I=class extends R{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return f.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError,deleteServer,getServerStatus,isServerRunning,killServer});
1
+ "use strict";var xe=Object.create;var k=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Ee=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Oe=(t,e)=>{for(var r in e)k(t,r,{get:e[r],enumerable:!0})},re=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of _e(e))!$e.call(t,n)&&n!==r&&k(t,n,{get:()=>e[n],enumerable:!(o=Te(e,n))||o.enumerable});return t};var T=(t,e,r)=>(r=t!=null?xe(Ee(t)):{},re(e||!t||!t.__esModule?k(r,"default",{value:t,enumerable:!0}):r,t)),ke=t=>re(k({},"__esModule",{value:!0}),t);var Je={};Oe(Je,{ServerAlreadyRunningError:()=>L,ServerState:()=>f,ServerStateAlreadyExistsError:()=>j,deleteServer:()=>He,getServerStatus:()=>te,isServerRunning:()=>we,killServer:()=>Se});module.exports=ke(Je);var ve=require("fs/promises"),y=require("pathe"),x=require("proper-lockfile"),Q=require("std-env"),s=require("valibot");var se=require("fs"),m=require("fs/promises"),oe=require("util"),ae=require("zlib");var d=T(require("path"),1),B=T(require("os"),1),M=T(require("process"),1),b=B.default.homedir(),C=B.default.tmpdir(),{env:w}=M.default,Me=t=>{let e=d.default.join(b,"Library");return{data:d.default.join(e,"Application Support",t),config:d.default.join(e,"Preferences",t),cache:d.default.join(e,"Caches",t),log:d.default.join(e,"Logs",t),temp:d.default.join(C,t)}},Re=t=>{let e=w.APPDATA||d.default.join(b,"AppData","Roaming"),r=w.LOCALAPPDATA||d.default.join(b,"AppData","Local");return{data:d.default.join(r,t,"Data"),config:d.default.join(e,t,"Config"),cache:d.default.join(r,t,"Cache"),log:d.default.join(r,t,"Log"),temp:d.default.join(C,t)}},Ae=t=>{let e=d.default.basename(b);return{data:d.default.join(w.XDG_DATA_HOME||d.default.join(b,".local","share"),t),config:d.default.join(w.XDG_CONFIG_HOME||d.default.join(b,".config"),t),cache:d.default.join(w.XDG_CACHE_HOME||d.default.join(b,".cache"),t),log:d.default.join(w.XDG_STATE_HOME||d.default.join(b,".local","state"),t),temp:d.default.join(C,e,t)}};function V(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),M.default.platform==="darwin"?Me(t):M.default.platform==="win32"?Re(t):Ae(t)}var ne=T(require("zeptomatch"),1),q=V("prisma-dev"),Ze=(0,oe.promisify)(ae.unzip);function S(t){return`${q.data}/${t}`}function ie(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function ue(t){try{return await(0,m.readFile)(t,{encoding:"utf-8"})}catch(e){if(ie(e))return null;throw e}}async function ce(t){await(0,m.mkdir)(t,{recursive:!0})}async function de(t,e){try{return(await(0,m.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,ne.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(ie(r))return[];throw r}}async function F(t){await(0,m.rm)(t,{force:!0,recursive:!0})}var le=require("timers/promises"),E=require("std-env");function G(t,e){if(t==null)return!1;try{return E.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}async function pe(t,e){if(!E.process.kill)return!1;try{E.process.kill(t,"SIGTERM")}catch(o){return e&&console.error(`Error killing process with PID ${t}:`,o),!1}let r=0;do{if(!G(t,e))return!0;await(0,le.setTimeout)(100)}while(++r<50);try{return E.process.kill(t,"SIGKILL")}catch(o){return e&&console.error(`Error forcefully killing process with PID ${t}:`,o),!1}}var g=require("get-port-please"),I=require("remeda"),me=51214,he=51213,fe=51215,Pe=51216,R=65535,D=0,p=-1/0;async function W(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:a,portsUsedByThisServerLastTime:i}=Le(r,n);e&&(console.debug(`ports used by other servers: ${Object.keys(a).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(i)}`));let u={databasePort:p,port:p,shadowDatabasePort:p,streamsPort:p},c=["port","databasePort","shadowDatabasePort","streamsPort"];for(let l of c){let h=await Ie({debug:e,portKey:l,portsUsedByOtherServers:a,portsUsedByThisServerLastTime:i,requestedPorts:o})??await je({debug:e,pickedPorts:u,portKey:l,portsUsedByOtherServers:a,portsUsedByThisServerLastTime:i});e&&console.debug(`Got port for "${l}": ${h}`),u[l]=h}return e&&console.debug(`Picked ports: ${JSON.stringify(u)}`),u}async function Ie(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:a}=t,{[r]:i,...u}=a;if(K(i))return await Be({debug:e,otherRequestedPorts:u,portKey:r,portsUsedByOtherServers:o,requestedPort:i}),i;let c=n?.[r]??p;if(!K(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=c in o;return l||Object.values(u).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,g.checkPort)(c)===!1?(e&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function je(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:a}=t,i=Math.max(me,he,fe,Pe)+1,u=Object.values(r).filter(P=>P!==void 0),c=a?Ue(a):[],l=[...u,...Object.keys(n).map(Number),...c],h=Math.min(Math.max(i,...l)+100,R),N=(0,I.difference)((0,I.range)(i,h),l),v={port:he,databasePort:me,shadowDatabasePort:fe,streamsPort:Pe}[o];try{return await(0,g.getPort)({port:v in n||u.includes(v)||c.includes(v)?void 0:v,ports:N})}catch(P){if(P instanceof Error&&P.name==="GetPortError"&&h+1<=R)return e&&console.debug(`Expanding port lookup to range [${h+1}, ${R}].`),await(0,g.getPort)({portRange:[h+1,R]});throw P}}function K(t){return Number.isFinite(t)&&t>=0}function Le(t,e){let r={},o;for(let n of e){let{databasePort:a,port:i,shadowDatabasePort:u}=n,c=Ne(n);if(n.name===t){o={databasePort:a,port:i,shadowDatabasePort:u,streamsPort:c};continue}r[a]=!0,r[i]=!0,r[u]=!0,K(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:o}}function Ne(t){let e=t.experimental?.streams?.serverUrl;if(!e)return p;try{let r=Number(new URL(e).port);return Number.isInteger(r)&&r>0?r:p}catch{return p}}function Ue(t){return[t.port,t.databasePort,t.shadowDatabasePort,t.streamsPort]}async function Be(t){let{debug:e,otherRequestedPorts:r,portKey:o,portsUsedByOtherServers:n,requestedPort:a}=t;if(a!==D){if(a in n)throw e&&console.error(`Port ${a} was requested for "${o}", but is already used by another server.`),new J(a);if(Object.values(r).includes(a))throw e&&console.error(`Port ${a} was requested for "${o}", but also for another key.`),new H(a);if((0,g.isUnsafePort)(a))throw e&&console.error(`Port ${a} was requested for "${o}", but is unsafe.`),new A(a);if(await(0,g.checkPort)(a)===!1)throw e&&console.error(`Port ${a} was requested for "${o}", but is not available.`),new A(a)}}var A=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},H=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"},J=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"};var X=require("pathe");function Ce(){return(0,X.join)(q.data,"durable-streams")}function be(t){return(0,X.join)(Ce(),t)}var O=(0,s.pipe)((0,s.string)(),(0,s.url)()),ge=(0,s.object)({connectionString:O,prismaORMConnectionString:(0,s.optional)(O),terminalCommand:(0,s.optional)((0,s.string)())}),ye=(0,s.object)({url:O}),Ve=(0,s.object)({serverUrl:O,sqlitePath:(0,s.pipe)((0,s.string)(),(0,s.minLength)(1)),streamName:(0,s.pipe)((0,s.string)(),(0,s.minLength)(1)),url:O}),qe=(0,s.object)({streams:(0,s.optional)(Ve)}),Y=(0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(1)),Fe=(0,s.object)({database:ge,http:ye,ppg:ye,shadowDatabase:ge}),Ge=(0,s.object)({databasePort:Y,experimental:(0,s.optional)(qe),exports:(0,s.optional)(Fe),name:(0,s.pipe)((0,s.string)(),(0,s.minLength)(1)),pid:(0,s.optional)((0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(0))),port:Y,shadowDatabasePort:Y,version:(0,s.literal)("1")}),ee=Symbol("initialize"),z="default",Ke=new Set(["durable-streams"]),f=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(e){this._databasePort=e.databasePort??p,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??z,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Q.process.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??p,this._shadowDatabasePort=e.shadowDatabasePort??p,this._streamsPort=p}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new $(e):new Z(e);return await r[ee](),r}static async fromServerDump(e){let{debug:r,name:o=z}=e??{},n=S(o),a=$.getServerDumpPath(n),i=await ue(a);if(i==null)return r&&console.debug(`[State] No server dump file found at: ${a}`),null;r&&(console.debug(`[State] server dump file found at "${a}":`),console.debug(i));let{issues:u,output:c,success:l}=(0,s.safeParse)((0,s.pipe)((0,s.string)(),(0,s.parseJson)(),Ge),i);if(!l)throw r&&console.debug(`[State] Invalid server dump file at "${a}":
2
+ ${JSON.stringify(u,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new $({databasePort:c.databasePort,debug:r,dryRun:!1,name:o,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r,globs:o}=e??{},n=(0,y.join)(S(z),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let a=(await de(n,o)).filter(i=>!Ke.has(i));return r&&console.debug(`[State] found server names: ${JSON.stringify(a)}`),await Promise.all(a.map(i=>te(i,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}get streamsPort(){return this._streamsPort}set shadowDatabasePort(e){this.#t("shadowDatabasePort",e)}#t(e,r){if(r<0||!Number.isInteger(r))throw new Error(`Invalid port number: ${r}`);let o=`_${e}`;if(this[o]!==D&&this[o]!==r)throw new Error(`\`${e}\` is already set to ${this[o]}, cannot change it to ${r}`);this[o]=r}},Z=class extends f{constructor(e){super({...e,databasePort:e?.databasePort||D,persistenceMode:"stateless",port:e?.port||D,shadowDatabasePort:e?.shadowDatabasePort||D})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[ee](){let e;try{e=await f.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let r=await W({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort}async close(){}async writeServerDump(){}},$=class t extends f{#t;#e;#s;#a;#n;#o;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#o=!1,this.#e=S(this.name),this.#t=(0,y.join)(this.#e,"db_dump.bak"),this.#s=(0,y.join)(this.#e,".lock"),this.#a=(0,y.join)(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#n=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,y.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get experimental(){return this.#r?.experimental}get pgliteDataDirPath(){return this.#a}async[ee](){await ce(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,x.lock)(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await f.scan({debug:this.debug,onlyMetadata:!0}),r=await W({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new L(this):e}}async close(){if(!this.#o)try{await(0,x.unlock)(this.#e,{lockfilePath:this.#s}),this.#o=!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,r){this.#r={name:this.name,version:"1",pid:Q.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,ve.writeFile)(this.#n,`${JSON.stringify(this.#r,null,2)}
3
+ `,{encoding:"utf-8"})}};async function He(t,e){await Se(t,e);let r=typeof t=="string"?t:t.name,o=S(r);await F(o),await F(be(r))}async function te(t,e){let{debug:r,onlyMetadata:o}=e||{},n=typeof t=="string"?t:t.name,a=typeof t!="string"?t:void 0,i={databasePort:a?.databasePort??-1,experimental:a?.experimental,exports:a?.exports,name:n,pid:a?.pid,port:a?.port??-1,shadowDatabasePort:a?.shadowDatabasePort??-1,version:"1"};try{let u=a||await f.fromServerDump({debug:r,name:n});if(!u)return r&&console.debug(`[State] no server state found for name: ${n}`),{...i,status:"no_such_server"};i.databasePort=u.databasePort,i.experimental=u.experimental,i.exports=u.exports,i.pid=u.pid,i.port=u.port,i.shadowDatabasePort=u.shadowDatabasePort;let{exports:c,pid:l}=u;if(o)return{...i,status:"unknown"};if(!G(l,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${l}`),{...i,status:"not_running"};let h=S(n);try{if(!await(0,x.check)(h,{lockfilePath:(0,y.join)(h,".lock")}))return r&&console.debug(`[State] server state for "${n}" is not locked, indicating it is not running.`),{...i,status:"not_running"}}catch(De){r&&console.error(`[State] server state for "${n}" failed to check lock:`,De)}if(!c)return{...i,status:"starting_up"};let{http:N}=c,{hc:v}=await import("hono/client"),P=await v(N.url).health.$get();if(!P.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(P)}`),{...i,status:"not_running"};let U=await P.json();return U.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(U)}`),{...i,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(U)}`),{...i,status:"running"})}catch(u){return r&&console.error(`[State] failed to get server status for "${n}":`,u),{...i,status:"error"}}}function we(t){let{status:e}=t;return e==="running"||e==="starting_up"}async function Se(t,e){let{pid:r,...o}=typeof t=="string"?await te(t,{debug:e}):t;if(!we(o))return!1;let n=await f.fromServerDump({debug:e,name:o.name});if(r==null){e&&console.debug(`[State] No PID found for server "${o.name}" to kill.`);try{await n?.close()}catch{}return!1}let a=await pe(r,e);try{await n?.close()}catch{}return a}var j=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},L=class extends j{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return f.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError,deleteServer,getServerStatus,isServerRunning,killServer});