cosense-ws-bundle
cosense/std browser websocket の self-hosted bundle(CSP回避用・自動生成・編集しない)
code:script.js
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: allname, enumerable: true }); };
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/_dnt.polyfills.js
if (Promise.withResolvers === void 0) {
Promise.withResolvers = () => {
const out = {};
out.promise = new Promise((resolve_, reject_) => {
out.resolve = resolve_;
out.reject = reject_;
});
return out;
};
}
// ../../.local/share/scrapbox-write/node_modules/engine.io-parser/build/esm/commons.js
var PACKET_TYPES = /* @__PURE__ */ Object.create(null);
var PACKET_TYPES_REVERSE = /* @__PURE__ */ Object.create(null);
Object.keys(PACKET_TYPES).forEach((key) => {
PACKET_TYPES_REVERSE[PACKET_TYPESkey] = key; });
var ERROR_PACKET = { type: "error", data: "parser error" };
// ../../.local/share/scrapbox-write/node_modules/engine.io-parser/build/esm/encodePacket.browser.js
var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "object BlobConstructor"; var withNativeArrayBuffer = typeof ArrayBuffer === "function";
var isView = (obj) => {
return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
};
var encodePacket = ({ type, data }, supportsBinary, callback) => {
if (withNativeBlob && data instanceof Blob) {
if (supportsBinary) {
return callback(data);
} else {
return encodeBlobAsBase64(data, callback);
}
} else if (withNativeArrayBuffer && (data instanceof ArrayBuffer || isView(data))) {
if (supportsBinary) {
return callback(data);
} else {
return encodeBlobAsBase64(new Blob(data), callback); }
}
return callback(PACKET_TYPEStype + (data || "")); };
var encodeBlobAsBase64 = (data, callback) => {
const fileReader = new FileReader();
fileReader.onload = function() {
const content = fileReader.result.split(",")1; callback("b" + (content || ""));
};
return fileReader.readAsDataURL(data);
};
function toArray(data) {
if (data instanceof Uint8Array) {
return data;
} else if (data instanceof ArrayBuffer) {
return new Uint8Array(data);
} else {
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
}
}
var TEXT_ENCODER;
function encodePacketToBinary(packet, callback) {
if (withNativeBlob && packet.data instanceof Blob) {
return packet.data.arrayBuffer().then(toArray).then(callback);
} else if (withNativeArrayBuffer && (packet.data instanceof ArrayBuffer || isView(packet.data))) {
return callback(toArray(packet.data));
}
encodePacket(packet, false, (encoded) => {
if (!TEXT_ENCODER) {
TEXT_ENCODER = new TextEncoder();
}
callback(TEXT_ENCODER.encode(encoded));
});
}
// ../../.local/share/scrapbox-write/node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.js
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
for (let i2 = 0; i2 < chars.length; i2++) {
}
var decode = (base64) => {
let bufferLength = base64.length * 0.75, len = base64.length, i2, p2 = 0, encoded1, encoded2, encoded3, encoded4;
bufferLength--;
bufferLength--;
}
}
const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
for (i2 = 0; i2 < len; i2 += 4) {
bytesp2++ = encoded1 << 2 | encoded2 >> 4; bytesp2++ = (encoded2 & 15) << 4 | encoded3 >> 2; bytesp2++ = (encoded3 & 3) << 6 | encoded4 & 63; }
return arraybuffer;
};
// ../../.local/share/scrapbox-write/node_modules/engine.io-parser/build/esm/decodePacket.browser.js
var withNativeArrayBuffer2 = typeof ArrayBuffer === "function";
var decodePacket = (encodedPacket, binaryType) => {
if (typeof encodedPacket !== "string") {
return {
type: "message",
data: mapBinary(encodedPacket, binaryType)
};
}
const type = encodedPacket.charAt(0);
if (type === "b") {
return {
type: "message",
data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
};
}
const packetType = PACKET_TYPES_REVERSEtype; if (!packetType) {
return ERROR_PACKET;
}
return encodedPacket.length > 1 ? {
type: PACKET_TYPES_REVERSEtype, data: encodedPacket.substring(1)
} : {
type: PACKET_TYPES_REVERSEtype };
};
var decodeBase64Packet = (data, binaryType) => {
if (withNativeArrayBuffer2) {
const decoded = decode(data);
return mapBinary(decoded, binaryType);
} else {
return { base64: true, data };
}
};
var mapBinary = (data, binaryType) => {
switch (binaryType) {
case "blob":
if (data instanceof Blob) {
return data;
} else {
}
case "arraybuffer":
default:
if (data instanceof ArrayBuffer) {
return data;
} else {
return data.buffer;
}
}
};
// ../../.local/share/scrapbox-write/node_modules/engine.io-parser/build/esm/index.js
var SEPARATOR = String.fromCharCode(30);
var encodePayload = (packets, callback) => {
const length = packets.length;
const encodedPackets = new Array(length);
let count = 0;
packets.forEach((packet, i2) => {
encodePacket(packet, false, (encodedPacket) => {
encodedPacketsi2 = encodedPacket; if (++count === length) {
callback(encodedPackets.join(SEPARATOR));
}
});
});
};
var decodePayload = (encodedPayload, binaryType) => {
const encodedPackets = encodedPayload.split(SEPARATOR);
const packets = [];
for (let i2 = 0; i2 < encodedPackets.length; i2++) {
const decodedPacket = decodePacket(encodedPacketsi2, binaryType); packets.push(decodedPacket);
if (decodedPacket.type === "error") {
break;
}
}
return packets;
};
function createPacketEncoderStream() {
return new TransformStream({
transform(packet, controller) {
encodePacketToBinary(packet, (encodedPacket) => {
const payloadLength = encodedPacket.length;
let header;
if (payloadLength < 126) {
header = new Uint8Array(1);
new DataView(header.buffer).setUint8(0, payloadLength);
} else if (payloadLength < 65536) {
header = new Uint8Array(3);
const view = new DataView(header.buffer);
view.setUint8(0, 126);
view.setUint16(1, payloadLength);
} else {
header = new Uint8Array(9);
const view = new DataView(header.buffer);
view.setUint8(0, 127);
view.setBigUint64(1, BigInt(payloadLength));
}
if (packet.data && typeof packet.data !== "string") {
}
controller.enqueue(header);
controller.enqueue(encodedPacket);
});
}
});
}
var TEXT_DECODER;
function totalLength(chunks) {
return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
}
function concatChunks(chunks, size) {
if (chunks0.length === size) { return chunks.shift();
}
const buffer = new Uint8Array(size);
let j2 = 0;
for (let i2 = 0; i2 < size; i2++) {
if (j2 === chunks0.length) { chunks.shift();
j2 = 0;
}
}
if (chunks.length && j2 < chunks0.length) { chunks0 = chunks0.slice(j2); }
return buffer;
}
function createPacketDecoderStream(maxPayload, binaryType) {
if (!TEXT_DECODER) {
TEXT_DECODER = new TextDecoder();
}
const chunks = [];
let state = 0;
let expectedLength = -1;
let isBinary2 = false;
return new TransformStream({
transform(chunk, controller) {
chunks.push(chunk);
while (true) {
if (state === 0) {
if (totalLength(chunks) < 1) {
break;
}
const header = concatChunks(chunks, 1);
isBinary2 = (header0 & 128) === 128; expectedLength = header0 & 127; if (expectedLength < 126) {
state = 3;
} else if (expectedLength === 126) {
state = 1;
} else {
state = 2;
}
} else if (state === 1) {
if (totalLength(chunks) < 2) {
break;
}
const headerArray = concatChunks(chunks, 2);
expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
state = 3;
} else if (state === 2) {
if (totalLength(chunks) < 8) {
break;
}
const headerArray = concatChunks(chunks, 8);
const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
const n2 = view.getUint32(0);
if (n2 > Math.pow(2, 53 - 32) - 1) {
controller.enqueue(ERROR_PACKET);
break;
}
expectedLength = n2 * Math.pow(2, 32) + view.getUint32(4);
state = 3;
} else {
if (totalLength(chunks) < expectedLength) {
break;
}
const data = concatChunks(chunks, expectedLength);
controller.enqueue(decodePacket(isBinary2 ? data : TEXT_DECODER.decode(data), binaryType));
state = 0;
}
if (expectedLength === 0 || expectedLength > maxPayload) {
controller.enqueue(ERROR_PACKET);
break;
}
}
}
});
}
var protocol = 4;
// ../../.local/share/scrapbox-write/node_modules/@socket.io/component-emitter/lib/esm/index.js
function Emitter(obj) {
if (obj) return mixin(obj);
}
function mixin(obj) {
for (var key in Emitter.prototype) {
objkey = Emitter.prototypekey; }
return obj;
}
Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn) {
this._callbacks = this._callbacks || {};
return this;
};
Emitter.prototype.once = function(event, fn) {
function on2() {
this.off(event, on2);
fn.apply(this, arguments);
}
on2.fn = fn;
this.on(event, on2);
return this;
};
Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn) {
this._callbacks = this._callbacks || {};
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
if (!callbacks) return this;
if (1 == arguments.length) {
return this;
}
var cb;
for (var i2 = 0; i2 < callbacks.length; i2++) {
if (cb === fn || cb.fn === fn) {
callbacks.splice(i2, 1);
break;
}
}
if (callbacks.length === 0) {
}
return this;
};
Emitter.prototype.emit = function(event) {
this._callbacks = this._callbacks || {};
var args = new Array(arguments.length - 1), callbacks = this._callbacks"$" + event; for (var i2 = 1; i2 < arguments.length; i2++) {
}
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i2 = 0, len = callbacks.length; i2 < len; ++i2) {
callbacksi2.apply(this, args); }
}
return this;
};
Emitter.prototype.emitReserved = Emitter.prototype.emit;
Emitter.prototype.listeners = function(event) {
this._callbacks = this._callbacks || {};
};
Emitter.prototype.hasListeners = function(event) {
return !!this.listeners(event).length;
};
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/globals.js
var nextTick = (() => {
const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
if (isPromiseAvailable) {
return (cb) => Promise.resolve().then(cb);
} else {
return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
}
})();
var globalThisShim = (() => {
if (typeof self !== "undefined") {
return self;
} else if (typeof window !== "undefined") {
return window;
} else {
return Function("return this")();
}
})();
var defaultBinaryType = "arraybuffer";
function createCookieJar() {
}
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/util.js
function pick(obj, ...attr) {
return attr.reduce((acc, k2) => {
if (obj.hasOwnProperty(k2)) {
}
return acc;
}, {});
}
var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
function installTimerFunctions(obj, opts) {
if (opts.useNativeTimers) {
obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
} else {
obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
}
}
var BASE64_OVERHEAD = 1.33;
function byteLength(obj) {
if (typeof obj === "string") {
return utf8Length(obj);
}
return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
}
function utf8Length(str) {
let c2 = 0, length = 0;
for (let i2 = 0, l2 = str.length; i2 < l2; i2++) {
c2 = str.charCodeAt(i2);
if (c2 < 128) {
length += 1;
} else if (c2 < 2048) {
length += 2;
} else if (c2 < 55296 || c2 >= 57344) {
length += 3;
} else {
i2++;
length += 4;
}
}
return length;
}
function randomString() {
return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
}
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/contrib/parseqs.js
function encode(obj) {
let str = "";
for (let i2 in obj) {
if (obj.hasOwnProperty(i2)) {
if (str.length)
str += "&";
str += encodeURIComponent(i2) + "=" + encodeURIComponent(obji2); }
}
return str;
}
function decode2(qs) {
let qry = {};
let pairs = qs.split("&");
for (let i2 = 0, l2 = pairs.length; i2 < l2; i2++) {
let pair = pairsi2.split("="); qry[decodeURIComponent(pair0)] = decodeURIComponent(pair1); }
return qry;
}
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/transport.js
var TransportError = class extends Error {
constructor(reason, description, context) {
super(reason);
this.description = description;
this.context = context;
this.type = "TransportError";
}
};
var Transport = class extends Emitter {
/**
* Transport abstract constructor.
*
* @param {Object} opts - options
* @protected
*/
constructor(opts) {
super();
this.writable = false;
installTimerFunctions(this, opts);
this.opts = opts;
this.query = opts.query;
this.socket = opts.socket;
this.supportsBinary = !opts.forceBase64;
}
/**
* Emits an error.
*
* @param {String} reason
* @param description
* @param context - the error context
* @return {Transport} for chaining
* @protected
*/
onError(reason, description, context) {
super.emitReserved("error", new TransportError(reason, description, context));
return this;
}
/**
* Opens the transport.
*/
open() {
this.readyState = "opening";
this.doOpen();
return this;
}
/**
* Closes the transport.
*/
close() {
if (this.readyState === "opening" || this.readyState === "open") {
this.doClose();
this.onClose();
}
return this;
}
/**
* Sends multiple packets.
*
* @param {Array} packets
*/
send(packets) {
if (this.readyState === "open") {
this.write(packets);
} else {
}
}
/**
* Called upon open
*
* @protected
*/
onOpen() {
this.readyState = "open";
this.writable = true;
super.emitReserved("open");
}
/**
* Called with data.
*
* @param {String} data
* @protected
*/
onData(data) {
const packet = decodePacket(data, this.socket.binaryType);
this.onPacket(packet);
}
/**
* Called with a decoded packet.
*
* @protected
*/
onPacket(packet) {
super.emitReserved("packet", packet);
}
/**
* Called upon close.
*
* @protected
*/
onClose(details) {
this.readyState = "closed";
super.emitReserved("close", details);
}
/**
* Pauses the transport, in order not to lose packets during an upgrade.
*
* @param onPause
*/
pause(onPause) {
}
createUri(schema, query = {}) {
return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
}
_hostname() {
const hostname = this.opts.hostname;
return hostname.indexOf(":") === -1 ? hostname : "+ hostname + "";
}
_port() {
if (this.opts.port && (this.opts.secure && Number(this.opts.port) !== 443 || !this.opts.secure && Number(this.opts.port) !== 80)) {
return ":" + this.opts.port;
} else {
return "";
}
}
_query(query) {
const encodedQuery = encode(query);
return encodedQuery.length ? "?" + encodedQuery : "";
}
};
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/transports/polling.js
var Polling = class extends Transport {
constructor() {
super(...arguments);
this._polling = false;
}
get name() {
return "polling";
}
/**
* Opens the socket (triggers polling). We write a PING message to determine
* when the transport is open.
*
* @protected
*/
doOpen() {
this._poll();
}
/**
* Pauses polling.
*
* @param {Function} onPause - callback upon buffers are flushed and transport is paused
* @package
*/
pause(onPause) {
this.readyState = "pausing";
const pause = () => {
this.readyState = "paused";
onPause();
};
if (this._polling || !this.writable) {
let total = 0;
if (this._polling) {
total++;
this.once("pollComplete", function() {
--total || pause();
});
}
if (!this.writable) {
total++;
this.once("drain", function() {
--total || pause();
});
}
} else {
pause();
}
}
/**
* Starts polling cycle.
*
* @private
*/
_poll() {
this._polling = true;
this.doPoll();
this.emitReserved("poll");
}
/**
* Overloads onData to detect payloads.
*
* @protected
*/
onData(data) {
const callback = (packet) => {
if ("opening" === this.readyState && packet.type === "open") {
this.onOpen();
}
if ("close" === packet.type) {
this.onClose({ description: "transport closed by the server" });
return false;
}
this.onPacket(packet);
};
decodePayload(data, this.socket.binaryType).forEach(callback);
if ("closed" !== this.readyState) {
this._polling = false;
this.emitReserved("pollComplete");
if ("open" === this.readyState) {
this._poll();
} else {
}
}
}
/**
* For polling, send a close packet.
*
* @protected
*/
doClose() {
const close = () => {
this.write(type: "close" });
};
if ("open" === this.readyState) {
close();
} else {
this.once("open", close);
}
}
/**
* Writes a packets payload.
*
* @param {Array} packets - data packets
* @protected
*/
write(packets) {
this.writable = false;
encodePayload(packets, (data) => {
this.doWrite(data, () => {
this.writable = true;
this.emitReserved("drain");
});
});
}
/**
* Generates uri for connection.
*
* @private
*/
uri() {
const schema = this.opts.secure ? "https" : "http";
const query = this.query || {};
if (false !== this.opts.timestampRequests) {
}
if (!this.supportsBinary && !query.sid) {
query.b64 = 1;
}
return this.createUri(schema, query);
}
};
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/contrib/has-cors.js
var value = false;
try {
value = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest();
} catch (err) {
}
var hasCORS = value;
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/transports/polling-xhr.js
function empty() {
}
var BaseXHR = class extends Polling {
/**
* XHR Polling constructor.
*
* @param {Object} opts
* @package
*/
constructor(opts) {
super(opts);
if (typeof location !== "undefined") {
const isSSL = "https:" === location.protocol;
let port = location.port;
if (!port) {
port = isSSL ? "443" : "80";
}
this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
}
}
/**
* Sends data.
*
* @param {String} data to send.
* @param {Function} called upon flush.
* @private
*/
doWrite(data, fn) {
const req = this.request({
method: "POST",
data
});
req.on("success", fn);
req.on("error", (xhrStatus, context) => {
this.onError("xhr post error", xhrStatus, context);
});
}
/**
* Starts a poll cycle.
*
* @private
*/
doPoll() {
const req = this.request();
req.on("data", this.onData.bind(this));
req.on("error", (xhrStatus, context) => {
this.onError("xhr poll error", xhrStatus, context);
});
this.pollXhr = req;
}
};
var Request2 = class _Request extends Emitter {
/**
* Request constructor
*
* @param {Object} options
* @package
*/
constructor(createRequest, uri, opts) {
super();
this.createRequest = createRequest;
installTimerFunctions(this, opts);
this._opts = opts;
this._method = opts.method || "GET";
this._uri = uri;
this._data = void 0 !== opts.data ? opts.data : null;
this._create();
}
/**
* Creates the XHR object and sends the request.
*
* @private
*/
_create() {
var _a;
const opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
opts.xdomain = !!this._opts.xd;
const xhr = this._xhr = this.createRequest(opts);
try {
xhr.open(this._method, this._uri, true);
try {
if (this._opts.extraHeaders) {
xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
for (let i2 in this._opts.extraHeaders) {
if (this._opts.extraHeaders.hasOwnProperty(i2)) {
xhr.setRequestHeader(i2, this._opts.extraHeadersi2); }
}
}
} catch (e2) {
}
if ("POST" === this._method) {
try {
xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
} catch (e2) {
}
}
try {
xhr.setRequestHeader("Accept", "*/*");
} catch (e2) {
}
(_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
if ("withCredentials" in xhr) {
xhr.withCredentials = this._opts.withCredentials;
}
if (this._opts.requestTimeout) {
xhr.timeout = this._opts.requestTimeout;
}
xhr.onreadystatechange = () => {
var _a2;
if (xhr.readyState === 3) {
(_a2 = this._opts.cookieJar) === null || _a2 === void 0 ? void 0 : _a2.parseCookies(
// @ts-ignore
xhr.getResponseHeader("set-cookie")
);
}
if (4 !== xhr.readyState)
return;
if (200 === xhr.status || 1223 === xhr.status) {
this._onLoad();
} else {
this.setTimeoutFn(() => {
this._onError(typeof xhr.status === "number" ? xhr.status : 0);
}, 0);
}
};
xhr.send(this._data);
} catch (e2) {
this.setTimeoutFn(() => {
this._onError(e2);
}, 0);
return;
}
if (typeof document !== "undefined") {
this._index = _Request.requestsCount++;
}
}
/**
* Called upon error.
*
* @private
*/
_onError(err) {
this.emitReserved("error", err, this._xhr);
this._cleanup(true);
}
/**
* Cleans up house.
*
* @private
*/
_cleanup(fromError) {
if ("undefined" === typeof this._xhr || null === this._xhr) {
return;
}
this._xhr.onreadystatechange = empty;
if (fromError) {
try {
this._xhr.abort();
} catch (e2) {
}
}
if (typeof document !== "undefined") {
}
this._xhr = null;
}
/**
* Called upon load.
*
* @private
*/
_onLoad() {
const data = this._xhr.responseText;
if (data !== null) {
this.emitReserved("data", data);
this.emitReserved("success");
this._cleanup();
}
}
/**
* Aborts the request.
*
* @package
*/
abort() {
this._cleanup();
}
};
Request2.requestsCount = 0;
Request2.requests = {};
if (typeof document !== "undefined") {
if (typeof attachEvent === "function") {
attachEvent("onunload", unloadHandler);
} else if (typeof addEventListener === "function") {
const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
addEventListener(terminationEvent, unloadHandler, false);
}
}
function unloadHandler() {
for (let i2 in Request2.requests) {
if (Request2.requests.hasOwnProperty(i2)) {
Request2.requestsi2.abort(); }
}
}
var hasXHR2 = (function() {
const xhr = newRequest({
xdomain: false
});
return xhr && xhr.responseType !== null;
})();
var XHR = class extends BaseXHR {
constructor(opts) {
super(opts);
const forceBase64 = opts && opts.forceBase64;
this.supportsBinary = hasXHR2 && !forceBase64;
}
request(opts = {}) {
Object.assign(opts, { xd: this.xd }, this.opts);
return new Request2(newRequest, this.uri(), opts);
}
};
function newRequest(opts) {
const xdomain = opts.xdomain;
try {
if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
return new XMLHttpRequest();
}
} catch (e2) {
}
if (!xdomain) {
try {
return new globalThisShim["Active".concat("Object").join("X")]("Microsoft.XMLHTTP"); } catch (e2) {
}
}
}
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/transports/websocket.js
var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
var BaseWS = class extends Transport {
get name() {
return "websocket";
}
doOpen() {
const uri = this.uri();
const protocols = this.opts.protocols;
const opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
if (this.opts.extraHeaders) {
opts.headers = this.opts.extraHeaders;
}
try {
this.ws = this.createSocket(uri, protocols, opts);
} catch (err) {
return this.emitReserved("error", err);
}
this.ws.binaryType = this.socket.binaryType;
this.addEventListeners();
}
/**
* Adds event listeners to the socket
*
* @private
*/
addEventListeners() {
this.ws.onopen = () => {
if (this.opts.autoUnref) {
this.ws._socket.unref();
}
this.onOpen();
};
this.ws.onclose = (closeEvent) => this.onClose({
description: "websocket connection closed",
context: closeEvent
});
this.ws.onmessage = (ev) => this.onData(ev.data);
this.ws.onerror = (e2) => this.onError("websocket error", e2);
}
write(packets) {
this.writable = false;
for (let i2 = 0; i2 < packets.length; i2++) {
const packet = packetsi2; const lastPacket = i2 === packets.length - 1;
encodePacket(packet, this.supportsBinary, (data) => {
try {
this.doWrite(packet, data);
} catch (e2) {
}
if (lastPacket) {
nextTick(() => {
this.writable = true;
this.emitReserved("drain");
}, this.setTimeoutFn);
}
});
}
}
doClose() {
if (typeof this.ws !== "undefined") {
this.ws.onerror = () => {
};
this.ws.close();
this.ws = null;
}
}
/**
* Generates uri for connection.
*
* @private
*/
uri() {
const schema = this.opts.secure ? "wss" : "ws";
const query = this.query || {};
if (this.opts.timestampRequests) {
}
if (!this.supportsBinary) {
query.b64 = 1;
}
return this.createUri(schema, query);
}
};
var WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
var WS = class extends BaseWS {
createSocket(uri, protocols, opts) {
return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
}
doWrite(_packet, data) {
this.ws.send(data);
}
};
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/transports/webtransport.js
var WT = class extends Transport {
get name() {
return "webtransport";
}
doOpen() {
try {
this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptionsthis.name); } catch (err) {
return this.emitReserved("error", err);
}
this._transport.closed.then(() => {
this.onClose();
}).catch((err) => {
this.onError("webtransport error", err);
});
this._transport.ready.then(() => {
this._transport.createBidirectionalStream().then((stream) => {
const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
const reader = stream.readable.pipeThrough(decoderStream).getReader();
const encoderStream = createPacketEncoderStream();
encoderStream.readable.pipeTo(stream.writable);
this._writer = encoderStream.writable.getWriter();
const read = () => {
reader.read().then(({ done, value: value2 }) => {
if (done) {
return;
}
this.onPacket(value2);
read();
}).catch((err) => {
});
};
read();
const packet = { type: "open" };
if (this.query.sid) {
packet.data = {"sid":"${this.query.sid}"};
}
this._writer.write(packet).then(() => this.onOpen());
});
});
}
write(packets) {
this.writable = false;
for (let i2 = 0; i2 < packets.length; i2++) {
const packet = packetsi2; const lastPacket = i2 === packets.length - 1;
this._writer.write(packet).then(() => {
if (lastPacket) {
nextTick(() => {
this.writable = true;
this.emitReserved("drain");
}, this.setTimeoutFn);
}
});
}
}
doClose() {
var _a;
(_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
}
};
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/transports/index.js
var transports = {
websocket: WS,
webtransport: WT,
polling: XHR
};
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/contrib/parseuri.js
var parts = [
"source",
"protocol",
"authority",
"userInfo",
"user",
"password",
"host",
"port",
"relative",
"path",
"directory",
"file",
"query",
"anchor"
];
function parse(str) {
if (str.length > 8e3) {
throw "URI too long";
}
const src = str, b2 = str.indexOf("e2 = str.indexOf("");
if (b2 != -1 && e2 != -1) {
str = str.substring(0, b2) + str.substring(b2, e2).replace(/:/g, ";") + str.substring(e2, str.length);
}
let m2 = re.exec(str || ""), uri = {}, i2 = 14;
while (i2--) {
uri[partsi2] = m2i2 || ""; }
if (b2 != -1 && e2 != -1) {
uri.source = src;
uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ":");
uri.authority = uri.authority.replace(""").replace("", "").replace(/;/g, ":");
uri.ipv6uri = true;
}
uri.pathNames = pathNames(uri, uri"path"); uri.queryKey = queryKey(uri, uri"query"); return uri;
}
function pathNames(obj, path) {
const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
if (path.slice(0, 1) == "/" || path.length === 0) {
names.splice(0, 1);
}
if (path.slice(-1) == "/") {
names.splice(names.length - 1, 1);
}
return names;
}
function queryKey(uri, query) {
const data = {};
query.replace(/(?:^|&)(^&=*)=?(^&*)/g, function($0, $1, $2) { if ($1) {
}
});
return data;
}
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/socket.js
var withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
var OFFLINE_EVENT_LISTENERS = [];
if (withEventListeners) {
addEventListener("offline", () => {
OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
}, false);
}
var SocketWithoutUpgrade = class _SocketWithoutUpgrade extends Emitter {
/**
* Socket constructor.
*
* @param {String|Object} uri - uri or options
* @param {Object} opts - options
*/
constructor(uri, opts) {
super();
this.binaryType = defaultBinaryType;
this.writeBuffer = [];
this._prevBufferLen = 0;
this._pingInterval = -1;
this._pingTimeout = -1;
this._maxPayload = -1;
this._pingTimeoutTime = Infinity;
if (uri && "object" === typeof uri) {
opts = uri;
uri = null;
}
if (uri) {
const parsedUri = parse(uri);
opts.hostname = parsedUri.host;
opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
opts.port = parsedUri.port;
if (parsedUri.query)
opts.query = parsedUri.query;
} else if (opts.host) {
opts.hostname = parse(opts.host).host;
}
installTimerFunctions(this, opts);
this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
if (opts.hostname && !opts.port) {
opts.port = this.secure ? "443" : "80";
}
this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : this.secure ? "443" : "80");
this.transports = [];
this._transportsByName = {};
opts.transports.forEach((t2) => {
const transportName = t2.prototype.name;
this.transports.push(transportName);
});
this.opts = Object.assign({
path: "/engine.io",
agent: false,
withCredentials: false,
upgrade: true,
timestampParam: "t",
rememberUpgrade: false,
addTrailingSlash: true,
rejectUnauthorized: true,
perMessageDeflate: {
threshold: 1024
},
transportOptions: {},
closeOnBeforeunload: false
}, opts);
this.opts.path = this.opts.path.replace(/\/$/, "") + (this.opts.addTrailingSlash ? "/" : "");
if (typeof this.opts.query === "string") {
this.opts.query = decode2(this.opts.query);
}
if (withEventListeners) {
if (this.opts.closeOnBeforeunload) {
this._beforeunloadEventListener = () => {
if (this.transport) {
this.transport.removeAllListeners();
this.transport.close();
}
};
addEventListener("beforeunload", this._beforeunloadEventListener, false);
}
if (this.hostname !== "localhost") {
this._offlineEventListener = () => {
this._onClose("transport close", {
description: "network connection lost"
});
};
OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
}
}
if (this.opts.withCredentials) {
this._cookieJar = createCookieJar();
}
this._open();
}
/**
* Creates transport of the given type.
*
* @param {String} name - transport name
* @return {Transport}
* @private
*/
createTransport(name) {
const query = Object.assign({}, this.opts.query);
query.EIO = protocol;
query.transport = name;
if (this.id)
query.sid = this.id;
const opts = Object.assign({}, this.opts, {
query,
socket: this,
hostname: this.hostname,
secure: this.secure,
port: this.port
}, this.opts.transportOptionsname); return new this._transportsByNamename(opts); }
/**
* Initializes transport to use and starts probe.
*
* @private
*/
_open() {
if (this.transports.length === 0) {
this.setTimeoutFn(() => {
this.emitReserved("error", "No transports available");
}, 0);
return;
}
const transportName = this.opts.rememberUpgrade && _SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports0; this.readyState = "opening";
const transport = this.createTransport(transportName);
transport.open();
this.setTransport(transport);
}
/**
* Sets the current transport. Disables the existing one (if any).
*
* @private
*/
setTransport(transport) {
if (this.transport) {
this.transport.removeAllListeners();
}
this.transport = transport;
transport.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", (reason) => this._onClose("transport close", reason));
}
/**
* Called when connection is deemed open.
*
* @private
*/
onOpen() {
this.readyState = "open";
_SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
this.emitReserved("open");
this.flush();
}
/**
* Handles a packet.
*
* @private
*/
_onPacket(packet) {
if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
this.emitReserved("packet", packet);
this.emitReserved("heartbeat");
switch (packet.type) {
case "open":
this.onHandshake(JSON.parse(packet.data));
break;
case "ping":
this._sendPacket("pong");
this.emitReserved("ping");
this.emitReserved("pong");
this._resetPingTimeout();
break;
case "error":
const err = new Error("server error");
err.code = packet.data;
this._onError(err);
break;
case "message":
this.emitReserved("data", packet.data);
this.emitReserved("message", packet.data);
break;
}
} else {
}
}
/**
* Called upon handshake completion.
*
* @param {Object} data - handshake obj
* @private
*/
onHandshake(data) {
this.emitReserved("handshake", data);
this.id = data.sid;
this.transport.query.sid = data.sid;
this._pingInterval = data.pingInterval;
this._pingTimeout = data.pingTimeout;
this._maxPayload = data.maxPayload;
this.onOpen();
if ("closed" === this.readyState)
return;
this._resetPingTimeout();
}
/**
* Sets and resets ping timeout timer based on server pings.
*
* @private
*/
_resetPingTimeout() {
this.clearTimeoutFn(this._pingTimeoutTimer);
const delay2 = this._pingInterval + this._pingTimeout;
this._pingTimeoutTime = Date.now() + delay2;
this._pingTimeoutTimer = this.setTimeoutFn(() => {
this._onClose("ping timeout");
}, delay2);
if (this.opts.autoUnref) {
this._pingTimeoutTimer.unref();
}
}
/**
* Called on drain event
*
* @private
*/
_onDrain() {
this.writeBuffer.splice(0, this._prevBufferLen);
this._prevBufferLen = 0;
if (0 === this.writeBuffer.length) {
this.emitReserved("drain");
} else {
this.flush();
}
}
/**
* Flush write buffers.
*
* @private
*/
flush() {
if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
const packets = this._getWritablePackets();
this.transport.send(packets);
this._prevBufferLen = packets.length;
this.emitReserved("flush");
}
}
/**
* Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
* long-polling)
*
* @private
*/
_getWritablePackets() {
const shouldCheckPayloadSize = this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
if (!shouldCheckPayloadSize) {
return this.writeBuffer;
}
let payloadSize = 1;
for (let i2 = 0; i2 < this.writeBuffer.length; i2++) {
const data = this.writeBufferi2.data; if (data) {
payloadSize += byteLength(data);
}
if (i2 > 0 && payloadSize > this._maxPayload) {
return this.writeBuffer.slice(0, i2);
}
payloadSize += 2;
}
return this.writeBuffer;
}
/**
* Checks whether the heartbeat timer has expired but the socket has not yet been notified.
*
* Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
* write() method then the message would not be buffered by the Socket.IO client.
*
* @return {boolean}
* @private
*/
/* private */
_hasPingExpired() {
if (!this._pingTimeoutTime)
return true;
const hasExpired = Date.now() > this._pingTimeoutTime;
if (hasExpired) {
this._pingTimeoutTime = 0;
nextTick(() => {
this._onClose("ping timeout");
}, this.setTimeoutFn);
}
return hasExpired;
}
/**
* Sends a message.
*
* @param {String} msg - message.
* @param {Object} options.
* @param {Function} fn - callback function.
* @return {Socket} for chaining.
*/
write(msg, options, fn) {
this._sendPacket("message", msg, options, fn);
return this;
}
/**
* Sends a message. Alias of {@link Socket#write}.
*
* @param {String} msg - message.
* @param {Object} options.
* @param {Function} fn - callback function.
* @return {Socket} for chaining.
*/
send(msg, options, fn) {
this._sendPacket("message", msg, options, fn);
return this;
}
/**
* Sends a packet.
*
* @param {String} type: packet type.
* @param {String} data.
* @param {Object} options.
* @param {Function} fn - callback function.
* @private
*/
_sendPacket(type, data, options, fn) {
if ("function" === typeof data) {
fn = data;
data = void 0;
}
if ("function" === typeof options) {
fn = options;
options = null;
}
if ("closing" === this.readyState || "closed" === this.readyState) {
return;
}
options = options || {};
options.compress = false !== options.compress;
const packet = {
type,
data,
options
};
this.emitReserved("packetCreate", packet);
this.writeBuffer.push(packet);
if (fn)
this.once("flush", fn);
this.flush();
}
/**
* Closes the connection.
*/
close() {
const close = () => {
this._onClose("forced close");
this.transport.close();
};
const cleanupAndClose = () => {
this.off("upgrade", cleanupAndClose);
this.off("upgradeError", cleanupAndClose);
close();
};
const waitForUpgrade = () => {
this.once("upgrade", cleanupAndClose);
this.once("upgradeError", cleanupAndClose);
};
if ("opening" === this.readyState || "open" === this.readyState) {
this.readyState = "closing";
if (this.writeBuffer.length) {
this.once("drain", () => {
if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
});
} else if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
}
return this;
}
/**
* Called upon transport error
*
* @private
*/
_onError(err) {
_SocketWithoutUpgrade.priorWebsocketSuccess = false;
if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
this.transports.shift();
return this._open();
}
this.emitReserved("error", err);
this._onClose("transport error", err);
}
/**
* Called upon transport close.
*
* @private
*/
_onClose(reason, description) {
if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
this.clearTimeoutFn(this._pingTimeoutTimer);
this.transport.removeAllListeners("close");
this.transport.close();
this.transport.removeAllListeners();
if (withEventListeners) {
if (this._beforeunloadEventListener) {
removeEventListener("beforeunload", this._beforeunloadEventListener, false);
}
if (this._offlineEventListener) {
const i2 = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
if (i2 !== -1) {
OFFLINE_EVENT_LISTENERS.splice(i2, 1);
}
}
}
this.readyState = "closed";
this.id = null;
this.emitReserved("close", reason, description);
this.writeBuffer = [];
this._prevBufferLen = 0;
}
}
};
SocketWithoutUpgrade.protocol = protocol;
var SocketWithUpgrade = class extends SocketWithoutUpgrade {
constructor() {
super(...arguments);
this._upgrades = [];
}
onOpen() {
super.onOpen();
if ("open" === this.readyState && this.opts.upgrade) {
for (let i2 = 0; i2 < this._upgrades.length; i2++) {
this._probe(this._upgradesi2); }
}
}
/**
* Probes a transport.
*
* @param {String} name - transport name
* @private
*/
_probe(name) {
let transport = this.createTransport(name);
let failed = false;
SocketWithoutUpgrade.priorWebsocketSuccess = false;
const onTransportOpen = () => {
if (failed)
return;
transport.send(type: "ping", data: "probe" });
transport.once("packet", (msg) => {
if (failed)
return;
if ("pong" === msg.type && "probe" === msg.data) {
this.upgrading = true;
this.emitReserved("upgrading", transport);
if (!transport)
return;
SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
this.transport.pause(() => {
if (failed)
return;
if ("closed" === this.readyState)
return;
cleanup();
this.setTransport(transport);
transport.send(type: "upgrade" });
this.emitReserved("upgrade", transport);
transport = null;
this.upgrading = false;
this.flush();
});
} else {
const err = new Error("probe error");
err.transport = transport.name;
this.emitReserved("upgradeError", err);
}
});
};
function freezeTransport() {
if (failed)
return;
failed = true;
cleanup();
transport.close();
transport = null;
}
const onerror = (err) => {
const error = new Error("probe error: " + err);
error.transport = transport.name;
freezeTransport();
this.emitReserved("upgradeError", error);
};
function onTransportClose() {
onerror("transport closed");
}
function onclose() {
onerror("socket closed");
}
function onupgrade(to) {
if (transport && to.name !== transport.name) {
freezeTransport();
}
}
const cleanup = () => {
transport.removeListener("open", onTransportOpen);
transport.removeListener("error", onerror);
transport.removeListener("close", onTransportClose);
this.off("close", onclose);
this.off("upgrading", onupgrade);
};
transport.once("open", onTransportOpen);
transport.once("error", onerror);
transport.once("close", onTransportClose);
this.once("close", onclose);
this.once("upgrading", onupgrade);
if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
this.setTimeoutFn(() => {
if (!failed) {
transport.open();
}
}, 200);
} else {
transport.open();
}
}
onHandshake(data) {
this._upgrades = this._filterUpgrades(data.upgrades);
super.onHandshake(data);
}
/**
* Filters upgrades, returning only those matching client transports.
*
* @param {Array} upgrades - server upgrades
* @private
*/
_filterUpgrades(upgrades) {
const filteredUpgrades = [];
for (let i2 = 0; i2 < upgrades.length; i2++) {
if (~this.transports.indexOf(upgradesi2)) filteredUpgrades.push(upgradesi2); }
return filteredUpgrades;
}
};
var Socket = class extends SocketWithUpgrade {
constructor(uri, opts = {}) {
const o2 = typeof uri === "object" ? uri : opts;
if (!o2.transports || o2.transports && typeof o2.transports0 === "string") { }
super(uri, o2);
}
};
// ../../.local/share/scrapbox-write/node_modules/engine.io-client/build/esm/index.js
var protocol2 = Socket.protocol;
// ../../.local/share/scrapbox-write/node_modules/socket.io-client/build/esm/url.js
function url(uri, path = "", loc) {
let obj = uri;
loc = loc || typeof location !== "undefined" && location;
if (null == uri)
uri = loc.protocol + "//" + loc.host;
if (typeof uri === "string") {
if ("/" === uri.charAt(0)) {
if ("/" === uri.charAt(1)) {
uri = loc.protocol + uri;
} else {
uri = loc.host + uri;
}
}
if (!/^(https?|wss?):\/\//.test(uri)) {
if ("undefined" !== typeof loc) {
uri = loc.protocol + "//" + uri;
} else {
}
}
obj = parse(uri);
}
if (!obj.port) {
if (/^(http|ws)$/.test(obj.protocol)) {
obj.port = "80";
} else if (/^(http|ws)s$/.test(obj.protocol)) {
obj.port = "443";
}
}
obj.path = obj.path || "/";
const ipv6 = obj.host.indexOf(":") !== -1;
const host = ipv6 ? "+ obj.host + "" : obj.host;
obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
return obj;
}
// ../../.local/share/scrapbox-write/node_modules/socket.io-parser/build/esm/index.js
var esm_exports = {};
__export(esm_exports, {
Decoder: () => Decoder,
Encoder: () => Encoder,
PacketType: () => PacketType,
isPacketValid: () => isPacketValid,
protocol: () => protocol3
});
// ../../.local/share/scrapbox-write/node_modules/socket.io-parser/build/esm/is-binary.js
var withNativeArrayBuffer3 = typeof ArrayBuffer === "function";
var isView2 = (obj) => {
return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
};
var toString = Object.prototype.toString;
var withNativeBlob2 = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "object BlobConstructor"; var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "object FileConstructor"; function isBinary(obj) {
return withNativeArrayBuffer3 && (obj instanceof ArrayBuffer || isView2(obj)) || withNativeBlob2 && obj instanceof Blob || withNativeFile && obj instanceof File;
}
function hasBinary(obj, toJSON) {
if (!obj || typeof obj !== "object") {
return false;
}
if (Array.isArray(obj)) {
for (let i2 = 0, l2 = obj.length; i2 < l2; i2++) {
return true;
}
}
return false;
}
if (isBinary(obj)) {
return true;
}
if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
return hasBinary(obj.toJSON(), true);
}
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(objkey)) { return true;
}
}
return false;
}
// ../../.local/share/scrapbox-write/node_modules/socket.io-parser/build/esm/binary.js
function deconstructPacket(packet) {
const buffers = [];
const packetData = packet.data;
const pack = packet;
pack.data = _deconstructPacket(packetData, buffers);
pack.attachments = buffers.length;
return { packet: pack, buffers };
}
function _deconstructPacket(data, buffers) {
if (!data)
return data;
if (isBinary(data)) {
const placeholder = { _placeholder: true, num: buffers.length };
buffers.push(data);
return placeholder;
} else if (Array.isArray(data)) {
const newData = new Array(data.length);
for (let i2 = 0; i2 < data.length; i2++) {
newDatai2 = _deconstructPacket(datai2, buffers); }
return newData;
} else if (typeof data === "object" && !(data instanceof Date)) {
const newData = {};
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
newDatakey = _deconstructPacket(datakey, buffers); }
}
return newData;
}
return data;
}
function reconstructPacket(packet, buffers) {
packet.data = _reconstructPacket(packet.data, buffers);
delete packet.attachments;
return packet;
}
function _reconstructPacket(data, buffers) {
if (!data)
return data;
if (data && data._placeholder === true) {
const isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
if (isIndexValid) {
} else {
throw new Error("illegal attachments");
}
} else if (Array.isArray(data)) {
for (let i2 = 0; i2 < data.length; i2++) {
datai2 = _reconstructPacket(datai2, buffers); }
} else if (typeof data === "object") {
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
datakey = _reconstructPacket(datakey, buffers); }
}
}
return data;
}
// ../../.local/share/scrapbox-write/node_modules/socket.io-parser/build/esm/index.js
var RESERVED_EVENTS = [
"connect",
// used on the client side
"connect_error",
// used on the client side
"disconnect",
// used on both sides
"disconnecting",
// used on the server side
"newListener",
// used by the Node.js EventEmitter
"removeListener"
// used by the Node.js EventEmitter
];
var protocol3 = 5;
var PacketType;
(function(PacketType2) {
PacketType2[PacketType2"CONNECT" = 0] = "CONNECT"; PacketType2[PacketType2"EVENT" = 2] = "EVENT"; PacketType2[PacketType2"ACK" = 3] = "ACK"; })(PacketType || (PacketType = {}));
var Encoder = class {
/**
* Encoder constructor
*
* @param {function} replacer - custom replacer to pass down to JSON.parse
*/
constructor(replacer) {
this.replacer = replacer;
}
/**
* Encode a packet as a single string if non-binary, or as a
* buffer sequence, depending on packet type.
*
* @param {Object} obj - packet object
*/
encode(obj) {
if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
if (hasBinary(obj)) {
return this.encodeAsBinary({
type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
nsp: obj.nsp,
data: obj.data,
id: obj.id
});
}
}
}
/**
* Encode packet as string.
*/
encodeAsString(obj) {
let str = "" + obj.type;
if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
str += obj.attachments + "-";
}
if (obj.nsp && "/" !== obj.nsp) {
str += obj.nsp + ",";
}
if (null != obj.id) {
str += obj.id;
}
if (null != obj.data) {
str += JSON.stringify(obj.data, this.replacer);
}
return str;
}
/**
* Encode packet as 'buffer sequence' by removing blobs, and
* deconstructing packet into object with placeholders and
* a list of buffers.
*/
encodeAsBinary(obj) {
const deconstruction = deconstructPacket(obj);
const pack = this.encodeAsString(deconstruction.packet);
const buffers = deconstruction.buffers;
buffers.unshift(pack);
return buffers;
}
};
var Decoder = class _Decoder extends Emitter {
/**
* Decoder constructor
*
* @param {function} reviver - custom reviver to pass down to JSON.stringify
*/
constructor(reviver) {
super();
this.reviver = reviver;
}
/**
* Decodes an encoded packet string into packet JSON.
*
* @param {String} obj - encoded packet
*/
add(obj) {
let packet;
if (typeof obj === "string") {
if (this.reconstructor) {
throw new Error("got plaintext data when reconstructing a packet");
}
packet = this.decodeString(obj);
const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
this.reconstructor = new BinaryReconstructor(packet);
if (packet.attachments === 0) {
super.emitReserved("decoded", packet);
}
} else {
super.emitReserved("decoded", packet);
}
} else if (isBinary(obj) || obj.base64) {
if (!this.reconstructor) {
throw new Error("got binary data when not reconstructing a packet");
} else {
packet = this.reconstructor.takeBinaryData(obj);
if (packet) {
this.reconstructor = null;
super.emitReserved("decoded", packet);
}
}
} else {
throw new Error("Unknown type: " + obj);
}
}
/**
* Decode a packet String (JSON data)
*
* @param {String} str
* @return {Object} packet
*/
decodeString(str) {
let i2 = 0;
const p2 = {
type: Number(str.charAt(0))
};
if (PacketTypep2.type === void 0) { throw new Error("unknown packet type " + p2.type);
}
if (p2.type === PacketType.BINARY_EVENT || p2.type === PacketType.BINARY_ACK) {
const start = i2 + 1;
while (str.charAt(++i2) !== "-" && i2 != str.length) {
}
const buf = str.substring(start, i2);
if (buf != Number(buf) || str.charAt(i2) !== "-") {
throw new Error("Illegal attachments");
}
p2.attachments = Number(buf);
}
if ("/" === str.charAt(i2 + 1)) {
const start = i2 + 1;
while (++i2) {
const c2 = str.charAt(i2);
if ("," === c2)
break;
if (i2 === str.length)
break;
}
p2.nsp = str.substring(start, i2);
} else {
p2.nsp = "/";
}
const next = str.charAt(i2 + 1);
if ("" !== next && Number(next) == next) {
const start = i2 + 1;
while (++i2) {
const c2 = str.charAt(i2);
if (null == c2 || Number(c2) != c2) {
--i2;
break;
}
if (i2 === str.length)
break;
}
p2.id = Number(str.substring(start, i2 + 1));
}
if (str.charAt(++i2)) {
const payload = this.tryParse(str.substr(i2));
if (_Decoder.isPayloadValid(p2.type, payload)) {
p2.data = payload;
} else {
throw new Error("invalid payload");
}
}
return p2;
}
tryParse(str) {
try {
return JSON.parse(str, this.reviver);
} catch (e2) {
return false;
}
}
static isPayloadValid(type, payload) {
switch (type) {
case PacketType.CONNECT:
return isObject(payload);
case PacketType.DISCONNECT:
return payload === void 0;
case PacketType.CONNECT_ERROR:
return typeof payload === "string" || isObject(payload);
case PacketType.EVENT:
case PacketType.BINARY_EVENT:
return Array.isArray(payload) && (typeof payload0 === "number" || typeof payload0 === "string" && RESERVED_EVENTS.indexOf(payload0) === -1); case PacketType.ACK:
case PacketType.BINARY_ACK:
return Array.isArray(payload);
}
}
/**
* Deallocates a parser's resources
*/
destroy() {
if (this.reconstructor) {
this.reconstructor.finishedReconstruction();
this.reconstructor = null;
}
}
};
var BinaryReconstructor = class {
constructor(packet) {
this.packet = packet;
this.buffers = [];
this.reconPack = packet;
}
/**
* Method to be called when binary data received from connection
* after a BINARY_EVENT packet.
*
* @param {Buffer | ArrayBuffer} binData - the raw binary data received
* @return {null | Object} returns null if more binary data is expected or
* a reconstructed packet object if all buffers have been received.
*/
takeBinaryData(binData) {
this.buffers.push(binData);
if (this.buffers.length === this.reconPack.attachments) {
const packet = reconstructPacket(this.reconPack, this.buffers);
this.finishedReconstruction();
return packet;
}
return null;
}
/**
* Cleans up binary packet reconstruction variables.
*/
finishedReconstruction() {
this.reconPack = null;
this.buffers = [];
}
};
function isNamespaceValid(nsp) {
return typeof nsp === "string";
}
var isInteger = Number.isInteger || function(value2) {
return typeof value2 === "number" && isFinite(value2) && Math.floor(value2) === value2;
};
function isAckIdValid(id) {
return id === void 0 || isInteger(id);
}
function isObject(value2) {
return Object.prototype.toString.call(value2) === "object Object"; }
function isDataValid(type, payload) {
switch (type) {
case PacketType.CONNECT:
return payload === void 0 || isObject(payload);
case PacketType.DISCONNECT:
return payload === void 0;
case PacketType.EVENT:
return Array.isArray(payload) && (typeof payload0 === "number" || typeof payload0 === "string" && RESERVED_EVENTS.indexOf(payload0) === -1); case PacketType.ACK:
return Array.isArray(payload);
case PacketType.CONNECT_ERROR:
return typeof payload === "string" || isObject(payload);
default:
return false;
}
}
function isPacketValid(packet) {
return isNamespaceValid(packet.nsp) && isAckIdValid(packet.id) && isDataValid(packet.type, packet.data);
}
// ../../.local/share/scrapbox-write/node_modules/socket.io-client/build/esm/on.js
function on(obj, ev, fn) {
obj.on(ev, fn);
return function subDestroy() {
obj.off(ev, fn);
};
}
// ../../.local/share/scrapbox-write/node_modules/socket.io-client/build/esm/socket.js
var RESERVED_EVENTS2 = Object.freeze({
connect: 1,
connect_error: 1,
disconnect: 1,
disconnecting: 1,
newListener: 1,
removeListener: 1
});
var Socket2 = class extends Emitter {
/**
* Socket constructor.
*/
constructor(io, nsp, opts) {
super();
this.connected = false;
this.recovered = false;
this.receiveBuffer = [];
this.sendBuffer = [];
this._queue = [];
this._queueSeq = 0;
this.ids = 0;
this.acks = {};
this.flags = {};
this.io = io;
this.nsp = nsp;
if (opts && opts.auth) {
this.auth = opts.auth;
}
this._opts = Object.assign({}, opts);
if (this.io._autoConnect)
this.open();
}
/**
* Whether the socket is currently disconnected
*
* @example
* const socket = io();
*
* socket.on("connect", () => {
* console.log(socket.disconnected); // false
* });
*
* socket.on("disconnect", () => {
* console.log(socket.disconnected); // true
* });
*/
get disconnected() {
return !this.connected;
}
/**
* Subscribe to open, close and packet events
*
* @private
*/
subEvents() {
if (this.subs)
return;
const io = this.io;
this.subs = [
on(io, "open", this.onopen.bind(this)),
on(io, "packet", this.onpacket.bind(this)),
on(io, "error", this.onerror.bind(this)),
on(io, "close", this.onclose.bind(this))
];
}
/**
* Whether the Socket will try to reconnect when its Manager connects or reconnects.
*
* @example
* const socket = io();
*
* console.log(socket.active); // true
*
* socket.on("disconnect", (reason) => {
* if (reason === "io server disconnect") {
* // the disconnection was initiated by the server, you need to manually reconnect
* console.log(socket.active); // false
* }
* // else the socket will automatically try to reconnect
* console.log(socket.active); // true
* });
*/
get active() {
return !!this.subs;
}
/**
* "Opens" the socket.
*
* @example
* const socket = io({
* autoConnect: false
* });
*
* socket.connect();
*/
connect() {
if (this.connected)
return this;
this.subEvents();
this.io.open();
if ("open" === this.io._readyState)
this.onopen();
return this;
}
/**
* Alias for {@link connect()}.
*/
open() {
return this.connect();
}
/**
* Sends a message event.
*
* This method mimics the WebSocket.send() method.
*
*
* @example
* socket.send("hello");
*
* // this is equivalent to
* socket.emit("message", "hello");
*
* @return self
*/
send(...args) {
args.unshift("message");
this.emit.apply(this, args);
return this;
}
/**
* Override emit.
* If the event is in events, it's emitted normally.
*
* @example
* socket.emit("hello", "world");
*
* // all serializable datastructures are supported (no need to call JSON.stringify)
* socket.emit("hello", 1, "2", { 3: "4", 5: Uint8Array.from(6) }); *
* // with an acknowledgement from the server
* socket.emit("hello", "world", (val) => {
* // ...
* });
*
* @return self
*/
emit(ev, ...args) {
var _a, _b, _c;
if (RESERVED_EVENTS2.hasOwnProperty(ev)) {
throw new Error('"' + ev.toString() + '" is a reserved event name');
}
args.unshift(ev);
if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
this._addToQueue(args);
return this;
}
const packet = {
type: PacketType.EVENT,
data: args
};
packet.options = {};
packet.options.compress = this.flags.compress !== false;
const id = this.ids++;
const ack = args.pop();
this._registerAckCallback(id, ack);
packet.id = id;
}
const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
const discardPacket = this.flags.volatile && !isTransportWritable;
if (discardPacket) {
} else if (isConnected) {
this.notifyOutgoingListeners(packet);
this.packet(packet);
} else {
this.sendBuffer.push(packet);
}
this.flags = {};
return this;
}
/**
* @private
*/
_registerAckCallback(id, ack) {
var _a;
const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
if (timeout === void 0) {
return;
}
const timer = this.io.setTimeoutFn(() => {
for (let i2 = 0; i2 < this.sendBuffer.length; i2++) {
if (this.sendBufferi2.id === id) { this.sendBuffer.splice(i2, 1);
}
}
ack.call(this, new Error("operation has timed out"));
}, timeout);
const fn = (...args) => {
this.io.clearTimeoutFn(timer);
ack.apply(this, args);
};
fn.withError = true;
}
/**
* Emits an event and waits for an acknowledgement
*
* @example
* // without timeout
* const response = await socket.emitWithAck("hello", "world");
*
* // with a specific timeout
* try {
* const response = await socket.timeout(1000).emitWithAck("hello", "world");
* } catch (err) {
* // the server did not acknowledge the event in the given delay
* }
*
* @return a Promise that will be fulfilled when the server acknowledges the event
*/
emitWithAck(ev, ...args) {
return new Promise((resolve, reject) => {
const fn = (arg1, arg2) => {
return arg1 ? reject(arg1) : resolve(arg2);
};
fn.withError = true;
args.push(fn);
this.emit(ev, ...args);
});
}
/**
* Add the packet to the queue.
* @param args
* @private
*/
_addToQueue(args) {
let ack;
ack = args.pop();
}
const packet = {
id: this._queueSeq++,
tryCount: 0,
pending: false,
args,
flags: Object.assign({ fromQueue: true }, this.flags)
};
args.push((err, ...responseArgs) => {
if (packet !== this._queue0) { }
const hasError = err !== null;
if (hasError) {
if (packet.tryCount > this._opts.retries) {
this._queue.shift();
if (ack) {
ack(err);
}
}
} else {
this._queue.shift();
if (ack) {
ack(null, ...responseArgs);
}
}
packet.pending = false;
return this._drainQueue();
});
this._queue.push(packet);
this._drainQueue();
}
/**
* Send the first packet of the queue, and wait for an acknowledgement from the server.
* @param force - whether to resend a packet that has not been acknowledged yet
*
* @private
*/
_drainQueue(force = false) {
if (!this.connected || this._queue.length === 0) {
return;
}
const packet = this._queue0; if (packet.pending && !force) {
return;
}
packet.pending = true;
packet.tryCount++;
this.flags = packet.flags;
this.emit.apply(this, packet.args);
}
/**
* Sends a packet.
*
* @param packet
* @private
*/
packet(packet) {
packet.nsp = this.nsp;
this.io._packet(packet);
}
/**
* Called upon engine open.
*
* @private
*/
onopen() {
if (typeof this.auth == "function") {
this.auth((data) => {
this._sendConnectPacket(data);
});
} else {
this._sendConnectPacket(this.auth);
}
}
/**
* Sends a CONNECT packet to initiate the Socket.IO session.
*
* @param data
* @private
*/
_sendConnectPacket(data) {
this.packet({
type: PacketType.CONNECT,
data: this._pid ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data) : data
});
}
/**
* Called upon engine or manager error.
*
* @param err
* @private
*/
onerror(err) {
if (!this.connected) {
this.emitReserved("connect_error", err);
}
}
/**
* Called upon engine close.
*
* @param reason
* @param description
* @private
*/
onclose(reason, description) {
this.connected = false;
delete this.id;
this.emitReserved("disconnect", reason, description);
this._clearAcks();
}
/**
* Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
* the server.
*
* @private
*/
_clearAcks() {
Object.keys(this.acks).forEach((id) => {
const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
if (!isBuffered) {
if (ack.withError) {
ack.call(this, new Error("socket has been disconnected"));
}
}
});
}
/**
* Called with socket packet.
*
* @param packet
* @private
*/
onpacket(packet) {
const sameNamespace = packet.nsp === this.nsp;
if (!sameNamespace)
return;
switch (packet.type) {
case PacketType.CONNECT:
if (packet.data && packet.data.sid) {
this.onconnect(packet.data.sid, packet.data.pid);
} else {
}
break;
case PacketType.EVENT:
case PacketType.BINARY_EVENT:
this.onevent(packet);
break;
case PacketType.ACK:
case PacketType.BINARY_ACK:
this.onack(packet);
break;
case PacketType.DISCONNECT:
this.ondisconnect();
break;
case PacketType.CONNECT_ERROR:
this.destroy();
const err = new Error(packet.data.message);
err.data = packet.data.data;
this.emitReserved("connect_error", err);
break;
}
}
/**
* Called upon a server event.
*
* @param packet
* @private
*/
onevent(packet) {
const args = packet.data || [];
if (null != packet.id) {
args.push(this.ack(packet.id));
}
if (this.connected) {
this.emitEvent(args);
} else {
this.receiveBuffer.push(Object.freeze(args));
}
}
emitEvent(args) {
if (this._anyListeners && this._anyListeners.length) {
const listeners = this._anyListeners.slice();
for (const listener of listeners) {
listener.apply(this, args);
}
}
super.emit.apply(this, args);
}
}
/**
* Produces an ack callback to emit with an event.
*
* @private
*/
ack(id) {
const self2 = this;
let sent = false;
return function(...args) {
if (sent)
return;
sent = true;
self2.packet({
type: PacketType.ACK,
id,
data: args
});
};
}
/**
* Called upon a server acknowledgement.
*
* @param packet
* @private
*/
onack(packet) {
if (typeof ack !== "function") {
return;
}
if (ack.withError) {
packet.data.unshift(null);
}
ack.apply(this, packet.data);
}
/**
* Called upon server connect.
*
* @private
*/
onconnect(id, pid) {
this.id = id;
this.recovered = pid && this._pid === pid;
this._pid = pid;
this.connected = true;
this.emitBuffered();
this._drainQueue(true);
this.emitReserved("connect");
}
/**
* Emit buffered events (received and emitted).
*
* @private
*/
emitBuffered() {
this.receiveBuffer.forEach((args) => this.emitEvent(args));
this.receiveBuffer = [];
this.sendBuffer.forEach((packet) => {
this.notifyOutgoingListeners(packet);
this.packet(packet);
});
this.sendBuffer = [];
}
/**
* Called upon server disconnect.
*
* @private
*/
ondisconnect() {
this.destroy();
this.onclose("io server disconnect");
}
/**
* Called upon forced client/server side disconnections,
* this method ensures the manager stops tracking us and
* that reconnections don't get triggered for this.
*
* @private
*/
destroy() {
if (this.subs) {
this.subs.forEach((subDestroy) => subDestroy());
this.subs = void 0;
}
}
/**
* Disconnects the socket manually. In that case, the socket will not try to reconnect.
*
* If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
*
* @example
* const socket = io();
*
* socket.on("disconnect", (reason) => {
* // console.log(reason); prints "io client disconnect"
* });
*
* socket.disconnect();
*
* @return self
*/
disconnect() {
if (this.connected) {
this.packet({ type: PacketType.DISCONNECT });
}
this.destroy();
if (this.connected) {
this.onclose("io client disconnect");
}
return this;
}
/**
* Alias for {@link disconnect()}.
*
* @return self
*/
close() {
return this.disconnect();
}
/**
* Sets the compress flag.
*
* @example
* socket.compress(false).emit("hello");
*
* @param compress - if true, compresses the sending data
* @return self
*/
compress(compress) {
this.flags.compress = compress;
return this;
}
/**
* Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
* ready to send messages.
*
* @example
* socket.volatile.emit("hello"); // the server may or may not receive it
*
* @returns self
*/
get volatile() {
this.flags.volatile = true;
return this;
}
/**
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
* given number of milliseconds have elapsed without an acknowledgement from the server:
*
* @example
* socket.timeout(5000).emit("my-event", (err) => {
* if (err) {
* // the server did not acknowledge the event in the given delay
* }
* });
*
* @returns self
*/
timeout(timeout) {
this.flags.timeout = timeout;
return this;
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
*
* @example
* socket.onAny((event, ...args) => {
* console.log(got ${event});
* });
*
* @param listener
*/
onAny(listener) {
this._anyListeners = this._anyListeners || [];
this._anyListeners.push(listener);
return this;
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* @example
* socket.prependAny((event, ...args) => {
* console.log(got event ${event});
* });
*
* @param listener
*/
prependAny(listener) {
this._anyListeners = this._anyListeners || [];
this._anyListeners.unshift(listener);
return this;
}
/**
* Removes the listener that will be fired when any event is emitted.
*
* @example
* const catchAllListener = (event, ...args) => {
* console.log(got event ${event});
* }
*
* socket.onAny(catchAllListener);
*
* // remove a specific listener
* socket.offAny(catchAllListener);
*
* // or remove all listeners
* socket.offAny();
*
* @param listener
*/
offAny(listener) {
if (!this._anyListeners) {
return this;
}
if (listener) {
const listeners = this._anyListeners;
for (let i2 = 0; i2 < listeners.length; i2++) {
if (listener === listenersi2) { listeners.splice(i2, 1);
return this;
}
}
} else {
this._anyListeners = [];
}
return this;
}
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*/
listenersAny() {
return this._anyListeners || [];
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
*
* Note: acknowledgements sent to the server are not included.
*
* @example
* socket.onAnyOutgoing((event, ...args) => {
* console.log(sent event ${event});
* });
*
* @param listener
*/
onAnyOutgoing(listener) {
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
this._anyOutgoingListeners.push(listener);
return this;
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* Note: acknowledgements sent to the server are not included.
*
* @example
* socket.prependAnyOutgoing((event, ...args) => {
* console.log(sent event ${event});
* });
*
* @param listener
*/
prependAnyOutgoing(listener) {
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
this._anyOutgoingListeners.unshift(listener);
return this;
}
/**
* Removes the listener that will be fired when any event is emitted.
*
* @example
* const catchAllListener = (event, ...args) => {
* console.log(sent event ${event});
* }
*
* socket.onAnyOutgoing(catchAllListener);
*
* // remove a specific listener
* socket.offAnyOutgoing(catchAllListener);
*
* // or remove all listeners
* socket.offAnyOutgoing();
*
* @param listener - the catch-all listener (optional) */
offAnyOutgoing(listener) {
if (!this._anyOutgoingListeners) {
return this;
}
if (listener) {
const listeners = this._anyOutgoingListeners;
for (let i2 = 0; i2 < listeners.length; i2++) {
if (listener === listenersi2) { listeners.splice(i2, 1);
return this;
}
}
} else {
this._anyOutgoingListeners = [];
}
return this;
}
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*/
listenersAnyOutgoing() {
return this._anyOutgoingListeners || [];
}
/**
* Notify the listeners for each packet sent
*
* @param packet
*
* @private
*/
notifyOutgoingListeners(packet) {
if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
const listeners = this._anyOutgoingListeners.slice();
for (const listener of listeners) {
listener.apply(this, packet.data);
}
}
}
};
// ../../.local/share/scrapbox-write/node_modules/socket.io-client/build/esm/contrib/backo2.js
function Backoff(opts) {
opts = opts || {};
this.ms = opts.min || 100;
this.max = opts.max || 1e4;
this.factor = opts.factor || 2;
this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
this.attempts = 0;
}
Backoff.prototype.duration = function() {
var ms = this.ms * Math.pow(this.factor, this.attempts++);
if (this.jitter) {
var rand = Math.random();
var deviation = Math.floor(rand * this.jitter * ms);
ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
}
return Math.min(ms, this.max) | 0;
};
Backoff.prototype.reset = function() {
this.attempts = 0;
};
Backoff.prototype.setMin = function(min) {
this.ms = min;
};
Backoff.prototype.setMax = function(max) {
this.max = max;
};
Backoff.prototype.setJitter = function(jitter) {
this.jitter = jitter;
};
// ../../.local/share/scrapbox-write/node_modules/socket.io-client/build/esm/manager.js
var Manager = class extends Emitter {
constructor(uri, opts) {
var _a;
super();
this.nsps = {};
this.subs = [];
if (uri && "object" === typeof uri) {
opts = uri;
uri = void 0;
}
opts = opts || {};
opts.path = opts.path || "/socket.io";
this.opts = opts;
installTimerFunctions(this, opts);
this.reconnection(opts.reconnection !== false);
this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
this.reconnectionDelay(opts.reconnectionDelay || 1e3);
this.reconnectionDelayMax(opts.reconnectionDelayMax || 5e3);
this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
this.backoff = new Backoff({
min: this.reconnectionDelay(),
max: this.reconnectionDelayMax(),
jitter: this.randomizationFactor()
});
this.timeout(null == opts.timeout ? 2e4 : opts.timeout);
this._readyState = "closed";
this.uri = uri;
const _parser = opts.parser || esm_exports;
this.encoder = new _parser.Encoder();
this.decoder = new _parser.Decoder();
this._autoConnect = opts.autoConnect !== false;
if (this._autoConnect)
this.open();
}
reconnection(v2) {
if (!arguments.length)
return this._reconnection;
this._reconnection = !!v2;
if (!v2) {
this.skipReconnect = true;
}
return this;
}
reconnectionAttempts(v2) {
if (v2 === void 0)
return this._reconnectionAttempts;
this._reconnectionAttempts = v2;
return this;
}
reconnectionDelay(v2) {
var _a;
if (v2 === void 0)
return this._reconnectionDelay;
this._reconnectionDelay = v2;
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v2);
return this;
}
randomizationFactor(v2) {
var _a;
if (v2 === void 0)
return this._randomizationFactor;
this._randomizationFactor = v2;
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v2);
return this;
}
reconnectionDelayMax(v2) {
var _a;
if (v2 === void 0)
return this._reconnectionDelayMax;
this._reconnectionDelayMax = v2;
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v2);
return this;
}
timeout(v2) {
if (!arguments.length)
return this._timeout;
this._timeout = v2;
return this;
}
/**
* Starts trying to reconnect if reconnection is enabled and we have not
* started reconnecting yet
*
* @private
*/
maybeReconnectOnOpen() {
if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
this.reconnect();
}
}
/**
* Sets the current transport socket.
*
* @param {Function} fn - optional, callback
* @return self
* @public
*/
open(fn) {
if (~this._readyState.indexOf("open"))
return this;
this.engine = new Socket(this.uri, this.opts);
const socket = this.engine;
const self2 = this;
this._readyState = "opening";
this.skipReconnect = false;
const openSubDestroy = on(socket, "open", function() {
self2.onopen();
fn && fn();
});
const onError = (err) => {
this.cleanup();
this._readyState = "closed";
this.emitReserved("error", err);
if (fn) {
fn(err);
} else {
this.maybeReconnectOnOpen();
}
};
const errorSub = on(socket, "error", onError);
if (false !== this._timeout) {
const timeout = this._timeout;
const timer = this.setTimeoutFn(() => {
openSubDestroy();
onError(new Error("timeout"));
socket.close();
}, timeout);
if (this.opts.autoUnref) {
timer.unref();
}
this.subs.push(() => {
this.clearTimeoutFn(timer);
});
}
this.subs.push(openSubDestroy);
this.subs.push(errorSub);
return this;
}
/**
* Alias for open()
*
* @return self
* @public
*/
connect(fn) {
return this.open(fn);
}
/**
* Called upon transport open.
*
* @private
*/
onopen() {
this.cleanup();
this._readyState = "open";
this.emitReserved("open");
const socket = this.engine;
this.subs.push(
on(socket, "ping", this.onping.bind(this)),
on(socket, "data", this.ondata.bind(this)),
on(socket, "error", this.onerror.bind(this)),
on(socket, "close", this.onclose.bind(this)),
// @ts-ignore
on(this.decoder, "decoded", this.ondecoded.bind(this))
);
}
/**
* Called upon a ping.
*
* @private
*/
onping() {
this.emitReserved("ping");
}
/**
* Called with data.
*
* @private
*/
ondata(data) {
try {
this.decoder.add(data);
} catch (e2) {
this.onclose("parse error", e2);
}
}
/**
* Called when parser fully decodes a packet.
*
* @private
*/
ondecoded(packet) {
nextTick(() => {
this.emitReserved("packet", packet);
}, this.setTimeoutFn);
}
/**
* Called upon socket error.
*
* @private
*/
onerror(err) {
this.emitReserved("error", err);
}
/**
* Creates a new socket for the given nsp.
*
* @return {Socket}
* @public
*/
socket(nsp, opts) {
let socket = this.nspsnsp; if (!socket) {
socket = new Socket2(this, nsp, opts);
} else if (this._autoConnect && !socket.active) {
socket.connect();
}
return socket;
}
/**
* Called upon a socket close.
*
* @param socket
* @private
*/
_destroy(socket) {
const nsps = Object.keys(this.nsps);
for (const nsp of nsps) {
const socket2 = this.nspsnsp; if (socket2.active) {
return;
}
}
this._close();
}
/**
* Writes a packet.
*
* @param packet
* @private
*/
_packet(packet) {
const encodedPackets = this.encoder.encode(packet);
for (let i2 = 0; i2 < encodedPackets.length; i2++) {
this.engine.write(encodedPacketsi2, packet.options); }
}
/**
* Clean up transport subscriptions and packet buffer.
*
* @private
*/
cleanup() {
this.subs.forEach((subDestroy) => subDestroy());
this.subs.length = 0;
this.decoder.destroy();
}
/**
* Close the current socket.
*
* @private
*/
_close() {
this.skipReconnect = true;
this._reconnecting = false;
this.onclose("forced close");
}
/**
* Alias for close()
*
* @private
*/
disconnect() {
return this._close();
}
/**
* Called when:
*
* - the low-level engine is closed
* - the parser encountered a badly formatted packet
* - all sockets are disconnected
*
* @private
*/
onclose(reason, description) {
var _a;
this.cleanup();
(_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
this.backoff.reset();
this._readyState = "closed";
this.emitReserved("close", reason, description);
if (this._reconnection && !this.skipReconnect) {
this.reconnect();
}
}
/**
* Attempt a reconnection.
*
* @private
*/
reconnect() {
if (this._reconnecting || this.skipReconnect)
return this;
const self2 = this;
if (this.backoff.attempts >= this._reconnectionAttempts) {
this.backoff.reset();
this.emitReserved("reconnect_failed");
this._reconnecting = false;
} else {
const delay2 = this.backoff.duration();
this._reconnecting = true;
const timer = this.setTimeoutFn(() => {
if (self2.skipReconnect)
return;
this.emitReserved("reconnect_attempt", self2.backoff.attempts);
if (self2.skipReconnect)
return;
self2.open((err) => {
if (err) {
self2._reconnecting = false;
self2.reconnect();
this.emitReserved("reconnect_error", err);
} else {
self2.onreconnect();
}
});
}, delay2);
if (this.opts.autoUnref) {
timer.unref();
}
this.subs.push(() => {
this.clearTimeoutFn(timer);
});
}
}
/**
* Called upon successful reconnect.
*
* @private
*/
onreconnect() {
const attempt = this.backoff.attempts;
this._reconnecting = false;
this.backoff.reset();
this.emitReserved("reconnect", attempt);
}
};
// ../../.local/share/scrapbox-write/node_modules/socket.io-client/build/esm/index.js
var cache = {};
function lookup2(uri, opts) {
if (typeof uri === "object") {
opts = uri;
uri = void 0;
}
opts = opts || {};
const parsed = url(uri, opts.path || "/socket.io");
const source = parsed.source;
const id = parsed.id;
const path = parsed.path;
const sameNamespace = cacheid && path in cacheid"nsps"; const newConnection = opts.forceNew || opts"force new connection" || false === opts.multiplex || sameNamespace; let io;
if (newConnection) {
io = new Manager(source, opts);
} else {
cacheid = new Manager(source, opts); }
}
if (parsed.query && !opts.query) {
opts.query = parsed.queryKey;
}
return io.socket(parsed.path, opts);
}
Object.assign(lookup2, {
Manager,
Socket: Socket2,
io: lookup2,
connect: lookup2
});
// ../../.local/share/scrapbox-write/node_modules/option-t/esm/internal/error_message.js
var ERR_MSG_MUST_NOT_RETURN = " must not return ";
var TRANSFORM_FUNCTION_NAME = "transformer";
var RECOVERY_FUNCTION_NAME = "recoverer";
var DEFAULT_VALUE_NAME = "defaultValue";
var ERR_MSG_TRANSFORMER_MUST_NOT_RETURN = TRANSFORM_FUNCTION_NAME + ERR_MSG_MUST_NOT_RETURN;
var ERR_MSG_CALLED_WITH = "called with ";
var ERR_MSG_DEFAULT_VALUE_MUST_NOT_BE = DEFAULT_VALUE_NAME + " must not be ";
var ERR_MSG_RECOVERER_MUST_NOT_RETURN = RECOVERY_FUNCTION_NAME + ERR_MSG_MUST_NOT_RETURN;
// ../../.local/share/scrapbox-write/node_modules/option-t/esm/plain_result/internal/error_message.js
var OK_TYPE_STR = "Ok";
var ERR_TYPE_STR = "Err";
var ERR_MSG_UNWRAP_OK_BUT_INPUT_IS_ERR = ERR_MSG_CALLED_WITH + ERR_TYPE_STR;
var ERR_MSG_UNWRAP_ERR_BUT_INPUT_IS_OK = ERR_MSG_CALLED_WITH + OK_TYPE_STR;
var ERR_MSG_FOR_ERROR_OBJECT_GENERATED_BY_UNWRAP_OR_THROW = "Carrying E in " + ERR_TYPE_STR + " instead of throwing it directly. See .cause";
var MSG_BUILTIN_ERROR_INSTANCE_OF_CURRENT_REALM = "an instance of Error of the current realm.";
var ERR_MSG_THROWN_VALUE_IS_NOT_BUILTIN_ERROR_INSTANCE = "The thrown value is not " + MSG_BUILTIN_ERROR_INSTANCE_OF_CURRENT_REALM;
var ERR_MSG_CONTAINED_TYPE_E_SHOULD_BE_BUILTIN_ERROR_INSTANCE = "The contained E should be " + MSG_BUILTIN_ERROR_INSTANCE_OF_CURRENT_REALM;
var ERR_MSG_DOT_CAUSE_PROPS_IS_NOT_CURRENT_REALM_BUILTIN_ERROR_INSTANCE = "This .cause is not " + MSG_BUILTIN_ERROR_INSTANCE_OF_CURRENT_REALM;
// ../../.local/share/scrapbox-write/node_modules/option-t/esm/plain_result/result.js
function isOk(input) {
return input.ok;
}
function createOk(val) {
const r2 = {
ok: true,
val,
// XXX:
// We need to fill with null to improve the compatibility with Next.js
err: null
};
return r2;
}
function isErr(input) {
return !input.ok;
}
function createErr(err) {
const r2 = {
ok: false,
// XXX:
// We need to fill with null to improve the compatibility with Next.js
val: null,
err
};
return r2;
}
function unwrapOk(input) {
return expectOk(input, ERR_MSG_UNWRAP_OK_BUT_INPUT_IS_ERR);
}
function unwrapErr(input) {
return expectErr(input, ERR_MSG_UNWRAP_ERR_BUT_INPUT_IS_OK);
}
function expectOk(input, msg) {
if (isErr(input)) {
throw new TypeError(msg);
}
const val = input.val;
return val;
}
function expectErr(input, msg) {
if (isOk(input)) {
throw new TypeError(msg);
}
const err = input.err;
return err;
}
// ../../.local/share/scrapbox-write/node_modules/option-t/esm/plain_result/internal/intrinsics_unsafe.js
function unsafeUnwrapValueInOkWithoutAnyCheck(input) {
const val = input.val;
return val;
}
function unsafeUnwrapValueInErrWithoutAnyCheck(input) {
const err = input.err;
return err;
}
// ../../.local/share/scrapbox-write/node_modules/option-t/esm/plain_result/and_then_async.js
async function andThenAsyncForResult(input, transformer) {
if (isErr(input)) {
return input;
}
const source = unsafeUnwrapValueInOkWithoutAnyCheck(input);
const result = await transformer(source);
return result;
}
// ../../.local/share/scrapbox-write/node_modules/option-t/esm/plain_result/map.js
function mapForResult(input, transformer) {
if (isErr(input)) {
return input;
}
const val = unsafeUnwrapValueInOkWithoutAnyCheck(input);
const result = transformer(val);
return createOk(result);
}
// ../../.local/share/scrapbox-write/node_modules/option-t/esm/plain_result/map_async.js
async function mapAsyncForResult(input, transformer) {
if (isErr(input)) {
const fallback = input;
return fallback;
}
const inner = unsafeUnwrapValueInOkWithoutAnyCheck(input);
const mapped = await transformer(inner);
const result = createOk(mapped);
return result;
}
// ../../.local/share/scrapbox-write/node_modules/option-t/esm/plain_result/map_err_async.js
async function mapErrAsyncForResult(input, transformer) {
if (isOk(input)) {
return input;
}
const err = unsafeUnwrapValueInErrWithoutAnyCheck(input);
const e2 = await transformer(err);
const result = createErr(e2);
return result;
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/_dnt.shims.js
var dntGlobals = {};
var dntGlobalThis = createMergeProxy(globalThis, dntGlobals);
function createMergeProxy(baseObj, extObj) {
return new Proxy(baseObj, {
get(_target, prop, _receiver) {
if (prop in extObj) {
} else {
}
},
set(_target, prop, value2) {
if (prop in extObj) {
}
return true;
},
deleteProperty(_target, prop) {
let success = false;
if (prop in extObj) {
success = true;
}
if (prop in baseObj) {
success = true;
}
return success;
},
ownKeys(_target) {
const baseKeys = Reflect.ownKeys(baseObj);
const extKeys = Reflect.ownKeys(extObj);
const extKeysSet = new Set(extKeys);
},
defineProperty(_target, prop, desc) {
if (prop in extObj) {
}
Reflect.defineProperty(baseObj, prop, desc);
return true;
},
getOwnPropertyDescriptor(_target, prop) {
if (prop in extObj) {
return Reflect.getOwnPropertyDescriptor(extObj, prop);
} else {
return Reflect.getOwnPropertyDescriptor(baseObj, prop);
}
},
has(_target, prop) {
return prop in extObj || prop in baseObj;
}
});
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/rest/responseIntoResult.js
var responseIntoResult = (response) => !response.ok ? createErr({
name: "HTTPError",
message: ${response.status} ${response.statusText},
response
}) : createOk(response);
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/rest/robustFetch.js
var robustFetch = async (input, init) => {
const request = new Request(input, init);
try {
return createOk(await globalThis.fetch(request));
} catch (e2) {
if (e2 instanceof DOMException && e2.name === "AbortError") {
return createErr({
name: "AbortError",
message: e2.message,
request
});
}
if (e2 instanceof TypeError) {
return createErr({
name: "NetworkError",
message: e2.message,
request
});
}
throw e2;
}
};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/rest/options.js
var setDefaults = (options) => {
const { fetch: fetch2 = robustFetch, hostName = "scrapbox.io", ...rest } = options;
return { fetch: fetch2, hostName, ...rest };
};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/rest/profile.js
var getProfile_toRequest = (init) => {
const { sid, hostName } = setDefaults(init ?? {});
return new Request(https://${hostName}/api/users/me, sid ? { headers: { Cookie: cookie(sid) } } : void 0);
};
var getProfile_fromResponse = (response) => mapAsyncForResult(responseIntoResult(response), async (res) => await res.json());
var getProfile = /* @__PURE__ */ (() => {
const fn = async (init) => {
const { fetch: fetch2, ...rest } = setDefaults(init ?? {});
const resResult = await fetch2(getProfile_toRequest(rest));
return isErr(resResult) ? resResult : getProfile_fromResponse(unwrapOk(resResult));
};
fn.toRequest = getProfile_toRequest;
fn.fromResponse = getProfile_fromResponse;
return fn;
})();
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/rest/auth.js
var cookie = (sid) => connect.sid=${sid};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/socket.js
var connect = (socket, sid) => {
if (socket?.connected)
return Promise.resolve(createOk(socket));
reconnectionDelay: 5e3,
...sid ? {
rejectUnauthorized: false,
extraHeaders: {
Cookie: cookie(sid),
Host: "scrapbox.io",
}
} : {}
}));
const promise = new Promise((resolve) => {
const onDisconnect = (reason) => resolve(createErr(reason));
socket.once("connect", () => {
socket.off("disconnect", onDisconnect);
resolve(createOk(socket));
});
socket.once("disconnect", onDisconnect);
});
socket.connect();
return promise;
};
var disconnect = (socket) => {
if (socket.disconnected)
return Promise.resolve(createOk(void 0));
const promise = new Promise((resolve) => {
const onDisconnect = (reason) => {
if (reason !== "io client disconnect") {
resolve(createErr(reason));
return;
}
resolve(createOk(void 0));
socket.off("disconnect", onDisconnect);
};
socket.on("disconnect", onDisconnect);
});
socket.disconnect();
return promise;
};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/error.js
var isPageCommitError = (error) => pageCommitErrorNames.includes(error.name);
var pageCommitErrorNames = [
"SocketIOError",
"DuplicateTitleError",
"NotFastForwardError"
];
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/emit.js
var emit = (socket, event, data, options) => {
if (event === "cursor") {
socket.emit(event, data);
return Promise.resolve(createOk(void 0));
}
const { resolve, promise, reject } = Promise.withResolvers();
const dispose = () => {
socket.off("disconnect", onDisconnect);
clearTimeout(timeoutId);
};
const onDisconnect = (reason) => {
if (reason === "io client disconnect") {
dispose();
reject(new Error("io client disconnect"));
return;
}
if (reason === "io server disconnect") {
dispose();
resolve(createErr({ name: "SocketIOError" }));
return;
}
};
socket.on("disconnect", onDisconnect);
const timeout = options?.timeout ?? 9e4;
const timeoutId = setTimeout(() => {
dispose();
resolve(createErr({
name: "TimeoutError",
message: exceeded ${timeout} (ms)
}));
}, timeout);
const payload = event === "commit" ? { method: "commit", data } : { method: "room:join", data };
socket.emit("socket.io-request", payload, (res) => {
dispose();
if ("error" in res) {
resolve(createErr(isPageCommitError(res.error) ? res.error : { name: "UnexpectedRequestError", ...res }));
return;
}
resolve(createOk(res.data));
});
return promise;
};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/deps_2/jsr.io/@core/unknownutil/4.3.0/_inspect.js
var defaultThreshold = 20;
function inspect(value2, options = {}) {
if (value2 === null) {
return "null";
} else if (Array.isArray(value2)) {
return inspectArray(value2, options);
}
switch (typeof value2) {
case "string":
return JSON.stringify(value2);
case "bigint":
return ${value2}n;
case "object":
if (value2.constructor?.name !== "Object") {
return value2.constructor?.name;
}
return inspectRecord(value2, options);
case "function":
return value2.name || "(anonymous)";
}
return value2?.toString() ?? "undefined";
}
function inspectArray(value2, options) {
const { threshold = defaultThreshold } = options;
const vs = value2.map((v2) => inspect(v2, options));
const s2 = vs.join(", ");
if (s2.length <= threshold)
return [${s2}];
const m2 = vs.join(",\n");
return `[
${indent(2, m2)}
]`;
}
function inspectRecord(value2, options) {
const { threshold = defaultThreshold } = options;
const s2 = vs.join(", ");
if (s2.length <= threshold)
return {${s2}};
const m2 = vs.join(",\n");
return `{
${indent(2, m2)}
}`;
}
function indent(level, text) {
const prefix = " ".repeat(level);
return text.split("\n").map((line) => ${prefix}${line}).join("\n");
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/deps_2/jsr.io/@core/unknownutil/4.3.0/_funcutil.js
function rewriteName(fn, name, ...args) {
let cachedName;
return Object.defineProperties(fn, {
name: {
get: () => {
if (cachedName)
return cachedName;
cachedName = ${name}(${args.map((v2) => inspect(v2)).join(", ")});
return cachedName;
}
}
});
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/deps_2/jsr.io/@core/unknownutil/4.3.0/is/array.js
function isArray(x2) {
return Array.isArray(x2);
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/deps_2/jsr.io/@core/unknownutil/4.3.0/is/array_of.js
function isArrayOf(pred) {
return rewriteName((x2) => isArray(x2) && x2.every((v2) => pred(v2)), "isArrayOf", pred);
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/deps_2/jsr.io/@core/unknownutil/4.3.0/is/literal_one_of.js
function isLiteralOneOf(literals) {
const s2 = new Set(literals);
return rewriteName((x2) => s2.has(x2), "isLiteralOneOf", literals);
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/deps_2/jsr.io/@core/unknownutil/4.3.0/is/record.js
function isRecord(x2) {
return x2 != null && !Array.isArray(x2) && typeof x2 === "object";
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/deps_2/jsr.io/@core/unknownutil/4.3.0/is/string.js
function isString(x2) {
return typeof x2 === "string";
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/rest/parseHTTPError.js
var parseHTTPError = async (error, errorNames) => {
const res = error.response.clone();
const isErrorNames = isLiteralOneOf(errorNames);
try {
const json = await res.json();
if (!isRecord(json))
return;
if (res.status === 422) {
if (!isString(json.message))
return;
for (const name of [
"NoQueryError",
"InvalidURLError"
]) {
if (!errorNames.includes(name))
continue;
return {
name,
message: json.message
};
}
}
if (!isErrorNames(json.name))
return;
if (!isString(json.message))
return;
if (json.name === "NotLoggedInError") {
if (!isRecord(json.detals))
return;
if (!isString(json.detals.project))
return;
if (!isArrayOf(isLoginStrategies)(json.detals.loginStrategies))
return;
return {
name: json.name,
message: json.message,
details: {
project: json.detals.project,
loginStrategies: json.detals.loginStrategies
}
};
}
return {
name: json.name,
message: json.message
};
} catch (e2) {
if (e2 instanceof SyntaxError)
return;
throw e2;
}
};
var isLoginStrategies = /* @__PURE__ */ isLiteralOneOf([
"google",
"github",
"microsoft",
"gyazo",
"email",
"saml",
"easy-trial"
]);
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/title.js
var toTitleLc = (text) => text.replaceAll(" ", "_").toLowerCase();
var encodeTitleURI = (title) => {
if (char === " ")
return "_";
if (!noEncodeChars.includes(char) || index === title.length - 1 && noTailChars.includes(char)) {
return encodeURIComponent(char);
}
return char;
}).join("");
};
var noEncodeChars = '@$&+=:;",';
var noTailChars = ':;",';
// ../../.local/share/scrapbox-write/node_modules/option-t/esm/maybe/internal/error_message.js
var NO_VAL_VALUE_TYPE_STR = "null or undefined";
var ERR_MSG_TRANSFORMER_MUST_NOT_RETURN_NO_VAL_FOR_MAYBE = ERR_MSG_TRANSFORMER_MUST_NOT_RETURN + NO_VAL_VALUE_TYPE_STR;
var ERR_MSG_UNWRAP_NO_VAL_FOR_MAYBE = ERR_MSG_CALLED_WITH + NO_VAL_VALUE_TYPE_STR;
var ERR_MSG_DEFAULT_VALUE_MUST_NOT_BE_NO_VAL_FOR_MAYBE = ERR_MSG_DEFAULT_VALUE_MUST_NOT_BE + NO_VAL_VALUE_TYPE_STR;
var ERR_MSG_RECOVERER_MUST_NOT_RETURN_NO_VAL_FOR_MAYBE = ERR_MSG_RECOVERER_MUST_NOT_RETURN + NO_VAL_VALUE_TYPE_STR;
// ../../.local/share/scrapbox-write/node_modules/option-t/esm/maybe/maybe.js
function isNotNullOrUndefined(input) {
return input !== void 0 && input !== null;
}
function expectNotNullOrUndefined(input, msg) {
if (isNotNullOrUndefined(input)) {
return input;
}
throw new TypeError(msg);
}
// ../../.local/share/scrapbox-write/node_modules/option-t/esm/maybe/unwrap_or.js
function unwrapOrForMaybe(input, defaultValue) {
if (isNotNullOrUndefined(input)) {
return input;
}
const passed = expectNotNullOrUndefined(defaultValue, ERR_MSG_DEFAULT_VALUE_MUST_NOT_BE_NO_VAL_FOR_MAYBE);
return passed;
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/rest/pages.js
var getPage_toRequest = (project, title, options) => {
const { sid, hostName, followRename, projects } = setDefaults(options ?? {});
const params = new URLSearchParams([
["followRename", ${followRename ?? true}],
]);
return new Request(https://${hostName}/api/pages/${project}/${encodeTitleURI(title)}?${params}, sid ? { headers: { Cookie: cookie(sid) } } : void 0);
};
var getPage_fromResponse = async (res) => mapErrAsyncForResult(await mapAsyncForResult(responseIntoResult(res), (res2) => res2.json()), async (error) => {
if (error.response.status === 414) {
return {
name: "TooLongURIError",
message: "project ids may be too much."
};
}
return unwrapOrForMaybe(await parseHTTPError(error, [
"NotFoundError",
"NotLoggedInError",
"NotMemberError"
]), error);
});
var getPage = /* @__PURE__ */ (() => {
const fn = async (project, title, options) => andThenAsyncForResult(await setDefaults(options ?? {}).fetch(getPage_toRequest(project, title, options)), (input) => getPage_fromResponse(input));
fn.toRequest = getPage_toRequest;
fn.fromResponse = getPage_fromResponse;
return fn;
})();
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/rest/project.js
var getProject_toRequest = (project, init) => {
const { sid, hostName } = setDefaults(init ?? {});
return new Request(https://${hostName}/api/projects/${project}, sid ? { headers: { Cookie: cookie(sid) } } : void 0);
};
var getProject_fromResponse = async (res) => mapAsyncForResult(await mapErrAsyncForResult(responseIntoResult(res), async (error) => await parseHTTPError(error, [
"NotFoundError",
"NotLoggedInError",
"NotMemberError"
]) ?? error), (res2) => res2.json());
var getProject = /* @__PURE__ */ (() => {
const fn = async (project, init) => {
const { fetch: fetch2 } = setDefaults(init ?? {});
const req = getProject_toRequest(project, init);
const res = await fetch2(req);
if (isErr(res))
return res;
return getProject_fromResponse(unwrapOk(res));
};
fn.toRequest = getProject_toRequest;
fn.fromResponse = getProject_fromResponse;
return fn;
})();
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/pull.js
var pull = async (project, title, options) => {
getPage(project, title, options),
getUserId(options),
getProjectId(project, options)
]);
if (isErr(pageRes))
return pageRes;
if (isErr(userRes))
return userRes;
if (isErr(projectRes))
return projectRes;
return createOk({
...unwrapOk(pageRes),
projectId: unwrapOk(projectRes),
userId: unwrapOk(userRes)
});
};
var userId;
var getUserId = async (init) => {
if (userId)
return createOk(userId);
const result = await getProfile(init);
if (isErr(result))
return result;
const user = unwrapOk(result);
if ("id" in user) {
userId = user.id;
return createOk(user.id);
}
return createErr({
name: "NotLoggedInError",
message: "This script cannot be used without login"
});
};
var projectMap = /* @__PURE__ */ new Map();
var getProjectId = async (project, options) => {
const cachedId = projectMap.get(project);
if (cachedId)
return createOk(cachedId);
return mapForResult(await getProject(project, options), ({ id }) => {
projectMap.set(project, id);
return id;
});
};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/deps_2/jsr.io/@std/async/1.0.14/delay.js
function delay(ms, options = {}) {
const { signal, persistent = true } = options;
if (signal?.aborted)
return Promise.reject(signal.reason);
return new Promise((resolve, reject) => {
const abort = () => {
clearTimeout(+i2);
reject(signal?.reason);
};
const done = () => {
signal?.removeEventListener("abort", abort);
resolve();
};
const i2 = setArbitraryLengthTimeout(done, ms);
signal?.addEventListener("abort", abort, { once: true });
if (persistent === false) {
try {
Deno.unrefTimer(i2);
} catch (error) {
if (!(error instanceof ReferenceError)) {
throw error;
}
console.error("persistent option is only available in Deno");
}
}
});
}
var I32_MAX = 2 ** 31 - 1;
function setArbitraryLengthTimeout(callback, delay2) {
let currentDelay = delay2 = Math.trunc(Math.max(delay2, 0) || 0);
const start = Date.now();
let timeoutId;
const queueTimeout = () => {
currentDelay = delay2 - (Date.now() - start);
timeoutId = currentDelay > I32_MAX ? setTimeout(queueTimeout, I32_MAX) : setTimeout(callback, currentDelay);
};
queueTimeout();
return { valueOf: () => timeoutId };
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/push.js
var push = async (project, title, makeCommit, options) => {
const result = await connect(options?.socket, options?.sid);
if (isErr(result)) {
return createErr({
name: "UnexpectedRequestError",
error: unwrapErr(result)
});
}
const socket = unwrapOk(result);
const pullResult = await pull(project, title, options);
if (isErr(pullResult))
return pullResult;
let metadata = unwrapOk(pullResult);
try {
let attempts = 0;
let changes = [];
let reason;
while (options?.maxAttempts === void 0 || attempts < options.maxAttempts) {
const pending = makeCommit(metadata, attempts, changes, reason);
changes = pending instanceof Promise ? await pending : pending;
attempts++;
if (changes.length === 0)
return createOk(metadata.commitId);
const data = {
kind: "page",
// Indicates page modification
projectId: metadata.projectId,
// Project scope
pageId: metadata.id,
// Target page
parentId: metadata.commitId,
// Base commit for change
userId: metadata.userId,
// Change author
changes,
// Actual modifications
cursor: null,
// No cursor position
freeze: true
// Prevent concurrent edits
};
while (true) {
const result2 = await emit(socket, "commit", data);
if (isOk(result2)) {
metadata.commitId = unwrapOk(result2).commitId;
return createOk(metadata.commitId);
}
const error = unwrapErr(result2);
const name = error.name;
if (name === "SocketIOServerDisconnectError" || name === "UnexpectedRequestError") {
return createErr(error);
}
if (name === "TimeoutError" || name === "SocketIOError") {
await delay(3e3);
continue;
}
if (name === "NotFastForwardError") {
await delay(1e3);
const pullResult2 = await pull(project, title, options);
if (isErr(pullResult2))
return pullResult2;
metadata = unwrapOk(pullResult2);
}
reason = name;
break;
}
}
return createErr({
name: "RetryError",
attempts,
message: Retrying exceeded the maxAttempts (${attempts}).
});
} finally {
if (!options?.socket)
await disconnect(socket);
}
};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/vendor/raw.githubusercontent.com/takker99/onp/0.0.1/mod.js
var diff = (left, right) => {
const reversed = left.length > right.length;
const a2 = reversed ? right : left;
const b2 = reversed ? left : right;
const offset = a2.length + 1;
const MAXSIZE = a2.length + b2.length + 3;
const path = new Array(MAXSIZE);
path.fill(-1);
const pathpos = [];
function snake(k2, p3, pp) {
let y2 = Math.max(p3, pp);
let x2 = y2 - k2;
while (x2 < a2.length && y2 < b2.length && a2x2 === b2y2) { ++x2;
++y2;
}
return y2;
}
const fp = new Array(MAXSIZE);
fp.fill(-1);
let p2 = -1;
const delta = b2.length - a2.length;
do {
++p2;
for (let k2 = -p2; k2 <= delta - 1; ++k2) {
}
for (let k2 = delta + p2; k2 >= delta + 1; --k2) {
}
const epc = [];
while (r2 !== -1) {
}
return {
from: left,
to: right,
editDistance: delta + p2 * 2,
buildSES: function* () {
let xIndex = 0;
let yIndex = 0;
for (const { x: x2, y: y2 } of reverse(epc)) {
while (xIndex < x2 || yIndex < y2) {
if (y2 - x2 > yIndex - xIndex) {
yield { value: b2yIndex, type: reversed ? "deleted" : "added" }; ++yIndex;
} else if (y2 - x2 < yIndex - xIndex) {
yield { value: a2xIndex, type: reversed ? "added" : "deleted" }; ++xIndex;
} else {
yield { value: a2xIndex, type: "common" }; ++xIndex;
++yIndex;
}
}
}
}
};
};
function* toExtendedChanges(changes) {
let addedList = [];
let deletedList = [];
function* flush() {
if (addedList.length > deletedList.length) {
for (let i2 = 0; i2 < deletedList.length; i2++) {
yield makeReplaced(addedListi2, deletedListi2); }
for (let i2 = deletedList.length; i2 < addedList.length; i2++) {
}
} else {
for (let i2 = 0; i2 < addedList.length; i2++) {
yield makeReplaced(addedListi2, deletedListi2); }
for (let i2 = addedList.length; i2 < deletedList.length; i2++) {
}
}
addedList = [];
deletedList = [];
}
for (const change of changes) {
switch (change.type) {
case "added":
addedList.push(change);
break;
case "deleted":
deletedList.push(change);
break;
case "common":
yield* flush();
yield change;
break;
}
}
yield* flush();
}
var makeReplaced = (left, right) => ({
value: left.value,
oldValue: right.value,
type: "replaced"
});
function* reverse(list) {
for (let i2 = list.length - 1; i2 >= 0; i2--) {
}
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/id.js
var zero = (n2) => n2.padStart(8, "0");
var createNewLineId = (userId2) => {
const time = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3).toString(16);
const rand = Math.floor(16777214 * Math.random()).toString(16);
return ${zero(time).slice(-8)}${userId2.slice(-6)}0000${zero(rand)};
};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/diffToChanges.js
function* diffToChanges(left, right, { userId: userId2 }) {
const { buildSES } = diff(left.map(({ text }) => text), right);
let lineNo = 0;
for (const change of toExtendedChanges(buildSES())) {
switch (change.type) {
case "added":
yield {
_insert: lineId,
lines: {
id: createNewLineId(userId2),
text: change.value
}
};
continue;
case "deleted":
yield {
_delete: lineId,
lines: -1
};
break;
case "replaced":
yield {
_update: lineId,
lines: { text: change.value }
};
break;
}
lineNo++;
lineId = leftlineNo?.id ?? "_end"; }
}
// ../../.local/share/scrapbox-write/node_modules/@progfay/scrapbox-parser/dist/index.js
var e = (e2) => {
let { rows: indent: t2, text: n2 }, ...r2 } = e2;
return { indent: t2, type: codeBlock, fileName: n2.replace(/^\s*code:/, ), content: r2.map((e3) => e3.text.substring(t2 + 1)).join(`
`) };
};
var t = (e2, { parseOnNested: t2, parseOnQuoted: n2, patterns: r2 }) => (i2, a2, o2) => {
if (!t2 && a2.nested || !n2 && a2.quoted) return o2();
for (let t3 of r2) {
let n3 = t3.exec(i2);
if (n3 === null) continue;
let r3 = i2.substring(0, n3.index), o3 = i2.substring(n3.index + n30.length), s2 = e2(n3, a2); }
return o2();
};
var n = (e2) => [{ type: plain, raw: e2, text: e2 }];
var r = n;
var i = t((e2, t2) => t2.context === table ? n(e2) : [{ type: blank, raw: e2, text: e2.substring(1, e2.length - 1) }], { parseOnNested: false, parseOnQuoted: true, patterns: [/\\s+\/] }); var a = t((e2, t2) => t2.context === table ? n(e2) : [{ type: code, raw: e2, text: e2.substring(1, e2.length - 1) }], { parseOnNested: false, parseOnQuoted: true, patterns: [/.*?/] }); var o = t((e2, t2) => t2.context === table ? n(e2) : [{ type: commandLine, raw: e2, symbol: e2.charAt(0), text: e2.substring(2) }], { parseOnNested: false, parseOnQuoted: false, patterns: [/^$% .+$/] }); if (t2.context === table) return n(e2);
let r2 = e2.indexOf( ), i2 = e2.substring(1, r2), a2 = e2.substring(r2 + 1, e2.length - 1), o2 = new Set(i2);
if (o2.has(*)) {
let e3 = i2.split(*).length - 1;
o2.delete(*), o2.add(*-${Math.min(e3, 10)});
}
return [{ type: decoration, raw: e2, rawDecos: i2, decos: Array.from(o2), nodes: O(a2, { ...t2, nested: true }) }];
}, { parseOnNested: false, parseOnQuoted: true, patterns: [/\!"#%&'()*+,\-./{|}<>_~]+ (?:\[[^[\+\]|^\])+\]/] }); if (t2.context === table) return n(e2);
let r2 = e2.startsWith([) && e2.endsWith(]) ? e2.substring(1, e2.length - 1) : e2, i2 = /^https?:\/\/^\s\]/.test(r2), a2 = (i2 ? /^https?:\/\/^\s\]+/ : /https?:\/\/^\s\]+$/).exec(r2); if (a2 === null) return [];
let o2 = i2 ? r2.substring(a20.length) : r2.substring(0, a2.index - 1); return [{ type: link, raw: e2, pathType: absolute, href: a20, content: o2.trim() }]; }, { parseOnNested: true, parseOnQuoted: true, patterns: [/\[https?:\/\/^\s\]+\s+^\]*^\s\]/, /\^[\*^\s\s+https?:\/\/^\s\]+\]/, /\[https?:\/\/^\s\]+\]/, /https?:\/\/^\s+/] }); var l = t((e2, t2) => t2.context === table ? n(e2) : [{ type: formula, raw: e2, formula: e2.substring(3, e2.length - (e2.endsWith( ]) ? 2 : 1)) }], { parseOnNested: false, parseOnQuoted: true, patterns: [/\\$ .+? \/, /\[\$ ^\]+\]/] }); var u = /\[(^\]*^\s)\s+(NS\d+(?:\.\d+)?,EW\d+(?:\.\d+)?(?:,Z\d+)?)\]/; var d = /\[(NS\d+(?:\.\d+)?,EW\d+(?:\.\d+)?(?:,Z\d+)?)(?:\s+(^\]*^\s))?\]/; var f = (e2) => {
let [t2 = , n2 = , r2 = ] = e2.split(,);
return { latitude: Number.parseFloat(t2.replace(/^N/, ).replace(/^S/, -)), longitude: Number.parseFloat(n2.replace(/^E/, ).replace(/^W/, -)), zoom: /^Z\d+$/.test(r2) ? Number.parseInt(r2.replace(/^Z/, ), 10) : 14 };
};
var p = t((e2, t2) => {
if (t2.context === table) return n(r2);
let [, i2 = , a2 = ] = r2.startsWith([N) || r2.startsWith([S) ? e2 : [e20, e22, e21], { latitude: o2, longitude: s2, zoom: c2 } = f(i2); return [{ type: googleMap, raw: r2, latitude: o2, longitude: s2, zoom: c2, place: a2, url: a2 === ? https://www.google.com/maps/@${o2},${s2},${c2}z : https://www.google.com/maps/place/${encodeURIComponent(a2)}/@${o2},${s2},${c2}z }];
}, { parseOnNested: false, parseOnQuoted: true, patterns: u, d }); if (t2.context === table) return n(e2);
if (e2.startsWith(#)) return [{ type: hashTag, raw: e2, href: e2.substring(1) }];
let r2 = e2.substring(0, 1), i2 = e2.substring(1);
return [...n(r2), { type: hashTag, raw: i2, href: i2.substring(1) }];
}, { parseOnNested: true, parseOnQuoted: true, patterns: /(?:^|\s)#\S+/ }); var h = t((e2, t2) => t2.context === table ? n(e2) : [{ type: helpfeel, raw: e2, text: e2.substring(2) }], { parseOnNested: false, parseOnQuoted: false, patterns: /^\? .+$/ }); let t2 = e2.substring(1, e2.length - 1), n2 = t2.lastIndexOf(.icon), r2 = t2.substring(0, n2), i2 = r2.startsWith(/) ? root : relative, a2 = t2.substring(n2 + 5, t2.length), o2 = a2.startsWith(*) ? Number.parseInt(a2.substring(1), 10) : 1;
return Array(o2).fill({}).map(() => ({ path: r2, pathType: i2, type: icon, raw: e2 }));
}, { parseOnNested: true, parseOnQuoted: true, patterns: [/\^[\*\.icon(?:\*1-9\d*)?\]/] }); var _ = /\[https?:\/\/^\s\]+\.(?:png|jpe?g|gif|svg|webp)(?:\?^\\s]+)?(?:\s+https?:\/\/^\s\]+)?\]/i; var v = /\[https?:\/\/^\s\]+\s+https?:\/\/^\s\]+\.(?:png|jpe?g|gif|svg|webp)(?:\?^\\s]+)?\]/i; var y = /\[https?:\/\/(?:0-9a-z-+\.)?gyazo\.com\/0-9a-f{32}(?:\/raw)?(?:\s+https?:\/\/^\s\]+)?\]/; var b = /\[https?:\/\/^\s\]+\s+https?:\/\/(?:0-9a-z-+\.)?gyazo\.com\/0-9a-f{32}(?:\/raw)?\]/; var x = (e2) => /^https?:\/\/^\s\]+\.(png|jpe?g|gif|svg|webp)(\?^\\s]+)?$/i.test(e2) || S(e2); var S = (e2) => /^https?:\/\/(0-9a-z-\.)?gyazo\.com\/0-9a-f{32}(\/raw)?$/.test(e2); if (t2.context === table) return n(e2);
let r2 = e2.search(/\s/), i2 = r2 === -1 ? e2.substring(1, e2.length - 1) : e2.substring(1, r2), a2 = r2 === -1 ? : e2.substring(r2, e2.length - 1).replace(/^\s+/, ), o2, s2 = x(a2) ? a2, i2 : i2, a2; return [{ type: image, raw: e2, src: /^https?:\/\/(0-9a-z-\.)?gyazo\.com\/0-9a-f{32}$/.test(o2) ? ${o2}/thumb/1000 : o2, link: s2 }]; }, { parseOnNested: true, parseOnQuoted: true, patterns: v, y, b });
let t2 = e2.substring(1, e2.length - 1);
return [{ type: link, raw: e2, pathType: t2.startsWith(/) ? root : relative, href: t2, content: }];
}, { parseOnNested: true, parseOnQuoted: true, patterns: [/\[\/?[^\]+\]/] }); if (t2.context === table) return n(e2);
let r2 = e2.indexOf( ), i2 = e2.substring(0, r2 - 1);
return [{ type: numberList, raw: e2, rawNumber: i2, number: Number.parseInt(i2, 10), nodes: O(e2.substring(r2 + 1, e2.length), { ...t2, nested: false }) }];
}, { parseOnNested: false, parseOnQuoted: false, patterns: [/^0-9+\. .*$/] }); var E = t((e2, t2) => t2.context === table ? n(e2) : [{ type: quote, raw: e2, nodes: O(e2.substring(1), { ...t2, quoted: true }) }], { parseOnNested: false, parseOnQuoted: false, patterns: /^>.*$/ }); if (t2.context === table) return n(e2);
let r2 = e2.substring(2, e2.length - 2), i2 = r2.lastIndexOf(.icon), a2 = r2.substring(0, i2), o2 = a2.startsWith(/) ? root : relative, s2 = r2.substring(i2 + 5, r2.length), c2 = s2.startsWith(*) ? Number.parseInt(s2.substring(1), 10) : 1;
return Array(c2).fill({}).map(() => ({ path: a2, pathType: o2, type: strongIcon, raw: e2 }));
}, { parseOnNested: false, parseOnQuoted: true, patterns: [/\[\^[\*\.icon(?:\*\d+)?\]\]/] });
var O = /* @__PURE__ */ ((...e2) => (t2, n2) => e2.reduceRight((e3, r2) => () => r2(t2, n2, e3), () => r(t2, n2))())((e2, t2, n2) => e2 === ? [] : n2(), E, h, T, a, o, i, s, l, t((e2, t2) => { if (t2.context === table) return n(e2);
let r2 = e2.substring(2, e2.length - 2);
return [{ type: strongImage, raw: e2, src: /^https?:\/\/(0-9a-z-\.)?gyazo\.com\/0-9a-f{32}$/.test(r2) ? ${r2}/thumb/1000 : r2 }]; }, { parseOnNested: false, parseOnQuoted: true, patterns: [/\[\[https?:\/\/^\s\]+\.(?:png|jpe?g|gif|svg|webp)\]\]/i, /\[\[https?:\/\/(?:0-9a-z-+\.)?gyazo\.com\/0-9a-f{32}\]\]/] }), D, t((e2, t2) => t2.context === table ? n(e2) : [{ type: strong, raw: e2, nodes: O(e2.substring(2, e2.length - 2), { ...t2, nested: true }) }], { parseOnNested: false, parseOnQuoted: true, patterns: [/\[\[(?:[^[]|\[[^[]).*?\]*\]\]/] }), C, c, g, p, w, m); var k = (e2) => {
let { indent: t2, text: n2 } = e2.rows0; return { indent: t2, type: line, nodes: O(n2.substring(t2), { nested: false, quoted: false, context: line }) };
};
var A = (e2) => {
let { rows: indent: t2, text: n2 }, ...r2 } = e2;
return { indent: t2, type: table, fileName: n2.replace(/^\s*table:/, ), cells: r2.map((e3) => e3.text.substring(t2 + 1)).map((e3) => e3.split( ).map((e4) => O(e4, { nested: false, quoted: false, context: table }))) };
};
var j = (e2) => ({ type: title, text: e2.rows0.text }); var M = (t2) => {
switch (t2.type) {
case title:
return j(t2);
case codeBlock:
return e(t2);
case table:
return A(t2);
case line:
return k(t2);
}
};
var N = ({ type: e2, rows: t2 }, n2) => (e2 === codeBlock || e2 === table) && n2.indent > t2.indent; var P = (e2, t2) => {
return n2 !== void 0 && N(n2, t2) ? n2.rows.push(t2) : e2.push({ type: /^\s*code:/.test(t2.text) ? codeBlock : /^\s*table:/.test(t2.text) ? table : line, rows: t2 }), e2; };
var F = (e2, { hasTitle: t2 = true }) => {
if (t2) {
return t3 === void 0 ? [] : [{ type: title, rows: t3 }, ...n2.reduce(P, [])]; }
return e2.reduce(P, []);
};
var I = (e2) => e2.split(`
`).map((e3) => ({ indent: /^\s+/.exec(e3)?.0.length ?? 0, text: e3 })); var L = (e2, { hasTitle: t2 = true } = {}) => F(I(e2), { hasTitle: t2 }).map(M);
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/parser/youtube.js
var youtubeRegExp = /https?:\/\/(?:www\.|music\.|)youtube\.com\/watch/;
var youtubeDotBeRegExp = /https?:\/\/youtu\.be\/(a-zA-Z\d_-+)(?:\?(^\s{0,100})|)/; var youtubeShortRegExp = /https?:\/\/(?:www\.|)youtube\.com\/shorts\/(a-zA-Z\d_-+)(?:\?(^\s+)|)/; var youtubeListRegExp = /https?:\/\/(?:www\.|music\.|)youtube\.com\/playlist\?((?:^\s+&|)list=(a-zA-Z\d_-+)(?:&^\s+|))/; var parseYoutube = (url2) => {
if (youtubeRegExp.test(url2)) {
const params = new URL(url2).searchParams;
const videoId = params.get("v");
if (videoId) {
return {
pathType: "com",
videoId,
params
};
}
}
{
const matches = url2.match(youtubeDotBeRegExp);
if (matches) {
const videoId, params = matches;
return {
videoId,
params: new URLSearchParams(params),
pathType: "dotbe"
};
}
}
{
const matches = url2.match(youtubeShortRegExp);
if (matches) {
const videoId, params = matches;
return {
videoId,
params: new URLSearchParams(params),
pathType: "short"
};
}
}
{
const matches = url2.match(youtubeListRegExp);
if (matches) {
const params, listId = matches;
return { listId, params: new URLSearchParams(params), pathType: "list" };
}
}
return void 0;
};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/getPageMetadataFromLines.js
var getPageMetadataFromLines = (text) => {
const blocks = L(text, { hasTitle: true });
let title = "";
const linksLc = /* @__PURE__ */ new Map();
const links = [];
const projectLinksLc = /* @__PURE__ */ new Set();
const projectLinks = [];
const iconsLc = /* @__PURE__ */ new Set();
const icons = [];
let image = null;
const descriptions = [];
const files = /* @__PURE__ */ new Set();
const helpfeels = /* @__PURE__ */ new Set();
const fileUrlPattern = new RegExp(${// For Node compatibility, we need to access location via globalThis`
// deno-lint-ignore no-explicit-any
const lookup3 = (node) => {
switch (node.type) {
case "hashTag":
if (linksLc.has(toTitleLc(node.href)))
return;
linksLc.set(toTitleLc(node.href), false);
links.push(node.href);
return;
case "link":
switch (node.pathType) {
case "relative": {
const link = cutId(node.href);
if (linksLc.get(toTitleLc(link)))
return;
linksLc.set(toTitleLc(link), true);
links.push(link);
return;
}
case "root": {
const link = cutId(node.href);
if (/^\/\w\d-+\/?$/.test(link)) return;
if (projectLinksLc.has(toTitleLc(link)))
return;
projectLinksLc.add(toTitleLc(link));
projectLinks.push(link);
return;
}
case "absolute": {
if (node.content)
return;
const props = parseYoutube(node.href);
if (props && props.pathType !== "list") {
image ?? (image = https://i.ytimg.com/vi/${props.videoId}/mqdefault.jpg);
return;
}
const fileId = node.href.match(fileUrlPattern)?.1; if (fileId)
files.add(fileId);
return;
}
default:
return;
}
case "icon":
case "strongIcon": {
if (node.pathType === "root")
return;
if (iconsLc.has(toTitleLc(node.path)))
return;
iconsLc.add(toTitleLc(node.path));
icons.push(node.path);
return;
}
case "image":
case "strongImage": {
image ?? (image = node.src.endsWith("/thumb/1000") ? node.src.replace(/\/thumb\/1000$/, "/raw") : node.src);
{
const fileId = node.src.match(fileUrlPattern)?.1; if (fileId)
files.add(fileId);
}
if (node.type === "image") {
const fileId = node.link.match(fileUrlPattern)?.1; if (fileId)
files.add(fileId);
}
return;
}
case "helpfeel":
helpfeels.add(node.text);
return;
case "numberList":
case "strong":
case "quote":
case "decoration": {
for (const n2 of node.nodes) {
lookup3(n2);
}
return;
}
default:
return;
}
};
const infoboxDefinition = [];
for (const block of blocks) {
switch (block.type) {
case "title": {
title = block.text;
continue;
}
case "line":
if (descriptions.length < 5 && block.nodes.length > 0) {
descriptions.push(block.nodes0.type === "helpfeel" || block.nodes0.type === "commandLine" ? makeInlineCodeForDescription(block.nodes0.raw) : block.nodes.map((node) => node.raw).join("").trim().slice(0, 200)); }
for (const node of block.nodes) {
lookup3(node);
}
continue;
case "codeBlock":
if (descriptions.length < 5) {
descriptions.push(makeInlineCodeForDescription(block.content));
}
continue;
case "table": {
for (const row of block.cells) {
for (const nodes of row) {
for (const node of nodes) {
lookup3(node);
}
}
}
continue;
infoboxDefinition.push(...block.cells.map((row) => row.map((cell) => cell.map((node) => node.raw).join("")).join(" ").trim()));
continue;
}
}
}
const lines = text.split("\n");
return [
title,
links,
projectLinks,
icons,
image,
descriptions,
infoboxDefinition,
lines.length,
lines.reduce((acc, line) => acc + ...line.length, 0) ];
};
var makeInlineCodeForDescription = (text) => \`${text.trim().replaceAll("", "\\").slice(0, 198)}\`;
var cutId = (link) => link.replace(/#a-f\d{24,32}$/, ""); // ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/isSameArray.js
var isSameArray = (a2, b2) => a2.length === b2.length && a2.every((x2) => b2.includes(x2));
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/getHelpfeels.js
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/makeChanges.js
function* makeChanges(before, after, userId2) {
const after_ = after.flatMap((text) => (isString(text) ? text : text.text).split("\n"));
for (const change of diffToChanges(before.lines, after_, { userId: userId2 })) {
yield change;
}
const title, links, projectLinks, icons, image, descriptions, files, helpfeels, infoboxDefinition, linesCount, charsCount = getPageMetadataFromLines(after_.join("\n")); if (before.title !== title || !before.persistent)
yield { title };
if (!isSameArray(before.links, links))
yield { links };
if (!isSameArray(before.projectLinks, projectLinks))
yield { projectLinks };
if (!isSameArray(before.icons, icons))
yield { icons };
if (before.image !== image)
yield { image };
if (!isSameArray(before.descriptions, descriptions))
yield { descriptions };
if (!isSameArray(before.files, files))
yield { files };
if (!isSameArray(getHelpfeels(before.lines), helpfeels))
yield { helpfeels };
if (!isSameArray(before.infoboxDefinition, infoboxDefinition)) {
yield { infoboxDefinition };
}
yield { linesCount };
yield { charsCount };
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/suggestUnDupTitle.js
var suggestUnDupTitle = (title) => {
const matched = title.match(/(.+?)(?:_(\d+))?$/);
const title_ = matched?.1 ?? title; const num = matched?.2 ? parseInt(matched2) + 1 : 2; return ${title_}_${num};
};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/pin.js
var pin = (project, title, options) => push(project, title, (page) => {
if (page.pin > 0 || !page.persistent && !(options?.create ?? false))
return [];
const changes = pin: pinNumber() };
if (!page.persistent)
changes.unshift({ title });
return changes;
}, options);
var unpin = (project, title, options) => push(project, title, (page) => (
// Skip if already unpinned or if page doesn't exist
page.pin == 0 || !page.persistent ? [] : pin: 0 }
), options);
var pinNumber = () => Number.MAX_SAFE_INTEGER - Math.floor(Date.now() / 1e3);
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/patch.js
var patch = (project, title, update, options) => push(project, title, async (page, attempts, prev, reason) => {
if (reason === "DuplicateTitleError") {
const fallbackTitle = suggestUnDupTitle(title);
return prev.map((change) => {
if ("title" in change)
change.title = fallbackTitle;
return change;
});
}
const pending = update(page.lines, { ...page, attempts });
const newContent = pending instanceof Promise ? await pending : pending;
if (newContent === void 0)
return [];
if (newLines.length === 0)
return deleted: true };
if (pin2 !== void 0 && (pin2 && page.pin === 0 || !pin2 && page.pin > 0)) {
changes.push({ pin: pin2 ? pinNumber() : 0 });
}
return changes;
}, options);
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/deletePage.js
var deletePage = (project, title, options) => push(project, title, (page) => page.persistent ? deleted: true } : [], options);
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/listen.js
var listen = (socket, event, listener, options) => {
if (options?.signal?.aborted)
return;
(options?.once ? socket.once : socket.on)(event, listener);
options?.signal?.addEventListener?.(
"abort",
// deno-lint-ignore no-explicit-any
() => socket.off(event, listener),
{ once: true }
);
};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/isSimpleCodeFile.js
function isSimpleCodeFile(obj) {
if (Array.isArray(obj) || !(obj instanceof Object))
return false;
const code = obj;
const { filename, content, lang } = code;
return typeof filename == "string" && (typeof content == "string" || Array.isArray(content) && (content.length == 0 || typeof content0 == "string")) && (typeof lang == "string" || lang === void 0); }
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/_codeBlock.js
var extractFromCodeTitle = (lineText) => {
const matched = lineText.match(/^(\s*)code:(.+?)(\(.+\)){0,1}\s*$/);
if (matched === null)
return null;
const filename = matched2.trim(); let lang = "";
if (matched3 === void 0) { const ext = filename.match(/.+\.(.*)$/);
if (ext === null) {
lang = filename;
} else if (ext1 === "") { return null;
} else {
}
} else {
lang = matched3.slice(1, -1); }
return {
filename,
lang,
};
};
function countBodyIndent(codeBlock) {
return codeBlock.titleLine.text.length - codeBlock.titleLine.text.trimStart().length + 1;
}
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/updateCodeBlock.js
var updateCodeBlock = (newCode, target, options) => {
const newCodeBody = getCodeBody(newCode);
const bodyIndent = countBodyIndent(target);
const oldCodeWithoutIndent = target.bodyLines.map((e2) => {
return { ...e2, text: e2.text.slice(bodyIndent) };
});
return push(target.pageInfo.projectName, target.pageInfo.pageTitle, (page) => {
const diffGenerator = diffToChanges(
oldCodeWithoutIndent,
// Original code without indentation
newCodeBody,
// New code content
page
);
if (isSimpleCodeFile(newCode)) {
const titleCommit = makeTitleChangeCommit(newCode, target);
if (titleCommit)
commits.push(titleCommit);
}
if (options?.debug) {
console.log("%cvvv original code block vvv", "color: limegreen;");
console.log(target);
console.log("%cvvv new codes vvv", "color: limegreen;");
console.log(newCode);
console.log("%cvvv commits vvv", "color: limegreen;");
console.log(commits);
}
return commits;
}, options);
};
var getCodeBody = (code) => {
const content = isSimpleCodeFile(code) ? code.content : code;
if (Array.isArray(content))
return content;
return content.split("\n");
};
function* fixCommits(commits, target) {
const { nextLine } = target;
const indent2 = " ".repeat(countBodyIndent(target));
for (const commit of commits) {
if ("_delete" in commit) {
yield commit;
} else if ("_update" in commit) {
yield {
...commit,
lines: {
...commit.lines,
text: indent2 + commit.lines.text
// Add block's indentation
}
};
} else if (commit._insert != "_end" || // Not an end insertion
nextLine === null) {
yield {
...commit,
lines: {
...commit.lines,
text: indent2 + commit.lines.text
}
};
} else {
yield {
_insert: nextLine.id,
// Insert before the next line
lines: {
...commit.lines,
text: indent2 + commit.lines.text
}
};
}
}
}
var makeTitleChangeCommit = (code, target) => {
const lineId = target.titleLine.id;
const targetTitle = extractFromCodeTitle(target.titleLine.text);
if (targetTitle && code.filename.trim() == targetTitle.filename && code.lang?.trim() == targetTitle.lang)
return null;
const ext = (() => {
const matched = code.filename.match(/.+\.(.*)$/);
if (matched === null)
return code.filename;
else if (matched1 === "") return "";
else
})();
const title = code.filename + (code.lang && code.lang != ext ? (${code.lang}) : "");
return {
_update: lineId,
lines: {
text: " ".repeat(countBodyIndent(target) - 1) + "code:" + title
}
};
};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/rest/getCodeBlocks.js
var getCodeBlocks = (target, filter) => {
const codeBlocks = [];
let currentCode = {
isCodeBlock: false,
filename: "",
lang: "",
indent: 0
};
for (const line of target.lines) {
if (currentCode.isCodeBlock) {
const body = extractFromCodeBody(line.text, currentCode.indent);
if (body === null) {
currentCode.isCodeBlock = false;
continue;
}
} else {
const matched = extractFromCodeTitle(line.text);
if (matched === null) {
currentCode.isCodeBlock = false;
continue;
}
currentCode = { isCodeBlock: true, ...matched };
codeBlocks.push({
filename: currentCode.filename,
lang: currentCode.lang,
titleLine: line,
bodyLines: [],
nextLine: null,
pageInfo: {
projectName: target.project,
pageTitle: target.title
}
});
}
}
return codeBlocks.filter((codeBlock) => isMatchFilter(codeBlock, filter));
};
var isMatchFilter = (codeBlock, filter) => equals(filter?.filename, codeBlock.filename) && equals(filter?.lang, codeBlock.lang) && equals(filter?.titleLineId, codeBlock.titleLine.id);
var equals = (a2, b2) => !a2 || a2 === b2;
var extractFromCodeBody = (lineText, titleIndent) => {
const matched = lineText.replaceAll("\r", "").match(/^(\s*)(.*)$/);
if (matched === null || matched.length < 2) {
return null;
}
const indent2 = matched1; if (indent2.length <= titleIndent)
return null;
return indent2.slice(indent2.length - titleIndent) + body;
};
// ../../.local/share/scrapbox-write/node_modules/@cosense/std/esm/websocket/updateCodeFile.js
var updateCodeFile = (codeFile, project, title, options) => {
const defaultOptions = {
insertPositionIfNotExist: "notInsert",
isInsertEmptyLineInTail: true,
debug: false
};
const opt = options ? { ...defaultOptions, ...options } : defaultOptions;
return push(project, title, (page) => {
const lines = page.lines;
const codeBlocks = getCodeBlocks({ project, title, lines }, {
filename: codeFile.filename
});
const commits = [
...makeCommits(codeBlocks, codeFile, lines, {
...opt,
userId: page.userId
})
];
if (opt.debug) {
console.log("%cvvv original code Blocks vvv", "color: limegreen;");
console.log(codeBlocks);
console.log("%cvvv new codes vvv", "color: limegreen;");
const newCode = Array.isArray(codeFile.content) ? codeFile.content : codeFile.content.split("\n");
console.log(newCode);
console.log("%cvvv commits vvv", "color: limegreen;");
console.log(commits);
}
return commits;
}, options);
};
var flatCodeBodies = (codeBlocks) => {
return codeBlocks.map((block) => {
const indent2 = countBodyIndent(block);
return block.bodyLines.map((body) => {
return { ...body, text: body.text.slice(indent2) };
});
}).flat();
};
function* makeCommits(_codeBlocks, codeFile, lines, { userId: userId2, insertPositionIfNotExist, isInsertEmptyLineInTail }) {
function makeIndent(codeBlock) {
return " ".repeat(countBodyIndent(codeBlock));
}
const codeBodies = flatCodeBodies(_codeBlocks);
if (codeBlocks.length <= 0) {
if (insertPositionIfNotExist === "notInsert")
return;
const nextLine = insertPositionIfNotExist === "top" && lines.length > 1 ? lines1 : null; const title = {
// Code block title line
_insert: nextLine?.id ?? "_end",
lines: {
id: createNewLineId(userId2),
text: makeCodeBlockTitle(codeFile)
}
};
yield title;
codeBlocks.push({
titleLine: { ...title.lines, userId: userId2, created: -1, updated: -1 },
bodyLines: [],
nextLine
});
}
const { buildSES } = diff(codeBodies.map((e2) => e2.text), Array.isArray(codeFile.content) ? codeFile.content : codeFile.content.split("\n"));
let lineNo = 0;
let isInsertBottom = false;
for (const change of toExtendedChanges(buildSES())) {
const { lineId, codeIndex } = (() => {
if (lineNo >= codeBodies.length) {
const index = codeBlocks.length - 1;
return {
lineId: codeBlocksindex.nextLine?.id ?? "_end", codeIndex: index
};
}
return {
codeIndex: codeBlocks.findIndex((e0) => e0.bodyLines.some((e1) => e1.id == codeBodieslineNo.id)) };
})();
if (change.type == "added") {
const insertCodeBlock = lineId == codeBlock.bodyLines0?.id && codeIndex >= 1 ? codeBlockscodeIndex - 1 : codeBlockscodeIndex; const id = insertCodeBlock?.nextLine?.id ?? "_end";
yield {
_insert: id,
lines: {
id: createNewLineId(userId2),
text: makeIndent(insertCodeBlock) + change.value
}
};
if (id == "_end")
isInsertBottom = true;
continue;
} else if (change.type == "deleted") {
yield {
_delete: lineId,
lines: -1
};
} else if (change.type == "replaced") {
yield {
_update: lineId,
lines: {
text: makeIndent(codeBlock) + change.value
}
};
}
lineNo++;
}
if (isInsertBottom && isInsertEmptyLineInTail) {
yield {
_insert: "_end",
lines: {
id: createNewLineId(userId2),
text: ""
}
};
}
}
var makeCodeBlockTitle = (code) => {
const codeName = code.filename + (code.lang ? (${code.lang}) : "");
return code:${codeName};
};
export {
connect,
deletePage,
disconnect,
listen,
patch,
pin,
pinNumber,
push,
unpin,
updateCodeBlock,
updateCodeFile
};