@prisma/composer-prisma-cloud 0.2.0-dev.13 → 0.2.0-dev.15
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/buckets-main.mjs +1 -1
- package/dist/compute-main.mjs +1 -1
- package/dist/local-target.mjs +89 -37
- package/dist/local-target.mjs.map +1 -1
- package/dist/postgres-main.mjs +184 -77
- package/dist/postgres-main.mjs.map +1 -1
- package/dist/{segments-NpKN-46R-B01DmCqy.mjs → segments-NpKN-46R-C_LQ2urs.mjs} +15 -2
- package/dist/{segments-NpKN-46R-B01DmCqy.mjs.map → segments-NpKN-46R-C_LQ2urs.mjs.map} +1 -1
- package/package.json +17 -17
package/dist/postgres-main.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as readOwnVersion, i as readJsonFile, n as isPidAlive, r as isValidSegment, t as StateFile } from "./segments-NpKN-46R-C_LQ2urs.mjs";
|
|
2
2
|
import { n as portNumbers, t as getPorts } from "./get-port-BYnpbW5H.mjs";
|
|
3
3
|
import * as fs from "node:fs";
|
|
4
4
|
import * as path from "node:path";
|
|
@@ -58,6 +58,16 @@ const MAX_DATABASE_PORT = 65535;
|
|
|
58
58
|
const APPS_STATE_MODE = 384;
|
|
59
59
|
/** Spec § 2 step 5's pattern, applied to a fresh database-port allocation. */
|
|
60
60
|
const MAX_FRESH_PORT_CANDIDATES = 5;
|
|
61
|
+
/**
|
|
62
|
+
* A name refused as "already running" is retried a few times, each attempt
|
|
63
|
+
* first waiting out the holder: a cold server boot takes seconds, and a
|
|
64
|
+
* crashed holder's lock is only released once proper-lockfile's ~10s stale
|
|
65
|
+
* threshold passes. Bounded so a genuinely stuck name still fails visibly
|
|
66
|
+
* inside the dev command's own startup budget.
|
|
67
|
+
*/
|
|
68
|
+
const MAX_ALREADY_RUNNING_RETRIES = 2;
|
|
69
|
+
const ALREADY_RUNNING_POLLS = 24;
|
|
70
|
+
const ALREADY_RUNNING_POLL_MS = 500;
|
|
61
71
|
const NOT_INSTALLED_MESSAGE = "local dev needs @prisma/dev for its local Postgres emulator — add \"prisma\" to your app's devDependencies.";
|
|
62
72
|
function maskCredentials(text) {
|
|
63
73
|
return text.replace(/:\/\/([^:@/\s]+):[^@/\s]+@/g, "://$1:***@");
|
|
@@ -92,9 +102,30 @@ function isPrismaDevModule(value) {
|
|
|
92
102
|
* number matching the candidate we just tried — is what actually survives
|
|
93
103
|
* that boundary.
|
|
94
104
|
*/
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
105
|
+
/**
|
|
106
|
+
* The port a start refusal is about, when it is one of THIS attempt's ports.
|
|
107
|
+
* Duck-typed (`instanceof` fails across the dynamic-import boundary): every
|
|
108
|
+
* `@prisma/dev` port refusal — not-available, requested-twice, and
|
|
109
|
+
* belongs-to-another-server (its registry can claim a port no bind probe
|
|
110
|
+
* sees) — carries the offending port as `.port`, and any of the four ports
|
|
111
|
+
* we requested (database + the three aux listeners) can be the one refused.
|
|
112
|
+
*/
|
|
113
|
+
function portConflictOf(err, ports) {
|
|
114
|
+
if (typeof err !== "object" || err === null || !("port" in err)) return void 0;
|
|
115
|
+
const port = err.port;
|
|
116
|
+
return typeof port === "number" && ports.includes(port) ? port : void 0;
|
|
117
|
+
}
|
|
118
|
+
function isNameAlreadyTaken(err) {
|
|
119
|
+
return isStringKeyedRecord(err) && (err["name"] === "ServerAlreadyRunningError" || err["name"] === "ServerStateAlreadyExistsError");
|
|
120
|
+
}
|
|
121
|
+
/** The port of a postgres connection URL, when it parses as one. */
|
|
122
|
+
function databasePortOf(connectionString) {
|
|
123
|
+
try {
|
|
124
|
+
const port = Number(new URL(connectionString).port);
|
|
125
|
+
return Number.isInteger(port) && port > 0 ? port : void 0;
|
|
126
|
+
} catch {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
98
129
|
}
|
|
99
130
|
/**
|
|
100
131
|
* A dynamic `import()` failure's own message routinely names a SECOND path
|
|
@@ -122,7 +153,48 @@ function isStringKeyedRecord(value) {
|
|
|
122
153
|
return typeof value === "object" && value !== null;
|
|
123
154
|
}
|
|
124
155
|
function isPrismaDevInternalStateModule(value) {
|
|
125
|
-
return isStringKeyedRecord(value) && typeof value["deleteServer"] === "function";
|
|
156
|
+
return isStringKeyedRecord(value) && typeof value["deleteServer"] === "function" && typeof value["killServer"] === "function" && typeof value["getServerStatus"] === "function";
|
|
157
|
+
}
|
|
158
|
+
function readServerStatus(status) {
|
|
159
|
+
if (!isStringKeyedRecord(status)) return {
|
|
160
|
+
live: false,
|
|
161
|
+
pid: void 0,
|
|
162
|
+
url: void 0,
|
|
163
|
+
databasePort: void 0
|
|
164
|
+
};
|
|
165
|
+
const exports = status["exports"];
|
|
166
|
+
const database = isStringKeyedRecord(exports) ? exports["database"] : void 0;
|
|
167
|
+
const url = isStringKeyedRecord(database) ? database["connectionString"] : void 0;
|
|
168
|
+
const pid = status["pid"];
|
|
169
|
+
const databasePort = status["databasePort"];
|
|
170
|
+
return {
|
|
171
|
+
live: status["status"] === "running" || status["status"] === "starting_up",
|
|
172
|
+
pid: typeof pid === "number" ? pid : void 0,
|
|
173
|
+
url: typeof url === "string" ? url : void 0,
|
|
174
|
+
databasePort: typeof databasePort === "number" ? databasePort : void 0
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
async function serverStatusOf(internalState, instanceName) {
|
|
178
|
+
try {
|
|
179
|
+
return readServerStatus(await internalState.getServerStatus(instanceName));
|
|
180
|
+
} catch {
|
|
181
|
+
return {
|
|
182
|
+
live: false,
|
|
183
|
+
pid: void 0,
|
|
184
|
+
url: void 0,
|
|
185
|
+
databasePort: void 0
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const CLOSE_SETTLE_ATTEMPTS = 40;
|
|
190
|
+
const CLOSE_SETTLE_DELAY_MS = 250;
|
|
191
|
+
/** True once the named server's persisted state no longer claims it is live — the precondition for `deleteServer`, whose kill path targets the pid in that state, which for an in-daemon server is THIS DAEMON's own pid. */
|
|
192
|
+
async function settledAfterClose(internalState, instanceName) {
|
|
193
|
+
for (let attempt = 1; attempt <= CLOSE_SETTLE_ATTEMPTS; attempt += 1) {
|
|
194
|
+
if (!(await serverStatusOf(internalState, instanceName)).live) return true;
|
|
195
|
+
if (attempt < CLOSE_SETTLE_ATTEMPTS) await new Promise((resolve) => setTimeout(resolve, CLOSE_SETTLE_DELAY_MS));
|
|
196
|
+
}
|
|
197
|
+
return false;
|
|
126
198
|
}
|
|
127
199
|
/**
|
|
128
200
|
* `@prisma/dev`'s own package.json declares `./internal/state`, whose
|
|
@@ -190,11 +262,22 @@ function main() {
|
|
|
190
262
|
const stateFile = new StateFile(appsJsonPath, APPS_STATE_MODE);
|
|
191
263
|
let state = {};
|
|
192
264
|
const runtimes = /* @__PURE__ */ new Map();
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
265
|
+
/**
|
|
266
|
+
* Server starts run ONE AT A TIME. `@prisma/dev`'s start is not
|
|
267
|
+
* concurrency-safe within a process: two simultaneous calls pick their
|
|
268
|
+
* ports without seeing each other and one fails with a port refusal
|
|
269
|
+
* (verified directly — two concurrent starts with distinct, pinned
|
|
270
|
+
* database ports fail; the same two started in sequence both succeed).
|
|
271
|
+
* The daemon issues concurrent starts whenever an app converges more than
|
|
272
|
+
* one database, which is what produced the port refusals, the retries
|
|
273
|
+
* whose half-started servers held their own name's lock, and every
|
|
274
|
+
* "already running" failure downstream of that.
|
|
275
|
+
*/
|
|
276
|
+
let startQueue = Promise.resolve();
|
|
277
|
+
function serializeStart(run) {
|
|
278
|
+
const next = startQueue.then(run, run);
|
|
279
|
+
startQueue = next.then(() => void 0, () => void 0);
|
|
280
|
+
return next;
|
|
198
281
|
}
|
|
199
282
|
function schedulePersist() {
|
|
200
283
|
stateFile.write(state);
|
|
@@ -212,101 +295,119 @@ function main() {
|
|
|
212
295
|
for (const appRec of Object.values(state)) for (const db of Object.values(appRec.databases)) ports.add(db.databasePort);
|
|
213
296
|
return ports;
|
|
214
297
|
}
|
|
215
|
-
async function smallestUnusedDatabasePort(min) {
|
|
298
|
+
async function smallestUnusedDatabasePort(min, alsoExclude = /* @__PURE__ */ new Set()) {
|
|
216
299
|
return getPorts({
|
|
217
300
|
port: portNumbers(min, MAX_DATABASE_PORT),
|
|
218
|
-
exclude: usedDatabasePorts()
|
|
301
|
+
exclude: [...usedDatabasePorts(), ...alsoExclude]
|
|
219
302
|
});
|
|
220
303
|
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
port: portNumbers(MIN_DATABASE_PORT, MAX_DATABASE_PORT),
|
|
230
|
-
exclude: taken
|
|
231
|
-
});
|
|
232
|
-
taken.add(httpPort);
|
|
233
|
-
const shadowDatabasePort = await getPorts({
|
|
234
|
-
port: portNumbers(MIN_DATABASE_PORT, MAX_DATABASE_PORT),
|
|
235
|
-
exclude: taken
|
|
304
|
+
const inflightEnsures = /* @__PURE__ */ new Map();
|
|
305
|
+
/** Concurrent PUTs for the same database coalesce onto one start — a second `startPrismaDevServer` for a name whose first start is still booting fails as "already running". */
|
|
306
|
+
function ensureDatabase(app, id, prismaDevModulePath) {
|
|
307
|
+
const instanceName = instanceNameFor(app, id);
|
|
308
|
+
const inflight = inflightEnsures.get(instanceName);
|
|
309
|
+
if (inflight) return inflight;
|
|
310
|
+
const run = ensureDatabaseSerialized(app, id, prismaDevModulePath, instanceName).finally(() => {
|
|
311
|
+
inflightEnsures.delete(instanceName);
|
|
236
312
|
});
|
|
237
|
-
|
|
238
|
-
return
|
|
239
|
-
httpPort,
|
|
240
|
-
shadowDatabasePort,
|
|
241
|
-
streamsPort: await getPorts({
|
|
242
|
-
port: portNumbers(MIN_DATABASE_PORT, MAX_DATABASE_PORT),
|
|
243
|
-
exclude: taken
|
|
244
|
-
})
|
|
245
|
-
};
|
|
313
|
+
inflightEnsures.set(instanceName, run);
|
|
314
|
+
return run;
|
|
246
315
|
}
|
|
247
|
-
async function
|
|
316
|
+
async function ensureDatabaseSerialized(app, id, prismaDevModulePath, instanceName) {
|
|
248
317
|
const appRec = getOrCreateApp(app);
|
|
249
|
-
const instanceName = instanceNameFor(app, id);
|
|
250
318
|
const existingRecord = appRec.databases[id];
|
|
251
319
|
const runningServer = runtimes.get(instanceName);
|
|
252
320
|
if (existingRecord && runningServer) return { url: existingRecord.url };
|
|
253
321
|
const prismaDev = await importPrismaDev(prismaDevModulePath);
|
|
254
|
-
const
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
const aux = await allocateAuxPorts(/* @__PURE__ */ new Set([dbPort]));
|
|
259
|
-
try {
|
|
260
|
-
const server = await prismaDev.startPrismaDevServer({
|
|
261
|
-
name: instanceName,
|
|
262
|
-
databasePort: dbPort,
|
|
263
|
-
port: aux.httpPort,
|
|
264
|
-
shadowDatabasePort: aux.shadowDatabasePort,
|
|
265
|
-
streamsPort: aux.streamsPort,
|
|
266
|
-
persistenceMode: "stateful"
|
|
267
|
-
});
|
|
268
|
-
const url = server.database.connectionString;
|
|
269
|
-
runtimes.set(instanceName, server);
|
|
270
|
-
liveAuxPorts.add(aux.httpPort);
|
|
271
|
-
liveAuxPorts.add(aux.shadowDatabasePort);
|
|
272
|
-
liveAuxPorts.add(aux.streamsPort);
|
|
273
|
-
auxPortsByInstance.set(instanceName, [
|
|
274
|
-
aux.httpPort,
|
|
275
|
-
aux.shadowDatabasePort,
|
|
276
|
-
aux.streamsPort
|
|
277
|
-
]);
|
|
322
|
+
const internalState = await importPrismaDevInternalState(prismaDevModulePath);
|
|
323
|
+
const recorded = await serverStatusOf(internalState, instanceName);
|
|
324
|
+
if (recorded.live && recorded.pid !== void 0 && isPidAlive(recorded.pid)) {
|
|
325
|
+
if (recorded.url !== void 0) {
|
|
278
326
|
appRec.databases[id] = {
|
|
279
327
|
id,
|
|
280
328
|
instanceName,
|
|
281
|
-
databasePort:
|
|
282
|
-
url
|
|
329
|
+
databasePort: recorded.databasePort ?? databasePortOf(recorded.url) ?? MIN_DATABASE_PORT,
|
|
330
|
+
url: recorded.url
|
|
283
331
|
};
|
|
284
332
|
schedulePersist();
|
|
285
|
-
return { url };
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
333
|
+
return { url: recorded.url };
|
|
334
|
+
}
|
|
335
|
+
} else if (recorded.live) await internalState.killServer(instanceName).catch(() => void 0);
|
|
336
|
+
const isFreshAllocation = existingRecord === void 0;
|
|
337
|
+
let dbPort = existingRecord?.databasePort ?? await smallestUnusedDatabasePort(MIN_DATABASE_PORT);
|
|
338
|
+
const conflicted = /* @__PURE__ */ new Set();
|
|
339
|
+
let alreadyRunningRetries = 0;
|
|
340
|
+
for (let attempt = 1;; attempt++) try {
|
|
341
|
+
const server = await serializeStart(() => prismaDev.startPrismaDevServer({
|
|
342
|
+
name: instanceName,
|
|
343
|
+
databasePort: dbPort,
|
|
344
|
+
persistenceMode: "stateful"
|
|
345
|
+
}));
|
|
346
|
+
const url = server.database.connectionString;
|
|
347
|
+
runtimes.set(instanceName, server);
|
|
348
|
+
appRec.databases[id] = {
|
|
349
|
+
id,
|
|
350
|
+
instanceName,
|
|
351
|
+
databasePort: dbPort,
|
|
352
|
+
url
|
|
353
|
+
};
|
|
354
|
+
schedulePersist();
|
|
355
|
+
return { url };
|
|
356
|
+
} catch (err) {
|
|
357
|
+
if (isNameAlreadyTaken(err) && alreadyRunningRetries < MAX_ALREADY_RUNNING_RETRIES) {
|
|
358
|
+
alreadyRunningRetries += 1;
|
|
359
|
+
for (let poll = 1; poll <= ALREADY_RUNNING_POLLS; poll += 1) {
|
|
360
|
+
const now = await serverStatusOf(internalState, instanceName);
|
|
361
|
+
if (now.live && now.pid !== void 0 && isPidAlive(now.pid) && now.url !== void 0) {
|
|
362
|
+
appRec.databases[id] = {
|
|
363
|
+
id,
|
|
364
|
+
instanceName,
|
|
365
|
+
databasePort: now.databasePort ?? databasePortOf(now.url) ?? dbPort,
|
|
366
|
+
url: now.url
|
|
367
|
+
};
|
|
368
|
+
schedulePersist();
|
|
369
|
+
return { url: now.url };
|
|
370
|
+
}
|
|
371
|
+
if (now.live && (now.pid === void 0 || !isPidAlive(now.pid))) {
|
|
372
|
+
await internalState.killServer(instanceName).catch(() => void 0);
|
|
373
|
+
break;
|
|
374
|
+
}
|
|
375
|
+
await new Promise((resolve) => setTimeout(resolve, ALREADY_RUNNING_POLL_MS));
|
|
290
376
|
}
|
|
291
|
-
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
const conflictPort = portConflictOf(err, [dbPort]);
|
|
380
|
+
if (!(conflictPort !== void 0 && attempt < MAX_FRESH_PORT_CANDIDATES && (conflictPort !== dbPort || isFreshAllocation))) {
|
|
381
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
382
|
+
throw new Error(`postgres emulator failed to start database "${instanceName}" on port ${String(dbPort)}: ${maskCredentials(firstLine(reason))}`);
|
|
292
383
|
}
|
|
384
|
+
conflicted.add(conflictPort);
|
|
385
|
+
if (conflictPort === dbPort) dbPort = await smallestUnusedDatabasePort(dbPort + 1, conflicted);
|
|
293
386
|
}
|
|
294
387
|
}
|
|
295
388
|
async function deleteApp(app, prismaDevModulePathHint) {
|
|
296
389
|
const appRec = state[app];
|
|
297
390
|
if (!appRec) return;
|
|
298
391
|
const entries = Object.values(appRec.databases);
|
|
299
|
-
|
|
392
|
+
for (const db of entries) {
|
|
300
393
|
const server = runtimes.get(db.instanceName);
|
|
301
394
|
if (server) {
|
|
302
|
-
await server.close();
|
|
395
|
+
await server.close().catch(() => void 0);
|
|
303
396
|
runtimes.delete(db.instanceName);
|
|
304
|
-
releaseAuxPorts(db.instanceName);
|
|
305
397
|
}
|
|
306
|
-
}
|
|
398
|
+
}
|
|
307
399
|
if (entries.length > 0 && prismaDevModulePathHint) {
|
|
308
|
-
const
|
|
309
|
-
|
|
400
|
+
const internalState = await importPrismaDevInternalState(prismaDevModulePathHint);
|
|
401
|
+
for (const db of entries) {
|
|
402
|
+
if (!runtimes.has(db.instanceName)) {
|
|
403
|
+
if ((await serverStatusOf(internalState, db.instanceName)).pid !== process.pid) await internalState.killServer(db.instanceName).catch(() => void 0);
|
|
404
|
+
}
|
|
405
|
+
if (!await settledAfterClose(internalState, db.instanceName)) {
|
|
406
|
+
console.error(`postgres-main: server "${db.instanceName}" still reports running after close — leaving its persisted data in place instead of risking a self-kill.`);
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
await internalState.deleteServer(db.instanceName);
|
|
410
|
+
}
|
|
310
411
|
}
|
|
311
412
|
delete state[app];
|
|
312
413
|
schedulePersist();
|
|
@@ -378,13 +479,19 @@ function main() {
|
|
|
378
479
|
});
|
|
379
480
|
});
|
|
380
481
|
async function shutdown() {
|
|
381
|
-
|
|
482
|
+
for (const server of runtimes.values()) await server.close().catch(() => void 0);
|
|
382
483
|
await stateFile.flush();
|
|
383
484
|
server.close();
|
|
384
485
|
process.exit(0);
|
|
385
486
|
}
|
|
386
487
|
process.on("SIGTERM", () => void shutdown());
|
|
387
488
|
process.on("SIGINT", () => void shutdown());
|
|
489
|
+
process.on("unhandledRejection", (reason) => {
|
|
490
|
+
console.error("postgres-main: unhandled rejection from background work:", reason instanceof Error ? maskCredentials(reason.stack ?? reason.message) : reason);
|
|
491
|
+
});
|
|
492
|
+
process.on("uncaughtException", (err) => {
|
|
493
|
+
console.error("postgres-main: uncaught exception from background work:", err instanceof Error ? maskCredentials(err.stack ?? err.message) : err);
|
|
494
|
+
});
|
|
388
495
|
readJsonFile(appsJsonPath, isAppsState).then((loaded) => {
|
|
389
496
|
if (loaded) state = loaded;
|
|
390
497
|
server.listen(port, "127.0.0.1", () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-main.mjs","names":["getPort"],"sources":["../../../1-prisma-cloud/0-lowering/dev-emulators/dist/instance-name-BF6J_weL.mjs","../../../1-prisma-cloud/0-lowering/dev-emulators/dist/postgres-main.mjs"],"sourcesContent":["//#region src/instance-name.ts\n/**\n* `pcdev-<app>-<database-id>` instance-name derivation (local-dev spec § 2\n* `postgres-main.ts`): each half lowercased, every char outside `[a-z0-9]`\n* replaced by `-`, runs collapsed, the combined name trimmed to 63 chars.\n*\n* A separate, side-effect-free module (not defined inline in\n* `postgres-main.ts`) so it can be imported directly by tests without also\n* running that file's own `main()` — `postgres-main.ts` is a daemon\n* entrypoint script, always invoked as a subprocess, and calls `main()`\n* unconditionally at module load.\n*/\n/**\n* Deliberately linear, no ambiguous quantifiers: a per-character replace\n* (no `+`, so no run-length backtracking surface), a bounded-quantifier\n* collapse (`{2,}`, not alternation-with-quantifiers), and plain\n* index-walking for the leading/trailing trim instead of a regex — a\n* combined `+`-plus-alternation trim (`/^-+|-+$/g`) is exactly the shape\n* CodeQL's polynomial-ReDoS check flags, whether or not this particular\n* instance is provably safe.\n*/\nfunction slug(segment) {\n\tconst collapsed = segment.toLowerCase().replace(/[^a-z0-9]/g, \"-\").replace(/-{2,}/g, \"-\");\n\tlet start = 0;\n\tlet end = collapsed.length;\n\twhile (start < end && collapsed[start] === \"-\") start++;\n\twhile (end > start && collapsed[end - 1] === \"-\") end--;\n\treturn collapsed.slice(start, end);\n}\nfunction instanceNameFor(app, id) {\n\treturn `pcdev-${slug(app)}-${slug(id)}`.slice(0, 63);\n}\n//#endregion\nexport { slug as n, instanceNameFor as t };\n\n//# sourceMappingURL=instance-name-BF6J_weL.mjs.map","import { c as readOwnVersion, f as StateFile, p as readJsonFile, t as isValidSegment } from \"./segments-NpKN-46R.mjs\";\nimport { t as instanceNameFor } from \"./instance-name-BF6J_weL.mjs\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport getPort, { portNumbers } from \"get-port\";\nimport * as http from \"node:http\";\n//#region src/postgres-main.ts\n/**\n* The Postgres emulator daemon (local-dev spec § 2 `postgres-main.ts`): a\n* small local counterpart of hosted Postgres, hosting `@prisma/dev`'s\n* `startPrismaDevServer()` — one named, persistent server per `Database`\n* resource, several servers in this one daemon process. Loopback\n* `node:http` JSON admin API; state under its `--state-dir`.\n*\n* `@prisma/dev` is imported dynamically from a CALLER-RESOLVED path (each\n* admin request that needs it carries `prismaDevModulePath`) so the app\n* owns its own Prisma version — this daemon has no `@prisma/dev` dependency\n* of its own.\n*\n* Runs as its own OS process, started by `daemon.ts`'s `ensureDaemon` via\n* `process.execPath <this file> --port <n> --state-dir <dir>`.\n*/\nconst MIN_DATABASE_PORT = 51300;\nconst MAX_DATABASE_PORT = 65535;\nconst APPS_STATE_MODE = 384;\n/** Spec § 2 step 5's pattern, applied to a fresh database-port allocation. */\nconst MAX_FRESH_PORT_CANDIDATES = 5;\nconst NOT_INSTALLED_MESSAGE = \"local dev needs @prisma/dev for its local Postgres emulator — add \\\"prisma\\\" to your app's devDependencies.\";\nfunction maskCredentials(text) {\n\treturn text.replace(/:\\/\\/([^:@/\\s]+):[^@/\\s]+@/g, \"://$1:***@\");\n}\nfunction firstLine(text) {\n\treturn (text.split(\"\\n\")[0] ?? text).trim();\n}\nfunction isDatabaseRecord(value) {\n\treturn typeof value === \"object\" && value !== null && \"id\" in value && typeof value.id === \"string\" && \"instanceName\" in value && typeof value.instanceName === \"string\" && \"databasePort\" in value && typeof value.databasePort === \"number\" && \"url\" in value && typeof value.url === \"string\";\n}\nfunction isAppRecord(value) {\n\treturn typeof value === \"object\" && value !== null && \"databases\" in value && typeof value.databases === \"object\" && value.databases !== null && Object.values(value.databases).every(isDatabaseRecord);\n}\nfunction isAppsState(value) {\n\treturn typeof value === \"object\" && value !== null && Object.values(value).every(isAppRecord);\n}\nfunction isDatabaseBody(value) {\n\treturn typeof value === \"object\" && value !== null && \"prismaDevModulePath\" in value && typeof value.prismaDevModulePath === \"string\";\n}\nfunction isPrismaDevModule(value) {\n\treturn typeof value === \"object\" && value !== null && \"startPrismaDevServer\" in value && typeof value.startPrismaDevServer === \"function\";\n}\n/**\n* `@prisma/dev` exports a `PortNotAvailableError` class with a `readonly\n* port: number`, but the daemon dynamically imports the module from a\n* caller-given path while the class identity checked here would come from\n* whatever module graph THIS file's own bundle produced — two separate\n* instantiations of the same logical class, so `instanceof` doesn't match\n* across them (confirmed empirically: a real port conflict's `err\n* instanceof mod.PortNotAvailableError` is `false` even though the error IS\n* the port-conflict one). Duck-typing the documented shape — a `port`\n* number matching the candidate we just tried — is what actually survives\n* that boundary.\n*/\nfunction isPortConflict(err, port) {\n\tif (typeof err !== \"object\" || err === null || !(\"port\" in err)) return false;\n\treturn err.port === port;\n}\n/**\n* A dynamic `import()` failure's own message routinely names a SECOND path\n* (e.g. bun's \"Cannot find module '<target>' from '<importer>'\") — the\n* importer half is this daemon's own internal location, not anything the\n* caller gave us, and has no business in a response body. Rather than try\n* to scrub an arbitrary underlying message for every runtime's own error\n* phrasing, the resolution-failure case names only what the caller\n* supplied — the pinned message plus the given `prismaDevModulePath`, and\n* nothing else. (A DIFFERENT case — a module that resolves fine but whose\n* `startPrismaDevServer()` call itself fails — still surfaces its\n* underlying text verbatim, credential-masked, per spec § 2.)\n*/\nasync function importPrismaDev(prismaDevModulePath) {\n\tlet mod;\n\ttry {\n\t\tmod = await import(pathToFileURL(prismaDevModulePath).href);\n\t} catch {\n\t\tthrow new Error(`${NOT_INSTALLED_MESSAGE} (could not resolve \"${prismaDevModulePath}\")`);\n\t}\n\tif (!isPrismaDevModule(mod)) throw new Error(`${NOT_INSTALLED_MESSAGE} (\"${prismaDevModulePath}\" is not a @prisma/dev module)`);\n\treturn mod;\n}\nfunction isStringKeyedRecord(value) {\n\treturn typeof value === \"object\" && value !== null;\n}\nfunction isPrismaDevInternalStateModule(value) {\n\treturn isStringKeyedRecord(value) && typeof value[\"deleteServer\"] === \"function\";\n}\n/**\n* `@prisma/dev`'s own package.json declares `./internal/state`, whose\n* `deleteServer(name)` actually removes a stateful server's persisted PGlite\n* data — `startPrismaDevServer`'s public surface only starts/closes a live\n* server, never deletes what a closed one left on disk. Resolved by reading\n* the SAME package's own `exports` map (walked up from the caller-given\n* entry path to find `@prisma/dev`'s `package.json`), never by guessing at\n* `dist/` file layout.\n*/\nasync function importPrismaDevInternalState(prismaDevModulePath) {\n\tlet dir = path.dirname(prismaDevModulePath);\n\tfor (;;) {\n\t\tconst pkgPath = path.join(dir, \"package.json\");\n\t\tif (fs.existsSync(pkgPath)) {\n\t\t\tconst pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf8\"));\n\t\t\tif (isStringKeyedRecord(pkg) && pkg[\"name\"] === \"@prisma/dev\" && isStringKeyedRecord(pkg[\"exports\"])) {\n\t\t\t\tconst entry = pkg[\"exports\"][\"./internal/state\"];\n\t\t\t\tconst target = resolveExportTarget(entry);\n\t\t\t\tif (target === void 0) throw new Error(`\"@prisma/dev\" at \"${dir}\" does not declare an \"./internal/state\" export — cannot delete its persisted database data.`);\n\t\t\t\tconst mod = await import(pathToFileURL(path.join(dir, target)).href);\n\t\t\t\tif (isPrismaDevInternalStateModule(mod)) return mod;\n\t\t\t\tthrow new Error(`\"@prisma/dev\"'s \"./internal/state\" export at \"${dir}\" has no deleteServer.`);\n\t\t\t}\n\t\t}\n\t\tconst parent = path.dirname(dir);\n\t\tif (parent === dir) throw new Error(`could not find \"@prisma/dev\"'s package.json above \"${prismaDevModulePath}\".`);\n\t\tdir = parent;\n\t}\n}\nfunction resolveExportTarget(entry) {\n\tif (typeof entry === \"string\") return entry;\n\tif (!isStringKeyedRecord(entry)) return void 0;\n\tconst nested = entry[\"import\"] ?? entry[\"require\"] ?? entry[\"default\"];\n\tif (typeof nested === \"string\") return nested;\n\tif (isStringKeyedRecord(nested)) {\n\t\tconst def = nested[\"default\"];\n\t\tif (typeof def === \"string\") return def;\n\t}\n}\nfunction parseArgs(argv) {\n\tlet port;\n\tlet stateDir;\n\tfor (let i = 0; i < argv.length; i++) if (argv[i] === \"--port\") port = Number(argv[i + 1]);\n\telse if (argv[i] === \"--state-dir\") stateDir = argv[i + 1];\n\tif (port === void 0 || Number.isNaN(port)) throw new Error(\"postgres-main: --port <n> is required\");\n\tif (stateDir === void 0) throw new Error(\"postgres-main: --state-dir <dir> is required\");\n\treturn {\n\t\tport,\n\t\tstateDir\n\t};\n}\nfunction readBody(req) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst chunks = [];\n\t\treq.on(\"data\", (chunk) => chunks.push(chunk));\n\t\treq.on(\"end\", () => resolve(Buffer.concat(chunks)));\n\t\treq.on(\"error\", reject);\n\t});\n}\nfunction main() {\n\tconst { port, stateDir } = parseArgs(process.argv.slice(2));\n\tconst ownVersion = readOwnVersion();\n\tconst appsJsonPath = path.join(stateDir, \"apps.json\");\n\tconst stateFile = new StateFile(appsJsonPath, APPS_STATE_MODE);\n\tlet state = {};\n\tconst runtimes = /* @__PURE__ */ new Map();\n\tconst liveAuxPorts = /* @__PURE__ */ new Set();\n\tconst auxPortsByInstance = /* @__PURE__ */ new Map();\n\tfunction releaseAuxPorts(instanceName) {\n\t\tfor (const p of auxPortsByInstance.get(instanceName) ?? []) liveAuxPorts.delete(p);\n\t\tauxPortsByInstance.delete(instanceName);\n\t}\n\tfunction schedulePersist() {\n\t\tstateFile.write(state);\n\t}\n\tfunction getOrCreateApp(app) {\n\t\tlet appRec = state[app];\n\t\tif (!appRec) {\n\t\t\tappRec = { databases: {} };\n\t\t\tstate[app] = appRec;\n\t\t}\n\t\treturn appRec;\n\t}\n\tfunction usedDatabasePorts() {\n\t\tconst ports = /* @__PURE__ */ new Set();\n\t\tfor (const appRec of Object.values(state)) for (const db of Object.values(appRec.databases)) ports.add(db.databasePort);\n\t\treturn ports;\n\t}\n\tasync function smallestUnusedDatabasePort(min) {\n\t\treturn getPort({\n\t\t\tport: portNumbers(min, MAX_DATABASE_PORT),\n\t\t\texclude: usedDatabasePorts()\n\t\t});\n\t}\n\t/** Three fresh, mutually distinct ports for a server's own HTTP/shadow-database/streams listeners — never persisted, only unique right now. */\n\tasync function allocateAuxPorts(excluding) {\n\t\tconst taken = /* @__PURE__ */ new Set([\n\t\t\t...usedDatabasePorts(),\n\t\t\t...liveAuxPorts,\n\t\t\t...excluding\n\t\t]);\n\t\tconst httpPort = await getPort({\n\t\t\tport: portNumbers(MIN_DATABASE_PORT, MAX_DATABASE_PORT),\n\t\t\texclude: taken\n\t\t});\n\t\ttaken.add(httpPort);\n\t\tconst shadowDatabasePort = await getPort({\n\t\t\tport: portNumbers(MIN_DATABASE_PORT, MAX_DATABASE_PORT),\n\t\t\texclude: taken\n\t\t});\n\t\ttaken.add(shadowDatabasePort);\n\t\treturn {\n\t\t\thttpPort,\n\t\t\tshadowDatabasePort,\n\t\t\tstreamsPort: await getPort({\n\t\t\t\tport: portNumbers(MIN_DATABASE_PORT, MAX_DATABASE_PORT),\n\t\t\t\texclude: taken\n\t\t\t})\n\t\t};\n\t}\n\tasync function ensureDatabase(app, id, prismaDevModulePath) {\n\t\tconst appRec = getOrCreateApp(app);\n\t\tconst instanceName = instanceNameFor(app, id);\n\t\tconst existingRecord = appRec.databases[id];\n\t\tconst runningServer = runtimes.get(instanceName);\n\t\tif (existingRecord && runningServer) return { url: existingRecord.url };\n\t\tconst prismaDev = await importPrismaDev(prismaDevModulePath);\n\t\tconst isFreshAllocation = existingRecord === void 0;\n\t\tconst maxAttempts = isFreshAllocation ? MAX_FRESH_PORT_CANDIDATES : 1;\n\t\tlet dbPort = existingRecord?.databasePort ?? await smallestUnusedDatabasePort(MIN_DATABASE_PORT);\n\t\tfor (let attempt = 1;; attempt++) {\n\t\t\tconst aux = await allocateAuxPorts(/* @__PURE__ */ new Set([dbPort]));\n\t\t\ttry {\n\t\t\t\tconst server = await prismaDev.startPrismaDevServer({\n\t\t\t\t\tname: instanceName,\n\t\t\t\t\tdatabasePort: dbPort,\n\t\t\t\t\tport: aux.httpPort,\n\t\t\t\t\tshadowDatabasePort: aux.shadowDatabasePort,\n\t\t\t\t\tstreamsPort: aux.streamsPort,\n\t\t\t\t\tpersistenceMode: \"stateful\"\n\t\t\t\t});\n\t\t\t\tconst url = server.database.connectionString;\n\t\t\t\truntimes.set(instanceName, server);\n\t\t\t\tliveAuxPorts.add(aux.httpPort);\n\t\t\t\tliveAuxPorts.add(aux.shadowDatabasePort);\n\t\t\t\tliveAuxPorts.add(aux.streamsPort);\n\t\t\t\tauxPortsByInstance.set(instanceName, [\n\t\t\t\t\taux.httpPort,\n\t\t\t\t\taux.shadowDatabasePort,\n\t\t\t\t\taux.streamsPort\n\t\t\t\t]);\n\t\t\t\tappRec.databases[id] = {\n\t\t\t\t\tid,\n\t\t\t\t\tinstanceName,\n\t\t\t\t\tdatabasePort: dbPort,\n\t\t\t\t\turl\n\t\t\t\t};\n\t\t\t\tschedulePersist();\n\t\t\t\treturn { url };\n\t\t\t} catch (err) {\n\t\t\t\tif (!(isFreshAllocation && isPortConflict(err, dbPort) && attempt < maxAttempts)) {\n\t\t\t\t\tconst reason = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tthrow new Error(`postgres emulator failed to start database \"${instanceName}\" on port ${String(dbPort)}: ${maskCredentials(firstLine(reason))}`);\n\t\t\t\t}\n\t\t\t\tdbPort = await smallestUnusedDatabasePort(dbPort + 1);\n\t\t\t}\n\t\t}\n\t}\n\tasync function deleteApp(app, prismaDevModulePathHint) {\n\t\tconst appRec = state[app];\n\t\tif (!appRec) return;\n\t\tconst entries = Object.values(appRec.databases);\n\t\tawait Promise.all(entries.map(async (db) => {\n\t\t\tconst server = runtimes.get(db.instanceName);\n\t\t\tif (server) {\n\t\t\t\tawait server.close();\n\t\t\t\truntimes.delete(db.instanceName);\n\t\t\t\treleaseAuxPorts(db.instanceName);\n\t\t\t}\n\t\t}));\n\t\tif (entries.length > 0 && prismaDevModulePathHint) {\n\t\t\tconst { deleteServer } = await importPrismaDevInternalState(prismaDevModulePathHint);\n\t\t\tawait Promise.all(entries.map((db) => deleteServer(db.instanceName)));\n\t\t}\n\t\tdelete state[app];\n\t\tschedulePersist();\n\t}\n\tfunction json(res, status, body) {\n\t\tres.writeHead(status, { \"content-type\": \"application/json\" });\n\t\tres.end(JSON.stringify(body));\n\t}\n\tfunction text(res, status, body) {\n\t\tres.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\" });\n\t\tres.end(body);\n\t}\n\tfunction badSegment(res, segment) {\n\t\ttext(res, 400, `invalid path segment \"${segment}\": must match /^[a-z0-9][a-z0-9-]*$/ and be at most 63 characters`);\n\t}\n\tfunction databaseView(db) {\n\t\treturn {\n\t\t\tid: db.id,\n\t\t\turl: db.url,\n\t\t\tinstanceName: db.instanceName,\n\t\t\tdatabasePort: db.databasePort\n\t\t};\n\t}\n\t/** The most recently observed `prismaDevModulePath` for any database of `app` — DELETE has no body of its own to carry one. */\n\tconst recentPrismaDevModulePath = /* @__PURE__ */ new Map();\n\tfunction lastKnownPrismaDevModulePath(app) {\n\t\treturn recentPrismaDevModulePath.get(app);\n\t}\n\tasync function handleRequest(req, res) {\n\t\tconst url = new URL(req.url ?? \"/\", `http://127.0.0.1:${String(port)}`);\n\t\tconst method = req.method ?? \"GET\";\n\t\tconst segments = url.pathname.split(\"/\").filter((s) => s.length > 0).map((s) => decodeURIComponent(s));\n\t\tif (method === \"GET\" && segments.length === 1 && segments[0] === \"health\") return json(res, 200, { version: ownVersion });\n\t\tif (segments[0] === \"apps\" && segments.length >= 2) {\n\t\t\tconst app = segments[1];\n\t\t\tif (app === void 0 || !isValidSegment(app)) return badSegment(res, app ?? \"\");\n\t\t\tif (method === \"PUT\" && segments.length === 4 && segments[2] === \"databases\") {\n\t\t\t\tconst id = segments[3];\n\t\t\t\tif (id === void 0 || !isValidSegment(id)) return badSegment(res, id ?? \"\");\n\t\t\t\tconst raw = await readBody(req);\n\t\t\t\tlet parsed;\n\t\t\t\ttry {\n\t\t\t\t\tparsed = JSON.parse(raw.toString(\"utf8\"));\n\t\t\t\t} catch {\n\t\t\t\t\treturn text(res, 400, \"malformed JSON body\");\n\t\t\t\t}\n\t\t\t\tif (!isDatabaseBody(parsed)) return text(res, 400, \"malformed database body: expected { \\\"prismaDevModulePath\\\": string }\");\n\t\t\t\trecentPrismaDevModulePath.set(app, parsed.prismaDevModulePath);\n\t\t\t\treturn json(res, 200, await ensureDatabase(app, id, parsed.prismaDevModulePath));\n\t\t\t}\n\t\t\tif (method === \"GET\" && segments.length === 3 && segments[2] === \"databases\") {\n\t\t\t\tconst appRec = state[app];\n\t\t\t\treturn json(res, 200, appRec ? Object.values(appRec.databases).map(databaseView) : []);\n\t\t\t}\n\t\t\tif (method === \"DELETE\" && segments.length === 2) {\n\t\t\t\tawait deleteApp(app, lastKnownPrismaDevModulePath(app));\n\t\t\t\tres.writeHead(204);\n\t\t\t\tres.end();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tres.writeHead(404);\n\t\tres.end();\n\t}\n\tconst server = http.createServer((req, res) => {\n\t\thandleRequest(req, res).catch((err) => {\n\t\t\tif (!res.headersSent) res.writeHead(500, { \"content-type\": \"text/plain\" });\n\t\t\tres.end(err instanceof Error ? maskCredentials(err.message) : String(err));\n\t\t});\n\t});\n\tasync function shutdown() {\n\t\tawait Promise.all([...runtimes.values()].map((server) => server.close().catch(() => void 0)));\n\t\tawait stateFile.flush();\n\t\tserver.close();\n\t\tprocess.exit(0);\n\t}\n\tprocess.on(\"SIGTERM\", () => void shutdown());\n\tprocess.on(\"SIGINT\", () => void shutdown());\n\treadJsonFile(appsJsonPath, isAppsState).then((loaded) => {\n\t\tif (loaded) state = loaded;\n\t\tserver.listen(port, \"127.0.0.1\", () => {\n\t\t\tconsole.log(`[dev-emulators] postgres-main listening on 127.0.0.1:${String(port)}`);\n\t\t});\n\t}).catch((err) => {\n\t\tconsole.error(\"postgres-main: failed to load state\", err);\n\t\tprocess.exit(1);\n\t});\n}\nmain();\n//#endregion\nexport {};\n\n//# sourceMappingURL=postgres-main.mjs.map"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,KAAK,SAAS;CACtB,MAA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names":["getPort"],"sources":["../../../1-prisma-cloud/0-lowering/dev-emulators/dist/instance-name-BF6J_weL.mjs","../../../1-prisma-cloud/0-lowering/dev-emulators/dist/postgres-main.mjs"],"sourcesContent":["//#region src/instance-name.ts\n/**\n* `pcdev-<app>-<database-id>` instance-name derivation (local-dev spec § 2\n* `postgres-main.ts`): each half lowercased, every char outside `[a-z0-9]`\n* replaced by `-`, runs collapsed, the combined name trimmed to 63 chars.\n*\n* A separate, side-effect-free module (not defined inline in\n* `postgres-main.ts`) so it can be imported directly by tests without also\n* running that file's own `main()` — `postgres-main.ts` is a daemon\n* entrypoint script, always invoked as a subprocess, and calls `main()`\n* unconditionally at module load.\n*/\n/**\n* Deliberately linear, no ambiguous quantifiers: a per-character replace\n* (no `+`, so no run-length backtracking surface), a bounded-quantifier\n* collapse (`{2,}`, not alternation-with-quantifiers), and plain\n* index-walking for the leading/trailing trim instead of a regex — a\n* combined `+`-plus-alternation trim (`/^-+|-+$/g`) is exactly the shape\n* CodeQL's polynomial-ReDoS check flags, whether or not this particular\n* instance is provably safe.\n*/\nfunction slug(segment) {\n\tconst collapsed = segment.toLowerCase().replace(/[^a-z0-9]/g, \"-\").replace(/-{2,}/g, \"-\");\n\tlet start = 0;\n\tlet end = collapsed.length;\n\twhile (start < end && collapsed[start] === \"-\") start++;\n\twhile (end > start && collapsed[end - 1] === \"-\") end--;\n\treturn collapsed.slice(start, end);\n}\nfunction instanceNameFor(app, id) {\n\treturn `pcdev-${slug(app)}-${slug(id)}`.slice(0, 63);\n}\n//#endregion\nexport { slug as n, instanceNameFor as t };\n\n//# sourceMappingURL=instance-name-BF6J_weL.mjs.map","import { c as readOwnVersion, f as StateFile, p as readJsonFile, s as isPidAlive, t as isValidSegment } from \"./segments-NpKN-46R.mjs\";\nimport { t as instanceNameFor } from \"./instance-name-BF6J_weL.mjs\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport getPort, { portNumbers } from \"get-port\";\nimport * as http from \"node:http\";\n//#region src/postgres-main.ts\n/**\n* The Postgres emulator daemon (local-dev spec § 2 `postgres-main.ts`): a\n* small local counterpart of hosted Postgres, hosting `@prisma/dev`'s\n* `startPrismaDevServer()` — one named, persistent server per `Database`\n* resource, several servers in this one daemon process. Loopback\n* `node:http` JSON admin API; state under its `--state-dir`.\n*\n* `@prisma/dev` is imported dynamically from a CALLER-RESOLVED path (each\n* admin request that needs it carries `prismaDevModulePath`) so the app\n* owns its own Prisma version — this daemon has no `@prisma/dev` dependency\n* of its own.\n*\n* Runs as its own OS process, started by `daemon.ts`'s `ensureDaemon` via\n* `process.execPath <this file> --port <n> --state-dir <dir>`.\n*/\nconst MIN_DATABASE_PORT = 51300;\nconst MAX_DATABASE_PORT = 65535;\nconst APPS_STATE_MODE = 384;\n/** Spec § 2 step 5's pattern, applied to a fresh database-port allocation. */\nconst MAX_FRESH_PORT_CANDIDATES = 5;\n/**\n* A name refused as \"already running\" is retried a few times, each attempt\n* first waiting out the holder: a cold server boot takes seconds, and a\n* crashed holder's lock is only released once proper-lockfile's ~10s stale\n* threshold passes. Bounded so a genuinely stuck name still fails visibly\n* inside the dev command's own startup budget.\n*/\nconst MAX_ALREADY_RUNNING_RETRIES = 2;\nconst ALREADY_RUNNING_POLLS = 24;\nconst ALREADY_RUNNING_POLL_MS = 500;\nconst NOT_INSTALLED_MESSAGE = \"local dev needs @prisma/dev for its local Postgres emulator — add \\\"prisma\\\" to your app's devDependencies.\";\nfunction maskCredentials(text) {\n\treturn text.replace(/:\\/\\/([^:@/\\s]+):[^@/\\s]+@/g, \"://$1:***@\");\n}\nfunction firstLine(text) {\n\treturn (text.split(\"\\n\")[0] ?? text).trim();\n}\nfunction isDatabaseRecord(value) {\n\treturn typeof value === \"object\" && value !== null && \"id\" in value && typeof value.id === \"string\" && \"instanceName\" in value && typeof value.instanceName === \"string\" && \"databasePort\" in value && typeof value.databasePort === \"number\" && \"url\" in value && typeof value.url === \"string\";\n}\nfunction isAppRecord(value) {\n\treturn typeof value === \"object\" && value !== null && \"databases\" in value && typeof value.databases === \"object\" && value.databases !== null && Object.values(value.databases).every(isDatabaseRecord);\n}\nfunction isAppsState(value) {\n\treturn typeof value === \"object\" && value !== null && Object.values(value).every(isAppRecord);\n}\nfunction isDatabaseBody(value) {\n\treturn typeof value === \"object\" && value !== null && \"prismaDevModulePath\" in value && typeof value.prismaDevModulePath === \"string\";\n}\nfunction isPrismaDevModule(value) {\n\treturn typeof value === \"object\" && value !== null && \"startPrismaDevServer\" in value && typeof value.startPrismaDevServer === \"function\";\n}\n/**\n* `@prisma/dev` exports a `PortNotAvailableError` class with a `readonly\n* port: number`, but the daemon dynamically imports the module from a\n* caller-given path while the class identity checked here would come from\n* whatever module graph THIS file's own bundle produced — two separate\n* instantiations of the same logical class, so `instanceof` doesn't match\n* across them (confirmed empirically: a real port conflict's `err\n* instanceof mod.PortNotAvailableError` is `false` even though the error IS\n* the port-conflict one). Duck-typing the documented shape — a `port`\n* number matching the candidate we just tried — is what actually survives\n* that boundary.\n*/\n/**\n* The port a start refusal is about, when it is one of THIS attempt's ports.\n* Duck-typed (`instanceof` fails across the dynamic-import boundary): every\n* `@prisma/dev` port refusal — not-available, requested-twice, and\n* belongs-to-another-server (its registry can claim a port no bind probe\n* sees) — carries the offending port as `.port`, and any of the four ports\n* we requested (database + the three aux listeners) can be the one refused.\n*/\nfunction portConflictOf(err, ports) {\n\tif (typeof err !== \"object\" || err === null || !(\"port\" in err)) return void 0;\n\tconst port = err.port;\n\treturn typeof port === \"number\" && ports.includes(port) ? port : void 0;\n}\nfunction isNameAlreadyTaken(err) {\n\treturn isStringKeyedRecord(err) && (err[\"name\"] === \"ServerAlreadyRunningError\" || err[\"name\"] === \"ServerStateAlreadyExistsError\");\n}\n/** The port of a postgres connection URL, when it parses as one. */\nfunction databasePortOf(connectionString) {\n\ttry {\n\t\tconst port = Number(new URL(connectionString).port);\n\t\treturn Number.isInteger(port) && port > 0 ? port : void 0;\n\t} catch {\n\t\treturn;\n\t}\n}\n/**\n* A dynamic `import()` failure's own message routinely names a SECOND path\n* (e.g. bun's \"Cannot find module '<target>' from '<importer>'\") — the\n* importer half is this daemon's own internal location, not anything the\n* caller gave us, and has no business in a response body. Rather than try\n* to scrub an arbitrary underlying message for every runtime's own error\n* phrasing, the resolution-failure case names only what the caller\n* supplied — the pinned message plus the given `prismaDevModulePath`, and\n* nothing else. (A DIFFERENT case — a module that resolves fine but whose\n* `startPrismaDevServer()` call itself fails — still surfaces its\n* underlying text verbatim, credential-masked, per spec § 2.)\n*/\nasync function importPrismaDev(prismaDevModulePath) {\n\tlet mod;\n\ttry {\n\t\tmod = await import(pathToFileURL(prismaDevModulePath).href);\n\t} catch {\n\t\tthrow new Error(`${NOT_INSTALLED_MESSAGE} (could not resolve \"${prismaDevModulePath}\")`);\n\t}\n\tif (!isPrismaDevModule(mod)) throw new Error(`${NOT_INSTALLED_MESSAGE} (\"${prismaDevModulePath}\" is not a @prisma/dev module)`);\n\treturn mod;\n}\nfunction isStringKeyedRecord(value) {\n\treturn typeof value === \"object\" && value !== null;\n}\nfunction isPrismaDevInternalStateModule(value) {\n\treturn isStringKeyedRecord(value) && typeof value[\"deleteServer\"] === \"function\" && typeof value[\"killServer\"] === \"function\" && typeof value[\"getServerStatus\"] === \"function\";\n}\nfunction readServerStatus(status) {\n\tif (!isStringKeyedRecord(status)) return {\n\t\tlive: false,\n\t\tpid: void 0,\n\t\turl: void 0,\n\t\tdatabasePort: void 0\n\t};\n\tconst exports = status[\"exports\"];\n\tconst database = isStringKeyedRecord(exports) ? exports[\"database\"] : void 0;\n\tconst url = isStringKeyedRecord(database) ? database[\"connectionString\"] : void 0;\n\tconst pid = status[\"pid\"];\n\tconst databasePort = status[\"databasePort\"];\n\treturn {\n\t\tlive: status[\"status\"] === \"running\" || status[\"status\"] === \"starting_up\",\n\t\tpid: typeof pid === \"number\" ? pid : void 0,\n\t\turl: typeof url === \"string\" ? url : void 0,\n\t\tdatabasePort: typeof databasePort === \"number\" ? databasePort : void 0\n\t};\n}\nasync function serverStatusOf(internalState, instanceName) {\n\ttry {\n\t\treturn readServerStatus(await internalState.getServerStatus(instanceName));\n\t} catch {\n\t\treturn {\n\t\t\tlive: false,\n\t\t\tpid: void 0,\n\t\t\turl: void 0,\n\t\t\tdatabasePort: void 0\n\t\t};\n\t}\n}\nconst CLOSE_SETTLE_ATTEMPTS = 40;\nconst CLOSE_SETTLE_DELAY_MS = 250;\n/** True once the named server's persisted state no longer claims it is live — the precondition for `deleteServer`, whose kill path targets the pid in that state, which for an in-daemon server is THIS DAEMON's own pid. */\nasync function settledAfterClose(internalState, instanceName) {\n\tfor (let attempt = 1; attempt <= CLOSE_SETTLE_ATTEMPTS; attempt += 1) {\n\t\tif (!(await serverStatusOf(internalState, instanceName)).live) return true;\n\t\tif (attempt < CLOSE_SETTLE_ATTEMPTS) await new Promise((resolve) => setTimeout(resolve, CLOSE_SETTLE_DELAY_MS));\n\t}\n\treturn false;\n}\n/**\n* `@prisma/dev`'s own package.json declares `./internal/state`, whose\n* `deleteServer(name)` actually removes a stateful server's persisted PGlite\n* data — `startPrismaDevServer`'s public surface only starts/closes a live\n* server, never deletes what a closed one left on disk. Resolved by reading\n* the SAME package's own `exports` map (walked up from the caller-given\n* entry path to find `@prisma/dev`'s `package.json`), never by guessing at\n* `dist/` file layout.\n*/\nasync function importPrismaDevInternalState(prismaDevModulePath) {\n\tlet dir = path.dirname(prismaDevModulePath);\n\tfor (;;) {\n\t\tconst pkgPath = path.join(dir, \"package.json\");\n\t\tif (fs.existsSync(pkgPath)) {\n\t\t\tconst pkg = JSON.parse(fs.readFileSync(pkgPath, \"utf8\"));\n\t\t\tif (isStringKeyedRecord(pkg) && pkg[\"name\"] === \"@prisma/dev\" && isStringKeyedRecord(pkg[\"exports\"])) {\n\t\t\t\tconst entry = pkg[\"exports\"][\"./internal/state\"];\n\t\t\t\tconst target = resolveExportTarget(entry);\n\t\t\t\tif (target === void 0) throw new Error(`\"@prisma/dev\" at \"${dir}\" does not declare an \"./internal/state\" export — cannot delete its persisted database data.`);\n\t\t\t\tconst mod = await import(pathToFileURL(path.join(dir, target)).href);\n\t\t\t\tif (isPrismaDevInternalStateModule(mod)) return mod;\n\t\t\t\tthrow new Error(`\"@prisma/dev\"'s \"./internal/state\" export at \"${dir}\" has no deleteServer.`);\n\t\t\t}\n\t\t}\n\t\tconst parent = path.dirname(dir);\n\t\tif (parent === dir) throw new Error(`could not find \"@prisma/dev\"'s package.json above \"${prismaDevModulePath}\".`);\n\t\tdir = parent;\n\t}\n}\nfunction resolveExportTarget(entry) {\n\tif (typeof entry === \"string\") return entry;\n\tif (!isStringKeyedRecord(entry)) return void 0;\n\tconst nested = entry[\"import\"] ?? entry[\"require\"] ?? entry[\"default\"];\n\tif (typeof nested === \"string\") return nested;\n\tif (isStringKeyedRecord(nested)) {\n\t\tconst def = nested[\"default\"];\n\t\tif (typeof def === \"string\") return def;\n\t}\n}\nfunction parseArgs(argv) {\n\tlet port;\n\tlet stateDir;\n\tfor (let i = 0; i < argv.length; i++) if (argv[i] === \"--port\") port = Number(argv[i + 1]);\n\telse if (argv[i] === \"--state-dir\") stateDir = argv[i + 1];\n\tif (port === void 0 || Number.isNaN(port)) throw new Error(\"postgres-main: --port <n> is required\");\n\tif (stateDir === void 0) throw new Error(\"postgres-main: --state-dir <dir> is required\");\n\treturn {\n\t\tport,\n\t\tstateDir\n\t};\n}\nfunction readBody(req) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst chunks = [];\n\t\treq.on(\"data\", (chunk) => chunks.push(chunk));\n\t\treq.on(\"end\", () => resolve(Buffer.concat(chunks)));\n\t\treq.on(\"error\", reject);\n\t});\n}\nfunction main() {\n\tconst { port, stateDir } = parseArgs(process.argv.slice(2));\n\tconst ownVersion = readOwnVersion();\n\tconst appsJsonPath = path.join(stateDir, \"apps.json\");\n\tconst stateFile = new StateFile(appsJsonPath, APPS_STATE_MODE);\n\tlet state = {};\n\tconst runtimes = /* @__PURE__ */ new Map();\n\t/**\n\t* Server starts run ONE AT A TIME. `@prisma/dev`'s start is not\n\t* concurrency-safe within a process: two simultaneous calls pick their\n\t* ports without seeing each other and one fails with a port refusal\n\t* (verified directly — two concurrent starts with distinct, pinned\n\t* database ports fail; the same two started in sequence both succeed).\n\t* The daemon issues concurrent starts whenever an app converges more than\n\t* one database, which is what produced the port refusals, the retries\n\t* whose half-started servers held their own name's lock, and every\n\t* \"already running\" failure downstream of that.\n\t*/\n\tlet startQueue = Promise.resolve();\n\tfunction serializeStart(run) {\n\t\tconst next = startQueue.then(run, run);\n\t\tstartQueue = next.then(() => void 0, () => void 0);\n\t\treturn next;\n\t}\n\tfunction schedulePersist() {\n\t\tstateFile.write(state);\n\t}\n\tfunction getOrCreateApp(app) {\n\t\tlet appRec = state[app];\n\t\tif (!appRec) {\n\t\t\tappRec = { databases: {} };\n\t\t\tstate[app] = appRec;\n\t\t}\n\t\treturn appRec;\n\t}\n\tfunction usedDatabasePorts() {\n\t\tconst ports = /* @__PURE__ */ new Set();\n\t\tfor (const appRec of Object.values(state)) for (const db of Object.values(appRec.databases)) ports.add(db.databasePort);\n\t\treturn ports;\n\t}\n\tasync function smallestUnusedDatabasePort(min, alsoExclude = /* @__PURE__ */ new Set()) {\n\t\treturn getPort({\n\t\t\tport: portNumbers(min, MAX_DATABASE_PORT),\n\t\t\texclude: [...usedDatabasePorts(), ...alsoExclude]\n\t\t});\n\t}\n\tconst inflightEnsures = /* @__PURE__ */ new Map();\n\t/** Concurrent PUTs for the same database coalesce onto one start — a second `startPrismaDevServer` for a name whose first start is still booting fails as \"already running\". */\n\tfunction ensureDatabase(app, id, prismaDevModulePath) {\n\t\tconst instanceName = instanceNameFor(app, id);\n\t\tconst inflight = inflightEnsures.get(instanceName);\n\t\tif (inflight) return inflight;\n\t\tconst run = ensureDatabaseSerialized(app, id, prismaDevModulePath, instanceName).finally(() => {\n\t\t\tinflightEnsures.delete(instanceName);\n\t\t});\n\t\tinflightEnsures.set(instanceName, run);\n\t\treturn run;\n\t}\n\tasync function ensureDatabaseSerialized(app, id, prismaDevModulePath, instanceName) {\n\t\tconst appRec = getOrCreateApp(app);\n\t\tconst existingRecord = appRec.databases[id];\n\t\tconst runningServer = runtimes.get(instanceName);\n\t\tif (existingRecord && runningServer) return { url: existingRecord.url };\n\t\tconst prismaDev = await importPrismaDev(prismaDevModulePath);\n\t\tconst internalState = await importPrismaDevInternalState(prismaDevModulePath);\n\t\tconst recorded = await serverStatusOf(internalState, instanceName);\n\t\tif (recorded.live && recorded.pid !== void 0 && isPidAlive(recorded.pid)) {\n\t\t\tif (recorded.url !== void 0) {\n\t\t\t\tappRec.databases[id] = {\n\t\t\t\t\tid,\n\t\t\t\t\tinstanceName,\n\t\t\t\t\tdatabasePort: recorded.databasePort ?? databasePortOf(recorded.url) ?? MIN_DATABASE_PORT,\n\t\t\t\t\turl: recorded.url\n\t\t\t\t};\n\t\t\t\tschedulePersist();\n\t\t\t\treturn { url: recorded.url };\n\t\t\t}\n\t\t} else if (recorded.live) await internalState.killServer(instanceName).catch(() => void 0);\n\t\tconst isFreshAllocation = existingRecord === void 0;\n\t\tlet dbPort = existingRecord?.databasePort ?? await smallestUnusedDatabasePort(MIN_DATABASE_PORT);\n\t\tconst conflicted = /* @__PURE__ */ new Set();\n\t\tlet alreadyRunningRetries = 0;\n\t\tfor (let attempt = 1;; attempt++) try {\n\t\t\tconst server = await serializeStart(() => prismaDev.startPrismaDevServer({\n\t\t\t\tname: instanceName,\n\t\t\t\tdatabasePort: dbPort,\n\t\t\t\tpersistenceMode: \"stateful\"\n\t\t\t}));\n\t\t\tconst url = server.database.connectionString;\n\t\t\truntimes.set(instanceName, server);\n\t\t\tappRec.databases[id] = {\n\t\t\t\tid,\n\t\t\t\tinstanceName,\n\t\t\t\tdatabasePort: dbPort,\n\t\t\t\turl\n\t\t\t};\n\t\t\tschedulePersist();\n\t\t\treturn { url };\n\t\t} catch (err) {\n\t\t\tif (isNameAlreadyTaken(err) && alreadyRunningRetries < MAX_ALREADY_RUNNING_RETRIES) {\n\t\t\t\talreadyRunningRetries += 1;\n\t\t\t\tfor (let poll = 1; poll <= ALREADY_RUNNING_POLLS; poll += 1) {\n\t\t\t\t\tconst now = await serverStatusOf(internalState, instanceName);\n\t\t\t\t\tif (now.live && now.pid !== void 0 && isPidAlive(now.pid) && now.url !== void 0) {\n\t\t\t\t\t\tappRec.databases[id] = {\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tinstanceName,\n\t\t\t\t\t\t\tdatabasePort: now.databasePort ?? databasePortOf(now.url) ?? dbPort,\n\t\t\t\t\t\t\turl: now.url\n\t\t\t\t\t\t};\n\t\t\t\t\t\tschedulePersist();\n\t\t\t\t\t\treturn { url: now.url };\n\t\t\t\t\t}\n\t\t\t\t\tif (now.live && (now.pid === void 0 || !isPidAlive(now.pid))) {\n\t\t\t\t\t\tawait internalState.killServer(instanceName).catch(() => void 0);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, ALREADY_RUNNING_POLL_MS));\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst conflictPort = portConflictOf(err, [dbPort]);\n\t\t\tif (!(conflictPort !== void 0 && attempt < MAX_FRESH_PORT_CANDIDATES && (conflictPort !== dbPort || isFreshAllocation))) {\n\t\t\t\tconst reason = err instanceof Error ? err.message : String(err);\n\t\t\t\tthrow new Error(`postgres emulator failed to start database \"${instanceName}\" on port ${String(dbPort)}: ${maskCredentials(firstLine(reason))}`);\n\t\t\t}\n\t\t\tconflicted.add(conflictPort);\n\t\t\tif (conflictPort === dbPort) dbPort = await smallestUnusedDatabasePort(dbPort + 1, conflicted);\n\t\t}\n\t}\n\tasync function deleteApp(app, prismaDevModulePathHint) {\n\t\tconst appRec = state[app];\n\t\tif (!appRec) return;\n\t\tconst entries = Object.values(appRec.databases);\n\t\tfor (const db of entries) {\n\t\t\tconst server = runtimes.get(db.instanceName);\n\t\t\tif (server) {\n\t\t\t\tawait server.close().catch(() => void 0);\n\t\t\t\truntimes.delete(db.instanceName);\n\t\t\t}\n\t\t}\n\t\tif (entries.length > 0 && prismaDevModulePathHint) {\n\t\t\tconst internalState = await importPrismaDevInternalState(prismaDevModulePathHint);\n\t\t\tfor (const db of entries) {\n\t\t\t\tif (!runtimes.has(db.instanceName)) {\n\t\t\t\t\tif ((await serverStatusOf(internalState, db.instanceName)).pid !== process.pid) await internalState.killServer(db.instanceName).catch(() => void 0);\n\t\t\t\t}\n\t\t\t\tif (!await settledAfterClose(internalState, db.instanceName)) {\n\t\t\t\t\tconsole.error(`postgres-main: server \"${db.instanceName}\" still reports running after close — leaving its persisted data in place instead of risking a self-kill.`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tawait internalState.deleteServer(db.instanceName);\n\t\t\t}\n\t\t}\n\t\tdelete state[app];\n\t\tschedulePersist();\n\t}\n\tfunction json(res, status, body) {\n\t\tres.writeHead(status, { \"content-type\": \"application/json\" });\n\t\tres.end(JSON.stringify(body));\n\t}\n\tfunction text(res, status, body) {\n\t\tres.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\" });\n\t\tres.end(body);\n\t}\n\tfunction badSegment(res, segment) {\n\t\ttext(res, 400, `invalid path segment \"${segment}\": must match /^[a-z0-9][a-z0-9-]*$/ and be at most 63 characters`);\n\t}\n\tfunction databaseView(db) {\n\t\treturn {\n\t\t\tid: db.id,\n\t\t\turl: db.url,\n\t\t\tinstanceName: db.instanceName,\n\t\t\tdatabasePort: db.databasePort\n\t\t};\n\t}\n\t/** The most recently observed `prismaDevModulePath` for any database of `app` — DELETE has no body of its own to carry one. */\n\tconst recentPrismaDevModulePath = /* @__PURE__ */ new Map();\n\tfunction lastKnownPrismaDevModulePath(app) {\n\t\treturn recentPrismaDevModulePath.get(app);\n\t}\n\tasync function handleRequest(req, res) {\n\t\tconst url = new URL(req.url ?? \"/\", `http://127.0.0.1:${String(port)}`);\n\t\tconst method = req.method ?? \"GET\";\n\t\tconst segments = url.pathname.split(\"/\").filter((s) => s.length > 0).map((s) => decodeURIComponent(s));\n\t\tif (method === \"GET\" && segments.length === 1 && segments[0] === \"health\") return json(res, 200, { version: ownVersion });\n\t\tif (segments[0] === \"apps\" && segments.length >= 2) {\n\t\t\tconst app = segments[1];\n\t\t\tif (app === void 0 || !isValidSegment(app)) return badSegment(res, app ?? \"\");\n\t\t\tif (method === \"PUT\" && segments.length === 4 && segments[2] === \"databases\") {\n\t\t\t\tconst id = segments[3];\n\t\t\t\tif (id === void 0 || !isValidSegment(id)) return badSegment(res, id ?? \"\");\n\t\t\t\tconst raw = await readBody(req);\n\t\t\t\tlet parsed;\n\t\t\t\ttry {\n\t\t\t\t\tparsed = JSON.parse(raw.toString(\"utf8\"));\n\t\t\t\t} catch {\n\t\t\t\t\treturn text(res, 400, \"malformed JSON body\");\n\t\t\t\t}\n\t\t\t\tif (!isDatabaseBody(parsed)) return text(res, 400, \"malformed database body: expected { \\\"prismaDevModulePath\\\": string }\");\n\t\t\t\trecentPrismaDevModulePath.set(app, parsed.prismaDevModulePath);\n\t\t\t\treturn json(res, 200, await ensureDatabase(app, id, parsed.prismaDevModulePath));\n\t\t\t}\n\t\t\tif (method === \"GET\" && segments.length === 3 && segments[2] === \"databases\") {\n\t\t\t\tconst appRec = state[app];\n\t\t\t\treturn json(res, 200, appRec ? Object.values(appRec.databases).map(databaseView) : []);\n\t\t\t}\n\t\t\tif (method === \"DELETE\" && segments.length === 2) {\n\t\t\t\tawait deleteApp(app, lastKnownPrismaDevModulePath(app));\n\t\t\t\tres.writeHead(204);\n\t\t\t\tres.end();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tres.writeHead(404);\n\t\tres.end();\n\t}\n\tconst server = http.createServer((req, res) => {\n\t\thandleRequest(req, res).catch((err) => {\n\t\t\tif (!res.headersSent) res.writeHead(500, { \"content-type\": \"text/plain\" });\n\t\t\tres.end(err instanceof Error ? maskCredentials(err.message) : String(err));\n\t\t});\n\t});\n\tasync function shutdown() {\n\t\tfor (const server of runtimes.values()) await server.close().catch(() => void 0);\n\t\tawait stateFile.flush();\n\t\tserver.close();\n\t\tprocess.exit(0);\n\t}\n\tprocess.on(\"SIGTERM\", () => void shutdown());\n\tprocess.on(\"SIGINT\", () => void shutdown());\n\tprocess.on(\"unhandledRejection\", (reason) => {\n\t\tconsole.error(\"postgres-main: unhandled rejection from background work:\", reason instanceof Error ? maskCredentials(reason.stack ?? reason.message) : reason);\n\t});\n\tprocess.on(\"uncaughtException\", (err) => {\n\t\tconsole.error(\"postgres-main: uncaught exception from background work:\", err instanceof Error ? maskCredentials(err.stack ?? err.message) : err);\n\t});\n\treadJsonFile(appsJsonPath, isAppsState).then((loaded) => {\n\t\tif (loaded) state = loaded;\n\t\tserver.listen(port, \"127.0.0.1\", () => {\n\t\t\tconsole.log(`[dev-emulators] postgres-main listening on 127.0.0.1:${String(port)}`);\n\t\t});\n\t}).catch((err) => {\n\t\tconsole.error(\"postgres-main: failed to load state\", err);\n\t\tprocess.exit(1);\n\t});\n}\nmain();\n//#endregion\nexport {};\n\n//# sourceMappingURL=postgres-main.mjs.map"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,KAAK,SAAS;CACtB,MAAM,YAAY,QAAQ,YAAY,CAAC,CAAC,QAAQ,cAAc,GAAG,CAAC,CAAC,QAAQ,UAAU,GAAG;CACxF,IAAI,QAAQ;CACZ,IAAI,MAAM,UAAU;CACpB,OAAO,QAAQ,OAAO,UAAU,WAAW,KAAK;CAChD,OAAO,MAAM,SAAS,UAAU,MAAM,OAAO,KAAK;CAClD,OAAO,UAAU,MAAM,OAAO,GAAG;AAClC;AACA,SAAS,gBAAgB,KAAK,IAAI;CACjC,OAAO,SAAS,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,IAAI,MAAM,GAAG,EAAE;AACpD;;;;;;;;;;;;;;;;;;ACRA,MAAM,oBAAoB;AAC1B,MAAM,oBA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417
|
+
function isErrnoException(err) {
|
|
1418
|
+
return err instanceof Error && "code" in err;
|
|
1419
|
+
}
|
|
1417
1420
|
function isPackageJson(value) {
|
|
1418
1421
|
return typeof value === "object" && value !== null && "version" in value && typeof value.version === "string";
|
|
1419
1422
|
}
|
|
@@ -1426,6 +1429,16 @@ function readOwnVersion() {
|
|
|
1426
1429
|
if (!isPackageJson(parsed)) throw new Error(`could not read a version string from ${pkgPath}`);
|
|
1427
1430
|
return parsed.version;
|
|
1428
1431
|
}
|
|
1432
|
+
/** `process.kill(pid, 0)` existence probe — true unless the pid is provably gone (ESRCH). */
|
|
1433
|
+
function isPidAlive(pid) {
|
|
1434
|
+
try {
|
|
1435
|
+
process.kill(pid, 0);
|
|
1436
|
+
return true;
|
|
1437
|
+
} catch (err) {
|
|
1438
|
+
if (isErrnoException(err) && err.code === "EPERM") return true;
|
|
1439
|
+
return false;
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1429
1442
|
/**
|
|
1430
1443
|
* API hygiene shared by both daemons (local-dev spec § 2): every `<app>`,
|
|
1431
1444
|
* `<id>`, and `<name>` path segment must match this shape or the request is
|
|
@@ -1436,6 +1449,6 @@ function isValidSegment(segment) {
|
|
|
1436
1449
|
return segment.length <= 63 && SEGMENT_RE.test(segment);
|
|
1437
1450
|
}
|
|
1438
1451
|
//#endregion
|
|
1439
|
-
export { readOwnVersion as i,
|
|
1452
|
+
export { readOwnVersion as a, readJsonFile as i, isPidAlive as n, isValidSegment as r, StateFile as t };
|
|
1440
1453
|
|
|
1441
|
-
//# sourceMappingURL=segments-NpKN-46R-
|
|
1454
|
+
//# sourceMappingURL=segments-NpKN-46R-C_LQ2urs.mjs.map
|