@prisma/dev 0.10.0 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/accelerate-6Y3KVRYK.js +1 -0
- package/dist/chunk-EPFUMVT3.js +1 -0
- package/dist/chunk-FZ7JBZR6.js +3 -0
- package/dist/{chunk-354SKE3R.js → chunk-IKAJO6YD.js} +1 -1
- package/dist/{chunk-GUT43IYK.js → chunk-RBVZVBDC.js} +1 -1
- package/dist/db.cjs +1 -1
- package/dist/db.js +1 -1
- package/dist/index.cjs +5 -8
- package/dist/index.js +1 -1
- package/dist/state.cjs +3 -3
- package/dist/state.d.cts +6 -1
- package/dist/state.d.ts +6 -1
- package/dist/state.js +1 -1
- package/package.json +4 -2
- package/dist/accelerate-44Q3JQWR.js +0 -4
- package/dist/chunk-I55EQWKN.js +0 -1
- package/dist/chunk-VPXPYVXN.js +0 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as i,d as H,e as m}from"./chunk-IKAJO6YD.js";import"./chunk-EPFUMVT3.js";import{Hono as z}from"hono/tiny";import{validator as c}from"hono/validator";import{array as M,literal as $,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(M(N()),V(1)),$("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";import{produceSchema as D}from"@mrleebo/prisma-ast";var f=new Map;async function g(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(s=>s.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}}async function O(t,n,e){let r=b.from(t,"base64").toString("utf8"),a=D(r,s=>{s.datasource('"postgresql"',n.toString())});e&&console.log("[Accelerate] schema with override:",a);let o=await g(a);return{base64Override:b.from(a,"utf8").toString("base64"),overrideHash:o}}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 T,number as l,object as Y,optional as G,pipe as E,safeParse as R,string as A,union as K}from"valibot";var Q=Y({isolation_level:G(A()),max_wait:E(l(),w(),T(0)),timeout:E(l(),w(),T(0))});async function C(t){let{issues:n,output:e,success:r}=R(Q,await t.req.json(),{abortEarly:!0});return r?e:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:n}},400)}var W=F({id:K([A(),l()])});function P(t,n){let{output:e,success:r}=R(W,t);return r?e:n.json({EngineMalfunction:{}},500)}var S=new z;S.post("/invalidate",c("header",i),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",i),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"),o=await e.request(r,{...d(t),"X-transaction-id":a});return t.text(o)}catch(e){return m(e,t)}});p.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],c("header",i),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`,o=n.param("transactionId"),s=await e[a](o,d(t));return t.json(s)}catch(e){return m(e,t)}});p.put("/schema",c("header",i),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 g(e))return t.text("Schema hash mismatch",400);let o=await O(e,t.get("db").prismaORMConnectionString,t.get("debug"));return f.set(r,{base64Original:e,...o}),t.text(r)}return e!==a.base64Original?t.text("Schema mismatch",400):t.text(r)});p.post("/transaction/start",c("header",i),async t=>{let{req:n}=t,e=await C(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)),o=P(a,t);if(o instanceof Response)return o;let{id:s}=o,x=n.param("clientVersion"),q=t.get("port"),_=t.get("protocol"),j=n.param("schemaHash");return t.json({...a,"data-proxy":{endpoint:`${_}://localhost:${q}/${x}/${j}/itx/${s}`}})}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 @@
|
|
|
1
|
+
import{createWriteStream as w,WriteStream as A}from"fs";import{access as D,chmod as x,constants as P,mkdir as E,readdir as T,readFile as _,rm as F,writeFile as O}from"fs/promises";import{promisify as v}from"util";import{unzip as L}from"zlib";import o from"path";import g from"os";import c from"process";var n=g.homedir(),a=g.tmpdir(),{env:e}=c,h=r=>{let t=o.join(n,"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)}},y=r=>{let t=e.APPDATA||o.join(n,"AppData","Roaming"),i=e.LOCALAPPDATA||o.join(n,"AppData","Local");return{data:o.join(i,r,"Data"),config:o.join(t,r,"Config"),cache:o.join(i,r,"Cache"),log:o.join(i,r,"Log"),temp:o.join(a,r)}},j=r=>{let t=o.basename(n);return{data:o.join(e.XDG_DATA_HOME||o.join(n,".local","share"),r),config:o.join(e.XDG_CONFIG_HOME||o.join(n,".config"),r),cache:o.join(e.XDG_CACHE_HOME||o.join(n,".cache"),r),log:o.join(e.XDG_STATE_HOME||o.join(n,".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"?h(r):c.platform==="win32"?y(r):j(r)}import C from"zeptomatch";var l=p("prisma-dev"),G=v(L);function z(r,t){return`${l.cache}/engine/${r}/${t}`}function I(r){return`${l.data}/${r}`}async function J(r){try{return await D(r,P.F_OK),!0}catch(t){if(u(t))return!1;throw t}}async function K(r,t){let i=await G(r);await O(t,i),await x(t,"755")}async function q(r,t){await r.stream().pipeTo(A.toWeb(w(t,{encoding:"utf-8"})))}function u(r){return r!=null&&typeof r=="object"&&"code"in r&&r.code==="ENOENT"}async function Q(r){try{return await _(r,{encoding:"utf-8"})}catch(t){if(u(t))return null;throw t}}async function U(r){await E(r,{recursive:!0})}async function V(r,t){try{return(await T(r,{withFileTypes:!0})).reduce((f,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||C(t,s.name))&&f.push(s.name),f),[])}catch(i){if(u(i))return[];throw i}}async function Y(r){await F(r,{force:!0,recursive:!0})}export{z as a,I as b,J as c,K as d,q as e,Q as f,U as g,V as h,Y as i};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a as V,b as N,c as L,d as f,e as F}from"./chunk-LMPFMHCB.js";import{b as d,f as O,g as I,h as A,i as T}from"./chunk-EPFUMVT3.js";import{writeFile as X}from"fs/promises";import{join as l}from"pathe";import{check as ee,lock as te,unlock as re}from"proper-lockfile";import{process as B}from"std-env";import{integer as C,literal as se,minLength as ae,minValue as H,number as K,object as P,optional as g,parseJson as oe,pipe as h,safeParse as ne,string as v,url as ie}from"valibot";import{setTimeout as Q}from"timers/promises";import{process as b}from"std-env";function y(t,e){if(t==null)return!1;try{return b.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}async function J(t,e){if(!b.kill)return!1;try{b.kill(t,"SIGTERM")}catch(n){return e&&console.error(`Error killing process with PID ${t}:`,n),!1}let r=0;do{if(!y(t,e))return!0;await Q(100)}while(++r<50);try{return b.kill(t,"SIGKILL")}catch(n){return e&&console.error(`Error forcefully killing process with PID ${t}:`,n),!1}}var _=h(v(),ie()),U=P({connectionString:_,prismaORMConnectionString:g(_),terminalCommand:g(v())}),j=P({url:_}),w=h(K(),C(),H(1)),ue=P({database:U,http:j,ppg:j,shadowDatabase:U}),ce=P({databasePort:w,exports:g(ue),name:h(v(),ae(1)),pid:g(h(K(),C(),H(0))),port:w,shadowDatabasePort:w,version:se("1")}),R=Symbol("initialize"),x="default",c=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??f,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??x,this.persistenceMode=e.persistenceMode,this.pid=e.pid??B.pid,this._port=e.port??f,this._shadowDatabasePort=e.shadowDatabasePort??f}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new p(e):new k(e);return await r[R](),r}static async fromServerDump(e){let{debug:r,name:n=x}=e??{},a=d(n),o=p.getServerDumpPath(a),s=await O(o);if(s==null)return r&&console.debug(`[State] No server dump file found at: ${o}`),null;r&&(console.debug(`[State] server dump file found at "${o}":`),console.debug(s));let{issues:i,output:u,success:m}=ne(h(v(),oe(),ce),s);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${o}":
|
|
2
|
+
${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new p({databasePort:u.databasePort,debug:r,dryRun:!1,name:n,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r,globs:n}=e??{},a=l(d(x),"..");r&&console.debug(`[State] scanning for server states in: ${a}`);let o=await A(a,n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(s=>q(s,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},k=class extends c{constructor(e){super({...e,databasePort:e?.databasePort??V,persistenceMode:"stateless",port:e?.port??N,shadowDatabasePort:e?.shadowDatabasePort??L})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[R](){}async close(){}async writeServerDump(){}},p=class t extends c{#t;#e;#s;#o;#n;#a;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#a=!1,this.#e=d(this.name),this.#t=l(this.#e,"db_dump.bak"),this.#s=l(this.#e,".lock"),this.#o=l(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#n=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return l(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[R](){await I(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await te(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await c.scan({debug:this.debug,onlyMetadata:!0}),r=await F({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 E(this):e}}async close(){if(!this.#a)try{await re(this.#e,{lockfilePath:this.#s}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:B.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await X(this.#n,`${JSON.stringify(this.#r,null,2)}
|
|
3
|
+
`,{encoding:"utf-8"})}};async function xe(t,e){await le(t,e);let r=d(typeof t=="string"?t:t.name);await T(r)}async function q(t,e){let{debug:r,onlyMetadata:n}=e||{},a=typeof t=="string"?t:t.name,o=typeof t!="string"?t:void 0,s={databasePort:o?.databasePort??-1,exports:o?.exports,name:a,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let i=o||await c.fromServerDump({debug:r,name:a});if(!i)return r&&console.debug(`[State] no server state found for name: ${a}`),{...s,status:"no_such_server"};s.databasePort=i.databasePort,s.exports=i.exports,s.pid=i.pid,s.port=i.port,s.shadowDatabasePort=i.shadowDatabasePort;let{exports:u,pid:m}=i;if(n)return{...s,status:"unknown"};if(!y(m,r))return r&&console.debug(`[State] server state for "${a}" has no running process with PID: ${m}`),{...s,status:"not_running"};let M=d(a);try{if(!await ee(M,{lockfilePath:l(M,".lock")}))return r&&console.debug(`[State] server state for "${a}" is not locked, indicating it is not running.`),{...s,status:"starting_up"}}catch(Z){r&&console.error(`[State] server state for "${a}" failed to check lock:`,Z)}if(!u)return{...s,status:"starting_up"};let{http:G}=u,{hc:Y}=await import("hono/client"),S=await Y(G.url).health.$get();if(!S.ok)return r&&console.debug(`[State] server state for "${a}" is not live: ${JSON.stringify(S)}`),{...s,status:"not_running"};let D=await S.json();return D.name!==t?(r&&console.debug(`[State] server state for "${a}" has mismatched health response: ${JSON.stringify(D)}`),{...s,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(D)}`),{...s,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${a}":`,i),{...s,status:"error"}}}function de(t){let{status:e}=t;return e==="running"||e==="starting_up"}async function le(t,e){let{pid:r,...n}=typeof t=="string"?await q(t,{debug:e}):t;if(!de(n))return!1;let a=await c.fromServerDump({debug:e,name:n.name});if(r==null){e&&console.debug(`[State] No PID found for server "${n.name}" to kill.`);try{await a?.close()}catch{}return!1}let o=await J(r,e);try{await a?.close()}catch{}return o}var $=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},E=class extends ${#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return c.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{c as a,xe as b,q as c,de as d,le as e,$ as f,E as g};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as P,c as v,d as b}from"./chunk-
|
|
1
|
+
import{a as P,c as v,d as b}from"./chunk-EPFUMVT3.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
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
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as u}from"./chunk-LMPFMHCB.js";import{e as m}from"./chunk-
|
|
1
|
+
import{f as u}from"./chunk-LMPFMHCB.js";import{e as m}from"./chunk-EPFUMVT3.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};
|
package/dist/db.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var G=Object.create;var g=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var M=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var F=(e,t)=>{for(var r in t)g(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&&g(e,a,{get:()=>t[a],enumerable:!(s=N(t,a))||s.enumerable});return e};var u=(e,t,r)=>(r=e!=null?G(M(e)):{},O(t||!e||!e.__esModule?g(r,"default",{value:e,enumerable:!0}):r,e)),I=e=>O(g({},"__esModule",{value:!0}),e);var Y={};F(Y,{dumpDB:()=>j,startDBServer:()=>z});module.exports=I(Y);var k=require("pathe/utils");var y=require("fs"),m=require("fs/promises"),T=require("util"),x=require("zlib");var o=u(require("path"),1),v=u(require("os"),1),b=u(require("process"),1),l=v.default.homedir(),S=v.default.tmpdir(),{env:f}=b.default,K=e=>{let t=o.default.join(l,"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(S,e)}},H=e=>{let t=f.APPDATA||o.default.join(l,"AppData","Roaming"),r=f.LOCALAPPDATA||o.default.join(l,"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(S,e)}},W=e=>{let t=o.default.basename(l);return{data:o.default.join(f.XDG_DATA_HOME||o.default.join(l,".local","share"),e),config:o.default.join(f.XDG_CONFIG_HOME||o.default.join(l,".config"),e),cache:o.default.join(f.XDG_CACHE_HOME||o.default.join(l,".cache"),e),log:o.default.join(f.XDG_STATE_HOME||o.default.join(l,".local","state"),e),temp:o.default.join(S,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}`),b.default.platform==="darwin"?K(e):b.default.platform==="win32"?H(e):W(e)}var V=u(require("zeptomatch"),1),oe=D("prisma-dev"),ne=(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"},X=`postgres://${i.username}:${i.password}@localhost`,R=new URLSearchParams({sslmode:i.sslMode}),J=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 z(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"?Q:L)(t.pgliteDataDirPath,s);s&&d.onNotification((n,p)=>{console.debug(`[${e}][${n}] ${p}`)});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:p}=n;console.debug(`[${e}] server listening on ${JSON.stringify(p)}`)}),c.addEventListener("connection",n=>{let{clientAddress:p,clientPort:U}=n.detail;console.debug(`[${e}] client connected from ${p}:${U}`)}),c.addEventListener("error",n=>{let{detail:p}=n;console.error(`[${e}] server error:`,p)}));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,J),terminalCommand:`PGPASSWORD=${i.password} PGSSLMODE=${i.sslMode} psql -h localhost -p ${d} -U ${i.username} -d ${i.database}`}}function B(e,t){return`${X}:${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 Q(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-
|
|
1
|
+
import{a,b}from"./chunk-RBVZVBDC.js";import"./chunk-LMPFMHCB.js";import"./chunk-EPFUMVT3.js";export{b as dumpDB,a as startDBServer};
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).find(
|
|
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
|
-
|
|
5
|
-
|
|
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});
|
|
1
|
+
"use strict";var _t=Object.create;var J=Object.defineProperty;var kt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var Ct=Object.getPrototypeOf,Bt=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var ne=(t,e)=>{for(var r in e)J(t,r,{get:e[r],enumerable:!0})},Te=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of It(e))!Bt.call(t,n)&&n!==r&&J(t,n,{get:()=>e[n],enumerable:!(o=kt(e,n))||o.enumerable});return t};var S=(t,e,r)=>(r=t!=null?_t(Ct(t)):{},Te(e||!t||!t.__esModule?J(r,"default",{value:t,enumerable:!0}):r,t)),Ht=t=>Te(J({},"__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 jt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:o,success:n}=(0,f.safeParse)(Lt,e,{abortEarly:!0});return n?[null,o]:[r]}var f,Oe,Lt,k,se=D(()=>{"use strict";p();f=require("valibot"),Oe=/^(postgres|postgresql):\/\//,Lt=(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)(Oe)),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)(Oe))}));k=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[i,c]=jt(s);if(i)throw new o(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:u,name:l,shadowDatabaseUrl:g}=c,{name:b}=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 "${b}" server's output for the updated \`DATABASE_URL\` value.`});if(l!==b)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${b}", but the API Key is for "${l}"`});let{hostname:T,port:O}=new URL(u),{port:N}=e.get("db"),{hostname:At,port:xt}=new URL(g),$t=e.get("shadowDBPort");if(T!=="localhost"||Number(O)!==N||At!=="localhost"||Number(xt)!==$t)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:c}}});function ce(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),Q.default.platform==="darwin"?Mt(t):Q.default.platform==="win32"?Ut(t):Nt(t)}var h,ae,Q,A,ie,I,Mt,Ut,Nt,xe=D(()=>{"use strict";p();h=S(require("path"),1),ae=S(require("os"),1),Q=S(require("process"),1),A=ae.default.homedir(),ie=ae.default.tmpdir(),{env:I}=Q.default,Mt=t=>{let e=h.default.join(A,"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)}},Ut=t=>{let e=I.APPDATA||h.default.join(A,"AppData","Roaming"),r=I.LOCALAPPDATA||h.default.join(A,"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)}},Nt=t=>{let e=h.default.basename(A);return{data:h.default.join(I.XDG_DATA_HOME||h.default.join(A,".local","share"),t),config:h.default.join(I.XDG_CONFIG_HOME||h.default.join(A,".config"),t),cache:h.default.join(I.XDG_CACHE_HOME||h.default.join(A,".cache"),t),log:h.default.join(I.XDG_STATE_HOME||h.default.join(A,".local","state"),t),temp:h.default.join(ie,e,t)}}});function Ce(t,e){return`${Ie.cache}/engine/${t}/${e}`}function F(t){return`${Ie.data}/${t}`}async function Be(t){try{return await(0,v.access)(t,v.constants.F_OK),!0}catch(e){if(ue(e))return!1;throw e}}async function He(t,e){let r=await Ft(t);await(0,v.writeFile)(e,r),await(0,v.chmod)(e,"755")}async function Le(t,e){await t.stream().pipeTo(W.WriteStream.toWeb((0,W.createWriteStream)(e,{encoding:"utf-8"})))}function ue(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function je(t){try{return await(0,v.readFile)(t,{encoding:"utf-8"})}catch(e){if(ue(e))return null;throw e}}async function Me(t){await(0,v.mkdir)(t,{recursive:!0})}async function Ue(t,e){try{return(await(0,v.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,ke.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(ue(r))return[];throw r}}var W,v,$e,_e,ke,Ie,Ft,z=D(()=>{"use strict";p();W=require("fs"),v=require("fs/promises"),$e=require("util"),_e=require("zlib");xe();ke=S(require("zeptomatch"),1),Ie=ce("prisma-dev"),Ft=(0,$e.promisify)(_e.unzip)});function Z(t){let e,r,o=new Promise((a,i)=>{e=a,r=i}),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 ee(t,e){return console.error(t),t instanceof q?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof L?e.text(t.responseBody,t.statusCode):e.body(null,500)}var We,ze,Xe,Ye,Ze,et,Xt,Yt,Qe,j,q,L,fe=D(()=>{"use strict";p();We=require("child_process"),ze=require("events"),Xe=require("fs/promises"),Ye=require("path"),Ze=require("timers/promises");me();et=require("std-env");z();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Xt,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Yt,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Qe}=et.process.env),j=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.#o(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 L.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.#o(r),s=await fetch(`${o}/transaction/start`,{body:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await L.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:o}=Z();this.#t=e;let n=Yt||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,We.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 i=l=>{let g=l.split(`
|
|
2
|
+
`).find(N=>N.includes("Started query engine http server"));if(!g)return;a.stdout.removeListener("data",i);let{fields:b}=JSON.parse(g);if(b==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${l}`));let{ip:T,port:O}=b;if(T==null||O==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://${T}:${O}`})},c=l=>{this.#t=null,r(new q(String(l))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(l,g)=>{this.#t=null,r(new q(`Query Engine exited with code ${l} and signal ${g}`))};return a.once("exit",u),a.stdout.on("data",i),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,ze.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#a();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=Ce(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,Xe.mkdir)(r,{recursive:!0});let{platform:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,Ye.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Xt==="1"||await Be(s)===!1)&&await this.#n({commitHash:e,extension:n,engineBinaryPath:s}),s}async#a(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let 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 i=await fetch(a);if(!i.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${i.status}`);Qe&&await(0,Ze.setTimeout)(Number(Qe)),await He(await i.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#o(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.#o(r),a=await fetch(`${n}/transaction/${e}/${o}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await L.fromResponse(a);try{return await a.json()}catch{return{}}}};q=class extends Error{name="EngineStartError"},L=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 tt(t){let{output:e,success:r}=(0,w.safeParse)(Zt,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var w,Zt,rt=D(()=>{"use strict";p();w=require("valibot"),Zt=(0,w.object)({tags:(0,w.union)([(0,w.pipe)((0,w.array)((0,w.string)()),(0,w.minLength)(1)),(0,w.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 nt(t){let e=t.req.param("schemaHash"),r=te.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}async function st(t,e,r){let o=he.Buffer.from(t,"base64").toString("utf8"),n=(0,ot.produceSchema)(o,a=>{a.datasource('"postgresql"',e.toString())});r&&console.log("[Accelerate] schema with override:",n);let s=await ge(n);return{base64Override:he.Buffer.from(n,"utf8").toString("base64"),overrideHash:s}}var he,ot,te,at=D(()=>{"use strict";p();he=require("buffer"),ot=require("@mrleebo/prisma-ast"),te=new Map});function re(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var it=D(()=>{"use strict";p()});async function ct(t){let{issues:e,output:r,success:o}=(0,m.safeParse)(er,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}function ut(t,e){let{output:r,success:o}=(0,m.safeParse)(tr,t);return o?r:e.json({EngineMalfunction:{}},500)}var m,er,tr,dt=D(()=>{"use strict";p();m=require("valibot"),er=(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))});tr=(0,m.looseObject)({id:(0,m.union)([(0,m.string)(),(0,m.number)()])})});var pt={};ne(pt,{accelerateRoute:()=>oe});async function ye(t){let{req:e}=t,r=nt(t);if(r instanceof Response)return r;let{base64Override:o,overrideHash:n}=r.schemas;return await j.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 lt,M,oe,rr,V,or,mt=D(()=>{"use strict";p();lt=require("hono/tiny"),M=require("hono/validator");se();rt();fe();at();it();dt();oe=new lt.Hono;oe.post("/invalidate",(0,M.validator)("header",k),async t=>{let e=await tt(t);return e instanceof Response?e:t.body(null)});rr="/:clientVersion/:schemaHash",V=oe.basePath(rr);oe.route("/",V);or=["/graphql","/itx/:transactionId/graphql"];V.on("POST",[...or],(0,M.validator)("header",k),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,{...re(t),"X-transaction-id":n});return t.text(s)}catch(r){return ee(r,t)}});V.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,M.validator)("header",k),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,re(t));return t.json(a)}catch(r){return ee(r,t)}});V.put("/schema",(0,M.validator)("header",k),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let o=e.param("schemaHash"),n=te.get(o);if(n==null){if(o!==await ge(r))return t.text("Schema hash mismatch",400);let s=await st(r,t.get("db").prismaORMConnectionString,t.get("debug"));return te.set(o,{base64Original:r,...s}),t.text(o)}return r!==n.base64Original?t.text("Schema mismatch",400):t.text(o)});V.post("/transaction/start",(0,M.validator)("header",k),async t=>{let{req:e}=t,r=await ct(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,re(t)),s=ut(n,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),u=t.get("protocol"),l=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${u}://localhost:${c}/${i}/${l}/itx/${a}`}})}catch(o){return ee(o,t)}})});var gt={};ne(gt,{utilityRoute:()=>be});var ft,ht,be,Qr,yt=D(()=>{"use strict";p();ft=require("hono/tiny"),ht=require("http-status-codes"),be=new ft.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},ht.StatusCodes.CREATED)});Qr=be.get("/health",t=>t.json({name:t.get("serverState").name}))});var dr={};ne(dr,{DEFAULT_DATABASE_PORT:()=>C,DEFAULT_SERVER_PORT:()=>B,DEFAULT_SHADOW_DATABASE_PORT:()=>H,PortNotAvailableError:()=>E,ServerAlreadyRunningError:()=>K,unstable_startServer:()=>ur});module.exports=Ht(dr);p();se();p();var Ge=require("pathe/utils");z();p();var $=require("get-port-please"),Y=require("remeda"),C=51214,B=51213,H=51215,X=65535,x=-1/0;async function Fe(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=Gt(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 i={databasePort:x,port:x,shadowDatabasePort:x},c=["port","databasePort","shadowDatabasePort"];for(let u of c){let l=await qt({debug:e,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await Vt({debug:e,pickedPorts:i,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${u}": ${l}`),i[u]=l}return e&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function qt(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s}=t,{[r]:a,...i}=s;if(Ne(a))return await Kt({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let c=n?.[r]??x;if(!Ne(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=c in o;return u||Object.values(i).includes(c)?(e&&console.debug(`Port ${c} 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,$.checkPort)(c)===!1?(e&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function Vt(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(C,B,H)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,X),u=(0,Y.difference)((0,Y.range)(a,c),i),l={port:B,databasePort:C,shadowDatabasePort:H}[o];try{return await(0,$.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"&&c+1<=X)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${X}].`),await(0,$.getPort)({portRange:[c+1,X]});throw g}}function Ne(t){return t>=0}function Gt(t,e){let r={},o;for(let n of e){let{databasePort:s,port:a,shadowDatabasePort:i}=n;if(n.name===t){o={databasePort:s,port:a,shadowDatabasePort:i};continue}r[s]=!0,r[a]=!0,r[i]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:o}}async function Kt(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 de(s);if((0,$.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${o}", but is unsafe.`),new E(s);if(await(0,$.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"},de=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 y={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Jt=`postgres://${y.username}:${y.password}@localhost`,Ke=new URLSearchParams({sslmode:y.sslMode}),Qt=new URLSearchParams({...Object.fromEntries(Ke.entries()),connection_limit:String(y.connectionLimit),connect_timeout:String(y.connectTimeout),max_idle_connection_lifetime:String(y.maxIdleConnectionLifetime),pool_timeout:String(y.poolTimeout),single_use_connections:"true",socket_timeout:String(y.socketTimeout)});async function pe(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return qe(t,e,{db:null,port:r,server:null});let{debug:o}=e,s=await(t==="shadow_database"?Wt:Je)(e.pgliteDataDirPath,o);o&&s.onNotification((c,u)=>{console.debug(`[${t}][${c}] ${u}`)});let{PGLiteSocketServer:a}=await import("@electric-sql/pglite-socket"),i=new a({db:s,debug:o,inspect:o,port:r});o&&(i.addEventListener("listening",c=>{let{detail:u}=c;console.debug(`[${t}] server listening on ${JSON.stringify(u)}`)}),i.addEventListener("connection",c=>{let{clientAddress:u,clientPort:l}=c.detail;console.debug(`[${t}] client connected from ${u}:${l}`)}),i.addEventListener("error",c=>{let{detail:u}=c;console.error(`[${t}] server error:`,u)}));try{await i.start()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="EADDRINUSE"?new E(r):c}return qe(t,e,{db:s,port:r,server:i})}function qe(t,e,r){let{debug:o}=e,{db:n,port:s,server:a}=r||{};return o&&console.debug(`[${t}] server started on port ${s}`),{...y,close:async()=>{let i=[];try{await a?.stop(),o&&console.debug(`[${t}] server stopped on port ${s}`)}catch(c){console.error(`[${t}] server stop error`,c),i.push(c)}if(t==="database")try{await n?.syncToFs(),o&&console.debug(`[${t}] synced to filesystem`)}catch(c){console.error(`[${t}] sync error`,c),i.push(c)}try{await n?.close(),o&&console.debug(`[${t}] closed`)}catch(c){console.error(`[${t}] close error`,c),i.push(c)}if(i.length>0)throw new AggregateError(i,`Failed to close ${t} properly`)},connectionString:Ve(s,Ke),dump:async i=>{t==="shadow_database"||!n||await zt({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:Ve(s,Qt),terminalCommand:`PGPASSWORD=${y.password} PGSSLMODE=${y.sslMode} psql -h localhost -p ${s} -U ${y.username} -d ${y.database}`}}function Ve(t,e){return`${Jt}:${t}/${y.database}?${e.toString()}`}async function Je(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:y.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:y.username})}async function Wt(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:y.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:y.username})}async function zt(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Je(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:n?(0,Ge.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await Le(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}p();var Pt=require("http"),wt=require("util"),St=S(require("@prisma/get-platform"),1);me();fe();async function vt(t,e){let{port:r}=e;if(e.dryRun)return bt(r,null);let o=await nr(r,t,e),{promise:n,reject:s,resolve:a}=Z(),{serve:i}=await import("@hono/node-server"),c=i({createServer:Pt.createServer,fetch:o.fetch,overrideGlobalObjects:!1,port:r},a);return c.on("error",u=>{if(typeof u=="object"&&"code"in u&&u.code==="EADDRINUSE")return s(new E(r));console.error("[Accelerate]",u)}),await n,bt(r,c)}function bt(t,e){return{async close(){e&&await Promise.allSettled([(0,wt.promisify)(e.close.bind(e))(),j.stopAll()])},port:t,url:`http://localhost:${t}`}}async function nr(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(mt(),pt)),Promise.resolve().then(()=>(yt(),gt))]),i=new n,c=await St.default.getPlatformInfo();if(o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),o){let{logger:l}=await import("hono/logger");i.use("*",l((...g)=>console.log("[Accelerate]",...g)))}i.use("*",async(l,g)=>(l.set("db",e),l.set("debug",!!o),l.set("platform",c),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),i.route("/",u),i}p();var Ot=require("fs/promises"),_=require("pathe"),U=require("proper-lockfile"),Ee=require("std-env"),d=require("valibot");z();p();var sr=require("timers/promises"),Dt=require("std-env");function Et(t,e){if(t==null)return!1;try{return Dt.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var Se=(0,d.pipe)((0,d.string)(),(0,d.url)()),Rt=(0,d.object)({connectionString:Se,prismaORMConnectionString:(0,d.optional)(Se),terminalCommand:(0,d.optional)((0,d.string)())}),Tt=(0,d.object)({url:Se}),Pe=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),ar=(0,d.object)({database:Rt,http:Tt,ppg:Tt,shadowDatabase:Rt}),ir=(0,d.object)({databasePort:Pe,exports:(0,d.optional)(ar),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")}),Re=Symbol("initialize"),we="default",R=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??x,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??we,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Ee.process.pid,this._port=e.port??x,this._shadowDatabasePort=e.shadowDatabasePort??x}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new G(e):new ve(e);return await r[Re](),r}static async fromServerDump(e){let{debug:r,name:o=we}=e??{},n=F(o),s=G.getServerDumpPath(n),a=await je(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:i,output:c,success:u}=(0,d.safeParse)((0,d.pipe)((0,d.string)(),(0,d.parseJson)(),ir),a);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
|
|
4
|
+
${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new G({databasePort:c.databasePort,debug:r,dryRun:!1,name:o,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r,globs:o}=e??{},n=(0,_.join)(F(we),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let s=await Ue(n,o);return r&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>cr(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},ve=class extends R{constructor(e){super({...e,databasePort:e?.databasePort??C,persistenceMode:"stateless",port:e?.port??B,shadowDatabasePort:e?.shadowDatabasePort??H})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Re](){}async close(){}async writeServerDump(){}},G=class t extends R{#r;#e;#t;#s;#a;#n;#o;constructor(e){super({...e,persistenceMode:"stateful"}),this.#n=!1,this.#e=F(this.name),this.#r=(0,_.join)(this.#e,"db_dump.bak"),this.#t=(0,_.join)(this.#e,".lock"),this.#s=(0,_.join)(this.#e,".pglite"),this.#o=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,_.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#o?.exports}get pgliteDataDirPath(){return this.#s}async[Re](){await Me(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,U.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await R.scan({debug:this.debug,onlyMetadata:!0}),r=await Fe({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 K(this):e}}async close(){if(!this.#n)try{await(0,U.unlock)(this.#e,{lockfilePath:this.#t}),this.#n=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,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.#a,`${JSON.stringify(this.#o,null,2)}
|
|
5
|
+
`,{encoding:"utf-8"})}};async function cr(t,e){let{debug:r,onlyMetadata:o}=e||{},n=typeof t=="string"?t:t.name,s=typeof t!="string"?t:void 0,a={databasePort:s?.databasePort??-1,exports:s?.exports,name:n,pid:s?.pid,port:s?.port??-1,shadowDatabasePort:s?.shadowDatabasePort??-1,version:"1"};try{let i=s||await R.fromServerDump({debug:r,name:n});if(!i)return r&&console.debug(`[State] no server state found for name: ${n}`),{...a,status:"no_such_server"};a.databasePort=i.databasePort,a.exports=i.exports,a.pid=i.pid,a.port=i.port,a.shadowDatabasePort=i.shadowDatabasePort;let{exports:c,pid:u}=i;if(o)return{...a,status:"unknown"};if(!Et(u,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${u}`),{...a,status:"not_running"};let l=F(n);try{if(!await(0,U.check)(l,{lockfilePath:(0,_.join)(l,".lock")}))return r&&console.debug(`[State] server state for "${n}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(N){r&&console.error(`[State] server state for "${n}" failed to check lock:`,N)}if(!c)return{...a,status:"starting_up"};let{http:g}=c,{hc:b}=await import("hono/client"),T=await b(g.url).health.$get();if(!T.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(T)}`),{...a,status:"not_running"};let O=await T.json();return O.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(O)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(O)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${n}":`,i),{...a,status:"error"}}}var De=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},K=class extends De{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return R.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function ur(t){let e=await R.createExclusively(t),[r,o]=await Promise.all([pe("database",e),pe("shadow_database",e)]),n=await vt(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:()=>i(e,[n,r,o]),name:e.name};async function i(c,u){let g=(await Promise.allSettled(u.map(b=>b.close()))).filter(b=>b.status==="rejected").map(b=>new Error(b.reason));try{await c.close()}catch(b){g.push(b)}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.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as f}from"./chunk-
|
|
1
|
+
import{a as f}from"./chunk-RBVZVBDC.js";import{a as w,g as R}from"./chunk-FZ7JBZR6.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-IKAJO6YD.js";import"./chunk-EPFUMVT3.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-6Y3KVRYK.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
|
|
2
|
-
${JSON.stringify(
|
|
3
|
-
`,{encoding:"utf-8"})}};async function
|
|
1
|
+
"use strict";var ye=Object.create;var k=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var we=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty;var xe=(t,e)=>{for(var r in e)k(t,r,{get:e[r],enumerable:!0})},Z=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Se(e))!De.call(t,o)&&o!==r&&k(t,o,{get:()=>e[o],enumerable:!(n=ve(e,o))||n.enumerable});return t};var D=(t,e,r)=>(r=t!=null?ye(we(t)):{},Z(e||!t||!t.__esModule?k(r,"default",{value:t,enumerable:!0}):r,t)),Oe=t=>Z(k({},"__esModule",{value:!0}),t);var Be={};xe(Be,{ServerAlreadyRunningError:()=>U,ServerState:()=>h,ServerStateAlreadyExistsError:()=>L,deleteServer:()=>Ue,getServerStatus:()=>Y,isServerRunning:()=>me,killServer:()=>Pe});module.exports=Oe(Be);var he=require("fs/promises"),g=require("pathe"),S=require("proper-lockfile"),X=require("std-env"),a=require("valibot");var Q=require("fs"),l=require("fs/promises"),ee=require("util"),te=require("zlib");var d=D(require("path"),1),N=D(require("os"),1),_=D(require("process"),1),m=N.default.homedir(),F=N.default.tmpdir(),{env:y}=_.default,ke=t=>{let e=d.default.join(m,"Library");return{data:d.default.join(e,"Application Support",t),config:d.default.join(e,"Preferences",t),cache:d.default.join(e,"Caches",t),log:d.default.join(e,"Logs",t),temp:d.default.join(F,t)}},_e=t=>{let e=y.APPDATA||d.default.join(m,"AppData","Roaming"),r=y.LOCALAPPDATA||d.default.join(m,"AppData","Local");return{data:d.default.join(r,t,"Data"),config:d.default.join(e,t,"Config"),cache:d.default.join(r,t,"Cache"),log:d.default.join(r,t,"Log"),temp:d.default.join(F,t)}},$e=t=>{let e=d.default.basename(m);return{data:d.default.join(y.XDG_DATA_HOME||d.default.join(m,".local","share"),t),config:d.default.join(y.XDG_CONFIG_HOME||d.default.join(m,".config"),t),cache:d.default.join(y.XDG_CACHE_HOME||d.default.join(m,".cache"),t),log:d.default.join(y.XDG_STATE_HOME||d.default.join(m,".local","state"),t),temp:d.default.join(F,e,t)}};function V(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),_.default.platform==="darwin"?ke(t):_.default.platform==="win32"?_e(t):$e(t)}var re=D(require("zeptomatch"),1),Te=V("prisma-dev"),qe=(0,ee.promisify)(te.unzip);function v(t){return`${Te.data}/${t}`}function oe(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function se(t){try{return await(0,l.readFile)(t,{encoding:"utf-8"})}catch(e){if(oe(e))return null;throw e}}async function ae(t){await(0,l.mkdir)(t,{recursive:!0})}async function ne(t,e){try{return(await(0,l.readdir)(t,{withFileTypes:!0})).reduce((n,o)=>(o.isDirectory()&&!o.name.startsWith(".")&&(!e||(0,re.default)(e,o.name))&&n.push(o.name),n),[])}catch(r){if(oe(r))return[];throw r}}async function ie(t){await(0,l.rm)(t,{force:!0,recursive:!0})}var ce=require("timers/promises"),x=require("std-env");function q(t,e){if(t==null)return!1;try{return x.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}async function ue(t,e){if(!x.process.kill)return!1;try{x.process.kill(t,"SIGTERM")}catch(n){return e&&console.error(`Error killing process with PID ${t}:`,n),!1}let r=0;do{if(!q(t,e))return!0;await(0,ce.setTimeout)(100)}while(++r<50);try{return x.process.kill(t,"SIGKILL")}catch(n){return e&&console.error(`Error forcefully killing process with PID ${t}:`,n),!1}}var b=require("get-port-please"),M=require("remeda"),E=51214,A=51213,R=51215,T=65535,P=-1/0;async function pe(t){let{debug:e,name:r,requestedPorts:n,servers:o}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:i}=Re(r,o);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(i)}`));let c={databasePort:P,port:P,shadowDatabasePort:P},u=["port","databasePort","shadowDatabasePort"];for(let p of u){let f=await Ee({debug:e,portKey:p,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:i,requestedPorts:n})??await Ae({debug:e,pickedPorts:c,portKey:p,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:i});e&&console.debug(`Got port for "${p}": ${f}`),c[p]=f}return e&&console.debug(`Picked ports: ${JSON.stringify(c)}`),c}async function Ee(t){let{debug:e,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:o,requestedPorts:s}=t,{[r]:i,...c}=s;if(de(i))return await je({debug:e,otherRequestedPorts:c,portKey:r,portsUsedByOtherServers:n,requestedPort:i}),i;let u=o?.[r]??P;if(!de(u))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let p=u in n;return p||Object.values(c).includes(u)?(e&&console.debug(`Port ${u} 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,b.checkPort)(u)===!1?(e&&console.debug(`Port ${u}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${u} for "${r}" as it was used last time and is available.`),u)}async function Ae(t){let{debug:e,pickedPorts:r,portKey:n,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:s}=t,i=Math.max(E,A,R)+1,c=[...Object.values(r),...Object.keys(o).map(Number),...Object.values(s||{})],u=Math.min(Math.max(i,...c)+100,T),p=(0,M.difference)((0,M.range)(i,u),c),f={port:A,databasePort:E,shadowDatabasePort:R}[n];try{return await(0,b.getPort)({port:f in o||Object.values(r).includes(f)||Object.values(s||{}).includes(f)?void 0:f,ports:p})}catch(w){if(w instanceof Error&&w.name==="GetPortError"&&u+1<=T)return e&&console.debug(`Expanding port lookup to range [${u+1}, ${T}].`),await(0,b.getPort)({portRange:[u+1,T]});throw w}}function de(t){return t>=0}function Re(t,e){let r={},n;for(let o of e){let{databasePort:s,port:i,shadowDatabasePort:c}=o;if(o.name===t){n={databasePort:s,port:i,shadowDatabasePort:c};continue}r[s]=!0,r[i]=!0,r[c]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}async function je(t){let{debug:e,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:o,requestedPort:s}=t;if(s in o)throw e&&console.error(`Port ${s} was requested for "${n}", but is already used by another server.`),new K(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${n}", but also for another key.`),new C(s);if((0,b.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${n}", but is unsafe.`),new j(s);if(await(0,b.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${n}", but is not available.`),new j(s)}var j=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},C=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"},K=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 J=(0,a.pipe)((0,a.string)(),(0,a.url)()),le=(0,a.object)({connectionString:J,prismaORMConnectionString:(0,a.optional)(J),terminalCommand:(0,a.optional)((0,a.string)())}),fe=(0,a.object)({url:J}),G=(0,a.pipe)((0,a.number)(),(0,a.integer)(),(0,a.minValue)(1)),Me=(0,a.object)({database:le,http:fe,ppg:fe,shadowDatabase:le}),Le=(0,a.object)({databasePort:G,exports:(0,a.optional)(Me),name:(0,a.pipe)((0,a.string)(),(0,a.minLength)(1)),pid:(0,a.optional)((0,a.pipe)((0,a.number)(),(0,a.integer)(),(0,a.minValue)(0))),port:G,shadowDatabasePort:G,version:(0,a.literal)("1")}),z=Symbol("initialize"),H="default",h=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??P,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??H,this.persistenceMode=e.persistenceMode,this.pid=e.pid??X.process.pid,this._port=e.port??P,this._shadowDatabasePort=e.shadowDatabasePort??P}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new O(e):new W(e);return await r[z](),r}static async fromServerDump(e){let{debug:r,name:n=H}=e??{},o=v(n),s=O.getServerDumpPath(o),i=await se(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:c,output:u,success:p}=(0,a.safeParse)((0,a.pipe)((0,a.string)(),(0,a.parseJson)(),Le),i);if(!p)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
|
|
2
|
+
${JSON.stringify(c,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new O({databasePort:u.databasePort,debug:r,dryRun:!1,name:n,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r,globs:n}=e??{},o=(0,g.join)(v(H),"..");r&&console.debug(`[State] scanning for server states in: ${o}`);let s=await ne(o,n);return r&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(i=>Y(i,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},W=class extends h{constructor(e){super({...e,databasePort:e?.databasePort??E,persistenceMode:"stateless",port:e?.port??A,shadowDatabasePort:e?.shadowDatabasePort??R})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[z](){}async close(){}async writeServerDump(){}},O=class t extends h{#t;#e;#o;#a;#n;#s;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#s=!1,this.#e=v(this.name),this.#t=(0,g.join)(this.#e,"db_dump.bak"),this.#o=(0,g.join)(this.#e,".lock"),this.#a=(0,g.join)(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#n=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,g.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#a}async[z](){await ae(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,S.lock)(this.#e,{lockfilePath:this.#o}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await h.scan({debug:this.debug,onlyMetadata:!0}),r=await pe({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 U(this):e}}async close(){if(!this.#s)try{await(0,S.unlock)(this.#e,{lockfilePath:this.#o}),this.#s=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:X.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,he.writeFile)(this.#n,`${JSON.stringify(this.#r,null,2)}
|
|
3
|
+
`,{encoding:"utf-8"})}};async function Ue(t,e){await Pe(t,e);let r=v(typeof t=="string"?t:t.name);await ie(r)}async function Y(t,e){let{debug:r,onlyMetadata:n}=e||{},o=typeof t=="string"?t:t.name,s=typeof t!="string"?t:void 0,i={databasePort:s?.databasePort??-1,exports:s?.exports,name:o,pid:s?.pid,port:s?.port??-1,shadowDatabasePort:s?.shadowDatabasePort??-1,version:"1"};try{let c=s||await h.fromServerDump({debug:r,name:o});if(!c)return r&&console.debug(`[State] no server state found for name: ${o}`),{...i,status:"no_such_server"};i.databasePort=c.databasePort,i.exports=c.exports,i.pid=c.pid,i.port=c.port,i.shadowDatabasePort=c.shadowDatabasePort;let{exports:u,pid:p}=c;if(n)return{...i,status:"unknown"};if(!q(p,r))return r&&console.debug(`[State] server state for "${o}" has no running process with PID: ${p}`),{...i,status:"not_running"};let f=v(o);try{if(!await(0,S.check)(f,{lockfilePath:(0,g.join)(f,".lock")}))return r&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...i,status:"starting_up"}}catch(ge){r&&console.error(`[State] server state for "${o}" failed to check lock:`,ge)}if(!u)return{...i,status:"starting_up"};let{http:w}=u,{hc:be}=await import("hono/client"),B=await be(w.url).health.$get();if(!B.ok)return r&&console.debug(`[State] server state for "${o}" is not live: ${JSON.stringify(B)}`),{...i,status:"not_running"};let I=await B.json();return I.name!==t?(r&&console.debug(`[State] server state for "${o}" has mismatched health response: ${JSON.stringify(I)}`),{...i,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(I)}`),{...i,status:"running"})}catch(c){return r&&console.error(`[State] failed to get server status for "${o}":`,c),{...i,status:"error"}}}function me(t){let{status:e}=t;return e==="running"||e==="starting_up"}async function Pe(t,e){let{pid:r,...n}=typeof t=="string"?await Y(t,{debug:e}):t;if(!me(n))return!1;let o=await h.fromServerDump({debug:e,name:n.name});if(r==null){e&&console.debug(`[State] No PID found for server "${n.name}" to kill.`);try{await o?.close()}catch{}return!1}let s=await ue(r,e);try{await o?.close()}catch{}return s}var L=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},U=class extends L{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return h.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError,deleteServer,getServerStatus,isServerRunning,killServer});
|
package/dist/state.d.cts
CHANGED
|
@@ -101,6 +101,7 @@ type ResolvedServerOptions = Required<ServerOptions>;
|
|
|
101
101
|
type PersistenceMode = "stateless" | "stateful";
|
|
102
102
|
interface ScanOptions {
|
|
103
103
|
debug?: boolean;
|
|
104
|
+
globs?: string[];
|
|
104
105
|
onlyMetadata?: boolean;
|
|
105
106
|
}
|
|
106
107
|
declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
|
|
@@ -146,6 +147,10 @@ declare class StatefulServerState extends ServerState {
|
|
|
146
147
|
interface ServerStatusV1 extends ServerDumpV1 {
|
|
147
148
|
status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
|
|
148
149
|
}
|
|
150
|
+
declare function deleteServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<void>;
|
|
151
|
+
declare function getServerStatus(nameOrState: string | StatefulServerState, options?: ScanOptions): Promise<ServerStatusV1>;
|
|
152
|
+
declare function isServerRunning(server: ServerStatusV1): boolean;
|
|
153
|
+
declare function killServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<boolean>;
|
|
149
154
|
/**
|
|
150
155
|
* @deprecated use `ServerAlreadyRunningError` instead. Will be removed in a future version.
|
|
151
156
|
*/
|
|
@@ -160,4 +165,4 @@ declare class ServerAlreadyRunningError extends ServerStateAlreadyExistsError {
|
|
|
160
165
|
get server(): Promise<ServerState | null>;
|
|
161
166
|
}
|
|
162
167
|
|
|
163
|
-
export { type Exports, type PersistenceMode, type ResolvedServerOptions, type ScanOptions, ServerAlreadyRunningError, type ServerDumpV1, type ServerOptions, ServerState, ServerStateAlreadyExistsError, type ServerStatusV1 };
|
|
168
|
+
export { type Exports, type PersistenceMode, type ResolvedServerOptions, type ScanOptions, ServerAlreadyRunningError, type ServerDumpV1, type ServerOptions, ServerState, ServerStateAlreadyExistsError, type ServerStatusV1, deleteServer, getServerStatus, isServerRunning, killServer };
|
package/dist/state.d.ts
CHANGED
|
@@ -101,6 +101,7 @@ type ResolvedServerOptions = Required<ServerOptions>;
|
|
|
101
101
|
type PersistenceMode = "stateless" | "stateful";
|
|
102
102
|
interface ScanOptions {
|
|
103
103
|
debug?: boolean;
|
|
104
|
+
globs?: string[];
|
|
104
105
|
onlyMetadata?: boolean;
|
|
105
106
|
}
|
|
106
107
|
declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
|
|
@@ -146,6 +147,10 @@ declare class StatefulServerState extends ServerState {
|
|
|
146
147
|
interface ServerStatusV1 extends ServerDumpV1 {
|
|
147
148
|
status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
|
|
148
149
|
}
|
|
150
|
+
declare function deleteServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<void>;
|
|
151
|
+
declare function getServerStatus(nameOrState: string | StatefulServerState, options?: ScanOptions): Promise<ServerStatusV1>;
|
|
152
|
+
declare function isServerRunning(server: ServerStatusV1): boolean;
|
|
153
|
+
declare function killServer(nameOrStatus: string | ServerStatusV1, debug?: boolean): Promise<boolean>;
|
|
149
154
|
/**
|
|
150
155
|
* @deprecated use `ServerAlreadyRunningError` instead. Will be removed in a future version.
|
|
151
156
|
*/
|
|
@@ -160,4 +165,4 @@ declare class ServerAlreadyRunningError extends ServerStateAlreadyExistsError {
|
|
|
160
165
|
get server(): Promise<ServerState | null>;
|
|
161
166
|
}
|
|
162
167
|
|
|
163
|
-
export { type Exports, type PersistenceMode, type ResolvedServerOptions, type ScanOptions, ServerAlreadyRunningError, type ServerDumpV1, type ServerOptions, ServerState, ServerStateAlreadyExistsError, type ServerStatusV1 };
|
|
168
|
+
export { type Exports, type PersistenceMode, type ResolvedServerOptions, type ScanOptions, ServerAlreadyRunningError, type ServerDumpV1, type ServerOptions, ServerState, ServerStateAlreadyExistsError, type ServerStatusV1, deleteServer, getServerStatus, isServerRunning, killServer };
|
package/dist/state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-FZ7JBZR6.js";import"./chunk-LMPFMHCB.js";import"./chunk-EPFUMVT3.js";export{g as ServerAlreadyRunningError,a as ServerState,f as ServerStateAlreadyExistsError,b as deleteServer,c as getServerStatus,d as isServerRunning,e as killServer};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma/dev",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.1",
|
|
4
4
|
"description": "A local Prisma Postgres server for development and testing",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -78,6 +78,7 @@
|
|
|
78
78
|
"@electric-sql/pglite-socket": "0.0.6",
|
|
79
79
|
"@electric-sql/pglite-tools": "0.2.7",
|
|
80
80
|
"@hono/node-server": "1.14.2",
|
|
81
|
+
"@mrleebo/prisma-ast": "0.12.1",
|
|
81
82
|
"@prisma/get-platform": "6.8.2",
|
|
82
83
|
"foreground-child": "3.3.1",
|
|
83
84
|
"get-port-please": "3.1.2",
|
|
@@ -88,7 +89,8 @@
|
|
|
88
89
|
"remeda": "2.21.3",
|
|
89
90
|
"sock-daemon": "1.4.2",
|
|
90
91
|
"std-env": "3.9.0",
|
|
91
|
-
"valibot": "1.1.0"
|
|
92
|
+
"valibot": "1.1.0",
|
|
93
|
+
"zeptomatch": "2.0.2"
|
|
92
94
|
},
|
|
93
95
|
"scripts": {
|
|
94
96
|
"build": "tsup",
|
|
@@ -1,4 +0,0 @@
|
|
|
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};
|
package/dist/chunk-I55EQWKN.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
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};
|
package/dist/chunk-VPXPYVXN.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
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};
|