🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@prisma/dev

Package Overview
Dependencies
Maintainers
4
Versions
838
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@prisma/dev - npm Package Compare versions

Comparing version
0.24.13
to
0.24.14
+11
dist/accelerate-45DUGMGZ.js
import{b as p}from"./chunk-662IKR3V.js";import{a as g}from"./chunk-SW3J2PL2.js";import{a as M}from"./chunk-ANHBRJRZ.js";import"./chunk-EDFHV3AK.js";import{a as d,b as m,c as B}from"./chunk-DOJAPHLY.js";import{text as Q}from"stream/consumers";import{json as en}from"stream/consumers";import{array as tn,literal as rn,minLength as on,object as sn,pipe as an,safeParse as cn,string as un,union as ln}from"valibot";var fn=sn({tags:ln([an(tn(un()),on(1)),rn("all")])});async function C(n,r){let e;try{e=await en(n)}catch{return m(r,"Invalid input",400),null}let{output:t,success:i}=cn(fn,e,{abortEarly:!0});return i?t:(m(r,"Invalid input",400),null)}import{Buffer as L}from"buffer";var x=new Map;async function O(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(a=>a.toString(16).padStart(2,"0")).join("")}function N(n,r){let e=n.schemaHash;if(e==null)return d(r,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let t=x.get(e);return t==null?(d(r,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:e,schemas:t}}async function V(n,r,e){let t=L.from(n,"base64").toString("utf8"),i=mn(t,r.toString());e&&console.log("[Accelerate] schema with override:",i);let o=await O(i);return{base64Override:L.from(i,"utf8").toString("base64"),overrideHash:o}}var dn=" ";function mn(n,r){let e=pn(n);if(!e)throw new Error("No datasource block found in schema.");let t=n.slice(e.openBraceIndex+1,e.closeBraceIndex),i=Sn(t,r,wn(n,e.openBraceIndex));return`${n.slice(0,e.openBraceIndex+1)}${i}${n.slice(e.closeBraceIndex)}`}function pn(n){let r="datasource";for(let e=0;e<n.length;e+=1){let t=n[e];if(t==="/"&&n[e+1]==="/"){e=R(n,e+2);continue}if(t==="/"&&n[e+1]==="*"){e=P(n,e+2);continue}if(t==='"'){e=v(n,e+1);continue}if(n.startsWith(r,e)&&!_(n[e-1])&&!_(n[e+r.length])){let i=gn(n,e+r.length,"{");if(i===-1)return null;let o=hn(n,i);return o===-1?null:{closeBraceIndex:o,openBraceIndex:i}}}return null}function gn(n,r,e){for(let t=r;t<n.length;t+=1){let i=n[t];if(i==="/"&&n[t+1]==="/"){t=R(n,t+2);continue}if(i==="/"&&n[t+1]==="*"){t=P(n,t+2);continue}if(i==='"'){t=v(n,t+1);continue}if(i===e)return t}return-1}function hn(n,r){let e=0;for(let t=r;t<n.length;t+=1){let i=n[t];if(i==="/"&&n[t+1]==="/"){t=R(n,t+2);continue}if(i==="/"&&n[t+1]==="*"){t=P(n,t+2);continue}if(i==='"'){t=v(n,t+1);continue}if(i==="{"){e+=1;continue}if(i==="}"&&(e-=1,e===0))return t}return-1}function R(n,r){let e=r;for(;e<n.length&&n[e]!==`
`;)e+=1;return e}function P(n,r){let e=n.indexOf("*/",r);return e===-1?n.length:e+1}function v(n,r){let e=r;for(;e<n.length;){if(n[e]==="\\"){e+=2;continue}if(n[e]==='"')return e;e+=1}return n.length}function _(n){return n!=null&&/[A-Za-z0-9_]/.test(n)}function Sn(n,r,e){let t=`"${xn(r)}"`,i=yn(n);for(let[f,h]of i.entries()){let{comment:I,code:nn}=D(h.line),T=nn.match(/^(\s*)url(\s*)=(\s*).*/);if(T)return i[f]={line:`${T[1]}url${T[2]}=${T[3]}${t}${I}`,terminator:h.terminator},$(i)}let o=Tn(n),a=In(i,e),u=`${a}url = ${t}`;if(!n.includes(`
`)&&!n.includes("\r")){let f=n.trim();return f.length===0?`${o}${u}${o}${e}`:`${o}${a}${f}${o}${u}${o}${e}`}let s=i.at(-1);if(s&&s.terminator===""&&/^\s*$/.test(s.line))return`${$(i.slice(0,-1))}${u}${o}${e}`;let c=$(i),l=c.endsWith(`
`)||c.endsWith("\r")?"":o;return`${c}${l}${u}${o}${e}`}function yn(n){let r=[],e=0;for(let t=0;t<n.length;t+=1){if(n[t]==="\r"&&n[t+1]===`
`){r.push({line:n.slice(e,t),terminator:`\r
`}),t+=1,e=t+1;continue}(n[t]===`
`||n[t]==="\r")&&(r.push({line:n.slice(e,t),terminator:n[t]}),e=t+1)}return(e<n.length||n.length===0)&&r.push({line:n.slice(e),terminator:""}),r}function $(n){return n.map(r=>`${r.line}${r.terminator}`).join("")}function D(n){let r=!1,e=!1;for(let t=0;t<n.length;t+=1){let i=n[t];if(e){if(r){r=!1;continue}if(i==="\\"){r=!0;continue}i==='"'&&(e=!1);continue}if(i==='"'){e=!0;continue}if(i==="/"&&n[t+1]==="/")return{code:n.slice(0,t),comment:n.slice(t)}}return{code:n,comment:""}}function In(n,r){for(let e of n){let{code:t}=D(e.line),i=t.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(i?.[1])return i[1]}return`${r}${dn}`}function wn(n,r){let e=n.lastIndexOf(`
`,r)+1,t=e;for(;n[t]===" "||n[t]===" ";)t+=1;return n.slice(e,t)}function Tn(n){return n.includes(`\r
`)?`\r
`:`
`}function xn(n){return n.replaceAll("\\","\\\\").replaceAll('"','\\"')}function w(n,r){let e=n[r];return Array.isArray(e)?e.at(-1):e}import{Readable as q}from"stream";import{pipeline as Hn}from"stream/promises";var En=new Set(["GET","HEAD"]);function U(n,r){let e=(n.method??"GET").toUpperCase(),t=`${r.origin}${n.url??"/"}`,i={headers:$n(n.headers),method:e};return En.has(e)||(i.body=q.toWeb(n),i.duplex="half"),new Request(t,i)}async function j(n,r){r.statusCode=n.status;for(let[e,t]of n.headers)r.setHeader(e,t);if(n.body===null){r.end();return}await Hn(q.fromWeb(n.body),r)}function $n(n){let r=new Headers;for(let[e,t]of Object.entries(n))if(typeof t=="string")r.append(e,t);else if(Array.isArray(t))for(let i of t)r.append(e,i);return r}function H(n){return{traceparent:w(n.headers,"traceparent"),"X-capture-telemetry":w(n.headers,"x-capture-telemetry")}}import{json as On}from"stream/consumers";import{integer as F,looseObject as Rn,minValue as k,number as b,object as Pn,optional as vn,pipe as W,safeParse as G,string as z,union as bn}from"valibot";var An=Pn({isolation_level:vn(z()),max_wait:W(b(),F(),k(0)),timeout:W(b(),F(),k(0))});async function Y(n,r){let e;try{e=await On(n)}catch{return d(r,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:t,output:i,success:o}=G(An,e,{abortEarly:!0});return o?i:(d(r,{EngineNotStarted:{reason:"InvalidRequest",issues:t}},400),null)}var Mn=Rn({id:bn([z(),b()])});function J(n,r){let{output:e,success:t}=G(Mn,n);return t?e:(d(r,{EngineMalfunction:{}},500),null)}var X,Z,K;function E(){return X??=import("./engine-YTEOPVUP.js"),X}function Bn(){return K??=import("./query-plan-executor-ZS4544O3.js"),K}async function Cn(){return Z??=import("@prisma/get-platform").then(async({default:n})=>await n.getPlatformInfo()),await Z}function ge(n,r,e){n.on("POST","/invalidate",g(async(i,o)=>{p(i,r),await C(i,o)!==null&&B(o,200)},e));for(let i of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])n.on("POST",i,g(async(o,a,u)=>{p(o,r);try{let s=await A(a,r,u);if(s===null)return;let c=await Q(o),l=u.transactionId,f=await s.request(c,{...H(o),"X-transaction-id":l});m(a,f)}catch(s){let{handleEngineError:c}=await E();c(s,a)}},e));for(let i of["commit","rollback"])n.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${i}`,g(async(o,a,u)=>{p(o,r);try{let s=await A(a,r,u);if(s===null)return;let c=u.transactionId;if(c==null){d(a,{EngineMalfunction:{}},500);return}let l=`${i}Transaction`,f=await s[l](c,H(o));d(a,f)}catch(s){let{handleEngineError:c}=await E();c(s,a)}},e));n.on("PUT","/:clientVersion/:schemaHash/schema",g(async(i,o,a)=>{p(i,r);let u=await Q(i);if(!u){m(o,"Missing schema",400);return}let s=a.schemaHash;if(s==null){m(o,"Missing schema hash",400);return}let c=x.get(s);if(c==null){if(s!==await O(u)){m(o,"Schema hash mismatch",400);return}let l=await V(u,r.db.prismaORMConnectionString,r.debug);x.set(s,{base64Original:u,...l}),m(o,s);return}if(u!==c.base64Original){m(o,"Schema mismatch",400);return}m(o,s)},e)),n.on("POST","/:clientVersion/:schemaHash/transaction/start",g(async(i,o,a)=>{p(i,r);let u=await Y(i,o);if(u!==null)try{let s=await A(o,r,a);if(s===null)return;let c=await s.startTransaction(u,H(i)),l=J(c,o);if(l===null)return;let{id:f}=l,h=a.clientVersion,I=a.schemaHash;d(o,{...c,"data-proxy":{endpoint:`http://localhost:${r.port}/${h}/${I}/itx/${f}`}})}catch(s){let{handleEngineError:c}=await E();c(s,o)}},e));let t=[["GET","/connection-info"],["POST","/query"],["POST","/transaction/start"],["POST","/transaction/:transactionId/commit"],["POST","/transaction/:transactionId/query"],["POST","/transaction/:transactionId/rollback"]];for(let[i,o]of t)n.on(i,o,g(async(a,u)=>{p(a,r);let{getQueryPlanExecutorServer:s,queryPlanExecutorVersion:c}=await Bn(),l=w(a.headers,"prisma-engine-hash");if(l!=="0.0.0"&&l!==c)throw new M(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 ${c}.`);let f=await s(r),h=U(a,{origin:`http://localhost:${r.port}`}),I=await f.fetch(h);await j(I,u)},e))}async function A(n,r,e){let{Engine:t}=await E(),i=N(e,n);if(i===null)return null;let{base64Override:o,overrideHash:a}=i.schemas;return await t.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.clientVersion||"",debug:r.debug,platform:await Cn(),schemaHash:a})}export{ge as registerAccelerateRoutes};
import{a as r}from"./chunk-ANHBRJRZ.js";import{minLength as D,object as S,optional as B,parseJson as x,pipe as n,regex as h,safeParse as O,string as s,url as f}from"valibot";var l=/^(postgres|postgresql):\/\//,T=n(s(),x(),S({databaseUrl:n(s(),f(),h(l)),name:B(n(s(),D(1))),shadowDatabaseUrl:n(s(),f(),h(l))}));function $(o){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(o).sort(([[e],[t]])=>e.localeCompare(t)))),"utf8").toString("base64url")}function E(o){let e=Buffer.from(o,"base64url").toString("utf8"),{issues:t,output:a,success:i}=O(T,e,{abortEarly:!0});return i?[null,a]:[t]}function j(o,e){let t=o.headers.authorization;if(!t)throw new r(401,"Missing API Key");let[a,i="",y]=t.split(" ");if(a!=="Bearer"||y)throw new r(401,"Invalid API Key");let[c,p]=E(i);if(c)throw new r(401,"Invalid API Key",{cause:c.join(", ")});let{databaseUrl:P,name:d,shadowDatabaseUrl:A}=p,u=e.name,m=e.port;if(!d)throw new r(401,`Wrong API Key; The Prisma Dev server running at port ${m} requires an API Key from a newer version of \`prisma dev\`. Check the "${u}" server's output for the updated \`DATABASE_URL\` value.`);if(d!==u)throw new r(401,`Wrong API Key; The Prisma Dev server running at port ${m} is named "${u}", but the API Key is for "${d}"`);let{hostname:I,port:w}=new URL(P),{port:g}=e.db,{hostname:b,port:K}=new URL(A),v=e.shadowDBPort;if(I!=="localhost"||Number(w)!==g||b!=="localhost"||Number(K)!==v)throw new r(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 p}export{$ as a,j as b};
var r=class extends Error{constructor(t,e,n){super(e,n);this.status=t}name="HTTPError"};export{r as a};
import{Buffer as r}from"buffer";function i(e,t,o=200){let n=r.from(JSON.stringify(t),"utf8");e.headersSent||(e.setHeader("Content-Type","application/json; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=o),e.end(n)}function s(e,t,o=200){let n=r.from(t,"utf8");e.headersSent||(e.setHeader("Content-Type","text/plain; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=o),e.end(n)}function f(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function u(e,t){s(e,t.message,t.status)}export{i as a,s as b,f as c,u as d};
import{a as D}from"./chunk-662IKR3V.js";import{a as q,b as W,f as x}from"./chunk-PP43TGA5.js";import{a as N,b as R,c as M,d as I,e as v,f as $}from"./chunk-HFONW2ZS.js";import{d as _,j as y}from"./chunk-DWY47FQV.js";import{b as O}from"./chunk-DOJAPHLY.js";import X from"find-my-way";async function C(r,e){let{port:t}=e;if(e.dryRun)return{async close(){},port:t,url:`http://localhost:${t}`};let n=!!e.debug,[{registerAccelerateRoutes:s},{registerUtilityRoutes:i},{createHTTPServer:l}]=await Promise.all([import("./accelerate-45DUGMGZ.js"),import("./utility-YEFNU35E.js"),import("./server-QR7P25DP.js")]),a={databaseDumpPath:e.databaseDumpPath,db:r,debug:n,name:e.name,port:t,shadowDBPort:e.shadowDatabasePort},o=X({defaultRoute(m,d){O(d,"Not Found",404)},ignoreTrailingSlash:!1});s(o,a,n),i(o,a,n);let c=await l({router:o}).listen(t);return e.port=c.port,a.port=c.port,{async close(){let{Engine:m}=await import("./engine-YTEOPVUP.js");await Promise.allSettled([c.close(),m.stopAll()])},port:c.port,url:c.url}}import{isDeepStrictEqual as U}from"util";var Z="application/json",P={connection:"close","content-type":Z},T={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 F(r){return{...r,snapshot:async e=>await ee(r.url,e)}}async function j(r){let e={serverUrl:r.serverUrl,sqlitePath:r.sqlitePath,streamName:R,url:v(r.serverUrl,R)};await te(e);let t=new k({debug:r.debug,streamUrl:e.url}),n=r.bridge.subscribe(s=>{t.enqueue(s)});return{close:async()=>{n(),await t.close()},experimental:e}}async function ee(r,e){if(!r)return q();let t=await re(r);return W(t,e)}async function re(r){let e=await fetch(`${r}?offset=-1&format=json`,{headers:{connection:"close"}});if(!e.ok)throw new Error(`Failed to read ${r}: HTTP ${e.status}`);return await e.json()}var k=class{#t;#r;#e;constructor(e){this.#t=e.debug,this.#r=Promise.resolve(),this.#e=e.streamUrl}enqueue(e){e.length!==0&&(this.#r=this.#r.then(async()=>{await ae(this.#e,e),this.#t&&console.debug(`[streams] appended ${e.length} query insight record(s) to ${this.#e}`)}).catch(t=>{console.error("[streams] failed to ingest query insights into prisma-queries",t)}))}async close(){await this.#r}};async function te(r){let e=await fetch(r.url,{headers:P,method:"PUT"});if(!e.ok)throw await b(e,`Failed to create ${r.streamName}`);let t=await se(r);if(ne(t,r.streamName))return;if(t.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let n=await fetch(`${r.url}/_schema`,{body:JSON.stringify(T),headers:P,method:"POST"});if(!n.ok)throw await b(n,`Failed to install schema for ${r.streamName}`)}function ne(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return U(t,T.schema)&&U(r.search,T.search)}async function se(r){let e=await fetch(`${r.url}/_schema`,{headers:P,method:"GET"});if(!e.ok)throw await b(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}async function ae(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:P,method:"POST"});if(!t.ok)throw await b(t,"Failed to append to prisma-queries")}async function b(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}import{randomUUID as ie}from"crypto";import{setTimeout as H}from"timers/promises";import{isDeepStrictEqual as L}from"util";import{process as oe}from"std-env";var le="application/json",S={connection:"close","content-type":le},ce={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},A={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 V(r){let{dbServer:e,debug:t,name:n,persistenceMode:s,port:i,queryInsightsBridge:l,walBridge:a}=r,o=s==="stateless",c=o?we(n):n,m=I(c),d=!o&&await _(m);oe.env.DS_LOCAL_DATA_ROOT=M(),o&&await y(m);let u=await ue({debug:t,hadExistingStreamsData:d,name:c,port:i}),h={serverUrl:u.exports.http.url,sqlitePath:u.exports.sqlite.path,streamName:N,url:v(u.exports.http.url)};try{await he(h);let p=await j({bridge:l,debug:t,serverUrl:u.exports.http.url,sqlitePath:u.exports.sqlite.path}),g=new Q({dbServer:e,debug:t,streamUrl:h.url}),Y=a.subscribe(z=>{g.enqueue(z)});return{close:async()=>{Y(),await g.close(),await p.close(),await u.close(),await H(100),o&&await y(m)},experimental:h,experimentalQueryInsights:p.experimental}}catch(p){throw await u.close().catch(()=>{}),await H(100),o&&await y(m).catch(()=>{}),p}}var me=["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 ue(r){let{debug:e,hadExistingStreamsData:t,name:n,port:s}=r,{startLocalDurableStreamsServer:i}=await import("@prisma/streams-local"),l=()=>i({hostname:"127.0.0.1",name:n,port:s});try{return await l()}catch(a){if(!t||!pe(a))throw a;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),e&&console.debug(`[streams] original durable streams startup error for "${n}"`,a),await y(I(n)),await l()}}function pe(r){return de(r).map(t=>t.toLowerCase()).some(t=>me.some(n=>t.includes(n)))}function de(r){let e=[],t=[r],n=new Set;for(;t.length>0;){let s=t.shift();if(!(s==null||n.has(s))){if(n.add(s),typeof s=="string"){e.push(s);continue}if(s instanceof AggregateError)for(let i of s.errors)t.push(i);if(s instanceof Error){e.push(s.message);let i=s.cause;i!==void 0&&t.push(i)}}}return e}var Q=class{#t;#r;#e;#n;#s;constructor(e){this.#t=e.dbServer,this.#r=e.debug,this.#e=Promise.resolve(),this.#n=e.streamUrl,this.#s=new Set}enqueue(e){e.length!==0&&(this.#e=this.#e.then(async()=>{let t=await this.#i(e);t.length!==0&&(await Se(this.#n,t),this.#r&&console.debug(`[streams] appended ${t.length} state-protocol record(s) to ${this.#n}`))}).catch(t=>{console.error("[streams] failed to ingest WAL events into prisma-wal",t)}))}async close(){await this.#e}async#i(e){let t=[],n=new Date().toISOString();for(let s of e)t.push(...await this.#o(s,n));return t}async#o(e,t){let n=`${e.schema}.${e.table}`,s=await this.#t.getPrimaryKeyColumns(e.schema,e.table),i=K(e.record),l=K(e.oldRecord),a=this.#a(n,s,l),o=this.#a(n,s,i),c=e.txid===""?void 0:e.txid;return e.type==="insert"?i&&o?[{headers:{operation:"insert",timestamp:t,txid:c},key:o,old_value:null,type:n,value:i}]:[]:e.type==="delete"?l&&a?[{headers:{operation:"delete",timestamp:t,txid:c},key:a,old_value:l,type:n,value:null}]:[]:!i||!l||!a||!o?[]:a!==o?[{headers:{operation:"delete",timestamp:t,txid:c},key:a,old_value:l,type:n,value:null},{headers:{operation:"insert",timestamp:t,txid:c},key:o,old_value:null,type:n,value:i}]:[{headers:{operation:"update",timestamp:t,txid:c},key:o,old_value:l,type:n,value:i}]}#a(e,t,n){if(!n)return null;let s=fe(n,t);return s||(this.#s.has(e)||(this.#s.add(e),console.warn(`[streams] falling back to full-row keys for ${e} because no primary key could be resolved`)),ve(n))}};async function he(r){let e=await fetch(r.url,{headers:S,method:"PUT"});if(!e.ok)throw await f(e,`Failed to create ${r.streamName}`);let t=await fetch(`${r.url}/_profile`,{body:JSON.stringify(ce),headers:S,method:"POST"});if(!t.ok)throw await f(t,`Failed to configure ${r.streamName}`);let n=await ge(r);if(ye(n,r.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${r.url}/_schema`,{body:JSON.stringify(A),headers:S,method:"POST"});if(!s.ok)throw await f(s,`Failed to install schema for ${r.streamName}`)}async function ge(r){let e=await fetch(`${r.url}/_schema`,{headers:S,method:"GET"});if(!e.ok)throw await f(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}function ye(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return L(t,A.schema)&&L(r.search,A.search)}async function Se(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:S,method:"POST"});if(!t.ok)throw await f(t,"Failed to append to prisma-wal")}async function f(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}function fe(r,e){if(e.length===0)return null;let t=[];for(let n of e){if(!Object.prototype.hasOwnProperty.call(r,n))return null;let s=Ee(r[n]);if(s==null)return null;t.push(e.length===1?s:`${n}=${s}`)}return t.join("|")}function ve(r){return JSON.stringify(B(r))}function B(r){return Array.isArray(r)?r.map(e=>B(e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,B(t)])):r}function K(r){return r?structuredClone(r):null}function Ee(r){if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="string")return r;if(typeof r=="number")return Number.isFinite(r)?String(r):null;if(typeof r=="bigint")return r.toString();if(typeof r=="boolean")return r?"true":"false";try{return JSON.stringify(r)}catch{return null}}function we(r){return`${r}.${ie().replaceAll("-","")}`}async function J(r){let e=await $.createExclusively(r),t=null,n=null,s=null,i=null;try{[t,s]=await Promise.all([x("database",e),x("shadow_database",e)]);let l,a;e.dryRun?(l=Re(),a=Ie(),i=Te()):(l=await t.attachWalEventBridge(),a=await t.attachQueryInsightsBridge(),i=await V({dbServer:t,debug:e.debug,name:e.name,port:e.streamsPort,persistenceMode:e.persistenceMode,queryInsightsBridge:a,walBridge:l})),n=await C(t,e);let o=Pe(t,s,n,e);await e.writeServerDump(o,e.dryRun?{}:{queryInsights:i.experimentalQueryInsights,streams:i.experimental});let c=xe(l),m=F(i.experimentalQueryInsights),d=t,u=s,h=n,p=i,g=async()=>{c.close(),await G(e,[h,p,d,u])};return{close:g,dbServer:t,httpServer:n,server:{...o,close:g,experimental:{queryInsights:m,streams:i.experimental,wal:c.api},name:e.name},serverState:e,shadowDbServer:s,streamsServer:i,queryInsightsBridge:a,walBridge:l}}catch(l){return await be(e,[n,i,t,s],l)}}function Pe(r,e,t,n){let s=`prisma+postgres://localhost:${t.port}/?${new URLSearchParams({api_key:D({databaseUrl:r.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:e.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:t.url},ppg:{url:s},shadowDatabase:{connectionString:e.prismaORMConnectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand}}}async function G(r,e){let t=[];for(let n of e)try{await n.close()}catch(s){t.push(s)}try{await r.close()}catch(n){t.push(n)}if(t.length>0)throw new AggregateError(t,"Failed to close some servers")}async function be(r,e,t){try{await G(r,e.filter(n=>n!==null))}catch(n){throw new AggregateError([t,n],"Failed to start Prisma Dev server cleanly")}throw t}function xe(r){let e=new Set;return{api:{stream:()=>{let t=()=>{},n=ke(r,()=>{e.delete(t)});return t=()=>n.close(),e.add(t),n.stream},subscribe:t=>r.subscribe(t)},close:()=>{for(let t of[...e])t();e.clear()}}}function Re(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Ie(){return{async close(){},subscribe(){return()=>{}}}}function Te(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function ke(r,e){let t=[],n=!1,s=null,i=r.subscribe(a=>{if(!n){if(s){let o=s;s=null,o.resolve({done:!1,value:a});return}t.push(a)}}),l=()=>{if(!n&&(n=!0,i(),t.length=0,e(),s)){let a=s;s=null,a.resolve({done:!0,value:void 0})}};return{close:l,stream:{[Symbol.asyncIterator](){return this},next(){return t.length>0?Promise.resolve({done:!1,value:t.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((a,o)=>{s={reject:o,resolve:a}})},return(){return l(),Promise.resolve({done:!0,value:void 0})},throw(a){let o=s;return l(),o&&o.reject(a),Promise.reject(a instanceof Error?a:new Error(String(a)))}}}}async function Ae(r){let{server:e}=await J(r);return e}async function pr(r){return await Ae(r)}export{Ae as a,pr as b};
import{e as h,f,g as M}from"./chunk-EDFHV3AK.js";import{a as A,c as m,g as V,h as C,i as L,j as x}from"./chunk-DWY47FQV.js";import{writeFile as ae}from"fs/promises";import{join as p}from"pathe";import{check as se,lock as oe,unlock as ie}from"proper-lockfile";import{process as H}from"std-env";import{integer as K,literal as ne,minLength as k,minValue as Q,number as Z,object as P,optional as l,parseJson as de,pipe as c,safeParse as ue,string as b,url as le}from"valibot";import{setTimeout as ee}from"timers/promises";import{process as D}from"std-env";function _(r,e){if(r==null)return!1;try{return D.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}async function J(r,e){if(!D.kill)return!1;try{D.kill(r,"SIGTERM")}catch(a){return e&&console.error(`Error killing process with PID ${r}:`,a),!1}let t=0;do{if(!_(r,e))return!0;await ee(100)}while(++t<50);try{return D.kill(r,"SIGKILL")}catch(a){return e&&console.error(`Error forcefully killing process with PID ${r}:`,a),!1}}import{join as j}from"pathe";var te="prisma-wal",ye="prisma-queries";function re(){return j(A.data,"durable-streams")}function Y(r){return j(re(),r)}function xe(r,e=te){return new URL(`/v1/stream/${encodeURIComponent(e)}`,r).toString()}var S=c(b(),le()),F=P({connectionString:S,prismaORMConnectionString:l(S),terminalCommand:l(b())}),G=P({url:S}),B=P({serverUrl:S,sqlitePath:c(b(),k(1)),streamName:c(b(),k(1)),url:S}),ce=P({queryInsights:l(B),streams:l(B)}),I=c(Z(),K(),Q(1)),me=P({database:F,http:G,ppg:G,shadowDatabase:F}),he=P({databasePort:I,experimental:l(ce),exports:l(me),name:c(b(),k(1)),pid:l(c(Z(),K(),Q(0))),port:I,shadowDatabasePort:I,version:ne("1")}),O=Symbol("initialize"),E="default",pe=new Set(["durable-streams"]),d=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(e){this._databasePort=e.databasePort??f,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??E,this.persistenceMode=e.persistenceMode,this.pid=e.pid??H.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??f,this._shadowDatabasePort=e.shadowDatabasePort??f,this._streamsPort=e.streamsPort??f}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new g(e):new R(e);return await t[O](),t}static async fromServerDump(e){let{debug:t,name:a=E}=e??{},o=m(a),i=g.getServerDumpPath(o),s=await V(i);if(s==null)return t&&console.debug(`[State] No server dump file found at: ${i}`),null;t&&(console.debug(`[State] server dump file found at "${i}":`),console.debug(s));let{issues:n,output:u,success:v}=ue(c(b(),de(),he),s);if(!v)throw t&&console.debug(`[State] Invalid server dump file at "${i}":
${JSON.stringify(n,null,2)}`),new Error(`Invalid Prisma Dev state for "${a}".`);return new g({databasePort:u.databasePort,debug:t,dryRun:!1,name:a,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:t,globs:a}=e??{},o=p(m(E),"..");t&&console.debug(`[State] scanning for server states in: ${o}`);let i=(await L(o,a)).filter(s=>!pe.has(s));return t&&console.debug(`[State] found server names: ${JSON.stringify(i)}`),await Promise.all(i.map(s=>z(s,e)))}get databasePort(){return this._databasePort}set databasePort(e){this.#t("databasePort",e)}get port(){return this._port}set port(e){this.#t("port",e)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(e){this.#t("shadowDatabasePort",e)}#t(e,t){if(t<0||!Number.isInteger(t))throw new Error(`Invalid port number: ${t}`);let a=`_${e}`;if(this[a]!==h&&this[a]!==t)throw new Error(`\`${e}\` is already set to ${this[a]}, cannot change it to ${t}`);this[a]=t}},R=class extends d{constructor(e){super({...e,databasePort:e?.databasePort||h,persistenceMode:"stateless",port:e?.port||h,shadowDatabasePort:e?.shadowDatabasePort||h,streamsPort:e?.streamsPort||h})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[O](){let e;try{e=await d.scan({debug:this.debug,onlyMetadata:!0})}catch(a){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",a),e=[]}let t=await M({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,this._streamsPort=t.streamsPort}async close(){}async writeServerDump(){}},g=class r extends d{#t;#e;#a;#o;#i;#s;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#s=!1,this.#e=m(this.name),this.#t=p(this.#e,"db_dump.bak"),this.#a=p(this.#e,".lock"),this.#o=p(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#i=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return p(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get experimental(){return this.#r?.experimental}get pgliteDataDirPath(){return this.#o}async[O](){await C(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await oe(this.#e,{lockfilePath:this.#a}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await d.scan({debug:this.debug,onlyMetadata:!0}),t=await M({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,this._streamsPort=t.streamsPort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new $(this):e}}async close(){if(!this.#s)try{await ie(this.#e,{lockfilePath:this.#a}),this.#s=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e,t){this.#r={name:this.name,version:"1",pid:H.pid,port:this.port,databasePort:this.databasePort,experimental:t,shadowDatabasePort:this.shadowDatabasePort,exports:e},await ae(this.#i,`${JSON.stringify(this.#r,null,2)}
`,{encoding:"utf-8"})}};async function Ve(r,e){await Pe(r,e);let t=typeof r=="string"?r:r.name,a=m(t);await x(a),await x(Y(t))}async function z(r,e){let{debug:t,onlyMetadata:a}=e||{},o=typeof r=="string"?r:r.name,i=typeof r!="string"?r:void 0,s={databasePort:i?.databasePort??-1,experimental:i?.experimental,exports:i?.exports,name:o,pid:i?.pid,port:i?.port??-1,shadowDatabasePort:i?.shadowDatabasePort??-1,version:"1"};try{let n=i||await d.fromServerDump({debug:t,name:o});if(!n)return t&&console.debug(`[State] no server state found for name: ${o}`),{...s,status:"no_such_server"};s.databasePort=n.databasePort,s.experimental=n.experimental,s.exports=n.exports,s.pid=n.pid,s.port=n.port,s.shadowDatabasePort=n.shadowDatabasePort;let{exports:u,pid:v}=n;if(a)return{...s,status:"unknown"};if(!_(v,t))return t&&console.debug(`[State] server state for "${o}" has no running process with PID: ${v}`),{...s,status:"not_running"};let N=m(o);try{if(!await se(N,{lockfilePath:p(N,".lock")}))return t&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...s,status:"not_running"}}catch(X){t&&console.error(`[State] server state for "${o}" failed to check lock:`,X)}if(!u)return{...s,status:"starting_up"};let{http:W}=u,w=await fetch(`${W.url}/health`,{headers:{connection:"close"}});if(!w.ok)return t&&console.debug(`[State] server state for "${o}" is not live: ${JSON.stringify(w)}`),{...s,status:"not_running"};let y=await w.json();return y.name!==r?(t&&console.debug(`[State] server state for "${o}" has mismatched health response: ${JSON.stringify(y)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(y)}`),{...s,status:"running"})}catch(n){return t&&console.error(`[State] failed to get server status for "${o}":`,n),{...s,status:"error"}}}function be(r){let{status:e}=r;return e==="running"||e==="starting_up"}async function Pe(r,e){let{pid:t,...a}=typeof r=="string"?await z(r,{debug:e}):r;if(!be(a))return!1;let o=await d.fromServerDump({debug:e,name:a.name});if(t==null){e&&console.debug(`[State] No PID found for server "${a.name}" to kill.`);try{await o?.close()}catch{}return!1}let i=await J(t,e);try{await o?.close()}catch{}return i}var T=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},$=class extends T{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return d.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{te as a,ye as b,re as c,Y as d,xe as e,d as f,Ve as g,z as h,be as i,Pe as j,T as k,$ as l};
import{a as c}from"./chunk-ANHBRJRZ.js";import{h as d}from"./chunk-EDFHV3AK.js";import{c as l,d as f}from"./chunk-DOJAPHLY.js";import{createServer as m}from"http";import{promisify as u}from"util";function A(r,e){return async function(o,n,i){let t=e?Date.now():0;e&&n.once("finish",()=>{let a=Date.now()-t;console.log("[Accelerate]",`<-- ${o.method??"?"} ${o.url??""} ${n.statusCode} ${a}ms`)});try{await r(o,n,i)}catch(a){try{y(a,n,o,e)}catch(p){e&&console.error("[Accelerate]","error while handling handler error",p),n.destroyed||n.destroy()}}}}function y(r,e,s,o){if(e.destroyed||e.headersSent||e.writableEnded){o&&console.error("[Accelerate]",`error after response was no longer writable for ${s.method??"?"} ${s.url??""}`,r),e.destroy();return}if(r instanceof c){f(e,r);return}console.error("[Accelerate]",r);try{l(e,500)}catch(n){o&&console.error("[Accelerate]","failed to write 500 response (client likely disconnected)",n),e.destroy()}}function E(r){let{router:e}=r;return{async listen(s){let o=m((t,a)=>{e.lookup(t,a)}),i=(await T(o,s)).port;return o.on("error",t=>{console.error("[Accelerate]",t)}),{async close(){await u(o.close.bind(o))()},port:i,url:`http://localhost:${i}`}}}}function T(r,e){return new Promise((s,o)=>{let n=t=>{if(r.off("listening",i),typeof t=="object"&&t!==null&&"code"in t&&t.code==="EADDRINUSE"){o(new d(e));return}o(t)},i=()=>{r.off("error",n),s(r.address())};r.once("error",n),r.once("listening",i),r.listen(e)})}export{A as a,E as b};
import{b as f,d as w,e as y}from"./chunk-DWY47FQV.js";import{a as E,b as v,c as b}from"./chunk-DOJAPHLY.js";import{spawn as $}from"child_process";import{once as H}from"events";import{mkdir as C}from"fs/promises";import{join as A}from"path";import{setTimeout as j}from"timers/promises";function R(r){let e,t,s=new Promise((i,a)=>{e=i,t=a}),n=i=>{n=o=null,t(i),r?.onRejected?.(i),r?.onFulfilled?.()},o=i=>{o=n=null,e(i),r?.onResolved?.(i),r?.onFulfilled?.()};return{isFulfilled:()=>o===n,promise:s,reject:i=>n?.(i),resolve:i=>o?.(i)}}import{process as B}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:L,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:N,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:P}=B.env,S=class r{static#t=new Map;#e;#n;constructor(e){this.#e=e,this.#n=null}static async get(e){let{debug:t}=e,s=`${e.schemaHash}:${e.clientVersion}`;try{let n=r.#t.get(s);if(n)return n;let o=new r(e);return r.#t.set(s,o),t&&console.debug("[Query Engine] starting...",e),await o.start(),t&&console.debug("[Query Engine] started!"),o}finally{r.stopAll(s)}}static async stopAll(e){let s=(await Promise.allSettled(Array.from(r.#t.entries()).filter(([n])=>n!==e).map(async([n,o])=>{try{await o.stop()}finally{r.#t.delete(n)}}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(s.length>0)throw new AggregateError(s,"Failed to stop engines")}async commitTransaction(e,t){return await this.#s(e,t,"commit")}async request(e,t){let{url:s}=await this.start(),n=this.#i(t),o=await fetch(s,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await l.fromResponse(o);return await o.text()}async rollbackTransaction(e,t){return await this.#s(e,t,"rollback")}async startTransaction(e,t){let{url:s}=await this.start(),n=this.#i(t),o=await fetch(`${s}/transaction/start`,{body:JSON.stringify(e),headers:{...n,"Content-Type":"application/json"},method:"POST"});if(!o.ok)throw await l.fromResponse(o);return await o.json()}async start(){if(this.#n!=null)return await this.#n;let{promise:e,reject:t,resolve:s}=R();this.#n=e;let n=N||await this.#o();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",n);let{proxySignals:o}=await import("foreground-child/proxy-signals"),i=$(n,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});o(i),i.stderr.setEncoding("utf8"),i.stdout.setEncoding("utf8");let a=c=>{let u=c.split(`
`).find(k=>k.includes("Started query engine http server"));if(!u)return;i.stdout.removeListener("data",a);let{fields:p}=JSON.parse(u);if(p==null)return t(new Error(`Unexpected data during initialization, "fields" are missing: ${c}`));let{ip:m,port:h}=p;if(m==null||h==null)return t(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
Received data: ${c}`));s({childProcess:i,url:`http://${m}:${h}`})},T=c=>{this.#n=null,t(new d(String(c))),i.removeListener("exit",g),i.kill()};i.once("error",T);let g=(c,u)=>{this.#n=null,t(new d(`Query Engine exited with code ${c} and signal ${u}`))};return i.once("exit",g),i.stdout.on("data",a),this.#e.debug&&(i.stderr.on("data",console.error.bind(console,"[Query Engine]")),i.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#n}async stop(){if(this.#n==null)return;let{childProcess:e}=await this.#n;e.exitCode==null&&e.signalCode==null&&(this.#n=null,e.kill(),await H(e,"exit"))}async#o(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#r();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let t=f(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",t),await C(t,{recursive:!0});let{binaryTarget:s}=this.#e.platform,n=s==="windows"?".exe":"",o=A(t,`query-engine-${s}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",o),(L==="1"||await w(o)===!1)&&await this.#a({commitHash:e,extension:n,engineBinaryPath:o}),o}async#r(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let s=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!s)throw new Error("Couldn't find engines version in package.json");let n=s.split(".").at(-1);if(!n)throw new Error("Couldn't find commit hash in engines version");return n}async#a(e){let{commitHash:t,extension:s,engineBinaryPath:n}=e,{binaryTarget:o}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${t}/${o}/query-engine${s}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);P&&await j(Number(P)),await y(await a.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#i(e){let t={};for(let[s,n]of Object.entries(e))n!=null&&(t[s]=n);return t}async#s(e,t,s){let{url:n}=await this.#n,o=this.#i(t),i=await fetch(`${n}/transaction/${e}/${s}`,{headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await l.fromResponse(i);try{return await i.json()}catch{return{}}}};function G(r,e){if(console.error(r),r instanceof d){E(e,{EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:r.message}}}},500);return}if(r instanceof l){v(e,r.responseBody,r.statusCode);return}b(e,500)}var d=class extends Error{name="EngineStartError"},l=class r extends Error{constructor(t,s,n){super(`${t}: Query Engine response status ${s}, body: ${n}`);this.action=t;this.statusCode=s;this.responseBody=n}name="EngineHttpError";static async fromResponse(t){let s=new URL(t.url),n=await t.text();return new r(s.pathname,t.status,n)}};export{S as Engine,G as handleEngineError};
import{parseDuration as e,parseSize as o,Server as n}from"@prisma/query-plan-executor";import{version as c}from"@prisma/query-plan-executor";var r;async function u(t){return r===void 0&&(r=await n.create({databaseUrl:t.db.connectionString,maxResponseSize:o("128 MiB"),queryTimeout:e("PT5M"),maxTransactionTimeout:e("PT5M"),maxTransactionWaitTime:e("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.debug?"debug":"off"}})),r}export{u as getQueryPlanExecutorServer,c as queryPlanExecutorVersion};
import{a,b}from"./chunk-SW3J2PL2.js";import"./chunk-ANHBRJRZ.js";import"./chunk-EDFHV3AK.js";import"./chunk-DOJAPHLY.js";export{b as createHTTPServer,a as wrap};
import{a as r}from"./chunk-SW3J2PL2.js";import"./chunk-ANHBRJRZ.js";import"./chunk-EDFHV3AK.js";import{a}from"./chunk-DOJAPHLY.js";function h(o,e,m){o.on("POST","/database/dump",r(async(p,t)=>{await e.db.dump(e.databaseDumpPath),a(t,{dumpPath:e.databaseDumpPath},201)},m)),o.on("GET","/health",r((p,t)=>{a(t,{name:e.name})},m))}export{h as registerUtilityRoutes};
+1
-1

@@ -1,1 +0,1 @@

import{a}from"./chunk-GMUOAEZU.js";import"./chunk-PP43TGA5.js";import"./chunk-KWCQYPJI.js";import"./chunk-2XJK3IOI.js";import"./chunk-EDFHV3AK.js";import"./chunk-HQMJSXYT.js";import"./chunk-DWY47FQV.js";import"./chunk-3UF2MBYQ.js";import{setTimeout as o}from"timers/promises";var e;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,e?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,e?.close().finally(()=>process.exit())});async function n(){let[,,t]=process.argv;if(!t)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{e=await a({debug:!0,persistenceMode:"stateful",name:t});let r=e.experimental.queryInsights,s={database:e.database,experimental:{queryInsights:{serverUrl:r.serverUrl,sqlitePath:r.sqlitePath,streamName:r.streamName,url:r.url},streams:e.experimental.streams},http:e.http,name:e.name,ppg:e.ppg,shadowDatabase:e.shadowDatabase};process.send?.({type:"started",server:s},void 0)}catch(r){console.error(r);let s=r instanceof Error?r.message:String(r);process.send?.({type:"error",error:s},void 0),await o(1e3),process.exit(1)}}n();
import{a}from"./chunk-FB4QA6EA.js";import"./chunk-662IKR3V.js";import"./chunk-PP43TGA5.js";import"./chunk-KWCQYPJI.js";import"./chunk-HFONW2ZS.js";import"./chunk-ANHBRJRZ.js";import"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";import"./chunk-DOJAPHLY.js";import{setTimeout as o}from"timers/promises";var e;process.once("SIGTERM",()=>{console.log("SIGTERM received, shutting down..."),process.removeAllListeners("SIGINT"),process.exitCode=143,e?.close().finally(()=>process.exit())});process.once("SIGINT",()=>{console.log("SIGINT received, shutting down..."),process.removeAllListeners("SIGTERM"),process.exitCode=130,e?.close().finally(()=>process.exit())});async function n(){let[,,t]=process.argv;if(!t)return process.send?.({type:"error",error:'Missing "name" argument, server cannot be started'},void 0),process.exit(1);try{e=await a({debug:!0,persistenceMode:"stateful",name:t});let r=e.experimental.queryInsights,s={database:e.database,experimental:{queryInsights:{serverUrl:r.serverUrl,sqlitePath:r.sqlitePath,streamName:r.streamName,url:r.url},streams:e.experimental.streams},http:e.http,name:e.name,ppg:e.ppg,shadowDatabase:e.shadowDatabase};process.send?.({type:"started",server:s},void 0)}catch(r){console.error(r);let s=r instanceof Error?r.message:String(r);process.send?.({type:"error",error:s},void 0),await o(1e3),process.exit(1)}}n();

@@ -1,1 +0,1 @@

import{a as i,b as j}from"./chunk-GMUOAEZU.js";import"./chunk-PP43TGA5.js";import{a as f,b as g}from"./chunk-KWCQYPJI.js";import{l as h}from"./chunk-2XJK3IOI.js";import{a,b,c,d,h as e}from"./chunk-EDFHV3AK.js";import"./chunk-HQMJSXYT.js";import"./chunk-DWY47FQV.js";import"./chunk-3UF2MBYQ.js";export{a as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,c as DEFAULT_SHADOW_DATABASE_PORT,d as DEFAULT_STREAMS_PORT,e as PortNotAvailableError,h as ServerAlreadyRunningError,f as copyPrismaDevRuntimeAssets,g as getPrismaDevRuntimeAssetManifest,i as startPrismaDevServer,j as unstable_startServer};
import{a as i,b as j}from"./chunk-FB4QA6EA.js";import"./chunk-662IKR3V.js";import"./chunk-PP43TGA5.js";import{a as f,b as g}from"./chunk-KWCQYPJI.js";import{l as h}from"./chunk-HFONW2ZS.js";import"./chunk-ANHBRJRZ.js";import{a,b,c,d,h as e}from"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";import"./chunk-DOJAPHLY.js";export{a as DEFAULT_DATABASE_PORT,b as DEFAULT_SERVER_PORT,c as DEFAULT_SHADOW_DATABASE_PORT,d as DEFAULT_STREAMS_PORT,e as PortNotAvailableError,h as ServerAlreadyRunningError,f as copyPrismaDevRuntimeAssets,g as getPrismaDevRuntimeAssetManifest,i as startPrismaDevServer,j as unstable_startServer};

@@ -1,3 +0,3 @@

"use strict";var Te=Object.create;var O=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Me=Object.prototype.hasOwnProperty;var Oe=(t,e)=>{for(var r in e)O(t,r,{get:e[r],enumerable:!0})},re=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ee(e))!Me.call(t,n)&&n!==r&&O(t,n,{get:()=>e[n],enumerable:!(o=_e(e,n))||o.enumerable});return t};var T=(t,e,r)=>(r=t!=null?Te($e(t)):{},re(e||!t||!t.__esModule?O(r,"default",{value:t,enumerable:!0}):r,t)),ke=t=>re(O({},"__esModule",{value:!0}),t);var Je={};Oe(Je,{ServerAlreadyRunningError:()=>U,ServerState:()=>f,ServerStateAlreadyExistsError:()=>N,deleteServer:()=>Ke,getServerStatus:()=>te,isServerRunning:()=>Se,killServer:()=>De});module.exports=ke(Je);var we=require("fs/promises"),v=require("pathe"),x=require("proper-lockfile"),Z=require("std-env"),s=require("valibot");var se=require("fs"),m=require("fs/promises"),oe=require("util"),ae=require("zlib");var d=T(require("path"),1),q=T(require("os"),1),k=T(require("process"),1),b=q.default.homedir(),B=q.default.tmpdir(),{env:S}=k.default,Re=t=>{let e=d.default.join(b,"Library");return{data:d.default.join(e,"Application Support",t),config:d.default.join(e,"Preferences",t),cache:d.default.join(e,"Caches",t),log:d.default.join(e,"Logs",t),temp:d.default.join(B,t)}},Ae=t=>{let e=S.APPDATA||d.default.join(b,"AppData","Roaming"),r=S.LOCALAPPDATA||d.default.join(b,"AppData","Local");return{data:d.default.join(r,t,"Data"),config:d.default.join(e,t,"Config"),cache:d.default.join(r,t,"Cache"),log:d.default.join(r,t,"Log"),temp:d.default.join(B,t)}},Ie=t=>{let e=d.default.basename(b);return{data:d.default.join(S.XDG_DATA_HOME||d.default.join(b,".local","share"),t),config:d.default.join(S.XDG_CONFIG_HOME||d.default.join(b,".config"),t),cache:d.default.join(S.XDG_CACHE_HOME||d.default.join(b,".cache"),t),log:d.default.join(S.XDG_STATE_HOME||d.default.join(b,".local","state"),t),temp:d.default.join(B,e,t)}};function C(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),k.default.platform==="darwin"?Re(t):k.default.platform==="win32"?Ae(t):Ie(t)}var ne=T(require("zeptomatch"),1),V=C("prisma-dev"),Qe=(0,oe.promisify)(ae.unzip);function D(t){return`${V.data}/${t}`}function ie(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function ue(t){try{return await(0,m.readFile)(t,{encoding:"utf-8"})}catch(e){if(ie(e))return null;throw e}}async function ce(t){await(0,m.mkdir)(t,{recursive:!0})}async function de(t,e){try{return(await(0,m.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,ne.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(ie(r))return[];throw r}}async function F(t){await(0,m.rm)(t,{force:!0,recursive:!0})}var le=require("timers/promises"),E=require("std-env");function G(t,e){if(t==null)return!1;try{return E.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}async function pe(t,e){if(!E.process.kill)return!1;try{E.process.kill(t,"SIGTERM")}catch(o){return e&&console.error(`Error killing process with PID ${t}:`,o),!1}let r=0;do{if(!G(t,e))return!0;await(0,le.setTimeout)(100)}while(++r<50);try{return E.process.kill(t,"SIGKILL")}catch(o){return e&&console.error(`Error forcefully killing process with PID ${t}:`,o),!1}}var g=require("get-port-please"),I=require("remeda"),me=51214,he=51213,fe=51215,Pe=51216,R=65535,y=0,p=-1/0;async function W(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:a,portsUsedByThisServerLastTime:i}=je(r,n);e&&(console.debug(`ports used by other servers: ${Object.keys(a).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(i)}`));let u={databasePort:p,port:p,shadowDatabasePort:p,streamsPort:p},c=["port","databasePort","shadowDatabasePort","streamsPort"];for(let l of c){let h=await Ne({debug:e,portKey:l,portsUsedByOtherServers:a,portsUsedByThisServerLastTime:i,requestedPorts:o})??await Ue({debug:e,pickedPorts:u,portKey:l,portsUsedByOtherServers:a,portsUsedByThisServerLastTime:i});e&&console.debug(`Got port for "${l}": ${h}`),u[l]=h}return e&&console.debug(`Picked ports: ${JSON.stringify(u)}`),u}async function Ne(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:a}=t,{[r]:i,...u}=a;if(H(i))return await Be({debug:e,otherRequestedPorts:u,portKey:r,portsUsedByOtherServers:o,requestedPort:i}),i;let c=n?.[r]??p;if(!H(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=c in o;return l||Object.values(u).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,g.checkPort)(c)===!1?(e&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function Ue(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:a}=t,i=Math.max(me,he,fe,Pe)+1,u=Object.values(r).filter(P=>P!==void 0),c=a?qe(a):[],l=[...u,...Object.keys(n).map(Number),...c],h=Math.min(Math.max(i,...l)+100,R),j=(0,I.difference)((0,I.range)(i,h),l),w={port:he,databasePort:me,shadowDatabasePort:fe,streamsPort:Pe}[o];try{return await(0,g.getPort)({port:w in n||u.includes(w)||c.includes(w)?void 0:w,ports:j})}catch(P){if(P instanceof Error&&P.name==="GetPortError"&&h+1<=R)return e&&console.debug(`Expanding port lookup to range [${h+1}, ${R}].`),await(0,g.getPort)({portRange:[h+1,R]});throw P}}function H(t){return Number.isFinite(t)&&t>=0}function je(t,e){let r={},o;for(let n of e){let{databasePort:a,port:i,shadowDatabasePort:u}=n,c=Le(n);if(n.name===t){o={databasePort:a,port:i,shadowDatabasePort:u,streamsPort:c};continue}r[a]=!0,r[i]=!0,r[u]=!0,H(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:o}}function Le(t){let e=t.experimental?.streams?.serverUrl;if(!e)return p;try{let r=Number(new URL(e).port);return Number.isInteger(r)&&r>0?r:p}catch{return p}}function qe(t){return[t.port,t.databasePort,t.shadowDatabasePort,t.streamsPort]}async function Be(t){let{debug:e,otherRequestedPorts:r,portKey:o,portsUsedByOtherServers:n,requestedPort:a}=t;if(a!==y){if(a in n)throw e&&console.error(`Port ${a} was requested for "${o}", but is already used by another server.`),new J(a);if(Object.values(r).includes(a))throw e&&console.error(`Port ${a} was requested for "${o}", but also for another key.`),new K(a);if((0,g.isUnsafePort)(a))throw e&&console.error(`Port ${a} was requested for "${o}", but is unsafe.`),new A(a);if(await(0,g.checkPort)(a)===!1)throw e&&console.error(`Port ${a} was requested for "${o}", but is not available.`),new A(a)}}var A=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},K=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"},J=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 X=require("pathe");function Ce(){return(0,X.join)(V.data,"durable-streams")}function be(t){return(0,X.join)(Ce(),t)}var M=(0,s.pipe)((0,s.string)(),(0,s.url)()),ge=(0,s.object)({connectionString:M,prismaORMConnectionString:(0,s.optional)(M),terminalCommand:(0,s.optional)((0,s.string)())}),ye=(0,s.object)({url:M}),ve=(0,s.object)({serverUrl:M,sqlitePath:(0,s.pipe)((0,s.string)(),(0,s.minLength)(1)),streamName:(0,s.pipe)((0,s.string)(),(0,s.minLength)(1)),url:M}),Ve=(0,s.object)({queryInsights:(0,s.optional)(ve),streams:(0,s.optional)(ve)}),Y=(0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(1)),Fe=(0,s.object)({database:ge,http:ye,ppg:ye,shadowDatabase:ge}),Ge=(0,s.object)({databasePort:Y,experimental:(0,s.optional)(Ve),exports:(0,s.optional)(Fe),name:(0,s.pipe)((0,s.string)(),(0,s.minLength)(1)),pid:(0,s.optional)((0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(0))),port:Y,shadowDatabasePort:Y,version:(0,s.literal)("1")}),ee=Symbol("initialize"),z="default",He=new Set(["durable-streams"]),f=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(e){this._databasePort=e.databasePort??p,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??z,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Z.process.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??p,this._shadowDatabasePort=e.shadowDatabasePort??p,this._streamsPort=e.streamsPort??p}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new $(e):new Q(e);return await r[ee](),r}static async fromServerDump(e){let{debug:r,name:o=z}=e??{},n=D(o),a=$.getServerDumpPath(n),i=await ue(a);if(i==null)return r&&console.debug(`[State] No server dump file found at: ${a}`),null;r&&(console.debug(`[State] server dump file found at "${a}":`),console.debug(i));let{issues:u,output:c,success:l}=(0,s.safeParse)((0,s.pipe)((0,s.string)(),(0,s.parseJson)(),Ge),i);if(!l)throw r&&console.debug(`[State] Invalid server dump file at "${a}":
${JSON.stringify(u,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new $({databasePort:c.databasePort,debug:r,dryRun:!1,name:o,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r,globs:o}=e??{},n=(0,v.join)(D(z),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let a=(await de(n,o)).filter(i=>!He.has(i));return r&&console.debug(`[State] found server names: ${JSON.stringify(a)}`),await Promise.all(a.map(i=>te(i,e)))}get databasePort(){return this._databasePort}set databasePort(e){this.#t("databasePort",e)}get port(){return this._port}set port(e){this.#t("port",e)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(e){this.#t("shadowDatabasePort",e)}#t(e,r){if(r<0||!Number.isInteger(r))throw new Error(`Invalid port number: ${r}`);let o=`_${e}`;if(this[o]!==y&&this[o]!==r)throw new Error(`\`${e}\` is already set to ${this[o]}, cannot change it to ${r}`);this[o]=r}},Q=class extends f{constructor(e){super({...e,databasePort:e?.databasePort||y,persistenceMode:"stateless",port:e?.port||y,shadowDatabasePort:e?.shadowDatabasePort||y,streamsPort:e?.streamsPort||y})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[ee](){let e;try{e=await f.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let r=await W({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort}async close(){}async writeServerDump(){}},$=class t extends f{#t;#e;#s;#a;#n;#o;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#o=!1,this.#e=D(this.name),this.#t=(0,v.join)(this.#e,"db_dump.bak"),this.#s=(0,v.join)(this.#e,".lock"),this.#a=(0,v.join)(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#n=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,v.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get experimental(){return this.#r?.experimental}get pgliteDataDirPath(){return this.#a}async[ee](){await ce(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,x.lock)(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await f.scan({debug:this.debug,onlyMetadata:!0}),r=await W({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new U(this):e}}async close(){if(!this.#o)try{await(0,x.unlock)(this.#e,{lockfilePath:this.#s}),this.#o=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e,r){this.#r={name:this.name,version:"1",pid:Z.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,we.writeFile)(this.#n,`${JSON.stringify(this.#r,null,2)}
`,{encoding:"utf-8"})}};async function Ke(t,e){await De(t,e);let r=typeof t=="string"?t:t.name,o=D(r);await F(o),await F(be(r))}async function te(t,e){let{debug:r,onlyMetadata:o}=e||{},n=typeof t=="string"?t:t.name,a=typeof t!="string"?t:void 0,i={databasePort:a?.databasePort??-1,experimental:a?.experimental,exports:a?.exports,name:n,pid:a?.pid,port:a?.port??-1,shadowDatabasePort:a?.shadowDatabasePort??-1,version:"1"};try{let u=a||await f.fromServerDump({debug:r,name:n});if(!u)return r&&console.debug(`[State] no server state found for name: ${n}`),{...i,status:"no_such_server"};i.databasePort=u.databasePort,i.experimental=u.experimental,i.exports=u.exports,i.pid=u.pid,i.port=u.port,i.shadowDatabasePort=u.shadowDatabasePort;let{exports:c,pid:l}=u;if(o)return{...i,status:"unknown"};if(!G(l,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${l}`),{...i,status:"not_running"};let h=D(n);try{if(!await(0,x.check)(h,{lockfilePath:(0,v.join)(h,".lock")}))return r&&console.debug(`[State] server state for "${n}" is not locked, indicating it is not running.`),{...i,status:"not_running"}}catch(xe){r&&console.error(`[State] server state for "${n}" failed to check lock:`,xe)}if(!c)return{...i,status:"starting_up"};let{http:j}=c,{hc:w}=await import("hono/client"),P=await w(j.url).health.$get();if(!P.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(P)}`),{...i,status:"not_running"};let L=await P.json();return L.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(L)}`),{...i,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(L)}`),{...i,status:"running"})}catch(u){return r&&console.error(`[State] failed to get server status for "${n}":`,u),{...i,status:"error"}}}function Se(t){let{status:e}=t;return e==="running"||e==="starting_up"}async function De(t,e){let{pid:r,...o}=typeof t=="string"?await te(t,{debug:e}):t;if(!Se(o))return!1;let n=await f.fromServerDump({debug:e,name:o.name});if(r==null){e&&console.debug(`[State] No PID found for server "${o.name}" to kill.`);try{await n?.close()}catch{}return!1}let a=await pe(r,e);try{await n?.close()}catch{}return a}var N=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},U=class extends N{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return f.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError,deleteServer,getServerStatus,isServerRunning,killServer});
"use strict";var xe=Object.create;var M=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Ee=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var Me=(t,e)=>{for(var r in e)M(t,r,{get:e[r],enumerable:!0})},te=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of _e(e))!$e.call(t,n)&&n!==r&&M(t,n,{get:()=>e[n],enumerable:!(o=Te(e,n))||o.enumerable});return t};var O=(t,e,r)=>(r=t!=null?xe(Ee(t)):{},te(e||!t||!t.__esModule?M(r,"default",{value:t,enumerable:!0}):r,t)),Oe=t=>te(M({},"__esModule",{value:!0}),t);var He={};Me(He,{ServerAlreadyRunningError:()=>U,ServerState:()=>f,ServerStateAlreadyExistsError:()=>N,deleteServer:()=>Ke,getServerStatus:()=>ee,isServerRunning:()=>Se,killServer:()=>we});module.exports=Oe(He);var ve=require("fs/promises"),S=require("pathe"),x=require("proper-lockfile"),Q=require("std-env"),s=require("valibot");var re=require("fs"),m=require("fs/promises"),se=require("util"),oe=require("zlib");var d=O(require("path"),1),L=O(require("os"),1),k=O(require("process"),1),g=L.default.homedir(),q=L.default.tmpdir(),{env:w}=k.default,ke=t=>{let e=d.default.join(g,"Library");return{data:d.default.join(e,"Application Support",t),config:d.default.join(e,"Preferences",t),cache:d.default.join(e,"Caches",t),log:d.default.join(e,"Logs",t),temp:d.default.join(q,t)}},Ae=t=>{let e=w.APPDATA||d.default.join(g,"AppData","Roaming"),r=w.LOCALAPPDATA||d.default.join(g,"AppData","Local");return{data:d.default.join(r,t,"Data"),config:d.default.join(e,t,"Config"),cache:d.default.join(r,t,"Cache"),log:d.default.join(r,t,"Log"),temp:d.default.join(q,t)}},Re=t=>{let e=d.default.basename(g);return{data:d.default.join(w.XDG_DATA_HOME||d.default.join(g,".local","share"),t),config:d.default.join(w.XDG_CONFIG_HOME||d.default.join(g,".config"),t),cache:d.default.join(w.XDG_CACHE_HOME||d.default.join(g,".cache"),t),log:d.default.join(w.XDG_STATE_HOME||d.default.join(g,".local","state"),t),temp:d.default.join(q,e,t)}};function B(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),k.default.platform==="darwin"?ke(t):k.default.platform==="win32"?Ae(t):Re(t)}var ae=O(require("zeptomatch"),1),C=B("prisma-dev"),ze=(0,se.promisify)(oe.unzip);function D(t){return`${C.data}/${t}`}function ne(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function ie(t){try{return await(0,m.readFile)(t,{encoding:"utf-8"})}catch(e){if(ne(e))return null;throw e}}async function ue(t){await(0,m.mkdir)(t,{recursive:!0})}async function ce(t,e){try{return(await(0,m.readdir)(t,{withFileTypes:!0})).reduce((o,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&(!e||(0,ae.default)(e,n.name))&&o.push(n.name),o),[])}catch(r){if(ne(r))return[];throw r}}async function V(t){await(0,m.rm)(t,{force:!0,recursive:!0})}var de=require("timers/promises"),_=require("std-env");function F(t,e){if(t==null)return!1;try{return _.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}async function le(t,e){if(!_.process.kill)return!1;try{_.process.kill(t,"SIGTERM")}catch(o){return e&&console.error(`Error killing process with PID ${t}:`,o),!1}let r=0;do{if(!F(t,e))return!0;await(0,de.setTimeout)(100)}while(++r<50);try{return _.process.kill(t,"SIGKILL")}catch(o){return e&&console.error(`Error forcefully killing process with PID ${t}:`,o),!1}}var y=require("get-port-please"),I=require("remeda"),pe=51214,me=51213,he=51215,fe=51216,A=65535,v=0,p=-1/0;async function J(t){let{debug:e,name:r,requestedPorts:o,servers:n}=t,{portsUsedByOtherServers:a,portsUsedByThisServerLastTime:i}=Ue(r,n);e&&(console.debug(`ports used by other servers: ${Object.keys(a).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(i)}`));let u={databasePort:p,port:p,shadowDatabasePort:p,streamsPort:p},c=["port","databasePort","shadowDatabasePort","streamsPort"];for(let l of c){let h=await Ie({debug:e,portKey:l,portsUsedByOtherServers:a,portsUsedByThisServerLastTime:i,requestedPorts:o})??await Ne({debug:e,pickedPorts:u,portKey:l,portsUsedByOtherServers:a,portsUsedByThisServerLastTime:i});e&&console.debug(`Got port for "${l}": ${h}`),u[l]=h}return e&&console.debug(`Picked ports: ${JSON.stringify(u)}`),u}async function Ie(t){let{debug:e,portKey:r,portsUsedByOtherServers:o,portsUsedByThisServerLastTime:n,requestedPorts:a}=t,{[r]:i,...u}=a;if(G(i))return await qe({debug:e,otherRequestedPorts:u,portKey:r,portsUsedByOtherServers:o,requestedPort:i}),i;let c=n?.[r]??p;if(!G(c))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let l=c in o;return l||Object.values(u).includes(c)?(e&&console.debug(`Port ${c} that was used last time for this server, ${l?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,y.checkPort)(c)===!1?(e&&console.debug(`Port ${c}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${c} for "${r}" as it was used last time and is available.`),c)}async function Ne(t){let{debug:e,pickedPorts:r,portKey:o,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:a}=t,i=Math.max(pe,me,he,fe)+1,u=Object.values(r).filter(P=>P!==void 0),c=a?Le(a):[],l=[...u,...Object.keys(n).map(Number),...c],h=Math.min(Math.max(i,...l)+100,A),j=(0,I.difference)((0,I.range)(i,h),l),b={port:me,databasePort:pe,shadowDatabasePort:he,streamsPort:fe}[o];try{return await(0,y.getPort)({port:b in n||u.includes(b)||c.includes(b)?void 0:b,ports:j})}catch(P){if(P instanceof Error&&P.name==="GetPortError"&&h+1<=A)return e&&console.debug(`Expanding port lookup to range [${h+1}, ${A}].`),await(0,y.getPort)({portRange:[h+1,A]});throw P}}function G(t){return Number.isFinite(t)&&t>=0}function Ue(t,e){let r={},o;for(let n of e){let{databasePort:a,port:i,shadowDatabasePort:u}=n,c=je(n);if(n.name===t){o={databasePort:a,port:i,shadowDatabasePort:u,streamsPort:c};continue}r[a]=!0,r[i]=!0,r[u]=!0,G(c)&&(r[c]=!0)}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:o}}function je(t){let e=t.experimental?.streams?.serverUrl;if(!e)return p;try{let r=Number(new URL(e).port);return Number.isInteger(r)&&r>0?r:p}catch{return p}}function Le(t){return[t.port,t.databasePort,t.shadowDatabasePort,t.streamsPort]}async function qe(t){let{debug:e,otherRequestedPorts:r,portKey:o,portsUsedByOtherServers:n,requestedPort:a}=t;if(a!==v){if(a in n)throw e&&console.error(`Port ${a} was requested for "${o}", but is already used by another server.`),new H(a);if(Object.values(r).includes(a))throw e&&console.error(`Port ${a} was requested for "${o}", but also for another key.`),new K(a);if((0,y.isUnsafePort)(a))throw e&&console.error(`Port ${a} was requested for "${o}", but is unsafe.`),new R(a);if(await(0,y.checkPort)(a)===!1)throw e&&console.error(`Port ${a} was requested for "${o}", but is not available.`),new R(a)}}var R=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},K=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"},H=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 W=require("pathe");function Be(){return(0,W.join)(C.data,"durable-streams")}function Pe(t){return(0,W.join)(Be(),t)}var $=(0,s.pipe)((0,s.string)(),(0,s.url)()),be=(0,s.object)({connectionString:$,prismaORMConnectionString:(0,s.optional)($),terminalCommand:(0,s.optional)((0,s.string)())}),ge=(0,s.object)({url:$}),ye=(0,s.object)({serverUrl:$,sqlitePath:(0,s.pipe)((0,s.string)(),(0,s.minLength)(1)),streamName:(0,s.pipe)((0,s.string)(),(0,s.minLength)(1)),url:$}),Ce=(0,s.object)({queryInsights:(0,s.optional)(ye),streams:(0,s.optional)(ye)}),X=(0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(1)),Ve=(0,s.object)({database:be,http:ge,ppg:ge,shadowDatabase:be}),Fe=(0,s.object)({databasePort:X,experimental:(0,s.optional)(Ce),exports:(0,s.optional)(Ve),name:(0,s.pipe)((0,s.string)(),(0,s.minLength)(1)),pid:(0,s.optional)((0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(0))),port:X,shadowDatabasePort:X,version:(0,s.literal)("1")}),Z=Symbol("initialize"),Y="default",Ge=new Set(["durable-streams"]),f=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(e){this._databasePort=e.databasePort??p,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??Y,this.persistenceMode=e.persistenceMode,this.pid=e.pid??Q.process.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??p,this._shadowDatabasePort=e.shadowDatabasePort??p,this._streamsPort=e.streamsPort??p}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new E(e):new z(e);return await r[Z](),r}static async fromServerDump(e){let{debug:r,name:o=Y}=e??{},n=D(o),a=E.getServerDumpPath(n),i=await ie(a);if(i==null)return r&&console.debug(`[State] No server dump file found at: ${a}`),null;r&&(console.debug(`[State] server dump file found at "${a}":`),console.debug(i));let{issues:u,output:c,success:l}=(0,s.safeParse)((0,s.pipe)((0,s.string)(),(0,s.parseJson)(),Fe),i);if(!l)throw r&&console.debug(`[State] Invalid server dump file at "${a}":
${JSON.stringify(u,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new E({databasePort:c.databasePort,debug:r,dryRun:!1,name:o,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r,globs:o}=e??{},n=(0,S.join)(D(Y),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let a=(await ce(n,o)).filter(i=>!Ge.has(i));return r&&console.debug(`[State] found server names: ${JSON.stringify(a)}`),await Promise.all(a.map(i=>ee(i,e)))}get databasePort(){return this._databasePort}set databasePort(e){this.#t("databasePort",e)}get port(){return this._port}set port(e){this.#t("port",e)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(e){this.#t("shadowDatabasePort",e)}#t(e,r){if(r<0||!Number.isInteger(r))throw new Error(`Invalid port number: ${r}`);let o=`_${e}`;if(this[o]!==v&&this[o]!==r)throw new Error(`\`${e}\` is already set to ${this[o]}, cannot change it to ${r}`);this[o]=r}},z=class extends f{constructor(e){super({...e,databasePort:e?.databasePort||v,persistenceMode:"stateless",port:e?.port||v,shadowDatabasePort:e?.shadowDatabasePort||v,streamsPort:e?.streamsPort||v})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[Z](){let e;try{e=await f.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let r=await J({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort}async close(){}async writeServerDump(){}},E=class t extends f{#t;#e;#s;#a;#n;#o;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#o=!1,this.#e=D(this.name),this.#t=(0,S.join)(this.#e,"db_dump.bak"),this.#s=(0,S.join)(this.#e,".lock"),this.#a=(0,S.join)(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#n=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,S.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get experimental(){return this.#r?.experimental}get pgliteDataDirPath(){return this.#a}async[Z](){await ue(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,x.lock)(this.#e,{lockfilePath:this.#s}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await f.scan({debug:this.debug,onlyMetadata:!0}),r=await J({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,this._streamsPort=r.streamsPort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new U(this):e}}async close(){if(!this.#o)try{await(0,x.unlock)(this.#e,{lockfilePath:this.#s}),this.#o=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e,r){this.#r={name:this.name,version:"1",pid:Q.process.pid,port:this.port,databasePort:this.databasePort,experimental:r,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,ve.writeFile)(this.#n,`${JSON.stringify(this.#r,null,2)}
`,{encoding:"utf-8"})}};async function Ke(t,e){await we(t,e);let r=typeof t=="string"?t:t.name,o=D(r);await V(o),await V(Pe(r))}async function ee(t,e){let{debug:r,onlyMetadata:o}=e||{},n=typeof t=="string"?t:t.name,a=typeof t!="string"?t:void 0,i={databasePort:a?.databasePort??-1,experimental:a?.experimental,exports:a?.exports,name:n,pid:a?.pid,port:a?.port??-1,shadowDatabasePort:a?.shadowDatabasePort??-1,version:"1"};try{let u=a||await f.fromServerDump({debug:r,name:n});if(!u)return r&&console.debug(`[State] no server state found for name: ${n}`),{...i,status:"no_such_server"};i.databasePort=u.databasePort,i.experimental=u.experimental,i.exports=u.exports,i.pid=u.pid,i.port=u.port,i.shadowDatabasePort=u.shadowDatabasePort;let{exports:c,pid:l}=u;if(o)return{...i,status:"unknown"};if(!F(l,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${l}`),{...i,status:"not_running"};let h=D(n);try{if(!await(0,x.check)(h,{lockfilePath:(0,S.join)(h,".lock")}))return r&&console.debug(`[State] server state for "${n}" is not locked, indicating it is not running.`),{...i,status:"not_running"}}catch(De){r&&console.error(`[State] server state for "${n}" failed to check lock:`,De)}if(!c)return{...i,status:"starting_up"};let{http:j}=c,b=await fetch(`${j.url}/health`,{headers:{connection:"close"}});if(!b.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(b)}`),{...i,status:"not_running"};let P=await b.json();return P.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(P)}`),{...i,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(P)}`),{...i,status:"running"})}catch(u){return r&&console.error(`[State] failed to get server status for "${n}":`,u),{...i,status:"error"}}}function Se(t){let{status:e}=t;return e==="running"||e==="starting_up"}async function we(t,e){let{pid:r,...o}=typeof t=="string"?await ee(t,{debug:e}):t;if(!Se(o))return!1;let n=await f.fromServerDump({debug:e,name:o.name});if(r==null){e&&console.debug(`[State] No PID found for server "${o.name}" to kill.`);try{await n?.close()}catch{}return!1}let a=await le(r,e);try{await n?.close()}catch{}return a}var N=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},U=class extends N{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return f.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError,deleteServer,getServerStatus,isServerRunning,killServer});

@@ -1,1 +0,1 @@

import{f as a,g as b,h as c,i as d,j as e,k as f,l as g}from"./chunk-2XJK3IOI.js";import"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";export{g as ServerAlreadyRunningError,a as ServerState,f as ServerStateAlreadyExistsError,b as deleteServer,c as getServerStatus,d as isServerRunning,e as killServer};
import{f as a,g as b,h as c,i as d,j as e,k as f,l as g}from"./chunk-HFONW2ZS.js";import"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";export{g as ServerAlreadyRunningError,a as ServerState,f as ServerStateAlreadyExistsError,b as deleteServer,c as getServerStatus,d as isServerRunning,e as killServer};
{
"name": "@prisma/dev",
"version": "0.24.13",
"version": "0.24.14",
"description": "A local Prisma Postgres server for development and testing",

@@ -84,10 +84,8 @@ "type": "module",

"@electric-sql/pglite-tools": "0.3.3",
"@hono/node-server": "^1.19.14",
"@prisma/get-platform": "7.2.0",
"@prisma/query-plan-executor": "7.2.0",
"@prisma/streams-local": "0.1.11",
"find-my-way": "9.6.0",
"foreground-child": "3.3.1",
"get-port-please": "3.2.0",
"hono": "^4.12.23",
"http-status-codes": "2.3.0",
"pathe": "2.0.3",

@@ -94,0 +92,0 @@ "proper-lockfile": "4.1.2",

import{b as s}from"./chunk-3UF2MBYQ.js";import{HTTPException as Pn}from"hono/http-exception";import{Hono as xn}from"hono/tiny";import{validator as u}from"hono/validator";import{array as X,literal as G,minLength as Y,object as Z,pipe as K,safeParse as J,string as nn,union as tn}from"valibot";var en=Z({tags:tn([K(X(nn()),Y(1)),G("all")])});async function C(n){let{output:r,success:t}=J(en,await n.req.json(),{abortEarly:!0});return t?r:n.text("Invalid input",400)}import{Buffer as A}from"buffer";var h=new Map;async function x(n){let t=new TextEncoder().encode(n),e=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(e)).map(a=>a.toString(16).padStart(2,"0")).join("")}function q(n){let r=n.req.param("schemaHash"),t=h.get(r);return t==null?n.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:r,schemas:t}}async function v(n,r,t){let e=A.from(n,"base64").toString("utf8"),o=on(e,r.toString());t&&console.log("[Accelerate] schema with override:",o);let i=await x(o);return{base64Override:A.from(o,"utf8").toString("base64"),overrideHash:i}}var rn=" ";function on(n,r){let t=an(n);if(!t)throw new Error("No datasource block found in schema.");let e=n.slice(t.openBraceIndex+1,t.closeBraceIndex),o=un(e,r,mn(n,t.openBraceIndex));return`${n.slice(0,t.openBraceIndex+1)}${o}${n.slice(t.closeBraceIndex)}`}function an(n){let r="datasource";for(let t=0;t<n.length;t+=1){let e=n[t];if(e==="/"&&n[t+1]==="/"){t=$(n,t+2);continue}if(e==="/"&&n[t+1]==="*"){t=E(n,t+2);continue}if(e==='"'){t=T(n,t+1);continue}if(n.startsWith(r,t)&&!R(n[t-1])&&!R(n[t+r.length])){let o=sn(n,t+r.length,"{");if(o===-1)return null;let i=cn(n,o);return i===-1?null:{closeBraceIndex:i,openBraceIndex:o}}}return null}function sn(n,r,t){for(let e=r;e<n.length;e+=1){let o=n[e];if(o==="/"&&n[e+1]==="/"){e=$(n,e+2);continue}if(o==="/"&&n[e+1]==="*"){e=E(n,e+2);continue}if(o==='"'){e=T(n,e+1);continue}if(o===t)return e}return-1}function cn(n,r){let t=0;for(let e=r;e<n.length;e+=1){let o=n[e];if(o==="/"&&n[e+1]==="/"){e=$(n,e+2);continue}if(o==="/"&&n[e+1]==="*"){e=E(n,e+2);continue}if(o==='"'){e=T(n,e+1);continue}if(o==="{"){t+=1;continue}if(o==="}"&&(t-=1,t===0))return e}return-1}function $(n,r){let t=r;for(;t<n.length&&n[t]!==`
`;)t+=1;return t}function E(n,r){let t=n.indexOf("*/",r);return t===-1?n.length:t+1}function T(n,r){let t=r;for(;t<n.length;){if(n[t]==="\\"){t+=2;continue}if(n[t]==='"')return t;t+=1}return n.length}function R(n){return n!=null&&/[A-Za-z0-9_]/.test(n)}function un(n,r,t){let e=`"${dn(r)}"`,o=fn(n);for(let[m,O]of o.entries()){let{comment:Q,code:W}=B(O.line),p=W.match(/^(\s*)url(\s*)=(\s*).*/);if(p)return o[m]={line:`${p[1]}url${p[2]}=${p[3]}${e}${Q}`,terminator:O.terminator},P(o)}let i=pn(n),a=ln(o,t),c=`${a}url = ${e}`;if(!n.includes(`
`)&&!n.includes("\r")){let m=n.trim();return m.length===0?`${i}${c}${i}${t}`:`${i}${a}${m}${i}${c}${i}${t}`}let f=o.at(-1);if(f&&f.terminator===""&&/^\s*$/.test(f.line))return`${P(o.slice(0,-1))}${c}${i}${t}`;let w=P(o),z=w.endsWith(`
`)||w.endsWith("\r")?"":i;return`${w}${z}${c}${i}${t}`}function fn(n){let r=[],t=0;for(let e=0;e<n.length;e+=1){if(n[e]==="\r"&&n[e+1]===`
`){r.push({line:n.slice(t,e),terminator:`\r
`}),e+=1,t=e+1;continue}(n[e]===`
`||n[e]==="\r")&&(r.push({line:n.slice(t,e),terminator:n[e]}),t=e+1)}return(t<n.length||n.length===0)&&r.push({line:n.slice(t),terminator:""}),r}function P(n){return n.map(r=>`${r.line}${r.terminator}`).join("")}function B(n){let r=!1,t=!1;for(let e=0;e<n.length;e+=1){let o=n[e];if(t){if(r){r=!1;continue}if(o==="\\"){r=!0;continue}o==='"'&&(t=!1);continue}if(o==='"'){t=!0;continue}if(o==="/"&&n[e+1]==="/")return{code:n.slice(0,e),comment:n.slice(e)}}return{code:n,comment:""}}function ln(n,r){for(let t of n){let{code:e}=B(t.line),o=e.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(o?.[1])return o[1]}return`${r}${rn}`}function mn(n,r){let t=n.lastIndexOf(`
`,r)+1,e=t;for(;n[e]===" "||n[e]===" ";)e+=1;return n.slice(t,e)}function pn(n){return n.includes(`\r
`)?`\r
`:`
`}function dn(n){return n.replaceAll("\\","\\\\").replaceAll('"','\\"')}function S(n){let{req:r}=n;return{traceparent:r.header("traceparent"),"X-capture-telemetry":r.header("X-capture-telemetry")}}import{integer as L,looseObject as gn,minValue as _,number as b,object as hn,optional as Sn,pipe as M,safeParse as j,string as V,union as yn}from"valibot";var In=hn({isolation_level:Sn(V()),max_wait:M(b(),L(),_(0)),timeout:M(b(),L(),_(0))});async function D(n){let{issues:r,output:t,success:e}=j(In,await n.req.json(),{abortEarly:!0});return e?t:n.json({EngineNotStarted:{reason:"InvalidRequest",issues:r}},400)}var wn=gn({id:yn([V(),b()])});function N(n,r){let{output:t,success:e}=j(wn,n);return e?t:r.json({EngineMalfunction:{}},500)}var U,k,F;function y(){return U??=import("./engine-XP6YJ63T.js"),U}function $n(){return F??=import("./query-plan-executor-F6RXHJSD.js"),F}async function En(){return k??=import("@prisma/get-platform").then(async({default:n})=>await n.getPlatformInfo()),await k}var I=new xn;I.post("/invalidate",u("header",s),async n=>{let r=await C(n);return r instanceof Response?r:n.body(null)});var Tn="/:clientVersion/:schemaHash",l=I.basePath(Tn);I.route("/",l);var bn=["/graphql","/itx/:transactionId/graphql"];l.on("POST",[...bn],u("header",s),async n=>{let{req:r}=n;try{let t=await H(n);if(t instanceof Response)return t;let e=await r.text(),o=r.param("transactionId"),i=await t.request(e,{...S(n),"X-transaction-id":o});return n.text(i)}catch(t){let{handleEngineError:e}=await y();return e(t,n)}});l.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],u("header",s),async n=>{let{req:r}=n;try{let t=await H(n);if(t instanceof Response)return t;let o=`${r.routePath.split("/").filter(Boolean).at(-1)}Transaction`,i=r.param("transactionId"),a=await t[o](i,S(n));return n.json(a)}catch(t){let{handleEngineError:e}=await y();return e(t,n)}});l.put("/schema",u("header",s),async n=>{let{req:r}=n,t=await r.text();if(!t)return n.text("Missing schema",400);let e=r.param("schemaHash"),o=h.get(e);if(o==null){if(e!==await x(t))return n.text("Schema hash mismatch",400);let i=await v(t,n.get("db").prismaORMConnectionString,n.get("debug"));return h.set(e,{base64Original:t,...i}),n.text(e)}return t!==o.base64Original?n.text("Schema mismatch",400):n.text(e)});l.post("/transaction/start",u("header",s),async n=>{let{req:r}=n,t=await D(n);if(t instanceof Response)return t;try{let e=await H(n);if(e instanceof Response)return e;let o=await e.startTransaction(t,S(n)),i=N(o,n);if(i instanceof Response)return i;let{id:a}=i,c=r.param("clientVersion"),f=r.param("schemaHash");return n.json({...o,"data-proxy":{endpoint:`${new URL(r.url).origin}/${c}/${f}/itx/${a}`}})}catch(e){let{handleEngineError:o}=await y();return o(e,n)}});async function H(n){let{req:r}=n,{Engine:t}=await y(),e=q(n);if(e instanceof Response)return e;let{base64Override:o,overrideHash:i}=e.schemas;return await t.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||r.param("clientVersion"),debug:n.get("debug"),platform:await En(),schemaHash:i})}var Hn=[["/connection-info","GET"],["/query","POST"],["/transaction/start","POST"],["/transaction/:transactionId/commit","POST"],["/transaction/:transactionId/query","POST"],["/transaction/:transactionId/rollback","POST"]];for(let[n,r]of Hn)I.on(r,n,u("header",s),async t=>{let{getQueryPlanExecutorServer:e,queryPlanExecutorVersion:o}=await $n(),i=t.req.header("prisma-engine-hash");if(i!=="0.0.0"&&i!==o)throw new Pn(400,{message:`Using an HTTP connection string is not supported with Prisma Client version ${i} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${o}.`});return await(await e(t)).fetch(t.req.raw)});export{I as accelerateRoute};
import{e as h,f,g as M}from"./chunk-EDFHV3AK.js";import{a as A,c as m,g as V,h as C,i as L,j as x}from"./chunk-DWY47FQV.js";import{writeFile as se}from"fs/promises";import{join as p}from"pathe";import{check as oe,lock as ie,unlock as ne}from"proper-lockfile";import{process as B}from"std-env";import{integer as K,literal as ue,minLength as R,minValue as Q,number as Z,object as P,optional as l,parseJson as de,pipe as c,safeParse as le,string as b,url as ce}from"valibot";import{setTimeout as te}from"timers/promises";import{process as D}from"std-env";function _(r,e){if(r==null)return!1;try{return D.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}async function J(r,e){if(!D.kill)return!1;try{D.kill(r,"SIGTERM")}catch(a){return e&&console.error(`Error killing process with PID ${r}:`,a),!1}let t=0;do{if(!_(r,e))return!0;await te(100)}while(++t<50);try{return D.kill(r,"SIGKILL")}catch(a){return e&&console.error(`Error forcefully killing process with PID ${r}:`,a),!1}}import{join as j}from"pathe";var re="prisma-wal",xe="prisma-queries";function ae(){return j(A.data,"durable-streams")}function H(r){return j(ae(),r)}function Me(r,e=re){return new URL(`/v1/stream/${encodeURIComponent(e)}`,r).toString()}var S=c(b(),ce()),Y=P({connectionString:S,prismaORMConnectionString:l(S),terminalCommand:l(b())}),F=P({url:S}),G=P({serverUrl:S,sqlitePath:c(b(),R(1)),streamName:c(b(),R(1)),url:S}),me=P({queryInsights:l(G),streams:l(G)}),I=c(Z(),K(),Q(1)),he=P({database:Y,http:F,ppg:F,shadowDatabase:Y}),pe=P({databasePort:I,experimental:l(me),exports:l(he),name:c(b(),R(1)),pid:l(c(Z(),K(),Q(0))),port:I,shadowDatabasePort:I,version:ue("1")}),O=Symbol("initialize"),E="default",be=new Set(["durable-streams"]),u=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(e){this._databasePort=e.databasePort??f,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??E,this.persistenceMode=e.persistenceMode,this.pid=e.pid??B.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??f,this._shadowDatabasePort=e.shadowDatabasePort??f,this._streamsPort=e.streamsPort??f}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new g(e):new k(e);return await t[O](),t}static async fromServerDump(e){let{debug:t,name:a=E}=e??{},o=m(a),i=g.getServerDumpPath(o),s=await V(i);if(s==null)return t&&console.debug(`[State] No server dump file found at: ${i}`),null;t&&(console.debug(`[State] server dump file found at "${i}":`),console.debug(s));let{issues:n,output:d,success:v}=le(c(b(),de(),pe),s);if(!v)throw t&&console.debug(`[State] Invalid server dump file at "${i}":
${JSON.stringify(n,null,2)}`),new Error(`Invalid Prisma Dev state for "${a}".`);return new g({databasePort:d.databasePort,debug:t,dryRun:!1,name:a,pid:d.pid,port:d.port,serverDump:d,shadowDatabasePort:d.shadowDatabasePort})}static async scan(e){let{debug:t,globs:a}=e??{},o=p(m(E),"..");t&&console.debug(`[State] scanning for server states in: ${o}`);let i=(await L(o,a)).filter(s=>!be.has(s));return t&&console.debug(`[State] found server names: ${JSON.stringify(i)}`),await Promise.all(i.map(s=>z(s,e)))}get databasePort(){return this._databasePort}set databasePort(e){this.#t("databasePort",e)}get port(){return this._port}set port(e){this.#t("port",e)}get shadowDatabasePort(){return this._shadowDatabasePort}get streamsPort(){return this._streamsPort}set shadowDatabasePort(e){this.#t("shadowDatabasePort",e)}#t(e,t){if(t<0||!Number.isInteger(t))throw new Error(`Invalid port number: ${t}`);let a=`_${e}`;if(this[a]!==h&&this[a]!==t)throw new Error(`\`${e}\` is already set to ${this[a]}, cannot change it to ${t}`);this[a]=t}},k=class extends u{constructor(e){super({...e,databasePort:e?.databasePort||h,persistenceMode:"stateless",port:e?.port||h,shadowDatabasePort:e?.shadowDatabasePort||h,streamsPort:e?.streamsPort||h})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[O](){let e;try{e=await u.scan({debug:this.debug,onlyMetadata:!0})}catch(a){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",a),e=[]}let t=await M({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,this._streamsPort=t.streamsPort}async close(){}async writeServerDump(){}},g=class r extends u{#t;#e;#a;#o;#i;#s;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#s=!1,this.#e=m(this.name),this.#t=p(this.#e,"db_dump.bak"),this.#a=p(this.#e,".lock"),this.#o=p(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#i=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return p(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get experimental(){return this.#r?.experimental}get pgliteDataDirPath(){return this.#o}async[O](){await C(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await ie(this.#e,{lockfilePath:this.#a}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await u.scan({debug:this.debug,onlyMetadata:!0}),t=await M({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,this._streamsPort=t.streamsPort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new $(this):e}}async close(){if(!this.#s)try{await ne(this.#e,{lockfilePath:this.#a}),this.#s=!0,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw this.debug&&console.error(`[State] failed to release lock on: ${this.#e}`,e),e}}async writeServerDump(e,t){this.#r={name:this.name,version:"1",pid:B.pid,port:this.port,databasePort:this.databasePort,experimental:t,shadowDatabasePort:this.shadowDatabasePort,exports:e},await se(this.#i,`${JSON.stringify(this.#r,null,2)}
`,{encoding:"utf-8"})}};async function Ce(r,e){await fe(r,e);let t=typeof r=="string"?r:r.name,a=m(t);await x(a),await x(H(t))}async function z(r,e){let{debug:t,onlyMetadata:a}=e||{},o=typeof r=="string"?r:r.name,i=typeof r!="string"?r:void 0,s={databasePort:i?.databasePort??-1,experimental:i?.experimental,exports:i?.exports,name:o,pid:i?.pid,port:i?.port??-1,shadowDatabasePort:i?.shadowDatabasePort??-1,version:"1"};try{let n=i||await u.fromServerDump({debug:t,name:o});if(!n)return t&&console.debug(`[State] no server state found for name: ${o}`),{...s,status:"no_such_server"};s.databasePort=n.databasePort,s.experimental=n.experimental,s.exports=n.exports,s.pid=n.pid,s.port=n.port,s.shadowDatabasePort=n.shadowDatabasePort;let{exports:d,pid:v}=n;if(a)return{...s,status:"unknown"};if(!_(v,t))return t&&console.debug(`[State] server state for "${o}" has no running process with PID: ${v}`),{...s,status:"not_running"};let N=m(o);try{if(!await oe(N,{lockfilePath:p(N,".lock")}))return t&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...s,status:"not_running"}}catch(ee){t&&console.error(`[State] server state for "${o}" failed to check lock:`,ee)}if(!d)return{...s,status:"starting_up"};let{http:W}=d,{hc:X}=await import("hono/client"),y=await X(W.url).health.$get();if(!y.ok)return t&&console.debug(`[State] server state for "${o}" is not live: ${JSON.stringify(y)}`),{...s,status:"not_running"};let w=await y.json();return w.name!==r?(t&&console.debug(`[State] server state for "${o}" has mismatched health response: ${JSON.stringify(w)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(w)}`),{...s,status:"running"})}catch(n){return t&&console.error(`[State] failed to get server status for "${o}":`,n),{...s,status:"error"}}}function Pe(r){let{status:e}=r;return e==="running"||e==="starting_up"}async function fe(r,e){let{pid:t,...a}=typeof r=="string"?await z(r,{debug:e}):r;if(!Pe(a))return!1;let o=await u.fromServerDump({debug:e,name:a.name});if(t==null){e&&console.debug(`[State] No PID found for server "${a.name}" to kill.`);try{await o?.close()}catch{}return!1}let i=await J(t,e);try{await o?.close()}catch{}return i}var T=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},$=class extends T{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return u.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{re as a,xe as b,ae as c,H as d,Me as e,u as f,Ce as g,z as h,Pe as i,fe as j,T as k,$ as l};
import{minLength as D,object as B,optional as S,parseJson as O,pipe as s,regex as m,safeParse as T,string as n,url as l}from"valibot";var y=/^(postgres|postgresql):\/\//,U=s(n(),O(),B({databaseUrl:s(n(),l(),m(y)),name:S(s(n(),D(1))),shadowDatabaseUrl:s(n(),l(),m(y))}));function H(r){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(r).sort(([[e],[o]])=>e.localeCompare(o)))),"utf8").toString("base64url")}function E(r){let e=Buffer.from(r,"base64url").toString("utf8"),{issues:o,output:t,success:a}=T(U,e,{abortEarly:!0});return a?[null,t]:[o]}var $=async(r,e)=>{let{authorization:o}=r,{HTTPException:t}=await import("hono/http-exception");if(!o)throw new t(401,{message:"Missing API Key"});let[a,f="",h]=o.split(" ");if(a!=="Bearer"||h)throw new t(401,{message:"Invalid API Key"});let[u,c]=E(f);if(u)throw new t(401,{message:"Invalid API Key",cause:u.join(", ")});let{databaseUrl:P,name:i,shadowDatabaseUrl:g}=c,d=e.get("name"),p=new URL(e.req.url).port;if(!i)throw new t(401,{message:`Wrong API Key; The Prisma Dev server running at port ${p} requires an API Key from a newer version of \`prisma dev\`. Check the "${d}" server's output for the updated \`DATABASE_URL\` value.`});if(i!==d)throw new t(401,{message:`Wrong API Key; The Prisma Dev server running at port ${p} is named "${d}", but the API Key is for "${i}"`});let{hostname:w,port:A}=new URL(P),{port:I}=e.get("db"),{hostname:K,port:b}=new URL(g),v=e.get("shadowDBPort");if(w!=="localhost"||Number(A)!==I||K!=="localhost"||Number(b)!==v)throw new t(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}};export{H as a,$ as b};
import{a as W,b as O,f as R}from"./chunk-PP43TGA5.js";import{a as C,b as I,c as $,d as T,e as f,f as M}from"./chunk-2XJK3IOI.js";import{h as x}from"./chunk-EDFHV3AK.js";import{a as N}from"./chunk-HQMJSXYT.js";import{d as q,j as g}from"./chunk-DWY47FQV.js";import{a as _}from"./chunk-3UF2MBYQ.js";import{createServer as ee}from"http";import{promisify as re}from"util";async function j(r,e){let{port:t}=e;if(e.dryRun)return U(t,null);let n=await te(r,e),{promise:s,reject:i,resolve:l}=N(),{serve:a}=await import("@hono/node-server"),o=a({createServer:ee,fetch:n.fetch,overrideGlobalObjects:!1,port:t},l);o.on("error",m=>{if(typeof m=="object"&&"code"in m&&m.code==="EADDRINUSE")return i(new x(t));console.error("[Accelerate]",m)});let{port:c}=await s;return e.port=c,U(c,o)}function U(r,e){return{async close(){if(!e)return;let{Engine:t}=await import("./engine-XP6YJ63T.js");await Promise.allSettled([re(e.close.bind(e))(),t.stopAll()])},port:r,url:`http://localhost:${r}`}}async function te(r,e){let{debug:t}=e,[{Hono:n},{accelerateRoute:s},{utilityRoute:i}]=await Promise.all([import("hono/tiny"),import("./accelerate-5FDEK4T6.js"),import("./utility-Q5A254LJ.js")]),l=new n;if(t){let{logger:o}=await import("hono/logger");l.use("*",o((...c)=>console.log("[Accelerate]",...c)))}l.use("*",async(o,c)=>(o.set("databaseDumpPath",e.databaseDumpPath),o.set("db",r),o.set("debug",!!t),o.set("name",e.name),o.set("shadowDBPort",e.shadowDatabasePort),await c()));let a=new n;return a.route("/",s),a.route("/",i),l.route("/",a),l}import{isDeepStrictEqual as F}from"util";var ne="application/json",w={connection:"close","content-type":ne},k={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 H(r){return{...r,snapshot:async e=>await se(r.url,e)}}async function L(r){let e={serverUrl:r.serverUrl,sqlitePath:r.sqlitePath,streamName:I,url:f(r.serverUrl,I)};await oe(e);let t=new A({debug:r.debug,streamUrl:e.url}),n=r.bridge.subscribe(s=>{t.enqueue(s)});return{close:async()=>{n(),await t.close()},experimental:e}}async function se(r,e){if(!r)return W();let t=await ae(r);return O(t,e)}async function ae(r){let e=await fetch(`${r}?offset=-1&format=json`,{headers:{connection:"close"}});if(!e.ok)throw new Error(`Failed to read ${r}: HTTP ${e.status}`);return await e.json()}var A=class{#t;#r;#e;constructor(e){this.#t=e.debug,this.#r=Promise.resolve(),this.#e=e.streamUrl}enqueue(e){e.length!==0&&(this.#r=this.#r.then(async()=>{await ce(this.#e,e),this.#t&&console.debug(`[streams] appended ${e.length} query insight record(s) to ${this.#e}`)}).catch(t=>{console.error("[streams] failed to ingest query insights into prisma-queries",t)}))}async close(){await this.#r}};async function oe(r){let e=await fetch(r.url,{headers:w,method:"PUT"});if(!e.ok)throw await b(e,`Failed to create ${r.streamName}`);let t=await le(r);if(ie(t,r.streamName))return;if(t.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let n=await fetch(`${r.url}/_schema`,{body:JSON.stringify(k),headers:w,method:"POST"});if(!n.ok)throw await b(n,`Failed to install schema for ${r.streamName}`)}function ie(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return F(t,k.schema)&&F(r.search,k.search)}async function le(r){let e=await fetch(`${r.url}/_schema`,{headers:w,method:"GET"});if(!e.ok)throw await b(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}async function ce(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:w,method:"POST"});if(!t.ok)throw await b(t,"Failed to append to prisma-queries")}async function b(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}import{randomUUID as me}from"crypto";import{setTimeout as K}from"timers/promises";import{isDeepStrictEqual as V}from"util";import{process as ue}from"std-env";var pe="application/json",y={connection:"close","content-type":pe},de={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},Q={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 G(r){let{dbServer:e,debug:t,name:n,persistenceMode:s,port:i,queryInsightsBridge:l,walBridge:a}=r,o=s==="stateless",c=o?Re(n):n,m=T(c),P=!o&&await q(m);ue.env.DS_LOCAL_DATA_ROOT=$(),o&&await g(m);let u=await ge({debug:t,hadExistingStreamsData:P,name:c,port:i}),d={serverUrl:u.exports.http.url,sqlitePath:u.exports.sqlite.path,streamName:C,url:f(u.exports.http.url)};try{await fe(d);let p=await L({bridge:l,debug:t,serverUrl:u.exports.http.url,sqlitePath:u.exports.sqlite.path}),h=new D({dbServer:e,debug:t,streamUrl:d.url}),X=a.subscribe(Z=>{h.enqueue(Z)});return{close:async()=>{X(),await h.close(),await p.close(),await u.close(),await K(100),o&&await g(m)},experimental:d,experimentalQueryInsights:p.experimental}}catch(p){throw await u.close().catch(()=>{}),await K(100),o&&await g(m).catch(()=>{}),p}}var he=["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 ge(r){let{debug:e,hadExistingStreamsData:t,name:n,port:s}=r,{startLocalDurableStreamsServer:i}=await import("@prisma/streams-local"),l=()=>i({hostname:"127.0.0.1",name:n,port:s});try{return await l()}catch(a){if(!t||!ye(a))throw a;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),e&&console.debug(`[streams] original durable streams startup error for "${n}"`,a),await g(T(n)),await l()}}function ye(r){return Se(r).map(t=>t.toLowerCase()).some(t=>he.some(n=>t.includes(n)))}function Se(r){let e=[],t=[r],n=new Set;for(;t.length>0;){let s=t.shift();if(!(s==null||n.has(s))){if(n.add(s),typeof s=="string"){e.push(s);continue}if(s instanceof AggregateError)for(let i of s.errors)t.push(i);if(s instanceof Error){e.push(s.message);let i=s.cause;i!==void 0&&t.push(i)}}}return e}var D=class{#t;#r;#e;#n;#s;constructor(e){this.#t=e.dbServer,this.#r=e.debug,this.#e=Promise.resolve(),this.#n=e.streamUrl,this.#s=new Set}enqueue(e){e.length!==0&&(this.#e=this.#e.then(async()=>{let t=await this.#o(e);t.length!==0&&(await we(this.#n,t),this.#r&&console.debug(`[streams] appended ${t.length} state-protocol record(s) to ${this.#n}`))}).catch(t=>{console.error("[streams] failed to ingest WAL events into prisma-wal",t)}))}async close(){await this.#e}async#o(e){let t=[],n=new Date().toISOString();for(let s of e)t.push(...await this.#i(s,n));return t}async#i(e,t){let n=`${e.schema}.${e.table}`,s=await this.#t.getPrimaryKeyColumns(e.schema,e.table),i=J(e.record),l=J(e.oldRecord),a=this.#a(n,s,l),o=this.#a(n,s,i),c=e.txid===""?void 0:e.txid;return e.type==="insert"?i&&o?[{headers:{operation:"insert",timestamp:t,txid:c},key:o,old_value:null,type:n,value:i}]:[]:e.type==="delete"?l&&a?[{headers:{operation:"delete",timestamp:t,txid:c},key:a,old_value:l,type:n,value:null}]:[]:!i||!l||!a||!o?[]:a!==o?[{headers:{operation:"delete",timestamp:t,txid:c},key:a,old_value:l,type:n,value:null},{headers:{operation:"insert",timestamp:t,txid:c},key:o,old_value:null,type:n,value:i}]:[{headers:{operation:"update",timestamp:t,txid:c},key:o,old_value:l,type:n,value:i}]}#a(e,t,n){if(!n)return null;let s=be(n,t);return s||(this.#s.has(e)||(this.#s.add(e),console.warn(`[streams] falling back to full-row keys for ${e} because no primary key could be resolved`)),Pe(n))}};async function fe(r){let e=await fetch(r.url,{headers:y,method:"PUT"});if(!e.ok)throw await S(e,`Failed to create ${r.streamName}`);let t=await fetch(`${r.url}/_profile`,{body:JSON.stringify(de),headers:y,method:"POST"});if(!t.ok)throw await S(t,`Failed to configure ${r.streamName}`);let n=await ve(r);if(Ee(n,r.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${r.url}/_schema`,{body:JSON.stringify(Q),headers:y,method:"POST"});if(!s.ok)throw await S(s,`Failed to install schema for ${r.streamName}`)}async function ve(r){let e=await fetch(`${r.url}/_schema`,{headers:y,method:"GET"});if(!e.ok)throw await S(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}function Ee(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return V(t,Q.schema)&&V(r.search,Q.search)}async function we(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:y,method:"POST"});if(!t.ok)throw await S(t,"Failed to append to prisma-wal")}async function S(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}function be(r,e){if(e.length===0)return null;let t=[];for(let n of e){if(!Object.prototype.hasOwnProperty.call(r,n))return null;let s=xe(r[n]);if(s==null)return null;t.push(e.length===1?s:`${n}=${s}`)}return t.join("|")}function Pe(r){return JSON.stringify(B(r))}function B(r){return Array.isArray(r)?r.map(e=>B(e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,B(t)])):r}function J(r){return r?structuredClone(r):null}function xe(r){if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="string")return r;if(typeof r=="number")return Number.isFinite(r)?String(r):null;if(typeof r=="bigint")return r.toString();if(typeof r=="boolean")return r?"true":"false";try{return JSON.stringify(r)}catch{return null}}function Re(r){return`${r}.${me().replaceAll("-","")}`}async function Y(r){let e=await M.createExclusively(r),t=null,n=null,s=null,i=null;try{[t,s]=await Promise.all([R("database",e),R("shadow_database",e)]);let l,a;e.dryRun?(l=Ae(),a=Qe(),i=De()):(l=await t.attachWalEventBridge(),a=await t.attachQueryInsightsBridge(),i=await G({dbServer:t,debug:e.debug,name:e.name,port:e.streamsPort,persistenceMode:e.persistenceMode,queryInsightsBridge:a,walBridge:l})),n=await j(t,e);let o=Ie(t,s,n,e);await e.writeServerDump(o,e.dryRun?{}:{queryInsights:i.experimentalQueryInsights,streams:i.experimental});let c=ke(l),m=H(i.experimentalQueryInsights),P=t,u=s,d=n,p=i,h=async()=>{c.close(),await z(e,[d,p,P,u])};return{close:h,dbServer:t,httpServer:n,server:{...o,close:h,experimental:{queryInsights:m,streams:i.experimental,wal:c.api},name:e.name},serverState:e,shadowDbServer:s,streamsServer:i,queryInsightsBridge:a,walBridge:l}}catch(l){return await Te(e,[n,i,t,s],l)}}function Ie(r,e,t,n){let s=`prisma+postgres://localhost:${t.port}/?${new URLSearchParams({api_key:_({databaseUrl:r.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:e.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:t.url},ppg:{url:s},shadowDatabase:{connectionString:e.prismaORMConnectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand}}}async function z(r,e){let t=[];for(let n of e)try{await n.close()}catch(s){t.push(s)}try{await r.close()}catch(n){t.push(n)}if(t.length>0)throw new AggregateError(t,"Failed to close some servers")}async function Te(r,e,t){try{await z(r,e.filter(n=>n!==null))}catch(n){throw new AggregateError([t,n],"Failed to start Prisma Dev server cleanly")}throw t}function ke(r){let e=new Set;return{api:{stream:()=>{let t=()=>{},n=Be(r,()=>{e.delete(t)});return t=()=>n.close(),e.add(t),n.stream},subscribe:t=>r.subscribe(t)},close:()=>{for(let t of[...e])t();e.clear()}}}function Ae(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Qe(){return{async close(){},subscribe(){return()=>{}}}}function De(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function Be(r,e){let t=[],n=!1,s=null,i=r.subscribe(a=>{if(!n){if(s){let o=s;s=null,o.resolve({done:!1,value:a});return}t.push(a)}}),l=()=>{if(!n&&(n=!0,i(),t.length=0,e(),s)){let a=s;s=null,a.resolve({done:!0,value:void 0})}};return{close:l,stream:{[Symbol.asyncIterator](){return this},next(){return t.length>0?Promise.resolve({done:!1,value:t.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((a,o)=>{s={reject:o,resolve:a}})},return(){return l(),Promise.resolve({done:!0,value:void 0})},throw(a){let o=s;return l(),o&&o.reject(a),Promise.reject(a instanceof Error?a:new Error(String(a)))}}}}async function _e(r){let{server:e}=await Y(r);return e}async function Sr(r){return await _e(r)}export{_e as a,Sr as b};
function r(o){let n,d,s=new Promise((e,v)=>{n=e,d=v}),i=e=>{i=l=null,d(e),o?.onRejected?.(e),o?.onFulfilled?.()},l=e=>{l=i=null,n(e),o?.onResolved?.(e),o?.onFulfilled?.()};return{isFulfilled:()=>l===i,promise:s,reject:e=>i?.(e),resolve:e=>l?.(e)}}export{r as a};
import{a as E}from"./chunk-HQMJSXYT.js";import{b as f,d as w,e as y}from"./chunk-DWY47FQV.js";import{spawn as k}from"child_process";import{once as v}from"events";import{mkdir as T}from"fs/promises";import{join as $}from"path";import{setTimeout as x}from"timers/promises";import{process as C}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:O,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:H,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:b}=C.env,P=class o{static#t=new Map;#e;#n;constructor(e){this.#e=e,this.#n=null}static async get(e){let{debug:n}=e,i=`${e.schemaHash}:${e.clientVersion}`;try{let t=o.#t.get(i);if(t)return t;let s=new o(e);return o.#t.set(i,s),n&&console.debug("[Query Engine] starting...",e),await s.start(),n&&console.debug("[Query Engine] started!"),s}finally{o.stopAll(i)}}static async stopAll(e){let i=(await Promise.allSettled(Array.from(o.#t.entries()).filter(([t])=>t!==e).map(async([t,s])=>{try{await s.stop()}finally{o.#t.delete(t)}}))).filter(t=>t.status==="rejected").map(t=>t.reason);if(i.length>0)throw new AggregateError(i,"Failed to stop engines")}async commitTransaction(e,n){return await this.#s(e,n,"commit")}async request(e,n){let{url:i}=await this.start(),t=this.#i(n),s=await fetch(i,{body:typeof e=="string"?e:JSON.stringify(e),headers:{...t,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await l.fromResponse(s);return await s.text()}async rollbackTransaction(e,n){return await this.#s(e,n,"rollback")}async startTransaction(e,n){let{url:i}=await this.start(),t=this.#i(n),s=await fetch(`${i}/transaction/start`,{body:JSON.stringify(e),headers:{...t,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await l.fromResponse(s);return await s.json()}async start(){if(this.#n!=null)return await this.#n;let{promise:e,reject:n,resolve:i}=E();this.#n=e;let t=H||await this.#r();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",t);let{proxySignals:s}=await import("foreground-child/proxy-signals"),r=k(t,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});s(r),r.stderr.setEncoding("utf8"),r.stdout.setEncoding("utf8");let c=a=>{let d=a.split(`
`).find(S=>S.includes("Started query engine http server"));if(!d)return;r.stdout.removeListener("data",c);let{fields:p}=JSON.parse(d);if(p==null)return n(new Error(`Unexpected data during initialization, "fields" are missing: ${a}`));let{ip:m,port:h}=p;if(m==null||h==null)return n(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
Received data: ${a}`));i({childProcess:r,url:`http://${m}:${h}`})},R=a=>{this.#n=null,n(new g(String(a))),r.removeListener("exit",u),r.kill()};r.once("error",R);let u=(a,d)=>{this.#n=null,n(new g(`Query Engine exited with code ${a} and signal ${d}`))};return r.once("exit",u),r.stdout.on("data",c),this.#e.debug&&(r.stderr.on("data",console.error.bind(console,"[Query Engine]")),r.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#n}async stop(){if(this.#n==null)return;let{childProcess:e}=await this.#n;e.exitCode==null&&e.signalCode==null&&(this.#n=null,e.kill(),await v(e,"exit"))}async#r(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#o();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let n=f(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",n),await T(n,{recursive:!0});let{binaryTarget:i}=this.#e.platform,t=i==="windows"?".exe":"",s=$(n,`query-engine-${i}${t}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(O==="1"||await w(s)===!1)&&await this.#a({commitHash:e,extension:t,engineBinaryPath:s}),s}async#o(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let i=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!i)throw new Error("Couldn't find engines version in package.json");let t=i.split(".").at(-1);if(!t)throw new Error("Couldn't find commit hash in engines version");return t}async#a(e){let{commitHash:n,extension:i,engineBinaryPath:t}=e,{binaryTarget:s}=this.#e.platform,r=`https://binaries.prisma.sh/all_commits/${n}/${s}/query-engine${i}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",r);let c=await fetch(r);if(!c.ok)throw new Error(`Couldn't download engine. URL: ${r}, status code: ${c.status}`);b&&await x(Number(b)),await y(await c.arrayBuffer(),t),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",t)}#i(e){let n={};for(let[i,t]of Object.entries(e))t!=null&&(n[i]=t);return n}async#s(e,n,i){let{url:t}=await this.#n,s=this.#i(n),r=await fetch(`${t}/transaction/${e}/${i}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!r.ok)throw await l.fromResponse(r);try{return await r.json()}catch{return{}}}};function M(o,e){return console.error(o),o instanceof g?e.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:o.message}}}},500):o instanceof l?e.text(o.responseBody,o.statusCode):e.body(null,500)}var g=class extends Error{name="EngineStartError"},l=class o extends Error{constructor(n,i,t){super(`${n}: Query Engine response status ${i}, body: ${t}`);this.action=n;this.statusCode=i;this.responseBody=t}name="EngineHttpError";static async fromResponse(n){let i=new URL(n.url),t=await n.text();return new o(i.pathname,n.status,t)}};export{P as Engine,M as handleEngineError};
import{parseDuration as e,parseSize as o,Server as n}from"@prisma/query-plan-executor";import{version as d}from"@prisma/query-plan-executor";var r;async function u(t){return r===void 0&&(r=await n.create({databaseUrl:t.get("db").connectionString,maxResponseSize:o("128 MiB"),queryTimeout:e("PT5M"),maxTransactionTimeout:e("PT5M"),maxTransactionWaitTime:e("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.get("debug")?"debug":"off"}})),r}export{u as getQueryPlanExecutorServer,d as queryPlanExecutorVersion};
import{Hono as n}from"hono/tiny";import{StatusCodes as p}from"http-status-codes";var o=new n;o.post("/database/dump",async t=>{let a=t.get("db"),e=t.get("databaseDumpPath");return await a.dump(e),t.json({dumpPath:e},p.CREATED)});var u=o.get("/health",t=>t.json({name:t.get("name")}));export{o as utilityRoute};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display