swarm-mail 0.1.4 → 0.2.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,4 +1,21 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
1
4
  var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __toESM = (mod, isNodeMode, target) => {
8
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
9
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
+ for (let key of __getOwnPropNames(mod))
11
+ if (!__hasOwnProp.call(to, key))
12
+ __defProp(to, key, {
13
+ get: () => mod[key],
14
+ enumerable: true
15
+ });
16
+ return to;
17
+ };
18
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
2
19
  var __export = (target, all) => {
3
20
  for (var name in all)
4
21
  __defProp(target, name, {
@@ -9,6 +26,1575 @@ var __export = (target, all) => {
9
26
  });
10
27
  };
11
28
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
29
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
30
+
31
+ // ../../node_modules/.bun/graceful-fs@4.2.11/node_modules/graceful-fs/polyfills.js
32
+ var require_polyfills = __commonJS((exports, module) => {
33
+ var constants = __require("constants");
34
+ var origCwd = process.cwd;
35
+ var cwd = null;
36
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
37
+ process.cwd = function() {
38
+ if (!cwd)
39
+ cwd = origCwd.call(process);
40
+ return cwd;
41
+ };
42
+ try {
43
+ process.cwd();
44
+ } catch (er) {}
45
+ if (typeof process.chdir === "function") {
46
+ chdir = process.chdir;
47
+ process.chdir = function(d) {
48
+ cwd = null;
49
+ chdir.call(process, d);
50
+ };
51
+ if (Object.setPrototypeOf)
52
+ Object.setPrototypeOf(process.chdir, chdir);
53
+ }
54
+ var chdir;
55
+ module.exports = patch;
56
+ function patch(fs) {
57
+ if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
58
+ patchLchmod(fs);
59
+ }
60
+ if (!fs.lutimes) {
61
+ patchLutimes(fs);
62
+ }
63
+ fs.chown = chownFix(fs.chown);
64
+ fs.fchown = chownFix(fs.fchown);
65
+ fs.lchown = chownFix(fs.lchown);
66
+ fs.chmod = chmodFix(fs.chmod);
67
+ fs.fchmod = chmodFix(fs.fchmod);
68
+ fs.lchmod = chmodFix(fs.lchmod);
69
+ fs.chownSync = chownFixSync(fs.chownSync);
70
+ fs.fchownSync = chownFixSync(fs.fchownSync);
71
+ fs.lchownSync = chownFixSync(fs.lchownSync);
72
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
73
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
74
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
75
+ fs.stat = statFix(fs.stat);
76
+ fs.fstat = statFix(fs.fstat);
77
+ fs.lstat = statFix(fs.lstat);
78
+ fs.statSync = statFixSync(fs.statSync);
79
+ fs.fstatSync = statFixSync(fs.fstatSync);
80
+ fs.lstatSync = statFixSync(fs.lstatSync);
81
+ if (fs.chmod && !fs.lchmod) {
82
+ fs.lchmod = function(path, mode, cb) {
83
+ if (cb)
84
+ process.nextTick(cb);
85
+ };
86
+ fs.lchmodSync = function() {};
87
+ }
88
+ if (fs.chown && !fs.lchown) {
89
+ fs.lchown = function(path, uid, gid, cb) {
90
+ if (cb)
91
+ process.nextTick(cb);
92
+ };
93
+ fs.lchownSync = function() {};
94
+ }
95
+ if (platform === "win32") {
96
+ fs.rename = typeof fs.rename !== "function" ? fs.rename : function(fs$rename) {
97
+ function rename(from, to, cb) {
98
+ var start = Date.now();
99
+ var backoff = 0;
100
+ fs$rename(from, to, function CB(er) {
101
+ if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 60000) {
102
+ setTimeout(function() {
103
+ fs.stat(to, function(stater, st) {
104
+ if (stater && stater.code === "ENOENT")
105
+ fs$rename(from, to, CB);
106
+ else
107
+ cb(er);
108
+ });
109
+ }, backoff);
110
+ if (backoff < 100)
111
+ backoff += 10;
112
+ return;
113
+ }
114
+ if (cb)
115
+ cb(er);
116
+ });
117
+ }
118
+ if (Object.setPrototypeOf)
119
+ Object.setPrototypeOf(rename, fs$rename);
120
+ return rename;
121
+ }(fs.rename);
122
+ }
123
+ fs.read = typeof fs.read !== "function" ? fs.read : function(fs$read) {
124
+ function read(fd, buffer, offset, length, position, callback_) {
125
+ var callback;
126
+ if (callback_ && typeof callback_ === "function") {
127
+ var eagCounter = 0;
128
+ callback = function(er, _, __) {
129
+ if (er && er.code === "EAGAIN" && eagCounter < 10) {
130
+ eagCounter++;
131
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
132
+ }
133
+ callback_.apply(this, arguments);
134
+ };
135
+ }
136
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
137
+ }
138
+ if (Object.setPrototypeOf)
139
+ Object.setPrototypeOf(read, fs$read);
140
+ return read;
141
+ }(fs.read);
142
+ fs.readSync = typeof fs.readSync !== "function" ? fs.readSync : function(fs$readSync) {
143
+ return function(fd, buffer, offset, length, position) {
144
+ var eagCounter = 0;
145
+ while (true) {
146
+ try {
147
+ return fs$readSync.call(fs, fd, buffer, offset, length, position);
148
+ } catch (er) {
149
+ if (er.code === "EAGAIN" && eagCounter < 10) {
150
+ eagCounter++;
151
+ continue;
152
+ }
153
+ throw er;
154
+ }
155
+ }
156
+ };
157
+ }(fs.readSync);
158
+ function patchLchmod(fs2) {
159
+ fs2.lchmod = function(path, mode, callback) {
160
+ fs2.open(path, constants.O_WRONLY | constants.O_SYMLINK, mode, function(err, fd) {
161
+ if (err) {
162
+ if (callback)
163
+ callback(err);
164
+ return;
165
+ }
166
+ fs2.fchmod(fd, mode, function(err2) {
167
+ fs2.close(fd, function(err22) {
168
+ if (callback)
169
+ callback(err2 || err22);
170
+ });
171
+ });
172
+ });
173
+ };
174
+ fs2.lchmodSync = function(path, mode) {
175
+ var fd = fs2.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode);
176
+ var threw = true;
177
+ var ret;
178
+ try {
179
+ ret = fs2.fchmodSync(fd, mode);
180
+ threw = false;
181
+ } finally {
182
+ if (threw) {
183
+ try {
184
+ fs2.closeSync(fd);
185
+ } catch (er) {}
186
+ } else {
187
+ fs2.closeSync(fd);
188
+ }
189
+ }
190
+ return ret;
191
+ };
192
+ }
193
+ function patchLutimes(fs2) {
194
+ if (constants.hasOwnProperty("O_SYMLINK") && fs2.futimes) {
195
+ fs2.lutimes = function(path, at, mt, cb) {
196
+ fs2.open(path, constants.O_SYMLINK, function(er, fd) {
197
+ if (er) {
198
+ if (cb)
199
+ cb(er);
200
+ return;
201
+ }
202
+ fs2.futimes(fd, at, mt, function(er2) {
203
+ fs2.close(fd, function(er22) {
204
+ if (cb)
205
+ cb(er2 || er22);
206
+ });
207
+ });
208
+ });
209
+ };
210
+ fs2.lutimesSync = function(path, at, mt) {
211
+ var fd = fs2.openSync(path, constants.O_SYMLINK);
212
+ var ret;
213
+ var threw = true;
214
+ try {
215
+ ret = fs2.futimesSync(fd, at, mt);
216
+ threw = false;
217
+ } finally {
218
+ if (threw) {
219
+ try {
220
+ fs2.closeSync(fd);
221
+ } catch (er) {}
222
+ } else {
223
+ fs2.closeSync(fd);
224
+ }
225
+ }
226
+ return ret;
227
+ };
228
+ } else if (fs2.futimes) {
229
+ fs2.lutimes = function(_a, _b, _c, cb) {
230
+ if (cb)
231
+ process.nextTick(cb);
232
+ };
233
+ fs2.lutimesSync = function() {};
234
+ }
235
+ }
236
+ function chmodFix(orig) {
237
+ if (!orig)
238
+ return orig;
239
+ return function(target, mode, cb) {
240
+ return orig.call(fs, target, mode, function(er) {
241
+ if (chownErOk(er))
242
+ er = null;
243
+ if (cb)
244
+ cb.apply(this, arguments);
245
+ });
246
+ };
247
+ }
248
+ function chmodFixSync(orig) {
249
+ if (!orig)
250
+ return orig;
251
+ return function(target, mode) {
252
+ try {
253
+ return orig.call(fs, target, mode);
254
+ } catch (er) {
255
+ if (!chownErOk(er))
256
+ throw er;
257
+ }
258
+ };
259
+ }
260
+ function chownFix(orig) {
261
+ if (!orig)
262
+ return orig;
263
+ return function(target, uid, gid, cb) {
264
+ return orig.call(fs, target, uid, gid, function(er) {
265
+ if (chownErOk(er))
266
+ er = null;
267
+ if (cb)
268
+ cb.apply(this, arguments);
269
+ });
270
+ };
271
+ }
272
+ function chownFixSync(orig) {
273
+ if (!orig)
274
+ return orig;
275
+ return function(target, uid, gid) {
276
+ try {
277
+ return orig.call(fs, target, uid, gid);
278
+ } catch (er) {
279
+ if (!chownErOk(er))
280
+ throw er;
281
+ }
282
+ };
283
+ }
284
+ function statFix(orig) {
285
+ if (!orig)
286
+ return orig;
287
+ return function(target, options, cb) {
288
+ if (typeof options === "function") {
289
+ cb = options;
290
+ options = null;
291
+ }
292
+ function callback(er, stats) {
293
+ if (stats) {
294
+ if (stats.uid < 0)
295
+ stats.uid += 4294967296;
296
+ if (stats.gid < 0)
297
+ stats.gid += 4294967296;
298
+ }
299
+ if (cb)
300
+ cb.apply(this, arguments);
301
+ }
302
+ return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback);
303
+ };
304
+ }
305
+ function statFixSync(orig) {
306
+ if (!orig)
307
+ return orig;
308
+ return function(target, options) {
309
+ var stats = options ? orig.call(fs, target, options) : orig.call(fs, target);
310
+ if (stats) {
311
+ if (stats.uid < 0)
312
+ stats.uid += 4294967296;
313
+ if (stats.gid < 0)
314
+ stats.gid += 4294967296;
315
+ }
316
+ return stats;
317
+ };
318
+ }
319
+ function chownErOk(er) {
320
+ if (!er)
321
+ return true;
322
+ if (er.code === "ENOSYS")
323
+ return true;
324
+ var nonroot = !process.getuid || process.getuid() !== 0;
325
+ if (nonroot) {
326
+ if (er.code === "EINVAL" || er.code === "EPERM")
327
+ return true;
328
+ }
329
+ return false;
330
+ }
331
+ }
332
+ });
333
+
334
+ // ../../node_modules/.bun/graceful-fs@4.2.11/node_modules/graceful-fs/legacy-streams.js
335
+ var require_legacy_streams = __commonJS((exports, module) => {
336
+ var Stream = __require("stream").Stream;
337
+ module.exports = legacy;
338
+ function legacy(fs) {
339
+ return {
340
+ ReadStream,
341
+ WriteStream
342
+ };
343
+ function ReadStream(path, options) {
344
+ if (!(this instanceof ReadStream))
345
+ return new ReadStream(path, options);
346
+ Stream.call(this);
347
+ var self = this;
348
+ this.path = path;
349
+ this.fd = null;
350
+ this.readable = true;
351
+ this.paused = false;
352
+ this.flags = "r";
353
+ this.mode = 438;
354
+ this.bufferSize = 64 * 1024;
355
+ options = options || {};
356
+ var keys = Object.keys(options);
357
+ for (var index = 0, length = keys.length;index < length; index++) {
358
+ var key = keys[index];
359
+ this[key] = options[key];
360
+ }
361
+ if (this.encoding)
362
+ this.setEncoding(this.encoding);
363
+ if (this.start !== undefined) {
364
+ if (typeof this.start !== "number") {
365
+ throw TypeError("start must be a Number");
366
+ }
367
+ if (this.end === undefined) {
368
+ this.end = Infinity;
369
+ } else if (typeof this.end !== "number") {
370
+ throw TypeError("end must be a Number");
371
+ }
372
+ if (this.start > this.end) {
373
+ throw new Error("start must be <= end");
374
+ }
375
+ this.pos = this.start;
376
+ }
377
+ if (this.fd !== null) {
378
+ process.nextTick(function() {
379
+ self._read();
380
+ });
381
+ return;
382
+ }
383
+ fs.open(this.path, this.flags, this.mode, function(err, fd) {
384
+ if (err) {
385
+ self.emit("error", err);
386
+ self.readable = false;
387
+ return;
388
+ }
389
+ self.fd = fd;
390
+ self.emit("open", fd);
391
+ self._read();
392
+ });
393
+ }
394
+ function WriteStream(path, options) {
395
+ if (!(this instanceof WriteStream))
396
+ return new WriteStream(path, options);
397
+ Stream.call(this);
398
+ this.path = path;
399
+ this.fd = null;
400
+ this.writable = true;
401
+ this.flags = "w";
402
+ this.encoding = "binary";
403
+ this.mode = 438;
404
+ this.bytesWritten = 0;
405
+ options = options || {};
406
+ var keys = Object.keys(options);
407
+ for (var index = 0, length = keys.length;index < length; index++) {
408
+ var key = keys[index];
409
+ this[key] = options[key];
410
+ }
411
+ if (this.start !== undefined) {
412
+ if (typeof this.start !== "number") {
413
+ throw TypeError("start must be a Number");
414
+ }
415
+ if (this.start < 0) {
416
+ throw new Error("start must be >= zero");
417
+ }
418
+ this.pos = this.start;
419
+ }
420
+ this.busy = false;
421
+ this._queue = [];
422
+ if (this.fd === null) {
423
+ this._open = fs.open;
424
+ this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
425
+ this.flush();
426
+ }
427
+ }
428
+ }
429
+ });
430
+
431
+ // ../../node_modules/.bun/graceful-fs@4.2.11/node_modules/graceful-fs/clone.js
432
+ var require_clone = __commonJS((exports, module) => {
433
+ module.exports = clone;
434
+ var getPrototypeOf = Object.getPrototypeOf || function(obj) {
435
+ return obj.__proto__;
436
+ };
437
+ function clone(obj) {
438
+ if (obj === null || typeof obj !== "object")
439
+ return obj;
440
+ if (obj instanceof Object)
441
+ var copy = { __proto__: getPrototypeOf(obj) };
442
+ else
443
+ var copy = Object.create(null);
444
+ Object.getOwnPropertyNames(obj).forEach(function(key) {
445
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
446
+ });
447
+ return copy;
448
+ }
449
+ });
450
+
451
+ // ../../node_modules/.bun/graceful-fs@4.2.11/node_modules/graceful-fs/graceful-fs.js
452
+ var require_graceful_fs = __commonJS((exports, module) => {
453
+ var fs = __require("fs");
454
+ var polyfills = require_polyfills();
455
+ var legacy = require_legacy_streams();
456
+ var clone = require_clone();
457
+ var util = __require("util");
458
+ var gracefulQueue;
459
+ var previousSymbol;
460
+ if (typeof Symbol === "function" && typeof Symbol.for === "function") {
461
+ gracefulQueue = Symbol.for("graceful-fs.queue");
462
+ previousSymbol = Symbol.for("graceful-fs.previous");
463
+ } else {
464
+ gracefulQueue = "___graceful-fs.queue";
465
+ previousSymbol = "___graceful-fs.previous";
466
+ }
467
+ function noop() {}
468
+ function publishQueue(context, queue2) {
469
+ Object.defineProperty(context, gracefulQueue, {
470
+ get: function() {
471
+ return queue2;
472
+ }
473
+ });
474
+ }
475
+ var debug = noop;
476
+ if (util.debuglog)
477
+ debug = util.debuglog("gfs4");
478
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
479
+ debug = function() {
480
+ var m = util.format.apply(util, arguments);
481
+ m = "GFS4: " + m.split(/\n/).join(`
482
+ GFS4: `);
483
+ console.error(m);
484
+ };
485
+ if (!fs[gracefulQueue]) {
486
+ queue = global[gracefulQueue] || [];
487
+ publishQueue(fs, queue);
488
+ fs.close = function(fs$close) {
489
+ function close(fd, cb) {
490
+ return fs$close.call(fs, fd, function(err) {
491
+ if (!err) {
492
+ resetQueue();
493
+ }
494
+ if (typeof cb === "function")
495
+ cb.apply(this, arguments);
496
+ });
497
+ }
498
+ Object.defineProperty(close, previousSymbol, {
499
+ value: fs$close
500
+ });
501
+ return close;
502
+ }(fs.close);
503
+ fs.closeSync = function(fs$closeSync) {
504
+ function closeSync(fd) {
505
+ fs$closeSync.apply(fs, arguments);
506
+ resetQueue();
507
+ }
508
+ Object.defineProperty(closeSync, previousSymbol, {
509
+ value: fs$closeSync
510
+ });
511
+ return closeSync;
512
+ }(fs.closeSync);
513
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
514
+ process.on("exit", function() {
515
+ debug(fs[gracefulQueue]);
516
+ __require("assert").equal(fs[gracefulQueue].length, 0);
517
+ });
518
+ }
519
+ }
520
+ var queue;
521
+ if (!global[gracefulQueue]) {
522
+ publishQueue(global, fs[gracefulQueue]);
523
+ }
524
+ module.exports = patch(clone(fs));
525
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
526
+ module.exports = patch(fs);
527
+ fs.__patched = true;
528
+ }
529
+ function patch(fs2) {
530
+ polyfills(fs2);
531
+ fs2.gracefulify = patch;
532
+ fs2.createReadStream = createReadStream;
533
+ fs2.createWriteStream = createWriteStream;
534
+ var fs$readFile = fs2.readFile;
535
+ fs2.readFile = readFile;
536
+ function readFile(path, options, cb) {
537
+ if (typeof options === "function")
538
+ cb = options, options = null;
539
+ return go$readFile(path, options, cb);
540
+ function go$readFile(path2, options2, cb2, startTime) {
541
+ return fs$readFile(path2, options2, function(err) {
542
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
543
+ enqueue([go$readFile, [path2, options2, cb2], err, startTime || Date.now(), Date.now()]);
544
+ else {
545
+ if (typeof cb2 === "function")
546
+ cb2.apply(this, arguments);
547
+ }
548
+ });
549
+ }
550
+ }
551
+ var fs$writeFile = fs2.writeFile;
552
+ fs2.writeFile = writeFile;
553
+ function writeFile(path, data, options, cb) {
554
+ if (typeof options === "function")
555
+ cb = options, options = null;
556
+ return go$writeFile(path, data, options, cb);
557
+ function go$writeFile(path2, data2, options2, cb2, startTime) {
558
+ return fs$writeFile(path2, data2, options2, function(err) {
559
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
560
+ enqueue([go$writeFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
561
+ else {
562
+ if (typeof cb2 === "function")
563
+ cb2.apply(this, arguments);
564
+ }
565
+ });
566
+ }
567
+ }
568
+ var fs$appendFile = fs2.appendFile;
569
+ if (fs$appendFile)
570
+ fs2.appendFile = appendFile;
571
+ function appendFile(path, data, options, cb) {
572
+ if (typeof options === "function")
573
+ cb = options, options = null;
574
+ return go$appendFile(path, data, options, cb);
575
+ function go$appendFile(path2, data2, options2, cb2, startTime) {
576
+ return fs$appendFile(path2, data2, options2, function(err) {
577
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
578
+ enqueue([go$appendFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
579
+ else {
580
+ if (typeof cb2 === "function")
581
+ cb2.apply(this, arguments);
582
+ }
583
+ });
584
+ }
585
+ }
586
+ var fs$copyFile = fs2.copyFile;
587
+ if (fs$copyFile)
588
+ fs2.copyFile = copyFile;
589
+ function copyFile(src, dest, flags, cb) {
590
+ if (typeof flags === "function") {
591
+ cb = flags;
592
+ flags = 0;
593
+ }
594
+ return go$copyFile(src, dest, flags, cb);
595
+ function go$copyFile(src2, dest2, flags2, cb2, startTime) {
596
+ return fs$copyFile(src2, dest2, flags2, function(err) {
597
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
598
+ enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
599
+ else {
600
+ if (typeof cb2 === "function")
601
+ cb2.apply(this, arguments);
602
+ }
603
+ });
604
+ }
605
+ }
606
+ var fs$readdir = fs2.readdir;
607
+ fs2.readdir = readdir;
608
+ var noReaddirOptionVersions = /^v[0-5]\./;
609
+ function readdir(path, options, cb) {
610
+ if (typeof options === "function")
611
+ cb = options, options = null;
612
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir(path2, options2, cb2, startTime) {
613
+ return fs$readdir(path2, fs$readdirCallback(path2, options2, cb2, startTime));
614
+ } : function go$readdir(path2, options2, cb2, startTime) {
615
+ return fs$readdir(path2, options2, fs$readdirCallback(path2, options2, cb2, startTime));
616
+ };
617
+ return go$readdir(path, options, cb);
618
+ function fs$readdirCallback(path2, options2, cb2, startTime) {
619
+ return function(err, files) {
620
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
621
+ enqueue([
622
+ go$readdir,
623
+ [path2, options2, cb2],
624
+ err,
625
+ startTime || Date.now(),
626
+ Date.now()
627
+ ]);
628
+ else {
629
+ if (files && files.sort)
630
+ files.sort();
631
+ if (typeof cb2 === "function")
632
+ cb2.call(this, err, files);
633
+ }
634
+ };
635
+ }
636
+ }
637
+ if (process.version.substr(0, 4) === "v0.8") {
638
+ var legStreams = legacy(fs2);
639
+ ReadStream = legStreams.ReadStream;
640
+ WriteStream = legStreams.WriteStream;
641
+ }
642
+ var fs$ReadStream = fs2.ReadStream;
643
+ if (fs$ReadStream) {
644
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
645
+ ReadStream.prototype.open = ReadStream$open;
646
+ }
647
+ var fs$WriteStream = fs2.WriteStream;
648
+ if (fs$WriteStream) {
649
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
650
+ WriteStream.prototype.open = WriteStream$open;
651
+ }
652
+ Object.defineProperty(fs2, "ReadStream", {
653
+ get: function() {
654
+ return ReadStream;
655
+ },
656
+ set: function(val) {
657
+ ReadStream = val;
658
+ },
659
+ enumerable: true,
660
+ configurable: true
661
+ });
662
+ Object.defineProperty(fs2, "WriteStream", {
663
+ get: function() {
664
+ return WriteStream;
665
+ },
666
+ set: function(val) {
667
+ WriteStream = val;
668
+ },
669
+ enumerable: true,
670
+ configurable: true
671
+ });
672
+ var FileReadStream = ReadStream;
673
+ Object.defineProperty(fs2, "FileReadStream", {
674
+ get: function() {
675
+ return FileReadStream;
676
+ },
677
+ set: function(val) {
678
+ FileReadStream = val;
679
+ },
680
+ enumerable: true,
681
+ configurable: true
682
+ });
683
+ var FileWriteStream = WriteStream;
684
+ Object.defineProperty(fs2, "FileWriteStream", {
685
+ get: function() {
686
+ return FileWriteStream;
687
+ },
688
+ set: function(val) {
689
+ FileWriteStream = val;
690
+ },
691
+ enumerable: true,
692
+ configurable: true
693
+ });
694
+ function ReadStream(path, options) {
695
+ if (this instanceof ReadStream)
696
+ return fs$ReadStream.apply(this, arguments), this;
697
+ else
698
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
699
+ }
700
+ function ReadStream$open() {
701
+ var that = this;
702
+ open(that.path, that.flags, that.mode, function(err, fd) {
703
+ if (err) {
704
+ if (that.autoClose)
705
+ that.destroy();
706
+ that.emit("error", err);
707
+ } else {
708
+ that.fd = fd;
709
+ that.emit("open", fd);
710
+ that.read();
711
+ }
712
+ });
713
+ }
714
+ function WriteStream(path, options) {
715
+ if (this instanceof WriteStream)
716
+ return fs$WriteStream.apply(this, arguments), this;
717
+ else
718
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
719
+ }
720
+ function WriteStream$open() {
721
+ var that = this;
722
+ open(that.path, that.flags, that.mode, function(err, fd) {
723
+ if (err) {
724
+ that.destroy();
725
+ that.emit("error", err);
726
+ } else {
727
+ that.fd = fd;
728
+ that.emit("open", fd);
729
+ }
730
+ });
731
+ }
732
+ function createReadStream(path, options) {
733
+ return new fs2.ReadStream(path, options);
734
+ }
735
+ function createWriteStream(path, options) {
736
+ return new fs2.WriteStream(path, options);
737
+ }
738
+ var fs$open = fs2.open;
739
+ fs2.open = open;
740
+ function open(path, flags, mode, cb) {
741
+ if (typeof mode === "function")
742
+ cb = mode, mode = null;
743
+ return go$open(path, flags, mode, cb);
744
+ function go$open(path2, flags2, mode2, cb2, startTime) {
745
+ return fs$open(path2, flags2, mode2, function(err, fd) {
746
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
747
+ enqueue([go$open, [path2, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
748
+ else {
749
+ if (typeof cb2 === "function")
750
+ cb2.apply(this, arguments);
751
+ }
752
+ });
753
+ }
754
+ }
755
+ return fs2;
756
+ }
757
+ function enqueue(elem) {
758
+ debug("ENQUEUE", elem[0].name, elem[1]);
759
+ fs[gracefulQueue].push(elem);
760
+ retry();
761
+ }
762
+ var retryTimer;
763
+ function resetQueue() {
764
+ var now = Date.now();
765
+ for (var i = 0;i < fs[gracefulQueue].length; ++i) {
766
+ if (fs[gracefulQueue][i].length > 2) {
767
+ fs[gracefulQueue][i][3] = now;
768
+ fs[gracefulQueue][i][4] = now;
769
+ }
770
+ }
771
+ retry();
772
+ }
773
+ function retry() {
774
+ clearTimeout(retryTimer);
775
+ retryTimer = undefined;
776
+ if (fs[gracefulQueue].length === 0)
777
+ return;
778
+ var elem = fs[gracefulQueue].shift();
779
+ var fn = elem[0];
780
+ var args = elem[1];
781
+ var err = elem[2];
782
+ var startTime = elem[3];
783
+ var lastTime = elem[4];
784
+ if (startTime === undefined) {
785
+ debug("RETRY", fn.name, args);
786
+ fn.apply(null, args);
787
+ } else if (Date.now() - startTime >= 60000) {
788
+ debug("TIMEOUT", fn.name, args);
789
+ var cb = args.pop();
790
+ if (typeof cb === "function")
791
+ cb.call(null, err);
792
+ } else {
793
+ var sinceAttempt = Date.now() - lastTime;
794
+ var sinceStart = Math.max(lastTime - startTime, 1);
795
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
796
+ if (sinceAttempt >= desiredDelay) {
797
+ debug("RETRY", fn.name, args);
798
+ fn.apply(null, args.concat([startTime]));
799
+ } else {
800
+ fs[gracefulQueue].push(elem);
801
+ }
802
+ }
803
+ if (retryTimer === undefined) {
804
+ retryTimer = setTimeout(retry, 0);
805
+ }
806
+ }
807
+ });
808
+
809
+ // ../../node_modules/.bun/retry@0.12.0/node_modules/retry/lib/retry_operation.js
810
+ var require_retry_operation = __commonJS((exports, module) => {
811
+ function RetryOperation(timeouts, options) {
812
+ if (typeof options === "boolean") {
813
+ options = { forever: options };
814
+ }
815
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
816
+ this._timeouts = timeouts;
817
+ this._options = options || {};
818
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
819
+ this._fn = null;
820
+ this._errors = [];
821
+ this._attempts = 1;
822
+ this._operationTimeout = null;
823
+ this._operationTimeoutCb = null;
824
+ this._timeout = null;
825
+ this._operationStart = null;
826
+ if (this._options.forever) {
827
+ this._cachedTimeouts = this._timeouts.slice(0);
828
+ }
829
+ }
830
+ module.exports = RetryOperation;
831
+ RetryOperation.prototype.reset = function() {
832
+ this._attempts = 1;
833
+ this._timeouts = this._originalTimeouts;
834
+ };
835
+ RetryOperation.prototype.stop = function() {
836
+ if (this._timeout) {
837
+ clearTimeout(this._timeout);
838
+ }
839
+ this._timeouts = [];
840
+ this._cachedTimeouts = null;
841
+ };
842
+ RetryOperation.prototype.retry = function(err) {
843
+ if (this._timeout) {
844
+ clearTimeout(this._timeout);
845
+ }
846
+ if (!err) {
847
+ return false;
848
+ }
849
+ var currentTime = new Date().getTime();
850
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
851
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
852
+ return false;
853
+ }
854
+ this._errors.push(err);
855
+ var timeout = this._timeouts.shift();
856
+ if (timeout === undefined) {
857
+ if (this._cachedTimeouts) {
858
+ this._errors.splice(this._errors.length - 1, this._errors.length);
859
+ this._timeouts = this._cachedTimeouts.slice(0);
860
+ timeout = this._timeouts.shift();
861
+ } else {
862
+ return false;
863
+ }
864
+ }
865
+ var self = this;
866
+ var timer = setTimeout(function() {
867
+ self._attempts++;
868
+ if (self._operationTimeoutCb) {
869
+ self._timeout = setTimeout(function() {
870
+ self._operationTimeoutCb(self._attempts);
871
+ }, self._operationTimeout);
872
+ if (self._options.unref) {
873
+ self._timeout.unref();
874
+ }
875
+ }
876
+ self._fn(self._attempts);
877
+ }, timeout);
878
+ if (this._options.unref) {
879
+ timer.unref();
880
+ }
881
+ return true;
882
+ };
883
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
884
+ this._fn = fn;
885
+ if (timeoutOps) {
886
+ if (timeoutOps.timeout) {
887
+ this._operationTimeout = timeoutOps.timeout;
888
+ }
889
+ if (timeoutOps.cb) {
890
+ this._operationTimeoutCb = timeoutOps.cb;
891
+ }
892
+ }
893
+ var self = this;
894
+ if (this._operationTimeoutCb) {
895
+ this._timeout = setTimeout(function() {
896
+ self._operationTimeoutCb();
897
+ }, self._operationTimeout);
898
+ }
899
+ this._operationStart = new Date().getTime();
900
+ this._fn(this._attempts);
901
+ };
902
+ RetryOperation.prototype.try = function(fn) {
903
+ console.log("Using RetryOperation.try() is deprecated");
904
+ this.attempt(fn);
905
+ };
906
+ RetryOperation.prototype.start = function(fn) {
907
+ console.log("Using RetryOperation.start() is deprecated");
908
+ this.attempt(fn);
909
+ };
910
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
911
+ RetryOperation.prototype.errors = function() {
912
+ return this._errors;
913
+ };
914
+ RetryOperation.prototype.attempts = function() {
915
+ return this._attempts;
916
+ };
917
+ RetryOperation.prototype.mainError = function() {
918
+ if (this._errors.length === 0) {
919
+ return null;
920
+ }
921
+ var counts = {};
922
+ var mainError = null;
923
+ var mainErrorCount = 0;
924
+ for (var i = 0;i < this._errors.length; i++) {
925
+ var error = this._errors[i];
926
+ var message = error.message;
927
+ var count = (counts[message] || 0) + 1;
928
+ counts[message] = count;
929
+ if (count >= mainErrorCount) {
930
+ mainError = error;
931
+ mainErrorCount = count;
932
+ }
933
+ }
934
+ return mainError;
935
+ };
936
+ });
937
+
938
+ // ../../node_modules/.bun/retry@0.12.0/node_modules/retry/lib/retry.js
939
+ var require_retry = __commonJS((exports) => {
940
+ var RetryOperation = require_retry_operation();
941
+ exports.operation = function(options) {
942
+ var timeouts = exports.timeouts(options);
943
+ return new RetryOperation(timeouts, {
944
+ forever: options && options.forever,
945
+ unref: options && options.unref,
946
+ maxRetryTime: options && options.maxRetryTime
947
+ });
948
+ };
949
+ exports.timeouts = function(options) {
950
+ if (options instanceof Array) {
951
+ return [].concat(options);
952
+ }
953
+ var opts = {
954
+ retries: 10,
955
+ factor: 2,
956
+ minTimeout: 1 * 1000,
957
+ maxTimeout: Infinity,
958
+ randomize: false
959
+ };
960
+ for (var key in options) {
961
+ opts[key] = options[key];
962
+ }
963
+ if (opts.minTimeout > opts.maxTimeout) {
964
+ throw new Error("minTimeout is greater than maxTimeout");
965
+ }
966
+ var timeouts = [];
967
+ for (var i = 0;i < opts.retries; i++) {
968
+ timeouts.push(this.createTimeout(i, opts));
969
+ }
970
+ if (options && options.forever && !timeouts.length) {
971
+ timeouts.push(this.createTimeout(i, opts));
972
+ }
973
+ timeouts.sort(function(a, b) {
974
+ return a - b;
975
+ });
976
+ return timeouts;
977
+ };
978
+ exports.createTimeout = function(attempt, opts) {
979
+ var random = opts.randomize ? Math.random() + 1 : 1;
980
+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
981
+ timeout = Math.min(timeout, opts.maxTimeout);
982
+ return timeout;
983
+ };
984
+ exports.wrap = function(obj, options, methods) {
985
+ if (options instanceof Array) {
986
+ methods = options;
987
+ options = null;
988
+ }
989
+ if (!methods) {
990
+ methods = [];
991
+ for (var key in obj) {
992
+ if (typeof obj[key] === "function") {
993
+ methods.push(key);
994
+ }
995
+ }
996
+ }
997
+ for (var i = 0;i < methods.length; i++) {
998
+ var method = methods[i];
999
+ var original = obj[method];
1000
+ obj[method] = function retryWrapper(original2) {
1001
+ var op = exports.operation(options);
1002
+ var args = Array.prototype.slice.call(arguments, 1);
1003
+ var callback = args.pop();
1004
+ args.push(function(err) {
1005
+ if (op.retry(err)) {
1006
+ return;
1007
+ }
1008
+ if (err) {
1009
+ arguments[0] = op.mainError();
1010
+ }
1011
+ callback.apply(this, arguments);
1012
+ });
1013
+ op.attempt(function() {
1014
+ original2.apply(obj, args);
1015
+ });
1016
+ }.bind(obj, original);
1017
+ obj[method].options = options;
1018
+ }
1019
+ };
1020
+ });
1021
+
1022
+ // ../../node_modules/.bun/signal-exit@3.0.7/node_modules/signal-exit/signals.js
1023
+ var require_signals = __commonJS((exports, module) => {
1024
+ module.exports = [
1025
+ "SIGABRT",
1026
+ "SIGALRM",
1027
+ "SIGHUP",
1028
+ "SIGINT",
1029
+ "SIGTERM"
1030
+ ];
1031
+ if (process.platform !== "win32") {
1032
+ module.exports.push("SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT");
1033
+ }
1034
+ if (process.platform === "linux") {
1035
+ module.exports.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT", "SIGUNUSED");
1036
+ }
1037
+ });
1038
+
1039
+ // ../../node_modules/.bun/signal-exit@3.0.7/node_modules/signal-exit/index.js
1040
+ var require_signal_exit = __commonJS((exports, module) => {
1041
+ var process2 = global.process;
1042
+ var processOk = function(process3) {
1043
+ 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";
1044
+ };
1045
+ if (!processOk(process2)) {
1046
+ module.exports = function() {
1047
+ return function() {};
1048
+ };
1049
+ } else {
1050
+ assert = __require("assert");
1051
+ signals = require_signals();
1052
+ isWin = /^win/i.test(process2.platform);
1053
+ EE = __require("events");
1054
+ if (typeof EE !== "function") {
1055
+ EE = EE.EventEmitter;
1056
+ }
1057
+ if (process2.__signal_exit_emitter__) {
1058
+ emitter = process2.__signal_exit_emitter__;
1059
+ } else {
1060
+ emitter = process2.__signal_exit_emitter__ = new EE;
1061
+ emitter.count = 0;
1062
+ emitter.emitted = {};
1063
+ }
1064
+ if (!emitter.infinite) {
1065
+ emitter.setMaxListeners(Infinity);
1066
+ emitter.infinite = true;
1067
+ }
1068
+ module.exports = function(cb, opts) {
1069
+ if (!processOk(global.process)) {
1070
+ return function() {};
1071
+ }
1072
+ assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
1073
+ if (loaded === false) {
1074
+ load();
1075
+ }
1076
+ var ev = "exit";
1077
+ if (opts && opts.alwaysLast) {
1078
+ ev = "afterexit";
1079
+ }
1080
+ var remove = function() {
1081
+ emitter.removeListener(ev, cb);
1082
+ if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
1083
+ unload();
1084
+ }
1085
+ };
1086
+ emitter.on(ev, cb);
1087
+ return remove;
1088
+ };
1089
+ unload = function unload() {
1090
+ if (!loaded || !processOk(global.process)) {
1091
+ return;
1092
+ }
1093
+ loaded = false;
1094
+ signals.forEach(function(sig) {
1095
+ try {
1096
+ process2.removeListener(sig, sigListeners[sig]);
1097
+ } catch (er) {}
1098
+ });
1099
+ process2.emit = originalProcessEmit;
1100
+ process2.reallyExit = originalProcessReallyExit;
1101
+ emitter.count -= 1;
1102
+ };
1103
+ module.exports.unload = unload;
1104
+ emit = function emit(event, code, signal) {
1105
+ if (emitter.emitted[event]) {
1106
+ return;
1107
+ }
1108
+ emitter.emitted[event] = true;
1109
+ emitter.emit(event, code, signal);
1110
+ };
1111
+ sigListeners = {};
1112
+ signals.forEach(function(sig) {
1113
+ sigListeners[sig] = function listener() {
1114
+ if (!processOk(global.process)) {
1115
+ return;
1116
+ }
1117
+ var listeners = process2.listeners(sig);
1118
+ if (listeners.length === emitter.count) {
1119
+ unload();
1120
+ emit("exit", null, sig);
1121
+ emit("afterexit", null, sig);
1122
+ if (isWin && sig === "SIGHUP") {
1123
+ sig = "SIGINT";
1124
+ }
1125
+ process2.kill(process2.pid, sig);
1126
+ }
1127
+ };
1128
+ });
1129
+ module.exports.signals = function() {
1130
+ return signals;
1131
+ };
1132
+ loaded = false;
1133
+ load = function load() {
1134
+ if (loaded || !processOk(global.process)) {
1135
+ return;
1136
+ }
1137
+ loaded = true;
1138
+ emitter.count += 1;
1139
+ signals = signals.filter(function(sig) {
1140
+ try {
1141
+ process2.on(sig, sigListeners[sig]);
1142
+ return true;
1143
+ } catch (er) {
1144
+ return false;
1145
+ }
1146
+ });
1147
+ process2.emit = processEmit;
1148
+ process2.reallyExit = processReallyExit;
1149
+ };
1150
+ module.exports.load = load;
1151
+ originalProcessReallyExit = process2.reallyExit;
1152
+ processReallyExit = function processReallyExit(code) {
1153
+ if (!processOk(global.process)) {
1154
+ return;
1155
+ }
1156
+ process2.exitCode = code || 0;
1157
+ emit("exit", process2.exitCode, null);
1158
+ emit("afterexit", process2.exitCode, null);
1159
+ originalProcessReallyExit.call(process2, process2.exitCode);
1160
+ };
1161
+ originalProcessEmit = process2.emit;
1162
+ processEmit = function processEmit(ev, arg) {
1163
+ if (ev === "exit" && processOk(global.process)) {
1164
+ if (arg !== undefined) {
1165
+ process2.exitCode = arg;
1166
+ }
1167
+ var ret = originalProcessEmit.apply(this, arguments);
1168
+ emit("exit", process2.exitCode, null);
1169
+ emit("afterexit", process2.exitCode, null);
1170
+ return ret;
1171
+ } else {
1172
+ return originalProcessEmit.apply(this, arguments);
1173
+ }
1174
+ };
1175
+ }
1176
+ var assert;
1177
+ var signals;
1178
+ var isWin;
1179
+ var EE;
1180
+ var emitter;
1181
+ var unload;
1182
+ var emit;
1183
+ var sigListeners;
1184
+ var loaded;
1185
+ var load;
1186
+ var originalProcessReallyExit;
1187
+ var processReallyExit;
1188
+ var originalProcessEmit;
1189
+ var processEmit;
1190
+ });
1191
+
1192
+ // ../../node_modules/.bun/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/mtime-precision.js
1193
+ var require_mtime_precision = __commonJS((exports, module) => {
1194
+ var cacheSymbol = Symbol();
1195
+ function probe(file, fs, callback) {
1196
+ const cachedPrecision = fs[cacheSymbol];
1197
+ if (cachedPrecision) {
1198
+ return fs.stat(file, (err, stat) => {
1199
+ if (err) {
1200
+ return callback(err);
1201
+ }
1202
+ callback(null, stat.mtime, cachedPrecision);
1203
+ });
1204
+ }
1205
+ const mtime = new Date(Math.ceil(Date.now() / 1000) * 1000 + 5);
1206
+ fs.utimes(file, mtime, mtime, (err) => {
1207
+ if (err) {
1208
+ return callback(err);
1209
+ }
1210
+ fs.stat(file, (err2, stat) => {
1211
+ if (err2) {
1212
+ return callback(err2);
1213
+ }
1214
+ const precision = stat.mtime.getTime() % 1000 === 0 ? "s" : "ms";
1215
+ Object.defineProperty(fs, cacheSymbol, { value: precision });
1216
+ callback(null, stat.mtime, precision);
1217
+ });
1218
+ });
1219
+ }
1220
+ function getMtime(precision) {
1221
+ let now = Date.now();
1222
+ if (precision === "s") {
1223
+ now = Math.ceil(now / 1000) * 1000;
1224
+ }
1225
+ return new Date(now);
1226
+ }
1227
+ exports.probe = probe;
1228
+ exports.getMtime = getMtime;
1229
+ });
1230
+
1231
+ // ../../node_modules/.bun/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/lockfile.js
1232
+ var require_lockfile = __commonJS((exports, module) => {
1233
+ var path = __require("path");
1234
+ var fs = require_graceful_fs();
1235
+ var retry = require_retry();
1236
+ var onExit = require_signal_exit();
1237
+ var mtimePrecision = require_mtime_precision();
1238
+ var locks = {};
1239
+ function getLockFile(file, options) {
1240
+ return options.lockfilePath || `${file}.lock`;
1241
+ }
1242
+ function resolveCanonicalPath(file, options, callback) {
1243
+ if (!options.realpath) {
1244
+ return callback(null, path.resolve(file));
1245
+ }
1246
+ options.fs.realpath(file, callback);
1247
+ }
1248
+ function acquireLock(file, options, callback) {
1249
+ const lockfilePath = getLockFile(file, options);
1250
+ options.fs.mkdir(lockfilePath, (err) => {
1251
+ if (!err) {
1252
+ return mtimePrecision.probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision2) => {
1253
+ if (err2) {
1254
+ options.fs.rmdir(lockfilePath, () => {});
1255
+ return callback(err2);
1256
+ }
1257
+ callback(null, mtime, mtimePrecision2);
1258
+ });
1259
+ }
1260
+ if (err.code !== "EEXIST") {
1261
+ return callback(err);
1262
+ }
1263
+ if (options.stale <= 0) {
1264
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1265
+ }
1266
+ options.fs.stat(lockfilePath, (err2, stat) => {
1267
+ if (err2) {
1268
+ if (err2.code === "ENOENT") {
1269
+ return acquireLock(file, { ...options, stale: 0 }, callback);
1270
+ }
1271
+ return callback(err2);
1272
+ }
1273
+ if (!isLockStale(stat, options)) {
1274
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1275
+ }
1276
+ removeLock(file, options, (err3) => {
1277
+ if (err3) {
1278
+ return callback(err3);
1279
+ }
1280
+ acquireLock(file, { ...options, stale: 0 }, callback);
1281
+ });
1282
+ });
1283
+ });
1284
+ }
1285
+ function isLockStale(stat, options) {
1286
+ return stat.mtime.getTime() < Date.now() - options.stale;
1287
+ }
1288
+ function removeLock(file, options, callback) {
1289
+ options.fs.rmdir(getLockFile(file, options), (err) => {
1290
+ if (err && err.code !== "ENOENT") {
1291
+ return callback(err);
1292
+ }
1293
+ callback();
1294
+ });
1295
+ }
1296
+ function updateLock(file, options) {
1297
+ const lock2 = locks[file];
1298
+ if (lock2.updateTimeout) {
1299
+ return;
1300
+ }
1301
+ lock2.updateDelay = lock2.updateDelay || options.update;
1302
+ lock2.updateTimeout = setTimeout(() => {
1303
+ lock2.updateTimeout = null;
1304
+ options.fs.stat(lock2.lockfilePath, (err, stat) => {
1305
+ const isOverThreshold = lock2.lastUpdate + options.stale < Date.now();
1306
+ if (err) {
1307
+ if (err.code === "ENOENT" || isOverThreshold) {
1308
+ return setLockAsCompromised(file, lock2, Object.assign(err, { code: "ECOMPROMISED" }));
1309
+ }
1310
+ lock2.updateDelay = 1000;
1311
+ return updateLock(file, options);
1312
+ }
1313
+ const isMtimeOurs = lock2.mtime.getTime() === stat.mtime.getTime();
1314
+ if (!isMtimeOurs) {
1315
+ return setLockAsCompromised(file, lock2, Object.assign(new Error("Unable to update lock within the stale threshold"), { code: "ECOMPROMISED" }));
1316
+ }
1317
+ const mtime = mtimePrecision.getMtime(lock2.mtimePrecision);
1318
+ options.fs.utimes(lock2.lockfilePath, mtime, mtime, (err2) => {
1319
+ const isOverThreshold2 = lock2.lastUpdate + options.stale < Date.now();
1320
+ if (lock2.released) {
1321
+ return;
1322
+ }
1323
+ if (err2) {
1324
+ if (err2.code === "ENOENT" || isOverThreshold2) {
1325
+ return setLockAsCompromised(file, lock2, Object.assign(err2, { code: "ECOMPROMISED" }));
1326
+ }
1327
+ lock2.updateDelay = 1000;
1328
+ return updateLock(file, options);
1329
+ }
1330
+ lock2.mtime = mtime;
1331
+ lock2.lastUpdate = Date.now();
1332
+ lock2.updateDelay = null;
1333
+ updateLock(file, options);
1334
+ });
1335
+ });
1336
+ }, lock2.updateDelay);
1337
+ if (lock2.updateTimeout.unref) {
1338
+ lock2.updateTimeout.unref();
1339
+ }
1340
+ }
1341
+ function setLockAsCompromised(file, lock2, err) {
1342
+ lock2.released = true;
1343
+ if (lock2.updateTimeout) {
1344
+ clearTimeout(lock2.updateTimeout);
1345
+ }
1346
+ if (locks[file] === lock2) {
1347
+ delete locks[file];
1348
+ }
1349
+ lock2.options.onCompromised(err);
1350
+ }
1351
+ function lock(file, options, callback) {
1352
+ options = {
1353
+ stale: 1e4,
1354
+ update: null,
1355
+ realpath: true,
1356
+ retries: 0,
1357
+ fs,
1358
+ onCompromised: (err) => {
1359
+ throw err;
1360
+ },
1361
+ ...options
1362
+ };
1363
+ options.retries = options.retries || 0;
1364
+ options.retries = typeof options.retries === "number" ? { retries: options.retries } : options.retries;
1365
+ options.stale = Math.max(options.stale || 0, 2000);
1366
+ options.update = options.update == null ? options.stale / 2 : options.update || 0;
1367
+ options.update = Math.max(Math.min(options.update, options.stale / 2), 1000);
1368
+ resolveCanonicalPath(file, options, (err, file2) => {
1369
+ if (err) {
1370
+ return callback(err);
1371
+ }
1372
+ const operation = retry.operation(options.retries);
1373
+ operation.attempt(() => {
1374
+ acquireLock(file2, options, (err2, mtime, mtimePrecision2) => {
1375
+ if (operation.retry(err2)) {
1376
+ return;
1377
+ }
1378
+ if (err2) {
1379
+ return callback(operation.mainError());
1380
+ }
1381
+ const lock2 = locks[file2] = {
1382
+ lockfilePath: getLockFile(file2, options),
1383
+ mtime,
1384
+ mtimePrecision: mtimePrecision2,
1385
+ options,
1386
+ lastUpdate: Date.now()
1387
+ };
1388
+ updateLock(file2, options);
1389
+ callback(null, (releasedCallback) => {
1390
+ if (lock2.released) {
1391
+ return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
1392
+ }
1393
+ unlock(file2, { ...options, realpath: false }, releasedCallback);
1394
+ });
1395
+ });
1396
+ });
1397
+ });
1398
+ }
1399
+ function unlock(file, options, callback) {
1400
+ options = {
1401
+ fs,
1402
+ realpath: true,
1403
+ ...options
1404
+ };
1405
+ resolveCanonicalPath(file, options, (err, file2) => {
1406
+ if (err) {
1407
+ return callback(err);
1408
+ }
1409
+ const lock2 = locks[file2];
1410
+ if (!lock2) {
1411
+ return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
1412
+ }
1413
+ lock2.updateTimeout && clearTimeout(lock2.updateTimeout);
1414
+ lock2.released = true;
1415
+ delete locks[file2];
1416
+ removeLock(file2, options, callback);
1417
+ });
1418
+ }
1419
+ function check(file, options, callback) {
1420
+ options = {
1421
+ stale: 1e4,
1422
+ realpath: true,
1423
+ fs,
1424
+ ...options
1425
+ };
1426
+ options.stale = Math.max(options.stale || 0, 2000);
1427
+ resolveCanonicalPath(file, options, (err, file2) => {
1428
+ if (err) {
1429
+ return callback(err);
1430
+ }
1431
+ options.fs.stat(getLockFile(file2, options), (err2, stat) => {
1432
+ if (err2) {
1433
+ return err2.code === "ENOENT" ? callback(null, false) : callback(err2);
1434
+ }
1435
+ return callback(null, !isLockStale(stat, options));
1436
+ });
1437
+ });
1438
+ }
1439
+ function getLocks() {
1440
+ return locks;
1441
+ }
1442
+ onExit(() => {
1443
+ for (const file in locks) {
1444
+ const options = locks[file].options;
1445
+ try {
1446
+ options.fs.rmdirSync(getLockFile(file, options));
1447
+ } catch (e) {}
1448
+ }
1449
+ });
1450
+ exports.lock = lock;
1451
+ exports.unlock = unlock;
1452
+ exports.check = check;
1453
+ exports.getLocks = getLocks;
1454
+ });
1455
+
1456
+ // ../../node_modules/.bun/proper-lockfile@4.1.2/node_modules/proper-lockfile/lib/adapter.js
1457
+ var require_adapter = __commonJS((exports, module) => {
1458
+ var fs = require_graceful_fs();
1459
+ function createSyncFs(fs2) {
1460
+ const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
1461
+ const newFs = { ...fs2 };
1462
+ methods.forEach((method) => {
1463
+ newFs[method] = (...args) => {
1464
+ const callback = args.pop();
1465
+ let ret;
1466
+ try {
1467
+ ret = fs2[`${method}Sync`](...args);
1468
+ } catch (err) {
1469
+ return callback(err);
1470
+ }
1471
+ callback(null, ret);
1472
+ };
1473
+ });
1474
+ return newFs;
1475
+ }
1476
+ function toPromise(method) {
1477
+ return (...args) => new Promise((resolve, reject) => {
1478
+ args.push((err, result) => {
1479
+ if (err) {
1480
+ reject(err);
1481
+ } else {
1482
+ resolve(result);
1483
+ }
1484
+ });
1485
+ method(...args);
1486
+ });
1487
+ }
1488
+ function toSync(method) {
1489
+ return (...args) => {
1490
+ let err;
1491
+ let result;
1492
+ args.push((_err, _result) => {
1493
+ err = _err;
1494
+ result = _result;
1495
+ });
1496
+ method(...args);
1497
+ if (err) {
1498
+ throw err;
1499
+ }
1500
+ return result;
1501
+ };
1502
+ }
1503
+ function toSyncOptions(options) {
1504
+ options = { ...options };
1505
+ options.fs = createSyncFs(options.fs || fs);
1506
+ if (typeof options.retries === "number" && options.retries > 0 || options.retries && typeof options.retries.retries === "number" && options.retries.retries > 0) {
1507
+ throw Object.assign(new Error("Cannot use retries with the sync api"), { code: "ESYNC" });
1508
+ }
1509
+ return options;
1510
+ }
1511
+ module.exports = {
1512
+ toPromise,
1513
+ toSync,
1514
+ toSyncOptions
1515
+ };
1516
+ });
1517
+
1518
+ // ../../node_modules/.bun/proper-lockfile@4.1.2/node_modules/proper-lockfile/index.js
1519
+ var require_proper_lockfile = __commonJS((exports, module) => {
1520
+ var lockfile = require_lockfile();
1521
+ var { toPromise, toSync, toSyncOptions } = require_adapter();
1522
+ async function lock(file, options) {
1523
+ const release = await toPromise(lockfile.lock)(file, options);
1524
+ return toPromise(release);
1525
+ }
1526
+ function lockSync(file, options) {
1527
+ const release = toSync(lockfile.lock)(file, toSyncOptions(options));
1528
+ return toSync(release);
1529
+ }
1530
+ function unlock(file, options) {
1531
+ return toPromise(lockfile.unlock)(file, options);
1532
+ }
1533
+ function unlockSync(file, options) {
1534
+ return toSync(lockfile.unlock)(file, toSyncOptions(options));
1535
+ }
1536
+ function check(file, options) {
1537
+ return toPromise(lockfile.check)(file, options);
1538
+ }
1539
+ function checkSync(file, options) {
1540
+ return toSync(lockfile.check)(file, toSyncOptions(options));
1541
+ }
1542
+ module.exports = lock;
1543
+ module.exports.lock = lock;
1544
+ module.exports.unlock = unlock;
1545
+ module.exports.lockSync = lockSync;
1546
+ module.exports.unlockSync = unlockSync;
1547
+ module.exports.check = check;
1548
+ module.exports.checkSync = checkSync;
1549
+ });
1550
+
1551
+ // src/streams/leader-election.ts
1552
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
1553
+ import { join, dirname } from "node:path";
1554
+ function getLockFilePath(dbPath) {
1555
+ const dir = dirname(dbPath);
1556
+ return join(dir, LOCK_FILE);
1557
+ }
1558
+ function ensureLockFile(lockPath) {
1559
+ const dir = dirname(lockPath);
1560
+ if (!existsSync(dir)) {
1561
+ mkdirSync(dir, { recursive: true });
1562
+ }
1563
+ if (!existsSync(lockPath)) {
1564
+ writeFileSync(lockPath, `${process.pid}
1565
+ `);
1566
+ }
1567
+ }
1568
+ async function acquireInitLock(dbPath) {
1569
+ const lockPath = getLockFilePath(dbPath);
1570
+ ensureLockFile(lockPath);
1571
+ const startTime = Date.now();
1572
+ while (true) {
1573
+ try {
1574
+ const release = await import_proper_lockfile.lock(lockPath, {
1575
+ stale: STALE_THRESHOLD_MS,
1576
+ retries: 0
1577
+ });
1578
+ return async () => {
1579
+ try {
1580
+ await release();
1581
+ } catch (err) {
1582
+ console.warn(`[swarm-mail] Warning: Failed to release init lock: ${err.message}`);
1583
+ }
1584
+ };
1585
+ } catch (err) {
1586
+ const error = err;
1587
+ if (Date.now() - startTime > LOCK_TIMEOUT_MS) {
1588
+ throw new Error(`Failed to acquire database init lock after ${LOCK_TIMEOUT_MS}ms. ` + `Another process may be stuck. Lock file: ${lockPath}. ` + `Original error: ${error.message}`);
1589
+ }
1590
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_INTERVAL_MS));
1591
+ }
1592
+ }
1593
+ }
1594
+ var import_proper_lockfile, LOCK_FILE = "streams.lock", LOCK_TIMEOUT_MS = 30000, LOCK_RETRY_INTERVAL_MS = 100, STALE_THRESHOLD_MS = 60000;
1595
+ var init_leader_election = __esm(() => {
1596
+ import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
1597
+ });
12
1598
 
