@prisma/dev 0.0.0-dev.202506032027 → 0.0.0-dev.202506040104
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/chunk-A33H6MPG.js +4 -0
- package/dist/daemon/client.d.ts +1 -1
- package/dist/{index-Bi1Nraoi.d.ts → index-BY1kJS25.d.ts} +5 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +4 -4
- package/dist/state.d.ts +1 -1
- package/dist/state.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-IDQVT2IP.js +0 -4
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{mkdir as K,writeFile as Y}from"fs/promises";import{join as d}from"pathe";import{lock as Z}from"proper-lockfile";import{process as u}from"std-env";import{integer as _,literal as q,minLength as z,minValue as F,number as M,object as p,optional as E,parseJson as G,pipe as i,safeParse as Q,string as g,url as X}from"valibot";import{createWriteStream as B,WriteStream as N}from"fs";import{access as V,chmod as U,constants as W,readFile as j,writeFile as H}from"fs/promises";import J from"env-paths";import{inflate as C}from"pako";var v=J("prisma-dev");function ie(t,e){return`${v.cache}/engine/${t}/${e}`}function l(t){return`${v.data}/${t}`}async function ne(t){try{return await V(t,W.F_OK),!0}catch(e){if(D(e))return!1;throw e}}async function de(t,e){let r=C(t);await H(e,r),await U(e,"755")}async function ue(t,e){await t.stream().pipeTo(N.toWeb(B(e,{encoding:"utf-8"})))}function D(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function S(t){try{return await j(t,{encoding:"utf-8"})}catch(e){if(D(e))return null;throw e}}var w=51214,A=51213,x=51215,y=class extends Error{constructor(r,s){super(`Port number \`${r}\` is not available for service ${s}.`);this.port=r;this.service=s}name="PortNotAvailableError"};var $=i(g(),X()),O=p({connectionString:$}),T=p({url:$}),h=i(M(),_(),F(1)),ee=p({database:O,http:T,ppg:T,shadowDatabase:O}),te=p({databasePort:h,exports:E(ee),name:i(g(),z(1)),pid:E(i(M(),_(),F(0))),port:h,shadowDatabasePort:h,version:q("1")}),f=Symbol("initialize"),R="default",c=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??R,this.persistenceMode=e.persistenceMode,this.pid=e.pid??u.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async create(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new o({...e,pid:u.pid}):new b(e);return await r[f](),r}static async fromServerDump(e){let{debug:r,name:s=R}=e??{},I=l(s),n=o.getServerDumpPath(I),m=await S(n);if(m==null)return r&&console.debug(`[State] No server dump file found at: ${n}`),null;r&&(console.debug(`[State] server dump file found at "${n}":`),console.debug(m));let{issues:L,output:a,success:k}=Q(i(g(),G(),te),m);if(!k)throw r&&console.debug(`[State] Invalid server dump file at "${n}":
|
|
3
|
+
${JSON.stringify(L,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new o({databasePort:a.databasePort,debug:r,dryRun:!1,name:s,pid:a.pid,port:a.port,serverDump:a,shadowDatabasePort:a.shadowDatabasePort})}},b=class extends c{constructor(e){super({...e,persistenceMode:"stateless",pid:u.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[f](){}async close(){}async writeServerDump(){}},o=class t extends c{#s;#e;#a;#o;#r;#t=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=l(this.name),this.#s=d(this.#e,"db_dump.bak"),this.#a=d(this.#e,".pglite"),this.#r=e.serverDump??null,this.#o=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return d(e,"server.json")}get databaseDumpPath(){return this.#s}get pgliteDataDirPath(){return this.#a}async[f](){await K(this.#e,{recursive:!0}),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#t=await Z(this.#e,{lockfilePath:d(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 P(this.name):e}}async close(){if(this.#t!=null)try{await this.#t(),this.#t=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:u.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await Y(this.#o,`${JSON.stringify(this.#r,null,2)}
|
|
4
|
+
`,{encoding:"utf-8"})}},P=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A server with the name "${e}" is already running.`)}};export{ie as a,ne as b,de as c,ue as d,w as e,A as f,x as g,y as h,c as i,P as j};
|
package/dist/daemon/client.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as url from 'url';
|
|
2
2
|
import { SockDaemonClient } from 'sock-daemon/client';
|
|
3
|
-
import { S as ServerOptions, a as Server } from '../index-
|
|
3
|
+
import { S as ServerOptions, a as Server } from '../index-BY1kJS25.js';
|
|
4
4
|
import { MessageBase } from 'sock-daemon/server';
|
|
5
5
|
import 'valibot';
|
|
6
6
|
|
|
@@ -113,6 +113,10 @@ declare abstract class ServerState implements ResolvedServerOptions {
|
|
|
113
113
|
abstract close(): Promise<void>;
|
|
114
114
|
abstract writeServerDump(exports?: Omit<Server, "close">): Promise<void>;
|
|
115
115
|
}
|
|
116
|
+
declare class ServerStateAlreadyExistsError extends Error {
|
|
117
|
+
name: string;
|
|
118
|
+
constructor(name: string);
|
|
119
|
+
}
|
|
116
120
|
|
|
117
121
|
type DBServerPurpose = "database" | "shadow_database";
|
|
118
122
|
|
|
@@ -132,4 +136,4 @@ interface Server extends Exports {
|
|
|
132
136
|
}
|
|
133
137
|
declare function unstable_startServer(options?: ServerOptions): Promise<Server>;
|
|
134
138
|
|
|
135
|
-
export { DEFAULT_DATABASE_PORT as D, type Exports as E, type PersistenceMode as P, type ResolvedServerOptions as R, type ServerOptions as S, type Server as a, type ServerDumpV1 as b, ServerState as c,
|
|
139
|
+
export { DEFAULT_DATABASE_PORT as D, type Exports as E, type PersistenceMode as P, type ResolvedServerOptions as R, type ServerOptions as S, type Server as a, type ServerDumpV1 as b, ServerState as c, ServerStateAlreadyExistsError as d, DEFAULT_SERVER_PORT as e, DEFAULT_SHADOW_DATABASE_PORT as f, type PortAssignableService as g, PortNotAvailableError as h, unstable_startServer as u };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { D as DEFAULT_DATABASE_PORT,
|
|
1
|
+
export { D as DEFAULT_DATABASE_PORT, e as DEFAULT_SERVER_PORT, f as DEFAULT_SHADOW_DATABASE_PORT, g as PortAssignableService, h as PortNotAvailableError, a as Server, u as unstable_startServer } from './index-BY1kJS25.js';
|
|
2
2
|
import 'valibot';
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{a as
|
|
3
|
-
`).find(
|
|
4
|
-
Received data: ${
|
|
2
|
+
import{a as k,b as L,c as j,d as N,e as it,f as at,g as ct,h as v,i as U}from"./chunk-A33H6MPG.js";import{HTTPException as P}from"hono/http-exception";import{object as le,optional as ue,parseJson as me,pipe as x,regex as q,safeParse as pe,string as H,url as M}from"valibot";var V=/^(postgres|postgresql):\/\//,ge=x(H(),me(),le({databaseUrl:x(H(),M(),q(V)),shadowDatabaseUrl:ue(x(H(),M(),q(V)))}));function K(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function fe(e){let t=Buffer.from(e,"base64url").toString("utf8"),{issues:n,output:r,success:o}=pe(ge,t,{abortEarly:!0});return o?[null,r]:[n]}var g=(e,t)=>{let{authorization:n}=e;if(!n)throw new P(401,{message:"Missing API Key"});let[r,o="",s]=n.split(" ");if(r!=="Bearer"||s)throw new P(401,{message:"Invalid API Key"});let[i,a]=fe(o);if(i)throw new P(401,{message:"Invalid API Key",cause:i.join(", ")});let{databaseUrl:c}=a;if(c!==t.var.db.connectionString)throw new P(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:a}};import{PGlite as G}from"@electric-sql/pglite";import{PGLiteSocketServer as he}from"@electric-sql/pglite-socket";import{pgDump as ye}from"@electric-sql/pglite-tools/pg_dump";import{filename as we}from"pathe/utils";var d={connectionLimit:1,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},Se=`postgres://${d.username}:${d.password}@localhost`,be=new URLSearchParams({connection_limit:String(d.connectionLimit),connect_timeout:String(d.connectTimeout),max_idle_connection_lifetime:String(d.maxIdleConnectionLifetime),pool_timeout:String(d.poolTimeout),socket_timeout:String(d.socketTimeout),sslmode:d.sslMode});async function I(e,t){let n=e==="database"?t.databasePort:t.shadowDatabasePort;if(t.dryRun)return F(e,t,{db:null,port:n,server:null});let{debug:r}=t,s=await(e==="shadow_database"?Pe:Q)(t.pgliteDataDirPath,r);r&&s.onNotification((a,c)=>{console.debug(`[${e}][${a}] ${c}`)});let i=new he({db:s,debug:r,inspect:r,port:n});r&&(i.addEventListener("listening",a=>{let{detail:c}=a;console.debug(`[${e}] server listening on ${JSON.stringify(c)}`)}),i.addEventListener("connection",a=>{let{clientAddress:c,clientPort:l}=a.detail;console.debug(`[${e}] client connected from ${c}:${l}`)}),i.addEventListener("error",a=>{let{detail:c}=a;console.error(`[${e}] server error:`,c)}));try{await i.start()}catch(a){throw a instanceof Error&&"code"in a&&a.code==="EADDRINUSE"?new v(n,e):a}return F(e,t,{db:s,port:n,server:i})}function F(e,t,n){let{debug:r}=t,{db:o,port:s,server:i}=n||{};return r&&console.debug(`[${e}] server started on port ${s}`),{...d,close:async()=>{let a=[];try{await i?.stop(),r&&console.debug(`[${e}] server stopped on port ${s}`)}catch(c){console.error(`[${e}] server stop error`,c),a.push(c)}if(e==="database")try{await o?.syncToFs(),r&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),a.push(c)}try{await o?.close(),r&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),a.push(c)}if(a.length>0)throw new AggregateError(a,`Failed to close ${e} properly`)},connectionString:ve(s),dump:async a=>{e==="shadow_database"||!o||await Ee({db:o,debug:r,destinationPath:a})},port:s}}function ve(e){return`${Se}:${e}/${d.database}?${be.toString()}`}async function Q(e,t){return await G.create({database:d.database,dataDir:e,debug:t?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:d.username})}async function Pe(e,t){return await G.create({database:d.database,dataDir:"memory://",debug:t?5:void 0,defaultDataTransferContainer:"file",relaxedDurability:!1,username:d.username})}async function Ee(e){let{dataDir:t,db:n,debug:r,destinationPath:o}=e,s=n||await Q(t,r),i=await ye({args:["--quote-all-identifiers","--schema-only"],fileName:o?we(o):void 0,pg:s});return o?(r&&console.debug(`[DB] Dumping database to ${o}`),await N(i,o)):(r&&console.debug("[DB] Dumping database to memory"),await i.text())}import{createServer as et}from"http";import{promisify as tt}from"util";import{serve as nt}from"@hono/node-server";import rt from"@prisma/get-platform";function E(){let e,t,n=new Promise((s,i)=>{e=s,t=i}),r=s=>{r=o=null,t(s)},o=s=>{o=r=null,e(s)};return{promise:n,reject:s=>r?.(s),resolve:s=>o?.(s)}}import{logger as ot}from"hono/logger";import{Hono as ae}from"hono/tiny";import{Hono as ze}from"hono/tiny";import{validator as w}from"hono/validator";import{array as Te,literal as Re,minLength as De,object as Ae,pipe as xe,safeParse as He,string as Ie,union as Oe}from"valibot";var $e=Ae({tags:Oe([xe(Te(Ie()),De(1)),Re("all")])});async function J(e){let{output:t,success:n}=He($e,await e.req.json(),{abortEarly:!0});return n?t:e.text("Invalid input",400)}import{spawn as Ce}from"child_process";import{once as Be}from"events";import{mkdir as _e}from"fs/promises";import{join as ke}from"path";import{setTimeout as Le}from"timers/promises";import{proxySignals as je}from"foreground-child/proxy-signals";import{process as Ne}from"std-env";var{PRISMA_DEV_FORCE_ENGINE_BINARY_DOWNLOAD:Ue,PRISMA_DEV_FORCE_ENGINE_BINARY_PATH:qe,PRISMA_DEV_FORCE_NETWORK_DELAY_MS:z}=Ne.env,h=class e{static#n=new Map;#e;#t;constructor(t){this.#e=t,this.#t=null}static async get(t){let{debug:n}=t,r=`${t.schemaHash}:${t.clientVersion}`;try{let o=e.#n.get(r);if(o)return o;let s=new e(t);return e.#n.set(r,s),n&&console.debug("[Query Engine] starting...",t),await s.start(),n&&console.debug("[Query Engine] started!"),s}finally{e.stopAll(r)}}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.start(),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 f.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.start(),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 f.fromResponse(s);return await s.json()}async start(){if(this.#t!=null)return await this.#t;let{promise:t,reject:n,resolve:r}=E();this.#t=t;let o=qe||await this.#s();this.#e.debug&&console.debug("[Query Engine] spinning up at path...",o);let s=Ce(o,["--enable-raw-queries","--enable-telemetry-in-response","--port","0"],{env:{LOG_QUERIES:"y",PRISMA_DML:this.#e.base64Schema,QE_LOG_LEVEL:"TRACE",RUST_BACKTRACE:"1",RUST_LOG:"info"},stdio:["ignore","pipe","pipe"],windowsHide:!0});je(s),s.stderr.setEncoding("utf8"),s.stdout.setEncoding("utf8");let i=l=>{let m=l.split(`
|
|
3
|
+
`).find(de=>de.includes("Started query engine http server"));if(!m)return;s.stdout.removeListener("data",i);let{fields:p}=JSON.parse(m);if(p==null)return n(new Error(`Unexpected data during initialization, "fields" are missing: ${l}`));let{ip:u,port:_}=p;if(u==null||_==null)return n(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: ${l}`));r({childProcess:s,url:`http://${u}:${_}`})},a=l=>{this.#t=null,n(new y(String(l))),s.removeListener("exit",c),s.kill()};s.once("error",a);let c=(l,m)=>{this.#t=null,n(new y(`Query Engine exited with code ${l} and signal ${m}`))};return s.once("exit",c),s.stdout.on("data",i),this.#e.debug&&(s.stderr.on("data",console.error.bind(console,"[Query Engine]")),s.stdout.on("data",console.debug.bind(console,"[Query Engine]"))),await this.#t}async stop(){if(this.#t==null)return;let{childProcess:t}=await this.#t;t.exitCode==null&&t.signalCode==null&&(this.#t=null,t.kill(),await Be(t,"exit"))}async#s(){this.#e.debug&&console.debug("[Query Engine] getting engine commit hash...");let t=await this.#i();this.#e.debug&&console.debug("[Query Engine] got engine commit hash",t);let n=k(this.#e.clientVersion,t);this.#e.debug&&console.debug("[Query Engine] cache directory path",n),await _e(n,{recursive:!0});let{platform:r}=this.#e.platform,o=r==="windows"?".exe":"",s=ke(n,`query-engine-${r}${o}`);return this.#e.debug&&console.debug("[Query Engine] binary path",s),(Ue==="1"||await L(s)===!1)&&await this.#a({commitHash:t,extension:o,engineBinaryPath:s}),s}async#i(){let t=await fetch(`https://registry.npmjs.org/@prisma/client/${this.#e.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,{binaryTarget:s}=this.#e.platform,i=`https://binaries.prisma.sh/all_commits/${n}/${s}/query-engine${r}.gz`;this.#e.debug&&console.debug("[Query Engine] downloading engine from url",i);let a=await fetch(i);if(!a.ok)throw new Error(`Couldn't download engine. URL: ${i}, status code: ${a.status}`);z&&await Le(Number(z)),await j(await a.arrayBuffer(),o),this.#e.debug&&console.debug("[Query Engine] downloaded and saved at",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.#t,s=this.#r(n),i=await fetch(`${o}/transaction/${t}/${r}`,{headers:{...s,"Content-Type":"application/json"},method:"POST"});if(!i.ok)throw await f.fromResponse(i);try{return await i.json()}catch{return{}}}};function T(e,t){return console.error(e),e instanceof y?t.json({EngineNotStarted:{reason:{EngineStartupError:{logs:[],msg:e.message}}}},500):e instanceof f?t.text(e.responseBody,e.statusCode):t.body(null,500)}var y=class extends Error{name="EngineStartError"},f=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)}};import{Buffer as Y}from"buffer";var R=new Map;async function O(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 X(e){let t=e.req.param("schemaHash"),n=R.get(t);return n==null?e.json({EngineNotStarted:{reason:"SchemaMissing"}},404):{schemaHash:t,schemas:n}}var Me=/datasource\s+db\s+\{\s*provider\s*=\s*"postgres(!?ql)?"\s+url\s*=\s*.+\s*\}/;async function W(e,t){let n=Y.from(e,"base64").toString("utf8"),r=`datasource db {
|
|
5
5
|
provider = "postgresql"
|
|
6
6
|
url = "${t.toString()}"
|
|
7
|
-
}`,o=n.replace(
|
|
7
|
+
}`,o=n.replace(Me,r),s=await O(o);return{base64Override:Y.from(o,"utf8").toString("base64"),overrideHash:s}}function D(e){let{req:t}=e;return{traceparent:t.header("traceparent"),"X-capture-telemetry":t.header("X-capture-telemetry")}}import{integer as Z,looseObject as Ve,minValue as ee,number as $,object as Ke,optional as Fe,pipe as te,safeParse as ne,string as re,union as Ge}from"valibot";var Qe=Ke({isolation_level:Fe(re()),max_wait:te($(),Z(),ee(0)),timeout:te($(),Z(),ee(0))});async function oe(e){let{issues:t,output:n,success:r}=ne(Qe,await e.req.json(),{abortEarly:!0});return r?n:e.json({EngineNotStarted:{reason:"InvalidRequest",issues:t}},400)}var Je=Ve({id:Ge([re(),$()])});function se(e,t){let{output:n,success:r}=ne(Je,e);return r?n:t.json({EngineMalfunction:{}},500)}var S=new ze;S.post("/invalidate",w("header",g),async e=>{let t=await J(e);return t instanceof Response?t:e.body(null)});var Ye="/:clientVersion/:schemaHash",b=S.basePath(Ye);S.route("/",b);var Xe=["/graphql","/itx/:transactionId/graphql"];b.on("POST",[...Xe],w("header",g),async e=>{let{req:t}=e;try{let n=await C(e);if(n instanceof Response)return n;let r=await t.text(),o=t.param("transactionId"),s=await n.request(r,{...D(e),"X-transaction-id":o});return e.text(s)}catch(n){return T(n,e)}});b.basePath("/itx/:transactionId").on("POST",["/commit","/rollback"],w("header",g),async e=>{let{req:t}=e;try{let n=await C(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,D(e));return e.json(i)}catch(n){return T(n,e)}});b.put("/schema",w("header",g),async e=>{let{req:t}=e,n=await t.text();if(!n)return e.text("Missing schema",400);let r=t.param("schemaHash"),o=R.get(r);if(o==null){if(r!==await O(n))return e.text("Schema hash mismatch",400);let s=new URL(e.get("db").connectionString);s.searchParams.set("single_use_connections","true");let i=await W(n,s);return R.set(r,{base64Original:n,...i}),e.text(r)}return n!==o.base64Original?e.text("Schema mismatch",400):e.text(r)});b.post("/transaction/start",w("header",g),async e=>{let{req:t}=e,n=await oe(e);if(n instanceof Response)return n;try{let r=await C(e);if(r instanceof Response)return r;let o=await r.startTransaction(n,D(e)),s=se(o,e);if(s instanceof Response)return s;let{id:i}=s,a=t.param("clientVersion"),c=e.get("port"),l=e.get("protocol"),m=t.param("schemaHash");return e.json({...o,"data-proxy":{endpoint:`${l}://localhost:${c}/${a}/${m}/itx/${i}`}})}catch(r){return T(r,e)}});async function C(e){let{req:t}=e,n=X(e);if(n instanceof Response)return n;let{base64Override:r,overrideHash:o}=n.schemas;return await h.get({base64Schema:r,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||t.param("clientVersion"),debug:e.get("debug"),platform:e.get("platform"),schemaHash:o})}import{Hono as We}from"hono/tiny";import{StatusCodes as Ze}from"http-status-codes";var A=new We;A.post("/database/dump",async e=>{let n=await e.get("db").dump();return e.json(n,Ze.CREATED)});A.get("/health",e=>e.json({name:e.get("serverState").name}));async function ce(e,t){let{port:n}=t;if(t.dryRun)return ie(n,null);let r=await st(n,e,t),{promise:o,reject:s,resolve:i}=E(),a=nt({createServer:et,fetch:r.fetch,overrideGlobalObjects:!1,port:n},i);return a.on("error",c=>{if(typeof c=="object"&&"code"in c&&c.code==="EADDRINUSE")return s(new v(n,"server"));console.error("[Accelerate]",c)}),await o,ie(n,a)}function ie(e,t){return{async close(){t&&await Promise.allSettled([tt(t.close.bind(t))(),h.stopAll()])},port:e,url:`http://localhost:${e}`}}async function st(e,t,n){let{debug:r}=n,o=new ae,s=await rt.getPlatformInfo();return r&&console.debug("[Accelerate] platform info: %s",JSON.stringify(s)),r&&o.use("*",ot((...i)=>console.log("[Accelerate]",...i))),o.use("*",async(i,a)=>(i.set("db",t),i.set("debug",!!r),i.set("platform",s),i.set("port",e),i.set("protocol","http"),i.set("serverState",n),await a())),o.route("/",B),o}var B=new ae;B.route("/",S);B.route("/",A);async function pn(e){let t=await U.create(e),[n,r]=await Promise.all([I("database",t),I("shadow_database",t)]),o=await ce(n,t),s=`prisma+postgres://localhost:${o.port}/?${new URLSearchParams({api_key:K({databaseUrl:n.connectionString,shadowDatabaseUrl:r.connectionString})}).toString()}`,i={database:{connectionString:n.connectionString},http:{url:o.url},ppg:{url:s},shadowDatabase:{connectionString:r.connectionString}};return await t.writeServerDump(i),{...i,close:()=>a(t,[o,n,r])};async function a(c,l){let p=(await Promise.allSettled(l.map(u=>u.close()))).filter(u=>u.status==="rejected").map(u=>new Error(u.reason));try{await c.close()}catch(u){p.push(u)}if(p.length>0)throw new AggregateError(p,"Failed to close some servers")}}export{it as DEFAULT_DATABASE_PORT,at as DEFAULT_SERVER_PORT,ct as DEFAULT_SHADOW_DATABASE_PORT,v as PortNotAvailableError,pn as unstable_startServer};
|
package/dist/state.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import 'valibot';
|
|
2
|
-
export { E as Exports, P as PersistenceMode, R as ResolvedServerOptions, b as ServerDumpV1, S as ServerOptions, c as ServerState } from './index-
|
|
2
|
+
export { E as Exports, P as PersistenceMode, R as ResolvedServerOptions, b as ServerDumpV1, S as ServerOptions, c as ServerState, d as ServerStateAlreadyExistsError } from './index-BY1kJS25.js';
|
package/dist/state.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{i as a}from"./chunk-
|
|
2
|
+
import{i as a,j as b}from"./chunk-A33H6MPG.js";export{a as ServerState,b as ServerStateAlreadyExistsError};
|
package/package.json
CHANGED
package/dist/chunk-IDQVT2IP.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{mkdir as C,writeFile as K}from"fs/promises";import{join as d}from"pathe";import{lock as Y}from"proper-lockfile";import{process as u}from"std-env";import{integer as R,literal as Z,minLength as q,minValue as _,number as F,object as p,optional as E,parseJson as z,pipe as o,safeParse as G,string as P,url as Q}from"valibot";import{createWriteStream as k,WriteStream as B}from"fs";import{access as N,chmod as V,constants as U,readFile as W,writeFile as j}from"fs/promises";import H from"env-paths";import{inflate as J}from"pako";var f=H("prisma-dev");function ie(t,e){return`${f.cache}/engine/${t}/${e}`}function l(t){return`${f.data}/${t}`}async function oe(t){try{return await N(t,U.F_OK),!0}catch(e){if(v(e))return!1;throw e}}async function ne(t,e){let r=J(t);await j(e,r),await V(e,"755")}async function de(t,e){await t.stream().pipeTo(B.toWeb(k(e,{encoding:"utf-8"})))}function v(t){return t!=null&&typeof t=="object"&&"code"in t&&t.code==="ENOENT"}async function D(t){try{return await W(t,{encoding:"utf-8"})}catch(e){if(v(e))return null;throw e}}var y=51214,w=51213,A=51215,S=class extends Error{constructor(r,s){super(`Port number \`${r}\` is not available for service ${s}.`);this.port=r;this.service=s}name="PortNotAvailableError"};var M=o(P(),Q()),O=p({connectionString:M}),x=p({url:M}),h=o(F(),R(),_(1)),X=p({database:O,http:x,ppg:x,shadowDatabase:O}),ee=p({databasePort:h,exports:E(X),name:o(P(),q(1)),pid:E(o(F(),R(),_(0))),port:h,shadowDatabasePort:h,version:Z("1")}),g=Symbol("initialize"),T="default",c=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??T,this.persistenceMode=e.persistenceMode,this.pid=e.pid??u.pid,this.port=e.port??51213,this.shadowDatabasePort=e.shadowDatabasePort??51215}static async create(e){let r=e?.dryRun!==!0&&e?.persistenceMode!=="stateless"?new i({...e,pid:u.pid}):new b(e);return await r[g](),r}static async fromServerDump(e){let{debug:r,name:s=T}=e??{},$=l(s),n=i.getServerDumpPath($),m=await D(n);if(m==null)return r&&console.debug(`[State] No server dump file found at: ${n}`),null;r&&(console.debug(`[State] server dump file found at "${n}":`),console.debug(m));let{issues:I,output:a,success:L}=G(o(P(),z(),ee),m);if(!L)throw r&&console.debug(`[State] Invalid server dump file at "${n}":
|
|
3
|
-
${JSON.stringify(I,null,2)}`),new Error(`Invalid Prisma Dev state for "${s}".`);return new i({databasePort:a.databasePort,debug:r,dryRun:!1,name:s,pid:a.pid,port:a.port,serverDump:a,shadowDatabasePort:a.shadowDatabasePort})}},b=class extends c{constructor(e){super({...e,persistenceMode:"stateless",pid:u.pid})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[g](){}async close(){}async writeServerDump(){}},i=class t extends c{#s;#e;#a;#i;#t;#r=null;constructor(e){super({...e,persistenceMode:"stateful"}),this.#e=l(this.name),this.#s=d(this.#e,"db_dump.bak"),this.#a=d(this.#e,".pglite"),this.#t=e.serverDump??null,this.#i=t.getServerDumpPath(this.#e)}static getServerDumpPath(e){return d(e,"server.json")}get databaseDumpPath(){return this.#s}get pgliteDataDirPath(){return this.#a}async[g](){await C(this.#e,{recursive:!0}),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{this.#r=await Y(this.#e,{lockfilePath:d(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 Error(`A server with the name "${this.name}" is already running. `):e}}async close(){this.#r!=null&&(await this.#r(),this.debug&&console.debug(`[State] released lock on: ${this.#e}`))}async writeServerDump(e){this.#t={name:this.name,version:"1",pid:u.pid,port:this.port,databasePort:this.databasePort,shadowDatabasePort:this.shadowDatabasePort,exports:e},await K(this.#i,`${JSON.stringify(this.#t,null,2)}
|
|
4
|
-
`,{encoding:"utf-8"})}};export{ie as a,oe as b,ne as c,de as d,y as e,w as f,A as g,S as h,c as i};
|