@prisma/dev 0.0.0-dev.202607271058 → 0.0.0-dev.202607271405

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -65,6 +65,57 @@ declare class PortNotAvailableError extends Error {
65
65
  constructor(port: number);
66
66
  }
67
67
 
68
+ interface PrismaDevConnectionStrings {
69
+ /**
70
+ * Direct TCP connection string for the main database.
71
+ */
72
+ readonly databaseUrl: string;
73
+ /**
74
+ * The `prisma+postgres://` HTTP connection string. Carries an API key.
75
+ */
76
+ readonly prismaPostgresUrl: string;
77
+ /**
78
+ * Direct TCP connection string for the shadow database, which
79
+ * `prisma migrate dev` requires.
80
+ */
81
+ readonly shadowDatabaseUrl: string;
82
+ }
83
+ interface PrismaDevServerConnection extends PrismaDevConnectionStrings {
84
+ /**
85
+ * The server name that was looked up.
86
+ */
87
+ readonly name: string;
88
+ }
89
+ interface GetPrismaDevServerConnectionOptions {
90
+ /**
91
+ * Whether to log the lookup's debug output.
92
+ *
93
+ * Defaults to `false`.
94
+ */
95
+ debug?: boolean;
96
+ /**
97
+ * Name of the server to look up.
98
+ *
99
+ * Defaults to `default`.
100
+ */
101
+ name?: string;
102
+ }
103
+ /**
104
+ * Reads the connection strings of a running `stateful` server by name.
105
+ *
106
+ * This is the supported way for a process outside the one hosting the database
107
+ * to address it. A migration, a seed script, or `psql` cannot see the
108
+ * `process.env` of the Vite dev server that started the database, and a named
109
+ * `stateful` server keeps its ports across restarts, so a lookup by name is
110
+ * stable where a hardcoded connection string is not.
111
+ *
112
+ * Resolves to `null` when no server of that name is running, or when one is
113
+ * still starting up and has not published its endpoints yet. Only `stateful`
114
+ * servers are visible: a `stateless` server writes no state and can only be
115
+ * addressed through the handle that started it.
116
+ */
117
+ declare function getPrismaDevServerConnection(options?: GetPrismaDevServerConnectionOptions): Promise<PrismaDevServerConnection | null>;
118
+
68
119
  type ReadonlyServer = Omit<ProgrammaticServer, "close">;
69
120
  /**
70
121
  * Starts a `prisma dev` server instance programmatically.
@@ -82,4 +133,4 @@ declare function startPrismaDevServer(options?: ServerOptions): Promise<Programm
82
133
  */
83
134
  declare function unstable_startServer(options?: ServerOptions): Promise<ProgrammaticServer>;
84
135
 