13
1599
  // ../../node_modules/.bun/@isaacs+balanced-match@4.0.1/node_modules/@isaacs/balanced-match/dist/esm/index.js
14
1600
  var balanced = (a, b, str) => {
@@ -13371,7 +14957,7 @@ function _function(params) {
13371
14957
  output: params?.output ?? unknown()
13372
14958
  });
13373
14959
  }
13374
- function check(fn) {
14960
+ function check2(fn) {
13375
14961
  const ch = new $ZodCheck({
13376
14962
  check: "custom"
13377
14963
  });
@@ -13453,7 +15039,7 @@ var init_schemas2 = __esm(() => {
13453
15039
  inst.safeDecode = (data, params) => safeDecode2(inst, data, params);
13454
15040
  inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params);
13455
15041
  inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params);
13456
- inst.refine = (check, params) => inst.check(refine(check, params));
15042
+ inst.refine = (check2, params) => inst.check(refine(check2, params));
13457
15043
  inst.superRefine = (refinement) => inst.check(superRefine(refinement));
13458
15044
  inst.overwrite = (fn) => inst.check(_overwrite(fn));
13459
15045
  inst.optional = () => optional(inst);
@@ -14161,7 +15747,7 @@ __export(exports_external, {
14161
15747
  clone: () => clone,
14162
15748
  cidrv6: () => cidrv62,
14163
15749
  cidrv4: () => cidrv42,
14164
- check: () => check,
15750
+ check: () => check2,
14165
15751
  catch: () => _catch2,
14166
15752
  boolean: () => boolean2,
14167
15753
  bigint: () => bigint2,
@@ -15682,8 +17268,8 @@ __export(exports_streams, {
15682
17268
  AgentActiveEventSchema: () => AgentActiveEventSchema
15683
17269
  });
15684
17270
  import { PGlite } from "@electric-sql/pglite";
15685
- import { existsSync, mkdirSync, appendFileSync } from "node:fs";
15686
- import { join } from "node:path";
17271
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, appendFileSync } from "node:fs";
17272
+ import { join as join2 } from "node:path";
15687
17273
  import { homedir } from "node:os";
15688
17274
  async function withTimeout(promise2, ms, operation) {
15689
17275
  const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error(`${operation} timed out after ${ms}ms`)), ms));
@@ -15711,19 +17297,19 @@ function debugLog(message, data) {
15711
17297
  }
15712
17298
  function getDatabasePath(projectPath) {
15713
17299
  if (projectPath) {
15714
- const localDir = join(projectPath, ".opencode");
15715
- if (existsSync(localDir) || existsSync(projectPath)) {
15716
- if (!existsSync(localDir)) {
15717
- mkdirSync(localDir, { recursive: true });
17300
+ const localDir = join2(projectPath, ".opencode");
17301
+ if (existsSync2(localDir) || existsSync2(projectPath)) {
17302
+ if (!existsSync2(localDir)) {
17303
+ mkdirSync2(localDir, { recursive: true });
15718
17304
  }
15719
- return join(localDir, "streams");
17305
+ return join2(localDir, "streams");
15720
17306
  }
15721
17307
  }
15722
- const globalDir = join(homedir(), ".opencode");
15723
- if (!existsSync(globalDir)) {
15724
- mkdirSync(globalDir, { recursive: true });
17308
+ const globalDir = join2(homedir(), ".opencode");
17309
+ if (!existsSync2(globalDir)) {
17310
+ mkdirSync2(globalDir, { recursive: true });
15725
17311
  }
15726
- return join(globalDir, "streams");
17312
+ return join2(globalDir, "streams");
15727
17313
  }
15728
17314
  function evictLRU() {
15729
17315
  if (instances.size < MAX_CACHE_SIZE) {
@@ -15777,7 +17363,11 @@ async function createDatabaseInstance(dbPath) {
15777
17363
  evictLRU();
15778
17364
  debugLog("createDatabaseInstance called", { dbPath, cwd: process.cwd() });
15779
17365
  let db;
17366
+ let releaseLock = null;
15780
17367
  try {
17368
+ debugLog("Acquiring init lock", { dbPath });
17369
+ releaseLock = await acquireInitLock(dbPath);
17370
+ debugLog("Init lock acquired");
15781
17371
  debugLog("Creating PGlite instance", { dbPath });
15782
17372
  db = new PGlite(dbPath);
15783
17373
  debugLog("PGlite instance created successfully");
@@ -15808,6 +17398,12 @@ async function createDatabaseInstance(dbPath) {
15808
17398
  console.error(`[swarm-mail] CRITICAL: In-memory fallback failed:`, fallbackErr.message);
15809
17399
  throw new Error(`Database initialization failed: ${err.message}. Fallback also failed: ${fallbackErr.message}`);
15810
17400
  }
17401
+ } finally {
17402
+ if (releaseLock) {
17403
+ debugLog("Releasing init lock");
17404
+ await releaseLock();
17405
+ debugLog("Init lock released");
17406
+ }
15811
17407
  }
15812
17408
  }
15813
17409
  async function closeDatabase(projectPath) {
@@ -15981,6 +17577,7 @@ function handleExit() {
15981
17577
  }
15982
17578
  var SLOW_QUERY_THRESHOLD_MS = 100, DEBUG_LOG_PATH, instances, pendingInstances, schemaInitialized, degradedInstances, lastAccess, MAX_CACHE_SIZE = 10;
15983
17579
  var init_streams = __esm(() => {
17580
+ init_leader_election();
15984
17581
  init_agent_mail();
15985
17582
  init_debug();
15986
17583
  init_events();
@@ -15988,7 +17585,7 @@ var init_streams = __esm(() => {
15988
17585
  init_projections();
15989
17586
  init_store();
15990
17587
  init_swarm_mail();
15991
- DEBUG_LOG_PATH = join(homedir(), ".opencode", "streams-debug.log");
17588
+ DEBUG_LOG_PATH = join2(homedir(), ".opencode", "streams-debug.log");
15992
17589
  instances = new Map;
15993
17590
  pendingInstances = new Map;
15994
17591
  schemaInitialized = new Map;
@@ -16891,9 +18488,227 @@ function createSwarmMailAdapter(db, projectKey) {
16891
18488
  }
16892
18489
  // src/pglite.ts
16893
18490
  import { PGlite as PGlite2 } from "@electric-sql/pglite";
16894
- import { existsSync as existsSync2, mkdirSync as mkdirSync2 } from "node:fs";
16895
- import { join as join2 } from "node:path";
16896
- import { homedir as homedir2 } from "node:os";
18491
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4 } from "node:fs";
18492
+ import { join as join4, basename } from "node:path";
18493
+ import { tmpdir as tmpdir2 } from "node:os";
18494
+ import { createHash } from "node:crypto";
18495
+
18496
+ // src/socket-adapter.ts
18497
+ import postgres from "postgres";
18498
+ function wrapPostgres(sql) {
18499
+ return {
18500
+ query: async (sqlString, params) => {
18501
+ const rows = await sql.unsafe(sqlString, params ?? []);
18502
+ return { rows };
18503
+ },
18504
+ exec: async (sqlString) => {
18505
+ await sql.unsafe(sqlString);
18506
+ },
18507
+ transaction: async (fn) => {
18508
+ const result = await sql.begin(async (transaction) => {
18509
+ const txAdapter = wrapPostgres(transaction);
18510
+ return await fn(txAdapter);
18511
+ });
18512
+ return result;
18513
+ },
18514
+ close: async () => {
18515
+ await sql.end();
18516
+ }
18517
+ };
18518
+ }
18519
+ async function createSocketAdapter(options) {
18520
+ if (!options.path && (!options.host || !options.port)) {
18521
+ throw new Error("Socket adapter requires either 'path' (unix socket) or 'host' + 'port' (TCP)");
18522
+ }
18523
+ if (options.path && (options.host || options.port)) {
18524
+ throw new Error("Socket adapter: cannot specify both 'path' and 'host'/'port'. Choose one connection method.");
18525
+ }
18526
+ try {
18527
+ const sql = postgres({
18528
+ path: options.path,
18529
+ host: options.host,
18530
+ port: options.port,
18531
+ connect_timeout: options.timeout,
18532
+ max: options.max ?? 10,
18533
+ idle_timeout: 0,
18534
+ max_lifetime: null
18535
+ });
18536
+ await sql`SELECT 1 as ping`;
18537
+ return wrapPostgres(sql);
18538
+ } catch (error45) {
18539
+ const connType = options.path ? `unix socket: ${options.path}` : `TCP: ${options.host}:${options.port}`;
18540
+ throw new Error(`Failed to connect to PostgreSQL via ${connType}: ${error45 instanceof Error ? error45.message : String(error45)}`);
18541
+ }
18542
+ }
18543
+
18544
+ // src/daemon.ts
18545
+ import { spawn } from "node:child_process";
18546
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3 } from "node:fs";
18547
+ import { readFile, writeFile, unlink } from "node:fs/promises";
18548
+ import { join as join3 } from "node:path";
18549
+ import { tmpdir } from "node:os";
18550
+ function getPidFilePath(projectPath) {
18551
+ const tmp = tmpdir();
18552
+ if (projectPath) {
18553
+ const dirName = getProjectTempDirName(projectPath);
18554
+ const projectTmpDir = join3(tmp, dirName);
18555
+ if (!existsSync3(projectTmpDir)) {
18556
+ mkdirSync3(projectTmpDir, { recursive: true });
18557
+ }
18558
+ return join3(projectTmpDir, "pglite-server.pid");
18559
+ }
18560
+ const globalTmpDir = join3(tmp, "opencode-global");
18561
+ if (!existsSync3(globalTmpDir)) {
18562
+ mkdirSync3(globalTmpDir, { recursive: true });
18563
+ }
18564
+ return join3(globalTmpDir, "pglite-server.pid");
18565
+ }
18566
+ function isProcessAlive(pid) {
18567
+ try {
18568
+ process.kill(pid, 0);
18569
+ return true;
18570
+ } catch (error45) {
18571
+ if (error45 instanceof Error && "code" in error45 && error45.code === "ESRCH") {
18572
+ return false;
18573
+ }
18574
+ return true;
18575
+ }
18576
+ }
18577
+ async function readPidFile(projectPath) {
18578
+ const pidFilePath = getPidFilePath(projectPath);
18579
+ if (!existsSync3(pidFilePath)) {
18580
+ return null;
18581
+ }
18582
+ try {
18583
+ const content = await readFile(pidFilePath, "utf-8");
18584
+ const pid = Number.parseInt(content.trim(), 10);
18585
+ if (Number.isNaN(pid) || pid <= 0) {
18586
+ return null;
18587
+ }
18588
+ return pid;
18589
+ } catch {
18590
+ return null;
18591
+ }
18592
+ }
18593
+ async function writePidFile(pid, projectPath) {
18594
+ const pidFilePath = getPidFilePath(projectPath);
18595
+ await writeFile(pidFilePath, pid.toString(), "utf-8");
18596
+ }
18597
+ async function deletePidFile(projectPath) {
18598
+ const pidFilePath = getPidFilePath(projectPath);
18599
+ try {
18600
+ await unlink(pidFilePath);
18601
+ } catch {}
18602
+ }
18603
+ async function waitFor(condition, timeoutMs, intervalMs = 100) {
18604
+ const start = Date.now();
18605
+ while (Date.now() - start < timeoutMs) {
18606
+ if (await condition()) {
18607
+ return true;
18608
+ }
18609
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
18610
+ }
18611
+ return false;
18612
+ }
18613
+ async function isDaemonRunning(projectPath) {
18614
+ const pid = await readPidFile(projectPath);
18615
+ if (!pid) {
18616
+ return false;
18617
+ }
18618
+ return isProcessAlive(pid);
18619
+ }
18620
+ async function healthCheck(options) {
18621
+ try {
18622
+ const postgres2 = await import("postgres").then((m) => m.default);
18623
+ const sql = options.path ? postgres2({ path: options.path }) : postgres2({
18624
+ host: options.host || "127.0.0.1",
18625
+ port: options.port || 5433,
18626
+ max: 1
18627
+ });
18628
+ try {
18629
+ await Promise.race([
18630
+ sql`SELECT 1`,
18631
+ new Promise((_, reject) => setTimeout(() => reject(new Error("Health check timeout")), 5000))
18632
+ ]);
18633
+ return true;
18634
+ } finally {
18635
+ await sql.end();
18636
+ }
18637
+ } catch {
18638
+ return false;
18639
+ }
18640
+ }
18641
+ async function startDaemon(options = {}) {
18642
+ const { port = 5433, host = "127.0.0.1", path: path2, dbPath, projectPath } = options;
18643
+ if (await isDaemonRunning(projectPath)) {
18644
+ const pid = await readPidFile(projectPath);
18645
+ if (!pid) {
18646
+ throw new Error("Daemon appears to be running but PID file is invalid");
18647
+ }
18648
+ return {
18649
+ pid,
18650
+ port: path2 ? undefined : port,
18651
+ socketPath: path2
18652
+ };
18653
+ }
18654
+ const finalDbPath = dbPath || getDatabasePath2(projectPath);
18655
+ const args = [`--db=${finalDbPath}`];
18656
+ if (path2) {
18657
+ args.push(`--path=${path2}`);
18658
+ } else {
18659
+ args.push(`--port=${port}`);
18660
+ args.push(`--host=${host}`);
18661
+ }
18662
+ const child = spawn("pglite-server", args, {
18663
+ detached: true,
18664
+ stdio: "ignore"
18665
+ });
18666
+ child.unref();
18667
+ if (!child.pid) {
18668
+ throw new Error("Failed to spawn pglite-server - no PID returned");
18669
+ }
18670
+ await writePidFile(child.pid, projectPath);
18671
+ const healthOptions = path2 ? { path: path2 } : { port, host };
18672
+ const ready = await waitFor(() => healthCheck(healthOptions), 1e4);
18673
+ if (!ready) {
18674
+ await deletePidFile(projectPath);
18675
+ throw new Error("pglite-server failed to start - health check timeout after 10s");
18676
+ }
18677
+ return {
18678
+ pid: child.pid,
18679
+ port: path2 ? undefined : port,
18680
+ socketPath: path2
18681
+ };
18682
+ }
18683
+ async function stopDaemon(projectPath) {
18684
+ const pid = await readPidFile(projectPath);
18685
+ if (!pid) {
18686
+ return;
18687
+ }
18688
+ if (!isProcessAlive(pid)) {
18689
+ await deletePidFile(projectPath);
18690
+ return;
18691
+ }
18692
+ try {
18693
+ process.kill(pid, "SIGTERM");
18694
+ } catch (error45) {
18695
+ if (error45 instanceof Error && "code" in error45 && error45.code === "ESRCH") {
18696
+ await deletePidFile(projectPath);
18697
+ return;
18698
+ }
18699
+ throw error45;
18700
+ }
18701
+ const stopped = await waitFor(() => Promise.resolve(!isProcessAlive(pid)), 5000);
18702
+ if (!stopped) {
18703
+ try {
18704
+ process.kill(pid, "SIGKILL");
18705
+ await waitFor(() => Promise.resolve(!isProcessAlive(pid)), 2000);
18706
+ } catch {}
18707
+ }
18708
+ await deletePidFile(projectPath);
18709
+ }
18710
+
18711
+ // src/pglite.ts
16897
18712
  function wrapPGlite(pglite) {
16898
18713
  return {
16899
18714
  query: (sql, params) => pglite.query(sql, params),
@@ -16903,25 +18718,45 @@ function wrapPGlite(pglite) {
16903
18718
  close: () => pglite.close()
16904
18719
  };
16905
18720
  }
18721
+ function hashProjectPath(projectPath) {
18722
+ return createHash("sha256").update(projectPath).digest("hex").slice(0, 8);
18723
+ }
18724
+ function getProjectTempDirName(projectPath) {
18725
+ const projectName = basename(projectPath).toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").slice(0, 32);
18726
+ const hash2 = hashProjectPath(projectPath);
18727
+ return `opencode-${projectName}-${hash2}`;
18728
+ }
16906
18729
  function getDatabasePath2(projectPath) {
18730
+ const tmp = tmpdir2();
16907
18731
  if (projectPath) {
16908
- const localDir = join2(projectPath, ".opencode");
16909
- if (!existsSync2(localDir)) {
16910
- mkdirSync2(localDir, { recursive: true });
18732
+ const dirName = getProjectTempDirName(projectPath);
18733
+ const projectTmpDir = join4(tmp, dirName);
18734
+ if (!existsSync4(projectTmpDir)) {
18735
+ mkdirSync4(projectTmpDir, { recursive: true });
16911
18736
  }
16912
- return join2(localDir, "streams");
18737
+ return join4(projectTmpDir, "streams");
16913
18738
  }
16914
- const globalDir = join2(homedir2(), ".opencode");
16915
- if (!existsSync2(globalDir)) {
16916
- mkdirSync2(globalDir, { recursive: true });
18739
+ const globalTmpDir = join4(tmp, "opencode-global");
18740
+ if (!existsSync4(globalTmpDir)) {
18741
+ mkdirSync4(globalTmpDir, { recursive: true });
16917
18742
  }
16918
- return join2(globalDir, "streams");
18743
+ return join4(globalTmpDir, "streams");
16919
18744
  }
16920
18745
  var instances2 = new Map;
16921
18746
  async function getSwarmMail(projectPath) {
16922
18747
  const dbPath = getDatabasePath2(projectPath);
16923
18748
  const projectKey = projectPath || dbPath;
16924
18749
  if (!instances2.has(dbPath)) {
18750
+ const useSocket = process.env.SWARM_MAIL_SOCKET === "true";
18751
+ if (useSocket) {
18752
+ try {
18753
+ const adapter2 = await getSwarmMailSocketInternal(projectPath);
18754
+ instances2.set(dbPath, { adapter: adapter2, isSocket: true });
18755
+ return adapter2;
18756
+ } catch (error45) {
18757
+ console.warn(`[swarm-mail] Socket mode failed, falling back to embedded PGLite: ${error45 instanceof Error ? error45.message : String(error45)}`);
18758
+ }
18759
+ }
16925
18760
  const pglite = new PGlite2(dbPath);
16926
18761
  const db = wrapPGlite(pglite);
16927
18762
  const adapter = createSwarmMailAdapter(db, projectKey);
@@ -16930,6 +18765,36 @@ async function getSwarmMail(projectPath) {
16930
18765
  }
16931
18766
  return instances2.get(dbPath).adapter;
16932
18767
  }
18768
+ async function getSwarmMailSocket(projectPath) {
18769
+ const dbPath = getDatabasePath2(projectPath);
18770
+ if (!instances2.has(dbPath)) {
18771
+ const adapter = await getSwarmMailSocketInternal(projectPath);
18772
+ instances2.set(dbPath, { adapter, isSocket: true });
18773
+ }
18774
+ return instances2.get(dbPath).adapter;
18775
+ }
18776
+ async function getSwarmMailSocketInternal(projectPath) {
18777
+ const projectKey = projectPath || getDatabasePath2(projectPath);
18778
+ const dbPath = getDatabasePath2(projectPath);
18779
+ const socketPath = process.env.SWARM_MAIL_SOCKET_PATH;
18780
+ const port = process.env.SWARM_MAIL_SOCKET_PORT ? Number.parseInt(process.env.SWARM_MAIL_SOCKET_PORT, 10) : 5433;
18781
+ const host = process.env.SWARM_MAIL_SOCKET_HOST || "127.0.0.1";
18782
+ const running = await isDaemonRunning(projectPath);
18783
+ if (!running) {
18784
+ const daemonOptions = socketPath ? { path: socketPath, dbPath, projectPath } : { port, host, dbPath, projectPath };
18785
+ await startDaemon(daemonOptions);
18786
+ }
18787
+ const healthOptions = socketPath ? { path: socketPath } : { port, host };
18788
+ const healthy = await healthCheck(healthOptions);
18789
+ if (!healthy) {
18790
+ throw new Error(`Daemon health check failed after startup (${socketPath ? `socket: ${socketPath}` : `TCP: ${host}:${port}`})`);
18791
+ }
18792
+ const adapterOptions = socketPath ? { path: socketPath } : { host, port };
18793
+ const db = await createSocketAdapter(adapterOptions);
18794
+ const adapter = createSwarmMailAdapter(db, projectKey);
18795
+ await adapter.runMigrations();
18796
+ return adapter;
18797
+ }
16933
18798
  async function createInMemorySwarmMail(projectKey = "test") {
16934
18799
  const pglite = new PGlite2;
16935
18800
  const db = wrapPGlite(pglite);
@@ -16941,13 +18806,21 @@ async function closeSwarmMail(projectPath) {
16941
18806
  const dbPath = getDatabasePath2(projectPath);
16942
18807
  const instance = instances2.get(dbPath);
16943
18808
  if (instance) {
16944
- await instance.pglite.close();
18809
+ if (instance.pglite) {
18810
+ await instance.pglite.close();
18811
+ } else {
18812
+ await instance.adapter.close();
18813
+ }
16945
18814
  instances2.delete(dbPath);
16946
18815
  }
16947
18816
  }
16948
18817
  async function closeAllSwarmMail() {
16949
18818
  for (const [path2, instance] of instances2) {
16950
- await instance.pglite.close();
18819
+ if (instance.pglite) {
18820
+ await instance.pglite.close();
18821
+ } else {
18822
+ await instance.adapter.close();
18823
+ }
16951
18824
  instances2.delete(path2);
16952
18825
  }
16953
18826
  }
@@ -17850,7 +19723,7 @@ async function getCommentThread(db, rootCommentId) {
17850
19723
  return result.rows;
17851
19724
  }
17852
19725
  // src/beads/jsonl.ts
17853
- import { createHash } from "node:crypto";
19726
+ import { createHash as createHash2 } from "node:crypto";
17854
19727
  function serializeToJSONL(bead) {
17855
19728
  return JSON.stringify(bead);
17856
19729
  }
@@ -17877,7 +19750,7 @@ function parseJSONL(jsonl) {
17877
19750
  }
17878
19751
  function computeContentHash(bead) {
17879
19752
  const canonical = JSON.stringify(bead, Object.keys(bead).sort());
17880
- return createHash("sha256").update(canonical).digest("hex");
19753
+ return createHash2("sha256").update(canonical).digest("hex");
17881
19754
  }
17882
19755
  async function exportToJSONL(adapter, projectKey, options = {}) {
17883
19756
  const db = await adapter.getDatabase();
@@ -18098,7 +19971,7 @@ async function importComments(adapter, projectKey, beadExport) {
18098
19971
  }
18099
19972
  }
18100
19973
  // src/beads/flush-manager.ts
18101
- import { writeFile } from "node:fs/promises";
19974
+ import { writeFile as writeFile2 } from "node:fs/promises";
18102
19975
  class FlushManager {
18103
19976
  adapter;
18104
19977
  projectKey;
@@ -18147,7 +20020,7 @@ class FlushManager {
18147
20020
  duration: Date.now() - startTime
18148
20021
  };
18149
20022
  }
18150
- await writeFile(this.outputPath, jsonl, "utf-8");
20023
+ await writeFile2(this.outputPath, jsonl, "utf-8");
18151
20024
  const bytesWritten = Buffer.byteLength(jsonl, "utf-8");
18152
20025
  const db = await this.adapter.getDatabase();
18153
20026
  for (const beadId of beadIds) {
@@ -18496,10 +20369,13 @@ function mergeJsonl(baseJsonl, leftJsonl, rightJsonl, options = {}) {
18496
20369
  // src/index.ts
18497
20370
  var SWARM_MAIL_VERSION = "0.1.0";
18498
20371
  export {
20372
+ wrapPostgres,
18499
20373
  wouldCreateCycle,
18500
20374
  withTiming,
18501
20375
  withTimeout,
18502
20376
  updateProjections,
20377
+ stopDaemon,
20378
+ startDaemon,
18503
20379
  serializeToJSONL,
18504
20380
  sendSwarmMessage,
18505
20381
  sendMessage,
@@ -18533,15 +20409,21 @@ export {
18533
20409
  isExpiredTombstone,
18534
20410
  isEventType,
18535
20411
  isDatabaseHealthy,
20412
+ isDaemonRunning,
18536
20413
  isBlocked,
18537
20414
  invalidateBlockedCache,
18538
20415
  inspectState,
18539
20416
  initSwarmAgent,
18540
20417
  initAgent,
18541
20418
  importFromJSONL,
20419
+ healthCheck,
20420
+ hashProjectPath,
18542
20421
  getThreadMessages,
20422
+ getSwarmMailSocket,
18543
20423
  getSwarmMail,
18544
20424
  getSwarmInbox,
20425
+ getProjectTempDirName,
20426
+ getPidFilePath,
18545
20427
  getPendingMigrations,
18546
20428
  getOpenBlockers,
18547
20429
  getNextReadyBead,
@@ -18580,6 +20462,7 @@ export {
18580
20462
  debugEvents,
18581
20463
  debugAgent,
18582
20464
  createSwarmMailAdapter,
20465
+ createSocketAdapter,
18583
20466
  createInMemorySwarmMail,
18584
20467
  createEvent,
18585
20468
  createBeadsAdapter,