6 lines
36 KiB
JavaScript
6 lines
36 KiB
JavaScript
|
|
"use strict";var Ut=Object.create;var Q=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var Vt=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,Gt=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(t&&(e=t(t=0)),e);var ce=(t,e)=>{for(var r in e)Q(t,r,{get:e[r],enumerable:!0})},Ie=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Vt(e))!Gt.call(t,n)&&n!==r&&Q(t,n,{get:()=>e[n],enumerable:!(o=qt(e,n))||o.enumerable});return t};var u=(t,e,r)=>(r=t!=null?Ut(Ft(t)):{},Ie(e||!t||!t.__esModule?Q(r,"default",{value:t,enumerable:!0}):r,t)),Kt=t=>Ie(Q({},"__esModule",{value:!0}),t);var p=D(()=>{"use strict"});function Ce(t){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([[e],[r]])=>e.localeCompare(r)))),"utf8").toString("base64url")}function Jt(t){let e=Buffer.from(t,"base64url").toString("utf8"),{issues:r,output:o,success:n}=(0,g.safeParse)(Qt,e,{abortEarly:!0});return n?[null,o]:[r]}var g,ke,Qt,I,ue=D(()=>{"use strict";p();g=require("valibot"),ke=/^(postgres|postgresql):\/\//,Qt=(0,g.pipe)((0,g.string)(),(0,g.parseJson)(),(0,g.object)({databaseUrl:(0,g.pipe)((0,g.string)(),(0,g.url)(),(0,g.regex)(ke)),name:(0,g.optional)((0,g.pipe)((0,g.string)(),(0,g.minLength)(1))),shadowDatabaseUrl:(0,g.pipe)((0,g.string)(),(0,g.url)(),(0,g.regex)(ke))}));I=async(t,e)=>{let{authorization:r}=t,{HTTPException:o}=await import("hono/http-exception");if(!r)throw new o(401,{message:"Missing API Key"});let[n,s="",a]=r.split(" ");if(n!=="Bearer"||a)throw new o(401,{message:"Invalid API Key"});let[i,c]=Jt(s);if(i)throw new o(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:d,name:m,shadowDatabaseUrl:h}=c,b=e.get("name"),T=new URL(e.req.url).port;if(!m)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${T} requires an API Key from a newer version of \`prisma dev\`. Check the "${b}" server's output for the updated \`DATABASE_URL\` value.`});if(m!==b)throw new o(401,{message:`Wrong API Key; The Prisma Dev server running at port ${T} is named "${b}", but the API Key is for "${m}"`});let{hostname:R,port:N}=new URL(d),{port:Lt}=e.get("db"),{hostname:Bt,port:jt}=new URL(h),Nt=e.get("shadowDBPort");if(R!=="localhost"||Number(N)!==Lt||Bt!=="localhost"||Number(jt)!==Nt)throw new o(401,{message:"Wrong API Key; Check your Prisma schema's `provider.url` value (probably defined in `.env`'s `DATABASE_URL` environment variable) is aligned with `prisma dev`'s output"});return{decodedAPIKey:c}}});function pe(t,{suffix:e="nodejs"}={}){if(typeof t!="string")throw new TypeError(`Expected a string, got ${typeof t}`);return e&&(t+=`-${e}`),J.default.platform==="darwin"?Wt(t):J.default.platform==="win32"?zt(t):Yt(t)}var y,de,J,O,le,M,Wt,zt,Yt,Me=D(()=>{"use strict";p();y=u(require("path"),1),de=u(require("os"),1),J=u(require("process"),1),O=de.default.homedir(),le=de.default.tmpdir(),{env:M}=J.default,Wt=t=>{let e=y.default.join(O,"Library");return{data:y.default.join(e,"Application Support",t),config:y.default.join(e,"Preferences",t),cache:y.default.join(e,"Caches",t),log:y.default.join(e,"Logs",t),temp:y.default.join(le,t)}},zt=t=>{let e=M.APPDATA||y.default.join(O,"AppData","Roaming"),r=M.LOCALAPPDATA||y.default.join(O,"AppData","Local");return{data:y.default.join(r,t,"Data"),config:y.default.join(e,t,"Config"),cache:y.default.join(r,t,"Cache"),log:y.default.join(r,t,"Log"),temp:y.default.join(le,t)}},Yt=t=>{let e=y.default.basename(O);return{data:y.default.join(M.XDG_DATA_HOME||y.default.join(O,".local","share"),t),config:y.default.join(M.XDG_CONFIG_HOME||y.default.join(O,".config"),t),cache:y.default.join(M.XDG_CACHE_HOME||y.default.join(O,".cache"),t),log:y.default.join(M.XDG_STATE_HOME||y.default.join(O,".local","state"),t),temp:y.default.join(le,e,t)}}});function Ne(t,e){return`${je.cache}/engine/${t}/${e}`}function U(t){return`${je.data}/${t}`}async function Ue(t){try{return await(0,v.access)(t,v.constants.F_OK),!0}catch(e){if(me(e))return!1;throw e}}async function qe(t,e){let r=await Xt(t);await(0,v.writeFile)(e,r),await(0,v.chmod)(e,"755")}async
|
||
|
|
`).find(N=>N.includes("Started query engine http server"));if(!h)return;a.stdout.removeListener("data",i);let{fields:b}=JSON.parse(h);if(b==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${m}`));let{ip:T,port:R}=b;if(T==null||R==null)return r(new Error(`This version of query-engine is not compatible with minippg, "ip" and "port" are missing in the startup log entry.
|
||
|
|
Received data: ${m}`));o({childProcess:a,url:`http://${T}:${R}`})},c=m=>{this.#r=null,r(new q(String(m))),a.removeListener("exit",d),a.kill()};a.once("error",c);let d=(m,h)=>{this.#r=null,r(new q(`Query Engine exited with code ${m} and signal ${h}`))};return a.once("exit",d),a.stdout.on("data",i),this.#e.debug&&(a.stderr.on("data",console.error.bind(console,"[Query Engine]")),a.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#r}async stop(){if(this.#r==null)return;let{childProcess:e}=await this.#r;e.exitCode==null&&e.signalCode==null&&(this.#r=null,e.kill(),await(0,rt.once)(e,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let e=await this.#a();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",e);let r=Ne(this.#e.clientVersion,e);this.#e.debug&&console.debug("[Query Engine] cache directory path",r),await(0,ot.mkdir)(r,{recursive:!0});let{binaryTarget:o}=this.#e.platform,n=o==="windows"?".exe":"",s=(0,nt.join)(r,`query-engine-${o}${n}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(cr==="1"||await Ue(s)===!1)&&await this.#n({commitHash:e,extension:n,engineBinaryPath:s}),s}async#a(){let e=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.clientVersion}`);if(!e.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${e.status}`);let o=(await e.json()).devDependencies?.["@prisma/engines-version"];if(!o)throw new Error("Couldn't find engines version in package.json");let n=o.split(".").at(-1);if(!n)throw new Error("Couldn't find commit hash in engines version");return n}async#n(e){let{commitHash:r,extension:o,engineBinaryPath:n}=e,{binaryTarget:s}=this.#e.platform,a=`https://binaries.prisma.sh/all_commits/${r}/${s}/query-engine${o}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",a);let i=await fetch(a);if(!i.ok)throw new Error(`Couldn't download engine. URL: ${a}, status code: ${i.status}`);et&&await(0,st.setTimeout)(Number(et)),await qe(await i.arrayBuffer(),n),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",n)}#o(e){let r={};for(let[o,n]of Object.entries(e))n!=null&&(r[o]=n);return r}async#i(e,r,o){let{url:n}=await this.#r,s=this.#o(r),a=await fetch(`${n}/transaction/${e}/${o}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!a.ok)throw await L.fromResponse(a);try{return await a.json()}catch{return{}}}};q=class extends Error{name="EngineStartError"},L=class t extends Error{constructor(r,o,n){super(`${r}: Query Engine response status ${o}, body: ${n}`);this.action=r;this.statusCode=o;this.responseBody=n}name="EngineHttpError";static async fromResponse(r){let o=new URL(r.url),n=await r.text();return new t(o.pathname,r.status,n)}}});async function it(t){let{output:e,success:r}=(0,S.safeParse)(dr,await t.req.json(),{abortEarly:!0});return r?e:t.text("Invalid input",400)}var S,dr,ct=D(()=>{"use strict";p();S=require("valibot"),dr=(0,S.object)({tags:(0,S.union)([(0,S.pipe)((0,S.array)((0,S.string)()),(0,S.minLength)(1)),(0,S.literal)("all")])})});async function ut(t){return we===void 0&&(we=await $.Server.create({databaseUrl:t.get("db").connectionString,maxResponseSize:(0,$.parseSize)("128 MiB"),queryTimeout:(0,$.parseDuration)("PT5M"),maxTransactionTimeout:(0,$.parseDuration)("PT5M"),maxTransactionWaitTime:(0,$.parseDuration)("PT5M"),perRequestLogContext:{logFormat:"text",logLevel:t.get("debug")?"debug":"off"}})),we}var $,ne,we,dt=D(()=>{"use strict";p();$=require("@prisma/query-plan-executor"),ne=require("@prisma/query-plan-executor")});async function ve(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(a=>a.toString(16).padStart(2,"0")).join("")}function lt(t){let e=t.req.param("schemaHash"),r=ae.get(e);return r==null?t.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:e,schemas:r}}async function pt(t,e,r){let o=Se.Buffer.from(t,"base64").toString("utf8"),n=(0,se.getSchema)(o),s=n.list.find(d=>d.type==="datasource")
|
||
|
|
${JSON.stringify(i,null,2)}`),new Error(`Invalid Prisma Dev state for "${o}".`);return new G({databasePort:c.databasePort,debug:r,dryRun:!1,name:o,pid:c.pid,port:c.port,serverDump:c,shadowDatabasePort:c.shadowDatabasePort})}static async scan(e){let{debug:r,globs:o}=e??{},n=(0,C.join)(U(xe),"..");r&&console.debug(`[State] scanning for server states in: ${n}`);let s=await Ke(n,o);return r&&console.debug(`[State] found server names: ${JSON.stringify(s)}`),await Promise.all(s.map(a=>wr(a,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}set shadowDatabasePort(e){this.#t("shadowDatabasePort",e)}#t(e,r){if(r<0||!Number.isInteger(r))throw new Error(`Invalid port number: ${r}`);let o=`_${e}`;if(this[o]!==H&&this[o]!==r)throw new Error(`\`${e}\` is already set to ${this[o]}, cannot change it to ${r}`);this[o]=r}},Oe=class extends x{constructor(e){super({...e,databasePort:e?.databasePort||H,persistenceMode:"stateless",port:e?.port||H,shadowDatabasePort:e?.shadowDatabasePort||H})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[$e](){let e;try{e=await x.scan({debug:this.debug,onlyMetadata:!0})}catch(o){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",o),e=[]}let r=await ge({debug:this.debug,name:this.dryRun?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}async close(){}async writeServerDump(){}},G=class t extends x{#t;#e;#r;#s;#a;#n;#o;constructor(e){super({...e,persistenceMode:"stateful"}),this.#n=!1,this.#e=U(this.name),this.#t=(0,C.join)(this.#e,"db_dump.bak"),this.#r=(0,C.join)(this.#e,".lock"),this.#s=(0,C.join)(this.#e,".pglite"),this.#o=e?.serverDump??null,this.#a=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return(0,C.join)(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#o?.exports}get pgliteDataDirPath(){return this.#s}async[$e](){await Ge(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await(0,j.lock)(this.#e,{lockfilePath:this.#r}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await x.scan({debug:this.debug,onlyMetadata:!0}),r=await ge({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 K(this):e}}async close(){if(!this.#n)try{await(0,j.unlock)(this.#e,{lockfilePath:this.#r}),this.#n=!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){this.#o={name:this.name,version:"1",pid:Ae.process.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await(0,Mt.writeFile)(this.#a,`${JSON.stringify(this.#o,null,2)}
|
||
|
|
`,{encoding:"utf-8"})}};async function wr(t,e){let{debug:r,onlyMetadata:o}=e||{},n=typeof t=="string"?t:t.name,s=typeof t!="string"?t:void 0,a={databasePort:s?.databasePort??-1,exports:s?.exports,name:n,pid:s?.pid,port:s?.port??-1,shadowDatabasePort:s?.shadowDatabasePort??-1,version:"1"};try{let i=s||await x.fromServerDump({debug:r,name:n});if(!i)return r&&console.debug(`[State] no server state found for name: ${n}`),{...a,status:"no_such_server"};a.databasePort=i.databasePort,a.exports=i.exports,a.pid=i.pid,a.port=i.port,a.shadowDatabasePort=i.shadowDatabasePort;let{exports:c,pid:d}=i;if(o)return{...a,status:"unknown"};if(!It(d,r))return r&&console.debug(`[State] server state for "${n}" has no running process with PID: ${d}`),{...a,status:"not_running"};let m=U(n);try{if(!await(0,j.check)(m,{lockfilePath:(0,C.join)(m,".lock")}))return r&&console.debug(`[State] server state for "${n}" is not locked, indicating it is not running.`),{...a,status:"starting_up"}}catch(N){r&&console.error(`[State] server state for "${n}" failed to check lock:`,N)}if(!c)return{...a,status:"starting_up"};let{http:h}=c,{hc:b}=await import("hono/client"),T=await b(h.url).health.$get();if(!T.ok)return r&&console.debug(`[State] server state for "${n}" is not live: ${JSON.stringify(T)}`),{...a,status:"not_running"};let R=await T.json();return R.name!==t?(r&&console.debug(`[State] server state for "${n}" has mismatched health response: ${JSON.stringify(R)}`),{...a,status:"unknown"}):(r&&console.debug(`[State] server state for "${t}" is live: ${JSON.stringify(R)}`),{...a,status:"running"})}catch(i){return r&&console.error(`[State] failed to get server status for "${n}":`,i),{...a,status:"error"}}}var _e=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},K=class extends _e{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return x.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};async function Ht(t){let e=await x.createExclusively(t),[r,o]=await Promise.all([be("database",e),be("shadow_database",e)]),n=await At(r,e),s=`prisma+postgres://localhost:${n.port}/?${new URLSearchParams({api_key:Ce({databaseUrl:r.prismaORMConnectionString,name:e.name,shadowDatabaseUrl:o.prismaORMConnectionString})}).toString()}`,a={database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:n.url},ppg:{url:s},shadowDatabase:{connectionString:o.prismaORMConnectionString,prismaORMConnectionString:o.prismaORMConnectionString,terminalCommand:o.terminalCommand}};return await e.writeServerDump(a),{...a,close:()=>i(e,[n,r,o]),name:e.name};async function i(c,d){let h=(await Promise.allSettled(d.map(b=>b.close()))).filter(b=>b.status==="rejected").map(b=>new Error(b.reason));try{await c.close()}catch(b){h.push(b)}if(h.length>0)throw new AggregateError(h,"Failed to close some servers")}}async function Sr(t){return await Ht(t)}0&&(module.exports={DEFAULT_DATABASE_PORT,DEFAULT_SERVER_PORT,DEFAULT_SHADOW_DATABASE_PORT,PortNotAvailableError,ServerAlreadyRunningError,startPrismaDevServer,unstable_startServer});
|