Files
bare-operating-system/kernel/lib/bare/bundles/bareTuiUpdater.js
T
Raven Scott 9bdecc4170
Release rolling / release (push) Successful in 11m16s
Sync Holepunch modules to current clone/npm latest
Bump published pins (compact-encoding 3, bare-fetch/tls/https/ws 3,
bare-subprocess 6, bare-signals 5, corestore 7.12, protomux 3.11,
hypercore-crypto 3.7, bare-runtime 1.31) and regenerate catalogs,
manifests, and kernel/seeder bundles.

Adapt call sites to the new APIs:
- Corestore: explicit session flush before suspend(); treeCache ctor opts
- bare-crypto: KeyObject.export() instead of removed ._key
- Protomux 3.11: wait for fullyOpened()/fullyClosed() on chat channels
- bare-fetch: surface response.type and Headers.getSetCookie
- host snapshots: bare-os 3.9 / bare-posix / bare-fs.statfs frsize
- bare-subprocess 6: optional IPC channel + json serialization

Keep catalog sync from wiping curated pearEntries. Teach the Node test
shim to stub bare-thread/bare-worker (ESM absolute paths) and chain
Bare.on so bare-timers can load. Booter 479, protocol 34, seeder 14.
2026-08-12 20:56:28 -04:00

10422 lines
360 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/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-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];
}
rawListeners(name) {
if (this._events === void 0) return [];
const e = this._events[name];
return e === void 0 ? [] : e.list.map((l) => l[0]);
}
eventNames() {
if (this._events === void 0) return [];
return Reflect.ownKeys(this._events);
}
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/events-universal/default.js
var require_default = __commonJS({
"../../node_modules/events-universal/default.js"(exports, module) {
module.exports = require_bare_node_events();
}
});
// ../../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/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/lib/errors.js
var require_errors2 = __commonJS({
"../../node_modules/streamx/lib/errors.js"(exports, module) {
module.exports = class StreamError extends Error {
constructor(msg, code, fn = StreamError) {
super(msg);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
static isStreamDestroyed(err) {
return err && err.code === "STREAM_DESTROYED";
}
static isPrematureClose(err) {
return err && err.code === "PREMATURE_CLOSE";
}
static isAborted(err) {
return err && err.code === "ABORTED";
}
static isBadArgument(err) {
return err && err.code === "BAD_ARGUMENT";
}
get name() {
return "StreamError";
}
static STREAM_DESTROYED() {
return new StreamError("Stream was destroyed", "STREAM_DESTROYED", StreamError.STREAM_DESTROYED);
}
static PREMATURE_CLOSE(msg = "Premature close") {
return new StreamError(msg, "PREMATURE_CLOSE", StreamError.PREMATURE_CLOSE);
}
static ABORTED() {
return new StreamError("Stream aborted", "ABORTED", StreamError.ABORTED);
}
static BAD_ARGUMENT(msg = "Bad argument") {
return new StreamError(msg, "BAD_ARGUMENT", StreamError.BAD_ARGUMENT);
}
};
}
});
// ../../node_modules/streamx/index.js
var require_streamx = __commonJS({
"../../node_modules/streamx/index.js"(exports, module) {
var { EventEmitter } = require_default();
var FIFO = require_fast_fifo();
var TextDecoder = require_text_decoder();
var StreamError = require_errors2();
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 StreamError.BAD_ARGUMENT("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 || StreamError.PREMATURE_CLOSE("Writable stream closed"));
}
return;
}
}
if (stream === this.from) {
this.from = null;
if (this.to !== null) {
if ((stream._duplexState & READ_DONE) === 0) {
this.to.destroy(this.error || StreamError.PREMATURE_CLOSE("Readable stream closed"));
}
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 && !StreamError.isStreamDestroyed(this.error)) 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 = StreamError.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);
}
}
static deferred(fn, opts) {
const out = new PassThrough(opts);
fn().then((src) => {
if (src === null) return out.end();
if (out.destroying) return;
pipeline(src, out, noop);
}).catch((err) => out.destroy(err));
return out;
}
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(StreamError.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 StreamError.BAD_ARGUMENT("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 : StreamError.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(StreamError.PREMATURE_CLOSE());
}
if (wr && s._writableState && !s._writableState.ended) {
return onerror2(StreamError.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 && StreamError.isStreamDestroyed(err) ? 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(StreamError.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);
try {
let starting = Promise.resolve();
if (start) starting = forwardError(start.call(this, controller), controller);
if (pull) {
this._stream._read = this._read.bind(this, starting, pull.bind(this, controller));
}
if (cancel) {
this._stream.once("error", cancel.bind(this));
}
} catch (err) {
controller.error(err);
}
}
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 _read(starting, pull, cb) {
await starting;
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 });
const controller = new exports.WritableStreamDefaultController(this);
this._controller = controller;
try {
let starting = Promise.resolve();
if (start) starting = forwardError(start.call(this, controller), controller);
if (write) {
this._stream._write = this._write.bind(this, starting, write.bind(this));
}
if (close) {
this._stream._destroy = this._destroy.bind(this, close.call(this));
}
if (abort) {
this._stream.once("error", abort.bind(this));
}
} catch (err) {
controller.error(err);
}
}
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 _write(starting, write, data, cb) {
await starting;
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 = {}) {
if (isStreamx(transformer)) {
this._stream = transformer;
} else {
const { start, transform, flush } = transformer;
this._stream = new Transform({ ...writableStrategy, ...readableStrategy });
const controller = new exports.TransformStreamDefaultController(this);
this._controller = controller;
try {
let starting = Promise.resolve();
if (start) starting = forwardError(start.call(this, controller), controller);
if (transform) {
this._stream._transform = this._transform.bind(this, starting, transform.bind(this));
}
if (flush) {
this._stream._flush = this._flush.bind(this, flush.call(this, this._controller));
}
} catch (err) {
controller.error(err);
}
}
this._writable = new WritableStream(this._stream);
this._readable = new ReadableStream(this._stream);
}
get [transformKind]() {
return _TransformStream[transformKind];
}
get writable() {
return this._writable;
}
get readable() {
return this._readable;
}
async _transform(starting, transform, data, cb) {
await starting;
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];
};
async function forwardError(promise, controller) {
try {
await promise;
} catch (err) {
controller.error(err);
}
}
function noop() {
}
}
});
// ../../node_modules/bare-stream/index.js
var require_bare_stream = __commonJS({
"../../node_modules/bare-stream/index.js"(exports, module) {
var b4a = require_b4a();
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 = b4a.from(chunk, encoding || defaultEncoding);
}
return super.push(chunk);
}
unshift(chunk, encoding) {
if (typeof chunk === "string") {
chunk = b4a.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 = b4a.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 = b4a.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 = b4a.from(chunk, encoding || defaultEncoding);
}
return super.push(chunk);
}
unshift(chunk, encoding) {
if (typeof chunk === "string") {
chunk = b4a.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 = b4a.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 = b4a.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.Writable.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 = b4a.from(chunk, encoding || defaultEncoding);
}
return super.push(chunk);
}
unshift(chunk, encoding) {
if (typeof chunk === "string") {
chunk = b4a.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 = b4a.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 = b4a.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-tty/node_modules/bare-signals/binding.js
var require_binding = __commonJS({
"../../node_modules/bare-tty/node_modules/bare-signals/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-tty/node_modules/bare-signals/lib/errors.js
var require_errors3 = __commonJS({
"../../node_modules/bare-tty/node_modules/bare-signals/lib/errors.js"(exports, module) {
module.exports = class SignalError extends Error {
constructor(msg, fn = SignalError, code = fn.name) {
super(`${code}: ${msg}`);
this.code = code;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn);
}
}
get name() {
return "SignalError";
}
static UNKNOWN_SIGNAL(msg) {
return new SignalError(msg, SignalError.UNKNOWN_SIGNAL);
}
static SIGNAL_CLOSED(msg) {
return new SignalError(msg, SignalError.SIGNAL_CLOSED);
}
};
}
});
// ../../node_modules/bare-tty/node_modules/bare-signals/lib/emitter.js
var require_emitter = __commonJS({
"../../node_modules/bare-tty/node_modules/bare-signals/lib/emitter.js"(exports, module) {
var EventEmitter = require_bare_events();
var Signal = require_bare_signals();
module.exports = class SignalEmitter extends EventEmitter {
constructor() {
super();
this._signals = /* @__PURE__ */ new Map();
this._unrefed = false;
this.on("newListener", this._onnewlistener).on("removeListener", this._onremovelistener);
}
ref() {
this._unrefed = false;
for (const signal of this._signals.values()) signal.ref();
return this;
}
unref() {
this._unrefed = true;
for (const signal of this._signals.values()) signal.unref();
return this;
}
_onnewlistener(name) {
if (name === "newListener" || name === "removeListener") return;
if (this.listenerCount(name) === 0) {
const signal = new Signal(name);
signal.on("signal", this._onsignal.bind(this, name)).start();
if (this._unrefed) signal.unref();
this._signals.set(name, signal);
}
}
_onremovelistener(name) {
if (name === "newListener" || name === "removeListener") return;
if (this.listenerCount(name) === 0) {
const signal = this._signals.get(name);
if (this._unrefed) signal.ref();
signal.close();
this._signals.delete(name);
}
}
_onsignal(name) {
this.emit(name, name, Signal.constants[name]);
}
};
}
});
// ../../node_modules/bare-tty/node_modules/bare-signals/index.js
var require_bare_signals = __commonJS({
"../../node_modules/bare-tty/node_modules/bare-signals/index.js"(exports, module) {
var EventEmitter = require_bare_events();
var binding = require_binding();
var errors = require_errors3();
var signals = binding.signals;
module.exports = exports = class Signal extends EventEmitter {
constructor(signum) {
super();
if (typeof signum === "string") {
if (signum in signals === false) {
throw errors.UNKNOWN_SIGNAL(`Unknown signal '${signum}'`);
}
signum = signals[signum];
}
this._signum = signum;
this._closing = null;
this._handle = binding.init(this, this._onsignal, this._onclose);
}
start() {
if (this._closing) throw errors.SIGNAL_CLOSED("Signal is closed");
binding.start(this._handle, this._signum);
return this;
}
stop() {
if (this._closing) return this;
binding.stop(this._handle);
return this;
}
ref() {
if (this._closing) return this;
binding.ref(this._handle);
return this;
}
unref() {
if (this._closing) return this;
binding.unref(this._handle);
return this;
}
close() {
if (this._closing) return this._closing;
this._closing = EventEmitter.once(this, "close");
binding.close(this._handle);
return this._closing;
}
_onsignal() {
this.emit("signal", this._signum);
}
_onclose() {
this._handle = null;
this.emit("close");
}
};
exports.Emitter = require_emitter();
exports.constants = signals;
exports.errors = errors;
}
});
// ../../node_modules/bare-tty/binding.js
var require_binding2 = __commonJS({
"../../node_modules/bare-tty/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-tty/lib/constants.js
var require_constants = __commonJS({
"../../node_modules/bare-tty/lib/constants.js"(exports, module) {
var binding = require_binding2();
module.exports = exports = {
mode: {
NORMAL: binding.MODE_NORMAL,
RAW: binding.MODE_RAW,
IO: binding.MODE_IO || 0
},
state: {
READING: 1,
CLOSING: 2
}
};
exports.MODE_NORMAL = exports.mode.NORMAL;
exports.MODE_RAW = exports.mode.RAW;
exports.MODE_IO = exports.mode.IO;
}
});
// ../../node_modules/bare-tty/index.js
var require_bare_tty = __commonJS({
"../../node_modules/bare-tty/index.js"(exports) {
var { Readable, Writable } = require_bare_stream();
var Signal = require_bare_signals();
var binding = require_binding2();
var constants = require_constants();
var defaultReadBufferSize = 65536;
var empty = Buffer.alloc(0);
exports.ReadStream = class TTYReadStream extends Readable {
constructor(fd, opts = {}) {
super();
const { readBufferSize = defaultReadBufferSize, allowHalfOpen = true } = opts;
this._fd = fd;
this._state = 0;
this._allowHalfOpen = allowHalfOpen;
this._buffer = Buffer.alloc(readBufferSize);
this._pendingDestroy = null;
this._handle = binding.init(fd, this._buffer, this, noop, this._onread, this._onclose);
}
get fd() {
return this._fd;
}
get isTTY() {
return true;
}
setMode(mode) {
binding.setMode(this._handle, mode);
return this;
}
setRawMode(enabled) {
return this.setMode(enabled ? constants.mode.RAW : constants.mode.NORMAL);
}
_read() {
if ((this._state & constants.state.READING) === 0) {
this._state |= constants.state.READING;
binding.resume(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);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
_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);
}
}
_onclose() {
this._handle = null;
this._continueDestroy();
}
};
exports.WriteStream = class TTYWriteStream extends Writable {
constructor(fd, opts = {}) {
super();
this._fd = fd;
this._state = 0;
this._size = null;
this._pendingWrite = null;
this._pendingWriteBatch = null;
this._pendingDestroy = null;
this._handle = binding.init(fd, empty, this, this._onwrite, noop, this._onclose);
this._size = this.getWindowSize();
if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.start();
TTYWriteStream._streams.add(this);
}
get fd() {
return this._fd;
}
get isTTY() {
return true;
}
get columns() {
return this._size[0];
}
get rows() {
return this._size[1];
}
getWindowSize() {
return binding.getWindowSize(this._handle);
}
_writev(batch, cb) {
this._pendingWrite = cb;
this._pendingWriteBatch = batch;
try {
binding.writev(
this._handle,
batch.map(({ chunk }) => chunk)
);
} catch (err) {
this._continueWrite(err);
}
}
_predestroy() {
if (this._state & constants.state.CLOSING) return;
this._state |= constants.state.CLOSING;
binding.close(this._handle);
TTYWriteStream._streams.delete(this);
if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop();
}
_destroy(err, cb) {
if (this._state & constants.state.CLOSING) return cb(err);
this._state |= constants.state.CLOSING;
this._pendingDestroy = cb;
binding.close(this._handle);
TTYWriteStream._streams.delete(this);
if (TTYWriteStream._streams.size === 0) TTYWriteStream._resize.stop();
}
_continueWrite(err) {
if (this._pendingWrite === null) return;
const cb = this._pendingWrite;
this._pendingWrite = null;
this._pendingWriteBatch = null;
cb(err);
}
_continueDestroy() {
if (this._pendingDestroy === null) return;
const cb = this._pendingDestroy;
this._pendingDestroy = null;
cb(null);
}
_onwrite(err) {
this._continueWrite(err);
}
_onclose() {
this._handle = null;
this._continueDestroy();
}
_onresize() {
this._size = this.getWindowSize();
this.emit("resize");
}
static _streams = /* @__PURE__ */ new Set();
static _resize = new Signal("SIGWINCH");
};
exports.constants = constants;
exports.isTTY = binding.isTTY;
exports.isatty = exports.isTTY;
exports.WriteStream._resize.on("signal", () => {
for (const stream of exports.WriteStream._streams) {
stream._onresize();
}
}).unref();
function noop() {
}
}
});
// ../../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-ansi-escapes/key-decoder.js
var require_key_decoder = __commonJS({
"../../node_modules/bare-ansi-escapes/key-decoder.js"(exports, module) {
var { Transform } = require_bare_stream();
var {
constants: { ESC }
} = require_bare_ansi_escapes();
module.exports = class KeyDecoder extends Transform {
constructor(opts = {}) {
const { encoding = "utf8", escapeCodeTimeout = 500 } = opts;
super();
this.encoding = encoding;
this._escapeDelay = escapeCodeTimeout;
this._escapeTimer = null;
this._parser = parseKeys(this);
this._parser.next();
}
_transform(data, encoding, cb) {
clearTimeout(this._escapeTimer);
if (data[0] > 127 && data.length === 1) {
data[0] -= 128;
data = ESC + data.toString(this.encoding);
} else {
data = data.toString(this.encoding);
}
let n = 0;
for (const c of data) {
n += c.length;
this._parser.next(c);
if (n === data.length && c === ESC) {
this._escapeTimer = setTimeout(
this._escape.bind(this),
this._escapeDelay
);
}
}
cb(null);
}
_escape() {
this._parser.next("");
}
};
var Key = class {
constructor(name, sequence, ctrl, meta, shift) {
this.name = typeof name === "number" ? String.fromCharCode(name) : name;
this.sequence = sequence;
this.ctrl = ctrl;
this.meta = meta;
this.shift = shift;
}
};
function charLengthAt(str, i) {
if (str.length <= i) {
return 1;
}
return str.codePointAt(i) >= 65536 ? 2 : 1;
}
function* parseKeys(stream) {
while (true) {
let c = yield;
let s = c;
let escaped = false;
let name = null;
let ctrl = false;
let meta = false;
let shift = false;
if (c === ESC) {
escaped = true;
s += c = yield;
if (c === ESC) {
s += c = yield;
}
}
if (escaped && (c === "O" || c === "[")) {
let code = c;
let modifier = 0;
if (c === "O") {
s += c = yield;
if (c >= "0" && c <= "9") {
modifier = (c >> 0) - 1;
s += c = yield;
}
code += c;
} else if (c === "[") {
s += c = yield;
if (c === "[") {
code += c;
s += c = yield;
}
const start = s.length - 1;
if (c >= "0" && c <= "9") {
s += c = yield;
if (c >= "0" && c <= "9") {
s += c = yield;
if (c >= "0" && c <= "9") {
s += c = yield;
}
}
}
if (c === ";") {
s += c = yield;
if (c >= "0" && c <= "9") {
s += yield;
}
}
const cmd = s.slice(start);
let match;
if (match = /^(?:(\d\d?)(?:;(\d))?([~^$])|(\d{3}~))$/.exec(cmd)) {
if (match[4]) {
code += match[4];
} else {
code += match[1] + match[3];
modifier = (match[2] || 1) - 1;
}
} else if (match = /^((\d;)?(\d))?([A-Za-z])$/.exec(cmd)) {
code += match[4];
modifier = (match[3] || 1) - 1;
} else {
code += cmd;
}
}
ctrl = !!(modifier & 4);
meta = !!(modifier & 10);
shift = !!(modifier & 1);
switch (code) {
/* xterm/gnome ESC [ letter (with modifier) */
case "[P":
name = "f1";
break;
case "[Q":
name = "f2";
break;
case "[R":
name = "f3";
break;
case "[S":
name = "f4";
break;
/* xterm/gnome ESC O letter (without modifier) */
case "OP":
name = "f1";
break;
case "OQ":
name = "f2";
break;
case "OR":
name = "f3";
break;
case "OS":
name = "f4";
break;
/* xterm/rxvt ESC [ number ~ */
case "[11~":
name = "f1";
break;
case "[12~":
name = "f2";
break;
case "[13~":
name = "f3";
break;
case "[14~":
name = "f4";
break;
/* paste bracket mode */
case "[200~":
name = "paste-start";
break;
case "[201~":
name = "paste-end";
break;
/* from Cygwin and used in libuv */
case "[[A":
name = "f1";
break;
case "[[B":
name = "f2";
break;
case "[[C":
name = "f3";
break;
case "[[D":
name = "f4";
break;
case "[[E":
name = "f5";
break;
/* common */
case "[15~":
name = "f5";
break;
case "[17~":
name = "f6";
break;
case "[18~":
name = "f7";
break;
case "[19~":
name = "f8";
break;
case "[20~":
name = "f9";
break;
case "[21~":
name = "f10";
break;
case "[23~":
name = "f11";
break;
case "[24~":
name = "f12";
break;
/* xterm ESC [ letter */
case "[A":
name = "up";
break;
case "[B":
name = "down";
break;
case "[C":
name = "right";
break;
case "[D":
name = "left";
break;
case "[E":
name = "clear";
break;
case "[F":
name = "end";
break;
case "[H":
name = "home";
break;
/* xterm/gnome ESC O letter */
case "OA":
name = "up";
break;
case "OB":
name = "down";
break;
case "OC":
name = "right";
break;
case "OD":
name = "left";
break;
case "OE":
name = "clear";
break;
case "OF":
name = "end";
break;
case "OH":
name = "home";
break;
/* xterm/rxvt ESC [ number ~ */
case "[1~":
name = "home";
break;
case "[2~":
name = "insert";
break;
case "[3~":
name = "delete";
break;
case "[4~":
name = "end";
break;
case "[5~":
name = "pageup";
break;
case "[6~":
name = "pagedown";
break;
/* putty */
case "[[5~":
name = "pageup";
break;
case "[[6~":
name = "pagedown";
break;
/* rxvt */
case "[7~":
name = "home";
break;
case "[8~":
name = "end";
break;
/* rxvt keys with modifiers */
case "[a":
name = "up";
shift = true;
break;
case "[b":
name = "down";
shift = true;
break;
case "[c":
name = "right";
shift = true;
break;
case "[d":
name = "left";
shift = true;
break;
case "[e":
name = "clear";
shift = true;
break;
case "[2$":
name = "insert";
shift = true;
break;
case "[3$":
name = "delete";
shift = true;
break;
case "[5$":
name = "pageup";
shift = true;
break;
case "[6$":
name = "pagedown";
shift = true;
break;
case "[7$":
name = "home";
shift = true;
break;
case "[8$":
name = "end";
shift = true;
break;
case "Oa":
name = "up";
ctrl = true;
break;
case "Ob":
name = "down";
ctrl = true;
break;
case "Oc":
name = "right";
ctrl = true;
break;
case "Od":
name = "left";
ctrl = true;
break;
case "Oe":
name = "clear";
ctrl = true;
break;
case "[2^":
name = "insert";
ctrl = true;
break;
case "[3^":
name = "delete";
ctrl = true;
break;
case "[5^":
name = "pageup";
ctrl = true;
break;
case "[6^":
name = "pagedown";
ctrl = true;
break;
case "[7^":
name = "home";
ctrl = true;
break;
case "[8^":
name = "end";
ctrl = true;
break;
case "[Z":
name = "tab";
shift = true;
break;
default:
name = "undefined";
break;
}
} else if (c === "\r") {
name = "return";
meta = escaped;
} else if (c === "\n") {
name = "linefeed";
meta = escaped;
} else if (c === " ") {
name = "tab";
meta = escaped;
} else if (c === "\b" || c === "\x7F") {
name = "backspace";
meta = escaped;
} else if (c === ESC) {
name = "escape";
meta = escaped;
} else if (c === " ") {
name = "space";
meta = escaped;
} else if (!escaped && c <= "") {
name = String.fromCharCode(c.charCodeAt(0) + "a".charCodeAt(0) - 1);
ctrl = true;
} else if (/^[0-9A-Za-z]$/.exec(c) !== null) {
name = c.toLowerCase();
shift = /^[A-Z]$/.exec(c) !== null;
meta = escaped;
} else if (escaped) {
name = c.length ? null : "escape";
meta = true;
}
const sequence = s;
if (s.length > 0 && (name !== null || escaped || charLengthAt(s, 0) === s.length)) {
stream.push(
new Key(name === null ? sequence : name, sequence, ctrl, meta, shift)
);
}
}
}
}
});
// ../../node_modules/bare-tui/ansi.js
var require_ansi = __commonJS({
"../../node_modules/bare-tui/ansi.js"(exports, module) {
var ansi = require_bare_ansi_escapes();
var {
constants: { CSI, SGR }
} = ansi;
module.exports = {
...ansi,
// Absolute cursor move (0-indexed row/col). bare-ansi-escapes' cursorPosition
// has a column-first signature and treats row 0 as "stay", which is awkward
// for a renderer that thinks in (row, col), so we expose our own.
cursorTo: (row = 0, col = 0) => CSI + (row + 1) + ";" + (col + 1) + "H",
home: CSI + "H",
// Reverse video — used to draw a cursor cell when the real terminal cursor is
// hidden (e.g. inside a text input).
modifierReverse: SGR(7),
modifierNotReverse: SGR(27),
// Alternate screen buffer — gives the app its own full screen and restores
// the user's scrollback untouched on exit.
enterAltScreen: CSI + "?1049h",
leaveAltScreen: CSI + "?1049l",
// SGR mouse tracking (button events + SGR extended coordinates).
enableMouse: CSI + "?1000h" + CSI + "?1006h",
disableMouse: CSI + "?1006l" + CSI + "?1000l"
};
}
});
// ../../node_modules/bare-tui/renderer.js
var require_renderer = __commonJS({
"../../node_modules/bare-tui/renderer.js"(exports, module) {
var ansi = require_ansi();
module.exports = class Renderer {
constructor(output, { altScreen = true } = {}) {
this.out = output;
this.altScreen = altScreen;
this.lastLines = null;
}
// Enter the screen: optional alt buffer, hide the cursor, clear.
start() {
let s = "";
if (this.altScreen) s += ansi.enterAltScreen;
s += ansi.cursorHide + ansi.home + ansi.eraseDisplay;
this.out.write(s);
}
// Force the next render() to repaint everything (used on resize).
clear() {
this.lastLines = null;
}
render(view) {
const lines = String(view).split("\n");
let s = "";
if (this.lastLines === null) {
s += ansi.home;
for (let i = 0; i < lines.length; i++) {
s += ansi.eraseLineEnd + lines[i];
if (i < lines.length - 1) s += "\r\n";
}
s += ansi.eraseDisplayEnd;
} else {
for (let i = 0; i < lines.length; i++) {
if (lines[i] !== this.lastLines[i]) {
s += ansi.cursorTo(i, 0) + ansi.eraseLineEnd + lines[i];
}
}
if (this.lastLines.length > lines.length) {
s += ansi.cursorTo(lines.length, 0) + ansi.eraseDisplayEnd;
}
}
this.lastLines = lines;
if (s) this.out.write(s);
}
// Restore the terminal: show the cursor, leave the alt buffer.
stop() {
let s = ansi.cursorShow;
if (this.altScreen) s += ansi.leaveAltScreen;
this.out.write(s);
}
};
}
});
// ../../node_modules/bare-tui/mouse.js
var require_mouse = __commonJS({
"../../node_modules/bare-tui/mouse.js"(exports, module) {
var { constants } = require_bare_ansi_escapes();
var CSI = constants.CSI;
var SGR = "?1006";
var MODES = {
basic: "?1000",
// press / release
drag: "?1002",
// + motion while a button is held
all: "?1003"
// + motion with no button (hover)
};
function enable(mode = "basic") {
const m = MODES[mode] || MODES.basic;
return CSI + m + "h" + CSI + SGR + "h";
}
function disable(mode = "basic") {
const m = MODES[mode] || MODES.basic;
return CSI + SGR + "l" + CSI + m + "l";
}
var BUTTONS = ["left", "middle", "right", "none"];
function decode(body, final) {
const parts = body.split(";");
if (parts.length !== 3) return null;
const b = Number(parts[0]);
const col = Number(parts[1]);
const row = Number(parts[2]);
if (!Number.isInteger(b) || !Number.isInteger(col) || !Number.isInteger(row)) {
return null;
}
const mods = { ctrl: !!(b & 16), alt: !!(b & 8), shift: !!(b & 4) };
let action;
let button;
if (b & 64) {
action = "wheel";
button = b & 1 ? "wheeldown" : "wheelup";
} else {
button = BUTTONS[b & 3];
action = b & 32 ? "motion" : final === "M" ? "press" : "release";
}
return { type: "mouse", action, button, x: col - 1, y: row - 1, ...mods };
}
var MouseParser = class {
constructor() {
this._partial = "";
}
feed(buf) {
const s = this._partial + buf.toString("latin1");
this._partial = "";
let keys = "";
const events = [];
let i = 0;
while (i < s.length) {
if (s[i] === "\x1B" && s[i + 1] === "[" && s[i + 2] === "<") {
let j = i + 3;
while (j < s.length && s[j] !== "M" && s[j] !== "m") j++;
if (j >= s.length) {
this._partial = s.slice(i);
break;
}
const ev = decode(s.slice(i + 3, j), s[j]);
if (ev) events.push(ev);
i = j + 1;
} else {
keys += s[i];
i++;
}
}
return { keys: Buffer.from(keys, "latin1"), events };
}
};
module.exports = { enable, disable, decode, MouseParser, MODES };
}
});
// ../../node_modules/bare-tui/messages.js
var require_messages = __commonJS({
"../../node_modules/bare-tui/messages.js"(exports, module) {
var KeyMsg = class {
constructor(key) {
this.type = "key";
this.name = key.name;
this.sequence = key.sequence;
this.ctrl = key.ctrl;
this.meta = key.meta;
this.shift = key.shift;
}
toString() {
const parts = [];
if (this.ctrl) parts.push("ctrl");
if (this.meta) parts.push("alt");
if (this.shift && this.name && this.name.length > 1) parts.push("shift");
parts.push(this.name === "return" ? "enter" : this.name);
return parts.join("+");
}
// True if this key matches any of the given chords. A chord is matched
// against both the full string form ("ctrl+c", "enter") and the bare name
// ("c", "return"), so 'enter'/'return' and 'esc'/'escape' both work.
// if (msg.is('q', 'ctrl+c')) ...
is(...chords) {
const str = this.toString();
for (let chord of chords) {
if (chord === "esc") chord = "escape";
if (chord === str || chord === this.name) return true;
}
return false;
}
};
function windowSize(width, height) {
return { type: "resize", width, height };
}
function quitMsg() {
return { type: "quit" };
}
function errorMsg(error) {
return { type: "error", error };
}
module.exports = { KeyMsg, windowSize, quitMsg, errorMsg };
}
});
// ../../node_modules/bare-tui/program.js
var require_program = __commonJS({
"../../node_modules/bare-tui/program.js"(exports, module) {
var tty = require_bare_tty();
var KeyDecoder = require_key_decoder();
var Renderer = require_renderer();
var mouse = require_mouse();
var { KeyMsg, windowSize } = require_messages();
module.exports = class Program {
constructor(model, opts = {}) {
this.model = model;
this.opts = opts;
this.altScreen = opts.altScreen !== false;
this.fps = opts.fps ?? 60;
this._frameMs = this.fps > 0 ? Math.max(1, Math.round(1e3 / this.fps)) : 0;
this._frameTimer = null;
this._needsRender = false;
const m = opts.mouse;
this._mouseMode = m === true ? "basic" : m === "motion" ? "drag" : m in mouse.MODES ? m : null;
this._mouseParser = null;
this._ownsInput = !opts.input;
this._ownsOutput = !opts.output;
this.input = opts.input || (tty.isTTY(0) ? new tty.ReadStream(0) : null);
this.output = opts.output || (tty.isTTY(1) ? new tty.WriteStream(1) : null);
const detected = (s) => !!(s && s.isTTY);
this.inputIsTTY = opts.isTTY ?? detected(this.input);
this.outputIsTTY = opts.isTTY ?? detected(this.output);
if (!this.output) {
throw new Error("tea: no output stream (not a TTY); pass opts.output");
}
this.renderer = new Renderer(this.output, { altScreen: this.altScreen });
this._queue = [];
this._wake = null;
this._running = false;
this._tornDown = false;
this._suspended = false;
this._decoder = null;
this._onInput = null;
this._onKey = null;
this._onResize = null;
this._signals = [];
}
// Enqueue a Msg from anywhere — key decoder, resize handler, Cmd result, or
// external code (e.g. a worker IPC bridge calling program.send(...)).
send(msg) {
if (!msg) return;
this._queue.push(msg);
if (this._wake) {
const wake = this._wake;
this._wake = null;
wake();
}
}
quit() {
this.send({ type: "quit" });
}
async run() {
this._running = true;
try {
this._setup();
if (typeof this.model.init === "function") this._exec(this.model.init());
this.renderer.render(this._view());
while (this._running) {
const msg = await this._next();
if (!msg) continue;
if (msg.type === "quit") break;
if (msg.type === "resize") this.renderer.clear();
const [model, cmd] = this._update(msg);
this.model = model;
this._invalidate();
this._exec(cmd);
}
} finally {
this._running = false;
this._cancelFrame();
if (this._needsRender) {
this._needsRender = false;
this.renderer.render(this._view());
}
this._teardown();
}
return this.model;
}
// Mark the view dirty and schedule a render at most once per frame. Updates
// that land in the same frame collapse into one write.
_invalidate() {
if (this._suspended) return;
if (this._frameMs === 0) {
this.renderer.render(this._view());
return;
}
this._needsRender = true;
if (this._frameTimer) return;
this._frameTimer = setTimeout(() => {
this._frameTimer = null;
if (this._needsRender) {
this._needsRender = false;
this.renderer.render(this._view());
}
}, this._frameMs);
}
_cancelFrame() {
if (this._frameTimer) {
clearTimeout(this._frameTimer);
this._frameTimer = null;
}
}
_setup() {
if (this.input) {
if (this.inputIsTTY && this.input.setRawMode) this.input.setRawMode(true);
this._decoder = new KeyDecoder();
this._mouseParser = this._mouseMode ? new mouse.MouseParser() : null;
this._onKey = (key) => this.send(new KeyMsg(key));
this._onInput = (data) => {
if (this._mouseParser) {
const { keys, events } = this._mouseParser.feed(data);
for (const event of events) this.send(event);
if (keys.length) this._decoder.write(keys);
} else {
this._decoder.write(data);
}
};
this._decoder.on("data", this._onKey);
this.input.on("data", this._onInput);
}
if (this.outputIsTTY && typeof this.output.on === "function") {
this._onResize = () => this.send(windowSize(this.output.columns, this.output.rows));
this.output.on("resize", this._onResize);
}
this.renderer.start();
if (this._mouseMode) this.output.write(mouse.enable(this._mouseMode));
const width = this.output.columns ?? this.opts.width ?? 80;
const height = this.output.rows ?? this.opts.height ?? 24;
this.send(windowSize(width, height));
for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) {
const handler = () => this.send({ type: "quit" });
try {
global.Bare.on(sig, handler);
this._signals.push([sig, handler]);
} catch {
}
}
}
_teardown() {
if (this._tornDown) return;
this._tornDown = true;
this._cancelFrame();
for (const [sig, handler] of this._signals) {
try {
global.Bare.removeListener(sig, handler);
} catch {
}
}
try {
if (this._onResize) this.output.removeListener("resize", this._onResize);
} catch {
}
try {
if (this.input && this._onInput) {
this.input.removeListener("data", this._onInput);
}
} catch {
}
try {
if (this._decoder && this._onKey) {
this._decoder.removeListener("data", this._onKey);
}
} catch {
}
try {
this._decoder?.destroy();
} catch {
}
try {
if (this.input && this.inputIsTTY && this.input.setRawMode) {
this.input.setRawMode(false);
}
} catch {
}
try {
if (this._mouseMode) this.output.write(mouse.disable(this._mouseMode));
} catch {
}
this.renderer.stop();
if (this._ownsInput && this.input) {
try {
this.input.destroy();
} catch {
}
}
}
// Hand the terminal back to the shell: stop decoding input, drop raw mode,
// stop reading stdin, and leave the alt-screen. Mirrors the terminal parts of
// _teardown, but keeps the model and loop alive.
//
// Crucially we must NOT close stdin's fd here: a child spawned with
// `stdio: 'inherit'` inherits fd 0 directly, and a closed fd would hand it a
// dead stdin (the editor exits instantly). So we detach + pause and leave the
// fd open for the child.
_suspendTerminal() {
this._suspended = true;
this._cancelFrame();
try {
if (this.input && this._onInput) this.input.removeListener("data", this._onInput);
} catch {
}
try {
if (this._decoder && this._onKey) this._decoder.removeListener("data", this._onKey);
} catch {
}
try {
this._decoder?.destroy();
} catch {
}
this._decoder = null;
try {
if (this.input && this.inputIsTTY && this.input.setRawMode) this.input.setRawMode(false);
} catch {
}
try {
this.input?.pause?.();
} catch {
}
try {
if (this._mouseMode) this.output.write(mouse.disable(this._mouseMode));
} catch {
}
this.renderer.stop();
}
// Reclaim the terminal after a suspend: re-enter the screen, restore raw mode,
// re-attach the decoder, resume reading, and force a full repaint.
_resumeTerminal() {
this.renderer.start();
if (this.input) {
try {
if (this.inputIsTTY && this.input.setRawMode) this.input.setRawMode(true);
} catch {
}
this._decoder = new KeyDecoder();
this._decoder.on("data", this._onKey);
this.input.on("data", this._onInput);
try {
this.input.resume?.();
} catch {
}
}
if (this._mouseMode) this.output.write(mouse.enable(this._mouseMode));
this.renderer.clear();
this._suspended = false;
}
// Normalise update()'s return into a [model, cmd] pair. Accepts a bare model
// (no cmd) or null (no change), so update() can be terse.
_update(msg) {
const ret = this.model.update(msg);
if (ret === void 0 || ret === null) return [this.model, null];
if (Array.isArray(ret)) return [ret[0] ?? this.model, ret[1] ?? null];
return [ret, null];
}
_view() {
try {
return String(this.model.view());
} catch (err) {
return "view error: " + (err && err.message);
}
}
// Kick off a Cmd off the update path. Fire-and-forget at the top level —
// _runCmd dispatches each resulting Msg as it resolves.
_exec(cmd) {
this._runCmd(cmd);
}
// Recursively run a Cmd to completion. One function handles every shape so
// they nest correctly:
// null/undefined -> nothing
// array (batch) -> run all concurrently, resolve when the last finishes
// { __seq } (seq) -> run in order, awaiting each (and its nested cmds)
// function (Cmd) -> call it, send the Msg it returns
// Bails if the program is quitting so a sequence can't outlive teardown.
async _runCmd(cmd) {
if (!cmd || !this._running) return;
if (Array.isArray(cmd)) {
await Promise.all(cmd.map((c) => this._runCmd(c)));
return;
}
if (cmd.__seq) {
for (const c of cmd.__seq) {
if (!this._running) return;
await this._runCmd(c);
}
return;
}
if (cmd.__suspend) {
this._suspendTerminal();
let msg = null;
try {
msg = await cmd.__suspend();
} catch (error) {
msg = { type: "error", error };
}
if (this._running) {
this._resumeTerminal();
this._invalidate();
}
this.send(msg);
return;
}
try {
this.send(await cmd());
} catch (error) {
this.send({ type: "error", error });
}
}
// Await the next Msg. The executor body runs synchronously, so _wake is set
// before we suspend — no lost-wakeup race with send().
async _next() {
if (this._queue.length === 0) {
await new Promise((resolve) => {
this._wake = resolve;
});
}
return this._queue.shift();
}
};
}
});
// ../../node_modules/bare-tui/commands.js
var require_commands = __commonJS({
"../../node_modules/bare-tui/commands.js"(exports, module) {
var { quitMsg } = require_messages();
function quit() {
return quitMsg();
}
function batch(...cmds) {
return cmds.flat().filter(Boolean);
}
function sequence(...cmds) {
return { __seq: cmds.flat().filter(Boolean) };
}
function tick(ms, fn) {
return () => new Promise((resolve) => {
setTimeout(() => resolve(fn ? fn(/* @__PURE__ */ new Date()) : null), ms);
});
}
function suspend(fn) {
return { __suspend: fn };
}
function every(ms, fn) {
return () => new Promise((resolve) => {
const delay = ms - Date.now() % ms;
setTimeout(() => resolve(fn ? fn(/* @__PURE__ */ new Date()) : null), delay);
});
}
module.exports = { quit, batch, sequence, tick, every, suspend };
}
});
// ../../node_modules/bare-tui/key.js
var require_key = __commonJS({
"../../node_modules/bare-tui/key.js"(exports, module) {
function binding({ keys = [], help = null } = {}) {
return { keys: [].concat(keys), help };
}
function matches(msg, ...items) {
if (!msg || msg.type !== "key" || typeof msg.is !== "function") return false;
const chords = items.flatMap(
(item) => item && typeof item === "object" && Array.isArray(item.keys) ? item.keys : [item]
);
return msg.is(...chords);
}
module.exports = { matches, binding };
}
});
// ../../node_modules/bare-tui/style.js
var require_style = __commonJS({
"../../node_modules/bare-tui/style.js"(exports, module) {
var { constants } = require_bare_ansi_escapes();
var ansi = require_ansi();
var CSI = constants.CSI;
var RESET = ansi.modifierReset;
var ANSI_RE = /\x1b\[[0-9;?]*[A-Za-z]/g;
var ANSI_STICKY = /\x1b\[[0-9;?]*[A-Za-z]/y;
function stripAnsi(str) {
return String(str).replace(ANSI_RE, "");
}
function charWidth(cp) {
if (cp === 0) return 0;
if (cp < 32 || cp >= 127 && cp < 160) return 0;
if (isZeroWidth(cp)) return 0;
if (isWide(cp)) return 2;
return 1;
}
function isZeroWidth(cp) {
return cp >= 768 && cp <= 879 || // combining diacriticals
cp >= 6832 && cp <= 6911 || cp >= 7616 && cp <= 7679 || cp >= 8400 && cp <= 8447 || // combining marks for symbols
cp >= 65056 && cp <= 65071 || cp === 8203 || // zero-width space
cp >= 8204 && cp <= 8207 || cp === 65279;
}
function isWide(cp) {
return cp >= 4352 && cp <= 4447 || // Hangul Jamo
cp >= 11904 && cp <= 12350 || // CJK radicals … punctuation
cp >= 12353 && cp <= 13311 || // Hiragana … CJK compat
cp >= 13312 && cp <= 19903 || // CJK Ext A
cp >= 19968 && cp <= 40959 || // CJK Unified
cp >= 40960 && cp <= 42191 || // Yi
cp >= 44032 && cp <= 55203 || // Hangul syllables
cp >= 63744 && cp <= 64255 || // CJK compat ideographs
cp >= 65072 && cp <= 65103 || // CJK compat forms
cp >= 65280 && cp <= 65376 || // fullwidth forms
cp >= 65504 && cp <= 65510 || cp >= 127744 && cp <= 129791 || // emoji & symbols
cp >= 131072 && cp <= 262141;
}
function lineWidth(line) {
let w = 0;
for (const ch of stripAnsi(line)) w += charWidth(ch.codePointAt(0));
return w;
}
function width(str) {
let w = 0;
for (const line of String(str).split("\n")) w = Math.max(w, lineWidth(line));
return w;
}
function height(str) {
return String(str).split("\n").length;
}
function truncate(str, w) {
if (w <= 0) return "";
let out = "";
let used = 0;
let sawAnsi = false;
let i = 0;
while (i < str.length) {
if (str[i] === "\x1B") {
ANSI_STICKY.lastIndex = i;
const m = ANSI_STICKY.exec(str);
if (m) {
out += m[0];
sawAnsi = true;
i = ANSI_STICKY.lastIndex;
continue;
}
}
const cp = str.codePointAt(i);
const ch = String.fromCodePoint(cp);
const cw = charWidth(cp);
if (used + cw > w) break;
out += ch;
used += cw;
i += ch.length;
}
if (sawAnsi) out += RESET;
return out;
}
function padLine(line, w, pos = 0) {
const lw = lineWidth(line);
if (lw > w) return truncate(line, w);
const space = w - lw;
if (space === 0) return line;
if (pos <= 0) return line + " ".repeat(space);
if (pos >= 1) return " ".repeat(space) + line;
const left = Math.floor(space * pos);
return " ".repeat(left) + line + " ".repeat(space - left);
}
var NAMED = {
black: 30,
red: 31,
green: 32,
yellow: 33,
blue: 34,
magenta: 35,
cyan: 36,
white: 37,
default: 39,
gray: 90,
grey: 90,
brightblack: 90,
brightred: 91,
brightgreen: 92,
brightyellow: 93,
brightblue: 94,
brightmagenta: 95,
brightcyan: 96,
brightwhite: 97
};
function colorParams(spec, bg) {
if (spec === void 0 || spec === null || spec === "") return [];
const lead = bg ? 48 : 38;
if (typeof spec === "number") return [lead, 5, spec & 255];
const s = String(spec);
if (s[0] === "#") {
let hex = s.slice(1);
if (hex.length === 3) hex = hex.replace(/./g, (c) => c + c);
const n = parseInt(hex, 16);
return [lead, 2, n >> 16 & 255, n >> 8 & 255, n & 255];
}
const name = s.toLowerCase();
if (name in NAMED) return [bg ? NAMED[name] + 10 : NAMED[name]];
if (/^\d+$/.test(s)) return [lead, 5, parseInt(s, 10) & 255];
return [];
}
function sgr(params) {
return params.length ? CSI + params.join(";") + "m" : "";
}
var borders = {
normal: {
topLeft: "\u250C",
top: "\u2500",
topRight: "\u2510",
left: "\u2502",
right: "\u2502",
bottomLeft: "\u2514",
bottom: "\u2500",
bottomRight: "\u2518"
},
rounded: {
topLeft: "\u256D",
top: "\u2500",
topRight: "\u256E",
left: "\u2502",
right: "\u2502",
bottomLeft: "\u2570",
bottom: "\u2500",
bottomRight: "\u256F"
},
thick: {
topLeft: "\u250F",
top: "\u2501",
topRight: "\u2513",
left: "\u2503",
right: "\u2503",
bottomLeft: "\u2517",
bottom: "\u2501",
bottomRight: "\u251B"
},
double: {
topLeft: "\u2554",
top: "\u2550",
topRight: "\u2557",
left: "\u2551",
right: "\u2551",
bottomLeft: "\u255A",
bottom: "\u2550",
bottomRight: "\u255D"
}
};
var position = { top: 0, left: 0, center: 0.5, right: 1, bottom: 1 };
function sides(args) {
const a = args.map((n) => n || 0);
if (a.length <= 1) return [a[0] || 0, a[0] || 0, a[0] || 0, a[0] || 0];
if (a.length === 2) return [a[0], a[1], a[0], a[1]];
if (a.length === 3) return [a[0], a[1], a[2], a[1]];
return [a[0], a[1], a[2], a[3]];
}
var Style = class _Style {
constructor(props = {}) {
this.props = props;
}
_with(patch) {
return new _Style({ ...this.props, ...patch });
}
bold(v = true) {
return this._with({ bold: v });
}
faint(v = true) {
return this._with({ faint: v });
}
italic(v = true) {
return this._with({ italic: v });
}
underline(v = true) {
return this._with({ underline: v });
}
strikethrough(v = true) {
return this._with({ strikethrough: v });
}
reverse(v = true) {
return this._with({ reverse: v });
}
foreground(c) {
return this._with({ fg: c });
}
background(c) {
return this._with({ bg: c });
}
width(n) {
return this._with({ width: n });
}
height(n) {
return this._with({ height: n });
}
align(pos) {
return this._with({ align: pos });
}
alignVertical(pos) {
return this._with({ alignV: pos });
}
padding(...v) {
return this._with({ padding: sides(v) });
}
margin(...v) {
return this._with({ margin: sides(v) });
}
border(chars, ...sidesOn) {
const on = sidesOn.length ? sides(sidesOn).map(Boolean) : [true, true, true, true];
return this._with({ border: chars, borderSides: on });
}
borderForeground(c) {
return this._with({ borderFg: c });
}
// SGR for text styling, opened once per inner line and closed with RESET.
_open() {
const p = this.props;
const params = [];
if (p.bold) params.push(1);
if (p.faint) params.push(2);
if (p.italic) params.push(3);
if (p.underline) params.push(4);
if (p.reverse) params.push(7);
if (p.strikethrough) params.push(9);
params.push(...colorParams(p.fg, false));
params.push(...colorParams(p.bg, true));
return sgr(params);
}
render(text) {
const p = this.props;
const pad = p.padding || [0, 0, 0, 0];
const mar = p.margin || [0, 0, 0, 0];
const align = p.align || 0;
let lines = String(text).split("\n");
const block = !!p.border || p.bg !== void 0 && p.bg !== null || !!p.width || align !== 0 || pad[0] || pad[1] || pad[2] || pad[3];
const contentW = p.width || width(lines.join("\n"));
if (block) lines = lines.map((l) => padLine(l, contentW, align));
else lines = lines.map((l) => lineWidth(l) > contentW ? truncate(l, contentW) : l);
if (p.height) lines = fitHeight(lines, p.height, contentW, p.alignV || 0);
const innerW = contentW + pad[1] + pad[3];
if (pad[1] || pad[3]) {
const l = " ".repeat(pad[3]);
const r = " ".repeat(pad[1]);
lines = lines.map((line) => l + line + r);
}
const blank = " ".repeat(innerW);
for (let i = 0; i < pad[0]; i++) lines.unshift(blank);
for (let i = 0; i < pad[2]; i++) lines.push(blank);
const open = this._open();
if (open) lines = lines.map((line) => open + line.split(RESET).join(RESET + open) + RESET);
if (p.border) lines = applyBorder(lines, innerW, p.border, p.borderSides, p.borderFg);
if (mar[3] || mar[1]) {
const l = " ".repeat(mar[3]);
const r = " ".repeat(mar[1]);
lines = lines.map((line) => l + line + r);
}
const fullW = width(lines.join("\n"));
const marginBlank = " ".repeat(fullW);
for (let i = 0; i < mar[0]; i++) lines.unshift(marginBlank);
for (let i = 0; i < mar[2]; i++) lines.push(marginBlank);
return lines.join("\n");
}
};
function fitHeight(lines, h, w, posV) {
if (lines.length >= h) return lines.slice(0, h);
const extra = h - lines.length;
const before = posV <= 0 ? 0 : posV >= 1 ? extra : Math.floor(extra * posV);
const blank = " ".repeat(w);
return [...Array(before).fill(blank), ...lines, ...Array(extra - before).fill(blank)];
}
function applyBorder(lines, innerW, chars, on, fg) {
const [t, r, b, l] = on;
const paint = (s) => {
const params = colorParams(fg, false);
return params.length ? sgr(params) + s + RESET : s;
};
const out = [];
if (t) {
out.push(paint((l ? chars.topLeft : "") + chars.top.repeat(innerW) + (r ? chars.topRight : "")));
}
const left = l ? paint(chars.left) : "";
const right = r ? paint(chars.right) : "";
for (const line of lines) out.push(left + line + right);
if (b) {
out.push(
paint(
(l ? chars.bottomLeft : "") + chars.bottom.repeat(innerW) + (r ? chars.bottomRight : "")
)
);
}
return out;
}
function joinHorizontal(pos, ...blocks) {
const cols = blocks.map((b) => String(b).split("\n"));
const widths = cols.map((lines) => width(lines.join("\n")));
const h = Math.max(...cols.map((lines) => lines.length));
const padded = cols.map((lines, i) => {
const w = widths[i];
const filled = lines.map((line) => padLine(line, w, 0));
const extra = h - filled.length;
const before = pos <= 0 ? 0 : pos >= 1 ? extra : Math.floor(extra * pos);
const blank = " ".repeat(w);
return [...Array(before).fill(blank), ...filled, ...Array(extra - before).fill(blank)];
});
const out = [];
for (let row = 0; row < h; row++) out.push(padded.map((c) => c[row]).join(""));
return out.join("\n");
}
function joinVertical(pos, ...blocks) {
const cols = blocks.map((b) => String(b).split("\n"));
const w = Math.max(...cols.map((lines) => width(lines.join("\n"))));
const out = [];
for (const lines of cols) {
for (const line of lines) out.push(padLine(line, w, pos));
}
return out.join("\n");
}
function style() {
return new Style();
}
style.Style = Style;
style.borders = borders;
style.position = position;
style.joinHorizontal = joinHorizontal;
style.joinVertical = joinVertical;
style.width = width;
style.height = height;
style.truncate = truncate;
style.stripAnsi = stripAnsi;
module.exports = {
style,
Style,
borders,
position,
joinHorizontal,
joinVertical,
width,
height,
truncate,
stripAnsi
};
}
});
// ../../node_modules/bare-tui/components/spinner.js
var require_spinner = __commonJS({
"../../node_modules/bare-tui/components/spinner.js"(exports, module) {
var { tick } = require_commands();
var dots = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
var line = ["|", "/", "-", "\\"];
var points = ["\u2219\u2219\u2219", "\u25CF\u2219\u2219", "\u2219\u25CF\u2219", "\u2219\u2219\u25CF"];
var nextId = 1;
var Spinner = class {
constructor(opts = {}) {
this.frames = opts.frames || dots;
this.fps = opts.fps || 10;
this.frame = 0;
this.id = nextId++;
this.tag = 0;
}
// Returns the Cmd that starts the animation. Call from the parent's init().
init() {
return this._tick();
}
_tick() {
const id = this.id;
const tag = this.tag;
const ms = Math.max(1, Math.round(1e3 / this.fps));
return tick(ms, () => ({ type: "spinner.tick", id, tag }));
}
update(msg) {
if (!msg || msg.type !== "spinner.tick") return [this, null];
if (msg.id !== this.id || msg.tag !== this.tag) return [this, null];
this.frame = (this.frame + 1) % this.frames.length;
this.tag++;
return [this, this._tick()];
}
view() {
return this.frames[this.frame];
}
};
function create(opts) {
return new Spinner(opts);
}
module.exports = { create, Spinner, dots, line, points };
}
});
// ../../node_modules/bare-tui/components/textinput.js
var require_textinput = __commonJS({
"../../node_modules/bare-tui/components/textinput.js"(exports, module) {
var ansi = require_ansi();
var dim = (s) => ansi.modifierDim + s + ansi.modifierReset;
var reverse = (s) => ansi.modifierReverse + s + ansi.modifierNotReverse;
var TextInput = class {
constructor(opts = {}) {
this.value = opts.value || "";
this.placeholder = opts.placeholder || "";
this.prompt = opts.prompt || "";
this.charLimit = opts.charLimit || 0;
this.echoMode = opts.echoMode || "normal";
this.maskChar = opts.maskChar || "\u2022";
this.focused = !!opts.focused;
this.cursor = this.value.length;
}
focus() {
this.focused = true;
return this;
}
blur() {
this.focused = false;
return this;
}
setValue(v) {
v = String(v);
this.value = this.charLimit ? v.slice(0, this.charLimit) : v;
this.cursor = Math.min(this.cursor, this.value.length);
return this;
}
reset() {
this.value = "";
this.cursor = 0;
return this;
}
update(msg) {
if (!this.focused || !msg || msg.type !== "key") return [this, null];
if (msg.is("left", "ctrl+b")) {
this.cursor = Math.max(0, this.cursor - 1);
} else if (msg.is("right", "ctrl+f")) {
this.cursor = Math.min(this.value.length, this.cursor + 1);
} else if (msg.is("home", "ctrl+a")) {
this.cursor = 0;
} else if (msg.is("end", "ctrl+e")) {
this.cursor = this.value.length;
} else if (msg.is("backspace")) {
if (this.cursor > 0) {
this.value = this.value.slice(0, this.cursor - 1) + this.value.slice(this.cursor);
this.cursor--;
}
} else if (msg.is("delete")) {
if (this.cursor < this.value.length) {
this.value = this.value.slice(0, this.cursor) + this.value.slice(this.cursor + 1);
}
} else {
this._insert(msg);
}
return [this, null];
}
// Insert a single printable character at the cursor. We key off the decoded
// sequence (not name) so case and punctuation come through verbatim, and skip
// control bytes, chorded keys, and DEL.
_insert(msg) {
const ch = msg.sequence;
const printable = !msg.ctrl && !msg.meta && typeof ch === "string" && ch.length === 1 && ch >= " " && ch !== "\x7F";
if (!printable) return;
if (this.charLimit && this.value.length >= this.charLimit) return;
this.value = this.value.slice(0, this.cursor) + ch + this.value.slice(this.cursor);
this.cursor++;
}
_display() {
if (this.echoMode === "password") return this.maskChar.repeat(this.value.length);
return this.value;
}
view() {
if (this.value.length === 0) {
if (!this.focused) return this.prompt + dim(this.placeholder);
const head = this.placeholder.slice(0, 1) || " ";
return this.prompt + reverse(head) + dim(this.placeholder.slice(1));
}
const text = this._display();
if (!this.focused) return this.prompt + text;
const at = text.slice(this.cursor, this.cursor + 1) || " ";
return this.prompt + text.slice(0, this.cursor) + reverse(at) + text.slice(this.cursor + 1);
}
};
function create(opts) {
return new TextInput(opts);
}
module.exports = { create, TextInput };
}
});
// ../../node_modules/bare-tui/components/autocomplete.js
var require_autocomplete = __commonJS({
"../../node_modules/bare-tui/components/autocomplete.js"(exports, module) {
var key = require_key();
var ansi = require_ansi();
var { style } = require_style();
var textinput = require_textinput();
var dim = (s) => ansi.modifierDim + s + ansi.modifierReset;
var keys = {
up: key.binding({ keys: ["up", "ctrl+p"], help: { key: "\u2191", desc: "prev" } }),
down: key.binding({ keys: ["down", "ctrl+n"], help: { key: "\u2193", desc: "next" } }),
accept: key.binding({ keys: ["tab"], help: { key: "tab", desc: "accept" } }),
dismiss: key.binding({ keys: ["esc"], help: { key: "esc", desc: "dismiss" } })
};
function normalize(s) {
if (typeof s === "string") return { name: s, desc: "" };
return { name: String(s.name ?? ""), desc: String(s.desc ?? "") };
}
var Autocomplete = class {
constructor(opts = {}) {
this.trigger = opts.trigger ?? "/";
this.suggestions = (opts.suggestions || []).map(normalize);
this.maxVisible = opts.maxVisible || 6;
this.width = opts.width || 0;
this.input = textinput.create({
value: opts.value || "",
placeholder: opts.placeholder || "",
prompt: opts.prompt || "",
focused: !!opts.focused
});
this.selected = 0;
this.dismissed = false;
this._lastValue = this.input.value;
}
get value() {
return this.input.value;
}
get focused() {
return this.input.focused;
}
focus() {
this.input.focus();
return this;
}
blur() {
this.input.blur();
return this;
}
setValue(v) {
this.input.setValue(v);
this._lastValue = this.input.value;
return this;
}
reset() {
this.input.reset();
this.selected = 0;
this.dismissed = false;
this._lastValue = "";
return this;
}
setSuggestions(list) {
this.suggestions = (list || []).map(normalize);
return this;
}
// The suggestions matching the typed text, or [] when no menu is warranted.
// A menu is warranted once the line begins with the trigger; the text after
// it is a case-insensitive prefix filter over suggestion names.
matches() {
const v = this.input.value;
if (!v.startsWith(this.trigger)) return [];
const typed = v.slice(this.trigger.length).toLowerCase();
return this.suggestions.filter((s) => s.name.toLowerCase().startsWith(typed));
}
// Whether the dropdown is currently showing.
get open() {
return this.input.focused && !this.dismissed && this.matches().length > 0;
}
// The highlighted suggestion, or null.
selectedSuggestion() {
const m = this.matches();
return m.length ? m[Math.min(this.selected, m.length - 1)] : null;
}
// Complete the line to the highlighted suggestion and close the menu.
accept() {
const s = this.selectedSuggestion();
if (!s) return this;
this.input.setValue(this.trigger + s.name + " ");
this.input.cursor = this.input.value.length;
this.dismissed = true;
this._lastValue = this.input.value;
return this;
}
update(msg) {
if (!msg || msg.type !== "key" || !this.input.focused) return [this, null];
if (this.open) {
if (key.matches(msg, keys.up)) return [this._move(-1), null];
if (key.matches(msg, keys.down)) return [this._move(1), null];
if (key.matches(msg, keys.accept)) return [this.accept(), null];
if (key.matches(msg, keys.dismiss)) {
this.dismissed = true;
return [this, null];
}
}
const [input, cmd] = this.input.update(msg);
this.input = input;
if (this.input.value !== this._lastValue) {
this.dismissed = false;
this._lastValue = this.input.value;
this.selected = 0;
}
return [this, cmd];
}
_move(dir) {
const n = this.matches().length;
if (n) this.selected = (this.selected + dir + n) % n;
return this;
}
view() {
return this.input.view();
}
// The dropdown, or '' when closed. Rows are `/name desc`, the highlight in
// reverse video; a footer notes any matches scrolled out of view.
menuView() {
if (!this.open) return "";
const all = this.matches();
const sel = Math.min(this.selected, all.length - 1);
const start = Math.max(0, Math.min(sel - this.maxVisible + 1, all.length - this.maxVisible));
const top = all.length > this.maxVisible ? Math.max(0, start) : 0;
const shown = all.slice(top, top + this.maxVisible);
const nameW = Math.max(...all.map((s) => (this.trigger + s.name).length));
const rows = shown.map((s, i) => {
const isSel = top + i === sel;
const label = (this.trigger + s.name).padEnd(nameW);
const text = s.desc ? label + " " + s.desc : label;
if (isSel) {
return style().foreground("black").background("magenta").render(" " + text + " ");
}
return " " + style().foreground("magenta").render(label) + (s.desc ? " " + dim(s.desc) : "");
});
if (all.length > shown.length) {
rows.push(dim(` \u2026${all.length - shown.length} more`));
}
return rows.join("\n");
}
};
function create(opts) {
return new Autocomplete(opts);
}
module.exports = { create, Autocomplete, keys };
}
});
// ../../node_modules/bare-tui/components/textarea.js
var require_textarea = __commonJS({
"../../node_modules/bare-tui/components/textarea.js"(exports, module) {
var ansi = require_ansi();
var dim = (s) => ansi.modifierDim + s + ansi.modifierReset;
var reverse = (s) => ansi.modifierReverse + s + ansi.modifierNotReverse;
var TextArea = class {
constructor(opts = {}) {
this.width = Math.max(1, opts.width || 40);
this.height = Math.max(1, opts.height || 6);
this.placeholder = opts.placeholder || "";
this.charLimit = opts.charLimit || 0;
this.focused = !!opts.focused;
this.lines = String(opts.value || "").split("\n");
this.row = this.lines.length - 1;
this.col = this.lines[this.row].length;
this.yOffset = 0;
}
get value() {
return this.lines.join("\n");
}
// Total character count including the newlines between lines.
get length() {
let n = this.lines.length - 1;
for (const line of this.lines) n += line.length;
return n;
}
focus() {
this.focused = true;
return this;
}
blur() {
this.focused = false;
return this;
}
setValue(v) {
this.lines = String(v).split("\n");
if (this.lines.length === 0) this.lines = [""];
this.row = this.lines.length - 1;
this.col = this.lines[this.row].length;
this._clamp();
return this;
}
setSize(width, height) {
if (width) this.width = Math.max(1, width);
if (height) this.height = Math.max(1, height);
return this;
}
reset() {
this.lines = [""];
this.row = 0;
this.col = 0;
this.yOffset = 0;
return this;
}
update(msg) {
if (!this.focused || !msg || msg.type !== "key") return [this, null];
if (msg.is("left", "ctrl+b")) this._left();
else if (msg.is("right", "ctrl+f")) this._right();
else if (msg.is("up")) this._vertical(-1);
else if (msg.is("down")) this._vertical(1);
else if (msg.is("home", "ctrl+a")) this._home();
else if (msg.is("end", "ctrl+e")) this._end();
else if (msg.is("enter")) this._newline();
else if (msg.is("backspace")) this._backspace();
else if (msg.is("delete")) this._delete();
else this._insert(msg);
return [this, null];
}
// ── editing ────────────────────────────────────────────────────────────
_line() {
return this.lines[this.row];
}
_left() {
if (this.col > 0) this.col--;
else if (this.row > 0) {
this.row--;
this.col = this._line().length;
}
}
_right() {
if (this.col < this._line().length) this.col++;
else if (this.row < this.lines.length - 1) {
this.row++;
this.col = 0;
}
}
_home() {
const { vrow, rows } = this._cursor();
this.col = rows[vrow].start;
}
_end() {
const { vrow, rows } = this._cursor();
this.col = rows[vrow].start + rows[vrow].text.length;
}
_newline() {
if (this.charLimit && this.length >= this.charLimit) return;
const line = this._line();
this.lines.splice(this.row, 1, line.slice(0, this.col), line.slice(this.col));
this.row++;
this.col = 0;
}
_backspace() {
const line = this._line();
if (this.col > 0) {
this.lines[this.row] = line.slice(0, this.col - 1) + line.slice(this.col);
this.col--;
} else if (this.row > 0) {
const prev = this.lines[this.row - 1];
this.col = prev.length;
this.lines[this.row - 1] = prev + line;
this.lines.splice(this.row, 1);
this.row--;
}
}
_delete() {
const line = this._line();
if (this.col < line.length) {
this.lines[this.row] = line.slice(0, this.col) + line.slice(this.col + 1);
} else if (this.row < this.lines.length - 1) {
this.lines[this.row] = line + this.lines[this.row + 1];
this.lines.splice(this.row + 1, 1);
}
}
_insert(msg) {
const ch = msg.sequence;
const printable = !msg.ctrl && !msg.meta && typeof ch === "string" && ch.length === 1 && ch >= " " && ch !== "\x7F";
if (!printable) return;
if (this.charLimit && this.length >= this.charLimit) return;
const line = this._line();
this.lines[this.row] = line.slice(0, this.col) + ch + line.slice(this.col);
this.col++;
}
_vertical(delta) {
const { vrow, vcol, rows } = this._cursor();
const target = Math.max(0, Math.min(vrow + delta, rows.length - 1));
if (target === vrow) return;
const r = rows[target];
this.row = r.line;
this.col = r.start + Math.min(vcol, r.text.length);
}
_clamp() {
this.row = Math.max(0, Math.min(this.row, this.lines.length - 1));
this.col = Math.max(0, Math.min(this.col, this._line().length));
}
// ── wrapping / cursor mapping ────────────────────────────────────────────
// Visual rows: each logical line char-wrapped to width. A line whose length
// is an exact multiple of width gets a trailing empty row so the cursor has
// somewhere to sit at the wrap boundary.
_visualRows() {
const w = this.width;
const rows = [];
for (let l = 0; l < this.lines.length; l++) {
const line = this.lines[l];
if (line.length === 0) {
rows.push({ line: l, start: 0, text: "" });
continue;
}
for (let s = 0; s < line.length; s += w) {
rows.push({ line: l, start: s, text: line.slice(s, s + w) });
}
if (line.length % w === 0) rows.push({ line: l, start: line.length, text: "" });
}
return rows;
}
// Locate the cursor among the visual rows.
_cursor() {
const rows = this._visualRows();
let last = 0;
for (let i = 0; i < rows.length; i++) {
const r2 = rows[i];
if (r2.line !== this.row) continue;
last = i;
if (this.col >= r2.start && this.col < r2.start + r2.text.length) {
return { vrow: i, vcol: this.col - r2.start, rows };
}
if (r2.text.length === 0 && this.col === r2.start) {
return { vrow: i, vcol: 0, rows };
}
}
const r = rows[last];
return { vrow: last, vcol: this.col - r.start, rows };
}
// ── rendering ────────────────────────────────────────────────────────────
view() {
const empty = this.lines.length === 1 && this.lines[0] === "";
const { vrow, vcol, rows } = this._cursor();
if (vrow < this.yOffset) this.yOffset = vrow;
else if (vrow >= this.yOffset + this.height) this.yOffset = vrow - this.height + 1;
const maxOffset = Math.max(0, rows.length - this.height);
this.yOffset = Math.max(0, Math.min(this.yOffset, maxOffset));
const out = [];
for (let i = 0; i < this.height; i++) {
const idx = this.yOffset + i;
if (empty && idx === 0) {
out.push(this._placeholderRow());
} else if (!rows[idx]) {
out.push(" ".repeat(this.width));
} else {
const onCursor = this.focused && idx === vrow;
out.push(this._renderRow(rows[idx].text, onCursor ? vcol : -1));
}
}
return out.join("\n");
}
_renderRow(text, cursorCol) {
if (cursorCol < 0) return text.padEnd(this.width);
const at = text[cursorCol] ?? " ";
const line = text.slice(0, cursorCol) + reverse(at) + text.slice(cursorCol + 1);
const visible = Math.max(text.length, cursorCol + 1);
return line + " ".repeat(Math.max(0, this.width - visible));
}
_placeholderRow() {
const ph = this.placeholder;
if (!this.focused) return this._pad(dim(ph), ph.length);
const head = ph.slice(0, 1) || " ";
const body = reverse(head) + dim(ph.slice(1));
return this._pad(body, Math.max(ph.length, 1));
}
_pad(styled, visibleLen) {
return styled + " ".repeat(Math.max(0, this.width - visibleLen));
}
};
function create(opts) {
return new TextArea(opts);
}
module.exports = { create, TextArea };
}
});
// ../../node_modules/bare-tui/components/viewport.js
var require_viewport = __commonJS({
"../../node_modules/bare-tui/components/viewport.js"(exports, module) {
var key = require_key();
var keys = {
up: key.binding({ keys: ["up", "k"], help: { key: "\u2191/k", desc: "up" } }),
down: key.binding({ keys: ["down", "j"], help: { key: "\u2193/j", desc: "down" } }),
pageUp: key.binding({ keys: ["pageup", "b"], help: { key: "pgup", desc: "page up" } }),
pageDown: key.binding({ keys: ["pagedown", "f"], help: { key: "pgdn", desc: "page down" } }),
halfUp: key.binding({ keys: ["ctrl+u"] }),
halfDown: key.binding({ keys: ["ctrl+d"] }),
top: key.binding({ keys: ["home"], help: { key: "home", desc: "top" } }),
bottom: key.binding({ keys: ["end"], help: { key: "end", desc: "bottom" } })
};
var Viewport = class {
constructor(opts = {}) {
this.width = opts.width || 0;
this.height = opts.height || 0;
this.yOffset = 0;
this.lines = [];
}
setContent(content) {
this.lines = String(content).split("\n");
this._clamp();
return this;
}
get maxOffset() {
return Math.max(0, this.lines.length - this.height);
}
get atTop() {
return this.yOffset <= 0;
}
get atBottom() {
return this.yOffset >= this.maxOffset;
}
get scrollPercent() {
if (this.lines.length <= this.height) return 1;
return this.yOffset / this.maxOffset;
}
setYOffset(n) {
this.yOffset = n;
this._clamp();
return this;
}
scrollUp(n = 1) {
return this.setYOffset(this.yOffset - n);
}
scrollDown(n = 1) {
return this.setYOffset(this.yOffset + n);
}
gotoTop() {
return this.setYOffset(0);
}
gotoBottom() {
return this.setYOffset(this.maxOffset);
}
_clamp() {
this.yOffset = Math.max(0, Math.min(this.yOffset, this.maxOffset));
}
update(msg) {
if (!msg || msg.type !== "key") return [this, null];
const h = this.height || 1;
if (key.matches(msg, keys.up)) this.scrollUp(1);
else if (key.matches(msg, keys.down)) this.scrollDown(1);
else if (key.matches(msg, keys.pageUp)) this.scrollUp(h);
else if (key.matches(msg, keys.pageDown)) this.scrollDown(h);
else if (key.matches(msg, keys.halfUp)) this.scrollUp(Math.ceil(h / 2));
else if (key.matches(msg, keys.halfDown)) this.scrollDown(Math.ceil(h / 2));
else if (key.matches(msg, keys.top)) this.gotoTop();
else if (key.matches(msg, keys.bottom)) this.gotoBottom();
return [this, null];
}
view() {
const out = [];
for (let i = 0; i < this.height; i++) {
const line = this.lines[this.yOffset + i] ?? "";
out.push(this.width > 0 ? line.slice(0, this.width) : line);
}
return out.join("\n");
}
};
function create(opts) {
return new Viewport(opts);
}
module.exports = { create, Viewport, keys };
}
});
// ../../node_modules/bare-tui/components/list.js
var require_list = __commonJS({
"../../node_modules/bare-tui/components/list.js"(exports, module) {
var key = require_key();
var ansi = require_ansi();
var textinput = require_textinput();
var reverse = (s) => ansi.modifierReverse + s + ansi.modifierNotReverse;
var dim = (s) => ansi.modifierDim + s + ansi.modifierReset;
var keys = {
up: key.binding({ keys: ["up", "k"], help: { key: "\u2191/k", desc: "up" } }),
down: key.binding({ keys: ["down", "j"], help: { key: "\u2193/j", desc: "down" } }),
pageUp: key.binding({ keys: ["pageup"] }),
pageDown: key.binding({ keys: ["pagedown"] }),
filter: key.binding({ keys: ["/"], help: { key: "/", desc: "filter" } }),
accept: key.binding({ keys: ["enter"] }),
cancel: key.binding({ keys: ["esc"], help: { key: "esc", desc: "clear filter" } })
};
function filterValue(item) {
if (item === void 0 || item === null) return "";
if (typeof item === "string") return item;
return item.filterValue || item.title || String(item);
}
function titleOf(item) {
if (item === void 0 || item === null) return "";
if (typeof item === "string") return item;
return item.title ?? String(item);
}
var List = class {
constructor(opts = {}) {
this.items = opts.items ? opts.items.slice() : [];
this.height = opts.height || 10;
this.width = opts.width || 0;
this.title = opts.title || "";
this.filterable = opts.filterable !== false;
this.input = textinput.create({ prompt: "" });
this.filter = "";
this.filtering = false;
this.selected = 0;
this.offset = 0;
this.filtered = this.items.map((_, i) => i);
}
get visibleCount() {
return this.filtered.length;
}
selectedItem() {
if (!this.filtered.length) return null;
return this.items[this.filtered[this.selected]];
}
setItems(items) {
this.items = items.slice();
this._applyFilter();
return this;
}
update(msg) {
if (!msg || msg.type !== "key") return [this, null];
if (this.filtering) {
if (key.matches(msg, keys.cancel)) {
this.filtering = false;
this.filter = "";
this.input.reset().blur();
this._applyFilter();
return [this, null];
}
if (key.matches(msg, keys.accept)) {
this.filtering = false;
this.input.blur();
return [this, null];
}
const [input, cmd] = this.input.update(msg);
this.input = input;
this.filter = this.input.value;
this._applyFilter();
return [this, cmd];
}
if (this.filterable && key.matches(msg, keys.filter)) {
this.filtering = true;
this.input.focus();
return [this, null];
}
if (key.matches(msg, keys.cancel) && this.filter) {
this.filter = "";
this.input.reset();
this._applyFilter();
return [this, null];
}
if (key.matches(msg, keys.up)) this._move(-1);
else if (key.matches(msg, keys.down)) this._move(1);
else if (key.matches(msg, keys.pageUp)) this._move(-this.height);
else if (key.matches(msg, keys.pageDown)) this._move(this.height);
return [this, null];
}
_applyFilter() {
const q = this.filter.trim().toLowerCase();
const all = this.items.map((_, i) => i);
this.filtered = q ? all.filter((i) => filterValue(this.items[i]).toLowerCase().includes(q)) : all;
this.selected = 0;
this.offset = 0;
}
_move(delta) {
if (!this.filtered.length) return;
const last = this.filtered.length - 1;
this.selected = Math.max(0, Math.min(this.selected + delta, last));
if (this.selected < this.offset) this.offset = this.selected;
else if (this.selected >= this.offset + this.height) {
this.offset = this.selected - this.height + 1;
}
}
view() {
const lines = [];
if (this.title) lines.push(this.title);
if (this.filtering || this.filter) {
lines.push("/" + (this.filtering ? this.input.view() : this.filter));
}
const rows = [];
if (!this.filtered.length) {
rows.push(dim(" no matches"));
} else {
const end = Math.min(this.offset + this.height, this.filtered.length);
for (let p = this.offset; p < end; p++) {
const item = this.items[this.filtered[p]];
rows.push(this._renderRow(titleOf(item), p === this.selected));
}
}
while (rows.length < this.height) rows.push("");
lines.push(...rows);
const pos = this.filtered.length ? this.selected + 1 : 0;
lines.push(dim(` ${pos}/${this.filtered.length}`));
return lines.join("\n");
}
_renderRow(label, selected) {
let line = (selected ? "\u203A " : " ") + label;
if (this.width > 0) line = line.slice(0, this.width).padEnd(this.width);
return selected ? reverse(line) : line;
}
};
function create(opts) {
return new List(opts);
}
module.exports = { create, List, keys };
}
});
// ../../node_modules/bare-tui/components/table.js
var require_table = __commonJS({
"../../node_modules/bare-tui/components/table.js"(exports, module) {
var key = require_key();
var { style, width, truncate } = require_style();
var header = (s) => style().bold(true).render(s);
var selected = (s) => style().reverse(true).render(s);
var dim = (s) => style().faint(true).render(s);
var keys = {
up: key.binding({ keys: ["up", "k"], help: { key: "\u2191/k", desc: "up" } }),
down: key.binding({ keys: ["down", "j"], help: { key: "\u2193/j", desc: "down" } }),
pageUp: key.binding({ keys: ["pageup"] }),
pageDown: key.binding({ keys: ["pagedown"] }),
top: key.binding({ keys: ["home"], help: { key: "home", desc: "top" } }),
bottom: key.binding({ keys: ["end"], help: { key: "end", desc: "bottom" } })
};
function cell(value, w) {
const text = String(value ?? "");
if (width(text) > w) return truncate(text, w);
return text + " ".repeat(w - width(text));
}
var Table = class {
constructor(opts = {}) {
this.columns = opts.columns || [];
this.rows = opts.rows || [];
this.height = opts.height || 10;
this.rule = opts.rule || "\u2500";
this.cursor = 0;
this.offset = 0;
this._clamp();
}
get totalWidth() {
if (!this.columns.length) return 0;
const cols = this.columns.reduce((sum, c) => sum + c.width, 0);
return cols + (this.columns.length - 1);
}
selectedRow() {
return this.rows[this.cursor] || null;
}
setRows(rows) {
this.rows = rows;
this._clamp();
return this;
}
setColumns(columns) {
this.columns = columns;
return this;
}
gotoTop() {
this.cursor = 0;
this.offset = 0;
return this;
}
gotoBottom() {
this.cursor = Math.max(0, this.rows.length - 1);
this.offset = Math.max(0, this.rows.length - this.height);
return this;
}
_move(delta) {
if (!this.rows.length) return;
this.cursor = Math.max(0, Math.min(this.cursor + delta, this.rows.length - 1));
if (this.cursor < this.offset) this.offset = this.cursor;
else if (this.cursor >= this.offset + this.height) {
this.offset = this.cursor - this.height + 1;
}
}
_clamp() {
this.cursor = Math.max(0, Math.min(this.cursor, Math.max(0, this.rows.length - 1)));
const maxOffset = Math.max(0, this.rows.length - this.height);
this.offset = Math.max(0, Math.min(this.offset, maxOffset));
}
update(msg) {
if (!msg || msg.type !== "key") return [this, null];
if (key.matches(msg, keys.up)) this._move(-1);
else if (key.matches(msg, keys.down)) this._move(1);
else if (key.matches(msg, keys.pageUp)) this._move(-this.height);
else if (key.matches(msg, keys.pageDown)) this._move(this.height);
else if (key.matches(msg, keys.top)) this.gotoTop();
else if (key.matches(msg, keys.bottom)) this.gotoBottom();
return [this, null];
}
_row(cells) {
return this.columns.map((c, i) => cell(cells[i], c.width)).join(" ");
}
view() {
const lines = [];
lines.push(header(this._row(this.columns.map((c) => c.title))));
lines.push(dim(this.rule.repeat(this.totalWidth)));
const end = Math.min(this.offset + this.height, this.rows.length);
const body = [];
for (let i = this.offset; i < end; i++) {
const line = this._row(this.rows[i]);
body.push(i === this.cursor ? selected(line) : line);
}
while (body.length < this.height) body.push(" ".repeat(this.totalWidth));
return lines.concat(body).join("\n");
}
};
function create(opts) {
return new Table(opts);
}
module.exports = { create, Table, keys };
}
});
// ../../node_modules/bare-tui/components/help.js
var require_help = __commonJS({
"../../node_modules/bare-tui/components/help.js"(exports, module) {
var { style, width, truncate } = require_style();
var defaultStyles = {
key: (s) => s,
desc: (s) => style().faint(true).render(s),
sep: (s) => style().faint(true).render(s)
};
function toBindings(x) {
if (!x) return [];
return Array.isArray(x) ? x : Object.values(x);
}
function resolve(keymap, showAll) {
if (Array.isArray(keymap)) {
if (!showAll) return keymap;
return keymap.length && Array.isArray(keymap[0]) ? keymap : [keymap];
}
if (showAll) {
if (typeof keymap.fullHelp === "function") return keymap.fullHelp();
if (keymap.full) return keymap.full;
const short = typeof keymap.shortHelp === "function" ? keymap.shortHelp() : keymap.short || toBindings(keymap);
return [short];
}
if (typeof keymap.shortHelp === "function") return keymap.shortHelp();
if (keymap.short) return keymap.short;
return toBindings(keymap);
}
function helpful(binding) {
return binding && binding.help && binding.help.key;
}
var Help = class {
constructor(opts = {}) {
this.width = opts.width || 0;
this.showAll = !!opts.showAll;
this.separator = opts.separator || " \u2022 ";
this.styles = { ...defaultStyles, ...opts.styles || {} };
}
setWidth(n) {
this.width = n;
return this;
}
view(keymap) {
if (this.showAll) {
const columns = resolve(keymap, true).map((group) => this._column(group)).filter((c) => c.length);
if (!columns.length) return "";
const blocks = [];
columns.forEach((c, i) => {
if (i) blocks.push(" ");
blocks.push(c);
});
return style.joinHorizontal(style.position.top, ...blocks);
}
return this._short(resolve(keymap, false));
}
_short(bindings) {
const items = bindings.filter(helpful);
if (!items.length) return "";
const sep = this.styles.sep(this.separator);
let line = items.map((b) => this.styles.key(b.help.key) + " " + this.styles.desc(b.help.desc)).join(sep);
if (this.width > 0 && width(line) > this.width) line = truncate(line, this.width);
return line;
}
_column(bindings) {
const items = bindings.filter(helpful);
if (!items.length) return "";
const keyW = Math.max(...items.map((b) => width(b.help.key)));
return items.map((b) => {
const gap = " ".repeat(keyW - width(b.help.key) + 2);
return this.styles.key(b.help.key) + gap + this.styles.desc(b.help.desc);
}).join("\n");
}
};
function create(opts) {
return new Help(opts);
}
module.exports = { create, Help };
}
});
// ../../node_modules/bare-tui/components/progress.js
var require_progress = __commonJS({
"../../node_modules/bare-tui/components/progress.js"(exports, module) {
var { style } = require_style();
var dim = (s) => style().faint(true).render(s);
var Progress = class {
constructor(opts = {}) {
this.width = opts.width || 40;
this.full = opts.full || "\u2588";
this.empty = opts.empty || "\u2591";
this.showPercentage = opts.showPercentage !== false;
this.color = opts.color || null;
this.gradient = opts.gradient || null;
}
setWidth(n) {
this.width = n;
return this;
}
view(percent) {
percent = Math.max(0, Math.min(1, percent || 0));
const reserve = this.showPercentage ? 5 : 0;
const w = Math.max(1, this.width - reserve);
const filled = Math.round(w * percent);
const gap = w - filled;
let bar;
if (this.gradient) {
let head = "";
for (let i = 0; i < filled; i++) {
const t = filled <= 1 ? 0 : i / (filled - 1);
const color = lerpHex(this.gradient[0], this.gradient[1], t);
head += style().foreground(color).render(this.full);
}
bar = head + dim(this.empty.repeat(gap));
} else {
const head = this.color ? style().foreground(this.color).render(this.full.repeat(filled)) : this.full.repeat(filled);
bar = head + dim(this.empty.repeat(gap));
}
if (!this.showPercentage) return bar;
const pct = Math.round(percent * 100);
return bar + " " + (pct + "%").padStart(4);
}
};
function hexToRgb(hex) {
let h = hex.replace("#", "");
if (h.length === 3) h = h.replace(/./g, (c) => c + c);
const n = parseInt(h, 16);
return [n >> 16 & 255, n >> 8 & 255, n & 255];
}
function lerpHex(a, b, t) {
const A = hexToRgb(a);
const B = hexToRgb(b);
const mix = A.map((v, i) => Math.round(v + (B[i] - v) * t));
return "#" + mix.map((v) => v.toString(16).padStart(2, "0")).join("");
}
function create(opts) {
return new Progress(opts);
}
module.exports = { create, Progress };
}
});
// ../../node_modules/bare-tui/components/paginator.js
var require_paginator = __commonJS({
"../../node_modules/bare-tui/components/paginator.js"(exports, module) {
var key = require_key();
var { style } = require_style();
var dim = (s) => style().faint(true).render(s);
var keys = {
prev: key.binding({
keys: ["left", "h", "pageup"],
help: { key: "\u2190/h", desc: "prev page" }
}),
next: key.binding({
keys: ["right", "l", "pagedown"],
help: { key: "\u2192/l", desc: "next page" }
})
};
var Paginator = class {
constructor(opts = {}) {
this.perPage = opts.perPage || 10;
this.total = opts.total || 0;
this.page = opts.page || 0;
this.type = opts.type || "arabic";
this.activeDot = opts.activeDot || "\u25CF";
this.inactiveDot = opts.inactiveDot || "\u25CB";
this._clamp();
}
get totalPages() {
return Math.max(1, Math.ceil(this.total / this.perPage));
}
onFirstPage() {
return this.page <= 0;
}
onLastPage() {
return this.page >= this.totalPages - 1;
}
setTotal(n) {
this.total = n;
this._clamp();
return this;
}
setPage(n) {
this.page = n;
this._clamp();
return this;
}
nextPage() {
if (!this.onLastPage()) this.page++;
return this;
}
prevPage() {
if (!this.onFirstPage()) this.page--;
return this;
}
_clamp() {
this.page = Math.max(0, Math.min(this.page, this.totalPages - 1));
}
// Items on the current page (last page may be short).
itemsOnPage(length = this.total) {
const [start, end] = this.sliceBounds(length);
return Math.max(0, end - start);
}
// [start, end) into a collection of `length` items for the current page.
sliceBounds(length = this.total) {
const start = Math.min(this.page * this.perPage, length);
const end = Math.min(start + this.perPage, length);
return [start, end];
}
update(msg) {
if (!msg || msg.type !== "key") return [this, null];
if (key.matches(msg, keys.next)) this.nextPage();
else if (key.matches(msg, keys.prev)) this.prevPage();
return [this, null];
}
view() {
if (this.type === "dots") {
let out = "";
for (let i = 0; i < this.totalPages; i++) {
out += i === this.page ? this.activeDot : dim(this.inactiveDot);
}
return out;
}
return `${this.page + 1}/${this.totalPages}`;
}
};
function create(opts) {
return new Paginator(opts);
}
module.exports = { create, Paginator, keys };
}
});
// ../../node_modules/bare-tui/components/stopwatch.js
var require_stopwatch = __commonJS({
"../../node_modules/bare-tui/components/stopwatch.js"(exports, module) {
var { tick } = require_commands();
var nextId = 1;
function pad(n) {
return String(n).padStart(2, "0");
}
function format(ms) {
const total = Math.floor(ms / 1e3);
const h = Math.floor(total / 3600);
const m = Math.floor(total % 3600 / 60);
const s = total % 60;
return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${pad(m)}:${pad(s)}`;
}
var Stopwatch = class {
constructor(opts = {}) {
this.interval = opts.interval || 1e3;
this.elapsed = opts.elapsed || 0;
this.running = false;
this.id = nextId++;
this.tag = 0;
}
_tick() {
const id = this.id;
const tag = this.tag;
return tick(this.interval, () => ({ type: "stopwatch.tick", id, tag }));
}
start() {
if (this.running) return null;
this.running = true;
return this._tick();
}
stop() {
this.running = false;
this.tag++;
return null;
}
toggle() {
return this.running ? this.stop() : this.start();
}
reset() {
this.elapsed = 0;
return null;
}
update(msg) {
if (!msg || msg.type !== "stopwatch.tick" || msg.id !== this.id || msg.tag !== this.tag || !this.running) {
return [this, null];
}
this.elapsed += this.interval;
this.tag++;
return [this, this._tick()];
}
view() {
return format(this.elapsed);
}
};
function create(opts) {
return new Stopwatch(opts);
}
module.exports = { create, Stopwatch, format };
}
});
// ../../node_modules/bare-tui/components/timer.js
var require_timer = __commonJS({
"../../node_modules/bare-tui/components/timer.js"(exports, module) {
var { tick } = require_commands();
var { format } = require_stopwatch();
var nextId = 1;
var Timer = class {
constructor(opts = {}) {
this.interval = opts.interval || 1e3;
this.timeout = opts.timeout ?? 0;
this.initial = this.timeout;
this.running = false;
this.id = nextId++;
this.tag = 0;
}
get timedOut() {
return this.timeout <= 0;
}
_tick() {
const id = this.id;
const tag = this.tag;
return tick(this.interval, () => ({ type: "timer.tick", id, tag }));
}
start() {
if (this.running || this.timeout <= 0) return null;
this.running = true;
return this._tick();
}
stop() {
this.running = false;
this.tag++;
return null;
}
toggle() {
return this.running ? this.stop() : this.start();
}
reset() {
this.timeout = this.initial;
return null;
}
update(msg) {
if (!msg || msg.type !== "timer.tick" || msg.id !== this.id || msg.tag !== this.tag || !this.running) {
return [this, null];
}
this.timeout = Math.max(0, this.timeout - this.interval);
this.tag++;
if (this.timeout === 0) {
this.running = false;
const id = this.id;
return [this, () => ({ type: "timer.timeout", id })];
}
return [this, this._tick()];
}
view() {
return format(this.timeout);
}
};
function create(opts) {
return new Timer(opts);
}
module.exports = { create, Timer };
}
});
// ../../node_modules/bare-path/binding.js
var require_binding3 = __commonJS({
"../../node_modules/bare-path/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../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.validateString = function validateString(value, name) {
if (typeof value !== "string") {
throw new TypeError(
`The "${name}" argument must be of type string. Received type ${typeof value}`
);
}
};
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 binding = require_binding3();
var { normalizeString, validateString } = 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] : binding.cwd();
if (i >= 0) validateString(path, `paths[${i}]`);
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) {
validateString(path, "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) {
validateString(path, "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];
validateString(arg, "path");
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) {
validateString(from, "from");
validateString(to, "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) {
validateString(path, "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) {
if (suffix !== void 0) validateString(suffix, "suffix");
validateString(path, "path");
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) {
validateString(path, "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 binding = require_binding3();
var { normalizeString, validateString } = 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];
validateString(path, `paths[${i}]`);
if (path.length === 0) continue;
} else if (resolvedDevice.length === 0) {
path = binding.cwd();
} else {
path = binding.cwd(resolvedDevice);
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) {
validateString(path, "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) {
validateString(path, "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];
validateString(arg, "path");
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) {
validateString(from, "from");
validateString(to, "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 (typeof path !== "string" || 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) {
validateString(path, "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) {
if (suffix !== void 0) validateString(suffix, "suffix");
validateString(path, "path");
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) {
validateString(path, "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_binding4 = __commonJS({
"../../node_modules/bare-url/binding.js"(exports, module) {
module.exports = __require.addon();
}
});
// ../../node_modules/bare-url/lib/errors.js
var require_errors4 = __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 = null;
if (url) _URLSearchParams._urls.set(this, url);
if (typeof init === "string") {
this._parse(init);
} else {
this._params = /* @__PURE__ */ new Map();
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() {
let size = 0;
for (const values of this._params.values()) size += values.length;
return size;
}
// 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) {
const params = /* @__PURE__ */ new Map();
this._params = params;
const len = input.length;
let start = input.charCodeAt(0) === 63 ? 1 : 0;
while (start < len) {
let end = input.indexOf("&", start);
if (end === -1) end = len;
if (end !== start) {
let split = input.indexOf("=", start);
if (split === -1 || split > end) split = end;
const name = decode(input.slice(start, split));
const value = split === end ? "" : decode(input.slice(split + 1, end));
const list = params.get(name);
if (list === void 0) params.set(name, [value]);
else list.push(value);
}
start = end + 1;
}
}
// https://url.spec.whatwg.org/#concept-urlencoded-serializer
_serialize() {
let result = "";
let separator = "";
for (const [name, values] of this._params) {
const encoded = encode(String(name));
for (const value of values) {
result += separator + encoded + "=" + encode(String(value));
separator = "&";
}
}
return result;
}
};
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];
};
var unencoded = /^[\w*.-]*$/;
var spaced = /^[\w*. -]*$/;
var extra = /[!'()~]/;
var extraAll = /[!'()~]/g;
var escapes = {
"!": "%21",
"'": "%27",
"(": "%28",
")": "%29",
"~": "%7E"
};
var lone = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
function encode(component) {
if (unencoded.test(component)) return component;
if (spaced.test(component)) return component.replaceAll(" ", "+");
let encoded;
try {
encoded = encodeURIComponent(component);
} catch {
encoded = encodeURIComponent(component.replace(lone, "\uFFFD"));
}
if (encoded.includes("%20")) encoded = encoded.replaceAll("%20", "+");
if (extra.test(encoded)) encoded = encoded.replace(extraAll, (match) => escapes[match]);
return encoded;
}
function decode(component) {
if (component.indexOf("+") !== -1) component = component.replaceAll("+", " ");
if (component.indexOf("%") === -1) return component;
return decodeURIComponent(component);
}
}
});
// ../../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_binding4();
var errors = require_errors4();
var URLSearchParams = require_url_search_params();
var kind = Symbol.for("bare.url.kind");
var isWindows = Bare.platform === "win32";
var components = new Uint32Array(8);
var unset = 4294967295;
var reserved = isWindows ? /[%#?\n\r\t]/ : /[%#?\n\r\t\\]/;
var URL = 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._href = void 0;
this._schemeEnd = 0;
this._usernameEnd = 0;
this._hostStart = 0;
this._hostEnd = 0;
this._pathStart = 0;
this._queryStart = 0;
this._fragmentStart = 0;
this._params = null;
this._parse(input, base, opts.throw !== false);
}
get [kind]() {
return _URL[kind];
}
// https://url.spec.whatwg.org/#dom-url-href
get href() {
return this._href;
}
set href(value) {
this._update(value);
if (this._params) this._params._parse(this.search);
}
// https://url.spec.whatwg.org/#dom-url-protocol
get protocol() {
return this._slice(0, this._schemeEnd) + ":";
}
set protocol(value) {
this._update(this._replace(value.replace(/:+$/, ""), 0, this._schemeEnd));
}
// https://url.spec.whatwg.org/#dom-url-username
get username() {
return this._slice(this._schemeEnd + 3, this._usernameEnd);
}
set username(value) {
if (cannotHaveCredentialsOrPort(this)) {
return;
}
if (this.username === "") value += "@";
this._update(this._replace(value, this._schemeEnd + 3, this._usernameEnd));
}
// https://url.spec.whatwg.org/#dom-url-password
get password() {
return this._href.slice(
this._usernameEnd + 1,
this._hostStart - 1
/* @ */
);
}
set password(value) {
if (cannotHaveCredentialsOrPort(this)) {
return;
}
let start = this._usernameEnd + 1;
let end = this._hostStart - 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._hostStart, this._pathStart);
}
set host(value) {
if (hasOpaquePath(this)) {
return;
}
this._update(
this._replace(value, this._hostStart, value.includes(":") ? this._pathStart : this._hostEnd)
);
}
// https://url.spec.whatwg.org/#dom-url-hostname
get hostname() {
return this._slice(this._hostStart, this._hostEnd);
}
set hostname(value) {
if (hasOpaquePath(this)) {
return;
}
this._update(this._replace(value, this._hostStart, this._hostEnd));
}
// https://url.spec.whatwg.org/#dom-url-port
get port() {
return this._slice(this._hostEnd + 1, this._pathStart);
}
set port(value) {
if (cannotHaveCredentialsOrPort(this)) {
return;
}
let start = this._hostEnd + 1;
if (this.port === "") {
value = ":" + value;
start--;
}
this._update(this._replace(value, start, this._pathStart));
}
// https://url.spec.whatwg.org/#dom-url-pathname
get pathname() {
return this._slice(
this._pathStart,
this._queryStart - 1
/* ? */
);
}
set pathname(value) {
if (hasOpaquePath(this)) {
return;
}
if (value[0] !== "/" && value[0] !== "\\") {
value = "/" + value;
}
this._update(this._replace(
value,
this._pathStart,
this._queryStart - 1
/* ? */
));
}
// https://url.spec.whatwg.org/#dom-url-search
get search() {
return this._slice(
this._queryStart - 1,
this._fragmentStart - 1
/* # */
);
}
set search(value) {
if (value && value[0] !== "?") value = "?" + value;
this._update(
this._replace(
value,
this._queryStart - 1,
this._fragmentStart - 1
/* # */
)
);
if (this._params) this._params._parse(this.search);
}
// https://url.spec.whatwg.org/#dom-url-searchparams
get searchParams() {
if (this._params === null) {
this._params = new URLSearchParams(this.search, this);
}
return this._params;
}
// https://url.spec.whatwg.org/#dom-url-hash
get hash() {
return this._slice(
this._fragmentStart - 1
/* # */
);
}
set hash(value) {
if (value && value[0] !== "#") value = "#" + value;
this._update(this._replace(
value,
this._fragmentStart - 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) {
let href;
try {
href = binding.parse(input, base || null, components, shouldThrow);
} catch (err) {
if (err instanceof TypeError) throw err;
throw errors.INVALID_URL(`Invalid URL '${input}'`, input);
}
if (href === void 0) return;
this._href = href;
this._schemeEnd = components[0];
this._usernameEnd = components[1];
this._hostStart = components[2];
this._hostEnd = components[3];
this._pathStart = components[5];
const queryStart = components[6];
const fragmentStart = components[7];
const end = href.length + 1;
this._queryStart = queryStart === unset ? end : queryStart;
this._fragmentStart = fragmentStart === unset ? end : fragmentStart;
}
_update(input) {
try {
this._parse(input, null, true);
} catch (err) {
if (err instanceof TypeError) throw err;
}
}
};
module.exports = exports = URL;
function hasOpaquePath(url) {
return url.pathname[0] !== "/";
}
function cannotHaveCredentialsOrPort(url) {
return url.hostname === "" || url.protocol === "file:";
}
exports.URL = URL;
exports.URLSearchParams = URLSearchParams;
exports.errors = errors;
exports.isURL = function isURL(value) {
if (value instanceof URL) return true;
return typeof value === "object" && value !== null && value[kind] === URL[kind];
};
exports.isURLSearchParams = URLSearchParams.isURLSearchParams;
exports.parse = function parse(input, base) {
const url = new URL(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 URL(url);
}
if (url.protocol !== "file:") {
throw errors.INVALID_URL_SCHEME("The URL must use the file: protocol");
}
if (!isWindows && url.hostname) {
throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty");
}
const encoded = url.pathname;
const hasEncoded = encoded.includes("%");
if (hasEncoded) {
if (isWindows) {
if (/%2f|%5c/i.test(encoded)) {
throw errors.INVALID_FILE_URL_PATH(
"The file: URL path must not include encoded \\ or / characters"
);
}
} else if (/%2f/i.test(encoded)) {
throw errors.INVALID_FILE_URL_PATH("The file: URL path must not include encoded / characters");
}
if (/%00/i.test(encoded)) {
throw errors.INVALID_FILE_URL_PATH(
"The file: URL path must not include encoded NUL characters"
);
}
}
const pathname = path.normalize(hasEncoded ? decodeURIComponent(encoded) : encoded);
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 += "\\";
}
if (reserved.test(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 URL("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/bare-fs/binding.js
var require_binding5 = __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_binding5();
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_errors5 = __commonJS({
"../../node_modules/bare-fs/lib/errors.js"(exports, module) {
var binding = require_binding5();
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 binding.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);
}
async chown(uid, gid) {
await fs.fchown(this.fd, uid, gid);
}
async datasync() {
return fs.fdatasync(this.fd);
}
async sync() {
return fs.fsync(this.fd);
}
async truncate(len) {
await fs.ftruncate(this.fd, len);
}
async utimes(atime, mtime) {
await fs.futimes(this.fd, atime, mtime);
}
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.chown = fs.chown;
exports.constants = fs.constants;
exports.copyFile = fs.copyFile;
exports.cp = fs.cp;
exports.lchown = fs.lchown;
exports.lutimes = fs.lutimes;
exports.link = fs.link;
exports.lstat = fs.lstat;
exports.mkdir = fs.mkdir;
exports.mkdtemp = fs.mkdtemp;
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.statfs = fs.statfs;
exports.truncate = fs.truncate;
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_binding5();
var constants = require_constants3();
var FileError = require_errors5();
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);
req.retain(buffer);
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);
req.retain(buffers);
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);
req.retain(data);
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);
req.retain(buffers);
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 statfs(filepath, cb) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let st;
let err = null;
try {
binding.statfs(req.handle, filepath);
await req;
st = new StatFs(...binding.requestResultStatfs(req.handle));
} catch (e) {
err = new FileError(e.message, { operation: "statfs", code: e.code, path: filepath });
} finally {
req.return();
}
return done(err, st, cb);
}
function statfsSync(filepath) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.statfsSync(req.handle, filepath);
return new StatFs(...binding.requestResultStatfs(req.handle));
} catch (e) {
throw new FileError(e.message, { operation: "statfs", code: e.code, path: filepath });
} 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 truncate(filepath, len, cb) {
let fd = -1;
let err;
try {
fd = await open(filepath, "r+");
await ftruncate(fd, len);
} catch (e) {
err = e;
} finally {
if (fd !== -1) await close(fd);
}
return done(err, cb);
}
function truncateSync(filepath, len) {
let fd = -1;
let err;
try {
fd = openSync(filepath, "r+");
ftruncateSync(fd, len);
} catch (e) {
err = e;
} finally {
if (fd !== -1) closeSync(fd);
}
}
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 chown(filepath, uid, gid, cb) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.chown(req.handle, filepath, uid, gid);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "chown", code: e.code, path: filepath });
} finally {
req.return();
}
return done(err, cb);
}
function chownSync(filepath, uid, gid) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.chownSync(req.handle, filepath, uid, gid);
} catch (e) {
throw new FileError(e.message, { operation: "chownSync", code: e.code, path: filepath });
} finally {
req.return();
}
}
async function lchown(filepath, uid, gid, cb) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
let err = null;
try {
binding.lchown(req.handle, filepath, uid, gid);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "lchown", code: e.code, path: filepath });
} finally {
req.return();
}
return done(err, cb);
}
function lchownSync(filepath, uid, gid) {
filepath = toNamespacedPath(filepath);
const req = FileRequest.borrow();
try {
binding.lchownSync(req.handle, filepath, uid, gid);
} catch (e) {
throw new FileError(e.message, { operation: "lchownSync", code: e.code, path: filepath });
} finally {
req.return();
}
}
async function fchown(fd, uid, gid, cb) {
const req = FileRequest.borrow();
let err = null;
try {
binding.fchown(req.handle, fd, uid, gid);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "fchown", code: e.code, fd });
} finally {
req.return();
}
return done(err, cb);
}
function fchownSync(fd, uid, gid) {
const req = FileRequest.borrow();
try {
binding.fchownSync(req.handle, fd, uid, gid);
} catch (e) {
throw new FileError(e.message, { operation: "fchownSync", 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 lutimes(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.lutimes(req.handle, filepath, atime, mtime);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "lutimes", code: e.code, path: filepath });
} finally {
req.return();
}
return done(err, cb);
}
function lutimesSync(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.lutimesSync(req.handle, filepath, atime, mtime);
} catch (e) {
throw new FileError(e.message, { operation: "lutimes", code: e.code, path: filepath });
} finally {
req.return();
}
}
async function futimes(fd, atime, mtime, cb) {
if (typeof atime !== "number") atime = atime.getTime() / 1e3;
if (typeof mtime !== "number") mtime = mtime.getTime() / 1e3;
const req = FileRequest.borrow();
let err = null;
try {
binding.futimes(req.handle, fd, atime, mtime);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "futimes", code: e.code, fd });
} finally {
req.return();
}
return done(err, cb);
}
function futimesSync(fd, atime, mtime) {
if (typeof atime !== "number") atime = atime.getTime() / 1e3;
if (typeof mtime !== "number") mtime = mtime.getTime() / 1e3;
const req = FileRequest.borrow();
try {
binding.futimesSync(req.handle, fd, atime, mtime);
} catch (e) {
throw new FileError(e.message, { operation: "futimesSync", code: e.code, fd });
} finally {
req.return();
}
}
async function link(src, dst, cb) {
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
const req = FileRequest.borrow();
let err = null;
try {
binding.link(req.handle, src, dst);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "link", code: e.code, path: src, destination: dst });
} finally {
req.return();
}
return done(err, cb);
}
function linkSync(src, dst) {
src = toNamespacedPath(src);
dst = toNamespacedPath(dst);
const req = FileRequest.borrow();
try {
binding.linkSync(req.handle, src, dst);
} catch (e) {
throw new FileError(e.message, {
operation: "linkSync",
code: e.code,
path: src,
destination: dst
});
} 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 mkdtemp(prefix, cb) {
prefix = toNamespacedPath(prefix);
const req = FileRequest.borrow();
let res;
let err = null;
try {
binding.mkdtemp(req.handle, prefix + "XXXXXX");
await req;
res = binding.requestResultPath(req.handle);
} catch (e) {
err = new FileError(e.message, { operation: "mkdtemp", code: e.code, path: prefix });
} finally {
req.return();
}
return done(err, res, cb);
}
function mkdtempSync(prefix) {
prefix = toNamespacedPath(prefix);
const req = FileRequest.borrow();
try {
binding.mkdtempSync(req.handle, prefix + "XXXXXX");
return binding.requestResultPath(req.handle);
} catch (e) {
throw new FileError(e.message, { operation: "mkdtempSync", code: e.code, path: prefix });
} 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();
}
}
async function fsync(fd, cb) {
const req = FileRequest.borrow();
let err = null;
try {
binding.fsync(req.handle, fd);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "fsync", code: e.code, fd });
} finally {
req.return();
}
return done(err, cb);
}
function fsyncSync(fd) {
const req = FileRequest.borrow();
try {
binding.fsyncSync(req.handle, fd);
} catch (e) {
throw new FileError(e.message, { operation: "fsyncSync", code: e.code, fd });
} finally {
req.return();
}
}
async function fdatasync(fd, cb) {
const req = FileRequest.borrow();
let err = null;
try {
binding.fdatasync(req.handle, fd);
await req;
} catch (e) {
err = new FileError(e.message, { operation: "fdatasync", code: e.code, fd });
} finally {
req.return();
}
return done(err, cb);
}
function fdatasyncSync(fd) {
const req = FileRequest.borrow();
try {
binding.fdatasyncSync(req.handle, fd);
} catch (e) {
throw new FileError(e.message, { operation: "fdatasyncSync", code: e.code, fd });
} 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, recursive = false } = opts;
filepath = toNamespacedPath(filepath);
const queue = [filepath];
let result = [];
let err = null;
try {
while (queue.length !== 0) {
const dir = await opendir(queue.pop());
for await (const entry of dir) {
const entryPath = path.join(entry.parentPath, entry.name);
if (withFileTypes) {
result.push(entry);
} else {
result.push(path.relative(filepath, entryPath));
}
if (recursive && entry.isDirectory()) queue.push(entryPath);
}
}
} 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, recursive = false } = opts;
filepath = toNamespacedPath(filepath);
const queue = [filepath];
const result = [];
while (queue.length !== 0) {
const dir = opendirSync(queue.pop(), opts);
for (const entry of dir) {
const entryPath = path.join(entry.parentPath, entry.name);
if (withFileTypes) {
result.push(entry);
} else {
result.push(path.relative(filepath, entryPath));
}
if (recursive && entry.isDirectory()) queue.push(entryPath);
}
}
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 StatFs = class {
constructor(type, bsize, blocks, bfree, bavail, files, ffree, frsize) {
this.type = type;
this.bsize = bsize;
this.blocks = blocks;
this.bfree = bfree;
this.bavail = bavail;
this.files = files;
this.ffree = ffree;
this.frsize = frsize;
}
};
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.chown = chown;
exports.close = close;
exports.copyFile = copyFile;
exports.cp = cp;
exports.exists = exists;
exports.fchmod = fchmod;
exports.fchown = fchown;
exports.fdatasync = fdatasync;
exports.fstat = fstat;
exports.fsync = fsync;
exports.ftruncate = ftruncate;
exports.futimes = futimes;
exports.lchown = lchown;
exports.lutimes = lutimes;
exports.link = link;
exports.lstat = lstat;
exports.mkdir = mkdir;
exports.mkdtemp = mkdtemp;
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.statfs = statfs;
exports.symlink = symlink;
exports.truncate = truncate;
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.chownSync = chownSync;
exports.closeSync = closeSync;
exports.copyFileSync = copyFileSync;
exports.cpSync = cpSync;
exports.existsSync = existsSync;
exports.fchmodSync = fchmodSync;
exports.fchownSync = fchownSync;
exports.fdatasyncSync = fdatasyncSync;
exports.fstatSync = fstatSync;
exports.fsyncSync = fsyncSync;
exports.ftruncateSync = ftruncateSync;
exports.futimesSync = futimesSync;
exports.lchownSync = lchownSync;
exports.lutimesSync = lutimesSync;
exports.linkSync = linkSync;
exports.lstatSync = lstatSync;
exports.mkdirSync = mkdirSync;
exports.mkdtempSync = mkdtempSync;
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.statfsSync = statfsSync;
exports.symlinkSync = symlinkSync;
exports.truncateSync = truncateSync;
exports.unlinkSync = unlinkSync;
exports.utimesSync = utimesSync;
exports.writeFileSync = writeFileSync;
exports.writeSync = writeSync;
exports.writevSync = writevSync;
exports.promises = require_promises();
exports.Stats = Stats;
exports.StatFs = StatFs;
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);
}
}
});
// ../../node_modules/bare-tui/components/filepicker.js
var require_filepicker = __commonJS({
"../../node_modules/bare-tui/components/filepicker.js"(exports, module) {
var key = require_key();
var { style } = require_style();
var dirStyle = (s) => style().foreground("cyan").render(s);
var selectedStyle = (s) => style().reverse(true).render(s);
var dim = (s) => style().faint(true).render(s);
var keys = {
up: key.binding({ keys: ["up", "k"], help: { key: "\u2191/k", desc: "up" } }),
down: key.binding({ keys: ["down", "j"], help: { key: "\u2193/j", desc: "down" } }),
open: key.binding({ keys: ["enter", "right", "l"], help: { key: "\u21B5", desc: "open" } }),
descend: key.binding({ keys: ["right", "l"], help: { key: "\u2192/l", desc: "open dir" } }),
choose: key.binding({ keys: ["enter"], help: { key: "\u21B5", desc: "select" } }),
back: key.binding({ keys: ["backspace", "left", "h"], help: { key: "\u232B", desc: "up dir" } })
};
function listDir(fs, dir) {
return new Promise((resolve, reject) => {
fs.readdir(dir, { withFileTypes: true }, (err, ents) => {
if (err) return reject(err);
resolve(ents.map((e) => ({ name: e.name, directory: e.isDirectory() })));
});
});
}
function sortEntries(entries, showHidden) {
return entries.filter((e) => showHidden || !e.name.startsWith(".")).sort((a, b) => {
if (a.directory !== b.directory) return a.directory ? -1 : 1;
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
});
}
var FilePicker = class {
constructor(opts = {}) {
this.fs = opts.fs;
this.path = opts.path;
this.cwd = opts.cwd;
this.height = opts.height || 12;
this.showHidden = !!opts.showHidden;
this.pick = opts.pick === "dir" ? "dir" : "file";
this.entries = [];
this.cursor = 0;
this.offset = 0;
this.selected = null;
this.error = null;
this.loading = true;
}
init() {
return this._read(this.cwd);
}
selectedPath() {
return this.selected;
}
// A Cmd that reads `dir` and resolves to an entries (or error) Msg.
_read(dir) {
const fs = this.fs;
const showHidden = this.showHidden;
return () => listDir(fs, dir).then(
(entries) => ({
type: "filepicker.entries",
dir,
entries: sortEntries(entries, showHidden)
}),
(err) => ({
type: "filepicker.error",
dir,
error: err && err.message || String(err)
})
);
}
update(msg) {
if (!msg) return [this, null];
if (msg.type === "filepicker.entries" && msg.dir === this.cwd) {
this.entries = msg.entries;
this.cursor = 0;
this.offset = 0;
this.loading = false;
this.error = null;
return [this, null];
}
if (msg.type === "filepicker.error" && msg.dir === this.cwd) {
this.error = msg.error;
this.entries = [];
this.loading = false;
return [this, null];
}
if (msg.type === "key") return this._key(msg);
return [this, null];
}
_key(msg) {
if (key.matches(msg, keys.up)) {
this._move(-1);
return [this, null];
}
if (key.matches(msg, keys.down)) {
this._move(1);
return [this, null];
}
if (key.matches(msg, keys.back)) return this._open(this.path.dirname(this.cwd));
if (this.pick === "dir") {
const entry = this.entries[this.cursor];
if (!entry || !entry.directory) return [this, null];
const full = this.path.join(this.cwd, entry.name);
if (key.matches(msg, keys.descend)) return this._open(full);
if (key.matches(msg, keys.choose)) {
this.selected = full;
return [this, () => ({ type: "filepicker.select", path: full })];
}
return [this, null];
}
if (key.matches(msg, keys.open)) {
const entry = this.entries[this.cursor];
if (!entry) return [this, null];
const full = this.path.join(this.cwd, entry.name);
if (entry.directory) return this._open(full);
this.selected = full;
return [this, () => ({ type: "filepicker.select", path: full })];
}
return [this, null];
}
_open(dir) {
this.cwd = dir;
this.loading = true;
return [this, this._read(dir)];
}
_move(delta) {
if (!this.entries.length) return;
this.cursor = Math.max(0, Math.min(this.cursor + delta, this.entries.length - 1));
if (this.cursor < this.offset) this.offset = this.cursor;
else if (this.cursor >= this.offset + this.height) {
this.offset = this.cursor - this.height + 1;
}
}
view() {
const out = [
style().bold(true).render(this.cwd || "")
];
const rows = [];
if (this.loading) rows.push(dim(" loading\u2026"));
else if (this.error) rows.push(dim(" \u26A0 " + this.error));
else if (!this.entries.length) rows.push(dim(" (empty)"));
else {
const end = Math.min(this.offset + this.height, this.entries.length);
for (let p = this.offset; p < end; p++) {
const entry = this.entries[p];
const label = entry.directory ? entry.name + "/" : entry.name;
const text = (p === this.cursor ? "\u203A " : " ") + label;
const plain = this.pick === "dir" && !entry.directory ? dim(text) : text;
rows.push(
p === this.cursor ? selectedStyle(text) : entry.directory ? dirStyle(text) : plain
);
}
}
while (rows.length < this.height) rows.push("");
return out.concat(rows).join("\n");
}
};
function create(opts = {}) {
const fs = opts.fs || require_bare_fs();
const path = opts.path || require_bare_path();
const cwd = opts.cwd || path.resolve(".");
return new FilePicker({ ...opts, fs, path, cwd });
}
var mockPath = {
sep: "/",
join: (...parts) => parts.join("/").replace(/\/{2,}/g, "/") || "/",
dirname: (p) => {
const segs = p.replace(/\/+$/, "").split("/");
segs.pop();
const d = segs.join("/");
return d === "" ? "/" : d;
},
basename: (p) => p.replace(/\/+$/, "").split("/").pop() || "/",
resolve: (p) => p
};
function resolveNode(tree, root, p) {
if (p === root) return tree;
let rel = p;
if (root !== "/" && p.startsWith(root)) rel = p.slice(root.length);
const segs = rel.split("/").filter(Boolean);
let node = tree;
for (const s of segs) {
if (node && typeof node === "object" && s in node) node = node[s];
else return void 0;
}
return node;
}
function mock(tree, opts = {}) {
const root = opts.root || "/";
const fs = {
readdir(dir, options, cb) {
if (typeof options === "function") cb = options;
const node = resolveNode(tree, root, dir);
if (!node || typeof node !== "object") {
return cb(new Error("ENOTDIR: " + dir));
}
const ents = Object.keys(node).map((name) => {
const isDir = !!(node[name] && typeof node[name] === "object");
return { name, isDirectory: () => isDir };
});
cb(null, ents);
}
};
return { fs, path: mockPath, root };
}
module.exports = { create, FilePicker, mock };
}
});
// ../../node_modules/bare-tui/components/checkbox.js
var require_checkbox = __commonJS({
"../../node_modules/bare-tui/components/checkbox.js"(exports, module) {
var key = require_key();
var keys = {
// Space only — enter is left for the parent (e.g. submit).
toggle: key.binding({ keys: ["space"], help: { key: "space", desc: "toggle" } })
};
var Checkbox = class {
constructor(opts = {}) {
this.label = opts.label || "";
this.checked = !!opts.checked;
this.focused = !!opts.focused;
this.checkedGlyph = opts.checkedGlyph || "[x]";
this.uncheckedGlyph = opts.uncheckedGlyph || "[ ]";
}
focus() {
this.focused = true;
return this;
}
blur() {
this.focused = false;
return this;
}
setChecked(v) {
this.checked = !!v;
return this;
}
toggle() {
this.checked = !this.checked;
return this;
}
update(msg) {
if (!this.focused || !msg || msg.type !== "key") return [this, null];
if (key.matches(msg, keys.toggle)) this.toggle();
return [this, null];
}
view() {
const pointer = this.focused ? "\u203A " : " ";
const box = this.checked ? this.checkedGlyph : this.uncheckedGlyph;
return pointer + (this.label ? box + " " + this.label : box);
}
};
function create(opts) {
return new Checkbox(opts);
}
module.exports = { create, Checkbox, keys };
}
});
// ../../node_modules/bare-tui/components/radio.js
var require_radio = __commonJS({
"../../node_modules/bare-tui/components/radio.js"(exports, module) {
var key = require_key();
var keys = {
up: key.binding({ keys: ["up", "k"], help: { key: "\u2191/k", desc: "up" } }),
down: key.binding({ keys: ["down", "j"], help: { key: "\u2193/j", desc: "down" } })
};
function normalize(opt) {
if (opt !== null && typeof opt === "object") {
const value = "value" in opt ? opt.value : opt.label;
return { label: String(opt.label ?? opt.value ?? ""), value };
}
return { label: String(opt), value: opt };
}
var Radio = class {
constructor(opts = {}) {
this.options = (opts.options || []).map(normalize);
this.selected = opts.selected || 0;
this.focused = !!opts.focused;
this.onGlyph = opts.onGlyph || "(\u2022)";
this.offGlyph = opts.offGlyph || "( )";
this._clamp();
}
focus() {
this.focused = true;
return this;
}
blur() {
this.focused = false;
return this;
}
// The chosen option's value, or null when there are no options.
value() {
const o = this.options[this.selected];
return o ? o.value : null;
}
// The chosen { label, value }, or null.
selectedOption() {
return this.options[this.selected] || null;
}
setOptions(options) {
this.options = (options || []).map(normalize);
this._clamp();
return this;
}
// Select by value; no-op if the value isn't present.
setValue(v) {
const i = this.options.findIndex((o) => o.value === v);
if (i >= 0) this.selected = i;
return this;
}
update(msg) {
if (!this.focused || !msg || msg.type !== "key") return [this, null];
if (key.matches(msg, keys.up)) this._move(-1);
else if (key.matches(msg, keys.down)) this._move(1);
return [this, null];
}
_move(delta) {
if (!this.options.length) return;
this.selected = Math.max(0, Math.min(this.selected + delta, this.options.length - 1));
}
_clamp() {
if (!this.options.length) this.selected = 0;
else this.selected = Math.max(0, Math.min(this.selected, this.options.length - 1));
}
view() {
return this.options.map((o, i) => {
const chosen = i === this.selected;
const pointer = this.focused && chosen ? "\u203A " : " ";
const bullet = chosen ? this.onGlyph : this.offGlyph;
return pointer + bullet + " " + o.label;
}).join("\n");
}
};
function create(opts) {
return new Radio(opts);
}
module.exports = { create, Radio, keys };
}
});
// ../../node_modules/bare-tui/components/select.js
var require_select = __commonJS({
"../../node_modules/bare-tui/components/select.js"(exports, module) {
var key = require_key();
var ansi = require_ansi();
var { style } = require_style();
var dim = (s) => ansi.modifierDim + s + ansi.modifierReset;
var keys = {
open: key.binding({ keys: ["space"], help: { key: "space", desc: "open" } }),
up: key.binding({ keys: ["up", "k"], help: { key: "\u2191/k", desc: "up" } }),
down: key.binding({ keys: ["down", "j"], help: { key: "\u2193/j", desc: "down" } }),
commit: key.binding({ keys: ["enter", "space"], help: { key: "enter", desc: "select" } }),
cancel: key.binding({ keys: ["esc"], help: { key: "esc", desc: "cancel" } })
};
function normalize(opt) {
if (opt !== null && typeof opt === "object") {
const value = "value" in opt ? opt.value : opt.label;
return { label: String(opt.label ?? opt.value ?? ""), value };
}
return { label: String(opt), value: opt };
}
var Select = class {
constructor(opts = {}) {
this.options = (opts.options || []).map(normalize);
this.selected = opts.selected ?? -1;
this.placeholder = opts.placeholder || "select\u2026";
this.focused = !!opts.focused;
this.maxVisible = opts.maxVisible || 6;
this.openGlyph = opts.openGlyph || "\u25BE";
this.open = false;
this.highlight = 0;
this._clampSelected();
}
focus() {
this.focused = true;
return this;
}
blur() {
this.focused = false;
this.open = false;
return this;
}
// The committed value, or null when nothing is chosen.
value() {
const o = this.options[this.selected];
return o ? o.value : null;
}
selectedOption() {
return this.options[this.selected] || null;
}
setOptions(options) {
this.options = (options || []).map(normalize);
this._clampSelected();
return this;
}
// Select by value; no-op if absent.
setValue(v) {
const i = this.options.findIndex((o) => o.value === v);
if (i >= 0) this.selected = i;
return this;
}
update(msg) {
if (!this.focused || !msg || msg.type !== "key") return [this, null];
if (!this.open) {
if (key.matches(msg, keys.open) && this.options.length) {
this.open = true;
this.highlight = this.selected >= 0 ? this.selected : 0;
}
return [this, null];
}
if (key.matches(msg, keys.cancel)) this.open = false;
else if (key.matches(msg, keys.up)) this._move(-1);
else if (key.matches(msg, keys.down)) this._move(1);
else if (key.matches(msg, keys.commit)) {
this.selected = this.highlight;
this.open = false;
}
return [this, null];
}
_move(delta) {
if (!this.options.length) return;
this.highlight = Math.max(0, Math.min(this.highlight + delta, this.options.length - 1));
}
_clampSelected() {
if (this.selected < -1) this.selected = -1;
if (this.selected > this.options.length - 1) this.selected = this.options.length - 1;
}
view() {
const pointer = this.focused ? "\u203A " : " ";
const chosen = this.options[this.selected];
const label = chosen ? chosen.label : dim(this.placeholder);
return pointer + label + " " + this.openGlyph;
}
// The dropdown, or '' when closed. Highlight is drawn black-on-magenta to
// match autocomplete's menu; a footer notes options scrolled out of view.
menuView() {
if (!this.open || !this.options.length) return "";
const n = this.options.length;
const start = n > this.maxVisible ? Math.max(0, Math.min(this.highlight - this.maxVisible + 1, n - this.maxVisible)) : 0;
const shown = this.options.slice(start, start + this.maxVisible);
const rows = shown.map((o, i) => {
const isSel = start + i === this.highlight;
if (isSel) {
return style().foreground("black").background("magenta").render(" " + o.label + " ");
}
return " " + o.label;
});
if (n > shown.length) rows.push(dim(` \u2026${n - shown.length} more`));
return rows.join("\n");
}
};
function create(opts) {
return new Select(opts);
}
module.exports = { create, Select, keys };
}
});
// ../../node_modules/bare-tui/components/focus.js
var require_focus = __commonJS({
"../../node_modules/bare-tui/components/focus.js"(exports, module) {
var key = require_key();
var defaultKeys = {
next: key.binding({ keys: ["tab"], help: { key: "tab", desc: "next field" } }),
prev: key.binding({ keys: ["shift+tab"], help: { key: "shift+tab", desc: "prev field" } })
};
var Focus = class {
constructor(opts = {}) {
this.items = opts.items ? opts.items.slice() : [];
this.index = opts.index || 0;
this.keys = opts.keys || defaultKeys;
this._clamp();
this._sync();
}
// The currently focused child, or null when there are none.
focused() {
return this.items[this.index] || null;
}
setItems(items) {
this.items = items ? items.slice() : [];
this._clamp();
this._sync();
return this;
}
// Focus a specific index (clamped); blurs the rest.
focus(i) {
this.index = i;
this._clamp();
this._sync();
return this;
}
next() {
this._move(1);
return this;
}
prev() {
this._move(-1);
return this;
}
update(msg) {
if (key.matches(msg, this.keys.prev)) {
this._move(-1);
return [this, null];
}
if (key.matches(msg, this.keys.next)) {
this._move(1);
return [this, null];
}
const cur = this.items[this.index];
if (cur && typeof cur.update === "function") {
const [m, cmd] = cur.update(msg);
this.items[this.index] = m;
return [this, cmd];
}
return [this, null];
}
_move(dir) {
if (this.items.length < 2) return;
this.index = (this.index + dir + this.items.length) % this.items.length;
this._sync();
}
_clamp() {
if (!this.items.length) this.index = 0;
else this.index = Math.max(0, Math.min(this.index, this.items.length - 1));
}
// Make exactly items[index] focused; blur the rest. Guards children that
// don't implement the focus contract.
_sync() {
this.items.forEach((it, i) => {
if (!it) return;
if (i === this.index) {
if (typeof it.focus === "function") it.focus();
} else if (typeof it.blur === "function") it.blur();
});
}
};
function create(opts) {
return new Focus(opts);
}
module.exports = { create, Focus, defaultKeys };
}
});
// ../../node_modules/bare-tui/index.js
var require_bare_tui = __commonJS({
"../../node_modules/bare-tui/index.js"(exports, module) {
var Program = require_program();
var commands = require_commands();
var messages = require_messages();
var key = require_key();
var ansi = require_ansi();
var { style } = require_style();
var spinner = require_spinner();
var textinput = require_textinput();
var autocomplete = require_autocomplete();
var textarea = require_textarea();
var viewport = require_viewport();
var list = require_list();
var table = require_table();
var help = require_help();
var progress = require_progress();
var paginator = require_paginator();
var stopwatch = require_stopwatch();
var timer = require_timer();
var filepicker = require_filepicker();
var checkbox = require_checkbox();
var radio = require_radio();
var select = require_select();
var focus = require_focus();
module.exports = {
Program,
...commands,
// quit, batch, sequence, tick, every, suspend
KeyMsg: messages.KeyMsg,
key,
// key.matches(msg, ...chords | bindings), key.binding({ keys, help })
ansi,
style,
// style().bold().border(style.borders.rounded).render(...) + style.joinHorizontal/Vertical
// Components — each a composable { init?, update, view } model.
spinner,
// spinner.create({ frames, fps })
textinput,
// textinput.create({ placeholder, prompt, charLimit, echoMode })
autocomplete,
// autocomplete.create({ prompt, placeholder, suggestions, trigger }) — input + suggestion menu
textarea,
// textarea.create({ width, height, placeholder, charLimit }) — multi-line
viewport,
// viewport.create({ width, height }) — scrollable window
list,
// list.create({ items, height, width, title }) — selectable + filterable
table,
// table.create({ columns, rows, height }) — selectable scrolling rows
help,
// help.create() — renders keybinding hints; view(keymap)
progress,
// progress.create({ width, gradient }) — view(percent)
paginator,
// paginator.create({ perPage, total, type }) — page state + indicator
stopwatch,
// stopwatch.create({ interval }) — counts up; start/stop/toggle
timer,
// timer.create({ timeout, interval }) — counts down; emits timer.timeout
filepicker,
// filepicker.create({ fs, path, cwd }) — browse + pick; filepicker.mock(tree)
checkbox,
// checkbox.create({ label, checked }) — boolean toggle (space)
radio,
// radio.create({ options, selected }) — single choice; value()
select,
// select.create({ options, placeholder }) — dropdown; view() + menuView()
focus
// focus.create({ items }) — ordered focus ring across child components
};
}
});
// ../../node_modules/bare-tui-updater/theme.js
var require_theme = __commonJS({
"../../node_modules/bare-tui-updater/theme.js"(exports, module) {
var { style } = require_bare_tui();
var defaultTheme = {
accent: (s) => style().foreground("cyan").render(s),
success: (s) => style().foreground("green").render(s),
error: (s) => style().foreground("red").render(s),
hint: (s) => style().faint(true).render(s),
border: style.borders.rounded
};
function merge(user) {
return { ...defaultTheme, ...user || {} };
}
module.exports = { defaultTheme, merge };
}
});
// ../../node_modules/bare-tui-updater/updater.js
var require_updater = __commonJS({
"../../node_modules/bare-tui-updater/updater.js"(exports, module) {
var { style } = require_bare_tui();
var spinner = require_bare_tui().spinner;
var theme = require_theme();
var nextId = 1;
var Updater = class {
constructor(opts = {}) {
this.id = nextId++;
this.tag = 0;
this.width = opts.width || 60;
this.themeOverrides = theme.merge(opts.theme);
this.onAccept = opts.onAccept || null;
this.autoDismissMs = opts.autoDismissMs ?? 0;
this.acceptKey = opts.acceptKey || "u";
this.focused = opts.focused !== false;
this.mode = opts.mode || "confirm";
this.showProgress = opts.showProgress !== false;
this.dismissible = opts.dismissible !== false;
this.copy = { ...defaultCopy, ...opts.copy || {} };
this.state = "idle";
this.version = null;
this.error = null;
this.progressCount = 0;
this.progressBytesAdded = 0;
this.spinner = spinner.create({ fps: 8 });
if (this.mode === "silent" && this.onAccept) {
this._applyTimer = null;
}
}
focus() {
this.focused = true;
return this;
}
blur() {
this.focused = false;
return this;
}
visible() {
return this.state !== "idle";
}
update(msg) {
if (!msg) return [this, null];
switch (msg.type) {
case "update.downloading":
if (this.state === "applied" || this.state === "applying") return [this, null];
this.state = "downloading";
this.progressCount = 0;
this.progressBytesAdded = 0;
this.tag++;
return [this, this.spinner.init()];
case "update.progress":
if (this.state !== "downloading") return [this, null];
if (msg.delta) {
this.progressCount++;
if (msg.delta.bytesAdded) this.progressBytesAdded += msg.delta.bytesAdded;
}
return [this, null];
case "update.ready":
if (this.state === "applied" || this.state === "applying") return [this, null];
this.state = "ready";
this.version = msg.version || this.version;
this.tag++;
if (this.mode === "silent" && this.onAccept) {
return [this, this._acceptCmd()];
}
return [this, this._autoDismissCmd()];
case "update.apply":
if (this.state !== "ready") return [this, null];
this.state = "applying";
this.tag++;
return [this, this._acceptCmd()];
case "update.applied":
if (msg.runId !== this.runId) return [this, null];
this.state = "applied";
return [this, this._autoDismissCmd()];
case "update.error":
if (this.state === "applied") return [this, null];
this.state = "error";
this.error = msg.error;
this.tag++;
return [this, this._autoDismissCmd()];
case "update.dismiss":
if (!this.dismissible) return [this, null];
this.state = "idle";
this.tag++;
return [this, null];
case "update.hide":
if (msg.id === this.id && msg.tag === this.tag) this.state = "idle";
return [this, null];
case "spinner.tick": {
if (this.state !== "downloading" && this.state !== "applying") return [this, null];
const [s, cmd] = this.spinner.update(msg);
this.spinner = s;
return [this, cmd];
}
case "key":
return this._onKey(msg);
default:
return [this, null];
}
}
_onKey(msg) {
if (!this.focused) return [this, null];
const matches = (chord) => {
if (typeof msg.is === "function") return msg.is(chord);
if (msg.chord === chord) return true;
return false;
};
if (this.state === "ready" && (matches(this.acceptKey) || matches("enter"))) {
this.state = "applying";
this.tag++;
return [this, this._acceptCmd()];
}
if (this.dismissible && (this.state === "ready" || this.state === "applied" || this.state === "error") && matches("esc")) {
this.state = "idle";
this.tag++;
return [this, null];
}
return [this, null];
}
_acceptCmd() {
if (!this.onAccept) {
return () => ({ type: "update.apply" });
}
const runId = this.runId = {};
return () => Promise.resolve(this.onAccept()).then(() => ({ type: "update.applied", runId })).catch((error) => ({ type: "update.error", error, runId }));
}
_autoDismissCmd() {
if (!this.autoDismissMs) return null;
const id = this.id;
const tag = ++this.tag;
const ms = this.autoDismissMs;
return () => new Promise((resolve) => setTimeout(() => resolve({ type: "update.hide", id, tag }), ms));
}
view() {
const t = this.themeOverrides;
let text;
switch (this.state) {
case "idle":
case "disabled":
return "";
case "downloading":
text = (this.showProgress ? t.accent(this.spinner.view()) + " " : "") + "Downloading update" + (this.progressCount > 0 ? ` (${this.progressCount} file${this.progressCount === 1 ? "" : "s"})` : "\u2026");
break;
case "ready":
text = t.success("\u2713") + " Update" + (this.version ? ` v${this.version}` : "") + " ready \u2014 " + t.hint(`press ${this.acceptKey} to update, esc to dismiss`);
break;
case "applying":
text = t.accent(this.spinner.view()) + " Applying update" + (this.version ? ` v${this.version}` : "") + "\u2026";
break;
case "applied":
text = t.success("\u2713") + " Updated" + (this.version ? ` to v${this.version}` : "") + " \u2014 restart to use it";
break;
case "error":
text = t.error("\u2717") + " Update failed" + (this.error?.message ? `: ${this.error.message}` : this.error ? `: ${this.error}` : "");
break;
default:
return "";
}
return style().border(t.border).borderForeground("cyan").padding(0, 1).width(Math.max(20, this.width)).render(style.truncate(text, Math.max(20, this.width - 4)));
}
};
var defaultCopy = {
checking: "Checking for updates\u2026",
downloading: "Downloading update",
ready: "Update ready",
applying: "Applying update",
applied: "Updated",
error: "Update failed"
};
function create(opts) {
return new Updater(opts);
}
module.exports = { create, Updater, defaultCopy };
}
});
// ../../node_modules/bare-tui-updater/index.js
var require_bare_tui_updater = __commonJS({
"../../node_modules/bare-tui-updater/index.js"(exports, module) {
var { create, Updater } = require_updater();
var { defaultCopy } = require_updater();
var theme = require_theme();
module.exports = {
create,
Updater,
theme,
defaultCopy
};
}
});
// ../../bare-lib-entry-bareTuiUpdater.js
var bare_lib_entry_bareTuiUpdater_exports = {};
__export(bare_lib_entry_bareTuiUpdater_exports, {
default: () => bare_lib_entry_bareTuiUpdater_default
});
var import_bare_tui_updater = __toESM(require_bare_tui_updater());
var bare_lib_entry_bareTuiUpdater_default = import_bare_tui_updater.default;
return __toCommonJS(bare_lib_entry_bareTuiUpdater_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]["bareTuiUpdater"]=v;})();