@prisma/dev 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{b as i,d as E,e as d}from"./chunk-7EOUKLQR.js";import"./chunk-EPFUMVT3.js";import{HTTPException as ae}from"hono/http-exception";import{Hono as oe}from"hono/tiny";import{validator as p}from"hono/validator";import{array as k,literal as B,minLength as U,object as N,pipe as D,safeParse as F,string as Q,union as X}from"valibot";var Y=N({tags:X([D(k(Q()),U(1)),B("all")])});async function O(e){let{output:n,success:t}=F(Y,await e.req.json(),{abortEarly:!0});return t?n:e.text("Invalid input",400)}import{parseDuration as v,parseSize as z,Server as G}from"@prisma/query-plan-executor";import{version as P}from"@prisma/query-plan-executor";var T;async function x(e){return T===void 0&&(T=await G.create({databaseUrl:e.get("db").connectionString,maxResponseSize:z("128 MiB"),queryTimeout:v("PT5M"),maxTransactionTimeout:v("PT5M"),maxTransactionWaitTime:v("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.get("debug")?"debug":"off"}})),T}import{Buffer as I}from"buffer";import{getSchema as W,printSchema as K}from"@mrleebo/prisma-ast";var l=new Map;async function H(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}function C(e){let n=e.req.param("schemaHash"),t=l.get(n);return t==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:n,schemas:t}}async function R(e,n,t){let r=I.from(e,"base64").toString("utf8"),a=W(r),o=a.list.find(c=>c.type==="datasource");if(!o)throw new Error("No datasource block found in schema.");let s=o.assignments.find(c=>c.type==="assignment"&&c.key==="url");s?s.value=`"${n.toString()}"`:o.assignments.push({key:"url",type:"assignment",value:`"${n.toString()}"`});let m=K(a);t&&console.log("[Accelerate] schema with override:",m);let S=await H(m);return{base64Override:I.from(m,"utf8").toString("base64"),overrideHash:S}}function g(e){let{req:n}=e;return{traceparent:n.header("traceparent"),"X-capture-telemetry":n.header("X-capture-telemetry")}}import{integer as q,looseObject as J,minValue as A,number as b,object as Z,optional as ee,pipe as _,safeParse as M,string as $,union as te}from"valibot";var ne=Z({isolation_level:ee($()),max_wait:_(b(),q(),A(0)),timeout:_(b(),q(),A(0))});async function V(e){let{issues:n,output:t,success:r}=M(ne,await e.req.json(),{abortEarly:!0});return r?t:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:n}},400)}var re=J({id:te([$(),b()])});function j(e,n){let{output:t,success:r}=M(re,e);return r?t:n.json({EngineMalfunction:{}},500)}var y=new oe;y.post("/invalidate",p("header",i),async e=>{let n=await O(e);return n instanceof Response?n:e.body(null)});var se="/:clientVersion/:schemaHash",f=y.basePath(se);y.route("/",f);var ie=["/graphql","/itx/:transactionId/graphql"];f.on("POST",[...ie],p("header",i),async e=>{let{req:n}=e;try{let t=await w(e);if(t instanceof Response)return t;let r=await n.text(),a=n.param("transactionId"),o=await t.request(r,{...g(e),"X-transaction-id":a});return e.text(o)}catch(t){return d(t,e)}});f.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],p("header",i),async e=>{let{req:n}=e;try{let t=await w(e);if(t instanceof Response)return t;let a=`${n.routePath.split("/").filter(Boolean).at(-1)}Transaction`,o=n.param("transactionId"),s=await t[a](o,g(e));return e.json(s)}catch(t){return d(t,e)}});f.put("/schema",p("header",i),async e=>{let{req:n}=e,t=await n.text();if(!t)return e.text("Missing schema",400);let r=n.param("schemaHash"),a=l.get(r);if(a==null){if(r!==await H(t))return e.text("Schema hash mismatch",400);let o=await R(t,e.get("db").prismaORMConnectionString,e.get("debug"));return l.set(r,{base64Original:t,...o}),e.text(r)}return t!==a.base64Original?e.text("Schema mismatch",400):e.text(r)});f.post("/transaction/start",p("header",i),async e=>{let{req:n}=e,t=await V(e);if(t instanceof Response)return t;try{let r=await w(e);if(r instanceof Response)return r;let a=await r.startTransaction(t,g(e)),o=j(a,e);if(o instanceof Response)return o;let{id:s}=o,m=n.param("clientVersion"),S=e.get("port"),c=e.get("protocol"),L=n.param("schemaHash");return e.json({...a,"data-proxy":{endpoint:`${c}://localhost:${S}/${m}/${L}/itx/${s}`}})}catch(r){return d(r,e)}});async function w(e){let{req:n}=e,t=C(e);if(t instanceof Response)return t;let{base64Override:r,overrideHash:a}=t.schemas;return await E.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||n.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:a})}var ce=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[e,n]of ce)y.on(n,e,p("header",i),async t=>{let r=t.req.header("prisma-engine-hash");if(r!=="0.0.0"&&r!==P)throw new ae(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${r} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${P}.`});return await(await x(t)).fetch(t.req.raw)});export{y as accelerateRoute};
1
+ import{b as i,d as E,e as d}from"./chunk-GZSROICS.js";import"./chunk-ITQ6ILGR.js";import{HTTPException as ae}from"hono/http-exception";import{Hono as oe}from"hono/tiny";import{validator as p}from"hono/validator";import{array as k,literal as B,minLength as U,object as N,pipe as D,safeParse as F,string as Q,union as X}from"valibot";var Y=N({tags:X([D(k(Q()),U(1)),B("all")])});async function O(e){let{output:n,success:t}=F(Y,await e.req.json(),{abortEarly:!0});return t?n:e.text("Invalid input",400)}import{parseDuration as v,parseSize as z,Server as G}from"@prisma/query-plan-executor";import{version as P}from"@prisma/query-plan-executor";var T;async function x(e){return T===void 0&&(T=await G.create({databaseUrl:e.get("db").connectionString,maxResponseSize:z("128 MiB"),queryTimeout:v("PT5M"),maxTransactionTimeout:v("PT5M"),maxTransactionWaitTime:v("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.get("debug")?"debug":"off"}})),T}import{Buffer as I}from"buffer";import{getSchema as W,printSchema as K}from"@mrleebo/prisma-ast";var l=new Map;async function H(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("")}function C(e){let n=e.req.param("schemaHash"),t=l.get(n);return t==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:n,schemas:t}}async function R(e,n,t){let r=I.from(e,"base64").toString("utf8"),a=W(r),o=a.list.find(c=>c.type==="datasource");if(!o)throw new Error("No datasource block found in schema.");let s=o.assignments.find(c=>c.type==="assignment"&&c.key==="url");s?s.value=`"${n.toString()}"`:o.assignments.push({key:"url",type:"assignment",value:`"${n.toString()}"`});let m=K(a);t&&console.log("[Accelerate] schema with override:",m);let S=await H(m);return{base64Override:I.from(m,"utf8").toString("base64"),overrideHash:S}}function g(e){let{req:n}=e;return{traceparent:n.header("traceparent"),"X-capture-telemetry":n.header("X-capture-telemetry")}}import{integer as q,looseObject as J,minValue as A,number as b,object as Z,optional as ee,pipe as _,safeParse as M,string as $,union as te}from"valibot";var ne=Z({isolation_level:ee($()),max_wait:_(b(),q(),A(0)),timeout:_(b(),q(),A(0))});async function V(e){let{issues:n,output:t,success:r}=M(ne,await e.req.json(),{abortEarly:!0});return r?t:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:n}},400)}var re=J({id:te([$(),b()])});function j(e,n){let{output:t,success:r}=M(re,e);return r?t:n.json({EngineMalfunction:{}},500)}var y=new oe;y.post("/invalidate",p("header",i),async e=>{let n=await O(e);return n instanceof Response?n:e.body(null)});var se="/:clientVersion/:schemaHash",f=y.basePath(se);y.route("/",f);var ie=["/graphql","/itx/:transactionId/graphql"];f.on("POST",[...ie],p("header",i),async e=>{let{req:n}=e;try{let t=await w(e);if(t instanceof Response)return t;let r=await n.text(),a=n.param("transactionId"),o=await t.request(r,{...g(e),"X-transaction-id":a});return e.text(o)}catch(t){return d(t,e)}});f.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],p("header",i),async e=>{let{req:n}=e;try{let t=await w(e);if(t instanceof Response)return t;let a=`${n.routePath.split("/").filter(Boolean).at(-1)}Transaction`,o=n.param("transactionId"),s=await t[a](o,g(e));return e.json(s)}catch(t){return d(t,e)}});f.put("/schema",p("header",i),async e=>{let{req:n}=e,t=await n.text();if(!t)return e.text("Missing schema",400);let r=n.param("schemaHash"),a=l.get(r);if(a==null){if(r!==await H(t))return e.text("Schema hash mismatch",400);let o=await R(t,e.get("db").prismaORMConnectionString,e.get("debug"));return l.set(r,{base64Original:t,...o}),e.text(r)}return t!==a.base64Original?e.text("Schema mismatch",400):e.text(r)});f.post("/transaction/start",p("header",i),async e=>{let{req:n}=e,t=await V(e);if(t instanceof Response)return t;try{let r=await w(e);if(r instanceof Response)return r;let a=await r.startTransaction(t,g(e)),o=j(a,e);if(o instanceof Response)return o;let{id:s}=o,m=n.param("clientVersion"),S=e.get("port"),c=e.get("protocol"),L=n.param("schemaHash");return e.json({...a,"data-proxy":{endpoint:`${c}://localhost:${S}/${m}/${L}/itx/${s}`}})}catch(r){return d(r,e)}});async function w(e){let{req:n}=e,t=C(e);if(t instanceof Response)return t;let{base64Override:r,overrideHash:a}=t.schemas;return await E.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||n.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:a})}var ce=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[e,n]of ce)y.on(n,e,p("header",i),async t=>{let r=t.req.header("prisma-engine-hash");if(r!=="0.0.0"&&r!==P)throw new ae(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${r} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${P}.`});return await(await x(t)).fetch(t.req.raw)});export{y as accelerateRoute};
@@ -0,0 +1 @@
1
+ import{f as g}from"./chunk-LMPFMHCB.js";import{e as p}from"./chunk-ITQ6ILGR.js";import{filename as P}from"pathe/utils";var o={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},S=`postgres://${o.username}:${o.password}@localhost`,D=new URLSearchParams({sslmode:o.sslMode}),h=new URLSearchParams({...Object.fromEntries(D.entries()),connection_limit:String(o.connectionLimit),connect_timeout:String(o.connectTimeout),max_idle_connection_lifetime:String(o.maxIdleConnectionLifetime),pool_timeout:String(o.poolTimeout),single_use_connections:"true",socket_timeout:String(o.socketTimeout)});async function B(e,t){let n=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return b(e,t,{db:null,port:n,server:null});let{debug:i}=t,a=await(e==="shadow_database"?T:y)(t.pgliteDataDirPath,i);i&&a.onNotification((d,l)=>{console.debug(`[${e}][${d}] ${l}`)});let{PGLiteSocketHandler:m,PGLiteSocketServer:s}=await import("@electric-sql/pglite-socket"),c=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis;v(c,a,m);let u=new s({connectionQueueTimeout:e==="shadow_database"?t.shadowDatabaseConnectTimeoutMillis:t.databaseConnectTimeoutMillis,db:a,debug:i,inspect:i,port:n});i&&(u.addEventListener("listening",d=>{let{detail:l}=d;console.debug(`[${e}] server listening on ${JSON.stringify(l)}`)}),u.addEventListener("connection",d=>{let{clientAddress:l,clientPort:w}=d.detail;console.debug(`[${e}] client connected from ${l}:${w}`)}),u.addEventListener("error",d=>{let{detail:l}=d;console.error(`[${e}] server error:`,l)}));try{await u.start()}catch(d){throw d instanceof Error&&"code"in d&&d.code==="EADDRINUSE"?new g(n):d}return b(e,t,{db:a,port:n,server:u})}function b(e,t,n){let{debug:i}=t,{db:r,port:a,server:m}=n||{};return i&&console.debug(`[${e}] server started on port ${a}`),{...o,close:async()=>{let s=[];try{await m?.stop(),i&&console.debug(`[${e}] server stopped on port ${a}`)}catch(c){console.error(`[${e}] server stop error`,c),s.push(c)}if(e==="database")try{await r?.syncToFs(),i&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),s.push(c)}try{await r?.close(),i&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),s.push(c)}if(s.length>0)throw new AggregateError(s,`Failed to close ${e} properly`)},connectionString:f(a,D),dump:async s=>{e==="shadow_database"||!r||await E({db:r,debug:i,destinationPath:s})},port:a,prismaORMConnectionString:f(a,h),terminalCommand:`PGPASSWORD=${o.password} PGSSLMODE=${o.sslMode} psql -h localhost -p ${a} -U ${o.username} -d ${o.database}`}}function f(e,t){return`${S}:${e}/${o.database}?${t.toString()}`}async function y(e,t){let{PGlite:n}=await import("@electric-sql/pglite");return await n.create({database:o.database,dataDir:e,debug:t?5:void 0,extensions:await _(),relaxedDurability:!1,username:o.username})}async function T(e,t){let{PGlite:n}=await import("@electric-sql/pglite");return await n.create({database:o.database,dataDir:"memory://",debug:t?5:void 0,extensions:await _(),relaxedDurability:!1,username:o.username})}async function _(){let e=await Promise.all([import("@electric-sql/pglite/contrib/amcheck"),import("@electric-sql/pglite/contrib/bloom"),import("@electric-sql/pglite/contrib/btree_gin"),import("@electric-sql/pglite/contrib/btree_gist"),import("@electric-sql/pglite/contrib/citext"),import("@electric-sql/pglite/contrib/cube"),import("@electric-sql/pglite/contrib/dict_int"),import("@electric-sql/pglite/contrib/dict_xsyn"),import("@electric-sql/pglite/contrib/earthdistance"),import("@electric-sql/pglite/contrib/file_fdw"),import("@electric-sql/pglite/contrib/fuzzystrmatch"),import("@electric-sql/pglite/contrib/hstore"),import("@electric-sql/pglite/contrib/intarray"),import("@electric-sql/pglite/contrib/isn"),import("@electric-sql/pglite/contrib/lo"),import("@electric-sql/pglite/contrib/ltree"),import("@electric-sql/pglite/contrib/pageinspect"),import("@electric-sql/pglite/contrib/pg_buffercache"),import("@electric-sql/pglite/contrib/pg_freespacemap"),import("@electric-sql/pglite/contrib/pg_surgery"),import("@electric-sql/pglite/contrib/pg_trgm"),import("@electric-sql/pglite/contrib/pg_visibility"),import("@electric-sql/pglite/contrib/pg_walinspect"),import("@electric-sql/pglite/contrib/seg"),import("@electric-sql/pglite/contrib/tablefunc"),import("@electric-sql/pglite/contrib/tcn"),import("@electric-sql/pglite/contrib/tsm_system_rows"),import("@electric-sql/pglite/contrib/tsm_system_time"),import("@electric-sql/pglite/contrib/unaccent"),import("@electric-sql/pglite/contrib/uuid_ossp"),import("@electric-sql/pglite/vector")]);return Object.assign({},...e)}function v(e,t,n){if(t.__IDLE_TIMEOUT__=e,n.prototype.__ATTACH_OVERRIDDEN__)return;n.prototype.__ATTACH_OVERRIDDEN__=!0;let i=n.prototype.attach;n.prototype.attach=async function(r){let a=await i.call(this,r);if(!Number.isFinite(this.db.__IDLE_TIMEOUT__))return a;let m=null,s=()=>{m!=null&&(clearTimeout(m),m=null)},c=()=>{s(),m=setTimeout(()=>{this.dispatchEvent(new CustomEvent("close")),this.detach(!1)},this.db.__IDLE_TIMEOUT__)};return r.on("error",()=>{s()}),r.on("data",()=>{c()}),r.on("close",()=>{s()}),c(),a}}async function E(e){let{dataDir:t,db:n,debug:i,destinationPath:r}=e,a=n||await y(t,i),{pgDump:m}=await import("@electric-sql/pglite-tools/pg_dump"),s=await m({args:["--schema-only","--no-owner"],fileName:r?P(r):void 0,pg:await a.clone()});return r?(i&&console.debug(`[DB] Dumping database to ${r}`),await p(s,r)):(i&&console.debug("[DB] Dumping database to memory"),await s.text())}export{B as a,E as b};
@@ -1,3 +1,3 @@
1
- import{a as P,c as b,d as v}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(`
1
+ import{a as P,c as b,d as v}from"./chunk-ITQ6ILGR.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{binaryTarget: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 b(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 v(await a.arrayBuffer(),t),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",t)}#s(e){let n={};for(let[s,t]of Object.entries(e))t!=null&&(n[s]=t);return n}async#i(e,n,s){let{url:t}=await this.#n,o=this.#s(n),i=await fetch(`${t}/transaction/${e}/${s}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await u.fromResponse(i);try{return await i.json()}catch{return{}}}};function de(r,e){return console.error(r),r instanceof g?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:r.message}}}},500):r instanceof u?e.text(r.responseBody,r.statusCode):e.body(null,500)}var g=class extends Error{name="EngineStartError"},u=class r extends Error{constructor(n,s,t){super(`${n}: Query Engine response status ${s}, body: ${t}`);this.action=n;this.statusCode=s;this.responseBody=t}name="EngineHttpError";static async fromResponse(n){let s=new URL(n.url),t=await n.text();return new r(s.pathname,n.status,t)}};export{W as a,Y as b,O as c,x as d,de as e};
@@ -0,0 +1 @@
1
+ import{createWriteStream as w,WriteStream as A}from"fs";import{access as D,chmod as x,constants as P,mkdir as T,readdir as E,readFile as _,rm as F,writeFile as O}from"fs/promises";import{promisify as v}from"util";import{unzip as C}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=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)}},y=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"?h(t):c.platform==="win32"?y(t):j(t)}import L from"zeptomatch";var l=p("prisma-dev"),G=v(C);function z(t,r){return`${l.cache}/engine/${t}/${r}`}function B(t){return`${l.data}/${t}`}async function J(t){try{return await D(t,P.F_OK),!0}catch(r){if(u(r))return!1;throw r}}async function K(t,r){let i=await G(t);await O(r,i),await x(r,"755")}async function q(t,r){await t.stream().pipeTo(A.toWeb(w(r,{encoding:"utf8"})))}function u(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Q(t){try{return await _(t,{encoding:"utf-8"})}catch(r){if(u(r))return null;throw r}}async function U(t){await T(t,{recursive:!0})}async function V(t,r){try{return(await E(t,{withFileTypes:!0})).reduce((f,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!r||L(r,s.name))&&f.push(s.name),f),[])}catch(i){if(u(i))return[];throw i}}async function Y(t){await F(t,{force:!0,recursive:!0})}export{z as a,B 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{d as b,e as S}from"./chunk-LMPFMHCB.js";import{b as l,f as R,g as O,h as V,i as C}from"./chunk-ITQ6ILGR.js";import{writeFile as z}from"fs/promises";import{join as c}from"pathe";import{check as Q,lock as W,unlock as X}from"proper-lockfile";import{process as J}from"std-env";import{integer as j,literal as ee,minLength as te,minValue as F,number as q,object as P,optional as g,parseJson as re,pipe as p,safeParse as se,string as v,url as ae}from"valibot";import{setTimeout as Z}from"timers/promises";import{process as f}from"std-env";function y(r,e){if(r==null)return!1;try{return f.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}async function N(r,e){if(!f.kill)return!1;try{f.kill(r,"SIGTERM")}catch(o){return e&&console.error(`Error killing process with PID ${r}:`,o),!1}let t=0;do{if(!y(r,e))return!0;await Z(100)}while(++t<50);try{return f.kill(r,"SIGKILL")}catch(o){return e&&console.error(`Error forcefully killing process with PID ${r}:`,o),!1}}var k=p(v(),ae()),A=P({connectionString:k,prismaORMConnectionString:g(k),terminalCommand:g(v())}),L=P({url:k}),x=p(q(),j(),F(1)),oe=P({database:A,http:L,ppg:L,shadowDatabase:A}),ie=P({databasePort:x,exports:g(oe),name:p(v(),te(1)),pid:g(p(q(),j(),F(0))),port:x,shadowDatabasePort:x,version:ee("1")}),T=Symbol("initialize"),M="default",u=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??b,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??M,this.persistenceMode=e.persistenceMode,this.pid=e.pid??J.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??b,this._shadowDatabasePort=e.shadowDatabasePort??b}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new h(e):new _(e);return await t[T](),t}static async fromServerDump(e){let{debug:t,name:o=M}=e??{},a=l(o),i=h.getServerDumpPath(a),s=await R(i);if(s==null)return t&&console.debug(`[State] No server dump file found at: ${i}`),null;t&&(console.debug(`[State] server dump file found at "${i}":`),console.debug(s));let{issues:n,output:d,success:m}=se(p(v(),re(),ie),s);if(!m)throw t&&console.debug(`[State] Invalid server dump file at "${i}":
2
+ ${JSON.stringify(n,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new h({databasePort:d.databasePort,debug:t,dryRun:!1,name:o,pid:d.pid,port:d.port,serverDump:d,shadowDatabasePort:d.shadowDatabasePort})}static async scan(e){let{debug:t,globs:o}=e??{},a=c(l(M),"..");t&&console.debug(`[State] scanning for server states in: ${a}`);let i=await V(a,o);return t&&console.debug(`[State] found server names: ${JSON.stringify(i)}`),await Promise.all(i.map(s=>H(s,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},_=class extends u{constructor(e){super({...e,databasePort:e?.databasePort,persistenceMode:"stateless",port:e?.port,shadowDatabasePort:e?.shadowDatabasePort})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[T](){let e;try{e=await u.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let t=await S({debug:this.debug,name:this.dryRun?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}async close(){}async writeServerDump(){}},h=class r extends u{#t;#e;#s;#o;#i;#a;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#a=!1,this.#e=l(this.name),this.#t=c(this.#e,"db_dump.bak"),this.#s=c(this.#e,".lock"),this.#o=c(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#i=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return c(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[T](){await O(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await W(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await u.scan({debug:this.debug,onlyMetadata:!0}),t=await S({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 $(this):e}}async close(){if(!this.#a)try{await X(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:J.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await z(this.#i,`${JSON.stringify(this.#r,null,2)}
3
+ `,{encoding:"utf-8"})}};async function we(r,e){await ue(r,e);let t=l(typeof r=="string"?r:r.name);await C(t)}async function H(r,e){let{debug:t,onlyMetadata:o}=e||{},a=typeof r=="string"?r:r.name,i=typeof r!="string"?r:void 0,s={databasePort:i?.databasePort??-1,exports:i?.exports,name:a,pid:i?.pid,port:i?.port??-1,shadowDatabasePort:i?.shadowDatabasePort??-1,version:"1"};try{let n=i||await u.fromServerDump({debug:t,name:a});if(!n)return t&&console.debug(`[State] no server state found for name: ${a}`),{...s,status:"no_such_server"};s.databasePort=n.databasePort,s.exports=n.exports,s.pid=n.pid,s.port=n.port,s.shadowDatabasePort=n.shadowDatabasePort;let{exports:d,pid:m}=n;if(o)return{...s,status:"unknown"};if(!y(m,t))return t&&console.debug(`[State] server state for "${a}" has no running process with PID: ${m}`),{...s,status:"not_running"};let E=l(a);try{if(!await Q(E,{lockfilePath:c(E,".lock")}))return t&&console.debug(`[State] server state for "${a}" is not locked, indicating it is not running.`),{...s,status:"starting_up"}}catch(G){t&&console.error(`[State] server state for "${a}" failed to check lock:`,G)}if(!d)return{...s,status:"starting_up"};let{http:K}=d,{hc:B}=await import("hono/client"),D=await B(K.url).health.$get();if(!D.ok)return t&&console.debug(`[State] server state for "${a}" is not live: ${JSON.stringify(D)}`),{...s,status:"not_running"};let w=await D.json();return w.name!==r?(t&&console.debug(`[State] server state for "${a}" has mismatched health response: ${JSON.stringify(w)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(w)}`),{...s,status:"running"})}catch(n){return t&&console.error(`[State] failed to get server status for "${a}":`,n),{...s,status:"error"}}}function ne(r){let{status:e}=r;return e==="running"||e==="starting_up"}async function ue(r,e){let{pid:t,...o}=typeof r=="string"?await H(r,{debug:e}):r;if(!ne(o))return!1;let a=await u.fromServerDump({debug:e,name:o.name});if(t==null){e&&console.debug(`[State] No PID found for server "${o.name}" to kill.`);try{await a?.close()}catch{}return!1}let i=await N(t,e);try{await a?.close()}catch{}return i}var I=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},$=class extends I{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return u.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{u as a,we as b,H as c,ne as d,ue as e,I as f,$ as g};
@@ -1 +1 @@
1
- import{a as d}from"./chunk-RBVZVBDC.js";import{a as w}from"./chunk-ZCVJ53EE.js";import{f as u}from"./chunk-LMPFMHCB.js";import{a as f,c as v,d as g}from"./chunk-7EOUKLQR.js";import{createServer as A}from"http";import{promisify as R}from"util";import T from"@prisma/get-platform";async function P(o,e){let{port:r}=e;if(e.dryRun)return y(r,null);let t=await D(r,o,e),{promise:s,reject:S,resolve:l}=v(),{serve:i}=await import("@hono/node-server"),m=i({createServer:A,fetch:t.fetch,overrideGlobalObjects:!1,port:r},l);return m.on("error",n=>{if(typeof n=="object"&&"code"in n&&n.code==="EADDRINUSE")return S(new u(r));console.error("[Accelerate]",n)}),await s,y(r,m)}function y(o,e){return{async close(){e&&await Promise.allSettled([R(e.close.bind(e))(),g.stopAll()])},port:o,url:`http://localhost:${o}`}}async function D(o,e,r){let{debug:t}=r,[{Hono:s},{accelerateRoute:S},{utilityRoute:l}]=await Promise.all([import("hono/tiny"),import("./accelerate-UHQZHRYG.js"),import("./utility-YJ4TFSMW.js")]),i=new s,m=await T.getPlatformInfo();if(t&&console.debug("[Accelerate] platform info: %s",JSON.stringify(m)),t){let{logger:a}=await import("hono/logger");i.use("*",a((...p)=>console.log("[Accelerate]",...p)))}i.use("*",async(a,p)=>(a.set("db",e),a.set("debug",!!t),a.set("platform",m),a.set("port",o),a.set("protocol","http"),a.set("serverState",r),a.set("shadowDBPort",r.shadowDatabasePort),await p()));let n=new s;return n.route("/",S),n.route("/",l),i.route("/",n),i}async function E(o){let e=await w.createExclusively(o),[r,t]=await Promise.all([d("database",e),d("shadow_database",e)]),s=await P(r,e),S=`prisma+postgres://localhost:${s.port}/?${new URLSearchParams({api_key:f({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`,l={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(l),{...l,close:()=>i(e,[s,r,t]),name:e.name};async function i(m,n){let p=(await Promise.allSettled(n.map(c=>c.close()))).filter(c=>c.status==="rejected").map(c=>new Error(c.reason));try{await m.close()}catch(c){p.push(c)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}async function J(o){return await E(o)}export{E as a,J as b};
1
+ import{a as d}from"./chunk-3BZW3EVN.js";import{a as w}from"./chunk-MO5SCYLN.js";import{f as u}from"./chunk-LMPFMHCB.js";import{a as f,c as v,d as g}from"./chunk-GZSROICS.js";import{createServer as A}from"http";import{promisify as R}from"util";import T from"@prisma/get-platform";async function P(o,e){let{port:r}=e;if(e.dryRun)return y(r,null);let t=await D(r,o,e),{promise:s,reject:S,resolve:l}=v(),{serve:i}=await import("@hono/node-server"),m=i({createServer:A,fetch:t.fetch,overrideGlobalObjects:!1,port:r},l);return m.on("error",n=>{if(typeof n=="object"&&"code"in n&&n.code==="EADDRINUSE")return S(new u(r));console.error("[Accelerate]",n)}),await s,y(r,m)}function y(o,e){return{async close(){e&&await Promise.allSettled([R(e.close.bind(e))(),g.stopAll()])},port:o,url:`http://localhost:${o}`}}async function D(o,e,r){let{debug:t}=r,[{Hono:s},{accelerateRoute:S},{utilityRoute:l}]=await Promise.all([import("hono/tiny"),import("./accelerate-ZET2GIPN.js"),import("./utility-YJ4TFSMW.js")]),i=new s,m=await T.getPlatformInfo();if(t&&console.debug("[Accelerate] platform info: %s",JSON.stringify(m)),t){let{logger:a}=await import("hono/logger");i.use("*",a((...p)=>console.log("[Accelerate]",...p)))}i.use("*",async(a,p)=>(a.set("db",e),a.set("debug",!!t),a.set("platform",m),a.set("port",o),a.set("protocol","http"),a.set("serverState",r),a.set("shadowDBPort",r.shadowDatabasePort),await p()));let n=new s;return n.route("/",S),n.route("/",l),i.route("/",n),i}async function E(o){let e=await w.createExclusively(o),[r,t]=await Promise.all([d("database",e),d("shadow_database",e)]),s=await P(r,e),S=`prisma+postgres://localhost:${s.port}/?${new URLSearchParams({api_key:f({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`,l={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(l),{...l,close:()=>i(e,[s,r,t]),name:e.name};async function i(m,n){let p=(await Promise.allSettled(n.map(c=>c.close()))).filter(c=>c.status==="rejected").map(c=>new Error(c.reason));try{await m.close()}catch(c){p.push(c)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}async function J(o){return await E(o)}export{E as a,J as b};
package/dist/daemon.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var Nt=Object.create;var G=Object.defineProperty;var Ut=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Vt=Object.getPrototypeOf,Ft=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var _e=(t,e)=>{for(var r in e)G(t,r,{get:e[r],enumerable:!0})},ke=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qt(e))!Ft.call(t,n)&&n!==r&&G(t,n,{get:()=>e[n],enumerable:!(o=Ut(e,n))||o.enumerable});return t};var v=(t,e,r)=>(r=t!=null?Nt(Vt(t)):{},ke(e||!t||!t.__esModule?G(r,"default",{value:t,enumerable:!0}):r,t)),Gt=t=>ke(G({},"__esModule",{value:!0}),t);var l=D(()=>{"use strict"});function Ce(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function Qt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:o,success:n}=(0,f.safeParse)(Kt,e,{abortEarly:!0});return n?[null,o]:[r]}var f,Ie,Kt,k,se=D(()=>{"use strict";l();f=require("valibot"),Ie=/^(postgres|postgresql):\/\//,Kt=(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)(Ie)),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)(Ie))}));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]=Qt(s);if(i)throw new o(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:u,name:p,shadowDatabaseUrl:g}=c,{name:b}=e.get("serverState");if(!p)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(p!==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 "${p}"`});let{hostname:x,port:R}=new URL(u),{port:j}=e.get("db"),{hostname:Lt,port:Bt}=new URL(g),jt=e.get("shadowDBPort");if(x!=="localhost"||Number(R)!==j||Lt!=="localhost"||Number(Bt)!==jt)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}`),K.default.platform==="darwin"?Jt(t):K.default.platform==="win32"?Wt(t):zt(t)}var h,ae,K,O,ie,M,Jt,Wt,zt,Me=D(()=>{"use strict";l();h=v(require("path"),1),ae=v(require("os"),1),K=v(require("process"),1),O=ae.default.homedir(),ie=ae.default.tmpdir(),{env:M}=K.default,Jt=t=>{let e=h.default.join(O,"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)}},Wt=t=>{let e=M.APPDATA||h.default.join(O,"AppData","Roaming"),r=M.LOCALAPPDATA||h.default.join(O,"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)}},zt=t=>{let e=h.default.basename(O);return{data:h.default.join(M.XDG_DATA_HOME||h.default.join(O,".local","share"),t),config:h.default.join(M.XDG_CONFIG_HOME||h.default.join(O,".config"),t),cache:h.default.join(M.XDG_CACHE_HOME||h.default.join(O,".cache"),t),log:h.default.join(M.XDG_STATE_HOME||h.default.join(O,".local","state"),t),temp:h.default.join(ie,e,t)}}});function Ne(t,e){return`${je.cache}/engine/${t}/${e}`}function N(t){return`${je.data}/${t}`}async function Ue(t){try{return await(0,w.access)(t,w.constants.F_OK),!0}catch(e){if(ue(e))return!1;throw e}}async function qe(t,e){let r=await Xt(t);await(0,w.writeFile)(e,r),await(0,w.chmod)(e,"755")}async function Ve(t,e){await t.stream().pipeTo(Q.WriteStream.toWeb((0,Q.createWriteStream)(e,{encoding:"utf-8"})))}function ue(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Fe(t){try{return await(0,w.readFile)(t,{encoding:"utf-8"})}catch(e){if(ue(e))return null;throw e}}async function Ge(t){await(0,w.mkdir)(t,{recursive:!0})}async function Ke(t,e){try{return(await(0,w.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,Be.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(ue(r))return[];throw r}}var Q,w,He,Le,Be,je,Xt,J=D(()=>{"use strict";l();Q=require("fs"),w=require("fs/promises"),He=require("util"),Le=require("zlib");Me();Be=v(require("zeptomatch"),1),je=ce("prisma-dev"),Xt=(0,He.promisify)(Le.unzip)});function X(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 ye=D(()=>{"use strict";l()});function Y(t,e){return console.error(t),t instanceof U?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof H?e.text(t.responseBody,t.statusCode):e.body(null,500)}var et,tt,rt,ot,nt,st,ar,ir,Ze,L,U,H,Pe=D(()=>{"use strict";l();et=require("child_process"),tt=require("events"),rt=require("fs/promises"),ot=require("path"),nt=require("timers/promises");ye();st=require("std-env");J();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:ar,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:ir,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Ze}=st.process.env),L=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,o=`${e.schemaHash}:${e.clientVersion}`;try{let n=t.#r.get(o);if(n)return n;let s=new t(e);return t.#r.set(o,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(o)}}static async stopAll(e){let o=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([n])=>n!==e).map(async([n,s])=>{try{await s.stop()}finally{t.#r.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(o.length>0)throw new AggregateError(o,"Failed to stop engines")}async commitTransaction(e,r){return await this.#i(e,r,"commit")}async request(e,r){let{url:o}=await this.start(),n=this.#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 H.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#i(e,r,"rollback")}async startTransaction(e,r){let{url:o}=await this.start(),n=this.#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 H.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:o}=X();this.#t=e;let n=ir||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,et.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=p=>{let g=p.split(`
2
- `).find(j=>j.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: ${p}`));let{ip:x,port:R}=b;if(x==null||R==null)return r(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
- Received data: ${p}`));o({childProcess:a,url:`http://${x}:${R}`})},c=p=>{this.#t=null,r(new U(String(p))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(p,g)=>{this.#t=null,r(new U(`Query Engine exited with code ${p} 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,tt.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=Ne(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,rt.mkdir)(r,{recursive:!0});let{binaryTarget:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,ot.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(ar==="1"||await Ue(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}`);Ze&&await(0,nt.setTimeout)(Number(Ze)),await qe(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 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 at(t){let{output:e,success:r}=(0,S.safeParse)(cr,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var S,cr,it=D(()=>{"use strict";l();S=require("valibot"),cr=(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 ct(t){return be===void 0&&(be=await _.Server.create({databaseUrl:t.get("db").connectionString,maxResponseSize:(0,_.parseSize)("128 MiB"),queryTimeout:(0,_.parseDuration)("PT5M"),maxTransactionTimeout:(0,_.parseDuration)("PT5M"),maxTransactionWaitTime:(0,_.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.get("debug")?"debug":"off"}})),be}var _,Z,be,ut=D(()=>{"use strict";l();_=require("@prisma/query-plan-executor"),Z=require("@prisma/query-plan-executor")});async function ve(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 dt(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 lt(t,e,r){let o=Se.Buffer.from(t,"base64").toString("utf8"),n=(0,ee.getSchema)(o),s=n.list.find(u=>u.type==="datasource");if(!s)throw new Error("No datasource block found in schema.");let a=s.assignments.find(u=>u.type==="assignment"&&u.key==="url");a?a.value=`"${e.toString()}"`:s.assignments.push({key:"url",type:"assignment",value:`"${e.toString()}"`});let i=(0,ee.printSchema)(n);r&&console.log("[Accelerate] schema with override:",i);let c=await ve(i);return{base64Override:Se.Buffer.from(i,"utf8").toString("base64"),overrideHash:c}}var Se,ee,te,pt=D(()=>{"use strict";l();Se=require("buffer"),ee=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 mt=D(()=>{"use strict";l()});async function ft(t){let{issues:e,output:r,success:o}=(0,m.safeParse)(ur,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}function ht(t,e){let{output:r,success:o}=(0,m.safeParse)(dr,t);return o?r:e.json({EngineMalfunction:{}},500)}var m,ur,dr,gt=D(()=>{"use strict";l();m=require("valibot"),ur=(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))});dr=(0,m.looseObject)({id:(0,m.union)([(0,m.string)(),(0,m.number)()])})});var bt={};_e(bt,{accelerateRoute:()=>q});async function we(t){let{req:e}=t,r=dt(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 yt,Pt,I,q,lr,V,pr,mr,St=D(()=>{"use strict";l();yt=require("hono/http-exception"),Pt=require("hono/tiny"),I=require("hono/validator");se();it();Pe();ut();pt();mt();gt();q=new Pt.Hono;q.post("/invalidate",(0,I.validator)("header",k),async t=>{let e=await at(t);return e instanceof Response?e:t.body(null)});lr="/:clientVersion/:schemaHash",V=q.basePath(lr);q.route("/",V);pr=["/graphql","/itx/:transactionId/graphql"];V.on("POST",[...pr],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await we(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 Y(r,t)}});V.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await we(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 Y(r,t)}});V.put("/schema",(0,I.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 ve(r))return t.text("Schema hash mismatch",400);let s=await lt(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,I.validator)("header",k),async t=>{let{req:e}=t,r=await ft(t);if(r instanceof Response)return r;try{let o=await we(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,re(t)),s=ht(n,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),u=t.get("protocol"),p=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${u}://localhost:${c}/${i}/${p}/itx/${a}`}})}catch(o){return Y(o,t)}});mr=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[t,e]of mr)q.on(e,t,(0,I.validator)("header",k),async r=>{let o=r.req.header("prisma-engine-hash");if(o!=="0.0.0"&&o!==Z.version)throw new yt.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${o} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${Z.version}.`});return await(await ct(r)).fetch(r.req.raw)})});var Dt={};_e(Dt,{utilityRoute:()=>De});var vt,wt,De,io,Et=D(()=>{"use strict";l();vt=require("hono/tiny"),wt=require("http-status-codes"),De=new vt.Hono;De.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},wt.StatusCodes.CREATED)});io=De.get("/health",t=>t.json({name:t.get("serverState").name}))});var Sr={};module.exports=Gt(Sr);l();var Ht=require("timers/promises");l();se();l();var ze=require("pathe/utils");J();l();var $=require("get-port-please"),z=require("remeda"),de=51214,le=51213,pe=51215,W=65535,A=-1/0;async function he(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=er(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:A,port:A,shadowDatabasePort:A},c=["port","databasePort","shadowDatabasePort"];for(let u of c){let p=await Yt({debug:e,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await Zt({debug:e,pickedPorts:i,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${u}": ${p}`),i[u]=p}return e&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function Yt(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s}=t,{[r]:a,...i}=s;if(Qe(a))return await tr({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let c=n?.[r]??A;if(!Qe(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 Zt(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(de,le,pe)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,W),u=(0,z.difference)((0,z.range)(a,c),i),p={port:le,databasePort:de,shadowDatabasePort:pe}[o];try{return await(0,$.getPort)({port:p in n||Object.values(r).includes(p)||Object.values(s||{}).includes(p)?void 0:p,ports:u})}catch(g){if(g instanceof Error&&g.name==="GetPortError"&&c+1<=W)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${W}].`),await(0,$.getPort)({portRange:[c+1,W]});throw g}}function Qe(t){return t>=0}function er(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 tr(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 fe(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${o}", but also for another key.`),new me(s);if((0,$.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${o}", but is unsafe.`),new T(s);if(await(0,$.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${o}", but is not available.`),new T(s)}var T=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},me=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"},fe=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 P={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},rr=`postgres://${P.username}:${P.password}@localhost`,Xe=new URLSearchParams({sslmode:P.sslMode}),or=new URLSearchParams({...Object.fromEntries(Xe.entries()),connection_limit:String(P.connectionLimit),connect_timeout:String(P.connectTimeout),max_idle_connection_lifetime:String(P.maxIdleConnectionLifetime),pool_timeout:String(P.poolTimeout),single_use_connections:"true",socket_timeout:String(P.socketTimeout)});async function ge(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Je(t,e,{db:null,port:r,server:null});let{debug:o}=e,s=await(t==="shadow_database"?nr:Ye)(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:p}=c.detail;console.debug(`[${t}] client connected from ${u}:${p}`)}),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 T(r):c}return Je(t,e,{db:s,port:r,server:i})}function Je(t,e,r){let{debug:o}=e,{db:n,port:s,server:a}=r||{};return o&&console.debug(`[${t}] server started on port ${s}`),{...P,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:We(s,Xe),dump:async i=>{t==="shadow_database"||!n||await sr({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:We(s,or),terminalCommand:`PGPASSWORD=${P.password} PGSSLMODE=${P.sslMode} psql -h localhost -p ${s} -U ${P.username} -d ${P.database}`}}function We(t,e){return`${rr}:${t}/${P.database}?${e.toString()}`}async function Ye(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:P.database,dataDir:t,debug:e?5:void 0,relaxedDurability:!1,username:P.username})}async function nr(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:P.database,dataDir:"memory://",debug:e?5:void 0,relaxedDurability:!1,username:P.username})}async function sr(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Ye(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:n?(0,ze.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await Ve(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}l();var xt=require("http"),Rt=require("util"),Ot=v(require("@prisma/get-platform"),1);ye();Pe();async function At(t,e){let{port:r}=e;if(e.dryRun)return Tt(r,null);let o=await fr(r,t,e),{promise:n,reject:s,resolve:a}=X(),{serve:i}=await import("@hono/node-server"),c=i({createServer:xt.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 T(r));console.error("[Accelerate]",u)}),await n,Tt(r,c)}function Tt(t,e){return{async close(){e&&await Promise.allSettled([(0,Rt.promisify)(e.close.bind(e))(),L.stopAll()])},port:t,url:`http://localhost:${t}`}}async function fr(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(St(),bt)),Promise.resolve().then(()=>(Et(),Dt))]),i=new n,c=await Ot.default.getPlatformInfo();if(o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),o){let{logger:p}=await import("hono/logger");i.use("*",p((...g)=>console.log("[Accelerate]",...g)))}i.use("*",async(p,g)=>(p.set("db",e),p.set("debug",!!o),p.set("platform",c),p.set("port",t),p.set("protocol","http"),p.set("serverState",r),p.set("shadowDBPort",r.shadowDatabasePort),await g()));let u=new n;return u.route("/",s),u.route("/",a),i.route("/",u),i}l();var Ct=require("fs/promises"),C=require("pathe"),B=require("proper-lockfile"),Ae=require("std-env"),d=require("valibot");J();l();var hr=require("timers/promises"),$t=require("std-env");function _t(t,e){if(t==null)return!1;try{return $t.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var xe=(0,d.pipe)((0,d.string)(),(0,d.url)()),kt=(0,d.object)({connectionString:xe,prismaORMConnectionString:(0,d.optional)(xe),terminalCommand:(0,d.optional)((0,d.string)())}),It=(0,d.object)({url:xe}),Ee=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),gr=(0,d.object)({database:kt,http:It,ppg:It,shadowDatabase:kt}),yr=(0,d.object)({databasePort:Ee,exports:(0,d.optional)(gr),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:Ee,shadowDatabasePort:Ee,version:(0,d.literal)("1")}),$e=Symbol("initialize"),Te="default",E=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??A,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??Te,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Ae.process.pid,this._port=e.port??A,this._shadowDatabasePort=e.shadowDatabasePort??A}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new F(e):new Re(e);return await r[$e](),r}static async fromServerDump(e){let{debug:r,name:o=Te}=e??{},n=N(o),s=F.getServerDumpPath(n),a=await Fe(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)(),yr),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 F({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,C.join)(N(Te),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let s=await Ke(n,o);return r&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>Pr(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},Re=class extends E{constructor(e){super({...e,databasePort:e?.databasePort,persistenceMode:"stateless",port:e?.port,shadowDatabasePort:e?.shadowDatabasePort})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[$e](){let e;try{e=await E.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let r=await he({debug:this.debug,name:this.dryRun?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}async close(){}async writeServerDump(){}},F=class t extends E{#r;#e;#t;#s;#a;#n;#o;constructor(e){super({...e,persistenceMode:"stateful"}),this.#n=!1,this.#e=N(this.name),this.#r=(0,C.join)(this.#e,"db_dump.bak"),this.#t=(0,C.join)(this.#e,".lock"),this.#s=(0,C.join)(this.#e,".pglite"),this.#o=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,C.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#o?.exports}get pgliteDataDirPath(){return this.#s}async[$e](){await Ge(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,B.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await E.scan({debug:this.debug,onlyMetadata:!0}),r=await he({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 oe(this):e}}async close(){if(!this.#n)try{await(0,B.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:Ae.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,Ct.writeFile)(this.#a,`${JSON.stringify(this.#o,null,2)}
5
- `,{encoding:"utf-8"})}};async function Pr(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 E.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(!_t(u,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${u}`),{...a,status:"not_running"};let p=N(n);try{if(!await(0,B.check)(p,{lockfilePath:(0,C.join)(p,".lock")}))return r&&console.debug(`[State] server state for "${n}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(j){r&&console.error(`[State] server state for "${n}" failed to check lock:`,j)}if(!c)return{...a,status:"starting_up"};let{http:g}=c,{hc:b}=await import("hono/client"),x=await b(g.url).health.$get();if(!x.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(x)}`),{...a,status:"not_running"};let R=await x.json();return R.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${n}":`,i),{...a,status:"error"}}}var Oe=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},oe=class extends Oe{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return E.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function Mt(t){let e=await E.createExclusively(t),[r,o]=await Promise.all([ge("database",e),ge("shadow_database",e)]),n=await At(r,e),s=`prisma+postgres://localhost:${n.port}/?${new URLSearchParams({api_key:Ce({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")}}var ne;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,ne?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,ne?.close().finally(()=>process.exit())});async function br(){let[,,t]=process.argv;if(!t)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{ne=await Mt({debug:!0,persistenceMode:"stateful",name:t}),process.send?.({type:"started",server:ne},void 0)}catch(e){console.error(e);let r=e instanceof Error?e.message:String(e);process.send?.({type:"error",error:r},void 0),await(0,Ht.setTimeout)(1e3),process.exit(1)}}br();
1
+ "use strict";var Ut=Object.create;var G=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,Gt=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ie=(t,e)=>{for(var r in e)G(t,r,{get:e[r],enumerable:!0})},$e=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Vt(e))!Gt.call(t,n)&&n!==r&&G(t,n,{get:()=>e[n],enumerable:!(o=qt(e,n))||o.enumerable});return t};var d=(t,e,r)=>(r=t!=null?Ut(Ft(t)):{},$e(e||!t||!t.__esModule?G(r,"default",{value:t,enumerable:!0}):r,t)),Kt=t=>$e(G({},"__esModule",{value:!0}),t);var m=D(()=>{"use strict"});function Me(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,g.safeParse)(Qt,e,{abortEarly:!0});return n?[null,o]:[r]}var g,ke,Qt,$,se=D(()=>{"use strict";m();g=require("valibot"),ke=/^(postgres|postgresql):\/\//,Qt=(0,g.pipe)((0,g.string)(),(0,g.parseJson)(),(0,g.object)({databaseUrl:(0,g.pipe)((0,g.string)(),(0,g.url)(),(0,g.regex)(ke)),name:(0,g.optional)((0,g.pipe)((0,g.string)(),(0,g.minLength)(1))),shadowDatabaseUrl:(0,g.pipe)((0,g.string)(),(0,g.url)(),(0,g.regex)(ke))}));$=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:l,name:u,shadowDatabaseUrl:f}=c,{name:b}=e.get("serverState");if(!u)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(u!==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 "${u}"`});let{hostname:x,port:R}=new URL(l),{port:j}=e.get("db"),{hostname:Bt,port:jt}=new URL(f),Nt=e.get("shadowDBPort");if(x!=="localhost"||Number(R)!==j||Bt!=="localhost"||Number(jt)!==Nt)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}`),K.default.platform==="darwin"?Wt(t):K.default.platform==="win32"?zt(t):Xt(t)}var y,ae,K,O,ie,C,Wt,zt,Xt,Ce=D(()=>{"use strict";m();y=d(require("path"),1),ae=d(require("os"),1),K=d(require("process"),1),O=ae.default.homedir(),ie=ae.default.tmpdir(),{env:C}=K.default,Wt=t=>{let e=y.default.join(O,"Library");return{data:y.default.join(e,"Application Support",t),config:y.default.join(e,"Preferences",t),cache:y.default.join(e,"Caches",t),log:y.default.join(e,"Logs",t),temp:y.default.join(ie,t)}},zt=t=>{let e=C.APPDATA||y.default.join(O,"AppData","Roaming"),r=C.LOCALAPPDATA||y.default.join(O,"AppData","Local");return{data:y.default.join(r,t,"Data"),config:y.default.join(e,t,"Config"),cache:y.default.join(r,t,"Cache"),log:y.default.join(r,t,"Log"),temp:y.default.join(ie,t)}},Xt=t=>{let e=y.default.basename(O);return{data:y.default.join(C.XDG_DATA_HOME||y.default.join(O,".local","share"),t),config:y.default.join(C.XDG_CONFIG_HOME||y.default.join(O,".config"),t),cache:y.default.join(C.XDG_CACHE_HOME||y.default.join(O,".cache"),t),log:y.default.join(C.XDG_STATE_HOME||y.default.join(O,".local","state"),t),temp:y.default.join(ie,e,t)}}});function Ne(t,e){return`${je.cache}/engine/${t}/${e}`}function N(t){return`${je.data}/${t}`}async function Ue(t){try{return await(0,v.access)(t,v.constants.F_OK),!0}catch(e){if(ue(e))return!1;throw e}}async function qe(t,e){let r=await Yt(t);await(0,v.writeFile)(e,r),await(0,v.chmod)(e,"755")}async function Ve(t,e){await t.stream().pipeTo(Q.WriteStream.toWeb((0,Q.createWriteStream)(e,{encoding:"utf8"})))}function ue(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Fe(t){try{return await(0,v.readFile)(t,{encoding:"utf-8"})}catch(e){if(ue(e))return null;throw e}}async function Ge(t){await(0,v.mkdir)(t,{recursive:!0})}async function Ke(t,e){try{return(await(0,v.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,Be.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(ue(r))return[];throw r}}var Q,v,He,Le,Be,je,Yt,J=D(()=>{"use strict";m();Q=require("fs"),v=require("fs/promises"),He=require("util"),Le=require("zlib");Ce();Be=d(require("zeptomatch"),1),je=ce("prisma-dev"),Yt=(0,He.promisify)(Le.unzip)});function X(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 ye=D(()=>{"use strict";m()});function Y(t,e){return console.error(t),t instanceof U?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof H?e.text(t.responseBody,t.statusCode):e.body(null,500)}var tt,rt,ot,nt,st,at,cr,ur,et,L,U,H,be=D(()=>{"use strict";m();tt=require("child_process"),rt=require("events"),ot=require("fs/promises"),nt=require("path"),st=require("timers/promises");ye();at=require("std-env");J();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:cr,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:ur,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:et}=at.process.env),L=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,o=`${e.schemaHash}:${e.clientVersion}`;try{let n=t.#r.get(o);if(n)return n;let s=new t(e);return t.#r.set(o,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(o)}}static async stopAll(e){let o=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([n])=>n!==e).map(async([n,s])=>{try{await s.stop()}finally{t.#r.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(o.length>0)throw new AggregateError(o,"Failed to stop engines")}async commitTransaction(e,r){return await this.#i(e,r,"commit")}async request(e,r){let{url:o}=await this.start(),n=this.#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 H.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#i(e,r,"rollback")}async startTransaction(e,r){let{url:o}=await this.start(),n=this.#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 H.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:o}=X();this.#t=e;let n=ur||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,tt.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=u=>{let f=u.split(`
2
+ `).find(j=>j.includes("Started query engine http server"));if(!f)return;a.stdout.removeListener("data",i);let{fields:b}=JSON.parse(f);if(b==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${u}`));let{ip:x,port:R}=b;if(x==null||R==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: ${u}`));o({childProcess:a,url:`http://${x}:${R}`})},c=u=>{this.#t=null,r(new U(String(u))),a.removeListener("exit",l),a.kill()};a.once("error",c);let l=(u,f)=>{this.#t=null,r(new U(`Query Engine exited with code ${u} and signal ${f}`))};return a.once("exit",l),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,rt.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=Ne(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,ot.mkdir)(r,{recursive:!0});let{binaryTarget:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,nt.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(cr==="1"||await Ue(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}`);et&&await(0,st.setTimeout)(Number(et)),await qe(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 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 it(t){let{output:e,success:r}=(0,S.safeParse)(dr,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var S,dr,ct=D(()=>{"use strict";m();S=require("valibot"),dr=(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 ut(t){return Pe===void 0&&(Pe=await I.Server.create({databaseUrl:t.get("db").connectionString,maxResponseSize:(0,I.parseSize)("128 MiB"),queryTimeout:(0,I.parseDuration)("PT5M"),maxTransactionTimeout:(0,I.parseDuration)("PT5M"),maxTransactionWaitTime:(0,I.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.get("debug")?"debug":"off"}})),Pe}var I,Z,Pe,dt=D(()=>{"use strict";m();I=require("@prisma/query-plan-executor"),Z=require("@prisma/query-plan-executor")});async function Se(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 lt(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 pt(t,e,r){let o=we.Buffer.from(t,"base64").toString("utf8"),n=(0,ee.getSchema)(o),s=n.list.find(l=>l.type==="datasource");if(!s)throw new Error("No datasource block found in schema.");let a=s.assignments.find(l=>l.type==="assignment"&&l.key==="url");a?a.value=`"${e.toString()}"`:s.assignments.push({key:"url",type:"assignment",value:`"${e.toString()}"`});let i=(0,ee.printSchema)(n);r&&console.log("[Accelerate] schema with override:",i);let c=await Se(i);return{base64Override:we.Buffer.from(i,"utf8").toString("base64"),overrideHash:c}}var we,ee,te,mt=D(()=>{"use strict";m();we=require("buffer"),ee=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 ft=D(()=>{"use strict";m()});async function ht(t){let{issues:e,output:r,success:o}=(0,h.safeParse)(lr,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}function gt(t,e){let{output:r,success:o}=(0,h.safeParse)(pr,t);return o?r:e.json({EngineMalfunction:{}},500)}var h,lr,pr,yt=D(()=>{"use strict";m();h=require("valibot"),lr=(0,h.object)({isolation_level:(0,h.optional)((0,h.string)()),max_wait:(0,h.pipe)((0,h.number)(),(0,h.integer)(),(0,h.minValue)(0)),timeout:(0,h.pipe)((0,h.number)(),(0,h.integer)(),(0,h.minValue)(0))});pr=(0,h.looseObject)({id:(0,h.union)([(0,h.string)(),(0,h.number)()])})});var wt={};Ie(wt,{accelerateRoute:()=>q});async function ve(t){let{req:e}=t,r=lt(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 bt,Pt,k,q,mr,V,fr,hr,St=D(()=>{"use strict";m();bt=require("hono/http-exception"),Pt=require("hono/tiny"),k=require("hono/validator");se();ct();be();dt();mt();ft();yt();q=new Pt.Hono;q.post("/invalidate",(0,k.validator)("header",$),async t=>{let e=await it(t);return e instanceof Response?e:t.body(null)});mr="/:clientVersion/:schemaHash",V=q.basePath(mr);q.route("/",V);fr=["/graphql","/itx/:transactionId/graphql"];V.on("POST",[...fr],(0,k.validator)("header",$),async t=>{let{req:e}=t;try{let r=await ve(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 Y(r,t)}});V.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,k.validator)("header",$),async t=>{let{req:e}=t;try{let r=await ve(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 Y(r,t)}});V.put("/schema",(0,k.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=te.get(o);if(n==null){if(o!==await Se(r))return t.text("Schema hash mismatch",400);let s=await pt(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,k.validator)("header",$),async t=>{let{req:e}=t,r=await ht(t);if(r instanceof Response)return r;try{let o=await ve(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,re(t)),s=gt(n,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),l=t.get("protocol"),u=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${l}://localhost:${c}/${i}/${u}/itx/${a}`}})}catch(o){return Y(o,t)}});hr=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[t,e]of hr)q.on(e,t,(0,k.validator)("header",$),async r=>{let o=r.req.header("prisma-engine-hash");if(o!=="0.0.0"&&o!==Z.version)throw new bt.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${o} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${Z.version}.`});return await(await ut(r)).fetch(r.req.raw)})});var Tt={};Ie(Tt,{utilityRoute:()=>De});var vt,Dt,De,uo,Et=D(()=>{"use strict";m();vt=require("hono/tiny"),Dt=require("http-status-codes"),De=new vt.Hono;De.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},Dt.StatusCodes.CREATED)});uo=De.get("/health",t=>t.json({name:t.get("serverState").name}))});var vr={};module.exports=Kt(vr);m();var Lt=require("timers/promises");m();se();m();var ze=require("pathe/utils");J();m();var A=require("get-port-please"),z=require("remeda"),de=51214,le=51213,pe=51215,W=65535,_=-1/0;async function he(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=tr(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:_,port:_,shadowDatabasePort:_},c=["port","databasePort","shadowDatabasePort"];for(let l of c){let u=await Zt({debug:e,portKey:l,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await er({debug:e,pickedPorts:i,portKey:l,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${l}": ${u}`),i[l]=u}return e&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function Zt(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s}=t,{[r]:a,...i}=s;if(Qe(a))return await rr({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let c=n?.[r]??_;if(!Qe(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=c in o;return l||Object.values(i).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,A.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 er(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(de,le,pe)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,W),l=(0,z.difference)((0,z.range)(a,c),i),u={port:le,databasePort:de,shadowDatabasePort:pe}[o];try{return await(0,A.getPort)({port:u in n||Object.values(r).includes(u)||Object.values(s||{}).includes(u)?void 0:u,ports:l})}catch(f){if(f instanceof Error&&f.name==="GetPortError"&&c+1<=W)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${W}].`),await(0,A.getPort)({portRange:[c+1,W]});throw f}}function Qe(t){return t>=0}function tr(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 rr(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 fe(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${o}", but also for another key.`),new me(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"},me=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"},fe=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 w={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},or=`postgres://${w.username}:${w.password}@localhost`,Xe=new URLSearchParams({sslmode:w.sslMode}),nr=new URLSearchParams({...Object.fromEntries(Xe.entries()),connection_limit:String(w.connectionLimit),connect_timeout:String(w.connectTimeout),max_idle_connection_lifetime:String(w.maxIdleConnectionLifetime),pool_timeout:String(w.poolTimeout),single_use_connections:"true",socket_timeout:String(w.socketTimeout)});async function ge(t,e){let r=t==="database"?e.databasePort:e.shadowDatabasePort;if(e.dryRun)return Je(t,e,{db:null,port:r,server:null});let{debug:o}=e,s=await(t==="shadow_database"?sr:Ye)(e.pgliteDataDirPath,o);o&&s.onNotification((u,f)=>{console.debug(`[${t}][${u}] ${f}`)});let{PGLiteSocketHandler:a,PGLiteSocketServer:i}=await import("@electric-sql/pglite-socket"),c=t==="shadow_database"?e.shadowDatabaseIdleTimeoutMillis:e.databaseIdleTimeoutMillis;ar(c,s,a);let l=new i({connectionQueueTimeout:t==="shadow_database"?e.shadowDatabaseConnectTimeoutMillis:e.databaseConnectTimeoutMillis,db:s,debug:o,inspect:o,port:r});o&&(l.addEventListener("listening",u=>{let{detail:f}=u;console.debug(`[${t}] server listening on ${JSON.stringify(f)}`)}),l.addEventListener("connection",u=>{let{clientAddress:f,clientPort:b}=u.detail;console.debug(`[${t}] client connected from ${f}:${b}`)}),l.addEventListener("error",u=>{let{detail:f}=u;console.error(`[${t}] server error:`,f)}));try{await l.start()}catch(u){throw u instanceof Error&&"code"in u&&u.code==="EADDRINUSE"?new E(r):u}return Je(t,e,{db:s,port:r,server:l})}function Je(t,e,r){let{debug:o}=e,{db:n,port:s,server:a}=r||{};return o&&console.debug(`[${t}] server started on port ${s}`),{...w,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:We(s,Xe),dump:async i=>{t==="shadow_database"||!n||await ir({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:We(s,nr),terminalCommand:`PGPASSWORD=${w.password} PGSSLMODE=${w.sslMode} psql -h localhost -p ${s} -U ${w.username} -d ${w.database}`}}function We(t,e){return`${or}:${t}/${w.database}?${e.toString()}`}async function Ye(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:w.database,dataDir:t,debug:e?5:void 0,extensions:await Ze(),relaxedDurability:!1,username:w.username})}async function sr(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:w.database,dataDir:"memory://",debug:e?5:void 0,extensions:await Ze(),relaxedDurability:!1,username:w.username})}async function Ze(){let t=await Promise.all([import("@electric-sql/pglite/contrib/amcheck"),import("@electric-sql/pglite/contrib/bloom"),import("@electric-sql/pglite/contrib/btree_gin"),import("@electric-sql/pglite/contrib/btree_gist"),import("@electric-sql/pglite/contrib/citext"),import("@electric-sql/pglite/contrib/cube"),import("@electric-sql/pglite/contrib/dict_int"),import("@electric-sql/pglite/contrib/dict_xsyn"),import("@electric-sql/pglite/contrib/earthdistance"),import("@electric-sql/pglite/contrib/file_fdw"),import("@electric-sql/pglite/contrib/fuzzystrmatch"),import("@electric-sql/pglite/contrib/hstore"),import("@electric-sql/pglite/contrib/intarray"),import("@electric-sql/pglite/contrib/isn"),import("@electric-sql/pglite/contrib/lo"),import("@electric-sql/pglite/contrib/ltree"),import("@electric-sql/pglite/contrib/pageinspect"),import("@electric-sql/pglite/contrib/pg_buffercache"),import("@electric-sql/pglite/contrib/pg_freespacemap"),import("@electric-sql/pglite/contrib/pg_surgery"),import("@electric-sql/pglite/contrib/pg_trgm"),import("@electric-sql/pglite/contrib/pg_visibility"),import("@electric-sql/pglite/contrib/pg_walinspect"),import("@electric-sql/pglite/contrib/seg"),import("@electric-sql/pglite/contrib/tablefunc"),import("@electric-sql/pglite/contrib/tcn"),import("@electric-sql/pglite/contrib/tsm_system_rows"),import("@electric-sql/pglite/contrib/tsm_system_time"),import("@electric-sql/pglite/contrib/unaccent"),import("@electric-sql/pglite/contrib/uuid_ossp"),import("@electric-sql/pglite/vector")]);return Object.assign({},...t)}function ar(t,e,r){if(e.__IDLE_TIMEOUT__=t,r.prototype.__ATTACH_OVERRIDDEN__)return;r.prototype.__ATTACH_OVERRIDDEN__=!0;let o=r.prototype.attach;r.prototype.attach=async function(n){let s=await o.call(this,n);if(!Number.isFinite(this.db.__IDLE_TIMEOUT__))return s;let a=null,i=()=>{a!=null&&(clearTimeout(a),a=null)},c=()=>{i(),a=setTimeout(()=>{this.dispatchEvent(new CustomEvent("close")),this.detach(!1)},this.db.__IDLE_TIMEOUT__)};return n.on("error",()=>{i()}),n.on("data",()=>{c()}),n.on("close",()=>{i()}),c(),s}}async function ir(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Ye(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:n?(0,ze.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await Ve(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}m();var Rt=require("http"),Ot=require("util"),_t=d(require("@prisma/get-platform"),1);ye();be();async function At(t,e){let{port:r}=e;if(e.dryRun)return xt(r,null);let o=await gr(r,t,e),{promise:n,reject:s,resolve:a}=X(),{serve:i}=await import("@hono/node-server"),c=i({createServer:Rt.createServer,fetch:o.fetch,overrideGlobalObjects:!1,port:r},a);return c.on("error",l=>{if(typeof l=="object"&&"code"in l&&l.code==="EADDRINUSE")return s(new E(r));console.error("[Accelerate]",l)}),await n,xt(r,c)}function xt(t,e){return{async close(){e&&await Promise.allSettled([(0,Ot.promisify)(e.close.bind(e))(),L.stopAll()])},port:t,url:`http://localhost:${t}`}}async function gr(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(St(),wt)),Promise.resolve().then(()=>(Et(),Tt))]),i=new n,c=await _t.default.getPlatformInfo();if(o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),o){let{logger:u}=await import("hono/logger");i.use("*",u((...f)=>console.log("[Accelerate]",...f)))}i.use("*",async(u,f)=>(u.set("db",e),u.set("debug",!!o),u.set("platform",c),u.set("port",t),u.set("protocol","http"),u.set("serverState",r),u.set("shadowDBPort",r.shadowDatabasePort),await f()));let l=new n;return l.route("/",s),l.route("/",a),i.route("/",l),i}m();var Ct=require("fs/promises"),M=require("pathe"),B=require("proper-lockfile"),_e=require("std-env"),p=require("valibot");J();m();var yr=require("timers/promises"),It=require("std-env");function $t(t,e){if(t==null)return!1;try{return It.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var xe=(0,p.pipe)((0,p.string)(),(0,p.url)()),kt=(0,p.object)({connectionString:xe,prismaORMConnectionString:(0,p.optional)(xe),terminalCommand:(0,p.optional)((0,p.string)())}),Mt=(0,p.object)({url:xe}),Te=(0,p.pipe)((0,p.number)(),(0,p.integer)(),(0,p.minValue)(1)),br=(0,p.object)({database:kt,http:Mt,ppg:Mt,shadowDatabase:kt}),Pr=(0,p.object)({databasePort:Te,exports:(0,p.optional)(br),name:(0,p.pipe)((0,p.string)(),(0,p.minLength)(1)),pid:(0,p.optional)((0,p.pipe)((0,p.number)(),(0,p.integer)(),(0,p.minValue)(0))),port:Te,shadowDatabasePort:Te,version:(0,p.literal)("1")}),Ae=Symbol("initialize"),Ee="default",T=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??_,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??Ee,this.persistenceMode=e.persistenceMode,this.pid=e.pid??_e.process.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??_,this._shadowDatabasePort=e.shadowDatabasePort??_}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new F(e):new Re(e);return await r[Ae](),r}static async fromServerDump(e){let{debug:r,name:o=Ee}=e??{},n=N(o),s=F.getServerDumpPath(n),a=await Fe(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:l}=(0,p.safeParse)((0,p.pipe)((0,p.string)(),(0,p.parseJson)(),Pr),a);if(!l)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 F({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,M.join)(N(Ee),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let s=await Ke(n,o);return r&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>wr(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},Re=class extends T{constructor(e){super({...e,databasePort:e?.databasePort,persistenceMode:"stateless",port:e?.port,shadowDatabasePort:e?.shadowDatabasePort})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Ae](){let e;try{e=await T.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let r=await he({debug:this.debug,name:this.dryRun?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}async close(){}async writeServerDump(){}},F=class t extends T{#r;#e;#t;#s;#a;#n;#o;constructor(e){super({...e,persistenceMode:"stateful"}),this.#n=!1,this.#e=N(this.name),this.#r=(0,M.join)(this.#e,"db_dump.bak"),this.#t=(0,M.join)(this.#e,".lock"),this.#s=(0,M.join)(this.#e,".pglite"),this.#o=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,M.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#o?.exports}get pgliteDataDirPath(){return this.#s}async[Ae](){await Ge(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,B.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await T.scan({debug:this.debug,onlyMetadata:!0}),r=await he({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 oe(this):e}}async close(){if(!this.#n)try{await(0,B.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:_e.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,Ct.writeFile)(this.#a,`${JSON.stringify(this.#o,null,2)}
5
+ `,{encoding:"utf-8"})}};async function wr(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 T.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:l}=i;if(o)return{...a,status:"unknown"};if(!$t(l,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${l}`),{...a,status:"not_running"};let u=N(n);try{if(!await(0,B.check)(u,{lockfilePath:(0,M.join)(u,".lock")}))return r&&console.debug(`[State] server state for "${n}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(j){r&&console.error(`[State] server state for "${n}" failed to check lock:`,j)}if(!c)return{...a,status:"starting_up"};let{http:f}=c,{hc:b}=await import("hono/client"),x=await b(f.url).health.$get();if(!x.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(x)}`),{...a,status:"not_running"};let R=await x.json();return R.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${n}":`,i),{...a,status:"error"}}}var Oe=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},oe=class extends Oe{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return T.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function Ht(t){let e=await T.createExclusively(t),[r,o]=await Promise.all([ge("database",e),ge("shadow_database",e)]),n=await At(r,e),s=`prisma+postgres://localhost:${n.port}/?${new URLSearchParams({api_key:Me({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,l){let f=(await Promise.allSettled(l.map(b=>b.close()))).filter(b=>b.status==="rejected").map(b=>new Error(b.reason));try{await c.close()}catch(b){f.push(b)}if(f.length>0)throw new AggregateError(f,"Failed to close some servers")}}var ne;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,ne?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,ne?.close().finally(()=>process.exit())});async function Sr(){let[,,t]=process.argv;if(!t)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{ne=await Ht({debug:!0,persistenceMode:"stateful",name:t}),process.send?.({type:"started",server:ne},void 0)}catch(e){console.error(e);let r=e instanceof Error?e.message:String(e);process.send?.({type:"error",error:r},void 0),await(0,Lt.setTimeout)(1e3),process.exit(1)}}Sr();
package/dist/daemon.js CHANGED
@@ -1 +1 @@
1
- import{a as o}from"./chunk-4Q54Y6ZK.js";import"./chunk-RBVZVBDC.js";import"./chunk-ZCVJ53EE.js";import"./chunk-LMPFMHCB.js";import"./chunk-7EOUKLQR.js";import"./chunk-EPFUMVT3.js";import{setTimeout as n}from"timers/promises";var r;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,r?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,r?.close().finally(()=>process.exit())});async function a(){let[,,s]=process.argv;if(!s)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{r=await o({debug:!0,persistenceMode:"stateful",name:s}),process.send?.({type:"started",server:r},void 0)}catch(e){console.error(e);let t=e instanceof Error?e.message:String(e);process.send?.({type:"error",error:t},void 0),await n(1e3),process.exit(1)}}a();
1
+ import{a as o}from"./chunk-OUMJ6Z34.js";import"./chunk-3BZW3EVN.js";import"./chunk-MO5SCYLN.js";import"./chunk-LMPFMHCB.js";import"./chunk-GZSROICS.js";import"./chunk-ITQ6ILGR.js";import{setTimeout as n}from"timers/promises";var r;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,r?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,r?.close().finally(()=>process.exit())});async function a(){let[,,s]=process.argv;if(!s)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{r=await o({debug:!0,persistenceMode:"stateful",name:s}),process.send?.({type:"started",server:r},void 0)}catch(e){console.error(e);let t=e instanceof Error?e.message:String(e);process.send?.({type:"error",error:t},void 0),await n(1e3),process.exit(1)}}a();
package/dist/db.cjs CHANGED
@@ -1 +1 @@
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});
1
+ "use strict";var M=Object.create;var y=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var q=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty;var K=(e,t)=>{for(var o in t)y(e,o,{get:t[o],enumerable:!0})},$=(e,t,o,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of F(t))!H.call(e,i)&&i!==o&&y(e,i,{get:()=>t[i],enumerable:!(s=C(t,i))||s.enumerable});return e};var r=(e,t,o)=>(o=e!=null?M(q(e)):{},$(t||!e||!e.__esModule?y(o,"default",{value:e,enumerable:!0}):o,e)),V=e=>$(y({},"__esModule",{value:!0}),e);var re={};K(re,{dumpDB:()=>N,startDBServer:()=>Z});module.exports=V(re);var L=require("pathe/utils");var w=require("fs"),f=require("fs/promises"),x=require("util"),E=require("zlib");var n=r(require("path"),1),D=r(require("os"),1),h=r(require("process"),1),p=D.default.homedir(),T=D.default.tmpdir(),{env:b}=h.default,W=e=>{let t=n.default.join(p,"Library");return{data:n.default.join(t,"Application Support",e),config:n.default.join(t,"Preferences",e),cache:n.default.join(t,"Caches",e),log:n.default.join(t,"Logs",e),temp:n.default.join(T,e)}},J=e=>{let t=b.APPDATA||n.default.join(p,"AppData","Roaming"),o=b.LOCALAPPDATA||n.default.join(p,"AppData","Local");return{data:n.default.join(o,e,"Data"),config:n.default.join(t,e,"Config"),cache:n.default.join(o,e,"Cache"),log:n.default.join(o,e,"Log"),temp:n.default.join(T,e)}},X=e=>{let t=n.default.basename(p);return{data:n.default.join(b.XDG_DATA_HOME||n.default.join(p,".local","share"),e),config:n.default.join(b.XDG_CONFIG_HOME||n.default.join(p,".config"),e),cache:n.default.join(b.XDG_CACHE_HOME||n.default.join(p,".cache"),e),log:n.default.join(b.XDG_STATE_HOME||n.default.join(p,".local","state"),e),temp:n.default.join(T,t,e)}};function _(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),h.default.platform==="darwin"?W(e):h.default.platform==="win32"?J(e):X(e)}var Q=r(require("zeptomatch"),1),ae=_("prisma-dev"),ce=(0,x.promisify)(E.unzip);async function A(e,t){await e.stream().pipeTo(w.WriteStream.toWeb((0,w.createWriteStream)(t,{encoding:"utf8"})))}var O=require("get-port-please"),B=require("remeda");var v=class extends Error{constructor(o){super(`Port \`${o}\` is not available.`);this.port=o}name="PortNotAvailableError"};var a={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},z=`postgres://${a.username}:${a.password}@localhost`,j=new URLSearchParams({sslmode:a.sslMode}),Y=new URLSearchParams({...Object.fromEntries(j.entries()),connection_limit:String(a.connectionLimit),connect_timeout:String(a.connectTimeout),max_idle_connection_lifetime:String(a.maxIdleConnectionLifetime),pool_timeout:String(a.poolTimeout),single_use_connections:"true",socket_timeout:String(a.socketTimeout)});async function Z(e,t){let o=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return R(e,t,{db:null,port:o,server:null});let{debug:s}=t,c=await(e==="shadow_database"?ee:U)(t.pgliteDataDirPath,s);s&&c.onNotification((l,P)=>{console.debug(`[${e}][${l}] ${P}`)});let{PGLiteSocketHandler:m,PGLiteSocketServer:d}=await import("@electric-sql/pglite-socket"),u=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis;te(u,c,m);let g=new d({connectionQueueTimeout:e==="shadow_database"?t.shadowDatabaseConnectTimeoutMillis:t.databaseConnectTimeoutMillis,db:c,debug:s,inspect:s,port:o});s&&(g.addEventListener("listening",l=>{let{detail:P}=l;console.debug(`[${e}] server listening on ${JSON.stringify(P)}`)}),g.addEventListener("connection",l=>{let{clientAddress:P,clientPort:G}=l.detail;console.debug(`[${e}] client connected from ${P}:${G}`)}),g.addEventListener("error",l=>{let{detail:P}=l;console.error(`[${e}] server error:`,P)}));try{await g.start()}catch(l){throw l instanceof Error&&"code"in l&&l.code==="EADDRINUSE"?new v(o):l}return R(e,t,{db:c,port:o,server:g})}function R(e,t,o){let{debug:s}=t,{db:i,port:c,server:m}=o||{};return s&&console.debug(`[${e}] server started on port ${c}`),{...a,close:async()=>{let d=[];try{await m?.stop(),s&&console.debug(`[${e}] server stopped on port ${c}`)}catch(u){console.error(`[${e}] server stop error`,u),d.push(u)}if(e==="database")try{await i?.syncToFs(),s&&console.debug(`[${e}] synced to filesystem`)}catch(u){console.error(`[${e}] sync error`,u),d.push(u)}try{await i?.close(),s&&console.debug(`[${e}] closed`)}catch(u){console.error(`[${e}] close error`,u),d.push(u)}if(d.length>0)throw new AggregateError(d,`Failed to close ${e} properly`)},connectionString:k(c,j),dump:async d=>{e==="shadow_database"||!i||await N({db:i,debug:s,destinationPath:d})},port:c,prismaORMConnectionString:k(c,Y),terminalCommand:`PGPASSWORD=${a.password} PGSSLMODE=${a.sslMode} psql -h localhost -p ${c} -U ${a.username} -d ${a.database}`}}function k(e,t){return`${z}:${e}/${a.database}?${t.toString()}`}async function U(e,t){let{PGlite:o}=await import("@electric-sql/pglite");return await o.create({database:a.database,dataDir:e,debug:t?5:void 0,extensions:await I(),relaxedDurability:!1,username:a.username})}async function ee(e,t){let{PGlite:o}=await import("@electric-sql/pglite");return await o.create({database:a.database,dataDir:"memory://",debug:t?5:void 0,extensions:await I(),relaxedDurability:!1,username:a.username})}async function I(){let e=await Promise.all([import("@electric-sql/pglite/contrib/amcheck"),import("@electric-sql/pglite/contrib/bloom"),import("@electric-sql/pglite/contrib/btree_gin"),import("@electric-sql/pglite/contrib/btree_gist"),import("@electric-sql/pglite/contrib/citext"),import("@electric-sql/pglite/contrib/cube"),import("@electric-sql/pglite/contrib/dict_int"),import("@electric-sql/pglite/contrib/dict_xsyn"),import("@electric-sql/pglite/contrib/earthdistance"),import("@electric-sql/pglite/contrib/file_fdw"),import("@electric-sql/pglite/contrib/fuzzystrmatch"),import("@electric-sql/pglite/contrib/hstore"),import("@electric-sql/pglite/contrib/intarray"),import("@electric-sql/pglite/contrib/isn"),import("@electric-sql/pglite/contrib/lo"),import("@electric-sql/pglite/contrib/ltree"),import("@electric-sql/pglite/contrib/pageinspect"),import("@electric-sql/pglite/contrib/pg_buffercache"),import("@electric-sql/pglite/contrib/pg_freespacemap"),import("@electric-sql/pglite/contrib/pg_surgery"),import("@electric-sql/pglite/contrib/pg_trgm"),import("@electric-sql/pglite/contrib/pg_visibility"),import("@electric-sql/pglite/contrib/pg_walinspect"),import("@electric-sql/pglite/contrib/seg"),import("@electric-sql/pglite/contrib/tablefunc"),import("@electric-sql/pglite/contrib/tcn"),import("@electric-sql/pglite/contrib/tsm_system_rows"),import("@electric-sql/pglite/contrib/tsm_system_time"),import("@electric-sql/pglite/contrib/unaccent"),import("@electric-sql/pglite/contrib/uuid_ossp"),import("@electric-sql/pglite/vector")]);return Object.assign({},...e)}function te(e,t,o){if(t.__IDLE_TIMEOUT__=e,o.prototype.__ATTACH_OVERRIDDEN__)return;o.prototype.__ATTACH_OVERRIDDEN__=!0;let s=o.prototype.attach;o.prototype.attach=async function(i){let c=await s.call(this,i);if(!Number.isFinite(this.db.__IDLE_TIMEOUT__))return c;let m=null,d=()=>{m!=null&&(clearTimeout(m),m=null)},u=()=>{d(),m=setTimeout(()=>{this.dispatchEvent(new CustomEvent("close")),this.detach(!1)},this.db.__IDLE_TIMEOUT__)};return i.on("error",()=>{d()}),i.on("data",()=>{u()}),i.on("close",()=>{d()}),u(),c}}async function N(e){let{dataDir:t,db:o,debug:s,destinationPath:i}=e,c=o||await U(t,s),{pgDump:m}=await import("@electric-sql/pglite-tools/pg_dump"),d=await m({args:["--schema-only","--no-owner"],fileName:i?(0,L.filename)(i):void 0,pg:await c.clone()});return i?(s&&console.debug(`[DB] Dumping database to ${i}`),await A(d,i)):(s&&console.debug("[DB] Dumping database to memory"),await d.text())}0&&(module.exports={dumpDB,startDBServer});
package/dist/db.js CHANGED
@@ -1 +1 @@
1
- import{a,b}from"./chunk-RBVZVBDC.js";import"./chunk-LMPFMHCB.js";import"./chunk-EPFUMVT3.js";export{b as dumpDB,a as startDBServer};
1
+ import{a,b}from"./chunk-3BZW3EVN.js";import"./chunk-LMPFMHCB.js";import"./chunk-ITQ6ILGR.js";export{b as dumpDB,a as startDBServer};
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var Mt=Object.create;var K=Object.defineProperty;var jt=Object.getOwnPropertyDescriptor;var Nt=Object.getOwnPropertyNames;var Ut=Object.getPrototypeOf,qt=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var ie=(t,e)=>{for(var r in e)K(t,r,{get:e[r],enumerable:!0})},_e=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Nt(e))!qt.call(t,n)&&n!==r&&K(t,n,{get:()=>e[n],enumerable:!(o=jt(e,n))||o.enumerable});return t};var w=(t,e,r)=>(r=t!=null?Mt(Ut(t)):{},_e(e||!t||!t.__esModule?K(r,"default",{value:t,enumerable:!0}):r,t)),Vt=t=>_e(K({},"__esModule",{value:!0}),t);var p=D(()=>{"use strict"});function Ie(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function Gt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:o,success:n}=(0,f.safeParse)(Ft,e,{abortEarly:!0});return n?[null,o]:[r]}var f,ke,Ft,k,ce=D(()=>{"use strict";p();f=require("valibot"),ke=/^(postgres|postgresql):\/\//,Ft=(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)(ke)),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)(ke))}));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]=Gt(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:x,port:R}=new URL(u),{port:j}=e.get("db"),{hostname:Ht,port:Bt}=new URL(g),Lt=e.get("shadowDBPort");if(x!=="localhost"||Number(R)!==j||Ht!=="localhost"||Number(Bt)!==Lt)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 le(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"?Kt(t):Q.default.platform==="win32"?Qt(t):Jt(t)}var h,ue,Q,O,de,H,Kt,Qt,Jt,Ce=D(()=>{"use strict";p();h=w(require("path"),1),ue=w(require("os"),1),Q=w(require("process"),1),O=ue.default.homedir(),de=ue.default.tmpdir(),{env:H}=Q.default,Kt=t=>{let e=h.default.join(O,"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(de,t)}},Qt=t=>{let e=H.APPDATA||h.default.join(O,"AppData","Roaming"),r=H.LOCALAPPDATA||h.default.join(O,"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(de,t)}},Jt=t=>{let e=h.default.basename(O);return{data:h.default.join(H.XDG_DATA_HOME||h.default.join(O,".local","share"),t),config:h.default.join(H.XDG_CONFIG_HOME||h.default.join(O,".config"),t),cache:h.default.join(H.XDG_CACHE_HOME||h.default.join(O,".cache"),t),log:h.default.join(H.XDG_STATE_HOME||h.default.join(O,".local","state"),t),temp:h.default.join(de,e,t)}}});function je(t,e){return`${Me.cache}/engine/${t}/${e}`}function N(t){return`${Me.data}/${t}`}async function Ne(t){try{return await(0,v.access)(t,v.constants.F_OK),!0}catch(e){if(pe(e))return!1;throw e}}async function Ue(t,e){let r=await Wt(t);await(0,v.writeFile)(e,r),await(0,v.chmod)(e,"755")}async function qe(t,e){await t.stream().pipeTo(J.WriteStream.toWeb((0,J.createWriteStream)(e,{encoding:"utf-8"})))}function pe(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Ve(t){try{return await(0,v.readFile)(t,{encoding:"utf-8"})}catch(e){if(pe(e))return null;throw e}}async function Fe(t){await(0,v.mkdir)(t,{recursive:!0})}async function Ge(t,e){try{return(await(0,v.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,Le.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(pe(r))return[];throw r}}var J,v,He,Be,Le,Me,Wt,W=D(()=>{"use strict";p();J=require("fs"),v=require("fs/promises"),He=require("util"),Be=require("zlib");Ce();Le=w(require("zeptomatch"),1),Me=le("prisma-dev"),Wt=(0,He.promisify)(Be.unzip)});function te(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 ye=D(()=>{"use strict";p()});function re(t,e){return console.error(t),t instanceof U?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof B?e.text(t.responseBody,t.statusCode):e.body(null,500)}var Ze,et,tt,rt,ot,nt,nr,sr,Ye,L,U,B,Pe=D(()=>{"use strict";p();Ze=require("child_process"),et=require("events"),tt=require("fs/promises"),rt=require("path"),ot=require("timers/promises");ye();nt=require("std-env");W();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:nr,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:sr,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Ye}=nt.process.env),L=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,o=`${e.schemaHash}:${e.clientVersion}`;try{let n=t.#r.get(o);if(n)return n;let s=new t(e);return t.#r.set(o,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(o)}}static async stopAll(e){let o=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([n])=>n!==e).map(async([n,s])=>{try{await s.stop()}finally{t.#r.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(o.length>0)throw new AggregateError(o,"Failed to stop engines")}async commitTransaction(e,r){return await this.#i(e,r,"commit")}async request(e,r){let{url:o}=await this.start(),n=this.#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 B.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 B.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:o}=te();this.#t=e;let n=sr||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,Ze.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(j=>j.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:x,port:R}=b;if(x==null||R==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://${x}:${R}`})},c=l=>{this.#t=null,r(new U(String(l))),a.removeListener("exit",u),a.kill()};a.once("error",c);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",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,et.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=je(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,tt.mkdir)(r,{recursive:!0});let{binaryTarget:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,rt.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(nr==="1"||await Ne(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}`);Ye&&await(0,ot.setTimeout)(Number(Ye)),await Ue(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 B.fromResponse(a);try{return await a.json()}catch{return{}}}};U=class extends Error{name="EngineStartError"},B=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 st(t){let{output:e,success:r}=(0,S.safeParse)(ar,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var S,ar,at=D(()=>{"use strict";p();S=require("valibot"),ar=(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 it(t){return be===void 0&&(be=await _.Server.create({databaseUrl:t.get("db").connectionString,maxResponseSize:(0,_.parseSize)("128 MiB"),queryTimeout:(0,_.parseDuration)("PT5M"),maxTransactionTimeout:(0,_.parseDuration)("PT5M"),maxTransactionWaitTime:(0,_.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.get("debug")?"debug":"off"}})),be}var _,oe,be,ct=D(()=>{"use strict";p();_=require("@prisma/query-plan-executor"),oe=require("@prisma/query-plan-executor")});async function we(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 ut(t){let e=t.req.param("schemaHash"),r=se.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}async function dt(t,e,r){let o=Se.Buffer.from(t,"base64").toString("utf8"),n=(0,ne.getSchema)(o),s=n.list.find(u=>u.type==="datasource");if(!s)throw new Error("No datasource block found in schema.");let a=s.assignments.find(u=>u.type==="assignment"&&u.key==="url");a?a.value=`"${e.toString()}"`:s.assignments.push({key:"url",type:"assignment",value:`"${e.toString()}"`});let i=(0,ne.printSchema)(n);r&&console.log("[Accelerate] schema with override:",i);let c=await we(i);return{base64Override:Se.Buffer.from(i,"utf8").toString("base64"),overrideHash:c}}var Se,ne,se,lt=D(()=>{"use strict";p();Se=require("buffer"),ne=require("@mrleebo/prisma-ast"),se=new Map});function ae(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var pt=D(()=>{"use strict";p()});async function mt(t){let{issues:e,output:r,success:o}=(0,m.safeParse)(ir,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}function ft(t,e){let{output:r,success:o}=(0,m.safeParse)(cr,t);return o?r:e.json({EngineMalfunction:{}},500)}var m,ir,cr,ht=D(()=>{"use strict";p();m=require("valibot"),ir=(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))});cr=(0,m.looseObject)({id:(0,m.union)([(0,m.string)(),(0,m.number)()])})});var Pt={};ie(Pt,{accelerateRoute:()=>q});async function ve(t){let{req:e}=t,r=ut(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 gt,yt,I,q,ur,V,dr,lr,bt=D(()=>{"use strict";p();gt=require("hono/http-exception"),yt=require("hono/tiny"),I=require("hono/validator");ce();at();Pe();ct();lt();pt();ht();q=new yt.Hono;q.post("/invalidate",(0,I.validator)("header",k),async t=>{let e=await st(t);return e instanceof Response?e:t.body(null)});ur="/:clientVersion/:schemaHash",V=q.basePath(ur);q.route("/",V);dr=["/graphql","/itx/:transactionId/graphql"];V.on("POST",[...dr],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await ve(t);if(r instanceof Response)return r;let o=await e.text(),n=e.param("transactionId"),s=await r.request(o,{...ae(t),"X-transaction-id":n});return t.text(s)}catch(r){return re(r,t)}});V.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,I.validator)("header",k),async t=>{let{req:e}=t;try{let r=await ve(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,ae(t));return t.json(a)}catch(r){return re(r,t)}});V.put("/schema",(0,I.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=se.get(o);if(n==null){if(o!==await we(r))return t.text("Schema hash mismatch",400);let s=await dt(r,t.get("db").prismaORMConnectionString,t.get("debug"));return se.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,I.validator)("header",k),async t=>{let{req:e}=t,r=await mt(t);if(r instanceof Response)return r;try{let o=await ve(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,ae(t)),s=ft(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 re(o,t)}});lr=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[t,e]of lr)q.on(e,t,(0,I.validator)("header",k),async r=>{let o=r.req.header("prisma-engine-hash");if(o!=="0.0.0"&&o!==oe.version)throw new gt.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${o} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${oe.version}.`});return await(await it(r)).fetch(r.req.raw)})});var vt={};ie(vt,{utilityRoute:()=>De});var St,wt,De,so,Dt=D(()=>{"use strict";p();St=require("hono/tiny"),wt=require("http-status-codes"),De=new St.Hono;De.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},wt.StatusCodes.CREATED)});so=De.get("/health",t=>t.json({name:t.get("serverState").name}))});var Pr={};ie(Pr,{DEFAULT_DATABASE_PORT:()=>X,DEFAULT_SERVER_PORT:()=>Y,DEFAULT_SHADOW_DATABASE_PORT:()=>Z,PortNotAvailableError:()=>E,ServerAlreadyRunningError:()=>G,startPrismaDevServer:()=>Ct,unstable_startServer:()=>yr});module.exports=Vt(Pr);p();ce();p();var We=require("pathe/utils");W();p();var $=require("get-port-please"),ee=require("remeda"),X=51214,Y=51213,Z=51215,z=65535,A=-1/0;async function he(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=Yt(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:A,port:A,shadowDatabasePort:A},c=["port","databasePort","shadowDatabasePort"];for(let u of c){let l=await zt({debug:e,portKey:u,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await Xt({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 zt(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s}=t,{[r]:a,...i}=s;if(Ke(a))return await Zt({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let c=n?.[r]??A;if(!Ke(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 Xt(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(X,Y,Z)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,z),u=(0,ee.difference)((0,ee.range)(a,c),i),l={port:Y,databasePort:X,shadowDatabasePort:Z}[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<=z)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${z}].`),await(0,$.getPort)({portRange:[c+1,z]});throw g}}function Ke(t){return t>=0}function Yt(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 Zt(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 fe(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${o}", but also for another key.`),new me(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"},me=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"},fe=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"},er=`postgres://${y.username}:${y.password}@localhost`,ze=new URLSearchParams({sslmode:y.sslMode}),tr=new URLSearchParams({...Object.fromEntries(ze.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 ge(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"?rr:Xe)(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:Je(s,ze),dump:async i=>{t==="shadow_database"||!n||await or({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:Je(s,tr),terminalCommand:`PGPASSWORD=${y.password} PGSSLMODE=${y.sslMode} psql -h localhost -p ${s} -U ${y.username} -d ${y.database}`}}function Je(t,e){return`${er}:${t}/${y.database}?${e.toString()}`}async function Xe(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 rr(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 or(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Xe(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:n?(0,We.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await qe(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}p();var Tt=require("http"),xt=require("util"),Rt=w(require("@prisma/get-platform"),1);ye();Pe();async function Ot(t,e){let{port:r}=e;if(e.dryRun)return Et(r,null);let o=await pr(r,t,e),{promise:n,reject:s,resolve:a}=te(),{serve:i}=await import("@hono/node-server"),c=i({createServer:Tt.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,Et(r,c)}function Et(t,e){return{async close(){e&&await Promise.allSettled([(0,xt.promisify)(e.close.bind(e))(),L.stopAll()])},port:t,url:`http://localhost:${t}`}}async function pr(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(bt(),Pt)),Promise.resolve().then(()=>(Dt(),vt))]),i=new n,c=await Rt.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 It=require("fs/promises"),C=require("pathe"),M=require("proper-lockfile"),Ae=require("std-env"),d=require("valibot");W();p();var mr=require("timers/promises"),At=require("std-env");function $t(t,e){if(t==null)return!1;try{return At.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var xe=(0,d.pipe)((0,d.string)(),(0,d.url)()),_t=(0,d.object)({connectionString:xe,prismaORMConnectionString:(0,d.optional)(xe),terminalCommand:(0,d.optional)((0,d.string)())}),kt=(0,d.object)({url:xe}),Ee=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),fr=(0,d.object)({database:_t,http:kt,ppg:kt,shadowDatabase:_t}),hr=(0,d.object)({databasePort:Ee,exports:(0,d.optional)(fr),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:Ee,shadowDatabasePort:Ee,version:(0,d.literal)("1")}),$e=Symbol("initialize"),Te="default",T=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??A,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??Te,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Ae.process.pid,this._port=e.port??A,this._shadowDatabasePort=e.shadowDatabasePort??A}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new F(e):new Re(e);return await r[$e](),r}static async fromServerDump(e){let{debug:r,name:o=Te}=e??{},n=N(o),s=F.getServerDumpPath(n),a=await Ve(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)(),hr),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 F({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,C.join)(N(Te),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let s=await Ge(n,o);return r&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>gr(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},Re=class extends T{constructor(e){super({...e,databasePort:e?.databasePort,persistenceMode:"stateless",port:e?.port,shadowDatabasePort:e?.shadowDatabasePort})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[$e](){let e;try{e=await T.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let r=await he({debug:this.debug,name:this.dryRun?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}async close(){}async writeServerDump(){}},F=class t extends T{#r;#e;#t;#s;#a;#n;#o;constructor(e){super({...e,persistenceMode:"stateful"}),this.#n=!1,this.#e=N(this.name),this.#r=(0,C.join)(this.#e,"db_dump.bak"),this.#t=(0,C.join)(this.#e,".lock"),this.#s=(0,C.join)(this.#e,".pglite"),this.#o=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,C.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#o?.exports}get pgliteDataDirPath(){return this.#s}async[$e](){await Fe(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,M.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await T.scan({debug:this.debug,onlyMetadata:!0}),r=await he({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 G(this):e}}async close(){if(!this.#n)try{await(0,M.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:Ae.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,It.writeFile)(this.#a,`${JSON.stringify(this.#o,null,2)}
5
- `,{encoding:"utf-8"})}};async function gr(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 T.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(!$t(u,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${u}`),{...a,status:"not_running"};let l=N(n);try{if(!await(0,M.check)(l,{lockfilePath:(0,C.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(j){r&&console.error(`[State] server state for "${n}" failed to check lock:`,j)}if(!c)return{...a,status:"starting_up"};let{http:g}=c,{hc:b}=await import("hono/client"),x=await b(g.url).health.$get();if(!x.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(x)}`),{...a,status:"not_running"};let R=await x.json();return R.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${n}":`,i),{...a,status:"error"}}}var Oe=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},G=class extends Oe{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return T.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function Ct(t){let e=await T.createExclusively(t),[r,o]=await Promise.all([ge("database",e),ge("shadow_database",e)]),n=await Ot(r,e),s=`prisma+postgres://localhost:${n.port}/?${new URLSearchParams({api_key:Ie({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")}}async function yr(t){return await Ct(t)}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,PortNotAvailableError,ServerAlreadyRunningError,startPrismaDevServer,unstable_startServer});
1
+ "use strict";var jt=Object.create;var K=Object.defineProperty;var Nt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var qt=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var ie=(t,e)=>{for(var r in e)K(t,r,{get:e[r],enumerable:!0})},$e=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ut(e))!Vt.call(t,n)&&n!==r&&K(t,n,{get:()=>e[n],enumerable:!(o=Nt(e,n))||o.enumerable});return t};var d=(t,e,r)=>(r=t!=null?jt(qt(t)):{},$e(e||!t||!t.__esModule?K(r,"default",{value:t,enumerable:!0}):r,t)),Ft=t=>$e(K({},"__esModule",{value:!0}),t);var m=D(()=>{"use strict"});function ke(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function Kt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:o,success:n}=(0,g.safeParse)(Gt,e,{abortEarly:!0});return n?[null,o]:[r]}var g,Ie,Gt,I,ce=D(()=>{"use strict";m();g=require("valibot"),Ie=/^(postgres|postgresql):\/\//,Gt=(0,g.pipe)((0,g.string)(),(0,g.parseJson)(),(0,g.object)({databaseUrl:(0,g.pipe)((0,g.string)(),(0,g.url)(),(0,g.regex)(Ie)),name:(0,g.optional)((0,g.pipe)((0,g.string)(),(0,g.minLength)(1))),shadowDatabaseUrl:(0,g.pipe)((0,g.string)(),(0,g.url)(),(0,g.regex)(Ie))}));I=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]=Kt(s);if(i)throw new o(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:l,name:u,shadowDatabaseUrl:h}=c,{name:y}=e.get("serverState");if(!u)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} requires an API Key from a newer version of \`prisma dev\`. Check the "${y}" server's output for the updated \`DATABASE_URL\` value.`});if(u!==y)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${y}", but the API Key is for "${u}"`});let{hostname:x,port:R}=new URL(l),{port:j}=e.get("db"),{hostname:Ht,port:Lt}=new URL(h),Bt=e.get("shadowDBPort");if(x!=="localhost"||Number(R)!==j||Ht!=="localhost"||Number(Lt)!==Bt)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 le(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"?Qt(t):Q.default.platform==="win32"?Jt(t):Wt(t)}var b,ue,Q,O,de,M,Qt,Jt,Wt,Ce=D(()=>{"use strict";m();b=d(require("path"),1),ue=d(require("os"),1),Q=d(require("process"),1),O=ue.default.homedir(),de=ue.default.tmpdir(),{env:M}=Q.default,Qt=t=>{let e=b.default.join(O,"Library");return{data:b.default.join(e,"Application Support",t),config:b.default.join(e,"Preferences",t),cache:b.default.join(e,"Caches",t),log:b.default.join(e,"Logs",t),temp:b.default.join(de,t)}},Jt=t=>{let e=M.APPDATA||b.default.join(O,"AppData","Roaming"),r=M.LOCALAPPDATA||b.default.join(O,"AppData","Local");return{data:b.default.join(r,t,"Data"),config:b.default.join(e,t,"Config"),cache:b.default.join(r,t,"Cache"),log:b.default.join(r,t,"Log"),temp:b.default.join(de,t)}},Wt=t=>{let e=b.default.basename(O);return{data:b.default.join(M.XDG_DATA_HOME||b.default.join(O,".local","share"),t),config:b.default.join(M.XDG_CONFIG_HOME||b.default.join(O,".config"),t),cache:b.default.join(M.XDG_CACHE_HOME||b.default.join(O,".cache"),t),log:b.default.join(M.XDG_STATE_HOME||b.default.join(O,".local","state"),t),temp:b.default.join(de,e,t)}}});function je(t,e){return`${Be.cache}/engine/${t}/${e}`}function N(t){return`${Be.data}/${t}`}async function Ne(t){try{return await(0,v.access)(t,v.constants.F_OK),!0}catch(e){if(pe(e))return!1;throw e}}async function Ue(t,e){let r=await zt(t);await(0,v.writeFile)(e,r),await(0,v.chmod)(e,"755")}async function qe(t,e){await t.stream().pipeTo(J.WriteStream.toWeb((0,J.createWriteStream)(e,{encoding:"utf8"})))}function pe(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Ve(t){try{return await(0,v.readFile)(t,{encoding:"utf-8"})}catch(e){if(pe(e))return null;throw e}}async function Fe(t){await(0,v.mkdir)(t,{recursive:!0})}async function Ge(t,e){try{return(await(0,v.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,Le.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(pe(r))return[];throw r}}var J,v,Me,He,Le,Be,zt,W=D(()=>{"use strict";m();J=require("fs"),v=require("fs/promises"),Me=require("util"),He=require("zlib");Ce();Le=d(require("zeptomatch"),1),Be=le("prisma-dev"),zt=(0,Me.promisify)(He.unzip)});function te(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 be=D(()=>{"use strict";m()});function re(t,e){return console.error(t),t instanceof U?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof H?e.text(t.responseBody,t.statusCode):e.body(null,500)}var et,tt,rt,ot,nt,st,ar,ir,Ze,L,U,H,ye=D(()=>{"use strict";m();et=require("child_process"),tt=require("events"),rt=require("fs/promises"),ot=require("path"),nt=require("timers/promises");be();st=require("std-env");W();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:ar,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:ir,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Ze}=st.process.env),L=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,o=`${e.schemaHash}:${e.clientVersion}`;try{let n=t.#r.get(o);if(n)return n;let s=new t(e);return t.#r.set(o,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(o)}}static async stopAll(e){let o=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([n])=>n!==e).map(async([n,s])=>{try{await s.stop()}finally{t.#r.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(o.length>0)throw new AggregateError(o,"Failed to stop engines")}async commitTransaction(e,r){return await this.#i(e,r,"commit")}async request(e,r){let{url:o}=await this.start(),n=this.#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 H.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#i(e,r,"rollback")}async startTransaction(e,r){let{url:o}=await this.start(),n=this.#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 H.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:o}=te();this.#t=e;let n=ir||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,et.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=u=>{let h=u.split(`
2
+ `).find(j=>j.includes("Started query engine http server"));if(!h)return;a.stdout.removeListener("data",i);let{fields:y}=JSON.parse(h);if(y==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${u}`));let{ip:x,port:R}=y;if(x==null||R==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: ${u}`));o({childProcess:a,url:`http://${x}:${R}`})},c=u=>{this.#t=null,r(new U(String(u))),a.removeListener("exit",l),a.kill()};a.once("error",c);let l=(u,h)=>{this.#t=null,r(new U(`Query Engine exited with code ${u} and signal ${h}`))};return a.once("exit",l),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,tt.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=je(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,rt.mkdir)(r,{recursive:!0});let{binaryTarget:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,ot.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(ar==="1"||await Ne(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}`);Ze&&await(0,nt.setTimeout)(Number(Ze)),await Ue(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 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 at(t){let{output:e,success:r}=(0,S.safeParse)(cr,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var S,cr,it=D(()=>{"use strict";m();S=require("valibot"),cr=(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 ct(t){return Pe===void 0&&(Pe=await $.Server.create({databaseUrl:t.get("db").connectionString,maxResponseSize:(0,$.parseSize)("128 MiB"),queryTimeout:(0,$.parseDuration)("PT5M"),maxTransactionTimeout:(0,$.parseDuration)("PT5M"),maxTransactionWaitTime:(0,$.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.get("debug")?"debug":"off"}})),Pe}var $,oe,Pe,ut=D(()=>{"use strict";m();$=require("@prisma/query-plan-executor"),oe=require("@prisma/query-plan-executor")});async function Se(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 dt(t){let e=t.req.param("schemaHash"),r=se.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}async function lt(t,e,r){let o=we.Buffer.from(t,"base64").toString("utf8"),n=(0,ne.getSchema)(o),s=n.list.find(l=>l.type==="datasource");if(!s)throw new Error("No datasource block found in schema.");let a=s.assignments.find(l=>l.type==="assignment"&&l.key==="url");a?a.value=`"${e.toString()}"`:s.assignments.push({key:"url",type:"assignment",value:`"${e.toString()}"`});let i=(0,ne.printSchema)(n);r&&console.log("[Accelerate] schema with override:",i);let c=await Se(i);return{base64Override:we.Buffer.from(i,"utf8").toString("base64"),overrideHash:c}}var we,ne,se,pt=D(()=>{"use strict";m();we=require("buffer"),ne=require("@mrleebo/prisma-ast"),se=new Map});function ae(t){let{req:e}=t;return{traceparent:e.header("traceparent"),"X-capture-telemetry":e.header("X-capture-telemetry")}}var mt=D(()=>{"use strict";m()});async function ht(t){let{issues:e,output:r,success:o}=(0,f.safeParse)(ur,await t.req.json(),{abortEarly:!0});return o?r:t.json({EngineNotStarted:{reason:"InvalidRequest",issues:e}},400)}function ft(t,e){let{output:r,success:o}=(0,f.safeParse)(dr,t);return o?r:e.json({EngineMalfunction:{}},500)}var f,ur,dr,gt=D(()=>{"use strict";m();f=require("valibot"),ur=(0,f.object)({isolation_level:(0,f.optional)((0,f.string)()),max_wait:(0,f.pipe)((0,f.number)(),(0,f.integer)(),(0,f.minValue)(0)),timeout:(0,f.pipe)((0,f.number)(),(0,f.integer)(),(0,f.minValue)(0))});dr=(0,f.looseObject)({id:(0,f.union)([(0,f.string)(),(0,f.number)()])})});var Pt={};ie(Pt,{accelerateRoute:()=>q});async function ve(t){let{req:e}=t,r=dt(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 bt,yt,k,q,lr,V,pr,mr,wt=D(()=>{"use strict";m();bt=require("hono/http-exception"),yt=require("hono/tiny"),k=require("hono/validator");ce();it();ye();ut();pt();mt();gt();q=new yt.Hono;q.post("/invalidate",(0,k.validator)("header",I),async t=>{let e=await at(t);return e instanceof Response?e:t.body(null)});lr="/:clientVersion/:schemaHash",V=q.basePath(lr);q.route("/",V);pr=["/graphql","/itx/:transactionId/graphql"];V.on("POST",[...pr],(0,k.validator)("header",I),async t=>{let{req:e}=t;try{let r=await ve(t);if(r instanceof Response)return r;let o=await e.text(),n=e.param("transactionId"),s=await r.request(o,{...ae(t),"X-transaction-id":n});return t.text(s)}catch(r){return re(r,t)}});V.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,k.validator)("header",I),async t=>{let{req:e}=t;try{let r=await ve(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,ae(t));return t.json(a)}catch(r){return re(r,t)}});V.put("/schema",(0,k.validator)("header",I),async t=>{let{req:e}=t,r=await e.text();if(!r)return t.text("Missing schema",400);let o=e.param("schemaHash"),n=se.get(o);if(n==null){if(o!==await Se(r))return t.text("Schema hash mismatch",400);let s=await lt(r,t.get("db").prismaORMConnectionString,t.get("debug"));return se.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,k.validator)("header",I),async t=>{let{req:e}=t,r=await ht(t);if(r instanceof Response)return r;try{let o=await ve(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,ae(t)),s=ft(n,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),l=t.get("protocol"),u=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${l}://localhost:${c}/${i}/${u}/itx/${a}`}})}catch(o){return re(o,t)}});mr=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[t,e]of mr)q.on(e,t,(0,k.validator)("header",I),async r=>{let o=r.req.header("prisma-engine-hash");if(o!=="0.0.0"&&o!==oe.version)throw new bt.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${o} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${oe.version}.`});return await(await ct(r)).fetch(r.req.raw)})});var Dt={};ie(Dt,{utilityRoute:()=>De});var St,vt,De,io,Tt=D(()=>{"use strict";m();St=require("hono/tiny"),vt=require("http-status-codes"),De=new St.Hono;De.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},vt.StatusCodes.CREATED)});io=De.get("/health",t=>t.json({name:t.get("serverState").name}))});var wr={};ie(wr,{DEFAULT_DATABASE_PORT:()=>X,DEFAULT_SERVER_PORT:()=>Y,DEFAULT_SHADOW_DATABASE_PORT:()=>Z,PortNotAvailableError:()=>T,ServerAlreadyRunningError:()=>G,startPrismaDevServer:()=>Mt,unstable_startServer:()=>Pr});module.exports=Ft(wr);m();ce();m();var We=require("pathe/utils");W();m();var A=require("get-port-please"),ee=require("remeda"),X=51214,Y=51213,Z=51215,z=65535,_=-1/0;async function fe(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a}=Zt(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:_,port:_,shadowDatabasePort:_},c=["port","databasePort","shadowDatabasePort"];for(let l of c){let u=await Xt({debug:e,portKey:l,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await Yt({debug:e,pickedPorts:i,portKey:l,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${l}": ${u}`),i[l]=u}return e&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function Xt(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:s}=t,{[r]:a,...i}=s;if(Ke(a))return await er({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let c=n?.[r]??_;if(!Ke(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=c in o;return l||Object.values(i).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,A.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 Yt(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(X,Y,Z)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,z),l=(0,ee.difference)((0,ee.range)(a,c),i),u={port:Y,databasePort:X,shadowDatabasePort:Z}[o];try{return await(0,A.getPort)({port:u in n||Object.values(r).includes(u)||Object.values(s||{}).includes(u)?void 0:u,ports:l})}catch(h){if(h instanceof Error&&h.name==="GetPortError"&&c+1<=z)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${z}].`),await(0,A.getPort)({portRange:[c+1,z]});throw h}}function Ke(t){return t>=0}function Zt(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 er(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 he(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${o}", but also for another key.`),new me(s);if((0,A.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${o}", but is unsafe.`),new T(s);if(await(0,A.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${o}", but is not available.`),new T(s)}var T=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},me=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"},he=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 P={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},tr=`postgres://${P.username}:${P.password}@localhost`,ze=new URLSearchParams({sslmode:P.sslMode}),rr=new URLSearchParams({...Object.fromEntries(ze.entries()),connection_limit:String(P.connectionLimit),connect_timeout:String(P.connectTimeout),max_idle_connection_lifetime:String(P.maxIdleConnectionLifetime),pool_timeout:String(P.poolTimeout),single_use_connections:"true",socket_timeout:String(P.socketTimeout)});async function ge(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"?or:Xe)(e.pgliteDataDirPath,o);o&&s.onNotification((u,h)=>{console.debug(`[${t}][${u}] ${h}`)});let{PGLiteSocketHandler:a,PGLiteSocketServer:i}=await import("@electric-sql/pglite-socket"),c=t==="shadow_database"?e.shadowDatabaseIdleTimeoutMillis:e.databaseIdleTimeoutMillis;nr(c,s,a);let l=new i({connectionQueueTimeout:t==="shadow_database"?e.shadowDatabaseConnectTimeoutMillis:e.databaseConnectTimeoutMillis,db:s,debug:o,inspect:o,port:r});o&&(l.addEventListener("listening",u=>{let{detail:h}=u;console.debug(`[${t}] server listening on ${JSON.stringify(h)}`)}),l.addEventListener("connection",u=>{let{clientAddress:h,clientPort:y}=u.detail;console.debug(`[${t}] client connected from ${h}:${y}`)}),l.addEventListener("error",u=>{let{detail:h}=u;console.error(`[${t}] server error:`,h)}));try{await l.start()}catch(u){throw u instanceof Error&&"code"in u&&u.code==="EADDRINUSE"?new T(r):u}return Qe(t,e,{db:s,port:r,server:l})}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}`),{...P,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:Je(s,ze),dump:async i=>{t==="shadow_database"||!n||await sr({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:Je(s,rr),terminalCommand:`PGPASSWORD=${P.password} PGSSLMODE=${P.sslMode} psql -h localhost -p ${s} -U ${P.username} -d ${P.database}`}}function Je(t,e){return`${tr}:${t}/${P.database}?${e.toString()}`}async function Xe(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:P.database,dataDir:t,debug:e?5:void 0,extensions:await Ye(),relaxedDurability:!1,username:P.username})}async function or(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:P.database,dataDir:"memory://",debug:e?5:void 0,extensions:await Ye(),relaxedDurability:!1,username:P.username})}async function Ye(){let t=await Promise.all([import("@electric-sql/pglite/contrib/amcheck"),import("@electric-sql/pglite/contrib/bloom"),import("@electric-sql/pglite/contrib/btree_gin"),import("@electric-sql/pglite/contrib/btree_gist"),import("@electric-sql/pglite/contrib/citext"),import("@electric-sql/pglite/contrib/cube"),import("@electric-sql/pglite/contrib/dict_int"),import("@electric-sql/pglite/contrib/dict_xsyn"),import("@electric-sql/pglite/contrib/earthdistance"),import("@electric-sql/pglite/contrib/file_fdw"),import("@electric-sql/pglite/contrib/fuzzystrmatch"),import("@electric-sql/pglite/contrib/hstore"),import("@electric-sql/pglite/contrib/intarray"),import("@electric-sql/pglite/contrib/isn"),import("@electric-sql/pglite/contrib/lo"),import("@electric-sql/pglite/contrib/ltree"),import("@electric-sql/pglite/contrib/pageinspect"),import("@electric-sql/pglite/contrib/pg_buffercache"),import("@electric-sql/pglite/contrib/pg_freespacemap"),import("@electric-sql/pglite/contrib/pg_surgery"),import("@electric-sql/pglite/contrib/pg_trgm"),import("@electric-sql/pglite/contrib/pg_visibility"),import("@electric-sql/pglite/contrib/pg_walinspect"),import("@electric-sql/pglite/contrib/seg"),import("@electric-sql/pglite/contrib/tablefunc"),import("@electric-sql/pglite/contrib/tcn"),import("@electric-sql/pglite/contrib/tsm_system_rows"),import("@electric-sql/pglite/contrib/tsm_system_time"),import("@electric-sql/pglite/contrib/unaccent"),import("@electric-sql/pglite/contrib/uuid_ossp"),import("@electric-sql/pglite/vector")]);return Object.assign({},...t)}function nr(t,e,r){if(e.__IDLE_TIMEOUT__=t,r.prototype.__ATTACH_OVERRIDDEN__)return;r.prototype.__ATTACH_OVERRIDDEN__=!0;let o=r.prototype.attach;r.prototype.attach=async function(n){let s=await o.call(this,n);if(!Number.isFinite(this.db.__IDLE_TIMEOUT__))return s;let a=null,i=()=>{a!=null&&(clearTimeout(a),a=null)},c=()=>{i(),a=setTimeout(()=>{this.dispatchEvent(new CustomEvent("close")),this.detach(!1)},this.db.__IDLE_TIMEOUT__)};return n.on("error",()=>{i()}),n.on("data",()=>{c()}),n.on("close",()=>{i()}),c(),s}}async function sr(t){let{dataDir:e,db:r,debug:o,destinationPath:n}=t,s=r||await Xe(e,o),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:n?(0,We.filename)(n):void 0,pg:await s.clone()});return n?(o&&console.debug(`[DB] Dumping database to ${n}`),await qe(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}m();var xt=require("http"),Rt=require("util"),Ot=d(require("@prisma/get-platform"),1);be();ye();async function _t(t,e){let{port:r}=e;if(e.dryRun)return Et(r,null);let o=await hr(r,t,e),{promise:n,reject:s,resolve:a}=te(),{serve:i}=await import("@hono/node-server"),c=i({createServer:xt.createServer,fetch:o.fetch,overrideGlobalObjects:!1,port:r},a);return c.on("error",l=>{if(typeof l=="object"&&"code"in l&&l.code==="EADDRINUSE")return s(new T(r));console.error("[Accelerate]",l)}),await n,Et(r,c)}function Et(t,e){return{async close(){e&&await Promise.allSettled([(0,Rt.promisify)(e.close.bind(e))(),L.stopAll()])},port:t,url:`http://localhost:${t}`}}async function hr(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(wt(),Pt)),Promise.resolve().then(()=>(Tt(),Dt))]),i=new n,c=await Ot.default.getPlatformInfo();if(o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),o){let{logger:u}=await import("hono/logger");i.use("*",u((...h)=>console.log("[Accelerate]",...h)))}i.use("*",async(u,h)=>(u.set("db",e),u.set("debug",!!o),u.set("platform",c),u.set("port",t),u.set("protocol","http"),u.set("serverState",r),u.set("shadowDBPort",r.shadowDatabasePort),await h()));let l=new n;return l.route("/",s),l.route("/",a),i.route("/",l),i}m();var Ct=require("fs/promises"),C=require("pathe"),B=require("proper-lockfile"),_e=require("std-env"),p=require("valibot");W();m();var fr=require("timers/promises"),At=require("std-env");function $t(t,e){if(t==null)return!1;try{return At.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var xe=(0,p.pipe)((0,p.string)(),(0,p.url)()),It=(0,p.object)({connectionString:xe,prismaORMConnectionString:(0,p.optional)(xe),terminalCommand:(0,p.optional)((0,p.string)())}),kt=(0,p.object)({url:xe}),Te=(0,p.pipe)((0,p.number)(),(0,p.integer)(),(0,p.minValue)(1)),gr=(0,p.object)({database:It,http:kt,ppg:kt,shadowDatabase:It}),br=(0,p.object)({databasePort:Te,exports:(0,p.optional)(gr),name:(0,p.pipe)((0,p.string)(),(0,p.minLength)(1)),pid:(0,p.optional)((0,p.pipe)((0,p.number)(),(0,p.integer)(),(0,p.minValue)(0))),port:Te,shadowDatabasePort:Te,version:(0,p.literal)("1")}),Ae=Symbol("initialize"),Ee="default",E=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??_,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??Ee,this.persistenceMode=e.persistenceMode,this.pid=e.pid??_e.process.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??_,this._shadowDatabasePort=e.shadowDatabasePort??_}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new F(e):new Re(e);return await r[Ae](),r}static async fromServerDump(e){let{debug:r,name:o=Ee}=e??{},n=N(o),s=F.getServerDumpPath(n),a=await Ve(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:l}=(0,p.safeParse)((0,p.pipe)((0,p.string)(),(0,p.parseJson)(),br),a);if(!l)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 F({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,C.join)(N(Ee),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let s=await Ge(n,o);return r&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>yr(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},Re=class extends E{constructor(e){super({...e,databasePort:e?.databasePort,persistenceMode:"stateless",port:e?.port,shadowDatabasePort:e?.shadowDatabasePort})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Ae](){let e;try{e=await E.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let r=await fe({debug:this.debug,name:this.dryRun?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}async close(){}async writeServerDump(){}},F=class t extends E{#r;#e;#t;#s;#a;#n;#o;constructor(e){super({...e,persistenceMode:"stateful"}),this.#n=!1,this.#e=N(this.name),this.#r=(0,C.join)(this.#e,"db_dump.bak"),this.#t=(0,C.join)(this.#e,".lock"),this.#s=(0,C.join)(this.#e,".pglite"),this.#o=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,C.join)(e,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#o?.exports}get pgliteDataDirPath(){return this.#s}async[Ae](){await Fe(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,B.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await E.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 G(this):e}}async close(){if(!this.#n)try{await(0,B.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:_e.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,Ct.writeFile)(this.#a,`${JSON.stringify(this.#o,null,2)}
5
+ `,{encoding:"utf-8"})}};async function yr(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 E.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:l}=i;if(o)return{...a,status:"unknown"};if(!$t(l,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${l}`),{...a,status:"not_running"};let u=N(n);try{if(!await(0,B.check)(u,{lockfilePath:(0,C.join)(u,".lock")}))return r&&console.debug(`[State] server state for "${n}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(j){r&&console.error(`[State] server state for "${n}" failed to check lock:`,j)}if(!c)return{...a,status:"starting_up"};let{http:h}=c,{hc:y}=await import("hono/client"),x=await y(h.url).health.$get();if(!x.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(x)}`),{...a,status:"not_running"};let R=await x.json();return R.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${n}":`,i),{...a,status:"error"}}}var Oe=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},G=class extends Oe{#r;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#r=e}get server(){return E.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};async function Mt(t){let e=await E.createExclusively(t),[r,o]=await Promise.all([ge("database",e),ge("shadow_database",e)]),n=await _t(r,e),s=`prisma+postgres://localhost:${n.port}/?${new URLSearchParams({api_key:ke({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,l){let h=(await Promise.allSettled(l.map(y=>y.close()))).filter(y=>y.status==="rejected").map(y=>new Error(y.reason));try{await c.close()}catch(y){h.push(y)}if(h.length>0)throw new AggregateError(h,"Failed to close some servers")}}async function Pr(t){return await Mt(t)}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,PortNotAvailableError,ServerAlreadyRunningError,startPrismaDevServer,unstable_startServer});
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as f,b as g}from"./chunk-4Q54Y6ZK.js";import"./chunk-RBVZVBDC.js";import{g as e}from"./chunk-ZCVJ53EE.js";import{a,b,c,f as d}from"./chunk-LMPFMHCB.js";import"./chunk-7EOUKLQR.js";import"./chunk-EPFUMVT3.js";export{a as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,c as DEFAULT_SHADOW_DATABASE_PORT,d as PortNotAvailableError,e as ServerAlreadyRunningError,f as startPrismaDevServer,g as unstable_startServer};
1
+ import{a as f,b as g}from"./chunk-OUMJ6Z34.js";import"./chunk-3BZW3EVN.js";import{g as e}from"./chunk-MO5SCYLN.js";import{a,b,c,f as d}from"./chunk-LMPFMHCB.js";import"./chunk-GZSROICS.js";import"./chunk-ITQ6ILGR.js";export{a as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,c as DEFAULT_SHADOW_DATABASE_PORT,d as PortNotAvailableError,e as ServerAlreadyRunningError,f as startPrismaDevServer,g as unstable_startServer};
package/dist/state.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var ye=Object.create;var O=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty;var xe=(t,e)=>{for(var r in e)O(t,r,{get:e[r],enumerable:!0})},z=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of we(e))!De.call(t,s)&&s!==r&&O(t,s,{get:()=>e[s],enumerable:!(n=ve(e,s))||n.enumerable});return t};var D=(t,e,r)=>(r=t!=null?ye(Se(t)):{},z(e||!t||!t.__esModule?O(r,"default",{value:t,enumerable:!0}):r,t)),ke=t=>z(O({},"__esModule",{value:!0}),t);var Be={};xe(Be,{ServerAlreadyRunningError:()=>j,ServerState:()=>h,ServerStateAlreadyExistsError:()=>R,deleteServer:()=>Ie,getServerStatus:()=>X,isServerRunning:()=>me,killServer:()=>Pe});module.exports=ke(Be);var he=require("fs/promises"),g=require("pathe"),w=require("proper-lockfile"),J=require("std-env"),a=require("valibot");var Y=require("fs"),l=require("fs/promises"),Z=require("util"),Q=require("zlib");var d=D(require("path"),1),I=D(require("os"),1),$=D(require("process"),1),m=I.default.homedir(),B=I.default.tmpdir(),{env:y}=$.default,Oe=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(B,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(B,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(B,e,t)}};function N(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),$.default.platform==="darwin"?Oe(t):$.default.platform==="win32"?$e(t):_e(t)}var ee=D(require("zeptomatch"),1),Te=N("prisma-dev"),Fe=(0,Z.promisify)(Q.unzip);function v(t){return`${Te.data}/${t}`}function te(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function re(t){try{return await(0,l.readFile)(t,{encoding:"utf-8"})}catch(e){if(te(e))return null;throw e}}async function se(t){await(0,l.mkdir)(t,{recursive:!0})}async function oe(t,e){try{return(await(0,l.readdir)(t,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!e||(0,ee.default)(e,s.name))&&n.push(s.name),n),[])}catch(r){if(te(r))return[];throw r}}async function ae(t){await(0,l.rm)(t,{force:!0,recursive:!0})}var ne=require("timers/promises"),x=require("std-env");function U(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 ie(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(!U(t,e))return!0;await(0,ne.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"),A=require("remeda"),ce=51214,ue=51213,de=51215,T=65535,P=-1/0;async function F(t){let{debug:e,name:r,requestedPorts:n,servers:s}=t,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:i}=Re(r,s);e&&(console.debug(`ports used by other servers: ${Object.keys(o).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:o,portsUsedByThisServerLastTime:i,requestedPorts:n})??await Ae({debug:e,pickedPorts:c,portKey:p,portsUsedByOtherServers:o,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:s,requestedPorts:o}=t,{[r]:i,...c}=o;if(pe(i))return await je({debug:e,otherRequestedPorts:c,portKey:r,portsUsedByOtherServers:n,requestedPort:i}),i;let u=s?.[r]??P;if(!pe(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:s,portsUsedByThisServerLastTime:o}=t,i=Math.max(ce,ue,de)+1,c=[...Object.values(r),...Object.keys(s).map(Number),...Object.values(o||{})],u=Math.min(Math.max(i,...c)+100,T),p=(0,A.difference)((0,A.range)(i,u),c),f={port:ue,databasePort:ce,shadowDatabasePort:de}[n];try{return await(0,b.getPort)({port:f in s||Object.values(r).includes(f)||Object.values(o||{}).includes(f)?void 0:f,ports:p})}catch(S){if(S instanceof Error&&S.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 S}}function pe(t){return t>=0}function Re(t,e){let r={},n;for(let s of e){let{databasePort:o,port:i,shadowDatabasePort:c}=s;if(s.name===t){n={databasePort:o,port:i,shadowDatabasePort:c};continue}r[o]=!0,r[i]=!0,r[c]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}async function je(t){let{debug:e,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=t;if(o in s)throw e&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new q(o);if(Object.values(r).includes(o))throw e&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new V(o);if((0,b.isUnsafePort)(o))throw e&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new E(o);if(await(0,b.checkPort)(o)===!1)throw e&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new E(o)}var E=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},V=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},q=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};var G=(0,a.pipe)((0,a.string)(),(0,a.url)()),le=(0,a.object)({connectionString:G,prismaORMConnectionString:(0,a.optional)(G),terminalCommand:(0,a.optional)((0,a.string)())}),fe=(0,a.object)({url:G}),C=(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:C,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:C,shadowDatabasePort:C,version:(0,a.literal)("1")}),W=Symbol("initialize"),K="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??K,this.persistenceMode=e.persistenceMode,this.pid=e.pid??J.process.pid,this._port=e.port??P,this._shadowDatabasePort=e.shadowDatabasePort??P}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new k(e):new H(e);return await r[W](),r}static async fromServerDump(e){let{debug:r,name:n=K}=e??{},s=v(n),o=k.getServerDumpPath(s),i=await re(o);if(i==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(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 "${o}":
2
- ${JSON.stringify(c,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new k({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??{},s=(0,g.join)(v(K),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let o=await oe(s,n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(i=>X(i,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},H=class extends h{constructor(e){super({...e,databasePort:e?.databasePort,persistenceMode:"stateless",port:e?.port,shadowDatabasePort:e?.shadowDatabasePort})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[W](){let e;try{e=await h.scan({debug:this.debug,onlyMetadata:!0})}catch(n){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",n),e=[]}let r=await F({debug:this.debug,name:this.dryRun?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}async close(){}async writeServerDump(){}},k=class t extends h{#t;#e;#s;#a;#n;#o;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#o=!1,this.#e=v(this.name),this.#t=(0,g.join)(this.#e,"db_dump.bak"),this.#s=(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[W](){await se(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,w.lock)(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await h.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 j(this):e}}async close(){if(!this.#o)try{await(0,w.unlock)(this.#e,{lockfilePath:this.#s}),this.#o=!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:J.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 Ie(t,e){await Pe(t,e);let r=v(typeof t=="string"?t:t.name);await ae(r)}async function X(t,e){let{debug:r,onlyMetadata:n}=e||{},s=typeof t=="string"?t:t.name,o=typeof t!="string"?t:void 0,i={databasePort:o?.databasePort??-1,exports:o?.exports,name:s,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let c=o||await h.fromServerDump({debug:r,name:s});if(!c)return r&&console.debug(`[State] no server state found for name: ${s}`),{...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(!U(p,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${p}`),{...i,status:"not_running"};let f=v(s);try{if(!await(0,w.check)(f,{lockfilePath:(0,g.join)(f,".lock")}))return r&&console.debug(`[State] server state for "${s}" is not locked, indicating it is not running.`),{...i,status:"starting_up"}}catch(ge){r&&console.error(`[State] server state for "${s}" failed to check lock:`,ge)}if(!u)return{...i,status:"starting_up"};let{http:S}=u,{hc:be}=await import("hono/client"),M=await be(S.url).health.$get();if(!M.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(M)}`),{...i,status:"not_running"};let L=await M.json();return L.name!==t?(r&&console.debug(`[State] server state for "${s}" has mismatched health response: ${JSON.stringify(L)}`),{...i,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(L)}`),{...i,status:"running"})}catch(c){return r&&console.error(`[State] failed to get server status for "${s}":`,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 X(t,{debug:e}):t;if(!me(n))return!1;let s=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 s?.close()}catch{}return!1}let o=await ie(r,e);try{await s?.close()}catch{}return o}var R=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},j=class extends R{#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});
1
+ "use strict";var ye=Object.create;var O=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty;var xe=(t,e)=>{for(var r in e)O(t,r,{get:e[r],enumerable:!0})},z=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of we(e))!De.call(t,s)&&s!==r&&O(t,s,{get:()=>e[s],enumerable:!(i=ve(e,s))||i.enumerable});return t};var D=(t,e,r)=>(r=t!=null?ye(Se(t)):{},z(e||!t||!t.__esModule?O(r,"default",{value:t,enumerable:!0}):r,t)),Te=t=>z(O({},"__esModule",{value:!0}),t);var Ne={};xe(Ne,{ServerAlreadyRunningError:()=>R,ServerState:()=>f,ServerStateAlreadyExistsError:()=>A,deleteServer:()=>Le,getServerStatus:()=>X,isServerRunning:()=>me,killServer:()=>be});module.exports=Te(Ne);var fe=require("fs/promises"),g=require("pathe"),w=require("proper-lockfile"),J=require("std-env"),a=require("valibot");var Y=require("fs"),p=require("fs/promises"),Z=require("util"),Q=require("zlib");var d=D(require("path"),1),L=D(require("os"),1),k=D(require("process"),1),m=L.default.homedir(),N=L.default.tmpdir(),{env:y}=k.default,Oe=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(N,t)}},ke=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(N,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(N,e,t)}};function U(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),k.default.platform==="darwin"?Oe(t):k.default.platform==="win32"?ke(t):$e(t)}var ee=D(require("zeptomatch"),1),_e=U("prisma-dev"),qe=(0,Z.promisify)(Q.unzip);function v(t){return`${_e.data}/${t}`}function te(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function re(t){try{return await(0,p.readFile)(t,{encoding:"utf-8"})}catch(e){if(te(e))return null;throw e}}async function se(t){await(0,p.mkdir)(t,{recursive:!0})}async function oe(t,e){try{return(await(0,p.readdir)(t,{withFileTypes:!0})).reduce((i,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!e||(0,ee.default)(e,s.name))&&i.push(s.name),i),[])}catch(r){if(te(r))return[];throw r}}async function ae(t){await(0,p.rm)(t,{force:!0,recursive:!0})}var ie=require("timers/promises"),x=require("std-env");function B(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 ne(t,e){if(!x.process.kill)return!1;try{x.process.kill(t,"SIGTERM")}catch(i){return e&&console.error(`Error killing process with PID ${t}:`,i),!1}let r=0;do{if(!B(t,e))return!0;await(0,ie.setTimeout)(100)}while(++r<50);try{return x.process.kill(t,"SIGKILL")}catch(i){return e&&console.error(`Error forcefully killing process with PID ${t}:`,i),!1}}var P=require("get-port-please"),E=require("remeda"),ue=51214,ce=51213,de=51215,_=65535,b=-1/0;async function q(t){let{debug:e,name:r,requestedPorts:i,servers:s}=t,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n}=Ae(r,s);e&&(console.debug(`ports used by other servers: ${Object.keys(o).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(n)}`));let u={databasePort:b,port:b,shadowDatabasePort:b},c=["port","databasePort","shadowDatabasePort"];for(let l of c){let h=await Me({debug:e,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:i})??await Ee({debug:e,pickedPorts:u,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n});e&&console.debug(`Got port for "${l}": ${h}`),u[l]=h}return e&&console.debug(`Picked ports: ${JSON.stringify(u)}`),u}async function Me(t){let{debug:e,portKey:r,portsUsedByOtherServers:i,portsUsedByThisServerLastTime:s,requestedPorts:o}=t,{[r]:n,...u}=o;if(le(n))return await Re({debug:e,otherRequestedPorts:u,portKey:r,portsUsedByOtherServers:i,requestedPort:n}),n;let c=s?.[r]??b;if(!le(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=c in i;return l||Object.values(u).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,P.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 Ee(t){let{debug:e,pickedPorts:r,portKey:i,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=t,n=Math.max(ue,ce,de)+1,u=[...Object.values(r),...Object.keys(s).map(Number),...Object.values(o||{})],c=Math.min(Math.max(n,...u)+100,_),l=(0,E.difference)((0,E.range)(n,c),u),h={port:ce,databasePort:ue,shadowDatabasePort:de}[i];try{return await(0,P.getPort)({port:h in s||Object.values(r).includes(h)||Object.values(o||{}).includes(h)?void 0:h,ports:l})}catch(S){if(S instanceof Error&&S.name==="GetPortError"&&c+1<=_)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${_}].`),await(0,P.getPort)({portRange:[c+1,_]});throw S}}function le(t){return t>=0}function Ae(t,e){let r={},i;for(let s of e){let{databasePort:o,port:n,shadowDatabasePort:u}=s;if(s.name===t){i={databasePort:o,port:n,shadowDatabasePort:u};continue}r[o]=!0,r[n]=!0,r[u]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:i}}async function Re(t){let{debug:e,otherRequestedPorts:r,portKey:i,portsUsedByOtherServers:s,requestedPort:o}=t;if(o in s)throw e&&console.error(`Port ${o} was requested for "${i}", but is already used by another server.`),new V(o);if(Object.values(r).includes(o))throw e&&console.error(`Port ${o} was requested for "${i}", but also for another key.`),new C(o);if((0,P.isUnsafePort)(o))throw e&&console.error(`Port ${o} was requested for "${i}", but is unsafe.`),new M(o);if(await(0,P.checkPort)(o)===!1)throw e&&console.error(`Port ${o} was requested for "${i}", but is not available.`),new M(o)}var M=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"},V=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 G=(0,a.pipe)((0,a.string)(),(0,a.url)()),pe=(0,a.object)({connectionString:G,prismaORMConnectionString:(0,a.optional)(G),terminalCommand:(0,a.optional)((0,a.string)())}),he=(0,a.object)({url:G}),F=(0,a.pipe)((0,a.number)(),(0,a.integer)(),(0,a.minValue)(1)),Ie=(0,a.object)({database:pe,http:he,ppg:he,shadowDatabase:pe}),je=(0,a.object)({databasePort:F,exports:(0,a.optional)(Ie),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:F,shadowDatabasePort:F,version:(0,a.literal)("1")}),W=Symbol("initialize"),K="default",f=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??b,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??K,this.persistenceMode=e.persistenceMode,this.pid=e.pid??J.process.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??b,this._shadowDatabasePort=e.shadowDatabasePort??b}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new T(e):new H(e);return await r[W](),r}static async fromServerDump(e){let{debug:r,name:i=K}=e??{},s=v(i),o=T.getServerDumpPath(s),n=await re(o);if(n==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(n));let{issues:u,output:c,success:l}=(0,a.safeParse)((0,a.pipe)((0,a.string)(),(0,a.parseJson)(),je),n);if(!l)throw r&&console.debug(`[State] Invalid server dump file at "${o}":
2
+ ${JSON.stringify(u,null,2)}`),new Error(`Invalid Prisma Dev state for "${i}".`);return new T({databasePort:c.databasePort,debug:r,dryRun:!1,name:i,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r,globs:i}=e??{},s=(0,g.join)(v(K),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let o=await oe(s,i);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(n=>X(n,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},H=class extends f{constructor(e){super({...e,databasePort:e?.databasePort,persistenceMode:"stateless",port:e?.port,shadowDatabasePort:e?.shadowDatabasePort})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[W](){let e;try{e=await f.scan({debug:this.debug,onlyMetadata:!0})}catch(i){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",i),e=[]}let r=await q({debug:this.debug,name:this.dryRun?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}async close(){}async writeServerDump(){}},T=class t extends f{#t;#e;#s;#a;#i;#o;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#o=!1,this.#e=v(this.name),this.#t=(0,g.join)(this.#e,"db_dump.bak"),this.#s=(0,g.join)(this.#e,".lock"),this.#a=(0,g.join)(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#i=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[W](){await se(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,w.lock)(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await f.scan({debug:this.debug,onlyMetadata:!0}),r=await q({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 R(this):e}}async close(){if(!this.#o)try{await(0,w.unlock)(this.#e,{lockfilePath:this.#s}),this.#o=!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:J.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,fe.writeFile)(this.#i,`${JSON.stringify(this.#r,null,2)}
3
+ `,{encoding:"utf-8"})}};async function Le(t,e){await be(t,e);let r=v(typeof t=="string"?t:t.name);await ae(r)}async function X(t,e){let{debug:r,onlyMetadata:i}=e||{},s=typeof t=="string"?t:t.name,o=typeof t!="string"?t:void 0,n={databasePort:o?.databasePort??-1,exports:o?.exports,name:s,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let u=o||await f.fromServerDump({debug:r,name:s});if(!u)return r&&console.debug(`[State] no server state found for name: ${s}`),{...n,status:"no_such_server"};n.databasePort=u.databasePort,n.exports=u.exports,n.pid=u.pid,n.port=u.port,n.shadowDatabasePort=u.shadowDatabasePort;let{exports:c,pid:l}=u;if(i)return{...n,status:"unknown"};if(!B(l,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${l}`),{...n,status:"not_running"};let h=v(s);try{if(!await(0,w.check)(h,{lockfilePath:(0,g.join)(h,".lock")}))return r&&console.debug(`[State] server state for "${s}" is not locked, indicating it is not running.`),{...n,status:"starting_up"}}catch(ge){r&&console.error(`[State] server state for "${s}" failed to check lock:`,ge)}if(!c)return{...n,status:"starting_up"};let{http:S}=c,{hc:Pe}=await import("hono/client"),I=await Pe(S.url).health.$get();if(!I.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(I)}`),{...n,status:"not_running"};let j=await I.json();return j.name!==t?(r&&console.debug(`[State] server state for "${s}" has mismatched health response: ${JSON.stringify(j)}`),{...n,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(j)}`),{...n,status:"running"})}catch(u){return r&&console.error(`[State] failed to get server status for "${s}":`,u),{...n,status:"error"}}}function me(t){let{status:e}=t;return e==="running"||e==="starting_up"}async function be(t,e){let{pid:r,...i}=typeof t=="string"?await X(t,{debug:e}):t;if(!me(i))return!1;let s=await f.fromServerDump({debug:e,name:i.name});if(r==null){e&&console.debug(`[State] No PID found for server "${i.name}" to kill.`);try{await s?.close()}catch{}return!1}let o=await ne(r,e);try{await s?.close()}catch{}return o}var A=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},R=class extends A{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return f.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
@@ -48,6 +48,34 @@ declare const serverDumpV1Schema: valibot.ObjectSchema<{
48
48
  }, undefined>;
49
49
  type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
50
50
  interface ServerOptions {
51
+ /**
52
+ * Connection timeout in milliseconds for pending database connections.
53
+ *
54
+ * Starts ticking for every new client that attempts to connect. When exceeded,
55
+ * the pending client connection is evicted and closed.
56
+ *
57
+ * Default is 1 minute (60,000 milliseconds).
58
+ *
59
+ * Use it with caution, as it may lead to unexpected behavior. Best used with
60
+ * a pool client that retries connections.
61
+ */
62
+ databaseConnectTimeoutMillis?: number;
63
+ /**
64
+ * Idle timeout in milliseconds for active database connections.
65
+ *
66
+ * Re-starts ticking after each message received on the active connection. When
67
+ * exceeded - meaning there hasn't been any activity for a while, the active
68
+ * client connection is closed, and a pending connection is promoted to active.
69
+ *
70
+ * Is not applied by default.
71
+ *
72
+ * Use it with caution, as it may lead to unexpected disconnections. Best used
73
+ * with a pool client that can handle disconnections gracefully.
74
+ *
75
+ * Set it if you suffer from client hanging indefinitely as the active connection
76
+ * remain open forever.
77
+ */
78
+ databaseIdleTimeoutMillis?: number;
51
79
  /**
52
80
  * The port the database server will listen on.
53
81
  *
@@ -88,6 +116,18 @@ interface ServerOptions {
88
116
  * An error is thrown if the port is already in use.
89
117
  */
90
118
  port?: number;
119
+ /**
120
+ * Connection timeout in milliseconds for pending shadow database connections.
121
+ *
122
+ * Default is {@link databaseConnectTimeoutMillis}.
123
+ */
124
+ shadowDatabaseConnectTimeoutMillis?: number;
125
+ /**
126
+ * Idle timeout in milliseconds for active shadow database connections.
127
+ *
128
+ * Default is {@link databaseIdleTimeoutMillis}.
129
+ */
130
+ shadowDatabaseIdleTimeoutMillis?: number;
91
131
  /**
92
132
  * The port the shadow database server will listen on.
93
133
  *
@@ -107,11 +147,15 @@ interface ScanOptions {
107
147
  declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
108
148
  declare abstract class ServerState implements ResolvedServerOptions {
109
149
  protected _databasePort: number;
150
+ readonly databaseConnectTimeoutMillis: number;
151
+ readonly databaseIdleTimeoutMillis: number;
110
152
  readonly debug: boolean;
111
153
  readonly dryRun: boolean;
112
154
  readonly name: string;
113
155
  readonly persistenceMode: PersistenceMode;
114
156
  readonly pid: number | undefined;
157
+ readonly shadowDatabaseConnectTimeoutMillis: number;
158
+ readonly shadowDatabaseIdleTimeoutMillis: number;
115
159
  protected _port: number;
116
160
  protected _shadowDatabasePort: number;
117
161
  protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
package/dist/state.d.ts CHANGED
@@ -48,6 +48,34 @@ declare const serverDumpV1Schema: valibot.ObjectSchema<{
48
48
  }, undefined>;
49
49
  type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
50
50
  interface ServerOptions {
51
+ /**
52
+ * Connection timeout in milliseconds for pending database connections.
53
+ *
54
+ * Starts ticking for every new client that attempts to connect. When exceeded,
55
+ * the pending client connection is evicted and closed.
56
+ *
57
+ * Default is 1 minute (60,000 milliseconds).
58
+ *
59
+ * Use it with caution, as it may lead to unexpected behavior. Best used with
60
+ * a pool client that retries connections.
61
+ */
62
+ databaseConnectTimeoutMillis?: number;
63
+ /**
64
+ * Idle timeout in milliseconds for active database connections.
65
+ *
66
+ * Re-starts ticking after each message received on the active connection. When
67
+ * exceeded - meaning there hasn't been any activity for a while, the active
68
+ * client connection is closed, and a pending connection is promoted to active.
69
+ *
70
+ * Is not applied by default.
71
+ *
72
+ * Use it with caution, as it may lead to unexpected disconnections. Best used
73
+ * with a pool client that can handle disconnections gracefully.
74
+ *
75
+ * Set it if you suffer from client hanging indefinitely as the active connection
76
+ * remain open forever.
77
+ */
78
+ databaseIdleTimeoutMillis?: number;
51
79
  /**
52
80
  * The port the database server will listen on.
53
81
  *
@@ -88,6 +116,18 @@ interface ServerOptions {
88
116
  * An error is thrown if the port is already in use.
89
117
  */
90
118
  port?: number;
119
+ /**
120
+ * Connection timeout in milliseconds for pending shadow database connections.
121
+ *
122
+ * Default is {@link databaseConnectTimeoutMillis}.
123
+ */
124
+ shadowDatabaseConnectTimeoutMillis?: number;
125
+ /**
126
+ * Idle timeout in milliseconds for active shadow database connections.
127
+ *
128
+ * Default is {@link databaseIdleTimeoutMillis}.
129
+ */
130
+ shadowDatabaseIdleTimeoutMillis?: number;
91
131
  /**
92
132
  * The port the shadow database server will listen on.
93
133
  *
@@ -107,11 +147,15 @@ interface ScanOptions {
107
147
  declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
108
148
  declare abstract class ServerState implements ResolvedServerOptions {
109
149
  protected _databasePort: number;
150
+ readonly databaseConnectTimeoutMillis: number;
151
+ readonly databaseIdleTimeoutMillis: number;
110
152
  readonly debug: boolean;
111
153
  readonly dryRun: boolean;
112
154
  readonly name: string;
113
155
  readonly persistenceMode: PersistenceMode;
114
156
  readonly pid: number | undefined;
157
+ readonly shadowDatabaseConnectTimeoutMillis: number;
158
+ readonly shadowDatabaseIdleTimeoutMillis: number;
115
159
  protected _port: number;
116
160
  protected _shadowDatabasePort: number;
117
161
  protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
package/dist/state.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g}from"./chunk-ZCVJ53EE.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};
1
+ import{a,b,c,d,e,f,g}from"./chunk-MO5SCYLN.js";import"./chunk-LMPFMHCB.js";import"./chunk-ITQ6ILGR.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.17.0",
3
+ "version": "0.19.0",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
6
  "author": "Igal Klebanov <igalklebanov@gmail.com> (https://github.com/igalklebanov)",
@@ -63,35 +63,35 @@
63
63
  ],
64
64
  "license": "ISC",
65
65
  "devDependencies": {
66
- "@arethetypeswrong/cli": "0.18.1",
67
- "@types/node": "22.15.21",
68
- "@types/pako": "2.0.3",
66
+ "@arethetypeswrong/cli": "0.18.2",
67
+ "@types/node": "25.0.3",
68
+ "@types/pako": "2.0.4",
69
69
  "@types/proper-lockfile": "4.1.4",
70
70
  "env-paths": "3.0.0",
71
- "pkg-types": "2.1.0",
72
- "tsup": "8.5.0",
73
- "typescript": "5.8.3",
74
- "vitest": "3.1.4",
71
+ "pkg-types": "2.3.0",
72
+ "tsup": "8.5.1",
73
+ "typescript": "5.9.3",
74
+ "vitest": "4.0.16",
75
75
  "common-stuff": "^0.0.0"
76
76
  },
77
77
  "dependencies": {
78
- "@electric-sql/pglite": "0.3.2",
79
- "@electric-sql/pglite-socket": "0.0.6",
80
- "@electric-sql/pglite-tools": "0.2.7",
81
- "@hono/node-server": "1.19.6",
82
- "@mrleebo/prisma-ast": "0.12.1",
83
- "@prisma/get-platform": "6.8.2",
84
- "@prisma/query-plan-executor": "6.18.0",
78
+ "@electric-sql/pglite": "0.3.14",
79
+ "@electric-sql/pglite-socket": "0.0.19",
80
+ "@electric-sql/pglite-tools": "0.2.19",
81
+ "@hono/node-server": "1.19.7",
82
+ "@mrleebo/prisma-ast": "0.13.1",
83
+ "@prisma/get-platform": "7.1.0",
84
+ "@prisma/query-plan-executor": "7.1.0",
85
85
  "foreground-child": "3.3.1",
86
- "get-port-please": "3.1.2",
87
- "hono": "4.10.6",
86
+ "get-port-please": "3.2.0",
87
+ "hono": "4.11.1",
88
88
  "http-status-codes": "2.3.0",
89
89
  "pathe": "2.0.3",
90
90
  "proper-lockfile": "4.1.2",
91
- "remeda": "2.21.3",
92
- "std-env": "3.9.0",
91
+ "remeda": "2.32.0",
92
+ "std-env": "3.10.0",
93
93
  "valibot": "1.2.0",
94
- "zeptomatch": "2.0.2"
94
+ "zeptomatch": "2.1.0"
95
95
  },
96
96
  "scripts": {
97
97
  "build": "tsup",
@@ -1 +0,0 @@
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};
@@ -1 +0,0 @@
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};
@@ -1,3 +0,0 @@
1
- import{d as f,e as w}from"./chunk-LMPFMHCB.js";import{b as c,f as O,g as V,h as N,i as T}from"./chunk-EPFUMVT3.js";import{writeFile as z}from"fs/promises";import{join as l}from"pathe";import{check as Q,lock as W,unlock as X}from"proper-lockfile";import{process as j}from"std-env";import{integer as C,literal as ee,minLength as te,minValue as F,number as q,object as P,optional as g,parseJson as re,pipe as h,safeParse as se,string as v,url as ae}from"valibot";import{setTimeout as Z}from"timers/promises";import{process as b}from"std-env";function y(r,e){if(r==null)return!1;try{return b.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}async function A(r,e){if(!b.kill)return!1;try{b.kill(r,"SIGTERM")}catch(o){return e&&console.error(`Error killing process with PID ${r}:`,o),!1}let t=0;do{if(!y(r,e))return!0;await Z(100)}while(++t<50);try{return b.kill(r,"SIGKILL")}catch(o){return e&&console.error(`Error forcefully killing process with PID ${r}:`,o),!1}}var _=h(v(),ae()),L=P({connectionString:_,prismaORMConnectionString:g(_),terminalCommand:g(v())}),J=P({url:_}),x=h(q(),C(),F(1)),oe=P({database:L,http:J,ppg:J,shadowDatabase:L}),ne=P({databasePort:x,exports:g(oe),name:h(v(),te(1)),pid:g(h(q(),C(),F(0))),port:x,shadowDatabasePort:x,version:ee("1")}),E=Symbol("initialize"),k="default",u=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??k,this.persistenceMode=e.persistenceMode,this.pid=e.pid??j.pid,this._port=e.port??f,this._shadowDatabasePort=e.shadowDatabasePort??f}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new p(e):new $(e);return await t[E](),t}static async fromServerDump(e){let{debug:t,name:o=k}=e??{},a=c(o),n=p.getServerDumpPath(a),s=await O(n);if(s==null)return t&&console.debug(`[State] No server dump file found at: ${n}`),null;t&&(console.debug(`[State] server dump file found at "${n}":`),console.debug(s));let{issues:i,output:d,success:m}=se(h(v(),re(),ne),s);if(!m)throw t&&console.debug(`[State] Invalid server dump file at "${n}":
2
- ${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new p({databasePort:d.databasePort,debug:t,dryRun:!1,name:o,pid:d.pid,port:d.port,serverDump:d,shadowDatabasePort:d.shadowDatabasePort})}static async scan(e){let{debug:t,globs:o}=e??{},a=l(c(k),"..");t&&console.debug(`[State] scanning for server states in: ${a}`);let n=await N(a,o);return t&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(s=>H(s,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},$=class extends u{constructor(e){super({...e,databasePort:e?.databasePort,persistenceMode:"stateless",port:e?.port,shadowDatabasePort:e?.shadowDatabasePort})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[E](){let e;try{e=await u.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let t=await w({debug:this.debug,name:this.dryRun?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}async close(){}async writeServerDump(){}},p=class r extends u{#t;#e;#s;#o;#n;#a;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#a=!1,this.#e=c(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=r.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[E](){await V(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await W(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await u.scan({debug:this.debug,onlyMetadata:!0}),t=await w({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 I(this):e}}async close(){if(!this.#a)try{await X(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:j.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await z(this.#n,`${JSON.stringify(this.#r,null,2)}
3
- `,{encoding:"utf-8"})}};async function De(r,e){await ue(r,e);let t=c(typeof r=="string"?r:r.name);await T(t)}async function H(r,e){let{debug:t,onlyMetadata:o}=e||{},a=typeof r=="string"?r:r.name,n=typeof r!="string"?r:void 0,s={databasePort:n?.databasePort??-1,exports:n?.exports,name:a,pid:n?.pid,port:n?.port??-1,shadowDatabasePort:n?.shadowDatabasePort??-1,version:"1"};try{let i=n||await u.fromServerDump({debug:t,name:a});if(!i)return t&&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:d,pid:m}=i;if(o)return{...s,status:"unknown"};if(!y(m,t))return t&&console.debug(`[State] server state for "${a}" has no running process with PID: ${m}`),{...s,status:"not_running"};let R=c(a);try{if(!await Q(R,{lockfilePath:l(R,".lock")}))return t&&console.debug(`[State] server state for "${a}" is not locked, indicating it is not running.`),{...s,status:"starting_up"}}catch(G){t&&console.error(`[State] server state for "${a}" failed to check lock:`,G)}if(!d)return{...s,status:"starting_up"};let{http:K}=d,{hc:B}=await import("hono/client"),S=await B(K.url).health.$get();if(!S.ok)return t&&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!==r?(t&&console.debug(`[State] server state for "${a}" has mismatched health response: ${JSON.stringify(D)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(D)}`),{...s,status:"running"})}catch(i){return t&&console.error(`[State] failed to get server status for "${a}":`,i),{...s,status:"error"}}}function ie(r){let{status:e}=r;return e==="running"||e==="starting_up"}async function ue(r,e){let{pid:t,...o}=typeof r=="string"?await H(r,{debug:e}):r;if(!ie(o))return!1;let a=await u.fromServerDump({debug:e,name:o.name});if(t==null){e&&console.debug(`[State] No PID found for server "${o.name}" to kill.`);try{await a?.close()}catch{}return!1}let n=await A(t,e);try{await a?.close()}catch{}return n}var M=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},I=class extends M{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return u.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{u as a,De as b,H as c,ie as d,ue as e,M as f,I as g};