@prisma/cli-init 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,3069 @@
1
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
+ import {
3
+ Engine,
4
+ encodeAPIKey,
5
+ ensureDirectory,
6
+ getDataDirPath,
7
+ integer,
8
+ literal,
9
+ minLength,
10
+ minValue,
11
+ number,
12
+ object,
13
+ optional,
14
+ parseJson,
15
+ pipe,
16
+ readDirectoryNames,
17
+ readFileAsText,
18
+ safeParse,
19
+ streamAsTextTo,
20
+ string,
21
+ url,
22
+ withResolvers,
23
+ y
24
+ } from "./chunk-ASMCGOOW.js";
1
25
  import {
2
26
  credentialsFile,
3
27
  poll,
4
28
  printPpgInitOutput,
5
29
  requestOrThrow,
6
30
  successMessage
7
- } from "./chunk-CMRCQXCF.js";
31
+ } from "./chunk-SORRSNB3.js";
32
+ import {
33
+ __commonJS,
34
+ __require,
35
+ __toESM
36
+ } from "./chunk-YX4UTTNJ.js";
37
+
38
+ // ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/polyfills.js
39
+ var require_polyfills = __commonJS({
40
+ "../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/polyfills.js"(exports, module) {
41
+ "use strict";
42
+ var constants = __require("constants");
43
+ var origCwd = process.cwd;
44
+ var cwd = null;
45
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
46
+ process.cwd = function() {
47
+ if (!cwd)
48
+ cwd = origCwd.call(process);
49
+ return cwd;
50
+ };
51
+ try {
52
+ process.cwd();
53
+ } catch (er) {
54
+ }
55
+ if (typeof process.chdir === "function") {
56
+ chdir = process.chdir;
57
+ process.chdir = function(d2) {
58
+ cwd = null;
59
+ chdir.call(process, d2);
60
+ };
61
+ if (Object.setPrototypeOf)
62
+ Object.setPrototypeOf(process.chdir, chdir);
63
+ }
64
+ var chdir;
65
+ module.exports = patch;
66
+ function patch(fs3) {
67
+ if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
68
+ patchLchmod(fs3);
69
+ }
70
+ if (!fs3.lutimes) {
71
+ patchLutimes(fs3);
72
+ }
73
+ fs3.chown = chownFix(fs3.chown);
74
+ fs3.fchown = chownFix(fs3.fchown);
75
+ fs3.lchown = chownFix(fs3.lchown);
76
+ fs3.chmod = chmodFix(fs3.chmod);
77
+ fs3.fchmod = chmodFix(fs3.fchmod);
78
+ fs3.lchmod = chmodFix(fs3.lchmod);
79
+ fs3.chownSync = chownFixSync(fs3.chownSync);
80
+ fs3.fchownSync = chownFixSync(fs3.fchownSync);
81
+ fs3.lchownSync = chownFixSync(fs3.lchownSync);
82
+ fs3.chmodSync = chmodFixSync(fs3.chmodSync);
83
+ fs3.fchmodSync = chmodFixSync(fs3.fchmodSync);
84
+ fs3.lchmodSync = chmodFixSync(fs3.lchmodSync);
85
+ fs3.stat = statFix(fs3.stat);
86
+ fs3.fstat = statFix(fs3.fstat);
87
+ fs3.lstat = statFix(fs3.lstat);
88
+ fs3.statSync = statFixSync(fs3.statSync);
89
+ fs3.fstatSync = statFixSync(fs3.fstatSync);
90
+ fs3.lstatSync = statFixSync(fs3.lstatSync);
91
+ if (fs3.chmod && !fs3.lchmod) {
92
+ fs3.lchmod = function(path3, mode, cb) {
93
+ if (cb)
94
+ process.nextTick(cb);
95
+ };
96
+ fs3.lchmodSync = function() {
97
+ };
98
+ }
99
+ if (fs3.chown && !fs3.lchown) {
100
+ fs3.lchown = function(path3, uid, gid, cb) {
101
+ if (cb)
102
+ process.nextTick(cb);
103
+ };
104
+ fs3.lchownSync = function() {
105
+ };
106
+ }
107
+ if (platform === "win32") {
108
+ fs3.rename = typeof fs3.rename !== "function" ? fs3.rename : function(fs$rename) {
109
+ function rename(from, to, cb) {
110
+ var start = Date.now();
111
+ var backoff = 0;
112
+ fs$rename(from, to, function CB(er) {
113
+ if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 6e4) {
114
+ setTimeout(function() {
115
+ fs3.stat(to, function(stater, st) {
116
+ if (stater && stater.code === "ENOENT")
117
+ fs$rename(from, to, CB);
118
+ else
119
+ cb(er);
120
+ });
121
+ }, backoff);
122
+ if (backoff < 100)
123
+ backoff += 10;
124
+ return;
125
+ }
126
+ if (cb)
127
+ cb(er);
128
+ });
129
+ }
130
+ if (Object.setPrototypeOf)
131
+ Object.setPrototypeOf(rename, fs$rename);
132
+ return rename;
133
+ }(fs3.rename);
134
+ }
135
+ fs3.read = typeof fs3.read !== "function" ? fs3.read : function(fs$read) {
136
+ function read(fd, buffer, offset, length, position, callback_) {
137
+ var callback;
138
+ if (callback_ && typeof callback_ === "function") {
139
+ var eagCounter = 0;
140
+ callback = function(er, _, __) {
141
+ if (er && er.code === "EAGAIN" && eagCounter < 10) {
142
+ eagCounter++;
143
+ return fs$read.call(fs3, fd, buffer, offset, length, position, callback);
144
+ }
145
+ callback_.apply(this, arguments);
146
+ };
147
+ }
148
+ return fs$read.call(fs3, fd, buffer, offset, length, position, callback);
149
+ }
150
+ if (Object.setPrototypeOf)
151
+ Object.setPrototypeOf(read, fs$read);
152
+ return read;
153
+ }(fs3.read);
154
+ fs3.readSync = typeof fs3.readSync !== "function" ? fs3.readSync : /* @__PURE__ */ function(fs$readSync) {
155
+ return function(fd, buffer, offset, length, position) {
156
+ var eagCounter = 0;
157
+ while (true) {
158
+ try {
159
+ return fs$readSync.call(fs3, fd, buffer, offset, length, position);
160
+ } catch (er) {
161
+ if (er.code === "EAGAIN" && eagCounter < 10) {
162
+ eagCounter++;
163
+ continue;
164
+ }
165
+ throw er;
166
+ }
167
+ }
168
+ };
169
+ }(fs3.readSync);
170
+ function patchLchmod(fs4) {
171
+ fs4.lchmod = function(path3, mode, callback) {
172
+ fs4.open(
173
+ path3,
174
+ constants.O_WRONLY | constants.O_SYMLINK,
175
+ mode,
176
+ function(err, fd) {
177
+ if (err) {
178
+ if (callback)
179
+ callback(err);
180
+ return;
181
+ }
182
+ fs4.fchmod(fd, mode, function(err2) {
183
+ fs4.close(fd, function(err22) {
184
+ if (callback)
185
+ callback(err2 || err22);
186
+ });
187
+ });
188
+ }
189
+ );
190
+ };
191
+ fs4.lchmodSync = function(path3, mode) {
192
+ var fd = fs4.openSync(path3, constants.O_WRONLY | constants.O_SYMLINK, mode);
193
+ var threw = true;
194
+ var ret;
195
+ try {
196
+ ret = fs4.fchmodSync(fd, mode);
197
+ threw = false;
198
+ } finally {
199
+ if (threw) {
200
+ try {
201
+ fs4.closeSync(fd);
202
+ } catch (er) {
203
+ }
204
+ } else {
205
+ fs4.closeSync(fd);
206
+ }
207
+ }
208
+ return ret;
209
+ };
210
+ }
211
+ function patchLutimes(fs4) {
212
+ if (constants.hasOwnProperty("O_SYMLINK") && fs4.futimes) {
213
+ fs4.lutimes = function(path3, at, mt, cb) {
214
+ fs4.open(path3, constants.O_SYMLINK, function(er, fd) {
215
+ if (er) {
216
+ if (cb)
217
+ cb(er);
218
+ return;
219
+ }
220
+ fs4.futimes(fd, at, mt, function(er2) {
221
+ fs4.close(fd, function(er22) {
222
+ if (cb)
223
+ cb(er2 || er22);
224
+ });
225
+ });
226
+ });
227
+ };
228
+ fs4.lutimesSync = function(path3, at, mt) {
229
+ var fd = fs4.openSync(path3, constants.O_SYMLINK);
230
+ var ret;
231
+ var threw = true;
232
+ try {
233
+ ret = fs4.futimesSync(fd, at, mt);
234
+ threw = false;
235
+ } finally {
236
+ if (threw) {
237
+ try {
238
+ fs4.closeSync(fd);
239
+ } catch (er) {
240
+ }
241
+ } else {
242
+ fs4.closeSync(fd);
243
+ }
244
+ }
245
+ return ret;
246
+ };
247
+ } else if (fs4.futimes) {
248
+ fs4.lutimes = function(_a, _b, _c, cb) {
249
+ if (cb)
250
+ process.nextTick(cb);
251
+ };
252
+ fs4.lutimesSync = function() {
253
+ };
254
+ }
255
+ }
256
+ function chmodFix(orig) {
257
+ if (!orig)
258
+ return orig;
259
+ return function(target, mode, cb) {
260
+ return orig.call(fs3, target, mode, function(er) {
261
+ if (chownErOk(er))
262
+ er = null;
263
+ if (cb)
264
+ cb.apply(this, arguments);
265
+ });
266
+ };
267
+ }
268
+ function chmodFixSync(orig) {
269
+ if (!orig)
270
+ return orig;
271
+ return function(target, mode) {
272
+ try {
273
+ return orig.call(fs3, target, mode);
274
+ } catch (er) {
275
+ if (!chownErOk(er))
276
+ throw er;
277
+ }
278
+ };
279
+ }
280
+ function chownFix(orig) {
281
+ if (!orig)
282
+ return orig;
283
+ return function(target, uid, gid, cb) {
284
+ return orig.call(fs3, target, uid, gid, function(er) {
285
+ if (chownErOk(er))
286
+ er = null;
287
+ if (cb)
288
+ cb.apply(this, arguments);
289
+ });
290
+ };
291
+ }
292
+ function chownFixSync(orig) {
293
+ if (!orig)
294
+ return orig;
295
+ return function(target, uid, gid) {
296
+ try {
297
+ return orig.call(fs3, target, uid, gid);
298
+ } catch (er) {
299
+ if (!chownErOk(er))
300
+ throw er;
301
+ }
302
+ };
303
+ }
304
+ function statFix(orig) {
305
+ if (!orig)
306
+ return orig;
307
+ return function(target, options, cb) {
308
+ if (typeof options === "function") {
309
+ cb = options;
310
+ options = null;
311
+ }
312
+ function callback(er, stats) {
313
+ if (stats) {
314
+ if (stats.uid < 0)
315
+ stats.uid += 4294967296;
316
+ if (stats.gid < 0)
317
+ stats.gid += 4294967296;
318
+ }
319
+ if (cb)
320
+ cb.apply(this, arguments);
321
+ }
322
+ return options ? orig.call(fs3, target, options, callback) : orig.call(fs3, target, callback);
323
+ };
324
+ }
325
+ function statFixSync(orig) {
326
+ if (!orig)
327
+ return orig;
328
+ return function(target, options) {
329
+ var stats = options ? orig.call(fs3, target, options) : orig.call(fs3, target);
330
+ if (stats) {
331
+ if (stats.uid < 0)
332
+ stats.uid += 4294967296;
333
+ if (stats.gid < 0)
334
+ stats.gid += 4294967296;
335
+ }
336
+ return stats;
337
+ };
338
+ }
339
+ function chownErOk(er) {
340
+ if (!er)
341
+ return true;
342
+ if (er.code === "ENOSYS")
343
+ return true;
344
+ var nonroot = !process.getuid || process.getuid() !== 0;
345
+ if (nonroot) {
346
+ if (er.code === "EINVAL" || er.code === "EPERM")
347
+ return true;
348
+ }
349
+ return false;
350
+ }
351
+ }
352
+ }
353
+ });
354
+
355
+ // ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/legacy-streams.js
356
+ var require_legacy_streams = __commonJS({
357
+ "../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/legacy-streams.js"(exports, module) {
358
+ "use strict";
359
+ var Stream = __require("stream").Stream;
360
+ module.exports = legacy;
361
+ function legacy(fs3) {
362
+ return {
363
+ ReadStream,
364
+ WriteStream
365
+ };
366
+ function ReadStream(path3, options) {
367
+ if (!(this instanceof ReadStream))
368
+ return new ReadStream(path3, options);
369
+ Stream.call(this);
370
+ var self = this;
371
+ this.path = path3;
372
+ this.fd = null;
373
+ this.readable = true;
374
+ this.paused = false;
375
+ this.flags = "r";
376
+ this.mode = 438;
377
+ this.bufferSize = 64 * 1024;
378
+ options = options || {};
379
+ var keys = Object.keys(options);
380
+ for (var index = 0, length = keys.length; index < length; index++) {
381
+ var key = keys[index];
382
+ this[key] = options[key];
383
+ }
384
+ if (this.encoding)
385
+ this.setEncoding(this.encoding);
386
+ if (this.start !== void 0) {
387
+ if ("number" !== typeof this.start) {
388
+ throw TypeError("start must be a Number");
389
+ }
390
+ if (this.end === void 0) {
391
+ this.end = Infinity;
392
+ } else if ("number" !== typeof this.end) {
393
+ throw TypeError("end must be a Number");
394
+ }
395
+ if (this.start > this.end) {
396
+ throw new Error("start must be <= end");
397
+ }
398
+ this.pos = this.start;
399
+ }
400
+ if (this.fd !== null) {
401
+ process.nextTick(function() {
402
+ self._read();
403
+ });
404
+ return;
405
+ }
406
+ fs3.open(this.path, this.flags, this.mode, function(err, fd) {
407
+ if (err) {
408
+ self.emit("error", err);
409
+ self.readable = false;
410
+ return;
411
+ }
412
+ self.fd = fd;
413
+ self.emit("open", fd);
414
+ self._read();
415
+ });
416
+ }
417
+ function WriteStream(path3, options) {
418
+ if (!(this instanceof WriteStream))
419
+ return new WriteStream(path3, options);
420
+ Stream.call(this);
421
+ this.path = path3;
422
+ this.fd = null;
423
+ this.writable = true;
424
+ this.flags = "w";
425
+ this.encoding = "binary";
426
+ this.mode = 438;
427
+ this.bytesWritten = 0;
428
+ options = options || {};
429
+ var keys = Object.keys(options);
430
+ for (var index = 0, length = keys.length; index < length; index++) {
431
+ var key = keys[index];
432
+ this[key] = options[key];
433
+ }
434
+ if (this.start !== void 0) {
435
+ if ("number" !== typeof this.start) {
436
+ throw TypeError("start must be a Number");
437
+ }
438
+ if (this.start < 0) {
439
+ throw new Error("start must be >= zero");
440
+ }
441
+ this.pos = this.start;
442
+ }
443
+ this.busy = false;
444
+ this._queue = [];
445
+ if (this.fd === null) {
446
+ this._open = fs3.open;
447
+ this._queue.push([this._open, this.path, this.flags, this.mode, void 0]);
448
+ this.flush();
449
+ }
450
+ }
451
+ }
452
+ }
453
+ });
454
+
455
+ // ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/clone.js
456
+ var require_clone = __commonJS({
457
+ "../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/clone.js"(exports, module) {
458
+ "use strict";
459
+ module.exports = clone;
460
+ var getPrototypeOf = Object.getPrototypeOf || function(obj) {
461
+ return obj.__proto__;
462
+ };
463
+ function clone(obj) {
464
+ if (obj === null || typeof obj !== "object")
465
+ return obj;
466
+ if (obj instanceof Object)
467
+ var copy = { __proto__: getPrototypeOf(obj) };
468
+ else
469
+ var copy = /* @__PURE__ */ Object.create(null);
470
+ Object.getOwnPropertyNames(obj).forEach(function(key) {
471
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
472
+ });
473
+ return copy;
474
+ }
475
+ }
476
+ });
477
+
478
+ // ../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js
479
+ var require_graceful_fs = __commonJS({
480
+ "../../node_modules/.pnpm/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js"(exports, module) {
481
+ "use strict";
482
+ var fs3 = __require("fs");
483
+ var polyfills = require_polyfills();
484
+ var legacy = require_legacy_streams();
485
+ var clone = require_clone();
486
+ var util = __require("util");
487
+ var gracefulQueue;
488
+ var previousSymbol;
489
+ if (typeof Symbol === "function" && typeof Symbol.for === "function") {
490
+ gracefulQueue = Symbol.for("graceful-fs.queue");
491
+ previousSymbol = Symbol.for("graceful-fs.previous");
492
+ } else {
493
+ gracefulQueue = "___graceful-fs.queue";
494
+ previousSymbol = "___graceful-fs.previous";
495
+ }
496
+ function noop() {
497
+ }
498
+ function publishQueue(context, queue2) {
499
+ Object.defineProperty(context, gracefulQueue, {
500
+ get: function() {
501
+ return queue2;
502
+ }
503
+ });
504
+ }
505
+ var debug = noop;
506
+ if (util.debuglog)
507
+ debug = util.debuglog("gfs4");
508
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
509
+ debug = function() {
510
+ var m = util.format.apply(util, arguments);
511
+ m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
512
+ console.error(m);
513
+ };
514
+ if (!fs3[gracefulQueue]) {
515
+ queue = global[gracefulQueue] || [];
516
+ publishQueue(fs3, queue);
517
+ fs3.close = function(fs$close) {
518
+ function close(fd, cb) {
519
+ return fs$close.call(fs3, fd, function(err) {
520
+ if (!err) {
521
+ resetQueue();
522
+ }
523
+ if (typeof cb === "function")
524
+ cb.apply(this, arguments);
525
+ });
526
+ }
527
+ Object.defineProperty(close, previousSymbol, {
528
+ value: fs$close
529
+ });
530
+ return close;
531
+ }(fs3.close);
532
+ fs3.closeSync = function(fs$closeSync) {
533
+ function closeSync(fd) {
534
+ fs$closeSync.apply(fs3, arguments);
535
+ resetQueue();
536
+ }
537
+ Object.defineProperty(closeSync, previousSymbol, {
538
+ value: fs$closeSync
539
+ });
540
+ return closeSync;
541
+ }(fs3.closeSync);
542
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
543
+ process.on("exit", function() {
544
+ debug(fs3[gracefulQueue]);
545
+ __require("assert").equal(fs3[gracefulQueue].length, 0);
546
+ });
547
+ }
548
+ }
549
+ var queue;
550
+ if (!global[gracefulQueue]) {
551
+ publishQueue(global, fs3[gracefulQueue]);
552
+ }
553
+ module.exports = patch(clone(fs3));
554
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs3.__patched) {
555
+ module.exports = patch(fs3);
556
+ fs3.__patched = true;
557
+ }
558
+ function patch(fs4) {
559
+ polyfills(fs4);
560
+ fs4.gracefulify = patch;
561
+ fs4.createReadStream = createReadStream;
562
+ fs4.createWriteStream = createWriteStream;
563
+ var fs$readFile = fs4.readFile;
564
+ fs4.readFile = readFile;
565
+ function readFile(path3, options, cb) {
566
+ if (typeof options === "function")
567
+ cb = options, options = null;
568
+ return go$readFile(path3, options, cb);
569
+ function go$readFile(path4, options2, cb2, startTime) {
570
+ return fs$readFile(path4, options2, function(err) {
571
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
572
+ enqueue([go$readFile, [path4, options2, cb2], err, startTime || Date.now(), Date.now()]);
573
+ else {
574
+ if (typeof cb2 === "function")
575
+ cb2.apply(this, arguments);
576
+ }
577
+ });
578
+ }
579
+ }
580
+ var fs$writeFile = fs4.writeFile;
581
+ fs4.writeFile = writeFile2;
582
+ function writeFile2(path3, data, options, cb) {
583
+ if (typeof options === "function")
584
+ cb = options, options = null;
585
+ return go$writeFile(path3, data, options, cb);
586
+ function go$writeFile(path4, data2, options2, cb2, startTime) {
587
+ return fs$writeFile(path4, data2, options2, function(err) {
588
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
589
+ enqueue([go$writeFile, [path4, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
590
+ else {
591
+ if (typeof cb2 === "function")
592
+ cb2.apply(this, arguments);
593
+ }
594
+ });
595
+ }
596
+ }
597
+ var fs$appendFile = fs4.appendFile;
598
+ if (fs$appendFile)
599
+ fs4.appendFile = appendFile;
600
+ function appendFile(path3, data, options, cb) {
601
+ if (typeof options === "function")
602
+ cb = options, options = null;
603
+ return go$appendFile(path3, data, options, cb);
604
+ function go$appendFile(path4, data2, options2, cb2, startTime) {
605
+ return fs$appendFile(path4, data2, options2, function(err) {
606
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
607
+ enqueue([go$appendFile, [path4, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
608
+ else {
609
+ if (typeof cb2 === "function")
610
+ cb2.apply(this, arguments);
611
+ }
612
+ });
613
+ }
614
+ }
615
+ var fs$copyFile = fs4.copyFile;
616
+ if (fs$copyFile)
617
+ fs4.copyFile = copyFile;
618
+ function copyFile(src, dest, flags, cb) {
619
+ if (typeof flags === "function") {
620
+ cb = flags;
621
+ flags = 0;
622
+ }
623
+ return go$copyFile(src, dest, flags, cb);
624
+ function go$copyFile(src2, dest2, flags2, cb2, startTime) {
625
+ return fs$copyFile(src2, dest2, flags2, function(err) {
626
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
627
+ enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
628
+ else {
629
+ if (typeof cb2 === "function")
630
+ cb2.apply(this, arguments);
631
+ }
632
+ });
633
+ }
634
+ }
635
+ var fs$readdir = fs4.readdir;
636
+ fs4.readdir = readdir;
637
+ var noReaddirOptionVersions = /^v[0-5]\./;
638
+ function readdir(path3, options, cb) {
639
+ if (typeof options === "function")
640
+ cb = options, options = null;
641
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path4, options2, cb2, startTime) {
642
+ return fs$readdir(path4, fs$readdirCallback(
643
+ path4,
644
+ options2,
645
+ cb2,
646
+ startTime
647
+ ));
648
+ } : function go$readdir2(path4, options2, cb2, startTime) {
649
+ return fs$readdir(path4, options2, fs$readdirCallback(
650
+ path4,
651
+ options2,
652
+ cb2,
653
+ startTime
654
+ ));
655
+ };
656
+ return go$readdir(path3, options, cb);
657
+ function fs$readdirCallback(path4, options2, cb2, startTime) {
658
+ return function(err, files) {
659
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
660
+ enqueue([
661
+ go$readdir,
662
+ [path4, options2, cb2],
663
+ err,
664
+ startTime || Date.now(),
665
+ Date.now()
666
+ ]);
667
+ else {
668
+ if (files && files.sort)
669
+ files.sort();
670
+ if (typeof cb2 === "function")
671
+ cb2.call(this, err, files);
672
+ }
673
+ };
674
+ }
675
+ }
676
+ if (process.version.substr(0, 4) === "v0.8") {
677
+ var legStreams = legacy(fs4);
678
+ ReadStream = legStreams.ReadStream;
679
+ WriteStream = legStreams.WriteStream;
680
+ }
681
+ var fs$ReadStream = fs4.ReadStream;
682
+ if (fs$ReadStream) {
683
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
684
+ ReadStream.prototype.open = ReadStream$open;
685
+ }
686
+ var fs$WriteStream = fs4.WriteStream;
687
+ if (fs$WriteStream) {
688
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
689
+ WriteStream.prototype.open = WriteStream$open;
690
+ }
691
+ Object.defineProperty(fs4, "ReadStream", {
692
+ get: function() {
693
+ return ReadStream;
694
+ },
695
+ set: function(val) {
696
+ ReadStream = val;
697
+ },
698
+ enumerable: true,
699
+ configurable: true
700
+ });
701
+ Object.defineProperty(fs4, "WriteStream", {
702
+ get: function() {
703
+ return WriteStream;
704
+ },
705
+ set: function(val) {
706
+ WriteStream = val;
707
+ },
708
+ enumerable: true,
709
+ configurable: true
710
+ });
711
+ var FileReadStream = ReadStream;
712
+ Object.defineProperty(fs4, "FileReadStream", {
713
+ get: function() {
714
+ return FileReadStream;
715
+ },
716
+ set: function(val) {
717
+ FileReadStream = val;
718
+ },
719
+ enumerable: true,
720
+ configurable: true
721
+ });
722
+ var FileWriteStream = WriteStream;
723
+ Object.defineProperty(fs4, "FileWriteStream", {
724
+ get: function() {
725
+ return FileWriteStream;
726
+ },
727
+ set: function(val) {
728
+ FileWriteStream = val;
729
+ },
730
+ enumerable: true,
731
+ configurable: true
732
+ });
733
+ function ReadStream(path3, options) {
734
+ if (this instanceof ReadStream)
735
+ return fs$ReadStream.apply(this, arguments), this;
736
+ else
737
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
738
+ }
739
+ function ReadStream$open() {
740
+ var that = this;
741
+ open(that.path, that.flags, that.mode, function(err, fd) {
742
+ if (err) {
743
+ if (that.autoClose)
744
+ that.destroy();
745
+ that.emit("error", err);
746
+ } else {
747
+ that.fd = fd;
748
+ that.emit("open", fd);
749
+ that.read();
750
+ }
751
+ });
752
+ }
753
+ function WriteStream(path3, options) {
754
+ if (this instanceof WriteStream)
755
+ return fs$WriteStream.apply(this, arguments), this;
756
+ else
757
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
758
+ }
759
+ function WriteStream$open() {
760
+ var that = this;
761
+ open(that.path, that.flags, that.mode, function(err, fd) {
762
+ if (err) {
763
+ that.destroy();
764
+ that.emit("error", err);
765
+ } else {
766
+ that.fd = fd;
767
+ that.emit("open", fd);
768
+ }
769
+ });
770
+ }
771
+ function createReadStream(path3, options) {
772
+ return new fs4.ReadStream(path3, options);
773
+ }
774
+ function createWriteStream(path3, options) {
775
+ return new fs4.WriteStream(path3, options);
776
+ }
777
+ var fs$open = fs4.open;
778
+ fs4.open = open;
779
+ function open(path3, flags, mode, cb) {
780
+ if (typeof mode === "function")
781
+ cb = mode, mode = null;
782
+ return go$open(path3, flags, mode, cb);
783
+ function go$open(path4, flags2, mode2, cb2, startTime) {
784
+ return fs$open(path4, flags2, mode2, function(err, fd) {
785
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
786
+ enqueue([go$open, [path4, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
787
+ else {
788
+ if (typeof cb2 === "function")
789
+ cb2.apply(this, arguments);
790
+ }
791
+ });
792
+ }
793
+ }
794
+ return fs4;
795
+ }
796
+ function enqueue(elem) {
797
+ debug("ENQUEUE", elem[0].name, elem[1]);
798
+ fs3[gracefulQueue].push(elem);
799
+ retry();
800
+ }
801
+ var retryTimer;
802
+ function resetQueue() {
803
+ var now = Date.now();
804
+ for (var i = 0; i < fs3[gracefulQueue].length; ++i) {
805
+ if (fs3[gracefulQueue][i].length > 2) {
806
+ fs3[gracefulQueue][i][3] = now;
807
+ fs3[gracefulQueue][i][4] = now;
808
+ }
809
+ }
810
+ retry();
811
+ }
812
+ function retry() {
813
+ clearTimeout(retryTimer);
814
+ retryTimer = void 0;
815
+ if (fs3[gracefulQueue].length === 0)
816
+ return;
817
+ var elem = fs3[gracefulQueue].shift();
818
+ var fn = elem[0];
819
+ var args = elem[1];
820
+ var err = elem[2];
821
+ var startTime = elem[3];
822
+ var lastTime = elem[4];
823
+ if (startTime === void 0) {
824
+ debug("RETRY", fn.name, args);
825
+ fn.apply(null, args);
826
+ } else if (Date.now() - startTime >= 6e4) {
827
+ debug("TIMEOUT", fn.name, args);
828
+ var cb = args.pop();
829
+ if (typeof cb === "function")
830
+ cb.call(null, err);
831
+ } else {
832
+ var sinceAttempt = Date.now() - lastTime;
833
+ var sinceStart = Math.max(lastTime - startTime, 1);
834
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
835
+ if (sinceAttempt >= desiredDelay) {
836
+ debug("RETRY", fn.name, args);
837
+ fn.apply(null, args.concat([startTime]));
838
+ } else {
839
+ fs3[gracefulQueue].push(elem);
840
+ }
841
+ }
842
+ if (retryTimer === void 0) {
843
+ retryTimer = setTimeout(retry, 0);
844
+ }
845
+ }
846
+ }
847
+ });
848
+
849
+ // ../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/lib/retry_operation.js
850
+ var require_retry_operation = __commonJS({
851
+ "../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/lib/retry_operation.js"(exports, module) {
852
+ "use strict";
853
+ function RetryOperation(timeouts, options) {
854
+ if (typeof options === "boolean") {
855
+ options = { forever: options };
856
+ }
857
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
858
+ this._timeouts = timeouts;
859
+ this._options = options || {};
860
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
861
+ this._fn = null;
862
+ this._errors = [];
863
+ this._attempts = 1;
864
+ this._operationTimeout = null;
865
+ this._operationTimeoutCb = null;
866
+ this._timeout = null;
867
+ this._operationStart = null;
868
+ if (this._options.forever) {
869
+ this._cachedTimeouts = this._timeouts.slice(0);
870
+ }
871
+ }
872
+ module.exports = RetryOperation;
873
+ RetryOperation.prototype.reset = function() {
874
+ this._attempts = 1;
875
+ this._timeouts = this._originalTimeouts;
876
+ };
877
+ RetryOperation.prototype.stop = function() {
878
+ if (this._timeout) {
879
+ clearTimeout(this._timeout);
880
+ }
881
+ this._timeouts = [];
882
+ this._cachedTimeouts = null;
883
+ };
884
+ RetryOperation.prototype.retry = function(err) {
885
+ if (this._timeout) {
886
+ clearTimeout(this._timeout);
887
+ }
888
+ if (!err) {
889
+ return false;
890
+ }
891
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
892
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
893
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
894
+ return false;
895
+ }
896
+ this._errors.push(err);
897
+ var timeout = this._timeouts.shift();
898
+ if (timeout === void 0) {
899
+ if (this._cachedTimeouts) {
900
+ this._errors.splice(this._errors.length - 1, this._errors.length);
901
+ this._timeouts = this._cachedTimeouts.slice(0);
902
+ timeout = this._timeouts.shift();
903
+ } else {
904
+ return false;
905
+ }
906
+ }
907
+ var self = this;
908
+ var timer = setTimeout(function() {
909
+ self._attempts++;
910
+ if (self._operationTimeoutCb) {
911
+ self._timeout = setTimeout(function() {
912
+ self._operationTimeoutCb(self._attempts);
913
+ }, self._operationTimeout);
914
+ if (self._options.unref) {
915
+ self._timeout.unref();
916
+ }
917
+ }
918
+ self._fn(self._attempts);
919
+ }, timeout);
920
+ if (this._options.unref) {
921
+ timer.unref();
922
+ }
923
+ return true;
924
+ };
925
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
926
+ this._fn = fn;
927
+ if (timeoutOps) {
928
+ if (timeoutOps.timeout) {
929
+ this._operationTimeout = timeoutOps.timeout;
930
+ }
931
+ if (timeoutOps.cb) {
932
+ this._operationTimeoutCb = timeoutOps.cb;
933
+ }
934
+ }
935
+ var self = this;
936
+ if (this._operationTimeoutCb) {
937
+ this._timeout = setTimeout(function() {
938
+ self._operationTimeoutCb();
939
+ }, self._operationTimeout);
940
+ }
941
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
942
+ this._fn(this._attempts);
943
+ };
944
+ RetryOperation.prototype.try = function(fn) {
945
+ console.log("Using RetryOperation.try() is deprecated");
946
+ this.attempt(fn);
947
+ };
948
+ RetryOperation.prototype.start = function(fn) {
949
+ console.log("Using RetryOperation.start() is deprecated");
950
+ this.attempt(fn);
951
+ };
952
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
953
+ RetryOperation.prototype.errors = function() {
954
+ return this._errors;
955
+ };
956
+ RetryOperation.prototype.attempts = function() {
957
+ return this._attempts;
958
+ };
959
+ RetryOperation.prototype.mainError = function() {
960
+ if (this._errors.length === 0) {
961
+ return null;
962
+ }
963
+ var counts = {};
964
+ var mainError = null;
965
+ var mainErrorCount = 0;
966
+ for (var i = 0; i < this._errors.length; i++) {
967
+ var error = this._errors[i];
968
+ var message = error.message;
969
+ var count = (counts[message] || 0) + 1;
970
+ counts[message] = count;
971
+ if (count >= mainErrorCount) {
972
+ mainError = error;
973
+ mainErrorCount = count;
974
+ }
975
+ }
976
+ return mainError;
977
+ };
978
+ }
979
+ });
980
+
981
+ // ../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/lib/retry.js
982
+ var require_retry = __commonJS({
983
+ "../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/lib/retry.js"(exports) {
984
+ "use strict";
985
+ var RetryOperation = require_retry_operation();
986
+ exports.operation = function(options) {
987
+ var timeouts = exports.timeouts(options);
988
+ return new RetryOperation(timeouts, {
989
+ forever: options && options.forever,
990
+ unref: options && options.unref,
991
+ maxRetryTime: options && options.maxRetryTime
992
+ });
993
+ };
994
+ exports.timeouts = function(options) {
995
+ if (options instanceof Array) {
996
+ return [].concat(options);
997
+ }
998
+ var opts = {
999
+ retries: 10,
1000
+ factor: 2,
1001
+ minTimeout: 1 * 1e3,
1002
+ maxTimeout: Infinity,
1003
+ randomize: false
1004
+ };
1005
+ for (var key in options) {
1006
+ opts[key] = options[key];
1007
+ }
1008
+ if (opts.minTimeout > opts.maxTimeout) {
1009
+ throw new Error("minTimeout is greater than maxTimeout");
1010
+ }
1011
+ var timeouts = [];
1012
+ for (var i = 0; i < opts.retries; i++) {
1013
+ timeouts.push(this.createTimeout(i, opts));
1014
+ }
1015
+ if (options && options.forever && !timeouts.length) {
1016
+ timeouts.push(this.createTimeout(i, opts));
1017
+ }
1018
+ timeouts.sort(function(a2, b) {
1019
+ return a2 - b;
1020
+ });
1021
+ return timeouts;
1022
+ };
1023
+ exports.createTimeout = function(attempt, opts) {
1024
+ var random = opts.randomize ? Math.random() + 1 : 1;
1025
+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
1026
+ timeout = Math.min(timeout, opts.maxTimeout);
1027
+ return timeout;
1028
+ };
1029
+ exports.wrap = function(obj, options, methods) {
1030
+ if (options instanceof Array) {
1031
+ methods = options;
1032
+ options = null;
1033
+ }
1034
+ if (!methods) {
1035
+ methods = [];
1036
+ for (var key in obj) {
1037
+ if (typeof obj[key] === "function") {
1038
+ methods.push(key);
1039
+ }
1040
+ }
1041
+ }
1042
+ for (var i = 0; i < methods.length; i++) {
1043
+ var method = methods[i];
1044
+ var original = obj[method];
1045
+ obj[method] = function retryWrapper(original2) {
1046
+ var op = exports.operation(options);
1047
+ var args = Array.prototype.slice.call(arguments, 1);
1048
+ var callback = args.pop();
1049
+ args.push(function(err) {
1050
+ if (op.retry(err)) {
1051
+ return;
1052
+ }
1053
+ if (err) {
1054
+ arguments[0] = op.mainError();
1055
+ }
1056
+ callback.apply(this, arguments);
1057
+ });
1058
+ op.attempt(function() {
1059
+ original2.apply(obj, args);
1060
+ });
1061
+ }.bind(obj, original);
1062
+ obj[method].options = options;
1063
+ }
1064
+ };
1065
+ }
1066
+ });
1067
+
1068
+ // ../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/index.js
1069
+ var require_retry2 = __commonJS({
1070
+ "../../node_modules/.pnpm/retry@0.12.0/node_modules/retry/index.js"(exports, module) {
1071
+ "use strict";
1072
+ module.exports = require_retry();
1073
+ }
1074
+ });
1075
+
1076
+ // ../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/signals.js
1077
+ var require_signals = __commonJS({
1078
+ "../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/signals.js"(exports, module) {
1079
+ "use strict";
1080
+ module.exports = [
1081
+ "SIGABRT",
1082
+ "SIGALRM",
1083
+ "SIGHUP",
1084
+ "SIGINT",
1085
+ "SIGTERM"
1086
+ ];
1087
+ if (process.platform !== "win32") {
1088
+ module.exports.push(
1089
+ "SIGVTALRM",
1090
+ "SIGXCPU",
1091
+ "SIGXFSZ",
1092
+ "SIGUSR2",
1093
+ "SIGTRAP",
1094
+ "SIGSYS",
1095
+ "SIGQUIT",
1096
+ "SIGIOT"
1097
+ // should detect profiler and enable/disable accordingly.
1098
+ // see #21
1099
+ // 'SIGPROF'
1100
+ );
1101
+ }
1102
+ if (process.platform === "linux") {
1103
+ module.exports.push(
1104
+ "SIGIO",
1105
+ "SIGPOLL",
1106
+ "SIGPWR",
1107
+ "SIGSTKFLT",
1108
+ "SIGUNUSED"
1109
+ );
1110
+ }
1111
+ }
1112
+ });
1113
+
1114
+ // ../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/index.js
1115
+ var require_signal_exit = __commonJS({
1116
+ "../../node_modules/.pnpm/signal-exit@3.0.7/node_modules/signal-exit/index.js"(exports, module) {
1117
+ "use strict";
1118
+ var process2 = global.process;
1119
+ var processOk = function(process3) {
1120
+ return process3 && typeof process3 === "object" && typeof process3.removeListener === "function" && typeof process3.emit === "function" && typeof process3.reallyExit === "function" && typeof process3.listeners === "function" && typeof process3.kill === "function" && typeof process3.pid === "number" && typeof process3.on === "function";
1121
+ };
1122
+ if (!processOk(process2)) {
1123
+ module.exports = function() {
1124
+ return function() {
1125
+ };
1126
+ };
1127
+ } else {
1128
+ assert = __require("assert");
1129
+ signals = require_signals();
1130
+ isWin = /^win/i.test(process2.platform);
1131
+ EE = __require("events");
1132
+ if (typeof EE !== "function") {
1133
+ EE = EE.EventEmitter;
1134
+ }
1135
+ if (process2.__signal_exit_emitter__) {
1136
+ emitter = process2.__signal_exit_emitter__;
1137
+ } else {
1138
+ emitter = process2.__signal_exit_emitter__ = new EE();
1139
+ emitter.count = 0;
1140
+ emitter.emitted = {};
1141
+ }
1142
+ if (!emitter.infinite) {
1143
+ emitter.setMaxListeners(Infinity);
1144
+ emitter.infinite = true;
1145
+ }
1146
+ module.exports = function(cb, opts) {
1147
+ if (!processOk(global.process)) {
1148
+ return function() {
1149
+ };
1150
+ }
1151
+ assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
1152
+ if (loaded === false) {
1153
+ load();
1154
+ }
1155
+ var ev = "exit";
1156
+ if (opts && opts.alwaysLast) {
1157
+ ev = "afterexit";
1158
+ }
1159
+ var remove = function() {
1160
+ emitter.removeListener(ev, cb);
1161
+ if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
1162
+ unload();
1163
+ }
1164
+ };
1165
+ emitter.on(ev, cb);
1166
+ return remove;
1167
+ };
1168
+ unload = function unload2() {
1169
+ if (!loaded || !processOk(global.process)) {
1170
+ return;
1171
+ }
1172
+ loaded = false;
1173
+ signals.forEach(function(sig) {
1174
+ try {
1175
+ process2.removeListener(sig, sigListeners[sig]);
1176
+ } catch (er) {
1177
+ }
1178
+ });
1179
+ process2.emit = originalProcessEmit;
1180
+ process2.reallyExit = originalProcessReallyExit;
1181
+ emitter.count -= 1;
1182
+ };
1183
+ module.exports.unload = unload;
1184
+ emit = function emit2(event, code, signal) {
1185
+ if (emitter.emitted[event]) {
1186
+ return;
1187
+ }
1188
+ emitter.emitted[event] = true;
1189
+ emitter.emit(event, code, signal);
1190
+ };
1191
+ sigListeners = {};
1192
+ signals.forEach(function(sig) {
1193
+ sigListeners[sig] = function listener() {
1194
+ if (!processOk(global.process)) {
1195
+ return;
1196
+ }
1197
+ var listeners = process2.listeners(sig);
1198
+ if (listeners.length === emitter.count) {
1199
+ unload();
1200
+ emit("exit", null, sig);
1201
+ emit("afterexit", null, sig);
1202
+ if (isWin && sig === "SIGHUP") {
1203
+ sig = "SIGINT";
1204
+ }
1205
+ process2.kill(process2.pid, sig);
1206
+ }
1207
+ };
1208
+ });
1209
+ module.exports.signals = function() {
1210
+ return signals;
1211
+ };
1212
+ loaded = false;
1213
+ load = function load2() {
1214
+ if (loaded || !processOk(global.process)) {
1215
+ return;
1216
+ }
1217
+ loaded = true;
1218
+ emitter.count += 1;
1219
+ signals = signals.filter(function(sig) {
1220
+ try {
1221
+ process2.on(sig, sigListeners[sig]);
1222
+ return true;
1223
+ } catch (er) {
1224
+ return false;
1225
+ }
1226
+ });
1227
+ process2.emit = processEmit;
1228
+ process2.reallyExit = processReallyExit;
1229
+ };
1230
+ module.exports.load = load;
1231
+ originalProcessReallyExit = process2.reallyExit;
1232
+ processReallyExit = function processReallyExit2(code) {
1233
+ if (!processOk(global.process)) {
1234
+ return;
1235
+ }
1236
+ process2.exitCode = code || /* istanbul ignore next */
1237
+ 0;
1238
+ emit("exit", process2.exitCode, null);
1239
+ emit("afterexit", process2.exitCode, null);
1240
+ originalProcessReallyExit.call(process2, process2.exitCode);
1241
+ };
1242
+ originalProcessEmit = process2.emit;
1243
+ processEmit = function processEmit2(ev, arg) {
1244
+ if (ev === "exit" && processOk(global.process)) {
1245
+ if (arg !== void 0) {
1246
+ process2.exitCode = arg;
1247
+ }
1248
+ var ret = originalProcessEmit.apply(this, arguments);
1249
+ emit("exit", process2.exitCode, null);
1250
+ emit("afterexit", process2.exitCode, null);
1251
+ return ret;
1252
+ } else {
1253
+ return originalProcessEmit.apply(this, arguments);
1254
+ }
1255
+ };
1256
+ }
1257
+ var assert;
1258
+ var signals;
1259
+ var isWin;
1260
+ var EE;
1261
+ var emitter;
1262
+ var unload;
1263
+ var emit;
1264
+ var sigListeners;
1265
+ var loaded;
1266
+ var load;
1267
+ var originalProcessReallyExit;
1268
+ var processReallyExit;
1269
+ var originalProcessEmit;
1270
+ var processEmit;
1271
+ }
1272
+ });
1273
+
1274
+ // ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/mtime-precision.js
1275
+ var require_mtime_precision = __commonJS({
1276
+ "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/mtime-precision.js"(exports, module) {
1277
+ "use strict";
1278
+ var cacheSymbol = Symbol();
1279
+ function probe(file, fs3, callback) {
1280
+ const cachedPrecision = fs3[cacheSymbol];
1281
+ if (cachedPrecision) {
1282
+ return fs3.stat(file, (err, stat) => {
1283
+ if (err) {
1284
+ return callback(err);
1285
+ }
1286
+ callback(null, stat.mtime, cachedPrecision);
1287
+ });
1288
+ }
1289
+ const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
1290
+ fs3.utimes(file, mtime, mtime, (err) => {
1291
+ if (err) {
1292
+ return callback(err);
1293
+ }
1294
+ fs3.stat(file, (err2, stat) => {
1295
+ if (err2) {
1296
+ return callback(err2);
1297
+ }
1298
+ const precision = stat.mtime.getTime() % 1e3 === 0 ? "s" : "ms";
1299
+ Object.defineProperty(fs3, cacheSymbol, { value: precision });
1300
+ callback(null, stat.mtime, precision);
1301
+ });
1302
+ });
1303
+ }
1304
+ function getMtime(precision) {
1305
+ let now = Date.now();
1306
+ if (precision === "s") {
1307
+ now = Math.ceil(now / 1e3) * 1e3;
1308
+ }
1309
+ return new Date(now);
1310
+ }
1311
+ module.exports.probe = probe;
1312
+ module.exports.getMtime = getMtime;
1313
+ }
1314
+ });
1315
+
1316
+ // ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/lockfile.js
1317
+ var require_lockfile = __commonJS({
1318
+ "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/lockfile.js"(exports, module) {
1319
+ "use strict";
1320
+ var path3 = __require("path");
1321
+ var fs3 = require_graceful_fs();
1322
+ var retry = require_retry2();
1323
+ var onExit = require_signal_exit();
1324
+ var mtimePrecision = require_mtime_precision();
1325
+ var locks = {};
1326
+ function getLockFile(file, options) {
1327
+ return options.lockfilePath || `${file}.lock`;
1328
+ }
1329
+ function resolveCanonicalPath(file, options, callback) {
1330
+ if (!options.realpath) {
1331
+ return callback(null, path3.resolve(file));
1332
+ }
1333
+ options.fs.realpath(file, callback);
1334
+ }
1335
+ function acquireLock(file, options, callback) {
1336
+ const lockfilePath = getLockFile(file, options);
1337
+ options.fs.mkdir(lockfilePath, (err) => {
1338
+ if (!err) {
1339
+ return mtimePrecision.probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision2) => {
1340
+ if (err2) {
1341
+ options.fs.rmdir(lockfilePath, () => {
1342
+ });
1343
+ return callback(err2);
1344
+ }
1345
+ callback(null, mtime, mtimePrecision2);
1346
+ });
1347
+ }
1348
+ if (err.code !== "EEXIST") {
1349
+ return callback(err);
1350
+ }
1351
+ if (options.stale <= 0) {
1352
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1353
+ }
1354
+ options.fs.stat(lockfilePath, (err2, stat) => {
1355
+ if (err2) {
1356
+ if (err2.code === "ENOENT") {
1357
+ return acquireLock(file, { ...options, stale: 0 }, callback);
1358
+ }
1359
+ return callback(err2);
1360
+ }
1361
+ if (!isLockStale(stat, options)) {
1362
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1363
+ }
1364
+ removeLock(file, options, (err3) => {
1365
+ if (err3) {
1366
+ return callback(err3);
1367
+ }
1368
+ acquireLock(file, { ...options, stale: 0 }, callback);
1369
+ });
1370
+ });
1371
+ });
1372
+ }
1373
+ function isLockStale(stat, options) {
1374
+ return stat.mtime.getTime() < Date.now() - options.stale;
1375
+ }
1376
+ function removeLock(file, options, callback) {
1377
+ options.fs.rmdir(getLockFile(file, options), (err) => {
1378
+ if (err && err.code !== "ENOENT") {
1379
+ return callback(err);
1380
+ }
1381
+ callback();
1382
+ });
1383
+ }
1384
+ function updateLock(file, options) {
1385
+ const lock3 = locks[file];
1386
+ if (lock3.updateTimeout) {
1387
+ return;
1388
+ }
1389
+ lock3.updateDelay = lock3.updateDelay || options.update;
1390
+ lock3.updateTimeout = setTimeout(() => {
1391
+ lock3.updateTimeout = null;
1392
+ options.fs.stat(lock3.lockfilePath, (err, stat) => {
1393
+ const isOverThreshold = lock3.lastUpdate + options.stale < Date.now();
1394
+ if (err) {
1395
+ if (err.code === "ENOENT" || isOverThreshold) {
1396
+ return setLockAsCompromised(file, lock3, Object.assign(err, { code: "ECOMPROMISED" }));
1397
+ }
1398
+ lock3.updateDelay = 1e3;
1399
+ return updateLock(file, options);
1400
+ }
1401
+ const isMtimeOurs = lock3.mtime.getTime() === stat.mtime.getTime();
1402
+ if (!isMtimeOurs) {
1403
+ return setLockAsCompromised(
1404
+ file,
1405
+ lock3,
1406
+ Object.assign(
1407
+ new Error("Unable to update lock within the stale threshold"),
1408
+ { code: "ECOMPROMISED" }
1409
+ )
1410
+ );
1411
+ }
1412
+ const mtime = mtimePrecision.getMtime(lock3.mtimePrecision);
1413
+ options.fs.utimes(lock3.lockfilePath, mtime, mtime, (err2) => {
1414
+ const isOverThreshold2 = lock3.lastUpdate + options.stale < Date.now();
1415
+ if (lock3.released) {
1416
+ return;
1417
+ }
1418
+ if (err2) {
1419
+ if (err2.code === "ENOENT" || isOverThreshold2) {
1420
+ return setLockAsCompromised(file, lock3, Object.assign(err2, { code: "ECOMPROMISED" }));
1421
+ }
1422
+ lock3.updateDelay = 1e3;
1423
+ return updateLock(file, options);
1424
+ }
1425
+ lock3.mtime = mtime;
1426
+ lock3.lastUpdate = Date.now();
1427
+ lock3.updateDelay = null;
1428
+ updateLock(file, options);
1429
+ });
1430
+ });
1431
+ }, lock3.updateDelay);
1432
+ if (lock3.updateTimeout.unref) {
1433
+ lock3.updateTimeout.unref();
1434
+ }
1435
+ }
1436
+ function setLockAsCompromised(file, lock3, err) {
1437
+ lock3.released = true;
1438
+ if (lock3.updateTimeout) {
1439
+ clearTimeout(lock3.updateTimeout);
1440
+ }
1441
+ if (locks[file] === lock3) {
1442
+ delete locks[file];
1443
+ }
1444
+ lock3.options.onCompromised(err);
1445
+ }
1446
+ function lock2(file, options, callback) {
1447
+ options = {
1448
+ stale: 1e4,
1449
+ update: null,
1450
+ realpath: true,
1451
+ retries: 0,
1452
+ fs: fs3,
1453
+ onCompromised: (err) => {
1454
+ throw err;
1455
+ },
1456
+ ...options
1457
+ };
1458
+ options.retries = options.retries || 0;
1459
+ options.retries = typeof options.retries === "number" ? { retries: options.retries } : options.retries;
1460
+ options.stale = Math.max(options.stale || 0, 2e3);
1461
+ options.update = options.update == null ? options.stale / 2 : options.update || 0;
1462
+ options.update = Math.max(Math.min(options.update, options.stale / 2), 1e3);
1463
+ resolveCanonicalPath(file, options, (err, file2) => {
1464
+ if (err) {
1465
+ return callback(err);
1466
+ }
1467
+ const operation = retry.operation(options.retries);
1468
+ operation.attempt(() => {
1469
+ acquireLock(file2, options, (err2, mtime, mtimePrecision2) => {
1470
+ if (operation.retry(err2)) {
1471
+ return;
1472
+ }
1473
+ if (err2) {
1474
+ return callback(operation.mainError());
1475
+ }
1476
+ const lock3 = locks[file2] = {
1477
+ lockfilePath: getLockFile(file2, options),
1478
+ mtime,
1479
+ mtimePrecision: mtimePrecision2,
1480
+ options,
1481
+ lastUpdate: Date.now()
1482
+ };
1483
+ updateLock(file2, options);
1484
+ callback(null, (releasedCallback) => {
1485
+ if (lock3.released) {
1486
+ return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
1487
+ }
1488
+ unlock(file2, { ...options, realpath: false }, releasedCallback);
1489
+ });
1490
+ });
1491
+ });
1492
+ });
1493
+ }
1494
+ function unlock(file, options, callback) {
1495
+ options = {
1496
+ fs: fs3,
1497
+ realpath: true,
1498
+ ...options
1499
+ };
1500
+ resolveCanonicalPath(file, options, (err, file2) => {
1501
+ if (err) {
1502
+ return callback(err);
1503
+ }
1504
+ const lock3 = locks[file2];
1505
+ if (!lock3) {
1506
+ return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
1507
+ }
1508
+ lock3.updateTimeout && clearTimeout(lock3.updateTimeout);
1509
+ lock3.released = true;
1510
+ delete locks[file2];
1511
+ removeLock(file2, options, callback);
1512
+ });
1513
+ }
1514
+ function check2(file, options, callback) {
1515
+ options = {
1516
+ stale: 1e4,
1517
+ realpath: true,
1518
+ fs: fs3,
1519
+ ...options
1520
+ };
1521
+ options.stale = Math.max(options.stale || 0, 2e3);
1522
+ resolveCanonicalPath(file, options, (err, file2) => {
1523
+ if (err) {
1524
+ return callback(err);
1525
+ }
1526
+ options.fs.stat(getLockFile(file2, options), (err2, stat) => {
1527
+ if (err2) {
1528
+ return err2.code === "ENOENT" ? callback(null, false) : callback(err2);
1529
+ }
1530
+ return callback(null, !isLockStale(stat, options));
1531
+ });
1532
+ });
1533
+ }
1534
+ function getLocks() {
1535
+ return locks;
1536
+ }
1537
+ onExit(() => {
1538
+ for (const file in locks) {
1539
+ const options = locks[file].options;
1540
+ try {
1541
+ options.fs.rmdirSync(getLockFile(file, options));
1542
+ } catch (e) {
1543
+ }
1544
+ }
1545
+ });
1546
+ module.exports.lock = lock2;
1547
+ module.exports.unlock = unlock;
1548
+ module.exports.check = check2;
1549
+ module.exports.getLocks = getLocks;
1550
+ }
1551
+ });
1552
+
1553
+ // ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/adapter.js
1554
+ var require_adapter = __commonJS({
1555
+ "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/adapter.js"(exports, module) {
1556
+ "use strict";
1557
+ var fs3 = require_graceful_fs();
1558
+ function createSyncFs(fs4) {
1559
+ const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
1560
+ const newFs = { ...fs4 };
1561
+ methods.forEach((method) => {
1562
+ newFs[method] = (...args) => {
1563
+ const callback = args.pop();
1564
+ let ret;
1565
+ try {
1566
+ ret = fs4[`${method}Sync`](...args);
1567
+ } catch (err) {
1568
+ return callback(err);
1569
+ }
1570
+ callback(null, ret);
1571
+ };
1572
+ });
1573
+ return newFs;
1574
+ }
1575
+ function toPromise(method) {
1576
+ return (...args) => new Promise((resolve2, reject) => {
1577
+ args.push((err, result) => {
1578
+ if (err) {
1579
+ reject(err);
1580
+ } else {
1581
+ resolve2(result);
1582
+ }
1583
+ });
1584
+ method(...args);
1585
+ });
1586
+ }
1587
+ function toSync(method) {
1588
+ return (...args) => {
1589
+ let err;
1590
+ let result;
1591
+ args.push((_err, _result) => {
1592
+ err = _err;
1593
+ result = _result;
1594
+ });
1595
+ method(...args);
1596
+ if (err) {
1597
+ throw err;
1598
+ }
1599
+ return result;
1600
+ };
1601
+ }
1602
+ function toSyncOptions(options) {
1603
+ options = { ...options };
1604
+ options.fs = createSyncFs(options.fs || fs3);
1605
+ if (typeof options.retries === "number" && options.retries > 0 || options.retries && typeof options.retries.retries === "number" && options.retries.retries > 0) {
1606
+ throw Object.assign(new Error("Cannot use retries with the sync api"), { code: "ESYNC" });
1607
+ }
1608
+ return options;
1609
+ }
1610
+ module.exports = {
1611
+ toPromise,
1612
+ toSync,
1613
+ toSyncOptions
1614
+ };
1615
+ }
1616
+ });
1617
+
1618
+ // ../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/index.js
1619
+ var require_proper_lockfile = __commonJS({
1620
+ "../../node_modules/.pnpm/proper-lockfile@4.1.2/node_modules/proper-lockfile/index.js"(exports, module) {
1621
+ "use strict";
1622
+ var lockfile = require_lockfile();
1623
+ var { toPromise, toSync, toSyncOptions } = require_adapter();
1624
+ async function lock2(file, options) {
1625
+ const release = await toPromise(lockfile.lock)(file, options);
1626
+ return toPromise(release);
1627
+ }
1628
+ function lockSync(file, options) {
1629
+ const release = toSync(lockfile.lock)(file, toSyncOptions(options));
1630
+ return toSync(release);
1631
+ }
1632
+ function unlock(file, options) {
1633
+ return toPromise(lockfile.unlock)(file, options);
1634
+ }
1635
+ function unlockSync(file, options) {
1636
+ return toSync(lockfile.unlock)(file, toSyncOptions(options));
1637
+ }
1638
+ function check2(file, options) {
1639
+ return toPromise(lockfile.check)(file, options);
1640
+ }
1641
+ function checkSync(file, options) {
1642
+ return toSync(lockfile.check)(file, toSyncOptions(options));
1643
+ }
1644
+ module.exports = lock2;
1645
+ module.exports.lock = lock2;
1646
+ module.exports.unlock = unlock;
1647
+ module.exports.lockSync = lockSync;
1648
+ module.exports.unlockSync = unlockSync;
1649
+ module.exports.check = check2;
1650
+ module.exports.checkSync = checkSync;
1651
+ }
1652
+ });
1653
+
1654
+ // src/Init.ts
1655
+ import { confirm, input, select } from "@inquirer/prompts";
1656
+
1657
+ // ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
1658
+ var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
1659
+ function normalizeWindowsPath(input2 = "") {
1660
+ if (!input2) {
1661
+ return input2;
1662
+ }
1663
+ return input2.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
1664
+ }
1665
+ var _UNC_REGEX = /^[/\\]{2}/;
1666
+ var _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
1667
+ var _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
1668
+ var normalize = function(path3) {
1669
+ if (path3.length === 0) {
1670
+ return ".";
1671
+ }
1672
+ path3 = normalizeWindowsPath(path3);
1673
+ const isUNCPath = path3.match(_UNC_REGEX);
1674
+ const isPathAbsolute = isAbsolute(path3);
1675
+ const trailingSeparator = path3[path3.length - 1] === "/";
1676
+ path3 = normalizeString(path3, !isPathAbsolute);
1677
+ if (path3.length === 0) {
1678
+ if (isPathAbsolute) {
1679
+ return "/";
1680
+ }
1681
+ return trailingSeparator ? "./" : ".";
1682
+ }
1683
+ if (trailingSeparator) {
1684
+ path3 += "/";
1685
+ }
1686
+ if (_DRIVE_LETTER_RE.test(path3)) {
1687
+ path3 += "/";
1688
+ }
1689
+ if (isUNCPath) {
1690
+ if (!isPathAbsolute) {
1691
+ return `//./${path3}`;
1692
+ }
1693
+ return `//${path3}`;
1694
+ }
1695
+ return isPathAbsolute && !isAbsolute(path3) ? `/${path3}` : path3;
1696
+ };
1697
+ var join = function(...segments) {
1698
+ let path3 = "";
1699
+ for (const seg of segments) {
1700
+ if (!seg) {
1701
+ continue;
1702
+ }
1703
+ if (path3.length > 0) {
1704
+ const pathTrailing = path3[path3.length - 1] === "/";
1705
+ const segLeading = seg[0] === "/";
1706
+ const both = pathTrailing && segLeading;
1707
+ if (both) {
1708
+ path3 += seg.slice(1);
1709
+ } else {
1710
+ path3 += pathTrailing || segLeading ? seg : `/${seg}`;
1711
+ }
1712
+ } else {
1713
+ path3 += seg;
1714
+ }
1715
+ }
1716
+ return normalize(path3);
1717
+ };
1718
+ function normalizeString(path3, allowAboveRoot) {
1719
+ let res = "";
1720
+ let lastSegmentLength = 0;
1721
+ let lastSlash = -1;
1722
+ let dots = 0;
1723
+ let char = null;
1724
+ for (let index = 0; index <= path3.length; ++index) {
1725
+ if (index < path3.length) {
1726
+ char = path3[index];
1727
+ } else if (char === "/") {
1728
+ break;
1729
+ } else {
1730
+ char = "/";
1731
+ }
1732
+ if (char === "/") {
1733
+ if (lastSlash === index - 1 || dots === 1)
1734
+ ;
1735
+ else if (dots === 2) {
1736
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
1737
+ if (res.length > 2) {
1738
+ const lastSlashIndex = res.lastIndexOf("/");
1739
+ if (lastSlashIndex === -1) {
1740
+ res = "";
1741
+ lastSegmentLength = 0;
1742
+ } else {
1743
+ res = res.slice(0, lastSlashIndex);
1744
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
1745
+ }
1746
+ lastSlash = index;
1747
+ dots = 0;
1748
+ continue;
1749
+ } else if (res.length > 0) {
1750
+ res = "";
1751
+ lastSegmentLength = 0;
1752
+ lastSlash = index;
1753
+ dots = 0;
1754
+ continue;
1755
+ }
1756
+ }
1757
+ if (allowAboveRoot) {
1758
+ res += res.length > 0 ? "/.." : "..";
1759
+ lastSegmentLength = 2;
1760
+ }
1761
+ } else {
1762
+ if (res.length > 0) {
1763
+ res += `/${path3.slice(lastSlash + 1, index)}`;
1764
+ } else {
1765
+ res = path3.slice(lastSlash + 1, index);
1766
+ }
1767
+ lastSegmentLength = index - lastSlash - 1;
1768
+ }
1769
+ lastSlash = index;
1770
+ dots = 0;
1771
+ } else if (char === "." && dots !== -1) {
1772
+ ++dots;
1773
+ } else {
1774
+ dots = -1;
1775
+ }
1776
+ }
1777
+ return res;
1778
+ }
1779
+ var isAbsolute = function(p) {
1780
+ return _IS_ABSOLUTE_RE.test(p);
1781
+ };
1782
+
1783
+ // ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/utils.mjs
1784
+ var normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");
1785
+ var SLASH_RE = /[/\\]/;
1786
+ function filename(path3) {
1787
+ const base = path3.split(SLASH_RE).pop();
1788
+ if (!base) {
1789
+ return void 0;
1790
+ }
1791
+ const separatorIndex = base.lastIndexOf(".");
1792
+ if (separatorIndex <= 0) {
1793
+ return base;
1794
+ }
1795
+ return base.slice(0, separatorIndex);
1796
+ }
1797
+
1798
+ // ../../node_modules/.pnpm/get-port-please@3.1.2/node_modules/get-port-please/dist/index.mjs
1799
+ import { createServer } from "net";
1800
+ import { networkInterfaces } from "os";
1801
+ var unsafePorts = /* @__PURE__ */ new Set([
1802
+ 1,
1803
+ // tcpmux
1804
+ 7,
1805
+ // echo
1806
+ 9,
1807
+ // discard
1808
+ 11,
1809
+ // systat
1810
+ 13,
1811
+ // daytime
1812
+ 15,
1813
+ // netstat
1814
+ 17,
1815
+ // qotd
1816
+ 19,
1817
+ // chargen
1818
+ 20,
1819
+ // ftp data
1820
+ 21,
1821
+ // ftp access
1822
+ 22,
1823
+ // ssh
1824
+ 23,
1825
+ // telnet
1826
+ 25,
1827
+ // smtp
1828
+ 37,
1829
+ // time
1830
+ 42,
1831
+ // name
1832
+ 43,
1833
+ // nicname
1834
+ 53,
1835
+ // domain
1836
+ 69,
1837
+ // tftp
1838
+ 77,
1839
+ // priv-rjs
1840
+ 79,
1841
+ // finger
1842
+ 87,
1843
+ // ttylink
1844
+ 95,
1845
+ // supdup
1846
+ 101,
1847
+ // hostriame
1848
+ 102,
1849
+ // iso-tsap
1850
+ 103,
1851
+ // gppitnp
1852
+ 104,
1853
+ // acr-nema
1854
+ 109,
1855
+ // pop2
1856
+ 110,
1857
+ // pop3
1858
+ 111,
1859
+ // sunrpc
1860
+ 113,
1861
+ // auth
1862
+ 115,
1863
+ // sftp
1864
+ 117,
1865
+ // uucp-path
1866
+ 119,
1867
+ // nntp
1868
+ 123,
1869
+ // NTP
1870
+ 135,
1871
+ // loc-srv /epmap
1872
+ 137,
1873
+ // netbios
1874
+ 139,
1875
+ // netbios
1876
+ 143,
1877
+ // imap2
1878
+ 161,
1879
+ // snmp
1880
+ 179,
1881
+ // BGP
1882
+ 389,
1883
+ // ldap
1884
+ 427,
1885
+ // SLP (Also used by Apple Filing Protocol)
1886
+ 465,
1887
+ // smtp+ssl
1888
+ 512,
1889
+ // print / exec
1890
+ 513,
1891
+ // login
1892
+ 514,
1893
+ // shell
1894
+ 515,
1895
+ // printer
1896
+ 526,
1897
+ // tempo
1898
+ 530,
1899
+ // courier
1900
+ 531,
1901
+ // chat
1902
+ 532,
1903
+ // netnews
1904
+ 540,
1905
+ // uucp
1906
+ 548,
1907
+ // AFP (Apple Filing Protocol)
1908
+ 554,
1909
+ // rtsp
1910
+ 556,
1911
+ // remotefs
1912
+ 563,
1913
+ // nntp+ssl
1914
+ 587,
1915
+ // smtp (rfc6409)
1916
+ 601,
1917
+ // syslog-conn (rfc3195)
1918
+ 636,
1919
+ // ldap+ssl
1920
+ 989,
1921
+ // ftps-data
1922
+ 990,
1923
+ // ftps
1924
+ 993,
1925
+ // ldap+ssl
1926
+ 995,
1927
+ // pop3+ssl
1928
+ 1719,
1929
+ // h323gatestat
1930
+ 1720,
1931
+ // h323hostcall
1932
+ 1723,
1933
+ // pptp
1934
+ 2049,
1935
+ // nfs
1936
+ 3659,
1937
+ // apple-sasl / PasswordServer
1938
+ 4045,
1939
+ // lockd
1940
+ 5060,
1941
+ // sip
1942
+ 5061,
1943
+ // sips
1944
+ 6e3,
1945
+ // X11
1946
+ 6566,
1947
+ // sane-port
1948
+ 6665,
1949
+ // Alternate IRC [Apple addition]
1950
+ 6666,
1951
+ // Alternate IRC [Apple addition]
1952
+ 6667,
1953
+ // Standard IRC [Apple addition]
1954
+ 6668,
1955
+ // Alternate IRC [Apple addition]
1956
+ 6669,
1957
+ // Alternate IRC [Apple addition]
1958
+ 6697,
1959
+ // IRC + TLS
1960
+ 10080
1961
+ // Amanda
1962
+ ]);
1963
+ function isUnsafePort(port) {
1964
+ return unsafePorts.has(port);
1965
+ }
1966
+ function isSafePort(port) {
1967
+ return !isUnsafePort(port);
1968
+ }
1969
+ var __defProp = Object.defineProperty;
1970
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1971
+ var __publicField = (obj, key, value) => {
1972
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1973
+ return value;
1974
+ };
1975
+ var GetPortError = class extends Error {
1976
+ constructor(message, opts) {
1977
+ super(message, opts);
1978
+ this.message = message;
1979
+ __publicField(this, "name", "GetPortError");
1980
+ }
1981
+ };
1982
+ function _log(verbose, message) {
1983
+ if (verbose) {
1984
+ console.log(`[get-port] ${message}`);
1985
+ }
1986
+ }
1987
+ function _generateRange(from, to) {
1988
+ if (to < from) {
1989
+ return [];
1990
+ }
1991
+ const r = [];
1992
+ for (let index = from; index <= to; index++) {
1993
+ r.push(index);
1994
+ }
1995
+ return r;
1996
+ }
1997
+ function _tryPort(port, host) {
1998
+ return new Promise((resolve2) => {
1999
+ const server = createServer();
2000
+ server.unref();
2001
+ server.on("error", () => {
2002
+ resolve2(false);
2003
+ });
2004
+ server.listen({ port, host }, () => {
2005
+ const { port: port2 } = server.address();
2006
+ server.close(() => {
2007
+ resolve2(isSafePort(port2) && port2);
2008
+ });
2009
+ });
2010
+ });
2011
+ }
2012
+ function _getLocalHosts(additional) {
2013
+ const hosts = new Set(additional);
2014
+ for (const _interface of Object.values(networkInterfaces())) {
2015
+ for (const config of _interface || []) {
2016
+ if (config.address && !config.internal && !config.address.startsWith("fe80::")) {
2017
+ hosts.add(config.address);
2018
+ }
2019
+ }
2020
+ }
2021
+ return [...hosts];
2022
+ }
2023
+ async function _findPort(ports, host) {
2024
+ for (const port of ports) {
2025
+ const r = await _tryPort(port, host);
2026
+ if (r) {
2027
+ return r;
2028
+ }
2029
+ }
2030
+ }
2031
+ function _fmtOnHost(hostname) {
2032
+ return hostname ? `on host ${JSON.stringify(hostname)}` : "on any host";
2033
+ }
2034
+ var HOSTNAME_RE = /^(?!-)[\d.:A-Za-z-]{1,63}(?<!-)$/;
2035
+ function _validateHostname(hostname, _public, verbose) {
2036
+ if (hostname && !HOSTNAME_RE.test(hostname)) {
2037
+ const fallbackHost = _public ? "0.0.0.0" : "127.0.0.1";
2038
+ _log(
2039
+ verbose,
2040
+ `Invalid hostname: ${JSON.stringify(hostname)}. Using ${JSON.stringify(
2041
+ fallbackHost
2042
+ )} as fallback.`
2043
+ );
2044
+ return fallbackHost;
2045
+ }
2046
+ return hostname;
2047
+ }
2048
+ async function getPort(_userOptions = {}) {
2049
+ if (typeof _userOptions === "number" || typeof _userOptions === "string") {
2050
+ _userOptions = { port: Number.parseInt(_userOptions + "") || 0 };
2051
+ }
2052
+ const _port = Number(_userOptions.port ?? process.env.PORT);
2053
+ const _userSpecifiedAnyPort = Boolean(
2054
+ _userOptions.port || _userOptions.ports?.length || _userOptions.portRange?.length
2055
+ );
2056
+ const options = {
2057
+ name: "default",
2058
+ random: _port === 0,
2059
+ ports: [],
2060
+ portRange: [],
2061
+ alternativePortRange: _userSpecifiedAnyPort ? [] : [3e3, 3100],
2062
+ verbose: false,
2063
+ ..._userOptions,
2064
+ port: _port,
2065
+ host: _validateHostname(
2066
+ _userOptions.host ?? process.env.HOST,
2067
+ _userOptions.public,
2068
+ _userOptions.verbose
2069
+ )
2070
+ };
2071
+ if (options.random && !_userSpecifiedAnyPort) {
2072
+ return getRandomPort(options.host);
2073
+ }
2074
+ const portsToCheck = [
2075
+ options.port,
2076
+ ...options.ports,
2077
+ ..._generateRange(...options.portRange)
2078
+ ].filter((port) => {
2079
+ if (!port) {
2080
+ return false;
2081
+ }
2082
+ if (!isSafePort(port)) {
2083
+ _log(options.verbose, `Ignoring unsafe port: ${port}`);
2084
+ return false;
2085
+ }
2086
+ return true;
2087
+ });
2088
+ if (portsToCheck.length === 0) {
2089
+ portsToCheck.push(3e3);
2090
+ }
2091
+ let availablePort = await _findPort(portsToCheck, options.host);
2092
+ if (!availablePort && options.alternativePortRange.length > 0) {
2093
+ availablePort = await _findPort(
2094
+ _generateRange(...options.alternativePortRange),
2095
+ options.host
2096
+ );
2097
+ if (portsToCheck.length > 0) {
2098
+ let message = `Unable to find an available port (tried ${portsToCheck.join(
2099
+ "-"
2100
+ )} ${_fmtOnHost(options.host)}).`;
2101
+ if (availablePort) {
2102
+ message += ` Using alternative port ${availablePort}.`;
2103
+ }
2104
+ _log(options.verbose, message);
2105
+ }
2106
+ }
2107
+ if (!availablePort && _userOptions.random !== false) {
2108
+ availablePort = await getRandomPort(options.host);
2109
+ if (availablePort) {
2110
+ _log(options.verbose, `Using random port ${availablePort}`);
2111
+ }
2112
+ }
2113
+ if (!availablePort) {
2114
+ const triedRanges = [
2115
+ options.port,
2116
+ options.portRange.join("-"),
2117
+ options.alternativePortRange.join("-")
2118
+ ].filter(Boolean).join(", ");
2119
+ throw new GetPortError(
2120
+ `Unable to find an available port ${_fmtOnHost(
2121
+ options.host
2122
+ )} (tried ${triedRanges})`
2123
+ );
2124
+ }
2125
+ return availablePort;
2126
+ }
2127
+ async function getRandomPort(host) {
2128
+ const port = await checkPort(0, host);
2129
+ if (port === false) {
2130
+ throw new GetPortError(`Unable to find a random port ${_fmtOnHost(host)}`);
2131
+ }
2132
+ return port;
2133
+ }
2134
+ async function checkPort(port, host = process.env.HOST, verbose) {
2135
+ if (!host) {
2136
+ host = _getLocalHosts([void 0, "0.0.0.0"]);
2137
+ }
2138
+ if (!Array.isArray(host)) {
2139
+ return _tryPort(port, host);
2140
+ }
2141
+ for (const _host of host) {
2142
+ const _port = await _tryPort(port, _host);
2143
+ if (_port === false) {
2144
+ if (port < 1024 && verbose) {
2145
+ _log(
2146
+ verbose,
2147
+ `Unable to listen to the privileged port ${port} ${_fmtOnHost(
2148
+ _host
2149
+ )}`
2150
+ );
2151
+ }
2152
+ return false;
2153
+ }
2154
+ if (port === 0 && _port !== 0) {
2155
+ port = _port;
2156
+ }
2157
+ }
2158
+ return port;
2159
+ }
2160
+
2161
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-ANXBDSUI.js
2162
+ var s = { done: false, hasNext: false };
2163
+ var o = (t) => ({ hasNext: true, next: t, done: false });
2164
+
2165
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-3GOCSNFN.js
2166
+ function C(t, ...o3) {
2167
+ let n = t, u3 = o3.map((e) => "lazy" in e ? y2(e) : void 0), p = 0;
2168
+ for (; p < o3.length; ) {
2169
+ if (u3[p] === void 0 || !B(n)) {
2170
+ let i = o3[p];
2171
+ n = i(n), p += 1;
2172
+ continue;
2173
+ }
2174
+ let r = [];
2175
+ for (let i = p; i < o3.length; i++) {
2176
+ let l = u3[i];
2177
+ if (l === void 0 || (r.push(l), l.isSingle))
2178
+ break;
2179
+ }
2180
+ let a2 = [];
2181
+ for (let i of n)
2182
+ if (f(i, a2, r))
2183
+ break;
2184
+ let { isSingle: s2 } = r.at(-1);
2185
+ n = s2 ? a2[0] : a2, p += r.length;
2186
+ }
2187
+ return n;
2188
+ }
2189
+ function f(t, o3, n) {
2190
+ if (n.length === 0)
2191
+ return o3.push(t), false;
2192
+ let u3 = t, p = s, e = false;
2193
+ for (let [r, a2] of n.entries()) {
2194
+ let { index: s2, items: i } = a2;
2195
+ if (i.push(u3), p = a2(u3, s2, i), a2.index += 1, p.hasNext) {
2196
+ if (p.hasMany ?? false) {
2197
+ for (let l of p.next)
2198
+ if (f(l, o3, n.slice(r + 1)))
2199
+ return true;
2200
+ return e;
2201
+ }
2202
+ u3 = p.next;
2203
+ }
2204
+ if (!p.hasNext)
2205
+ break;
2206
+ p.done && (e = true);
2207
+ }
2208
+ return p.hasNext && o3.push(u3), e;
2209
+ }
2210
+ function y2(t) {
2211
+ let { lazy: o3, lazyArgs: n } = t, u3 = o3(...n);
2212
+ return Object.assign(u3, { isSingle: o3.single ?? false, index: 0, items: [] });
2213
+ }
2214
+ function B(t) {
2215
+ return typeof t == "string" || typeof t == "object" && t !== null && Symbol.iterator in t;
2216
+ }
2217
+
2218
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-LFJW7BOT.js
2219
+ function y3(t, i) {
2220
+ let a2 = i.length - t.length;
2221
+ if (a2 === 1) {
2222
+ let [n, ...r] = i;
2223
+ return C(n, { lazy: t, lazyArgs: r });
2224
+ }
2225
+ if (a2 === 0) {
2226
+ let n = { lazy: t, lazyArgs: i };
2227
+ return Object.assign((e) => C(e, n), n);
2228
+ }
2229
+ throw new Error("Wrong number of arguments");
2230
+ }
2231
+
2232
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-D6FCK2GA.js
2233
+ function u(o3, n, a2) {
2234
+ let t = (r) => o3(r, ...n);
2235
+ return a2 === void 0 ? t : Object.assign(t, { lazy: a2, lazyArgs: n });
2236
+ }
2237
+
2238
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-WIMGWYZL.js
2239
+ function u2(r, n, o3) {
2240
+ let a2 = r.length - n.length;
2241
+ if (a2 === 0)
2242
+ return r(...n);
2243
+ if (a2 === 1)
2244
+ return u(r, n, o3);
2245
+ throw new Error("Wrong number of arguments");
2246
+ }
2247
+
2248
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-ENS7GPLZ.js
2249
+ function a(...r) {
2250
+ return u2(o2, r);
2251
+ }
2252
+ function o2(r, t) {
2253
+ let e = [];
2254
+ for (let n = r; n < t; n++)
2255
+ e.push(n);
2256
+ return e;
2257
+ }
2258
+
2259
+ // ../../node_modules/.pnpm/remeda@2.21.3/node_modules/remeda/dist/chunk-GKXRNLHM.js
2260
+ function d(...e) {
2261
+ return y3(f2, e);
2262
+ }
2263
+ function f2(e) {
2264
+ if (e.length === 0)
2265
+ return o;
2266
+ let n = /* @__PURE__ */ new Map();
2267
+ for (let r of e)
2268
+ n.set(r, (n.get(r) ?? 0) + 1);
2269
+ return (r) => {
2270
+ let t = n.get(r);
2271
+ return t === void 0 || t === 0 ? { done: false, hasNext: true, next: r } : (n.set(r, t - 1), s);
2272
+ };
2273
+ }
2274
+
2275
+ // ../../dev/server/src/port.ts
2276
+ var DEFAULT_DATABASE_PORT = 51214;
2277
+ var DEFAULT_SERVER_PORT = 51213;
2278
+ var DEFAULT_SHADOW_DATABASE_PORT = 51215;
2279
+ var MAX_PORT = 65535;
2280
+ var NO_PORT = -Infinity;
2281
+ async function pickPorts(options) {
2282
+ const { debug, name, requestedPorts, servers } = options;
2283
+ const { portsUsedByOtherServers, portsUsedByThisServerLastTime } = extractUsedPorts(name, servers);
2284
+ if (debug) {
2285
+ console.debug(`ports used by other servers: ${Object.keys(portsUsedByOtherServers).join(", ")}`);
2286
+ console.debug(`ports used by "${name}" server last time: ${JSON.stringify(portsUsedByThisServerLastTime)}`);
2287
+ }
2288
+ const pickedPorts = { databasePort: NO_PORT, port: NO_PORT, shadowDatabasePort: NO_PORT };
2289
+ const portKeys = ["port", "databasePort", "shadowDatabasePort"];
2290
+ for (const portKey of portKeys) {
2291
+ const port = await trySpecificPorts({
2292
+ debug,
2293
+ portKey,
2294
+ portsUsedByOtherServers,
2295
+ portsUsedByThisServerLastTime,
2296
+ requestedPorts
2297
+ }) ?? await tryAnyPort({ debug, pickedPorts, portKey, portsUsedByOtherServers, portsUsedByThisServerLastTime });
2298
+ if (debug) {
2299
+ console.debug(`Got port for "${portKey}": ${port}`);
2300
+ }
2301
+ pickedPorts[portKey] = port;
2302
+ }
2303
+ if (debug) {
2304
+ console.debug(`Picked ports: ${JSON.stringify(pickedPorts)}`);
2305
+ }
2306
+ return pickedPorts;
2307
+ }
2308
+ async function trySpecificPorts(options) {
2309
+ const { debug, portKey, portsUsedByOtherServers, portsUsedByThisServerLastTime, requestedPorts } = options;
2310
+ const { [portKey]: requestedPort, ...otherRequestedPorts } = requestedPorts;
2311
+ if (isPortSpecified(requestedPort)) {
2312
+ await assertPickablePort({ debug, otherRequestedPorts, portKey, portsUsedByOtherServers, requestedPort });
2313
+ return requestedPort;
2314
+ }
2315
+ const portUsedLastTime = portsUsedByThisServerLastTime?.[portKey] ?? NO_PORT;
2316
+ if (!isPortSpecified(portUsedLastTime)) {
2317
+ if (debug) {
2318
+ console.debug(`No port specified for "${portKey}". Trying to pick a new port.`);
2319
+ }
2320
+ return null;
2321
+ }
2322
+ const isPortUsedByOtherServers = portUsedLastTime in portsUsedByOtherServers;
2323
+ if (isPortUsedByOtherServers || Object.values(otherRequestedPorts).includes(portUsedLastTime)) {
2324
+ if (debug) {
2325
+ console.debug(
2326
+ `Port ${portUsedLastTime} that was used last time for this server, ${isPortUsedByOtherServers ? "is also used by another server" : "has been requested for another service"}. Trying to pick a new port.`
2327
+ );
2328
+ }
2329
+ return null;
2330
+ }
2331
+ if (await checkPort(portUsedLastTime) === false) {
2332
+ if (debug) {
2333
+ console.debug(
2334
+ `Port ${portUsedLastTime}, that was used last time for this server, is not available. Trying to pick a new port.`
2335
+ );
2336
+ }
2337
+ return null;
2338
+ }
2339
+ if (debug) {
2340
+ console.debug(`Using port ${portUsedLastTime} for "${portKey}" as it was used last time and is available.`);
2341
+ }
2342
+ return portUsedLastTime;
2343
+ }
2344
+ async function tryAnyPort(options) {
2345
+ const { debug, pickedPorts, portKey, portsUsedByOtherServers, portsUsedByThisServerLastTime } = options;
2346
+ const minimumPort = Math.max(DEFAULT_DATABASE_PORT, DEFAULT_SERVER_PORT, DEFAULT_SHADOW_DATABASE_PORT) + 1;
2347
+ const excludedPorts = [
2348
+ ...Object.values(pickedPorts),
2349
+ ...Object.keys(portsUsedByOtherServers).map(Number),
2350
+ ...Object.values(portsUsedByThisServerLastTime || {})
2351
+ ];
2352
+ const maximumSpecificPort = Math.min(Math.max(minimumPort, ...excludedPorts) + 100, MAX_PORT);
2353
+ const ports = d(a(minimumPort, maximumSpecificPort), excludedPorts);
2354
+ const defaultPort2 = {
2355
+ port: DEFAULT_SERVER_PORT,
2356
+ databasePort: DEFAULT_DATABASE_PORT,
2357
+ shadowDatabasePort: DEFAULT_SHADOW_DATABASE_PORT
2358
+ }[portKey];
2359
+ try {
2360
+ return await getPort({
2361
+ port: defaultPort2 in portsUsedByOtherServers || Object.values(pickedPorts).includes(defaultPort2) || Object.values(portsUsedByThisServerLastTime || {}).includes(defaultPort2) ? void 0 : defaultPort2,
2362
+ ports
2363
+ });
2364
+ } catch (error) {
2365
+ if (error instanceof Error && error.name === "GetPortError" && maximumSpecificPort + 1 <= MAX_PORT) {
2366
+ if (debug) {
2367
+ console.debug(`Expanding port lookup to range [${maximumSpecificPort + 1}, ${MAX_PORT}].`);
2368
+ }
2369
+ return await getPort({ portRange: [maximumSpecificPort + 1, MAX_PORT] });
2370
+ }
2371
+ throw error;
2372
+ }
2373
+ }
2374
+ function isPortSpecified(port) {
2375
+ return port >= 0;
2376
+ }
2377
+ function extractUsedPorts(name, servers) {
2378
+ const portsUsedByOtherServers = {};
2379
+ let portsUsedByThisServerLastTime;
2380
+ for (const server of servers) {
2381
+ const { databasePort, port, shadowDatabasePort } = server;
2382
+ if (server.name === name) {
2383
+ portsUsedByThisServerLastTime = { databasePort, port, shadowDatabasePort };
2384
+ continue;
2385
+ }
2386
+ portsUsedByOtherServers[databasePort] = true;
2387
+ portsUsedByOtherServers[port] = true;
2388
+ portsUsedByOtherServers[shadowDatabasePort] = true;
2389
+ }
2390
+ return { portsUsedByOtherServers, portsUsedByThisServerLastTime };
2391
+ }
2392
+ async function assertPickablePort(options) {
2393
+ const { debug, otherRequestedPorts, portKey, portsUsedByOtherServers, requestedPort } = options;
2394
+ if (requestedPort in portsUsedByOtherServers) {
2395
+ if (debug) {
2396
+ console.error(`Port ${requestedPort} was requested for "${portKey}", but is already used by another server.`);
2397
+ }
2398
+ throw new PortBelongsToAnotherServerError(requestedPort);
2399
+ }
2400
+ if (Object.values(otherRequestedPorts).includes(requestedPort)) {
2401
+ if (debug) {
2402
+ console.error(`Port ${requestedPort} was requested for "${portKey}", but also for another key.`);
2403
+ }
2404
+ throw new PortRequestedTwiceError(requestedPort);
2405
+ }
2406
+ if (isUnsafePort(requestedPort)) {
2407
+ if (debug) {
2408
+ console.error(`Port ${requestedPort} was requested for "${portKey}", but is unsafe.`);
2409
+ }
2410
+ throw new PortNotAvailableError(requestedPort);
2411
+ }
2412
+ if (await checkPort(requestedPort) === false) {
2413
+ if (debug) {
2414
+ console.error(`Port ${requestedPort} was requested for "${portKey}", but is not available.`);
2415
+ }
2416
+ throw new PortNotAvailableError(requestedPort);
2417
+ }
2418
+ }
2419
+ var PortNotAvailableError = class extends Error {
2420
+ constructor(port) {
2421
+ super(`Port \`${port}\` is not available.`);
2422
+ this.port = port;
2423
+ }
2424
+ name = "PortNotAvailableError";
2425
+ };
2426
+ var PortRequestedTwiceError = class extends Error {
2427
+ constructor(port) {
2428
+ super(`Port number \`${port}\` was requested twice. Please choose a different port for each service.`);
2429
+ this.port = port;
2430
+ }
2431
+ name = "PortRequestedTwiceError";
2432
+ };
2433
+ var PortBelongsToAnotherServerError = class extends Error {
2434
+ constructor(port) {
2435
+ super(`Port number \`${port}\` belongs to another Prisma Dev server. Please choose a different port.`);
2436
+ this.port = port;
2437
+ }
2438
+ name = "PortBelongsToAnotherServerError";
2439
+ };
2440
+
2441
+ // ../../dev/server/src/db.ts
2442
+ var BASE_PGLITE_OPTIONS = {
2443
+ connectionLimit: 1,
2444
+ connectTimeout: 0,
2445
+ database: "template1",
2446
+ maxIdleConnectionLifetime: 0,
2447
+ password: "postgres",
2448
+ poolTimeout: 0,
2449
+ socketTimeout: 0,
2450
+ sslMode: "disable",
2451
+ username: "postgres"
2452
+ };
2453
+ var BASE_DB_URL = `postgres://${BASE_PGLITE_OPTIONS.username}:${BASE_PGLITE_OPTIONS.password}@localhost`;
2454
+ var CONNECTION_STRING_QUERY_PARAMS = new URLSearchParams({ sslmode: BASE_PGLITE_OPTIONS.sslMode });
2455
+ var PRISMA_ORM_CONNECTION_STRING_QUERY_PARAMS = new URLSearchParams({
2456
+ ...Object.fromEntries(CONNECTION_STRING_QUERY_PARAMS.entries()),
2457
+ connection_limit: String(BASE_PGLITE_OPTIONS.connectionLimit),
2458
+ connect_timeout: String(BASE_PGLITE_OPTIONS.connectTimeout),
2459
+ max_idle_connection_lifetime: String(BASE_PGLITE_OPTIONS.maxIdleConnectionLifetime),
2460
+ pool_timeout: String(BASE_PGLITE_OPTIONS.poolTimeout),
2461
+ single_use_connections: "true",
2462
+ socket_timeout: String(BASE_PGLITE_OPTIONS.socketTimeout)
2463
+ });
2464
+ async function startDBServer(purpose, serverState) {
2465
+ const port = purpose === "database" ? serverState.databasePort : serverState.shadowDatabasePort;
2466
+ if (serverState.dryRun) {
2467
+ return getStartDBServerResult(purpose, serverState, { db: null, port, server: null });
2468
+ }
2469
+ const { debug } = serverState;
2470
+ const getDBFn = purpose === "shadow_database" ? getShadowDB : getDB;
2471
+ const db = await getDBFn(serverState.pgliteDataDirPath, debug);
2472
+ if (debug) {
2473
+ db.onNotification((channel, payload) => {
2474
+ console.debug(`[${purpose}][${channel}] ${payload}`);
2475
+ });
2476
+ }
2477
+ const { PGLiteSocketServer } = await import("@electric-sql/pglite-socket");
2478
+ const server = new PGLiteSocketServer({ db, debug, inspect: debug, port });
2479
+ if (debug) {
2480
+ server.addEventListener("listening", (event) => {
2481
+ const { detail } = event;
2482
+ console.debug(`[${purpose}] server listening on ${JSON.stringify(detail)}`);
2483
+ });
2484
+ server.addEventListener("connection", (event) => {
2485
+ const { clientAddress, clientPort } = event.detail;
2486
+ console.debug(`[${purpose}] client connected from ${clientAddress}:${clientPort}`);
2487
+ });
2488
+ server.addEventListener("error", (event) => {
2489
+ const { detail } = event;
2490
+ console.error(`[${purpose}] server error:`, detail);
2491
+ });
2492
+ }
2493
+ try {
2494
+ await server.start();
2495
+ } catch (error) {
2496
+ if (error instanceof Error && "code" in error && error.code === "EADDRINUSE") {
2497
+ throw new PortNotAvailableError(port);
2498
+ }
2499
+ throw error;
2500
+ }
2501
+ return getStartDBServerResult(purpose, serverState, { db, port, server });
2502
+ }
2503
+ function getStartDBServerResult(purpose, serverState, options) {
2504
+ const { debug } = serverState;
2505
+ const { db, port, server } = options || {};
2506
+ if (debug) {
2507
+ console.debug(`[${purpose}] server started on port ${port}`);
2508
+ }
2509
+ return {
2510
+ ...BASE_PGLITE_OPTIONS,
2511
+ close: async () => {
2512
+ const errors = [];
2513
+ try {
2514
+ await server?.stop();
2515
+ if (debug) {
2516
+ console.debug(`[${purpose}] server stopped on port ${port}`);
2517
+ }
2518
+ } catch (error) {
2519
+ console.error(`[${purpose}] server stop error`, error);
2520
+ errors.push(error);
2521
+ }
2522
+ if (purpose === "database") {
2523
+ try {
2524
+ await db?.syncToFs();
2525
+ if (debug) {
2526
+ console.debug(`[${purpose}] synced to filesystem`);
2527
+ }
2528
+ } catch (error) {
2529
+ console.error(`[${purpose}] sync error`, error);
2530
+ errors.push(error);
2531
+ }
2532
+ }
2533
+ try {
2534
+ await db?.close();
2535
+ if (debug) {
2536
+ console.debug(`[${purpose}] closed`);
2537
+ }
2538
+ } catch (error) {
2539
+ console.error(`[${purpose}] close error`, error);
2540
+ errors.push(error);
2541
+ }
2542
+ if (errors.length > 0) {
2543
+ throw new AggregateError(errors, `Failed to close ${purpose} properly`);
2544
+ }
2545
+ },
2546
+ connectionString: getConnectionString(port, CONNECTION_STRING_QUERY_PARAMS),
2547
+ dump: async (destinationPath) => {
2548
+ if (purpose === "shadow_database" || !db) {
2549
+ return;
2550
+ }
2551
+ await dumpDB({ db, debug, destinationPath });
2552
+ },
2553
+ port,
2554
+ prismaORMConnectionString: getConnectionString(port, PRISMA_ORM_CONNECTION_STRING_QUERY_PARAMS),
2555
+ terminalCommand: `PGPASSWORD=${BASE_PGLITE_OPTIONS.password} PGSSLMODE=${BASE_PGLITE_OPTIONS.sslMode} psql -h localhost -p ${port} -U ${BASE_PGLITE_OPTIONS.username} -d ${BASE_PGLITE_OPTIONS.database}`
2556
+ };
2557
+ }
2558
+ function getConnectionString(port, queryParams) {
2559
+ return `${BASE_DB_URL}:${port}/${BASE_PGLITE_OPTIONS.database}?${queryParams.toString()}`;
2560
+ }
2561
+ async function getDB(dataDir, debug) {
2562
+ const { PGlite } = await import("@electric-sql/pglite");
2563
+ return await PGlite.create({
2564
+ database: BASE_PGLITE_OPTIONS.database,
2565
+ dataDir,
2566
+ debug: debug ? 5 : void 0,
2567
+ relaxedDurability: false,
2568
+ username: BASE_PGLITE_OPTIONS.username
2569
+ });
2570
+ }
2571
+ async function getShadowDB(_dataDir, debug) {
2572
+ const { PGlite } = await import("@electric-sql/pglite");
2573
+ return await PGlite.create({
2574
+ database: BASE_PGLITE_OPTIONS.database,
2575
+ dataDir: "memory://",
2576
+ debug: debug ? 5 : void 0,
2577
+ relaxedDurability: false,
2578
+ username: BASE_PGLITE_OPTIONS.username
2579
+ });
2580
+ }
2581
+ async function dumpDB(options) {
2582
+ const { dataDir, db, debug, destinationPath } = options;
2583
+ const pg = db || await getDB(dataDir, debug);
2584
+ const { pgDump } = await import("@electric-sql/pglite-tools/pg_dump");
2585
+ const dumpFile = await pgDump({
2586
+ args: [
2587
+ // TODO: enable once it's fixed by PGLite team. This is highly recommended for cross-major-version pg restores.
2588
+ // "--quote-all-identifiers",
2589
+ // TODO: remove once we decide to also dump data.
2590
+ "--schema-only",
2591
+ "--no-owner"
2592
+ // avoids `ALTER TABLE public."Post" OWNER TO postgres;`
2593
+ ],
2594
+ fileName: destinationPath ? filename(destinationPath) : void 0,
2595
+ // workaround, see https://prisma-company.slack.com/archives/C08LDD4THBJ/p1749486737052709?thread_ts=1749211391.517819&cid=C08LDD4THBJ
2596
+ pg: await pg.clone()
2597
+ });
2598
+ if (destinationPath) {
2599
+ if (debug) {
2600
+ console.debug(`[DB] Dumping database to ${destinationPath}`);
2601
+ }
2602
+ return await streamAsTextTo(dumpFile, destinationPath);
2603
+ }
2604
+ if (debug) {
2605
+ console.debug(`[DB] Dumping database to memory`);
2606
+ }
2607
+ return await dumpFile.text();
2608
+ }
2609
+
2610
+ // ../../dev/server/src/http.ts
2611
+ import { createServer as createServer2 } from "http";
2612
+ import { promisify } from "util";
2613
+ import getPlatformModule from "@prisma/get-platform";
2614
+ async function startHTTPServer(dbServer, serverState) {
2615
+ const { port } = serverState;
2616
+ if (serverState.dryRun) {
2617
+ return getStartHTTPServerResult(port, null);
2618
+ }
2619
+ const app = await getApp(port, dbServer, serverState);
2620
+ const { promise: waitReady, reject, resolve: resolve2 } = withResolvers();
2621
+ const { serve } = await import("@hono/node-server");
2622
+ const server = serve({ createServer: createServer2, fetch: app.fetch, overrideGlobalObjects: false, port }, resolve2);
2623
+ server.on("error", (error) => {
2624
+ if (typeof error === "object" && "code" in error && error.code === "EADDRINUSE") {
2625
+ return reject(new PortNotAvailableError(port));
2626
+ }
2627
+ console.error("[Accelerate]", error);
2628
+ });
2629
+ await waitReady;
2630
+ return getStartHTTPServerResult(port, server);
2631
+ }
2632
+ function getStartHTTPServerResult(port, server) {
2633
+ return {
2634
+ async close() {
2635
+ if (!server) {
2636
+ return;
2637
+ }
2638
+ await Promise.allSettled([promisify(server.close.bind(server))(), Engine.stopAll()]);
2639
+ },
2640
+ port,
2641
+ url: `http://localhost:${port}`
2642
+ };
2643
+ }
2644
+ async function getApp(port, dbServer, serverState) {
2645
+ const { debug } = serverState;
2646
+ const [{ Hono }, { accelerateRoute }, { utilityRoute }] = await Promise.all([
2647
+ import("hono/tiny"),
2648
+ import("./accelerate-GABM6I4V.js"),
2649
+ import("./utility-W6LOZZIT.js")
2650
+ ]);
2651
+ const app = new Hono();
2652
+ const platform = await getPlatformModule.getPlatformInfo();
2653
+ if (debug) {
2654
+ console.debug("[Accelerate] platform info: %s", JSON.stringify(platform));
2655
+ }
2656
+ if (debug) {
2657
+ const { logger } = await import("hono/logger");
2658
+ app.use(
2659
+ "*",
2660
+ logger((...args) => console.log("[Accelerate]", ...args))
2661
+ );
2662
+ }
2663
+ app.use("*", async (ctx, next) => {
2664
+ ctx.set("db", dbServer);
2665
+ ctx.set("debug", Boolean(debug));
2666
+ ctx.set("platform", platform);
2667
+ ctx.set("port", port);
2668
+ ctx.set("protocol", "http");
2669
+ ctx.set("serverState", serverState);
2670
+ ctx.set("shadowDBPort", serverState.shadowDatabasePort);
2671
+ return await next();
2672
+ });
2673
+ const mainRoute = new Hono();
2674
+ mainRoute.route("/", accelerateRoute);
2675
+ mainRoute.route("/", utilityRoute);
2676
+ app.route("/", mainRoute);
2677
+ return app;
2678
+ }
2679
+
2680
+ // ../../dev/server/src/state.ts
2681
+ import { writeFile } from "fs/promises";
2682
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
2683
+
2684
+ // ../../dev/server/src/kernel.ts
2685
+ function checkProcessExists(pid, debug) {
2686
+ if (pid == null) {
2687
+ return false;
2688
+ }
2689
+ try {
2690
+ return y.kill?.(pid, 0) ?? true;
2691
+ } catch (error) {
2692
+ if (debug) {
2693
+ console.error(`Error checking if process with PID ${pid} exists:`, error);
2694
+ }
2695
+ return false;
2696
+ }
2697
+ }
2698
+
2699
+ // ../../dev/server/src/state.ts
2700
+ var urlSchema = pipe(string(), url());
2701
+ var databaseSchema = object({
2702
+ connectionString: urlSchema,
2703
+ prismaORMConnectionString: optional(urlSchema),
2704
+ terminalCommand: optional(string())
2705
+ });
2706
+ var serverSchema = object({
2707
+ url: urlSchema
2708
+ });
2709
+ var portSchema = pipe(number(), integer(), minValue(1));
2710
+ var exportsSchema = object({
2711
+ database: databaseSchema,
2712
+ http: serverSchema,
2713
+ ppg: serverSchema,
2714
+ shadowDatabase: databaseSchema
2715
+ });
2716
+ var serverDumpV1Schema = object({
2717
+ databasePort: portSchema,
2718
+ exports: optional(exportsSchema),
2719
+ name: pipe(string(), minLength(1)),
2720
+ pid: optional(pipe(number(), integer(), minValue(0))),
2721
+ port: portSchema,
2722
+ shadowDatabasePort: portSchema,
2723
+ version: literal("1")
2724
+ });
2725
+ var PRIVATE_INITIALIZE_SYMBOL = Symbol("initialize");
2726
+ var DEFAULT_NAME = "default";
2727
+ var ServerState = class {
2728
+ _databasePort;
2729
+ debug;
2730
+ dryRun;
2731
+ name;
2732
+ persistenceMode;
2733
+ pid;
2734
+ _port;
2735
+ _shadowDatabasePort;
2736
+ constructor(options) {
2737
+ this._databasePort = options.databasePort ?? NO_PORT;
2738
+ this.debug = options.debug ?? false;
2739
+ this.dryRun = options.dryRun ?? false;
2740
+ this.name = options.name ?? DEFAULT_NAME;
2741
+ this.persistenceMode = options.persistenceMode;
2742
+ this.pid = options.pid ?? y.pid;
2743
+ this._port = options.port ?? NO_PORT;
2744
+ this._shadowDatabasePort = options.shadowDatabasePort ?? NO_PORT;
2745
+ }
2746
+ static async createExclusively(options) {
2747
+ const serverState = options?.dryRun !== true && options?.persistenceMode !== "stateless" ? new StatefulServerState(options) : new StatelessServerState(options);
2748
+ await serverState[PRIVATE_INITIALIZE_SYMBOL]();
2749
+ return serverState;
2750
+ }
2751
+ static async fromServerDump(options) {
2752
+ const { debug, name = DEFAULT_NAME } = options ?? {};
2753
+ const dataDirPath = getDataDirPath(name);
2754
+ const serverDumpPath = StatefulServerState.getServerDumpPath(dataDirPath);
2755
+ const serverDumpFileContent = await readFileAsText(serverDumpPath);
2756
+ if (serverDumpFileContent == null) {
2757
+ if (debug) {
2758
+ console.debug(`[State] No server dump file found at: ${serverDumpPath}`);
2759
+ }
2760
+ return null;
2761
+ }
2762
+ if (debug) {
2763
+ console.debug(`[State] server dump file found at "${serverDumpPath}":`);
2764
+ console.debug(serverDumpFileContent);
2765
+ }
2766
+ const {
2767
+ issues,
2768
+ output: serverDump,
2769
+ success
2770
+ } = safeParse(pipe(string(), parseJson(), serverDumpV1Schema), serverDumpFileContent);
2771
+ if (!success) {
2772
+ if (debug) {
2773
+ console.debug(`[State] Invalid server dump file at "${serverDumpPath}":
2774
+ ${JSON.stringify(issues, null, 2)}`);
2775
+ }
2776
+ throw new Error(`Invalid Prisma Dev state for "${name}".`);
2777
+ }
2778
+ return new StatefulServerState({
2779
+ databasePort: serverDump.databasePort,
2780
+ debug,
2781
+ dryRun: false,
2782
+ name,
2783
+ pid: serverDump.pid,
2784
+ port: serverDump.port,
2785
+ serverDump,
2786
+ shadowDatabasePort: serverDump.shadowDatabasePort
2787
+ });
2788
+ }
2789
+ static async scan(options) {
2790
+ const { debug } = options ?? {};
2791
+ const dataDirsPath = join(getDataDirPath(DEFAULT_NAME), "..");
2792
+ if (debug) {
2793
+ console.debug(`[State] scanning for server states in: ${dataDirsPath}`);
2794
+ }
2795
+ const names = await readDirectoryNames(dataDirsPath);
2796
+ if (debug) {
2797
+ console.debug(`[State] found server names: ${JSON.stringify(names)}`);
2798
+ }
2799
+ return await Promise.all(names.map((name) => getServerStatus(name, options)));
2800
+ }
2801
+ get databasePort() {
2802
+ return this._databasePort;
2803
+ }
2804
+ get port() {
2805
+ return this._port;
2806
+ }
2807
+ get shadowDatabasePort() {
2808
+ return this._shadowDatabasePort;
2809
+ }
2810
+ };
2811
+ var StatelessServerState = class extends ServerState {
2812
+ constructor(options) {
2813
+ super({
2814
+ ...options,
2815
+ databasePort: options?.databasePort ?? DEFAULT_DATABASE_PORT,
2816
+ persistenceMode: "stateless",
2817
+ port: options?.port ?? DEFAULT_SERVER_PORT,
2818
+ shadowDatabasePort: options?.shadowDatabasePort ?? DEFAULT_SHADOW_DATABASE_PORT
2819
+ });
2820
+ }
2821
+ get databaseDumpPath() {
2822
+ return "<DUMP_PATH>";
2823
+ }
2824
+ get pgliteDataDirPath() {
2825
+ return "memory://";
2826
+ }
2827
+ async [PRIVATE_INITIALIZE_SYMBOL]() {
2828
+ }
2829
+ async close() {
2830
+ }
2831
+ async writeServerDump() {
2832
+ }
2833
+ };
2834
+ var StatefulServerState = class _StatefulServerState extends ServerState {
2835
+ #databaseDumpPath;
2836
+ #dataDirPath;
2837
+ #pglitePath;
2838
+ #serverDumpPath;
2839
+ #serverDump;
2840
+ #unlock = null;
2841
+ constructor(options) {
2842
+ super({ ...options, persistenceMode: "stateful" });
2843
+ this.#dataDirPath = getDataDirPath(this.name);
2844
+ this.#databaseDumpPath = join(this.#dataDirPath, "db_dump.bak");
2845
+ this.#pglitePath = join(this.#dataDirPath, ".pglite");
2846
+ this.#serverDump = options?.serverDump ?? null;
2847
+ this.#serverDumpPath = _StatefulServerState.getServerDumpPath(this.#dataDirPath);
2848
+ }
2849
+ static getServerDumpPath(dataDirPath) {
2850
+ return join(dataDirPath, "server.json");
2851
+ }
2852
+ get databaseDumpPath() {
2853
+ return this.#databaseDumpPath;
2854
+ }
2855
+ get exports() {
2856
+ return this.#serverDump?.exports;
2857
+ }
2858
+ get pgliteDataDirPath() {
2859
+ return this.#pglitePath;
2860
+ }
2861
+ async [PRIVATE_INITIALIZE_SYMBOL]() {
2862
+ await ensureDirectory(this.#dataDirPath);
2863
+ if (this.debug) {
2864
+ console.debug(`[State] using data directory: ${this.#dataDirPath}`);
2865
+ }
2866
+ try {
2867
+ this.#unlock = await (0, import_proper_lockfile.lock)(this.#dataDirPath, { lockfilePath: join(this.#dataDirPath, ".lock") });
2868
+ if (this.debug) {
2869
+ console.debug(`[State] obtained lock on: ${this.#dataDirPath}`);
2870
+ }
2871
+ const servers = await ServerState.scan({ debug: this.debug, onlyMetadata: true });
2872
+ const ports = await pickPorts({
2873
+ debug: this.debug,
2874
+ name: this.name,
2875
+ requestedPorts: {
2876
+ databasePort: this.databasePort,
2877
+ port: this.port,
2878
+ shadowDatabasePort: this.shadowDatabasePort
2879
+ },
2880
+ servers
2881
+ });
2882
+ this._databasePort = ports.databasePort;
2883
+ this._port = ports.port;
2884
+ this._shadowDatabasePort = ports.shadowDatabasePort;
2885
+ await this.writeServerDump();
2886
+ } catch (error) {
2887
+ if (error instanceof Error && "code" in error && error.code === "ELOCKED") {
2888
+ throw new ServerAlreadyRunningError(this);
2889
+ }
2890
+ throw error;
2891
+ }
2892
+ }
2893
+ async close() {
2894
+ if (this.#unlock == null) {
2895
+ return;
2896
+ }
2897
+ try {
2898
+ await this.#unlock();
2899
+ this.#unlock = null;
2900
+ if (this.debug) {
2901
+ console.debug(`[State] released lock on: ${this.#dataDirPath}`);
2902
+ }
2903
+ } catch (error) {
2904
+ console.error(`[State] failed to release lock on: ${this.#dataDirPath}`);
2905
+ throw error;
2906
+ }
2907
+ }
2908
+ async writeServerDump(exports) {
2909
+ this.#serverDump = {
2910
+ name: this.name,
2911
+ version: "1",
2912
+ pid: y.pid,
2913
+ port: this.port,
2914
+ databasePort: this.databasePort,
2915
+ shadowDatabasePort: this.shadowDatabasePort,
2916
+ exports
2917
+ };
2918
+ await writeFile(this.#serverDumpPath, `${JSON.stringify(this.#serverDump, null, 2)}
2919
+ `, { encoding: "utf-8" });
2920
+ }
2921
+ };
2922
+ async function getServerStatus(name, options) {
2923
+ const { debug, onlyMetadata } = options || {};
2924
+ const baseResult = {
2925
+ databasePort: -1,
2926
+ exports: void 0,
2927
+ name,
2928
+ pid: void 0,
2929
+ port: -1,
2930
+ shadowDatabasePort: -1,
2931
+ version: "1"
2932
+ };
2933
+ try {
2934
+ const serverState = await ServerState.fromServerDump({ debug, name });
2935
+ if (!serverState) {
2936
+ if (debug) {
2937
+ console.debug(`[State] no server state found for name: ${name}`);
2938
+ }
2939
+ return { ...baseResult, status: "no_such_server" };
2940
+ }
2941
+ baseResult.databasePort = serverState.databasePort;
2942
+ baseResult.exports = serverState.exports;
2943
+ baseResult.pid = serverState.pid;
2944
+ baseResult.port = serverState.port;
2945
+ baseResult.shadowDatabasePort = serverState.shadowDatabasePort;
2946
+ const { exports, pid } = serverState;
2947
+ if (onlyMetadata) {
2948
+ return { ...baseResult, status: "unknown" };
2949
+ }
2950
+ if (!checkProcessExists(pid, debug)) {
2951
+ if (debug) {
2952
+ console.debug(`[State] server state for "${name}" has no running process with PID: ${pid}`);
2953
+ }
2954
+ return { ...baseResult, status: "not_running" };
2955
+ }
2956
+ const dataDirPath = getDataDirPath(name);
2957
+ try {
2958
+ if (!await (0, import_proper_lockfile.check)(dataDirPath, { lockfilePath: join(dataDirPath, ".lock") })) {
2959
+ if (debug) {
2960
+ console.debug(`[State] server state for "${name}" is not locked, indicating it is not running.`);
2961
+ }
2962
+ return { ...baseResult, status: "starting_up" };
2963
+ }
2964
+ } catch (error) {
2965
+ if (debug) {
2966
+ console.error(`[State] server state for "${name}" failed to check lock:`, error);
2967
+ }
2968
+ }
2969
+ if (!exports) {
2970
+ return { ...baseResult, status: "starting_up" };
2971
+ }
2972
+ const { http } = exports;
2973
+ const { hc } = await import("hono/client");
2974
+ const healthResponse = await hc(http.url).health.$get();
2975
+ if (!healthResponse.ok) {
2976
+ if (debug) {
2977
+ console.debug(`[State] server state for "${name}" is not live: ${JSON.stringify(healthResponse)}`);
2978
+ }
2979
+ return { ...baseResult, status: "not_running" };
2980
+ }
2981
+ const health = await healthResponse.json();
2982
+ if (health.name !== name) {
2983
+ if (debug) {
2984
+ console.debug(`[State] server state for "${name}" has mismatched health response: ${JSON.stringify(health)}`);
2985
+ }
2986
+ return { ...baseResult, status: "unknown" };
2987
+ }
2988
+ if (debug) {
2989
+ console.debug(`[State] server state for "${name}" is live: ${JSON.stringify(health)}`);
2990
+ }
2991
+ return { ...baseResult, status: "running" };
2992
+ } catch (error) {
2993
+ if (debug) {
2994
+ console.error(`[State] failed to get server status for "${name}":`, error);
2995
+ }
2996
+ return { ...baseResult, status: "error" };
2997
+ }
2998
+ }
2999
+ var ServerStateAlreadyExistsError = class extends Error {
3000
+ name = "ServerStateAlreadyExistsError";
3001
+ constructor(name) {
3002
+ super(`A Prisma Dev server with the name "${name}" is already running.`);
3003
+ }
3004
+ };
3005
+ var ServerAlreadyRunningError = class extends ServerStateAlreadyExistsError {
3006
+ #server;
3007
+ name = "ServerAlreadyRunningError";
3008
+ constructor(server) {
3009
+ super(server.name);
3010
+ this.#server = server;
3011
+ }
3012
+ get server() {
3013
+ return ServerState.fromServerDump({ debug: this.#server.debug, name: this.#server.name });
3014
+ }
3015
+ };
3016
+
3017
+ // ../../dev/server/src/index.ts
3018
+ async function unstable_startServer(options) {
3019
+ const serverState = await ServerState.createExclusively(options);
3020
+ const [dbServer, shadowDbServer] = await Promise.all([
3021
+ startDBServer("database", serverState),
3022
+ startDBServer("shadow_database", serverState)
3023
+ ]);
3024
+ const httpServer = await startHTTPServer(dbServer, serverState);
3025
+ const ppgURL = `prisma+postgres://localhost:${httpServer.port}/?${new URLSearchParams({
3026
+ api_key: encodeAPIKey({
3027
+ databaseUrl: dbServer.prismaORMConnectionString,
3028
+ name: serverState.name,
3029
+ shadowDatabaseUrl: shadowDbServer.prismaORMConnectionString
3030
+ })
3031
+ }).toString()}`;
3032
+ const exports = {
3033
+ database: {
3034
+ connectionString: dbServer.connectionString,
3035
+ prismaORMConnectionString: dbServer.prismaORMConnectionString,
3036
+ terminalCommand: dbServer.terminalCommand
3037
+ },
3038
+ http: { url: httpServer.url },
3039
+ ppg: { url: ppgURL },
3040
+ shadowDatabase: {
3041
+ connectionString: shadowDbServer.prismaORMConnectionString,
3042
+ prismaORMConnectionString: shadowDbServer.prismaORMConnectionString,
3043
+ terminalCommand: shadowDbServer.terminalCommand
3044
+ }
3045
+ };
3046
+ await serverState.writeServerDump(exports);
3047
+ return {
3048
+ ...exports,
3049
+ close: () => closeServer(serverState, [httpServer, dbServer, shadowDbServer]),
3050
+ name: serverState.name
3051
+ };
3052
+ async function closeServer(serverState2, servers) {
3053
+ const results = await Promise.allSettled(servers.map((server) => server.close()));
3054
+ const errors = results.filter((result) => result.status === "rejected").map((result) => new Error(result.reason));
3055
+ try {
3056
+ await serverState2.close();
3057
+ } catch (error) {
3058
+ errors.push(error);
3059
+ }
3060
+ if (errors.length > 0) {
3061
+ throw new AggregateError(errors, `Failed to close some servers`);
3062
+ }
3063
+ }
3064
+ }
8
3065
 
9
3066
  // src/Init.ts
10
- import { confirm, input, select } from "@inquirer/prompts";
11
3067
  import internals from "@prisma/internals";
12
3068
  import dotenv from "dotenv";
13
3069
  import { Schema as Shape } from "effect";
@@ -78,7 +3134,7 @@ var getRegionsOrThrow = async (input2) => {
78
3134
  };
79
3135
  var getPrismaPostgresRegionsOrThrow = async (input2) => {
80
3136
  const regions = await getRegionsOrThrow(input2);
81
- const ppgRegions = regions.filter((_) => _.ppgStatus !== "unsupported").sort((a, b) => b.displayName.localeCompare(a.displayName));
3137
+ const ppgRegions = regions.filter((_) => _.ppgStatus !== "unsupported").sort((a2, b) => b.displayName.localeCompare(a2.displayName));
82
3138
  return ppgRegions;
83
3139
  };
84
3140
 
@@ -89,7 +3145,6 @@ function printError(text) {
89
3145
  }
90
3146
 
91
3147
  // src/Init.ts
92
- var PRISMA_DEV_DEFAULT_URL = "prisma+postgres://localhost:51213/?api_key=eyJkYXRhYmFzZVVybCI6InBvc3RncmVzOi8vcG9zdGdyZXM6cG9zdGdyZXNAbG9jYWxob3N0OjUxMjE0L3RlbXBsYXRlMT9jb25uZWN0aW9uX2xpbWl0PTEmY29ubmVjdF90aW1lb3V0PTAmbWF4X2lkbGVfY29ubmVjdGlvbl9saWZldGltZT0wJnBvb2xfdGltZW91dD0wJnNvY2tldF90aW1lb3V0PTAmc3NsbW9kZT1kaXNhYmxlIiwic2hhZG93RGF0YWJhc2VVcmwiOiJwb3N0Z3JlczovL3Bvc3RncmVzOnBvc3RncmVzQGxvY2FsaG9zdDo1MTIxNS90ZW1wbGF0ZTE_Y29ubmVjdGlvbl9saW1pdD0xJmNvbm5lY3RfdGltZW91dD0wJm1heF9pZGxlX2Nvbm5lY3Rpb25fbGlmZXRpbWU9MCZwb29sX3RpbWVvdXQ9MCZzb2NrZXRfdGltZW91dD0wJnNzbG1vZGU9ZGlzYWJsZSJ9";
93
3148
  var defaultSchema = (props) => {
94
3149
  const {
95
3150
  datasourceProvider = "postgresql",
@@ -148,19 +3203,33 @@ model User {
148
3203
  }
149
3204
  return schema;
150
3205
  };
151
- var defaultEnv = (url = PRISMA_DEV_DEFAULT_URL, comments = true) => {
3206
+ var defaultEnv = async (url2, comments = true) => {
3207
+ if (url2 === void 0) {
3208
+ let created = false;
3209
+ const state = await ServerState.fromServerDump() || (created = true, await ServerState.createExclusively({ persistenceMode: "stateful" }));
3210
+ if (created) {
3211
+ await state.close();
3212
+ }
3213
+ const server = await unstable_startServer({
3214
+ databasePort: state.databasePort,
3215
+ dryRun: true,
3216
+ port: state.port,
3217
+ shadowDatabasePort: state.shadowDatabasePort
3218
+ });
3219
+ url2 = server.ppg.url;
3220
+ }
152
3221
  let env = comments ? `# Environment variables declared in this file are automatically made available to Prisma.
