swarm-mail 0.1.4 → 0.2.1

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, {
@@ -7,8 +24,1577 @@ var __export = (target, all) => {
7
24
  configurable: true,
8
25
  set: (newValue) => all[name] = () => newValue
9
26
  });
10
- };
11
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
27
+ };
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,
@@ -15378,6 +16964,90 @@ var init_migrations = __esm(() => {
15378
16964
  CREATE INDEX IF NOT EXISTS idx_swarm_contexts_epic ON swarm_contexts(epic_id);
15379
16965
  CREATE INDEX IF NOT EXISTS idx_swarm_contexts_bead ON swarm_contexts(bead_id);
15380
16966
  `
16967
+ },
16968
+ {
16969
+ version: 6,
16970
+ description: "Add core event store tables (events, agents, messages, reservations)",
16971
+ up: `
16972
+ -- Events table: append-only event log
16973
+ CREATE TABLE IF NOT EXISTS events (
16974
+ id SERIAL PRIMARY KEY,
16975
+ sequence SERIAL,
16976
+ type TEXT NOT NULL,
16977
+ project_key TEXT NOT NULL,
16978
+ timestamp BIGINT NOT NULL,
16979
+ data JSONB NOT NULL DEFAULT '{}'
16980
+ );
16981
+ CREATE INDEX IF NOT EXISTS idx_events_project ON events(project_key);
16982
+ CREATE INDEX IF NOT EXISTS idx_events_type ON events(type);
16983
+ CREATE INDEX IF NOT EXISTS idx_events_sequence ON events(sequence);
16984
+ CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
16985
+
16986
+ -- Agents table: materialized view of registered agents
16987
+ CREATE TABLE IF NOT EXISTS agents (
16988
+ id SERIAL PRIMARY KEY,
16989
+ project_key TEXT NOT NULL,
16990
+ name TEXT NOT NULL,
16991
+ program TEXT,
16992
+ model TEXT,
16993
+ task_description TEXT,
16994
+ registered_at BIGINT NOT NULL,
16995
+ last_active_at BIGINT NOT NULL,
16996
+ UNIQUE(project_key, name)
16997
+ );
16998
+ CREATE INDEX IF NOT EXISTS idx_agents_project ON agents(project_key);
16999
+
17000
+ -- Messages table: materialized view of sent messages
17001
+ CREATE TABLE IF NOT EXISTS messages (
17002
+ id SERIAL PRIMARY KEY,
17003
+ project_key TEXT NOT NULL,
17004
+ from_agent TEXT NOT NULL,
17005
+ subject TEXT NOT NULL,
17006
+ body TEXT,
17007
+ thread_id TEXT,
17008
+ importance TEXT NOT NULL DEFAULT 'normal',
17009
+ ack_required BOOLEAN NOT NULL DEFAULT FALSE,
17010
+ created_at BIGINT NOT NULL
17011
+ );
17012
+ CREATE INDEX IF NOT EXISTS idx_messages_project ON messages(project_key);
17013
+ CREATE INDEX IF NOT EXISTS idx_messages_thread ON messages(thread_id);
17014
+ CREATE INDEX IF NOT EXISTS idx_messages_from ON messages(from_agent);
17015
+
17016
+ -- Message recipients: join table for message routing
17017
+ CREATE TABLE IF NOT EXISTS message_recipients (
17018
+ id SERIAL PRIMARY KEY,
17019
+ message_id INTEGER NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
17020
+ agent_name TEXT NOT NULL,
17021
+ read_at BIGINT,
17022
+ acked_at BIGINT,
17023
+ UNIQUE(message_id, agent_name)
17024
+ );
17025
+ CREATE INDEX IF NOT EXISTS idx_message_recipients_agent ON message_recipients(agent_name);
17026
+ CREATE INDEX IF NOT EXISTS idx_message_recipients_message ON message_recipients(message_id);
17027
+
17028
+ -- Reservations table: materialized view of file locks
17029
+ CREATE TABLE IF NOT EXISTS reservations (
17030
+ id SERIAL PRIMARY KEY,
17031
+ project_key TEXT NOT NULL,
17032
+ agent_name TEXT NOT NULL,
17033
+ path_pattern TEXT NOT NULL,
17034
+ exclusive BOOLEAN NOT NULL DEFAULT TRUE,
17035
+ reason TEXT,
17036
+ created_at BIGINT NOT NULL,
17037
+ expires_at BIGINT NOT NULL,
17038
+ released_at BIGINT
17039
+ );
17040
+ CREATE INDEX IF NOT EXISTS idx_reservations_project ON reservations(project_key);
17041
+ CREATE INDEX IF NOT EXISTS idx_reservations_agent ON reservations(agent_name);
17042
+ CREATE INDEX IF NOT EXISTS idx_reservations_expires ON reservations(expires_at);
17043
+ `,
17044
+ down: `
17045
+ DROP TABLE IF EXISTS message_recipients;
17046
+ DROP TABLE IF EXISTS messages;
17047
+ DROP TABLE IF EXISTS reservations;
17048
+ DROP TABLE IF EXISTS agents;
17049
+ DROP TABLE IF EXISTS events;
17050
+ `
15381
17051
  }
15382
17052
  ];
15383
17053
  });
@@ -15682,8 +17352,8 @@ __export(exports_streams, {
15682
17352
  AgentActiveEventSchema: () => AgentActiveEventSchema
15683
17353
  });
15684
17354
  import { PGlite } from "@electric-sql/pglite";
15685
- import { existsSync, mkdirSync, appendFileSync } from "node:fs";
15686
- import { join } from "node:path";
17355
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, appendFileSync } from "node:fs";
17356
+ import { join as join2 } from "node:path";
15687
17357
  import { homedir } from "node:os";
15688
17358
  async function withTimeout(promise2, ms, operation) {
15689
17359
  const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error(`${operation} timed out after ${ms}ms`)), ms));
@@ -15711,19 +17381,19 @@ function debugLog(message, data) {
15711
17381
  }
15712
17382
  function getDatabasePath(projectPath) {
15713
17383
  if (projectPath) {
15714
- const localDir = join(projectPath, ".opencode");
15715
- if (existsSync(localDir) || existsSync(projectPath)) {
15716
- if (!existsSync(localDir)) {
15717
- mkdirSync(localDir, { recursive: true });
17384
+ const localDir = join2(projectPath, ".opencode");
17385
+ if (existsSync2(localDir) || existsSync2(projectPath)) {
17386
+ if (!existsSync2(localDir)) {
17387
+ mkdirSync2(localDir, { recursive: true });
15718
17388
  }
15719
- return join(localDir, "streams");
17389
+ return join2(localDir, "streams");
15720
17390
  }
15721
17391
  }
15722
- const globalDir = join(homedir(), ".opencode");
15723
- if (!existsSync(globalDir)) {
15724
- mkdirSync(globalDir, { recursive: true });
17392
+ const globalDir = join2(homedir(), ".opencode");
17393
+ if (!existsSync2(globalDir)) {
17394
+ mkdirSync2(globalDir, { recursive: true });
15725
17395
  }
15726
- return join(globalDir, "streams");
17396
+ return join2(globalDir, "streams");
15727
17397
  }
15728
17398
  function evictLRU() {
15729
17399
  if (instances.size < MAX_CACHE_SIZE) {
@@ -15777,7 +17447,11 @@ async function createDatabaseInstance(dbPath) {
15777
17447
  evictLRU();
15778
17448
  debugLog("createDatabaseInstance called", { dbPath, cwd: process.cwd() });
15779
17449
  let db;
17450
+ let releaseLock = null;
15780
17451
  try {
17452
+ debugLog("Acquiring init lock", { dbPath });
17453
+ releaseLock = await acquireInitLock(dbPath);
17454
+ debugLog("Init lock acquired");
15781
17455
  debugLog("Creating PGlite instance", { dbPath });
15782
17456
  db = new PGlite(dbPath);
15783
17457
  debugLog("PGlite instance created successfully");
@@ -15808,6 +17482,12 @@ async function createDatabaseInstance(dbPath) {
15808
17482
  console.error(`[swarm-mail] CRITICAL: In-memory fallback failed:`, fallbackErr.message);
15809
17483
  throw new Error(`Database initialization failed: ${err.message}. Fallback also failed: ${fallbackErr.message}`);
15810
17484
  }
17485
+ } finally {
17486
+ if (releaseLock) {
17487
+ debugLog("Releasing init lock");
17488
+ await releaseLock();
17489
+ debugLog("Init lock released");
17490
+ }
15811
17491
  }
15812
17492
  }
15813
17493
  async function closeDatabase(projectPath) {
@@ -15981,6 +17661,7 @@ function handleExit() {
15981
17661
  }
15982
17662
  var SLOW_QUERY_THRESHOLD_MS = 100, DEBUG_LOG_PATH, instances, pendingInstances, schemaInitialized, degradedInstances, lastAccess, MAX_CACHE_SIZE = 10;
15983
17663
  var init_streams = __esm(() => {
17664
+ init_leader_election();
15984
17665
  init_agent_mail();
15985
17666
  init_debug();
15986
17667
  init_events();
@@ -15988,7 +17669,7 @@ var init_streams = __esm(() => {
15988
17669
  init_projections();
15989
17670
  init_store();
15990
17671
  init_swarm_mail();
15991
- DEBUG_LOG_PATH = join(homedir(), ".opencode", "streams-debug.log");
17672
+ DEBUG_LOG_PATH = join2(homedir(), ".opencode", "streams-debug.log");
15992
17673
  instances = new Map;
15993
17674
  pendingInstances = new Map;
15994
17675
  schemaInitialized = new Map;
@@ -16891,9 +18572,227 @@ function createSwarmMailAdapter(db, projectKey) {
16891
18572
  }
16892
18573
  // src/pglite.ts
16893
18574
  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";
18575
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4 } from "node:fs";
18576
+ import { join as join4, basename } from "node:path";
18577
+ import { tmpdir as tmpdir2 } from "node:os";
18578
+ import { createHash } from "node:crypto";
18579
+
18580
+ // src/socket-adapter.ts
18581
+ import postgres from "postgres";
18582
+ function wrapPostgres(sql) {
18583
+ return {
18584
+ query: async (sqlString, params) => {
18585
+ const rows = await sql.unsafe(sqlString, params ?? []);
18586
+ return { rows };
18587
+ },
18588
+ exec: async (sqlString) => {
18589
+ await sql.unsafe(sqlString);
18590
+ },
18591
+ transaction: async (fn) => {
18592
+ const result = await sql.begin(async (transaction) => {
18593
+ const txAdapter = wrapPostgres(transaction);
18594
+ return await fn(txAdapter);
18595
+ });
18596
+ return result;
18597
+ },
18598
+ close: async () => {
18599
+ await sql.end();
18600
+ }
18601
+ };
18602
+ }
18603
+ async function createSocketAdapter(options) {
18604
+ if (!options.path && (!options.host || !options.port)) {
18605
+ throw new Error("Socket adapter requires either 'path' (unix socket) or 'host' + 'port' (TCP)");
18606
+ }
18607
+ if (options.path && (options.host || options.port)) {
18608
+ throw new Error("Socket adapter: cannot specify both 'path' and 'host'/'port'. Choose one connection method.");
18609
+ }
18610
+ try {
18611
+ const sql = postgres({
18612
+ path: options.path,
18613
+ host: options.host,
18614
+ port: options.port,
18615
+ connect_timeout: options.timeout,
18616
+ max: options.max ?? 10,
18617
+ idle_timeout: 0,
18618
+ max_lifetime: null
18619
+ });
18620
+ await sql`SELECT 1 as ping`;
18621
+ return wrapPostgres(sql);
18622
+ } catch (error45) {
18623
+ const connType = options.path ? `unix socket: ${options.path}` : `TCP: ${options.host}:${options.port}`;
18624
+ throw new Error(`Failed to connect to PostgreSQL via ${connType}: ${error45 instanceof Error ? error45.message : String(error45)}`);
18625
+ }
18626
+ }
18627
+
18628
+ // src/daemon.ts
18629
+ import { spawn } from "node:child_process";
18630
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3 } from "node:fs";
18631
+ import { readFile, writeFile, unlink } from "node:fs/promises";
18632
+ import { join as join3 } from "node:path";
18633
+ import { tmpdir } from "node:os";
18634
+ function getPidFilePath(projectPath) {
18635
+ const tmp = tmpdir();
18636
+ if (projectPath) {
18637
+ const dirName = getProjectTempDirName(projectPath);
18638
+ const projectTmpDir = join3(tmp, dirName);
18639
+ if (!existsSync3(projectTmpDir)) {
18640
+ mkdirSync3(projectTmpDir, { recursive: true });
18641
+ }
18642
+ return join3(projectTmpDir, "pglite-server.pid");
18643
+ }
18644
+ const globalTmpDir = join3(tmp, "opencode-global");
18645
+ if (!existsSync3(globalTmpDir)) {
18646
+ mkdirSync3(globalTmpDir, { recursive: true });
18647
+ }
18648
+ return join3(globalTmpDir, "pglite-server.pid");
18649
+ }
18650
+ function isProcessAlive(pid) {
18651
+ try {
18652
+ process.kill(pid, 0);
18653
+ return true;
18654
+ } catch (error45) {
18655
+ if (error45 instanceof Error && "code" in error45 && error45.code === "ESRCH") {
18656
+ return false;
18657
+ }
18658
+ return true;
18659
+ }
18660
+ }
18661
+ async function readPidFile(projectPath) {
18662
+ const pidFilePath = getPidFilePath(projectPath);
18663
+ if (!existsSync3(pidFilePath)) {
18664
+ return null;
18665
+ }
18666
+ try {
18667
+ const content = await readFile(pidFilePath, "utf-8");
18668
+ const pid = Number.parseInt(content.trim(), 10);
18669
+ if (Number.isNaN(pid) || pid <= 0) {
18670
+ return null;
18671
+ }
18672
+ return pid;
18673
+ } catch {
18674
+ return null;
18675
+ }
18676
+ }
18677
+ async function writePidFile(pid, projectPath) {
18678
+ const pidFilePath = getPidFilePath(projectPath);
18679
+ await writeFile(pidFilePath, pid.toString(), "utf-8");
18680
+ }
18681
+ async function deletePidFile(projectPath) {
18682
+ const pidFilePath = getPidFilePath(projectPath);
18683
+ try {
18684
+ await unlink(pidFilePath);
18685
+ } catch {}
18686
+ }
18687
+ async function waitFor(condition, timeoutMs, intervalMs = 100) {
18688
+ const start = Date.now();
18689
+ while (Date.now() - start < timeoutMs) {
18690
+ if (await condition()) {
18691
+ return true;
18692
+ }
18693
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
18694
+ }
18695
+ return false;
18696
+ }
18697
+ async function isDaemonRunning(projectPath) {
18698
+ const pid = await readPidFile(projectPath);
18699
+ if (!pid) {
18700
+ return false;
18701
+ }
18702
+ return isProcessAlive(pid);
18703
+ }
18704
+ async function healthCheck(options) {
18705
+ try {
18706
+ const postgres2 = await import("postgres").then((m) => m.default);
18707
+ const sql = options.path ? postgres2({ path: options.path }) : postgres2({
18708
+ host: options.host || "127.0.0.1",
18709
+ port: options.port || 5433,
18710
+ max: 1
18711
+ });
18712
+ try {
18713
+ await Promise.race([
18714
+ sql`SELECT 1`,
18715
+ new Promise((_, reject) => setTimeout(() => reject(new Error("Health check timeout")), 5000))
18716
+ ]);
18717
+ return true;
18718
+ } finally {
18719
+ await sql.end();
18720
+ }
18721
+ } catch {
18722
+ return false;
18723
+ }
18724
+ }
18725
+ async function startDaemon(options = {}) {
18726
+ const { port = 5433, host = "127.0.0.1", path: path2, dbPath, projectPath } = options;
18727
+ if (await isDaemonRunning(projectPath)) {
18728
+ const pid = await readPidFile(projectPath);
18729
+ if (!pid) {
18730
+ throw new Error("Daemon appears to be running but PID file is invalid");
18731
+ }
18732
+ return {
18733
+ pid,
18734
+ port: path2 ? undefined : port,
18735
+ socketPath: path2
18736
+ };
18737
+ }
18738
+ const finalDbPath = dbPath || getDatabasePath2(projectPath);
18739
+ const args = [`--db=${finalDbPath}`];
18740
+ if (path2) {
18741
+ args.push(`--path=${path2}`);
18742
+ } else {
18743
+ args.push(`--port=${port}`);
18744
+ args.push(`--host=${host}`);
18745
+ }
18746
+ const child = spawn("pglite-server", args, {
18747
+ detached: true,
18748
+ stdio: "ignore"
18749
+ });
18750
+ child.unref();
18751
+ if (!child.pid) {
18752
+ throw new Error("Failed to spawn pglite-server - no PID returned");
18753
+ }
18754
+ await writePidFile(child.pid, projectPath);
18755
+ const healthOptions = path2 ? { path: path2 } : { port, host };
18756
+ const ready = await waitFor(() => healthCheck(healthOptions), 1e4);
18757
+ if (!ready) {
18758
+ await deletePidFile(projectPath);
18759
+ throw new Error("pglite-server failed to start - health check timeout after 10s");
18760
+ }
18761
+ return {
18762
+ pid: child.pid,
18763
+ port: path2 ? undefined : port,
18764
+ socketPath: path2
18765
+ };
18766
+ }
18767
+ async function stopDaemon(projectPath) {
18768
+ const pid = await readPidFile(projectPath);
18769
+ if (!pid) {
18770
+ return;
18771
+ }
18772
+ if (!isProcessAlive(pid)) {
18773
+ await deletePidFile(projectPath);
18774
+ return;
18775
+ }
18776
+ try {
18777
+ process.kill(pid, "SIGTERM");
18778
+ } catch (error45) {
18779
+ if (error45 instanceof Error && "code" in error45 && error45.code === "ESRCH") {
18780
+ await deletePidFile(projectPath);
18781
+ return;
18782
+ }
18783
+ throw error45;
18784
+ }
18785
+ const stopped = await waitFor(() => Promise.resolve(!isProcessAlive(pid)), 5000);
18786
+ if (!stopped) {
18787
+ try {
18788
+ process.kill(pid, "SIGKILL");
18789
+ await waitFor(() => Promise.resolve(!isProcessAlive(pid)), 2000);
18790
+ } catch {}
18791
+ }
18792
+ await deletePidFile(projectPath);
18793
+ }
18794
+
18795
+ // src/pglite.ts
16897
18796
  function wrapPGlite(pglite) {
16898
18797
  return {
16899
18798
  query: (sql, params) => pglite.query(sql, params),
@@ -16903,25 +18802,45 @@ function wrapPGlite(pglite) {
16903
18802
  close: () => pglite.close()
16904
18803
  };
16905
18804
  }
18805
+ function hashProjectPath(projectPath) {
18806
+ return createHash("sha256").update(projectPath).digest("hex").slice(0, 8);
18807
+ }
18808
+ function getProjectTempDirName(projectPath) {
18809
+ const projectName = basename(projectPath).toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").slice(0, 32);
18810
+ const hash2 = hashProjectPath(projectPath);
18811
+ return `opencode-${projectName}-${hash2}`;
18812
+ }
16906
18813
  function getDatabasePath2(projectPath) {
18814
+ const tmp = tmpdir2();
16907
18815
  if (projectPath) {
16908
- const localDir = join2(projectPath, ".opencode");
16909
- if (!existsSync2(localDir)) {
16910
- mkdirSync2(localDir, { recursive: true });
18816
+ const dirName = getProjectTempDirName(projectPath);
18817
+ const projectTmpDir = join4(tmp, dirName);
18818
+ if (!existsSync4(projectTmpDir)) {
18819
+ mkdirSync4(projectTmpDir, { recursive: true });
16911
18820
  }
16912
- return join2(localDir, "streams");
18821
+ return join4(projectTmpDir, "streams");
16913
18822
  }
16914
- const globalDir = join2(homedir2(), ".opencode");
16915
- if (!existsSync2(globalDir)) {
16916
- mkdirSync2(globalDir, { recursive: true });
18823
+ const globalTmpDir = join4(tmp, "opencode-global");
18824
+ if (!existsSync4(globalTmpDir)) {
18825
+ mkdirSync4(globalTmpDir, { recursive: true });
16917
18826
  }
16918
- return join2(globalDir, "streams");
18827
+ return join4(globalTmpDir, "streams");
16919
18828
  }
16920
18829
  var instances2 = new Map;
16921
18830
  async function getSwarmMail(projectPath) {
16922
18831
  const dbPath = getDatabasePath2(projectPath);
16923
18832
  const projectKey = projectPath || dbPath;
16924
18833
  if (!instances2.has(dbPath)) {
18834
+ const useSocket = process.env.SWARM_MAIL_SOCKET === "true";
18835
+ if (useSocket) {
18836
+ try {
18837
+ const adapter2 = await getSwarmMailSocketInternal(projectPath);
18838
+ instances2.set(dbPath, { adapter: adapter2, isSocket: true });
18839
+ return adapter2;
18840
+ } catch (error45) {
18841
+ console.warn(`[swarm-mail] Socket mode failed, falling back to embedded PGLite: ${error45 instanceof Error ? error45.message : String(error45)}`);
18842
+ }
18843
+ }
16925
18844
  const pglite = new PGlite2(dbPath);
16926
18845
  const db = wrapPGlite(pglite);
16927
18846
  const adapter = createSwarmMailAdapter(db, projectKey);
@@ -16930,6 +18849,36 @@ async function getSwarmMail(projectPath) {
16930
18849
  }
16931
18850
  return instances2.get(dbPath).adapter;
16932
18851
  }
18852
+ async function getSwarmMailSocket(projectPath) {
18853
+ const dbPath = getDatabasePath2(projectPath);
18854
+ if (!instances2.has(dbPath)) {
18855
+ const adapter = await getSwarmMailSocketInternal(projectPath);
18856
+ instances2.set(dbPath, { adapter, isSocket: true });
18857
+ }
18858
+ return instances2.get(dbPath).adapter;
18859
+ }
18860
+ async function getSwarmMailSocketInternal(projectPath) {
18861
+ const projectKey = projectPath || getDatabasePath2(projectPath);
18862
+ const dbPath = getDatabasePath2(projectPath);
18863
+ const socketPath = process.env.SWARM_MAIL_SOCKET_PATH;
18864
+ const port = process.env.SWARM_MAIL_SOCKET_PORT ? Number.parseInt(process.env.SWARM_MAIL_SOCKET_PORT, 10) : 5433;
18865
+ const host = process.env.SWARM_MAIL_SOCKET_HOST || "127.0.0.1";
18866
+ const running = await isDaemonRunning(projectPath);
18867
+ if (!running) {
18868
+ const daemonOptions = socketPath ? { path: socketPath, dbPath, projectPath } : { port, host, dbPath, projectPath };
18869
+ await startDaemon(daemonOptions);
18870
+ }
18871
+ const healthOptions = socketPath ? { path: socketPath } : { port, host };
18872
+ const healthy = await healthCheck(healthOptions);
18873
+ if (!healthy) {
18874
+ throw new Error(`Daemon health check failed after startup (${socketPath ? `socket: ${socketPath}` : `TCP: ${host}:${port}`})`);
18875
+ }
18876
+ const adapterOptions = socketPath ? { path: socketPath } : { host, port };
18877
+ const db = await createSocketAdapter(adapterOptions);
18878
+ const adapter = createSwarmMailAdapter(db, projectKey);
18879
+ await adapter.runMigrations();
18880
+ return adapter;
18881
+ }
16933
18882
  async function createInMemorySwarmMail(projectKey = "test") {
16934
18883
  const pglite = new PGlite2;
16935
18884
  const db = wrapPGlite(pglite);
@@ -16941,13 +18890,21 @@ async function closeSwarmMail(projectPath) {
16941
18890
  const dbPath = getDatabasePath2(projectPath);
16942
18891
  const instance = instances2.get(dbPath);
16943
18892
  if (instance) {
16944
- await instance.pglite.close();
18893
+ if (instance.pglite) {
18894
+ await instance.pglite.close();
18895
+ } else {
18896
+ await instance.adapter.close();
18897
+ }
16945
18898
  instances2.delete(dbPath);
16946
18899
  }
16947
18900
  }
16948
18901
  async function closeAllSwarmMail() {
16949
18902
  for (const [path2, instance] of instances2) {
16950
- await instance.pglite.close();
18903
+ if (instance.pglite) {
18904
+ await instance.pglite.close();
18905
+ } else {
18906
+ await instance.adapter.close();
18907
+ }
16951
18908
  instances2.delete(path2);
16952
18909
  }
16953
18910
  }
@@ -17850,7 +19807,7 @@ async function getCommentThread(db, rootCommentId) {
17850
19807
  return result.rows;
17851
19808
  }
17852
19809
  // src/beads/jsonl.ts
17853
- import { createHash } from "node:crypto";
19810
+ import { createHash as createHash2 } from "node:crypto";
17854
19811
  function serializeToJSONL(bead) {
17855
19812
  return JSON.stringify(bead);
17856
19813
  }
@@ -17877,7 +19834,7 @@ function parseJSONL(jsonl) {
17877
19834
  }
17878
19835
  function computeContentHash(bead) {
17879
19836
  const canonical = JSON.stringify(bead, Object.keys(bead).sort());
17880
- return createHash("sha256").update(canonical).digest("hex");
19837
+ return createHash2("sha256").update(canonical).digest("hex");
17881
19838
  }
17882
19839
  async function exportToJSONL(adapter, projectKey, options = {}) {
17883
19840
  const db = await adapter.getDatabase();
@@ -17990,25 +19947,26 @@ async function importSingleBead(adapter, projectKey, beadExport, options, result
17990
19947
  }
17991
19948
  if (!existing) {
17992
19949
  const db = await adapter.getDatabase();
19950
+ const status = beadExport.status === "tombstone" ? "closed" : beadExport.status;
19951
+ const isClosed = status === "closed";
19952
+ const closedAt = isClosed ? beadExport.closed_at ? new Date(beadExport.closed_at).getTime() : new Date(beadExport.updated_at).getTime() : null;
17993
19953
  await db.query(`INSERT INTO beads (
17994
19954
  id, project_key, type, status, title, description, priority,
17995
- parent_id, assignee, created_at, updated_at
17996
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`, [
19955
+ parent_id, assignee, created_at, updated_at, closed_at
19956
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`, [
17997
19957
  beadExport.id,
17998
19958
  projectKey,
17999
19959
  beadExport.issue_type,
18000
- beadExport.status === "tombstone" ? "closed" : beadExport.status,
19960
+ status,
18001
19961
  beadExport.title,
18002
19962
  beadExport.description || null,
18003
19963
  beadExport.priority,
18004
19964
  beadExport.parent_id || null,
18005
19965
  beadExport.assignee || null,
18006
19966
  new Date(beadExport.created_at).getTime(),
18007
- new Date(beadExport.updated_at).getTime()
19967
+ new Date(beadExport.updated_at).getTime(),
19968
+ closedAt
18008
19969
  ]);
18009
- if (beadExport.status === "closed" && beadExport.closed_at) {
18010
- await db.query("UPDATE beads SET closed_at = $1 WHERE id = $2", [new Date(beadExport.closed_at).getTime(), beadExport.id]);
18011
- }
18012
19970
  if (beadExport.status === "tombstone") {
18013
19971
  await db.query("UPDATE beads SET deleted_at = $1 WHERE id = $2", [Date.now(), beadExport.id]);
18014
19972
  }
@@ -18071,6 +20029,9 @@ async function computeBeadHash(adapter, projectKey, beadId) {
18071
20029
  return computeContentHash(beadExport);
18072
20030
  }
18073
20031
  async function importDependencies(adapter, projectKey, beadExport) {
20032
+ if (!beadExport.dependencies || beadExport.dependencies.length === 0) {
20033
+ return;
20034
+ }
18074
20035
  const db = await adapter.getDatabase();
18075
20036
  await db.query("DELETE FROM bead_dependencies WHERE bead_id = $1", [
18076
20037
  beadExport.id
@@ -18080,6 +20041,9 @@ async function importDependencies(adapter, projectKey, beadExport) {
18080
20041
  }
18081
20042
  }
18082
20043
  async function importLabels(adapter, projectKey, beadExport) {
20044
+ if (!beadExport.labels || beadExport.labels.length === 0) {
20045
+ return;
20046
+ }
18083
20047
  const db = await adapter.getDatabase();
18084
20048
  await db.query("DELETE FROM bead_labels WHERE bead_id = $1", [
18085
20049
  beadExport.id
@@ -18089,6 +20053,9 @@ async function importLabels(adapter, projectKey, beadExport) {
18089
20053
  }
18090
20054
  }
18091
20055
  async function importComments(adapter, projectKey, beadExport) {
20056
+ if (!beadExport.comments || beadExport.comments.length === 0) {
20057
+ return;
20058
+ }
18092
20059
  const db = await adapter.getDatabase();
18093
20060
  await db.query("DELETE FROM bead_comments WHERE bead_id = $1", [
18094
20061
  beadExport.id
@@ -18098,7 +20065,7 @@ async function importComments(adapter, projectKey, beadExport) {
18098
20065
  }
18099
20066
  }
18100
20067
  // src/beads/flush-manager.ts
18101
- import { writeFile } from "node:fs/promises";
20068
+ import { writeFile as writeFile2 } from "node:fs/promises";
18102
20069
  class FlushManager {
18103
20070
  adapter;
18104
20071
  projectKey;
@@ -18147,7 +20114,7 @@ class FlushManager {
18147
20114
  duration: Date.now() - startTime
18148
20115
  };
18149
20116
  }
18150
- await writeFile(this.outputPath, jsonl, "utf-8");
20117
+ await writeFile2(this.outputPath, jsonl, "utf-8");
18151
20118
  const bytesWritten = Buffer.byteLength(jsonl, "utf-8");
18152
20119
  const db = await this.adapter.getDatabase();
18153
20120
  for (const beadId of beadIds) {
@@ -18496,10 +20463,13 @@ function mergeJsonl(baseJsonl, leftJsonl, rightJsonl, options = {}) {
18496
20463
  // src/index.ts
18497
20464
  var SWARM_MAIL_VERSION = "0.1.0";
18498
20465
  export {
20466
+ wrapPostgres,
18499
20467
  wouldCreateCycle,
18500
20468
  withTiming,
18501
20469
  withTimeout,
18502
20470
  updateProjections,
20471
+ stopDaemon,
20472
+ startDaemon,
18503
20473
  serializeToJSONL,
18504
20474
  sendSwarmMessage,
18505
20475
  sendMessage,
@@ -18533,15 +20503,21 @@ export {
18533
20503
  isExpiredTombstone,
18534
20504
  isEventType,
18535
20505
  isDatabaseHealthy,
20506
+ isDaemonRunning,
18536
20507
  isBlocked,
18537
20508
  invalidateBlockedCache,
18538
20509
  inspectState,
18539
20510
  initSwarmAgent,
18540
20511
  initAgent,
18541
20512
  importFromJSONL,
20513
+ healthCheck,
20514
+ hashProjectPath,
18542
20515
  getThreadMessages,
20516
+ getSwarmMailSocket,
18543
20517
  getSwarmMail,
18544
20518
  getSwarmInbox,
20519
+ getProjectTempDirName,
20520
+ getPidFilePath,
18545
20521
  getPendingMigrations,
18546
20522
  getOpenBlockers,
18547
20523
  getNextReadyBead,
@@ -18580,6 +20556,7 @@ export {
18580
20556
  debugEvents,
18581
20557
  debugAgent,
18582
20558
  createSwarmMailAdapter,
20559
+ createSocketAdapter,
18583
20560
  createInMemorySwarmMail,
18584
20561
  createEvent,
18585
20562
  createBeadsAdapter,