@prisma/dev 0.16.1 → 0.18.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,3 @@
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-ITQ6ILGR.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};
@@ -1 +1 @@
1
- import{a as d}from"./chunk-RBVZVBDC.js";import{a as w}from"./chunk-FZ7JBZR6.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-QWUDE25K.js";import{a as w}from"./chunk-6374E7DO.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};
@@ -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 @@
1
+ import{f as u}from"./chunk-LMPFMHCB.js";import{e as l}from"./chunk-ITQ6ILGR.js";import{filename as w}from"pathe/utils";var n={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},P=`postgres://${n.username}:${n.password}@localhost`,b=new URLSearchParams({sslmode:n.sslMode}),y=new URLSearchParams({...Object.fromEntries(b.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 R(e,o){let a=e==="database"?o.databasePort:o.shadowDatabasePort;if(o.dryRun)return p(e,o,{db:null,port:a,server:null});let{debug:i}=o,s=await(e==="shadow_database"?v:f)(o.pgliteDataDirPath,i);i&&s.onNotification((t,m)=>{console.debug(`[${e}][${t}] ${m}`)});let{PGLiteSocketServer:d}=await import("@electric-sql/pglite-socket"),r=new d({db:s,debug:i,inspect:i,port:a});i&&(r.addEventListener("listening",t=>{let{detail:m}=t;console.debug(`[${e}] server listening on ${JSON.stringify(m)}`)}),r.addEventListener("connection",t=>{let{clientAddress:m,clientPort:D}=t.detail;console.debug(`[${e}] client connected from ${m}:${D}`)}),r.addEventListener("error",t=>{let{detail:m}=t;console.error(`[${e}] server error:`,m)}));try{await r.start()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="EADDRINUSE"?new u(a):t}return p(e,o,{db:s,port:a,server:r})}function p(e,o,a){let{debug:i}=o,{db:c,port:s,server:d}=a||{};return i&&console.debug(`[${e}] server started on port ${s}`),{...n,close:async()=>{let r=[];try{await d?.stop(),i&&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(),i&&console.debug(`[${e}] synced to filesystem`)}catch(t){console.error(`[${e}] sync error`,t),r.push(t)}try{await c?.close(),i&&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:g(s,b),dump:async r=>{e==="shadow_database"||!c||await $({db:c,debug:i,destinationPath:r})},port:s,prismaORMConnectionString:g(s,y),terminalCommand:`PGPASSWORD=${n.password} PGSSLMODE=${n.sslMode} psql -h localhost -p ${s} -U ${n.username} -d ${n.database}`}}function g(e,o){return`${P}:${e}/${n.database}?${o.toString()}`}async function f(e,o){let{PGlite:a}=await import("@electric-sql/pglite");return await a.create({database:n.database,dataDir:e,debug:o?5:void 0,extensions:await S(),relaxedDurability:!1,username:n.username})}async function v(e,o){let{PGlite:a}=await import("@electric-sql/pglite");return await a.create({database:n.database,dataDir:"memory://",debug:o?5:void 0,extensions:await S(),relaxedDurability:!1,username:n.username})}async function S(){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)}async function $(e){let{dataDir:o,db:a,debug:i,destinationPath:c}=e,s=a||await f(o,i),{pgDump:d}=await import("@electric-sql/pglite-tools/pg_dump"),r=await d({args:["--schema-only","--no-owner"],fileName:c?w(c):void 0,pg:await s.clone()});return c?(i&&console.debug(`[DB] Dumping database to ${c}`),await l(r,c)):(i&&console.debug("[DB] Dumping database to memory"),await r.text())}export{R as a,$ as b};
package/dist/daemon.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var Nt=Object.create;var J=Object.defineProperty;var Ut=Object.getOwnPropertyDescriptor;var qt=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var $e=(t,e)=>{for(var r in e)J(t,r,{get:e[r],enumerable:!0})},_e=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qt(e))!Vt.call(t,n)&&n!==r&&J(t,n,{get:()=>e[n],enumerable:!(o=Ut(e,n))||o.enumerable});return t};var v=(t,e,r)=>(r=t!=null?Nt(Ft(t)):{},_e(e||!t||!t.__esModule?J(r,"default",{value:t,enumerable:!0}):r,t)),Gt=t=>_e(J({},"__esModule",{value:!0}),t);var l=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 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,ke,Kt,k,ce=D(()=>{"use strict";l();f=require("valibot"),ke=/^(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)(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]=Qt(s);if(i)throw new o(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:u,name:p,shadowDatabaseUrl:h}=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:Bt,port:Ht}=new URL(h),jt=e.get("shadowDBPort");if(x!=="localhost"||Number(R)!==j||Bt!=="localhost"||Number(Ht)!==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 le(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),W.default.platform==="darwin"?Jt(t):W.default.platform==="win32"?Wt(t):zt(t)}var g,ue,W,O,de,M,Jt,Wt,zt,Ce=D(()=>{"use strict";l();g=v(require("path"),1),ue=v(require("os"),1),W=v(require("process"),1),O=ue.default.homedir(),de=ue.default.tmpdir(),{env:M}=W.default,Jt=t=>{let e=g.default.join(O,"Library");return{data:g.default.join(e,"Application Support",t),config:g.default.join(e,"Preferences",t),cache:g.default.join(e,"Caches",t),log:g.default.join(e,"Logs",t),temp:g.default.join(de,t)}},Wt=t=>{let e=M.APPDATA||g.default.join(O,"AppData","Roaming"),r=M.LOCALAPPDATA||g.default.join(O,"AppData","Local");return{data:g.default.join(r,t,"Data"),config:g.default.join(e,t,"Config"),cache:g.default.join(r,t,"Cache"),log:g.default.join(r,t,"Log"),temp:g.default.join(de,t)}},zt=t=>{let e=g.default.basename(O);return{data:g.default.join(M.XDG_DATA_HOME||g.default.join(O,".local","share"),t),config:g.default.join(M.XDG_CONFIG_HOME||g.default.join(O,".config"),t),cache:g.default.join(M.XDG_CACHE_HOME||g.default.join(O,".cache"),t),log:g.default.join(M.XDG_STATE_HOME||g.default.join(O,".local","state"),t),temp:g.default.join(de,e,t)}}});function je(t,e){return`${He.cache}/engine/${t}/${e}`}function N(t){return`${He.data}/${t}`}async function Ne(t){try{return await(0,w.access)(t,w.constants.F_OK),!0}catch(e){if(pe(e))return!1;throw e}}async function Ue(t,e){let r=await Xt(t);await(0,w.writeFile)(e,r),await(0,w.chmod)(e,"755")}async function qe(t,e){await t.stream().pipeTo(z.WriteStream.toWeb((0,z.createWriteStream)(e,{encoding:"utf-8"})))}function pe(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(pe(e))return null;throw e}}async function Ve(t){await(0,w.mkdir)(t,{recursive:!0})}async function Ge(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(pe(r))return[];throw r}}var z,w,Me,Le,Be,He,Xt,X=D(()=>{"use strict";l();z=require("fs"),w=require("fs/promises"),Me=require("util"),Le=require("zlib");Ce();Be=v(require("zeptomatch"),1),He=le("prisma-dev"),Xt=(0,Me.promisify)(Le.unzip)});function ee(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 he=D(()=>{"use strict";l()});function te(t,e){return console.error(t),t instanceof V?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof L?e.text(t.responseBody,t.statusCode):e.body(null,500)}var et,tt,rt,ot,nt,st,ar,ir,Ze,B,V,L,ye=D(()=>{"use strict";l();et=require("child_process"),tt=require("events"),rt=require("fs/promises"),ot=require("path"),nt=require("timers/promises");he();st=require("std-env");X();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:ar,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:ir,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Ze}=st.process.env),B=class t{static#r=new Map;#e;#t;constructor(e){this.#e=e,this.#t=null}static async get(e){let{debug:r}=e,o=`${e.schemaHash}:${e.clientVersion}`;try{let n=t.#r.get(o);if(n)return n;let s=new t(e);return t.#r.set(o,s),r&&console.debug("[Query Engine] starting...",e),await s.start(),r&&console.debug("[Query Engine] started!"),s}finally{t.stopAll(o)}}static async stopAll(e){let o=(await Promise.allSettled(Array.from(t.#r.entries()).filter(([n])=>n!==e).map(async([n,s])=>{try{await s.stop()}finally{t.#r.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(o.length>0)throw new AggregateError(o,"Failed to stop engines")}async commitTransaction(e,r){return await this.#i(e,r,"commit")}async request(e,r){let{url:o}=await this.start(),n=this.#o(r),s=await fetch(o,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await L.fromResponse(s);return await s.text()}async rollbackTransaction(e,r){return await this.#i(e,r,"rollback")}async startTransaction(e,r){let{url:o}=await this.start(),n=this.#o(r),s=await fetch(`${o}/transaction/start`,{body:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await L.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:e,reject:r,resolve:o}=ee();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 h=p.split(`
2
- `).find(j=>j.includes("Started query engine http server"));if(!h)return;a.stdout.removeListener("data",i);let{fields:b}=JSON.parse(h);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 V(String(p))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(p,h)=>{this.#t=null,r(new V(`Query Engine exited with code ${p} and signal ${h}`))};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=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 L.fromResponse(a);try{return await a.json()}catch{return{}}}};V=class extends Error{name="EngineStartError"},L=class t extends Error{constructor(r,o,n){super(`${r}: Query Engine response status ${o}, body: ${n}`);this.action=r;this.statusCode=o;this.responseBody=n}name="EngineHttpError";static async fromResponse(r){let o=new URL(r.url),n=await r.text();return new t(o.pathname,r.status,n)}}});async function 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 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 _,re,Pe,ut=D(()=>{"use strict";l();_=require("@prisma/query-plan-executor"),re=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=ne.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}async function lt(t,e,r){let o=be.Buffer.from(t,"base64").toString("utf8"),n=(0,oe.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,oe.printSchema)(n);r&&console.log("[Accelerate] schema with override:",i);let c=await Se(i);return{base64Override:be.Buffer.from(i,"utf8").toString("base64"),overrideHash:c}}var be,oe,ne,pt=D(()=>{"use strict";l();be=require("buffer"),oe=require("@mrleebo/prisma-ast"),ne=new Map});function se(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 gt(t,e){let{output:r,success:o}=(0,m.safeParse)(dr,t);return o?r:e.json({EngineMalfunction:{}},500)}var m,ur,dr,ht=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:()=>G});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 B.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,G,lr,K,pr,mr,St=D(()=>{"use strict";l();yt=require("hono/http-exception"),Pt=require("hono/tiny"),I=require("hono/validator");ce();it();ye();ut();pt();mt();ht();G=new Pt.Hono;G.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",K=G.basePath(lr);G.route("/",K);pr=["/graphql","/itx/:transactionId/graphql"];K.on("POST",[...pr],(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,{...se(t),"X-transaction-id":n});return t.text(s)}catch(r){return te(r,t)}});K.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,se(t));return t.json(a)}catch(r){return te(r,t)}});K.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=ne.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 ne.set(o,{base64Original:r,...s}),t.text(o)}return r!==n.base64Original?t.text("Schema mismatch",400):t.text(o)});K.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 ve(t);if(o instanceof Response)return o;let n=await o.startTransaction(r,se(t)),s=gt(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 te(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)G.on(e,t,(0,I.validator)("header",k),async r=>{let o=r.req.header("prisma-engine-hash");if(o!=="0.0.0"&&o!==re.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 ${re.version}.`});return await(await ct(r)).fetch(r.req.raw)})});var Dt={};$e(Dt,{utilityRoute:()=>we});var vt,wt,we,io,Et=D(()=>{"use strict";l();vt=require("hono/tiny"),wt=require("http-status-codes"),we=new vt.Hono;we.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=we.get("/health",t=>t.json({name:t.get("serverState").name}))});var Sr={};module.exports=Gt(Sr);l();var Lt=require("timers/promises");l();ce();l();var ze=require("pathe/utils");X();l();var $=require("get-port-please"),Z=require("remeda"),U=51214,q=51213,F=51215,Y=65535,A=-1/0;async function Qe(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(Ke(a))return await tr({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 Zt(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(U,q,F)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,Y),u=(0,Z.difference)((0,Z.range)(a,c),i),p={port:q,databasePort:U,shadowDatabasePort:F}[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(h){if(h instanceof Error&&h.name==="GetPortError"&&c+1<=Y)return e&&console.debug(`Expanding port lookup to range [${c+1}, ${Y}].`),await(0,$.getPort)({portRange:[c+1,Y]});throw h}}function Ke(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 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 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 E(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 qe(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);he();ye();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}=ee(),{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 E(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))(),B.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((...h)=>console.log("[Accelerate]",...h)))}i.use("*",async(p,h)=>(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 h()));let u=new n;return u.route("/",s),u.route("/",a),i.route("/",u),i}l();var Ct=require("fs/promises"),C=require("pathe"),H=require("proper-lockfile"),Oe=require("std-env"),d=require("valibot");X();l();var gr=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 Te=(0,d.pipe)((0,d.string)(),(0,d.url)()),kt=(0,d.object)({connectionString:Te,prismaORMConnectionString:(0,d.optional)(Te),terminalCommand:(0,d.optional)((0,d.string)())}),It=(0,d.object)({url:Te}),De=(0,d.pipe)((0,d.number)(),(0,d.integer)(),(0,d.minValue)(1)),hr=(0,d.object)({database:kt,http:It,ppg:It,shadowDatabase:kt}),yr=(0,d.object)({databasePort:De,exports:(0,d.optional)(hr),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:De,shadowDatabasePort:De,version:(0,d.literal)("1")}),Ae=Symbol("initialize"),Ee="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??Ee,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Oe.process.pid,this._port=e.port??A,this._shadowDatabasePort=e.shadowDatabasePort??A}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new Q(e):new xe(e);return await r[Ae](),r}static async fromServerDump(e){let{debug:r,name:o=Ee}=e??{},n=N(o),s=Q.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 Q({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=>Pr(a,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},xe=class extends T{constructor(e){super({...e,databasePort:e?.databasePort??U,persistenceMode:"stateless",port:e?.port??q,shadowDatabasePort:e?.shadowDatabasePort??F})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Ae](){}async close(){}async writeServerDump(){}},Q=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[Ae](){await Ve(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,H.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 Qe({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 ae(this):e}}async close(){if(!this.#n)try{await(0,H.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:Oe.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 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 p=N(n);try{if(!await(0,H.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:h}=c,{hc:b}=await import("hono/client"),x=await b(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 Re=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},ae=class extends Re{#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 Mt(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: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 h=(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){h.push(b)}if(h.length>0)throw new AggregateError(h,"Failed to close some servers")}}var ie;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,ie?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,ie?.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{ie=await Mt({debug:!0,persistenceMode:"stateful",name:t}),process.send?.({type:"started",server:ie},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)}}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 _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 Vt(e))!Gt.call(t,n)&&n!==r&&G(t,n,{get:()=>e[n],enumerable:!(o=qt(e,n))||o.enumerable});return t};var u=(t,e,r)=>(r=t!=null?Ut(Ft(t)):{},ke(e||!t||!t.__esModule?G(r,"default",{value:t,enumerable:!0}):r,t)),Kt=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 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,Ie,Qt,k,se=D(()=>{"use strict";l();g=require("valibot"),Ie=/^(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)(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))}));k=async(t,e)=>{let{authorization:r}=t,{HTTPException:o}=await import("hono/http-exception");if(!r)throw new o(401,{message:"Missing API Key"});let[n,s="",a]=r.split(" ");if(n!=="Bearer"||a)throw new o(401,{message:"Invalid API Key"});let[i,c]=Jt(s);if(i)throw new o(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:d,name:m,shadowDatabaseUrl:y}=c,{name:S}=e.get("serverState");if(!m)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 "${S}" server's output for the updated \`DATABASE_URL\` value.`});if(m!==S)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${S}", but the API Key is for "${m}"`});let{hostname:x,port:R}=new URL(d),{port:j}=e.get("db"),{hostname:Bt,port:jt}=new URL(y),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 h,ae,K,O,ie,M,Wt,zt,Xt,Me=D(()=>{"use strict";l();h=u(require("path"),1),ae=u(require("os"),1),K=u(require("process"),1),O=ae.default.homedir(),ie=ae.default.tmpdir(),{env:M}=K.default,Wt=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)}},zt=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)}},Xt=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 Yt(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:"utf8"})))}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,Yt,J=D(()=>{"use strict";l();Q=require("fs"),w=require("fs/promises"),He=require("util"),Le=require("zlib");Me();Be=u(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";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 tt,rt,ot,nt,st,at,ir,cr,et,L,U,H,Pe=D(()=>{"use strict";l();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:ir,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:cr,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=cr||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=m=>{let y=m.split(`
2
+ `).find(j=>j.includes("Started query engine http server"));if(!y)return;a.stdout.removeListener("data",i);let{fields:S}=JSON.parse(y);if(S==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${m}`));let{ip:x,port:R}=S;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: ${m}`));o({childProcess:a,url:`http://${x}:${R}`})},c=m=>{this.#t=null,r(new U(String(m))),a.removeListener("exit",d),a.kill()};a.once("error",c);let d=(m,y)=>{this.#t=null,r(new U(`Query Engine exited with code ${m} and signal ${y}`))};return a.once("exit",d),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),(ir==="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,v.safeParse)(ur,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var v,ur,ct=D(()=>{"use strict";l();v=require("valibot"),ur=(0,v.object)({tags:(0,v.union)([(0,v.pipe)((0,v.array)((0,v.string)()),(0,v.minLength)(1)),(0,v.literal)("all")])})});async function ut(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,dt=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 pt(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(d=>d.type==="datasource");if(!s)throw new Error("No datasource block found in schema.");let a=s.assignments.find(d=>d.type==="assignment"&&d.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,mt=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 ft=D(()=>{"use strict";l()});async function gt(t){let{issues:e,output:r,success:o}=(0,f.safeParse)(dr,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,f.safeParse)(pr,t);return o?r:e.json({EngineMalfunction:{}},500)}var f,dr,pr,yt=D(()=>{"use strict";l();f=require("valibot"),dr=(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))});pr=(0,f.looseObject)({id:(0,f.union)([(0,f.string)(),(0,f.number)()])})});var St={};_e(St,{accelerateRoute:()=>q});async function we(t){let{req:e}=t,r=pt(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 Pt,bt,I,q,lr,V,mr,fr,vt=D(()=>{"use strict";l();Pt=require("hono/http-exception"),bt=require("hono/tiny"),I=require("hono/validator");se();ct();Pe();dt();mt();ft();yt();q=new bt.Hono;q.post("/invalidate",(0,I.validator)("header",k),async t=>{let e=await it(t);return e instanceof Response?e:t.body(null)});lr="/:clientVersion/:schemaHash",V=q.basePath(lr);q.route("/",V);mr=["/graphql","/itx/:transactionId/graphql"];V.on("POST",[...mr],(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 gt(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"),d=t.get("protocol"),m=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${d}://localhost:${c}/${i}/${m}/itx/${a}`}})}catch(o){return Y(o,t)}});fr=[["/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 fr)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 Pt.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 Et={};_e(Et,{utilityRoute:()=>De});var wt,Dt,De,co,Tt=D(()=>{"use strict";l();wt=require("hono/tiny"),Dt=require("http-status-codes"),De=new wt.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)});co=De.get("/health",t=>t.json({name:t.get("serverState").name}))});var vr={};module.exports=Kt(vr);l();var Lt=require("timers/promises");l();se();l();var ze=require("pathe/utils");J();l();var $=require("get-port-please"),z=require("remeda"),de=51214,pe=51213,le=51215,W=65535,A=-1/0;async function ge(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:A,port:A,shadowDatabasePort:A},c=["port","databasePort","shadowDatabasePort"];for(let d of c){let m=await Zt({debug:e,portKey:d,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await er({debug:e,pickedPorts:i,portKey:d,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${d}": ${m}`),i[d]=m}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]??A;if(!Qe(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let d=c in o;return d||Object.values(i).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${d?"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 er(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s}=t,a=Math.max(de,pe,le)+1,i=[...Object.values(r),...Object.keys(n).map(Number),...Object.values(s||{})],c=Math.min(Math.max(a,...i)+100,W),d=(0,z.difference)((0,z.range)(a,c),i),m={port:pe,databasePort:de,shadowDatabasePort:le}[o];try{return await(0,$.getPort)({port:m in n||Object.values(r).includes(m)||Object.values(s||{}).includes(m)?void 0:m,ports:d})}catch(y){if(y instanceof Error&&y.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 y}}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,$.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 b={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},or=`postgres://${b.username}:${b.password}@localhost`,Xe=new URLSearchParams({sslmode:b.sslMode}),nr=new URLSearchParams({...Object.fromEntries(Xe.entries()),connection_limit:String(b.connectionLimit),connect_timeout:String(b.connectTimeout),max_idle_connection_lifetime:String(b.maxIdleConnectionLifetime),pool_timeout:String(b.poolTimeout),single_use_connections:"true",socket_timeout:String(b.socketTimeout)});async function he(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((c,d)=>{console.debug(`[${t}][${c}] ${d}`)});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:d}=c;console.debug(`[${t}] server listening on ${JSON.stringify(d)}`)}),i.addEventListener("connection",c=>{let{clientAddress:d,clientPort:m}=c.detail;console.debug(`[${t}] client connected from ${d}:${m}`)}),i.addEventListener("error",c=>{let{detail:d}=c;console.error(`[${t}] server error:`,d)}));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}`),{...b,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 ar({db:n,debug:o,destinationPath:i})},port:s,prismaORMConnectionString:We(s,nr),terminalCommand:`PGPASSWORD=${b.password} PGSSLMODE=${b.sslMode} psql -h localhost -p ${s} -U ${b.username} -d ${b.database}`}}function We(t,e){return`${or}:${t}/${b.database}?${e.toString()}`}async function Ye(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:b.database,dataDir:t,debug:e?5:void 0,extensions:await Ze(),relaxedDurability:!1,username:b.username})}async function sr(t,e){let{PGlite:r}=await import("@electric-sql/pglite");return await r.create({database:b.database,dataDir:"memory://",debug:e?5:void 0,extensions:await Ze(),relaxedDurability:!1,username:b.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)}async function ar(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 Rt=require("http"),Ot=require("util"),At=u(require("@prisma/get-platform"),1);ye();Pe();async function $t(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",d=>{if(typeof d=="object"&&"code"in d&&d.code==="EADDRINUSE")return s(new T(r));console.error("[Accelerate]",d)}),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(()=>(vt(),St)),Promise.resolve().then(()=>(Tt(),Et))]),i=new n,c=await At.default.getPlatformInfo();if(o&&console.debug("[Accelerate] platform info: %s",JSON.stringify(c)),o){let{logger:m}=await import("hono/logger");i.use("*",m((...y)=>console.log("[Accelerate]",...y)))}i.use("*",async(m,y)=>(m.set("db",e),m.set("debug",!!o),m.set("platform",c),m.set("port",t),m.set("protocol","http"),m.set("serverState",r),m.set("shadowDBPort",r.shadowDatabasePort),await y()));let d=new n;return d.route("/",s),d.route("/",a),i.route("/",d),i}l();var Mt=require("fs/promises"),C=require("pathe"),B=require("proper-lockfile"),Ae=require("std-env"),p=require("valibot");J();l();var hr=require("timers/promises"),_t=require("std-env");function kt(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,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)())}),Ct=(0,p.object)({url:xe}),Ee=(0,p.pipe)((0,p.number)(),(0,p.integer)(),(0,p.minValue)(1)),yr=(0,p.object)({database:It,http:Ct,ppg:Ct,shadowDatabase:It}),Pr=(0,p.object)({databasePort:Ee,exports:(0,p.optional)(yr),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:Ee,shadowDatabasePort:Ee,version:(0,p.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:d}=(0,p.safeParse)((0,p.pipe)((0,p.string)(),(0,p.parseJson)(),Pr),a);if(!d)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=>br(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 ge({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 ge({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,Mt.writeFile)(this.#a,`${JSON.stringify(this.#o,null,2)}
5
+ `,{encoding:"utf-8"})}};async function br(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:d}=i;if(o)return{...a,status:"unknown"};if(!kt(d,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${d}`),{...a,status:"not_running"};let m=N(n);try{if(!await(0,B.check)(m,{lockfilePath:(0,C.join)(m,".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:y}=c,{hc:S}=await import("hono/client"),x=await S(y.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 Ht(t){let e=await E.createExclusively(t),[r,o]=await Promise.all([he("database",e),he("shadow_database",e)]),n=await $t(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,d){let y=(await Promise.allSettled(d.map(S=>S.close()))).filter(S=>S.status==="rejected").map(S=>new Error(S.reason));try{await c.close()}catch(S){y.push(S)}if(y.length>0)throw new AggregateError(y,"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-Z3KIQH3D.js";import"./chunk-RBVZVBDC.js";import"./chunk-FZ7JBZR6.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-FPKS7HN2.js";import"./chunk-QWUDE25K.js";import"./chunk-6374E7DO.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 N=Object.create;var g=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var q=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var I=(e,t)=>{for(var o in t)g(e,o,{get:t[o],enumerable:!0})},T=(e,t,o,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of M(t))!F.call(e,c)&&c!==o&&g(e,c,{get:()=>t[c],enumerable:!(i=C(t,c))||i.enumerable});return e};var r=(e,t,o)=>(o=e!=null?N(q(e)):{},T(t||!e||!e.__esModule?g(o,"default",{value:e,enumerable:!0}):o,e)),K=e=>T(g({},"__esModule",{value:!0}),e);var Z={};I(Z,{dumpDB:()=>U,startDBServer:()=>Q});module.exports=K(Z);var k=require("pathe/utils");var y=require("fs"),l=require("fs/promises"),O=require("util"),x=require("zlib");var n=r(require("path"),1),v=r(require("os"),1),b=r(require("process"),1),p=v.default.homedir(),S=v.default.tmpdir(),{env:f}=b.default,H=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(S,e)}},W=e=>{let t=f.APPDATA||n.default.join(p,"AppData","Roaming"),o=f.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(S,e)}},V=e=>{let t=n.default.basename(p);return{data:n.default.join(f.XDG_DATA_HOME||n.default.join(p,".local","share"),e),config:n.default.join(f.XDG_CONFIG_HOME||n.default.join(p,".config"),e),cache:n.default.join(f.XDG_CACHE_HOME||n.default.join(p,".cache"),e),log:n.default.join(f.XDG_STATE_HOME||n.default.join(p,".local","state"),e),temp:n.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"?H(e):b.default.platform==="win32"?W(e):V(e)}var X=r(require("zeptomatch"),1),ne=D("prisma-dev"),se=(0,O.promisify)(x.unzip);async function _(e,t){await e.stream().pipeTo(y.WriteStream.toWeb((0,y.createWriteStream)(t,{encoding:"utf8"})))}var $=require("get-port-please"),A=require("remeda");var h=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"},J=`postgres://${a.username}:${a.password}@localhost`,R=new URLSearchParams({sslmode:a.sslMode}),z=new URLSearchParams({...Object.fromEntries(R.entries()),connection_limit:String(a.connectionLimit),connect_timeout:String(a.connectTimeout),max_idle_connection_lifetime:String(a.maxIdleConnectionLifetime),pool_timeout:String(a.poolTimeout),single_use_connections:"true",socket_timeout:String(a.socketTimeout)});async function Q(e,t){let o=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return E(e,t,{db:null,port:o,server:null});let{debug:i}=t,u=await(e==="shadow_database"?Y:L)(t.pgliteDataDirPath,i);i&&u.onNotification((s,m)=>{console.debug(`[${e}][${s}] ${m}`)});let{PGLiteSocketServer:P}=await import("@electric-sql/pglite-socket"),d=new P({db:u,debug:i,inspect:i,port:o});i&&(d.addEventListener("listening",s=>{let{detail:m}=s;console.debug(`[${e}] server listening on ${JSON.stringify(m)}`)}),d.addEventListener("connection",s=>{let{clientAddress:m,clientPort:G}=s.detail;console.debug(`[${e}] client connected from ${m}:${G}`)}),d.addEventListener("error",s=>{let{detail:m}=s;console.error(`[${e}] server error:`,m)}));try{await d.start()}catch(s){throw s instanceof Error&&"code"in s&&s.code==="EADDRINUSE"?new h(o):s}return E(e,t,{db:u,port:o,server:d})}function E(e,t,o){let{debug:i}=t,{db:c,port:u,server:P}=o||{};return i&&console.debug(`[${e}] server started on port ${u}`),{...a,close:async()=>{let d=[];try{await P?.stop(),i&&console.debug(`[${e}] server stopped on port ${u}`)}catch(s){console.error(`[${e}] server stop error`,s),d.push(s)}if(e==="database")try{await c?.syncToFs(),i&&console.debug(`[${e}] synced to filesystem`)}catch(s){console.error(`[${e}] sync error`,s),d.push(s)}try{await c?.close(),i&&console.debug(`[${e}] closed`)}catch(s){console.error(`[${e}] close error`,s),d.push(s)}if(d.length>0)throw new AggregateError(d,`Failed to close ${e} properly`)},connectionString:B(u,R),dump:async d=>{e==="shadow_database"||!c||await U({db:c,debug:i,destinationPath:d})},port:u,prismaORMConnectionString:B(u,z),terminalCommand:`PGPASSWORD=${a.password} PGSSLMODE=${a.sslMode} psql -h localhost -p ${u} -U ${a.username} -d ${a.database}`}}function B(e,t){return`${J}:${e}/${a.database}?${t.toString()}`}async function L(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 j(),relaxedDurability:!1,username:a.username})}async function Y(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 j(),relaxedDurability:!1,username:a.username})}async function j(){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)}async function U(e){let{dataDir:t,db:o,debug:i,destinationPath:c}=e,u=o||await L(t,i),{pgDump:P}=await import("@electric-sql/pglite-tools/pg_dump"),d=await P({args:["--schema-only","--no-owner"],fileName:c?(0,k.filename)(c):void 0,pg:await u.clone()});return c?(i&&console.debug(`[DB] Dumping database to ${c}`),await _(d,c)):(i&&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-QWUDE25K.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 jt=Object.create;var W=Object.defineProperty;var Mt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var Nt=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)W(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))!qt.call(t,n)&&n!==r&&W(t,n,{get:()=>e[n],enumerable:!(o=Mt(e,n))||o.enumerable});return t};var w=(t,e,r)=>(r=t!=null?jt(Nt(t)):{},$e(e||!t||!t.__esModule?W(r,"default",{value:t,enumerable:!0}):r,t)),Ft=t=>$e(W({},"__esModule",{value:!0}),t);var p=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 Gt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:o,success:n}=(0,f.safeParse)(Vt,e,{abortEarly:!0});return n?[null,o]:[r]}var f,_e,Vt,k,ce=D(()=>{"use strict";p();f=require("valibot"),_e=/^(postgres|postgresql):\/\//,Vt=(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)(_e)),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)(_e))}));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:R,port:x}=new URL(u),{port:q}=e.get("db"),{hostname:Bt,port:Ht}=new URL(g),Lt=e.get("shadowDBPort");if(R!=="localhost"||Number(x)!==q||Bt!=="localhost"||Number(Ht)!==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}`),z.default.platform==="darwin"?Kt(t):z.default.platform==="win32"?Qt(t):Jt(t)}var h,ue,z,O,de,B,Kt,Qt,Jt,Ie=D(()=>{"use strict";p();h=w(require("path"),1),ue=w(require("os"),1),z=w(require("process"),1),O=ue.default.homedir(),de=ue.default.tmpdir(),{env:B}=z.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=B.APPDATA||h.default.join(O,"AppData","Roaming"),r=B.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(B.XDG_DATA_HOME||h.default.join(O,".local","share"),t),config:h.default.join(B.XDG_CONFIG_HOME||h.default.join(O,".config"),t),cache:h.default.join(B.XDG_CACHE_HOME||h.default.join(O,".cache"),t),log:h.default.join(B.XDG_STATE_HOME||h.default.join(O,".local","state"),t),temp:h.default.join(de,e,t)}}});function je(t,e){return`${Le.cache}/engine/${t}/${e}`}function F(t){return`${Le.data}/${t}`}async function Me(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 Ne(t,e){await t.stream().pipeTo(X.WriteStream.toWeb((0,X.createWriteStream)(e,{encoding:"utf-8"})))}function pe(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function qe(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 Ve(t,e){try{return(await(0,v.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,He.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(pe(r))return[];throw r}}var X,v,Ce,Be,He,Le,Wt,Y=D(()=>{"use strict";p();X=require("fs"),v=require("fs/promises"),Ce=require("util"),Be=require("zlib");Ie();He=w(require("zeptomatch"),1),Le=le("prisma-dev"),Wt=(0,Ce.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 ge=D(()=>{"use strict";p()});function re(t,e){return console.error(t),t instanceof V?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:t.message}}}},500):t instanceof M?e.text(t.responseBody,t.statusCode):e.body(null,500)}var Ze,et,tt,rt,ot,nt,nr,sr,Ye,U,V,M,ye=D(()=>{"use strict";p();Ze=require("child_process"),et=require("events"),tt=require("fs/promises"),rt=require("path"),ot=require("timers/promises");ge();nt=require("std-env");Y();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:nr,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:sr,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Ye}=nt.process.env),U=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 M.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 M.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(q=>q.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:R,port:x}=b;if(R==null||x==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://${R}:${x}`})},c=l=>{this.#t=null,r(new V(String(l))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(l,g)=>{this.#t=null,r(new V(`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 Me(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 M.fromResponse(a);try{return await a.json()}catch{return{}}}};V=class extends Error{name="EngineStartError"},M=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 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,ct=D(()=>{"use strict";p();_=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 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=be.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 Se(i);return{base64Override:be.Buffer.from(i,"utf8").toString("base64"),overrideHash:c}}var be,ne,se,lt=D(()=>{"use strict";p();be=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:()=>G});async function we(t){let{req:e}=t,r=ut(t);if(r instanceof Response)return r;let{base64Override:o,overrideHash:n}=r.schemas;return await U.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,G,ur,K,dr,lr,bt=D(()=>{"use strict";p();gt=require("hono/http-exception"),yt=require("hono/tiny"),I=require("hono/validator");ce();at();ye();ct();lt();pt();ht();G=new yt.Hono;G.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",K=G.basePath(ur);G.route("/",K);dr=["/graphql","/itx/:transactionId/graphql"];K.on("POST",[...dr],(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,{...ae(t),"X-transaction-id":n});return t.text(s)}catch(r){return re(r,t)}});K.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,ae(t));return t.json(a)}catch(r){return re(r,t)}});K.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 Se(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)});K.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 we(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)G.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:()=>ve});var St,wt,ve,so,Dt=D(()=>{"use strict";p();St=require("hono/tiny"),wt=require("http-status-codes"),ve=new St.Hono;ve.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=ve.get("/health",t=>t.json({name:t.get("serverState").name}))});var Pr={};ie(Pr,{DEFAULT_DATABASE_PORT:()=>H,DEFAULT_SERVER_PORT:()=>L,DEFAULT_SHADOW_DATABASE_PORT:()=>j,PortNotAvailableError:()=>E,ServerAlreadyRunningError:()=>J,startPrismaDevServer:()=>Ct,unstable_startServer:()=>yr});module.exports=Ft(Pr);p();ce();p();var We=require("pathe/utils");Y();p();var $=require("get-port-please"),ee=require("remeda"),H=51214,L=51213,j=51215,Z=65535,A=-1/0;async function Ke(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(Ge(a))return await Zt({debug:e,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:o,requestedPort:a}),a;let c=n?.[r]??A;if(!Ge(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(H,L,j)+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:L,databasePort:H,shadowDatabasePort:j}[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 Ge(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 he(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 Ne(i,n)):(o&&console.debug("[DB] Dumping database to memory"),await i.text())}p();var Tt=require("http"),Rt=require("util"),xt=w(require("@prisma/get-platform"),1);ge();ye();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,Rt.promisify)(e.close.bind(e))(),U.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 xt.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"),N=require("proper-lockfile"),Oe=require("std-env"),d=require("valibot");Y();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 Te=(0,d.pipe)((0,d.string)(),(0,d.url)()),_t=(0,d.object)({connectionString:Te,prismaORMConnectionString:(0,d.optional)(Te),terminalCommand:(0,d.optional)((0,d.string)())}),kt=(0,d.object)({url:Te}),De=(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:De,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:De,shadowDatabasePort:De,version:(0,d.literal)("1")}),Ae=Symbol("initialize"),Ee="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??Ee,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Oe.process.pid,this._port=e.port??A,this._shadowDatabasePort=e.shadowDatabasePort??A}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new Q(e):new Re(e);return await r[Ae](),r}static async fromServerDump(e){let{debug:r,name:o=Ee}=e??{},n=F(o),s=Q.getServerDumpPath(n),a=await qe(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 Q({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)(F(Ee),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let s=await Ve(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??H,persistenceMode:"stateless",port:e?.port??L,shadowDatabasePort:e?.shadowDatabasePort??j})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Ae](){}async close(){}async writeServerDump(){}},Q=class t extends T{#r;#e;#t;#s;#a;#n;#o;constructor(e){super({...e,persistenceMode:"stateful"}),this.#n=!1,this.#e=F(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,N.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 Ke({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.#n)try{await(0,N.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:Oe.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=F(n);try{if(!await(0,N.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(q){r&&console.error(`[State] server state for "${n}" failed to check lock:`,q)}if(!c)return{...a,status:"starting_up"};let{http:g}=c,{hc:b}=await import("hono/client"),R=await b(g.url).health.$get();if(!R.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(R)}`),{...a,status:"not_running"};let x=await R.json();return x.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(x)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(x)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${n}":`,i),{...a,status:"error"}}}var xe=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},J=class extends xe{#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([he("database",e),he("shadow_database",e)]),n=await Ot(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,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 Mt=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 u=(t,e,r)=>(r=t!=null?Mt(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 Ie(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,h.safeParse)(Gt,e,{abortEarly:!0});return n?[null,o]:[r]}var h,ke,Gt,k,ce=D(()=>{"use strict";m();h=require("valibot"),ke=/^(postgres|postgresql):\/\//,Gt=(0,h.pipe)((0,h.string)(),(0,h.parseJson)(),(0,h.object)({databaseUrl:(0,h.pipe)((0,h.string)(),(0,h.url)(),(0,h.regex)(ke)),name:(0,h.optional)((0,h.pipe)((0,h.string)(),(0,h.minLength)(1))),shadowDatabaseUrl:(0,h.pipe)((0,h.string)(),(0,h.url)(),(0,h.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]=Kt(s);if(i)throw new o(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:d,name:l,shadowDatabaseUrl:y}=c,{name:w}=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 "${w}" server's output for the updated \`DATABASE_URL\` value.`});if(l!==w)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${e.get("port")} is named "${w}", but the API Key is for "${l}"`});let{hostname:x,port:R}=new URL(d),{port:M}=e.get("db"),{hostname:Bt,port:Lt}=new URL(y),jt=e.get("shadowDBPort");if(x!=="localhost"||Number(R)!==M||Bt!=="localhost"||Number(Lt)!==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 pe(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 g,ue,Q,O,de,H,Qt,Jt,Wt,Ce=D(()=>{"use strict";m();g=u(require("path"),1),ue=u(require("os"),1),Q=u(require("process"),1),O=ue.default.homedir(),de=ue.default.tmpdir(),{env:H}=Q.default,Qt=t=>{let e=g.default.join(O,"Library");return{data:g.default.join(e,"Application Support",t),config:g.default.join(e,"Preferences",t),cache:g.default.join(e,"Caches",t),log:g.default.join(e,"Logs",t),temp:g.default.join(de,t)}},Jt=t=>{let e=H.APPDATA||g.default.join(O,"AppData","Roaming"),r=H.LOCALAPPDATA||g.default.join(O,"AppData","Local");return{data:g.default.join(r,t,"Data"),config:g.default.join(e,t,"Config"),cache:g.default.join(r,t,"Cache"),log:g.default.join(r,t,"Log"),temp:g.default.join(de,t)}},Wt=t=>{let e=g.default.basename(O);return{data:g.default.join(H.XDG_DATA_HOME||g.default.join(O,".local","share"),t),config:g.default.join(H.XDG_CONFIG_HOME||g.default.join(O,".config"),t),cache:g.default.join(H.XDG_CACHE_HOME||g.default.join(O,".cache"),t),log:g.default.join(H.XDG_STATE_HOME||g.default.join(O,".local","state"),t),temp:g.default.join(de,e,t)}}});function Me(t,e){return`${je.cache}/engine/${t}/${e}`}function N(t){return`${je.data}/${t}`}async function Ne(t){try{return await(0,v.access)(t,v.constants.F_OK),!0}catch(e){if(le(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 le(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(le(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(le(r))return[];throw r}}var J,v,He,Be,Le,je,zt,W=D(()=>{"use strict";m();J=require("fs"),v=require("fs/promises"),He=require("util"),Be=require("zlib");Ce();Le=u(require("zeptomatch"),1),je=pe("prisma-dev"),zt=(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";m()});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 et,tt,rt,ot,nt,st,sr,ar,Ze,L,U,B,Pe=D(()=>{"use strict";m();et=require("child_process"),tt=require("events"),rt=require("fs/promises"),ot=require("path"),nt=require("timers/promises");ye();st=require("std-env");W();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:sr,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:ar,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 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=ar||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=l=>{let y=l.split(`
2
+ `).find(M=>M.includes("Started query engine http server"));if(!y)return;a.stdout.removeListener("data",i);let{fields:w}=JSON.parse(y);if(w==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${l}`));let{ip:x,port:R}=w;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",d),a.kill()};a.once("error",c);let d=(l,y)=>{this.#t=null,r(new U(`Query Engine exited with code ${l} and signal ${y}`))};return a.once("exit",d),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=Me(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),(sr==="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 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 at(t){let{output:e,success:r}=(0,S.safeParse)(ir,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var S,ir,it=D(()=>{"use strict";m();S=require("valibot"),ir=(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 _,oe,be,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 pt(t,e,r){let o=we.Buffer.from(t,"base64").toString("utf8"),n=(0,ne.getSchema)(o),s=n.list.find(d=>d.type==="datasource");if(!s)throw new Error("No datasource block found in schema.");let a=s.assignments.find(d=>d.type==="assignment"&&d.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,lt=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 ft(t){let{issues:e,output:r,success:o}=(0,f.safeParse)(cr,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,f.safeParse)(ur,t);return o?r:e.json({EngineMalfunction:{}},500)}var f,cr,ur,gt=D(()=>{"use strict";m();f=require("valibot"),cr=(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))});ur=(0,f.looseObject)({id:(0,f.union)([(0,f.string)(),(0,f.number)()])})});var bt={};ie(bt,{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 yt,Pt,I,q,dr,V,pr,lr,wt=D(()=>{"use strict";m();yt=require("hono/http-exception"),Pt=require("hono/tiny"),I=require("hono/validator");ce();it();Pe();ut();lt();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)});dr="/:clientVersion/:schemaHash",V=q.basePath(dr);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 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 Se(r))return t.text("Schema hash mismatch",400);let s=await pt(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 ft(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=ht(n,t);if(s instanceof Response)return s;let{id:a}=s,i=e.param("clientVersion"),c=t.get("port"),d=t.get("protocol"),l=e.param("schemaHash");return t.json({...n,"data-proxy":{endpoint:`${d}://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 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 ${oe.version}.`});return await(await ct(r)).fetch(r.req.raw)})});var Dt={};ie(Dt,{utilityRoute:()=>De});var St,vt,De,ao,Et=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)});ao=De.get("/health",t=>t.json({name:t.get("serverState").name}))});var br={};ie(br,{DEFAULT_DATABASE_PORT:()=>X,DEFAULT_SERVER_PORT:()=>Y,DEFAULT_SHADOW_DATABASE_PORT:()=>Z,PortNotAvailableError:()=>E,ServerAlreadyRunningError:()=>G,startPrismaDevServer:()=>Ht,unstable_startServer:()=>Pr});module.exports=Ft(br);m();ce();m();var We=require("pathe/utils");W();m();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}=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:A,port:A,shadowDatabasePort:A},c=["port","databasePort","shadowDatabasePort"];for(let d of c){let l=await Xt({debug:e,portKey:d,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a,requestedPorts:o})??await Yt({debug:e,pickedPorts:i,portKey:d,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:a});e&&console.debug(`Got port for "${d}": ${l}`),i[d]=l}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]??A;if(!Ke(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let d=c in o;return d||Object.values(i).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${d?"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 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),d=(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:d})}catch(y){if(y instanceof Error&&y.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 y}}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 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 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((c,d)=>{console.debug(`[${t}][${c}] ${d}`)});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:d}=c;console.debug(`[${t}] server listening on ${JSON.stringify(d)}`)}),i.addEventListener("connection",c=>{let{clientAddress:d,clientPort:l}=c.detail;console.debug(`[${t}] client connected from ${d}:${l}`)}),i.addEventListener("error",c=>{let{detail:d}=c;console.error(`[${t}] server error:`,d)}));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}`),{...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 nr({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)}async function nr(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=u(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 mr(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",d=>{if(typeof d=="object"&&"code"in d&&d.code==="EADDRINUSE")return s(new E(r));console.error("[Accelerate]",d)}),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 mr(t,e,r){let{debug:o}=r,[{Hono:n},{accelerateRoute:s},{utilityRoute:a}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(wt(),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:l}=await import("hono/logger");i.use("*",l((...y)=>console.log("[Accelerate]",...y)))}i.use("*",async(l,y)=>(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 y()));let d=new n;return d.route("/",s),d.route("/",a),i.route("/",d),i}m();var Ct=require("fs/promises"),C=require("pathe"),j=require("proper-lockfile"),Ae=require("std-env"),p=require("valibot");W();m();var fr=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,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)())}),It=(0,p.object)({url:xe}),Ee=(0,p.pipe)((0,p.number)(),(0,p.integer)(),(0,p.minValue)(1)),hr=(0,p.object)({database:kt,http:It,ppg:It,shadowDatabase:kt}),gr=(0,p.object)({databasePort:Ee,exports:(0,p.optional)(hr),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:Ee,shadowDatabasePort:Ee,version:(0,p.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:d}=(0,p.safeParse)((0,p.pipe)((0,p.string)(),(0,p.parseJson)(),gr),a);if(!d)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=>yr(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,j.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,j.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 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 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:d}=i;if(o)return{...a,status:"unknown"};if(!_t(d,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${d}`),{...a,status:"not_running"};let l=N(n);try{if(!await(0,j.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(M){r&&console.error(`[State] server state for "${n}" failed to check lock:`,M)}if(!c)return{...a,status:"starting_up"};let{http:y}=c,{hc:w}=await import("hono/client"),x=await w(y.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 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: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,d){let y=(await Promise.allSettled(d.map(w=>w.close()))).filter(w=>w.status==="rejected").map(w=>new Error(w.reason));try{await c.close()}catch(w){y.push(w)}if(y.length>0)throw new AggregateError(y,"Failed to close some servers")}}async function Pr(t){return await Ht(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-Z3KIQH3D.js";import"./chunk-RBVZVBDC.js";import{g as e}from"./chunk-FZ7JBZR6.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-FPKS7HN2.js";import"./chunk-QWUDE25K.js";import{g as e}from"./chunk-6374E7DO.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 k=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var we=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty;var xe=(t,e)=>{for(var r in e)k(t,r,{get:e[r],enumerable:!0})},Z=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Se(e))!De.call(t,o)&&o!==r&&k(t,o,{get:()=>e[o],enumerable:!(n=ve(e,o))||n.enumerable});return t};var D=(t,e,r)=>(r=t!=null?ye(we(t)):{},Z(e||!t||!t.__esModule?k(r,"default",{value:t,enumerable:!0}):r,t)),Oe=t=>Z(k({},"__esModule",{value:!0}),t);var Be={};xe(Be,{ServerAlreadyRunningError:()=>U,ServerState:()=>h,ServerStateAlreadyExistsError:()=>L,deleteServer:()=>Ue,getServerStatus:()=>Y,isServerRunning:()=>me,killServer:()=>Pe});module.exports=Oe(Be);var he=require("fs/promises"),g=require("pathe"),S=require("proper-lockfile"),X=require("std-env"),a=require("valibot");var Q=require("fs"),l=require("fs/promises"),ee=require("util"),te=require("zlib");var d=D(require("path"),1),N=D(require("os"),1),_=D(require("process"),1),m=N.default.homedir(),F=N.default.tmpdir(),{env:y}=_.default,ke=t=>{let e=d.default.join(m,"Library");return{data:d.default.join(e,"Application Support",t),config:d.default.join(e,"Preferences",t),cache:d.default.join(e,"Caches",t),log:d.default.join(e,"Logs",t),temp:d.default.join(F,t)}},_e=t=>{let e=y.APPDATA||d.default.join(m,"AppData","Roaming"),r=y.LOCALAPPDATA||d.default.join(m,"AppData","Local");return{data:d.default.join(r,t,"Data"),config:d.default.join(e,t,"Config"),cache:d.default.join(r,t,"Cache"),log:d.default.join(r,t,"Log"),temp:d.default.join(F,t)}},$e=t=>{let e=d.default.basename(m);return{data:d.default.join(y.XDG_DATA_HOME||d.default.join(m,".local","share"),t),config:d.default.join(y.XDG_CONFIG_HOME||d.default.join(m,".config"),t),cache:d.default.join(y.XDG_CACHE_HOME||d.default.join(m,".cache"),t),log:d.default.join(y.XDG_STATE_HOME||d.default.join(m,".local","state"),t),temp:d.default.join(F,e,t)}};function V(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),_.default.platform==="darwin"?ke(t):_.default.platform==="win32"?_e(t):$e(t)}var re=D(require("zeptomatch"),1),Te=V("prisma-dev"),qe=(0,ee.promisify)(te.unzip);function v(t){return`${Te.data}/${t}`}function oe(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function se(t){try{return await(0,l.readFile)(t,{encoding:"utf-8"})}catch(e){if(oe(e))return null;throw e}}async function ae(t){await(0,l.mkdir)(t,{recursive:!0})}async function ne(t,e){try{return(await(0,l.readdir)(t,{withFileTypes:!0})).reduce((n,o)=>(o.isDirectory()&&!o.name.startsWith(".")&&(!e||(0,re.default)(e,o.name))&&n.push(o.name),n),[])}catch(r){if(oe(r))return[];throw r}}async function ie(t){await(0,l.rm)(t,{force:!0,recursive:!0})}var ce=require("timers/promises"),x=require("std-env");function q(t,e){if(t==null)return!1;try{return x.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}async function ue(t,e){if(!x.process.kill)return!1;try{x.process.kill(t,"SIGTERM")}catch(n){return e&&console.error(`Error killing process with PID ${t}:`,n),!1}let r=0;do{if(!q(t,e))return!0;await(0,ce.setTimeout)(100)}while(++r<50);try{return x.process.kill(t,"SIGKILL")}catch(n){return e&&console.error(`Error forcefully killing process with PID ${t}:`,n),!1}}var b=require("get-port-please"),M=require("remeda"),E=51214,A=51213,R=51215,T=65535,P=-1/0;async function pe(t){let{debug:e,name:r,requestedPorts:n,servers:o}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:i}=Re(r,o);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(i)}`));let c={databasePort:P,port:P,shadowDatabasePort:P},u=["port","databasePort","shadowDatabasePort"];for(let p of u){let f=await Ee({debug:e,portKey:p,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:i,requestedPorts:n})??await Ae({debug:e,pickedPorts:c,portKey:p,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:i});e&&console.debug(`Got port for "${p}": ${f}`),c[p]=f}return e&&console.debug(`Picked ports: ${JSON.stringify(c)}`),c}async function Ee(t){let{debug:e,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:o,requestedPorts:s}=t,{[r]:i,...c}=s;if(de(i))return await je({debug:e,otherRequestedPorts:c,portKey:r,portsUsedByOtherServers:n,requestedPort:i}),i;let u=o?.[r]??P;if(!de(u))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let p=u in n;return p||Object.values(c).includes(u)?(e&&console.debug(`Port ${u} that was used last time for this server, ${p?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,b.checkPort)(u)===!1?(e&&console.debug(`Port ${u}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${u} for "${r}" as it was used last time and is available.`),u)}async function Ae(t){let{debug:e,pickedPorts:r,portKey:n,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:s}=t,i=Math.max(E,A,R)+1,c=[...Object.values(r),...Object.keys(o).map(Number),...Object.values(s||{})],u=Math.min(Math.max(i,...c)+100,T),p=(0,M.difference)((0,M.range)(i,u),c),f={port:A,databasePort:E,shadowDatabasePort:R}[n];try{return await(0,b.getPort)({port:f in o||Object.values(r).includes(f)||Object.values(s||{}).includes(f)?void 0:f,ports:p})}catch(w){if(w instanceof Error&&w.name==="GetPortError"&&u+1<=T)return e&&console.debug(`Expanding port lookup to range [${u+1}, ${T}].`),await(0,b.getPort)({portRange:[u+1,T]});throw w}}function de(t){return t>=0}function Re(t,e){let r={},n;for(let o of e){let{databasePort:s,port:i,shadowDatabasePort:c}=o;if(o.name===t){n={databasePort:s,port:i,shadowDatabasePort:c};continue}r[s]=!0,r[i]=!0,r[c]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}async function je(t){let{debug:e,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:o,requestedPort:s}=t;if(s in o)throw e&&console.error(`Port ${s} was requested for "${n}", but is already used by another server.`),new K(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${n}", but also for another key.`),new C(s);if((0,b.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${n}", but is unsafe.`),new j(s);if(await(0,b.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${n}", but is not available.`),new j(s)}var j=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},C=class extends Error{constructor(r){super(`Port number \`${r}\` was requested twice. Please choose a different port for each service.`);this.port=r}name="PortRequestedTwiceError"},K=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"};var J=(0,a.pipe)((0,a.string)(),(0,a.url)()),le=(0,a.object)({connectionString:J,prismaORMConnectionString:(0,a.optional)(J),terminalCommand:(0,a.optional)((0,a.string)())}),fe=(0,a.object)({url:J}),G=(0,a.pipe)((0,a.number)(),(0,a.integer)(),(0,a.minValue)(1)),Me=(0,a.object)({database:le,http:fe,ppg:fe,shadowDatabase:le}),Le=(0,a.object)({databasePort:G,exports:(0,a.optional)(Me),name:(0,a.pipe)((0,a.string)(),(0,a.minLength)(1)),pid:(0,a.optional)((0,a.pipe)((0,a.number)(),(0,a.integer)(),(0,a.minValue)(0))),port:G,shadowDatabasePort:G,version:(0,a.literal)("1")}),z=Symbol("initialize"),H="default",h=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??P,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??H,this.persistenceMode=e.persistenceMode,this.pid=e.pid??X.process.pid,this._port=e.port??P,this._shadowDatabasePort=e.shadowDatabasePort??P}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new O(e):new W(e);return await r[z](),r}static async fromServerDump(e){let{debug:r,name:n=H}=e??{},o=v(n),s=O.getServerDumpPath(o),i=await se(s);if(i==null)return r&&console.debug(`[State] No server dump file found at: ${s}`),null;r&&(console.debug(`[State] server dump file found at "${s}":`),console.debug(i));let{issues:c,output:u,success:p}=(0,a.safeParse)((0,a.pipe)((0,a.string)(),(0,a.parseJson)(),Le),i);if(!p)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
2
- ${JSON.stringify(c,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new O({databasePort:u.databasePort,debug:r,dryRun:!1,name:n,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r,globs:n}=e??{},o=(0,g.join)(v(H),"..");r&&console.debug(`[State] scanning for server states in: ${o}`);let s=await ne(o,n);return r&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(i=>Y(i,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},W=class extends h{constructor(e){super({...e,databasePort:e?.databasePort??E,persistenceMode:"stateless",port:e?.port??A,shadowDatabasePort:e?.shadowDatabasePort??R})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[z](){}async close(){}async writeServerDump(){}},O=class t extends h{#t;#e;#o;#a;#n;#s;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#s=!1,this.#e=v(this.name),this.#t=(0,g.join)(this.#e,"db_dump.bak"),this.#o=(0,g.join)(this.#e,".lock"),this.#a=(0,g.join)(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#n=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,g.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#a}async[z](){await ae(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,S.lock)(this.#e,{lockfilePath:this.#o}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await h.scan({debug:this.debug,onlyMetadata:!0}),r=await pe({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new U(this):e}}async close(){if(!this.#s)try{await(0,S.unlock)(this.#e,{lockfilePath:this.#o}),this.#s=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:X.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,he.writeFile)(this.#n,`${JSON.stringify(this.#r,null,2)}
3
- `,{encoding:"utf-8"})}};async function Ue(t,e){await Pe(t,e);let r=v(typeof t=="string"?t:t.name);await ie(r)}async function Y(t,e){let{debug:r,onlyMetadata:n}=e||{},o=typeof t=="string"?t:t.name,s=typeof t!="string"?t:void 0,i={databasePort:s?.databasePort??-1,exports:s?.exports,name:o,pid:s?.pid,port:s?.port??-1,shadowDatabasePort:s?.shadowDatabasePort??-1,version:"1"};try{let c=s||await h.fromServerDump({debug:r,name:o});if(!c)return r&&console.debug(`[State] no server state found for name: ${o}`),{...i,status:"no_such_server"};i.databasePort=c.databasePort,i.exports=c.exports,i.pid=c.pid,i.port=c.port,i.shadowDatabasePort=c.shadowDatabasePort;let{exports:u,pid:p}=c;if(n)return{...i,status:"unknown"};if(!q(p,r))return r&&console.debug(`[State] server state for "${o}" has no running process with PID: ${p}`),{...i,status:"not_running"};let f=v(o);try{if(!await(0,S.check)(f,{lockfilePath:(0,g.join)(f,".lock")}))return r&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...i,status:"starting_up"}}catch(ge){r&&console.error(`[State] server state for "${o}" failed to check lock:`,ge)}if(!u)return{...i,status:"starting_up"};let{http:w}=u,{hc:be}=await import("hono/client"),B=await be(w.url).health.$get();if(!B.ok)return r&&console.debug(`[State] server state for "${o}" is not live: ${JSON.stringify(B)}`),{...i,status:"not_running"};let I=await B.json();return I.name!==t?(r&&console.debug(`[State] server state for "${o}" has mismatched health response: ${JSON.stringify(I)}`),{...i,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(I)}`),{...i,status:"running"})}catch(c){return r&&console.error(`[State] failed to get server status for "${o}":`,c),{...i,status:"error"}}}function me(t){let{status:e}=t;return e==="running"||e==="starting_up"}async function Pe(t,e){let{pid:r,...n}=typeof t=="string"?await Y(t,{debug:e}):t;if(!me(n))return!1;let o=await h.fromServerDump({debug:e,name:n.name});if(r==null){e&&console.debug(`[State] No PID found for server "${n.name}" to kill.`);try{await o?.close()}catch{}return!1}let s=await ue(r,e);try{await o?.close()}catch{}return s}var L=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},U=class extends L{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return h.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError,deleteServer,getServerStatus,isServerRunning,killServer});
1
+ "use strict";var ye=Object.create;var k=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)k(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&&k(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?k(r,"default",{value:t,enumerable:!0}):r,t)),Oe=t=>z(k({},"__esModule",{value:!0}),t);var Ne={};xe(Ne,{ServerAlreadyRunningError:()=>j,ServerState:()=>h,ServerStateAlreadyExistsError:()=>R,deleteServer:()=>Le,getServerStatus:()=>X,isServerRunning:()=>me,killServer:()=>Pe});module.exports=Oe(Ne);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),L=D(require("os"),1),$=D(require("process"),1),m=L.default.homedir(),N=L.default.tmpdir(),{env:y}=$.default,ke=t=>{let e=d.default.join(m,"Library");return{data:d.default.join(e,"Application Support",t),config:d.default.join(e,"Preferences",t),cache:d.default.join(e,"Caches",t),log:d.default.join(e,"Logs",t),temp:d.default.join(N,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(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}`),$.default.platform==="darwin"?ke(t):$.default.platform==="win32"?$e(t):_e(t)}var ee=D(require("zeptomatch"),1),Te=U("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 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 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(!B(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}),Ie=(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 O(e):new H(e);return await r[W](),r}static async fromServerDump(e){let{debug:r,name:n=K}=e??{},s=v(n),o=O.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)(),Ie),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 O({databasePort:u.databasePort,debug:r,dryRun:!1,name:n,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r,globs:n}=e??{},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(){}},O=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 Le(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(!B(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 I=await M.json();return I.name!==t?(r&&console.debug(`[State] server state for "${s}" has mismatched health response: ${JSON.stringify(I)}`),{...i,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(I)}`),{...i,status:"running"})}catch(c){return r&&console.error(`[State] failed to get server status for "${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});
package/dist/state.js CHANGED
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g}from"./chunk-FZ7JBZR6.js";import"./chunk-LMPFMHCB.js";import"./chunk-EPFUMVT3.js";export{g as ServerAlreadyRunningError,a as ServerState,f as ServerStateAlreadyExistsError,b as deleteServer,c as getServerStatus,d as isServerRunning,e as killServer};
1
+ import{a,b,c,d,e,f,g}from"./chunk-6374E7DO.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.16.1",
3
+ "version": "0.18.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,3 +0,0 @@
1
- import{a as V,b as N,c as L,d as f,e as F}from"./chunk-LMPFMHCB.js";import{b as d,f as O,g as I,h as A,i as T}from"./chunk-EPFUMVT3.js";import{writeFile as X}from"fs/promises";import{join as l}from"pathe";import{check as ee,lock as te,unlock as re}from"proper-lockfile";import{process as B}from"std-env";import{integer as C,literal as se,minLength as ae,minValue as H,number as K,object as P,optional as g,parseJson as oe,pipe as h,safeParse as ne,string as v,url as ie}from"valibot";import{setTimeout as Q}from"timers/promises";import{process as b}from"std-env";function y(t,e){if(t==null)return!1;try{return b.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}async function J(t,e){if(!b.kill)return!1;try{b.kill(t,"SIGTERM")}catch(n){return e&&console.error(`Error killing process with PID ${t}:`,n),!1}let r=0;do{if(!y(t,e))return!0;await Q(100)}while(++r<50);try{return b.kill(t,"SIGKILL")}catch(n){return e&&console.error(`Error forcefully killing process with PID ${t}:`,n),!1}}var _=h(v(),ie()),U=P({connectionString:_,prismaORMConnectionString:g(_),terminalCommand:g(v())}),j=P({url:_}),w=h(K(),C(),H(1)),ue=P({database:U,http:j,ppg:j,shadowDatabase:U}),ce=P({databasePort:w,exports:g(ue),name:h(v(),ae(1)),pid:g(h(K(),C(),H(0))),port:w,shadowDatabasePort:w,version:se("1")}),R=Symbol("initialize"),x="default",c=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??f,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??x,this.persistenceMode=e.persistenceMode,this.pid=e.pid??B.pid,this._port=e.port??f,this._shadowDatabasePort=e.shadowDatabasePort??f}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new p(e):new k(e);return await r[R](),r}static async fromServerDump(e){let{debug:r,name:n=x}=e??{},a=d(n),o=p.getServerDumpPath(a),s=await O(o);if(s==null)return r&&console.debug(`[State] No server dump file found at: ${o}`),null;r&&(console.debug(`[State] server dump file found at "${o}":`),console.debug(s));let{issues:i,output:u,success:m}=ne(h(v(),oe(),ce),s);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${o}":
2
- ${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new p({databasePort:u.databasePort,debug:r,dryRun:!1,name:n,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r,globs:n}=e??{},a=l(d(x),"..");r&&console.debug(`[State] scanning for server states in: ${a}`);let o=await A(a,n);return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(s=>q(s,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},k=class extends c{constructor(e){super({...e,databasePort:e?.databasePort??V,persistenceMode:"stateless",port:e?.port??N,shadowDatabasePort:e?.shadowDatabasePort??L})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[R](){}async close(){}async writeServerDump(){}},p=class t extends c{#t;#e;#s;#o;#n;#a;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#a=!1,this.#e=d(this.name),this.#t=l(this.#e,"db_dump.bak"),this.#s=l(this.#e,".lock"),this.#o=l(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#n=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return l(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[R](){await I(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await te(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await c.scan({debug:this.debug,onlyMetadata:!0}),r=await F({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new E(this):e}}async close(){if(!this.#a)try{await re(this.#e,{lockfilePath:this.#s}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:B.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await X(this.#n,`${JSON.stringify(this.#r,null,2)}
3
- `,{encoding:"utf-8"})}};async function xe(t,e){await le(t,e);let r=d(typeof t=="string"?t:t.name);await T(r)}async function q(t,e){let{debug:r,onlyMetadata:n}=e||{},a=typeof t=="string"?t:t.name,o=typeof t!="string"?t:void 0,s={databasePort:o?.databasePort??-1,exports:o?.exports,name:a,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let i=o||await c.fromServerDump({debug:r,name:a});if(!i)return r&&console.debug(`[State] no server state found for name: ${a}`),{...s,status:"no_such_server"};s.databasePort=i.databasePort,s.exports=i.exports,s.pid=i.pid,s.port=i.port,s.shadowDatabasePort=i.shadowDatabasePort;let{exports:u,pid:m}=i;if(n)return{...s,status:"unknown"};if(!y(m,r))return r&&console.debug(`[State] server state for "${a}" has no running process with PID: ${m}`),{...s,status:"not_running"};let M=d(a);try{if(!await ee(M,{lockfilePath:l(M,".lock")}))return r&&console.debug(`[State] server state for "${a}" is not locked, indicating it is not running.`),{...s,status:"starting_up"}}catch(Z){r&&console.error(`[State] server state for "${a}" failed to check lock:`,Z)}if(!u)return{...s,status:"starting_up"};let{http:G}=u,{hc:Y}=await import("hono/client"),S=await Y(G.url).health.$get();if(!S.ok)return r&&console.debug(`[State] server state for "${a}" is not live: ${JSON.stringify(S)}`),{...s,status:"not_running"};let D=await S.json();return D.name!==t?(r&&console.debug(`[State] server state for "${a}" has mismatched health response: ${JSON.stringify(D)}`),{...s,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(D)}`),{...s,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${a}":`,i),{...s,status:"error"}}}function de(t){let{status:e}=t;return e==="running"||e==="starting_up"}async function le(t,e){let{pid:r,...n}=typeof t=="string"?await q(t,{debug:e}):t;if(!de(n))return!1;let a=await c.fromServerDump({debug:e,name:n.name});if(r==null){e&&console.debug(`[State] No PID found for server "${n.name}" to kill.`);try{await a?.close()}catch{}return!1}let o=await J(r,e);try{await a?.close()}catch{}return o}var $=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},E=class extends ${#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return c.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{c as a,xe as b,q as c,de as d,le as e,$ as f,E as g};
@@ -1 +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};