153
3222
  # See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
154
3223
 
155
3224
  # Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
156
3225
  # See the documentation for all the connection string options: https://pris.ly/d/connection-strings
157
3226
 
158
- ${url === PRISMA_DEV_DEFAULT_URL ? `# The following \`prisma+postgres\` URL is similar to the URL produced by running a local Prisma Postgres
3227
+ ${url2.startsWith("prisma+postgres:") && url2.includes("localhost") ? `# The following \`prisma+postgres\` URL is similar to the URL produced by running a local Prisma Postgres
159
3228
  # server with the \`prisma dev\` CLI command, when not choosing any non-default ports or settings. The API key, unlike the
160
3229
  # one found in a remote Prisma Postgres URL, does not contain any sensitive information.
161
3230
 
162
3231
  ` : ""}` : "";
163
- env += `DATABASE_URL="${url}"`;
3232
+ env += `DATABASE_URL="${url2}"`;
164
3233
  return env;
165
3234
  };
166
3235
  var defaultPort = (datasourceProvider) => {
@@ -279,7 +3348,7 @@ var Init = class _Init {
279
3348
  if (outputDirName) {
280
3349
  throw Error("The init command does not take any argument.");
281
3350
  }
282
- const { datasourceProvider, url } = await match(args).with(
3351
+ const { datasourceProvider, url: url2 } = await match(args).with(
283
3352
  {
284
3353
  "--datasource-provider": P.when(
285
3354
  (datasourceProvider2) => Boolean(datasourceProvider2)
@@ -288,16 +3357,16 @@ var Init = class _Init {
288
3357
  (input2) => {
289
3358
  const datasourceProvider2 = input2["--datasource-provider"].toLowerCase();
290
3359
  assertDatasourceProvider(datasourceProvider2);
291
- const url2 = defaultURL(datasourceProvider2);
292
- return { datasourceProvider: datasourceProvider2, url: url2 };
3360
+ const url3 = defaultURL(datasourceProvider2);
3361
+ return { datasourceProvider: datasourceProvider2, url: url3 };
293
3362
  }
294
3363
  ).with(
295
3364
  {
296
- "--url": P.when((url2) => Boolean(url2))
3365
+ "--url": P.when((url3) => Boolean(url3))
297
3366
  },
298
3367
  async (input2) => {
299
- const url2 = input2["--url"];
300
- const canConnect = await internals.canConnectToDatabase(url2);
3368
+ const url3 = input2["--url"];
3369
+ const canConnect = await internals.canConnectToDatabase(url3);
301
3370
  if (canConnect !== true) {
302
3371
  const { code, message } = canConnect;
303
3372
  if (code !== "P1003") {
@@ -308,8 +3377,8 @@ var Init = class _Init {
308
3377
  }
309
3378
  }
310
3379
  }
311
- const datasourceProvider2 = internals.protocolToConnectorType(`${url2.split(":")[0]}:`);
312
- return { datasourceProvider: datasourceProvider2, url: url2 };
3380
+ const datasourceProvider2 = internals.protocolToConnectorType(`${url3.split(":")[0]}:`);
3381
+ return { datasourceProvider: datasourceProvider2, url: url3 };
313
3382
  }
314
3383
  ).otherwise(() => {
315
3384
  return {
@@ -330,7 +3399,7 @@ var Init = class _Init {
330
3399
  let generatedSchema;
331
3400
  let generatedName;
332
3401
  if (isPpgCommand) {
333
- const PlatformCommands = await import("./_-O567UZLT.js");
3402
+ const PlatformCommands = await import("./_-WIN5AVS3.js");
334
3403
  const credentials = await credentialsFile.load();
335
3404
  if (internals.isError(credentials))
336
3405
  throw credentials;
@@ -481,11 +3550,11 @@ var Init = class _Init {
481
3550
  withModel: args["--with-model"]
482
3551
  })
483
3552
  );
484
- const databaseUrl = prismaPostgresDatabaseUrl || url;
3553
+ const databaseUrl = prismaPostgresDatabaseUrl || url2;
485
3554
  const warnings = [];
486
3555
  const envPath = path2.join(outputDir, ".env");
487
3556
  if (!fs2.existsSync(envPath)) {
488
- fs2.writeFileSync(envPath, defaultEnv(databaseUrl));
3557
+ fs2.writeFileSync(envPath, await defaultEnv(databaseUrl));
489
3558
  } else {
490
3559
  const envFile = fs2.readFileSync(envPath, { encoding: "utf8" });
491
3560
  const config = dotenv.parse(envFile);
@@ -525,39 +3594,41 @@ var Init = class _Init {
525
3594
  console.error("Failed to append client path to .gitignore file, reason: ", e);
526
3595
  }
527
3596
  const steps = [];
528
- if (datasourceProvider === "mongodb") {
529
- steps.push(`Define models in the schema.prisma file.`);
3597
+ const isPrismaDev = !args["--url"] && (datasourceProvider === "postgres" || datasourceProvider === "postgresql");
3598
+ if (isPrismaDev) {
3599
+ steps.push(
3600
+ `Run ${green(internals.getCommandWithExecutor("prisma dev"))} to start a local Prisma Postgres server.`
3601
+ );
3602
+ } else if (!args["--url"]) {
3603
+ steps.push(
3604
+ `Set the ${green("DATABASE_URL")} in the ${green(
3605
+ ".env"
3606
+ )} file to point to your existing database. If your database has no ${datasourceProvider === "mongodb" ? "collections" : "tables"} yet, read https://pris.ly/d/getting-started`
3607
+ );
3608
+ }
3609
+ if (isPrismaDev || datasourceProvider === "mongodb") {
3610
+ steps.push(`Define models in the ${green("schema.prisma")} file.`);
530
3611
  } else {
531
3612
  steps.push(
532
3613
  `Run ${green(internals.getCommandWithExecutor("prisma db pull"))} to turn your database schema into a Prisma schema.`
533
3614
  );
534
3615
  }
535
- steps.push(
536
- `Run ${green(
537
- internals.getCommandWithExecutor("prisma generate")
538
- )} to generate the Prisma Client. You can then start querying your database.`
539
- );
3616
+ if (isPrismaDev) {
3617
+ steps.push(
3618
+ `Run ${green(internals.getCommandWithExecutor("prisma migrate dev"))} to migrate your local Prisma Postgres database.`
3619
+ );
3620
+ } else {
3621
+ steps.push(
3622
+ `Run ${green(
3623
+ internals.getCommandWithExecutor("prisma generate")
3624
+ )} to generate the Prisma Client. You can then start querying your database.`
3625
+ );
3626
+ }
540
3627
  steps.push(
541
3628
  `Tip: Explore how you can extend the ${green(
542
3629
  "ORM"
543
- )} with scalable connection pooling, global caching, and real-time database events. Read: https://pris.ly/cli/beyond-orm`
3630
+ )} with scalable connection pooling, global caching, and a managed serverless Postgres database. Read: https://pris.ly/cli/beyond-orm`
544
3631
  );
545
- if (!url && !args["--datasource-provider"]) {
546
- steps.unshift(
547
- `Set the ${green("provider")} of the ${green("datasource")} block in ${green(
548
- "schema.prisma"
549
- )} to match your database: ${green("postgresql")}, ${green("mysql")}, ${green("sqlite")}, ${green(
550
- "sqlserver"
551
- )}, ${green("mongodb")} or ${green("cockroachdb")}.`
552
- );
553
- }
554
- if (!args["--url"]) {
555
- steps.unshift(
556
- `Set the ${green("DATABASE_URL")} in the ${green(
557
- ".env"
558
- )} file to point to your existing database. If your database has no tables yet, read https://pris.ly/d/getting-started`
559
- );
560
- }
561
3632
  const defaultOutput = `
562
3633
  \u2714 Your Prisma schema was created at ${green("prisma/schema.prisma")}
563
3634
  You can now open it in your favorite editor.
@@ -565,7 +3636,7 @@ ${warnings.length > 0 && internals.logger.should.warn() ? `
565
3636
  ${warnings.join("\n")}
566
3637
  ` : ""}
567
3638
  Next steps:
568
- ${steps.map((s, i) => `${i + 1}. ${s}`).join("\n")}
3639
+ ${steps.map((s2, i) => `${i + 1}. ${s2}`).join("\n")}
569
3640
 
570
3641
  More information in our documentation:
571
3642
  ${internals.link("https://pris.ly/d/getting-started")}