85
- export { DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT, DEFAULT_STREAMS_PORT, ExperimentalQueryInsights, type ExperimentalServerFeatures, ExperimentalStreams, WalEvent as ExperimentalWalEvent, type ExperimentalWalEventBatch, type ExperimentalWalEvents, type PortAssignableService, PortNotAvailableError, type ReadonlyServer, type ProgrammaticServer as Server, ServerOptions, startPrismaDevServer, unstable_startServer };
136
+ export { DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT, DEFAULT_STREAMS_PORT, ExperimentalQueryInsights, type ExperimentalServerFeatures, ExperimentalStreams, WalEvent as ExperimentalWalEvent, type ExperimentalWalEventBatch, type ExperimentalWalEvents, type GetPrismaDevServerConnectionOptions, type PortAssignableService, PortNotAvailableError, type PrismaDevConnectionStrings, type PrismaDevServerConnection, type ReadonlyServer, type ProgrammaticServer as Server, ServerOptions, getPrismaDevServerConnection, startPrismaDevServer, unstable_startServer };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as i,b as j}from"./chunk-A5B4L65Y.js";import"./chunk-MTR5KBPH.js";import"./chunk-662IKR3V.js";import"./chunk-PP43TGA5.js";import{a as f,b as g}from"./chunk-KWCQYPJI.js";import{l as h}from"./chunk-HFONW2ZS.js";import"./chunk-ANHBRJRZ.js";import{a,b,c,d,h as e}from"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";import"./chunk-DOJAPHLY.js";export{a as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,c as DEFAULT_SHADOW_DATABASE_PORT,d as DEFAULT_STREAMS_PORT,e as PortNotAvailableError,h as ServerAlreadyRunningError,f as copyPrismaDevRuntimeAssets,g as getPrismaDevRuntimeAssetManifest,i as startPrismaDevServer,j as unstable_startServer};
1
+ import{a as j,b as k}from"./chunk-MD3K2IUP.js";import{c as i}from"./chunk-J6FIMHSD.js";import"./chunk-662IKR3V.js";import"./chunk-PP43TGA5.js";import{a as f,b as g}from"./chunk-KWCQYPJI.js";import{l as h}from"./chunk-HFONW2ZS.js";import"./chunk-ANHBRJRZ.js";import{a,b,c,d,h as e}from"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";import"./chunk-DOJAPHLY.js";export{a as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,c as DEFAULT_SHADOW_DATABASE_PORT,d as DEFAULT_STREAMS_PORT,e as PortNotAvailableError,h as ServerAlreadyRunningError,f as copyPrismaDevRuntimeAssets,g as getPrismaDevRuntimeAssetManifest,i as getPrismaDevServerConnection,j as startPrismaDevServer,k as unstable_startServer};
package/dist/vite.cjs CHANGED
@@ -1,24 +1,26 @@
1
- "use strict";var ns=Object.create;var me=Object.defineProperty;var ss=Object.getOwnPropertyDescriptor;var os=Object.getOwnPropertyNames;var as=Object.getPrototypeOf,is=Object.prototype.hasOwnProperty;var E=(e,t)=>()=>(e&&(t=e(e=0)),t);var K=(e,t)=>{for(var r in t)me(e,r,{get:t[r],enumerable:!0})},Ft=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of os(t))!is.call(e,s)&&s!==r&&me(e,s,{get:()=>t[s],enumerable:!(n=ss(t,s))||n.enumerable});return e};var I=(e,t,r)=>(r=e!=null?ns(as(e)):{},Ft(t||!e||!e.__esModule?me(r,"default",{value:e,enumerable:!0}):r,e)),cs=e=>Ft(me({},"__esModule",{value:!0}),e);var ls,h,m=E(()=>{"use strict";ls=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,h=ls()});var A,pe=E(()=>{"use strict";m();A=class extends Error{constructor(r,n,s){super(n,s);this.status=r}name="HTTPError"}});function Vt(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function ps(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,P.safeParse)(ms,t,{abortEarly:!0});return s?[null,n]:[r]}function W(e,t){let r=e.headers.authorization;if(!r)throw new A(401,"Missing API Key");let[n,s="",o]=r.split(" ");if(n!=="Bearer"||o)throw new A(401,"Invalid API Key");let[a,i]=ps(s);if(a)throw new A(401,"Invalid API Key",{cause:a.join(", ")});let{databaseUrl:c,name:l,shadowDatabaseUrl:u}=i,g=t.name,d=t.port;if(!l)throw new A(401,`Wrong API Key; The Prisma Dev server running at port ${d} requires an API Key from a newer version of \`prisma dev\`. Check the "${g}" server's output for the updated \`DATABASE_URL\` value.`);if(l!==g)throw new A(401,`Wrong API Key; The Prisma Dev server running at port ${d} is named "${g}", but the API Key is for "${l}"`);let{hostname:p,port:y}=new URL(c),{port:v}=t.db,{hostname:re,port:$e}=new URL(u),rs=t.shadowDBPort;if(p!=="localhost"||Number(y)!==v||re!=="localhost"||Number($e)!==rs)throw new A(401,"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 i}var P,jt,ms,Ue=E(()=>{"use strict";m();P=require("valibot");pe();jt=/^(postgres|postgresql):\/\//,ms=(0,P.pipe)((0,P.string)(),(0,P.parseJson)(),(0,P.object)({databaseUrl:(0,P.pipe)((0,P.string)(),(0,P.url)(),(0,P.regex)(jt)),name:(0,P.optional)((0,P.pipe)((0,P.string)(),(0,P.minLength)(1))),shadowDatabaseUrl:(0,P.pipe)((0,P.string)(),(0,P.url)(),(0,P.regex)(jt))}))});function qe(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),ge.default.platform==="darwin"?gs(e):ge.default.platform==="win32"?fs(e):hs(e)}var w,Ce,ge,U,Qe,z,gs,fs,hs,Kt=E(()=>{"use strict";m();w=I(require("path"),1),Ce=I(require("os"),1),ge=I(require("process"),1),U=Ce.default.homedir(),Qe=Ce.default.tmpdir(),{env:z}=ge.default,gs=e=>{let t=w.default.join(U,"Library");return{data:w.default.join(t,"Application Support",e),config:w.default.join(t,"Preferences",e),cache:w.default.join(t,"Caches",e),log:w.default.join(t,"Logs",e),temp:w.default.join(Qe,e)}},fs=e=>{let t=z.APPDATA||w.default.join(U,"AppData","Roaming"),r=z.LOCALAPPDATA||w.default.join(U,"AppData","Local");return{data:w.default.join(r,e,"Data"),config:w.default.join(t,e,"Config"),cache:w.default.join(r,e,"Cache"),log:w.default.join(r,e,"Log"),temp:w.default.join(Qe,e)}},hs=e=>{let t=w.default.basename(U);return{data:w.default.join(z.XDG_DATA_HOME||w.default.join(U,".local","share"),e),config:w.default.join(z.XDG_CONFIG_HOME||w.default.join(U,".config"),e),cache:w.default.join(z.XDG_CACHE_HOME||w.default.join(U,".cache"),e),log:w.default.join(z.XDG_STATE_HOME||w.default.join(U,".local","state"),e),temp:w.default.join(Qe,t,e)}}});function Xt(e,t){return`${he.cache}/engine/${e}/${t}`}function ne(e){return`${he.data}/${e}`}async function J(e){try{return await(0,R.access)(e,R.constants.F_OK),!0}catch(t){if(He(t))return!1;throw t}}async function Zt(e,t){let r=await ys(e);await(0,R.writeFile)(t,r),await(0,R.chmod)(t,"755")}async function er(e,t){await e.stream().pipeTo(fe.WriteStream.toWeb((0,fe.createWriteStream)(t,{encoding:"utf8"})))}function He(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function tr(e){try{return await(0,R.readFile)(e,{encoding:"utf-8"})}catch(t){if(He(t))return null;throw t}}async function rr(e){await(0,R.mkdir)(e,{recursive:!0})}async function nr(e,t){try{return(await(0,R.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,Yt.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(He(r))return[];throw r}}async function Y(e){await(0,R.rm)(e,{force:!0,recursive:!0})}var fe,R,zt,Jt,Yt,he,ys,X=E(()=>{"use strict";m();fe=require("fs"),R=require("fs/promises"),zt=require("util"),Jt=require("zlib");Kt();Yt=I(require("zeptomatch"),1),he=qe("prisma-dev"),ys=(0,zt.promisify)(Jt.unzip)});async function je(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=Ps(r,s);t&&(console.debug(`ports used by other servers: ${Object.keys(o).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let i={databasePort:_,port:_,shadowDatabasePort:_,streamsPort:_},c=["port","databasePort","shadowDatabasePort","streamsPort"];for(let l of c){let u=await Ss({debug:t,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await bs({debug:t,pickedPorts:i,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${l}": ${u}`),i[l]=u}return t&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function Ss(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...i}=o;if(Fe(a))return await Es({debug:t,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let c=s?.[r]??_;if(!Fe(c))return t&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=c in n;return l||Object.values(i).includes(c)?(t&&console.debug(`Port ${c} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,C.checkPort)(c)===!1?(t&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(t&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function bs(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(sr,or,ar,ir)+1,i=Object.values(r).filter(p=>p!==void 0),c=o?vs(o):[],l=[...i,...Object.keys(s).map(Number),...c],u=Math.min(Math.max(a,...l)+100,ye),g=(0,Se.difference)((0,Se.range)(a,u),l),d={port:or,databasePort:sr,shadowDatabasePort:ar,streamsPort:ir}[n];try{return await(0,C.getPort)({port:d in s||i.includes(d)||c.includes(d)?void 0:d,ports:g})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&u+1<=ye)return t&&console.debug(`Expanding port lookup to range [${u+1}, ${ye}].`),await(0,C.getPort)({portRange:[u+1,ye]});throw p}}function Fe(e){return Number.isFinite(e)&&e>=0}function Ps(e,t){let r={},n;for(let s of t){let{databasePort:o,port:a,shadowDatabasePort:i}=s,c=ws(s);if(s.name===e){n={databasePort:o,port:a,shadowDatabasePort:i,streamsPort:c};continue}r[o]=!0,r[a]=!0,r[i]=!0,Fe(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function ws(e){let t=e.experimental?.streams?.serverUrl;if(!t)return _;try{let r=Number(new URL(t).port);return Number.isInteger(r)&&r>0?r:_}catch{return _}}function vs(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function Es(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=e;if(o!==G){if(o in s)throw t&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new Ge(o);if(Object.values(r).includes(o))throw t&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new We(o);if((0,C.isUnsafePort)(o))throw t&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new L(o);if(await(0,C.checkPort)(o)===!1)throw t&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new L(o)}}var C,Se,sr,or,ar,ir,ye,G,_,L,We,Ge,be=E(()=>{"use strict";m();C=require("get-port-please"),Se=require("remeda"),sr=51214,or=51213,ar=51215,ir=51216,ye=65535,G=0,_=-1/0;L=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},We=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"},Ge=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"}});function T(e,t,r=200){let n=at.Buffer.from(JSON.stringify(t),"utf8");e.headersSent||(e.setHeader("Content-Type","application/json; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=r),e.end(n)}function x(e,t,r=200){let n=at.Buffer.from(t,"utf8");e.headersSent||(e.setHeader("Content-Type","text/plain; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=r),e.end(n)}function Z(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function jr(e,t){x(e,t.message,t.status)}var at,k=E(()=>{"use strict";m();at=require("buffer")});async function Kr(e,t){let r;try{r=await(0,Vr.json)(e)}catch{return x(t,"Invalid input",400),null}let{output:n,success:s}=(0,D.safeParse)(Po,r,{abortEarly:!0});return s?n:(x(t,"Invalid input",400),null)}var Vr,D,Po,zr=E(()=>{"use strict";m();Vr=require("stream/consumers"),D=require("valibot");k();Po=(0,D.object)({tags:(0,D.union)([(0,D.pipe)((0,D.array)((0,D.string)()),(0,D.minLength)(1)),(0,D.literal)("all")])})});async function lt(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}function Yr(e,t){let r=e.schemaHash;if(r==null)return T(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let n=De.get(r);return n==null?(T(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:r,schemas:n}}async function Xr(e,t,r){let n=ct.Buffer.from(e,"base64").toString("utf8"),s=vo(n,t.toString());r&&console.log("[Accelerate] schema with override:",s);let o=await lt(s);return{base64Override:ct.Buffer.from(s,"utf8").toString("base64"),overrideHash:o}}function vo(e,t){let r=Eo(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=xo(n,t,Ao(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function Eo(e){let t="datasource";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){r=ut(e,r+2);continue}if(n==="/"&&e[r+1]==="*"){r=dt(e,r+2);continue}if(n==='"'){r=mt(e,r+1);continue}if(e.startsWith(t,r)&&!Jr(e[r-1])&&!Jr(e[r+t.length])){let s=Ro(e,r+t.length,"{");if(s===-1)return null;let o=To(e,s);return o===-1?null:{closeBraceIndex:o,openBraceIndex:s}}}return null}function Ro(e,t,r){for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=ut(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=dt(e,n+2);continue}if(s==='"'){n=mt(e,n+1);continue}if(s===r)return n}return-1}function To(e,t){let r=0;for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=ut(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=dt(e,n+2);continue}if(s==='"'){n=mt(e,n+1);continue}if(s==="{"){r+=1;continue}if(s==="}"&&(r-=1,r===0))return n}return-1}function ut(e,t){let r=t;for(;r<e.length&&e[r]!==`
2
- `;)r+=1;return r}function dt(e,t){let r=e.indexOf("*/",t);return r===-1?e.length:r+1}function mt(e,t){let r=t;for(;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(e[r]==='"')return r;r+=1}return e.length}function Jr(e){return e!=null&&/[A-Za-z0-9_]/.test(e)}function xo(e,t,r){let n=`"${Oo(t)}"`,s=Do(e);for(let[g,d]of s.entries()){let{comment:p,code:y}=Zr(d.line),v=y.match(/^(\s*)url(\s*)=(\s*).*/);if(v)return s[g]={line:`${v[1]}url${v[2]}=${v[3]}${n}${p}`,terminator:d.terminator},it(s)}let o=_o(e),a=Io(s,r),i=`${a}url = ${n}`;if(!e.includes(`
3
- `)&&!e.includes("\r")){let g=e.trim();return g.length===0?`${o}${i}${o}${r}`:`${o}${a}${g}${o}${i}${o}${r}`}let c=s.at(-1);if(c&&c.terminator===""&&/^\s*$/.test(c.line))return`${it(s.slice(0,-1))}${i}${o}${r}`;let l=it(s),u=l.endsWith(`
4
- `)||l.endsWith("\r")?"":o;return`${l}${u}${i}${o}${r}`}function Do(e){let t=[],r=0;for(let n=0;n<e.length;n+=1){if(e[n]==="\r"&&e[n+1]===`
1
+ "use strict";var os=Object.create;var me=Object.defineProperty;var as=Object.getOwnPropertyDescriptor;var is=Object.getOwnPropertyNames;var cs=Object.getPrototypeOf,ls=Object.prototype.hasOwnProperty;var E=(e,t)=>()=>(e&&(t=e(e=0)),t);var K=(e,t)=>{for(var r in t)me(e,r,{get:t[r],enumerable:!0})},Ft=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of is(t))!ls.call(e,s)&&s!==r&&me(e,s,{get:()=>t[s],enumerable:!(n=as(t,s))||n.enumerable});return e};var I=(e,t,r)=>(r=e!=null?os(cs(e)):{},Ft(t||!e||!e.__esModule?me(r,"default",{value:e,enumerable:!0}):r,e)),us=e=>Ft(me({},"__esModule",{value:!0}),e);var ds,h,m=E(()=>{"use strict";ds=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,h=ds()});function qe(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),pe.default.platform==="darwin"?ms(e):pe.default.platform==="win32"?ps(e):gs(e)}var w,Ue,pe,C,Qe,z,ms,ps,gs,Wt=E(()=>{"use strict";m();w=I(require("path"),1),Ue=I(require("os"),1),pe=I(require("process"),1),C=Ue.default.homedir(),Qe=Ue.default.tmpdir(),{env:z}=pe.default,ms=e=>{let t=w.default.join(C,"Library");return{data:w.default.join(t,"Application Support",e),config:w.default.join(t,"Preferences",e),cache:w.default.join(t,"Caches",e),log:w.default.join(t,"Logs",e),temp:w.default.join(Qe,e)}},ps=e=>{let t=z.APPDATA||w.default.join(C,"AppData","Roaming"),r=z.LOCALAPPDATA||w.default.join(C,"AppData","Local");return{data:w.default.join(r,e,"Data"),config:w.default.join(t,e,"Config"),cache:w.default.join(r,e,"Cache"),log:w.default.join(r,e,"Log"),temp:w.default.join(Qe,e)}},gs=e=>{let t=w.default.basename(C);return{data:w.default.join(z.XDG_DATA_HOME||w.default.join(C,".local","share"),e),config:w.default.join(z.XDG_CONFIG_HOME||w.default.join(C,".config"),e),cache:w.default.join(z.XDG_CACHE_HOME||w.default.join(C,".cache"),e),log:w.default.join(z.XDG_STATE_HOME||w.default.join(C,".local","state"),e),temp:w.default.join(Qe,t,e)}}});function Kt(e,t){return`${fe.cache}/engine/${e}/${t}`}function ne(e){return`${fe.data}/${e}`}async function J(e){try{return await(0,R.access)(e,R.constants.F_OK),!0}catch(t){if(He(t))return!1;throw t}}async function zt(e,t){let r=await fs(e);await(0,R.writeFile)(t,r),await(0,R.chmod)(t,"755")}async function Jt(e,t){await e.stream().pipeTo(ge.WriteStream.toWeb((0,ge.createWriteStream)(t,{encoding:"utf8"})))}function He(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function Yt(e){try{return await(0,R.readFile)(e,{encoding:"utf-8"})}catch(t){if(He(t))return null;throw t}}async function Xt(e){await(0,R.mkdir)(e,{recursive:!0})}async function Zt(e,t){try{return(await(0,R.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,Vt.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(He(r))return[];throw r}}async function Y(e){await(0,R.rm)(e,{force:!0,recursive:!0})}var ge,R,Gt,jt,Vt,fe,fs,X=E(()=>{"use strict";m();ge=require("fs"),R=require("fs/promises"),Gt=require("util"),jt=require("zlib");Wt();Vt=I(require("zeptomatch"),1),fe=qe("prisma-dev"),fs=(0,Gt.promisify)(jt.unzip)});async function je(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=bs(r,s);t&&(console.debug(`ports used by other servers: ${Object.keys(o).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(a)}`));let i={databasePort:A,port:A,shadowDatabasePort:A,streamsPort:A},c=["port","databasePort","shadowDatabasePort","streamsPort"];for(let l of c){let u=await ys({debug:t,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await Ss({debug:t,pickedPorts:i,portKey:l,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${l}": ${u}`),i[l]=u}return t&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function ys(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...i}=o;if(Fe(a))return await vs({debug:t,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let c=s?.[r]??A;if(!Fe(c))return t&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=c in n;return l||Object.values(i).includes(c)?(t&&console.debug(`Port ${c} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,U.checkPort)(c)===!1?(t&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(t&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function Ss(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(rr,nr,sr,or)+1,i=Object.values(r).filter(p=>p!==void 0),c=o?ws(o):[],l=[...i,...Object.keys(s).map(Number),...c],u=Math.min(Math.max(a,...l)+100,he),g=(0,ye.difference)((0,ye.range)(a,u),l),d={port:nr,databasePort:rr,shadowDatabasePort:sr,streamsPort:or}[n];try{return await(0,U.getPort)({port:d in s||i.includes(d)||c.includes(d)?void 0:d,ports:g})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&u+1<=he)return t&&console.debug(`Expanding port lookup to range [${u+1}, ${he}].`),await(0,U.getPort)({portRange:[u+1,he]});throw p}}function Fe(e){return Number.isFinite(e)&&e>=0}function bs(e,t){let r={},n;for(let s of t){let{databasePort:o,port:a,shadowDatabasePort:i}=s,c=Ps(s);if(s.name===e){n={databasePort:o,port:a,shadowDatabasePort:i,streamsPort:c};continue}r[o]=!0,r[a]=!0,r[i]=!0,Fe(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function Ps(e){let t=e.experimental?.streams?.serverUrl;if(!t)return A;try{let r=Number(new URL(t).port);return Number.isInteger(r)&&r>0?r:A}catch{return A}}function ws(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function vs(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=e;if(o!==W){if(o in s)throw t&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new Ge(o);if(Object.values(r).includes(o))throw t&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new We(o);if((0,U.isUnsafePort)(o))throw t&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new L(o);if(await(0,U.checkPort)(o)===!1)throw t&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new L(o)}}var U,ye,rr,nr,sr,or,he,W,A,L,We,Ge,Se=E(()=>{"use strict";m();U=require("get-port-please"),ye=require("remeda"),rr=51214,nr=51213,sr=51215,or=51216,he=65535,W=0,A=-1/0;L=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},We=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"},Ge=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 _,Ee=E(()=>{"use strict";m();_=class extends Error{constructor(r,n,s){super(n,s);this.status=r}name="HTTPError"}});function pr(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function _s(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,P.safeParse)(As,t,{abortEarly:!0});return s?[null,n]:[r]}function j(e,t){let r=e.headers.authorization;if(!r)throw new _(401,"Missing API Key");let[n,s="",o]=r.split(" ");if(n!=="Bearer"||o)throw new _(401,"Invalid API Key");let[a,i]=_s(s);if(a)throw new _(401,"Invalid API Key",{cause:a.join(", ")});let{databaseUrl:c,name:l,shadowDatabaseUrl:u}=i,g=t.name,d=t.port;if(!l)throw new _(401,`Wrong API Key; The Prisma Dev server running at port ${d} requires an API Key from a newer version of \`prisma dev\`. Check the "${g}" server's output for the updated \`DATABASE_URL\` value.`);if(l!==g)throw new _(401,`Wrong API Key; The Prisma Dev server running at port ${d} is named "${g}", but the API Key is for "${l}"`);let{hostname:p,port:y}=new URL(c),{port:v}=t.db,{hostname:re,port:Ce}=new URL(u),ss=t.shadowDBPort;if(p!=="localhost"||Number(y)!==v||re!=="localhost"||Number(Ce)!==ss)throw new _(401,"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 i}var P,mr,As,st=E(()=>{"use strict";m();P=require("valibot");Ee();mr=/^(postgres|postgresql):\/\//,As=(0,P.pipe)((0,P.string)(),(0,P.parseJson)(),(0,P.object)({databaseUrl:(0,P.pipe)((0,P.string)(),(0,P.url)(),(0,P.regex)(mr)),name:(0,P.optional)((0,P.pipe)((0,P.string)(),(0,P.minLength)(1))),shadowDatabaseUrl:(0,P.pipe)((0,P.string)(),(0,P.url)(),(0,P.regex)(mr))}))});function T(e,t,r=200){let n=St.Buffer.from(JSON.stringify(t),"utf8");e.headersSent||(e.setHeader("Content-Type","application/json; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=r),e.end(n)}function x(e,t,r=200){let n=St.Buffer.from(t,"utf8");e.headersSent||(e.setHeader("Content-Type","text/plain; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=r),e.end(n)}function ee(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function Xr(e,t){x(e,t.message,t.status)}var St,k=E(()=>{"use strict";m();St=require("buffer")});async function en(e,t){let r;try{r=await(0,Zr.json)(e)}catch{return x(t,"Invalid input",400),null}let{output:n,success:s}=(0,D.safeParse)(Do,r,{abortEarly:!0});return s?n:(x(t,"Invalid input",400),null)}var Zr,D,Do,tn=E(()=>{"use strict";m();Zr=require("stream/consumers"),D=require("valibot");k();Do=(0,D.object)({tags:(0,D.union)([(0,D.pipe)((0,D.array)((0,D.string)()),(0,D.minLength)(1)),(0,D.literal)("all")])})});async function wt(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(a=>a.toString(16).padStart(2,"0")).join("")}function nn(e,t){let r=e.schemaHash;if(r==null)return T(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let n=Oe.get(r);return n==null?(T(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:r,schemas:n}}async function sn(e,t,r){let n=Pt.Buffer.from(e,"base64").toString("utf8"),s=Ao(n,t.toString());r&&console.log("[Accelerate] schema with override:",s);let o=await wt(s);return{base64Override:Pt.Buffer.from(s,"utf8").toString("base64"),overrideHash:o}}function Ao(e,t){let r=_o(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=Mo(n,t,$o(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function _o(e){let t="datasource";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){r=vt(e,r+2);continue}if(n==="/"&&e[r+1]==="*"){r=Et(e,r+2);continue}if(n==='"'){r=Rt(e,r+1);continue}if(e.startsWith(t,r)&&!rn(e[r-1])&&!rn(e[r+t.length])){let s=Oo(e,r+t.length,"{");if(s===-1)return null;let o=No(e,s);return o===-1?null:{closeBraceIndex:o,openBraceIndex:s}}}return null}function Oo(e,t,r){for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=vt(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=Et(e,n+2);continue}if(s==='"'){n=Rt(e,n+1);continue}if(s===r)return n}return-1}function No(e,t){let r=0;for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=vt(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=Et(e,n+2);continue}if(s==='"'){n=Rt(e,n+1);continue}if(s==="{"){r+=1;continue}if(s==="}"&&(r-=1,r===0))return n}return-1}function vt(e,t){let r=t;for(;r<e.length&&e[r]!==`
2
+ `;)r+=1;return r}function Et(e,t){let r=e.indexOf("*/",t);return r===-1?e.length:r+1}function Rt(e,t){let r=t;for(;r<e.length;){if(e[r]==="\\"){r+=2;continue}if(e[r]==='"')return r;r+=1}return e.length}function rn(e){return e!=null&&/[A-Za-z0-9_]/.test(e)}function Mo(e,t,r){let n=`"${Co(t)}"`,s=Lo(e);for(let[g,d]of s.entries()){let{comment:p,code:y}=on(d.line),v=y.match(/^(\s*)url(\s*)=(\s*).*/);if(v)return s[g]={line:`${v[1]}url${v[2]}=${v[3]}${n}${p}`,terminator:d.terminator},bt(s)}let o=ko(e),a=Bo(s,r),i=`${a}url = ${n}`;if(!e.includes(`
3
+ `)&&!e.includes("\r")){let g=e.trim();return g.length===0?`${o}${i}${o}${r}`:`${o}${a}${g}${o}${i}${o}${r}`}let c=s.at(-1);if(c&&c.terminator===""&&/^\s*$/.test(c.line))return`${bt(s.slice(0,-1))}${i}${o}${r}`;let l=bt(s),u=l.endsWith(`
4
+ `)||l.endsWith("\r")?"":o;return`${l}${u}${i}${o}${r}`}function Lo(e){let t=[],r=0;for(let n=0;n<e.length;n+=1){if(e[n]==="\r"&&e[n+1]===`
5
5
  `){t.push({line:e.slice(r,n),terminator:`\r
6
6
  `}),n+=1,r=n+1;continue}(e[n]===`
7
- `||e[n]==="\r")&&(t.push({line:e.slice(r,n),terminator:e[n]}),r=n+1)}return(r<e.length||e.length===0)&&t.push({line:e.slice(r),terminator:""}),t}function it(e){return e.map(t=>`${t.line}${t.terminator}`).join("")}function Zr(e){let t=!1,r=!1;for(let n=0;n<e.length;n+=1){let s=e[n];if(r){if(t){t=!1;continue}if(s==="\\"){t=!0;continue}s==='"'&&(r=!1);continue}if(s==='"'){r=!0;continue}if(s==="/"&&e[n+1]==="/")return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:""}}function Io(e,t){for(let r of e){let{code:n}=Zr(r.line),s=n.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(s?.[1])return s[1]}return`${t}${wo}`}function Ao(e,t){let r=e.lastIndexOf(`
8
- `,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function _o(e){return e.includes(`\r
7
+ `||e[n]==="\r")&&(t.push({line:e.slice(r,n),terminator:e[n]}),r=n+1)}return(r<e.length||e.length===0)&&t.push({line:e.slice(r),terminator:""}),t}function bt(e){return e.map(t=>`${t.line}${t.terminator}`).join("")}function on(e){let t=!1,r=!1;for(let n=0;n<e.length;n+=1){let s=e[n];if(r){if(t){t=!1;continue}if(s==="\\"){t=!0;continue}s==='"'&&(r=!1);continue}if(s==='"'){r=!0;continue}if(s==="/"&&e[n+1]==="/")return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:""}}function Bo(e,t){for(let r of e){let{code:n}=on(r.line),s=n.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(s?.[1])return s[1]}return`${t}${Io}`}function $o(e,t){let r=e.lastIndexOf(`
8
+ `,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function ko(e){return e.includes(`\r
9
9
  `)?`\r
10
10
  `:`
11
- `}function Oo(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var ct,De,wo,en=E(()=>{"use strict";m();ct=require("buffer");k();De=new Map;wo=" "});function oe(e,t){let r=e[t];return Array.isArray(r)?r.at(-1):r}var pt=E(()=>{"use strict";m()});function rn(e,t){let r=(e.method??"GET").toUpperCase(),n=`${t.origin}${e.url??"/"}`,s={headers:Mo(e.headers),method:r};return No.has(r)||(s.body=gt.Readable.toWeb(e),s.duplex="half"),new Request(n,s)}async function nn(e,t){t.statusCode=e.status;for(let[r,n]of e.headers)t.setHeader(r,n);if(e.body===null){t.end();return}await(0,tn.pipeline)(gt.Readable.fromWeb(e.body),t)}function Mo(e){let t=new Headers;for(let[r,n]of Object.entries(e))if(typeof n=="string")t.append(r,n);else if(Array.isArray(n))for(let s of n)t.append(r,s);return t}var gt,tn,No,sn=E(()=>{"use strict";m();gt=require("stream"),tn=require("stream/promises"),No=new Set(["GET","HEAD"])});var cn={};K(cn,{createHTTPServer:()=>Bo,wrap:()=>O});function O(e,t){return async function(n,s,o){let a=t?Date.now():0;t&&s.once("finish",()=>{let i=Date.now()-a;console.log("[Accelerate]",`<-- ${n.method??"?"} ${n.url??""} ${s.statusCode} ${i}ms`)});try{await e(n,s,o)}catch(i){try{Lo(i,s,n,t)}catch(c){t&&console.error("[Accelerate]","error while handling handler error",c),s.destroyed||s.destroy()}}}}function Lo(e,t,r,n){if(t.destroyed||t.headersSent||t.writableEnded){n&&console.error("[Accelerate]",`error after response was no longer writable for ${r.method??"?"} ${r.url??""}`,e),t.destroy();return}if(e instanceof A){jr(t,e);return}console.error("[Accelerate]",e);try{Z(t,500)}catch(s){n&&console.error("[Accelerate]","failed to write 500 response (client likely disconnected)",s),t.destroy()}}function Bo(e){let{router:t}=e;return{async listen(r){let n=(0,on.createServer)((a,i)=>{t.lookup(a,i)}),o=(await $o(n,r)).port;return n.on("error",a=>{console.error("[Accelerate]",a)}),{async close(){await(0,an.promisify)(n.close.bind(n))()},port:o,url:`http://localhost:${o}`}}}}function $o(e,t){return new Promise((r,n)=>{let s=a=>{if(e.off("listening",o),typeof a=="object"&&a!==null&&"code"in a&&a.code==="EADDRINUSE"){n(new L(t));return}n(a)},o=()=>{e.off("error",s),r(e.address())};e.once("error",s),e.once("listening",o),e.listen(t)})}var on,an,Ie=E(()=>{"use strict";m();on=require("http"),an=require("util");be();pe();k()});function Ae(e){return{traceparent:oe(e.headers,"traceparent"),"X-capture-telemetry":oe(e.headers,"x-capture-telemetry")}}var ln=E(()=>{"use strict";m();pt()});async function dn(e,t){let r;try{r=await(0,un.json)(e)}catch{return T(t,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:n,output:s,success:o}=(0,b.safeParse)(ko,r,{abortEarly:!0});return o?s:(T(t,{EngineNotStarted:{reason:"InvalidRequest",issues:n}},400),null)}function mn(e,t){let{output:r,success:n}=(0,b.safeParse)(Uo,e);return n?r:(T(t,{EngineMalfunction:{}},500),null)}var un,b,ko,Uo,pn=E(()=>{"use strict";m();un=require("stream/consumers"),b=require("valibot");k();ko=(0,b.object)({isolation_level:(0,b.optional)((0,b.string)()),max_wait:(0,b.pipe)((0,b.number)(),(0,b.integer)(),(0,b.minValue)(0)),timeout:(0,b.pipe)((0,b.number)(),(0,b.integer)(),(0,b.minValue)(0))});Uo=(0,b.looseObject)({id:(0,b.union)([(0,b.string)(),(0,b.number)()])})});function gn(e){let t,r,n=new Promise((a,i)=>{t=a,r=i}),s=a=>{s=o=null,r(a),e?.onRejected?.(a),e?.onFulfilled?.()},o=a=>{o=s=null,t(a),e?.onResolved?.(a),e?.onFulfilled?.()};return{isFulfilled:()=>o===s,promise:n,reject:a=>s?.(a),resolve:a=>o?.(a)}}var fn=E(()=>{"use strict";m()});var ht={};K(ht,{Engine:()=>ft,handleEngineError:()=>qo});function qo(e,t){if(console.error(e),e instanceof ae){T(t,{EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500);return}if(e instanceof ee){x(t,e.responseBody,e.statusCode);return}Z(t,500)}var yn,Sn,bn,Pn,wn,vn,Co,Qo,hn,ft,ae,ee,yt=E(()=>{"use strict";m();yn=require("child_process"),Sn=require("events"),bn=require("fs/promises"),Pn=require("path"),wn=require("timers/promises");fn();vn=require("std-env");X();k();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Co,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Qo,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:hn}=vn.process.env),ft=class e{static#r=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:r}=t,n=`${t.schemaHash}:${t.clientVersion}`;try{let s=e.#r.get(n);if(s)return s;let o=new e(t);return e.#r.set(n,o),r&&console.debug("[Query Engine] starting...",t),await o.start(),r&&console.debug("[Query Engine] started!"),o}finally{e.stopAll(n)}}static async stopAll(t){let n=(await Promise.allSettled(Array.from(e.#r.entries()).filter(([s])=>s!==t).map(async([s,o])=>{try{await o.stop()}finally{e.#r.delete(s)}}))).filter(s=>s.status==="rejected").map(s=>s.reason);if(n.length>0)throw new AggregateError(n,"Failed to stop engines")}async commitTransaction(t,r){return await this.#i(t,r,"commit")}async request(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(n,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await ee.fromResponse(o);return await o.text()}async rollbackTransaction(t,r){return await this.#i(t,r,"rollback")}async startTransaction(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(`${n}/transaction/start`,{body:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await ee.fromResponse(o);return await o.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:r,resolve:n}=gn();this.#t=t;let s=Qo||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",s);let{proxySignals:o}=await import("foreground-child/proxy-signals"),a=(0,yn.spawn)(s,["--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(a),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8");let i=u=>{let g=u.split(`
11
+ `}function Co(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var Pt,Oe,Io,an=E(()=>{"use strict";m();Pt=require("buffer");k();Oe=new Map;Io=" "});function ce(e,t){let r=e[t];return Array.isArray(r)?r.at(-1):r}var Tt=E(()=>{"use strict";m()});function ln(e,t){let r=(e.method??"GET").toUpperCase(),n=`${t.origin}${e.url??"/"}`,s={headers:Qo(e.headers),method:r};return Uo.has(r)||(s.body=xt.Readable.toWeb(e),s.duplex="half"),new Request(n,s)}async function un(e,t){t.statusCode=e.status;for(let[r,n]of e.headers)t.setHeader(r,n);if(e.body===null){t.end();return}await(0,cn.pipeline)(xt.Readable.fromWeb(e.body),t)}function Qo(e){let t=new Headers;for(let[r,n]of Object.entries(e))if(typeof n=="string")t.append(r,n);else if(Array.isArray(n))for(let s of n)t.append(r,s);return t}var xt,cn,Uo,dn=E(()=>{"use strict";m();xt=require("stream"),cn=require("stream/promises"),Uo=new Set(["GET","HEAD"])});var gn={};K(gn,{createHTTPServer:()=>Ho,wrap:()=>O});function O(e,t){return async function(n,s,o){let a=t?Date.now():0;t&&s.once("finish",()=>{let i=Date.now()-a;console.log("[Accelerate]",`<-- ${n.method??"?"} ${n.url??""} ${s.statusCode} ${i}ms`)});try{await e(n,s,o)}catch(i){try{qo(i,s,n,t)}catch(c){t&&console.error("[Accelerate]","error while handling handler error",c),s.destroyed||s.destroy()}}}}function qo(e,t,r,n){if(t.destroyed||t.headersSent||t.writableEnded){n&&console.error("[Accelerate]",`error after response was no longer writable for ${r.method??"?"} ${r.url??""}`,e),t.destroy();return}if(e instanceof _){Xr(t,e);return}console.error("[Accelerate]",e);try{ee(t,500)}catch(s){n&&console.error("[Accelerate]","failed to write 500 response (client likely disconnected)",s),t.destroy()}}function Ho(e){let{router:t}=e;return{async listen(r){let n=(0,mn.createServer)((a,i)=>{t.lookup(a,i)}),o=(await Fo(n,r)).port;return n.on("error",a=>{console.error("[Accelerate]",a)}),{async close(){await(0,pn.promisify)(n.close.bind(n))()},port:o,url:`http://localhost:${o}`}}}}function Fo(e,t){return new Promise((r,n)=>{let s=a=>{if(e.off("listening",o),typeof a=="object"&&a!==null&&"code"in a&&a.code==="EADDRINUSE"){n(new L(t));return}n(a)},o=()=>{e.off("error",s),r(e.address())};e.once("error",s),e.once("listening",o),e.listen(t)})}var mn,pn,Ne=E(()=>{"use strict";m();mn=require("http"),pn=require("util");Se();Ee();k()});function Me(e){return{traceparent:ce(e.headers,"traceparent"),"X-capture-telemetry":ce(e.headers,"x-capture-telemetry")}}var fn=E(()=>{"use strict";m();Tt()});async function yn(e,t){let r;try{r=await(0,hn.json)(e)}catch{return T(t,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:n,output:s,success:o}=(0,b.safeParse)(Wo,r,{abortEarly:!0});return o?s:(T(t,{EngineNotStarted:{reason:"InvalidRequest",issues:n}},400),null)}function Sn(e,t){let{output:r,success:n}=(0,b.safeParse)(Go,e);return n?r:(T(t,{EngineMalfunction:{}},500),null)}var hn,b,Wo,Go,bn=E(()=>{"use strict";m();hn=require("stream/consumers"),b=require("valibot");k();Wo=(0,b.object)({isolation_level:(0,b.optional)((0,b.string)()),max_wait:(0,b.pipe)((0,b.number)(),(0,b.integer)(),(0,b.minValue)(0)),timeout:(0,b.pipe)((0,b.number)(),(0,b.integer)(),(0,b.minValue)(0))});Go=(0,b.looseObject)({id:(0,b.union)([(0,b.string)(),(0,b.number)()])})});function Pn(e){let t,r,n=new Promise((a,i)=>{t=a,r=i}),s=a=>{s=o=null,r(a),e?.onRejected?.(a),e?.onFulfilled?.()},o=a=>{o=s=null,t(a),e?.onResolved?.(a),e?.onFulfilled?.()};return{isFulfilled:()=>o===s,promise:n,reject:a=>s?.(a),resolve:a=>o?.(a)}}var wn=E(()=>{"use strict";m()});var It={};K(It,{Engine:()=>Dt,handleEngineError:()=>Ko});function Ko(e,t){if(console.error(e),e instanceof le){T(t,{EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500);return}if(e instanceof te){x(t,e.responseBody,e.statusCode);return}ee(t,500)}var En,Rn,Tn,xn,Dn,In,jo,Vo,vn,Dt,le,te,At=E(()=>{"use strict";m();En=require("child_process"),Rn=require("events"),Tn=require("fs/promises"),xn=require("path"),Dn=require("timers/promises");wn();In=require("std-env");X();k();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:jo,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Vo,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:vn}=In.process.env),Dt=class e{static#r=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:r}=t,n=`${t.schemaHash}:${t.clientVersion}`;try{let s=e.#r.get(n);if(s)return s;let o=new e(t);return e.#r.set(n,o),r&&console.debug("[Query Engine] starting...",t),await o.start(),r&&console.debug("[Query Engine] started!"),o}finally{e.stopAll(n)}}static async stopAll(t){let n=(await Promise.allSettled(Array.from(e.#r.entries()).filter(([s])=>s!==t).map(async([s,o])=>{try{await o.stop()}finally{e.#r.delete(s)}}))).filter(s=>s.status==="rejected").map(s=>s.reason);if(n.length>0)throw new AggregateError(n,"Failed to stop engines")}async commitTransaction(t,r){return await this.#i(t,r,"commit")}async request(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(n,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await te.fromResponse(o);return await o.text()}async rollbackTransaction(t,r){return await this.#i(t,r,"rollback")}async startTransaction(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(`${n}/transaction/start`,{body:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await te.fromResponse(o);return await o.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:r,resolve:n}=Pn();this.#t=t;let s=Vo||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",s);let{proxySignals:o}=await import("foreground-child/proxy-signals"),a=(0,En.spawn)(s,["--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(a),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8");let i=u=>{let g=u.split(`
12
12
  `).find(v=>v.includes("Started query engine http server"));if(!g)return;a.stdout.removeListener("data",i);let{fields:d}=JSON.parse(g);if(d==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${u}`));let{ip:p,port:y}=d;if(p==null||y==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.
13
- Received data: ${u}`));n({childProcess:a,url:`http://${p}:${y}`})},c=u=>{this.#t=null,r(new ae(String(u))),a.removeListener("exit",l),a.kill()};a.once("error",c);let l=(u,g)=>{this.#t=null,r(new ae(`Query Engine exited with code ${u} and signal ${g}`))};return a.once("exit",l),a.stdout.on("data",i),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await(0,Sn.once)(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#o();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let r=Xt(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,bn.mkdir)(r,{recursive:!0});let{binaryTarget:n}=this.#e.platform,s=n==="windows"?".exe":"",o=(0,Pn.join)(r,`query-engine-${n}${s}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(Co==="1"||await J(o)===!1)&&await this.#a({commitHash:t,extension:s,engineBinaryPath:o}),o}async#o(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let n=(await t.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let s=n.split(".").at(-1);if(!s)throw new Error("Couldn't find commit hash in engines version");return s}async#a(t){let{commitHash:r,extension:n,engineBinaryPath:s}=t,{binaryTarget:o}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${o}/query-engine${n}.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}`);hn&&await(0,wn.setTimeout)(Number(hn)),await Zt(await i.arrayBuffer(),s),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",s)}#n(t){let r={};for(let[n,s]of Object.entries(t))s!=null&&(r[n]=s);return r}async#i(t,r,n){let{url:s}=await this.#t,o=this.#n(r),a=await fetch(`${s}/transaction/${t}/${n}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await ee.fromResponse(a);try{return await a.json()}catch{return{}}}};ae=class extends Error{name="EngineStartError"},ee=class e extends Error{constructor(r,n,s){super(`${r}: Query Engine response status ${n}, body: ${s}`);this.action=r;this.statusCode=n;this.responseBody=s}name="EngineHttpError";static async fromResponse(r){let n=new URL(r.url),s=await r.text();return new e(n.pathname,r.status,s)}}});var En={};K(En,{getQueryPlanExecutorServer:()=>Ho,queryPlanExecutorVersion:()=>Rn.version});async function Ho(e){return St===void 0&&(St=await F.Server.create({databaseUrl:e.db.connectionString,maxResponseSize:(0,F.parseSize)("128 MiB"),queryTimeout:(0,F.parseDuration)("PT5M"),maxTransactionTimeout:(0,F.parseDuration)("PT5M"),maxTransactionWaitTime:(0,F.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.debug?"debug":"off"}})),St}var F,Rn,St,Tn=E(()=>{"use strict";m();F=require("@prisma/query-plan-executor"),Rn=require("@prisma/query-plan-executor")});var An={};K(An,{registerAccelerateRoutes:()=>Go});function _e(){return xn??=Promise.resolve().then(()=>(yt(),ht)),xn}function Fo(){return In??=Promise.resolve().then(()=>(Tn(),En)),In}async function Wo(){return Dn??=import("@prisma/get-platform").then(async({default:e})=>await e.getPlatformInfo()),await Dn}function Go(e,t,r){e.on("POST","/invalidate",O(async(s,o)=>{W(s,t),await Kr(s,o)!==null&&Z(o,200)},r));for(let s of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])e.on("POST",s,O(async(o,a,i)=>{W(o,t);try{let c=await bt(a,t,i);if(c===null)return;let l=await(0,Pt.text)(o),u=i.transactionId,g=await c.request(l,{...Ae(o),"X-transaction-id":u});x(a,g)}catch(c){let{handleEngineError:l}=await _e();l(c,a)}},r));for(let s of["commit","rollback"])e.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${s}`,O(async(o,a,i)=>{W(o,t);try{let c=await bt(a,t,i);if(c===null)return;let l=i.transactionId;if(l==null){T(a,{EngineMalfunction:{}},500);return}let u=`${s}Transaction`,g=await c[u](l,Ae(o));T(a,g)}catch(c){let{handleEngineError:l}=await _e();l(c,a)}},r));e.on("PUT","/:clientVersion/:schemaHash/schema",O(async(s,o,a)=>{W(s,t);let i=await(0,Pt.text)(s);if(!i){x(o,"Missing schema",400);return}let c=a.schemaHash;if(c==null){x(o,"Missing schema hash",400);return}let l=De.get(c);if(l==null){if(c!==await lt(i)){x(o,"Schema hash mismatch",400);return}let u=await Xr(i,t.db.prismaORMConnectionString,t.debug);De.set(c,{base64Original:i,...u}),x(o,c);return}if(i!==l.base64Original){x(o,"Schema mismatch",400);return}x(o,c)},r)),e.on("POST","/:clientVersion/:schemaHash/transaction/start",O(async(s,o,a)=>{W(s,t);let i=await dn(s,o);if(i!==null)try{let c=await bt(o,t,a);if(c===null)return;let l=await c.startTransaction(i,Ae(s)),u=mn(l,o);if(u===null)return;let{id:g}=u,d=a.clientVersion,p=a.schemaHash;T(o,{...l,"data-proxy":{endpoint:`http://localhost:${t.port}/${d}/${p}/itx/${g}`}})}catch(c){let{handleEngineError:l}=await _e();l(c,o)}},r));let n=[["GET","/connection-info"],["POST","/query"],["POST","/transaction/start"],["POST","/transaction/:transactionId/commit"],["POST","/transaction/:transactionId/query"],["POST","/transaction/:transactionId/rollback"]];for(let[s,o]of n)e.on(s,o,O(async(a,i)=>{W(a,t);let{getQueryPlanExecutorServer:c,queryPlanExecutorVersion:l}=await Fo(),u=oe(a.headers,"prisma-engine-hash");if(u!=="0.0.0"&&u!==l)throw new A(400,`Using an HTTP connection string is not supported with Prisma Client version ${u??"<missing>"} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${l}.`);let g=await c(t),d=rn(a,{origin:`http://localhost:${t.port}`}),p=await g.fetch(d);await nn(p,i)},r))}async function bt(e,t,r){let{Engine:n}=await _e(),s=Yr(r,e);if(s===null)return null;let{base64Override:o,overrideHash:a}=s.schemas;return await n.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||r.clientVersion||"",debug:t.debug,platform:await Wo(),schemaHash:a})}var Pt,xn,Dn,In,_n=E(()=>{"use strict";m();Pt=require("stream/consumers");Ue();zr();en();pt();pe();sn();k();Ie();ln();pn()});var On={};K(On,{registerUtilityRoutes:()=>jo});function jo(e,t,r){e.on("POST","/database/dump",O(async(n,s)=>{await t.db.dump(t.databaseDumpPath),T(s,{dumpPath:t.databaseDumpPath},201)},r)),e.on("GET","/health",O((n,s)=>{T(s,{name:t.name})},r))}var Nn=E(()=>{"use strict";m();k();Ie()});var Ua={};K(Ua,{default:()=>Ma,prismaDev:()=>ts});module.exports=cs(Ua);m();m();var us="DATABASE_URL",ds="SHADOW_DATABASE_URL";function ke(e){return{databaseUrl:e.database.prismaORMConnectionString??e.database.connectionString,prismaPostgresUrl:e.ppg.url,shadowDatabaseUrl:e.shadowDatabase.prismaORMConnectionString??e.shadowDatabase.connectionString}}function Wt(e,t={}){let{databaseUrl:r=us,prismaPostgresUrl:n=!1,shadowDatabaseUrl:s=ds}=t,o=ke(e);return[[r,o.databaseUrl],[s,o.shadowDatabaseUrl],[n,o.prismaPostgresUrl]].filter(i=>typeof i[0]=="string"&&i[0].length>0).map(([i,c])=>({name:i,value:c}))}function Gt(e,t,r={}){let n=[],s=[];for(let o of e){let a=t[o.name];if(!r.override&&a!=null&&a!==""){s.push(o);continue}t[o.name]=o.value,n.push(o)}return{applied:n,skipped:s}}m();m();m();var Jn=require("timers/promises");m();Ue();m();var xe=require("net"),$r=require("path"),kr=require("pathe/utils");X();be();m();var Ke=require("perf_hooks"),br=require("@electric-sql/pglite");m();var dr=require("buffer"),cr=500,lr=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,Rs=new RegExp(`(?:${lr.source}\\.)*${lr.source}`),Ts=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${Rs.source})`,"gi"),xs=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,ur=/prismaQuery='([^']+)'/,Ds=new Set([Q(`
13
+ Received data: ${u}`));n({childProcess:a,url:`http://${p}:${y}`})},c=u=>{this.#t=null,r(new le(String(u))),a.removeListener("exit",l),a.kill()};a.once("error",c);let l=(u,g)=>{this.#t=null,r(new le(`Query Engine exited with code ${u} and signal ${g}`))};return a.once("exit",l),a.stdout.on("data",i),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await(0,Rn.once)(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#o();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let r=Kt(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,Tn.mkdir)(r,{recursive:!0});let{binaryTarget:n}=this.#e.platform,s=n==="windows"?".exe":"",o=(0,xn.join)(r,`query-engine-${n}${s}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(jo==="1"||await J(o)===!1)&&await this.#a({commitHash:t,extension:s,engineBinaryPath:o}),o}async#o(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let n=(await t.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let s=n.split(".").at(-1);if(!s)throw new Error("Couldn't find commit hash in engines version");return s}async#a(t){let{commitHash:r,extension:n,engineBinaryPath:s}=t,{binaryTarget:o}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${o}/query-engine${n}.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}`);vn&&await(0,Dn.setTimeout)(Number(vn)),await zt(await i.arrayBuffer(),s),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",s)}#n(t){let r={};for(let[n,s]of Object.entries(t))s!=null&&(r[n]=s);return r}async#i(t,r,n){let{url:s}=await this.#t,o=this.#n(r),a=await fetch(`${s}/transaction/${t}/${n}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await te.fromResponse(a);try{return await a.json()}catch{return{}}}};le=class extends Error{name="EngineStartError"},te=class e extends Error{constructor(r,n,s){super(`${r}: Query Engine response status ${n}, body: ${s}`);this.action=r;this.statusCode=n;this.responseBody=s}name="EngineHttpError";static async fromResponse(r){let n=new URL(r.url),s=await r.text();return new e(n.pathname,r.status,s)}}});var An={};K(An,{getQueryPlanExecutorServer:()=>zo,queryPlanExecutorVersion:()=>_n.version});async function zo(e){return _t===void 0&&(_t=await F.Server.create({databaseUrl:e.db.connectionString,maxResponseSize:(0,F.parseSize)("128 MiB"),queryTimeout:(0,F.parseDuration)("PT5M"),maxTransactionTimeout:(0,F.parseDuration)("PT5M"),maxTransactionWaitTime:(0,F.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.debug?"debug":"off"}})),_t}var F,_n,_t,On=E(()=>{"use strict";m();F=require("@prisma/query-plan-executor"),_n=require("@prisma/query-plan-executor")});var Bn={};K(Bn,{registerAccelerateRoutes:()=>Xo});function Le(){return Nn??=Promise.resolve().then(()=>(At(),It)),Nn}function Jo(){return Ln??=Promise.resolve().then(()=>(On(),An)),Ln}async function Yo(){return Mn??=import("@prisma/get-platform").then(async({default:e})=>await e.getPlatformInfo()),await Mn}function Xo(e,t,r){e.on("POST","/invalidate",O(async(s,o)=>{j(s,t),await en(s,o)!==null&&ee(o,200)},r));for(let s of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])e.on("POST",s,O(async(o,a,i)=>{j(o,t);try{let c=await Ot(a,t,i);if(c===null)return;let l=await(0,Nt.text)(o),u=i.transactionId,g=await c.request(l,{...Me(o),"X-transaction-id":u});x(a,g)}catch(c){let{handleEngineError:l}=await Le();l(c,a)}},r));for(let s of["commit","rollback"])e.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${s}`,O(async(o,a,i)=>{j(o,t);try{let c=await Ot(a,t,i);if(c===null)return;let l=i.transactionId;if(l==null){T(a,{EngineMalfunction:{}},500);return}let u=`${s}Transaction`,g=await c[u](l,Me(o));T(a,g)}catch(c){let{handleEngineError:l}=await Le();l(c,a)}},r));e.on("PUT","/:clientVersion/:schemaHash/schema",O(async(s,o,a)=>{j(s,t);let i=await(0,Nt.text)(s);if(!i){x(o,"Missing schema",400);return}let c=a.schemaHash;if(c==null){x(o,"Missing schema hash",400);return}let l=Oe.get(c);if(l==null){if(c!==await wt(i)){x(o,"Schema hash mismatch",400);return}let u=await sn(i,t.db.prismaORMConnectionString,t.debug);Oe.set(c,{base64Original:i,...u}),x(o,c);return}if(i!==l.base64Original){x(o,"Schema mismatch",400);return}x(o,c)},r)),e.on("POST","/:clientVersion/:schemaHash/transaction/start",O(async(s,o,a)=>{j(s,t);let i=await yn(s,o);if(i!==null)try{let c=await Ot(o,t,a);if(c===null)return;let l=await c.startTransaction(i,Me(s)),u=Sn(l,o);if(u===null)return;let{id:g}=u,d=a.clientVersion,p=a.schemaHash;T(o,{...l,"data-proxy":{endpoint:`http://localhost:${t.port}/${d}/${p}/itx/${g}`}})}catch(c){let{handleEngineError:l}=await Le();l(c,o)}},r));let n=[["GET","/connection-info"],["POST","/query"],["POST","/transaction/start"],["POST","/transaction/:transactionId/commit"],["POST","/transaction/:transactionId/query"],["POST","/transaction/:transactionId/rollback"]];for(let[s,o]of n)e.on(s,o,O(async(a,i)=>{j(a,t);let{getQueryPlanExecutorServer:c,queryPlanExecutorVersion:l}=await Jo(),u=ce(a.headers,"prisma-engine-hash");if(u!=="0.0.0"&&u!==l)throw new _(400,`Using an HTTP connection string is not supported with Prisma Client version ${u??"<missing>"} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${l}.`);let g=await c(t),d=ln(a,{origin:`http://localhost:${t.port}`}),p=await g.fetch(d);await un(p,i)},r))}async function Ot(e,t,r){let{Engine:n}=await Le(),s=nn(r,e);if(s===null)return null;let{base64Override:o,overrideHash:a}=s.schemas;return await n.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||r.clientVersion||"",debug:t.debug,platform:await Yo(),schemaHash:a})}var Nt,Nn,Mn,Ln,$n=E(()=>{"use strict";m();Nt=require("stream/consumers");st();tn();an();Tt();Ee();dn();k();Ne();fn();bn()});var kn={};K(kn,{registerUtilityRoutes:()=>Zo});function Zo(e,t,r){e.on("POST","/database/dump",O(async(n,s)=>{await t.db.dump(t.databaseDumpPath),T(s,{dumpPath:t.databaseDumpPath},201)},r)),e.on("GET","/health",O((n,s)=>{T(s,{name:t.name})},r))}var Cn=E(()=>{"use strict";m();k();Ne()});var qa={};K(qa,{default:()=>Ba,prismaDev:()=>ns});module.exports=us(qa);m();m();m();var lr=require("fs/promises"),G=require("pathe"),Z=require("proper-lockfile"),tt=require("std-env"),f=require("valibot");X();m();var hs=require("timers/promises"),er=require("std-env");function tr(e,t){if(e==null)return!1;try{return er.process.kill?.(e,0)??!0}catch(r){return t&&console.error(`Error checking if process with PID ${e} exists:`,r),!1}}Se();m();var Ve=require("pathe");X();var Ke="prisma-wal",ze="prisma-queries";function Je(){return(0,Ve.join)(fe.data,"durable-streams")}function be(e){return(0,Ve.join)(Je(),e)}function Pe(e,t=Ke){return new URL(`/v1/stream/${encodeURIComponent(t)}`,e).toString()}var oe=(0,f.pipe)((0,f.string)(),(0,f.url)()),ar=(0,f.object)({connectionString:oe,prismaORMConnectionString:(0,f.optional)(oe),terminalCommand:(0,f.optional)((0,f.string)())}),ir=(0,f.object)({url:oe}),cr=(0,f.object)({serverUrl:oe,sqlitePath:(0,f.pipe)((0,f.string)(),(0,f.minLength)(1)),streamName:(0,f.pipe)((0,f.string)(),(0,f.minLength)(1)),url:oe}),Es=(0,f.object)({queryInsights:(0,f.optional)(cr),streams:(0,f.optional)(cr)}),Ye=(0,f.pipe)((0,f.number)(),(0,f.integer)(),(0,f.minValue)(1)),Rs=(0,f.object)({database:ar,http:ir,ppg:ir,shadowDatabase:ar}),Ts=(0,f.object)({databasePort:Ye,experimental:(0,f.optional)(Es),exports:(0,f.optional)(Rs),name:(0,f.pipe)((0,f.string)(),(0,f.minLength)(1)),pid:(0,f.optional)((0,f.pipe)((0,f.number)(),(0,f.integer)(),(0,f.minValue)(0))),port:Ye,shadowDatabasePort:Ye,version:(0,f.literal)("1")}),rt=Symbol("initialize"),Xe="default",xs=new Set(["durable-streams"]),N=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(t){this._databasePort=t.databasePort??A,this.databaseConnectTimeoutMillis=t.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=t.databaseIdleTimeoutMillis??1/0,this.debug=t.debug??!1,this.dryRun=t.dryRun??!1,this.name=t.name??Xe,this.persistenceMode=t.persistenceMode,this.pid=t.pid??tt.process.pid,this.shadowDatabaseConnectTimeoutMillis=t.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=t.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=t.port??A,this._shadowDatabasePort=t.shadowDatabasePort??A,this._streamsPort=t.streamsPort??A}static async createExclusively(t){let r=t?.dryRun!==!0&&t?.persistenceMode==="stateful"?new se(t):new Ze(t);return await r[rt](),r}static async fromServerDump(t){let{debug:r,name:n=Xe}=t??{},s=ne(n),o=se.getServerDumpPath(s),a=await Yt(o);if(a==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(a));let{issues:i,output:c,success:l}=(0,f.safeParse)((0,f.pipe)((0,f.string)(),(0,f.parseJson)(),Ts),a);if(!l)throw r&&console.debug(`[State] Invalid server dump file at "${o}":
14
+ ${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new se({databasePort:c.databasePort,debug:r,dryRun:!1,name:n,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(t){let{debug:r,globs:n}=t??{},s=(0,G.join)(ne(Xe),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let o=(await Zt(s,n)).filter(a=>!xs.has(a));return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(a=>we(a,t)))}get databasePort(){return this._databasePort}set databasePort(t){this.#r("databasePort",t)}get port(){return this._port}set port(t){this.#r("port",t)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(t){this.#r("shadowDatabasePort",t)}#r(t,r){if(r<0||!Number.isInteger(r))throw new Error(`Invalid port number: ${r}`);let n=`_${t}`;if(this[n]!==W&&this[n]!==r)throw new Error(`\`${t}\` is already set to ${this[n]}, cannot change it to ${r}`);this[n]=r}},Ze=class extends N{constructor(t){super({...t,databasePort:t?.databasePort||W,persistenceMode:"stateless",port:t?.port||W,shadowDatabasePort:t?.shadowDatabasePort||W,streamsPort:t?.streamsPort||W})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[rt](){let t;try{t=await N.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),t=[]}let r=await je({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort}async close(){}async writeServerDump(){}},se=class e extends N{#r;#e;#t;#s;#o;#a;#n;constructor(t){super({...t,persistenceMode:"stateful"}),this.#a=!1,this.#e=ne(this.name),this.#r=(0,G.join)(this.#e,"db_dump.bak"),this.#t=(0,G.join)(this.#e,".lock"),this.#s=(0,G.join)(this.#e,".pglite"),this.#n=t?.serverDump??null,this.#o=e.getServerDumpPath(this.#e)}static getServerDumpPath(t){return(0,G.join)(t,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get experimental(){return this.#n?.experimental}get pgliteDataDirPath(){return this.#s}async[rt](){await Xt(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,Z.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let t=await N.scan({debug:this.debug,onlyMetadata:!0}),r=await je({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort,await this.writeServerDump()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ELOCKED"?new ae(this):t}}async close(){if(!this.#a)try{await(0,Z.unlock)(this.#e,{lockfilePath:this.#t}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(t){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,t),t}}async writeServerDump(t,r){this.#n={name:this.name,version:"1",pid:tt.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:t},await(0,lr.writeFile)(this.#o,`${JSON.stringify(this.#n,null,2)}
15
+ `,{encoding:"utf-8"})}};async function we(e,t){let{debug:r,onlyMetadata:n}=t||{},s=typeof e=="string"?e:e.name,o=typeof e!="string"?e:void 0,a={databasePort:o?.databasePort??-1,experimental:o?.experimental,exports:o?.exports,name:s,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let i=o||await N.fromServerDump({debug:r,name:s});if(!i)return r&&console.debug(`[State] no server state found for name: ${s}`),{...a,status:"no_such_server"};a.databasePort=i.databasePort,a.experimental=i.experimental,a.exports=i.exports,a.pid=i.pid,a.port=i.port,a.shadowDatabasePort=i.shadowDatabasePort;let{exports:c,pid:l}=i;if(n)return{...a,status:"unknown"};if(!tr(l,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${l}`),{...a,status:"not_running"};let u=ne(s);try{if(!await(0,Z.check)(u,{lockfilePath:(0,G.join)(u,".lock")}))return r&&console.debug(`[State] server state for "${s}" is not locked, indicating it is not running.`),{...a,status:"not_running"}}catch(y){r&&console.error(`[State] server state for "${s}" failed to check lock:`,y)}if(!c)return{...a,status:"starting_up"};let{http:g}=c,d=await fetch(`${g.url}/health`,{headers:{connection:"close"}});if(!d.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(d)}`),{...a,status:"not_running"};let p=await d.json();return p.name!==e?(r&&console.debug(`[State] server state for "${s}" has mismatched health response: ${JSON.stringify(p)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${e}" is live: ${JSON.stringify(p)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${s}":`,i),{...a,status:"error"}}}function nt(e){let{status:t}=e;return t==="running"||t==="starting_up"}var et=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},ae=class extends et{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return N.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};function ve(e){return{databaseUrl:e.database.prismaORMConnectionString??e.database.connectionString,prismaPostgresUrl:e.ppg.url,shadowDatabaseUrl:e.shadowDatabase.prismaORMConnectionString??e.shadowDatabase.connectionString}}m();var Ds="DATABASE_URL",Is="SHADOW_DATABASE_URL";function ur(e,t={}){let{databaseUrl:r=Ds,prismaPostgresUrl:n=!1,shadowDatabaseUrl:s=Is}=t,o=ve(e);return[[r,o.databaseUrl],[s,o.shadowDatabaseUrl],[n,o.prismaPostgresUrl]].filter(i=>typeof i[0]=="string"&&i[0].length>0).map(([i,c])=>({name:i,value:c}))}function dr(e,t,r={}){let n=[],s=[],o=[];for(let a of e){let i=t[a.name],c=i!=null&&i!=="";if(c&&i===a.value){s.push(a);continue}if(c&&!r.override){o.push(a);continue}t[a.name]=a.value,n.push(a)}return{applied:n,retained:s,skipped:o}}m();m();m();var zn=require("timers/promises");m();st();m();var _e=require("net"),Hr=require("path"),Fr=require("pathe/utils");X();Se();m();var at=require("perf_hooks"),Tr=require("@electric-sql/pglite");m();var yr=require("buffer"),gr=500,fr=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,Os=new RegExp(`(?:${fr.source}\\.)*${fr.source}`),Ns=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${Os.source})`,"gi"),Ms=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,hr=/prismaQuery='([^']+)'/,Ls=new Set([Q(`
14
16
  select b.oid, b.typarray
15
17
  from pg_catalog.pg_type a
16
18
  left join pg_catalog.pg_type b on b.oid = a.typelem
17
19
  where a.typcategory = $1
18
20
  group by b.oid, b.typarray
19
21
  order by b.oid
20
- `),Q('GRANT "pg_write_all_data" TO "prisma_application"'),Q("SELECT SUM(reads)::BIGINT AS reads, SUM(writes)::BIGINT AS writes, SUM(COALESCE(extends, $1))::BIGINT AS extends FROM pg_stat_io"),Q("SELECT pg_database_size(current_database())::BIGINT, SUM(pg_total_relation_size(relid))::BIGINT AS pg_total_relation_size FROM pg_stat_user_tables"),Q("SELECT COUNT(*) AS cnt FROM pg_stat_activity WHERE pid <> pg_backend_pid() and xact_start notnull")]),Is=[/^BEGIN\b/i,/^COMMIT\b/i,/^ROLLBACK\b/i,/^SAVEPOINT\b/i,/^RELEASE\b/i,/^SET\b/i,/^SHOW\b/i,/^DISCARD\b/i,/^DEALLOCATE\b/i,/^CLOSE\b/i,/^CREATE EXTENSION\b/i,/^WITH state_assign\b/i];function mr(){return{generatedAt:Date.now(),queries:[]}}function Q(e){return e.replace(/\s+/g," ").trim()}function pr(e){return Sr(Q(e))}function gr(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?Sr(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function As(e){let t=new Set;for(let r of e.matchAll(Ts)){let n=r[1];if(!n)continue;let s;for(let o of n.matchAll(xs))s=o[1]??o[2]??o[3]??o[4];s&&!s.startsWith("pg_")&&t.add(s)}return Array.from(t)}function _s(e){return Ds.has(e)?!0:Is.some(t=>t.test(e))}function fr(e){if(_s(Q(e)))return null;let t=As(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function Ve(e){if(Array.isArray(e))return e.map(Ve);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Ve(n)]))}return e}function hr(e){let t=e.match(ur);if(!t?.[1])return{cleanedSql:Q(e),prismaQueryInfo:null};let r=e.replace(ur,"");r=r.replace(/,\s*,/g,",").replace(/\/\*\s*,/g,"/*").replace(/,\s*\*\//g,"*/").replace(/\/\*\s*\*\//g,"").replace(/\s+/g," ").trim();let n=decodeURIComponent(t[1]),s=n.indexOf(":");if(s===-1)return{cleanedSql:r,prismaQueryInfo:{action:n,isRaw:!0}};let o=n.slice(0,s),a=n.slice(s+1),i=o.indexOf("."),c=i===-1?void 0:o.slice(0,i),l=i===-1?o:o.slice(i+1);if(!l)return{cleanedSql:r,prismaQueryInfo:null};let u;try{u=Ve(JSON.parse(dr.Buffer.from(a,"base64url").toString("utf8")))}catch{u=void 0}return{cleanedSql:r,prismaQueryInfo:{action:l,isRaw:!1,model:c,payload:u}}}function yr(e,t={}){let r=new Set(t.excludeApplications??[]),n=Os(t.limit),s=typeof t.since=="number"&&Number.isFinite(t.since)?t.since:null,o=new Map;for(let i of e){if(i.applicationName&&r.has(i.applicationName))continue;let c=Date.parse(i.timestamp);if(!Number.isFinite(c))continue;let l=`${i.queryId}:${i.groupKey??""}`,u=o.get(l);if(!u){o.set(l,{count:1,duration:i.durationMs,groupKey:i.groupKey,id:l,lastSeen:c,maxDurationMs:i.durationMs,minDurationMs:i.durationMs,prismaQueryInfo:i.prismaQueryInfo,query:i.query,queryId:i.queryId,reads:i.reads,rowsReturned:i.rowsReturned,tables:i.tables,totalDurationMs:i.durationMs});continue}u.count+=1,u.lastSeen=Math.max(u.lastSeen,c),u.maxDurationMs=Math.max(u.maxDurationMs??i.durationMs,i.durationMs),u.minDurationMs=Math.min(u.minDurationMs??i.durationMs,i.durationMs),u.reads+=i.reads,u.rowsReturned+=i.rowsReturned,u.totalDurationMs+=i.durationMs,u.duration=u.totalDurationMs/u.count,!u.prismaQueryInfo&&i.prismaQueryInfo&&(u.prismaQueryInfo=i.prismaQueryInfo),u.tables.length===0&&i.tables.length>0&&(u.tables=i.tables)}let a=Array.from(o.values()).filter(i=>s===null||i.lastSeen>=s).sort((i,c)=>c.lastSeen-i.lastSeen).slice(0,n).map(({totalDurationMs:i,...c})=>c);return{generatedAt:Date.now(),queries:a}}function Os(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,cr):cr}function Sr(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)&4294967295;return(t>>>0).toString(36)}var Pe=new WeakMap;function Pr(e){let t=Pe.get(e);if(t&&!t.closed)return t.bridge;let r=Ns(e),n={bridge:{close:()=>(n.closed||(n.closed=!0,n.sessions.clear(),n.subscribers.clear(),n.queryQueue.enqueue=n.originalEnqueue,n.queryQueue.clearQueueForHandler=n.originalClearQueueForHandler,Pe.delete(e)),Promise.resolve()),subscribe:s=>(n.subscribers.add(s),()=>{n.subscribers.delete(s)})},closed:!1,originalClearQueueForHandler:r.clearQueueForHandler.bind(r),originalEnqueue:r.enqueue.bind(r),queryQueue:r,sessions:new Map,subscribers:new Set};return r.clearQueueForHandler=s=>{n.sessions.delete(s),n.originalClearQueueForHandler(s)},r.enqueue=async(s,o,a)=>{let i=Ms(n,s),c=$s(o);Ls(i,c);let l=Bs(i,c);if(!l)return await n.originalEnqueue(s,o,a);let u={commandTags:[],dataRowCount:0},g=new br.protocol.Parser,d=Ke.performance.now(),p=await n.originalEnqueue(s,o,v=>{g.parse(v,re=>{Fs(u,re)}),a(v)}),y=Math.max(0,Ke.performance.now()-d);return Ws(n,{applicationName:l.applicationName,durationMs:y,query:l.query,responseStats:u}),p},Pe.set(e,n),n.bridge}async function wr(e){await Pe.get(e)?.bridge.close()}function Ns(e){let t=e.queryQueue;if(!t||typeof t.enqueue!="function"||typeof t.clearQueueForHandler!="function")throw new Error("PGLiteSocketServer query queue is unavailable for query insights capture");return t}function Ms(e,t){let r=e.sessions.get(t);if(r)return r;let n={applicationName:null,portals:new Map,statements:new Map};return e.sessions.set(t,n),n}function Ls(e,t){if(t)switch(t.kind){case"startup":e.applicationName=t.applicationName;return;case"parse":e.statements.set(t.statementName,t.query);return;case"bind":{let r=e.statements.get(t.statementName);r&&e.portals.set(t.portalName,r);return}case"close":t.target==="portal"?e.portals.delete(t.name):e.statements.delete(t.name);return;default:return}}function Bs(e,t){if(!t)return null;if(t.kind==="query")return{applicationName:e.applicationName,query:t.query};if(t.kind==="execute"){let r=e.portals.get(t.portalName);return r?{applicationName:e.applicationName,query:r}:null}return null}function $s(e){let t=Buffer.from(e);if(t.length<4)return null;let r=t.readInt32BE(0);if(t.length>=8&&r===t.length){let s=t.readInt32BE(4);if(s===196608||s===196608)return ks(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return Us(t);case"P":return Cs(t);case"B":return Qs(t);case"E":return qs(t);case"C":return Hs(t);default:return null}}function ks(e){let t=8,r=null;for(;t<e.length-1;){let n=B(e,t);if(!n||n.value==="")break;t=n.nextOffset;let s=B(e,t);if(!s)break;t=s.nextOffset,n.value==="application_name"&&(r=s.value)}return{applicationName:r,kind:"startup"}}function Us(e){let t=B(e,5);return t?{kind:"query",query:t.value}:null}function Cs(e){let t=B(e,5);if(!t)return null;let r=B(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function Qs(e){let t=B(e,5);if(!t)return null;let r=B(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function qs(e){let t=B(e,5);return t?{kind:"execute",portalName:t.value}:null}function Hs(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=B(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function B(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function Fs(e,t){if(t.name==="dataRow"){e.dataRowCount+=1;return}t.name==="commandComplete"&&typeof t.text=="string"&&t.text.length>0&&e.commandTags.push(t.text)}function Ws(e,t){let r=hr(t.query),n=fr(r.cleanedSql);if(!n)return;let s=pr(r.cleanedSql),o={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:gr(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:s,reads:0,rowsReturned:Gs(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let a of e.subscribers)a([o])}function Gs(e){let t=e.commandTags.reduce((r,n)=>r+js(n),0);return Math.max(t,e.dataRowCount)}function js(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}m();var H=require("fs"),q=require("fs/promises"),Er=require("module"),Rr=require("path"),$=require("url"),Vs=(0,Er.createRequire)(h),Ks=["initdb.wasm","pglite.data","pglite.wasm"],Je="pglite-seed.tar.gz",Tr={amcheck:"amcheck.tar.gz",bloom:"bloom.tar.gz",btree_gin:"btree_gin.tar.gz",btree_gist:"btree_gist.tar.gz",citext:"citext.tar.gz",cube:"cube.tar.gz",dict_int:"dict_int.tar.gz",dict_xsyn:"dict_xsyn.tar.gz",earthdistance:"earthdistance.tar.gz",file_fdw:"file_fdw.tar.gz",fuzzystrmatch:"fuzzystrmatch.tar.gz",hstore:"hstore.tar.gz",intarray:"intarray.tar.gz",isn:"isn.tar.gz",lo:"lo.tar.gz",ltree:"ltree.tar.gz",pageinspect:"pageinspect.tar.gz",pg_buffercache:"pg_buffercache.tar.gz",pg_freespacemap:"pg_freespacemap.tar.gz",pg_surgery:"pg_surgery.tar.gz",pg_trgm:"pg_trgm.tar.gz",pg_visibility:"pg_visibility.tar.gz",pg_walinspect:"pg_walinspect.tar.gz",seg:"seg.tar.gz",tablefunc:"tablefunc.tar.gz",tcn:"tcn.tar.gz",tsm_system_rows:"tsm_system_rows.tar.gz",tsm_system_time:"tsm_system_time.tar.gz",unaccent:"unaccent.tar.gz",uuid_ossp:"uuid-ossp.tar.gz",vector:"vector.tar.gz"},zs=[...Ks.map(e=>({fileName:e,kind:"core",name:e})),{fileName:Je,kind:"core",name:Je},...Object.entries(Tr).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],Ee=new Map,Js=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),we=null;async function Ye(){await so();let e=xr();if(e)return await eo(e),await Ys(e);let t=ro(),r=t.href,n=Ee.get(r);return n||(n=Xs(t),Ee.set(r,n)),await n}async function Ys(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=Ee.get(t);return r||(r=Zs(e),Ee.set(t,r)),await r}async function Xs(e){let t=Re(new URL("./runtime-assets/",h)),[r,n,s]=await Promise.all([(0,q.readFile)(ve("pglite.data",e,t)),(0,q.readFile)(ve(Je,e,t)),(0,q.readFile)(ve("pglite.wasm",e,t))]),o=Dr();return{extensions:Object.fromEntries(Object.entries(Tr).map(([a,i])=>[a,ve(i,e,t)])),fsBundle:new Blob([Uint8Array.from(r)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await o.compile(s)}}async function Zs(e){let[t,r,n]=await Promise.all([ze(e.fsBundle),ze(e.loadDataDir),ze(e.wasmModule)]),s=Dr();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(r)]),wasmModule:await s.compile(n)}}async function eo(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",Re(new URL("./",e.initdbWasm))),r=(0,$.fileURLToPath)(t);(0,H.existsSync)(r)||await(0,q.copyFile)((0,$.fileURLToPath)(e.initdbWasm),r)}function Re(e){return e instanceof URL?vr(e):vr((0,$.pathToFileURL)(e))}function vr(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function to(){let e=Vs.resolve("@electric-sql/pglite");return Re((0,Rr.dirname)(e))}function ro(){let e=Re(new URL("./",h));if(no(e))return e;if(oo())return to();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function no(e){return zs.every(t=>(0,H.existsSync)((0,$.fileURLToPath)(new URL(t.fileName,e))))}function xr(){return globalThis[Js]??null}async function so(){!ao()||xr()||(we||(we=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw we=null,e})),await we)}function oo(){let e=(0,$.fileURLToPath)(new URL("../package.json",h));if(!(0,H.existsSync)(e))return!1;try{return JSON.parse((0,H.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function ao(){return typeof globalThis.Bun<"u"}function Dr(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function ze(e){if(e.protocol==="file:")return await(0,q.readFile)(e);let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch runtime asset ${e.href}: ${t.status} ${t.statusText}`);return new Uint8Array(await t.arrayBuffer())}function ve(e,t,r){let n=new URL(e,t);if((0,H.existsSync)((0,$.fileURLToPath)(n)))return n;if(r){let s=new URL(e,r);if((0,H.existsSync)((0,$.fileURLToPath)(s)))return s}return n}m();var et=require("@electric-sql/pglite"),N="_prisma_dev_wal",Ze="events",_r="install_all_triggers",Ir="capture_event",Ar="prisma_dev_wal_capture",se=new WeakMap,io=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function tt(e,t){let r=se.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),s=e.execProtocolRawStream.bind(e),o={bridge:{close:async()=>{o.closed||(o.closed=!0,o.subscribers.clear(),e.execProtocolRaw===a&&(e.execProtocolRaw=n),e.execProtocolRawStream===i&&(e.execProtocolRawStream=s),await o.pollPromise,se.delete(e))},poll:async()=>{await Xe(o,e)},subscribe:c=>(o.subscribers.add(c),()=>{o.subscribers.delete(c)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},a=async(c,l)=>{let u=await n(c,l);return!o.closed&&o.suppressDepth===0&&Nr(u)&&Xe(o,e),u},i=async(c,l)=>{let u=[],g=new et.protocol.Parser,d=l?.onRawData;await s(c,{...l,onRawData:p=>{g.parse(p,y=>{u.push(y)}),d?.(p)}}),!o.closed&&o.suppressDepth===0&&rt(u)&&Xe(o,e)};return e.execProtocolRaw=a,e.execProtocolRawStream=i,se.set(e,o),await Mr(o,e),o.bridge}async function Or(e){let t=se.get(e);t&&await t.bridge.close()}function rt(e){for(let t of e){if(t.name!=="commandComplete"||typeof t.text!="string")continue;let r=t.text.split(/\s+/,1)[0]?.toUpperCase();if(r&&io.has(r))return!0}return!1}function Nr(e){if(e.length===0)return!1;let t=[];return new et.protocol.Parser().parse(e,n=>{t.push(n)}),rt(t)}async function Mr(e,t){e.ensureInfrastructurePromise??=nt(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${N}"`),await t.exec(`
21
- CREATE TABLE IF NOT EXISTS "${N}"."${Ze}" (
22
+ `),Q('GRANT "pg_write_all_data" TO "prisma_application"'),Q("SELECT SUM(reads)::BIGINT AS reads, SUM(writes)::BIGINT AS writes, SUM(COALESCE(extends, $1))::BIGINT AS extends FROM pg_stat_io"),Q("SELECT pg_database_size(current_database())::BIGINT, SUM(pg_total_relation_size(relid))::BIGINT AS pg_total_relation_size FROM pg_stat_user_tables"),Q("SELECT COUNT(*) AS cnt FROM pg_stat_activity WHERE pid <> pg_backend_pid() and xact_start notnull")]),Bs=[/^BEGIN\b/i,/^COMMIT\b/i,/^ROLLBACK\b/i,/^SAVEPOINT\b/i,/^RELEASE\b/i,/^SET\b/i,/^SHOW\b/i,/^DISCARD\b/i,/^DEALLOCATE\b/i,/^CLOSE\b/i,/^CREATE EXTENSION\b/i,/^WITH state_assign\b/i];function Sr(){return{generatedAt:Date.now(),queries:[]}}function Q(e){return e.replace(/\s+/g," ").trim()}function br(e){return Rr(Q(e))}function Pr(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?Rr(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function $s(e){let t=new Set;for(let r of e.matchAll(Ns)){let n=r[1];if(!n)continue;let s;for(let o of n.matchAll(Ms))s=o[1]??o[2]??o[3]??o[4];s&&!s.startsWith("pg_")&&t.add(s)}return Array.from(t)}function ks(e){return Ls.has(e)?!0:Bs.some(t=>t.test(e))}function wr(e){if(ks(Q(e)))return null;let t=$s(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function ot(e){if(Array.isArray(e))return e.map(ot);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,ot(n)]))}return e}function vr(e){let t=e.match(hr);if(!t?.[1])return{cleanedSql:Q(e),prismaQueryInfo:null};let r=e.replace(hr,"");r=r.replace(/,\s*,/g,",").replace(/\/\*\s*,/g,"/*").replace(/,\s*\*\//g,"*/").replace(/\/\*\s*\*\//g,"").replace(/\s+/g," ").trim();let n=decodeURIComponent(t[1]),s=n.indexOf(":");if(s===-1)return{cleanedSql:r,prismaQueryInfo:{action:n,isRaw:!0}};let o=n.slice(0,s),a=n.slice(s+1),i=o.indexOf("."),c=i===-1?void 0:o.slice(0,i),l=i===-1?o:o.slice(i+1);if(!l)return{cleanedSql:r,prismaQueryInfo:null};let u;try{u=ot(JSON.parse(yr.Buffer.from(a,"base64url").toString("utf8")))}catch{u=void 0}return{cleanedSql:r,prismaQueryInfo:{action:l,isRaw:!1,model:c,payload:u}}}function Er(e,t={}){let r=new Set(t.excludeApplications??[]),n=Cs(t.limit),s=typeof t.since=="number"&&Number.isFinite(t.since)?t.since:null,o=new Map;for(let i of e){if(i.applicationName&&r.has(i.applicationName))continue;let c=Date.parse(i.timestamp);if(!Number.isFinite(c))continue;let l=`${i.queryId}:${i.groupKey??""}`,u=o.get(l);if(!u){o.set(l,{count:1,duration:i.durationMs,groupKey:i.groupKey,id:l,lastSeen:c,maxDurationMs:i.durationMs,minDurationMs:i.durationMs,prismaQueryInfo:i.prismaQueryInfo,query:i.query,queryId:i.queryId,reads:i.reads,rowsReturned:i.rowsReturned,tables:i.tables,totalDurationMs:i.durationMs});continue}u.count+=1,u.lastSeen=Math.max(u.lastSeen,c),u.maxDurationMs=Math.max(u.maxDurationMs??i.durationMs,i.durationMs),u.minDurationMs=Math.min(u.minDurationMs??i.durationMs,i.durationMs),u.reads+=i.reads,u.rowsReturned+=i.rowsReturned,u.totalDurationMs+=i.durationMs,u.duration=u.totalDurationMs/u.count,!u.prismaQueryInfo&&i.prismaQueryInfo&&(u.prismaQueryInfo=i.prismaQueryInfo),u.tables.length===0&&i.tables.length>0&&(u.tables=i.tables)}let a=Array.from(o.values()).filter(i=>s===null||i.lastSeen>=s).sort((i,c)=>c.lastSeen-i.lastSeen).slice(0,n).map(({totalDurationMs:i,...c})=>c);return{generatedAt:Date.now(),queries:a}}function Cs(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,gr):gr}function Rr(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)&4294967295;return(t>>>0).toString(36)}var Re=new WeakMap;function xr(e){let t=Re.get(e);if(t&&!t.closed)return t.bridge;let r=Us(e),n={bridge:{close:()=>(n.closed||(n.closed=!0,n.sessions.clear(),n.subscribers.clear(),n.queryQueue.enqueue=n.originalEnqueue,n.queryQueue.clearQueueForHandler=n.originalClearQueueForHandler,Re.delete(e)),Promise.resolve()),subscribe:s=>(n.subscribers.add(s),()=>{n.subscribers.delete(s)})},closed:!1,originalClearQueueForHandler:r.clearQueueForHandler.bind(r),originalEnqueue:r.enqueue.bind(r),queryQueue:r,sessions:new Map,subscribers:new Set};return r.clearQueueForHandler=s=>{n.sessions.delete(s),n.originalClearQueueForHandler(s)},r.enqueue=async(s,o,a)=>{let i=Qs(n,s),c=Fs(o);qs(i,c);let l=Hs(i,c);if(!l)return await n.originalEnqueue(s,o,a);let u={commandTags:[],dataRowCount:0},g=new Tr.protocol.Parser,d=at.performance.now(),p=await n.originalEnqueue(s,o,v=>{g.parse(v,re=>{Js(u,re)}),a(v)}),y=Math.max(0,at.performance.now()-d);return Ys(n,{applicationName:l.applicationName,durationMs:y,query:l.query,responseStats:u}),p},Re.set(e,n),n.bridge}async function Dr(e){await Re.get(e)?.bridge.close()}function Us(e){let t=e.queryQueue;if(!t||typeof t.enqueue!="function"||typeof t.clearQueueForHandler!="function")throw new Error("PGLiteSocketServer query queue is unavailable for query insights capture");return t}function Qs(e,t){let r=e.sessions.get(t);if(r)return r;let n={applicationName:null,portals:new Map,statements:new Map};return e.sessions.set(t,n),n}function qs(e,t){if(t)switch(t.kind){case"startup":e.applicationName=t.applicationName;return;case"parse":e.statements.set(t.statementName,t.query);return;case"bind":{let r=e.statements.get(t.statementName);r&&e.portals.set(t.portalName,r);return}case"close":t.target==="portal"?e.portals.delete(t.name):e.statements.delete(t.name);return;default:return}}function Hs(e,t){if(!t)return null;if(t.kind==="query")return{applicationName:e.applicationName,query:t.query};if(t.kind==="execute"){let r=e.portals.get(t.portalName);return r?{applicationName:e.applicationName,query:r}:null}return null}function Fs(e){let t=Buffer.from(e);if(t.length<4)return null;let r=t.readInt32BE(0);if(t.length>=8&&r===t.length){let s=t.readInt32BE(4);if(s===196608||s===196608)return Ws(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return Gs(t);case"P":return js(t);case"B":return Vs(t);case"E":return Ks(t);case"C":return zs(t);default:return null}}function Ws(e){let t=8,r=null;for(;t<e.length-1;){let n=B(e,t);if(!n||n.value==="")break;t=n.nextOffset;let s=B(e,t);if(!s)break;t=s.nextOffset,n.value==="application_name"&&(r=s.value)}return{applicationName:r,kind:"startup"}}function Gs(e){let t=B(e,5);return t?{kind:"query",query:t.value}:null}function js(e){let t=B(e,5);if(!t)return null;let r=B(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function Vs(e){let t=B(e,5);if(!t)return null;let r=B(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function Ks(e){let t=B(e,5);return t?{kind:"execute",portalName:t.value}:null}function zs(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=B(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function B(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function Js(e,t){if(t.name==="dataRow"){e.dataRowCount+=1;return}t.name==="commandComplete"&&typeof t.text=="string"&&t.text.length>0&&e.commandTags.push(t.text)}function Ys(e,t){let r=vr(t.query),n=wr(r.cleanedSql);if(!n)return;let s=br(r.cleanedSql),o={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:Pr(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:s,reads:0,rowsReturned:Xs(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let a of e.subscribers)a([o])}function Xs(e){let t=e.commandTags.reduce((r,n)=>r+Zs(n),0);return Math.max(t,e.dataRowCount)}function Zs(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}m();var H=require("fs"),q=require("fs/promises"),Ar=require("module"),_r=require("path"),$=require("url"),eo=(0,Ar.createRequire)(h),to=["initdb.wasm","pglite.data","pglite.wasm"],ct="pglite-seed.tar.gz",Or={amcheck:"amcheck.tar.gz",bloom:"bloom.tar.gz",btree_gin:"btree_gin.tar.gz",btree_gist:"btree_gist.tar.gz",citext:"citext.tar.gz",cube:"cube.tar.gz",dict_int:"dict_int.tar.gz",dict_xsyn:"dict_xsyn.tar.gz",earthdistance:"earthdistance.tar.gz",file_fdw:"file_fdw.tar.gz",fuzzystrmatch:"fuzzystrmatch.tar.gz",hstore:"hstore.tar.gz",intarray:"intarray.tar.gz",isn:"isn.tar.gz",lo:"lo.tar.gz",ltree:"ltree.tar.gz",pageinspect:"pageinspect.tar.gz",pg_buffercache:"pg_buffercache.tar.gz",pg_freespacemap:"pg_freespacemap.tar.gz",pg_surgery:"pg_surgery.tar.gz",pg_trgm:"pg_trgm.tar.gz",pg_visibility:"pg_visibility.tar.gz",pg_walinspect:"pg_walinspect.tar.gz",seg:"seg.tar.gz",tablefunc:"tablefunc.tar.gz",tcn:"tcn.tar.gz",tsm_system_rows:"tsm_system_rows.tar.gz",tsm_system_time:"tsm_system_time.tar.gz",unaccent:"unaccent.tar.gz",uuid_ossp:"uuid-ossp.tar.gz",vector:"vector.tar.gz"},ro=[...to.map(e=>({fileName:e,kind:"core",name:e})),{fileName:ct,kind:"core",name:ct},...Object.entries(Or).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],De=new Map,no=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),Te=null;async function lt(){await mo();let e=Nr();if(e)return await io(e),await so(e);let t=lo(),r=t.href,n=De.get(r);return n||(n=oo(t),De.set(r,n)),await n}async function so(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=De.get(t);return r||(r=ao(e),De.set(t,r)),await r}async function oo(e){let t=Ie(new URL("./runtime-assets/",h)),[r,n,s]=await Promise.all([(0,q.readFile)(xe("pglite.data",e,t)),(0,q.readFile)(xe(ct,e,t)),(0,q.readFile)(xe("pglite.wasm",e,t))]),o=Mr();return{extensions:Object.fromEntries(Object.entries(Or).map(([a,i])=>[a,xe(i,e,t)])),fsBundle:new Blob([Uint8Array.from(r)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await o.compile(s)}}async function ao(e){let[t,r,n]=await Promise.all([it(e.fsBundle),it(e.loadDataDir),it(e.wasmModule)]),s=Mr();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(r)]),wasmModule:await s.compile(n)}}async function io(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",Ie(new URL("./",e.initdbWasm))),r=(0,$.fileURLToPath)(t);(0,H.existsSync)(r)||await(0,q.copyFile)((0,$.fileURLToPath)(e.initdbWasm),r)}function Ie(e){return e instanceof URL?Ir(e):Ir((0,$.pathToFileURL)(e))}function Ir(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function co(){let e=eo.resolve("@electric-sql/pglite");return Ie((0,_r.dirname)(e))}function lo(){let e=Ie(new URL("./",h));if(uo(e))return e;if(po())return co();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function uo(e){return ro.every(t=>(0,H.existsSync)((0,$.fileURLToPath)(new URL(t.fileName,e))))}function Nr(){return globalThis[no]??null}async function mo(){!go()||Nr()||(Te||(Te=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw Te=null,e})),await Te)}function po(){let e=(0,$.fileURLToPath)(new URL("../package.json",h));if(!(0,H.existsSync)(e))return!1;try{return JSON.parse((0,H.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function go(){return typeof globalThis.Bun<"u"}function Mr(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function it(e){if(e.protocol==="file:")return await(0,q.readFile)(e);let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch runtime asset ${e.href}: ${t.status} ${t.statusText}`);return new Uint8Array(await t.arrayBuffer())}function xe(e,t,r){let n=new URL(e,t);if((0,H.existsSync)((0,$.fileURLToPath)(n)))return n;if(r){let s=new URL(e,r);if((0,H.existsSync)((0,$.fileURLToPath)(s)))return s}return n}m();var mt=require("@electric-sql/pglite"),M="_prisma_dev_wal",dt="events",$r="install_all_triggers",Lr="capture_event",Br="prisma_dev_wal_capture",ie=new WeakMap,fo=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function pt(e,t){let r=ie.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),s=e.execProtocolRawStream.bind(e),o={bridge:{close:async()=>{o.closed||(o.closed=!0,o.subscribers.clear(),e.execProtocolRaw===a&&(e.execProtocolRaw=n),e.execProtocolRawStream===i&&(e.execProtocolRawStream=s),await o.pollPromise,ie.delete(e))},poll:async()=>{await ut(o,e)},subscribe:c=>(o.subscribers.add(c),()=>{o.subscribers.delete(c)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},a=async(c,l)=>{let u=await n(c,l);return!o.closed&&o.suppressDepth===0&&Cr(u)&&ut(o,e),u},i=async(c,l)=>{let u=[],g=new mt.protocol.Parser,d=l?.onRawData;await s(c,{...l,onRawData:p=>{g.parse(p,y=>{u.push(y)}),d?.(p)}}),!o.closed&&o.suppressDepth===0&&gt(u)&&ut(o,e)};return e.execProtocolRaw=a,e.execProtocolRawStream=i,ie.set(e,o),await Ur(o,e),o.bridge}async function kr(e){let t=ie.get(e);t&&await t.bridge.close()}function gt(e){for(let t of e){if(t.name!=="commandComplete"||typeof t.text!="string")continue;let r=t.text.split(/\s+/,1)[0]?.toUpperCase();if(r&&fo.has(r))return!0}return!1}function Cr(e){if(e.length===0)return!1;let t=[];return new mt.protocol.Parser().parse(e,n=>{t.push(n)}),gt(t)}async function Ur(e,t){e.ensureInfrastructurePromise??=ft(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${M}"`),await t.exec(`
23
+ CREATE TABLE IF NOT EXISTS "${M}"."${dt}" (
22
24
  id BIGSERIAL PRIMARY KEY,
23
25
  txid BIGINT NOT NULL DEFAULT txid_current(),
24
26
  schema_name TEXT NOT NULL,
@@ -29,16 +31,16 @@ Received data: ${u}`));n({childProcess:a,url:`http://${p}:${y}`})},c=u=>{this.#t
29
31
  created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
30
32
  )
31
33
  `),await t.exec(`
32
- CREATE OR REPLACE FUNCTION "${N}"."${Ir}"()
34
+ CREATE OR REPLACE FUNCTION "${M}"."${Lr}"()
33
35
  RETURNS trigger
34
36
  LANGUAGE plpgsql
35
37
  AS $$
36
38
  BEGIN
37
- IF TG_TABLE_SCHEMA = '${N}' THEN
39
+ IF TG_TABLE_SCHEMA = '${M}' THEN
38
40
  RETURN COALESCE(NEW, OLD);
39
41
  END IF;
40
42
 
41
- INSERT INTO "${N}"."${Ze}" (
43
+ INSERT INTO "${M}"."${dt}" (
42
44
  txid,
43
45
  schema_name,
44
46
  table_name,
@@ -59,7 +61,7 @@ Received data: ${u}`));n({childProcess:a,url:`http://${p}:${y}`})},c=u=>{this.#t
59
61
  END;
60
62
  $$;
61
63
  `),await t.exec(`
62
- CREATE OR REPLACE FUNCTION "${N}"."${_r}"()
64
+ CREATE OR REPLACE FUNCTION "${M}"."${$r}"()
63
65
  RETURNS void
64
66
  LANGUAGE plpgsql
65
67
  AS $$
@@ -71,7 +73,7 @@ Received data: ${u}`));n({childProcess:a,url:`http://${p}:${y}`})},c=u=>{this.#t
71
73
  FROM pg_class AS c
72
74
  JOIN pg_namespace AS n ON n.oid = c.relnamespace
73
75
  WHERE c.relkind IN ('r', 'p')
74
- AND n.nspname NOT IN ('${N}', 'information_schema', 'pg_catalog')
76
+ AND n.nspname NOT IN ('${M}', 'information_schema', 'pg_catalog')
75
77
  AND n.nspname NOT LIKE 'pg_temp_%'
76
78
  AND n.nspname NOT LIKE 'pg_toast%'
77
79
  LOOP
@@ -79,28 +81,28 @@ Received data: ${u}`));n({childProcess:a,url:`http://${p}:${y}`})},c=u=>{this.#t
79
81
  SELECT 1
80
82
  FROM pg_trigger
81
83
  WHERE tgrelid = target
82
- AND tgname = '${Ar}'
84
+ AND tgname = '${Br}'
83
85
  ) THEN
84
86
  CONTINUE;
85
87
  END IF;
86
88
 
87
89
  EXECUTE format(
88
- 'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${N}"."${Ir}"()',
89
- '${Ar}',
90
+ 'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${M}"."${Lr}"()',
91
+ '${Br}',
90
92
  target::text
91
93
  );
92
94
  END LOOP;
93
95
  END;
94
96
  $$;
95
- `),await Lr(e,t)}),await e.ensureInfrastructurePromise}async function Lr(e,t){await nt(e,t,async()=>{await t.query(`SELECT "${N}"."${_r}"()`)})}async function co(e,t){await Mr(e,t),await Lr(e,t);let r=await nt(e,t,async()=>await t.query(`
97
+ `),await Qr(e,t)}),await e.ensureInfrastructurePromise}async function Qr(e,t){await ft(e,t,async()=>{await t.query(`SELECT "${M}"."${$r}"()`)})}async function ho(e,t){await Ur(e,t),await Qr(e,t);let r=await ft(e,t,async()=>await t.query(`
96
98
  WITH drained AS (
97
- DELETE FROM "${N}"."${Ze}"
99
+ DELETE FROM "${M}"."${dt}"
98
100
  RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id
99
101
  )
100
102
  SELECT txid, schema_name, table_name, op, row_data, old_row_data
101
103
  FROM drained
102
104
  ORDER BY id
103
- `));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(lo);for(let s of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(s))try{s(n)}catch(o){console.error("[WAL bridge] subscriber failed",o)}})}async function Xe(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await co(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function nt(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&se.get(t)!==e&&(e.closed=!0)}}function lo(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:uo(e.op)}}function uo(e){switch(e.toLowerCase()){case"delete":return"delete";case"insert":return"insert";case"update":return"update";default:throw new Error(`Unsupported WAL bridge operation: ${e}`)}}var mo=10,Ur="127.0.0.1",Cr=128*1024*1024,Qr=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],S={connectionLimit:mo,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},po=`postgres://${S.username}:${S.password}@localhost`,st=new URLSearchParams({sslmode:S.sslMode}),qr=new URLSearchParams({...Object.fromEntries(st.entries()),connection_limit:String(S.connectionLimit),connect_timeout:String(S.connectTimeout),max_idle_connection_lifetime:String(S.maxIdleConnectionLifetime),pool_timeout:String(S.poolTimeout),socket_timeout:String(S.socketTimeout)});async function Hr(e){let{rows:t}=await e.query("SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = 'postgres') AS exists");t[0]?.exists?await e.exec(`ALTER ROLE ${S.username} WITH LOGIN SUPERUSER PASSWORD '${S.password}'`):await e.exec(`CREATE ROLE ${S.username} WITH LOGIN SUPERUSER PASSWORD '${S.password}'`),await e.exec(`SET ROLE ${S.username}`)}async function ot(e,t){if(e==="shadow_database"&&!t.dryRun)return await go(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?Wr(e,t,{db:null,port:r,server:null}):await Fr(e,t,{port:r,updateServerStatePort:!0})}async function go(e,t=async()=>await Fr("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,s=null,o=!1,a=new Set,i=(0,xe.createServer)(l),c=await fo(i,e.shadowDatabasePort);return e.shadowDatabasePort=c,r&&console.debug(`[shadow_database] lazy proxy listening on port ${c}`),{...S,attachWalEventBridge:()=>Promise.reject(new Error("WAL bridge is only available for the primary database server")),attachQueryInsightsBridge:()=>Promise.reject(new Error("Query insights are only available for the primary database server")),close:async()=>{o=!0;for(let p of a)p.destroy();a.clear();let d=[];try{await ho(i),r&&console.debug(`[shadow_database] lazy proxy stopped on port ${c}`)}catch(p){console.error("[shadow_database] lazy proxy stop error",p),d.push(p)}try{await s?.catch(()=>null),await n?.close()}catch(p){console.error("[shadow_database] backend close error",p),d.push(p)}if(d.length>0)throw new AggregateError(d,"Failed to close shadow_database properly")},connectionString:Te(c,st),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:c,prismaORMConnectionString:Te(c,qr),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${c} -U ${S.username} -d ${S.database}`};function l(d){a.add(d);let p=()=>{a.delete(d)};d.once("close",p),d.once("error",p),d.pause(),u(d)}async function u(d){try{let p=await g();if(o){d.destroy();return}let y=(0,xe.createConnection)({host:Ur,port:p.port});a.add(y);let v=()=>{a.delete(y)};y.once("close",v),y.once("error",v),d.once("close",()=>y.destroy()),d.once("error",()=>y.destroy()),y.once("error",()=>d.destroy()),y.once("connect",()=>{r&&console.debug(`[shadow_database] proxying connection to lazy backend on port ${p.port}`),d.resume(),d.pipe(y),y.pipe(d)})}catch(p){r&&console.error("[shadow_database] failed to start lazy backend",p),d.destroy(p instanceof Error?p:void 0)}}async function g(){if(n)return n;if(o)throw new Error("shadow_database is closed");return s||(r&&console.debug("[shadow_database] starting lazy backend..."),s=t().then(d=>(n=d,r&&console.debug(`[shadow_database] lazy backend started on port ${d.port}`),d)).catch(d=>{throw s=null,d})),await s}}async function Fr(e,t,r){let{debug:n}=t,{port:s,updateServerStatePort:o}=r,i=await(e==="shadow_database"?yo:Gr)(t.pgliteDataDirPath,n);n&&i.onNotification((d,p)=>{console.debug(`[${e}][${d}] ${p}`)});let{PGLiteSocketServer:c}=await import("@electric-sql/pglite-socket"),l=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis,u=new c({db:i,debug:n,idleTimeout:Number.isFinite(l)?l:0,inspect:n,maxConnections:S.connectionLimit,port:s});n&&(u.addEventListener("listening",d=>{let{detail:p}=d;console.debug(`[${e}] server listening on ${JSON.stringify(p)}`)}),u.addEventListener("connection",d=>{let{clientAddress:p,clientPort:y}=d.detail;console.debug(`[${e}] client connected from ${p}:${y}`)}),u.addEventListener("error",d=>{let{detail:p}=d;console.error(`[${e}] server error:`,p)}));try{await u.start()}catch(d){throw d instanceof Error&&"code"in d&&d.code==="EADDRINUSE"?new L(s):d}let g=Number(u.getServerConn().split(":").at(1));return o&&(t[e==="database"?"databasePort":"shadowDatabasePort"]=g),Wr(e,t,{db:i,port:g,server:u})}function Wr(e,t,r){let{debug:n}=t,{db:s,port:o,server:a}=r||{},i=new Map;return n&&console.debug(`[${e}] server started on port ${o}`),{...S,attachWalEventBridge:async()=>{if(e!=="database"||!s)throw new Error("WAL bridge is only available for the primary database server");return await tt(s)},attachQueryInsightsBridge:()=>{if(e!=="database"||!a)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(Pr(a))},close:async()=>{let c=[];try{await a?.stop(),n&&console.debug(`[${e}] server stopped on port ${o}`)}catch(l){console.error(`[${e}] server stop error`,l),c.push(l)}if(e==="database"){try{a&&await wr(a),n&&console.debug(`[${e}] closed query insights bridge`)}catch(l){console.error(`[${e}] query insights bridge close error`,l),c.push(l)}try{s&&await Or(s),n&&console.debug(`[${e}] closed WAL bridge`)}catch(l){console.error(`[${e}] WAL bridge close error`,l),c.push(l)}try{await s?.syncToFs(),n&&console.debug(`[${e}] synced to filesystem`)}catch(l){console.error(`[${e}] sync error`,l),c.push(l)}}try{await s?.close(),n&&console.debug(`[${e}] closed`)}catch(l){console.error(`[${e}] close error`,l),c.push(l)}if(c.length>0)throw new AggregateError(c,`Failed to close ${e} properly`)},connectionString:Te(o,st),dump:async c=>{e==="shadow_database"||!s||await bo({db:s,debug:n,destinationPath:c})},getPrimaryKeyColumns:async(c,l)=>{if(e==="shadow_database"||!s)throw new Error("Primary key resolution is only available for the primary database server");let u=`${c}.${l}`,g=i.get(u);return g||(g=So(s,c,l).catch(d=>{throw i.delete(u),d}),i.set(u,g)),await g},port:o,prismaORMConnectionString:Te(o,qr),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${o} -U ${S.username} -d ${S.database}`}}function Te(e,t){return`${po}:${e}/${S.database}?${t.toString()}`}async function Gr(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await Ye(),s=e==="memory://"||!await J((0,$r.join)(e,"PG_VERSION")),o=await r.create({database:S.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Cr,loadDataDir:s?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...Qr],wasmModule:n.wasmModule});return await Hr(o),o}async function fo(e,t){return await new Promise((r,n)=>{let s=i=>{if(a(),i.code==="EADDRINUSE"){n(new L(t));return}n(i)},o=()=>{let i=e.address();if(a(),!i||typeof i=="string"){n(new Error("Failed to determine TCP server port"));return}r(i.port)},a=()=>{e.off("error",s),e.off("listening",o)};e.once("error",s),e.once("listening",o),e.listen(t,Ur)})}async function ho(e){await new Promise((t,r)=>{e.close(n=>{let s=n;if(s&&s.code!=="ERR_SERVER_NOT_RUNNING"){r(s);return}t()})})}async function yo(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await Ye(),s=await r.create({database:S.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Cr,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...Qr],wasmModule:n.wasmModule});return await Hr(s),s}async function So(e,t,r){let{rows:n}=await e.query(`
105
+ `));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(yo);for(let s of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(s))try{s(n)}catch(o){console.error("[WAL bridge] subscriber failed",o)}})}async function ut(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await ho(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function ft(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&ie.get(t)!==e&&(e.closed=!0)}}function yo(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:So(e.op)}}function So(e){switch(e.toLowerCase()){case"delete":return"delete";case"insert":return"insert";case"update":return"update";default:throw new Error(`Unsupported WAL bridge operation: ${e}`)}}var bo=10,Wr="127.0.0.1",Gr=128*1024*1024,jr=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],S={connectionLimit:bo,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Po=`postgres://${S.username}:${S.password}@localhost`,ht=new URLSearchParams({sslmode:S.sslMode}),Vr=new URLSearchParams({...Object.fromEntries(ht.entries()),connection_limit:String(S.connectionLimit),connect_timeout:String(S.connectTimeout),max_idle_connection_lifetime:String(S.maxIdleConnectionLifetime),pool_timeout:String(S.poolTimeout),socket_timeout:String(S.socketTimeout)});async function Kr(e){let{rows:t}=await e.query("SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = 'postgres') AS exists");t[0]?.exists?await e.exec(`ALTER ROLE ${S.username} WITH LOGIN SUPERUSER PASSWORD '${S.password}'`):await e.exec(`CREATE ROLE ${S.username} WITH LOGIN SUPERUSER PASSWORD '${S.password}'`),await e.exec(`SET ROLE ${S.username}`)}async function yt(e,t){if(e==="shadow_database"&&!t.dryRun)return await wo(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?Jr(e,t,{db:null,port:r,server:null}):await zr(e,t,{port:r,updateServerStatePort:!0})}async function wo(e,t=async()=>await zr("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,s=null,o=!1,a=new Set,i=(0,_e.createServer)(l),c=await vo(i,e.shadowDatabasePort);return e.shadowDatabasePort=c,r&&console.debug(`[shadow_database] lazy proxy listening on port ${c}`),{...S,attachWalEventBridge:()=>Promise.reject(new Error("WAL bridge is only available for the primary database server")),attachQueryInsightsBridge:()=>Promise.reject(new Error("Query insights are only available for the primary database server")),close:async()=>{o=!0;for(let p of a)p.destroy();a.clear();let d=[];try{await Eo(i),r&&console.debug(`[shadow_database] lazy proxy stopped on port ${c}`)}catch(p){console.error("[shadow_database] lazy proxy stop error",p),d.push(p)}try{await s?.catch(()=>null),await n?.close()}catch(p){console.error("[shadow_database] backend close error",p),d.push(p)}if(d.length>0)throw new AggregateError(d,"Failed to close shadow_database properly")},connectionString:Ae(c,ht),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:c,prismaORMConnectionString:Ae(c,Vr),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${c} -U ${S.username} -d ${S.database}`};function l(d){a.add(d);let p=()=>{a.delete(d)};d.once("close",p),d.once("error",p),d.pause(),u(d)}async function u(d){try{let p=await g();if(o){d.destroy();return}let y=(0,_e.createConnection)({host:Wr,port:p.port});a.add(y);let v=()=>{a.delete(y)};y.once("close",v),y.once("error",v),d.once("close",()=>y.destroy()),d.once("error",()=>y.destroy()),y.once("error",()=>d.destroy()),y.once("connect",()=>{r&&console.debug(`[shadow_database] proxying connection to lazy backend on port ${p.port}`),d.resume(),d.pipe(y),y.pipe(d)})}catch(p){r&&console.error("[shadow_database] failed to start lazy backend",p),d.destroy(p instanceof Error?p:void 0)}}async function g(){if(n)return n;if(o)throw new Error("shadow_database is closed");return s||(r&&console.debug("[shadow_database] starting lazy backend..."),s=t().then(d=>(n=d,r&&console.debug(`[shadow_database] lazy backend started on port ${d.port}`),d)).catch(d=>{throw s=null,d})),await s}}async function zr(e,t,r){let{debug:n}=t,{port:s,updateServerStatePort:o}=r,i=await(e==="shadow_database"?Ro:Yr)(t.pgliteDataDirPath,n);n&&i.onNotification((d,p)=>{console.debug(`[${e}][${d}] ${p}`)});let{PGLiteSocketServer:c}=await import("@electric-sql/pglite-socket"),l=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis,u=new c({db:i,debug:n,idleTimeout:Number.isFinite(l)?l:0,inspect:n,maxConnections:S.connectionLimit,port:s});n&&(u.addEventListener("listening",d=>{let{detail:p}=d;console.debug(`[${e}] server listening on ${JSON.stringify(p)}`)}),u.addEventListener("connection",d=>{let{clientAddress:p,clientPort:y}=d.detail;console.debug(`[${e}] client connected from ${p}:${y}`)}),u.addEventListener("error",d=>{let{detail:p}=d;console.error(`[${e}] server error:`,p)}));try{await u.start()}catch(d){throw d instanceof Error&&"code"in d&&d.code==="EADDRINUSE"?new L(s):d}let g=Number(u.getServerConn().split(":").at(1));return o&&(t[e==="database"?"databasePort":"shadowDatabasePort"]=g),Jr(e,t,{db:i,port:g,server:u})}function Jr(e,t,r){let{debug:n}=t,{db:s,port:o,server:a}=r||{},i=new Map;return n&&console.debug(`[${e}] server started on port ${o}`),{...S,attachWalEventBridge:async()=>{if(e!=="database"||!s)throw new Error("WAL bridge is only available for the primary database server");return await pt(s)},attachQueryInsightsBridge:()=>{if(e!=="database"||!a)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(xr(a))},close:async()=>{let c=[];try{await a?.stop(),n&&console.debug(`[${e}] server stopped on port ${o}`)}catch(l){console.error(`[${e}] server stop error`,l),c.push(l)}if(e==="database"){try{a&&await Dr(a),n&&console.debug(`[${e}] closed query insights bridge`)}catch(l){console.error(`[${e}] query insights bridge close error`,l),c.push(l)}try{s&&await kr(s),n&&console.debug(`[${e}] closed WAL bridge`)}catch(l){console.error(`[${e}] WAL bridge close error`,l),c.push(l)}try{await s?.syncToFs(),n&&console.debug(`[${e}] synced to filesystem`)}catch(l){console.error(`[${e}] sync error`,l),c.push(l)}}try{await s?.close(),n&&console.debug(`[${e}] closed`)}catch(l){console.error(`[${e}] close error`,l),c.push(l)}if(c.length>0)throw new AggregateError(c,`Failed to close ${e} properly`)},connectionString:Ae(o,ht),dump:async c=>{e==="shadow_database"||!s||await xo({db:s,debug:n,destinationPath:c})},getPrimaryKeyColumns:async(c,l)=>{if(e==="shadow_database"||!s)throw new Error("Primary key resolution is only available for the primary database server");let u=`${c}.${l}`,g=i.get(u);return g||(g=To(s,c,l).catch(d=>{throw i.delete(u),d}),i.set(u,g)),await g},port:o,prismaORMConnectionString:Ae(o,Vr),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${o} -U ${S.username} -d ${S.database}`}}function Ae(e,t){return`${Po}:${e}/${S.database}?${t.toString()}`}async function Yr(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await lt(),s=e==="memory://"||!await J((0,Hr.join)(e,"PG_VERSION")),o=await r.create({database:S.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Gr,loadDataDir:s?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...jr],wasmModule:n.wasmModule});return await Kr(o),o}async function vo(e,t){return await new Promise((r,n)=>{let s=i=>{if(a(),i.code==="EADDRINUSE"){n(new L(t));return}n(i)},o=()=>{let i=e.address();if(a(),!i||typeof i=="string"){n(new Error("Failed to determine TCP server port"));return}r(i.port)},a=()=>{e.off("error",s),e.off("listening",o)};e.once("error",s),e.once("listening",o),e.listen(t,Wr)})}async function Eo(e){await new Promise((t,r)=>{e.close(n=>{let s=n;if(s&&s.code!=="ERR_SERVER_NOT_RUNNING"){r(s);return}t()})})}async function Ro(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await lt(),s=await r.create({database:S.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Gr,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...jr],wasmModule:n.wasmModule});return await Kr(s),s}async function To(e,t,r){let{rows:n}=await e.query(`
104
106
  SELECT attribute.attname AS column_name
105
107
  FROM pg_constraint pk_constraint
106
108
  INNER JOIN pg_class relation
@@ -113,9 +115,7 @@ Received data: ${u}`));n({childProcess:a,url:`http://${p}:${y}`})},c=u=>{this.#t
113
115
  ON attribute.attrelid = relation.oid
114
116
  AND attribute.attnum = keys.attnum
115
117
  WHERE pk_constraint.contype = 'p'
116
- AND namespace.nspname = ${Br(t)}
117
- AND relation.relname = ${Br(r)}
118
+ AND namespace.nspname = ${qr(t)}
119
+ AND relation.relname = ${qr(r)}
118
120
  ORDER BY keys.ordinality
119
- `);return n.map(s=>s.column_name)}function Br(e){return`'${e.replaceAll("'","''")}'`}async function bo(e){let{dataDir:t,db:r,debug:n,destinationPath:s}=e,o=r||await Gr(t,n),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:s?(0,kr.filename)(s):void 0,pg:await o.clone()});return s?(n&&console.debug(`[DB] Dumping database to ${s}`),await er(i,s)):(n&&console.debug("[DB] Dumping database to memory"),await i.text())}m();var Mn=I(require("find-my-way"),1);k();async function Ln(e,t){let{port:r}=t;if(t.dryRun)return{async close(){},port:r,url:`http://localhost:${r}`};let n=!!t.debug,[{registerAccelerateRoutes:s},{registerUtilityRoutes:o},{createHTTPServer:a}]=await Promise.all([Promise.resolve().then(()=>(_n(),An)),Promise.resolve().then(()=>(Nn(),On)),Promise.resolve().then(()=>(Ie(),cn))]),i={databaseDumpPath:t.databaseDumpPath,db:e,debug:n,name:t.name,port:r,shadowDBPort:t.shadowDatabasePort},c=(0,Mn.default)({defaultRoute(u,g){x(g,"Not Found",404)},ignoreTrailingSlash:!1});s(c,i,n),o(c,i,n);let l=await a({router:c}).listen(r);return t.port=l.port,i.port=l.port,{async close(){let{Engine:u}=await Promise.resolve().then(()=>(yt(),ht));await Promise.allSettled([l.close(),u.stopAll()])},port:l.port,url:l.url}}m();var Tt=require("util");m();var wt=require("pathe");X();var vt="prisma-wal",Et="prisma-queries";function Rt(){return(0,wt.join)(he.data,"durable-streams")}function Oe(e){return(0,wt.join)(Rt(),e)}function Ne(e,t=vt){return new URL(`/v1/stream/${encodeURIComponent(t)}`,e).toString()}var Vo="application/json",Me={connection:"close","content-type":Vo},xt={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{applicationName:{type:["string","null"]},durationMs:{type:"number"},groupKey:{type:["string","null"]},query:{type:"string"},queryId:{type:"string"},reads:{type:"number"},rowsReturned:{type:"number"},tables:{items:{type:"string"},type:"array"},timestamp:{format:"date-time",type:"string"}},required:["durationMs","query","queryId","reads","rowsReturned","tables","timestamp"],type:"object"},search:{aliases:{applicationName:"applicationName",groupKey:"groupKey",queryId:"queryId"},fields:{applicationName:{bindings:[{jsonPointer:"/applicationName",version:1}],exact:!0,exists:!0,kind:"keyword"},eventTime:{bindings:[{jsonPointer:"/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},groupKey:{bindings:[{jsonPointer:"/groupKey",version:1}],exact:!0,exists:!0,kind:"keyword"},queryId:{bindings:[{jsonPointer:"/queryId",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};function Bn(e){return{...e,snapshot:async t=>await Ko(e.url,t)}}async function $n(e){let t={serverUrl:e.serverUrl,sqlitePath:e.sqlitePath,streamName:Et,url:Ne(e.serverUrl,Et)};await Jo(t);let r=new Dt({debug:e.debug,streamUrl:t.url}),n=e.bridge.subscribe(s=>{r.enqueue(s)});return{close:async()=>{n(),await r.close()},experimental:t}}async function Ko(e,t){if(!e)return mr();let r=await zo(e);return yr(r,t)}async function zo(e){let t=await fetch(`${e}?offset=-1&format=json`,{headers:{connection:"close"}});if(!t.ok)throw new Error(`Failed to read ${e}: HTTP ${t.status}`);return await t.json()}var Dt=class{#r;#e;#t;constructor(t){this.#r=t.debug,this.#e=Promise.resolve(),this.#t=t.streamUrl}enqueue(t){t.length!==0&&(this.#e=this.#e.then(async()=>{await Zo(this.#t,t),this.#r&&console.debug(`[streams] appended ${t.length} query insight record(s) to ${this.#t}`)}).catch(r=>{console.error("[streams] failed to ingest query insights into prisma-queries",r)}))}async close(){await this.#e}};async function Jo(e){let t=await fetch(e.url,{headers:Me,method:"PUT"});if(!t.ok)throw await Le(t,`Failed to create ${e.streamName}`);let r=await Xo(e);if(Yo(r,e.streamName))return;if(r.currentVersion>0)throw new Error(`Failed to install schema for ${e.streamName}: existing schema registry is incompatible and requires a lens migration`);let n=await fetch(`${e.url}/_schema`,{body:JSON.stringify(xt),headers:Me,method:"POST"});if(!n.ok)throw await Le(n,`Failed to install schema for ${e.streamName}`)}function Yo(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,Tt.isDeepStrictEqual)(r,xt.schema)&&(0,Tt.isDeepStrictEqual)(e.search,xt.search)}async function Xo(e){let t=await fetch(`${e.url}/_schema`,{headers:Me,method:"GET"});if(!t.ok)throw await Le(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}async function Zo(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:Me,method:"POST"});if(!r.ok)throw await Le(r,"Failed to append to prisma-queries")}async function Le(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}m();var Hn=require("fs/promises"),j=require("pathe"),te=require("proper-lockfile"),Nt=require("std-env"),f=require("valibot");X();m();var ea=require("timers/promises"),kn=require("std-env");function Un(e,t){if(e==null)return!1;try{return kn.process.kill?.(e,0)??!0}catch(r){return t&&console.error(`Error checking if process with PID ${e} exists:`,r),!1}}be();var ce=(0,f.pipe)((0,f.string)(),(0,f.url)()),Cn=(0,f.object)({connectionString:ce,prismaORMConnectionString:(0,f.optional)(ce),terminalCommand:(0,f.optional)((0,f.string)())}),Qn=(0,f.object)({url:ce}),qn=(0,f.object)({serverUrl:ce,sqlitePath:(0,f.pipe)((0,f.string)(),(0,f.minLength)(1)),streamName:(0,f.pipe)((0,f.string)(),(0,f.minLength)(1)),url:ce}),ta=(0,f.object)({queryInsights:(0,f.optional)(qn),streams:(0,f.optional)(qn)}),It=(0,f.pipe)((0,f.number)(),(0,f.integer)(),(0,f.minValue)(1)),ra=(0,f.object)({database:Cn,http:Qn,ppg:Qn,shadowDatabase:Cn}),na=(0,f.object)({databasePort:It,experimental:(0,f.optional)(ta),exports:(0,f.optional)(ra),name:(0,f.pipe)((0,f.string)(),(0,f.minLength)(1)),pid:(0,f.optional)((0,f.pipe)((0,f.number)(),(0,f.integer)(),(0,f.minValue)(0))),port:It,shadowDatabasePort:It,version:(0,f.literal)("1")}),Mt=Symbol("initialize"),At="default",sa=new Set(["durable-streams"]),M=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(t){this._databasePort=t.databasePort??_,this.databaseConnectTimeoutMillis=t.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=t.databaseIdleTimeoutMillis??1/0,this.debug=t.debug??!1,this.dryRun=t.dryRun??!1,this.name=t.name??At,this.persistenceMode=t.persistenceMode,this.pid=t.pid??Nt.process.pid,this.shadowDatabaseConnectTimeoutMillis=t.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=t.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=t.port??_,this._shadowDatabasePort=t.shadowDatabasePort??_,this._streamsPort=t.streamsPort??_}static async createExclusively(t){let r=t?.dryRun!==!0&&t?.persistenceMode==="stateful"?new ie(t):new _t(t);return await r[Mt](),r}static async fromServerDump(t){let{debug:r,name:n=At}=t??{},s=ne(n),o=ie.getServerDumpPath(s),a=await tr(o);if(a==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(a));let{issues:i,output:c,success:l}=(0,f.safeParse)((0,f.pipe)((0,f.string)(),(0,f.parseJson)(),na),a);if(!l)throw r&&console.debug(`[State] Invalid server dump file at "${o}":
120
- ${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new ie({databasePort:c.databasePort,debug:r,dryRun:!1,name:n,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(t){let{debug:r,globs:n}=t??{},s=(0,j.join)(ne(At),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let o=(await nr(s,n)).filter(a=>!sa.has(a));return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(a=>Lt(a,t)))}get databasePort(){return this._databasePort}set databasePort(t){this.#r("databasePort",t)}get port(){return this._port}set port(t){this.#r("port",t)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(t){this.#r("shadowDatabasePort",t)}#r(t,r){if(r<0||!Number.isInteger(r))throw new Error(`Invalid port number: ${r}`);let n=`_${t}`;if(this[n]!==G&&this[n]!==r)throw new Error(`\`${t}\` is already set to ${this[n]}, cannot change it to ${r}`);this[n]=r}},_t=class extends M{constructor(t){super({...t,databasePort:t?.databasePort||G,persistenceMode:"stateless",port:t?.port||G,shadowDatabasePort:t?.shadowDatabasePort||G,streamsPort:t?.streamsPort||G})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Mt](){let t;try{t=await M.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),t=[]}let r=await je({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort}async close(){}async writeServerDump(){}},ie=class e extends M{#r;#e;#t;#s;#o;#a;#n;constructor(t){super({...t,persistenceMode:"stateful"}),this.#a=!1,this.#e=ne(this.name),this.#r=(0,j.join)(this.#e,"db_dump.bak"),this.#t=(0,j.join)(this.#e,".lock"),this.#s=(0,j.join)(this.#e,".pglite"),this.#n=t?.serverDump??null,this.#o=e.getServerDumpPath(this.#e)}static getServerDumpPath(t){return(0,j.join)(t,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get experimental(){return this.#n?.experimental}get pgliteDataDirPath(){return this.#s}async[Mt](){await rr(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,te.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let t=await M.scan({debug:this.debug,onlyMetadata:!0}),r=await je({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort,await this.writeServerDump()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ELOCKED"?new le(this):t}}async close(){if(!this.#a)try{await(0,te.unlock)(this.#e,{lockfilePath:this.#t}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(t){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,t),t}}async writeServerDump(t,r){this.#n={name:this.name,version:"1",pid:Nt.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:t},await(0,Hn.writeFile)(this.#o,`${JSON.stringify(this.#n,null,2)}
121
- `,{encoding:"utf-8"})}};async function Lt(e,t){let{debug:r,onlyMetadata:n}=t||{},s=typeof e=="string"?e:e.name,o=typeof e!="string"?e:void 0,a={databasePort:o?.databasePort??-1,experimental:o?.experimental,exports:o?.exports,name:s,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let i=o||await M.fromServerDump({debug:r,name:s});if(!i)return r&&console.debug(`[State] no server state found for name: ${s}`),{...a,status:"no_such_server"};a.databasePort=i.databasePort,a.experimental=i.experimental,a.exports=i.exports,a.pid=i.pid,a.port=i.port,a.shadowDatabasePort=i.shadowDatabasePort;let{exports:c,pid:l}=i;if(n)return{...a,status:"unknown"};if(!Un(l,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${l}`),{...a,status:"not_running"};let u=ne(s);try{if(!await(0,te.check)(u,{lockfilePath:(0,j.join)(u,".lock")}))return r&&console.debug(`[State] server state for "${s}" is not locked, indicating it is not running.`),{...a,status:"not_running"}}catch(y){r&&console.error(`[State] server state for "${s}" failed to check lock:`,y)}if(!c)return{...a,status:"starting_up"};let{http:g}=c,d=await fetch(`${g.url}/health`,{headers:{connection:"close"}});if(!d.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(d)}`),{...a,status:"not_running"};let p=await d.json();return p.name!==e?(r&&console.debug(`[State] server state for "${s}" has mismatched health response: ${JSON.stringify(p)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${e}" is live: ${JSON.stringify(p)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${s}":`,i),{...a,status:"error"}}}function Fn(e){let{status:t}=e;return t==="running"||t==="starting_up"}var Ot=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},le=class extends Ot{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return M.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};m();var Gn=require("crypto"),Bt=require("timers/promises"),$t=require("util"),jn=require("std-env");X();var oa="application/json",ue={connection:"close","content-type":oa},aa={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},kt={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{headers:{properties:{operation:{type:"string"},timestamp:{format:"date-time",type:"string"}},required:["timestamp","operation"],type:"object"},key:{type:"string"},type:{type:"string"}},required:["type","key","headers"],type:"object"},search:{aliases:{rowKey:"key",table:"type"},fields:{eventTime:{bindings:[{jsonPointer:"/headers/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},key:{bindings:[{jsonPointer:"/key",version:1}],exact:!0,exists:!0,kind:"keyword"},operation:{bindings:[{jsonPointer:"/headers/operation",version:1}],exact:!0,exists:!0,kind:"keyword"},type:{bindings:[{jsonPointer:"/type",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};async function Vn(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:o,queryInsightsBridge:a,walBridge:i}=e,c=s==="stateless",l=c?Sa(n):n,u=Oe(l),g=!c&&await J(u);jn.process.env.DS_LOCAL_DATA_ROOT=Rt(),c&&await Y(u);let d=await ca({debug:r,hadExistingStreamsData:g,name:l,port:o}),p={serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path,streamName:vt,url:Ne(d.exports.http.url)};try{await da(p);let y=await $n({bridge:a,debug:r,serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path}),v=new Ut({dbServer:t,debug:r,streamUrl:p.url}),re=i.subscribe($e=>{v.enqueue($e)});return{close:async()=>{re(),await v.close(),await y.close(),await d.close(),await(0,Bt.setTimeout)(100),c&&await Y(u)},experimental:p,experimentalQueryInsights:y.experimental}}catch(y){throw await d.close().catch(()=>{}),await(0,Bt.setTimeout)(100),c&&await Y(u).catch(()=>{}),y}}var ia=["database disk image is malformed","duplicate column name:","file is not a database","malformed database schema","no such column:","no such table:","schema_version row missing after migration","unexpected schema version:"];async function ca(e){let{debug:t,hadExistingStreamsData:r,name:n,port:s}=e,{startLocalDurableStreamsServer:o}=await import("@prisma/streams-local"),a=()=>o({hostname:"127.0.0.1",name:n,port:s});try{return await a()}catch(i){if(!r||!la(i))throw i;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),t&&console.debug(`[streams] original durable streams startup error for "${n}"`,i),await Y(Oe(n)),await a()}}function la(e){return ua(e).map(r=>r.toLowerCase()).some(r=>ia.some(n=>r.includes(n)))}function ua(e){let t=[],r=[e],n=new Set;for(;r.length>0;){let s=r.shift();if(!(s==null||n.has(s))){if(n.add(s),typeof s=="string"){t.push(s);continue}if(s instanceof AggregateError)for(let o of s.errors)r.push(o);if(s instanceof Error){t.push(s.message);let o=s.cause;o!==void 0&&r.push(o)}}}return t}var Ut=class{#r;#e;#t;#s;#o;constructor(t){this.#r=t.dbServer,this.#e=t.debug,this.#t=Promise.resolve(),this.#s=t.streamUrl,this.#o=new Set}enqueue(t){t.length!==0&&(this.#t=this.#t.then(async()=>{let r=await this.#a(t);r.length!==0&&(await ga(this.#s,r),this.#e&&console.debug(`[streams] appended ${r.length} state-protocol record(s) to ${this.#s}`))}).catch(r=>{console.error("[streams] failed to ingest WAL events into prisma-wal",r)}))}async close(){await this.#t}async#a(t){let r=[],n=new Date().toISOString();for(let s of t)r.push(...await this.#n(s,n));return r}async#n(t,r){let n=`${t.schema}.${t.table}`,s=await this.#r.getPrimaryKeyColumns(t.schema,t.table),o=Wn(t.record),a=Wn(t.oldRecord),i=this.#i(n,s,a),c=this.#i(n,s,o),l=t.txid===""?void 0:t.txid;return t.type==="insert"?o&&c?[{headers:{operation:"insert",timestamp:r,txid:l},key:c,old_value:null,type:n,value:o}]:[]:t.type==="delete"?a&&i?[{headers:{operation:"delete",timestamp:r,txid:l},key:i,old_value:a,type:n,value:null}]:[]:!o||!a||!i||!c?[]:i!==c?[{headers:{operation:"delete",timestamp:r,txid:l},key:i,old_value:a,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:l},key:c,old_value:null,type:n,value:o}]:[{headers:{operation:"update",timestamp:r,txid:l},key:c,old_value:a,type:n,value:o}]}#i(t,r,n){if(!n)return null;let s=fa(n,r);return s||(this.#o.has(t)||(this.#o.add(t),console.warn(`[streams] falling back to full-row keys for ${t} because no primary key could be resolved`)),ha(n))}};async function da(e){let t=await fetch(e.url,{headers:ue,method:"PUT"});if(!t.ok)throw await de(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(aa),headers:ue,method:"POST"});if(!r.ok)throw await de(r,`Failed to configure ${e.streamName}`);let n=await ma(e);if(pa(n,e.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${e.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${e.url}/_schema`,{body:JSON.stringify(kt),headers:ue,method:"POST"});if(!s.ok)throw await de(s,`Failed to install schema for ${e.streamName}`)}async function ma(e){let t=await fetch(`${e.url}/_schema`,{headers:ue,method:"GET"});if(!t.ok)throw await de(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function pa(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,$t.isDeepStrictEqual)(r,kt.schema)&&(0,$t.isDeepStrictEqual)(e.search,kt.search)}async function ga(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:ue,method:"POST"});if(!r.ok)throw await de(r,"Failed to append to prisma-wal")}async function de(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function fa(e,t){if(t.length===0)return null;let r=[];for(let n of t){if(!Object.prototype.hasOwnProperty.call(e,n))return null;let s=ya(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function ha(e){return JSON.stringify(Ct(e))}function Ct(e){return Array.isArray(e)?e.map(t=>Ct(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Ct(r)])):e}function Wn(e){return e?structuredClone(e):null}function ya(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?String(e):null;if(typeof e=="bigint")return e.toString();if(typeof e=="boolean")return e?"true":"false";try{return JSON.stringify(e)}catch{return null}}function Sa(e){return`${e}.${(0,Gn.randomUUID)().replaceAll("-","")}`}async function Qt(e){let t=await M.createExclusively(e),r=null,n=null,s=null,o=null;try{[r,s]=await Promise.all([ot("database",t),ot("shadow_database",t)]);let a,i;t.dryRun?(a=va(),i=Ea(),o=Ra()):(a=await r.attachWalEventBridge(),i=await r.attachQueryInsightsBridge(),o=await Vn({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,queryInsightsBridge:i,walBridge:a})),n=await Ln(r,t);let c=ba(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{queryInsights:o.experimentalQueryInsights,streams:o.experimental});let l=wa(a),u=Bn(o.experimentalQueryInsights),g=r,d=s,p=n,y=o,v=async()=>{l.close(),await Kn(t,[p,y,g,d])};return{close:v,dbServer:r,httpServer:n,server:{...c,close:v,experimental:{queryInsights:u,streams:o.experimental,wal:l.api},name:t.name},serverState:t,shadowDbServer:s,streamsServer:o,queryInsightsBridge:i,walBridge:a}}catch(a){return await Pa(t,[n,o,r,s],a)}}function ba(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:Vt({databaseUrl:e.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:e.connectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand},http:{url:r.url},ppg:{url:s},shadowDatabase:{connectionString:t.prismaORMConnectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand}}}async function Kn(e,t){let r=[];for(let n of t)try{await n.close()}catch(s){r.push(s)}try{await e.close()}catch(n){r.push(n)}if(r.length>0)throw new AggregateError(r,"Failed to close some servers")}async function Pa(e,t,r){try{await Kn(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function wa(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=Ta(e,()=>{t.delete(r)});return r=()=>n.close(),t.add(r),n.stream},subscribe:r=>e.subscribe(r)},close:()=>{for(let r of[...t])r();t.clear()}}}function va(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Ea(){return{async close(){},subscribe(){return()=>{}}}}function Ra(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function Ta(e,t){let r=[],n=!1,s=null,o=e.subscribe(i=>{if(!n){if(s){let c=s;s=null,c.resolve({done:!1,value:i});return}r.push(i)}}),a=()=>{if(!n&&(n=!0,o(),r.length=0,t(),s)){let i=s;s=null,i.resolve({done:!0,value:void 0})}};return{close:a,stream:{[Symbol.asyncIterator](){return this},next(){return r.length>0?Promise.resolve({done:!1,value:r.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((i,c)=>{s={reject:c,resolve:i}})},return(){return a(),Promise.resolve({done:!0,value:void 0})},throw(i){let c=s;return a(),c&&c.reject(i),Promise.reject(i instanceof Error?i:new Error(String(i)))}}}}var xa="default",Da=15e3,Ia=250;async function Yn(e){let{lockRetryTimeoutMillis:t=Da,persistenceMode:r="stateful",...n}=e??{};if(r==="stateless"){let{server:o}=await Qt({...n,persistenceMode:r});return zn(o)}let s=Date.now()+t;for(;;)try{let{server:o}=await Qt({...n,persistenceMode:"stateful"});return zn(o)}catch(o){if(!(o instanceof le))throw o;let a=await Aa(n.name,n.debug);if(a)return a;if(Date.now()>=s)throw o;await(0,Jn.setTimeout)(Ia)}}function zn(e){return{close:()=>e.close(),database:e.database,http:e.http,name:e.name,owned:!0,ppg:e.ppg,server:e,shadowDatabase:e.shadowDatabase}}async function Aa(e,t){let r=await Lt(e??xa,{debug:t});return!Fn(r)||!r.exports?null:{...r.exports,close:()=>Promise.resolve(),experimental:r.experimental,name:r.name,owned:!1}}var V=new Map;async function Xn(e){let{name:t}=e;await qt(t);let r=Yn(e);V.set(t,r);let n;try{n=await r}catch(s){throw V.get(t)===r&&V.delete(t),s}return{release:async()=>{V.get(t)===r&&await qt(t)},server:n}}async function Ht(){await Promise.allSettled([...V.keys()].map(e=>qt(e)))}async function qt(e){let t=V.get(e);if(!t)return;V.delete(e),await(await t).close()}var _a=["SIGINT","SIGTERM"],Zn=!1;function es(){if(!Zn){Zn=!0,process.once("beforeExit",()=>{Ht()});for(let e of _a)process.once(e,()=>{Ht().finally(()=>{process.kill(process.pid,e)})})}}var Be="prisma-dev",Oa="default",Na={info:e=>console.info(e),warn:e=>console.warn(e)};function ts(e={}){let{debug:t,enableInTest:r=!1,env:n,name:s=Oa,onDatabaseReady:o,overrideExistingEnv:a=!1,persistenceMode:i="stateful"}=e,c=null;return{apply(u,g){return g.command==="serve"&&g.isPreview!==!0&&(r||!$a())},async config(u){let g=u.customLogger??Na;es(),c=await Xn({databasePort:e.databasePort,debug:t,name:s,persistenceMode:i,port:e.port,shadowDatabasePort:e.shadowDatabasePort,streamsPort:e.streamsPort});let d=Wt(c.server,n),{applied:p,skipped:y}=Gt(d,process.env,{override:a});return ka(g,c.server,p.length,y),o&&await Ba(o,La(c.server,d),g,l),{}},async closeBundle(){await l()},configureServer(u){u.httpServer?.once("close",()=>{l()})},name:Be};async function l(){let u=c;c=null,await u?.release()}}var Ma=ts;function La(e,t){return{...ke(e),env:Object.fromEntries(t.map(({name:r,value:n})=>[r,n])),name:e.name,owned:e.owned}}async function Ba(e,t,r,n){try{await e(t)}catch(s){throw r.warn(`[${Be}] \`onDatabaseReady\` failed, shutting the database down`,{timestamp:!0}),await n(),s}}function $a(){return process.env.VITEST!=null||process.env.VITEST_WORKER_ID!=null}function ka(e,t,r,n){let s=t.owned?"started":"attached to already-running";e.info(`[${Be}] ${s} database "${t.name}", set ${r} environment variable(s)`,{timestamp:!0});for(let{name:o}of n)e.warn(`[${Be}] ${o} is already set, leaving it untouched. Pass \`overrideExistingEnv: true\` to let the local database win.`,{timestamp:!0})}0&&(module.exports={prismaDev});
121
+ `);return n.map(s=>s.column_name)}function qr(e){return`'${e.replaceAll("'","''")}'`}async function xo(e){let{dataDir:t,db:r,debug:n,destinationPath:s}=e,o=r||await Yr(t,n),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:s?(0,Fr.filename)(s):void 0,pg:await o.clone()});return s?(n&&console.debug(`[DB] Dumping database to ${s}`),await Jt(i,s)):(n&&console.debug("[DB] Dumping database to memory"),await i.text())}m();var Un=I(require("find-my-way"),1);k();async function Qn(e,t){let{port:r}=t;if(t.dryRun)return{async close(){},port:r,url:`http://localhost:${r}`};let n=!!t.debug,[{registerAccelerateRoutes:s},{registerUtilityRoutes:o},{createHTTPServer:a}]=await Promise.all([Promise.resolve().then(()=>($n(),Bn)),Promise.resolve().then(()=>(Cn(),kn)),Promise.resolve().then(()=>(Ne(),gn))]),i={databaseDumpPath:t.databaseDumpPath,db:e,debug:n,name:t.name,port:r,shadowDBPort:t.shadowDatabasePort},c=(0,Un.default)({defaultRoute(u,g){x(g,"Not Found",404)},ignoreTrailingSlash:!1});s(c,i,n),o(c,i,n);let l=await a({router:c}).listen(r);return t.port=l.port,i.port=l.port,{async close(){let{Engine:u}=await Promise.resolve().then(()=>(At(),It));await Promise.allSettled([l.close(),u.stopAll()])},port:l.port,url:l.url}}m();var Mt=require("util");var ea="application/json",Be={connection:"close","content-type":ea},Lt={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{applicationName:{type:["string","null"]},durationMs:{type:"number"},groupKey:{type:["string","null"]},query:{type:"string"},queryId:{type:"string"},reads:{type:"number"},rowsReturned:{type:"number"},tables:{items:{type:"string"},type:"array"},timestamp:{format:"date-time",type:"string"}},required:["durationMs","query","queryId","reads","rowsReturned","tables","timestamp"],type:"object"},search:{aliases:{applicationName:"applicationName",groupKey:"groupKey",queryId:"queryId"},fields:{applicationName:{bindings:[{jsonPointer:"/applicationName",version:1}],exact:!0,exists:!0,kind:"keyword"},eventTime:{bindings:[{jsonPointer:"/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},groupKey:{bindings:[{jsonPointer:"/groupKey",version:1}],exact:!0,exists:!0,kind:"keyword"},queryId:{bindings:[{jsonPointer:"/queryId",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};function qn(e){return{...e,snapshot:async t=>await ta(e.url,t)}}async function Hn(e){let t={serverUrl:e.serverUrl,sqlitePath:e.sqlitePath,streamName:ze,url:Pe(e.serverUrl,ze)};await na(t);let r=new Bt({debug:e.debug,streamUrl:t.url}),n=e.bridge.subscribe(s=>{r.enqueue(s)});return{close:async()=>{n(),await r.close()},experimental:t}}async function ta(e,t){if(!e)return Sr();let r=await ra(e);return Er(r,t)}async function ra(e){let t=await fetch(`${e}?offset=-1&format=json`,{headers:{connection:"close"}});if(!t.ok)throw new Error(`Failed to read ${e}: HTTP ${t.status}`);return await t.json()}var Bt=class{#r;#e;#t;constructor(t){this.#r=t.debug,this.#e=Promise.resolve(),this.#t=t.streamUrl}enqueue(t){t.length!==0&&(this.#e=this.#e.then(async()=>{await aa(this.#t,t),this.#r&&console.debug(`[streams] appended ${t.length} query insight record(s) to ${this.#t}`)}).catch(r=>{console.error("[streams] failed to ingest query insights into prisma-queries",r)}))}async close(){await this.#e}};async function na(e){let t=await fetch(e.url,{headers:Be,method:"PUT"});if(!t.ok)throw await $e(t,`Failed to create ${e.streamName}`);let r=await oa(e);if(sa(r,e.streamName))return;if(r.currentVersion>0)throw new Error(`Failed to install schema for ${e.streamName}: existing schema registry is incompatible and requires a lens migration`);let n=await fetch(`${e.url}/_schema`,{body:JSON.stringify(Lt),headers:Be,method:"POST"});if(!n.ok)throw await $e(n,`Failed to install schema for ${e.streamName}`)}function sa(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,Mt.isDeepStrictEqual)(r,Lt.schema)&&(0,Mt.isDeepStrictEqual)(e.search,Lt.search)}async function oa(e){let t=await fetch(`${e.url}/_schema`,{headers:Be,method:"GET"});if(!t.ok)throw await $e(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}async function aa(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:Be,method:"POST"});if(!r.ok)throw await $e(r,"Failed to append to prisma-queries")}async function $e(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}m();var Wn=require("crypto"),$t=require("timers/promises"),kt=require("util"),Gn=require("std-env");X();var ia="application/json",ue={connection:"close","content-type":ia},ca={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},Ct={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{headers:{properties:{operation:{type:"string"},timestamp:{format:"date-time",type:"string"}},required:["timestamp","operation"],type:"object"},key:{type:"string"},type:{type:"string"}},required:["type","key","headers"],type:"object"},search:{aliases:{rowKey:"key",table:"type"},fields:{eventTime:{bindings:[{jsonPointer:"/headers/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},key:{bindings:[{jsonPointer:"/key",version:1}],exact:!0,exists:!0,kind:"keyword"},operation:{bindings:[{jsonPointer:"/headers/operation",version:1}],exact:!0,exists:!0,kind:"keyword"},type:{bindings:[{jsonPointer:"/type",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};async function jn(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:o,queryInsightsBridge:a,walBridge:i}=e,c=s==="stateless",l=c?Pa(n):n,u=be(l),g=!c&&await J(u);Gn.process.env.DS_LOCAL_DATA_ROOT=Je(),c&&await Y(u);let d=await ua({debug:r,hadExistingStreamsData:g,name:l,port:o}),p={serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path,streamName:Ke,url:Pe(d.exports.http.url)};try{await pa(p);let y=await Hn({bridge:a,debug:r,serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path}),v=new Ut({dbServer:t,debug:r,streamUrl:p.url}),re=i.subscribe(Ce=>{v.enqueue(Ce)});return{close:async()=>{re(),await v.close(),await y.close(),await d.close(),await(0,$t.setTimeout)(100),c&&await Y(u)},experimental:p,experimentalQueryInsights:y.experimental}}catch(y){throw await d.close().catch(()=>{}),await(0,$t.setTimeout)(100),c&&await Y(u).catch(()=>{}),y}}var la=["database disk image is malformed","duplicate column name:","file is not a database","malformed database schema","no such column:","no such table:","schema_version row missing after migration","unexpected schema version:"];async function ua(e){let{debug:t,hadExistingStreamsData:r,name:n,port:s}=e,{startLocalDurableStreamsServer:o}=await import("@prisma/streams-local"),a=()=>o({hostname:"127.0.0.1",name:n,port:s});try{return await a()}catch(i){if(!r||!da(i))throw i;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),t&&console.debug(`[streams] original durable streams startup error for "${n}"`,i),await Y(be(n)),await a()}}function da(e){return ma(e).map(r=>r.toLowerCase()).some(r=>la.some(n=>r.includes(n)))}function ma(e){let t=[],r=[e],n=new Set;for(;r.length>0;){let s=r.shift();if(!(s==null||n.has(s))){if(n.add(s),typeof s=="string"){t.push(s);continue}if(s instanceof AggregateError)for(let o of s.errors)r.push(o);if(s instanceof Error){t.push(s.message);let o=s.cause;o!==void 0&&r.push(o)}}}return t}var Ut=class{#r;#e;#t;#s;#o;constructor(t){this.#r=t.dbServer,this.#e=t.debug,this.#t=Promise.resolve(),this.#s=t.streamUrl,this.#o=new Set}enqueue(t){t.length!==0&&(this.#t=this.#t.then(async()=>{let r=await this.#a(t);r.length!==0&&(await ha(this.#s,r),this.#e&&console.debug(`[streams] appended ${r.length} state-protocol record(s) to ${this.#s}`))}).catch(r=>{console.error("[streams] failed to ingest WAL events into prisma-wal",r)}))}async close(){await this.#t}async#a(t){let r=[],n=new Date().toISOString();for(let s of t)r.push(...await this.#n(s,n));return r}async#n(t,r){let n=`${t.schema}.${t.table}`,s=await this.#r.getPrimaryKeyColumns(t.schema,t.table),o=Fn(t.record),a=Fn(t.oldRecord),i=this.#i(n,s,a),c=this.#i(n,s,o),l=t.txid===""?void 0:t.txid;return t.type==="insert"?o&&c?[{headers:{operation:"insert",timestamp:r,txid:l},key:c,old_value:null,type:n,value:o}]:[]:t.type==="delete"?a&&i?[{headers:{operation:"delete",timestamp:r,txid:l},key:i,old_value:a,type:n,value:null}]:[]:!o||!a||!i||!c?[]:i!==c?[{headers:{operation:"delete",timestamp:r,txid:l},key:i,old_value:a,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:l},key:c,old_value:null,type:n,value:o}]:[{headers:{operation:"update",timestamp:r,txid:l},key:c,old_value:a,type:n,value:o}]}#i(t,r,n){if(!n)return null;let s=ya(n,r);return s||(this.#o.has(t)||(this.#o.add(t),console.warn(`[streams] falling back to full-row keys for ${t} because no primary key could be resolved`)),Sa(n))}};async function pa(e){let t=await fetch(e.url,{headers:ue,method:"PUT"});if(!t.ok)throw await de(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(ca),headers:ue,method:"POST"});if(!r.ok)throw await de(r,`Failed to configure ${e.streamName}`);let n=await ga(e);if(fa(n,e.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${e.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${e.url}/_schema`,{body:JSON.stringify(Ct),headers:ue,method:"POST"});if(!s.ok)throw await de(s,`Failed to install schema for ${e.streamName}`)}async function ga(e){let t=await fetch(`${e.url}/_schema`,{headers:ue,method:"GET"});if(!t.ok)throw await de(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function fa(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,kt.isDeepStrictEqual)(r,Ct.schema)&&(0,kt.isDeepStrictEqual)(e.search,Ct.search)}async function ha(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:ue,method:"POST"});if(!r.ok)throw await de(r,"Failed to append to prisma-wal")}async function de(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function ya(e,t){if(t.length===0)return null;let r=[];for(let n of t){if(!Object.prototype.hasOwnProperty.call(e,n))return null;let s=ba(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function Sa(e){return JSON.stringify(Qt(e))}function Qt(e){return Array.isArray(e)?e.map(t=>Qt(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Qt(r)])):e}function Fn(e){return e?structuredClone(e):null}function ba(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?String(e):null;if(typeof e=="bigint")return e.toString();if(typeof e=="boolean")return e?"true":"false";try{return JSON.stringify(e)}catch{return null}}function Pa(e){return`${e}.${(0,Wn.randomUUID)().replaceAll("-","")}`}async function qt(e){let t=await N.createExclusively(e),r=null,n=null,s=null,o=null;try{[r,s]=await Promise.all([yt("database",t),yt("shadow_database",t)]);let a,i;t.dryRun?(a=Ra(),i=Ta(),o=xa()):(a=await r.attachWalEventBridge(),i=await r.attachQueryInsightsBridge(),o=await jn({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,queryInsightsBridge:i,walBridge:a})),n=await Qn(r,t);let c=wa(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{queryInsights:o.experimentalQueryInsights,streams:o.experimental});let l=Ea(a),u=qn(o.experimentalQueryInsights),g=r,d=s,p=n,y=o,v=async()=>{l.close(),await Vn(t,[p,y,g,d])};return{close:v,dbServer:r,httpServer:n,server:{...c,close:v,experimental:{queryInsights:u,streams:o.experimental,wal:l.api},name:t.name},serverState:t,shadowDbServer:s,streamsServer:o,queryInsightsBridge:i,walBridge:a}}catch(a){return await va(t,[n,o,r,s],a)}}function wa(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:pr({databaseUrl:e.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:t.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:e.connectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand},http:{url:r.url},ppg:{url:s},shadowDatabase:{connectionString:t.prismaORMConnectionString,prismaORMConnectionString:t.prismaORMConnectionString,terminalCommand:t.terminalCommand}}}async function Vn(e,t){let r=[];for(let n of t)try{await n.close()}catch(s){r.push(s)}try{await e.close()}catch(n){r.push(n)}if(r.length>0)throw new AggregateError(r,"Failed to close some servers")}async function va(e,t,r){try{await Vn(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function Ea(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=Da(e,()=>{t.delete(r)});return r=()=>n.close(),t.add(r),n.stream},subscribe:r=>e.subscribe(r)},close:()=>{for(let r of[...t])r();t.clear()}}}function Ra(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Ta(){return{async close(){},subscribe(){return()=>{}}}}function xa(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function Da(e,t){let r=[],n=!1,s=null,o=e.subscribe(i=>{if(!n){if(s){let c=s;s=null,c.resolve({done:!1,value:i});return}r.push(i)}}),a=()=>{if(!n&&(n=!0,o(),r.length=0,t(),s)){let i=s;s=null,i.resolve({done:!0,value:void 0})}};return{close:a,stream:{[Symbol.asyncIterator](){return this},next(){return r.length>0?Promise.resolve({done:!1,value:r.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((i,c)=>{s={reject:c,resolve:i}})},return(){return a(),Promise.resolve({done:!0,value:void 0})},throw(i){let c=s;return a(),c&&c.reject(i),Promise.reject(i instanceof Error?i:new Error(String(i)))}}}}var Ia="default",Aa=15e3,_a=250;async function Jn(e){let{lockRetryTimeoutMillis:t=Aa,persistenceMode:r="stateful",...n}=e??{};if(r==="stateless"){let{server:o}=await qt({...n,persistenceMode:r});return Kn(o)}let s=Date.now()+t;for(;;)try{let{server:o}=await qt({...n,persistenceMode:"stateful"});return Kn(o)}catch(o){if(!(o instanceof ae))throw o;let a=await Oa(n.name,n.debug);if(a)return a;if(Date.now()>=s)throw o;await(0,zn.setTimeout)(_a)}}function Kn(e){return{close:()=>e.close(),database:e.database,http:e.http,name:e.name,owned:!0,ppg:e.ppg,server:e,shadowDatabase:e.shadowDatabase}}async function Oa(e,t){let r=await we(e??Ia,{debug:t});return!nt(r)||!r.exports?null:{...r.exports,close:()=>Promise.resolve(),experimental:r.experimental,name:r.name,owned:!1}}var V=new Map;async function Zn(e){let{name:t}=e,r=Na(e),n=V.get(t);if(n&&n.signature===r)return n.holders+=1,await Yn(t,n,!1);await es(t);let s={holders:1,pending:Jn(e),signature:r};return V.set(t,s),await Yn(t,s,!0)}async function Ht(){await Promise.allSettled([...V.keys()].map(e=>es(e)))}async function Yn(e,t,r){let n;try{n=await t.pending}catch(o){throw Xn(e,t),o}let s=!1;return{release:async()=>{s||(s=!0,Xn(e,t)&&await n.close())},server:n,started:r}}function Xn(e,t){return t.holders-=1,t.holders>0||V.get(e)!==t?!1:(V.delete(e),!0)}async function es(e){let t=V.get(e);if(!t)return;V.delete(e),await(await t.pending.catch(()=>null))?.close()}function Na(e){return JSON.stringify(e,Object.keys(e).sort())}var Ma=["SIGINT","SIGTERM"],ts=!1;function rs(){if(!ts){ts=!0,process.once("beforeExit",()=>{Ht()});for(let e of Ma)process.once(e,()=>{Ht().finally(()=>{process.kill(process.pid,e)})})}}var ke="prisma-dev",La="default";function ns(e={}){let{debug:t,enableInTest:r=!1,env:n,name:s=La,onDatabaseReady:o,overrideExistingEnv:a=!1,persistenceMode:i="stateful"}=e,c=null;return{apply(u,g){return g.command==="serve"&&g.isPreview!==!0&&(r||!Ca())},async closeBundle(){await l()},async configureServer(u){let{logger:g}=u.config;rs(),c=await Zn({databasePort:e.databasePort,debug:t,name:s,persistenceMode:i,port:e.port,shadowDatabasePort:e.shadowDatabasePort,streamsPort:e.streamsPort}),u.httpServer?.once("close",()=>{l()});let d=ur(c.server,n),{applied:p,retained:y,skipped:v}=dr(d,process.env,{override:a});Ua(g,c,[...p,...y],v),o&&c.started&&await ka(o,$a(c.server,d),g,l)},name:ke};async function l(){let u=c;c=null,await u?.release()}}var Ba=ns;function $a(e,t){return{...ve(e),env:Object.fromEntries(t.map(({name:r,value:n})=>[r,n])),name:e.name,owned:e.owned}}async function ka(e,t,r,n){try{await e(t)}catch(s){throw r.warn(`[${ke}] \`onDatabaseReady\` failed, shutting the database down`,{timestamp:!0}),await n(),s}}function Ca(){return process.env.VITEST!=null||process.env.VITEST_WORKER_ID!=null}function Ua(e,t,r,n){let{server:s}=t,o=Qa(t),a=r.length>0?r.map(({name:i})=>i).join(", "):"no environment variables";e.info(`[${ke}] ${o} database "${s.name}", set ${a}`,{timestamp:!0});for(let{name:i}of n)e.warn(`[${ke}] ${i} already points somewhere else, leaving it untouched. Pass \`overrideExistingEnv: true\` to let the local database win.`,{timestamp:!0})}function Qa({server:e,started:t}){return e.owned?t?"started":"reusing":"attached to already-running"}0&&(module.exports={prismaDev});