import{e as m,f as P,g as M}from"./chunk-EDFHV3AK.js";import{a as A,c,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 h}from"pathe";import{check as se,lock as oe,unlock as ie}from"proper-lockfile";import{process as B}from"std-env";import{integer as G,literal as ne,minLength as k,minValue as K,number as Z,object as f,optional as p,parseJson as ue,pipe as l,safeParse as de,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 q}from"pathe";var te="prisma-wal";function re(){return q(A.data,"durable-streams")}function F(r){return q(re(),r)}function xe(r,e=te){return new URL(`/v1/stream/${encodeURIComponent(e)}`,r).toString()}var S=l(b(),le()),H=f({connectionString:S,prismaORMConnectionString:p(S),terminalCommand:p(b())}),Y=f({url:S}),ce=f({serverUrl:S,sqlitePath:l(b(),k(1)),streamName:l(b(),k(1)),url:S}),me=f({streams:p(ce)}),E=l(Z(),G(),K(1)),he=f({database:H,http:Y,ppg:Y,shadowDatabase:H}),pe=f({databasePort:E,experimental:p(me),exports:p(he),name:l(b(),k(1)),pid:p(l(Z(),G(),K(0))),port:E,shadowDatabasePort:E,version:ne("1")}),O=Symbol("initialize"),I="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??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??I,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??P,this._shadowDatabasePort=e.shadowDatabasePort??P,this._streamsPort=e.streamsPort??P}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new g(e):new $(e);return await t[O](),t}static async fromServerDump(e){let{debug:t,name:a=I}=e??{},o=c(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}=de(l(b(),ue(),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=h(c(I),"..");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]!==m&&this[a]!==t)throw new Error(`\`${e}\` is already set to ${this[a]}, cannot change it to ${t}`);this[a]=t}},$=class extends u{constructor(e){super({...e,databasePort:e?.databasePort||m,persistenceMode:"stateless",port:e?.port||m,shadowDatabasePort:e?.shadowDatabasePort||m,streamsPort:e?.streamsPort||m})}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=c(this.name),this.#t=h(this.#e,"db_dump.bak"),this.#a=h(this.#e,".lock"),this.#o=h(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#i=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return h(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 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 T(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:B.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=c(t);await x(a),await x(F(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=c(o);try{if(!await se(N,{lockfilePath:h(N,".lock")}))return t&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...s,status:"not_running"}}catch(Q){t&&console.error(`[State] server state for "${o}" failed to check lock:`,Q)}if(!d)return{...s,status:"starting_up"};let{http:W}=d,{hc:X}=await import("hono/client"),w=await X(W.url).health.$get();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 fe(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(!fe(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 R=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},T=class extends R{#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{te as a,re as b,F as c,xe as d,u as e,Ve as f,z as g,fe as h,Pe as i,R as j,T as k};
