@prisma/dev 0.0.0-dev.202607271058 → 0.0.0-dev.202607271405

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/vite.d.cts CHANGED
@@ -79,7 +79,12 @@ interface PrismaDevPluginOptions {
79
79
  /**
80
80
  * The port the database server listens on.
81
81
  *
82
- * Defaults to `51214`, falling back to another free port when taken.
82
+ * Defaults to `51214`. Only the default falls back to another free port when
83
+ * taken; a port passed here is bound or the start fails, because a caller who
84
+ * names a port has something outside this process depending on it.
85
+ *
86
+ * A named `stateful` server records the ports it settled on and reuses them on
87
+ * the next start, so pinning is not required for a stable address.
83
88
  */
84
89
  databasePort?: number;
85
90
  /**
@@ -114,9 +119,11 @@ interface PrismaDevPluginOptions {
114
119
  * unprepared database. `vite dev` waits for it, so a slow migration delays
115
120
  * startup.
116
121
  *
117
- * Runs on every start, including a config restart and the case where the
118
- * plugin attached to a database `prisma dev` already had running. Make it
119
- * idempotent -- `prisma migrate deploy` already is.
122
+ * Runs once per database, not once per dev server. A config restart that does
123
+ * not change this plugin's options keeps the running database, and so does not
124
+ * re-run this hook. It does run when the plugin attached to a database
125
+ * `prisma dev` already had running. Make it idempotent -- `prisma migrate
126
+ * deploy` already is.
120
127
  *
121
128
  * If it rejects, the database is shut down and Vite fails to start rather than
122
129
  * serving against a half-prepared database.
@@ -151,19 +158,22 @@ interface PrismaDevPluginOptions {
151
158
  /**
152
159
  * The port the Prisma Dev HTTP server listens on.
153
160
  *
154
- * Defaults to `51213`, falling back to another free port when taken.
161
+ * Defaults to `51213`. See {@link databasePort} for how an explicitly
162
+ * requested port differs from the default.
155
163
  */
156
164
  port?: number;
157
165
  /**
158
166
  * The port the shadow database server listens on.
159
167
  *
160
- * Defaults to `51215`, falling back to another free port when taken.
168
+ * Defaults to `51215`. See {@link databasePort} for how an explicitly
169
+ * requested port differs from the default.
161
170
  */
162
171
  shadowDatabasePort?: number;
163
172
  /**
164
173
  * The port the colocated Prisma Streams server listens on.
165
174
  *
166
- * Defaults to `51216`, falling back to another free port when taken.
175
+ * Defaults to `51216`. See {@link databasePort} for how an explicitly
176
+ * requested port differs from the default.
167
177
  */
168
178
  streamsPort?: number;
169
179
  }
package/dist/vite.d.ts CHANGED
@@ -79,7 +79,12 @@ interface PrismaDevPluginOptions {
79
79
  /**
80
80
  * The port the database server listens on.
81
81
  *
82
- * Defaults to `51214`, falling back to another free port when taken.
82
+ * Defaults to `51214`. Only the default falls back to another free port when
83
+ * taken; a port passed here is bound or the start fails, because a caller who
84
+ * names a port has something outside this process depending on it.
85
+ *
86
+ * A named `stateful` server records the ports it settled on and reuses them on
87
+ * the next start, so pinning is not required for a stable address.
83
88
  */
84
89
  databasePort?: number;
85
90
  /**
@@ -114,9 +119,11 @@ interface PrismaDevPluginOptions {
114
119
  * unprepared database. `vite dev` waits for it, so a slow migration delays
115
120
  * startup.
116
121
  *
117
- * Runs on every start, including a config restart and the case where the
118
- * plugin attached to a database `prisma dev` already had running. Make it
119
- * idempotent -- `prisma migrate deploy` already is.
122
+ * Runs once per database, not once per dev server. A config restart that does
123
+ * not change this plugin's options keeps the running database, and so does not
124
+ * re-run this hook. It does run when the plugin attached to a database
125
+ * `prisma dev` already had running. Make it idempotent -- `prisma migrate
126
+ * deploy` already is.
120
127
  *
121
128
  * If it rejects, the database is shut down and Vite fails to start rather than
122
129
  * serving against a half-prepared database.
@@ -151,19 +158,22 @@ interface PrismaDevPluginOptions {
151
158
  /**
152
159
  * The port the Prisma Dev HTTP server listens on.
153
160
  *
154
- * Defaults to `51213`, falling back to another free port when taken.
161
+ * Defaults to `51213`. See {@link databasePort} for how an explicitly
162
+ * requested port differs from the default.
155
163
  */
156
164
  port?: number;
157
165
  /**
158
166
  * The port the shadow database server listens on.
159
167
  *
160
- * Defaults to `51215`, falling back to another free port when taken.
168
+ * Defaults to `51215`. See {@link databasePort} for how an explicitly
169
+ * requested port differs from the default.
161
170
  */
162
171
  shadowDatabasePort?: number;
163
172
  /**
164
173
  * The port the colocated Prisma Streams server listens on.
165
174
  *
166
- * Defaults to `51216`, falling back to another free port when taken.
175
+ * Defaults to `51216`. See {@link databasePort} for how an explicitly
176
+ * requested port differs from the default.
167
177
  */
168
178
  streamsPort?: number;
169
179
  }
