@prisma/dev
Version:
A local Prisma Postgres server for development and testing
4 lines (3 loc) • 5.98 kB
JavaScript
import{b as f,d as w,e as y}from"./chunk-DWY47FQV.js";import{a as E,b as v,c as b}from"./chunk-DOJAPHLY.js";import{spawn as $}from"child_process";import{once as H}from"events";import{mkdir as C}from"fs/promises";import{join as A}from"path";import{setTimeout as j}from"timers/promises";function R(r){let e,t,s=new Promise((i,a)=>{e=i,t=a}),n=i=>{n=o=null,t(i),r?.onRejected?.(i),r?.onFulfilled?.()},o=i=>{o=n=null,e(i),r?.onResolved?.(i),r?.onFulfilled?.()};return{isFulfilled:()=>o===n,promise:s,reject:i=>n?.(i),resolve:i=>o?.(i)}}import{process as B}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:L,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:N,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:P}=B.env,S=class r{static#t=new Map;#e;#n;constructor(e){this.#e=e,this.#n=null}static async get(e){let{debug:t}=e,s=`${e.schemaHash}:${e.clientVersion}`;try{let n=r.#t.get(s);if(n)return n;let o=new r(e);return r.#t.set(s,o),t&&console.debug("[Query Engine] starting...",e),await o.start(),t&&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(([n])=>n!==e).map(async([n,o])=>{try{await o.stop()}finally{r.#t.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(s.length>0)throw new AggregateError(s,"Failed to stop engines")}async commitTransaction(e,t){return await this.#s(e,t,"commit")}async request(e,t){let{url:s}=await this.start(),n=this.#i(t),o=await fetch(s,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await l.fromResponse(o);return await o.text()}async rollbackTransaction(e,t){return await this.#s(e,t,"rollback")}async startTransaction(e,t){let{url:s}=await this.start(),n=this.#i(t),o=await fetch(`${s}/transaction/start`,{body:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await l.fromResponse(o);return await o.json()}async start(){if(this.#n!=null)return await this.#n;let{promise:e,reject:t,resolve:s}=R();this.#n=e;let n=N||await this.#o();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",n);let{proxySignals:o}=await import("foreground-child/proxy-signals"),i=$(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});o(i),i.stderr.setEncoding("utf8"),i.stdout.setEncoding("utf8");let a=c=>{let u=c.split(`
`).find(k=>k.includes("Started query engine http server"));if(!u)return;i.stdout.removeListener("data",a);let{fields:p}=JSON.parse(u);if(p==null)return t(new Error(`Unexpected data during initialization, "fields" are missing: ${c}`));let{ip:m,port:h}=p;if(m==null||h==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.
Received data: ${c}`));s({childProcess:i,url:`http://${m}:${h}`})},T=c=>{this.#n=null,t(new d(String(c))),i.removeListener("exit",g),i.kill()};i.once("error",T);let g=(c,u)=>{this.#n=null,t(new d(`Query Engine exited with code ${c} and signal ${u}`))};return i.once("exit",g),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 H(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 t=f(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await C(t,{recursive:!0});let{binaryTarget:s}=this.#e.platform,n=s==="windows"?".exe":"",o=A(t,`query-engine-${s}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(L==="1"||await w(o)===!1)&&await this.#a({commitHash:e,extension:n,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 n=s.split(".").at(-1);if(!n)throw new Error("Couldn't find commit hash in engines version");return n}async#a(e){let{commitHash:t,extension:s,engineBinaryPath:n}=e,{binaryTarget:o}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${t}/${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}`);P&&await j(Number(P)),await y(await a.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#i(e){let t={};for(let[s,n]of Object.entries(e))n!=null&&(t[s]=n);return t}async#s(e,t,s){let{url:n}=await this.#n,o=this.#i(t),i=await fetch(`${n}/transaction/${e}/${s}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await l.fromResponse(i);try{return await i.json()}catch{return{}}}};function G(r,e){if(console.error(r),r instanceof d){E(e,{EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:r.message}}}},500);return}if(r instanceof l){v(e,r.responseBody,r.statusCode);return}b(e,500)}var d=class extends Error{name="EngineStartError"},l=class r extends Error{constructor(t,s,n){super(`${t}: Query Engine response status ${s}, body: ${n}`);this.action=t;this.statusCode=s;this.responseBody=n}name="EngineHttpError";static async fromResponse(t){let s=new URL(t.url),n=await t.text();return new r(s.pathname,t.status,n)}};export{S as Engine,G as handleEngineError};