@prisma/dev 0.25.1 → 0.25.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{accelerate-TRR43YJ5.js → accelerate-KNP4MGMV.js} +1 -1
- package/dist/{chunk-VSS2IOVU.js → chunk-AVDGCP6B.js} +1 -1
- package/dist/chunk-GK3XD2W4.js +3 -0
- package/dist/{chunk-QDQPFKGQ.js → chunk-MGHBCHO2.js} +1 -1
- package/dist/{chunk-T75J7DN5.js → chunk-S2WDC6AE.js} +1 -1
- package/dist/{chunk-DWY47FQV.js → chunk-ZEM5OLPM.js} +1 -1
- package/dist/daemon.cjs +24 -24
- package/dist/daemon.js +1 -1
- package/dist/db.js +1 -1
- package/dist/{engine-YTEOPVUP.js → engine-XTNCE4RM.js} +1 -1
- package/dist/index.cjs +24 -24
- package/dist/index.js +1 -1
- package/dist/state.cjs +3 -3
- package/dist/state.js +1 -1
- package/dist/vite.cjs +24 -24
- package/dist/vite.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-HFONW2ZS.js +0 -3
package/dist/index.cjs
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
"use strict";var Yn=Object.create;var ge=Object.defineProperty;var Xn=Object.getOwnPropertyDescriptor;var Zn=Object.getOwnPropertyNames;var es=Object.getPrototypeOf,ts=Object.prototype.hasOwnProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var V=(e,t)=>{for(var r in t)ge(e,r,{get:t[r],enumerable:!0})},Ht=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Zn(t))!ts.call(e,s)&&s!==r&&ge(e,s,{get:()=>t[s],enumerable:!(n=Xn(t,s))||n.enumerable});return e};var D=(e,t,r)=>(r=e!=null?Yn(es(e)):{},Ht(t||!e||!e.__esModule?ge(r,"default",{value:e,enumerable:!0}):r,e)),rs=e=>Ht(ge({},"__esModule",{value:!0}),e);var ns,h,m=v(()=>{"use strict";ns=()=>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=ns()});var A,fe=v(()=>{"use strict";m();A=class extends Error{constructor(r,n,s){super(n,s);this.status=r}name="HTTPError"}});function Gt(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function os(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,P.safeParse)(ss,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]=os(s);if(a)throw new A(401,"Invalid API Key",{cause:a.join(", ")});let{databaseUrl:c,name:u,shadowDatabaseUrl:l}=i,f=t.name,d=t.port;if(!u)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 "${f}" server's output for the updated \`DATABASE_URL\` value.`);if(u!==f)throw new A(401,`Wrong API Key; The Prisma Dev server running at port ${d} is named "${f}", but the API Key is for "${u}"`);let{hostname:p,port:y}=new URL(c),{port:E}=t.db,{hostname:re,port:Ue}=new URL(l),Jn=t.shadowDBPort;if(p!=="localhost"||Number(y)!==E||re!=="localhost"||Number(Ue)!==Jn)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,Wt,ss,Qe=v(()=>{"use strict";m();P=require("valibot");fe();Wt=/^(postgres|postgresql):\/\//,ss=(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)(Wt)),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)(Wt))}))});function He(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),he.default.platform==="darwin"?as(e):he.default.platform==="win32"?is(e):cs(e)}var w,qe,he,U,Fe,K,as,is,cs,jt=v(()=>{"use strict";m();w=D(require("path"),1),qe=D(require("os"),1),he=D(require("process"),1),U=qe.default.homedir(),Fe=qe.default.tmpdir(),{env:K}=he.default,as=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(Fe,e)}},is=e=>{let t=K.APPDATA||w.default.join(U,"AppData","Roaming"),r=K.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(Fe,e)}},cs=e=>{let t=w.default.basename(U);return{data:w.default.join(K.XDG_DATA_HOME||w.default.join(U,".local","share"),e),config:w.default.join(K.XDG_CONFIG_HOME||w.default.join(U,".config"),e),cache:w.default.join(K.XDG_CACHE_HOME||w.default.join(U,".cache"),e),log:w.default.join(K.XDG_STATE_HOME||w.default.join(U,".local","state"),e),temp:w.default.join(Fe,t,e)}}});function Jt(e,t){return`${Se.cache}/engine/${e}/${t}`}function ne(e){return`${Se.data}/${e}`}async function z(e){try{return await(0,R.access)(e,R.constants.F_OK),!0}catch(t){if(We(t))return!1;throw t}}async function Yt(e,t){let r=await us(e);await(0,R.writeFile)(t,r),await(0,R.chmod)(t,"755")}async function Xt(e,t){await e.stream().pipeTo(ye.WriteStream.toWeb((0,ye.createWriteStream)(t,{encoding:"utf8"})))}function We(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function Zt(e){try{return await(0,R.readFile)(e,{encoding:"utf-8"})}catch(t){if(We(t))return null;throw t}}async function er(e){await(0,R.mkdir)(e,{recursive:!0})}async function tr(e,t){try{return(await(0,R.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,zt.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(We(r))return[];throw r}}async function J(e){await(0,R.rm)(e,{force:!0,recursive:!0})}var ye,R,Vt,Kt,zt,Se,us,Y=v(()=>{"use strict";m();ye=require("fs"),R=require("fs/promises"),Vt=require("util"),Kt=require("zlib");jt();zt=D(require("zeptomatch"),1),Se=He("prisma-dev"),us=(0,Vt.promisify)(Kt.unzip)});async function Ke(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=ms(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 u of c){let l=await ls({debug:t,portKey:u,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await ds({debug:t,pickedPorts:i,portKey:u,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${u}": ${l}`),i[u]=l}return t&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function ls(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...i}=o;if(Ge(a))return await fs({debug:t,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let c=s?.[r]??_;if(!Ge(c))return t&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=c in n;return u||Object.values(i).includes(c)?(t&&console.debug(`Port ${c} that was used last time for this server, ${u?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,Q.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 ds(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(Pe,we,Ee,ve)+1,i=Object.values(r).filter(p=>p!==void 0),c=o?gs(o):[],u=[...i,...Object.keys(s).map(Number),...c],l=Math.min(Math.max(a,...u)+100,be),f=(0,Re.difference)((0,Re.range)(a,l),u),d={port:we,databasePort:Pe,shadowDatabasePort:Ee,streamsPort:ve}[n];try{return await(0,Q.getPort)({port:d in s||i.includes(d)||c.includes(d)?void 0:d,ports:f})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&l+1<=be)return t&&console.debug(`Expanding port lookup to range [${l+1}, ${be}].`),await(0,Q.getPort)({portRange:[l+1,be]});throw p}}function Ge(e){return Number.isFinite(e)&&e>=0}function ms(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,Ge(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function ps(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 gs(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function fs(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 Ve(o);if(Object.values(r).includes(o))throw t&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new je(o);if((0,Q.isUnsafePort)(o))throw t&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new N(o);if(await(0,Q.checkPort)(o)===!1)throw t&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new N(o)}}var Q,Re,Pe,we,Ee,ve,be,G,_,N,je,Ve,se=v(()=>{"use strict";m();Q=require("get-port-please"),Re=require("remeda"),Pe=51214,we=51213,Ee=51215,ve=51216,be=65535,G=0,_=-1/0;N=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},je=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"},Ve=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=ut.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=ut.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 Wr(e,t){x(e,t.message,t.status)}var ut,C=v(()=>{"use strict";m();ut=require("buffer")});async function jr(e,t){let r;try{r=await(0,Gr.json)(e)}catch{return x(t,"Invalid input",400),null}let{output:n,success:s}=(0,I.safeParse)(po,r,{abortEarly:!0});return s?n:(x(t,"Invalid input",400),null)}var Gr,I,po,Vr=v(()=>{"use strict";m();Gr=require("stream/consumers"),I=require("valibot");C();po=(0,I.object)({tags:(0,I.union)([(0,I.pipe)((0,I.array)((0,I.string)()),(0,I.minLength)(1)),(0,I.literal)("all")])})});async function mt(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 zr(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 Jr(e,t,r){let n=dt.Buffer.from(e,"base64").toString("utf8"),s=fo(n,t.toString());r&&console.log("[Accelerate] schema with override:",s);let o=await mt(s);return{base64Override:dt.Buffer.from(s,"utf8").toString("base64"),overrideHash:o}}function fo(e,t){let r=ho(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=bo(n,t,Eo(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function ho(e){let t="datasource";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){r=pt(e,r+2);continue}if(n==="/"&&e[r+1]==="*"){r=gt(e,r+2);continue}if(n==='"'){r=ft(e,r+1);continue}if(e.startsWith(t,r)&&!Kr(e[r-1])&&!Kr(e[r+t.length])){let s=yo(e,r+t.length,"{");if(s===-1)return null;let o=So(e,s);return o===-1?null:{closeBraceIndex:o,openBraceIndex:s}}}return null}function yo(e,t,r){for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=pt(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=gt(e,n+2);continue}if(s==='"'){n=ft(e,n+1);continue}if(s===r)return n}return-1}function So(e,t){let r=0;for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=pt(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=gt(e,n+2);continue}if(s==='"'){n=ft(e,n+1);continue}if(s==="{"){r+=1;continue}if(s==="}"&&(r-=1,r===0))return n}return-1}function pt(e,t){let r=t;for(;r<e.length&&e[r]!==`
|
|
2
|
-
`;)r+=1;return r}function
|
|
3
|
-
`)&&!e.includes("\r")){let f=e.trim();return f.length===0?`${o}${i}${o}${r}`:`${o}${a}${f}${o}${i}${o}${r}`}let c=s.at(-1);if(c&&c.terminator===""&&/^\s*$/.test(c.line))return`${
|
|
4
|
-
`)||u.endsWith("\r")?"":o;return`${u}${l}${i}${o}${r}`}function
|
|
1
|
+
"use strict";var Zn=Object.create;var he=Object.defineProperty;var es=Object.getOwnPropertyDescriptor;var ts=Object.getOwnPropertyNames;var rs=Object.getPrototypeOf,ns=Object.prototype.hasOwnProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>{for(var r in t)he(e,r,{get:t[r],enumerable:!0})},jt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ts(t))!ns.call(e,s)&&s!==r&&he(e,s,{get:()=>t[s],enumerable:!(n=es(t,s))||n.enumerable});return e};var D=(e,t,r)=>(r=e!=null?Zn(rs(e)):{},jt(t||!e||!e.__esModule?he(r,"default",{value:e,enumerable:!0}):r,e)),ss=e=>jt(he({},"__esModule",{value:!0}),e);var os,h,m=v(()=>{"use strict";os=()=>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=os()});var A,ye=v(()=>{"use strict";m();A=class extends Error{constructor(r,n,s){super(n,s);this.status=r}name="HTTPError"}});function Kt(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function is(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 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]=is(s);if(a)throw new A(401,"Invalid API Key",{cause:a.join(", ")});let{databaseUrl:c,name:u,shadowDatabaseUrl:l}=i,f=t.name,d=t.port;if(!u)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 "${f}" server's output for the updated \`DATABASE_URL\` value.`);if(u!==f)throw new A(401,`Wrong API Key; The Prisma Dev server running at port ${d} is named "${f}", but the API Key is for "${u}"`);let{hostname:p,port:y}=new URL(c),{port:E}=t.db,{hostname:ne,port:qe}=new URL(l),Xn=t.shadowDBPort;if(p!=="localhost"||Number(y)!==E||ne!=="localhost"||Number(qe)!==Xn)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,Vt,as,He=v(()=>{"use strict";m();P=require("valibot");ye();Vt=/^(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)(Vt)),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)(Vt))}))});function je(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),Se.default.platform==="darwin"?cs(e):Se.default.platform==="win32"?us(e):ls(e)}var w,We,Se,Q,Ge,J,cs,us,ls,zt=v(()=>{"use strict";m();w=D(require("path"),1),We=D(require("os"),1),Se=D(require("process"),1),Q=We.default.homedir(),Ge=We.default.tmpdir(),{env:J}=Se.default,cs=e=>{let t=w.default.join(Q,"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(Ge,e)}},us=e=>{let t=J.APPDATA||w.default.join(Q,"AppData","Roaming"),r=J.LOCALAPPDATA||w.default.join(Q,"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(Ge,e)}},ls=e=>{let t=w.default.basename(Q);return{data:w.default.join(J.XDG_DATA_HOME||w.default.join(Q,".local","share"),e),config:w.default.join(J.XDG_CONFIG_HOME||w.default.join(Q,".config"),e),cache:w.default.join(J.XDG_CACHE_HOME||w.default.join(Q,".cache"),e),log:w.default.join(J.XDG_STATE_HOME||w.default.join(Q,".local","state"),e),temp:w.default.join(Ge,t,e)}}});function Zt(e,t){return`${Pe.cache}/engine/${e}/${t}`}function se(e){return`${Pe.data}/${e}`}async function Y(e){try{return await(0,R.access)(e,R.constants.F_OK),!0}catch(t){if(oe(t))return!1;throw t}}async function er(e,t){let r=await ds(e);await(0,R.writeFile)(t,r),await(0,R.chmod)(t,"755")}async function tr(e,t){await e.stream().pipeTo(be.WriteStream.toWeb((0,be.createWriteStream)(t,{encoding:"utf8"})))}function oe(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function rr(e){try{return await(0,R.readFile)(e,{encoding:"utf-8"})}catch(t){if(oe(t))return null;throw t}}async function nr(e){await(0,R.mkdir)(e,{recursive:!0})}async function sr(e,t){try{return(await(0,R.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,Xt.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(oe(r))return[];throw r}}async function $(e){await(0,R.rm)(e,{force:!0,recursive:!0})}var be,R,Jt,Yt,Xt,Pe,ds,X=v(()=>{"use strict";m();be=require("fs"),R=require("fs/promises"),Jt=require("util"),Yt=require("zlib");zt();Xt=D(require("zeptomatch"),1),Pe=je("prisma-dev"),ds=(0,Jt.promisify)(Yt.unzip)});async function Je(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=gs(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 u of c){let l=await ms({debug:t,portKey:u,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await ps({debug:t,pickedPorts:i,portKey:u,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a});t&&console.debug(`Got port for "${u}": ${l}`),i[u]=l}return t&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function ms(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...i}=o;if(Ve(a))return await ys({debug:t,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let c=s?.[r]??_;if(!Ve(c))return t&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let u=c in n;return u||Object.values(i).includes(c)?(t&&console.debug(`Port ${c} that was used last time for this server, ${u?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,F.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 ps(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(Ee,ve,Re,Te)+1,i=Object.values(r).filter(p=>p!==void 0),c=o?hs(o):[],u=[...i,...Object.keys(s).map(Number),...c],l=Math.min(Math.max(a,...u)+100,we),f=(0,xe.difference)((0,xe.range)(a,l),u),d={port:ve,databasePort:Ee,shadowDatabasePort:Re,streamsPort:Te}[n];try{return await(0,F.getPort)({port:d in s||i.includes(d)||c.includes(d)?void 0:d,ports:f})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&l+1<=we)return t&&console.debug(`Expanding port lookup to range [${l+1}, ${we}].`),await(0,F.getPort)({portRange:[l+1,we]});throw p}}function Ve(e){return Number.isFinite(e)&&e>=0}function gs(e,t){let r={},n;for(let s of t){let{databasePort:o,port:a,shadowDatabasePort:i}=s,c=fs(s);if(s.name===e){n={databasePort:o,port:a,shadowDatabasePort:i,streamsPort:c};continue}r[o]=!0,r[a]=!0,r[i]=!0,Ve(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function fs(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 hs(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function ys(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=e;if(o!==V){if(o in s)throw t&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new ze(o);if(Object.values(r).includes(o))throw t&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new Ke(o);if((0,F.isUnsafePort)(o))throw t&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new N(o);if(await(0,F.checkPort)(o)===!1)throw t&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new N(o)}}var F,xe,Ee,ve,Re,Te,we,V,_,N,Ke,ze,ae=v(()=>{"use strict";m();F=require("get-port-please"),xe=require("remeda"),Ee=51214,ve=51213,Re=51215,Te=51216,we=65535,V=0,_=-1/0;N=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},Ke=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"},ze=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=dt.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=dt.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 Vr(e,t){x(e,t.message,t.status)}var dt,U=v(()=>{"use strict";m();dt=require("buffer")});async function zr(e,t){let r;try{r=await(0,Kr.json)(e)}catch{return x(t,"Invalid input",400),null}let{output:n,success:s}=(0,I.safeParse)(fo,r,{abortEarly:!0});return s?n:(x(t,"Invalid input",400),null)}var Kr,I,fo,Jr=v(()=>{"use strict";m();Kr=require("stream/consumers"),I=require("valibot");U();fo=(0,I.object)({tags:(0,I.union)([(0,I.pipe)((0,I.array)((0,I.string)()),(0,I.minLength)(1)),(0,I.literal)("all")])})});async function gt(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 Xr(e,t){let r=e.schemaHash;if(r==null)return T(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let n=Me.get(r);return n==null?(T(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:r,schemas:n}}async function Zr(e,t,r){let n=pt.Buffer.from(e,"base64").toString("utf8"),s=yo(n,t.toString());r&&console.log("[Accelerate] schema with override:",s);let o=await gt(s);return{base64Override:pt.Buffer.from(s,"utf8").toString("base64"),overrideHash:o}}function yo(e,t){let r=So(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=wo(n,t,Ro(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function So(e){let t="datasource";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){r=ft(e,r+2);continue}if(n==="/"&&e[r+1]==="*"){r=ht(e,r+2);continue}if(n==='"'){r=yt(e,r+1);continue}if(e.startsWith(t,r)&&!Yr(e[r-1])&&!Yr(e[r+t.length])){let s=bo(e,r+t.length,"{");if(s===-1)return null;let o=Po(e,s);return o===-1?null:{closeBraceIndex:o,openBraceIndex:s}}}return null}function bo(e,t,r){for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=ft(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=ht(e,n+2);continue}if(s==='"'){n=yt(e,n+1);continue}if(s===r)return n}return-1}function Po(e,t){let r=0;for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=ft(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=ht(e,n+2);continue}if(s==='"'){n=yt(e,n+1);continue}if(s==="{"){r+=1;continue}if(s==="}"&&(r-=1,r===0))return n}return-1}function ft(e,t){let r=t;for(;r<e.length&&e[r]!==`
|
|
2
|
+
`;)r+=1;return r}function ht(e,t){let r=e.indexOf("*/",t);return r===-1?e.length:r+1}function yt(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 Yr(e){return e!=null&&/[A-Za-z0-9_]/.test(e)}function wo(e,t,r){let n=`"${xo(t)}"`,s=Eo(e);for(let[f,d]of s.entries()){let{comment:p,code:y}=en(d.line),E=y.match(/^(\s*)url(\s*)=(\s*).*/);if(E)return s[f]={line:`${E[1]}url${E[2]}=${E[3]}${n}${p}`,terminator:d.terminator},mt(s)}let o=To(e),a=vo(s,r),i=`${a}url = ${n}`;if(!e.includes(`
|
|
3
|
+
`)&&!e.includes("\r")){let f=e.trim();return f.length===0?`${o}${i}${o}${r}`:`${o}${a}${f}${o}${i}${o}${r}`}let c=s.at(-1);if(c&&c.terminator===""&&/^\s*$/.test(c.line))return`${mt(s.slice(0,-1))}${i}${o}${r}`;let u=mt(s),l=u.endsWith(`
|
|
4
|
+
`)||u.endsWith("\r")?"":o;return`${u}${l}${i}${o}${r}`}function Eo(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
|
|
8
|
-
`,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function
|
|
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 mt(e){return e.map(t=>`${t.line}${t.terminator}`).join("")}function en(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 vo(e,t){for(let r of e){let{code:n}=en(r.line),s=n.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(s?.[1])return s[1]}return`${t}${ho}`}function Ro(e,t){let r=e.lastIndexOf(`
|
|
8
|
+
`,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function To(e){return e.includes(`\r
|
|
9
9
|
`)?`\r
|
|
10
10
|
`:`
|
|
11
|
-
`}function
|
|
11
|
+
`}function xo(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var pt,Me,ho,tn=v(()=>{"use strict";m();pt=require("buffer");U();Me=new Map;ho=" "});function ue(e,t){let r=e[t];return Array.isArray(r)?r.at(-1):r}var St=v(()=>{"use strict";m()});function nn(e,t){let r=(e.method??"GET").toUpperCase(),n=`${t.origin}${e.url??"/"}`,s={headers:Do(e.headers),method:r};return Io.has(r)||(s.body=bt.Readable.toWeb(e),s.duplex="half"),new Request(n,s)}async function sn(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,rn.pipeline)(bt.Readable.fromWeb(e.body),t)}function Do(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 bt,rn,Io,on=v(()=>{"use strict";m();bt=require("stream"),rn=require("stream/promises"),Io=new Set(["GET","HEAD"])});var un={};z(un,{createHTTPServer:()=>_o,wrap:()=>M});function M(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{Ao(i,s,n,t)}catch(c){t&&console.error("[Accelerate]","error while handling handler error",c),s.destroyed||s.destroy()}}}}function Ao(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){Vr(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 _o(e){let{router:t}=e;return{async listen(r){let n=(0,an.createServer)((a,i)=>{t.lookup(a,i)}),o=(await Oo(n,r)).port;return n.on("error",a=>{console.error("[Accelerate]",a)}),{async close(){await(0,cn.promisify)(n.close.bind(n))()},port:o,url:`http://localhost:${o}`}}}}function Oo(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 N(t));return}n(a)},o=()=>{e.off("error",s),r(e.address())};e.once("error",s),e.once("listening",o),e.listen(t)})}var an,cn,Be=v(()=>{"use strict";m();an=require("http"),cn=require("util");ae();ye();U()});function Le(e){return{traceparent:ue(e.headers,"traceparent"),"X-capture-telemetry":ue(e.headers,"x-capture-telemetry")}}var ln=v(()=>{"use strict";m();St()});async function mn(e,t){let r;try{r=await(0,dn.json)(e)}catch{return T(t,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:n,output:s,success:o}=(0,b.safeParse)(No,r,{abortEarly:!0});return o?s:(T(t,{EngineNotStarted:{reason:"InvalidRequest",issues:n}},400),null)}function pn(e,t){let{output:r,success:n}=(0,b.safeParse)(Mo,e);return n?r:(T(t,{EngineMalfunction:{}},500),null)}var dn,b,No,Mo,gn=v(()=>{"use strict";m();dn=require("stream/consumers"),b=require("valibot");U();No=(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))});Mo=(0,b.looseObject)({id:(0,b.union)([(0,b.string)(),(0,b.number)()])})});function fn(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 hn=v(()=>{"use strict";m()});var wt={};z(wt,{Engine:()=>Pt,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 Sn,bn,Pn,wn,En,vn,Bo,Lo,yn,Pt,le,te,Et=v(()=>{"use strict";m();Sn=require("child_process"),bn=require("events"),Pn=require("fs/promises"),wn=require("path"),En=require("timers/promises");hn();vn=require("std-env");X();U();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Bo,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Lo,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:yn}=vn.process.env),Pt=class e{static#r=new Map;#t;#e;constructor(t){this.#t=t,this.#e=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.#s(t,r,"commit")}async request(t,r){let{url:n}=await this.start(),s=this.#o(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.#s(t,r,"rollback")}async startTransaction(t,r){let{url:n}=await this.start(),s=this.#o(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.#e!=null)return await this.#e;let{promise:t,reject:r,resolve:n}=fn();this.#e=t;let s=Lo||await this.#n();this.#t.debug&&console.debug("[Query Engine] spinning up at path...",s);let{proxySignals:o}=await import("foreground-child/proxy-signals"),a=(0,Sn.spawn)(s,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#t.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=l=>{let f=l.split(`
|
|
12
12
|
`).find(E=>E.includes("Started query engine http server"));if(!f)return;a.stdout.removeListener("data",i);let{fields:d}=JSON.parse(f);if(d==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${l}`));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: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#
|
|
13
|
+
Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#e=null,r(new le(String(l))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(l,f)=>{this.#e=null,r(new le(`Query Engine exited with code ${l} and signal ${f}`))};return a.once("exit",u),a.stdout.on("data",i),this.#t.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#e}async stop(){if(this.#e==null)return;let{childProcess:t}=await this.#e;t.exitCode==null&&t.signalCode==null&&(this.#e=null,t.kill(),await(0,bn.once)(t,"exit"))}async#n(){this.#t.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#a();this.#t.debug&&console.debug("[Query Engine] got engine commit hash",t);let r=Zt(this.#t.clientVersion,t);this.#t.debug&&console.debug("[Query Engine] cache directory path",r),await(0,Pn.mkdir)(r,{recursive:!0});let{binaryTarget:n}=this.#t.platform,s=n==="windows"?".exe":"",o=(0,wn.join)(r,`query-engine-${n}${s}`);return this.#t.debug&&console.debug("[Query Engine] binary path",o),(Bo==="1"||await Y(o)===!1)&&await this.#i({commitHash:t,extension:s,engineBinaryPath:o}),o}async#a(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#t.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#i(t){let{commitHash:r,extension:n,engineBinaryPath:s}=t,{binaryTarget:o}=this.#t.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${o}/query-engine${n}.gz`;this.#t.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}`);yn&&await(0,En.setTimeout)(Number(yn)),await er(await i.arrayBuffer(),s),this.#t.debug&&console.debug("[Query Engine] downloaded and saved at",s)}#o(t){let r={};for(let[n,s]of Object.entries(t))s!=null&&(r[n]=s);return r}async#s(t,r,n){let{url:s}=await this.#e,o=this.#o(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 Rn={};z(Rn,{getQueryPlanExecutorServer:()=>$o,queryPlanExecutorVersion:()=>Tn.version});async function $o(e){return vt===void 0&&(vt=await W.Server.create({databaseUrl:e.db.connectionString,maxResponseSize:(0,W.parseSize)("128 MiB"),queryTimeout:(0,W.parseDuration)("PT5M"),maxTransactionTimeout:(0,W.parseDuration)("PT5M"),maxTransactionWaitTime:(0,W.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.debug?"debug":"off"}})),vt}var W,Tn,vt,xn=v(()=>{"use strict";m();W=require("@prisma/query-plan-executor"),Tn=require("@prisma/query-plan-executor")});var _n={};z(_n,{registerAccelerateRoutes:()=>Qo});function ke(){return In??=Promise.resolve().then(()=>(Et(),wt)),In}function Co(){return An??=Promise.resolve().then(()=>(xn(),Rn)),An}async function Uo(){return Dn??=import("@prisma/get-platform").then(async({default:e})=>await e.getPlatformInfo()),await Dn}function Qo(e,t,r){e.on("POST","/invalidate",M(async(s,o)=>{j(s,t),await zr(s,o)!==null&&ee(o,200)},r));for(let s of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])e.on("POST",s,M(async(o,a,i)=>{j(o,t);try{let c=await Rt(a,t,i);if(c===null)return;let u=await(0,Tt.text)(o),l=i.transactionId,f=await c.request(u,{...Le(o),"X-transaction-id":l});x(a,f)}catch(c){let{handleEngineError:u}=await ke();u(c,a)}},r));for(let s of["commit","rollback"])e.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${s}`,M(async(o,a,i)=>{j(o,t);try{let c=await Rt(a,t,i);if(c===null)return;let u=i.transactionId;if(u==null){T(a,{EngineMalfunction:{}},500);return}let l=`${s}Transaction`,f=await c[l](u,Le(o));T(a,f)}catch(c){let{handleEngineError:u}=await ke();u(c,a)}},r));e.on("PUT","/:clientVersion/:schemaHash/schema",M(async(s,o,a)=>{j(s,t);let i=await(0,Tt.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 u=Me.get(c);if(u==null){if(c!==await gt(i)){x(o,"Schema hash mismatch",400);return}let l=await Zr(i,t.db.prismaORMConnectionString,t.debug);Me.set(c,{base64Original:i,...l}),x(o,c);return}if(i!==u.base64Original){x(o,"Schema mismatch",400);return}x(o,c)},r)),e.on("POST","/:clientVersion/:schemaHash/transaction/start",M(async(s,o,a)=>{j(s,t);let i=await mn(s,o);if(i!==null)try{let c=await Rt(o,t,a);if(c===null)return;let u=await c.startTransaction(i,Le(s)),l=pn(u,o);if(l===null)return;let{id:f}=l,d=a.clientVersion,p=a.schemaHash;T(o,{...u,"data-proxy":{endpoint:`http://localhost:${t.port}/${d}/${p}/itx/${f}`}})}catch(c){let{handleEngineError:u}=await ke();u(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,M(async(a,i)=>{j(a,t);let{getQueryPlanExecutorServer:c,queryPlanExecutorVersion:u}=await Co(),l=ue(a.headers,"prisma-engine-hash");if(l!=="0.0.0"&&l!==u)throw new A(400,`Using an HTTP connection string is not supported with Prisma Client version ${l??"<missing>"} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${u}.`);let f=await c(t),d=nn(a,{origin:`http://localhost:${t.port}`}),p=await f.fetch(d);await sn(p,i)},r))}async function Rt(e,t,r){let{Engine:n}=await ke(),s=Xr(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 Uo(),schemaHash:a})}var Tt,In,Dn,An,On=v(()=>{"use strict";m();Tt=require("stream/consumers");He();Jr();tn();St();ye();on();U();Be();ln();gn()});var Nn={};z(Nn,{registerUtilityRoutes:()=>Fo});function Fo(e,t,r){e.on("POST","/database/dump",M(async(n,s)=>{await t.db.dump(t.databaseDumpPath),T(s,{dumpPath:t.databaseDumpPath},201)},r)),e.on("GET","/health",M((n,s)=>{T(s,{name:t.name})},r))}var Mn=v(()=>{"use strict";m();U();Be()});var Ta={};z(Ta,{DEFAULT_DATABASE_PORT:()=>Ee,DEFAULT_SERVER_PORT:()=>ve,DEFAULT_SHADOW_DATABASE_PORT:()=>Re,DEFAULT_STREAMS_PORT:()=>Te,PortNotAvailableError:()=>N,ServerAlreadyRunningError:()=>pe,copyPrismaDevRuntimeAssets:()=>Tr,getPrismaDevRuntimeAssetManifest:()=>tt,getPrismaDevServerConnection:()=>Jn,startPrismaDevServer:()=>Yn,unstable_startServer:()=>Ra});module.exports=ss(Ta);m();m();He();m();var Ne=require("net"),$r=require("path"),Cr=require("pathe/utils");X();ae();m();var Xe=require("perf_hooks"),hr=require("@electric-sql/pglite");m();var cr=require("buffer"),or=500,ar=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,Ss=new RegExp(`(?:${ar.source}\\.)*${ar.source}`),bs=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${Ss.source})`,"gi"),Ps=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,ir=/prismaQuery='([^']+)'/,ws=new Set([q(`
|
|
14
14
|
select b.oid, b.typarray
|
|
15
15
|
from pg_catalog.pg_type a
|
|
16
16
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
17
17
|
where a.typcategory = $1
|
|
18
18
|
group by b.oid, b.typarray
|
|
19
19
|
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")]),Ps=[/^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 ar(){return{generatedAt:Date.now(),queries:[]}}function q(e){return e.replace(/\s+/g," ").trim()}function ir(e){return mr(q(e))}function cr(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?mr(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function ws(e){let t=new Set;for(let r of e.matchAll(ys)){let n=r[1];if(!n)continue;let s;for(let o of n.matchAll(Ss))s=o[1]??o[2]??o[3]??o[4];s&&!s.startsWith("pg_")&&t.add(s)}return Array.from(t)}function Es(e){return bs.has(e)?!0:Ps.some(t=>t.test(e))}function ur(e){if(Es(q(e)))return null;let t=ws(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function ze(e){if(Array.isArray(e))return e.map(ze);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,ze(n)]))}return e}function lr(e){let t=e.match(sr);if(!t?.[1])return{cleanedSql:q(e),prismaQueryInfo:null};let r=e.replace(sr,"");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),u=i===-1?o:o.slice(i+1);if(!u)return{cleanedSql:r,prismaQueryInfo:null};let l;try{l=ze(JSON.parse(or.Buffer.from(a,"base64url").toString("utf8")))}catch{l=void 0}return{cleanedSql:r,prismaQueryInfo:{action:u,isRaw:!1,model:c,payload:l}}}function dr(e,t={}){let r=new Set(t.excludeApplications??[]),n=vs(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 u=`${i.queryId}:${i.groupKey??""}`,l=o.get(u);if(!l){o.set(u,{count:1,duration:i.durationMs,groupKey:i.groupKey,id:u,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}l.count+=1,l.lastSeen=Math.max(l.lastSeen,c),l.maxDurationMs=Math.max(l.maxDurationMs??i.durationMs,i.durationMs),l.minDurationMs=Math.min(l.minDurationMs??i.durationMs,i.durationMs),l.reads+=i.reads,l.rowsReturned+=i.rowsReturned,l.totalDurationMs+=i.durationMs,l.duration=l.totalDurationMs/l.count,!l.prismaQueryInfo&&i.prismaQueryInfo&&(l.prismaQueryInfo=i.prismaQueryInfo),l.tables.length===0&&i.tables.length>0&&(l.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 vs(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,rr):rr}function mr(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)}m();function Te(e){let t=e.queryQueue;if(!t||typeof t.enqueue!="function"||typeof t.clearQueueForHandler!="function")throw new Error("PGLiteSocketServer query queue is unavailable");return t}var xe=new WeakMap;function gr(e){let t=xe.get(e);if(t&&!t.closed)return t.bridge;let r=Te(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,xe.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=Rs(n,s),c=Is(o);Ts(i,c);let u=xs(i,c);if(!u)return await n.originalEnqueue(s,o,a);let l={commandTags:[],dataRowCount:0},f=new pr.protocol.Parser,d=Je.performance.now(),p=await n.originalEnqueue(s,o,E=>{f.parse(E,re=>{Bs(l,re)}),a(E)}),y=Math.max(0,Je.performance.now()-d);return Ls(n,{applicationName:u.applicationName,durationMs:y,query:u.query,responseStats:l}),p},xe.set(e,n),n.bridge}async function fr(e){await xe.get(e)?.bridge.close()}function Rs(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 Ts(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 xs(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 Is(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 Ds(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return As(t);case"P":return _s(t);case"B":return Os(t);case"E":return Ns(t);case"C":return Ms(t);default:return null}}function Ds(e){let t=8,r=null;for(;t<e.length-1;){let n=k(e,t);if(!n||n.value==="")break;t=n.nextOffset;let s=k(e,t);if(!s)break;t=s.nextOffset,n.value==="application_name"&&(r=s.value)}return{applicationName:r,kind:"startup"}}function As(e){let t=k(e,5);return t?{kind:"query",query:t.value}:null}function _s(e){let t=k(e,5);if(!t)return null;let r=k(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function Os(e){let t=k(e,5);if(!t)return null;let r=k(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function Ns(e){let t=k(e,5);return t?{kind:"execute",portalName:t.value}:null}function Ms(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=k(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function k(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function Bs(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 Ls(e,t){let r=lr(t.query),n=ur(r.cleanedSql);if(!n)return;let s=ir(r.cleanedSql),o={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:cr(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:s,reads:0,rowsReturned:$s(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let a of e.subscribers)a([o])}function $s(e){let t=e.commandTags.reduce((r,n)=>r+ks(n),0);return Math.max(t,e.dataRowCount)}function ks(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}m();var Cs=new Set([66,67,68,69,72,80,100]),Us=90;function Qs(e){let t=e[0];return t!==void 0&&Cs.has(t)}function qs(){let e=Buffer.alloc(0);return{filter(t,r){e=e.length===0?Buffer.from(t):Buffer.concat([e,t]);let n=[],s=0;for(;e.length-s>=5;){let a=1+e.readInt32BE(s+1);if(a<5){n.push(e.subarray(s)),s=e.length;break}if(e.length-s<a)break;r&&e[s]===Us||n.push(e.subarray(s,s+a)),s+=a}e=e.subarray(s);let o=n[0];return n.length===1&&o?o:Buffer.concat(n)},get holdsPartialFrame(){return e.length>0}}}function hr(e){let t=Te(e),r=t.enqueue.bind(t),n=t.clearQueueForHandler.bind(t),s=new Map;t.clearQueueForHandler=o=>{s.delete(o),n(o)},t.enqueue=async(o,a,i)=>{let c=Qs(a),u=s.get(o);if(!c&&!u)return await r(o,a,i);u||(u=qs(),s.set(o,u));let l=u;try{return await r(o,a,f=>{let d=l.filter(f,c);d.length>0&&i(d)})}finally{l.holdsPartialFrame||s.delete(o)}}}m();var F=require("fs"),B=require("fs/promises"),Sr=require("module"),br=require("path"),O=require("url"),Fs=(0,Sr.createRequire)(h),Hs=["initdb.wasm","pglite.data","pglite.wasm"],Xe="pglite-seed.tar.gz",Pr={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"},wr=[...Hs.map(e=>({fileName:e,kind:"core",name:e})),{fileName:Xe,kind:"core",name:Xe},...Object.entries(Pr).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],De=new Map,Ws=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),Ie=null;async function Er(e){let t=X(e),r=(0,O.fileURLToPath)(t);await(0,B.mkdir)(r,{recursive:!0});let n=[];for(let s of Ze()){let o=new URL(s.fileName,t),a=(0,O.fileURLToPath)(o);await(0,B.copyFile)(s.sourcePath,a),n.push({...s,destinationPath:a})}return n}function Ze(){let e=vr(),t=X(new URL("./runtime-assets/",h));return wr.map(r=>({...r,sourcePath:(0,O.fileURLToPath)(oe(r.fileName,e,t))}))}async function et(){await Ys();let e=Rr();if(e)return await Ks(e),await Gs(e);let t=zs(),r=t.href,n=De.get(r);return n||(n=js(t),De.set(r,n)),await n}async function Gs(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=De.get(t);return r||(r=Vs(e),De.set(t,r)),await r}async function js(e){let t=X(new URL("./runtime-assets/",h)),[r,n,s]=await Promise.all([(0,B.readFile)(oe("pglite.data",e,t)),(0,B.readFile)(oe(Xe,e,t)),(0,B.readFile)(oe("pglite.wasm",e,t))]),o=Tr();return{extensions:Object.fromEntries(Object.entries(Pr).map(([a,i])=>[a,oe(i,e,t)])),fsBundle:new Blob([Uint8Array.from(r)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await o.compile(s)}}async function Vs(e){let[t,r,n]=await Promise.all([Ye(e.fsBundle),Ye(e.loadDataDir),Ye(e.wasmModule)]),s=Tr();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(r)]),wasmModule:await s.compile(n)}}async function Ks(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",X(new URL("./",e.initdbWasm))),r=(0,O.fileURLToPath)(t);(0,F.existsSync)(r)||await(0,B.copyFile)((0,O.fileURLToPath)(e.initdbWasm),r)}function X(e){return e instanceof URL?yr(e):yr((0,O.pathToFileURL)(e))}function yr(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function vr(){let e=Fs.resolve("@electric-sql/pglite");return X((0,br.dirname)(e))}function zs(){let e=X(new URL("./",h));if(Js(e))return e;if(Xs())return vr();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function Js(e){return wr.every(t=>(0,F.existsSync)((0,O.fileURLToPath)(new URL(t.fileName,e))))}function Rr(){return globalThis[Ws]??null}async function Ys(){!Zs()||Rr()||(Ie||(Ie=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw Ie=null,e})),await Ie)}function Xs(){let e=(0,O.fileURLToPath)(new URL("../package.json",h));if(!(0,F.existsSync)(e))return!1;try{return JSON.parse((0,F.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function Zs(){return typeof globalThis.Bun<"u"}function Tr(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function Ye(e){if(e.protocol==="file:")return await(0,B.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 oe(e,t,r){let n=new URL(e,t);if((0,F.existsSync)((0,O.fileURLToPath)(n)))return n;if(r){let s=new URL(e,r);if((0,F.existsSync)((0,O.fileURLToPath)(s)))return s}return n}m();var nt=require("@electric-sql/pglite"),L="_prisma_dev_wal",rt="events",Dr="install_all_triggers",xr="capture_event",Ir="prisma_dev_wal_capture",ae=new WeakMap,eo=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function st(e,t){let r=ae.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,ae.delete(e))},poll:async()=>{await tt(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,u)=>{let l=await n(c,u);return!o.closed&&o.suppressDepth===0&&_r(l)&&tt(o,e),l},i=async(c,u)=>{let l=[],f=new nt.protocol.Parser,d=u?.onRawData;await s(c,{...u,onRawData:p=>{f.parse(p,y=>{l.push(y)}),d?.(p)}}),!o.closed&&o.suppressDepth===0&&ot(l)&&tt(o,e)};return e.execProtocolRaw=a,e.execProtocolRawStream=i,ae.set(e,o),await Or(o,e),o.bridge}async function Ar(e){let t=ae.get(e);t&&await t.bridge.close()}function ot(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&&eo.has(r))return!0}return!1}function _r(e){if(e.length===0)return!1;let t=[];return new nt.protocol.Parser().parse(e,n=>{t.push(n)}),ot(t)}async function Or(e,t){e.ensureInfrastructurePromise??=at(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${L}"`),await t.exec(`
|
|
21
|
-
CREATE TABLE IF NOT EXISTS "${L}"."${
|
|
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")]),Es=[/^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 ur(){return{generatedAt:Date.now(),queries:[]}}function q(e){return e.replace(/\s+/g," ").trim()}function lr(e){return fr(q(e))}function dr(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?fr(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function vs(e){let t=new Set;for(let r of e.matchAll(bs)){let n=r[1];if(!n)continue;let s;for(let o of n.matchAll(Ps))s=o[1]??o[2]??o[3]??o[4];s&&!s.startsWith("pg_")&&t.add(s)}return Array.from(t)}function Rs(e){return ws.has(e)?!0:Es.some(t=>t.test(e))}function mr(e){if(Rs(q(e)))return null;let t=vs(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function Ye(e){if(Array.isArray(e))return e.map(Ye);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Ye(n)]))}return e}function pr(e){let t=e.match(ir);if(!t?.[1])return{cleanedSql:q(e),prismaQueryInfo:null};let r=e.replace(ir,"");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),u=i===-1?o:o.slice(i+1);if(!u)return{cleanedSql:r,prismaQueryInfo:null};let l;try{l=Ye(JSON.parse(cr.Buffer.from(a,"base64url").toString("utf8")))}catch{l=void 0}return{cleanedSql:r,prismaQueryInfo:{action:u,isRaw:!1,model:c,payload:l}}}function gr(e,t={}){let r=new Set(t.excludeApplications??[]),n=Ts(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 u=`${i.queryId}:${i.groupKey??""}`,l=o.get(u);if(!l){o.set(u,{count:1,duration:i.durationMs,groupKey:i.groupKey,id:u,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}l.count+=1,l.lastSeen=Math.max(l.lastSeen,c),l.maxDurationMs=Math.max(l.maxDurationMs??i.durationMs,i.durationMs),l.minDurationMs=Math.min(l.minDurationMs??i.durationMs,i.durationMs),l.reads+=i.reads,l.rowsReturned+=i.rowsReturned,l.totalDurationMs+=i.durationMs,l.duration=l.totalDurationMs/l.count,!l.prismaQueryInfo&&i.prismaQueryInfo&&(l.prismaQueryInfo=i.prismaQueryInfo),l.tables.length===0&&i.tables.length>0&&(l.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 Ts(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,or):or}function fr(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)}m();function Ie(e){let t=e.queryQueue;if(!t||typeof t.enqueue!="function"||typeof t.clearQueueForHandler!="function")throw new Error("PGLiteSocketServer query queue is unavailable");return t}var De=new WeakMap;function yr(e){let t=De.get(e);if(t&&!t.closed)return t.bridge;let r=Ie(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,De.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=xs(n,s),c=As(o);Is(i,c);let u=Ds(i,c);if(!u)return await n.originalEnqueue(s,o,a);let l={commandTags:[],dataRowCount:0},f=new hr.protocol.Parser,d=Xe.performance.now(),p=await n.originalEnqueue(s,o,E=>{f.parse(E,ne=>{ks(l,ne)}),a(E)}),y=Math.max(0,Xe.performance.now()-d);return $s(n,{applicationName:u.applicationName,durationMs:y,query:u.query,responseStats:l}),p},De.set(e,n),n.bridge}async function Sr(e){await De.get(e)?.bridge.close()}function xs(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 Is(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 Ds(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 As(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 _s(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return Os(t);case"P":return Ns(t);case"B":return Ms(t);case"E":return Bs(t);case"C":return Ls(t);default:return null}}function _s(e){let t=8,r=null;for(;t<e.length-1;){let n=C(e,t);if(!n||n.value==="")break;t=n.nextOffset;let s=C(e,t);if(!s)break;t=s.nextOffset,n.value==="application_name"&&(r=s.value)}return{applicationName:r,kind:"startup"}}function Os(e){let t=C(e,5);return t?{kind:"query",query:t.value}:null}function Ns(e){let t=C(e,5);if(!t)return null;let r=C(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function Ms(e){let t=C(e,5);if(!t)return null;let r=C(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function Bs(e){let t=C(e,5);return t?{kind:"execute",portalName:t.value}:null}function Ls(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=C(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function C(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function ks(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 $s(e,t){let r=pr(t.query),n=mr(r.cleanedSql);if(!n)return;let s=lr(r.cleanedSql),o={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:dr(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:s,reads:0,rowsReturned:Cs(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let a of e.subscribers)a([o])}function Cs(e){let t=e.commandTags.reduce((r,n)=>r+Us(n),0);return Math.max(t,e.dataRowCount)}function Us(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}m();var Qs=new Set([66,67,68,69,72,80,100]),Fs=90;function qs(e){let t=e[0];return t!==void 0&&Qs.has(t)}function Hs(){let e=Buffer.alloc(0);return{filter(t,r){e=e.length===0?Buffer.from(t):Buffer.concat([e,t]);let n=[],s=0;for(;e.length-s>=5;){let a=1+e.readInt32BE(s+1);if(a<5){n.push(e.subarray(s)),s=e.length;break}if(e.length-s<a)break;r&&e[s]===Fs||n.push(e.subarray(s,s+a)),s+=a}e=e.subarray(s);let o=n[0];return n.length===1&&o?o:Buffer.concat(n)},get holdsPartialFrame(){return e.length>0}}}function br(e){let t=Ie(e),r=t.enqueue.bind(t),n=t.clearQueueForHandler.bind(t),s=new Map;t.clearQueueForHandler=o=>{s.delete(o),n(o)},t.enqueue=async(o,a,i)=>{let c=qs(a),u=s.get(o);if(!c&&!u)return await r(o,a,i);u||(u=Hs(),s.set(o,u));let l=u;try{return await r(o,a,f=>{let d=l.filter(f,c);d.length>0&&i(d)})}finally{l.holdsPartialFrame||s.delete(o)}}}m();var H=require("fs"),B=require("fs/promises"),wr=require("module"),Er=require("path"),O=require("url"),Ws=(0,wr.createRequire)(h),Gs=["initdb.wasm","pglite.data","pglite.wasm"],et="pglite-seed.tar.gz",vr={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"},Rr=[...Gs.map(e=>({fileName:e,kind:"core",name:e})),{fileName:et,kind:"core",name:et},...Object.entries(vr).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],_e=new Map,js=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),Ae=null;async function Tr(e){let t=Z(e),r=(0,O.fileURLToPath)(t);await(0,B.mkdir)(r,{recursive:!0});let n=[];for(let s of tt()){let o=new URL(s.fileName,t),a=(0,O.fileURLToPath)(o);await(0,B.copyFile)(s.sourcePath,a),n.push({...s,destinationPath:a})}return n}function tt(){let e=xr(),t=Z(new URL("./runtime-assets/",h));return Rr.map(r=>({...r,sourcePath:(0,O.fileURLToPath)(ie(r.fileName,e,t))}))}async function rt(){await Zs();let e=Ir();if(e)return await Js(e),await Vs(e);let t=Ys(),r=t.href,n=_e.get(r);return n||(n=Ks(t),_e.set(r,n)),await n}async function Vs(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=_e.get(t);return r||(r=zs(e),_e.set(t,r)),await r}async function Ks(e){let t=Z(new URL("./runtime-assets/",h)),[r,n,s]=await Promise.all([(0,B.readFile)(ie("pglite.data",e,t)),(0,B.readFile)(ie(et,e,t)),(0,B.readFile)(ie("pglite.wasm",e,t))]),o=Dr();return{extensions:Object.fromEntries(Object.entries(vr).map(([a,i])=>[a,ie(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 Js(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",Z(new URL("./",e.initdbWasm))),r=(0,O.fileURLToPath)(t);(0,H.existsSync)(r)||await(0,B.copyFile)((0,O.fileURLToPath)(e.initdbWasm),r)}function Z(e){return e instanceof URL?Pr(e):Pr((0,O.pathToFileURL)(e))}function Pr(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function xr(){let e=Ws.resolve("@electric-sql/pglite");return Z((0,Er.dirname)(e))}function Ys(){let e=Z(new URL("./",h));if(Xs(e))return e;if(eo())return xr();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function Xs(e){return Rr.every(t=>(0,H.existsSync)((0,O.fileURLToPath)(new URL(t.fileName,e))))}function Ir(){return globalThis[js]??null}async function Zs(){!to()||Ir()||(Ae||(Ae=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw Ae=null,e})),await Ae)}function eo(){let e=(0,O.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 to(){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,B.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 ie(e,t,r){let n=new URL(e,t);if((0,H.existsSync)((0,O.fileURLToPath)(n)))return n;if(r){let s=new URL(e,r);if((0,H.existsSync)((0,O.fileURLToPath)(s)))return s}return n}m();var ot=require("@electric-sql/pglite"),L="_prisma_dev_wal",st="events",Or="install_all_triggers",Ar="capture_event",_r="prisma_dev_wal_capture",ce=new WeakMap,ro=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function at(e,t){let r=ce.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,ce.delete(e))},poll:async()=>{await nt(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,u)=>{let l=await n(c,u);return!o.closed&&o.suppressDepth===0&&Mr(l)&&nt(o,e),l},i=async(c,u)=>{let l=[],f=new ot.protocol.Parser,d=u?.onRawData;await s(c,{...u,onRawData:p=>{f.parse(p,y=>{l.push(y)}),d?.(p)}}),!o.closed&&o.suppressDepth===0&&it(l)&&nt(o,e)};return e.execProtocolRaw=a,e.execProtocolRawStream=i,ce.set(e,o),await Br(o,e),o.bridge}async function Nr(e){let t=ce.get(e);t&&await t.bridge.close()}function it(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&&ro.has(r))return!0}return!1}function Mr(e){if(e.length===0)return!1;let t=[];return new ot.protocol.Parser().parse(e,n=>{t.push(n)}),it(t)}async function Br(e,t){e.ensureInfrastructurePromise??=ct(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${L}"`),await t.exec(`
|
|
21
|
+
CREATE TABLE IF NOT EXISTS "${L}"."${st}" (
|
|
22
22
|
id BIGSERIAL PRIMARY KEY,
|
|
23
23
|
txid BIGINT NOT NULL DEFAULT txid_current(),
|
|
24
24
|
schema_name TEXT NOT NULL,
|
|
@@ -29,7 +29,7 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
|
|
|
29
29
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
|
|
30
30
|
)
|
|
31
31
|
`),await t.exec(`
|
|
32
|
-
CREATE OR REPLACE FUNCTION "${L}"."${
|
|
32
|
+
CREATE OR REPLACE FUNCTION "${L}"."${Ar}"()
|
|
33
33
|
RETURNS trigger
|
|
34
34
|
LANGUAGE plpgsql
|
|
35
35
|
AS $$
|
|
@@ -38,7 +38,7 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
|
|
|
38
38
|
RETURN COALESCE(NEW, OLD);
|
|
39
39
|
END IF;
|
|
40
40
|
|
|
41
|
-
INSERT INTO "${L}"."${
|
|
41
|
+
INSERT INTO "${L}"."${st}" (
|
|
42
42
|
txid,
|
|
43
43
|
schema_name,
|
|
44
44
|
table_name,
|
|
@@ -59,7 +59,7 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
|
|
|
59
59
|
END;
|
|
60
60
|
$$;
|
|
61
61
|
`),await t.exec(`
|
|
62
|
-
CREATE OR REPLACE FUNCTION "${L}"."${
|
|
62
|
+
CREATE OR REPLACE FUNCTION "${L}"."${Or}"()
|
|
63
63
|
RETURNS void
|
|
64
64
|
LANGUAGE plpgsql
|
|
65
65
|
AS $$
|
|
@@ -79,28 +79,28 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
|
|
|
79
79
|
SELECT 1
|
|
80
80
|
FROM pg_trigger
|
|
81
81
|
WHERE tgrelid = target
|
|
82
|
-
AND tgname = '${
|
|
82
|
+
AND tgname = '${_r}'
|
|
83
83
|
) THEN
|
|
84
84
|
CONTINUE;
|
|
85
85
|
END IF;
|
|
86
86
|
|
|
87
87
|
EXECUTE format(
|
|
88
|
-
'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${L}"."${
|
|
89
|
-
'${
|
|
88
|
+
'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${L}"."${Ar}"()',
|
|
89
|
+
'${_r}',
|
|
90
90
|
target::text
|
|
91
91
|
);
|
|
92
92
|
END LOOP;
|
|
93
93
|
END;
|
|
94
94
|
$$;
|
|
95
|
-
`),await
|
|
95
|
+
`),await Lr(e,t)}),await e.ensureInfrastructurePromise}async function Lr(e,t){await ct(e,t,async()=>{await t.query(`SELECT "${L}"."${Or}"()`)})}async function no(e,t){await Br(e,t),await Lr(e,t);let r=await ct(e,t,async()=>await t.query(`
|
|
96
96
|
WITH drained AS (
|
|
97
|
-
DELETE FROM "${L}"."${
|
|
97
|
+
DELETE FROM "${L}"."${st}"
|
|
98
98
|
RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id
|
|
99
99
|
)
|
|
100
100
|
SELECT txid, schema_name, table_name, op, row_data, old_row_data
|
|
101
101
|
FROM drained
|
|
102
102
|
ORDER BY id
|
|
103
|
-
`));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(
|
|
103
|
+
`));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(so);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 nt(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await no(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function ct(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&ce.get(t)!==e&&(e.closed=!0)}}function so(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:oo(e.op)}}function oo(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 ao=10,Ur="127.0.0.1",Qr=128*1024*1024,Fr=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],S={connectionLimit:ao,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},io=`postgres://${S.username}:${S.password}@localhost`,ut=new URLSearchParams({sslmode:S.sslMode}),qr=new URLSearchParams({...Object.fromEntries(ut.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 lt(e,t){if(e==="shadow_database"&&!t.dryRun)return await co(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?Gr(e,t,{db:null,port:r,server:null}):await Wr(e,t,{port:r,updateServerStatePort:!0})}async function co(e,t=async()=>await Wr("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,s=null,o=!1,a=new Set,i=(0,Ne.createServer)(u),c=await uo(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 lo(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:Oe(c,ut),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:c,prismaORMConnectionString:Oe(c,qr),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${c} -U ${S.username} -d ${S.database}`};function u(d){a.add(d);let p=()=>{a.delete(d)};d.once("close",p),d.once("error",p),d.pause(),l(d)}async function l(d){try{let p=await f();if(o){d.destroy();return}let y=(0,Ne.createConnection)({host:Ur,port:p.port});a.add(y);let E=()=>{a.delete(y)};y.once("close",E),y.once("error",E),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 f(){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 Wr(e,t,r){let{debug:n}=t,{port:s,updateServerStatePort:o}=r,i=await(e==="shadow_database"?mo:jr)(t.pgliteDataDirPath,n);n&&i.onNotification((d,p)=>{console.debug(`[${e}][${d}] ${p}`)});let{PGLiteSocketServer:c}=await import("@electric-sql/pglite-socket"),u=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis,l=new c({db:i,debug:n,idleTimeout:Number.isFinite(u)?u:0,inspect:n,maxConnections:S.connectionLimit,port:s});br(l),n&&(l.addEventListener("listening",d=>{let{detail:p}=d;console.debug(`[${e}] server listening on ${JSON.stringify(p)}`)}),l.addEventListener("connection",d=>{let{clientAddress:p,clientPort:y}=d.detail;console.debug(`[${e}] client connected from ${p}:${y}`)}),l.addEventListener("error",d=>{let{detail:p}=d;console.error(`[${e}] server error:`,p)}));try{await l.start()}catch(d){throw d instanceof Error&&"code"in d&&d.code==="EADDRINUSE"?new N(s):d}let f=Number(l.getServerConn().split(":").at(1));return o&&(t[e==="database"?"databasePort":"shadowDatabasePort"]=f),Gr(e,t,{db:i,port:f,server:l})}function Gr(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 at(s)},attachQueryInsightsBridge:()=>{if(e!=="database"||!a)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(yr(a))},close:async()=>{let c=[];try{await a?.stop(),n&&console.debug(`[${e}] server stopped on port ${o}`)}catch(u){console.error(`[${e}] server stop error`,u),c.push(u)}if(e==="database"){try{a&&await Sr(a),n&&console.debug(`[${e}] closed query insights bridge`)}catch(u){console.error(`[${e}] query insights bridge close error`,u),c.push(u)}try{s&&await Nr(s),n&&console.debug(`[${e}] closed WAL bridge`)}catch(u){console.error(`[${e}] WAL bridge close error`,u),c.push(u)}try{await s?.syncToFs(),n&&console.debug(`[${e}] synced to filesystem`)}catch(u){console.error(`[${e}] sync error`,u),c.push(u)}}try{await s?.close(),n&&console.debug(`[${e}] closed`)}catch(u){console.error(`[${e}] close error`,u),c.push(u)}if(c.length>0)throw new AggregateError(c,`Failed to close ${e} properly`)},connectionString:Oe(o,ut),dump:async c=>{e==="shadow_database"||!s||await go({db:s,debug:n,destinationPath:c})},getPrimaryKeyColumns:async(c,u)=>{if(e==="shadow_database"||!s)throw new Error("Primary key resolution is only available for the primary database server");let l=`${c}.${u}`,f=i.get(l);return f||(f=po(s,c,u).catch(d=>{throw i.delete(l),d}),i.set(l,f)),await f},port:o,prismaORMConnectionString:Oe(o,qr),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${o} -U ${S.username} -d ${S.database}`}}function Oe(e,t){return`${io}:${e}/${S.database}?${t.toString()}`}async function jr(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await rt(),s=e==="memory://"||!await Y((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:Qr,loadDataDir:s?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...Fr],wasmModule:n.wasmModule});return await Hr(o),o}async function uo(e,t){return await new Promise((r,n)=>{let s=i=>{if(a(),i.code==="EADDRINUSE"){n(new N(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 lo(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 mo(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await rt(),s=await r.create({database:S.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Qr,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...Fr],wasmModule:n.wasmModule});return await Hr(s),s}async function po(e,t,r){let{rows:n}=await e.query(`
|
|
104
104
|
SELECT attribute.attname AS column_name
|
|
105
105
|
FROM pg_constraint pk_constraint
|
|
106
106
|
INNER JOIN pg_class relation
|
|
@@ -113,9 +113,9 @@ Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t
|
|
|
113
113
|
ON attribute.attrelid = relation.oid
|
|
114
114
|
AND attribute.attnum = keys.attnum
|
|
115
115
|
WHERE pk_constraint.contype = 'p'
|
|
116
|
-
AND namespace.nspname = ${
|
|
117
|
-
AND relation.relname = ${
|
|
116
|
+
AND namespace.nspname = ${kr(t)}
|
|
117
|
+
AND relation.relname = ${kr(r)}
|
|
118
118
|
ORDER BY keys.ordinality
|
|
119
|
-
`);return n.map(s=>s.column_name)}function
|
|
120
|
-
${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new
|
|
121
|
-
`,{encoding:"utf-8"})}};async function kt(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 $.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:u}=i;if(n)return{...a,status:"unknown"};if(!$n(u,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${u}`),{...a,status:"not_running"};let l=ne(s);try{if(!await(0,te.check)(l,{lockfilePath:(0,j.join)(l,".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:f}=c,d=await fetch(`${f.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 qn(e){let{status:t}=e;return t==="running"||t==="starting_up"}var Bt=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},de=class extends Bt{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return $.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};m();var Hn=require("crypto"),Ct=require("timers/promises"),Ut=require("util"),Wn=require("std-env");Y();var Xo="application/json",me={connection:"close","content-type":Xo},Zo={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},Qt={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 Gn(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:o,queryInsightsBridge:a,walBridge:i}=e,c=s==="stateless",u=c?da(n):n,l=Le(u),f=!c&&await z(l);Wn.process.env.DS_LOCAL_DATA_ROOT=It(),c&&await J(l);let d=await ta({debug:r,hadExistingStreamsData:f,name:u,port:o}),p={serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path,streamName:Tt,url:$e(d.exports.http.url)};try{await sa(p);let y=await Bn({bridge:a,debug:r,serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path}),E=new qt({dbServer:t,debug:r,streamUrl:p.url}),re=i.subscribe(Ue=>{E.enqueue(Ue)});return{close:async()=>{re(),await E.close(),await y.close(),await d.close(),await(0,Ct.setTimeout)(100),c&&await J(l)},experimental:p,experimentalQueryInsights:y.experimental}}catch(y){throw await d.close().catch(()=>{}),await(0,Ct.setTimeout)(100),c&&await J(l).catch(()=>{}),y}}var ea=["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 ta(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||!ra(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 J(Le(n)),await a()}}function ra(e){return na(e).map(r=>r.toLowerCase()).some(r=>ea.some(n=>r.includes(n)))}function na(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 qt=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 ia(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),u=t.txid===""?void 0:t.txid;return t.type==="insert"?o&&c?[{headers:{operation:"insert",timestamp:r,txid:u},key:c,old_value:null,type:n,value:o}]:[]:t.type==="delete"?a&&i?[{headers:{operation:"delete",timestamp:r,txid:u},key:i,old_value:a,type:n,value:null}]:[]:!o||!a||!i||!c?[]:i!==c?[{headers:{operation:"delete",timestamp:r,txid:u},key:i,old_value:a,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:u},key:c,old_value:null,type:n,value:o}]:[{headers:{operation:"update",timestamp:r,txid:u},key:c,old_value:a,type:n,value:o}]}#i(t,r,n){if(!n)return null;let s=ca(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`)),ua(n))}};async function sa(e){let t=await fetch(e.url,{headers:me,method:"PUT"});if(!t.ok)throw await pe(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(Zo),headers:me,method:"POST"});if(!r.ok)throw await pe(r,`Failed to configure ${e.streamName}`);let n=await oa(e);if(aa(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(Qt),headers:me,method:"POST"});if(!s.ok)throw await pe(s,`Failed to install schema for ${e.streamName}`)}async function oa(e){let t=await fetch(`${e.url}/_schema`,{headers:me,method:"GET"});if(!t.ok)throw await pe(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function aa(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,Ut.isDeepStrictEqual)(r,Qt.schema)&&(0,Ut.isDeepStrictEqual)(e.search,Qt.search)}async function ia(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:me,method:"POST"});if(!r.ok)throw await pe(r,"Failed to append to prisma-wal")}async function pe(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function ca(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=la(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function ua(e){return JSON.stringify(Ft(e))}function Ft(e){return Array.isArray(e)?e.map(t=>Ft(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Ft(r)])):e}function Fn(e){return e?structuredClone(e):null}function la(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 da(e){return`${e}.${(0,Hn.randomUUID)().replaceAll("-","")}`}async function jn(e){let t=await $.createExclusively(e),r=null,n=null,s=null,o=null;try{[r,s]=await Promise.all([ct("database",t),ct("shadow_database",t)]);let a,i;t.dryRun?(a=fa(),i=ha(),o=ya()):(a=await r.attachWalEventBridge(),i=await r.attachQueryInsightsBridge(),o=await Gn({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,queryInsightsBridge:i,walBridge:a})),n=await Nn(r,t);let c=ma(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{queryInsights:o.experimentalQueryInsights,streams:o.experimental});let u=ga(a),l=Mn(o.experimentalQueryInsights),f=r,d=s,p=n,y=o,E=async()=>{u.close(),await Vn(t,[p,y,f,d])};return{close:E,dbServer:r,httpServer:n,server:{...c,close:E,experimental:{queryInsights:l,streams:o.experimental,wal:u.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 ma(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:Gt({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 pa(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 ga(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=Sa(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 fa(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function ha(){return{async close(){},subscribe(){return()=>{}}}}function ya(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function Sa(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)))}}}}se();m();var ba="default";function Pa(e){return{databaseUrl:e.database.prismaORMConnectionString??e.database.connectionString,prismaPostgresUrl:e.ppg.url,shadowDatabaseUrl:e.shadowDatabase.prismaORMConnectionString??e.shadowDatabase.connectionString}}async function Kn(e){let{debug:t,name:r=ba}=e??{},n=await kt(r,{debug:t});return!qn(n)||!n.exports?null:{...Pa(n.exports),name:n.name}}async function zn(e){let{server:t}=await jn(e);return t}async function wa(e){return await zn(e)}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,DEFAULT_STREAMS_PORT,PortNotAvailableError,ServerAlreadyRunningError,copyPrismaDevRuntimeAssets,getPrismaDevRuntimeAssetManifest,getPrismaDevServerConnection,startPrismaDevServer,unstable_startServer});
|
|
119
|
+
`);return n.map(s=>s.column_name)}function kr(e){return`'${e.replaceAll("'","''")}'`}async function go(e){let{dataDir:t,db:r,debug:n,destinationPath:s}=e,o=r||await jr(t,n),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:s?(0,Cr.filename)(s):void 0,pg:await o.clone()});return s?(n&&console.debug(`[DB] Dumping database to ${s}`),await tr(i,s)):(n&&console.debug("[DB] Dumping database to memory"),await i.text())}m();var Bn=D(require("find-my-way"),1);U();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(()=>(On(),_n)),Promise.resolve().then(()=>(Mn(),Nn)),Promise.resolve().then(()=>(Be(),un))]),i={databaseDumpPath:t.databaseDumpPath,db:e,debug:n,name:t.name,port:r,shadowDBPort:t.shadowDatabasePort},c=(0,Bn.default)({defaultRoute(l,f){x(f,"Not Found",404)},ignoreTrailingSlash:!1});s(c,i,n),o(c,i,n);let u=await a({router:c}).listen(r);return t.port=u.port,i.port=u.port,{async close(){let{Engine:l}=await Promise.resolve().then(()=>(Et(),wt));await Promise.allSettled([u.close(),l.stopAll()])},port:u.port,url:u.url}}m();var _t=require("util");m();var xt=require("pathe");X();var It="prisma-wal",Dt="prisma-queries";function At(){return(0,xt.join)(Pe.data,"durable-streams")}function $e(e){return(0,xt.join)(At(),e)}function Ce(e,t=It){return new URL(`/v1/stream/${encodeURIComponent(t)}`,e).toString()}var qo="application/json",Ue={connection:"close","content-type":qo},Ot={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 kn(e){return{...e,snapshot:async t=>await Ho(e.url,t)}}async function $n(e){let t={serverUrl:e.serverUrl,sqlitePath:e.sqlitePath,streamName:Dt,url:Ce(e.serverUrl,Dt)};await Go(t);let r=new Nt({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 Ho(e,t){if(!e)return ur();let r=await Wo(e);return gr(r,t)}async function Wo(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 Nt=class{#r;#t;#e;constructor(t){this.#r=t.debug,this.#t=Promise.resolve(),this.#e=t.streamUrl}enqueue(t){t.length!==0&&(this.#t=this.#t.then(async()=>{await Ko(this.#e,t),this.#r&&console.debug(`[streams] appended ${t.length} query insight record(s) to ${this.#e}`)}).catch(r=>{console.error("[streams] failed to ingest query insights into prisma-queries",r)}))}async close(){await this.#t}};async function Go(e){let t=await fetch(e.url,{headers:Ue,method:"PUT"});if(!t.ok)throw await Qe(t,`Failed to create ${e.streamName}`);let r=await Vo(e);if(jo(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(Ot),headers:Ue,method:"POST"});if(!n.ok)throw await Qe(n,`Failed to install schema for ${e.streamName}`)}function jo(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,_t.isDeepStrictEqual)(r,Ot.schema)&&(0,_t.isDeepStrictEqual)(e.search,Ot.search)}async function Vo(e){let t=await fetch(`${e.url}/_schema`,{headers:Ue,method:"GET"});if(!t.ok)throw await Qe(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}async function Ko(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:Ue,method:"POST"});if(!r.ok)throw await Qe(r,"Failed to append to prisma-queries")}async function Qe(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}m();var re=require("fs/promises"),G=require("pathe"),K=require("proper-lockfile"),Ct=require("std-env"),g=require("valibot");X();m();var zo=require("timers/promises"),Cn=require("std-env");function Un(e,t){if(e==null)return!1;try{return Cn.process.kill?.(e,0)??!0}catch(r){return t&&console.error(`Error checking if process with PID ${e} exists:`,r),!1}}ae();var me=(0,g.pipe)((0,g.string)(),(0,g.url)()),Qn=(0,g.object)({connectionString:me,prismaORMConnectionString:(0,g.optional)(me),terminalCommand:(0,g.optional)((0,g.string)())}),Fn=(0,g.object)({url:me}),qn=(0,g.object)({serverUrl:me,sqlitePath:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),streamName:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),url:me}),Jo=(0,g.object)({queryInsights:(0,g.optional)(qn),streams:(0,g.optional)(qn)}),Mt=(0,g.pipe)((0,g.number)(),(0,g.integer)(),(0,g.minValue)(1)),Yo=(0,g.object)({database:Qn,http:Fn,ppg:Fn,shadowDatabase:Qn}),Xo=(0,g.object)({databasePort:Mt,experimental:(0,g.optional)(Jo),exports:(0,g.optional)(Yo),name:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),pid:(0,g.optional)((0,g.pipe)((0,g.number)(),(0,g.integer)(),(0,g.minValue)(0))),port:Mt,shadowDatabasePort:Mt,version:(0,g.literal)("1")}),Ut=Symbol("initialize"),Zo=1e4,Bt="default",ea=new Set(["durable-streams"]);function Hn(e){return e instanceof Error&&"code"in e&&e.code==="ELOCKED"}async function Lt(e){try{return await(0,re.stat)(e)}catch(t){if(oe(t))return null;throw t}}var k=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??Bt,this.persistenceMode=t.persistenceMode,this.pid=t.pid??Ct.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 de(t):new kt(t);return await r[Ut](),r}static async fromServerDump(t){let{debug:r,name:n=Bt}=t??{},s=se(n),o=de.getServerDumpPath(s),a=await rr(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:u}=(0,g.safeParse)((0,g.pipe)((0,g.string)(),(0,g.parseJson)(),Xo),a);if(!u)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 de({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)(se(Bt),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let o=(await sr(s,n)).filter(a=>!ea.has(a));return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(a=>Fe(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]!==V&&this[n]!==r)throw new Error(`\`${t}\` is already set to ${this[n]}, cannot change it to ${r}`);this[n]=r}},kt=class extends k{constructor(t){super({...t,databasePort:t?.databasePort||V,persistenceMode:"stateless",port:t?.port||V,shadowDatabasePort:t?.shadowDatabasePort||V,streamsPort:t?.streamsPort||V})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Ut](){let t;try{t=await k.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(){}},de=class e extends k{#r;#t;#e;#n;#a;#i;#o;#s;constructor(t){super({...t,persistenceMode:"stateful"}),this.#o=!1,this.#e=se(this.name),this.#r=(0,G.join)(this.#e,".lock-break"),this.#t=(0,G.join)(this.#e,"db_dump.bak"),this.#n=(0,G.join)(this.#e,".lock"),this.#a=(0,G.join)(this.#e,".pglite"),this.#s=t?.serverDump??null,this.#i=e.getServerDumpPath(this.#e)}static getServerDumpPath(t){return(0,G.join)(t,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#s?.exports}get experimental(){return this.#s?.experimental}get pgliteDataDirPath(){return this.#a}async[Ut](){await nr(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await this.#c(),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let t=await k.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 Hn(t)?new pe(this):t}}async#c(){try{await(0,K.lock)(this.#e,{lockfilePath:this.#n});return}catch(t){if(!Hn(t)||!await this.#u())throw t}await(0,K.lock)(this.#e,{lockfilePath:this.#n})}async#u(){let t=await Lt(this.#n);if(t==null)return!0;let r=await Fe(this.name,{debug:this.debug});if(Qt(r)||r.status==="unknown"||!await this.#l())return!1;try{let n=await Lt(this.#n);return n==null?!0:n.ino!==t.ino||n.mtimeMs!==t.mtimeMs?!1:(this.debug&&console.debug(`[State] breaking lock left behind by dead server "${this.name}" (status: ${r.status})`),await $(this.#n),!0)}finally{await $(this.#r)}}async#l(){for(let t=0;t<2;t++){try{return await(0,re.mkdir)(this.#r),!0}catch(n){if(!(n instanceof Error&&"code"in n&&n.code==="EEXIST"))throw n}let r=await Lt(this.#r);if(r!=null&&Date.now()-r.mtimeMs<Zo)return!1;await $(this.#r)}return!1}async close(){if(!this.#o)try{await(0,K.unlock)(this.#e,{lockfilePath:this.#n}),this.#o=!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.#s={name:this.name,version:"1",pid:Ct.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:t},await(0,re.writeFile)(this.#i,`${JSON.stringify(this.#s,null,2)}
|
|
121
|
+
`,{encoding:"utf-8"})}};async function Fe(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 k.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:u}=i;if(n)return{...a,status:"unknown"};if(!Un(u,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${u}`),{...a,status:"not_running"};let l=se(s);try{if(!await(0,K.check)(l,{lockfilePath:(0,G.join)(l,".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:f}=c,d=await fetch(`${f.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 Qt(e){let{status:t}=e;return t==="running"||t==="starting_up"}var $t=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},pe=class extends $t{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return k.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};m();var Gn=require("crypto"),Ft=require("timers/promises"),qt=require("util"),jn=require("std-env");X();var ta="application/json",ge={connection:"close","content-type":ta},ra={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},Ht={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",u=c?ga(n):n,l=$e(u),f=!c&&await Y(l);jn.process.env.DS_LOCAL_DATA_ROOT=At(),c&&await $(l);let d=await sa({debug:r,hadExistingStreamsData:f,name:u,port:o}),p={serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path,streamName:It,url:Ce(d.exports.http.url)};try{await ia(p);let y=await $n({bridge:a,debug:r,serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path}),E=new Wt({dbServer:t,debug:r,streamUrl:p.url}),ne=i.subscribe(qe=>{E.enqueue(qe)});return{close:async()=>{ne(),await E.close(),await y.close(),await d.close(),await(0,Ft.setTimeout)(100),c&&await $(l)},experimental:p,experimentalQueryInsights:y.experimental}}catch(y){throw await d.close().catch(()=>{}),await(0,Ft.setTimeout)(100),c&&await $(l).catch(()=>{}),y}}var na=["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 sa(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||!oa(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 $($e(n)),await a()}}function oa(e){return aa(e).map(r=>r.toLowerCase()).some(r=>na.some(n=>r.includes(n)))}function aa(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 Wt=class{#r;#t;#e;#n;#a;constructor(t){this.#r=t.dbServer,this.#t=t.debug,this.#e=Promise.resolve(),this.#n=t.streamUrl,this.#a=new Set}enqueue(t){t.length!==0&&(this.#e=this.#e.then(async()=>{let r=await this.#i(t);r.length!==0&&(await la(this.#n,r),this.#t&&console.debug(`[streams] appended ${r.length} state-protocol record(s) to ${this.#n}`))}).catch(r=>{console.error("[streams] failed to ingest WAL events into prisma-wal",r)}))}async close(){await this.#e}async#i(t){let r=[],n=new Date().toISOString();for(let s of t)r.push(...await this.#o(s,n));return r}async#o(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.#s(n,s,a),c=this.#s(n,s,o),u=t.txid===""?void 0:t.txid;return t.type==="insert"?o&&c?[{headers:{operation:"insert",timestamp:r,txid:u},key:c,old_value:null,type:n,value:o}]:[]:t.type==="delete"?a&&i?[{headers:{operation:"delete",timestamp:r,txid:u},key:i,old_value:a,type:n,value:null}]:[]:!o||!a||!i||!c?[]:i!==c?[{headers:{operation:"delete",timestamp:r,txid:u},key:i,old_value:a,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:u},key:c,old_value:null,type:n,value:o}]:[{headers:{operation:"update",timestamp:r,txid:u},key:c,old_value:a,type:n,value:o}]}#s(t,r,n){if(!n)return null;let s=da(n,r);return s||(this.#a.has(t)||(this.#a.add(t),console.warn(`[streams] falling back to full-row keys for ${t} because no primary key could be resolved`)),ma(n))}};async function ia(e){let t=await fetch(e.url,{headers:ge,method:"PUT"});if(!t.ok)throw await fe(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(ra),headers:ge,method:"POST"});if(!r.ok)throw await fe(r,`Failed to configure ${e.streamName}`);let n=await ca(e);if(ua(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(Ht),headers:ge,method:"POST"});if(!s.ok)throw await fe(s,`Failed to install schema for ${e.streamName}`)}async function ca(e){let t=await fetch(`${e.url}/_schema`,{headers:ge,method:"GET"});if(!t.ok)throw await fe(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function ua(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,qt.isDeepStrictEqual)(r,Ht.schema)&&(0,qt.isDeepStrictEqual)(e.search,Ht.search)}async function la(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:ge,method:"POST"});if(!r.ok)throw await fe(r,"Failed to append to prisma-wal")}async function fe(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function da(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=pa(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function ma(e){return JSON.stringify(Gt(e))}function Gt(e){return Array.isArray(e)?e.map(t=>Gt(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Gt(r)])):e}function Wn(e){return e?structuredClone(e):null}function pa(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 ga(e){return`${e}.${(0,Gn.randomUUID)().replaceAll("-","")}`}async function Kn(e){let t=await k.createExclusively(e),r=null,n=null,s=null,o=null;try{[r,s]=await Promise.all([lt("database",t),lt("shadow_database",t)]);let a,i;t.dryRun?(a=Sa(),i=ba(),o=Pa()):(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=fa(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{queryInsights:o.experimentalQueryInsights,streams:o.experimental});let u=ya(a),l=kn(o.experimentalQueryInsights),f=r,d=s,p=n,y=o,E=async()=>{u.close(),await zn(t,[p,y,f,d])};return{close:E,dbServer:r,httpServer:n,server:{...c,close:E,experimental:{queryInsights:l,streams:o.experimental,wal:u.api},name:t.name},serverState:t,shadowDbServer:s,streamsServer:o,queryInsightsBridge:i,walBridge:a}}catch(a){return await ha(t,[n,o,r,s],a)}}function fa(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:Kt({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 zn(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 ha(e,t,r){try{await zn(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function ya(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=wa(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 Sa(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function ba(){return{async close(){},subscribe(){return()=>{}}}}function Pa(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function wa(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)))}}}}ae();m();var Ea="default";function va(e){return{databaseUrl:e.database.prismaORMConnectionString??e.database.connectionString,prismaPostgresUrl:e.ppg.url,shadowDatabaseUrl:e.shadowDatabase.prismaORMConnectionString??e.shadowDatabase.connectionString}}async function Jn(e){let{debug:t,name:r=Ea}=e??{},n=await Fe(r,{debug:t});return!Qt(n)||!n.exports?null:{...va(n.exports),name:n.name}}async function Yn(e){let{server:t}=await Kn(e);return t}async function Ra(e){return await Yn(e)}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,DEFAULT_STREAMS_PORT,PortNotAvailableError,ServerAlreadyRunningError,copyPrismaDevRuntimeAssets,getPrismaDevRuntimeAssetManifest,getPrismaDevServerConnection,startPrismaDevServer,unstable_startServer});
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as j,b as k}from"./chunk-
|
|
1
|
+
import{a as j,b as k}from"./chunk-S2WDC6AE.js";import{c as i}from"./chunk-AVDGCP6B.js";import"./chunk-662IKR3V.js";import"./chunk-MGHBCHO2.js";import{a as f,b as g}from"./chunk-KWCQYPJI.js";import{l as h}from"./chunk-GK3XD2W4.js";import"./chunk-ANHBRJRZ.js";import{a,b,c,d,h as e}from"./chunk-EDFHV3AK.js";import"./chunk-ZEM5OLPM.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};
|