@prisma/dev 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ import{b as o,d as H,e as m}from"./chunk-354SKE3R.js";import"./chunk-I55EQWKN.js";import{Hono as z}from"hono/tiny";import{validator as c}from"hono/validator";import{array as $,literal as M,minLength as V,object as B,pipe as L,safeParse as k,string as N,union as U}from"valibot";var X=B({tags:U([L($(N()),V(1)),M("all")])});async function v(t){let{output:n,success:e}=k(X,await t.req.json(),{abortEarly:!0});return e?n:t.text("Invalid input",400)}import{Buffer as b}from"buffer";var f=new Map;async function l(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function I(t){let n=t.req.param("schemaHash"),e=f.get(n);return e==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:n,schemas:e}}var D=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function O(t,n){let e=b.from(t,"base64").toString("utf8"),r=`datasource db {
2
+ provider = "postgresql"
3
+ url = "${n.toString()}"
4
+ }`,a=e.replace(D,r),s=await l(a);return{base64Override:b.from(a,"utf8").toString("base64"),overrideHash:s}}function d(t){let{req:n}=t;return{traceparent:n.header("traceparent"),"X-capture-telemetry":n.header("X-capture-telemetry")}}import{integer as w,looseObject as F,minValue as R,number as g,object as Y,optional as G,pipe as T,safeParse as E,string as C,union as K}from"valibot";var Q=Y({isolation_level:G(C()),max_wait:T(g(),w(),R(0)),timeout:T(g(),w(),R(0))});async function A(t){let{issues:n,output:e,success:r}=E(Q,await t.req.json(),{abortEarly:!0});return r?e:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:n}},400)}var W=F({id:K([C(),g()])});function x(t,n){let{output:e,success:r}=E(W,t);return r?e:n.json({EngineMalfunction:{}},500)}var S=new z;S.post("/invalidate",c("header",o),async t=>{let n=await v(t);return n instanceof Response?n:t.body(null)});var J="/:clientVersion/:schemaHash",p=S.basePath(J);S.route("/",p);var Z=["/graphql","/itx/:transactionId/graphql"];p.on("POST",[...Z],c("header",o),async t=>{let{req:n}=t;try{let e=await y(t);if(e instanceof Response)return e;let r=await n.text(),a=n.param("transactionId"),s=await e.request(r,{...d(t),"X-transaction-id":a});return t.text(s)}catch(e){return m(e,t)}});p.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],c("header",o),async t=>{let{req:n}=t;try{let e=await y(t);if(e instanceof Response)return e;let a=`${n.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=n.param("transactionId"),i=await e[a](s,d(t));return t.json(i)}catch(e){return m(e,t)}});p.put("/schema",c("header",o),async t=>{let{req:n}=t,e=await n.text();if(!e)return t.text("Missing schema",400);let r=n.param("schemaHash"),a=f.get(r);if(a==null){if(r!==await l(e))return t.text("Schema hash mismatch",400);let s=await O(e,t.get("db").prismaORMConnectionString);return f.set(r,{base64Original:e,...s}),t.text(r)}return e!==a.base64Original?t.text("Schema mismatch",400):t.text(r)});p.post("/transaction/start",c("header",o),async t=>{let{req:n}=t,e=await A(t);if(e instanceof Response)return e;try{let r=await y(t);if(r instanceof Response)return r;let a=await r.startTransaction(e,d(t)),s=x(a,t);if(s instanceof Response)return s;let{id:i}=s,P=n.param("clientVersion"),q=t.get("port"),_=t.get("protocol"),j=n.param("schemaHash");return t.json({...a,"data-proxy":{endpoint:`${_}://localhost:${q}/${P}/${j}/itx/${i}`}})}catch(r){return m(r,t)}});async function y(t){let{req:n}=t,e=I(t);if(e instanceof Response)return e;let{base64Override:r,overrideHash:a}=e.schemas;return await H.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||n.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:a})}export{S as accelerateRoute};
@@ -0,0 +1,3 @@
1
+ import{a as P,c as v,d as b}from"./chunk-I55EQWKN.js";import{minLength as D,object as j,optional as B,parseJson as K,pipe as y,regex as R,safeParse as L,string as w,url as S}from"valibot";var A=/^(postgres|postgresql):\/\//,_=y(w(),K(),j({databaseUrl:y(w(),S(),R(A)),name:B(y(w(),D(1))),shadowDatabaseUrl:y(w(),S(),R(A))}));function W(r){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(r).sort(([[e],[n]])=>e.localeCompare(n)))),"utf8").toString("base64url")}function N(r){let e=Buffer.from(r,"base64url").toString("utf8"),{issues:n,output:s,success:t}=L(_,e,{abortEarly:!0});return t?[null,s]:[n]}var Y=async(r,e)=>{let{authorization:n}=r,{HTTPException:s}=await import("hono/http-exception");if(!n)throw new s(401,{message:"Missing API Key"});let[t,o="",i]=n.split(" ");if(t!=="Bearer"||i)throw new s(401,{message:"Invalid API Key"});let[a,p]=N(o);if(a)throw new s(401,{message:"Invalid API Key",cause:a.join(", ")});let{databaseUrl:m,name:c,shadowDatabaseUrl:l}=p,{name:d}=e.get("serverState");if(!c)throw new s(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${d}" server's output for the updated \`DATABASE_URL\` value.`});if(c!==d)throw new s(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${d}", but the API Key is for "${c}"`});let{hostname:h,port:f}=new URL(m),{port:E}=e.get("db"),{hostname:$,port:C}=new URL(l),H=e.get("shadowDBPort");if(h!=="localhost"||Number(f)!==E||$!=="localhost"||Number(C)!==H)throw new s(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:p}};import{spawn as Q}from"child_process";import{once as F}from"events";import{mkdir as U}from"fs/promises";import{join as V}from"path";import{setTimeout as z}from"timers/promises";function O(r){let e,n,s=new Promise((i,a)=>{e=i,n=a}),t=i=>{t=o=null,n(i),r?.onRejected?.(i),r?.onFulfilled?.()},o=i=>{o=t=null,e(i),r?.onResolved?.(i),r?.onFulfilled?.()};return{isFulfilled:()=>o===t,promise:s,reject:i=>t?.(i),resolve:i=>o?.(i)}}import{process as M}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:q,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:J,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:I}=M.env,x=class r{static#t=new Map;#e;#n;constructor(e){this.#e=e,this.#n=null}static async get(e){let{debug:n}=e,s=`${e.schemaHash}:${e.clientVersion}`;try{let t=r.#t.get(s);if(t)return t;let o=new r(e);return r.#t.set(s,o),n&&console.debug("[Query Engine] starting...",e),await o.start(),n&&console.debug("[Query Engine] started!"),o}finally{r.stopAll(s)}}static async stopAll(e){let s=(await Promise.allSettled(Array.from(r.#t.entries()).filter(([t])=>t!==e).map(async([t,o])=>{try{await o.stop()}finally{r.#t.delete(t)}}))).filter(t=>t.status==="rejected").map(t=>t.reason);if(s.length>0)throw new AggregateError(s,"Failed to stop engines")}async commitTransaction(e,n){return await this.#i(e,n,"commit")}async request(e,n){let{url:s}=await this.start(),t=this.#s(n),o=await fetch(s,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...t,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await u.fromResponse(o);return await o.text()}async rollbackTransaction(e,n){return await this.#i(e,n,"rollback")}async startTransaction(e,n){let{url:s}=await this.start(),t=this.#s(n),o=await fetch(`${s}/transaction/start`,{body:JSON.stringify(e),headers:{...t,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await u.fromResponse(o);return await o.json()}async start(){if(this.#n!=null)return await this.#n;let{promise:e,reject:n,resolve:s}=O();this.#n=e;let t=J||await this.#o();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",t);let{proxySignals:o}=await import("foreground-child/proxy-signals"),i=Q(t,["--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});o(i),i.stderr.setEncoding("utf8"),i.stdout.setEncoding("utf8");let a=c=>{let l=c.split(`
2
+ `).find(E=>E.includes("Started query engine http server"));if(!l)return;i.stdout.removeListener("data",a);let{fields:d}=JSON.parse(l);if(d==null)return n(new Error(`Unexpected data during initialization, "fields" are missing: ${c}`));let{ip:h,port:f}=d;if(h==null||f==null)return n(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
+ Received data: ${c}`));s({childProcess:i,url:`http://${h}:${f}`})},p=c=>{this.#n=null,n(new g(String(c))),i.removeListener("exit",m),i.kill()};i.once("error",p);let m=(c,l)=>{this.#n=null,n(new g(`Query Engine exited with code ${c} and signal ${l}`))};return i.once("exit",m),i.stdout.on("data",a),this.#e.debug&&(i.stderr.on("data",console.error.bind(console,"[Query Engine]")),i.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#n}async stop(){if(this.#n==null)return;let{childProcess:e}=await this.#n;e.exitCode==null&&e.signalCode==null&&(this.#n=null,e.kill(),await F(e,"exit"))}async#o(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#r();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let n=P(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",n),await U(n,{recursive:!0});let{platform:s}=this.#e.platform,t=s==="windows"?".exe":"",o=V(n,`query-engine-${s}${t}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(q==="1"||await v(o)===!1)&&await this.#a({commitHash:e,extension:t,engineBinaryPath:o}),o}async#r(){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 s=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!s)throw new Error("Couldn't find engines version in package.json");let t=s.split(".").at(-1);if(!t)throw new Error("Couldn't find commit hash in engines version");return t}async#a(e){let{commitHash:n,extension:s,engineBinaryPath:t}=e,{binaryTarget:o}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${n}/${o}/query-engine${s}.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}`);I&&await z(Number(I)),await b(await a.arrayBuffer(),t),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",t)}#s(e){let n={};for(let[s,t]of Object.entries(e))t!=null&&(n[s]=t);return n}async#i(e,n,s){let{url:t}=await this.#n,o=this.#s(n),i=await fetch(`${t}/transaction/${e}/${s}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await u.fromResponse(i);try{return await i.json()}catch{return{}}}};function de(r,e){return console.error(r),r instanceof g?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:r.message}}}},500):r instanceof u?e.text(r.responseBody,r.statusCode):e.body(null,500)}var g=class extends Error{name="EngineStartError"},u=class r extends Error{constructor(n,s,t){super(`${n}: Query Engine response status ${s}, body: ${t}`);this.action=n;this.statusCode=s;this.responseBody=t}name="EngineHttpError";static async fromResponse(n){let s=new URL(n.url),t=await n.text();return new r(s.pathname,n.status,t)}};export{W as a,Y as b,O as c,x as d,de as e};
@@ -0,0 +1 @@
1
+ import{f as u}from"./chunk-LMPFMHCB.js";import{e as m}from"./chunk-I55EQWKN.js";import{filename as D}from"pathe/utils";var n={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},P=`postgres://${n.username}:${n.password}@localhost`,S=new URLSearchParams({sslmode:n.sslMode}),w=new URLSearchParams({...Object.fromEntries(S.entries()),connection_limit:String(n.connectionLimit),connect_timeout:String(n.connectTimeout),max_idle_connection_lifetime:String(n.maxIdleConnectionLifetime),pool_timeout:String(n.poolTimeout),single_use_connections:"true",socket_timeout:String(n.socketTimeout)});async function L(e,o){let i=e==="database"?o.databasePort:o.shadowDatabasePort;if(o.dryRun)return g(e,o,{db:null,port:i,server:null});let{debug:a}=o,s=await(e==="shadow_database"?y:f)(o.pgliteDataDirPath,a);a&&s.onNotification((t,d)=>{console.debug(`[${e}][${t}] ${d}`)});let{PGLiteSocketServer:l}=await import("@electric-sql/pglite-socket"),r=new l({db:s,debug:a,inspect:a,port:i});a&&(r.addEventListener("listening",t=>{let{detail:d}=t;console.debug(`[${e}] server listening on ${JSON.stringify(d)}`)}),r.addEventListener("connection",t=>{let{clientAddress:d,clientPort:p}=t.detail;console.debug(`[${e}] client connected from ${d}:${p}`)}),r.addEventListener("error",t=>{let{detail:d}=t;console.error(`[${e}] server error:`,d)}));try{await r.start()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="EADDRINUSE"?new u(i):t}return g(e,o,{db:s,port:i,server:r})}function g(e,o,i){let{debug:a}=o,{db:c,port:s,server:l}=i||{};return a&&console.debug(`[${e}] server started on port ${s}`),{...n,close:async()=>{let r=[];try{await l?.stop(),a&&console.debug(`[${e}] server stopped on port ${s}`)}catch(t){console.error(`[${e}] server stop error`,t),r.push(t)}if(e==="database")try{await c?.syncToFs(),a&&console.debug(`[${e}] synced to filesystem`)}catch(t){console.error(`[${e}] sync error`,t),r.push(t)}try{await c?.close(),a&&console.debug(`[${e}] closed`)}catch(t){console.error(`[${e}] close error`,t),r.push(t)}if(r.length>0)throw new AggregateError(r,`Failed to close ${e} properly`)},connectionString:b(s,S),dump:async r=>{e==="shadow_database"||!c||await v({db:c,debug:a,destinationPath:r})},port:s,prismaORMConnectionString:b(s,w),terminalCommand:`PGPASSWORD=${n.password} PGSSLMODE=${n.sslMode} psql -h localhost -p ${s} -U ${n.username} -d ${n.database}`}}function b(e,o){return`${P}:${e}/${n.database}?${o.toString()}`}async function f(e,o){let{PGlite:i}=await import("@electric-sql/pglite");return await i.create({database:n.database,dataDir:e,debug:o?5:void 0,relaxedDurability:!1,username:n.username})}async function y(e,o){let{PGlite:i}=await import("@electric-sql/pglite");return await i.create({database:n.database,dataDir:"memory://",debug:o?5:void 0,relaxedDurability:!1,username:n.username})}async function v(e){let{dataDir:o,db:i,debug:a,destinationPath:c}=e,s=i||await f(o,a),{pgDump:l}=await import("@electric-sql/pglite-tools/pg_dump"),r=await l({args:["--schema-only","--no-owner"],fileName:c?D(c):void 0,pg:await s.clone()});return c?(a&&console.debug(`[DB] Dumping database to ${c}`),await m(r,c)):(a&&console.debug("[DB] Dumping database to memory"),await r.text())}export{L as a,v as b};
@@ -0,0 +1 @@
1
+ import{createWriteStream as y,WriteStream as w}from"fs";import{access as A,chmod as D,constants as x,mkdir as P,readdir as E,readFile as T,writeFile as _}from"fs/promises";import{promisify as F}from"util";import{unzip as O}from"zlib";import o from"path";import f from"os";import c from"process";var n=f.homedir(),a=f.tmpdir(),{env:e}=c,m=t=>{let r=o.join(n,"Library");return{data:o.join(r,"Application Support",t),config:o.join(r,"Preferences",t),cache:o.join(r,"Caches",t),log:o.join(r,"Logs",t),temp:o.join(a,t)}},h=t=>{let r=e.APPDATA||o.join(n,"AppData","Roaming"),i=e.LOCALAPPDATA||o.join(n,"AppData","Local");return{data:o.join(i,t,"Data"),config:o.join(r,t,"Config"),cache:o.join(i,t,"Cache"),log:o.join(i,t,"Log"),temp:o.join(a,t)}},j=t=>{let r=o.basename(n);return{data:o.join(e.XDG_DATA_HOME||o.join(n,".local","share"),t),config:o.join(e.XDG_CONFIG_HOME||o.join(n,".config"),t),cache:o.join(e.XDG_CACHE_HOME||o.join(n,".cache"),t),log:o.join(e.XDG_STATE_HOME||o.join(n,".local","state"),t),temp:o.join(a,r,t)}};function p(t,{suffix:r="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return r&&(t+=`-${r}`),c.platform==="darwin"?m(t):c.platform==="win32"?h(t):j(t)}var g=p("prisma-dev"),L=F(O);function W(t,r){return`${g.cache}/engine/${t}/${r}`}function X(t){return`${g.data}/${t}`}async function B(t){try{return await A(t,x.F_OK),!0}catch(r){if(u(r))return!1;throw r}}async function R(t,r){let i=await L(t);await _(r,i),await D(r,"755")}async function z(t,r){await t.stream().pipeTo(w.toWeb(y(r,{encoding:"utf-8"})))}function u(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function I(t){try{return await T(t,{encoding:"utf-8"})}catch(r){if(u(r))return null;throw r}}async function J(t){await P(t,{recursive:!0})}async function K(t){try{return(await E(t,{withFileTypes:!0})).reduce((i,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&i.push(s.name),i),[])}catch(r){if(u(r))return[];throw r}}export{W as a,X as b,B as c,R as d,z as e,I as f,J as g,K as h};
@@ -0,0 +1 @@
1
+ import{checkPort as w,getPort as m,isUnsafePort as O}from"get-port-please";import{difference as T,range as $}from"remeda";var v=51214,h=51213,S=51215,p=65535,P=-1/0;async function E(s){let{debug:t,name:e,requestedPorts:n,servers:u}=s,{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:a}=x(e,u);t&&(console.debug(`ports used by other servers: ${Object.keys(r).join(", ")}`),console.debug(`ports used by "${e}" server last time: ${JSON.stringify(a)}`));let i={databasePort:P,port:P,shadowDatabasePort:P},o=["port","databasePort","shadowDatabasePort"];for(let c of o){let d=await k({debug:t,portKey:c,portsUsedByOtherServers:r,portsUsedByThisServerLastTime:a,requestedPorts:n})??await U({debug:t,pickedPorts:i,portKey:c,portsUsedByOtherServers:r,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${c}": ${d}`),i[c]=d}return t&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function k(s){let{debug:t,portKey:e,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:u,requestedPorts:r}=s,{[e]:a,...i}=r;if(g(a))return await B({debug:t,otherRequestedPorts:i,portKey:e,portsUsedByOtherServers:n,requestedPort:a}),a;let o=u?.[e]??P;if(!g(o))return t&&console.debug(`No port specified for "${e}". Trying to pick a new port.`),null;let c=o in n;return c||Object.values(i).includes(o)?(t&&console.debug(`Port ${o} that was used last time for this server, ${c?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await w(o)===!1?(t&&console.debug(`Port ${o}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(t&&console.debug(`Using port ${o} for "${e}" as it was used last time and is available.`),o)}async function U(s){let{debug:t,pickedPorts:e,portKey:n,portsUsedByOtherServers:u,portsUsedByThisServerLastTime:r}=s,a=Math.max(v,h,S)+1,i=[...Object.values(e),...Object.keys(u).map(Number),...Object.values(r||{})],o=Math.min(Math.max(a,...i)+100,p),c=T($(a,o),i),d={port:h,databasePort:v,shadowDatabasePort:S}[n];try{return await m({port:d in u||Object.values(e).includes(d)||Object.values(r||{}).includes(d)?void 0:d,ports:c})}catch(b){if(b instanceof Error&&b.name==="GetPortError"&&o+1<=p)return t&&console.debug(`Expanding port lookup to range [${o+1}, ${p}].`),await m({portRange:[o+1,p]});throw b}}function g(s){return s>=0}function x(s,t){let e={},n;for(let u of t){let{databasePort:r,port:a,shadowDatabasePort:i}=u;if(u.name===s){n={databasePort:r,port:a,shadowDatabasePort:i};continue}e[r]=!0,e[a]=!0,e[i]=!0}return{portsUsedByOtherServers:e,portsUsedByThisServerLastTime:n}}async function B(s){let{debug:t,otherRequestedPorts:e,portKey:n,portsUsedByOtherServers:u,requestedPort:r}=s;if(r in u)throw t&&console.error(`Port ${r} was requested for "${n}", but is already used by another server.`),new y(r);if(Object.values(e).includes(r))throw t&&console.error(`Port ${r} was requested for "${n}", but also for another key.`),new l(r);if(O(r))throw t&&console.error(`Port ${r} was requested for "${n}", but is unsafe.`),new f(r);if(await w(r)===!1)throw t&&console.error(`Port ${r} was requested for "${n}", but is not available.`),new f(r)}var f=class extends Error{constructor(e){super(`Port \`${e}\` is not available.`);this.port=e}name="PortNotAvailableError"},l=class extends Error{constructor(e){super(`Port number \`${e}\` was requested twice. Please choose a different port for each service.`);this.port=e}name="PortRequestedTwiceError"},y=class extends Error{constructor(e){super(`Port number \`${e}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=e}name="PortBelongsToAnotherServerError"};export{v as a,h as b,S as c,P as d,E as e,f};
@@ -0,0 +1,3 @@
1
+ import{a as M,b as A,c as I,d as m,e as T}from"./chunk-LMPFMHCB.js";import{b as c,f as $,g as k,h as R}from"./chunk-I55EQWKN.js";import{writeFile as Z}from"fs/promises";import{join as d}from"pathe";import{check as z,lock as K}from"proper-lockfile";import{process as F}from"std-env";import{integer as J,literal as W,minLength as G,minValue as U,number as j,object as f,optional as b,parseJson as Q,pipe as l,safeParse as X,string as g,url as ee}from"valibot";import{process as Y}from"std-env";function V(r,e){if(r==null)return!1;try{return Y.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}var w=l(g(),ee()),N=f({connectionString:w,prismaORMConnectionString:b(w),terminalCommand:b(g())}),L=f({url:w}),D=l(j(),J(),U(1)),te=f({database:N,http:L,ppg:L,shadowDatabase:N}),re=f({databasePort:D,exports:b(te),name:l(g(),G(1)),pid:b(l(j(),J(),U(0))),port:D,shadowDatabasePort:D,version:W("1")}),E=Symbol("initialize"),y="default",i=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??m,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??y,this.persistenceMode=e.persistenceMode,this.pid=e.pid??F.pid,this._port=e.port??m,this._shadowDatabasePort=e.shadowDatabasePort??m}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new p(e):new x(e);return await t[E](),t}static async fromServerDump(e){let{debug:t,name:o=y}=e??{},s=c(o),a=p.getServerDumpPath(s),u=await $(a);if(u==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(u));let{issues:h,output:n,success:P}=X(l(g(),Q(),re),u);if(!P)throw t&&console.debug(`[State] Invalid server dump file at "${a}":
2
+ ${JSON.stringify(h,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new p({databasePort:n.databasePort,debug:t,dryRun:!1,name:o,pid:n.pid,port:n.port,serverDump:n,shadowDatabasePort:n.shadowDatabasePort})}static async scan(e){let{debug:t}=e??{},o=d(c(y),"..");t&&console.debug(`[State] scanning for server states in: ${o}`);let s=await R(o);return t&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>se(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},x=class extends i{constructor(e){super({...e,databasePort:e?.databasePort??M,persistenceMode:"stateless",port:e?.port??A,shadowDatabasePort:e?.shadowDatabasePort??I})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[E](){}async close(){}async writeServerDump(){}},p=class r extends i{#t;#e;#a;#o;#r;#s=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=c(this.name),this.#t=d(this.#e,"db_dump.bak"),this.#a=d(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#o=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return d(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#a}async[E](){await k(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await K(this.#e,{lockfilePath:d(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await i.scan({debug:this.debug,onlyMetadata:!0}),t=await T({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new O(this):e}}async close(){if(this.#s!=null)try{await this.#s(),this.#s=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.#r={name:this.name,version:"1",pid:F.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await Z(this.#o,`${JSON.stringify(this.#r,null,2)}
3
+ `,{encoding:"utf-8"})}};async function se(r,e){let{debug:t,onlyMetadata:o}=e||{},s={databasePort:-1,exports:void 0,name:r,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let a=await i.fromServerDump({debug:t,name:r});if(!a)return t&&console.debug(`[State] no server state found for name: ${r}`),{...s,status:"no_such_server"};s.databasePort=a.databasePort,s.exports=a.exports,s.pid=a.pid,s.port=a.port,s.shadowDatabasePort=a.shadowDatabasePort;let{exports:u,pid:h}=a;if(o)return{...s,status:"unknown"};if(!V(h,t))return t&&console.debug(`[State] server state for "${r}" has no running process with PID: ${h}`),{...s,status:"not_running"};let n=c(r);try{if(!await z(n,{lockfilePath:d(n,".lock")}))return t&&console.debug(`[State] server state for "${r}" is not locked, indicating it is not running.`),{...s,status:"starting_up"}}catch(C){t&&console.error(`[State] server state for "${r}" failed to check lock:`,C)}if(!u)return{...s,status:"starting_up"};let{http:P}=u,{hc:B}=await import("hono/client"),v=await B(P.url).health.$get();if(!v.ok)return t&&console.debug(`[State] server state for "${r}" is not live: ${JSON.stringify(v)}`),{...s,status:"not_running"};let S=await v.json();return S.name!==r?(t&&console.debug(`[State] server state for "${r}" has mismatched health response: ${JSON.stringify(S)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(S)}`),{...s,status:"running"})}catch(a){return t&&console.error(`[State] failed to get server status for "${r}":`,a),{...s,status:"error"}}}var _=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},O=class extends _{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return i.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{i as a,_ as b,O as c};
package/dist/db.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var j=Object.create;var p=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty;var k=(e,t)=>{for(var n in t)p(e,n,{get:t[n],enumerable:!0})},A=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of N(t))!G.call(e,s)&&s!==n&&p(e,s,{get:()=>t[s],enumerable:!(i=C(t,s))||i.enumerable});return e};var f=(e,t,n)=>(n=e!=null?j(F(e)):{},A(t||!e||!e.__esModule?p(n,"default",{value:e,enumerable:!0}):n,e)),M=e=>A(p({},"__esModule",{value:!0}),e);var q={};k(q,{dumpDB:()=>L,startDBServer:()=>Q});module.exports=M(q);var v=require("@electric-sql/pglite"),$=require("@electric-sql/pglite-socket"),x=require("pathe/utils");var D=require("fs"),m=require("fs/promises");var r=f(require("path"),1),w=f(require("os"),1),b=f(require("process"),1),u=w.default.homedir(),S=w.default.tmpdir(),{env:g}=b.default,I=e=>{let t=r.default.join(u,"Library");return{data:r.default.join(t,"Application Support",e),config:r.default.join(t,"Preferences",e),cache:r.default.join(t,"Caches",e),log:r.default.join(t,"Logs",e),temp:r.default.join(S,e)}},U=e=>{let t=g.APPDATA||r.default.join(u,"AppData","Roaming"),n=g.LOCALAPPDATA||r.default.join(u,"AppData","Local");return{data:r.default.join(n,e,"Data"),config:r.default.join(t,e,"Config"),cache:r.default.join(n,e,"Cache"),log:r.default.join(n,e,"Log"),temp:r.default.join(S,e)}},H=e=>{let t=r.default.basename(u);return{data:r.default.join(g.XDG_DATA_HOME||r.default.join(u,".local","share"),e),config:r.default.join(g.XDG_CONFIG_HOME||r.default.join(u,".config"),e),cache:r.default.join(g.XDG_CACHE_HOME||r.default.join(u,".cache"),e),log:r.default.join(g.XDG_STATE_HOME||r.default.join(u,".local","state"),e),temp:r.default.join(S,t,e)}};function h(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),b.default.platform==="darwin"?I(e):b.default.platform==="win32"?U(e):H(e)}var W=require("pako"),ee=h("prisma-dev");async function _(e,t){await e.stream().pipeTo(D.WriteStream.toWeb((0,D.createWriteStream)(t,{encoding:"utf-8"})))}var P=class extends Error{constructor(n,i){super(`Port number \`${n}\` is not available for service ${i}.`);this.port=n;this.service=i}name="PortNotAvailableError"};var a={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},X=`postgres://${a.username}:${a.password}@localhost`,O=new URLSearchParams({sslmode:a.sslMode}),J=new URLSearchParams({...Object.fromEntries(O.entries()),connection_limit:String(a.connectionLimit),connect_timeout:String(a.connectTimeout),max_idle_connection_lifetime:String(a.maxIdleConnectionLifetime),pool_timeout:String(a.poolTimeout),single_use_connections:"true",socket_timeout:String(a.socketTimeout)});async function Q(e,t){let n=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return E(e,t,{db:null,port:n,server:null});let{debug:i}=t,d=await(e==="shadow_database"?Y:B)(t.pgliteDataDirPath,i);i&&d.onNotification((o,c)=>{console.debug(`[${e}][${o}] ${c}`)});let l=new $.PGLiteSocketServer({db:d,debug:i,inspect:i,port:n});i&&(l.addEventListener("listening",o=>{let{detail:c}=o;console.debug(`[${e}] server listening on ${JSON.stringify(c)}`)}),l.addEventListener("connection",o=>{let{clientAddress:c,clientPort:R}=o.detail;console.debug(`[${e}] client connected from ${c}:${R}`)}),l.addEventListener("error",o=>{let{detail:c}=o;console.error(`[${e}] server error:`,c)}));try{await l.start()}catch(o){throw o instanceof Error&&"code"in o&&o.code==="EADDRINUSE"?new P(n,e):o}return E(e,t,{db:d,port:n,server:l})}function E(e,t,n){let{debug:i}=t,{db:s,port:d,server:l}=n||{};return i&&console.debug(`[${e}] server started on port ${d}`),{...a,close:async()=>{let o=[];try{await l?.stop(),i&&console.debug(`[${e}] server stopped on port ${d}`)}catch(c){console.error(`[${e}] server stop error`,c),o.push(c)}if(e==="database")try{await s?.syncToFs(),i&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),o.push(c)}try{await s?.close(),i&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),o.push(c)}if(o.length>0)throw new AggregateError(o,`Failed to close ${e} properly`)},connectionString:T(d,O),dump:async o=>{e==="shadow_database"||!s||await L({db:s,debug:i,destinationPath:o})},port:d,prismaORMConnectionString:T(d,J),terminalCommand:`PGPASSWORD=${a.password} PGSSLMODE=${a.sslMode} psql -h localhost -p ${d} -U ${a.username} -d ${a.database}`}}function T(e,t){return`${X}:${e}/${a.database}?${t.toString()}`}async function B(e,t){return await v.PGlite.create({database:a.database,dataDir:e,debug:t?5:void 0,relaxedDurability:!1,username:a.username})}async function Y(e,t){return await v.PGlite.create({database:a.database,dataDir:"memory://",debug:t?5:void 0,relaxedDurability:!1,username:a.username})}async function L(e){let{dataDir:t,db:n,debug:i,destinationPath:s}=e,d=n||await B(t,i),{pgDump:l}=await import("@electric-sql/pglite-tools/pg_dump"),o=await l({args:["--schema-only","--no-owner"],fileName:s?(0,x.filename)(s):void 0,pg:await d.clone()});return s?(i&&console.debug(`[DB] Dumping database to ${s}`),await _(o,s)):(i&&console.debug("[DB] Dumping database to memory"),await o.text())}0&&(module.exports={dumpDB,startDBServer});
1
+ "use strict";var N=Object.create;var b=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var M=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var F=(e,t)=>{for(var r in t)b(e,r,{get:t[r],enumerable:!0})},O=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of C(t))!q.call(e,a)&&a!==r&&b(e,a,{get:()=>t[a],enumerable:!(s=G(t,a))||s.enumerable});return e};var p=(e,t,r)=>(r=e!=null?N(M(e)):{},O(t||!e||!e.__esModule?b(r,"default",{value:e,enumerable:!0}):r,e)),I=e=>O(b({},"__esModule",{value:!0}),e);var Q={};F(Q,{dumpDB:()=>j,startDBServer:()=>J});module.exports=I(Q);var k=require("pathe/utils");var y=require("fs"),m=require("fs/promises"),T=require("util"),x=require("zlib");var o=p(require("path"),1),S=p(require("os"),1),g=p(require("process"),1),u=S.default.homedir(),v=S.default.tmpdir(),{env:f}=g.default,K=e=>{let t=o.default.join(u,"Library");return{data:o.default.join(t,"Application Support",e),config:o.default.join(t,"Preferences",e),cache:o.default.join(t,"Caches",e),log:o.default.join(t,"Logs",e),temp:o.default.join(v,e)}},H=e=>{let t=f.APPDATA||o.default.join(u,"AppData","Roaming"),r=f.LOCALAPPDATA||o.default.join(u,"AppData","Local");return{data:o.default.join(r,e,"Data"),config:o.default.join(t,e,"Config"),cache:o.default.join(r,e,"Cache"),log:o.default.join(r,e,"Log"),temp:o.default.join(v,e)}},W=e=>{let t=o.default.basename(u);return{data:o.default.join(f.XDG_DATA_HOME||o.default.join(u,".local","share"),e),config:o.default.join(f.XDG_CONFIG_HOME||o.default.join(u,".config"),e),cache:o.default.join(f.XDG_CACHE_HOME||o.default.join(u,".cache"),e),log:o.default.join(f.XDG_STATE_HOME||o.default.join(u,".local","state"),e),temp:o.default.join(v,t,e)}};function D(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),g.default.platform==="darwin"?K(e):g.default.platform==="win32"?H(e):W(e)}var re=D("prisma-dev"),oe=(0,T.promisify)(x.unzip);async function A(e,t){await e.stream().pipeTo(y.WriteStream.toWeb((0,y.createWriteStream)(t,{encoding:"utf-8"})))}var $=require("get-port-please"),_=require("remeda");var h=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"};var i={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},V=`postgres://${i.username}:${i.password}@localhost`,R=new URLSearchParams({sslmode:i.sslMode}),X=new URLSearchParams({...Object.fromEntries(R.entries()),connection_limit:String(i.connectionLimit),connect_timeout:String(i.connectTimeout),max_idle_connection_lifetime:String(i.maxIdleConnectionLifetime),pool_timeout:String(i.poolTimeout),single_use_connections:"true",socket_timeout:String(i.socketTimeout)});async function J(e,t){let r=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return E(e,t,{db:null,port:r,server:null});let{debug:s}=t,d=await(e==="shadow_database"?z:L)(t.pgliteDataDirPath,s);s&&d.onNotification((n,l)=>{console.debug(`[${e}][${n}] ${l}`)});let{PGLiteSocketServer:P}=await import("@electric-sql/pglite-socket"),c=new P({db:d,debug:s,inspect:s,port:r});s&&(c.addEventListener("listening",n=>{let{detail:l}=n;console.debug(`[${e}] server listening on ${JSON.stringify(l)}`)}),c.addEventListener("connection",n=>{let{clientAddress:l,clientPort:U}=n.detail;console.debug(`[${e}] client connected from ${l}:${U}`)}),c.addEventListener("error",n=>{let{detail:l}=n;console.error(`[${e}] server error:`,l)}));try{await c.start()}catch(n){throw n instanceof Error&&"code"in n&&n.code==="EADDRINUSE"?new h(r):n}return E(e,t,{db:d,port:r,server:c})}function E(e,t,r){let{debug:s}=t,{db:a,port:d,server:P}=r||{};return s&&console.debug(`[${e}] server started on port ${d}`),{...i,close:async()=>{let c=[];try{await P?.stop(),s&&console.debug(`[${e}] server stopped on port ${d}`)}catch(n){console.error(`[${e}] server stop error`,n),c.push(n)}if(e==="database")try{await a?.syncToFs(),s&&console.debug(`[${e}] synced to filesystem`)}catch(n){console.error(`[${e}] sync error`,n),c.push(n)}try{await a?.close(),s&&console.debug(`[${e}] closed`)}catch(n){console.error(`[${e}] close error`,n),c.push(n)}if(c.length>0)throw new AggregateError(c,`Failed to close ${e} properly`)},connectionString:B(d,R),dump:async c=>{e==="shadow_database"||!a||await j({db:a,debug:s,destinationPath:c})},port:d,prismaORMConnectionString:B(d,X),terminalCommand:`PGPASSWORD=${i.password} PGSSLMODE=${i.sslMode} psql -h localhost -p ${d} -U ${i.username} -d ${i.database}`}}function B(e,t){return`${V}:${e}/${i.database}?${t.toString()}`}async function L(e,t){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:i.database,dataDir:e,debug:t?5:void 0,relaxedDurability:!1,username:i.username})}async function z(e,t){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:i.database,dataDir:"memory://",debug:t?5:void 0,relaxedDurability:!1,username:i.username})}async function j(e){let{dataDir:t,db:r,debug:s,destinationPath:a}=e,d=r||await L(t,s),{pgDump:P}=await import("@electric-sql/pglite-tools/pg_dump"),c=await P({args:["--schema-only","--no-owner"],fileName:a?(0,k.filename)(a):void 0,pg:await d.clone()});return a?(s&&console.debug(`[DB] Dumping database to ${a}`),await A(c,a)):(s&&console.debug("[DB] Dumping database to memory"),await c.text())}0&&(module.exports={dumpDB,startDBServer});
package/dist/db.js CHANGED
@@ -1 +1 @@
1
- import{a,b}from"./chunk-GBG44OEG.js";import"./chunk-Q3M6SQC2.js";export{b as dumpDB,a as startDBServer};
1
+ import{a,b}from"./chunk-GUT43IYK.js";import"./chunk-LMPFMHCB.js";import"./chunk-I55EQWKN.js";export{b as dumpDB,a as startDBServer};
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var pt=Object.create;var N=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var yt=(t,e)=>{for(var r in e)N(t,r,{get:e[r],enumerable:!0})},me=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of gt(e))!ft.call(t,o)&&o!==r&&N(t,o,{get:()=>e[o],enumerable:!(n=mt(e,o))||n.enumerable});return t};var _=(t,e,r)=>(r=t!=null?pt(ht(t)):{},me(e||!t||!t.__esModule?N(r,"default",{value:t,enumerable:!0}):r,t)),St=t=>me(N({},"__esModule",{value:!0}),t);var Ft={};yt(Ft,{DEFAULT_DATABASE_PORT:()=>Re,DEFAULT_SERVER_PORT:()=>Ae,DEFAULT_SHADOW_DATABASE_PORT:()=>Oe,PortNotAvailableError:()=>E,ServerAlreadyRunningError:()=>L,unstable_startServer:()=>Nt});module.exports=St(Ft);var D=require("hono/http-exception"),l=require("valibot"),ge=/^(postgres|postgresql):\/\//,bt=(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)(ge)),name:(0,l.optional)((0,l.pipe)((0,l.string)(),(0,l.minLength)(1))),shadowDatabaseUrl:(0,l.pipe)((0,l.string)(),(0,l.url)(),(0,l.regex)(ge))}));function he(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function vt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:n,success:o}=(0,l.safeParse)(bt,e,{abortEarly:!0});return o?[null,n]:[r]}var A=(t,e)=>{let{authorization:r}=t;if(!r)throw new D.HTTPException(401,{message:"Missing API Key"});let[n,o="",s]=r.split(" ");if(n!=="Bearer"||s)throw new D.HTTPException(401,{message:"Invalid API Key"});let[i,a]=vt(o);if(i)throw new D.HTTPException(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c,name:m,shadowDatabaseUrl:b}=a,{name:v}=e.get("serverState");if(!m)throw new D.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${v}" server's output for the updated \`DATABASE_URL\` value.`});if(m!==v)throw new D.HTTPException(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${v}", but the API Key is for "${m}"`});let{hostname:S,port:M}=new URL(c),{port:W}=e.get("db"),{hostname:dt,port:ut}=new URL(b),lt=e.get("shadowDBPort");if(S!=="localhost"||Number(M)!==W||dt!=="localhost"||Number(ut)!==lt)throw new D.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 ee=require("@electric-sql/pglite"),$e=require("@electric-sql/pglite-socket"),_e=require("pathe/utils");var U=require("fs"),y=require("fs/promises");var p=_(require("path"),1),z=_(require("os"),1),F=_(require("process"),1),w=z.default.homedir(),X=z.default.tmpdir(),{env:O}=F.default,wt=t=>{let e=p.default.join(w,"Library");return{data:p.default.join(e,"Application Support",t),config:p.default.join(e,"Preferences",t),cache:p.default.join(e,"Caches",t),log:p.default.join(e,"Logs",t),temp:p.default.join(X,t)}},Pt=t=>{let e=O.APPDATA||p.default.join(w,"AppData","Roaming"),r=O.LOCALAPPDATA||p.default.join(w,"AppData","Local");return{data:p.default.join(r,t,"Data"),config:p.default.join(e,t,"Config"),cache:p.default.join(r,t,"Cache"),log:p.default.join(r,t,"Log"),temp:p.default.join(X,t)}},Dt=t=>{let e=p.default.basename(w);return{data:p.default.join(O.XDG_DATA_HOME||p.default.join(w,".local","share"),t),config:p.default.join(O.XDG_CONFIG_HOME||p.default.join(w,".config"),t),cache:p.default.join(O.XDG_CACHE_HOME||p.default.join(w,".cache"),t),log:p.default.join(O.XDG_STATE_HOME||p.default.join(w,".local","state"),t),temp:p.default.join(X,e,t)}};function Y(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),F.default.platform==="darwin"?wt(t):F.default.platform==="win32"?Pt(t):Dt(t)}var fe=require("pako"),ye=Y("prisma-dev");function Se(t,e){return`${ye.cache}/engine/${t}/${e}`}function I(t){return`${ye.data}/${t}`}async function be(t){try{return await(0,y.access)(t,y.constants.F_OK),!0}catch(e){if(Z(e))return!1;throw e}}async function ve(t,e){let r=(0,fe.inflate)(t);await(0,y.writeFile)(e,r),await(0,y.chmod)(e,"755")}async function we(t,e){await t.stream().pipeTo(U.WriteStream.toWeb((0,U.createWriteStream)(e,{encoding:"utf-8"})))}function Z(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Pe(t){try{return await(0,y.readFile)(t,{encoding:"utf-8"})}catch(e){if(Z(e))return null;throw e}}async function De(t){await(0,y.mkdir)(t,{recursive:!0})}async function Ee(t){try{return(await(0,y.readdir)(t,{withFileTypes:!0})).reduce((r,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&r.push(n.name),r),[])}catch(e){if(Z(e))return[];throw e}}var Re=51214,Ae=51213,Oe=51215,E=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"},Et=`postgres://${g.username}:${g.password}@localhost`,Ie=new URLSearchParams({sslmode:g.sslMode}),Rt=new URLSearchParams({...Object.fromEntries(Ie.entries()),connection_limit:String(g.connectionLimit),connect_timeout:String(g.connectTimeout),max_idle_connection_lifetime:String(g.maxIdleConnectionLifetime),pool_timeout:String(g.poolTimeout),single_use_connections:"true",socket_timeout:String(g.socketTimeout)});async function te(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return xe(t,e,{db:null,port:r,server:null});let{debug:n}=e,s=await(t==="shadow_database"?At:Ce)(e.pgliteDataDirPath,n);n&&s.onNotification((a,c)=>{console.debug(`[${t}][${a}] ${c}`)});let i=new $e.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 E(r,t):a}return xe(t,e,{db:s,port:r,server:i})}function xe(t,e,r){let{debug:n}=e,{db:o,port:s,server:i}=r||{};return n&&console.debug(`[${t}] server started on port ${s}`),{...g,close:async()=>{let a=[];try{await i?.stop(),n&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),a.push(c)}if(t==="database")try{await o?.syncToFs(),n&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),a.push(c)}try{await o?.close(),n&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${t} properly`)},connectionString:Te(s,Ie),dump:async a=>{t==="shadow_database"||!o||await Ot({db:o,debug:n,destinationPath:a})},port:s,prismaORMConnectionString:Te(s,Rt),terminalCommand:`PGPASSWORD=${g.password} PGSSLMODE=${g.sslMode} psql -h localhost -p ${s} -U ${g.username} -d ${g.database}`}}function Te(t,e){return`${Et}:${t}/${g.database}?${e.toString()}`}async function Ce(t,e){return await ee.PGlite.create({database:g.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function At(t,e){return await ee.PGlite.create({database:g.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:g.username})}async function Ot(t){let{dataDir:e,db:r,debug:n,destinationPath:o}=t,s=r||await Ce(e,n),{pgDump:i}=await import("@electric-sql/pglite-tools/pg_dump"),a=await i({args:["--schema-only","--no-owner"],fileName:o?(0,_e.filename)(o):void 0,pg:await s.clone()});return o?(n&&console.debug(`[DB] Dumping database to ${o}`),await we(a,o)):(n&&console.debug("[DB] Dumping database to memory"),await a.text())}var Xe=require("http"),Ye=require("util"),Ze=require("@hono/node-server"),et=_(require("@prisma/get-platform"),1);function V(t){let e,r,n=new Promise((i,a)=>{e=i,r=a}),o=i=>{o=s=null,r(i),t?.onRejected?.(i),t?.onFulfilled?.()},s=i=>{s=o=null,e(i),t?.onResolved?.(i),t?.onFulfilled?.()};return{isFulfilled:()=>s===o,promise:n,reject:i=>o?.(i),resolve:i=>s?.(i)}}var tt=require("hono/logger"),se=require("hono/tiny");var Je=require("hono/tiny"),$=require("hono/validator");var f=require("valibot"),xt=(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 ke(t){let{output:e,success:r}=(0,f.safeParse)(xt,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var Be=require("child_process"),je=require("events"),Le=require("fs/promises"),Me=require("path"),Ne=require("timers/promises");var Fe=require("foreground-child/proxy-signals"),Ue=require("std-env");var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Tt,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:$t,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:He}=Ue.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 x.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 x.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:n}=V();this.#t=e;let o=$t||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=(0,Be.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,Fe.proxySignals)(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=m=>{let b=m.split(`
2
- `).find(W=>W.includes("Started query engine http server"));if(!b)return;s.stdout.removeListener("data",i);let{fields:v}=JSON.parse(b);if(v==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${m}`));let{ip:S,port:M}=v;if(S==null||M==null)return r(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
- Received data: ${m}`));n({childProcess:s,url:`http://${S}:${M}`})},a=m=>{this.#t=null,r(new C(String(m))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(m,b)=>{this.#t=null,r(new C(`Query Engine exited with code ${m} and signal ${b}`))};return s.once("exit",c),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:e}=await this.#t;e.exitCode==null&&e.signalCode==null&&(this.#t=null,e.kill(),await(0,je.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=Se(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,Le.mkdir)(r,{recursive:!0});let{platform:n}=this.#e.platform,o=n==="windows"?".exe":"",s=(0,Me.join)(r,`query-engine-${n}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Tt==="1"||await be(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}`);He&&await(0,Ne.setTimeout)(Number(He)),await ve(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 x.fromResponse(i);try{return await i.json()}catch{return{}}}};function G(t,e){return console.error(t),t instanceof C?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof x?e.text(t.responseBody,t.statusCode):e.body(null,500)}var C=class extends Error{name="EngineStartError"},x=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 re=require("buffer"),q=new Map;async function ne(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 Ve(t){let e=t.req.param("schemaHash"),r=q.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}var _t=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function Ge(t,e){let r=re.Buffer.from(t,"base64").toString("utf8"),n=`datasource db {
1
+ "use strict";var xt=Object.create;var K=Object.defineProperty;var _t=Object.getOwnPropertyDescriptor;var $t=Object.getOwnPropertyNames;var kt=Object.getPrototypeOf,It=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var ne=(t,e)=>{for(var r in e)K(t,r,{get:e[r],enumerable:!0})},Re=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of $t(e))!It.call(t,n)&&n!==r&&K(t,n,{get:()=>e[n],enumerable:!(o=_t(e,n))||o.enumerable});return t};var w=(t,e,r)=>(r=t!=null?xt(kt(t)):{},Re(e||!t||!t.__esModule?K(r,"default",{value:t,enumerable:!0}):r,t)),Ct=t=>Re(K({},"__esModule",{value:!0}),t);var p=D(()=>{"use strict"});function Ae(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function Ht(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:o,success:n}=(0,f.safeParse)(Bt,e,{abortEarly:!0});return n?[null,o]:[r]}var f,Te,Bt,$,se=D(()=>{"use strict";p();f=require("valibot"),Te=/^(postgres|postgresql):\/\//,Bt=(0,f.pipe)((0,f.string)(),(0,f.parseJson)(),(0,f.object)({databaseUrl:(0,f.pipe)((0,f.string)(),(0,f.url)(),(0,f.regex)(Te)),name:(0,f.optional)((0,f.pipe)((0,f.string)(),(0,f.minLength)(1))),shadowDatabaseUrl:(0,f.pipe)((0,f.string)(),(0,f.url)(),(0,f.regex)(Te))}));$=async(t,e)=>{let{authorization:r}=t,{HTTPException:o}=await import("hono/http-exception");if(!r)throw new o(401,{message:"Missing API Key"});let[n,s="",a]=r.split(" ");if(n!=="Bearer"||a)throw new o(401,{message:"Invalid API Key"});let[c,i]=Ht(s);if(c)throw new o(401,{message:"Invalid API Key",cause:c.join(", ")});let{databaseUrl:u,name:l,shadowDatabaseUrl:g}=i,{name:y}=e.get("serverState");if(!l)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${y}" server's output for the updated \`DATABASE_URL\` value.`});if(l!==y)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${y}", but the API Key is for "${l}"`});let{hostname:_,port:V}=new URL(u),{port:oe}=e.get("db"),{hostname:Rt,port:Tt}=new URL(g),At=e.get("shadowDBPort");if(_!=="localhost"||Number(V)!==oe||Rt!=="localhost"||Number(Tt)!==At)throw new o(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:i}}});function ce(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),G.default.platform==="darwin"?Lt(t):G.default.platform==="win32"?jt(t):Mt(t)}var h,ae,G,R,ie,k,Lt,jt,Mt,xe=D(()=>{"use strict";p();h=w(require("path"),1),ae=w(require("os"),1),G=w(require("process"),1),R=ae.default.homedir(),ie=ae.default.tmpdir(),{env:k}=G.default,Lt=t=>{let e=h.default.join(R,"Library");return{data:h.default.join(e,"Application Support",t),config:h.default.join(e,"Preferences",t),cache:h.default.join(e,"Caches",t),log:h.default.join(e,"Logs",t),temp:h.default.join(ie,t)}},jt=t=>{let e=k.APPDATA||h.default.join(R,"AppData","Roaming"),r=k.LOCALAPPDATA||h.default.join(R,"AppData","Local");return{data:h.default.join(r,t,"Data"),config:h.default.join(e,t,"Config"),cache:h.default.join(r,t,"Cache"),log:h.default.join(r,t,"Log"),temp:h.default.join(ie,t)}},Mt=t=>{let e=h.default.basename(R);return{data:h.default.join(k.XDG_DATA_HOME||h.default.join(R,".local","share"),t),config:h.default.join(k.XDG_CONFIG_HOME||h.default.join(R,".config"),t),cache:h.default.join(k.XDG_CACHE_HOME||h.default.join(R,".cache"),t),log:h.default.join(k.XDG_STATE_HOME||h.default.join(R,".local","state"),t),temp:h.default.join(ie,e,t)}}});function Ie(t,e){return`${ke.cache}/engine/${t}/${e}`}function M(t){return`${ke.data}/${t}`}async function Ce(t){try{return await(0,v.access)(t,v.constants.F_OK),!0}catch(e){if(de(e))return!1;throw e}}async function Be(t,e){let r=await Ut(t);await(0,v.writeFile)(e,r),await(0,v.chmod)(e,"755")}async function He(t,e){await t.stream().pipeTo(J.WriteStream.toWeb((0,J.createWriteStream)(e,{encoding:"utf-8"})))}function de(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Le(t){try{return await(0,v.readFile)(t,{encoding:"utf-8"})}catch(e){if(de(e))return null;throw e}}async function je(t){await(0,v.mkdir)(t,{recursive:!0})}async function Me(t){try{return(await(0,v.readdir)(t,{withFileTypes:!0})).reduce((r,o)=>(o.isDirectory()&&!o.name.startsWith(".")&&r.push(o.name),r),[])}catch(e){if(de(e))return[];throw e}}var J,v,_e,$e,ke,Ut,Q=D(()=>{"use strict";p();J=require("fs"),v=require("fs/promises"),_e=require("util"),$e=require("zlib");xe();ke=ce("prisma-dev"),Ut=(0,_e.promisify)($e.unzip)});function X(t){let e,r,o=new Promise((a,c)=>{e=a,r=c}),n=a=>{n=s=null,r(a),t?.onRejected?.(a),t?.onFulfilled?.()},s=a=>{s=n=null,e(a),t?.onResolved?.(a),t?.onFulfilled?.()};return{isFulfilled:()=>s===n,promise:o,reject:a=>n?.(a),resolve:a=>s?.(a)}}var me=D(()=>{"use strict";p()});function Y(t,e){return console.error(t),t instanceof U?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof H?e.text(t.responseBody,t.statusCode):e.body(null,500)}var Qe,We,ze,Xe,Ye,Ze,Wt,zt,Je,L,U,H,fe=D(()=>{"use strict";p();Qe=require("child_process"),We=require("events"),ze=require("fs/promises"),Xe=require("path"),Ye=require("timers/promises");me();Ze=require("std-env");Q();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Wt,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:zt,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Je}=Ze.process.env),L=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,o=`${e.schemaHash}:${e.clientVersion}`;try{let n=t.#r.get(o);if(n)return n;let s=new t(e);return t.#r.set(o,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(o)}}static async stopAll(e){let o=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([n])=>n!==e).map(async([n,s])=>{try{await s.stop()}finally{t.#r.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(o.length>0)throw new AggregateError(o,"Failed to stop engines")}async commitTransaction(e,r){return await this.#i(e,r,"commit")}async request(e,r){let{url:o}=await this.start(),n=this.#a(r),s=await fetch(o,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await H.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#i(e,r,"rollback")}async startTransaction(e,r){let{url:o}=await this.start(),n=this.#a(r),s=await fetch(`${o}/transaction/start`,{body:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await H.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:o}=X();this.#t=e;let n=zt||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",n);let{proxySignals:s}=await import("foreground-child/proxy-signals"),a=(0,Qe.spawn)(n,["--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});s(a),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8");let c=l=>{let g=l.split(`
2
+ `).find(oe=>oe.includes("Started query engine http server"));if(!g)return;a.stdout.removeListener("data",c);let{fields:y}=JSON.parse(g);if(y==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${l}`));let{ip:_,port:V}=y;if(_==null||V==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: ${l}`));o({childProcess:a,url:`http://${_}:${V}`})},i=l=>{this.#t=null,r(new U(String(l))),a.removeListener("exit",u),a.kill()};a.once("error",i);let u=(l,g)=>{this.#t=null,r(new U(`Query Engine exited with code ${l} and signal ${g}`))};return a.once("exit",u),a.stdout.on("data",c),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.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,We.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#o();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=Ie(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,ze.mkdir)(r,{recursive:!0});let{platform:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,Xe.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Wt==="1"||await Ce(s)===!1)&&await this.#n({commitHash:e,extension:n,engineBinaryPath:s}),s}async#o(){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 o=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!o)throw new Error("Couldn't find engines version in package.json");let n=o.split(".").at(-1);if(!n)throw new Error("Couldn't find commit hash in engines version");return n}async#n(e){let{commitHash:r,extension:o,engineBinaryPath:n}=e,{binaryTarget:s}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${o}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",a);let c=await fetch(a);if(!c.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${c.status}`);Je&&await(0,Ye.setTimeout)(Number(Je)),await Be(await c.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#a(e){let r={};for(let[o,n]of Object.entries(e))n!=null&&(r[o]=n);return r}async#i(e,r,o){let{url:n}=await this.#t,s=this.#a(r),a=await fetch(`${n}/transaction/${e}/${o}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await H.fromResponse(a);try{return await a.json()}catch{return{}}}};U=class extends Error{name="EngineStartError"},H=class t extends Error{constructor(r,o,n){super(`${r}: Query Engine response status ${o}, body: ${n}`);this.action=r;this.statusCode=o;this.responseBody=n}name="EngineHttpError";static async fromResponse(r){let o=new URL(r.url),n=await r.text();return new t(o.pathname,r.status,n)}}});async function et(t){let{output:e,success:r}=(0,S.safeParse)(Xt,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var S,Xt,tt=D(()=>{"use strict";p();S=require("valibot"),Xt=(0,S.object)({tags:(0,S.union)([(0,S.pipe)((0,S.array)((0,S.string)()),(0,S.minLength)(1)),(0,S.literal)("all")])})});async function ge(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(a=>a.toString(16).padStart(2,"0")).join("")}function rt(t){let e=t.req.param("schemaHash"),r=Z.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}async function ot(t,e){let r=he.Buffer.from(t,"base64").toString("utf8"),o=`datasource db {
4
4
  provider = "postgresql"
5
5
  url = "${e.toString()}"
6
- }`,o=r.replace(_t,n),s=await ne(o);return{base64Override:re.Buffer.from(o,"utf8").toString("base64"),overrideHash:s}}function K(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var u=require("valibot"),It=(0,u.object)({isolation_level:(0,u.optional)((0,u.string)()),max_wait:(0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(0)),timeout:(0,u.pipe)((0,u.number)(),(0,u.integer)(),(0,u.minValue)(0))});async function qe(t){let{issues:e,output:r,success:n}=(0,u.safeParse)(It,await t.req.json(),{abortEarly:!0});return n?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var Ct=(0,u.looseObject)({id:(0,u.union)([(0,u.string)(),(0,u.number)()])});function Ke(t,e){let{output:r,success:n}=(0,u.safeParse)(Ct,t);return n?r:e.json({EngineMalfunction:{}},500)}var k=new Je.Hono;k.post("/invalidate",(0,$.validator)("header",A),async t=>{let e=await ke(t);return e instanceof Response?e:t.body(null)});var kt="/:clientVersion/:schemaHash",H=k.basePath(kt);k.route("/",H);var Ht=["/graphql","/itx/:transactionId/graphql"];H.on("POST",[...Ht],(0,$.validator)("header",A),async t=>{let{req:e}=t;try{let r=await oe(t);if(r instanceof Response)return r;let n=await e.text(),o=e.param("transactionId"),s=await r.request(n,{...K(t),"X-transaction-id":o});return t.text(s)}catch(r){return G(r,t)}});H.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,$.validator)("header",A),async t=>{let{req:e}=t;try{let r=await oe(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,K(t));return t.json(i)}catch(r){return G(r,t)}});H.put("/schema",(0,$.validator)("header",A),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let n=e.param("schemaHash"),o=q.get(n);if(o==null){if(n!==await ne(r))return t.text("Schema hash mismatch",400);let s=await Ge(r,t.get("db").prismaORMConnectionString);return q.set(n,{base64Original:r,...s}),t.text(n)}return r!==o.base64Original?t.text("Schema mismatch",400):t.text(n)});H.post("/transaction/start",(0,$.validator)("header",A),async t=>{let{req:e}=t,r=await qe(t);if(r instanceof Response)return r;try{let n=await oe(t);if(n instanceof Response)return n;let o=await n.startTransaction(r,K(t)),s=Ke(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 G(n,t)}});async function oe(t){let{req:e}=t,r=Ve(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 Qe=require("hono/tiny"),We=require("http-status-codes"),J=new Qe.Hono;J.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},We.StatusCodes.CREATED)});var Rr=J.get("/health",t=>t.json({name:t.get("serverState").name}));async function rt(t,e){let{port:r}=e;if(e.dryRun)return ze(r,null);let n=await Bt(r,t,e),{promise:o,reject:s,resolve:i}=V(),a=(0,Ze.serve)({createServer:Xe.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 E(r,"server"));console.error("[Accelerate]",c)}),await o,ze(r,a)}function ze(t,e){return{async close(){e&&await Promise.allSettled([(0,Ye.promisify)(e.close.bind(e))(),T.stopAll()])},port:t,url:`http://localhost:${t}`}}async function Bt(t,e,r){let{debug:n}=r,o=new se.Hono,s=await et.default.getPlatformInfo();return n&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),n&&o.use("*",(0,tt.logger)((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",e),i.set("debug",!!n),i.set("platform",s),i.set("port",t),i.set("protocol","http"),i.set("serverState",r),i.set("shadowDBPort",r.shadowDatabasePort),await a())),o.route("/",ie),o}var ie=new se.Hono;ie.route("/",k);ie.route("/",J);var at=require("fs/promises"),ct=require("hono/client"),R=require("pathe"),Q=require("proper-lockfile"),j=require("std-env"),d=require("valibot");var nt=require("std-env");function ot(t,e){if(t==null)return!1;try{return nt.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var de=(0,d.pipe)((0,d.string)(),(0,d.url)()),st=(0,d.object)({connectionString:de,prismaORMConnectionString:(0,d.optional)(de),terminalCommand:(0,d.optional)((0,d.string)())}),it=(0,d.object)({url:de}),ae=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),jt=(0,d.object)({database:st,http:it,ppg:it,shadowDatabase:st}),Lt=(0,d.object)({databasePort:ae,exports:(0,d.optional)(jt),name:(0,d.pipe)((0,d.string)(),(0,d.minLength)(1)),pid:(0,d.optional)((0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0))),port:ae,shadowDatabasePort:ae,version:(0,d.literal)("1")}),pe=Symbol("initialize"),ce="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??ce,this.persistenceMode=e.persistenceMode,this.pid=e.pid??j.process.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new B({...e,pid:j.process.pid}):new ue(e);return await r[pe](),r}static async fromServerDump(e){let{debug:r,name:n=ce}=e??{},o=I(n),s=B.getServerDumpPath(o),i=await Pe(s);if(i==null)return r&&console.debug(`[State] No server dump file found at: ${s}`),null;r&&(console.debug(`[State] server dump file found at "${s}":`),console.debug(i));let{issues:a,output:c,success:m}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),Lt),i);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
7
- ${JSON.stringify(a,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new B({databasePort:c.databasePort,debug:r,dryRun:!1,name:n,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},n=(0,R.join)(I(ce),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let o=await Ee(n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(s=>Mt(s,r)))}},ue=class extends P{constructor(e){super({...e,persistenceMode:"stateless",pid:j.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[pe](){}async close(){}async writeServerDump(){}},B=class t extends P{#r;#e;#t;#s;#n;#o=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=I(this.name),this.#r=(0,R.join)(this.#e,"db_dump.bak"),this.#t=(0,R.join)(this.#e,".pglite"),this.#n=e.serverDump??null,this.#s=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,R.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get pgliteDataDirPath(){return this.#t}async[pe](){await De(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#o=await(0,Q.lock)(this.#e,{lockfilePath:(0,R.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 L(this):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:j.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,at.writeFile)(this.#s,`${JSON.stringify(this.#n,null,2)}
8
- `,{encoding:"utf-8"})}};async function Mt(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(!ot(s,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${s}`),{...r,status:"not_running"};let i=I(t);try{if(!await(0,Q.check)(i,{lockfilePath:(0,R.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,ct.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 le=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},L=class extends le{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return P.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function Nt(t){let e=await P.createExclusively(t),[r,n]=await Promise.all([te("database",e),te("shadow_database",e)]),o=await rt(r,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:he({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:n.prismaORMConnectionString})}).toString()}`,i={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:n.prismaORMConnectionString,prismaORMConnectionString:n.prismaORMConnectionString,terminalCommand:n.terminalCommand}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,r,n]),name:e.name};async function a(c,m){let v=(await Promise.allSettled(m.map(S=>S.close()))).filter(S=>S.status==="rejected").map(S=>new Error(S.reason));try{await c.close()}catch(S){v.push(S)}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,ServerAlreadyRunningError,unstable_startServer});
6
+ }`,n=r.replace(Yt,o),s=await ge(n);return{base64Override:he.Buffer.from(n,"utf8").toString("base64"),overrideHash:s}}var he,Z,Yt,nt=D(()=>{"use strict";p();he=require("buffer"),Z=new Map;Yt=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/});function ee(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var st=D(()=>{"use strict";p()});async function at(t){let{issues:e,output:r,success:o}=(0,m.safeParse)(Zt,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}function it(t,e){let{output:r,success:o}=(0,m.safeParse)(er,t);return o?r:e.json({EngineMalfunction:{}},500)}var m,Zt,er,ct=D(()=>{"use strict";p();m=require("valibot"),Zt=(0,m.object)({isolation_level:(0,m.optional)((0,m.string)()),max_wait:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0)),timeout:(0,m.pipe)((0,m.number)(),(0,m.integer)(),(0,m.minValue)(0))});er=(0,m.looseObject)({id:(0,m.union)([(0,m.string)(),(0,m.number)()])})});var ut={};ne(ut,{accelerateRoute:()=>te});async function ye(t){let{req:e}=t,r=rt(t);if(r instanceof Response)return r;let{base64Override:o,overrideHash:n}=r.schemas;return await L.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:t.get("debug"),platform:t.get("platform"),schemaHash:n})}var dt,j,te,tr,N,rr,lt=D(()=>{"use strict";p();dt=require("hono/tiny"),j=require("hono/validator");se();tt();fe();nt();st();ct();te=new dt.Hono;te.post("/invalidate",(0,j.validator)("header",$),async t=>{let e=await et(t);return e instanceof Response?e:t.body(null)});tr="/:clientVersion/:schemaHash",N=te.basePath(tr);te.route("/",N);rr=["/graphql","/itx/:transactionId/graphql"];N.on("POST",[...rr],(0,j.validator)("header",$),async t=>{let{req:e}=t;try{let r=await ye(t);if(r instanceof Response)return r;let o=await e.text(),n=e.param("transactionId"),s=await r.request(o,{...ee(t),"X-transaction-id":n});return t.text(s)}catch(r){return Y(r,t)}});N.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,j.validator)("header",$),async t=>{let{req:e}=t;try{let r=await ye(t);if(r instanceof Response)return r;let n=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),a=await r[n](s,ee(t));return t.json(a)}catch(r){return Y(r,t)}});N.put("/schema",(0,j.validator)("header",$),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let o=e.param("schemaHash"),n=Z.get(o);if(n==null){if(o!==await ge(r))return t.text("Schema hash mismatch",400);let s=await ot(r,t.get("db").prismaORMConnectionString);return Z.set(o,{base64Original:r,...s}),t.text(o)}return r!==n.base64Original?t.text("Schema mismatch",400):t.text(o)});N.post("/transaction/start",(0,j.validator)("header",$),async t=>{let{req:e}=t,r=await at(t);if(r instanceof Response)return r;try{let o=await ye(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,ee(t)),s=it(n,t);if(s instanceof Response)return s;let{id:a}=s,c=e.param("clientVersion"),i=t.get("port"),u=t.get("protocol"),l=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${u}://localhost:${i}/${c}/${l}/itx/${a}`}})}catch(o){return Y(o,t)}})});var ft={};ne(ft,{utilityRoute:()=>be});var pt,mt,be,Gr,ht=D(()=>{"use strict";p();pt=require("hono/tiny"),mt=require("http-status-codes"),be=new pt.Hono;be.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},mt.StatusCodes.CREATED)});Gr=be.get("/health",t=>t.json({name:t.get("serverState").name}))});var cr={};ne(cr,{DEFAULT_DATABASE_PORT:()=>I,DEFAULT_SERVER_PORT:()=>C,DEFAULT_SHADOW_DATABASE_PORT:()=>B,PortNotAvailableError:()=>E,ServerAlreadyRunningError:()=>q,unstable_startServer:()=>ir});module.exports=Ct(cr);p();se();p();var Ve=require("pathe/utils");Q();p();var A=require("get-port-please"),z=require("remeda"),I=51214,C=51213,B=51215,W=65535,T=-1/0;async function Ne(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=qt(r,n);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let c={databasePort:T,port:T,shadowDatabasePort:T},i=["port","databasePort","shadowDatabasePort"];for(let u of i){let l=await Nt({debug:e,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await Ft({debug:e,pickedPorts:c,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${u}": ${l}`),c[u]=l}return e&&console.debug(`Picked ports: ${JSON.stringify(c)}`),c}async function Nt(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s}=t,{[r]:a,...c}=s;if(Ue(a))return await Vt({debug:e,otherRequestedPorts:c,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let i=n?.[r]??T;if(!Ue(i))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=i in o;return u||Object.values(c).includes(i)?(e&&console.debug(`Port ${i} that was used last time for this server, ${u?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,A.checkPort)(i)===!1?(e&&console.debug(`Port ${i}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${i} for "${r}" as it was used last time and is available.`),i)}async function Ft(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(I,C,B)+1,c=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],i=Math.min(Math.max(a,...c)+100,W),u=(0,z.difference)((0,z.range)(a,i),c),l={port:C,databasePort:I,shadowDatabasePort:B}[o];try{return await(0,A.getPort)({port:l in n||Object.values(r).includes(l)||Object.values(s||{}).includes(l)?void 0:l,ports:u})}catch(g){if(g instanceof Error&&g.name==="GetPortError"&&i+1<=W)return e&&console.debug(`Expanding port lookup to range [${i+1}, ${W}].`),await(0,A.getPort)({portRange:[i+1,W]});throw g}}function Ue(t){return t>=0}function qt(t,e){let r={},o;for(let n of e){let{databasePort:s,port:a,shadowDatabasePort:c}=n;if(n.name===t){o={databasePort:s,port:a,shadowDatabasePort:c};continue}r[s]=!0,r[a]=!0,r[c]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:o}}async function Vt(t){let{debug:e,otherRequestedPorts:r,portKey:o,portsUsedByOtherServers:n,requestedPort:s}=t;if(s in n)throw e&&console.error(`Port ${s} was requested for "${o}", but is already used by another server.`),new le(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${o}", but also for another key.`),new ue(s);if((0,A.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${o}", but is unsafe.`),new E(s);if(await(0,A.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${o}", but is not available.`),new E(s)}var E=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},ue=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},le=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};var b={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Kt=`postgres://${b.username}:${b.password}@localhost`,Ke=new URLSearchParams({sslmode:b.sslMode}),Gt=new URLSearchParams({...Object.fromEntries(Ke.entries()),connection_limit:String(b.connectionLimit),connect_timeout:String(b.connectTimeout),max_idle_connection_lifetime:String(b.maxIdleConnectionLifetime),pool_timeout:String(b.poolTimeout),single_use_connections:"true",socket_timeout:String(b.socketTimeout)});async function pe(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Fe(t,e,{db:null,port:r,server:null});let{debug:o}=e,s=await(t==="shadow_database"?Jt:Ge)(e.pgliteDataDirPath,o);o&&s.onNotification((i,u)=>{console.debug(`[${t}][${i}] ${u}`)});let{PGLiteSocketServer:a}=await import("@electric-sql/pglite-socket"),c=new a({db:s,debug:o,inspect:o,port:r});o&&(c.addEventListener("listening",i=>{let{detail:u}=i;console.debug(`[${t}] server listening on ${JSON.stringify(u)}`)}),c.addEventListener("connection",i=>{let{clientAddress:u,clientPort:l}=i.detail;console.debug(`[${t}] client connected from ${u}:${l}`)}),c.addEventListener("error",i=>{let{detail:u}=i;console.error(`[${t}] server error:`,u)}));try{await c.start()}catch(i){throw i instanceof Error&&"code"in i&&i.code==="EADDRINUSE"?new E(r):i}return Fe(t,e,{db:s,port:r,server:c})}function Fe(t,e,r){let{debug:o}=e,{db:n,port:s,server:a}=r||{};return o&&console.debug(`[${t}] server started on port ${s}`),{...b,close:async()=>{let c=[];try{await a?.stop(),o&&console.debug(`[${t}] server stopped on port ${s}`)}catch(i){console.error(`[${t}] server stop error`,i),c.push(i)}if(t==="database")try{await n?.syncToFs(),o&&console.debug(`[${t}] synced to filesystem`)}catch(i){console.error(`[${t}] sync error`,i),c.push(i)}try{await n?.close(),o&&console.debug(`[${t}] closed`)}catch(i){console.error(`[${t}] close error`,i),c.push(i)}if(c.length>0)throw new AggregateError(c,`Failed to close ${t} properly`)},connectionString:qe(s,Ke),dump:async c=>{t==="shadow_database"||!n||await Qt({db:n,debug:o,destinationPath:c})},port:s,prismaORMConnectionString:qe(s,Gt),terminalCommand:`PGPASSWORD=${b.password} PGSSLMODE=${b.sslMode} psql -h localhost -p ${s} -U ${b.username} -d ${b.database}`}}function qe(t,e){return`${Kt}:${t}/${b.database}?${e.toString()}`}async function Ge(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:b.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:b.username})}async function Jt(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:b.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:b.username})}async function Qt(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Ge(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),c=await a({args:["--schema-only","--no-owner"],fileName:n?(0,Ve.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await He(c,n)):(o&&console.debug("[DB] Dumping database to memory"),await c.text())}p();var yt=require("http"),bt=require("util"),Pt=w(require("@prisma/get-platform"),1);me();fe();async function St(t,e){let{port:r}=e;if(e.dryRun)return gt(r,null);let o=await or(r,t,e),{promise:n,reject:s,resolve:a}=X(),{serve:c}=await import("@hono/node-server"),i=c({createServer:yt.createServer,fetch:o.fetch,overrideGlobalObjects:!1,port:r},a);return i.on("error",u=>{if(typeof u=="object"&&"code"in u&&u.code==="EADDRINUSE")return s(new E(r));console.error("[Accelerate]",u)}),await n,gt(r,i)}function gt(t,e){return{async close(){e&&await Promise.allSettled([(0,bt.promisify)(e.close.bind(e))(),L.stopAll()])},port:t,url:`http://localhost:${t}`}}async function or(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(lt(),ut)),Promise.resolve().then(()=>(ht(),ft))]),c=new n,i=await Pt.default.getPlatformInfo();if(o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(i)),o){let{logger:l}=await import("hono/logger");c.use("*",l((...g)=>console.log("[Accelerate]",...g)))}c.use("*",async(l,g)=>(l.set("db",e),l.set("debug",!!o),l.set("platform",i),l.set("port",t),l.set("protocol","http"),l.set("serverState",r),l.set("shadowDBPort",r.shadowDatabasePort),await g()));let u=new n;return u.route("/",s),u.route("/",a),c.route("/",u),c}p();var Ot=require("fs/promises"),x=require("pathe"),re=require("proper-lockfile"),Ee=require("std-env"),d=require("valibot");Q();p();var wt=require("std-env");function vt(t,e){if(t==null)return!1;try{return wt.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var we=(0,d.pipe)((0,d.string)(),(0,d.url)()),Dt=(0,d.object)({connectionString:we,prismaORMConnectionString:(0,d.optional)(we),terminalCommand:(0,d.optional)((0,d.string)())}),Et=(0,d.object)({url:we}),Pe=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),nr=(0,d.object)({database:Dt,http:Et,ppg:Et,shadowDatabase:Dt}),sr=(0,d.object)({databasePort:Pe,exports:(0,d.optional)(nr),name:(0,d.pipe)((0,d.string)(),(0,d.minLength)(1)),pid:(0,d.optional)((0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(0))),port:Pe,shadowDatabasePort:Pe,version:(0,d.literal)("1")}),Oe=Symbol("initialize"),Se="default",O=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??T,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??Se,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Ee.process.pid,this._port=e.port??T,this._shadowDatabasePort=e.shadowDatabasePort??T}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new F(e):new ve(e);return await r[Oe](),r}static async fromServerDump(e){let{debug:r,name:o=Se}=e??{},n=M(o),s=F.getServerDumpPath(n),a=await Le(s);if(a==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(a));let{issues:c,output:i,success:u}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),sr),a);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
7
+ ${JSON.stringify(c,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new F({databasePort:i.databasePort,debug:r,dryRun:!1,name:o,pid:i.pid,port:i.port,serverDump:i,shadowDatabasePort:i.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},o=(0,x.join)(M(Se),"..");r&&console.debug(`[State] scanning for server states in: ${o}`);let n=await Me(o);return r&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(s=>ar(s,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},ve=class extends O{constructor(e){super({...e,databasePort:e?.databasePort??I,persistenceMode:"stateless",port:e?.port??C,shadowDatabasePort:e?.shadowDatabasePort??B})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Oe](){}async close(){}async writeServerDump(){}},F=class t extends O{#r;#e;#t;#s;#o;#n=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=M(this.name),this.#r=(0,x.join)(this.#e,"db_dump.bak"),this.#t=(0,x.join)(this.#e,".pglite"),this.#o=e?.serverDump??null,this.#s=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,x.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#o?.exports}get pgliteDataDirPath(){return this.#t}async[Oe](){await je(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#n=await(0,re.lock)(this.#e,{lockfilePath:(0,x.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await O.scan({debug:this.debug,onlyMetadata:!0}),r=await Ne({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new q(this):e}}async close(){if(this.#n!=null)try{await this.#n(),this.#n=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.#o={name:this.name,version:"1",pid:Ee.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,Ot.writeFile)(this.#s,`${JSON.stringify(this.#o,null,2)}
8
+ `,{encoding:"utf-8"})}};async function ar(t,e){let{debug:r,onlyMetadata:o}=e||{},n={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await O.fromServerDump({debug:r,name:t});if(!s)return r&&console.debug(`[State] no server state found for name: ${t}`),{...n,status:"no_such_server"};n.databasePort=s.databasePort,n.exports=s.exports,n.pid=s.pid,n.port=s.port,n.shadowDatabasePort=s.shadowDatabasePort;let{exports:a,pid:c}=s;if(o)return{...n,status:"unknown"};if(!vt(c,r))return r&&console.debug(`[State] server state for "${t}" has no running process with PID: ${c}`),{...n,status:"not_running"};let i=M(t);try{if(!await(0,re.check)(i,{lockfilePath:(0,x.join)(i,".lock")}))return r&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...n,status:"starting_up"}}catch(_){r&&console.error(`[State] server state for "${t}" failed to check lock:`,_)}if(!a)return{...n,status:"starting_up"};let{http:u}=a,{hc:l}=await import("hono/client"),g=await l(u.url).health.$get();if(!g.ok)return r&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(g)}`),{...n,status:"not_running"};let y=await g.json();return y.name!==t?(r&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(y)}`),{...n,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(y)}`),{...n,status:"running"})}catch(s){return r&&console.error(`[State] failed to get server status for "${t}":`,s),{...n,status:"error"}}}var De=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},q=class extends De{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return O.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function ir(t){let e=await O.createExclusively(t),[r,o]=await Promise.all([pe("database",e),pe("shadow_database",e)]),n=await St(r,e),s=`prisma+postgres://localhost:${n.port}/?${new URLSearchParams({api_key:Ae({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:o.prismaORMConnectionString})}).toString()}`,a={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:n.url},ppg:{url:s},shadowDatabase:{connectionString:o.prismaORMConnectionString,prismaORMConnectionString:o.prismaORMConnectionString,terminalCommand:o.terminalCommand}};return await e.writeServerDump(a),{...a,close:()=>c(e,[n,r,o]),name:e.name};async function c(i,u){let g=(await Promise.allSettled(u.map(y=>y.close()))).filter(y=>y.status==="rejected").map(y=>new Error(y.reason));try{await i.close()}catch(y){g.push(y)}if(g.length>0)throw new AggregateError(g,"Failed to close some servers")}}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,PortNotAvailableError,ServerAlreadyRunningError,unstable_startServer});
package/dist/index.d.cts CHANGED
@@ -9,10 +9,9 @@ declare const DEFAULT_SERVER_PORT = 51213;
9
9
  declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
10
10
  type PortAssignableService = DBServerPurpose | "server";
11
11
  declare class PortNotAvailableError extends Error {
12
- port: number;
13
- service: PortAssignableService;
12
+ readonly port: number;
14
13
  name: string;
15
- constructor(port: number, service: PortAssignableService);
14
+ constructor(port: number);
16
15
  }
17
16
 
18
17
  interface Server extends Exports {
package/dist/index.d.ts CHANGED
@@ -9,10 +9,9 @@ declare const DEFAULT_SERVER_PORT = 51213;
9
9
  declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
10
10
  type PortAssignableService = DBServerPurpose | "server";
11
11
  declare class PortNotAvailableError extends Error {
12
- port: number;
13
- service: PortAssignableService;
12
+ readonly port: number;
14
13
  name: string;
15
- constructor(port: number, service: PortAssignableService);
14
+ constructor(port: number);
16
15
  }
17
16
 
18
17
  interface Server extends Exports {
package/dist/index.js CHANGED
@@ -1,6 +1 @@
1
- import{a as k}from"./chunk-GBG44OEG.js";import{a as q,c as le}from"./chunk-LBY4H4LD.js";import{a as B,c as L,d as M,i as et,j as tt,k as nt,l as N}from"./chunk-Q3M6SQC2.js";import{HTTPException as h}from"hono/http-exception";import{minLength as ue,object as me,optional as de,parseJson as ge,pipe as R,regex as K,safeParse as he,string as T,url as U}from"valibot";var V=/^(postgres|postgresql):\/\//,fe=R(T(),ge(),me({databaseUrl:R(T(),U(),K(V)),name:de(R(T(),ue(1))),shadowDatabaseUrl:R(T(),U(),K(V))}));function F(n){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(n).sort(([[e],[t]])=>e.localeCompare(t)))),"utf8").toString("base64url")}function ye(n){let e=Buffer.from(n,"base64url").toString("utf8"),{issues:t,output:r,success:o}=he(fe,e,{abortEarly:!0});return o?[null,r]:[t]}var f=(n,e)=>{let{authorization:t}=n;if(!t)throw new h(401,{message:"Missing API Key"});let[r,o="",s]=t.split(" ");if(r!=="Bearer"||s)throw new h(401,{message:"Invalid API Key"});let[i,a]=ye(o);if(i)throw new h(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:p,name:c,shadowDatabaseUrl:g}=a,{name:u}=e.get("serverState");if(!c)throw new h(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${u}" server's output for the updated \`DATABASE_URL\` value.`});if(c!==u)throw new h(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${u}", but the API Key is for "${c}"`});let{hostname:l,port:E}=new URL(p),{port:x}=e.get("db"),{hostname:ae,port:ce}=new URL(g),pe=e.get("shadowDBPort");if(l!=="localhost"||Number(E)!==x||ae!=="localhost"||Number(ce)!==pe)throw new h(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:a}};import{createServer as Ge}from"http";import{promisify as Je}from"util";import{serve as We}from"@hono/node-server";import Xe from"@prisma/get-platform";function A(n){let e,t,r=new Promise((i,a)=>{e=i,t=a}),o=i=>{o=s=null,t(i),n?.onRejected?.(i),n?.onFulfilled?.()},s=i=>{s=o=null,e(i),n?.onResolved?.(i),n?.onFulfilled?.()};return{isFulfilled:()=>s===o,promise:r,reject:i=>o?.(i),resolve:i=>s?.(i)}}import{logger as Ye}from"hono/logger";import{Hono as se}from"hono/tiny";import{Hono as Ue}from"hono/tiny";import{validator as v}from"hono/validator";import{array as we,literal as Se,minLength as ve,object as be,pipe as Pe,safeParse as Ee,string as Re,union as Te}from"valibot";var Ae=be({tags:Te([Pe(we(Re()),ve(1)),Se("all")])});async function Q(n){let{output:e,success:t}=Ee(Ae,await n.req.json(),{abortEarly:!0});return t?e:n.text("Invalid input",400)}import{spawn as Oe}from"child_process";import{once as He}from"events";import{mkdir as Ce}from"fs/promises";import{join as Ie}from"path";import{setTimeout as xe}from"timers/promises";import{proxySignals as ke}from"foreground-child/proxy-signals";import{process as $e}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:De,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:je,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:z}=$e.env,w=class n{static#n=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:t}=e,r=`${e.schemaHash}:${e.clientVersion}`;try{let o=n.#n.get(r);if(o)return o;let s=new n(e);return n.#n.set(r,s),t&&console.debug("[Query Engine] starting...",e),await s.start(),t&&console.debug("[Query Engine] started!"),s}finally{n.stopAll(r)}}static async stopAll(e){let r=(await Promise.allSettled(Array.from(n.#n.entries()).filter(([o])=>o!==e).map(async([o,s])=>{try{await s.stop()}finally{n.#n.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(r.length>0)throw new AggregateError(r,"Failed to stop engines")}async commitTransaction(e,t){return await this.#o(e,t,"commit")}async request(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(r,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await y.fromResponse(s);return await s.text()}async rollbackTransaction(e,t){return await this.#o(e,t,"rollback")}async startTransaction(e,t){let{url:r}=await this.start(),o=this.#r(t),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(e),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await y.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:t,resolve:r}=A();this.#t=e;let o=je||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Oe(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});ke(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=c=>{let g=c.split(`
2
- `).find(x=>x.includes("Started query engine http server"));if(!g)return;s.stdout.removeListener("data",i);let{fields:u}=JSON.parse(g);if(u==null)return t(new Error(`Unexpected data during initialization, "fields" are missing: ${c}`));let{ip:l,port:E}=u;if(l==null||E==null)return t(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
- Received data: ${c}`));r({childProcess:s,url:`http://${l}:${E}`})},a=c=>{this.#t=null,t(new S(String(c))),s.removeListener("exit",p),s.kill()};s.once("error",a);let p=(c,g)=>{this.#t=null,t(new S(`Query Engine exited with code ${c} and signal ${g}`))};return s.once("exit",p),s.stdout.on("data",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 He(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=B(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await Ce(t,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=Ie(t,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(De==="1"||await L(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}`);z&&await xe(Number(z)),await M(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 y.fromResponse(i);try{return await i.json()}catch{return{}}}};function O(n,e){return console.error(n),n instanceof S?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:n.message}}}},500):n instanceof y?e.text(n.responseBody,n.statusCode):e.body(null,500)}var S=class extends Error{name="EngineStartError"},y=class n extends Error{constructor(t,r,o){super(`${t}: Query Engine response status ${r}, body: ${o}`);this.action=t;this.statusCode=r;this.responseBody=o}name="EngineHttpError";static async fromResponse(t){let r=new URL(t.url),o=await t.text();return new n(r.pathname,t.status,o)}};import{Buffer as G}from"buffer";var H=new Map;async function $(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function J(n){let e=n.req.param("schemaHash"),t=H.get(e);return t==null?n.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:t}}var _e=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function W(n,e){let t=G.from(n,"base64").toString("utf8"),r=`datasource db {
4
- provider = "postgresql"
5
- url = "${e.toString()}"
6
- }`,o=t.replace(_e,r),s=await $(o);return{base64Override:G.from(o,"utf8").toString("base64"),overrideHash:s}}function C(n){let{req:e}=n;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}import{integer as X,looseObject as Be,minValue as Y,number as D,object as Le,optional as Me,pipe as Z,safeParse as ee,string as te,union as Ne}from"valibot";var qe=Le({isolation_level:Me(te()),max_wait:Z(D(),X(),Y(0)),timeout:Z(D(),X(),Y(0))});async function ne(n){let{issues:e,output:t,success:r}=ee(qe,await n.req.json(),{abortEarly:!0});return r?t:n.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}var Ke=Be({id:Ne([te(),D()])});function re(n,e){let{output:t,success:r}=ee(Ke,n);return r?t:e.json({EngineMalfunction:{}},500)}var b=new Ue;b.post("/invalidate",v("header",f),async n=>{let e=await Q(n);return e instanceof Response?e:n.body(null)});var Ve="/:clientVersion/:schemaHash",P=b.basePath(Ve);b.route("/",P);var Fe=["/graphql","/itx/:transactionId/graphql"];P.on("POST",[...Fe],v("header",f),async n=>{let{req:e}=n;try{let t=await j(n);if(t instanceof Response)return t;let r=await e.text(),o=e.param("transactionId"),s=await t.request(r,{...C(n),"X-transaction-id":o});return n.text(s)}catch(t){return O(t,n)}});P.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],v("header",f),async n=>{let{req:e}=n;try{let t=await j(n);if(t instanceof Response)return t;let o=`${e.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=e.param("transactionId"),i=await t[o](s,C(n));return n.json(i)}catch(t){return O(t,n)}});P.put("/schema",v("header",f),async n=>{let{req:e}=n,t=await e.text();if(!t)return n.text("Missing schema",400);let r=e.param("schemaHash"),o=H.get(r);if(o==null){if(r!==await $(t))return n.text("Schema hash mismatch",400);let s=await W(t,n.get("db").prismaORMConnectionString);return H.set(r,{base64Original:t,...s}),n.text(r)}return t!==o.base64Original?n.text("Schema mismatch",400):n.text(r)});P.post("/transaction/start",v("header",f),async n=>{let{req:e}=n,t=await ne(n);if(t instanceof Response)return t;try{let r=await j(n);if(r instanceof Response)return r;let o=await r.startTransaction(t,C(n)),s=re(o,n);if(s instanceof Response)return s;let{id:i}=s,a=e.param("clientVersion"),p=n.get("port"),c=n.get("protocol"),g=e.param("schemaHash");return n.json({...o,"data-proxy":{endpoint:`${c}://localhost:${p}/${a}/${g}/itx/${i}`}})}catch(r){return O(r,n)}});async function j(n){let{req:e}=n,t=J(n);if(t instanceof Response)return t;let{base64Override:r,overrideHash:o}=t.schemas;return await w.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.param("clientVersion"),debug:n.get("debug"),platform:n.get("platform"),schemaHash:o})}import{Hono as Qe}from"hono/tiny";import{StatusCodes as ze}from"http-status-codes";var I=new Qe;I.post("/database/dump",async n=>{let e=n.get("db"),t=n.get("serverState");return await e.dump(t.databaseDumpPath),n.json({dumpPath:t.databaseDumpPath},ze.CREATED)});var Vt=I.get("/health",n=>n.json({name:n.get("serverState").name}));async function ie(n,e){let{port:t}=e;if(e.dryRun)return oe(t,null);let r=await Ze(t,n,e),{promise:o,reject:s,resolve:i}=A(),a=We({createServer:Ge,fetch:r.fetch,overrideGlobalObjects:!1,port:t},i);return a.on("error",p=>{if(typeof p=="object"&&"code"in p&&p.code==="EADDRINUSE")return s(new N(t,"server"));console.error("[Accelerate]",p)}),await o,oe(t,a)}function oe(n,e){return{async close(){e&&await Promise.allSettled([Je(e.close.bind(e))(),w.stopAll()])},port:n,url:`http://localhost:${n}`}}async function Ze(n,e,t){let{debug:r}=t,o=new se,s=await Xe.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",Ye((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",e),i.set("debug",!!r),i.set("platform",s),i.set("port",n),i.set("protocol","http"),i.set("serverState",t),i.set("shadowDBPort",t.shadowDatabasePort),await a())),o.route("/",_),o}var _=new se;_.route("/",b);_.route("/",I);async function un(n){let e=await q.createExclusively(n),[t,r]=await Promise.all([k("database",e),k("shadow_database",e)]),o=await ie(t,e),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:F({databaseUrl:t.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:r.prismaORMConnectionString})}).toString()}`,i={database:{connectionString:t.connectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:r.prismaORMConnectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand}};return await e.writeServerDump(i),{...i,close:()=>a(e,[o,t,r]),name:e.name};async function a(p,c){let u=(await Promise.allSettled(c.map(l=>l.close()))).filter(l=>l.status==="rejected").map(l=>new Error(l.reason));try{await p.close()}catch(l){u.push(l)}if(u.length>0)throw new AggregateError(u,"Failed to close some servers")}}export{et as DEFAULT_DATABASE_PORT,tt as DEFAULT_SERVER_PORT,nt as DEFAULT_SHADOW_DATABASE_PORT,N as PortNotAvailableError,le as ServerAlreadyRunningError,un as unstable_startServer};
1
+ import{a as f}from"./chunk-GUT43IYK.js";import{a as w,c as R}from"./chunk-VPXPYVXN.js";import{a as h,b,c as A,f as d}from"./chunk-LMPFMHCB.js";import{a as u,c as v,d as g}from"./chunk-354SKE3R.js";import"./chunk-I55EQWKN.js";import{createServer as D}from"http";import{promisify as O}from"util";import C from"@prisma/get-platform";async function P(a,e){let{port:r}=e;if(e.dryRun)return y(r,null);let t=await x(r,a,e),{promise:s,reject:S,resolve:c}=v(),{serve:i}=await import("@hono/node-server"),m=i({createServer:D,fetch:t.fetch,overrideGlobalObjects:!1,port:r},c);return m.on("error",o=>{if(typeof o=="object"&&"code"in o&&o.code==="EADDRINUSE")return S(new d(r));console.error("[Accelerate]",o)}),await s,y(r,m)}function y(a,e){return{async close(){e&&await Promise.allSettled([O(e.close.bind(e))(),g.stopAll()])},port:a,url:`http://localhost:${a}`}}async function x(a,e,r){let{debug:t}=r,[{Hono:s},{accelerateRoute:S},{utilityRoute:c}]=await Promise.all([import("hono/tiny"),import("./accelerate-44Q3JQWR.js"),import("./utility-YJ4TFSMW.js")]),i=new s,m=await C.getPlatformInfo();if(t&&console.debug("[Accelerate] platform info: %s",JSON.stringify(m)),t){let{logger:n}=await import("hono/logger");i.use("*",n((...p)=>console.log("[Accelerate]",...p)))}i.use("*",async(n,p)=>(n.set("db",e),n.set("debug",!!t),n.set("platform",m),n.set("port",a),n.set("protocol","http"),n.set("serverState",r),n.set("shadowDBPort",r.shadowDatabasePort),await p()));let o=new s;return o.route("/",S),o.route("/",c),i.route("/",o),i}async function G(a){let e=await w.createExclusively(a),[r,t]=await Promise.all([f("database",e),f("shadow_database",e)]),s=await P(r,e),S=`prisma+postgres://localhost:${s.port}/?${new URLSearchParams({api_key:u({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`,c={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:s.url},ppg:{url:S},shadowDatabase:{connectionString:t.prismaORMConnectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand}};return await e.writeServerDump(c),{...c,close:()=>i(e,[s,r,t]),name:e.name};async function i(m,o){let p=(await Promise.allSettled(o.map(l=>l.close()))).filter(l=>l.status==="rejected").map(l=>new Error(l.reason));try{await m.close()}catch(l){p.push(l)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}export{h as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,A as DEFAULT_SHADOW_DATABASE_PORT,d as PortNotAvailableError,R as ServerAlreadyRunningError,G as unstable_startServer};
package/dist/state.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var K=Object.create;var b=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var q=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var Q=(t,e)=>{for(var r in e)b(t,r,{get:e[r],enumerable:!0})},L=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Z(e))!z.call(t,n)&&n!==r&&b(t,n,{get:()=>e[n],enumerable:!(i=Y(e,n))||i.enumerable});return t};var E=(t,e,r)=>(r=t!=null?K(q(t)):{},L(e||!t||!t.__esModule?b(r,"default",{value:t,enumerable:!0}):r,t)),ee=t=>L(b({},"__esModule",{value:!0}),t);var le={};Q(le,{ServerAlreadyRunningError:()=>w,ServerState:()=>l,ServerStateAlreadyExistsError:()=>y});module.exports=ee(le);var G=require("fs/promises"),W=require("hono/client"),d=require("pathe"),x=require("proper-lockfile"),v=require("std-env"),s=require("valibot");var F=require("fs"),a=require("fs/promises");var o=E(require("path"),1),O=E(require("os"),1),D=E(require("process"),1),p=O.default.homedir(),_=O.default.tmpdir(),{env:h}=D.default,te=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(_,t)}},re=t=>{let e=h.APPDATA||o.default.join(p,"AppData","Roaming"),r=h.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(_,t)}},se=t=>{let e=o.default.basename(p);return{data:o.default.join(h.XDG_DATA_HOME||o.default.join(p,".local","share"),t),config:o.default.join(h.XDG_CONFIG_HOME||o.default.join(p,".config"),t),cache:o.default.join(h.XDG_CACHE_HOME||o.default.join(p,".cache"),t),log:o.default.join(h.XDG_STATE_HOME||o.default.join(p,".local","state"),t),temp:o.default.join(_,e,t)}};function T(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"?te(t):D.default.platform==="win32"?re(t):se(t)}var oe=require("pako"),ie=T("prisma-dev");function g(t){return`${ie.data}/${t}`}function I(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function N(t){try{return await(0,a.readFile)(t,{encoding:"utf-8"})}catch(e){if(I(e))return null;throw e}}async function V(t){await(0,a.mkdir)(t,{recursive:!0})}async function C(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(I(e))return[];throw e}}var B=require("std-env");function H(t,e){if(t==null)return!1;try{return B.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var j=(0,s.pipe)((0,s.string)(),(0,s.url)()),J=(0,s.object)({connectionString:j,prismaORMConnectionString:(0,s.optional)(j),terminalCommand:(0,s.optional)((0,s.string)())}),U=(0,s.object)({url:j}),$=(0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(1)),ue=(0,s.object)({database:J,http:U,ppg:U,shadowDatabase:J}),pe=(0,s.object)({databasePort:$,exports:(0,s.optional)(ue),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")}),M=Symbol("initialize"),R="default",l=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??R,this.persistenceMode=e.persistenceMode,this.pid=e.pid??v.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:v.process.pid}):new k(e);return await r[M](),r}static async fromServerDump(e){let{debug:r,name:i=R}=e??{},n=g(i),c=P.getServerDumpPath(n),m=await N(c);if(m==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(m));let{issues:A,output:u,success:f}=(0,s.safeParse)((0,s.pipe)((0,s.string)(),(0,s.parseJson)(),pe),m);if(!f)throw r&&console.debug(`[State] Invalid server dump file at "${c}":
2
- ${JSON.stringify(A,null,2)}`),new Error(`Invalid Prisma Dev state for "${i}".`);return new P({databasePort:u.databasePort,debug:r,dryRun:!1,name:i,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},i=(0,d.join)(g(R),"..");r&&console.debug(`[State] scanning for server states in: ${i}`);let n=await C(i);return r&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(c=>de(c,r)))}},k=class extends l{constructor(e){super({...e,persistenceMode:"stateless",pid:v.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[M](){}async close(){}async writeServerDump(){}},P=class t extends l{#t;#e;#o;#i;#r;#s=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=g(this.name),this.#t=(0,d.join)(this.#e,"db_dump.bak"),this.#o=(0,d.join)(this.#e,".pglite"),this.#r=e.serverDump??null,this.#i=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,d.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[M](){await V(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await(0,x.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 w(this):e}}async close(){if(this.#s!=null)try{await this.#s(),this.#s=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.#r={name:this.name,version:"1",pid:v.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,G.writeFile)(this.#i,`${JSON.stringify(this.#r,null,2)}
3
- `,{encoding:"utf-8"})}};async function de(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let i=await l.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(!H(c,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${c}`),{...r,status:"not_running"};let m=g(t);try{if(!await(0,x.check)(m,{lockfilePath:(0,d.join)(m,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(X){e&&console.error(`[State] server state for "${t}" failed to check lock:`,X)}if(!n)return{...r,status:"starting_up"};let{http:A}=n,u=await(0,W.hc)(A.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 f=await u.json();return f.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(f)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(f)}`),{...r,status:"running"})}catch(i){return e&&console.error(`[State] failed to get server status for "${t}":`,i),{...r,status:"error"}}}var y=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},w=class extends y{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return l.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError});
1
+ "use strict";var de=Object.create;var D=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var fe=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var me=(t,e)=>{for(var r in e)D(t,r,{get:e[r],enumerable:!0})},W=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of le(e))!he.call(t,a)&&a!==r&&D(t,a,{get:()=>e[a],enumerable:!(n=pe(e,a))||n.enumerable});return t};var O=(t,e,r)=>(r=t!=null?de(fe(t)):{},W(e||!t||!t.__esModule?D(r,"default",{value:t,enumerable:!0}):r,t)),Pe=t=>W(D({},"__esModule",{value:!0}),t);var $e={};me($e,{ServerAlreadyRunningError:()=>M,ServerState:()=>b,ServerStateAlreadyExistsError:()=>j});module.exports=Pe($e);var ue=require("fs/promises"),y=require("pathe"),L=require("proper-lockfile"),K=require("std-env"),o=require("valibot");var X=require("fs"),l=require("fs/promises"),z=require("util"),Y=require("zlib");var u=O(require("path"),1),B=O(require("os"),1),x=O(require("process"),1),h=B.default.homedir(),N=B.default.tmpdir(),{env:v}=x.default,be=t=>{let e=u.default.join(h,"Library");return{data:u.default.join(e,"Application Support",t),config:u.default.join(e,"Preferences",t),cache:u.default.join(e,"Caches",t),log:u.default.join(e,"Logs",t),temp:u.default.join(N,t)}},ge=t=>{let e=v.APPDATA||u.default.join(h,"AppData","Roaming"),r=v.LOCALAPPDATA||u.default.join(h,"AppData","Local");return{data:u.default.join(r,t,"Data"),config:u.default.join(e,t,"Config"),cache:u.default.join(r,t,"Cache"),log:u.default.join(r,t,"Log"),temp:u.default.join(N,t)}},ye=t=>{let e=u.default.basename(h);return{data:u.default.join(v.XDG_DATA_HOME||u.default.join(h,".local","share"),t),config:u.default.join(v.XDG_CONFIG_HOME||u.default.join(h,".config"),t),cache:u.default.join(v.XDG_CACHE_HOME||u.default.join(h,".cache"),t),log:u.default.join(v.XDG_STATE_HOME||u.default.join(h,".local","state"),t),temp:u.default.join(N,e,t)}};function F(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),x.default.platform==="darwin"?be(t):x.default.platform==="win32"?ge(t):ye(t)}var ve=F("prisma-dev"),je=(0,z.promisify)(Y.unzip);function S(t){return`${ve.data}/${t}`}function Z(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Q(t){try{return await(0,l.readFile)(t,{encoding:"utf-8"})}catch(e){if(Z(e))return null;throw e}}async function ee(t){await(0,l.mkdir)(t,{recursive:!0})}async function te(t){try{return(await(0,l.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 re=require("std-env");function se(t,e){if(t==null)return!1;try{return re.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var P=require("get-port-please"),R=require("remeda"),$=51214,A=51213,E=51215,T=65535,m=-1/0;async function ae(t){let{debug:e,name:r,requestedPorts:n,servers:a}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:c}=De(r,a);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(c)}`));let d={databasePort:m,port:m,shadowDatabasePort:m},i=["port","databasePort","shadowDatabasePort"];for(let p of i){let f=await Se({debug:e,portKey:p,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:c,requestedPorts:n})??await we({debug:e,pickedPorts:d,portKey:p,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:c});e&&console.debug(`Got port for "${p}": ${f}`),d[p]=f}return e&&console.debug(`Picked ports: ${JSON.stringify(d)}`),d}async function Se(t){let{debug:e,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:a,requestedPorts:s}=t,{[r]:c,...d}=s;if(oe(c))return await Oe({debug:e,otherRequestedPorts:d,portKey:r,portsUsedByOtherServers:n,requestedPort:c}),c;let i=a?.[r]??m;if(!oe(i))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let p=i in n;return p||Object.values(d).includes(i)?(e&&console.debug(`Port ${i} that was used last time for this server, ${p?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,P.checkPort)(i)===!1?(e&&console.debug(`Port ${i}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${i} for "${r}" as it was used last time and is available.`),i)}async function we(t){let{debug:e,pickedPorts:r,portKey:n,portsUsedByOtherServers:a,portsUsedByThisServerLastTime:s}=t,c=Math.max($,A,E)+1,d=[...Object.values(r),...Object.keys(a).map(Number),...Object.values(s||{})],i=Math.min(Math.max(c,...d)+100,T),p=(0,R.difference)((0,R.range)(c,i),d),f={port:A,databasePort:$,shadowDatabasePort:E}[n];try{return await(0,P.getPort)({port:f in a||Object.values(r).includes(f)||Object.values(s||{}).includes(f)?void 0:f,ports:p})}catch(g){if(g instanceof Error&&g.name==="GetPortError"&&i+1<=T)return e&&console.debug(`Expanding port lookup to range [${i+1}, ${T}].`),await(0,P.getPort)({portRange:[i+1,T]});throw g}}function oe(t){return t>=0}function De(t,e){let r={},n;for(let a of e){let{databasePort:s,port:c,shadowDatabasePort:d}=a;if(a.name===t){n={databasePort:s,port:c,shadowDatabasePort:d};continue}r[s]=!0,r[c]=!0,r[d]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}async function Oe(t){let{debug:e,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:a,requestedPort:s}=t;if(s in a)throw e&&console.error(`Port ${s} was requested for "${n}", but is already used by another server.`),new q(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${n}", but also for another key.`),new I(s);if((0,P.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${n}", but is unsafe.`),new k(s);if(await(0,P.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${n}", but is not available.`),new k(s)}var k=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},I=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},q=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};var H=(0,o.pipe)((0,o.string)(),(0,o.url)()),ne=(0,o.object)({connectionString:H,prismaORMConnectionString:(0,o.optional)(H),terminalCommand:(0,o.optional)((0,o.string)())}),ie=(0,o.object)({url:H}),V=(0,o.pipe)((0,o.number)(),(0,o.integer)(),(0,o.minValue)(1)),xe=(0,o.object)({database:ne,http:ie,ppg:ie,shadowDatabase:ne}),_e=(0,o.object)({databasePort:V,exports:(0,o.optional)(xe),name:(0,o.pipe)((0,o.string)(),(0,o.minLength)(1)),pid:(0,o.optional)((0,o.pipe)((0,o.number)(),(0,o.integer)(),(0,o.minValue)(0))),port:V,shadowDatabasePort:V,version:(0,o.literal)("1")}),G=Symbol("initialize"),C="default",b=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??m,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??C,this.persistenceMode=e.persistenceMode,this.pid=e.pid??K.process.pid,this._port=e.port??m,this._shadowDatabasePort=e.shadowDatabasePort??m}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new w(e):new J(e);return await r[G](),r}static async fromServerDump(e){let{debug:r,name:n=C}=e??{},a=S(n),s=w.getServerDumpPath(a),c=await Q(s);if(c==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(c));let{issues:d,output:i,success:p}=(0,o.safeParse)((0,o.pipe)((0,o.string)(),(0,o.parseJson)(),_e),c);if(!p)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
2
+ ${JSON.stringify(d,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new w({databasePort:i.databasePort,debug:r,dryRun:!1,name:n,pid:i.pid,port:i.port,serverDump:i,shadowDatabasePort:i.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},n=(0,y.join)(S(C),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let a=await te(n);return r&&console.debug(`[State] found server names: ${JSON.stringify(a)}`),await Promise.all(a.map(s=>Te(s,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},J=class extends b{constructor(e){super({...e,databasePort:e?.databasePort??$,persistenceMode:"stateless",port:e?.port??A,shadowDatabasePort:e?.shadowDatabasePort??E})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[G](){}async close(){}async writeServerDump(){}},w=class t extends b{#t;#e;#o;#a;#r;#s=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=S(this.name),this.#t=(0,y.join)(this.#e,"db_dump.bak"),this.#o=(0,y.join)(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,y.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[G](){await ee(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await(0,L.lock)(this.#e,{lockfilePath:(0,y.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await b.scan({debug:this.debug,onlyMetadata:!0}),r=await ae({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new M(this):e}}async close(){if(this.#s!=null)try{await this.#s(),this.#s=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.#r={name:this.name,version:"1",pid:K.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,ue.writeFile)(this.#a,`${JSON.stringify(this.#r,null,2)}
3
+ `,{encoding:"utf-8"})}};async function Te(t,e){let{debug:r,onlyMetadata:n}=e||{},a={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await b.fromServerDump({debug:r,name:t});if(!s)return r&&console.debug(`[State] no server state found for name: ${t}`),{...a,status:"no_such_server"};a.databasePort=s.databasePort,a.exports=s.exports,a.pid=s.pid,a.port=s.port,a.shadowDatabasePort=s.shadowDatabasePort;let{exports:c,pid:d}=s;if(n)return{...a,status:"unknown"};if(!se(d,r))return r&&console.debug(`[State] server state for "${t}" has no running process with PID: ${d}`),{...a,status:"not_running"};let i=S(t);try{if(!await(0,L.check)(i,{lockfilePath:(0,y.join)(i,".lock")}))return r&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(ce){r&&console.error(`[State] server state for "${t}" failed to check lock:`,ce)}if(!c)return{...a,status:"starting_up"};let{http:p}=c,{hc:f}=await import("hono/client"),g=await f(p.url).health.$get();if(!g.ok)return r&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(g)}`),{...a,status:"not_running"};let U=await g.json();return U.name!==t?(r&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(U)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(U)}`),{...a,status:"running"})}catch(s){return r&&console.error(`[State] failed to get server status for "${t}":`,s),{...a,status:"error"}}}var j=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},M=class extends j{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return b.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError});
package/dist/state.d.cts CHANGED
@@ -101,20 +101,21 @@ type ResolvedServerOptions = Required<ServerOptions>;
101
101
  type PersistenceMode = "stateless" | "stateful";
102
102
  interface ScanOptions {
103
103
  debug?: boolean;
104
+ onlyMetadata?: boolean;
104
105
  }
105
106
  declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
106
107
  declare abstract class ServerState implements ResolvedServerOptions {
107
- readonly databasePort: number;
108
+ protected _databasePort: number;
108
109
  readonly debug: boolean;
109
110
  readonly dryRun: boolean;
110
111
  readonly name: string;
111
112
  readonly persistenceMode: PersistenceMode;
112
113
  readonly pid: number | undefined;
113
- readonly port: number;
114
- readonly shadowDatabasePort: number;
114
+ protected _port: number;
115
+ protected _shadowDatabasePort: number;
115
116
  protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
116
117
  persistenceMode: PersistenceMode;
117
- pid: number | undefined;
118
+ pid?: number | undefined;
118
119
  });
119
120
  static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
120
121
  static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
@@ -124,13 +125,16 @@ declare abstract class ServerState implements ResolvedServerOptions {
124
125
  abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
125
126
  abstract close(): Promise<void>;
126
127
  abstract writeServerDump(exports?: Exports): Promise<void>;
128
+ get databasePort(): number;
129
+ get port(): number;
130
+ get shadowDatabasePort(): number;
127
131
  }
128
132
  declare class StatefulServerState extends ServerState {
129
133
  #private;
130
- constructor(options: Omit<ServerOptions, "persistenceMode"> & {
131
- pid: number | undefined;
134
+ constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
135
+ pid?: number | undefined;
132
136
  serverDump?: ServerDumpV1;
133
- });
137
+ }) | undefined);
134
138
  static getServerDumpPath(dataDirPath: string): string;
135
139
  get databaseDumpPath(): string;
136
140
  get exports(): Exports | undefined;
package/dist/state.d.ts CHANGED
@@ -101,20 +101,21 @@ type ResolvedServerOptions = Required<ServerOptions>;
101
101
  type PersistenceMode = "stateless" | "stateful";
102
102
  interface ScanOptions {
103
103
  debug?: boolean;
104
+ onlyMetadata?: boolean;
104
105
  }
105
106
  declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
106
107
  declare abstract class ServerState implements ResolvedServerOptions {
107
- readonly databasePort: number;
108
+ protected _databasePort: number;
108
109
  readonly debug: boolean;
109
110
  readonly dryRun: boolean;
110
111
  readonly name: string;
111
112
  readonly persistenceMode: PersistenceMode;
112
113
  readonly pid: number | undefined;
113
- readonly port: number;
114
- readonly shadowDatabasePort: number;
114
+ protected _port: number;
115
+ protected _shadowDatabasePort: number;
115
116
  protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
116
117
  persistenceMode: PersistenceMode;
117
- pid: number | undefined;
118
+ pid?: number | undefined;
118
119
  });
119
120
  static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
120
121
  static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
@@ -124,13 +125,16 @@ declare abstract class ServerState implements ResolvedServerOptions {
124
125
  abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
125
126
  abstract close(): Promise<void>;
126
127
  abstract writeServerDump(exports?: Exports): Promise<void>;
128
+ get databasePort(): number;
129
+ get port(): number;
130
+ get shadowDatabasePort(): number;
127
131
  }
128
132
  declare class StatefulServerState extends ServerState {
129
133
  #private;
130
- constructor(options: Omit<ServerOptions, "persistenceMode"> & {
131
- pid: number | undefined;
134
+ constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
135
+ pid?: number | undefined;
132
136
  serverDump?: ServerDumpV1;
133
- });
137
+ }) | undefined);
134
138
  static getServerDumpPath(dataDirPath: string): string;
135
139
  get databaseDumpPath(): string;
136
140
  get exports(): Exports | undefined;
package/dist/state.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c}from"./chunk-LBY4H4LD.js";import"./chunk-Q3M6SQC2.js";export{c as ServerAlreadyRunningError,a as ServerState,b as ServerStateAlreadyExistsError};
1
+ import{a,b,c}from"./chunk-VPXPYVXN.js";import"./chunk-LMPFMHCB.js";import"./chunk-I55EQWKN.js";export{c as ServerAlreadyRunningError,a as ServerState,b as ServerStateAlreadyExistsError};
@@ -0,0 +1 @@
1
+ import{Hono as r}from"hono/tiny";import{StatusCodes as n}from"http-status-codes";var a=new r;a.post("/database/dump",async t=>{let o=t.get("db"),e=t.get("serverState");return await o.dump(e.databaseDumpPath),t.json({dumpPath:e.databaseDumpPath},n.CREATED)});var u=a.get("/health",t=>t.json({name:t.get("serverState").name}));export{a as utilityRoute};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/dev",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -66,11 +66,11 @@
66
66
  "@types/node": "22.15.21",
67
67
  "@types/pako": "2.0.3",
68
68
  "@types/proper-lockfile": "4.1.4",
69
+ "env-paths": "3.0.0",
69
70
  "pkg-types": "2.1.0",
70
71
  "tsup": "8.5.0",
71
72
  "typescript": "5.8.3",
72
73
  "vitest": "3.1.4",
73
- "env-paths": "3.0.0",
74
74
  "common-stuff": "^0.0.0"
75
75
  },
76
76
  "dependencies": {
@@ -80,12 +80,12 @@
80
80
  "@hono/node-server": "1.14.2",
81
81
  "@prisma/get-platform": "6.8.2",
82
82
  "foreground-child": "3.3.1",
83
+ "get-port-please": "3.1.2",
83
84
  "hono": "4.7.10",
84
85
  "http-status-codes": "2.3.0",
85
- "pako": "2.1.0",
86
86
  "pathe": "2.0.3",
87
87
  "proper-lockfile": "4.1.2",
88
- "read-last-lines-ts": "1.2.1",
88
+ "remeda": "2.21.3",
89
89
  "sock-daemon": "1.4.2",
90
90
  "std-env": "3.9.0",
91
91
  "valibot": "1.1.0"
@@ -1 +0,0 @@
1
- import{e as l,l as m}from"./chunk-Q3M6SQC2.js";import{PGlite as b}from"@electric-sql/pglite";import{PGLiteSocketServer as P}from"@electric-sql/pglite-socket";import{filename as w}from"pathe/utils";var n={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},y=`postgres://${n.username}:${n.password}@localhost`,f=new URLSearchParams({sslmode:n.sslMode}),p=new URLSearchParams({...Object.fromEntries(f.entries()),connection_limit:String(n.connectionLimit),connect_timeout:String(n.connectTimeout),max_idle_connection_lifetime:String(n.maxIdleConnectionLifetime),pool_timeout:String(n.poolTimeout),single_use_connections:"true",socket_timeout:String(n.socketTimeout)});async function L(e,o){let c=e==="database"?o.databasePort:o.shadowDatabasePort;if(o.dryRun)return u(e,o,{db:null,port:c,server:null});let{debug:a}=o,i=await(e==="shadow_database"?v:D)(o.pgliteDataDirPath,a);a&&i.onNotification((t,r)=>{console.debug(`[${e}][${t}] ${r}`)});let d=new P({db:i,debug:a,inspect:a,port:c});a&&(d.addEventListener("listening",t=>{let{detail:r}=t;console.debug(`[${e}] server listening on ${JSON.stringify(r)}`)}),d.addEventListener("connection",t=>{let{clientAddress:r,clientPort:S}=t.detail;console.debug(`[${e}] client connected from ${r}:${S}`)}),d.addEventListener("error",t=>{let{detail:r}=t;console.error(`[${e}] server error:`,r)}));try{await d.start()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="EADDRINUSE"?new m(c,e):t}return u(e,o,{db:i,port:c,server:d})}function u(e,o,c){let{debug:a}=o,{db:s,port:i,server:d}=c||{};return a&&console.debug(`[${e}] server started on port ${i}`),{...n,close:async()=>{let t=[];try{await d?.stop(),a&&console.debug(`[${e}] server stopped on port ${i}`)}catch(r){console.error(`[${e}] server stop error`,r),t.push(r)}if(e==="database")try{await s?.syncToFs(),a&&console.debug(`[${e}] synced to filesystem`)}catch(r){console.error(`[${e}] sync error`,r),t.push(r)}try{await s?.close(),a&&console.debug(`[${e}] closed`)}catch(r){console.error(`[${e}] close error`,r),t.push(r)}if(t.length>0)throw new AggregateError(t,`Failed to close ${e} properly`)},connectionString:g(i,f),dump:async t=>{e==="shadow_database"||!s||await $({db:s,debug:a,destinationPath:t})},port:i,prismaORMConnectionString:g(i,p),terminalCommand:`PGPASSWORD=${n.password} PGSSLMODE=${n.sslMode} psql -h localhost -p ${i} -U ${n.username} -d ${n.database}`}}function g(e,o){return`${y}:${e}/${n.database}?${o.toString()}`}async function D(e,o){return await b.create({database:n.database,dataDir:e,debug:o?5:void 0,relaxedDurability:!1,username:n.username})}async function v(e,o){return await b.create({database:n.database,dataDir:"memory://",debug:o?5:void 0,relaxedDurability:!1,username:n.username})}async function $(e){let{dataDir:o,db:c,debug:a,destinationPath:s}=e,i=c||await D(o,a),{pgDump:d}=await import("@electric-sql/pglite-tools/pg_dump"),t=await d({args:["--schema-only","--no-owner"],fileName:s?w(s):void 0,pg:await i.clone()});return s?(a&&console.debug(`[DB] Dumping database to ${s}`),await l(t,s)):(a&&console.debug("[DB] Dumping database to memory"),await t.text())}export{L as a,$ as b};
@@ -1,3 +0,0 @@
1
- import{b as p,f as E,g as $,h as R,i as _,j as k,k as A}from"./chunk-Q3M6SQC2.js";import{writeFile as B}from"fs/promises";import{hc as C}from"hono/client";import{join as u}from"pathe";import{check as H,lock as Y}from"proper-lockfile";import{process as m}from"std-env";import{integer as V,literal as Z,minLength as q,minValue as N,number as L,object as g,optional as f,parseJson as z,pipe as h,safeParse as K,string as b,url as W}from"valibot";import{process as j}from"std-env";function M(r,e){if(r==null)return!1;try{return j.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}var D=h(b(),W()),I=g({connectionString:D,prismaORMConnectionString:f(D),terminalCommand:f(b())}),T=g({url:D}),S=h(L(),V(),N(1)),G=g({database:I,http:T,ppg:T,shadowDatabase:I}),Q=g({databasePort:S,exports:f(G),name:h(b(),q(1)),pid:f(h(L(),V(),N(0))),port:S,shadowDatabasePort:S,version:Z("1")}),O=Symbol("initialize"),P="default",d=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??P,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 l({...e,pid:m.pid}):new y(e);return await t[O](),t}static async fromServerDump(e){let{debug:t,name:s=P}=e??{},n=p(s),a=l.getServerDumpPath(n),i=await E(a);if(i==null)return t&&console.debug(`[State] No server dump file found at: ${a}`),null;t&&(console.debug(`[State] server dump file found at "${a}":`),console.debug(i));let{issues:v,output:o,success:c}=K(h(b(),z(),Q),i);if(!c)throw t&&console.debug(`[State] Invalid server dump file at "${a}":
2
- ${JSON.stringify(v,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new l({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(p(P),"..");t&&console.debug(`[State] scanning for server states in: ${s}`);let n=await R(s);return t&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(a=>X(a,t)))}},y=class extends d{constructor(e){super({...e,persistenceMode:"stateless",pid:m.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[O](){}async close(){}async writeServerDump(){}},l=class r extends d{#t;#e;#a;#o;#r;#s=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=p(this.name),this.#t=u(this.#e,"db_dump.bak"),this.#a=u(this.#e,".pglite"),this.#r=e.serverDump??null,this.#o=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return u(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#a}async[O](){await $(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await Y(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 x(this):e}}async close(){if(this.#s!=null)try{await this.#s(),this.#s=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.#r={name:this.name,version:"1",pid:m.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await B(this.#o,`${JSON.stringify(this.#r,null,2)}
3
- `,{encoding:"utf-8"})}};async function X(r,e){let t={databasePort:-1,exports:void 0,name:r,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await d.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(!M(a,e))return e&&console.debug(`[State] server state for "${r}" has no running process with PID: ${a}`),{...t,status:"not_running"};let i=p(r);try{if(!await H(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(F){e&&console.error(`[State] server state for "${r}" failed to check lock:`,F)}if(!n)return{...t,status:"starting_up"};let{http:v}=n,o=await C(v.url).health.$get();if(!o.ok)return e&&console.debug(`[State] server state for "${r}" is not live: ${JSON.stringify(o)}`),{...t,status:"not_running"};let c=await o.json();return c.name!==r?(e&&console.debug(`[State] server state for "${r}" has mismatched health response: ${JSON.stringify(c)}`),{...t,status:"unknown"}):(e&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(c)}`),{...t,status:"running"})}catch(s){return e&&console.error(`[State] failed to get server status for "${r}":`,s),{...t,status:"error"}}}var w=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},x=class extends w{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return d.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{d as a,w as b,x as c};
@@ -1 +0,0 @@
1
- import{createWriteStream as j,WriteStream as P}from"fs";import{access as y,chmod as E,constants as x,mkdir as T,readdir as w,readFile as _,writeFile as v}from"fs/promises";import o from"path";import g from"os";import c from"process";var i=g.homedir(),a=g.tmpdir(),{env:n}=c,m=r=>{let t=o.join(i,"Library");return{data:o.join(t,"Application Support",r),config:o.join(t,"Preferences",r),cache:o.join(t,"Caches",r),log:o.join(t,"Logs",r),temp:o.join(a,r)}},h=r=>{let t=n.APPDATA||o.join(i,"AppData","Roaming"),e=n.LOCALAPPDATA||o.join(i,"AppData","Local");return{data:o.join(e,r,"Data"),config:o.join(t,r,"Config"),cache:o.join(e,r,"Cache"),log:o.join(e,r,"Log"),temp:o.join(a,r)}},D=r=>{let t=o.basename(i);return{data:o.join(n.XDG_DATA_HOME||o.join(i,".local","share"),r),config:o.join(n.XDG_CONFIG_HOME||o.join(i,".config"),r),cache:o.join(n.XDG_CACHE_HOME||o.join(i,".cache"),r),log:o.join(n.XDG_STATE_HOME||o.join(i,".local","state"),r),temp:o.join(a,t,r)}};function p(r,{suffix:t="nodejs"}={}){if(typeof r!="string")throw new TypeError(`Expected a string, got ${typeof r}`);return t&&(r+=`-${t}`),c.platform==="darwin"?m(r):c.platform==="win32"?h(r):D(r)}import{inflate as O}from"pako";var d=p("prisma-dev");function G(r,t){return`${d.cache}/engine/${r}/${t}`}function N(r){return`${d.data}/${r}`}async function W(r){try{return await y(r,x.F_OK),!0}catch(t){if(u(t))return!1;throw t}}async function k(r,t){let e=O(r);await v(t,e),await E(t,"755")}async function M(r,t){await r.stream().pipeTo(P.toWeb(j(t,{encoding:"utf-8"})))}function u(r){return r!=null&&typeof r=="object"&&"code"in r&&r.code==="ENOENT"}async function X(r){try{return await _(r,{encoding:"utf-8"})}catch(t){if(u(t))return null;throw t}}async function U(r){await T(r,{recursive:!0})}async function I(r){try{return(await w(r,{withFileTypes:!0})).reduce((e,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&e.push(s.name),e),[])}catch(t){if(u(t))return[];throw t}}var V=51214,q=51213,z=51215,A=class extends Error{constructor(e,s){super(`Port number \`${e}\` is not available for service ${s}.`);this.port=e;this.service=s}name="PortNotAvailableError"};export{G as a,N as b,W as c,k as d,M as e,X as f,U as g,I as h,V as i,q as j,z as k,A as l};