Files
bare-operating-system/packages/bare-os-seeder/kernel/lib/bare/bundles/holesail.js
T

27460 lines
990 KiB
JavaScript

var __bare_os_bundle_exports__ = (() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// ../../node_modules/bare-events/lib/errors.js
var require_errors = __commonJS({
"../../node_modules/bare-events/lib/errors.js"(exports, module) {
module.exports = class EventEmitterError extends Error {
constructor(msg, code, fn = EventEmitterError, opts) {
super(`${code}: ${msg}`, opts);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "EventEmitterError";
}
static OPERATION_ABORTED(cause, msg = "Operation aborted") {
return new EventEmitterError(msg, "OPERATION_ABORTED", EventEmitterError.OPERATION_ABORTED, {
cause
});
}
static UNHANDLED_ERROR(cause, msg = "Unhandled error") {
return new EventEmitterError(msg, "UNHANDLED_ERROR", EventEmitterError.UNHANDLED_ERROR, {
cause
});
}
};
}
});
// ../../node_modules/bare-events/index.js
var require_bare_events = __commonJS({
"../../node_modules/bare-events/index.js"(exports, module) {
var errors = require_errors();
var EventListener = class {
constructor() {
this.list = [];
this.count = 0;
}
append(ctx, name, fn, once) {
this.count++;
ctx.emit("newListener", name, fn);
this.list.push([fn, once]);
}
prepend(ctx, name, fn, once) {
this.count++;
ctx.emit("newListener", name, fn);
this.list.unshift([fn, once]);
}
remove(ctx, name, fn) {
for (let i = 0, n = this.list.length; i < n; i++) {
const l = this.list[i];
if (l[0] === fn) {
this.list.splice(i, 1);
if (this.count === 1) delete ctx._events[name];
ctx.emit("removeListener", name, fn);
this.count--;
return;
}
}
}
removeAll(ctx, name) {
const list = [...this.list];
this.list = [];
if (this.count === list.length) delete ctx._events[name];
for (let i = list.length - 1; i >= 0; i--) {
ctx.emit("removeListener", name, list[i][0]);
}
this.count -= list.length;
}
emit(ctx, name, ...args) {
const list = [...this.list];
for (let i = 0, n = list.length; i < n; i++) {
const l = list[i];
if (l[1] === true) this.remove(ctx, name, l[0]);
Reflect.apply(l[0], ctx, args);
}
return list.length > 0;
}
};
function appendListener(ctx, name, fn, once) {
if (ctx._events === void 0) ctx._events = /* @__PURE__ */ Object.create(null);
const e = ctx._events[name] || (ctx._events[name] = new EventListener());
e.append(ctx, name, fn, once);
return ctx;
}
function prependListener(ctx, name, fn, once) {
if (ctx._events === void 0) ctx._events = /* @__PURE__ */ Object.create(null);
const e = ctx._events[name] || (ctx._events[name] = new EventListener());
e.prepend(ctx, name, fn, once);
return ctx;
}
function removeListener(ctx, name, fn) {
if (ctx._events === void 0) return ctx;
const e = ctx._events[name];
if (e !== void 0) e.remove(ctx, name, fn);
return ctx;
}
function throwUnhandledError(...args) {
let err;
if (args.length > 0) err = args[0];
if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err);
if (Error.captureStackTrace) {
Error.captureStackTrace(err, exports.prototype.emit);
}
queueMicrotask(() => {
throw err;
});
}
module.exports = exports = class EventEmitter {
constructor() {
this._events = /* @__PURE__ */ Object.create(null);
}
addListener(name, fn) {
return appendListener(this, name, fn, false);
}
addOnceListener(name, fn) {
return appendListener(this, name, fn, true);
}
prependListener(name, fn) {
return prependListener(this, name, fn, false);
}
prependOnceListener(name, fn) {
return prependListener(this, name, fn, true);
}
removeListener(name, fn) {
return removeListener(this, name, fn);
}
on(name, fn) {
return appendListener(this, name, fn, false);
}
once(name, fn) {
return appendListener(this, name, fn, true);
}
off(name, fn) {
return removeListener(this, name, fn);
}
emit(name, ...args) {
if (name === "error" && this._events !== void 0 && this._events.error === void 0) {
throwUnhandledError(...args);
}
if (this._events === void 0) return false;
const e = this._events[name];
return e === void 0 ? false : e.emit(this, name, ...args);
}
listeners(name) {
if (this._events === void 0) return [];
const e = this._events[name];
return e === void 0 ? [] : [...e.list];
}
listenerCount(name) {
if (this._events === void 0) return 0;
const e = this._events[name];
return e === void 0 ? 0 : e.list.length;
}
getMaxListeners() {
return EventEmitter.defaultMaxListeners;
}
setMaxListeners(n) {
}
removeAllListeners(name) {
if (arguments.length === 0) {
for (const key of Reflect.ownKeys(this._events)) {
if (key === "removeListener") continue;
this.removeAllListeners(key);
}
this.removeAllListeners("removeListener");
} else {
const e = this._events[name];
if (e !== void 0) e.removeAll(this, name);
}
return this;
}
};
exports.EventEmitter = exports;
exports.errors = errors;
exports.defaultMaxListeners = 10;
exports.on = function on(emitter, name, opts = {}) {
const { signal } = opts;
if (signal && signal.aborted) {
throw errors.OPERATION_ABORTED(signal.reason);
}
let error = null;
let done = false;
const events = [];
const promises = [];
if (name !== "error") emitter.on("error", onerror);
if (signal) signal.addEventListener("abort", onabort);
emitter.on(name, onevent);
return {
next() {
if (events.length) {
return Promise.resolve({ value: events.shift(), done: false });
}
if (error) {
const err = error;
error = null;
return Promise.reject(err);
}
if (done) return onclose();
return new Promise((resolve, reject) => promises.push({ resolve, reject }));
},
return() {
return onclose();
},
throw(err) {
return onerror(err);
},
[Symbol.asyncIterator]() {
return this;
}
};
function onevent(...args) {
if (promises.length) {
promises.shift().resolve({ value: args, done: false });
} else {
events.push(args);
}
}
function onerror(err) {
emitter.off(name, onevent).off("error", onerror);
if (promises.length) {
promises.shift().reject(err);
} else {
error = err;
}
return Promise.resolve({ done: true });
}
function onabort() {
signal.removeEventListener("abort", onabort);
onerror(errors.OPERATION_ABORTED(signal.reason));
}
function onclose() {
emitter.off(name, onevent);
if (name !== "error") emitter.off("error", onerror);
if (signal) signal.removeEventListener("abort", onabort);
done = true;
if (promises.length) promises.shift().resolve({ done: true });
return Promise.resolve({ done: true });
}
};
exports.once = function once(emitter, name, opts = {}) {
const { signal } = opts;
if (signal && signal.aborted) {
return Promise.reject(errors.OPERATION_ABORTED(signal.reason));
}
return new Promise((resolve, reject) => {
if (name !== "error") emitter.on("error", onerror);
if (signal) signal.addEventListener("abort", onabort);
emitter.once(name, onevent);
function onevent(...args) {
if (name !== "error") emitter.off("error", onerror);
if (signal) signal.removeEventListener("abort", onabort);
resolve(args);
}
function onerror(err) {
emitter.off(name, onevent);
if (name !== "error") emitter.off("error", onerror);
reject(err);
}
function onabort() {
signal.removeEventListener("abort", onabort);
onerror(errors.OPERATION_ABORTED(signal.reason));
}
});
};
exports.forward = function forward(from, to, names, opts = {}) {
if (typeof names === "string") names = [names];
const { emit = to.emit.bind(to) } = opts;
const listeners = names.map(
(name) => function onevent(...args) {
emit(name, ...args);
}
);
to.on("newListener", (name) => {
const i = names.indexOf(name);
if (i !== -1 && to.listenerCount(name) === 0) {
from.on(name, listeners[i]);
}
}).on("removeListener", (name) => {
const i = names.indexOf(name);
if (i !== -1 && to.listenerCount(name) === 0) {
from.off(name, listeners[i]);
}
});
};
exports.listenerCount = function listenerCount(emitter, name) {
return emitter.listenerCount(name);
};
exports.getMaxListeners = function getMaxListeners(emitter) {
if (typeof emitter.getMaxListeners === "function") {
return emitter.getMaxListeners();
}
return exports.defaultMaxListeners;
};
exports.setMaxListeners = function setMaxListeners(n, ...emitters) {
if (emitters.length === 0) exports.defaultMaxListeners = n;
else {
for (const emitter of emitters) {
if (typeof emitter.setMaxListeners === "function") {
emitter.setMaxListeners(n);
}
}
}
};
}
});
// ../bare-os-openssh/vendor/bare-node-shims/bare-node-events/index.js
var require_bare_node_events = __commonJS({
"../bare-os-openssh/vendor/bare-node-shims/bare-node-events/index.js"(exports, module) {
module.exports = require_bare_events();
}
});
// ../../node_modules/ready-resource/index.js
var require_ready_resource = __commonJS({
"../../node_modules/ready-resource/index.js"(exports, module) {
var EventEmitter = require_bare_node_events();
module.exports = class ReadyResource extends EventEmitter {
constructor() {
super();
this.opening = null;
this.closing = null;
this.opened = false;
this.closed = false;
}
ready() {
if (this.opening !== null) return this.opening;
this.opening = open(this);
return this.opening;
}
close() {
if (this.closing !== null) return this.closing;
this.closing = close(this);
return this.closing;
}
async _open() {
}
async _close() {
}
};
async function open(self) {
if (self.closing !== null) return;
try {
await self._open();
} catch (err) {
self.close();
throw err;
}
self.opened = true;
self.emit("ready");
}
async function close(self) {
try {
if (self.opened === false && self.opening !== null) await self.opening;
} catch {
}
if (self.opened === true || self.opening === null) await self._close();
self.closed = true;
self.emit("close");
}
}
});
// ../../node_modules/kademlia-routing-table/index.js
var require_kademlia_routing_table = __commonJS({
"../../node_modules/kademlia-routing-table/index.js"(exports, module) {
var { EventEmitter } = require_bare_node_events();
module.exports = class RoutingTable extends EventEmitter {
constructor(id, opts) {
if (!opts) opts = {};
super();
this.id = id;
this.k = opts.k || 20;
this.size = 0;
this.rows = new Array(id.length * 8);
}
add(node) {
const i = this._diff(node.id);
let row = this.rows[i];
if (!row) {
row = this.rows[i] = new Row(this, i);
this.emit("row", row);
}
const len = row.nodes.length;
if (!row.add(node, this.k)) return false;
this.size += row.nodes.length - len;
return true;
}
remove(id) {
const i = this._diff(id);
const row = this.rows[i];
if (!row) return false;
if (!row.remove(id)) return false;
this.size--;
return true;
}
get(id) {
const i = this._diff(id);
const row = this.rows[i];
if (!row) return null;
return row.get(id);
}
has(id) {
return this.get(id) !== null;
}
random() {
let n = Math.random() * this.size | 0;
for (let i = 0; i < this.rows.length; i++) {
const r = this.rows[i];
if (!r) continue;
if (n < r.nodes.length) return r.nodes[n];
n -= r.nodes.length;
}
return null;
}
closest(id, k) {
if (!k) k = this.k;
const result = [];
const d = this._diff(id);
for (let i = d; i >= 0 && result.length < k; i--) this._pushNodes(i, k, result);
for (let i = d + 1; i < this.rows.length && result.length < k; i++) this._pushNodes(i, k, result);
return result;
}
_pushNodes(i, k, result) {
const row = this.rows[i];
if (!row) return;
const missing = Math.min(k - result.length, row.nodes.length);
for (let j = 0; j < missing; j++) result.push(row.nodes[j]);
}
toArray() {
return this.closest(this.id, Infinity);
}
_diff(id) {
for (let i = 0; i < id.length; i++) {
const a = id[i];
const b = this.id[i];
if (a !== b) return i * 8 + Math.clz32(a ^ b) - 24;
}
return this.rows.length - 1;
}
};
var Row = class extends EventEmitter {
constructor(table, index) {
super();
this.data = null;
this.byteOffset = index >> 3;
this.index = index;
this.table = table;
this.nodes = [];
}
add(node) {
const id = node.id;
let l = 0;
let r = this.nodes.length - 1;
while (l <= r) {
const m = l + r >> 1;
const c = this.compare(id, this.nodes[m].id);
if (c === 0) {
this.nodes[m] = node;
return true;
}
if (c < 0) r = m - 1;
else l = m + 1;
}
if (this.nodes.length >= this.table.k) {
this.emit("full", node);
return false;
}
this.insert(l, node);
return true;
}
remove(id) {
let l = 0;
let r = this.nodes.length - 1;
while (l <= r) {
const m = l + r >> 1;
const c = this.compare(id, this.nodes[m].id);
if (c === 0) {
this.splice(m);
return true;
}
if (c < 0) r = m - 1;
else l = m + 1;
}
return false;
}
get(id) {
let l = 0;
let r = this.nodes.length - 1;
while (l <= r) {
const m = l + r >> 1;
const node = this.nodes[m];
const c = this.compare(id, node.id);
if (c === 0) return node;
if (c < 0) r = m - 1;
else l = m + 1;
}
return null;
}
insert(i, node) {
this.nodes.push(node);
for (let j = this.nodes.length - 1; j > i; j--) this.nodes[j] = this.nodes[j - 1];
this.nodes[i] = node;
this.emit("add", node);
}
splice(i) {
for (; i < this.nodes.length - 1; i++) this.nodes[i] = this.nodes[i + 1];
this.emit("remove", this.nodes.pop());
}
// very likely they diverge after a couple of bytes so a simple impl, like this is prop fastest vs Buffer.compare
compare(a, b) {
for (let i = this.byteOffset; i < a.length; i++) {
const ai = a[i];
const bi = b[i];
if (ai === bi) continue;
return ai < bi ? -1 : 1;
}
return 0;
}
};
}
});
// ../../node_modules/time-ordered-set/index.js
var require_time_ordered_set = __commonJS({
"../../node_modules/time-ordered-set/index.js"(exports, module) {
module.exports = class TimeOrderedSet {
constructor() {
this.oldest = null;
this.latest = null;
this.length = 0;
}
has(node) {
return !!(node.next || node.prev) || node === this.oldest;
}
add(node) {
if (this.has(node)) this.remove(node);
if (!this.latest && !this.oldest) {
this.latest = this.oldest = node;
node.prev = node.next = null;
} else {
this.latest.next = node;
node.prev = this.latest;
node.next = null;
this.latest = node;
}
this.length++;
return node;
}
remove(node) {
if (!this.has(node)) return node;
if (this.oldest !== node && this.latest !== node) {
node.prev.next = node.next;
node.next.prev = node.prev;
} else {
if (this.oldest === node) {
this.oldest = node.next;
if (this.oldest) this.oldest.prev = null;
}
if (this.latest === node) {
this.latest = node.prev;
if (this.latest) this.latest.next = null;
}
}
node.next = node.prev = null;
this.length--;
return node;
}
toArray({ limit = Infinity, reverse = false } = {}) {
const list = [];
if (reverse) {
let node = this.latest;
while (node && limit--) {
list.push(node);
node = node.prev;
}
} else {
let node = this.oldest;
while (node && limit--) {
list.push(node);
node = node.next;
}
}
return list;
}
};
}
});
// ../../node_modules/b4a/index.js
var require_b4a = __commonJS({
"../../node_modules/b4a/index.js"(exports, module) {
function isBuffer(value) {
return Buffer.isBuffer(value) || value instanceof Uint8Array;
}
function isEncoding(encoding) {
return Buffer.isEncoding(encoding);
}
function alloc(size, fill2, encoding) {
return Buffer.alloc(size, fill2, encoding);
}
function allocUnsafe(size) {
return Buffer.allocUnsafe(size);
}
function allocUnsafeSlow(size) {
return Buffer.allocUnsafeSlow(size);
}
function byteLength(string, encoding) {
return Buffer.byteLength(string, encoding);
}
function compare(a, b) {
return Buffer.compare(a, b);
}
function concat(buffers, totalLength) {
return Buffer.concat(buffers, totalLength);
}
function copy(source, target, targetStart, start, end) {
return toBuffer(source).copy(target, targetStart, start, end);
}
function equals(a, b) {
return toBuffer(a).equals(b);
}
function fill(buffer, value, offset, end, encoding) {
return toBuffer(buffer).fill(value, offset, end, encoding);
}
function from(value, encodingOrOffset, length) {
return Buffer.from(value, encodingOrOffset, length);
}
function includes(buffer, value, byteOffset, encoding) {
return toBuffer(buffer).includes(value, byteOffset, encoding);
}
function indexOf(buffer, value, byfeOffset, encoding) {
return toBuffer(buffer).indexOf(value, byfeOffset, encoding);
}
function lastIndexOf(buffer, value, byteOffset, encoding) {
return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding);
}
function swap16(buffer) {
return toBuffer(buffer).swap16();
}
function swap32(buffer) {
return toBuffer(buffer).swap32();
}
function swap64(buffer) {
return toBuffer(buffer).swap64();
}
function toBuffer(buffer) {
if (Buffer.isBuffer(buffer)) return buffer;
return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
}
function toString(buffer, encoding, start, end) {
return toBuffer(buffer).toString(encoding, start, end);
}
function write(buffer, string, offset, length, encoding) {
return toBuffer(buffer).write(string, offset, length, encoding);
}
function readDoubleBE(buffer, offset) {
return toBuffer(buffer).readDoubleBE(offset);
}
function readDoubleLE(buffer, offset) {
return toBuffer(buffer).readDoubleLE(offset);
}
function readFloatBE(buffer, offset) {
return toBuffer(buffer).readFloatBE(offset);
}
function readFloatLE(buffer, offset) {
return toBuffer(buffer).readFloatLE(offset);
}
function readInt32BE(buffer, offset) {
return toBuffer(buffer).readInt32BE(offset);
}
function readInt32LE(buffer, offset) {
return toBuffer(buffer).readInt32LE(offset);
}
function readUInt32BE(buffer, offset) {
return toBuffer(buffer).readUInt32BE(offset);
}
function readUInt32LE(buffer, offset) {
return toBuffer(buffer).readUInt32LE(offset);
}
function writeDoubleBE(buffer, value, offset) {
return toBuffer(buffer).writeDoubleBE(value, offset);
}
function writeDoubleLE(buffer, value, offset) {
return toBuffer(buffer).writeDoubleLE(value, offset);
}
function writeFloatBE(buffer, value, offset) {
return toBuffer(buffer).writeFloatBE(value, offset);
}
function writeFloatLE(buffer, value, offset) {
return toBuffer(buffer).writeFloatLE(value, offset);
}
function writeInt32BE(buffer, value, offset) {
return toBuffer(buffer).writeInt32BE(value, offset);
}
function writeInt32LE(buffer, value, offset) {
return toBuffer(buffer).writeInt32LE(value, offset);
}
function writeUInt32BE(buffer, value, offset) {
return toBuffer(buffer).writeUInt32BE(value, offset);
}
function writeUInt32LE(buffer, value, offset) {
return toBuffer(buffer).writeUInt32LE(value, offset);
}
module.exports = {
isBuffer,
isEncoding,
alloc,
allocUnsafe,
allocUnsafeSlow,
byteLength,
compare,
concat,
copy,
equals,
fill,
from,
includes,
indexOf,
lastIndexOf,
swap16,
swap32,
swap64,
toBuffer,
toString,
write,
readDoubleBE,
readDoubleLE,
readFloatBE,
readFloatLE,
readInt32BE,
readInt32LE,
readUInt32BE,
readUInt32LE,
writeDoubleBE,
writeDoubleLE,
writeFloatBE,
writeFloatLE,
writeInt32BE,
writeInt32LE,
writeUInt32BE,
writeUInt32LE
};
}
});
// ../../node_modules/bare-os/binding.js
var require_binding = __commonJS({
"../../node_modules/bare-os/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-os/lib/errors.js
var require_errors2 = __commonJS({
"../../node_modules/bare-os/lib/errors.js"(exports, module) {
module.exports = class OSError extends Error {
constructor(msg, code, fn = OSError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "OSError";
}
static UNKNOWN_SIGNAL(msg) {
return new OSError(msg, "UNKNOWN_SIGNAL", OSError.UNKNOWN_SIGNAL);
}
static TITLE_OVERFLOW(msg) {
return new OSError(msg, "TITLE_OVERFLOW", OSError.TITLE_OVERFLOW);
}
};
}
});
// ../../node_modules/bare-os/lib/constants.js
var require_constants = __commonJS({
"../../node_modules/bare-os/lib/constants.js"(exports, module) {
var binding = require_binding();
module.exports = {
signals: binding.signals,
errnos: binding.errnos,
priority: binding.priority
};
}
});
// ../../node_modules/bare-os/index.js
var require_bare_os = __commonJS({
"../../node_modules/bare-os/index.js"(exports) {
var binding = require_binding();
var errors = require_errors2();
var constants = require_constants();
exports.constants = constants;
exports.EOL = binding.platform === "win32" ? "\r\n" : "\n";
exports.devNull = binding.platform === "win32" ? "\\\\.\\nul" : "/dev/null";
exports.platform = function platform() {
return binding.platform;
};
exports.arch = function arch() {
return binding.arch;
};
exports.type = binding.type;
exports.version = binding.version;
exports.release = binding.release;
exports.machine = binding.machine;
exports.execPath = binding.execPath;
exports.pid = binding.pid;
exports.ppid = binding.ppid;
exports.cwd = binding.cwd;
exports.chdir = binding.chdir;
exports.tmpdir = binding.tmpdir;
exports.homedir = binding.homedir;
exports.hostname = binding.hostname;
exports.userInfo = binding.userInfo;
exports.networkInterfaces = function networkInterfaces() {
const result = {};
for (const entry of binding.networkInterfaces()) {
const { name, ...properties } = entry;
if (result[name]) result[name].push(properties);
else result[name] = [properties];
}
return result;
};
exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
if (typeof signal === "string") {
if (signal in constants.signals === false) {
throw errors.UNKNOWN_SIGNAL("Unknown signal: " + signal);
}
signal = constants.signals[signal];
}
binding.kill(pid, signal);
};
exports.endianness = function endianness() {
return binding.isLittleEndian ? "LE" : "BE";
};
exports.availableParallelism = binding.availableParallelism;
exports.cpuUsage = function cpuUsage(previous) {
const current = binding.cpuUsage();
if (previous) {
return {
user: current.user - previous.user,
system: current.system - previous.system
};
}
return current;
};
exports.threadCpuUsage = function threadCpuUsage(previous) {
const current = binding.threadCpuUsage();
if (previous) {
return {
user: current.user - previous.user,
system: current.system - previous.system
};
}
return current;
};
exports.resourceUsage = binding.resourceUsage;
exports.memoryUsage = binding.memoryUsage;
exports.freemem = binding.freemem;
exports.totalmem = binding.totalmem;
exports.availableMemory = binding.availableMemory;
exports.constrainedMemory = binding.constrainedMemory;
exports.uptime = binding.uptime;
exports.loadavg = binding.loadavg;
exports.cpus = binding.cpus;
exports.getProcessTitle = binding.getProcessTitle;
exports.setProcessTitle = function setProcessTitle(title) {
if (typeof title !== "string") title = title.toString();
if (title.length >= 256) {
throw errors.TITLE_OVERFLOW("Process title is too long");
}
binding.setProcessTitle(title);
};
exports.getPriority = function getPriority(pid = 0) {
return binding.getPriority(pid);
};
exports.setPriority = function setPriority(pid, priority) {
if (priority === void 0) {
priority = pid;
pid = 0;
}
binding.setPriority(pid, priority);
};
exports.getEnvKeys = binding.getEnvKeys;
exports.getEnv = binding.getEnv;
exports.hasEnv = binding.hasEnv;
exports.setEnv = binding.setEnv;
exports.unsetEnv = binding.unsetEnv;
}
});
// ../../node_modules/bare-path/lib/constants.js
var require_constants2 = __commonJS({
"../../node_modules/bare-path/lib/constants.js"(exports, module) {
module.exports = {
CHAR_UPPERCASE_A: 65,
CHAR_LOWERCASE_A: 97,
CHAR_UPPERCASE_Z: 90,
CHAR_LOWERCASE_Z: 122,
CHAR_DOT: 46,
CHAR_FORWARD_SLASH: 47,
CHAR_BACKWARD_SLASH: 92,
CHAR_COLON: 58,
CHAR_QUESTION_MARK: 63
};
}
});
// ../../node_modules/bare-path/lib/shared.js
var require_shared = __commonJS({
"../../node_modules/bare-path/lib/shared.js"(exports) {
var {
CHAR_DOT,
CHAR_FORWARD_SLASH
} = require_constants2();
exports.normalizeString = function normalizeString(path, allowAboveRoot, separator, isPathSeparator) {
let res = "";
let lastSegmentLength = 0;
let lastSlash = -1;
let dots = 0;
let code = 0;
for (let i = 0; i <= path.length; ++i) {
if (i < path.length) {
code = path.charCodeAt(i);
} else if (isPathSeparator(code)) {
break;
} else {
code = CHAR_FORWARD_SLASH;
}
if (isPathSeparator(code)) {
if (lastSlash === i - 1 || dots === 1) ;
else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
if (res.length > 2) {
const lastSlashIndex = res.lastIndexOf(separator);
if (lastSlashIndex === -1) {
res = "";
lastSegmentLength = 0;
} else {
res = res.substring(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
}
lastSlash = i;
dots = 0;
continue;
} else if (res.length !== 0) {
res = "";
lastSegmentLength = 0;
lastSlash = i;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += res.length > 0 ? `${separator}..` : "..";
lastSegmentLength = 2;
}
} else {
if (res.length > 0) {
res += `${separator}${path.substring(lastSlash + 1, i)}`;
} else {
res = path.substring(lastSlash + 1, i);
}
lastSegmentLength = i - lastSlash - 1;
}
lastSlash = i;
dots = 0;
} else if (code === CHAR_DOT && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
};
}
});
// ../../node_modules/bare-path/lib/posix.js
var require_posix = __commonJS({
"../../node_modules/bare-path/lib/posix.js"(exports) {
var os = require_bare_os();
var { normalizeString } = require_shared();
var {
CHAR_DOT,
CHAR_FORWARD_SLASH
} = require_constants2();
function isPosixPathSeparator(code) {
return code === CHAR_FORWARD_SLASH;
}
exports.win32 = require_win32();
exports.posix = exports;
exports.sep = "/";
exports.delimiter = ":";
exports.resolve = function resolve(...args) {
let resolvedPath = "";
let resolvedAbsolute = false;
for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
const path = i >= 0 ? args[i] : os.cwd();
if (path.length === 0) {
continue;
}
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
}
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator);
if (resolvedAbsolute) {
return `/${resolvedPath}`;
}
return resolvedPath.length > 0 ? resolvedPath : ".";
};
exports.normalize = function normalize(path) {
if (path.length === 0) return ".";
const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH;
path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator);
if (path.length === 0) {
if (isAbsolute) return "/";
return trailingSeparator ? "./" : ".";
}
if (trailingSeparator) path += "/";
return isAbsolute ? `/${path}` : path;
};
exports.isAbsolute = function isAbsolute(path) {
return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH;
};
exports.join = function join(...args) {
if (args.length === 0) return ".";
let joined;
for (let i = 0; i < args.length; ++i) {
const arg = args[i];
if (arg.length > 0) {
if (joined === void 0) joined = arg;
else joined += `/${arg}`;
}
}
if (joined === void 0) return ".";
return exports.normalize(joined);
};
exports.relative = function relative(from, to) {
if (from === to) return "";
from = exports.resolve(from);
to = exports.resolve(to);
if (from === to) return "";
const fromStart = 1;
const fromEnd = from.length;
const fromLen = fromEnd - fromStart;
const toStart = 1;
const toLen = to.length - toStart;
const length = fromLen < toLen ? fromLen : toLen;
let lastCommonSep = -1;
let i = 0;
for (; i < length; i++) {
const fromCode = from.charCodeAt(fromStart + i);
if (fromCode !== to.charCodeAt(toStart + i)) {
break;
} else if (fromCode === CHAR_FORWARD_SLASH) {
lastCommonSep = i;
}
}
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
return to.substring(toStart + i + 1);
}
if (i === 0) {
return to.substring(toStart + i);
}
} else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
lastCommonSep = i;
} else if (i === 0) {
lastCommonSep = 0;
}
}
}
let out = "";
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
out += out.length === 0 ? ".." : "/..";
}
}
return `${out}${to.substring(toStart + lastCommonSep)}`;
};
exports.toNamespacedPath = function toNamespacedPath(path) {
return path;
};
exports.dirname = function dirname(path) {
if (path.length === 0) return ".";
const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
let end = -1;
let matchedSlash = true;
for (let i = path.length - 1; i >= 1; --i) {
if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
end = i;
break;
}
} else {
matchedSlash = false;
}
}
if (end === -1) return hasRoot ? "/" : ".";
if (hasRoot && end === 1) return "//";
return path.substring(0, end);
};
exports.basename = function basename(path, suffix) {
let start = 0;
let end = -1;
let matchedSlash = true;
if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) {
if (suffix === path) {
return "";
}
let extIdx = suffix.length - 1;
let firstNonSlashEnd = -1;
for (let i = path.length - 1; i >= 0; --i) {
const code = path.charCodeAt(i);
if (code === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
start = i + 1;
break;
}
} else {
if (firstNonSlashEnd === -1) {
matchedSlash = false;
firstNonSlashEnd = i + 1;
}
if (extIdx >= 0) {
if (code === suffix.charCodeAt(extIdx)) {
if (--extIdx === -1) {
end = i;
}
} else {
extIdx = -1;
end = firstNonSlashEnd;
}
}
}
}
if (start === end) end = firstNonSlashEnd;
else if (end === -1) end = path.length;
return path.substring(start, end);
}
for (let i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return "";
return path.substring(start, end);
};
exports.extname = function extname(path) {
let startDot = -1;
let startPart = 0;
let end = -1;
let matchedSlash = true;
let preDotState = 0;
for (let i = path.length - 1; i >= 0; --i) {
const code = path.charCodeAt(i);
if (code === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
matchedSlash = false;
end = i + 1;
}
if (code === CHAR_DOT) {
if (startDot === -1) startDot = i;
else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
preDotState = -1;
}
}
if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
return "";
}
return path.substring(startDot, end);
};
}
});
// ../../node_modules/bare-path/lib/win32.js
var require_win32 = __commonJS({
"../../node_modules/bare-path/lib/win32.js"(exports) {
var os = require_bare_os();
var { normalizeString } = require_shared();
var {
CHAR_UPPERCASE_A,
CHAR_LOWERCASE_A,
CHAR_UPPERCASE_Z,
CHAR_LOWERCASE_Z,
CHAR_DOT,
CHAR_FORWARD_SLASH,
CHAR_BACKWARD_SLASH,
CHAR_COLON,
CHAR_QUESTION_MARK
} = require_constants2();
function isWindowsPathSeparator(code) {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
}
function isWindowsDeviceRoot(code) {
return code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z || code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z;
}
exports.posix = require_posix();
exports.win32 = exports;
exports.sep = "\\";
exports.delimiter = ";";
exports.resolve = function resolve(...args) {
let resolvedDevice = "";
let resolvedTail = "";
let resolvedAbsolute = false;
for (let i = args.length - 1; i >= -1; i--) {
let path;
if (i >= 0) {
path = args[i];
if (path.length === 0) continue;
} else if (resolvedDevice.length === 0) {
path = os.cwd();
} else {
path = os.getEnv(`=${resolvedDevice}`) || os.cwd();
if (path === void 0 || path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
path = `${resolvedDevice}\\`;
}
}
const len = path.length;
let rootEnd = 0;
let device = "";
let isAbsolute = false;
const code = path.charCodeAt(0);
if (len === 1) {
if (isWindowsPathSeparator(code)) {
rootEnd = 1;
isAbsolute = true;
}
} else if (isWindowsPathSeparator(code)) {
isAbsolute = true;
if (isWindowsPathSeparator(path.charCodeAt(1))) {
let j = 2;
let last = j;
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j < len && j !== last) {
const firstPart = path.substring(last, j);
last = j;
while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j < len && j !== last) {
last = j;
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j === len || j !== last) {
device = `\\\\${firstPart}\\${path.substring(last, j)}`;
rootEnd = j;
}
}
}
} else {
rootEnd = 1;
}
} else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
device = path.substring(0, 2);
rootEnd = 2;
if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
isAbsolute = true;
rootEnd = 3;
}
}
if (device.length > 0) {
if (resolvedDevice.length > 0) {
if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
continue;
}
} else {
resolvedDevice = device;
}
}
if (resolvedAbsolute) {
if (resolvedDevice.length > 0) {
break;
}
} else {
resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`;
resolvedAbsolute = isAbsolute;
if (isAbsolute && resolvedDevice.length > 0) {
break;
}
}
}
resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isWindowsPathSeparator);
return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || ".";
};
exports.normalize = function normalize(path) {
const len = path.length;
if (len === 0) return ".";
let rootEnd = 0;
let device;
let isAbsolute = false;
const code = path.charCodeAt(0);
if (len === 1) {
return code === CHAR_FORWARD_SLASH ? "\\" : path;
}
if (isWindowsPathSeparator(code)) {
isAbsolute = true;
if (isWindowsPathSeparator(path.charCodeAt(1))) {
let j = 2;
let last = j;
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j < len && j !== last) {
const firstPart = path.substring(last, j);
last = j;
while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j < len && j !== last) {
last = j;
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j === len) {
return `\\\\${firstPart}\\${path.substring(last)}\\`;
}
if (j !== last) {
device = `\\\\${firstPart}\\${path.substring(last, j)}`;
rootEnd = j;
}
}
}
} else {
rootEnd = 1;
}
} else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
device = path.substring(0, 2);
rootEnd = 2;
if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
isAbsolute = true;
rootEnd = 3;
}
}
let tail = rootEnd < len ? normalizeString(path.substring(rootEnd), !isAbsolute, "\\", isWindowsPathSeparator) : "";
if (tail.length === 0 && !isAbsolute) {
tail = ".";
}
if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
tail += "\\";
}
if (device === void 0) {
return isAbsolute ? `\\${tail}` : tail;
}
return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`;
};
exports.isAbsolute = function isAbsolute(path) {
const len = path.length;
if (len === 0) return false;
const code = path.charCodeAt(0);
return isWindowsPathSeparator(code) || len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isWindowsPathSeparator(path.charCodeAt(2));
};
exports.join = function join(...args) {
if (args.length === 0) return ".";
let joined;
let firstPart;
for (let i = 0; i < args.length; ++i) {
const arg = args[i];
if (arg.length > 0) {
if (joined === void 0) joined = firstPart = arg;
else joined += `\\${arg}`;
}
}
if (joined === void 0) return ".";
let needsReplace = true;
let slashCount = 0;
if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
++slashCount;
const firstLen = firstPart.length;
if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
++slashCount;
if (firstLen > 2) {
if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
++slashCount;
} else {
needsReplace = false;
}
}
}
}
if (needsReplace) {
while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
slashCount++;
}
if (slashCount >= 2) {
joined = `\\${joined.substring(slashCount)}`;
}
}
return exports.normalize(joined);
};
exports.relative = function relative(from, to) {
if (from === to) return "";
const fromOrig = exports.resolve(from);
const toOrig = exports.resolve(to);
if (fromOrig === toOrig) return "";
from = fromOrig.toLowerCase();
to = toOrig.toLowerCase();
if (from === to) return "";
let fromStart = 0;
while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
fromStart++;
}
let fromEnd = from.length;
while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
fromEnd--;
}
const fromLen = fromEnd - fromStart;
let toStart = 0;
while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
toStart++;
}
let toEnd = to.length;
while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
toEnd--;
}
const toLen = toEnd - toStart;
const length = fromLen < toLen ? fromLen : toLen;
let lastCommonSep = -1;
let i = 0;
for (; i < length; i++) {
const fromCode = from.charCodeAt(fromStart + i);
if (fromCode !== to.charCodeAt(toStart + i)) {
break;
} else if (fromCode === CHAR_BACKWARD_SLASH) {
lastCommonSep = i;
}
}
if (i !== length) {
if (lastCommonSep === -1) return toOrig;
} else {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
return toOrig.substring(toStart + i + 1);
}
if (i === 2) {
return toOrig.substring(toStart + i);
}
}
if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
lastCommonSep = i;
} else if (i === 2) {
lastCommonSep = 3;
}
}
if (lastCommonSep === -1) lastCommonSep = 0;
}
let out = "";
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
out += out.length === 0 ? ".." : "\\..";
}
}
toStart += lastCommonSep;
if (out.length > 0) {
return `${out}${toOrig.substring(toStart, toEnd)}`;
}
if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
++toStart;
}
return toOrig.substring(toStart, toEnd);
};
exports.toNamespacedPath = function toNamespacedPath(path) {
if (path.length === 0) return path;
const resolvedPath = exports.resolve(path);
if (resolvedPath.length <= 2) return path;
if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
const code = resolvedPath.charCodeAt(2);
if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
return `\\\\?\\UNC\\${resolvedPath.substring(2)}`;
}
}
} else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) && resolvedPath.charCodeAt(1) === CHAR_COLON && resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
return `\\\\?\\${resolvedPath}`;
}
return path;
};
exports.dirname = function dirname(path) {
const len = path.length;
if (len === 0) return ".";
let rootEnd = -1;
let offset = 0;
const code = path.charCodeAt(0);
if (len === 1) {
return isWindowsPathSeparator(code) ? path : ".";
}
if (isWindowsPathSeparator(code)) {
rootEnd = offset = 1;
if (isWindowsPathSeparator(path.charCodeAt(1))) {
let j = 2;
let last = j;
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j < len && j !== last) {
last = j;
while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j < len && j !== last) {
last = j;
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++;
}
if (j === len) {
return path;
}
if (j !== last) {
rootEnd = offset = j + 1;
}
}
}
}
} else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2;
offset = rootEnd;
}
let end = -1;
let matchedSlash = true;
for (let i = len - 1; i >= offset; --i) {
if (isWindowsPathSeparator(path.charCodeAt(i))) {
if (!matchedSlash) {
end = i;
break;
}
} else {
matchedSlash = false;
}
}
if (end === -1) {
if (rootEnd === -1) return ".";
end = rootEnd;
}
return path.substring(0, end);
};
exports.basename = function basename(path, suffix) {
let start = 0;
let end = -1;
let matchedSlash = true;
if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) {
start = 2;
}
if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) {
if (suffix === path) return "";
let extIdx = suffix.length - 1;
let firstNonSlashEnd = -1;
for (let i = path.length - 1; i >= start; --i) {
const code = path.charCodeAt(i);
if (isWindowsPathSeparator(code)) {
if (!matchedSlash) {
start = i + 1;
break;
}
} else {
if (firstNonSlashEnd === -1) {
matchedSlash = false;
firstNonSlashEnd = i + 1;
}
if (extIdx >= 0) {
if (code === suffix.charCodeAt(extIdx)) {
if (--extIdx === -1) {
end = i;
}
} else {
extIdx = -1;
end = firstNonSlashEnd;
}
}
}
}
if (start === end) end = firstNonSlashEnd;
else if (end === -1) end = path.length;
return path.substring(start, end);
}
for (let i = path.length - 1; i >= start; --i) {
if (isWindowsPathSeparator(path.charCodeAt(i))) {
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return "";
return path.substring(start, end);
};
exports.extname = function extname(path) {
let start = 0;
let startDot = -1;
let startPart = 0;
let end = -1;
let matchedSlash = true;
let preDotState = 0;
if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) {
start = startPart = 2;
}
for (let i = path.length - 1; i >= start; --i) {
const code = path.charCodeAt(i);
if (isWindowsPathSeparator(code)) {
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
matchedSlash = false;
end = i + 1;
}
if (code === CHAR_DOT) {
if (startDot === -1) startDot = i;
else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
preDotState = -1;
}
}
if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
return "";
}
return path.substring(startDot, end);
};
}
});
// ../../node_modules/bare-path/index.js
var require_bare_path = __commonJS({
"../../node_modules/bare-path/index.js"(exports, module) {
if (Bare.platform === "win32") {
module.exports = require_win32();
} else {
module.exports = require_posix();
}
}
});
// ../../node_modules/bare-url/binding.js
var require_binding2 = __commonJS({
"../../node_modules/bare-url/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-url/lib/errors.js
var require_errors3 = __commonJS({
"../../node_modules/bare-url/lib/errors.js"(exports, module) {
module.exports = class URLError extends Error {
constructor(msg, fn = URLError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) Error.captureStackTrace(this, fn);
}
get name() {
return "URLError";
}
static INVALID_URL(msg, input) {
const err = new URLError(msg, URLError.INVALID_URL);
err.input = input;
return err;
}
static INVALID_URL_SCHEME(msg = "Invalid URL") {
return new URLError(msg, URLError.INVALID_URL_SCHEME);
}
static INVALID_FILE_URL_HOST(msg = "Invalid file: URL host") {
return new URLError(msg, URLError.INVALID_FILE_URL_HOST);
}
static INVALID_FILE_URL_PATH(msg = "Invalid file: URL path") {
return new URLError(msg, URLError.INVALID_FILE_URL_PATH);
}
};
}
});
// ../../node_modules/bare-url/lib/url-search-params.js
var require_url_search_params = __commonJS({
"../../node_modules/bare-url/lib/url-search-params.js"(exports, module) {
var kind = Symbol.for("bare.url.search-params.kind");
var URLSearchParams = class _URLSearchParams {
static _urls = /* @__PURE__ */ new WeakMap();
static get [kind]() {
return 0;
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
constructor(init, url = null) {
this._params = /* @__PURE__ */ new Map();
if (url) _URLSearchParams._urls.set(this, url);
if (typeof init === "string") {
this._parse(init);
} else if (init) {
for (const [name, value] of typeof init[Symbol.iterator] === "function" ? init : Object.entries(init)) {
this.append(name, value);
}
}
}
get [kind]() {
return _URLSearchParams[kind];
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-size
get size() {
return this._params.length;
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-append
append(name, value = null) {
if (value === null) return;
let list = this._params.get(name);
if (list === void 0) {
list = [];
this._params.set(name, list);
}
list.push(value);
this._update();
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-delete
delete(name, value = null) {
if (value === null) this._params.delete(name);
else {
let list = this._params.get(name);
if (list === void 0) return;
list = list.filter((found) => found !== value);
if (list.length === 0) this._params.delete(name);
else this._params.set(name, list);
}
this._update();
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-get
get(name) {
const list = this._params.get(name);
if (list === void 0) return null;
return list[0];
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
getAll(name) {
const list = this._params.get(name);
if (list === void 0) return [];
return Array.from(list);
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-has
has(name, value = null) {
const list = this._params.get(name);
if (list === void 0) return false;
if (value === null) return true;
return list.includes(value);
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-set
set(name, value = null) {
if (value === null) this._params.delete(name);
else this._params.set(name, [value]);
this._update();
}
toString() {
return this._serialize();
}
toJSON() {
return [...this];
}
*[Symbol.iterator]() {
for (const [name, values] of this._params) {
for (const value of values) yield [name, value];
}
}
[Symbol.for("bare.inspect")]() {
const object = {
__proto__: { constructor: _URLSearchParams }
};
for (const [name, values] of this._params) {
if (values.length === 1) object[name] = values[0];
else object[name] = values;
}
return object;
}
// https://url.spec.whatwg.org/#concept-urlsearchparams-update
_update() {
const url = _URLSearchParams._urls.get(this);
if (url === void 0) return;
url.search = this._serialize();
}
// https://url.spec.whatwg.org/#concept-urlencoded-parser
_parse(input) {
if (input[0] === "?") input = input.substring(1);
this._params = /* @__PURE__ */ new Map();
for (const sequence of input.split("&")) {
if (sequence.length === 0) continue;
let i = sequence.indexOf("=");
if (i === -1) i = sequence.length;
const name = decodeURIComponent(sequence.substring(0, i));
const value = decodeURIComponent(sequence.substring(i + 1, sequence.length));
let list = this._params.get(name);
if (list === void 0) {
list = [];
this._params.set(name, list);
}
list.push(value);
}
}
// https://url.spec.whatwg.org/#concept-urlencoded-serializer
_serialize() {
let output = "";
for (let [name, values] of this._params) {
name = encodeURIComponent(name);
for (const value of values) {
if (output) output += "&";
output += name + "=" + encodeURIComponent(value);
}
}
return output;
}
};
module.exports = exports = URLSearchParams;
exports.isURLSearchParams = function isURLSearchParams(value) {
if (value instanceof URLSearchParams) return true;
return typeof value === "object" && value !== null && value[kind] === URLSearchParams[kind];
};
}
});
// ../../node_modules/bare-url/index.js
var require_bare_url = __commonJS({
"../../node_modules/bare-url/index.js"(exports, module) {
var path = require_bare_path();
var binding = require_binding2();
var errors = require_errors3();
var URLSearchParams = require_url_search_params();
var kind = Symbol.for("bare.url.kind");
var isWindows = Bare.platform === "win32";
var URL2 = class _URL {
static get [kind]() {
return 0;
}
constructor(input, base, opts = {}) {
if (arguments.length === 0) throw errors.INVALID_URL();
input = String(input);
if (base !== void 0) base = String(base);
this._components = new Uint32Array(8);
this._parse(input, base, opts.throw !== false);
if (this._href) this._params = new URLSearchParams(this.search, this);
}
get [kind]() {
return _URL[kind];
}
// https://url.spec.whatwg.org/#dom-url-href
get href() {
return this._href;
}
set href(value) {
this._update(value);
this._params._parse(this.search);
}
// https://url.spec.whatwg.org/#dom-url-protocol
get protocol() {
return this._slice(0, this._components[0]) + ":";
}
set protocol(value) {
this._update(this._replace(value.replace(/:+$/, ""), 0, this._components[0]));
}
// https://url.spec.whatwg.org/#dom-url-username
get username() {
return this._slice(this._components[0] + 3, this._components[1]);
}
set username(value) {
if (cannotHaveCredentialsOrPort(this)) {
return;
}
if (this.username === "") value += "@";
this._update(this._replace(value, this._components[0] + 3, this._components[1]));
}
// https://url.spec.whatwg.org/#dom-url-password
get password() {
return this._href.slice(
this._components[1] + 1,
this._components[2] - 1
/* @ */
);
}
set password(value) {
if (cannotHaveCredentialsOrPort(this)) {
return;
}
let start = this._components[1] + 1;
let end = this._components[2] - 1;
if (this.password === "") {
value = ":" + value;
start--;
}
if (this.username === "") {
value += "@";
end++;
}
this._update(this._replace(value, start, end));
}
// https://url.spec.whatwg.org/#dom-url-host
get host() {
return this._slice(this._components[2], this._components[5]);
}
set host(value) {
if (hasOpaquePath(this)) {
return;
}
this._update(
this._replace(value, this._components[2], this._components[value.includes(":") ? 5 : 3])
);
}
// https://url.spec.whatwg.org/#dom-url-hostname
get hostname() {
return this._slice(this._components[2], this._components[3]);
}
set hostname(value) {
if (hasOpaquePath(this)) {
return;
}
this._update(this._replace(value, this._components[2], this._components[3]));
}
// https://url.spec.whatwg.org/#dom-url-port
get port() {
return this._slice(this._components[3] + 1, this._components[5]);
}
set port(value) {
if (cannotHaveCredentialsOrPort(this)) {
return;
}
let start = this._components[3] + 1;
if (this.port === "") {
value = ":" + value;
start--;
}
this._update(this._replace(value, start, this._components[5]));
}
// https://url.spec.whatwg.org/#dom-url-pathname
get pathname() {
return this._slice(
this._components[5],
this._components[6] - 1
/* ? */
);
}
set pathname(value) {
if (hasOpaquePath(this)) {
return;
}
if (value[0] !== "/" && value[0] !== "\\") {
value = "/" + value;
}
this._update(this._replace(
value,
this._components[5],
this._components[6] - 1
/* ? */
));
}
// https://url.spec.whatwg.org/#dom-url-search
get search() {
return this._slice(
this._components[6] - 1,
this._components[7] - 1
/* # */
);
}
set search(value) {
if (value && value[0] !== "?") value = "?" + value;
this._update(
this._replace(
value,
this._components[6] - 1,
this._components[7] - 1
/* # */
)
);
this._params._parse(this.search);
}
// https://url.spec.whatwg.org/#dom-url-searchparams
get searchParams() {
return this._params;
}
// https://url.spec.whatwg.org/#dom-url-hash
get hash() {
return this._slice(
this._components[7] - 1
/* # */
);
}
set hash(value) {
if (value && value[0] !== "#") value = "#" + value;
this._update(this._replace(
value,
this._components[7] - 1
/* # */
));
}
toString() {
return this._href;
}
toJSON() {
return this._href;
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: _URL },
href: this.href,
protocol: this.protocol,
username: this.username,
password: this.password,
host: this.host,
hostname: this.hostname,
port: this.port,
pathname: this.pathname,
search: this.search,
searchParams: this.searchParams,
hash: this.hash
};
}
_slice(start, end = this._href.length) {
return this._href.slice(start, end);
}
_replace(replacement, start, end = this._href.length) {
return this._slice(0, start) + replacement + this._slice(end);
}
_parse(input, base, shouldThrow) {
try {
this._href = binding.parse(
String(input),
base ? String(base) : null,
this._components,
shouldThrow
);
} catch (err) {
if (err instanceof TypeError) throw err;
throw errors.INVALID_URL(`Invalid URL '${input}'`, input);
}
}
_update(input) {
try {
this._parse(input, null, true);
} catch (err) {
if (err instanceof TypeError) throw err;
}
}
};
module.exports = exports = URL2;
function hasOpaquePath(url) {
return url.pathname[0] !== "/";
}
function cannotHaveCredentialsOrPort(url) {
return url.hostname === "" || url.protocol === "file:";
}
exports.URL = URL2;
exports.URLSearchParams = URLSearchParams;
exports.errors = errors;
exports.isURL = function isURL(value) {
if (value instanceof URL2) return true;
return typeof value === "object" && value !== null && value[kind] === URL2[kind];
};
exports.isURLSearchParams = URLSearchParams.isURLSearchParams;
exports.parse = function parse(input, base) {
const url = new URL2(input, base, { throw: false });
return url._href ? url : null;
};
exports.canParse = function canParse(input, base) {
return binding.canParse(String(input), base ? String(base) : null);
};
exports.fileURLToPath = function fileURLToPath(url) {
if (typeof url === "string") {
url = new URL2(url);
}
if (url.protocol !== "file:") {
throw errors.INVALID_URL_SCHEME("The URL must use the file: protocol");
}
if (isWindows) {
if (/%2f|%5c/i.test(url.pathname)) {
throw errors.INVALID_FILE_URL_PATH(
"The file: URL path must not include encoded \\ or / characters"
);
}
} else {
if (url.hostname) {
throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty");
}
if (/%2f/i.test(url.pathname)) {
throw errors.INVALID_FILE_URL_PATH("The file: URL path must not include encoded / characters");
}
}
const pathname = path.normalize(decodeURIComponent(url.pathname));
if (isWindows) {
if (url.hostname) return "\\\\" + url.hostname + pathname;
const letter = pathname.charCodeAt(1) | 32;
if (letter < 97 || letter > 122 || pathname.charCodeAt(2) !== 58) {
throw errors.INVALID_FILE_URL_PATH("The file: URL path must be absolute");
}
return pathname.slice(1);
}
return pathname;
};
exports.pathToFileURL = function pathToFileURL(pathname) {
let resolved = path.resolve(pathname);
if (pathname[pathname.length - 1] === "/") {
resolved += "/";
} else if (isWindows && pathname[pathname.length - 1] === "\\") {
resolved += "\\";
}
resolved = resolved.replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("?", "%3f").replaceAll("\n", "%0a").replaceAll("\r", "%0d").replaceAll(" ", "%09");
if (!isWindows) {
resolved = resolved.replaceAll("\\", "%5c");
}
return new URL2("file:" + resolved);
};
exports.format = function format(parts) {
const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts;
let result = "";
if (typeof protocol === "string") {
result += protocol;
if (protocol[protocol.length - 1] !== ":") {
result += ":";
}
if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) {
result += "//";
}
}
if (typeof auth === "string") {
if (host || hostname) result += auth + "@";
}
if (typeof host === "string") result += host;
else {
result += hostname;
if (port) result += ":" + port;
}
if (typeof pathname === "string" && pathname !== "") {
if (pathname[0] !== "/") result += "/";
result += pathname;
}
if (typeof search === "string") {
if (search[0] !== "?") result += "?";
result += search;
} else if (typeof query === "object" && query !== null) {
result += "?" + new URLSearchParams(query);
}
if (typeof hash === "string") {
if (hash[0] !== "#") result += "#";
result += hash;
}
return result;
};
}
});
// ../../node_modules/fast-fifo/fixed-size.js
var require_fixed_size = __commonJS({
"../../node_modules/fast-fifo/fixed-size.js"(exports, module) {
module.exports = class FixedFIFO {
constructor(hwm) {
if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) throw new Error("Max size for a FixedFIFO should be a power of two");
this.buffer = new Array(hwm);
this.mask = hwm - 1;
this.top = 0;
this.btm = 0;
this.next = null;
}
clear() {
this.top = this.btm = 0;
this.next = null;
this.buffer.fill(void 0);
}
push(data) {
if (this.buffer[this.top] !== void 0) return false;
this.buffer[this.top] = data;
this.top = this.top + 1 & this.mask;
return true;
}
shift() {
const last = this.buffer[this.btm];
if (last === void 0) return void 0;
this.buffer[this.btm] = void 0;
this.btm = this.btm + 1 & this.mask;
return last;
}
peek() {
return this.buffer[this.btm];
}
isEmpty() {
return this.buffer[this.btm] === void 0;
}
};
}
});
// ../../node_modules/fast-fifo/index.js
var require_fast_fifo = __commonJS({
"../../node_modules/fast-fifo/index.js"(exports, module) {
var FixedFIFO = require_fixed_size();
module.exports = class FastFIFO {
constructor(hwm) {
this.hwm = hwm || 16;
this.head = new FixedFIFO(this.hwm);
this.tail = this.head;
this.length = 0;
}
clear() {
this.head = this.tail;
this.head.clear();
this.length = 0;
}
push(val) {
this.length++;
if (!this.head.push(val)) {
const prev = this.head;
this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);
this.head.push(val);
}
}
shift() {
if (this.length !== 0) this.length--;
const val = this.tail.shift();
if (val === void 0 && this.tail.next) {
const next = this.tail.next;
this.tail.next = null;
this.tail = next;
return this.tail.shift();
}
return val;
}
peek() {
const val = this.tail.peek();
if (val === void 0 && this.tail.next) return this.tail.next.peek();
return val;
}
isEmpty() {
return this.length === 0;
}
};
}
});
// ../../node_modules/events-universal/default.js
var require_default = __commonJS({
"../../node_modules/events-universal/default.js"(exports, module) {
module.exports = require_bare_node_events();
}
});
// ../../node_modules/text-decoder/lib/pass-through-decoder.js
var require_pass_through_decoder = __commonJS({
"../../node_modules/text-decoder/lib/pass-through-decoder.js"(exports, module) {
var b4a = require_b4a();
module.exports = class PassThroughDecoder {
constructor(encoding) {
this.encoding = encoding;
}
get remaining() {
return 0;
}
decode(data) {
return b4a.toString(data, this.encoding);
}
flush() {
return "";
}
};
}
});
// ../../node_modules/text-decoder/lib/utf8-decoder.js
var require_utf8_decoder = __commonJS({
"../../node_modules/text-decoder/lib/utf8-decoder.js"(exports, module) {
var b4a = require_b4a();
module.exports = class UTF8Decoder {
constructor() {
this._reset();
}
get remaining() {
return this.bytesSeen;
}
decode(data) {
if (data.byteLength === 0) return "";
if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {
this.bytesSeen = trailingBytesSeen(data);
return b4a.toString(data, "utf8");
}
let result = "";
let start = 0;
if (this.bytesNeeded > 0) {
while (start < data.byteLength) {
const byte = data[start];
if (byte < this.lowerBoundary || byte > this.upperBoundary) {
result += "\uFFFD";
this._reset();
break;
}
this.lowerBoundary = 128;
this.upperBoundary = 191;
this.codePoint = this.codePoint << 6 | byte & 63;
this.bytesSeen++;
start++;
if (this.bytesSeen === this.bytesNeeded) {
result += String.fromCodePoint(this.codePoint);
this._reset();
break;
}
}
if (this.bytesNeeded > 0) return result;
}
const trailing = trailingIncomplete(data, start);
const end = data.byteLength - trailing;
if (end > start) result += b4a.toString(data, "utf8", start, end);
for (let i = end; i < data.byteLength; i++) {
const byte = data[i];
if (this.bytesNeeded === 0) {
if (byte <= 127) {
this.bytesSeen = 0;
result += String.fromCharCode(byte);
} else if (byte >= 194 && byte <= 223) {
this.bytesNeeded = 2;
this.bytesSeen = 1;
this.codePoint = byte & 31;
} else if (byte >= 224 && byte <= 239) {
if (byte === 224) this.lowerBoundary = 160;
else if (byte === 237) this.upperBoundary = 159;
this.bytesNeeded = 3;
this.bytesSeen = 1;
this.codePoint = byte & 15;
} else if (byte >= 240 && byte <= 244) {
if (byte === 240) this.lowerBoundary = 144;
else if (byte === 244) this.upperBoundary = 143;
this.bytesNeeded = 4;
this.bytesSeen = 1;
this.codePoint = byte & 7;
} else {
this.bytesSeen = 1;
result += "\uFFFD";
}
continue;
}
if (byte < this.lowerBoundary || byte > this.upperBoundary) {
result += "\uFFFD";
i--;
this._reset();
continue;
}
this.lowerBoundary = 128;
this.upperBoundary = 191;
this.codePoint = this.codePoint << 6 | byte & 63;
this.bytesSeen++;
if (this.bytesSeen === this.bytesNeeded) {
result += String.fromCodePoint(this.codePoint);
this._reset();
}
}
return result;
}
flush() {
const result = this.bytesNeeded > 0 ? "\uFFFD" : "";
this._reset();
return result;
}
_reset() {
this.codePoint = 0;
this.bytesNeeded = 0;
this.bytesSeen = 0;
this.lowerBoundary = 128;
this.upperBoundary = 191;
}
};
function trailingIncomplete(data, start) {
const len = data.byteLength;
if (len <= start) return 0;
const limit = Math.max(start, len - 4);
let i = len - 1;
while (i > limit && (data[i] & 192) === 128) i--;
if (i < start) return 0;
const byte = data[i];
let needed;
if (byte <= 127) return 0;
if (byte >= 194 && byte <= 223) needed = 2;
else if (byte >= 224 && byte <= 239) needed = 3;
else if (byte >= 240 && byte <= 244) needed = 4;
else return 0;
const available = len - i;
return available < needed ? available : 0;
}
function trailingBytesSeen(data) {
const len = data.byteLength;
if (len === 0) return 0;
const last = data[len - 1];
if (last <= 127) return 0;
if ((last & 192) !== 128) return 1;
const limit = Math.max(0, len - 4);
let i = len - 2;
while (i >= limit && (data[i] & 192) === 128) i--;
if (i < 0) return 1;
const first = data[i];
let needed;
if (first >= 194 && first <= 223) needed = 2;
else if (first >= 224 && first <= 239) needed = 3;
else if (first >= 240 && first <= 244) needed = 4;
else return 1;
if (len - i !== needed) return 1;
if (needed >= 3) {
const second = data[i + 1];
if (first === 224 && second < 160) return 1;
if (first === 237 && second > 159) return 1;
if (first === 240 && second < 144) return 1;
if (first === 244 && second > 143) return 1;
}
return 0;
}
}
});
// ../../node_modules/text-decoder/index.js
var require_text_decoder = __commonJS({
"../../node_modules/text-decoder/index.js"(exports, module) {
var PassThroughDecoder = require_pass_through_decoder();
var UTF8Decoder = require_utf8_decoder();
module.exports = class TextDecoder {
constructor(encoding = "utf8") {
this.encoding = normalizeEncoding(encoding);
switch (this.encoding) {
case "utf8":
this.decoder = new UTF8Decoder();
break;
case "utf16le":
case "base64":
throw new Error("Unsupported encoding: " + this.encoding);
default:
this.decoder = new PassThroughDecoder(this.encoding);
}
}
get remaining() {
return this.decoder.remaining;
}
push(data) {
if (typeof data === "string") return data;
return this.decoder.decode(data);
}
// For Node.js compatibility
write(data) {
return this.push(data);
}
end(data) {
let result = "";
if (data) result = this.push(data);
result += this.decoder.flush();
return result;
}
};
function normalizeEncoding(encoding) {
encoding = encoding.toLowerCase();
switch (encoding) {
case "utf8":
case "utf-8":
return "utf8";
case "ucs2":
case "ucs-2":
case "utf16le":
case "utf-16le":
return "utf16le";
case "latin1":
case "binary":
return "latin1";
case "base64":
case "ascii":
case "hex":
return encoding;
default:
throw new Error("Unknown encoding: " + encoding);
}
}
}
});
// ../../node_modules/streamx/index.js
var require_streamx = __commonJS({
"../../node_modules/streamx/index.js"(exports, module) {
var { EventEmitter } = require_default();
var STREAM_DESTROYED = new Error("Stream was destroyed");
var PREMATURE_CLOSE = new Error("Premature close");
var FIFO = require_fast_fifo();
var TextDecoder = require_text_decoder();
var qmt = typeof queueMicrotask === "undefined" ? (fn) => global.process.nextTick(fn) : queueMicrotask;
var MAX = (1 << 29) - 1;
var OPENING = 1;
var PREDESTROYING = 2;
var DESTROYING = 4;
var DESTROYED = 8;
var NOT_OPENING = MAX ^ OPENING;
var NOT_PREDESTROYING = MAX ^ PREDESTROYING;
var READ_ACTIVE = 1 << 4;
var READ_UPDATING = 2 << 4;
var READ_PRIMARY = 4 << 4;
var READ_QUEUED = 8 << 4;
var READ_RESUMED = 16 << 4;
var READ_PIPE_DRAINED = 32 << 4;
var READ_ENDING = 64 << 4;
var READ_EMIT_DATA = 128 << 4;
var READ_EMIT_READABLE = 256 << 4;
var READ_EMITTED_READABLE = 512 << 4;
var READ_DONE = 1024 << 4;
var READ_NEXT_TICK = 2048 << 4;
var READ_NEEDS_PUSH = 4096 << 4;
var READ_READ_AHEAD = 8192 << 4;
var READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED;
var READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH;
var READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE;
var READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED;
var READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD;
var READ_NOT_ACTIVE = MAX ^ READ_ACTIVE;
var READ_NON_PRIMARY = MAX ^ READ_PRIMARY;
var READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH);
var READ_PUSHED = MAX ^ READ_NEEDS_PUSH;
var READ_PAUSED = MAX ^ READ_RESUMED;
var READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE);
var READ_NOT_ENDING = MAX ^ READ_ENDING;
var READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING;
var READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK;
var READ_NOT_UPDATING = MAX ^ READ_UPDATING;
var READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD;
var READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD;
var WRITE_ACTIVE = 1 << 18;
var WRITE_UPDATING = 2 << 18;
var WRITE_PRIMARY = 4 << 18;
var WRITE_QUEUED = 8 << 18;
var WRITE_UNDRAINED = 16 << 18;
var WRITE_DONE = 32 << 18;
var WRITE_EMIT_DRAIN = 64 << 18;
var WRITE_NEXT_TICK = 128 << 18;
var WRITE_WRITING = 256 << 18;
var WRITE_FINISHING = 512 << 18;
var WRITE_CORKED = 1024 << 18;
var WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING);
var WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY;
var WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING);
var WRITE_DRAINED = MAX ^ WRITE_UNDRAINED;
var WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED;
var WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK;
var WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING;
var WRITE_NOT_CORKED = MAX ^ WRITE_CORKED;
var ACTIVE = READ_ACTIVE | WRITE_ACTIVE;
var NOT_ACTIVE = MAX ^ ACTIVE;
var DONE = READ_DONE | WRITE_DONE;
var DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING;
var OPEN_STATUS = DESTROY_STATUS | OPENING;
var AUTO_DESTROY = DESTROY_STATUS | DONE;
var NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY;
var ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK;
var TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE;
var IS_OPENING = OPEN_STATUS | TICKING;
var READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE;
var READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED;
var READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED;
var READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE;
var SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD;
var READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE;
var READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY;
var READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING;
var WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE;
var WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED;
var WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE;
var WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE;
var WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED;
var WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE;
var WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING;
var WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE;
var WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE;
var WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY;
var WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS;
var asyncIterator = Symbol.asyncIterator || Symbol("asyncIterator");
var WritableState = class {
constructor(stream, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) {
this.stream = stream;
this.queue = new FIFO();
this.highWaterMark = highWaterMark;
this.buffered = 0;
this.error = null;
this.pipeline = null;
this.drains = null;
this.byteLength = byteLengthWritable || byteLength || defaultByteLength;
this.map = mapWritable || map;
this.afterWrite = afterWrite.bind(this);
this.afterUpdateNextTick = updateWriteNT.bind(this);
}
get ending() {
return (this.stream._duplexState & WRITE_FINISHING) !== 0;
}
get ended() {
return (this.stream._duplexState & WRITE_DONE) !== 0;
}
push(data) {
if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false;
if (this.map !== null) data = this.map(data);
this.buffered += this.byteLength(data);
this.queue.push(data);
if (this.buffered < this.highWaterMark) {
this.stream._duplexState |= WRITE_QUEUED;
return true;
}
this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED;
return false;
}
shift() {
const data = this.queue.shift();
this.buffered -= this.byteLength(data);
if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED;
return data;
}
end(data) {
if (typeof data === "function") this.stream.once("finish", data);
else if (data !== void 0 && data !== null) this.push(data);
this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY;
}
autoBatch(data, cb) {
const buffer = [];
const stream = this.stream;
buffer.push(data);
while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {
buffer.push(stream._writableState.shift());
}
if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null);
stream._writev(buffer, cb);
}
update() {
const stream = this.stream;
stream._duplexState |= WRITE_UPDATING;
do {
while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {
const data = this.shift();
stream._duplexState |= WRITE_ACTIVE_AND_WRITING;
stream._write(data, this.afterWrite);
}
if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
} while (this.continueUpdate() === true);
stream._duplexState &= WRITE_NOT_UPDATING;
}
updateNonPrimary() {
const stream = this.stream;
if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {
stream._duplexState = stream._duplexState | WRITE_ACTIVE;
stream._final(afterFinal.bind(this));
return;
}
if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
stream._duplexState |= ACTIVE;
stream._destroy(afterDestroy.bind(this));
}
return;
}
if ((stream._duplexState & IS_OPENING) === OPENING) {
stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
stream._open(afterOpen.bind(this));
}
}
continueUpdate() {
if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false;
this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
return true;
}
updateCallback() {
if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update();
else this.updateNextTick();
}
updateNextTick() {
if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return;
this.stream._duplexState |= WRITE_NEXT_TICK;
if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick);
}
};
var ReadableState = class {
constructor(stream, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) {
this.stream = stream;
this.queue = new FIFO();
this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark;
this.buffered = 0;
this.readAhead = highWaterMark > 0;
this.error = null;
this.pipeline = null;
this.byteLength = byteLengthReadable || byteLength || defaultByteLength;
this.map = mapReadable || map;
this.pipeTo = null;
this.afterRead = afterRead.bind(this);
this.afterUpdateNextTick = updateReadNT.bind(this);
}
get ending() {
return (this.stream._duplexState & READ_ENDING) !== 0;
}
get ended() {
return (this.stream._duplexState & READ_DONE) !== 0;
}
pipe(pipeTo, cb) {
if (this.pipeTo !== null) throw new Error("Can only pipe to one destination");
if (typeof cb !== "function") cb = null;
this.stream._duplexState |= READ_PIPE_DRAINED;
this.pipeTo = pipeTo;
this.pipeline = new Pipeline(this.stream, pipeTo, cb);
if (cb) this.stream.on("error", noop);
if (isStreamx(pipeTo)) {
pipeTo._writableState.pipeline = this.pipeline;
if (cb) pipeTo.on("error", noop);
pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
} else {
const onerror = this.pipeline.done.bind(this.pipeline, pipeTo);
const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null);
pipeTo.on("error", onerror);
pipeTo.on("close", onclose);
pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline));
}
pipeTo.on("drain", afterDrain.bind(this));
this.stream.emit("piping", pipeTo);
pipeTo.emit("pipe", this.stream);
}
push(data) {
const stream = this.stream;
if (data === null) {
this.highWaterMark = 0;
stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED;
return false;
}
if (this.map !== null) {
data = this.map(data);
if (data === null) {
stream._duplexState &= READ_PUSHED;
return this.buffered < this.highWaterMark;
}
}
this.buffered += this.byteLength(data);
this.queue.push(data);
stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED;
return this.buffered < this.highWaterMark;
}
shift() {
const data = this.queue.shift();
this.buffered -= this.byteLength(data);
if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED;
return data;
}
unshift(data) {
const pending = [this.map !== null ? this.map(data) : data];
while (this.buffered > 0) pending.push(this.shift());
for (let i = 0; i < pending.length - 1; i++) {
const data2 = pending[i];
this.buffered += this.byteLength(data2);
this.queue.push(data2);
}
this.push(pending[pending.length - 1]);
}
read() {
const stream = this.stream;
if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {
const data = this.shift();
if (this.pipeTo !== null && this.pipeTo.write(data) === false)
stream._duplexState &= READ_PIPE_NOT_DRAINED;
if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
return data;
}
if (this.readAhead === false) {
stream._duplexState |= READ_READ_AHEAD;
this.updateNextTick();
}
return null;
}
drain() {
const stream = this.stream;
while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {
const data = this.shift();
if (this.pipeTo !== null && this.pipeTo.write(data) === false)
stream._duplexState &= READ_PIPE_NOT_DRAINED;
if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data);
}
}
update() {
const stream = this.stream;
stream._duplexState |= READ_UPDATING;
do {
this.drain();
while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) {
stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH;
stream._read(this.afterRead);
this.drain();
}
if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {
stream._duplexState |= READ_EMITTED_READABLE;
stream.emit("readable");
}
if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary();
} while (this.continueUpdate() === true);
stream._duplexState &= READ_NOT_UPDATING;
}
updateNonPrimary() {
const stream = this.stream;
if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {
stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING;
stream.emit("end");
if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING;
if (this.pipeTo !== null) this.pipeTo.end();
}
if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {
if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {
stream._duplexState |= ACTIVE;
stream._destroy(afterDestroy.bind(this));
}
return;
}
if ((stream._duplexState & IS_OPENING) === OPENING) {
stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING;
stream._open(afterOpen.bind(this));
}
}
continueUpdate() {
if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false;
this.stream._duplexState &= READ_NOT_NEXT_TICK;
return true;
}
updateCallback() {
if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update();
else this.updateNextTick();
}
updateNextTickIfOpen() {
if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return;
this.stream._duplexState |= READ_NEXT_TICK;
if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick);
}
updateNextTick() {
if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return;
this.stream._duplexState |= READ_NEXT_TICK;
if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick);
}
};
var TransformState = class {
constructor(stream) {
this.data = null;
this.afterTransform = afterTransform.bind(stream);
this.afterFinal = null;
}
};
var Pipeline = class {
constructor(src, dst, cb) {
this.from = src;
this.to = dst;
this.afterPipe = cb;
this.error = null;
this.pipeToFinished = false;
}
finished() {
this.pipeToFinished = true;
}
done(stream, err) {
if (err) this.error = err;
if (stream === this.to) {
this.to = null;
if (this.from !== null) {
if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {
this.from.destroy(this.error || new Error("Writable stream closed prematurely"));
}
return;
}
}
if (stream === this.from) {
this.from = null;
if (this.to !== null) {
if ((stream._duplexState & READ_DONE) === 0) {
this.to.destroy(this.error || new Error("Readable stream closed before ending"));
}
return;
}
}
if (this.afterPipe !== null) this.afterPipe(this.error);
this.to = this.from = this.afterPipe = null;
}
};
function afterDrain() {
this.stream._duplexState |= READ_PIPE_DRAINED;
this.updateCallback();
}
function afterFinal(err) {
const stream = this.stream;
if (err) stream.destroy(err);
if ((stream._duplexState & DESTROY_STATUS) === 0) {
stream._duplexState |= WRITE_DONE;
stream.emit("finish");
}
if ((stream._duplexState & AUTO_DESTROY) === DONE) {
stream._duplexState |= DESTROYING;
}
stream._duplexState &= WRITE_NOT_FINISHING;
if ((stream._duplexState & WRITE_UPDATING) === 0) this.update();
else this.updateNextTick();
}
function afterDestroy(err) {
const stream = this.stream;
if (!err && this.error !== STREAM_DESTROYED) err = this.error;
if (err) stream.emit("error", err);
stream._duplexState |= DESTROYED;
stream.emit("close");
const rs = stream._readableState;
const ws = stream._writableState;
if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err);
if (ws !== null) {
while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false);
if (ws.pipeline !== null) ws.pipeline.done(stream, err);
}
}
function afterWrite(err) {
const stream = this.stream;
if (err) stream.destroy(err);
stream._duplexState &= WRITE_NOT_ACTIVE;
if (this.drains !== null) tickDrains(this.drains);
if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {
stream._duplexState &= WRITE_DRAINED;
if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {
stream.emit("drain");
}
}
this.updateCallback();
}
function afterRead(err) {
if (err) this.stream.destroy(err);
this.stream._duplexState &= READ_NOT_ACTIVE;
if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0)
this.stream._duplexState &= READ_NO_READ_AHEAD;
this.updateCallback();
}
function updateReadNT() {
if ((this.stream._duplexState & READ_UPDATING) === 0) {
this.stream._duplexState &= READ_NOT_NEXT_TICK;
this.update();
}
}
function updateWriteNT() {
if ((this.stream._duplexState & WRITE_UPDATING) === 0) {
this.stream._duplexState &= WRITE_NOT_NEXT_TICK;
this.update();
}
}
function tickDrains(drains) {
for (let i = 0; i < drains.length; i++) {
if (--drains[i].writes === 0) {
drains.shift().resolve(true);
i--;
}
}
}
function afterOpen(err) {
const stream = this.stream;
if (err) stream.destroy(err);
if ((stream._duplexState & DESTROYING) === 0) {
if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY;
if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY;
stream.emit("open");
}
stream._duplexState &= NOT_ACTIVE;
if (stream._writableState !== null) {
stream._writableState.updateCallback();
}
if (stream._readableState !== null) {
stream._readableState.updateCallback();
}
}
function afterTransform(err, data) {
if (data !== void 0 && data !== null) this.push(data);
this._writableState.afterWrite(err);
}
function newListener(name) {
if (this._readableState !== null) {
if (name === "data") {
this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD;
this._readableState.updateNextTick();
}
if (name === "readable") {
this._duplexState |= READ_EMIT_READABLE;
this._readableState.updateNextTick();
}
}
if (this._writableState !== null) {
if (name === "drain") {
this._duplexState |= WRITE_EMIT_DRAIN;
this._writableState.updateNextTick();
}
}
}
var Stream = class extends EventEmitter {
constructor(opts) {
super();
this._duplexState = 0;
this._readableState = null;
this._writableState = null;
if (opts) {
if (opts.open) this._open = opts.open;
if (opts.destroy) this._destroy = opts.destroy;
if (opts.predestroy) this._predestroy = opts.predestroy;
if (opts.signal) {
opts.signal.addEventListener("abort", abort.bind(this));
}
}
this.on("newListener", newListener);
}
_open(cb) {
cb(null);
}
_destroy(cb) {
cb(null);
}
_predestroy() {
}
get readable() {
return this._readableState !== null ? true : void 0;
}
get writable() {
return this._writableState !== null ? true : void 0;
}
get destroyed() {
return (this._duplexState & DESTROYED) !== 0;
}
get destroying() {
return (this._duplexState & DESTROY_STATUS) !== 0;
}
destroy(err) {
if ((this._duplexState & DESTROY_STATUS) === 0) {
if (!err) err = STREAM_DESTROYED;
this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY;
if (this._readableState !== null) {
this._readableState.highWaterMark = 0;
this._readableState.error = err;
}
if (this._writableState !== null) {
this._writableState.highWaterMark = 0;
this._writableState.error = err;
}
this._duplexState |= PREDESTROYING;
this._predestroy();
this._duplexState &= NOT_PREDESTROYING;
if (this._readableState !== null) this._readableState.updateNextTick();
if (this._writableState !== null) this._writableState.updateNextTick();
}
}
};
var Readable = class _Readable extends Stream {
constructor(opts) {
super(opts);
this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD;
this._readableState = new ReadableState(this, opts);
if (opts) {
if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD;
if (opts.read) this._read = opts.read;
if (opts.eagerOpen) this._readableState.updateNextTick();
if (opts.encoding) this.setEncoding(opts.encoding);
}
}
setEncoding(encoding) {
const dec = new TextDecoder(encoding);
const map = this._readableState.map || echo;
this._readableState.map = mapOrSkip;
return this;
function mapOrSkip(data) {
const next = dec.push(data);
return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next);
}
}
_read(cb) {
cb(null);
}
pipe(dest, cb) {
this._readableState.updateNextTick();
this._readableState.pipe(dest, cb);
return dest;
}
read() {
this._readableState.updateNextTick();
return this._readableState.read();
}
push(data) {
this._readableState.updateNextTickIfOpen();
return this._readableState.push(data);
}
unshift(data) {
this._readableState.updateNextTickIfOpen();
return this._readableState.unshift(data);
}
resume() {
this._duplexState |= READ_RESUMED_READ_AHEAD;
this._readableState.updateNextTick();
return this;
}
pause() {
this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED;
return this;
}
static _fromAsyncIterator(ite, opts) {
let destroy;
const rs = new _Readable({
...opts,
read(cb) {
ite.next().then(push).then(cb.bind(null, null)).catch(cb);
},
predestroy() {
destroy = ite.return();
},
destroy(cb) {
if (!destroy) return cb(null);
destroy.then(cb.bind(null, null)).catch(cb);
}
});
return rs;
function push(data) {
if (data.done) rs.push(null);
else rs.push(data.value);
}
}
static from(data, opts) {
if (isReadStreamx(data)) return data;
if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts);
if (!Array.isArray(data)) data = data === void 0 ? [] : [data];
let i = 0;
return new _Readable({
...opts,
read(cb) {
this.push(i === data.length ? null : data[i++]);
cb(null);
}
});
}
static isBackpressured(rs) {
return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark;
}
static isPaused(rs) {
return (rs._duplexState & READ_RESUMED) === 0;
}
[asyncIterator]() {
const stream = this;
let error = null;
let promiseResolve = null;
let promiseReject = null;
this.on("error", (err) => {
error = err;
});
this.on("readable", onreadable);
this.on("close", onclose);
return {
[asyncIterator]() {
return this;
},
next() {
return new Promise(function(resolve, reject) {
promiseResolve = resolve;
promiseReject = reject;
const data = stream.read();
if (data !== null) ondata(data);
else if ((stream._duplexState & DESTROYED) !== 0) ondata(null);
});
},
return() {
return destroy(null);
},
throw(err) {
return destroy(err);
}
};
function onreadable() {
if (promiseResolve !== null) ondata(stream.read());
}
function onclose() {
if (promiseResolve !== null) ondata(null);
}
function ondata(data) {
if (promiseReject === null) return;
if (error) promiseReject(error);
else if (data === null && (stream._duplexState & READ_DONE) === 0)
promiseReject(STREAM_DESTROYED);
else promiseResolve({ value: data, done: data === null });
promiseReject = promiseResolve = null;
}
function destroy(err) {
stream.destroy(err);
return new Promise((resolve, reject) => {
if (stream._duplexState & DESTROYED) return resolve({ value: void 0, done: true });
stream.once("close", function() {
if (err) reject(err);
else resolve({ value: void 0, done: true });
});
});
}
}
};
var Writable = class extends Stream {
constructor(opts) {
super(opts);
this._duplexState |= OPENING | READ_DONE;
this._writableState = new WritableState(this, opts);
if (opts) {
if (opts.writev) this._writev = opts.writev;
if (opts.write) this._write = opts.write;
if (opts.final) this._final = opts.final;
if (opts.eagerOpen) this._writableState.updateNextTick();
}
}
cork() {
this._duplexState |= WRITE_CORKED;
}
uncork() {
this._duplexState &= WRITE_NOT_CORKED;
this._writableState.updateNextTick();
}
_writev(batch, cb) {
cb(null);
}
_write(data, cb) {
this._writableState.autoBatch(data, cb);
}
_final(cb) {
cb(null);
}
static isBackpressured(ws) {
return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0;
}
static drained(ws) {
if (ws.destroyed) return Promise.resolve(false);
const state = ws._writableState;
const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length;
const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0);
if (writes === 0) return Promise.resolve(true);
if (state.drains === null) state.drains = [];
return new Promise((resolve) => {
state.drains.push({ writes, resolve });
});
}
write(data) {
this._writableState.updateNextTick();
return this._writableState.push(data);
}
end(data) {
this._writableState.updateNextTick();
this._writableState.end(data);
return this;
}
};
var Duplex = class extends Readable {
// and Writable
constructor(opts) {
super(opts);
this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD;
this._writableState = new WritableState(this, opts);
if (opts) {
if (opts.writev) this._writev = opts.writev;
if (opts.write) this._write = opts.write;
if (opts.final) this._final = opts.final;
}
}
cork() {
this._duplexState |= WRITE_CORKED;
}
uncork() {
this._duplexState &= WRITE_NOT_CORKED;
this._writableState.updateNextTick();
}
_writev(batch, cb) {
cb(null);
}
_write(data, cb) {
this._writableState.autoBatch(data, cb);
}
_final(cb) {
cb(null);
}
write(data) {
this._writableState.updateNextTick();
return this._writableState.push(data);
}
end(data) {
this._writableState.updateNextTick();
this._writableState.end(data);
return this;
}
};
var Transform = class extends Duplex {
constructor(opts) {
super(opts);
this._transformState = new TransformState(this);
if (opts) {
if (opts.transform) this._transform = opts.transform;
if (opts.flush) this._flush = opts.flush;
}
}
_write(data, cb) {
if (this._readableState.buffered >= this._readableState.highWaterMark) {
this._transformState.data = data;
} else {
this._transform(data, this._transformState.afterTransform);
}
}
_read(cb) {
if (this._transformState.data !== null) {
const data = this._transformState.data;
this._transformState.data = null;
cb(null);
this._transform(data, this._transformState.afterTransform);
} else {
cb(null);
}
}
destroy(err) {
super.destroy(err);
if (this._transformState.data !== null) {
this._transformState.data = null;
this._transformState.afterTransform();
}
}
_transform(data, cb) {
cb(null, data);
}
_flush(cb) {
cb(null);
}
_final(cb) {
this._transformState.afterFinal = cb;
this._flush(transformAfterFlush.bind(this));
}
};
var PassThrough = class extends Transform {
};
function transformAfterFlush(err, data) {
const cb = this._transformState.afterFinal;
if (err) return cb(err);
if (data !== null && data !== void 0) this.push(data);
this.push(null);
cb(null);
}
function pipelinePromise(...streams) {
return new Promise((resolve, reject) => {
return pipeline(...streams, (err) => {
if (err) return reject(err);
resolve();
});
});
}
function pipeline(stream, ...streams) {
const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams];
const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null;
if (all.length < 2) throw new Error("Pipeline requires at least 2 streams");
let src = all[0];
let dest = null;
let error = null;
for (let i = 1; i < all.length; i++) {
dest = all[i];
if (isStreamx(src)) {
src.pipe(dest, onerror);
} else {
errorHandle(src, true, i > 1, onerror);
src.pipe(dest);
}
src = dest;
}
if (done) {
let fin = false;
const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy);
dest.on("error", (err) => {
if (error === null) error = err;
});
dest.on("finish", () => {
fin = true;
if (!autoDestroy) done(error);
});
if (autoDestroy) {
dest.on("close", () => done(error || (fin ? null : PREMATURE_CLOSE)));
}
}
return dest;
function errorHandle(s, rd, wr, onerror2) {
s.on("error", onerror2);
s.on("close", onclose);
function onclose() {
if (rd && s._readableState && !s._readableState.ended) return onerror2(PREMATURE_CLOSE);
if (wr && s._writableState && !s._writableState.ended) return onerror2(PREMATURE_CLOSE);
}
}
function onerror(err) {
if (!err || error) return;
error = err;
for (const s of all) {
s.destroy(err);
}
}
}
function echo(s) {
return s;
}
function isStream(stream) {
return !!stream._readableState || !!stream._writableState;
}
function isStreamx(stream) {
return typeof stream._duplexState === "number" && isStream(stream);
}
function isEnding(stream) {
return !!stream._readableState && stream._readableState.ending;
}
function isEnded(stream) {
return !!stream._readableState && stream._readableState.ended;
}
function isFinishing(stream) {
return !!stream._writableState && stream._writableState.ending;
}
function isFinished(stream) {
return !!stream._writableState && stream._writableState.ended;
}
function getStreamError(stream, opts = {}) {
const err = stream._readableState && stream._readableState.error || stream._writableState && stream._writableState.error;
return !opts.all && err === STREAM_DESTROYED ? null : err;
}
function isReadStreamx(stream) {
return isStreamx(stream) && stream.readable;
}
function isDisturbed(stream) {
return (stream._duplexState & OPENING) !== OPENING || (stream._duplexState & DESTROYING) === DESTROYING || (stream._duplexState & ACTIVE_OR_TICKING) !== 0;
}
function isTypedArray(data) {
return typeof data === "object" && data !== null && typeof data.byteLength === "number";
}
function defaultByteLength(data) {
return isTypedArray(data) ? data.byteLength : 1024;
}
function noop() {
}
function abort() {
this.destroy(new Error("Stream aborted."));
}
function isWritev(s) {
return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev;
}
module.exports = {
pipeline,
pipelinePromise,
isStream,
isStreamx,
isEnding,
isEnded,
isFinishing,
isFinished,
isDisturbed,
getStreamError,
Stream,
Writable,
Readable,
Duplex,
Transform,
// Export PassThrough for compatibility with Node.js core's stream module
PassThrough
};
}
});
// ../../node_modules/teex/index.js
var require_teex = __commonJS({
"../../node_modules/teex/index.js"(exports, module) {
var { Readable } = require_streamx();
module.exports = function(s, forks = 2) {
const streams = new Array(forks);
const status = new Array(forks).fill(true);
let ended = false;
for (let i = 0; i < forks; i++) {
streams[i] = new Readable({
read(cb) {
const check = !status[i];
status[i] = true;
if (check && allReadable()) s.resume();
cb(null);
}
});
}
s.on("end", function() {
ended = true;
for (const stream of streams) stream.push(null);
});
s.on("error", function(err) {
for (const stream of streams) stream.destroy(err);
});
s.on("close", function() {
if (ended) return;
for (const stream of streams) stream.destroy();
});
s.on("data", function(data) {
let needsPause = false;
for (let i = 0; i < streams.length; i++) {
if (!(status[i] = streams[i].push(data))) {
needsPause = true;
}
}
if (needsPause) s.pause();
});
return streams;
function allReadable() {
for (let j = 0; j < status.length; j++) {
if (!status[j]) return false;
}
return true;
}
};
}
});
// ../../node_modules/bare-stream/web.js
var require_web = __commonJS({
"../../node_modules/bare-stream/web.js"(exports) {
var { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require_streamx();
var tee = require_teex();
var readableKind = Symbol.for("bare.stream.readable.kind");
var writableKind = Symbol.for("bare.stream.writable.kind");
var transformKind = Symbol.for("bare.stream.transform.kind");
exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader {
constructor(stream) {
this._stream = stream;
this._stream._stream.once("close", onclose).once("error", onerror);
const closed = Promise.withResolvers();
closed.promise.catch(noop);
this._closed = closed;
function onclose() {
closed.resolve();
}
function onerror(err) {
closed.reject(err);
}
}
get closed() {
return this._closed.promise;
}
read() {
const stream = this._stream._stream;
return new Promise((resolve, reject) => {
const err = getStreamError(stream);
if (err) return reject(err);
if (stream.destroyed) {
return resolve({ value: void 0, done: true });
}
const value = stream.read();
if (value !== null) {
return resolve({ value, done: false });
}
stream.once("readable", onreadable).once("close", onclose).once("error", onerror);
function onreadable() {
const value2 = stream.read();
ondone(null, value2 === null ? { value: void 0, done: true } : { value: value2, done: false });
}
function onclose() {
ondone(null, { value: void 0, done: true });
}
function onerror(err2) {
ondone(err2, null);
}
function ondone(err2, value2) {
stream.off("readable", onreadable).off("close", onclose).off("error", onerror);
if (err2) reject(err2);
else resolve(value2);
}
});
}
releaseLock() {
this._closed.reject(new TypeError("Reader was released"));
this._stream._releaseLock();
this._stream = null;
}
cancel(reason = new TypeError("Stream was cancelled")) {
const stream = this._stream._stream;
if (stream.destroyed) return Promise.resolve();
return new Promise(
(resolve) => stream.once("close", resolve).once("error", noop).destroy(reason)
);
}
};
exports.ReadableStreamDefaultController = class ReadableStreamDefaultController {
constructor(stream) {
this._stream = stream;
}
get desiredSize() {
const stream = this._stream._stream;
return stream._readableState.highWaterMark - stream._readableState.buffered;
}
enqueue(data) {
this._stream._stream.push(data);
}
close() {
this._stream._stream.push(null);
}
error(err) {
this._stream._stream.destroy(err);
}
};
var ReadableStream = class _ReadableStream {
static get [readableKind]() {
return 0;
}
static from(iterable) {
return new _ReadableStream(Readable.from(iterable));
}
constructor(underlyingSource = {}, queuingStrategy) {
if (isStreamx(underlyingSource)) {
this._stream = underlyingSource;
} else {
if (queuingStrategy === void 0) {
queuingStrategy = new exports.CountQueuingStrategy();
}
const { start, pull, cancel } = underlyingSource;
const { highWaterMark = 1, size = defaultSize } = queuingStrategy;
this._stream = new Readable({ highWaterMark, byteLength: size });
const controller = new exports.ReadableStreamDefaultController(this);
if (start) {
this._stream._open = this._open.bind(this, start.call(this, controller));
}
if (pull) {
this._stream._read = this._read.bind(this, pull.bind(this, controller));
}
if (cancel) {
this._stream.once("error", cancel);
}
}
this._reader = null;
}
get [readableKind]() {
return _ReadableStream[readableKind];
}
get locked() {
return this._reader !== null;
}
getReader() {
if (this.locked) throw new TypeError("Stream is locked");
this._reader = new exports.ReadableStreamDefaultReader(this);
return this._reader;
}
cancel(reason = new TypeError("Stream was cancelled")) {
const stream = this._stream;
if (stream.destroyed) return Promise.resolve();
if (this.locked) return Promise.reject(new TypeError("Stream is locked"));
return new Promise(
(resolve) => stream.once("close", resolve).once("error", noop).destroy(reason)
);
}
tee() {
const [a, b] = tee(this._stream);
return [new _ReadableStream(a), new _ReadableStream(b)];
}
pipeTo(destination) {
return new Promise(
(resolve, reject) => this._stream.pipe(destination._stream, (err) => {
err ? reject(err) : resolve();
})
);
}
[Symbol.asyncIterator]() {
return this._stream[Symbol.asyncIterator]();
}
_releaseLock() {
this._reader = null;
}
async _open(starting, cb) {
let err = null;
try {
await starting;
} catch (e) {
err = e;
}
cb(err);
}
async _read(pull, cb) {
let err = null;
try {
await pull();
} catch (e) {
err = e;
}
cb(err);
}
};
function defaultSize() {
return 1;
}
exports.ReadableStream = ReadableStream;
exports.CountQueuingStrategy = class CountQueuingStrategy {
constructor(opts = {}) {
const { highWaterMark = 1 } = opts;
this.highWaterMark = highWaterMark;
}
size(chunk) {
return 1;
}
};
exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy {
constructor(opts = {}) {
const { highWaterMark = 16384 } = opts;
this.highWaterMark = highWaterMark;
}
size(chunk) {
return chunk.byteLength;
}
};
exports.isReadableStream = function isReadableStream(value) {
if (value instanceof ReadableStream) return true;
return typeof value === "object" && value !== null && value[readableKind] === ReadableStream[readableKind];
};
exports.isReadableStreamErrored = function isReadableStreamErrored(stream) {
return getStreamError(stream._stream) !== null;
};
exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) {
return isDisturbed(stream._stream);
};
exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter {
constructor(stream) {
this._stream = stream;
this._stream._stream.once("close", onclose).once("error", onerror);
const closed = Promise.withResolvers();
closed.promise.catch(noop);
this._closed = closed;
function onclose() {
closed.resolve();
}
function onerror(err) {
closed.reject(err);
}
}
get desiredSize() {
const stream = this._stream._stream;
return stream._writableState.highWaterMark - stream._writableState.buffered;
}
get closed() {
return this._closed.promise;
}
get ready() {
const stream = this._stream._stream;
if (getStreamError(stream)) return Promise.reject();
return Writable.drained(stream).then();
}
async write(chunk) {
const stream = this._stream._stream;
let err = getStreamError(stream);
if (err) return Promise.reject(err);
stream.write(chunk);
await Writable.drained(stream);
err = getStreamError(stream);
if (err) return Promise.reject(err);
}
releaseLock() {
this._closed.reject(new TypeError("Writer was released"));
this._stream._releaseLock();
this._stream = null;
}
close() {
const stream = this._stream._stream;
if (stream.destroyed) return Promise.resolve();
return new Promise((resolve) => stream.once("close", resolve).end());
}
abort(reason = new TypeError("Stream was aborted")) {
const stream = this._stream._stream;
if (stream.destroyed) return Promise.resolve();
return new Promise((resolve) => stream.once("close", resolve).destroy(reason));
}
};
exports.WritableStreamDefaultController = class WritableStreamDefaultController {
constructor(stream) {
this._stream = stream;
}
error(err) {
this._stream._stream.destroy(err);
}
};
var WritableStream = class _WritableStream {
static get [writableKind]() {
return 0;
}
constructor(underlyingSink = {}, queuingStrategy = {}) {
if (isStreamx(underlyingSink)) {
this._stream = underlyingSink;
} else {
if (queuingStrategy === void 0) {
queuingStrategy = new exports.CountQueuingStrategy();
}
const { start, write, close, abort } = underlyingSink;
const { highWaterMark = 1, size = defaultSize } = queuingStrategy;
this._stream = new Writable({ highWaterMark, byteLength: size });
this._controller = new exports.WritableStreamDefaultController(this);
if (start) {
this._stream._open = this._open.bind(this, start.call(this, this._controller));
}
if (write) {
this._stream._write = this._write.bind(this, write);
}
if (close) {
this._stream._destroy = this._destroy.bind(this, close.call(this));
}
if (abort) {
this._stream.once("error", abort);
}
}
this._writer = null;
}
get [writableKind]() {
return _WritableStream[writableKind];
}
get locked() {
return this._writer !== null;
}
getWriter() {
if (this.locked) throw new TypeError("Stream is locked");
this._writer = new exports.WritableStreamDefaultWriter(this);
return this._writer;
}
abort(reason = new TypeError("Stream was aborted")) {
if (this._stream.destroyed) return Promise.resolve();
if (this.locked) return Promise.reject(new TypeError("Stream is locked"));
return new Promise((resolve) => this._stream.once("close", resolve).destroy(reason));
}
close() {
if (this._stream.destroyed) return Promise.resolve();
if (this.locked) return Promise.reject(new TypeError("Stream is locked"));
return new Promise((resolve) => this._stream.once("close", resolve).end());
}
_releaseLock() {
this._writer = null;
}
async _open(starting, cb) {
let err = null;
try {
await starting;
} catch (e) {
err = e;
}
cb(err);
}
async _write(write, data, cb) {
let err = null;
try {
await write(data, this._controller);
} catch (e) {
err = e;
}
cb(err);
}
async _destroy(closing, cb) {
let err = null;
try {
await closing;
} catch (e) {
err = e;
}
cb(err);
}
};
exports.WritableStream = WritableStream;
exports.isWritableStream = function isWritableStream(value) {
if (value instanceof WritableStream) return true;
return typeof value === "object" && value !== null && value[writableKind] === WritableStream[writableKind];
};
exports.TransformStreamDefaultController = class TransformStreamDefaultController {
constructor(stream) {
this._stream = stream;
}
get desiredSize() {
const stream = this._stream._stream;
return stream._readableState.highWaterMark - stream._readableState.buffered;
}
enqueue(data) {
this._stream._stream.push(data);
}
error(err) {
this._stream._stream.destroy(err);
}
terminate() {
const stream = this._stream._stream;
stream.push(null);
stream.destroy(new TypeError("Stream has been terminated"));
}
};
var TransformStream = class _TransformStream {
static get [transformKind]() {
return 0;
}
constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
const { start, transform, flush } = transformer;
this._stream = new Transform({ ...writableStrategy, ...readableStrategy });
this._writable = new WritableStream(this._stream);
this._readable = new ReadableStream(this._stream);
this._controller = new exports.TransformStreamDefaultController(this);
if (start) {
this._stream._open = this._open.bind(this, start.call(this, this._controller));
}
if (transform) {
this._stream._write = this._transform.bind(this, transform);
}
if (flush) {
this._stream._flush = this._flush.bind(this, flush.call(this, this._controller));
}
}
get [transformKind]() {
return _TransformStream[transformKind];
}
get writable() {
return this._writable;
}
get readable() {
return this._readable;
}
async _open(starting, cb) {
let err = null;
try {
await starting;
} catch (e) {
err = e;
}
cb(err);
}
async _transform(transform, data, cb) {
let err = null;
try {
await transform(data, this._controller);
} catch (e) {
err = e;
}
cb(err);
}
async _flush(flush, cb) {
let err = null;
try {
await flush;
} catch (e) {
err = e;
}
cb(err);
}
};
exports.TransformStream = TransformStream;
exports.isTransformStream = function isTransformStream(value) {
if (value instanceof TransformStream) return true;
return typeof value === "object" && value !== null && value[transformKind] === TransformStream[transformKind];
};
function noop() {
}
}
});
// ../../node_modules/bare-stream/index.js
var require_bare_stream = __commonJS({
"../../node_modules/bare-stream/index.js"(exports, module) {
var stream = require_streamx();
var { ReadableStream, WritableStream } = require_web();
var defaultEncoding = "utf8";
module.exports = exports = stream.Stream;
exports.pipeline = stream.pipeline;
exports.isStream = stream.isStream;
exports.isEnding = stream.isEnding;
exports.isEnded = stream.isEnded;
exports.isFinishing = stream.isFinishing;
exports.isFinished = stream.isFinished;
exports.isDisturbed = stream.isDisturbed;
exports.isErrored = function isErrored(stream2) {
return exports.getStreamError(stream2) !== null;
};
exports.isReadable = function isReadable(stream2) {
return stream2.readable && !stream2.destroying && !exports.isEnded(stream2);
};
exports.isWritable = function isWritable(stream2) {
return stream2.writable && !stream2.destroying && !exports.isFinishing(stream2);
};
exports.getStreamError = stream.getStreamError;
exports.addAbortSignal = function addAbortSignal(signal, stream2) {
function onAbort() {
stream2.destroy(signal.reason);
}
if (signal.aborted) onAbort();
else signal.addEventListener("abort", onAbort);
return stream2;
};
exports.Stream = exports;
exports.Readable = class Readable extends stream.Readable {
constructor(opts = {}) {
super({
...opts,
byteLength: null,
byteLengthReadable: null,
map: null,
mapReadable: null
});
if (this._construct) this._open = this._construct;
if (this._read !== stream.Readable.prototype._read) {
this._read = read.bind(this, this._read);
}
if (this._destroy !== stream.Stream.prototype._destroy) {
this._destroy = destroy.bind(this, this._destroy);
}
}
get closed() {
return !exports.isReadable(this);
}
get errored() {
return stream.getStreamError(this);
}
push(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
return super.push(chunk);
}
unshift(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
super.unshift(chunk);
}
static fromWeb(readableStream, opts = {}) {
const stream2 = readableStream._stream;
if (opts.encoding) stream2.setEncoding(opts.encoding);
if (opts.signal) exports.addAbortSignal(opts.signal, stream2);
return stream2;
}
static toWeb(readable, opts = {}) {
return new ReadableStream(readable, opts.strategy);
}
async [Symbol.asyncDispose]() {
if (!this.destroyed) this.destroy();
await new Promise((resolve) => exports.finished(this, resolve));
}
};
exports.Writable = class Writable extends stream.Writable {
constructor(opts = {}) {
super({
...opts,
byteLength: null,
byteLengthWritable,
map: null,
mapWritable: null
});
if (this._construct) this._open = this._construct;
if (this._write !== stream.Writable.prototype._write) {
this._write = write.bind(this, this._write);
}
if (this._destroy !== stream.Stream.prototype._destroy) {
this._destroy = destroy.bind(this, this._destroy);
}
}
get closed() {
return !exports.isWritable(this);
}
get errored() {
return stream.getStreamError(this);
}
write(chunk, encoding, cb) {
if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = super.write({ chunk, encoding });
if (cb) stream.Writable.drained(this).then(() => cb(null), cb);
return result;
}
end(chunk, encoding, cb) {
if (typeof chunk === "function") {
cb = chunk;
chunk = null;
} else if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding || defaultEncoding);
} else {
encoding = "buffer";
}
const result = chunk !== void 0 && chunk !== null ? super.end({ chunk, encoding }) : super.end();
if (cb) this.once("finish", () => cb(null));
return result;
}
static fromWeb(writableStream, opts = {}) {
const stream2 = writableStream._stream;
if (opts.signal) exports.addAbortSignal(opts.signal, stream2);
return stream2;
}
static toWeb(writable) {
return new WritableStream(writable);
}
async [Symbol.asyncDispose]() {
if (!this.destroyed) this.destroy();
await new Promise((resolve) => exports.finished(this, resolve));
}
};
exports.Duplex = class Duplex extends stream.Duplex {
constructor(opts = {}) {
super({
...opts,
byteLength: null,
byteLengthReadable: null,
byteLengthWritable,
map: null,
mapReadable: null,
mapWritable: null
});
if (this._construct) this._open = this._construct;
if (this._read !== stream.Readable.prototype._read) {
this._read = read.bind(this, this._read);
}
if (this._write !== stream.Duplex.prototype._write) {
this._write = write.bind(this, this._write);
}
if (this._destroy !== stream.Stream.prototype._destroy) {
this._destroy = destroy.bind(this, this._destroy);
}
}
push(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
return super.push(chunk);
}
unshift(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
super.unshift(chunk);
}
write(chunk, encoding, cb) {
if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = super.write({ chunk, encoding });
if (cb) stream.Writable.drained(this).then(() => cb(null), cb);
return result;
}
end(chunk, encoding, cb) {
if (typeof chunk === "function") {
cb = chunk;
chunk = null;
} else if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = chunk !== void 0 && chunk !== null ? super.end({ chunk, encoding }) : super.end();
if (cb) this.once("finish", () => cb(null));
return result;
}
static fromWeb({ readable: readableStream, writable: writableStream }, opts) {
const readable = exports.Readable.fromWeb(readableStream, opts);
const writable = exports.Readable.fromWeb(writableStream, opts);
const duplex = new exports.Duplex({
write(data, encoding, cb) {
writable.write(data, encoding, cb);
}
});
readable.on("data", (data) => duplex.push(data)).on("end", () => duplex.push(null)).on("error", (err) => duplex.destroy(err));
writable.on("finish", () => duplex.end()).on("error", (err) => duplex.destroy(err));
return duplex;
}
static toWeb(duplex) {
const readableStream = exports.Readable.toWeb(duplex);
const writableStream = exports.Writable.toWeb(duplex);
return { readable: readableStream, writable: writableStream };
}
};
var DuplexSide = class extends exports.Duplex {
constructor(opts) {
super(opts);
this._otherSide = null;
this._cb = null;
}
_read() {
const cb = this._cb;
if (!cb) return;
this._cb = null;
cb();
}
_write(chunk, encoding, cb) {
this._otherSide.push(chunk, encoding);
this._otherSide._cb = cb;
}
_final(cb) {
this._otherSide.on("end", cb);
this._otherSide.push(null);
}
};
exports.duplexPair = function duplexPair(opts) {
const sideA = new DuplexSide(opts);
const sideB = new DuplexSide(opts);
sideA._otherSide = sideB;
sideB._otherSide = sideA;
return [sideA, sideB];
};
exports.Transform = class Transform extends stream.Transform {
constructor(opts = {}) {
super({
...opts,
byteLength: null,
byteLengthReadable: null,
byteLengthWritable,
map: null,
mapReadable: null,
mapWritable: null
});
if (this._transform !== stream.Transform.prototype._transform) {
this._transform = transform.bind(this, this._transform);
} else {
this._transform = passthrough;
}
}
push(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
return super.push(chunk);
}
unshift(chunk, encoding) {
if (typeof chunk === "string") {
chunk = Buffer.from(chunk, encoding || defaultEncoding);
}
super.unshift(chunk);
}
write(chunk, encoding, cb) {
if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = super.write({ chunk, encoding });
if (cb) stream.Writable.drained(this).then(() => cb(null), cb);
return result;
}
end(chunk, encoding, cb) {
if (typeof chunk === "function") {
cb = chunk;
chunk = null;
} else if (typeof encoding === "function") {
cb = encoding;
encoding = null;
}
if (typeof chunk === "string") {
encoding = encoding || defaultEncoding;
chunk = Buffer.from(chunk, encoding);
} else {
encoding = "buffer";
}
const result = chunk !== void 0 && chunk !== null ? super.end({ chunk, encoding }) : super.end();
if (cb) this.once("finish", () => cb(null));
return result;
}
};
exports.PassThrough = class PassThrough extends exports.Transform {
};
exports.finished = function finished(stream2, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (!opts) opts = {};
const { cleanup = false } = opts;
const done = () => {
cb(exports.getStreamError(stream2, { all: true }));
if (cleanup) detach();
};
const detach = () => {
stream2.off("close", done);
stream2.off("error", noop);
};
if (stream2.destroyed) {
done();
} else {
stream2.on("close", done);
stream2.on("error", noop);
}
return detach;
};
function read(read2, cb) {
read2.call(this, 65536);
cb(null);
}
function write(write2, data, cb) {
write2.call(this, data.chunk, data.encoding, cb);
}
function transform(transform2, data, cb) {
transform2.call(this, data.chunk, data.encoding, cb);
}
function destroy(destroy2, cb) {
destroy2.call(this, exports.getStreamError(this), cb);
}
function passthrough(data, cb) {
cb(null, data.chunk);
}
function byteLengthWritable(data) {
return data.chunk.byteLength;
}
function noop() {
}
}
});
// ../../node_modules/bare-fs/binding.js
var require_binding3 = __commonJS({
"../../node_modules/bare-fs/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-fs/lib/constants.js
var require_constants3 = __commonJS({
"../../node_modules/bare-fs/lib/constants.js"(exports, module) {
var binding = require_binding3();
module.exports = {
O_RDWR: binding.O_RDWR,
O_RDONLY: binding.O_RDONLY,
O_WRONLY: binding.O_WRONLY,
O_CREAT: binding.O_CREAT,
O_TRUNC: binding.O_TRUNC,
O_APPEND: binding.O_APPEND,
F_OK: binding.F_OK || 0,
R_OK: binding.R_OK || 0,
W_OK: binding.W_OK || 0,
X_OK: binding.X_OK || 0,
S_IFMT: binding.S_IFMT,
S_IFREG: binding.S_IFREG,
S_IFDIR: binding.S_IFDIR,
S_IFCHR: binding.S_IFCHR,
S_IFLNK: binding.S_IFLNK,
S_IFBLK: binding.S_IFBLK || 0,
S_IFIFO: binding.S_IFIFO || 0,
S_IFSOCK: binding.S_IFSOCK || 0,
S_IRUSR: binding.S_IRUSR || 0,
S_IWUSR: binding.S_IWUSR || 0,
S_IXUSR: binding.S_IXUSR || 0,
S_IRGRP: binding.S_IRGRP || 0,
S_IWGRP: binding.S_IWGRP || 0,
S_IXGRP: binding.S_IXGRP || 0,
S_IROTH: binding.S_IROTH || 0,
S_IWOTH: binding.S_IWOTH || 0,
S_IXOTH: binding.S_IXOTH || 0,
UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN,
UV_DIRENT_FILE: binding.UV_DIRENT_FILE,
UV_DIRENT_DIR: binding.UV_DIRENT_DIR,
UV_DIRENT_LINK: binding.UV_DIRENT_LINK,
UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO,
UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET,
UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR,
UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK,
COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL,
COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE,
COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE,
UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR,
UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION
};
}
});
// ../../node_modules/bare-fs/lib/errors.js
var require_errors4 = __commonJS({
"../../node_modules/bare-fs/lib/errors.js"(exports, module) {
var os = require_bare_os();
module.exports = class FileError extends Error {
constructor(msg, opts = {}) {
const { code, operation = null, path = null, destination = null, fd = -1 } = opts;
if (operation !== null) msg += describe(operation, opts);
super(`${code}: ${msg}`);
this.code = code;
if (operation !== null) this.operation = operation;
if (path !== null) this.path = path;
if (destination !== null) this.destination = destination;
if (fd !== -1) this.fd = fd;
}
get name() {
return "FileError";
}
// For Node.js compatibility
get errno() {
return os.constants.errnos[this.code];
}
// For Node.js compatibility
get syscall() {
return this.operation;
}
// For Node.js compatibility
get dest() {
return this.destination;
}
};
function describe(operation, opts) {
const { path = null, destination = null, fd = -1 } = opts;
let result = `, ${operation}`;
if (path !== null) {
result += ` ${JSON.stringify(path)}`;
if (destination !== null) {
result += ` -> ${JSON.stringify(destination)}`;
}
} else if (fd !== -1) {
result += ` ${fd}`;
}
return result;
}
}
});
// ../../node_modules/bare-fs/promises.js
var require_promises = __commonJS({
"../../node_modules/bare-fs/promises.js"(exports) {
var EventEmitter = require_bare_events();
var fs = require_bare_fs();
var FileHandle = class extends EventEmitter {
constructor(fd) {
super();
this.fd = fd;
}
async close() {
await fs.close(this.fd);
this.fd = -1;
this.emit("close");
}
async read(buffer, ...args) {
return {
bytesRead: await fs.read(this.fd, buffer, ...args),
buffer
};
}
async readv(buffers, ...args) {
return {
bytesRead: await fs.readv(this.fd, buffers, ...args),
buffers
};
}
async write(buffer, ...args) {
return {
bytesWritten: await fs.write(this.fd, buffer, ...args),
buffer
};
}
async writev(buffers, ...args) {
return {
bytesWritten: await fs.writev(this.fd, buffers, ...args),
buffers
};
}
async stat() {
return fs.fstat(this.fd);
}
async chmod(mode) {
await fs.fchmod(this.fd, mode);
}
createReadStream(opts) {
return fs.createReadStream(null, { ...opts, fd: this.fd });
}
createWriteStream(opts) {
return fs.createWriteStream(null, { ...opts, fd: this.fd });
}
async [Symbol.asyncDispose]() {
await this.close();
}
};
exports.open = async function open(filepath, flags, mode) {
return new FileHandle(await fs.open(filepath, flags, mode));
};
exports.access = fs.access;
exports.appendFile = fs.appendFile;
exports.chmod = fs.chmod;
exports.constants = fs.constants;
exports.copyFile = fs.copyFile;
exports.cp = fs.cp;
exports.lstat = fs.lstat;
exports.mkdir = fs.mkdir;
exports.opendir = fs.opendir;
exports.readFile = fs.readFile;
exports.readdir = fs.readdir;
exports.readlink = fs.readlink;
exports.realpath = fs.realpath;
exports.rename = fs.rename;
exports.rm = fs.rm;
exports.rmdir = fs.rmdir;
exports.stat = fs.stat;
exports.symlink = fs.symlink;
exports.unlink = fs.unlink;
exports.utimes = fs.utimes;
exports.watch = fs.watch;
exports.writeFile = fs.writeFile;
}
});
// ../../node_modules/bare-fs/index.js
var require_bare_fs = __commonJS({
"../../node_modules/bare-fs/index.js"(exports) {
var FIFO = require_fast_fifo();
var EventEmitter = require_bare_events();
var path = require_bare_path();
var { isURL, fileURLToPath } = require_bare_url();
var { Readable, Writable } = require_bare_stream();
var binding = require_binding3();
var constants = require_constants3();
var FileError = require_errors4();
var isWindows = Bare.platform === "win32";
exports.constants = constants;
var FileRequest = class _FileRequest {
static borrow() {
if (this._free.length > 0) return this._free.pop();
return new _FileRequest();
}
static return(req) {
if (this._free.length < 32) this._free.push(req.reset());
else req.destroy();
}
constructor() {
this._reset();
this._handle = binding.requestInit(this, this._onresult);
}
get handle() {
return this._handle;
}
retain(value) {
this._retain = value;
}
reset() {
if (this._handle === null) return this;
binding.requestReset(this._handle);
this._reset();
return this;
}
destroy() {
if (this._handle === null) return this;
binding.requestDestroy(this._handle);
this._reset();
this._handle = null;
return this;
}
then(resolve, reject) {
return this._promise.then(resolve, reject);
}
return() {
if (this._handle === null) return this;
_FileRequest.return(this);
return this;
}
_reset() {
this._promise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
this._retain = null;
}
_onresult(err, status) {
if (err) this._reject(err);
else this._resolve(status);
}
};
FileRequest._free = [];
function ok(result, cb) {
if (typeof result === "function") {
cb = result;
result = void 0;
}
if (cb) cb(null, result);
else return result;
}
function fail(err, cb) {
if (cb) cb(err);
else throw err;
}
function done(err, result, cb) {
if (typeof result === "function") {
cb = result;
result = void 0;
}
if (err) fail(err, cb);
else return ok(result, cb);
}
async function open(filepath, flags = "r", mode = 438, cb) {
if (typeof flags === "function") {
cb = flags;
flags = "r";
mode = 438;
} else if (typeof mode === "function") {
cb = mode;
mode = 438;
}
if (typeof flags === "string") flags = toFlags(flags);
if (typeof mode === "string") mode = toMode(mode);
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let fd;
let err = null;
try {
binding.open(req.handle, filepath, flags, mode);
fd = await req;
} catch (e) {
err = new FileError(e.message, {
operation: "open",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, fd, cb);
}
function openSync(filepath, flags = "r", mode = 438) {
if (typeof flags === "string") flags = toFlags(flags);
if (typeof mode === "string") mode = toMode(mode);
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
return binding.openSync(req.handle, filepath, flags, mode);
} catch (e) {
throw new FileError(e.message, {
operation: "open",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function close(fd, cb) {
const req = FileRequest.borrow();
let err = null;
try {
binding.close(req.handle, fd);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "close", code: e.code, fd });
} finally {
req.return();
}
return done(err, cb);
}
function closeSync(fd) {
const req = FileRequest.borrow();
try {
binding.closeSync(req.handle, fd);
} catch (e) {
throw new FileError(e.message, { operation: "close", code: e.code, fd });
} finally {
req.return();
}
}
async function access(filepath, mode = constants.F_OK, cb) {
if (typeof mode === "function") {
cb = mode;
mode = constants.F_OK;
}
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.access(req.handle, filepath, mode);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "access",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function accessSync(filepath, mode = constants.F_OK) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.accessSync(req.handle, filepath, mode);
} catch (e) {
throw new FileError(e.message, {
operation: "access",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function exists(filepath, cb) {
let ok2 = true;
try {
await access(filepath);
} catch {
ok2 = false;
}
return done(null, ok2, cb);
}
function existsSync(filepath) {
try {
accessSync(filepath);
} catch {
return false;
}
return true;
}
async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) {
if (typeof offset === "function") {
cb = offset;
offset = 0;
len = buffer.byteLength;
pos = -1;
} else if (typeof len === "function") {
cb = len;
len = buffer.byteLength - offset;
pos = -1;
} else if (typeof pos === "function") {
cb = pos;
pos = -1;
}
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
let bytes;
let err = null;
try {
binding.read(req.handle, fd, buffer, offset, len, pos);
bytes = await req;
} catch (e) {
err = new FileError(e.message, { operation: "read", code: e.code, fd });
} finally {
req.return();
}
return done(err, bytes, cb);
}
function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) {
const req = FileRequest.borrow();
try {
return binding.readSync(req.handle, fd, buffer, offset, len, pos);
} catch (e) {
throw new FileError(e.message, { operation: "read", code: e.code, fd });
} finally {
req.return();
}
}
async function readv(fd, buffers, pos = -1, cb) {
if (typeof pos === "function") {
cb = pos;
pos = -1;
}
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
let bytes;
let err = null;
try {
binding.readv(req.handle, fd, buffers, pos);
bytes = await req;
} catch (e) {
err = new FileError(e.message, { operation: "readv", code: e.code, fd });
} finally {
req.return();
}
return done(err, bytes, cb);
}
function readvSync(fd, buffers, pos = -1) {
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
try {
return binding.readvSync(req.handle, fd, buffers, pos);
} catch (e) {
throw new FileError(e.message, { operation: "readv", code: e.code, fd });
} finally {
req.return();
}
}
async function write(fd, data, offset, len, pos = -1, cb) {
if (typeof data === "string") {
let encoding = len;
cb = pos;
pos = offset;
if (typeof pos === "function") {
cb = pos;
pos = -1;
encoding = "utf8";
} else if (typeof encoding === "function") {
cb = encoding;
encoding = "utf8";
}
if (typeof pos === "string") {
encoding = pos;
pos = -1;
}
data = Buffer.from(data, encoding);
offset = 0;
len = data.byteLength;
} else if (typeof offset === "function") {
cb = offset;
offset = 0;
len = data.byteLength;
pos = -1;
} else if (typeof len === "function") {
cb = len;
len = data.byteLength - offset;
pos = -1;
} else if (typeof pos === "function") {
cb = pos;
pos = -1;
}
if (typeof offset !== "number") offset = 0;
if (typeof len !== "number") len = data.byteLength - offset;
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
let bytes;
let err = null;
try {
binding.write(req.handle, fd, data, offset, len, pos);
bytes = await req;
} catch (e) {
err = new FileError(e.message, { operation: "write", code: e.code, fd });
} finally {
req.return();
}
return done(err, bytes, cb);
}
function writeSync(fd, data, offset, len, pos = -1) {
if (typeof data === "string") {
let encoding = len;
pos = offset;
if (typeof pos === "string") {
encoding = pos;
pos = -1;
}
data = Buffer.from(data, encoding);
offset = 0;
len = data.byteLength;
}
if (typeof offset !== "number") offset = 0;
if (typeof len !== "number") len = data.byteLength - offset;
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
try {
return binding.writeSync(req.handle, fd, data, offset, len, pos);
} catch (e) {
throw new FileError(e.message, { operation: "write", code: e.code, fd });
} finally {
req.return();
}
}
async function writev(fd, buffers, pos = -1, cb) {
if (typeof pos === "function") {
cb = pos;
pos = -1;
}
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
let bytes;
let err = null;
try {
binding.writev(req.handle, fd, buffers, pos);
bytes = await req;
} catch (e) {
err = new FileError(e.message, { operation: "writev", code: e.code, fd });
} finally {
req.return();
}
return done(err, bytes, cb);
}
function writevSync(fd, buffers, pos = -1) {
if (typeof pos !== "number") pos = -1;
const req = FileRequest.borrow();
try {
return binding.writevSync(req.handle, fd, buffers, pos);
} catch (e) {
throw new FileError(e.message, { operation: "writev", code: e.code, fd });
} finally {
req.return();
}
}
async function stat(filepath, cb) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let st;
let err = null;
try {
binding.stat(req.handle, filepath);
await req;
st = new Stats(...binding.requestResultStat(req.handle));
} catch (e) {
err = new FileError(e.message, {
operation: "stat",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, st, cb);
}
function statSync(filepath) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.statSync(req.handle, filepath);
return new Stats(...binding.requestResultStat(req.handle));
} catch (e) {
throw new FileError(e.message, {
operation: "stat",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function lstat(filepath, cb) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let st;
let err = null;
try {
binding.lstat(req.handle, filepath);
await req;
st = new Stats(...binding.requestResultStat(req.handle));
} catch (e) {
err = new FileError(e.message, {
operation: "lstat",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, st, cb);
}
function lstatSync(filepath) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.lstatSync(req.handle, filepath);
return new Stats(...binding.requestResultStat(req.handle));
} catch (e) {
throw new FileError(e.message, {
operation: "lstat",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function fstat(fd, cb) {
const req = FileRequest.borrow();
let st;
let err = null;
try {
binding.fstat(req.handle, fd);
await req;
st = new Stats(...binding.requestResultStat(req.handle));
} catch (e) {
err = new FileError(e.message, { operation: "fstat", code: e.code, fd });
} finally {
req.return();
}
return done(err, st, cb);
}
function fstatSync(fd) {
const req = FileRequest.borrow();
try {
binding.fstatSync(req.handle, fd);
return new Stats(...binding.requestResultStat(req.handle));
} catch (e) {
throw new FileError(e.message, { operation: "fstat", code: e.code, fd });
} finally {
req.return();
}
}
async function ftruncate(fd, len = 0, cb) {
if (typeof len === "function") {
cb = len;
len = 0;
}
if (typeof len !== "number") len = 0;
const req = FileRequest.borrow();
let err = null;
try {
binding.ftruncate(req.handle, fd, len);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "ftruncate", code: e.code, fd });
} finally {
req.return();
}
return done(err, cb);
}
function ftruncateSync(fd, len = 0) {
if (typeof len !== "number") len = 0;
const req = FileRequest.borrow();
try {
binding.ftruncateSync(req.handle, fd, len);
} catch (e) {
throw new FileError(e.message, { operation: "ftruncate", code: e.code, fd });
} finally {
req.return();
}
}
async function chmod(filepath, mode, cb) {
if (typeof mode === "string") mode = toMode(mode);
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.chmod(req.handle, filepath, mode);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "chmod",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function chmodSync(filepath, mode) {
if (typeof mode === "string") mode = toMode(mode);
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.chmodSync(req.handle, filepath, mode);
} catch (e) {
throw new FileError(e.message, {
operation: "chmod",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function fchmod(fd, mode, cb) {
if (typeof mode === "string") mode = toMode(mode);
const req = FileRequest.borrow();
let err = null;
try {
binding.fchmod(req.handle, fd, mode);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "fchmod", code: e.code, fd });
} finally {
req.return();
}
return done(err, cb);
}
function fchmodSync(fd, mode) {
if (typeof mode === "string") mode = toMode(mode);
const req = FileRequest.borrow();
try {
binding.fchmodSync(req.handle, fd, mode);
} catch (e) {
throw new FileError(e.message, { operation: "fchmod", code: e.code, fd });
} finally {
req.return();
}
}
async function utimes(filepath, atime, mtime, cb) {
if (typeof atime !== "number") atime = atime.getTime() / 1e3;
if (typeof mtime !== "number") mtime = mtime.getTime() / 1e3;
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.utimes(req.handle, filepath, atime, mtime);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "utimes",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function utimesSync(filepath, atime, mtime) {
if (typeof atime !== "number") atime = atime.getTime() / 1e3;
if (typeof mtime !== "number") mtime = mtime.getTime() / 1e3;
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.utimesSync(req.handle, filepath, atime, mtime);
} catch (e) {
throw new FileError(e.message, {
operation: "utimes",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function mkdir(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = { mode: 511 };
}
if (typeof opts === "number") opts = { mode: opts };
else if (!opts) opts = {};
const mode = typeof opts.mode === "number" ? opts.mode : 511;
filepath = toNamespacedPath(filepath);
if (opts.recursive) {
let err2 = null;
try {
try {
await mkdir(filepath, { mode });
} catch (err3) {
if (err3.code !== "ENOENT") {
if (!(await stat(filepath)).isDirectory()) throw err3;
} else {
while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1);
const i = filepath.lastIndexOf(path.sep);
if (i <= 0) throw err3;
await mkdir(filepath.slice(0, i), { mode, recursive: true });
try {
await mkdir(filepath, { mode });
} catch (err4) {
if (!(await stat(filepath)).isDirectory()) throw err4;
}
}
}
} catch (e) {
err2 = e;
}
return done(err2, cb);
}
const req = FileRequest.borrow();
let err = null;
try {
binding.mkdir(req.handle, filepath, mode);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "mkdir",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function mkdirSync(filepath, opts) {
if (typeof opts === "number") opts = { mode: opts };
else if (!opts) opts = {};
const mode = typeof opts.mode === "number" ? opts.mode : 511;
filepath = toNamespacedPath(filepath);
if (opts.recursive) {
try {
mkdirSync(filepath, { mode });
} catch (err) {
if (err.code !== "ENOENT") {
if (!statSync(filepath).isDirectory()) throw err;
} else {
while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1);
const i = filepath.lastIndexOf(path.sep);
if (i <= 0) throw err;
mkdirSync(filepath.slice(0, i), { mode, recursive: true });
try {
mkdirSync(filepath, { mode });
} catch (err2) {
if (!statSync(filepath).isDirectory()) throw err2;
}
}
}
return;
}
const req = FileRequest.borrow();
try {
binding.mkdirSync(req.handle, filepath, mode);
} catch (e) {
throw new FileError(e.message, {
operation: "mkdir",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function rmdir(filepath, cb) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.rmdir(req.handle, filepath);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "rmdir",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function rmdirSync(filepath) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.rmdirSync(req.handle, filepath);
} catch (e) {
throw new FileError(e.message, {
operation: "rmdir",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function rm(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (!opts) opts = {};
filepath = toNamespacedPath(filepath);
let err = null;
try {
const st = await lstat(filepath);
if (st.isDirectory()) {
if (opts.recursive) {
try {
await rmdir(filepath);
} catch (err2) {
if (err2.code !== "ENOTEMPTY") throw err2;
const files = await readdir(filepath);
for (const file of files) {
await rm(filepath + path.sep + file, opts);
}
await rmdir(filepath);
}
} else {
throw new FileError("is a directory", {
operation: "rm",
code: "EISDIR",
path: filepath
});
}
} else {
await unlink(filepath);
}
} catch (e) {
if (e.code !== "ENOENT" || !opts.force) err = e;
}
return done(err, cb);
}
function rmSync(filepath, opts) {
if (!opts) opts = {};
filepath = toNamespacedPath(filepath);
try {
const st = lstatSync(filepath);
if (st.isDirectory()) {
if (opts.recursive) {
try {
rmdirSync(filepath);
} catch (err) {
if (err.code !== "ENOTEMPTY") throw err;
const files = readdirSync(filepath);
for (const file of files) {
rmSync(filepath + path.sep + file, opts);
}
rmdirSync(filepath);
}
} else {
throw new FileError("is a directory", {
operation: "rm",
code: "EISDIR",
path: filepath
});
}
} else {
unlinkSync(filepath);
}
} catch (err) {
if (err.code !== "ENOENT" || !opts.force) throw err;
}
}
async function unlink(filepath, cb) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.unlink(req.handle, filepath);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "unlink",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function unlinkSync(filepath) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.unlinkSync(req.handle, filepath);
} catch (e) {
throw new FileError(e.message, {
operation: "unlink",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function rename(src, dst, cb) {
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
const req = FileRequest.borrow();
let err = null;
try {
binding.rename(req.handle, src, dst);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "rename",
code: e.code,
path: src,
destination: dst
});
} finally {
req.return();
}
return done(err, cb);
}
function renameSync(src, dst) {
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
const req = FileRequest.borrow();
try {
binding.renameSync(req.handle, src, dst);
} catch (e) {
throw new FileError(e.message, {
operation: "rename",
code: e.code,
path: src,
destination: dst
});
} finally {
req.return();
}
}
async function copyFile(src, dst, mode = 0, cb) {
if (typeof mode === "function") {
cb = mode;
mode = 0;
}
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
const req = FileRequest.borrow();
let err = null;
try {
binding.copyfile(req.handle, src, dst, mode);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "copyfile",
code: e.code,
path: src,
destination: dst
});
} finally {
req.return();
}
return done(err, cb);
}
function copyFileSync(src, dst, mode = 0) {
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
const req = FileRequest.borrow();
try {
binding.copyfileSync(req.handle, src, dst, mode);
} catch (e) {
throw new FileError(e.message, {
operation: "copyfile",
code: e.code,
path: src,
destination: dst
});
} finally {
req.return();
}
}
async function cp(src, dst, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (!opts) opts = {};
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
let err = null;
try {
const st = await lstat(src);
if (st.isDirectory()) {
if (opts.recursive !== true) {
throw new FileError("is a directory", { operation: "cp", code: "EISDIR", path: src });
}
try {
await lstat(dst);
} catch (e) {
if (e.code !== "ENOENT") throw e;
await mkdir(dst, { mode: st.mode, recursive: true });
}
const dir = await opendir(src);
for await (const { name } of dir) {
await cp(path.join(src, name), path.join(dst, name), opts);
}
} else if (st.isFile()) {
await copyFile(src, dst);
await chmod(dst, st.mode);
}
} catch (e) {
err = e;
}
return done(err, cb);
}
function cpSync(src, dst, opts = {}) {
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
const st = lstatSync(src);
if (st.isDirectory()) {
if (opts.recursive !== true) {
throw new FileError("is a directory", { operation: "cp", code: "EISDIR", path: src });
}
try {
lstatSync(dst);
} catch (e) {
if (e.code !== "ENOENT") throw e;
mkdirSync(dst, { mode: st.mode, recursive: true });
}
const dir = opendirSync(src);
for (const { name } of dir) {
cpSync(path.join(src, name), path.join(dst, name), opts);
}
} else if (st.isFile()) {
copyFileSync(src, dst);
chmodSync(dst, st.mode);
}
}
async function realpath(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { encoding = "utf8" } = opts;
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let res;
let err = null;
try {
binding.realpath(req.handle, filepath);
await req;
res = Buffer.from(binding.requestResultString(req.handle));
if (encoding !== "buffer") res = res.toString(encoding);
} catch (e) {
err = new FileError(e.message, {
operation: "realpath",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, res, cb);
}
function realpathSync(filepath, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { encoding = "utf8" } = opts;
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.realpathSync(req.handle, filepath);
let res = Buffer.from(binding.requestResultString(req.handle));
if (encoding !== "buffer") res = res.toString(encoding);
return res;
} catch (e) {
throw new FileError(e.message, {
operation: "realpath",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function readlink(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { encoding = "utf8" } = opts;
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let res;
let err = null;
try {
binding.readlink(req.handle, filepath);
await req;
res = Buffer.from(binding.requestResultString(req.handle));
if (encoding !== "buffer") res = res.toString(encoding);
} catch (e) {
err = new FileError(e.message, {
operation: "readlink",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, res, cb);
}
function readlinkSync(filepath, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { encoding = "utf8" } = opts;
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.readlinkSync(req.handle, filepath);
let res = Buffer.from(binding.requestResultString(req.handle));
if (encoding !== "buffer") res = res.toString(encoding);
return res;
} catch (e) {
throw new FileError(e.message, {
operation: "readlink",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
function normalizeSymlinkTarget(target, type, filepath) {
if (isWindows) {
if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, "..", target);
if (path.isAbsolute(target)) return path.toNamespacedPath(target);
return target.replace(/\//g, path.sep);
}
return target;
}
async function symlink(target, filepath, type, cb) {
if (typeof type === "function") {
cb = type;
type = null;
}
filepath = toNamespacedPath(filepath);
if (typeof type === "string") {
switch (type) {
case "dir":
type = constants.UV_FS_SYMLINK_DIR;
break;
case "junction":
type = constants.UV_FS_SYMLINK_JUNCTION;
break;
case "file":
default:
type = 0;
break;
}
} else if (typeof type !== "number") {
if (isWindows) {
target = path.resolve(filepath, "..", target);
try {
type = (await stat(target)).isDirectory() ? constants.UV_FS_SYMLINK_DIR : constants.UV_FS_SYMLINK_JUNCTION;
} catch {
type = 0;
}
} else {
type = 0;
}
}
target = normalizeSymlinkTarget(target, type, filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.symlink(req.handle, target, filepath, type);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "symlink",
code: e.code,
path: target,
destination: filepath
});
} finally {
req.return();
}
return done(err, cb);
}
function symlinkSync(target, filepath, type) {
filepath = toNamespacedPath(filepath);
if (typeof type === "string") {
switch (type) {
case "dir":
type = constants.UV_FS_SYMLINK_DIR;
break;
case "junction":
type = constants.UV_FS_SYMLINK_JUNCTION;
break;
case "file":
default:
type = 0;
break;
}
} else if (typeof type !== "number") {
if (isWindows) {
target = path.resolve(filepath, "..", target);
try {
type = statSync(target).isDirectory() ? constants.UV_FS_SYMLINK_DIR : constants.UV_FS_SYMLINK_JUNCTION;
} catch {
type = 0;
}
} else {
type = 0;
}
}
target = normalizeSymlinkTarget(target, type, filepath);
const req = FileRequest.borrow();
try {
binding.symlinkSync(req.handle, target, filepath, type);
} catch (e) {
throw new FileError(e.message, {
operation: "symlink",
code: e.code,
path: target,
destination: filepath
});
} finally {
req.return();
}
}
async function opendir(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let dir;
let err = null;
try {
binding.opendir(req.handle, filepath);
await req;
dir = new Dir(filepath, binding.requestResultDir(req.handle), opts);
} catch (e) {
err = new FileError(e.message, {
operation: "opendir",
code: e.code,
path: filepath
});
} finally {
req.return();
}
return done(err, dir, cb);
}
function opendirSync(filepath, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.opendirSync(req.handle, filepath);
return new Dir(filepath, binding.requestResultDir(req.handle), opts);
} catch (e) {
throw new FileError(e.message, {
operation: "opendir",
code: e.code,
path: filepath
});
} finally {
req.return();
}
}
async function readdir(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { withFileTypes = false } = opts;
filepath = toNamespacedPath(filepath);
let result = [];
let err = null;
try {
const dir = await opendir(filepath);
for await (const entry of dir) {
result.push(withFileTypes ? entry : entry.name);
}
} catch (e) {
result = [];
err = e;
}
return done(err, result, cb);
}
function readdirSync(filepath, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { withFileTypes = false } = opts;
filepath = toNamespacedPath(filepath);
const dir = opendirSync(filepath, opts);
const result = [];
for (const entry of dir) {
result.push(withFileTypes ? entry : entry.name);
}
return result;
}
async function readFile(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { encoding = "buffer" } = opts;
let fd = -1;
let buffer = null;
let err = null;
try {
fd = await open(filepath, opts.flag || "r");
const st = await fstat(fd);
let len = 0;
if (st.size === 0) {
const buffers = [];
while (true) {
buffer = Buffer.allocUnsafe(8192);
const r = await read(fd, buffer);
len += r;
if (r === 0) break;
buffers.push(buffer.subarray(0, r));
}
buffer = Buffer.concat(buffers);
} else {
buffer = Buffer.allocUnsafe(st.size);
while (true) {
const r = await read(fd, len ? buffer.subarray(len) : buffer);
len += r;
if (r === 0 || len === buffer.byteLength) break;
}
if (len !== buffer.byteLength) buffer = buffer.subarray(0, len);
}
if (encoding !== "buffer") buffer = buffer.toString(encoding);
} catch (e) {
err = e;
} finally {
if (fd !== -1) await close(fd);
}
return done(err, buffer, cb);
}
function readFileSync(filepath, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
const { encoding = "buffer" } = opts;
let fd = -1;
try {
fd = openSync(filepath, opts.flag || "r");
const st = fstatSync(fd);
let buffer;
let len = 0;
if (st.size === 0) {
const buffers = [];
while (true) {
buffer = Buffer.allocUnsafe(8192);
const r = readSync(fd, buffer);
len += r;
if (r === 0) break;
buffers.push(buffer.subarray(0, r));
}
buffer = Buffer.concat(buffers);
} else {
buffer = Buffer.allocUnsafe(st.size);
while (true) {
const r = readSync(fd, len ? buffer.subarray(len) : buffer);
len += r;
if (r === 0 || len === buffer.byteLength) break;
}
if (len !== buffer.byteLength) buffer = buffer.subarray(0, len);
}
if (encoding !== "buffer") buffer = buffer.toString(encoding);
return buffer;
} finally {
if (fd !== -1) closeSync(fd);
}
}
async function writeFile(filepath, data, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
if (typeof data === "string") data = Buffer.from(data, opts.encoding);
let fd = -1;
let len = 0;
let err = null;
try {
fd = await open(filepath, opts.flag || "w", opts.mode || 438);
while (true) {
len += await write(fd, len ? data.subarray(len) : data);
if (len === data.byteLength) break;
}
} catch (e) {
err = e;
} finally {
if (fd !== -1) await close(fd);
}
return done(err, len, cb);
}
function writeFileSync(filepath, data, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
if (typeof data === "string") data = Buffer.from(data, opts.encoding);
let fd = -1;
try {
fd = openSync(filepath, opts.flag || "w", opts.mode || 438);
let len = 0;
while (true) {
len += writeSync(fd, len ? data.subarray(len) : data);
if (len === data.byteLength) break;
}
} finally {
if (fd !== -1) closeSync(fd);
}
}
function appendFile(filepath, data, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
if (!opts.flag) opts = { ...opts, flag: "a" };
return writeFile(filepath, data, opts, cb);
}
function appendFileSync(filepath, data, opts) {
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
if (!opts.flag) opts = { ...opts, flag: "a" };
return writeFileSync(filepath, data, opts);
}
function watch(filepath, opts, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
if (typeof opts === "string") opts = { encoding: opts };
else if (!opts) opts = {};
filepath = toNamespacedPath(filepath);
return new Watcher(filepath, opts, cb);
}
var Stats = class {
constructor(dev, mode, nlink, uid, gid, rdev, blksize, ino, size, blocks, atimeMs, mtimeMs, ctimeMs, birthtimeMs) {
this.dev = dev;
this.mode = mode;
this.nlink = nlink;
this.uid = uid;
this.gid = gid;
this.rdev = rdev;
this.blksize = blksize;
this.ino = ino;
this.size = size;
this.blocks = blocks;
this.atimeMs = atimeMs;
this.mtimeMs = mtimeMs;
this.ctimeMs = ctimeMs;
this.birthtimeMs = birthtimeMs;
this.atime = new Date(atimeMs);
this.mtime = new Date(mtimeMs);
this.ctime = new Date(ctimeMs);
this.birthtime = new Date(birthtimeMs);
}
isDirectory() {
return (this.mode & constants.S_IFMT) === constants.S_IFDIR;
}
isFile() {
return (this.mode & constants.S_IFMT) === constants.S_IFREG;
}
isBlockDevice() {
return (this.mode & constants.S_IFMT) === constants.S_IFBLK;
}
isCharacterDevice() {
return (this.mode & constants.S_IFMT) === constants.S_IFCHR;
}
isFIFO() {
return (this.mode & constants.S_IFMT) === constants.S_IFIFO;
}
isSymbolicLink() {
return (this.mode & constants.S_IFMT) === constants.S_IFLNK;
}
isSocket() {
return (this.mode & constants.S_IFMT) === constants.S_IFSOCK;
}
};
var Dir = class {
constructor(path2, handle, opts = {}) {
const { encoding = "utf8", bufferSize = 32 } = opts;
this.path = path2;
this._encoding = encoding;
this._capacity = bufferSize;
this._buffer = new FIFO();
this._ended = false;
this._handle = handle;
}
async read(cb) {
if (this._buffer.length) return ok(this._buffer.shift(), cb);
if (this._ended) return ok(null, cb);
const req = FileRequest.borrow();
let entries;
let err = null;
try {
req.retain(binding.readdir(req.handle, this._handle, this._capacity));
await req;
entries = binding.requestResultDirents(req.handle);
} catch (e) {
err = new FileError(e.message, {
operation: "readdir",
code: e.code,
path: this.path
});
} finally {
req.return();
}
if (err) return fail(err, cb);
if (entries.length === 0) {
this._ended = true;
return ok(null, cb);
}
for (const entry of entries) {
let name = Buffer.from(entry.name);
if (this._encoding !== "buffer") name = name.toString(this._encoding);
this._buffer.push(new Dirent(this.path, name, entry.type));
}
return ok(this._buffer.shift(), cb);
}
readSync() {
if (this._buffer.length) return this._buffer.shift();
if (this._ended) return null;
const req = FileRequest.borrow();
let entries;
try {
req.retain(binding.readdirSync(req.handle, this._handle, this._capacity));
entries = binding.requestResultDirents(req.handle);
} catch (e) {
throw new FileError(e.message, {
operation: "readdir",
code: e.code,
path: this.path
});
} finally {
req.return();
}
if (entries.length === 0) {
this._ended = true;
return null;
}
for (const entry of entries) {
let name = Buffer.from(entry.name);
if (this._encoding !== "buffer") name = name.toString(this._encoding);
this._buffer.push(new Dirent(this.path, name, entry.type));
}
return this._buffer.shift();
}
async close(cb) {
const req = FileRequest.borrow();
let err = null;
try {
binding.closedir(req.handle, this._handle);
await req;
} catch (e) {
err = new FileError(e.message, {
operation: "closedir",
code: e.code,
path: this.path
});
} finally {
req.return();
}
this._handle = null;
return done(err, cb);
}
closeSync() {
const req = FileRequest.borrow();
try {
binding.closedirSync(req.handle, this._handle);
} catch (e) {
throw new FileError(e.message, {
operation: "closedir",
code: e.code,
path: this.path
});
} finally {
req.return();
}
this._handle = null;
}
[Symbol.dispose]() {
this.closeSync();
}
async [Symbol.asyncDispose]() {
await this.close();
}
*[Symbol.iterator]() {
while (true) {
const entry = this.readSync();
if (entry === null) break;
yield entry;
}
this.closeSync();
}
async *[Symbol.asyncIterator]() {
while (true) {
const entry = await this.read();
if (entry === null) break;
yield entry;
}
await this.close();
}
};
var Dirent = class {
constructor(parentPath, name, type) {
this.parentPath = parentPath;
this.name = name;
this.type = type;
}
isFile() {
return this.type === constants.UV_DIRENT_FILE;
}
isDirectory() {
return this.type === constants.UV_DIRENT_DIR;
}
isSymbolicLink() {
return this.type === constants.UV_DIRENT_LINK;
}
isFIFO() {
return this.type === constants.UV_DIRENT_FIFO;
}
isSocket() {
return this.type === constants.UV_DIRENT_SOCKET;
}
isCharacterDevice() {
return this.type === constants.UV_DIRENT_CHAR;
}
isBlockDevice() {
return this.type === constants.UV_DIRENT_BLOCK;
}
};
var FileReadStream = class extends Readable {
constructor(path2, opts = {}) {
const { eagerOpen = true } = opts;
super({ eagerOpen, ...opts });
this.path = path2;
this.fd = typeof opts.fd === "number" ? opts.fd : -1;
this.flags = opts.flags || "r";
this.mode = opts.mode || 438;
this._offset = opts.start || 0;
this._missing = 0;
if (opts.length) {
this._missing = opts.length;
} else if (typeof opts.end === "number") {
this._missing = opts.end - this._offset + 1;
} else {
this._missing = -1;
}
}
async _open(cb) {
let err;
if (this.fd === -1) {
err = null;
try {
this.fd = await open(this.path, this.flags, this.mode);
} catch (e) {
err = e;
}
if (err) return cb(err);
}
let st;
err = null;
try {
st = await fstat(this.fd);
} catch (e) {
err = e;
}
if (err) return cb(err);
if (this._missing === -1) this._missing = st.size;
if (st.size < this._offset) {
this._offset = st.size;
this._missing = 0;
} else if (st.size < this._offset + this._missing) {
this._missing = st.size - this._offset;
}
cb(null);
}
async _read(size) {
if (this._missing <= 0) return this.push(null);
const data = Buffer.allocUnsafe(Math.min(this._missing, size));
let len;
let err = null;
try {
len = await read(this.fd, data, 0, data.byteLength, this._offset);
} catch (e) {
err = e;
}
if (err) return this.destroy(err);
if (len === 0) return this.push(null);
if (this._missing < len) len = this._missing;
this._missing -= len;
this._offset += len;
this.push(data.subarray(0, len));
}
async _destroy(err, cb) {
if (this.fd === -1) return cb(err);
try {
await close(this.fd);
} catch (e) {
err = err || e;
}
cb(err);
}
};
var FileWriteStream = class extends Writable {
constructor(path2, opts = {}) {
const { eagerOpen = true } = opts;
super({ eagerOpen, ...opts });
this.path = path2;
this.fd = typeof opts.fd === "number" ? opts.fd : -1;
this.flags = opts.flags || "w";
this.mode = opts.mode || 438;
}
async _open(cb) {
if (this.fd !== -1) return cb(null);
let err = null;
try {
this.fd = await open(this.path, this.flags, this.mode);
} catch (e) {
err = e;
}
cb(err);
}
async _writev(batch, cb) {
let err = null;
try {
await writev(
this.fd,
batch.map(({ chunk }) => chunk)
);
} catch (e) {
err = e;
}
cb(err);
}
async _destroy(err, cb) {
if (this.fd === -1) return cb(err);
try {
await close(this.fd);
} catch (e) {
err = err || e;
}
cb(err);
}
};
var Watcher = class extends EventEmitter {
constructor(path2, opts, onchange) {
if (typeof opts === "function") {
onchange = opts;
opts = {};
}
if (!opts) opts = {};
const { persistent = true, recursive = false, encoding = "utf8" } = opts;
super();
this._closed = false;
this._encoding = encoding;
this._handle = binding.watcherInit(path2, recursive, this, this._onevent, this._onclose);
if (!persistent) this.unref();
if (onchange) this.on("change", onchange);
}
close() {
if (this._closed) return;
this._closed = true;
binding.watcherClose(this._handle);
}
ref() {
if (this._handle) binding.watcherRef(this._handle);
return this;
}
unref() {
if (this._handle) binding.watcherUnref(this._handle);
return this;
}
[Symbol.asyncIterator]() {
const buffer = [];
let done2 = false;
let error = null;
let next = null;
this.on("change", (eventType, filename) => {
if (next) {
next.resolve({ done: false, value: { eventType, filename } });
next = null;
} else {
buffer.push({ eventType, filename });
}
}).on("error", (err) => {
done2 = true;
error = err;
if (next) {
next.reject(error);
next = null;
}
}).on("close", () => {
done2 = true;
if (next) {
next.resolve({ done: done2 });
next = null;
}
});
return {
next: () => new Promise((resolve, reject) => {
if (error) return reject(error);
if (buffer.length) return resolve({ done: false, value: buffer.shift() });
if (done2) return resolve({ done: done2 });
next = { resolve, reject };
})
};
}
_onevent(err, events, filename) {
if (err) {
this.close();
this.emit("error", err);
} else {
const path2 = this._encoding === "buffer" ? Buffer.from(filename) : Buffer.from(filename).toString(this._encoding);
if (events & binding.UV_RENAME) {
this.emit("change", "rename", path2);
}
if (events & binding.UV_CHANGE) {
this.emit("change", "change", path2);
}
}
}
_onclose() {
this._handle = null;
this.emit("close");
}
};
exports.access = access;
exports.appendFile = appendFile;
exports.chmod = chmod;
exports.close = close;
exports.copyFile = copyFile;
exports.cp = cp;
exports.exists = exists;
exports.fchmod = fchmod;
exports.fstat = fstat;
exports.ftruncate = ftruncate;
exports.lstat = lstat;
exports.mkdir = mkdir;
exports.open = open;
exports.opendir = opendir;
exports.read = read;
exports.readFile = readFile;
exports.readdir = readdir;
exports.readlink = readlink;
exports.readv = readv;
exports.realpath = realpath;
exports.rename = rename;
exports.rm = rm;
exports.rmdir = rmdir;
exports.stat = stat;
exports.symlink = symlink;
exports.unlink = unlink;
exports.utimes = utimes;
exports.watch = watch;
exports.write = write;
exports.writeFile = writeFile;
exports.writev = writev;
exports.accessSync = accessSync;
exports.appendFileSync = appendFileSync;
exports.chmodSync = chmodSync;
exports.closeSync = closeSync;
exports.copyFileSync = copyFileSync;
exports.cpSync = cpSync;
exports.existsSync = existsSync;
exports.fchmodSync = fchmodSync;
exports.fstatSync = fstatSync;
exports.ftruncateSync = ftruncateSync;
exports.lstatSync = lstatSync;
exports.mkdirSync = mkdirSync;
exports.openSync = openSync;
exports.opendirSync = opendirSync;
exports.readFileSync = readFileSync;
exports.readSync = readSync;
exports.readdirSync = readdirSync;
exports.readlinkSync = readlinkSync;
exports.readvSync = readvSync;
exports.realpathSync = realpathSync;
exports.renameSync = renameSync;
exports.rmSync = rmSync;
exports.rmdirSync = rmdirSync;
exports.statSync = statSync;
exports.symlinkSync = symlinkSync;
exports.unlinkSync = unlinkSync;
exports.utimesSync = utimesSync;
exports.writeFileSync = writeFileSync;
exports.writeSync = writeSync;
exports.writevSync = writevSync;
exports.promises = require_promises();
exports.Stats = Stats;
exports.Dir = Dir;
exports.Dirent = Dirent;
exports.Watcher = Watcher;
exports.ReadStream = FileReadStream;
exports.createReadStream = function createReadStream(path2, opts) {
return new FileReadStream(path2, opts);
};
exports.WriteStream = FileWriteStream;
exports.createWriteStream = function createWriteStream(path2, opts) {
return new FileWriteStream(path2, opts);
};
function toNamespacedPath(filepath) {
if (typeof filepath !== "string") {
if (isURL(filepath)) filepath = fileURLToPath(filepath);
else filepath = filepath.toString();
}
return path.toNamespacedPath(filepath);
}
function toFlags(flags) {
switch (flags) {
case "r":
return constants.O_RDONLY;
case "rs":
// Fall through.
case "sr":
return constants.O_RDONLY | constants.O_SYNC;
case "r+":
return constants.O_RDWR;
case "rs+":
// Fall through.
case "sr+":
return constants.O_RDWR | constants.O_SYNC;
case "w":
return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY;
case "wx":
// Fall through.
case "xw":
return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL;
case "w+":
return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR;
case "wx+":
// Fall through.
case "xw+":
return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL;
case "a":
return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY;
case "ax":
// Fall through.
case "xa":
return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL;
case "as":
// Fall through.
case "sa":
return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC;
case "a+":
return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR;
case "ax+":
// Fall through.
case "xa+":
return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL;
case "as+":
// Fall through.
case "sa+":
return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC;
default:
return 0;
}
}
function toMode(mode) {
return parseInt(mode, 8);
}
}
});
// ../bare-os-openssh/vendor/bare-node-shims/bare-node-fs/index.js
var require_bare_node_fs = __commonJS({
"../bare-os-openssh/vendor/bare-node-shims/bare-node-fs/index.js"(exports, module) {
module.exports = require_bare_fs();
}
});
// ../../node_modules/bare-semver/lib/constants.js
var require_constants4 = __commonJS({
"../../node_modules/bare-semver/lib/constants.js"(exports, module) {
module.exports = {
EQ: 1,
LT: 2,
LTE: 3,
GT: 4,
GTE: 5
};
}
});
// ../../node_modules/bare-semver/lib/errors.js
var require_errors5 = __commonJS({
"../../node_modules/bare-semver/lib/errors.js"(exports, module) {
module.exports = class SemVerError extends Error {
constructor(msg, code, fn = SemVerError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "SemVerError";
}
static INVALID_VERSION(msg, fn = SemVerError.INVALID_VERSION) {
return new SemVerError(msg, "INVALID_VERSION", fn);
}
static INVALID_RANGE(msg, fn = SemVerError.INVALID_RANGE) {
return new SemVerError(msg, "INVALID_RANGE", fn);
}
};
}
});
// ../../node_modules/bare-semver/lib/version.js
var require_version = __commonJS({
"../../node_modules/bare-semver/lib/version.js"(exports, module) {
var errors = require_errors5();
var Version = class {
constructor(major, minor, patch, opts = {}) {
const { prerelease = [], build = [] } = opts;
this.major = major;
this.minor = minor;
this.patch = patch;
this.prerelease = prerelease;
this.build = build;
}
compare(version) {
return exports.compare(this, version);
}
toString() {
let result = `${this.major}.${this.minor}.${this.patch}`;
if (this.prerelease.length) {
result += "-" + this.prerelease.join(".");
}
if (this.build.length) {
result += "+" + this.build.join(".");
}
return result;
}
};
module.exports = exports = Version;
exports.parse = function parse(input, state = { position: 0, partial: false, range: false }) {
let i = state.position;
let c;
const unexpected = (expected) => {
let msg;
if (i >= input.length) {
msg = `Unexpected end of input in '${input}'`;
} else {
msg = `Unexpected token '${input[i]}' in '${input}' at position ${i}`;
}
if (expected) msg += `, ${expected}`;
throw errors.INVALID_VERSION(msg, unexpected);
};
const components = [0, 0, 0];
let k = 0;
while (k < 3) {
c = input[i];
if (k > 0) {
if (c === ".") c = input[++i];
else if (state.range) break;
else unexpected("expected '.'");
}
if (c === "0") {
i++;
k++;
} else if (c >= "1" && c <= "9") {
let j = 0;
do
c = input[i + ++j];
while (c >= "0" && c <= "9");
components[k++] = parseInt(input.substring(i, i + j));
i += j;
} else unexpected("expected /[0-9]/");
}
const prerelease = [];
if (k === 3 && input[i] === "-") {
i++;
while (true) {
c = input[i];
let tag = "";
let j = 0;
while (c >= "0" && c <= "9") c = input[i + ++j];
let isNumeric = false;
if (j) {
tag += input.substring(i, i + j);
c = input[i += j];
isNumeric = tag[0] !== "0" || tag.length === 1;
}
j = 0;
while (c >= "0" && c <= "9" || c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c === "-")
c = input[i + ++j];
if (j) {
tag += input.substring(i, i + j);
c = input[i += j];
} else if (!isNumeric) unexpected("expected /[a-zA-Z-]/");
prerelease.push(tag);
if (c === ".") c = input[++i];
else break;
}
}
const build = [];
if (k === 3 && input[i] === "+") {
i++;
while (true) {
c = input[i];
let tag = "";
let j = 0;
while (c >= "0" && c <= "9" || c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c === "-")
c = input[i + ++j];
if (j) {
tag += input.substring(i, i + j);
c = input[i += j];
} else unexpected("expected /[0-9a-zA-Z-]/");
build.push(tag);
if (c === ".") c = input[++i];
else break;
}
}
if (i < input.length && state.partial === false) {
unexpected("expected end of input");
}
state.position = i;
return new Version(...components, { prerelease, build });
};
var integer = /^[0-9]+$/;
exports.compare = function compare(a, b) {
if (a.major > b.major) return 1;
if (a.major < b.major) return -1;
if (a.minor > b.minor) return 1;
if (a.minor < b.minor) return -1;
if (a.patch > b.patch) return 1;
if (a.patch < b.patch) return -1;
if (a.prerelease.length === 0) return b.prerelease.length === 0 ? 0 : 1;
if (b.prerelease.length === 0) return -1;
let i = 0;
do {
let x = a.prerelease[i];
let y = b.prerelease[i];
if (x === void 0) return y === void 0 ? 0 : -1;
if (y === void 0) return 1;
if (x === y) continue;
const xInt = integer.test(x);
const yInt = integer.test(y);
if (xInt && yInt) {
x = +x;
y = +y;
} else {
if (xInt) return -1;
if (yInt) return 1;
}
return x > y ? 1 : -1;
} while (++i);
};
}
});
// ../../node_modules/bare-semver/lib/comparator.js
var require_comparator = __commonJS({
"../../node_modules/bare-semver/lib/comparator.js"(exports, module) {
var constants = require_constants4();
var symbols = {
[constants.EQ]: "=",
[constants.LT]: "<",
[constants.LTE]: "<=",
[constants.GT]: ">",
[constants.GTE]: ">="
};
module.exports = class Comparator {
constructor(operator, version) {
this.operator = operator;
this.version = version;
}
test(version) {
const result = version.compare(this.version);
switch (this.operator) {
case constants.LT:
return result < 0;
case constants.LTE:
return result <= 0;
case constants.GT:
return result > 0;
case constants.GTE:
return result >= 0;
default:
return result === 0;
}
}
toString() {
return symbols[this.operator] + this.version;
}
};
}
});
// ../../node_modules/bare-semver/lib/range.js
var require_range = __commonJS({
"../../node_modules/bare-semver/lib/range.js"(exports, module) {
var constants = require_constants4();
var errors = require_errors5();
var Version = require_version();
var Comparator = require_comparator();
var Range = class {
constructor(comparators = []) {
this.comparators = comparators;
}
test(version) {
for (const set of this.comparators) {
let matches = true;
for (const comparator of set) {
if (comparator.test(version)) continue;
matches = false;
break;
}
if (matches) return true;
}
return false;
}
toString() {
let result = "";
let first = true;
for (const set of this.comparators) {
if (first) first = false;
else result += " || ";
result += set.join(" ");
}
return result;
}
};
module.exports = exports = Range;
exports.parse = function parse(input, state = { position: 0, partial: false }) {
let i = state.position;
let c;
const unexpected = (expected) => {
let msg;
if (i >= input.length) {
msg = `Unexpected end of input in '${input}'`;
} else {
msg = `Unexpected token '${input[i]}' in '${input}' at position ${i}`;
}
if (expected) msg += `, ${expected}`;
throw errors.INVALID_VERSION(msg, unexpected);
};
const comparators = [];
while (i < input.length) {
const set = [];
while (i < input.length) {
c = input[i];
let operator = constants.EQ;
if (c === "<") {
operator = constants.LT;
c = input[++i];
if (c === "=") {
operator = constants.LTE;
c = input[++i];
}
} else if (c === ">") {
operator = constants.GT;
c = input[++i];
if (c === "=") {
operator = constants.GTE;
c = input[++i];
}
} else if (c === "=") {
c = input[++i];
}
const state2 = { position: i, partial: true, range: true };
set.push(new Comparator(operator, Version.parse(input, state2)));
c = input[i = state2.position];
while (c === " ") c = input[++i];
if (c === "|" && input[i + 1] === "|") {
c = input[i += 2];
while (c === " ") c = input[++i];
break;
}
if (c && c !== "<" && c !== ">") unexpected("expected '||', '<', or '>'");
}
if (set.length) comparators.push(set);
}
if (i < input.length && state.partial === false) {
unexpected("expected end of input");
}
state.position = i;
return new Range(comparators);
};
}
});
// ../../node_modules/bare-semver/index.js
var require_bare_semver = __commonJS({
"../../node_modules/bare-semver/index.js"(exports) {
exports.constants = require_constants4();
exports.errors = require_errors5();
var Version = exports.Version = require_version();
var Range = exports.Range = require_range();
exports.Comparator = require_comparator();
exports.satisfies = function satisfies(version, range) {
if (typeof version === "string") version = Version.parse(version);
if (typeof range === "string") range = Range.parse(range);
return range.test(version);
};
}
});
// ../../node_modules/bare-module-resolve/lib/errors.js
var require_errors6 = __commonJS({
"../../node_modules/bare-module-resolve/lib/errors.js"(exports, module) {
module.exports = class ModuleResolveError extends Error {
constructor(msg, code, fn = ModuleResolveError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "ModuleResolveError";
}
static INVALID_MODULE_SPECIFIER(msg) {
return new ModuleResolveError(
msg,
"INVALID_MODULE_SPECIFIER",
ModuleResolveError.INVALID_MODULE_SPECIFIER
);
}
static INVALID_PACKAGE_TARGET(msg) {
return new ModuleResolveError(
msg,
"INVALID_PACKAGE_TARGET",
ModuleResolveError.INVALID_PACKAGE_TARGET
);
}
static PACKAGE_PATH_NOT_EXPORTED(msg) {
return new ModuleResolveError(
msg,
"PACKAGE_PATH_NOT_EXPORTED",
ModuleResolveError.PACKAGE_PATH_NOT_EXPORTED
);
}
static PACKAGE_IMPORT_NOT_DEFINED(msg) {
return new ModuleResolveError(
msg,
"PACKAGE_IMPORT_NOT_DEFINED",
ModuleResolveError.PACKAGE_IMPORT_NOT_DEFINED
);
}
static UNSUPPORTED_ENGINE(msg) {
return new ModuleResolveError(msg, "UNSUPPORTED_ENGINE", ModuleResolveError.UNSUPPORTED_ENGINE);
}
};
}
});
// ../../node_modules/bare-module-resolve/index.js
var require_bare_module_resolve = __commonJS({
"../../node_modules/bare-module-resolve/index.js"(exports, module) {
var { satisfies } = require_bare_semver();
var errors = require_errors6();
module.exports = exports = function resolve(specifier, parentURL, opts, readPackage) {
if (typeof opts === "function") {
readPackage = opts;
opts = {};
} else if (typeof readPackage !== "function") {
readPackage = defaultReadPackage;
}
return {
*[Symbol.iterator]() {
const generator = exports.module(specifier, parentURL, opts);
let next = generator.next();
while (next.done !== true) {
const value = next.value;
if (value.package) {
next = generator.next(readPackage(value.package));
} else {
next = generator.next(yield value.resolution);
}
}
return next.value;
},
async *[Symbol.asyncIterator]() {
const generator = exports.module(specifier, parentURL, opts);
let next = generator.next();
while (next.done !== true) {
const value = next.value;
if (value.package) {
next = generator.next(await readPackage(value.package));
} else {
next = generator.next(yield value.resolution);
}
}
return next.value;
}
};
};
function defaultReadPackage() {
return null;
}
var UNRESOLVED = 0;
var YIELDED = 1;
var RESOLVED = YIELDED | 2;
exports.constants = {
UNRESOLVED,
YIELDED,
RESOLVED
};
exports.module = function* (specifier, parentURL, opts = {}) {
const { resolutions = null, imports = null } = opts;
if (exports.startsWithWindowsDriveLetter(specifier)) {
specifier = "/" + specifier;
}
let status;
if (resolutions) {
status = yield* exports.preresolved(specifier, resolutions, parentURL, opts);
if (status) return status;
}
status = yield* exports.url(specifier, parentURL, opts);
if (status) return status;
status = yield* exports.packageImports(specifier, parentURL, opts);
if (status) return status;
if (specifier === "." || specifier === ".." || specifier[0] === "/" || specifier[0] === "\\" || specifier.startsWith("./") || specifier.startsWith(".\\") || specifier.startsWith("../") || specifier.startsWith("..\\")) {
if (imports) {
status = yield* exports.packageImportsExports(specifier, imports, parentURL, true, opts);
if (status) return status;
}
status = yield* exports.deferred(specifier, opts);
if (status) return status;
status = yield* exports.file(specifier, parentURL, false, opts);
if (status === RESOLVED) return status;
return yield* exports.directory(specifier, parentURL, opts);
}
return yield* exports.package(specifier, parentURL, opts);
};
exports.url = function* (url, parentURL, opts = {}) {
const { imports = null, deferredProtocol = "deferred:", resolutions = null } = opts;
let resolution;
try {
resolution = new URL(url);
} catch {
return UNRESOLVED;
}
if (imports) {
const status = yield* exports.packageImportsExports(
resolution.href,
imports,
parentURL,
true,
opts
);
if (status) return status;
}
if (resolution.protocol === deferredProtocol) {
const specifier = resolution.pathname;
if (resolutions) {
const imports2 = resolutions[parentURL.href];
if (typeof imports2 === "object" && imports2 !== null) {
opts = {
...opts,
resolutions: { ...resolutions, [parentURL.href]: { ...imports2, [specifier]: null } }
};
}
}
return yield* exports.module(specifier, parentURL, opts);
}
if (resolution.protocol === "node:") {
const specifier = resolution.pathname;
if (specifier === "." || specifier === ".." || specifier[0] === "/" || specifier.startsWith("./") || specifier.startsWith("../")) {
throw errors.INVALID_MODULE_SPECIFIER(`Module specifier '${url}' is not a valid package name`);
}
return yield* exports.package(specifier, parentURL, opts);
}
const resolved = yield { resolution };
return resolved ? RESOLVED : YIELDED;
};
exports.preresolved = function* (specifier, resolutions, parentURL, opts = {}) {
const imports = resolutions[parentURL.href];
if (typeof imports === "object" && imports !== null) {
return yield* exports.packageImportsExports(specifier, imports, parentURL, true, opts);
}
return UNRESOLVED;
};
exports.deferred = function* (specifier, opts = {}) {
const { deferredProtocol = "deferred:", defer = [] } = opts;
if (defer.includes(specifier)) {
const resolved = yield { resolution: new URL(deferredProtocol + specifier) };
return resolved ? RESOLVED : YIELDED;
}
return UNRESOLVED;
};
exports.package = function* (packageSpecifier, parentURL, opts = {}) {
const { builtins = [] } = opts;
if (packageSpecifier === "") {
throw errors.INVALID_MODULE_SPECIFIER(
`Module specifier '${packageSpecifier}' is not a valid package name`
);
}
let packageName;
if (packageSpecifier[0] !== "@") {
packageName = packageSpecifier.split("/", 1).join();
} else {
if (!packageSpecifier.includes("/")) {
throw errors.INVALID_MODULE_SPECIFIER(
`Module specifier '${packageSpecifier}' is not a valid package name`
);
}
packageName = packageSpecifier.split("/", 2).join("/");
}
if (packageName[0] === "." || packageName.includes("\\") || packageName.includes("%")) {
throw errors.INVALID_MODULE_SPECIFIER(
`Module specifier '${packageSpecifier}' is not a valid package name`
);
}
let status;
status = yield* exports.builtinTarget(packageSpecifier, null, builtins, opts);
if (status) return status;
status = yield* exports.deferred(packageSpecifier, opts);
if (status) return status;
let packageSubpath = "." + packageSpecifier.substring(packageName.length);
status = yield* exports.packageSelf(packageName, packageSubpath, parentURL, opts);
if (status) return status;
parentURL = new URL(parentURL.href);
for (const packageURL of exports.lookupPackageRoot(packageName, parentURL)) {
const info = yield { package: packageURL };
if (info) {
if (info.engines) exports.validateEngines(packageURL, info.engines, opts);
if (info.exports) {
return yield* exports.packageExports(packageURL, packageSubpath, info.exports, opts);
}
if (packageSubpath === ".") {
if (typeof info.main === "string" && info.main !== "") {
packageSubpath = info.main;
} else {
return yield* exports.file("index", packageURL, true, opts);
}
}
status = yield* exports.file(packageSubpath, packageURL, false, opts);
if (status === RESOLVED) return status;
return yield* exports.directory(packageSubpath, packageURL, opts);
}
}
return UNRESOLVED;
};
exports.packageSelf = function* (packageName, packageSubpath, parentURL, opts = {}) {
for (const packageURL of exports.lookupPackageScope(parentURL, opts)) {
const info = yield { package: packageURL };
if (info) {
if (info.name !== packageName) return false;
if (info.exports) {
return yield* exports.packageExports(packageURL, packageSubpath, info.exports, opts);
}
if (packageSubpath === ".") {
if (typeof info.main === "string" && info.main !== "") {
packageSubpath = info.main;
} else {
return yield* exports.file("index", packageURL, true, opts);
}
}
const status = yield* exports.file(packageSubpath, packageURL, false, opts);
if (status === RESOLVED) return status;
return yield* exports.directory(packageSubpath, packageURL, opts);
}
}
return UNRESOLVED;
};
exports.packageExports = function* (packageURL, subpath, packageExports, opts = {}) {
if (subpath === ".") {
let mainExport;
if (typeof packageExports === "string" || Array.isArray(packageExports)) {
mainExport = packageExports;
} else if (typeof packageExports === "object" && packageExports !== null) {
const keys = Object.keys(packageExports);
if (keys.some((key) => key.startsWith("."))) {
if ("." in packageExports) mainExport = packageExports["."];
} else {
mainExport = packageExports;
}
}
if (mainExport) {
const status = yield* exports.packageTarget(packageURL, mainExport, null, false, opts);
if (status) return status;
}
} else if (typeof packageExports === "object" && packageExports !== null) {
const keys = Object.keys(packageExports);
if (keys.every((key) => key.startsWith("."))) {
const status = yield* exports.packageImportsExports(
subpath,
packageExports,
packageURL,
false,
opts
);
if (status) return status;
}
}
throw errors.PACKAGE_PATH_NOT_EXPORTED(
`Package subpath '${subpath}' is not defined by "exports" in '${packageURL}'`
);
};
exports.packageImports = function* (specifier, parentURL, opts = {}) {
const { imports = null } = opts;
if (specifier === "#" || specifier.startsWith("#/")) {
throw errors.INVALID_MODULE_SPECIFIER(
`Module specifier '${specifier}' is not a valid internal imports specifier`
);
}
for (const packageURL of exports.lookupPackageScope(parentURL, opts)) {
const info = yield { package: packageURL };
if (info) {
if (info.imports) {
const status = yield* exports.packageImportsExports(
specifier,
info.imports,
packageURL,
true,
opts
);
if (status) return status;
}
if (specifier.startsWith("#")) {
throw errors.PACKAGE_IMPORT_NOT_DEFINED(
`Package import specifier '${specifier}' is not defined by "imports" in '${packageURL}'`
);
}
break;
}
}
if (imports) {
const status = yield* exports.packageImportsExports(specifier, imports, parentURL, true, opts);
if (status) return status;
}
return UNRESOLVED;
};
exports.packageImportsExports = function* (matchKey, matchObject, packageURL, isImports, opts = {}) {
if (matchKey in matchObject && !matchKey.includes("*")) {
const target = matchObject[matchKey];
return yield* exports.packageTarget(packageURL, target, null, isImports, opts);
}
const expansionKeys = Object.keys(matchObject).filter((key) => key.includes("*")).sort(exports.patternKeyCompare);
for (const expansionKey of expansionKeys) {
const patternIndex = expansionKey.indexOf("*");
const patternBase = expansionKey.substring(0, patternIndex);
if (matchKey.startsWith(patternBase) && matchKey !== patternBase) {
const patternTrailer = expansionKey.substring(patternIndex + 1);
if (patternTrailer === "" || matchKey.endsWith(patternTrailer) && matchKey.length >= expansionKey.length) {
const target = matchObject[expansionKey];
const patternMatch = matchKey.substring(
patternBase.length,
matchKey.length - patternTrailer.length
);
return yield* exports.packageTarget(packageURL, target, patternMatch, isImports, opts);
}
}
}
return UNRESOLVED;
};
exports.validateEngines = function validateEngines(packageURL, packageEngines, opts = {}) {
const { engines = {} } = opts;
for (const [engine, range] of Object.entries(packageEngines)) {
if (engine in engines) {
const version = engines[engine];
if (!satisfies(version, range)) {
throw errors.UNSUPPORTED_ENGINE(
`Package not compatible with engine '${engine}' ${version}, requires range '${range}' defined by "engines" in '${packageURL}'`
);
}
}
}
};
exports.patternKeyCompare = function patternKeyCompare(keyA, keyB) {
const patternIndexA = keyA.indexOf("*");
const patternIndexB = keyB.indexOf("*");
const baseLengthA = patternIndexA === -1 ? keyA.length : patternIndexA + 1;
const baseLengthB = patternIndexB === -1 ? keyB.length : patternIndexB + 1;
if (baseLengthA > baseLengthB) return -1;
if (baseLengthB > baseLengthA) return 1;
if (patternIndexA === -1) return 1;
if (patternIndexB === -1) return -1;
if (keyA.length > keyB.length) return -1;
if (keyB.length > keyA.length) return 1;
return 0;
};
exports.packageTarget = function* (packageURL, target, patternMatch, isImports, opts = {}) {
const { conditions = [], matchedConditions = [] } = opts;
if (typeof target === "string") {
if (!target.startsWith("./") && !isImports) {
throw errors.INVALID_PACKAGE_TARGET(
`Invalid target '${target}' defined by "exports" in '${packageURL}'`
);
}
if (patternMatch !== null) {
target = target.replaceAll("*", patternMatch);
}
const status = yield* exports.url(target, packageURL, opts);
if (status) return status;
if (target === "." || target === ".." || target[0] === "/" || target.startsWith("./") || target.startsWith("../")) {
const resolved = yield { resolution: new URL(target, packageURL) };
return resolved ? RESOLVED : YIELDED;
}
return yield* exports.package(target, packageURL, opts);
}
if (Array.isArray(target)) {
for (const targetValue of target) {
const status = yield* exports.packageTarget(
packageURL,
targetValue,
patternMatch,
isImports,
opts
);
if (status) return status;
}
} else if (typeof target === "object" && target !== null) {
let status = UNRESOLVED;
for (const [condition, targetValue, subset] of exports.conditionMatches(
target,
conditions,
opts
)) {
matchedConditions.push(condition);
status |= yield* exports.packageTarget(packageURL, targetValue, patternMatch, isImports, {
...opts,
conditions: subset
});
matchedConditions.pop();
}
if (status) return status;
}
return UNRESOLVED;
};
exports.builtinTarget = function* (packageSpecifier, packageVersion, target, opts = {}) {
const { builtinProtocol = "builtin:", conditions = [], matchedConditions = [] } = opts;
if (typeof target === "string") {
const targetParts = target.split("@");
let targetName;
let targetVersion;
if (target[0] !== "@") {
targetName = targetParts[0];
targetVersion = targetParts[1] || null;
} else {
targetName = targetParts.slice(0, 2).join("@");
targetVersion = targetParts[2] || null;
}
if (packageSpecifier === targetName) {
if (packageVersion === null && targetVersion === null) {
const resolved = yield {
resolution: new URL(builtinProtocol + packageSpecifier)
};
return resolved ? RESOLVED : YIELDED;
}
let version = null;
if (packageVersion === null) {
version = targetVersion;
} else if (targetVersion === null || packageVersion === targetVersion) {
version = packageVersion;
}
if (version !== null) {
const resolved = yield {
resolution: new URL(builtinProtocol + packageSpecifier + "@" + version)
};
return resolved ? RESOLVED : YIELDED;
}
}
} else if (Array.isArray(target)) {
for (const targetValue of target) {
const status = yield* exports.builtinTarget(
packageSpecifier,
packageVersion,
targetValue,
opts
);
if (status) return status;
}
} else if (typeof target === "object" && target !== null) {
let status = UNRESOLVED;
for (const [condition, targetValue, subset] of exports.conditionMatches(
target,
conditions,
opts
)) {
matchedConditions.push(condition);
status |= yield* exports.builtinTarget(packageSpecifier, packageVersion, targetValue, {
...opts,
conditions: subset
});
matchedConditions.pop();
}
if (status) return status;
}
return UNRESOLVED;
};
exports.conditionMatches = function* conditionMatches(target, conditions, opts = {}) {
if (conditions.every((condition) => typeof condition === "string")) {
const keys = Object.keys(target);
for (const condition of keys) {
if (condition === "default" || conditions.includes(condition)) {
yield [condition, target[condition], conditions];
return true;
}
}
return false;
}
let yielded = false;
for (const subset of conditions) {
if (yield* conditionMatches(target, subset, opts)) {
yielded = true;
}
}
return yielded;
};
exports.lookupPackageRoot = function* (packageName, parentURL) {
parentURL = new URL(parentURL.href);
do {
const packageURL = new URL("node_modules/" + packageName + "/", parentURL);
const info = yield new URL("package.json", packageURL);
if (info) return info;
parentURL.pathname = parentURL.pathname.substring(0, parentURL.pathname.lastIndexOf("/"));
if (parentURL.pathname.length === 3 && exports.isWindowsDriveLetter(parentURL.pathname.substring(1))) {
break;
}
} while (parentURL.pathname !== "" && parentURL.pathname !== "/");
return null;
};
exports.lookupPackageScope = function* lookupPackageScope(scopeURL, opts = {}) {
const { resolutions = null } = opts;
if (resolutions) {
for (const { resolution } of exports.preresolved("#package", resolutions, scopeURL, opts)) {
if (resolution) return yield resolution;
}
}
scopeURL = new URL(scopeURL.href);
do {
if (scopeURL.pathname.endsWith("/node_modules")) break;
const info = yield new URL("package.json", scopeURL);
if (info) return info;
scopeURL.pathname = scopeURL.pathname.substring(0, scopeURL.pathname.lastIndexOf("/"));
if (scopeURL.pathname.length === 3 && exports.isWindowsDriveLetter(scopeURL.pathname.substring(1))) {
break;
}
} while (scopeURL.pathname !== "" && scopeURL.pathname !== "/");
return null;
};
exports.file = function* (filename, parentURL, isIndex, opts = {}) {
if (filename === "." || filename === ".." || filename[filename.length - 1] === "/" || filename[filename.length - 1] === "\\") {
return UNRESOLVED;
}
if (parentURL.protocol === "file:" && /%2f|%5c/i.test(filename)) {
throw errors.INVALID_MODULE_SPECIFIER(`Module specifier '${filename}' is invalid`);
}
const { extensions = [] } = opts;
let status = UNRESOLVED;
if (!isIndex) {
if (yield { resolution: new URL(filename, parentURL) }) {
return RESOLVED;
}
status = YIELDED;
}
for (const ext of extensions) {
if (filename.endsWith(ext)) continue;
if (yield { resolution: new URL(filename + ext, parentURL) }) {
return RESOLVED;
}
status = YIELDED;
}
return status;
};
exports.directory = function* (dirname, parentURL, opts = {}) {
let directoryURL;
if (dirname[dirname.length - 1] === "/" || dirname[dirname.length - 1] === "\\") {
directoryURL = new URL(dirname, parentURL);
} else {
directoryURL = new URL(dirname + "/", parentURL);
}
const info = yield { package: new URL("package.json", directoryURL) };
if (info) {
if (info.exports) {
return yield* exports.packageExports(directoryURL, ".", info.exports, opts);
}
if (typeof info.main === "string" && info.main !== "") {
const status = yield* exports.file(info.main, directoryURL, false, opts);
if (status === RESOLVED) return status;
return yield* exports.directory(info.main, directoryURL, opts);
}
}
return yield* exports.file("index", directoryURL, true, opts);
};
function isASCIIUpperAlpha(c) {
return c >= 65 && c <= 90;
}
function isASCIILowerAlpha(c) {
return c >= 97 && c <= 122;
}
function isASCIIAlpha(c) {
return isASCIIUpperAlpha(c) || isASCIILowerAlpha(c);
}
exports.isWindowsDriveLetter = function isWindowsDriveLetter(input) {
return input.length >= 2 && isASCIIAlpha(input.charCodeAt(0)) && (input.charCodeAt(1) === 58 || input.charCodeAt(1) === 124);
};
exports.startsWithWindowsDriveLetter = function startsWithWindowsDriveLetter(input) {
return input.length >= 2 && exports.isWindowsDriveLetter(input) && (input.length === 2 || input.charCodeAt(2) === 47 || input.charCodeAt(2) === 92 || input.charCodeAt(2) === 63 || input.charCodeAt(2) === 35);
};
}
});
// ../../node_modules/bare-addon-resolve/lib/errors.js
var require_errors7 = __commonJS({
"../../node_modules/bare-addon-resolve/lib/errors.js"(exports, module) {
module.exports = class AddonResolveError extends Error {
constructor(msg, code, fn = AddonResolveError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "AddonResolveError";
}
static INVALID_ADDON_SPECIFIER(msg) {
return new AddonResolveError(
msg,
"INVALID_ADDON_SPECIFIER",
AddonResolveError.INVALID_ADDON_SPECIFIER
);
}
static INVALID_PACKAGE_NAME(msg) {
return new AddonResolveError(
msg,
"INVALID_PACKAGE_NAME",
AddonResolveError.INVALID_PACKAGE_NAME
);
}
};
}
});
// ../../node_modules/bare-addon-resolve/index.js
var require_bare_addon_resolve = __commonJS({
"../../node_modules/bare-addon-resolve/index.js"(exports, module) {
var resolve = require_bare_module_resolve();
var { Version } = require_bare_semver();
var errors = require_errors7();
module.exports = exports = function resolve2(specifier, parentURL, opts, readPackage) {
if (typeof opts === "function") {
readPackage = opts;
opts = {};
} else if (typeof readPackage !== "function") {
readPackage = defaultReadPackage;
}
return {
*[Symbol.iterator]() {
const generator = exports.addon(specifier, parentURL, opts);
let next = generator.next();
while (next.done !== true) {
const value = next.value;
if (value.package) {
next = generator.next(readPackage(value.package));
} else {
next = generator.next(yield value.resolution);
}
}
return next.value;
},
async *[Symbol.asyncIterator]() {
const generator = exports.addon(specifier, parentURL, opts);
let next = generator.next();
while (next.done !== true) {
const value = next.value;
if (value.package) {
next = generator.next(await readPackage(value.package));
} else {
next = generator.next(yield value.resolution);
}
}
return next.value;
}
};
};
function defaultReadPackage() {
return null;
}
var { UNRESOLVED, YIELDED, RESOLVED } = resolve.constants;
exports.constants = {
UNRESOLVED,
YIELDED,
RESOLVED
};
exports.addon = function* (specifier, parentURL, opts = {}) {
const { resolutions = null } = opts;
if (exports.startsWithWindowsDriveLetter(specifier)) {
specifier = "/" + specifier;
}
let status;
if (resolutions) {
status = yield* resolve.preresolved(specifier, resolutions, parentURL, opts);
if (status) return status;
}
status = yield* exports.url(specifier, parentURL, opts);
if (status) return status;
let version = null;
const i = specifier.lastIndexOf("@");
if (i > 0) {
version = specifier.substring(i + 1);
try {
Version.parse(version);
specifier = specifier.substring(0, i);
} catch {
version = null;
}
}
if (specifier === "." || specifier === ".." || specifier[0] === "/" || specifier[0] === "\\" || specifier.startsWith("./") || specifier.startsWith(".\\") || specifier.startsWith("../") || specifier.startsWith("..\\")) {
status = yield* exports.file(specifier, parentURL, opts);
if (status === RESOLVED) return status;
return yield* exports.directory(specifier, version, parentURL, opts);
}
return yield* exports.package(specifier, version, parentURL, opts);
};
exports.url = function* (url, parentURL, opts = {}) {
let resolution;
try {
resolution = new URL(url);
} catch {
return UNRESOLVED;
}
const resolved = yield { resolution };
return resolved ? RESOLVED : YIELDED;
};
exports.package = function* (packageSpecifier, packageVersion, parentURL, opts = {}) {
if (packageSpecifier === "") {
throw errors.INVALID_ADDON_SPECIFIER(
`Addon specifier '${packageSpecifier}' is not a valid package name`
);
}
let packageName;
if (packageSpecifier[0] !== "@") {
packageName = packageSpecifier.split("/", 1).join();
} else {
if (!packageSpecifier.includes("/")) {
throw errors.INVALID_ADDON_SPECIFIER(
`Addon specifier '${packageSpecifier}' is not a valid package name`
);
}
packageName = packageSpecifier.split("/", 2).join("/");
}
if (packageName[0] === "." || packageName.includes("\\") || packageName.includes("%")) {
throw errors.INVALID_ADDON_SPECIFIER(
`Addon specifier '${packageSpecifier}' is not a valid package name`
);
}
const packageSubpath = "." + packageSpecifier.substring(packageName.length);
const status = yield* exports.packageSelf(
packageName,
packageSubpath,
packageVersion,
parentURL,
opts
);
if (status) return status;
parentURL = new URL(parentURL.href);
do {
const packageURL = new URL("node_modules/" + packageName + "/", parentURL);
parentURL.pathname = parentURL.pathname.substring(0, parentURL.pathname.lastIndexOf("/"));
const info = yield { package: new URL("package.json", packageURL) };
if (info) {
return yield* exports.directory(packageSubpath, packageVersion, packageURL, opts);
}
} while (parentURL.pathname !== "" && parentURL.pathname !== "/");
return UNRESOLVED;
};
exports.packageSelf = function* (packageName, packageSubpath, packageVersion, parentURL, opts = {}) {
for (const packageURL of resolve.lookupPackageScope(parentURL, opts)) {
const info = yield { package: packageURL };
if (info) {
if (info.name === packageName) {
return yield* exports.directory(packageSubpath, packageVersion, packageURL, opts);
}
break;
}
}
return UNRESOLVED;
};
exports.lookupPrebuildsScope = function* lookupPrebuildsScope(url, opts = {}) {
const scopeURL = new URL(url.href);
do {
yield new URL("prebuilds/", scopeURL);
scopeURL.pathname = scopeURL.pathname.substring(0, scopeURL.pathname.lastIndexOf("/"));
if (scopeURL.pathname.length === 3 && exports.isWindowsDriveLetter(scopeURL.pathname.substring(1))) {
break;
}
} while (scopeURL.pathname !== "" && scopeURL.pathname !== "/");
};
exports.file = function* (filename, parentURL, opts = {}) {
if (filename === "." || filename === ".." || filename[filename.length - 1] === "/" || filename[filename.length - 1] === "\\") {
return UNRESOLVED;
}
if (parentURL.protocol === "file:" && /%2f|%5c/i.test(filename)) {
throw errors.INVALID_ADDON_SPECIFIER(`Addon specifier '${filename}' is invalid`);
}
const { extensions = [] } = opts;
let status = UNRESOLVED;
for (let ext of extensions) {
if (filename.endsWith(ext)) ext = "";
if (yield { resolution: new URL(filename + ext, parentURL) }) {
return RESOLVED;
}
status = YIELDED;
}
return status;
};
exports.directory = function* (dirname, version, parentURL, opts = {}) {
const {
host = null,
// Shorthand for single host resolution
hosts = host !== null ? [host] : [],
builtins = [],
matchedConditions = []
} = opts;
let directoryURL;
if (dirname[dirname.length - 1] === "/" || dirname[dirname.length - 1] === "\\") {
directoryURL = new URL(dirname, parentURL);
} else {
directoryURL = new URL(dirname + "/", parentURL);
}
const unversioned = version === null;
let name = null;
const info = yield { package: new URL("package.json", directoryURL) };
if (info) {
if (typeof info.name === "string" && info.name !== "") {
if (info.name.includes("__")) {
throw errors.INVALID_PACKAGE_NAME(`Package name '${info.name}' is invalid`);
}
name = info.name.replace(/\//g, "__").replace(/^@/, "");
} else {
return UNRESOLVED;
}
if (typeof info.version === "string" && info.version !== "") {
if (version !== null && info.version !== version) return UNRESOLVED;
version = info.version;
}
} else {
return UNRESOLVED;
}
let status;
status = yield* resolve.builtinTarget(name, version, builtins, opts);
if (status) return status;
for (const prebuildsURL of exports.lookupPrebuildsScope(directoryURL, opts)) {
status = UNRESOLVED;
for (const host2 of hosts) {
const conditions = host2.split("-");
const universal = supportsUniversalPrebuilds(host2) ? conditions.with(1, "universal").join("-") : null;
matchedConditions.push(...conditions);
if (version !== null) {
status |= yield* exports.file(host2 + "/" + name + "@" + version, prebuildsURL, opts);
if (universal) {
status |= yield* exports.file(universal + "/" + name + "@" + version, prebuildsURL, opts);
}
}
if (unversioned) {
status |= yield* exports.file(host2 + "/" + name, prebuildsURL, opts);
if (universal) {
status |= yield* exports.file(universal + "/" + name, prebuildsURL, opts);
}
}
for (const _ of conditions) matchedConditions.pop();
}
if (status === RESOLVED) return status;
}
return yield* exports.linked(name, version, opts);
};
exports.linked = function* (name, version = null, opts = {}) {
const {
linked = true,
host = null,
// Shorthand for single host resolution
hosts = host !== null ? [host] : [],
matchedConditions = []
} = opts;
if (linked === false || hosts.length === 0) return UNRESOLVED;
let status = UNRESOLVED;
for (const host2 of hosts) {
const [platform = null] = host2.split("-", 1);
if (platform === null) continue;
matchedConditions.push(platform);
status |= yield* platformArtefact(name, version, platform, opts);
matchedConditions.pop();
}
return status;
};
function* platformArtefact(name, version = null, platform, opts = {}) {
const { linkedProtocol = "linked:" } = opts;
if (platform === "darwin" || platform === "ios") {
if (version !== null) {
if (yield {
resolution: new URL(`${linkedProtocol}${name}.${version}.framework/${name}.${version}`)
}) {
return RESOLVED;
}
if (platform === "darwin") {
if (yield {
resolution: new URL(`${linkedProtocol}lib${name}.${version}.dylib`)
}) {
return RESOLVED;
}
}
}
if (yield {
resolution: new URL(`${linkedProtocol}${name}.framework/${name}`)
}) {
return RESOLVED;
}
if (platform === "darwin") {
if (yield {
resolution: new URL(`${linkedProtocol}lib${name}.dylib`)
}) {
return RESOLVED;
}
}
return YIELDED;
}
if (platform === "linux" || platform === "android") {
if (version !== null) {
if (yield {
resolution: new URL(`${linkedProtocol}lib${name}.${version}.so`)
}) {
return RESOLVED;
}
}
if (yield {
resolution: new URL(`${linkedProtocol}lib${name}.so`)
}) {
return RESOLVED;
}
return YIELDED;
}
if (platform === "win32") {
if (version !== null) {
if (yield {
resolution: new URL(`${linkedProtocol}${name}-${version}.dll`)
}) {
return RESOLVED;
}
}
if (yield {
resolution: new URL(`${linkedProtocol}${name}.dll`)
}) {
return RESOLVED;
}
}
return UNRESOLVED;
}
exports.isWindowsDriveLetter = resolve.isWindowsDriveLetter;
exports.startsWithWindowsDriveLetter = resolve.startsWithWindowsDriveLetter;
function supportsUniversalPrebuilds(host) {
return host === "darwin-arm64" || host === "darwin-x64" || host === "ios-arm64-simulator" || host === "ios-x64-simulator";
}
}
});
// ../../node_modules/require-addon/lib/node.js
var require_node = __commonJS({
"../../node_modules/require-addon/lib/node.js"(exports, module) {
if (typeof __require.addon === "function") {
module.exports = __require.addon.bind(__require);
} else {
let readPackage2 = function(packageURL) {
try {
return __require(url.fileURLToPath(packageURL));
} catch (err) {
return null;
}
}, isAlpine2 = function() {
return process.platform === "linux" && fs.existsSync("/etc/alpine-release");
};
readPackage = readPackage2, isAlpine = isAlpine2;
const url = require_bare_url();
const fs = require_bare_node_fs();
const resolve = require_bare_addon_resolve();
let host = process.platform + "-" + process.arch;
const conditions = ["addon", "node", process.platform, process.arch];
const extensions = [".node"];
if (isAlpine2()) {
host += "-musl";
conditions.push("musl");
}
module.exports = function addon(specifier, parentURL) {
if (typeof parentURL === "string") parentURL = url.pathToFileURL(parentURL);
const candidates = [];
let cause;
for (const resolution of resolve(
specifier,
parentURL,
{ host, conditions, extensions },
readPackage2
)) {
candidates.push(resolution);
switch (resolution.protocol) {
case "file:":
try {
return __require(url.fileURLToPath(resolution));
} catch (err2) {
cause = err2;
continue;
}
}
}
let message = `Cannot find addon '${specifier}' imported from '${parentURL.href}'`;
if (candidates.length > 0) {
message += "\nCandidates:";
message += "\n" + candidates.map((url2) => "- " + url2.href).join("\n");
}
const err = new Error(message, cause ? { cause } : {});
err.code = "ADDON_NOT_FOUND";
err.specifier = specifier;
err.referrer = parentURL;
err.candidates = candidates;
throw err;
};
}
var readPackage;
var isAlpine;
}
});
// ../../node_modules/udx-native/binding.js
var require_binding4 = __commonJS({
"../../node_modules/udx-native/binding.js"(exports, module) {
__require.addon = require_node();
module.exports = __require.addon(".", __filename);
}
});
// ../../node_modules/udx-native/lib/ip.js
var require_ip = __commonJS({
"../../node_modules/udx-native/lib/ip.js"(exports) {
var v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
var v4Str = `(${v4Seg}[.]){3}${v4Seg}`;
var IPv4Pattern = new RegExp(`^${v4Str}$`);
var v6Seg = "(?:[0-9a-fA-F]{1,4})";
var IPv6Pattern = new RegExp(
`^((?:${v6Seg}:){7}(?:${v6Seg}|:)|(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})?$`
);
var isIPv4 = exports.isIPv4 = function isIPv42(host) {
return IPv4Pattern.test(host);
};
var isIPv6 = exports.isIPv6 = function isIPv62(host) {
return IPv6Pattern.test(host);
};
exports.isIP = function isIP(host) {
if (isIPv4(host)) return 4;
if (isIPv6(host)) return 6;
return 0;
};
}
});
// ../../node_modules/udx-native/lib/socket.js
var require_socket = __commonJS({
"../../node_modules/udx-native/lib/socket.js"(exports, module) {
var events = require_bare_node_events();
var b4a = require_b4a();
var binding = require_binding4();
var ip = require_ip();
module.exports = class UDXSocket extends events.EventEmitter {
constructor(udx, opts = {}) {
super();
this.udx = udx;
this._handle = b4a.alloc(binding.sizeof_udx_napi_socket_t);
this._inited = false;
this._host = null;
this._family = 0;
this._ipv6Only = opts.ipv6Only === true;
this._reuseAddress = opts.reuseAddress === true;
this._port = 0;
this._reqs = [];
this._free = [];
this._closing = null;
this._closed = false;
this._view64 = new BigUint64Array(
this._handle.buffer,
this._handle.byteOffset,
this._handle.byteLength >> 3
);
this.streams = /* @__PURE__ */ new Set();
this.userData = null;
}
get bound() {
return this._port !== 0;
}
get closing() {
return this._closing !== null;
}
get idle() {
return this.streams.size === 0;
}
get busy() {
return this.streams.size > 0;
}
get bytesTransmitted() {
if (this._inited !== true) return 0;
return Number(this._view64[binding.offsetof_udx_socket_t_bytes_tx >> 3]);
}
get packetsTransmitted() {
if (this._inited !== true) return 0;
return Number(this._view64[binding.offsetof_udx_socket_t_packets_tx >> 3]);
}
get bytesReceived() {
if (this._inited !== true) return 0;
return Number(this._view64[binding.offsetof_udx_socket_t_bytes_rx >> 3]);
}
get packetsReceived() {
if (this._inited !== true) return 0;
return Number(this._view64[binding.offsetof_udx_socket_t_packets_rx >> 3]);
}
get packetsDroppedByKernel() {
if (this._inited !== true) return 0;
return Number(this._view64[binding.offsetof_udx_socket_t_packets_dropped_by_kernel >> 3]);
}
toJSON() {
return {
bound: this.bound,
closing: this.closing,
streams: this.streams.size,
address: this.address(),
ipv6Only: this._ipv6Only,
reuseAddress: this._reuseAddress,
idle: this.idle,
busy: this.busy
};
}
_init() {
if (this._inited) return;
binding.udx_napi_socket_init(
this.udx._handle,
this._handle,
this,
this._onsend,
this._onmessage,
this._onclose,
this._reallocMessage
);
this._inited = true;
}
_onsend(id, err) {
const req = this._reqs[id];
const onflush = req.onflush;
req.buffer = null;
req.onflush = null;
this._free.push(id);
onflush(err >= 0);
if (this._free.length >= 16 && this._free.length === this._reqs.length) {
this._free = [];
this._reqs = [];
}
}
_onmessage(len, port, host, family) {
this.emit("message", this.udx._consumeMessage(len), { host, family, port });
return this.udx._buffer;
}
_onclose() {
this.emit("close");
}
_reallocMessage() {
return this.udx._reallocMessage();
}
_onidle() {
this.emit("idle");
}
_onbusy() {
this.emit("busy");
}
_addStream(stream) {
if (this.streams.has(stream)) return false;
this.streams.add(stream);
if (this.streams.size === 1) this._onbusy();
return true;
}
_removeStream(stream) {
if (!this.streams.has(stream)) return false;
this.streams.delete(stream);
const closed = this._closeMaybe();
if (this.idle && !closed) this._onidle();
return true;
}
address() {
if (!this.bound) return null;
return { host: this._host, family: this._family, port: this._port };
}
bind(port, host) {
if (this.bound) throw new Error("Already bound");
if (this.closing) throw new Error("Socket is closed");
if (!port) port = 0;
let flags = 0;
if (this._ipv6Only) flags |= binding.UV_UDP_IPV6ONLY;
if (this._reuseAddress) flags |= binding.UV_UDP_REUSEADDR;
let family;
if (host) {
family = ip.isIP(host);
if (!family) throw new Error(`${host} is not a valid IP address`);
if (!this._inited) this._init();
this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags);
} else {
if (!this._inited) this._init();
try {
host = "::";
family = 6;
this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags);
} catch {
host = "0.0.0.0";
family = 4;
this._port = binding.udx_napi_socket_bind(this._handle, port, host, family, flags);
}
}
this._host = host;
this._family = family;
this.emit("listening");
}
async close() {
if (this._closing) return this._closing;
this._closing = new Promise((resolve) => this.once("close", resolve));
this._closeMaybe();
return this._closing;
}
_closeMaybe() {
if (this._closed || this._closing === null) return this._closed;
if (!this._inited) {
this._closed = true;
this.emit("close");
return true;
}
if (this.idle) {
binding.udx_napi_socket_close(this._handle);
this._closed = true;
}
return this._closed;
}
setTTL(ttl) {
if (!this._inited) throw new Error("Socket not active");
binding.udx_napi_socket_set_ttl(this._handle, ttl);
}
getRecvBufferSize() {
if (!this._inited) throw new Error("Socket not active");
return binding.udx_napi_socket_get_recv_buffer_size(this._handle);
}
setRecvBufferSize(size) {
if (!this._inited) throw new Error("Socket not active");
return binding.udx_napi_socket_set_recv_buffer_size(this._handle, size);
}
getSendBufferSize() {
if (!this._inited) throw new Error("Socket not active");
return binding.udx_napi_socket_get_send_buffer_size(this._handle);
}
setSendBufferSize(size) {
if (!this._inited) throw new Error("Socket not active");
return binding.udx_napi_socket_set_send_buffer_size(this._handle, size);
}
addMembership(group, ifaceAddress) {
if (!this._inited) throw new Error("Socket not active");
return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || "", true);
}
dropMembership(group, ifaceAddress) {
if (!this._inited) throw new Error("Socket not active");
return binding.udx_napi_socket_set_membership(this._handle, group, ifaceAddress || "", false);
}
async send(buffer, port, host, ttl) {
if (this.closing) return false;
if (!host) host = "127.0.0.1";
const family = ip.isIP(host);
if (!family) throw new Error(`${host} is not a valid IP address`);
if (!this.bound) this.bind(0);
const id = this._allocSend();
const req = this._reqs[id];
req.buffer = buffer;
const promise = new Promise((resolve) => {
req.onflush = resolve;
});
binding.udx_napi_socket_send_ttl(
this._handle,
req.handle,
id,
buffer,
port,
host,
family,
ttl || 0
);
return promise;
}
trySend(buffer, port, host, ttl) {
if (this.closing) return;
if (!host) host = "127.0.0.1";
const family = ip.isIP(host);
if (!family) throw new Error(`${host} is not a valid IP address`);
if (!this.bound) this.bind(0);
const id = this._allocSend();
const req = this._reqs[id];
req.buffer = buffer;
req.onflush = noop;
binding.udx_napi_socket_send_ttl(
this._handle,
req.handle,
id,
buffer,
port,
host,
family,
ttl || 0
);
}
_allocSend() {
if (this._free.length > 0) return this._free.pop();
const handle = b4a.allocUnsafe(binding.sizeof_udx_socket_send_t);
return this._reqs.push({ handle, buffer: null, onflush: null }) - 1;
}
};
function noop() {
}
}
});
// ../../node_modules/udx-native/lib/stream.js
var require_stream = __commonJS({
"../../node_modules/udx-native/lib/stream.js"(exports, module) {
var streamx = require_streamx();
var b4a = require_b4a();
var binding = require_binding4();
var ip = require_ip();
var MAX_PACKET = 2048;
var BUFFER_SIZE = 65536 + MAX_PACKET;
module.exports = class UDXStream extends streamx.Duplex {
constructor(udx, id, opts = {}) {
super({ mapWritable: toBuffer, eagerOpen: true });
this.udx = udx;
this.socket = null;
this._handle = b4a.alloc(binding.sizeof_udx_napi_stream_t);
this._view = new Uint32Array(
this._handle.buffer,
this._handle.byteOffset,
this._handle.byteLength >> 2
);
this._view16 = new Uint16Array(
this._handle.buffer,
this._handle.byteOffset,
this._handle.byteLength >> 1
);
this._view64 = new BigUint64Array(
this._handle.buffer,
this._handle.byteOffset,
this._handle.byteLength >> 3
);
this._wreqs = [];
this._wfree = [];
this._sreqs = [];
this._sfree = [];
this._closed = false;
this._flushing = 0;
this._flushes = [];
this._buffer = null;
this._reallocData();
this._onwrite = null;
this._ondestroy = null;
this._firewall = opts.firewall || firewallAll;
this._remoteChanging = null;
this._previousSocket = null;
this.id = id;
this.remoteId = 0;
this.remoteHost = null;
this.remoteFamily = 0;
this.remotePort = 0;
this.userData = null;
binding.udx_napi_stream_init(
this.udx._handle,
this._handle,
id,
opts.framed ? 1 : 0,
this,
this._ondata,
this._onend,
this._ondrain,
this._onack,
this._onsend,
this._onmessage,
this._onclose,
this._onfirewall,
this._onremotechanged,
this._reallocData,
this._reallocMessage
);
if (opts.seq) binding.udx_napi_stream_set_seq(this._handle, opts.seq);
binding.udx_napi_stream_recv_start(this._handle, this._buffer);
}
get connected() {
return this.socket !== null;
}
get mtu() {
return this._view16[binding.offsetof_udx_stream_t_mtu >> 1];
}
get rtt() {
return this._view[binding.offsetof_udx_stream_t_srtt >> 2];
}
get cwnd() {
return this._view[binding.offsetof_udx_stream_t_cwnd >> 2];
}
get rtoCount() {
return this._view16[binding.offsetof_udx_stream_t_rto_count >> 1];
}
get retransmits() {
return this._view16[binding.offsetof_udx_stream_t_retransmit_count >> 1];
}
get fastRecoveries() {
return this._view16[binding.offsetof_udx_stream_t_fast_recovery_count >> 1];
}
get inflight() {
return this._view[binding.offsetof_udx_stream_t_inflight >> 2];
}
get bytesTransmitted() {
return Number(this._view64[binding.offsetof_udx_stream_t_bytes_tx >> 3]);
}
get packetsTransmitted() {
return Number(this._view64[binding.offsetof_udx_stream_t_packets_tx >> 3]);
}
get bytesReceived() {
return Number(this._view64[binding.offsetof_udx_stream_t_bytes_rx >> 3]);
}
get packetsReceived() {
return Number(this._view64[binding.offsetof_udx_stream_t_packets_rx >> 3]);
}
get localHost() {
return this.socket ? this.socket.address().host : null;
}
get localFamily() {
return this.socket ? this.socket.address().family : 0;
}
get localPort() {
return this.socket ? this.socket.address().port : 0;
}
setInteractive(bool) {
if (!this._closed) return;
binding.udx_napi_stream_set_mode(this._handle, bool ? 0 : 1);
}
connect(socket, remoteId, port, host, opts = {}) {
if (this._closed) return;
if (this.connected) throw new Error("Already connected");
if (socket.closing) throw new Error("Socket is closed");
if (typeof host === "object") {
opts = host;
host = null;
}
if (!host) host = "127.0.0.1";
const family = ip.isIP(host);
if (!family) throw new Error(`${host} is not a valid IP address`);
if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`);
if (!socket.bound) socket.bind(0);
this.remoteId = remoteId;
this.remotePort = port;
this.remoteHost = host;
this.remoteFamily = family;
this.socket = socket;
if (opts.ack) binding.udx_napi_stream_set_ack(this._handle, opts.ack);
binding.udx_napi_stream_connect(this._handle, socket._handle, remoteId, port, host, family);
this.socket._addStream(this);
this.emit("connect");
}
changeRemote(socket, remoteId, port, host) {
if (this._remoteChanging) throw new Error("Remote already changing");
if (!this.connected) throw new Error("Not yet connected");
if (socket.closing) throw new Error("Socket is closed");
if (this.socket.udx !== socket.udx) {
throw new Error("Cannot change to a socket on another UDX instance");
}
if (!host) host = "127.0.0.1";
const family = ip.isIP(host);
if (!family) throw new Error(`${host} is not a valid IP address`);
if (!(port > 0 && port < 65536)) throw new Error(`${port} is not a valid port`);
if (this.socket !== socket) this._previousSocket = this.socket;
this.remoteId = remoteId;
this.remotePort = port;
this.remoteHost = host;
this.remoteFamily = family;
this.socket = socket;
this._remoteChanging = new Promise((resolve, reject) => {
const onchanged = () => {
this.off("close", onclose);
resolve();
};
const onclose = () => {
this.off("remote-changed", onchanged);
reject(new Error("Stream is closed"));
};
this.once("remote-changed", onchanged).once("close", onclose);
});
binding.udx_napi_stream_change_remote(
this._handle,
socket._handle,
remoteId,
port,
host,
family
);
this.socket._addStream(this);
return this._remoteChanging;
}
relayTo(destination) {
if (this._closed) return;
binding.udx_napi_stream_relay_to(this._handle, destination._handle);
}
async send(buffer) {
if (!this.connected || this._closed) return false;
const id = this._allocSend();
const req = this._sreqs[id];
req.buffer = buffer;
const promise = new Promise((resolve) => {
req.onflush = resolve;
});
binding.udx_napi_stream_send(this._handle, req.handle, id, buffer);
return promise;
}
trySend(buffer) {
if (!this.connected || this._closed) return;
const id = this._allocSend();
const req = this._sreqs[id];
req.buffer = buffer;
req.onflush = noop;
binding.udx_napi_stream_send(this._handle, req.handle, id, buffer);
}
async flush() {
if (await streamx.Writable.drained(this) === false) return false;
if (this.destroying) return false;
const missing = this._wreqs.length - this._wfree.length;
if (missing === 0) return true;
return new Promise((resolve) => {
this._flushes.push({ flush: this._flushing++, missing, resolve });
});
}
toJSON() {
return {
id: this.id,
connected: this.connected,
destroying: this.destroying,
destroyed: this.destroyed,
remoteId: this.remoteId,
remoteHost: this.remoteHost,
remoteFamily: this.remoteFamily,
remotePort: this.remotePort,
mtu: this.mtu,
rtt: this.rtt,
cwnd: this.cwnd,
inflight: this.inflight,
socket: this.socket ? this.socket.toJSON() : null
};
}
_read(cb) {
cb(null);
}
_writeContinue(err) {
if (this._onwrite === null) return;
const cb = this._onwrite;
this._onwrite = null;
cb(err);
}
_destroyContinue(err) {
if (this._ondestroy === null) return;
const cb = this._ondestroy;
this._ondestroy = null;
cb(err);
}
_writev(buffers, cb) {
if (!this.connected)
throw customError("Writing while not connected not currently supported", "ERR_ASSERTION");
let drained = true;
if (buffers.length === 1) {
const id = this._allocWrite(1);
const req = this._wreqs[id];
req.flush = this._flushing;
req.buffer = buffers[0];
drained = binding.udx_napi_stream_write(this._handle, req.handle, id, req.buffer) !== 0;
} else {
const id = this._allocWrite(nextBatchSize(buffers.length));
const req = this._wreqs[id];
req.flush = this._flushing;
req.buffers = buffers;
drained = binding.udx_napi_stream_writev(this._handle, req.handle, id, req.buffers) !== 0;
}
if (drained) cb(null);
else this._onwrite = cb;
}
_final(cb) {
const id = this._allocWrite(1);
const req = this._wreqs[id];
req.flush = this._flushes;
req.buffer = b4a.allocUnsafe(0);
const drained = binding.udx_napi_stream_write_end(this._handle, req.handle, id, req.buffer) !== 0;
if (drained) cb(null);
else this._onwrite = cb;
}
_predestroy() {
if (!this._closed) binding.udx_napi_stream_destroy(this._handle);
this._closed = true;
this._writeContinue(null);
}
_destroy(cb) {
if (this.connected) this._ondestroy = cb;
else cb(null);
}
_ondata(read) {
this.push(this._consumeData(read));
return this._buffer;
}
_onend(read) {
if (read > 0) this.push(this._consumeData(read));
this.push(null);
}
_ondrain() {
this._writeContinue(null);
}
_flushAck(flush) {
for (let i = this._flushes.length - 1; i >= 0; i--) {
const f = this._flushes[i];
if (f.flush < flush) break;
f.missing--;
}
while (this._flushes.length > 0 && this._flushes[0].missing === 0) {
this._flushes.shift().resolve(true);
}
}
_onack(id) {
const req = this._wreqs[id];
req.buffers = req.buffer = null;
this._wfree.push(id);
if (this._flushes.length > 0) this._flushAck(req.flush);
if (this._wfree.length >= 64 && this._wfree.length === this._wreqs.length) {
this._wfree = [];
this._wreqs = [];
}
}
_onsend(id, err) {
const req = this._sreqs[id];
const onflush = req.onflush;
req.buffer = null;
req.onflush = null;
this._sfree.push(id);
onflush(err >= 0);
if (this._sfree.length >= 16 && this._sfree.length === this._sreqs.length) {
this._sfree = [];
this._sreqs = [];
}
}
_onmessage(len) {
this.emit("message", this.udx._consumeMessage(len));
return this.udx._buffer;
}
_onclose(err) {
this._closed = true;
if (this.socket) {
this.socket._removeStream(this);
this.socket = null;
}
if (this._previousSocket) {
this._previousSocket._removeStream(this);
this._previousSocket = null;
}
if (!err) return this._destroyContinue(null);
if (this._ondestroy === null) this.destroy(err);
else this._destroyContinue(err);
}
_onfirewall(socket, port, host, family) {
return this._firewall(socket, port, host, family) ? 1 : 0;
}
_onremotechanged() {
if (this._previousSocket) {
this._previousSocket._removeStream(this);
this._previousSocket = null;
}
this._remoteChanging = null;
this.emit("remote-changed");
}
_consumeData(len) {
const next = this._buffer.subarray(0, len);
this._buffer = this._buffer.subarray(len);
if (this._buffer.byteLength < MAX_PACKET) this._reallocData();
return next;
}
_reallocData() {
this._buffer = b4a.allocUnsafe(BUFFER_SIZE);
return this._buffer;
}
_reallocMessage() {
return this.udx._reallocMessage();
}
_allocWrite(size) {
if (this._wfree.length === 0) {
const handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size));
return this._wreqs.push({
handle,
size,
buffers: null,
buffer: null,
flush: 0
}) - 1;
}
const free = this._wfree.pop();
if (size === 1) return free;
const next = this._wreqs[free];
if (next.size < size) {
next.handle = b4a.allocUnsafe(binding.udx_napi_stream_write_sizeof(size));
next.size = size;
}
return free;
}
_allocSend() {
if (this._sfree.length > 0) return this._sfree.pop();
const handle = b4a.allocUnsafe(binding.sizeof_udx_stream_send_t);
return this._sreqs.push({ handle, buffer: null, resolve: null, reject: null }) - 1;
}
};
function noop() {
}
function toBuffer(data) {
return typeof data === "string" ? b4a.from(data) : data;
}
function firewallAll(socket, port, host) {
return true;
}
function customError(message, code) {
const error = new Error(message);
error.code = code;
return error;
}
function nextBatchSize(n) {
if (n === 1) return 1;
if (n < 8) return 8;
if (n < 16) return 16;
if (n < 32) return 32;
if (n < 64) return 64;
return n;
}
}
});
// ../../node_modules/udx-native/lib/network-interfaces.js
var require_network_interfaces = __commonJS({
"../../node_modules/udx-native/lib/network-interfaces.js"(exports, module) {
var events = require_bare_node_events();
var b4a = require_b4a();
var binding = require_binding4();
module.exports = class NetworkInterfaces extends events.EventEmitter {
constructor(udx) {
super();
this._handle = b4a.alloc(binding.sizeof_udx_napi_interface_event_t);
this._watching = false;
this._destroying = null;
binding.udx_napi_interface_event_init(
udx._handle,
this._handle,
this,
this._onevent,
this._onclose
);
this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle);
}
_onclose() {
this.emit("close");
}
_onevent() {
this.interfaces = binding.udx_napi_interface_event_get_addrs(this._handle);
this.emit("change", this.interfaces);
}
watch() {
if (this._watching) return this;
this._watching = true;
binding.udx_napi_interface_event_start(this._handle);
return this;
}
unwatch() {
if (!this._watching) return this;
this._watching = false;
binding.udx_napi_interface_event_stop(this._handle);
return this;
}
async destroy() {
if (this._destroying) return this._destroying;
this._destroying = events.once(this, "close");
binding.udx_napi_interface_event_close(this._handle);
return this._destroying;
}
[Symbol.iterator]() {
return this.interfaces[Symbol.iterator]();
}
};
}
});
// ../../node_modules/udx-native/lib/udx.js
var require_udx = __commonJS({
"../../node_modules/udx-native/lib/udx.js"(exports, module) {
var b4a = require_b4a();
var binding = require_binding4();
var ip = require_ip();
var Socket = require_socket();
var Stream = require_stream();
var NetworkInterfaces = require_network_interfaces();
var MAX_MESSAGE = 4096;
var BUFFER_SIZE = 65536 + MAX_MESSAGE;
module.exports = class UDX {
constructor() {
this._handle = b4a.alloc(binding.sizeof_udx_napi_t);
this._watchers = /* @__PURE__ */ new Set();
this._view64 = new BigUint64Array(
this._handle.buffer,
this._handle.byteOffset,
this._handle.byteLength >> 3
);
this._buffer = null;
this._reallocMessage();
binding.udx_napi_init(this._handle, this._buffer);
}
static isIPv4(host) {
return ip.isIPv4(host);
}
static isIPv6(host) {
return ip.isIPv6(host);
}
static isIP(host) {
return ip.isIP(host);
}
get bytesTransmitted() {
return Number(this._view64[binding.offsetof_udx_t_bytes_tx >> 3]);
}
get packetsTransmitted() {
return Number(this._view64[binding.offsetof_udx_t_packets_tx >> 3]);
}
get bytesReceived() {
return Number(this._view64[binding.offsetof_udx_t_bytes_rx >> 3]);
}
get packetsReceived() {
return Number(this._view64[binding.offsetof_udx_t_packets_rx >> 3]);
}
get packetsDroppedByKernel() {
return Number(this._view64[binding.offsetof_udx_t_packets_dropped_by_kernel >> 3]);
}
_consumeMessage(len) {
const next = this._buffer.subarray(0, len);
this._buffer = this._buffer.subarray(len);
if (this._buffer.byteLength < MAX_MESSAGE) this._reallocMessage();
return next;
}
_reallocMessage() {
this._buffer = b4a.allocUnsafe(BUFFER_SIZE);
return this._buffer;
}
createSocket(opts) {
return new Socket(this, opts);
}
createStream(id, opts) {
return new Stream(this, id, opts);
}
networkInterfaces() {
let [watcher = null] = this._watchers;
if (watcher) return watcher.interfaces;
watcher = new NetworkInterfaces(this);
watcher.destroy();
return watcher.interfaces;
}
watchNetworkInterfaces(onchange) {
const watcher = new NetworkInterfaces(this);
this._watchers.add(watcher);
watcher.on("close", () => {
this._watchers.delete(watcher);
});
if (onchange) watcher.on("change", onchange);
return watcher.watch();
}
async lookup(host, opts = {}) {
const { family = 0 } = opts;
const req = b4a.alloc(binding.sizeof_udx_napi_lookup_t);
const ctx = {
req,
resolve: null,
reject: null
};
const promise = new Promise((resolve, reject) => {
ctx.resolve = resolve;
ctx.reject = reject;
});
binding.udx_napi_lookup(this._handle, req, host, family, ctx, onlookup);
return promise;
}
};
function onlookup(err, host, family) {
if (err) this.reject(err);
else this.resolve({ host, family });
}
}
});
// ../../node_modules/bare-ansi-escapes/index.js
var require_bare_ansi_escapes = __commonJS({
"../../node_modules/bare-ansi-escapes/index.js"(exports) {
var ESC = "\x1B";
var CSI = ESC + "[";
var SGR = (n) => CSI + n + "m";
exports.constants = {
ESC,
CSI,
SGR
};
exports.cursorHide = CSI + "?25l";
exports.cursorShow = CSI + "?25h";
exports.cursorUp = function cursorUp(n = 1) {
return CSI + n + "A";
};
exports.cursorDown = function cursorDown(n = 1) {
return CSI + n + "B";
};
exports.cursorForward = function cursorForward(n = 1) {
return CSI + n + "C";
};
exports.cursorBack = function cursorBack(n = 1) {
return CSI + n + "D";
};
exports.cursorNextLine = function cursorNextLine(n = 1) {
return CSI + n + "E";
};
exports.cursorPreviousLine = function cursorPreviousLine(n = 1) {
return CSI + n + "F";
};
exports.cursorPosition = function cursorPosition(column, row = 0) {
if (row === 0) return CSI + (column + 1) + "G";
return CSI + (row + 1) + ";" + (column + 1) + "H";
};
exports.eraseDisplayEnd = CSI + "J";
exports.eraseDisplayStart = CSI + "1J";
exports.eraseDisplay = CSI + "2J";
exports.eraseLineEnd = CSI + "K";
exports.eraseLineStart = CSI + "1K";
exports.eraseLine = CSI + "2K";
exports.scrollUp = function scrollUp(n = 1) {
return CSI + n + "S";
};
exports.scrollDown = function scrollDown(n = 1) {
return CSI + n + "T";
};
exports.modifierReset = SGR(0);
exports.modifierBold = SGR(1);
exports.modifierDim = SGR(2);
exports.modifierItalic = SGR(3);
exports.modifierUnderline = SGR(4);
exports.modifierNormal = SGR(22);
exports.modifierNotItalic = SGR(23);
exports.modifierNotUnderline = SGR(24);
exports.colorBlack = SGR(30);
exports.colorRed = SGR(31);
exports.colorGreen = SGR(32);
exports.colorYellow = SGR(33);
exports.colorBlue = SGR(34);
exports.colorMagenta = SGR(35);
exports.colorCyan = SGR(36);
exports.colorWhite = SGR(37);
exports.colorDefault = SGR(39);
exports.colorBrightBlack = SGR(90);
exports.colorBrightRed = SGR(91);
exports.colorBrightGreen = SGR(92);
exports.colorBrightYellow = SGR(93);
exports.colorBrightBlue = SGR(94);
exports.colorBrightMagenta = SGR(95);
exports.colorBrightCyan = SGR(96);
exports.colorBrightWhite = SGR(97);
}
});
// ../../node_modules/bare-type/binding.js
var require_binding5 = __commonJS({
"../../node_modules/bare-type/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-type/index.js
var require_bare_type = __commonJS({
"../../node_modules/bare-type/index.js"(exports, module) {
var binding = require_binding5();
var t = binding.constants;
var Type = class {
constructor(type) {
this._type = type;
}
isUndefined() {
return this._type === t.UNDEFINED;
}
isNull() {
return this._type === t.NULL;
}
isBoolean() {
return this._type === t.BOOLEAN;
}
isNumber() {
return (this._type & 255) === t.NUMBER;
}
isInt32() {
return (this._type & (255 | t.INT32)) === (t.NUMBER | t.INT32);
}
isUint32() {
return (this._type & (255 | t.UINT32)) === (t.NUMBER | t.UINT32);
}
isString() {
return this._type === t.STRING;
}
isSymbol() {
return this._type === t.SYMBOL;
}
isObject() {
return (this._type & 255) === t.OBJECT;
}
isArray() {
return this._type === (t.OBJECT | t.ARRAY);
}
isArguments() {
return this._type === (t.OBJECT | t.ARGUMENTS);
}
isDate() {
return this._type === (t.OBJECT | t.DATE);
}
isRegExp() {
return this._type === (t.OBJECT | t.REGEXP);
}
isError() {
return this._type === (t.OBJECT | t.ERROR);
}
isPromise() {
return this._type === (t.OBJECT | t.PROMISE);
}
isProxy() {
return this._type === (t.OBJECT | t.PROXY);
}
isGenerator() {
return this._type === (t.OBJECT | t.GENERATOR);
}
isMap() {
return this._type === (t.OBJECT | t.MAP);
}
isSet() {
return this._type === (t.OBJECT | t.SET);
}
isWeakMap() {
return this._type === (t.OBJECT | t.WEAK_MAP);
}
isWeakSet() {
return this._type === (t.OBJECT | t.WEAK_SET);
}
isWeakRef() {
return this._type === (t.OBJECT | t.WEAK_REF);
}
isArrayBuffer() {
return this._type === (t.OBJECT | t.ARRAYBUFFER);
}
isSharedArrayBuffer() {
return this._type === (t.OBJECT | t.SHAREDARRAYBUFFER);
}
isTypedArray() {
return (this._type & 65535) === (t.OBJECT | t.TYPEDARRAY);
}
isInt8Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT8ARRAY);
}
isUint8Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8ARRAY);
}
isUint8ClampedArray() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT8CLAMPEDARRAY);
}
isInt16Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT16ARRAY);
}
isUint16Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT16ARRAY);
}
isInt32Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.INT32ARRAY);
}
isUint32Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.UINT32ARRAY);
}
isFloat16Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT16ARRAY);
}
isFloat32Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT32ARRAY);
}
isFloat64Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.FLOAT64ARRAY);
}
isBigInt64Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGINT64ARRAY);
}
isBigUint64Array() {
return this._type === (t.OBJECT | t.TYPEDARRAY | t.BIGUINT64ARRAY);
}
isDataView() {
return this._type === (t.OBJECT | t.DATAVIEW);
}
isModuleNamespace() {
return this._type === (t.OBJECT | t.MODULE_NAMESPACE);
}
isFunction() {
return (this._type & 255) === t.FUNCTION;
}
isAsyncFunction() {
return (this._type & (255 | t.ASYNC_FUNCTION)) === (t.FUNCTION | t.ASYNC_FUNCTION);
}
isGeneratorFunction() {
return (this._type & (255 | t.GENERATOR_FUNCTION)) === (t.FUNCTION | t.GENERATOR_FUNCTION);
}
isExternal() {
return this._type === t.EXTERNAL;
}
isBigInt() {
return this._type === t.BIGINT;
}
};
module.exports = exports = function type(value) {
switch (typeof value) {
case "undefined":
return new Type(t.UNDEFINED);
case "boolean":
return new Type(t.BOOLEAN);
case "number":
return new Type(
Number.isSafeInteger(value) ? binding.type(value) : t.NUMBER
);
case "string":
return new Type(t.STRING);
case "symbol":
return new Type(t.SYMBOL);
case "object":
return new Type(value === null ? t.NULL : binding.type(value));
case "function":
return new Type(binding.type(value));
case "bigint":
return new Type(t.BIGINT);
}
};
exports.createTag = function createTag(...components) {
const tag = new Uint32Array(4);
for (let i = 0; i < 4; i++) tag[i] = components[i] || 0;
return tag;
};
exports.addTag = function addTag(object, tag) {
binding.addTag(object, tag);
};
exports.checkTag = function checkTag(object, tag) {
return binding.checkTag(object, tag);
};
}
});
// ../../node_modules/bare-inspect/binding.js
var require_binding6 = __commonJS({
"../../node_modules/bare-inspect/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-inspect/index.js
var require_bare_inspect = __commonJS({
"../../node_modules/bare-inspect/index.js"(exports, module) {
var ansiEscapes = require_bare_ansi_escapes();
var getType = require_bare_type();
var binding = require_binding6();
var PLAIN_KEY = /^[a-zA-Z_][a-zA-Z_0-9]*$/;
var defaultDepth = 2;
var defaultBreakLength = 80;
var defaultMaxArrayLength = 40;
module.exports = exports = function inspect(value, opts = {}) {
const {
colors = false,
depth = defaultDepth,
breakLength = defaultBreakLength,
stylize = defaultStylize(colors)
} = opts;
const references = new InspectRefMap();
const tree = inspectValue(value, 0, {
colors,
depth,
breakLength,
stylize,
references
});
return tree.toString();
};
exports.styles = {
bigint: ansiEscapes.colorYellow,
boolean: ansiEscapes.colorYellow,
date: ansiEscapes.colorMagenta,
module: ansiEscapes.modifierUnderline,
name: ansiEscapes.modifierReset,
null: ansiEscapes.modifierBold,
number: ansiEscapes.colorYellow,
regexp: ansiEscapes.colorRed,
special: ansiEscapes.colorCyan,
string: ansiEscapes.colorGreen,
symbol: ansiEscapes.colorGreen,
undefined: ansiEscapes.colorBrightBlack
};
var styles = exports.styles;
function defaultStylize(colors) {
return function stylize(value, style) {
const color = colors && styles[style];
if (color) return color + value + ansiEscapes.modifierReset;
return value;
};
}
var InspectRefMap = class {
constructor() {
this.refs = /* @__PURE__ */ new WeakMap();
this.ids = /* @__PURE__ */ new WeakMap();
this.nextId = 1;
}
has(object) {
return this.refs.has(object);
}
get(object) {
return this.refs.get(object) || null;
}
set(object, ref) {
this.refs.set(object, ref);
}
id(object) {
let id = this.ids.get(object);
if (id) return id;
id = this.nextId++;
this.ids.set(object, id);
return id;
}
};
var InspectNode = class {
constructor(depth, length, opts) {
const { breakLength = defaultBreakLength, breakAlways = false } = opts;
this.depth = depth;
this.length = length;
this.breakLength = breakLength;
this.breakAlways = breakAlways;
}
pad(n, string) {
return string.padStart(n, " ");
}
indent(n, string) {
return " ".repeat(n) + string;
}
};
var InspectRef = class extends InspectNode {
constructor(depth, opts) {
super(depth, "[circular *]".length, opts);
this.refs = opts.references;
this.count = 0;
this.circular = false;
this.color = opts.colors && styles.special;
}
get id() {
return this.refs.id(this);
}
increment() {
return ++this.count;
}
decrement() {
return --this.count;
}
toString(opts = {}) {
const { offset = 0, pad = 0, indent = 0 } = opts;
let value = this.pad(pad, "[circular *" + this.id + "]");
if (this.color) value = this.color + value + ansiEscapes.modifierReset;
return offset ? value : this.indent(indent, value);
}
};
var InspectLeaf = class extends InspectNode {
constructor(value, color, depth, opts) {
const length = value.length;
if (value.includes("\n")) {
value = value.replaceAll("\n", "\n" + " ".repeat(depth));
opts = { ...opts, breakAlways: true };
}
super(depth, length, opts);
this.value = value;
this.color = opts.colors && color;
}
toString(opts = {}) {
const { offset = 0, pad = 0, indent = 0 } = opts;
let value = this.pad(pad, this.value);
if (this.color) value = this.color + value + ansiEscapes.modifierReset;
return offset ? value : this.indent(indent, value);
}
};
var InspectPair = class extends InspectNode {
constructor(delim, left, right, depth, opts) {
const length = left.length + delim.length + right.length;
if (left.breakAlways || right.breakAlways) {
opts = { ...opts, breakAlways: true };
}
super(depth, length, opts);
this.delim = delim;
this.left = left;
this.right = right;
}
toString(opts = {}) {
const { indent = 0 } = opts;
return this.indent(
indent,
this.left + this.delim + this.right.toString({
indent,
offset: this.left.length + this.delim.length
})
);
}
};
var InspectSuspension = class extends InspectNode {
constructor(overflow, depth, opts) {
const label = `... ${overflow} more`;
super(depth, label.length, opts);
this.label = label;
}
toString(opts = {}) {
const { indent = 0 } = opts;
return this.indent(indent, this.label);
}
};
var InspectSequence = class extends InspectNode {
constructor(header, footer, delim, values, ref, depth, opts) {
const { tabulate = false } = opts;
const length = (ref.circular ? "<ref *>".length + 1 : 0) + header.length + values.reduce(
(length2, value, i) => length2 + value.length + (i === 0 ? 0 : delim.length),
0
) + footer.length;
if (values.some((value) => value.breakAlways)) {
opts = { ...opts, breakAlways: true };
}
super(depth, length, opts);
this.header = header;
this.footer = footer;
this.delim = delim;
this.values = values;
this.ref = ref;
this.tabulate = tabulate;
}
toString(opts = {}) {
const { offset = 0, indent = 0 } = opts;
const split = this.breakAlways || this.values.length && (offset + this.length > this.breakLength || indent * 2 + this.length > this.breakLength);
let header = this.header;
if (this.ref.circular) {
header = "<ref *" + this.ref.id + "> " + header;
}
if (this.values.length === 0) {
header = header.trimEnd();
}
if (offset === 0) {
header = this.indent(indent, header);
}
if (split) {
header = header.trimEnd() + "\n";
}
let string = header;
let columns = 1;
let pad = 0;
if (this.tabulate) {
const widest = this.values.reduce(
(length, value) => value.breakAlways ? length : Math.max(length, value.length),
0
);
if (widest) {
columns = Math.max(
columns,
Math.floor(
(this.breakLength - indent * 2) / (widest + this.delim.length)
)
);
if (columns > 1) pad = widest;
}
}
for (let i = 0, n = this.values.length, offset2 = 0; i < n; i++) {
const value = this.values[i];
if (split) {
let part;
if (i % columns === 0 || value.breakAlways) {
part = value.toString({ indent: indent + 1, pad });
} else {
part = value.toString({ pad });
}
string += part;
if (i < n - 1) {
if (i % columns === columns - 1 || this.values[i + 1].breakAlways) {
string += this.delim.trimEnd() + "\n";
} else {
string += this.delim;
}
}
} else {
if (i > 0) string += this.delim;
string += value.toString({ offset: offset2 });
offset2 += value.length;
}
}
let footer = this.footer;
if (this.values.length === 0) {
footer = footer.trimStart();
}
if (split) {
string += "\n" + this.indent(indent, footer.trimStart());
} else {
string += footer;
}
return string;
}
};
function inspectValue(value, depth, opts) {
const type = getType(value);
if (type.isUndefined()) return inspectUndefined(depth, opts);
if (type.isNull()) return inspectNull(depth, opts);
if (type.isBoolean()) return inspectBoolean(value, depth, opts);
if (type.isNumber()) return inspectNumber(value, depth, opts);
if (type.isBigInt()) return inspectBigInt(value, depth, opts);
if (type.isString()) return inspectString(value, depth, opts);
if (type.isSymbol()) return inspectSymbol(value, depth, opts);
if (type.isObject()) return inspectObject(type, value, depth, opts);
if (type.isFunction()) return inspectFunction(type, value, depth, opts);
if (type.isExternal()) return inspectExternal(value, opts, opts);
}
function inspectUndefined(depth, opts) {
return new InspectLeaf("undefined", styles.undefined, depth, opts);
}
function inspectNull(depth, opts) {
return new InspectLeaf("null", styles.null, depth, opts);
}
function inspectBoolean(value, depth, opts) {
return new InspectLeaf(value.toString(), styles.boolean, depth, opts);
}
function inspectNumber(value, depth, opts) {
let string;
if (Object.is(value, -0)) {
string = "-0";
} else {
string = value.toString(10);
}
return new InspectLeaf(string, styles.number, depth, opts);
}
function inspectBigInt(value, depth, opts) {
return new InspectLeaf(value.toString(10) + "n", styles.bigint, depth, opts);
}
var STRING_ESCAPES = /[\ud800-\udbff][\udc00-\udfff]|[\u0000-\u001f'\\\ud800-\udfff]/g;
function inspectString(value, depth, opts) {
const string = value.replace(STRING_ESCAPES, (match) => {
if (match.length === 2) return match;
switch (match) {
case "'":
return "\\'";
case "\\":
return "\\\\";
case "\b":
return "\\b";
case " ":
return "\\t";
case "\n":
return "\\n";
case "\f":
return "\\f";
case "\r":
return "\\r";
default:
return "\\u" + match.charCodeAt(0).toString(16).padStart(4, "0");
}
});
return new InspectLeaf("'" + string + "'", styles.string, depth, opts);
}
function inspectSymbol(value, depth, opts) {
return new InspectLeaf(value.toString(), styles.symbol, depth, opts);
}
function inspectKey(value, depth, opts) {
if (PLAIN_KEY.test(value)) {
return new InspectLeaf(value, null, depth, opts);
} else {
return inspectValue(value, depth, opts);
}
}
function inspectObject(type, object, depth, opts) {
const refs = opts.references;
let ref = refs.get(object);
if (ref === null) {
ref = new InspectRef(depth, opts);
refs.set(object, ref);
} else if (ref.count) {
ref.circular = true;
return ref;
}
const maxDepth = typeof opts.depth === "number" ? opts.depth : Infinity;
if (maxDepth < depth) {
const constructor = object.constructor;
return new InspectLeaf(
"[" + (constructor && constructor.name ? constructor.name : "Object") + "]",
styles.special,
depth,
opts
);
}
const inspect = object[Symbol.for("bare.inspect")] || object[Symbol.for("nodejs.util.inspect.custom")];
if (typeof inspect === "function") {
const value = inspect.call(
object,
typeof opts.depth === "number" ? opts.depth - depth : null,
{
colors: opts.colors,
breakLength: opts.breakLength,
stylize: opts.stylize
},
exports
);
if (typeof value === "object" && value !== null) {
refs.set(value, ref);
}
if (typeof value !== "string") {
return inspectValue(value, depth, opts);
}
return new InspectLeaf(value, null, depth, opts);
}
if (type.isArray()) return inspectArray(object, ref, depth, opts);
if (type.isDate()) return inspectDate(object, ref, depth, opts);
if (type.isRegExp()) return inspectRegExp(object, ref, depth, opts);
if (type.isError()) return inspectError(object, ref, depth, opts);
if (type.isPromise()) return inspectPromise(object, ref, depth, opts);
if (type.isMap()) return inspectMap(object, ref, depth, opts);
if (type.isSet()) return inspectSet(object, ref, depth, opts);
if (type.isWeakMap()) return inspectWeakMap(object, ref, depth, opts);
if (type.isWeakSet()) return inspectWeakSet(object, ref, depth, opts);
if (type.isWeakRef()) return inspectWeakRef(object, ref, depth, opts);
if (type.isArrayBuffer()) return inspectArrayBuffer(object, ref, depth, opts);
if (type.isSharedArrayBuffer())
return inspectSharedArrayBuffer(object, ref, depth, opts);
if (type.isTypedArray()) return inspectTypedArray(object, ref, depth, opts);
if (type.isDataView()) return inspectDataView(object, ref, depth, opts);
ref.increment();
const values = [];
for (const key in object) {
if (key === "constructor") continue;
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(object[key], depth + 1, opts),
depth + 1,
opts
)
);
}
ref.decrement();
let header = "{ ";
const tag = object[Symbol.toStringTag];
if (tag) header = "[" + tag + "] " + header;
if (object.constructor) {
const name = object.constructor.name;
if (name && name !== "Object") {
header = object.constructor.name + " " + header;
}
}
return new InspectSequence(header, " }", ", ", values, ref, depth, opts);
}
function inspectArray(array, ref, depth, opts) {
const { maxArrayLength = defaultMaxArrayLength } = opts;
ref.increment();
const values = [];
let remaining = Math.max(maxArrayLength, 0);
for (let i = 0, n = array.length; i < n; i++) {
if (remaining-- === 0) {
values.push(
new InspectSuspension(array.length - values.length, depth + 1, {
...opts,
breakAlways: true
})
);
break;
}
values.push(inspectValue(array[i], depth + 1, opts));
}
for (const key of binding.getOwnNonIndexPropertyNames(array)) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(array[key], depth + 1, opts),
depth + 1,
{ ...opts, breakAlways: remaining < 0 }
)
);
}
ref.decrement();
let header = "[ ";
if (array.constructor.name !== "Array") {
header = array.constructor.name + "(" + array.length + ") " + header;
}
return new InspectSequence(header, " ]", ", ", values, ref, depth, {
...opts,
tabulate: true
});
}
function inspectDate(date, ref, depth, opts) {
return new InspectLeaf(date.toISOString(), styles.date, depth, opts);
}
function inspectRegExp(regExp, ref, depth, opts) {
return new InspectLeaf(regExp.toString(), styles.regexp, depth, opts);
}
function inspectError(error, ref, depth, opts) {
let header;
if ("stack" in error) {
header = error.stack;
if (depth > 0) {
header = header.replaceAll("\n", "\n" + " ".repeat(depth));
}
} else {
header = error.toString();
}
const builtins = ["cause"];
if (error.name === "AggregateError") {
builtins.push("errors");
} else if (error.name === "SuppressedError") {
builtins.push("error", "suppressed");
}
const values = [];
for (const key of builtins) {
if (key in error === false) continue;
values.push(
new InspectPair(
": ",
new InspectLeaf("[" + key + "]", null, depth + 1, opts),
inspectValue(error[key], depth + 1, opts),
depth + 1,
opts
)
);
}
for (const key in error) {
if (key === "constructor" || builtins.includes(key)) continue;
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(error[key], depth + 1, opts),
depth + 1,
opts
)
);
}
if (values.length === 0) return new InspectLeaf(header, null, depth, opts);
return new InspectSequence(
header + " {",
" }",
", ",
values,
ref,
depth,
opts
);
}
function inspectPromise(promise, ref, depth, opts) {
ref.increment();
const state = binding.getPromiseState(promise);
const values = [];
switch (state) {
case 0:
values.push(new InspectLeaf("<pending>", styles.special, depth, opts));
break;
case 1:
values.push(inspectValue(binding.getPromiseResult(promise), depth, opts));
break;
case 2:
values.push(
new InspectLeaf("<rejected>", styles.special, depth, opts),
inspectValue(binding.getPromiseResult(promise), depth, opts)
);
}
ref.decrement();
const header = promise.constructor.name + " { ";
return new InspectSequence(header, " }", " ", values, ref, depth, opts);
}
function inspectMap(map, ref, depth, opts) {
const {
maxArrayLength = defaultMaxArrayLength,
maxMapLength = maxArrayLength
} = opts;
ref.increment();
const values = [];
let remaining = maxMapLength;
for (const entry of map) {
if (remaining-- === 0) {
values.push(
new InspectSuspension(map.size - values.length, depth + 1, {
...opts,
breakAlways: true
})
);
break;
}
values.push(
new InspectPair(
" => ",
inspectValue(entry[0], depth + 1, opts),
inspectValue(entry[1], depth + 1, opts),
depth + 1,
opts
)
);
}
for (const key in map) {
if (key === "constructor") continue;
const value = inspectValue(map[key], depth + 1, opts);
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
value,
depth + 1,
{ ...opts, breakAlways: remaining < 0 }
)
);
}
ref.decrement();
const header = map.constructor.name + "(" + map.size + ") { ";
return new InspectSequence(header, " }", ", ", values, ref, depth, {
...opts,
tabulate: true
});
}
function inspectSet(set, ref, depth, opts) {
const {
maxArrayLength = defaultMaxArrayLength,
maxSetLength = maxArrayLength
} = opts;
ref.increment();
const values = [];
let remaining = maxSetLength;
for (const entry of set) {
if (remaining-- === 0) {
values.push(
new InspectSuspension(set.size - values.length, depth + 1, {
...opts,
breakAlways: true
})
);
break;
}
values.push(inspectValue(entry, depth + 1, opts));
}
for (const key in set) {
if (key === "constructor") continue;
const value = inspectValue(set[key], depth + 1, opts);
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
value,
depth + 1,
{ ...opts, breakAlways: remaining < 0 }
)
);
}
ref.decrement();
const header = set.constructor.name + "(" + set.size + ") { ";
return new InspectSequence(header, " }", ", ", values, ref, depth, {
...opts,
tabulate: true
});
}
function inspectWeakMap(weakMap, ref, depth, opts) {
const header = weakMap.constructor.name + " { ";
return new InspectSequence(
header,
" }",
" ",
[new InspectLeaf("<items unknown>", styles.special, depth + 1, opts)],
ref,
depth,
opts
);
}
function inspectWeakSet(weakSet, ref, depth, opts) {
const header = weakSet.constructor.name + " { ";
return new InspectSequence(
header,
" }",
" ",
[new InspectLeaf("<items unknown>", styles.special, depth + 1, opts)],
ref,
depth,
opts
);
}
function inspectWeakRef(weakRef, ref, depth, opts) {
const target = weakRef.deref();
let value;
if (target === void 0) {
value = new InspectLeaf("<cleared>", styles.special, depth + 1, opts);
} else {
value = inspectValue(target, depth + 1, opts);
}
const header = weakRef.constructor.name + " { ";
return new InspectSequence(header, " }", " ", [value], ref, depth, opts);
}
function inspectArrayBuffer(arrayBuffer, ref, depth, opts) {
ref.increment();
const values = [];
for (const key of ["byteLength"]) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(arrayBuffer[key], depth + 1, opts),
depth + 1,
opts
)
);
}
ref.decrement();
const header = arrayBuffer.constructor.name + " { ";
return new InspectSequence(header, " }", ", ", values, ref, depth, opts);
}
function inspectSharedArrayBuffer(sharedArrayBuffer, ref, depth, opts) {
ref.increment();
const values = [];
for (const key of ["byteLength"]) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(sharedArrayBuffer[key], depth + 1, opts),
depth + 1,
opts
)
);
}
ref.decrement();
const header = sharedArrayBuffer.constructor.name + " { ";
return new InspectSequence(header, " }", ", ", values, ref, depth, opts);
}
function inspectTypedArray(typedArray, ref, depth, opts) {
if (Buffer.isBuffer(typedArray)) {
return inspectBuffer(typedArray, ref, depth, opts);
}
const {
maxArrayLength = defaultMaxArrayLength,
maxTypedArrayLength = maxArrayLength
} = opts;
ref.increment();
const values = [];
let remaining = Math.max(maxTypedArrayLength, 0);
for (let i = 0, n = typedArray.length; i < n; i++) {
if (remaining-- === 0) {
values.push(
new InspectSuspension(typedArray.length - values.length, depth + 1, {
...opts,
breakAlways: true
})
);
break;
}
values.push(inspectValue(typedArray[i], depth + 1, opts));
}
for (const key of binding.getOwnNonIndexPropertyNames(typedArray)) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(typedArray[key], depth + 1, opts),
depth + 1,
{ ...opts, breakAlways: remaining < 0 }
)
);
}
ref.decrement();
const header = typedArray.constructor.name + "(" + typedArray.length + ") [ ";
return new InspectSequence(header, " ]", ", ", values, ref, depth, {
...opts,
tabulate: true
});
}
function inspectBuffer(buffer, ref, depth, opts) {
const {
maxArrayLength = defaultMaxArrayLength,
maxBufferLength = maxArrayLength
} = opts;
ref.increment();
const values = [];
let remaining = Math.max(maxBufferLength, 0);
for (let i = 0, n = buffer.byteLength; i < n; i++) {
if (remaining-- === 0) {
values.push(
new InspectSuspension(buffer.length - values.length, depth + 1, {
...opts,
breakAlways: true
})
);
break;
}
values.push(
new InspectLeaf(
buffer[i].toString(16).padStart(2, "0"),
null,
depth + 1,
opts
)
);
}
for (const key of binding.getOwnNonIndexPropertyNames(buffer)) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(buffer[key], depth + 1, opts),
depth + 1,
{ ...opts, breakAlways: remaining < 0 }
)
);
}
ref.decrement();
return new InspectSequence("<Buffer ", ">", " ", values, ref, depth, {
...opts,
tabulate: true
});
}
function inspectDataView(dataView, ref, depth, opts) {
ref.increment();
const values = [];
for (const key of ["byteLength", "byteOffset", "buffer"]) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(dataView[key], depth + 1, opts),
depth + 1,
opts
)
);
}
for (const key of binding.getOwnNonIndexPropertyNames(dataView)) {
values.push(
new InspectPair(
": ",
inspectKey(key, depth + 1, opts),
inspectValue(dataView[key], depth + 1, opts),
depth + 1,
opts
)
);
}
ref.decrement();
const header = dataView.constructor.name + " { ";
return new InspectSequence(header, " }", ", ", values, ref, depth, opts);
}
function inspectFunction(type, fn, depth, opts) {
if (fn.toString().startsWith("class")) return inspectClass(fn, depth, opts);
let tag = "function";
if (type.isGeneratorFunction()) tag = "generator " + tag;
if (type.isAsyncFunction()) tag = "async " + tag;
return new InspectLeaf(
"[" + tag + " " + (fn.name ? fn.name : "(anonymous)") + "]",
styles.special,
depth,
opts
);
}
function inspectClass(ctor, depth, opts) {
return new InspectLeaf(
"[class " + (ctor.name ? ctor.name : "(anonymous)") + "]",
styles.special,
depth,
opts
);
}
function inspectExternal(external, depth, opts) {
return new InspectLeaf(
"[external 0x" + binding.getExternal(external).toString(16) + "]",
styles.special,
depth,
opts
);
}
}
});
// ../../node_modules/bare-assert/index.js
var require_bare_assert = __commonJS({
"../../node_modules/bare-assert/index.js"(exports, module) {
var inspect = require_bare_inspect();
var AssertionError = class extends Error {
constructor(opts = {}) {
let { message = null, actual, expected, operator } = opts;
if (message === null) {
message = `${inspect(actual)} ${operator} ${inspect(expected)}`;
}
super(message);
this.actual = actual;
this.expected = expected;
this.operator = operator;
}
get name() {
return "AssertionError";
}
get code() {
"ASSERTION";
}
};
function assertFail(opts, fn) {
if (opts.message instanceof Error) throw opts.message;
const err = new AssertionError(opts);
if (Error.captureStackTrace) Error.captureStackTrace(err, fn);
throw err;
}
module.exports = exports = function assert(actual, message) {
if (actual) return;
assertFail({ message, actual, expected: true, operator: "==" }, assert);
};
exports.AssertionError = AssertionError;
exports.fail = function fail(message) {
if (message === void 0) message = "Failed";
assertFail({ message, operator: "fail" }, fail);
};
exports.ok = function ok(actual, message) {
if (actual) return;
assertFail({ message, actual, expected: true, operator: "==" }, ok);
};
exports.notOk = function ok(actual, message) {
if (!actual) return;
assertFail({ message, actual, expected: false, operator: "==" }, ok);
};
exports.equal = function equal(actual, expected, message) {
if (actual == expected || actual !== actual && expected !== expected) {
return;
}
assertFail({ message, actual, expected, operator: "==" }, equal);
};
exports.notEqual = function notEqual(actual, expected, message) {
if (actual != expected && (actual === actual || expected === expected)) {
return;
}
assertFail({ message, actual, expected, operator: "!=" }, notEqual);
};
exports.strictEqual = function strictEqual(actual, expected, message) {
if (Object.is(actual, expected)) return;
assertFail(
{ message, actual, expected, operator: "strictEqual" },
strictEqual
);
};
exports.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (!Object.is(actual, expected)) return;
assertFail(
{ message, actual, expected, operator: "notStrictEqual" },
notStrictEqual
);
};
}
});
// ../../node_modules/sodium-native/binding.js
var require_binding7 = __commonJS({
"../../node_modules/sodium-native/binding.js"(exports, module) {
__require.addon = require_node();
module.exports = __require.addon(".", __filename);
}
});
// ../../node_modules/which-runtime/index.js
var require_which_runtime = __commonJS({
"../../node_modules/which-runtime/index.js"(exports) {
var { runtime, platform, arch } = typeof Bare !== "undefined" ? { runtime: "bare", platform: global.Bare.platform, arch: global.Bare.arch } : typeof process !== "undefined" ? { runtime: "node", platform: global.process.platform, arch: global.process.arch } : typeof Window !== "undefined" ? { runtime: "browser", platform: "unknown", arch: "unknown" } : { runtime: "unknown", platform: "unknown", arch: "unknown" };
exports.runtime = runtime;
exports.platform = platform;
exports.arch = arch;
exports.isBare = runtime === "bare";
exports.isBareKit = exports.isBare && typeof BareKit !== "undefined";
exports.isPear = typeof Pear !== "undefined";
exports.isNode = runtime === "node";
exports.isBrowser = runtime === "browser";
exports.isWindows = platform === "win32";
exports.isLinux = platform === "linux";
exports.isMac = platform === "darwin";
exports.isIOS = platform === "ios" || platform === "ios-simulator";
exports.isAndroid = platform === "android";
exports.isElectron = typeof process !== "undefined" && !!global.process.versions?.electron;
exports.isElectronRenderer = exports.isElectron && global.process.type === "renderer";
exports.isElectronWorker = exports.isElectron && global.process.type === "worker";
}
});
// ../../node_modules/sodium-native/index.js
var require_sodium_native = __commonJS({
"../../node_modules/sodium-native/index.js"(exports, module) {
var assert = require_bare_assert();
var binding = require_binding7();
var { isNode } = require_which_runtime();
var OPTIONAL = Buffer.from(new ArrayBuffer(0));
module.exports = exports = { ...binding };
exports.sodium_memzero = function(buf) {
assert(ArrayBuffer.isView(buf), "buf must be a typed array");
binding.sodium_memzero(buf);
};
exports.sodium_mlock = function(buf) {
assert(ArrayBuffer.isView(buf), "buf must be a typed array");
const res = binding.sodium_mlock(buf);
if (res !== 0) throw new Error("memory lock failed");
};
exports.sodium_munlock = function(buf) {
assert(ArrayBuffer.isView(buf), "buf must be a typed array");
const res = binding.sodium_munlock(buf);
if (res !== 0) throw new Error("memory unlock failed");
};
exports.sodium_malloc = function(size) {
assert(size >= 0, "invalid size");
const buf = Buffer.from(binding.sodium_malloc(size));
buf.secure = true;
return buf;
};
exports.sodium_free = function(buf) {
if (!buf || !buf.secure) return;
binding.sodium_free(buf.buffer);
};
exports.sodium_mprotect_noaccess = function(buf) {
const res = binding.sodium_mprotect_noaccess(buf.buffer);
if (res !== 0) throw new Error("failed to lock buffer");
};
exports.sodium_mprotect_readonly = function(buf) {
const res = binding.sodium_mprotect_readonly(buf.buffer);
if (res !== 0) throw new Error("failed to unlock buffer");
};
exports.sodium_mprotect_readwrite = function(buf) {
const res = binding.sodium_mprotect_readwrite(buf.buffer);
if (res !== 0) throw new Error("failed to unlock buffer");
};
exports.randombytes_buf = function(buffer) {
assert(ArrayBuffer.isView(buffer), "buffer must be a typed array");
binding.randombytes_buf(buffer.buffer, buffer.byteOffset, buffer.byteLength);
};
exports.randombytes_buf_deterministic = function(buffer, seed) {
assert(ArrayBuffer.isView(buffer), "buffer must be a typed array");
assert(ArrayBuffer.isView(seed), "seed must be a typed array");
assert(
seed.byteLength === binding.randombytes_SEEDBYTES,
"seed must be 'randombytes_SEEDBYTES' bytes"
);
binding.randombytes_buf_deterministic(
buffer.buffer,
buffer.byteOffset,
buffer.byteLength,
seed.buffer,
seed.byteOffset,
seed.byteLength
);
};
exports.sodium_memcmp = function(a, b) {
assert(ArrayBuffer.isView(a), "a must be a typed array");
assert(ArrayBuffer.isView(b), "b must be a typed array");
assert(a.byteLength === b.byteLength, "buffers must be of same length");
return binding.sodium_memcmp(a, b);
};
exports.sodium_add = function(a, b) {
assert(ArrayBuffer.isView(a), "a must be a typed array");
assert(ArrayBuffer.isView(b), "b must be a typed array");
assert(a.byteLength === b.byteLength, "buffers must be of same length");
binding.sodium_add(a, b);
};
exports.sodium_sub = function(a, b) {
assert(ArrayBuffer.isView(a), "a must be a typed array");
assert(ArrayBuffer.isView(b), "b must be a typed array");
assert(a.byteLength === b.byteLength, "buffers must be of same length");
binding.sodium_sub(a, b);
};
exports.sodium_compare = function(a, b) {
assert(ArrayBuffer.isView(a), "a must be a typed array");
assert(ArrayBuffer.isView(b), "b must be a typed array");
assert(a.byteLength === b.byteLength, "buffers must be of same length");
return binding.sodium_compare(a, b);
};
exports.sodium_is_zero = function(buffer, length) {
if (length === void 0) length = buffer.byteLength;
assert(ArrayBuffer.isView(buffer), "buffer must be a typed array");
assert(length >= 0 && length <= buffer.byteLength, "invalid length");
return binding.sodium_is_zero(buffer, length);
};
exports.sodium_pad = function(buffer, unpaddedBuflen, blockSize) {
assert(ArrayBuffer.isView(buffer), "buffer must be a typed array");
assert(unpaddedBuflen <= buffer.byteLength, "unpadded length cannot exceed buffer length");
assert(blockSize <= buffer.byteLength, "block size cannot exceed buffer length");
assert(blockSize >= 1, "block size must be at least 1 byte");
assert(
buffer.byteLength >= unpaddedBuflen + (blockSize - unpaddedBuflen % blockSize),
"buf not long enough"
);
return binding.sodium_pad(buffer, unpaddedBuflen, blockSize);
};
exports.sodium_unpad = function(buffer, paddedBuflen, blockSize) {
assert(ArrayBuffer.isView(buffer), "buffer must be a typed array");
assert(paddedBuflen <= buffer.byteLength, "unpadded length cannot exceed buffer length");
assert(blockSize <= buffer.byteLength, "block size cannot exceed buffer length");
assert(blockSize >= 1, "block size must be at least 1 byte");
return binding.sodium_unpad(buffer, paddedBuflen, blockSize);
};
exports.crypto_sign_keypair = function(pk, sk) {
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(
pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
assert(
sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
"sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
);
const res = binding.crypto_sign_keypair(pk, sk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_sign_seed_keypair = function(pk, sk, seed) {
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(ArrayBuffer.isView(seed), "seed must be a typed array");
assert(
pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
assert(
sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
"sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
);
assert(
seed.byteLength === binding.crypto_sign_SEEDBYTES,
"seed must be 'crypto_sign_SEEDBYTES' bytes"
);
const res = binding.crypto_sign_seed_keypair(pk, sk, seed);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_sign = function(sm, m, sk) {
assert(ArrayBuffer.isView(sm), "sm must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(
sm.byteLength === binding.crypto_sign_BYTES + m.byteLength,
"sm must be 'm.byteLength + crypto_sign_BYTES' bytes"
);
assert(
sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
"sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
);
const res = binding.crypto_sign(sm, m, sk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_sign_open = function(m, sm, pk) {
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(sm), "sm must be a typed array");
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(
sm.byteLength >= binding.crypto_sign_BYTES,
"sm must be at least 'crypto_sign_BYTES' bytes"
);
assert(
m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
"m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
);
assert(
pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
const res = binding.crypto_sign_open(m, sm, pk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_sign_open = function(m, sm, pk) {
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(sm), "sm must be a typed array");
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(
sm.byteLength >= binding.crypto_sign_BYTES,
"sm must be at least 'crypto_sign_BYTES' bytes"
);
assert(
m.byteLength === sm.byteLength - binding.crypto_sign_BYTES,
"m must be 'sm.byteLength - crypto_sign_BYTES' bytes"
);
assert(
pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
return binding.crypto_sign_open(m, sm, pk);
};
exports.crypto_sign_detached = function(sig, m, sk) {
assert(ArrayBuffer.isView(sig), "sig must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes");
assert(
sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
"sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
);
const res = binding.crypto_sign_detached(sig, m, sk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_sign_verify_detached = function(sig, m, pk) {
assert(ArrayBuffer.isView(sig), "sig must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(
sig.byteLength >= binding.crypto_sign_BYTES,
"sig must be at least 'crypto_sign_BYTES' bytes"
);
assert(
pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
return binding.crypto_sign_verify_detached(
sig.buffer,
sig.byteOffset,
sig.byteLength,
m.buffer,
m.byteOffset,
m.byteLength,
pk.buffer,
pk.byteOffset,
pk.byteLength
);
};
exports.crypto_sign_ed25519_sk_to_pk = function(pk, sk) {
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(
pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
assert(
sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
"sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
);
const res = binding.crypto_sign_ed25519_sk_to_pk(pk, sk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_sign_ed25519_pk_to_curve25519 = function(x25519pk, ed25519pk) {
assert(ArrayBuffer.isView(x25519pk), "x25519pk must be a typed array");
assert(ArrayBuffer.isView(ed25519pk), "ed25519pk must be a typed array");
assert(
x25519pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
"x25519pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
);
assert(
ed25519pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"ed25519pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
const res = binding.crypto_sign_ed25519_pk_to_curve25519(x25519pk, ed25519pk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_sign_ed25519_sk_to_curve25519 = function(x25519sk, ed25519sk) {
assert(ArrayBuffer.isView(x25519sk), "x25519sk must be a typed array");
assert(ArrayBuffer.isView(ed25519sk), "ed25519sk must be a typed array");
assert(
x25519sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
"x25519sk must be 'crypto_box_SECRETKEYBYTES' bytes"
);
const edLen = ed25519sk.byteLength;
assert(
edLen === binding.crypto_sign_SECRETKEYBYTES || edLen === binding.crypto_box_SECRETKEYBYTES,
"ed25519sk must be 'crypto_sign_SECRETKEYBYTES' or 'crypto_sign_SECRETKEYBYTES - crypto_sign_PUBLICKEYBYTES' bytes"
);
const res = binding.crypto_sign_ed25519_sk_to_curve25519(x25519sk, ed25519sk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_box_keypair = function(pk, sk) {
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(
pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
"pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
);
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(
sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
"sk must be 'crypto_box_SECRETKEYBYTES' bytes"
);
const res = binding.crypto_box_keypair(pk, sk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_box_seed_keypair = function(pk, sk, seed) {
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(
pk.byteLength === binding.crypto_box_PUBLICKEYBYTES,
"pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
);
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(
sk.byteLength === binding.crypto_box_SECRETKEYBYTES,
"sk must be 'crypto_box_SECRETKEYBYTES' bytes"
);
assert(ArrayBuffer.isView(seed), "seed must be a typed array");
assert(
seed.byteLength === binding.crypto_box_SEEDBYTES,
"seed must be 'crypto_box_SEEDBYTES' bytes"
);
const res = binding.crypto_box_seed_keypair(pk, sk, seed);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_box_easy = function(c, m, n, pk, sk) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(
c.byteLength === m.byteLength + exports.crypto_box_MACBYTES,
"c must be 'm.byteLength + crypto_box_MACBYTES' bytes"
);
assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes");
assert(
pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
"pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
);
assert(
sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
"sk must be 'crypto_box_SECRETKEYBYTES' bytes"
);
const res = binding.crypto_box_easy(c, m, n, pk, sk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_box_detached = function(c, mac, m, n, pk, sk) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(mac), "mac must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes");
assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes");
assert(
pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
"pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
);
assert(
sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
"sk must be 'crypto_box_SECRETKEYBYTES' bytes"
);
const res = binding.crypto_box_detached(c, mac, m, n, pk, sk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_box_open_easy = function(m, c, n, pk, sk) {
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(
c.byteLength >= exports.crypto_box_MACBYTES,
"c must be at least 'crypto_box_MACBYTES' bytes"
);
assert(
m.byteLength === c.byteLength - exports.crypto_box_MACBYTES,
"m must be 'c.byteLength - crypto_box_MACBYTES' bytes"
);
assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes");
assert(
pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
"pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
);
assert(
sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
"sk must be 'crypto_box_SECRETKEYBYTES' bytes"
);
return binding.crypto_box_open_easy(m, c, n, pk, sk);
};
exports.crypto_box_open_detached = function(m, c, mac, n, pk, sk) {
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(mac), "mac must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes");
assert(mac.byteLength === exports.crypto_box_MACBYTES, "mac must be 'crypto_box_MACBYTES' bytes");
assert(n.byteLength === exports.crypto_box_NONCEBYTES, "n must be 'crypto_box_NONCEBYTES' bytes");
assert(
pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
"pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
);
assert(
sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
"sk must be 'crypto_box_SECRETKEYBYTES' bytes"
);
return binding.crypto_box_open_detached(m, c, mac, n, pk, sk);
};
exports.crypto_box_seal = function(c, m, pk) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(
c.byteLength === m.byteLength + exports.crypto_box_SEALBYTES,
"c must be 'm.byteLength + crypto_box_SEALBYTES' bytes"
);
assert(
pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
"pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
);
const res = binding.crypto_box_seal(c, m, pk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_box_seal_open = function(m, c, pk, sk) {
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(
c.byteLength >= exports.crypto_box_SEALBYTES,
"c must be at least 'crypto_box_SEALBYTES' bytes"
);
assert(
m.byteLength === c.byteLength - exports.crypto_box_SEALBYTES,
"m must be 'c.byteLength - crypto_box_SEALBYTES' bytes"
);
assert(
pk.byteLength === exports.crypto_box_PUBLICKEYBYTES,
"pk must be 'crypto_box_PUBLICKEYBYTES' bytes"
);
assert(
sk.byteLength === exports.crypto_box_SECRETKEYBYTES,
"sk must be 'crypto_box_SECRETKEYBYTES' bytes"
);
return binding.crypto_box_seal_open(
m.buffer,
m.byteOffset,
m.byteLength,
c.buffer,
c.byteOffset,
c.byteLength,
pk.buffer,
pk.byteOffset,
pk.byteLength,
sk.buffer,
sk.byteOffset,
sk.byteLength
);
};
exports.crypto_secretbox_easy = function(c, m, n, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
c.byteLength === m.byteLength + binding.crypto_secretbox_MACBYTES,
"c must be 'm.byteLength + crypto_secretbox_MACBYTES' bytes"
);
assert(
n.byteLength === binding.crypto_secretbox_NONCEBYTES,
"n must be 'crypto_secretbox_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_secretbox_KEYBYTES,
"k must be 'crypto_secretbox_KEYBYTES' bytes"
);
const res = binding.crypto_secretbox_easy(c, m, n, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_secretbox_open_easy = function(m, c, n, k) {
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
c.byteLength >= binding.crypto_secretbox_MACBYTES,
"c must be at least 'crypto_secretbox_MACBYTES' bytes"
);
assert(
m.byteLength === c.byteLength - binding.crypto_secretbox_MACBYTES,
"m must be 'c.byteLength - crypto_secretbox_MACBYTES' bytes"
);
assert(
n.byteLength === binding.crypto_secretbox_NONCEBYTES,
"n must be 'crypto_secretbox_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_secretbox_KEYBYTES,
"k must be 'crypto_secretbox_KEYBYTES' bytes"
);
return binding.crypto_secretbox_open_easy(m, c, n, k);
};
exports.crypto_secretbox_detached = function(c, mac, m, n, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(mac), "mac must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(
mac.byteLength === binding.crypto_secretbox_MACBYTES,
"mac must be 'crypto_secretbox_MACBYTES' bytes"
);
assert(
n.byteLength === binding.crypto_secretbox_NONCEBYTES,
"n must be 'crypto_secretbox_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_secretbox_KEYBYTES,
"k must be 'crypto_secretbox_KEYBYTES' bytes"
);
const res = binding.crypto_secretbox_detached(c, mac, m, n, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_secretbox_open_detached = function(m, c, mac, n, k) {
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(mac), "mac must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes");
assert(
mac.byteLength === binding.crypto_secretbox_MACBYTES,
"mac must be 'crypto_secretbox_MACBYTES' bytes"
);
assert(
n.byteLength === binding.crypto_secretbox_NONCEBYTES,
"n must be 'crypto_secretbox_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_secretbox_KEYBYTES,
"k must be 'crypto_secretbox_KEYBYTES' bytes"
);
return binding.crypto_secretbox_open_detached(m, c, mac, n, k);
};
exports.crypto_generichash = function(output, input, key) {
if (!key) key = OPTIONAL;
assert(ArrayBuffer.isView(output), "output must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(
output.byteLength >= binding.crypto_generichash_BYTES_MIN && output.byteLength <= binding.crypto_generichash_BYTES_MAX,
"output must be between crypto_generichash_BYTES_MIN and crypto_generichash_BYTES_MAX bytes"
);
if (key !== OPTIONAL) {
assert(ArrayBuffer.isView(key), "key must be a typed array");
assert(
key.byteLength >= binding.crypto_generichash_KEYBYTES_MIN && key.byteLength <= binding.crypto_generichash_KEYBYTES_MAX,
"key must be between crypto_generichash_KEYBYTES_MIN and crypto_generichash_KEYBYTES_MAX bytes"
);
}
const res = binding.crypto_generichash(
output.buffer,
output.byteOffset,
output.byteLength,
input.buffer,
input.byteOffset,
input.byteLength,
key.buffer,
key.byteOffset,
key.byteLength
);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_generichash_batch = function(output, batch, key) {
assert(ArrayBuffer.isView(output), "output must be a typed array");
if (isNode || batch.length < 4) {
const res = binding.crypto_generichash_batch(output, batch, !!key, key || OPTIONAL);
if (res !== 0) throw new Error("status: " + res);
} else {
const state = Buffer.alloc(binding.crypto_generichash_STATEBYTES);
exports.crypto_generichash_init(state, key, output.byteLength);
for (const buf of batch) {
exports.crypto_generichash_update(state, buf);
}
exports.crypto_generichash_final(state, output);
}
};
exports.crypto_generichash_keygen = function(key) {
assert(ArrayBuffer.isView(key), "key must be a typed array");
assert(
key.byteLength === binding.crypto_generichash_KEYBYTES,
"key must be 'crypto_generichash_KEYBYTES' bytes"
);
const res = binding.crypto_generichash_keygen(key.buffer, key.byteOffset, key.byteLength);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_generichash_init = function(state, key, outputLength) {
if (!key) key = OPTIONAL;
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_generichash_STATEBYTES,
"state must be 'crypto_generichash_STATEBYTES' bytes"
);
const res = binding.crypto_generichash_init(
state.buffer,
state.byteOffset,
state.byteLength,
key.buffer,
key.byteOffset,
key.byteLength,
outputLength
);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_generichash_update = function(state, input) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(
state.byteLength === binding.crypto_generichash_STATEBYTES,
"state must be 'crypto_generichash_STATEBYTES' bytes"
);
const res = binding.crypto_generichash_update(
state.buffer,
state.byteOffset,
state.byteLength,
input.buffer,
input.byteOffset,
input.byteLength
);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_generichash_final = function(state, output) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(ArrayBuffer.isView(output), "output must be a typed array");
assert(
state.byteLength === binding.crypto_generichash_STATEBYTES,
"state must be 'crypto_generichash_STATEBYTES' bytes"
);
const res = binding.crypto_generichash_final(
state.buffer,
state.byteOffset,
state.byteLength,
output.buffer,
output.byteOffset,
output.byteLength
);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_secretstream_xchacha20poly1305_keygen = function(k) {
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
"k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
);
binding.crypto_secretstream_xchacha20poly1305_keygen(k.buffer, k.byteOffset, k.byteLength);
};
exports.crypto_secretstream_xchacha20poly1305_init_push = function(state, header, k) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(ArrayBuffer.isView(header), "header must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
"state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
);
assert(
header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
"header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
"k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
);
const res = binding.crypto_secretstream_xchacha20poly1305_init_push(
state.buffer,
state.byteOffset,
state.byteLength,
header.buffer,
header.byteOffset,
header.byteLength,
k.buffer,
k.byteOffset,
k.byteLength
);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_secretstream_xchacha20poly1305_init_pull = function(state, header, k) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(ArrayBuffer.isView(header), "header must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
"state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
);
assert(
header.byteLength === binding.crypto_secretstream_xchacha20poly1305_HEADERBYTES,
"header must be 'crypto_secretstream_xchacha20poly1305_HEADERBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_secretstream_xchacha20poly1305_KEYBYTES,
"k must be 'crypto_secretstream_xchacha20poly1305_KEYBYTES' bytes"
);
const res = binding.crypto_secretstream_xchacha20poly1305_init_pull(
state.buffer,
state.byteOffset,
state.byteLength,
header.buffer,
header.byteOffset,
header.byteLength,
k.buffer,
k.byteOffset,
k.byteLength
);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_secretstream_xchacha20poly1305_push = function(state, c, m, ad, tag) {
if (!ad) ad = OPTIONAL;
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(
state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
"state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
);
assert(
c.byteLength === m.byteLength + binding.crypto_secretstream_xchacha20poly1305_ABYTES,
"c must be 'm.byteLength + crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
);
const res = binding.crypto_secretstream_xchacha20poly1305_push(
state.buffer,
state.byteOffset,
state.byteLength,
c.buffer,
c.byteOffset,
c.byteLength,
m.buffer,
m.byteOffset,
m.byteLength,
ad.buffer,
ad.byteOffset,
ad.byteLength,
tag
);
if (res < 0) throw new Error("push failed");
return res;
};
exports.crypto_secretstream_xchacha20poly1305_pull = function(state, m, tag, c, ad) {
if (!ad) ad = OPTIONAL;
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
"state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(tag), "tag must be a typed array");
assert(tag.byteLength === 1, "tag must be 1 byte");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(
c.byteLength >= binding.crypto_secretstream_xchacha20poly1305_ABYTES,
"c must be at least 'crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
);
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(
m.byteLength === c.byteLength - binding.crypto_secretstream_xchacha20poly1305_ABYTES,
"m must be 'c.byteLength - crypto_secretstream_xchacha20poly1305_ABYTES' bytes"
);
const res = binding.crypto_secretstream_xchacha20poly1305_pull(
state.buffer,
state.byteOffset,
state.byteLength,
m.buffer,
m.byteOffset,
m.byteLength,
tag.buffer,
tag.byteOffset,
tag.byteLength,
c.buffer,
c.byteOffset,
c.byteLength,
ad.buffer,
ad.byteOffset,
ad.byteLength
);
if (res < 0) throw new Error("pull failed");
return res;
};
exports.crypto_secretstream_xchacha20poly1305_rekey = function(state) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_secretstream_xchacha20poly1305_STATEBYTES,
"state must be 'crypto_secretstream_xchacha20poly1305_STATEBYTES' bytes"
);
binding.crypto_secretstream_xchacha20poly1305_rekey(
state.buffer,
state.byteOffset,
state.byteLength
);
};
exports.crypto_stream = function(c, n, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
n.byteLength === binding.crypto_stream_NONCEBYTES,
"n must be 'crypto_stream_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_KEYBYTES,
"k must be 'crypto_stream_KEYBYTES' bytes"
);
const res = binding.crypto_stream(c, n, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_xor = function(c, m, n, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(
n.byteLength === binding.crypto_stream_NONCEBYTES,
"n must be 'crypto_stream_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_KEYBYTES,
"k must be 'crypto_stream_KEYBYTES' bytes"
);
const res = binding.crypto_stream_xor(
c.buffer,
c.byteOffset,
c.byteLength,
m.buffer,
m.byteOffset,
m.byteLength,
n.buffer,
n.byteOffset,
n.byteLength,
k.buffer,
k.byteOffset,
k.byteLength
);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_chacha20 = function(c, n, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
"n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
"k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
);
const res = binding.crypto_stream_chacha20(c, n, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_chacha20_xor = function(c, m, n, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(
n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
"n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
"k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
);
const res = binding.crypto_stream_chacha20_xor(c, m, n, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_chacha20_xor_ic = function(c, m, n, ic, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(
n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
"n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
"k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
);
const res = binding.crypto_stream_chacha20_xor_ic(c, m, n, ic, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_chacha20_ietf = function(c, n, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
"n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
"k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
);
const res = binding.crypto_stream_chacha20_ietf(c, n, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_chacha20_ietf_xor = function(c, m, n, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(
n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
"n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
"k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
);
const res = binding.crypto_stream_chacha20_ietf_xor(c, m, n, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_chacha20_ietf_xor_ic = function(c, m, n, ic, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(
n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
"n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
"k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
);
const res = binding.crypto_stream_chacha20_ietf_xor_ic(c, m, n, ic, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_xchacha20 = function(c, n, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
"n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
"k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
);
const res = binding.crypto_stream_xchacha20(c, n, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_xchacha20_xor = function(c, m, n, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(
n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
"n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
"k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
);
const res = binding.crypto_stream_xchacha20_xor(c, m, n, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_xchacha20_xor_ic = function(c, m, n, ic, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(
n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
"n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
"k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
);
const res = binding.crypto_stream_xchacha20_xor_ic(c, m, n, ic, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_salsa20 = function(c, n, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
"n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
"k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
);
const res = binding.crypto_stream_salsa20(c, n, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_salsa20_xor = function(c, m, n, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(
n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
"n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
"k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
);
const res = binding.crypto_stream_salsa20_xor(c, m, n, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_stream_salsa20_xor_ic = function(c, m, n, ic, k) {
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(
n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
"n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
"k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
);
const res = binding.crypto_stream_salsa20_xor_ic(c, m, n, ic, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_auth = function(out, input, k) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(out.byteLength === binding.crypto_auth_BYTES, "out must be 'crypto_auth_BYTES' bytes");
assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes");
const res = binding.crypto_auth(out, input, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_auth_verify = function(h, input, k) {
assert(ArrayBuffer.isView(h), "h must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(h.byteLength === binding.crypto_auth_BYTES, "h must be 'crypto_auth_BYTES' bytes");
assert(k.byteLength === binding.crypto_auth_KEYBYTES, "k must be 'crypto_auth_KEYBYTES' bytes");
return binding.crypto_auth_verify(h, input, k);
};
exports.crypto_onetimeauth = function(out, input, k) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
out.byteLength === binding.crypto_onetimeauth_BYTES,
"out must be 'crypto_onetimeauth_BYTES' bytes"
);
assert(
k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
"k must be 'crypto_onetimeauth_KEYBYTES' bytes"
);
const res = binding.crypto_onetimeauth(out, input, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_onetimeauth_init = function(state, k) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
"state must be 'crypto_onetimeauth_STATEBYTES' bytes"
);
assert(
k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
"k must be 'crypto_onetimeauth_KEYBYTES' bytes"
);
const res = binding.crypto_onetimeauth_init(state, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_onetimeauth_update = function(state, input) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(
state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
"state must be 'crypto_onetimeauth_STATEBYTES' bytes"
);
const res = binding.crypto_onetimeauth_update(state, input);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_onetimeauth_final = function(state, out) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(
state.byteLength === binding.crypto_onetimeauth_STATEBYTES,
"state must be 'crypto_onetimeauth_STATEBYTES' bytes"
);
assert(
out.byteLength === binding.crypto_onetimeauth_BYTES,
"out must be 'crypto_onetimeauth_BYTES' bytes"
);
const res = binding.crypto_onetimeauth_final(state, out);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_onetimeauth_verify = function(h, input, k) {
assert(ArrayBuffer.isView(h), "h must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
h.byteLength === binding.crypto_onetimeauth_BYTES,
"h must be 'crypto_onetimeauth_BYTES' bytes"
);
assert(
k.byteLength === binding.crypto_onetimeauth_KEYBYTES,
"k must be 'crypto_onetimeauth_KEYBYTES' bytes"
);
return binding.crypto_onetimeauth_verify(h, input, k);
};
exports.crypto_pwhash = function(out, passwd, salt, opslimit, memlimit, alg) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(ArrayBuffer.isView(salt), "salt must be a typed array");
assert(
out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
"out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
);
assert(
out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
"out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
);
assert(
salt.byteLength === binding.crypto_pwhash_SALTBYTES,
"salt must be 'crypto_pwhash_SALTBYTES' bytes"
);
assert(
opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
"opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
);
assert(
opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
"opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
);
assert(
memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
"memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
);
assert(
memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
"memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
);
assert(alg >= 1 && alg <= 2, "alg must be either Argon2i 1.3 or Argon2id 1.3");
const res = binding.crypto_pwhash(out, passwd, salt, opslimit, memlimit, alg);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_pwhash_async = function(out, passwd, salt, opslimit, memlimit, alg, callback = void 0) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(ArrayBuffer.isView(salt), "salt must be a typed array");
assert(
out.byteLength >= binding.crypto_pwhash_BYTES_MIN,
"out must be at least 'crypto_pwhash_BYTES_MIN' bytes"
);
assert(
out.byteLength <= binding.crypto_pwhash_BYTES_MAX,
"out must be at most 'crypto_pwhash_BYTES_MAX' bytes"
);
assert(
salt.byteLength === binding.crypto_pwhash_SALTBYTES,
"salt must be 'crypto_pwhash_SALTBYTES' bytes"
);
assert(
opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
"opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
);
assert(
opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
"opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
);
assert(
memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
"memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
);
assert(
memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
"memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
);
assert(alg >= 1 && alg <= 2, "alg must be either Argon2i 1.3 or Argon2id 1.3");
const [done, promise] = checkStatus(callback);
binding.crypto_pwhash_async(
out.buffer,
out.byteOffset,
out.byteLength,
passwd.buffer,
passwd.byteOffset,
passwd.byteLength,
salt.buffer,
salt.byteOffset,
salt.byteLength,
opslimit,
memlimit,
alg,
done
);
return promise;
};
exports.crypto_pwhash_str = function(out, passwd, opslimit, memlimit) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(
out.byteLength === binding.crypto_pwhash_STRBYTES,
"out must be 'crypto_pwhash_STRBYTES' bytes"
);
assert(typeof opslimit === "number", "opslimit must be a number");
assert(
opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
"opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
);
assert(
opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
"opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
);
assert(typeof memlimit === "number", "memlimit must be a number");
assert(
memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
"memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
);
assert(
memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
"memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
);
const res = binding.crypto_pwhash_str(out, passwd, opslimit, memlimit);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_pwhash_str_async = function(out, passwd, opslimit, memlimit, callback = void 0) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(
out.byteLength === binding.crypto_pwhash_STRBYTES,
"out must be 'crypto_pwhash_STRBYTES' bytes"
);
assert(passwd.byteLength > 0, "passwd must not be empty");
assert(typeof opslimit === "number", "opslimit must be a number");
assert(
opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
"opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
);
assert(
opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
"opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
);
assert(typeof memlimit === "number", "memlimit must be a number");
assert(
memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
"memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
);
assert(
memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
"memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
);
const [done, promise] = checkStatus(callback);
binding.crypto_pwhash_str_async(
out.buffer,
out.byteOffset,
out.byteLength,
passwd.buffer,
passwd.byteOffset,
passwd.byteLength,
opslimit,
memlimit,
done
);
return promise;
};
exports.crypto_pwhash_str_verify = function(str, passwd) {
assert(ArrayBuffer.isView(str), "str must be a typed array");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(
str.byteLength === binding.crypto_pwhash_STRBYTES,
"str must be 'crypto_pwhash_STRBYTES' bytes"
);
return binding.crypto_pwhash_str_verify(str, passwd);
};
exports.crypto_pwhash_str_verify_async = function(str, passwd, callback = void 0) {
assert(ArrayBuffer.isView(str), "str must be a typed array");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(
str.byteLength === binding.crypto_pwhash_STRBYTES,
"str must be 'crypto_pwhash_STRBYTES' bytes"
);
assert(passwd.byteLength > 0, "passwd must not be empty");
const [done, promise] = checkStatus(callback, true);
binding.crypto_pwhash_str_verify_async(
str.buffer,
str.byteOffset,
str.byteLength,
passwd.buffer,
passwd.byteOffset,
passwd.byteLength,
done
);
return promise;
};
exports.crypto_pwhash_str_needs_rehash = function(str, opslimit, memlimit) {
assert(ArrayBuffer.isView(str), "str must be a typed array");
assert(
str.byteLength === binding.crypto_pwhash_STRBYTES,
"str must be 'crypto_pwhash_STRBYTES' bytes"
);
assert(
opslimit >= binding.crypto_pwhash_OPSLIMIT_MIN,
"opslimit must be at least 'crypto_pwhash_OPSLIMIT_MIN'"
);
assert(
opslimit <= binding.crypto_pwhash_OPSLIMIT_MAX,
"opslimit must be at most 'crypto_pwhash_OPSLIMIT_MAX'"
);
assert(
memlimit >= binding.crypto_pwhash_MEMLIMIT_MIN,
"memlimit must be at least 'crypto_pwhash_MEMLIMIT_MIN'"
);
assert(
memlimit <= binding.crypto_pwhash_MEMLIMIT_MAX,
"memlimit must be at most 'crypto_pwhash_MEMLIMIT_MAX'"
);
return binding.crypto_pwhash_str_needs_rehash(str, opslimit, memlimit);
};
exports.crypto_pwhash_scryptsalsa208sha256 = function(out, passwd, salt, opslimit, memlimit) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(ArrayBuffer.isView(salt), "salt must be a typed array");
assert(
out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
"out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
);
assert(
out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
"out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
);
assert(
salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
"salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
);
assert(
opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
"opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
);
assert(
opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
"opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
);
assert(
memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
"memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
);
assert(
memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
"memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
);
const res = binding.crypto_pwhash_scryptsalsa208sha256(out, passwd, salt, opslimit, memlimit);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_pwhash_scryptsalsa208sha256_async = function(out, passwd, salt, opslimit, memlimit, callback = void 0) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(ArrayBuffer.isView(salt), "salt must be a typed array");
assert(
out.byteLength >= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MIN,
"out must be at least 'crypto_pwhash_scryptsalsa208sha256_BYTES_MIN' bytes"
);
assert(
out.byteLength <= binding.crypto_pwhash_scryptsalsa208sha256_BYTES_MAX,
"out must be at most 'crypto_pwhash_scryptsalsa208sha256_BYTES_MAX' bytes"
);
assert(passwd.byteLength > 0, "passwd must not be empty");
assert(
salt.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_SALTBYTES,
"salt must be 'crypto_pwhash_scryptsalsa208sha256_SALTBYTES' bytes"
);
assert(
opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
"opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
);
assert(
opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
"opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
);
assert(
memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
"memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
);
assert(
memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
"memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
);
const [done, promise] = checkStatus(callback);
binding.crypto_pwhash_scryptsalsa208sha256_async(
out.buffer,
out.byteOffset,
out.byteLength,
passwd.buffer,
passwd.byteOffset,
passwd.byteLength,
salt.buffer,
salt.byteOffset,
salt.byteLength,
opslimit,
memlimit,
done
);
return promise;
};
exports.crypto_pwhash_scryptsalsa208sha256_str_async = function(out, passwd, opslimit, memlimit, callback = void 0) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(
out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
"out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
);
assert(passwd.byteLength > 0, "passwd must not be empty");
assert(
opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
"opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
);
assert(
opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
"opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
);
assert(
memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
"memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
);
assert(
memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
"memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
);
const [done, promise] = checkStatus(callback);
binding.crypto_pwhash_scryptsalsa208sha256_str_async(
out.buffer,
out.byteOffset,
out.byteLength,
passwd.buffer,
passwd.byteOffset,
passwd.byteLength,
opslimit,
memlimit,
done
);
return promise;
};
exports.crypto_pwhash_scryptsalsa208sha256_str = function(out, passwd, opslimit, memlimit) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(
out.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
"out must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
);
assert(passwd.byteLength > 0, "passwd must not be empty");
assert(
opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
"opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
);
assert(
opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
"opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
);
assert(
memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
"memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
);
assert(
memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
"memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
);
const res = binding.crypto_pwhash_scryptsalsa208sha256_str(out, passwd, opslimit, memlimit);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_pwhash_scryptsalsa208sha256_str_verify_async = function(str, passwd, callback = void 0) {
assert(ArrayBuffer.isView(str), "str must be a typed array");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(
str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
"str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
);
assert(passwd.byteLength > 0, "passwd must not be empty");
const [done, promise] = checkStatus(callback, true);
binding.crypto_pwhash_scryptsalsa208sha256_str_verify_async(
str.buffer,
str.byteOffset,
str.byteLength,
passwd.buffer,
passwd.byteOffset,
passwd.byteLength,
done
);
return promise;
};
exports.crypto_pwhash_scryptsalsa208sha256_str_verify = function(str, passwd) {
assert(ArrayBuffer.isView(str), "str must be a typed array");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(
str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
"str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
);
assert(passwd.byteLength > 0, "passwd must not be empty");
return binding.crypto_pwhash_scryptsalsa208sha256_str_verify(str, passwd);
};
exports.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash = function(str, opslimit, memlimit) {
assert(ArrayBuffer.isView(str), "str must be a typed array");
assert(
str.byteLength === binding.crypto_pwhash_scryptsalsa208sha256_STRBYTES,
"str must be 'crypto_pwhash_scryptsalsa208sha256_STRBYTES' bytes"
);
assert(
opslimit >= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN,
"opslimit must be at least 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN'"
);
assert(
opslimit <= binding.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX,
"opslimit must be at most 'crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX'"
);
assert(
memlimit >= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN,
"memlimit must be at least 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN'"
);
assert(
memlimit <= binding.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX,
"memlimit must be at most 'crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX'"
);
return binding.crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(str, opslimit, memlimit);
};
exports.crypto_kx_keypair = function(pk, sk) {
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(
pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
"pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
);
assert(
sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
"sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
);
const res = binding.crypto_kx_keypair(pk, sk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_kx_seed_keypair = function(pk, sk, seed) {
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(ArrayBuffer.isView(seed), "seed must be a typed array");
assert(
pk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
"pk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
);
assert(
sk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
"sk must be 'crypto_kx_SECRETKEYBYTES' bytes"
);
assert(
seed.byteLength === binding.crypto_kx_SEEDBYTES,
"seed must be 'crypto_kx_SEEDBYTES' bytes"
);
const res = binding.crypto_kx_seed_keypair(pk, sk, seed);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_kx_client_session_keys = function(rx, tx, clientPk, clientSk, serverPk) {
if (!rx) rx = void 0;
if (!tx) tx = void 0;
assert(rx || tx, "at least one session key must be specified");
if (rx) {
assert(ArrayBuffer.isView(rx), "rx must be a typed array");
assert(
rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
"rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
);
}
if (tx) {
assert(ArrayBuffer.isView(tx), "tx must be a typed array");
assert(
tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
"tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
);
}
assert(ArrayBuffer.isView(clientPk), "clientPk must be a typed array");
assert(ArrayBuffer.isView(clientSk), "clientSk must be a typed array");
assert(ArrayBuffer.isView(serverPk), "serverPk must be a typed array");
assert(
clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
"clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
);
assert(
clientSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
"clientSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
);
assert(
serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
"serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
);
const res = binding.crypto_kx_client_session_keys(rx, tx, clientPk, clientSk, serverPk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_kx_server_session_keys = function(rx, tx, serverPk, serverSk, clientPk) {
if (!rx) rx = void 0;
if (!tx) tx = void 0;
assert(rx || tx, "at least one session key must be specified");
if (rx) {
assert(ArrayBuffer.isView(rx), "rx must be a typed array");
assert(
rx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
"rx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
);
}
if (tx) {
assert(ArrayBuffer.isView(tx), "tx must be a typed array");
assert(
tx.byteLength === binding.crypto_kx_SESSIONKEYBYTES,
"tx must be 'crypto_kx_SESSIONKEYBYTES' bytes"
);
}
assert(ArrayBuffer.isView(serverPk), "serverPk must be a typed array");
assert(ArrayBuffer.isView(serverSk), "serverSk must be a typed array");
assert(ArrayBuffer.isView(clientPk), "clientPk must be a typed array");
assert(
serverPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
"serverPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
);
assert(
serverSk.byteLength === binding.crypto_kx_SECRETKEYBYTES,
"serverSk must be 'crypto_kx_SECRETKEYBYTES' bytes"
);
assert(
clientPk.byteLength === binding.crypto_kx_PUBLICKEYBYTES,
"clientPk must be 'crypto_kx_PUBLICKEYBYTES' bytes"
);
const res = binding.crypto_kx_server_session_keys(rx, tx, serverPk, serverSk, clientPk);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_scalarmult_base = function(q, n) {
assert(ArrayBuffer.isView(q), "q must be a typed array");
assert(
q.byteLength === binding.crypto_scalarmult_BYTES,
"q must be 'crypto_scalarmult_BYTES' bytes"
);
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
"n must be 'crypto_scalarmult_SCALARBYTES' bytes"
);
const res = binding.crypto_scalarmult_base(q, n);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_scalarmult = function(q, n, p) {
assert(ArrayBuffer.isView(q), "q must be a typed array");
assert(
q.byteLength === binding.crypto_scalarmult_BYTES,
"q must be 'crypto_scalarmult_BYTES' bytes"
);
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.crypto_scalarmult_SCALARBYTES,
"n must be 'crypto_scalarmult_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(p), "p must be a typed array");
assert(
p.byteLength === binding.crypto_scalarmult_BYTES,
"p must be 'crypto_scalarmult_BYTES' bytes"
);
const res = binding.crypto_scalarmult(q, n, p);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_scalarmult_ed25519_base = function(q, n) {
assert(ArrayBuffer.isView(q), "q must be a typed array");
assert(
q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
"q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
);
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
"n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
);
const res = binding.crypto_scalarmult_ed25519_base(q, n);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_scalarmult_ed25519 = function(q, n, p) {
assert(ArrayBuffer.isView(q), "q must be a typed array");
assert(
q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
"q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
);
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
"n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(p), "p must be a typed array");
assert(
p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
"p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
);
const res = binding.crypto_scalarmult_ed25519(q, n, p);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_core_ed25519_is_valid_point = function(p) {
assert(ArrayBuffer.isView(p), "p must be a typed array");
assert(
p.byteLength === binding.crypto_core_ed25519_BYTES,
"p must be 'crypto_core_ed25519_BYTES' bytes"
);
return binding.crypto_core_ed25519_is_valid_point(p);
};
exports.crypto_core_ed25519_from_uniform = function(p, r) {
assert(ArrayBuffer.isView(p), "p must be a typed array");
assert(
p.byteLength === binding.crypto_core_ed25519_BYTES,
"p must be 'crypto_core_ed25519_BYTES' bytes"
);
assert(ArrayBuffer.isView(r), "r must be a typed array");
assert(
r.byteLength === binding.crypto_core_ed25519_UNIFORMBYTES,
"r must be 'crypto_core_ed25519_UNIFORMBYTES' bytes"
);
const res = binding.crypto_core_ed25519_from_uniform(p, r);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_scalarmult_ed25519_base_noclamp = function(q, n) {
assert(ArrayBuffer.isView(q), "q must be a typed array");
assert(
q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
"q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
);
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
"n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
);
const res = binding.crypto_scalarmult_ed25519_base_noclamp(q, n);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_scalarmult_ed25519_noclamp = function(q, n, p) {
assert(ArrayBuffer.isView(q), "q must be a typed array");
assert(
q.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
"q must be 'crypto_scalarmult_ed25519_BYTES' bytes"
);
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.crypto_scalarmult_ed25519_SCALARBYTES,
"n must be 'crypto_scalarmult_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(p), "p must be a typed array");
assert(
p.byteLength === binding.crypto_scalarmult_ed25519_BYTES,
"p must be 'crypto_scalarmult_ed25519_BYTES' bytes"
);
const res = binding.crypto_scalarmult_ed25519_noclamp(q, n, p);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_core_ed25519_add = function(r, p, q) {
assert(ArrayBuffer.isView(r), "r must be a typed array");
assert(
r.byteLength === binding.crypto_core_ed25519_BYTES,
"r must be 'crypto_core_ed25519_BYTES' bytes"
);
assert(ArrayBuffer.isView(p), "p must be a typed array");
assert(
p.byteLength === binding.crypto_core_ed25519_BYTES,
"p must be 'crypto_core_ed25519_BYTES' bytes"
);
assert(ArrayBuffer.isView(q), "q must be a typed array");
assert(
q.byteLength === binding.crypto_core_ed25519_BYTES,
"q must be 'crypto_core_ed25519_BYTES' bytes"
);
const res = binding.crypto_core_ed25519_add(r, p, q);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_core_ed25519_sub = function(r, p, q) {
assert(ArrayBuffer.isView(r), "r must be a typed array");
assert(
r.byteLength === binding.crypto_core_ed25519_BYTES,
"r must be 'crypto_core_ed25519_BYTES' bytes"
);
assert(ArrayBuffer.isView(p), "p must be a typed array");
assert(
p.byteLength === binding.crypto_core_ed25519_BYTES,
"p must be 'crypto_core_ed25519_BYTES' bytes"
);
assert(ArrayBuffer.isView(q), "q must be a typed array");
assert(
q.byteLength === binding.crypto_core_ed25519_BYTES,
"q must be 'crypto_core_ed25519_BYTES' bytes"
);
const res = binding.crypto_core_ed25519_sub(r, p, q);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_core_ed25519_scalar_random = function(r) {
assert(ArrayBuffer.isView(r), "r must be a typed array");
assert(
r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
binding.crypto_core_ed25519_scalar_random(r);
};
exports.crypto_core_ed25519_scalar_reduce = function(r, s) {
assert(ArrayBuffer.isView(r), "r must be a typed array");
assert(
r.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"r must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(s), "s must be a typed array");
assert(
s.byteLength === binding.crypto_core_ed25519_NONREDUCEDSCALARBYTES,
"s must be 'crypto_core_ed25519_NONREDUCEDSCALARBYTES' bytes"
);
binding.crypto_core_ed25519_scalar_reduce(r, s);
};
exports.crypto_core_ed25519_scalar_invert = function(recip, s) {
assert(ArrayBuffer.isView(recip), "recip must be a typed array");
assert(
recip.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"recip must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(s), "s must be a typed array");
assert(
s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
binding.crypto_core_ed25519_scalar_invert(recip, s);
};
exports.crypto_core_ed25519_scalar_negate = function(neg, s) {
assert(ArrayBuffer.isView(neg), "neg must be a typed array");
assert(
neg.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"neg must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(s), "s must be a typed array");
assert(
s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
binding.crypto_core_ed25519_scalar_negate(neg, s);
};
exports.crypto_core_ed25519_scalar_complement = function(comp, s) {
assert(ArrayBuffer.isView(comp), "comp must be a typed array");
assert(
comp.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"comp must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(s), "s must be a typed array");
assert(
s.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"s must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
binding.crypto_core_ed25519_scalar_complement(comp, s);
};
exports.crypto_core_ed25519_scalar_add = function(z, x, y) {
assert(ArrayBuffer.isView(z), "z must be a typed array");
assert(
z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(x), "x must be a typed array");
assert(
x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(y), "y must be a typed array");
assert(
y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
binding.crypto_core_ed25519_scalar_add(z, x, y);
};
exports.crypto_core_ed25519_scalar_sub = function(z, x, y) {
assert(ArrayBuffer.isView(z), "z must be a typed array");
assert(
z.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"z must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(x), "x must be a typed array");
assert(
x.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"x must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(y), "y must be a typed array");
assert(
y.byteLength === binding.crypto_core_ed25519_SCALARBYTES,
"y must be 'crypto_core_ed25519_SCALARBYTES' bytes"
);
binding.crypto_core_ed25519_scalar_sub(z, x, y);
};
exports.crypto_shorthash = function(out, input, k) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(
out.byteLength === binding.crypto_shorthash_BYTES,
"out must be 'crypto_shorthash_BYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_shorthash_KEYBYTES,
"k must be 'crypto_shorthash_KEYBYTES' bytes"
);
const res = binding.crypto_shorthash(out, input, k);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_kdf_keygen = function(key) {
assert(ArrayBuffer.isView(key), "key must be a typed array");
assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes");
binding.crypto_kdf_keygen(key);
};
exports.crypto_kdf_derive_from_key = function(subkey, subkeyId, ctx, key) {
assert(ArrayBuffer.isView(subkey), "subkey must be a typed array");
assert(
subkey.byteLength >= binding.crypto_kdf_BYTES_MIN,
"subkey must be at least 'crypto_kdf_BYTES_MIN' bytes"
);
assert(
subkey.byteLength <= binding.crypto_kdf_BYTES_MAX,
"subkey must be at most 'crypto_kdf_BYTES_MAX' bytes"
);
assert(ArrayBuffer.isView(ctx), "ctx must be a typed array");
assert(
ctx.byteLength === binding.crypto_kdf_CONTEXTBYTES,
"ctx must be 'crypto_kdf_CONTEXTBYTES' bytes"
);
assert(ArrayBuffer.isView(key), "key must be a typed array");
assert(key.byteLength === binding.crypto_kdf_KEYBYTES, "key must be 'crypto_kdf_KEYBYTES' bytes");
const res = binding.crypto_kdf_derive_from_key(subkey, subkeyId, ctx, key);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_hash = function(out, input) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(out.byteLength === binding.crypto_hash_BYTES, "out must be 'crypto_hash_BYTES' bytes");
const res = binding.crypto_hash(out, input);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_hash_sha256 = function(out, input) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(
out.byteLength === binding.crypto_hash_sha256_BYTES,
"out must be 'crypto_hash_sha256_BYTES' bytes"
);
const res = binding.crypto_hash_sha256(out, input);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_hash_sha256_init = function(state) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
"state must be 'crypto_hash_sha256_STATEBYTES' bytes"
);
const res = binding.crypto_hash_sha256_init(state);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_hash_sha256_update = function(state, input) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(
state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
"state must be 'crypto_hash_sha256_STATEBYTES' bytes"
);
const res = binding.crypto_hash_sha256_update(state, input);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_hash_sha256_final = function(state, out) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_hash_sha256_STATEBYTES,
"state must be 'crypto_hash_sha256_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(
out.byteLength === binding.crypto_hash_sha256_BYTES,
"out must be 'crypto_hash_sha256_BYTES' bytes"
);
const res = binding.crypto_hash_sha256_final(state, out);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_hash_sha512 = function(out, input) {
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(
out.byteLength === binding.crypto_hash_sha512_BYTES,
"out must be 'crypto_hash_sha512_BYTES' bytes"
);
const res = binding.crypto_hash_sha512(out, input);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_hash_sha512_init = function(state) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
"state must be 'crypto_hash_sha512_STATEBYTES' bytes"
);
const res = binding.crypto_hash_sha512_init(state);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_hash_sha512_update = function(state, input) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(ArrayBuffer.isView(input), "input must be a typed array");
assert(
state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
"state must be 'crypto_hash_sha512_STATEBYTES' bytes"
);
const res = binding.crypto_hash_sha512_update(state, input);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_hash_sha512_final = function(state, out) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_hash_sha512_STATEBYTES,
"state must be 'crypto_hash_sha512_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(
out.byteLength === binding.crypto_hash_sha512_BYTES,
"out must be 'crypto_hash_sha512_BYTES' bytes"
);
const res = binding.crypto_hash_sha512_final(state, out);
if (res !== 0) throw new Error("status: " + res);
};
exports.crypto_aead_xchacha20poly1305_ietf_keygen = function(k) {
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
"k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
);
binding.crypto_aead_xchacha20poly1305_ietf_keygen(k);
};
exports.crypto_aead_xchacha20poly1305_ietf_encrypt = function(c, m, ad, nsec, npub, k) {
if (!ad) ad = void 0;
assert(nsec === null, "nsec must always be set to null");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(
c.byteLength === m.byteLength + binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
"c must be 'm.byteLength + crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
);
assert(c.byteLength <= 4294967295, "c.byteLength must be a 32bit integer");
assert(ArrayBuffer.isView(npub), "npub must be a typed array");
assert(
npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
"npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
"k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
);
const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt(c, m, ad, npub, k);
if (res < 0) throw new Error("could not encrypt data");
return res;
};
exports.crypto_aead_xchacha20poly1305_ietf_decrypt = function(m, nsec, c, ad, npub, k) {
if (!ad) ad = void 0;
assert(nsec === null, "nsec must always be set to null");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(
m.byteLength === c.byteLength - binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
"m must be 'c.byteLength - crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
);
assert(m.byteLength <= 4294967295, "m.byteLength must be a 32bit integer");
assert(ArrayBuffer.isView(npub), "npub must be a typed array");
assert(
npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
"npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
"k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
);
const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt(m, c, ad, npub, k);
if (res < 0) throw new Error("could not verify data");
return res;
};
exports.crypto_aead_xchacha20poly1305_ietf_encrypt_detached = function(c, mac, m, ad, nsec, npub, k) {
if (!ad) ad = void 0;
assert(nsec === null, "nsec must always be set to null");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(ArrayBuffer.isView(mac), "mac must be a typed array");
assert(
mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
"mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
);
assert(ArrayBuffer.isView(npub), "npub must be a typed array");
assert(
npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
"npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
"k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
);
const res = binding.crypto_aead_xchacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k);
if (res < 0) throw new Error("could not encrypt data");
return res;
};
exports.crypto_aead_xchacha20poly1305_ietf_decrypt_detached = function(m, nsec, c, mac, ad, npub, k) {
if (!ad) ad = void 0;
assert(nsec === null, "nsec must always be set to null");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes");
assert(ArrayBuffer.isView(mac), "mac must be a typed array");
assert(
mac.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_ABYTES,
"mac must be 'crypto_aead_xchacha20poly1305_ietf_ABYTES' bytes"
);
assert(ArrayBuffer.isView(npub), "npub must be a typed array");
assert(
npub.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES,
"npub must be 'crypto_aead_xchacha20poly1305_ietf_NPUBBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_aead_xchacha20poly1305_ietf_KEYBYTES,
"k must be 'crypto_aead_xchacha20poly1305_ietf_KEYBYTES' bytes"
);
const res = binding.crypto_aead_xchacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k);
if (res !== 0) throw new Error("could not verify data");
};
exports.crypto_aead_chacha20poly1305_ietf_keygen = function(k) {
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
"k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
);
binding.crypto_aead_chacha20poly1305_ietf_keygen(k);
};
exports.crypto_aead_chacha20poly1305_ietf_encrypt = function(c, m, ad, nsec, npub, k) {
if (!ad) ad = void 0;
assert(nsec === null, "nsec must always be set to null");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(
c.byteLength === m.byteLength + binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
"c must be 'm.byteLength + crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
);
assert(c.byteLength <= 4294967295, "c.byteLength must be a 32bit integer");
assert(ArrayBuffer.isView(npub), "npub must be a typed array");
assert(
npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
"npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
"k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
);
const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt(c, m, ad, npub, k);
if (res < 0) throw new Error("could not encrypt data");
return res;
};
exports.crypto_aead_chacha20poly1305_ietf_decrypt = function(m, nsec, c, ad, npub, k) {
if (!ad) ad = void 0;
assert(nsec === null, "nsec must always be set to null");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(
m.byteLength === c.byteLength - binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
"m must be 'c.byteLength - crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
);
assert(m.byteLength <= 4294967295, "m.byteLength must be a 32bit integer");
assert(ArrayBuffer.isView(npub), "npub must be a typed array");
assert(
npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
"npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
"k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
);
const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt(m, c, ad, npub, k);
if (res < 0) throw new Error("could not verify data");
return res;
};
exports.crypto_aead_chacha20poly1305_ietf_encrypt_detached = function(c, mac, m, ad, nsec, npub, k) {
if (!ad) ad = void 0;
assert(nsec === null, "nsec must always be set to null");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
assert(ArrayBuffer.isView(mac), "mac must be a typed array");
assert(
mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
"mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
);
assert(ArrayBuffer.isView(npub), "npub must be a typed array");
assert(
npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
"npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
"k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
);
const res = binding.crypto_aead_chacha20poly1305_ietf_encrypt_detached(c, mac, m, ad, npub, k);
if (res < 0) throw new Error("could not encrypt data");
return res;
};
exports.crypto_aead_chacha20poly1305_ietf_decrypt_detached = function(m, nsec, c, mac, ad, npub, k) {
if (!ad) ad = void 0;
assert(nsec === null, "nsec must always be set to null");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(m.byteLength === c.byteLength, "m must be 'c.byteLength' bytes");
assert(ArrayBuffer.isView(mac), "mac must be a typed array");
assert(
mac.byteLength === binding.crypto_aead_chacha20poly1305_ietf_ABYTES,
"mac must be 'crypto_aead_chacha20poly1305_ietf_ABYTES' bytes"
);
assert(ArrayBuffer.isView(npub), "npub must be a typed array");
assert(
npub.byteLength === binding.crypto_aead_chacha20poly1305_ietf_NPUBBYTES,
"npub must be 'crypto_aead_chacha20poly1305_ietf_NPUBBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_aead_chacha20poly1305_ietf_KEYBYTES,
"k must be 'crypto_aead_chacha20poly1305_ietf_KEYBYTES' bytes"
);
const res = binding.crypto_aead_chacha20poly1305_ietf_decrypt_detached(m, c, mac, ad, npub, k);
if (res !== 0) throw new Error("could not verify data");
};
exports.crypto_stream_xor_wrap_init = function(state, n, k) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
"state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.crypto_stream_NONCEBYTES,
"n must be 'crypto_stream_NONCEBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_stream_KEYBYTES,
"k must be 'crypto_stream_KEYBYTES' bytes"
);
binding.crypto_stream_xor_wrap_init(state, n, k);
};
exports.crypto_stream_xor_wrap_update = function(state, c, m) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
"state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
binding.crypto_stream_xor_wrap_update(state, c, m);
};
exports.crypto_stream_xor_wrap_final = function(state) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.sn_crypto_stream_xor_STATEBYTES,
"state must be 'sn_crypto_stream_xor_STATEBYTES' bytes"
);
binding.crypto_stream_xor_wrap_final(state);
};
exports.crypto_stream_chacha20_xor_wrap_init = function(state, n, k) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
"state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.crypto_stream_chacha20_NONCEBYTES,
"n must be 'crypto_stream_chacha20_NONCEBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_stream_chacha20_KEYBYTES,
"k must be 'crypto_stream_chacha20_KEYBYTES' bytes"
);
binding.crypto_stream_chacha20_xor_wrap_init(state, n, k);
};
exports.crypto_stream_chacha20_xor_wrap_update = function(state, c, m) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
"state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
binding.crypto_stream_chacha20_xor_wrap_update(state, c, m);
};
exports.crypto_stream_chacha20_xor_wrap_final = function(state) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_stream_chacha20_xor_STATEBYTES,
"state must be 'crypto_stream_chacha20_xor_STATEBYTES' bytes"
);
binding.crypto_stream_chacha20_xor_wrap_final(state);
};
exports.crypto_stream_chacha20_ietf_xor_wrap_init = function(state, n, k) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
"state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.crypto_stream_chacha20_ietf_NONCEBYTES,
"n must be 'crypto_stream_chacha20_ietf_NONCEBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_stream_chacha20_ietf_KEYBYTES,
"k must be 'crypto_stream_chacha20_ietf_KEYBYTES' bytes"
);
binding.crypto_stream_chacha20_ietf_xor_wrap_init(state, n, k);
};
exports.crypto_stream_chacha20_ietf_xor_wrap_update = function(state, c, m) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
"state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
binding.crypto_stream_chacha20_ietf_xor_wrap_update(state, c, m);
};
exports.crypto_stream_chacha20_ietf_xor_wrap_final = function(state) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_stream_chacha20_ietf_xor_STATEBYTES,
"state must be 'crypto_stream_chacha20_ietf_xor_STATEBYTES' bytes"
);
binding.crypto_stream_chacha20_ietf_xor_wrap_final(state);
};
exports.crypto_stream_xchacha20_xor_wrap_init = function(state, n, k) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
"state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.crypto_stream_xchacha20_NONCEBYTES,
"n must be 'crypto_stream_xchacha20_NONCEBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_stream_xchacha20_KEYBYTES,
"k must be 'crypto_stream_xchacha20_KEYBYTES' bytes"
);
binding.crypto_stream_xchacha20_xor_wrap_init(state, n, k);
};
exports.crypto_stream_xchacha20_xor_wrap_update = function(state, c, m) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
"state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
binding.crypto_stream_xchacha20_xor_wrap_update(state, c, m);
};
exports.crypto_stream_xchacha20_xor_wrap_final = function(state) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_stream_xchacha20_xor_STATEBYTES,
"state must be 'crypto_stream_xchacha20_xor_STATEBYTES' bytes"
);
binding.crypto_stream_xchacha20_xor_wrap_final(state);
};
exports.crypto_stream_salsa20_xor_wrap_init = function(state, n, k) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
"state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.crypto_stream_salsa20_NONCEBYTES,
"n must be 'crypto_stream_salsa20_NONCEBYTES' bytes"
);
assert(ArrayBuffer.isView(k), "k must be a typed array");
assert(
k.byteLength === binding.crypto_stream_salsa20_KEYBYTES,
"k must be 'crypto_stream_salsa20_KEYBYTES' bytes"
);
binding.crypto_stream_salsa20_xor_wrap_init(state, n, k);
};
exports.crypto_stream_salsa20_xor_wrap_update = function(state, c, m) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
"state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
);
assert(ArrayBuffer.isView(c), "c must be a typed array");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(c.byteLength === m.byteLength, "c must be 'm.byteLength' bytes");
binding.crypto_stream_salsa20_xor_wrap_update(state, c, m);
};
exports.crypto_stream_salsa20_xor_wrap_final = function(state) {
assert(ArrayBuffer.isView(state), "state must be a typed array");
assert(
state.byteLength === binding.crypto_stream_salsa20_xor_STATEBYTES,
"state must be 'crypto_stream_salsa20_xor_STATEBYTES' bytes"
);
binding.crypto_stream_salsa20_xor_wrap_final(state);
};
exports.extension_tweak_ed25519_base = function(n, p, ns) {
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(p), "p must be a typed array");
assert(
p.byteLength === binding.extension_tweak_ed25519_BYTES,
"p must be 'extension_tweak_ed25519_BYTES' bytes"
);
binding.extension_tweak_ed25519_base(n, p, ns);
};
exports.extension_tweak_ed25519_sign_detached = function(sig, m, scalar, pk) {
assert(ArrayBuffer.isView(sig), "sig must be a typed array");
assert(sig.byteLength === binding.crypto_sign_BYTES, "sig must be 'crypto_sign_BYTES' bytes");
assert(ArrayBuffer.isView(m), "m must be a typed array");
assert(ArrayBuffer.isView(scalar), "scalar must be a typed array");
assert(
scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
if (pk) {
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(
pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
}
const res = binding.extension_tweak_ed25519_sign_detached(sig, m, scalar, pk);
if (res !== 0) throw new Error("failed to compute signature");
};
exports.extension_tweak_ed25519_sk_to_scalar = function(n, sk) {
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(sk), "sk must be a typed array");
assert(
sk.byteLength === binding.crypto_sign_SECRETKEYBYTES,
"sk must be 'crypto_sign_SECRETKEYBYTES' bytes"
);
binding.extension_tweak_ed25519_sk_to_scalar(n, sk);
};
exports.extension_tweak_ed25519_scalar = function(scalarOut, scalar, ns) {
assert(ArrayBuffer.isView(scalarOut), "scalarOut must be a typed array");
assert(
scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(scalar), "scalar must be a typed array");
assert(
scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
binding.extension_tweak_ed25519_scalar(scalarOut, scalar, ns);
};
exports.extension_tweak_ed25519_pk = function(tpk, pk, ns) {
assert(ArrayBuffer.isView(tpk), "tpk must be a typed array");
assert(
tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(
pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
const res = binding.extension_tweak_ed25519_pk(tpk, pk, ns);
if (res !== 0) throw new Error("failed to tweak public key");
};
exports.extension_tweak_ed25519_keypair = function(pk, scalarOut, scalarIn, ns) {
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(
pk.byteLength === binding.extension_tweak_ed25519_BYTES,
"pk must be 'extension_tweak_ed25519_BYTES' bytes"
);
assert(ArrayBuffer.isView(scalarOut), "scalarOut must be a typed array");
assert(
scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(scalarIn), "scalarIn must be a typed array");
assert(
scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
binding.extension_tweak_ed25519_keypair(pk, scalarOut, scalarIn, ns);
};
exports.extension_tweak_ed25519_scalar_add = function(scalarOut, scalar, n) {
assert(ArrayBuffer.isView(scalarOut), "scalarOut must be a typed array");
assert(
scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(scalar), "scalar must be a typed array");
assert(
scalar.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"scalar must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(n), "n must be a typed array");
assert(
n.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"n must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
binding.extension_tweak_ed25519_scalar_add(scalarOut, scalar, n);
};
exports.extension_tweak_ed25519_pk_add = function(tpk, pk, p) {
assert(ArrayBuffer.isView(tpk), "tpk must be a typed array");
assert(
tpk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"tpk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(
pk.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"pk must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
assert(ArrayBuffer.isView(p), "p must be a typed array");
assert(
p.byteLength === binding.crypto_sign_PUBLICKEYBYTES,
"p must be 'crypto_sign_PUBLICKEYBYTES' bytes"
);
const res = binding.extension_tweak_ed25519_pk_add(tpk, pk, p);
if (res !== 0) throw new Error("failed to add tweak to public key");
};
exports.extension_tweak_ed25519_keypair_add = function(pk, scalarOut, scalarIn, tweak) {
assert(ArrayBuffer.isView(pk), "pk must be a typed array");
assert(
pk.byteLength === binding.extension_tweak_ed25519_BYTES,
"pk must be 'extension_tweak_ed25519_BYTES' bytes"
);
assert(ArrayBuffer.isView(scalarOut), "scalarOut must be a typed array");
assert(
scalarOut.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"scalarOut must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(scalarIn), "scalarIn must be a typed array");
assert(
scalarIn.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"scalarIn must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
assert(ArrayBuffer.isView(tweak), "tweak must be a typed array");
assert(
tweak.byteLength === binding.extension_tweak_ed25519_SCALARBYTES,
"tweak must be 'extension_tweak_ed25519_SCALARBYTES' bytes"
);
const res = binding.extension_tweak_ed25519_keypair_add(pk, scalarOut, scalarIn, tweak);
if (res !== 0) throw new Error("failed to add tweak to keypair");
};
exports.extension_pbkdf2_sha512_async = function(out, passwd, salt, iter, outlen, callback) {
assert(
iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
"iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
);
assert(
outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
"outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
);
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes");
assert(out.byteLength > 0, "out must not be empty");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(passwd.byteLength > 0, "passwd must not be empty");
assert(ArrayBuffer.isView(salt), "salt must be a typed array");
assert(salt.byteLength > 0, "salt must not be empty");
const [done, promise] = checkStatus(callback);
binding.extension_pbkdf2_sha512_async(
out.buffer,
out.byteOffset,
out.byteLength,
passwd.buffer,
passwd.byteOffset,
passwd.byteLength,
salt.buffer,
salt.byteOffset,
salt.byteLength,
iter,
outlen,
done
);
return promise;
};
exports.extension_pbkdf2_sha512 = function(out, passwd, salt, iter, outlen) {
assert(
iter >= binding.extension_pbkdf2_sha512_ITERATIONS_MIN,
"iter must be at least 'extension_pbkdf2_sha512_ITERATIONS_MIN'"
);
assert(
outlen <= binding.extension_pbkdf2_sha512_BYTES_MAX,
"outlen must be at most 'extension_pbkdf2_sha512_BYTES_MAX'"
);
assert(ArrayBuffer.isView(out), "out must be a typed array");
assert(out.byteLength >= outlen, "out must be at least 'outlen' bytes");
assert(out.byteLength > 0, "out must not be empty");
assert(ArrayBuffer.isView(passwd), "passwd must be a typed array");
assert(passwd.byteLength > 0, "passwd must not be empty");
assert(ArrayBuffer.isView(salt), "salt must be a typed array");
assert(salt.byteLength > 0, "salt must not be empty");
const res = binding.extension_pbkdf2_sha512(out, passwd, salt, iter, outlen);
if (res !== 0) throw new Error("failed to add tweak to public key");
};
function checkStatus(callback, booleanResult = false) {
let done, promise;
if (typeof callback === "function") {
done = function(status) {
if (booleanResult) callback(null, status === 0);
else if (status === 0) callback(null);
else callback(new Error("status: " + status));
};
} else {
promise = new Promise(function(resolve, reject) {
done = function(status) {
if (booleanResult) resolve(status === 0);
else if (status === 0) resolve();
else reject(new Error("status: " + status));
};
});
}
return [done, promise];
}
}
});
// ../../node_modules/sodium-universal/index.js
var require_sodium_universal = __commonJS({
"../../node_modules/sodium-universal/index.js"(exports, module) {
module.exports = require_sodium_native();
}
});
// ../../node_modules/compact-encoding/endian.js
var require_endian = __commonJS({
"../../node_modules/compact-encoding/endian.js"(exports) {
var LE = exports.LE = new Uint8Array(new Uint16Array([255]).buffer)[0] === 255;
exports.BE = !LE;
}
});
// ../../node_modules/compact-encoding/raw.js
var require_raw = __commonJS({
"../../node_modules/compact-encoding/raw.js"(exports, module) {
var b4a = require_b4a();
var { BE } = require_endian();
exports = module.exports = {
preencode(state, b) {
state.end += b.byteLength;
},
encode(state, b) {
state.buffer.set(b, state.start);
state.start += b.byteLength;
},
decode(state) {
const b = state.buffer.subarray(state.start, state.end);
state.start = state.end;
return b;
}
};
var buffer = exports.buffer = {
preencode(state, b) {
if (b) uint8array.preencode(state, b);
else state.end++;
},
encode(state, b) {
if (b) uint8array.encode(state, b);
else state.buffer[state.start++] = 0;
},
decode(state) {
const b = state.buffer.subarray(state.start);
if (b.byteLength === 0) return null;
state.start = state.end;
return b;
}
};
exports.binary = {
...buffer,
preencode(state, b) {
if (typeof b === "string") utf8.preencode(state, b);
else buffer.preencode(state, b);
},
encode(state, b) {
if (typeof b === "string") utf8.encode(state, b);
else buffer.encode(state, b);
}
};
exports.arraybuffer = {
preencode(state, b) {
state.end += b.byteLength;
},
encode(state, b) {
const view = new Uint8Array(b);
state.buffer.set(view, state.start);
state.start += b.byteLength;
},
decode(state) {
const b = new ArrayBuffer(state.end - state.start);
const view = new Uint8Array(b);
view.set(state.buffer.subarray(state.start));
state.start = state.end;
return b;
}
};
function typedarray(TypedArray, swap) {
const n = TypedArray.BYTES_PER_ELEMENT;
return {
preencode(state, b) {
state.end += b.byteLength;
},
encode(state, b) {
const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
if (BE && swap) swap(view);
state.buffer.set(view, state.start);
state.start += b.byteLength;
},
decode(state) {
let b = state.buffer.subarray(state.start);
if (b.byteOffset % n !== 0) b = new Uint8Array(b);
if (BE && swap) swap(b);
state.start = state.end;
return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n);
}
};
}
var uint8array = exports.uint8array = typedarray(Uint8Array);
exports.uint16array = typedarray(Uint16Array, b4a.swap16);
exports.uint32array = typedarray(Uint32Array, b4a.swap32);
exports.int8array = typedarray(Int8Array);
exports.int16array = typedarray(Int16Array, b4a.swap16);
exports.int32array = typedarray(Int32Array, b4a.swap32);
exports.biguint64array = typedarray(BigUint64Array, b4a.swap64);
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64);
exports.float32array = typedarray(Float32Array, b4a.swap32);
exports.float64array = typedarray(Float64Array, b4a.swap64);
function string(encoding) {
return {
preencode(state, s) {
state.end += b4a.byteLength(s, encoding);
},
encode(state, s) {
state.start += b4a.write(state.buffer, s, state.start, encoding);
},
decode(state) {
const s = b4a.toString(state.buffer, encoding, state.start);
state.start = state.end;
return s;
}
};
}
var utf8 = exports.string = exports.utf8 = string("utf-8");
exports.ascii = string("ascii");
exports.hex = string("hex");
exports.base64 = string("base64");
exports.ucs2 = exports.utf16le = string("utf16le");
exports.array = function array(enc) {
return {
preencode(state, list) {
for (const value of list) enc.preencode(state, value);
},
encode(state, list) {
for (const value of list) enc.encode(state, value);
},
decode(state) {
const arr = [];
while (state.start < state.end) arr.push(enc.decode(state));
return arr;
}
};
};
exports.json = {
preencode(state, v) {
utf8.preencode(state, JSON.stringify(v));
},
encode(state, v) {
utf8.encode(state, JSON.stringify(v));
},
decode(state) {
return JSON.parse(utf8.decode(state));
}
};
exports.ndjson = {
preencode(state, v) {
utf8.preencode(state, JSON.stringify(v) + "\n");
},
encode(state, v) {
utf8.encode(state, JSON.stringify(v) + "\n");
},
decode(state) {
return JSON.parse(utf8.decode(state));
}
};
}
});
// ../../node_modules/compact-encoding/lexint.js
var require_lexint = __commonJS({
"../../node_modules/compact-encoding/lexint.js"(exports, module) {
module.exports = {
preencode,
encode,
decode
};
function preencode(state, num) {
if (num < 251) {
state.end++;
} else if (num < 256) {
state.end += 2;
} else if (num < 65536) {
state.end += 3;
} else if (num < 16777216) {
state.end += 4;
} else if (num < 4294967296) {
state.end += 5;
} else {
state.end++;
const exp = Math.floor(Math.log(num) / Math.log(2)) - 32;
preencode(state, exp);
state.end += 6;
}
}
function encode(state, num) {
const max = 251;
const x = num - max;
if (num < max) {
state.buffer[state.start++] = num;
} else if (num < 256) {
state.buffer[state.start++] = max;
state.buffer[state.start++] = x;
} else if (num < 65536) {
state.buffer[state.start++] = max + 1;
state.buffer[state.start++] = x >> 8 & 255;
state.buffer[state.start++] = x & 255;
} else if (num < 16777216) {
state.buffer[state.start++] = max + 2;
state.buffer[state.start++] = x >> 16;
state.buffer[state.start++] = x >> 8 & 255;
state.buffer[state.start++] = x & 255;
} else if (num < 4294967296) {
state.buffer[state.start++] = max + 3;
state.buffer[state.start++] = x >> 24;
state.buffer[state.start++] = x >> 16 & 255;
state.buffer[state.start++] = x >> 8 & 255;
state.buffer[state.start++] = x & 255;
} else {
const exp = Math.floor(Math.log(x) / Math.log(2)) - 32;
state.buffer[state.start++] = 255;
encode(state, exp);
const rem = x / Math.pow(2, exp - 11);
for (let i = 5; i >= 0; i--) {
state.buffer[state.start++] = rem / Math.pow(2, 8 * i) & 255;
}
}
}
function decode(state) {
const max = 251;
if (state.end - state.start < 1) throw new Error("Out of bounds");
const flag = state.buffer[state.start++];
if (flag < max) return flag;
if (state.end - state.start < flag - max + 1) {
throw new Error("Out of bounds.");
}
if (flag < 252) {
return state.buffer[state.start++] + max;
}
if (flag < 253) {
return (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max;
}
if (flag < 254) {
return (state.buffer[state.start++] << 16) + (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max;
}
if (flag < 255) {
return state.buffer[state.start++] * 16777216 + (state.buffer[state.start++] << 16) + (state.buffer[state.start++] << 8) + state.buffer[state.start++] + max;
}
const exp = decode(state);
if (state.end - state.start < 6) throw new Error("Out of bounds");
let rem = 0;
for (let i = 5; i >= 0; i--) {
rem += state.buffer[state.start++] * Math.pow(2, 8 * i);
}
return rem * Math.pow(2, exp - 11) + max;
}
}
});
// ../../node_modules/compact-encoding/index.js
var require_compact_encoding = __commonJS({
"../../node_modules/compact-encoding/index.js"(exports) {
var b4a = require_b4a();
var { BE } = require_endian();
exports.state = function(start = 0, end = 0, buffer2 = null) {
return { start, end, buffer: buffer2 };
};
var raw = exports.raw = require_raw();
var uint = exports.uint = {
preencode(state, n) {
state.end += n <= 252 ? 1 : n <= 65535 ? 3 : n <= 4294967295 ? 5 : 9;
},
encode(state, n) {
if (n <= 252) uint8.encode(state, n);
else if (n <= 65535) {
state.buffer[state.start++] = 253;
uint16.encode(state, n);
} else if (n <= 4294967295) {
state.buffer[state.start++] = 254;
uint32.encode(state, n);
} else {
state.buffer[state.start++] = 255;
uint64.encode(state, n);
}
},
decode(state) {
const a = uint8.decode(state);
if (a <= 252) return a;
if (a === 253) return uint16.decode(state);
if (a === 254) return uint32.decode(state);
return uint64.decode(state);
}
};
var uint8 = exports.uint8 = {
preencode(state, n) {
state.end += 1;
},
encode(state, n) {
validateUint(n);
state.buffer[state.start++] = n;
},
decode(state) {
if (state.start >= state.end) throw new Error("Out of bounds");
return state.buffer[state.start++];
}
};
var uint16 = exports.uint16 = {
preencode(state, n) {
state.end += 2;
},
encode(state, n) {
validateUint(n);
state.buffer[state.start++] = n;
state.buffer[state.start++] = n >>> 8;
},
decode(state) {
if (state.end - state.start < 2) throw new Error("Out of bounds");
return state.buffer[state.start++] + state.buffer[state.start++] * 256;
}
};
var uint24 = exports.uint24 = {
preencode(state, n) {
state.end += 3;
},
encode(state, n) {
validateUint(n);
state.buffer[state.start++] = n;
state.buffer[state.start++] = n >>> 8;
state.buffer[state.start++] = n >>> 16;
},
decode(state) {
if (state.end - state.start < 3) throw new Error("Out of bounds");
return state.buffer[state.start++] + state.buffer[state.start++] * 256 + state.buffer[state.start++] * 65536;
}
};
var uint32 = exports.uint32 = {
preencode(state, n) {
state.end += 4;
},
encode(state, n) {
validateUint(n);
state.buffer[state.start++] = n;
state.buffer[state.start++] = n >>> 8;
state.buffer[state.start++] = n >>> 16;
state.buffer[state.start++] = n >>> 24;
},
decode(state) {
if (state.end - state.start < 4) throw new Error("Out of bounds");
return state.buffer[state.start++] + state.buffer[state.start++] * 256 + state.buffer[state.start++] * 65536 + state.buffer[state.start++] * 16777216;
}
};
var uint40 = exports.uint40 = {
preencode(state, n) {
state.end += 5;
},
encode(state, n) {
validateUint(n);
const r = Math.floor(n / 256);
uint8.encode(state, n);
uint32.encode(state, r);
},
decode(state) {
if (state.end - state.start < 5) throw new Error("Out of bounds");
return uint8.decode(state) + 256 * uint32.decode(state);
}
};
var uint48 = exports.uint48 = {
preencode(state, n) {
state.end += 6;
},
encode(state, n) {
validateUint(n);
const r = Math.floor(n / 65536);
uint16.encode(state, n);
uint32.encode(state, r);
},
decode(state) {
if (state.end - state.start < 6) throw new Error("Out of bounds");
return uint16.decode(state) + 65536 * uint32.decode(state);
}
};
var uint56 = exports.uint56 = {
preencode(state, n) {
state.end += 7;
},
encode(state, n) {
validateUint(n);
const r = Math.floor(n / 16777216);
uint24.encode(state, n);
uint32.encode(state, r);
},
decode(state) {
if (state.end - state.start < 7) throw new Error("Out of bounds");
return uint24.decode(state) + 16777216 * uint32.decode(state);
}
};
var uint64 = exports.uint64 = {
preencode(state, n) {
state.end += 8;
},
encode(state, n) {
validateUint(n);
const r = Math.floor(n / 4294967296);
uint32.encode(state, n);
uint32.encode(state, r);
},
decode(state) {
if (state.end - state.start < 8) throw new Error("Out of bounds");
return uint32.decode(state) + 4294967296 * uint32.decode(state);
}
};
var int = exports.int = zigZagInt(uint);
exports.int8 = zigZagInt(uint8);
exports.int16 = zigZagInt(uint16);
exports.int24 = zigZagInt(uint24);
exports.int32 = zigZagInt(uint32);
exports.int40 = zigZagInt(uint40);
exports.int48 = zigZagInt(uint48);
exports.int56 = zigZagInt(uint56);
exports.int64 = zigZagInt(uint64);
var biguint64 = exports.biguint64 = {
preencode(state, n) {
state.end += 8;
},
encode(state, n) {
const view = new DataView(
state.buffer.buffer,
state.start + state.buffer.byteOffset,
8
);
view.setBigUint64(0, n, true);
state.start += 8;
},
decode(state) {
if (state.end - state.start < 8) throw new Error("Out of bounds");
const view = new DataView(
state.buffer.buffer,
state.start + state.buffer.byteOffset,
8
);
const n = view.getBigUint64(0, true);
state.start += 8;
return n;
}
};
exports.bigint64 = zigZagBigInt(biguint64);
var biguint = exports.biguint = {
preencode(state, n) {
let len = 0;
for (let m = n; m; m = m >> 64n) len++;
uint.preencode(state, len);
state.end += 8 * len;
},
encode(state, n) {
let len = 0;
for (let m = n; m; m = m >> 64n) len++;
uint.encode(state, len);
const view = new DataView(
state.buffer.buffer,
state.start + state.buffer.byteOffset,
8 * len
);
for (let m = n, i = 0; m; m = m >> 64n, i += 8) {
view.setBigUint64(i, BigInt.asUintN(64, m), true);
}
state.start += 8 * len;
},
decode(state) {
const len = uint.decode(state);
if (state.end - state.start < 8 * len) throw new Error("Out of bounds");
const view = new DataView(
state.buffer.buffer,
state.start + state.buffer.byteOffset,
8 * len
);
let n = 0n;
for (let i = len - 1; i >= 0; i--)
n = (n << 64n) + view.getBigUint64(i * 8, true);
state.start += 8 * len;
return n;
}
};
exports.bigint = zigZagBigInt(biguint);
exports.lexint = require_lexint();
exports.float32 = {
preencode(state, n) {
state.end += 4;
},
encode(state, n) {
const view = new DataView(
state.buffer.buffer,
state.start + state.buffer.byteOffset,
4
);
view.setFloat32(0, n, true);
state.start += 4;
},
decode(state) {
if (state.end - state.start < 4) throw new Error("Out of bounds");
const view = new DataView(
state.buffer.buffer,
state.start + state.buffer.byteOffset,
4
);
const float = view.getFloat32(0, true);
state.start += 4;
return float;
}
};
exports.float64 = {
preencode(state, n) {
state.end += 8;
},
encode(state, n) {
const view = new DataView(
state.buffer.buffer,
state.start + state.buffer.byteOffset,
8
);
view.setFloat64(0, n, true);
state.start += 8;
},
decode(state) {
if (state.end - state.start < 8) throw new Error("Out of bounds");
const view = new DataView(
state.buffer.buffer,
state.start + state.buffer.byteOffset,
8
);
const float = view.getFloat64(0, true);
state.start += 8;
return float;
}
};
var buffer = exports.buffer = {
preencode(state, b) {
if (b) uint8array.preencode(state, b);
else state.end++;
},
encode(state, b) {
if (b) uint8array.encode(state, b);
else state.buffer[state.start++] = 0;
},
decode(state) {
const len = uint.decode(state);
if (len === 0) return null;
if (state.end - state.start < len) throw new Error("Out of bounds");
return state.buffer.subarray(state.start, state.start += len);
}
};
exports.binary = {
...buffer,
preencode(state, b) {
if (typeof b === "string") utf8.preencode(state, b);
else buffer.preencode(state, b);
},
encode(state, b) {
if (typeof b === "string") utf8.encode(state, b);
else buffer.encode(state, b);
}
};
exports.arraybuffer = {
preencode(state, b) {
uint.preencode(state, b.byteLength);
state.end += b.byteLength;
},
encode(state, b) {
uint.encode(state, b.byteLength);
const view = new Uint8Array(b);
state.buffer.set(view, state.start);
state.start += b.byteLength;
},
decode(state) {
const len = uint.decode(state);
const b = new ArrayBuffer(len);
const view = new Uint8Array(b);
view.set(state.buffer.subarray(state.start, state.start += len));
return b;
}
};
function typedarray(TypedArray, swap) {
const n = TypedArray.BYTES_PER_ELEMENT;
return {
preencode(state, b) {
uint.preencode(state, b.length);
state.end += b.byteLength;
},
encode(state, b) {
uint.encode(state, b.length);
const view = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
if (BE && swap) swap(view);
state.buffer.set(view, state.start);
state.start += b.byteLength;
},
decode(state) {
const len = uint.decode(state);
let b = state.buffer.subarray(state.start, state.start += len * n);
if (b.byteLength !== len * n) throw new Error("Out of bounds");
if (b.byteOffset % n !== 0) b = new Uint8Array(b);
if (BE && swap) swap(b);
return new TypedArray(b.buffer, b.byteOffset, b.byteLength / n);
}
};
}
var uint8array = exports.uint8array = typedarray(Uint8Array);
exports.uint16array = typedarray(Uint16Array, b4a.swap16);
exports.uint32array = typedarray(Uint32Array, b4a.swap32);
exports.int8array = typedarray(Int8Array);
exports.int16array = typedarray(Int16Array, b4a.swap16);
exports.int32array = typedarray(Int32Array, b4a.swap32);
exports.biguint64array = typedarray(BigUint64Array, b4a.swap64);
exports.bigint64array = typedarray(BigInt64Array, b4a.swap64);
exports.float32array = typedarray(Float32Array, b4a.swap32);
exports.float64array = typedarray(Float64Array, b4a.swap64);
function string(encoding) {
return {
preencode(state, s) {
const len = b4a.byteLength(s, encoding);
uint.preencode(state, len);
state.end += len;
},
encode(state, s) {
const len = b4a.byteLength(s, encoding);
uint.encode(state, len);
b4a.write(state.buffer, s, state.start, encoding);
state.start += len;
},
decode(state) {
const len = uint.decode(state);
if (state.end - state.start < len) throw new Error("Out of bounds");
return b4a.toString(
state.buffer,
encoding,
state.start,
state.start += len
);
},
fixed(n) {
return {
preencode(state) {
state.end += n;
},
encode(state, s) {
b4a.write(state.buffer, s, state.start, n, encoding);
state.start += n;
},
decode(state) {
if (state.end - state.start < n) throw new Error("Out of bounds");
return b4a.toString(
state.buffer,
encoding,
state.start,
state.start += n
);
}
};
}
};
}
var utf8 = exports.string = exports.utf8 = string("utf-8");
exports.ascii = string("ascii");
exports.hex = string("hex");
exports.base64 = string("base64");
exports.ucs2 = exports.utf16le = string("utf16le");
exports.bool = {
preencode(state, b) {
state.end++;
},
encode(state, b) {
state.buffer[state.start++] = b ? 1 : 0;
},
decode(state) {
if (state.start >= state.end) throw Error("Out of bounds");
return state.buffer[state.start++] === 1;
}
};
var fixed = exports.fixed = function fixed2(n) {
return {
preencode(state, s) {
if (s.byteLength !== n) throw new Error("Incorrect buffer size");
state.end += n;
},
encode(state, s) {
state.buffer.set(s, state.start);
state.start += n;
},
decode(state) {
if (state.end - state.start < n) throw new Error("Out of bounds");
return state.buffer.subarray(state.start, state.start += n);
}
};
};
exports.fixed32 = fixed(32);
exports.fixed64 = fixed(64);
exports.array = function array(enc) {
return {
preencode(state, list) {
uint.preencode(state, list.length);
for (let i = 0; i < list.length; i++) enc.preencode(state, list[i]);
},
encode(state, list) {
uint.encode(state, list.length);
for (let i = 0; i < list.length; i++) enc.encode(state, list[i]);
},
decode(state) {
const len = uint.decode(state);
if (len > 1048576) throw new Error("Array is too big");
const arr = new Array(len);
for (let i = 0; i < len; i++) arr[i] = enc.decode(state);
return arr;
}
};
};
exports.frame = function frame(enc) {
const dummy = exports.state();
return {
preencode(state, m) {
const end = state.end;
enc.preencode(state, m);
uint.preencode(state, state.end - end);
},
encode(state, m) {
dummy.end = 0;
enc.preencode(dummy, m);
uint.encode(state, dummy.end);
enc.encode(state, m);
},
decode(state) {
const end = state.end;
const len = uint.decode(state);
state.end = state.start + len;
const m = enc.decode(state);
state.start = state.end;
state.end = end;
return m;
}
};
};
exports.date = {
preencode(state, d) {
int.preencode(state, d.getTime());
},
encode(state, d) {
int.encode(state, d.getTime());
},
decode(state, d) {
return new Date(int.decode(state));
}
};
exports.json = {
preencode(state, v) {
utf8.preencode(state, JSON.stringify(v));
},
encode(state, v) {
utf8.encode(state, JSON.stringify(v));
},
decode(state) {
return JSON.parse(utf8.decode(state));
}
};
exports.ndjson = {
preencode(state, v) {
utf8.preencode(state, JSON.stringify(v) + "\n");
},
encode(state, v) {
utf8.encode(state, JSON.stringify(v) + "\n");
},
decode(state) {
return JSON.parse(utf8.decode(state));
}
};
exports.none = {
preencode(state, n) {
},
encode(state, n) {
},
decode(state) {
return null;
}
};
var anyArray = {
preencode(state, arr) {
uint.preencode(state, arr.length);
for (let i = 0; i < arr.length; i++) {
any.preencode(state, arr[i]);
}
},
encode(state, arr) {
uint.encode(state, arr.length);
for (let i = 0; i < arr.length; i++) {
any.encode(state, arr[i]);
}
},
decode(state) {
const arr = [];
let len = uint.decode(state);
while (len-- > 0) {
arr.push(any.decode(state));
}
return arr;
}
};
var anyObject = {
preencode(state, o) {
const keys = Object.keys(o);
uint.preencode(state, keys.length);
for (const key of keys) {
utf8.preencode(state, key);
any.preencode(state, o[key]);
}
},
encode(state, o) {
const keys = Object.keys(o);
uint.encode(state, keys.length);
for (const key of keys) {
utf8.encode(state, key);
any.encode(state, o[key]);
}
},
decode(state) {
let len = uint.decode(state);
const o = {};
while (len-- > 0) {
const key = utf8.decode(state);
o[key] = any.decode(state);
}
return o;
}
};
var anyTypes = [
exports.none,
exports.bool,
exports.string,
exports.buffer,
exports.uint,
exports.int,
exports.float64,
anyArray,
anyObject,
exports.date
];
var any = exports.any = {
preencode(state, o) {
const t = getType(o);
uint.preencode(state, t);
anyTypes[t].preencode(state, o);
},
encode(state, o) {
const t = getType(o);
uint.encode(state, t);
anyTypes[t].encode(state, o);
},
decode(state) {
const t = uint.decode(state);
if (t >= anyTypes.length) throw new Error("Unknown type: " + t);
return anyTypes[t].decode(state);
}
};
var port = exports.port = uint16;
var address = (host, family) => {
return {
preencode(state, m) {
host.preencode(state, m.host);
port.preencode(state, m.port);
},
encode(state, m) {
host.encode(state, m.host);
port.encode(state, m.port);
},
decode(state) {
return {
host: host.decode(state),
family,
port: port.decode(state)
};
}
};
};
var ipv4 = exports.ipv4 = {
preencode(state) {
state.end += 4;
},
encode(state, string2) {
const start = state.start;
const end = start + 4;
let i = 0;
while (i < string2.length) {
let n = 0;
let c;
while (i < string2.length && (c = string2.charCodeAt(i++)) !== /* . */
46) {
n = n * 10 + (c - /* 0 */
48);
}
state.buffer[state.start++] = n;
}
state.start = end;
},
decode(state) {
if (state.end - state.start < 4) throw new Error("Out of bounds");
return state.buffer[state.start++] + "." + state.buffer[state.start++] + "." + state.buffer[state.start++] + "." + state.buffer[state.start++];
}
};
exports.ipv4Address = address(ipv4, 4);
var ipv6 = exports.ipv6 = {
preencode(state) {
state.end += 16;
},
encode(state, string2) {
const start = state.start;
const end = start + 16;
let i = 0;
let split = null;
while (i < string2.length) {
let n = 0;
let c;
while (i < string2.length && (c = string2.charCodeAt(i++)) !== /* : */
58) {
if (c >= 48 && c <= 57) n = n * 16 + (c - /* 0 */
48);
else if (c >= 65 && c <= 70) n = n * 16 + (c - /* A */
65 + 10);
else if (c >= 97 && c <= 102) n = n * 16 + (c - /* a */
97 + 10);
}
state.buffer[state.start++] = n >>> 8;
state.buffer[state.start++] = n;
if (i < string2.length && string2.charCodeAt(i) === /* : */
58) {
i++;
split = state.start;
}
}
if (split !== null) {
const offset = end - state.start;
state.buffer.copyWithin(split + offset, split).fill(0, split, split + offset);
}
state.start = end;
},
decode(state) {
if (state.end - state.start < 16) throw new Error("Out of bounds");
return (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16);
}
};
exports.ipv6Address = address(ipv6, 6);
var ip = exports.ip = {
preencode(state, string2) {
const family = string2.includes(":") ? 6 : 4;
uint8.preencode(state, family);
if (family === 4) ipv4.preencode(state);
else ipv6.preencode(state);
},
encode(state, string2) {
const family = string2.includes(":") ? 6 : 4;
uint8.encode(state, family);
if (family === 4) ipv4.encode(state, string2);
else ipv6.encode(state, string2);
},
decode(state) {
const family = uint8.decode(state);
if (family === 4) return ipv4.decode(state);
else return ipv6.decode(state);
}
};
exports.ipAddress = {
preencode(state, m) {
ip.preencode(state, m.host);
port.preencode(state, m.port);
},
encode(state, m) {
ip.encode(state, m.host);
port.encode(state, m.port);
},
decode(state) {
const family = uint8.decode(state);
return {
host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
family,
port: port.decode(state)
};
}
};
var record = exports.record = function(keyEncoding, valueEncoding) {
return {
preencode(state, v) {
const keys = Object.keys(v);
uint.preencode(state, keys.length);
for (const k of keys) {
keyEncoding.preencode(state, k);
valueEncoding.preencode(state, v[k]);
}
},
encode(state, v) {
const keys = Object.keys(v);
uint.encode(state, keys.length);
for (const k of keys) {
keyEncoding.encode(state, k);
valueEncoding.encode(state, v[k]);
}
},
decode(state) {
const out = /* @__PURE__ */ Object.create(null);
const keys = uint.decode(state);
for (let i = 0; i < keys; i++) {
out[keyEncoding.decode(state)] = valueEncoding.decode(state);
}
return out;
}
};
};
exports.stringRecord = record(utf8, utf8);
function getType(o) {
if (o === null || o === void 0) return 0;
if (typeof o === "boolean") return 1;
if (typeof o === "string") return 2;
if (b4a.isBuffer(o)) return 3;
if (typeof o === "number") {
if (Number.isInteger(o)) return o >= 0 ? 4 : 5;
return 6;
}
if (Array.isArray(o)) return 7;
if (o instanceof Date) return 9;
if (typeof o === "object") return 8;
throw new Error("Unsupported type for " + o);
}
exports.from = function from(enc) {
if (typeof enc === "string") return fromNamed(enc);
if (enc.preencode) return enc;
if (enc.encodingLength) return fromAbstractEncoder(enc);
return fromCodec(enc);
};
function fromNamed(enc) {
switch (enc) {
case "ascii":
return raw.ascii;
case "utf-8":
case "utf8":
return raw.utf8;
case "hex":
return raw.hex;
case "base64":
return raw.base64;
case "utf16-le":
case "utf16le":
case "ucs-2":
case "ucs2":
return raw.ucs2;
case "ndjson":
return raw.ndjson;
case "json":
return raw.json;
case "binary":
default:
return raw.binary;
}
}
function fromCodec(enc) {
let tmpM = null;
let tmpBuf = null;
return {
preencode(state, m) {
tmpM = m;
tmpBuf = enc.encode(m);
state.end += tmpBuf.byteLength;
},
encode(state, m) {
raw.encode(state, m === tmpM ? tmpBuf : enc.encode(m));
tmpM = tmpBuf = null;
},
decode(state) {
return enc.decode(raw.decode(state));
}
};
}
function fromAbstractEncoder(enc) {
return {
preencode(state, m) {
state.end += enc.encodingLength(m);
},
encode(state, m) {
enc.encode(m, state.buffer, state.start);
state.start += enc.encode.bytes;
},
decode(state) {
const m = enc.decode(state.buffer, state.start, state.end);
state.start += enc.decode.bytes;
return m;
}
};
}
exports.encode = function encode(enc, m) {
const state = exports.state();
enc.preencode(state, m);
state.buffer = b4a.allocUnsafe(state.end);
enc.encode(state, m);
return state.buffer;
};
exports.decode = function decode(enc, buffer2) {
return enc.decode(exports.state(0, buffer2.byteLength, buffer2));
};
function zigZagInt(enc) {
return {
preencode(state, n) {
enc.preencode(state, zigZagEncodeInt(n));
},
encode(state, n) {
enc.encode(state, zigZagEncodeInt(n));
},
decode(state) {
return zigZagDecodeInt(enc.decode(state));
}
};
}
function zigZagDecodeInt(n) {
return n === 0 ? n : (n & 1) === 0 ? n / 2 : -(n + 1) / 2;
}
function zigZagEncodeInt(n) {
return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n;
}
function zigZagBigInt(enc) {
return {
preencode(state, n) {
enc.preencode(state, zigZagEncodeBigInt(n));
},
encode(state, n) {
enc.encode(state, zigZagEncodeBigInt(n));
},
decode(state) {
return zigZagDecodeBigInt(enc.decode(state));
}
};
}
function zigZagDecodeBigInt(n) {
return n === 0n ? n : (n & 1n) === 0n ? n / 2n : -(n + 1n) / 2n;
}
function zigZagEncodeBigInt(n) {
return n < 0n ? 2n * -n - 1n : n === 0n ? 0n : 2n * n;
}
function validateUint(n) {
if (n >= 0 === false)
throw new Error("uint must be positive");
}
}
});
// ../../node_modules/nat-sampler/index.js
var require_nat_sampler = __commonJS({
"../../node_modules/nat-sampler/index.js"(exports, module) {
module.exports = class NatSampler {
constructor() {
this.host = null;
this.port = 0;
this.size = 0;
this._a = null;
this._b = null;
this._threshold = 0;
this._top = 0;
this._samples = [];
}
add(host, port) {
const a = this._bump(host, port, 2);
const b = this._bump(host, 0, 1);
if (this._samples.length < 32) {
this.size++;
this._threshold = this.size - (this.size < 4 ? 0 : this.size < 8 ? 1 : this.size < 12 ? 2 : 3);
this._samples.push(a, b);
this._top += 2;
} else {
if (this._top === 32) this._top = 0;
const oa = this._samples[this._top];
this._samples[this._top++] = a;
oa.hits--;
const ob = this._samples[this._top];
this._samples[this._top++] = b;
ob.hits--;
}
if (this._a === null || this._a.hits < a.hits) this._a = a;
if (this._b === null || this._b.hits < b.hits) this._b = b;
if (this._a.hits >= this._threshold) {
this.host = this._a.host;
this.port = this._a.port;
} else if (this._b.hits >= this._threshold) {
this.host = this._b.host;
this.port = 0;
} else {
this.host = null;
this.port = 0;
}
return a.hits;
}
_bump(host, port, inc) {
for (let i = 0; i < 4; i++) {
const j = this._top - inc - 2 * i & 31;
if (j >= this._samples.length) return { host, port, hits: 1 };
const s = this._samples[j];
if (s.port === port && s.host === host) {
s.hits++;
return s;
}
}
return { host, port, hits: 1 };
}
};
}
});
// ../../node_modules/dht-rpc/lib/health.js
var require_health = __commonJS({
"../../node_modules/dht-rpc/lib/health.js"(exports, module) {
var MAX_HEALTH_WINDOW = 4;
var IDLE_THRESHOLD = 4;
var DEGRADED_TIMEOUT_RATE_THRESHOLD = 0.5;
module.exports = class NetworkHealth {
constructor(dht) {
this._dht = dht;
this._window = [];
this._head = -1;
this._degradedTicks = 0;
this._healthyTicks = 0;
this.online = true;
this.degraded = false;
}
get oldest() {
return this._window[this._tail];
}
get previous() {
return this._window[(this._head - 1 + MAX_HEALTH_WINDOW) % MAX_HEALTH_WINDOW];
}
get newest() {
return this._window[this._head];
}
get responses() {
if (!this.newest || !this.previous) return 0;
return this.newest.responses - this.previous.responses;
}
get timeouts() {
if (!this.newest || !this.previous) return 0;
return this.newest.timeouts - this.previous.timeouts;
}
get timeoutsRate() {
if (this.timeouts === 0) return 0;
return this.timeouts / (this.responses + this.timeouts);
}
get cold() {
return this._window.length < MAX_HEALTH_WINDOW;
}
get idle() {
return this.responses + this.timeouts < IDLE_THRESHOLD;
}
get allDegraded() {
return this._degradedTicks === MAX_HEALTH_WINDOW;
}
get allHealthy() {
return this._healthyTicks === MAX_HEALTH_WINDOW;
}
get stats() {
return {
online: this.online,
degraded: this.degraded,
cold: this.cold,
idle: this.idle,
responses: this.responses,
timeouts: this.timeouts,
timeoutsRate: this.timeoutsRate
};
}
get _tail() {
return (this._head + 1) % MAX_HEALTH_WINDOW;
}
reset() {
this._window = [];
this._head = -1;
this._degradedTicks = 0;
this._healthyTicks = 0;
this.online = true;
this.degraded = false;
this._dht._online();
}
update() {
if (this.oldest?.degraded) this._degradedTicks--;
else if (this.oldest?.degraded === false) this._healthyTicks--;
this._head = this._tail;
this._window[this._head] = {
responses: this._dht.stats.requests.responses,
timeouts: this._dht.stats.requests.timeouts
};
if (this.cold || this.idle) return;
this.newest.degraded = this.timeoutsRate > DEGRADED_TIMEOUT_RATE_THRESHOLD;
if (this.newest.degraded) this._degradedTicks++;
else this._healthyTicks++;
this.online = this.responses > 0;
if (this.online && this.allDegraded) this.degraded = true;
if (!this.online || this.allHealthy) this.degraded = false;
if (this.online && !this.degraded) this._dht._online();
else if (this.degraded) this._dht._degraded();
else this._dht._offline();
}
};
}
});
// ../../node_modules/xache/index.js
var require_xache = __commonJS({
"../../node_modules/xache/index.js"(exports, module) {
module.exports = class MaxCache {
constructor({ maxSize, maxAge, createMap, ongc }) {
this.maxSize = maxSize;
this.maxAge = maxAge;
this.ongc = ongc || null;
this._createMap = createMap || defaultCreateMap;
this._latest = this._createMap();
this._oldest = this._createMap();
this._retained = this._createMap();
this._gced = false;
this._interval = null;
if (this.maxAge > 0 && this.maxAge < Infinity) {
const tick = Math.ceil(2 / 3 * this.maxAge);
this._interval = setInterval(this._gcAuto.bind(this), tick);
if (this._interval.unref) this._interval.unref();
}
}
*[Symbol.iterator]() {
for (const it of [this._latest, this._oldest, this._retained]) {
yield* it;
}
}
*keys() {
for (const it of [this._latest, this._oldest, this._retained]) {
yield* it.keys();
}
}
*values() {
for (const it of [this._latest, this._oldest, this._retained]) {
yield* it.values();
}
}
destroy() {
this.clear();
clearInterval(this._interval);
this._interval = null;
}
clear() {
this._gced = true;
this._latest.clear();
this._oldest.clear();
this._retained.clear();
}
set(k, v) {
if (this._retained.has(k)) return this;
this._latest.set(k, v);
this._oldest.delete(k) || this._retained.delete(k);
if (this._latest.size >= this.maxSize) this._gc();
return this;
}
retain(k, v) {
this._retained.set(k, v);
this._latest.delete(k) || this._oldest.delete(k);
return this;
}
delete(k) {
return this._latest.delete(k) || this._oldest.delete(k) || this._retained.delete(k);
}
has(k) {
return this._latest.has(k) || this._oldest.has(k) || this._retained.has(k);
}
get(k) {
if (this._latest.has(k)) {
return this._latest.get(k);
}
if (this._oldest.has(k)) {
const v = this._oldest.get(k);
this._latest.set(k, v);
this._oldest.delete(k);
return v;
}
if (this._retained.has(k)) {
return this._retained.get(k);
}
return null;
}
_gcAuto() {
if (!this._gced) this._gc();
this._gced = false;
}
_gc() {
this._gced = true;
if (this.ongc !== null && this._oldest.size > 0) this.ongc(this._oldest);
this._oldest = this._latest;
this._latest = this._createMap();
}
};
function defaultCreateMap() {
return /* @__PURE__ */ new Map();
}
}
});
// ../../node_modules/adaptive-timeout/index.js
var require_adaptive_timeout = __commonJS({
"../../node_modules/adaptive-timeout/index.js"(exports, module) {
var Cache = require_xache();
module.exports = class AdaptiveTimeout {
constructor(opts = {}) {
this._cache = new Cache({
maxSize: opts.maxSize || 65536,
maxAge: opts.maxAge || 10 * 60 * 1e3
// 10 minutes
});
this._fallback = opts.fallback || AdaptiveTimeout.TimeoutExponential;
this._min = opts.min ?? 300;
this._max = opts.max || 4e3;
this._jitter = opts.jitter ?? 256;
}
// Default - aggressive ramp
static TimeoutAggressive = [500, 750, 1e3, 1500, 2e3];
// Linear - steady increase
static TimeoutLinear = [500, 1e3, 1500, 2e3, 2500];
// Exponential - slow start, rapid backoff
static TimeoutExponential = [250, 500, 1e3, 2e3, 4e3];
// Gentle - conservative, patient
static TimeoutGentle = [1e3, 1250, 1500, 1750, 2e3];
// Fast - rapid fire retries
static TimeoutFast = [200, 400, 600, 800, 1e3];
// U-shape - long, short, long
static TimeoutUShape = [1500, 750, 500, 750, 1500];
// Inverse U - short, long, short
static TimeoutInverseU = [500, 1e3, 1500, 1e3, 500];
// Sawtooth - alternating fast/slow
static TimeoutSawtooth = [500, 1500, 500, 1500, 500];
// Plateau - quick ramp then steady
static TimeoutPlateau = [500, 1e3, 2e3, 2e3, 2e3];
// Logarithmic - diminishing increases
static TimeoutLogarithmic = [500, 1e3, 1300, 1500, 1600];
getValue(key) {
return this._cache.get(key);
}
put(key, value) {
let p = this._cache.get(key);
if (!p) {
p = { avg: value, variance: value >> 1 };
} else {
p.variance += Math.abs(p.avg - value) - p.variance >> 2;
p.avg += value - p.avg >> 3;
}
this._cache.set(key, p);
return p;
}
get(key, attempt = 1) {
const p = this._cache.get(key);
const jitter = Math.random() * this._jitter | 0;
if (p) {
const base = p.avg + (p.variance << 1);
const backoff = base * attempt;
return Math.min(Math.max(backoff + jitter, this._min), this._max);
} else {
const base = this._fallback[Math.min(attempt - 1, this._fallback.length - 1)];
return base + jitter;
}
}
has(key) {
return this._cache.has(key);
}
delete(key) {
return this._cache.delete(key);
}
clear() {
this._cache.clear();
}
};
}
});
// ../../node_modules/compact-encoding-net/index.js
var require_compact_encoding_net = __commonJS({
"../../node_modules/compact-encoding-net/index.js"(exports, module) {
var c = require_compact_encoding();
var port = c.uint16;
var address = (host, family) => {
return {
preencode(state, m) {
host.preencode(state, m.host);
port.preencode(state, m.port);
},
encode(state, m) {
host.encode(state, m.host);
port.encode(state, m.port);
},
decode(state) {
return {
host: host.decode(state),
family,
port: port.decode(state)
};
}
};
};
var ipv4 = {
preencode(state) {
state.end += 4;
},
encode(state, string) {
const start = state.start;
const end = start + 4;
let i = 0;
while (i < string.length) {
let n = 0;
let c2;
while (i < string.length && (c2 = string.charCodeAt(i++)) !== /* . */
46) {
n = n * 10 + (c2 - /* 0 */
48);
}
state.buffer[state.start++] = n;
}
state.start = end;
},
decode(state) {
if (state.end - state.start < 4) throw new Error("Out of bounds");
return state.buffer[state.start++] + "." + state.buffer[state.start++] + "." + state.buffer[state.start++] + "." + state.buffer[state.start++];
}
};
var ipv4Address = address(ipv4, 4);
var ipv6 = {
preencode(state) {
state.end += 16;
},
encode(state, string) {
const start = state.start;
const end = start + 16;
let i = 0;
let split = null;
while (i < string.length) {
let n = 0;
let c2;
while (i < string.length && (c2 = string.charCodeAt(i++)) !== /* : */
58) {
if (c2 >= 48 && c2 <= 57) n = n * 16 + (c2 - /* 0 */
48);
else if (c2 >= 65 && c2 <= 70) n = n * 16 + (c2 - /* A */
65 + 10);
else if (c2 >= 97 && c2 <= 102) n = n * 16 + (c2 - /* a */
97 + 10);
}
state.buffer[state.start++] = n >>> 8;
state.buffer[state.start++] = n;
if (i < string.length && string.charCodeAt(i) === /* : */
58) {
i++;
split = state.start;
}
}
if (split !== null) {
const offset = end - state.start;
state.buffer.copyWithin(split + offset, split).fill(0, split, split + offset);
}
state.start = end;
},
decode(state) {
if (state.end - state.start < 16) throw new Error("Out of bounds");
return (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16) + ":" + (state.buffer[state.start++] * 256 + state.buffer[state.start++]).toString(16);
}
};
var ipv6Address = address(ipv6, 6);
var ip = {
preencode(state, string) {
const family = string.includes(":") ? 6 : 4;
c.uint8.preencode(state, family);
if (family === 4) ipv4.preencode(state);
else ipv6.preencode(state);
},
encode(state, string) {
const family = string.includes(":") ? 6 : 4;
c.uint8.encode(state, family);
if (family === 4) ipv4.encode(state, string);
else ipv6.encode(state, string);
},
decode(state) {
const family = c.uint8.decode(state);
if (family === 4) return ipv4.decode(state);
else return ipv6.decode(state);
}
};
var ipAddress = {
preencode(state, m) {
ip.preencode(state, m.host);
port.preencode(state, m.port);
},
encode(state, m) {
ip.encode(state, m.host);
port.encode(state, m.port);
},
decode(state) {
const family = c.uint8.decode(state);
return {
host: family === 4 ? ipv4.decode(state) : ipv6.decode(state),
family,
port: port.decode(state)
};
}
};
module.exports = {
port,
ipv4,
ipv4Address,
ipv6,
ipv6Address,
ip,
ipAddress
};
}
});
// ../../node_modules/dht-rpc/lib/peer.js
var require_peer = __commonJS({
"../../node_modules/dht-rpc/lib/peer.js"(exports, module) {
var sodium = require_sodium_universal();
var c = require_compact_encoding();
var net = require_compact_encoding_net();
var b4a = require_b4a();
var ipv4 = {
...net.ipv4Address,
decode(state) {
const ip = net.ipv4Address.decode(state);
return {
id: null,
// populated by the callee
host: ip.host,
port: ip.port
};
}
};
module.exports = { id, ipv4, ipv4Array: c.array(ipv4) };
function id(host, port, out = b4a.allocUnsafeSlow(32)) {
const addr = out.subarray(0, 6);
ipv4.encode({ start: 0, end: 6, buffer: addr }, { host, port });
sodium.crypto_generichash(out, addr);
return out;
}
}
});
// ../../node_modules/dht-rpc/lib/errors.js
var require_errors8 = __commonJS({
"../../node_modules/dht-rpc/lib/errors.js"(exports, module) {
module.exports = class DHTError extends Error {
constructor(msg, code, fn = DHTError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "DHTError";
}
static UNKNOWN_COMMAND = 1;
static INVALID_TOKEN = 2;
static REQUEST_TIMEOUT(msg = "Request timed out") {
return new DHTError(msg, "REQUEST_TIMEOUT", DHTError.REQUEST_TIMEOUT);
}
static REQUEST_DESTROYED(msg = "Request destroyed") {
return new DHTError(msg, "REQUEST_DESTROYED", DHTError.REQUEST_DESTROYED);
}
static IO_SUSPENDED(msg = "I/O suspended") {
return new DHTError(msg, "IO_SUSPENDED", DHTError.IO_SUSPENDED);
}
};
}
});
// ../../node_modules/dht-rpc/lib/io.js
var require_io = __commonJS({
"../../node_modules/dht-rpc/lib/io.js"(exports, module) {
var FIFO = require_fast_fifo();
var sodium = require_sodium_universal();
var c = require_compact_encoding();
var b4a = require_b4a();
var AdaptiveTimeout = require_adaptive_timeout();
var peer = require_peer();
var { INVALID_TOKEN, REQUEST_TIMEOUT, REQUEST_DESTROYED, IO_SUSPENDED } = require_errors8();
var VERSION = 3;
var RESPONSE_ID = 1 << 4 | VERSION;
var REQUEST_ID = 0 << 4 | VERSION;
var EMPTY_ARRAY = [];
var MAX_WINDOW = 80;
module.exports = class IO {
constructor(table, udx, {
maxWindow = MAX_WINDOW,
port = 0,
host = "0.0.0.0",
anyPort = true,
firewalled = true,
onrequest,
onresponse = noop,
ontimeout = noop,
adaptiveTimeout
} = {}) {
this.table = table;
this.udx = udx;
this.inflight = [];
this.clientSocket = null;
this.serverSocket = null;
this.firewalled = firewalled !== false;
this.ephemeral = true;
this.congestion = new CongestionWindow(maxWindow);
this.networkInterfaces = udx.watchNetworkInterfaces();
this.suspended = false;
this.stats = {
requests: {
active: 0,
total: 0,
responses: 0,
timeouts: 0,
retries: 0
},
commands: [
{ tx: 0, rx: 0 },
// tx = transmitted, rx = received
{ tx: 0, rx: 0 },
{ tx: 0, rx: 0 },
{ tx: 0, rx: 0 }
]
};
this.onrequest = onrequest;
this.onresponse = onresponse;
this.ontimeout = ontimeout;
this._pending = new FIFO();
this._rotateSecrets = 10;
this._tid = Math.random() * 65536 | 0;
this._secrets = null;
this._drainInterval = null;
this._destroying = null;
this._binding = null;
this.portRange = port.length ? port : port === 0 ? [0, 0] : [port, port + 5];
this._host = host;
this._anyPort = anyPort !== false;
this._boundServerPort = 0;
this._boundClientPort = 0;
this._adt = adaptiveTimeout ? new AdaptiveTimeout(adaptiveTimeout) : null;
}
static DEFAULT_MAX_WINDOW = MAX_WINDOW;
onmessage(socket, buffer, { host, port }) {
if (buffer.byteLength < 2 || !(port > 0 && port < 65536) || this.suspended === true) return;
const from = { id: null, host, port };
const state = { start: 1, end: buffer.byteLength, buffer };
const expectedSocket = this.firewalled ? this.clientSocket : this.serverSocket;
const external = socket !== expectedSocket;
if (buffer[0] === REQUEST_ID) {
const req = Request.decode(this, socket, from, state);
if (req === null) return;
if (req.token !== null && !b4a.equals(req.token, this.token(req.from, 1)) && !b4a.equals(req.token, this.token(req.from, 0))) {
req.error(INVALID_TOKEN, { token: true });
return;
}
this.onrequest(req, external);
return;
}
if (buffer[0] === RESPONSE_ID) {
const res = decodeReply(from, state);
if (res === null) return;
for (let i = 0; i < this.inflight.length; i++) {
const req = this.inflight[i];
if (req.tid !== res.tid) continue;
res.rtt = Date.now() - req._timestamp;
if (this._adt && req.sent <= 2) {
this._adt.put(`${req.to.host}:${req.to.port}`, res.rtt);
}
if (i === this.inflight.length - 1) this.inflight.pop();
else this.inflight[i] = this.inflight.pop();
if (req.session) req.session._detach(req);
if (req._timeout) {
clearTimeout(req._timeout);
req._timeout = null;
}
this.congestion.recv();
if (req.internal && req.command < this.stats.commands.length) {
this.stats.commands[req.command].rx++;
}
this.stats.requests.active--;
this.stats.requests.responses++;
this.onresponse(res, external);
req.onresponse(res, req);
break;
}
}
}
token(addr, i) {
if (this._secrets === null) {
const buf = b4a.alloc(64);
this._secrets = [buf.subarray(0, 32), buf.subarray(32, 64)];
sodium.randombytes_buf(this._secrets[0]);
sodium.randombytes_buf(this._secrets[1]);
}
const token = b4a.allocUnsafe(32);
sodium.crypto_generichash(token, b4a.from(addr.host), this._secrets[i]);
return token;
}
async destroy() {
if (this._destroying) return this._destroying;
this._destroying = this._destroy();
return this._destroying;
}
async _destroy() {
await this.bind();
await this._clear(false);
}
async _clear(suspended) {
if (this._drainInterval) {
clearInterval(this._drainInterval);
this._drainInterval = null;
}
while (this.inflight.length) {
const req = this.inflight.pop();
if (req._timeout) clearTimeout(req._timeout);
req._timeout = null;
req.destroyed = true;
if (req.session) req.session._detach(req);
this.congestion.recv();
this.stats.requests.active--;
req.onerror(suspended ? IO_SUSPENDED() : REQUEST_DESTROYED(), req);
}
await Promise.allSettled([this.serverSocket.close(), this.clientSocket.close()]);
this.networkInterfaces.destroy();
}
async suspend() {
this.suspended = true;
await this._clear(true);
this.congestion.clear();
if (this._drainInterval) {
clearInterval(this._drainInterval);
this._drainInterval = null;
}
}
async _rebind(binding) {
if (binding) await binding;
if (this._destroying) return this._destroying;
await this._bindSockets();
this.networkInterfaces = this.udx.watchNetworkInterfaces();
}
resume() {
this.suspended = false;
const binding = this._binding;
this._binding = this._rebind(binding);
return this._binding;
}
bind() {
if (this._binding) return this._binding;
this._binding = this._bindSockets();
return this._binding;
}
async _bindSockets() {
const serverSocket = this.udx.createSocket();
const candidatePorts = [];
if (this._boundServerPort) candidatePorts.push(this._boundServerPort);
for (let i = this.portRange[0]; i < this.portRange[1]; i++) candidatePorts.push(i);
for (const port of candidatePorts) {
if (serverSocket.bound) break;
try {
serverSocket.bind(port, this._host);
} catch (err) {
if (!this._anyPort) {
await serverSocket.close();
throw err;
}
}
}
if (!serverSocket.bound) {
try {
serverSocket.bind(0, this._host);
} catch (err) {
await serverSocket.close();
throw err;
}
}
const clientSocket = this.udx.createSocket();
try {
clientSocket.bind(this._boundClientPort || 0, this._host);
} catch {
try {
clientSocket.bind(0, this._host);
} catch (err) {
await serverSocket.close();
await clientSocket.close();
throw err;
}
}
this._boundServerPort = serverSocket.address().port;
this._boundClientPort = clientSocket.address().port;
this.clientSocket = clientSocket;
this.serverSocket = serverSocket;
this.serverSocket.on("message", this.onmessage.bind(this, this.serverSocket));
this.clientSocket.on("message", this.onmessage.bind(this, this.clientSocket));
if (this._drainInterval === null) {
this._drainInterval = setInterval(this._drain.bind(this), 750);
if (this._drainInterval.unref) this._drainInterval.unref();
}
for (const req of this.inflight) {
if (!req.socket) req.socket = this.firewalled ? this.clientSocket : this.serverSocket;
req.sent = 0;
req.send(false);
}
}
_drain() {
if (this._secrets !== null && --this._rotateSecrets === 0) {
this._rotateSecrets = 10;
const tmp = this._secrets[0];
this._secrets[0] = this._secrets[1];
this._secrets[1] = tmp;
sodium.crypto_generichash(tmp, tmp);
}
this.congestion.drain();
while (!this.congestion.isFull()) {
const p = this._pending.shift();
if (p === void 0) return;
p._sendNow();
}
}
createRequest(to, token, internal, command, target, value, session, ttl) {
if (this._destroying !== null) return null;
if (this._tid === 65536) this._tid = 0;
const tid = this._tid++;
const socket = this.firewalled ? this.clientSocket : this.serverSocket;
const req = new Request(
this,
socket,
tid,
null,
to,
token,
internal,
command,
target,
value,
session,
ttl || 0
);
this.inflight.push(req);
if (session) session._attach(req);
if (internal && command < this.stats.commands.length) {
this.stats.commands[command].tx++;
}
this.stats.requests.active++;
this.stats.requests.total++;
return req;
}
};
var Request = class _Request {
constructor(io, socket, tid, from, to, token, internal, command, target, value, session, ttl) {
this.socket = socket;
this.tid = tid;
this.from = from;
this.to = to;
this.token = token;
this.command = command;
this.target = target;
this.value = value;
this.internal = internal;
this.session = session;
this.ttl = ttl;
this.index = -1;
this.sent = 0;
this.retries = 3;
this.destroyed = false;
this.timeout = 0;
this.oncycle = noop;
this.onerror = noop;
this.onresponse = noop;
this._buffer = null;
this._io = io;
this._timeout = null;
this._timestamp = Date.now();
}
static decode(io, socket, from, state) {
try {
const flags = c.uint.decode(state);
const tid = c.uint16.decode(state);
const to = peer.ipv4.decode(state);
const id = flags & 1 ? c.fixed32.decode(state) : null;
const token = flags & 2 ? c.fixed32.decode(state) : null;
const internal = (flags & 4) !== 0;
const command = c.uint.decode(state);
const target = flags & 8 ? c.fixed32.decode(state) : null;
const value = flags & 16 ? c.buffer.decode(state) : null;
if (id !== null) from.id = validateId(id, from);
return new _Request(
io,
socket,
tid,
from,
to,
token,
internal,
command,
target,
value,
null,
0
);
} catch {
return null;
}
}
reply(value, opts = {}) {
const socket = opts.socket || this.socket;
const to = opts.to || this.from;
this._sendReply(0, value || null, opts.token !== false, opts.closerNodes !== false, to, socket);
}
error(code, opts = {}) {
const socket = opts.socket || this.socket;
const to = opts.to || this.from;
this._sendReply(code, null, opts.token === true, opts.closerNodes !== false, to, socket);
}
relay(value, to, opts) {
const socket = opts && opts.socket || this.socket;
const buffer = this._encodeRequest(null, value, to, socket);
socket.trySend(buffer, to.port, to.host, this.ttl);
}
send(force = false) {
if (this.destroyed) return;
if (this.socket === null) return;
if (this._buffer === null) {
this._buffer = this._encodeRequest(this.token, this.value, this.to, this.socket);
}
if (!force && this._io.congestion.isFull()) {
this._io._pending.push(this);
return;
}
this._sendNow();
}
sendReply(error, value, token, hasCloserNodes) {
this._sendReply(error, value, token, hasCloserNodes, this.from, this.socket, null);
}
_sendNow() {
if (this.destroyed) return;
this.sent++;
this._io.congestion.send();
this.socket.trySend(this._buffer, this.to.port, this.to.host, this.ttl);
if (this._timeout) clearTimeout(this._timeout);
const value = this.timeout || this._io._adt?.get(`${this.to.host}:${this.to.port}`, this.sent) || 1e3;
this._timeout = setTimeout(oncycle, value, this);
}
destroy(err) {
if (this.destroyed) return;
this.destroyed = true;
if (this._timeout) {
clearTimeout(this._timeout);
this._timeout = null;
}
const i = this._io.inflight.indexOf(this);
if (i === -1) return;
if (i === this._io.inflight.length - 1) this._io.inflight.pop();
else this._io.inflight[i] = this._io.inflight.pop();
if (this.session) this.session._detach(this);
this._io.stats.requests.active--;
this._io.congestion.recv();
this.onerror(err || REQUEST_DESTROYED(), this);
}
_sendReply(error, value, token, hasCloserNodes, from, socket) {
if (socket === null || this.destroyed) return;
const id = this._io.ephemeral === false && socket === this._io.serverSocket;
const closerNodes = this.target !== null && hasCloserNodes ? this._io.table.closest(this.target) : EMPTY_ARRAY;
const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null };
if (id) state.end += 32;
if (token) state.end += 32;
if (closerNodes.length > 0) peer.ipv4Array.preencode(state, closerNodes);
if (error > 0) c.uint.preencode(state, error);
if (value) c.buffer.preencode(state, value);
state.buffer = b4a.allocUnsafe(state.end);
state.buffer[state.start++] = RESPONSE_ID;
state.buffer[state.start++] = (id ? 1 : 0) | (token ? 2 : 0) | (closerNodes.length > 0 ? 4 : 0) | (error > 0 ? 8 : 0) | (value ? 16 : 0);
c.uint16.encode(state, this.tid);
peer.ipv4.encode(state, from);
if (id) c.fixed32.encode(state, this._io.table.id);
if (token) c.fixed32.encode(state, this._io.token(from, 1));
if (closerNodes.length > 0) peer.ipv4Array.encode(state, closerNodes);
if (error > 0) c.uint.encode(state, error);
if (value) c.buffer.encode(state, value);
socket.trySend(state.buffer, from.port, from.host, this.ttl);
}
_encodeRequest(token, value, to, socket) {
const id = this._io.ephemeral === false && socket === this._io.serverSocket;
const state = { start: 0, end: 1 + 1 + 6 + 2, buffer: null };
if (id) state.end += 32;
if (token) state.end += 32;
c.uint.preencode(state, this.command);
if (this.target) state.end += 32;
if (value) c.buffer.preencode(state, value);
state.buffer = b4a.allocUnsafe(state.end);
state.buffer[state.start++] = REQUEST_ID;
state.buffer[state.start++] = (id ? 1 : 0) | (token ? 2 : 0) | (this.internal ? 4 : 0) | (this.target ? 8 : 0) | (value ? 16 : 0);
c.uint16.encode(state, this.tid);
peer.ipv4.encode(state, to);
if (id) c.fixed32.encode(state, this._io.table.id);
if (token) c.fixed32.encode(state, token);
c.uint.encode(state, this.command);
if (this.target) c.fixed32.encode(state, this.target);
if (value) c.buffer.encode(state, value);
return state.buffer;
}
};
var CongestionWindow = class {
constructor(maxWindow) {
this._i = 0;
this._total = 0;
this._window = [0, 0, 0, 0];
this._maxWindow = maxWindow;
}
clear() {
this._i = 0;
this._total = 0;
this._window = [0, 0, 0, 0];
}
isFull() {
return this._total >= 2 * this._maxWindow || this._window[this._i] >= this._maxWindow;
}
recv() {
if (this._window[this._i] > 0) {
this._window[this._i]--;
this._total--;
}
}
send() {
this._total++;
this._window[this._i]++;
}
drain() {
this._i = this._i + 1 & 3;
this._total -= this._window[this._i];
this._window[this._i] = 0;
}
};
function noop() {
}
function oncycle(req) {
req._timeout = null;
req.oncycle(req);
if (req.sent > req.retries) {
req._io.stats.requests.timeouts++;
req.destroy(REQUEST_TIMEOUT());
req._io.ontimeout(req);
} else {
req._io.stats.requests.retries++;
req.send();
}
}
function decodeReply(from, state) {
try {
const flags = c.uint.decode(state);
const tid = c.uint16.decode(state);
const to = peer.ipv4.decode(state);
const id = flags & 1 ? c.fixed32.decode(state) : null;
const token = flags & 2 ? c.fixed32.decode(state) : null;
const closerNodes = flags & 4 ? peer.ipv4Array.decode(state) : null;
const error = flags & 8 ? c.uint.decode(state) : 0;
const value = flags & 16 ? c.buffer.decode(state) : null;
if (id !== null) from.id = validateId(id, from);
return { tid, rtt: 0, from, to, token, closerNodes, error, value };
} catch {
return null;
}
}
function validateId(id, from) {
const expected = peer.id(from.host, from.port);
return b4a.equals(expected, id) ? expected : null;
}
}
});
// ../../node_modules/dht-rpc/lib/commands.js
var require_commands = __commonJS({
"../../node_modules/dht-rpc/lib/commands.js"(exports) {
exports.PING = 0;
exports.PING_NAT = 1;
exports.FIND_NODE = 2;
exports.DOWN_HINT = 3;
exports.DELAYED_PING = 4;
}
});
// ../../node_modules/dht-rpc/lib/query.js
var require_query = __commonJS({
"../../node_modules/dht-rpc/lib/query.js"(exports, module) {
var { Readable, getStreamError } = require_streamx();
var b4a = require_b4a();
var peer = require_peer();
var { DOWN_HINT } = require_commands();
var DONE = [];
var DOWN = [];
module.exports = class Query extends Readable {
constructor(dht, target, internal, command, value, opts = {}) {
super();
dht.stats.queries.total++;
dht.stats.queries.active++;
this.force = !!opts.force;
this.dht = dht;
this.k = this.dht.table.k;
this.target = target;
this.internal = internal;
this.command = command;
this.value = value;
this.errors = 0;
this.successes = 0;
this.concurrency = opts.concurrency || this.dht.concurrency;
this.inflight = 0;
this.map = opts.map || defaultMap;
this.retries = opts.retries === 0 ? 0 : opts.retries || (this.internal && command === DOWN_HINT ? 3 : 5);
this.closestReplies = [];
this._slow = 0;
this._slowdown = false;
this._seen = /* @__PURE__ */ new Map();
this._pending = [];
this._fromTable = false;
this._commit = opts.commit === true ? autoCommit : opts.commit || null;
this._commiting = false;
this._session = opts.session || dht.session();
this._autoDestroySession = !opts.session;
this._onlyClosestNodes = false;
this._onvisitbound = this._onvisit.bind(this);
this._onerrorbound = this._onerror.bind(this);
this._oncyclebound = this._oncycle.bind(this);
const nodes = opts.nodes || opts.closestNodes;
const replies = opts.replies || opts.closestReplies;
if (nodes) {
for (let i = nodes.length - 1; i >= 0; i--) {
const node = nodes[i];
this._addPending(
{
id: node.id || peer.id(node.host, node.port),
host: node.host,
port: node.port
},
null
);
}
} else if (replies) {
for (let i = replies.length - 1; i >= 0; i--) {
this._addPending(replies[i].from, null);
}
}
if (opts.onlyClosestNodes) this._onlyClosestNodes = true;
}
get closestNodes() {
const nodes = new Array(this.closestReplies.length);
for (let i = 0; i < nodes.length; i++) {
nodes[i] = this.closestReplies[i].from;
}
return nodes;
}
finished() {
return new Promise((resolve, reject) => {
if (this.destroyed) {
const error2 = getStreamError(this);
if (error2) reject(error2);
else resolve();
return;
}
const self = this;
let error = null;
this.resume();
this.on("error", onerror);
this.on("close", onclose);
function onclose() {
self.removeListener("error", onerror);
self.removeListener("close", onclose);
if (error) reject(error);
else resolve();
}
function onerror(err) {
error = err;
}
});
}
_addFromTable() {
if (this._pending.length >= this.k) return;
this._fromTable = true;
const closest = this.dht.table.closest(this.target, this.k - this._pending.length);
for (const node of closest) {
this._addPending({ id: node.id, host: node.host, port: node.port }, null);
}
}
async _open(cb) {
this._addFromTable();
if (this._pending.length >= this.k) return cb(null);
for await (const node of this.dht._resolveBootstrapNodes()) {
this._addPending(node, null);
}
cb(null);
}
_isCloser(id) {
return this.closestReplies.length < this.k || this._compare(id, this.closestReplies[this.closestReplies.length - 1].from.id) < 0;
}
_addPending(node, ref) {
if (this._onlyClosestNodes) return false;
const addr = node.host + ":" + node.port;
const refs = this._seen.get(addr);
const isCloser = this._isCloser(node.id);
if (refs === DONE) {
return isCloser;
}
if (refs === DOWN) {
if (ref) this._downHint(ref, node);
return isCloser;
}
if (refs) {
if (ref !== null) refs.push(ref);
return isCloser;
}
if (!isCloser) {
return false;
}
this._seen.set(addr, ref === null ? [] : [ref]);
this._pending.push(node);
return true;
}
_read(cb) {
this._readMore();
cb(null);
}
_readMore() {
if (this.destroying || this._commiting) return;
const concurrency = (this._slowdown ? 3 : this.concurrency) + this._slow;
while (this.inflight < concurrency && this._pending.length > 0) {
const next = this._pending.pop();
if (next && next.id && !this._isCloser(next.id)) continue;
this._visit(next);
}
if (!this._fromTable && this.successes === 0 && this.errors === 0) {
this._slowdown = true;
}
if (this._pending.length > 0) return;
if (this.inflight === 0 || this._slow === this.inflight && this.closestReplies.length >= this.k) {
if (!this._fromTable && this.successes < this.k / 4) {
this._addFromTable();
this._readMore();
return;
}
this._flush();
}
}
_flush() {
if (this._commiting) return;
this._commiting = true;
if (this._commit === null) {
this.push(null);
return;
}
const p = [];
for (const m of this.closestReplies) p.push(this._commit(m, this.dht, this));
this._endAfterCommit(p);
}
_endAfterCommit(ps) {
if (!ps.length) {
this.destroy(new Error("Too few nodes responded"));
return;
}
const self = this;
let pending = ps.length;
let success = 0;
for (const p of ps) p.then(ondone, onerror);
function ondone() {
success++;
if (--pending === 0) self.push(null);
}
function onerror(err) {
if (--pending > 0) return;
if (success) self.push(null);
else self.destroy(err);
}
}
_dec(req) {
if (req.oncycle === noop) {
this._slow--;
} else {
req.oncycle = noop;
}
this.inflight--;
}
_onvisit(m, req) {
this._dec(req);
const addr = req.to.host + ":" + req.to.port;
this._seen.set(addr, DONE);
if (this._commiting) return;
if (m.error === 0) this.successes++;
else this.errors++;
if (m.error === 0 && m.from.id !== null && this._isCloser(m.from.id)) this._pushClosest(m);
if (m.closerNodes !== null) {
for (const node of m.closerNodes) {
node.id = peer.id(node.host, node.port);
if (this.dht._filterNode !== null && !this.dht._filterNode(node)) continue;
if (b4a.equals(node.id, this.dht.table.id)) continue;
if (!this._addPending(node, m.from)) break;
}
}
if (!this._fromTable && this.successes + this.errors >= this.concurrency) {
this._slowdown = false;
}
if (m.error !== 0) {
this._readMore();
return;
}
const data = this.map(m);
if (!data || this.push(data) !== false) {
this._readMore();
}
}
_onerror(err, req) {
const addr = req.to.host + ":" + req.to.port;
const refs = this._seen.get(addr);
if (err.code === "REQUEST_TIMEOUT") {
this._seen.set(addr, DOWN);
for (const node of refs) this._downHint(node, req.to);
}
this._dec(req);
this.errors++;
this._readMore();
}
_oncycle(req) {
req.oncycle = noop;
this._slow++;
this._readMore();
}
_downHint(node, down) {
if (this.dht._downHintsRateLimit !== -1 && this.dht._downHintsSentPerTick >= this.dht._downHintsRateLimit) {
return null;
}
this.dht._downHintsSentPerTick++;
const state = { start: 0, end: 6, buffer: b4a.allocUnsafe(6) };
peer.ipv4.encode(state, down);
this.dht._request(node, false, true, DOWN_HINT, null, state.buffer, this._session, noop, noop);
}
_pushClosest(m) {
this.closestReplies.push(m);
for (let i = this.closestReplies.length - 2; i >= 0; i--) {
const prev = this.closestReplies[i];
const cmp = this._compare(prev.from.id, m.from.id);
if (cmp < 0) break;
if (cmp === 0) {
this.closestReplies.splice(i + 1, 1);
break;
}
this.closestReplies[i + 1] = prev;
this.closestReplies[i] = m;
}
if (this.closestReplies.length > this.k) this.closestReplies.pop();
}
_compare(a, b) {
for (let i = 0; i < a.length; i++) {
if (a[i] === b[i]) continue;
const t = this.target[i];
return (t ^ a[i]) - (t ^ b[i]);
}
return 0;
}
_visit(to) {
this.inflight++;
const req = this.dht._request(
to,
this.force,
this.internal,
this.command,
this.target,
this.value,
this._session,
this._onvisitbound,
this._onerrorbound
);
if (req === null) {
this.destroy(new Error("Node was destroyed"));
return;
}
req.retries = this.retries;
req.oncycle = this._oncyclebound;
if (this.force) req.retries = 0;
}
_destroy(cb) {
this.dht.stats.queries.active--;
if (this._autoDestroySession) this._session.destroy();
cb(null);
}
};
function autoCommit(reply, dht, query) {
if (!reply.token) return Promise.reject(new Error("No token received for closest node"));
return dht.request(
{
token: reply.token,
target: query.target,
command: query.command,
value: query.value
},
reply.from
);
}
function defaultMap(m) {
return m;
}
function noop() {
}
}
});
// ../../node_modules/dht-rpc/lib/session.js
var require_session = __commonJS({
"../../node_modules/dht-rpc/lib/session.js"(exports, module) {
module.exports = class Session {
constructor(dht) {
this.dht = dht;
this.inflight = [];
}
_attach(req) {
req.index = this.inflight.push(req) - 1;
}
_detach(req) {
const i = req.index;
if (i === -1) return;
req.index = -1;
if (i === this.inflight.length - 1) this.inflight.pop();
else {
const req2 = this.inflight[i] = this.inflight.pop();
req2.index = i;
}
}
query({ target, command, value }, opts = {}) {
return this.dht.query({ target, command, value }, { ...opts, session: this });
}
request({ token, command, target, value }, { host, port }, opts = {}) {
return this.dht.request(
{ token, command, target, value },
{ host, port },
{ ...opts, session: this }
);
}
ping({ host, port }, opts = {}) {
return this.dht.ping({ host, port }, { ...opts, session: this });
}
destroy(err) {
while (this.inflight.length) {
const req = this.inflight[0];
this.dht.io.congestion.recv();
req.destroy(err);
}
}
};
}
});
// ../../node_modules/dht-rpc/index.js
var require_dht_rpc = __commonJS({
"../../node_modules/dht-rpc/index.js"(exports, module) {
var { EventEmitter } = require_bare_node_events();
var Table = require_kademlia_routing_table();
var TOS = require_time_ordered_set();
var UDX = require_udx();
var sodium = require_sodium_universal();
var c = require_compact_encoding();
var NatSampler = require_nat_sampler();
var b4a = require_b4a();
var NetworkHealth = require_health();
var IO = require_io();
var Query = require_query();
var Session = require_session();
var peer = require_peer();
var { UNKNOWN_COMMAND, INVALID_TOKEN } = require_errors8();
var { PING, PING_NAT, FIND_NODE, DOWN_HINT, DELAYED_PING } = require_commands();
var TMP = b4a.allocUnsafe(32);
var TICK_INTERVAL = 5e3;
var SLEEPING_INTERVAL = 3 * TICK_INTERVAL;
var STABLE_TICKS = 240;
var MORE_STABLE_TICKS = 3 * STABLE_TICKS;
var REFRESH_TICKS = 60;
var RECENT_NODE = 12;
var OLD_NODE = 360;
var DEFAULTS = {
concurrency: 10,
maxWindow: IO.DEFAULT_MAX_WINDOW,
maxPingDelay: 1e4
};
var DHT = class extends EventEmitter {
constructor(opts = {}) {
super();
this.bootstrapNodes = opts.bootstrap === false ? [] : (opts.bootstrap || []).map(parseNode);
this.table = new Table(randomBytes(32));
this.nodes = new TOS();
this.udx = opts.udx || new UDX();
this.io = new IO(this.table, this.udx, {
...opts,
onrequest: this._onrequest.bind(this),
onresponse: this._onresponse.bind(this),
ontimeout: this._ontimeout.bind(this)
});
this.health = new NetworkHealth(this);
this.concurrency = opts.concurrency || DEFAULTS.concurrency;
this.maxPingDelay = opts.maxPingDelay || DEFAULTS.maxPingDelay;
this.bootstrapped = false;
this.ephemeral = true;
this.firewalled = this.io.firewalled;
this.adaptive = typeof opts.ephemeral !== "boolean" && opts.adaptive !== false;
this.destroyed = false;
this.suspended = false;
this.online = true;
this.degraded = false;
this.stats = {
queries: { active: 0, total: 0 },
requests: this.io.stats.requests,
commands: {
ping: this.io.stats.commands[PING],
pingNat: this.io.stats.commands[PING_NAT],
findNode: this.io.stats.commands[FIND_NODE],
downHint: this.io.stats.commands[DOWN_HINT]
}
};
this._nat = new NatSampler();
this._quickFirewall = opts.quickFirewall !== false;
this._forcePersistent = opts.ephemeral === false;
this._repinging = 0;
this._checks = 0;
this._tick = randomOffset(100);
this._refreshTicks = randomOffset(REFRESH_TICKS);
this._stableTicks = this.adaptive ? STABLE_TICKS : 0;
this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL);
this._lastTick = Date.now();
this._lastHost = null;
this._filterNode = opts.filterNode || opts.addNode || null;
this._onrow = (row) => row.on("full", (node) => this._onfullrow(node, row));
this._nonePersistentSamples = [];
this._bootstrapping = this._bootstrap();
this._bootstrapping.catch(noop);
this._sendDownHints = opts.sendDownHints !== false;
this._downHintsRateLimit = opts.downHintsRateLimit !== void 0 ? opts.downHintsRateLimit : 10 * 5;
this._downHintsSentPerTick = 0;
this._pendingTimers = /* @__PURE__ */ new Set();
this.table.on("row", this._onrow);
this.io.networkInterfaces.on("change", (interfaces) => this._onnetworkchange(interfaces));
if (opts.nodes) {
for (let i = opts.nodes.length - 1; i >= 0; i--) {
this.addNode(opts.nodes[i]);
}
}
}
static DEFAULTS = DEFAULTS;
static bootstrapper(port, host, opts) {
if (!port) throw new Error("Port is required");
if (!host) throw new Error("Host is required");
if (host === "0.0.0.0" || host === "::") throw new Error("Invalid host");
if (!UDX.isIPv4(host)) throw new Error("Host must be a IPv4 address");
const dht = new this({
port,
ephemeral: false,
firewalled: false,
anyPort: false,
bootstrap: [],
...opts
});
dht._nat.add(host, port);
return dht;
}
get id() {
return this.ephemeral ? null : this.table.id;
}
get host() {
return this._nat.host;
}
get port() {
return this._nat.port;
}
get randomized() {
return this._nat.host !== null && this._nat.port === 0;
}
get socket() {
return this.firewalled ? this.io.clientSocket : this.io.serverSocket;
}
get config() {
return {
concurrency: this.concurrency,
maxWindow: this.io.congestion._maxWindow,
randomPunchInterval: this._randomPunchInterval,
connectionKeepAlive: this.connectionKeepAlive,
sendDownHints: this._sendDownHints,
downHintsRateLimit: this._downHintsRateLimit
};
}
onmessage(socket, buf, rinfo) {
if (buf.byteLength > 1) this.io.onmessage(socket, buf, rinfo);
}
bind() {
return this.io.bind();
}
async suspend({ log = noop } = {}) {
log("Suspending waiting for io bind...");
await this.io.bind();
log("Done, continuing");
if (this.suspended || this.destroyed) return;
this.suspended = true;
clearInterval(this._tickInterval);
log("Done, suspending io");
await this.io.suspend({ log });
log("Done, dht suspended");
this.emit("suspend");
}
async resume({ log = noop } = {}) {
if (!this.suspended || this.destroyed) return;
this.suspended = false;
this._tickInterval = setInterval(this._ontick.bind(this), TICK_INTERVAL);
this._onwakeup();
log("Resuming io");
await this.io.resume();
log("Done, dht resumed");
this.io.networkInterfaces.on("change", (interfaces) => this._onnetworkchange(interfaces));
this.refresh();
this.emit("resume");
}
address() {
const socket = this.socket;
return socket ? socket.address() : null;
}
localAddress() {
if (!this.io.serverSocket) return null;
return {
host: localIP(this.udx),
port: this.io.serverSocket.address().port
};
}
remoteAddress() {
if (!this.host) return null;
if (!this.port) return null;
if (this.firewalled) return null;
if (!this.io.serverSocket) return null;
const port = this.io.serverSocket.address().port;
if (port !== this.port) return null;
return {
host: this.host,
port
};
}
addNode({ host, port }) {
this._addNode({
id: peer.id(host, port),
port,
host,
token: null,
to: null,
sampled: 0,
added: this._tick,
pinged: 0,
seen: 0,
downHints: 0,
prev: null,
next: null
});
}
toArray(opts) {
const limit = opts && opts.limit;
if (limit === 0) return [];
return this.nodes.toArray({ limit, reverse: true }).map(({ host, port }) => ({ host, port }));
}
async fullyBootstrapped() {
return this._bootstrapping;
}
ready() {
return this.fullyBootstrapped();
}
findNode(target, opts) {
if (this.destroyed) throw new Error("Node destroyed");
this._refreshTicks = REFRESH_TICKS;
return new Query(this, target, true, FIND_NODE, null, opts);
}
query({ target, command, value }, opts) {
if (this.destroyed) throw new Error("Node destroyed");
this._refreshTicks = REFRESH_TICKS;
return new Query(this, target, false, command, value || null, opts);
}
ping({ host, port }, opts) {
let value = null;
if (opts && opts.size && opts.size > 0) value = b4a.alloc(opts.size);
const req = this.io.createRequest(
{ id: null, host, port },
null,
true,
PING,
null,
value,
opts && opts.session || null,
opts && opts.ttl
);
return this._requestToPromise(req, opts);
}
delayedPing({ host, port }, delayMs, opts) {
if (delayMs > this.maxPingDelay) {
throw new Error(`Delay exceeds max delay: ${this.maxPingDelay}ms`);
}
const value = b4a.allocUnsafe(4);
c.uint32.encode({ start: 0, end: 4, buffer: value }, delayMs);
const req = this.io.createRequest(
{ id: null, host, port },
null,
true,
DELAYED_PING,
null,
value,
opts && opts.session || null,
opts && opts.ttl
);
req.timeout = delayMs + 1e3;
return this._requestToPromise(req, opts);
}
async rttStats() {
const stats = {
successes: 0,
errors: 0,
responses: {
avgRtt: 0,
errors: 0,
avgCloserNodes: 0
},
closestReplies: {
avgRtt: 0,
errors: 0,
avgCloserNodes: 0
}
};
if (this.nodes.latest) {
const q = this.findNode(this.nodes.latest.id);
let responseCount = 0;
let closestCount = 0;
for await (const msg of q) {
stats.responses.avgRtt += msg.rtt;
stats.responses.errors += msg.error;
stats.responses.avgCloserNodes += msg.closerNodes?.length || 0;
responseCount++;
}
stats.responses.avgRtt /= responseCount;
stats.responses.avgCloserNodes /= responseCount;
for await (const msg of q.closestReplies) {
stats.closestReplies.avgRtt += msg.rtt;
stats.closestReplies.errors += msg.error;
stats.closestReplies.avgCloserNodes += msg.closerNodes?.length || 0;
closestCount++;
}
stats.closestReplies.avgRtt /= closestCount;
stats.closestReplies.avgCloserNodes /= closestCount;
stats.successes = q.successes;
stats.errors = q.errors;
}
return stats;
}
request({ token = null, command, target = null, value = null }, { host, port }, opts) {
const req = this.io.createRequest(
{ id: null, host, port },
token,
false,
command,
target,
value,
opts && opts.session || null,
opts && opts.ttl
);
return this._requestToPromise(req, opts);
}
session() {
return new Session(this);
}
_requestToPromise(req, opts) {
if (req === null) return Promise.reject(new Error("Node destroyed"));
if (opts && opts.socket) req.socket = opts.socket;
if (opts && opts.retry === false) req.retries = 0;
return new Promise((resolve, reject) => {
req.onresponse = resolve;
req.onerror = reject;
req.send();
});
}
async _bootstrap() {
const self = this;
await Promise.resolve();
await this.io.bind();
this.emit("listening");
let first = this.firewalled && this._quickFirewall && !this._forcePersistent;
let testNat = false;
const onlyFirewall = !this._forcePersistent;
for (let i = 0; i < 2; i++) {
await this._backgroundQuery(this.table.id).on("data", ondata).finished();
if (this.bootstrapped || !testNat && !this._forcePersistent) break;
if (!await this._updateNetworkState(onlyFirewall)) break;
}
if (this.bootstrapped) return;
this.bootstrapped = true;
this.emit("ready");
function ondata(data) {
if (!first) return;
first = false;
const value = b4a.allocUnsafe(2);
c.uint16.encode({ start: 0, end: 2, buffer: value }, self.io.serverSocket.address().port);
self._request(
data.from,
false,
true,
PING_NAT,
null,
value,
null,
() => {
testNat = true;
},
noop
);
}
}
refresh() {
const node = this.table.random();
this._backgroundQuery(node ? node.id : this.table.id).on("error", noop);
}
async destroy() {
const emitClose = !this.destroyed;
this.destroyed = true;
clearInterval(this._tickInterval);
for (const timer of this._pendingTimers) {
clearTimeout(timer);
}
await this.io.destroy();
if (emitClose) this.emit("close");
}
_request(to, force, internal, command, target, value, session, onresponse, onerror) {
if (internal && !this._sendDownHints && command === DOWN_HINT) return null;
const req = this.io.createRequest(to, null, internal, command, target, value, session);
if (req === null) return null;
req.onresponse = onresponse;
req.onerror = onerror;
req.send(force);
return req;
}
_natAdd(host, port) {
const prevHost = this._nat.host;
const prevPort = this._nat.port;
this._nat.add(host, port);
if (prevHost === this._nat.host && prevPort === this._nat.port) return;
this.emit("nat-update", this._nat.host, this._nat.port);
}
// we don't check that this is a bootstrap node but we limit the sample size to very few nodes, so fine
_sampleBootstrapMaybe(from, to) {
if (this._nonePersistentSamples.length >= Math.max(1, this.bootstrapNodes.length)) return;
const id = from.host + ":" + from.port;
if (this._nonePersistentSamples.indexOf(id) > -1) return;
this._nonePersistentSamples.push(id);
this._natAdd(to.host, to.port);
}
_addNodeFromNetwork(sample, from, to) {
if (this._filterNode !== null && !this._filterNode(from)) {
return;
}
if (from.id === null) {
this._sampleBootstrapMaybe(from, to);
return;
}
const oldNode = this.table.get(from.id);
if (oldNode) {
if (sample && (oldNode.sampled === 0 || this._tick - oldNode.sampled >= OLD_NODE)) {
oldNode.to = to;
oldNode.sampled = this._tick;
this._natAdd(to.host, to.port);
}
oldNode.pinged = oldNode.seen = this._tick;
this.nodes.add(oldNode);
return;
}
this._addNode({
id: from.id,
port: from.port,
host: from.host,
to,
sampled: 0,
added: this._tick,
pinged: this._tick,
// last time we interacted with them
seen: this._tick,
// last time we heard from them
downHints: 0,
prev: null,
next: null
});
}
_addNode(node) {
if (this.nodes.has(node) || b4a.equals(node.id, this.table.id)) return;
node.added = node.pinged = node.seen = this._tick;
if (!this.table.add(node)) return;
this.nodes.add(node);
if (node.to && node.sampled === 0) {
node.sampled = this._tick;
this._natAdd(node.to.host, node.to.port);
}
this.emit("add-node", node);
}
_removeStaleNode(node, lastSeen) {
if (node.seen <= lastSeen) this._removeNode(node);
}
_removeNode(node) {
if (!this.nodes.has(node)) return;
this.table.remove(node.id);
this.nodes.remove(node);
this.emit("remove-node", node);
}
_onwakeup() {
this._tick += 2 * OLD_NODE;
this._tick += 8 - (this._tick & 7) - 2;
this._stableTicks = MORE_STABLE_TICKS;
this._refreshTicks = 1;
this._lastHost = null;
this.health.reset();
if (this.adaptive) {
if (!this.ephemeral) {
this.ephemeral = true;
this.io.ephemeral = true;
this.emit("ephemeral");
}
}
this.emit("wakeup");
}
_onfullrow(newNode, row) {
if (!this.bootstrapped || this._repinging >= 3) return;
let oldest = null;
for (const node of row.nodes) {
if (node.pinged === this._tick) continue;
if (oldest === null || oldest.pinged > node.pinged || oldest.pinged === node.pinged && oldest.added > node.added) {
oldest = node;
}
}
if (oldest === null) return;
if (this._tick - oldest.pinged < RECENT_NODE && this._tick - oldest.added > OLD_NODE) return;
this._repingAndSwap(newNode, oldest);
}
_onnetworkchange(interfaces) {
this.emit("network-change", interfaces);
this.emit("network-update");
}
_repingAndSwap(newNode, oldNode) {
const self = this;
const lastSeen = oldNode.seen;
oldNode.pinged = this._tick;
this._repinging++;
this._request(
{ id: null, host: oldNode.host, port: oldNode.port },
false,
true,
PING,
null,
null,
null,
onsuccess,
onswap
);
function onsuccess(m) {
if (oldNode.seen <= lastSeen) return onswap();
self._repinging--;
}
function onswap(e) {
self._repinging--;
self._removeNode(oldNode);
self._addNode(newNode);
}
}
_onrequest(req, external) {
if (req.from.id !== null) {
this._addNodeFromNetwork(!external, req.from, req.to);
}
if (req.internal) {
switch (req.command) {
// standard keep alive call
case PING: {
req.sendReply(0, null, false, false);
return;
}
case DELAYED_PING: {
this._ondelayedping(req);
return;
}
// check if the other side can receive a message to their other socket
case PING_NAT: {
if (req.value === null || req.value.byteLength < 2) return;
const port = c.uint16.decode({ start: 0, end: 2, buffer: req.value });
if (port === 0) return;
req.from.port = port;
req.sendReply(0, null, false, false);
return;
}
// empty dht reply back
case FIND_NODE: {
if (!req.target) return;
req.sendReply(0, null, false, true);
return;
}
// "this is node you sent me is down" - let's try to ping it
case DOWN_HINT: {
if (req.value === null || req.value.byteLength < 6) return;
if (this._checks < 10) {
sodium.crypto_generichash(TMP, req.value.subarray(0, 6));
const node = this.table.get(TMP);
if (node && (node.pinged < this._tick || node.downHints === 0)) {
node.downHints++;
this._check(node);
}
}
req.sendReply(0, null, false, false);
return;
}
}
req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null);
return;
}
if (this.onrequest(req) === false) {
req.sendReply(UNKNOWN_COMMAND, null, false, req.target !== null);
}
}
onrequest(req) {
return this.emit("request", req);
}
_ondelayedping(req) {
if (req.value === null || req.value.byteLength < 4) return;
const delayMs = c.uint32.decode({ start: 0, end: 4, buffer: req.value });
if (delayMs > this.maxPingDelay) return;
const timer = setTimeout(() => {
if (this.destroyed) return;
this._pendingTimers.delete(timer);
req.sendReply(0, null, false, false);
}, delayMs);
this._pendingTimers.add(timer);
}
_onresponse(res, external) {
this._addNodeFromNetwork(!external, res.from, res.to);
}
_ontimeout(req) {
if (!req.to.id) return;
const node = this.table.get(req.to.id);
if (node) this._removeNode(node);
}
_pingSome() {
let cnt = this.io.inflight.length > 2 ? 3 : 5;
let oldest = this.nodes.oldest;
if (!oldest) {
this.refresh();
return;
}
if (this._tick - oldest.pinged < RECENT_NODE) {
cnt = 2;
}
while (cnt--) {
if (!oldest || this._tick === oldest.pinged) continue;
this._check(oldest);
oldest = oldest.next;
}
}
_check(node) {
node.pinged = this._tick;
const lastSeen = node.seen;
const onresponse = () => {
this._checks--;
this._removeStaleNode(node, lastSeen);
};
const onerror = () => {
this._checks--;
this._removeNode(node);
};
this._checks++;
this._request(
{ id: null, host: node.host, port: node.port },
false,
true,
PING,
null,
null,
null,
onresponse,
onerror
);
}
_ontick() {
const time = Date.now();
if (time - this._lastTick > SLEEPING_INTERVAL && this.suspended === false) {
this._onwakeup();
} else {
this._tick++;
}
this._lastTick = time;
if (!this.bootstrapped || this.suspended) return;
if (this.adaptive && this.ephemeral && --this._stableTicks <= 0) {
if (this._lastHost === this._nat.host) {
this._stableTicks = MORE_STABLE_TICKS;
} else {
this._updateNetworkState();
}
}
if ((this._tick & 7) === 0) {
this._pingSome();
}
if ((this._tick & 63) === 0 && this.nodes.length < this.table.k || --this._refreshTicks <= 0) {
this.refresh();
}
this._downHintsSentPerTick = 0;
this.health.update();
}
async _updateNetworkState(onlyFirewall = false) {
if (!this.ephemeral) return false;
if (onlyFirewall && !this.firewalled) return false;
const { host, port } = this._nat;
if (!onlyFirewall) {
this._stableTicks = MORE_STABLE_TICKS;
this._lastHost = host;
}
if (host === null || port === 0) {
return false;
}
const natSampler = this.firewalled ? new NatSampler() : this._nat;
const firewalled = this.firewalled && await this._checkIfFirewalled(natSampler);
if (firewalled) return false;
this.firewalled = this.io.firewalled = false;
if (!this.ephemeral || host !== this._nat.host || port !== this._nat.port) return false;
if (natSampler.host !== host || natSampler.port === 0) return false;
const id = peer.id(natSampler.host, natSampler.port);
if (!onlyFirewall) {
this.ephemeral = this.io.ephemeral = false;
}
if (natSampler !== this._nat) {
const prevHost = this._nat.host;
const prevPort = this._nat.port;
this._nonePersistentSamples = [];
this._nat = natSampler;
if (prevHost !== this._nat.host || prevPort !== this._nat.port) {
this.emit("nat-update", this._nat.host, this._nat.port);
}
}
if (!b4a.equals(this.table.id, id)) {
const nodes = this.table.toArray();
this.table = this.io.table = new Table(id);
for (const node of nodes) {
if (b4a.equals(node.id, id)) continue;
if (!this.table.add(node)) this.nodes.remove(node);
}
this.table.on("row", this._onrow);
if (this.bootstrapped) this.refresh();
}
if (!this.ephemeral) {
this.emit("persistent");
}
return true;
}
async *_resolveBootstrapNodes() {
for (let { host, port } of this.bootstrapNodes) {
let doLookup = false;
if (host.indexOf("@") === -1) {
doLookup = true;
} else {
const [suggestedIP, fallbackHost] = host.split("@");
try {
await this.ping({ host: suggestedIP, port });
host = suggestedIP;
} catch {
host = fallbackHost;
doLookup = true;
}
}
if (doLookup) {
try {
host = UDX.isIPv4(host) ? host : (await this.udx.lookup(host, { family: 4 })).host;
} catch {
continue;
}
}
yield {
id: peer.id(host, port),
host,
port
};
}
}
async _addBootstrapNodes(nodes) {
for await (const node of this._resolveBootstrapNodes()) {
nodes.push(node);
}
}
async _checkIfFirewalled(natSampler = new NatSampler()) {
const nodes = [];
for (let node = this.nodes.latest; node && nodes.length < 5; node = node.prev) {
nodes.push(node);
}
if (nodes.length < 5) await this._addBootstrapNodes(nodes);
if (nodes.length === 0) return true;
const hosts = /* @__PURE__ */ new Set();
const value = b4a.allocUnsafe(2);
c.uint16.encode({ start: 0, end: 2, buffer: value }, this.io.serverSocket.address().port);
this.io.serverSocket.on("message", onmessage);
const pongs = await requestAll(this, true, PING_NAT, value, nodes);
let count = 0;
for (const res of pongs) {
if (hosts.has(res.from.host)) {
count++;
natSampler.add(res.to.host, res.to.port);
}
}
this.io.serverSocket.removeListener("message", onmessage);
if (count < (nodes.length >= 5 ? 3 : 1)) return true;
if (natSampler.host === null || this._nat.host !== natSampler.host) return true;
if (natSampler.port === 0 || natSampler.port !== this.io.serverSocket.address().port) {
return true;
}
return false;
function onmessage(_, { host }) {
hosts.add(host);
}
}
_backgroundQuery(target) {
this._refreshTicks = REFRESH_TICKS;
const backgroundCon = Math.min(this.concurrency, Math.max(2, this.concurrency / 8 | 0));
const q = new Query(this, target, true, FIND_NODE, null, {
concurrency: backgroundCon
});
q.on("data", () => {
q.concurrency = this.io.inflight.length < 3 ? this.concurrency : backgroundCon;
});
return q;
}
// called by health
_online() {
if (this.online && !this.degraded) return;
this.online = true;
this.degraded = false;
this.emit("network-update");
}
// called by health
_degraded() {
if (this.degraded) return;
this.online = true;
this.degraded = true;
this.emit("network-update");
}
// called by health
_offline() {
if (!this.online) return;
this.online = false;
this.degraded = false;
this.emit("network-update");
}
};
DHT.OK = 0;
DHT.ERROR_UNKNOWN_COMMAND = UNKNOWN_COMMAND;
DHT.ERROR_INVALID_TOKEN = INVALID_TOKEN;
module.exports = DHT;
function localIP(udx, family = 4) {
let host = null;
for (const n of udx.networkInterfaces()) {
if (n.family !== family || n.internal) continue;
if (n.name === "en0") return n.host;
if (host === null) host = n.host;
}
return host || (family === 4 ? "127.0.0.1" : "::1");
}
function parseNode(s) {
if (typeof s === "object") return s;
if (typeof s === "number") return { host: "127.0.0.1", port: s };
const [host, port] = s.split(":");
if (!port) throw new Error("Bootstrap node format is host:port");
return {
host,
port: Number(port)
};
}
function randomBytes(n) {
const b = b4a.alloc(n);
sodium.randombytes_buf(b);
return b;
}
function randomOffset(n) {
return n - (Math.random() * 0.5 * n | 0);
}
function requestAll(dht, internal, command, value, nodes) {
let missing = nodes.length;
const replies = [];
return new Promise((resolve) => {
for (const node of nodes) {
const req = dht._request(
node,
false,
internal,
command,
null,
value,
null,
onsuccess,
onerror
);
if (!req) return resolve(replies);
}
function onsuccess(res) {
replies.push(res);
if (--missing === 0) resolve(replies);
}
function onerror() {
if (--missing === 0) resolve(replies);
}
});
}
function noop() {
}
}
});
// ../../node_modules/safety-catch/index.js
var require_safety_catch = __commonJS({
"../../node_modules/safety-catch/index.js"(exports, module) {
module.exports = safetyCatch;
function isActuallyUncaught(err) {
if (!err) return false;
return err instanceof TypeError || err instanceof SyntaxError || err instanceof ReferenceError || err instanceof EvalError || err instanceof RangeError || err instanceof URIError || err.code === "ERR_ASSERTION" || err.name === "AssertionError";
}
function throwErrorNT(err) {
queueMicrotask(() => {
throw err;
});
}
function safetyCatch(err) {
if (isActuallyUncaught(err)) {
throwErrorNT(err);
throw err;
}
}
}
});
// ../../node_modules/hyperdht/lib/messages.js
var require_messages = __commonJS({
"../../node_modules/hyperdht/lib/messages.js"(exports) {
var c = require_compact_encoding();
var ipv4 = {
...c.ipv4Address,
decode(state) {
const ip = c.ipv4Address.decode(state);
return {
host: ip.host,
port: ip.port
};
}
};
var ipv4Array = c.array(ipv4);
var ipv6 = {
...c.ipv6Address,
decode(state) {
const ip = c.ipv6Address.decode(state);
return {
host: ip.host,
port: ip.port
};
}
};
var ipv6Array = c.array(ipv6);
exports.handshake = {
preencode(state, m) {
state.end += 1 + 1 + (m.peerAddress ? 6 : 0) + (m.relayAddress ? 6 : 0);
c.buffer.preencode(state, m.noise);
},
encode(state, m) {
const flags = (m.peerAddress ? 1 : 0) | (m.relayAddress ? 2 : 0);
c.uint.encode(state, flags);
c.uint.encode(state, m.mode);
c.buffer.encode(state, m.noise);
if (m.peerAddress) ipv4.encode(state, m.peerAddress);
if (m.relayAddress) ipv4.encode(state, m.relayAddress);
},
decode(state) {
const flags = c.uint.decode(state);
return {
mode: c.uint.decode(state),
noise: c.buffer.decode(state),
peerAddress: flags & 1 ? ipv4.decode(state) : null,
relayAddress: flags & 2 ? ipv4.decode(state) : null
};
}
};
var relayInfo = {
preencode(state, m) {
state.end += 12;
},
encode(state, m) {
ipv4.encode(state, m.relayAddress);
ipv4.encode(state, m.peerAddress);
},
decode(state) {
return {
relayAddress: ipv4.decode(state),
peerAddress: ipv4.decode(state)
};
}
};
var relayInfoArray = c.array(relayInfo);
var holepunchInfo = {
preencode(state, m) {
c.uint.preencode(state, m.id);
relayInfoArray.preencode(state, m.relays);
},
encode(state, m) {
c.uint.encode(state, m.id);
relayInfoArray.encode(state, m.relays);
},
decode(state) {
return {
id: c.uint.decode(state),
relays: relayInfoArray.decode(state)
};
}
};
var udxInfo = {
preencode(state, m) {
state.end += 2;
c.uint.preencode(state, m.id);
c.uint.preencode(state, m.seq);
},
encode(state, m) {
c.uint.encode(state, 1);
c.uint.encode(state, m.reusableSocket ? 1 : 0);
c.uint.encode(state, m.id);
c.uint.encode(state, m.seq);
},
decode(state) {
const version = c.uint.decode(state);
const features = c.uint.decode(state);
return {
version,
reusableSocket: (features & 1) !== 0,
id: c.uint.decode(state),
seq: c.uint.decode(state)
};
}
};
var secretStreamInfo = {
preencode(state, m) {
c.uint.preencode(state, 1);
},
encode(state, m) {
c.uint.encode(state, 1);
},
decode(state) {
return {
version: c.uint.decode(state)
};
}
};
var relayThroughInfo = {
preencode(state, m) {
c.uint.preencode(state, 1);
c.uint.preencode(state, 0);
c.fixed32.preencode(state, m.publicKey);
c.fixed32.preencode(state, m.token);
},
encode(state, m) {
c.uint.encode(state, 1);
c.uint.encode(state, 0);
c.fixed32.encode(state, m.publicKey);
c.fixed32.encode(state, m.token);
},
decode(state) {
const version = c.uint.decode(state);
c.uint.decode(state);
return {
version,
publicKey: c.fixed32.decode(state),
token: c.fixed32.decode(state)
};
}
};
exports.noisePayload = {
preencode(state, m) {
state.end += 4;
if (m.holepunch) holepunchInfo.preencode(state, m.holepunch);
if (m.addresses4 && m.addresses4.length) ipv4Array.preencode(state, m.addresses4);
if (m.addresses6 && m.addresses6.length) ipv6Array.preencode(state, m.addresses6);
if (m.udx) udxInfo.preencode(state, m.udx);
if (m.secretStream) secretStreamInfo.preencode(state, m.secretStream);
if (m.relayThrough) relayThroughInfo.preencode(state, m.relayThrough);
if (m.relayAddresses) ipv4Array.preencode(state, m.relayAddresses);
},
encode(state, m) {
let flags = 0;
if (m.holepunch) flags |= 1;
if (m.addresses4 && m.addresses4.length) flags |= 2;
if (m.addresses6 && m.addresses6.length) flags |= 4;
if (m.udx) flags |= 8;
if (m.secretStream) flags |= 16;
if (m.relayThrough) flags |= 32;
if (m.relayAddresses) flags |= 64;
c.uint.encode(state, 1);
c.uint.encode(state, flags);
c.uint.encode(state, m.error);
c.uint.encode(state, m.firewall);
if (m.holepunch) holepunchInfo.encode(state, m.holepunch);
if (m.addresses4 && m.addresses4.length) ipv4Array.encode(state, m.addresses4);
if (m.addresses6 && m.addresses6.length) ipv6Array.encode(state, m.addresses6);
if (m.udx) udxInfo.encode(state, m.udx);
if (m.secretStream) secretStreamInfo.encode(state, m.secretStream);
if (m.relayThrough) relayThroughInfo.encode(state, m.relayThrough);
if (m.relayAddresses) ipv4Array.encode(state, m.relayAddresses);
},
decode(state) {
const version = c.uint.decode(state);
if (version !== 1) {
return {
version,
error: 0,
firewall: 0,
holepunch: null,
addresses4: [],
addresses6: [],
udx: null,
secretStream: null,
relayThrough: null,
relayAddresses: null
};
}
const flags = c.uint.decode(state);
return {
version,
error: c.uint.decode(state),
firewall: c.uint.decode(state),
holepunch: (flags & 1) !== 0 ? holepunchInfo.decode(state) : null,
addresses4: (flags & 2) !== 0 ? ipv4Array.decode(state) : [],
addresses6: (flags & 4) !== 0 ? ipv6Array.decode(state) : [],
udx: (flags & 8) !== 0 ? udxInfo.decode(state) : null,
secretStream: (flags & 16) !== 0 ? secretStreamInfo.decode(state) : null,
relayThrough: (flags & 32) !== 0 ? relayThroughInfo.decode(state) : null,
relayAddresses: (flags & 64) !== 0 ? ipv4Array.decode(state) : null
};
}
};
exports.holepunch = {
preencode(state, m) {
state.end += 2;
c.uint.preencode(state, m.id);
c.buffer.preencode(state, m.payload);
if (m.peerAddress) ipv4.preencode(state, m.peerAddress);
},
encode(state, m) {
const flags = m.peerAddress ? 1 : 0;
c.uint.encode(state, flags);
c.uint.encode(state, m.mode);
c.uint.encode(state, m.id);
c.buffer.encode(state, m.payload);
if (m.peerAddress) ipv4.encode(state, m.peerAddress);
},
decode(state) {
const flags = c.uint.decode(state);
return {
mode: c.uint.decode(state),
id: c.uint.decode(state),
payload: c.buffer.decode(state),
peerAddress: flags & 1 ? ipv4.decode(state) : null
};
}
};
exports.holepunchPayload = {
preencode(state, m) {
state.end += 4;
if (m.addresses) ipv4Array.preencode(state, m.addresses);
if (m.remoteAddress) state.end += 6;
if (m.token) state.end += 32;
if (m.remoteToken) state.end += 32;
},
encode(state, m) {
const flags = (m.connected ? 1 : 0) | (m.punching ? 2 : 0) | (m.addresses ? 4 : 0) | (m.remoteAddress ? 8 : 0) | (m.token ? 16 : 0) | (m.remoteToken ? 32 : 0);
c.uint.encode(state, flags);
c.uint.encode(state, m.error);
c.uint.encode(state, m.firewall);
c.uint.encode(state, m.round);
if (m.addresses) ipv4Array.encode(state, m.addresses);
if (m.remoteAddress) ipv4.encode(state, m.remoteAddress);
if (m.token) c.fixed32.encode(state, m.token);
if (m.remoteToken) c.fixed32.encode(state, m.remoteToken);
},
decode(state) {
const flags = c.uint.decode(state);
return {
error: c.uint.decode(state),
firewall: c.uint.decode(state),
round: c.uint.decode(state),
connected: (flags & 1) !== 0,
punching: (flags & 2) !== 0,
addresses: (flags & 4) !== 0 ? ipv4Array.decode(state) : null,
remoteAddress: (flags & 8) !== 0 ? ipv4.decode(state) : null,
token: (flags & 16) !== 0 ? c.fixed32.decode(state) : null,
remoteToken: (flags & 32) !== 0 ? c.fixed32.decode(state) : null
};
}
};
var peer = exports.peer = {
preencode(state, m) {
state.end += 32;
ipv4Array.preencode(state, m.relayAddresses);
},
encode(state, m) {
c.fixed32.encode(state, m.publicKey);
ipv4Array.encode(state, m.relayAddresses);
},
decode(state) {
return {
publicKey: c.fixed32.decode(state),
relayAddresses: ipv4Array.decode(state)
};
}
};
var peers = exports.peers = c.array(peer);
var rawPeers = c.array(c.raw);
exports.lookupRawReply = {
preencode(state, m) {
rawPeers.preencode(state, m.peers);
c.uint.preencode(state, m.bump);
},
encode(state, m) {
rawPeers.encode(state, m.peers);
c.uint.encode(state, m.bump);
},
decode(state) {
return {
peers: peers.decode(state),
bump: state.start < state.end ? c.uint.decode(state) : 0
};
}
};
exports.announce = {
preencode(state, m) {
state.end++;
if (m.peer) peer.preencode(state, m.peer);
if (m.refresh) state.end += 32;
if (m.signature) state.end += 64;
if (m.bump) c.uint.preencode(state, m.bump);
},
encode(state, m) {
const flags = (m.peer ? 1 : 0) | (m.refresh ? 2 : 0) | (m.signature ? 4 : 0) | (m.bump ? 8 : 0);
c.uint.encode(state, flags);
if (m.peer) peer.encode(state, m.peer);
if (m.refresh) c.fixed32.encode(state, m.refresh);
if (m.signature) c.fixed64.encode(state, m.signature);
if (m.bump) c.uint.encode(state, m.bump);
},
decode(state) {
const flags = c.uint.decode(state);
return {
peer: (flags & 1) !== 0 ? peer.decode(state) : null,
refresh: (flags & 2) !== 0 ? c.fixed32.decode(state) : null,
signature: (flags & 4) !== 0 ? c.fixed64.decode(state) : null,
bump: (flags & 8) !== 0 ? c.uint.decode(state) : 0
};
}
};
exports.mutableSignable = {
preencode(state, m) {
c.uint.preencode(state, m.seq);
c.buffer.preencode(state, m.value);
},
encode(state, m) {
c.uint.encode(state, m.seq);
c.buffer.encode(state, m.value);
},
decode(state) {
return {
seq: c.uint.decode(state),
value: c.buffer.decode(state)
};
}
};
exports.mutablePutRequest = {
preencode(state, m) {
c.fixed32.preencode(state, m.publicKey);
c.uint.preencode(state, m.seq);
c.buffer.preencode(state, m.value);
c.fixed64.preencode(state, m.signature);
},
encode(state, m) {
c.fixed32.encode(state, m.publicKey);
c.uint.encode(state, m.seq);
c.buffer.encode(state, m.value);
c.fixed64.encode(state, m.signature);
},
decode(state) {
return {
publicKey: c.fixed32.decode(state),
seq: c.uint.decode(state),
value: c.buffer.decode(state),
signature: c.fixed64.decode(state)
};
}
};
exports.mutableGetResponse = {
preencode(state, m) {
c.uint.preencode(state, m.seq);
c.buffer.preencode(state, m.value);
c.fixed64.preencode(state, m.signature);
},
encode(state, m) {
c.uint.encode(state, m.seq);
c.buffer.encode(state, m.value);
c.fixed64.encode(state, m.signature);
},
decode(state) {
return {
seq: c.uint.decode(state),
value: c.buffer.decode(state),
signature: c.fixed64.decode(state)
};
}
};
}
});
// ../../node_modules/hyperdht/lib/socket-pool.js
var require_socket_pool = __commonJS({
"../../node_modules/hyperdht/lib/socket-pool.js"(exports, module) {
var b4a = require_b4a();
var LINGER_TIME = 3e3;
module.exports = class SocketPool {
constructor(dht, host) {
this._dht = dht;
this._sockets = /* @__PURE__ */ new Map();
this._lingering = /* @__PURE__ */ new Set();
this._host = host;
this.routes = new SocketRoutes(this);
}
_onmessage(ref, data, address) {
this._dht.onmessage(ref.socket, data, address);
}
_add(ref) {
this._sockets.set(ref.socket, ref);
}
_remove(ref) {
this._sockets.delete(ref.socket);
this._lingering.delete(ref);
}
lookup(socket) {
return this._sockets.get(socket) || null;
}
setReusable(socket, bool) {
const ref = this.lookup(socket);
if (ref) ref.reusable = bool;
}
acquire() {
return new SocketRef(this);
}
async destroy() {
const closing = [];
for (const ref of this._sockets.values()) {
ref._unlinger();
closing.push(ref.socket.close());
}
await Promise.allSettled(closing);
}
};
var SocketRoutes = class {
constructor(pool) {
this._pool = pool;
this._routes = /* @__PURE__ */ new Map();
}
add(publicKey, rawStream) {
if (rawStream.socket) this._onconnect(publicKey, rawStream);
else rawStream.on("connect", this._onconnect.bind(this, publicKey, rawStream));
}
get(publicKey) {
const id = b4a.toString(publicKey, "hex");
const route = this._routes.get(id);
if (!route) return null;
return route;
}
_onconnect(publicKey, rawStream) {
const id = b4a.toString(publicKey, "hex");
const socket = rawStream.socket;
let route = this._routes.get(id);
if (!route) {
const gc = () => {
if (this._routes.get(id) === route) this._routes.delete(id);
socket.removeListener("close", gc);
};
route = {
socket,
address: { host: rawStream.remoteHost, port: rawStream.remotePort },
gc
};
this._routes.set(id, route);
socket.on("close", gc);
}
this._pool.setReusable(socket, true);
rawStream.on("error", () => {
this._pool.setReusable(socket, false);
if (!route) route = this._routes.get(id);
if (route && route.socket === socket) route.gc();
});
}
};
var SocketRef = class {
constructor(pool) {
this._pool = pool;
this.onholepunchmessage = noop;
this.reusable = false;
this.socket = pool._dht.udx.createSocket();
this.socket.on("close", this._onclose.bind(this)).on("message", this._onmessage.bind(this)).on("idle", this._onidle.bind(this)).on("busy", this._onbusy.bind(this)).bind(0, this._pool._host);
this._refs = 1;
this._released = false;
this._closed = false;
this._timeout = null;
this._wasBusy = false;
this._pool._add(this);
}
_onclose() {
this._pool._remove(this);
}
_onmessage(data, address) {
if (data.byteLength > 1) {
this._pool._onmessage(this, data, address);
} else {
this.onholepunchmessage(data, address, this);
}
}
_onidle() {
this._closeMaybe();
}
_onbusy() {
this._wasBusy = true;
this._unlinger();
}
_reset() {
this.onholepunchmessage = noop;
}
_closeMaybe() {
if (this._refs === 0 && this.socket.idle && !this._timeout) this._close();
}
_lingeringClose() {
this._pool._lingering.delete(this);
this._timeout = null;
this._closeMaybe();
}
_close() {
this._unlinger();
if (this.reusable && this._wasBusy) {
this._wasBusy = false;
this._pool._lingering.add(this);
this._timeout = setTimeout(this._lingeringClose.bind(this), LINGER_TIME);
return;
}
this._closed = true;
this.socket.close();
}
_unlinger() {
if (this._timeout !== null) {
clearTimeout(this._timeout);
this._pool._lingering.delete(this);
this._timeout = null;
}
}
get free() {
return this._refs === 0;
}
active() {
this._refs++;
this._unlinger();
}
inactive() {
this._refs--;
this._closeMaybe();
}
address() {
return this.socket.address();
}
release() {
if (this._released) return;
this._released = true;
this._reset();
this._refs--;
this._closeMaybe();
}
};
function noop() {
}
}
});
// ../../node_modules/record-cache/index.js
var require_record_cache = __commonJS({
"../../node_modules/record-cache/index.js"(exports, module) {
var b4a = require_b4a();
var EMPTY = [];
module.exports = RecordCache;
function RecordSet() {
this.list = [];
this.map = /* @__PURE__ */ new Map();
}
RecordSet.prototype.add = function(record, value) {
var k = toString(record);
var r = this.map.get(k);
if (r) return false;
r = { index: this.list.length, record: value || record };
this.list.push(r);
this.map.set(k, r);
return true;
};
RecordSet.prototype.remove = function(record) {
var k = toString(record);
var r = this.map.get(k);
if (!r) return false;
swap(this.list, r.index, this.list.length - 1);
this.list.pop();
this.map.delete(k);
return true;
};
function RecordStore() {
this.records = /* @__PURE__ */ new Map();
this.size = 0;
}
RecordStore.prototype.add = function(name, record, value) {
var r = this.records.get(name);
if (!r) {
r = new RecordSet();
this.records.set(name, r);
}
if (r.add(record, value)) {
this.size++;
return true;
}
return false;
};
RecordStore.prototype.remove = function(name, record, value) {
var r = this.records.get(name);
if (!r) return false;
if (r.remove(record, value)) {
this.size--;
if (!r.map.size) this.records.delete(name);
return true;
}
return false;
};
RecordStore.prototype.get = function(name) {
var r = this.records.get(name);
return r ? r.list : EMPTY;
};
function RecordCache(opts) {
if (!(this instanceof RecordCache)) return new RecordCache(opts);
if (!opts) opts = {};
this.maxSize = opts.maxSize || Infinity;
this.maxAge = opts.maxAge || 0;
this._onstale = opts.onStale || opts.onstale || null;
this._fresh = new RecordStore();
this._stale = new RecordStore();
this._interval = null;
this._gced = false;
if (this.maxAge && this.maxAge < Infinity) {
var tick = Math.ceil(2 / 3 * this.maxAge);
this._interval = setInterval(this._gcAuto.bind(this), tick);
if (this._interval.unref) this._interval.unref();
}
}
Object.defineProperty(RecordCache.prototype, "size", {
get: function() {
return this._fresh.size + this._stale.size;
}
});
RecordCache.prototype.add = function(name, record, value) {
this._stale.remove(name, record, value);
if (this._fresh.add(name, record, value) && this._fresh.size > this.maxSize) {
this._gc();
}
};
RecordCache.prototype.remove = function(name, record, value) {
this._fresh.remove(name, record, value);
this._stale.remove(name, record, value);
};
RecordCache.prototype.get = function(name, n) {
var a = this._fresh.get(name);
var b = this._stale.get(name);
var aLen = a.length;
var bLen = b.length;
var len = aLen + bLen;
if (n > len || !n) n = len;
var result = new Array(n);
for (var i = 0; i < n; i++) {
var j = Math.floor(Math.random() * (aLen + bLen));
if (j < aLen) {
result[i] = a[j].record;
swap(a, j, --aLen);
} else {
j -= aLen;
result[i] = b[j].record;
swap(b, j, --bLen);
}
}
return result;
};
RecordCache.prototype._gcAuto = function() {
if (!this._gced) this._gc();
this._gced = false;
};
RecordCache.prototype._gc = function() {
if (this._onstale && this._stale.size > 0) this._onstale(this._stale);
this._stale = this._fresh;
this._fresh = new RecordStore();
this._gced = true;
};
RecordCache.prototype.clear = function() {
this._gc();
this._gc();
};
RecordCache.prototype.destroy = function() {
this.clear();
clearInterval(this._interval);
this._interval = null;
};
function toString(record) {
return b4a.isBuffer(record) ? b4a.toString(record, "hex") : record;
}
function swap(list, a, b) {
var tmp = list[a];
tmp.index = b;
list[b].index = a;
list[a] = list[b];
list[b] = tmp;
}
}
});
// ../../node_modules/unslab/index.js
var require_unslab = __commonJS({
"../../node_modules/unslab/index.js"(exports, module) {
var b4a = require_b4a();
unslab.all = all;
unslab.is = is;
module.exports = unslab;
function unslab(buf) {
if (buf === null || buf.buffer.byteLength === buf.byteLength) return buf;
const copy = b4a.allocUnsafeSlow(buf.byteLength);
copy.set(buf, 0);
return copy;
}
function is(buf) {
return buf.buffer.byteLength !== buf.byteLength;
}
function all(list) {
let size = 0;
for (let i = 0; i < list.length; i++) {
const buf = list[i];
size += buf === null || buf.buffer.byteLength === buf.byteLength ? 0 : buf.byteLength;
}
const copy = b4a.allocUnsafeSlow(size);
const result = new Array(list.length);
let offset = 0;
for (let i = 0; i < list.length; i++) {
let buf = list[i];
if (buf !== null && buf.buffer.byteLength !== buf.byteLength) {
copy.set(buf, offset);
buf = copy.subarray(offset, offset += buf.byteLength);
}
result[i] = buf;
}
return result;
}
}
});
// ../../node_modules/hyperdht/lib/encode.js
var require_encode = __commonJS({
"../../node_modules/hyperdht/lib/encode.js"(exports, module) {
var b4a = require_b4a();
var cenc = require_compact_encoding();
function encodeUnslab(enc, m) {
const state = cenc.state();
enc.preencode(state, m);
state.buffer = b4a.allocUnsafeSlow(state.end);
enc.encode(state, m);
return state.buffer;
}
module.exports = {
encodeUnslab
};
}
});
// ../../node_modules/hypercore-crypto/index.js
var require_hypercore_crypto = __commonJS({
"../../node_modules/hypercore-crypto/index.js"(exports) {
var sodium = require_sodium_universal();
var c = require_compact_encoding();
var b4a = require_b4a();
var LEAF_TYPE = b4a.from([0]);
var PARENT_TYPE = b4a.from([1]);
var ROOT_TYPE = b4a.from([2]);
var HYPERCORE = b4a.from("hypercore");
exports.keyPair = function(seed) {
const slab = b4a.allocUnsafeSlow(sodium.crypto_sign_PUBLICKEYBYTES + sodium.crypto_sign_SECRETKEYBYTES);
const publicKey = slab.subarray(0, sodium.crypto_sign_PUBLICKEYBYTES);
const secretKey = slab.subarray(sodium.crypto_sign_PUBLICKEYBYTES);
if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed);
else sodium.crypto_sign_keypair(publicKey, secretKey);
return {
publicKey,
secretKey
};
};
exports.validateKeyPair = function(keyPair) {
const pk = b4a.allocUnsafe(sodium.crypto_sign_PUBLICKEYBYTES);
sodium.crypto_sign_ed25519_sk_to_pk(pk, keyPair.secretKey);
return b4a.equals(pk, keyPair.publicKey);
};
exports.sign = function(message, secretKey) {
const signature = b4a.allocUnsafeSlow(sodium.crypto_sign_BYTES);
sodium.crypto_sign_detached(signature, message, secretKey);
return signature;
};
exports.verify = function(message, signature, publicKey) {
if (signature.byteLength !== sodium.crypto_sign_BYTES) return false;
if (publicKey.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) return false;
return sodium.crypto_sign_verify_detached(signature, message, publicKey);
};
exports.encrypt = function(message, publicKey) {
const ciphertext = b4a.alloc(message.byteLength + sodium.crypto_box_SEALBYTES);
sodium.crypto_box_seal(ciphertext, message, publicKey);
return ciphertext;
};
exports.decrypt = function(ciphertext, keyPair) {
if (ciphertext.byteLength < sodium.crypto_box_SEALBYTES) return null;
const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_box_SEALBYTES);
if (!sodium.crypto_box_seal_open(plaintext, ciphertext, keyPair.publicKey, keyPair.secretKey)) {
return null;
}
return plaintext;
};
exports.encryptionKeyPair = function(seed) {
const publicKey = b4a.alloc(sodium.crypto_box_PUBLICKEYBYTES);
const secretKey = b4a.alloc(sodium.crypto_box_SECRETKEYBYTES);
if (seed) {
sodium.crypto_box_seed_keypair(publicKey, secretKey, seed);
} else {
sodium.crypto_box_keypair(publicKey, secretKey);
}
return {
publicKey,
secretKey
};
};
exports.data = function(data) {
const out = b4a.allocUnsafe(32);
sodium.crypto_generichash_batch(out, [
LEAF_TYPE,
c.encode(c.uint64, data.byteLength),
data
]);
return out;
};
exports.parent = function(a, b) {
if (a.index > b.index) {
const tmp = a;
a = b;
b = tmp;
}
const out = b4a.allocUnsafe(32);
sodium.crypto_generichash_batch(out, [
PARENT_TYPE,
c.encode(c.uint64, a.size + b.size),
a.hash,
b.hash
]);
return out;
};
exports.tree = function(roots, out) {
const buffers = new Array(3 * roots.length + 1);
let j = 0;
buffers[j++] = ROOT_TYPE;
for (let i = 0; i < roots.length; i++) {
const r = roots[i];
buffers[j++] = r.hash;
buffers[j++] = c.encode(c.uint64, r.index);
buffers[j++] = c.encode(c.uint64, r.size);
}
if (!out) out = b4a.allocUnsafe(32);
sodium.crypto_generichash_batch(out, buffers);
return out;
};
exports.hash = function(data, out) {
if (!out) out = b4a.allocUnsafe(32);
if (!Array.isArray(data)) data = [data];
sodium.crypto_generichash_batch(out, data);
return out;
};
exports.randomBytes = function(n) {
const buf = b4a.allocUnsafe(n);
sodium.randombytes_buf(buf);
return buf;
};
exports.discoveryKey = function(key) {
if (!key || key.byteLength !== 32) throw new Error("Must pass a 32 byte buffer");
const digest = b4a.allocUnsafeSlow(32);
sodium.crypto_generichash(digest, HYPERCORE, key);
return digest;
};
if (sodium.sodium_free) {
exports.free = function(secureBuf) {
if (secureBuf.secure) sodium.sodium_free(secureBuf);
};
} else {
exports.free = function() {
};
}
exports.namespace = function(name, count) {
const ids = typeof count === "number" ? range(count) : count;
const buf = b4a.allocUnsafeSlow(32 * ids.length);
const list = new Array(ids.length);
const ns = b4a.allocUnsafe(33);
sodium.crypto_generichash(ns.subarray(0, 32), typeof name === "string" ? b4a.from(name) : name);
for (let i = 0; i < list.length; i++) {
list[i] = buf.subarray(32 * i, 32 * i + 32);
ns[32] = ids[i];
sodium.crypto_generichash(list[i], ns);
}
return list;
};
function range(count) {
const arr = new Array(count);
for (let i = 0; i < count; i++) arr[i] = i;
return arr;
}
}
});
// ../../node_modules/hyperdht/lib/constants.js
var require_constants5 = __commonJS({
"../../node_modules/hyperdht/lib/constants.js"(exports) {
var crypto = require_hypercore_crypto();
var COMMANDS = exports.COMMANDS = {
PEER_HANDSHAKE: 0,
PEER_HOLEPUNCH: 1,
FIND_PEER: 2,
LOOKUP: 3,
ANNOUNCE: 4,
UNANNOUNCE: 5,
MUTABLE_PUT: 6,
MUTABLE_GET: 7,
IMMUTABLE_PUT: 8,
IMMUTABLE_GET: 9
};
exports.BOOTSTRAP_NODES = global.Pear?.config.dht?.bootstrap || [
"[email protected]:49737",
"[email protected]:49737",
"[email protected]:49737"
];
exports.KNOWN_NODES = global.Pear?.config.dht?.nodes || [];
exports.FIREWALL = {
UNKNOWN: 0,
OPEN: 1,
CONSISTENT: 2,
RANDOM: 3
};
exports.ERROR = {
// noise / connection related
NONE: 0,
ABORTED: 1,
VERSION_MISMATCH: 2,
TRY_LATER: 3,
// dht related
SEQ_REUSED: 16,
SEQ_TOO_LOW: 17
};
var [NS_ANNOUNCE, NS_UNANNOUNCE, NS_MUTABLE_PUT, NS_PEER_HANDSHAKE, NS_PEER_HOLEPUNCH] = crypto.namespace("hyperswarm/dht", [
COMMANDS.ANNOUNCE,
COMMANDS.UNANNOUNCE,
COMMANDS.MUTABLE_PUT,
COMMANDS.PEER_HANDSHAKE,
COMMANDS.PEER_HOLEPUNCH
]);
exports.NS = {
ANNOUNCE: NS_ANNOUNCE,
UNANNOUNCE: NS_UNANNOUNCE,
MUTABLE_PUT: NS_MUTABLE_PUT,
PEER_HANDSHAKE: NS_PEER_HANDSHAKE,
PEER_HOLEPUNCH: NS_PEER_HOLEPUNCH
};
}
});
// ../../node_modules/hyperdht/lib/persistent.js
var require_persistent = __commonJS({
"../../node_modules/hyperdht/lib/persistent.js"(exports, module) {
var c = require_compact_encoding();
var sodium = require_sodium_universal();
var RecordCache = require_record_cache();
var Cache = require_xache();
var b4a = require_b4a();
var unslab = require_unslab();
var { encodeUnslab } = require_encode();
var m = require_messages();
var { NS, ERROR } = require_constants5();
var EMPTY = b4a.alloc(0);
var TMP = b4a.allocUnsafe(32);
var MAX_BUMP_DRIFT = 6e4;
module.exports = class Persistent {
constructor(dht, opts) {
this.dht = dht;
this.records = new RecordCache(opts.records);
this.bumps = new Cache(opts.bumps);
this.refreshes = new Cache(opts.refreshes);
this.mutables = new Cache(opts.mutables);
this.immutables = new Cache(opts.immutables);
}
onlookup(req) {
if (!req.target) return;
const k = b4a.toString(req.target, "hex");
const records = this.records.get(k, 20);
const bump = this.bumps.get(k) || 0;
const fwd = this.dht._router.get(k);
if (fwd && records.length < 20) records.push(fwd.record);
req.reply(records.length ? c.encode(m.lookupRawReply, { peers: records, bump }) : null);
}
onfindpeer(req) {
if (!req.target) return;
const fwd = this.dht._router.get(req.target);
req.reply(fwd ? fwd.record : null);
}
unannounce(target, publicKey) {
const k = b4a.toString(target, "hex");
sodium.crypto_generichash(TMP, publicKey);
if (b4a.equals(TMP, target)) this.dht._router.delete(k);
this.records.remove(k, publicKey);
}
onunannounce(req) {
if (!req.target || !req.token) return;
const unann = decode(m.announce, req.value);
if (unann === null) return;
const { peer, signature } = unann;
if (!peer || !signature) return;
const signable = annSignable(req.target, req.token, this.dht.id, unann, NS.UNANNOUNCE);
if (!sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
return;
}
this.unannounce(req.target, peer.publicKey);
req.reply(null, { token: false, closerNodes: false });
}
_onrefresh(token, req) {
sodium.crypto_generichash(TMP, token);
const activeRefresh = b4a.toString(TMP, "hex");
const r = this.refreshes.get(activeRefresh);
if (!r) return;
const { announceSelf, k, record } = r;
const publicKey = record.subarray(0, 32);
if (announceSelf) {
this.dht._router.set(k, {
relay: req.from,
record,
onconnect: null,
onholepunch: null
});
this.records.remove(k, publicKey);
} else {
this.records.add(k, publicKey, record);
}
this.refreshes.delete(activeRefresh);
this.refreshes.set(b4a.toString(token, "hex"), r);
req.reply(null, { token: false, closerNodes: false });
}
onannounce(req) {
if (!req.target || !req.token || !this.dht.id) return;
const ann = decode(m.announce, req.value);
if (ann === null) return;
const { peer, refresh, signature, bump } = ann;
if (!peer) {
if (!refresh) return;
this._onrefresh(refresh, req);
return;
}
const signable = annSignable(req.target, req.token, this.dht.id, ann, NS.ANNOUNCE);
if (!signature || !sodium.crypto_sign_verify_detached(signature, signable, peer.publicKey)) {
return;
}
if (peer.relayAddresses.length > 3) {
peer.relayAddresses = peer.relayAddresses.slice(0, 3);
}
sodium.crypto_generichash(TMP, peer.publicKey);
const k = b4a.toString(req.target, "hex");
const announceSelf = b4a.equals(TMP, req.target);
const record = encodeUnslab(m.peer, peer);
if (announceSelf) {
this.dht._router.set(k, {
relay: req.from,
record,
onconnect: null,
onholepunch: null
});
this.records.remove(k, peer.publicKey);
} else {
const currentBump = this.bumps.get(k) || 0;
if (bump > currentBump && bump <= Date.now() + MAX_BUMP_DRIFT) this.bumps.set(k, bump);
this.records.add(k, peer.publicKey, record);
}
if (refresh) {
this.refreshes.set(b4a.toString(refresh, "hex"), { k, record, announceSelf });
}
req.reply(null, { token: false, closerNodes: false });
}
onmutableget(req) {
if (!req.target || !req.value) return;
let seq = 0;
try {
seq = c.decode(c.uint, req.value);
} catch {
return;
}
const k = b4a.toString(req.target, "hex");
const value = this.mutables.get(k);
if (!value) {
req.reply(null);
return;
}
const localSeq = c.decode(c.uint, value);
req.reply(localSeq < seq ? null : value);
}
onmutableput(req) {
if (!req.target || !req.token || !req.value) return;
const p = decode(m.mutablePutRequest, req.value);
if (!p) return;
const { publicKey, seq, value, signature } = p;
const hash = b4a.allocUnsafe(32);
sodium.crypto_generichash(hash, publicKey);
if (!b4a.equals(hash, req.target)) return;
if (!value || !verifyMutable(signature, seq, value, publicKey)) return;
const k = b4a.toString(hash, "hex");
const local = this.mutables.get(k);
if (local) {
const existing = c.decode(m.mutableGetResponse, local);
if (existing.value && existing.seq === seq && b4a.compare(value, existing.value) !== 0) {
req.error(ERROR.SEQ_REUSED);
return;
}
if (seq < existing.seq) {
req.error(ERROR.SEQ_TOO_LOW);
return;
}
}
this.mutables.set(k, encodeUnslab(m.mutableGetResponse, { seq, value, signature }));
req.reply(null);
}
onimmutableget(req) {
if (!req.target) return;
const k = b4a.toString(req.target, "hex");
const value = this.immutables.get(k);
req.reply(value || null);
}
onimmutableput(req) {
if (!req.target || !req.token || !req.value) return;
const hash = b4a.alloc(32);
sodium.crypto_generichash(hash, req.value);
if (!b4a.equals(hash, req.target)) return;
const k = b4a.toString(hash, "hex");
this.immutables.set(k, unslab(req.value));
req.reply(null);
}
destroy() {
this.records.destroy();
this.refreshes.destroy();
this.mutables.destroy();
this.immutables.destroy();
}
static signMutable(seq, value, keyPair) {
const signable = b4a.allocUnsafe(32 + 32);
const hash = signable.subarray(32);
signable.set(NS.MUTABLE_PUT, 0);
sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }));
return sign(signable, keyPair);
}
static verifyMutable(signature, seq, value, publicKey) {
return verifyMutable(signature, seq, value, publicKey);
}
static signAnnounce(target, token, id, ann, keyPair) {
return sign(annSignable(target, token, id, ann, NS.ANNOUNCE), keyPair);
}
static signUnannounce(target, token, id, ann, keyPair) {
return sign(annSignable(target, token, id, ann, NS.UNANNOUNCE), keyPair);
}
};
function verifyMutable(signature, seq, value, publicKey) {
const signable = b4a.allocUnsafe(32 + 32);
const hash = signable.subarray(32);
signable.set(NS.MUTABLE_PUT, 0);
sodium.crypto_generichash(hash, c.encode(m.mutableSignable, { seq, value }));
return sodium.crypto_sign_verify_detached(signature, signable, publicKey);
}
function annSignable(target, token, id, ann, ns) {
const signable = b4a.allocUnsafe(32 + 32);
const hash = signable.subarray(32);
signable.set(ns, 0);
sodium.crypto_generichash_batch(hash, [
target,
id,
token,
c.encode(m.peer, ann.peer),
// note that this is the partial encoding of the announce message so we could just use that for perf
ann.refresh || EMPTY
]);
return signable;
}
function sign(signable, keyPair) {
if (keyPair.sign) {
return keyPair.sign(signable);
}
const secretKey = keyPair.secretKey ? keyPair.secretKey : keyPair;
const signature = b4a.allocUnsafe(64);
sodium.crypto_sign_detached(signature, signable, secretKey);
return signature;
}
function decode(enc, val) {
try {
return val && c.decode(enc, val);
} catch (err) {
return null;
}
}
}
});
// ../../node_modules/hyperdht/lib/errors.js
var require_errors9 = __commonJS({
"../../node_modules/hyperdht/lib/errors.js"(exports, module) {
module.exports = class DHTError extends Error {
constructor(msg, code, fn = DHTError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "DHTError";
}
static BAD_HANDSHAKE_REPLY(msg = "Bad handshake reply") {
return new DHTError(msg, "BAD_HANDSHAKE_REPLY", DHTError.BAD_HANDSHAKE_REPLY);
}
static BAD_HOLEPUNCH_REPLY(msg = "Bad holepunch reply") {
return new DHTError(msg, "BAD_HOLEPUNCH_REPLY", DHTError.BAD_HOLEPUNCH_REPLY);
}
static HOLEPUNCH_ABORTED(msg = "Holepunch aborted") {
return new DHTError(msg, "HOLEPUNCH_ABORTED", DHTError.HOLEPUNCH_ABORTED);
}
static HOLEPUNCH_INVALID(msg = "Invalid holepunch payload") {
return new DHTError(msg, "HOLEPUNCH_INVALID", DHTError.HOLEPUNCH_INVALID);
}
static HOLEPUNCH_PROBE_TIMEOUT(msg = "Holepunching probe did not finish in time") {
return new DHTError(msg, "HOLEPUNCH_PROBE_TIMEOUT", DHTError.HOLEPUNCH_PROBE_TIMEOUT);
}
static HOLEPUNCH_DOUBLE_RANDOMIZED_NATS(msg = "Both remote and local NATs are randomized") {
return new DHTError(
msg,
"HOLEPUNCH_DOUBLE_RANDOMIZED_NATS",
DHTError.HOLEPUNCH_DOUBLE_RANDOMIZED_NATS
);
}
static CANNOT_HOLEPUNCH(msg = "Cannot holepunch to remote") {
return new DHTError(msg, "CANNOT_HOLEPUNCH", DHTError.CANNOT_HOLEPUNCH);
}
static REMOTE_NOT_HOLEPUNCHING(msg = "Remote is not holepunching") {
return new DHTError(msg, "REMOTE_NOT_HOLEPUNCHING", DHTError.REMOTE_NOT_HOLEPUNCHING);
}
static REMOTE_NOT_HOLEPUNCHABLE(msg = "Remote is not holepunchable") {
return new DHTError(msg, "REMOTE_NOT_HOLEPUNCHABLE", DHTError.REMOTE_NOT_HOLEPUNCHABLE);
}
static REMOTE_ABORTED(msg = "Remote aborted") {
return new DHTError(msg, "REMOTE_ABORTED", DHTError.REMOTE_ABORTED);
}
static HANDSHAKE_UNFINISHED(msg = "Handshake did not finish") {
return new DHTError(msg, "HANDSHAKE_UNFINISHED", DHTError.HANDSHAKE_UNFINISHED);
}
static HANDSHAKE_INVALID(msg = "Received invalid handshake") {
return new DHTError(msg, "HANDSHAKE_INVALID", DHTError.HANDSHAKE_INVALID);
}
static ALREADY_LISTENING(msg = "Already listening") {
return new DHTError(msg, "ALREADY_LISTENING", DHTError.ALREADY_LISTENING);
}
static KEYPAIR_ALREADY_USED(msg = "Keypair already used") {
return new DHTError(msg, "KEYPAIR_ALREADY_USED", DHTError.KEYPAIR_ALREADY_USED);
}
static NODE_DESTROYED(msg = "Node destroyed") {
return new DHTError(msg, "NODE_DESTROYED", DHTError.NODE_DESTROYED);
}
static PEER_CONNECTION_FAILED(msg = "Could not connect to peer") {
return new DHTError(msg, "PEER_CONNECTION_FAILED", DHTError.PEER_CONNECTION_FAILED);
}
static PEER_NOT_FOUND(msg = "Peer not found") {
return new DHTError(msg, "PEER_NOT_FOUND", DHTError.PEER_NOT_FOUND);
}
static STREAM_NOT_CONNECTED(msg = "Stream is not connected") {
return new DHTError(msg, "STREAM_NOT_CONNECTED", DHTError.STREAM_DISCONNECTED);
}
static SERVER_INCOMPATIBLE(msg = "Server is using an incompatible version") {
return new DHTError(msg, "SERVER_INCOMPATIBLE", DHTError.SERVER_INCOMPATIBLE);
}
static SERVER_ERROR(msg = "Server returned an error") {
return new DHTError(msg, "SERVER_ERROR", DHTError.SERVER_ERROR);
}
static DUPLICATE_CONNECTION(msg = "Duplicate connection") {
return new DHTError(msg, "DUPLICATE_CONNECTION", DHTError.DUPLICATE_CONNECTION);
}
static RELAY_ABORTED(msg = "Relay aborted") {
return new DHTError(msg, "RELAY_ABORTED", DHTError.RELAY_ABORTED);
}
static SUSPENDED(msg = "Suspended") {
return new DHTError(msg, "SUSPENDED", DHTError.SUSPENDED);
}
};
}
});
// ../../node_modules/hyperdht/lib/router.js
var require_router = __commonJS({
"../../node_modules/hyperdht/lib/router.js"(exports, module) {
var c = require_compact_encoding();
var Cache = require_xache();
var safetyCatch = require_safety_catch();
var b4a = require_b4a();
var { handshake, holepunch } = require_messages();
var { COMMANDS } = require_constants5();
var { BAD_HANDSHAKE_REPLY, BAD_HOLEPUNCH_REPLY } = require_errors9();
var FROM_CLIENT = 0;
var FROM_SERVER = 1;
var FROM_RELAY = 2;
var FROM_SECOND_RELAY = 3;
var REPLY = 4;
module.exports = class Router {
constructor(dht, opts) {
this.dht = dht;
this.forwards = new Cache(opts.forwards);
}
set(target, state) {
if (state.onpeerhandshake) {
this.forwards.retain(toString(target), state);
} else {
this.forwards.set(toString(target), state);
}
}
get(target) {
return this.forwards.get(toString(target));
}
delete(target) {
this.forwards.delete(toString(target));
}
destroy() {
this.forwards.destroy();
}
async peerHandshake(target, { noise, peerAddress, relayAddress, socket, session }, to) {
const dht = this.dht;
const requestValue = c.encode(handshake, {
mode: FROM_CLIENT,
noise,
peerAddress,
relayAddress
});
const res = await dht.request(
{ command: COMMANDS.PEER_HANDSHAKE, target, value: requestValue },
to,
{ socket, session }
);
const hs = decode(handshake, res.value);
if (!hs || hs.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port || !hs.noise) {
throw BAD_HANDSHAKE_REPLY();
}
return {
noise: hs.noise,
relayed: !!hs.peerAddress,
serverAddress: hs.peerAddress || to,
clientAddress: res.to
};
}
async onpeerhandshake(req) {
const hs = req.value && decode(handshake, req.value);
if (!hs) return;
const { mode, noise, peerAddress, relayAddress } = hs;
const state = req.target && this.get(req.target);
const isServer = !!(state && state.onpeerhandshake);
const relay = state && state.relay;
if (isServer) {
let reply = null;
try {
reply = noise && await state.onpeerhandshake({ noise, peerAddress }, req);
} catch (e) {
safetyCatch(e);
return;
}
if (!reply || !reply.noise) return;
const opts = { socket: reply.socket, closerNodes: false, token: false };
switch (mode) {
case FROM_CLIENT: {
req.reply(
c.encode(handshake, { mode: REPLY, noise: reply.noise, peerAddress: null }),
opts
);
return;
}
case FROM_RELAY: {
req.relay(
c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
req.from,
opts
);
return;
}
case FROM_SECOND_RELAY: {
if (!relayAddress) return;
req.relay(
c.encode(handshake, { mode: FROM_SERVER, noise: reply.noise, peerAddress }),
relayAddress,
opts
);
return;
}
}
} else {
switch (mode) {
case FROM_CLIENT: {
if (!noise) return;
if (!relay && !relayAddress) {
req.reply(null, { token: false, closerNodes: true });
return;
}
req.relay(
c.encode(handshake, {
mode: FROM_RELAY,
noise,
peerAddress: req.from,
relayAddress: null
}),
relayAddress || relay
);
return;
}
case FROM_RELAY: {
if (!relay || !noise) return;
req.relay(
c.encode(handshake, {
mode: FROM_SECOND_RELAY,
noise,
peerAddress,
relayAddress: req.from
}),
relay
);
return;
}
case FROM_SERVER: {
if (!peerAddress || !noise) return;
req.reply(
c.encode(handshake, { mode: REPLY, noise, peerAddress: req.from, relayAddress: null }),
{ to: peerAddress, closerNodes: false, token: false }
);
return;
}
}
}
}
async peerHolepunch(target, { id, payload, peerAddress, socket, session }, to) {
const dht = this.dht;
const requestValue = c.encode(holepunch, {
mode: FROM_CLIENT,
id,
payload,
peerAddress
});
const res = await dht.request(
{ command: COMMANDS.PEER_HOLEPUNCH, target, value: requestValue },
to,
{ socket, session }
);
const hp = decode(holepunch, res.value);
if (!hp || hp.mode !== REPLY || to.host !== res.from.host || to.port !== res.from.port) {
throw BAD_HOLEPUNCH_REPLY();
}
return {
from: res.from,
to: res.to,
payload: hp.payload,
peerAddress: hp.peerAddress || to
};
}
async onpeerholepunch(req) {
const hp = req.value && decode(holepunch, req.value);
if (!hp) return;
const { mode, id, payload, peerAddress } = hp;
const state = req.target && this.get(req.target);
const isServer = !!(state && state.onpeerholepunch);
const relay = state && state.relay;
switch (mode) {
case FROM_CLIENT: {
if (!peerAddress && !relay) return;
req.relay(
c.encode(holepunch, { mode: FROM_RELAY, id, payload, peerAddress: req.from }),
peerAddress || relay
);
return;
}
case FROM_RELAY: {
if (!isServer || !peerAddress) return;
let reply = null;
try {
reply = await state.onpeerholepunch({ id, payload, peerAddress }, req);
} catch (e) {
safetyCatch(e);
return;
}
if (!reply) return;
const opts = { socket: reply.socket, closerNodes: false, token: false };
req.relay(
c.encode(holepunch, { mode: FROM_SERVER, id: 0, payload: reply.payload, peerAddress }),
req.from,
opts
);
return;
}
case FROM_SERVER: {
req.reply(c.encode(holepunch, { mode: REPLY, id, payload, peerAddress: req.from }), {
to: peerAddress,
closerNodes: false,
token: false
});
return;
}
}
}
};
function decode(enc, val) {
try {
return c.decode(enc, val);
} catch {
return null;
}
}
function toString(t) {
return typeof t === "string" ? t : b4a.toString(t, "hex");
}
}
});
// ../../node_modules/sodium-secretstream/index.js
var require_sodium_secretstream = __commonJS({
"../../node_modules/sodium-secretstream/index.js"(exports, module) {
var sodium = require_sodium_universal();
var b4a = require_b4a();
var ABYTES = sodium.crypto_secretstream_xchacha20poly1305_ABYTES;
var TAG_MESSAGE = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;
var TAG_FINAL = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL;
var STATEBYTES = sodium.crypto_secretstream_xchacha20poly1305_STATEBYTES;
var HEADERBYTES = sodium.crypto_secretstream_xchacha20poly1305_HEADERBYTES;
var KEYBYTES = sodium.crypto_secretstream_xchacha20poly1305_KEYBYTES;
var TAG_FINAL_BYTE = b4a.isBuffer(TAG_FINAL) ? TAG_FINAL[0] : TAG_FINAL;
var EMPTY = b4a.alloc(0);
var TAG = b4a.alloc(1);
var Push = class {
constructor(key, state = b4a.allocUnsafeSlow(STATEBYTES), header = b4a.allocUnsafeSlow(HEADERBYTES)) {
if (!TAG_FINAL) throw new Error("JavaScript sodium version needs to support crypto_secretstream_xchacha20poly");
this.key = key;
this.state = state;
this.header = header;
sodium.crypto_secretstream_xchacha20poly1305_init_push(this.state, this.header, this.key);
}
next(message, cipher = b4a.allocUnsafe(message.byteLength + ABYTES)) {
sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_MESSAGE);
return cipher;
}
final(message = EMPTY, cipher = b4a.allocUnsafe(ABYTES)) {
sodium.crypto_secretstream_xchacha20poly1305_push(this.state, cipher, message, null, TAG_FINAL);
return cipher;
}
};
var Pull = class {
constructor(key, state = b4a.allocUnsafeSlow(STATEBYTES)) {
if (!TAG_FINAL) throw new Error("JavaScript sodium version needs to support crypto_secretstream_xchacha20poly");
this.key = key;
this.state = state;
this.final = false;
}
init(header) {
sodium.crypto_secretstream_xchacha20poly1305_init_pull(this.state, header, this.key);
}
next(cipher, message = b4a.allocUnsafe(cipher.byteLength - ABYTES)) {
sodium.crypto_secretstream_xchacha20poly1305_pull(this.state, message, TAG, cipher, null);
this.final = TAG[0] === TAG_FINAL_BYTE;
return message;
}
};
function keygen(buf = b4a.alloc(KEYBYTES)) {
sodium.crypto_secretstream_xchacha20poly1305_keygen(buf);
return buf;
}
module.exports = {
keygen,
KEYBYTES,
ABYTES,
STATEBYTES,
HEADERBYTES,
Push,
Pull
};
}
});
// ../../node_modules/timeout-refresh/node.js
var require_node2 = __commonJS({
"../../node_modules/timeout-refresh/node.js"(exports, module) {
module.exports = class Timer {
constructor(ms, fn, ctx = null, interval = false) {
this.ms = ms;
this.ontimeout = fn;
this.context = ctx;
this.interval = interval;
this.done = false;
this._timer = interval ? setInterval(callInterval, ms, this) : setTimeout(callTimeout, ms, this);
}
unref() {
this._timer.unref();
}
ref() {
this._timer.ref();
}
refresh() {
if (this.done !== true) this._timer.refresh();
}
destroy() {
this.done = true;
this.ontimeout = null;
if (this.interval) clearInterval(this._timer);
else clearTimeout(this._timer);
}
static once(ms, fn, ctx) {
return new this(ms, fn, ctx, false);
}
static on(ms, fn, ctx) {
return new this(ms, fn, ctx, true);
}
};
function callTimeout(self) {
self.done = true;
self.ontimeout.call(self.context);
}
function callInterval(self) {
self.ontimeout.call(self.context);
}
}
});
// ../../node_modules/timeout-refresh/browser.js
var require_browser = __commonJS({
"../../node_modules/timeout-refresh/browser.js"(exports, module) {
module.exports = class TimerBrowser {
constructor(ms, fn, ctx = null, interval = false) {
this.ms = ms;
this.ontimeout = fn;
this.context = ctx || null;
this.interval = interval;
this.done = false;
this._timer = interval ? setInterval(callInterval, ms, this) : setTimeout(callTimeout, ms, this);
}
unref() {
}
ref() {
}
refresh() {
if (this.done) return;
if (this.interval) {
clearInterval(this._timer);
this._timer = setInterval(callInterval, this.ms, this);
} else {
clearTimeout(this._timer);
this._timer = setTimeout(callTimeout, this.ms, this);
}
}
destroy() {
this.done = true;
this.ontimeout = null;
if (this.interval) clearInterval(this._timer);
else clearTimeout(this._timer);
}
static once(ms, fn, ctx) {
return new this(ms, fn, ctx, false);
}
static on(ms, fn, ctx) {
return new this(ms, fn, ctx, true);
}
};
function callTimeout(self) {
self.done = true;
self.ontimeout.call(self.context);
}
function callInterval(self) {
self.ontimeout.call(self.context);
}
}
});
// ../../node_modules/timeout-refresh/index.js
var require_timeout_refresh = __commonJS({
"../../node_modules/timeout-refresh/index.js"(exports, module) {
module.exports = isNode() ? require_node2() : require_browser();
function isNode() {
const to = setTimeout(function() {
}, 1e3);
clearTimeout(to);
return !!to.refresh;
}
}
});
// ../../node_modules/@hyperswarm/secret-stream/lib/bridge.js
var require_bridge = __commonJS({
"../../node_modules/@hyperswarm/secret-stream/lib/bridge.js"(exports, module) {
var { Duplex, Writable } = require_streamx();
var ReversePassThrough = class extends Duplex {
constructor(s) {
super();
this._stream = s;
this._ondrain = null;
}
_write(data, cb) {
if (this._stream.push(data) === false) {
this._stream._ondrain = cb;
} else {
cb(null);
}
}
_final(cb) {
this._stream.push(null);
cb(null);
}
_read(cb) {
const ondrain = this._ondrain;
this._ondrain = null;
if (ondrain) ondrain();
cb(null);
}
};
module.exports = class Bridge extends Duplex {
constructor(noiseStream) {
super();
this.noiseStream = noiseStream;
this._ondrain = null;
this.reverse = new ReversePassThrough(this);
}
get publicKey() {
return this.noiseStream.publicKey;
}
get remotePublicKey() {
return this.noiseStream.remotePublicKey;
}
get handshakeHash() {
return this.noiseStream.handshakeHash;
}
flush() {
return Writable.drained(this);
}
_read(cb) {
const ondrain = this._ondrain;
this._ondrain = null;
if (ondrain) ondrain();
cb(null);
}
_write(data, cb) {
if (this.reverse.push(data) === false) {
this.reverse._ondrain = cb;
} else {
cb(null);
}
}
_final(cb) {
this.reverse.push(null);
cb(null);
}
};
}
});
// ../../node_modules/nanoassert/index.js
var require_nanoassert = __commonJS({
"../../node_modules/nanoassert/index.js"(exports, module) {
module.exports = assert;
var AssertionError = class extends Error {
};
AssertionError.prototype.name = "AssertionError";
function assert(t, m) {
if (!t) {
var err = new AssertionError(m);
if (Error.captureStackTrace) Error.captureStackTrace(err, assert);
throw err;
}
}
}
});
// ../../node_modules/noise-curve-ed/index.js
var require_noise_curve_ed = __commonJS({
"../../node_modules/noise-curve-ed/index.js"(exports, module) {
var sodium = require_sodium_universal();
var assert = require_nanoassert();
var b4a = require_b4a();
var DHLEN = sodium.crypto_scalarmult_ed25519_BYTES;
var PKLEN = sodium.crypto_scalarmult_ed25519_BYTES;
var SCALARLEN = sodium.crypto_scalarmult_ed25519_BYTES;
var SKLEN = sodium.crypto_sign_SECRETKEYBYTES;
var ALG = "Ed25519";
module.exports = {
DHLEN,
PKLEN,
SCALARLEN,
SKLEN,
ALG,
name: ALG,
generateKeyPair,
dh
};
function generateKeyPair(privKey) {
if (privKey) return generateSeedKeyPair(privKey.subarray(0, 32));
const keyPair = {};
keyPair.secretKey = b4a.alloc(SKLEN);
keyPair.publicKey = b4a.alloc(PKLEN);
sodium.crypto_sign_keypair(keyPair.publicKey, keyPair.secretKey);
return keyPair;
}
function generateSeedKeyPair(seed) {
const keyPair = {};
keyPair.secretKey = b4a.alloc(SKLEN);
keyPair.publicKey = b4a.alloc(PKLEN);
sodium.crypto_sign_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed);
return keyPair;
}
function dh(publicKey, { scalar, secretKey }) {
if (!scalar) {
assert(secretKey.byteLength === SKLEN);
const sk = b4a.alloc(64);
sodium.crypto_hash_sha512(sk, secretKey.subarray(0, 32));
sk[0] &= 248;
sk[31] &= 127;
sk[31] |= 64;
scalar = sk.subarray(0, 32);
}
assert(scalar.byteLength === SCALARLEN);
assert(publicKey.byteLength === PKLEN);
const output = b4a.alloc(DHLEN);
sodium.crypto_scalarmult_ed25519_noclamp(
output,
scalar,
publicKey
);
return output;
}
}
});
// ../../node_modules/noise-handshake/cipher.js
var require_cipher = __commonJS({
"../../node_modules/noise-handshake/cipher.js"(exports, module) {
var sodium = require_sodium_universal();
var b4a = require_b4a();
module.exports = class CipherState {
constructor(key) {
this.key = key || null;
this.nonce = 0;
this.CIPHER_ALG = "ChaChaPoly";
}
initialiseKey(key) {
this.key = key;
this.nonce = 0;
}
setNonce(nonce) {
this.nonce = nonce;
}
encrypt(plaintext, ad) {
if (!this.hasKey) return plaintext;
if (!ad) ad = b4a.alloc(0);
const ciphertext = encryptWithAD(this.key, this.nonce, ad, plaintext);
if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`);
this.nonce++;
return ciphertext;
}
decrypt(ciphertext, ad) {
if (!this.hasKey) return ciphertext;
if (!ad) ad = b4a.alloc(0);
if (ciphertext.length > 65535) throw new Error(`ciphertext length of ${ciphertext.length} exceeds maximum Noise message length of 65535`);
const plaintext = decryptWithAD(this.key, this.nonce, ad, ciphertext);
this.nonce++;
return plaintext;
}
get hasKey() {
return this.key !== null;
}
_clear() {
sodium.sodium_memzero(this.key);
this.key = null;
this.nonce = null;
}
static get MACBYTES() {
return 16;
}
static get NONCEBYTES() {
return 8;
}
static get KEYBYTES() {
return 32;
}
};
function encryptWithAD(key, counter, additionalData, plaintext) {
if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, "hex");
if (!b4a.isBuffer(plaintext)) plaintext = b4a.from(plaintext, "hex");
const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES);
const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength);
view.setUint32(4, counter, true);
const ciphertext = b4a.alloc(plaintext.byteLength + sodium.crypto_aead_chacha20poly1305_ietf_ABYTES);
sodium.crypto_aead_chacha20poly1305_ietf_encrypt(ciphertext, plaintext, additionalData, null, nonce, key);
return ciphertext;
}
function decryptWithAD(key, counter, additionalData, ciphertext) {
if (!b4a.isBuffer(additionalData)) additionalData = b4a.from(additionalData, "hex");
if (!b4a.isBuffer(ciphertext)) ciphertext = b4a.from(ciphertext, "hex");
const nonce = b4a.alloc(sodium.crypto_aead_chacha20poly1305_ietf_NPUBBYTES);
const view = new DataView(nonce.buffer, nonce.byteOffset, nonce.byteLength);
view.setUint32(4, counter, true);
const plaintext = b4a.alloc(ciphertext.byteLength - sodium.crypto_aead_chacha20poly1305_ietf_ABYTES);
sodium.crypto_aead_chacha20poly1305_ietf_decrypt(plaintext, null, ciphertext, additionalData, nonce, key);
return plaintext;
}
}
});
// ../../node_modules/noise-handshake/dh.js
var require_dh = __commonJS({
"../../node_modules/noise-handshake/dh.js"(exports, module) {
var {
crypto_kx_SEEDBYTES,
crypto_kx_keypair,
crypto_kx_seed_keypair,
crypto_scalarmult_BYTES,
crypto_scalarmult_SCALARBYTES,
crypto_scalarmult,
crypto_scalarmult_base
} = require_sodium_universal();
var assert = require_nanoassert();
var b4a = require_b4a();
var DHLEN = crypto_scalarmult_BYTES;
var PKLEN = crypto_scalarmult_BYTES;
var SKLEN = crypto_scalarmult_SCALARBYTES;
var SEEDLEN = crypto_kx_SEEDBYTES;
var ALG = "25519";
module.exports = {
DHLEN,
PKLEN,
SKLEN,
SEEDLEN,
ALG,
generateKeyPair,
generateSeedKeyPair,
dh
};
function generateKeyPair(privKey) {
const keyPair = {};
keyPair.secretKey = privKey || b4a.alloc(SKLEN);
keyPair.publicKey = b4a.alloc(PKLEN);
if (privKey) {
crypto_scalarmult_base(keyPair.publicKey, keyPair.secretKey);
} else {
crypto_kx_keypair(keyPair.publicKey, keyPair.secretKey);
}
return keyPair;
}
function generateSeedKeyPair(seed) {
assert(seed.byteLength === SKLEN);
const keyPair = {};
keyPair.secretKey = b4a.alloc(SKLEN);
keyPair.publicKey = b4a.alloc(PKLEN);
crypto_kx_seed_keypair(keyPair.publicKey, keyPair.secretKey, seed);
return keyPair;
}
function dh(publicKey, { secretKey }) {
assert(secretKey.byteLength === SKLEN);
assert(publicKey.byteLength === PKLEN);
const output = b4a.alloc(DHLEN);
crypto_scalarmult(
output,
secretKey,
publicKey
);
return output;
}
}
});
// ../../node_modules/noise-handshake/hmac.js
var require_hmac = __commonJS({
"../../node_modules/noise-handshake/hmac.js"(exports, module) {
var b4a = require_b4a();
var { sodium_memzero, crypto_generichash, crypto_generichash_batch } = require_sodium_universal();
var HASHLEN = 64;
var BLOCKLEN = 128;
var scratch = b4a.alloc(BLOCKLEN * 3);
var HMACKey = scratch.subarray(BLOCKLEN * 0, BLOCKLEN * 1);
var OuterKeyPad = scratch.subarray(BLOCKLEN * 1, BLOCKLEN * 2);
var InnerKeyPad = scratch.subarray(BLOCKLEN * 2, BLOCKLEN * 3);
module.exports = function hmac(out, batch, key) {
if (key.byteLength > BLOCKLEN) {
crypto_generichash(HMACKey.subarray(0, HASHLEN), key);
sodium_memzero(HMACKey.subarray(HASHLEN));
} else {
HMACKey.set(key);
sodium_memzero(HMACKey.subarray(key.byteLength));
}
for (let i = 0; i < HMACKey.byteLength; i++) {
OuterKeyPad[i] = 92 ^ HMACKey[i];
InnerKeyPad[i] = 54 ^ HMACKey[i];
}
sodium_memzero(HMACKey);
crypto_generichash_batch(out, [InnerKeyPad].concat(batch));
sodium_memzero(InnerKeyPad);
crypto_generichash_batch(out, [OuterKeyPad, out]);
sodium_memzero(OuterKeyPad);
};
module.exports.BYTES = HASHLEN;
module.exports.KEYBYTES = BLOCKLEN;
}
});
// ../../node_modules/noise-handshake/hkdf.js
var require_hkdf = __commonJS({
"../../node_modules/noise-handshake/hkdf.js"(exports, module) {
var hmacBlake2b = require_hmac();
var b4a = require_b4a();
var HASHLEN = 64;
module.exports = {
hkdf,
HASHLEN
};
function hkdf(salt, inputKeyMaterial, info = "", length = 2 * HASHLEN) {
const pseudoRandomKey = hkdfExtract(salt, inputKeyMaterial);
return hkdfExpand(pseudoRandomKey, info, length);
}
function hkdfExtract(salt, inputKeyMaterial) {
const hmac = b4a.alloc(HASHLEN);
return hmacDigest(hmac, salt, inputKeyMaterial);
}
function hkdfExpand(key, info, length) {
const buffer = b4a.allocUnsafeSlow(length);
const infoBuf = b4a.from(info);
let prev = infoBuf;
const result = [];
for (let i = 0; i < length; i += HASHLEN) {
const pos = b4a.from([i / HASHLEN + 1]);
const out = buffer.subarray(i, i + HASHLEN);
result.push(out);
prev = hmacDigest(out, key, [prev, infoBuf, pos]);
}
return result;
}
function hmacDigest(out, key, input) {
hmacBlake2b(out, input, key);
return out;
}
}
});
// ../../node_modules/noise-handshake/symmetric-state.js
var require_symmetric_state = __commonJS({
"../../node_modules/noise-handshake/symmetric-state.js"(exports, module) {
var sodium = require_sodium_universal();
var assert = require_nanoassert();
var b4a = require_b4a();
var CipherState = require_cipher();
var curve = require_dh();
var { HASHLEN, hkdf } = require_hkdf();
module.exports = class SymmetricState extends CipherState {
constructor(opts = {}) {
super();
this.curve = opts.curve || curve;
this.digest = b4a.alloc(HASHLEN);
this.chainingKey = null;
this.offset = 0;
this.DH_ALG = this.curve.ALG;
}
mixHash(data) {
accumulateDigest(this.digest, data);
}
mixKeyAndHash(key) {
const [ck, tempH, tempK] = hkdf(this.chainingKey, key, "", 3 * HASHLEN);
this.chainingKey = ck;
this.mixHash(tempH);
this.initialiseKey(tempK.subarray(0, 32));
}
mixKeyNormal(key) {
const [ck, tempK] = hkdf(this.chainingKey, key);
this.chainingKey = ck;
this.initialiseKey(tempK.subarray(0, 32));
}
mixKey(remoteKey, localKey) {
const dh = this.curve.dh(remoteKey, localKey);
const hkdfResult = hkdf(this.chainingKey, dh);
this.chainingKey = hkdfResult[0];
this.initialiseKey(hkdfResult[1].subarray(0, 32));
}
encryptAndHash(plaintext) {
const ciphertext = this.encrypt(plaintext, this.digest);
accumulateDigest(this.digest, ciphertext);
return ciphertext;
}
decryptAndHash(ciphertext) {
const plaintext = this.decrypt(ciphertext, this.digest);
accumulateDigest(this.digest, ciphertext);
return plaintext;
}
getHandshakeHash(out) {
if (!out) return this.getHandshakeHash(b4a.alloc(HASHLEN));
assert(out.byteLength === HASHLEN, `output must be ${HASHLEN} bytes`);
out.set(this.digest);
return out;
}
split() {
const res = hkdf(this.chainingKey, b4a.alloc(0));
return res.map((k) => k.subarray(0, 32));
}
_clear() {
super._clear();
sodium.sodium_memzero(this.digest);
sodium.sodium_memzero(this.chainingKey);
this.digest = null;
this.chainingKey = null;
this.offset = null;
this.curve = null;
}
static get alg() {
return CipherState.alg + "_BLAKE2b";
}
};
function accumulateDigest(digest, input) {
const toHash = b4a.concat([digest, input]);
sodium.crypto_generichash(digest, toHash);
}
}
});
// ../../node_modules/noise-handshake/noise.js
var require_noise = __commonJS({
"../../node_modules/noise-handshake/noise.js"(exports, module) {
var assert = require_nanoassert();
var b4a = require_b4a();
var SymmetricState = require_symmetric_state();
var { HASHLEN } = require_hkdf();
var PRESHARE_IS = Symbol("initiator static key preshared");
var PRESHARE_RS = Symbol("responder static key preshared");
var TOK_PSK = Symbol("psk");
var TOK_S = Symbol("s");
var TOK_E = Symbol("e");
var TOK_ES = Symbol("es");
var TOK_SE = Symbol("se");
var TOK_EE = Symbol("ee");
var TOK_SS = Symbol("ss");
var HANDSHAKES = Object.freeze({
NN: [
[TOK_E],
[TOK_E, TOK_EE]
],
NNpsk0: [
[TOK_PSK, TOK_E],
[TOK_E, TOK_EE]
],
XX: [
[TOK_E],
[TOK_E, TOK_EE, TOK_S, TOK_ES],
[TOK_S, TOK_SE]
],
XXpsk0: [
[TOK_PSK, TOK_E],
[TOK_E, TOK_EE, TOK_S, TOK_ES],
[TOK_S, TOK_SE]
],
IK: [
PRESHARE_RS,
[TOK_E, TOK_ES, TOK_S, TOK_SS],
[TOK_E, TOK_EE, TOK_SE]
],
XK: [
PRESHARE_RS,
[TOK_E, TOK_ES],
[TOK_E, TOK_EE],
[TOK_S, TOK_SE]
]
});
var Writer = class {
constructor() {
this.size = 0;
this.buffers = [];
}
push(b) {
this.size += b.byteLength;
this.buffers.push(b);
}
end() {
const all = b4a.alloc(this.size);
let offset = 0;
for (const b of this.buffers) {
all.set(b, offset);
offset += b.byteLength;
}
return all;
}
};
var Reader = class {
constructor(buf) {
this.offset = 0;
this.buffer = buf;
}
shift(n) {
const start = this.offset;
const end = this.offset += n;
if (end > this.buffer.byteLength) throw new Error("Insufficient bytes");
return this.buffer.subarray(start, end);
}
end() {
return this.shift(this.buffer.byteLength - this.offset);
}
};
module.exports = class NoiseState extends SymmetricState {
constructor(pattern, initiator, staticKeypair, opts = {}) {
super(opts);
this.s = staticKeypair || this.curve.generateKeyPair();
this.e = null;
this.psk = null;
if (opts && opts.psk) this.psk = opts.psk;
this.re = null;
this.rs = null;
this.pattern = pattern;
this.handshake = HANDSHAKES[this.pattern].slice();
this.isPskHandshake = !!this.psk && hasPskToken(this.handshake);
this.protocol = b4a.from([
"Noise",
this.pattern,
this.DH_ALG,
this.CIPHER_ALG,
"BLAKE2b"
].join("_"));
this.initiator = initiator;
this.complete = false;
this.rx = null;
this.tx = null;
this.hash = null;
}
initialise(prologue, remoteStatic) {
if (this.protocol.byteLength <= HASHLEN) this.digest.set(this.protocol);
else this.mixHash(this.protocol);
this.chainingKey = b4a.from(this.digest);
this.mixHash(prologue);
while (!Array.isArray(this.handshake[0])) {
const message = this.handshake.shift();
assert(
message === PRESHARE_RS || message === PRESHARE_IS,
"Unexpected pattern"
);
const takeRemoteKey = this.initiator ? message === PRESHARE_RS : message === PRESHARE_IS;
if (takeRemoteKey) this.rs = remoteStatic;
const key = takeRemoteKey ? this.rs : this.s.publicKey;
assert(key != null, "Remote pubkey required");
this.mixHash(key);
}
}
final() {
const [k1, k2] = this.split();
this.tx = this.initiator ? k1 : k2;
this.rx = this.initiator ? k2 : k1;
this.complete = true;
this.hash = this.getHandshakeHash();
this._clear();
}
recv(buf) {
const r = new Reader(buf);
for (const pattern of this.handshake.shift()) {
switch (pattern) {
case TOK_PSK:
this.mixKeyAndHash(this.psk);
break;
case TOK_E:
this.re = r.shift(this.curve.PKLEN);
this.mixHash(this.re);
if (this.isPskHandshake) this.mixKeyNormal(this.re);
break;
case TOK_S: {
const klen = this.hasKey ? this.curve.PKLEN + 16 : this.curve.PKLEN;
this.rs = this.decryptAndHash(r.shift(klen));
break;
}
case TOK_EE:
case TOK_ES:
case TOK_SE:
case TOK_SS: {
const useStatic = keyPattern(pattern, this.initiator);
const localKey = useStatic.local ? this.s : this.e;
const remoteKey = useStatic.remote ? this.rs : this.re;
this.mixKey(remoteKey, localKey);
break;
}
default:
throw new Error("Unexpected message");
}
}
const payload = this.decryptAndHash(r.end());
if (!this.handshake.length) this.final();
return payload;
}
send(payload = b4a.alloc(0)) {
const w = new Writer();
for (const pattern of this.handshake.shift()) {
switch (pattern) {
case TOK_PSK:
this.mixKeyAndHash(this.psk);
break;
case TOK_E:
if (this.e === null) this.e = this.curve.generateKeyPair();
this.mixHash(this.e.publicKey);
if (this.isPskHandshake) this.mixKeyNormal(this.e.publicKey);
w.push(this.e.publicKey);
break;
case TOK_S:
w.push(this.encryptAndHash(this.s.publicKey));
break;
case TOK_ES:
case TOK_SE:
case TOK_EE:
case TOK_SS: {
const useStatic = keyPattern(pattern, this.initiator);
const localKey = useStatic.local ? this.s : this.e;
const remoteKey = useStatic.remote ? this.rs : this.re;
this.mixKey(remoteKey, localKey);
break;
}
default:
throw new Error("Unexpected message");
}
}
w.push(this.encryptAndHash(payload));
const response = w.end();
if (!this.handshake.length) this.final();
return response;
}
_clear() {
super._clear();
this.e.secretKey.fill(0);
this.e.publicKey.fill(0);
this.re.fill(0);
this.e = null;
this.re = null;
}
};
function keyPattern(pattern, initiator) {
const ret = {
local: false,
remote: false
};
switch (pattern) {
case TOK_EE:
return ret;
case TOK_ES:
ret.local ^= !initiator;
ret.remote ^= initiator;
return ret;
case TOK_SE:
ret.local ^= initiator;
ret.remote ^= !initiator;
return ret;
case TOK_SS:
ret.local ^= 1;
ret.remote ^= 1;
return ret;
}
}
function hasPskToken(handshake) {
return handshake.some((x) => {
return Array.isArray(x) && x.indexOf(TOK_PSK) !== -1;
});
}
}
});
// ../../node_modules/@hyperswarm/secret-stream/lib/handshake.js
var require_handshake = __commonJS({
"../../node_modules/@hyperswarm/secret-stream/lib/handshake.js"(exports, module) {
var sodium = require_sodium_universal();
var curve = require_noise_curve_ed();
var Noise = require_noise();
var b4a = require_b4a();
var EMPTY = b4a.alloc(0);
module.exports = class Handshake {
constructor(isInitiator, keyPair, remotePublicKey, pattern) {
this.isInitiator = isInitiator;
this.keyPair = keyPair;
this.noise = new Noise(pattern, isInitiator, keyPair, { curve });
this.noise.initialise(EMPTY, remotePublicKey);
this.destroyed = false;
}
static keyPair(seed) {
const publicKey = b4a.alloc(32);
const secretKey = b4a.alloc(64);
if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed);
else sodium.crypto_sign_keypair(publicKey, secretKey);
return { publicKey, secretKey };
}
recv(data) {
try {
this.noise.recv(data);
if (this.noise.complete) return this._return(null);
return this.send();
} catch {
this.destroy();
return null;
}
}
// note that the data returned here is framed so we don't have to do an extra copy
// when sending it...
send() {
try {
const data = this.noise.send();
const wrap = b4a.allocUnsafe(data.byteLength + 3);
writeUint24le(data.byteLength, wrap);
wrap.set(data, 3);
return this._return(wrap);
} catch {
this.destroy();
return null;
}
}
destroy() {
if (this.destroyed) return;
this.destroyed = true;
}
_return(data) {
const tx = this.noise.complete ? b4a.toBuffer(this.noise.tx) : null;
const rx = this.noise.complete ? b4a.toBuffer(this.noise.rx) : null;
const hash = this.noise.complete ? b4a.toBuffer(this.noise.hash) : null;
const remotePublicKey = this.noise.complete ? b4a.toBuffer(this.noise.rs) : null;
return {
data,
remotePublicKey,
hash,
tx,
rx
};
}
};
function writeUint24le(n, buf) {
buf[0] = n & 255;
buf[1] = n >>> 8 & 255;
buf[2] = n >>> 16 & 255;
}
}
});
// ../../node_modules/@hyperswarm/secret-stream/index.js
var require_secret_stream = __commonJS({
"../../node_modules/@hyperswarm/secret-stream/index.js"(exports, module) {
var { Pull, Push, HEADERBYTES, KEYBYTES, ABYTES } = require_sodium_secretstream();
var sodium = require_sodium_universal();
var crypto = require_hypercore_crypto();
var { Duplex, Writable, getStreamError } = require_streamx();
var b4a = require_b4a();
var Timeout = require_timeout_refresh();
var unslab = require_unslab();
var Bridge = require_bridge();
var Handshake = require_handshake();
var IDHEADERBYTES = HEADERBYTES + 32;
var [NS_INITIATOR, NS_RESPONDER, NS_SEND] = crypto.namespace("hyperswarm/secret-stream", 3);
var MAX_ATOMIC_WRITE = 256 * 256 * 256 - 1;
module.exports = class NoiseSecretStream extends Duplex {
constructor(isInitiator, rawStream, opts = {}) {
super({ mapWritable: toBuffer });
if (typeof isInitiator !== "boolean") {
throw new Error("isInitiator should be a boolean");
}
this.noiseStream = this;
this.isInitiator = isInitiator;
this.rawStream = null;
this.publicKey = opts.publicKey || null;
this.remotePublicKey = opts.remotePublicKey || null;
this.handshakeHash = null;
this.connected = false;
this.keepAlive = opts.keepAlive || 0;
this.timeout = 0;
this.enableSend = opts.enableSend !== false;
this.userData = null;
let openedDone = null;
this.opened = new Promise((resolve) => {
openedDone = resolve;
});
this.rawBytesWritten = 0;
this.rawBytesRead = 0;
this.relay = null;
this.puncher = null;
this._rawStream = null;
this._handshake = null;
this._handshakePattern = opts.pattern || null;
this._handshakeDone = null;
this._state = 0;
this._len = 0;
this._tmp = 1;
this._message = null;
this._openedDone = openedDone;
this._startDone = null;
this._drainDone = null;
this._outgoingPlain = null;
this._outgoingWrapped = null;
this._utp = null;
this._setup = true;
this._ended = 2;
this._encrypt = null;
this._decrypt = null;
this._timeoutTimer = null;
this._keepAliveTimer = null;
this._sendState = null;
if (opts.autoStart !== false) this.start(rawStream, opts);
this.resume();
this.pause();
}
static keyPair(seed) {
return Handshake.keyPair(seed);
}
static id(handshakeHash, isInitiator, id) {
return streamId(handshakeHash, isInitiator, id);
}
setTimeout(ms) {
if (!ms) ms = 0;
this._clearTimeout();
this.timeout = ms;
if (!ms || this.rawStream === null) return;
this._timeoutTimer = Timeout.once(ms, destroyTimeout, this);
this._timeoutTimer.unref();
}
setKeepAlive(ms) {
if (!ms) ms = 0;
this._clearKeepAlive();
this.keepAlive = ms;
if (!ms || this.rawStream === null) return;
this._keepAliveTimer = Timeout.on(ms, sendKeepAlive, this);
this._keepAliveTimer.unref();
}
sendKeepAlive() {
const empty = this.alloc(0);
this.write(empty);
}
start(rawStream, opts = {}) {
if (rawStream) {
this.rawStream = rawStream;
this._rawStream = rawStream;
if (typeof this.rawStream.setContentSize === "function") {
this._utp = rawStream;
}
} else {
this.rawStream = new Bridge(this);
this._rawStream = this.rawStream.reverse;
}
this.rawStream.on("error", this._onrawerror.bind(this));
this.rawStream.on("close", this._onrawclose.bind(this));
this._startHandshake(opts.handshake, opts.keyPair || null);
this._continueOpen(null);
if (this.destroying) return;
if (opts.data) this._onrawdata(opts.data);
if (opts.ended) this._onrawend();
if (this.keepAlive > 0 && this._keepAliveTimer === null) {
this.setKeepAlive(this.keepAlive);
}
if (this.timeout > 0 && this._timeoutTimer === null) {
this.setTimeout(this.timeout);
}
}
async flush() {
if (await this.opened === false) return false;
if (await Writable.drained(this) === false) return false;
if (this.destroying) return false;
if (this.rawStream !== null && this.rawStream.flush) {
return await this.rawStream.flush();
}
return true;
}
_continueOpen(err) {
if (err) this.destroy(err);
if (this._startDone === null) return;
const done = this._startDone;
this._startDone = null;
this._open(done);
}
_onkeypairpromise(p) {
const self = this;
const cont = this._continueOpen.bind(this);
p.then(onkeypair, cont);
function onkeypair(kp) {
self._onkeypair(kp);
cont(null);
}
}
_onkeypair(keyPair) {
const pattern = this._handshakePattern || "XX";
const remotePublicKey = this.remotePublicKey;
this._handshake = new Handshake(this.isInitiator, keyPair, remotePublicKey, pattern);
this.publicKey = this._handshake.keyPair.publicKey;
}
_startHandshake(handshake, keyPair) {
if (handshake) {
const { tx, rx, hash, publicKey, remotePublicKey } = handshake;
this._setupSecretStream(tx, rx, hash, publicKey, remotePublicKey);
return;
}
if (!keyPair) keyPair = Handshake.keyPair();
if (typeof keyPair.then === "function") {
this._onkeypairpromise(keyPair);
} else {
this._onkeypair(keyPair);
}
}
_onrawerror(err) {
this.destroy(err);
}
_onrawclose() {
if (this._ended !== 0) this.destroy();
}
_onrawdata(data) {
let offset = 0;
if (this._timeoutTimer !== null) {
this._timeoutTimer.refresh();
}
do {
switch (this._state) {
case 0: {
while (this._tmp !== 16777216 && offset < data.byteLength) {
const v = data[offset++];
this._len += this._tmp * v;
this._tmp *= 256;
}
if (this._tmp === 16777216) {
this._tmp = 0;
this._state = 1;
const unprocessed = data.byteLength - offset;
if (unprocessed < this._len && this._utp !== null)
this._utp.setContentSize(this._len - unprocessed);
}
break;
}
case 1: {
const missing = this._len - this._tmp;
const end = missing + offset;
if (this._message === null && end <= data.byteLength) {
this._message = data.subarray(offset, end);
offset += missing;
this._incoming();
break;
}
const unprocessed = data.byteLength - offset;
if (this._message === null) {
this._message = b4a.allocUnsafe(this._len);
}
b4a.copy(data, this._message, this._tmp, offset);
this._tmp += unprocessed;
if (end <= data.byteLength) {
offset += missing;
this._incoming();
} else {
offset += unprocessed;
}
break;
}
}
} while (offset < data.byteLength && !this.destroying);
}
_onrawend() {
this._ended--;
this.push(null);
}
_onrawdrain() {
const drain = this._drainDone;
if (drain === null) return;
this._drainDone = null;
drain();
}
_read(cb) {
this.rawStream.resume();
cb(null);
}
_incoming() {
const message = this._message;
this._state = 0;
this._len = 0;
this._tmp = 1;
this._message = null;
if (this._setup === true) {
if (this._handshake) {
this._onhandshakert(this._handshake.recv(message));
} else {
if (message.byteLength !== IDHEADERBYTES) {
this.destroy(new Error("Invalid header message received"));
return;
}
const remoteId = message.subarray(0, 32);
const expectedId = streamId(this.handshakeHash, !this.isInitiator);
const header = message.subarray(32);
if (!b4a.equals(expectedId, remoteId)) {
this.destroy(new Error("Invalid header received"));
return;
}
this._decrypt.init(header);
this._setup = false;
}
return;
}
if (message.byteLength < ABYTES) {
this.destroy(new Error("Invalid message received"));
return;
}
this.rawBytesRead += message.byteLength;
const plain = message.subarray(1, message.byteLength - ABYTES + 1);
try {
this._decrypt.next(message, plain);
} catch (err) {
this.destroy(err);
return;
}
if (plain.byteLength === 0 && this.keepAlive !== 0) return;
if (this.push(plain) === false) {
this.rawStream.pause();
}
}
_onhandshakert(h) {
if (this._handshakeDone === null) return;
if (h !== null) {
if (h.data) this._rawStream.write(h.data);
if (!h.tx) return;
}
const done = this._handshakeDone;
const publicKey = this._handshake.keyPair.publicKey;
this._handshakeDone = null;
this._handshake = null;
if (h === null) return done(new Error("Noise handshake failed"));
this._setupSecretStream(h.tx, h.rx, h.hash, publicKey, h.remotePublicKey);
this._resolveOpened(true);
done(null);
}
_setupSecretStream(tx, rx, handshakeHash, publicKey, remotePublicKey) {
const buf = b4a.allocUnsafeSlow(3 + IDHEADERBYTES);
writeUint24le(IDHEADERBYTES, buf);
this._encrypt = new Push(unslab(tx.subarray(0, KEYBYTES)), void 0, buf.subarray(3 + 32));
this._decrypt = new Pull(unslab(rx.subarray(0, KEYBYTES)));
this.publicKey = publicKey;
this.remotePublicKey = remotePublicKey;
this.handshakeHash = handshakeHash;
const id = buf.subarray(3, 3 + 32);
streamId(handshakeHash, this.isInitiator, id);
this._setupSecretSend(handshakeHash);
this.emit("handshake");
if (this.rawStream !== this._rawStream) this.rawStream.emit("handshake");
if (this.destroying) return;
this._rawStream.write(buf);
}
_setupSecretSend(handshakeHash) {
this._sendState = b4a.allocUnsafeSlow(32 + 32 + 8 + 8);
const encrypt = this._sendState.subarray(0, 32);
const decrypt = this._sendState.subarray(32, 64);
const counter = this._sendState.subarray(64, 72);
const initial = this._sendState.subarray(72);
const inputs = this.isInitiator ? [
[NS_INITIATOR, NS_SEND],
[NS_RESPONDER, NS_SEND]
] : [
[NS_RESPONDER, NS_SEND],
[NS_INITIATOR, NS_SEND]
];
sodium.crypto_generichash_batch(encrypt, inputs[0], handshakeHash);
sodium.crypto_generichash_batch(decrypt, inputs[1], handshakeHash);
sodium.randombytes_buf(initial);
counter.set(initial);
}
_open(cb) {
if (this._rawStream === null || this._handshake === null && this._encrypt === null) {
this._startDone = cb;
return;
}
this._rawStream.on("data", this._onrawdata.bind(this));
this._rawStream.on("end", this._onrawend.bind(this));
this._rawStream.on("drain", this._onrawdrain.bind(this));
if (this.enableSend) this._rawStream.on("message", this._onmessage.bind(this));
if (this._encrypt !== null) {
this._resolveOpened(true);
return cb(null);
}
this._handshakeDone = cb;
if (this.isInitiator) this._onhandshakert(this._handshake.send());
}
_predestroy() {
if (this.rawStream) {
const error = getStreamError(this);
this.rawStream.destroy(error);
}
if (this._startDone !== null) {
const done = this._startDone;
this._startDone = null;
done(new Error("Stream destroyed"));
}
if (this._handshakeDone !== null) {
const done = this._handshakeDone;
this._handshakeDone = null;
done(new Error("Stream destroyed"));
}
if (this._drainDone !== null) {
const done = this._drainDone;
this._drainDone = null;
done(new Error("Stream destroyed"));
}
}
_write(data, cb) {
let wrapped = this._outgoingWrapped;
if (data !== this._outgoingPlain) {
wrapped = b4a.allocUnsafe(data.byteLength + 3 + ABYTES);
wrapped.set(data, 4);
} else {
this._outgoingWrapped = this._outgoingPlain = null;
}
if (wrapped.byteLength - 3 > MAX_ATOMIC_WRITE) {
return cb(
new Error(
"Message is too large for an atomic write. Max size is " + MAX_ATOMIC_WRITE + " bytes."
)
);
}
this.rawBytesWritten += wrapped.byteLength;
writeUint24le(wrapped.byteLength - 3, wrapped);
this._encrypt.next(wrapped.subarray(4, 4 + data.byteLength), wrapped.subarray(3));
if (this._keepAliveTimer !== null) this._keepAliveTimer.refresh();
if (this._rawStream.write(wrapped) === false) {
this._drainDone = cb;
} else {
cb(null);
}
}
_final(cb) {
this._clearKeepAlive();
this._ended--;
this._rawStream.end();
cb(null);
}
_resolveOpened(val) {
if (this._openedDone === null) return;
const opened = this._openedDone;
this._openedDone = null;
opened(val);
if (!val) return;
this.connected = true;
this.emit("connect");
}
_clearTimeout() {
if (this._timeoutTimer === null) return;
this._timeoutTimer.destroy();
this._timeoutTimer = null;
this.timeout = 0;
}
_clearKeepAlive() {
if (this._keepAliveTimer === null) return;
this._keepAliveTimer.destroy();
this._keepAliveTimer = null;
this.keepAlive = 0;
}
_destroy(cb) {
this._clearKeepAlive();
this._clearTimeout();
this._resolveOpened(false);
cb(null);
}
_boxMessage(buffer) {
const MB = sodium.crypto_secretbox_MACBYTES;
const NB = sodium.crypto_secretbox_NONCEBYTES;
const counter = this._sendState.subarray(64, 72);
sodium.sodium_increment(counter);
if (b4a.equals(counter, this._sendState.subarray(72))) {
this.destroy(new Error("udp send nonce exchausted"));
return;
}
const secret = this._sendState.subarray(0, 32);
const envelope = b4a.allocUnsafe(8 + MB + buffer.byteLength);
const nonce = envelope.subarray(0, NB);
const ciphertext = envelope.subarray(8);
b4a.fill(nonce, 0);
nonce.set(counter);
sodium.crypto_secretbox_easy(ciphertext, buffer, nonce, secret);
return envelope;
}
send(buffer) {
if (!this._sendState) return;
if (!this.rawStream?.send) return;
const message = this._boxMessage(buffer);
return this.rawStream.send(message);
}
trySend(buffer) {
if (!this._sendState) return;
if (!this.rawStream?.trySend) return;
const message = this._boxMessage(buffer);
this.rawStream.trySend(message);
}
_onmessage(buffer) {
if (!this._sendState) return;
const MB = sodium.crypto_secretbox_MACBYTES;
const NB = sodium.crypto_secretbox_NONCEBYTES;
if (buffer.byteLength < NB) return;
const nonce = b4a.allocUnsafe(NB);
b4a.fill(nonce, 0);
nonce.set(buffer.subarray(0, 8));
const secret = this._sendState.subarray(32, 64);
const ciphertext = buffer.subarray(8);
const plain = buffer.subarray(8, buffer.byteLength - MB);
if (ciphertext.byteLength < MB) return;
const success = sodium.crypto_secretbox_open_easy(plain, ciphertext, nonce, secret);
if (success) this.emit("message", plain);
}
alloc(len) {
const buf = b4a.allocUnsafe(len + 3 + ABYTES);
this._outgoingWrapped = buf;
this._outgoingPlain = buf.subarray(4, buf.byteLength - ABYTES + 1);
return this._outgoingPlain;
}
toJSON() {
return {
isInitiator: this.isInitiator,
publicKey: this.publicKey && b4a.toString(this.publicKey, "hex"),
remotePublicKey: this.remotePublicKey && b4a.toString(this.remotePublicKey, "hex"),
connected: this.connected,
destroying: this.destroying,
destroyed: this.destroyed,
rawStream: this.rawStream && this.rawStream.toJSON ? this.rawStream.toJSON() : null
};
}
};
function writeUint24le(n, buf) {
buf[0] = n & 255;
buf[1] = n >>> 8 & 255;
buf[2] = n >>> 16 & 255;
}
function streamId(handshakeHash, isInitiator, out = b4a.allocUnsafe(32)) {
sodium.crypto_generichash(out, isInitiator ? NS_INITIATOR : NS_RESPONDER, handshakeHash);
return out;
}
function toBuffer(data) {
return typeof data === "string" ? b4a.from(data) : data;
}
function destroyTimeout() {
this.destroy(new Error("Stream timed out"));
}
function sendKeepAlive() {
const empty = this.alloc(0);
this.write(empty);
}
}
});
// ../../node_modules/queue-tick/queue-microtask.js
var require_queue_microtask = __commonJS({
"../../node_modules/queue-tick/queue-microtask.js"(exports, module) {
module.exports = typeof queueMicrotask === "function" ? queueMicrotask : (fn) => Promise.resolve().then(fn);
}
});
// ../../node_modules/queue-tick/process-next-tick.js
var require_process_next_tick = __commonJS({
"../../node_modules/queue-tick/process-next-tick.js"(exports, module) {
module.exports = typeof process !== "undefined" && typeof process.nextTick === "function" ? process.nextTick.bind(process) : require_queue_microtask();
}
});
// ../../node_modules/protomux/index.js
var require_protomux = __commonJS({
"../../node_modules/protomux/index.js"(exports, module) {
var b4a = require_b4a();
var c = require_compact_encoding();
var queueTick = require_process_next_tick();
var safetyCatch = require_safety_catch();
var unslab = require_unslab();
var MAX_BUFFERED = 32768;
var MAX_BACKLOG = Infinity;
var MAX_BATCH = 8 * 1024 * 1024;
var Channel = class {
constructor(mux, info, userData, protocol, aliases, id, handshake, messages, onopen, onclose, ondestroy, ondrain) {
this.userData = userData;
this.protocol = protocol;
this.aliases = aliases;
this.id = id;
this.handshake = null;
this.messages = [];
this.opened = false;
this.closed = false;
this.destroyed = false;
this.onopen = onopen;
this.onclose = onclose;
this.ondestroy = ondestroy;
this.ondrain = ondrain;
this._handshake = handshake;
this._mux = mux;
this._info = info;
this._localId = 0;
this._remoteId = 0;
this._active = 0;
this._extensions = null;
this._decBound = this._dec.bind(this);
this._decAndDestroyBound = this._decAndDestroy.bind(this);
this._openedPromise = null;
this._openedResolve = null;
this._destroyedPromise = null;
this._destroyedResolve = null;
for (const m of messages) this.addMessage(m);
}
get drained() {
return this._mux.drained;
}
fullyOpened() {
if (this.opened) return Promise.resolve(true);
if (this.closed) return Promise.resolve(false);
if (this._openedPromise) return this._openedPromise;
this._openedPromise = new Promise((resolve) => {
this._openedResolve = resolve;
});
return this._openedPromise;
}
fullyClosed() {
if (this.destroyed) return Promise.resolve();
if (this._destroyedPromise) return this._destroyedPromise;
this._destroyedPromise = new Promise((resolve) => {
this._destroyedResolve = resolve;
});
return this._destroyedPromise;
}
open(handshake) {
const id = this._mux._free.length > 0 ? this._mux._free.pop() : this._mux._local.push(null) - 1;
this._info.opened++;
this._info.lastChannel = this;
this._localId = id + 1;
this._mux._local[id] = this;
if (this._remoteId === 0) {
this._info.outgoing.push(this._localId);
}
const state = { buffer: null, start: 2, end: 2 };
c.uint.preencode(state, this._localId);
c.string.preencode(state, this.protocol);
c.buffer.preencode(state, this.id);
if (this._handshake) this._handshake.preencode(state, handshake);
state.buffer = this._mux._alloc(state.end);
state.buffer[0] = 0;
state.buffer[1] = 1;
c.uint.encode(state, this._localId);
c.string.encode(state, this.protocol);
c.buffer.encode(state, this.id);
if (this._handshake) this._handshake.encode(state, handshake);
this._mux._write0(state.buffer);
}
_dec() {
if (--this._active === 0 && this.closed === true) this._destroy();
}
_decAndDestroy(err) {
this._dec();
this._mux._safeDestroy(err);
}
_fullyOpenSoon() {
this._mux._remote[this._remoteId - 1].session = this;
queueTick(this._fullyOpen.bind(this));
}
_fullyOpen() {
if (this.opened === true || this.closed === true) return;
const remote = this._mux._remote[this._remoteId - 1];
this.opened = true;
this.handshake = this._handshake ? this._handshake.decode(remote.state) : null;
this._track(this.onopen(this.handshake, this));
remote.session = this;
remote.state = null;
if (remote.pending !== null) this._drain(remote);
this._resolveOpen(true);
}
_resolveOpen(opened) {
if (this._openedResolve !== null) {
this._openedResolve(opened);
this._openedResolve = this._openedPromise = null;
}
}
_resolveDestroyed() {
if (this._destroyedResolve !== null) {
this._destroyedResolve();
this._destroyedResolve = this._destroyedPromise = null;
}
}
_drain(remote) {
for (let i = 0; i < remote.pending.length; i++) {
const p = remote.pending[i];
this._mux._buffered -= byteSize(p.state);
this._recv(p.type, p.state);
}
remote.pending = null;
this._mux._resumeMaybe();
}
_track(p) {
if (isPromise(p) === true) {
this._active++;
return p.then(this._decBound, this._decAndDestroyBound);
}
return null;
}
_close(isRemote) {
if (this.closed === true) return;
this.closed = true;
this._info.opened--;
if (this._info.lastChannel === this) this._info.lastChannel = null;
if (this._remoteId > 0) {
this._mux._remote[this._remoteId - 1] = null;
this._remoteId = 0;
this._mux._free.push(this._localId - 1);
}
this._mux._local[this._localId - 1] = null;
this._localId = 0;
this._mux._gc(this._info);
this._track(this.onclose(isRemote, this));
if (this._active === 0) this._destroy();
this._resolveOpen(false);
}
_destroy() {
if (this.destroyed === true) return;
this.destroyed = true;
this._track(this.ondestroy(this));
this._resolveDestroyed();
}
_recv(type, state) {
if (type < this.messages.length) {
const m = this.messages[type];
const p = m.recv(state, this);
if (m.autoBatch === true) return p;
}
return null;
}
cork() {
this._mux.cork();
}
uncork() {
this._mux.uncork();
}
close() {
if (this.closed === true) return;
const state = { buffer: null, start: 2, end: 2 };
c.uint.preencode(state, this._localId);
state.buffer = this._mux._alloc(state.end);
state.buffer[0] = 0;
state.buffer[1] = 3;
c.uint.encode(state, this._localId);
this._close(false);
this._mux._write0(state.buffer);
}
addMessage(opts) {
if (!opts) return this._skipMessage();
const type = this.messages.length;
const autoBatch = opts.autoBatch !== false;
const encoding = opts.encoding || c.raw;
const onmessage = opts.onmessage || noop;
const s = this;
const typeLen = encodingLength(c.uint, type);
const m = {
type,
autoBatch,
encoding,
onmessage,
recv(state, session) {
return session._track(m.onmessage(encoding.decode(state), session));
},
send(m2, session = s) {
if (session.closed === true) return false;
const mux = session._mux;
const state = { buffer: null, start: 0, end: typeLen };
if (mux._batch !== null) {
encoding.preencode(state, m2);
state.buffer = mux._alloc(state.end);
c.uint.encode(state, type);
encoding.encode(state, m2);
mux._pushBatch(session._localId, state.buffer);
return true;
}
c.uint.preencode(state, session._localId);
encoding.preencode(state, m2);
state.buffer = mux._alloc(state.end);
c.uint.encode(state, session._localId);
c.uint.encode(state, type);
encoding.encode(state, m2);
mux.drained = mux.stream.write(state.buffer);
return mux.drained;
}
};
this.messages.push(m);
return m;
}
_skipMessage() {
const type = this.messages.length;
const m = {
type,
encoding: c.raw,
onmessage: noop,
recv(state, session) {
},
send(m2, session) {
}
};
this.messages.push(m);
return m;
}
};
module.exports = class Protomux {
constructor(stream, { alloc } = {}) {
if (stream.userData === null) stream.userData = this;
this.isProtomux = true;
this.stream = stream;
this.corked = 0;
this.drained = true;
this._alloc = alloc || (typeof stream.alloc === "function" ? stream.alloc.bind(stream) : b4a.allocUnsafe);
this._safeDestroyBound = this._safeDestroy.bind(this);
this._uncorkBound = this.uncork.bind(this);
this._remoteBacklog = 0;
this._buffered = 0;
this._paused = false;
this._remote = [];
this._local = [];
this._free = [];
this._batch = null;
this._batchState = null;
this._infos = /* @__PURE__ */ new Map();
this._notify = /* @__PURE__ */ new Map();
this.stream.on("data", this._ondata.bind(this));
this.stream.on("drain", this._ondrain.bind(this));
this.stream.on("end", this._onend.bind(this));
this.stream.on("error", noop);
this.stream.on("close", this._shutdown.bind(this));
}
static from(stream, opts) {
if (stream.userData && stream.userData.isProtomux) return stream.userData;
if (stream.isProtomux) return stream;
return new this(stream, opts);
}
static isProtomux(mux) {
return typeof mux === "object" && mux.isProtomux === true;
}
*[Symbol.iterator]() {
for (const session of this._local) {
if (session !== null) yield session;
}
}
isIdle() {
return this._local.length === this._free.length;
}
cork() {
if (++this.corked === 1) {
this._batch = [];
this._batchState = { buffer: null, start: 0, end: 1 };
}
}
uncork() {
if (--this.corked === 0) {
this._sendBatch(this._batch, this._batchState);
this._batch = null;
this._batchState = null;
}
}
getLastChannel({ protocol, id = null }) {
const key = toKey(protocol, id);
const info = this._infos.get(key);
if (info) return info.lastChannel;
return null;
}
pair({ protocol, id = null }, notify) {
this._notify.set(toKey(protocol, id), notify);
}
unpair({ protocol, id = null }) {
this._notify.delete(toKey(protocol, id));
}
opened({ protocol, id = null }) {
const key = toKey(protocol, id);
const info = this._infos.get(key);
return info ? info.opened > 0 : false;
}
createChannel({ userData = null, protocol, aliases = [], id = null, unique = true, handshake = null, messages = [], onopen = noop, onclose = noop, ondestroy = noop, ondrain = noop }) {
if (this.stream.destroyed) return null;
const info = this._get(protocol, id, aliases);
if (unique && info.opened > 0) return null;
if (info.incoming.length === 0) {
return new Channel(this, info, userData, protocol, aliases, id, handshake, messages, onopen, onclose, ondestroy, ondrain);
}
this._remoteBacklog--;
const remoteId = info.incoming.shift();
const r = this._remote[remoteId - 1];
if (r === null) return null;
const session = new Channel(this, info, userData, protocol, aliases, id, handshake, messages, onopen, onclose, ondestroy, ondrain);
session._remoteId = remoteId;
session._fullyOpenSoon();
return session;
}
_pushBatch(localId, buffer) {
if (this._batchState.end >= MAX_BATCH) {
this._sendBatch(this._batch, this._batchState);
this._batch = [];
this._batchState = { buffer: null, start: 0, end: 1 };
}
if (this._batch.length === 0 || this._batch[this._batch.length - 1].localId !== localId) {
this._batchState.end++;
c.uint.preencode(this._batchState, localId);
}
c.buffer.preencode(this._batchState, buffer);
this._batch.push({ localId, buffer });
}
_sendBatch(batch, state) {
if (batch.length === 0) return;
let prev = batch[0].localId;
state.buffer = this._alloc(state.end);
state.buffer[state.start++] = 0;
state.buffer[state.start++] = 0;
c.uint.encode(state, prev);
for (let i = 0; i < batch.length; i++) {
const b = batch[i];
if (prev !== b.localId) {
state.buffer[state.start++] = 0;
c.uint.encode(state, prev = b.localId);
}
c.buffer.encode(state, b.buffer);
}
this.drained = this.stream.write(state.buffer);
}
_get(protocol, id, aliases = []) {
const key = toKey(protocol, id);
let info = this._infos.get(key);
if (info) return info;
info = { key, protocol, aliases: [], id, pairing: 0, opened: 0, incoming: [], outgoing: [], lastChannel: null };
this._infos.set(key, info);
for (const alias of aliases) {
const key2 = toKey(alias, id);
info.aliases.push(key2);
this._infos.set(key2, info);
}
return info;
}
_gc(info) {
if (info.opened === 0 && info.outgoing.length === 0 && info.incoming.length === 0) {
this._infos.delete(info.key);
for (const alias of info.aliases) this._infos.delete(alias);
}
}
_ondata(buffer) {
if (buffer.byteLength === 0) return;
try {
const state = { buffer, start: 0, end: buffer.byteLength };
this._decode(c.uint.decode(state), state);
} catch (err) {
this._safeDestroy(err);
}
}
_ondrain() {
this.drained = true;
for (const s of this._local) {
if (s !== null) s._track(s.ondrain(s));
}
}
_onend() {
this.stream.end();
}
_decode(remoteId, state) {
const type = c.uint.decode(state);
if (remoteId === 0) {
return this._oncontrolsession(type, state);
}
const r = remoteId <= this._remote.length ? this._remote[remoteId - 1] : null;
if (r === null) return null;
if (r.pending !== null) {
this._bufferMessage(r, type, state);
return null;
}
return r.session._recv(type, state);
}
_oncontrolsession(type, state) {
switch (type) {
case 0:
this._onbatch(state);
break;
case 1:
return this._onopensession(state);
case 2:
this._onrejectsession(state);
break;
case 3:
this._onclosesession(state);
break;
}
return null;
}
_bufferMessage(r, type, { buffer, start, end }) {
const state = { buffer, start, end };
r.pending.push({ type, state });
this._buffered += byteSize(state);
this._pauseMaybe();
}
_pauseMaybe() {
if (this._paused === true || this._buffered <= MAX_BUFFERED) return;
this._paused = true;
this.stream.pause();
}
_resumeMaybe() {
if (this._paused === false || this._buffered > MAX_BUFFERED) return;
this._paused = false;
this.stream.resume();
}
_onbatch(state) {
const end = state.end;
let remoteId = c.uint.decode(state);
let waiting = null;
while (state.end > state.start) {
const len = c.uint.decode(state);
if (len === 0) {
remoteId = c.uint.decode(state);
continue;
}
state.end = state.start + len;
if (end !== state.end && waiting === null) {
waiting = [];
this.cork();
}
const p = this._decode(remoteId, state);
if (waiting !== null && p !== null) waiting.push(p);
state.start = state.end;
state.end = end;
}
if (waiting !== null) {
Promise.all(waiting).then(this._uncorkBound, this._safeDestroyBound);
}
}
_onopensession(state) {
const remoteId = c.uint.decode(state);
const protocol = c.string.decode(state);
const id = unslab(c.buffer.decode(state));
if (remoteId === 0) {
this._rejectSession(0);
return null;
}
const rid = remoteId - 1;
const info = this._get(protocol, id);
if (this._remote.length === rid) {
this._remote.push(null);
}
if (rid >= this._remote.length || this._remote[rid] !== null) {
throw new Error("Invalid open message");
}
if (info.outgoing.length > 0) {
const localId = info.outgoing.shift();
const session = this._local[localId - 1];
if (session === null) {
this._free.push(localId - 1);
return null;
}
this._remote[rid] = { state, pending: null, session: null };
session._remoteId = remoteId;
session._fullyOpen();
return null;
}
const copyState = { buffer: state.buffer, start: state.start, end: state.end };
this._remote[rid] = { state: copyState, pending: [], session: null };
if (++this._remoteBacklog > MAX_BACKLOG) {
throw new Error("Remote exceeded backlog");
}
info.pairing++;
info.incoming.push(remoteId);
return this._requestSession(protocol, id, info).catch(this._safeDestroyBound);
}
_onrejectsession(state) {
const localId = c.uint.decode(state);
for (const info of this._infos.values()) {
const i = info.outgoing.indexOf(localId);
if (i === -1) continue;
info.outgoing.splice(i, 1);
const session = this._local[localId - 1];
this._free.push(localId - 1);
if (session !== null) session._close(true);
this._gc(info);
return;
}
throw new Error("Invalid reject message");
}
_onclosesession(state) {
const remoteId = c.uint.decode(state);
if (remoteId === 0) return;
const rid = remoteId - 1;
const r = rid < this._remote.length ? this._remote[rid] : null;
if (r === null) return;
if (r.session !== null) r.session._close(true);
}
async _requestSession(protocol, id, info) {
const notify = this._notify.get(toKey(protocol, id)) || this._notify.get(toKey(protocol, null));
if (notify) await notify(id);
if (--info.pairing > 0) return;
while (info.incoming.length > 0) {
this._rejectSession(info, info.incoming.shift());
}
this._gc(info);
}
_rejectSession(info, remoteId) {
if (remoteId > 0) {
const r = this._remote[remoteId - 1];
if (r.pending !== null) {
for (let i = 0; i < r.pending.length; i++) {
this._buffered -= byteSize(r.pending[i].state);
}
}
this._remote[remoteId - 1] = null;
this._resumeMaybe();
}
const state = { buffer: null, start: 2, end: 2 };
c.uint.preencode(state, remoteId);
state.buffer = this._alloc(state.end);
state.buffer[0] = 0;
state.buffer[1] = 2;
c.uint.encode(state, remoteId);
this._write0(state.buffer);
}
_write0(buffer) {
if (this._batch !== null) {
this._pushBatch(0, buffer.subarray(1));
return;
}
this.drained = this.stream.write(buffer);
}
destroy(err) {
this.stream.destroy(err);
}
_safeDestroy(err) {
safetyCatch(err);
this.stream.destroy(err);
}
_shutdown() {
for (const s of this._local) {
if (s !== null) s._close(true);
}
}
};
function noop() {
}
function toKey(protocol, id) {
return protocol + "##" + (id ? b4a.toString(id, "hex") : "");
}
function byteSize(state) {
return 512 + (state.end - state.start);
}
function isPromise(p) {
return !!(p && typeof p.then === "function");
}
function encodingLength(enc, val) {
const state = { buffer: null, start: 0, end: 0 };
enc.preencode(state, val);
return state.end;
}
}
});
// ../../node_modules/compact-encoding-bitfield/index.js
var require_compact_encoding_bitfield = __commonJS({
"../../node_modules/compact-encoding-bitfield/index.js"(exports, module) {
var c = require_compact_encoding();
module.exports = function bitfield(length) {
if (length > 64) throw new RangeError("Bitfield cannot be larger than 64 bits");
let byteLength;
if (length < 8) byteLength = 1;
else if (length <= 16) byteLength = 2;
else if (length <= 32) byteLength = 4;
else byteLength = 8;
return {
preencode(state) {
state.end++;
if (byteLength === 1) ;
else if (byteLength === 2) c.uint16.preencode(state);
else if (byteLength === 4) c.uint32.preencode(state);
else c.uint64.preencode(state);
},
encode(state, b) {
if (byteLength === 1) ;
else if (byteLength === 2) c.uint8.encode(state, 253);
else if (byteLength === 4) c.uint8.encode(state, 254);
else c.uint8.encode(state, 255);
if (typeof b === "number") {
if (byteLength === 1) c.uint8.encode(state, b);
else if (byteLength === 2) c.uint16.encode(state, b);
else if (byteLength === 4) c.uint32.encode(state, b);
else c.uint64.encode(state, b);
} else {
state.buffer.set(b, state.start);
if (b.byteLength < byteLength) {
state.buffer.fill(
0,
state.start + b.byteLength,
state.start + byteLength
);
}
state.start += byteLength;
}
},
decode(state) {
const byte = state.buffer[state.start];
let byteLength2;
if (byte <= 252) byteLength2 = 1;
else if (byte === 253) byteLength2 = 2;
else if (byte === 254) byteLength2 = 4;
else byteLength2 = 8;
if (byteLength2 > 1) state.start++;
if (state.end - state.start < byteLength2) throw new Error("Out of bounds");
const b = state.buffer.subarray(state.start, state.start += byteLength2);
return length <= 8 ? b.subarray(0, 1) : b;
}
};
};
}
});
// ../../node_modules/bits-to-bytes/index.js
var require_bits_to_bytes = __commonJS({
"../../node_modules/bits-to-bytes/index.js"(exports, module) {
var b4a = require_b4a();
function byteLength(size) {
return Math.ceil(size / 8);
}
function get(buffer, bit) {
const n = buffer.BYTES_PER_ELEMENT * 8;
const offset = bit & n - 1;
const i = (bit - offset) / n;
return (buffer[i] & 1 << offset) !== 0;
}
function set(buffer, bit, value = true) {
const n = buffer.BYTES_PER_ELEMENT * 8;
const offset = bit & n - 1;
const i = (bit - offset) / n;
const mask = 1 << offset;
if (value) {
if ((buffer[i] & mask) !== 0) return false;
} else {
if ((buffer[i] & mask) === 0) return false;
}
buffer[i] ^= mask;
return true;
}
function setRange(buffer, start, end, value = true) {
const n = buffer.BYTES_PER_ELEMENT * 8;
let remaining = end - start;
let offset = start & n - 1;
let i = (start - offset) / n;
let changed = false;
while (remaining > 0) {
const mask = 2 ** Math.min(remaining, n - offset) - 1 << offset;
if (value) {
if ((buffer[i] & mask) !== mask) {
buffer[i] |= mask;
changed = true;
}
} else {
if ((buffer[i] & mask) !== 0) {
buffer[i] &= ~mask;
changed = true;
}
}
remaining -= n - offset;
offset = 0;
i++;
}
return changed;
}
function fill(buffer, value, start = 0, end = buffer.byteLength * 8) {
const n = buffer.BYTES_PER_ELEMENT * 8;
let i, j;
{
const offset = start & n - 1;
i = (start - offset) / n;
if (offset !== 0) {
const mask = 2 ** Math.min(n - offset, end - start) - 1 << offset;
if (value) buffer[i] |= mask;
else buffer[i] &= ~mask;
i++;
}
}
{
const offset = end & n - 1;
j = (end - offset) / n;
if (offset !== 0 && j >= i) {
const mask = 2 ** offset - 1;
if (value) buffer[j] |= mask;
else buffer[j] &= ~mask;
}
}
return buffer.fill(value ? 2 ** n - 1 : 0, i, j);
}
function toggle(buffer, bit) {
const n = buffer.BYTES_PER_ELEMENT * 8;
const offset = bit & n - 1;
const i = (bit - offset) / n;
const mask = 1 << offset;
buffer[i] ^= mask;
return (buffer[i] & mask) !== 0;
}
function remove(buffer, bit) {
return set(buffer, bit, false);
}
function removeRange(buffer, start, end) {
return setRange(buffer, start, end, false);
}
function indexOf(buffer, value, position = 0) {
for (let i = position, n = buffer.byteLength * 8; i < n; i++) {
if (get(buffer, i) === value) return i;
}
return -1;
}
function lastIndexOf(buffer, value, position = buffer.byteLength * 8 - 1) {
for (let i = position; i >= 0; i--) {
if (get(buffer, i) === value) return i;
}
return -1;
}
function of(...bits) {
return from(bits);
}
function from(bits) {
const buffer = b4a.alloc(byteLength(bits.length));
for (let i = 0; i < bits.length; i++) set(buffer, i, bits[i]);
return buffer;
}
function* iterator(buffer) {
for (let i = 0, n = buffer.byteLength * 8; i < n; i++) yield get(buffer, i);
}
module.exports = {
byteLength,
get,
set,
setRange,
fill,
toggle,
remove,
removeRange,
indexOf,
lastIndexOf,
of,
from,
iterator
};
}
});
// ../../node_modules/blind-relay/lib/errors.js
var require_errors10 = __commonJS({
"../../node_modules/blind-relay/lib/errors.js"(exports, module) {
module.exports = class BlindRelayError extends Error {
constructor(msg, code, fn = BlindRelayError) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "BlindRelayError";
}
static DUPLICATE_CHANNEL(msg = "Duplicate channel") {
return new BlindRelayError(msg, "DUPLICATE_CHANNEL", BlindRelayError.DUPLICATE_CHANNEL);
}
static CHANNEL_CLOSED(msg = "Channel closed") {
return new BlindRelayError(msg, "CHANNEL_CLOSED", BlindRelayError.CHANNEL_CLOSED);
}
static CHANNEL_DESTROYED(msg = "Channel destroyed") {
return new BlindRelayError(msg, "CHANNEL_DESTROYED", BlindRelayError.CHANNEL_DESTROYED);
}
static ALREADY_PAIRING(msg = "Already pairing") {
return new BlindRelayError(msg, "ALREADY_PAIRING", BlindRelayError.ALREADY_PAIRING);
}
static PAIRING_CANCELLED(msg = "Pairing cancelled") {
return new BlindRelayError(msg, "PAIRING_CANCELLED", BlindRelayError.PAIRING_CANCELLED);
}
};
}
});
// ../../node_modules/blind-relay/index.js
var require_blind_relay = __commonJS({
"../../node_modules/blind-relay/index.js"(exports) {
var EventEmitter = require_bare_node_events();
var Protomux = require_protomux();
var { Readable } = require_streamx();
var sodium = require_sodium_universal();
var b4a = require_b4a();
var c = require_compact_encoding();
var bitfield = require_compact_encoding_bitfield();
var bits = require_bits_to_bytes();
var errors = require_errors10();
exports.Server = class BlindRelayServer extends EventEmitter {
constructor(opts = {}) {
super();
const {
createStream
} = opts;
this._createStream = createStream;
this._pairing = /* @__PURE__ */ new Map();
this._sessions = /* @__PURE__ */ new Set();
}
get sessions() {
return this._sessions[Symbol.iterator]();
}
accept(stream, opts) {
const session = new BlindRelaySession(this, stream, opts);
this._sessions.add(session);
return session;
}
async close() {
const ending = [];
for (const session of this._sessions) {
ending.push(session.end());
}
await Promise.all(ending);
this._pairing.clear();
}
};
var BlindRelaySession = class extends EventEmitter {
constructor(server, stream, opts = {}) {
super();
const {
id,
handshake,
handshakeEncoding
} = opts;
this._server = server;
this._mux = Protomux.from(stream);
this._channel = this._mux.createChannel({
protocol: "blind-relay",
id,
handshake: handshake ? handshakeEncoding || c.raw : null,
onopen: this._onopen.bind(this),
onclose: this._onclose.bind(this),
ondestroy: this._ondestroy.bind(this)
});
this._pair = this._channel.addMessage({
encoding: m.pair,
onmessage: this._onpair.bind(this)
});
this._unpair = this._channel.addMessage({
encoding: m.unpair,
onmessage: this._onunpair.bind(this)
});
this._ending = null;
this._destroyed = false;
this._error = null;
this._pairing = /* @__PURE__ */ new Set();
this._streams = /* @__PURE__ */ new Map();
this._onerror = (err) => this.emit("error", err);
this._channel.open(handshake);
}
get closed() {
return this._channel.closed;
}
get mux() {
return this._mux;
}
get stream() {
return this._mux.stream;
}
_onopen() {
this.emit("open");
}
_onclose() {
this._ending = Promise.resolve();
const err = this._error || errors.CHANNEL_CLOSED();
for (const token of this._pairing) {
this._server._pairing.delete(token.toString("hex"));
}
for (const stream of this._streams.values()) {
stream.off("error", this._onerror).on("error", noop).destroy(err);
}
this._pairing.clear();
this._streams.clear();
this._server._sessions.delete(this);
this.emit("close");
}
_ondestroy() {
this._destroyed = true;
this.emit("destroy");
}
_onpair({ isInitiator, token, id: remoteId }) {
const keyString = token.toString("hex");
let pair = this._server._pairing.get(keyString);
if (pair === void 0) {
pair = new BlindRelayPair(token);
this._server._pairing.set(keyString, pair);
} else if (pair.links[+isInitiator]) return;
this._pairing.add(keyString);
pair.links[+isInitiator] = new BlindRelayLink(this, isInitiator, remoteId);
if (!pair.paired) return;
this._server._pairing.delete(keyString);
for (const link of pair.links) {
link.createStream();
}
for (const { isInitiator: isInitiator2, session, stream } of pair.links) {
const remote = pair.remote(isInitiator2);
stream.on("error", session._onerror).on("close", () => session._streams.delete(keyString)).relayTo(remote.stream);
session._pairing.delete(keyString);
session._streams.set(keyString, stream);
}
for (const { isInitiator: isInitiator2, session, remoteId: remoteId2, stream } of pair.links) {
session._pair.send({
isInitiator: isInitiator2,
token,
id: stream.id,
seq: 0
});
session._endMaybe();
session.emit("pair", isInitiator2, token, stream, remoteId2);
}
}
_onunpair({ token }) {
const keyString = token.toString("hex");
const pair = this._server._pairing.get(keyString);
if (pair) {
for (const link of pair.links) {
if (link) link.session._pairing.delete(keyString);
}
return this._server._pairing.delete(keyString);
}
const stream = this._streams.get(keyString);
if (stream) {
stream.off("error", this._onerror).on("error", noop).destroy(errors.PAIRING_CANCELLED());
this._streams.delete(keyString);
}
}
cork() {
this._channel.cork();
}
uncork() {
this._channel.uncork();
}
async end() {
if (this._ending) return this._ending;
this._ending = EventEmitter.once(this, "close");
this._endMaybe();
return this._ending;
}
_endMaybe() {
if (this._ending && this._pairing.size === 0) {
this._channel.close();
}
}
destroy(err) {
if (this._destroyed) return;
this._destroyed = true;
this._error = err || errors.CHANNEL_DESTROYED();
this._channel.close();
}
};
var BlindRelayPair = class {
constructor(token) {
this.token = token;
this.links = [null, null];
}
get paired() {
return this.links[0] !== null && this.links[1] !== null;
}
remote(isInitiator) {
return this.links[isInitiator ? 0 : 1];
}
};
var BlindRelayLink = class {
constructor(session, isInitiator, remoteId) {
this.session = session;
this.isInitiator = isInitiator;
this.remoteId = remoteId;
this.stream = null;
}
createStream() {
if (this.stream) return;
this.stream = this.session._server._createStream({
firewall: this._onfirewall.bind(this)
});
}
_onfirewall(socket, port, host) {
this.stream.connect(socket, this.remoteId, port, host);
return false;
}
};
exports.Client = class BlindRelayClient extends EventEmitter {
static _clients = /* @__PURE__ */ new WeakMap();
static from(stream, opts) {
let client = this._clients.get(stream);
if (client) return client;
client = new this(stream, opts);
this._clients.set(stream, client);
return client;
}
constructor(stream, opts = {}) {
super();
const {
id,
handshake,
handshakeEncoding
} = opts;
this._mux = Protomux.from(stream);
this._channel = this._mux.createChannel({
protocol: "blind-relay",
id,
handshake: handshake ? handshakeEncoding || c.raw : null,
onopen: this._onopen.bind(this),
onclose: this._onclose.bind(this),
ondestroy: this._ondestroy.bind(this)
});
this._pair = this._channel.addMessage({
encoding: m.pair,
onmessage: this._onpair.bind(this)
});
this._unpair = this._channel.addMessage({
encoding: m.unpair
});
this._ending = false;
this._destroyed = false;
this._error = null;
this._requests = /* @__PURE__ */ new Map();
this._channel.open(handshake);
}
get closed() {
return this._channel.closed;
}
get mux() {
return this._mux;
}
get stream() {
return this._mux.stream;
}
get requests() {
return this._requests.values();
}
_onopen() {
this.emit("open");
}
_onclose() {
this._ending = Promise.resolve();
const err = this._error || errors.CHANNEL_CLOSED();
for (const request of this._requests.values()) {
request.destroy(err);
}
this._requests.clear();
this.constructor._clients.delete(this.stream);
this.emit("close");
}
_ondestroy() {
this._destroyed = true;
this.emit("destroy");
}
_onpair({ isInitiator, token, id: remoteId }) {
const request = this._requests.get(token.toString("hex"));
if (request === void 0 || request.isInitiator !== isInitiator) return;
request.push(remoteId);
request.push(null);
this.emit("pair", request.isInitiator, request.token, request.stream, remoteId);
}
pair(isInitiator, token, stream) {
if (this._destroyed) throw errors.CHANNEL_DESTROYED();
const keyString = token.toString("hex");
if (this._requests.has(keyString)) throw errors.ALREADY_PAIRING();
const request = new BlindRelayRequest(this, isInitiator, token, stream);
this._requests.set(keyString, request);
return request;
}
unpair(token) {
if (this._destroyed) throw errors.CHANNEL_DESTROYED();
const request = this._requests.get(token.toString("hex"));
if (request) request.destroy(errors.PAIRING_CANCELLED());
this._unpair.send({ token });
}
cork() {
this._channel.cork();
}
uncork() {
this._channel.uncork();
}
async end() {
if (this._ending) return this._ending;
this._ending = EventEmitter.once(this, "close");
this._endMaybe();
return this._ending;
}
_endMaybe() {
if (this._ending && this._requests.size === 0) {
this._channel.close();
}
}
destroy(err) {
if (this._destroyed) return;
this._destroyed = true;
this._error = err || errors.CHANNEL_DESTROYED();
this._channel.close();
}
};
var BlindRelayRequest = class extends Readable {
constructor(client, isInitiator, token, stream) {
super();
this.client = client;
this.isInitiator = isInitiator;
this.token = token;
this.stream = stream;
}
_open(cb) {
if (this.client._destroyed) return cb(errors.CHANNEL_DESTROYED());
this.client._pair.send({
isInitiator: this.isInitiator,
token: this.token,
id: this.stream.id,
seq: 0
});
cb(null);
}
_destroy(cb) {
this.client._requests.delete(this.token.toString("hex"));
cb(null);
this.client._endMaybe();
}
};
exports.token = function token(buf = b4a.allocUnsafe(32)) {
sodium.randombytes_buf(buf);
return buf;
};
function noop() {
}
var m = exports.messages = {};
var flags = bitfield(7);
m.pair = {
preencode(state, m2) {
flags.preencode(state);
c.fixed32.preencode(state, m2.token);
c.uint.preencode(state, m2.id);
c.uint.preencode(state, m2.seq);
},
encode(state, m2) {
flags.encode(state, bits.of(m2.isInitiator));
c.fixed32.encode(state, m2.token);
c.uint.encode(state, m2.id);
c.uint.encode(state, m2.seq);
},
decode(state) {
const [isInitiator] = bits.iterator(flags.decode(state));
return {
isInitiator,
token: c.fixed32.decode(state),
id: c.uint.decode(state),
seq: c.uint.decode(state)
};
}
};
m.unpair = {
preencode(state, m2) {
flags.preencode(state);
c.fixed32.preencode(state, m2.token);
},
encode(state, m2) {
flags.encode(state, bits.of());
c.fixed32.encode(state, m2.token);
},
decode(state) {
flags.decode(state);
return {
token: c.fixed32.decode(state)
};
}
};
}
});
// ../../node_modules/hyperdht/lib/noise-wrap.js
var require_noise_wrap = __commonJS({
"../../node_modules/hyperdht/lib/noise-wrap.js"(exports, module) {
var NoiseSecretStream = require_secret_stream();
var NoiseHandshake = require_noise();
var curve = require_noise_curve_ed();
var c = require_compact_encoding();
var b4a = require_b4a();
var sodium = require_sodium_universal();
var m = require_messages();
var { NS } = require_constants5();
var { HANDSHAKE_UNFINISHED } = require_errors9();
var NOISE_PROLOUGE = NS.PEER_HANDSHAKE;
module.exports = class NoiseWrap {
constructor(keyPair, remotePublicKey) {
this.isInitiator = !!remotePublicKey;
this.remotePublicKey = remotePublicKey;
this.keyPair = keyPair;
this.handshake = new NoiseHandshake("IK", this.isInitiator, keyPair, { curve });
this.handshake.initialise(NOISE_PROLOUGE, remotePublicKey);
}
send(payload) {
const buf = c.encode(m.noisePayload, payload);
return this.handshake.send(buf);
}
recv(buf) {
const payload = c.decode(m.noisePayload, this.handshake.recv(buf));
this.remotePublicKey = b4a.toBuffer(this.handshake.rs);
return payload;
}
final() {
if (!this.handshake.complete) throw HANDSHAKE_UNFINISHED();
const holepunchSecret = b4a.allocUnsafe(32);
sodium.crypto_generichash(holepunchSecret, NS.PEER_HOLEPUNCH, this.handshake.hash);
return {
isInitiator: this.isInitiator,
publicKey: this.keyPair.publicKey,
streamId: this.streamId,
remotePublicKey: this.remotePublicKey,
remoteId: NoiseSecretStream.id(this.handshake.hash, !this.isInitiator),
holepunchSecret,
hash: b4a.toBuffer(this.handshake.hash),
rx: b4a.toBuffer(this.handshake.rx),
tx: b4a.toBuffer(this.handshake.tx)
};
}
};
}
});
// ../../node_modules/signal-promise/index.js
var require_signal_promise = __commonJS({
"../../node_modules/signal-promise/index.js"(exports, module) {
module.exports = class Signal {
constructor() {
this._resolve = null;
this._reject = null;
this._promise = null;
this._bind = bind.bind(this);
this._onerror = clear.bind(this);
this._onsuccess = clear.bind(this, null);
this._timers = /* @__PURE__ */ new Set();
}
wait(max) {
if (!this._promise) {
this._promise = new Promise(this._bind);
this._promise.then(this._onsuccess).catch(this._onerror);
}
if (max) return this._sleep(max);
return this._promise;
}
_sleep(max) {
const s = new Promise((resolve, reject) => {
const done = () => {
this._timers.delete(state);
resolve(true);
};
const id = setTimeout(done, max);
const state = { id, resolve, reject };
this._timers.add(state);
});
return s;
}
notify(err) {
if (!this._promise) return;
const resolve = this._resolve;
const reject = this._reject;
this._promise = null;
if (err) reject(err);
else resolve(true);
}
};
function clear(err) {
for (const { id, resolve, reject } of this._timers) {
clearTimeout(id);
if (err) reject(err);
else resolve(true);
}
this._timers.clear();
}
function bind(resolve, reject) {
this._resolve = resolve;
this._reject = reject;
}
}
});
// ../../node_modules/hyperdht/lib/sleeper.js
var require_sleeper = __commonJS({
"../../node_modules/hyperdht/lib/sleeper.js"(exports, module) {
module.exports = class Sleeper {
constructor() {
this._timeout = null;
this._resolve = null;
this._start = (resolve) => {
this._resolve = resolve;
};
this._trigger = () => {
if (this._resolve === null) return;
const resolve = this._resolve;
this._timeout = null;
this._resolve = null;
resolve();
};
}
pause(ms) {
const p = new Promise(this._start);
if (this._timeout !== null) {
clearTimeout(this._timeout);
this._trigger();
}
this._timeout = setTimeout(this._trigger, ms);
return p;
}
resume() {
if (this._timeout !== null) {
clearTimeout(this._timeout);
this._trigger();
}
}
};
}
});
// ../../node_modules/hyperdht/lib/announcer.js
var require_announcer = __commonJS({
"../../node_modules/hyperdht/lib/announcer.js"(exports, module) {
var safetyCatch = require_safety_catch();
var c = require_compact_encoding();
var Signal = require_signal_promise();
var { encodeUnslab } = require_encode();
var Sleeper = require_sleeper();
var m = require_messages();
var Persistent = require_persistent();
var { COMMANDS } = require_constants5();
var MIN_ACTIVE = 3;
module.exports = class Announcer {
constructor(dht, keyPair, target, opts = {}) {
this.dht = dht;
this.keyPair = keyPair;
this.target = target;
this.relays = [];
this.relayAddresses = [];
this.stopped = false;
this.suspended = false;
this.record = encodeUnslab(m.peer, { publicKey: keyPair.publicKey, relayAddresses: [] });
this.online = new Signal();
this._refreshing = false;
this._closestNodes = null;
this._active = null;
this._sleeper = new Sleeper();
this._resumed = new Signal();
this._signAnnounce = opts.signAnnounce || Persistent.signAnnounce;
this._signUnannounce = opts.signUnannounce || Persistent.signUnannounce;
this._updating = null;
this._activeQuery = null;
this._unannouncing = null;
this._serverRelays = [/* @__PURE__ */ new Map(), /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map()];
}
isRelay(addr) {
const id = addr.host + ":" + addr.port;
const [a, b, c2] = this._serverRelays;
return a.has(id) || b.has(id) || c2.has(id);
}
async suspend({ log = noop } = {}) {
if (this.suspended) return;
this.suspended = true;
log("Suspending announcer");
this.online.notify();
if (this._activeQuery) this._activeQuery.destroy();
this._sleeper.resume();
if (this._updating) await this._updating;
log("Suspending announcer (post update)");
if (this.suspended === false || this.stopped) return;
log("Suspending announcer (pre unannounce)");
await this._unannounceCurrent();
log("Suspending announcer (post unannounce)");
}
resume() {
if (!this.suspended) return;
this.suspended = false;
this.refresh();
this._sleeper.resume();
this._resumed.notify();
}
refresh() {
if (this.stopped) return;
this._refreshing = true;
}
async start() {
if (this.stopped) return;
this._active = this._runUpdate();
await this._active;
if (this.stopped) return;
this._active = this._background();
}
async stop() {
this.stopped = true;
this.online.notify();
this._sleeper.resume();
this._resumed.notify();
await this._active;
await this._unannounceCurrent();
}
async _unannounceCurrent() {
while (this._unannouncing !== null) await this._unannouncing;
const un = this._unannouncing = this._unannounceAll(this._serverRelays[2].values());
await this._unannouncing;
if (un === this._unannouncing) this._unannouncing = null;
}
async _background() {
while (!this.dht.destroyed && !this.stopped) {
try {
this._refreshing = false;
for (let i = 0; i < 100 && !this.stopped && !this._refreshing && !this.suspended; i++) {
const pings = [];
for (const node of this._serverRelays[2].values()) {
pings.push(this.dht.ping(node));
}
const active = await resolved(pings);
if (active < Math.min(pings.length, MIN_ACTIVE)) {
this.refresh();
}
if (this.stopped) return;
if (!this.suspended && !this._refreshing) await this._sleeper.pause(3e3);
}
while (!this.stopped && this.suspended) await this._resumed.wait();
if (!this.stopped) await this._runUpdate();
while (!this.dht.online && !this.stopped && !this.suspended) {
await this.online.wait();
}
} catch (err) {
safetyCatch(err);
}
}
}
async _runUpdate() {
this._updating = this._update();
await this._updating;
this._updating = null;
}
async _update() {
while (this._unannouncing) await this._unannouncing;
this._cycle();
const q = this._activeQuery = this.dht.findPeer(this.target, {
hash: false,
nodes: this._closestNodes
});
try {
await q.finished();
} catch {
}
this._activeQuery = null;
if (this.stopped || this.suspended) return;
const ann = [];
const replies = pickBest(q.closestReplies);
const relays = [];
const relayAddresses = [];
if (!this.dht.firewalled) {
const addr = this.dht.remoteAddress();
if (addr) relayAddresses.push(addr);
}
for (const msg of replies) {
ann.push(this._commit(msg, relays, relayAddresses));
}
await Promise.allSettled(ann);
if (this.stopped || this.suspended) return;
this._closestNodes = q.closestNodes;
this.relays = relays;
this.relayAddresses = relayAddresses;
const removed = [];
for (const [key, value] of this._serverRelays[1]) {
if (!this._serverRelays[2].has(key)) removed.push(value);
}
await this._unannounceAll(removed);
}
_unannounceAll(relays) {
const unann = [];
for (const r of relays) unann.push(this._unannounce(r));
return Promise.allSettled(unann);
}
async _unannounce(to) {
const unann = {
peer: {
publicKey: this.keyPair.publicKey,
relayAddresses: []
},
refresh: null,
signature: null
};
const { from, token, value } = await this.dht.request(
{
token: null,
command: COMMANDS.FIND_PEER,
target: this.target,
value: null
},
to
);
if (!token || !from.id || !value) return;
unann.signature = await this._signUnannounce(this.target, token, from.id, unann, this.keyPair);
await this.dht.request(
{
token,
command: COMMANDS.UNANNOUNCE,
target: this.target,
value: c.encode(m.announce, unann)
},
to
);
}
async _commit(msg, relays, relayAddresses) {
const ann = {
peer: {
publicKey: this.keyPair.publicKey,
relayAddresses: []
},
refresh: null,
signature: null
};
ann.signature = await this._signAnnounce(this.target, msg.token, msg.from.id, ann, this.keyPair);
const res = await this.dht.request(
{
token: msg.token,
command: COMMANDS.ANNOUNCE,
target: this.target,
value: c.encode(m.announce, ann)
},
msg.from
);
if (res.error !== 0) return;
if (relayAddresses.length < 3) relayAddresses.push({ host: msg.from.host, port: msg.from.port });
relays.push({ relayAddress: msg.from, peerAddress: msg.to });
this._serverRelays[2].set(msg.from.host + ":" + msg.from.port, msg.from);
}
_cycle() {
const tmp = this._serverRelays[0];
this._serverRelays[0] = this._serverRelays[1];
this._serverRelays[1] = this._serverRelays[2];
this._serverRelays[2] = tmp;
tmp.clear();
}
};
function resolved(ps) {
let replied = 0;
let ticks = ps.length + 1;
return new Promise((resolve) => {
for (const p of ps) p.then(push, tick);
tick();
function push(v) {
replied++;
tick();
}
function tick() {
if (--ticks === 0) resolve(replied);
}
});
}
function pickBest(replies) {
return replies.slice(0, 3);
}
function noop() {
}
}
});
// ../../node_modules/hyperdht/lib/crypto.js
var require_crypto = __commonJS({
"../../node_modules/hyperdht/lib/crypto.js"(exports, module) {
var sodium = require_sodium_universal();
var b4a = require_b4a();
function hash(data) {
const out = b4a.allocUnsafe(32);
sodium.crypto_generichash(out, data);
return out;
}
function unslabbedHash(data) {
const out = b4a.allocUnsafeSlow(32);
sodium.crypto_generichash(out, data);
return out;
}
function createKeyPair(seed) {
const publicKey = b4a.alloc(32);
const secretKey = b4a.alloc(64);
if (seed) sodium.crypto_sign_seed_keypair(publicKey, secretKey, seed);
else sodium.crypto_sign_keypair(publicKey, secretKey);
return { publicKey, secretKey };
}
module.exports = {
hash,
unslabbedHash,
createKeyPair
};
}
});
// ../../node_modules/hyperdht/lib/secure-payload.js
var require_secure_payload = __commonJS({
"../../node_modules/hyperdht/lib/secure-payload.js"(exports, module) {
var sodium = require_sodium_universal();
var b4a = require_b4a();
var { holepunchPayload } = require_messages();
module.exports = class HolepunchPayload {
constructor(holepunchSecret) {
this._sharedSecret = holepunchSecret;
this._localSecret = b4a.allocUnsafe(32);
sodium.randombytes_buf(this._localSecret);
}
decrypt(buffer) {
const state = { start: 24, end: buffer.byteLength - 16, buffer };
if (state.end <= state.start) return null;
const nonce = buffer.subarray(0, 24);
const msg = state.buffer.subarray(state.start, state.end);
const cipher = state.buffer.subarray(state.start);
if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, this._sharedSecret)) return null;
try {
return holepunchPayload.decode(state);
} catch {
return null;
}
}
encrypt(payload) {
const state = { start: 24, end: 24, buffer: null };
holepunchPayload.preencode(state, payload);
state.buffer = b4a.allocUnsafe(state.end + 16);
const nonce = state.buffer.subarray(0, 24);
const msg = state.buffer.subarray(state.start, state.end);
const cipher = state.buffer.subarray(state.start);
holepunchPayload.encode(state, payload);
sodium.randombytes_buf(nonce);
sodium.crypto_secretbox_easy(cipher, msg, nonce, this._sharedSecret);
return state.buffer;
}
token(addr) {
const out = b4a.allocUnsafe(32);
sodium.crypto_generichash(out, b4a.from(addr.host), this._localSecret);
return out;
}
};
}
});
// ../../node_modules/hyperdht/lib/nat.js
var require_nat = __commonJS({
"../../node_modules/hyperdht/lib/nat.js"(exports, module) {
var { FIREWALL } = require_constants5();
module.exports = class Nat {
constructor(dht, session, socket) {
this._samplesHost = [];
this._samplesFull = [];
this._visited = /* @__PURE__ */ new Map();
this._resolve = null;
this._minSamples = 4;
this._autoSampling = false;
this.dht = dht;
this.session = session;
this.socket = socket;
this.sampled = 0;
this.firewall = dht.firewalled ? FIREWALL.UNKNOWN : FIREWALL.OPEN;
this.addresses = null;
this.analyzing = new Promise((resolve) => {
this._resolve = resolve;
});
}
autoSample(retry = true) {
if (this._autoSampling) return;
this._autoSampling = true;
const self = this;
const socket = this.socket;
const maxPings = this._minSamples;
let skip = this.dht.nodes.length >= 8 ? 5 : 0;
let pending = 0;
for (let node = this.dht.nodes.latest; node && this.sampled + pending < maxPings; node = node.prev) {
if (skip > 0) {
skip--;
continue;
}
const ref = node.host + ":" + node.port;
if (this._visited.has(ref)) continue;
this._visited.set(ref, 1);
pending++;
this.session.ping(node, { socket, retry: false }).then(onpong, onskip);
}
pending++;
onskip();
function onpong(res) {
self.add(res.to, res.from);
onskip();
}
function onskip() {
if (--pending === 0 && self.sampled < self._minSamples) {
if (retry) {
self._autoSampling = false;
self.autoSample(false);
return;
}
self._resolve();
}
}
}
destroy() {
this._autoSampling = true;
this._minSamples = 0;
this._resolve();
}
unfreeze() {
this.frozen = false;
this._updateFirewall();
this._updateAddresses();
}
freeze() {
this.frozen = true;
}
_updateFirewall() {
if (!this.dht.firewalled) {
this.firewall = FIREWALL.OPEN;
return;
}
if (this.sampled < 3) return;
const max = this._samplesFull[0].hits;
if (max >= 3) {
this.firewall = FIREWALL.CONSISTENT;
return;
}
if (max === 1) {
this.firewall = FIREWALL.RANDOM;
return;
}
if (this._samplesHost.length === 1 && this.sampled > 3) {
this.firewall = FIREWALL.RANDOM;
return;
}
if (this._samplesHost.length > 1 && this._samplesFull[1].hits > 1) {
this.firewall = FIREWALL.CONSISTENT;
return;
}
if (this.sampled > 4) {
this.firewall = FIREWALL.RANDOM;
}
}
_updateAddresses() {
if (this.firewall === FIREWALL.UNKNOWN) {
this.addresses = null;
return;
}
if (this.firewall === FIREWALL.RANDOM) {
this.addresses = [this._samplesHost[0]];
return;
}
if (this.firewall === FIREWALL.CONSISTENT) {
this.addresses = [];
for (const addr of this._samplesFull) {
if (addr.hits >= 2 || this.addresses.length < 2) this.addresses.push(addr);
}
}
}
update() {
if (this.dht.firewalled && this.firewall === FIREWALL.OPEN) {
this.firewall = FIREWALL.UNKNOWN;
}
this._updateFirewall();
this._updateAddresses();
}
add(addr, from) {
const ref = from.host + ":" + from.port;
if (this._visited.get(ref) === 2) return;
this._visited.set(ref, 2);
addSample(this._samplesHost, addr.host, 0);
addSample(this._samplesFull, addr.host, addr.port);
if ((++this.sampled >= 3 || !this.dht.firewalled) && !this.frozen) {
this.update();
}
if (this.firewall === FIREWALL.CONSISTENT || this.firewall === FIREWALL.OPEN) {
this._resolve();
} else if (this.sampled >= this._minSamples) {
this._resolve();
}
}
};
function addSample(samples, host, port) {
for (let i = 0; i < samples.length; i++) {
const s = samples[i];
if (s.port !== port || s.host !== host) continue;
s.hits++;
for (; i > 0; i--) {
const prev = samples[i - 1];
if (prev.hits >= s.hits) return;
samples[i - 1] = s;
samples[i] = prev;
}
return;
}
samples.push({
host,
port,
hits: 1
});
}
}
});
// ../../node_modules/hyperdht/lib/holepuncher.js
var require_holepuncher = __commonJS({
"../../node_modules/hyperdht/lib/holepuncher.js"(exports, module) {
var b4a = require_b4a();
var Nat = require_nat();
var Sleeper = require_sleeper();
var { FIREWALL } = require_constants5();
var BIRTHDAY_SOCKETS = 256;
var HOLEPUNCH = b4a.from([0]);
var HOLEPUNCH_TTL = 5;
var DEFAULT_TTL = 64;
var MAX_REOPENS = 3;
module.exports = class Holepuncher {
constructor(dht, session, isInitiator, remoteFirewall = FIREWALL.UNKNOWN) {
const holder = dht._socketPool.acquire();
this.dht = dht;
this.session = session;
this.nat = new Nat(dht, session, holder.socket);
this.nat.autoSample();
this.isInitiator = isInitiator;
this.onconnect = noop;
this.onabort = noop;
this.punching = false;
this.connected = false;
this.destroyed = false;
this.randomized = false;
this.remoteFirewall = remoteFirewall;
this.remoteAddresses = [];
this.remoteHolepunching = false;
this._sleeper = new Sleeper();
this._reopening = null;
this._timeout = null;
this._punching = null;
this._allHolders = [];
this._holder = this._addRef(holder);
}
get socket() {
return this._holder.socket;
}
updateRemote({ punching, firewall, addresses, verified }) {
const remoteAddresses = [];
if (addresses) {
for (const addr of addresses) {
remoteAddresses.push({
host: addr.host,
port: addr.port,
verified: verified === addr.host || this._isVerified(addr.host)
});
}
}
this.remoteFirewall = firewall;
this.remoteAddresses = remoteAddresses;
this.remoteHolepunching = punching;
}
_isVerified(host) {
for (const addr of this.remoteAddresses) {
if (addr.verified && addr.host === host) {
return true;
}
}
return false;
}
ping(addr, socket = this._holder.socket) {
return holepunch(socket, addr, false);
}
openSession(addr, socket = this._holder.socket) {
return holepunch(socket, addr, true);
}
async analyze(allowReopen) {
await this.nat.analyzing;
if (this._unstable()) {
if (!allowReopen) return false;
if (!this._reopening) this._reopening = this._reopen();
return this._reopening;
}
return true;
}
_unstable() {
const firewall = this.nat.firewall;
return this.remoteFirewall >= FIREWALL.RANDOM && firewall >= FIREWALL.RANDOM || firewall === FIREWALL.UNKNOWN;
}
_reset() {
const prev = this._holder;
this._allHolders.pop();
this._holder = this._addRef(this.dht._socketPool.acquire());
prev.release();
this.nat.destroy();
this.nat = new Nat(this.dht, this.session, this._holder.socket);
this.nat.autoSample();
}
_addRef(ref) {
this._allHolders.push(ref);
ref.onholepunchmessage = (msg, rinfo) => this._onholepunchmessage(msg, rinfo, ref);
return ref;
}
_onholepunchmessage(_, addr, ref) {
if (!this.isInitiator) {
holepunch(ref.socket, addr, false);
return;
}
if (this.connected) return;
this.connected = true;
this.punching = false;
for (const r of this._allHolders) {
if (r === ref) continue;
r.release();
}
this._allHolders[0] = ref;
while (this._allHolders.length > 1) this._allHolders.pop();
this._decrementRandomized();
this.onconnect(ref.socket, addr.port, addr.host);
}
_done() {
return this.destroyed || this.connected;
}
async _reopen() {
for (let i = 0; this._unstable() && i < MAX_REOPENS && !this._done() && !this.punching; i++) {
this._reset();
await this.nat.analyzing;
}
return coerceFirewall(this.nat.firewall) === FIREWALL.CONSISTENT;
}
punch() {
if (!this._punching) this._punching = this._punch();
return this._punching;
}
async _punch() {
if (this._done() || !this.remoteAddresses.length) return false;
this.punching = true;
const local = coerceFirewall(this.nat.firewall);
const remote = coerceFirewall(this.remoteFirewall);
let remoteVerifiedAddress = null;
for (const addr of this.remoteAddresses) {
if (addr.verified) {
remoteVerifiedAddress = addr;
break;
}
}
if (local === FIREWALL.CONSISTENT && remote === FIREWALL.CONSISTENT) {
this.dht.stats.punches.consistent++;
this._consistentProbe();
return true;
}
if (!remoteVerifiedAddress) return false;
if (local === FIREWALL.CONSISTENT && remote >= FIREWALL.RANDOM) {
this.dht.stats.punches.random++;
this._incrementRandomized();
this._randomProbes(remoteVerifiedAddress);
return true;
}
if (local >= FIREWALL.RANDOM && remote === FIREWALL.CONSISTENT) {
this.dht.stats.punches.random++;
this._incrementRandomized();
await this._openBirthdaySockets(remoteVerifiedAddress);
if (this.punching) this._keepAliveRandomNat(remoteVerifiedAddress);
return true;
}
return false;
}
// Note that this never throws so it is safe to run in the background
async _consistentProbe() {
if (!this.isInitiator) await this._sleeper.pause(1e3);
let tries = 0;
while (this.punching && tries++ < 10) {
for (const addr of this.remoteAddresses) {
if (!addr.verified && (tries & 3) !== 0) continue;
await holepunch(this._holder.socket, addr, false);
}
if (this.punching) await this._sleeper.pause(1e3);
}
this._autoDestroy();
}
// Note that this never throws so it is safe to run in the background
async _randomProbes(remoteAddr) {
let tries = 1750;
while (this.punching && tries-- > 0) {
const addr = { host: remoteAddr.host, port: randomPort() };
await holepunch(this._holder.socket, addr, false);
if (this.punching) await this._sleeper.pause(20);
}
this._autoDestroy();
}
// Note that this never throws so it is safe to run in the background
async _keepAliveRandomNat(remoteAddr) {
let i = 0;
let lowTTLRounds = 1;
await this._sleeper.pause(100);
let tries = 1750;
while (this.punching && tries-- > 0) {
if (i === this._allHolders.length) {
i = 0;
if (lowTTLRounds > 0) lowTTLRounds--;
}
await holepunch(this._allHolders[i++].socket, remoteAddr, lowTTLRounds > 0);
if (this.punching) await this._sleeper.pause(20);
}
this._autoDestroy();
}
async _openBirthdaySockets(remoteAddr) {
while (this.punching && this._allHolders.length < BIRTHDAY_SOCKETS) {
const ref = this._addRef(this.dht._socketPool.acquire());
await holepunch(ref.socket, remoteAddr, HOLEPUNCH_TTL);
}
}
_autoDestroy() {
if (!this.connected) this.destroy();
}
_incrementRandomized() {
if (!this.randomized) {
this.randomized = true;
this.dht._randomPunches++;
}
}
_decrementRandomized() {
if (this.randomized) {
this.dht._lastRandomPunch = Date.now();
this.randomized = false;
this.dht._randomPunches--;
}
}
destroy() {
if (this.destroyed) return;
this.destroyed = true;
this.punching = false;
for (const ref of this._allHolders) ref.release();
this._allHolders = [];
this.nat.destroy();
if (!this.connected) {
this._decrementRandomized();
this.onabort();
}
}
static ping(socket, addr) {
return holepunch(socket, addr, false);
}
static localAddresses(socket) {
return localAddresses(socket);
}
static matchAddress(myAddresses, externalAddresses) {
return matchAddress(myAddresses, externalAddresses);
}
};
function holepunch(socket, addr, lowTTL) {
return socket.send(HOLEPUNCH, addr.port, addr.host, lowTTL ? HOLEPUNCH_TTL : DEFAULT_TTL);
}
function randomPort() {
return 1e3 + Math.random() * 64536 | 0;
}
function coerceFirewall(fw) {
return fw === FIREWALL.OPEN ? FIREWALL.CONSISTENT : fw;
}
function localAddresses(socket) {
const addrs = [];
const { host, port } = socket.address();
if (host === "127.0.0.1") return [{ host, port }];
for (const n of socket.udx.networkInterfaces()) {
if (n.family !== 4 || n.internal) continue;
addrs.push({ host: n.host, port });
}
if (addrs.length === 0) {
addrs.push({ host: "127.0.0.1", port });
}
return addrs;
}
function matchAddress(localAddresses2, remoteLocalAddresses) {
if (remoteLocalAddresses.length === 0) return null;
let best = { segment: 1, addr: null };
for (const localAddress of localAddresses2) {
const a = localAddress.host.split(".");
for (const remoteAddress of remoteLocalAddresses) {
const b = remoteAddress.host.split(".");
if (a[0] === b[0]) {
if (best.segment === 1) best = { segment: 2, addr: remoteAddress };
if (a[1] === b[1]) {
if (best.segment === 2) best = { segment: 3, addr: remoteAddress };
if (a[2] === b[2]) return remoteAddress;
}
}
}
}
return best.addr;
}
function noop() {
}
}
});
// ../../node_modules/bogon/index.js
var require_bogon = __commonJS({
"../../node_modules/bogon/index.js"(exports, module) {
var b4a = require_b4a();
var c = require_compact_encoding();
var net = require_compact_encoding_net();
module.exports = exports = function isBogon(ip) {
return isBogonIP(ensureBuffer(ip));
};
exports.isBogon = exports;
exports.isPrivate = function isPrivate(ip) {
return isPrivateIP(ensureBuffer(ip));
};
exports.isReserved = function isReserved(ip) {
return isReservedIP(ensureBuffer(ip));
};
function isBogonIP(ip) {
return isPrivateIP(ip) || isReservedIP(ip);
}
function isPrivateIP(ip) {
return ip.byteLength === 4 ? isPrivateIPv4(ip) : false;
}
function isPrivateIPv4(ip) {
return (
// 10.0.0.0/8 Private-use networks
ip[0] === 10 || // 100.64.0.0/10 Carrier-grade NAT
ip[0] === 100 && ip[1] >= 64 && ip[1] <= 127 || // 127.0.0.0/8 Loopback + Name collision occurrence (127.0.53.53)
ip[0] === 127 || // 169.254.0.0/16 Link local
ip[0] === 169 && ip[1] === 254 || // 172.16.0.0/12 Private-use networks
ip[0] === 172 && ip[1] >= 16 && ip[1] <= 31 || // 192.168.0.0/16 Private-use networks
ip[0] === 192 && ip[1] === 168
);
}
function isReservedIP(ip) {
return ip.byteLength === 4 ? isReservedIPv4(ip) : isReservedIPv6(ip);
}
function isReservedIPv4(ip) {
return (
// 0.0.0.0/8 "This" network
ip[0] === 0 || // 192.0.0.0/24 IETF protocol assignments
ip[0] === 192 && ip[1] === 0 && ip[2] === 0 || // 192.0.2.0/24 TEST-NET-1
ip[0] === 192 && ip[1] === 0 && ip[2] === 2 || // 198.18.0.0/15 Network interconnect device benchmark testing
ip[0] === 198 && ip[1] >= 18 && ip[1] <= 19 || // 198.51.100.0/24 TEST-NET-2
ip[0] === 198 && ip[1] === 51 && ip[2] === 100 || // 203.0.113.0/24 TEST-NET-3
ip[0] === 203 && ip[1] === 0 && ip[2] === 113 || // 224.0.0.0/4 Multicast
ip[0] >= 224 && ip[0] <= 239 || // 240.0.0.0/4 Reserved for future use
ip[0] >= 240 || // 255.255.255.255/32
ip[0] === 255 && ip[1] === 255 && ip[2] === 255 && ip[3] === 255
);
}
function isReservedIPv6(ip) {
return (
// ::/128 Node-scope unicast unspecified address
// ::1/128 Node-scope unicast loopback address
ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 && ip[10] === 0 && ip[11] === 0 && ip[12] === 0 && ip[13] === 0 && ip[14] === 0 && ip[15] <= 1 || // ::ffff:0:0/96 IPv4-mapped addresses
// ::/96 IPv4-compatible addresses
ip[0] === 0 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0 && ip[8] === 0 && ip[9] === 0 && (ip[10] === 0 || ip[10] === 255) && (ip[11] === 0 || ip[11] === 255) || // 100::/64 Remotely triggered black hole addresses
ip[0] === 1 && ip[1] === 0 && ip[2] === 0 && ip[3] === 0 && ip[4] === 0 && ip[5] === 0 && ip[6] === 0 && ip[7] === 0 || // 2001:10::/28 Overlay routable cryptographic hash identifiers (ORCHID)
ip[0] === 32 && ip[1] === 1 && ip[2] === 0 && ip[3] >= 16 && ip[3] <= 31 || // 2001:20::/28 Overlay routable cryptographic hash identifiers version 2 (ORCHIDv2)
ip[0] === 32 && ip[1] === 1 && ip[2] === 0 && ip[3] >= 32 && ip[3] <= 47 || // 2001:db8::/32 Documentation prefix
ip[0] === 32 && ip[1] === 1 && ip[2] === 13 && ip[3] === 184 || // fc00::/7 Unique local addresses (ULA)
ip[0] >= 252 && ip[0] <= 253 || // fe80::/10 Link-local unicast
ip[0] === 254 && ip[1] >= 128 && ip[1] <= 191 || // ff00::/8 Multicast
ip[0] === 255
);
}
var state = c.state(0, 0, b4a.allocUnsafe(1 + 16));
function ensureBuffer(ip) {
if (b4a.isBuffer(ip)) return ip;
net.ip.preencode(state, ip);
net.ip.encode(state, ip);
const buffer = state.buffer.subarray(1, state.end);
state.start = 0;
state.end = 0;
return buffer;
}
}
});
// ../../node_modules/hyperdht/lib/server.js
var require_server = __commonJS({
"../../node_modules/hyperdht/lib/server.js"(exports, module) {
var { EventEmitter } = require_bare_node_events();
var safetyCatch = require_safety_catch();
var NoiseSecretStream = require_secret_stream();
var b4a = require_b4a();
var relay = require_blind_relay();
var NoiseWrap = require_noise_wrap();
var Announcer = require_announcer();
var { FIREWALL, ERROR } = require_constants5();
var { unslabbedHash } = require_crypto();
var SecurePayload = require_secure_payload();
var Holepuncher = require_holepuncher();
var { isPrivate } = require_bogon();
var { ALREADY_LISTENING, NODE_DESTROYED, KEYPAIR_ALREADY_USED } = require_errors9();
var HANDSHAKE_CLEAR_WAIT = 1e4;
var HANDSHAKE_INITIAL_TIMEOUT = 1e4;
module.exports = class Server extends EventEmitter {
constructor(dht, opts = {}) {
super();
this.dht = dht;
this.target = null;
this.closed = false;
this.firewall = opts.firewall || (() => false);
this.holepunch = opts.holepunch || (() => true);
this.relayThrough = opts.relayThrough || null;
this.relayKeepAlive = opts.relayKeepAlive || 5e3;
this.pool = opts.pool || null;
this.createHandshake = opts.createHandshake || defaultCreateHandshake;
this.createSecretStream = opts.createSecretStream || defaultCreateSecretStream;
this.suspended = false;
this.handshakeClearWait = opts.handshakeClearWait || HANDSHAKE_CLEAR_WAIT;
this._shareLocalAddress = opts.shareLocalAddress !== false;
this._reusableSocket = !!opts.reusableSocket;
this._neverPunch = opts.holepunch === false;
this._keyPair = null;
this._announcer = null;
this._connects = /* @__PURE__ */ new Map();
this._holepunches = [];
this._listening = null;
this._closing = null;
}
get listening() {
return this._listening !== null;
}
get publicKey() {
return this._keyPair && this._keyPair.publicKey;
}
get relayAddresses() {
return this._announcer ? this._announcer.relayAddresses : [];
}
onconnection(encryptedSocket) {
this.emit("connection", encryptedSocket);
}
async suspend({ log = noop } = {}) {
log("Suspending hyperdht server");
if (this._listening !== null) await this._listening;
log("Suspending hyperdht server (post listening)");
this.suspended = true;
this._clearAll();
return this._announcer ? this._announcer.suspend({ log }) : Promise.resolve();
}
async resume() {
if (this._listening !== null) await this._listening;
this.suspended = false;
return this._announcer ? this._announcer.resume() : Promise.resolve();
}
address() {
if (!this._keyPair) return null;
return {
publicKey: this._keyPair.publicKey,
host: this.dht.host,
port: this.dht.port
};
}
close() {
if (this._closing) return this._closing;
this._closing = this._close();
return this._closing;
}
_gc() {
this.dht.listening.delete(this);
if (this.target) this.dht._router.delete(this.target);
}
async _stopListening() {
try {
if (this._announcer) await this._announcer.stop();
} catch {
}
this._announcer = null;
this._listening = null;
this._keyPair = null;
}
async _close() {
if (this._listening === null) {
this.closed = true;
this.emit("close");
return;
}
try {
await this._listening;
} catch {
}
this._gc();
this._clearAll();
await this._stopListening();
this.closed = true;
this.emit("close");
}
_clearAll() {
while (this._holepunches.length > 0) {
const h = this._holepunches.pop();
if (h && h.puncher) h.puncher.destroy();
if (h && h.clearing) clearTimeout(h.clearing);
if (h && h.prepunching) clearTimeout(h.prepunching);
if (h && h.rawStream) h.rawStream.destroy();
}
this._connects.clear();
}
async listen(keyPair = this.dht.defaultKeyPair, opts = {}) {
if (this._listening !== null) throw ALREADY_LISTENING();
if (this.dht.destroyed) throw NODE_DESTROYED();
this._listening = this._listen(keyPair, opts);
await this._listening;
return this;
}
async _listen(keyPair, opts) {
this.dht.listening.add(this);
try {
await this.dht.bind();
if (this._closing) return;
for (const s of this.dht.listening) {
if (s._keyPair && b4a.equals(s._keyPair.publicKey, keyPair.publicKey)) {
throw KEYPAIR_ALREADY_USED();
}
}
this.target = unslabbedHash(keyPair.publicKey);
this._keyPair = keyPair;
this._announcer = new Announcer(this.dht, keyPair, this.target, opts);
this.dht._router.set(this.target, {
relay: null,
record: this._announcer.record,
onpeerhandshake: this._onpeerhandshake.bind(this),
onpeerholepunch: this._onpeerholepunch.bind(this)
});
this._localAddresses().catch(safetyCatch);
await this._announcer.start();
} catch (err) {
await this._stopListening();
this._gc();
throw err;
}
if (this._closing) return;
if (this.suspended) await this._announcer.suspend();
if (this._closing) return;
if (this.dht.destroyed) throw NODE_DESTROYED();
if (this.pool) this.pool._attachServer(this);
this.emit("listening");
}
refresh() {
if (this._announcer && !this.suspended) this._announcer.refresh();
}
notifyOnline() {
if (this._announcer) this._announcer.online.notify();
}
_localAddresses() {
return this.dht.validateLocalAddresses(Holepuncher.localAddresses(this.dht.io.serverSocket));
}
async _addHandshake(k, noise, clientAddress, { from, to: serverAddress, socket }, direct) {
let id = this._holepunches.indexOf(null);
if (id === -1) id = this._holepunches.push(null) - 1;
const hs = {
round: 0,
reply: null,
puncher: null,
payload: null,
rawStream: null,
encryptedSocket: null,
prepunching: null,
firewalled: true,
clearing: null,
onsocket: null,
aborted: false,
// Relay state
relayTimeout: null,
relayToken: null,
relaySocket: null,
relayClient: null,
relayPaired: false
};
this._holepunches[id] = hs;
const handshake = this.createHandshake(this._keyPair, null);
let remotePayload;
try {
remotePayload = await handshake.recv(noise);
} catch (err) {
safetyCatch(err);
this._clearLater(hs, id, k);
return null;
}
if (this._closing || this.suspended) return null;
try {
hs.firewalled = await this.firewall(handshake.remotePublicKey, remotePayload, clientAddress);
} catch (err) {
safetyCatch(err);
}
if (this._closing || this.suspended) return null;
if (hs.firewalled) {
this._clearLater(hs, id, k);
return null;
}
const error = remotePayload.version === 1 ? remotePayload.udx ? ERROR.NONE : ERROR.ABORTED : ERROR.VERSION_MISMATCH;
const addresses = [];
const ourRemoteAddr = this.dht.remoteAddress();
const ourLocalAddrs = this._shareLocalAddress ? await this._localAddresses() : null;
if (this._closing || this.suspended) return null;
if (ourRemoteAddr) addresses.push(ourRemoteAddr);
if (ourLocalAddrs) addresses.push(...ourLocalAddrs);
if (error === ERROR.NONE) {
let autoDestroy2 = function() {
if (hs.puncher) hs.puncher.destroy();
};
var autoDestroy = autoDestroy2;
hs.rawStream = this.dht.createRawStream({
framed: true,
firewall(socket2, port, host) {
if (!(port > 0 && port < 65536)) return true;
if (hs.relaySocket && isRelay(hs.relaySocket, socket2, port, host)) {
return false;
}
hs.onsocket(socket2, port, host);
return false;
}
});
hs.rawStream.on("error", autoDestroy2);
const onrawstreamclose = () => {
if (this._closing) return;
this._clearLater(hs, id, k);
};
hs.rawStream.on("close", onrawstreamclose);
hs.onsocket = (socket2, port, host) => {
if (hs.rawStream === null) return;
this._clearLater(hs, id, k);
if (hs.prepunching) {
clearTimeout(hs.prepunching);
hs.prepunching = null;
}
if (this._reusableSocket && remotePayload.udx.reusableSocket) {
this.dht._socketPool.routes.add(handshake.remotePublicKey, hs.rawStream);
}
hs.rawStream.removeListener("error", autoDestroy2);
hs.rawStream.removeListener("close", onrawstreamclose);
if (hs.rawStream.connected) {
const remoteChanging = hs.rawStream.changeRemote(socket2, remotePayload.udx.id, port, host);
if (remoteChanging) remoteChanging.catch(safetyCatch);
} else {
hs.rawStream.connect(socket2, remotePayload.udx.id, port, host);
hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, {
handshake: h,
keepAlive: this.dht.connectionKeepAlive
});
this.onconnection(hs.encryptedSocket);
}
if (hs.puncher) {
hs.puncher.onabort = noop;
hs.puncher.destroy();
}
hs.rawStream = null;
};
}
const relayAddresses = this.relayAddresses;
const relayThrough = selectRelay(this.relayThrough);
if (relayThrough) hs.relayToken = relay.token();
try {
hs.reply = await handshake.send({
error,
firewall: ourRemoteAddr ? FIREWALL.OPEN : FIREWALL.UNKNOWN,
holepunch: ourRemoteAddr ? null : { id, relays: this._announcer.relays },
addresses4: addresses,
addresses6: null,
udx: {
reusableSocket: this._reusableSocket,
id: hs.rawStream ? hs.rawStream.id : 0,
seq: 0
},
secretStream: {},
relayThrough: relayThrough ? { publicKey: relayThrough, token: hs.relayToken } : null,
relayAddresses: relayAddresses.length ? relayAddresses : null
});
} catch (err) {
safetyCatch(err);
if (hs.rawStream) hs.rawStream.destroy();
this._clearLater(hs, id, k);
return null;
}
if (this._closing || this.suspended) {
if (hs.rawStream) hs.rawStream.destroy();
return null;
}
const h = handshake.final();
if (error !== ERROR.NONE) {
if (hs.rawStream) hs.rawStream.destroy();
this._clearLater(hs, id, k);
return hs;
}
if (remotePayload.firewall === FIREWALL.OPEN || direct) {
const sock = direct ? socket : this.dht.socket;
this.dht.stats.punches.open++;
hs.onsocket(sock, clientAddress.port, clientAddress.host);
return hs;
}
if (relayThrough || remotePayload.relayThrough) {
this._relayConnection(hs, relayThrough, remotePayload, h);
}
const onabort = () => {
hs.aborted = true;
if (hs.prepunching) clearTimeout(hs.prepunching);
hs.prepunching = null;
if (hs.rawStream.destroyed) {
this._clearLater(hs, id, k);
return;
}
hs.rawStream.on("close", () => this._clearLater(hs, id, k));
if (hs.relayToken === null) hs.rawStream.destroy();
};
if (!direct && clientAddress.host === serverAddress.host) {
const clientAddresses = remotePayload.addresses4.filter(onlyPrivateHosts);
if (clientAddresses.length > 0 && this._shareLocalAddress) {
const myAddresses = await this._localAddresses();
const addr = Holepuncher.matchAddress(myAddresses, clientAddresses);
if (addr) {
hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT);
return hs;
}
}
}
if (this._closing || this.suspended) return null;
if (ourRemoteAddr || this._neverPunch) {
hs.prepunching = setTimeout(onabort, HANDSHAKE_INITIAL_TIMEOUT);
return hs;
}
hs.payload = new SecurePayload(h.holepunchSecret);
hs.puncher = new Holepuncher(this.dht, this.dht.session(), false, remotePayload.firewall);
hs.puncher.onconnect = hs.onsocket;
hs.puncher.onabort = onabort;
hs.prepunching = setTimeout(hs.puncher.destroy.bind(hs.puncher), HANDSHAKE_INITIAL_TIMEOUT);
return hs;
}
_clearLater(hs, id, k) {
if (hs.clearing) return;
hs.clearing = setTimeout(() => this._clear(hs, id, k), this.handshakeClearWait);
}
_clear(hs, id, k) {
if (id >= this._holepunches.length || this._holepunches[id] !== hs) return;
if (hs.clearing) clearTimeout(hs.clearing);
this._holepunches[id] = null;
while (this._holepunches.length > 0 && this._holepunches[this._holepunches.length - 1] === null) {
this._holepunches.pop();
}
this._connects.delete(k);
}
async _onpeerhandshake({ noise, peerAddress }, req) {
const k = b4a.toString(noise, "hex");
let p = this._connects.get(k);
if (!p) {
p = this._addHandshake(k, noise, peerAddress || req.from, req, !peerAddress);
this._connects.set(k, p);
}
const h = await p;
if (!h) return null;
if (this._closing !== null || this.suspended) return null;
return { socket: h.puncher && h.puncher.socket, noise: h.reply };
}
async _onpeerholepunch({ id, peerAddress, payload }, req) {
const h = id < this._holepunches.length ? this._holepunches[id] : null;
if (!h) return null;
if (!peerAddress || this._closing !== null || this.suspended) return null;
const p = h.puncher;
if (!p || !p.socket) return this._abort(h);
const remotePayload = h.payload.decrypt(payload);
if (!remotePayload) return null;
const isServerRelay = this._announcer.isRelay(req.from);
const { error, firewall, round, punching, addresses, remoteAddress, remoteToken } = remotePayload;
if (error !== ERROR.NONE) {
if (round >= h.round) h.round = round;
return this._abort(h);
}
const token = h.payload.token(peerAddress);
const echoed = isServerRelay && !!remoteToken && b4a.equals(token, remoteToken);
if (req.socket === p.socket) {
p.nat.add(req.to, req.from);
}
if (round >= h.round) {
h.round = round;
p.updateRemote({ punching, firewall, addresses, verified: echoed ? peerAddress.host : null });
}
let stable = await p.analyze(false);
if (p.destroyed) return null;
if (!p.remoteHolepunching && !stable) {
stable = await p.analyze(true);
if (p.destroyed) return null;
if (!stable) return this._abort(h);
}
if (isConsistent(p.nat.firewall) && remoteAddress && hasSameAddr(p.nat.addresses, remoteAddress)) {
await p.ping(peerAddress);
if (p.destroyed) return null;
}
if (p.remoteHolepunching) {
if (!this.holepunch(p.remoteFirewall, p.nat.firewall, p.remoteAddresses, p.nat.addresses)) {
return p.destroyed ? null : this._abort(h);
}
if (h.prepunching) {
clearTimeout(h.prepunching);
h.prepunching = null;
}
if (p.remoteFirewall >= FIREWALL.RANDOM || p.nat.firewall >= FIREWALL.RANDOM) {
if (this.dht._randomPunches >= this.dht._randomPunchLimit || Date.now() - this.dht._lastRandomPunch < this.dht._randomPunchInterval) {
if (!h.relayToken) return this._abort(h, ERROR.TRY_LATER);
return {
socket: p.socket,
payload: h.payload.encrypt({
error: ERROR.TRY_LATER,
firewall: p.nat.firewall,
round: h.round,
connected: p.connected,
punching: p.punching,
addresses: p.nat.addresses,
remoteAddress: null,
token: isServerRelay ? token : null,
remoteToken: remotePayload.token
})
};
}
}
const punching2 = await p.punch();
if (p.destroyed) return null;
if (!punching2) return this._abort(h);
}
if (p.nat.firewall !== FIREWALL.UNKNOWN) {
p.nat.freeze();
}
return {
socket: p.socket,
payload: h.payload.encrypt({
error: ERROR.NONE,
firewall: p.nat.firewall,
round: h.round,
connected: p.connected,
punching: p.punching,
addresses: p.nat.addresses,
remoteAddress: null,
token: isServerRelay ? token : null,
remoteToken: remotePayload.token
})
};
}
_abort(h, error = ERROR.ABORTED) {
if (!h.payload) {
if (h.puncher) h.puncher.destroy();
return null;
}
const payload = h.payload.encrypt({
error,
firewall: FIREWALL.UNKNOWN,
round: h.round,
connected: false,
punching: false,
addresses: null,
remoteAddress: null,
token: null,
remoteToken: null
});
h.puncher.destroy();
return { socket: this.dht.socket, payload };
}
_relayConnection(hs, relayThrough, remotePayload, h) {
this.dht.stats.relaying.attempts++;
let isInitiator;
let publicKey;
let token;
if (relayThrough) {
isInitiator = true;
publicKey = relayThrough;
token = hs.relayToken;
} else {
isInitiator = false;
publicKey = remotePayload.relayThrough.publicKey;
token = remotePayload.relayThrough.token;
}
hs.relayToken = token;
hs.relaySocket = this.dht.connect(publicKey);
hs.relaySocket.setKeepAlive(this.relayKeepAlive);
hs.relayClient = relay.Client.from(hs.relaySocket, { id: hs.relaySocket.publicKey });
hs.relayTimeout = setTimeout(onabort, 15e3);
hs.relayClient.pair(isInitiator, token, hs.rawStream).on("error", onabort).on("data", (remoteId) => {
if (hs.relayTimeout) clearRelayTimeout(hs);
if (hs.rawStream === null) {
onabort(null);
return;
}
hs.relayPaired = true;
this.dht.stats.relaying.successes++;
if (hs.prepunching) clearTimeout(hs.prepunching);
hs.prepunching = null;
const { remotePort, remoteHost, socket } = hs.relaySocket.rawStream;
hs.rawStream.on("close", () => hs.relaySocket.destroy()).connect(socket, remoteId, remotePort, remoteHost);
hs.encryptedSocket = this.createSecretStream(false, hs.rawStream, { handshake: h });
this.onconnection(hs.encryptedSocket);
});
const dht = this.dht;
function onabort() {
if (!hs.relayPaired) dht.stats.relaying.aborts++;
if (hs.relayTimeout) clearRelayTimeout(hs);
const socket = hs.relaySocket;
hs.relayToken = null;
hs.relaySocket = null;
if (socket) socket.destroy();
if (hs.aborted && hs.rawStream) hs.rawStream.destroy();
}
}
};
function clearRelayTimeout(hs) {
clearTimeout(hs.relayTimeout);
hs.relayTimeout = null;
}
function isConsistent(fw) {
return fw === FIREWALL.OPEN || fw === FIREWALL.CONSISTENT;
}
function hasSameAddr(addrs, other) {
if (addrs === null) return false;
for (const addr of addrs) {
if (addr.port === other.port && addr.host === other.host) return true;
}
return false;
}
function defaultCreateHandshake(keyPair, remotePublicKey) {
return new NoiseWrap(keyPair, remotePublicKey);
}
function defaultCreateSecretStream(isInitiator, rawStream, opts) {
return new NoiseSecretStream(isInitiator, rawStream, opts);
}
function onlyPrivateHosts(addr) {
return isPrivate(addr.host);
}
function isRelay(relaySocket, socket, port, host) {
const stream = relaySocket.rawStream;
if (!stream) return false;
if (stream.socket !== socket) return false;
return port === stream.remotePort && host === stream.remoteHost;
}
function selectRelay(relayThrough) {
if (typeof relayThrough === "function") relayThrough = relayThrough();
if (relayThrough === null) return null;
if (Array.isArray(relayThrough)) {
return relayThrough[Math.floor(Math.random() * relayThrough.length)];
}
return relayThrough;
}
function noop() {
}
}
});
// ../../node_modules/hyperdht/lib/semaphore.js
var require_semaphore = __commonJS({
"../../node_modules/hyperdht/lib/semaphore.js"(exports, module) {
var DONE = Promise.resolve(true);
var DESTROYED = Promise.resolve(false);
module.exports = class Semaphore {
constructor(limit = 1) {
this.limit = limit;
this.active = 0;
this.waiting = [];
this.flushedPromise = null;
this.flushedResolve = null;
this.destroyed = false;
this._onwait = this._queueWaiting.bind(this);
this._onflush = this._queueFlushed.bind(this);
}
_queueWaiting(resolve) {
this.waiting.push(resolve);
}
_queueFlushed(resolve) {
this.flushedResolve = resolve;
}
wait() {
if (this.destroyed === true) return DESTROYED;
if (this.active < this.limit && this.waiting.length === 0) {
this.active++;
return DONE;
}
return new Promise(this._onwait);
}
signal() {
if (this.destroyed === true) return;
this.active--;
while (this.active < this.limit && this.waiting.length > 0 && this.destroyed === false) {
this.active++;
this.waiting.shift()(true);
}
if (this.active === 0 && this.flushedResolve) {
const resolve = this.flushedResolve;
this.flushedResolve = null;
this.flushedPromise = null;
resolve(true);
}
}
async flush() {
if (this.destroyed === true) return;
if (this.active === 0) return;
if (this.flushedPromise) return this.flushedPromise;
this.flushedPromise = new Promise(this._onflush);
return this.flushedPromise;
}
destroy() {
this.destroyed = true;
this.active = 0;
while (this.waiting.length) this.waiting.pop()(false);
if (this.flushedResolve) this.flushedResolve(false);
}
};
}
});
// ../../node_modules/hyperdht/lib/connect.js
var require_connect = __commonJS({
"../../node_modules/hyperdht/lib/connect.js"(exports, module) {
var NoiseSecretStream = require_secret_stream();
var b4a = require_b4a();
var relay = require_blind_relay();
var { isReserved, isBogon } = require_bogon();
var safetyCatch = require_safety_catch();
var unslab = require_unslab();
var Semaphore = require_semaphore();
var NoiseWrap = require_noise_wrap();
var SecurePayload = require_secure_payload();
var Holepuncher = require_holepuncher();
var Sleeper = require_sleeper();
var { FIREWALL, ERROR } = require_constants5();
var { unslabbedHash } = require_crypto();
var {
CANNOT_HOLEPUNCH,
HANDSHAKE_INVALID,
HOLEPUNCH_ABORTED,
HOLEPUNCH_INVALID,
HOLEPUNCH_PROBE_TIMEOUT,
HOLEPUNCH_DOUBLE_RANDOMIZED_NATS,
PEER_CONNECTION_FAILED,
PEER_NOT_FOUND,
REMOTE_ABORTED,
REMOTE_NOT_HOLEPUNCHABLE,
REMOTE_NOT_HOLEPUNCHING,
SERVER_ERROR,
SERVER_INCOMPATIBLE,
RELAY_ABORTED,
SUSPENDED
} = require_errors9();
module.exports = function connect(dht, publicKey, opts = {}) {
const pool = opts.pool || null;
if (pool && pool.has(publicKey)) return pool.get(publicKey);
publicKey = unslab(publicKey);
const keyPair = opts.keyPair || dht.defaultKeyPair;
const relayThrough = selectRelay(opts.relayThrough || null);
const encryptedSocket = (opts.createSecretStream || defaultCreateSecretStream)(true, null, {
publicKey: keyPair.publicKey,
remotePublicKey: publicKey,
autoStart: false,
keepAlive: dht.connectionKeepAlive
});
if (dht.suspended || !dht._connectable) {
encryptedSocket.destroy(SUSPENDED());
return encryptedSocket;
}
if (pool) pool._attachStream(encryptedSocket, false);
const id = b4a.toString(publicKey, "hex");
const c = {
id,
dht,
session: dht.session(),
relayAddresses: opts.relayAddresses || [],
remoteRelayAddresses: [],
pool,
round: 0,
target: unslabbedHash(publicKey),
remotePublicKey: publicKey,
reusableSocket: !!opts.reusableSocket,
handshake: (opts.createHandshake || defaultCreateHandshake)(keyPair, publicKey),
request: null,
requesting: false,
lan: opts.localConnection !== false,
firewall: FIREWALL.UNKNOWN,
rawStream: dht.createRawStream({ framed: true, firewall }),
connect: null,
query: null,
puncher: null,
payload: null,
passiveConnectTimeout: null,
serverSocket: null,
serverAddress: null,
onsocket: null,
sleeper: new Sleeper(),
encryptedSocket,
// Relay state
relayTimeout: null,
relayThrough,
relayToken: relayThrough ? relay.token() : null,
relaySocket: null,
relayClient: null,
relayPaired: false,
relayKeepAlive: opts.relayKeepAlive || 5e3
};
c.rawStream.on("error", autoDestroy);
c.rawStream.once("connect", () => {
c.rawStream.removeListener("error", autoDestroy);
});
encryptedSocket.on("close", function() {
if (c.passiveConnectTimeout) clearPassiveConnectTimeout(c);
if (c.query) c.query.destroy();
if (c.puncher) c.puncher.destroy();
if (c.rawStream) c.rawStream.destroy();
c.session.destroy();
c.sleeper.resume();
});
if (dht.suspended) encryptedSocket.destroy(SUSPENDED());
else connectAndHolepunch(c, opts);
return encryptedSocket;
function autoDestroy(err) {
maybeDestroyEncryptedSocket(c, err);
}
function firewall(socket, port, host) {
if (c.relaySocket && isRelay(c.relaySocket, socket, port, host)) {
return false;
}
if (c.onsocket) {
c.onsocket(socket, port, host);
} else {
c.serverSocket = socket;
c.serverAddress = { port, host };
}
return false;
}
};
function isDone(c) {
if (c.encryptedSocket.destroying || !!(c.puncher && c.puncher.connected)) {
return true;
}
if (c.encryptedSocket.rawStream === null) {
return false;
}
if (c.relaySocket && !!(c.puncher && !c.puncher.connected && !c.puncher.destroyed)) {
return false;
}
return true;
}
async function retryRoute(c, route) {
const ref = c.dht._socketPool.lookup(route.socket);
if (!ref) {
if (route.socket === c.dht.socket) {
await connectThroughNode(c, route.address, c.dht.socket);
}
return;
}
ref.active();
try {
await connectThroughNode(c, route.address, route.socket);
} catch {
}
ref.inactive();
}
async function connectAndHolepunch(c, opts) {
const route = c.reusableSocket ? c.dht._socketPool.routes.get(c.remotePublicKey) : null;
if (route) {
await retryRoute(c, route);
if (isDone(c)) return;
}
await findAndConnect(c, opts);
if (isDone(c)) return;
if (!c.connect) {
maybeDestroyEncryptedSocket(c, HANDSHAKE_INVALID());
return;
}
await holepunch(c, opts);
}
function getFirstRemoteAddress(addrs, serverAddress) {
for (const addr of addrs) {
if (isBogon(addr.host)) continue;
return addr;
}
return serverAddress;
}
async function holepunch(c, opts) {
let { relayAddress, serverAddress, clientAddress, payload } = c.connect;
const remoteHolepunchable = !!(payload.holepunch && payload.holepunch.relays.length);
const relayed = diffAddress(serverAddress, relayAddress);
if (payload.firewall === FIREWALL.OPEN || relayed && !remoteHolepunchable) {
const addr = getFirstRemoteAddress(payload.addresses4, serverAddress);
if (addr) {
const socket = c.dht.socket;
c.dht.stats.punches.open++;
c.onsocket(socket, addr.port, addr.host);
return;
}
}
const onabort = () => {
c.session.destroy();
maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED());
};
if (c.firewall === FIREWALL.OPEN) {
c.passiveConnectTimeout = setTimeout(onabort, 1e4);
return;
}
if (c.lan && relayed && clientAddress.host === serverAddress.host) {
const serverAddresses = payload.addresses4.filter(onlyNonReserved);
if (serverAddresses.length > 0) {
const myAddresses = Holepuncher.localAddresses(c.dht.io.serverSocket);
const addr = Holepuncher.matchAddress(myAddresses, serverAddresses) || serverAddresses[0];
const socket = c.dht.io.serverSocket;
try {
await c.dht.ping(addr);
} catch {
maybeDestroyEncryptedSocket(c, HOLEPUNCH_ABORTED());
return;
}
c.onsocket(socket, addr.port, addr.host);
return;
}
}
if (!remoteHolepunchable) {
maybeDestroyEncryptedSocket(c, CANNOT_HOLEPUNCH());
return;
}
c.puncher = new Holepuncher(c.dht, c.session, true, payload.firewall);
c.puncher.onconnect = c.onsocket;
c.puncher.onabort = onabort;
const serverRelay = pickServerRelay(payload.holepunch.relays, relayAddress);
let probe;
try {
probe = await probeRound(c, opts.fastOpen === false ? null : serverAddress, serverRelay, true);
} catch (err) {
destroyPuncher(c);
maybeDestroyEncryptedSocket(c, err);
return;
}
if (isDone(c) || !probe) return;
const { token, peerAddress } = probe;
if (!diffAddress(serverRelay.relayAddress, relayAddress) && diffAddress(serverAddress, peerAddress)) {
serverAddress = peerAddress;
await c.puncher.openSession(serverAddress);
if (isDone(c)) return;
}
if (opts.holepunch && !opts.holepunch(
c.puncher.remoteFirewall,
c.puncher.nat.firewall,
c.puncher.remoteAddresses,
c.puncher.nat.addresses
)) {
await abort(c, serverRelay, HOLEPUNCH_ABORTED("Client aborted holepunch"));
return;
}
try {
await roundPunch(c, serverAddress, token, relayAddress, serverRelay, false);
} catch (err) {
destroyPuncher(c);
maybeDestroyEncryptedSocket(c, err);
}
}
async function findAndConnect(c, opts) {
let attempts = 0;
let closestNodes = opts.relayAddresses && opts.relayAddresses.length ? opts.relayAddresses : null;
if (!closestNodes) {
const cachedRelayAddresses = c.dht._relayAddressesCache.get(c.id);
if (cachedRelayAddresses) closestNodes = cachedRelayAddresses;
}
if (c.dht._persistent) {
const route = c.dht._router.get(c.target);
if (route && route.relay !== null) {
closestNodes = [{ host: route.relay.host, port: route.relay.port }];
}
}
const sem = new Semaphore(2);
const signal = sem.signal.bind(sem);
const tries = closestNodes !== null ? 2 : 1;
try {
for (let i = 0; i < tries && !isDone(c) && !c.connect; i++) {
c.query = c.dht.findPeer(c.target, {
hash: false,
session: c.session,
closestNodes,
onlyClosestNodes: closestNodes !== null,
retries: closestNodes ? 1 : 3
});
for await (const data of c.query) {
await sem.wait();
if (isDone(c)) return;
if (c.connect) {
sem.signal();
break;
}
c.remoteRelayAddresses.push(data.from);
attempts++;
connectThroughNode(c, data.from, null).then(signal, signal);
}
closestNodes = null;
if (attempts > 0) await sem.flush();
}
c.query = null;
if (isDone(c)) return;
await sem.flush();
if (isDone(c)) return;
} catch (err) {
c.query = null;
maybeDestroyEncryptedSocket(c, err);
return;
}
if (!c.connect) {
maybeDestroyEncryptedSocket(c, attempts ? PEER_CONNECTION_FAILED() : PEER_NOT_FOUND());
}
}
async function connectThroughNode(c, address, socket) {
if (!c.requesting) {
const addr = c.dht.remoteAddress();
const localAddrs = c.lan ? Holepuncher.localAddresses(c.dht.io.serverSocket) : null;
const addresses4 = [];
if (addr) addresses4.push(addr);
if (localAddrs) addresses4.push(...localAddrs);
c.firewall = addr ? FIREWALL.OPEN : FIREWALL.UNKNOWN;
c.requesting = true;
c.request = await c.handshake.send({
error: ERROR.NONE,
firewall: c.firewall,
holepunch: null,
addresses4,
addresses6: [],
udx: {
reusableSocket: c.reusableSocket,
id: c.rawStream.id,
seq: 0
},
secretStream: {},
relayThrough: c.relayThrough ? { publicKey: c.relayThrough, token: c.relayToken } : null
});
if (isDone(c)) return;
}
const { serverAddress, clientAddress, relayed, noise } = await c.dht._router.peerHandshake(
c.target,
{ noise: c.request, socket, session: c.session },
address
);
if (isDone(c) || c.connect) return;
const payload = await c.handshake.recv(noise);
if (isDone(c) || !payload) return;
if (payload.version !== 1) {
maybeDestroyEncryptedSocket(c, SERVER_INCOMPATIBLE());
return;
}
if (payload.error !== ERROR.NONE) {
maybeDestroyEncryptedSocket(c, SERVER_ERROR());
return;
}
if (!payload.udx) {
maybeDestroyEncryptedSocket(c, SERVER_ERROR("Server did not send UDX data"));
return;
}
const hs = c.handshake.final();
c.handshake = null;
c.request = null;
c.requesting = false;
c.connect = {
relayed,
relayAddress: address,
clientAddress,
serverAddress,
payload
};
c.payload = new SecurePayload(hs.holepunchSecret);
c.onsocket = function(socket2, port, host) {
if (c.rawStream === null) return;
if (c.rawStream.connected) {
const remoteChanging = c.rawStream.changeRemote(socket2, c.connect.payload.udx.id, port, host);
if (remoteChanging) remoteChanging.catch(safetyCatch);
} else {
if (payload.relayAddresses && payload.relayAddresses.length) {
c.dht._relayAddressesCache.set(c.id, payload.relayAddresses);
} else if (c.remoteRelayAddresses.length) {
c.dht._relayAddressesCache.set(c.id, c.remoteRelayAddresses);
}
c.rawStream.connect(socket2, c.connect.payload.udx.id, port, host);
c.encryptedSocket.start(c.rawStream, { handshake: hs });
}
if (c.reusableSocket && payload.udx.reusableSocket) {
c.dht._socketPool.routes.add(c.remotePublicKey, c.rawStream);
}
if (c.puncher) {
c.puncher.onabort = noop;
c.puncher.destroy();
}
if (c.passiveConnectTimeout) {
clearPassiveConnectTimeout(c);
}
c.rawStream = null;
};
if (payload.relayThrough || c.relayThrough) {
relayConnection(c, c.relayThrough, payload, hs);
}
if (c.serverSocket) {
c.onsocket(c.serverSocket, c.serverAddress.port, c.serverAddress.host);
return;
}
if (!relayed) {
c.onsocket(socket || c.dht.socket, address.port, address.host);
}
c.session.destroy();
}
async function updateHolepunch(c, peerAddress, relayAddr, payload) {
const holepunch2 = await c.dht._router.peerHolepunch(
c.target,
{
id: c.connect.payload.holepunch.id,
payload: c.payload.encrypt(payload),
peerAddress,
socket: c.puncher.socket,
session: c.session
},
relayAddr
);
if (isDone(c)) return null;
const remotePayload = c.payload.decrypt(holepunch2.payload);
if (!remotePayload) {
throw HOLEPUNCH_INVALID();
}
const { error, firewall, punching, addresses, remoteToken } = remotePayload;
if (error === ERROR.TRY_LATER && c.relayToken && payload.punching) {
return {
tryLater: true,
...holepunch2,
payload: remotePayload
};
}
if (error !== ERROR.NONE) {
throw REMOTE_ABORTED("Remote aborted with error code " + error);
}
const echoed = !!(remoteToken && payload.token && b4a.equals(remoteToken, payload.token));
c.puncher.updateRemote({
punching,
firewall,
addresses,
verified: echoed ? peerAddress.host : null
});
return {
tryLater: false,
...holepunch2,
payload: remotePayload
};
}
async function probeRound(c, serverAddress, serverRelay, retry) {
if (serverAddress) await c.puncher.openSession(serverAddress);
if (isDone(c)) return null;
const reply = await updateHolepunch(c, serverRelay.peerAddress, serverRelay.relayAddress, {
error: ERROR.NONE,
firewall: c.puncher.nat.firewall,
round: c.round++,
connected: false,
punching: false,
addresses: c.puncher.nat.addresses,
remoteAddress: serverAddress,
token: null,
remoteToken: null
});
if (isDone(c) || !reply) return null;
const { peerAddress } = reply;
const { address, token } = reply.payload;
c.puncher.nat.add(reply.to, reply.from);
if (c.puncher.remoteFirewall < FIREWALL.RANDOM && address && address.host && address.port && diffAddress(address, serverAddress)) {
await c.puncher.openSession(address);
if (isDone(c)) return null;
}
if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN) {
await c.sleeper.pause(1e3);
if (isDone(c)) return null;
}
let stable = await c.puncher.analyze(false);
if (isDone(c)) return null;
if (!stable) {
stable = await c.puncher.analyze(true);
if (isDone(c)) return null;
if (stable) return probeRound(c, serverAddress, serverRelay, false);
}
if ((c.puncher.remoteFirewall === FIREWALL.UNKNOWN || !token) && retry) {
return probeRound(c, serverAddress, serverRelay, false);
}
if (c.puncher.remoteFirewall === FIREWALL.UNKNOWN || c.puncher.nat.firewall === FIREWALL.UNKNOWN) {
await abort(c, serverRelay, HOLEPUNCH_PROBE_TIMEOUT());
return null;
}
if (c.puncher.remoteFirewall >= FIREWALL.RANDOM && c.puncher.nat.firewall >= FIREWALL.RANDOM) {
await abort(c, serverRelay, HOLEPUNCH_DOUBLE_RANDOMIZED_NATS());
return null;
}
return { token, peerAddress };
}
async function roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, delayed) {
c.puncher.nat.freeze();
const isRandom = c.puncher.remoteFirewall >= FIREWALL.RANDOM || c.puncher.nat.firewall >= FIREWALL.RANDOM;
if (isRandom) {
while (c.dht._randomPunches >= c.dht._randomPunchLimit || Date.now() - c.dht._lastRandomPunch < c.dht._randomPunchInterval) {
if (!c.relayToken) throw HOLEPUNCH_ABORTED();
if (!delayed) {
delayed = true;
await updateHolepunch(c, serverAddress, clientRelay, {
error: ERROR.NONE,
firewall: c.puncher.nat.firewall,
round: c.round++,
connected: false,
punching: false,
addresses: c.puncher.nat.addresses,
remoteAddress: null,
token: c.payload.token(serverAddress),
remoteToken
});
if (isDone(c)) return;
}
await tryLater(c);
if (isDone(c)) return;
}
}
if (isRandom) c.dht._randomPunches++;
let reply;
try {
reply = await updateHolepunch(
c,
delayed ? serverRelay.peerAddress : serverAddress,
delayed ? serverRelay.relayAddress : clientRelay,
{
error: ERROR.NONE,
firewall: c.puncher.nat.firewall,
round: c.round++,
connected: false,
punching: true,
addresses: c.puncher.nat.addresses,
remoteAddress: null,
token: delayed ? null : c.payload.token(serverAddress),
remoteToken
}
);
} finally {
if (isRandom) c.dht._randomPunches--;
}
if (isDone(c)) return;
if (!reply) return;
if (reply.tryLater) {
await tryLater(c);
if (isDone(c)) return;
return roundPunch(c, serverAddress, remoteToken, clientRelay, serverRelay, true);
}
if (!c.puncher.remoteHolepunching) {
throw REMOTE_NOT_HOLEPUNCHING();
}
if (!await c.puncher.punch()) {
throw REMOTE_NOT_HOLEPUNCHABLE();
}
}
async function tryLater(c) {
if (!c.relayToken) throw HOLEPUNCH_ABORTED();
await c.sleeper.pause(1e4 + Math.round(Math.random() * 1e4));
}
function maybeDestroyEncryptedSocket(c, err) {
if (isDone(c)) return;
if (c.encryptedSocket.rawStream) return;
if (c.relaySocket) return;
if (c.puncher && !c.puncher.destroyed) return;
c.session.destroy();
c.encryptedSocket.destroy(err);
}
async function abort(c, { peerAddress, relayAddress }, err) {
try {
await updateHolepunch(peerAddress, relayAddress, {
error: ERROR.ABORTED,
firewall: FIREWALL.UNKNOWN,
round: c.round++,
connected: false,
punching: false,
addresses: null,
remoteAddress: null,
token: null,
remoteToken: null
});
} catch {
}
destroyPuncher(c);
maybeDestroyEncryptedSocket(c, err);
}
function relayConnection(c, relayThrough, payload, hs) {
let isInitiator;
let publicKey;
let token;
if (payload.relayThrough) {
isInitiator = false;
publicKey = payload.relayThrough.publicKey;
token = payload.relayThrough.token;
} else {
isInitiator = true;
publicKey = relayThrough;
token = c.relayToken;
}
c.relayToken = token;
c.relaySocket = c.dht.connect(publicKey);
c.relaySocket.setKeepAlive(c.relayKeepAlive);
c.relayClient = relay.Client.from(c.relaySocket, { id: c.relaySocket.publicKey });
c.relayTimeout = setTimeout(onabort, 15e3, null);
c.relayClient.pair(isInitiator, token, c.rawStream).on("error", onabort).on("data", ondata);
function ondata(remoteId) {
if (c.relayTimeout) clearRelayTimeout(c);
if (c.rawStream === null) {
onabort(null);
return;
}
c.relayPaired = true;
const { remotePort, remoteHost, socket } = c.relaySocket.rawStream;
c.rawStream.on("close", () => c.relaySocket.destroy()).connect(socket, remoteId, remotePort, remoteHost);
c.encryptedSocket.start(c.rawStream, { handshake: hs });
}
function onabort(err) {
if (c.relayTimeout) clearRelayTimeout(c);
const socket = c.relaySocket;
c.relayToken = null;
c.relaySocket = null;
if (socket) socket.destroy();
maybeDestroyEncryptedSocket(c, err || RELAY_ABORTED());
}
}
function clearPassiveConnectTimeout(c) {
clearTimeout(c.passiveConnectTimeout);
c.passiveConnectTimeout = null;
}
function clearRelayTimeout(c) {
clearTimeout(c.relayTimeout);
c.relayTimeout = null;
}
function destroyPuncher(c) {
if (c.puncher) c.puncher.destroy();
c.session.destroy();
}
function pickServerRelay(relays, clientRelay) {
for (const r of relays) {
if (!diffAddress(r.relayAddress, clientRelay)) return r;
}
return relays[0];
}
function diffAddress(a, b) {
return a.host !== b.host || a.port !== b.port;
}
function defaultCreateHandshake(keyPair, remotePublicKey) {
return new NoiseWrap(keyPair, remotePublicKey);
}
function defaultCreateSecretStream(isInitiator, rawStream, opts) {
return new NoiseSecretStream(isInitiator, rawStream, opts);
}
function onlyNonReserved(addr) {
return !isReserved(addr.host);
}
function isRelay(relaySocket, socket, port, host) {
const stream = relaySocket.rawStream;
if (!stream) return false;
if (stream.socket !== socket) return false;
return port === stream.remotePort && host === stream.remoteHost;
}
function selectRelay(relayThrough) {
if (typeof relayThrough === "function") relayThrough = relayThrough();
if (relayThrough === null) return null;
if (Array.isArray(relayThrough))
return relayThrough[Math.floor(Math.random() * relayThrough.length)];
return relayThrough;
}
function noop() {
}
}
});
// ../../node_modules/z32/index.js
var require_z32 = __commonJS({
"../../node_modules/z32/index.js"(exports) {
var b4a = require_b4a();
var ALPHABET = "ybndrfg8ejkmcpqxot1uwisza345h769";
var MIN = 49;
var MAX = 122;
var REVERSE = new Int8Array(1 + MAX - MIN);
REVERSE.fill(-1);
for (let i = 0; i < ALPHABET.length; i++) {
const v = ALPHABET.charCodeAt(i) - MIN;
REVERSE[v] = i;
}
exports.encode = encode;
exports.decode = decode;
exports.ALPHABET = ALPHABET;
function decode(s, out) {
let pb = 0;
let ps = 0;
const r = s.length & 7;
const q = (s.length - r) / 8;
if (!out) out = b4a.allocUnsafe(Math.ceil(s.length * 5 / 8));
for (let i = 0; i < q; i++) {
const a2 = quintet(s, ps++);
const b2 = quintet(s, ps++);
const c2 = quintet(s, ps++);
const d2 = quintet(s, ps++);
const e2 = quintet(s, ps++);
const f2 = quintet(s, ps++);
const g2 = quintet(s, ps++);
const h2 = quintet(s, ps++);
out[pb++] = a2 << 3 | b2 >>> 2;
out[pb++] = (b2 & 3) << 6 | c2 << 1 | d2 >>> 4;
out[pb++] = (d2 & 15) << 4 | e2 >>> 1;
out[pb++] = (e2 & 1) << 7 | f2 << 2 | g2 >>> 3;
out[pb++] = (g2 & 7) << 5 | h2;
}
if (r === 0) return out.subarray(0, pb);
const a = quintet(s, ps++);
const b = quintet(s, ps++);
out[pb++] = a << 3 | b >>> 2;
if (r <= 2) return out.subarray(0, pb);
const c = quintet(s, ps++);
const d = quintet(s, ps++);
out[pb++] = (b & 3) << 6 | c << 1 | d >>> 4;
if (r <= 4) return out.subarray(0, pb);
const e = quintet(s, ps++);
out[pb++] = (d & 15) << 4 | e >>> 1;
if (r <= 5) return out.subarray(0, pb);
const f = quintet(s, ps++);
const g = quintet(s, ps++);
out[pb++] = (e & 1) << 7 | f << 2 | g >>> 3;
if (r <= 7) return out.subarray(0, pb);
const h = quintet(s, ps++);
out[pb++] = (g & 7) << 5 | h;
return out.subarray(0, pb);
}
function encode(buf) {
if (typeof buf === "string") buf = b4a.from(buf);
const max = buf.byteLength * 8;
let s = "";
for (let p = 0; p < max; p += 5) {
const i = p >>> 3;
const j = p & 7;
if (j <= 3) {
s += ALPHABET[buf[i] >>> 3 - j & 31];
continue;
}
const of = j - 3;
const h = buf[i] << of & 31;
const l = (i >= buf.byteLength ? 0 : buf[i + 1]) >>> 8 - of;
s += ALPHABET[h | l];
}
return s;
}
function quintet(s, i) {
if (i > s.length) {
return 0;
}
const v = s.charCodeAt(i);
if (v < MIN || v > MAX) {
throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i);
}
const bits = REVERSE[v - MIN];
if (bits === -1) {
throw Error('Invalid character in base32 input: "' + s[i] + '" at position ' + i);
}
return bits;
}
}
});
// ../../node_modules/hypercore-id-encoding/index.js
var require_hypercore_id_encoding = __commonJS({
"../../node_modules/hypercore-id-encoding/index.js"(exports, module) {
var z32 = require_z32();
var b4a = require_b4a();
module.exports = {
encode,
decode,
normalize,
isValid
};
function encode(key) {
if (!b4a.isBuffer(key)) throw new Error("Key must be a Buffer");
if (key.byteLength !== 32) throw new Error("Key must be 32-bytes long");
return z32.encode(key);
}
function decode(id) {
if (b4a.isBuffer(id)) {
if (id.byteLength !== 32) throw new Error("ID must be 32-bytes long");
return id;
}
if (typeof id === "string") {
if (id.startsWith("pear://")) id = id.slice(7).split("/")[0];
if (id.length === 52) return z32.decode(id);
if (id.length === 64) {
const buf = b4a.from(id, "hex");
if (buf.byteLength === 32) return buf;
}
}
throw new Error("Invalid Hypercore key");
}
function normalize(any) {
return encode(decode(any));
}
function isValid(any) {
try {
decode(any);
return true;
} catch {
return false;
}
}
}
});
// ../../node_modules/hyperdht/lib/raw-stream-set.js
var require_raw_stream_set = __commonJS({
"../../node_modules/hyperdht/lib/raw-stream-set.js"(exports, module) {
module.exports = class RawStreamSet {
constructor(dht) {
this._dht = dht;
this._prefix = 16 - 1;
this._streams = /* @__PURE__ */ new Map();
}
get size() {
return this._streams.size;
}
[Symbol.iterator]() {
return this._streams.values();
}
add(opts) {
const self = this;
let id = 0;
while (true) {
id = Math.random() * 4294967296 >>> 0;
if (this._streams.has(id & this._prefix)) continue;
break;
}
if (2 * this._streams.size >= this._prefix) {
this._prefix = 2 * this._prefix + 1;
const next = /* @__PURE__ */ new Map();
for (const stream2 of this._streams.values()) {
next.set(stream2.id & this._prefix, stream2);
}
this._streams = next;
}
const stream = this._dht.udx.createStream(id, opts);
this._streams.set(id & this._prefix, stream);
stream.on("close", onclose);
return stream;
function onclose() {
self._streams.delete(id & self._prefix);
}
}
async clear() {
const destroying = [];
for (const stream of this._streams.values()) {
destroying.push(new Promise((resolve) => stream.once("close", resolve).destroy()));
}
await Promise.allSettled(destroying);
}
};
}
});
// ../../node_modules/hyperdht/lib/connection-pool.js
var require_connection_pool = __commonJS({
"../../node_modules/hyperdht/lib/connection-pool.js"(exports, module) {
var EventEmitter = require_bare_node_events();
var b4a = require_b4a();
var errors = require_errors9();
module.exports = class ConnectionPool extends EventEmitter {
constructor(dht) {
super();
this._dht = dht;
this._servers = /* @__PURE__ */ new Map();
this._connecting = /* @__PURE__ */ new Map();
this._connections = /* @__PURE__ */ new Map();
}
_attachServer(server) {
const keyString = b4a.toString(server.publicKey, "hex");
this._servers.set(keyString, server);
server.on("close", () => {
this._servers.delete(keyString);
}).on("connection", (socket) => {
this._attachStream(socket, true);
});
}
_attachStream(stream, opened) {
const existing = this.get(stream.remotePublicKey);
if (existing) {
const keepNew = stream.isInitiator === existing.isInitiator || b4a.compare(stream.publicKey, stream.remotePublicKey) > 0;
if (keepNew) {
let closed = false;
const onclose = () => {
closed = true;
};
existing.on("error", noop).on("close", () => {
if (closed) return;
stream.off("error", noop).off("close", onclose);
this._attachStream(stream, opened);
}).destroy(errors.DUPLICATE_CONNECTION());
stream.on("error", noop).on("close", onclose);
} else {
stream.on("error", noop).destroy(errors.DUPLICATE_CONNECTION());
}
return;
}
const session = new ConnectionRef(this, stream);
const keyString = b4a.toString(stream.remotePublicKey, "hex");
if (opened) {
this._connections.set(keyString, session);
stream.on("close", () => {
this._connections.delete(keyString);
});
this.emit("connection", stream, session);
} else {
this._connecting.set(keyString, session);
stream.on("error", noop).on("close", () => {
if (opened) this._connections.delete(keyString);
else this._connecting.delete(keyString);
}).on("open", () => {
opened = true;
this._connecting.delete(keyString);
this._connections.set(keyString, session);
stream.off("error", noop);
this.emit("connection", stream, session);
});
}
return session;
}
get connecting() {
return this._connecting.size;
}
get connections() {
return this._connections.values();
}
has(publicKey) {
const keyString = b4a.toString(publicKey, "hex");
return this._connections.has(keyString) || this._connecting.has(keyString);
}
get(publicKey) {
const keyString = b4a.toString(publicKey, "hex");
const existing = this._connections.get(keyString) || this._connecting.get(keyString);
return existing?._stream || null;
}
};
var ConnectionRef = class {
constructor(pool, stream) {
this._pool = pool;
this._stream = stream;
this._refs = 0;
}
active() {
this._refs++;
}
inactive() {
this._refs--;
}
release() {
this._stream.destroy();
}
};
function noop() {
}
}
});
// ../../node_modules/hyperdht/index.js
var require_hyperdht = __commonJS({
"../../node_modules/hyperdht/index.js"(exports, module) {
var DHT = require_dht_rpc();
var sodium = require_sodium_universal();
var c = require_compact_encoding();
var b4a = require_b4a();
var safetyCatch = require_safety_catch();
var m = require_messages();
var SocketPool = require_socket_pool();
var Persistent = require_persistent();
var Router = require_router();
var Cache = require_xache();
var Server = require_server();
var connect = require_connect();
var { FIREWALL, BOOTSTRAP_NODES, KNOWN_NODES, COMMANDS } = require_constants5();
var { hash, createKeyPair } = require_crypto();
var { decode } = require_hypercore_id_encoding();
var RawStreamSet = require_raw_stream_set();
var ConnectionPool = require_connection_pool();
var { STREAM_NOT_CONNECTED } = require_errors9();
var DEFAULTS = {
...DHT.DEFAULTS,
connectionKeepAlive: 5e3,
randomPunchInterval: 2e4
};
var HyperDHT = class extends DHT {
constructor(opts = {}) {
const port = opts.port || 49737;
const bootstrap = opts.bootstrap || BOOTSTRAP_NODES;
const nodes = opts.nodes || KNOWN_NODES;
super({ ...opts, port, bootstrap, nodes, filterNode });
const { router, relayAddresses, persistent } = defaultCacheOpts(opts);
this.defaultKeyPair = opts.keyPair || createKeyPair(opts.seed);
this.listening = /* @__PURE__ */ new Set();
this.connectionKeepAlive = opts.connectionKeepAlive === false ? 0 : opts.connectionKeepAlive || DEFAULTS.connectionKeepAlive;
this.stats = {
punches: { consistent: 0, random: 0, open: 0 },
relaying: { attempts: 0, successes: 0, aborts: 0 },
...this.stats
};
this.rawStreams = new RawStreamSet(this);
this._router = new Router(this, router);
this._socketPool = new SocketPool(this, opts.host || "0.0.0.0");
this._persistent = null;
this._validatedLocalAddresses = /* @__PURE__ */ new Map();
this._relayAddressesCache = new Cache(relayAddresses);
this._deferRandomPunch = !!opts.deferRandomPunch;
this._lastRandomPunch = this._deferRandomPunch ? Date.now() : 0;
this._connectable = true;
this._randomPunchInterval = opts.randomPunchInterval || DEFAULTS.randomPunchInterval;
this._randomPunches = 0;
this._randomPunchLimit = 1;
this.once("persistent", () => {
this._persistent = new Persistent(this, persistent);
});
this.on("network-change", () => {
for (const server of this.listening) server.refresh();
});
this.on("network-update", () => {
if (!this.online) return;
for (const server of this.listening) server.notifyOnline();
});
}
static DEFAULTS = DEFAULTS;
connect(remotePublicKey, opts) {
return connect(this, decode(remotePublicKey), opts);
}
createServer(opts, onconnection) {
if (typeof opts === "function") return this.createServer({}, opts);
if (opts && opts.onconnection) onconnection = opts.onconnection;
const s = new Server(this, opts);
if (onconnection) s.on("connection", onconnection);
return s;
}
pool() {
return new ConnectionPool(this);
}
async resume({ log = noop } = {}) {
if (this._deferRandomPunch) this._lastRandomPunch = Date.now();
await super.resume({ log });
const resuming = [];
for (const server of this.listening) resuming.push(server.resume());
log("Resuming hyperdht servers");
await Promise.allSettled(resuming);
log("Done, hyperdht fully resumed");
}
async suspend({ log = noop } = {}) {
this._connectable = false;
const suspending = [];
for (const server of this.listening) suspending.push(server.suspend());
log("Suspending all hyperdht servers");
await Promise.allSettled(suspending);
log("Done, clearing all raw streams");
await this.rawStreams.clear();
log("Done, suspending dht-rpc");
await super.suspend({ log });
log("Done, clearing raw streams again");
await this.rawStreams.clear();
log("Done, hyperdht fully suspended");
this._connectable = true;
}
async destroy({ force = false } = {}) {
if (!force) {
const closing = [];
for (const server of this.listening) closing.push(server.close());
await Promise.allSettled(closing);
}
this._router.destroy();
if (this._persistent) this._persistent.destroy();
await this.rawStreams.clear();
await this._socketPool.destroy();
await super.destroy();
}
async validateLocalAddresses(addresses) {
const list = [];
const socks = [];
const waiting = [];
for (const addr of addresses) {
const { host } = addr;
if (this._validatedLocalAddresses.has(host)) {
if (await this._validatedLocalAddresses.get(host)) {
list.push(addr);
}
continue;
}
const sock = this.udx.createSocket();
try {
sock.bind(0, host);
} catch {
this._validatedLocalAddresses.set(host, Promise.resolve(false));
continue;
}
socks.push(sock);
const promise = new Promise((resolve) => {
sock.on("message", () => resolve(true));
setTimeout(() => resolve(false), 500);
sock.trySend(b4a.alloc(1), sock.address().port, addr.host);
});
this._validatedLocalAddresses.set(host, promise);
waiting.push(addr);
}
for (const addr of waiting) {
const { host } = addr;
if (this._validatedLocalAddresses.has(host)) {
if (await this._validatedLocalAddresses.get(host)) {
list.push(addr);
}
continue;
}
}
for (const sock of socks) await sock.close();
return list;
}
findPeer(publicKey, opts = {}) {
const target = opts.hash === false ? publicKey : hash(publicKey);
opts = { ...opts, map: mapFindPeer };
return this.query({ target, command: COMMANDS.FIND_PEER, value: null }, opts);
}
lookup(target, opts = {}) {
opts = { ...opts, map: mapLookup };
return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts);
}
lookupAndUnannounce(target, keyPair, opts = {}) {
const unannounces = [];
const dht = this;
const userCommit = opts.commit || noop;
const signUnannounce = opts.signUnannounce || Persistent.signUnannounce;
if (this._persistent !== null) {
this._persistent.unannounce(target, keyPair.publicKey);
}
opts = { ...opts, map, commit };
return this.query({ target, command: COMMANDS.LOOKUP, value: null }, opts);
async function commit(reply, dht2, query) {
await Promise.all(unannounces);
return userCommit(reply, dht2, query);
}
function map(reply) {
const data = mapLookup(reply);
if (!data || !data.token) return data;
let found = data.peers.length >= 20;
for (let i = 0; !found && i < data.peers.length; i++) {
found = b4a.equals(data.peers[i].publicKey, keyPair.publicKey);
}
if (!found) return data;
if (!data.from.id) return data;
unannounces.push(
dht._requestUnannounce(keyPair, dht, target, data.token, data.from, signUnannounce).catch(safetyCatch)
);
return data;
}
}
unannounce(target, keyPair, opts = {}) {
return this.lookupAndUnannounce(target, keyPair, opts).finished();
}
announce(target, keyPair, relayAddresses, opts = {}) {
const signAnnounce = opts.signAnnounce || Persistent.signAnnounce;
const bump = opts.bump || 0;
opts = { ...opts, commit };
return opts.clear ? this.lookupAndUnannounce(target, keyPair, opts) : this.lookup(target, opts);
function commit(reply, dht) {
return dht._requestAnnounce(
keyPair,
dht,
target,
reply.token,
reply.from,
relayAddresses,
signAnnounce,
bump
);
}
}
async immutableGet(target, opts = {}) {
opts = { ...opts, map: mapImmutable };
const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts);
const check = b4a.allocUnsafe(32);
for await (const node of query) {
const { value } = node;
sodium.crypto_generichash(check, value);
if (b4a.equals(check, target)) return node;
}
return null;
}
async immutablePut(value, opts = {}) {
const target = b4a.allocUnsafe(32);
sodium.crypto_generichash(target, value);
opts = {
...opts,
map: mapImmutable,
commit(reply, dht) {
return dht.request(
{ token: reply.token, target, command: COMMANDS.IMMUTABLE_PUT, value },
reply.from
);
}
};
const query = this.query({ target, command: COMMANDS.IMMUTABLE_GET, value: null }, opts);
await query.finished();
return { hash: target, closestNodes: query.closestNodes };
}
async mutableGet(publicKey, opts = {}) {
let refresh = opts.refresh || null;
let signed = null;
let result = null;
opts = { ...opts, map: mapMutable, commit: refresh ? commit : null };
const target = b4a.allocUnsafe(32);
sodium.crypto_generichash(target, publicKey);
const userSeq = opts.seq || 0;
const query = this.query(
{ target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, userSeq) },
opts
);
const latest = opts.latest !== false;
for await (const node of query) {
if (result && node.seq <= result.seq) continue;
if (node.seq < userSeq || !Persistent.verifyMutable(node.signature, node.seq, node.value, publicKey))
continue;
if (!latest) return node;
if (!result || node.seq > result.seq) result = node;
}
return result;
function commit(reply, dht) {
if (!signed && result && refresh) {
if (refresh(result)) {
signed = c.encode(m.mutablePutRequest, {
publicKey,
seq: result.seq,
value: result.value,
signature: result.signature
});
} else {
refresh = null;
}
}
return signed ? dht.request(
{ token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
reply.from
) : Promise.resolve(null);
}
}
async mutablePut(keyPair, value, opts = {}) {
const signMutable = opts.signMutable || Persistent.signMutable;
const target = b4a.allocUnsafe(32);
sodium.crypto_generichash(target, keyPair.publicKey);
const seq = opts.seq || 0;
const signature = await signMutable(seq, value, keyPair);
const signed = c.encode(m.mutablePutRequest, {
publicKey: keyPair.publicKey,
seq,
value,
signature
});
opts = {
...opts,
map: mapMutable,
commit(reply, dht) {
return dht.request(
{ token: reply.token, target, command: COMMANDS.MUTABLE_PUT, value: signed },
reply.from
);
}
};
const query = this.query(
{ target, command: COMMANDS.MUTABLE_GET, value: c.encode(c.uint, 0) },
opts
);
await query.finished();
return { publicKey: keyPair.publicKey, closestNodes: query.closestNodes, seq, signature };
}
onrequest(req) {
switch (req.command) {
case COMMANDS.PEER_HANDSHAKE: {
this._router.onpeerhandshake(req);
return true;
}
case COMMANDS.PEER_HOLEPUNCH: {
this._router.onpeerholepunch(req);
return true;
}
}
if (this._persistent === null || this.id === null) return false;
switch (req.command) {
case COMMANDS.FIND_PEER: {
this._persistent.onfindpeer(req);
return true;
}
case COMMANDS.LOOKUP: {
this._persistent.onlookup(req);
return true;
}
case COMMANDS.ANNOUNCE: {
this._persistent.onannounce(req);
return true;
}
case COMMANDS.UNANNOUNCE: {
this._persistent.onunannounce(req);
return true;
}
case COMMANDS.MUTABLE_PUT: {
this._persistent.onmutableput(req);
return true;
}
case COMMANDS.MUTABLE_GET: {
this._persistent.onmutableget(req);
return true;
}
case COMMANDS.IMMUTABLE_PUT: {
this._persistent.onimmutableput(req);
return true;
}
case COMMANDS.IMMUTABLE_GET: {
this._persistent.onimmutableget(req);
return true;
}
}
return false;
}
static keyPair(seed) {
return createKeyPair(seed);
}
static hash(data) {
return hash(data);
}
static connectRawStream(encryptedStream, rawStream, remoteId) {
const stream = encryptedStream.rawStream;
if (!stream.connected) throw STREAM_NOT_CONNECTED();
rawStream.connect(stream.socket, remoteId, stream.remotePort, stream.remoteHost);
}
createRawStream(opts) {
return this.rawStreams.add(opts);
}
async _requestAnnounce(keyPair, dht, target, token, from, relayAddresses, sign, bump) {
const ann = {
peer: {
publicKey: keyPair.publicKey,
relayAddresses: relayAddresses || []
},
refresh: null,
signature: null,
bump
};
ann.signature = await sign(target, token, from.id, ann, keyPair);
const value = c.encode(m.announce, ann);
return dht.request(
{
token,
target,
command: COMMANDS.ANNOUNCE,
value
},
from
);
}
async _requestUnannounce(keyPair, dht, target, token, from, sign) {
const unann = {
peer: {
publicKey: keyPair.publicKey,
relayAddresses: []
},
signature: null
};
unann.signature = await sign(target, token, from.id, unann, keyPair);
const value = c.encode(m.announce, unann);
return dht.request(
{
token,
target,
command: COMMANDS.UNANNOUNCE,
value
},
from
);
}
};
HyperDHT.BOOTSTRAP = BOOTSTRAP_NODES;
HyperDHT.FIREWALL = FIREWALL;
module.exports = HyperDHT;
function mapLookup(node) {
if (!node.value) return null;
try {
const l = c.decode(m.lookupRawReply, node.value);
return {
token: node.token,
from: node.from,
to: node.to,
peers: l.peers,
bump: l.bump
};
} catch {
return null;
}
}
function mapFindPeer(node) {
if (!node.value) return null;
try {
return {
token: node.token,
from: node.from,
to: node.to,
peer: c.decode(m.peer, node.value)
};
} catch {
return null;
}
}
function mapImmutable(node) {
if (!node.value) return null;
return {
token: node.token,
from: node.from,
to: node.to,
value: node.value
};
}
function mapMutable(node) {
if (!node.value) return null;
try {
const { seq, value, signature } = c.decode(m.mutableGetResponse, node.value);
return {
token: node.token,
from: node.from,
to: node.to,
seq,
value,
signature
};
} catch {
return null;
}
}
function noop() {
}
function filterNode(node) {
return !(node.port === 49738 && (node.host === "134.209.28.98" || node.host === "167.99.142.185")) && !(node.port === 9400 && node.host === "35.233.47.252") && !(node.host === "150.136.142.116");
}
var defaultMaxSize = 65536;
var defaultMaxAge = 20 * 60 * 1e3;
function defaultCacheOpts(opts) {
const maxSize = opts.maxSize || defaultMaxSize;
const maxAge = opts.maxAge || defaultMaxAge;
return {
router: {
forwards: { maxSize, maxAge }
},
relayAddresses: { maxSize: Math.min(maxSize, 512), maxAge: 0 },
persistent: {
records: { maxSize, maxAge },
refreshes: { maxSize, maxAge },
mutables: {
maxSize: maxSize / 2 | 0,
maxAge: opts.maxAge || 48 * 60 * 60 * 1e3
// 48 hours
},
immutables: {
maxSize: maxSize / 2 | 0,
maxAge: opts.maxAge || 48 * 60 * 60 * 1e3
// 48 hours
},
bumps: { maxSize, maxAge }
}
};
}
}
});
// ../../node_modules/bare-dgram/index.js
var require_bare_dgram = __commonJS({
"../../node_modules/bare-dgram/index.js"(exports) {
var EventEmitter = require_bare_events();
var UDX = require_udx();
var udx = new UDX();
var Socket = exports.Socket = class Socket extends EventEmitter {
constructor(opts = {}) {
super();
this._remotePort = -1;
this._remoteAddress = null;
this._remoteFamily = 0;
this._socket = udx.createSocket(opts);
this._socket.on("error", (err) => this.emit("error", err)).on("close", () => this.emit("close")).on(
"listening",
() => queueMicrotask(() => this.emit("listening"))
/* Deferred for Node.js compatibility */
).on("message", (message, address) => this.emit("message", message, {
address: address.host,
family: `IPv${address.family}`,
port: address.port
}));
}
address() {
const address = this._socket.address();
if (address === null) return null;
return {
address: address.host,
family: `IPv${address.family}`,
port: address.port
};
}
remoteAddress() {
if (this._remotePort === -1) return null;
return {
address: this._remoteAddress,
family: `IPv${this._remoteFamily}`,
port: this._remotePort
};
}
bind(port, address, cb) {
if (typeof port === "function") {
cb = port;
port = 0;
address = null;
} else if (typeof address === "function") {
cb = address;
address = null;
}
if (typeof port === "object" && port !== null) {
const opts = port || {};
port = opts.port || null;
address = opts.address || null;
}
if (cb) this.once("listening", cb);
this._socket.bind(port, address);
return this;
}
connect(port, address, cb) {
if (typeof address === "function") {
cb = address;
address = null;
}
this._remotePort = port;
this._remoteAddress = address;
this._remoteFamily = UDX.isIP(address);
if (cb) this.once("connect", cb);
queueMicrotask(() => this.emit("connect"));
}
async close(cb) {
try {
await this._socket.close();
if (cb) cb(null);
} catch (err) {
if (cb) cb(err);
else throw err;
}
}
async send(buffer, offset, length, port, address, cb) {
if (typeof buffer === "string") buffer = Buffer.from(buffer);
if (typeof offset === "function") {
cb = offset;
offset = 0;
length = buffer.byteLength;
port = 0;
address = null;
} else if (typeof length === "function") {
cb = length;
port = offset;
address = null;
offset = 0;
length = buffer.byteLength;
} else if (typeof port === "function") {
cb = port;
if (typeof length === "string") {
port = offset;
address = length;
offset = 0;
length = buffer.byteLength;
} else {
port = 0;
address = null;
}
} else if (typeof address === "function") {
cb = address;
if (typeof port === "string") {
address = port;
port = 0;
} else {
address = null;
}
}
if (typeof offset === "string") {
address = offset;
port = 0;
offset = 0;
length = buffer.byteLength;
}
if (typeof length === "string") {
address = length;
port = offset;
offset = 0;
length = buffer.byteLength;
} else if (typeof length !== "number") {
port = offset;
address = null;
offset = 0;
length = buffer.byteLength;
}
if (!port) port = this._remotePort;
if (!address) address = this._remoteAddress;
if (offset !== 0 || length !== buffer.byteLength) {
buffer = buffer.subarray(offset, offset + length);
}
try {
await this._socket.send(buffer, port, address);
if (cb) cb(null);
} catch (err) {
if (cb) cb(err);
else throw err;
}
}
};
exports.createSocket = function createSocket(opts, cb) {
if (typeof opts === "string") opts = {};
const socket = new Socket(opts);
if (cb) socket.on("message", cb);
return socket;
};
}
});
// ../../node_modules/bare-dns/binding.js
var require_binding8 = __commonJS({
"../../node_modules/bare-dns/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-dns/index.js
var require_bare_dns = __commonJS({
"../../node_modules/bare-dns/index.js"(exports) {
var binding = require_binding8();
exports.Resolver = class DNSResolver {
constructor() {
this._handle = binding.initResolver();
}
resolveTxt(hostname, cb = noop) {
binding.resolveTxt(this._handle, hostname, cb, this);
}
destroy() {
binding.destroyResolver(this._handle);
this._handle = null;
}
static global = new this();
};
function onlookup(err, addresses) {
const req = this;
if (err) return req.cb(err, null, 0);
const { address, family } = addresses[0];
return req.cb(null, address, family);
}
function onlookupall(err, addresses) {
const req = this;
if (err) return req.cb(err, null);
return req.cb(null, addresses);
}
exports.lookup = function lookup(hostname, opts = {}, cb) {
if (typeof opts === "function") {
cb = opts;
opts = {};
}
let { family = 0, all = false } = opts;
if (typeof family === "string") {
switch (family) {
case "IPv4":
family = 4;
break;
case "IPv6":
family = 6;
break;
default:
family = 0;
}
}
const req = {
cb,
handle: null
};
req.handle = binding.lookup(
hostname,
family || 0,
all,
req,
all ? onlookupall : onlookup
);
};
exports.resolveTxt = function resolveTxt(hostname, cb) {
exports.Resolver.global.resolveTxt(hostname, cb);
};
function noop() {
}
}
});
// ../../node_modules/bare-tcp/binding.js
var require_binding9 = __commonJS({
"../../node_modules/bare-tcp/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-tcp/lib/constants.js
var require_constants6 = __commonJS({
"../../node_modules/bare-tcp/lib/constants.js"(exports, module) {
module.exports = {
state: {
CONNECTING: 1,
CONNECTED: 2,
BINDING: 4,
BOUND: 8,
READING: 16,
CLOSING: 32,
UNREFED: 64
}
};
}
});
// ../../node_modules/bare-tcp/lib/errors.js
var require_errors11 = __commonJS({
"../../node_modules/bare-tcp/lib/errors.js"(exports, module) {
module.exports = class TCPError extends Error {
constructor(msg, fn = TCPError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "TCPError";
}
static SOCKET_ALREADY_CONNECTED(msg) {
return new TCPError(msg, TCPError.SOCKET_ALREADY_CONNECTED);
}
static SERVER_ALREADY_LISTENING(msg) {
return new TCPError(msg, TCPError.SERVER_ALREADY_LISTENING);
}
static SERVER_IS_CLOSED(msg) {
return new TCPError(msg, TCPError.SERVER_IS_CLOSED);
}
static INVALID_HOST(msg = "Unrecognizable host format") {
return new TCPError(msg, TCPError.INVALID_HOST);
}
};
}
});
// ../../node_modules/bare-tcp/lib/ip.js
var require_ip2 = __commonJS({
"../../node_modules/bare-tcp/lib/ip.js"(exports) {
var v4Seg = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
var v4Str = `(${v4Seg}[.]){3}${v4Seg}`;
var IPv4Pattern = new RegExp(`^${v4Str}$`);
var v6Seg = "(?:[0-9a-fA-F]{1,4})";
var IPv6Pattern = new RegExp(
`^((?:${v6Seg}:){7}(?:${v6Seg}|:)|(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})?$`
);
var isIPv4 = exports.isIPv4 = function isIPv42(host) {
return IPv4Pattern.test(host);
};
var isIPv6 = exports.isIPv6 = function isIPv62(host) {
return IPv6Pattern.test(host);
};
exports.isIP = function isIP(host) {
if (isIPv4(host)) return 4;
if (isIPv6(host)) return 6;
return 0;
};
}
});
// ../../node_modules/bare-tcp/index.js
var require_bare_tcp = __commonJS({
"../../node_modules/bare-tcp/index.js"(exports) {
var EventEmitter = require_bare_events();
var { Duplex } = require_bare_stream();
var dns = require_bare_dns();
var binding = require_binding9();
var constants = require_constants6();
var errors = require_errors11();
var ip = require_ip2();
var defaultReadBufferSize = 65536;
var empty = Buffer.alloc(0);
exports.Socket = class TCPSocket extends Duplex {
constructor(opts = {}) {
const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts;
super({ eagerOpen });
this._state = 0;
this._allowHalfOpen = allowHalfOpen;
this._keepAlive = 0;
this._keepAliveInitialDelay = 0;
this._noDelay = 0;
this._localAddress = null;
this._remoteAddress = null;
this._pendingOpen = null;
this._pendingWrite = null;
this._pendingFinal = null;
this._pendingDestroy = null;
this._timer = null;
this._timeout = 0;
this._buffer = Buffer.alloc(readBufferSize);
this._addresses = null;
this._errors = null;
this._handle = binding.init(
this._buffer,
this,
noop,
this._onconnect,
this._onreset,
this._onread,
this._onwrite,
this._onfinal,
this._onclose
);
}
get connecting() {
return (this._state & constants.state.CONNECTING) !== 0;
}
get pending() {
return (this._state & constants.state.CONNECTED) === 0;
}
get timeout() {
return this._timeout || void 0;
}
get readyState() {
if (this._state & constants.state.CONNECTED) {
return "open";
}
return "opening";
}
get localAddress() {
if (this._localAddress) return this._localAddress.address;
}
get localFamily() {
if (this._localAddress) return `IPv${this._localAddress.family}`;
}
get localPort() {
if (this._localAddress) return this._localAddress.port;
}
get remoteAddress() {
if (this._remoteAddress) return this._remoteAddress.address;
}
get remoteFamily() {
if (this._remoteAddress) return `IPv${this._remoteAddress.family}`;
}
get remotePort() {
if (this._remoteAddress) return this._remoteAddress.port;
}
connect(port, host = "localhost", opts = {}, onconnect) {
if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
throw errors.SOCKET_ALREADY_CONNECTED("Socket is already connected");
}
this._state |= constants.state.CONNECTING;
if (typeof host === "function") {
onconnect = host;
host = "localhost";
} else if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
let family = 0;
if (typeof port === "object" && port !== null) {
opts = port || {};
port = opts.port || 0;
host = opts.host || "localhost";
family = opts.family || 0;
}
if (!host) host = "localhost";
const {
lookup = dns.lookup,
hints,
keepAlive = false,
keepAliveInitialDelay = 0,
noDelay = false,
timeout
} = opts;
const type = ip.isIP(host);
if (type === 0) {
lookup(host, { all: true, family, hints }, (err, addresses) => {
if (this._state & constants.state.CLOSING) return;
this._state &= ~constants.state.CONNECTING;
if (err || addresses.length === 0) {
if (!err) {
err = new Error(`No address found for host "${host}"`);
err.code = "ENOTFOUND";
}
this.emit("lookup", err, null, 0, host);
if (this._pendingOpen) this._continueOpen(err);
else this.destroy(err);
return;
}
for (const { address: address2, family: family3 } of addresses) {
this.emit("lookup", null, address2, family3, host);
}
const [{ address, family: family2 }, ...rest] = addresses;
if (rest.length > 0) {
this._addresses = rest.map(({ address: address2, family: family3 }) => [
port,
address2,
{ ...opts, family: family3 },
onconnect
]);
this._errors = [];
}
this.connect(port, address, { ...opts, family: family2 }, onconnect);
});
return this;
}
family = type;
try {
binding.connect(this._handle, port, host, family);
if (keepAlive) {
this._keepAlive = keepAlive;
this._keepAliveInitialDelay = keepAliveInitialDelay;
}
if (noDelay) this._noDelay = noDelay;
if (timeout) this.setTimeout(timeout);
if (onconnect) this.once("connect", onconnect);
} catch (err) {
queueMicrotask(() => {
if (this._pendingOpen) this._pendingOpen(err);
else this.destroy(err);
});
}
return this;
}
setKeepAlive(enable = false, delay = 0) {
if (typeof enable === "number") {
delay = enable;
enable = false;
}
delay = Math.floor(delay / 1e3);
if (delay === 0) enable = false;
binding.keepalive(this._handle, enable, delay);
return this;
}
setNoDelay(enable = true) {
binding.nodelay(this._handle, enable);
return this;
}
setTimeout(ms, ontimeout) {
if (ms === 0) {
clearTimeout(this._timer);
this._timer = null;
} else {
if (ontimeout) this.once("timeout", ontimeout);
this._timer = setTimeout(() => this.emit("timeout"), ms);
this._timer.unref();
}
this._timeout = ms;
return this;
}
ref() {
binding.ref(this._handle);
return this;
}
unref() {
binding.unref(this._handle);
return this;
}
_open(cb) {
if (this._state & constants.state.CONNECTED) return cb(null);
this._pendingOpen = cb;
}
_read() {
if ((this._state & constants.state.READING) === 0) {
this._state |= constants.state.READING;
binding.resume(this._handle);
}
}
_writev(batch, cb) {
this._pendingWrite = [cb, batch];
binding.writev(
this._handle,
batch.map(({ chunk }) => chunk)
);
}
_final(cb) {
this._pendingFinal = cb;
binding.end(this._handle);
}
_predestroy() {
if (this._state & constants.state.CLOSING) return;
this._state |= constants.state.CLOSING;
binding.close(this._handle);
}
_destroy(err, cb) {
if (this._state & constants.state.CLOSING) return cb(err);
this._state |= constants.state.CLOSING;
this._pendingDestroy = cb;
binding.close(this._handle);
}
_continueOpen(err) {
if (this._pendingOpen === null) return;
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(err);
}
_continueWrite(err) {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite[0];
this._pendingWrite = null;
cb(err);
}
_continueFinal(err) {
if (this._pendingFinal === null) return;
const cb = this._pendingFinal;
this._pendingFinal = null;
cb(err);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
_reset() {
this._state = 0;
this._localAddress = null;
this._remoteAddress = null;
binding.reset(this._handle);
}
_onconnect(err) {
if (err) {
if (this._addresses !== null) {
this._errors.push(err);
if (this._addresses.length > 0) return this._reset();
err = this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors);
}
if (this._pendingOpen) this._continueOpen(err);
else this.destroy(err);
return;
}
if (this._keepAlive) this.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay);
if (this._noDelay) this.setNoDelay();
this._localAddress = binding.address(this._handle, true);
this._remoteAddress = binding.address(this._handle, false);
this._state |= constants.state.CONNECTED;
this._state &= ~constants.state.CONNECTING;
this._continueOpen();
this.emit("connect");
}
_onreset(err) {
if (err) {
this._errors.push(err);
this.destroy(this._errors.length === 1 ? this._errors[0] : new AggregateError(this._errors));
return;
}
this.connect(...this._addresses.shift());
}
_onread(err, read) {
if (this._timer) this._timer.refresh();
if (err) {
this.destroy(err);
return;
}
if (read === 0) {
this.push(null);
if (this._allowHalfOpen === false) this.end();
return;
}
const copy = Buffer.allocUnsafe(read);
copy.set(this._buffer.subarray(0, read));
if (this.push(copy) === false && this.destroying === false) {
this._state &= ~constants.state.READING;
binding.pause(this._handle);
}
}
_onwrite(err) {
if (this._timer) this._timer.refresh();
this._continueWrite(err);
}
_onfinal(err) {
this._continueFinal(err);
}
_onclose() {
clearTimeout(this._timer);
this._continueDestroy();
}
};
exports.Server = class TCPServer extends EventEmitter {
constructor(opts = {}, onconnection) {
if (typeof opts === "function") {
onconnection = opts;
opts = {};
}
super();
const {
readBufferSize = defaultReadBufferSize,
allowHalfOpen = true,
keepAlive = false,
keepAliveInitialDelay = 0,
noDelay = false,
pauseOnConnect = false
} = opts;
this._state = 0;
this._readBufferSize = readBufferSize;
this._allowHalfOpen = allowHalfOpen;
this._keepAlive = keepAlive;
this._keepAliveInitialDelay = keepAliveInitialDelay;
this._noDelay = noDelay;
this._pauseOnConnect = pauseOnConnect;
this._address = null;
this._connections = /* @__PURE__ */ new Set();
this._error = null;
this._handle = null;
if (onconnection) this.on("connection", onconnection);
}
get listening() {
return (this._state & constants.state.BOUND) !== 0;
}
get closing() {
return (this._state & constants.state.CLOSING) !== 0;
}
get connections() {
return this._connections;
}
address() {
if ((this._state & constants.state.BOUND) === 0) return null;
const { address, family, port } = this._address;
return { address, family: `IPv${family}`, port };
}
listen(port = 0, host = "localhost", backlog = 511, opts = {}, onlistening) {
if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
throw errors.SERVER_ALREADY_LISTENING("Server is already listening");
}
if (this._state & constants.state.CLOSING) {
throw errors.SERVER_IS_CLOSED("Server is closed");
}
this._state |= constants.state.BINDING;
if (typeof port === "function") {
onlistening = port;
port = 0;
} else if (typeof host === "function") {
onlistening = host;
host = "localhost";
} else if (typeof backlog === "function") {
onlistening = backlog;
backlog = 511;
} else if (typeof opts === "function") {
onlistening = opts;
opts = {};
}
let family = 0;
if (typeof port === "object" && port !== null) {
opts = port || {};
port = opts.port || 0;
host = opts.host || "localhost";
family = opts.family || 0;
backlog = opts.backlog || 511;
}
if (!host) host = "localhost";
if (!backlog) backlog = 511;
const { lookup = dns.lookup, hints } = opts;
const type = ip.isIP(host);
if (type === 0) {
lookup(host, { family, hints }, (err, address, family2) => {
if (this._state & constants.state.CLOSING) return;
this.emit("lookup", err, address, family2, host);
this._state &= ~constants.state.BINDING;
if (err) return this.emit("error", err);
this.listen(port, address, backlog, { ...opts, family: family2 }, onlistening);
});
return this;
}
family = type;
this._handle = binding.init(
empty,
this,
this._onconnection,
noop,
noop,
noop,
noop,
noop,
this._onclose
);
if (this._state & constants.state.UNREFED) binding.unref(this._handle);
try {
binding.bind(this._handle, port, host, backlog, family);
this._address = binding.address(this._handle, true);
this._state |= constants.state.BOUND;
this._state &= ~constants.state.BINDING;
if (onlistening) this.once("listening", onlistening);
queueMicrotask(() => this.emit("listening"));
} catch (err) {
this._error = err;
binding.close(this._handle);
}
return this;
}
close(onclose) {
if (onclose) this.once("close", onclose);
if (this._state & constants.state.CLOSING) return this;
this._state |= constants.state.CLOSING;
this._closeMaybe();
return this;
}
ref() {
this._state &= ~constants.state.UNREFED;
if (this._handle !== null) binding.ref(this._handle);
return this;
}
unref() {
this._state |= constants.state.UNREFED;
if (this._handle !== null) binding.unref(this._handle);
return this;
}
_closeMaybe() {
if (this._state & constants.state.CLOSING && this._connections.size === 0) {
if (this._handle !== null) binding.close(this._handle);
else queueMicrotask(() => this.emit("close"));
}
}
_onconnection(err) {
if (err) {
this.emit("error", err);
return;
}
if (this._state & constants.state.CLOSING) return;
const socket = new exports.Socket({
readBufferSize: this._readBufferSize,
allowHalfOpen: this._allowHalfOpen,
eagerOpen: !this._pauseOnConnect
});
try {
binding.accept(this._handle, socket._handle);
socket._localAddress = binding.address(socket._handle, true);
socket._remoteAddress = binding.address(socket._handle, false);
socket._state |= constants.state.CONNECTED;
this._connections.add(socket);
if (this._keepAlive) socket.setKeepAlive(this._keepAlive, this._keepAliveInitialDelay);
if (this._noDelay) socket.setNoDelay();
socket.on("close", () => {
this._connections.delete(socket);
this._closeMaybe();
});
this.emit("connection", socket);
} catch (err2) {
socket.destroy();
this.emit("error", err2);
}
}
_onclose() {
const err = this._error;
this._state &= ~constants.state.BINDING;
this._error = null;
this._handle = null;
this._address = null;
if (err) this.emit("error", err);
else this.emit("close");
}
};
exports.constants = constants;
exports.errors = errors;
exports.isIP = ip.isIP;
exports.isIPv4 = ip.isIPv4;
exports.isIPv6 = ip.isIPv6;
exports.createConnection = function createConnection(port, host, opts, onconnect) {
if (typeof host === "function") {
onconnect = host;
host = "localhost";
} else if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
if (typeof port === "object" && port !== null) {
opts = port || {};
port = opts.port || 0;
host = opts.host || "localhost";
}
return new exports.Socket(opts).connect(port, host, opts, onconnect);
};
exports.connect = exports.createConnection;
exports.createServer = function createServer(opts, onconnection) {
return new exports.Server(opts, onconnection);
};
function noop() {
}
}
});
// ../../node_modules/bare-pipe/binding.js
var require_binding10 = __commonJS({
"../../node_modules/bare-pipe/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-pipe/lib/constants.js
var require_constants7 = __commonJS({
"../../node_modules/bare-pipe/lib/constants.js"(exports, module) {
module.exports = {
state: {
CONNECTING: 1,
CONNECTED: 2,
BINDING: 4,
BOUND: 8,
READING: 16,
CLOSING: 32,
READABLE: 64,
WRITABLE: 128,
UNREFED: 256
}
};
}
});
// ../../node_modules/bare-pipe/lib/errors.js
var require_errors12 = __commonJS({
"../../node_modules/bare-pipe/lib/errors.js"(exports, module) {
module.exports = class PipeError extends Error {
constructor(msg, fn = PipeError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "PipeError";
}
static PIPE_ALREADY_CONNECTED(msg) {
return new PipeError(msg, PipeError.PIPE_ALREADY_CONNECTED);
}
static SERVER_ALREADY_LISTENING(msg) {
return new PipeError(msg, PipeError.SERVER_ALREADY_LISTENING);
}
static SERVER_IS_CLOSED(msg) {
return new PipeError(msg, PipeError.SERVER_IS_CLOSED);
}
};
}
});
// ../../node_modules/bare-pipe/index.js
var require_bare_pipe = __commonJS({
"../../node_modules/bare-pipe/index.js"(exports, module) {
var EventEmitter = require_bare_events();
var { Duplex } = require_bare_stream();
var binding = require_binding10();
var constants = require_constants7();
var errors = require_errors12();
var defaultReadBufferSize = 65536;
var empty = Buffer.alloc(0);
module.exports = exports = class Pipe extends Duplex {
constructor(path, opts = {}) {
if (typeof path === "object" && path !== null) {
opts = path;
path = null;
}
const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true, eagerOpen = true } = opts;
super({ eagerOpen });
this._state = 0;
this._allowHalfOpen = allowHalfOpen;
this._fd = -1;
this._path = null;
this._pendingOpen = null;
this._pendingWrite = null;
this._pendingFinal = null;
this._pendingDestroy = null;
this._buffer = Buffer.alloc(readBufferSize);
this._handle = binding.init(
this._buffer,
this,
noop,
this._onconnect,
this._onwrite,
this._onfinal,
this._onread,
this._onclose
);
if (typeof path === "number") {
this.open(path);
} else if (typeof path === "string") {
this.connect(path);
}
}
get connecting() {
return (this._state & constants.state.CONNECTING) !== 0;
}
get pending() {
return (this._state & constants.state.CONNECTED) === 0;
}
get readyState() {
if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
return "open";
}
if (this._state & constants.state.READABLE) {
return "readOnly";
}
if (this._state & constants.state.WRITABLE) {
return "writeOnly";
}
return "opening";
}
open(fd, opts = {}, onconnect) {
if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
if (typeof fd === "object" && fd !== null) {
opts = fd || {};
fd = opts.fd;
}
try {
const status = binding.open(this._handle, fd);
this._state |= constants.state.CONNECTED;
this._fd = fd;
if (status & binding.READABLE) {
this._state |= constants.state.READABLE;
} else {
this.push(null);
}
if (status & binding.WRITABLE) {
this._state |= constants.state.WRITABLE;
} else {
this.end();
}
if (onconnect) this.once("connect", onconnect);
queueMicrotask(() => this.emit("connect"));
} catch (err) {
queueMicrotask(() => {
if (this._pendingOpen) this._pendingOpen(err);
else this.destroy(err);
});
}
return this;
}
connect(path, opts = {}, onconnect) {
if (this._state & constants.state.CONNECTING || this._state & constants.state.CONNECTED) {
throw errors.PIPE_ALREADY_CONNECTED("Pipe is already connected");
}
this._state |= constants.state.CONNECTING;
if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
if (typeof path === "object" && path !== null) {
opts = path || {};
path = opts.path;
}
try {
binding.connect(this._handle, path);
this._path = path;
if (onconnect) this.once("connect", onconnect);
} catch (err) {
queueMicrotask(() => {
if (this._pendingOpen) this._pendingOpen(err);
else this.destroy(err);
});
}
return this;
}
ref() {
binding.ref(this._handle);
return this;
}
unref() {
binding.unref(this._handle);
return this;
}
_open(cb) {
if (this._state & constants.state.CONNECTED) return cb(null);
this._pendingOpen = cb;
}
_read() {
if ((this._state & constants.state.READING) === 0) {
this._state |= constants.state.READING;
binding.resume(this._handle);
}
}
_writev(batch, cb) {
this._pendingWrite = [cb, batch];
binding.writev(
this._handle,
batch.map(({ chunk }) => chunk)
);
}
_final(cb) {
if (this._state & constants.state.READABLE && this._state & constants.state.WRITABLE) {
this._pendingFinal = cb;
binding.end(this._handle);
} else {
cb(null);
}
}
_predestroy() {
if (this._state & constants.state.CLOSING) return;
this._state |= constants.state.CLOSING;
binding.close(this._handle);
}
_destroy(err, cb) {
if (this._state & constants.state.CLOSING) return cb(err);
this._state |= constants.state.CLOSING;
this._pendingDestroy = cb;
binding.close(this._handle);
}
_continueOpen(err) {
if (this._pendingOpen === null) return;
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(err);
}
_continueWrite(err) {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite[0];
this._pendingWrite = null;
cb(err);
}
_continueFinal(err) {
if (this._pendingFinal === null) return;
const cb = this._pendingFinal;
this._pendingFinal = null;
cb(err);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
_onconnect(err) {
if (err) {
if (this._pendingOpen) this._continueOpen(err);
else this.destroy(err);
return;
}
this._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE;
this._state &= ~constants.state.CONNECTING;
this._continueOpen();
this.emit("connect");
}
_onread(err, read) {
if (err) {
this.destroy(err);
return;
}
if (read === 0) {
this.push(null);
if (this._allowHalfOpen === false) this.end();
return;
}
const copy = Buffer.allocUnsafe(read);
copy.set(this._buffer.subarray(0, read));
if (this.push(copy) === false && this.destroying === false) {
this._state &= ~constants.state.READING;
binding.pause(this._handle);
}
}
_onwrite(err) {
this._continueWrite(err);
}
_onfinal(err) {
this._continueFinal(err === null || err.code === "ENOTCONN" ? null : err);
}
_onclose() {
this._continueDestroy();
}
_onspawn(readable, writable) {
this._state |= constants.state.CONNECTED;
if (readable) {
this._state |= constants.state.READABLE;
} else {
this.push(null);
}
if (writable) {
this._state |= constants.state.WRITABLE;
} else {
this.end();
}
this._continueOpen();
}
};
exports.Pipe = exports;
exports.pipe = function pipe() {
return binding.pipe();
};
exports.Server = class PipeServer extends EventEmitter {
constructor(opts = {}, onconnection) {
if (typeof opts === "function") {
onconnection = opts;
opts = {};
}
super();
const {
readBufferSize = defaultReadBufferSize,
allowHalfOpen = true,
pauseOnConnect = false
} = opts;
this._state = 0;
this._readBufferSize = readBufferSize;
this._allowHalfOpen = allowHalfOpen;
this._pauseOnConnect = pauseOnConnect;
this._path = null;
this._connections = /* @__PURE__ */ new Set();
this._error = null;
this._handle = null;
if (onconnection) this.on("connection", onconnection);
}
get listening() {
return (this._state & constants.state.BOUND) !== 0;
}
address() {
if ((this._state & constants.state.BOUND) === 0) {
return null;
}
return this._path;
}
listen(path, backlog = 511, opts = {}, onlistening) {
if (this._state & constants.state.BINDING || this._state & constants.state.BOUND) {
throw errors.SERVER_ALREADY_LISTENING("Server is already listening");
}
if (this._state & constants.state.CLOSING) {
throw errors.SERVER_IS_CLOSED("Server is closed");
}
this._state |= constants.state.BINDING;
if (typeof backlog === "function") {
onlistening = backlog;
backlog = 511;
} else if (typeof opts === "function") {
onlistening = opts;
opts = {};
}
if (typeof path === "object" && path !== null) {
opts = path || {};
path = opts.path;
backlog = opts.backlog || 511;
}
this._handle = binding.init(
empty,
this,
this._onconnection,
noop,
noop,
noop,
noop,
this._onclose
);
if (this._state & constants.state.UNREFED) binding.unref(this._handle);
try {
binding.bind(this._handle, path, backlog);
this._path = path;
this._state |= constants.state.BOUND;
this._state &= ~constants.state.BINDING;
if (onlistening) this.once("listening", onlistening);
queueMicrotask(() => this.emit("listening"));
} catch (err) {
this._error = err;
binding.close(this._handle);
}
return this;
}
close(onclose) {
if (onclose) this.once("close", onclose);
if (this._state & constants.state.CLOSING) return;
this._state |= constants.state.CLOSING;
this._closeMaybe();
return this;
}
ref() {
this._state &= ~constants.state.UNREFED;
if (this._handle !== null) binding.ref(this._handle);
return this;
}
unref() {
this._state |= constants.state.UNREFED;
if (this._handle !== null) binding.unref(this._handle);
return this;
}
_closeMaybe() {
if (this._state & constants.state.CLOSING && this._connections.size === 0) {
if (this._handle !== null) binding.close(this._handle);
else queueMicrotask(() => this.emit("close"));
}
}
_onconnection(err) {
if (err) {
this.emit("error", err);
return;
}
if (this._state & constants.state.CLOSING) return;
const pipe = new exports.Pipe({
readBufferSize: this._readBufferSize,
allowHalfOpen: this._allowHalfOpen,
eagerOpen: !this._pauseOnConnect
});
try {
binding.accept(this._handle, pipe._handle);
pipe._path = this._path;
pipe._state |= constants.state.CONNECTED | constants.state.READABLE | constants.state.WRITABLE;
this._connections.add(pipe);
pipe.on("close", () => {
this._connections.delete(pipe);
this._closeMaybe();
});
this.emit("connection", pipe);
} catch (err2) {
pipe.destroy();
throw err2;
}
}
_onclose() {
const err = this._error;
this._state &= ~constants.state.BINDING;
this._error = null;
this._handle = null;
if (err) this.emit("error", err);
else this.emit("close");
}
};
exports.constants = constants;
exports.errors = errors;
exports.createConnection = function createConnection(path, opts, onconnect) {
if (typeof opts === "function") {
onconnect = opts;
opts = {};
}
if (typeof path === "object" && path !== null) {
opts = path || {};
path = opts.path;
}
return new exports.Pipe(opts).connect(path, opts, onconnect);
};
exports.createServer = function createServer(opts, onconnection) {
return new exports.Server(opts, onconnection);
};
function noop() {
}
}
});
// ../bare-os-openssh/vendor/bare-node-shims/bare-net/lib/constants.js
var require_constants8 = __commonJS({
"../bare-os-openssh/vendor/bare-node-shims/bare-net/lib/constants.js"(exports, module) {
module.exports = {
type: {
TCP: 1,
IPC: 2
},
state: {
UNREFED: 1
}
};
}
});
// ../bare-os-openssh/vendor/bare-node-shims/bare-net/index.js
var require_bare_net = __commonJS({
"../bare-os-openssh/vendor/bare-node-shims/bare-net/index.js"(exports) {
var EventEmitter = require_bare_events();
var { Duplex } = require_bare_stream();
var tcp = require_bare_tcp();
var pipe = require_bare_pipe();
var constants = require_constants8();
var defaultReadBufferSize = 65536;
exports.Socket = class NetSocket extends Duplex {
constructor(opts = {}) {
const {
readBufferSize = defaultReadBufferSize,
allowHalfOpen = false,
eagerOpen = false
} = opts;
super({ eagerOpen, allowHalfOpen });
this._type = 0;
this._state = 0;
this._socket = null;
this._opts = { readBufferSize, allowHalfOpen, eagerOpen };
this._pendingOpen = null;
this._pendingWrite = null;
this._pendingFinal = null;
this._pendingDestroy = null;
}
get connecting() {
return this._socket !== null && this._socket.connecting;
}
get pending() {
return this._socket === null || this._socket.pending;
}
get timeout() {
return this._socket === null ? void 0 : this._socket.timeout;
}
get readyState() {
return this._socket === null ? "opening" : this._socket.readyState;
}
get localAddress() {
return this._socket === null ? void 0 : this._socket.localAddress;
}
get localPort() {
return this._socket === null ? void 0 : this._socket.localPort;
}
get localFamily() {
return this._socket === null ? void 0 : this._socket.localFamily;
}
get remoteAddress() {
return this._socket === null ? void 0 : this._socket.remoteAddress;
}
get remotePort() {
return this._socket === null ? void 0 : this._socket.remotePort;
}
get remoteFamily() {
return this._socket === null ? void 0 : this._socket.remoteFamily;
}
connect(...args) {
let opts = {};
let onconnect;
if (typeof args[0] === "string") {
opts.path = args[0];
onconnect = args[1];
} else if (typeof args[0] === "number") {
opts.port = args[0];
if (typeof args[1] === "function") {
onconnect = args[1];
} else {
opts.host = args[1];
onconnect = args[2];
}
} else {
opts = args[0] || {};
onconnect = args[1];
}
opts = { ...opts, ...this._opts };
if (opts.path) {
this._attach(constants.type.IPC, pipe.createConnection(opts));
} else {
this._attach(constants.type.TCP, tcp.createConnection(opts));
}
if (onconnect) this.once("connect", onconnect);
return this;
}
setKeepAlive(...args) {
if (this._socket !== null) this._socket.setKeepAlive(...args);
return this;
}
setNoDelay(...args) {
if (this._socket !== null) this._socket.setNoDelay(...args);
return this;
}
setTimeout(...args) {
if (this._socket !== null) this._socket.setTimeout(...args);
return this;
}
ref() {
this._state &= ~constants.state.UNREFED;
if (this._socket !== null) this._socket.ref();
return this;
}
unref() {
this._state |= constants.state.UNREFED;
if (this._socket !== null) this._socket.unref();
return this;
}
_attach(type, socket) {
this._type = type;
this._socket = socket;
this._socket.on("connect", this._onconnect.bind(this)).on("timeout", this._ontimeout.bind(this)).on("error", this._onerror.bind(this)).on("data", this._ondata.bind(this)).on("end", this._onend.bind(this)).on("finish", this._onfinish.bind(this)).on("drain", this._ondrain.bind(this)).on("close", this._onclose.bind(this));
if (this._state & constants.state.UNREFED) this._socket.unref();
this._continueOpen();
return this;
}
_open(cb) {
if (this._socket !== null) return cb(null);
this._pendingOpen = cb;
}
_write(data, encoding, cb) {
if (this._socket.write(data)) return cb(null);
this._pendingWrite = cb;
}
_final(cb) {
this._socket.end();
this._pendingFinal = cb;
}
_destroy(err, cb) {
if (this._socket === null || this._socket.destroyed) return cb(null);
this._socket.destroy(err);
this._pendingDestroy = cb;
}
_onconnect() {
this.emit("connect");
}
_ontimeout() {
this.emit("timeout");
}
_onerror(err) {
this.destroy(err);
}
_ondata(data) {
this.push(data);
}
_onend() {
this.push(null);
}
_onfinish() {
this._continueFinal();
}
_ondrain() {
this._continueWrite();
}
_onclose() {
this._continueWrite();
this._continueFinal();
if (this._pendingDestroy) this._continueDestroy();
else this.destroy();
}
_continueOpen() {
if (this._pendingOpen === null) return;
const cb = this._pendingOpen;
this._pendingOpen = null;
cb(null);
}
_continueWrite() {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite;
this._pendingWrite = null;
cb(null);
}
_continueFinal() {
if (this._pendingFinal === null) return;
const cb = this._pendingFinal;
this._pendingFinal = null;
cb(null);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
};
exports.Server = class NetServer extends EventEmitter {
constructor(opts = {}, onconnection) {
if (typeof opts === "function") {
onconnection = opts;
opts = {};
}
super();
const {
readBufferSize = defaultReadBufferSize,
allowHalfOpen = false,
pauseOnConnect = false
} = opts;
this._type = 0;
this._state = 0;
this._server = null;
this._opts = { readBufferSize, allowHalfOpen, pauseOnConnect };
if (onconnection) this.on("connection", onconnection);
}
get listening() {
return this._server !== null && this._server.listening;
}
address() {
return this._server === null ? null : this._server.address();
}
listen(...args) {
let opts = {};
let onlistening;
if (typeof args[0] === "string") {
opts.path = args[0];
if (typeof args[1] === "function") {
onlistening = args[1];
} else {
opts.backlog = args[1];
onlistening = args[2];
}
} else {
if (typeof args[0] === "function") {
onlistening = args[0];
} else {
opts.port = args[0];
if (typeof args[1] === "function") {
onlistening = args[1];
} else {
opts.host = args[1];
if (typeof args[2] === "function") {
onlistening = args[2];
} else {
opts.backlog = args[2];
onlistening = args[3];
}
}
}
}
opts = { ...opts, ...this._opts };
if (opts.path) {
this._attach(constants.type.IPC, pipe.createServer(opts));
} else {
this._attach(constants.type.TCP, tcp.createServer(opts));
}
this._server.listen(opts);
if (onlistening) this.once("listening", onlistening);
return this;
}
close(onclose) {
if (onclose) this.once("close", onclose);
this._server.close();
return this;
}
ref() {
this._state &= ~constants.state.UNREFED;
if (this._server !== null) this._server.ref();
return this;
}
unref() {
this._state |= constants.state.UNREFED;
if (this._server !== null) this._server.unref();
return this;
}
_attach(type, server) {
this._type = type;
this._server = server;
this._server.on("listening", this._onlistening.bind(this)).on("connection", this._onconnection.bind(this)).on("error", this._onerror.bind(this)).on("close", this._onclose.bind(this));
if (this._state & constants.state.UNREFED) this._server.unref();
return this;
}
_onlistening() {
this.emit("listening");
}
_onconnection(socket) {
this.emit("connection", new exports.Socket(this._opts)._attach(this._type, socket));
}
_onerror(err) {
this.emit("error", err);
}
_onclose() {
this.emit("close");
}
};
exports.constants = constants;
exports.isIP = tcp.isIP;
exports.isIPv4 = tcp.isIPv4;
exports.isIPv6 = tcp.isIPv6;
exports.createConnection = function createConnection(...args) {
let opts = {};
let onconnect;
if (typeof args[0] === "string") {
opts.path = args[0];
onconnect = args[1];
} else if (typeof args[0] === "number") {
opts.port = args[0];
if (typeof args[1] === "function") {
onconnect = args[1];
} else {
opts.host = args[1];
onconnect = args[2];
}
} else {
opts = args[0] || {};
onconnect = args[1];
}
return new exports.Socket(opts).connect(opts, onconnect);
};
exports.connect = exports.createConnection;
exports.createServer = function createServer(opts, onconnection) {
return new exports.Server(opts, onconnection);
};
}
});
// ../bare-os-openssh/vendor/bare-node-shims/bare-node-net/index.js
var require_bare_node_net = __commonJS({
"../bare-os-openssh/vendor/bare-node-shims/bare-node-net/index.js"(exports, module) {
module.exports = require_bare_net();
}
});
// ../../node_modules/@holesail/hyper-cmd-lib-net/index.js
var require_hyper_cmd_lib_net = __commonJS({
"../../node_modules/@holesail/hyper-cmd-lib-net/index.js"(exports, module) {
var dgram = require_bare_dgram();
var net = require_bare_node_net();
var EventEmitter = require_bare_node_events();
function connPiper(connection, _dst, opts = {}, stats = {}) {
const logger = opts.logger || { log: () => {
} };
logger.log({ type: 1, msg: "Starting TCP connection piper" });
const loc = _dst();
if (loc === null) {
logger.log({ type: 2, msg: "Connection rejected (null destination)" });
connection.destroy();
if (!stats.rejectCnt) {
stats.rejectCnt = 0;
}
stats.rejectCnt++;
return;
}
if (!stats.locCnt) {
stats.locCnt = 0;
}
if (!stats.remCnt) {
stats.remCnt = 0;
}
stats.locCnt++;
stats.remCnt++;
let destroyed = false;
loc.on("data", (d) => {
logger.log({ type: 0, msg: `Data from local to remote: ${d.length} bytes` });
connection.write(d);
});
connection.on("data", (d) => {
logger.log({ type: 0, msg: `Data from remote to local: ${d.length} bytes` });
loc.write(d);
});
loc.on("error", destroy).on("close", destroy);
connection.on("error", destroy).on("close", destroy);
loc.on("end", () => {
logger.log({ type: 0, msg: "Local end, ending connection" });
connection.end();
});
connection.on("end", () => {
logger.log({ type: 0, msg: "Connection end, ending local" });
loc.end();
});
loc.on("connect", (err) => {
if (err) {
logger.log({ type: 3, msg: err.message });
} else {
logger.log({ type: 1, msg: "Connected" });
}
});
function destroy(err) {
if (destroyed) {
return;
}
logger.log({
type: 1,
msg: `Destroying connection piper${err ? ` due to error: ${err.message}` : ""}`
});
stats.locCnt--;
stats.remCnt--;
destroyed = true;
loc.end();
connection.end();
loc.destroy(err);
connection.destroy(err);
if (opts.onDestroy) {
opts.onDestroy(err);
}
}
return {};
}
var UdpSocket = class {
constructor(opts) {
this.opts = opts;
this.logger = this.opts.logger || { log: () => {
} };
this.server = dgram.createSocket("udp4");
this.client = dgram.createSocket("udp4");
this.event = new EventEmitter();
this.rinfo = null;
this.connect();
this.logger.log({
type: 1,
msg: `UDP socket created${opts.bind ? `, binding to ${opts.host}:${opts.port}` : ""}`
});
}
connect() {
if (this.opts.bind) {
this.server.bind(this.opts.port, this.opts.host);
}
this.server.on("message", (msg, rinfo) => {
this.logger.log({
type: 0,
msg: `UDP message from server: ${msg.length} bytes from ${rinfo.address}:${rinfo.port}`
});
this.event.emit("message", msg, rinfo);
this.rinfo = rinfo;
});
this.client.on("message", (response, rinfo) => {
this.logger.log({
type: 0,
msg: `UDP message from client: ${response.length} bytes from ${rinfo.address}:${rinfo.port}`
});
this.event.emit("message", response);
});
this.client.on("error", (err) => {
this.logger.log({ type: 3, msg: `UDP error: ${err.stack}` });
this.client.close();
});
}
write(msg) {
this.logger.log({ type: 0, msg: `Writing UDP message: ${msg.length} bytes` });
if (this.rinfo) {
this.server.send(msg, 0, msg.length, this.rinfo.port, this.rinfo.address);
} else {
this.client.send(msg, 0, msg.length, this.opts.port, this.opts.host);
}
}
};
var UdpConnPiper = class {
constructor(remote, local, opts = {}) {
this.opts = opts;
this.logger = this.opts.logger || { log: () => {
} };
this.remote = remote;
this.local = local;
this.client = opts.client;
this.retryDelay = opts.retryDelay || 2e3;
this.destroyed = false;
this._bindListeners();
this.connect();
this.logger.log({
type: 1,
msg: `Starting UDP connection piper${opts.client ? " (client mode)" : " (server mode)"}`
});
}
_bindListeners() {
this.bound = {
onLocMessage: this.onLocMessage.bind(this),
onConnectionMessage: this.onConnectionMessage.bind(this),
onLocError: this._handleError.bind(this),
onLocClose: this._handleError.bind(this),
onConnectionError: this._handleError.bind(this),
onConnectionClose: this._handleError.bind(this)
};
}
connect() {
if (this.destroyed) return;
this.logger.log({ type: 0, msg: "Connecting UDP piper" });
this.removeListeners();
this.localStream = typeof this.local === "function" ? this.local() : this.local;
this.remoteStream = typeof this.remote === "function" ? this.remote() : this.remote;
if (!this.localStream || !this.remoteStream) {
this.logger.log({ type: 2, msg: "UDP connect failed (missing streams)" });
this.destroy();
return;
}
this.attachListeners();
}
attachListeners() {
this.localStream.event.on("message", this.bound.onLocMessage);
this.localStream.server.on("error", this.bound.onLocError);
this.localStream.server.on("close", this.bound.onLocClose);
this.remoteStream.on("message", this.bound.onConnectionMessage);
this.remoteStream.on("error", this.bound.onConnectionError);
this.remoteStream.on("close", this.bound.onConnectionClose);
this.logger.log({ type: 0, msg: "UDP listeners attached" });
}
removeListeners() {
if (this.localStream) {
this.localStream.event.off("message", this.bound.onLocMessage);
this.localStream.server.off("error", this.bound.onLocError);
this.localStream.server.off("close", this.bound.onLocClose);
}
if (this.remoteStream) {
this.remoteStream.off("message", this.bound.onConnectionMessage);
this.remoteStream.off("error", this.bound.onConnectionError);
this.remoteStream.off("close", this.bound.onConnectionClose);
}
this.logger.log({ type: 0, msg: "UDP listeners removed" });
}
onLocMessage(msg, rinfo) {
this.logger.log({ type: 0, msg: `UDP message from local: ${msg.length} bytes` });
if (this.remoteStream && !this.destroyed) {
this.remoteStream.trySend?.(msg);
}
}
onConnectionMessage(msg) {
this.logger.log({ type: 0, msg: `UDP message from connection: ${msg.length} bytes` });
if (this.localStream && !this.destroyed) {
this.localStream.write?.(msg);
}
}
_handleError(err) {
this.logger.log({ type: 2, msg: `UDP error: ${err ? err.message : "close"}` });
this.destroy(err);
}
destroy(err) {
if (this.destroyed) return;
this.destroyed = true;
this.logger.log({
type: 1,
msg: `Destroying UDP piper${err ? ` due to error: ${err.message}` : ""}`
});
this.removeListeners();
try {
this.localStream?.destroy?.(err);
} catch (e) {
}
try {
this.remoteStream?.close?.(err);
} catch (e) {
}
if (this.client) {
this.logger.log({ type: 1, msg: `Scheduling retry in ${this.retryDelay}ms` });
setTimeout(() => {
this.destroyed = false;
this.connect();
}, this.retryDelay);
}
}
};
function udpConnect(opts, callback) {
const socket = new UdpSocket(opts);
if (typeof callback === "function") {
callback(socket);
} else {
return socket;
}
}
function udpPiper(connection, _dst, opts) {
return new UdpConnPiper(connection, _dst, opts);
}
function createTcpProxy(listenOpts, connectRemote, piperOpts, stats, onListen) {
const proxy = net.createServer({ allowHalfOpen: true }, (c) => {
connPiper(c, connectRemote, piperOpts, stats);
});
proxy.listen(listenOpts.port, listenOpts.host, onListen);
return proxy;
}
function pipeTcpServer(remoteStream, localOpts, piperOpts, stats) {
connPiper(
remoteStream,
() => net.connect({
port: +localOpts.port,
host: localOpts.host,
allowHalfOpen: true
}),
piperOpts,
stats
);
}
function createUdpFramedProxy(listenOpts, connectRemote, logger, onBind) {
const proxySocket = dgram.createSocket("udp4");
const clients = /* @__PURE__ */ new Map();
proxySocket.on("error", (err) => {
logger.log({ type: 3, msg: `Proxy socket error: ${err.stack}` });
proxySocket.close();
});
proxySocket.on("message", (msg, rinfo) => {
const clientId = `${rinfo.address}:${rinfo.port}`;
logger.log({ type: 0, msg: `UDP message from ${clientId}: ${msg.length} bytes` });
let client = clients.get(clientId);
if (!client) {
const remoteStream = connectRemote();
client = { remoteStream, rinfo, buffer: Buffer.alloc(0) };
clients.set(clientId, client);
remoteStream.on("data", (chunk) => {
client.buffer = Buffer.concat([client.buffer, chunk]);
while (client.buffer.length >= 4) {
const len = client.buffer.readUInt32BE(0);
if (client.buffer.length < 4 + len) break;
const response = client.buffer.slice(4, 4 + len);
logger.log({ type: 0, msg: `UDP response for ${clientId}: ${response.length} bytes` });
proxySocket.send(response, 0, response.length, rinfo.port, rinfo.address, (err) => {
if (err) logger.log({ type: 3, msg: `Send error to ${clientId}: ${err.stack}` });
});
client.buffer = client.buffer.slice(4 + len);
}
});
remoteStream.on("error", (err) => {
logger.log({ type: 3, msg: `Remote error for ${clientId}: ${err.stack}` });
clients.delete(clientId);
remoteStream.destroy();
});
remoteStream.on("close", () => {
logger.log({ type: 0, msg: `Remote close for ${clientId}` });
clients.delete(clientId);
});
}
const lenBuf = Buffer.alloc(4);
lenBuf.writeUInt32BE(msg.length, 0);
client.remoteStream.write(Buffer.concat([lenBuf, msg]));
});
proxySocket.bind(listenOpts.port, listenOpts.host, onBind);
return { proxySocket, clients };
}
function pipeUdpFramedServer(remoteStream, localOpts, logger, stats) {
const localSocket = dgram.createSocket("udp4");
let buffer = Buffer.alloc(0);
localSocket.on("error", (err) => {
logger.log({ type: 3, msg: `Local UDP socket error: ${err.stack}` });
remoteStream.destroy(err);
});
localSocket.on("message", (msg) => {
logger.log({ type: 0, msg: `Data from local to remote: ${msg.length} bytes` });
const lenBuf = Buffer.alloc(4);
lenBuf.writeUInt32BE(msg.length, 0);
remoteStream.write(Buffer.concat([lenBuf, msg]));
});
remoteStream.on("data", (chunk) => {
logger.log({ type: 0, msg: `Data from remote to local: ${chunk.length} bytes` });
buffer = Buffer.concat([buffer, chunk]);
while (buffer.length >= 4) {
const len = buffer.readUInt32BE(0);
if (buffer.length < 4 + len) break;
const msg = buffer.slice(4, 4 + len);
localSocket.send(msg, 0, msg.length, +localOpts.port, localOpts.host, (err) => {
if (err) logger.log({ type: 3, msg: `Send error to local: ${err.stack}` });
});
buffer = buffer.slice(4 + len);
}
});
remoteStream.on("end", () => localSocket.close());
localSocket.on("close", () => remoteStream.end());
remoteStream.on("error", (err) => localSocket.close());
localSocket.on("error", (err) => remoteStream.destroy(err));
}
module.exports = {
connPiper,
udpPiper,
udpConnect,
createTcpProxy,
pipeTcpServer,
createUdpFramedProxy,
pipeUdpFramedServer
};
}
});
// ../../node_modules/holesail-server/node_modules/hyper-cmd-lib-keys/index.js
var require_hyper_cmd_lib_keys = __commonJS({
"../../node_modules/holesail-server/node_modules/hyper-cmd-lib-keys/index.js"(exports, module) {
var sodium = require_sodium_universal();
function parseKeyPair(k) {
const kp = JSON.parse(k);
return {
secretKey: Buffer.from(kp.secretKey, "hex"),
publicKey: Buffer.from(kp.publicKey, "hex")
};
}
function randomBytes(n) {
const b = Buffer.alloc(n);
sodium.randombytes_buf(b);
return b;
}
function findBuf(arr, buf) {
return arr.findIndex((k) => k.equals(buf)) >= 0;
}
function checkAllowList(allow, k) {
return findBuf(allow, k);
}
function prepKeyList(keys) {
return keys.map((pk) => prepKey(pk));
}
function prepKey(k) {
return Buffer.from(k, "hex");
}
module.exports = {
checkAllowList,
prepKeyList,
prepKey,
randomBytes,
parseKeyPair
};
}
});
// ../../node_modules/holesail-server/index.js
var require_holesail_server = __commonJS({
"../../node_modules/holesail-server/index.js"(exports, module) {
var HyperDHT = require_hyperdht();
var libNet = require_hyper_cmd_lib_net();
var libKeys = require_hyper_cmd_lib_keys();
var b4a = require_b4a();
var z32 = require_z32();
var HolesailServer = class {
constructor(opts = {}) {
this.logger = opts.logger || { log: () => {
} };
this.dht = new HyperDHT();
this.stats = {};
this.server = null;
this.keyPair = null;
this.seed = null;
this.state = null;
this.connection = null;
this.refreshInterval = null;
this.activeConnections = /* @__PURE__ */ new Map();
}
generateKeyPair(seed) {
if (!seed) {
seed = libKeys.randomBytes(32).toString("hex");
}
this.seed = Buffer.from(seed, "hex");
this.keyPair = HyperDHT.keyPair(this.seed);
this.logger.log({ type: 0, msg: `Generated key pair from seed: ${seed}` });
return this.keyPair;
}
// start the client on port and the address specified
async start(args, callback) {
this.logger.log({ type: 1, msg: "Starting server" });
this.args = args;
this.secure = args.secure === true;
this.generateKeyPair(args.seed);
let privateFirewall = false;
if (this.secure) {
privateFirewall = (remotePublicKey) => {
return !b4a.equals(remotePublicKey, this.keyPair.publicKey);
};
this.logger.log({ type: 1, msg: "Using Private Mode" });
} else {
this.logger.log({ type: 1, msg: "Using Public Mode" });
}
this.server = this.dht.createServer(
{
firewall: privateFirewall,
reusableSocket: true
},
(c) => {
const encodedKey = z32.encode(c.remotePublicKey);
this.logger.log({
type: 0,
msg: `Incoming connection received from ${encodedKey}`
});
const count = this.activeConnections.get(encodedKey) || 0;
this.activeConnections.set(encodedKey, count + 1);
if (!args.udp) {
this.handleTCP(c, args);
} else {
this.handleUDP(c, args);
}
}
);
this.logger.log({ type: 0, msg: "Server created, awaiting listen" });
this.server.listen(this.keyPair).then(() => {
this.state = "listening";
this.logger.log({ type: 1, msg: `Server listening on key: ${this.key}` });
if (typeof callback === "function") {
callback();
}
});
const interval = 50 * 60 * 1e3;
const data = JSON.stringify({
host: this.args.host,
udp: this.args.udp,
port: this.args.port
});
this.logger.log({
type: 0,
msg: `Initializing DHT with host info: ${data}`
});
await this.put(data);
this.refreshInterval = setInterval(async () => {
this.logger.log({ type: 0, msg: `Refreshing DHT record: ${data}` });
await this.put(data);
}, interval);
}
// Handle TCP connections
handleTCP(c, args) {
this.logger.log({ type: 0, msg: "Handling TCP connection" });
const encodedKey = z32.encode(c.remotePublicKey);
c.on("close", () => {
let count = this.activeConnections.get(encodedKey) || 1;
count--;
if (count <= 0) {
this.logger.log({ type: 0, msg: `Disconnected from ${encodedKey}` });
this.activeConnections.delete(encodedKey);
} else {
this.activeConnections.set(encodedKey, count);
}
});
this.connection = libNet.pipeTcpServer(
c,
{ port: args.port, host: args.host },
{ isServer: true, compress: false, logger: this.logger },
this.stats
);
this.logger.log({ type: 0, msg: "TCP connection piped" });
}
// Handle UDP connections (updated to use framed reliable tunneling)
handleUDP(c, args) {
this.logger.log({ type: 0, msg: "Handling UDP connection" });
const encodedKey = z32.encode(c.remotePublicKey);
c.on("close", () => {
let count = this.activeConnections.get(encodedKey) || 1;
count--;
if (count <= 0) {
this.logger.log({ type: 0, msg: `Disconnected from ${encodedKey}` });
this.activeConnections.delete(encodedKey);
} else {
this.activeConnections.set(encodedKey, count);
}
});
this.connection = libNet.pipeUdpFramedServer(
c,
{ port: args.port, host: args.host },
this.logger,
this.stats
);
this.logger.log({ type: 0, msg: "UDP connection framed and piped" });
}
// Return the public/connection key
get key() {
if (this.secure) {
return z32.encode(this.seed);
} else {
return z32.encode(this.keyPair.publicKey);
}
}
// resume functionality
async resume() {
this.logger.log({ type: 1, msg: "Resuming server" });
await this.dht.resume();
this.state = "listening";
this.logger.log({ type: 1, msg: "Server resumed" });
}
async pause() {
this.logger.log({ type: 1, msg: "Pausing server" });
await this.dht.suspend();
this.state = "paused";
this.logger.log({ type: 1, msg: "Server paused" });
}
// destroy the dht instance and free up resources
async destroy() {
this.logger.log({ type: 1, msg: "Destroying server" });
if (this.refreshInterval) {
clearInterval(this.refreshInterval);
this.refreshInterval = null;
this.logger.log({ type: 1, msg: "Cleared DHT refresh interval" });
}
if (this.dht) await this.dht.destroy();
this.dht = null;
if (this.server) this.server = null;
if (this.connection) this.connection = null;
this.state = "destroyed";
this.logger.log({ type: 1, msg: "Server destroyed" });
}
// put a mutable record on the dht, can be retrieved by any client using the keypair, max limit is 1KB
async put(data, opts = {}) {
if (data == null) {
throw new Error("data cannot be undefined");
}
this.logger.log({ type: 0, msg: `Putting DHT record: ${data}` });
this.logger.log({
type: 0,
msg: `Incoming data type: ${typeof data}, value: ${data}`
});
data = b4a.isBuffer(data) ? data : Buffer.from(data);
this.logger.log({ type: 0, msg: "Checking for existing DHT record" });
const oldRecord = await this.get({ latest: true });
const putOpts = { ...opts };
if (oldRecord) {
if (oldRecord.value == null) {
this.logger.log({
type: 0,
msg: "oldRecord.value is null or undefined"
});
putOpts.seq = oldRecord.seq + 1;
} else {
const same = b4a.equals(b4a.from(oldRecord.value), data);
putOpts.seq = same ? oldRecord.seq : oldRecord.seq + 1;
this.logger.log({
type: 0,
msg: `Existing record found, putting with seq: ${putOpts.seq} (same: ${same})`
});
}
} else {
this.logger.log({
type: 0,
msg: "No existing DHT record found, creating new"
});
}
const { seq } = await this.dht.mutablePut(this.keyPair, data, putOpts);
this.logger.log({ type: 0, msg: `DHT put completed with seq: ${seq}` });
return seq;
}
// get mutable record from dht
async get(opts = {}) {
const record = await this.dht.mutableGet(this.keyPair.publicKey, opts);
if (record) {
const value = b4a.toString(record.value);
this.logger.log({
type: 0,
msg: `Existing DHT record found: seq=${record.seq}, value=${value}`
});
return { seq: record.seq, value };
}
return null;
}
// return information about the server
get info() {
return {
type: "server",
state: this.state,
secure: this.secure,
port: this.args.port,
host: this.args.host,
protocol: this.args.udp ? "udp" : "tcp",
seed: this.args.seed,
key: this.key,
publicKey: z32.encode(this.keyPair.publicKey)
};
}
};
module.exports = HolesailServer;
}
});
// ../../node_modules/holesail-client/index.js
var require_holesail_client = __commonJS({
"../../node_modules/holesail-client/index.js"(exports, module) {
var HyperDHT = require_hyperdht();
var libNet = require_hyper_cmd_lib_net();
var b4a = require_b4a();
var z32 = require_z32();
var HolesailClient = class {
constructor(opts = {}) {
this.logger = opts.logger || { log: () => {
} };
this.seed = opts.key;
this.secure = opts.secure || false;
if (this.secure) {
this.keyPair = HyperDHT.keyPair(z32.decode(this.seed));
this.publicKey = this.keyPair.publicKey;
} else {
this.publicKey = z32.decode(this.seed);
}
this.dht = new HyperDHT({ keyPair: this.keyPair });
this.stats = {};
}
async connect(options = {}, callback) {
this.logger.log({ type: 1, msg: `Connecting to key: ${this.seed}, secure: ${this.secure}` });
let dhtData = {};
const dhtValue = await this.get();
if (dhtValue) {
dhtData = JSON.parse(dhtValue.value);
this.logger.log({ type: 0, msg: `Retrieved DHT data: ${JSON.stringify(dhtData)}` });
} else {
this.logger.log({ type: 2, msg: "No DHT data retrieved" });
}
options.port = options.port ?? dhtData.port ?? 8989;
options.host = options.host ?? dhtData.host ?? "127.0.0.1";
options.udp = options.udp ?? dhtData.udp ?? false;
this.args = options;
this.state = "waiting";
if (!options.udp) {
this.handleTCP(options, callback);
} else {
this.handleUDP(options, callback);
}
}
// end connect
// Handle TCP connections (unchanged, supports multiple naturally)
handleTCP(options, callback) {
this.logger.log({ type: 0, msg: "Handling TCP connection" });
this.proxy = libNet.createTcpProxy(
{ port: options.port, host: options.host },
() => this.dht.connect(this.publicKey, { reusableSocket: true }),
{ compress: false, logger: this.logger },
this.stats,
() => {
this.state = "listening";
this.logger.log({ type: 1, msg: `Proxy listening on ${options.host}:${options.port}` });
callback?.();
}
);
}
// Handle UDP connections (updated for framed reliable tunneling with multi-client support)
handleUDP(options, callback) {
this.logger.log({ type: 0, msg: "Handling UDP connection" });
const { proxySocket, clients } = libNet.createUdpFramedProxy(
{ port: options.port, host: options.host },
() => this.dht.connect(this.publicKey),
this.logger,
() => {
this.state = "listening";
this.logger.log({
type: 1,
msg: `Proxy listening on ${options.host}:${options.port} for UDP`
});
callback?.();
}
);
this.proxy = proxySocket;
this.clients = clients;
}
// resume functionality
async resume() {
this.logger.log({ type: 1, msg: "Resuming client" });
await this.dht.resume();
this.state = "listening";
this.logger.log({ type: 1, msg: "Client resumed" });
}
async pause() {
this.logger.log({ type: 1, msg: "Pausing client" });
await this.dht.suspend();
this.state = "paused";
this.logger.log({ type: 1, msg: "Client paused" });
}
async destroy() {
this.logger.log({ type: 1, msg: "Destroying client" });
await this.dht.destroy();
if (this.proxy) this.proxy.close();
if (this.clients) {
for (const client of this.clients.values()) {
client.remoteStream.destroy();
}
this.clients.clear();
}
this.proxy = null;
this.clients = null;
this.state = "destroyed";
this.logger.log({ type: 1, msg: "Client destroyed" });
}
// get mutable record stored on the dht
async get(opts = {}) {
this.logger.log({ type: 0, msg: "Getting DHT record" });
const record = await this.dht.mutableGet(this.publicKey, opts);
if (record) {
const value = b4a.toString(record.value);
this.logger.log({ type: 0, msg: `DHT get completed: seq=${record.seq}, value=${value}` });
return { seq: record.seq, value };
}
this.logger.log({ type: 2, msg: "DHT get: no record found" });
return null;
}
get info() {
return {
type: "client",
state: this.state,
secure: this.secure,
port: this.args.port,
host: this.args.host,
protocol: this.args.udp ? "udp" : "tcp",
key: this.seed,
publicKey: z32.encode(this.publicKey)
};
}
static async ping(key, dht = null) {
let ownDht = false;
if (!dht) {
dht = new HyperDHT();
ownDht = true;
}
let result = null;
const keyBuffer = z32.decode(key);
let publicKey = HyperDHT.keyPair(keyBuffer).publicKey;
let record = await dht.mutableGet(publicKey, { latest: true });
if (record) {
const value = b4a.toString(record.value);
try {
result = JSON.parse(value);
result.protocol = result.udp ? "udp" : "tcp";
} catch {
}
}
if (!result) {
publicKey = keyBuffer;
record = await dht.mutableGet(publicKey, { latest: true });
if (record) {
const value = b4a.toString(record.value);
try {
result = JSON.parse(value);
result.protocol = result.udp ? "udp" : "tcp";
} catch {
}
}
}
if (ownDht) {
await dht.destroy();
}
return result;
}
};
module.exports = HolesailClient;
}
});
// ../../node_modules/hyper-cmd-lib-keys/node_modules/sodium-native/index.js
var require_sodium_native2 = __commonJS({
"../../node_modules/hyper-cmd-lib-keys/node_modules/sodium-native/index.js"(exports, module) {
__require.addon = require_node();
module.exports = __require.addon(".", __filename);
}
});
// ../../node_modules/hyper-cmd-lib-keys/node_modules/sodium-universal/index.js
var require_sodium_universal2 = __commonJS({
"../../node_modules/hyper-cmd-lib-keys/node_modules/sodium-universal/index.js"(exports, module) {
module.exports = require_sodium_native2();
}
});
// ../../node_modules/hyper-cmd-lib-keys/index.js
var require_hyper_cmd_lib_keys2 = __commonJS({
"../../node_modules/hyper-cmd-lib-keys/index.js"(exports, module) {
var sodium = require_sodium_universal2();
function parseKeyPair(k) {
const kp = JSON.parse(k);
return {
secretKey: Buffer.from(kp.secretKey, "hex"),
publicKey: Buffer.from(kp.publicKey, "hex")
};
}
function randomBytes(n) {
const b = Buffer.alloc(n);
sodium.randombytes_buf(b);
return b;
}
function findBuf(arr, buf) {
return arr.findIndex((k) => k.equals(buf)) >= 0;
}
function checkAllowList(allow, k) {
return findBuf(allow, k);
}
function prepKeyList(keys) {
return keys.map((pk) => prepKey(pk));
}
function prepKey(k) {
return Buffer.from(k, "hex");
}
module.exports = {
checkAllowList,
prepKeyList,
prepKey,
randomBytes,
parseKeyPair
};
}
});
// ../../node_modules/barely-colours/index.js
var require_barely_colours = __commonJS({
"../../node_modules/barely-colours/index.js"(exports, module) {
var KeyDecoder = require_bare_ansi_escapes();
var reset = KeyDecoder.modifierReset;
var BarelyColours = class {
red(d) {
return KeyDecoder.colorRed + d + reset;
}
black(d) {
return KeyDecoder.colorBlack + d + reset;
}
green(d) {
return KeyDecoder.colorGreen + d + reset;
}
yellow(d) {
return KeyDecoder.colorYellow + d + reset;
}
blue(d) {
return KeyDecoder.colorBlue + d + reset;
}
magenta(d) {
return KeyDecoder.colorMagenta + d + reset;
}
cyan(d) {
return KeyDecoder.colorCyan + d + reset;
}
white(d) {
return KeyDecoder.colorWhite + d + reset;
}
brightBlack(d) {
return KeyDecoder.colorBrightBlack + d + reset;
}
brightRed(d) {
return KeyDecoder.colorBrightRed + d + reset;
}
brightGreen(d) {
return KeyDecoder.colorBrightGreen + d + reset;
}
brightYellow(d) {
return KeyDecoder.colorBrightYellow + d + reset;
}
brightBlue(d) {
return KeyDecoder.colorBrightBlue + d + reset;
}
brightMagenta(d) {
return KeyDecoder.colorBrightMagenta + d + reset;
}
brightCyan(d) {
return KeyDecoder.colorBrightCyan + d + reset;
}
brightWhite(d) {
return KeyDecoder.colorBrightWhite + d + reset;
}
bold(d) {
return KeyDecoder.modifierBold + d + reset;
}
dim(d) {
return KeyDecoder.modifierDim + d + reset;
}
italic(d) {
return KeyDecoder.modifierItalic + d + reset;
}
underline(d) {
return KeyDecoder.modifierUnderline + d + reset;
}
normal(d) {
return KeyDecoder.modifierNormal + d + reset;
}
notItalic(d) {
return KeyDecoder.modifierNotItalic + d + reset;
}
notUnderline(d) {
return KeyDecoder.modifierNotUnderline + d + reset;
}
};
var colours = new BarelyColours();
module.exports = colours;
}
});
// ../../node_modules/holesail/src/lib/validateInput.js
var require_validateInput = __commonJS({
"../../node_modules/holesail/src/lib/validateInput.js"(exports, module) {
var colors = require_barely_colours();
function validateInput(args) {
if (args.key && typeof args.key === "boolean") {
console.log(colors.red("Error: Key can not be empty"));
process.exit();
}
if (args.udp && (args.host === "localhost" || args.host === "0.0.0.0")) {
console.log(
colors.yellow("Warning: localhost or 0.0.0.0 may not work properly within netcat with UDP.")
);
}
if (args.key && args.key.length < 32 && !args.force) {
console.log(
colors.red(
"Error: A key should have a minimum length of 32 chars for security purposes. If you still wish to proceed use --force"
)
);
process.exit(2);
}
if (args.connect && args._[0]) {
console.log(
colors.red(
"Error: Are you trying to use two connection strings at once? Get some holesail --help"
)
);
process.exit(2);
}
if (args.live && typeof args.live !== "number") {
console.log(
colors.red("Error: Given port is not a valid number. Run holesail --help to see examples")
);
process.exit(2);
}
if (args.port) {
if (typeof args.port !== "number") {
console.log(
colors.red("Error: Given port is not a valid number. Run holesail --help to see examples")
);
process.exit(2);
}
} else if (args.port === "") {
console.log(
colors.red("Error: Given port is not a valid number. Run holesail --help to see examples")
);
process.exit(2);
}
if (args.filemanager && args.udp) {
console.log(colors.red("Error: You can't run filemanager in UDP mode."));
process.exit(2);
}
if (args.live && args.filemanager) {
console.log(
colors.red(
"Error: You can't start holesail server and filemanager at the same time. If you are trying to use filemanager on a specific local port use --port instead or see holesail --help"
)
);
process.exit(2);
}
if (args.filemanager && (args.connect || args._[0])) {
console.log(
colors.red(
"Error: You tried to create a connection and start filemanager both at once. Start them separately and check your command for mistakes. See holesail --help"
)
);
process.exit(2);
}
if (args.filemanager && typeof args.filemanager !== "boolean") {
const fs = require_bare_node_fs();
if (!fs.existsSync(args.filemanager)) {
console.log(colors.red("Error: Given path does not exist"));
process.exit(2);
}
}
if (args.role && args.role !== "admin" && args.role !== "user") {
console.log(colors.red('Error: Incorrect role set. Role can be either "admin" or "user" '));
process.exit(2);
}
}
function validateOpts(opts) {
if (opts.client && !opts.key || opts.key === "") {
throw new Error("Key is empty");
}
if (opts.protocol !== void 0 && opts.protocol !== "udp" && opts.protocol !== "tcp") {
throw new Error("Incorrect protocol set");
}
if (opts.server && opts.client) {
throw new Error("Can not set both server and client at once");
}
if (opts.server && opts.seed === "") {
throw new Error("Seed is empty");
}
if (opts.server && !opts.host) {
throw new Error("No host specified");
}
}
module.exports = {
validateInput,
validateOpts
};
}
});
// ../../node_modules/bare-crypto/binding.js
var require_binding11 = __commonJS({
"../../node_modules/bare-crypto/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-crypto/lib/errors.js
var require_errors13 = __commonJS({
"../../node_modules/bare-crypto/lib/errors.js"(exports, module) {
module.exports = class CryptoError extends Error {
constructor(msg, fn = CryptoError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "CryptoError";
}
static UNKNOWN_HASH(msg) {
return new CryptoError(msg, CryptoError.UNKNOWN_HASH);
}
static UNKNOWN_CIPHER(msg) {
return new CryptoError(msg, CryptoError.UNKNOWN_CIPHER);
}
static UNKNOWN_KEY_TYPE(msg) {
return new CryptoError(msg, CryptoError.UNKNOWN_KEY_TYPE);
}
static INVALID_ACCESS(msg) {
return new CryptoError(msg, CryptoError.INVALID_ACCESS);
}
static INVALID_DATA(msg) {
return new CryptoError(msg, CryptoError.INVALID_DATA);
}
static OPERATION_ERROR(msg) {
return new CryptoError(msg, CryptoError.OPERATION_ERROR);
}
static NOT_SUPPORTED(msg) {
return new CryptoError(msg, CryptoError.NOT_SUPPORTED);
}
};
}
});
// ../../node_modules/bare-crypto/lib/constants.js
var require_constants9 = __commonJS({
"../../node_modules/bare-crypto/lib/constants.js"(exports, module) {
var { fail } = require_bare_assert();
var binding = require_binding11();
var errors = require_errors13();
module.exports = exports = {
hash: {
MD5: binding.MD5,
SHA1: binding.SHA1,
SHA256: binding.SHA256,
SHA384: binding.SHA384,
SHA512: binding.SHA512,
BLAKE2B256: binding.BLAKE2B256,
RIPEMD160: binding.RIPEMD160
},
signature: {
ED25519: binding.ED25519
},
cipher: {
AES128ECB: binding.AES128ECB,
AES128CBC: binding.AES128CBC,
AES128CTR: binding.AES128CTR,
AES128OFB: binding.AES128OFB,
AES256ECB: binding.AES256ECB,
AES256CBC: binding.AES256CBC,
AES256CTR: binding.AES256CTR,
AES256OFB: binding.AES256OFB,
AES128GCM: binding.AES128GCM,
AES256GCM: binding.AES256GCM,
CHACHA20POLY1305: binding.CHACHA20POLY1305,
XCHACHA20POLY1305: binding.XCHACHA20POLY1305
},
keyType: {
ED25519: binding.ED25519
}
};
exports.toHash = function toHash(hash) {
if (typeof hash === "number" && !isNaN(hash)) return hash;
if (typeof hash === "string") {
hash = hash.replace(/-/g, "");
if (hash in exports.hash === false) {
hash = hash.toUpperCase();
if (hash in exports.hash === false) {
throw errors.UNKNOWN_HASH(`Unknown hash '${hash}'`);
}
}
return exports.hash[hash];
}
fail(`Hash must be a number or string. Received ${isNaN(hash) ? "NaN" : typeof hash} (${hash})`);
};
exports.toCipher = function toCiper(cipher) {
if (typeof cipher === "number" && !isNaN(cipher)) return cipher;
if (typeof cipher === "string") {
cipher = cipher.replace(/-/g, "");
if (cipher in exports.cipher === false) {
cipher = cipher.toUpperCase();
if (cipher in exports.cipher === false) {
throw errors.UNKNOWN_CIPHER(`Unknown cipher '${cipher}'`);
}
}
return exports.cipher[cipher];
}
fail(
`Cipher must be a number or string. Received ${isNaN(cipher) ? "NaN" : typeof cipher} (${cipher})`
);
};
exports.toKeyType = function toKeyType(type) {
if (typeof type === "number" && !isNaN(type)) return type;
if (typeof type === "string") {
type = type.replace(/-/g, "");
if (type in exports.keyType === false) {
type = type.toUpperCase();
if (type in exports.keyType === false) {
throw errors.UNKNOWN_KEY_TYPE(`Unknown key type '${type}'`);
}
}
return exports.keyType[type];
}
fail(
`Key type must be a number or string. Received ${isNaN(type) ? "NaN" : typeof type} (${type})`
);
};
}
});
// ../../node_modules/bare-crypto/lib/hash.js
var require_hash = __commonJS({
"../../node_modules/bare-crypto/lib/hash.js"(exports, module) {
var { Transform } = require_bare_stream();
var assert = require_bare_assert();
var binding = require_binding11();
var constants = require_constants9();
var {
hash: { RIPEMD160 }
} = constants;
var CryptoDigest = class {
constructor(algorithm) {
this._handle = binding.digestInit(algorithm);
}
update(data) {
if (this._handle === null) {
throw new Error("Digest has already been finalized");
}
binding.digestUpdate(this._handle, data.buffer, data.byteOffset, data.byteLength);
}
final() {
if (this._handle === null) {
throw new Error("Digest has already been finalized");
}
const result = Buffer.from(binding.digestFinal(this._handle));
this._handle = null;
return result;
}
};
var CryptoRIPEMD160Digest = class {
constructor() {
this._handle = binding.ripemd160Init();
}
update(data) {
if (this._handle === null) {
throw new Error("Digest has already been finalized");
}
binding.ripemd160Update(this._handle, data.buffer, data.byteOffset, data.byteLength);
}
final() {
if (this._handle === null) {
throw new Error("Digest has already been finalized");
}
const result = Buffer.from(binding.ripemd160Final(this._handle));
this._handle = null;
return result;
}
};
module.exports = class CryptoHash extends Transform {
constructor(algorithm, opts = {}) {
super(opts);
algorithm = constants.toHash(algorithm);
switch (algorithm) {
case RIPEMD160:
this._digest = new CryptoRIPEMD160Digest();
break;
default:
this._digest = new CryptoDigest(algorithm);
break;
}
}
update(data, encoding = "utf8") {
if (typeof data === "string") data = Buffer.from(data, encoding);
assert(ArrayBuffer.isView(data));
this._digest.update(data);
return this;
}
digest(encoding) {
const digest = this._digest.final();
return encoding && encoding !== "buffer" ? digest.toString(encoding) : digest;
}
_transform(data, encoding, cb) {
this.update(data);
cb(null);
}
_flush(cb) {
this.push(this.digest());
cb(null);
}
};
}
});
// ../../node_modules/bare-crypto/lib/hmac.js
var require_hmac2 = __commonJS({
"../../node_modules/bare-crypto/lib/hmac.js"(exports, module) {
var { Transform } = require_bare_stream();
var assert = require_bare_assert();
var binding = require_binding11();
var constants = require_constants9();
module.exports = class CryptoHmac extends Transform {
constructor(algorithm, key, opts = {}) {
super(opts);
const { encoding = "utf8" } = opts;
if (typeof key === "string") key = Buffer.from(key, encoding);
assert(ArrayBuffer.isView(key));
this._handle = binding.hmacInit(
constants.toHash(algorithm),
key.buffer,
key.byteOffset,
key.byteLength
);
}
update(data, encoding = "utf8") {
if (this._handle === null) {
throw new Error("Hmac has already been finalized");
}
if (typeof data === "string") data = Buffer.from(data, encoding);
assert(ArrayBuffer.isView(data));
binding.hmacUpdate(this._handle, data.buffer, data.byteOffset, data.byteLength);
return this;
}
digest(encoding) {
if (this._handle === null) {
throw new Error("Hmac has already been finalized");
}
const digest = Buffer.from(binding.hmacFinal(this._handle));
this._handle = null;
return encoding && encoding !== "buffer" ? digest.toString(encoding) : digest;
}
_transform(data, encoding, cb) {
this.update(data);
cb(null);
}
_flush(cb) {
this.push(this.digest());
cb(null);
}
};
}
});
// ../../node_modules/bare-crypto/lib/cipher.js
var require_cipher2 = __commonJS({
"../../node_modules/bare-crypto/lib/cipher.js"(exports) {
var { Transform } = require_bare_stream();
var assert = require_bare_assert();
var binding = require_binding11();
var constants = require_constants9();
var {
cipher: {
AES128ECB,
AES128CBC,
AES128CTR,
AES128OFB,
AES256ECB,
AES256CBC,
AES256CTR,
AES256OFB,
AES128GCM,
AES256GCM,
CHACHA20POLY1305,
XCHACHA20POLY1305
}
} = constants;
var CryptoCipher = class {
constructor(algorithm, key, iv, encrypt, opts = {}) {
const { encoding = "utf8" } = opts;
if (typeof key === "string") key = Buffer.from(key, encoding);
if (typeof iv === "string") iv = Buffer.from(iv, encoding);
assert(ArrayBuffer.isView(key));
assert(ArrayBuffer.isView(iv));
if (key.byteLength !== binding.cipherKeyLength(algorithm)) {
throw new RangeError("Invalid key length");
}
if (iv.byteLength < binding.cipherIVLength(algorithm)) {
throw new RangeError("Invalid iv length");
}
this._handle = binding.cipherInit(
algorithm,
key.buffer,
key.byteOffset,
key.byteLength,
iv.buffer,
iv.byteOffset,
iv.byteLength,
encrypt
);
}
update(data, inputEncoding = "utf8", outputEncoding) {
if (this._handle === null) {
throw new Error("Cipher has already been finalized");
}
if (typeof data === "string") data = Buffer.from(data, inputEncoding);
assert(ArrayBuffer.isView(data));
const out = new ArrayBuffer(data.byteLength + binding.cipherBlockSize(this._handle));
const written = binding.cipherUpdate(
this._handle,
data.buffer,
data.byteOffset,
data.byteLength,
out
);
const result = Buffer.from(out, 0, written);
return outputEncoding ? result.toString(outputEncoding) : result;
}
final(outputEncoding) {
if (this._handle === null) {
throw new Error("Cipher has already been finalized");
}
const out = new ArrayBuffer(binding.cipherBlockSize(this._handle));
const written = binding.cipherFinal(this._handle, out);
this._handle = null;
const result = Buffer.from(out, 0, written);
return outputEncoding ? result.toString(outputEncoding) : result;
}
setAutoPadding(pad) {
if (this._handle === null) {
throw new Error("Cipher has already been finalized");
}
binding.cipherSetPadding(this._handle, pad);
}
};
var CryptoAuthenticatedCipher = class {
constructor(algorithm, key, nonce, opts = {}) {
const { encoding = "utf8", authTagLength = 16 } = opts;
if (typeof key === "string") key = Buffer.from(key, encoding);
if (typeof nonce === "string") nonce = Buffer.from(nonce, encoding);
assert(ArrayBuffer.isView(key));
assert(ArrayBuffer.isView(nonce));
if (key.byteLength !== binding.aeadKeyLength(algorithm)) {
throw new RangeError("Invalid key length");
}
if (nonce.byteLength < binding.aeadNonceLength(algorithm)) {
throw new RangeError("Invalid nonce length");
}
this._buffer = [];
this._nonce = nonce;
this._authTag = null;
this._authTagLength = authTagLength;
this._additionalData = null;
this._handle = binding.aeadInit(
algorithm,
key.buffer,
key.byteOffset,
key.byteLength,
authTagLength
);
}
update(data, inputEncoding = "utf8", outputEncoding) {
if (typeof data === "string") data = Buffer.from(data, inputEncoding);
assert(ArrayBuffer.isView(data));
this._buffer.push(data);
return outputEncoding ? "" : Buffer.alloc(0);
}
setAAD(buffer, opts = {}) {
const { encoding = "utf8" } = opts;
if (typeof buffer === "string") buffer = Buffer.from(buffer, encoding);
assert(ArrayBuffer.isView(buffer));
this._additionalData = buffer;
}
getAuthTag() {
return this._authTag;
}
setAuthTag(authTag, encoding) {
if (typeof authTag === "string") authTag = Buffer.from(authTag, encoding);
assert(ArrayBuffer.isView(authTag));
this._authTag = authTag;
}
};
var CryptoAuthenticatedSeal = class extends CryptoAuthenticatedCipher {
final(outputEncoding) {
if (this._handle === null) {
throw new Error("Cipher has already been finalized");
}
const data = this._buffer.length === 1 ? this._buffer[0] : Buffer.concat(this._buffer);
const nonce = this._nonce;
const ad = this._additionalData || Buffer.alloc(0);
const out = new ArrayBuffer(data.byteLength + binding.aeadMaxOverhead(this._handle));
const written = binding.aeadSeal(
this._handle,
data.buffer,
data.byteOffset,
data.byteLength,
nonce.buffer,
nonce.byteOffset,
nonce.byteLength,
ad.buffer,
ad.byteOffset,
ad.byteLength,
out
);
this._handle = null;
const cipherLength = written - this._authTagLength;
this._authTag = Buffer.from(out, cipherLength);
const result = Buffer.from(out, 0, cipherLength);
return outputEncoding ? result.toString(outputEncoding) : result;
}
};
var CryptoAuthenticatedOpen = class extends CryptoAuthenticatedCipher {
final(outputEncoding) {
if (this._handle === null) {
throw new Error("Decipher has already been finalized");
}
this._buffer.push(this._authTag);
const data = Buffer.concat(this._buffer);
const nonce = this._nonce;
const ad = this._additionalData || Buffer.alloc(0);
const out = new ArrayBuffer(data.byteLength);
const written = binding.aeadOpen(
this._handle,
data.buffer,
data.byteOffset,
data.byteLength,
nonce.buffer,
nonce.byteOffset,
nonce.byteLength,
ad.buffer,
ad.byteOffset,
ad.byteLength,
out
);
this._handle = null;
const result = Buffer.from(out, 0, written);
return outputEncoding ? result.toString(outputEncoding) : result;
}
};
exports.Cipheriv = class CryptoCipheriv extends Transform {
constructor(algorithm, key, iv, opts = {}) {
super(opts);
algorithm = constants.toCipher(algorithm);
switch (algorithm) {
case AES128ECB:
case AES128CBC:
case AES128CTR:
case AES128OFB:
case AES256ECB:
case AES256CBC:
case AES256CTR:
case AES256OFB:
this._cipher = new CryptoCipher(algorithm, key, iv, true, opts);
break;
case AES128GCM:
case AES256GCM:
case CHACHA20POLY1305:
case XCHACHA20POLY1305:
this._cipher = new CryptoAuthenticatedSeal(algorithm, key, iv, opts);
break;
}
}
update(data, inputEncoding, outputEncoding) {
return this._cipher.update(data, inputEncoding, outputEncoding);
}
final(outputEncoding) {
return this._cipher.final(outputEncoding);
}
setAutoPadding(pad) {
this._cipher.setAutoPadding(pad);
return this;
}
setAAD(buffer, opts) {
this._cipher.setAAD(buffer, opts);
return this;
}
getAuthTag() {
return this._cipher.getAuthTag();
}
_transform(data, encoding, cb) {
this.push(this.update(data));
cb(null);
}
_flush(cb) {
this.push(this.final());
cb(null);
}
};
exports.Decipheriv = class CryptoDeipheriv extends Transform {
constructor(algorithm, key, iv, opts = {}) {
super(opts);
algorithm = constants.toCipher(algorithm);
switch (algorithm) {
case AES128ECB:
case AES128CBC:
case AES128CTR:
case AES128OFB:
case AES256ECB:
case AES256CBC:
case AES256CTR:
case AES256OFB:
this._cipher = new CryptoCipher(algorithm, key, iv, false, opts);
break;
case AES128GCM:
case AES256GCM:
case CHACHA20POLY1305:
case XCHACHA20POLY1305:
this._cipher = new CryptoAuthenticatedOpen(algorithm, key, iv, opts);
break;
}
}
update(data, inputEncoding, outputEncoding) {
return this._cipher.update(data, inputEncoding, outputEncoding);
}
final(outputEncoding) {
return this._cipher.final(outputEncoding);
}
setAutoPadding(pad) {
this._cipher.setAutoPadding(pad);
return this;
}
setAAD(buffer, opts) {
this._cipher.setAAD(buffer, opts);
return this;
}
setAuthTag(authTag, encoding) {
this._cipher.setAuthTag(authTag, encoding);
return this;
}
_transform(data, encoding, cb) {
this.push(this.update(data));
cb(null);
}
_flush(cb) {
this.push(this.final());
cb(null);
}
};
}
});
// ../../node_modules/bare-crypto/lib/random.js
var require_random = __commonJS({
"../../node_modules/bare-crypto/lib/random.js"(exports) {
var assert = require_bare_assert();
var binding = require_binding11();
exports.randomBytes = function randomBytes(size, cb) {
assert(typeof size === "number" && !isNaN(size));
const buffer = Buffer.allocUnsafe(size);
exports.randomFill(buffer);
if (cb) queueMicrotask(() => cb(null, buffer));
else return buffer;
};
exports.randomFill = function randomFill(buffer, offset, size, cb) {
if (typeof offset === "function") {
cb = offset;
offset = void 0;
} else if (typeof size === "function") {
cb = size;
size = void 0;
}
assert(buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer));
assert(size === void 0 || typeof size === "number" && !isNaN(size));
assert(offset === void 0 || typeof offset === "number" && !isNaN(offset));
const elementSize = buffer.BYTES_PER_ELEMENT || 1;
if (offset === void 0) offset = 0;
else offset *= elementSize;
if (size === void 0) size = buffer.byteLength - offset;
else size *= elementSize;
if (offset < 0 || offset > buffer.byteLength) {
throw new RangeError("offset is out of range");
}
if (size < 0 || size > buffer.byteLength) {
throw new RangeError("size is out of range");
}
if (offset + size > buffer.byteLength) {
throw new RangeError("offset + size is out of range");
}
let arraybuffer;
if (ArrayBuffer.isView(buffer)) {
offset += buffer.byteOffset;
arraybuffer = buffer.buffer;
} else {
arraybuffer = buffer;
}
binding.randomFill(arraybuffer, offset, size);
if (cb) queueMicrotask(() => cb(null, buffer));
else return buffer;
};
exports.randomUUID = function randomUUID() {
const uuid = exports.randomBytes(16);
uuid[6] = uuid[6] >>> 4 | 64;
uuid[8] = uuid[8] >>> 2 | 128;
return uuid.subarray(0, 4).toString("hex") + "-" + uuid.subarray(4, 6).toString("hex") + "-" + uuid.subarray(6, 8).toString("hex") + "-" + uuid.subarray(8, 10).toString("hex") + "-" + uuid.subarray(10, 16).toString("hex");
};
}
});
// ../../node_modules/bare-crypto/lib/pbkdf2.js
var require_pbkdf2 = __commonJS({
"../../node_modules/bare-crypto/lib/pbkdf2.js"(exports, module) {
var assert = require_bare_assert();
var binding = require_binding11();
var constants = require_constants9();
module.exports = function pbkdf2(password, salt, iterations, keylen, digest, cb) {
if (iterations <= 0) {
throw new RangeError("iterations is out of range");
}
assert(typeof iterations === "number" && !isNaN(iterations));
assert(typeof keylen === "number" && !isNaN(keylen));
if (typeof password === "string") password = Buffer.from(password);
if (typeof salt === "string") salt = Buffer.from(salt);
assert(ArrayBuffer.isView(password));
assert(ArrayBuffer.isView(salt));
const buffer = Buffer.from(
binding.pbkdf2(
password.buffer,
password.byteOffset,
password.byteLength,
salt.buffer,
salt.byteOffset,
salt.byteLength,
iterations,
constants.toHash(digest),
keylen
)
);
if (cb) queueMicrotask(() => cb(null, buffer));
else return buffer;
};
}
});
// ../../node_modules/bare-crypto/lib/key.js
var require_key = __commonJS({
"../../node_modules/bare-crypto/lib/key.js"(exports) {
var binding = require_binding11();
var constants = require_constants9();
var {
keyType: { ED25519 }
} = constants;
var CryptoKey = class {
constructor(keyType) {
this._keyType = keyType;
}
};
exports.Key = CryptoKey;
var CryptoEd25519Key = class extends CryptoKey {
constructor(key) {
super(ED25519);
this._key = key;
}
get asymmetricKeyType() {
return "ed25519";
}
};
var CryptoEd25519PublicKey = class extends CryptoEd25519Key {
get type() {
return "public";
}
};
exports.Ed25519PublicKey = CryptoEd25519PublicKey;
var CryptoEd25519PrivateKey = class extends CryptoEd25519Key {
get type() {
return "private";
}
};
exports.Ed25519PrivateKey = CryptoEd25519PrivateKey;
exports.generateKeyPair = function generateKeyPair(type, opts = {}) {
type = constants.toKeyType(type);
switch (type) {
case ED25519: {
const { publicKey, privateKey } = binding.ed25519GenerateKeypair();
return {
publicKey: new CryptoEd25519PublicKey(publicKey),
privateKey: new CryptoEd25519PrivateKey(privateKey)
};
}
}
};
}
});
// ../../node_modules/bare-crypto/lib/signature.js
var require_signature = __commonJS({
"../../node_modules/bare-crypto/lib/signature.js"(exports) {
var assert = require_bare_assert();
var binding = require_binding11();
var { Key } = require_key();
var constants = require_constants9();
var {
keyType: { ED25519 }
} = constants;
exports.sign = function sign(algorithm, data, key) {
assert(data instanceof ArrayBuffer || ArrayBuffer.isView(data));
if (ArrayBuffer.isView(data)) {
data = Buffer.coerce(data);
} else {
data = Buffer.from(data);
}
assert(key instanceof Key);
switch (key._keyType) {
case ED25519:
return Buffer.from(
binding.ed25519Sign(data.buffer, data.byteOffset, data.byteLength, key._key)
);
}
};
exports.verify = function verify(algorithm, data, key, signature) {
assert(data instanceof ArrayBuffer || ArrayBuffer.isView(data));
if (ArrayBuffer.isView(data)) {
data = Buffer.coerce(data);
} else {
data = Buffer.from(data);
}
assert(signature instanceof ArrayBuffer || ArrayBuffer.isView(signature));
if (ArrayBuffer.isView(signature)) {
signature = Buffer.coerce(signature);
} else {
signature = Buffer.from(signature);
}
assert(key instanceof Key);
switch (key._keyType) {
case ED25519:
assert(signature.byteLength === 64);
return binding.ed25519Verify(
data.buffer,
data.byteOffset,
data.byteLength,
signature.buffer,
signature.byteOffset,
key._key
);
}
};
}
});
// ../../node_modules/bare-crypto/lib/web/crypto-key.js
var require_crypto_key = __commonJS({
"../../node_modules/bare-crypto/lib/web/crypto-key.js"(exports, module) {
module.exports = class CryptoKey {
constructor(type, extractable, algorithm, usages, handle = null) {
this._type = type;
this._extractable = extractable;
this._algorithm = algorithm;
this._usages = usages;
this._handle = handle;
}
// https://w3c.github.io/webcrypto/#dom-cryptokey-type
get type() {
return this._type;
}
// https://w3c.github.io/webcrypto/#dom-cryptokey-extractable
get extractable() {
return this._extractable;
}
// https://w3c.github.io/webcrypto/#dom-cryptokey-algorithm
get algorithm() {
return this._algorithm;
}
// https://w3c.github.io/webcrypto/#dom-cryptokey-usages
get usages() {
return this._usages;
}
[Symbol.for("bare.inspect")]() {
return {
__proto__: { constructor: CryptoKey },
type: this.type,
extractable: this.extractable,
algorithm: this.algorithm,
usages: this.usages
};
}
};
}
});
// ../../node_modules/bare-crypto/lib/web/algorithm/hmac.js
var require_hmac3 = __commonJS({
"../../node_modules/bare-crypto/lib/web/algorithm/hmac.js"(exports) {
var crypto = require_bare_crypto();
var errors = require_errors13();
var CryptoKey = require_crypto_key();
exports.sign = function sign(algorithm, key, data) {
const digest = crypto.createHmac(key.algorithm.hash.name, key._handle).update(data).digest();
return digest.buffer.slice(0, digest.byteLength);
};
exports.verify = function verify(algorithm, key, signature, data) {
const digest = crypto.createHmac(key.algorithm.hash.name, key._handle).update(data).digest();
if (ArrayBuffer.isView(signature)) {
signature = Buffer.coerce(signature);
} else {
signature = Buffer.from(signature);
}
return signature.equals(digest);
};
exports.generateKey = function generateKey(algorithm, extractable, usages) {
for (const usage of usages) {
if (usage !== "sign" && usage !== "verify") {
throw new SyntaxError(`Usage '${usage}' cannot be used for the HMAC generateKey() operation`);
}
}
const { length = exports.getKeyLength(algorithm) } = algorithm.length;
let hash = algorithm.hash;
if (typeof hash === "string") hash = { name: hash };
const key = crypto.createHmac(hash.name, crypto.randomBytes(length)).digest();
return new CryptoKey(
"secret",
extractable,
{
name: "HMAC",
length,
hash: {
name: hash.name.toUpperCase()
}
},
usages,
key
);
};
exports.importKey = function importKey(format, keyData, algorithm, extractable, usages) {
for (const usage of usages) {
if (usage !== "sign" && usage !== "verify") {
throw new SyntaxError(`Invalid usage ${usage}`);
}
}
let hash = algorithm.hash;
if (typeof hash === "string") hash = { name: hash };
let data;
switch (format) {
case "raw":
data = keyData;
break;
case "jwk":
const jwk = keyData;
if (jwk.kty !== "oct") {
throw errors.INVALID_DATA("JWK key must be an octet sequence");
}
data = Buffer.from(jwk.k, "base64url");
switch (hash.name.toLowerCase()) {
case "sha-1":
if (jwk.alg === "HS1") break;
else throw errors.INVALID_DATA("Invalid JWK key algorithm");
case "sha-256":
if (jwk.alg === "HS256") break;
else throw errors.INVALID_DATA("Invalid JWK key algorithm");
case "sha-384":
if (jwk.alg === "HS384") break;
else throw errors.INVALID_DATA("Invalid JWK key algorithm");
case "sha-512":
if (jwk.alg === "HS512") break;
else throw errors.INVALID_DATA("Invalid JWK key algorithm");
}
if (usages.length && "use" in jwk && jwk.use !== "sign") {
throw errors.INVALID_DATA("JWK cannot be used for signing");
}
if ("ext" in jwk && jwk.ext !== extractable && extractable) {
throw errors.INVALID_DATA("JWK is not extractable");
}
break;
default:
throw errors.NOT_SUPPORTED(
`Format '${format}' cannot be used for the HMAC importKey() operation`
);
}
const length = data.byteLength * 8;
if (length === 0) {
throw errors.INVALID_DATA("Key cannot be empty");
}
return new CryptoKey(
"secret",
extractable,
{
name: "HMAC",
length,
hash: {
name: hash.name.toUpperCase()
}
},
usages,
data
);
};
exports.exportKey = function exportKey(format, key) {
const data = key._handle;
switch (format) {
case "raw":
return data.buffer.slice(0, data.byteLength);
case "jwk": {
const jwk = {
kty: "oct",
k: data.toString("base64url"),
alg: null,
key_ops: key.usages,
ext: key.extractable
};
switch (key.algorithm.hash.name) {
case "SHA-1":
jwk.alg = "HS1";
break;
case "SHA-256":
jwk.alg = "HS256";
break;
case "SHA-384":
jwk.alg = "HS384";
break;
case "SHA-512":
jwk.alg = "HS512";
break;
}
return jwk;
}
default:
throw errors.NOT_SUPPORTED(
`Format '${format}' cannot be used for the HMAC exportKey() operation`
);
}
};
exports.getKeyLength = function getKeyLength(algorithm) {
const { length, hash } = algorithm;
if (length === void 0) {
if (hash === "SHA-1" || hash === "SHA-256") return 512;
if (hash === "SHA-512") return 1024;
throw errors.OPERATION_ERROR(`Invalid hash '${hash}'`);
}
if (length === 0) {
throw errors.OPERATION_ERROR(`Invalid length ${length}`);
}
return length;
};
}
});
// ../../node_modules/bare-crypto/lib/web/algorithm/pbkdf2.js
var require_pbkdf22 = __commonJS({
"../../node_modules/bare-crypto/lib/web/algorithm/pbkdf2.js"(exports) {
var crypto = require_bare_crypto();
var errors = require_errors13();
var CryptoKey = require_crypto_key();
exports.deriveBits = function deriveBits(algorithm, key, length) {
if (length === void 0 || length % 8) {
throw errors.OPERATION_ERROR("Length must be multiple of 8");
}
if (algorithm.iterations === 0) {
throw errors.OPERATION_ERROR("Iterations must be non-0");
}
if (length === 0) {
return new ArrayBuffer(0);
}
let hash = algorithm.hash;
if (typeof hash === "string") hash = { name: hash };
const result = crypto.pbkdf2(
key._handle,
algorithm.salt,
algorithm.iterations,
length / 8,
hash.name
);
return result.buffer;
};
exports.importKey = function importKey(format, keyData, algorithm, extractable, usages) {
if (format !== "raw") {
throw errors.NOT_SUPPORTED(
`Format '${format}' cannot be used for the PBKDF2 importKey() operation`
);
}
for (const usage of usages) {
if (usage !== "deriveKey" && usage !== "deriveBits") {
throw new SyntaxError(`Invalid usage ${usage}`);
}
}
if (extractable) {
throw new SyntaxError("Extractable must be false");
}
return new CryptoKey(
"secret",
extractable,
{
name: "PBKDF2"
},
usages,
keyData
);
};
}
});
// ../../node_modules/bare-crypto/lib/web/algorithm/ed25519.js
var require_ed25519 = __commonJS({
"../../node_modules/bare-crypto/lib/web/algorithm/ed25519.js"(exports) {
var crypto = require_bare_crypto();
var binding = require_binding11();
var errors = require_errors13();
var { Ed25519PublicKey, Ed25519PrivateKey } = require_key();
var CryptoKey = require_crypto_key();
exports.sign = function sign(algorithm, key, data) {
if (key.type !== "private") {
throw errors.INVALID_ACCESS("Must pass private key for Ed25519 signing");
}
const signature = crypto.sign(null, data, key._handle);
return signature.buffer.slice(0, signature.byteLength);
};
exports.verify = function verify(algorithm, key, signature, data) {
if (key.type !== "public") {
throw errors.INVALID_ACCESS("Must pass public key for Ed25519 verification");
}
return crypto.verify(null, data, key._handle, signature);
};
exports.generateKey = function generateKey(algorithm, extractable, usages) {
for (const usage of usages) {
if (usage !== "sign" && usage !== "verify") {
throw new SyntaxError(
`Usage '${usage}' cannot be used for the Ed25519 generateKey() operation`
);
}
}
const keys = crypto.generateKeyPair("ed25519");
algorithm = { name: "Ed25519" };
return {
publicKey: new CryptoKey("public", true, algorithm, ["verify"], keys.publicKey),
privateKey: new CryptoKey("private", extractable, algorithm, ["sign"], keys.privateKey)
};
};
exports.importKey = function importKey(format, keyData, algorithm, extractable, usages) {
switch (format) {
case "spki":
for (const usage of usages) {
if (usage !== "verify") {
throw new SyntaxError(
`Usage '${usage}' cannot be used for the Ed25519 importKey() operation`
);
}
}
keyData = binding.ed25519FromSPKI(keyData.buffer, keyData.byteOffset, keyData.byteLength);
return new CryptoKey(
"public",
extractable,
{
name: "Ed25519"
},
usages,
new Ed25519PublicKey(keyData)
);
case "pkcs8":
for (const usage of usages) {
if (usage !== "sign") {
throw new SyntaxError(
`Usage '${usage}' cannot be used for the Ed25519 importKey() operation`
);
}
}
keyData = binding.ed25519FromPKCS8(keyData.buffer, keyData.byteOffset, keyData.byteLength);
return new CryptoKey(
"private",
extractable,
{
name: "Ed25519"
},
usages,
new Ed25519PrivateKey(keyData)
);
case "raw":
for (const usage of usages) {
if (usage !== "verify") {
throw new SyntaxError(
`Usage '${usage}' cannot be used for the Ed25519 importKey() operation`
);
}
}
if (keyData.byteLength * 8 !== 256) {
throw errors.INVALID_DATA("Key must be 256 bits");
}
return new CryptoKey(
"public",
extractable,
{
name: "Ed25519"
},
usages,
new Ed25519PublicKey(keyData.buffer)
);
case "jwk":
const jwk = keyData;
if ("d" in jwk) {
if (usages.some((usage) => usage !== "sign")) {
throw new SyntaxError("JWK must be valid for signing");
}
} else {
if (usages.some((usage) => usage !== "verify")) {
throw new SyntaxError("JWK must be valid for verification");
}
}
if (jwk.kty !== "OKP") {
throw errors.INVALID_DATA("JWK key must be an octet key-pair");
}
if (jwk.crv !== "Ed25519") {
throw errors.INVALID_DATA("JWK must use the Ed25519 curve");
}
if ("alg" in jwk && jwk.alg !== "Ed25519" && jwk.alg !== "EdDSA") {
throw errors.INVALID_DATA("JWK must use the Ed25519 curve");
}
if (usages.length && "use" in jwk && jwk.use !== "sig") {
throw errors.INVALID_DATA("JWK cannot be used for signatures");
}
if ("ext" in jwk && jwk.ext !== extractable && extractable) {
throw errors.INVALID_DATA("JWK is not extractable");
}
if ("d" in jwk) {
const key2 = Buffer.concat([
Buffer.from(jwk.d, "base64url"),
Buffer.from(jwk.x, "base64url")
]);
if (key2.byteLength * 8 !== 512) {
throw errors.INVALID_DATA("Key must be 512 bits");
}
return new CryptoKey(
"private",
extractable,
{
name: "Ed25519"
},
usages,
new Ed25519PrivateKey(key2.buffer)
);
}
const key = Buffer.from(jwk.x, "base64url");
if (key.byteLength * 8 !== 256) {
throw errors.INVALID_DATA("Key must be 256 bits");
}
return new CryptoKey(
"public",
extractable,
{
name: "Ed25519"
},
usages,
new Ed25519PublicKey(key.buffer)
);
default:
throw errors.NOT_SUPPORTED(
`Format '${format}' cannot be used for the Ed25519 importKey() operation`
);
}
};
exports.exportKey = function exportKey(format, key) {
const data = key._handle;
switch (format) {
case "spki":
if (key.type !== "public") {
throw errors.INVALID_ACCESS(
`Key of type '${key.type}' cannot be used for the Ed25519 exportKey() operation`
);
}
return binding.ed25519ToSPKI(data._key);
case "pkcs8":
if (key.type !== "private") {
throw errors.INVALID_ACCESS(
`Key of type '${key.type}' cannot be used for the Ed25519 exportKey() operation`
);
}
return binding.ed25519ToPKCS8(data._key);
case "raw": {
if (key.type !== "public") {
throw errors.INVALID_ACCESS(
`Key of type '${key.type}' cannot be used for the Ed25519 exportKey() operation`
);
}
return data._key.slice();
}
case "jwk": {
const buffer = Buffer.from(data._key);
if (key.type === "private") {
const d = buffer.subarray(0, 32).toString("base64url");
const x = buffer.subarray(32).toString("base64url");
return {
kty: "OKP",
alg: "Ed25519",
crv: "Ed25519",
x,
d,
key_ops: key.usages,
ext: key.extractable
};
}
return {
kty: "OKP",
alg: "Ed25519",
crv: "Ed25519",
x: buffer.toString("base64url"),
key_ops: key.usages,
ext: key.extractable
};
}
default:
throw errors.NOT_SUPPORTED(
`Format '${format}' cannot be used for the HMAC exportKey() operation`
);
}
};
}
});
// ../../node_modules/bare-crypto/lib/web/algorithm/sha.js
var require_sha = __commonJS({
"../../node_modules/bare-crypto/lib/web/algorithm/sha.js"(exports) {
var crypto = require_bare_crypto();
exports.digest = function digest(name, data) {
const digest2 = crypto.createHash(name).update(data).digest();
return digest2.buffer.slice(0, digest2.byteLength);
};
}
});
// ../../node_modules/bare-crypto/web.js
var require_web2 = __commonJS({
"../../node_modules/bare-crypto/web.js"(exports) {
var crypto = require_bare_crypto();
var errors = require_errors13();
var CryptoKey = require_crypto_key();
var hmac = require_hmac3();
var pbkdf2 = require_pbkdf22();
var ed25519 = require_ed25519();
var sha = require_sha();
exports.CryptoKey = CryptoKey;
exports.getRandomValues = function getRandomValues(array) {
return crypto.randomFillSync(array);
};
exports.randomUUID = crypto.randomUUID;
exports.SubtleCrypto = class SubtleCrypto {
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-generateKey
async generateKey(algorithm, extractable, usages) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
switch (algorithm.name.toLowerCase()) {
case "hmac":
return hmac.generateKey(algorithm, extractable, usages);
case "ed25519":
return ed25519.generateKey(algorithm, extractable, usages);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the generateKey() operation`
);
}
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-importKey
async importKey(format, keyData, algorithm, extractable, usages) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
switch (format) {
case "raw":
case "pkcs8":
case "spki":
if (ArrayBuffer.isView(keyData)) {
keyData = Buffer.from(keyData);
} else {
keyData = Buffer.from(keyData.slice());
}
break;
}
switch (algorithm.name.toLowerCase()) {
case "hmac":
return hmac.importKey(format, keyData, algorithm, extractable, usages);
case "ed25519":
return ed25519.importKey(format, keyData, algorithm, extractable, usages);
case "pbkdf2":
return pbkdf2.importKey(format, keyData, algorithm, extractable, usages);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the importKey() operation`
);
}
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-exportKey
async exportKey(format, key) {
if (!key.extractable) {
throw errors.INVALID_ACCESS("Key is not extractable");
}
switch (key.algorithm.name.toLowerCase()) {
case "hmac":
return hmac.exportKey(format, key);
case "ed25519":
return ed25519.exportKey(format, key);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${key.algorithm.name}' does not support the exportKey() operation`
);
}
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-sign
async sign(algorithm, key, data) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
if (algorithm.name.toLowerCase() !== key.algorithm.name.toLowerCase()) {
throw errors.INVALID_ACCESS(`Algorithm '${algorithm.name}' does not match key'`);
}
if (!key.usages.includes("sign")) {
throw errors.INVALID_ACCESS("Key cannot be used for signing");
}
switch (algorithm.name.toLowerCase()) {
case "hmac":
return hmac.sign(algorithm, key, data);
case "ed25519":
return ed25519.sign(algorithm, key, data);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the sign() operation`
);
}
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-verify
async verify(algorithm, key, signature, data) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
if (algorithm.name.toLowerCase() !== key.algorithm.name.toLowerCase()) {
throw errors.INVALID_ACCESS(`Algorithm '${algorithm.name}' does not match key'`);
}
if (!key.usages.includes("verify")) {
throw errors.INVALID_ACCESS("Key cannot be used for verification");
}
switch (algorithm.name.toLowerCase()) {
case "hmac":
return hmac.verify(algorithm, key, signature, data);
case "ed25519":
return ed25519.verify(algorithm, key, signature, data);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the verify() operation`
);
}
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-deriveBits
async deriveBits(algorithm, key, length) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
if (algorithm.name.toLowerCase() !== key.algorithm.name.toLowerCase()) {
throw errors.INVALID_ACCESS(`Algorithm '${algorithm.name}' does not match key'`);
}
if (!key.usages.includes("deriveBits")) {
throw errors.INVALID_ACCESS("Key cannot be used to derive bits");
}
switch (algorithm.name.toLowerCase()) {
case "pbkdf2":
return pbkdf2.deriveBits(algorithm, key, length);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the deriveBits() operation`
);
}
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-deriveKey
async deriveKey(algorithm, baseKey, derivedKeyType, extractable, usages) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
if (typeof derivedKeyType === "string") {
derivedKeyType = { name: derivedKeyType };
}
if (algorithm.name.toLowerCase() !== baseKey.algorithm.name.toLowerCase()) {
throw errors.INVALID_ACCESS(`Algorithm '${algorithm.name}' does not match key'`);
}
if (!baseKey.usages.includes("deriveKey")) {
throw errors.INVALID_ACCESS("Key cannot be used to derive key");
}
let length;
switch (derivedKeyType.name.toLowerCase()) {
case "hmac":
length = hmac.getKeyLength(derivedKeyType);
break;
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${derivedKeyType.name}' does not support the getKeyLength() operation`
);
}
let secret;
switch (algorithm.name.toLowerCase()) {
case "pbkdf2":
secret = pbkdf2.deriveBits(algorithm, baseKey, length);
break;
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the deriveBits() operation`
);
}
return this.importKey("raw", secret, derivedKeyType, extractable, usages);
}
// https://w3c.github.io/webcrypto/#SubtleCrypto-method-digest
async digest(algorithm, data) {
if (typeof algorithm === "string") algorithm = { name: algorithm };
switch (algorithm.name.toLowerCase()) {
case "sha-1":
return sha.digest(crypto.constants.hash.SHA1, data);
case "sha-256":
return sha.digest(crypto.constants.hash.SHA256, data);
case "sha-384":
return sha.digest(crypto.constants.hash.SHA384, data);
case "sha-512":
return sha.digest(crypto.constants.hash.SHA512, data);
default:
throw errors.NOT_SUPPORTED(
`Algorithm '${algorithm.name}' does not support the digest() operation`
);
}
}
};
exports.subtle = new exports.SubtleCrypto();
exports.Crypto = class Crypto {
get subtle() {
return exports.subtle;
}
getRandomValues(array) {
return exports.getRandomValues(array);
}
randomUUID() {
return exports.randomUUID();
}
};
}
});
// ../../node_modules/bare-crypto/index.js
var require_bare_crypto = __commonJS({
"../../node_modules/bare-crypto/index.js"(exports) {
var constants = require_constants9();
var Hash = require_hash();
var Hmac = require_hmac2();
var { Cipheriv, Decipheriv } = require_cipher2();
var { randomBytes, randomFill, randomUUID } = require_random();
var pbkdf2 = require_pbkdf2();
var { generateKeyPair } = require_key();
var { sign, verify } = require_signature();
exports.constants = constants;
exports.Hash = Hash;
exports.createHash = function createHash(algorithm, opts) {
return new Hash(algorithm, opts);
};
exports.Hmac = Hmac;
exports.createHmac = function createHmac(algorithm, key, opts) {
return new Hmac(algorithm, key, opts);
};
exports.Cipheriv = Cipheriv;
exports.createCipheriv = function createCipheriv(algorithm, key, iv, opts) {
return new Cipheriv(algorithm, key, iv, opts);
};
exports.Decipheriv = Decipheriv;
exports.createDecipheriv = function createDecipheriv(algorithm, key, iv, opts) {
return new Decipheriv(algorithm, key, iv, opts);
};
exports.randomBytes = randomBytes;
exports.randomFill = randomFill;
exports.randomFillSync = function randomFillSync(buffer, offset, size) {
return exports.randomFill(buffer, offset, size);
};
exports.randomUUID = randomUUID;
exports.pbkdf2 = pbkdf2;
exports.pbkdf2Sync = function pbkdf2Sync(password, salt, iterations, keylen, digest) {
return exports.pbkdf2(password, salt, iterations, keylen, digest);
};
exports.generateKeyPair = generateKeyPair;
exports.sign = sign;
exports.verify = verify;
exports.webcrypto = require_web2();
}
});
// ../../node_modules/holesail-logger/index.js
var require_holesail_logger = __commonJS({
"../../node_modules/holesail-logger/index.js"(exports, module) {
var colors = require_barely_colours();
var HolesailLogger = class {
constructor({ prefix = "Holesail", enabled = false, level = 1 } = {}) {
this.prefix = prefix;
this.enabled = enabled;
this.minLevel = level;
this.LOG_LEVELS = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3
};
}
log({ type, msg }) {
if (!this.enabled || type < this.minLevel) return;
let levelStr, colorFunc, consoleMethod;
switch (type) {
case this.LOG_LEVELS.DEBUG:
levelStr = "DEBUG";
colorFunc = colors.brightBlack;
consoleMethod = console.log;
break;
case this.LOG_LEVELS.INFO:
levelStr = "INFO";
colorFunc = colors.green;
consoleMethod = console.log;
break;
case this.LOG_LEVELS.WARN:
levelStr = "WARN";
colorFunc = colors.yellow;
consoleMethod = console.warn;
break;
case this.LOG_LEVELS.ERROR:
levelStr = "ERROR";
colorFunc = colors.red;
consoleMethod = console.error;
break;
default:
return;
}
const timestamp = colors.brightBlack((/* @__PURE__ */ new Date()).toISOString());
const prefix = colors.blue(`[${this.prefix}]`);
const level = colorFunc(`[${levelStr}]`);
consoleMethod(`${timestamp} ${prefix} ${level} ${msg}`);
}
};
module.exports = HolesailLogger;
}
});
// ../../node_modules/holesail/src/index.js
var require_src = __commonJS({
"../../node_modules/holesail/src/index.js"(exports, module) {
var ReadyResource = require_ready_resource();
var HolesailServer = require_holesail_server();
var HolesailClient = require_holesail_client();
var libKeys = require_hyper_cmd_lib_keys2();
var z32 = require_z32();
var { validateOpts } = require_validateInput();
var createHash = require_bare_crypto().createHash;
var HolesailLogger = require_holesail_logger();
var Holesail = class _Holesail extends ReadyResource {
constructor(opts = {}) {
super();
validateOpts(opts);
this.server = opts.server || false;
this.client = opts.client || false;
this.port = opts.port;
this.host = opts.host;
const data = _Holesail.urlParser(opts.key);
if (data.secure === void 0) {
this.secure = opts.secure;
} else {
this.secure = data.secure;
}
this.key = data.key;
this.udp = opts.udp;
this.log = opts.log !== void 0 ? opts.log : false;
this.dht = null;
this.running = false;
this.#initialise();
}
#initialise() {
if (this.server) {
if (this.key) {
this.seed = createHash("sha256").update(this.key.toString()).digest("hex");
} else if (this.secure) {
this.key = libKeys.randomBytes(32).toString("hex");
this.seed = createHash("sha256").update(this.key.toString()).digest("hex");
}
} else {
this.seed = this.secure ? z32.encode(createHash("sha256").update(this.key.toString()).digest()) : this.key;
}
}
static urlParser(url) {
url = String(url || "");
const protocol = "hs://";
let key;
let secure;
if (url && url.substring(0, 5) === protocol && url.substring(5, 9).length === 4) {
key = url.substring(9);
} else {
key = url;
}
if (url && url.substring(5, 6) === "s") {
secure = true;
}
return { key, secure };
}
static async lookup(url) {
const { key, secure: isSecure } = _Holesail.urlParser(url);
let argKey = key;
if (isSecure) {
const seedBuffer = createHash("sha256").update(key).digest();
argKey = z32.encode(seedBuffer);
} else {
try {
z32.decode(argKey);
} catch {
throw new Error(`Invalid key format: ${argKey}`);
}
}
const result = await HolesailClient.ping(argKey) || {};
result.secure = isSecure;
return result;
}
async _open() {
let enabled = false;
let level = 1;
if (typeof this.log === "boolean") {
enabled = this.log;
if (enabled) level = 1;
} else if (typeof this.log === "number") {
enabled = true;
level = Math.max(0, Math.min(3, this.log));
}
const loggerOpts = { prefix: "Holesail", enabled, level };
if (!this.server) {
loggerOpts.debug = this.log === 0;
}
const logger = new HolesailLogger(loggerOpts);
if (this.server) {
this.dht = new HolesailServer({ logger });
await this.connect();
} else {
this.dht = new HolesailClient({
key: this.seed,
secure: this.secure,
logger,
debug: this.log === 0
});
await this.connect();
}
}
async connect() {
if (this.running) throw new Error("Already connected");
if (this.server) {
await this.dht.start({
port: this.port,
host: this.host,
seed: this.seed,
secure: this.secure,
udp: this.udp
});
} else {
await this.dht.connect({
port: this.port,
host: this.host,
udp: this.udp
});
}
this.running = true;
}
async pause() {
await this.dht.pause();
}
async resume() {
await this.dht.resume();
}
get info() {
const info = this.dht.info;
let key;
if (this.key && this.secure) {
key = this.key;
} else {
key = info.key;
}
let url;
if (this.secure) {
url = "hs://s000" + key;
} else {
url = "hs://0000" + key;
}
if (this.secure && this.client) {
const key2 = this.key;
info.seed = createHash("sha256").update(key2.toString()).digest("hex");
}
return {
type: info.type,
state: info.state,
secure: info.secure,
port: info.port,
host: info.host,
protocol: info.protocol,
seed: info.seed,
key,
url,
publicKey: info.publicKey
};
}
async _close() {
this.dht.destroy();
this.running = false;
}
};
module.exports = Holesail;
}
});
// ../../bare-lib-entry-holesail.js
var bare_lib_entry_holesail_exports = {};
__export(bare_lib_entry_holesail_exports, {
default: () => bare_lib_entry_holesail_default
});
var import_holesail = __toESM(require_src());
var bare_lib_entry_holesail_default = import_holesail.default;
return __toCommonJS(bare_lib_entry_holesail_exports);
})();
;(function(){var g=globalThis;var s="__bare_os_stdlib__";g[s]=g[s]||{};var e=typeof __bare_os_bundle_exports__!=="undefined"?__bare_os_bundle_exports__:void 0;var v=e!=null&&typeof e==="object"&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e;g[s]["holesail"]=v;})();