@prisma/dev 0.0.0-dev.202506060935 → 0.0.0-dev.202506061849

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.
@@ -1,3 +1,3 @@
1
- import{b as c,f as w,g as x,h as O,i as $,j as E,k as _}from"./chunk-YMJGNP57.js";import{writeFile as J}from"fs/promises";import{hc as U}from"hono/client";import{join as u}from"pathe";import{check as j,lock as B}from"proper-lockfile";import{process as m}from"std-env";import{integer as I,literal as H,minLength as C,minValue as T,number as V,object as f,optional as R,parseJson as Y,pipe as l,safeParse as Z,string as D,url as q}from"valibot";import{process as F}from"std-env";function k(r,e){if(r==null)return!1;try{return F.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}var N=l(D(),q()),A=f({connectionString:N}),M=f({url:N}),g=l(V(),I(),T(1)),z=f({database:A,http:M,ppg:M,shadowDatabase:A}),K=f({databasePort:g,exports:R(z),name:l(D(),C(1)),pid:R(l(V(),I(),T(0))),port:g,shadowDatabasePort:g,version:H("1")}),y=Symbol("initialize"),v="default",h=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??v,this.persistenceMode=e.persistenceMode,this.pid=e.pid??m.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new p({...e,pid:m.pid}):new P(e);return await t[y](),t}static async fromServerDump(e){let{debug:t,name:s=v}=e??{},n=c(s),a=p.getServerDumpPath(n),i=await w(a);if(i==null)return t&&console.debug(`[State] No server dump file found at: ${a}`),null;t&&(console.debug(`[State] server dump file found at "${a}":`),console.debug(i));let{issues:b,output:o,success:d}=Z(l(D(),Y(),K),i);if(!d)throw t&&console.debug(`[State] Invalid server dump file at "${a}":
2
- ${JSON.stringify(b,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new p({databasePort:o.databasePort,debug:t,dryRun:!1,name:s,pid:o.pid,port:o.port,serverDump:o,shadowDatabasePort:o.shadowDatabasePort})}static async scan(e){let{debug:t}=e??{},s=u(c(v),"..");t&&console.debug(`[State] scanning for server states in: ${s}`);let n=await O(s);return t&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(a=>W(a,t)))}},P=class extends h{constructor(e){super({...e,persistenceMode:"stateless",pid:m.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[y](){}async close(){}async writeServerDump(){}},p=class r extends h{#s;#e;#a;#o;#t;#r=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=c(this.name),this.#s=u(this.#e,"db_dump.bak"),this.#a=u(this.#e,".pglite"),this.#t=e.serverDump??null,this.#o=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return u(e,"server.json")}get databaseDumpPath(){return this.#s}get exports(){return this.#t?.exports}get pgliteDataDirPath(){return this.#a}async[y](){await x(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await B(this.#e,{lockfilePath:u(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new S(this.name):e}}async close(){if(this.#r!=null)try{await this.#r(),this.#r=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#t={name:this.name,version:"1",pid:m.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await J(this.#o,`${JSON.stringify(this.#t,null,2)}
3
- `,{encoding:"utf-8"})}};async function W(r,e){let t={databasePort:-1,exports:void 0,name:r,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await h.fromServerDump({debug:e,name:r});if(!s)return e&&console.debug(`[State] no server state found for name: ${r}`),{...t,status:"no_such_server"};t.databasePort=s.databasePort,t.exports=s.exports,t.pid=s.pid,t.port=s.port,t.shadowDatabasePort=s.shadowDatabasePort;let{exports:n,pid:a}=s;if(!k(a,e))return e&&console.debug(`[State] server state for "${r}" has no running process with PID: ${a}`),{...t,status:"not_running"};let i=c(r);try{if(!await j(i,{lockfilePath:u(i,".lock")}))return e&&console.debug(`[State] server state for "${r}" is not locked, indicating it is not running.`),{...t,status:"starting_up"}}catch(L){e&&console.error(`[State] server state for "${r}" failed to check lock:`,L)}if(!n)return{...t,status:"starting_up"};let{http:b}=n,o=await U(b.url).health.$get();if(!o.ok)return e&&console.debug(`[State] server state for "${r}" is not live: ${JSON.stringify(o)}`),{...t,status:"not_running"};let d=await o.json();return d.name!==r?(e&&console.debug(`[State] server state for "${r}" has mismatched health response: ${JSON.stringify(d)}`),{...t,status:"unknown"}):(e&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(d)}`),{...t,status:"running"})}catch(s){return e&&console.error(`[State] failed to get server status for "${r}":`,s),{...t,status:"error"}}}var S=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};export{h as a,S as b};
1
+ import{b as c,f as O,g as $,h as E,i as R,j as _,k}from"./chunk-YMJGNP57.js";import{writeFile as J}from"fs/promises";import{hc as U}from"hono/client";import{join as u}from"pathe";import{check as j,lock as B}from"proper-lockfile";import{process as m}from"std-env";import{integer as T,literal as C,minLength as H,minValue as V,number as N,object as g,optional as f,parseJson as Y,pipe as l,safeParse as Z,string as b,url as q}from"valibot";import{process as F}from"std-env";function A(r,e){if(r==null)return!1;try{return F.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}var D=l(b(),q()),M=g({connectionString:D,prismaORMConnectionString:f(D),terminalCommand:f(b())}),I=g({url:D}),P=l(N(),T(),V(1)),z=g({database:M,http:I,ppg:I,shadowDatabase:M}),K=g({databasePort:P,exports:f(z),name:l(b(),H(1)),pid:f(l(N(),T(),V(0))),port:P,shadowDatabasePort:P,version:C("1")}),x=Symbol("initialize"),S="default",h=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??S,this.persistenceMode=e.persistenceMode,this.pid=e.pid??m.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new p({...e,pid:m.pid}):new y(e);return await t[x](),t}static async fromServerDump(e){let{debug:t,name:s=S}=e??{},n=c(s),a=p.getServerDumpPath(n),i=await O(a);if(i==null)return t&&console.debug(`[State] No server dump file found at: ${a}`),null;t&&(console.debug(`[State] server dump file found at "${a}":`),console.debug(i));let{issues:v,output:o,success:d}=Z(l(b(),Y(),K),i);if(!d)throw t&&console.debug(`[State] Invalid server dump file at "${a}":
2
+ ${JSON.stringify(v,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new p({databasePort:o.databasePort,debug:t,dryRun:!1,name:s,pid:o.pid,port:o.port,serverDump:o,shadowDatabasePort:o.shadowDatabasePort})}static async scan(e){let{debug:t}=e??{},s=u(c(S),"..");t&&console.debug(`[State] scanning for server states in: ${s}`);let n=await E(s);return t&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(a=>W(a,t)))}},y=class extends h{constructor(e){super({...e,persistenceMode:"stateless",pid:m.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[x](){}async close(){}async writeServerDump(){}},p=class r extends h{#s;#e;#a;#o;#t;#r=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=c(this.name),this.#s=u(this.#e,"db_dump.bak"),this.#a=u(this.#e,".pglite"),this.#t=e.serverDump??null,this.#o=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return u(e,"server.json")}get databaseDumpPath(){return this.#s}get exports(){return this.#t?.exports}get pgliteDataDirPath(){return this.#a}async[x](){await $(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await B(this.#e,{lockfilePath:u(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new w(this.name):e}}async close(){if(this.#r!=null)try{await this.#r(),this.#r=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#t={name:this.name,version:"1",pid:m.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await J(this.#o,`${JSON.stringify(this.#t,null,2)}
3
+ `,{encoding:"utf-8"})}};async function W(r,e){let t={databasePort:-1,exports:void 0,name:r,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await h.fromServerDump({debug:e,name:r});if(!s)return e&&console.debug(`[State] no server state found for name: ${r}`),{...t,status:"no_such_server"};t.databasePort=s.databasePort,t.exports=s.exports,t.pid=s.pid,t.port=s.port,t.shadowDatabasePort=s.shadowDatabasePort;let{exports:n,pid:a}=s;if(!A(a,e))return e&&console.debug(`[State] server state for "${r}" has no running process with PID: ${a}`),{...t,status:"not_running"};let i=c(r);try{if(!await j(i,{lockfilePath:u(i,".lock")}))return e&&console.debug(`[State] server state for "${r}" is not locked, indicating it is not running.`),{...t,status:"starting_up"}}catch(L){e&&console.error(`[State] server state for "${r}" failed to check lock:`,L)}if(!n)return{...t,status:"starting_up"};let{http:v}=n,o=await U(v.url).health.$get();if(!o.ok)return e&&console.debug(`[State] server state for "${r}" is not live: ${JSON.stringify(o)}`),{...t,status:"not_running"};let d=await o.json();return d.name!==r?(e&&console.debug(`[State] server state for "${r}" has mismatched health response: ${JSON.stringify(d)}`),{...t,status:"unknown"}):(e&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(d)}`),{...t,status:"running"})}catch(s){return e&&console.error(`[State] failed to get server status for "${r}":`,s),{...t,status:"error"}}}var w=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};export{h as a,w as b};
@@ -0,0 +1 @@
1
+ import{e as l,l as m}from"./chunk-YMJGNP57.js";import{PGlite as b}from"@electric-sql/pglite";import{PGLiteSocketServer as P}from"@electric-sql/pglite-socket";import{filename as y}from"pathe/utils";var n={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},p=`postgres://${n.username}:${n.password}@localhost`,f=new URLSearchParams({sslmode:n.sslMode}),w=new URLSearchParams({...Object.fromEntries(f.entries()),connection_limit:String(n.connectionLimit),connect_timeout:String(n.connectTimeout),max_idle_connection_lifetime:String(n.maxIdleConnectionLifetime),pool_timeout:String(n.poolTimeout),single_use_connections:"true",socket_timeout:String(n.socketTimeout)});async function x(e,r){let c=e==="database"?r.databasePort:r.shadowDatabasePort;if(r.dryRun)return u(e,r,{db:null,port:c,server:null});let{debug:a}=r,i=await(e==="shadow_database"?v:D)(r.pgliteDataDirPath,a);a&&i.onNotification((t,o)=>{console.debug(`[${e}][${t}] ${o}`)});let d=new P({db:i,debug:a,inspect:a,port:c});a&&(d.addEventListener("listening",t=>{let{detail:o}=t;console.debug(`[${e}] server listening on ${JSON.stringify(o)}`)}),d.addEventListener("connection",t=>{let{clientAddress:o,clientPort:S}=t.detail;console.debug(`[${e}] client connected from ${o}:${S}`)}),d.addEventListener("error",t=>{let{detail:o}=t;console.error(`[${e}] server error:`,o)}));try{await d.start()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="EADDRINUSE"?new m(c,e):t}return u(e,r,{db:i,port:c,server:d})}function u(e,r,c){let{debug:a}=r,{db:s,port:i,server:d}=c||{};return a&&console.debug(`[${e}] server started on port ${i}`),{...n,close:async()=>{let t=[];try{await d?.stop(),a&&console.debug(`[${e}] server stopped on port ${i}`)}catch(o){console.error(`[${e}] server stop error`,o),t.push(o)}if(e==="database")try{await s?.syncToFs(),a&&console.debug(`[${e}] synced to filesystem`)}catch(o){console.error(`[${e}] sync error`,o),t.push(o)}try{await s?.close(),a&&console.debug(`[${e}] closed`)}catch(o){console.error(`[${e}] close error`,o),t.push(o)}if(t.length>0)throw new AggregateError(t,`Failed to close ${e} properly`)},connectionString:g(i,f),dump:async t=>{e==="shadow_database"||!s||await $({db:s,debug:a,destinationPath:t})},port:i,prismaORMConnectionString:g(i,w),terminalCommand:`PGPASSWORD=${n.password} PGSSLMODE=${n.sslMode} psql -h localhost -p ${i} -U ${n.username} -d ${n.database}`}}function g(e,r){return`${p}:${e}/${n.database}?${r.toString()}`}async function D(e,r){return await b.create({database:n.database,dataDir:e,debug:r?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:n.username})}async function v(e,r){return await b.create({database:n.database,dataDir:"memory://",debug:r?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:n.username})}async function $(e){let{dataDir:r,db:c,debug:a,destinationPath:s}=e,i=c||await D(r,a),{pgDump:d}=await import("@electric-sql/pglite-tools/pg_dump"),t=await d({args:["--quote-all-identifiers","--schema-only"],fileName:s?y(s):void 0,pg:i});return s?(a&&console.debug(`[DB] Dumping database to ${s}`),await l(t,s)):(a&&console.debug("[DB] Dumping database to memory"),await t.text())}export{x as a,$ as b};
@@ -1,6 +1,6 @@
1
1
  import * as url from 'url';
2
2
  import { SockDaemonClient } from 'sock-daemon/client';
3
- import { S as ServerOptions, a as Server } from '../db-9fHowc0q.cjs';
3
+ import { S as ServerOptions, a as Server } from '../db-B1_DGnTu.cjs';
4
4
  import { MessageBase } from 'sock-daemon/server';
5
5
  import '@electric-sql/pglite';
6
6
  import 'valibot';
@@ -1,6 +1,6 @@
1
1
  import * as url from 'url';
2
2
  import { SockDaemonClient } from 'sock-daemon/client';
3
- import { S as ServerOptions, a as Server } from '../db-9fHowc0q.js';
3
+ import { S as ServerOptions, a as Server } from '../db-B1_DGnTu.js';
4
4
  import { MessageBase } from 'sock-daemon/server';
5
5
  import '@electric-sql/pglite';
6
6
  import 'valibot';
