@prisma/dev 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/state.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var X=Object.create;var v=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var z=(t,e)=>{for(var r in e)v(t,r,{get:e[r],enumerable:!0})},M=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Y(e))!q.call(t,n)&&n!==r&&v(t,n,{get:()=>e[n],enumerable:!(i=K(e,n))||i.enumerable});return t};var A=(t,e,r)=>(r=t!=null?X(Z(t)):{},M(e||!t||!t.__esModule?v(r,"default",{value:t,enumerable:!0}):r,t)),Q=t=>M(v({},"__esModule",{value:!0}),t);var de={};z(de,{ServerState:()=>h,ServerStateAlreadyExistsError:()=>y});module.exports=Q(de);var U=require("fs/promises"),G=require("hono/client"),d=require("pathe"),w=require("proper-lockfile"),b=require("std-env"),s=require("valibot");var L=require("fs"),a=require("fs/promises");var o=A(require("path"),1),E=A(require("os"),1),D=A(require("process"),1),p=E.default.homedir(),O=E.default.tmpdir(),{env:f}=D.default,ee=t=>{let e=o.default.join(p,"Library");return{data:o.default.join(e,"Application Support",t),config:o.default.join(e,"Preferences",t),cache:o.default.join(e,"Caches",t),log:o.default.join(e,"Logs",t),temp:o.default.join(O,t)}},te=t=>{let e=f.APPDATA||o.default.join(p,"AppData","Roaming"),r=f.LOCALAPPDATA||o.default.join(p,"AppData","Local");return{data:o.default.join(r,t,"Data"),config:o.default.join(e,t,"Config"),cache:o.default.join(r,t,"Cache"),log:o.default.join(r,t,"Log"),temp:o.default.join(O,t)}},re=t=>{let e=o.default.basename(p);return{data:o.default.join(f.XDG_DATA_HOME||o.default.join(p,".local","share"),t),config:o.default.join(f.XDG_CONFIG_HOME||o.default.join(p,".config"),t),cache:o.default.join(f.XDG_CACHE_HOME||o.default.join(p,".cache"),t),log:o.default.join(f.XDG_STATE_HOME||o.default.join(p,".local","state"),t),temp:o.default.join(O,e,t)}};function _(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),D.default.platform==="darwin"?ee(t):D.default.platform==="win32"?te(t):re(t)}var se=require("pako"),oe=_("prisma-dev");function g(t){return`${oe.data}/${t}`}function F(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function I(t){try{return await(0,a.readFile)(t,{encoding:"utf-8"})}catch(e){if(F(e))return null;throw e}}async function N(t){await(0,a.mkdir)(t,{recursive:!0})}async function V(t){try{return(await(0,a.readdir)(t,{withFileTypes:!0})).reduce((r,i)=>(i.isDirectory()&&!i.name.startsWith(".")&&r.push(i.name),r),[])}catch(e){if(F(e))return[];throw e}}var C=require("std-env");function B(t,e){if(t==null)return!1;try{return C.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var R=(0,s.pipe)((0,s.string)(),(0,s.url)()),H=(0,s.object)({connectionString:R,prismaORMConnectionString:(0,s.optional)(R),terminalCommand:(0,s.optional)((0,s.string)())}),J=(0,s.object)({url:R}),T=(0,s.pipe)((0,s.number)(),(0,s.integer)(),(0,s.minValue)(1)),ce=(0,s.object)({database:H,http:J,ppg:J,shadowDatabase:H}),ue=(0,s.object)({databasePort:T,exports:(0,s.optional)(ce),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:T,shadowDatabasePort:T,version:(0,s.literal)("1")}),k=Symbol("initialize"),$="default",h=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??$,this.persistenceMode=e.persistenceMode,this.pid=e.pid??b.process.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new P({...e,pid:b.process.pid}):new j(e);return await r[k](),r}static async fromServerDump(e){let{debug:r,name:i=$}=e??{},n=g(i),c=P.getServerDumpPath(n),l=await I(c);if(l==null)return r&&console.debug(`[State] No server dump file found at: ${c}`),null;r&&(console.debug(`[State] server dump file found at "${c}":`),console.debug(l));let{issues:x,output:u,success:m}=(0,s.safeParse)((0,s.pipe)((0,s.string)(),(0,s.parseJson)(),ue),l);if(!m)throw r&&console.debug(`[State] Invalid server dump file at "${c}":
2
- ${JSON.stringify(x,null,2)}`),new Error(`Invalid Prisma Dev state for "${i}".`);return new P({databasePort:u.databasePort,debug:r,dryRun:!1,name:i,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},i=(0,d.join)(g($),"..");r&&console.debug(`[State] scanning for server states in: ${i}`);let n=await V(i);return r&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(c=>pe(c,r)))}},j=class extends h{constructor(e){super({...e,persistenceMode:"stateless",pid:b.process.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[k](){}async close(){}async writeServerDump(){}},P=class t extends h{#s;#e;#o;#i;#t;#r=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=g(this.name),this.#s=(0,d.join)(this.#e,"db_dump.bak"),this.#o=(0,d.join)(this.#e,".pglite"),this.#t=e.serverDump??null,this.#i=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,d.join)(e,"server.json")}get databaseDumpPath(){return this.#s}get exports(){return this.#t?.exports}get pgliteDataDirPath(){return this.#o}async[k](){await N(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await(0,w.lock)(this.#e,{lockfilePath:(0,d.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new y(this.name):e}}async close(){if(this.#r!=null)try{await this.#r(),this.#r=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#t={name:this.name,version:"1",pid:b.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,U.writeFile)(this.#i,`${JSON.stringify(this.#t,null,2)}
3
- `,{encoding:"utf-8"})}};async function pe(t,e){let r={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let i=await h.fromServerDump({debug:e,name:t});if(!i)return e&&console.debug(`[State] no server state found for name: ${t}`),{...r,status:"no_such_server"};r.databasePort=i.databasePort,r.exports=i.exports,r.pid=i.pid,r.port=i.port,r.shadowDatabasePort=i.shadowDatabasePort;let{exports:n,pid:c}=i;if(!B(c,e))return e&&console.debug(`[State] server state for "${t}" has no running process with PID: ${c}`),{...r,status:"not_running"};let l=g(t);try{if(!await(0,w.check)(l,{lockfilePath:(0,d.join)(l,".lock")}))return e&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...r,status:"starting_up"}}catch(W){e&&console.error(`[State] server state for "${t}" failed to check lock:`,W)}if(!n)return{...r,status:"starting_up"};let{http:x}=n,u=await(0,G.hc)(x.url).health.$get();if(!u.ok)return e&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(u)}`),{...r,status:"not_running"};let m=await u.json();return m.name!==t?(e&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(m)}`),{...r,status:"unknown"}):(e&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(m)}`),{...r,status:"running"})}catch(i){return e&&console.error(`[State] failed to get server status for "${t}":`,i),{...r,status:"error"}}}var y=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};0&&(module.exports={ServerState,ServerStateAlreadyExistsError});
1
+ "use strict";var ue=Object.create;var D=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var pe=Object.getPrototypeOf,le=Object.prototype.hasOwnProperty;var fe=(t,e)=>{for(var r in e)D(t,r,{get:e[r],enumerable:!0})},G=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of de(e))!le.call(t,a)&&a!==r&&D(t,a,{get:()=>e[a],enumerable:!(n=ce(e,a))||n.enumerable});return t};var L=(t,e,r)=>(r=t!=null?ue(pe(t)):{},G(e||!t||!t.__esModule?D(r,"default",{value:t,enumerable:!0}):r,t)),he=t=>G(D({},"__esModule",{value:!0}),t);var Te={};fe(Te,{ServerAlreadyRunningError:()=>j,ServerState:()=>b,ServerStateAlreadyExistsError:()=>R});module.exports=he(Te);var ae=require("fs/promises"),ne=require("hono/client"),y=require("pathe"),M=require("proper-lockfile"),J=require("std-env"),o=require("valibot");var W=require("fs"),f=require("fs/promises");var u=L(require("path"),1),U=L(require("os"),1),O=L(require("process"),1),h=U.default.homedir(),B=U.default.tmpdir(),{env:v}=O.default,me=t=>{let e=u.default.join(h,"Library");return{data:u.default.join(e,"Application Support",t),config:u.default.join(e,"Preferences",t),cache:u.default.join(e,"Caches",t),log:u.default.join(e,"Logs",t),temp:u.default.join(B,t)}},Pe=t=>{let e=v.APPDATA||u.default.join(h,"AppData","Roaming"),r=v.LOCALAPPDATA||u.default.join(h,"AppData","Local");return{data:u.default.join(r,t,"Data"),config:u.default.join(e,t,"Config"),cache:u.default.join(r,t,"Cache"),log:u.default.join(r,t,"Log"),temp:u.default.join(B,t)}},be=t=>{let e=u.default.basename(h);return{data:u.default.join(v.XDG_DATA_HOME||u.default.join(h,".local","share"),t),config:u.default.join(v.XDG_CONFIG_HOME||u.default.join(h,".config"),t),cache:u.default.join(v.XDG_CACHE_HOME||u.default.join(h,".cache"),t),log:u.default.join(v.XDG_STATE_HOME||u.default.join(h,".local","state"),t),temp:u.default.join(B,e,t)}};function N(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),O.default.platform==="darwin"?me(t):O.default.platform==="win32"?Pe(t):be(t)}var ge=require("pako"),ye=N("prisma-dev");function S(t){return`${ye.data}/${t}`}function X(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function Y(t){try{return await(0,f.readFile)(t,{encoding:"utf-8"})}catch(e){if(X(e))return null;throw e}}async function Z(t){await(0,f.mkdir)(t,{recursive:!0})}async function z(t){try{return(await(0,f.readdir)(t,{withFileTypes:!0})).reduce((r,n)=>(n.isDirectory()&&!n.name.startsWith(".")&&r.push(n.name),r),[])}catch(e){if(X(e))return[];throw e}}var Q=require("std-env");function ee(t,e){if(t==null)return!1;try{return Q.process.kill?.(t,0)??!0}catch(r){return e&&console.error(`Error checking if process with PID ${t} exists:`,r),!1}}var P=require("get-port-please"),k=require("remeda"),T=51214,$=51213,A=51215,_=65535,m=-1/0;async function re(t){let{debug:e,name:r,requestedPorts:n,servers:a}=t,{portsUsedByOtherServers:s,portsUsedByThisServerLastTime:c}=we(r,a);e&&(console.debug(`ports used by other servers: ${Object.keys(s).join(", ")}`),console.debug(`ports used by "${r}" server last time: ${JSON.stringify(c)}`));let d={databasePort:m,port:m,shadowDatabasePort:m},i=["port","databasePort","shadowDatabasePort"];for(let p of i){let l=await ve({debug:e,portKey:p,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:c,requestedPorts:n})??await Se({debug:e,pickedPorts:d,portKey:p,portsUsedByOtherServers:s,portsUsedByThisServerLastTime:c});e&&console.debug(`Got port for "${p}": ${l}`),d[p]=l}return e&&console.debug(`Picked ports: ${JSON.stringify(d)}`),d}async function ve(t){let{debug:e,portKey:r,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:a,requestedPorts:s}=t,{[r]:c,...d}=s;if(te(c))return await De({debug:e,otherRequestedPorts:d,portKey:r,portsUsedByOtherServers:n,requestedPort:c}),c;let i=a?.[r]??m;if(!te(i))return e&&console.debug(`No port specified for "${r}". Trying to pick a new port.`),null;let p=i in n;return p||Object.values(d).includes(i)?(e&&console.debug(`Port ${i} that was used last time for this server, ${p?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await(0,P.checkPort)(i)===!1?(e&&console.debug(`Port ${i}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(e&&console.debug(`Using port ${i} for "${r}" as it was used last time and is available.`),i)}async function Se(t){let{debug:e,pickedPorts:r,portKey:n,portsUsedByOtherServers:a,portsUsedByThisServerLastTime:s}=t,c=Math.max(T,$,A)+1,d=[...Object.values(r),...Object.keys(a).map(Number),...Object.values(s||{})],i=Math.min(Math.max(c,...d)+100,_),p=(0,k.difference)((0,k.range)(c,i),d),l={port:$,databasePort:T,shadowDatabasePort:A}[n];try{return await(0,P.getPort)({port:l in a||Object.values(r).includes(l)||Object.values(s||{}).includes(l)?void 0:l,ports:p})}catch(g){if(g instanceof Error&&g.name==="GetPortError"&&i+1<=_)return e&&console.debug(`Expanding port lookup to range [${i+1}, ${_}].`),await(0,P.getPort)({portRange:[i+1,_]});throw g}}function te(t){return t>=0}function we(t,e){let r={},n;for(let a of e){let{databasePort:s,port:c,shadowDatabasePort:d}=a;if(a.name===t){n={databasePort:s,port:c,shadowDatabasePort:d};continue}r[s]=!0,r[c]=!0,r[d]=!0}return{portsUsedByOtherServers:r,portsUsedByThisServerLastTime:n}}async function De(t){let{debug:e,otherRequestedPorts:r,portKey:n,portsUsedByOtherServers:a,requestedPort:s}=t;if(s in a)throw e&&console.error(`Port ${s} was requested for "${n}", but is already used by another server.`),new I(s);if(Object.values(r).includes(s))throw e&&console.error(`Port ${s} was requested for "${n}", but also for another key.`),new F(s);if((0,P.isUnsafePort)(s))throw e&&console.error(`Port ${s} was requested for "${n}", but is unsafe.`),new E(s);if(await(0,P.checkPort)(s)===!1)throw e&&console.error(`Port ${s} was requested for "${n}", but is not available.`),new E(s)}var E=class extends Error{constructor(r){super(`Port \`${r}\` is not available.`);this.port=r}name="PortNotAvailableError"},F=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"},I=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 C=(0,o.pipe)((0,o.string)(),(0,o.url)()),se=(0,o.object)({connectionString:C,prismaORMConnectionString:(0,o.optional)(C),terminalCommand:(0,o.optional)((0,o.string)())}),oe=(0,o.object)({url:C}),q=(0,o.pipe)((0,o.number)(),(0,o.integer)(),(0,o.minValue)(1)),Oe=(0,o.object)({database:se,http:oe,ppg:oe,shadowDatabase:se}),xe=(0,o.object)({databasePort:q,exports:(0,o.optional)(Oe),name:(0,o.pipe)((0,o.string)(),(0,o.minLength)(1)),pid:(0,o.optional)((0,o.pipe)((0,o.number)(),(0,o.integer)(),(0,o.minValue)(0))),port:q,shadowDatabasePort:q,version:(0,o.literal)("1")}),K=Symbol("initialize"),V="default",b=class{_databasePort;debug;dryRun;name;persistenceMode;pid;_port;_shadowDatabasePort;constructor(e){this._databasePort=e.databasePort??m,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??V,this.persistenceMode=e.persistenceMode,this.pid=e.pid??J.process.pid,this._port=e.port??m,this._shadowDatabasePort=e.shadowDatabasePort??m}static async createExclusively(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new w(e):new H(e);return await r[K](),r}static async fromServerDump(e){let{debug:r,name:n=V}=e??{},a=S(n),s=w.getServerDumpPath(a),c=await Y(s);if(c==null)return r&&console.debug(`[State] No server dump file found at: ${s}`),null;r&&(console.debug(`[State] server dump file found at "${s}":`),console.debug(c));let{issues:d,output:i,success:p}=(0,o.safeParse)((0,o.pipe)((0,o.string)(),(0,o.parseJson)(),xe),c);if(!p)throw r&&console.debug(`[State] Invalid server dump file at "${s}":
2
+ ${JSON.stringify(d,null,2)}`),new Error(`Invalid Prisma Dev state for "${n}".`);return new w({databasePort:i.databasePort,debug:r,dryRun:!1,name:n,pid:i.pid,port:i.port,serverDump:i,shadowDatabasePort:i.shadowDatabasePort})}static async scan(e){let{debug:r}=e??{},n=(0,y.join)(S(V),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let a=await z(n);return r&&console.debug(`[State] found server names: ${JSON.stringify(a)}`),await Promise.all(a.map(s=>_e(s,e)))}get databasePort(){return this._databasePort}get port(){return this._port}get shadowDatabasePort(){return this._shadowDatabasePort}},H=class extends b{constructor(e){super({...e,databasePort:e?.databasePort??T,persistenceMode:"stateless",port:e?.port??$,shadowDatabasePort:e?.shadowDatabasePort??A})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[K](){}async close(){}async writeServerDump(){}},w=class t extends b{#t;#e;#o;#a;#r;#s=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=S(this.name),this.#t=(0,y.join)(this.#e,"db_dump.bak"),this.#o=(0,y.join)(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,y.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get pgliteDataDirPath(){return this.#o}async[K](){await Z(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#s=await(0,M.lock)(this.#e,{lockfilePath:(0,y.join)(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await b.scan({debug:this.debug,onlyMetadata:!0}),r=await re({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort},servers:e});this._databasePort=r.databasePort,this._port=r.port,this._shadowDatabasePort=r.shadowDatabasePort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new j(this):e}}async close(){if(this.#s!=null)try{await this.#s(),this.#s=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#r={name:this.name,version:"1",pid:J.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,ae.writeFile)(this.#a,`${JSON.stringify(this.#r,null,2)}
3
+ `,{encoding:"utf-8"})}};async function _e(t,e){let{debug:r,onlyMetadata:n}=e||{},a={databasePort:-1,exports:void 0,name:t,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await b.fromServerDump({debug:r,name:t});if(!s)return r&&console.debug(`[State] no server state found for name: ${t}`),{...a,status:"no_such_server"};a.databasePort=s.databasePort,a.exports=s.exports,a.pid=s.pid,a.port=s.port,a.shadowDatabasePort=s.shadowDatabasePort;let{exports:c,pid:d}=s;if(n)return{...a,status:"unknown"};if(!ee(d,r))return r&&console.debug(`[State] server state for "${t}" has no running process with PID: ${d}`),{...a,status:"not_running"};let i=S(t);try{if(!await(0,M.check)(i,{lockfilePath:(0,y.join)(i,".lock")}))return r&&console.debug(`[State] server state for "${t}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(ie){r&&console.error(`[State] server state for "${t}" failed to check lock:`,ie)}if(!c)return{...a,status:"starting_up"};let{http:p}=c,l=await(0,ne.hc)(p.url).health.$get();if(!l.ok)return r&&console.debug(`[State] server state for "${t}" is not live: ${JSON.stringify(l)}`),{...a,status:"not_running"};let g=await l.json();return g.name!==t?(r&&console.debug(`[State] server state for "${t}" has mismatched health response: ${JSON.stringify(g)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(g)}`),{...a,status:"running"})}catch(s){return r&&console.error(`[State] failed to get server status for "${t}":`,s),{...a,status:"error"}}}var R=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},j=class extends R{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return b.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};0&&(module.exports={ServerAlreadyRunningError,ServerState,ServerStateAlreadyExistsError});
package/dist/state.d.cts CHANGED
@@ -1,3 +1,163 @@
1
- import 'valibot';
2
- export { E as Exports, f as PersistenceMode, R as ResolvedServerOptions, g as ScanOptions, e as ServerDumpV1, S as ServerOptions, h as ServerState, j as ServerStateAlreadyExistsError, i as ServerStatusV1 } from './db-B1_DGnTu.cjs';
3
- import '@electric-sql/pglite';
1
+ import * as valibot from 'valibot';
2
+ import { InferOutput } from 'valibot';
3
+
4
+ declare const exportsSchema: valibot.ObjectSchema<{
5
+ readonly database: valibot.ObjectSchema<{
6
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
7
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
8
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
9
+ }, undefined>;
10
+ readonly http: valibot.ObjectSchema<{
11
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
12
+ }, undefined>;
13
+ readonly ppg: valibot.ObjectSchema<{
14
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
15
+ }, undefined>;
16
+ readonly shadowDatabase: valibot.ObjectSchema<{
17
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
18
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
19
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
20
+ }, undefined>;
21
+ }, undefined>;
22
+ type Exports = InferOutput<typeof exportsSchema>;
23
+ declare const serverDumpV1Schema: valibot.ObjectSchema<{
24
+ readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
25
+ readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
26
+ readonly database: valibot.ObjectSchema<{
27
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
28
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
29
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
30
+ }, undefined>;
31
+ readonly http: valibot.ObjectSchema<{
32
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
33
+ }, undefined>;
34
+ readonly ppg: valibot.ObjectSchema<{
35
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
36
+ }, undefined>;
37
+ readonly shadowDatabase: valibot.ObjectSchema<{
38
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
39
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
40
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
41
+ }, undefined>;
42
+ }, undefined>, undefined>;
43
+ readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
44
+ readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
45
+ readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
46
+ readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
47
+ readonly version: valibot.LiteralSchema<"1", undefined>;
48
+ }, undefined>;
49
+ type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
50
+ interface ServerOptions {
51
+ /**
52
+ * The port the database server will listen on.
53
+ *
54
+ * Defaults to `51214`.
55
+ *
56
+ * An error is thrown if the port is already in use.
57
+ */
58
+ databasePort?: number;
59
+ /**
60
+ * Whether to enable debug logging.
61
+ *
62
+ * Defaults to `false`.
63
+ */
64
+ debug?: boolean;
65
+ /**
66
+ * Whether to run the server in dry run mode.
67
+ *
68
+ * Defaults to `false`.
69
+ */
70
+ dryRun?: boolean;
71
+ /**
72
+ * The name of the server.
73
+ *
74
+ * Defaults to `default`.
75
+ */
76
+ name?: string;
77
+ /**
78
+ * The persistence mode of the server.
79
+ *
80
+ * Default is `stateless`.
81
+ */
82
+ persistenceMode?: PersistenceMode;
83
+ /**
84
+ * The port the server will listen on.
85
+ *
86
+ * Defaults to `51213`.
87
+ *
88
+ * An error is thrown if the port is already in use.
89
+ */
90
+ port?: number;
91
+ /**
92
+ * The port the shadow database server will listen on.
93
+ *
94
+ * Defaults to `51215`.
95
+ *
96
+ * An error is thrown if the port is already in use.
97
+ */
98
+ shadowDatabasePort?: number;
99
+ }
100
+ type ResolvedServerOptions = Required<ServerOptions>;
101
+ type PersistenceMode = "stateless" | "stateful";
102
+ interface ScanOptions {
103
+ debug?: boolean;
104
+ onlyMetadata?: boolean;
105
+ }
106
+ declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
107
+ declare abstract class ServerState implements ResolvedServerOptions {
108
+ protected _databasePort: number;
109
+ readonly debug: boolean;
110
+ readonly dryRun: boolean;
111
+ readonly name: string;
112
+ readonly persistenceMode: PersistenceMode;
113
+ readonly pid: number | undefined;
114
+ protected _port: number;
115
+ protected _shadowDatabasePort: number;
116
+ protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
117
+ persistenceMode: PersistenceMode;
118
+ pid?: number | undefined;
119
+ });
120
+ static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
121
+ static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
122
+ static scan(options?: ScanOptions): Promise<ServerStatusV1[]>;
123
+ abstract get databaseDumpPath(): string;
124
+ abstract get pgliteDataDirPath(): string;
125
+ abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
126
+ abstract close(): Promise<void>;
127
+ abstract writeServerDump(exports?: Exports): Promise<void>;
128
+ get databasePort(): number;
129
+ get port(): number;
130
+ get shadowDatabasePort(): number;
131
+ }
132
+ declare class StatefulServerState extends ServerState {
133
+ #private;
134
+ constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
135
+ pid?: number | undefined;
136
+ serverDump?: ServerDumpV1;
137
+ }) | undefined);
138
+ static getServerDumpPath(dataDirPath: string): string;
139
+ get databaseDumpPath(): string;
140
+ get exports(): Exports | undefined;
141
+ get pgliteDataDirPath(): string;
142
+ [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
143
+ close(): Promise<void>;
144
+ writeServerDump(exports?: Exports): Promise<void>;
145
+ }
146
+ interface ServerStatusV1 extends ServerDumpV1 {
147
+ status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
148
+ }
149
+ /**
150
+ * @deprecated use `ServerAlreadyRunningError` instead. Will be removed in a future version.
151
+ */
152
+ declare class ServerStateAlreadyExistsError extends Error {
153
+ name: string;
154
+ constructor(name: string);
155
+ }
156
+ declare class ServerAlreadyRunningError extends ServerStateAlreadyExistsError {
157
+ #private;
158
+ name: string;
159
+ constructor(server: ServerState);
160
+ get server(): Promise<ServerState | null>;
161
+ }
162
+
163
+ export { type Exports, type PersistenceMode, type ResolvedServerOptions, type ScanOptions, ServerAlreadyRunningError, type ServerDumpV1, type ServerOptions, ServerState, ServerStateAlreadyExistsError, type ServerStatusV1 };
package/dist/state.d.ts CHANGED
@@ -1,3 +1,163 @@
1
- import 'valibot';
2
- export { E as Exports, f as PersistenceMode, R as ResolvedServerOptions, g as ScanOptions, e as ServerDumpV1, S as ServerOptions, h as ServerState, j as ServerStateAlreadyExistsError, i as ServerStatusV1 } from './db-B1_DGnTu.js';
3
- import '@electric-sql/pglite';
1
+ import * as valibot from 'valibot';
2
+ import { InferOutput } from 'valibot';
3
+
4
+ declare const exportsSchema: valibot.ObjectSchema<{
5
+ readonly database: valibot.ObjectSchema<{
6
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
7
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
8
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
9
+ }, undefined>;
10
+ readonly http: valibot.ObjectSchema<{
11
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
12
+ }, undefined>;
13
+ readonly ppg: valibot.ObjectSchema<{
14
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
15
+ }, undefined>;
16
+ readonly shadowDatabase: valibot.ObjectSchema<{
17
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
18
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
19
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
20
+ }, undefined>;
21
+ }, undefined>;
22
+ type Exports = InferOutput<typeof exportsSchema>;
23
+ declare const serverDumpV1Schema: valibot.ObjectSchema<{
24
+ readonly databasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
25
+ readonly exports: valibot.OptionalSchema<valibot.ObjectSchema<{
26
+ readonly database: valibot.ObjectSchema<{
27
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
28
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
29
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
30
+ }, undefined>;
31
+ readonly http: valibot.ObjectSchema<{
32
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
33
+ }, undefined>;
34
+ readonly ppg: valibot.ObjectSchema<{
35
+ readonly url: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
36
+ }, undefined>;
37
+ readonly shadowDatabase: valibot.ObjectSchema<{
38
+ readonly connectionString: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>;
39
+ readonly prismaORMConnectionString: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.UrlAction<string, undefined>]>, undefined>;
40
+ readonly terminalCommand: valibot.OptionalSchema<valibot.StringSchema<undefined>, undefined>;
41
+ }, undefined>;
42
+ }, undefined>, undefined>;
43
+ readonly name: valibot.SchemaWithPipe<readonly [valibot.StringSchema<undefined>, valibot.MinLengthAction<string, 1, undefined>]>;
44
+ readonly pid: valibot.OptionalSchema<valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 0, undefined>]>, undefined>;
45
+ readonly port: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
46
+ readonly shadowDatabasePort: valibot.SchemaWithPipe<readonly [valibot.NumberSchema<undefined>, valibot.IntegerAction<number, undefined>, valibot.MinValueAction<number, 1, undefined>]>;
47
+ readonly version: valibot.LiteralSchema<"1", undefined>;
48
+ }, undefined>;
49
+ type ServerDumpV1 = InferOutput<typeof serverDumpV1Schema>;
50
+ interface ServerOptions {
51
+ /**
52
+ * The port the database server will listen on.
53
+ *
54
+ * Defaults to `51214`.
55
+ *
56
+ * An error is thrown if the port is already in use.
57
+ */
58
+ databasePort?: number;
59
+ /**
60
+ * Whether to enable debug logging.
61
+ *
62
+ * Defaults to `false`.
63
+ */
64
+ debug?: boolean;
65
+ /**
66
+ * Whether to run the server in dry run mode.
67
+ *
68
+ * Defaults to `false`.
69
+ */
70
+ dryRun?: boolean;
71
+ /**
72
+ * The name of the server.
73
+ *
74
+ * Defaults to `default`.
75
+ */
76
+ name?: string;
77
+ /**
78
+ * The persistence mode of the server.
79
+ *
80
+ * Default is `stateless`.
81
+ */
82
+ persistenceMode?: PersistenceMode;
83
+ /**
84
+ * The port the server will listen on.
85
+ *
86
+ * Defaults to `51213`.
87
+ *
88
+ * An error is thrown if the port is already in use.
89
+ */
90
+ port?: number;
91
+ /**
92
+ * The port the shadow database server will listen on.
93
+ *
94
+ * Defaults to `51215`.
95
+ *
96
+ * An error is thrown if the port is already in use.
97
+ */
98
+ shadowDatabasePort?: number;
99
+ }
100
+ type ResolvedServerOptions = Required<ServerOptions>;
101
+ type PersistenceMode = "stateless" | "stateful";
102
+ interface ScanOptions {
103
+ debug?: boolean;
104
+ onlyMetadata?: boolean;
105
+ }
106
+ declare const PRIVATE_INITIALIZE_SYMBOL: unique symbol;
107
+ declare abstract class ServerState implements ResolvedServerOptions {
108
+ protected _databasePort: number;
109
+ readonly debug: boolean;
110
+ readonly dryRun: boolean;
111
+ readonly name: string;
112
+ readonly persistenceMode: PersistenceMode;
113
+ readonly pid: number | undefined;
114
+ protected _port: number;
115
+ protected _shadowDatabasePort: number;
116
+ protected constructor(options: Omit<ServerOptions, "persistenceMode"> & {
117
+ persistenceMode: PersistenceMode;
118
+ pid?: number | undefined;
119
+ });
120
+ static createExclusively(options: ServerOptions | undefined): Promise<ServerState>;
121
+ static fromServerDump(options?: Pick<ServerOptions, "debug" | "name">): Promise<StatefulServerState | null>;
122
+ static scan(options?: ScanOptions): Promise<ServerStatusV1[]>;
123
+ abstract get databaseDumpPath(): string;
124
+ abstract get pgliteDataDirPath(): string;
125
+ abstract [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
126
+ abstract close(): Promise<void>;
127
+ abstract writeServerDump(exports?: Exports): Promise<void>;
128
+ get databasePort(): number;
129
+ get port(): number;
130
+ get shadowDatabasePort(): number;
131
+ }
132
+ declare class StatefulServerState extends ServerState {
133
+ #private;
134
+ constructor(options: (Omit<ServerOptions, "persistenceMode"> & {
135
+ pid?: number | undefined;
136
+ serverDump?: ServerDumpV1;
137
+ }) | undefined);
138
+ static getServerDumpPath(dataDirPath: string): string;
139
+ get databaseDumpPath(): string;
140
+ get exports(): Exports | undefined;
141
+ get pgliteDataDirPath(): string;
142
+ [PRIVATE_INITIALIZE_SYMBOL](): Promise<void>;
143
+ close(): Promise<void>;
144
+ writeServerDump(exports?: Exports): Promise<void>;
145
+ }
146
+ interface ServerStatusV1 extends ServerDumpV1 {
147
+ status: "running" | "starting_up" | "not_running" | "no_such_server" | "unknown" | "error";
148
+ }
149
+ /**
150
+ * @deprecated use `ServerAlreadyRunningError` instead. Will be removed in a future version.
151
+ */
152
+ declare class ServerStateAlreadyExistsError extends Error {
153
+ name: string;
154
+ constructor(name: string);
155
+ }
156
+ declare class ServerAlreadyRunningError extends ServerStateAlreadyExistsError {
157
+ #private;
158
+ name: string;
159
+ constructor(server: ServerState);
160
+ get server(): Promise<ServerState | null>;
161
+ }
162
+
163
+ export { type Exports, type PersistenceMode, type ResolvedServerOptions, type ScanOptions, ServerAlreadyRunningError, type ServerDumpV1, type ServerOptions, ServerState, ServerStateAlreadyExistsError, type ServerStatusV1 };
package/dist/state.js CHANGED
@@ -1 +1 @@
1
- import{a,b}from"./chunk-4M2BYKUR.js";import"./chunk-Q3M6SQC2.js";export{a as ServerState,b as ServerStateAlreadyExistsError};
1
+ import{a,b,c}from"./chunk-BS26VSZW.js";import"./chunk-H6HHF4W5.js";export{c as ServerAlreadyRunningError,a as ServerState,b as ServerStateAlreadyExistsError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/dev",
3
- "version": "0.7.1",
3
+ "version": "0.9.0",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -66,11 +66,11 @@
66
66
  "@types/node": "22.15.21",
67
67
  "@types/pako": "2.0.3",
68
68
  "@types/proper-lockfile": "4.1.4",
69
+ "env-paths": "3.0.0",
69
70
  "pkg-types": "2.1.0",
70
71
  "tsup": "8.5.0",
71
72
  "typescript": "5.8.3",
72
73
  "vitest": "3.1.4",
73
- "env-paths": "3.0.0",
74
74
  "common-stuff": "^0.0.0"
75
75
  },
76
76
  "dependencies": {
@@ -80,12 +80,14 @@
80
80
  "@hono/node-server": "1.14.2",
81
81
  "@prisma/get-platform": "6.8.2",
82
82
  "foreground-child": "3.3.1",
83
+ "get-port-please": "3.1.2",
83
84
  "hono": "4.7.10",
84
85
  "http-status-codes": "2.3.0",
85
86
  "pako": "2.1.0",
86
87
  "pathe": "2.0.3",
87
88
  "proper-lockfile": "4.1.2",
88
89
  "read-last-lines-ts": "1.2.1",
90
+ "remeda": "2.21.3",
89
91
  "sock-daemon": "1.4.2",
90
92
  "std-env": "3.9.0",
91
93
  "valibot": "1.1.0"
@@ -1,3 +0,0 @@
1
- import{b as c,f as O,g as $,h as E,i as R,j as _,k}from"./chunk-Q3M6SQC2.js";import{writeFile as j}from"fs/promises";import{hc as B}from"hono/client";import{join as u}from"pathe";import{check as C,lock as H}from"proper-lockfile";import{process as m}from"std-env";import{integer as T,literal as Y,minLength as Z,minValue as V,number as N,object as g,optional as f,parseJson as q,pipe as l,safeParse as z,string as b,url as K}from"valibot";import{process as U}from"std-env";function A(r,e){if(r==null)return!1;try{return U.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}var D=l(b(),K()),M=g({connectionString:D,prismaORMConnectionString:f(D),terminalCommand:f(b())}),I=g({url:D}),P=l(N(),T(),V(1)),W=g({database:M,http:I,ppg:I,shadowDatabase:M}),G=g({databasePort:P,exports:f(W),name:l(b(),Z(1)),pid:f(l(N(),T(),V(0))),port:P,shadowDatabasePort:P,version:Y("1")}),x=Symbol("initialize"),S="default",h=class{databasePort;debug;dryRun;name;persistenceMode;pid;port;shadowDatabasePort;constructor(e){this.databasePort=e.databasePort??51214,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??S,this.persistenceMode=e.persistenceMode,this.pid=e.pid??m.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new p({...e,pid:m.pid}):new y(e);return await t[x](),t}static async fromServerDump(e){let{debug:t,name:s=S}=e??{},n=c(s),a=p.getServerDumpPath(n),i=await O(a);if(i==null)return t&&console.debug(`[State] No server dump file found at: ${a}`),null;t&&(console.debug(`[State] server dump file found at "${a}":`),console.debug(i));let{issues:v,output:o,success:d}=z(l(b(),q(),G),i);if(!d)throw t&&console.debug(`[State] Invalid server dump file at "${a}":
2
- ${JSON.stringify(v,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new p({databasePort:o.databasePort,debug:t,dryRun:!1,name:s,pid:o.pid,port:o.port,serverDump:o,shadowDatabasePort:o.shadowDatabasePort})}static async scan(e){let{debug:t}=e??{},s=u(c(S),"..");t&&console.debug(`[State] scanning for server states in: ${s}`);let n=await E(s);return t&&console.debug(`[State] found server names: ${JSON.stringify(n)}`),await Promise.all(n.map(a=>Q(a,t)))}},y=class extends h{constructor(e){super({...e,persistenceMode:"stateless",pid:m.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[x](){}async close(){}async writeServerDump(){}},p=class r extends h{#s;#e;#a;#o;#t;#r=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=c(this.name),this.#s=u(this.#e,"db_dump.bak"),this.#a=u(this.#e,".pglite"),this.#t=e.serverDump??null,this.#o=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return u(e,"server.json")}get databaseDumpPath(){return this.#s}get exports(){return this.#t?.exports}get pgliteDataDirPath(){return this.#a}async[x](){await $(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await H(this.#e,{lockfilePath:u(this.#e,".lock")}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`),await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new w(this.name):e}}async close(){if(this.#r!=null)try{await this.#r(),this.#r=null,this.debug&&console.debug(`[State] released lock on: ${this.#e}`)}catch(e){throw console.error(`[State] failed to release lock on: ${this.#e}`),e}}async writeServerDump(e){this.#t={name:this.name,version:"1",pid:m.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await j(this.#o,`${JSON.stringify(this.#t,null,2)}
3
- `,{encoding:"utf-8"})}};async function Q(r,e){let t={databasePort:-1,exports:void 0,name:r,pid:void 0,port:-1,shadowDatabasePort:-1,version:"1"};try{let s=await h.fromServerDump({debug:e,name:r});if(!s)return e&&console.debug(`[State] no server state found for name: ${r}`),{...t,status:"no_such_server"};t.databasePort=s.databasePort,t.exports=s.exports,t.pid=s.pid,t.port=s.port,t.shadowDatabasePort=s.shadowDatabasePort;let{exports:n,pid:a}=s;if(!A(a,e))return e&&console.debug(`[State] server state for "${r}" has no running process with PID: ${a}`),{...t,status:"not_running"};let i=c(r);try{if(!await C(i,{lockfilePath:u(i,".lock")}))return e&&console.debug(`[State] server state for "${r}" is not locked, indicating it is not running.`),{...t,status:"starting_up"}}catch(L){e&&console.error(`[State] server state for "${r}" failed to check lock:`,L)}if(!n)return{...t,status:"starting_up"};let{http:v}=n,o=await B(v.url).health.$get();if(!o.ok)return e&&console.debug(`[State] server state for "${r}" is not live: ${JSON.stringify(o)}`),{...t,status:"not_running"};let d=await o.json();return d.name!==r?(e&&console.debug(`[State] server state for "${r}" has mismatched health response: ${JSON.stringify(d)}`),{...t,status:"unknown"}):(e&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(d)}`),{...t,status:"running"})}catch(s){return e&&console.error(`[State] failed to get server status for "${r}":`,s),{...t,status:"error"}}}var w=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};export{h as a,w as b};
@@ -1 +0,0 @@
1
- import{e as l,l as m}from"./chunk-Q3M6SQC2.js";import{PGlite as b}from"@electric-sql/pglite";import{PGLiteSocketServer as P}from"@electric-sql/pglite-socket";import{filename as w}from"pathe/utils";var n={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},y=`postgres://${n.username}:${n.password}@localhost`,f=new URLSearchParams({sslmode:n.sslMode}),p=new URLSearchParams({...Object.fromEntries(f.entries()),connection_limit:String(n.connectionLimit),connect_timeout:String(n.connectTimeout),max_idle_connection_lifetime:String(n.maxIdleConnectionLifetime),pool_timeout:String(n.poolTimeout),single_use_connections:"true",socket_timeout:String(n.socketTimeout)});async function L(e,o){let c=e==="database"?o.databasePort:o.shadowDatabasePort;if(o.dryRun)return u(e,o,{db:null,port:c,server:null});let{debug:a}=o,i=await(e==="shadow_database"?v:D)(o.pgliteDataDirPath,a);a&&i.onNotification((t,r)=>{console.debug(`[${e}][${t}] ${r}`)});let d=new P({db:i,debug:a,inspect:a,port:c});a&&(d.addEventListener("listening",t=>{let{detail:r}=t;console.debug(`[${e}] server listening on ${JSON.stringify(r)}`)}),d.addEventListener("connection",t=>{let{clientAddress:r,clientPort:S}=t.detail;console.debug(`[${e}] client connected from ${r}:${S}`)}),d.addEventListener("error",t=>{let{detail:r}=t;console.error(`[${e}] server error:`,r)}));try{await d.start()}catch(t){throw t instanceof Error&&"code"in t&&t.code==="EADDRINUSE"?new m(c,e):t}return u(e,o,{db:i,port:c,server:d})}function u(e,o,c){let{debug:a}=o,{db:s,port:i,server:d}=c||{};return a&&console.debug(`[${e}] server started on port ${i}`),{...n,close:async()=>{let t=[];try{await d?.stop(),a&&console.debug(`[${e}] server stopped on port ${i}`)}catch(r){console.error(`[${e}] server stop error`,r),t.push(r)}if(e==="database")try{await s?.syncToFs(),a&&console.debug(`[${e}] synced to filesystem`)}catch(r){console.error(`[${e}] sync error`,r),t.push(r)}try{await s?.close(),a&&console.debug(`[${e}] closed`)}catch(r){console.error(`[${e}] close error`,r),t.push(r)}if(t.length>0)throw new AggregateError(t,`Failed to close ${e} properly`)},connectionString:g(i,f),dump:async t=>{e==="shadow_database"||!s||await $({db:s,debug:a,destinationPath:t})},port:i,prismaORMConnectionString:g(i,p),terminalCommand:`PGPASSWORD=${n.password} PGSSLMODE=${n.sslMode} psql -h localhost -p ${i} -U ${n.username} -d ${n.database}`}}function g(e,o){return`${y}:${e}/${n.database}?${o.toString()}`}async function D(e,o){return await b.create({database:n.database,dataDir:e,debug:o?5:void 0,relaxedDurability:!1,username:n.username})}async function v(e,o){return await b.create({database:n.database,dataDir:"memory://",debug:o?5:void 0,relaxedDurability:!1,username:n.username})}async function $(e){let{dataDir:o,db:c,debug:a,destinationPath:s}=e,i=c||await D(o,a),{pgDump:d}=await import("@electric-sql/pglite-tools/pg_dump"),t=await d({args:["--schema-only","--no-owner"],fileName:s?w(s):void 0,pg:await i.clone()});return s?(a&&console.debug(`[DB] Dumping database to ${s}`),await l(t,s)):(a&&console.debug("[DB] Dumping database to memory"),await t.text())}export{L as a,$ as b};
@@ -1 +0,0 @@
1
- import{createWriteStream as j,WriteStream as P}from"fs";import{access as y,chmod as E,constants as x,mkdir as T,readdir as w,readFile as _,writeFile as v}from"fs/promises";import o from"path";import g from"os";import c from"process";var i=g.homedir(),a=g.tmpdir(),{env:n}=c,m=r=>{let t=o.join(i,"Library");return{data:o.join(t,"Application Support",r),config:o.join(t,"Preferences",r),cache:o.join(t,"Caches",r),log:o.join(t,"Logs",r),temp:o.join(a,r)}},h=r=>{let t=n.APPDATA||o.join(i,"AppData","Roaming"),e=n.LOCALAPPDATA||o.join(i,"AppData","Local");return{data:o.join(e,r,"Data"),config:o.join(t,r,"Config"),cache:o.join(e,r,"Cache"),log:o.join(e,r,"Log"),temp:o.join(a,r)}},D=r=>{let t=o.basename(i);return{data:o.join(n.XDG_DATA_HOME||o.join(i,".local","share"),r),config:o.join(n.XDG_CONFIG_HOME||o.join(i,".config"),r),cache:o.join(n.XDG_CACHE_HOME||o.join(i,".cache"),r),log:o.join(n.XDG_STATE_HOME||o.join(i,".local","state"),r),temp:o.join(a,t,r)}};function p(r,{suffix:t="nodejs"}={}){if(typeof r!="string")throw new TypeError(`Expected a string, got ${typeof r}`);return t&&(r+=`-${t}`),c.platform==="darwin"?m(r):c.platform==="win32"?h(r):D(r)}import{inflate as O}from"pako";var d=p("prisma-dev");function G(r,t){return`${d.cache}/engine/${r}/${t}`}function N(r){return`${d.data}/${r}`}async function W(r){try{return await y(r,x.F_OK),!0}catch(t){if(u(t))return!1;throw t}}async function k(r,t){let e=O(r);await v(t,e),await E(t,"755")}async function M(r,t){await r.stream().pipeTo(P.toWeb(j(t,{encoding:"utf-8"})))}function u(r){return r!=null&&typeof r=="object"&&"code"in r&&r.code==="ENOENT"}async function X(r){try{return await _(r,{encoding:"utf-8"})}catch(t){if(u(t))return null;throw t}}async function U(r){await T(r,{recursive:!0})}async function I(r){try{return(await w(r,{withFileTypes:!0})).reduce((e,s)=>(s.isDirectory()&&!s.name.startsWith(".")&&e.push(s.name),e),[])}catch(t){if(u(t))return[];throw t}}var V=51214,q=51213,z=51215,A=class extends Error{constructor(e,s){super(`Port number \`${e}\` is not available for service ${s}.`);this.port=e;this.service=s}name="PortNotAvailableError"};export{G as a,N as b,W as c,k as d,M as e,X as f,U as g,I as h,V as i,q as j,z as k,A as l};