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

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.
Files changed (87) hide show
  1. package/README.md +259 -0
  2. package/dist/accelerate-TRR43YJ5.js +11 -0
  3. package/dist/chunk-662IKR3V.js +1 -0
  4. package/dist/chunk-A5B4L65Y.js +1 -0
  5. package/dist/chunk-ANHBRJRZ.js +1 -0
  6. package/dist/chunk-DOJAPHLY.js +1 -0
  7. package/dist/{chunk-X3G665AK.js → chunk-EDFHV3AK.js} +1 -1
  8. package/dist/chunk-HFONW2ZS.js +3 -0
  9. package/dist/chunk-KWCQYPJI.js +1 -0
  10. package/dist/chunk-MTR5KBPH.js +1 -0
  11. package/dist/chunk-PP43TGA5.js +107 -0
  12. package/dist/chunk-SW3J2PL2.js +1 -0
  13. package/dist/daemon.cjs +33 -26
  14. package/dist/daemon.d.cts +12 -3
  15. package/dist/daemon.d.ts +12 -3
  16. package/dist/daemon.js +1 -1
  17. package/dist/db-BzbLAxLn.d.cts +126 -0
  18. package/dist/db-HU7BFiFV.d.ts +126 -0
  19. package/dist/db.cjs +23 -16
  20. package/dist/db.d.cts +3 -70
  21. package/dist/db.d.ts +3 -70
  22. package/dist/db.js +1 -1
  23. package/dist/engine-YTEOPVUP.js +3 -0
  24. package/dist/index.cjs +33 -26
  25. package/dist/index.d.cts +10 -6
  26. package/dist/index.d.ts +10 -6
  27. package/dist/index.js +1 -1
  28. package/dist/query-plan-executor-ZS4544O3.js +1 -0
  29. package/dist/runtime-assets/amcheck.tar.gz +0 -0
  30. package/dist/runtime-assets/bloom.tar.gz +0 -0
  31. package/dist/runtime-assets/btree_gin.tar.gz +0 -0
  32. package/dist/runtime-assets/btree_gist.tar.gz +0 -0
  33. package/dist/runtime-assets/citext.tar.gz +0 -0
  34. package/dist/runtime-assets/cube.tar.gz +0 -0
  35. package/dist/runtime-assets/dict_int.tar.gz +0 -0
  36. package/dist/runtime-assets/dict_xsyn.tar.gz +0 -0
  37. package/dist/runtime-assets/earthdistance.tar.gz +0 -0
  38. package/dist/runtime-assets/file_fdw.tar.gz +0 -0
  39. package/dist/runtime-assets/fuzzystrmatch.tar.gz +0 -0
  40. package/dist/runtime-assets/hstore.tar.gz +0 -0
  41. package/dist/runtime-assets/initdb.wasm +0 -0
  42. package/dist/runtime-assets/intarray.tar.gz +0 -0
  43. package/dist/runtime-assets/isn.tar.gz +0 -0
  44. package/dist/runtime-assets/lo.tar.gz +0 -0
  45. package/dist/runtime-assets/ltree.tar.gz +0 -0
  46. package/dist/runtime-assets/pageinspect.tar.gz +0 -0
  47. package/dist/runtime-assets/pg_buffercache.tar.gz +0 -0
  48. package/dist/runtime-assets/pg_freespacemap.tar.gz +0 -0
  49. package/dist/runtime-assets/pg_surgery.tar.gz +0 -0
  50. package/dist/runtime-assets/pg_trgm.tar.gz +0 -0
  51. package/dist/runtime-assets/pg_visibility.tar.gz +0 -0
  52. package/dist/runtime-assets/pg_walinspect.tar.gz +0 -0
  53. package/dist/runtime-assets/pglite-seed.tar.gz +0 -0
  54. package/dist/runtime-assets/pglite.wasm +0 -0
  55. package/dist/runtime-assets/seg.tar.gz +0 -0
  56. package/dist/runtime-assets/tablefunc.tar.gz +0 -0
  57. package/dist/runtime-assets/tcn.tar.gz +0 -0
  58. package/dist/runtime-assets/tsm_system_rows.tar.gz +0 -0
  59. package/dist/runtime-assets/tsm_system_time.tar.gz +0 -0
  60. package/dist/runtime-assets/unaccent.tar.gz +0 -0
  61. package/dist/runtime-assets/uuid-ossp.tar.gz +0 -0
  62. package/dist/runtime-assets/vector.tar.gz +0 -0
  63. package/dist/runtime-assets-manifest.bun.js +2 -0
  64. package/dist/runtime-assets.cjs +1 -1
  65. package/dist/runtime-assets.d.cts +2 -0
  66. package/dist/runtime-assets.d.ts +2 -0
  67. package/dist/runtime-assets.js +1 -1
  68. package/dist/server-QR7P25DP.js +1 -0
  69. package/dist/{state-DTMxyzXf.d.ts → state-CNKFAMiX.d.cts} +22 -1
  70. package/dist/{state-DTMxyzXf.d.cts → state-CNKFAMiX.d.ts} +22 -1
  71. package/dist/state.cjs +3 -3
  72. package/dist/state.d.cts +1 -1
  73. package/dist/state.d.ts +1 -1
  74. package/dist/state.js +1 -1
  75. package/dist/utility-YEFNU35E.js +1 -0
  76. package/dist/vite.cjs +121 -0
  77. package/dist/vite.d.cts +186 -0
  78. package/dist/vite.d.ts +184 -0
  79. package/dist/vite.js +1 -0
  80. package/package.json +27 -8
  81. package/dist/accelerate-HWGEFOM5.js +0 -11
  82. package/dist/chunk-62DM64XC.js +0 -1
  83. package/dist/chunk-CC3P7GPW.js +0 -3
  84. package/dist/chunk-TF5C7XJX.js +0 -3
  85. package/dist/chunk-X7AUCZJT.js +0 -1
  86. package/dist/chunk-YL6J3L2T.js +0 -100
  87. package/dist/utility-Q5A254LJ.js +0 -1