@@ -21,6 +21,8 @@ declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
21
21
  declare const exportsSchema: valibot.ObjectSchema<{
22
22
  readonly database: valibot.ObjectSchema<{
23
23
  readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
24
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
25
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
24
26
  }, undefined>;
25
27
  readonly http: valibot.ObjectSchema<{
26
28
  readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
@@ -30,6 +32,8 @@ declare const exportsSchema: valibot.ObjectSchema<{
30
32
  }, undefined>;
31
33
  readonly shadowDatabase: valibot.ObjectSchema<{
32
34
  readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
35
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
36
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
33
37
  }, undefined>;
34
38
  }, undefined>;
35
39
  type Exports = InferOutput<typeof exportsSchema>;
@@ -38,6 +42,8 @@ declare const serverDumpV1Schema: valibot.ObjectSchema<{
38
42
  readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
39
43
  readonly database: valibot.ObjectSchema<{
40
44
  readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
45
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
46
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
41
47
  }, undefined>;
42
48
  readonly http: valibot.ObjectSchema<{
43
49
  readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
@@ -47,6 +53,8 @@ declare const serverDumpV1Schema: valibot.ObjectSchema<{
47
53
  }, undefined>;
48
54
  readonly shadowDatabase: valibot.ObjectSchema<{
49
55
  readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
56
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
57
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
50
58
  }, undefined>;
51
59
  }, undefined>, undefined>;
52
60
  readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
@@ -167,8 +175,10 @@ interface DBServer {
167
175
  readonly password: string;
168
176
  readonly poolTimeout: number;
169
177
  readonly port: number;
178
+ readonly prismaORMConnectionString: string;
170
179
  readonly socketTimeout: number;
171
180
  readonly sslMode: string;
181
+ readonly terminalCommand: string;
172
182
  readonly username: string;
173
183
  }
174
184
  interface DBDump {
@@ -21,6 +21,8 @@ declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
21
21
  declare const exportsSchema: valibot.ObjectSchema<{
22
22
  readonly database: valibot.ObjectSchema<{
23
23
  readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
24
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
25
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
24
26
  }, undefined>;
25
27
  readonly http: valibot.ObjectSchema<{
26
28
  readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
@@ -30,6 +32,8 @@ declare const exportsSchema: valibot.ObjectSchema<{
30
32
  }, undefined>;
31
33
  readonly shadowDatabase: valibot.ObjectSchema<{
32
34
  readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
35
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
36
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
33
37
  }, undefined>;
34
38
  }, undefined>;
35
39
  type Exports = InferOutput<typeof exportsSchema>;
@@ -38,6 +42,8 @@ declare const serverDumpV1Schema: valibot.ObjectSchema<{
38
42
  readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
39
43
  readonly database: valibot.ObjectSchema<{
40
44
  readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
45
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
46
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
41
47
  }, undefined>;
42
48
  readonly http: valibot.ObjectSchema<{
43
49
  readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
@@ -47,6 +53,8 @@ declare const serverDumpV1Schema: valibot.ObjectSchema<{
47
53
  }, undefined>;
48
54
  readonly shadowDatabase: valibot.ObjectSchema<{
49
55
  readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
56
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
57
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
50
58
  }, undefined>;
51
59
  }, undefined>, undefined>;
52
60
  readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
@@ -167,8 +175,10 @@ interface DBServer {
167
175
  readonly password: string;
168
176
  readonly poolTimeout: number;
169
177
  readonly port: number;
178
+ readonly prismaORMConnectionString: string;
170
179
  readonly socketTimeout: number;
171
180
  readonly sslMode: string;
181
+ readonly terminalCommand: string;
172
182
  readonly username: string;
173
183
  }
174
184
  interface DBDump {
package/dist/db.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var j=Object.create;var f=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,R=Object.prototype.hasOwnProperty;var C=(e,t)=>{for(var o in t)f(e,o,{get:t[o],enumerable:!0})},S=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of F(t))!R.call(e,a)&&a!==o&&f(e,a,{get:()=>t[a],enumerable:!(n=O(t,a))||n.enumerable});return e};var y=(e,t,o)=>(o=e!=null?j(k(e)):{},S(t||!e||!e.__esModule?f(o,"default",{value:e,enumerable:!0}):o,e)),G=e=>S(f({},"__esModule",{value:!0}),e);var K={};C(K,{dumpDB:()=>B,startDBServer:()=>X});module.exports=G(K);var v=require("@electric-sql/pglite"),T=require("@electric-sql/pglite-socket"),_=require("@electric-sql/pglite-tools/pg_dump"),E=require("pathe/utils");var D=require("fs"),m=require("fs/promises");var r=y(require("path"),1),P=y(require("os"),1),p=y(require("process"),1),u=P.default.homedir(),w=P.default.tmpdir(),{env:g}=p.default,N=e=>{let t=r.default.join(u,"Library");return{data:r.default.join(t,"Application Support",e),config:r.default.join(t,"Preferences",e),cache:r.default.join(t,"Caches",e),log:r.default.join(t,"Logs",e),temp:r.default.join(w,e)}},I=e=>{let t=g.APPDATA||r.default.join(u,"AppData","Roaming"),o=g.LOCALAPPDATA||r.default.join(u,"AppData","Local");return{data:r.default.join(o,e,"Data"),config:r.default.join(t,e,"Config"),cache:r.default.join(o,e,"Cache"),log:r.default.join(o,e,"Log"),temp:r.default.join(w,e)}},M=e=>{let t=r.default.basename(u);return{data:r.default.join(g.XDG_DATA_HOME||r.default.join(u,".local","share"),e),config:r.default.join(g.XDG_CONFIG_HOME||r.default.join(u,".config"),e),cache:r.default.join(g.XDG_CACHE_HOME||r.default.join(u,".cache"),e),log:r.default.join(g.XDG_STATE_HOME||r.default.join(u,".local","state"),e),temp:r.default.join(w,t,e)}};function h(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),p.default.platform==="darwin"?N(e):p.default.platform==="win32"?I(e):M(e)}var U=require("pako"),z=h("prisma-dev");async function A(e,t){await e.stream().pipeTo(D.WriteStream.toWeb((0,D.createWriteStream)(t,{encoding:"utf-8"})))}var b=class extends Error{constructor(o,n){super(`Port number \`${o}\` is not available for service ${n}.`);this.port=o;this.service=n}name="PortNotAvailableError"};var c={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},H=`postgres://${c.username}:${c.password}@localhost`,W=new URLSearchParams({connection_limit:String(c.connectionLimit),connect_timeout:String(c.connectTimeout),max_idle_connection_lifetime:String(c.maxIdleConnectionLifetime),pool_timeout:String(c.poolTimeout),socket_timeout:String(c.socketTimeout),sslmode:c.sslMode});async function X(e,t){let o=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return x(e,t,{db:null,port:o,server:null});let{debug:n}=t,d=await(e==="shadow_database"?q:$)(t.pgliteDataDirPath,n);n&&d.onNotification((i,s)=>{console.debug(`[${e}][${i}] ${s}`)});let l=new T.PGLiteSocketServer({db:d,debug:n,inspect:n,port:o});n&&(l.addEventListener("listening",i=>{let{detail:s}=i;console.debug(`[${e}] server listening on ${JSON.stringify(s)}`)}),l.addEventListener("connection",i=>{let{clientAddress:s,clientPort:L}=i.detail;console.debug(`[${e}] client connected from ${s}:${L}`)}),l.addEventListener("error",i=>{let{detail:s}=i;console.error(`[${e}] server error:`,s)}));try{await l.start()}catch(i){throw i instanceof Error&&"code"in i&&i.code==="EADDRINUSE"?new b(o,e):i}return x(e,t,{db:d,port:o,server:l})}function x(e,t,o){let{debug:n}=t,{db:a,port:d,server:l}=o||{};return n&&console.debug(`[${e}] server started on port ${d}`),{...c,close:async()=>{let i=[];try{await l?.stop(),n&&console.debug(`[${e}] server stopped on port ${d}`)}catch(s){console.error(`[${e}] server stop error`,s),i.push(s)}if(e==="database")try{await a?.syncToFs(),n&&console.debug(`[${e}] synced to filesystem`)}catch(s){console.error(`[${e}] sync error`,s),i.push(s)}try{await a?.close(),n&&console.debug(`[${e}] closed`)}catch(s){console.error(`[${e}] close error`,s),i.push(s)}if(i.length>0)throw new AggregateError(i,`Failed to close ${e} properly`)},connectionString:J(d),dump:async i=>{e==="shadow_database"||!a||await B({db:a,debug:n,destinationPath:i})},port:d}}function J(e){return`${H}:${e}/${c.database}?${W.toString()}`}async function $(e,t){return await v.PGlite.create({database:c.database,dataDir:e,debug:t?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:c.username})}async function q(e,t){return await v.PGlite.create({database:c.database,dataDir:"memory://",debug:t?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:c.username})}async function B(e){let{dataDir:t,db:o,debug:n,destinationPath:a}=e,d=o||await $(t,n),l=await(0,_.pgDump)({args:["--quote-all-identifiers","--schema-only"],fileName:a?(0,E.filename)(a):void 0,pg:d});return a?(n&&console.debug(`[DB] Dumping database to ${a}`),await A(l,a)):(n&&console.debug("[DB] Dumping database to memory"),await l.text())}0&&(module.exports={dumpDB,startDBServer});
1
+ "use strict";var R=Object.create;var p=Object.defineProperty;var j=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var N=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var G=(e,t)=>{for(var n in t)p(e,n,{get:t[n],enumerable:!0})},v=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of C(t))!F.call(e,s)&&s!==n&&p(e,s,{get:()=>t[s],enumerable:!(i=j(t,s))||i.enumerable});return e};var f=(e,t,n)=>(n=e!=null?R(N(e)):{},v(t||!e||!e.__esModule?p(n,"default",{value:e,enumerable:!0}):n,e)),k=e=>v(p({},"__esModule",{value:!0}),e);var Q={};G(Q,{dumpDB:()=>B,startDBServer:()=>q});module.exports=k(Q);var w=require("@electric-sql/pglite"),E=require("@electric-sql/pglite-socket"),$=require("pathe/utils");var b=require("fs"),m=require("fs/promises");var r=f(require("path"),1),y=f(require("os"),1),D=f(require("process"),1),u=y.default.homedir(),S=y.default.tmpdir(),{env:g}=D.default,M=e=>{let t=r.default.join(u,"Library");return{data:r.default.join(t,"Application Support",e),config:r.default.join(t,"Preferences",e),cache:r.default.join(t,"Caches",e),log:r.default.join(t,"Logs",e),temp:r.default.join(S,e)}},I=e=>{let t=g.APPDATA||r.default.join(u,"AppData","Roaming"),n=g.LOCALAPPDATA||r.default.join(u,"AppData","Local");return{data:r.default.join(n,e,"Data"),config:r.default.join(t,e,"Config"),cache:r.default.join(n,e,"Cache"),log:r.default.join(n,e,"Log"),temp:r.default.join(S,e)}},U=e=>{let t=r.default.basename(u);return{data:r.default.join(g.XDG_DATA_HOME||r.default.join(u,".local","share"),e),config:r.default.join(g.XDG_CONFIG_HOME||r.default.join(u,".config"),e),cache:r.default.join(g.XDG_CACHE_HOME||r.default.join(u,".cache"),e),log:r.default.join(g.XDG_STATE_HOME||r.default.join(u,".local","state"),e),temp:r.default.join(S,t,e)}};function h(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),D.default.platform==="darwin"?M(e):D.default.platform==="win32"?I(e):U(e)}var H=require("pako"),z=h("prisma-dev");async function A(e,t){await e.stream().pipeTo(b.WriteStream.toWeb((0,b.createWriteStream)(t,{encoding:"utf-8"})))}var P=class extends Error{constructor(n,i){super(`Port number \`${n}\` is not available for service ${i}.`);this.port=n;this.service=i}name="PortNotAvailableError"};var a={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},W=`postgres://${a.username}:${a.password}@localhost`,x=new URLSearchParams({sslmode:a.sslMode}),X=new URLSearchParams({...Object.fromEntries(x.entries()),connection_limit:String(a.connectionLimit),connect_timeout:String(a.connectTimeout),max_idle_connection_lifetime:String(a.maxIdleConnectionLifetime),pool_timeout:String(a.poolTimeout),single_use_connections:"true",socket_timeout:String(a.socketTimeout)});async function q(e,t){let n=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return _(e,t,{db:null,port:n,server:null});let{debug:i}=t,d=await(e==="shadow_database"?J:O)(t.pgliteDataDirPath,i);i&&d.onNotification((o,c)=>{console.debug(`[${e}][${o}] ${c}`)});let l=new E.PGLiteSocketServer({db:d,debug:i,inspect:i,port:n});i&&(l.addEventListener("listening",o=>{let{detail:c}=o;console.debug(`[${e}] server listening on ${JSON.stringify(c)}`)}),l.addEventListener("connection",o=>{let{clientAddress:c,clientPort:L}=o.detail;console.debug(`[${e}] client connected from ${c}:${L}`)}),l.addEventListener("error",o=>{let{detail:c}=o;console.error(`[${e}] server error:`,c)}));try{await l.start()}catch(o){throw o instanceof Error&&"code"in o&&o.code==="EADDRINUSE"?new P(n,e):o}return _(e,t,{db:d,port:n,server:l})}function _(e,t,n){let{debug:i}=t,{db:s,port:d,server:l}=n||{};return i&&console.debug(`[${e}] server started on port ${d}`),{...a,close:async()=>{let o=[];try{await l?.stop(),i&&console.debug(`[${e}] server stopped on port ${d}`)}catch(c){console.error(`[${e}] server stop error`,c),o.push(c)}if(e==="database")try{await s?.syncToFs(),i&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),o.push(c)}try{await s?.close(),i&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),o.push(c)}if(o.length>0)throw new AggregateError(o,`Failed to close ${e} properly`)},connectionString:T(d,x),dump:async o=>{e==="shadow_database"||!s||await B({db:s,debug:i,destinationPath:o})},port:d,prismaORMConnectionString:T(d,X),terminalCommand:`PGPASSWORD=${a.password} PGSSLMODE=${a.sslMode} psql -h localhost -p ${d} -U ${a.username} -d ${a.database}`}}function T(e,t){return`${W}:${e}/${a.database}?${t.toString()}`}async function O(e,t){return await w.PGlite.create({database:a.database,dataDir:e,debug:t?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:a.username})}async function J(e,t){return await w.PGlite.create({database:a.database,dataDir:"memory://",debug:t?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:a.username})}async function B(e){let{dataDir:t,db:n,debug:i,destinationPath:s}=e,d=n||await O(t,i),{pgDump:l}=await import("@electric-sql/pglite-tools/pg_dump"),o=await l({args:["--quote-all-identifiers","--schema-only"],fileName:s?(0,$.filename)(s):void 0,pg:d});return s?(i&&console.debug(`[DB] Dumping database to ${s}`),await A(o,s)):(i&&console.debug("[DB] Dumping database to memory"),await o.text())}0&&(module.exports={dumpDB,startDBServer});
package/dist/db.d.cts CHANGED
@@ -1,3 +1,3 @@
1
1
  import '@electric-sql/pglite';