package/dist/vite.js CHANGED
@@ -1 +1 @@
1
- import{a as f}from"./chunk-MTR5KBPH.js";import"./chunk-662IKR3V.js";import"./chunk-PP43TGA5.js";import"./chunk-KWCQYPJI.js";import{h as y,i as b,l as w}from"./chunk-HFONW2ZS.js";import"./chunk-ANHBRJRZ.js";import"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";import"./chunk-DOJAPHLY.js";var M="DATABASE_URL",I="SHADOW_DATABASE_URL";function P(e){return{databaseUrl:e.database.prismaORMConnectionString??e.database.connectionString,prismaPostgresUrl:e.ppg.url,shadowDatabaseUrl:e.shadowDatabase.prismaORMConnectionString??e.shadowDatabase.connectionString}}function A(e,r={}){let{databaseUrl:n=M,prismaPostgresUrl:a=!1,shadowDatabaseUrl:s=I}=r,t=P(e);return[[n,t.databaseUrl],[s,t.shadowDatabaseUrl],[a,t.prismaPostgresUrl]].filter(d=>typeof d[0]=="string"&&d[0].length>0).map(([d,i])=>({name:d,value:i}))}function x(e,r,n={}){let a=[],s=[];for(let t of e){let o=r[t.name];if(!n.override&&o!=null&&o!==""){s.push(t);continue}r[t.name]=t.value,a.push(t)}return{applied:a,skipped:s}}import{setTimeout as C}from"timers/promises";var N="default",k=15e3,B=250;async function R(e){let{lockRetryTimeoutMillis:r=k,persistenceMode:n="stateful",...a}=e??{};if(n==="stateless"){let{server:t}=await f({...a,persistenceMode:n});return h(t)}let s=Date.now()+r;for(;;)try{let{server:t}=await f({...a,persistenceMode:"stateful"});return h(t)}catch(t){if(!(t instanceof w))throw t;let o=await V(a.name,a.debug);if(o)return o;if(Date.now()>=s)throw t;await C(B)}}function h(e){return{close:()=>e.close(),database:e.database,http:e.http,name:e.name,owned:!0,ppg:e.ppg,server:e,shadowDatabase:e.shadowDatabase}}async function V(e,r){let n=await y(e??N,{debug:r});return!b(n)||!n.exports?null:{...n.exports,close:()=>Promise.resolve(),experimental:n.experimental,name:n.name,owned:!1}}var l=new Map;async function U(e){let{name:r}=e;await D(r);let n=R(e);l.set(r,n);let a;try{a=await n}catch(s){throw l.get(r)===n&&l.delete(r),s}return{release:async()=>{l.get(r)===n&&await D(r)},server:a}}async function E(){await Promise.allSettled([...l.keys()].map(e=>D(e)))}async function D(e){let r=l.get(e);if(!r)return;l.delete(e),await(await r).close()}var q=["SIGINT","SIGTERM"],O=!1;function T(){if(!O){O=!0,process.once("beforeExit",()=>{E()});for(let e of q)process.once(e,()=>{E().finally(()=>{process.kill(process.pid,e)})})}}var u="prisma-dev",$="default",G={info:e=>console.info(e),warn:e=>console.warn(e)};function F(e={}){let{debug:r,enableInTest:n=!1,env:a,name:s=$,onDatabaseReady:t,overrideExistingEnv:o=!1,persistenceMode:d="stateful"}=e,i=null;return{apply(m,v){return v.command==="serve"&&v.isPreview!==!0&&(n||!H())},async config(m){let v=m.customLogger??G;T(),i=await U({databasePort:e.databasePort,debug:r,name:s,persistenceMode:d,port:e.port,shadowDatabasePort:e.shadowDatabasePort,streamsPort:e.streamsPort});let S=A(i.server,a),{applied:L,skipped:_}=x(S,process.env,{override:o});return Y(v,i.server,L.length,_),t&&await K(t,W(i.server,S),v,g),{}},async closeBundle(){await g()},configureServer(m){m.httpServer?.once("close",()=>{g()})},name:u};async function g(){let m=i;i=null,await m?.release()}}var me=F;function W(e,r){return{...P(e),env:Object.fromEntries(r.map(({name:n,value:a})=>[n,a])),name:e.name,owned:e.owned}}async function K(e,r,n,a){try{await e(r)}catch(s){throw n.warn(`[${u}] \`onDatabaseReady\` failed, shutting the database down`,{timestamp:!0}),await a(),s}}function H(){return process.env.VITEST!=null||process.env.VITEST_WORKER_ID!=null}function Y(e,r,n,a){let s=r.owned?"started":"attached to already-running";e.info(`[${u}] ${s} database "${r.name}", set ${n} environment variable(s)`,{timestamp:!0});for(let{name:t}of a)e.warn(`[${u}] ${t} is already set, leaving it untouched. Pass \`overrideExistingEnv: true\` to let the local database win.`,{timestamp:!0})}export{me as default,F as prismaDev};
1
+ import{a as P,b as c}from"./chunk-J6FIMHSD.js";import"./chunk-662IKR3V.js";import"./chunk-PP43TGA5.js";import"./chunk-KWCQYPJI.js";import{h as y,i as S,l as A}from"./chunk-HFONW2ZS.js";import"./chunk-ANHBRJRZ.js";import"./chunk-EDFHV3AK.js";import"./chunk-DWY47FQV.js";import"./chunk-DOJAPHLY.js";var N="DATABASE_URL",V="SHADOW_DATABASE_URL";function b(e,r={}){let{databaseUrl:n=N,prismaPostgresUrl:t=!1,shadowDatabaseUrl:a=V}=r,s=c(e);return[[n,s.databaseUrl],[a,s.shadowDatabaseUrl],[t,s.prismaPostgresUrl]].filter(o=>typeof o[0]=="string"&&o[0].length>0).map(([o,d])=>({name:o,value:d}))}function w(e,r,n={}){let t=[],a=[],s=[];for(let i of e){let o=r[i.name],d=o!=null&&o!=="";if(d&&o===i.value){a.push(i);continue}if(d&&!n.override){s.push(i);continue}r[i.name]=i.value,t.push(i)}return{applied:t,retained:a,skipped:s}}import{setTimeout as k}from"timers/promises";var B="default",C=15e3,$=250;async function x(e){let{lockRetryTimeoutMillis:r=C,persistenceMode:n="stateful",...t}=e??{};if(n==="stateless"){let{server:s}=await P({...t,persistenceMode:n});return h(s)}let a=Date.now()+r;for(;;)try{let{server:s}=await P({...t,persistenceMode:"stateful"});return h(s)}catch(s){if(!(s instanceof A))throw s;let i=await F(t.name,t.debug);if(i)return i;if(Date.now()>=a)throw s;await k($)}}function h(e){return{close:()=>e.close(),database:e.database,http:e.http,name:e.name,owned:!0,ppg:e.ppg,server:e,shadowDatabase:e.shadowDatabase}}async function F(e,r){let n=await y(e??B,{debug:r});return!S(n)||!n.exports?null:{...n.exports,close:()=>Promise.resolve(),experimental:n.experimental,name:n.name,owned:!1}}var l=new Map;async function T(e){let{name:r}=e,n=G(e),t=l.get(r);if(t&&t.signature===n)return t.holders+=1,await O(r,t,!1);await U(r);let a={holders:1,pending:x(e),signature:n};return l.set(r,a),await O(r,a,!0)}async function D(){await Promise.allSettled([...l.keys()].map(e=>U(e)))}async function O(e,r,n){let t;try{t=await r.pending}catch(s){throw R(e,r),s}let a=!1;return{release:async()=>{a||(a=!0,R(e,r)&&await t.close())},server:t,started:n}}function R(e,r){return r.holders-=1,r.holders>0||l.get(e)!==r?!1:(l.delete(e),!0)}async function U(e){let r=l.get(e);if(!r)return;l.delete(e),await(await r.pending.catch(()=>null))?.close()}function G(e){return JSON.stringify(e,Object.keys(e).sort())}var H=["SIGINT","SIGTERM"],_=!1;function I(){if(!_){_=!0,process.once("beforeExit",()=>{D()});for(let e of H)process.once(e,()=>{D().finally(()=>{process.kill(process.pid,e)})})}}var g="prisma-dev",W="default";function j(e={}){let{debug:r,enableInTest:n=!1,env:t,name:a=W,onDatabaseReady:s,overrideExistingEnv:i=!1,persistenceMode:o="stateful"}=e,d=null;return{apply(v,m){return m.command==="serve"&&m.isPreview!==!0&&(n||!J())},async closeBundle(){await f()},async configureServer(v){let{logger:m}=v.config;I(),d=await T({databasePort:e.databasePort,debug:r,name:a,persistenceMode:o,port:e.port,shadowDatabasePort:e.shadowDatabasePort,streamsPort:e.streamsPort}),v.httpServer?.once("close",()=>{f()});let E=b(d.server,t),{applied:L,retained:M,skipped:q}=w(E,process.env,{override:i});z(m,d,[...L,...M],q),s&&d.started&&await Y(s,K(d.server,E),m,f)},name:g};async function f(){let v=d;d=null,await v?.release()}}var fe=j;function K(e,r){return{...c(e),env:Object.fromEntries(r.map(({name:n,value:t})=>[n,t])),name:e.name,owned:e.owned}}async function Y(e,r,n,t){try{await e(r)}catch(a){throw n.warn(`[${g}] \`onDatabaseReady\` failed, shutting the database down`,{timestamp:!0}),await t(),a}}function J(){return process.env.VITEST!=null||process.env.VITEST_WORKER_ID!=null}function z(e,r,n,t){let{server:a}=r,s=Q(r),i=n.length>0?n.map(({name:o})=>o).join(", "):"no environment variables";e.info(`[${g}] ${s} database "${a.name}", set ${i}`,{timestamp:!0});for(let{name:o}of t)e.warn(`[${g}] ${o} already points somewhere else, leaving it untouched. Pass \`overrideExistingEnv: true\` to let the local database win.`,{timestamp:!0})}function Q({server:e,started:r}){return e.owned?r?"started":"reusing":"attached to already-running"}export{fe as default,j as prismaDev};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/dev",
3
- "version": "0.0.0-dev.202607271058",
3
+ "version": "0.0.0-dev.202607271405",
4
4
  "description": "A local Prisma Postgres server for development and testing",
