@prisma/dev 0.25.0 → 0.25.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-QDQPFKGQ.js +107 -0
- package/dist/{chunk-MD3K2IUP.js → chunk-T75J7DN5.js} +1 -1
- package/dist/{chunk-J6FIMHSD.js → chunk-VSS2IOVU.js} +1 -1
- package/dist/daemon.cjs +24 -24
- package/dist/daemon.js +1 -1
- package/dist/db.cjs +15 -15
- package/dist/db.js +1 -1
- package/dist/index.cjs +24 -24
- package/dist/index.js +1 -1
- package/dist/vite.cjs +25 -25
- package/dist/vite.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-PP43TGA5.js +0 -107
package/dist/daemon.cjs
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
"use strict";var Gn=Object.create;var pe=Object.defineProperty;var jn=Object.getOwnPropertyDescriptor;var Vn=Object.getOwnPropertyNames;var Kn=Object.getPrototypeOf,zn=Object.prototype.hasOwnProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var ne=(e,t)=>{for(var r in t)pe(e,r,{get:t[r],enumerable:!0})},qt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Vn(t))!zn.call(e,s)&&s!==r&&pe(e,s,{get:()=>t[s],enumerable:!(n=jn(t,s))||n.enumerable});return e};var D=(e,t,r)=>(r=e!=null?Gn(Kn(e)):{},qt(t||!e||!e.__esModule?pe(r,"default",{value:e,enumerable:!0}):r,e)),Jn=e=>qt(pe({},"__esModule",{value:!0}),e);var Yn,h,m=v(()=>{"use strict";Yn=()=>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=Yn()});var A,ge=v(()=>{"use strict";m();A=class extends Error{constructor(r,n,s){super(n,s);this.status=r}name="HTTPError"}});function Ft(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function Zn(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,P.safeParse)(Xn,t,{abortEarly:!0});return s?[null,n]:[r]}function G(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]=Zn(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:Le}=new URL(l),Wn=t.shadowDBPort;if(p!=="localhost"||Number(y)!==E||re!=="localhost"||Number(Le)!==Wn)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,Ht,Xn,$e=v(()=>{"use strict";m();P=require("valibot");ge();Ht=/^(postgres|postgresql):\/\//,Xn=(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)(Ht)),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)(Ht))}))});function Ue(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),fe.default.platform==="darwin"?es(e):fe.default.platform==="win32"?ts(e):rs(e)}var w,ke,fe,U,Ce,K,es,ts,rs,Wt=v(()=>{"use strict";m();w=D(require("path"),1),ke=D(require("os"),1),fe=D(require("process"),1),U=ke.default.homedir(),Ce=ke.default.tmpdir(),{env:K}=fe.default,es=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(Ce,e)}},ts=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(Ce,e)}},rs=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(Ce,t,e)}}});function Kt(e,t){return`${ye.cache}/engine/${e}/${t}`}function se(e){return`${ye.data}/${e}`}async function z(e){try{return await(0,R.access)(e,R.constants.F_OK),!0}catch(t){if(Qe(t))return!1;throw t}}async function zt(e,t){let r=await ns(e);await(0,R.writeFile)(t,r),await(0,R.chmod)(t,"755")}async function Jt(e,t){await e.stream().pipeTo(he.WriteStream.toWeb((0,he.createWriteStream)(t,{encoding:"utf8"})))}function Qe(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function Yt(e){try{return await(0,R.readFile)(e,{encoding:"utf-8"})}catch(t){if(Qe(t))return null;throw t}}async function Xt(e){await(0,R.mkdir)(e,{recursive:!0})}async function Zt(e,t){try{return(await(0,R.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,Vt.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(Qe(r))return[];throw r}}async function J(e){await(0,R.rm)(e,{force:!0,recursive:!0})}var he,R,Gt,jt,Vt,ye,ns,Y=v(()=>{"use strict";m();he=require("fs"),R=require("fs/promises"),Gt=require("util"),jt=require("zlib");Wt();Vt=D(require("zeptomatch"),1),ye=Ue("prisma-dev"),ns=(0,Gt.promisify)(jt.unzip)});async function Ke(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=as(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 ss({debug:t,portKey:u,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await os({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 ss(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...i}=o;if(Ge(a))return await us({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 os(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(qe,He,Fe,We)+1,i=Object.values(r).filter(p=>p!==void 0),c=o?cs(o):[],u=[...i,...Object.keys(s).map(Number),...c],l=Math.min(Math.max(a,...u)+100,Se),f=(0,be.difference)((0,be.range)(a,l),u),d={port:He,databasePort:qe,shadowDatabasePort:Fe,streamsPort:We}[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<=Se)return t&&console.debug(`Expanding port lookup to range [${l+1}, ${Se}].`),await(0,Q.getPort)({portRange:[l+1,Se]});throw p}}function Ge(e){return Number.isFinite(e)&&e>=0}function as(e,t){let r={},n;for(let s of t){let{databasePort:o,port:a,shadowDatabasePort:i}=s,c=is(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 is(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 cs(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function us(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=e;if(o!==j){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,be,qe,He,Fe,We,Se,j,_,N,je,Ve,oe=v(()=>{"use strict";m();Q=require("get-port-please"),be=require("remeda"),qe=51214,He=51213,Fe=51215,We=51216,Se=65535,j=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 x(e,t,r=200){let n=ct.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 T(e,t,r=200){let n=ct.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 X(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function Cr(e,t){T(e,t.message,t.status)}var ct,C=v(()=>{"use strict";m();ct=require("buffer")});async function Qr(e,t){let r;try{r=await(0,Ur.json)(e)}catch{return T(t,"Invalid input",400),null}let{output:n,success:s}=(0,I.safeParse)(oo,r,{abortEarly:!0});return s?n:(T(t,"Invalid input",400),null)}var Ur,I,oo,qr=v(()=>{"use strict";m();Ur=require("stream/consumers"),I=require("valibot");C();oo=(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 dt(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 Fr(e,t){let r=e.schemaHash;if(r==null)return x(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let n=Ie.get(r);return n==null?(x(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:r,schemas:n}}async function Wr(e,t,r){let n=lt.Buffer.from(e,"base64").toString("utf8"),s=io(n,t.toString());r&&console.log("[Accelerate] schema with override:",s);let o=await dt(s);return{base64Override:lt.Buffer.from(s,"utf8").toString("base64"),overrideHash:o}}function io(e,t){let r=co(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=mo(n,t,fo(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function co(e){let t="datasource";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){r=mt(e,r+2);continue}if(n==="/"&&e[r+1]==="*"){r=pt(e,r+2);continue}if(n==='"'){r=gt(e,r+1);continue}if(e.startsWith(t,r)&&!Hr(e[r-1])&&!Hr(e[r+t.length])){let s=uo(e,r+t.length,"{");if(s===-1)return null;let o=lo(e,s);return o===-1?null:{closeBraceIndex:o,openBraceIndex:s}}}return null}function uo(e,t,r){for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=mt(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=pt(e,n+2);continue}if(s==='"'){n=gt(e,n+1);continue}if(s===r)return n}return-1}function lo(e,t){let r=0;for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=mt(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=pt(e,n+2);continue}if(s==='"'){n=gt(e,n+1);continue}if(s==="{"){r+=1;continue}if(s==="}"&&(r-=1,r===0))return n}return-1}function mt(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 Vn=Object.create;var pe=Object.defineProperty;var Kn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Jn=Object.getPrototypeOf,Yn=Object.prototype.hasOwnProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var ne=(e,t)=>{for(var r in t)pe(e,r,{get:t[r],enumerable:!0})},Ft=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of zn(t))!Yn.call(e,s)&&s!==r&&pe(e,s,{get:()=>t[s],enumerable:!(n=Kn(t,s))||n.enumerable});return e};var D=(e,t,r)=>(r=e!=null?Vn(Jn(e)):{},Ft(t||!e||!e.__esModule?pe(r,"default",{value:e,enumerable:!0}):r,e)),Xn=e=>Ft(pe({},"__esModule",{value:!0}),e);var Zn,h,m=v(()=>{"use strict";Zn=()=>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=Zn()});var A,ge=v(()=>{"use strict";m();A=class extends Error{constructor(r,n,s){super(n,s);this.status=r}name="HTTPError"}});function Wt(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function ts(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,P.safeParse)(es,t,{abortEarly:!0});return s?[null,n]:[r]}function G(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]=ts(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:$e}=new URL(l),jn=t.shadowDBPort;if(p!=="localhost"||Number(y)!==E||re!=="localhost"||Number($e)!==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,Ht,es,ke=v(()=>{"use strict";m();P=require("valibot");ge();Ht=/^(postgres|postgresql):\/\//,es=(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)(Ht)),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)(Ht))}))});function Qe(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),fe.default.platform==="darwin"?rs(e):fe.default.platform==="win32"?ns(e):ss(e)}var w,Ce,fe,U,Ue,K,rs,ns,ss,Gt=v(()=>{"use strict";m();w=D(require("path"),1),Ce=D(require("os"),1),fe=D(require("process"),1),U=Ce.default.homedir(),Ue=Ce.default.tmpdir(),{env:K}=fe.default,rs=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(Ue,e)}},ns=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(Ue,e)}},ss=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(Ue,t,e)}}});function zt(e,t){return`${ye.cache}/engine/${e}/${t}`}function se(e){return`${ye.data}/${e}`}async function z(e){try{return await(0,R.access)(e,R.constants.F_OK),!0}catch(t){if(qe(t))return!1;throw t}}async function Jt(e,t){let r=await os(e);await(0,R.writeFile)(t,r),await(0,R.chmod)(t,"755")}async function Yt(e,t){await e.stream().pipeTo(he.WriteStream.toWeb((0,he.createWriteStream)(t,{encoding:"utf8"})))}function qe(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function Xt(e){try{return await(0,R.readFile)(e,{encoding:"utf-8"})}catch(t){if(qe(t))return null;throw t}}async function Zt(e){await(0,R.mkdir)(e,{recursive:!0})}async function er(e,t){try{return(await(0,R.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,Kt.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(qe(r))return[];throw r}}async function J(e){await(0,R.rm)(e,{force:!0,recursive:!0})}var he,R,jt,Vt,Kt,ye,os,Y=v(()=>{"use strict";m();he=require("fs"),R=require("fs/promises"),jt=require("util"),Vt=require("zlib");Gt();Kt=D(require("zeptomatch"),1),ye=Qe("prisma-dev"),os=(0,jt.promisify)(Vt.unzip)});async function ze(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=cs(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 as({debug:t,portKey:u,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await is({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 as(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...i}=o;if(je(a))return await ds({debug:t,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let c=s?.[r]??_;if(!je(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 is(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(Fe,He,We,Ge)+1,i=Object.values(r).filter(p=>p!==void 0),c=o?ls(o):[],u=[...i,...Object.keys(s).map(Number),...c],l=Math.min(Math.max(a,...u)+100,Se),f=(0,be.difference)((0,be.range)(a,l),u),d={port:He,databasePort:Fe,shadowDatabasePort:We,streamsPort:Ge}[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<=Se)return t&&console.debug(`Expanding port lookup to range [${l+1}, ${Se}].`),await(0,Q.getPort)({portRange:[l+1,Se]});throw p}}function je(e){return Number.isFinite(e)&&e>=0}function cs(e,t){let r={},n;for(let s of t){let{databasePort:o,port:a,shadowDatabasePort:i}=s,c=us(s);if(s.name===e){n={databasePort:o,port:a,shadowDatabasePort:i,streamsPort:c};continue}r[o]=!0,r[a]=!0,r[i]=!0,je(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function us(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 ls(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function ds(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=e;if(o!==j){if(o in s)throw t&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new Ke(o);if(Object.values(r).includes(o))throw t&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new Ve(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,be,Fe,He,We,Ge,Se,j,_,N,Ve,Ke,oe=v(()=>{"use strict";m();Q=require("get-port-please"),be=require("remeda"),Fe=51214,He=51213,We=51215,Ge=51216,Se=65535,j=0,_=-1/0;N=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},Ve=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"},Ke=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 x(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 T(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 X(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function Qr(e,t){T(e,t.message,t.status)}var ut,C=v(()=>{"use strict";m();ut=require("buffer")});async function Fr(e,t){let r;try{r=await(0,qr.json)(e)}catch{return T(t,"Invalid input",400),null}let{output:n,success:s}=(0,I.safeParse)(lo,r,{abortEarly:!0});return s?n:(T(t,"Invalid input",400),null)}var qr,I,lo,Hr=v(()=>{"use strict";m();qr=require("stream/consumers"),I=require("valibot");C();lo=(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 Gr(e,t){let r=e.schemaHash;if(r==null)return x(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let n=De.get(r);return n==null?(x(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=po(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 po(e,t){let r=go(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=yo(n,t,Po(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function go(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)&&!Wr(e[r-1])&&!Wr(e[r+t.length])){let s=fo(e,r+t.length,"{");if(s===-1)return null;let o=ho(e,s);return o===-1?null:{closeBraceIndex:o,openBraceIndex:s}}}return null}function fo(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 ho(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 gt(e,t){let r=e.indexOf("*/",t);return r===-1?e.length:r+1}function ft(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 Wr(e){return e!=null&&/[A-Za-z0-9_]/.test(e)}function yo(e,t,r){let n=`"${Eo(t)}"`,s=So(e);for(let[f,d]of s.entries()){let{comment:p,code:y}=Vr(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},lt(s)}let o=wo(e),a=bo(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`${lt(s.slice(0,-1))}${i}${o}${r}`;let u=lt(s),l=u.endsWith(`
|
|
4
|
+
`)||u.endsWith("\r")?"":o;return`${u}${l}${i}${o}${r}`}function So(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 lt(e){return e.map(t=>`${t.line}${t.terminator}`).join("")}function Vr(e){let t=!1,r=!1;for(let n=0;n<e.length;n+=1){let s=e[n];if(r){if(t){t=!1;continue}if(s==="\\"){t=!0;continue}s==='"'&&(r=!1);continue}if(s==='"'){r=!0;continue}if(s==="/"&&e[n+1]==="/")return{code:e.slice(0,n),comment:e.slice(n)}}return{code:e,comment:""}}function bo(e,t){for(let r of e){let{code:n}=Vr(r.line),s=n.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(s?.[1])return s[1]}return`${t}${mo}`}function Po(e,t){let r=e.lastIndexOf(`
|
|
8
|
+
`,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function wo(e){return e.includes(`\r
|
|
9
9
|
`)?`\r
|
|
10
10
|
`:`
|
|
11
|
-
`}function
|
|
11
|
+
`}function Eo(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var dt,De,mo,Kr=v(()=>{"use strict";m();dt=require("buffer");C();De=new Map;mo=" "});function ie(e,t){let r=e[t];return Array.isArray(r)?r.at(-1):r}var ht=v(()=>{"use strict";m()});function Jr(e,t){let r=(e.method??"GET").toUpperCase(),n=`${t.origin}${e.url??"/"}`,s={headers:Ro(e.headers),method:r};return vo.has(r)||(s.body=yt.Readable.toWeb(e),s.duplex="half"),new Request(n,s)}async function Yr(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,zr.pipeline)(yt.Readable.fromWeb(e.body),t)}function Ro(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 yt,zr,vo,Xr=v(()=>{"use strict";m();yt=require("stream"),zr=require("stream/promises"),vo=new Set(["GET","HEAD"])});var tn={};ne(tn,{createHTTPServer:()=>To,wrap:()=>O});function O(e,t){return async function(n,s,o){let a=t?Date.now():0;t&&s.once("finish",()=>{let i=Date.now()-a;console.log("[Accelerate]",`<-- ${n.method??"?"} ${n.url??""} ${s.statusCode} ${i}ms`)});try{await e(n,s,o)}catch(i){try{xo(i,s,n,t)}catch(c){t&&console.error("[Accelerate]","error while handling handler error",c),s.destroyed||s.destroy()}}}}function xo(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){Qr(t,e);return}console.error("[Accelerate]",e);try{X(t,500)}catch(s){n&&console.error("[Accelerate]","failed to write 500 response (client likely disconnected)",s),t.destroy()}}function To(e){let{router:t}=e;return{async listen(r){let n=(0,Zr.createServer)((a,i)=>{t.lookup(a,i)}),o=(await Io(n,r)).port;return n.on("error",a=>{console.error("[Accelerate]",a)}),{async close(){await(0,en.promisify)(n.close.bind(n))()},port:o,url:`http://localhost:${o}`}}}}function Io(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 Zr,en,Ae=v(()=>{"use strict";m();Zr=require("http"),en=require("util");oe();ge();C()});function _e(e){return{traceparent:ie(e.headers,"traceparent"),"X-capture-telemetry":ie(e.headers,"x-capture-telemetry")}}var rn=v(()=>{"use strict";m();ht()});async function sn(e,t){let r;try{r=await(0,nn.json)(e)}catch{return x(t,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:n,output:s,success:o}=(0,b.safeParse)(Do,r,{abortEarly:!0});return o?s:(x(t,{EngineNotStarted:{reason:"InvalidRequest",issues:n}},400),null)}function on(e,t){let{output:r,success:n}=(0,b.safeParse)(Ao,e);return n?r:(x(t,{EngineMalfunction:{}},500),null)}var nn,b,Do,Ao,an=v(()=>{"use strict";m();nn=require("stream/consumers"),b=require("valibot");C();Do=(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))});Ao=(0,b.looseObject)({id:(0,b.union)([(0,b.string)(),(0,b.number)()])})});function cn(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 un=v(()=>{"use strict";m()});var bt={};ne(bt,{Engine:()=>St,handleEngineError:()=>No});function No(e,t){if(console.error(e),e instanceof ce){x(t,{EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500);return}if(e instanceof Z){T(t,e.responseBody,e.statusCode);return}X(t,500)}var dn,mn,pn,gn,fn,hn,_o,Oo,ln,St,ce,Z,Pt=v(()=>{"use strict";m();dn=require("child_process"),mn=require("events"),pn=require("fs/promises"),gn=require("path"),fn=require("timers/promises");un();hn=require("std-env");Y();C();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:_o,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:Oo,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:ln}=hn.process.env),St=class e{static#r=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:r}=t,n=`${t.schemaHash}:${t.clientVersion}`;try{let s=e.#r.get(n);if(s)return s;let o=new e(t);return e.#r.set(n,o),r&&console.debug("[Query Engine] starting...",t),await o.start(),r&&console.debug("[Query Engine] started!"),o}finally{e.stopAll(n)}}static async stopAll(t){let n=(await Promise.allSettled(Array.from(e.#r.entries()).filter(([s])=>s!==t).map(async([s,o])=>{try{await o.stop()}finally{e.#r.delete(s)}}))).filter(s=>s.status==="rejected").map(s=>s.reason);if(n.length>0)throw new AggregateError(n,"Failed to stop engines")}async commitTransaction(t,r){return await this.#i(t,r,"commit")}async request(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(n,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await Z.fromResponse(o);return await o.text()}async rollbackTransaction(t,r){return await this.#i(t,r,"rollback")}async startTransaction(t,r){let{url:n}=await this.start(),s=this.#n(r),o=await fetch(`${n}/transaction/start`,{body:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await Z.fromResponse(o);return await o.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:r,resolve:n}=cn();this.#t=t;let s=Oo||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",s);let{proxySignals:o}=await import("foreground-child/proxy-signals"),a=(0,dn.spawn)(s,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});o(a),a.stderr.setEncoding("utf8"),a.stdout.setEncoding("utf8");let i=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.#t=null,r(new ce(String(l))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(l,f)=>{this.#t=null,r(new ce(`Query Engine exited with code ${l} and signal ${f}`))};return a.once("exit",u),a.stdout.on("data",i),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await(0,
|
|
13
|
+
Received data: ${l}`));n({childProcess:a,url:`http://${p}:${y}`})},c=l=>{this.#t=null,r(new ce(String(l))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(l,f)=>{this.#t=null,r(new ce(`Query Engine exited with code ${l} and signal ${f}`))};return a.once("exit",u),a.stdout.on("data",i),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await(0,mn.once)(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#o();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let r=zt(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,pn.mkdir)(r,{recursive:!0});let{binaryTarget:n}=this.#e.platform,s=n==="windows"?".exe":"",o=(0,gn.join)(r,`query-engine-${n}${s}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(_o==="1"||await z(o)===!1)&&await this.#a({commitHash:t,extension:s,engineBinaryPath:o}),o}async#o(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let n=(await t.json()).devDependencies?.["@prisma/engines-version"];if(!n)throw new Error("Couldn't find engines version in package.json");let s=n.split(".").at(-1);if(!s)throw new Error("Couldn't find commit hash in engines version");return s}async#a(t){let{commitHash:r,extension:n,engineBinaryPath:s}=t,{binaryTarget:o}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${o}/query-engine${n}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",a);let i=await fetch(a);if(!i.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${i.status}`);ln&&await(0,fn.setTimeout)(Number(ln)),await Jt(await i.arrayBuffer(),s),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",s)}#n(t){let r={};for(let[n,s]of Object.entries(t))s!=null&&(r[n]=s);return r}async#i(t,r,n){let{url:s}=await this.#t,o=this.#n(r),a=await fetch(`${s}/transaction/${t}/${n}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await Z.fromResponse(a);try{return await a.json()}catch{return{}}}};ce=class extends Error{name="EngineStartError"},Z=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 yn={};ne(yn,{getQueryPlanExecutorServer:()=>Mo,queryPlanExecutorVersion:()=>Sn.version});async function Mo(e){return wt===void 0&&(wt=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"}})),wt}var W,Sn,wt,bn=v(()=>{"use strict";m();W=require("@prisma/query-plan-executor"),Sn=require("@prisma/query-plan-executor")});var vn={};ne(vn,{registerAccelerateRoutes:()=>$o});function Oe(){return Pn??=Promise.resolve().then(()=>(Pt(),bt)),Pn}function Bo(){return En??=Promise.resolve().then(()=>(bn(),yn)),En}async function Lo(){return wn??=import("@prisma/get-platform").then(async({default:e})=>await e.getPlatformInfo()),await wn}function $o(e,t,r){e.on("POST","/invalidate",O(async(s,o)=>{G(s,t),await Fr(s,o)!==null&&X(o,200)},r));for(let s of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])e.on("POST",s,O(async(o,a,i)=>{G(o,t);try{let c=await Et(a,t,i);if(c===null)return;let u=await(0,vt.text)(o),l=i.transactionId,f=await c.request(u,{..._e(o),"X-transaction-id":l});T(a,f)}catch(c){let{handleEngineError:u}=await Oe();u(c,a)}},r));for(let s of["commit","rollback"])e.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${s}`,O(async(o,a,i)=>{G(o,t);try{let c=await Et(a,t,i);if(c===null)return;let u=i.transactionId;if(u==null){x(a,{EngineMalfunction:{}},500);return}let l=`${s}Transaction`,f=await c[l](u,_e(o));x(a,f)}catch(c){let{handleEngineError:u}=await Oe();u(c,a)}},r));e.on("PUT","/:clientVersion/:schemaHash/schema",O(async(s,o,a)=>{G(s,t);let i=await(0,vt.text)(s);if(!i){T(o,"Missing schema",400);return}let c=a.schemaHash;if(c==null){T(o,"Missing schema hash",400);return}let u=De.get(c);if(u==null){if(c!==await mt(i)){T(o,"Schema hash mismatch",400);return}let l=await jr(i,t.db.prismaORMConnectionString,t.debug);De.set(c,{base64Original:i,...l}),T(o,c);return}if(i!==u.base64Original){T(o,"Schema mismatch",400);return}T(o,c)},r)),e.on("POST","/:clientVersion/:schemaHash/transaction/start",O(async(s,o,a)=>{G(s,t);let i=await sn(s,o);if(i!==null)try{let c=await Et(o,t,a);if(c===null)return;let u=await c.startTransaction(i,_e(s)),l=on(u,o);if(l===null)return;let{id:f}=l,d=a.clientVersion,p=a.schemaHash;x(o,{...u,"data-proxy":{endpoint:`http://localhost:${t.port}/${d}/${p}/itx/${f}`}})}catch(c){let{handleEngineError:u}=await Oe();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,O(async(a,i)=>{G(a,t);let{getQueryPlanExecutorServer:c,queryPlanExecutorVersion:u}=await Bo(),l=ie(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=Jr(a,{origin:`http://localhost:${t.port}`}),p=await f.fetch(d);await Yr(p,i)},r))}async function Et(e,t,r){let{Engine:n}=await Oe(),s=Gr(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 Lo(),schemaHash:a})}var vt,Pn,wn,En,Rn=v(()=>{"use strict";m();vt=require("stream/consumers");ke();Hr();Kr();ht();ge();Xr();C();Ae();rn();an()});var xn={};ne(xn,{registerUtilityRoutes:()=>ko});function ko(e,t,r){e.on("POST","/database/dump",O(async(n,s)=>{await t.db.dump(t.databaseDumpPath),x(s,{dumpPath:t.databaseDumpPath},201)},r)),e.on("GET","/health",O((n,s)=>{x(s,{name:t.name})},r))}var Tn=v(()=>{"use strict";m();C();Ae()});var Sa={};module.exports=Xn(Sa);m();var Gn=require("timers/promises");m();m();ke();m();var Ie=require("net"),_r=require("path"),Or=require("pathe/utils");Y();oe();m();var Ye=require("perf_hooks"),mr=require("@electric-sql/pglite");m();var sr=require("buffer"),tr=500,rr=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,ms=new RegExp(`(?:${rr.source}\\.)*${rr.source}`),ps=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${ms.source})`,"gi"),gs=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,nr=/prismaQuery='([^']+)'/,fs=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")]),gs=[/^BEGIN\b/i,/^COMMIT\b/i,/^ROLLBACK\b/i,/^SAVEPOINT\b/i,/^RELEASE\b/i,/^SET\b/i,/^SHOW\b/i,/^DISCARD\b/i,/^DEALLOCATE\b/i,/^CLOSE\b/i,/^CREATE EXTENSION\b/i,/^WITH state_assign\b/i];function sr(){return{generatedAt:Date.now(),queries:[]}}function q(e){return e.replace(/\s+/g," ").trim()}function or(e){return lr(q(e))}function ar(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?lr(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function fs(e){let t=new Set;for(let r of e.matchAll(ds)){let n=r[1];if(!n)continue;let s;for(let o of n.matchAll(ms))s=o[1]??o[2]??o[3]??o[4];s&&!s.startsWith("pg_")&&t.add(s)}return Array.from(t)}function hs(e){return ps.has(e)?!0:gs.some(t=>t.test(e))}function ir(e){if(hs(q(e)))return null;let t=fs(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 cr(e){let t=e.match(rr);if(!t?.[1])return{cleanedSql:q(e),prismaQueryInfo:null};let r=e.replace(rr,"");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(nr.Buffer.from(a,"base64url").toString("utf8")))}catch{l=void 0}return{cleanedSql:r,prismaQueryInfo:{action:u,isRaw:!1,model:c,payload:l}}}function ur(e,t={}){let r=new Set(t.excludeApplications??[]),n=ys(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 ys(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,er):er}function lr(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)&4294967295;return(t>>>0).toString(36)}var Pe=new WeakMap;function mr(e){let t=Pe.get(e);if(t&&!t.closed)return t.bridge;let r=Ss(e),n={bridge:{close:()=>(n.closed||(n.closed=!0,n.sessions.clear(),n.subscribers.clear(),n.queryQueue.enqueue=n.originalEnqueue,n.queryQueue.clearQueueForHandler=n.originalClearQueueForHandler,Pe.delete(e)),Promise.resolve()),subscribe:s=>(n.subscribers.add(s),()=>{n.subscribers.delete(s)})},closed:!1,originalClearQueueForHandler:r.clearQueueForHandler.bind(r),originalEnqueue:r.enqueue.bind(r),queryQueue:r,sessions:new Map,subscribers:new Set};return r.clearQueueForHandler=s=>{n.sessions.delete(s),n.originalClearQueueForHandler(s)},r.enqueue=async(s,o,a)=>{let i=bs(n,s),c=Es(o);Ps(i,c);let u=ws(i,c);if(!u)return await n.originalEnqueue(s,o,a);let l={commandTags:[],dataRowCount:0},f=new dr.protocol.Parser,d=Je.performance.now(),p=await n.originalEnqueue(s,o,E=>{f.parse(E,re=>{As(l,re)}),a(E)}),y=Math.max(0,Je.performance.now()-d);return _s(n,{applicationName:u.applicationName,durationMs:y,query:u.query,responseStats:l}),p},Pe.set(e,n),n.bridge}async function pr(e){await Pe.get(e)?.bridge.close()}function Ss(e){let t=e.queryQueue;if(!t||typeof t.enqueue!="function"||typeof t.clearQueueForHandler!="function")throw new Error("PGLiteSocketServer query queue is unavailable for query insights capture");return t}function bs(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 Ps(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 ws(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 Es(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 vs(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return Rs(t);case"P":return xs(t);case"B":return Ts(t);case"E":return Is(t);case"C":return Ds(t);default:return null}}function vs(e){let t=8,r=null;for(;t<e.length-1;){let n=$(e,t);if(!n||n.value==="")break;t=n.nextOffset;let s=$(e,t);if(!s)break;t=s.nextOffset,n.value==="application_name"&&(r=s.value)}return{applicationName:r,kind:"startup"}}function Rs(e){let t=$(e,5);return t?{kind:"query",query:t.value}:null}function xs(e){let t=$(e,5);if(!t)return null;let r=$(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function Ts(e){let t=$(e,5);if(!t)return null;let r=$(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function Is(e){let t=$(e,5);return t?{kind:"execute",portalName:t.value}:null}function Ds(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=$(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function $(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function As(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=cr(t.query),n=ir(r.cleanedSql);if(!n)return;let s=or(r.cleanedSql),o={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:ar(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:s,reads:0,rowsReturned:Os(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let a of e.subscribers)a([o])}function Os(e){let t=e.commandTags.reduce((r,n)=>r+Ns(n),0);return Math.max(t,e.dataRowCount)}function Ns(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}m();var F=require("fs"),H=require("fs/promises"),fr=require("module"),hr=require("path"),k=require("url"),Ms=(0,fr.createRequire)(h),Bs=["initdb.wasm","pglite.data","pglite.wasm"],Xe="pglite-seed.tar.gz",yr={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"},Ls=[...Bs.map(e=>({fileName:e,kind:"core",name:e})),{fileName:Xe,kind:"core",name:Xe},...Object.entries(yr).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],ve=new Map,$s=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),we=null;async function Ze(){await Ws();let e=Sr();if(e)return await Qs(e),await ks(e);let t=Hs(),r=t.href,n=ve.get(r);return n||(n=Cs(t),ve.set(r,n)),await n}async function ks(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=ve.get(t);return r||(r=Us(e),ve.set(t,r)),await r}async function Cs(e){let t=Re(new URL("./runtime-assets/",h)),[r,n,s]=await Promise.all([(0,H.readFile)(Ee("pglite.data",e,t)),(0,H.readFile)(Ee(Xe,e,t)),(0,H.readFile)(Ee("pglite.wasm",e,t))]),o=br();return{extensions:Object.fromEntries(Object.entries(yr).map(([a,i])=>[a,Ee(i,e,t)])),fsBundle:new Blob([Uint8Array.from(r)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await o.compile(s)}}async function Us(e){let[t,r,n]=await Promise.all([Ye(e.fsBundle),Ye(e.loadDataDir),Ye(e.wasmModule)]),s=br();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(r)]),wasmModule:await s.compile(n)}}async function Qs(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",Re(new URL("./",e.initdbWasm))),r=(0,k.fileURLToPath)(t);(0,F.existsSync)(r)||await(0,H.copyFile)((0,k.fileURLToPath)(e.initdbWasm),r)}function Re(e){return e instanceof URL?gr(e):gr((0,k.pathToFileURL)(e))}function gr(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function qs(){let e=Ms.resolve("@electric-sql/pglite");return Re((0,hr.dirname)(e))}function Hs(){let e=Re(new URL("./",h));if(Fs(e))return e;if(Gs())return qs();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function Fs(e){return Ls.every(t=>(0,F.existsSync)((0,k.fileURLToPath)(new URL(t.fileName,e))))}function Sr(){return globalThis[$s]??null}async function Ws(){!js()||Sr()||(we||(we=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw we=null,e})),await we)}function Gs(){let e=(0,k.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 js(){return typeof globalThis.Bun<"u"}function br(){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,H.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 Ee(e,t,r){let n=new URL(e,t);if((0,F.existsSync)((0,k.fileURLToPath)(n)))return n;if(r){let s=new URL(e,r);if((0,F.existsSync)((0,k.fileURLToPath)(s)))return s}return n}m();var rt=require("@electric-sql/pglite"),M="_prisma_dev_wal",tt="events",Er="install_all_triggers",Pr="capture_event",wr="prisma_dev_wal_capture",ae=new WeakMap,Vs=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function nt(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 et(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&&Rr(l)&&et(o,e),l},i=async(c,u)=>{let l=[],f=new rt.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&&st(l)&&et(o,e)};return e.execProtocolRaw=a,e.execProtocolRawStream=i,ae.set(e,o),await xr(o,e),o.bridge}async function vr(e){let t=ae.get(e);t&&await t.bridge.close()}function st(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&&Vs.has(r))return!0}return!1}function Rr(e){if(e.length===0)return!1;let t=[];return new rt.protocol.Parser().parse(e,n=>{t.push(n)}),st(t)}async function xr(e,t){e.ensureInfrastructurePromise??=ot(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${M}"`),await t.exec(`
|
|
21
|
-
CREATE TABLE IF NOT EXISTS "${M}"."${
|
|
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")]),hs=[/^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 or(){return{generatedAt:Date.now(),queries:[]}}function q(e){return e.replace(/\s+/g," ").trim()}function ar(e){return dr(q(e))}function ir(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?dr(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function ys(e){let t=new Set;for(let r of e.matchAll(ps)){let n=r[1];if(!n)continue;let s;for(let o of n.matchAll(gs))s=o[1]??o[2]??o[3]??o[4];s&&!s.startsWith("pg_")&&t.add(s)}return Array.from(t)}function Ss(e){return fs.has(e)?!0:hs.some(t=>t.test(e))}function cr(e){if(Ss(q(e)))return null;let t=ys(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function Je(e){if(Array.isArray(e))return e.map(Je);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Je(n)]))}return e}function ur(e){let t=e.match(nr);if(!t?.[1])return{cleanedSql:q(e),prismaQueryInfo:null};let r=e.replace(nr,"");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=Je(JSON.parse(sr.Buffer.from(a,"base64url").toString("utf8")))}catch{l=void 0}return{cleanedSql:r,prismaQueryInfo:{action:u,isRaw:!1,model:c,payload:l}}}function lr(e,t={}){let r=new Set(t.excludeApplications??[]),n=bs(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 bs(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,tr):tr}function dr(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 Pe(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 we=new WeakMap;function pr(e){let t=we.get(e);if(t&&!t.closed)return t.bridge;let r=Pe(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,we.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=Ps(n,s),c=vs(o);ws(i,c);let u=Es(i,c);if(!u)return await n.originalEnqueue(s,o,a);let l={commandTags:[],dataRowCount:0},f=new mr.protocol.Parser,d=Ye.performance.now(),p=await n.originalEnqueue(s,o,E=>{f.parse(E,re=>{_s(l,re)}),a(E)}),y=Math.max(0,Ye.performance.now()-d);return Os(n,{applicationName:u.applicationName,durationMs:y,query:u.query,responseStats:l}),p},we.set(e,n),n.bridge}async function gr(e){await we.get(e)?.bridge.close()}function Ps(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 ws(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 Es(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 vs(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 Rs(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return xs(t);case"P":return Ts(t);case"B":return Is(t);case"E":return Ds(t);case"C":return As(t);default:return null}}function Rs(e){let t=8,r=null;for(;t<e.length-1;){let n=$(e,t);if(!n||n.value==="")break;t=n.nextOffset;let s=$(e,t);if(!s)break;t=s.nextOffset,n.value==="application_name"&&(r=s.value)}return{applicationName:r,kind:"startup"}}function xs(e){let t=$(e,5);return t?{kind:"query",query:t.value}:null}function Ts(e){let t=$(e,5);if(!t)return null;let r=$(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function Is(e){let t=$(e,5);if(!t)return null;let r=$(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function Ds(e){let t=$(e,5);return t?{kind:"execute",portalName:t.value}:null}function As(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=$(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function $(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function _s(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 Os(e,t){let r=ur(t.query),n=cr(r.cleanedSql);if(!n)return;let s=ar(r.cleanedSql),o={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:ir(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:s,reads:0,rowsReturned:Ns(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let a of e.subscribers)a([o])}function Ns(e){let t=e.commandTags.reduce((r,n)=>r+Ms(n),0);return Math.max(t,e.dataRowCount)}function Ms(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}m();var Bs=new Set([66,67,68,69,72,80,100]),Ls=90;function $s(e){let t=e[0];return t!==void 0&&Bs.has(t)}function ks(){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]===Ls||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 fr(e){let t=Pe(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=$s(a),u=s.get(o);if(!c&&!u)return await r(o,a,i);u||(u=ks(),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"),F=require("fs/promises"),yr=require("module"),Sr=require("path"),k=require("url"),Cs=(0,yr.createRequire)(h),Us=["initdb.wasm","pglite.data","pglite.wasm"],Ze="pglite-seed.tar.gz",br={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"},Qs=[...Us.map(e=>({fileName:e,kind:"core",name:e})),{fileName:Ze,kind:"core",name:Ze},...Object.entries(br).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],Re=new Map,qs=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),Ee=null;async function et(){await zs();let e=Pr();if(e)return await Gs(e),await Fs(e);let t=Vs(),r=t.href,n=Re.get(r);return n||(n=Hs(t),Re.set(r,n)),await n}async function Fs(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=Re.get(t);return r||(r=Ws(e),Re.set(t,r)),await r}async function Hs(e){let t=xe(new URL("./runtime-assets/",h)),[r,n,s]=await Promise.all([(0,F.readFile)(ve("pglite.data",e,t)),(0,F.readFile)(ve(Ze,e,t)),(0,F.readFile)(ve("pglite.wasm",e,t))]),o=wr();return{extensions:Object.fromEntries(Object.entries(br).map(([a,i])=>[a,ve(i,e,t)])),fsBundle:new Blob([Uint8Array.from(r)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await o.compile(s)}}async function Ws(e){let[t,r,n]=await Promise.all([Xe(e.fsBundle),Xe(e.loadDataDir),Xe(e.wasmModule)]),s=wr();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(r)]),wasmModule:await s.compile(n)}}async function Gs(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",xe(new URL("./",e.initdbWasm))),r=(0,k.fileURLToPath)(t);(0,H.existsSync)(r)||await(0,F.copyFile)((0,k.fileURLToPath)(e.initdbWasm),r)}function xe(e){return e instanceof URL?hr(e):hr((0,k.pathToFileURL)(e))}function hr(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function js(){let e=Cs.resolve("@electric-sql/pglite");return xe((0,Sr.dirname)(e))}function Vs(){let e=xe(new URL("./",h));if(Ks(e))return e;if(Js())return js();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function Ks(e){return Qs.every(t=>(0,H.existsSync)((0,k.fileURLToPath)(new URL(t.fileName,e))))}function Pr(){return globalThis[qs]??null}async function zs(){!Ys()||Pr()||(Ee||(Ee=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw Ee=null,e})),await Ee)}function Js(){let e=(0,k.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 Ys(){return typeof globalThis.Bun<"u"}function wr(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function Xe(e){if(e.protocol==="file:")return await(0,F.readFile)(e);let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch runtime asset ${e.href}: ${t.status} ${t.statusText}`);return new Uint8Array(await t.arrayBuffer())}function ve(e,t,r){let n=new URL(e,t);if((0,H.existsSync)((0,k.fileURLToPath)(n)))return n;if(r){let s=new URL(e,r);if((0,H.existsSync)((0,k.fileURLToPath)(s)))return s}return n}m();var nt=require("@electric-sql/pglite"),M="_prisma_dev_wal",rt="events",Rr="install_all_triggers",Er="capture_event",vr="prisma_dev_wal_capture",ae=new WeakMap,Xs=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&&Tr(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 Ir(o,e),o.bridge}async function xr(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&&Xs.has(r))return!0}return!1}function Tr(e){if(e.length===0)return!1;let t=[];return new nt.protocol.Parser().parse(e,n=>{t.push(n)}),ot(t)}async function Ir(e,t){e.ensureInfrastructurePromise??=at(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${M}"`),await t.exec(`
|
|
21
|
+
CREATE TABLE IF NOT EXISTS "${M}"."${rt}" (
|
|
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 "${M}"."${
|
|
32
|
+
CREATE OR REPLACE FUNCTION "${M}"."${Er}"()
|
|
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 "${M}"."${
|
|
41
|
+
INSERT INTO "${M}"."${rt}" (
|
|
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 "${M}"."${
|
|
62
|
+
CREATE OR REPLACE FUNCTION "${M}"."${Rr}"()
|
|
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 = '${vr}'
|
|
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 "${M}"."${
|
|
89
|
-
'${
|
|
88
|
+
'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${M}"."${Er}"()',
|
|
89
|
+
'${vr}',
|
|
90
90
|
target::text
|
|
91
91
|
);
|
|
92
92
|
END LOOP;
|
|
93
93
|
END;
|
|
94
94
|
$$;
|
|
95
|
-
`),await
|
|
95
|
+
`),await Dr(e,t)}),await e.ensureInfrastructurePromise}async function Dr(e,t){await at(e,t,async()=>{await t.query(`SELECT "${M}"."${Rr}"()`)})}async function Zs(e,t){await Ir(e,t),await Dr(e,t);let r=await at(e,t,async()=>await t.query(`
|
|
96
96
|
WITH drained AS (
|
|
97
|
-
DELETE FROM "${M}"."${
|
|
97
|
+
DELETE FROM "${M}"."${rt}"
|
|
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(eo);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 tt(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await Zs(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function at(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&ae.get(t)!==e&&(e.closed=!0)}}function eo(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:to(e.op)}}function to(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 ro=10,Nr="127.0.0.1",Mr=128*1024*1024,Br=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],S={connectionLimit:ro,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},no=`postgres://${S.username}:${S.password}@localhost`,it=new URLSearchParams({sslmode:S.sslMode}),Lr=new URLSearchParams({...Object.fromEntries(it.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 $r(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 ct(e,t){if(e==="shadow_database"&&!t.dryRun)return await so(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?Cr(e,t,{db:null,port:r,server:null}):await kr(e,t,{port:r,updateServerStatePort:!0})}async function so(e,t=async()=>await kr("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,s=null,o=!1,a=new Set,i=(0,Ie.createServer)(u),c=await oo(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 ao(i),r&&console.debug(`[shadow_database] lazy proxy stopped on port ${c}`)}catch(p){console.error("[shadow_database] lazy proxy stop error",p),d.push(p)}try{await s?.catch(()=>null),await n?.close()}catch(p){console.error("[shadow_database] backend close error",p),d.push(p)}if(d.length>0)throw new AggregateError(d,"Failed to close shadow_database properly")},connectionString:Te(c,it),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:c,prismaORMConnectionString:Te(c,Lr),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,Ie.createConnection)({host:Nr,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 kr(e,t,r){let{debug:n}=t,{port:s,updateServerStatePort:o}=r,i=await(e==="shadow_database"?io:Ur)(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});fr(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),Cr(e,t,{db:i,port:f,server:l})}function Cr(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 st(s)},attachQueryInsightsBridge:()=>{if(e!=="database"||!a)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(pr(a))},close:async()=>{let c=[];try{await a?.stop(),n&&console.debug(`[${e}] server stopped on port ${o}`)}catch(u){console.error(`[${e}] server stop error`,u),c.push(u)}if(e==="database"){try{a&&await gr(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 xr(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:Te(o,it),dump:async c=>{e==="shadow_database"||!s||await uo({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=co(s,c,u).catch(d=>{throw i.delete(l),d}),i.set(l,f)),await f},port:o,prismaORMConnectionString:Te(o,Lr),terminalCommand:`PGPASSWORD=${S.password} PGSSLMODE=${S.sslMode} psql -h localhost -p ${o} -U ${S.username} -d ${S.database}`}}function Te(e,t){return`${no}:${e}/${S.database}?${t.toString()}`}async function Ur(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await et(),s=e==="memory://"||!await z((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:Mr,loadDataDir:s?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...Br],wasmModule:n.wasmModule});return await $r(o),o}async function oo(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,Nr)})}async function ao(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 io(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await et(),s=await r.create({database:S.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Mr,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...Br],wasmModule:n.wasmModule});return await $r(s),s}async function co(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 = ${Ar(t)}
|
|
117
|
+
AND relation.relname = ${Ar(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 ue({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,V.join)(se(
|
|
121
|
-
`,{encoding:"utf-8"})}};async function Ln(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 B.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=se(s);try{if(!await(0,te.check)(l,{lockfilePath:(0,V.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"}}}var Mt=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},ee=class extends Mt{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return B.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};m();var kn=require("crypto"),$t=require("timers/promises"),kt=require("util"),Cn=require("std-env");Y();var Go="application/json",de={connection:"close","content-type":Go},jo={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},Ct={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{headers:{properties:{operation:{type:"string"},timestamp:{format:"date-time",type:"string"}},required:["timestamp","operation"],type:"object"},key:{type:"string"},type:{type:"string"}},required:["type","key","headers"],type:"object"},search:{aliases:{rowKey:"key",table:"type"},fields:{eventTime:{bindings:[{jsonPointer:"/headers/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},key:{bindings:[{jsonPointer:"/key",version:1}],exact:!0,exists:!0,kind:"keyword"},operation:{bindings:[{jsonPointer:"/headers/operation",version:1}],exact:!0,exists:!0,kind:"keyword"},type:{bindings:[{jsonPointer:"/type",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};async function Un(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:o,queryInsightsBridge:a,walBridge:i}=e,c=s==="stateless",u=c?sa(n):n,l=Oe(u),f=!c&&await z(l);Cn.process.env.DS_LOCAL_DATA_ROOT=Tt(),c&&await J(l);let d=await Ko({debug:r,hadExistingStreamsData:f,name:u,port:o}),p={serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path,streamName:Rt,url:Ne(d.exports.http.url)};try{await Yo(p);let y=await Dn({bridge:a,debug:r,serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path}),E=new Ut({dbServer:t,debug:r,streamUrl:p.url}),re=i.subscribe(Le=>{E.enqueue(Le)});return{close:async()=>{re(),await E.close(),await y.close(),await d.close(),await(0,$t.setTimeout)(100),c&&await J(l)},experimental:p,experimentalQueryInsights:y.experimental}}catch(y){throw await d.close().catch(()=>{}),await(0,$t.setTimeout)(100),c&&await J(l).catch(()=>{}),y}}var Vo=["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 Ko(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||!zo(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(Oe(n)),await a()}}function zo(e){return Jo(e).map(r=>r.toLowerCase()).some(r=>Vo.some(n=>r.includes(n)))}function Jo(e){let t=[],r=[e],n=new Set;for(;r.length>0;){let s=r.shift();if(!(s==null||n.has(s))){if(n.add(s),typeof s=="string"){t.push(s);continue}if(s instanceof AggregateError)for(let o of s.errors)r.push(o);if(s instanceof Error){t.push(s.message);let o=s.cause;o!==void 0&&r.push(o)}}}return t}var Ut=class{#r;#e;#t;#s;#o;constructor(t){this.#r=t.dbServer,this.#e=t.debug,this.#t=Promise.resolve(),this.#s=t.streamUrl,this.#o=new Set}enqueue(t){t.length!==0&&(this.#t=this.#t.then(async()=>{let r=await this.#a(t);r.length!==0&&(await ea(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=$n(t.record),a=$n(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=ta(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`)),ra(n))}};async function Yo(e){let t=await fetch(e.url,{headers:de,method:"PUT"});if(!t.ok)throw await me(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(jo),headers:de,method:"POST"});if(!r.ok)throw await me(r,`Failed to configure ${e.streamName}`);let n=await Xo(e);if(Zo(n,e.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${e.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${e.url}/_schema`,{body:JSON.stringify(Ct),headers:de,method:"POST"});if(!s.ok)throw await me(s,`Failed to install schema for ${e.streamName}`)}async function Xo(e){let t=await fetch(`${e.url}/_schema`,{headers:de,method:"GET"});if(!t.ok)throw await me(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function Zo(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,kt.isDeepStrictEqual)(r,Ct.schema)&&(0,kt.isDeepStrictEqual)(e.search,Ct.search)}async function ea(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:de,method:"POST"});if(!r.ok)throw await me(r,"Failed to append to prisma-wal")}async function me(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function ta(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=na(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function ra(e){return JSON.stringify(Qt(e))}function Qt(e){return Array.isArray(e)?e.map(t=>Qt(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Qt(r)])):e}function $n(e){return e?structuredClone(e):null}function na(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?String(e):null;if(typeof e=="bigint")return e.toString();if(typeof e=="boolean")return e?"true":"false";try{return JSON.stringify(e)}catch{return null}}function sa(e){return`${e}.${(0,kn.randomUUID)().replaceAll("-","")}`}async function Qn(e){let t=await B.createExclusively(e),r=null,n=null,s=null,o=null;try{[r,s]=await Promise.all([it("database",t),it("shadow_database",t)]);let a,i;t.dryRun?(a=ca(),i=ua(),o=la()):(a=await r.attachWalEventBridge(),i=await r.attachQueryInsightsBridge(),o=await Un({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,queryInsightsBridge:i,walBridge:a})),n=await Tn(r,t);let c=oa(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{queryInsights:o.experimentalQueryInsights,streams:o.experimental});let u=ia(a),l=In(o.experimentalQueryInsights),f=r,d=s,p=n,y=o,E=async()=>{u.close(),await qn(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 aa(t,[n,o,r,s],a)}}function oa(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:Ft({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 qn(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 aa(e,t,r){try{await qn(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function ia(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=da(e,()=>{t.delete(r)});return r=()=>n.close(),t.add(r),n.stream},subscribe:r=>e.subscribe(r)},close:()=>{for(let r of[...t])r();t.clear()}}}function ca(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function ua(){return{async close(){},subscribe(){return()=>{}}}}function la(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function da(e,t){let r=[],n=!1,s=null,o=e.subscribe(i=>{if(!n){if(s){let c=s;s=null,c.resolve({done:!1,value:i});return}r.push(i)}}),a=()=>{if(!n&&(n=!0,o(),r.length=0,t(),s)){let i=s;s=null,i.resolve({done:!0,value:void 0})}};return{close:a,stream:{[Symbol.asyncIterator](){return this},next(){return r.length>0?Promise.resolve({done:!1,value:r.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((i,c)=>{s={reject:c,resolve:i}})},return(){return a(),Promise.resolve({done:!0,value:void 0})},throw(i){let c=s;return a(),c&&c.reject(i),Promise.reject(i instanceof Error?i:new Error(String(i)))}}}}oe();m();async function Hn(e){let{server:t}=await Qn(e);return t}var L;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,L?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,L?.close().finally(()=>process.exit())});async function ma(){let[,,e]=process.argv;if(!e)return process.send?.({type:"error",code:"unknown",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{L=await Hn({debug:!0,persistenceMode:"stateful",name:e});let t=L.experimental.queryInsights,r={database:L.database,experimental:{queryInsights:{serverUrl:t.serverUrl,sqlitePath:t.sqlitePath,streamName:t.streamName,url:t.url},streams:L.experimental.streams},http:L.http,name:L.name,ppg:L.ppg,shadowDatabase:L.shadowDatabase};process.send?.({type:"started",server:r},void 0)}catch(t){console.error(t);let r=t instanceof Error?t.message:String(t),n=t instanceof ee?"server_already_running":"unknown";process.send?.({type:"error",code:n,error:r},void 0),await(0,Fn.setTimeout)(1e3),process.exit(1)}}ma();
|
|
119
|
+
`);return n.map(s=>s.column_name)}function Ar(e){return`'${e.replaceAll("'","''")}'`}async function uo(e){let{dataDir:t,db:r,debug:n,destinationPath:s}=e,o=r||await Ur(t,n),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:s?(0,Or.filename)(s):void 0,pg:await o.clone()});return s?(n&&console.debug(`[DB] Dumping database to ${s}`),await Yt(i,s)):(n&&console.debug("[DB] Dumping database to memory"),await i.text())}m();var In=D(require("find-my-way"),1);C();async function Dn(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(()=>(Rn(),vn)),Promise.resolve().then(()=>(Tn(),xn)),Promise.resolve().then(()=>(Ae(),tn))]),i={databaseDumpPath:t.databaseDumpPath,db:e,debug:n,name:t.name,port:r,shadowDBPort:t.shadowDatabasePort},c=(0,In.default)({defaultRoute(l,f){T(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(()=>(Pt(),bt));await Promise.allSettled([u.close(),l.stopAll()])},port:u.port,url:u.url}}m();var Dt=require("util");m();var Rt=require("pathe");Y();var xt="prisma-wal",Tt="prisma-queries";function It(){return(0,Rt.join)(ye.data,"durable-streams")}function Ne(e){return(0,Rt.join)(It(),e)}function Me(e,t=xt){return new URL(`/v1/stream/${encodeURIComponent(t)}`,e).toString()}var Co="application/json",Be={connection:"close","content-type":Co},At={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 An(e){return{...e,snapshot:async t=>await Uo(e.url,t)}}async function _n(e){let t={serverUrl:e.serverUrl,sqlitePath:e.sqlitePath,streamName:Tt,url:Me(e.serverUrl,Tt)};await qo(t);let r=new _t({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 Uo(e,t){if(!e)return or();let r=await Qo(e);return lr(r,t)}async function Qo(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 _t=class{#r;#e;#t;constructor(t){this.#r=t.debug,this.#e=Promise.resolve(),this.#t=t.streamUrl}enqueue(t){t.length!==0&&(this.#e=this.#e.then(async()=>{await Wo(this.#t,t),this.#r&&console.debug(`[streams] appended ${t.length} query insight record(s) to ${this.#t}`)}).catch(r=>{console.error("[streams] failed to ingest query insights into prisma-queries",r)}))}async close(){await this.#e}};async function qo(e){let t=await fetch(e.url,{headers:Be,method:"PUT"});if(!t.ok)throw await Le(t,`Failed to create ${e.streamName}`);let r=await Ho(e);if(Fo(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(At),headers:Be,method:"POST"});if(!n.ok)throw await Le(n,`Failed to install schema for ${e.streamName}`)}function Fo(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,Dt.isDeepStrictEqual)(r,At.schema)&&(0,Dt.isDeepStrictEqual)(e.search,At.search)}async function Ho(e){let t=await fetch(`${e.url}/_schema`,{headers:Be,method:"GET"});if(!t.ok)throw await Le(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}async function Wo(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:Be,method:"POST"});if(!r.ok)throw await Le(r,"Failed to append to prisma-queries")}async function Le(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}m();var $n=require("fs/promises"),V=require("pathe"),te=require("proper-lockfile"),Lt=require("std-env"),g=require("valibot");Y();m();var Go=require("timers/promises"),On=require("std-env");function Nn(e,t){if(e==null)return!1;try{return On.process.kill?.(e,0)??!0}catch(r){return t&&console.error(`Error checking if process with PID ${e} exists:`,r),!1}}oe();var le=(0,g.pipe)((0,g.string)(),(0,g.url)()),Mn=(0,g.object)({connectionString:le,prismaORMConnectionString:(0,g.optional)(le),terminalCommand:(0,g.optional)((0,g.string)())}),Bn=(0,g.object)({url:le}),Ln=(0,g.object)({serverUrl:le,sqlitePath:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),streamName:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),url:le}),jo=(0,g.object)({queryInsights:(0,g.optional)(Ln),streams:(0,g.optional)(Ln)}),Ot=(0,g.pipe)((0,g.number)(),(0,g.integer)(),(0,g.minValue)(1)),Vo=(0,g.object)({database:Mn,http:Bn,ppg:Bn,shadowDatabase:Mn}),Ko=(0,g.object)({databasePort:Ot,experimental:(0,g.optional)(jo),exports:(0,g.optional)(Vo),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:Ot,shadowDatabasePort:Ot,version:(0,g.literal)("1")}),$t=Symbol("initialize"),Nt="default",zo=new Set(["durable-streams"]),B=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??Nt,this.persistenceMode=t.persistenceMode,this.pid=t.pid??Lt.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 ue(t):new Mt(t);return await r[$t](),r}static async fromServerDump(t){let{debug:r,name:n=Nt}=t??{},s=se(n),o=ue.getServerDumpPath(s),a=await Xt(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)(),Ko),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 ue({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,V.join)(se(Nt),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let o=(await er(s,n)).filter(a=>!zo.has(a));return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(a=>kn(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]!==j&&this[n]!==r)throw new Error(`\`${t}\` is already set to ${this[n]}, cannot change it to ${r}`);this[n]=r}},Mt=class extends B{constructor(t){super({...t,databasePort:t?.databasePort||j,persistenceMode:"stateless",port:t?.port||j,shadowDatabasePort:t?.shadowDatabasePort||j,streamsPort:t?.streamsPort||j})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[$t](){let t;try{t=await B.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 ze({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(){}},ue=class e extends B{#r;#e;#t;#s;#o;#a;#n;constructor(t){super({...t,persistenceMode:"stateful"}),this.#a=!1,this.#e=se(this.name),this.#r=(0,V.join)(this.#e,"db_dump.bak"),this.#t=(0,V.join)(this.#e,".lock"),this.#s=(0,V.join)(this.#e,".pglite"),this.#n=t?.serverDump??null,this.#o=e.getServerDumpPath(this.#e)}static getServerDumpPath(t){return(0,V.join)(t,"server.json")}get databaseDumpPath(){return this.#r}get exports(){return this.#n?.exports}get experimental(){return this.#n?.experimental}get pgliteDataDirPath(){return this.#s}async[$t](){await Zt(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,te.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let t=await B.scan({debug:this.debug,onlyMetadata:!0}),r=await ze({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort,await this.writeServerDump()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ELOCKED"?new ee(this):t}}async close(){if(!this.#a)try{await(0,te.unlock)(this.#e,{lockfilePath:this.#t}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(t){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,t),t}}async writeServerDump(t,r){this.#n={name:this.name,version:"1",pid:Lt.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:t},await(0,$n.writeFile)(this.#o,`${JSON.stringify(this.#n,null,2)}
|
|
121
|
+
`,{encoding:"utf-8"})}};async function kn(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 B.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(!Nn(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,te.check)(l,{lockfilePath:(0,V.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"}}}var Bt=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},ee=class extends Bt{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return B.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};m();var Un=require("crypto"),kt=require("timers/promises"),Ct=require("util"),Qn=require("std-env");Y();var Jo="application/json",de={connection:"close","content-type":Jo},Yo={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},Ut={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 qn(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:o,queryInsightsBridge:a,walBridge:i}=e,c=s==="stateless",u=c?ua(n):n,l=Ne(u),f=!c&&await z(l);Qn.process.env.DS_LOCAL_DATA_ROOT=It(),c&&await J(l);let d=await Zo({debug:r,hadExistingStreamsData:f,name:u,port:o}),p={serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path,streamName:xt,url:Me(d.exports.http.url)};try{await ra(p);let y=await _n({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($e=>{E.enqueue($e)});return{close:async()=>{re(),await E.close(),await y.close(),await d.close(),await(0,kt.setTimeout)(100),c&&await J(l)},experimental:p,experimentalQueryInsights:y.experimental}}catch(y){throw await d.close().catch(()=>{}),await(0,kt.setTimeout)(100),c&&await J(l).catch(()=>{}),y}}var Xo=["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 Zo(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||!ea(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(Ne(n)),await a()}}function ea(e){return ta(e).map(r=>r.toLowerCase()).some(r=>Xo.some(n=>r.includes(n)))}function ta(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 oa(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=Cn(t.record),a=Cn(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=aa(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`)),ia(n))}};async function ra(e){let t=await fetch(e.url,{headers:de,method:"PUT"});if(!t.ok)throw await me(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(Yo),headers:de,method:"POST"});if(!r.ok)throw await me(r,`Failed to configure ${e.streamName}`);let n=await na(e);if(sa(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(Ut),headers:de,method:"POST"});if(!s.ok)throw await me(s,`Failed to install schema for ${e.streamName}`)}async function na(e){let t=await fetch(`${e.url}/_schema`,{headers:de,method:"GET"});if(!t.ok)throw await me(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function sa(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,Ct.isDeepStrictEqual)(r,Ut.schema)&&(0,Ct.isDeepStrictEqual)(e.search,Ut.search)}async function oa(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:de,method:"POST"});if(!r.ok)throw await me(r,"Failed to append to prisma-wal")}async function me(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function aa(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=ca(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function ia(e){return JSON.stringify(qt(e))}function qt(e){return Array.isArray(e)?e.map(t=>qt(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,qt(r)])):e}function Cn(e){return e?structuredClone(e):null}function ca(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 ua(e){return`${e}.${(0,Un.randomUUID)().replaceAll("-","")}`}async function Fn(e){let t=await B.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=pa(),i=ga(),o=fa()):(a=await r.attachWalEventBridge(),i=await r.attachQueryInsightsBridge(),o=await qn({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,queryInsightsBridge:i,walBridge:a})),n=await Dn(r,t);let c=la(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{queryInsights:o.experimentalQueryInsights,streams:o.experimental});let u=ma(a),l=An(o.experimentalQueryInsights),f=r,d=s,p=n,y=o,E=async()=>{u.close(),await Hn(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 da(t,[n,o,r,s],a)}}function la(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:Wt({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 Hn(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 da(e,t,r){try{await Hn(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function ma(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=ha(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 pa(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function ga(){return{async close(){},subscribe(){return()=>{}}}}function fa(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function ha(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)))}}}}oe();m();async function Wn(e){let{server:t}=await Fn(e);return t}var L;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,L?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,L?.close().finally(()=>process.exit())});async function ya(){let[,,e]=process.argv;if(!e)return process.send?.({type:"error",code:"unknown",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{L=await Wn({debug:!0,persistenceMode:"stateful",name:e});let t=L.experimental.queryInsights,r={database:L.database,experimental:{queryInsights:{serverUrl:t.serverUrl,sqlitePath:t.sqlitePath,streamName:t.streamName,url:t.url},streams:L.experimental.streams},http:L.http,name:L.name,ppg:L.ppg,shadowDatabase:L.shadowDatabase};process.send?.({type:"started",server:r},void 0)}catch(t){console.error(t);let r=t instanceof Error?t.message:String(t),n=t instanceof ee?"server_already_running":"unknown";process.send?.({type:"error",code:n,error:r},void 0),await(0,Gn.setTimeout)(1e3),process.exit(1)}}ya();
|
package/dist/daemon.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o}from"./chunk-
|
|
1
|
+
import{a as o}from"./chunk-T75J7DN5.js";import"./chunk-VSS2IOVU.js";import"./chunk-662IKR3V.js";import"./chunk-QDQPFKGQ.js";import"./chunk-KWCQYPJI.js";import{l as a}from"./chunk-HFONW2ZS.js";import"./chunk-ANHBRJRZ.js";import"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";import"./chunk-DOJAPHLY.js";import{setTimeout as i}from"timers/promises";var r;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,r?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,r?.close().finally(()=>process.exit())});async function m(){let[,,t]=process.argv;if(!t)return process.send?.({type:"error",code:"unknown",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{r=await o({debug:!0,persistenceMode:"stateful",name:t});let e=r.experimental.queryInsights,s={database:r.database,experimental:{queryInsights:{serverUrl:e.serverUrl,sqlitePath:e.sqlitePath,streamName:e.streamName,url:e.url},streams:r.experimental.streams},http:r.http,name:r.name,ppg:r.ppg,shadowDatabase:r.shadowDatabase};process.send?.({type:"started",server:s},void 0)}catch(e){console.error(e);let s=e instanceof Error?e.message:String(e),n=e instanceof a?"server_already_running":"unknown";process.send?.({type:"error",code:n,error:s},void 0),await i(1e3),process.exit(1)}}m();
|