2
- export { l as DBDump, k as DBServer, m as DBServerPurpose, n as DumpDBOptions, o as dumpDB, s as startDBServer } from './db-9fHowc0q.cjs';
2
+ export { l as DBDump, k as DBServer, m as DBServerPurpose, n as DumpDBOptions, o as dumpDB, s as startDBServer } from './db-B1_DGnTu.cjs';
3
3
  import 'valibot';
package/dist/db.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import '@electric-sql/pglite';
2
- export { l as DBDump, k as DBServer, m as DBServerPurpose, n as DumpDBOptions, o as dumpDB, s as startDBServer } from './db-9fHowc0q.js';
2
+ export { l as DBDump, k as DBServer, m as DBServerPurpose, n as DumpDBOptions, o as dumpDB, s as startDBServer } from './db-B1_DGnTu.js';
3
3
  import 'valibot';
package/dist/db.js CHANGED
@@ -1 +1 @@
1
- import{a,b}from"./chunk-UMLPYZWE.js";import"./chunk-YMJGNP57.js";export{b as dumpDB,a as startDBServer};
1
+ import{a,b}from"./chunk-QUQSA6T7.js";import"./chunk-YMJGNP57.js";export{b as dumpDB,a as startDBServer};
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var it=Object.create;var B=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var ut=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var lt=(t,e)=>{for(var r in e)B(t,r,{get:e[r],enumerable:!0})},ue=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ct(e))!dt.call(t,o)&&o!==r&&B(t,o,{get:()=>e[o],enumerable:!(n=at(e,o))||n.enumerable});return t};var L=(t,e,r)=>(r=t!=null?it(ut(t)):{},ue(e||!t||!t.__esModule?B(r,"default",{value:t,enumerable:!0}):r,t)),pt=t=>ue(B({},"__esModule",{value:!0}),t);var Bt={};lt(Bt,{DEFAULT_DATABASE_PORT:()=>ve,DEFAULT_SERVER_PORT:()=>Pe,DEFAULT_SHADOW_DATABASE_PORT:()=>De,PortNotAvailableError:()=>w,unstable_startServer:()=>Ct});module.exports=pt(Bt);var O=require("hono/http-exception"),p=require("valibot"),de=/^(postgres|postgresql):\/\//,mt=(0,p.pipe)((0,p.string)(),(0,p.parseJson)(),(0,p.object)({databaseUrl:(0,p.pipe)((0,p.string)(),(0,p.url)(),(0,p.regex)(de)),shadowDatabaseUrl:(0,p.optional)((0,p.pipe)((0,p.string)(),(0,p.url)(),(0,p.regex)(de)))}));function le(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function ft(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:n,success:o}=(0,p.safeParse)(mt,e,{abortEarly:!0});return o?[null,n]:[r]}var E=(t,e)=>{let{authorization:r}=t;if(!r)throw new O.HTTPException(401,{message:"Missing API Key"});let[n,o="",s]=r.split(" ");if(n!=="Bearer"||s)throw new O.HTTPException(401,{message:"Invalid API Key"});let[i,a]=ft(o);if(i)throw new O.HTTPException(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c}=a;if(c!==e.var.db.connectionString)throw new O.HTTPException(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:a}};var W=require("@electric-sql/pglite"),xe=require("@electric-sql/pglite-socket"),Ae=require("@electric-sql/pglite-tools/pg_dump"),Te=require("pathe/utils");var M=require("fs"),g=require("fs/promises");var l=L(require("path"),1),K=L(require("os"),1),j=L(require("process"),1),S=K.default.homedir(),J=K.default.tmpdir(),{env:x}=j.default,gt=t=>{let e=l.default.join(S,"Library");return{data:l.default.join(e,"Application Support",t),config:l.default.join(e,"Preferences",t),cache:l.default.join(e,"Caches",t),log:l.default.join(e,"Logs",t),temp:l.default.join(J,t)}},ht=t=>{let e=x.APPDATA||l.default.join(S,"AppData","Roaming"),r=x.LOCALAPPDATA||l.default.join(S,"AppData","Local");return{data:l.default.join(r,t,"Data"),config:l.default.join(e,t,"Config"),cache:l.default.join(r,t,"Cache"),log:l.default.join(r,t,"Log"),temp:l.default.join(J,t)}},yt=t=>{let e=l.default.basename(S);return{data:l.default.join(x.XDG_DATA_HOME||l.default.join(S,".local","share"),t),config:l.default.join(x.XDG_CONFIG_HOME||l.default.join(S,".config"),t),cache:l.default.join(x.XDG_CACHE_HOME||l.default.join(S,".cache"),t),log:l.default.join(x.XDG_STATE_HOME||l.default.join(S,".local","state"),t),temp:l.default.join(J,e,t)}};function Q(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),j.default.platform==="darwin"?gt(t):j.default.platform==="win32"?ht(t):yt(t)}var pe=require("pako"),me=Q("prisma-dev");function fe(t,e){return`${me.cache}/engine/${t}/${e}`}function _(t){return`${me.data}/${t}`}async function ge(t){try{return await(0,g.access)(t,g.constants.F_OK),!0}catch(e){if(z(e))return!1;throw e}}async function he(t,e){let r=(0,pe.inflate)(t);await(0,g.writeFile)(e,r),await(0,g.chmod)(e,"755")}async function ye(t,e){await t.stream().pipeTo(M.WriteStream.toWeb((0,M.createWriteStream)(e,{encoding:"utf-8"})))}function z(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function be(t){try{return await(0,g.readFile)(t,{encoding:"utf-8"})}catch(e){if(z(e))return null;throw e}}async function Se(t){await(0,g.mkdir)(t,{recursive:!0})}async function we(t){try{return(await(0,g.readdir)(t,{withFileTypes:!0})).reduce((r,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&r.push(n.name),r),[])}catch(e){if(z(e))return[];throw e}}var ve=51214,Pe=51213,De=51215,w=class extends Error{constructor(r,n){super(`Port number \`${r}\` is not available for service ${n}.`);this.port=r;this.service=n}name="PortNotAvailableError"};var h={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},bt=`postgres://${h.username}:${h.password}@localhost`,St=new URLSearchParams({connection_limit:String(h.connectionLimit),connect_timeout:String(h.connectTimeout),max_idle_connection_lifetime:String(h.maxIdleConnectionLifetime),pool_timeout:String(h.poolTimeout),socket_timeout:String(h.socketTimeout),sslmode:h.sslMode});async function X(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Ee(t,e,{db:null,port:r,server:null});let{debug:n}=e,s=await(t==="shadow_database"?vt:Re)(e.pgliteDataDirPath,n);n&&s.onNotification((a,c)=>{console.debug(`[${t}][${a}] ${c}`)});let i=new xe.PGLiteSocketServer({db:s,debug:n,inspect:n,port:r});n&&(i.addEventListener("listening",a=>{let{detail:c}=a;console.debug(`[${t}] server listening on ${JSON.stringify(c)}`)}),i.addEventListener("connection",a=>{let{clientAddress:c,clientPort:m}=a.detail;console.debug(`[${t}] client connected from ${c}:${m}`)}),i.addEventListener("error",a=>{let{detail:c}=a;console.error(`[${t}] server error:`,c)}));try{await i.start()}catch(a){throw a instanceof Error&&"code"in a&&a.code==="EADDRINUSE"?new w(r,t):a}return Ee(t,e,{db:s,port:r,server:i})}function Ee(t,e,r){let{debug:n}=e,{db:o,port:s,server:i}=r||{};return n&&console.debug(`[${t}] server started on port ${s}`),{...h,close:async()=>{let a=[];try{await i?.stop(),n&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),a.push(c)}if(t==="database")try{await o?.syncToFs(),n&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),a.push(c)}try{await o?.close(),n&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${t} properly`)},connectionString:wt(s),dump:async a=>{t==="shadow_database"||!o||await Pt({db:o,debug:n,destinationPath:a})},port:s}}function wt(t){return`${bt}:${t}/${h.database}?${St.toString()}`}async function Re(t,e){return await W.PGlite.create({database:h.database,dataDir:t,debug:e?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:h.username})}async function vt(t,e){return await W.PGlite.create({database:h.database,dataDir:"memory://",debug:e?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:h.username})}async function Pt(t){let{dataDir:e,db:r,debug:n,destinationPath:o}=t,s=r||await Re(e,n),i=await(0,Ae.pgDump)({args:["--quote-all-identifiers","--schema-only"],fileName:o?(0,Te.filename)(o):void 0,pg:s});return o?(n&&console.debug(`[DB] Dumping database to ${o}`),await ye(i,o)):(n&&console.debug("[DB] Dumping database to memory"),await i.text())}var Ke=require("http"),Je=require("util"),Qe=require("@hono/node-server"),ze=L(require("@prisma/get-platform"),1);function N(){let t,e,r=new Promise((s,i)=>{t=s,e=i}),n=s=>{n=o=null,e(s)},o=s=>{o=n=null,t(s)};return{promise:r,reject:s=>n?.(s),resolve:s=>o?.(s)}}var We=require("hono/logger"),te=require("hono/tiny");var Ve=require("hono/tiny"),R=require("hono/validator");var f=require("valibot"),Dt=(0,f.object)({tags:(0,f.union)([(0,f.pipe)((0,f.array)((0,f.string)()),(0,f.minLength)(1)),(0,f.literal)("all")])});async function Oe(t){let{output:e,success:r}=(0,f.safeParse)(Dt,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var $e=require("child_process"),Ie=require("events"),ke=require("fs/promises"),He=require("path"),Ce=require("timers/promises");var Be=require("foreground-child/proxy-signals"),Le=require("std-env");var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Et,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:xt,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:_e}=Le.process.env,T=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,n=`${e.schemaHash}:${e.clientVersion}`;try{let o=t.#r.get(n);if(o)return o;let s=new t(e);return t.#r.set(n,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(n)}}static async stopAll(e){let n=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([o])=>o!==e).map(async([o,s])=>{try{await s.stop()}finally{t.#r.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(n.length>0)throw new AggregateError(n,"Failed to stop engines")}async commitTransaction(e,r){return await this.#a(e,r,"commit")}async request(e,r){let{url:n}=await this.start(),o=this.#i(r),s=await fetch(n,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await A.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#a(e,r,"rollback")}async startTransaction(e,r){let{url:n}=await this.start(),o=this.#i(r),s=await fetch(`${n}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await A.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:n}=N();this.#t=e;let o=xt||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=(0,$e.spawn)(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});(0,Be.proxySignals)(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=m=>{let b=m.split(`
2
- `).find(st=>st.includes("Started query engine http server"));if(!b)return;s.stdout.removeListener("data",i);let{fields:D}=JSON.parse(b);if(D==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${m}`));let{ip:y,port:ce}=D;if(y==null||ce==null)return r(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
- Received data: ${m}`));n({childProcess:s,url:`http://${y}:${ce}`})},a=m=>{this.#t=null,r(new $(String(m))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(m,b)=>{this.#t=null,r(new $(`Query Engine exited with code ${m} and signal ${b}`))};return s.once("exit",c),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await(0,Ie.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#n();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=fe(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,ke.mkdir)(r,{recursive:!0});let{platform:n}=this.#e.platform,o=n==="windows"?".exe":"",s=(0,He.join)(r,`query-engine-${n}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Et==="1"||await ge(s)===!1)&&await this.#o({commitHash:e,extension:o,engineBinaryPath:s}),s}async#n(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let n=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let o=n.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#o(e){let{commitHash:r,extension:n,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${n}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);_e&&await(0,Ce.setTimeout)(Number(_e)),await he(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#i(e){let r={};for(let[n,o]of Object.entries(e))o!=null&&(r[n]=o);return r}async#a(e,r,n){let{url:o}=await this.#t,s=this.#i(r),i=await fetch(`${o}/transaction/${e}/${n}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await A.fromResponse(i);try{return await i.json()}catch{return{}}}};function F(t,e){return console.error(t),t instanceof $?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof A?e.text(t.responseBody,t.statusCode):e.body(null,500)}var $=class extends Error{name="EngineStartError"},A=class t extends Error{constructor(r,n,o){super(`${r}: Query Engine response status ${n}, body: ${o}`);this.action=r;this.statusCode=n;this.responseBody=o}name="EngineHttpError";static async fromResponse(r){let n=new URL(r.url),o=await r.text();return new t(n.pathname,r.status,o)}};var Y=require("buffer"),V=new Map;async function Z(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}function je(t){let e=t.req.param("schemaHash"),r=V.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}var At=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function Me(t,e){let r=Y.Buffer.from(t,"base64").toString("utf8"),n=`datasource db {
1
+ "use strict";var at=Object.create;var L=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,lt=Object.prototype.hasOwnProperty;var pt=(t,e)=>{for(var r in e)L(t,r,{get:e[r],enumerable:!0})},de=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ut(e))!lt.call(t,o)&&o!==r&&L(t,o,{get:()=>e[o],enumerable:!(n=ct(e,o))||n.enumerable});return t};var T=(t,e,r)=>(r=t!=null?at(dt(t)):{},de(e||!t||!t.__esModule?L(r,"default",{value:t,enumerable:!0}):r,t)),mt=t=>de(L({},"__esModule",{value:!0}),t);var Bt={};pt(Bt,{DEFAULT_DATABASE_PORT:()=>ve,DEFAULT_SERVER_PORT:()=>De,DEFAULT_SHADOW_DATABASE_PORT:()=>Ee,PortNotAvailableError:()=>P,unstable_startServer:()=>Ht});module.exports=mt(Bt);var _=require("hono/http-exception"),m=require("valibot"),le=/^(postgres|postgresql):\/\//,gt=(0,m.pipe)((0,m.string)(),(0,m.parseJson)(),(0,m.object)({databaseUrl:(0,m.pipe)((0,m.string)(),(0,m.url)(),(0,m.regex)(le)),shadowDatabaseUrl:(0,m.pipe)((0,m.string)(),(0,m.url)(),(0,m.regex)(le))}));function pe(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function ft(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:n,success:o}=(0,m.safeParse)(gt,e,{abortEarly:!0});return o?[null,n]:[r]}var E=(t,e)=>{let{authorization:r}=t;if(!r)throw new _.HTTPException(401,{message:"Missing API Key"});let[n,o="",s]=r.split(" ");if(n!=="Bearer"||s)throw new _.HTTPException(401,{message:"Invalid API Key"});let[i,a]=ft(o);if(i)throw new _.HTTPException(401,{message:"Invalid API Key",cause:i.join(", ")});let{hostname:c,port:p}=new URL(a.databaseUrl),{port:S}=e.get("db"),{hostname:b,port:y}=new URL(a.shadowDatabaseUrl),j=e.get("shadowDBPort");if(c!=="localhost"||Number(p)!==S||b!=="localhost"||Number(y)!==j)throw new _.HTTPException(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:a}};var X=require("@electric-sql/pglite"),Ae=require("@electric-sql/pglite-socket"),xe=require("pathe/utils");var N=require("fs"),h=require("fs/promises");var l=T(require("path"),1),J=T(require("os"),1),M=T(require("process"),1),w=J.default.homedir(),Q=J.default.tmpdir(),{env:R}=M.default,ht=t=>{let e=l.default.join(w,"Library");return{data:l.default.join(e,"Application Support",t),config:l.default.join(e,"Preferences",t),cache:l.default.join(e,"Caches",t),log:l.default.join(e,"Logs",t),temp:l.default.join(Q,t)}},yt=t=>{let e=R.APPDATA||l.default.join(w,"AppData","Roaming"),r=R.LOCALAPPDATA||l.default.join(w,"AppData","Local");return{data:l.default.join(r,t,"Data"),config:l.default.join(e,t,"Config"),cache:l.default.join(r,t,"Cache"),log:l.default.join(r,t,"Log"),temp:l.default.join(Q,t)}},St=t=>{let e=l.default.basename(w);return{data:l.default.join(R.XDG_DATA_HOME||l.default.join(w,".local","share"),t),config:l.default.join(R.XDG_CONFIG_HOME||l.default.join(w,".config"),t),cache:l.default.join(R.XDG_CACHE_HOME||l.default.join(w,".cache"),t),log:l.default.join(R.XDG_STATE_HOME||l.default.join(w,".local","state"),t),temp:l.default.join(Q,e,t)}};function W(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"?ht(t):M.default.platform==="win32"?yt(t):St(t)}var me=require("pako"),ge=W("prisma-dev");function fe(t,e){return`${ge.cache}/engine/${t}/${e}`}function $(t){return`${ge.data}/${t}`}async function he(t){try{return await(0,h.access)(t,h.constants.F_OK),!0}catch(e){if(z(e))return!1;throw e}}async function ye(t,e){let r=(0,me.inflate)(t);await(0,h.writeFile)(e,r),await(0,h.chmod)(e,"755")}async function Se(t,e){await t.stream().pipeTo(N.WriteStream.toWeb((0,N.createWriteStream)(e,{encoding:"utf-8"})))}function z(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function be(t){try{return await(0,h.readFile)(t,{encoding:"utf-8"})}catch(e){if(z(e))return null;throw e}}async function we(t){await(0,h.mkdir)(t,{recursive:!0})}async function Pe(t){try{return(await(0,h.readdir)(t,{withFileTypes:!0})).reduce((r,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&r.push(n.name),r),[])}catch(e){if(z(e))return[];throw e}}var ve=51214,De=51213,Ee=51215,P=class extends Error{constructor(r,n){super(`Port number \`${r}\` is not available for service ${n}.`);this.port=r;this.service=n}name="PortNotAvailableError"};var g={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},bt=`postgres://${g.username}:${g.password}@localhost`,Te=new URLSearchParams({sslmode:g.sslMode}),wt=new URLSearchParams({...Object.fromEntries(Te.entries()),connection_limit:String(g.connectionLimit),connect_timeout:String(g.connectTimeout),max_idle_connection_lifetime:String(g.maxIdleConnectionLifetime),pool_timeout:String(g.poolTimeout),single_use_connections:"true",socket_timeout:String(g.socketTimeout)});async function Y(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Re(t,e,{db:null,port:r,server:null});let{debug:n}=e,s=await(t==="shadow_database"?Pt:_e)(e.pgliteDataDirPath,n);n&&s.onNotification((a,c)=>{console.debug(`[${t}][${a}] ${c}`)});let i=new Ae.PGLiteSocketServer({db:s,debug:n,inspect:n,port:r});n&&(i.addEventListener("listening",a=>{let{detail:c}=a;console.debug(`[${t}] server listening on ${JSON.stringify(c)}`)}),i.addEventListener("connection",a=>{let{clientAddress:c,clientPort:p}=a.detail;console.debug(`[${t}] client connected from ${c}:${p}`)}),i.addEventListener("error",a=>{let{detail:c}=a;console.error(`[${t}] server error:`,c)}));try{await i.start()}catch(a){throw a instanceof Error&&"code"in a&&a.code==="EADDRINUSE"?new P(r,t):a}return Re(t,e,{db:s,port:r,server:i})}function Re(t,e,r){let{debug:n}=e,{db:o,port:s,server:i}=r||{};return n&&console.debug(`[${t}] server started on port ${s}`),{...g,close:async()=>{let a=[];try{await i?.stop(),n&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),a.push(c)}if(t==="database")try{await o?.syncToFs(),n&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),a.push(c)}try{await o?.close(),n&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${t} properly`)},connectionString:Oe(s,Te),dump:async a=>{t==="shadow_database"||!o||await vt({db:o,debug:n,destinationPath:a})},port:s,prismaORMConnectionString:Oe(s,wt),terminalCommand:`PGPASSWORD=${g.password} PGSSLMODE=${g.sslMode} psql -h localhost -p ${s} -U ${g.username} -d ${g.database}`}}function Oe(t,e){return`${bt}:${t}/${g.database}?${e.toString()}`}async function _e(t,e){return await X.PGlite.create({database:g.database,dataDir:t,debug:e?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:g.username})}async function Pt(t,e){return await X.PGlite.create({database:g.database,dataDir:"memory://",debug:e?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:g.username})}async function vt(t){let{dataDir:e,db:r,debug:n,destinationPath:o}=t,s=r||await _e(e,n),{pgDump:i}=await import("@electric-sql/pglite-tools/pg_dump"),a=await i({args:["--quote-all-identifiers","--schema-only"],fileName:o?(0,xe.filename)(o):void 0,pg:s});return o?(n&&console.debug(`[DB] Dumping database to ${o}`),await Se(a,o)):(n&&console.debug("[DB] Dumping database to memory"),await a.text())}var Qe=require("http"),We=require("util"),ze=require("@hono/node-server"),Xe=T(require("@prisma/get-platform"),1);function F(){let t,e,r=new Promise((s,i)=>{t=s,e=i}),n=s=>{n=o=null,e(s)},o=s=>{o=n=null,t(s)};return{promise:r,reject:s=>n?.(s),resolve:s=>o?.(s)}}var Ye=require("hono/logger"),re=require("hono/tiny");var Ge=require("hono/tiny"),x=require("hono/validator");var f=require("valibot"),Dt=(0,f.object)({tags:(0,f.union)([(0,f.pipe)((0,f.array)((0,f.string)()),(0,f.minLength)(1)),(0,f.literal)("all")])});async function $e(t){let{output:e,success:r}=(0,f.safeParse)(Dt,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var Ie=require("child_process"),ke=require("events"),He=require("fs/promises"),Be=require("path"),je=require("timers/promises");var Le=require("foreground-child/proxy-signals"),Me=require("std-env");var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Et,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Rt,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Ce}=Me.process.env,A=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,n=`${e.schemaHash}:${e.clientVersion}`;try{let o=t.#r.get(n);if(o)return o;let s=new t(e);return t.#r.set(n,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(n)}}static async stopAll(e){let n=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([o])=>o!==e).map(async([o,s])=>{try{await s.stop()}finally{t.#r.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(n.length>0)throw new AggregateError(n,"Failed to stop engines")}async commitTransaction(e,r){return await this.#a(e,r,"commit")}async request(e,r){let{url:n}=await this.start(),o=this.#i(r),s=await fetch(n,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await O.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#a(e,r,"rollback")}async startTransaction(e,r){let{url:n}=await this.start(),o=this.#i(r),s=await fetch(`${n}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await O.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:n}=F();this.#t=e;let o=Rt||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=(0,Ie.spawn)(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});(0,Le.proxySignals)(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=p=>{let S=p.split(`
2
+ `).find(it=>it.includes("Started query engine http server"));if(!S)return;s.stdout.removeListener("data",i);let{fields:b}=JSON.parse(S);if(b==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${p}`));let{ip:y,port:j}=b;if(y==null||j==null)return r(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
+ Received data: ${p}`));n({childProcess:s,url:`http://${y}:${j}`})},a=p=>{this.#t=null,r(new C(String(p))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(p,S)=>{this.#t=null,r(new C(`Query Engine exited with code ${p} and signal ${S}`))};return s.once("exit",c),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await(0,ke.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#n();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=fe(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,He.mkdir)(r,{recursive:!0});let{platform:n}=this.#e.platform,o=n==="windows"?".exe":"",s=(0,Be.join)(r,`query-engine-${n}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Et==="1"||await he(s)===!1)&&await this.#o({commitHash:e,extension:o,engineBinaryPath:s}),s}async#n(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let n=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let o=n.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#o(e){let{commitHash:r,extension:n,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${n}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);Ce&&await(0,je.setTimeout)(Number(Ce)),await ye(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#i(e){let r={};for(let[n,o]of Object.entries(e))o!=null&&(r[n]=o);return r}async#a(e,r,n){let{url:o}=await this.#t,s=this.#i(r),i=await fetch(`${o}/transaction/${e}/${n}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await O.fromResponse(i);try{return await i.json()}catch{return{}}}};function U(t,e){return console.error(t),t instanceof C?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof O?e.text(t.responseBody,t.statusCode):e.body(null,500)}var C=class extends Error{name="EngineStartError"},O=class t extends Error{constructor(r,n,o){super(`${r}: Query Engine response status ${n}, body: ${o}`);this.action=r;this.statusCode=n;this.responseBody=o}name="EngineHttpError";static async fromResponse(r){let n=new URL(r.url),o=await r.text();return new t(n.pathname,r.status,o)}};var Z=require("buffer"),V=new Map;async function ee(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}function Ne(t){let e=t.req.param("schemaHash"),r=V.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}var Ot=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function Fe(t,e){let r=Z.Buffer.from(t,"base64").toString("utf8"),n=`datasource db {
4
4
  provider = "postgresql"
5
5
  url = "${e.toString()}"
6
- }`,o=r.replace(At,n),s=await Z(o);return{base64Override:Y.Buffer.from(o,"utf8").toString("base64"),overrideHash:s}}function U(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var d=require("valibot"),Tt=(0,d.object)({isolation_level:(0,d.optional)((0,d.string)()),max_wait:(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0)),timeout:(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0))});async function Ne(t){let{issues:e,output:r,success:n}=(0,d.safeParse)(Tt,await t.req.json(),{abortEarly:!0});return n?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var Rt=(0,d.looseObject)({id:(0,d.union)([(0,d.string)(),(0,d.number)()])});function Fe(t,e){let{output:r,success:n}=(0,d.safeParse)(Rt,t);return n?r:e.json({EngineMalfunction:{}},500)}var I=new Ve.Hono;I.post("/invalidate",(0,R.validator)("header",E),async t=>{let e=await Oe(t);return e instanceof Response?e:t.body(null)});var Ot="/:clientVersion/:schemaHash",k=I.basePath(Ot);I.route("/",k);var _t=["/graphql","/itx/:transactionId/graphql"];k.on("POST",[..._t],(0,R.validator)("header",E),async t=>{let{req:e}=t;try{let r=await ee(t);if(r instanceof Response)return r;let n=await e.text(),o=e.param("transactionId"),s=await r.request(n,{...U(t),"X-transaction-id":o});return t.text(s)}catch(r){return F(r,t)}});k.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,R.validator)("header",E),async t=>{let{req:e}=t;try{let r=await ee(t);if(r instanceof Response)return r;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),i=await r[o](s,U(t));return t.json(i)}catch(r){return F(r,t)}});k.put("/schema",(0,R.validator)("header",E),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let n=e.param("schemaHash"),o=V.get(n);if(o==null){if(n!==await Z(r))return t.text("Schema hash mismatch",400);let s=new URL(t.get("db").connectionString);s.searchParams.set("single_use_connections","true");let i=await Me(r,s);return V.set(n,{base64Original:r,...i}),t.text(n)}return r!==o.base64Original?t.text("Schema mismatch",400):t.text(n)});k.post("/transaction/start",(0,R.validator)("header",E),async t=>{let{req:e}=t,r=await Ne(t);if(r instanceof Response)return r;try{let n=await ee(t);if(n instanceof Response)return n;let o=await n.startTransaction(r,U(t)),s=Fe(o,t);if(s instanceof Response)return s;let{id:i}=s,a=e.param("clientVersion"),c=t.get("port"),m=t.get("protocol"),b=e.param("schemaHash");return t.json({...o,"data-proxy":{endpoint:`${m}://localhost:${c}/${a}/${b}/itx/${i}`}})}catch(n){return F(n,t)}});async function ee(t){let{req:e}=t,r=je(t);if(r instanceof Response)return r;let{base64Override:n,overrideHash:o}=r.schemas;return await T.get({base64Schema:n,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:o})}var Ue=require("hono/tiny"),qe=require("http-status-codes"),q=new Ue.Hono;q.post("/database/dump",async t=>{let e=t.get("db"),r=t.get("serverState");return await e.dump(r.databaseDumpPath),t.json({dumpPath:r.databaseDumpPath},qe.StatusCodes.CREATED)});var cr=q.get("/health",t=>t.json({name:t.get("serverState").name}));async function Xe(t,e){let{port:r}=e;if(e.dryRun)return Ge(r,null);let n=await $t(r,t,e),{promise:o,reject:s,resolve:i}=N(),a=(0,Qe.serve)({createServer:Ke.createServer,fetch:n.fetch,overrideGlobalObjects:!1,port:r},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new w(r,"server"));console.error("[Accelerate]",c)}),await o,Ge(r,a)}function Ge(t,e){return{async close(){e&&await Promise.allSettled([(0,Je.promisify)(e.close.bind(e))(),T.stopAll()])},port:t,url:`http://localhost:${t}`}}async function $t(t,e,r){let{debug:n}=r,o=new te.Hono,s=await ze.default.getPlatformInfo();return n&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),n&&o.use("*",(0,We.logger)((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",e),i.set("debug",!!n),i.set("platform",s),i.set("port",t),i.set("protocol","http"),i.set("serverState",r),await a())),o.route("/",re),o}var re=new te.Hono;re.route("/",I);re.route("/",q);var rt=require("fs/promises"),nt=require("hono/client"),v=require("pathe"),G=require("proper-lockfile"),C=require("std-env"),u=require("valibot");var Ye=require("std-env");function Ze(t,e){if(t==null)return!1;try{return Ye.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var ot=(0,u.pipe)((0,u.string)(),(0,u.url)()),et=(0,u.object)({connectionString:ot}),tt=(0,u.object)({url:ot}),ne=(0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(1)),It=(0,u.object)({database:et,http:tt,ppg:tt,shadowDatabase:et}),kt=(0,u.object)({databasePort:ne,exports:(0,u.optional)(It),name:(0,u.pipe)((0,u.string)(),(0,u.minLength)(1)),pid:(0,u.optional)((0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(0))),port:ne,shadowDatabasePort:ne,version:(0,u.literal)("1")}),ae=Symbol("initialize"),oe="default",P=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??oe,this.persistenceMode=e.persistenceMode,this.pid=e.pid??C.process.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new H({...e,pid:C.process.pid}):new se(e);return await r[ae](),r}static async fromServerDump(e){let{debug:r,name:n=oe}=e??{},o=_(n),s=H.getServerDumpPath(o),i=await be(s);if(i==null)return r&&console.debug(`[State] No server dump file found at: ${s}`),null;r&&(console.debug(`[State] server dump file found at "${s}":`),console.debug(i));let{issues:a,output:c,success:m}=(0,u.safeParse)((0,u.pipe)((0,u.string)(),(0,u.parseJson)(),kt),i);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
7
- ${JSON.stringify(a,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new H({databasePort:c.databasePort,debug:r,dryRun:!1,name:n,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},n=(0,v.join)(_(oe),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let o=await we(n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(s=>Ht(s,r)))}},se=class extends P{constructor(e){super({...e,persistenceMode:"stateless",pid:C.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[ae](){}async close(){}async writeServerDump(){}},H=class t extends P{#r;#e;#t;#s;#n;#o=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=_(this.name),this.#r=(0,v.join)(this.#e,"db_dump.bak"),this.#t=(0,v.join)(this.#e,".pglite"),this.#n=e.serverDump??null,this.#s=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,v.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get pgliteDataDirPath(){return this.#t}async[ae](){await Se(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#o=await(0,G.lock)(this.#e,{lockfilePath:(0,v.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new ie(this.name):e}}async close(){if(this.#o!=null)try{await this.#o(),this.#o=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#n={name:this.name,version:"1",pid:C.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,rt.writeFile)(this.#s,`${JSON.stringify(this.#n,null,2)}
8
- `,{encoding:"utf-8"})}};async function Ht(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let n=await P.fromServerDump({debug:e,name:t});if(!n)return e&&console.debug(`[State] no server state found for name: ${t}`),{...r,status:"no_such_server"};r.databasePort=n.databasePort,r.exports=n.exports,r.pid=n.pid,r.port=n.port,r.shadowDatabasePort=n.shadowDatabasePort;let{exports:o,pid:s}=n;if(!Ze(s,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${s}`),{...r,status:"not_running"};let i=_(t);try{if(!await(0,G.check)(i,{lockfilePath:(0,v.join)(i,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(b){e&&console.error(`[State] server state for "${t}" failed to check lock:`,b)}if(!o)return{...r,status:"starting_up"};let{http:a}=o,c=await(0,nt.hc)(a.url).health.$get();if(!c.ok)return e&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(c)}`),{...r,status:"not_running"};let m=await c.json();return m.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(m)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(m)}`),{...r,status:"running"})}catch(n){return e&&console.error(`[State] failed to get server status for "${t}":`,n),{...r,status:"error"}}}var ie=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};async function Ct(t){let e=await P.createExclusively(t),[r,n]=await Promise.all([X("database",e),X("shadow_database",e)]),o=await Xe(r,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:le({databaseUrl:r.connectionString,shadowDatabaseUrl:n.connectionString})}).toString()}`,i={database:{connectionString:r.connectionString},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:n.connectionString}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,r,n])};async function a(c,m){let D=(await Promise.allSettled(m.map(y=>y.close()))).filter(y=>y.status==="rejected").map(y=>new Error(y.reason));try{await c.close()}catch(y){D.push(y)}if(D.length>0)throw new AggregateError(D,"Failed to close some servers")}}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,PortNotAvailableError,unstable_startServer});
6
+ }`,o=r.replace(Ot,n),s=await ee(o);return{base64Override:Z.Buffer.from(o,"utf8").toString("base64"),overrideHash:s}}function G(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var d=require("valibot"),At=(0,d.object)({isolation_level:(0,d.optional)((0,d.string)()),max_wait:(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0)),timeout:(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0))});async function Ue(t){let{issues:e,output:r,success:n}=(0,d.safeParse)(At,await t.req.json(),{abortEarly:!0});return n?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var xt=(0,d.looseObject)({id:(0,d.union)([(0,d.string)(),(0,d.number)()])});function Ve(t,e){let{output:r,success:n}=(0,d.safeParse)(xt,t);return n?r:e.json({EngineMalfunction:{}},500)}var I=new Ge.Hono;I.post("/invalidate",(0,x.validator)("header",E),async t=>{let e=await $e(t);return e instanceof Response?e:t.body(null)});var Tt="/:clientVersion/:schemaHash",k=I.basePath(Tt);I.route("/",k);var _t=["/graphql","/itx/:transactionId/graphql"];k.on("POST",[..._t],(0,x.validator)("header",E),async t=>{let{req:e}=t;try{let r=await te(t);if(r instanceof Response)return r;let n=await e.text(),o=e.param("transactionId"),s=await r.request(n,{...G(t),"X-transaction-id":o});return t.text(s)}catch(r){return U(r,t)}});k.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,x.validator)("header",E),async t=>{let{req:e}=t;try{let r=await te(t);if(r instanceof Response)return r;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),i=await r[o](s,G(t));return t.json(i)}catch(r){return U(r,t)}});k.put("/schema",(0,x.validator)("header",E),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let n=e.param("schemaHash"),o=V.get(n);if(o==null){if(n!==await ee(r))return t.text("Schema hash mismatch",400);let s=await Fe(r,t.get("db").prismaORMConnectionString);return V.set(n,{base64Original:r,...s}),t.text(n)}return r!==o.base64Original?t.text("Schema mismatch",400):t.text(n)});k.post("/transaction/start",(0,x.validator)("header",E),async t=>{let{req:e}=t,r=await Ue(t);if(r instanceof Response)return r;try{let n=await te(t);if(n instanceof Response)return n;let o=await n.startTransaction(r,G(t)),s=Ve(o,t);if(s instanceof Response)return s;let{id:i}=s,a=e.param("clientVersion"),c=t.get("port"),p=t.get("protocol"),S=e.param("schemaHash");return t.json({...o,"data-proxy":{endpoint:`${p}://localhost:${c}/${a}/${S}/itx/${i}`}})}catch(n){return U(n,t)}});async function te(t){let{req:e}=t,r=Ne(t);if(r instanceof Response)return r;let{base64Override:n,overrideHash:o}=r.schemas;return await A.get({base64Schema:n,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:o})}var qe=require("hono/tiny"),Ke=require("http-status-codes"),q=new qe.Hono;q.post("/database/dump",async t=>{let e=t.get("db"),r=t.get("serverState");return await e.dump(r.databaseDumpPath),t.json({dumpPath:r.databaseDumpPath},Ke.StatusCodes.CREATED)});var cr=q.get("/health",t=>t.json({name:t.get("serverState").name}));async function Ze(t,e){let{port:r}=e;if(e.dryRun)return Je(r,null);let n=await $t(r,t,e),{promise:o,reject:s,resolve:i}=F(),a=(0,ze.serve)({createServer:Qe.createServer,fetch:n.fetch,overrideGlobalObjects:!1,port:r},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new P(r,"server"));console.error("[Accelerate]",c)}),await o,Je(r,a)}function Je(t,e){return{async close(){e&&await Promise.allSettled([(0,We.promisify)(e.close.bind(e))(),A.stopAll()])},port:t,url:`http://localhost:${t}`}}async function $t(t,e,r){let{debug:n}=r,o=new re.Hono,s=await Xe.default.getPlatformInfo();return n&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),n&&o.use("*",(0,Ye.logger)((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",e),i.set("debug",!!n),i.set("platform",s),i.set("port",t),i.set("protocol","http"),i.set("serverState",r),i.set("shadowDBPort",r.shadowDatabasePort),await a())),o.route("/",ne),o}var ne=new re.Hono;ne.route("/",I);ne.route("/",q);var ot=require("fs/promises"),st=require("hono/client"),v=require("pathe"),K=require("proper-lockfile"),B=require("std-env"),u=require("valibot");var et=require("std-env");function tt(t,e){if(t==null)return!1;try{return et.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var ie=(0,u.pipe)((0,u.string)(),(0,u.url)()),rt=(0,u.object)({connectionString:ie,prismaORMConnectionString:(0,u.optional)(ie),terminalCommand:(0,u.optional)((0,u.string)())}),nt=(0,u.object)({url:ie}),oe=(0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(1)),Ct=(0,u.object)({database:rt,http:nt,ppg:nt,shadowDatabase:rt}),It=(0,u.object)({databasePort:oe,exports:(0,u.optional)(Ct),name:(0,u.pipe)((0,u.string)(),(0,u.minLength)(1)),pid:(0,u.optional)((0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(0))),port:oe,shadowDatabasePort:oe,version:(0,u.literal)("1")}),ue=Symbol("initialize"),se="default",D=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??se,this.persistenceMode=e.persistenceMode,this.pid=e.pid??B.process.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new H({...e,pid:B.process.pid}):new ae(e);return await r[ue](),r}static async fromServerDump(e){let{debug:r,name:n=se}=e??{},o=$(n),s=H.getServerDumpPath(o),i=await be(s);if(i==null)return r&&console.debug(`[State] No server dump file found at: ${s}`),null;r&&(console.debug(`[State] server dump file found at "${s}":`),console.debug(i));let{issues:a,output:c,success:p}=(0,u.safeParse)((0,u.pipe)((0,u.string)(),(0,u.parseJson)(),It),i);if(!p)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
7
+ ${JSON.stringify(a,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new H({databasePort:c.databasePort,debug:r,dryRun:!1,name:n,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},n=(0,v.join)($(se),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let o=await Pe(n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(s=>kt(s,r)))}},ae=class extends D{constructor(e){super({...e,persistenceMode:"stateless",pid:B.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[ue](){}async close(){}async writeServerDump(){}},H=class t extends D{#r;#e;#t;#s;#n;#o=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=$(this.name),this.#r=(0,v.join)(this.#e,"db_dump.bak"),this.#t=(0,v.join)(this.#e,".pglite"),this.#n=e.serverDump??null,this.#s=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,v.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get pgliteDataDirPath(){return this.#t}async[ue](){await we(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#o=await(0,K.lock)(this.#e,{lockfilePath:(0,v.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new ce(this.name):e}}async close(){if(this.#o!=null)try{await this.#o(),this.#o=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#n={name:this.name,version:"1",pid:B.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,ot.writeFile)(this.#s,`${JSON.stringify(this.#n,null,2)}
8
+ `,{encoding:"utf-8"})}};async function kt(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let n=await D.fromServerDump({debug:e,name:t});if(!n)return e&&console.debug(`[State] no server state found for name: ${t}`),{...r,status:"no_such_server"};r.databasePort=n.databasePort,r.exports=n.exports,r.pid=n.pid,r.port=n.port,r.shadowDatabasePort=n.shadowDatabasePort;let{exports:o,pid:s}=n;if(!tt(s,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${s}`),{...r,status:"not_running"};let i=$(t);try{if(!await(0,K.check)(i,{lockfilePath:(0,v.join)(i,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(S){e&&console.error(`[State] server state for "${t}" failed to check lock:`,S)}if(!o)return{...r,status:"starting_up"};let{http:a}=o,c=await(0,st.hc)(a.url).health.$get();if(!c.ok)return e&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(c)}`),{...r,status:"not_running"};let p=await c.json();return p.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(p)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(p)}`),{...r,status:"running"})}catch(n){return e&&console.error(`[State] failed to get server status for "${t}":`,n),{...r,status:"error"}}}var ce=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};async function Ht(t){let e=await D.createExclusively(t),[r,n]=await Promise.all([Y("database",e),Y("shadow_database",e)]),o=await Ze(r,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:pe({databaseUrl:r.prismaORMConnectionString,shadowDatabaseUrl:n.prismaORMConnectionString})}).toString()}`,i={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:n.prismaORMConnectionString,prismaORMConnectionString:n.prismaORMConnectionString,terminalCommand:n.terminalCommand}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,r,n])};async function a(c,p){let b=(await Promise.allSettled(p.map(y=>y.close()))).filter(y=>y.status==="rejected").map(y=>new Error(y.reason));try{await c.close()}catch(y){b.push(y)}if(b.length>0)throw new AggregateError(b,"Failed to close some servers")}}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,PortNotAvailableError,unstable_startServer});
package/dist/index.d.cts CHANGED
@@ -1,3 +1,3 @@
1
- export { D as DEFAULT_DATABASE_PORT, b as DEFAULT_SERVER_PORT, c as DEFAULT_SHADOW_DATABASE_PORT, P as PortAssignableService, d as PortNotAvailableError, a as Server, u as unstable_startServer } from './db-9fHowc0q.cjs';
1
+ export { D as DEFAULT_DATABASE_PORT, b as DEFAULT_SERVER_PORT, c as DEFAULT_SHADOW_DATABASE_PORT, P as PortAssignableService, d as PortNotAvailableError, a as Server, u as unstable_startServer } from './db-B1_DGnTu.cjs';
2
2
  import '@electric-sql/pglite';
3
3
  import 'valibot';
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { D as DEFAULT_DATABASE_PORT, b as DEFAULT_SERVER_PORT, c as DEFAULT_SHADOW_DATABASE_PORT, P as PortAssignableService, d as PortNotAvailableError, a as Server, u as unstable_startServer } from './db-9fHowc0q.js';
1
+ export { D as DEFAULT_DATABASE_PORT, b as DEFAULT_SERVER_PORT, c as DEFAULT_SHADOW_DATABASE_PORT, P as PortAssignableService, d as PortNotAvailableError, a as Server, u as unstable_startServer } from './db-B1_DGnTu.js';
2
2
  import '@electric-sql/pglite';
3
3
  import 'valibot';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import{a as H}from"./chunk-UMLPYZWE.js";import{a as L}from"./chunk-GFC5H6VQ.js";import{a as $,c as j,d as D,i as ze,j as Ge,k as Je,l as B}from"./chunk-YMJGNP57.js";import{HTTPException as v}from"hono/http-exception";import{object as se,optional as ie,parseJson as ae,pipe as A,regex as q,safeParse as ce,string as I,url as N}from"valibot";var V=/^(postgres|postgresql):\/\//,pe=A(I(),ae(),se({databaseUrl:A(I(),N(),q(V)),shadowDatabaseUrl:ie(A(I(),N(),q(V)))}));function U(n){return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}function ue(n){let e=Buffer.from(n,"base64url").toString("utf8"),{issues:t,output:r,success:o}=ce(pe,e,{abortEarly:!0});return o?[null,r]:[t]}var d=(n,e)=>{let{authorization:t}=n;if(!t)throw new v(401,{message:"Missing API Key"});let[r,o="",s]=t.split(" ");if(r!=="Bearer"||s)throw new v(401,{message:"Invalid API Key"});let[i,a]=ue(o);if(i)throw new v(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c}=a;if(c!==e.var.db.connectionString)throw new v(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:a}};import{createServer as Ve}from"http";import{promisify as Ue}from"util";import{serve as Ke}from"@hono/node-server";import Me from"@prisma/get-platform";function b(){let n,e,t=new Promise((s,i)=>{n=s,e=i}),r=s=>{r=o=null,e(s)},o=s=>{o=r=null,n(s)};return{promise:t,reject:s=>r?.(s),resolve:s=>o?.(s)}}import{logger as Qe}from"hono/logger";import{Hono as ne}from"hono/tiny";import{Hono as De}from"hono/tiny";import{validator as y}from"hono/validator";import{array as le,literal as me,minLength as de,object as ge,pipe as he,safeParse as fe,string as ye,union as we}from"valibot";var Se=ge({tags:we([he(le(ye()),de(1)),me("all")])});async function K(n){let{output:e,success:t}=fe(Se,await n.req.json(),{abortEarly:!0});return t?e:n.text("Invalid input",400)}import{spawn as ve}from"child_process";import{once as be}from"events";import{mkdir as Ee}from"fs/promises";import{join as Pe}from"path";import{setTimeout as Re}from"timers/promises";import{proxySignals as Te}from"foreground-child/proxy-signals";import{process as He}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Ae,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Ie,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:M}=He.env,h=class n{static#n=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:t}=e,r=`${e.schemaHash}:${e.clientVersion}`;try{let o=n.#n.get(r);if(o)return o;let s=new n(e);return n.#n.set(r,s),t&&console.debug("[Query Engine] starting...",e),await s.start(),t&&console.debug("[Query Engine] started!"),s}finally{n.stopAll(r)}}static async stopAll(e){let r=(await Promise.allSettled(Array.from(n.#n.entries()).filter(([o])=>o!==e).map(async([o,s])=>{try{await s.stop()}finally{n.#n.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(r.length>0)throw new AggregateError(r,"Failed to stop engines")}async commitTransaction(e,t){return await this.#o(e,t,"commit")}async request(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(r,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await g.fromResponse(s);return await s.text()}async rollbackTransaction(e,t){return await this.#o(e,t,"rollback")}async startTransaction(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await g.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:t,resolve:r}=b();this.#t=e;let o=Ie||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=ve(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});Te(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=p=>{let l=p.split(`
2
- `).find(oe=>oe.includes("Started query engine http server"));if(!l)return;s.stdout.removeListener("data",i);let{fields:m}=JSON.parse(l);if(m==null)return t(new Error(`Unexpected data during initialization, "fields" are missing: ${p}`));let{ip:u,port:_}=m;if(u==null||_==null)return t(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
- Received data: ${p}`));r({childProcess:s,url:`http://${u}:${_}`})},a=p=>{this.#t=null,t(new f(String(p))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(p,l)=>{this.#t=null,t(new f(`Query Engine exited with code ${p} and signal ${l}`))};return s.once("exit",c),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await be(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#i();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let t=$(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await Ee(t,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=Pe(t,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Ae==="1"||await j(s)===!1)&&await this.#a({commitHash:e,extension:o,engineBinaryPath:s}),s}async#i(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let r=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!r)throw new Error("Couldn't find engines version in package.json");let o=r.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#a(e){let{commitHash:t,extension:r,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${t}/${s}/query-engine${r}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);M&&await Re(Number(M)),await D(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#r(e){let t={};for(let[r,o]of Object.entries(e))o!=null&&(t[r]=o);return t}async#o(e,t,r){let{url:o}=await this.#t,s=this.#r(t),i=await fetch(`${o}/transaction/${e}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await g.fromResponse(i);try{return await i.json()}catch{return{}}}};function E(n,e){return console.error(n),n instanceof f?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:n.message}}}},500):n instanceof g?e.text(n.responseBody,n.statusCode):e.body(null,500)}var f=class extends Error{name="EngineStartError"},g=class n extends Error{constructor(t,r,o){super(`${t}: Query Engine response status ${r}, body: ${o}`);this.action=t;this.statusCode=r;this.responseBody=o}name="EngineHttpError";static async fromResponse(t){let r=new URL(t.url),o=await t.text();return new n(r.pathname,t.status,o)}};import{Buffer as Q}from"buffer";var P=new Map;async function O(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function F(n){let e=n.req.param("schemaHash"),t=P.get(e);return t==null?n.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:t}}var Oe=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function z(n,e){let t=Q.from(n,"base64").toString("utf8"),r=`datasource db {
1
+ import{a as H}from"./chunk-QUQSA6T7.js";import{a as L}from"./chunk-NYMMHKXT.js";import{a as _,c as $,d as j,i as Fe,j as ze,k as Ge,l as B}from"./chunk-YMJGNP57.js";import{HTTPException as v}from"hono/http-exception";import{object as se,parseJson as ie,pipe as A,regex as M,safeParse as ae,string as C,url as N}from"valibot";var q=/^(postgres|postgresql):\/\//,ce=A(C(),ie(),se({databaseUrl:A(C(),N(),M(q)),shadowDatabaseUrl:A(C(),N(),M(q))}));function U(n){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(n).sort(([[e],[t]])=>e.localeCompare(t)))),"utf8").toString("base64url")}function pe(n){let e=Buffer.from(n,"base64url").toString("utf8"),{issues:t,output:r,success:o}=ae(ce,e,{abortEarly:!0});return o?[null,r]:[t]}var d=(n,e)=>{let{authorization:t}=n;if(!t)throw new v(401,{message:"Missing API Key"});let[r,o="",s]=t.split(" ");if(r!=="Bearer"||s)throw new v(401,{message:"Invalid API Key"});let[i,a]=pe(o);if(i)throw new v(401,{message:"Invalid API Key",cause:i.join(", ")});let{hostname:c,port:p}=new URL(a.databaseUrl),{port:l}=e.get("db"),{hostname:m,port:u}=new URL(a.shadowDatabaseUrl),b=e.get("shadowDBPort");if(c!=="localhost"||Number(p)!==l||m!=="localhost"||Number(u)!==b)throw new v(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:a}};import{createServer as Ne}from"http";import{promisify as qe}from"util";import{serve as Ue}from"@hono/node-server";import Ve from"@prisma/get-platform";function E(){let n,e,t=new Promise((s,i)=>{n=s,e=i}),r=s=>{r=o=null,e(s)},o=s=>{o=r=null,n(s)};return{promise:t,reject:s=>r?.(s),resolve:s=>o?.(s)}}import{logger as Ke}from"hono/logger";import{Hono as ne}from"hono/tiny";import{Hono as $e}from"hono/tiny";import{validator as y}from"hono/validator";import{array as ue,literal as le,minLength as me,object as de,pipe as ge,safeParse as he,string as fe,union as ye}from"valibot";var we=de({tags:ye([ge(ue(fe()),me(1)),le("all")])});async function V(n){let{output:e,success:t}=he(we,await n.req.json(),{abortEarly:!0});return t?e:n.text("Invalid input",400)}import{spawn as Se}from"child_process";import{once as be}from"events";import{mkdir as ve}from"fs/promises";import{join as Ee}from"path";import{setTimeout as Pe}from"timers/promises";import{proxySignals as Re}from"foreground-child/proxy-signals";import{process as Te}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Oe,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:He,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:K}=Te.env,h=class n{static#n=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:t}=e,r=`${e.schemaHash}:${e.clientVersion}`;try{let o=n.#n.get(r);if(o)return o;let s=new n(e);return n.#n.set(r,s),t&&console.debug("[Query Engine] starting...",e),await s.start(),t&&console.debug("[Query Engine] started!"),s}finally{n.stopAll(r)}}static async stopAll(e){let r=(await Promise.allSettled(Array.from(n.#n.entries()).filter(([o])=>o!==e).map(async([o,s])=>{try{await s.stop()}finally{n.#n.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(r.length>0)throw new AggregateError(r,"Failed to stop engines")}async commitTransaction(e,t){return await this.#o(e,t,"commit")}async request(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(r,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await g.fromResponse(s);return await s.text()}async rollbackTransaction(e,t){return await this.#o(e,t,"rollback")}async startTransaction(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await g.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:t,resolve:r}=E();this.#t=e;let o=He||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Se(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});Re(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=p=>{let l=p.split(`
2
+ `).find(oe=>oe.includes("Started query engine http server"));if(!l)return;s.stdout.removeListener("data",i);let{fields:m}=JSON.parse(l);if(m==null)return t(new Error(`Unexpected data during initialization, "fields" are missing: ${p}`));let{ip:u,port:b}=m;if(u==null||b==null)return t(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
+ Received data: ${p}`));r({childProcess:s,url:`http://${u}:${b}`})},a=p=>{this.#t=null,t(new f(String(p))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(p,l)=>{this.#t=null,t(new f(`Query Engine exited with code ${p} and signal ${l}`))};return s.once("exit",c),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await be(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#i();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let t=_(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await ve(t,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=Ee(t,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Oe==="1"||await $(s)===!1)&&await this.#a({commitHash:e,extension:o,engineBinaryPath:s}),s}async#i(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let r=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!r)throw new Error("Couldn't find engines version in package.json");let o=r.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#a(e){let{commitHash:t,extension:r,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${t}/${s}/query-engine${r}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);K&&await Pe(Number(K)),await j(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#r(e){let t={};for(let[r,o]of Object.entries(e))o!=null&&(t[r]=o);return t}async#o(e,t,r){let{url:o}=await this.#t,s=this.#r(t),i=await fetch(`${o}/transaction/${e}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await g.fromResponse(i);try{return await i.json()}catch{return{}}}};function P(n,e){return console.error(n),n instanceof f?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:n.message}}}},500):n instanceof g?e.text(n.responseBody,n.statusCode):e.body(null,500)}var f=class extends Error{name="EngineStartError"},g=class n extends Error{constructor(t,r,o){super(`${t}: Query Engine response status ${r}, body: ${o}`);this.action=t;this.statusCode=r;this.responseBody=o}name="EngineHttpError";static async fromResponse(t){let r=new URL(t.url),o=await t.text();return new n(r.pathname,t.status,o)}};import{Buffer as Q}from"buffer";var R=new Map;async function I(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function F(n){let e=n.req.param("schemaHash"),t=R.get(e);return t==null?n.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:t}}var Ae=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function z(n,e){let t=Q.from(n,"base64").toString("utf8"),r=`datasource db {
4
4
  provider = "postgresql"
5
5
  url = "${e.toString()}"
6
- }`,o=t.replace(Oe,r),s=await O(o);return{base64Override:Q.from(o,"utf8").toString("base64"),overrideHash:s}}function R(n){let{req:e}=n;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}import{integer as G,looseObject as xe,minValue as J,number as x,object as Ce,optional as ke,pipe as X,safeParse as Y,string as W,union as _e}from"valibot";var $e=Ce({isolation_level:ke(W()),max_wait:X(x(),G(),J(0)),timeout:X(x(),G(),J(0))});async function Z(n){let{issues:e,output:t,success:r}=Y($e,await n.req.json(),{abortEarly:!0});return r?t:n.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var je=xe({id:_e([W(),x()])});function ee(n,e){let{output:t,success:r}=Y(je,n);return r?t:e.json({EngineMalfunction:{}},500)}var w=new De;w.post("/invalidate",y("header",d),async n=>{let e=await K(n);return e instanceof Response?e:n.body(null)});var Be="/:clientVersion/:schemaHash",S=w.basePath(Be);w.route("/",S);var Le=["/graphql","/itx/:transactionId/graphql"];S.on("POST",[...Le],y("header",d),async n=>{let{req:e}=n;try{let t=await C(n);if(t instanceof Response)return t;let r=await e.text(),o=e.param("transactionId"),s=await t.request(r,{...R(n),"X-transaction-id":o});return n.text(s)}catch(t){return E(t,n)}});S.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],y("header",d),async n=>{let{req:e}=n;try{let t=await C(n);if(t instanceof Response)return t;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),i=await t[o](s,R(n));return n.json(i)}catch(t){return E(t,n)}});S.put("/schema",y("header",d),async n=>{let{req:e}=n,t=await e.text();if(!t)return n.text("Missing schema",400);let r=e.param("schemaHash"),o=P.get(r);if(o==null){if(r!==await O(t))return n.text("Schema hash mismatch",400);let s=new URL(n.get("db").connectionString);s.searchParams.set("single_use_connections","true");let i=await z(t,s);return P.set(r,{base64Original:t,...i}),n.text(r)}return t!==o.base64Original?n.text("Schema mismatch",400):n.text(r)});S.post("/transaction/start",y("header",d),async n=>{let{req:e}=n,t=await Z(n);if(t instanceof Response)return t;try{let r=await C(n);if(r instanceof Response)return r;let o=await r.startTransaction(t,R(n)),s=ee(o,n);if(s instanceof Response)return s;let{id:i}=s,a=e.param("clientVersion"),c=n.get("port"),p=n.get("protocol"),l=e.param("schemaHash");return n.json({...o,"data-proxy":{endpoint:`${p}://localhost:${c}/${a}/${l}/itx/${i}`}})}catch(r){return E(r,n)}});async function C(n){let{req:e}=n,t=F(n);if(t instanceof Response)return t;let{base64Override:r,overrideHash:o}=t.schemas;return await h.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:n.get("debug"),platform:n.get("platform"),schemaHash:o})}import{Hono as qe}from"hono/tiny";import{StatusCodes as Ne}from"http-status-codes";var T=new qe;T.post("/database/dump",async n=>{let e=n.get("db"),t=n.get("serverState");return await e.dump(t.databaseDumpPath),n.json({dumpPath:t.databaseDumpPath},Ne.CREATED)});var Ot=T.get("/health",n=>n.json({name:n.get("serverState").name}));async function re(n,e){let{port:t}=e;if(e.dryRun)return te(t,null);let r=await Fe(t,n,e),{promise:o,reject:s,resolve:i}=b(),a=Ke({createServer:Ve,fetch:r.fetch,overrideGlobalObjects:!1,port:t},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new B(t,"server"));console.error("[Accelerate]",c)}),await o,te(t,a)}function te(n,e){return{async close(){e&&await Promise.allSettled([Ue(e.close.bind(e))(),h.stopAll()])},port:n,url:`http://localhost:${n}`}}async function Fe(n,e,t){let{debug:r}=t,o=new ne,s=await Me.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",Qe((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",e),i.set("debug",!!r),i.set("platform",s),i.set("port",n),i.set("protocol","http"),i.set("serverState",t),await a())),o.route("/",k),o}var k=new ne;k.route("/",w);k.route("/",T);async function zt(n){let e=await L.createExclusively(n),[t,r]=await Promise.all([H("database",e),H("shadow_database",e)]),o=await re(t,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:U({databaseUrl:t.connectionString,shadowDatabaseUrl:r.connectionString})}).toString()}`,i={database:{connectionString:t.connectionString},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:r.connectionString}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,t,r])};async function a(c,p){let m=(await Promise.allSettled(p.map(u=>u.close()))).filter(u=>u.status==="rejected").map(u=>new Error(u.reason));try{await c.close()}catch(u){m.push(u)}if(m.length>0)throw new AggregateError(m,"Failed to close some servers")}}export{ze as DEFAULT_DATABASE_PORT,Ge as DEFAULT_SERVER_PORT,Je as DEFAULT_SHADOW_DATABASE_PORT,B as PortNotAvailableError,zt as unstable_startServer};
6
+ }`,o=t.replace(Ae,r),s=await I(o);return{base64Override:Q.from(o,"utf8").toString("base64"),overrideHash:s}}function T(n){let{req:e}=n;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}import{integer as G,looseObject as Ce,minValue as J,number as x,object as Ie,optional as xe,pipe as X,safeParse as Y,string as W,union as ke}from"valibot";var De=Ie({isolation_level:xe(W()),max_wait:X(x(),G(),J(0)),timeout:X(x(),G(),J(0))});async function Z(n){let{issues:e,output:t,success:r}=Y(De,await n.req.json(),{abortEarly:!0});return r?t:n.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var _e=Ce({id:ke([W(),x()])});function ee(n,e){let{output:t,success:r}=Y(_e,n);return r?t:e.json({EngineMalfunction:{}},500)}var w=new $e;w.post("/invalidate",y("header",d),async n=>{let e=await V(n);return e instanceof Response?e:n.body(null)});var je="/:clientVersion/:schemaHash",S=w.basePath(je);w.route("/",S);var Be=["/graphql","/itx/:transactionId/graphql"];S.on("POST",[...Be],y("header",d),async n=>{let{req:e}=n;try{let t=await k(n);if(t instanceof Response)return t;let r=await e.text(),o=e.param("transactionId"),s=await t.request(r,{...T(n),"X-transaction-id":o});return n.text(s)}catch(t){return P(t,n)}});S.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],y("header",d),async n=>{let{req:e}=n;try{let t=await k(n);if(t instanceof Response)return t;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),i=await t[o](s,T(n));return n.json(i)}catch(t){return P(t,n)}});S.put("/schema",y("header",d),async n=>{let{req:e}=n,t=await e.text();if(!t)return n.text("Missing schema",400);let r=e.param("schemaHash"),o=R.get(r);if(o==null){if(r!==await I(t))return n.text("Schema hash mismatch",400);let s=await z(t,n.get("db").prismaORMConnectionString);return R.set(r,{base64Original:t,...s}),n.text(r)}return t!==o.base64Original?n.text("Schema mismatch",400):n.text(r)});S.post("/transaction/start",y("header",d),async n=>{let{req:e}=n,t=await Z(n);if(t instanceof Response)return t;try{let r=await k(n);if(r instanceof Response)return r;let o=await r.startTransaction(t,T(n)),s=ee(o,n);if(s instanceof Response)return s;let{id:i}=s,a=e.param("clientVersion"),c=n.get("port"),p=n.get("protocol"),l=e.param("schemaHash");return n.json({...o,"data-proxy":{endpoint:`${p}://localhost:${c}/${a}/${l}/itx/${i}`}})}catch(r){return P(r,n)}});async function k(n){let{req:e}=n,t=F(n);if(t instanceof Response)return t;let{base64Override:r,overrideHash:o}=t.schemas;return await h.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:n.get("debug"),platform:n.get("platform"),schemaHash:o})}import{Hono as Le}from"hono/tiny";import{StatusCodes as Me}from"http-status-codes";var O=new Le;O.post("/database/dump",async n=>{let e=n.get("db"),t=n.get("serverState");return await e.dump(t.databaseDumpPath),n.json({dumpPath:t.databaseDumpPath},Me.CREATED)});var At=O.get("/health",n=>n.json({name:n.get("serverState").name}));async function re(n,e){let{port:t}=e;if(e.dryRun)return te(t,null);let r=await Qe(t,n,e),{promise:o,reject:s,resolve:i}=E(),a=Ue({createServer:Ne,fetch:r.fetch,overrideGlobalObjects:!1,port:t},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new B(t,"server"));console.error("[Accelerate]",c)}),await o,te(t,a)}function te(n,e){return{async close(){e&&await Promise.allSettled([qe(e.close.bind(e))(),h.stopAll()])},port:n,url:`http://localhost:${n}`}}async function Qe(n,e,t){let{debug:r}=t,o=new ne,s=await Ve.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",Ke((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",e),i.set("debug",!!r),i.set("platform",s),i.set("port",n),i.set("protocol","http"),i.set("serverState",t),i.set("shadowDBPort",t.shadowDatabasePort),await a())),o.route("/",D),o}var D=new ne;D.route("/",w);D.route("/",O);async function Ft(n){let e=await L.createExclusively(n),[t,r]=await Promise.all([H("database",e),H("shadow_database",e)]),o=await re(t,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:U({databaseUrl:t.prismaORMConnectionString,shadowDatabaseUrl:r.prismaORMConnectionString})}).toString()}`,i={database:{connectionString:t.connectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:r.prismaORMConnectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,t,r])};async function a(c,p){let m=(await Promise.allSettled(p.map(u=>u.close()))).filter(u=>u.status==="rejected").map(u=>new Error(u.reason));try{await c.close()}catch(u){m.push(u)}if(m.length>0)throw new AggregateError(m,"Failed to close some servers")}}export{Fe as DEFAULT_DATABASE_PORT,ze as DEFAULT_SERVER_PORT,Ge as DEFAULT_SHADOW_DATABASE_PORT,B as PortNotAvailableError,Ft as unstable_startServer};
package/dist/state.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var W=Object.create;var v=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf,Z=Object.prototype.hasOwnProperty;var q=(t,e)=>{for(var r in e)v(t,r,{get:e[r],enumerable:!0})},j=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of K(e))!Z.call(t,n)&&n!==r&&v(t,n,{get:()=>e[n],enumerable:!(i=X(e,n))||i.enumerable});return t};var x=(t,e,r)=>(r=t!=null?W(Y(t)):{},j(e||!t||!t.__esModule?v(r,"default",{value:t,enumerable:!0}):r,t)),z=t=>j(v({},"__esModule",{value:!0}),t);var pe={};q(pe,{ServerState:()=>h,ServerStateAlreadyExistsError:()=>S});module.exports=z(pe);var C=require("fs/promises"),J=require("hono/client"),d=require("pathe"),y=require("proper-lockfile"),b=require("std-env"),s=require("valibot");var k=require("fs"),a=require("fs/promises");var o=x(require("path"),1),A=x(require("os"),1),D=x(require("process"),1),p=A.default.homedir(),E=A.default.tmpdir(),{env:f}=D.default,Q=t=>{let e=o.default.join(p,"Library");return{data:o.default.join(e,"Application Support",t),config:o.default.join(e,"Preferences",t),cache:o.default.join(e,"Caches",t),log:o.default.join(e,"Logs",t),temp:o.default.join(E,t)}},ee=t=>{let e=f.APPDATA||o.default.join(p,"AppData","Roaming"),r=f.LOCALAPPDATA||o.default.join(p,"AppData","Local");return{data:o.default.join(r,t,"Data"),config:o.default.join(e,t,"Config"),cache:o.default.join(r,t,"Cache"),log:o.default.join(r,t,"Log"),temp:o.default.join(E,t)}},te=t=>{let e=o.default.basename(p);return{data:o.default.join(f.XDG_DATA_HOME||o.default.join(p,".local","share"),t),config:o.default.join(f.XDG_CONFIG_HOME||o.default.join(p,".config"),t),cache:o.default.join(f.XDG_CACHE_HOME||o.default.join(p,".cache"),t),log:o.default.join(f.XDG_STATE_HOME||o.default.join(p,".local","state"),t),temp:o.default.join(E,e,t)}};function O(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),D.default.platform==="darwin"?Q(t):D.default.platform==="win32"?ee(t):te(t)}var re=require("pako"),se=O("prisma-dev");function g(t){return`${se.data}/${t}`}function M(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function L(t){try{return await(0,a.readFile)(t,{encoding:"utf-8"})}catch(e){if(M(e))return null;throw e}}async function F(t){await(0,a.mkdir)(t,{recursive:!0})}async function I(t){try{return(await(0,a.readdir)(t,{withFileTypes:!0})).reduce((r,i)=>(i.isDirectory()&&!i.name.startsWith(".")&&r.push(i.name),r),[])}catch(e){if(M(e))return[];throw e}}var N=require("std-env");function V(t,e){if(t==null)return!1;try{return N.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var U=(0,s.pipe)((0,s.string)(),(0,s.url)()),B=(0,s.object)({connectionString:U}),H=(0,s.object)({url:U}),_=(0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(1)),ae=(0,s.object)({database:B,http:H,ppg:H,shadowDatabase:B}),ce=(0,s.object)({databasePort:_,exports:(0,s.optional)(ae),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:_,shadowDatabasePort:_,version:(0,s.literal)("1")}),R=Symbol("initialize"),T="default",h=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??T,this.persistenceMode=e.persistenceMode,this.pid=e.pid??b.process.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new P({...e,pid:b.process.pid}):new $(e);return await r[R](),r}static async fromServerDump(e){let{debug:r,name:i=T}=e??{},n=g(i),c=P.getServerDumpPath(n),l=await L(c);if(l==null)return r&&console.debug(`[State] No server dump file found at: ${c}`),null;r&&(console.debug(`[State] server dump file found at "${c}":`),console.debug(l));let{issues:w,output:u,success:m}=(0,s.safeParse)((0,s.pipe)((0,s.string)(),(0,s.parseJson)(),ce),l);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${c}":
2
- ${JSON.stringify(w,null,2)}`),new Error(`Invalid Prisma Dev state for "${i}".`);return new P({databasePort:u.databasePort,debug:r,dryRun:!1,name:i,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},i=(0,d.join)(g(T),"..");r&&console.debug(`[State] scanning for server states in: ${i}`);let n=await I(i);return r&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(c=>ue(c,r)))}},$=class extends h{constructor(e){super({...e,persistenceMode:"stateless",pid:b.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[R](){}async close(){}async writeServerDump(){}},P=class t extends h{#s;#e;#o;#i;#t;#r=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=g(this.name),this.#s=(0,d.join)(this.#e,"db_dump.bak"),this.#o=(0,d.join)(this.#e,".pglite"),this.#t=e.serverDump??null,this.#i=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,d.join)(e,"server.json")}get databaseDumpPath(){return this.#s}get exports(){return this.#t?.exports}get pgliteDataDirPath(){return this.#o}async[R](){await F(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await(0,y.lock)(this.#e,{lockfilePath:(0,d.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new S(this.name):e}}async close(){if(this.#r!=null)try{await this.#r(),this.#r=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#t={name:this.name,version:"1",pid:b.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,C.writeFile)(this.#i,`${JSON.stringify(this.#t,null,2)}
3
- `,{encoding:"utf-8"})}};async function ue(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let i=await h.fromServerDump({debug:e,name:t});if(!i)return e&&console.debug(`[State] no server state found for name: ${t}`),{...r,status:"no_such_server"};r.databasePort=i.databasePort,r.exports=i.exports,r.pid=i.pid,r.port=i.port,r.shadowDatabasePort=i.shadowDatabasePort;let{exports:n,pid:c}=i;if(!V(c,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${c}`),{...r,status:"not_running"};let l=g(t);try{if(!await(0,y.check)(l,{lockfilePath:(0,d.join)(l,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(G){e&&console.error(`[State] server state for "${t}" failed to check lock:`,G)}if(!n)return{...r,status:"starting_up"};let{http:w}=n,u=await(0,J.hc)(w.url).health.$get();if(!u.ok)return e&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(u)}`),{...r,status:"not_running"};let m=await u.json();return m.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(m)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(m)}`),{...r,status:"running"})}catch(i){return e&&console.error(`[State] failed to get server status for "${t}":`,i),{...r,status:"error"}}}var S=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};0&&(module.exports={ServerState,ServerStateAlreadyExistsError});
1
+ "use strict";var W=Object.create;var v=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf,Z=Object.prototype.hasOwnProperty;var q=(t,e)=>{for(var r in e)v(t,r,{get:e[r],enumerable:!0})},k=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of K(e))!Z.call(t,n)&&n!==r&&v(t,n,{get:()=>e[n],enumerable:!(i=X(e,n))||i.enumerable});return t};var x=(t,e,r)=>(r=t!=null?W(Y(t)):{},k(e||!t||!t.__esModule?v(r,"default",{value:t,enumerable:!0}):r,t)),z=t=>k(v({},"__esModule",{value:!0}),t);var pe={};q(pe,{ServerState:()=>h,ServerStateAlreadyExistsError:()=>S});module.exports=z(pe);var J=require("fs/promises"),U=require("hono/client"),d=require("pathe"),y=require("proper-lockfile"),b=require("std-env"),s=require("valibot");var M=require("fs"),a=require("fs/promises");var o=x(require("path"),1),A=x(require("os"),1),D=x(require("process"),1),p=A.default.homedir(),E=A.default.tmpdir(),{env:f}=D.default,Q=t=>{let e=o.default.join(p,"Library");return{data:o.default.join(e,"Application Support",t),config:o.default.join(e,"Preferences",t),cache:o.default.join(e,"Caches",t),log:o.default.join(e,"Logs",t),temp:o.default.join(E,t)}},ee=t=>{let e=f.APPDATA||o.default.join(p,"AppData","Roaming"),r=f.LOCALAPPDATA||o.default.join(p,"AppData","Local");return{data:o.default.join(r,t,"Data"),config:o.default.join(e,t,"Config"),cache:o.default.join(r,t,"Cache"),log:o.default.join(r,t,"Log"),temp:o.default.join(E,t)}},te=t=>{let e=o.default.basename(p);return{data:o.default.join(f.XDG_DATA_HOME||o.default.join(p,".local","share"),t),config:o.default.join(f.XDG_CONFIG_HOME||o.default.join(p,".config"),t),cache:o.default.join(f.XDG_CACHE_HOME||o.default.join(p,".cache"),t),log:o.default.join(f.XDG_STATE_HOME||o.default.join(p,".local","state"),t),temp:o.default.join(E,e,t)}};function O(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),D.default.platform==="darwin"?Q(t):D.default.platform==="win32"?ee(t):te(t)}var re=require("pako"),se=O("prisma-dev");function g(t){return`${se.data}/${t}`}function L(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function F(t){try{return await(0,a.readFile)(t,{encoding:"utf-8"})}catch(e){if(L(e))return null;throw e}}async function I(t){await(0,a.mkdir)(t,{recursive:!0})}async function N(t){try{return(await(0,a.readdir)(t,{withFileTypes:!0})).reduce((r,i)=>(i.isDirectory()&&!i.name.startsWith(".")&&r.push(i.name),r),[])}catch(e){if(L(e))return[];throw e}}var V=require("std-env");function C(t,e){if(t==null)return!1;try{return V.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var $=(0,s.pipe)((0,s.string)(),(0,s.url)()),B=(0,s.object)({connectionString:$,prismaORMConnectionString:(0,s.optional)($),terminalCommand:(0,s.optional)((0,s.string)())}),H=(0,s.object)({url:$}),_=(0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(1)),ae=(0,s.object)({database:B,http:H,ppg:H,shadowDatabase:B}),ce=(0,s.object)({databasePort:_,exports:(0,s.optional)(ae),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:_,shadowDatabasePort:_,version:(0,s.literal)("1")}),j=Symbol("initialize"),T="default",h=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??T,this.persistenceMode=e.persistenceMode,this.pid=e.pid??b.process.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new P({...e,pid:b.process.pid}):new R(e);return await r[j](),r}static async fromServerDump(e){let{debug:r,name:i=T}=e??{},n=g(i),c=P.getServerDumpPath(n),l=await F(c);if(l==null)return r&&console.debug(`[State] No server dump file found at: ${c}`),null;r&&(console.debug(`[State] server dump file found at "${c}":`),console.debug(l));let{issues:w,output:u,success:m}=(0,s.safeParse)((0,s.pipe)((0,s.string)(),(0,s.parseJson)(),ce),l);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${c}":
2
+ ${JSON.stringify(w,null,2)}`),new Error(`Invalid Prisma Dev state for "${i}".`);return new P({databasePort:u.databasePort,debug:r,dryRun:!1,name:i,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},i=(0,d.join)(g(T),"..");r&&console.debug(`[State] scanning for server states in: ${i}`);let n=await N(i);return r&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(c=>ue(c,r)))}},R=class extends h{constructor(e){super({...e,persistenceMode:"stateless",pid:b.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[j](){}async close(){}async writeServerDump(){}},P=class t extends h{#s;#e;#o;#i;#t;#r=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=g(this.name),this.#s=(0,d.join)(this.#e,"db_dump.bak"),this.#o=(0,d.join)(this.#e,".pglite"),this.#t=e.serverDump??null,this.#i=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,d.join)(e,"server.json")}get databaseDumpPath(){return this.#s}get exports(){return this.#t?.exports}get pgliteDataDirPath(){return this.#o}async[j](){await I(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await(0,y.lock)(this.#e,{lockfilePath:(0,d.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new S(this.name):e}}async close(){if(this.#r!=null)try{await this.#r(),this.#r=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#t={name:this.name,version:"1",pid:b.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,J.writeFile)(this.#i,`${JSON.stringify(this.#t,null,2)}
3
+ `,{encoding:"utf-8"})}};async function ue(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let i=await h.fromServerDump({debug:e,name:t});if(!i)return e&&console.debug(`[State] no server state found for name: ${t}`),{...r,status:"no_such_server"};r.databasePort=i.databasePort,r.exports=i.exports,r.pid=i.pid,r.port=i.port,r.shadowDatabasePort=i.shadowDatabasePort;let{exports:n,pid:c}=i;if(!C(c,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${c}`),{...r,status:"not_running"};let l=g(t);try{if(!await(0,y.check)(l,{lockfilePath:(0,d.join)(l,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(G){e&&console.error(`[State] server state for "${t}" failed to check lock:`,G)}if(!n)return{...r,status:"starting_up"};let{http:w}=n,u=await(0,U.hc)(w.url).health.$get();if(!u.ok)return e&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(u)}`),{...r,status:"not_running"};let m=await u.json();return m.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(m)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(m)}`),{...r,status:"running"})}catch(i){return e&&console.error(`[State] failed to get server status for "${t}":`,i),{...r,status:"error"}}}var S=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};0&&(module.exports={ServerState,ServerStateAlreadyExistsError});
package/dist/state.d.cts CHANGED
@@ -1,3 +1,3 @@
1
1
  import 'valibot';
2
- export { E as Exports, f as PersistenceMode, R as ResolvedServerOptions, g as ScanOptions, e as ServerDumpV1, S as ServerOptions, h as ServerState, j as ServerStateAlreadyExistsError, i as ServerStatusV1 } from './db-9fHowc0q.cjs';
2
+ export { E as Exports, f as PersistenceMode, R as ResolvedServerOptions, g as ScanOptions, e as ServerDumpV1, S as ServerOptions, h as ServerState, j as ServerStateAlreadyExistsError, i as ServerStatusV1 } from './db-B1_DGnTu.cjs';
3
3
  import '@electric-sql/pglite';
package/dist/state.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import 'valibot';
2
- export { E as Exports, f as PersistenceMode, R as ResolvedServerOptions, g as ScanOptions, e as ServerDumpV1, S as ServerOptions, h as ServerState, j as ServerStateAlreadyExistsError, i as ServerStatusV1 } from './db-9fHowc0q.js';
2
+ export { E as Exports, f as PersistenceMode, R as ResolvedServerOptions, g as ScanOptions, e as ServerDumpV1, S as ServerOptions, h as ServerState, j as ServerStateAlreadyExistsError, i as ServerStatusV1 } from './db-B1_DGnTu.js';
3
3
  import '@electric-sql/pglite';
package/dist/state.js CHANGED
@@ -1 +1 @@
1
- import{a,b}from"./chunk-GFC5H6VQ.js";import"./chunk-YMJGNP57.js";export{a as ServerState,b as ServerStateAlreadyExistsError};
1
+ import{a,b}from"./chunk-NYMMHKXT.js";import"./chunk-YMJGNP57.js";export{a as ServerState,b as ServerStateAlreadyExistsError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/dev",
3
- "version": "0.0.0-dev.202506060935",
3
+ "version": "0.0.0-dev.202506061849",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -1 +0,0 @@
1
- import{e as l,l as m}from"./chunk-YMJGNP57.js";import{PGlite as g}from"@electric-sql/pglite";import{PGLiteSocketServer as D}from"@electric-sql/pglite-socket";import{pgDump as y}from"@electric-sql/pglite-tools/pg_dump";import{filename as w}from"pathe/utils";var a={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},P=`postgres://${a.username}:${a.password}@localhost`,S=new URLSearchParams({connection_limit:String(a.connectionLimit),connect_timeout:String(a.connectTimeout),max_idle_connection_lifetime:String(a.maxIdleConnectionLifetime),pool_timeout:String(a.poolTimeout),socket_timeout:String(a.socketTimeout),sslmode:a.sslMode});async function k(e,r){let c=e==="database"?r.databasePort:r.shadowDatabasePort;if(r.dryRun)return u(e,r,{db:null,port:c,server:null});let{debug:o}=r,s=await(e==="shadow_database"?p:b)(r.pgliteDataDirPath,o);o&&s.onNotification((t,n)=>{console.debug(`[${e}][${t}] ${n}`)});let d=new D({db:s,debug:o,inspect:o,port:c});o&&(d.addEventListener("listening",t=>{let{detail:n}=t;console.debug(`[${e}] server listening on ${JSON.stringify(n)}`)}),d.addEventListener("connection",t=>{let{clientAddress:n,clientPort:f}=t.detail;console.debug(`[${e}] client connected from ${n}:${f}`)}),d.addEventListener("error",t=>{let{detail:n}=t;console.error(`[${e}] server error:`,n)}));try{await d.start()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="EADDRINUSE"?new m(c,e):t}return u(e,r,{db:s,port:c,server:d})}function u(e,r,c){let{debug:o}=r,{db:i,port:s,server:d}=c||{};return o&&console.debug(`[${e}] server started on port ${s}`),{...a,close:async()=>{let t=[];try{await d?.stop(),o&&console.debug(`[${e}] server stopped on port ${s}`)}catch(n){console.error(`[${e}] server stop error`,n),t.push(n)}if(e==="database")try{await i?.syncToFs(),o&&console.debug(`[${e}] synced to filesystem`)}catch(n){console.error(`[${e}] sync error`,n),t.push(n)}try{await i?.close(),o&&console.debug(`[${e}] closed`)}catch(n){console.error(`[${e}] close error`,n),t.push(n)}if(t.length>0)throw new AggregateError(t,`Failed to close ${e} properly`)},connectionString:v(s),dump:async t=>{e==="shadow_database"||!i||await $({db:i,debug:o,destinationPath:t})},port:s}}function v(e){return`${P}:${e}/${a.database}?${S.toString()}`}async function b(e,r){return await g.create({database:a.database,dataDir:e,debug:r?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:a.username})}async function p(e,r){return await g.create({database:a.database,dataDir:"memory://",debug:r?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:a.username})}async function $(e){let{dataDir:r,db:c,debug:o,destinationPath:i}=e,s=c||await b(r,o),d=await y({args:["--quote-all-identifiers","--schema-only"],fileName:i?w(i):void 0,pg:s});return i?(o&&console.debug(`[DB] Dumping database to ${i}`),await l(d,i)):(o&&console.debug("[DB] Dumping database to memory"),await d.text())}export{k as a,$ as b};