@prisma/dev 0.25.1 → 0.25.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,4 +8,4 @@ import{b as p}from"./chunk-662IKR3V.js";import{a as g}from"./chunk-SW3J2PL2.js";
8
8
  `,r)+1,t=e;for(;n[t]===" "||n[t]===" ";)t+=1;return n.slice(e,t)}function Tn(n){return n.includes(`\r
9
9
  `)?`\r
10
10
  `:`
11
- `}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};
11
+ `}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-XTNCE4RM.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};
@@ -1 +1 @@
1
- import{a as q}from"./chunk-662IKR3V.js";import{a as W,b as _,f as x}from"./chunk-QDQPFKGQ.js";import{a as O,b as R,c as A,d as I,e as v,f as M,h as $,i as U}from"./chunk-HFONW2ZS.js";import{d as C,j as y}from"./chunk-DWY47FQV.js";import{b as N}from"./chunk-DOJAPHLY.js";import Z from"find-my-way";async function F(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-TRR43YJ5.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=Z({defaultRoute(u,p){N(p,"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:u}=await import("./engine-YTEOPVUP.js");await Promise.allSettled([c.close(),u.stopAll()])},port:c.port,url:c.url}}import{isDeepStrictEqual as j}from"util";var ee="application/json",E={connection:"close","content-type":ee},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 H(r){return{...r,snapshot:async e=>await re(r.url,e)}}async function K(r){let e={serverUrl:r.serverUrl,sqlitePath:r.sqlitePath,streamName:R,url:v(r.serverUrl,R)};await ne(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 re(r,e){if(!r)return W();let t=await te(r);return _(t,e)}async function te(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 ie(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 ne(r){let e=await fetch(r.url,{headers:E,method:"PUT"});if(!e.ok)throw await P(e,`Failed to create ${r.streamName}`);let t=await ae(r);if(se(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:E,method:"POST"});if(!n.ok)throw await P(n,`Failed to install schema for ${r.streamName}`)}function se(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return j(t,T.schema)&&j(r.search,T.search)}async function ae(r){let e=await fetch(`${r.url}/_schema`,{headers:E,method:"GET"});if(!e.ok)throw await P(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}async function ie(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:E,method:"POST"});if(!t.ok)throw await P(t,"Failed to append to prisma-queries")}async function P(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}import{randomUUID as oe}from"crypto";import{setTimeout as L}from"timers/promises";import{isDeepStrictEqual as V}from"util";import{process as le}from"std-env";var ce="application/json",S={connection:"close","content-type":ce},ue={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},B={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?Ee(n):n,u=I(c),p=!o&&await C(u);le.env.DS_LOCAL_DATA_ROOT=A(),o&&await y(u);let m=await de({debug:t,hadExistingStreamsData:p,name:c,port:i}),g={serverUrl:m.exports.http.url,sqlitePath:m.exports.sqlite.path,streamName:O,url:v(m.exports.http.url)};try{await he(g);let d=await K({bridge:l,debug:t,serverUrl:m.exports.http.url,sqlitePath:m.exports.sqlite.path}),h=new D({dbServer:e,debug:t,streamUrl:g.url}),z=a.subscribe(X=>{h.enqueue(X)});return{close:async()=>{z(),await h.close(),await d.close(),await m.close(),await L(100),o&&await y(u)},experimental:g,experimentalQueryInsights:d.experimental}}catch(d){throw await m.close().catch(()=>{}),await L(100),o&&await y(u).catch(()=>{}),d}}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 de(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 ge(r).map(t=>t.toLowerCase()).some(t=>me.some(n=>t.includes(n)))}function ge(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.#i(e);t.length!==0&&(await fe(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=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=ve(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`)),we(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(ue),headers:S,method:"POST"});if(!t.ok)throw await f(t,`Failed to configure ${r.streamName}`);let n=await ye(r);if(Se(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(B),headers:S,method:"POST"});if(!s.ok)throw await f(s,`Failed to install schema for ${r.streamName}`)}async function ye(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 Se(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return V(t,B.schema)&&V(r.search,B.search)}async function fe(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 ve(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=be(r[n]);if(s==null)return null;t.push(e.length===1?s:`${n}=${s}`)}return t.join("|")}function we(r){return JSON.stringify(Q(r))}function Q(r){return Array.isArray(r)?r.map(e=>Q(e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Q(t)])):r}function J(r){return r?structuredClone(r):null}function be(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 Ee(r){return`${r}.${oe().replaceAll("-","")}`}async function tr(r){let e=await M.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=Ie(),a=Te(),i=ke()):(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 F(t,e);let o=Pe(t,s,n,e);await e.writeServerDump(o,e.dryRun?{}:{queryInsights:i.experimentalQueryInsights,streams:i.experimental});let c=Re(l),u=H(i.experimentalQueryInsights),p=t,m=s,g=n,d=i,h=async()=>{c.close(),await Y(e,[g,d,p,m])};return{close:h,dbServer:t,httpServer:n,server:{...o,close:h,experimental:{queryInsights:u,streams:i.experimental,wal:c.api},name:e.name},serverState:e,shadowDbServer:s,streamsServer:i,queryInsightsBridge:a,walBridge:l}}catch(l){return await xe(e,[n,i,t,s],l)}}function Pe(r,e,t,n){let s=`prisma+postgres://localhost:${t.port}/?${new URLSearchParams({api_key:q({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 Y(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 xe(r,e,t){try{await Y(r,e.filter(n=>n!==null))}catch(n){throw new AggregateError([t,n],"Failed to start Prisma Dev server cleanly")}throw t}function Re(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 Ie(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Te(){return{async close(){},subscribe(){return()=>{}}}}function ke(){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)))}}}}var De="default";function Qe(r){return{databaseUrl:r.database.prismaORMConnectionString??r.database.connectionString,prismaPostgresUrl:r.ppg.url,shadowDatabaseUrl:r.shadowDatabase.prismaORMConnectionString??r.shadowDatabase.connectionString}}async function ir(r){let{debug:e,name:t=De}=r??{},n=await $(t,{debug:e});return!U(n)||!n.exports?null:{...Qe(n.exports),name:n.name}}export{tr as a,Qe as b,ir as c};
1
+ import{a as q}from"./chunk-662IKR3V.js";import{a as W,b as _,f as x}from"./chunk-MGHBCHO2.js";import{a as O,b as R,c as A,d as I,e as v,f as M,h as $,i as U}from"./chunk-GK3XD2W4.js";import{d as C,k as y}from"./chunk-ZEM5OLPM.js";import{b as N}from"./chunk-DOJAPHLY.js";import Z from"find-my-way";async function F(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-KNP4MGMV.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=Z({defaultRoute(u,p){N(p,"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:u}=await import("./engine-XTNCE4RM.js");await Promise.allSettled([c.close(),u.stopAll()])},port:c.port,url:c.url}}import{isDeepStrictEqual as j}from"util";var ee="application/json",E={connection:"close","content-type":ee},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 H(r){return{...r,snapshot:async e=>await re(r.url,e)}}async function K(r){let e={serverUrl:r.serverUrl,sqlitePath:r.sqlitePath,streamName:R,url:v(r.serverUrl,R)};await ne(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 re(r,e){if(!r)return W();let t=await te(r);return _(t,e)}async function te(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 ie(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 ne(r){let e=await fetch(r.url,{headers:E,method:"PUT"});if(!e.ok)throw await P(e,`Failed to create ${r.streamName}`);let t=await ae(r);if(se(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:E,method:"POST"});if(!n.ok)throw await P(n,`Failed to install schema for ${r.streamName}`)}function se(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return j(t,T.schema)&&j(r.search,T.search)}async function ae(r){let e=await fetch(`${r.url}/_schema`,{headers:E,method:"GET"});if(!e.ok)throw await P(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}async function ie(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:E,method:"POST"});if(!t.ok)throw await P(t,"Failed to append to prisma-queries")}async function P(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}import{randomUUID as oe}from"crypto";import{setTimeout as L}from"timers/promises";import{isDeepStrictEqual as V}from"util";import{process as le}from"std-env";var ce="application/json",S={connection:"close","content-type":ce},ue={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},B={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?Ee(n):n,u=I(c),p=!o&&await C(u);le.env.DS_LOCAL_DATA_ROOT=A(),o&&await y(u);let m=await de({debug:t,hadExistingStreamsData:p,name:c,port:i}),g={serverUrl:m.exports.http.url,sqlitePath:m.exports.sqlite.path,streamName:O,url:v(m.exports.http.url)};try{await he(g);let d=await K({bridge:l,debug:t,serverUrl:m.exports.http.url,sqlitePath:m.exports.sqlite.path}),h=new D({dbServer:e,debug:t,streamUrl:g.url}),z=a.subscribe(X=>{h.enqueue(X)});return{close:async()=>{z(),await h.close(),await d.close(),await m.close(),await L(100),o&&await y(u)},experimental:g,experimentalQueryInsights:d.experimental}}catch(d){throw await m.close().catch(()=>{}),await L(100),o&&await y(u).catch(()=>{}),d}}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 de(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 ge(r).map(t=>t.toLowerCase()).some(t=>me.some(n=>t.includes(n)))}function ge(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.#i(e);t.length!==0&&(await fe(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=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=ve(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`)),we(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(ue),headers:S,method:"POST"});if(!t.ok)throw await f(t,`Failed to configure ${r.streamName}`);let n=await ye(r);if(Se(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(B),headers:S,method:"POST"});if(!s.ok)throw await f(s,`Failed to install schema for ${r.streamName}`)}async function ye(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 Se(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return V(t,B.schema)&&V(r.search,B.search)}async function fe(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 ve(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=be(r[n]);if(s==null)return null;t.push(e.length===1?s:`${n}=${s}`)}return t.join("|")}function we(r){return JSON.stringify(Q(r))}function Q(r){return Array.isArray(r)?r.map(e=>Q(e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Q(t)])):r}function J(r){return r?structuredClone(r):null}function be(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 Ee(r){return`${r}.${oe().replaceAll("-","")}`}async function tr(r){let e=await M.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=Ie(),a=Te(),i=ke()):(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 F(t,e);let o=Pe(t,s,n,e);await e.writeServerDump(o,e.dryRun?{}:{queryInsights:i.experimentalQueryInsights,streams:i.experimental});let c=Re(l),u=H(i.experimentalQueryInsights),p=t,m=s,g=n,d=i,h=async()=>{c.close(),await Y(e,[g,d,p,m])};return{close:h,dbServer:t,httpServer:n,server:{...o,close:h,experimental:{queryInsights:u,streams:i.experimental,wal:c.api},name:e.name},serverState:e,shadowDbServer:s,streamsServer:i,queryInsightsBridge:a,walBridge:l}}catch(l){return await xe(e,[n,i,t,s],l)}}function Pe(r,e,t,n){let s=`prisma+postgres://localhost:${t.port}/?${new URLSearchParams({api_key:q({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 Y(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 xe(r,e,t){try{await Y(r,e.filter(n=>n!==null))}catch(n){throw new AggregateError([t,n],"Failed to start Prisma Dev server cleanly")}throw t}function Re(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 Ie(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Te(){return{async close(){},subscribe(){return()=>{}}}}function ke(){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)))}}}}var De="default";function Qe(r){return{databaseUrl:r.database.prismaORMConnectionString??r.database.connectionString,prismaPostgresUrl:r.ppg.url,shadowDatabaseUrl:r.shadowDatabase.prismaORMConnectionString??r.shadowDatabase.connectionString}}async function ir(r){let{debug:e,name:t=De}=r??{},n=await $(t,{debug:e});return!U(n)||!n.exports?null:{...Qe(n.exports),name:n.name}}export{tr as a,Qe as b,ir as c};
@@ -0,0 +1,3 @@
1
+ import{e as b,f as g,g as M}from"./chunk-EDFHV3AK.js";import{a as C,c as h,g as V,h as q,i as U,j as J,k as p}from"./chunk-ZEM5OLPM.js";import{mkdir as ue,stat as le,writeFile as de}from"fs/promises";import{join as d}from"pathe";import{check as ce,lock as Y,unlock as me}from"proper-lockfile";import{process as z}from"std-env";import{integer as W,literal as he,minLength as R,minValue as ee,number as te,object as P,optional as c,parseJson as pe,pipe as m,safeParse as be,string as f,url as fe}from"valibot";import{setTimeout as oe}from"timers/promises";import{process as v}from"std-env";function _(r,e){if(r==null)return!1;try{return v.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}async function B(r,e){if(!v.kill)return!1;try{v.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 oe(100)}while(++t<50);try{return v.kill(r,"SIGKILL")}catch(a){return e&&console.error(`Error forcefully killing process with PID ${r}:`,a),!1}}import{join as H}from"pathe";var ie="prisma-wal",Ie="prisma-queries";function ne(){return H(C.data,"durable-streams")}function K(r){return H(ne(),r)}function Re(r,e=ie){return new URL(`/v1/stream/${encodeURIComponent(e)}`,r).toString()}var S=m(f(),fe()),G=P({connectionString:S,prismaORMConnectionString:c(S),terminalCommand:c(f())}),Q=P({url:S}),X=P({serverUrl:S,sqlitePath:m(f(),R(1)),streamName:m(f(),R(1)),url:S}),Pe=P({queryInsights:c(X),streams:c(X)}),k=m(te(),W(),ee(1)),ge=P({database:G,http:Q,ppg:Q,shadowDatabase:G}),we=P({databasePort:k,experimental:c(Pe),exports:c(ge),name:m(f(),R(1)),pid:c(m(te(),W(),ee(0))),port:k,shadowDatabasePort:k,version:he("1")}),L=Symbol("initialize"),Se=1e4,E="default",ye=new Set(["durable-streams"]);function Z(r){return r instanceof Error&&"code"in r&&r.code==="ELOCKED"}async function I(r){try{return await le(r)}catch(e){if(V(e))return null;throw e}}var u=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(e){this._databasePort=e.databasePort??g,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??z.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??g,this._shadowDatabasePort=e.shadowDatabasePort??g,this._streamsPort=e.streamsPort??g}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new w(e):new T(e);return await t[L](),t}static async fromServerDump(e){let{debug:t,name:a=E}=e??{},o=h(a),i=w.getServerDumpPath(o),s=await q(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:l,success:y}=be(m(f(),pe(),we),s);if(!y)throw t&&console.debug(`[State] Invalid server dump file at "${i}":
2
+ ${JSON.stringify(n,null,2)}`),new Error(`Invalid Prisma Dev state for "${a}".`);return new w({databasePort:l.databasePort,debug:t,dryRun:!1,name:a,pid:l.pid,port:l.port,serverDump:l,shadowDatabasePort:l.shadowDatabasePort})}static async scan(e){let{debug:t,globs:a}=e??{},o=d(h(E),"..");t&&console.debug(`[State] scanning for server states in: ${o}`);let i=(await J(o,a)).filter(s=>!ye.has(s));return t&&console.debug(`[State] found server names: ${JSON.stringify(i)}`),await Promise.all(i.map(s=>N(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]!==b&&this[a]!==t)throw new Error(`\`${e}\` is already set to ${this[a]}, cannot change it to ${t}`);this[a]=t}},T=class extends u{constructor(e){super({...e,databasePort:e?.databasePort||b,persistenceMode:"stateless",port:e?.port||b,shadowDatabasePort:e?.shadowDatabasePort||b,streamsPort:e?.streamsPort||b})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[L](){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(){}},w=class r extends u{#t;#o;#e;#r;#i;#n;#s;#a;constructor(e){super({...e,persistenceMode:"stateful"}),this.#s=!1,this.#e=h(this.name),this.#t=d(this.#e,".lock-break"),this.#o=d(this.#e,"db_dump.bak"),this.#r=d(this.#e,".lock"),this.#i=d(this.#e,".pglite"),this.#a=e?.serverDump??null,this.#n=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return d(e,"server.json")}get databaseDumpPath(){return this.#o}get exports(){return this.#a?.exports}get experimental(){return this.#a?.experimental}get pgliteDataDirPath(){return this.#i}async[L](){await U(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await this.#u(),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 Z(e)?new O(this):e}}async#u(){try{await Y(this.#e,{lockfilePath:this.#r});return}catch(e){if(!Z(e)||!await this.#l())throw e}await Y(this.#e,{lockfilePath:this.#r})}async#l(){let e=await I(this.#r);if(e==null)return!0;let t=await N(this.name,{debug:this.debug});if(re(t)||t.status==="unknown"||!await this.#d())return!1;try{let a=await I(this.#r);return a==null?!0:a.ino!==e.ino||a.mtimeMs!==e.mtimeMs?!1:(this.debug&&console.debug(`[State] breaking lock left behind by dead server "${this.name}" (status: ${t.status})`),await p(this.#r),!0)}finally{await p(this.#t)}}async#d(){for(let e=0;e<2;e++){try{return await ue(this.#t),!0}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="EEXIST"))throw a}let t=await I(this.#t);if(t!=null&&Date.now()-t.mtimeMs<Se)return!1;await p(this.#t)}return!1}async close(){if(!this.#s)try{await me(this.#e,{lockfilePath:this.#r}),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.#a={name:this.name,version:"1",pid:z.pid,port:this.port,databasePort:this.databasePort,experimental:t,shadowDatabasePort:this.shadowDatabasePort,exports:e},await de(this.#n,`${JSON.stringify(this.#a,null,2)}
3
+ `,{encoding:"utf-8"})}};async function Fe(r,e){await ve(r,e);let t=typeof r=="string"?r:r.name,a=h(t);await p(a),await p(K(t))}async function N(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:l,pid:y}=n;if(a)return{...s,status:"unknown"};if(!_(y,t))return t&&console.debug(`[State] server state for "${o}" has no running process with PID: ${y}`),{...s,status:"not_running"};let A=h(o);try{if(!await ce(A,{lockfilePath:d(A,".lock")}))return t&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...s,status:"not_running"}}catch(se){t&&console.error(`[State] server state for "${o}" failed to check lock:`,se)}if(!l)return{...s,status:"starting_up"};let{http:ae}=l,D=await fetch(`${ae.url}/health`,{headers:{connection:"close"}});if(!D.ok)return t&&console.debug(`[State] server state for "${o}" is not live: ${JSON.stringify(D)}`),{...s,status:"not_running"};let x=await D.json();return x.name!==r?(t&&console.debug(`[State] server state for "${o}" has mismatched health response: ${JSON.stringify(x)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(x)}`),{...s,status:"running"})}catch(n){return t&&console.error(`[State] failed to get server status for "${o}":`,n),{...s,status:"error"}}}function re(r){let{status:e}=r;return e==="running"||e==="starting_up"}async function ve(r,e){let{pid:t,...a}=typeof r=="string"?await N(r,{debug:e}):r;if(!re(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 B(t,e);try{await o?.close()}catch{}return i}var $=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},O=class extends ${#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{ie as a,Ie as b,ne as c,K as d,Re as e,u as f,Fe as g,N as h,re as i,ve as j,$ as k,O as l};
@@ -1,4 +1,4 @@
1
- import{c as I}from"./chunk-KWCQYPJI.js";import{h as _}from"./chunk-EDFHV3AK.js";import{d as O,f as Q}from"./chunk-DWY47FQV.js";import{createConnection as He,createServer as Ye}from"net";import{join as Ke}from"path";import{filename as ze}from"pathe/utils";import{performance as H}from"perf_hooks";import{protocol as he}from"@electric-sql/pglite";import{Buffer as pe}from"buffer";var C=500,F=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,ge=new RegExp(`(?:${F.source}\\.)*${F.source}`),fe=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${ge.source})`,"gi"),ye=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,$=/prismaQuery='([^']+)'/,Ee=new Set([b(`
1
+ import{c as I}from"./chunk-KWCQYPJI.js";import{h as _}from"./chunk-EDFHV3AK.js";import{d as O,f as Q}from"./chunk-ZEM5OLPM.js";import{createConnection as He,createServer as Ye}from"net";import{join as Ke}from"path";import{filename as ze}from"pathe/utils";import{performance as H}from"perf_hooks";import{protocol as he}from"@electric-sql/pglite";import{Buffer as pe}from"buffer";var C=500,F=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,ge=new RegExp(`(?:${F.source}\\.)*${F.source}`),fe=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${ge.source})`,"gi"),ye=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,$=/prismaQuery='([^']+)'/,Ee=new Set([b(`
2
2
  select b.oid, b.typarray
3
3
  from pg_catalog.pg_type a
4
4
  left join pg_catalog.pg_type b on b.oid = a.typelem
@@ -1 +1 @@
1
- import{a as r}from"./chunk-VSS2IOVU.js";async function s(e){let{server:t}=await r(e);return t}async function A(e){return await s(e)}export{s as a,A as b};
1
+ import{a as r}from"./chunk-AVDGCP6B.js";async function s(e){let{server:t}=await r(e);return t}async function A(e){return await s(e)}export{s as a,A as b};
@@ -1 +1 @@
1
- import{createWriteStream as w,WriteStream as A}from"fs";import{access as D,chmod as x,constants as P,mkdir as T,readdir as E,readFile as _,rm as F,writeFile as O}from"fs/promises";import{promisify as v}from"util";import{unzip as C}from"zlib";import o from"path";import g from"os";import c from"process";var n=g.homedir(),a=g.tmpdir(),{env:e}=c,h=t=>{let r=o.join(n,"Library");return{data:o.join(r,"Application Support",t),config:o.join(r,"Preferences",t),cache:o.join(r,"Caches",t),log:o.join(r,"Logs",t),temp:o.join(a,t)}},y=t=>{let r=e.APPDATA||o.join(n,"AppData","Roaming"),i=e.LOCALAPPDATA||o.join(n,"AppData","Local");return{data:o.join(i,t,"Data"),config:o.join(r,t,"Config"),cache:o.join(i,t,"Cache"),log:o.join(i,t,"Log"),temp:o.join(a,t)}},j=t=>{let r=o.basename(n);return{data:o.join(e.XDG_DATA_HOME||o.join(n,".local","share"),t),config:o.join(e.XDG_CONFIG_HOME||o.join(n,".config"),t),cache:o.join(e.XDG_CACHE_HOME||o.join(n,".cache"),t),log:o.join(e.XDG_STATE_HOME||o.join(n,".local","state"),t),temp:o.join(a,r,t)}};function p(t,{suffix:r="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return r&&(t+=`-${r}`),c.platform==="darwin"?h(t):c.platform==="win32"?y(t):j(t)}import L from"zeptomatch";var l=p("prisma-dev"),G=v(C);function z(t,r){return`${l.cache}/engine/${t}/${r}`}function B(t){return`${l.data}/${t}`}async function J(t){try{return await D(t,P.F_OK),!0}catch(r){if(u(r))return!1;throw r}}async function K(t,r){let i=await G(t);await O(r,i),await x(r,"755")}async function q(t,r){await t.stream().pipeTo(A.toWeb(w(r,{encoding:"utf8"})))}function u(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Q(t){try{return await _(t,{encoding:"utf-8"})}catch(r){if(u(r))return null;throw r}}async function U(t){await T(t,{recursive:!0})}async function V(t,r){try{return(await E(t,{withFileTypes:!0})).reduce((f,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!r||L(r,s.name))&&f.push(s.name),f),[])}catch(i){if(u(i))return[];throw i}}async function Y(t){await F(t,{force:!0,recursive:!0})}export{l as a,z as b,B as c,J as d,K as e,q as f,Q as g,U as h,V as i,Y as j};
1
+ import{createWriteStream as w,WriteStream as A}from"fs";import{access as D,chmod as x,constants as P,mkdir as T,readdir as E,readFile as _,rm as F,writeFile as O}from"fs/promises";import{promisify as v}from"util";import{unzip as C}from"zlib";import o from"path";import g from"os";import c from"process";var n=g.homedir(),a=g.tmpdir(),{env:e}=c,h=t=>{let r=o.join(n,"Library");return{data:o.join(r,"Application Support",t),config:o.join(r,"Preferences",t),cache:o.join(r,"Caches",t),log:o.join(r,"Logs",t),temp:o.join(a,t)}},y=t=>{let r=e.APPDATA||o.join(n,"AppData","Roaming"),i=e.LOCALAPPDATA||o.join(n,"AppData","Local");return{data:o.join(i,t,"Data"),config:o.join(r,t,"Config"),cache:o.join(i,t,"Cache"),log:o.join(i,t,"Log"),temp:o.join(a,t)}},j=t=>{let r=o.basename(n);return{data:o.join(e.XDG_DATA_HOME||o.join(n,".local","share"),t),config:o.join(e.XDG_CONFIG_HOME||o.join(n,".config"),t),cache:o.join(e.XDG_CACHE_HOME||o.join(n,".cache"),t),log:o.join(e.XDG_STATE_HOME||o.join(n,".local","state"),t),temp:o.join(a,r,t)}};function p(t,{suffix:r="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return r&&(t+=`-${r}`),c.platform==="darwin"?h(t):c.platform==="win32"?y(t):j(t)}import L from"zeptomatch";var l=p("prisma-dev"),G=v(C);function z(t,r){return`${l.cache}/engine/${t}/${r}`}function B(t){return`${l.data}/${t}`}async function J(t){try{return await D(t,P.F_OK),!0}catch(r){if(u(r))return!1;throw r}}async function K(t,r){let i=await G(t);await O(r,i),await x(r,"755")}async function q(t,r){await t.stream().pipeTo(A.toWeb(w(r,{encoding:"utf8"})))}function u(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Q(t){try{return await _(t,{encoding:"utf-8"})}catch(r){if(u(r))return null;throw r}}async function U(t){await T(t,{recursive:!0})}async function V(t,r){try{return(await E(t,{withFileTypes:!0})).reduce((f,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&(!r||L(r,s.name))&&f.push(s.name),f),[])}catch(i){if(u(i))return[];throw i}}async function Y(t){await F(t,{force:!0,recursive:!0})}export{l as a,z as b,B as c,J as d,K as e,q as f,u as g,Q as h,U as i,V as j,Y as k};