5
5
  "type": "module",
6
6
  "author": "Igal Klebanov <igalklebanov@gmail.com> (https://github.com/igalklebanov)",
@@ -110,7 +110,7 @@
110
110
  "proper-lockfile": "4.1.2",
111
111
  "remeda": "2.33.4",
112
112
  "std-env": "3.10.0",
113
- "valibot": "1.2.0",
113
+ "valibot": "1.4.2",
114
114
  "zeptomatch": "2.1.0"
115
115
  },
116
116
  "scripts": {
@@ -1 +0,0 @@
1
- import{a as W}from"./chunk-662IKR3V.js";import{a as _,b as D,f as b}from"./chunk-PP43TGA5.js";import{a as A,b as P,c as O,d as x,e as v,f as C}from"./chunk-HFONW2ZS.js";import{d as N,j as y}from"./chunk-DWY47FQV.js";import{b as $}from"./chunk-DOJAPHLY.js";import z from"find-my-way";async function M(r,e){let{port:t}=e;if(e.dryRun)return{async close(){},port:t,url:`http://localhost:${t}`};let n=!!e.debug,[{registerAccelerateRoutes:s},{registerUtilityRoutes:i},{createHTTPServer:l}]=await Promise.all([import("./accelerate-TRR43YJ5.js"),import("./utility-YEFNU35E.js"),import("./server-QR7P25DP.js")]),a={databaseDumpPath:e.databaseDumpPath,db:r,debug:n,name:e.name,port:t,shadowDBPort:e.shadowDatabasePort},o=z({defaultRoute(u,p){$(p,"Not Found",404)},ignoreTrailingSlash:!1});s(o,a,n),i(o,a,n);let c=await l({router:o}).listen(t);return e.port=c.port,a.port=c.port,{async close(){let{Engine:u}=await import("./engine-YTEOPVUP.js");await Promise.allSettled([c.close(),u.stopAll()])},port:c.port,url:c.url}}import{isDeepStrictEqual as U}from"util";var X="application/json",w={connection:"close","content-type":X},T={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{applicationName:{type:["string","null"]},durationMs:{type:"number"},groupKey:{type:["string","null"]},query:{type:"string"},queryId:{type:"string"},reads:{type:"number"},rowsReturned:{type:"number"},tables:{items:{type:"string"},type:"array"},timestamp:{format:"date-time",type:"string"}},required:["durationMs","query","queryId","reads","rowsReturned","tables","timestamp"],type:"object"},search:{aliases:{applicationName:"applicationName",groupKey:"groupKey",queryId:"queryId"},fields:{applicationName:{bindings:[{jsonPointer:"/applicationName",version:1}],exact:!0,exists:!0,kind:"keyword"},eventTime:{bindings:[{jsonPointer:"/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},groupKey:{bindings:[{jsonPointer:"/groupKey",version:1}],exact:!0,exists:!0,kind:"keyword"},queryId:{bindings:[{jsonPointer:"/queryId",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};function j(r){return{...r,snapshot:async e=>await Z(r.url,e)}}async function F(r){let e={serverUrl:r.serverUrl,sqlitePath:r.sqlitePath,streamName:P,url:v(r.serverUrl,P)};await re(e);let t=new k({debug:r.debug,streamUrl:e.url}),n=r.bridge.subscribe(s=>{t.enqueue(s)});return{close:async()=>{n(),await t.close()},experimental:e}}async function Z(r,e){if(!r)return _();let t=await ee(r);return D(t,e)}async function ee(r){let e=await fetch(`${r}?offset=-1&format=json`,{headers:{connection:"close"}});if(!e.ok)throw new Error(`Failed to read ${r}: HTTP ${e.status}`);return await e.json()}var k=class{#t;#r;#e;constructor(e){this.#t=e.debug,this.#r=Promise.resolve(),this.#e=e.streamUrl}enqueue(e){e.length!==0&&(this.#r=this.#r.then(async()=>{await se(this.#e,e),this.#t&&console.debug(`[streams] appended ${e.length} query insight record(s) to ${this.#e}`)}).catch(t=>{console.error("[streams] failed to ingest query insights into prisma-queries",t)}))}async close(){await this.#r}};async function re(r){let e=await fetch(r.url,{headers:w,method:"PUT"});if(!e.ok)throw await E(e,`Failed to create ${r.streamName}`);let t=await ne(r);if(te(t,r.streamName))return;if(t.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let n=await fetch(`${r.url}/_schema`,{body:JSON.stringify(T),headers:w,method:"POST"});if(!n.ok)throw await E(n,`Failed to install schema for ${r.streamName}`)}function te(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return U(t,T.schema)&&U(r.search,T.search)}async function ne(r){let e=await fetch(`${r.url}/_schema`,{headers:w,method:"GET"});if(!e.ok)throw await E(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}async function se(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:w,method:"POST"});if(!t.ok)throw await E(t,"Failed to append to prisma-queries")}async function E(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}import{randomUUID as ae}from"crypto";import{setTimeout as H}from"timers/promises";import{isDeepStrictEqual as K}from"util";import{process as ie}from"std-env";var oe="application/json",S={connection:"close","content-type":oe},le={apiVersion:"durable.streams/profile/v1",profile:{kind:"state-protocol",touch:{enabled:!0,onMissingBefore:"coarse"}}},B={apiVersion:"durable.streams/schema-registry/v1",schema:{additionalProperties:!0,properties:{headers:{properties:{operation:{type:"string"},timestamp:{format:"date-time",type:"string"}},required:["timestamp","operation"],type:"object"},key:{type:"string"},type:{type:"string"}},required:["type","key","headers"],type:"object"},search:{aliases:{rowKey:"key",table:"type"},fields:{eventTime:{bindings:[{jsonPointer:"/headers/timestamp",version:1}],column:!0,exact:!0,exists:!0,kind:"date",sortable:!0},key:{bindings:[{jsonPointer:"/key",version:1}],exact:!0,exists:!0,kind:"keyword"},operation:{bindings:[{jsonPointer:"/headers/operation",version:1}],exact:!0,exists:!0,kind:"keyword"},type:{bindings:[{jsonPointer:"/type",version:1}],exact:!0,exists:!0,kind:"keyword"}},primaryTimestampField:"eventTime"}};async function V(r){let{dbServer:e,debug:t,name:n,persistenceMode:s,port:i,queryInsightsBridge:l,walBridge:a}=r,o=s==="stateless",c=o?we(n):n,u=x(c),p=!o&&await N(u);ie.env.DS_LOCAL_DATA_ROOT=O(),o&&await y(u);let m=await ue({debug:t,hadExistingStreamsData:p,name:c,port:i}),h={serverUrl:m.exports.http.url,sqlitePath:m.exports.sqlite.path,streamName:A,url:v(m.exports.http.url)};try{await pe(h);let d=await F({bridge:l,debug:t,serverUrl:m.exports.http.url,sqlitePath:m.exports.sqlite.path}),g=new Q({dbServer:e,debug:t,streamUrl:h.url}),G=a.subscribe(Y=>{g.enqueue(Y)});return{close:async()=>{G(),await g.close(),await d.close(),await m.close(),await H(100),o&&await y(u)},experimental:h,experimentalQueryInsights:d.experimental}}catch(d){throw await m.close().catch(()=>{}),await H(100),o&&await y(u).catch(()=>{}),d}}var ce=["database disk image is malformed","duplicate column name:","file is not a database","malformed database schema","no such column:","no such table:","schema_version row missing after migration","unexpected schema version:"];async function ue(r){let{debug:e,hadExistingStreamsData:t,name:n,port:s}=r,{startLocalDurableStreamsServer:i}=await import("@prisma/streams-local"),l=()=>i({hostname:"127.0.0.1",name:n,port:s});try{return await l()}catch(a){if(!t||!me(a))throw a;return console.warn(`[streams] resetting incompatible durable streams data for "${n}"`),e&&console.debug(`[streams] original durable streams startup error for "${n}"`,a),await y(x(n)),await l()}}function me(r){return de(r).map(t=>t.toLowerCase()).some(t=>ce.some(n=>t.includes(n)))}function de(r){let e=[],t=[r],n=new Set;for(;t.length>0;){let s=t.shift();if(!(s==null||n.has(s))){if(n.add(s),typeof s=="string"){e.push(s);continue}if(s instanceof AggregateError)for(let i of s.errors)t.push(i);if(s instanceof Error){e.push(s.message);let i=s.cause;i!==void 0&&t.push(i)}}}return e}var Q=class{#t;#r;#e;#n;#s;constructor(e){this.#t=e.dbServer,this.#r=e.debug,this.#e=Promise.resolve(),this.#n=e.streamUrl,this.#s=new Set}enqueue(e){e.length!==0&&(this.#e=this.#e.then(async()=>{let t=await this.#i(e);t.length!==0&&(await ye(this.#n,t),this.#r&&console.debug(`[streams] appended ${t.length} state-protocol record(s) to ${this.#n}`))}).catch(t=>{console.error("[streams] failed to ingest WAL events into prisma-wal",t)}))}async close(){await this.#e}async#i(e){let t=[],n=new Date().toISOString();for(let s of e)t.push(...await this.#o(s,n));return t}async#o(e,t){let n=`${e.schema}.${e.table}`,s=await this.#t.getPrimaryKeyColumns(e.schema,e.table),i=L(e.record),l=L(e.oldRecord),a=this.#a(n,s,l),o=this.#a(n,s,i),c=e.txid===""?void 0:e.txid;return e.type==="insert"?i&&o?[{headers:{operation:"insert",timestamp:t,txid:c},key:o,old_value:null,type:n,value:i}]:[]:e.type==="delete"?l&&a?[{headers:{operation:"delete",timestamp:t,txid:c},key:a,old_value:l,type:n,value:null}]:[]:!i||!l||!a||!o?[]:a!==o?[{headers:{operation:"delete",timestamp:t,txid:c},key:a,old_value:l,type:n,value:null},{headers:{operation:"insert",timestamp:t,txid:c},key:o,old_value:null,type:n,value:i}]:[{headers:{operation:"update",timestamp:t,txid:c},key:o,old_value:l,type:n,value:i}]}#a(e,t,n){if(!n)return null;let s=Se(n,t);return s||(this.#s.has(e)||(this.#s.add(e),console.warn(`[streams] falling back to full-row keys for ${e} because no primary key could be resolved`)),fe(n))}};async function pe(r){let e=await fetch(r.url,{headers:S,method:"PUT"});if(!e.ok)throw await f(e,`Failed to create ${r.streamName}`);let t=await fetch(`${r.url}/_profile`,{body:JSON.stringify(le),headers:S,method:"POST"});if(!t.ok)throw await f(t,`Failed to configure ${r.streamName}`);let n=await he(r);if(ge(n,r.streamName))return;if(n.currentVersion>0)throw new Error(`Failed to install schema for ${r.streamName}: existing schema registry is incompatible and requires a lens migration`);let s=await fetch(`${r.url}/_schema`,{body:JSON.stringify(B),headers:S,method:"POST"});if(!s.ok)throw await f(s,`Failed to install schema for ${r.streamName}`)}async function he(r){let e=await fetch(`${r.url}/_schema`,{headers:S,method:"GET"});if(!e.ok)throw await f(e,`Failed to inspect schema for ${r.streamName}`);return await e.json()}function ge(r,e){if(r.currentVersion<=0||r.schema!==e)return!1;let t=r.schemas[String(r.currentVersion)];return K(t,B.schema)&&K(r.search,B.search)}async function ye(r,e){let t=await fetch(r,{body:JSON.stringify(e),headers:S,method:"POST"});if(!t.ok)throw await f(t,"Failed to append to prisma-wal")}async function f(r,e){let t=await r.text().catch(()=>"");return new Error(`${e}: HTTP ${r.status}${t?` ${t}`:""}`)}function Se(r,e){if(e.length===0)return null;let t=[];for(let n of e){if(!Object.prototype.hasOwnProperty.call(r,n))return null;let s=ve(r[n]);if(s==null)return null;t.push(e.length===1?s:`${n}=${s}`)}return t.join("|")}function fe(r){return JSON.stringify(q(r))}function q(r){return Array.isArray(r)?r.map(e=>q(e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,q(t)])):r}function L(r){return r?structuredClone(r):null}function ve(r){if(r===null)return"null";if(r===void 0)return"undefined";if(typeof r=="string")return r;if(typeof r=="number")return Number.isFinite(r)?String(r):null;if(typeof r=="bigint")return r.toString();if(typeof r=="boolean")return r?"true":"false";try{return JSON.stringify(r)}catch{return null}}function we(r){return`${r}.${ae().replaceAll("-","")}`}async function Xe(r){let e=await C.createExclusively(r),t=null,n=null,s=null,i=null;try{[t,s]=await Promise.all([b("database",e),b("shadow_database",e)]);let l,a;e.dryRun?(l=xe(),a=Re(),i=Ie()):(l=await t.attachWalEventBridge(),a=await t.attachQueryInsightsBridge(),i=await V({dbServer:t,debug:e.debug,name:e.name,port:e.streamsPort,persistenceMode:e.persistenceMode,queryInsightsBridge:a,walBridge:l})),n=await M(t,e);let o=Ee(t,s,n,e);await e.writeServerDump(o,e.dryRun?{}:{queryInsights:i.experimentalQueryInsights,streams:i.experimental});let c=Pe(l),u=j(i.experimentalQueryInsights),p=t,m=s,h=n,d=i,g=async()=>{c.close(),await J(e,[h,d,p,m])};return{close:g,dbServer:t,httpServer:n,server:{...o,close:g,experimental:{queryInsights:u,streams:i.experimental,wal:c.api},name:e.name},serverState:e,shadowDbServer:s,streamsServer:i,queryInsightsBridge:a,walBridge:l}}catch(l){return await be(e,[n,i,t,s],l)}}function Ee(r,e,t,n){let s=`prisma+postgres://localhost:${t.port}/?${new URLSearchParams({api_key:W({databaseUrl:r.prismaORMConnectionString,name:n.name,shadowDatabaseUrl:e.prismaORMConnectionString})}).toString()}`;return{database:{connectionString:r.connectionString,prismaORMConnectionString:r.prismaORMConnectionString,terminalCommand:r.terminalCommand},http:{url:t.url},ppg:{url:s},shadowDatabase:{connectionString:e.prismaORMConnectionString,prismaORMConnectionString:e.prismaORMConnectionString,terminalCommand:e.terminalCommand}}}async function J(r,e){let t=[];for(let n of e)try{await n.close()}catch(s){t.push(s)}try{await r.close()}catch(n){t.push(n)}if(t.length>0)throw new AggregateError(t,"Failed to close some servers")}async function be(r,e,t){try{await J(r,e.filter(n=>n!==null))}catch(n){throw new AggregateError([t,n],"Failed to start Prisma Dev server cleanly")}throw t}function Pe(r){let e=new Set;return{api:{stream:()=>{let t=()=>{},n=Te(r,()=>{e.delete(t)});return t=()=>n.close(),e.add(t),n.stream},subscribe:t=>r.subscribe(t)},close:()=>{for(let t of[...e])t();e.clear()}}}function xe(){return{async close(){},async poll(){},subscribe(){return()=>{}}}}function Re(){return{async close(){},subscribe(){return()=>{}}}}function Ie(){return{async close(){},experimental:{serverUrl:"",sqlitePath:"",streamName:"",url:""},experimentalQueryInsights:{serverUrl:"",sqlitePath:"",streamName:"",url:""}}}function Te(r,e){let t=[],n=!1,s=null,i=r.subscribe(a=>{if(!n){if(s){let o=s;s=null,o.resolve({done:!1,value:a});return}t.push(a)}}),l=()=>{if(!n&&(n=!0,i(),t.length=0,e(),s)){let a=s;s=null,a.resolve({done:!0,value:void 0})}};return{close:l,stream:{[Symbol.asyncIterator](){return this},next(){return t.length>0?Promise.resolve({done:!1,value:t.shift()}):n?Promise.resolve({done:!0,value:void 0}):new Promise((a,o)=>{s={reject:o,resolve:a}})},return(){return l(),Promise.resolve({done:!0,value:void 0})},throw(a){let o=s;return l(),o&&o.reject(a),Promise.reject(a instanceof Error?a:new Error(String(a)))}}}}export{Xe as a};