package/README.md ADDED
@@ -0,0 +1,259 @@
1
+ # `@prisma/dev`
2
+
3
+ A local Prisma Postgres server for development and testing.
4
+
5
+ It runs a real PostgreSQL database in your own Node process — no Docker, no separate service to install — and exposes it over both a plain TCP connection string and the `prisma+postgres://` HTTP protocol that deployed Prisma Postgres uses.
6
+
7
+ > **Not for production.** This is a development and testing tool.
8
+
9
+ There are two ways to use it:
10
+
11
+ - **[`@prisma/dev/vite`](#vite-plugin)** — a Vite plugin that runs a database for the lifetime of your dev server.
12
+ - **[`@prisma/dev`](#programmatic-server)** — start and stop a server from your own code.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ npm install --save-dev @prisma/dev
18
+ ```
19
+
20
+ ## Vite plugin
21
+
22
+ Add the plugin and your app gets a database whenever `vite dev` runs.
23
+
24
+ ```ts
25
+ import { prismaDev } from "@prisma/dev/vite";
26
+ import { defineConfig } from "vite";
27
+
28
+ export default defineConfig({
29
+ plugins: [prismaDev({ name: "my-app" })],
30
+ });
31
+ ```
32
+
33
+ That sets two environment variables before any of your code runs:
34
+
35
+ | Variable | Value |
36
+ | --------------------- | ---------------------------------------------------------------------------------- |
37
+ | `DATABASE_URL` | TCP connection string for the main database |
38
+ | `SHADOW_DATABASE_URL` | TCP connection string for the shadow database, which `prisma migrate dev` requires |
39
+
40
+ Set `name` per project. It decides where the database files are persisted, so two projects left on the default name would share data.
41
+
42
+ Production builds are untouched. See [When the plugin does nothing](#when-the-plugin-does-nothing).
43
+
44
+ ### Applying migrations and seeding
45
+
46
+ A fresh database has no schema. You could migrate from application code, but then migration logic ships in your production artifact for the sake of local development. `onDatabaseReady` keeps it in the dev-only config instead.
47
+
48
+ ```ts
49
+ import { execFile } from "node:child_process";
50
+ import { promisify } from "node:util";
51
+
52
+ import { prismaDev } from "@prisma/dev/vite";
53
+ import { defineConfig } from "vite";
54
+
55
+ const execFileAsync = promisify(execFile);
56
+
57
+ export default defineConfig({
58
+ plugins: [
59
+ prismaDev({
60
+ name: "my-app",
61
+ async onDatabaseReady({ env }) {
62
+ await execFileAsync("npx", ["prisma", "migrate", "deploy"], { env: { ...process.env, ...env } });
63
+ },
64
+ }),
65
+ ],
66
+ });
67
+ ```
68
+
69
+ The hook runs before any application or framework code executes, so nothing can observe an unprepared database. `vite dev` waits for it, so a slow migration delays startup.
70
+
71
+ One hook is registered, but it can do as much as you need. Sequence with plain `await`:
72
+
73
+ ```ts
74
+ async onDatabaseReady(database) {
75
+ await migrate(database);
76
+ await seed(database);
77
+ }
78
+ ```
79
+
80
+ It receives:
81
+
82
+ | Property | Description |
83
+ | ------------------- | ---------------------------------------------------------------------- |
84
+ | `databaseUrl` | TCP connection string for the main database |
85
+ | `shadowDatabaseUrl` | TCP connection string for the shadow database |
86
+ | `prismaPostgresUrl` | The `prisma+postgres://` connection string. Carries an API key |
87
+ | `env` | The variables this plugin manages, mapped to the local database |
88
+ | `name` | The server name |
89
+ | `owned` | `false` when the plugin attached to a database another process started |
90
+
91
+ #### Pass `database.env` when spawning a subprocess
92
+
93
+ Spread `env` explicitly, as the example above does. Do not rely on the ambient `process.env`.
94
+
95
+ By default the plugin does not overwrite a variable your environment already defines. So if your `.env` points `DATABASE_URL` at a deployed database, the plugin leaves it alone — and a migration that inherited `process.env` would run **against that deployed database**.
96
+
97
+ `database.env` always describes the local database, whether or not those values were written to `process.env`. Spreading it keeps the migration local under either setting of [`overrideExistingEnv`](#conflicting-environment-variables), so it is the safe habit regardless of how you configure that.
98
+
99
+ #### The hook runs on every start
100
+
101
+ That includes restarts, and the case where the plugin attached to a database that was already running. Make it idempotent — `prisma migrate deploy` already is.
102
+
103
+ #### If the hook fails
104
+
105
+ The plugin shuts the database down and Vite fails to start. It will not serve your app against a half-prepared database.
106
+
107
+ ### Throwaway databases
108
+
109
+ By default the database is persisted under `name` and survives dev server restarts. Set `persistenceMode: "stateless"` to get a clean, in-memory database on every start instead.
110
+
111
+ ```ts
112
+ prismaDev({
113
+ enableInTest: true,
114
+ name: "my-tests",
115
+ persistenceMode: "stateless",
116
+ });
117
+ ```
118
+
119
+ The clearest use is integration tests, paired with `enableInTest`, where every run should start from a known state.
120
+
121
+ For interactive `vite dev` it is worth understanding what you give up:
122
+
123
+ - Editing `vite.config.ts` or an `.env` file restarts the dev server, which **discards the data**. Anything you seeded or entered by hand is gone.
124
+ - `onDatabaseReady` gets an empty database on every start, so it has to do the full migrate and seed each time.
125
+ - The database is invisible to `prisma dev ls`, `stop`, and `rm`, and cannot be shared with a running `prisma dev`.
126
+ - Ports are chosen from whatever is free rather than the defaults below, unless you set them explicitly. That matters if you want to `psql` in at a predictable address.
127
+
128
+ ### Sharing a database with `prisma dev`
129
+
130
+ If a `prisma dev` server is already running under the same `name`, the plugin uses it instead of starting its own, and leaves it running when Vite exits. `database.owned` is `false` in that case.
131
+
132
+ This applies to the default `stateful` mode only. A `stateless` plugin always starts its own throwaway database, so asking for one never hands you a persistent database by surprise.
133
+
134
+ So this works, with both terminals on one database:
135
+
136
+ ```bash
137
+ # terminal 1
138
+ npx prisma dev --name my-app
139
+
140
+ # terminal 2 — vite.config.ts uses prismaDev({ name: "my-app" })
141
+ npx vite dev
142
+ ```
143
+
144
+ ### Connection strings never reach the browser
145
+
146
+ The plugin writes to `process.env` and nothing else. It deliberately does not use Vite's `define` or `import.meta.env`.
147
+
148
+ Those inline values into browser assets. Both the TCP connection string and the `prisma+postgres://` URL carry credentials, so inlining either would hand database access to every visitor of your app.
149
+
150
+ Server-side code, SSR loaders, and Prisma Client all read `process.env`, which is the surface that actually needs these values.
151
+
152
+ ### The database's lifetime
153
+
154
+ The database runs inside the Vite process, so it cannot outlive it. There is no background daemon and nothing to clean up by hand.
155
+
156
+ Quitting Vite normally, or with `Ctrl-C`, shuts the database down cleanly. A `kill -9` takes the database down with the process; the next start recovers on its own, though it may pause briefly to do so.
157
+
158
+ Editing `vite.config.ts` or an `.env` file restarts the database, because the edit may have changed the plugin's own options. Your data is persisted, so it survives the restart — unless you opted into [a throwaway database](#throwaway-databases). Editing application code does not touch the database.
159
+
160
+ ### When the plugin does nothing
161
+
162
+ No database is started when:
163
+
164
+ - the command is `vite build`
165
+ - the command is `vite preview`
166
+ - the config was loaded by Vitest, which reads the same `vite.config.ts`
167
+
168
+ Pass `enableInTest: true` to allow a database under Vitest.
169
+
170
+ ### Conflicting environment variables
171
+
172
+ By default, if a variable the plugin wants to write already holds a value, the existing value wins and the plugin logs a warning. An intentional `.env` entry or shell export is not silently replaced.
173
+
174
+ Pass `overrideExistingEnv: true` to let the local database win instead.
175
+
176
+ ### Using the `prisma+postgres://` URL
177
+
178
+ Off by default, because it embeds an API key. Opt in by naming a variable:
179
+
180
+ ```ts
181
+ prismaDev({
182
+ env: { prismaPostgresUrl: "PRISMA_DATABASE_URL" },
183
+ name: "my-app",
184
+ });
185
+ ```
186
+
187
+ ### Options
188
+
189
+ | Option | Default | Description |
190
+ | ----------------------- | ----------------------- | -------------------------------------------------------------- |
191
+ | `name` | `"default"` | Server name, which decides where data is persisted |
192
+ | `onDatabaseReady` | — | Async hook to migrate and seed before Vite starts |
193
+ | `persistenceMode` | `"stateful"` | `"stateless"` for a clean in-memory database on every start |
194
+ | `env.databaseUrl` | `"DATABASE_URL"` | Variable for the main TCP connection string. `false` to skip |
195
+ | `env.shadowDatabaseUrl` | `"SHADOW_DATABASE_URL"` | Variable for the shadow TCP connection string. `false` to skip |
196
+ | `env.prismaPostgresUrl` | `false` | Variable for the `prisma+postgres://` URL. Name it to opt in |
197
+ | `overrideExistingEnv` | `false` | Overwrite variables that already hold a value |
198
+ | `enableInTest` | `false` | Start a database when the config is loaded by Vitest |
199
+ | `port` | `51213` | HTTP server port |
200
+ | `databasePort` | `51214` | Main database port |
201
+ | `shadowDatabasePort` | `51215` | Shadow database port |
202
+ | `streamsPort` | `51216` | Colocated Prisma Streams server port |
203
+ | `debug` | `false` | Log the server's debug output |
204
+
205
+ Every port falls back to another free port when the requested one is taken.
206
+
207
+ ## Programmatic server
208
+
209
+ For test harnesses, scripts, and integrations outside Vite:
210
+
211
+ ```ts
212
+ import { startPrismaDevServer } from "@prisma/dev";
213
+
214
+ const server = await startPrismaDevServer({ name: "my-tests" });
215
+
216
+ console.log(server.database.prismaORMConnectionString); // postgres://...
217
+ console.log(server.ppg.url); // prisma+postgres://...
218
+
219
+ await server.close();
220
+ ```
221
+
222
+ The resolved server exposes:
223
+
224
+ | Property | Description |
225
+ | ---------------- | ------------------------------------------------------------------------------- |
226
+ | `database` | `connectionString`, `prismaORMConnectionString`, and a `psql` `terminalCommand` |
227
+ | `shadowDatabase` | The same shape, for `prisma migrate` |
228
+ | `ppg.url` | The `prisma+postgres://` connection string, API key included |
229
+ | `http.url` | Base URL of the HTTP server |
230
+ | `name` | The server name |
231
+ | `close()` | Shuts everything down |
232
+
233
+ ### Persistence
234
+
235
+ `startPrismaDevServer()` defaults to `persistenceMode: "stateless"`, which discards all data when the server closes. That suits tests.
236
+
237
+ Pass `persistenceMode: "stateful"` to persist data under the given `name`, matching `prisma dev` and the Vite plugin's default.
238
+
239
+ ```ts
240
+ const server = await startPrismaDevServer({ name: "my-app", persistenceMode: "stateful" });
241
+ ```
242
+
243
+ ### Ports
244
+
245
+ Defaults are `51213` for HTTP, `51214` for the database, `51215` for the shadow database, and `51216` for the Prisma Streams server. Override any of them with `port`, `databasePort`, `shadowDatabasePort`, and `streamsPort`.
246
+
247
+ Starting a second server under a `name` that is already running rejects with `ServerAlreadyRunningError`.
248
+
249
+ ### Experimental
250
+
251
+ `server.experimental` exposes change-data-capture events, query insights, and the colocated Prisma Streams endpoint. These are experimental and may change without notice.
252
+
253
+ ## Requirements
254
+
255
+ The Vite plugin supports Vite 5, 6, 7, and 8. `vite` is an optional peer dependency, so installing `@prisma/dev` without Vite is fine — the plugin module references Vite for types only.
256
+
257
+ ## License
258
+
259
+ ISC
@@ -0,0 +1,11 @@
1
+ import{b as p}from"./chunk-662IKR3V.js";import{a as g}from"./chunk-SW3J2PL2.js";import{a as M}from"./chunk-ANHBRJRZ.js";import"./chunk-EDFHV3AK.js";import{a as d,b as m,c as B}from"./chunk-DOJAPHLY.js";import{text as Q}from"stream/consumers";import{json as en}from"stream/consumers";import{array as tn,literal as rn,minLength as on,object as sn,pipe as an,safeParse as cn,string as un,union as ln}from"valibot";var fn=sn({tags:ln([an(tn(un()),on(1)),rn("all")])});async function C(n,r){let e;try{e=await en(n)}catch{return m(r,"Invalid input",400),null}let{output:t,success:i}=cn(fn,e,{abortEarly:!0});return i?t:(m(r,"Invalid input",400),null)}import{Buffer as L}from"buffer";var x=new Map;async function O(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(a=>a.toString(16).padStart(2,"0")).join("")}function N(n,r){let e=n.schemaHash;if(e==null)return d(r,{EngineNotStarted:{reason:"SchemaMissing"}},404),null;let t=x.get(e);return t==null?(d(r,{EngineNotStarted:{reason:"SchemaMissing"}},404),null):{schemaHash:e,schemas:t}}async function V(n,r,e){let t=L.from(n,"base64").toString("utf8"),i=mn(t,r.toString());e&&console.log("[Accelerate] schema with override:",i);let o=await O(i);return{base64Override:L.from(i,"utf8").toString("base64"),overrideHash:o}}var dn=" ";function mn(n,r){let e=pn(n);if(!e)throw new Error("No datasource block found in schema.");let t=n.slice(e.openBraceIndex+1,e.closeBraceIndex),i=Sn(t,r,wn(n,e.openBraceIndex));return`${n.slice(0,e.openBraceIndex+1)}${i}${n.slice(e.closeBraceIndex)}`}function pn(n){let r="datasource";for(let e=0;e<n.length;e+=1){let t=n[e];if(t==="/"&&n[e+1]==="/"){e=R(n,e+2);continue}if(t==="/"&&n[e+1]==="*"){e=P(n,e+2);continue}if(t==='"'){e=v(n,e+1);continue}if(n.startsWith(r,e)&&!_(n[e-1])&&!_(n[e+r.length])){let i=gn(n,e+r.length,"{");if(i===-1)return null;let o=hn(n,i);return o===-1?null:{closeBraceIndex:o,openBraceIndex:i}}}return null}function gn(n,r,e){for(let t=r;t<n.length;t+=1){let i=n[t];if(i==="/"&&n[t+1]==="/"){t=R(n,t+2);continue}if(i==="/"&&n[t+1]==="*"){t=P(n,t+2);continue}if(i==='"'){t=v(n,t+1);continue}if(i===e)return t}return-1}function hn(n,r){let e=0;for(let t=r;t<n.length;t+=1){let i=n[t];if(i==="/"&&n[t+1]==="/"){t=R(n,t+2);continue}if(i==="/"&&n[t+1]==="*"){t=P(n,t+2);continue}if(i==='"'){t=v(n,t+1);continue}if(i==="{"){e+=1;continue}if(i==="}"&&(e-=1,e===0))return t}return-1}function R(n,r){let e=r;for(;e<n.length&&n[e]!==`
2
+ `;)e+=1;return e}function P(n,r){let e=n.indexOf("*/",r);return e===-1?n.length:e+1}function v(n,r){let e=r;for(;e<n.length;){if(n[e]==="\\"){e+=2;continue}if(n[e]==='"')return e;e+=1}return n.length}function _(n){return n!=null&&/[A-Za-z0-9_]/.test(n)}function Sn(n,r,e){let t=`"${xn(r)}"`,i=yn(n);for(let[f,h]of i.entries()){let{comment:I,code:nn}=D(h.line),T=nn.match(/^(\s*)url(\s*)=(\s*).*/);if(T)return i[f]={line:`${T[1]}url${T[2]}=${T[3]}${t}${I}`,terminator:h.terminator},$(i)}let o=Tn(n),a=In(i,e),u=`${a}url = ${t}`;if(!n.includes(`
3
+ `)&&!n.includes("\r")){let f=n.trim();return f.length===0?`${o}${u}${o}${e}`:`${o}${a}${f}${o}${u}${o}${e}`}let s=i.at(-1);if(s&&s.terminator===""&&/^\s*$/.test(s.line))return`${$(i.slice(0,-1))}${u}${o}${e}`;let c=$(i),l=c.endsWith(`
4
+ `)||c.endsWith("\r")?"":o;return`${c}${l}${u}${o}${e}`}function yn(n){let r=[],e=0;for(let t=0;t<n.length;t+=1){if(n[t]==="\r"&&n[t+1]===`
5
+ `){r.push({line:n.slice(e,t),terminator:`\r
6
+ `}),t+=1,e=t+1;continue}(n[t]===`
7
+ `||n[t]==="\r")&&(r.push({line:n.slice(e,t),terminator:n[t]}),e=t+1)}return(e<n.length||n.length===0)&&r.push({line:n.slice(e),terminator:""}),r}function $(n){return n.map(r=>`${r.line}${r.terminator}`).join("")}function D(n){let r=!1,e=!1;for(let t=0;t<n.length;t+=1){let i=n[t];if(e){if(r){r=!1;continue}if(i==="\\"){r=!0;continue}i==='"'&&(e=!1);continue}if(i==='"'){e=!0;continue}if(i==="/"&&n[t+1]==="/")return{code:n.slice(0,t),comment:n.slice(t)}}return{code:n,comment:""}}function In(n,r){for(let e of n){let{code:t}=D(e.line),i=t.match(/^([ \t]+)[A-Za-z_][A-Za-z0-9_]*\s*=/);if(i?.[1])return i[1]}return`${r}${dn}`}function wn(n,r){let e=n.lastIndexOf(`
8
+ `,r)+1,t=e;for(;n[t]===" "||n[t]===" ";)t+=1;return n.slice(e,t)}function Tn(n){return n.includes(`\r
9
+ `)?`\r
10
+ `:`
11
+ `}function xn(n){return n.replaceAll("\\","\\\\").replaceAll('"','\\"')}function w(n,r){let e=n[r];return Array.isArray(e)?e.at(-1):e}import{Readable as q}from"stream";import{pipeline as Hn}from"stream/promises";var En=new Set(["GET","HEAD"]);function U(n,r){let e=(n.method??"GET").toUpperCase(),t=`${r.origin}${n.url??"/"}`,i={headers:$n(n.headers),method:e};return En.has(e)||(i.body=q.toWeb(n),i.duplex="half"),new Request(t,i)}async function j(n,r){r.statusCode=n.status;for(let[e,t]of n.headers)r.setHeader(e,t);if(n.body===null){r.end();return}await Hn(q.fromWeb(n.body),r)}function $n(n){let r=new Headers;for(let[e,t]of Object.entries(n))if(typeof t=="string")r.append(e,t);else if(Array.isArray(t))for(let i of t)r.append(e,i);return r}function H(n){return{traceparent:w(n.headers,"traceparent"),"X-capture-telemetry":w(n.headers,"x-capture-telemetry")}}import{json as On}from"stream/consumers";import{integer as F,looseObject as Rn,minValue as k,number as b,object as Pn,optional as vn,pipe as W,safeParse as G,string as z,union as bn}from"valibot";var An=Pn({isolation_level:vn(z()),max_wait:W(b(),F(),k(0)),timeout:W(b(),F(),k(0))});async function Y(n,r){let e;try{e=await On(n)}catch{return d(r,{EngineNotStarted:{reason:"InvalidRequest",issues:[]}},400),null}let{issues:t,output:i,success:o}=G(An,e,{abortEarly:!0});return o?i:(d(r,{EngineNotStarted:{reason:"InvalidRequest",issues:t}},400),null)}var Mn=Rn({id:bn([z(),b()])});function J(n,r){let{output:e,success:t}=G(Mn,n);return t?e:(d(r,{EngineMalfunction:{}},500),null)}var X,Z,K;function E(){return X??=import("./engine-YTEOPVUP.js"),X}function Bn(){return K??=import("./query-plan-executor-ZS4544O3.js"),K}async function Cn(){return Z??=import("@prisma/get-platform").then(async({default:n})=>await n.getPlatformInfo()),await Z}function ge(n,r,e){n.on("POST","/invalidate",g(async(i,o)=>{p(i,r),await C(i,o)!==null&&B(o,200)},e));for(let i of["/:clientVersion/:schemaHash/graphql","/:clientVersion/:schemaHash/itx/:transactionId/graphql"])n.on("POST",i,g(async(o,a,u)=>{p(o,r);try{let s=await A(a,r,u);if(s===null)return;let c=await Q(o),l=u.transactionId,f=await s.request(c,{...H(o),"X-transaction-id":l});m(a,f)}catch(s){let{handleEngineError:c}=await E();c(s,a)}},e));for(let i of["commit","rollback"])n.on("POST",`/:clientVersion/:schemaHash/itx/:transactionId/${i}`,g(async(o,a,u)=>{p(o,r);try{let s=await A(a,r,u);if(s===null)return;let c=u.transactionId;if(c==null){d(a,{EngineMalfunction:{}},500);return}let l=`${i}Transaction`,f=await s[l](c,H(o));d(a,f)}catch(s){let{handleEngineError:c}=await E();c(s,a)}},e));n.on("PUT","/:clientVersion/:schemaHash/schema",g(async(i,o,a)=>{p(i,r);let u=await Q(i);if(!u){m(o,"Missing schema",400);return}let s=a.schemaHash;if(s==null){m(o,"Missing schema hash",400);return}let c=x.get(s);if(c==null){if(s!==await O(u)){m(o,"Schema hash mismatch",400);return}let l=await V(u,r.db.prismaORMConnectionString,r.debug);x.set(s,{base64Original:u,...l}),m(o,s);return}if(u!==c.base64Original){m(o,"Schema mismatch",400);return}m(o,s)},e)),n.on("POST","/:clientVersion/:schemaHash/transaction/start",g(async(i,o,a)=>{p(i,r);let u=await Y(i,o);if(u!==null)try{let s=await A(o,r,a);if(s===null)return;let c=await s.startTransaction(u,H(i)),l=J(c,o);if(l===null)return;let{id:f}=l,h=a.clientVersion,I=a.schemaHash;d(o,{...c,"data-proxy":{endpoint:`http://localhost:${r.port}/${h}/${I}/itx/${f}`}})}catch(s){let{handleEngineError:c}=await E();c(s,o)}},e));let t=[["GET","/connection-info"],["POST","/query"],["POST","/transaction/start"],["POST","/transaction/:transactionId/commit"],["POST","/transaction/:transactionId/query"],["POST","/transaction/:transactionId/rollback"]];for(let[i,o]of t)n.on(i,o,g(async(a,u)=>{p(a,r);let{getQueryPlanExecutorServer:s,queryPlanExecutorVersion:c}=await Bn(),l=w(a.headers,"prisma-engine-hash");if(l!=="0.0.0"&&l!==c)throw new M(400,`Using an HTTP connection string is not supported with Prisma Client version ${l??"<missing>"} by this version of \`prisma dev\`. Please either use a direct TCP connection string or upgrade your client to version ${c}.`);let f=await s(r),h=U(a,{origin:`http://localhost:${r.port}`}),I=await f.fetch(h);await j(I,u)},e))}async function A(n,r,e){let{Engine:t}=await E(),i=N(e,n);if(i===null)return null;let{base64Override:o,overrideHash:a}=i.schemas;return await t.get({base64Schema:o,clientVersion:process.env.PRISMA_DEV_FORCE_CLIENT_VERSION||e.clientVersion||"",debug:r.debug,platform:await Cn(),schemaHash:a})}export{ge as registerAccelerateRoutes};
@@ -0,0 +1 @@
1
+ import{a as r}from"./chunk-ANHBRJRZ.js";import{minLength as D,object as S,optional as B,parseJson as x,pipe as n,regex as h,safeParse as O,string as s,url as f}from"valibot";var l=/^(postgres|postgresql):\/\//,T=n(s(),x(),S({databaseUrl:n(s(),f(),h(l)),name:B(n(s(),D(1))),shadowDatabaseUrl:n(s(),f(),h(l))}));function $(o){return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(o).sort(([[e],[t]])=>e.localeCompare(t)))),"utf8").toString("base64url")}function E(o){let e=Buffer.from(o,"base64url").toString("utf8"),{issues:t,output:a,success:i}=O(T,e,{abortEarly:!0});return i?[null,a]:[t]}function j(o,e){let t=o.headers.authorization;if(!t)throw new r(401,"Missing API Key");let[a,i="",y]=t.split(" ");if(a!=="Bearer"||y)throw new r(401,"Invalid API Key");let[c,p]=E(i);if(c)throw new r(401,"Invalid API Key",{cause:c.join(", ")});let{databaseUrl:P,name:d,shadowDatabaseUrl:A}=p,u=e.name,m=e.port;if(!d)throw new r(401,`Wrong API Key; The Prisma Dev server running at port ${m} requires an API Key from a newer version of \`prisma dev\`. Check the "${u}" server's output for the updated \`DATABASE_URL\` value.`);if(d!==u)throw new r(401,`Wrong API Key; The Prisma Dev server running at port ${m} is named "${u}", but the API Key is for "${d}"`);let{hostname:I,port:w}=new URL(P),{port:g}=e.db,{hostname:b,port:K}=new URL(A),v=e.shadowDBPort;if(I!=="localhost"||Number(w)!==g||b!=="localhost"||Number(K)!==v)throw new r(401,"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 p}export{$ as a,j as b};
@@ -0,0 +1 @@
1
+ import{a as r}from"./chunk-MTR5KBPH.js";async function s(e){let{server:t}=await r(e);return t}async function A(e){return await s(e)}export{s as a,A as b};
@@ -0,0 +1 @@
1
+ var r=class extends Error{constructor(t,e,n){super(e,n);this.status=t}name="HTTPError"};export{r as a};
@@ -0,0 +1 @@
1
+ import{Buffer as r}from"buffer";function i(e,t,o=200){let n=r.from(JSON.stringify(t),"utf8");e.headersSent||(e.setHeader("Content-Type","application/json; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=o),e.end(n)}function s(e,t,o=200){let n=r.from(t,"utf8");e.headersSent||(e.setHeader("Content-Type","text/plain; charset=utf-8"),e.setHeader("Content-Length",n.byteLength),e.statusCode=o),e.end(n)}function f(e,t=204){e.headersSent||(e.statusCode=t,e.setHeader("Content-Length",0)),e.end()}function u(e,t){s(e,t.message,t.status)}export{i as a,s as b,f as c,u as d};
@@ -1 +1 @@
1
- import{checkPort as O,getPort as v,isUnsafePort as $}from"get-port-please";import{difference as x,range as k}from"remeda";var S=51214,g=51213,w=51215,T=51216,b=65535,R=0,d=-1/0;async function j(o){let{debug:r,name:e,requestedPorts:n,servers:u}=o,{portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a}=_(e,u);r&&(console.debug(`ports used by other servers: ${Object.keys(t).join(", ")}`),console.debug(`ports used by "${e}" server last time: ${JSON.stringify(a)}`));let i={databasePort:d,port:d,shadowDatabasePort:d,streamsPort:d},s=["port","databasePort","shadowDatabasePort","streamsPort"];for(let c of s){let P=await A({debug:r,portKey:c,portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a,requestedPorts:n})??await B({debug:r,pickedPorts:i,portKey:c,portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a});r&&console.debug(`Got port for "${c}": ${P}`),i[c]=P}return r&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function A(o){let{debug:r,portKey:e,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:u,requestedPorts:t}=o,{[e]:a,...i}=t;if(m(a))return await E({debug:r,otherRequestedPorts:i,portKey:e,portsUsedByOtherServers:n,requestedPort:a}),a;let s=u?.[e]??d;if(!m(s))return r&&console.debug(`No port specified for "${e}". Trying to pick a new port.`),null;let c=s in n;return c||Object.values(i).includes(s)?(r&&console.debug(`Port ${s} that was used last time for this server, ${c?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await O(s)===!1?(r&&console.debug(`Port ${s}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(r&&console.debug(`Using port ${s} for "${e}" as it was used last time and is available.`),s)}async function B(o){let{debug:r,pickedPorts:e,portKey:n,portsUsedByOtherServers:u,portsUsedByThisServerLastTime:t}=o,a=Math.max(S,g,w,T)+1,i=Object.values(e).filter(p=>p!==void 0),s=t?D(t):[],c=[...i,...Object.keys(u).map(Number),...s],P=Math.min(Math.max(a,...c)+100,b),U=x(k(a,P),c),f={port:g,databasePort:S,shadowDatabasePort:w,streamsPort:T}[n];try{return await v({port:f in u||i.includes(f)||s.includes(f)?void 0:f,ports:U})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&P+1<=b)return r&&console.debug(`Expanding port lookup to range [${P+1}, ${b}].`),await v({portRange:[P+1,b]});throw p}}function m(o){return Number.isFinite(o)&&o>=0}function _(o,r){let e={},n;for(let u of r){let{databasePort:t,port:a,shadowDatabasePort:i}=u,s=q(u);if(u.name===o){n={databasePort:t,port:a,shadowDatabasePort:i,streamsPort:s};continue}e[t]=!0,e[a]=!0,e[i]=!0,m(s)&&(e[s]=!0)}return{portsUsedByOtherServers:e,portsUsedByThisServerLastTime:n}}function q(o){let r=o.experimental?.streams?.serverUrl;if(!r)return d;try{let e=Number(new URL(r).port);return Number.isInteger(e)&&e>0?e:d}catch{return d}}function D(o){return[o.port,o.databasePort,o.shadowDatabasePort,o.streamsPort]}async function E(o){let{debug:r,otherRequestedPorts:e,portKey:n,portsUsedByOtherServers:u,requestedPort:t}=o;if(t!==R){if(t in u)throw r&&console.error(`Port ${t} was requested for "${n}", but is already used by another server.`),new h(t);if(Object.values(e).includes(t))throw r&&console.error(`Port ${t} was requested for "${n}", but also for another key.`),new y(t);if($(t))throw r&&console.error(`Port ${t} was requested for "${n}", but is unsafe.`),new l(t);if(await O(t)===!1)throw r&&console.error(`Port ${t} was requested for "${n}", but is not available.`),new l(t)}}var l=class extends Error{constructor(e){super(`Port \`${e}\` is not available.`);this.port=e}name="PortNotAvailableError"},y=class extends Error{constructor(e){super(`Port number \`${e}\` was requested twice. Please choose a different port for each service.`);this.port=e}name="PortRequestedTwiceError"},h=class extends Error{constructor(e){super(`Port number \`${e}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=e}name="PortBelongsToAnotherServerError"};export{S as a,g as b,w as c,R as d,d as e,j as f,l as g};
1
+ import{checkPort as O,getPort as v,isUnsafePort as $}from"get-port-please";import{difference as x,range as k}from"remeda";var S=51214,g=51213,w=51215,T=51216,b=65535,R=0,d=-1/0;async function j(o){let{debug:r,name:e,requestedPorts:n,servers:u}=o,{portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a}=_(e,u);r&&(console.debug(`ports used by other servers: ${Object.keys(t).join(", ")}`),console.debug(`ports used by "${e}" server last time: ${JSON.stringify(a)}`));let i={databasePort:d,port:d,shadowDatabasePort:d,streamsPort:d},s=["port","databasePort","shadowDatabasePort","streamsPort"];for(let c of s){let P=await A({debug:r,portKey:c,portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a,requestedPorts:n})??await B({debug:r,pickedPorts:i,portKey:c,portsUsedByOtherServers:t,portsUsedByThisServerLastTime:a});r&&console.debug(`Got port for "${c}": ${P}`),i[c]=P}return r&&console.debug(`Picked ports: ${JSON.stringify(i)}`),i}async function A(o){let{debug:r,portKey:e,portsUsedByOtherServers:n,portsUsedByThisServerLastTime:u,requestedPorts:t}=o,{[e]:a,...i}=t;if(m(a))return await E({debug:r,otherRequestedPorts:i,portKey:e,portsUsedByOtherServers:n,requestedPort:a}),a;let s=u?.[e]??d;if(!m(s))return r&&console.debug(`No port specified for "${e}". Trying to pick a new port.`),null;let c=s in n;return c||Object.values(i).includes(s)?(r&&console.debug(`Port ${s} that was used last time for this server, ${c?"is also used by another server":"has been requested for another service"}. Trying to pick a new port.`),null):await O(s)===!1?(r&&console.debug(`Port ${s}, that was used last time for this server, is not available. Trying to pick a new port.`),null):(r&&console.debug(`Using port ${s} for "${e}" as it was used last time and is available.`),s)}async function B(o){let{debug:r,pickedPorts:e,portKey:n,portsUsedByOtherServers:u,portsUsedByThisServerLastTime:t}=o,a=Math.max(S,g,w,T)+1,i=Object.values(e).filter(p=>p!==void 0),s=t?D(t):[],c=[...i,...Object.keys(u).map(Number),...s],P=Math.min(Math.max(a,...c)+100,b),U=x(k(a,P),c),f={port:g,databasePort:S,shadowDatabasePort:w,streamsPort:T}[n];try{return await v({port:f in u||i.includes(f)||s.includes(f)?void 0:f,ports:U})}catch(p){if(p instanceof Error&&p.name==="GetPortError"&&P+1<=b)return r&&console.debug(`Expanding port lookup to range [${P+1}, ${b}].`),await v({portRange:[P+1,b]});throw p}}function m(o){return Number.isFinite(o)&&o>=0}function _(o,r){let e={},n;for(let u of r){let{databasePort:t,port:a,shadowDatabasePort:i}=u,s=q(u);if(u.name===o){n={databasePort:t,port:a,shadowDatabasePort:i,streamsPort:s};continue}e[t]=!0,e[a]=!0,e[i]=!0,m(s)&&(e[s]=!0)}return{portsUsedByOtherServers:e,portsUsedByThisServerLastTime:n}}function q(o){let r=o.experimental?.streams?.serverUrl;if(!r)return d;try{let e=Number(new URL(r).port);return Number.isInteger(e)&&e>0?e:d}catch{return d}}function D(o){return[o.port,o.databasePort,o.shadowDatabasePort,o.streamsPort]}async function E(o){let{debug:r,otherRequestedPorts:e,portKey:n,portsUsedByOtherServers:u,requestedPort:t}=o;if(t!==R){if(t in u)throw r&&console.error(`Port ${t} was requested for "${n}", but is already used by another server.`),new h(t);if(Object.values(e).includes(t))throw r&&console.error(`Port ${t} was requested for "${n}", but also for another key.`),new y(t);if($(t))throw r&&console.error(`Port ${t} was requested for "${n}", but is unsafe.`),new l(t);if(await O(t)===!1)throw r&&console.error(`Port ${t} was requested for "${n}", but is not available.`),new l(t)}}var l=class extends Error{constructor(e){super(`Port \`${e}\` is not available.`);this.port=e}name="PortNotAvailableError"},y=class extends Error{constructor(e){super(`Port number \`${e}\` was requested twice. Please choose a different port for each service.`);this.port=e}name="PortRequestedTwiceError"},h=class extends Error{constructor(e){super(`Port number \`${e}\` belongs to another Prisma Dev server. Please choose a different port.`);this.port=e}name="PortBelongsToAnotherServerError"};export{S as a,g as b,w as c,T as d,R as e,d as f,j as g,l as h};
@@ -0,0 +1,3 @@
1
+ import{e as h,f,g as M}from"./chunk-EDFHV3AK.js";import{a as A,c as m,g as V,h as C,i as L,j as x}from"./chunk-DWY47FQV.js";import{writeFile as ae}from"fs/promises";import{join as p}from"pathe";import{check as se,lock as oe,unlock as ie}from"proper-lockfile";import{process as H}from"std-env";import{integer as K,literal as ne,minLength as k,minValue as Q,number as Z,object as P,optional as l,parseJson as de,pipe as c,safeParse as ue,string as b,url as le}from"valibot";import{setTimeout as ee}from"timers/promises";import{process as D}from"std-env";function _(r,e){if(r==null)return!1;try{return D.kill?.(r,0)??!0}catch(t){return e&&console.error(`Error checking if process with PID ${r} exists:`,t),!1}}async function J(r,e){if(!D.kill)return!1;try{D.kill(r,"SIGTERM")}catch(a){return e&&console.error(`Error killing process with PID ${r}:`,a),!1}let t=0;do{if(!_(r,e))return!0;await ee(100)}while(++t<50);try{return D.kill(r,"SIGKILL")}catch(a){return e&&console.error(`Error forcefully killing process with PID ${r}:`,a),!1}}import{join as j}from"pathe";var te="prisma-wal",ye="prisma-queries";function re(){return j(A.data,"durable-streams")}function Y(r){return j(re(),r)}function xe(r,e=te){return new URL(`/v1/stream/${encodeURIComponent(e)}`,r).toString()}var S=c(b(),le()),F=P({connectionString:S,prismaORMConnectionString:l(S),terminalCommand:l(b())}),G=P({url:S}),B=P({serverUrl:S,sqlitePath:c(b(),k(1)),streamName:c(b(),k(1)),url:S}),ce=P({queryInsights:l(B),streams:l(B)}),I=c(Z(),K(),Q(1)),me=P({database:F,http:G,ppg:G,shadowDatabase:F}),he=P({databasePort:I,experimental:l(ce),exports:l(me),name:c(b(),k(1)),pid:l(c(Z(),K(),Q(0))),port:I,shadowDatabasePort:I,version:ne("1")}),O=Symbol("initialize"),E="default",pe=new Set(["durable-streams"]),d=class{_databasePort;databaseConnectTimeoutMillis;databaseIdleTimeoutMillis;debug;dryRun;name;persistenceMode;pid;shadowDatabaseConnectTimeoutMillis;shadowDatabaseIdleTimeoutMillis;_port;_shadowDatabasePort;_streamsPort;constructor(e){this._databasePort=e.databasePort??f,this.databaseConnectTimeoutMillis=e.databaseConnectTimeoutMillis??6e4,this.databaseIdleTimeoutMillis=e.databaseIdleTimeoutMillis??1/0,this.debug=e.debug??!1,this.dryRun=e.dryRun??!1,this.name=e.name??E,this.persistenceMode=e.persistenceMode,this.pid=e.pid??H.pid,this.shadowDatabaseConnectTimeoutMillis=e.shadowDatabaseConnectTimeoutMillis??this.databaseConnectTimeoutMillis,this.shadowDatabaseIdleTimeoutMillis=e.shadowDatabaseIdleTimeoutMillis??this.databaseIdleTimeoutMillis,this._port=e.port??f,this._shadowDatabasePort=e.shadowDatabasePort??f,this._streamsPort=e.streamsPort??f}static async createExclusively(e){let t=e?.dryRun!==!0&&e?.persistenceMode==="stateful"?new g(e):new R(e);return await t[O](),t}static async fromServerDump(e){let{debug:t,name:a=E}=e??{},o=m(a),i=g.getServerDumpPath(o),s=await V(i);if(s==null)return t&&console.debug(`[State] No server dump file found at: ${i}`),null;t&&(console.debug(`[State] server dump file found at "${i}":`),console.debug(s));let{issues:n,output:u,success:v}=ue(c(b(),de(),he),s);if(!v)throw t&&console.debug(`[State] Invalid server dump file at "${i}":
2
+ ${JSON.stringify(n,null,2)}`),new Error(`Invalid Prisma Dev state for "${a}".`);return new g({databasePort:u.databasePort,debug:t,dryRun:!1,name:a,pid:u.pid,port:u.port,serverDump:u,shadowDatabasePort:u.shadowDatabasePort})}static async scan(e){let{debug:t,globs:a}=e??{},o=p(m(E),"..");t&&console.debug(`[State] scanning for server states in: ${o}`);let i=(await L(o,a)).filter(s=>!pe.has(s));return t&&console.debug(`[State] found server names: ${JSON.stringify(i)}`),await Promise.all(i.map(s=>z(s,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}get streamsPort(){return this._streamsPort}set shadowDatabasePort(e){this.#t("shadowDatabasePort",e)}#t(e,t){if(t<0||!Number.isInteger(t))throw new Error(`Invalid port number: ${t}`);let a=`_${e}`;if(this[a]!==h&&this[a]!==t)throw new Error(`\`${e}\` is already set to ${this[a]}, cannot change it to ${t}`);this[a]=t}},R=class extends d{constructor(e){super({...e,databasePort:e?.databasePort||h,persistenceMode:"stateless",port:e?.port||h,shadowDatabasePort:e?.shadowDatabasePort||h,streamsPort:e?.streamsPort||h})}get databaseDumpPath(){return"<DUMP_PATH>"}get pgliteDataDirPath(){return"memory://"}async[O](){let e;try{e=await d.scan({debug:this.debug,onlyMetadata:!0})}catch(a){this.debug&&console.warn("[State] failed to scan for existing servers, assuming filesystem does not exist or other reasons.",a),e=[]}let t=await M({debug:this.debug,name:this.dryRun?this.name:"",requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,this._streamsPort=t.streamsPort}async close(){}async writeServerDump(){}},g=class r extends d{#t;#e;#a;#o;#i;#s;#r;constructor(e){super({...e,persistenceMode:"stateful"}),this.#s=!1,this.#e=m(this.name),this.#t=p(this.#e,"db_dump.bak"),this.#a=p(this.#e,".lock"),this.#o=p(this.#e,".pglite"),this.#r=e?.serverDump??null,this.#i=r.getServerDumpPath(this.#e)}static getServerDumpPath(e){return p(e,"server.json")}get databaseDumpPath(){return this.#t}get exports(){return this.#r?.exports}get experimental(){return this.#r?.experimental}get pgliteDataDirPath(){return this.#o}async[O](){await C(this.#e),this.debug&&console.debug(`[State] using data directory: ${this.#e}`);try{await oe(this.#e,{lockfilePath:this.#a}),this.debug&&console.debug(`[State] obtained lock on: ${this.#e}`);let e=await d.scan({debug:this.debug,onlyMetadata:!0}),t=await M({debug:this.debug,name:this.name,requestedPorts:{databasePort:this.databasePort,port:this.port,shadowDatabasePort:this.shadowDatabasePort,streamsPort:this.streamsPort},servers:e});this._databasePort=t.databasePort,this._port=t.port,this._shadowDatabasePort=t.shadowDatabasePort,this._streamsPort=t.streamsPort,await this.writeServerDump()}catch(e){throw e instanceof Error&&"code"in e&&e.code==="ELOCKED"?new $(this):e}}async close(){if(!this.#s)try{await ie(this.#e,{lockfilePath:this.#a}),this.#s=!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,t){this.#r={name:this.name,version:"1",pid:H.pid,port:this.port,databasePort:this.databasePort,experimental:t,shadowDatabasePort:this.shadowDatabasePort,exports:e},await ae(this.#i,`${JSON.stringify(this.#r,null,2)}
3
+ `,{encoding:"utf-8"})}};async function Ve(r,e){await Pe(r,e);let t=typeof r=="string"?r:r.name,a=m(t);await x(a),await x(Y(t))}async function z(r,e){let{debug:t,onlyMetadata:a}=e||{},o=typeof r=="string"?r:r.name,i=typeof r!="string"?r:void 0,s={databasePort:i?.databasePort??-1,experimental:i?.experimental,exports:i?.exports,name:o,pid:i?.pid,port:i?.port??-1,shadowDatabasePort:i?.shadowDatabasePort??-1,version:"1"};try{let n=i||await d.fromServerDump({debug:t,name:o});if(!n)return t&&console.debug(`[State] no server state found for name: ${o}`),{...s,status:"no_such_server"};s.databasePort=n.databasePort,s.experimental=n.experimental,s.exports=n.exports,s.pid=n.pid,s.port=n.port,s.shadowDatabasePort=n.shadowDatabasePort;let{exports:u,pid:v}=n;if(a)return{...s,status:"unknown"};if(!_(v,t))return t&&console.debug(`[State] server state for "${o}" has no running process with PID: ${v}`),{...s,status:"not_running"};let N=m(o);try{if(!await se(N,{lockfilePath:p(N,".lock")}))return t&&console.debug(`[State] server state for "${o}" is not locked, indicating it is not running.`),{...s,status:"not_running"}}catch(X){t&&console.error(`[State] server state for "${o}" failed to check lock:`,X)}if(!u)return{...s,status:"starting_up"};let{http:W}=u,w=await fetch(`${W.url}/health`,{headers:{connection:"close"}});if(!w.ok)return t&&console.debug(`[State] server state for "${o}" is not live: ${JSON.stringify(w)}`),{...s,status:"not_running"};let y=await w.json();return y.name!==r?(t&&console.debug(`[State] server state for "${o}" has mismatched health response: ${JSON.stringify(y)}`),{...s,status:"unknown"}):(t&&console.debug(`[State] server state for "${r}" is live: ${JSON.stringify(y)}`),{...s,status:"running"})}catch(n){return t&&console.error(`[State] failed to get server status for "${o}":`,n),{...s,status:"error"}}}function be(r){let{status:e}=r;return e==="running"||e==="starting_up"}async function Pe(r,e){let{pid:t,...a}=typeof r=="string"?await z(r,{debug:e}):r;if(!be(a))return!1;let o=await d.fromServerDump({debug:e,name:a.name});if(t==null){e&&console.debug(`[State] No PID found for server "${a.name}" to kill.`);try{await o?.close()}catch{}return!1}let i=await J(t,e);try{await o?.close()}catch{}return i}var T=class extends Error{name="ServerStateAlreadyExistsError";constructor(e){super(`A Prisma Dev server with the name "${e}" is already running.`)}},$=class extends T{#t;name="ServerAlreadyRunningError";constructor(e){super(e.name),this.#t=e}get server(){return d.fromServerDump({debug:this.#t.debug,name:this.#t.name})}};export{te as a,ye as b,re as c,Y as d,xe as e,d as f,Ve as g,z as h,be as i,Pe as j,T as k,$ as l};
@@ -0,0 +1 @@
1
+ import{existsSync as u,readFileSync as D}from"fs";import{copyFile as b,mkdir as B,readFile as d}from"fs/promises";import{createRequire as z}from"module";import{dirname as E}from"path";import{fileURLToPath as r,pathToFileURL as A}from"url";var v=z(import.meta.url),T=["initdb.wasm","pglite.data","pglite.wasm"],p="pglite-seed.tar.gz",w={amcheck:"amcheck.tar.gz",bloom:"bloom.tar.gz",btree_gin:"btree_gin.tar.gz",btree_gist:"btree_gist.tar.gz",citext:"citext.tar.gz",cube:"cube.tar.gz",dict_int:"dict_int.tar.gz",dict_xsyn:"dict_xsyn.tar.gz",earthdistance:"earthdistance.tar.gz",file_fdw:"file_fdw.tar.gz",fuzzystrmatch:"fuzzystrmatch.tar.gz",hstore:"hstore.tar.gz",intarray:"intarray.tar.gz",isn:"isn.tar.gz",lo:"lo.tar.gz",ltree:"ltree.tar.gz",pageinspect:"pageinspect.tar.gz",pg_buffercache:"pg_buffercache.tar.gz",pg_freespacemap:"pg_freespacemap.tar.gz",pg_surgery:"pg_surgery.tar.gz",pg_trgm:"pg_trgm.tar.gz",pg_visibility:"pg_visibility.tar.gz",pg_walinspect:"pg_walinspect.tar.gz",seg:"seg.tar.gz",tablefunc:"tablefunc.tar.gz",tcn:"tcn.tar.gz",tsm_system_rows:"tsm_system_rows.tar.gz",tsm_system_time:"tsm_system_time.tar.gz",unaccent:"unaccent.tar.gz",uuid_ossp:"uuid-ossp.tar.gz",vector:"vector.tar.gz"},U=[...T.map(e=>({fileName:e,kind:"core",name:e})),{fileName:p,kind:"core",name:p},...Object.entries(w).map(([e,t])=>({fileName:t,kind:"extension",name:e}))],f=new Map,P=Symbol.for("@prisma/dev/bundled-pglite-runtime-asset-sources"),c=null;async function Z(e){let t=a(e),n=r(t);await B(n,{recursive:!0});let s=[];for(let i of x()){let g=new URL(i.fileName,t),m=r(g);await b(i.sourcePath,m),s.push({...i,destinationPath:m})}return s}function x(){let e=L(),t=a(new URL("./runtime-assets/",import.meta.url));return U.map(n=>({...n,sourcePath:r(l(n.fileName,e,t))}))}async function H(){await W();let e=h();if(e)return await M(e),await G(e);let t=N(),n=t.href,s=f.get(n);return s||(s=I(t),f.set(n,s)),await s}function Q(e){let t=globalThis;t[P]={extensions:Object.fromEntries(Object.entries(e.extensions).map(([n,s])=>[n,o(s)])),fsBundle:o(e.fsBundle),initdbWasm:o(e.initdbWasm),loadDataDir:o(e.loadDataDir),wasmModule:o(e.wasmModule)}}function o(e,t=import.meta.url){return e instanceof URL?e:/^(?:https?:|data:|file:)/.test(e)?new URL(e):e.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(e)?A(e):new URL(e,t)}async function G(e){let t=`bundled:${e.wasmModule.href}:${e.fsBundle.href}`,n=f.get(t);return n||(n=k(e),f.set(t,n)),await n}async function I(e){let t=a(new URL("./runtime-assets/",import.meta.url)),[n,s,i]=await Promise.all([d(l("pglite.data",e,t)),d(l(p,e,t)),d(l("pglite.wasm",e,t))]),g=_();return{extensions:Object.fromEntries(Object.entries(w).map(([m,S])=>[m,l(S,e,t)])),fsBundle:new Blob([Uint8Array.from(n)]),loadDataDir:new Blob([Uint8Array.from(s)]),wasmModule:await g.compile(i)}}async function k(e){let[t,n,s]=await Promise.all([R(e.fsBundle),R(e.loadDataDir),R(e.wasmModule)]),i=_();return{extensions:e.extensions,fsBundle:new Blob([Uint8Array.from(t)]),loadDataDir:new Blob([Uint8Array.from(n)]),wasmModule:await i.compile(s)}}async function M(e){if(e.initdbWasm.protocol!=="file:")return;let t=new URL("initdb.wasm",a(new URL("./",e.initdbWasm))),n=r(t);u(n)||await b(r(e.initdbWasm),n)}function a(e){return e instanceof URL?y(e):y(A(e))}function y(e){return e.href.endsWith("/")?e:new URL(`${e.href}/`)}function L(){let e=v.resolve("@electric-sql/pglite");return a(E(e))}function N(){let e=a(new URL("./",import.meta.url));if(O(e))return e;if(C())return L();throw new Error("Unable to locate PGlite runtime assets. If you bundled @prisma/dev, copy them next to the bundle with copyPrismaDevRuntimeAssets().")}function O(e){return U.every(t=>u(r(new URL(t.fileName,e))))}function h(){return globalThis[P]??null}async function W(){!F()||h()||(c||(c=import("./runtime-assets-manifest.bun.js").then(()=>{}).catch(e=>{throw c=null,e})),await c)}function C(){let e=r(new URL("../package.json",import.meta.url));if(!u(e))return!1;try{return JSON.parse(D(e,"utf8")).name==="@prisma/dev"}catch{return!1}}function F(){return typeof globalThis.Bun<"u"}function _(){let e=globalThis.WebAssembly;if(!e)throw new Error("WebAssembly is not available in this runtime.");return e}async function R(e){if(e.protocol==="file:")return await d(e);let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch runtime asset ${e.href}: ${t.status} ${t.statusText}`);return new Uint8Array(await t.arrayBuffer())}function l(e,t,n){let s=new URL(e,t);if(u(r(s)))return s;if(n){let i=new URL(e,n);if(u(r(i)))return i}return s}export{Z as a,x as b,H as c,Q as d,o as e};
@@ -0,0 +1 @@
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};
@@ -0,0 +1,107 @@
1
+ import{c as I}from"./chunk-KWCQYPJI.js";import{h as T}from"./chunk-EDFHV3AK.js";import{d as L,f as O}from"./chunk-DWY47FQV.js";import{createConnection as ke,createServer as qe}from"net";import{join as Fe}from"path";import{filename as Ue}from"pathe/utils";import{performance as W}from"perf_hooks";import{protocol as we}from"@electric-sql/pglite";import{Buffer as de}from"buffer";var C=500,Q=/(?:"[^"]+"|`[^`]+`|\[[^\]]+\]|\w+)/,me=new RegExp(`(?:${Q.source}\\.)*${Q.source}`),pe=new RegExp(`(?:FROM|JOIN|UPDATE|INTO|TABLE)\\s+(${me.source})`,"gi"),ge=/"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+)/g,$=/prismaQuery='([^']+)'/,fe=new Set([S(`
2
+ select b.oid, b.typarray
3
+ from pg_catalog.pg_type a
4
+ left join pg_catalog.pg_type b on b.oid = a.typelem
5
+ where a.typcategory = $1
6
+ group by b.oid, b.typarray
7
+ order by b.oid
8
+ `),S('GRANT "pg_write_all_data" TO "prisma_application"'),S("SELECT SUM(reads)::BIGINT AS reads, SUM(writes)::BIGINT AS writes, SUM(COALESCE(extends, $1))::BIGINT AS extends FROM pg_stat_io"),S("SELECT pg_database_size(current_database())::BIGINT, SUM(pg_total_relation_size(relid))::BIGINT AS pg_total_relation_size FROM pg_stat_user_tables"),S("SELECT COUNT(*) AS cnt FROM pg_stat_activity WHERE pid <> pg_backend_pid() and xact_start notnull")]),ye=[/^BEGIN\b/i,/^COMMIT\b/i,/^ROLLBACK\b/i,/^SAVEPOINT\b/i,/^RELEASE\b/i,/^SET\b/i,/^SHOW\b/i,/^DISCARD\b/i,/^DEALLOCATE\b/i,/^CLOSE\b/i,/^CREATE EXTENSION\b/i,/^WITH state_assign\b/i];function Ze(){return{generatedAt:Date.now(),queries:[]}}function S(e){return e.replace(/\s+/g," ").trim()}function G(e){return U(S(e))}function k(e){if(!e?.action||!e.model&&/raw/i.test(e.action))return null;let t=e.payload?U(JSON.stringify(e.payload)):"0";return`${e.model??""}.${e.action}:${t}`}function Ee(e){let t=new Set;for(let r of e.matchAll(pe)){let n=r[1];if(!n)continue;let a;for(let s of n.matchAll(ge))a=s[1]??s[2]??s[3]??s[4];a&&!a.startsWith("pg_")&&t.add(a)}return Array.from(t)}function Se(e){return fe.has(e)?!0:ye.some(t=>t.test(e))}function q(e){if(Se(S(e)))return null;let t=Ee(e);return t.length===0&&/\bpg_\w+/i.test(e)?null:t}function N(e){if(Array.isArray(e))return e.map(N);if(e!==null&&typeof e=="object"){let t=e;return t.$type==="Param"?"<<redacted>>":Object.fromEntries(Object.entries(t).map(([r,n])=>[r,N(n)]))}return e}function F(e){let t=e.match($);if(!t?.[1])return{cleanedSql:S(e),prismaQueryInfo:null};let r=e.replace($,"");r=r.replace(/,\s*,/g,",").replace(/\/\*\s*,/g,"/*").replace(/,\s*\*\//g,"*/").replace(/\/\*\s*\*\//g,"").replace(/\s+/g," ").trim();let n=decodeURIComponent(t[1]),a=n.indexOf(":");if(a===-1)return{cleanedSql:r,prismaQueryInfo:{action:n,isRaw:!0}};let s=n.slice(0,a),d=n.slice(a+1),o=s.indexOf("."),u=o===-1?void 0:s.slice(0,o),c=o===-1?s:s.slice(o+1);if(!c)return{cleanedSql:r,prismaQueryInfo:null};let l;try{l=N(JSON.parse(de.from(d,"base64url").toString("utf8")))}catch{l=void 0}return{cleanedSql:r,prismaQueryInfo:{action:c,isRaw:!1,model:u,payload:l}}}function et(e,t={}){let r=new Set(t.excludeApplications??[]),n=be(t.limit),a=typeof t.since=="number"&&Number.isFinite(t.since)?t.since:null,s=new Map;for(let o of e){if(o.applicationName&&r.has(o.applicationName))continue;let u=Date.parse(o.timestamp);if(!Number.isFinite(u))continue;let c=`${o.queryId}:${o.groupKey??""}`,l=s.get(c);if(!l){s.set(c,{count:1,duration:o.durationMs,groupKey:o.groupKey,id:c,lastSeen:u,maxDurationMs:o.durationMs,minDurationMs:o.durationMs,prismaQueryInfo:o.prismaQueryInfo,query:o.query,queryId:o.queryId,reads:o.reads,rowsReturned:o.rowsReturned,tables:o.tables,totalDurationMs:o.durationMs});continue}l.count+=1,l.lastSeen=Math.max(l.lastSeen,u),l.maxDurationMs=Math.max(l.maxDurationMs??o.durationMs,o.durationMs),l.minDurationMs=Math.min(l.minDurationMs??o.durationMs,o.durationMs),l.reads+=o.reads,l.rowsReturned+=o.rowsReturned,l.totalDurationMs+=o.durationMs,l.duration=l.totalDurationMs/l.count,!l.prismaQueryInfo&&o.prismaQueryInfo&&(l.prismaQueryInfo=o.prismaQueryInfo),l.tables.length===0&&o.tables.length>0&&(l.tables=o.tables)}let d=Array.from(s.values()).filter(o=>a===null||o.lastSeen>=a).sort((o,u)=>u.lastSeen-o.lastSeen).slice(0,n).map(({totalDurationMs:o,...u})=>u);return{generatedAt:Date.now(),queries:d}}function be(e){return typeof e=="number"&&Number.isInteger(e)&&Number.isSafeInteger(e)&&e>0?Math.min(e,C):C}function U(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)&4294967295;return(t>>>0).toString(36)}var P=new WeakMap;function H(e){let t=P.get(e);if(t&&!t.closed)return t.bridge;let r=Pe(e),n={bridge:{close:()=>(n.closed||(n.closed=!0,n.sessions.clear(),n.subscribers.clear(),n.queryQueue.enqueue=n.originalEnqueue,n.queryQueue.clearQueueForHandler=n.originalClearQueueForHandler,P.delete(e)),Promise.resolve()),subscribe:a=>(n.subscribers.add(a),()=>{n.subscribers.delete(a)})},closed:!1,originalClearQueueForHandler:r.clearQueueForHandler.bind(r),originalEnqueue:r.enqueue.bind(r),queryQueue:r,sessions:new Map,subscribers:new Set};return r.clearQueueForHandler=a=>{n.sessions.delete(a),n.originalClearQueueForHandler(a)},r.enqueue=async(a,s,d)=>{let o=he(n,a),u=Ne(s);Te(o,u);let c=Ie(o,u);if(!c)return await n.originalEnqueue(a,s,d);let l={commandTags:[],dataRowCount:0},f=new we.Parser,i=W.now(),m=await n.originalEnqueue(a,s,b=>{f.parse(b,ce=>{Me(l,ce)}),d(b)}),g=Math.max(0,W.now()-i);return Be(n,{applicationName:c.applicationName,durationMs:g,query:c.query,responseStats:l}),m},P.set(e,n),n.bridge}async function K(e){await P.get(e)?.bridge.close()}function Pe(e){let t=e.queryQueue;if(!t||typeof t.enqueue!="function"||typeof t.clearQueueForHandler!="function")throw new Error("PGLiteSocketServer query queue is unavailable for query insights capture");return t}function he(e,t){let r=e.sessions.get(t);if(r)return r;let n={applicationName:null,portals:new Map,statements:new Map};return e.sessions.set(t,n),n}function Te(e,t){if(t)switch(t.kind){case"startup":e.applicationName=t.applicationName;return;case"parse":e.statements.set(t.statementName,t.query);return;case"bind":{let r=e.statements.get(t.statementName);r&&e.portals.set(t.portalName,r);return}case"close":t.target==="portal"?e.portals.delete(t.name):e.statements.delete(t.name);return;default:return}}function Ie(e,t){if(!t)return null;if(t.kind==="query")return{applicationName:e.applicationName,query:t.query};if(t.kind==="execute"){let r=e.portals.get(t.portalName);return r?{applicationName:e.applicationName,query:r}:null}return null}function Ne(e){let t=Buffer.from(e);if(t.length<4)return null;let r=t.readInt32BE(0);if(t.length>=8&&r===t.length){let a=t.readInt32BE(4);if(a===196608||a===196608)return Re(t)}if(t.length<5)return null;switch(String.fromCharCode(t[0]??0)){case"Q":return _e(t);case"P":return xe(t);case"B":return Ae(t);case"E":return De(t);case"C":return ve(t);default:return null}}function Re(e){let t=8,r=null;for(;t<e.length-1;){let n=E(e,t);if(!n||n.value==="")break;t=n.nextOffset;let a=E(e,t);if(!a)break;t=a.nextOffset,n.value==="application_name"&&(r=a.value)}return{applicationName:r,kind:"startup"}}function _e(e){let t=E(e,5);return t?{kind:"query",query:t.value}:null}function xe(e){let t=E(e,5);if(!t)return null;let r=E(e,t.nextOffset);return r?{kind:"parse",query:r.value,statementName:t.value}:null}function Ae(e){let t=E(e,5);if(!t)return null;let r=E(e,t.nextOffset);return r?{kind:"bind",portalName:t.value,statementName:r.value}:null}function De(e){let t=E(e,5);return t?{kind:"execute",portalName:t.value}:null}function ve(e){if(e.length<7)return null;let t=e[5];if(t===void 0)return null;let r=E(e,6);return r?{kind:"close",name:r.value,target:t===80?"portal":"statement"}:null}function E(e,t){let r=e.indexOf(0,t);return r===-1?null:{nextOffset:r+1,value:e.toString("utf8",t,r)}}function Me(e,t){if(t.name==="dataRow"){e.dataRowCount+=1;return}t.name==="commandComplete"&&typeof t.text=="string"&&t.text.length>0&&e.commandTags.push(t.text)}function Be(e,t){let r=F(t.query),n=q(r.cleanedSql);if(!n)return;let a=G(r.cleanedSql),s={applicationName:t.applicationName,durationMs:t.durationMs,groupKey:k(r.prismaQueryInfo),prismaQueryInfo:r.prismaQueryInfo,query:r.cleanedSql,queryId:a,reads:0,rowsReturned:Le(t.responseStats),tables:n,timestamp:new Date().toISOString()};for(let d of e.subscribers)d([s])}function Le(e){let t=e.commandTags.reduce((r,n)=>r+Oe(n),0);return Math.max(t,e.dataRowCount)}function Oe(e){let t=e.trim().split(/\s+/).at(-1);return!t||!/^\d+$/.test(t)?0:Number(t)}import{protocol as J}from"@electric-sql/pglite";var y="_prisma_dev_wal",A="events",X="install_all_triggers",Y="capture_event",z="prisma_dev_wal_capture",w=new WeakMap,Ce=new Set(["ALTER","COMMIT","COPY","CREATE","DELETE","DROP","INSERT","MERGE","TRUNCATE","UPDATE"]);async function D(e,t){let r=w.get(e);if(r&&!r.closed)return r.bridge;let n=e.execProtocolRaw.bind(e),a=e.execProtocolRawStream.bind(e),s={bridge:{close:async()=>{s.closed||(s.closed=!0,s.subscribers.clear(),e.execProtocolRaw===d&&(e.execProtocolRaw=n),e.execProtocolRawStream===o&&(e.execProtocolRawStream=a),await s.pollPromise,w.delete(e))},poll:async()=>{await x(s,e)},subscribe:u=>(s.subscribers.add(u),()=>{s.subscribers.delete(u)})},closed:!1,ensureInfrastructurePromise:null,pendingPoll:!1,pollPromise:null,subscribers:new Set,suppressDepth:0},d=async(u,c)=>{let l=await n(u,c);return!s.closed&&s.suppressDepth===0&&V(l)&&x(s,e),l},o=async(u,c)=>{let l=[],f=new J.Parser,i=c?.onRawData;await a(u,{...c,onRawData:m=>{f.parse(m,g=>{l.push(g)}),i?.(m)}}),!s.closed&&s.suppressDepth===0&&v(l)&&x(s,e)};return e.execProtocolRaw=d,e.execProtocolRawStream=o,w.set(e,s),await Z(s,e),s.bridge}async function j(e){let t=w.get(e);t&&await t.bridge.close()}function v(e){for(let t of e){if(t.name!=="commandComplete"||typeof t.text!="string")continue;let r=t.text.split(/\s+/,1)[0]?.toUpperCase();if(r&&Ce.has(r))return!0}return!1}function V(e){if(e.length===0)return!1;let t=[];return new J.Parser().parse(e,n=>{t.push(n)}),v(t)}async function Z(e,t){e.ensureInfrastructurePromise??=M(e,t,async()=>{await t.exec(`CREATE SCHEMA IF NOT EXISTS "${y}"`),await t.exec(`
9
+ CREATE TABLE IF NOT EXISTS "${y}"."${A}" (
10
+ id BIGSERIAL PRIMARY KEY,
11
+ txid BIGINT NOT NULL DEFAULT txid_current(),
12
+ schema_name TEXT NOT NULL,
13
+ table_name TEXT NOT NULL,
14
+ op TEXT NOT NULL,
15
+ row_data JSONB,
16
+ old_row_data JSONB,
17
+ created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
18
+ )
19
+ `),await t.exec(`
20
+ CREATE OR REPLACE FUNCTION "${y}"."${Y}"()
21
+ RETURNS trigger
22
+ LANGUAGE plpgsql
23
+ AS $$
24
+ BEGIN
25
+ IF TG_TABLE_SCHEMA = '${y}' THEN
26
+ RETURN COALESCE(NEW, OLD);
27
+ END IF;
28
+
29
+ INSERT INTO "${y}"."${A}" (
30
+ txid,
31
+ schema_name,
32
+ table_name,
33
+ op,
34
+ row_data,
35
+ old_row_data
36
+ )
37
+ VALUES (
38
+ txid_current(),
39
+ TG_TABLE_SCHEMA,
40
+ TG_TABLE_NAME,
41
+ lower(TG_OP),
42
+ CASE WHEN TG_OP IN ('INSERT', 'UPDATE') THEN to_jsonb(NEW) ELSE NULL END,
43
+ CASE WHEN TG_OP IN ('UPDATE', 'DELETE') THEN to_jsonb(OLD) ELSE NULL END
44
+ );
45
+
46
+ RETURN COALESCE(NEW, OLD);
47
+ END;
48
+ $$;
49
+ `),await t.exec(`
50
+ CREATE OR REPLACE FUNCTION "${y}"."${X}"()
51
+ RETURNS void
52
+ LANGUAGE plpgsql
53
+ AS $$
54
+ DECLARE
55
+ target REGCLASS;
56
+ BEGIN
57
+ FOR target IN
58
+ SELECT c.oid::regclass
59
+ FROM pg_class AS c
60
+ JOIN pg_namespace AS n ON n.oid = c.relnamespace
61
+ WHERE c.relkind IN ('r', 'p')
62
+ AND n.nspname NOT IN ('${y}', 'information_schema', 'pg_catalog')
63
+ AND n.nspname NOT LIKE 'pg_temp_%'
64
+ AND n.nspname NOT LIKE 'pg_toast%'
65
+ LOOP
66
+ IF EXISTS (
67
+ SELECT 1
68
+ FROM pg_trigger
69
+ WHERE tgrelid = target
70
+ AND tgname = '${z}'
71
+ ) THEN
72
+ CONTINUE;
73
+ END IF;
74
+
75
+ EXECUTE format(
76
+ 'CREATE TRIGGER %I AFTER INSERT OR UPDATE OR DELETE ON %s FOR EACH ROW EXECUTE FUNCTION "${y}"."${Y}"()',
77
+ '${z}',
78
+ target::text
79
+ );
80
+ END LOOP;
81
+ END;
82
+ $$;
83
+ `),await ee(e,t)}),await e.ensureInfrastructurePromise}async function ee(e,t){await M(e,t,async()=>{await t.query(`SELECT "${y}"."${X}"()`)})}async function Qe(e,t){await Z(e,t),await ee(e,t);let r=await M(e,t,async()=>await t.query(`
84
+ WITH drained AS (
85
+ DELETE FROM "${y}"."${A}"
86
+ RETURNING txid, schema_name, table_name, op, row_data, old_row_data, id
87
+ )
88
+ SELECT txid, schema_name, table_name, op, row_data, old_row_data
89
+ FROM drained
90
+ ORDER BY id
91
+ `));if(r.rows.length===0||e.subscribers.size===0)return;let n=r.rows.map($e);for(let a of e.subscribers)queueMicrotask(()=>{if(!e.closed&&e.subscribers.has(a))try{a(n)}catch(s){console.error("[WAL bridge] subscriber failed",s)}})}async function x(e,t){if(!e.closed){if(e.pollPromise){e.pendingPoll=!0,await e.pollPromise;return}e.pollPromise=(async()=>{do e.pendingPoll=!1,await Qe(e,t);while(e.pendingPoll&&!e.closed)})().finally(()=>{e.pollPromise=null}),await e.pollPromise}}async function M(e,t,r){e.suppressDepth+=1;try{return await r()}finally{e.suppressDepth-=1,e.suppressDepth===0&&!e.closed&&w.get(t)!==e&&(e.closed=!0)}}function $e(e){return{oldRecord:e.old_row_data,record:e.row_data,schema:e.schema_name,table:e.table_name,txid:String(e.txid),type:Ge(e.op)}}function Ge(e){switch(e.toLowerCase()){case"delete":return"delete";case"insert":return"insert";case"update":return"update";default:throw new Error(`Unsupported WAL bridge operation: ${e}`)}}var We=10,re="127.0.0.1",ne=128*1024*1024,ae=["-c","shared_buffers=16MB","-c","temp_buffers=1MB","-c","work_mem=1MB","-c","maintenance_work_mem=16MB","-c","wal_buffers=1MB"],p={connectionLimit:We,connectTimeout:0,database:"template1",maxIdleConnectionLifetime:0,password:"postgres",poolTimeout:0,socketTimeout:0,sslMode:"disable",username:"postgres"},He=`postgres://${p.username}:${p.password}@localhost`,B=new URLSearchParams({sslmode:p.sslMode}),oe=new URLSearchParams({...Object.fromEntries(B.entries()),connection_limit:String(p.connectionLimit),connect_timeout:String(p.connectTimeout),max_idle_connection_lifetime:String(p.maxIdleConnectionLifetime),pool_timeout:String(p.poolTimeout),socket_timeout:String(p.socketTimeout)});async function se(e){let{rows:t}=await e.query("SELECT EXISTS(SELECT 1 FROM pg_roles WHERE rolname = 'postgres') AS exists");t[0]?.exists?await e.exec(`ALTER ROLE ${p.username} WITH LOGIN SUPERUSER PASSWORD '${p.password}'`):await e.exec(`CREATE ROLE ${p.username} WITH LOGIN SUPERUSER PASSWORD '${p.password}'`),await e.exec(`SET ROLE ${p.username}`)}async function bt(e,t){if(e==="shadow_database"&&!t.dryRun)return await Ke(t);let r=e==="database"?t.databasePort:t.shadowDatabasePort;return t.dryRun?le(e,t,{db:null,port:r,server:null}):await ie(e,t,{port:r,updateServerStatePort:!0})}async function Ke(e,t=async()=>await ie("shadow_database",e,{port:0,updateServerStatePort:!1})){let{debug:r}=e,n=null,a=null,s=!1,d=new Set,o=qe(c),u=await Ye(o,e.shadowDatabasePort);return e.shadowDatabasePort=u,r&&console.debug(`[shadow_database] lazy proxy listening on port ${u}`),{...p,attachWalEventBridge:()=>Promise.reject(new Error("WAL bridge is only available for the primary database server")),attachQueryInsightsBridge:()=>Promise.reject(new Error("Query insights are only available for the primary database server")),close:async()=>{s=!0;for(let m of d)m.destroy();d.clear();let i=[];try{await ze(o),r&&console.debug(`[shadow_database] lazy proxy stopped on port ${u}`)}catch(m){console.error("[shadow_database] lazy proxy stop error",m),i.push(m)}try{await a?.catch(()=>null),await n?.close()}catch(m){console.error("[shadow_database] backend close error",m),i.push(m)}if(i.length>0)throw new AggregateError(i,"Failed to close shadow_database properly")},connectionString:h(u,B),dump:async()=>{},getPrimaryKeyColumns:()=>Promise.reject(new Error("Primary key resolution is only available for the primary database server")),port:u,prismaORMConnectionString:h(u,oe),terminalCommand:`PGPASSWORD=${p.password} PGSSLMODE=${p.sslMode} psql -h localhost -p ${u} -U ${p.username} -d ${p.database}`};function c(i){d.add(i);let m=()=>{d.delete(i)};i.once("close",m),i.once("error",m),i.pause(),l(i)}async function l(i){try{let m=await f();if(s){i.destroy();return}let g=ke({host:re,port:m.port});d.add(g);let b=()=>{d.delete(g)};g.once("close",b),g.once("error",b),i.once("close",()=>g.destroy()),i.once("error",()=>g.destroy()),g.once("error",()=>i.destroy()),g.once("connect",()=>{r&&console.debug(`[shadow_database] proxying connection to lazy backend on port ${m.port}`),i.resume(),i.pipe(g),g.pipe(i)})}catch(m){r&&console.error("[shadow_database] failed to start lazy backend",m),i.destroy(m instanceof Error?m:void 0)}}async function f(){if(n)return n;if(s)throw new Error("shadow_database is closed");return a||(r&&console.debug("[shadow_database] starting lazy backend..."),a=t().then(i=>(n=i,r&&console.debug(`[shadow_database] lazy backend started on port ${i.port}`),i)).catch(i=>{throw a=null,i})),await a}}async function ie(e,t,r){let{debug:n}=t,{port:a,updateServerStatePort:s}=r,o=await(e==="shadow_database"?Je:ue)(t.pgliteDataDirPath,n);n&&o.onNotification((i,m)=>{console.debug(`[${e}][${i}] ${m}`)});let{PGLiteSocketServer:u}=await import("@electric-sql/pglite-socket"),c=e==="shadow_database"?t.shadowDatabaseIdleTimeoutMillis:t.databaseIdleTimeoutMillis,l=new u({db:o,debug:n,idleTimeout:Number.isFinite(c)?c:0,inspect:n,maxConnections:p.connectionLimit,port:a});n&&(l.addEventListener("listening",i=>{let{detail:m}=i;console.debug(`[${e}] server listening on ${JSON.stringify(m)}`)}),l.addEventListener("connection",i=>{let{clientAddress:m,clientPort:g}=i.detail;console.debug(`[${e}] client connected from ${m}:${g}`)}),l.addEventListener("error",i=>{let{detail:m}=i;console.error(`[${e}] server error:`,m)}));try{await l.start()}catch(i){throw i instanceof Error&&"code"in i&&i.code==="EADDRINUSE"?new T(a):i}let f=Number(l.getServerConn().split(":").at(1));return s&&(t[e==="database"?"databasePort":"shadowDatabasePort"]=f),le(e,t,{db:o,port:f,server:l})}function le(e,t,r){let{debug:n}=t,{db:a,port:s,server:d}=r||{},o=new Map;return n&&console.debug(`[${e}] server started on port ${s}`),{...p,attachWalEventBridge:async()=>{if(e!=="database"||!a)throw new Error("WAL bridge is only available for the primary database server");return await D(a)},attachQueryInsightsBridge:()=>{if(e!=="database"||!d)throw new Error("Query insights are only available for the primary database server");return Promise.resolve(H(d))},close:async()=>{let u=[];try{await d?.stop(),n&&console.debug(`[${e}] server stopped on port ${s}`)}catch(c){console.error(`[${e}] server stop error`,c),u.push(c)}if(e==="database"){try{d&&await K(d),n&&console.debug(`[${e}] closed query insights bridge`)}catch(c){console.error(`[${e}] query insights bridge close error`,c),u.push(c)}try{a&&await j(a),n&&console.debug(`[${e}] closed WAL bridge`)}catch(c){console.error(`[${e}] WAL bridge close error`,c),u.push(c)}try{await a?.syncToFs(),n&&console.debug(`[${e}] synced to filesystem`)}catch(c){console.error(`[${e}] sync error`,c),u.push(c)}}try{await a?.close(),n&&console.debug(`[${e}] closed`)}catch(c){console.error(`[${e}] close error`,c),u.push(c)}if(u.length>0)throw new AggregateError(u,`Failed to close ${e} properly`)},connectionString:h(s,B),dump:async u=>{e==="shadow_database"||!a||await je({db:a,debug:n,destinationPath:u})},getPrimaryKeyColumns:async(u,c)=>{if(e==="shadow_database"||!a)throw new Error("Primary key resolution is only available for the primary database server");let l=`${u}.${c}`,f=o.get(l);return f||(f=Xe(a,u,c).catch(i=>{throw o.delete(l),i}),o.set(l,f)),await f},port:s,prismaORMConnectionString:h(s,oe),terminalCommand:`PGPASSWORD=${p.password} PGSSLMODE=${p.sslMode} psql -h localhost -p ${s} -U ${p.username} -d ${p.database}`}}function h(e,t){return`${He}:${e}/${p.database}?${t.toString()}`}async function ue(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await I(),a=e==="memory://"||!await L(Fe(e,"PG_VERSION")),s=await r.create({database:p.database,dataDir:e,debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:ne,loadDataDir:a?n.loadDataDir:void 0,relaxedDurability:!1,startParams:[...r.defaultStartParams,...ae],wasmModule:n.wasmModule});return await se(s),s}async function Ye(e,t){return await new Promise((r,n)=>{let a=o=>{if(d(),o.code==="EADDRINUSE"){n(new T(t));return}n(o)},s=()=>{let o=e.address();if(d(),!o||typeof o=="string"){n(new Error("Failed to determine TCP server port"));return}r(o.port)},d=()=>{e.off("error",a),e.off("listening",s)};e.once("error",a),e.once("listening",s),e.listen(t,re)})}async function ze(e){await new Promise((t,r)=>{e.close(n=>{let a=n;if(a&&a.code!=="ERR_SERVER_NOT_RUNNING"){r(a);return}t()})})}async function Je(e,t){let{PGlite:r}=await import("@electric-sql/pglite"),n=await I(),a=await r.create({database:p.database,dataDir:"memory://",debug:t?5:void 0,extensions:n.extensions,fsBundle:n.fsBundle,initialMemory:ne,loadDataDir:n.loadDataDir,relaxedDurability:!1,startParams:[...r.defaultStartParams,...ae],wasmModule:n.wasmModule});return await se(a),a}async function Xe(e,t,r){let{rows:n}=await e.query(`
92
+ SELECT attribute.attname AS column_name
93
+ FROM pg_constraint pk_constraint
94
+ INNER JOIN pg_class relation
95
+ ON relation.oid = pk_constraint.conrelid
96
+ INNER JOIN pg_namespace namespace
97
+ ON namespace.oid = relation.relnamespace
98
+ INNER JOIN unnest(pk_constraint.conkey) WITH ORDINALITY AS keys(attnum, ordinality)
99
+ ON TRUE
100
+ INNER JOIN pg_attribute attribute
101
+ ON attribute.attrelid = relation.oid
102
+ AND attribute.attnum = keys.attnum
103
+ WHERE pk_constraint.contype = 'p'
104
+ AND namespace.nspname = ${te(t)}
105
+ AND relation.relname = ${te(r)}
106
+ ORDER BY keys.ordinality
107
+ `);return n.map(a=>a.column_name)}function te(e){return`'${e.replaceAll("'","''")}'`}async function je(e){let{dataDir:t,db:r,debug:n,destinationPath:a}=e,s=r||await ue(t,n),{pgDump:d}=await import("@electric-sql/pglite-tools/pg_dump"),o=await d({args:["--schema-only","--no-owner"],fileName:a?Ue(a):void 0,pg:await s.clone()});return a?(n&&console.debug(`[DB] Dumping database to ${a}`),await O(o,a)):(n&&console.debug("[DB] Dumping database to memory"),await o.text())}export{Ze as a,et as b,D as c,v as d,V as e,bt as f,Ke as g,je as h};
@@ -0,0 +1 @@
1
+ import{a as c}from"./chunk-ANHBRJRZ.js";import{h as d}from"./chunk-EDFHV3AK.js";import{c as l,d as f}from"./chunk-DOJAPHLY.js";import{createServer as m}from"http";import{promisify as u}from"util";function A(r,e){return async function(o,n,i){let t=e?Date.now():0;e&&n.once("finish",()=>{let a=Date.now()-t;console.log("[Accelerate]",`<-- ${o.method??"?"} ${o.url??""} ${n.statusCode} ${a}ms`)});try{await r(o,n,i)}catch(a){try{y(a,n,o,e)}catch(p){e&&console.error("[Accelerate]","error while handling handler error",p),n.destroyed||n.destroy()}}}}function y(r,e,s,o){if(e.destroyed||e.headersSent||e.writableEnded){o&&console.error("[Accelerate]",`error after response was no longer writable for ${s.method??"?"} ${s.url??""}`,r),e.destroy();return}if(r instanceof c){f(e,r);return}console.error("[Accelerate]",r);try{l(e,500)}catch(n){o&&console.error("[Accelerate]","failed to write 500 response (client likely disconnected)",n),e.destroy()}}function E(r){let{router:e}=r;return{async listen(s){let o=m((t,a)=>{e.lookup(t,a)}),i=(await T(o,s)).port;return o.on("error",t=>{console.error("[Accelerate]",t)}),{async close(){await u(o.close.bind(o))()},port:i,url:`http://localhost:${i}`}}}}function T(r,e){return new Promise((s,o)=>{let n=t=>{if(r.off("listening",i),typeof t=="object"&&t!==null&&"code"in t&&t.code==="EADDRINUSE"){o(new d(e));return}o(t)},i=()=>{r.off("error",n),s(r.address())};r.once("error",n),r.once("listening",i),r.listen(e)})}export{A as a,E as b};