@prisma/dev 0.6.0 → 0.6.1

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