@prisma/dev 0.24.13 → 0.24.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,24 +1,46 @@
1
- "use strict";var Bn=Object.create;var ue=Object.defineProperty;var Mn=Object.getOwnPropertyDescriptor;var Ln=Object.getOwnPropertyNames;var $n=Object.getPrototypeOf,kn=Object.prototype.hasOwnProperty;var T=(e,t)=>()=>(e&&(t=e(e=0)),t);var Y=(e,t)=>{for(var r in t)ue(e,r,{get:t[r],enumerable:!0})},Bt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ln(t))!kn.call(e,s)&&s!==r&&ue(e,s,{get:()=>t[s],enumerable:!(n=Mn(t,s))||n.enumerable});return e};var v=(e,t,r)=>(r=e!=null?Bn($n(e)):{},Bt(t||!e||!e.__esModule?ue(r,"default",{value:e,enumerable:!0}):r,e)),Cn=e=>Bt(ue({},"__esModule",{value:!0}),e);var Un,y,p=T(()=>{"use strict";Un=()=>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,y=Un()});function Lt(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function qn(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,P.safeParse)(Qn,t,{abortEarly:!0});return s?[null,n]:[r]}var P,Mt,Qn,U,Be=T(()=>{"use strict";p();P=require("valibot"),Mt=/^(postgres|postgresql):\/\//,Qn=(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)(Mt)),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)(Mt))}));U=async(e,t)=>{let{authorization:r}=e,{HTTPException:n}=await import("hono/http-exception");if(!r)throw new n(401,{message:"Missing API Key"});let[s,o="",a]=r.split(" ");if(s!=="Bearer"||a)throw new n(401,{message:"Invalid API Key"});let[i,c]=qn(o);if(i)throw new n(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:u,name:l,shadowDatabaseUrl:h}=c,d=t.get("name"),m=new URL(t.req.url).port;if(!l)throw new n(401,{message:`Wrong API Key; The Prisma Dev server running at port ${m} requires an API Key from a newer version of \`prisma dev\`. Check the "${d}" server's output for the updated \`DATABASE_URL\` value.`});if(l!==d)throw new n(401,{message:`Wrong API Key; The Prisma Dev server running at port ${m} is named "${d}", but the API Key is for "${l}"`});let{hostname:f,port:E}=new URL(u),{port:J}=t.get("db"),{hostname:Ne,port:On}=new URL(h),Nn=t.get("shadowDBPort");if(f!=="localhost"||Number(E)!==J||Ne!=="localhost"||Number(On)!==Nn)throw new n(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:c}}});function $e(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),le.default.platform==="darwin"?Fn(e):le.default.platform==="win32"?Wn(e):Hn(e)}var w,Me,le,M,Le,W,Fn,Wn,Hn,$t=T(()=>{"use strict";p();w=v(require("path"),1),Me=v(require("os"),1),le=v(require("process"),1),M=Me.default.homedir(),Le=Me.default.tmpdir(),{env:W}=le.default,Fn=e=>{let t=w.default.join(M,"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(Le,e)}},Wn=e=>{let t=W.APPDATA||w.default.join(M,"AppData","Roaming"),r=W.LOCALAPPDATA||w.default.join(M,"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(Le,e)}},Hn=e=>{let t=w.default.basename(M);return{data:w.default.join(W.XDG_DATA_HOME||w.default.join(M,".local","share"),e),config:w.default.join(W.XDG_CONFIG_HOME||w.default.join(M,".config"),e),cache:w.default.join(W.XDG_CACHE_HOME||w.default.join(M,".cache"),e),log:w.default.join(W.XDG_STATE_HOME||w.default.join(M,".local","state"),e),temp:w.default.join(Le,t,e)}}});function Qt(e,t){return`${me.cache}/engine/${e}/${t}`}function X(e){return`${me.data}/${e}`}async function H(e){try{return await(0,R.access)(e,R.constants.F_OK),!0}catch(t){if(ke(t))return!1;throw t}}async function qt(e,t){let r=await Gn(e);await(0,R.writeFile)(t,r),await(0,R.chmod)(t,"755")}async function Ft(e,t){await e.stream().pipeTo(de.WriteStream.toWeb((0,de.createWriteStream)(t,{encoding:"utf8"})))}function ke(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function Wt(e){try{return await(0,R.readFile)(e,{encoding:"utf-8"})}catch(t){if(ke(t))return null;throw t}}async function Ht(e){await(0,R.mkdir)(e,{recursive:!0})}async function Gt(e,t){try{return(await(0,R.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,Ut.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(ke(r))return[];throw r}}async function G(e){await(0,R.rm)(e,{force:!0,recursive:!0})}var de,R,kt,Ct,Ut,me,Gn,j=T(()=>{"use strict";p();de=require("fs"),R=require("fs/promises"),kt=require("util"),Ct=require("zlib");$t();Ut=v(require("zeptomatch"),1),me=$e("prisma-dev"),Gn=(0,kt.promisify)(Ct.unzip)});function Re(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 rt=T(()=>{"use strict";p()});var st={};Y(st,{Engine:()=>nt,handleEngineError:()=>Ks});function Ks(e,t){return console.error(e),e instanceof te?t.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500):e instanceof V?t.text(e.responseBody,e.statusCode):t.body(null,500)}var Mr,Lr,$r,kr,Cr,Ur,Gs,js,Br,nt,te,V,ot=T(()=>{"use strict";p();Mr=require("child_process"),Lr=require("events"),$r=require("fs/promises"),kr=require("path"),Cr=require("timers/promises");rt();Ur=require("std-env");j();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Gs,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:js,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Br}=Ur.process.env),nt=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 V.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 V.fromResponse(o);return await o.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:r,resolve:n}=Re();this.#t=t;let s=js||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,Mr.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 h=l.split(`
2
- `).find(E=>E.includes("Started query engine http server"));if(!h)return;a.stdout.removeListener("data",i);let{fields:d}=JSON.parse(h);if(d==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${l}`));let{ip:m,port:f}=d;if(m==null||f==null)return r(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
3
- Received data: ${l}`));n({childProcess:a,url:`http://${m}:${f}`})},c=l=>{this.#t=null,r(new te(String(l))),a.removeListener("exit",u),a.kill()};a.once("error",c);let u=(l,h)=>{this.#t=null,r(new te(`Query Engine exited with code ${l} and signal ${h}`))};return a.once("exit",u),a.stdout.on("data",i),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await(0,Lr.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=Qt(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,$r.mkdir)(r,{recursive:!0});let{binaryTarget:n}=this.#e.platform,s=n==="windows"?".exe":"",o=(0,kr.join)(r,`query-engine-${n}${s}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(Gs==="1"||await H(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}`);Br&&await(0,Cr.setTimeout)(Number(Br)),await qt(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 V.fromResponse(a);try{return await a.json()}catch{return{}}}};te=class extends Error{name="EngineStartError"},V=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)}}});async function Qr(e){let{output:t,success:r}=(0,x.safeParse)(Vs,await e.req.json(),{abortEarly:!0});return r?t:e.text("Invalid input",400)}var x,Vs,qr=T(()=>{"use strict";p();x=require("valibot"),Vs=(0,x.object)({tags:(0,x.union)([(0,x.pipe)((0,x.array)((0,x.string)()),(0,x.minLength)(1)),(0,x.literal)("all")])})});async function ct(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 Wr(e){let t=e.req.param("schemaHash"),r=xe.get(t);return r==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:t,schemas:r}}async function Hr(e,t,r){let n=it.Buffer.from(e,"base64").toString("utf8"),s=Js(n,t.toString());r&&console.log("[Accelerate] schema with override:",s);let o=await ct(s);return{base64Override:it.Buffer.from(s,"utf8").toString("base64"),overrideHash:o}}function Js(e,t){let r=Ys(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=eo(n,t,no(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function Ys(e){let t="datasource";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){r=ut(e,r+2);continue}if(n==="/"&&e[r+1]==="*"){r=lt(e,r+2);continue}if(n==='"'){r=dt(e,r+1);continue}if(e.startsWith(t,r)&&!Fr(e[r-1])&&!Fr(e[r+t.length])){let s=Xs(e,r+t.length,"{");if(s===-1)return null;let o=Zs(e,s);return o===-1?null:{closeBraceIndex:o,openBraceIndex:s}}}return null}function Xs(e,t,r){for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=ut(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=lt(e,n+2);continue}if(s==='"'){n=dt(e,n+1);continue}if(s===r)return n}return-1}function Zs(e,t){let r=0;for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=ut(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=lt(e,n+2);continue}if(s==='"'){n=dt(e,n+1);continue}if(s==="{"){r+=1;continue}if(s==="}"&&(r-=1,r===0))return n}return-1}function ut(e,t){let r=t;for(;r<e.length&&e[r]!==`
4
- `;)r+=1;return r}function lt(e,t){let r=e.indexOf("*/",t);return r===-1?e.length:r+1}function dt(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 Fr(e){return e!=null&&/[A-Za-z0-9_]/.test(e)}function eo(e,t,r){let n=`"${oo(t)}"`,s=to(e);for(let[h,d]of s.entries()){let{comment:m,code:f}=Gr(d.line),E=f.match(/^(\s*)url(\s*)=(\s*).*/);if(E)return s[h]={line:`${E[1]}url${E[2]}=${E[3]}${n}${m}`,terminator:d.terminator},at(s)}let o=so(e),a=ro(s,r),i=`${a}url = ${n}`;if(!e.includes(`
5
- `)&&!e.includes("\r")){let h=e.trim();return h.length===0?`${o}${i}${o}${r}`:`${o}${a}${h}${o}${i}${o}${r}`}let c=s.at(-1);if(c&&c.terminator===""&&/^\s*$/.test(c.line))return`${at(s.slice(0,-1))}${i}${o}${r}`;let u=at(s),l=u.endsWith(`
6
- `)||u.endsWith("\r")?"":o;return`${u}${l}${i}${o}${r}`}function to(e){let t=[],r=0;for(let n=0;n<e.length;n+=1){if(e[n]==="\r"&&e[n+1]===`
1
+ "use strict";var $o=Object.create;var Je=Object.defineProperty;var Lo=Object.getOwnPropertyDescriptor;var Bo=Object.getOwnPropertyNames;var ko=Object.getPrototypeOf,Uo=Object.prototype.hasOwnProperty;var O=(e,t)=>()=>(e&&(t=e(e=0)),t);var E=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ee=(e,t)=>{for(var r in t)Je(e,r,{get:t[r],enumerable:!0})},on=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Bo(t))!Uo.call(e,s)&&s!==r&&Je(e,s,{get:()=>t[s],enumerable:!(n=Lo(t,s))||n.enumerable});return e};var U=(e,t,r)=>(r=e!=null?$o(ko(e)):{},on(t||!e||!e.__esModule?Je(r,"default",{value:e,enumerable:!0}):r,e)),Ho=e=>on(Je({},"__esModule",{value:!0}),e);var qo,h,f=O(()=>{"use strict";qo=()=>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=qo()});var H,Ye=O(()=>{"use strict";f();H=class extends Error{constructor(r,n,s){super(n,s);this.status=r}name="HTTPError"}});function cn(e){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([[t],[r]])=>t.localeCompare(r)))),"utf8").toString("base64url")}function Qo(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:r,output:n,success:s}=(0,x.safeParse)(jo,t,{abortEarly:!0});return s?[null,n]:[r]}function ge(e,t){let r=e.headers.authorization;if(!r)throw new H(401,"Missing API Key");let[n,s="",i]=r.split(" ");if(n!=="Bearer"||i)throw new H(401,"Invalid API Key");let[o,a]=Qo(s);if(o)throw new H(401,"Invalid API Key",{cause:o.join(", ")});let{databaseUrl:c,name:u,shadowDatabaseUrl:l}=a,m=t.name,d=t.port;if(!u)throw new H(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 "${m}" server's output for the updated \`DATABASE_URL\` value.`);if(u!==m)throw new H(401,`Wrong API Key; The Prisma Dev server running at port ${d} is named "${m}", but the API Key is for "${u}"`);let{hostname:p,port:y}=new URL(c),{port:b}=t.db,{hostname:S,port:D}=new URL(l),A=t.shadowDBPort;if(p!=="localhost"||Number(y)!==b||S!=="localhost"||Number(D)!==A)throw new H(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 a}var x,an,jo,Ht=O(()=>{"use strict";f();x=require("valibot");Ye();an=/^(postgres|postgresql):\/\//,jo=(0,x.pipe)((0,x.string)(),(0,x.parseJson)(),(0,x.object)({databaseUrl:(0,x.pipe)((0,x.string)(),(0,x.url)(),(0,x.regex)(an)),name:(0,x.optional)((0,x.pipe)((0,x.string)(),(0,x.minLength)(1))),shadowDatabaseUrl:(0,x.pipe)((0,x.string)(),(0,x.url)(),(0,x.regex)(an))}))});function Qt(e,{suffix:t="nodejs"}={}){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return t&&(e+=`-${t}`),Xe.default.platform==="darwin"?Fo(e):Xe.default.platform==="win32"?Wo(e):Go(e)}var I,qt,Xe,le,jt,ve,Fo,Wo,Go,ln=O(()=>{"use strict";f();I=U(require("path"),1),qt=U(require("os"),1),Xe=U(require("process"),1),le=qt.default.homedir(),jt=qt.default.tmpdir(),{env:ve}=Xe.default,Fo=e=>{let t=I.default.join(le,"Library");return{data:I.default.join(t,"Application Support",e),config:I.default.join(t,"Preferences",e),cache:I.default.join(t,"Caches",e),log:I.default.join(t,"Logs",e),temp:I.default.join(jt,e)}},Wo=e=>{let t=ve.APPDATA||I.default.join(le,"AppData","Roaming"),r=ve.LOCALAPPDATA||I.default.join(le,"AppData","Local");return{data:I.default.join(r,e,"Data"),config:I.default.join(t,e,"Config"),cache:I.default.join(r,e,"Cache"),log:I.default.join(r,e,"Log"),temp:I.default.join(jt,e)}},Go=e=>{let t=I.default.basename(le);return{data:I.default.join(ve.XDG_DATA_HOME||I.default.join(le,".local","share"),e),config:I.default.join(ve.XDG_CONFIG_HOME||I.default.join(le,".config"),e),cache:I.default.join(ve.XDG_CACHE_HOME||I.default.join(le,".cache"),e),log:I.default.join(ve.XDG_STATE_HOME||I.default.join(le,".local","state"),e),temp:I.default.join(jt,t,e)}}});function mn(e,t){return`${et.cache}/engine/${e}/${t}`}function Le(e){return`${et.data}/${e}`}async function Re(e){try{return await(0,N.access)(e,N.constants.F_OK),!0}catch(t){if(Ft(t))return!1;throw t}}async function pn(e,t){let r=await zo(e);await(0,N.writeFile)(t,r),await(0,N.chmod)(t,"755")}async function hn(e,t){await e.stream().pipeTo(Ze.WriteStream.toWeb((0,Ze.createWriteStream)(t,{encoding:"utf8"})))}function Ft(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ENOENT"}async function gn(e){try{return await(0,N.readFile)(e,{encoding:"utf-8"})}catch(t){if(Ft(t))return null;throw t}}async function yn(e){await(0,N.mkdir)(e,{recursive:!0})}async function Sn(e,t){try{return(await(0,N.readdir)(e,{withFileTypes:!0})).reduce((n,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!t||(0,fn.default)(t,s.name))&&n.push(s.name),n),[])}catch(r){if(Ft(r))return[];throw r}}async function xe(e){await(0,N.rm)(e,{force:!0,recursive:!0})}var Ze,N,un,dn,fn,et,zo,Te=O(()=>{"use strict";f();Ze=require("fs"),N=require("fs/promises"),un=require("util"),dn=require("zlib");ln();fn=U(require("zeptomatch"),1),et=Qt("prisma-dev"),zo=(0,un.promisify)(dn.unzip)});async function Vt(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:i,portsUsedByThisServerLastTime:o}=Jo(r,s);t&&(console.debug(`ports used by other servers: ${Object.keys(i).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(o)}`));let a={databasePort:q,port:q,shadowDatabasePort:q,streamsPort:q},c=["port","databasePort","shadowDatabasePort","streamsPort"];for(let u of c){let l=await Vo({debug:t,portKey:u,portsUsedByOtherServers:i,portsUsedByThisServerLastTime:o,requestedPorts:n})??await Ko({debug:t,pickedPorts:a,portKey:u,portsUsedByOtherServers:i,portsUsedByThisServerLastTime:o});t&&console.debug(`Got port for "${u}": ${l}`),a[u]=l}return t&&console.debug(`Picked ports: ${JSON.stringify(a)}`),a}async function Vo(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:i}=e,{[r]:o,...a}=i;if(Wt(o))return await Zo({debug:t,otherRequestedPorts:a,portKey:r,portsUsedByOtherServers:n,requestedPort:o}),o;let c=s?.[r]??q;if(!Wt(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(a).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,ue.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 Ko(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:i}=e,o=Math.max(rt,nt,st,it)+1,a=Object.values(r).filter(p=>p!==void 0),c=i?Xo(i):[],u=[...a,...Object.keys(s).map(Number),...c],l=Math.min(Math.max(o,...u)+100,tt),m=(0,ot.difference)((0,ot.range)(o,l),u),d={port:nt,databasePort:rt,shadowDatabasePort:st,streamsPort:it}[n];try{return await(0,ue.getPort)({port:d in s||a.includes(d)||c.includes(d)?void 0:d,ports:m})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&l+1<=tt)return t&&console.debug(`Expanding port lookup to range [${l+1}, ${tt}].`),await(0,ue.getPort)({portRange:[l+1,tt]});throw p}}function Wt(e){return Number.isFinite(e)&&e>=0}function Jo(e,t){let r={},n;for(let s of t){let{databasePort:i,port:o,shadowDatabasePort:a}=s,c=Yo(s);if(s.name===e){n={databasePort:i,port:o,shadowDatabasePort:a,streamsPort:c};continue}r[i]=!0,r[o]=!0,r[a]=!0,Wt(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function Yo(e){let t=e.experimental?.streams?.serverUrl;if(!t)return q;try{let r=Number(new URL(t).port);return Number.isInteger(r)&&r>0?r:q}catch{return q}}function Xo(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function Zo(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:i}=e;if(i!==ye){if(i in s)throw t&&console.error(`Port ${i} was requested for "${n}", but is already used by another server.`),new zt(i);if(Object.values(r).includes(i))throw t&&console.error(`Port ${i} was requested for "${n}", but also for another key.`),new Gt(i);if((0,ue.isUnsafePort)(i))throw t&&console.error(`Port ${i} was requested for "${n}", but is unsafe.`),new V(i);if(await(0,ue.checkPort)(i)===!1)throw t&&console.error(`Port ${i} was requested for "${n}", but is not available.`),new V(i)}}var ue,ot,rt,nt,st,it,tt,ye,q,V,Gt,zt,Be=O(()=>{"use strict";f();ue=require("get-port-please"),ot=require("remeda"),rt=51214,nt=51213,st=51215,it=51216,tt=65535,ye=0,q=-1/0;V=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},Gt=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"},zt=class extends Error{constructor(r){super(`Port number \`${r}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=r}name="PortBelongsToAnotherServerError"}});var ls=E((Nu,cs)=>{"use strict";f();var os=12,za=0,lr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,7,7,7,7,7,7,7,7,7,7,7,7,8,7,7,10,9,9,9,11,4,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,24,36,48,60,72,84,96,0,12,12,12,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0,0,24,24,24,0,0,0,0,0,0,0,0,0,24,24,0,0,0,0,0,0,0,0,0,0,48,48,48,0,0,0,0,0,0,0,0,0,0,48,48,0,0,0,0,0,0,0,0,0,48,0,0,0,0,0,0,0,0,0,0,127,63,63,63,0,31,15,15,15,7,7,7];function Va(e){var t=e.indexOf("%");if(t===-1)return e;for(var r=e.length,n="",s=0,i=0,o=t,a=os;t>-1&&t<r;){var c=as(e[t+1],4),u=as(e[t+2],0),l=c|u,m=lr[l];if(a=lr[256+a+m],i=i<<6|l&lr[364+m],a===os)n+=e.slice(s,o),n+=i<=65535?String.fromCharCode(i):String.fromCharCode(55232+(i>>10),56320+(i&1023)),i=0,s=t+3,t=o=e.indexOf("%",s);else{if(a===za)return null;if(t+=3,t<r&&e.charCodeAt(t)===37)continue;return null}}return n+e.slice(s)}var Ka={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};function as(e,t){var r=Ka[e];return r===void 0?255:r<<t}cs.exports=Va});var ps=E(($u,ms)=>{"use strict";f();var us=ls(),ds=/\+/g,fs=function(){};fs.prototype=Object.create(null);function Ja(e){let t=new fs;if(typeof e!="string")return t;let r=e.length,n="",s="",i=-1,o=-1,a=!1,c=!1,u=!1,l=!1,m=!1,d=0;for(let p=0;p<r+1;p++)if(d=p!==r?e.charCodeAt(p):38,d===38){if(m=o>i,m||(o=p),n=e.slice(i+1,o),m||n.length>0){u&&(n=n.replace(ds," ")),a&&(n=us(n)||n),m&&(s=e.slice(o+1,p),l&&(s=s.replace(ds," ")),c&&(s=us(s)||s));let y=t[n];y===void 0?t[n]=s:y.pop?y.push(s):t[n]=[y,s]}s="",i=p,o=p,a=!1,c=!1,u=!1,l=!1}else d===61?o<=i?o=p:c=!0:d===43?o>i?l=!0:u=!0:d===37&&(o>i?c=!0:a=!0);return t}ms.exports=Ja});var gs=E((Bu,hs)=>{"use strict";f();var X=Array.from({length:256},(e,t)=>"%"+((t<16?"0":"")+t.toString(16)).toUpperCase()),Ya=new Int8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,0]);function Xa(e){let t=e.length;if(t===0)return"";let r="",n=0,s=0;e:for(;s<t;s++){let i=e.charCodeAt(s);for(;i<128;){if(Ya[i]!==1&&(n<s&&(r+=e.slice(n,s)),n=s+1,r+=X[i]),++s===t)break e;i=e.charCodeAt(s)}if(n<s&&(r+=e.slice(n,s)),i<2048){n=s+1,r+=X[192|i>>6]+X[128|i&63];continue}if(i<55296||i>=57344){n=s+1,r+=X[224|i>>12]+X[128|i>>6&63]+X[128|i&63];continue}if(++s,s>=t)throw new Error("URI malformed");let o=e.charCodeAt(s)&1023;n=s+1,i=65536+((i&1023)<<10|o),r+=X[240|i>>18]+X[128|i>>12&63]+X[128|i>>6&63]+X[128|i&63]}return n===0?e:n<t?r+e.slice(n):r}hs.exports={encodeString:Xa}});var bs=E((Uu,Ss)=>{"use strict";f();var{encodeString:ur}=gs();function ys(e){let t=typeof e;return t==="string"?ur(e):t==="bigint"?e.toString():t==="boolean"?e?"true":"false":t==="number"&&Number.isFinite(e)?e<1e21?""+e:ur(""+e):""}function Za(e){let t="";if(e===null||typeof e!="object")return t;let r="&",n=Object.keys(e),s=n.length,i=0;for(let o=0;o<s;o++){let a=n[o],c=e[a],u=ur(a)+"=";if(o&&(t+=r),Array.isArray(c)){i=c.length;for(let l=0;l<i;l++)l&&(t+=r),t+=u,t+=ys(c[l])}else t+=u,t+=ys(c)}return t}Ss.exports=Za});var vs=E((qu,He)=>{"use strict";f();var Ps=ps(),ws=bs(),Es={parse:Ps,stringify:ws};He.exports=Es;He.exports.default=Es;He.exports.parse=Ps;He.exports.stringify=ws});var xs=E(Rs=>{"use strict";f();Object.defineProperty(Rs,"__esModule",{value:!0})});var Ts=E(qe=>{"use strict";f();Object.defineProperty(qe,"__esModule",{value:!0});qe.types=void 0;var ec;(function(e){e[e.ROOT=0]="ROOT",e[e.GROUP=1]="GROUP",e[e.POSITION=2]="POSITION",e[e.SET=3]="SET",e[e.RANGE=4]="RANGE",e[e.REPETITION=5]="REPETITION",e[e.REFERENCE=6]="REFERENCE",e[e.CHAR=7]="CHAR"})(ec=qe.types||(qe.types={}))});var Is=E(As=>{"use strict";f();Object.defineProperty(As,"__esModule",{value:!0})});var ie=E(se=>{"use strict";f();var tc=se&&se.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),dr=se&&se.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&tc(t,e,r)};Object.defineProperty(se,"__esModule",{value:!0});dr(xs(),se);dr(Ts(),se);dr(Is(),se)});var ft=E(M=>{"use strict";f();Object.defineProperty(M,"__esModule",{value:!0});M.anyChar=M.notWhitespace=M.whitespace=M.notInts=M.ints=M.notWords=M.words=void 0;var w=ie(),_s=()=>[{type:w.types.RANGE,from:48,to:57}],Os=()=>[{type:w.types.CHAR,value:95},{type:w.types.RANGE,from:97,to:122},{type:w.types.RANGE,from:65,to:90},{type:w.types.RANGE,from:48,to:57}],Ds=()=>[{type:w.types.CHAR,value:9},{type:w.types.CHAR,value:10},{type:w.types.CHAR,value:11},{type:w.types.CHAR,value:12},{type:w.types.CHAR,value:13},{type:w.types.CHAR,value:32},{type:w.types.CHAR,value:160},{type:w.types.CHAR,value:5760},{type:w.types.RANGE,from:8192,to:8202},{type:w.types.CHAR,value:8232},{type:w.types.CHAR,value:8233},{type:w.types.CHAR,value:8239},{type:w.types.CHAR,value:8287},{type:w.types.CHAR,value:12288},{type:w.types.CHAR,value:65279}],rc=()=>[{type:w.types.CHAR,value:10},{type:w.types.CHAR,value:13},{type:w.types.CHAR,value:8232},{type:w.types.CHAR,value:8233}];M.words=()=>({type:w.types.SET,set:Os(),not:!1});M.notWords=()=>({type:w.types.SET,set:Os(),not:!0});M.ints=()=>({type:w.types.SET,set:_s(),not:!1});M.notInts=()=>({type:w.types.SET,set:_s(),not:!0});M.whitespace=()=>({type:w.types.SET,set:Ds(),not:!1});M.notWhitespace=()=>({type:w.types.SET,set:Ds(),not:!0});M.anyChar=()=>({type:w.types.SET,set:rc(),not:!0})});var Ns=E(F=>{"use strict";f();var nc=F&&F.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),sc=F&&F.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),ic=F&&F.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&nc(t,e,r);return sc(t,e),t};Object.defineProperty(F,"__esModule",{value:!0});F.tokenizeClass=F.strToChars=void 0;var Cs=ie(),Ie=ic(ft()),oc="@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?";F.strToChars=e=>{let t=/(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g;return e.replace(t,(r,n,s,i,o,a,c)=>{if(s)return r;let u=n?8:i?parseInt(i,16):o?parseInt(o,16):a?oc.indexOf(a):{0:0,t:9,n:10,v:11,f:12,r:13}[c],l=String.fromCharCode(u);return/[[\]{}^$.|?*+()]/.test(l)?`\\${l}`:l})};F.tokenizeClass=(e,t)=>{var r,n,s,i,o,a,c;let u=[],l,m,d=/\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(((?:\\)])|(((?:\\)?([^\]])))))|(\])|(?:\\)?([^])/g;for(;(l=d.exec(e))!==null;){let p=(c=(a=(o=(i=(s=(n=(r=l[1]&&Ie.words())!==null&&r!==void 0?r:l[2]&&Ie.ints())!==null&&n!==void 0?n:l[3]&&Ie.whitespace())!==null&&s!==void 0?s:l[4]&&Ie.notWords())!==null&&i!==void 0?i:l[5]&&Ie.notInts())!==null&&o!==void 0?o:l[6]&&Ie.notWhitespace())!==null&&a!==void 0?a:l[7]&&{type:Cs.types.RANGE,from:(l[8]||l[9]).charCodeAt(0),to:(m=l[10]).charCodeAt(m.length-1)})!==null&&c!==void 0?c:(m=l[16])&&{type:Cs.types.CHAR,value:m.charCodeAt(0)};if(p)u.push(p);else return[u,d.lastIndex]}throw new SyntaxError(`Invalid regular expression: /${t}/: Unterminated character class`)}});var fr=E(Z=>{"use strict";f();var ac=Z&&Z.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),cc=Z&&Z.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Ls=Z&&Z.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&ac(t,e,r);return cc(t,e),t};Object.defineProperty(Z,"__esModule",{value:!0});Z.tokenizer=void 0;var Ms=Ls(Ns()),C=ie(),Se=Ls(ft()),lc=/^[a-zA-Z_$]$/i,uc=/^[a-zA-Z0-9_$]$/i,$s=/\d/;Z.tokenizer=e=>{let t=0,r,n={type:C.types.ROOT,stack:[]},s=n,i=n.stack,o=[],a=[],c=0,u=m=>{throw new SyntaxError(`Invalid regular expression: /${e}/: Nothing to repeat at column ${m-1}`)},l=Ms.strToChars(e);for(;t<l.length;)switch(r=l[t++]){case"\\":if(t===l.length)throw new SyntaxError(`Invalid regular expression: /${e}/: \\ at end of pattern`);switch(r=l[t++]){case"b":i.push({type:C.types.POSITION,value:"b"});break;case"B":i.push({type:C.types.POSITION,value:"B"});break;case"w":i.push(Se.words());break;case"W":i.push(Se.notWords());break;case"d":i.push(Se.ints());break;case"D":i.push(Se.notInts());break;case"s":i.push(Se.whitespace());break;case"S":i.push(Se.notWhitespace());break;default:if($s.test(r)){let m=r;for(;t<l.length&&$s.test(l[t]);)m+=l[t++];let d=parseInt(m,10),p={type:C.types.REFERENCE,value:d};i.push(p),a.push({reference:p,stack:i,index:i.length-1})}else i.push({type:C.types.CHAR,value:r.charCodeAt(0)})}break;case"^":i.push({type:C.types.POSITION,value:"^"});break;case"$":i.push({type:C.types.POSITION,value:"$"});break;case"[":{let m;l[t]==="^"?(m=!0,t++):m=!1;let d=Ms.tokenizeClass(l.slice(t),e);t+=d[1],i.push({type:C.types.SET,set:d[0],not:m});break}case".":i.push(Se.anyChar());break;case"(":{let m={type:C.types.GROUP,stack:[],remember:!0};if(l[t]==="?")if(r=l[t+1],t+=2,r==="=")m.followedBy=!0,m.remember=!1;else if(r==="!")m.notFollowedBy=!0,m.remember=!1;else if(r==="<"){let d="";if(lc.test(l[t]))d+=l[t],t++;else throw new SyntaxError(`Invalid regular expression: /${e}/: Invalid capture group name, character '${l[t]}' after '<' at column ${t+1}`);for(;t<l.length&&uc.test(l[t]);)d+=l[t],t++;if(!d)throw new SyntaxError(`Invalid regular expression: /${e}/: Invalid capture group name, character '${l[t]}' after '<' at column ${t+1}`);if(l[t]!==">")throw new SyntaxError(`Invalid regular expression: /${e}/: Unclosed capture group name, expected '>', found '${l[t]}' at column ${t+1}`);m.name=d,t++}else if(r===":")m.remember=!1;else throw new SyntaxError(`Invalid regular expression: /${e}/: Invalid group, character '${r}' after '?' at column ${t-1}`);else c+=1;i.push(m),o.push(s),s=m,i=m.stack;break}case")":if(o.length===0)throw new SyntaxError(`Invalid regular expression: /${e}/: Unmatched ) at column ${t-1}`);s=o.pop(),i=s.options?s.options[s.options.length-1]:s.stack;break;case"|":{s.options||(s.options=[s.stack],delete s.stack);let m=[];s.options.push(m),i=m;break}case"{":{let m=/^(\d+)(,(\d+)?)?\}/.exec(l.slice(t)),d,p;m!==null?(i.length===0&&u(t),d=parseInt(m[1],10),p=m[2]?m[3]?parseInt(m[3],10):1/0:d,t+=m[0].length,i.push({type:C.types.REPETITION,min:d,max:p,value:i.pop()})):i.push({type:C.types.CHAR,value:123});break}case"?":i.length===0&&u(t),i.push({type:C.types.REPETITION,min:0,max:1,value:i.pop()});break;case"+":i.length===0&&u(t),i.push({type:C.types.REPETITION,min:1,max:1/0,value:i.pop()});break;case"*":i.length===0&&u(t),i.push({type:C.types.REPETITION,min:0,max:1/0,value:i.pop()});break;default:i.push({type:C.types.CHAR,value:r.charCodeAt(0)})}if(o.length!==0)throw new SyntaxError(`Invalid regular expression: /${e}/: Unterminated group`);return dc(a,c),n};function dc(e,t){for(let r of e.reverse())if(t<r.reference.value){r.reference.type=C.types.CHAR;let n=r.reference.value.toString();if(r.reference.value=parseInt(n,8),!/^[0-7]+$/.test(n)){let s=0;for(;n[s]!=="8"&&n[s]!=="9";)s+=1;if(s===0?(r.reference.value=n.charCodeAt(0),s+=1):r.reference.value=parseInt(n.slice(0,s),8),n.length>s){let i=r.stack.splice(r.index+1);for(let o of n.slice(s))r.stack.push({type:C.types.CHAR,value:o.charCodeAt(0)});r.stack.push(...i)}}}}});var ks=E($=>{"use strict";f();var fc=$&&$.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),mc=$&&$.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),pc=$&&$.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&fc(t,e,r);return mc(t,e),t};Object.defineProperty($,"__esModule",{value:!0});$.NOTANYCHAR=$.WHITESPACE=$.WORDS=$.INTS=void 0;var mt=pc(ft()),Bs=ie();function pt(e){let t={},r=0;for(let n of e)n.type===Bs.types.CHAR&&(t[n.value]=!0),n.type===Bs.types.RANGE&&(t[`${n.from}-${n.to}`]=!0),r+=1;return{lookup:()=>Object.assign({},t),len:r}}$.INTS=pt(mt.ints().set);$.WORDS=pt(mt.words().set);$.WHITESPACE=pt(mt.whitespace().set);$.NOTANYCHAR=pt(mt.anyChar().set)});var Hs=E(W=>{"use strict";f();var hc=W&&W.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),gc=W&&W.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),yc=W&&W.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&hc(t,e,r);return gc(t,e),t};Object.defineProperty(W,"__esModule",{value:!0});W.writeSetTokens=W.setChar=void 0;var St=ie(),ht=yc(ks());function yt(e){return e===94?"\\^":e===92?"\\\\":e===93?"\\]":e===45?"\\-":String.fromCharCode(e)}W.setChar=yt;function gt(e,{lookup:t,len:r}){if(r!==e.length)return!1;let n=t();for(let s of e){if(s.type===St.types.SET)return!1;let i=s.type===St.types.CHAR?s.value:`${s.from}-${s.to}`;if(n[i])n[i]=!1;else return!1}return!0}function Us(e,t=!1){if(gt(e.set,ht.INTS))return e.not?"\\D":"\\d";if(gt(e.set,ht.WORDS))return e.not?"\\W":"\\w";if(e.not&&gt(e.set,ht.NOTANYCHAR))return".";if(gt(e.set,ht.WHITESPACE))return e.not?"\\S":"\\s";let r="";for(let s=0;s<e.set.length;s++){let i=e.set[s];r+=Sc(i)}let n=`${e.not?"^":""}${r}`;return t?n:`[${n}]`}W.writeSetTokens=Us;function Sc(e){return e.type===St.types.CHAR?yt(e.value):e.type===St.types.RANGE?`${yt(e.from)}-${yt(e.to)}`:Us(e,!0)}});var pr=E(_e=>{"use strict";f();Object.defineProperty(_e,"__esModule",{value:!0});_e.reconstruct=void 0;var me=ie(),mr=Hs(),qs=e=>e.map(_e.reconstruct).join(""),js=e=>{if("options"in e)return e.options.map(qs).join("|");if("stack"in e)return qs(e.stack);throw new Error("options or stack must be Root or Group token")};_e.reconstruct=e=>{switch(e.type){case me.types.ROOT:return js(e);case me.types.CHAR:{let t=String.fromCharCode(e.value);return(/[[\\{}$^.|?*+()]/.test(t)?"\\":"")+t}case me.types.POSITION:return e.value==="^"||e.value==="$"?e.value:`\\${e.value}`;case me.types.REFERENCE:return`\\${e.value}`;case me.types.SET:return mr.writeSetTokens(e);case me.types.GROUP:return`(${e.name?`?<${e.name}>`:e.remember?"":e.followedBy?"?=":e.notFollowedBy?"?!":"?:"}${js(e)})`;case me.types.REPETITION:{let{min:t,max:r}=e,n;return t===0&&r===1?n="?":t===1&&r===1/0?n="+":t===0&&r===1/0?n="*":r===1/0?n=`{${t},}`:t===r?n=`{${t}}`:n=`{${t},${r}}`,`${_e.reconstruct(e.value)}${n}`}case me.types.RANGE:return`${mr.setChar(e.from)}-${mr.setChar(e.to)}`;default:throw new Error(`Invalid token type ${e}`)}}});var gr=E((G,bt)=>{"use strict";f();var bc=G&&G.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),hr=G&&G.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&bc(t,e,r)};Object.defineProperty(G,"__esModule",{value:!0});G.types=void 0;var Qs=ie();Object.defineProperty(G,"types",{enumerable:!0,get:function(){return Qs.types}});hr(fr(),G);hr(pr(),G);var Fs=fr(),Pc=pr();hr(ie(),G);G.default=Fs.tokenizer;bt.exports=Fs.tokenizer;bt.exports.types=Qs.types;bt.exports.reconstruct=Pc.reconstruct});var Ws=E((ud,Pt)=>{"use strict";f();var wc=gr(),{types:Ec}=gr();function yr(e,t,r){let n,s,i;if(e.type===Ec.REPETITION&&(r++,t.reps++,r>1||t.reps>t.limit))return!1;let o=e.options||e.value?.options;if(o){for(n=0,i=o.length;n<i;n++)if(s=yr({stack:o[n]},t,r),!s)return!1}let a=e.stack||e.value?.stack;if(!a)return!0;for(n=0,i=a.length;n<i;n++)if(s=yr(a[n],t,r),!s)return!1;return!0}function Sr(e,t){let r={reps:0,limit:t?.limit??25};vc(e)?e=e.source:typeof e!="string"&&(e=String(e));try{return yr(wc(e),r,0)}catch{return!1}}function vc(e){return Object.prototype.toString.call(e)==="[object RegExp]"}Pt.exports=Sr;Pt.exports.default=Sr;Pt.exports.safeRegex=Sr});var br=E((fd,Gs)=>{"use strict";f();Gs.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,s,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!e(t[s],r[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[s]))return!1;for(s=n;s--!==0;){var o=i[s];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var wt=E((pd,zs)=>{"use strict";f();zs.exports={name:"__fmw_internal_strategy_merged_tree_http_method__",storage:function(){let e=new Map;return{get:t=>e.get(t)||null,set:(t,r)=>{e.set(t,r)}}},deriveConstraint:e=>e.method,mustMatchWhenDerived:!0}});var ei=E((gd,Zs)=>{"use strict";f();var Vs=br(),Ks=wt(),Js=Symbol("treeData");function Ys(e,t=""){let r="",n=Object.keys(e);for(let s=0;s<n.length;s++){let i=n[s],o=e[i],a=s===n.length-1,c=a?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=a?" ":"\u2502 ",m=(o[Js]||"").replaceAll(`
2
+ `,`
3
+ `+t+u);r+=t+c+i+m+`
4
+ `,r+=Ys(o,t+u)}return r}function Rc(e){let t=e.name||"";return t=t.replace("bound","").trim(),t=(t||"anonymous")+"()",t}function Xs(e){return Array.isArray(e)?e.map(t=>Xs(t)):typeof e=="symbol"?e.toString():typeof e=="function"?Rc(e):e}function xc(e,t){if(!t.includeMeta)return{};let r=t.buildPrettyMeta(e),n={},s=t.includeMeta;Array.isArray(s)||(s=Reflect.ownKeys(r));for(let i of s){if(!Object.prototype.hasOwnProperty.call(r,i))continue;let o=i.toString(),a=r[i];if(a!=null){let c=JSON.stringify(Xs(a));n[o]=c}}return n}function Tc(e){let t="";for(let[r,n]of Object.entries(e))t+=`
5
+ \u2022 (${r}) ${n}`;return t}function Ac(e){let t={...e.opts.constraints},r=t[Ks.name];return delete t[Ks.name],{...e,method:r,opts:{constraints:t}}}function Ic(e){let t=` (${e.method})`,r=e.opts.constraints||{};return Object.keys(r).length!==0&&(t+=" "+JSON.stringify(r)),t+=Tc(e.metaData),t}function _c(e){return e.reduce((t,r)=>{for(let n of t)if(Vs(r.opts.constraints,n.opts.constraints)&&Vs(r.metaData,n.metaData))return n.method+=", "+r.method,t;return t.push(r),t},[])}function Oc(e,t,r){let n=e.routes;return r.method===void 0&&(n=n.map(Ac)),n=n.map(s=>(s.metaData=xc(s,r),s)),r.method===void 0&&(n=_c(n)),n.map(Ic).join(`
6
+ ${t}`)}function Et(e,t,r,n){if((e.isLeafNode||n.commonPrefix!==!1)&&(r=r||"(empty root node)",t=t[r]={},e.isLeafNode&&(t[Js]=Oc(e,r,n)),r=""),e.staticChildren)for(let s of Object.values(e.staticChildren))Et(s,t,r+s.prefix,n);if(e.parametricChildren)for(let s of Object.values(e.parametricChildren)){let i=Array.from(s.nodePaths).join("|");Et(s,t,r+i,n)}e.wildcardChild&&Et(e.wildcardChild,t,"*",n)}function Dc(e,t){let r={};return Et(e,r,e.prefix,t),Ys(r)}Zs.exports={prettyPrintTree:Dc}});var ni=E((Sd,ri)=>{"use strict";f();var ti=function(){};ti.prototype=Object.create(null);ri.exports={NullObject:ti}});var ii=E((Pd,si)=>{"use strict";f();var{NullObject:Cc}=ni(),Nc=wt(),Pr=class{constructor(){this.unconstrainedHandler=null,this.constraints=[],this.handlers=[],this.constrainedHandlerStores=null}getMatchingHandler(t){return t===void 0?this.unconstrainedHandler:this._getHandlerMatchingConstraints(t)}addHandler(t,r){let n=r.params,s=r.opts.constraints||{},i={params:n,constraints:s,handler:r.handler,store:r.store||null,_createParamsObject:this._compileCreateParamsObject(n)},o=Object.keys(s);o.length===0&&(this.unconstrainedHandler=i);for(let c of o)this.constraints.includes(c)||(c==="version"?this.constraints.unshift(c):this.constraints.push(c));let a=o.includes(Nc.name);if(!a&&this.handlers.length>=31)throw new Error("find-my-way supports a maximum of 31 route handlers per node when there are constraints, limit reached");this.handlers.push(i),this.handlers.sort((c,u)=>Object.keys(c.constraints).length-Object.keys(u.constraints).length),a||this._compileGetHandlerMatchingConstraints(t,s)}_compileCreateParamsObject(t){let r=[];r.push("const fn = function _createParamsObject (paramsArray) {"),r.push("const params = new NullObject()");for(let n=0;n<t.length;n++)r.push(`params['${t[n]}'] = paramsArray[${n}]`);return r.push("return params"),r.push("}"),r.push("return fn"),new Function("NullObject",r.join(`
7
+ `))(Cc)}_getHandlerMatchingConstraints(){return null}_buildConstraintStore(t,r){for(let n=0;n<this.handlers.length;n++){let i=this.handlers[n].constraints[r];if(i!==void 0){let o=t.get(i)||0;o|=1<<n,t.set(i,o)}}}_constrainedIndexBitmask(t){let r=0;for(let n=0;n<this.handlers.length;n++)this.handlers[n].constraints[t]!==void 0&&(r|=1<<n);return~r}_compileGetHandlerMatchingConstraints(t){this.constrainedHandlerStores={};for(let n of this.constraints){let s=t.newStoreForConstraint(n);this.constrainedHandlerStores[n]=s,this._buildConstraintStore(s,n)}let r=[];r.push(`
8
+ let candidates = ${(1<<this.handlers.length)-1}
9
+ let mask, matches
10
+ `);for(let n of this.constraints){r.push(`
11
+ mask = ${this._constrainedIndexBitmask(n)}
12
+ value = derivedConstraints.${n}
13
+ `);let i=t.strategies[n].mustMatchWhenDerived?"matches":"(matches | mask)";r.push(`
14
+ if (value === undefined) {
15
+ candidates &= mask
16
+ } else {
17
+ matches = this.constrainedHandlerStores.${n}.get(value) || 0
18
+ candidates &= ${i}
19
+ }
20
+ if (candidates === 0) return null;
21
+ `)}for(let n in t.strategies){if(!Object.hasOwn(t.strategies,n))continue;t.strategies[n].mustMatchWhenDerived&&!this.constraints.includes(n)&&r.push(`if (derivedConstraints.${n} !== undefined) return null`)}r.push("return this.handlers[31 - Math.clz32(candidates)]"),this._getHandlerMatchingConstraints=new Function("derivedConstraints",r.join(`
22
+ `))}};si.exports=Pr});var ai=E((Ed,oi)=>{"use strict";f();var Mc=ii(),It={STATIC:0,PARAMETRIC:1,WILDCARD:2},vt=class{constructor(){this.isLeafNode=!1,this.routes=null,this.handlerStorage=null}addRoute(t,r){this.routes===null&&(this.routes=[]),this.handlerStorage===null&&(this.handlerStorage=new Mc),this.isLeafNode=!0,this.routes.push(t),this.handlerStorage.addHandler(r,t)}},Rt=class extends vt{constructor(){super(),this.staticChildren={}}findStaticMatchingChild(t,r){let n=this.staticChildren[t.charAt(r)];return n===void 0||!n.matchPrefix(t,r)?null:n}getStaticChild(t,r=0){if(t.length===r)return this;let n=this.findStaticMatchingChild(t,r);return n?n.getStaticChild(t,r+n.prefix.length):null}createStaticChild(t){if(t.length===0)return this;let r=this.staticChildren[t.charAt(0)];if(r){let s=1;for(;s<r.prefix.length;s++)if(t.charCodeAt(s)!==r.prefix.charCodeAt(s)){r=r.split(this,s);break}return r.createStaticChild(t.slice(s))}let n=t.charAt(0);return this.staticChildren[n]=new xt(t),this.staticChildren[n]}},xt=class e extends Rt{constructor(t){super(),this.prefix=t,this.wildcardChild=null,this.parametricChildren=[],this.kind=It.STATIC,this._compilePrefixMatch()}getParametricChild(t){let r=t&&t.source,n=this.parametricChildren.find(s=>(s.regex&&s.regex.source)===r);return n||null}createParametricChild(t,r,n){let s=this.getParametricChild(t);return s?(s.nodePaths.add(n),s):(s=new Tt(t,r,n),this.parametricChildren.push(s),this.parametricChildren.sort((i,o)=>i.isRegex?o.isRegex?i.staticSuffix===null?1:o.staticSuffix===null?-1:o.staticSuffix.endsWith(i.staticSuffix)?1:i.staticSuffix.endsWith(o.staticSuffix)?-1:0:-1:1),s)}getWildcardChild(){return this.wildcardChild}createWildcardChild(){return this.wildcardChild=this.getWildcardChild()||new At,this.wildcardChild}split(t,r){let n=this.prefix.slice(0,r),s=this.prefix.slice(r);this.prefix=s,this._compilePrefixMatch();let i=new e(n);return i.staticChildren[s.charAt(0)]=this,t.staticChildren[n.charAt(0)]=i,i}getNextNode(t,r,n,s){let i=this.findStaticMatchingChild(t,r),o=0;if(i===null){if(this.parametricChildren.length===0)return this.wildcardChild;i=this.parametricChildren[0],o=1}this.wildcardChild!==null&&n.push({paramsCount:s,brotherPathIndex:r,brotherNode:this.wildcardChild});for(let a=this.parametricChildren.length-1;a>=o;a--)n.push({paramsCount:s,brotherPathIndex:r,brotherNode:this.parametricChildren[a]});return i}_compilePrefixMatch(){if(this.prefix.length===1){this.matchPrefix=()=>!0;return}let t=[];for(let r=1;r<this.prefix.length;r++){let n=this.prefix.charCodeAt(r);t.push(`path.charCodeAt(i + ${r}) === ${n}`)}this.matchPrefix=new Function("path","i",`return ${t.join(" && ")}`)}},Tt=class extends Rt{constructor(t,r,n){super(),this.isRegex=!!t,this.regex=t||null,this.staticSuffix=r||null,this.kind=It.PARAMETRIC,this.nodePaths=new Set([n])}getNextNode(t,r){return this.findStaticMatchingChild(t,r)}},At=class extends vt{constructor(){super(),this.kind=It.WILDCARD}getNextNode(){return null}};oi.exports={StaticNode:xt,ParametricNode:Tt,WildcardNode:At,NODE_TYPES:It}});var li=E((Rd,ci)=>{"use strict";f();var $c=require("assert");function je(){if(!(this instanceof je))return new je;this.store=new Map,this.maxMajor=0,this.maxMinors={},this.maxPatches={}}je.prototype.set=function(e,t){if(typeof e!="string")throw new TypeError("Version should be a string");let[r,n,s]=e.split(".",3);if(isNaN(r))throw new TypeError("Major version must be a numeric value");return r=Number(r),n=Number(n)||0,s=Number(s)||0,r>=this.maxMajor&&(this.maxMajor=r,this.store.set("x",t),this.store.set("*",t),this.store.set("x.x",t),this.store.set("x.x.x",t)),n>=(this.maxMinors[r]||0)&&(this.maxMinors[r]=n,this.store.set(`${r}.x`,t),this.store.set(`${r}.x.x`,t)),s>=(this.maxPatches[`${r}.${n}`]||0)&&(this.maxPatches[`${r}.${n}`]=s,this.store.set(`${r}.${n}.x`,t)),this.store.set(`${r}.${n}.${s}`,t),this};je.prototype.get=function(e){return this.store.get(e)};ci.exports={name:"version",mustMatchWhenDerived:!0,storage:je,validate(e){$c(typeof e=="string","Version should be a string")}}});var di=E((Td,ui)=>{"use strict";f();var Lc=require("assert");function Bc(){let e=new Map,t=[],r=new Map;return{get:n=>{let s=e.get(n);if(s)return s;if(t.length!==0){if(r.has(n))return r.get(n);for(let i of t)if(i.host.test(n))return r.set(n,i.value),i.value;r.set(n,void 0)}},set:(n,s)=>{if(n instanceof RegExp){let i=new RegExp(n.source,n.flags.replace(/[gy]/g,""));t.push({host:i,value:s}),r.clear()}else e.set(n,s)}}}ui.exports={name:"host",mustMatchWhenDerived:!1,storage:Bc,validate(e){Lc(typeof e=="string"||Object.prototype.toString.call(e)==="[object RegExp]","Host should be a string or a RegExp")}}});var mi=E((Id,fi)=>{"use strict";f();var kc=li(),Uc=di(),wr=require("assert"),Er=class{constructor(t){if(this.strategies={version:kc,host:Uc},this.strategiesInUse=new Set,this.asyncStrategiesInUse=new Set,t)for(let r of Object.values(t))this.addConstraintStrategy(r)}isStrategyUsed(t){return this.strategiesInUse.has(t)||this.asyncStrategiesInUse.has(t)}hasConstraintStrategy(t){let r=this.strategies[t];return r!==void 0?r.isCustom||this.isStrategyUsed(t):!1}addConstraintStrategy(t){if(wr(typeof t.name=="string"&&t.name!=="","strategy.name is required."),wr(t.storage&&typeof t.storage=="function","strategy.storage function is required."),wr(t.deriveConstraint&&typeof t.deriveConstraint=="function","strategy.deriveConstraint function is required."),this.strategies[t.name]&&this.strategies[t.name].isCustom)throw new Error(`There already exists a custom constraint with the name ${t.name}.`);if(this.isStrategyUsed(t.name))throw new Error(`There already exists a route with ${t.name} constraint.`);t.isCustom=!0,t.isAsync=t.deriveConstraint.length===3,this.strategies[t.name]=t,t.mustMatchWhenDerived&&this.noteUsage({[t.name]:t})}deriveConstraints(t,r,n){let s=this.deriveSyncConstraints(t,r);if(n===void 0)return s;this.deriveAsyncConstraints(s,t,r,n)}deriveSyncConstraints(t,r){}noteUsage(t){if(t){let r=this.strategiesInUse.size;for(let n in t){if(!Object.hasOwn(t,n))continue;this.strategies[n].isAsync?this.asyncStrategiesInUse.add(n):this.strategiesInUse.add(n)}r!==this.strategiesInUse.size&&this._buildDeriveConstraints()}}newStoreForConstraint(t){if(!this.strategies[t])throw new Error(`No strategy registered for constraint key ${t}`);return this.strategies[t].storage()}validateConstraints(t){for(let r in t){if(!Object.hasOwn(t,r))continue;let n=t[r];if(typeof n>"u")throw new Error("Can't pass an undefined constraint value, must pass null or no key at all");let s=this.strategies[r];if(!s)throw new Error(`No strategy registered for constraint key ${r}`);s.validate&&s.validate(n)}}deriveAsyncConstraints(t,r,n,s){let i=this.asyncStrategiesInUse.size;if(i===0){s(null,t);return}let o=!1;t=t||{};for(let a of this.asyncStrategiesInUse)this.strategies[a].deriveConstraint(r,n,(u,l)=>{if(!o){if(u!==null){o=!0,s(u);return}t[a]=l,--i===0&&s(null,t)}})}_buildDeriveConstraints(){if(this.strategiesInUse.size===0)return;let t=["return {"];for(let r of this.strategiesInUse){let n=this.strategies[r];n.isCustom?t.push(` ${n.name}: this.strategies.${r}.deriveConstraint(req, ctx),`):r==="version"?t.push(" version: req.headers['accept-version'],"):t.push(" host: req.headers.host || req.headers[':authority'],")}t.push("}"),this.deriveSyncConstraints=new Function("req","ctx",t.join(`
23
+ `)).bind(this)}};fi.exports=Er});var hi=E((Od,pi)=>{"use strict";f();var Hc=["ACL","BIND","CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LINK","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCALENDAR","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","QUERY","REBIND","REPORT","SEARCH","SOURCE","SUBSCRIBE","TRACE","UNBIND","UNLINK","UNLOCK","UNSUBSCRIBE"];pi.exports=Hc});var Si=E((Cd,yi)=>{"use strict";f();function gi(e,t){return e===50?t===53?"%":t===51?"#":t===52?"$":t===54?"&":t===66||t===98?"+":t===67||t===99?",":t===70||t===102?"/":null:e===51?t===65||t===97?":":t===66||t===98?";":t===68||t===100?"=":t===70||t===102?"?":null:e===52&&t===48?"@":null}function qc(e,t){let r=!1,n=!1,s="";for(let o=1;o<e.length;o++){let a=e.charCodeAt(o);if(a===37){let c=e.charCodeAt(o+1),u=e.charCodeAt(o+2);gi(c,u)===null?r=!0:(n=!0,c===50&&u===53&&(r=!0,e=e.slice(0,o+1)+"25"+e.slice(o+1),o+=2),o+=2)}else if(a===63||a===35||a===59&&t){s=e.slice(o+1),e=e.slice(0,o);break}}return{path:r?decodeURI(e):e,querystring:s,shouldDecodeParam:n}}function jc(e){let t=e.indexOf("%");if(t===-1)return e;let r="",n=t;for(let s=t;s<e.length;s++)if(e.charCodeAt(s)===37){let i=e.charCodeAt(s+1),o=e.charCodeAt(s+2),a=gi(i,o);r+=e.slice(n,s)+a,n=s+3}return e.slice(0,t)+r+e.slice(n)}yi.exports={safeDecodeURI:qc,safeDecodeURIComponent:jc}});var _i=E((Md,Ii)=>{"use strict";f();var _=require("assert"),Qc=vs(),De=Ws(),xr=br(),{prettyPrintTree:Fc}=ei(),{StaticNode:bi,NODE_TYPES:Pi}=ai(),Wc=mi(),Oe=hi(),vr=wt(),{safeDecodeURI:wi,safeDecodeURIComponent:Rr}=Si(),Ei=/^https?:\/\/.*?\//,be=/(\/:[^/()]*?)\?(\/?)/,vi=/[.*+?^${}()|[\]\\]/g,Ri=/\/\/+/g;if(!De(Ei))throw new Error("the FULL_PATH_REGEXP is not safe, update this module");if(!De(be))throw new Error("the OPTIONAL_PARAM_REGEXP is not safe, update this module");if(!De(vi))throw new Error("the ESCAPE_REGEXP is not safe, update this module");if(!De(Ri))throw new Error("the REMOVE_DUPLICATE_SLASHES_REGEXP is not safe, update this module");function T(e){if(!(this instanceof T))return new T(e);e=e||{},this._opts=e,e.defaultRoute?(_(typeof e.defaultRoute=="function","The default route must be a function"),this.defaultRoute=e.defaultRoute):this.defaultRoute=null,e.onBadUrl?(_(typeof e.onBadUrl=="function","The bad url handler must be a function"),this.onBadUrl=e.onBadUrl):this.onBadUrl=null,e.buildPrettyMeta?(_(typeof e.buildPrettyMeta=="function","buildPrettyMeta must be a function"),this.buildPrettyMeta=e.buildPrettyMeta):this.buildPrettyMeta=Gc,e.querystringParser?(_(typeof e.querystringParser=="function","querystringParser must be a function"),this.querystringParser=e.querystringParser):this.querystringParser=t=>t.length===0?{}:Qc.parse(t),this.caseSensitive=e.caseSensitive===void 0?!0:e.caseSensitive,this.ignoreTrailingSlash=e.ignoreTrailingSlash||!1,this.ignoreDuplicateSlashes=e.ignoreDuplicateSlashes||!1,this.maxParamLength=e.maxParamLength||100,this.onMaxParamLength=e.onMaxParamLength||null,this.allowUnsafeRegex=e.allowUnsafeRegex||!1,this.constrainer=new Wc(e.constraints),this.useSemicolonDelimiter=e.useSemicolonDelimiter||!1,this.routes=[],this.trees=Object.create(null)}T.prototype.on=function(t,r,n,s,i){typeof n=="function"&&(s!==void 0&&(i=s),s=n,n={}),_(typeof r=="string","Path should be a string"),_(r.length>0,"The path could not be empty"),_(r[0]==="/"||r[0]==="*","The first character of a path should be `/` or `*`"),_(typeof s=="function","Handler should be a function");let o=r.match(be);if(o){_(r.length===o.index+o[0].length,"Optional Parameter needs to be the last parameter of the path");let u=r.replace(be,"$1$2"),l=r.replace(be,"$2")||"/";this.on(t,u,n,s,i),this.on(t,l,n,s,i);return}let a=r;this.ignoreDuplicateSlashes&&(r=_t(r)),this.ignoreTrailingSlash&&(r=Ot(r));let c=Array.isArray(t)?t:[t];for(let u of c)_(typeof u=="string","Method should be a string"),_(Oe.includes(u),`Method '${u}' is not an http method.`),this._on(u,r,n,s,i,a)};T.prototype._on=function(t,r,n,s,i){let o={};n.constraints!==void 0&&(_(typeof n.constraints=="object"&&n.constraints!==null,"Constraints should be an object"),Object.keys(n.constraints).length!==0&&(o=n.constraints)),this.constrainer.validateConstraints(o),this.constrainer.noteUsage(o),this.trees[t]===void 0&&(this.trees[t]=new bi("/"));let a=r;if(a==="*"&&this.trees[t].prefix.length!==0){let d=this.trees[t];this.trees[t]=new bi(""),this.trees[t].staticChildren["/"]=d}let c=this.trees[t],u=c.prefix.length,l=[];for(let d=0;d<=a.length;d++){if(a.charCodeAt(d)===58&&a.charCodeAt(d+1)===58){d++;continue}let p=a.charCodeAt(d)===58&&a.charCodeAt(d+1)!==58,y=a.charCodeAt(d)===42;if(p||y||d===a.length&&d!==u){let b=a.slice(u,d);this.caseSensitive||(b=b.toLowerCase()),b=b.replaceAll("::",":"),b=b.replaceAll("%","%25"),c=c.createStaticChild(b)}if(p){let b=!1,S=!0,D="",A=[],te=d+1;for(let P=te;;P++){let he=a.charCodeAt(P),$e=he===40,j=he===45||he===46,z=he===47||P===a.length;if($e||j||z){let ae=a.slice(te,P);if(l.push(ae),b=b||$e||j,$e){let ce=Ai(a,P),we=a.slice(P,ce+1);this.allowUnsafeRegex||_(De(new RegExp(we)),`The regex '${we}' is not safe!`),A.push(Ti(we)),P=ce+1,S=!0}else A.push(S?"(.*?)":`(${D}|(?:(?!${D}).)*)`),S=!1;let Ut=P;for(;P<a.length;P++){let ce=a.charCodeAt(P);if(ce===47)break;if(ce===58)if(a.charCodeAt(P+1)===58)P++;else break}let re=a.slice(Ut,P);if(re&&(re=re.replaceAll("::",":"),re=re.replaceAll("%","%25"),A.push(D=xi(re))),te=P+1,z||a.charCodeAt(P)===47||P===a.length){let ce=b?"()"+re:re,we=a.slice(d,P);a=a.slice(0,d+1)+ce+a.slice(P),d+=ce.length;let Mo=b?new RegExp("^"+A.join("")+"$"):null;c=c.createParametricChild(Mo,re||null,we),u=d+1;break}}}}else if(y&&(l.push("*"),c=c.createWildcardChild(),u=d+1,d!==a.length-1))throw new Error("Wildcard must be the last character in the route")}this.caseSensitive||(a=a.toLowerCase()),a==="*"&&(a="/*");for(let d of this.routes){let p=d.opts.constraints||{};if(d.method===t&&d.pattern===a&&xr(p,o))throw new Error(`Method '${t}' already declared for route '${a}' with constraints '${JSON.stringify(o)}'`)}let m={method:t,path:r,pattern:a,params:l,opts:n,handler:s,store:i};this.routes.push(m),c.addRoute(m,this.constrainer)};T.prototype.hasRoute=function(t,r,n){return this.findRoute(t,r,n)!==null};T.prototype.findRoute=function(t,r,n={}){if(this.trees[t]===void 0)return null;let s=r,i=this.trees[t],o=i.prefix.length,a=[];for(let c=0;c<=s.length;c++){if(s.charCodeAt(c)===58&&s.charCodeAt(c+1)===58){c++;continue}let u=s.charCodeAt(c)===58&&s.charCodeAt(c+1)!==58,l=s.charCodeAt(c)===42;if(u||l||c===s.length&&c!==o){let m=s.slice(o,c);if(this.caseSensitive||(m=m.toLowerCase()),m=m.replaceAll("::",":"),m=m.replaceAll("%","%25"),i=i.getStaticChild(m),i===null)return null}if(u){let m=!1,d=!0,p="",y=[],b=c+1;for(let S=b;;S++){let D=s.charCodeAt(S),A=D===40,te=D===45||D===46,P=D===47||S===s.length;if(A||te||P){let he=s.slice(b,S);if(a.push(he),m=m||A||te,A){let z=Ai(s,S),ae=s.slice(S,z+1);this.allowUnsafeRegex||_(De(new RegExp(ae)),`The regex '${ae}' is not safe!`),y.push(Ti(ae)),S=z+1,d=!0}else y.push(d?"(.*?)":`(${p}|(?:(?!${p}).)*)`),d=!1;let $e=S;for(;S<s.length;S++){let z=s.charCodeAt(S);if(z===47)break;if(z===58)if(s.charCodeAt(S+1)===58)S++;else break}let j=s.slice($e,S);if(j&&(j=j.replaceAll("::",":"),j=j.replaceAll("%","%25"),y.push(p=xi(j))),b=S+1,P||s.charCodeAt(S)===47||S===s.length){let z=m?"()"+j:j,ae=s.slice(c,S);s=s.slice(0,c+1)+z+s.slice(S),c+=z.length;let Ut=m?new RegExp("^"+y.join("")+"$"):null;if(i=i.getParametricChild(Ut,j||null,ae),i===null)return null;o=c+1;break}}}}else if(l&&(a.push("*"),i=i.getWildcardChild(),o=c+1,c!==s.length-1))throw new Error("Wildcard must be the last character in the route")}this.caseSensitive||(s=s.toLowerCase());for(let c of this.routes){let u=c.opts.constraints||{};if(c.method===t&&c.pattern===s&&xr(u,n))return{handler:c.handler,store:c.store,params:c.params}}return null};T.prototype.hasConstraintStrategy=function(e){return this.constrainer.hasConstraintStrategy(e)};T.prototype.addConstraintStrategy=function(e){this.constrainer.addConstraintStrategy(e),this._rebuild(this.routes)};T.prototype.reset=function(){this.trees=Object.create(null),this.routes=[]};T.prototype.off=function(t,r,n){_(typeof r=="string","Path should be a string"),_(r.length>0,"The path could not be empty"),_(r[0]==="/"||r[0]==="*","The first character of a path should be `/` or `*`"),_(typeof n>"u"||typeof n=="object"&&!Array.isArray(n)&&n!==null,"Constraints should be an object or undefined.");let s=r.match(be);if(s){_(r.length===s.index+s[0].length,"Optional Parameter needs to be the last parameter of the path");let o=r.replace(be,"$1$2"),a=r.replace(be,"$2")||"/";this.off(t,o,n),this.off(t,a,n);return}this.ignoreDuplicateSlashes&&(r=_t(r)),this.ignoreTrailingSlash&&(r=Ot(r));let i=Array.isArray(t)?t:[t];for(let o of i)this._off(o,r,n)};T.prototype._off=function(t,r,n){_(typeof t=="string","Method should be a string"),_(Oe.includes(t),`Method '${t}' is not an http method.`);function s(c){return t!==c.method||r!==c.path}function i(c){return s(c)||!xr(n,c.opts.constraints||{})}let o=n?i:s,a=this.routes.filter(o);this._rebuild(a)};T.prototype.lookup=function(t,r,n,s){if(typeof n=="function"&&(s=n,n=void 0),s===void 0){let i=this.constrainer.deriveConstraints(t,n),o=this.find(t.method,t.url,i);return this.callHandler(o,t,r,n)}this.constrainer.deriveConstraints(t,n,(i,o)=>{if(i!==null){s(i);return}try{let a=this.find(t.method,t.url,o),c=this.callHandler(a,t,r,n);s(null,c)}catch(a){s(a)}})};T.prototype.callHandler=function(t,r,n,s){return t===null?this._defaultRoute(r,n,s):s===void 0?t.handler(r,n,t.params,t.store,t.searchParams):t.handler.call(s,r,n,t.params,t.store,t.searchParams)};T.prototype.find=function(t,r,n){let s=this.trees[t];if(s===void 0)return null;r.charCodeAt(0)!==47&&(r=r.replace(Ei,"/")),this.ignoreDuplicateSlashes&&(r=_t(r));let i,o,a;try{i=wi(r,this.useSemicolonDelimiter),r=i.path,o=i.querystring,a=i.shouldDecodeParam}catch{return this._onBadUrl(r)}this.ignoreTrailingSlash&&(r=Ot(r));let c=r;this.caseSensitive===!1&&(r=r.toLowerCase());let u=this.maxParamLength,l=s.prefix.length,m=[],d=r.length,p=[],y=!1;for(;;){if(l===d&&s.isLeafNode){let S=s.handlerStorage.getMatchingHandler(n);if(S!==null)return{handler:S.handler,store:S.store,params:S._createParamsObject(m),searchParams:this.querystringParser(o)}}let b=s.getNextNode(r,l,p,m.length);if(b===null){if(p.length===0)return y&&this.onMaxParamLength?this._onMaxParamLength(c):null;let S=p.pop();l=S.brotherPathIndex,m.splice(S.paramsCount),b=S.brotherNode}for(s=b;;){if(s.kind===Pi.STATIC){l+=s.prefix.length;break}if(s.kind===Pi.WILDCARD){let A=c.slice(l);a&&(A=Rr(A)),m.push(A),l=d;break}let S=c.indexOf("/",l);S===-1&&(S=d);let D=c.slice(l,S);if(a&&(D=Rr(D)),s.isRegex){let A=s.regex.exec(D);if(A===null){if(p.length===0)return y&&this.onMaxParamLength?this._onMaxParamLength(c):null;let P=p.pop();l=P.brotherPathIndex,m.splice(P.paramsCount),s=P.brotherNode;continue}let te=!1;for(let P=1;P<A.length;P++)if((A[P]??"").length>u){te=!0;break}if(te){if(y=!0,p.length===0)return this.onMaxParamLength?this._onMaxParamLength(c):null;let P=p.pop();l=P.brotherPathIndex,m.splice(P.paramsCount),s=P.brotherNode;continue}for(let P=1;P<A.length;P++)m.push(A[P]??"")}else{if(D.length>u){if(y=!0,p.length===0)return this.onMaxParamLength?this._onMaxParamLength(c):null;let A=p.pop();l=A.brotherPathIndex,m.splice(A.paramsCount),s=A.brotherNode;continue}m.push(D)}l=S;break}}};T.prototype._rebuild=function(e){this.reset();for(let t of e){let{method:r,path:n,opts:s,handler:i,store:o}=t;this._on(r,n,s,i,o)}};T.prototype._defaultRoute=function(e,t,r){if(this.defaultRoute!==null)return r===void 0?this.defaultRoute(e,t):this.defaultRoute.call(r,e,t);t.statusCode=404,t.end()};T.prototype._onBadUrl=function(e){if(this.onBadUrl===null)return null;let t=this.onBadUrl;return{handler:(r,n,s)=>t(e,r,n),params:{},store:null}};T.prototype._onMaxParamLength=function(e){if(this.onMaxParamLength===null)return null;let t=this.onMaxParamLength;return{handler:(r,n,s)=>t(e,r,n),params:{},store:null}};T.prototype.prettyPrint=function(e={}){let t=e.method;e.buildPrettyMeta=this.buildPrettyMeta.bind(this);let r=null;if(t===void 0){let{version:n,host:s,...i}=this.constrainer.strategies;i[vr.name]=vr;let o=new T({...this._opts,constraints:i}),a=this.routes.map(c=>{let u={...c.opts.constraints,[vr.name]:c.method};return{...c,method:"MERGED",opts:{constraints:u}}});o._rebuild(a),r=o.trees.MERGED}else r=this.trees[t];return r==null?"(empty tree)":Fc(r,e)};for(let e in Oe){if(!Oe.hasOwnProperty(e))continue;let t=Oe[e],r=t.toLowerCase();T.prototype[r]=function(n,s,i){return this.on(t,n,s,i)}}T.prototype.all=function(e,t,r){this.on(Oe,e,t,r)};T.sanitizeUrlPath=function(t,r){let n=wi(t,r);return n.shouldDecodeParam?Rr(n.path):n.path};T.removeDuplicateSlashes=_t;T.trimLastSlash=Ot;Ii.exports=T;function xi(e){return e.replace(vi,"\\$&")}function _t(e){return e.indexOf("//")!==-1?e.replace(Ri,"/"):e}function Ot(e){return e.length>1&&e.charCodeAt(e.length-1)===47?e.slice(0,-1):e}function Ti(e){return e.charCodeAt(1)===94&&(e=e.slice(0,1)+e.slice(2)),e.charCodeAt(e.length-2)===36&&(e=e.slice(0,e.length-2)+e.slice(e.length-1)),e}function Ai(e,t){let r=1;for(;t<e.length;){if(t++,e.charCodeAt(t)===92){t++;continue}if(e.charCodeAt(t)===41?r--:e.charCodeAt(t)===40&&r++,!r)return t}throw new TypeError('Invalid regexp expression in "'+e+'"')}function Gc(e){return e?e.store?Object.assign({},e.store):{}:{}}});function L(e,t,r=200){let n=Tr.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 B(e,t,r=200){let n=Tr.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 Ce(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function Oi(e,t){B(e,t.message,t.status)}var Tr,oe=O(()=>{"use strict";f();Tr=require("buffer")});async function Ci(e,t){let r;try{r=await(0,Di.json)(e)}catch{return B(t,"Invalid input",400),null}let{output:n,success:s}=(0,k.safeParse)(zc,r,{abortEarly:!0});return s?n:(B(t,"Invalid input",400),null)}var Di,k,zc,Ni=O(()=>{"use strict";f();Di=require("stream/consumers"),k=require("valibot");oe();zc=(0,k.object)({tags:(0,k.union)([(0,k.pipe)((0,k.array)((0,k.string)()),(0,k.minLength)(1)),(0,k.literal)("all")])})});async function _r(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}function $i(e,t){let r=e.schemaHash;if(r==null)return L(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let n=Dt.get(r);return n==null?(L(t,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:r,schemas:n}}async function Li(e,t,r){let n=Ir.Buffer.from(e,"base64").toString("utf8"),s=Kc(n,t.toString());r&&console.log("[Accelerate] schema with override:",s);let i=await _r(s);return{base64Override:Ir.Buffer.from(s,"utf8").toString("base64"),overrideHash:i}}function Kc(e,t){let r=Jc(e);if(!r)throw new Error("No datasource block found in schema.");let n=e.slice(r.openBraceIndex+1,r.closeBraceIndex),s=Zc(n,t,rl(e,r.openBraceIndex));return`${e.slice(0,r.openBraceIndex+1)}${s}${e.slice(r.closeBraceIndex)}`}function Jc(e){let t="datasource";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="/"&&e[r+1]==="/"){r=Or(e,r+2);continue}if(n==="/"&&e[r+1]==="*"){r=Dr(e,r+2);continue}if(n==='"'){r=Cr(e,r+1);continue}if(e.startsWith(t,r)&&!Mi(e[r-1])&&!Mi(e[r+t.length])){let s=Yc(e,r+t.length,"{");if(s===-1)return null;let i=Xc(e,s);return i===-1?null:{closeBraceIndex:i,openBraceIndex:s}}}return null}function Yc(e,t,r){for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=Or(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=Dr(e,n+2);continue}if(s==='"'){n=Cr(e,n+1);continue}if(s===r)return n}return-1}function Xc(e,t){let r=0;for(let n=t;n<e.length;n+=1){let s=e[n];if(s==="/"&&e[n+1]==="/"){n=Or(e,n+2);continue}if(s==="/"&&e[n+1]==="*"){n=Dr(e,n+2);continue}if(s==='"'){n=Cr(e,n+1);continue}if(s==="{"){r+=1;continue}if(s==="}"&&(r-=1,r===0))return n}return-1}function Or(e,t){let r=t;for(;r<e.length&&e[r]!==`
24
+ `;)r+=1;return r}function Dr(e,t){let r=e.indexOf("*/",t);return r===-1?e.length:r+1}function Cr(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 Mi(e){return e!=null&&/[A-Za-z0-9_]/.test(e)}function Zc(e,t,r){let n=`"${sl(t)}"`,s=el(e);for(let[m,d]of s.entries()){let{comment:p,code:y}=Bi(d.line),b=y.match(/^(\s*)url(\s*)=(\s*).*/);if(b)return s[m]={line:`${b[1]}url${b[2]}=${b[3]}${n}${p}`,terminator:d.terminator},Ar(s)}let i=nl(e),o=tl(s,r),a=`${o}url = ${n}`;if(!e.includes(`
25
+ `)&&!e.includes("\r")){let m=e.trim();return m.length===0?`${i}${a}${i}${r}`:`${i}${o}${m}${i}${a}${i}${r}`}let c=s.at(-1);if(c&&c.terminator===""&&/^\s*$/.test(c.line))return`${Ar(s.slice(0,-1))}${a}${i}${r}`;let u=Ar(s),l=u.endsWith(`
26
+ `)||u.endsWith("\r")?"":i;return`${u}${l}${a}${i}${r}`}function el(e){let t=[],r=0;for(let n=0;n<e.length;n+=1){if(e[n]==="\r"&&e[n+1]===`
7
27
  `){t.push({line:e.slice(r,n),terminator:`\r
8
28
  `}),n+=1,r=n+1;continue}(e[n]===`
9
- `||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 at(e){return e.map(t=>`${t.line}${t.terminator}`).join("")}function Gr(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 ro(e,t){for(let r of e){let{code:n}=Gr(r.line),s=n.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(s?.[1])return s[1]}return`${t}${zs}`}function no(e,t){let r=e.lastIndexOf(`
10
- `,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function so(e){return e.includes(`\r
29
+ `||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 Ar(e){return e.map(t=>`${t.line}${t.terminator}`).join("")}function Bi(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 tl(e,t){for(let r of e){let{code:n}=Bi(r.line),s=n.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(s?.[1])return s[1]}return`${t}${Vc}`}function rl(e,t){let r=e.lastIndexOf(`
30
+ `,t)+1,n=r;for(;e[n]===" "||e[n]===" ";)n+=1;return e.slice(r,n)}function nl(e){return e.includes(`\r
11
31
  `)?`\r
12
32
  `:`
13
- `}function oo(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var it,xe,zs,jr=T(()=>{"use strict";p();it=require("buffer"),xe=new Map;zs=" "});function Te(e){let{req:t}=e;return{traceparent:t.header("traceparent"),"X-capture-telemetry":t.header("X-capture-telemetry")}}var Kr=T(()=>{"use strict";p()});async function Vr(e){let{issues:t,output:r,success:n}=(0,S.safeParse)(ao,await e.req.json(),{abortEarly:!0});return n?r:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:t}},400)}function zr(e,t){let{output:r,success:n}=(0,S.safeParse)(io,e);return n?r:t.json({EngineMalfunction:{}},500)}var S,ao,io,Jr=T(()=>{"use strict";p();S=require("valibot"),ao=(0,S.object)({isolation_level:(0,S.optional)((0,S.string)()),max_wait:(0,S.pipe)((0,S.number)(),(0,S.integer)(),(0,S.minValue)(0)),timeout:(0,S.pipe)((0,S.number)(),(0,S.integer)(),(0,S.minValue)(0))});io=(0,S.looseObject)({id:(0,S.union)([(0,S.string)(),(0,S.number)()])})});var Yr={};Y(Yr,{getQueryPlanExecutorServer:()=>co,queryPlanExecutorVersion:()=>Xr.version});async function co(e){return mt===void 0&&(mt=await C.Server.create({databaseUrl:e.get("db").connectionString,maxResponseSize:(0,C.parseSize)("128 MiB"),queryTimeout:(0,C.parseDuration)("PT5M"),maxTransactionTimeout:(0,C.parseDuration)("PT5M"),maxTransactionWaitTime:(0,C.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.get("debug")?"debug":"off"}})),mt}var C,Xr,mt,Zr=T(()=>{"use strict";p();C=require("@prisma/query-plan-executor"),Xr=require("@prisma/query-plan-executor")});var on={};Y(on,{accelerateRoute:()=>re});function Ie(){return en??=Promise.resolve().then(()=>(ot(),st)),en}function uo(){return rn??=Promise.resolve().then(()=>(Zr(),Yr)),rn}async function lo(){return tn??=import("@prisma/get-platform").then(async({default:e})=>await e.getPlatformInfo()),await tn}async function pt(e){let{req:t}=e,{Engine:r}=await Ie(),n=Wr(e);if(n instanceof Response)return n;let{base64Override:s,overrideHash:o}=n.schemas;return await r.get({base64Schema:s,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||t.param("clientVersion"),debug:e.get("debug"),platform:await lo(),schemaHash:o})}var nn,sn,q,en,tn,rn,re,mo,ne,po,go,an=T(()=>{"use strict";p();nn=require("hono/http-exception"),sn=require("hono/tiny"),q=require("hono/validator");Be();qr();jr();Kr();Jr();re=new sn.Hono;re.post("/invalidate",(0,q.validator)("header",U),async e=>{let t=await Qr(e);return t instanceof Response?t:e.body(null)});mo="/:clientVersion/:schemaHash",ne=re.basePath(mo);re.route("/",ne);po=["/graphql","/itx/:transactionId/graphql"];ne.on("POST",[...po],(0,q.validator)("header",U),async e=>{let{req:t}=e;try{let r=await pt(e);if(r instanceof Response)return r;let n=await t.text(),s=t.param("transactionId"),o=await r.request(n,{...Te(e),"X-transaction-id":s});return e.text(o)}catch(r){let{handleEngineError:n}=await Ie();return n(r,e)}});ne.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],(0,q.validator)("header",U),async e=>{let{req:t}=e;try{let r=await pt(e);if(r instanceof Response)return r;let s=`${t.routePath.split("/").filter(Boolean).at(-1)}Transaction`,o=t.param("transactionId"),a=await r[s](o,Te(e));return e.json(a)}catch(r){let{handleEngineError:n}=await Ie();return n(r,e)}});ne.put("/schema",(0,q.validator)("header",U),async e=>{let{req:t}=e,r=await t.text();if(!r)return e.text("Missing schema",400);let n=t.param("schemaHash"),s=xe.get(n);if(s==null){if(n!==await ct(r))return e.text("Schema hash mismatch",400);let o=await Hr(r,e.get("db").prismaORMConnectionString,e.get("debug"));return xe.set(n,{base64Original:r,...o}),e.text(n)}return r!==s.base64Original?e.text("Schema mismatch",400):e.text(n)});ne.post("/transaction/start",(0,q.validator)("header",U),async e=>{let{req:t}=e,r=await Vr(e);if(r instanceof Response)return r;try{let n=await pt(e);if(n instanceof Response)return n;let s=await n.startTransaction(r,Te(e)),o=zr(s,e);if(o instanceof Response)return o;let{id:a}=o,i=t.param("clientVersion"),c=t.param("schemaHash");return e.json({...s,"data-proxy":{endpoint:`${new URL(t.url).origin}/${i}/${c}/itx/${a}`}})}catch(n){let{handleEngineError:s}=await Ie();return s(n,e)}});go=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[e,t]of go)re.on(t,e,(0,q.validator)("header",U),async r=>{let{getQueryPlanExecutorServer:n,queryPlanExecutorVersion:s}=await uo(),o=r.req.header("prisma-engine-hash");if(o!=="0.0.0"&&o!==s)throw new nn.HTTPException(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${o} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${s}.`});return await(await n(r)).fetch(r.req.raw)})});var ln={};Y(ln,{utilityRoute:()=>gt});var cn,un,gt,Ka,dn=T(()=>{"use strict";p();cn=require("hono/tiny"),un=require("http-status-codes"),gt=new cn.Hono;gt.post("/database/dump",async e=>{let t=e.get("db"),r=e.get("databaseDumpPath");return await t.dump(r),e.json({dumpPath:r},un.StatusCodes.CREATED)});Ka=gt.get("/health",e=>e.json({name:e.get("name")}))});var Yo={};Y(Yo,{DEFAULT_DATABASE_PORT:()=>ge,DEFAULT_SERVER_PORT:()=>fe,DEFAULT_SHADOW_DATABASE_PORT:()=>he,DEFAULT_STREAMS_PORT:()=>ye,PortNotAvailableError:()=>_,ServerAlreadyRunningError:()=>ae,copyPrismaDevRuntimeAssets:()=>dr,getPrismaDevRuntimeAssetManifest:()=>je,startPrismaDevServer:()=>An,unstable_startServer:()=>Jo});module.exports=Cn(Yo);p();p();Be();p();var ve=require("net"),vr=require("path"),Rr=require("pathe/utils");j();p();var L=require("get-port-please"),be=require("remeda"),ge=51214,fe=51213,he=51215,ye=51216,pe=65535,Q=0,I=-1/0;async function qe(e){let{debug:t,name:r,requestedPorts:n,servers:s}=e,{portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a}=Vn(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:I,port:I,shadowDatabasePort:I,streamsPort:I},c=["port","databasePort","shadowDatabasePort","streamsPort"];for(let u of c){let l=await jn({debug:t,portKey:u,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:a,requestedPorts:n})??await Kn({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 jn(e){let{debug:t,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:s,requestedPorts:o}=e,{[r]:a,...i}=o;if(Ce(a))return await Yn({debug:t,otherRequestedPorts:i,portKey:r,portsUsedByOtherServers:n,requestedPort:a}),a;let c=s?.[r]??I;if(!Ce(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,L.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 Kn(e){let{debug:t,pickedPorts:r,portKey:n,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:o}=e,a=Math.max(ge,fe,he,ye)+1,i=Object.values(r).filter(m=>m!==void 0),c=o?Jn(o):[],u=[...i,...Object.keys(s).map(Number),...c],l=Math.min(Math.max(a,...u)+100,pe),h=(0,be.difference)((0,be.range)(a,l),u),d={port:fe,databasePort:ge,shadowDatabasePort:he,streamsPort:ye}[n];try{return await(0,L.getPort)({port:d in s||i.includes(d)||c.includes(d)?void 0:d,ports:h})}catch(m){if(m instanceof Error&&m.name==="GetPortError"&&l+1<=pe)return t&&console.debug(`Expanding port lookup to range [${l+1}, ${pe}].`),await(0,L.getPort)({portRange:[l+1,pe]});throw m}}function Ce(e){return Number.isFinite(e)&&e>=0}function Vn(e,t){let r={},n;for(let s of t){let{databasePort:o,port:a,shadowDatabasePort:i}=s,c=zn(s);if(s.name===e){n={databasePort:o,port:a,shadowDatabasePort:i,streamsPort:c};continue}r[o]=!0,r[a]=!0,r[i]=!0,Ce(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}function zn(e){let t=e.experimental?.streams?.serverUrl;if(!t)return I;try{let r=Number(new URL(t).port);return Number.isInteger(r)&&r>0?r:I}catch{return I}}function Jn(e){return[e.port,e.databasePort,e.shadowDatabasePort,e.streamsPort]}async function Yn(e){let{debug:t,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:s,requestedPort:o}=e;if(o!==Q){if(o in s)throw t&&console.error(`Port ${o} was requested for "${n}", but is already used by another server.`),new Qe(o);if(Object.values(r).includes(o))throw t&&console.error(`Port ${o} was requested for "${n}", but also for another key.`),new Ue(o);if((0,L.isUnsafePort)(o))throw t&&console.error(`Port ${o} was requested for "${n}", but is unsafe.`),new _(o);if(await(0,L.checkPort)(o)===!1)throw t&&console.error(`Port ${o} was requested for "${n}", but is not available.`),new _(o)}}var _=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},Ue=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"},Qe=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"};p();var We=require("perf_hooks"),nr=require("@electric-sql/pglite");p();var zt=require("buffer"),jt=500,Kt=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,Xn=new RegExp(`(?:${Kt.source}\\.)*${Kt.source}`),Zn=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${Xn.source})`,"gi"),es=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,Vt=/prismaQuery='([^']+)'/,ts=new Set([$(`
33
+ `}function sl(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}var Ir,Dt,Vc,ki=O(()=>{"use strict";f();Ir=require("buffer");oe();Dt=new Map;Vc=" "});function Qe(e,t){let r=e[t];return Array.isArray(r)?r.at(-1):r}var Nr=O(()=>{"use strict";f()});function Hi(e,t){let r=(e.method??"GET").toUpperCase(),n=`${t.origin}${e.url??"/"}`,s={headers:ol(e.headers),method:r};return il.has(r)||(s.body=Mr.Readable.toWeb(e),s.duplex="half"),new Request(n,s)}async function qi(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,Ui.pipeline)(Mr.Readable.fromWeb(e.body),t)}function ol(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 Mr,Ui,il,ji=O(()=>{"use strict";f();Mr=require("stream"),Ui=require("stream/promises"),il=new Set(["GET","HEAD"])});var Wi={};Ee(Wi,{createHTTPServer:()=>cl,wrap:()=>K});function K(e,t){return async function(n,s,i){let o=t?Date.now():0;t&&s.once("finish",()=>{let a=Date.now()-o;console.log("[Accelerate]",`<-- ${n.method??"?"} ${n.url??""} ${s.statusCode} ${a}ms`)});try{await e(n,s,i)}catch(a){try{al(a,s,n,t)}catch(c){t&&console.error("[Accelerate]","error while handling handler error",c),s.destroyed||s.destroy()}}}}function al(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 H){Oi(t,e);return}console.error("[Accelerate]",e);try{Ce(t,500)}catch(s){n&&console.error("[Accelerate]","failed to write 500 response (client likely disconnected)",s),t.destroy()}}function cl(e){let{router:t}=e;return{async listen(r){let n=(0,Qi.createServer)((o,a)=>{t.lookup(o,a)}),i=(await ll(n,r)).port;return n.on("error",o=>{console.error("[Accelerate]",o)}),{async close(){await(0,Fi.promisify)(n.close.bind(n))()},port:i,url:`http://localhost:${i}`}}}}function ll(e,t){return new Promise((r,n)=>{let s=o=>{if(e.off("listening",i),typeof o=="object"&&o!==null&&"code"in o&&o.code==="EADDRINUSE"){n(new V(t));return}n(o)},i=()=>{e.off("error",s),r(e.address())};e.once("error",s),e.once("listening",i),e.listen(t)})}var Qi,Fi,Ct=O(()=>{"use strict";f();Qi=require("http"),Fi=require("util");Be();Ye();oe()});function Nt(e){return{traceparent:Qe(e.headers,"traceparent"),"X-capture-telemetry":Qe(e.headers,"x-capture-telemetry")}}var Gi=O(()=>{"use strict";f();Nr()});async function Vi(e,t){let r;try{r=await(0,zi.json)(e)}catch{return L(t,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:n,output:s,success:i}=(0,R.safeParse)(ul,r,{abortEarly:!0});return i?s:(L(t,{EngineNotStarted:{reason:"InvalidRequest",issues:n}},400),null)}function Ki(e,t){let{output:r,success:n}=(0,R.safeParse)(dl,e);return n?r:(L(t,{EngineMalfunction:{}},500),null)}var zi,R,ul,dl,Ji=O(()=>{"use strict";f();zi=require("stream/consumers"),R=require("valibot");oe();ul=(0,R.object)({isolation_level:(0,R.optional)((0,R.string)()),max_wait:(0,R.pipe)((0,R.number)(),(0,R.integer)(),(0,R.minValue)(0)),timeout:(0,R.pipe)((0,R.number)(),(0,R.integer)(),(0,R.minValue)(0))});dl=(0,R.looseObject)({id:(0,R.union)([(0,R.string)(),(0,R.number)()])})});function Yi(e){let t,r,n=new Promise((o,a)=>{t=o,r=a}),s=o=>{s=i=null,r(o),e?.onRejected?.(o),e?.onFulfilled?.()},i=o=>{i=s=null,t(o),e?.onResolved?.(o),e?.onFulfilled?.()};return{isFulfilled:()=>i===s,promise:n,reject:o=>s?.(o),resolve:o=>i?.(o)}}var Xi=O(()=>{"use strict";f()});var Lr={};Ee(Lr,{Engine:()=>$r,handleEngineError:()=>pl});function pl(e,t){if(console.error(e),e instanceof Fe){L(t,{EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500);return}if(e instanceof Ne){B(t,e.responseBody,e.statusCode);return}Ce(t,500)}var eo,to,ro,no,so,io,fl,ml,Zi,$r,Fe,Ne,Br=O(()=>{"use strict";f();eo=require("child_process"),to=require("events"),ro=require("fs/promises"),no=require("path"),so=require("timers/promises");Xi();io=require("std-env");Te();oe();({PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:fl,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:ml,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:Zi}=io.process.env),$r=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 i=new e(t);return e.#r.set(n,i),r&&console.debug("[Query Engine] starting...",t),await i.start(),r&&console.debug("[Query Engine] started!"),i}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,i])=>{try{await i.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.#a(t,r,"commit")}async request(t,r){let{url:n}=await this.start(),s=this.#n(r),i=await fetch(n,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await Ne.fromResponse(i);return await i.text()}async rollbackTransaction(t,r){return await this.#a(t,r,"rollback")}async startTransaction(t,r){let{url:n}=await this.start(),s=this.#n(r),i=await fetch(`${n}/transaction/start`,{body:JSON.stringify(t),headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await Ne.fromResponse(i);return await i.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:r,resolve:n}=Yi();this.#t=t;let s=ml||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",s);let{proxySignals:i}=await import("foreground-child/proxy-signals"),o=(0,eo.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});i(o),o.stderr.setEncoding("utf8"),o.stdout.setEncoding("utf8");let a=l=>{let m=l.split(`
34
+ `).find(b=>b.includes("Started query engine http server"));if(!m)return;o.stdout.removeListener("data",a);let{fields:d}=JSON.parse(m);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.
35
+ Received data: ${l}`));n({childProcess:o,url:`http://${p}:${y}`})},c=l=>{this.#t=null,r(new Fe(String(l))),o.removeListener("exit",u),o.kill()};o.once("error",c);let u=(l,m)=>{this.#t=null,r(new Fe(`Query Engine exited with code ${l} and signal ${m}`))};return o.once("exit",u),o.stdout.on("data",a),this.#e.debug&&(o.stderr.on("data",console.error.bind(console,"[Query Engine]")),o.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,to.once)(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#i();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let r=mn(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,ro.mkdir)(r,{recursive:!0});let{binaryTarget:n}=this.#e.platform,s=n==="windows"?".exe":"",i=(0,no.join)(r,`query-engine-${n}${s}`);return this.#e.debug&&console.debug("[Query Engine] binary path",i),(fl==="1"||await Re(i)===!1)&&await this.#o({commitHash:t,extension:s,engineBinaryPath:i}),i}async#i(){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#o(t){let{commitHash:r,extension:n,engineBinaryPath:s}=t,{binaryTarget:i}=this.#e.platform,o=`https://binaries.prisma.sh/all_commits/${r}/${i}/query-engine${n}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",o);let a=await fetch(o);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${o}, status code: ${a.status}`);Zi&&await(0,so.setTimeout)(Number(Zi)),await pn(await a.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#a(t,r,n){let{url:s}=await this.#t,i=this.#n(r),o=await fetch(`${s}/transaction/${t}/${n}`,{headers:{...i,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await Ne.fromResponse(o);try{return await o.json()}catch{return{}}}};Fe=class extends Error{name="EngineStartError"},Ne=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 oo={};Ee(oo,{getQueryPlanExecutorServer:()=>hl,queryPlanExecutorVersion:()=>ao.version});async function hl(e){return kr===void 0&&(kr=await pe.Server.create({databaseUrl:e.db.connectionString,maxResponseSize:(0,pe.parseSize)("128 MiB"),queryTimeout:(0,pe.parseDuration)("PT5M"),maxTransactionTimeout:(0,pe.parseDuration)("PT5M"),maxTransactionWaitTime:(0,pe.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:e.debug?"debug":"off"}})),kr}var pe,ao,kr,co=O(()=>{"use strict";f();pe=require("@prisma/query-plan-executor"),ao=require("@prisma/query-plan-executor")});var mo={};Ee(mo,{registerAccelerateRoutes:()=>Sl});function Mt(){return lo??=Promise.resolve().then(()=>(Br(),Lr)),lo}function gl(){return fo??=Promise.resolve().then(()=>(co(),oo)),fo}async function yl(){return uo??=import("@prisma/get-platform").then(async({default:e})=>await e.getPlatformInfo()),await uo}function Sl(e,t,r){e.on("POST","/invalidate",K(async(s,i)=>{ge(s,t),await Ci(s,i)!==null&&Ce(i,200)},r));for(let s of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])e.on("POST",s,K(async(i,o,a)=>{ge(i,t);try{let c=await Ur(o,t,a);if(c===null)return;let u=await(0,Hr.text)(i),l=a.transactionId,m=await c.request(u,{...Nt(i),"X-transaction-id":l});B(o,m)}catch(c){let{handleEngineError:u}=await Mt();u(c,o)}},r));for(let s of["commit","rollback"])e.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${s}`,K(async(i,o,a)=>{ge(i,t);try{let c=await Ur(o,t,a);if(c===null)return;let u=a.transactionId;if(u==null){L(o,{EngineMalfunction:{}},500);return}let l=`${s}Transaction`,m=await c[l](u,Nt(i));L(o,m)}catch(c){let{handleEngineError:u}=await Mt();u(c,o)}},r));e.on("PUT","/:clientVersion/:schemaHash/schema",K(async(s,i,o)=>{ge(s,t);let a=await(0,Hr.text)(s);if(!a){B(i,"Missing schema",400);return}let c=o.schemaHash;if(c==null){B(i,"Missing schema hash",400);return}let u=Dt.get(c);if(u==null){if(c!==await _r(a)){B(i,"Schema hash mismatch",400);return}let l=await Li(a,t.db.prismaORMConnectionString,t.debug);Dt.set(c,{base64Original:a,...l}),B(i,c);return}if(a!==u.base64Original){B(i,"Schema mismatch",400);return}B(i,c)},r)),e.on("POST","/:clientVersion/:schemaHash/transaction/start",K(async(s,i,o)=>{ge(s,t);let a=await Vi(s,i);if(a!==null)try{let c=await Ur(i,t,o);if(c===null)return;let u=await c.startTransaction(a,Nt(s)),l=Ki(u,i);if(l===null)return;let{id:m}=l,d=o.clientVersion,p=o.schemaHash;L(i,{...u,"data-proxy":{endpoint:`http://localhost:${t.port}/${d}/${p}/itx/${m}`}})}catch(c){let{handleEngineError:u}=await Mt();u(c,i)}},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,i]of n)e.on(s,i,K(async(o,a)=>{ge(o,t);let{getQueryPlanExecutorServer:c,queryPlanExecutorVersion:u}=await gl(),l=Qe(o.headers,"prisma-engine-hash");if(l!=="0.0.0"&&l!==u)throw new H(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 m=await c(t),d=Hi(o,{origin:`http://localhost:${t.port}`}),p=await m.fetch(d);await qi(p,a)},r))}async function Ur(e,t,r){let{Engine:n}=await Mt(),s=$i(r,e);if(s===null)return null;let{base64Override:i,overrideHash:o}=s.schemas;return await n.get({base64Schema:i,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||r.clientVersion||"",debug:t.debug,platform:await yl(),schemaHash:o})}var Hr,lo,uo,fo,po=O(()=>{"use strict";f();Hr=require("stream/consumers");Ht();Ni();ki();Nr();Ye();ji();oe();Ct();Gi();Ji()});var ho={};Ee(ho,{registerUtilityRoutes:()=>bl});function bl(e,t,r){e.on("POST","/database/dump",K(async(n,s)=>{await t.db.dump(t.databaseDumpPath),L(s,{dumpPath:t.databaseDumpPath},201)},r)),e.on("GET","/health",K((n,s)=>{L(s,{name:t.name})},r))}var go=O(()=>{"use strict";f();oe();Ct()});var tu={};Ee(tu,{DEFAULT_DATABASE_PORT:()=>rt,DEFAULT_SERVER_PORT:()=>nt,DEFAULT_SHADOW_DATABASE_PORT:()=>st,DEFAULT_STREAMS_PORT:()=>it,PortNotAvailableError:()=>V,ServerAlreadyRunningError:()=>ze,copyPrismaDevRuntimeAssets:()=>kn,getPrismaDevRuntimeAssetManifest:()=>Zt,startPrismaDevServer:()=>No,unstable_startServer:()=>eu});module.exports=Ho(tu);f();f();Ht();f();var dt=require("net"),Jn=require("path"),Yn=require("pathe/utils");Te();Be();f();var Jt=require("perf_hooks"),On=require("@electric-sql/pglite");f();var En=require("buffer"),bn=500,Pn=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,ea=new RegExp(`(?:${Pn.source}\\.)*${Pn.source}`),ta=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${ea.source})`,"gi"),ra=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,wn=/prismaQuery='([^']+)'/,na=new Set([de(`
14
36
  select b.oid, b.typarray
15
37
  from pg_catalog.pg_type a
16
38
  left join pg_catalog.pg_type b on b.oid = a.typelem
17
39
  where a.typcategory = $1
18
40
  group by b.oid, b.typarray
19
41
  order by b.oid
20
- `),$('GRANT "pg_write_all_data" TO "prisma_application"'),$("SELECT SUM(reads)::BIGINT AS reads, SUM(writes)::BIGINT AS writes, SUM(COALESCE(extends, $1))::BIGINT AS extends FROM pg_stat_io"),$("SELECT pg_database_size(current_database())::BIGINT, SUM(pg_total_relation_size(relid))::BIGINT AS pg_total_relation_size FROM pg_stat_user_tables"),$("SELECT COUNT(*) AS cnt FROM pg_stat_activity WHERE pid <> pg_backend_pid() and xact_start notnull")]),rs=[/^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 Jt(){return{generatedAt:Date.now(),queries:[]}}function $(e){return e.replace(/\s+/g," ").trim()}function Yt(e){return rr($(e))}function Xt(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?rr(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function ns(e){let t=new Set;for(let r of e.matchAll(Zn)){let n=r[1];if(!n)continue;let s;for(let o of n.matchAll(es))s=o[1]??o[2]??o[3]??o[4];s&&!s.startsWith("pg_")&&t.add(s)}return Array.from(t)}function ss(e){return ts.has(e)?!0:rs.some(t=>t.test(e))}function Zt(e){if(ss($(e)))return null;let t=ns(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function Fe(e){if(Array.isArray(e))return e.map(Fe);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Fe(n)]))}return e}function er(e){let t=e.match(Vt);if(!t?.[1])return{cleanedSql:$(e),prismaQueryInfo:null};let r=e.replace(Vt,"");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=Fe(JSON.parse(zt.Buffer.from(a,"base64url").toString("utf8")))}catch{l=void 0}return{cleanedSql:r,prismaQueryInfo:{action:u,isRaw:!1,model:c,payload:l}}}function tr(e,t={}){let r=new Set(t.excludeApplications??[]),n=os(t.limit),s=typeof t.since=="number"&&Number.isFinite(t.since)?t.since:null,o=new Map;for(let i of e){if(i.applicationName&&r.has(i.applicationName))continue;let c=Date.parse(i.timestamp);if(!Number.isFinite(c))continue;let 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 os(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,jt):jt}function rr(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)&4294967295;return(t>>>0).toString(36)}var Se=new WeakMap;function sr(e){let t=Se.get(e);if(t&&!t.closed)return t.bridge;let r=as(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,Se.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=is(n,s),c=ls(o);cs(i,c);let u=us(i,c);if(!u)return await n.originalEnqueue(s,o,a);let l={commandTags:[],dataRowCount:0},h=new nr.protocol.Parser,d=We.performance.now(),m=await n.originalEnqueue(s,o,E=>{h.parse(E,J=>{ys(l,J)}),a(E)}),f=Math.max(0,We.performance.now()-d);return bs(n,{applicationName:u.applicationName,durationMs:f,query:u.query,responseStats:l}),m},Se.set(e,n),n.bridge}async function or(e){await Se.get(e)?.bridge.close()}function as(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 is(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 cs(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 us(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 ls(e){let t=Buffer.from(e);if(t.length<4)return null;let r=t.readInt32BE(0);if(t.length>=8&&r===t.length){let s=t.readInt32BE(4);if(s===196608||s===196608)return ds(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return ms(t);case"P":return ps(t);case"B":return gs(t);case"E":return fs(t);case"C":return hs(t);default:return null}}function ds(e){let t=8,r=null;for(;t<e.length-1;){let n=B(e,t);if(!n||n.value==="")break;t=n.nextOffset;let s=B(e,t);if(!s)break;t=s.nextOffset,n.value==="application_name"&&(r=s.value)}return{applicationName:r,kind:"startup"}}function ms(e){let t=B(e,5);return t?{kind:"query",query:t.value}:null}function ps(e){let t=B(e,5);if(!t)return null;let r=B(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function gs(e){let t=B(e,5);if(!t)return null;let r=B(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function fs(e){let t=B(e,5);return t?{kind:"execute",portalName:t.value}:null}function hs(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=B(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function B(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function ys(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 bs(e,t){let r=er(t.query),n=Zt(r.cleanedSql);if(!n)return;let s=Yt(r.cleanedSql),o={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:Xt(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:s,reads:0,rowsReturned:Ss(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let a of e.subscribers)a([o])}function Ss(e){let t=e.commandTags.reduce((r,n)=>r+Ps(n),0);return Math.max(t,e.dataRowCount)}function Ps(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}p();var k=require("fs"),A=require("fs/promises"),ir=require("module"),cr=require("path"),D=require("url"),ws=(0,ir.createRequire)(y),Es=["initdb.wasm","pglite.data","pglite.wasm"],Ge="pglite-seed.tar.gz",ur={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"},lr=[...Es.map(e=>({fileName:e,kind:"core",name:e})),{fileName:Ge,kind:"core",name:Ge},...Object.entries(ur).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],we=new Map,vs=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),Pe=null;async function dr(e){let t=K(e),r=(0,D.fileURLToPath)(t);await(0,A.mkdir)(r,{recursive:!0});let n=[];for(let s of je()){let o=new URL(s.fileName,t),a=(0,D.fileURLToPath)(o);await(0,A.copyFile)(s.sourcePath,a),n.push({...s,destinationPath:a})}return n}function je(){let e=mr(),t=K(new URL("./runtime-assets/",y));return lr.map(r=>({...r,sourcePath:(0,D.fileURLToPath)(Z(r.fileName,e,t))}))}async function Ke(){await As();let e=pr();if(e)return await Is(e),await Rs(e);let t=Ds(),r=t.href,n=we.get(r);return n||(n=xs(t),we.set(r,n)),await n}async function Rs(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=we.get(t);return r||(r=Ts(e),we.set(t,r)),await r}async function xs(e){let t=K(new URL("./runtime-assets/",y)),[r,n,s]=await Promise.all([(0,A.readFile)(Z("pglite.data",e,t)),(0,A.readFile)(Z(Ge,e,t)),(0,A.readFile)(Z("pglite.wasm",e,t))]),o=gr();return{extensions:Object.fromEntries(Object.entries(ur).map(([a,i])=>[a,Z(i,e,t)])),fsBundle:new Blob([Uint8Array.from(r)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await o.compile(s)}}async function Ts(e){let[t,r,n]=await Promise.all([He(e.fsBundle),He(e.loadDataDir),He(e.wasmModule)]),s=gr();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(r)]),wasmModule:await s.compile(n)}}async function Is(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",K(new URL("./",e.initdbWasm))),r=(0,D.fileURLToPath)(t);(0,k.existsSync)(r)||await(0,A.copyFile)((0,D.fileURLToPath)(e.initdbWasm),r)}function K(e){return e instanceof URL?ar(e):ar((0,D.pathToFileURL)(e))}function ar(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function mr(){let e=ws.resolve("@electric-sql/pglite");return K((0,cr.dirname)(e))}function Ds(){let e=K(new URL("./",y));if(_s(e))return e;if(Os())return mr();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function _s(e){return lr.every(t=>(0,k.existsSync)((0,D.fileURLToPath)(new URL(t.fileName,e))))}function pr(){return globalThis[vs]??null}async function As(){!Ns()||pr()||(Pe||(Pe=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw Pe=null,e})),await Pe)}function Os(){let e=(0,D.fileURLToPath)(new URL("../package.json",y));if(!(0,k.existsSync)(e))return!1;try{return JSON.parse((0,k.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function Ns(){return typeof globalThis.Bun<"u"}function gr(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function He(e){if(e.protocol==="file:")return await(0,A.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 Z(e,t,r){let n=new URL(e,t);if((0,k.existsSync)((0,D.fileURLToPath)(n)))return n;if(r){let s=new URL(e,r);if((0,k.existsSync)((0,D.fileURLToPath)(s)))return s}return n}p();var Je=require("@electric-sql/pglite"),O="_prisma_dev_wal",ze="events",yr="install_all_triggers",fr="capture_event",hr="prisma_dev_wal_capture",ee=new WeakMap,Bs=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function Ye(e,t){let r=ee.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,ee.delete(e))},poll:async()=>{await Ve(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&&Sr(l)&&Ve(o,e),l},i=async(c,u)=>{let l=[],h=new Je.protocol.Parser,d=u?.onRawData;await s(c,{...u,onRawData:m=>{h.parse(m,f=>{l.push(f)}),d?.(m)}}),!o.closed&&o.suppressDepth===0&&Xe(l)&&Ve(o,e)};return e.execProtocolRaw=a,e.execProtocolRawStream=i,ee.set(e,o),await Pr(o,e),o.bridge}async function br(e){let t=ee.get(e);t&&await t.bridge.close()}function Xe(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&&Bs.has(r))return!0}return!1}function Sr(e){if(e.length===0)return!1;let t=[];return new Je.protocol.Parser().parse(e,n=>{t.push(n)}),Xe(t)}async function Pr(e,t){e.ensureInfrastructurePromise??=Ze(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${O}"`),await t.exec(`
21
- CREATE TABLE IF NOT EXISTS "${O}"."${ze}" (
42
+ `),de('GRANT "pg_write_all_data" TO "prisma_application"'),de("SELECT SUM(reads)::BIGINT AS reads, SUM(writes)::BIGINT AS writes, SUM(COALESCE(extends, $1))::BIGINT AS extends FROM pg_stat_io"),de("SELECT pg_database_size(current_database())::BIGINT, SUM(pg_total_relation_size(relid))::BIGINT AS pg_total_relation_size FROM pg_stat_user_tables"),de("SELECT COUNT(*) AS cnt FROM pg_stat_activity WHERE pid <> pg_backend_pid() and xact_start notnull")]),sa=[/^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 vn(){return{generatedAt:Date.now(),queries:[]}}function de(e){return e.replace(/\s+/g," ").trim()}function Rn(e){return _n(de(e))}function xn(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?_n(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function ia(e){let t=new Set;for(let r of e.matchAll(ta)){let n=r[1];if(!n)continue;let s;for(let i of n.matchAll(ra))s=i[1]??i[2]??i[3]??i[4];s&&!s.startsWith("pg_")&&t.add(s)}return Array.from(t)}function oa(e){return na.has(e)?!0:sa.some(t=>t.test(e))}function Tn(e){if(oa(de(e)))return null;let t=ia(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function Kt(e){if(Array.isArray(e))return e.map(Kt);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Kt(n)]))}return e}function An(e){let t=e.match(wn);if(!t?.[1])return{cleanedSql:de(e),prismaQueryInfo:null};let r=e.replace(wn,"");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 i=n.slice(0,s),o=n.slice(s+1),a=i.indexOf("."),c=a===-1?void 0:i.slice(0,a),u=a===-1?i:i.slice(a+1);if(!u)return{cleanedSql:r,prismaQueryInfo:null};let l;try{l=Kt(JSON.parse(En.Buffer.from(o,"base64url").toString("utf8")))}catch{l=void 0}return{cleanedSql:r,prismaQueryInfo:{action:u,isRaw:!1,model:c,payload:l}}}function In(e,t={}){let r=new Set(t.excludeApplications??[]),n=aa(t.limit),s=typeof t.since=="number"&&Number.isFinite(t.since)?t.since:null,i=new Map;for(let a of e){if(a.applicationName&&r.has(a.applicationName))continue;let c=Date.parse(a.timestamp);if(!Number.isFinite(c))continue;let u=`${a.queryId}:${a.groupKey??""}`,l=i.get(u);if(!l){i.set(u,{count:1,duration:a.durationMs,groupKey:a.groupKey,id:u,lastSeen:c,maxDurationMs:a.durationMs,minDurationMs:a.durationMs,prismaQueryInfo:a.prismaQueryInfo,query:a.query,queryId:a.queryId,reads:a.reads,rowsReturned:a.rowsReturned,tables:a.tables,totalDurationMs:a.durationMs});continue}l.count+=1,l.lastSeen=Math.max(l.lastSeen,c),l.maxDurationMs=Math.max(l.maxDurationMs??a.durationMs,a.durationMs),l.minDurationMs=Math.min(l.minDurationMs??a.durationMs,a.durationMs),l.reads+=a.reads,l.rowsReturned+=a.rowsReturned,l.totalDurationMs+=a.durationMs,l.duration=l.totalDurationMs/l.count,!l.prismaQueryInfo&&a.prismaQueryInfo&&(l.prismaQueryInfo=a.prismaQueryInfo),l.tables.length===0&&a.tables.length>0&&(l.tables=a.tables)}let o=Array.from(i.values()).filter(a=>s===null||a.lastSeen>=s).sort((a,c)=>c.lastSeen-a.lastSeen).slice(0,n).map(({totalDurationMs:a,...c})=>c);return{generatedAt:Date.now(),queries:o}}function aa(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,bn):bn}function _n(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 at=new WeakMap;function Dn(e){let t=at.get(e);if(t&&!t.closed)return t.bridge;let r=ca(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,at.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,i,o)=>{let a=la(n,s),c=fa(i);ua(a,c);let u=da(a,c);if(!u)return await n.originalEnqueue(s,i,o);let l={commandTags:[],dataRowCount:0},m=new On.protocol.Parser,d=Jt.performance.now(),p=await n.originalEnqueue(s,i,b=>{m.parse(b,S=>{ba(l,S)}),o(b)}),y=Math.max(0,Jt.performance.now()-d);return Pa(n,{applicationName:u.applicationName,durationMs:y,query:u.query,responseStats:l}),p},at.set(e,n),n.bridge}async function Cn(e){await at.get(e)?.bridge.close()}function ca(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 la(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 ua(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 da(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 fa(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 ma(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return pa(t);case"P":return ha(t);case"B":return ga(t);case"E":return ya(t);case"C":return Sa(t);default:return null}}function ma(e){let t=8,r=null;for(;t<e.length-1;){let n=ne(e,t);if(!n||n.value==="")break;t=n.nextOffset;let s=ne(e,t);if(!s)break;t=s.nextOffset,n.value==="application_name"&&(r=s.value)}return{applicationName:r,kind:"startup"}}function pa(e){let t=ne(e,5);return t?{kind:"query",query:t.value}:null}function ha(e){let t=ne(e,5);if(!t)return null;let r=ne(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function ga(e){let t=ne(e,5);if(!t)return null;let r=ne(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function ya(e){let t=ne(e,5);return t?{kind:"execute",portalName:t.value}:null}function Sa(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=ne(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function ne(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function ba(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 Pa(e,t){let r=An(t.query),n=Tn(r.cleanedSql);if(!n)return;let s=Rn(r.cleanedSql),i={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:xn(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:s,reads:0,rowsReturned:wa(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let o of e.subscribers)o([i])}function wa(e){let t=e.commandTags.reduce((r,n)=>r+Ea(n),0);return Math.max(t,e.dataRowCount)}function Ea(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}f();var fe=require("fs"),J=require("fs/promises"),Mn=require("module"),$n=require("path"),Q=require("url"),va=(0,Mn.createRequire)(h),Ra=["initdb.wasm","pglite.data","pglite.wasm"],Xt="pglite-seed.tar.gz",Ln={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"},Bn=[...Ra.map(e=>({fileName:e,kind:"core",name:e})),{fileName:Xt,kind:"core",name:Xt},...Object.entries(Ln).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],lt=new Map,xa=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),ct=null;async function kn(e){let t=Ae(e),r=(0,Q.fileURLToPath)(t);await(0,J.mkdir)(r,{recursive:!0});let n=[];for(let s of Zt()){let i=new URL(s.fileName,t),o=(0,Q.fileURLToPath)(i);await(0,J.copyFile)(s.sourcePath,o),n.push({...s,destinationPath:o})}return n}function Zt(){let e=Un(),t=Ae(new URL("./runtime-assets/",h));return Bn.map(r=>({...r,sourcePath:(0,Q.fileURLToPath)(ke(r.fileName,e,t))}))}async function er(){await Ca();let e=Hn();if(e)return await _a(e),await Ta(e);let t=Oa(),r=t.href,n=lt.get(r);return n||(n=Aa(t),lt.set(r,n)),await n}async function Ta(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,r=lt.get(t);return r||(r=Ia(e),lt.set(t,r)),await r}async function Aa(e){let t=Ae(new URL("./runtime-assets/",h)),[r,n,s]=await Promise.all([(0,J.readFile)(ke("pglite.data",e,t)),(0,J.readFile)(ke(Xt,e,t)),(0,J.readFile)(ke("pglite.wasm",e,t))]),i=qn();return{extensions:Object.fromEntries(Object.entries(Ln).map(([o,a])=>[o,ke(a,e,t)])),fsBundle:new Blob([Uint8Array.from(r)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await i.compile(s)}}async function Ia(e){let[t,r,n]=await Promise.all([Yt(e.fsBundle),Yt(e.loadDataDir),Yt(e.wasmModule)]),s=qn();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(r)]),wasmModule:await s.compile(n)}}async function _a(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",Ae(new URL("./",e.initdbWasm))),r=(0,Q.fileURLToPath)(t);(0,fe.existsSync)(r)||await(0,J.copyFile)((0,Q.fileURLToPath)(e.initdbWasm),r)}function Ae(e){return e instanceof URL?Nn(e):Nn((0,Q.pathToFileURL)(e))}function Nn(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function Un(){let e=va.resolve("@electric-sql/pglite");return Ae((0,$n.dirname)(e))}function Oa(){let e=Ae(new URL("./",h));if(Da(e))return e;if(Na())return Un();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function Da(e){return Bn.every(t=>(0,fe.existsSync)((0,Q.fileURLToPath)(new URL(t.fileName,e))))}function Hn(){return globalThis[xa]??null}async function Ca(){!Ma()||Hn()||(ct||(ct=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw ct=null,e})),await ct)}function Na(){let e=(0,Q.fileURLToPath)(new URL("../package.json",h));if(!(0,fe.existsSync)(e))return!1;try{return JSON.parse((0,fe.readFileSync)(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function Ma(){return typeof globalThis.Bun<"u"}function qn(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function Yt(e){if(e.protocol==="file:")return await(0,J.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 ke(e,t,r){let n=new URL(e,t);if((0,fe.existsSync)((0,Q.fileURLToPath)(n)))return n;if(r){let s=new URL(e,r);if((0,fe.existsSync)((0,Q.fileURLToPath)(s)))return s}return n}f();var nr=require("@electric-sql/pglite"),Y="_prisma_dev_wal",rr="events",Fn="install_all_triggers",jn="capture_event",Qn="prisma_dev_wal_capture",Ue=new WeakMap,$a=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function sr(e,t){let r=Ue.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),s=e.execProtocolRawStream.bind(e),i={bridge:{close:async()=>{i.closed||(i.closed=!0,i.subscribers.clear(),e.execProtocolRaw===o&&(e.execProtocolRaw=n),e.execProtocolRawStream===a&&(e.execProtocolRawStream=s),await i.pollPromise,Ue.delete(e))},poll:async()=>{await tr(i,e)},subscribe:c=>(i.subscribers.add(c),()=>{i.subscribers.delete(c)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},o=async(c,u)=>{let l=await n(c,u);return!i.closed&&i.suppressDepth===0&&Gn(l)&&tr(i,e),l},a=async(c,u)=>{let l=[],m=new nr.protocol.Parser,d=u?.onRawData;await s(c,{...u,onRawData:p=>{m.parse(p,y=>{l.push(y)}),d?.(p)}}),!i.closed&&i.suppressDepth===0&&ir(l)&&tr(i,e)};return e.execProtocolRaw=o,e.execProtocolRawStream=a,Ue.set(e,i),await zn(i,e),i.bridge}async function Wn(e){let t=Ue.get(e);t&&await t.bridge.close()}function ir(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&&$a.has(r))return!0}return!1}function Gn(e){if(e.length===0)return!1;let t=[];return new nr.protocol.Parser().parse(e,n=>{t.push(n)}),ir(t)}async function zn(e,t){e.ensureInfrastructurePromise??=or(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${Y}"`),await t.exec(`
43
+ CREATE TABLE IF NOT EXISTS "${Y}"."${rr}" (
22
44
  id BIGSERIAL PRIMARY KEY,
23
45
  txid BIGINT NOT NULL DEFAULT txid_current(),
24
46
  schema_name TEXT NOT NULL,
@@ -29,16 +51,16 @@ Received data: ${l}`));n({childProcess:a,url:`http://${m}:${f}`})},c=l=>{this.#t
29
51
  created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
30
52
  )
31
53
  `),await t.exec(`
32
- CREATE OR REPLACE FUNCTION "${O}"."${fr}"()
54
+ CREATE OR REPLACE FUNCTION "${Y}"."${jn}"()
33
55
  RETURNS trigger
34
56
  LANGUAGE plpgsql
35
57
  AS $$
36
58
  BEGIN
37
- IF TG_TABLE_SCHEMA = '${O}' THEN
59
+ IF TG_TABLE_SCHEMA = '${Y}' THEN
38
60
  RETURN COALESCE(NEW, OLD);
39
61
  END IF;
40
62
 
41
- INSERT INTO "${O}"."${ze}" (
63
+ INSERT INTO "${Y}"."${rr}" (
42
64
  txid,
43
65
  schema_name,
44
66
  table_name,
@@ -59,7 +81,7 @@ Received data: ${l}`));n({childProcess:a,url:`http://${m}:${f}`})},c=l=>{this.#t
59
81
  END;
60
82
  $$;
61
83
  `),await t.exec(`
62
- CREATE OR REPLACE FUNCTION "${O}"."${yr}"()
84
+ CREATE OR REPLACE FUNCTION "${Y}"."${Fn}"()
63
85
  RETURNS void
64
86
  LANGUAGE plpgsql
65
87
  AS $$
@@ -71,7 +93,7 @@ Received data: ${l}`));n({childProcess:a,url:`http://${m}:${f}`})},c=l=>{this.#t
71
93
  FROM pg_class AS c
72
94
  JOIN pg_namespace AS n ON n.oid = c.relnamespace
73
95
  WHERE c.relkind IN ('r', 'p')
74
- AND n.nspname NOT IN ('${O}', 'information_schema', 'pg_catalog')
96
+ AND n.nspname NOT IN ('${Y}', 'information_schema', 'pg_catalog')
75
97
  AND n.nspname NOT LIKE 'pg_temp_%'
76
98
  AND n.nspname NOT LIKE 'pg_toast%'
77
99
  LOOP
@@ -79,28 +101,28 @@ Received data: ${l}`));n({childProcess:a,url:`http://${m}:${f}`})},c=l=>{this.#t
79
101
  SELECT 1
80
102
  FROM pg_trigger
81
103
  WHERE tgrelid = target
82
- AND tgname = '${hr}'
104
+ AND tgname = '${Qn}'
83
105
  ) THEN
84
106
  CONTINUE;
85
107
  END IF;
86
108
 
87
109
  EXECUTE format(
88
- 'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${O}"."${fr}"()',
89
- '${hr}',
110
+ 'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${Y}"."${jn}"()',
111
+ '${Qn}',
90
112
  target::text
91
113
  );
92
114
  END LOOP;
93
115
  END;
94
116
  $$;
95
- `),await wr(e,t)}),await e.ensureInfrastructurePromise}async function wr(e,t){await Ze(e,t,async()=>{await t.query(`SELECT "${O}"."${yr}"()`)})}async function Ms(e,t){await Pr(e,t),await wr(e,t);let r=await Ze(e,t,async()=>await t.query(`
117
+ `),await Vn(e,t)}),await e.ensureInfrastructurePromise}async function Vn(e,t){await or(e,t,async()=>{await t.query(`SELECT "${Y}"."${Fn}"()`)})}async function La(e,t){await zn(e,t),await Vn(e,t);let r=await or(e,t,async()=>await t.query(`
96
118
  WITH drained AS (
97
- DELETE FROM "${O}"."${ze}"
119
+ DELETE FROM "${Y}"."${rr}"
98
120
  RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id
99
121
  )
100
122
  SELECT txid, schema_name, table_name, op, row_data, old_row_data
101
123
  FROM drained
102
124
  ORDER BY id
103
- `));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(Ls);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 Ve(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await Ms(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function Ze(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&ee.get(t)!==e&&(e.closed=!0)}}function Ls(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:$s(e.op)}}function $s(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 ks=10,xr="127.0.0.1",Tr=128*1024*1024,Ir=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],b={connectionLimit:ks,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Cs=`postgres://${b.username}:${b.password}@localhost`,et=new URLSearchParams({sslmode:b.sslMode}),Dr=new URLSearchParams({...Object.fromEntries(et.entries()),connection_limit:String(b.connectionLimit),connect_timeout:String(b.connectTimeout),max_idle_connection_lifetime:String(b.maxIdleConnectionLifetime),pool_timeout:String(b.poolTimeout),socket_timeout:String(b.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 ${b.username} WITH LOGIN SUPERUSER PASSWORD '${b.password}'`):await e.exec(`CREATE ROLE ${b.username} WITH LOGIN SUPERUSER PASSWORD '${b.password}'`),await e.exec(`SET ROLE ${b.username}`)}async function tt(e,t){if(e==="shadow_database"&&!t.dryRun)return await Us(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?Or(e,t,{db:null,port:r,server:null}):await Ar(e,t,{port:r,updateServerStatePort:!0})}async function Us(e,t=async()=>await Ar("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,s=null,o=!1,a=new Set,i=(0,ve.createServer)(u),c=await Qs(i,e.shadowDatabasePort);return e.shadowDatabasePort=c,r&&console.debug(`[shadow_database] lazy proxy listening on port ${c}`),{...b,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 m of a)m.destroy();a.clear();let d=[];try{await qs(i),r&&console.debug(`[shadow_database] lazy proxy stopped on port ${c}`)}catch(m){console.error("[shadow_database] lazy proxy stop error",m),d.push(m)}try{await s?.catch(()=>null),await n?.close()}catch(m){console.error("[shadow_database] backend close error",m),d.push(m)}if(d.length>0)throw new AggregateError(d,"Failed to close shadow_database properly")},connectionString:Ee(c,et),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:c,prismaORMConnectionString:Ee(c,Dr),terminalCommand:`PGPASSWORD=${b.password} PGSSLMODE=${b.sslMode} psql -h localhost -p ${c} -U ${b.username} -d ${b.database}`};function u(d){a.add(d);let m=()=>{a.delete(d)};d.once("close",m),d.once("error",m),d.pause(),l(d)}async function l(d){try{let m=await h();if(o){d.destroy();return}let f=(0,ve.createConnection)({host:xr,port:m.port});a.add(f);let E=()=>{a.delete(f)};f.once("close",E),f.once("error",E),d.once("close",()=>f.destroy()),d.once("error",()=>f.destroy()),f.once("error",()=>d.destroy()),f.once("connect",()=>{r&&console.debug(`[shadow_database] proxying connection to lazy backend on port ${m.port}`),d.resume(),d.pipe(f),f.pipe(d)})}catch(m){r&&console.error("[shadow_database] failed to start lazy backend",m),d.destroy(m instanceof Error?m:void 0)}}async function h(){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 Ar(e,t,r){let{debug:n}=t,{port:s,updateServerStatePort:o}=r,i=await(e==="shadow_database"?Fs:Nr)(t.pgliteDataDirPath,n);n&&i.onNotification((d,m)=>{console.debug(`[${e}][${d}] ${m}`)});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:b.connectionLimit,port:s});n&&(l.addEventListener("listening",d=>{let{detail:m}=d;console.debug(`[${e}] server listening on ${JSON.stringify(m)}`)}),l.addEventListener("connection",d=>{let{clientAddress:m,clientPort:f}=d.detail;console.debug(`[${e}] client connected from ${m}:${f}`)}),l.addEventListener("error",d=>{let{detail:m}=d;console.error(`[${e}] server error:`,m)}));try{await l.start()}catch(d){throw d instanceof Error&&"code"in d&&d.code==="EADDRINUSE"?new _(s):d}let h=Number(l.getServerConn().split(":").at(1));return o&&(t[e==="database"?"databasePort":"shadowDatabasePort"]=h),Or(e,t,{db:i,port:h,server:l})}function Or(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}`),{...b,attachWalEventBridge:async()=>{if(e!=="database"||!s)throw new Error("WAL bridge is only available for the primary database server");return await Ye(s)},attachQueryInsightsBridge:()=>{if(e!=="database"||!a)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(sr(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 or(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 br(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:Ee(o,et),dump:async c=>{e==="shadow_database"||!s||await Hs({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}`,h=i.get(l);return h||(h=Ws(s,c,u).catch(d=>{throw i.delete(l),d}),i.set(l,h)),await h},port:o,prismaORMConnectionString:Ee(o,Dr),terminalCommand:`PGPASSWORD=${b.password} PGSSLMODE=${b.sslMode} psql -h localhost -p ${o} -U ${b.username} -d ${b.database}`}}function Ee(e,t){return`${Cs}:${e}/${b.database}?${t.toString()}`}async function Nr(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await Ke(),s=e==="memory://"||!await H((0,vr.join)(e,"PG_VERSION")),o=await r.create({database:b.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Tr,loadDataDir:s?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...Ir],wasmModule:n.wasmModule});return await _r(o),o}async function Qs(e,t){return await new Promise((r,n)=>{let s=i=>{if(a(),i.code==="EADDRINUSE"){n(new _(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,xr)})}async function qs(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 Fs(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await Ke(),s=await r.create({database:b.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Tr,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...Ir],wasmModule:n.wasmModule});return await _r(s),s}async function Ws(e,t,r){let{rows:n}=await e.query(`
125
+ `));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map(Ba);for(let s of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(s))try{s(n)}catch(i){console.error("[WAL bridge] subscriber failed",i)}})}async function tr(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await La(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function or(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&Ue.get(t)!==e&&(e.closed=!0)}}function Ba(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:ka(e.op)}}function ka(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 Ua=10,Xn="127.0.0.1",Zn=128*1024*1024,es=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],v={connectionLimit:Ua,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Ha=`postgres://${v.username}:${v.password}@localhost`,ar=new URLSearchParams({sslmode:v.sslMode}),ts=new URLSearchParams({...Object.fromEntries(ar.entries()),connection_limit:String(v.connectionLimit),connect_timeout:String(v.connectTimeout),max_idle_connection_lifetime:String(v.maxIdleConnectionLifetime),pool_timeout:String(v.poolTimeout),socket_timeout:String(v.socketTimeout)});async function rs(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 ${v.username} WITH LOGIN SUPERUSER PASSWORD '${v.password}'`):await e.exec(`CREATE ROLE ${v.username} WITH LOGIN SUPERUSER PASSWORD '${v.password}'`),await e.exec(`SET ROLE ${v.username}`)}async function cr(e,t){if(e==="shadow_database"&&!t.dryRun)return await qa(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?ss(e,t,{db:null,port:r,server:null}):await ns(e,t,{port:r,updateServerStatePort:!0})}async function qa(e,t=async()=>await ns("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,s=null,i=!1,o=new Set,a=(0,dt.createServer)(u),c=await ja(a,e.shadowDatabasePort);return e.shadowDatabasePort=c,r&&console.debug(`[shadow_database] lazy proxy listening on port ${c}`),{...v,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()=>{i=!0;for(let p of o)p.destroy();o.clear();let d=[];try{await Qa(a),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:ut(c,ar),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:c,prismaORMConnectionString:ut(c,ts),terminalCommand:`PGPASSWORD=${v.password} PGSSLMODE=${v.sslMode} psql -h localhost -p ${c} -U ${v.username} -d ${v.database}`};function u(d){o.add(d);let p=()=>{o.delete(d)};d.once("close",p),d.once("error",p),d.pause(),l(d)}async function l(d){try{let p=await m();if(i){d.destroy();return}let y=(0,dt.createConnection)({host:Xn,port:p.port});o.add(y);let b=()=>{o.delete(y)};y.once("close",b),y.once("error",b),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 m(){if(n)return n;if(i)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 ns(e,t,r){let{debug:n}=t,{port:s,updateServerStatePort:i}=r,a=await(e==="shadow_database"?Fa:is)(t.pgliteDataDirPath,n);n&&a.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:a,debug:n,idleTimeout:Number.isFinite(u)?u:0,inspect:n,maxConnections:v.connectionLimit,port:s});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 V(s):d}let m=Number(l.getServerConn().split(":").at(1));return i&&(t[e==="database"?"databasePort":"shadowDatabasePort"]=m),ss(e,t,{db:a,port:m,server:l})}function ss(e,t,r){let{debug:n}=t,{db:s,port:i,server:o}=r||{},a=new Map;return n&&console.debug(`[${e}] server started on port ${i}`),{...v,attachWalEventBridge:async()=>{if(e!=="database"||!s)throw new Error("WAL bridge is only available for the primary database server");return await sr(s)},attachQueryInsightsBridge:()=>{if(e!=="database"||!o)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(Dn(o))},close:async()=>{let c=[];try{await o?.stop(),n&&console.debug(`[${e}] server stopped on port ${i}`)}catch(u){console.error(`[${e}] server stop error`,u),c.push(u)}if(e==="database"){try{o&&await Cn(o),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 Wn(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:ut(i,ar),dump:async c=>{e==="shadow_database"||!s||await Ga({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}`,m=a.get(l);return m||(m=Wa(s,c,u).catch(d=>{throw a.delete(l),d}),a.set(l,m)),await m},port:i,prismaORMConnectionString:ut(i,ts),terminalCommand:`PGPASSWORD=${v.password} PGSSLMODE=${v.sslMode} psql -h localhost -p ${i} -U ${v.username} -d ${v.database}`}}function ut(e,t){return`${Ha}:${e}/${v.database}?${t.toString()}`}async function is(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await er(),s=e==="memory://"||!await Re((0,Jn.join)(e,"PG_VERSION")),i=await r.create({database:v.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Zn,loadDataDir:s?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...es],wasmModule:n.wasmModule});return await rs(i),i}async function ja(e,t){return await new Promise((r,n)=>{let s=a=>{if(o(),a.code==="EADDRINUSE"){n(new V(t));return}n(a)},i=()=>{let a=e.address();if(o(),!a||typeof a=="string"){n(new Error("Failed to determine TCP server port"));return}r(a.port)},o=()=>{e.off("error",s),e.off("listening",i)};e.once("error",s),e.once("listening",i),e.listen(t,Xn)})}async function Qa(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 Fa(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await er(),s=await r.create({database:v.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:Zn,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...es],wasmModule:n.wasmModule});return await rs(s),s}async function Wa(e,t,r){let{rows:n}=await e.query(`
104
126
  SELECT attribute.attname AS column_name
105
127
  FROM pg_constraint pk_constraint
106
128
  INNER JOIN pg_class relation
@@ -113,9 +135,9 @@ Received data: ${l}`));n({childProcess:a,url:`http://${m}:${f}`})},c=l=>{this.#t
113
135
  ON attribute.attrelid = relation.oid
114
136
  AND attribute.attnum = keys.attnum
115
137
  WHERE pk_constraint.contype = 'p'
116
- AND namespace.nspname = ${Er(t)}
117
- AND relation.relname = ${Er(r)}
138
+ AND namespace.nspname = ${Kn(t)}
139
+ AND relation.relname = ${Kn(r)}
118
140
  ORDER BY keys.ordinality
119
- `);return n.map(s=>s.column_name)}function Er(e){return`'${e.replaceAll("'","''")}'`}async function Hs(e){let{dataDir:t,db:r,debug:n,destinationPath:s}=e,o=r||await Nr(t,n),{pgDump:a}=await import("@electric-sql/pglite-tools/pg_dump"),i=await a({args:["--schema-only","--no-owner"],fileName:s?(0,Rr.filename)(s):void 0,pg:await o.clone()});return s?(n&&console.debug(`[DB] Dumping database to ${s}`),await Ft(i,s)):(n&&console.debug("[DB] Dumping database to memory"),await i.text())}p();var pn=require("http"),gn=require("util");rt();async function fn(e,t){let{port:r}=t;if(t.dryRun)return mn(r,null);let n=await fo(e,t),{promise:s,reject:o,resolve:a}=Re(),{serve:i}=await import("@hono/node-server"),c=i({createServer:pn.createServer,fetch:n.fetch,overrideGlobalObjects:!1,port:r},a);c.on("error",l=>{if(typeof l=="object"&&"code"in l&&l.code==="EADDRINUSE")return o(new _(r));console.error("[Accelerate]",l)});let{port:u}=await s;return t.port=u,mn(u,c)}function mn(e,t){return{async close(){if(!t)return;let{Engine:r}=await Promise.resolve().then(()=>(ot(),st));await Promise.allSettled([(0,gn.promisify)(t.close.bind(t))(),r.stopAll()])},port:e,url:`http://localhost:${e}`}}async function fo(e,t){let{debug:r}=t,[{Hono:n},{accelerateRoute:s},{utilityRoute:o}]=await Promise.all([import("hono/tiny"),Promise.resolve().then(()=>(an(),on)),Promise.resolve().then(()=>(dn(),ln))]),a=new n;if(r){let{logger:c}=await import("hono/logger");a.use("*",c((...u)=>console.log("[Accelerate]",...u)))}a.use("*",async(c,u)=>(c.set("databaseDumpPath",t.databaseDumpPath),c.set("db",e),c.set("debug",!!r),c.set("name",t.name),c.set("shadowDBPort",t.shadowDatabasePort),await u()));let i=new n;return i.route("/",s),i.route("/",o),a.route("/",i),a}p();var St=require("util");p();var ft=require("pathe");j();var ht="prisma-wal",yt="prisma-queries";function bt(){return(0,ft.join)(me.data,"durable-streams")}function De(e){return(0,ft.join)(bt(),e)}function _e(e,t=ht){return new URL(`/v1/stream/${encodeURIComponent(t)}`,e).toString()}var ho="application/json",Ae={connection:"close","content-type":ho},Pt={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 hn(e){return{...e,snapshot:async t=>await yo(e.url,t)}}async function yn(e){let t={serverUrl:e.serverUrl,sqlitePath:e.sqlitePath,streamName:yt,url:_e(e.serverUrl,yt)};await So(t);let r=new wt({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 yo(e,t){if(!e)return Jt();let r=await bo(e);return tr(r,t)}async function bo(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 wt=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 Eo(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 So(e){let t=await fetch(e.url,{headers:Ae,method:"PUT"});if(!t.ok)throw await Oe(t,`Failed to create ${e.streamName}`);let r=await wo(e);if(Po(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(Pt),headers:Ae,method:"POST"});if(!n.ok)throw await Oe(n,`Failed to install schema for ${e.streamName}`)}function Po(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,St.isDeepStrictEqual)(r,Pt.schema)&&(0,St.isDeepStrictEqual)(e.search,Pt.search)}async function wo(e){let t=await fetch(`${e.url}/_schema`,{headers:Ae,method:"GET"});if(!t.ok)throw await Oe(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}async function Eo(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:Ae,method:"POST"});if(!r.ok)throw await Oe(r,"Failed to append to prisma-queries")}async function Oe(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}p();var vn=require("fs/promises"),F=require("pathe"),z=require("proper-lockfile"),Tt=require("std-env"),g=require("valibot");j();p();var vo=require("timers/promises"),bn=require("std-env");function Sn(e,t){if(e==null)return!1;try{return bn.process.kill?.(e,0)??!0}catch(r){return t&&console.error(`Error checking if process with PID ${e} exists:`,r),!1}}var oe=(0,g.pipe)((0,g.string)(),(0,g.url)()),Pn=(0,g.object)({connectionString:oe,prismaORMConnectionString:(0,g.optional)(oe),terminalCommand:(0,g.optional)((0,g.string)())}),wn=(0,g.object)({url:oe}),En=(0,g.object)({serverUrl:oe,sqlitePath:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),streamName:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),url:oe}),Ro=(0,g.object)({queryInsights:(0,g.optional)(En),streams:(0,g.optional)(En)}),Et=(0,g.pipe)((0,g.number)(),(0,g.integer)(),(0,g.minValue)(1)),xo=(0,g.object)({database:Pn,http:wn,ppg:wn,shadowDatabase:Pn}),To=(0,g.object)({databasePort:Et,experimental:(0,g.optional)(Ro),exports:(0,g.optional)(xo),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:Et,shadowDatabasePort:Et,version:(0,g.literal)("1")}),It=Symbol("initialize"),vt="default",Io=new Set(["durable-streams"]),N=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(t){this._databasePort=t.databasePort??I,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??vt,this.persistenceMode=t.persistenceMode,this.pid=t.pid??Tt.process.pid,this.shadowDatabaseConnectTimeoutMillis=t.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=t.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=t.port??I,this._shadowDatabasePort=t.shadowDatabasePort??I,this._streamsPort=t.streamsPort??I}static async createExclusively(t){let r=t?.dryRun!==!0&&t?.persistenceMode==="stateful"?new se(t):new Rt(t);return await r[It](),r}static async fromServerDump(t){let{debug:r,name:n=vt}=t??{},s=X(n),o=se.getServerDumpPath(s),a=await Wt(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)(),To),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 se({databasePort:c.databasePort,debug:r,dryRun:!1,name:n,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(t){let{debug:r,globs:n}=t??{},s=(0,F.join)(X(vt),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let o=(await Gt(s,n)).filter(a=>!Io.has(a));return r&&console.debug(`[State] found server names: ${JSON.stringify(o)}`),await Promise.all(o.map(a=>Do(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]!==Q&&this[n]!==r)throw new Error(`\`${t}\` is already set to ${this[n]}, cannot change it to ${r}`);this[n]=r}},Rt=class extends N{constructor(t){super({...t,databasePort:t?.databasePort||Q,persistenceMode:"stateless",port:t?.port||Q,shadowDatabasePort:t?.shadowDatabasePort||Q,streamsPort:t?.streamsPort||Q})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[It](){let t;try{t=await N.scan({debug:this.debug,onlyMetadata:!0})}catch(n){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",n),t=[]}let r=await qe({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort}async close(){}async writeServerDump(){}},se=class e extends N{#r;#e;#t;#s;#o;#a;#n;constructor(t){super({...t,persistenceMode:"stateful"}),this.#a=!1,this.#e=X(this.name),this.#r=(0,F.join)(this.#e,"db_dump.bak"),this.#t=(0,F.join)(this.#e,".lock"),this.#s=(0,F.join)(this.#e,".pglite"),this.#n=t?.serverDump??null,this.#o=e.getServerDumpPath(this.#e)}static getServerDumpPath(t){return(0,F.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[It](){await Ht(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,z.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let t=await N.scan({debug:this.debug,onlyMetadata:!0}),r=await qe({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:t});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort,await this.writeServerDump()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ELOCKED"?new ae(this):t}}async close(){if(!this.#a)try{await(0,z.unlock)(this.#e,{lockfilePath:this.#t}),this.#a=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(t){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,t),t}}async writeServerDump(t,r){this.#n={name:this.name,version:"1",pid:Tt.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:t},await(0,vn.writeFile)(this.#o,`${JSON.stringify(this.#n,null,2)}
121
- `,{encoding:"utf-8"})}};async function Do(e,t){let{debug:r,onlyMetadata:n}=t||{},s=typeof e=="string"?e:e.name,o=typeof e!="string"?e:void 0,a={databasePort:o?.databasePort??-1,experimental:o?.experimental,exports:o?.exports,name:s,pid:o?.pid,port:o?.port??-1,shadowDatabasePort:o?.shadowDatabasePort??-1,version:"1"};try{let i=o||await N.fromServerDump({debug:r,name:s});if(!i)return r&&console.debug(`[State] no server state found for name: ${s}`),{...a,status:"no_such_server"};a.databasePort=i.databasePort,a.experimental=i.experimental,a.exports=i.exports,a.pid=i.pid,a.port=i.port,a.shadowDatabasePort=i.shadowDatabasePort;let{exports:c,pid:u}=i;if(n)return{...a,status:"unknown"};if(!Sn(u,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${u}`),{...a,status:"not_running"};let l=X(s);try{if(!await(0,z.check)(l,{lockfilePath:(0,F.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(E){r&&console.error(`[State] server state for "${s}" failed to check lock:`,E)}if(!c)return{...a,status:"starting_up"};let{http:h}=c,{hc:d}=await import("hono/client"),m=await d(h.url).health.$get();if(!m.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(m)}`),{...a,status:"not_running"};let f=await m.json();return f.name!==e?(r&&console.debug(`[State] server state for "${s}" has mismatched health response: ${JSON.stringify(f)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${e}" is live: ${JSON.stringify(f)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${s}":`,i),{...a,status:"error"}}}var xt=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},ae=class extends xt{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return N.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};p();var xn=require("crypto"),Dt=require("timers/promises"),_t=require("util"),Tn=require("std-env");j();var _o="application/json",ie={connection:"close","content-type":_o},Ao={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},At={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 In(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:o,queryInsightsBridge:a,walBridge:i}=e,c=s==="stateless",u=c?Fo(n):n,l=De(u),h=!c&&await H(l);Tn.process.env.DS_LOCAL_DATA_ROOT=bt(),c&&await G(l);let d=await No({debug:r,hadExistingStreamsData:h,name:u,port:o}),m={serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path,streamName:ht,url:_e(d.exports.http.url)};try{await Lo(m);let f=await yn({bridge:a,debug:r,serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path}),E=new Ot({dbServer:t,debug:r,streamUrl:m.url}),J=i.subscribe(Ne=>{E.enqueue(Ne)});return{close:async()=>{J(),await E.close(),await f.close(),await d.close(),await(0,Dt.setTimeout)(100),c&&await G(l)},experimental:m,experimentalQueryInsights:f.experimental}}catch(f){throw await d.close().catch(()=>{}),await(0,Dt.setTimeout)(100),c&&await G(l).catch(()=>{}),f}}var Oo=["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 No(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||!Bo(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 G(De(n)),await a()}}function Bo(e){return Mo(e).map(r=>r.toLowerCase()).some(r=>Oo.some(n=>r.includes(n)))}function Mo(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 Ot=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 Co(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=Rn(t.record),a=Rn(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=Uo(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`)),Qo(n))}};async function Lo(e){let t=await fetch(e.url,{headers:ie,method:"PUT"});if(!t.ok)throw await ce(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(Ao),headers:ie,method:"POST"});if(!r.ok)throw await ce(r,`Failed to configure ${e.streamName}`);let n=await $o(e);if(ko(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(At),headers:ie,method:"POST"});if(!s.ok)throw await ce(s,`Failed to install schema for ${e.streamName}`)}async function $o(e){let t=await fetch(`${e.url}/_schema`,{headers:ie,method:"GET"});if(!t.ok)throw await ce(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function ko(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,_t.isDeepStrictEqual)(r,At.schema)&&(0,_t.isDeepStrictEqual)(e.search,At.search)}async function Co(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:ie,method:"POST"});if(!r.ok)throw await ce(r,"Failed to append to prisma-wal")}async function ce(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function Uo(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=qo(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function Qo(e){return JSON.stringify(Nt(e))}function Nt(e){return Array.isArray(e)?e.map(t=>Nt(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Nt(r)])):e}function Rn(e){return e?structuredClone(e):null}function qo(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 Fo(e){return`${e}.${(0,xn.randomUUID)().replaceAll("-","")}`}async function Dn(e){let t=await N.createExclusively(e),r=null,n=null,s=null,o=null;try{[r,s]=await Promise.all([tt("database",t),tt("shadow_database",t)]);let a,i;t.dryRun?(a=jo(),i=Ko(),o=Vo()):(a=await r.attachWalEventBridge(),i=await r.attachQueryInsightsBridge(),o=await In({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,queryInsightsBridge:i,walBridge:a})),n=await fn(r,t);let c=Wo(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{queryInsights:o.experimentalQueryInsights,streams:o.experimental});let u=Go(a),l=hn(o.experimentalQueryInsights),h=r,d=s,m=n,f=o,E=async()=>{u.close(),await _n(t,[m,f,h,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 Ho(t,[n,o,r,s],a)}}function Wo(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:Lt({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 _n(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 Ho(e,t,r){try{await _n(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function Go(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=zo(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 jo(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Ko(){return{async close(){},subscribe(){return()=>{}}}}function Vo(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function zo(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)))}}}}async function An(e){let{server:t}=await Dn(e);return t}async function Jo(e){return await An(e)}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,DEFAULT_STREAMS_PORT,PortNotAvailableError,ServerAlreadyRunningError,copyPrismaDevRuntimeAssets,getPrismaDevRuntimeAssetManifest,startPrismaDevServer,unstable_startServer});
141
+ `);return n.map(s=>s.column_name)}function Kn(e){return`'${e.replaceAll("'","''")}'`}async function Ga(e){let{dataDir:t,db:r,debug:n,destinationPath:s}=e,i=r||await is(t,n),{pgDump:o}=await import("@electric-sql/pglite-tools/pg_dump"),a=await o({args:["--schema-only","--no-owner"],fileName:s?(0,Yn.filename)(s):void 0,pg:await i.clone()});return s?(n&&console.debug(`[DB] Dumping database to ${s}`),await hn(a,s)):(n&&console.debug("[DB] Dumping database to memory"),await a.text())}f();var yo=U(_i(),1);oe();async function So(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:i},{createHTTPServer:o}]=await Promise.all([Promise.resolve().then(()=>(po(),mo)),Promise.resolve().then(()=>(go(),ho)),Promise.resolve().then(()=>(Ct(),Wi))]),a={databaseDumpPath:t.databaseDumpPath,db:e,debug:n,name:t.name,port:r,shadowDBPort:t.shadowDatabasePort},c=(0,yo.default)({defaultRoute(l,m){B(m,"Not Found",404)},ignoreTrailingSlash:!1});s(c,a,n),i(c,a,n);let u=await o({router:c}).listen(r);return t.port=u.port,a.port=u.port,{async close(){let{Engine:l}=await Promise.resolve().then(()=>(Br(),Lr));await Promise.allSettled([u.close(),l.stopAll()])},port:u.port,url:u.url}}f();var Wr=require("util");f();var qr=require("pathe");Te();var jr="prisma-wal",Qr="prisma-queries";function Fr(){return(0,qr.join)(et.data,"durable-streams")}function $t(e){return(0,qr.join)(Fr(),e)}function Lt(e,t=jr){return new URL(`/v1/stream/${encodeURIComponent(t)}`,e).toString()}var Pl="application/json",Bt={connection:"close","content-type":Pl},Gr={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 bo(e){return{...e,snapshot:async t=>await wl(e.url,t)}}async function Po(e){let t={serverUrl:e.serverUrl,sqlitePath:e.sqlitePath,streamName:Qr,url:Lt(e.serverUrl,Qr)};await vl(t);let r=new zr({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 wl(e,t){if(!e)return vn();let r=await El(e);return In(r,t)}async function El(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 zr=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 Tl(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 vl(e){let t=await fetch(e.url,{headers:Bt,method:"PUT"});if(!t.ok)throw await kt(t,`Failed to create ${e.streamName}`);let r=await xl(e);if(Rl(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(Gr),headers:Bt,method:"POST"});if(!n.ok)throw await kt(n,`Failed to install schema for ${e.streamName}`)}function Rl(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,Wr.isDeepStrictEqual)(r,Gr.schema)&&(0,Wr.isDeepStrictEqual)(e.search,Gr.search)}async function xl(e){let t=await fetch(`${e.url}/_schema`,{headers:Bt,method:"GET"});if(!t.ok)throw await kt(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}async function Tl(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:Bt,method:"POST"});if(!r.ok)throw await kt(r,"Failed to append to prisma-queries")}async function kt(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}f();var To=require("fs/promises"),Pe=require("pathe"),Me=require("proper-lockfile"),Xr=require("std-env"),g=require("valibot");Te();f();var Al=require("timers/promises"),wo=require("std-env");function Eo(e,t){if(e==null)return!1;try{return wo.process.kill?.(e,0)??!0}catch(r){return t&&console.error(`Error checking if process with PID ${e} exists:`,r),!1}}Be();var Ge=(0,g.pipe)((0,g.string)(),(0,g.url)()),vo=(0,g.object)({connectionString:Ge,prismaORMConnectionString:(0,g.optional)(Ge),terminalCommand:(0,g.optional)((0,g.string)())}),Ro=(0,g.object)({url:Ge}),xo=(0,g.object)({serverUrl:Ge,sqlitePath:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),streamName:(0,g.pipe)((0,g.string)(),(0,g.minLength)(1)),url:Ge}),Il=(0,g.object)({queryInsights:(0,g.optional)(xo),streams:(0,g.optional)(xo)}),Vr=(0,g.pipe)((0,g.number)(),(0,g.integer)(),(0,g.minValue)(1)),_l=(0,g.object)({database:vo,http:Ro,ppg:Ro,shadowDatabase:vo}),Ol=(0,g.object)({databasePort:Vr,experimental:(0,g.optional)(Il),exports:(0,g.optional)(_l),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:Vr,shadowDatabasePort:Vr,version:(0,g.literal)("1")}),Zr=Symbol("initialize"),Kr="default",Dl=new Set(["durable-streams"]),ee=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(t){this._databasePort=t.databasePort??q,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??Kr,this.persistenceMode=t.persistenceMode,this.pid=t.pid??Xr.process.pid,this.shadowDatabaseConnectTimeoutMillis=t.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=t.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=t.port??q,this._shadowDatabasePort=t.shadowDatabasePort??q,this._streamsPort=t.streamsPort??q}static async createExclusively(t){let r=t?.dryRun!==!0&&t?.persistenceMode==="stateful"?new We(t):new Jr(t);return await r[Zr](),r}static async fromServerDump(t){let{debug:r,name:n=Kr}=t??{},s=Le(n),i=We.getServerDumpPath(s),o=await gn(i);if(o==null)return r&&console.debug(`[State] No server dump file found at: ${i}`),null;r&&(console.debug(`[State] server dump file found at "${i}":`),console.debug(o));let{issues:a,output:c,success:u}=(0,g.safeParse)((0,g.pipe)((0,g.string)(),(0,g.parseJson)(),Ol),o);if(!u)throw r&&console.debug(`[State] Invalid server dump file at "${i}":
142
+ ${JSON.stringify(a,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new We({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,Pe.join)(Le(Kr),"..");r&&console.debug(`[State] scanning for server states in: ${s}`);let i=(await Sn(s,n)).filter(o=>!Dl.has(o));return r&&console.debug(`[State] found server names: ${JSON.stringify(i)}`),await Promise.all(i.map(o=>Cl(o,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]!==ye&&this[n]!==r)throw new Error(`\`${t}\` is already set to ${this[n]}, cannot change it to ${r}`);this[n]=r}},Jr=class extends ee{constructor(t){super({...t,databasePort:t?.databasePort||ye,persistenceMode:"stateless",port:t?.port||ye,shadowDatabasePort:t?.shadowDatabasePort||ye,streamsPort:t?.streamsPort||ye})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Zr](){let t;try{t=await ee.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 Vt({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(){}},We=class e extends ee{#r;#e;#t;#s;#i;#o;#n;constructor(t){super({...t,persistenceMode:"stateful"}),this.#o=!1,this.#e=Le(this.name),this.#r=(0,Pe.join)(this.#e,"db_dump.bak"),this.#t=(0,Pe.join)(this.#e,".lock"),this.#s=(0,Pe.join)(this.#e,".pglite"),this.#n=t?.serverDump??null,this.#i=e.getServerDumpPath(this.#e)}static getServerDumpPath(t){return(0,Pe.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[Zr](){await yn(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,Me.lock)(this.#e,{lockfilePath:this.#t}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let t=await ee.scan({debug:this.debug,onlyMetadata:!0}),r=await Vt({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 ze(this):t}}async close(){if(!this.#o)try{await(0,Me.unlock)(this.#e,{lockfilePath:this.#t}),this.#o=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(t){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,t),t}}async writeServerDump(t,r){this.#n={name:this.name,version:"1",pid:Xr.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:t},await(0,To.writeFile)(this.#i,`${JSON.stringify(this.#n,null,2)}
143
+ `,{encoding:"utf-8"})}};async function Cl(e,t){let{debug:r,onlyMetadata:n}=t||{},s=typeof e=="string"?e:e.name,i=typeof e!="string"?e:void 0,o={databasePort:i?.databasePort??-1,experimental:i?.experimental,exports:i?.exports,name:s,pid:i?.pid,port:i?.port??-1,shadowDatabasePort:i?.shadowDatabasePort??-1,version:"1"};try{let a=i||await ee.fromServerDump({debug:r,name:s});if(!a)return r&&console.debug(`[State] no server state found for name: ${s}`),{...o,status:"no_such_server"};o.databasePort=a.databasePort,o.experimental=a.experimental,o.exports=a.exports,o.pid=a.pid,o.port=a.port,o.shadowDatabasePort=a.shadowDatabasePort;let{exports:c,pid:u}=a;if(n)return{...o,status:"unknown"};if(!Eo(u,r))return r&&console.debug(`[State] server state for "${s}" has no running process with PID: ${u}`),{...o,status:"not_running"};let l=Le(s);try{if(!await(0,Me.check)(l,{lockfilePath:(0,Pe.join)(l,".lock")}))return r&&console.debug(`[State] server state for "${s}" is not locked, indicating it is not running.`),{...o,status:"not_running"}}catch(y){r&&console.error(`[State] server state for "${s}" failed to check lock:`,y)}if(!c)return{...o,status:"starting_up"};let{http:m}=c,d=await fetch(`${m.url}/health`,{headers:{connection:"close"}});if(!d.ok)return r&&console.debug(`[State] server state for "${s}" is not live: ${JSON.stringify(d)}`),{...o,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)}`),{...o,status:"unknown"}):(r&&console.debug(`[State] server state for "${e}" is live: ${JSON.stringify(p)}`),{...o,status:"running"})}catch(a){return r&&console.error(`[State] failed to get server status for "${s}":`,a),{...o,status:"error"}}}var Yr=class extends Error{name="ServerStateAlreadyExistsError";constructor(t){super(`A Prisma Dev server with the name "${t}" is already running.`)}},ze=class extends Yr{#r;name="ServerAlreadyRunningError";constructor(t){super(t.name),this.#r=t}get server(){return ee.fromServerDump({debug:this.#r.debug,name:this.#r.name})}};f();var Io=require("crypto"),en=require("timers/promises"),tn=require("util"),_o=require("std-env");Te();var Nl="application/json",Ve={connection:"close","content-type":Nl},Ml={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},rn={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 Oo(e){let{dbServer:t,debug:r,name:n,persistenceMode:s,port:i,queryInsightsBridge:o,walBridge:a}=e,c=s==="stateless",u=c?Gl(n):n,l=$t(u),m=!c&&await Re(l);_o.process.env.DS_LOCAL_DATA_ROOT=Fr(),c&&await xe(l);let d=await Ll({debug:r,hadExistingStreamsData:m,name:u,port:i}),p={serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path,streamName:jr,url:Lt(d.exports.http.url)};try{await Ul(p);let y=await Po({bridge:o,debug:r,serverUrl:d.exports.http.url,sqlitePath:d.exports.sqlite.path}),b=new nn({dbServer:t,debug:r,streamUrl:p.url}),S=a.subscribe(D=>{b.enqueue(D)});return{close:async()=>{S(),await b.close(),await y.close(),await d.close(),await(0,en.setTimeout)(100),c&&await xe(l)},experimental:p,experimentalQueryInsights:y.experimental}}catch(y){throw await d.close().catch(()=>{}),await(0,en.setTimeout)(100),c&&await xe(l).catch(()=>{}),y}}var $l=["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 Ll(e){let{debug:t,hadExistingStreamsData:r,name:n,port:s}=e,{startLocalDurableStreamsServer:i}=await import("@prisma/streams-local"),o=()=>i({hostname:"127.0.0.1",name:n,port:s});try{return await o()}catch(a){if(!r||!Bl(a))throw a;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),t&&console.debug(`[streams] original durable streams startup error for "${n}"`,a),await xe($t(n)),await o()}}function Bl(e){return kl(e).map(r=>r.toLowerCase()).some(r=>$l.some(n=>r.includes(n)))}function kl(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 i of s.errors)r.push(i);if(s instanceof Error){t.push(s.message);let i=s.cause;i!==void 0&&r.push(i)}}}return t}var nn=class{#r;#e;#t;#s;#i;constructor(t){this.#r=t.dbServer,this.#e=t.debug,this.#t=Promise.resolve(),this.#s=t.streamUrl,this.#i=new Set}enqueue(t){t.length!==0&&(this.#t=this.#t.then(async()=>{let r=await this.#o(t);r.length!==0&&(await jl(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#o(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),i=Ao(t.record),o=Ao(t.oldRecord),a=this.#a(n,s,o),c=this.#a(n,s,i),u=t.txid===""?void 0:t.txid;return t.type==="insert"?i&&c?[{headers:{operation:"insert",timestamp:r,txid:u},key:c,old_value:null,type:n,value:i}]:[]:t.type==="delete"?o&&a?[{headers:{operation:"delete",timestamp:r,txid:u},key:a,old_value:o,type:n,value:null}]:[]:!i||!o||!a||!c?[]:a!==c?[{headers:{operation:"delete",timestamp:r,txid:u},key:a,old_value:o,type:n,value:null},{headers:{operation:"insert",timestamp:r,txid:u},key:c,old_value:null,type:n,value:i}]:[{headers:{operation:"update",timestamp:r,txid:u},key:c,old_value:o,type:n,value:i}]}#a(t,r,n){if(!n)return null;let s=Ql(n,r);return s||(this.#i.has(t)||(this.#i.add(t),console.warn(`[streams] falling back to full-row keys for ${t} because no primary key could be resolved`)),Fl(n))}};async function Ul(e){let t=await fetch(e.url,{headers:Ve,method:"PUT"});if(!t.ok)throw await Ke(t,`Failed to create ${e.streamName}`);let r=await fetch(`${e.url}/_profile`,{body:JSON.stringify(Ml),headers:Ve,method:"POST"});if(!r.ok)throw await Ke(r,`Failed to configure ${e.streamName}`);let n=await Hl(e);if(ql(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(rn),headers:Ve,method:"POST"});if(!s.ok)throw await Ke(s,`Failed to install schema for ${e.streamName}`)}async function Hl(e){let t=await fetch(`${e.url}/_schema`,{headers:Ve,method:"GET"});if(!t.ok)throw await Ke(t,`Failed to inspect schema for ${e.streamName}`);return await t.json()}function ql(e,t){if(e.currentVersion<=0||e.schema!==t)return!1;let r=e.schemas[String(e.currentVersion)];return(0,tn.isDeepStrictEqual)(r,rn.schema)&&(0,tn.isDeepStrictEqual)(e.search,rn.search)}async function jl(e,t){let r=await fetch(e,{body:JSON.stringify(t),headers:Ve,method:"POST"});if(!r.ok)throw await Ke(r,"Failed to append to prisma-wal")}async function Ke(e,t){let r=await e.text().catch(()=>"");return new Error(`${t}: HTTP ${e.status}${r?` ${r}`:""}`)}function Ql(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=Wl(e[n]);if(s==null)return null;r.push(t.length===1?s:`${n}=${s}`)}return r.join("|")}function Fl(e){return JSON.stringify(sn(e))}function sn(e){return Array.isArray(e)?e.map(t=>sn(t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,sn(r)])):e}function Ao(e){return e?structuredClone(e):null}function Wl(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 Gl(e){return`${e}.${(0,Io.randomUUID)().replaceAll("-","")}`}async function Do(e){let t=await ee.createExclusively(e),r=null,n=null,s=null,i=null;try{[r,s]=await Promise.all([cr("database",t),cr("shadow_database",t)]);let o,a;t.dryRun?(o=Jl(),a=Yl(),i=Xl()):(o=await r.attachWalEventBridge(),a=await r.attachQueryInsightsBridge(),i=await Oo({dbServer:r,debug:t.debug,name:t.name,port:t.streamsPort,persistenceMode:t.persistenceMode,queryInsightsBridge:a,walBridge:o})),n=await So(r,t);let c=zl(r,s,n,t);await t.writeServerDump(c,t.dryRun?{}:{queryInsights:i.experimentalQueryInsights,streams:i.experimental});let u=Kl(o),l=bo(i.experimentalQueryInsights),m=r,d=s,p=n,y=i,b=async()=>{u.close(),await Co(t,[p,y,m,d])};return{close:b,dbServer:r,httpServer:n,server:{...c,close:b,experimental:{queryInsights:l,streams:i.experimental,wal:u.api},name:t.name},serverState:t,shadowDbServer:s,streamsServer:i,queryInsightsBridge:a,walBridge:o}}catch(o){return await Vl(t,[n,i,r,s],o)}}function zl(e,t,r,n){let s=`prisma+postgres://localhost:${r.port}/?${new URLSearchParams({api_key:cn({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 Co(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 Vl(e,t,r){try{await Co(e,t.filter(n=>n!==null))}catch(n){throw new AggregateError([r,n],"Failed to start Prisma Dev server cleanly")}throw r}function Kl(e){let t=new Set;return{api:{stream:()=>{let r=()=>{},n=Zl(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 Jl(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Yl(){return{async close(){},subscribe(){return()=>{}}}}function Xl(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function Zl(e,t){let r=[],n=!1,s=null,i=e.subscribe(a=>{if(!n){if(s){let c=s;s=null,c.resolve({done:!1,value:a});return}r.push(a)}}),o=()=>{if(!n&&(n=!0,i(),r.length=0,t(),s)){let a=s;s=null,a.resolve({done:!0,value:void 0})}};return{close:o,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((a,c)=>{s={reject:c,resolve:a}})},return(){return o(),Promise.resolve({done:!0,value:void 0})},throw(a){let c=s;return o(),c&&c.reject(a),Promise.reject(a instanceof Error?a:new Error(String(a)))}}}}Be();async function No(e){let{server:t}=await Do(e);return t}async function eu(e){return await No(e)}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,DEFAULT_STREAMS_PORT,PortNotAvailableError,ServerAlreadyRunningError,copyPrismaDevRuntimeAssets,getPrismaDevRuntimeAssetManifest,startPrismaDevServer,unstable_startServer});