@prisma/dev 0.0.0-dev.202506031951 → 0.0.0-dev.202506032013

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,4 @@
1
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
+ import{mkdir as C,writeFile as K}from"fs/promises";import{join as d}from"pathe";import{lock as Y}from"proper-lockfile";import{process as u}from"std-env";import{integer as R,literal as Z,minLength as q,minValue as _,number as F,object as p,optional as E,parseJson as z,pipe as o,safeParse as G,string as P,url as Q}from"valibot";import{createWriteStream as k,WriteStream as B}from"fs";import{access as N,chmod as V,constants as U,readFile as W,writeFile as j}from"fs/promises";import H from"env-paths";import{inflate as J}from"pako";var f=H("prisma-dev");function ie(t,e){return`${f.cache}/engine/${t}/${e}`}function l(t){return`${f.data}/${t}`}async function oe(t){try{return await N(t,U.F_OK),!0}catch(e){if(v(e))return!1;throw e}}async function ne(t,e){let r=J(t);await j(e,r),await V(e,"755")}async function de(t,e){await t.stream().pipeTo(B.toWeb(k(e,{encoding:"utf-8"})))}function v(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function D(t){try{return await W(t,{encoding:"utf-8"})}catch(e){if(v(e))return null;throw e}}var y=51214,w=51213,A=51215,S=class extends Error{constructor(r,s){super(`Port number \`${r}\` is not available for service ${s}.`);this.port=r;this.service=s}name="PortNotAvailableError"};var M=o(P(),Q()),O=p({connectionString:M}),x=p({url:M}),h=o(F(),R(),_(1)),X=p({database:O,http:x,ppg:x,shadowDatabase:O}),ee=p({databasePort:h,exports:E(X),name:o(P(),q(1)),pid:E(o(F(),R(),_(0))),port:h,shadowDatabasePort:h,version:Z("1")}),g=Symbol("initialize"),T="default",c=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??T,this.persistenceMode=e.persistenceMode,this.pid=e.pid??u.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async create(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new i({...e,pid:u.pid}):new b(e);return await r[g](),r}static async fromServerDump(e){let{debug:r,name:s=T}=e??{},$=l(s),n=i.getServerDumpPath($),m=await D(n);if(m==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(m));let{issues:I,output:a,success:L}=G(o(P(),z(),ee),m);if(!L)throw r&&console.debug(`[State] Invalid server dump file at "${n}":
3
+ ${JSON.stringify(I,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new i({databasePort:a.databasePort,debug:r,dryRun:!1,name:s,pid:a.pid,port:a.port,serverDump:a,shadowDatabasePort:a.shadowDatabasePort})}},b=class extends c{constructor(e){super({...e,persistenceMode:"stateless",pid:u.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[g](){}async close(){}async writeServerDump(){}},i=class t extends c{#s;#e;#a;#i;#t;#r=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=l(this.name),this.#s=d(this.#e,"db_dump.bak"),this.#a=d(this.#e,".pglite"),this.#t=e.serverDump??null,this.#i=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return d(e,"server.json")}get databaseDumpPath(){return this.#s}get pgliteDataDirPath(){return this.#a}async[g](){await C(this.#e,{recursive:!0}),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await Y(this.#e,{lockfilePath:d(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 Error(`A server with the name "${this.name}" is already running. `):e}}async close(){this.#r!=null&&(await this.#r(),this.debug&&console.debug(`[State] released lock on: ${this.#e}`))}async writeServerDump(e){this.#t={name:this.name,version:"1",pid:u.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await K(this.#i,`${JSON.stringify(this.#t,null,2)}
4
+ `,{encoding:"utf-8"})}};export{ie as a,oe as b,ne as c,de as d,y as e,w as f,A as g,S as h,c as i};
@@ -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 '../index-CMQuwyab.js';
3
+ import { S as ServerOptions, a as Server } from '../index-Bi1Nraoi.js';
4
4
  import { MessageBase } from 'sock-daemon/server';
5
5
  import 'valibot';
6
6
 
@@ -98,13 +98,15 @@ declare abstract class ServerState implements ResolvedServerOptions {
98
98
  readonly dryRun: boolean;
99
99
  readonly name: string;
100
100
  readonly persistenceMode: PersistenceMode;
101
+ readonly pid: number | undefined;
101
102
  readonly port: number;
102
103
  readonly shadowDatabasePort: number;
103
104
  protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
104
105
  persistenceMode: PersistenceMode;
106
+ pid: number | undefined;
105
107
  });
106
- static readServerDump(name: string): Promise<ServerDumpV1 | null>;
107
- static get(options: ServerOptions | undefined): Promise<ServerState>;
108
+ static create(options: ServerOptions | undefined): Promise<ServerState>;
109
+ static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<ServerState | null>;
108
110
  abstract get databaseDumpPath(): string;
109
111
  abstract get pgliteDataDirPath(): string;
110
112
  abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { D as DEFAULT_DATABASE_PORT, d as DEFAULT_SERVER_PORT, e as DEFAULT_SHADOW_DATABASE_PORT, f as PortAssignableService, g as PortNotAvailableError, a as Server, u as unstable_startServer } from './index-CMQuwyab.js';
1
+ export { D as DEFAULT_DATABASE_PORT, d as DEFAULT_SERVER_PORT, e as DEFAULT_SHADOW_DATABASE_PORT, f as PortAssignableService, g as PortNotAvailableError, a as Server, u as unstable_startServer } from './index-Bi1Nraoi.js';
2
2
  import 'valibot';
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{a as B,b as L,c as j,d as N,e as rt,f as ot,g as st,h as v,i as U}from"./chunk-PVN7L773.js";import{HTTPException as P}from"hono/http-exception";import{object as ce,optional as le,parseJson as de,pipe as H,regex as q,safeParse as ue,string as I,url as M}from"valibot";var V=/^(postgres|postgresql):\/\//,me=H(I(),de(),ce({databaseUrl:H(I(),M(),q(V)),shadowDatabaseUrl:le(H(I(),M(),q(V)))}));function K(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function pe(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:n,output:r,success:o}=ue(me,t,{abortEarly:!0});return o?[null,r]:[n]}var g=(e,t)=>{let{authorization:n}=e;if(!n)throw new P(401,{message:"Missing API Key"});let[r,o="",s]=n.split(" ");if(r!=="Bearer"||s)throw new P(401,{message:"Invalid API Key"});let[i,a]=pe(o);if(i)throw new P(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c}=a;if(c!==t.var.db.connectionString)throw new P(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{PGlite as ge}from"@electric-sql/pglite";import{PGLiteSocketServer as fe}from"@electric-sql/pglite-socket";import{pgDump as he}from"@electric-sql/pglite-tools/pg_dump";import{filename as ye}from"pathe/utils";var l={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},we=`postgres://${l.username}:${l.password}@localhost`,Se=new URLSearchParams({connection_limit:String(l.connectionLimit),connect_timeout:String(l.connectTimeout),max_idle_connection_lifetime:String(l.maxIdleConnectionLifetime),pool_timeout:String(l.poolTimeout),socket_timeout:String(l.socketTimeout),sslmode:l.sslMode});async function O(e,t){let n=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return Q(e,t,{db:null,port:n,server:null});let{debug:r}=t,o=await ge.create({database:l.database,dataDir:e==="database"?t.pgliteDataDirPath:"memory://",debug:r?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:l.username});r&&o.onNotification((i,a)=>{console.debug(`[${e}][${i}] ${a}`)});let s=new fe({db:o,debug:r,inspect:r,port:n});r&&(s.addEventListener("listening",i=>{let{detail:a}=i;console.debug(`[${e}] server listening on ${JSON.stringify(a)}`)}),s.addEventListener("connection",i=>{let{clientAddress:a,clientPort:c}=i.detail;console.debug(`[${e}] client connected from ${a}:${c}`)}),s.addEventListener("error",i=>{let{detail:a}=i;console.error(`[${e}] server error:`,a)}));try{await s.start()}catch(i){throw i instanceof Error&&"code"in i&&i.code==="EADDRINUSE"?new v(n,e):i}return Q(e,t,{db:o,port:n,server:s})}function Q(e,t,n){let{debug:r}=t,{db:o,port:s,server:i}=n||{};return r&&console.debug(`[${e}] server started on port ${s}`),{...l,close:async()=>{let a=[];try{await i?.stop(),r&&console.debug(`[${e}] server stopped on port ${s}`)}catch(c){console.error(`[${e}] server stop error`,c),a.push(c)}if(e==="database")try{await o?.syncToFs(),r&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),a.push(c)}try{await o?.close(),r&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${e} properly`)},connectionString:be(s),dump:async()=>{if(!o||e==="shadow_database")return{dumpPath:""};let{databaseDumpPath:a}=t,c=await he({args:["--format=custom","--quote-all-identifiers","--schema-only","--verbose"],fileName:ye(a),pg:o});return await N(c,a),{dumpPath:a}},port:s}}function be(e){return`${we}:${e}/${l.database}?${Se.toString()}`}import{createServer as Xe}from"http";import{promisify as We}from"util";import{serve as Ze}from"@hono/node-server";import et from"@prisma/get-platform";function E(){let e,t,n=new Promise((s,i)=>{e=s,t=i}),r=s=>{r=o=null,t(s)},o=s=>{o=r=null,e(s)};return{promise:n,reject:s=>r?.(s),resolve:s=>o?.(s)}}import{logger as tt}from"hono/logger";import{Hono as se}from"hono/tiny";import{Hono as Fe}from"hono/tiny";import{validator as w}from"hono/validator";import{array as ve,literal as Pe,minLength as Ee,object as Te,pipe as Re,safeParse as Ae,string as xe,union as He}from"valibot";var Ie=Te({tags:He([Re(ve(xe()),Ee(1)),Pe("all")])});async function F(e){let{output:t,success:n}=Ae(Ie,await e.req.json(),{abortEarly:!0});return n?t:e.text("Invalid input",400)}import{spawn as Oe}from"child_process";import{once as $e}from"events";import{mkdir as Ce}from"fs/promises";import{join as De}from"path";import{setTimeout as ke}from"timers/promises";import{proxySignals as _e}from"foreground-child/proxy-signals";import{process as Be}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Le,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:je,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:G}=Be.env,h=class e{static#n=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:n}=t,r=`${t.schemaHash}:${t.clientVersion}`;try{let o=e.#n.get(r);if(o)return o;let s=new e(t);return e.#n.set(r,s),n&&console.debug("[Query Engine] starting...",t),await s.start(),n&&console.debug("[Query Engine] started!"),s}finally{e.stopAll(r)}}static async stopAll(t){let r=(await Promise.allSettled(Array.from(e.#n.entries()).filter(([o])=>o!==t).map(async([o,s])=>{try{await s.stop()}finally{e.#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(t,n){return await this.#o(t,n,"commit")}async request(t,n){let{url:r}=await this.start(),o=this.#r(n),s=await fetch(r,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await f.fromResponse(s);return await s.text()}async rollbackTransaction(t,n){return await this.#o(t,n,"rollback")}async startTransaction(t,n){let{url:r}=await this.start(),o=this.#r(n),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(t),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await f.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:n,resolve:r}=E();this.#t=t;let o=je||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Oe(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});_e(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=d=>{let m=d.split(`
2
+ import{a as B,b as L,c as j,d as N,e as rt,f as ot,g as st,h as v,i as U}from"./chunk-IDQVT2IP.js";import{HTTPException as P}from"hono/http-exception";import{object as ce,optional as le,parseJson as de,pipe as H,regex as q,safeParse as ue,string as I,url as M}from"valibot";var V=/^(postgres|postgresql):\/\//,me=H(I(),de(),ce({databaseUrl:H(I(),M(),q(V)),shadowDatabaseUrl:le(H(I(),M(),q(V)))}));function K(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function pe(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:n,output:r,success:o}=ue(me,t,{abortEarly:!0});return o?[null,r]:[n]}var g=(e,t)=>{let{authorization:n}=e;if(!n)throw new P(401,{message:"Missing API Key"});let[r,o="",s]=n.split(" ");if(r!=="Bearer"||s)throw new P(401,{message:"Invalid API Key"});let[i,a]=pe(o);if(i)throw new P(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c}=a;if(c!==t.var.db.connectionString)throw new P(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{PGlite as ge}from"@electric-sql/pglite";import{PGLiteSocketServer as fe}from"@electric-sql/pglite-socket";import{pgDump as he}from"@electric-sql/pglite-tools/pg_dump";import{filename as ye}from"pathe/utils";var l={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},we=`postgres://${l.username}:${l.password}@localhost`,Se=new URLSearchParams({connection_limit:String(l.connectionLimit),connect_timeout:String(l.connectTimeout),max_idle_connection_lifetime:String(l.maxIdleConnectionLifetime),pool_timeout:String(l.poolTimeout),socket_timeout:String(l.socketTimeout),sslmode:l.sslMode});async function O(e,t){let n=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return Q(e,t,{db:null,port:n,server:null});let{debug:r}=t,o=await ge.create({database:l.database,dataDir:e==="database"?t.pgliteDataDirPath:"memory://",debug:r?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:l.username});r&&o.onNotification((i,a)=>{console.debug(`[${e}][${i}] ${a}`)});let s=new fe({db:o,debug:r,inspect:r,port:n});r&&(s.addEventListener("listening",i=>{let{detail:a}=i;console.debug(`[${e}] server listening on ${JSON.stringify(a)}`)}),s.addEventListener("connection",i=>{let{clientAddress:a,clientPort:c}=i.detail;console.debug(`[${e}] client connected from ${a}:${c}`)}),s.addEventListener("error",i=>{let{detail:a}=i;console.error(`[${e}] server error:`,a)}));try{await s.start()}catch(i){throw i instanceof Error&&"code"in i&&i.code==="EADDRINUSE"?new v(n,e):i}return Q(e,t,{db:o,port:n,server:s})}function Q(e,t,n){let{debug:r}=t,{db:o,port:s,server:i}=n||{};return r&&console.debug(`[${e}] server started on port ${s}`),{...l,close:async()=>{let a=[];try{await i?.stop(),r&&console.debug(`[${e}] server stopped on port ${s}`)}catch(c){console.error(`[${e}] server stop error`,c),a.push(c)}if(e==="database")try{await o?.syncToFs(),r&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),a.push(c)}try{await o?.close(),r&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${e} properly`)},connectionString:be(s),dump:async()=>{if(!o||e==="shadow_database")return{dumpPath:""};let{databaseDumpPath:a}=t,c=await he({args:["--format=custom","--quote-all-identifiers","--schema-only","--verbose"],fileName:ye(a),pg:o});return await N(c,a),{dumpPath:a}},port:s}}function be(e){return`${we}:${e}/${l.database}?${Se.toString()}`}import{createServer as Xe}from"http";import{promisify as We}from"util";import{serve as Ze}from"@hono/node-server";import et from"@prisma/get-platform";function E(){let e,t,n=new Promise((s,i)=>{e=s,t=i}),r=s=>{r=o=null,t(s)},o=s=>{o=r=null,e(s)};return{promise:n,reject:s=>r?.(s),resolve:s=>o?.(s)}}import{logger as tt}from"hono/logger";import{Hono as se}from"hono/tiny";import{Hono as Fe}from"hono/tiny";import{validator as w}from"hono/validator";import{array as ve,literal as Pe,minLength as Ee,object as Te,pipe as Re,safeParse as Ae,string as xe,union as He}from"valibot";var Ie=Te({tags:He([Re(ve(xe()),Ee(1)),Pe("all")])});async function F(e){let{output:t,success:n}=Ae(Ie,await e.req.json(),{abortEarly:!0});return n?t:e.text("Invalid input",400)}import{spawn as Oe}from"child_process";import{once as $e}from"events";import{mkdir as Ce}from"fs/promises";import{join as De}from"path";import{setTimeout as ke}from"timers/promises";import{proxySignals as _e}from"foreground-child/proxy-signals";import{process as Be}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Le,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:je,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:G}=Be.env,h=class e{static#n=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:n}=t,r=`${t.schemaHash}:${t.clientVersion}`;try{let o=e.#n.get(r);if(o)return o;let s=new e(t);return e.#n.set(r,s),n&&console.debug("[Query Engine] starting...",t),await s.start(),n&&console.debug("[Query Engine] started!"),s}finally{e.stopAll(r)}}static async stopAll(t){let r=(await Promise.allSettled(Array.from(e.#n.entries()).filter(([o])=>o!==t).map(async([o,s])=>{try{await s.stop()}finally{e.#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(t,n){return await this.#o(t,n,"commit")}async request(t,n){let{url:r}=await this.start(),o=this.#r(n),s=await fetch(r,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await f.fromResponse(s);return await s.text()}async rollbackTransaction(t,n){return await this.#o(t,n,"rollback")}async startTransaction(t,n){let{url:r}=await this.start(),o=this.#r(n),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(t),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await f.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:n,resolve:r}=E();this.#t=t;let o=je||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Oe(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});_e(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=d=>{let m=d.split(`
3
3
  `).find(ae=>ae.includes("Started query engine http server"));if(!m)return;s.stdout.removeListener("data",i);let{fields:p}=JSON.parse(m);if(p==null)return n(new Error(`Unexpected data during initialization, "fields" are missing: ${d}`));let{ip:u,port:_}=p;if(u==null||_==null)return n(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
4
4
  Received data: ${d}`));r({childProcess:s,url:`http://${u}:${_}`})},a=d=>{this.#t=null,n(new y(String(d))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(d,m)=>{this.#t=null,n(new y(`Query Engine exited with code ${d} and signal ${m}`))};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:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await $e(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#i();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let n=B(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",n),await Ce(n,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=De(n,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Le==="1"||await L(s)===!1)&&await this.#a({commitHash:t,extension:o,engineBinaryPath:s}),s}async#i(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let r=(await t.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(t){let{commitHash:n,extension:r,engineBinaryPath:o}=t,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${n}/${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}`);G&&await ke(Number(G)),await j(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",o)}#r(t){let n={};for(let[r,o]of Object.entries(t))o!=null&&(n[r]=o);return n}async#o(t,n,r){let{url:o}=await this.#t,s=this.#r(n),i=await fetch(`${o}/transaction/${t}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await f.fromResponse(i);try{return await i.json()}catch{return{}}}};function T(e,t){return console.error(e),e instanceof y?t.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500):e instanceof f?t.text(e.responseBody,e.statusCode):t.body(null,500)}var y=class extends Error{name="EngineStartError"},f=class e extends Error{constructor(n,r,o){super(`${n}: Query Engine response status ${r}, body: ${o}`);this.action=n;this.statusCode=r;this.responseBody=o}name="EngineHttpError";static async fromResponse(n){let r=new URL(n.url),o=await n.text();return new e(r.pathname,n.status,o)}};import{Buffer as J}from"buffer";var R=new Map;async function $(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function z(e){let t=e.req.param("schemaHash"),n=R.get(t);return n==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:t,schemas:n}}var Ne=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function Y(e,t){let n=J.from(e,"base64").toString("utf8"),r=`datasource db {
5
5
  provider = "postgresql"
6
6
  url = "${t.toString()}"
7
- }`,o=n.replace(Ne,r),s=await $(o);return{base64Override:J.from(o,"utf8").toString("base64"),overrideHash:s}}function A(e){let{req:t}=e;return{traceparent:t.header("traceparent"),"X-capture-telemetry":t.header("X-capture-telemetry")}}import{integer as X,looseObject as Ue,minValue as W,number as C,object as qe,optional as Me,pipe as Z,safeParse as ee,string as te,union as Ve}from"valibot";var Ke=qe({isolation_level:Me(te()),max_wait:Z(C(),X(),W(0)),timeout:Z(C(),X(),W(0))});async function ne(e){let{issues:t,output:n,success:r}=ee(Ke,await e.req.json(),{abortEarly:!0});return r?n:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:t}},400)}var Qe=Ue({id:Ve([te(),C()])});function re(e,t){let{output:n,success:r}=ee(Qe,e);return r?n:t.json({EngineMalfunction:{}},500)}var S=new Fe;S.post("/invalidate",w("header",g),async e=>{let t=await F(e);return t instanceof Response?t:e.body(null)});var Ge="/:clientVersion/:schemaHash",b=S.basePath(Ge);S.route("/",b);var Je=["/graphql","/itx/:transactionId/graphql"];b.on("POST",[...Je],w("header",g),async e=>{let{req:t}=e;try{let n=await D(e);if(n instanceof Response)return n;let r=await t.text(),o=t.param("transactionId"),s=await n.request(r,{...A(e),"X-transaction-id":o});return e.text(s)}catch(n){return T(n,e)}});b.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],w("header",g),async e=>{let{req:t}=e;try{let n=await D(e);if(n instanceof Response)return n;let o=`${t.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=t.param("transactionId"),i=await n[o](s,A(e));return e.json(i)}catch(n){return T(n,e)}});b.put("/schema",w("header",g),async e=>{let{req:t}=e,n=await t.text();if(!n)return e.text("Missing schema",400);let r=t.param("schemaHash"),o=R.get(r);if(o==null){if(r!==await $(n))return e.text("Schema hash mismatch",400);let s=new URL(e.get("db").connectionString);s.searchParams.set("single_use_connections","true");let i=await Y(n,s);return R.set(r,{base64Original:n,...i}),e.text(r)}return n!==o.base64Original?e.text("Schema mismatch",400):e.text(r)});b.post("/transaction/start",w("header",g),async e=>{let{req:t}=e,n=await ne(e);if(n instanceof Response)return n;try{let r=await D(e);if(r instanceof Response)return r;let o=await r.startTransaction(n,A(e)),s=re(o,e);if(s instanceof Response)return s;let{id:i}=s,a=t.param("clientVersion"),c=e.get("port"),d=e.get("protocol"),m=t.param("schemaHash");return e.json({...o,"data-proxy":{endpoint:`${d}://localhost:${c}/${a}/${m}/itx/${i}`}})}catch(r){return T(r,e)}});async function D(e){let{req:t}=e,n=z(e);if(n instanceof Response)return n;let{base64Override:r,overrideHash:o}=n.schemas;return await h.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||t.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:o})}import{Hono as ze}from"hono/tiny";import{StatusCodes as Ye}from"http-status-codes";var x=new ze;x.post("/database/dump",async e=>{let n=await e.get("db").dump();return e.json(n,Ye.CREATED)});x.get("/health",e=>e.json({name:e.get("serverState").name}));async function ie(e,t){let{port:n}=t;if(t.dryRun)return oe(n,null);let r=await nt(n,e,t),{promise:o,reject:s,resolve:i}=E(),a=Ze({createServer:Xe,fetch:r.fetch,overrideGlobalObjects:!1,port:n},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new v(n,"server"));console.error("[Accelerate]",c)}),await o,oe(n,a)}function oe(e,t){return{async close(){t&&await Promise.allSettled([We(t.close.bind(t))(),h.stopAll()])},port:e,url:`http://localhost:${e}`}}async function nt(e,t,n){let{debug:r}=n,o=new se,s=await et.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",tt((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",t),i.set("debug",!!r),i.set("platform",s),i.set("port",e),i.set("protocol","http"),i.set("serverState",n),await a())),o.route("/",k),o}var k=new se;k.route("/",S);k.route("/",x);async function dn(e){let t=await U.get(e),[n,r]=await Promise.all([O("database",t),O("shadow_database",t)]),o=await ie(n,t),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:K({databaseUrl:n.connectionString,shadowDatabaseUrl:r.connectionString})}).toString()}`,i={database:{connectionString:n.connectionString},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:r.connectionString}};return await t.writeServerDump(i),{...i,close:()=>a(t,[o,n,r])};async function a(c,d){let p=(await Promise.allSettled(d.map(u=>u.close()))).filter(u=>u.status==="rejected").map(u=>new Error(u.reason));try{await c.close()}catch(u){p.push(u)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}export{rt as DEFAULT_DATABASE_PORT,ot as DEFAULT_SERVER_PORT,st as DEFAULT_SHADOW_DATABASE_PORT,v as PortNotAvailableError,dn as unstable_startServer};
7
+ }`,o=n.replace(Ne,r),s=await $(o);return{base64Override:J.from(o,"utf8").toString("base64"),overrideHash:s}}function A(e){let{req:t}=e;return{traceparent:t.header("traceparent"),"X-capture-telemetry":t.header("X-capture-telemetry")}}import{integer as X,looseObject as Ue,minValue as W,number as C,object as qe,optional as Me,pipe as Z,safeParse as ee,string as te,union as Ve}from"valibot";var Ke=qe({isolation_level:Me(te()),max_wait:Z(C(),X(),W(0)),timeout:Z(C(),X(),W(0))});async function ne(e){let{issues:t,output:n,success:r}=ee(Ke,await e.req.json(),{abortEarly:!0});return r?n:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:t}},400)}var Qe=Ue({id:Ve([te(),C()])});function re(e,t){let{output:n,success:r}=ee(Qe,e);return r?n:t.json({EngineMalfunction:{}},500)}var S=new Fe;S.post("/invalidate",w("header",g),async e=>{let t=await F(e);return t instanceof Response?t:e.body(null)});var Ge="/:clientVersion/:schemaHash",b=S.basePath(Ge);S.route("/",b);var Je=["/graphql","/itx/:transactionId/graphql"];b.on("POST",[...Je],w("header",g),async e=>{let{req:t}=e;try{let n=await D(e);if(n instanceof Response)return n;let r=await t.text(),o=t.param("transactionId"),s=await n.request(r,{...A(e),"X-transaction-id":o});return e.text(s)}catch(n){return T(n,e)}});b.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],w("header",g),async e=>{let{req:t}=e;try{let n=await D(e);if(n instanceof Response)return n;let o=`${t.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=t.param("transactionId"),i=await n[o](s,A(e));return e.json(i)}catch(n){return T(n,e)}});b.put("/schema",w("header",g),async e=>{let{req:t}=e,n=await t.text();if(!n)return e.text("Missing schema",400);let r=t.param("schemaHash"),o=R.get(r);if(o==null){if(r!==await $(n))return e.text("Schema hash mismatch",400);let s=new URL(e.get("db").connectionString);s.searchParams.set("single_use_connections","true");let i=await Y(n,s);return R.set(r,{base64Original:n,...i}),e.text(r)}return n!==o.base64Original?e.text("Schema mismatch",400):e.text(r)});b.post("/transaction/start",w("header",g),async e=>{let{req:t}=e,n=await ne(e);if(n instanceof Response)return n;try{let r=await D(e);if(r instanceof Response)return r;let o=await r.startTransaction(n,A(e)),s=re(o,e);if(s instanceof Response)return s;let{id:i}=s,a=t.param("clientVersion"),c=e.get("port"),d=e.get("protocol"),m=t.param("schemaHash");return e.json({...o,"data-proxy":{endpoint:`${d}://localhost:${c}/${a}/${m}/itx/${i}`}})}catch(r){return T(r,e)}});async function D(e){let{req:t}=e,n=z(e);if(n instanceof Response)return n;let{base64Override:r,overrideHash:o}=n.schemas;return await h.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||t.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:o})}import{Hono as ze}from"hono/tiny";import{StatusCodes as Ye}from"http-status-codes";var x=new ze;x.post("/database/dump",async e=>{let n=await e.get("db").dump();return e.json(n,Ye.CREATED)});x.get("/health",e=>e.json({name:e.get("serverState").name}));async function ie(e,t){let{port:n}=t;if(t.dryRun)return oe(n,null);let r=await nt(n,e,t),{promise:o,reject:s,resolve:i}=E(),a=Ze({createServer:Xe,fetch:r.fetch,overrideGlobalObjects:!1,port:n},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new v(n,"server"));console.error("[Accelerate]",c)}),await o,oe(n,a)}function oe(e,t){return{async close(){t&&await Promise.allSettled([We(t.close.bind(t))(),h.stopAll()])},port:e,url:`http://localhost:${e}`}}async function nt(e,t,n){let{debug:r}=n,o=new se,s=await et.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",tt((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",t),i.set("debug",!!r),i.set("platform",s),i.set("port",e),i.set("protocol","http"),i.set("serverState",n),await a())),o.route("/",k),o}var k=new se;k.route("/",S);k.route("/",x);async function dn(e){let t=await U.create(e),[n,r]=await Promise.all([O("database",t),O("shadow_database",t)]),o=await ie(n,t),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:K({databaseUrl:n.connectionString,shadowDatabaseUrl:r.connectionString})}).toString()}`,i={database:{connectionString:n.connectionString},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:r.connectionString}};return await t.writeServerDump(i),{...i,close:()=>a(t,[o,n,r])};async function a(c,d){let p=(await Promise.allSettled(d.map(u=>u.close()))).filter(u=>u.status==="rejected").map(u=>new Error(u.reason));try{await c.close()}catch(u){p.push(u)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}export{rt as DEFAULT_DATABASE_PORT,ot as DEFAULT_SERVER_PORT,st as DEFAULT_SHADOW_DATABASE_PORT,v as PortNotAvailableError,dn as unstable_startServer};
package/dist/state.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  import 'valibot';
2
- export { E as Exports, P as PersistenceMode, R as ResolvedServerOptions, b as ServerDumpV1, S as ServerOptions, c as ServerState } from './index-CMQuwyab.js';
2
+ export { E as Exports, P as PersistenceMode, R as ResolvedServerOptions, b as ServerDumpV1, S as ServerOptions, c as ServerState } from './index-Bi1Nraoi.js';
package/dist/state.js CHANGED
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{i as a}from"./chunk-PVN7L773.js";export{a as ServerState};
2
+ import{i as a}from"./chunk-IDQVT2IP.js";export{a as ServerState};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/dev",
3
- "version": "0.0.0-dev.202506031951",
3
+ "version": "0.0.0-dev.202506032013",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,3 +0,0 @@
1
- import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import{mkdir as B,writeFile as V}from"fs/promises";import{join as s}from"pathe";import{lock as N}from"proper-lockfile";import{process as U}from"std-env";import{integer as w,literal as W,minLength as j,minValue as x,number as A,object as n,optional as v,pipe as a,safeParse as H,string as E,url as C}from"valibot";import{createWriteStream as T,WriteStream as _}from"fs";import{access as R,chmod as F,constants as M,readFile as I,writeFile as L}from"fs/promises";import $ from"env-paths";import{inflate as k}from"pako";var m=$("prisma-dev");function G(t,e){return`${m.cache}/engine/${t}/${e}`}function l(t){return`${m.data}/${t}`}async function Q(t){try{return await R(t,M.F_OK),!0}catch(e){if(h(e))return!1;throw e}}async function X(t,e){let r=k(t);await L(e,r),await F(e,"755")}async function ee(t,e){await t.stream().pipeTo(_.toWeb(T(e,{encoding:"utf-8"})))}function h(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function P(t){try{return await I(t,{encoding:"utf-8"})}catch(e){if(h(e))return null;throw e}}var g=51214,f=51213,D=51215,b=class extends Error{constructor(r,c){super(`Port number \`${r}\` is not available for service ${c}.`);this.port=r;this.service=c}name="PortNotAvailableError"};var O=a(E(),C()),y=n({connectionString:O}),S=n({url:O}),u=a(A(),w(),x(1)),J=n({database:y,http:S,ppg:S,shadowDatabase:y}),K=n({databasePort:u,exports:v(J),name:a(E(),j(1)),pid:v(a(A(),w(),x(0))),port:u,shadowDatabasePort:u,version:W("1")}),p=Symbol("initialize"),i=class{databasePort;debug;dryRun;name;persistenceMode;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??"default",this.persistenceMode=e.persistenceMode,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async readServerDump(e){return await new o({name:e}).readServerDump()}static async get(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new o(e):new d(e);return await r[p](),r}},d=class extends i{constructor(e){super({...e,persistenceMode:"stateless"})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[p](){}async close(){}async writeServerDump(){}},o=class extends i{#s;#e;#a;#t;#r=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=l(this.name),this.#s=s(this.#e,"db_dump.bak"),this.#a=s(this.#e,".pglite"),this.#t=s(this.#e,"server.json")}get databaseDumpPath(){return this.#s}get pgliteDataDirPath(){return this.#a}async[p](){await B(this.#e,{recursive:!0}),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await N(this.#e,{lockfilePath:s(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 Error(`A server with the name "${this.name}" is already running. `):e}}async close(){this.#r!=null&&(await this.#r(),this.debug&&console.debug(`[State] released lock on: ${this.#e}`))}async readServerDump(){let e=await P(this.#t);if(e==null)return null;let{output:r,success:c}=H(K,JSON.parse(e));if(!c)throw new Error(`Invalid Prisma Dev state for "${this.name}".`);return r}async writeServerDump(e){await V(this.#t,`${JSON.stringify({name:this.name,version:"1",pid:U.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},null,2)}
3
- `,{encoding:"utf-8"})}};export{G as a,Q as b,X as c,ee as d,g as e,f,D as g,b as h,i};