@prisma/dev 0.0.0-dev.202505112026 → 0.0.0-dev.202505121240
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/index.d.ts +25 -3
- package/dist/index.js +5 -5
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,19 @@
|
|
|
1
|
+
declare const DEFAULT_ACCELERATE_PORT = 51213;
|
|
2
|
+
declare const DEFAULT_DATABASE_PORT = 51214;
|
|
3
|
+
declare const DEFAULT_SHADOW_DATABASE_PORT = 51215;
|
|
4
|
+
type PortAssignableService = "accelerate" | "database" | "shadow_database";
|
|
5
|
+
declare class PortNotAvailableError extends Error {
|
|
6
|
+
port: number;
|
|
7
|
+
service: PortAssignableService;
|
|
8
|
+
name: string;
|
|
9
|
+
constructor(port: number, service: PortAssignableService);
|
|
10
|
+
}
|
|
11
|
+
|
|
1
12
|
interface StartServerOptions {
|
|
2
13
|
/**
|
|
3
14
|
* The port the Accelerate server will listen on.
|
|
4
15
|
*
|
|
5
|
-
* Defaults to `
|
|
16
|
+
* Defaults to `51213`.
|
|
6
17
|
*
|
|
7
18
|
* An error is thrown if the port is already in use.
|
|
8
19
|
*/
|
|
@@ -10,7 +21,7 @@ interface StartServerOptions {
|
|
|
10
21
|
/**
|
|
11
22
|
* The port the database server will listen on.
|
|
12
23
|
*
|
|
13
|
-
* Defaults to `
|
|
24
|
+
* Defaults to `51214`.
|
|
14
25
|
*
|
|
15
26
|
* An error is thrown if the port is already in use.
|
|
16
27
|
*/
|
|
@@ -21,6 +32,14 @@ interface StartServerOptions {
|
|
|
21
32
|
* Defaults to `false`.
|
|
22
33
|
*/
|
|
23
34
|
debug?: boolean;
|
|
35
|
+
/**
|
|
36
|
+
* The port the shadow database server will listen on.
|
|
37
|
+
*
|
|
38
|
+
* Defaults to `51215`.
|
|
39
|
+
*
|
|
40
|
+
* An error is thrown if the port is already in use.
|
|
41
|
+
*/
|
|
42
|
+
shadowDatabasePort?: number;
|
|
24
43
|
}
|
|
25
44
|
interface Server {
|
|
26
45
|
accelerate: {
|
|
@@ -33,7 +52,10 @@ interface Server {
|
|
|
33
52
|
ppg: {
|
|
34
53
|
url: string;
|
|
35
54
|
};
|
|
55
|
+
shadowDatabase: {
|
|
56
|
+
connectionString: string;
|
|
57
|
+
};
|
|
36
58
|
}
|
|
37
59
|
declare function unstable_startServer(options?: StartServerOptions): Promise<Server>;
|
|
38
60
|
|
|
39
|
-
export { type Server, type StartServerOptions, unstable_startServer };
|
|
61
|
+
export { DEFAULT_ACCELERATE_PORT, DEFAULT_DATABASE_PORT, DEFAULT_SHADOW_DATABASE_PORT, type PortAssignableService, PortNotAvailableError, type Server, type StartServerOptions, unstable_startServer };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{createSecureServer as
|
|
3
|
-
`).find(
|
|
4
|
-
Received data: ${a}`));s({childProcess:
|
|
2
|
+
import{createSecureServer as qe}from"http2";import{promisify as Fe}from"util";import{serve as Ke}from"@hono/node-server";import Me from"@prisma/get-platform";import{Hono as re}from"hono/tiny";import{validator as w}from"hono/validator";import{HTTPException as v}from"hono/http-exception";import{object as se,parse as ie,pipe as ae,regex as ce,string as me,url as le}from"valibot";var pe=/^(postgres|postgresql):\/\//,ue=se({databaseUrl:ae(me(),le(),ce(pe))});function B(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function de(e){try{let t=Buffer.from(e,"base64url").toString("utf8");return ie(ue,JSON.parse(t))}catch{return null}}var p=(e,t)=>{let{authorization:n}=e;if(!n)throw new v(401,{message:"Missing API Key"});let[r,o="",s]=n.split(" ");if(r!=="Bearer"||s)throw new v(401,{message:"Invalid API Key"});let i=de(o);if(i==null)throw new v(401,{message:"Invalid API Key"});let{databaseUrl:a}=i;if(a!==t.var.db.connectionString)throw new v(401,{message:"Unauthorized"});return{decodedAPIKey:i}};import{array as fe,literal as ge,minLength as he,object as ye,pipe as we,safeParse as Se,string as Pe,union as ve}from"valibot";var be=ye({tags:ve([we(fe(Pe()),he(1)),ge("all")])});async function L(e){let{output:t,success:n}=Se(be,await e.req.json());return n?t:e.text("Invalid input",400)}import{mkdir as He,readFile as q,writeFile as F}from"fs/promises";import{join as I}from"path";import{certificateFor as Ce}from"@expo/devcert";import{chmod as Ee,stat as Te,writeFile as Ae}from"fs/promises";import Re from"env-paths";import{inflate as xe}from"pako";var H=Re("prisma-dev").cache;function j(e,t){return`${H}/${e}/${t}`}async function h(e){try{return await Te(e),!0}catch(t){if(t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT")return!1;throw t}}async function U(e,t){let n=xe(e);await Ae(t,n),await Ee(t,"755")}var k=I(H,"certs"),C=I(k,"tls.cert"),O=I(k,"tls.key");async function K(){if(await He(k,{recursive:!0}),await h(C)&&await h(O))return{cert:await q(C),key:await q(O)};let e=await Ce("localhost");return await Promise.all([F(C,e.cert),F(O,e.key)]),{cert:e.cert,key:e.key}}import{spawn as Oe}from"child_process";import{once as Ie}from"events";import{mkdir as ke}from"fs/promises";import{join as _e}from"path";function u(){let e,t,n=new Promise((r,o)=>{e=r,t=o});return{fail:t,promise:n,succeed:e}}var b=class e{static#n=new Map;#t;#e;constructor(t){this.#t=t,this.#e=null}static async get(t){let n=`${t.schemaHash}:${t.clientVersion}`;try{let r=e.#n.get(n);if(r)return r;let o=new e(t);return e.#n.set(n,o),await o.start(),o}finally{e.stopAll(n)}}static async stopAll(t){let r=(await Promise.allSettled(Array.from(e.#n.entries()).filter(([o])=>o!==t).map(async([o,s])=>{try{await s.stop()}finally{e.#n.delete(o)}}))).filter(o=>o.status==="rejected").map(o=>o.reason);if(r.length>0)throw new AggregateError(r,"Failed to stop engines")}async commitTransaction(t,n){return await this.#o(t,n,"commit")}async request(t,n){let{url:r}=await this.#e,o=this.#r(n),s=await fetch(r,{body:typeof t=="string"?t:JSON.stringify(t),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await d.fromResponse(s);return await s.text()}async rollbackTransaction(t,n){return await this.#o(t,n,"rollback")}async startTransaction(t,n){let{url:r}=await this.#e,o=this.#r(n),s=await fetch(`${r}/transaction/start`,{body:JSON.stringify(t),headers:{...o,"Content-Type":"application/json"},method:"POST"});if(!s.ok)throw await d.fromResponse(s);return await s.json()}async start(){if(this.#e!=null)return;let t=await this.#s(),n=Oe(t,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#t.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});n.stderr.setEncoding("utf8"),n.stdout.setEncoding("utf8");let{fail:r,promise:o,succeed:s}=u();this.#e=o;let i=a=>{let c=a.split(`
|
|
3
|
+
`).find(P=>P.includes("Started query engine http server"));if(!c)return;n.stdout.removeListener("data",i);let{fields:m}=JSON.parse(c);if(m==null)return r(new Error(`Unexpected data during initialization, "fields" are missing: ${a}`));let{ip:l,port:x}=m;if(l==null||x==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.
|
|
4
|
+
Received data: ${a}`));s({childProcess:n,url:`http://${l}:${x}`})};n.once("error",a=>{this.#e=null,r(new y(String(a)))}),n.once("exit",(a,c)=>{this.#e=null,r(new y(`Query Engine exited with code ${a} and signal ${c}`))}),n.stdout.on("data",i),n.stderr.on("data",a=>{console.error(a)}),await this.#e}async stop(){if(this.#e==null)return;let{childProcess:t}=await this.#e;t.exitCode==null&&t.signalCode==null&&(t.kill(),await Ie(t,"exit"))}async#s(){let t=await this.#i(),n=j(this.#t.clientVersion,t);await ke(n,{recursive:!0});let{platform:r}=this.#t.platform,o=r==="windows"?".exe":"",s=_e(n,`query-engine-${r}${o}`);return await h(s)||await this.#a({commitHash:t,extension:o,engineBinaryPath:s}),s}async#i(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#t.clientVersion}`);if(!t.ok)throw new Error(`Couldn't fetch package.json from npm registry, status code: ${t.status}`);let r=(await t.json()).devDependencies?.["@prisma/engines-version"];if(!r)throw new Error("Couldn't find engines version in package.json");let o=r.split(".").at(-1);if(!o)throw new Error("Couldn't find commit hash in engines version");return o}async#a(t){let{commitHash:n,extension:r,engineBinaryPath:o}=t,{platform:s}=this.#t.platform,i=`https://binaries.prisma.sh/all_commits/${n}/${s}/query-engine${r}.gz`,a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);await U(await a.arrayBuffer(),o)}#r(t){let n={};for(let[r,o]of Object.entries(t))o!=null&&(n[r]=o);return n}async#o(t,n,r){let{url:o}=await this.#e,s=this.#r(n),i=await fetch(`${o}/transaction/${t}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await d.fromResponse(i);try{return await i.json()}catch{return{}}}};function E(e,t){return console.error(e),e instanceof y?t.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500):e instanceof d?t.text(e.responseBody,e.statusCode):t.body(null,500)}var y=class extends Error{name="EngineStartError"},d=class e extends Error{constructor(n,r,o){super(`${n}: Query Engine response status ${r}, body: ${o}`);this.action=n;this.statusCode=r;this.responseBody=o}name="EngineHttpError";static async fromResponse(n){let r=new URL(n.url),o=await n.text();return new e(r.pathname,n.status,o)}};var M=51213,V=51214,N=51215,f=class extends Error{constructor(n,r){super(`Port ${n} is already in use.`);this.port=n;this.service=r}name="PortNotAvailableError"};import{Buffer as z}from"buffer";var T=new Map;async function J(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}function G(e){let t=e.req.param("schemaHash"),n=T.get(t);return n==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:t,schemas:n}}var De=/datasource\s+db\s+[\w\s\d{="[\])(]+}/;function Q(e,t){let n=z.from(e,"base64").toString("utf8"),r=`datasource db {
|
|
5
5
|
provider = "postgresql"
|
|
6
|
-
url = "${
|
|
7
|
-
}`,o=
|
|
6
|
+
url = "${t}"
|
|
7
|
+
}`,o=n.replace(De,r);return z.from(o,"utf8").toString("base64")}function A(e){let{req:t}=e;return{traceparent:t.header("traceparent"),"X-capture-telemetry":t.header("X-capture-telemetry")}}import{integer as X,looseObject as $e,minValue as W,number as _,object as Be,pipe as Y,safeParse as Z,string as ee,union as Le}from"valibot";var je=Be({isolation_level:ee(),max_wait:Y(_(),X(),W(0)),timeout:Y(_(),X(),W(0))});async function te(e){let{output:t,success:n}=Z(je,await e.req.json());return n?t:e.json({EngineNotStarted:{reason:"InvalidRequest"}},400)}var Ue=$e({id:Le([ee(),_()])});function ne(e,t){let{output:n,success:r}=Z(Ue,e);return r?n:t.json({EngineMalfunction:{}},500)}async function oe(e,t,n){let r=await Ve(e,t,n),o=await K(),{fail:s,promise:i,succeed:a}=u(),c=Ke({createServer:qe,fetch:r.fetch,port:e,serverOptions:{...o,allowHTTP1:!0}},()=>{a()});return c.on("error",m=>{if(typeof m=="object"&&"code"in m&&m.code==="EADDRINUSE")return s(new f(e,"accelerate"));console.error(m)}),await i,{async close(){await Fe(c.close.bind(c))()},port:e,url:`http://localhost:${e}`}}async function Ve(e,t,n){let r=new re,o=await Me.getPlatformInfo();return n&&console.debug("platform info: %s",JSON.stringify(o)),r.use("*",async(s,i)=>(s.set("db",t),s.set("debug",!!n),s.set("platform",o),s.set("port",e),s.set("protocol","https"),await i())),r.route("/",R),r}var R=new re;R.post("/invalidate",w("header",p),async e=>{let t=await L(e);return t instanceof Response?t:e.body(null)});var Ne="/:clientVersion/:schemaHash",S=R.basePath(Ne);R.route("/",S);var ze=["/graphql","/itx/:transactionId/graphql"];S.on("POST",[...ze],w("header",p),async e=>{let{req:t}=e;try{let n=await D(e);if(console.log("got engine!"),n instanceof Response)return n;let r=await t.text(),o=t.param("transactionId"),s=await n.request(r,{...A(e),"X-transaction-id":o});return e.text(s)}catch(n){return E(n,e)}});S.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],w("header",p),async e=>{let{req:t}=e;try{let n=await D(e);if(n instanceof Response)return n;let o=`${t.routePath.split("/").filter(Boolean).at(-1)}Transaction`,s=t.param("transactionId"),i=await n[o](s,A(e));return e.json(i)}catch(n){return E(n,e)}});S.put("/schema",w("header",p),async e=>{let{req:t}=e,n=await t.text();if(!n)return e.text("Missing schema",400);let r=t.param("schemaHash"),o=T.get(r);return o==null?r!==await J(n)?e.text("Schema hash mismatch",400):(T.set(r,{original:n,override:Q(n,e.get("db").connectionString)}),e.text(r)):n!==o.original?e.text("Schema mismatch",400):e.text(r)});S.post("/transaction/start",w("header",p),async e=>{let{req:t}=e,n=await te(e);if(n instanceof Response)return n;try{let r=await D(e);if(r instanceof Response)return r;let o=await r.startTransaction(n,A(e)),s=ne(o,e);if(s instanceof Response)return s;let{id:i}=s,a=t.param("clientVersion"),c=e.get("port"),m=e.get("protocol"),l=t.param("schemaHash");return e.json({...o,"data-proxy":{endpoint:`${m}://localhost:${c}/${a}/${l}/itx/${i}`}})}catch(r){return E(r,e)}});async function D(e){let{req:t}=e,n=G(e);return n instanceof Response?n:await b.get({base64Schema:n.schemas.override,clientVersion:t.param("clientVersion"),platform:e.get("platform"),schemaHash:n.schemaHash})}import{promisify as Je}from"util";import{PGlite as Ge}from"@electric-sql/pglite";import{createServer as Qe,LogLevel as Xe}from"pglite-server";async function $(e,t,n){let r={connectionLimit:1,connectTimeout:0,database:"postgres",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,port:e,socketTimeout:0,sslMode:"disable",username:"postgres"},o=await Ge.create({database:r.database,dataDir:"memory://",debug:n?5:void 0,defaultDataTransferContainer:"file",username:r.username});await o.waitReady;let s=Qe(o,{keepAlive:!0,logLevel:n?Xe.Debug:void 0}),{fail:i,promise:a,succeed:c}=u();s.on("error",l=>{if("code"in l&&l.code==="EADDRINUSE")return i(new f(e,t));console.error(l)}),s.listen(e,()=>c()),await a;let m=`postgres://${r.username}:${r.password}@localhost:${e}/${r.database}?${new URLSearchParams({connection_limit:String(r.connectionLimit),connect_timeout:String(r.connectTimeout),max_idle_connection_lifetime:String(r.maxIdleConnectionLifetime),pool_timeout:String(r.poolTimeout),socket_timeout:String(r.socketTimeout),sslmode:r.sslMode}).toString()}`;return{...r,async close(){try{await Je(s.close.bind(s))()}finally{await o.close()}},connectionString:m}}async function Yt(e){let{acceleratePort:t=51213,databasePort:n=51214,debug:r=!1,shadowDatabasePort:o=51215}=e||{},[s,i]=await Promise.all([$(n,"database",r),$(o,"shadow_database",r)]),a=await oe(t,s,r),c=`prisma+postgres://localhost:${a.port}/?${new URLSearchParams({api_key:B({databaseUrl:s.connectionString})}).toString()}`;return{accelerate:{url:a.url},close:()=>m([a,s,i]),database:{connectionString:s.connectionString},ppg:{url:c},shadowDatabase:{connectionString:i.connectionString}};async function m(l){let P=(await Promise.allSettled(l.map(g=>g.close()))).filter(g=>g.status==="rejected").map(g=>new Error(g.reason));if(P.length>0)throw new AggregateError(P,"Failed to close some servers")}}export{M as DEFAULT_ACCELERATE_PORT,V as DEFAULT_DATABASE_PORT,N as DEFAULT_SHADOW_DATABASE_PORT,f as PortNotAvailableError,Yt as unstable_startServer};
|