@prisma/dev 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ import{b as c,f as O,g as $,h as E,i as R,j as _,k}from"./chunk-Q3M6SQC2.js";import{writeFile as j}from"fs/promises";import{hc as B}from"hono/client";import{join as u}from"pathe";import{check as C,lock as H}from"proper-lockfile";import{process as m}from"std-env";import{integer as T,literal as Y,minLength as Z,minValue as V,number as N,object as g,optional as f,parseJson as q,pipe as l,safeParse as z,string as b,url as K}from"valibot";import{process as U}from"std-env";function A(r,e){if(r==null)return!1;try{return U.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}var D=l(b(),K()),M=g({connectionString:D,prismaORMConnectionString:f(D),terminalCommand:f(b())}),I=g({url:D}),P=l(N(),T(),V(1)),W=g({database:M,http:I,ppg:I,shadowDatabase:M}),G=g({databasePort:P,exports:f(W),name:l(b(),Z(1)),pid:f(l(N(),T(),V(0))),port:P,shadowDatabasePort:P,version:Y("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(),q(),G),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=>Q(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 H(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 Q(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 C(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 B(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
+ var e="daemon";export{e as a};
@@ -0,0 +1 @@
1
+ import{createWriteStream as j,WriteStream as P}from"fs";import{access as y,chmod as E,constants as x,mkdir as T,readdir as w,readFile as _,writeFile as v}from"fs/promises";import o from"path";import g from"os";import c from"process";var i=g.homedir(),a=g.tmpdir(),{env:n}=c,m=r=>{let t=o.join(i,"Library");return{data:o.join(t,"Application Support",r),config:o.join(t,"Preferences",r),cache:o.join(t,"Caches",r),log:o.join(t,"Logs",r),temp:o.join(a,r)}},h=r=>{let t=n.APPDATA||o.join(i,"AppData","Roaming"),e=n.LOCALAPPDATA||o.join(i,"AppData","Local");return{data:o.join(e,r,"Data"),config:o.join(t,r,"Config"),cache:o.join(e,r,"Cache"),log:o.join(e,r,"Log"),temp:o.join(a,r)}},D=r=>{let t=o.basename(i);return{data:o.join(n.XDG_DATA_HOME||o.join(i,".local","share"),r),config:o.join(n.XDG_CONFIG_HOME||o.join(i,".config"),r),cache:o.join(n.XDG_CACHE_HOME||o.join(i,".cache"),r),log:o.join(n.XDG_STATE_HOME||o.join(i,".local","state"),r),temp:o.join(a,t,r)}};function p(r,{suffix:t="nodejs"}={}){if(typeof r!="string")throw new TypeError(`Expected a string, got ${typeof r}`);return t&&(r+=`-${t}`),c.platform==="darwin"?m(r):c.platform==="win32"?h(r):D(r)}import{inflate as O}from"pako";var d=p("prisma-dev");function G(r,t){return`${d.cache}/engine/${r}/${t}`}function N(r){return`${d.data}/${r}`}async function W(r){try{return await y(r,x.F_OK),!0}catch(t){if(u(t))return!1;throw t}}async function k(r,t){let e=O(r);await v(t,e),await E(t,"755")}async function M(r,t){await r.stream().pipeTo(P.toWeb(j(t,{encoding:"utf-8"})))}function u(r){return r!=null&&typeof r=="object"&&"code"in r&&r.code==="ENOENT"}async function X(r){try{return await _(r,{encoding:"utf-8"})}catch(t){if(u(t))return null;throw t}}async function U(r){await T(r,{recursive:!0})}async function I(r){try{return(await w(r,{withFileTypes:!0})).reduce((e,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&e.push(s.name),e),[])}catch(t){if(u(t))return[];throw t}}var V=51214,q=51213,z=51215,A=class extends Error{constructor(e,s){super(`Port number \`${e}\` is not available for service ${s}.`);this.port=e;this.service=s}name="PortNotAvailableError"};export{G as a,N as b,W as c,k as d,M as e,X as f,U as g,I as h,V as i,q as j,z as k,A as l};
@@ -0,0 +1 @@
1
+ import{e as l,l as m}from"./chunk-Q3M6SQC2.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 L(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,relaxedDurability:!1,username:n.username})}async function v(e,r){return await b.create({database:n.database,dataDir:"memory://",debug:r?5:void 0,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:["--schema-only"],fileName:s?y(s):void 0,pg:await i.clone()});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{L as a,$ as b};
@@ -1 +1 @@
1
- "use strict";var a=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var R=(s,e)=>{for(var r in e)a(s,r,{get:e[r],enumerable:!0})},g=(s,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of S(e))!u.call(s,t)&&t!==r&&a(s,t,{get:()=>e[t],enumerable:!(n=m(e,t))||n.enumerable});return s};var v=s=>g(a({},"__esModule",{value:!0}),s);var E={};R(E,{MyServiceClient:()=>o});module.exports=v(E);var p=require("sock-daemon/client");var i="daemon";var c={},o=class extends p.SockDaemonClient{static get serviceName(){return i}static get daemonScript(){return new URL("./daemon.js",c.url)}isResponse(e){return super.isMessage(e)}async stopServer(){await super.request({kind:"STOP_SERVER"})}async startServer(e){let{result:r}=await super.request({kind:"START_SERVER",args:e});return r}};0&&(module.exports={MyServiceClient});
1
+ "use strict";var n=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var S=(s,e)=>{for(var r in e)n(s,r,{get:e[r],enumerable:!0})},d=(s,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of c(e))!R.call(s,t)&&t!==r&&n(s,t,{get:()=>e[t],enumerable:!(i=u(e,t))||i.enumerable});return s};var g=s=>d(n({},"__esModule",{value:!0}),s);var v={};S(v,{MyServiceClient:()=>a});module.exports=g(v);var f=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,o=f();var p=require("sock-daemon/client");var m="daemon";var a=class extends p.SockDaemonClient{static get serviceName(){return m}static get daemonScript(){return new URL("./daemon.js",o)}isResponse(e){return super.isMessage(e)}async stopServer(){await super.request({kind:"STOP_SERVER"})}async startServer(e){let{result:r}=await super.request({kind:"START_SERVER",args:e});return r}};0&&(module.exports={MyServiceClient});
@@ -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';
@@ -1 +1 @@
1
- import{a as s}from"../chunk-RJ2352JD.js";import{SockDaemonClient as a}from"sock-daemon/client";var r=class extends a{static get serviceName(){return s}static get daemonScript(){return new URL("./daemon.js",import.meta.url)}isResponse(e){return super.isMessage(e)}async stopServer(){await super.request({kind:"STOP_SERVER"})}async startServer(e){let{result:t}=await super.request({kind:"START_SERVER",args:e});return t}};export{r as MyServiceClient};
1
+ import{a as s}from"../chunk-JXTBAKC4.js";import{SockDaemonClient as a}from"sock-daemon/client";var r=class extends a{static get serviceName(){return s}static get daemonScript(){return new URL("./daemon.js",import.meta.url)}isResponse(e){return super.isMessage(e)}async stopServer(){await super.request({kind:"STOP_SERVER"})}async startServer(e){let{result:t}=await super.request({kind:"START_SERVER",args:e});return t}};export{r as MyServiceClient};
@@ -1 +1 @@
1
- "use strict";var o=require("sock-daemon/server");var r="daemon";var s=class extends o.SockDaemonServer{isRequest(e){return super.isMessage(e)}static get serviceName(){return r}handle(e){return console.error("got request",e),Promise.resolve({id:e.id,kind:e.kind,result:null})}};var t=new s({});t.listen();
1
+ "use strict";var t=require("sock-daemon/server");var o="daemon";var s=class extends t.SockDaemonServer{isRequest(e){return super.isMessage(e)}static get serviceName(){return o}handle(e){return console.error("got request",e),Promise.resolve({id:e.id,kind:e.kind,result:null})}};var n=new s({});n.listen();
@@ -1 +1 @@
1
- import{a as r}from"../chunk-RJ2352JD.js";import{SockDaemonServer as o}from"sock-daemon/server";var s=class extends o{isRequest(e){return super.isMessage(e)}static get serviceName(){return r}handle(e){return console.error("got request",e),Promise.resolve({id:e.id,kind:e.kind,result:null})}};var t=new s({});t.listen();
1
+ import{a as r}from"../chunk-JXTBAKC4.js";import{SockDaemonServer as n}from"sock-daemon/server";var s=class extends n{isRequest(e){return super.isMessage(e)}static get serviceName(){return r}handle(e){return console.error("got request",e),Promise.resolve({id:e.id,kind:e.kind,result:null})}};var i=new s({});i.listen();
@@ -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 $=Object.create;var u=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var _=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty;var E=(e,t)=>{for(var o in t)u(e,o,{get:t[o],enumerable:!0})},b=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of B(t))!A.call(e,i)&&i!==o&&u(e,i,{get:()=>t[i],enumerable:!(r=T(t,i))||r.enumerable});return e};var L=(e,t,o)=>(o=e!=null?$(_(e)):{},b(t||!e||!e.__esModule?u(o,"default",{value:e,enumerable:!0}):o,e)),F=e=>b(u({},"__esModule",{value:!0}),e);var C={};E(C,{dumpDB:()=>h,startDBServer:()=>N});module.exports=F(C);var f=require("@electric-sql/pglite"),P=require("@electric-sql/pglite-socket"),w=require("@electric-sql/pglite-tools/pg_dump"),v=require("pathe/utils");var m=require("fs"),l=require("fs/promises"),p=L(require("env-paths"),1),k=require("pako"),W=(0,p.default)("prisma-dev");async function D(e,t){await e.stream().pipeTo(m.WriteStream.toWeb((0,m.createWriteStream)(t,{encoding:"utf-8"})))}var g=class extends Error{constructor(o,r){super(`Port number \`${o}\` is not available for service ${r}.`);this.port=o;this.service=r}name="PortNotAvailableError"};var s={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},O=`postgres://${s.username}:${s.password}@localhost`,R=new URLSearchParams({connection_limit:String(s.connectionLimit),connect_timeout:String(s.connectTimeout),max_idle_connection_lifetime:String(s.maxIdleConnectionLifetime),pool_timeout:String(s.poolTimeout),socket_timeout:String(s.socketTimeout),sslmode:s.sslMode});async function N(e,t){let o=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return y(e,t,{db:null,port:o,server:null});let{debug:r}=t,c=await(e==="shadow_database"?U:S)(t.pgliteDataDirPath,r);r&&c.onNotification((n,a)=>{console.debug(`[${e}][${n}] ${a}`)});let d=new P.PGLiteSocketServer({db:c,debug:r,inspect:r,port:o});r&&(d.addEventListener("listening",n=>{let{detail:a}=n;console.debug(`[${e}] server listening on ${JSON.stringify(a)}`)}),d.addEventListener("connection",n=>{let{clientAddress:a,clientPort:x}=n.detail;console.debug(`[${e}] client connected from ${a}:${x}`)}),d.addEventListener("error",n=>{let{detail:a}=n;console.error(`[${e}] server error:`,a)}));try{await d.start()}catch(n){throw n instanceof Error&&"code"in n&&n.code==="EADDRINUSE"?new g(o,e):n}return y(e,t,{db:c,port:o,server:d})}function y(e,t,o){let{debug:r}=t,{db:i,port:c,server:d}=o||{};return r&&console.debug(`[${e}] server started on port ${c}`),{...s,close:async()=>{let n=[];try{await d?.stop(),r&&console.debug(`[${e}] server stopped on port ${c}`)}catch(a){console.error(`[${e}] server stop error`,a),n.push(a)}if(e==="database")try{await i?.syncToFs(),r&&console.debug(`[${e}] synced to filesystem`)}catch(a){console.error(`[${e}] sync error`,a),n.push(a)}try{await i?.close(),r&&console.debug(`[${e}] closed`)}catch(a){console.error(`[${e}] close error`,a),n.push(a)}if(n.length>0)throw new AggregateError(n,`Failed to close ${e} properly`)},connectionString:G(c),dump:async n=>{e==="shadow_database"||!i||await h({db:i,debug:r,destinationPath:n})},port:c}}function G(e){return`${O}:${e}/${s.database}?${R.toString()}`}async function S(e,t){return await f.PGlite.create({database:s.database,dataDir:e,debug:t?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:s.username})}async function U(e,t){return await f.PGlite.create({database:s.database,dataDir:"memory://",debug:t?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:s.username})}async function h(e){let{dataDir:t,db:o,debug:r,destinationPath:i}=e,c=o||await S(t,r),d=await(0,w.pgDump)({args:["--quote-all-identifiers","--schema-only"],fileName:i?(0,v.filename)(i):void 0,pg:c});return i?(r&&console.debug(`[DB] Dumping database to ${i}`),await D(d,i)):(r&&console.debug("[DB] Dumping database to memory"),await d.text())}0&&(module.exports={dumpDB,startDBServer});
1
+ "use strict";var j=Object.create;var p=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var k=(e,t)=>{for(var n in t)p(e,n,{get:t[n],enumerable:!0})},A=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of N(t))!G.call(e,s)&&s!==n&&p(e,s,{get:()=>t[s],enumerable:!(i=C(t,s))||i.enumerable});return e};var f=(e,t,n)=>(n=e!=null?j(F(e)):{},A(t||!e||!e.__esModule?p(n,"default",{value:e,enumerable:!0}):n,e)),M=e=>A(p({},"__esModule",{value:!0}),e);var q={};k(q,{dumpDB:()=>L,startDBServer:()=>Q});module.exports=M(q);var v=require("@electric-sql/pglite"),$=require("@electric-sql/pglite-socket"),x=require("pathe/utils");var D=require("fs"),m=require("fs/promises");var r=f(require("path"),1),S=f(require("os"),1),b=f(require("process"),1),u=S.default.homedir(),w=S.default.tmpdir(),{env:g}=b.default,I=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)}},U=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(w,e)}},H=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}`),b.default.platform==="darwin"?I(e):b.default.platform==="win32"?U(e):H(e)}var W=require("pako"),ee=h("prisma-dev");async function _(e,t){await e.stream().pipeTo(D.WriteStream.toWeb((0,D.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"},X=`postgres://${a.username}:${a.password}@localhost`,O=new URLSearchParams({sslmode:a.sslMode}),J=new URLSearchParams({...Object.fromEntries(O.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(e,t,{db:null,port:n,server:null});let{debug:i}=t,d=await(e==="shadow_database"?Y:B)(t.pgliteDataDirPath,i);i&&d.onNotification((o,c)=>{console.debug(`[${e}][${o}] ${c}`)});let l=new $.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:R}=o.detail;console.debug(`[${e}] client connected from ${c}:${R}`)}),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(e,t,{db:d,port:n,server:l})}function E(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,O),dump:async o=>{e==="shadow_database"||!s||await L({db:s,debug:i,destinationPath:o})},port:d,prismaORMConnectionString:T(d,J),terminalCommand:`PGPASSWORD=${a.password} PGSSLMODE=${a.sslMode} psql -h localhost -p ${d} -U ${a.username} -d ${a.database}`}}function T(e,t){return`${X}:${e}/${a.database}?${t.toString()}`}async function B(e,t){return await v.PGlite.create({database:a.database,dataDir:e,debug:t?5:void 0,relaxedDurability:!1,username:a.username})}async function Y(e,t){return await v.PGlite.create({database:a.database,dataDir:"memory://",debug:t?5:void 0,relaxedDurability:!1,username:a.username})}async function L(e){let{dataDir:t,db:n,debug:i,destinationPath:s}=e,d=n||await B(t,i),{pgDump:l}=await import("@electric-sql/pglite-tools/pg_dump"),o=await l({args:["--schema-only"],fileName:s?(0,x.filename)(s):void 0,pg:await d.clone()});return s?(i&&console.debug(`[DB] Dumping database to ${s}`),await _(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-5L5L4BWX.js";import"./chunk-6I7QQZIM.js";export{b as dumpDB,a as startDBServer};
1
+ import{a,b}from"./chunk-U4KQZNBE.js";import"./chunk-Q3M6SQC2.js";export{b as dumpDB,a as startDBServer};
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var et=Object.create;var k=Object.defineProperty;var tt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var nt=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty;var st=(t,e)=>{for(var r in e)k(t,r,{get:e[r],enumerable:!0})},te=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of rt(e))!ot.call(t,o)&&o!==r&&k(t,o,{get:()=>e[o],enumerable:!(n=tt(e,o))||n.enumerable});return t};var re=(t,e,r)=>(r=t!=null?et(nt(t)):{},te(e||!t||!t.__esModule?k(r,"default",{value:t,enumerable:!0}):r,t)),it=t=>te(k({},"__esModule",{value:!0}),t);var Rt={};st(Rt,{DEFAULT_DATABASE_PORT:()=>ge,DEFAULT_SERVER_PORT:()=>he,DEFAULT_SHADOW_DATABASE_PORT:()=>ye,PortNotAvailableError:()=>S,unstable_startServer:()=>Tt});module.exports=it(Rt);var T=require("hono/http-exception"),l=require("valibot"),ne=/^(postgres|postgresql):\/\//,at=(0,l.pipe)((0,l.string)(),(0,l.parseJson)(),(0,l.object)({databaseUrl:(0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(ne)),shadowDatabaseUrl:(0,l.optional)((0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(ne)))}));function oe(t){return Buffer.from(JSON.stringify(t),"utf8").toString("base64url")}function ct(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:n,success:o}=(0,l.safeParse)(at,e,{abortEarly:!0});return o?[null,n]:[r]}var P=(t,e)=>{let{authorization:r}=t;if(!r)throw new T.HTTPException(401,{message:"Missing API Key"});let[n,o="",s]=r.split(" ");if(n!=="Bearer"||s)throw new T.HTTPException(401,{message:"Invalid API Key"});let[i,a]=ct(o);if(i)throw new T.HTTPException(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c}=a;if(c!==e.var.db.connectionString)throw new T.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 V=require("@electric-sql/pglite"),be=require("@electric-sql/pglite-socket"),we=require("@electric-sql/pglite-tools/pg_dump"),ve=require("pathe/utils");var H=require("fs"),f=require("fs/promises"),se=re(require("env-paths"),1),ie=require("pako"),ae=(0,se.default)("prisma-dev");function ce(t,e){return`${ae.cache}/engine/${t}/${e}`}function R(t){return`${ae.data}/${t}`}async function ue(t){try{return await(0,f.access)(t,f.constants.F_OK),!0}catch(e){if(F(e))return!1;throw e}}async function de(t,e){let r=(0,ie.inflate)(t);await(0,f.writeFile)(e,r),await(0,f.chmod)(e,"755")}async function le(t,e){await t.stream().pipeTo(H.WriteStream.toWeb((0,H.createWriteStream)(e,{encoding:"utf-8"})))}function F(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function pe(t){try{return await(0,f.readFile)(t,{encoding:"utf-8"})}catch(e){if(F(e))return null;throw e}}async function me(t){await(0,f.mkdir)(t,{recursive:!0})}async function fe(t){try{return(await(0,f.readdir)(t,{withFileTypes:!0})).reduce((r,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&r.push(n.name),r),[])}catch(e){if(F(e))return[];throw e}}var ge=51214,he=51213,ye=51215,S=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"},ut=`postgres://${g.username}:${g.password}@localhost`,dt=new URLSearchParams({connection_limit:String(g.connectionLimit),connect_timeout:String(g.connectTimeout),max_idle_connection_lifetime:String(g.maxIdleConnectionLifetime),pool_timeout:String(g.poolTimeout),socket_timeout:String(g.socketTimeout),sslmode:g.sslMode});async function U(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Se(t,e,{db:null,port:r,server:null});let{debug:n}=e,s=await(t==="shadow_database"?pt:Pe)(e.pgliteDataDirPath,n);n&&s.onNotification((a,c)=>{console.debug(`[${t}][${a}] ${c}`)});let i=new be.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 S(r,t):a}return Se(t,e,{db:s,port:r,server:i})}function Se(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:lt(s),dump:async a=>{t==="shadow_database"||!o||await mt({db:o,debug:n,destinationPath:a})},port:s}}function lt(t){return`${ut}:${t}/${g.database}?${dt.toString()}`}async function Pe(t,e){return await V.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 V.PGlite.create({database:g.database,dataDir:"memory://",debug:e?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:g.username})}async function mt(t){let{dataDir:e,db:r,debug:n,destinationPath:o}=t,s=r||await Pe(e,n),i=await(0,we.pgDump)({args:["--quote-all-identifiers","--schema-only"],fileName:o?(0,ve.filename)(o):void 0,pg:s});return o?(n&&console.debug(`[DB] Dumping database to ${o}`),await le(i,o)):(n&&console.debug("[DB] Dumping database to memory"),await i.text())}var je=require("http"),Fe=require("util"),Ve=require("@hono/node-server"),Ue=re(require("@prisma/get-platform"),1);function B(){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 qe=require("hono/logger"),J=require("hono/tiny");var Ce=require("hono/tiny"),x=require("hono/validator");var m=require("valibot"),ft=(0,m.object)({tags:(0,m.union)([(0,m.pipe)((0,m.array)((0,m.string)()),(0,m.minLength)(1)),(0,m.literal)("all")])});async function De(t){let{output:e,success:r}=(0,m.safeParse)(ft,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var xe=require("child_process"),Te=require("events"),Re=require("fs/promises"),Ae=require("path"),Oe=require("timers/promises");var $e=require("foreground-child/proxy-signals"),_e=require("std-env");var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:gt,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:ht,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Ee}=_e.process.env,E=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 D.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 D.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:n}=B();this.#t=e;let o=ht||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=(0,xe.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,$e.proxySignals)(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=p=>{let y=p.split(`
2
- `).find(Ze=>Ze.includes("Started query engine http server"));if(!y)return;s.stdout.removeListener("data",i);let{fields:v}=JSON.parse(y);if(v==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${p}`));let{ip:h,port:ee}=v;if(h==null||ee==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://${h}:${ee}`})},a=p=>{this.#t=null,r(new A(String(p))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(p,y)=>{this.#t=null,r(new A(`Query Engine exited with code ${p} and signal ${y}`))};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,Te.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=ce(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,Re.mkdir)(r,{recursive:!0});let{platform:n}=this.#e.platform,o=n==="windows"?".exe":"",s=(0,Ae.join)(r,`query-engine-${n}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(gt==="1"||await ue(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}`);Ee&&await(0,Oe.setTimeout)(Number(Ee)),await de(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 D.fromResponse(i);try{return await i.json()}catch{return{}}}};function C(t,e){return console.error(t),t instanceof A?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof D?e.text(t.responseBody,t.statusCode):e.body(null,500)}var A=class extends Error{name="EngineStartError"},D=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 q=require("buffer"),L=new Map;async function K(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 Ie(t){let e=t.req.param("schemaHash"),r=L.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}var yt=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function ke(t,e){let r=q.Buffer.from(t,"base64").toString("utf8"),n=`datasource db {
1
+ "use strict";var lt=Object.create;var M=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var gt=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var ht=(t,e)=>{for(var r in e)M(t,r,{get:e[r],enumerable:!0})},pe=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of mt(e))!ft.call(t,o)&&o!==r&&M(t,o,{get:()=>e[o],enumerable:!(n=pt(e,o))||n.enumerable});return t};var _=(t,e,r)=>(r=t!=null?lt(gt(t)):{},pe(e||!t||!t.__esModule?M(r,"default",{value:t,enumerable:!0}):r,t)),yt=t=>pe(M({},"__esModule",{value:!0}),t);var Nt={};ht(Nt,{DEFAULT_DATABASE_PORT:()=>Ee,DEFAULT_SERVER_PORT:()=>Ae,DEFAULT_SHADOW_DATABASE_PORT:()=>Re,PortNotAvailableError:()=>D,unstable_startServer:()=>Mt});module.exports=yt(Nt);var v=require("hono/http-exception"),l=require("valibot"),me=/^(postgres|postgresql):\/\//,St=(0,l.pipe)((0,l.string)(),(0,l.parseJson)(),(0,l.object)({databaseUrl:(0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(me)),name:(0,l.optional)((0,l.pipe)((0,l.string)(),(0,l.minLength)(1))),shadowDatabaseUrl:(0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(me))}));function ge(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function bt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:n,success:o}=(0,l.safeParse)(St,e,{abortEarly:!0});return o?[null,n]:[r]}var R=(t,e)=>{let{authorization:r}=t;if(!r)throw new v.HTTPException(401,{message:"Missing API Key"});let[n,o="",s]=r.split(" ");if(n!=="Bearer"||s)throw new v.HTTPException(401,{message:"Invalid API Key"});let[i,a]=bt(o);if(i)throw new v.HTTPException(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c,name:m,shadowDatabaseUrl:b}=a,{name:w}=e.get("serverState");if(!m)throw new v.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${w}" server's output for the updated \`DATABASE_URL\` value.`});if(m!==w)throw new v.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${w}", but the API Key is for "${m}"`});let{hostname:S,port:j}=new URL(c),{port:Q}=e.get("db"),{hostname:ct,port:ut}=new URL(b),dt=e.get("shadowDBPort");if(S!=="localhost"||Number(j)!==Q||ct!=="localhost"||Number(ut)!==dt)throw new v.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 Z=require("@electric-sql/pglite"),xe=require("@electric-sql/pglite-socket"),$e=require("pathe/utils");var F=require("fs"),y=require("fs/promises");var p=_(require("path"),1),W=_(require("os"),1),N=_(require("process"),1),P=W.default.homedir(),z=W.default.tmpdir(),{env:O}=N.default,wt=t=>{let e=p.default.join(P,"Library");return{data:p.default.join(e,"Application Support",t),config:p.default.join(e,"Preferences",t),cache:p.default.join(e,"Caches",t),log:p.default.join(e,"Logs",t),temp:p.default.join(z,t)}},Pt=t=>{let e=O.APPDATA||p.default.join(P,"AppData","Roaming"),r=O.LOCALAPPDATA||p.default.join(P,"AppData","Local");return{data:p.default.join(r,t,"Data"),config:p.default.join(e,t,"Config"),cache:p.default.join(r,t,"Cache"),log:p.default.join(r,t,"Log"),temp:p.default.join(z,t)}},vt=t=>{let e=p.default.basename(P);return{data:p.default.join(O.XDG_DATA_HOME||p.default.join(P,".local","share"),t),config:p.default.join(O.XDG_CONFIG_HOME||p.default.join(P,".config"),t),cache:p.default.join(O.XDG_CACHE_HOME||p.default.join(P,".cache"),t),log:p.default.join(O.XDG_STATE_HOME||p.default.join(P,".local","state"),t),temp:p.default.join(z,e,t)}};function X(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),N.default.platform==="darwin"?wt(t):N.default.platform==="win32"?Pt(t):vt(t)}var fe=require("pako"),he=X("prisma-dev");function ye(t,e){return`${he.cache}/engine/${t}/${e}`}function I(t){return`${he.data}/${t}`}async function Se(t){try{return await(0,y.access)(t,y.constants.F_OK),!0}catch(e){if(Y(e))return!1;throw e}}async function be(t,e){let r=(0,fe.inflate)(t);await(0,y.writeFile)(e,r),await(0,y.chmod)(e,"755")}async function we(t,e){await t.stream().pipeTo(F.WriteStream.toWeb((0,F.createWriteStream)(e,{encoding:"utf-8"})))}function Y(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Pe(t){try{return await(0,y.readFile)(t,{encoding:"utf-8"})}catch(e){if(Y(e))return null;throw e}}async function ve(t){await(0,y.mkdir)(t,{recursive:!0})}async function De(t){try{return(await(0,y.readdir)(t,{withFileTypes:!0})).reduce((r,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&r.push(n.name),r),[])}catch(e){if(Y(e))return[];throw e}}var Ee=51214,Ae=51213,Re=51215,D=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"},Dt=`postgres://${g.username}:${g.password}@localhost`,_e=new URLSearchParams({sslmode:g.sslMode}),Et=new URLSearchParams({...Object.fromEntries(_e.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 ee(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Oe(t,e,{db:null,port:r,server:null});let{debug:n}=e,s=await(t==="shadow_database"?At:Ie)(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 D(r,t):a}return Oe(t,e,{db:s,port:r,server:i})}function Oe(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:Te(s,_e),dump:async a=>{t==="shadow_database"||!o||await Rt({db:o,debug:n,destinationPath:a})},port:s,prismaORMConnectionString:Te(s,Et),terminalCommand:`PGPASSWORD=${g.password} PGSSLMODE=${g.sslMode} psql -h localhost -p ${s} -U ${g.username} -d ${g.database}`}}function Te(t,e){return`${Dt}:${t}/${g.database}?${e.toString()}`}async function Ie(t,e){return await Z.PGlite.create({database:g.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function At(t,e){return await Z.PGlite.create({database:g.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function Rt(t){let{dataDir:e,db:r,debug:n,destinationPath:o}=t,s=r||await Ie(e,n),{pgDump:i}=await import("@electric-sql/pglite-tools/pg_dump"),a=await i({args:["--schema-only"],fileName:o?(0,$e.filename)(o):void 0,pg:await s.clone()});return o?(n&&console.debug(`[DB] Dumping database to ${o}`),await we(a,o)):(n&&console.debug("[DB] Dumping database to memory"),await a.text())}var ze=require("http"),Xe=require("util"),Ye=require("@hono/node-server"),Ze=_(require("@prisma/get-platform"),1);function U(){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 et=require("hono/logger"),oe=require("hono/tiny");var Ke=require("hono/tiny"),$=require("hono/validator");var h=require("valibot"),Ot=(0,h.object)({tags:(0,h.union)([(0,h.pipe)((0,h.array)((0,h.string)()),(0,h.minLength)(1)),(0,h.literal)("all")])});async function Ce(t){let{output:e,success:r}=(0,h.safeParse)(Ot,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var He=require("child_process"),Be=require("events"),Le=require("fs/promises"),je=require("path"),Me=require("timers/promises");var Ne=require("foreground-child/proxy-signals"),Fe=require("std-env");var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Tt,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:xt,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:ke}=Fe.process.env,x=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 T.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 T.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:n}=U();this.#t=e;let o=xt||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=(0,He.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,Ne.proxySignals)(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=m=>{let b=m.split(`
2
+ `).find(Q=>Q.includes("Started query engine http server"));if(!b)return;s.stdout.removeListener("data",i);let{fields:w}=JSON.parse(b);if(w==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${m}`));let{ip:S,port:j}=w;if(S==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: ${m}`));n({childProcess:s,url:`http://${S}:${j}`})},a=m=>{this.#t=null,r(new C(String(m))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(m,b)=>{this.#t=null,r(new C(`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,Be.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=ye(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,Le.mkdir)(r,{recursive:!0});let{platform:n}=this.#e.platform,o=n==="windows"?".exe":"",s=(0,je.join)(r,`query-engine-${n}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Tt==="1"||await Se(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}`);ke&&await(0,Me.setTimeout)(Number(ke)),await be(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 T.fromResponse(i);try{return await i.json()}catch{return{}}}};function V(t,e){return console.error(t),t instanceof C?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof T?e.text(t.responseBody,t.statusCode):e.body(null,500)}var C=class extends Error{name="EngineStartError"},T=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 te=require("buffer"),G=new Map;async function re(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 Ue(t){let e=t.req.param("schemaHash"),r=G.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}var $t=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function Ve(t,e){let r=te.Buffer.from(t,"base64").toString("utf8"),n=`datasource db {
4
4
  provider = "postgresql"
5
5
  url = "${e.toString()}"
6
- }`,o=r.replace(yt,n),s=await K(o);return{base64Override:q.Buffer.from(o,"utf8").toString("base64"),overrideHash:s}}function N(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var d=require("valibot"),St=(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 He(t){let{issues:e,output:r,success:n}=(0,d.safeParse)(St,await t.req.json(),{abortEarly:!0});return n?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var bt=(0,d.looseObject)({id:(0,d.union)([(0,d.string)(),(0,d.number)()])});function Be(t,e){let{output:r,success:n}=(0,d.safeParse)(bt,t);return n?r:e.json({EngineMalfunction:{}},500)}var O=new Ce.Hono;O.post("/invalidate",(0,x.validator)("header",P),async t=>{let e=await De(t);return e instanceof Response?e:t.body(null)});var wt="/:clientVersion/:schemaHash",$=O.basePath(wt);O.route("/",$);var vt=["/graphql","/itx/:transactionId/graphql"];$.on("POST",[...vt],(0,x.validator)("header",P),async t=>{let{req:e}=t;try{let r=await G(t);if(r instanceof Response)return r;let n=await e.text(),o=e.param("transactionId"),s=await r.request(n,{...N(t),"X-transaction-id":o});return t.text(s)}catch(r){return C(r,t)}});$.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,x.validator)("header",P),async t=>{let{req:e}=t;try{let r=await G(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,N(t));return t.json(i)}catch(r){return C(r,t)}});$.put("/schema",(0,x.validator)("header",P),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let n=e.param("schemaHash"),o=L.get(n);if(o==null){if(n!==await K(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 ke(r,s);return L.set(n,{base64Original:r,...i}),t.text(n)}return r!==o.base64Original?t.text("Schema mismatch",400):t.text(n)});$.post("/transaction/start",(0,x.validator)("header",P),async t=>{let{req:e}=t,r=await He(t);if(r instanceof Response)return r;try{let n=await G(t);if(n instanceof Response)return n;let o=await n.startTransaction(r,N(t)),s=Be(o,t);if(s instanceof Response)return s;let{id:i}=s,a=e.param("clientVersion"),c=t.get("port"),p=t.get("protocol"),y=e.param("schemaHash");return t.json({...o,"data-proxy":{endpoint:`${p}://localhost:${c}/${a}/${y}/itx/${i}`}})}catch(n){return C(n,t)}});async function G(t){let{req:e}=t,r=Ie(t);if(r instanceof Response)return r;let{base64Override:n,overrideHash:o}=r.schemas;return await E.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 Le=require("hono/tiny"),Ne=require("http-status-codes"),M=new Le.Hono;M.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},Ne.StatusCodes.CREATED)});var Yt=M.get("/health",t=>t.json({name:t.get("serverState").name}));async function Ke(t,e){let{port:r}=e;if(e.dryRun)return Me(r,null);let n=await Pt(r,t,e),{promise:o,reject:s,resolve:i}=B(),a=(0,Ve.serve)({createServer:je.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 S(r,"server"));console.error("[Accelerate]",c)}),await o,Me(r,a)}function Me(t,e){return{async close(){e&&await Promise.allSettled([(0,Fe.promisify)(e.close.bind(e))(),E.stopAll()])},port:t,url:`http://localhost:${t}`}}async function Pt(t,e,r){let{debug:n}=r,o=new J.Hono,s=await Ue.default.getPlatformInfo();return n&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),n&&o.use("*",(0,qe.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("/",Q),o}var Q=new J.Hono;Q.route("/",O);Q.route("/",M);var We=require("fs/promises"),Ye=require("hono/client"),b=require("pathe"),j=require("proper-lockfile"),I=require("std-env"),u=require("valibot");var Ge=require("std-env");function Je(t,e){if(t==null)return!1;try{return Ge.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var Xe=(0,u.pipe)((0,u.string)(),(0,u.url)()),Qe=(0,u.object)({connectionString:Xe}),ze=(0,u.object)({url:Xe}),z=(0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(1)),Dt=(0,u.object)({database:Qe,http:ze,ppg:ze,shadowDatabase:Qe}),Et=(0,u.object)({databasePort:z,exports:(0,u.optional)(Dt),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:z,shadowDatabasePort:z,version:(0,u.literal)("1")}),Z=Symbol("initialize"),W="default",w=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??W,this.persistenceMode=e.persistenceMode,this.pid=e.pid??I.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 _({...e,pid:I.process.pid}):new Y(e);return await r[Z](),r}static async fromServerDump(e){let{debug:r,name:n=W}=e??{},o=R(n),s=_.getServerDumpPath(o),i=await pe(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)(),Et),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 _({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,b.join)(R(W),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let o=await fe(n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(s=>xt(s,r)))}},Y=class extends w{constructor(e){super({...e,persistenceMode:"stateless",pid:I.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Z](){}async close(){}async writeServerDump(){}},_=class t extends w{#r;#e;#t;#s;#n;#o=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=R(this.name),this.#r=(0,b.join)(this.#e,"db_dump.bak"),this.#t=(0,b.join)(this.#e,".pglite"),this.#n=e.serverDump??null,this.#s=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,b.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get pgliteDataDirPath(){return this.#t}async[Z](){await me(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#o=await(0,j.lock)(this.#e,{lockfilePath:(0,b.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 X(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:I.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,We.writeFile)(this.#s,`${JSON.stringify(this.#n,null,2)}
8
- `,{encoding:"utf-8"})}};async function xt(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let n=await w.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(!Je(s,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${s}`),{...r,status:"not_running"};let i=R(t);try{if(!await(0,j.check)(i,{lockfilePath:(0,b.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(y){e&&console.error(`[State] server state for "${t}" failed to check lock:`,y)}if(!o)return{...r,status:"starting_up"};let{http:a}=o,c=await(0,Ye.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 X=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};async function Tt(t){let e=await w.createExclusively(t),[r,n]=await Promise.all([U("database",e),U("shadow_database",e)]),o=await Ke(r,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:oe({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,p){let v=(await Promise.allSettled(p.map(h=>h.close()))).filter(h=>h.status==="rejected").map(h=>new Error(h.reason));try{await c.close()}catch(h){v.push(h)}if(v.length>0)throw new AggregateError(v,"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($t,n),s=await re(o);return{base64Override:te.Buffer.from(o,"utf8").toString("base64"),overrideHash:s}}function q(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var d=require("valibot"),_t=(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 Ge(t){let{issues:e,output:r,success:n}=(0,d.safeParse)(_t,await t.req.json(),{abortEarly:!0});return n?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var It=(0,d.looseObject)({id:(0,d.union)([(0,d.string)(),(0,d.number)()])});function qe(t,e){let{output:r,success:n}=(0,d.safeParse)(It,t);return n?r:e.json({EngineMalfunction:{}},500)}var k=new Ke.Hono;k.post("/invalidate",(0,$.validator)("header",R),async t=>{let e=await Ce(t);return e instanceof Response?e:t.body(null)});var Ct="/:clientVersion/:schemaHash",H=k.basePath(Ct);k.route("/",H);var kt=["/graphql","/itx/:transactionId/graphql"];H.on("POST",[...kt],(0,$.validator)("header",R),async t=>{let{req:e}=t;try{let r=await ne(t);if(r instanceof Response)return r;let n=await e.text(),o=e.param("transactionId"),s=await r.request(n,{...q(t),"X-transaction-id":o});return t.text(s)}catch(r){return V(r,t)}});H.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,$.validator)("header",R),async t=>{let{req:e}=t;try{let r=await ne(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,q(t));return t.json(i)}catch(r){return V(r,t)}});H.put("/schema",(0,$.validator)("header",R),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let n=e.param("schemaHash"),o=G.get(n);if(o==null){if(n!==await re(r))return t.text("Schema hash mismatch",400);let s=await Ve(r,t.get("db").prismaORMConnectionString);return G.set(n,{base64Original:r,...s}),t.text(n)}return r!==o.base64Original?t.text("Schema mismatch",400):t.text(n)});H.post("/transaction/start",(0,$.validator)("header",R),async t=>{let{req:e}=t,r=await Ge(t);if(r instanceof Response)return r;try{let n=await ne(t);if(n instanceof Response)return n;let o=await n.startTransaction(r,q(t)),s=qe(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 V(n,t)}});async function ne(t){let{req:e}=t,r=Ue(t);if(r instanceof Response)return r;let{base64Override:n,overrideHash:o}=r.schemas;return await x.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 Je=require("hono/tiny"),Qe=require("http-status-codes"),K=new Je.Hono;K.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 Er=K.get("/health",t=>t.json({name:t.get("serverState").name}));async function tt(t,e){let{port:r}=e;if(e.dryRun)return We(r,null);let n=await Ht(r,t,e),{promise:o,reject:s,resolve:i}=U(),a=(0,Ye.serve)({createServer:ze.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 D(r,"server"));console.error("[Accelerate]",c)}),await o,We(r,a)}function We(t,e){return{async close(){e&&await Promise.allSettled([(0,Xe.promisify)(e.close.bind(e))(),x.stopAll()])},port:t,url:`http://localhost:${t}`}}async function Ht(t,e,r){let{debug:n}=r,o=new oe.Hono,s=await Ze.default.getPlatformInfo();return n&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),n&&o.use("*",(0,et.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("/",se),o}var se=new oe.Hono;se.route("/",k);se.route("/",K);var it=require("fs/promises"),at=require("hono/client"),E=require("pathe"),J=require("proper-lockfile"),L=require("std-env"),u=require("valibot");var rt=require("std-env");function nt(t,e){if(t==null)return!1;try{return rt.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var ce=(0,u.pipe)((0,u.string)(),(0,u.url)()),ot=(0,u.object)({connectionString:ce,prismaORMConnectionString:(0,u.optional)(ce),terminalCommand:(0,u.optional)((0,u.string)())}),st=(0,u.object)({url:ce}),ie=(0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(1)),Bt=(0,u.object)({database:ot,http:st,ppg:st,shadowDatabase:ot}),Lt=(0,u.object)({databasePort:ie,exports:(0,u.optional)(Bt),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:ie,shadowDatabasePort:ie,version:(0,u.literal)("1")}),le=Symbol("initialize"),ae="default",A=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??ae,this.persistenceMode=e.persistenceMode,this.pid=e.pid??L.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 B({...e,pid:L.process.pid}):new ue(e);return await r[le](),r}static async fromServerDump(e){let{debug:r,name:n=ae}=e??{},o=I(n),s=B.getServerDumpPath(o),i=await Pe(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)(),Lt),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 B({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,E.join)(I(ae),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let o=await De(n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(s=>jt(s,r)))}},ue=class extends A{constructor(e){super({...e,persistenceMode:"stateless",pid:L.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[le](){}async close(){}async writeServerDump(){}},B=class t extends A{#r;#e;#t;#s;#n;#o=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=I(this.name),this.#r=(0,E.join)(this.#e,"db_dump.bak"),this.#t=(0,E.join)(this.#e,".pglite"),this.#n=e.serverDump??null,this.#s=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,E.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get pgliteDataDirPath(){return this.#t}async[le](){await ve(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#o=await(0,J.lock)(this.#e,{lockfilePath:(0,E.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 de(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:L.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,it.writeFile)(this.#s,`${JSON.stringify(this.#n,null,2)}
8
+ `,{encoding:"utf-8"})}};async function jt(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let n=await A.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(!nt(s,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${s}`),{...r,status:"not_running"};let i=I(t);try{if(!await(0,J.check)(i,{lockfilePath:(0,E.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,at.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 de=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};async function Mt(t){let e=await A.createExclusively(t),[r,n]=await Promise.all([ee("database",e),ee("shadow_database",e)]),o=await tt(r,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:ge({databaseUrl:r.prismaORMConnectionString,name:e.name,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,m){let w=(await Promise.allSettled(m.map(S=>S.close()))).filter(S=>S.status==="rejected").map(S=>new Error(S.reason));try{await c.close()}catch(S){w.push(S)}if(w.length>0)throw new AggregateError(w,"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-5L5L4BWX.js";import{a as L}from"./chunk-BKR4PTFH.js";import{a as $,c as j,d as D,i as ze,j as Ge,k as Je,l as B}from"./chunk-6I7QQZIM.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 k}from"./chunk-U4KQZNBE.js";import{a as q}from"./chunk-4M2BYKUR.js";import{a as B,c as L,d as M,i as Ze,j as et,k as tt,l as N}from"./chunk-Q3M6SQC2.js";import{HTTPException as h}from"hono/http-exception";import{minLength as ue,object as me,optional as le,parseJson as de,pipe as R,regex as K,safeParse as ge,string as T,url as U}from"valibot";var V=/^(postgres|postgresql):\/\//,he=R(T(),de(),me({databaseUrl:R(T(),U(),K(V)),name:le(R(T(),ue(1))),shadowDatabaseUrl:R(T(),U(),K(V))}));function Q(n){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(n).sort(([[e],[t]])=>e.localeCompare(t)))),"utf8").toString("base64url")}function fe(n){let e=Buffer.from(n,"base64url").toString("utf8"),{issues:t,output:r,success:o}=ge(he,e,{abortEarly:!0});return o?[null,r]:[t]}var f=(n,e)=>{let{authorization:t}=n;if(!t)throw new h(401,{message:"Missing API Key"});let[r,o="",s]=t.split(" ");if(r!=="Bearer"||s)throw new h(401,{message:"Invalid API Key"});let[a,i]=fe(o);if(a)throw new h(401,{message:"Invalid API Key",cause:a.join(", ")});let{databaseUrl:p,name:c,shadowDatabaseUrl:g}=i,{name:m}=e.get("serverState");if(!c)throw new h(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${m}" server's output for the updated \`DATABASE_URL\` value.`});if(c!==m)throw new h(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${m}", but the API Key is for "${c}"`});let{hostname:u,port:E}=new URL(p),{port:x}=e.get("db"),{hostname:ie,port:ce}=new URL(g),pe=e.get("shadowDBPort");if(u!=="localhost"||Number(E)!==x||ie!=="localhost"||Number(ce)!==pe)throw new h(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:i}};import{createServer as ze}from"http";import{promisify as Ge}from"util";import{serve as Je}from"@hono/node-server";import We from"@prisma/get-platform";function A(){let n,e,t=new Promise((s,a)=>{n=s,e=a}),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 Xe}from"hono/logger";import{Hono as se}from"hono/tiny";import{Hono as Ke}from"hono/tiny";import{validator as v}from"hono/validator";import{array as ye,literal as we,minLength as Se,object as ve,pipe as be,safeParse as Pe,string as Ee,union as Re}from"valibot";var Te=ve({tags:Re([be(ye(Ee()),Se(1)),we("all")])});async function F(n){let{output:e,success:t}=Pe(Te,await n.req.json(),{abortEarly:!0});return t?e:n.text("Invalid input",400)}import{spawn as Ae}from"child_process";import{once as Oe}from"events";import{mkdir as He}from"fs/promises";import{join as Ce}from"path";import{setTimeout as Ie}from"timers/promises";import{proxySignals as xe}from"foreground-child/proxy-signals";import{process as ke}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:$e,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:De,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:z}=ke.env,w=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 y.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 y.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:t,resolve:r}=A();this.#t=e;let o=De||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Ae(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});xe(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let a=c=>{let g=c.split(`
2
+ `).find(x=>x.includes("Started query engine http server"));if(!g)return;s.stdout.removeListener("data",a);let{fields:m}=JSON.parse(g);if(m==null)return t(new Error(`Unexpected data during initialization, "fields" are missing: ${c}`));let{ip:u,port:E}=m;if(u==null||E==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: ${c}`));r({childProcess:s,url:`http://${u}:${E}`})},i=c=>{this.#t=null,t(new S(String(c))),s.removeListener("exit",p),s.kill()};s.once("error",i);let p=(c,g)=>{this.#t=null,t(new S(`Query Engine exited with code ${c} and signal ${g}`))};return s.once("exit",p),s.stdout.on("data",a),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 Oe(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#a();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let t=B(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await He(t,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=Ce(t,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),($e==="1"||await L(s)===!1)&&await this.#i({commitHash:e,extension:o,engineBinaryPath:s}),s}async#a(){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#i(e){let{commitHash:t,extension:r,engineBinaryPath:o}=e,{binaryTarget:s}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${t}/${s}/query-engine${r}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",a);let i=await fetch(a);if(!i.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${i.status}`);z&&await Ie(Number(z)),await M(await i.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),a=await fetch(`${o}/transaction/${e}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await y.fromResponse(a);try{return await a.json()}catch{return{}}}};function O(n,e){return console.error(n),n instanceof S?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:n.message}}}},500):n instanceof y?e.text(n.responseBody,n.statusCode):e.body(null,500)}var S=class extends Error{name="EngineStartError"},y=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 G}from"buffer";var H=new Map;async function $(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(a=>a.toString(16).padStart(2,"0")).join("")}function J(n){let e=n.req.param("schemaHash"),t=H.get(e);return t==null?n.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:t}}var _e=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function W(n,e){let t=G.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(_e,r),s=await $(o);return{base64Override:G.from(o,"utf8").toString("base64"),overrideHash:s}}function C(n){let{req:e}=n;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}import{integer as X,looseObject as je,minValue as Y,number as D,object as Be,optional as Le,pipe as Z,safeParse as ee,string as te,union as Me}from"valibot";var Ne=Be({isolation_level:Le(te()),max_wait:Z(D(),X(),Y(0)),timeout:Z(D(),X(),Y(0))});async function ne(n){let{issues:e,output:t,success:r}=ee(Ne,await n.req.json(),{abortEarly:!0});return r?t:n.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var qe=je({id:Me([te(),D()])});function re(n,e){let{output:t,success:r}=ee(qe,n);return r?t:e.json({EngineMalfunction:{}},500)}var b=new Ke;b.post("/invalidate",v("header",f),async n=>{let e=await F(n);return e instanceof Response?e:n.body(null)});var Ue="/:clientVersion/:schemaHash",P=b.basePath(Ue);b.route("/",P);var Ve=["/graphql","/itx/:transactionId/graphql"];P.on("POST",[...Ve],v("header",f),async n=>{let{req:e}=n;try{let t=await _(n);if(t instanceof Response)return t;let r=await e.text(),o=e.param("transactionId"),s=await t.request(r,{...C(n),"X-transaction-id":o});return n.text(s)}catch(t){return O(t,n)}});P.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],v("header",f),async n=>{let{req:e}=n;try{let t=await _(n);if(t instanceof Response)return t;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),a=await t[o](s,C(n));return n.json(a)}catch(t){return O(t,n)}});P.put("/schema",v("header",f),async n=>{let{req:e}=n,t=await e.text();if(!t)return n.text("Missing schema",400);let r=e.param("schemaHash"),o=H.get(r);if(o==null){if(r!==await $(t))return n.text("Schema hash mismatch",400);let s=await W(t,n.get("db").prismaORMConnectionString);return H.set(r,{base64Original:t,...s}),n.text(r)}return t!==o.base64Original?n.text("Schema mismatch",400):n.text(r)});P.post("/transaction/start",v("header",f),async n=>{let{req:e}=n,t=await ne(n);if(t instanceof Response)return t;try{let r=await _(n);if(r instanceof Response)return r;let o=await r.startTransaction(t,C(n)),s=re(o,n);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),p=n.get("port"),c=n.get("protocol"),g=e.param("schemaHash");return n.json({...o,"data-proxy":{endpoint:`${c}://localhost:${p}/${i}/${g}/itx/${a}`}})}catch(r){return O(r,n)}});async function _(n){let{req:e}=n,t=J(n);if(t instanceof Response)return t;let{base64Override:r,overrideHash:o}=t.schemas;return await w.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 Fe}from"http-status-codes";var I=new Qe;I.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},Fe.CREATED)});var Ut=I.get("/health",n=>n.json({name:n.get("serverState").name}));async function ae(n,e){let{port:t}=e;if(e.dryRun)return oe(t,null);let r=await Ye(t,n,e),{promise:o,reject:s,resolve:a}=A(),i=Je({createServer:ze,fetch:r.fetch,overrideGlobalObjects:!1,port:t},a);return i.on("error",p=>{if(typeof p=="object"&&"code"in p&&p.code==="EADDRINUSE")return s(new N(t,"server"));console.error("[Accelerate]",p)}),await o,oe(t,i)}function oe(n,e){return{async close(){e&&await Promise.allSettled([Ge(e.close.bind(e))(),w.stopAll()])},port:n,url:`http://localhost:${n}`}}async function Ye(n,e,t){let{debug:r}=t,o=new se,s=await We.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",Xe((...a)=>console.log("[Accelerate]",...a))),o.use("*",async(a,i)=>(a.set("db",e),a.set("debug",!!r),a.set("platform",s),a.set("port",n),a.set("protocol","http"),a.set("serverState",t),a.set("shadowDBPort",t.shadowDatabasePort),await i())),o.route("/",j),o}var j=new se;j.route("/",b);j.route("/",I);async function un(n){let e=await q.createExclusively(n),[t,r]=await Promise.all([k("database",e),k("shadow_database",e)]),o=await ae(t,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:Q({databaseUrl:t.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:r.prismaORMConnectionString})}).toString()}`,a={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(a),{...a,close:()=>i(e,[o,t,r])};async function i(p,c){let m=(await Promise.allSettled(c.map(u=>u.close()))).filter(u=>u.status==="rejected").map(u=>new Error(u.reason));try{await p.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,et as DEFAULT_SERVER_PORT,tt as DEFAULT_SHADOW_DATABASE_PORT,N as PortNotAvailableError,un as unstable_startServer};
package/dist/state.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var B=Object.create;var g=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var H=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty;var j=(t,e)=>{for(var r in e)g(t,r,{get:e[r],enumerable:!0})},x=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of U(e))!W.call(t,a)&&a!==r&&g(t,a,{get:()=>e[a],enumerable:!(o=J(e,a))||o.enumerable});return t};var C=(t,e,r)=>(r=t!=null?B(H(t)):{},x(e||!t||!t.__esModule?g(r,"default",{value:t,enumerable:!0}):r,t)),K=t=>x(g({},"__esModule",{value:!0}),t);var te={};j(te,{ServerState:()=>p,ServerStateAlreadyExistsError:()=>P});module.exports=K(te);var I=require("fs/promises"),L=require("hono/client"),c=require("pathe"),b=require("proper-lockfile"),f=require("std-env"),s=require("valibot");var E=require("fs"),i=require("fs/promises"),O=C(require("env-paths"),1),Y=require("pako"),Z=(0,O.default)("prisma-dev");function m(t){return`${Z.data}/${t}`}function A(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function _(t){try{return await(0,i.readFile)(t,{encoding:"utf-8"})}catch(e){if(A(e))return null;throw e}}async function $(t){await(0,i.mkdir)(t,{recursive:!0})}async function T(t){try{return(await(0,i.readdir)(t,{withFileTypes:!0})).reduce((r,o)=>(o.isDirectory()&&!o.name.startsWith(".")&&r.push(o.name),r),[])}catch(e){if(A(e))return[];throw e}}var R=require("std-env");function k(t,e){if(t==null)return!1;try{return R.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var N=(0,s.pipe)((0,s.string)(),(0,s.url)()),F=(0,s.object)({connectionString:N}),M=(0,s.object)({url:N}),S=(0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(1)),Q=(0,s.object)({database:F,http:M,ppg:M,shadowDatabase:F}),X=(0,s.object)({databasePort:S,exports:(0,s.optional)(Q),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:S,shadowDatabasePort:S,version:(0,s.literal)("1")}),w=Symbol("initialize"),D="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??D,this.persistenceMode=e.persistenceMode,this.pid=e.pid??f.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:f.process.pid}):new y(e);return await r[w](),r}static async fromServerDump(e){let{debug:r,name:o=D}=e??{},a=m(o),n=h.getServerDumpPath(a),d=await _(n);if(d==null)return r&&console.debug(`[State] No server dump file found at: ${n}`),null;r&&(console.debug(`[State] server dump file found at "${n}":`),console.debug(d));let{issues:v,output:u,success:l}=(0,s.safeParse)((0,s.pipe)((0,s.string)(),(0,s.parseJson)(),X),d);if(!l)throw r&&console.debug(`[State] Invalid server dump file at "${n}":
2
- ${JSON.stringify(v,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new h({databasePort:u.databasePort,debug:r,dryRun:!1,name:o,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},o=(0,c.join)(m(D),"..");r&&console.debug(`[State] scanning for server states in: ${o}`);let a=await T(o);return r&&console.debug(`[State] found server names: ${JSON.stringify(a)}`),await Promise.all(a.map(n=>ee(n,r)))}},y=class extends p{constructor(e){super({...e,persistenceMode:"stateless",pid:f.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[w](){}async close(){}async writeServerDump(){}},h=class t extends p{#s;#e;#o;#a;#t;#r=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=m(this.name),this.#s=(0,c.join)(this.#e,"db_dump.bak"),this.#o=(0,c.join)(this.#e,".pglite"),this.#t=e.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,c.join)(e,"server.json")}get databaseDumpPath(){return this.#s}get exports(){return this.#t?.exports}get pgliteDataDirPath(){return this.#o}async[w](){await $(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await(0,b.lock)(this.#e,{lockfilePath:(0,c.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 P(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:f.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,I.writeFile)(this.#a,`${JSON.stringify(this.#t,null,2)}
3
- `,{encoding:"utf-8"})}};async function ee(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let o=await p.fromServerDump({debug:e,name:t});if(!o)return e&&console.debug(`[State] no server state found for name: ${t}`),{...r,status:"no_such_server"};r.databasePort=o.databasePort,r.exports=o.exports,r.pid=o.pid,r.port=o.port,r.shadowDatabasePort=o.shadowDatabasePort;let{exports:a,pid:n}=o;if(!k(n,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${n}`),{...r,status:"not_running"};let d=m(t);try{if(!await(0,b.check)(d,{lockfilePath:(0,c.join)(d,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(V){e&&console.error(`[State] server state for "${t}" failed to check lock:`,V)}if(!a)return{...r,status:"starting_up"};let{http:v}=a,u=await(0,L.hc)(v.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 l=await u.json();return l.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(l)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(l)}`),{...r,status:"running"})}catch(o){return e&&console.error(`[State] failed to get server status for "${t}":`,o),{...r,status:"error"}}}var P=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 X=Object.create;var v=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var z=(t,e)=>{for(var r in e)v(t,r,{get:e[r],enumerable:!0})},M=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Y(e))!q.call(t,n)&&n!==r&&v(t,n,{get:()=>e[n],enumerable:!(i=K(e,n))||i.enumerable});return t};var A=(t,e,r)=>(r=t!=null?X(Z(t)):{},M(e||!t||!t.__esModule?v(r,"default",{value:t,enumerable:!0}):r,t)),Q=t=>M(v({},"__esModule",{value:!0}),t);var de={};z(de,{ServerState:()=>h,ServerStateAlreadyExistsError:()=>y});module.exports=Q(de);var U=require("fs/promises"),G=require("hono/client"),d=require("pathe"),w=require("proper-lockfile"),b=require("std-env"),s=require("valibot");var L=require("fs"),a=require("fs/promises");var o=A(require("path"),1),E=A(require("os"),1),D=A(require("process"),1),p=E.default.homedir(),O=E.default.tmpdir(),{env:f}=D.default,ee=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(O,t)}},te=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(O,t)}},re=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(O,e,t)}};function _(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"?ee(t):D.default.platform==="win32"?te(t):re(t)}var se=require("pako"),oe=_("prisma-dev");function g(t){return`${oe.data}/${t}`}function F(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function I(t){try{return await(0,a.readFile)(t,{encoding:"utf-8"})}catch(e){if(F(e))return null;throw e}}async function N(t){await(0,a.mkdir)(t,{recursive:!0})}async function V(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(F(e))return[];throw e}}var C=require("std-env");function B(t,e){if(t==null)return!1;try{return C.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var R=(0,s.pipe)((0,s.string)(),(0,s.url)()),H=(0,s.object)({connectionString:R,prismaORMConnectionString:(0,s.optional)(R),terminalCommand:(0,s.optional)((0,s.string)())}),J=(0,s.object)({url:R}),T=(0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(1)),ce=(0,s.object)({database:H,http:J,ppg:J,shadowDatabase:H}),ue=(0,s.object)({databasePort:T,exports:(0,s.optional)(ce),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:T,shadowDatabasePort:T,version:(0,s.literal)("1")}),k=Symbol("initialize"),$="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??$,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 j(e);return await r[k](),r}static async fromServerDump(e){let{debug:r,name:i=$}=e??{},n=g(i),c=P.getServerDumpPath(n),l=await I(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:x,output:u,success:m}=(0,s.safeParse)((0,s.pipe)((0,s.string)(),(0,s.parseJson)(),ue),l);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${c}":
2
+ ${JSON.stringify(x,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($),"..");r&&console.debug(`[State] scanning for server states in: ${i}`);let n=await V(i);return r&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(c=>pe(c,r)))}},j=class extends h{constructor(e){super({...e,persistenceMode:"stateless",pid:b.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[k](){}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[k](){await N(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await(0,w.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 y(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,U.writeFile)(this.#i,`${JSON.stringify(this.#t,null,2)}
3
+ `,{encoding:"utf-8"})}};async function pe(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(!B(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,w.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(W){e&&console.error(`[State] server state for "${t}" failed to check lock:`,W)}if(!n)return{...r,status:"starting_up"};let{http:x}=n,u=await(0,G.hc)(x.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 y=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-BKR4PTFH.js";import"./chunk-6I7QQZIM.js";export{a as ServerState,b as ServerStateAlreadyExistsError};
1
+ import{a,b}from"./chunk-4M2BYKUR.js";import"./chunk-Q3M6SQC2.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.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -70,6 +70,7 @@
70
70
  "tsup": "8.5.0",
71
71
  "typescript": "5.8.3",
72
72
  "vitest": "3.1.4",
73
+ "env-paths": "3.0.0",
73
74
  "common-stuff": "^0.0.0"
74
75
  },
75
76
  "dependencies": {
@@ -78,7 +79,6 @@
78
79
  "@electric-sql/pglite-tools": "0.2.7",
79
80
  "@hono/node-server": "1.14.2",
80
81
  "@prisma/get-platform": "6.8.2",
81
- "env-paths": "3.0.0",
82
82
  "foreground-child": "3.3.1",
83
83
  "hono": "4.7.10",
84
84
  "http-status-codes": "2.3.0",
@@ -1 +0,0 @@
1
- import{e as l,l as m}from"./chunk-6I7QQZIM.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};
@@ -1 +0,0 @@
1
- import{createWriteStream as a,WriteStream as c}from"fs";import{access as u,chmod as p,constants as m,mkdir as f,readdir as l,readFile as g,writeFile as d}from"fs/promises";import x from"env-paths";import{inflate as y}from"pako";var o=x("prisma-dev");function D(r,e){return`${o.cache}/engine/${r}/${e}`}function E(r){return`${o.data}/${r}`}async function w(r){try{return await u(r,m.F_OK),!0}catch(e){if(n(e))return!1;throw e}}async function v(r,e){let t=y(r);await d(e,t),await p(e,"755")}async function F(r,e){await r.stream().pipeTo(c.toWeb(a(e,{encoding:"utf-8"})))}function n(r){return r!=null&&typeof r=="object"&&"code"in r&&r.code==="ENOENT"}async function b(r){try{return await g(r,{encoding:"utf-8"})}catch(e){if(n(e))return null;throw e}}async function S(r){await f(r,{recursive:!0})}async function _(r){try{return(await l(r,{withFileTypes:!0})).reduce((t,i)=>(i.isDirectory()&&!i.name.startsWith(".")&&t.push(i.name),t),[])}catch(e){if(n(e))return[];throw e}}var B=51214,R=51213,$=51215,s=class extends Error{constructor(t,i){super(`Port number \`${t}\` is not available for service ${i}.`);this.port=t;this.service=i}name="PortNotAvailableError"};export{D as a,E as b,w as c,v as d,F as e,b as f,S as g,_ as h,B as i,R as j,$ as k,s as l};
@@ -1,3 +0,0 @@
1
- import{b as c,f as w,g as x,h as O,i as $,j as E,k as _}from"./chunk-6I7QQZIM.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 +0,0 @@
1
- var o="daemon";export{o as a};