fishing-api/build/index.js

17792 lines
568 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// node_modules/yaml/dist/nodes/identity.js
var require_identity = __commonJS({
"node_modules/yaml/dist/nodes/identity.js"(exports2) {
"use strict";
var ALIAS = Symbol.for("yaml.alias");
var DOC = Symbol.for("yaml.document");
var MAP = Symbol.for("yaml.map");
var PAIR = Symbol.for("yaml.pair");
var SCALAR = Symbol.for("yaml.scalar");
var SEQ = Symbol.for("yaml.seq");
var NODE_TYPE = Symbol.for("yaml.node.type");
var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
function isCollection(node) {
if (node && typeof node === "object")
switch (node[NODE_TYPE]) {
case MAP:
case SEQ:
return true;
}
return false;
}
function isNode(node) {
if (node && typeof node === "object")
switch (node[NODE_TYPE]) {
case ALIAS:
case MAP:
case SCALAR:
case SEQ:
return true;
}
return false;
}
var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
exports2.ALIAS = ALIAS;
exports2.DOC = DOC;
exports2.MAP = MAP;
exports2.NODE_TYPE = NODE_TYPE;
exports2.PAIR = PAIR;
exports2.SCALAR = SCALAR;
exports2.SEQ = SEQ;
exports2.hasAnchor = hasAnchor;
exports2.isAlias = isAlias;
exports2.isCollection = isCollection;
exports2.isDocument = isDocument;
exports2.isMap = isMap;
exports2.isNode = isNode;
exports2.isPair = isPair;
exports2.isScalar = isScalar;
exports2.isSeq = isSeq;
}
});
// node_modules/yaml/dist/visit.js
var require_visit = __commonJS({
"node_modules/yaml/dist/visit.js"(exports2) {
"use strict";
var identity = require_identity();
var BREAK = Symbol("break visit");
var SKIP = Symbol("skip children");
var REMOVE = Symbol("remove node");
function visit(node, visitor) {
const visitor_ = initVisitor(visitor);
if (identity.isDocument(node)) {
const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
if (cd === REMOVE)
node.contents = null;
} else
visit_(null, node, visitor_, Object.freeze([]));
}
visit.BREAK = BREAK;
visit.SKIP = SKIP;
visit.REMOVE = REMOVE;
function visit_(key, node, visitor, path) {
const ctrl = callVisitor(key, node, visitor, path);
if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
replaceNode(key, path, ctrl);
return visit_(key, ctrl, visitor, path);
}
if (typeof ctrl !== "symbol") {
if (identity.isCollection(node)) {
path = Object.freeze(path.concat(node));
for (let i = 0; i < node.items.length; ++i) {
const ci = visit_(i, node.items[i], visitor, path);
if (typeof ci === "number")
i = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
node.items.splice(i, 1);
i -= 1;
}
}
} else if (identity.isPair(node)) {
path = Object.freeze(path.concat(node));
const ck = visit_("key", node.key, visitor, path);
if (ck === BREAK)
return BREAK;
else if (ck === REMOVE)
node.key = null;
const cv = visit_("value", node.value, visitor, path);
if (cv === BREAK)
return BREAK;
else if (cv === REMOVE)
node.value = null;
}
}
return ctrl;
}
async function visitAsync(node, visitor) {
const visitor_ = initVisitor(visitor);
if (identity.isDocument(node)) {
const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
if (cd === REMOVE)
node.contents = null;
} else
await visitAsync_(null, node, visitor_, Object.freeze([]));
}
visitAsync.BREAK = BREAK;
visitAsync.SKIP = SKIP;
visitAsync.REMOVE = REMOVE;
async function visitAsync_(key, node, visitor, path) {
const ctrl = await callVisitor(key, node, visitor, path);
if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
replaceNode(key, path, ctrl);
return visitAsync_(key, ctrl, visitor, path);
}
if (typeof ctrl !== "symbol") {
if (identity.isCollection(node)) {
path = Object.freeze(path.concat(node));
for (let i = 0; i < node.items.length; ++i) {
const ci = await visitAsync_(i, node.items[i], visitor, path);
if (typeof ci === "number")
i = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
node.items.splice(i, 1);
i -= 1;
}
}
} else if (identity.isPair(node)) {
path = Object.freeze(path.concat(node));
const ck = await visitAsync_("key", node.key, visitor, path);
if (ck === BREAK)
return BREAK;
else if (ck === REMOVE)
node.key = null;
const cv = await visitAsync_("value", node.value, visitor, path);
if (cv === BREAK)
return BREAK;
else if (cv === REMOVE)
node.value = null;
}
}
return ctrl;
}
function initVisitor(visitor) {
if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
return Object.assign({
Alias: visitor.Node,
Map: visitor.Node,
Scalar: visitor.Node,
Seq: visitor.Node
}, visitor.Value && {
Map: visitor.Value,
Scalar: visitor.Value,
Seq: visitor.Value
}, visitor.Collection && {
Map: visitor.Collection,
Seq: visitor.Collection
}, visitor);
}
return visitor;
}
function callVisitor(key, node, visitor, path) {
if (typeof visitor === "function")
return visitor(key, node, path);
if (identity.isMap(node))
return visitor.Map?.(key, node, path);
if (identity.isSeq(node))
return visitor.Seq?.(key, node, path);
if (identity.isPair(node))
return visitor.Pair?.(key, node, path);
if (identity.isScalar(node))
return visitor.Scalar?.(key, node, path);
if (identity.isAlias(node))
return visitor.Alias?.(key, node, path);
return void 0;
}
function replaceNode(key, path, node) {
const parent = path[path.length - 1];
if (identity.isCollection(parent)) {
parent.items[key] = node;
} else if (identity.isPair(parent)) {
if (key === "key")
parent.key = node;
else
parent.value = node;
} else if (identity.isDocument(parent)) {
parent.contents = node;
} else {
const pt = identity.isAlias(parent) ? "alias" : "scalar";
throw new Error(`Cannot replace node with ${pt} parent`);
}
}
exports2.visit = visit;
exports2.visitAsync = visitAsync;
}
});
// node_modules/yaml/dist/doc/directives.js
var require_directives = __commonJS({
"node_modules/yaml/dist/doc/directives.js"(exports2) {
"use strict";
var identity = require_identity();
var visit = require_visit();
var escapeChars = {
"!": "%21",
",": "%2C",
"[": "%5B",
"]": "%5D",
"{": "%7B",
"}": "%7D"
};
var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]);
var Directives = class _Directives {
constructor(yaml, tags) {
this.docStart = null;
this.docEnd = false;
this.yaml = Object.assign({}, _Directives.defaultYaml, yaml);
this.tags = Object.assign({}, _Directives.defaultTags, tags);
}
clone() {
const copy = new _Directives(this.yaml, this.tags);
copy.docStart = this.docStart;
return copy;
}
/**
* During parsing, get a Directives instance for the current document and
* update the stream state according to the current version's spec.
*/
atDocument() {
const res = new _Directives(this.yaml, this.tags);
switch (this.yaml.version) {
case "1.1":
this.atNextDocument = true;
break;
case "1.2":
this.atNextDocument = false;
this.yaml = {
explicit: _Directives.defaultYaml.explicit,
version: "1.2"
};
this.tags = Object.assign({}, _Directives.defaultTags);
break;
}
return res;
}
/**
* @param onError - May be called even if the action was successful
* @returns `true` on success
*/
add(line, onError) {
if (this.atNextDocument) {
this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" };
this.tags = Object.assign({}, _Directives.defaultTags);
this.atNextDocument = false;
}
const parts2 = line.trim().split(/[ \t]+/);
const name = parts2.shift();
switch (name) {
case "%TAG": {
if (parts2.length !== 2) {
onError(0, "%TAG directive should contain exactly two parts");
if (parts2.length < 2)
return false;
}
const [handle, prefix] = parts2;
this.tags[handle] = prefix;
return true;
}
case "%YAML": {
this.yaml.explicit = true;
if (parts2.length !== 1) {
onError(0, "%YAML directive should contain exactly one part");
return false;
}
const [version] = parts2;
if (version === "1.1" || version === "1.2") {
this.yaml.version = version;
return true;
} else {
const isValid = /^\d+\.\d+$/.test(version);
onError(6, `Unsupported YAML version ${version}`, isValid);
return false;
}
}
default:
onError(0, `Unknown directive ${name}`, true);
return false;
}
}
/**
* Resolves a tag, matching handles to those defined in %TAG directives.
*
* @returns Resolved tag, which may also be the non-specific tag `'!'` or a
* `'!local'` tag, or `null` if unresolvable.
*/
tagName(source, onError) {
if (source === "!")
return "!";
if (source[0] !== "!") {
onError(`Not a valid tag: ${source}`);
return null;
}
if (source[1] === "<") {
const verbatim = source.slice(2, -1);
if (verbatim === "!" || verbatim === "!!") {
onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
return null;
}
if (source[source.length - 1] !== ">")
onError("Verbatim tags must end with a >");
return verbatim;
}
const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
if (!suffix)
onError(`The ${source} tag has no suffix`);
const prefix = this.tags[handle];
if (prefix) {
try {
return prefix + decodeURIComponent(suffix);
} catch (error) {
onError(String(error));
return null;
}
}
if (handle === "!")
return source;
onError(`Could not resolve tag: ${source}`);
return null;
}
/**
* Given a fully resolved tag, returns its printable string form,
* taking into account current tag prefixes and defaults.
*/
tagString(tag) {
for (const [handle, prefix] of Object.entries(this.tags)) {
if (tag.startsWith(prefix))
return handle + escapeTagName(tag.substring(prefix.length));
}
return tag[0] === "!" ? tag : `!<${tag}>`;
}
toString(doc) {
const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
const tagEntries = Object.entries(this.tags);
let tagNames;
if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {
const tags = {};
visit.visit(doc.contents, (_key, node) => {
if (identity.isNode(node) && node.tag)
tags[node.tag] = true;
});
tagNames = Object.keys(tags);
} else
tagNames = [];
for (const [handle, prefix] of tagEntries) {
if (handle === "!!" && prefix === "tag:yaml.org,2002:")
continue;
if (!doc || tagNames.some((tn) => tn.startsWith(prefix)))
lines.push(`%TAG ${handle} ${prefix}`);
}
return lines.join("\n");
}
};
Directives.defaultYaml = { explicit: false, version: "1.2" };
Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };
exports2.Directives = Directives;
}
});
// node_modules/yaml/dist/doc/anchors.js
var require_anchors = __commonJS({
"node_modules/yaml/dist/doc/anchors.js"(exports2) {
"use strict";
var identity = require_identity();
var visit = require_visit();
function anchorIsValid(anchor) {
if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
const sa = JSON.stringify(anchor);
const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
throw new Error(msg);
}
return true;
}
function anchorNames(root) {
const anchors = /* @__PURE__ */ new Set();
visit.visit(root, {
Value(_key, node) {
if (node.anchor)
anchors.add(node.anchor);
}
});
return anchors;
}
function findNewAnchor(prefix, exclude) {
for (let i = 1; true; ++i) {
const name = `${prefix}${i}`;
if (!exclude.has(name))
return name;
}
}
function createNodeAnchors(doc, prefix) {
const aliasObjects = [];
const sourceObjects = /* @__PURE__ */ new Map();
let prevAnchors = null;
return {
onAnchor: (source) => {
aliasObjects.push(source);
if (!prevAnchors)
prevAnchors = anchorNames(doc);
const anchor = findNewAnchor(prefix, prevAnchors);
prevAnchors.add(anchor);
return anchor;
},
/**
* With circular references, the source node is only resolved after all
* of its child nodes are. This is why anchors are set only after all of
* the nodes have been created.
*/
setAnchors: () => {
for (const source of aliasObjects) {
const ref = sourceObjects.get(source);
if (typeof ref === "object" && ref.anchor && (identity.isScalar(ref.node) || identity.isCollection(ref.node))) {
ref.node.anchor = ref.anchor;
} else {
const error = new Error("Failed to resolve repeated object (this should not happen)");
error.source = source;
throw error;
}
}
},
sourceObjects
};
}
exports2.anchorIsValid = anchorIsValid;
exports2.anchorNames = anchorNames;
exports2.createNodeAnchors = createNodeAnchors;
exports2.findNewAnchor = findNewAnchor;
}
});
// node_modules/yaml/dist/doc/applyReviver.js
var require_applyReviver = __commonJS({
"node_modules/yaml/dist/doc/applyReviver.js"(exports2) {
"use strict";
function applyReviver(reviver, obj, key, val) {
if (val && typeof val === "object") {
if (Array.isArray(val)) {
for (let i = 0, len = val.length; i < len; ++i) {
const v0 = val[i];
const v1 = applyReviver(reviver, val, String(i), v0);
if (v1 === void 0)
delete val[i];
else if (v1 !== v0)
val[i] = v1;
}
} else if (val instanceof Map) {
for (const k of Array.from(val.keys())) {
const v0 = val.get(k);
const v1 = applyReviver(reviver, val, k, v0);
if (v1 === void 0)
val.delete(k);
else if (v1 !== v0)
val.set(k, v1);
}
} else if (val instanceof Set) {
for (const v0 of Array.from(val)) {
const v1 = applyReviver(reviver, val, v0, v0);
if (v1 === void 0)
val.delete(v0);
else if (v1 !== v0) {
val.delete(v0);
val.add(v1);
}
}
} else {
for (const [k, v0] of Object.entries(val)) {
const v1 = applyReviver(reviver, val, k, v0);
if (v1 === void 0)
delete val[k];
else if (v1 !== v0)
val[k] = v1;
}
}
}
return reviver.call(obj, key, val);
}
exports2.applyReviver = applyReviver;
}
});
// node_modules/yaml/dist/nodes/toJS.js
var require_toJS = __commonJS({
"node_modules/yaml/dist/nodes/toJS.js"(exports2) {
"use strict";
var identity = require_identity();
function toJS(value2, arg, ctx) {
if (Array.isArray(value2))
return value2.map((v, i) => toJS(v, String(i), ctx));
if (value2 && typeof value2.toJSON === "function") {
if (!ctx || !identity.hasAnchor(value2))
return value2.toJSON(arg, ctx);
const data = { aliasCount: 0, count: 1, res: void 0 };
ctx.anchors.set(value2, data);
ctx.onCreate = (res2) => {
data.res = res2;
delete ctx.onCreate;
};
const res = value2.toJSON(arg, ctx);
if (ctx.onCreate)
ctx.onCreate(res);
return res;
}
if (typeof value2 === "bigint" && !ctx?.keep)
return Number(value2);
return value2;
}
exports2.toJS = toJS;
}
});
// node_modules/yaml/dist/nodes/Node.js
var require_Node = __commonJS({
"node_modules/yaml/dist/nodes/Node.js"(exports2) {
"use strict";
var applyReviver = require_applyReviver();
var identity = require_identity();
var toJS = require_toJS();
var NodeBase = class {
constructor(type) {
Object.defineProperty(this, identity.NODE_TYPE, { value: type });
}
/** Create a copy of this node. */
clone() {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (this.range)
copy.range = this.range.slice();
return copy;
}
/** A plain JavaScript representation of this node. */
toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
if (!identity.isDocument(doc))
throw new TypeError("A document argument is required");
const ctx = {
anchors: /* @__PURE__ */ new Map(),
doc,
keep: true,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
};
const res = toJS.toJS(this, "", ctx);
if (typeof onAnchor === "function")
for (const { count, res: res2 } of ctx.anchors.values())
onAnchor(res2, count);
return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
}
};
exports2.NodeBase = NodeBase;
}
});
// node_modules/yaml/dist/nodes/Alias.js
var require_Alias = __commonJS({
"node_modules/yaml/dist/nodes/Alias.js"(exports2) {
"use strict";
var anchors = require_anchors();
var visit = require_visit();
var identity = require_identity();
var Node = require_Node();
var toJS = require_toJS();
var Alias = class extends Node.NodeBase {
constructor(source) {
super(identity.ALIAS);
this.source = source;
Object.defineProperty(this, "tag", {
set() {
throw new Error("Alias nodes cannot have tags");
}
});
}
/**
* Resolve the value of this alias within `doc`, finding the last
* instance of the `source` anchor before this node.
*/
resolve(doc) {
let found = void 0;
visit.visit(doc, {
Node: (_key, node) => {
if (node === this)
return visit.visit.BREAK;
if (node.anchor === this.source)
found = node;
}
});
return found;
}
toJSON(_arg, ctx) {
if (!ctx)
return { source: this.source };
const { anchors: anchors2, doc, maxAliasCount } = ctx;
const source = this.resolve(doc);
if (!source) {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new ReferenceError(msg);
}
let data = anchors2.get(source);
if (!data) {
toJS.toJS(source, null, ctx);
data = anchors2.get(source);
}
if (!data || data.res === void 0) {
const msg = "This should not happen: Alias anchor was not resolved?";
throw new ReferenceError(msg);
}
if (maxAliasCount >= 0) {
data.count += 1;
if (data.aliasCount === 0)
data.aliasCount = getAliasCount(doc, source, anchors2);
if (data.count * data.aliasCount > maxAliasCount) {
const msg = "Excessive alias count indicates a resource exhaustion attack";
throw new ReferenceError(msg);
}
}
return data.res;
}
toString(ctx, _onComment, _onChompKeep) {
const src = `*${this.source}`;
if (ctx) {
anchors.anchorIsValid(this.source);
if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
throw new Error(msg);
}
if (ctx.implicitKey)
return `${src} `;
}
return src;
}
};
function getAliasCount(doc, node, anchors2) {
if (identity.isAlias(node)) {
const source = node.resolve(doc);
const anchor = anchors2 && source && anchors2.get(source);
return anchor ? anchor.count * anchor.aliasCount : 0;
} else if (identity.isCollection(node)) {
let count = 0;
for (const item of node.items) {
const c = getAliasCount(doc, item, anchors2);
if (c > count)
count = c;
}
return count;
} else if (identity.isPair(node)) {
const kc = getAliasCount(doc, node.key, anchors2);
const vc = getAliasCount(doc, node.value, anchors2);
return Math.max(kc, vc);
}
return 1;
}
exports2.Alias = Alias;
}
});
// node_modules/yaml/dist/nodes/Scalar.js
var require_Scalar = __commonJS({
"node_modules/yaml/dist/nodes/Scalar.js"(exports2) {
"use strict";
var identity = require_identity();
var Node = require_Node();
var toJS = require_toJS();
var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object";
var Scalar = class extends Node.NodeBase {
constructor(value2) {
super(identity.SCALAR);
this.value = value2;
}
toJSON(arg, ctx) {
return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);
}
toString() {
return String(this.value);
}
};
Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
Scalar.PLAIN = "PLAIN";
Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";
exports2.Scalar = Scalar;
exports2.isScalarValue = isScalarValue;
}
});
// node_modules/yaml/dist/doc/createNode.js
var require_createNode = __commonJS({
"node_modules/yaml/dist/doc/createNode.js"(exports2) {
"use strict";
var Alias = require_Alias();
var identity = require_identity();
var Scalar = require_Scalar();
var defaultTagPrefix = "tag:yaml.org,2002:";
function findTagObject(value2, tagName, tags) {
if (tagName) {
const match = tags.filter((t) => t.tag === tagName);
const tagObj = match.find((t) => !t.format) ?? match[0];
if (!tagObj)
throw new Error(`Tag ${tagName} not found`);
return tagObj;
}
return tags.find((t) => t.identify?.(value2) && !t.format);
}
function createNode(value2, tagName, ctx) {
if (identity.isDocument(value2))
value2 = value2.contents;
if (identity.isNode(value2))
return value2;
if (identity.isPair(value2)) {
const map2 = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);
map2.items.push(value2);
return map2;
}
if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) {
value2 = value2.valueOf();
}
const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
let ref = void 0;
if (aliasDuplicateObjects && value2 && typeof value2 === "object") {
ref = sourceObjects.get(value2);
if (ref) {
if (!ref.anchor)
ref.anchor = onAnchor(value2);
return new Alias.Alias(ref.anchor);
} else {
ref = { anchor: null, node: null };
sourceObjects.set(value2, ref);
}
}
if (tagName?.startsWith("!!"))
tagName = defaultTagPrefix + tagName.slice(2);
let tagObj = findTagObject(value2, tagName, schema.tags);
if (!tagObj) {
if (value2 && typeof value2.toJSON === "function") {
value2 = value2.toJSON();
}
if (!value2 || typeof value2 !== "object") {
const node2 = new Scalar.Scalar(value2);
if (ref)
ref.node = node2;
return node2;
}
tagObj = value2 instanceof Map ? schema[identity.MAP] : Symbol.iterator in Object(value2) ? schema[identity.SEQ] : schema[identity.MAP];
}
if (onTagObj) {
onTagObj(tagObj);
delete ctx.onTagObj;
}
const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value2, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar.Scalar(value2);
if (tagName)
node.tag = tagName;
else if (!tagObj.default)
node.tag = tagObj.tag;
if (ref)
ref.node = node;
return node;
}
exports2.createNode = createNode;
}
});
// node_modules/yaml/dist/nodes/Collection.js
var require_Collection = __commonJS({
"node_modules/yaml/dist/nodes/Collection.js"(exports2) {
"use strict";
var createNode = require_createNode();
var identity = require_identity();
var Node = require_Node();
function collectionFromPath(schema, path, value2) {
let v = value2;
for (let i = path.length - 1; i >= 0; --i) {
const k = path[i];
if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
const a = [];
a[k] = v;
v = a;
} else {
v = /* @__PURE__ */ new Map([[k, v]]);
}
}
return createNode.createNode(v, void 0, {
aliasDuplicateObjects: false,
keepUndefined: false,
onAnchor: () => {
throw new Error("This should not happen, please report a bug.");
},
schema,
sourceObjects: /* @__PURE__ */ new Map()
});
}
var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done;
var Collection = class extends Node.NodeBase {
constructor(type, schema) {
super(type);
Object.defineProperty(this, "schema", {
value: schema,
configurable: true,
enumerable: false,
writable: true
});
}
/**
* Create a copy of this collection.
*
* @param schema - If defined, overwrites the original's schema
*/
clone(schema) {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (schema)
copy.schema = schema;
copy.items = copy.items.map((it) => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);
if (this.range)
copy.range = this.range.slice();
return copy;
}
/**
* Adds a value to the collection. For `!!map` and `!!omap` the value must
* be a Pair instance or a `{ key, value }` object, which may not have a key
* that already exists in the map.
*/
addIn(path, value2) {
if (isEmptyPath(path))
this.add(value2);
else {
const [key, ...rest] = path;
const node = this.get(key, true);
if (identity.isCollection(node))
node.addIn(rest, value2);
else if (node === void 0 && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value2));
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
}
/**
* Removes a value from the collection.
* @returns `true` if the item was found and removed.
*/
deleteIn(path) {
const [key, ...rest] = path;
if (rest.length === 0)
return this.delete(key);
const node = this.get(key, true);
if (identity.isCollection(node))
return node.deleteIn(rest);
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
/**
* Returns item at `key`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
getIn(path, keepScalar) {
const [key, ...rest] = path;
const node = this.get(key, true);
if (rest.length === 0)
return !keepScalar && identity.isScalar(node) ? node.value : node;
else
return identity.isCollection(node) ? node.getIn(rest, keepScalar) : void 0;
}
hasAllNullValues(allowScalar) {
return this.items.every((node) => {
if (!identity.isPair(node))
return false;
const n = node.value;
return n == null || allowScalar && identity.isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag;
});
}
/**
* Checks if the collection includes a value with the key `key`.
*/
hasIn(path) {
const [key, ...rest] = path;
if (rest.length === 0)
return this.has(key);
const node = this.get(key, true);
return identity.isCollection(node) ? node.hasIn(rest) : false;
}
/**
* Sets a value in this collection. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
setIn(path, value2) {
const [key, ...rest] = path;
if (rest.length === 0) {
this.set(key, value2);
} else {
const node = this.get(key, true);
if (identity.isCollection(node))
node.setIn(rest, value2);
else if (node === void 0 && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value2));
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
}
};
exports2.Collection = Collection;
exports2.collectionFromPath = collectionFromPath;
exports2.isEmptyPath = isEmptyPath;
}
});
// node_modules/yaml/dist/stringify/stringifyComment.js
var require_stringifyComment = __commonJS({
"node_modules/yaml/dist/stringify/stringifyComment.js"(exports2) {
"use strict";
var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#");
function indentComment(comment, indent) {
if (/^\n+$/.test(comment))
return comment.substring(1);
return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
}
var lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment;
exports2.indentComment = indentComment;
exports2.lineComment = lineComment;
exports2.stringifyComment = stringifyComment;
}
});
// node_modules/yaml/dist/stringify/foldFlowLines.js
var require_foldFlowLines = __commonJS({
"node_modules/yaml/dist/stringify/foldFlowLines.js"(exports2) {
"use strict";
var FOLD_FLOW = "flow";
var FOLD_BLOCK = "block";
var FOLD_QUOTED = "quoted";
function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
if (!lineWidth || lineWidth < 0)
return text;
if (lineWidth < minContentWidth)
minContentWidth = 0;
const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
if (text.length <= endStep)
return text;
const folds = [];
const escapedFolds = {};
let end = lineWidth - indent.length;
if (typeof indentAtStart === "number") {
if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
folds.push(0);
else
end = lineWidth - indentAtStart;
}
let split = void 0;
let prev = void 0;
let overflow = false;
let i = -1;
let escStart = -1;
let escEnd = -1;
if (mode === FOLD_BLOCK) {
i = consumeMoreIndentedLines(text, i, indent.length);
if (i !== -1)
end = i + endStep;
}
for (let ch; ch = text[i += 1]; ) {
if (mode === FOLD_QUOTED && ch === "\\") {
escStart = i;
switch (text[i + 1]) {
case "x":
i += 3;
break;
case "u":
i += 5;
break;
case "U":
i += 9;
break;
default:
i += 1;
}
escEnd = i;
}
if (ch === "\n") {
if (mode === FOLD_BLOCK)
i = consumeMoreIndentedLines(text, i, indent.length);
end = i + indent.length + endStep;
split = void 0;
} else {
if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") {
const next = text[i + 1];
if (next && next !== " " && next !== "\n" && next !== " ")
split = i;
}
if (i >= end) {
if (split) {
folds.push(split);
end = split + endStep;
split = void 0;
} else if (mode === FOLD_QUOTED) {
while (prev === " " || prev === " ") {
prev = ch;
ch = text[i += 1];
overflow = true;
}
const j = i > escEnd + 1 ? i - 2 : escStart - 1;
if (escapedFolds[j])
return text;
folds.push(j);
escapedFolds[j] = true;
end = j + endStep;
split = void 0;
} else {
overflow = true;
}
}
}
prev = ch;
}
if (overflow && onOverflow)
onOverflow();
if (folds.length === 0)
return text;
if (onFold)
onFold();
let res = text.slice(0, folds[0]);
for (let i2 = 0; i2 < folds.length; ++i2) {
const fold = folds[i2];
const end2 = folds[i2 + 1] || text.length;
if (fold === 0)
res = `
${indent}${text.slice(0, end2)}`;
else {
if (mode === FOLD_QUOTED && escapedFolds[fold])
res += `${text[fold]}\\`;
res += `
${indent}${text.slice(fold + 1, end2)}`;
}
}
return res;
}
function consumeMoreIndentedLines(text, i, indent) {
let end = i;
let start = i + 1;
let ch = text[start];
while (ch === " " || ch === " ") {
if (i < start + indent) {
ch = text[++i];
} else {
do {
ch = text[++i];
} while (ch && ch !== "\n");
end = i;
start = i + 1;
ch = text[start];
}
}
return end;
}
exports2.FOLD_BLOCK = FOLD_BLOCK;
exports2.FOLD_FLOW = FOLD_FLOW;
exports2.FOLD_QUOTED = FOLD_QUOTED;
exports2.foldFlowLines = foldFlowLines;
}
});
// node_modules/yaml/dist/stringify/stringifyString.js
var require_stringifyString = __commonJS({
"node_modules/yaml/dist/stringify/stringifyString.js"(exports2) {
"use strict";
var Scalar = require_Scalar();
var foldFlowLines = require_foldFlowLines();
var getFoldOptions = (ctx, isBlock) => ({
indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
lineWidth: ctx.options.lineWidth,
minContentWidth: ctx.options.minContentWidth
});
var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
function lineLengthOverLimit(str, lineWidth, indentLength) {
if (!lineWidth || lineWidth < 0)
return false;
const limit = lineWidth - indentLength;
const strLen = str.length;
if (strLen <= limit)
return false;
for (let i = 0, start = 0; i < strLen; ++i) {
if (str[i] === "\n") {
if (i - start > limit)
return true;
start = i + 1;
if (strLen - start <= limit)
return false;
}
}
return true;
}
function doubleQuotedString(value2, ctx) {
const json = JSON.stringify(value2);
if (ctx.options.doubleQuotedAsJSON)
return json;
const { implicitKey } = ctx;
const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : "");
let str = "";
let start = 0;
for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") {
str += json.slice(start, i) + "\\ ";
i += 1;
start = i;
ch = "\\";
}
if (ch === "\\")
switch (json[i + 1]) {
case "u":
{
str += json.slice(start, i);
const code = json.substr(i + 2, 4);
switch (code) {
case "0000":
str += "\\0";
break;
case "0007":
str += "\\a";
break;
case "000b":
str += "\\v";
break;
case "001b":
str += "\\e";
break;
case "0085":
str += "\\N";
break;
case "00a0":
str += "\\_";
break;
case "2028":
str += "\\L";
break;
case "2029":
str += "\\P";
break;
default:
if (code.substr(0, 2) === "00")
str += "\\x" + code.substr(2);
else
str += json.substr(i, 6);
}
i += 5;
start = i + 1;
}
break;
case "n":
if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
i += 1;
} else {
str += json.slice(start, i) + "\n\n";
while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') {
str += "\n";
i += 2;
}
str += indent;
if (json[i + 2] === " ")
str += "\\";
i += 1;
start = i + 1;
}
break;
default:
i += 1;
}
}
str = start ? str + json.slice(start) : json;
return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));
}
function singleQuotedString(value2, ctx) {
if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2))
return doubleQuotedString(value2, ctx);
const indent = ctx.indent || (containsDocumentMarker(value2) ? " " : "");
const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$&
${indent}`) + "'";
return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
}
function quotedString(value2, ctx) {
const { singleQuote } = ctx.options;
let qs;
if (singleQuote === false)
qs = doubleQuotedString;
else {
const hasDouble = value2.includes('"');
const hasSingle = value2.includes("'");
if (hasDouble && !hasSingle)
qs = singleQuotedString;
else if (hasSingle && !hasDouble)
qs = doubleQuotedString;
else
qs = singleQuote ? singleQuotedString : doubleQuotedString;
}
return qs(value2, ctx);
}
var blockEndNewlines;
try {
blockEndNewlines = new RegExp("(^|(?<!\n))\n+(?!\n|$)", "g");
} catch {
blockEndNewlines = /\n+(?!\n|$)/g;
}
function blockString({ comment, type, value: value2 }, ctx, onComment, onChompKeep) {
const { blockQuote, commentString, lineWidth } = ctx.options;
if (!blockQuote || /\n[\t ]+$/.test(value2) || /^\s*$/.test(value2)) {
return quotedString(value2, ctx);
}
const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value2) ? " " : "");
const literal = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.Scalar.BLOCK_FOLDED ? false : type === Scalar.Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value2, lineWidth, indent.length);
if (!value2)
return literal ? "|\n" : ">\n";
let chomp;
let endStart;
for (endStart = value2.length; endStart > 0; --endStart) {
const ch = value2[endStart - 1];
if (ch !== "\n" && ch !== " " && ch !== " ")
break;
}
let end = value2.substring(endStart);
const endNlPos = end.indexOf("\n");
if (endNlPos === -1) {
chomp = "-";
} else if (value2 === end || endNlPos !== end.length - 1) {
chomp = "+";
if (onChompKeep)
onChompKeep();
} else {
chomp = "";
}
if (end) {
value2 = value2.slice(0, -end.length);
if (end[end.length - 1] === "\n")
end = end.slice(0, -1);
end = end.replace(blockEndNewlines, `$&${indent}`);
}
let startWithSpace = false;
let startEnd;
let startNlPos = -1;
for (startEnd = 0; startEnd < value2.length; ++startEnd) {
const ch = value2[startEnd];
if (ch === " ")
startWithSpace = true;
else if (ch === "\n")
startNlPos = startEnd;
else
break;
}
let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
if (start) {
value2 = value2.substring(start.length);
start = start.replace(/\n+/g, `$&${indent}`);
}
const indentSize = indent ? "2" : "1";
let header = (literal ? "|" : ">") + (startWithSpace ? indentSize : "") + chomp;
if (comment) {
header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " "));
if (onComment)
onComment();
}
if (literal) {
value2 = value2.replace(/\n+/g, `$&${indent}`);
return `${header}
${indent}${start}${value2}${end}`;
}
value2 = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
const body = foldFlowLines.foldFlowLines(`${start}${value2}${end}`, indent, foldFlowLines.FOLD_BLOCK, getFoldOptions(ctx, true));
return `${header}
${indent}${body}`;
}
function plainString(item, ctx, onComment, onChompKeep) {
const { type, value: value2 } = item;
const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) {
return quotedString(value2, ctx);
}
if (!value2 || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) {
return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep);
}
if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value2.includes("\n")) {
return blockString(item, ctx, onComment, onChompKeep);
}
if (containsDocumentMarker(value2)) {
if (indent === "") {
ctx.forceBlockIndent = true;
return blockString(item, ctx, onComment, onChompKeep);
} else if (implicitKey && indent === indentStep) {
return quotedString(value2, ctx);
}
}
const str = value2.replace(/\n+/g, `$&
${indent}`);
if (actualString) {
const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str);
const { compat, tags } = ctx.doc.schema;
if (tags.some(test) || compat?.some(test))
return quotedString(value2, ctx);
}
return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));
}
function stringifyString(item, ctx, onComment, onChompKeep) {
const { implicitKey, inFlow } = ctx;
const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
let { type } = item;
if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
type = Scalar.Scalar.QUOTE_DOUBLE;
}
const _stringify = (_type) => {
switch (_type) {
case Scalar.Scalar.BLOCK_FOLDED:
case Scalar.Scalar.BLOCK_LITERAL:
return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
case Scalar.Scalar.QUOTE_DOUBLE:
return doubleQuotedString(ss.value, ctx);
case Scalar.Scalar.QUOTE_SINGLE:
return singleQuotedString(ss.value, ctx);
case Scalar.Scalar.PLAIN:
return plainString(ss, ctx, onComment, onChompKeep);
default:
return null;
}
};
let res = _stringify(type);
if (res === null) {
const { defaultKeyType, defaultStringType } = ctx.options;
const t = implicitKey && defaultKeyType || defaultStringType;
res = _stringify(t);
if (res === null)
throw new Error(`Unsupported default string type ${t}`);
}
return res;
}
exports2.stringifyString = stringifyString;
}
});
// node_modules/yaml/dist/stringify/stringify.js
var require_stringify = __commonJS({
"node_modules/yaml/dist/stringify/stringify.js"(exports2) {
"use strict";
var anchors = require_anchors();
var identity = require_identity();
var stringifyComment = require_stringifyComment();
var stringifyString = require_stringifyString();
function createStringifyContext(doc, options) {
const opt = Object.assign({
blockQuote: true,
commentString: stringifyComment.stringifyComment,
defaultKeyType: null,
defaultStringType: "PLAIN",
directives: null,
doubleQuotedAsJSON: false,
doubleQuotedMinMultiLineLength: 40,
falseStr: "false",
flowCollectionPadding: true,
indentSeq: true,
lineWidth: 80,
minContentWidth: 20,
nullStr: "null",
simpleKeys: false,
singleQuote: null,
trueStr: "true",
verifyAliasOrder: true
}, doc.schema.toStringOptions, options);
let inFlow;
switch (opt.collectionStyle) {
case "block":
inFlow = false;
break;
case "flow":
inFlow = true;
break;
default:
inFlow = null;
}
return {
anchors: /* @__PURE__ */ new Set(),
doc,
flowCollectionPadding: opt.flowCollectionPadding ? " " : "",
indent: "",
indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ",
inFlow,
options: opt
};
}
function getTagObject(tags, item) {
if (item.tag) {
const match = tags.filter((t) => t.tag === item.tag);
if (match.length > 0)
return match.find((t) => t.format === item.format) ?? match[0];
}
let tagObj = void 0;
let obj;
if (identity.isScalar(item)) {
obj = item.value;
const match = tags.filter((t) => t.identify?.(obj));
tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format);
} else {
obj = item;
tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass);
}
if (!tagObj) {
const name = obj?.constructor?.name ?? typeof obj;
throw new Error(`Tag not resolved for ${name} value`);
}
return tagObj;
}
function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {
if (!doc.directives)
return "";
const props = [];
const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;
if (anchor && anchors.anchorIsValid(anchor)) {
anchors$1.add(anchor);
props.push(`&${anchor}`);
}
const tag = node.tag ? node.tag : tagObj.default ? null : tagObj.tag;
if (tag)
props.push(doc.directives.tagString(tag));
return props.join(" ");
}
function stringify2(item, ctx, onComment, onChompKeep) {
if (identity.isPair(item))
return item.toString(ctx, onComment, onChompKeep);
if (identity.isAlias(item)) {
if (ctx.doc.directives)
return item.toString(ctx);
if (ctx.resolvedAliases?.has(item)) {
throw new TypeError(`Cannot stringify circular structure without alias nodes`);
} else {
if (ctx.resolvedAliases)
ctx.resolvedAliases.add(item);
else
ctx.resolvedAliases = /* @__PURE__ */ new Set([item]);
item = item.resolve(ctx.doc);
}
}
let tagObj = void 0;
const node = identity.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o });
if (!tagObj)
tagObj = getTagObject(ctx.doc.schema.tags, node);
const props = stringifyProps(node, tagObj, ctx);
if (props.length > 0)
ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep);
if (!props)
return str;
return identity.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}
${ctx.indent}${str}`;
}
exports2.createStringifyContext = createStringifyContext;
exports2.stringify = stringify2;
}
});
// node_modules/yaml/dist/stringify/stringifyPair.js
var require_stringifyPair = __commonJS({
"node_modules/yaml/dist/stringify/stringifyPair.js"(exports2) {
"use strict";
var identity = require_identity();
var Scalar = require_Scalar();
var stringify2 = require_stringify();
var stringifyComment = require_stringifyComment();
function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) {
const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
let keyComment = identity.isNode(key) && key.comment || null;
if (simpleKeys) {
if (keyComment) {
throw new Error("With simple keys, key nodes cannot have comments");
}
if (identity.isCollection(key) || !identity.isNode(key) && typeof key === "object") {
const msg = "With simple keys, collection cannot be used as a key value";
throw new Error(msg);
}
}
let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || identity.isCollection(key) || (identity.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object"));
ctx = Object.assign({}, ctx, {
allNullValues: false,
implicitKey: !explicitKey && (simpleKeys || !allNullValues),
indent: indent + indentStep
});
let keyCommentDone = false;
let chompKeep = false;
let str = stringify2.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true);
if (!explicitKey && !ctx.inFlow && str.length > 1024) {
if (simpleKeys)
throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
explicitKey = true;
}
if (ctx.inFlow) {
if (allNullValues || value2 == null) {
if (keyCommentDone && onComment)
onComment();
return str === "" ? "?" : explicitKey ? `? ${str}` : str;
}
} else if (allNullValues && !simpleKeys || value2 == null && explicitKey) {
str = `? ${str}`;
if (keyComment && !keyCommentDone) {
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
} else if (chompKeep && onChompKeep)
onChompKeep();
return str;
}
if (keyCommentDone)
keyComment = null;
if (explicitKey) {
if (keyComment)
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
str = `? ${str}
${indent}:`;
} else {
str = `${str}:`;
if (keyComment)
str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));
}
let vsb, vcb, valueComment;
if (identity.isNode(value2)) {
vsb = !!value2.spaceBefore;
vcb = value2.commentBefore;
valueComment = value2.comment;
} else {
vsb = false;
vcb = null;
valueComment = null;
if (value2 && typeof value2 === "object")
value2 = doc.createNode(value2);
}
ctx.implicitKey = false;
if (!explicitKey && !keyComment && identity.isScalar(value2))
ctx.indentAtStart = str.length + 1;
chompKeep = false;
if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity.isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) {
ctx.indent = ctx.indent.substring(2);
}
let valueCommentDone = false;
const valueStr = stringify2.stringify(value2, ctx, () => valueCommentDone = true, () => chompKeep = true);
let ws = " ";
if (keyComment || vsb || vcb) {
ws = vsb ? "\n" : "";
if (vcb) {
const cs = commentString(vcb);
ws += `
${stringifyComment.indentComment(cs, ctx.indent)}`;
}
if (valueStr === "" && !ctx.inFlow) {
if (ws === "\n")
ws = "\n\n";
} else {
ws += `
${ctx.indent}`;
}
} else if (!explicitKey && identity.isCollection(value2)) {
const vs0 = valueStr[0];
const nl0 = valueStr.indexOf("\n");
const hasNewline = nl0 !== -1;
const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0;
if (hasNewline || !flow) {
let hasPropsLine = false;
if (hasNewline && (vs0 === "&" || vs0 === "!")) {
let sp0 = valueStr.indexOf(" ");
if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
sp0 = valueStr.indexOf(" ", sp0 + 1);
}
if (sp0 === -1 || nl0 < sp0)
hasPropsLine = true;
}
if (!hasPropsLine)
ws = `
${ctx.indent}`;
}
} else if (valueStr === "" || valueStr[0] === "\n") {
ws = "";
}
str += ws + valueStr;
if (ctx.inFlow) {
if (valueCommentDone && onComment)
onComment();
} else if (valueComment && !valueCommentDone) {
str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));
} else if (chompKeep && onChompKeep) {
onChompKeep();
}
return str;
}
exports2.stringifyPair = stringifyPair;
}
});
// node_modules/yaml/dist/log.js
var require_log = __commonJS({
"node_modules/yaml/dist/log.js"(exports2) {
"use strict";
function debug12(logLevel, ...messages) {
if (logLevel === "debug")
console.log(...messages);
}
function warn(logLevel, warning) {
if (logLevel === "debug" || logLevel === "warn") {
if (typeof process !== "undefined" && process.emitWarning)
process.emitWarning(warning);
else
console.warn(warning);
}
}
exports2.debug = debug12;
exports2.warn = warn;
}
});
// node_modules/yaml/dist/nodes/addPairToJSMap.js
var require_addPairToJSMap = __commonJS({
"node_modules/yaml/dist/nodes/addPairToJSMap.js"(exports2) {
"use strict";
var log = require_log();
var stringify2 = require_stringify();
var identity = require_identity();
var Scalar = require_Scalar();
var toJS = require_toJS();
var MERGE_KEY = "<<";
function addPairToJSMap(ctx, map2, { key, value: value2 }) {
if (ctx?.doc.schema.merge && isMergeKey(key)) {
value2 = identity.isAlias(value2) ? value2.resolve(ctx.doc) : value2;
if (identity.isSeq(value2))
for (const it of value2.items)
mergeToJSMap(ctx, map2, it);
else if (Array.isArray(value2))
for (const it of value2)
mergeToJSMap(ctx, map2, it);
else
mergeToJSMap(ctx, map2, value2);
} else {
const jsKey = toJS.toJS(key, "", ctx);
if (map2 instanceof Map) {
map2.set(jsKey, toJS.toJS(value2, jsKey, ctx));
} else if (map2 instanceof Set) {
map2.add(jsKey);
} else {
const stringKey = stringifyKey(key, jsKey, ctx);
const jsValue = toJS.toJS(value2, stringKey, ctx);
if (stringKey in map2)
Object.defineProperty(map2, stringKey, {
value: jsValue,
writable: true,
enumerable: true,
configurable: true
});
else
map2[stringKey] = jsValue;
}
}
return map2;
}
var isMergeKey = (key) => key === MERGE_KEY || identity.isScalar(key) && key.value === MERGE_KEY && (!key.type || key.type === Scalar.Scalar.PLAIN);
function mergeToJSMap(ctx, map2, value2) {
const source = ctx && identity.isAlias(value2) ? value2.resolve(ctx.doc) : value2;
if (!identity.isMap(source))
throw new Error("Merge sources must be maps or map aliases");
const srcMap = source.toJSON(null, ctx, Map);
for (const [key, value3] of srcMap) {
if (map2 instanceof Map) {
if (!map2.has(key))
map2.set(key, value3);
} else if (map2 instanceof Set) {
map2.add(key);
} else if (!Object.prototype.hasOwnProperty.call(map2, key)) {
Object.defineProperty(map2, key, {
value: value3,
writable: true,
enumerable: true,
configurable: true
});
}
}
return map2;
}
function stringifyKey(key, jsKey, ctx) {
if (jsKey === null)
return "";
if (typeof jsKey !== "object")
return String(jsKey);
if (identity.isNode(key) && ctx?.doc) {
const strCtx = stringify2.createStringifyContext(ctx.doc, {});
strCtx.anchors = /* @__PURE__ */ new Set();
for (const node of ctx.anchors.keys())
strCtx.anchors.add(node.anchor);
strCtx.inFlow = true;
strCtx.inStringifyKey = true;
const strKey = key.toString(strCtx);
if (!ctx.mapKeyWarned) {
let jsonStr = JSON.stringify(strKey);
if (jsonStr.length > 40)
jsonStr = jsonStr.substring(0, 36) + '..."';
log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
ctx.mapKeyWarned = true;
}
return strKey;
}
return JSON.stringify(jsKey);
}
exports2.addPairToJSMap = addPairToJSMap;
}
});
// node_modules/yaml/dist/nodes/Pair.js
var require_Pair = __commonJS({
"node_modules/yaml/dist/nodes/Pair.js"(exports2) {
"use strict";
var createNode = require_createNode();
var stringifyPair = require_stringifyPair();
var addPairToJSMap = require_addPairToJSMap();
var identity = require_identity();
function createPair(key, value2, ctx) {
const k = createNode.createNode(key, void 0, ctx);
const v = createNode.createNode(value2, void 0, ctx);
return new Pair(k, v);
}
var Pair = class _Pair {
constructor(key, value2 = null) {
Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });
this.key = key;
this.value = value2;
}
clone(schema) {
let { key, value: value2 } = this;
if (identity.isNode(key))
key = key.clone(schema);
if (identity.isNode(value2))
value2 = value2.clone(schema);
return new _Pair(key, value2);
}
toJSON(_, ctx) {
const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
return addPairToJSMap.addPairToJSMap(ctx, pair, this);
}
toString(ctx, onComment, onChompKeep) {
return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
}
};
exports2.Pair = Pair;
exports2.createPair = createPair;
}
});
// node_modules/yaml/dist/stringify/stringifyCollection.js
var require_stringifyCollection = __commonJS({
"node_modules/yaml/dist/stringify/stringifyCollection.js"(exports2) {
"use strict";
var identity = require_identity();
var stringify2 = require_stringify();
var stringifyComment = require_stringifyComment();
function stringifyCollection(collection, ctx, options) {
const flow = ctx.inFlow ?? collection.flow;
const stringify3 = flow ? stringifyFlowCollection : stringifyBlockCollection;
return stringify3(collection, ctx, options);
}
function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
const { indent, options: { commentString } } = ctx;
const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
let chompKeep = false;
const lines = [];
for (let i = 0; i < items.length; ++i) {
const item = items[i];
let comment2 = null;
if (identity.isNode(item)) {
if (!chompKeep && item.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
if (item.comment)
comment2 = item.comment;
} else if (identity.isPair(item)) {
const ik = identity.isNode(item.key) ? item.key : null;
if (ik) {
if (!chompKeep && ik.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
}
}
chompKeep = false;
let str2 = stringify2.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true);
if (comment2)
str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2));
if (chompKeep && comment2)
chompKeep = false;
lines.push(blockItemPrefix + str2);
}
let str;
if (lines.length === 0) {
str = flowChars.start + flowChars.end;
} else {
str = lines[0];
for (let i = 1; i < lines.length; ++i) {
const line = lines[i];
str += line ? `
${indent}${line}` : "\n";
}
}
if (comment) {
str += "\n" + stringifyComment.indentComment(commentString(comment), indent);
if (onComment)
onComment();
} else if (chompKeep && onChompKeep)
onChompKeep();
return str;
}
function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
itemIndent += indentStep;
const itemCtx = Object.assign({}, ctx, {
indent: itemIndent,
inFlow: true,
type: null
});
let reqNewline = false;
let linesAtValue = 0;
const lines = [];
for (let i = 0; i < items.length; ++i) {
const item = items[i];
let comment = null;
if (identity.isNode(item)) {
if (item.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, item.commentBefore, false);
if (item.comment)
comment = item.comment;
} else if (identity.isPair(item)) {
const ik = identity.isNode(item.key) ? item.key : null;
if (ik) {
if (ik.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, ik.commentBefore, false);
if (ik.comment)
reqNewline = true;
}
const iv = identity.isNode(item.value) ? item.value : null;
if (iv) {
if (iv.comment)
comment = iv.comment;
if (iv.commentBefore)
reqNewline = true;
} else if (item.value == null && ik?.comment) {
comment = ik.comment;
}
}
if (comment)
reqNewline = true;
let str = stringify2.stringify(item, itemCtx, () => comment = null);
if (i < items.length - 1)
str += ",";
if (comment)
str += stringifyComment.lineComment(str, itemIndent, commentString(comment));
if (!reqNewline && (lines.length > linesAtValue || str.includes("\n")))
reqNewline = true;
lines.push(str);
linesAtValue = lines.length;
}
const { start, end } = flowChars;
if (lines.length === 0) {
return start + end;
} else {
if (!reqNewline) {
const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
}
if (reqNewline) {
let str = start;
for (const line of lines)
str += line ? `
${indentStep}${indent}${line}` : "\n";
return `${str}
${indent}${end}`;
} else {
return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`;
}
}
}
function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
if (comment && chompKeep)
comment = comment.replace(/^\n+/, "");
if (comment) {
const ic = stringifyComment.indentComment(commentString(comment), indent);
lines.push(ic.trimStart());
}
}
exports2.stringifyCollection = stringifyCollection;
}
});
// node_modules/yaml/dist/nodes/YAMLMap.js
var require_YAMLMap = __commonJS({
"node_modules/yaml/dist/nodes/YAMLMap.js"(exports2) {
"use strict";
var stringifyCollection = require_stringifyCollection();
var addPairToJSMap = require_addPairToJSMap();
var Collection = require_Collection();
var identity = require_identity();
var Pair = require_Pair();
var Scalar = require_Scalar();
function findPair(items, key) {
const k = identity.isScalar(key) ? key.value : key;
for (const it of items) {
if (identity.isPair(it)) {
if (it.key === key || it.key === k)
return it;
if (identity.isScalar(it.key) && it.key.value === k)
return it;
}
}
return void 0;
}
var YAMLMap = class extends Collection.Collection {
static get tagName() {
return "tag:yaml.org,2002:map";
}
constructor(schema) {
super(identity.MAP, schema);
this.items = [];
}
/**
* A generic collection parsing method that can be extended
* to other node classes that inherit from YAMLMap
*/
static from(schema, obj, ctx) {
const { keepUndefined, replacer } = ctx;
const map2 = new this(schema);
const add = (key, value2) => {
if (typeof replacer === "function")
value2 = replacer.call(obj, key, value2);
else if (Array.isArray(replacer) && !replacer.includes(key))
return;
if (value2 !== void 0 || keepUndefined)
map2.items.push(Pair.createPair(key, value2, ctx));
};
if (obj instanceof Map) {
for (const [key, value2] of obj)
add(key, value2);
} else if (obj && typeof obj === "object") {
for (const key of Object.keys(obj))
add(key, obj[key]);
}
if (typeof schema.sortMapEntries === "function") {
map2.items.sort(schema.sortMapEntries);
}
return map2;
}
/**
* Adds a value to the collection.
*
* @param overwrite - If not set `true`, using a key that is already in the
* collection will throw. Otherwise, overwrites the previous value.
*/
add(pair, overwrite) {
let _pair;
if (identity.isPair(pair))
_pair = pair;
else if (!pair || typeof pair !== "object" || !("key" in pair)) {
_pair = new Pair.Pair(pair, pair?.value);
} else
_pair = new Pair.Pair(pair.key, pair.value);
const prev = findPair(this.items, _pair.key);
const sortEntries = this.schema?.sortMapEntries;
if (prev) {
if (!overwrite)
throw new Error(`Key ${_pair.key} already set`);
if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))
prev.value.value = _pair.value;
else
prev.value = _pair.value;
} else if (sortEntries) {
const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
if (i === -1)
this.items.push(_pair);
else
this.items.splice(i, 0, _pair);
} else {
this.items.push(_pair);
}
}
delete(key) {
const it = findPair(this.items, key);
if (!it)
return false;
const del = this.items.splice(this.items.indexOf(it), 1);
return del.length > 0;
}
get(key, keepScalar) {
const it = findPair(this.items, key);
const node = it?.value;
return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? void 0;
}
has(key) {
return !!findPair(this.items, key);
}
set(key, value2) {
this.add(new Pair.Pair(key, value2), true);
}
/**
* @param ctx - Conversion context, originally set in Document#toJS()
* @param {Class} Type - If set, forces the returned collection type
* @returns Instance of Type, Map, or Object
*/
toJSON(_, ctx, Type) {
const map2 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
if (ctx?.onCreate)
ctx.onCreate(map2);
for (const item of this.items)
addPairToJSMap.addPairToJSMap(ctx, map2, item);
return map2;
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
for (const item of this.items) {
if (!identity.isPair(item))
throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
}
if (!ctx.allNullValues && this.hasAllNullValues(false))
ctx = Object.assign({}, ctx, { allNullValues: true });
return stringifyCollection.stringifyCollection(this, ctx, {
blockItemPrefix: "",
flowChars: { start: "{", end: "}" },
itemIndent: ctx.indent || "",
onChompKeep,
onComment
});
}
};
exports2.YAMLMap = YAMLMap;
exports2.findPair = findPair;
}
});
// node_modules/yaml/dist/schema/common/map.js
var require_map = __commonJS({
"node_modules/yaml/dist/schema/common/map.js"(exports2) {
"use strict";
var identity = require_identity();
var YAMLMap = require_YAMLMap();
var map2 = {
collection: "map",
default: true,
nodeClass: YAMLMap.YAMLMap,
tag: "tag:yaml.org,2002:map",
resolve(map3, onError) {
if (!identity.isMap(map3))
onError("Expected a mapping for this tag");
return map3;
},
createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)
};
exports2.map = map2;
}
});
// node_modules/yaml/dist/nodes/YAMLSeq.js
var require_YAMLSeq = __commonJS({
"node_modules/yaml/dist/nodes/YAMLSeq.js"(exports2) {
"use strict";
var createNode = require_createNode();
var stringifyCollection = require_stringifyCollection();
var Collection = require_Collection();
var identity = require_identity();
var Scalar = require_Scalar();
var toJS = require_toJS();
var YAMLSeq = class extends Collection.Collection {
static get tagName() {
return "tag:yaml.org,2002:seq";
}
constructor(schema) {
super(identity.SEQ, schema);
this.items = [];
}
add(value2) {
this.items.push(value2);
}
/**
* Removes a value from the collection.
*
* `key` must contain a representation of an integer for this to succeed.
* It may be wrapped in a `Scalar`.
*
* @returns `true` if the item was found and removed.
*/
delete(key) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
return false;
const del = this.items.splice(idx, 1);
return del.length > 0;
}
get(key, keepScalar) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
return void 0;
const it = this.items[idx];
return !keepScalar && identity.isScalar(it) ? it.value : it;
}
/**
* Checks if the collection includes a value with the key `key`.
*
* `key` must contain a representation of an integer for this to succeed.
* It may be wrapped in a `Scalar`.
*/
has(key) {
const idx = asItemIndex(key);
return typeof idx === "number" && idx < this.items.length;
}
/**
* Sets a value in this collection. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*
* If `key` does not contain a representation of an integer, this will throw.
* It may be wrapped in a `Scalar`.
*/
set(key, value2) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
throw new Error(`Expected a valid index, not ${key}.`);
const prev = this.items[idx];
if (identity.isScalar(prev) && Scalar.isScalarValue(value2))
prev.value = value2;
else
this.items[idx] = value2;
}
toJSON(_, ctx) {
const seq = [];
if (ctx?.onCreate)
ctx.onCreate(seq);
let i = 0;
for (const item of this.items)
seq.push(toJS.toJS(item, String(i++), ctx));
return seq;
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
return stringifyCollection.stringifyCollection(this, ctx, {
blockItemPrefix: "- ",
flowChars: { start: "[", end: "]" },
itemIndent: (ctx.indent || "") + " ",
onChompKeep,
onComment
});
}
static from(schema, obj, ctx) {
const { replacer } = ctx;
const seq = new this(schema);
if (obj && Symbol.iterator in Object(obj)) {
let i = 0;
for (let it of obj) {
if (typeof replacer === "function") {
const key = obj instanceof Set ? it : String(i++);
it = replacer.call(obj, key, it);
}
seq.items.push(createNode.createNode(it, void 0, ctx));
}
}
return seq;
}
};
function asItemIndex(key) {
let idx = identity.isScalar(key) ? key.value : key;
if (idx && typeof idx === "string")
idx = Number(idx);
return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
}
exports2.YAMLSeq = YAMLSeq;
}
});
// node_modules/yaml/dist/schema/common/seq.js
var require_seq = __commonJS({
"node_modules/yaml/dist/schema/common/seq.js"(exports2) {
"use strict";
var identity = require_identity();
var YAMLSeq = require_YAMLSeq();
var seq = {
collection: "seq",
default: true,
nodeClass: YAMLSeq.YAMLSeq,
tag: "tag:yaml.org,2002:seq",
resolve(seq2, onError) {
if (!identity.isSeq(seq2))
onError("Expected a sequence for this tag");
return seq2;
},
createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)
};
exports2.seq = seq;
}
});
// node_modules/yaml/dist/schema/common/string.js
var require_string = __commonJS({
"node_modules/yaml/dist/schema/common/string.js"(exports2) {
"use strict";
var stringifyString = require_stringifyString();
var string = {
identify: (value2) => typeof value2 === "string",
default: true,
tag: "tag:yaml.org,2002:str",
resolve: (str) => str,
stringify(item, ctx, onComment, onChompKeep) {
ctx = Object.assign({ actualString: true }, ctx);
return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);
}
};
exports2.string = string;
}
});
// node_modules/yaml/dist/schema/common/null.js
var require_null = __commonJS({
"node_modules/yaml/dist/schema/common/null.js"(exports2) {
"use strict";
var Scalar = require_Scalar();
var nullTag = {
identify: (value2) => value2 == null,
createNode: () => new Scalar.Scalar(null),
default: true,
tag: "tag:yaml.org,2002:null",
test: /^(?:~|[Nn]ull|NULL)?$/,
resolve: () => new Scalar.Scalar(null),
stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr
};
exports2.nullTag = nullTag;
}
});
// node_modules/yaml/dist/schema/core/bool.js
var require_bool = __commonJS({
"node_modules/yaml/dist/schema/core/bool.js"(exports2) {
"use strict";
var Scalar = require_Scalar();
var boolTag = {
identify: (value2) => typeof value2 === "boolean",
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"),
stringify({ source, value: value2 }, ctx) {
if (source && boolTag.test.test(source)) {
const sv = source[0] === "t" || source[0] === "T";
if (value2 === sv)
return source;
}
return value2 ? ctx.options.trueStr : ctx.options.falseStr;
}
};
exports2.boolTag = boolTag;
}
});
// node_modules/yaml/dist/stringify/stringifyNumber.js
var require_stringifyNumber = __commonJS({
"node_modules/yaml/dist/stringify/stringifyNumber.js"(exports2) {
"use strict";
function stringifyNumber({ format, minFractionDigits, tag, value: value2 }) {
if (typeof value2 === "bigint")
return String(value2);
const num = typeof value2 === "number" ? value2 : Number(value2);
if (!isFinite(num))
return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
let n = JSON.stringify(value2);
if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n)) {
let i = n.indexOf(".");
if (i < 0) {
i = n.length;
n += ".";
}
let d = minFractionDigits - (n.length - i - 1);
while (d-- > 0)
n += "0";
}
return n;
}
exports2.stringifyNumber = stringifyNumber;
}
});
// node_modules/yaml/dist/schema/core/float.js
var require_float = __commonJS({
"node_modules/yaml/dist/schema/core/float.js"(exports2) {
"use strict";
var Scalar = require_Scalar();
var stringifyNumber = require_stringifyNumber();
var floatNaN = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
stringify: stringifyNumber.stringifyNumber
};
var floatExp = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
format: "EXP",
test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
resolve: (str) => parseFloat(str),
stringify(node) {
const num = Number(node.value);
return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
}
};
var float = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
resolve(str) {
const node = new Scalar.Scalar(parseFloat(str));
const dot = str.indexOf(".");
if (dot !== -1 && str[str.length - 1] === "0")
node.minFractionDigits = str.length - dot - 1;
return node;
},
stringify: stringifyNumber.stringifyNumber
};
exports2.float = float;
exports2.floatExp = floatExp;
exports2.floatNaN = floatNaN;
}
});
// node_modules/yaml/dist/schema/core/int.js
var require_int = __commonJS({
"node_modules/yaml/dist/schema/core/int.js"(exports2) {
"use strict";
var stringifyNumber = require_stringifyNumber();
var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2);
var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix);
function intStringify(node, radix, prefix) {
const { value: value2 } = node;
if (intIdentify(value2) && value2 >= 0)
return prefix + value2.toString(radix);
return stringifyNumber.stringifyNumber(node);
}
var intOct = {
identify: (value2) => intIdentify(value2) && value2 >= 0,
default: true,
tag: "tag:yaml.org,2002:int",
format: "OCT",
test: /^0o[0-7]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),
stringify: (node) => intStringify(node, 8, "0o")
};
var int = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
test: /^[-+]?[0-9]+$/,
resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
stringify: stringifyNumber.stringifyNumber
};
var intHex = {
identify: (value2) => intIdentify(value2) && value2 >= 0,
default: true,
tag: "tag:yaml.org,2002:int",
format: "HEX",
test: /^0x[0-9a-fA-F]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
stringify: (node) => intStringify(node, 16, "0x")
};
exports2.int = int;
exports2.intHex = intHex;
exports2.intOct = intOct;
}
});
// node_modules/yaml/dist/schema/core/schema.js
var require_schema = __commonJS({
"node_modules/yaml/dist/schema/core/schema.js"(exports2) {
"use strict";
var map2 = require_map();
var _null = require_null();
var seq = require_seq();
var string = require_string();
var bool = require_bool();
var float = require_float();
var int = require_int();
var schema = [
map2.map,
seq.seq,
string.string,
_null.nullTag,
bool.boolTag,
int.intOct,
int.int,
int.intHex,
float.floatNaN,
float.floatExp,
float.float
];
exports2.schema = schema;
}
});
// node_modules/yaml/dist/schema/json/schema.js
var require_schema2 = __commonJS({
"node_modules/yaml/dist/schema/json/schema.js"(exports2) {
"use strict";
var Scalar = require_Scalar();
var map2 = require_map();
var seq = require_seq();
function intIdentify(value2) {
return typeof value2 === "bigint" || Number.isInteger(value2);
}
var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2);
var jsonScalars = [
{
identify: (value2) => typeof value2 === "string",
default: true,
tag: "tag:yaml.org,2002:str",
resolve: (str) => str,
stringify: stringifyJSON
},
{
identify: (value2) => value2 == null,
createNode: () => new Scalar.Scalar(null),
default: true,
tag: "tag:yaml.org,2002:null",
test: /^null$/,
resolve: () => null,
stringify: stringifyJSON
},
{
identify: (value2) => typeof value2 === "boolean",
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^true|false$/,
resolve: (str) => str === "true",
stringify: stringifyJSON
},
{
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
test: /^-?(?:0|[1-9][0-9]*)$/,
resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
stringify: ({ value: value2 }) => intIdentify(value2) ? value2.toString() : JSON.stringify(value2)
},
{
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
resolve: (str) => parseFloat(str),
stringify: stringifyJSON
}
];
var jsonError = {
default: true,
tag: "",
test: /^/,
resolve(str, onError) {
onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
return str;
}
};
var schema = [map2.map, seq.seq].concat(jsonScalars, jsonError);
exports2.schema = schema;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/binary.js
var require_binary = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/binary.js"(exports2) {
"use strict";
var Scalar = require_Scalar();
var stringifyString = require_stringifyString();
var binary = {
identify: (value2) => value2 instanceof Uint8Array,
// Buffer inherits from Uint8Array
default: false,
tag: "tag:yaml.org,2002:binary",
/**
* Returns a Buffer in node and an Uint8Array in browsers
*
* To use the resulting buffer as an image, you'll want to do something like:
*
* const blob = new Blob([buffer], { type: 'image/jpeg' })
* document.querySelector('#photo').src = URL.createObjectURL(blob)
*/
resolve(src, onError) {
if (typeof Buffer === "function") {
return Buffer.from(src, "base64");
} else if (typeof atob === "function") {
const str = atob(src.replace(/[\n\r]/g, ""));
const buffer = new Uint8Array(str.length);
for (let i = 0; i < str.length; ++i)
buffer[i] = str.charCodeAt(i);
return buffer;
} else {
onError("This environment does not support reading binary tags; either Buffer or atob is required");
return src;
}
},
stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) {
const buf = value2;
let str;
if (typeof Buffer === "function") {
str = buf instanceof Buffer ? buf.toString("base64") : Buffer.from(buf.buffer).toString("base64");
} else if (typeof btoa === "function") {
let s = "";
for (let i = 0; i < buf.length; ++i)
s += String.fromCharCode(buf[i]);
str = btoa(s);
} else {
throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");
}
if (!type)
type = Scalar.Scalar.BLOCK_LITERAL;
if (type !== Scalar.Scalar.QUOTE_DOUBLE) {
const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
const n = Math.ceil(str.length / lineWidth);
const lines = new Array(n);
for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
lines[i] = str.substr(o, lineWidth);
}
str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? "\n" : " ");
}
return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
}
};
exports2.binary = binary;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/pairs.js
var require_pairs = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/pairs.js"(exports2) {
"use strict";
var identity = require_identity();
var Pair = require_Pair();
var Scalar = require_Scalar();
var YAMLSeq = require_YAMLSeq();
function resolvePairs(seq, onError) {
if (identity.isSeq(seq)) {
for (let i = 0; i < seq.items.length; ++i) {
let item = seq.items[i];
if (identity.isPair(item))
continue;
else if (identity.isMap(item)) {
if (item.items.length > 1)
onError("Each pair must have its own sequence indicator");
const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));
if (item.commentBefore)
pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}
${pair.key.commentBefore}` : item.commentBefore;
if (item.comment) {
const cn = pair.value ?? pair.key;
cn.comment = cn.comment ? `${item.comment}
${cn.comment}` : item.comment;
}
item = pair;
}
seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item);
}
} else
onError("Expected a sequence for this tag");
return seq;
}
function createPairs(schema, iterable, ctx) {
const { replacer } = ctx;
const pairs2 = new YAMLSeq.YAMLSeq(schema);
pairs2.tag = "tag:yaml.org,2002:pairs";
let i = 0;
if (iterable && Symbol.iterator in Object(iterable))
for (let it of iterable) {
if (typeof replacer === "function")
it = replacer.call(iterable, String(i++), it);
let key, value2;
if (Array.isArray(it)) {
if (it.length === 2) {
key = it[0];
value2 = it[1];
} else
throw new TypeError(`Expected [key, value] tuple: ${it}`);
} else if (it && it instanceof Object) {
const keys = Object.keys(it);
if (keys.length === 1) {
key = keys[0];
value2 = it[key];
} else {
throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
}
} else {
key = it;
}
pairs2.items.push(Pair.createPair(key, value2, ctx));
}
return pairs2;
}
var pairs = {
collection: "seq",
default: false,
tag: "tag:yaml.org,2002:pairs",
resolve: resolvePairs,
createNode: createPairs
};
exports2.createPairs = createPairs;
exports2.pairs = pairs;
exports2.resolvePairs = resolvePairs;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/omap.js
var require_omap = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/omap.js"(exports2) {
"use strict";
var identity = require_identity();
var toJS = require_toJS();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var pairs = require_pairs();
var YAMLOMap = class _YAMLOMap extends YAMLSeq.YAMLSeq {
constructor() {
super();
this.add = YAMLMap.YAMLMap.prototype.add.bind(this);
this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);
this.get = YAMLMap.YAMLMap.prototype.get.bind(this);
this.has = YAMLMap.YAMLMap.prototype.has.bind(this);
this.set = YAMLMap.YAMLMap.prototype.set.bind(this);
this.tag = _YAMLOMap.tag;
}
/**
* If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
* but TypeScript won't allow widening the signature of a child method.
*/
toJSON(_, ctx) {
if (!ctx)
return super.toJSON(_);
const map2 = /* @__PURE__ */ new Map();
if (ctx?.onCreate)
ctx.onCreate(map2);
for (const pair of this.items) {
let key, value2;
if (identity.isPair(pair)) {
key = toJS.toJS(pair.key, "", ctx);
value2 = toJS.toJS(pair.value, key, ctx);
} else {
key = toJS.toJS(pair, "", ctx);
}
if (map2.has(key))
throw new Error("Ordered maps must not include duplicate keys");
map2.set(key, value2);
}
return map2;
}
static from(schema, iterable, ctx) {
const pairs$1 = pairs.createPairs(schema, iterable, ctx);
const omap2 = new this();
omap2.items = pairs$1.items;
return omap2;
}
};
YAMLOMap.tag = "tag:yaml.org,2002:omap";
var omap = {
collection: "seq",
identify: (value2) => value2 instanceof Map,
nodeClass: YAMLOMap,
default: false,
tag: "tag:yaml.org,2002:omap",
resolve(seq, onError) {
const pairs$1 = pairs.resolvePairs(seq, onError);
const seenKeys = [];
for (const { key } of pairs$1.items) {
if (identity.isScalar(key)) {
if (seenKeys.includes(key.value)) {
onError(`Ordered maps must not include duplicate keys: ${key.value}`);
} else {
seenKeys.push(key.value);
}
}
}
return Object.assign(new YAMLOMap(), pairs$1);
},
createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)
};
exports2.YAMLOMap = YAMLOMap;
exports2.omap = omap;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/bool.js
var require_bool2 = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/bool.js"(exports2) {
"use strict";
var Scalar = require_Scalar();
function boolStringify({ value: value2, source }, ctx) {
const boolObj = value2 ? trueTag : falseTag;
if (source && boolObj.test.test(source))
return source;
return value2 ? ctx.options.trueStr : ctx.options.falseStr;
}
var trueTag = {
identify: (value2) => value2 === true,
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
resolve: () => new Scalar.Scalar(true),
stringify: boolStringify
};
var falseTag = {
identify: (value2) => value2 === false,
default: true,
tag: "tag:yaml.org,2002:bool",
test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
resolve: () => new Scalar.Scalar(false),
stringify: boolStringify
};
exports2.falseTag = falseTag;
exports2.trueTag = trueTag;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/float.js
var require_float2 = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/float.js"(exports2) {
"use strict";
var Scalar = require_Scalar();
var stringifyNumber = require_stringifyNumber();
var floatNaN = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
stringify: stringifyNumber.stringifyNumber
};
var floatExp = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
format: "EXP",
test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
resolve: (str) => parseFloat(str.replace(/_/g, "")),
stringify(node) {
const num = Number(node.value);
return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);
}
};
var float = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
resolve(str) {
const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, "")));
const dot = str.indexOf(".");
if (dot !== -1) {
const f = str.substring(dot + 1).replace(/_/g, "");
if (f[f.length - 1] === "0")
node.minFractionDigits = f.length;
}
return node;
},
stringify: stringifyNumber.stringifyNumber
};
exports2.float = float;
exports2.floatExp = floatExp;
exports2.floatNaN = floatNaN;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/int.js
var require_int2 = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/int.js"(exports2) {
"use strict";
var stringifyNumber = require_stringifyNumber();
var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2);
function intResolve(str, offset, radix, { intAsBigInt }) {
const sign = str[0];
if (sign === "-" || sign === "+")
offset += 1;
str = str.substring(offset).replace(/_/g, "");
if (intAsBigInt) {
switch (radix) {
case 2:
str = `0b${str}`;
break;
case 8:
str = `0o${str}`;
break;
case 16:
str = `0x${str}`;
break;
}
const n2 = BigInt(str);
return sign === "-" ? BigInt(-1) * n2 : n2;
}
const n = parseInt(str, radix);
return sign === "-" ? -1 * n : n;
}
function intStringify(node, radix, prefix) {
const { value: value2 } = node;
if (intIdentify(value2)) {
const str = value2.toString(radix);
return value2 < 0 ? "-" + prefix + str.substr(1) : prefix + str;
}
return stringifyNumber.stringifyNumber(node);
}
var intBin = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
format: "BIN",
test: /^[-+]?0b[0-1_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
stringify: (node) => intStringify(node, 2, "0b")
};
var intOct = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
format: "OCT",
test: /^[-+]?0[0-7_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
stringify: (node) => intStringify(node, 8, "0")
};
var int = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
test: /^[-+]?[0-9][0-9_]*$/,
resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
stringify: stringifyNumber.stringifyNumber
};
var intHex = {
identify: intIdentify,
default: true,
tag: "tag:yaml.org,2002:int",
format: "HEX",
test: /^[-+]?0x[0-9a-fA-F_]+$/,
resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
stringify: (node) => intStringify(node, 16, "0x")
};
exports2.int = int;
exports2.intBin = intBin;
exports2.intHex = intHex;
exports2.intOct = intOct;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/set.js
var require_set = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/set.js"(exports2) {
"use strict";
var identity = require_identity();
var Pair = require_Pair();
var YAMLMap = require_YAMLMap();
var YAMLSet = class _YAMLSet extends YAMLMap.YAMLMap {
constructor(schema) {
super(schema);
this.tag = _YAMLSet.tag;
}
add(key) {
let pair;
if (identity.isPair(key))
pair = key;
else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null)
pair = new Pair.Pair(key.key, null);
else
pair = new Pair.Pair(key, null);
const prev = YAMLMap.findPair(this.items, pair.key);
if (!prev)
this.items.push(pair);
}
/**
* If `keepPair` is `true`, returns the Pair matching `key`.
* Otherwise, returns the value of that Pair's key.
*/
get(key, keepPair) {
const pair = YAMLMap.findPair(this.items, key);
return !keepPair && identity.isPair(pair) ? identity.isScalar(pair.key) ? pair.key.value : pair.key : pair;
}
set(key, value2) {
if (typeof value2 !== "boolean")
throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`);
const prev = YAMLMap.findPair(this.items, key);
if (prev && !value2) {
this.items.splice(this.items.indexOf(prev), 1);
} else if (!prev && value2) {
this.items.push(new Pair.Pair(key));
}
}
toJSON(_, ctx) {
return super.toJSON(_, ctx, Set);
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
if (this.hasAllNullValues(true))
return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
else
throw new Error("Set items must all have null values");
}
static from(schema, iterable, ctx) {
const { replacer } = ctx;
const set2 = new this(schema);
if (iterable && Symbol.iterator in Object(iterable))
for (let value2 of iterable) {
if (typeof replacer === "function")
value2 = replacer.call(iterable, value2, value2);
set2.items.push(Pair.createPair(value2, null, ctx));
}
return set2;
}
};
YAMLSet.tag = "tag:yaml.org,2002:set";
var set = {
collection: "map",
identify: (value2) => value2 instanceof Set,
nodeClass: YAMLSet,
default: false,
tag: "tag:yaml.org,2002:set",
createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),
resolve(map2, onError) {
if (identity.isMap(map2)) {
if (map2.hasAllNullValues(true))
return Object.assign(new YAMLSet(), map2);
else
onError("Set items must all have null values");
} else
onError("Expected a mapping for this tag");
return map2;
}
};
exports2.YAMLSet = YAMLSet;
exports2.set = set;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/timestamp.js
var require_timestamp = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/timestamp.js"(exports2) {
"use strict";
var stringifyNumber = require_stringifyNumber();
function parseSexagesimal(str, asBigInt) {
const sign = str[0];
const parts2 = sign === "-" || sign === "+" ? str.substring(1) : str;
const num = (n) => asBigInt ? BigInt(n) : Number(n);
const res = parts2.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0));
return sign === "-" ? num(-1) * res : res;
}
function stringifySexagesimal(node) {
let { value: value2 } = node;
let num = (n) => n;
if (typeof value2 === "bigint")
num = (n) => BigInt(n);
else if (isNaN(value2) || !isFinite(value2))
return stringifyNumber.stringifyNumber(node);
let sign = "";
if (value2 < 0) {
sign = "-";
value2 *= num(-1);
}
const _60 = num(60);
const parts2 = [value2 % _60];
if (value2 < 60) {
parts2.unshift(0);
} else {
value2 = (value2 - parts2[0]) / _60;
parts2.unshift(value2 % _60);
if (value2 >= 60) {
value2 = (value2 - parts2[0]) / _60;
parts2.unshift(value2);
}
}
return sign + parts2.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, "");
}
var intTime = {
identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2),
default: true,
tag: "tag:yaml.org,2002:int",
format: "TIME",
test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
stringify: stringifySexagesimal
};
var floatTime = {
identify: (value2) => typeof value2 === "number",
default: true,
tag: "tag:yaml.org,2002:float",
format: "TIME",
test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
resolve: (str) => parseSexagesimal(str, false),
stringify: stringifySexagesimal
};
var timestamp = {
identify: (value2) => value2 instanceof Date,
default: true,
tag: "tag:yaml.org,2002:timestamp",
// If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
// may be omitted altogether, resulting in a date format. In such a case, the time part is
// assumed to be 00:00:00Z (start of day, UTC).
test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),
resolve(str) {
const match = str.match(timestamp.test);
if (!match)
throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
const [, year, month, day, hour, minute, second] = match.map(Number);
const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0;
let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
const tz = match[8];
if (tz && tz !== "Z") {
let d = parseSexagesimal(tz, false);
if (Math.abs(d) < 30)
d *= 60;
date -= 6e4 * d;
}
return new Date(date);
},
stringify: ({ value: value2 }) => value2.toISOString().replace(/((T00:00)?:00)?\.000Z$/, "")
};
exports2.floatTime = floatTime;
exports2.intTime = intTime;
exports2.timestamp = timestamp;
}
});
// node_modules/yaml/dist/schema/yaml-1.1/schema.js
var require_schema3 = __commonJS({
"node_modules/yaml/dist/schema/yaml-1.1/schema.js"(exports2) {
"use strict";
var map2 = require_map();
var _null = require_null();
var seq = require_seq();
var string = require_string();
var binary = require_binary();
var bool = require_bool2();
var float = require_float2();
var int = require_int2();
var omap = require_omap();
var pairs = require_pairs();
var set = require_set();
var timestamp = require_timestamp();
var schema = [
map2.map,
seq.seq,
string.string,
_null.nullTag,
bool.trueTag,
bool.falseTag,
int.intBin,
int.intOct,
int.int,
int.intHex,
float.floatNaN,
float.floatExp,
float.float,
binary.binary,
omap.omap,
pairs.pairs,
set.set,
timestamp.intTime,
timestamp.floatTime,
timestamp.timestamp
];
exports2.schema = schema;
}
});
// node_modules/yaml/dist/schema/tags.js
var require_tags = __commonJS({
"node_modules/yaml/dist/schema/tags.js"(exports2) {
"use strict";
var map2 = require_map();
var _null = require_null();
var seq = require_seq();
var string = require_string();
var bool = require_bool();
var float = require_float();
var int = require_int();
var schema = require_schema();
var schema$1 = require_schema2();
var binary = require_binary();
var omap = require_omap();
var pairs = require_pairs();
var schema$2 = require_schema3();
var set = require_set();
var timestamp = require_timestamp();
var schemas = /* @__PURE__ */ new Map([
["core", schema.schema],
["failsafe", [map2.map, seq.seq, string.string]],
["json", schema$1.schema],
["yaml11", schema$2.schema],
["yaml-1.1", schema$2.schema]
]);
var tagsByName = {
binary: binary.binary,
bool: bool.boolTag,
float: float.float,
floatExp: float.floatExp,
floatNaN: float.floatNaN,
floatTime: timestamp.floatTime,
int: int.int,
intHex: int.intHex,
intOct: int.intOct,
intTime: timestamp.intTime,
map: map2.map,
null: _null.nullTag,
omap: omap.omap,
pairs: pairs.pairs,
seq: seq.seq,
set: set.set,
timestamp: timestamp.timestamp
};
var coreKnownTags = {
"tag:yaml.org,2002:binary": binary.binary,
"tag:yaml.org,2002:omap": omap.omap,
"tag:yaml.org,2002:pairs": pairs.pairs,
"tag:yaml.org,2002:set": set.set,
"tag:yaml.org,2002:timestamp": timestamp.timestamp
};
function getTags(customTags, schemaName) {
let tags = schemas.get(schemaName);
if (!tags) {
if (Array.isArray(customTags))
tags = [];
else {
const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", ");
throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
}
}
if (Array.isArray(customTags)) {
for (const tag of customTags)
tags = tags.concat(tag);
} else if (typeof customTags === "function") {
tags = customTags(tags.slice());
}
return tags.map((tag) => {
if (typeof tag !== "string")
return tag;
const tagObj = tagsByName[tag];
if (tagObj)
return tagObj;
const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", ");
throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`);
});
}
exports2.coreKnownTags = coreKnownTags;
exports2.getTags = getTags;
}
});
// node_modules/yaml/dist/schema/Schema.js
var require_Schema = __commonJS({
"node_modules/yaml/dist/schema/Schema.js"(exports2) {
"use strict";
var identity = require_identity();
var map2 = require_map();
var seq = require_seq();
var string = require_string();
var tags = require_tags();
var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
var Schema = class _Schema {
constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
this.compat = Array.isArray(compat) ? tags.getTags(compat, "compat") : compat ? tags.getTags(null, compat) : null;
this.merge = !!merge;
this.name = typeof schema === "string" && schema || "core";
this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};
this.tags = tags.getTags(customTags, this.name);
this.toStringOptions = toStringDefaults ?? null;
Object.defineProperty(this, identity.MAP, { value: map2.map });
Object.defineProperty(this, identity.SCALAR, { value: string.string });
Object.defineProperty(this, identity.SEQ, { value: seq.seq });
this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null;
}
clone() {
const copy = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this));
copy.tags = this.tags.slice();
return copy;
}
};
exports2.Schema = Schema;
}
});
// node_modules/yaml/dist/stringify/stringifyDocument.js
var require_stringifyDocument = __commonJS({
"node_modules/yaml/dist/stringify/stringifyDocument.js"(exports2) {
"use strict";
var identity = require_identity();
var stringify2 = require_stringify();
var stringifyComment = require_stringifyComment();
function stringifyDocument(doc, options) {
const lines = [];
let hasDirectives = options.directives === true;
if (options.directives !== false && doc.directives) {
const dir = doc.directives.toString(doc);
if (dir) {
lines.push(dir);
hasDirectives = true;
} else if (doc.directives.docStart)
hasDirectives = true;
}
if (hasDirectives)
lines.push("---");
const ctx = stringify2.createStringifyContext(doc, options);
const { commentString } = ctx.options;
if (doc.commentBefore) {
if (lines.length !== 1)
lines.unshift("");
const cs = commentString(doc.commentBefore);
lines.unshift(stringifyComment.indentComment(cs, ""));
}
let chompKeep = false;
let contentComment = null;
if (doc.contents) {
if (identity.isNode(doc.contents)) {
if (doc.contents.spaceBefore && hasDirectives)
lines.push("");
if (doc.contents.commentBefore) {
const cs = commentString(doc.contents.commentBefore);
lines.push(stringifyComment.indentComment(cs, ""));
}
ctx.forceBlockIndent = !!doc.comment;
contentComment = doc.contents.comment;
}
const onChompKeep = contentComment ? void 0 : () => chompKeep = true;
let body = stringify2.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep);
if (contentComment)
body += stringifyComment.lineComment(body, "", commentString(contentComment));
if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") {
lines[lines.length - 1] = `--- ${body}`;
} else
lines.push(body);
} else {
lines.push(stringify2.stringify(doc.contents, ctx));
}
if (doc.directives?.docEnd) {
if (doc.comment) {
const cs = commentString(doc.comment);
if (cs.includes("\n")) {
lines.push("...");
lines.push(stringifyComment.indentComment(cs, ""));
} else {
lines.push(`... ${cs}`);
}
} else {
lines.push("...");
}
} else {
let dc = doc.comment;
if (dc && chompKeep)
dc = dc.replace(/^\n+/, "");
if (dc) {
if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "")
lines.push("");
lines.push(stringifyComment.indentComment(commentString(dc), ""));
}
}
return lines.join("\n") + "\n";
}
exports2.stringifyDocument = stringifyDocument;
}
});
// node_modules/yaml/dist/doc/Document.js
var require_Document = __commonJS({
"node_modules/yaml/dist/doc/Document.js"(exports2) {
"use strict";
var Alias = require_Alias();
var Collection = require_Collection();
var identity = require_identity();
var Pair = require_Pair();
var toJS = require_toJS();
var Schema = require_Schema();
var stringifyDocument = require_stringifyDocument();
var anchors = require_anchors();
var applyReviver = require_applyReviver();
var createNode = require_createNode();
var directives = require_directives();
var Document = class _Document {
constructor(value2, replacer, options) {
this.commentBefore = null;
this.comment = null;
this.errors = [];
this.warnings = [];
Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });
let _replacer = null;
if (typeof replacer === "function" || Array.isArray(replacer)) {
_replacer = replacer;
} else if (options === void 0 && replacer) {
options = replacer;
replacer = void 0;
}
const opt = Object.assign({
intAsBigInt: false,
keepSourceTokens: false,
logLevel: "warn",
prettyErrors: true,
strict: true,
uniqueKeys: true,
version: "1.2"
}, options);
this.options = opt;
let { version } = opt;
if (options?._directives) {
this.directives = options._directives.atDocument();
if (this.directives.yaml.explicit)
version = this.directives.yaml.version;
} else
this.directives = new directives.Directives({ version });
this.setSchema(version, options);
this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options);
}
/**
* Create a deep copy of this Document and its contents.
*
* Custom Node values that inherit from `Object` still refer to their original instances.
*/
clone() {
const copy = Object.create(_Document.prototype, {
[identity.NODE_TYPE]: { value: identity.DOC }
});
copy.commentBefore = this.commentBefore;
copy.comment = this.comment;
copy.errors = this.errors.slice();
copy.warnings = this.warnings.slice();
copy.options = Object.assign({}, this.options);
if (this.directives)
copy.directives = this.directives.clone();
copy.schema = this.schema.clone();
copy.contents = identity.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents;
if (this.range)
copy.range = this.range.slice();
return copy;
}
/** Adds a value to the document. */
add(value2) {
if (assertCollection(this.contents))
this.contents.add(value2);
}
/** Adds a value to the document. */
addIn(path, value2) {
if (assertCollection(this.contents))
this.contents.addIn(path, value2);
}
/**
* Create a new `Alias` node, ensuring that the target `node` has the required anchor.
*
* If `node` already has an anchor, `name` is ignored.
* Otherwise, the `node.anchor` value will be set to `name`,
* or if an anchor with that name is already present in the document,
* `name` will be used as a prefix for a new unique anchor.
* If `name` is undefined, the generated anchor will use 'a' as a prefix.
*/
createAlias(node, name) {
if (!node.anchor) {
const prev = anchors.anchorNames(this);
node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
!name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name;
}
return new Alias.Alias(node.anchor);
}
createNode(value2, replacer, options) {
let _replacer = void 0;
if (typeof replacer === "function") {
value2 = replacer.call({ "": value2 }, "", value2);
_replacer = replacer;
} else if (Array.isArray(replacer)) {
const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number;
const asStr = replacer.filter(keyToStr).map(String);
if (asStr.length > 0)
replacer = replacer.concat(asStr);
_replacer = replacer;
} else if (options === void 0 && replacer) {
options = replacer;
replacer = void 0;
}
const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(
this,
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
anchorPrefix || "a"
);
const ctx = {
aliasDuplicateObjects: aliasDuplicateObjects ?? true,
keepUndefined: keepUndefined ?? false,
onAnchor,
onTagObj,
replacer: _replacer,
schema: this.schema,
sourceObjects
};
const node = createNode.createNode(value2, tag, ctx);
if (flow && identity.isCollection(node))
node.flow = true;
setAnchors();
return node;
}
/**
* Convert a key and a value into a `Pair` using the current schema,
* recursively wrapping all values as `Scalar` or `Collection` nodes.
*/
createPair(key, value2, options = {}) {
const k = this.createNode(key, null, options);
const v = this.createNode(value2, null, options);
return new Pair.Pair(k, v);
}
/**
* Removes a value from the document.
* @returns `true` if the item was found and removed.
*/
delete(key) {
return assertCollection(this.contents) ? this.contents.delete(key) : false;
}
/**
* Removes a value from the document.
* @returns `true` if the item was found and removed.
*/
deleteIn(path) {
if (Collection.isEmptyPath(path)) {
if (this.contents == null)
return false;
this.contents = null;
return true;
}
return assertCollection(this.contents) ? this.contents.deleteIn(path) : false;
}
/**
* Returns item at `key`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
get(key, keepScalar) {
return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0;
}
/**
* Returns item at `path`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
getIn(path, keepScalar) {
if (Collection.isEmptyPath(path))
return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
return identity.isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0;
}
/**
* Checks if the document includes a value with the key `key`.
*/
has(key) {
return identity.isCollection(this.contents) ? this.contents.has(key) : false;
}
/**
* Checks if the document includes a value at `path`.
*/
hasIn(path) {
if (Collection.isEmptyPath(path))
return this.contents !== void 0;
return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;
}
/**
* Sets a value in this document. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
set(key, value2) {
if (this.contents == null) {
this.contents = Collection.collectionFromPath(this.schema, [key], value2);
} else if (assertCollection(this.contents)) {
this.contents.set(key, value2);
}
}
/**
* Sets a value in this document. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
setIn(path, value2) {
if (Collection.isEmptyPath(path)) {
this.contents = value2;
} else if (this.contents == null) {
this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value2);
} else if (assertCollection(this.contents)) {
this.contents.setIn(path, value2);
}
}
/**
* Change the YAML version and schema used by the document.
* A `null` version disables support for directives, explicit tags, anchors, and aliases.
* It also requires the `schema` option to be given as a `Schema` instance value.
*
* Overrides all previously set schema options.
*/
setSchema(version, options = {}) {
if (typeof version === "number")
version = String(version);
let opt;
switch (version) {
case "1.1":
if (this.directives)
this.directives.yaml.version = "1.1";
else
this.directives = new directives.Directives({ version: "1.1" });
opt = { merge: true, resolveKnownTags: false, schema: "yaml-1.1" };
break;
case "1.2":
case "next":
if (this.directives)
this.directives.yaml.version = version;
else
this.directives = new directives.Directives({ version });
opt = { merge: false, resolveKnownTags: true, schema: "core" };
break;
case null:
if (this.directives)
delete this.directives;
opt = null;
break;
default: {
const sv = JSON.stringify(version);
throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
}
}
if (options.schema instanceof Object)
this.schema = options.schema;
else if (opt)
this.schema = new Schema.Schema(Object.assign(opt, options));
else
throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
}
// json & jsonArg are only used from toJSON()
toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
const ctx = {
anchors: /* @__PURE__ */ new Map(),
doc: this,
keep: !json,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
};
const res = toJS.toJS(this.contents, jsonArg ?? "", ctx);
if (typeof onAnchor === "function")
for (const { count, res: res2 } of ctx.anchors.values())
onAnchor(res2, count);
return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res;
}
/**
* A JSON representation of the document `contents`.
*
* @param jsonArg Used by `JSON.stringify` to indicate the array index or
* property name.
*/
toJSON(jsonArg, onAnchor) {
return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
}
/** A YAML representation of the document. */
toString(options = {}) {
if (this.errors.length > 0)
throw new Error("Document with errors cannot be stringified");
if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
const s = JSON.stringify(options.indent);
throw new Error(`"indent" option must be a positive integer, not ${s}`);
}
return stringifyDocument.stringifyDocument(this, options);
}
};
function assertCollection(contents) {
if (identity.isCollection(contents))
return true;
throw new Error("Expected a YAML collection as document contents");
}
exports2.Document = Document;
}
});
// node_modules/yaml/dist/errors.js
var require_errors = __commonJS({
"node_modules/yaml/dist/errors.js"(exports2) {
"use strict";
var YAMLError = class extends Error {
constructor(name, pos, code, message) {
super();
this.name = name;
this.code = code;
this.message = message;
this.pos = pos;
}
};
var YAMLParseError = class extends YAMLError {
constructor(pos, code, message) {
super("YAMLParseError", pos, code, message);
}
};
var YAMLWarning = class extends YAMLError {
constructor(pos, code, message) {
super("YAMLWarning", pos, code, message);
}
};
var prettifyError = (src, lc) => (error) => {
if (error.pos[0] === -1)
return;
error.linePos = error.pos.map((pos) => lc.linePos(pos));
const { line, col } = error.linePos[0];
error.message += ` at line ${line}, column ${col}`;
let ci = col - 1;
let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, "");
if (ci >= 60 && lineStr.length > 80) {
const trimStart = Math.min(ci - 39, lineStr.length - 79);
lineStr = "\u2026" + lineStr.substring(trimStart);
ci -= trimStart - 1;
}
if (lineStr.length > 80)
lineStr = lineStr.substring(0, 79) + "\u2026";
if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
if (prev.length > 80)
prev = prev.substring(0, 79) + "\u2026\n";
lineStr = prev + lineStr;
}
if (/[^ ]/.test(lineStr)) {
let count = 1;
const end = error.linePos[1];
if (end && end.line === line && end.col > col) {
count = Math.max(1, Math.min(end.col - col, 80 - ci));
}
const pointer = " ".repeat(ci) + "^".repeat(count);
error.message += `:
${lineStr}
${pointer}
`;
}
};
exports2.YAMLError = YAMLError;
exports2.YAMLParseError = YAMLParseError;
exports2.YAMLWarning = YAMLWarning;
exports2.prettifyError = prettifyError;
}
});
// node_modules/yaml/dist/compose/resolve-props.js
var require_resolve_props = __commonJS({
"node_modules/yaml/dist/compose/resolve-props.js"(exports2) {
"use strict";
function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {
let spaceBefore = false;
let atNewline = startOnNewline;
let hasSpace = startOnNewline;
let comment = "";
let commentSep = "";
let hasNewline = false;
let reqSpace = false;
let tab = null;
let anchor = null;
let tag = null;
let newlineAfterProp = null;
let comma = null;
let found = null;
let start = null;
for (const token of tokens) {
if (reqSpace) {
if (token.type !== "space" && token.type !== "newline" && token.type !== "comma")
onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
reqSpace = false;
}
if (tab) {
if (atNewline && token.type !== "comment" && token.type !== "newline") {
onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
}
tab = null;
}
switch (token.type) {
case "space":
if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) {
tab = token;
}
hasSpace = true;
break;
case "comment": {
if (!hasSpace)
onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
const cb = token.source.substring(1) || " ";
if (!comment)
comment = cb;
else
comment += commentSep + cb;
commentSep = "";
atNewline = false;
break;
}
case "newline":
if (atNewline) {
if (comment)
comment += token.source;
else
spaceBefore = true;
} else
commentSep += token.source;
atNewline = true;
hasNewline = true;
if (anchor || tag)
newlineAfterProp = token;
hasSpace = true;
break;
case "anchor":
if (anchor)
onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor");
if (token.source.endsWith(":"))
onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true);
anchor = token;
if (start === null)
start = token.offset;
atNewline = false;
hasSpace = false;
reqSpace = true;
break;
case "tag": {
if (tag)
onError(token, "MULTIPLE_TAGS", "A node can have at most one tag");
tag = token;
if (start === null)
start = token.offset;
atNewline = false;
hasSpace = false;
reqSpace = true;
break;
}
case indicator:
if (anchor || tag)
onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`);
if (found)
onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`);
found = token;
atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind";
hasSpace = false;
break;
case "comma":
if (flow) {
if (comma)
onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`);
comma = token;
atNewline = false;
hasSpace = false;
break;
}
// else fallthrough
default:
onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`);
atNewline = false;
hasSpace = false;
}
}
const last = tokens[tokens.length - 1];
const end = last ? last.offset + last.source.length : offset;
if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) {
onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
}
if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq"))
onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
return {
comma,
found,
spaceBefore,
comment,
hasNewline,
anchor,
tag,
newlineAfterProp,
end,
start: start ?? end
};
}
exports2.resolveProps = resolveProps;
}
});
// node_modules/yaml/dist/compose/util-contains-newline.js
var require_util_contains_newline = __commonJS({
"node_modules/yaml/dist/compose/util-contains-newline.js"(exports2) {
"use strict";
function containsNewline(key) {
if (!key)
return null;
switch (key.type) {
case "alias":
case "scalar":
case "double-quoted-scalar":
case "single-quoted-scalar":
if (key.source.includes("\n"))
return true;
if (key.end) {
for (const st of key.end)
if (st.type === "newline")
return true;
}
return false;
case "flow-collection":
for (const it of key.items) {
for (const st of it.start)
if (st.type === "newline")
return true;
if (it.sep) {
for (const st of it.sep)
if (st.type === "newline")
return true;
}
if (containsNewline(it.key) || containsNewline(it.value))
return true;
}
return false;
default:
return true;
}
}
exports2.containsNewline = containsNewline;
}
});
// node_modules/yaml/dist/compose/util-flow-indent-check.js
var require_util_flow_indent_check = __commonJS({
"node_modules/yaml/dist/compose/util-flow-indent-check.js"(exports2) {
"use strict";
var utilContainsNewline = require_util_contains_newline();
function flowIndentCheck(indent, fc, onError) {
if (fc?.type === "flow-collection") {
const end = fc.end[0];
if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) {
const msg = "Flow end indicator should be more indented than parent";
onError(end, "BAD_INDENT", msg, true);
}
}
}
exports2.flowIndentCheck = flowIndentCheck;
}
});
// node_modules/yaml/dist/compose/util-map-includes.js
var require_util_map_includes = __commonJS({
"node_modules/yaml/dist/compose/util-map-includes.js"(exports2) {
"use strict";
var identity = require_identity();
function mapIncludes(ctx, items, search) {
const { uniqueKeys } = ctx.options;
if (uniqueKeys === false)
return false;
const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity.isScalar(a) && identity.isScalar(b) && a.value === b.value && !(a.value === "<<" && ctx.schema.merge);
return items.some((pair) => isEqual(pair.key, search));
}
exports2.mapIncludes = mapIncludes;
}
});
// node_modules/yaml/dist/compose/resolve-block-map.js
var require_resolve_block_map = __commonJS({
"node_modules/yaml/dist/compose/resolve-block-map.js"(exports2) {
"use strict";
var Pair = require_Pair();
var YAMLMap = require_YAMLMap();
var resolveProps = require_resolve_props();
var utilContainsNewline = require_util_contains_newline();
var utilFlowIndentCheck = require_util_flow_indent_check();
var utilMapIncludes = require_util_map_includes();
var startColMsg = "All mapping items must start at the same column";
function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {
const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;
const map2 = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset = bm.offset;
let commentEnd = null;
for (const collItem of bm.items) {
const { start, key, sep, value: value2 } = collItem;
const keyProps = resolveProps.resolveProps(start, {
indicator: "explicit-key-ind",
next: key ?? sep?.[0],
offset,
onError,
parentIndent: bm.indent,
startOnNewline: true
});
const implicitKey = !keyProps.found;
if (implicitKey) {
if (key) {
if (key.type === "block-seq")
onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key");
else if ("indent" in key && key.indent !== bm.indent)
onError(offset, "BAD_INDENT", startColMsg);
}
if (!keyProps.anchor && !keyProps.tag && !sep) {
commentEnd = keyProps.end;
if (keyProps.comment) {
if (map2.comment)
map2.comment += "\n" + keyProps.comment;
else
map2.comment = keyProps.comment;
}
continue;
}
if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {
onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line");
}
} else if (keyProps.found?.indent !== bm.indent) {
onError(offset, "BAD_INDENT", startColMsg);
}
const keyStart = keyProps.end;
const keyNode = key ? composeNode(ctx, key, keyProps, onError) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);
if (ctx.schema.compat)
utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);
if (utilMapIncludes.mapIncludes(ctx, map2.items, keyNode))
onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
const valueProps = resolveProps.resolveProps(sep ?? [], {
indicator: "map-value-ind",
next: value2,
offset: keyNode.range[2],
onError,
parentIndent: bm.indent,
startOnNewline: !key || key.type === "block-scalar"
});
offset = valueProps.end;
if (valueProps.found) {
if (implicitKey) {
if (value2?.type === "block-map" && !valueProps.hasNewline)
onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings");
if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
}
const valueNode = value2 ? composeNode(ctx, value2, valueProps, onError) : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);
if (ctx.schema.compat)
utilFlowIndentCheck.flowIndentCheck(bm.indent, value2, onError);
offset = valueNode.range[2];
const pair = new Pair.Pair(keyNode, valueNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
map2.items.push(pair);
} else {
if (implicitKey)
onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values");
if (valueProps.comment) {
if (keyNode.comment)
keyNode.comment += "\n" + valueProps.comment;
else
keyNode.comment = valueProps.comment;
}
const pair = new Pair.Pair(keyNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
map2.items.push(pair);
}
}
if (commentEnd && commentEnd < offset)
onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content");
map2.range = [bm.offset, offset, commentEnd ?? offset];
return map2;
}
exports2.resolveBlockMap = resolveBlockMap;
}
});
// node_modules/yaml/dist/compose/resolve-block-seq.js
var require_resolve_block_seq = __commonJS({
"node_modules/yaml/dist/compose/resolve-block-seq.js"(exports2) {
"use strict";
var YAMLSeq = require_YAMLSeq();
var resolveProps = require_resolve_props();
var utilFlowIndentCheck = require_util_flow_indent_check();
function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {
const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;
const seq = new NodeClass(ctx.schema);
if (ctx.atRoot)
ctx.atRoot = false;
let offset = bs.offset;
let commentEnd = null;
for (const { start, value: value2 } of bs.items) {
const props = resolveProps.resolveProps(start, {
indicator: "seq-item-ind",
next: value2,
offset,
onError,
parentIndent: bs.indent,
startOnNewline: true
});
if (!props.found) {
if (props.anchor || props.tag || value2) {
if (value2 && value2.type === "block-seq")
onError(props.end, "BAD_INDENT", "All sequence items must start at the same column");
else
onError(offset, "MISSING_CHAR", "Sequence item without - indicator");
} else {
commentEnd = props.end;
if (props.comment)
seq.comment = props.comment;
continue;
}
}
const node = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError);
if (ctx.schema.compat)
utilFlowIndentCheck.flowIndentCheck(bs.indent, value2, onError);
offset = node.range[2];
seq.items.push(node);
}
seq.range = [bs.offset, offset, commentEnd ?? offset];
return seq;
}
exports2.resolveBlockSeq = resolveBlockSeq;
}
});
// node_modules/yaml/dist/compose/resolve-end.js
var require_resolve_end = __commonJS({
"node_modules/yaml/dist/compose/resolve-end.js"(exports2) {
"use strict";
function resolveEnd(end, offset, reqSpace, onError) {
let comment = "";
if (end) {
let hasSpace = false;
let sep = "";
for (const token of end) {
const { source, type } = token;
switch (type) {
case "space":
hasSpace = true;
break;
case "comment": {
if (reqSpace && !hasSpace)
onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
const cb = source.substring(1) || " ";
if (!comment)
comment = cb;
else
comment += sep + cb;
sep = "";
break;
}
case "newline":
if (comment)
sep += source;
hasSpace = true;
break;
default:
onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`);
}
offset += source.length;
}
}
return { comment, offset };
}
exports2.resolveEnd = resolveEnd;
}
});
// node_modules/yaml/dist/compose/resolve-flow-collection.js
var require_resolve_flow_collection = __commonJS({
"node_modules/yaml/dist/compose/resolve-flow-collection.js"(exports2) {
"use strict";
var identity = require_identity();
var Pair = require_Pair();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var resolveEnd = require_resolve_end();
var resolveProps = require_resolve_props();
var utilContainsNewline = require_util_contains_newline();
var utilMapIncludes = require_util_map_includes();
var blockMsg = "Block collections are not allowed within flow collections";
var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq");
function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {
const isMap = fc.start.source === "{";
const fcName = isMap ? "flow map" : "flow sequence";
const NodeClass = tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq);
const coll = new NodeClass(ctx.schema);
coll.flow = true;
const atRoot = ctx.atRoot;
if (atRoot)
ctx.atRoot = false;
let offset = fc.offset + fc.start.source.length;
for (let i = 0; i < fc.items.length; ++i) {
const collItem = fc.items[i];
const { start, key, sep, value: value2 } = collItem;
const props = resolveProps.resolveProps(start, {
flow: fcName,
indicator: "explicit-key-ind",
next: key ?? sep?.[0],
offset,
onError,
parentIndent: fc.indent,
startOnNewline: false
});
if (!props.found) {
if (!props.anchor && !props.tag && !sep && !value2) {
if (i === 0 && props.comma)
onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
else if (i < fc.items.length - 1)
onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`);
if (props.comment) {
if (coll.comment)
coll.comment += "\n" + props.comment;
else
coll.comment = props.comment;
}
offset = props.end;
continue;
}
if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))
onError(
key,
// checked by containsNewline()
"MULTILINE_IMPLICIT_KEY",
"Implicit keys of flow sequence pairs need to be on a single line"
);
}
if (i === 0) {
if (props.comma)
onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
} else {
if (!props.comma)
onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`);
if (props.comment) {
let prevItemComment = "";
loop: for (const st of start) {
switch (st.type) {
case "comma":
case "space":
break;
case "comment":
prevItemComment = st.source.substring(1);
break loop;
default:
break loop;
}
}
if (prevItemComment) {
let prev = coll.items[coll.items.length - 1];
if (identity.isPair(prev))
prev = prev.value ?? prev.key;
if (prev.comment)
prev.comment += "\n" + prevItemComment;
else
prev.comment = prevItemComment;
props.comment = props.comment.substring(prevItemComment.length + 1);
}
}
}
if (!isMap && !sep && !props.found) {
const valueNode = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, sep, null, props, onError);
coll.items.push(valueNode);
offset = valueNode.range[2];
if (isBlock(value2))
onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
} else {
const keyStart = props.end;
const keyNode = key ? composeNode(ctx, key, props, onError) : composeEmptyNode(ctx, keyStart, start, null, props, onError);
if (isBlock(key))
onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
const valueProps = resolveProps.resolveProps(sep ?? [], {
flow: fcName,
indicator: "map-value-ind",
next: value2,
offset: keyNode.range[2],
onError,
parentIndent: fc.indent,
startOnNewline: false
});
if (valueProps.found) {
if (!isMap && !props.found && ctx.options.strict) {
if (sep)
for (const st of sep) {
if (st === valueProps.found)
break;
if (st.type === "newline") {
onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
break;
}
}
if (props.start < valueProps.found.offset - 1024)
onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key");
}
} else if (value2) {
if ("source" in value2 && value2.source && value2.source[0] === ":")
onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`);
else
onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
}
const valueNode = value2 ? composeNode(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) : null;
if (valueNode) {
if (isBlock(value2))
onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
} else if (valueProps.comment) {
if (keyNode.comment)
keyNode.comment += "\n" + valueProps.comment;
else
keyNode.comment = valueProps.comment;
}
const pair = new Pair.Pair(keyNode, valueNode);
if (ctx.options.keepSourceTokens)
pair.srcToken = collItem;
if (isMap) {
const map2 = coll;
if (utilMapIncludes.mapIncludes(ctx, map2.items, keyNode))
onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
map2.items.push(pair);
} else {
const map2 = new YAMLMap.YAMLMap(ctx.schema);
map2.flow = true;
map2.items.push(pair);
const endRange = (valueNode ?? keyNode).range;
map2.range = [keyNode.range[0], endRange[1], endRange[2]];
coll.items.push(map2);
}
offset = valueNode ? valueNode.range[2] : valueProps.end;
}
}
const expectedEnd = isMap ? "}" : "]";
const [ce, ...ee] = fc.end;
let cePos = offset;
if (ce && ce.source === expectedEnd)
cePos = ce.offset + ce.source.length;
else {
const name = fcName[0].toUpperCase() + fcName.substring(1);
const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg);
if (ce && ce.source.length !== 1)
ee.unshift(ce);
}
if (ee.length > 0) {
const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);
if (end.comment) {
if (coll.comment)
coll.comment += "\n" + end.comment;
else
coll.comment = end.comment;
}
coll.range = [fc.offset, cePos, end.offset];
} else {
coll.range = [fc.offset, cePos, cePos];
}
return coll;
}
exports2.resolveFlowCollection = resolveFlowCollection;
}
});
// node_modules/yaml/dist/compose/compose-collection.js
var require_compose_collection = __commonJS({
"node_modules/yaml/dist/compose/compose-collection.js"(exports2) {
"use strict";
var identity = require_identity();
var Scalar = require_Scalar();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var resolveBlockMap = require_resolve_block_map();
var resolveBlockSeq = require_resolve_block_seq();
var resolveFlowCollection = require_resolve_flow_collection();
function resolveCollection(CN, ctx, token, onError, tagName, tag) {
const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);
const Coll = coll.constructor;
if (tagName === "!" || tagName === Coll.tagName) {
coll.tag = Coll.tagName;
return coll;
}
if (tagName)
coll.tag = tagName;
return coll;
}
function composeCollection(CN, ctx, token, props, onError) {
const tagToken = props.tag;
const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg));
if (token.type === "block-seq") {
const { anchor, newlineAfterProp: nl } = props;
const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken;
if (lastProp && (!nl || nl.offset < lastProp.offset)) {
const message = "Missing newline after block sequence props";
onError(lastProp, "MISSING_CHAR", message);
}
}
const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq";
if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") {
return resolveCollection(CN, ctx, token, onError, tagName);
}
let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType);
if (!tag) {
const kt = ctx.schema.knownTags[tagName];
if (kt && kt.collection === expType) {
ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
tag = kt;
} else {
if (kt?.collection) {
onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection}`, true);
} else {
onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true);
}
return resolveCollection(CN, ctx, token, onError, tagName);
}
}
const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);
const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll;
const node = identity.isNode(res) ? res : new Scalar.Scalar(res);
node.range = coll.range;
node.tag = tagName;
if (tag?.format)
node.format = tag.format;
return node;
}
exports2.composeCollection = composeCollection;
}
});
// node_modules/yaml/dist/compose/resolve-block-scalar.js
var require_resolve_block_scalar = __commonJS({
"node_modules/yaml/dist/compose/resolve-block-scalar.js"(exports2) {
"use strict";
var Scalar = require_Scalar();
function resolveBlockScalar(ctx, scalar, onError) {
const start = scalar.offset;
const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);
if (!header)
return { value: "", type: null, comment: "", range: [start, start, start] };
const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;
const lines = scalar.source ? splitLines(scalar.source) : [];
let chompStart = lines.length;
for (let i = lines.length - 1; i >= 0; --i) {
const content = lines[i][1];
if (content === "" || content === "\r")
chompStart = i;
else
break;
}
if (chompStart === 0) {
const value3 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : "";
let end2 = start + header.length;
if (scalar.source)
end2 += scalar.source.length;
return { value: value3, type, comment: header.comment, range: [start, end2, end2] };
}
let trimIndent = scalar.indent + header.indent;
let offset = scalar.offset + header.length;
let contentStart = 0;
for (let i = 0; i < chompStart; ++i) {
const [indent, content] = lines[i];
if (content === "" || content === "\r") {
if (header.indent === 0 && indent.length > trimIndent)
trimIndent = indent.length;
} else {
if (indent.length < trimIndent) {
const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
onError(offset + indent.length, "MISSING_CHAR", message);
}
if (header.indent === 0)
trimIndent = indent.length;
contentStart = i;
if (trimIndent === 0 && !ctx.atRoot) {
const message = "Block scalar values in collections must be indented";
onError(offset, "BAD_INDENT", message);
}
break;
}
offset += indent.length + content.length + 1;
}
for (let i = lines.length - 1; i >= chompStart; --i) {
if (lines[i][0].length > trimIndent)
chompStart = i + 1;
}
let value2 = "";
let sep = "";
let prevMoreIndented = false;
for (let i = 0; i < contentStart; ++i)
value2 += lines[i][0].slice(trimIndent) + "\n";
for (let i = contentStart; i < chompStart; ++i) {
let [indent, content] = lines[i];
offset += indent.length + content.length + 1;
const crlf = content[content.length - 1] === "\r";
if (crlf)
content = content.slice(0, -1);
if (content && indent.length < trimIndent) {
const src = header.indent ? "explicit indentation indicator" : "first line";
const message = `Block scalar lines must not be less indented than their ${src}`;
onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message);
indent = "";
}
if (type === Scalar.Scalar.BLOCK_LITERAL) {
value2 += sep + indent.slice(trimIndent) + content;
sep = "\n";
} else if (indent.length > trimIndent || content[0] === " ") {
if (sep === " ")
sep = "\n";
else if (!prevMoreIndented && sep === "\n")
sep = "\n\n";
value2 += sep + indent.slice(trimIndent) + content;
sep = "\n";
prevMoreIndented = true;
} else if (content === "") {
if (sep === "\n")
value2 += "\n";
else
sep = "\n";
} else {
value2 += sep + content;
sep = " ";
prevMoreIndented = false;
}
}
switch (header.chomp) {
case "-":
break;
case "+":
for (let i = chompStart; i < lines.length; ++i)
value2 += "\n" + lines[i][0].slice(trimIndent);
if (value2[value2.length - 1] !== "\n")
value2 += "\n";
break;
default:
value2 += "\n";
}
const end = start + header.length + scalar.source.length;
return { value: value2, type, comment: header.comment, range: [start, end, end] };
}
function parseBlockScalarHeader({ offset, props }, strict, onError) {
if (props[0].type !== "block-scalar-header") {
onError(props[0], "IMPOSSIBLE", "Block scalar header not found");
return null;
}
const { source } = props[0];
const mode = source[0];
let indent = 0;
let chomp = "";
let error = -1;
for (let i = 1; i < source.length; ++i) {
const ch = source[i];
if (!chomp && (ch === "-" || ch === "+"))
chomp = ch;
else {
const n = Number(ch);
if (!indent && n)
indent = n;
else if (error === -1)
error = offset + i;
}
}
if (error !== -1)
onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`);
let hasSpace = false;
let comment = "";
let length = source.length;
for (let i = 1; i < props.length; ++i) {
const token = props[i];
switch (token.type) {
case "space":
hasSpace = true;
// fallthrough
case "newline":
length += token.source.length;
break;
case "comment":
if (strict && !hasSpace) {
const message = "Comments must be separated from other tokens by white space characters";
onError(token, "MISSING_CHAR", message);
}
length += token.source.length;
comment = token.source.substring(1);
break;
case "error":
onError(token, "UNEXPECTED_TOKEN", token.message);
length += token.source.length;
break;
/* istanbul ignore next should not happen */
default: {
const message = `Unexpected token in block scalar header: ${token.type}`;
onError(token, "UNEXPECTED_TOKEN", message);
const ts = token.source;
if (ts && typeof ts === "string")
length += ts.length;
}
}
}
return { mode, indent, chomp, comment, length };
}
function splitLines(source) {
const split = source.split(/\n( *)/);
const first = split[0];
const m = first.match(/^( *)/);
const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first];
const lines = [line0];
for (let i = 1; i < split.length; i += 2)
lines.push([split[i], split[i + 1]]);
return lines;
}
exports2.resolveBlockScalar = resolveBlockScalar;
}
});
// node_modules/yaml/dist/compose/resolve-flow-scalar.js
var require_resolve_flow_scalar = __commonJS({
"node_modules/yaml/dist/compose/resolve-flow-scalar.js"(exports2) {
"use strict";
var Scalar = require_Scalar();
var resolveEnd = require_resolve_end();
function resolveFlowScalar(scalar, strict, onError) {
const { offset, type, source, end } = scalar;
let _type;
let value2;
const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
switch (type) {
case "scalar":
_type = Scalar.Scalar.PLAIN;
value2 = plainValue(source, _onError);
break;
case "single-quoted-scalar":
_type = Scalar.Scalar.QUOTE_SINGLE;
value2 = singleQuotedValue(source, _onError);
break;
case "double-quoted-scalar":
_type = Scalar.Scalar.QUOTE_DOUBLE;
value2 = doubleQuotedValue(source, _onError);
break;
/* istanbul ignore next should not happen */
default:
onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
return {
value: "",
type: null,
comment: "",
range: [offset, offset + source.length, offset + source.length]
};
}
const valueEnd = offset + source.length;
const re2 = resolveEnd.resolveEnd(end, valueEnd, strict, onError);
return {
value: value2,
type: _type,
comment: re2.comment,
range: [offset, valueEnd, re2.offset]
};
}
function plainValue(source, onError) {
let badChar = "";
switch (source[0]) {
/* istanbul ignore next should not happen */
case " ":
badChar = "a tab character";
break;
case ",":
badChar = "flow indicator character ,";
break;
case "%":
badChar = "directive indicator character %";
break;
case "|":
case ">": {
badChar = `block scalar indicator ${source[0]}`;
break;
}
case "@":
case "`": {
badChar = `reserved character ${source[0]}`;
break;
}
}
if (badChar)
onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
return foldLines(source);
}
function singleQuotedValue(source, onError) {
if (source[source.length - 1] !== "'" || source.length === 1)
onError(source.length, "MISSING_CHAR", "Missing closing 'quote");
return foldLines(source.slice(1, -1)).replace(/''/g, "'");
}
function foldLines(source) {
let first, line;
try {
first = new RegExp("(.*?)(?<![ ])[ ]*\r?\n", "sy");
line = new RegExp("[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?\n", "sy");
} catch {
first = /(.*?)[ \t]*\r?\n/sy;
line = /[ \t]*(.*?)[ \t]*\r?\n/sy;
}
let match = first.exec(source);
if (!match)
return source;
let res = match[1];
let sep = " ";
let pos = first.lastIndex;
line.lastIndex = pos;
while (match = line.exec(source)) {
if (match[1] === "") {
if (sep === "\n")
res += sep;
else
sep = "\n";
} else {
res += sep + match[1];
sep = " ";
}
pos = line.lastIndex;
}
const last = /[ \t]*(.*)/sy;
last.lastIndex = pos;
match = last.exec(source);
return res + sep + (match?.[1] ?? "");
}
function doubleQuotedValue(source, onError) {
let res = "";
for (let i = 1; i < source.length - 1; ++i) {
const ch = source[i];
if (ch === "\r" && source[i + 1] === "\n")
continue;
if (ch === "\n") {
const { fold, offset } = foldNewline(source, i);
res += fold;
i = offset;
} else if (ch === "\\") {
let next = source[++i];
const cc = escapeCodes[next];
if (cc)
res += cc;
else if (next === "\n") {
next = source[i + 1];
while (next === " " || next === " ")
next = source[++i + 1];
} else if (next === "\r" && source[i + 1] === "\n") {
next = source[++i + 1];
while (next === " " || next === " ")
next = source[++i + 1];
} else if (next === "x" || next === "u" || next === "U") {
const length = { x: 2, u: 4, U: 8 }[next];
res += parseCharCode(source, i + 1, length, onError);
i += length;
} else {
const raw = source.substr(i - 1, 2);
onError(i - 1, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
res += raw;
}
} else if (ch === " " || ch === " ") {
const wsStart = i;
let next = source[i + 1];
while (next === " " || next === " ")
next = source[++i + 1];
if (next !== "\n" && !(next === "\r" && source[i + 2] === "\n"))
res += i > wsStart ? source.slice(wsStart, i + 1) : ch;
} else {
res += ch;
}
}
if (source[source.length - 1] !== '"' || source.length === 1)
onError(source.length, "MISSING_CHAR", 'Missing closing "quote');
return res;
}
function foldNewline(source, offset) {
let fold = "";
let ch = source[offset + 1];
while (ch === " " || ch === " " || ch === "\n" || ch === "\r") {
if (ch === "\r" && source[offset + 2] !== "\n")
break;
if (ch === "\n")
fold += "\n";
offset += 1;
ch = source[offset + 1];
}
if (!fold)
fold = " ";
return { fold, offset };
}
var escapeCodes = {
"0": "\0",
// null character
a: "\x07",
// bell character
b: "\b",
// backspace
e: "\x1B",
// escape character
f: "\f",
// form feed
n: "\n",
// line feed
r: "\r",
// carriage return
t: " ",
// horizontal tab
v: "\v",
// vertical tab
N: "\x85",
// Unicode next line
_: "\xA0",
// Unicode non-breaking space
L: "\u2028",
// Unicode line separator
P: "\u2029",
// Unicode paragraph separator
" ": " ",
'"': '"',
"/": "/",
"\\": "\\",
" ": " "
};
function parseCharCode(source, offset, length, onError) {
const cc = source.substr(offset, length);
const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
const code = ok ? parseInt(cc, 16) : NaN;
if (isNaN(code)) {
const raw = source.substr(offset - 2, length + 2);
onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
return raw;
}
return String.fromCodePoint(code);
}
exports2.resolveFlowScalar = resolveFlowScalar;
}
});
// node_modules/yaml/dist/compose/compose-scalar.js
var require_compose_scalar = __commonJS({
"node_modules/yaml/dist/compose/compose-scalar.js"(exports2) {
"use strict";
var identity = require_identity();
var Scalar = require_Scalar();
var resolveBlockScalar = require_resolve_block_scalar();
var resolveFlowScalar = require_resolve_flow_scalar();
function composeScalar(ctx, token, tagToken, onError) {
const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);
const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null;
const tag = tagToken && tagName ? findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError) : token.type === "scalar" ? findScalarTagByTest(ctx, value2, token, onError) : ctx.schema[identity.SCALAR];
let scalar;
try {
const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options);
scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg);
scalar = new Scalar.Scalar(value2);
}
scalar.range = range;
scalar.source = value2;
if (type)
scalar.type = type;
if (tagName)
scalar.tag = tagName;
if (tag.format)
scalar.format = tag.format;
if (comment)
scalar.comment = comment;
return scalar;
}
function findScalarTagByName(schema, value2, tagName, tagToken, onError) {
if (tagName === "!")
return schema[identity.SCALAR];
const matchWithTest = [];
for (const tag of schema.tags) {
if (!tag.collection && tag.tag === tagName) {
if (tag.default && tag.test)
matchWithTest.push(tag);
else
return tag;
}
}
for (const tag of matchWithTest)
if (tag.test?.test(value2))
return tag;
const kt = schema.knownTags[tagName];
if (kt && !kt.collection) {
schema.tags.push(Object.assign({}, kt, { default: false, test: void 0 }));
return kt;
}
onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str");
return schema[identity.SCALAR];
}
function findScalarTagByTest({ directives, schema }, value2, token, onError) {
const tag = schema.tags.find((tag2) => tag2.default && tag2.test?.test(value2)) || schema[identity.SCALAR];
if (schema.compat) {
const compat = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema[identity.SCALAR];
if (tag.tag !== compat.tag) {
const ts = directives.tagString(tag.tag);
const cs = directives.tagString(compat.tag);
const msg = `Value may be parsed as either ${ts} or ${cs}`;
onError(token, "TAG_RESOLVE_FAILED", msg, true);
}
}
return tag;
}
exports2.composeScalar = composeScalar;
}
});
// node_modules/yaml/dist/compose/util-empty-scalar-position.js
var require_util_empty_scalar_position = __commonJS({
"node_modules/yaml/dist/compose/util-empty-scalar-position.js"(exports2) {
"use strict";
function emptyScalarPosition(offset, before, pos) {
if (before) {
if (pos === null)
pos = before.length;
for (let i = pos - 1; i >= 0; --i) {
let st = before[i];
switch (st.type) {
case "space":
case "comment":
case "newline":
offset -= st.source.length;
continue;
}
st = before[++i];
while (st?.type === "space") {
offset += st.source.length;
st = before[++i];
}
break;
}
}
return offset;
}
exports2.emptyScalarPosition = emptyScalarPosition;
}
});
// node_modules/yaml/dist/compose/compose-node.js
var require_compose_node = __commonJS({
"node_modules/yaml/dist/compose/compose-node.js"(exports2) {
"use strict";
var Alias = require_Alias();
var composeCollection = require_compose_collection();
var composeScalar = require_compose_scalar();
var resolveEnd = require_resolve_end();
var utilEmptyScalarPosition = require_util_empty_scalar_position();
var CN = { composeNode, composeEmptyNode };
function composeNode(ctx, token, props, onError) {
const { spaceBefore, comment, anchor, tag } = props;
let node;
let isSrcToken = true;
switch (token.type) {
case "alias":
node = composeAlias(ctx, token, onError);
if (anchor || tag)
onError(token, "ALIAS_PROPS", "An alias node must not specify any properties");
break;
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
case "block-scalar":
node = composeScalar.composeScalar(ctx, token, tag, onError);
if (anchor)
node.anchor = anchor.source.substring(1);
break;
case "block-map":
case "block-seq":
case "flow-collection":
node = composeCollection.composeCollection(CN, ctx, token, props, onError);
if (anchor)
node.anchor = anchor.source.substring(1);
break;
default: {
const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`;
onError(token, "UNEXPECTED_TOKEN", message);
node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError);
isSrcToken = false;
}
}
if (anchor && node.anchor === "")
onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
if (spaceBefore)
node.spaceBefore = true;
if (comment) {
if (token.type === "scalar" && token.source === "")
node.comment = comment;
else
node.commentBefore = comment;
}
if (ctx.options.keepSourceTokens && isSrcToken)
node.srcToken = token;
return node;
}
function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {
const token = {
type: "scalar",
offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),
indent: -1,
source: ""
};
const node = composeScalar.composeScalar(ctx, token, tag, onError);
if (anchor) {
node.anchor = anchor.source.substring(1);
if (node.anchor === "")
onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
}
if (spaceBefore)
node.spaceBefore = true;
if (comment) {
node.comment = comment;
node.range[2] = end;
}
return node;
}
function composeAlias({ options }, { offset, source, end }, onError) {
const alias = new Alias.Alias(source.substring(1));
if (alias.source === "")
onError(offset, "BAD_ALIAS", "Alias cannot be an empty string");
if (alias.source.endsWith(":"))
onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true);
const valueEnd = offset + source.length;
const re2 = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);
alias.range = [offset, valueEnd, re2.offset];
if (re2.comment)
alias.comment = re2.comment;
return alias;
}
exports2.composeEmptyNode = composeEmptyNode;
exports2.composeNode = composeNode;
}
});
// node_modules/yaml/dist/compose/compose-doc.js
var require_compose_doc = __commonJS({
"node_modules/yaml/dist/compose/compose-doc.js"(exports2) {
"use strict";
var Document = require_Document();
var composeNode = require_compose_node();
var resolveEnd = require_resolve_end();
var resolveProps = require_resolve_props();
function composeDoc(options, directives, { offset, start, value: value2, end }, onError) {
const opts = Object.assign({ _directives: directives }, options);
const doc = new Document.Document(void 0, opts);
const ctx = {
atRoot: true,
directives: doc.directives,
options: doc.options,
schema: doc.schema
};
const props = resolveProps.resolveProps(start, {
indicator: "doc-start",
next: value2 ?? end?.[0],
offset,
onError,
parentIndent: 0,
startOnNewline: true
});
if (props.found) {
doc.directives.docStart = true;
if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline)
onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker");
}
doc.contents = value2 ? composeNode.composeNode(ctx, value2, props, onError) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);
const contentEnd = doc.contents.range[2];
const re2 = resolveEnd.resolveEnd(end, contentEnd, false, onError);
if (re2.comment)
doc.comment = re2.comment;
doc.range = [offset, contentEnd, re2.offset];
return doc;
}
exports2.composeDoc = composeDoc;
}
});
// node_modules/yaml/dist/compose/composer.js
var require_composer = __commonJS({
"node_modules/yaml/dist/compose/composer.js"(exports2) {
"use strict";
var directives = require_directives();
var Document = require_Document();
var errors = require_errors();
var identity = require_identity();
var composeDoc = require_compose_doc();
var resolveEnd = require_resolve_end();
function getErrorPos(src) {
if (typeof src === "number")
return [src, src + 1];
if (Array.isArray(src))
return src.length === 2 ? src : [src[0], src[1]];
const { offset, source } = src;
return [offset, offset + (typeof source === "string" ? source.length : 1)];
}
function parsePrelude(prelude) {
let comment = "";
let atComment = false;
let afterEmptyLine = false;
for (let i = 0; i < prelude.length; ++i) {
const source = prelude[i];
switch (source[0]) {
case "#":
comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " ");
atComment = true;
afterEmptyLine = false;
break;
case "%":
if (prelude[i + 1]?.[0] !== "#")
i += 1;
atComment = false;
break;
default:
if (!atComment)
afterEmptyLine = true;
atComment = false;
}
}
return { comment, afterEmptyLine };
}
var Composer = class {
constructor(options = {}) {
this.doc = null;
this.atDirectives = false;
this.prelude = [];
this.errors = [];
this.warnings = [];
this.onError = (source, code, message, warning) => {
const pos = getErrorPos(source);
if (warning)
this.warnings.push(new errors.YAMLWarning(pos, code, message));
else
this.errors.push(new errors.YAMLParseError(pos, code, message));
};
this.directives = new directives.Directives({ version: options.version || "1.2" });
this.options = options;
}
decorate(doc, afterDoc) {
const { comment, afterEmptyLine } = parsePrelude(this.prelude);
if (comment) {
const dc = doc.contents;
if (afterDoc) {
doc.comment = doc.comment ? `${doc.comment}
${comment}` : comment;
} else if (afterEmptyLine || doc.directives.docStart || !dc) {
doc.commentBefore = comment;
} else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {
let it = dc.items[0];
if (identity.isPair(it))
it = it.key;
const cb = it.commentBefore;
it.commentBefore = cb ? `${comment}
${cb}` : comment;
} else {
const cb = dc.commentBefore;
dc.commentBefore = cb ? `${comment}
${cb}` : comment;
}
}
if (afterDoc) {
Array.prototype.push.apply(doc.errors, this.errors);
Array.prototype.push.apply(doc.warnings, this.warnings);
} else {
doc.errors = this.errors;
doc.warnings = this.warnings;
}
this.prelude = [];
this.errors = [];
this.warnings = [];
}
/**
* Current stream status information.
*
* Mostly useful at the end of input for an empty stream.
*/
streamInfo() {
return {
comment: parsePrelude(this.prelude).comment,
directives: this.directives,
errors: this.errors,
warnings: this.warnings
};
}
/**
* Compose tokens into documents.
*
* @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
* @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
*/
*compose(tokens, forceDoc = false, endOffset = -1) {
for (const token of tokens)
yield* this.next(token);
yield* this.end(forceDoc, endOffset);
}
/** Advance the composer by one CST token. */
*next(token) {
if (process.env.LOG_STREAM)
console.dir(token, { depth: null });
switch (token.type) {
case "directive":
this.directives.add(token.source, (offset, message, warning) => {
const pos = getErrorPos(token);
pos[0] += offset;
this.onError(pos, "BAD_DIRECTIVE", message, warning);
});
this.prelude.push(token.source);
this.atDirectives = true;
break;
case "document": {
const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError);
if (this.atDirectives && !doc.directives.docStart)
this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line");
this.decorate(doc, false);
if (this.doc)
yield this.doc;
this.doc = doc;
this.atDirectives = false;
break;
}
case "byte-order-mark":
case "space":
break;
case "comment":
case "newline":
this.prelude.push(token.source);
break;
case "error": {
const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message;
const error = new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg);
if (this.atDirectives || !this.doc)
this.errors.push(error);
else
this.doc.errors.push(error);
break;
}
case "doc-end": {
if (!this.doc) {
const msg = "Unexpected doc-end without preceding document";
this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg));
break;
}
this.doc.directives.docEnd = true;
const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
this.decorate(this.doc, true);
if (end.comment) {
const dc = this.doc.comment;
this.doc.comment = dc ? `${dc}
${end.comment}` : end.comment;
}
this.doc.range[2] = end.offset;
break;
}
default:
this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`));
}
}
/**
* Call at end of input to yield any remaining document.
*
* @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
* @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
*/
*end(forceDoc = false, endOffset = -1) {
if (this.doc) {
this.decorate(this.doc, true);
yield this.doc;
this.doc = null;
} else if (forceDoc) {
const opts = Object.assign({ _directives: this.directives }, this.options);
const doc = new Document.Document(void 0, opts);
if (this.atDirectives)
this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line");
doc.range = [0, endOffset, endOffset];
this.decorate(doc, false);
yield doc;
}
}
};
exports2.Composer = Composer;
}
});
// node_modules/yaml/dist/parse/cst-scalar.js
var require_cst_scalar = __commonJS({
"node_modules/yaml/dist/parse/cst-scalar.js"(exports2) {
"use strict";
var resolveBlockScalar = require_resolve_block_scalar();
var resolveFlowScalar = require_resolve_flow_scalar();
var errors = require_errors();
var stringifyString = require_stringifyString();
function resolveAsScalar(token, strict = true, onError) {
if (token) {
const _onError = (pos, code, message) => {
const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
if (onError)
onError(offset, code, message);
else
throw new errors.YAMLParseError([offset, offset + 1], code, message);
};
switch (token.type) {
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);
case "block-scalar":
return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);
}
}
return null;
}
function createScalarToken(value2, context) {
const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context;
const source = stringifyString.stringifyString({ type, value: value2 }, {
implicitKey,
indent: indent > 0 ? " ".repeat(indent) : "",
inFlow,
options: { blockQuote: true, lineWidth: -1 }
});
const end = context.end ?? [
{ type: "newline", offset: -1, indent, source: "\n" }
];
switch (source[0]) {
case "|":
case ">": {
const he = source.indexOf("\n");
const head = source.substring(0, he);
const body = source.substring(he + 1) + "\n";
const props = [
{ type: "block-scalar-header", offset, indent, source: head }
];
if (!addEndtoBlockProps(props, end))
props.push({ type: "newline", offset: -1, indent, source: "\n" });
return { type: "block-scalar", offset, indent, props, source: body };
}
case '"':
return { type: "double-quoted-scalar", offset, indent, source, end };
case "'":
return { type: "single-quoted-scalar", offset, indent, source, end };
default:
return { type: "scalar", offset, indent, source, end };
}
}
function setScalarValue(token, value2, context = {}) {
let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
let indent = "indent" in token ? token.indent : null;
if (afterKey && typeof indent === "number")
indent += 2;
if (!type)
switch (token.type) {
case "single-quoted-scalar":
type = "QUOTE_SINGLE";
break;
case "double-quoted-scalar":
type = "QUOTE_DOUBLE";
break;
case "block-scalar": {
const header = token.props[0];
if (header.type !== "block-scalar-header")
throw new Error("Invalid block scalar header");
type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL";
break;
}
default:
type = "PLAIN";
}
const source = stringifyString.stringifyString({ type, value: value2 }, {
implicitKey: implicitKey || indent === null,
indent: indent !== null && indent > 0 ? " ".repeat(indent) : "",
inFlow,
options: { blockQuote: true, lineWidth: -1 }
});
switch (source[0]) {
case "|":
case ">":
setBlockScalarValue(token, source);
break;
case '"':
setFlowScalarValue(token, source, "double-quoted-scalar");
break;
case "'":
setFlowScalarValue(token, source, "single-quoted-scalar");
break;
default:
setFlowScalarValue(token, source, "scalar");
}
}
function setBlockScalarValue(token, source) {
const he = source.indexOf("\n");
const head = source.substring(0, he);
const body = source.substring(he + 1) + "\n";
if (token.type === "block-scalar") {
const header = token.props[0];
if (header.type !== "block-scalar-header")
throw new Error("Invalid block scalar header");
header.source = head;
token.source = body;
} else {
const { offset } = token;
const indent = "indent" in token ? token.indent : -1;
const props = [
{ type: "block-scalar-header", offset, indent, source: head }
];
if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0))
props.push({ type: "newline", offset: -1, indent, source: "\n" });
for (const key of Object.keys(token))
if (key !== "type" && key !== "offset")
delete token[key];
Object.assign(token, { type: "block-scalar", indent, props, source: body });
}
}
function addEndtoBlockProps(props, end) {
if (end)
for (const st of end)
switch (st.type) {
case "space":
case "comment":
props.push(st);
break;
case "newline":
props.push(st);
return true;
}
return false;
}
function setFlowScalarValue(token, source, type) {
switch (token.type) {
case "scalar":
case "double-quoted-scalar":
case "single-quoted-scalar":
token.type = type;
token.source = source;
break;
case "block-scalar": {
const end = token.props.slice(1);
let oa = source.length;
if (token.props[0].type === "block-scalar-header")
oa -= token.props[0].source.length;
for (const tok of end)
tok.offset += oa;
delete token.props;
Object.assign(token, { type, source, end });
break;
}
case "block-map":
case "block-seq": {
const offset = token.offset + source.length;
const nl = { type: "newline", offset, indent: token.indent, source: "\n" };
delete token.items;
Object.assign(token, { type, source, end: [nl] });
break;
}
default: {
const indent = "indent" in token ? token.indent : -1;
const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : [];
for (const key of Object.keys(token))
if (key !== "type" && key !== "offset")
delete token[key];
Object.assign(token, { type, indent, source, end });
}
}
}
exports2.createScalarToken = createScalarToken;
exports2.resolveAsScalar = resolveAsScalar;
exports2.setScalarValue = setScalarValue;
}
});
// node_modules/yaml/dist/parse/cst-stringify.js
var require_cst_stringify = __commonJS({
"node_modules/yaml/dist/parse/cst-stringify.js"(exports2) {
"use strict";
var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst);
function stringifyToken(token) {
switch (token.type) {
case "block-scalar": {
let res = "";
for (const tok of token.props)
res += stringifyToken(tok);
return res + token.source;
}
case "block-map":
case "block-seq": {
let res = "";
for (const item of token.items)
res += stringifyItem(item);
return res;
}
case "flow-collection": {
let res = token.start.source;
for (const item of token.items)
res += stringifyItem(item);
for (const st of token.end)
res += st.source;
return res;
}
case "document": {
let res = stringifyItem(token);
if (token.end)
for (const st of token.end)
res += st.source;
return res;
}
default: {
let res = token.source;
if ("end" in token && token.end)
for (const st of token.end)
res += st.source;
return res;
}
}
}
function stringifyItem({ start, key, sep, value: value2 }) {
let res = "";
for (const st of start)
res += st.source;
if (key)
res += stringifyToken(key);
if (sep)
for (const st of sep)
res += st.source;
if (value2)
res += stringifyToken(value2);
return res;
}
exports2.stringify = stringify2;
}
});
// node_modules/yaml/dist/parse/cst-visit.js
var require_cst_visit = __commonJS({
"node_modules/yaml/dist/parse/cst-visit.js"(exports2) {
"use strict";
var BREAK = Symbol("break visit");
var SKIP = Symbol("skip children");
var REMOVE = Symbol("remove item");
function visit(cst, visitor) {
if ("type" in cst && cst.type === "document")
cst = { start: cst.start, value: cst.value };
_visit(Object.freeze([]), cst, visitor);
}
visit.BREAK = BREAK;
visit.SKIP = SKIP;
visit.REMOVE = REMOVE;
visit.itemAtPath = (cst, path) => {
let item = cst;
for (const [field, index] of path) {
const tok = item?.[field];
if (tok && "items" in tok) {
item = tok.items[index];
} else
return void 0;
}
return item;
};
visit.parentCollection = (cst, path) => {
const parent = visit.itemAtPath(cst, path.slice(0, -1));
const field = path[path.length - 1][0];
const coll = parent?.[field];
if (coll && "items" in coll)
return coll;
throw new Error("Parent collection not found");
};
function _visit(path, item, visitor) {
let ctrl = visitor(item, path);
if (typeof ctrl === "symbol")
return ctrl;
for (const field of ["key", "value"]) {
const token = item[field];
if (token && "items" in token) {
for (let i = 0; i < token.items.length; ++i) {
const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);
if (typeof ci === "number")
i = ci - 1;
else if (ci === BREAK)
return BREAK;
else if (ci === REMOVE) {
token.items.splice(i, 1);
i -= 1;
}
}
if (typeof ctrl === "function" && field === "key")
ctrl = ctrl(item, path);
}
}
return typeof ctrl === "function" ? ctrl(item, path) : ctrl;
}
exports2.visit = visit;
}
});
// node_modules/yaml/dist/parse/cst.js
var require_cst = __commonJS({
"node_modules/yaml/dist/parse/cst.js"(exports2) {
"use strict";
var cstScalar = require_cst_scalar();
var cstStringify = require_cst_stringify();
var cstVisit = require_cst_visit();
var BOM = "\uFEFF";
var DOCUMENT = "";
var FLOW_END = "";
var SCALAR = "";
var isCollection = (token) => !!token && "items" in token;
var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
function prettyToken(token) {
switch (token) {
case BOM:
return "<BOM>";
case DOCUMENT:
return "<DOC>";
case FLOW_END:
return "<FLOW_END>";
case SCALAR:
return "<SCALAR>";
default:
return JSON.stringify(token);
}
}
function tokenType(source) {
switch (source) {
case BOM:
return "byte-order-mark";
case DOCUMENT:
return "doc-mode";
case FLOW_END:
return "flow-error-end";
case SCALAR:
return "scalar";
case "---":
return "doc-start";
case "...":
return "doc-end";
case "":
case "\n":
case "\r\n":
return "newline";
case "-":
return "seq-item-ind";
case "?":
return "explicit-key-ind";
case ":":
return "map-value-ind";
case "{":
return "flow-map-start";
case "}":
return "flow-map-end";
case "[":
return "flow-seq-start";
case "]":
return "flow-seq-end";
case ",":
return "comma";
}
switch (source[0]) {
case " ":
case " ":
return "space";
case "#":
return "comment";
case "%":
return "directive-line";
case "*":
return "alias";
case "&":
return "anchor";
case "!":
return "tag";
case "'":
return "single-quoted-scalar";
case '"':
return "double-quoted-scalar";
case "|":
case ">":
return "block-scalar-header";
}
return null;
}
exports2.createScalarToken = cstScalar.createScalarToken;
exports2.resolveAsScalar = cstScalar.resolveAsScalar;
exports2.setScalarValue = cstScalar.setScalarValue;
exports2.stringify = cstStringify.stringify;
exports2.visit = cstVisit.visit;
exports2.BOM = BOM;
exports2.DOCUMENT = DOCUMENT;
exports2.FLOW_END = FLOW_END;
exports2.SCALAR = SCALAR;
exports2.isCollection = isCollection;
exports2.isScalar = isScalar;
exports2.prettyToken = prettyToken;
exports2.tokenType = tokenType;
}
});
// node_modules/yaml/dist/parse/lexer.js
var require_lexer = __commonJS({
"node_modules/yaml/dist/parse/lexer.js"(exports2) {
"use strict";
var cst = require_cst();
function isEmpty(ch) {
switch (ch) {
case void 0:
case " ":
case "\n":
case "\r":
case " ":
return true;
default:
return false;
}
}
var hexDigits = new Set("0123456789ABCDEFabcdef");
var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
var flowIndicatorChars = new Set(",[]{}");
var invalidAnchorChars = new Set(" ,[]{}\n\r ");
var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);
var Lexer = class {
constructor() {
this.atEnd = false;
this.blockScalarIndent = -1;
this.blockScalarKeep = false;
this.buffer = "";
this.flowKey = false;
this.flowLevel = 0;
this.indentNext = 0;
this.indentValue = 0;
this.lineEndPos = null;
this.next = null;
this.pos = 0;
}
/**
* Generate YAML tokens from the `source` string. If `incomplete`,
* a part of the last line may be left as a buffer for the next call.
*
* @returns A generator of lexical tokens
*/
*lex(source, incomplete = false) {
if (source) {
if (typeof source !== "string")
throw TypeError("source is not a string");
this.buffer = this.buffer ? this.buffer + source : source;
this.lineEndPos = null;
}
this.atEnd = !incomplete;
let next = this.next ?? "stream";
while (next && (incomplete || this.hasChars(1)))
next = yield* this.parseNext(next);
}
atLineEnd() {
let i = this.pos;
let ch = this.buffer[i];
while (ch === " " || ch === " ")
ch = this.buffer[++i];
if (!ch || ch === "#" || ch === "\n")
return true;
if (ch === "\r")
return this.buffer[i + 1] === "\n";
return false;
}
charAt(n) {
return this.buffer[this.pos + n];
}
continueScalar(offset) {
let ch = this.buffer[offset];
if (this.indentNext > 0) {
let indent = 0;
while (ch === " ")
ch = this.buffer[++indent + offset];
if (ch === "\r") {
const next = this.buffer[indent + offset + 1];
if (next === "\n" || !next && !this.atEnd)
return offset + indent + 1;
}
return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1;
}
if (ch === "-" || ch === ".") {
const dt = this.buffer.substr(offset, 3);
if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3]))
return -1;
}
return offset;
}
getLine() {
let end = this.lineEndPos;
if (typeof end !== "number" || end !== -1 && end < this.pos) {
end = this.buffer.indexOf("\n", this.pos);
this.lineEndPos = end;
}
if (end === -1)
return this.atEnd ? this.buffer.substring(this.pos) : null;
if (this.buffer[end - 1] === "\r")
end -= 1;
return this.buffer.substring(this.pos, end);
}
hasChars(n) {
return this.pos + n <= this.buffer.length;
}
setNext(state) {
this.buffer = this.buffer.substring(this.pos);
this.pos = 0;
this.lineEndPos = null;
this.next = state;
return null;
}
peek(n) {
return this.buffer.substr(this.pos, n);
}
*parseNext(next) {
switch (next) {
case "stream":
return yield* this.parseStream();
case "line-start":
return yield* this.parseLineStart();
case "block-start":
return yield* this.parseBlockStart();
case "doc":
return yield* this.parseDocument();
case "flow":
return yield* this.parseFlowCollection();
case "quoted-scalar":
return yield* this.parseQuotedScalar();
case "block-scalar":
return yield* this.parseBlockScalar();
case "plain-scalar":
return yield* this.parsePlainScalar();
}
}
*parseStream() {
let line = this.getLine();
if (line === null)
return this.setNext("stream");
if (line[0] === cst.BOM) {
yield* this.pushCount(1);
line = line.substring(1);
}
if (line[0] === "%") {
let dirEnd = line.length;
let cs = line.indexOf("#");
while (cs !== -1) {
const ch = line[cs - 1];
if (ch === " " || ch === " ") {
dirEnd = cs - 1;
break;
} else {
cs = line.indexOf("#", cs + 1);
}
}
while (true) {
const ch = line[dirEnd - 1];
if (ch === " " || ch === " ")
dirEnd -= 1;
else
break;
}
const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
yield* this.pushCount(line.length - n);
this.pushNewline();
return "stream";
}
if (this.atLineEnd()) {
const sp = yield* this.pushSpaces(true);
yield* this.pushCount(line.length - sp);
yield* this.pushNewline();
return "stream";
}
yield cst.DOCUMENT;
return yield* this.parseLineStart();
}
*parseLineStart() {
const ch = this.charAt(0);
if (!ch && !this.atEnd)
return this.setNext("line-start");
if (ch === "-" || ch === ".") {
if (!this.atEnd && !this.hasChars(4))
return this.setNext("line-start");
const s = this.peek(3);
if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) {
yield* this.pushCount(3);
this.indentValue = 0;
this.indentNext = 0;
return s === "---" ? "doc" : "stream";
}
}
this.indentValue = yield* this.pushSpaces(false);
if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
this.indentNext = this.indentValue;
return yield* this.parseBlockStart();
}
*parseBlockStart() {
const [ch0, ch1] = this.peek(2);
if (!ch1 && !this.atEnd)
return this.setNext("block-start");
if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) {
const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
this.indentNext = this.indentValue + 1;
this.indentValue += n;
return yield* this.parseBlockStart();
}
return "doc";
}
*parseDocument() {
yield* this.pushSpaces(true);
const line = this.getLine();
if (line === null)
return this.setNext("doc");
let n = yield* this.pushIndicators();
switch (line[n]) {
case "#":
yield* this.pushCount(line.length - n);
// fallthrough
case void 0:
yield* this.pushNewline();
return yield* this.parseLineStart();
case "{":
case "[":
yield* this.pushCount(1);
this.flowKey = false;
this.flowLevel = 1;
return "flow";
case "}":
case "]":
yield* this.pushCount(1);
return "doc";
case "*":
yield* this.pushUntil(isNotAnchorChar);
return "doc";
case '"':
case "'":
return yield* this.parseQuotedScalar();
case "|":
case ">":
n += yield* this.parseBlockScalarHeader();
n += yield* this.pushSpaces(true);
yield* this.pushCount(line.length - n);
yield* this.pushNewline();
return yield* this.parseBlockScalar();
default:
return yield* this.parsePlainScalar();
}
}
*parseFlowCollection() {
let nl, sp;
let indent = -1;
do {
nl = yield* this.pushNewline();
if (nl > 0) {
sp = yield* this.pushSpaces(false);
this.indentValue = indent = sp;
} else {
sp = 0;
}
sp += yield* this.pushSpaces(true);
} while (nl + sp > 0);
const line = this.getLine();
if (line === null)
return this.setNext("flow");
if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) {
const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}");
if (!atFlowEndMarker) {
this.flowLevel = 0;
yield cst.FLOW_END;
return yield* this.parseLineStart();
}
}
let n = 0;
while (line[n] === ",") {
n += yield* this.pushCount(1);
n += yield* this.pushSpaces(true);
this.flowKey = false;
}
n += yield* this.pushIndicators();
switch (line[n]) {
case void 0:
return "flow";
case "#":
yield* this.pushCount(line.length - n);
return "flow";
case "{":
case "[":
yield* this.pushCount(1);
this.flowKey = false;
this.flowLevel += 1;
return "flow";
case "}":
case "]":
yield* this.pushCount(1);
this.flowKey = true;
this.flowLevel -= 1;
return this.flowLevel ? "flow" : "doc";
case "*":
yield* this.pushUntil(isNotAnchorChar);
return "flow";
case '"':
case "'":
this.flowKey = true;
return yield* this.parseQuotedScalar();
case ":": {
const next = this.charAt(1);
if (this.flowKey || isEmpty(next) || next === ",") {
this.flowKey = false;
yield* this.pushCount(1);
yield* this.pushSpaces(true);
return "flow";
}
}
// fallthrough
default:
this.flowKey = false;
return yield* this.parsePlainScalar();
}
}
*parseQuotedScalar() {
const quote = this.charAt(0);
let end = this.buffer.indexOf(quote, this.pos + 1);
if (quote === "'") {
while (end !== -1 && this.buffer[end + 1] === "'")
end = this.buffer.indexOf("'", end + 2);
} else {
while (end !== -1) {
let n = 0;
while (this.buffer[end - 1 - n] === "\\")
n += 1;
if (n % 2 === 0)
break;
end = this.buffer.indexOf('"', end + 1);
}
}
const qb = this.buffer.substring(0, end);
let nl = qb.indexOf("\n", this.pos);
if (nl !== -1) {
while (nl !== -1) {
const cs = this.continueScalar(nl + 1);
if (cs === -1)
break;
nl = qb.indexOf("\n", cs);
}
if (nl !== -1) {
end = nl - (qb[nl - 1] === "\r" ? 2 : 1);
}
}
if (end === -1) {
if (!this.atEnd)
return this.setNext("quoted-scalar");
end = this.buffer.length;
}
yield* this.pushToIndex(end + 1, false);
return this.flowLevel ? "flow" : "doc";
}
*parseBlockScalarHeader() {
this.blockScalarIndent = -1;
this.blockScalarKeep = false;
let i = this.pos;
while (true) {
const ch = this.buffer[++i];
if (ch === "+")
this.blockScalarKeep = true;
else if (ch > "0" && ch <= "9")
this.blockScalarIndent = Number(ch) - 1;
else if (ch !== "-")
break;
}
return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#");
}
*parseBlockScalar() {
let nl = this.pos - 1;
let indent = 0;
let ch;
loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) {
switch (ch) {
case " ":
indent += 1;
break;
case "\n":
nl = i2;
indent = 0;
break;
case "\r": {
const next = this.buffer[i2 + 1];
if (!next && !this.atEnd)
return this.setNext("block-scalar");
if (next === "\n")
break;
}
// fallthrough
default:
break loop;
}
}
if (!ch && !this.atEnd)
return this.setNext("block-scalar");
if (indent >= this.indentNext) {
if (this.blockScalarIndent === -1)
this.indentNext = indent;
else {
this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
}
do {
const cs = this.continueScalar(nl + 1);
if (cs === -1)
break;
nl = this.buffer.indexOf("\n", cs);
} while (nl !== -1);
if (nl === -1) {
if (!this.atEnd)
return this.setNext("block-scalar");
nl = this.buffer.length;
}
}
let i = nl + 1;
ch = this.buffer[i];
while (ch === " ")
ch = this.buffer[++i];
if (ch === " ") {
while (ch === " " || ch === " " || ch === "\r" || ch === "\n")
ch = this.buffer[++i];
nl = i - 1;
} else if (!this.blockScalarKeep) {
do {
let i2 = nl - 1;
let ch2 = this.buffer[i2];
if (ch2 === "\r")
ch2 = this.buffer[--i2];
const lastChar = i2;
while (ch2 === " ")
ch2 = this.buffer[--i2];
if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar)
nl = i2;
else
break;
} while (true);
}
yield cst.SCALAR;
yield* this.pushToIndex(nl + 1, true);
return yield* this.parseLineStart();
}
*parsePlainScalar() {
const inFlow = this.flowLevel > 0;
let end = this.pos - 1;
let i = this.pos - 1;
let ch;
while (ch = this.buffer[++i]) {
if (ch === ":") {
const next = this.buffer[i + 1];
if (isEmpty(next) || inFlow && flowIndicatorChars.has(next))
break;
end = i;
} else if (isEmpty(ch)) {
let next = this.buffer[i + 1];
if (ch === "\r") {
if (next === "\n") {
i += 1;
ch = "\n";
next = this.buffer[i + 1];
} else
end = i;
}
if (next === "#" || inFlow && flowIndicatorChars.has(next))
break;
if (ch === "\n") {
const cs = this.continueScalar(i + 1);
if (cs === -1)
break;
i = Math.max(i, cs - 2);
}
} else {
if (inFlow && flowIndicatorChars.has(ch))
break;
end = i;
}
}
if (!ch && !this.atEnd)
return this.setNext("plain-scalar");
yield cst.SCALAR;
yield* this.pushToIndex(end + 1, true);
return inFlow ? "flow" : "doc";
}
*pushCount(n) {
if (n > 0) {
yield this.buffer.substr(this.pos, n);
this.pos += n;
return n;
}
return 0;
}
*pushToIndex(i, allowEmpty) {
const s = this.buffer.slice(this.pos, i);
if (s) {
yield s;
this.pos += s.length;
return s.length;
} else if (allowEmpty)
yield "";
return 0;
}
*pushIndicators() {
switch (this.charAt(0)) {
case "!":
return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
case "&":
return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
case "-":
// this is an error
case "?":
// this is an error outside flow collections
case ":": {
const inFlow = this.flowLevel > 0;
const ch1 = this.charAt(1);
if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) {
if (!inFlow)
this.indentNext = this.indentValue + 1;
else if (this.flowKey)
this.flowKey = false;
return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
}
}
}
return 0;
}
*pushTag() {
if (this.charAt(1) === "<") {
let i = this.pos + 2;
let ch = this.buffer[i];
while (!isEmpty(ch) && ch !== ">")
ch = this.buffer[++i];
return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false);
} else {
let i = this.pos + 1;
let ch = this.buffer[i];
while (ch) {
if (tagChars.has(ch))
ch = this.buffer[++i];
else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) {
ch = this.buffer[i += 3];
} else
break;
}
return yield* this.pushToIndex(i, false);
}
}
*pushNewline() {
const ch = this.buffer[this.pos];
if (ch === "\n")
return yield* this.pushCount(1);
else if (ch === "\r" && this.charAt(1) === "\n")
return yield* this.pushCount(2);
else
return 0;
}
*pushSpaces(allowTabs) {
let i = this.pos - 1;
let ch;
do {
ch = this.buffer[++i];
} while (ch === " " || allowTabs && ch === " ");
const n = i - this.pos;
if (n > 0) {
yield this.buffer.substr(this.pos, n);
this.pos = i;
}
return n;
}
*pushUntil(test) {
let i = this.pos;
let ch = this.buffer[i];
while (!test(ch))
ch = this.buffer[++i];
return yield* this.pushToIndex(i, false);
}
};
exports2.Lexer = Lexer;
}
});
// node_modules/yaml/dist/parse/line-counter.js
var require_line_counter = __commonJS({
"node_modules/yaml/dist/parse/line-counter.js"(exports2) {
"use strict";
var LineCounter = class {
constructor() {
this.lineStarts = [];
this.addNewLine = (offset) => this.lineStarts.push(offset);
this.linePos = (offset) => {
let low = 0;
let high = this.lineStarts.length;
while (low < high) {
const mid = low + high >> 1;
if (this.lineStarts[mid] < offset)
low = mid + 1;
else
high = mid;
}
if (this.lineStarts[low] === offset)
return { line: low + 1, col: 1 };
if (low === 0)
return { line: 0, col: offset };
const start = this.lineStarts[low - 1];
return { line: low, col: offset - start + 1 };
};
}
};
exports2.LineCounter = LineCounter;
}
});
// node_modules/yaml/dist/parse/parser.js
var require_parser = __commonJS({
"node_modules/yaml/dist/parse/parser.js"(exports2) {
"use strict";
var cst = require_cst();
var lexer = require_lexer();
function includesToken(list, type) {
for (let i = 0; i < list.length; ++i)
if (list[i].type === type)
return true;
return false;
}
function findNonEmptyIndex(list) {
for (let i = 0; i < list.length; ++i) {
switch (list[i].type) {
case "space":
case "comment":
case "newline":
break;
default:
return i;
}
}
return -1;
}
function isFlowToken(token) {
switch (token?.type) {
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
case "flow-collection":
return true;
default:
return false;
}
}
function getPrevProps(parent) {
switch (parent.type) {
case "document":
return parent.start;
case "block-map": {
const it = parent.items[parent.items.length - 1];
return it.sep ?? it.start;
}
case "block-seq":
return parent.items[parent.items.length - 1].start;
/* istanbul ignore next should not happen */
default:
return [];
}
}
function getFirstKeyStartProps(prev) {
if (prev.length === 0)
return [];
let i = prev.length;
loop: while (--i >= 0) {
switch (prev[i].type) {
case "doc-start":
case "explicit-key-ind":
case "map-value-ind":
case "seq-item-ind":
case "newline":
break loop;
}
}
while (prev[++i]?.type === "space") {
}
return prev.splice(i, prev.length);
}
function fixFlowSeqItems(fc) {
if (fc.start.type === "flow-seq-start") {
for (const it of fc.items) {
if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) {
if (it.key)
it.value = it.key;
delete it.key;
if (isFlowToken(it.value)) {
if (it.value.end)
Array.prototype.push.apply(it.value.end, it.sep);
else
it.value.end = it.sep;
} else
Array.prototype.push.apply(it.start, it.sep);
delete it.sep;
}
}
}
}
var Parser = class {
/**
* @param onNewLine - If defined, called separately with the start position of
* each new line (in `parse()`, including the start of input).
*/
constructor(onNewLine) {
this.atNewLine = true;
this.atScalar = false;
this.indent = 0;
this.offset = 0;
this.onKeyLine = false;
this.stack = [];
this.source = "";
this.type = "";
this.lexer = new lexer.Lexer();
this.onNewLine = onNewLine;
}
/**
* Parse `source` as a YAML stream.
* If `incomplete`, a part of the last line may be left as a buffer for the next call.
*
* Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
*
* @returns A generator of tokens representing each directive, document, and other structure.
*/
*parse(source, incomplete = false) {
if (this.onNewLine && this.offset === 0)
this.onNewLine(0);
for (const lexeme of this.lexer.lex(source, incomplete))
yield* this.next(lexeme);
if (!incomplete)
yield* this.end();
}
/**
* Advance the parser by the `source` of one lexical token.
*/
*next(source) {
this.source = source;
if (process.env.LOG_TOKENS)
console.log("|", cst.prettyToken(source));
if (this.atScalar) {
this.atScalar = false;
yield* this.step();
this.offset += source.length;
return;
}
const type = cst.tokenType(source);
if (!type) {
const message = `Not a YAML token: ${source}`;
yield* this.pop({ type: "error", offset: this.offset, message, source });
this.offset += source.length;
} else if (type === "scalar") {
this.atNewLine = false;
this.atScalar = true;
this.type = "scalar";
} else {
this.type = type;
yield* this.step();
switch (type) {
case "newline":
this.atNewLine = true;
this.indent = 0;
if (this.onNewLine)
this.onNewLine(this.offset + source.length);
break;
case "space":
if (this.atNewLine && source[0] === " ")
this.indent += source.length;
break;
case "explicit-key-ind":
case "map-value-ind":
case "seq-item-ind":
if (this.atNewLine)
this.indent += source.length;
break;
case "doc-mode":
case "flow-error-end":
return;
default:
this.atNewLine = false;
}
this.offset += source.length;
}
}
/** Call at end of input to push out any remaining constructions */
*end() {
while (this.stack.length > 0)
yield* this.pop();
}
get sourceToken() {
const st = {
type: this.type,
offset: this.offset,
indent: this.indent,
source: this.source
};
return st;
}
*step() {
const top = this.peek(1);
if (this.type === "doc-end" && (!top || top.type !== "doc-end")) {
while (this.stack.length > 0)
yield* this.pop();
this.stack.push({
type: "doc-end",
offset: this.offset,
source: this.source
});
return;
}
if (!top)
return yield* this.stream();
switch (top.type) {
case "document":
return yield* this.document(top);
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
return yield* this.scalar(top);
case "block-scalar":
return yield* this.blockScalar(top);
case "block-map":
return yield* this.blockMap(top);
case "block-seq":
return yield* this.blockSequence(top);
case "flow-collection":
return yield* this.flowCollection(top);
case "doc-end":
return yield* this.documentEnd(top);
}
yield* this.pop();
}
peek(n) {
return this.stack[this.stack.length - n];
}
*pop(error) {
const token = error ?? this.stack.pop();
if (!token) {
const message = "Tried to pop an empty stack";
yield { type: "error", offset: this.offset, source: "", message };
} else if (this.stack.length === 0) {
yield token;
} else {
const top = this.peek(1);
if (token.type === "block-scalar") {
token.indent = "indent" in top ? top.indent : 0;
} else if (token.type === "flow-collection" && top.type === "document") {
token.indent = 0;
}
if (token.type === "flow-collection")
fixFlowSeqItems(token);
switch (top.type) {
case "document":
top.value = token;
break;
case "block-scalar":
top.props.push(token);
break;
case "block-map": {
const it = top.items[top.items.length - 1];
if (it.value) {
top.items.push({ start: [], key: token, sep: [] });
this.onKeyLine = true;
return;
} else if (it.sep) {
it.value = token;
} else {
Object.assign(it, { key: token, sep: [] });
this.onKeyLine = !it.explicitKey;
return;
}
break;
}
case "block-seq": {
const it = top.items[top.items.length - 1];
if (it.value)
top.items.push({ start: [], value: token });
else
it.value = token;
break;
}
case "flow-collection": {
const it = top.items[top.items.length - 1];
if (!it || it.value)
top.items.push({ start: [], key: token, sep: [] });
else if (it.sep)
it.value = token;
else
Object.assign(it, { key: token, sep: [] });
return;
}
/* istanbul ignore next should not happen */
default:
yield* this.pop();
yield* this.pop(token);
}
if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) {
const last = token.items[token.items.length - 1];
if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) {
if (top.type === "document")
top.end = last.start;
else
top.items.push({ start: last.start });
token.items.splice(-1, 1);
}
}
}
}
*stream() {
switch (this.type) {
case "directive-line":
yield { type: "directive", offset: this.offset, source: this.source };
return;
case "byte-order-mark":
case "space":
case "comment":
case "newline":
yield this.sourceToken;
return;
case "doc-mode":
case "doc-start": {
const doc = {
type: "document",
offset: this.offset,
start: []
};
if (this.type === "doc-start")
doc.start.push(this.sourceToken);
this.stack.push(doc);
return;
}
}
yield {
type: "error",
offset: this.offset,
message: `Unexpected ${this.type} token in YAML stream`,
source: this.source
};
}
*document(doc) {
if (doc.value)
return yield* this.lineEnd(doc);
switch (this.type) {
case "doc-start": {
if (findNonEmptyIndex(doc.start) !== -1) {
yield* this.pop();
yield* this.step();
} else
doc.start.push(this.sourceToken);
return;
}
case "anchor":
case "tag":
case "space":
case "comment":
case "newline":
doc.start.push(this.sourceToken);
return;
}
const bv = this.startBlockValue(doc);
if (bv)
this.stack.push(bv);
else {
yield {
type: "error",
offset: this.offset,
message: `Unexpected ${this.type} token in YAML document`,
source: this.source
};
}
}
*scalar(scalar) {
if (this.type === "map-value-ind") {
const prev = getPrevProps(this.peek(2));
const start = getFirstKeyStartProps(prev);
let sep;
if (scalar.end) {
sep = scalar.end;
sep.push(this.sourceToken);
delete scalar.end;
} else
sep = [this.sourceToken];
const map2 = {
type: "block-map",
offset: scalar.offset,
indent: scalar.indent,
items: [{ start, key: scalar, sep }]
};
this.onKeyLine = true;
this.stack[this.stack.length - 1] = map2;
} else
yield* this.lineEnd(scalar);
}
*blockScalar(scalar) {
switch (this.type) {
case "space":
case "comment":
case "newline":
scalar.props.push(this.sourceToken);
return;
case "scalar":
scalar.source = this.source;
this.atNewLine = true;
this.indent = 0;
if (this.onNewLine) {
let nl = this.source.indexOf("\n") + 1;
while (nl !== 0) {
this.onNewLine(this.offset + nl);
nl = this.source.indexOf("\n", nl) + 1;
}
}
yield* this.pop();
break;
/* istanbul ignore next should not happen */
default:
yield* this.pop();
yield* this.step();
}
}
*blockMap(map2) {
const it = map2.items[map2.items.length - 1];
switch (this.type) {
case "newline":
this.onKeyLine = false;
if (it.value) {
const end = "end" in it.value ? it.value.end : void 0;
const last = Array.isArray(end) ? end[end.length - 1] : void 0;
if (last?.type === "comment")
end?.push(this.sourceToken);
else
map2.items.push({ start: [this.sourceToken] });
} else if (it.sep) {
it.sep.push(this.sourceToken);
} else {
it.start.push(this.sourceToken);
}
return;
case "space":
case "comment":
if (it.value) {
map2.items.push({ start: [this.sourceToken] });
} else if (it.sep) {
it.sep.push(this.sourceToken);
} else {
if (this.atIndentedComment(it.start, map2.indent)) {
const prev = map2.items[map2.items.length - 2];
const end = prev?.value?.end;
if (Array.isArray(end)) {
Array.prototype.push.apply(end, it.start);
end.push(this.sourceToken);
map2.items.pop();
return;
}
}
it.start.push(this.sourceToken);
}
return;
}
if (this.indent >= map2.indent) {
const atMapIndent = !this.onKeyLine && this.indent === map2.indent;
const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind";
let start = [];
if (atNextItem && it.sep && !it.value) {
const nl = [];
for (let i = 0; i < it.sep.length; ++i) {
const st = it.sep[i];
switch (st.type) {
case "newline":
nl.push(i);
break;
case "space":
break;
case "comment":
if (st.indent > map2.indent)
nl.length = 0;
break;
default:
nl.length = 0;
}
}
if (nl.length >= 2)
start = it.sep.splice(nl[1]);
}
switch (this.type) {
case "anchor":
case "tag":
if (atNextItem || it.value) {
start.push(this.sourceToken);
map2.items.push({ start });
this.onKeyLine = true;
} else if (it.sep) {
it.sep.push(this.sourceToken);
} else {
it.start.push(this.sourceToken);
}
return;
case "explicit-key-ind":
if (!it.sep && !it.explicitKey) {
it.start.push(this.sourceToken);
it.explicitKey = true;
} else if (atNextItem || it.value) {
start.push(this.sourceToken);
map2.items.push({ start, explicitKey: true });
} else {
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken], explicitKey: true }]
});
}
this.onKeyLine = true;
return;
case "map-value-ind":
if (it.explicitKey) {
if (!it.sep) {
if (includesToken(it.start, "newline")) {
Object.assign(it, { key: null, sep: [this.sourceToken] });
} else {
const start2 = getFirstKeyStartProps(it.start);
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: start2, key: null, sep: [this.sourceToken] }]
});
}
} else if (it.value) {
map2.items.push({ start: [], key: null, sep: [this.sourceToken] });
} else if (includesToken(it.sep, "map-value-ind")) {
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start, key: null, sep: [this.sourceToken] }]
});
} else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
const start2 = getFirstKeyStartProps(it.start);
const key = it.key;
const sep = it.sep;
sep.push(this.sourceToken);
delete it.key;
delete it.sep;
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: start2, key, sep }]
});
} else if (start.length > 0) {
it.sep = it.sep.concat(start, this.sourceToken);
} else {
it.sep.push(this.sourceToken);
}
} else {
if (!it.sep) {
Object.assign(it, { key: null, sep: [this.sourceToken] });
} else if (it.value || atNextItem) {
map2.items.push({ start, key: null, sep: [this.sourceToken] });
} else if (includesToken(it.sep, "map-value-ind")) {
this.stack.push({
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start: [], key: null, sep: [this.sourceToken] }]
});
} else {
it.sep.push(this.sourceToken);
}
}
this.onKeyLine = true;
return;
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar": {
const fs = this.flowScalar(this.type);
if (atNextItem || it.value) {
map2.items.push({ start, key: fs, sep: [] });
this.onKeyLine = true;
} else if (it.sep) {
this.stack.push(fs);
} else {
Object.assign(it, { key: fs, sep: [] });
this.onKeyLine = true;
}
return;
}
default: {
const bv = this.startBlockValue(map2);
if (bv) {
if (atMapIndent && bv.type !== "block-seq") {
map2.items.push({ start });
}
this.stack.push(bv);
return;
}
}
}
}
yield* this.pop();
yield* this.step();
}
*blockSequence(seq) {
const it = seq.items[seq.items.length - 1];
switch (this.type) {
case "newline":
if (it.value) {
const end = "end" in it.value ? it.value.end : void 0;
const last = Array.isArray(end) ? end[end.length - 1] : void 0;
if (last?.type === "comment")
end?.push(this.sourceToken);
else
seq.items.push({ start: [this.sourceToken] });
} else
it.start.push(this.sourceToken);
return;
case "space":
case "comment":
if (it.value)
seq.items.push({ start: [this.sourceToken] });
else {
if (this.atIndentedComment(it.start, seq.indent)) {
const prev = seq.items[seq.items.length - 2];
const end = prev?.value?.end;
if (Array.isArray(end)) {
Array.prototype.push.apply(end, it.start);
end.push(this.sourceToken);
seq.items.pop();
return;
}
}
it.start.push(this.sourceToken);
}
return;
case "anchor":
case "tag":
if (it.value || this.indent <= seq.indent)
break;
it.start.push(this.sourceToken);
return;
case "seq-item-ind":
if (this.indent !== seq.indent)
break;
if (it.value || includesToken(it.start, "seq-item-ind"))
seq.items.push({ start: [this.sourceToken] });
else
it.start.push(this.sourceToken);
return;
}
if (this.indent > seq.indent) {
const bv = this.startBlockValue(seq);
if (bv) {
this.stack.push(bv);
return;
}
}
yield* this.pop();
yield* this.step();
}
*flowCollection(fc) {
const it = fc.items[fc.items.length - 1];
if (this.type === "flow-error-end") {
let top;
do {
yield* this.pop();
top = this.peek(1);
} while (top && top.type === "flow-collection");
} else if (fc.end.length === 0) {
switch (this.type) {
case "comma":
case "explicit-key-ind":
if (!it || it.sep)
fc.items.push({ start: [this.sourceToken] });
else
it.start.push(this.sourceToken);
return;
case "map-value-ind":
if (!it || it.value)
fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
else if (it.sep)
it.sep.push(this.sourceToken);
else
Object.assign(it, { key: null, sep: [this.sourceToken] });
return;
case "space":
case "comment":
case "newline":
case "anchor":
case "tag":
if (!it || it.value)
fc.items.push({ start: [this.sourceToken] });
else if (it.sep)
it.sep.push(this.sourceToken);
else
it.start.push(this.sourceToken);
return;
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar": {
const fs = this.flowScalar(this.type);
if (!it || it.value)
fc.items.push({ start: [], key: fs, sep: [] });
else if (it.sep)
this.stack.push(fs);
else
Object.assign(it, { key: fs, sep: [] });
return;
}
case "flow-map-end":
case "flow-seq-end":
fc.end.push(this.sourceToken);
return;
}
const bv = this.startBlockValue(fc);
if (bv)
this.stack.push(bv);
else {
yield* this.pop();
yield* this.step();
}
} else {
const parent = this.peek(2);
if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) {
yield* this.pop();
yield* this.step();
} else if (this.type === "map-value-ind" && parent.type !== "flow-collection") {
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
fixFlowSeqItems(fc);
const sep = fc.end.splice(1, fc.end.length);
sep.push(this.sourceToken);
const map2 = {
type: "block-map",
offset: fc.offset,
indent: fc.indent,
items: [{ start, key: fc, sep }]
};
this.onKeyLine = true;
this.stack[this.stack.length - 1] = map2;
} else {
yield* this.lineEnd(fc);
}
}
}
flowScalar(type) {
if (this.onNewLine) {
let nl = this.source.indexOf("\n") + 1;
while (nl !== 0) {
this.onNewLine(this.offset + nl);
nl = this.source.indexOf("\n", nl) + 1;
}
}
return {
type,
offset: this.offset,
indent: this.indent,
source: this.source
};
}
startBlockValue(parent) {
switch (this.type) {
case "alias":
case "scalar":
case "single-quoted-scalar":
case "double-quoted-scalar":
return this.flowScalar(this.type);
case "block-scalar-header":
return {
type: "block-scalar",
offset: this.offset,
indent: this.indent,
props: [this.sourceToken],
source: ""
};
case "flow-map-start":
case "flow-seq-start":
return {
type: "flow-collection",
offset: this.offset,
indent: this.indent,
start: this.sourceToken,
items: [],
end: []
};
case "seq-item-ind":
return {
type: "block-seq",
offset: this.offset,
indent: this.indent,
items: [{ start: [this.sourceToken] }]
};
case "explicit-key-ind": {
this.onKeyLine = true;
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
start.push(this.sourceToken);
return {
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start, explicitKey: true }]
};
}
case "map-value-ind": {
this.onKeyLine = true;
const prev = getPrevProps(parent);
const start = getFirstKeyStartProps(prev);
return {
type: "block-map",
offset: this.offset,
indent: this.indent,
items: [{ start, key: null, sep: [this.sourceToken] }]
};
}
}
return null;
}
atIndentedComment(start, indent) {
if (this.type !== "comment")
return false;
if (this.indent <= indent)
return false;
return start.every((st) => st.type === "newline" || st.type === "space");
}
*documentEnd(docEnd) {
if (this.type !== "doc-mode") {
if (docEnd.end)
docEnd.end.push(this.sourceToken);
else
docEnd.end = [this.sourceToken];
if (this.type === "newline")
yield* this.pop();
}
}
*lineEnd(token) {
switch (this.type) {
case "comma":
case "doc-start":
case "doc-end":
case "flow-seq-end":
case "flow-map-end":
case "map-value-ind":
yield* this.pop();
yield* this.step();
break;
case "newline":
this.onKeyLine = false;
// fallthrough
case "space":
case "comment":
default:
if (token.end)
token.end.push(this.sourceToken);
else
token.end = [this.sourceToken];
if (this.type === "newline")
yield* this.pop();
}
}
};
exports2.Parser = Parser;
}
});
// node_modules/yaml/dist/public-api.js
var require_public_api = __commonJS({
"node_modules/yaml/dist/public-api.js"(exports2) {
"use strict";
var composer = require_composer();
var Document = require_Document();
var errors = require_errors();
var log = require_log();
var lineCounter = require_line_counter();
var parser = require_parser();
function parseOptions(options) {
const prettyErrors = options.prettyErrors !== false;
const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter() || null;
return { lineCounter: lineCounter$1, prettyErrors };
}
function parseAllDocuments(source, options = {}) {
const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
const composer$1 = new composer.Composer(options);
const docs = Array.from(composer$1.compose(parser$1.parse(source)));
if (prettyErrors && lineCounter2)
for (const doc of docs) {
doc.errors.forEach(errors.prettifyError(source, lineCounter2));
doc.warnings.forEach(errors.prettifyError(source, lineCounter2));
}
if (docs.length > 0)
return docs;
return Object.assign([], { empty: true }, composer$1.streamInfo());
}
function parseDocument(source, options = {}) {
const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
const composer$1 = new composer.Composer(options);
let doc = null;
for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {
if (!doc)
doc = _doc;
else if (doc.options.logLevel !== "silent") {
doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()"));
break;
}
}
if (prettyErrors && lineCounter2) {
doc.errors.forEach(errors.prettifyError(source, lineCounter2));
doc.warnings.forEach(errors.prettifyError(source, lineCounter2));
}
return doc;
}
function parse5(src, reviver, options) {
let _reviver = void 0;
if (typeof reviver === "function") {
_reviver = reviver;
} else if (options === void 0 && reviver && typeof reviver === "object") {
options = reviver;
}
const doc = parseDocument(src, options);
if (!doc)
return null;
doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning));
if (doc.errors.length > 0) {
if (doc.options.logLevel !== "silent")
throw doc.errors[0];
else
doc.errors = [];
}
return doc.toJS(Object.assign({ reviver: _reviver }, options));
}
function stringify2(value2, replacer, options) {
let _replacer = null;
if (typeof replacer === "function" || Array.isArray(replacer)) {
_replacer = replacer;
} else if (options === void 0 && replacer) {
options = replacer;
}
if (typeof options === "string")
options = options.length;
if (typeof options === "number") {
const indent = Math.round(options);
options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent };
}
if (value2 === void 0) {
const { keepUndefined } = options ?? replacer ?? {};
if (!keepUndefined)
return void 0;
}
return new Document.Document(value2, _replacer, options).toString(options);
}
exports2.parse = parse5;
exports2.parseAllDocuments = parseAllDocuments;
exports2.parseDocument = parseDocument;
exports2.stringify = stringify2;
}
});
// node_modules/yaml/dist/index.js
var require_dist = __commonJS({
"node_modules/yaml/dist/index.js"(exports2) {
"use strict";
var composer = require_composer();
var Document = require_Document();
var Schema = require_Schema();
var errors = require_errors();
var Alias = require_Alias();
var identity = require_identity();
var Pair = require_Pair();
var Scalar = require_Scalar();
var YAMLMap = require_YAMLMap();
var YAMLSeq = require_YAMLSeq();
var cst = require_cst();
var lexer = require_lexer();
var lineCounter = require_line_counter();
var parser = require_parser();
var publicApi = require_public_api();
var visit = require_visit();
exports2.Composer = composer.Composer;
exports2.Document = Document.Document;
exports2.Schema = Schema.Schema;
exports2.YAMLError = errors.YAMLError;
exports2.YAMLParseError = errors.YAMLParseError;
exports2.YAMLWarning = errors.YAMLWarning;
exports2.Alias = Alias.Alias;
exports2.isAlias = identity.isAlias;
exports2.isCollection = identity.isCollection;
exports2.isDocument = identity.isDocument;
exports2.isMap = identity.isMap;
exports2.isNode = identity.isNode;
exports2.isPair = identity.isPair;
exports2.isScalar = identity.isScalar;
exports2.isSeq = identity.isSeq;
exports2.Pair = Pair.Pair;
exports2.Scalar = Scalar.Scalar;
exports2.YAMLMap = YAMLMap.YAMLMap;
exports2.YAMLSeq = YAMLSeq.YAMLSeq;
exports2.CST = cst;
exports2.Lexer = lexer.Lexer;
exports2.LineCounter = lineCounter.LineCounter;
exports2.Parser = parser.Parser;
exports2.parse = publicApi.parse;
exports2.parseAllDocuments = publicApi.parseAllDocuments;
exports2.parseDocument = publicApi.parseDocument;
exports2.stringify = publicApi.stringify;
exports2.visit = visit.visit;
exports2.visitAsync = visit.visitAsync;
}
});
// node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js
var require_XMLHttpRequest = __commonJS({
"node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js"(exports2, module2) {
"use strict";
var fs = require("fs");
var Url = require("url");
var spawn = require("child_process").spawn;
module2.exports = XMLHttpRequest3;
XMLHttpRequest3.XMLHttpRequest = XMLHttpRequest3;
function XMLHttpRequest3(opts) {
"use strict";
opts = opts || {};
var self = this;
var http = require("http");
var https = require("https");
var request;
var response;
var settings = {};
var disableHeaderCheck = false;
var defaultHeaders = {
"User-Agent": "node-XMLHttpRequest",
"Accept": "*/*"
};
var headers = Object.assign({}, defaultHeaders);
var forbiddenRequestHeaders = [
"accept-charset",
"accept-encoding",
"access-control-request-headers",
"access-control-request-method",
"connection",
"content-length",
"content-transfer-encoding",
"cookie",
"cookie2",
"date",
"expect",
"host",
"keep-alive",
"origin",
"referer",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"via"
];
var forbiddenRequestMethods = [
"TRACE",
"TRACK",
"CONNECT"
];
var sendFlag = false;
var errorFlag = false;
var abortedFlag = false;
var listeners = {};
this.UNSENT = 0;
this.OPENED = 1;
this.HEADERS_RECEIVED = 2;
this.LOADING = 3;
this.DONE = 4;
this.readyState = this.UNSENT;
this.onreadystatechange = null;
this.responseText = "";
this.responseXML = "";
this.response = Buffer.alloc(0);
this.status = null;
this.statusText = null;
var isAllowedHttpHeader = function(header) {
return disableHeaderCheck || header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1;
};
var isAllowedHttpMethod = function(method) {
return method && forbiddenRequestMethods.indexOf(method) === -1;
};
this.open = function(method, url2, async, user, password) {
this.abort();
errorFlag = false;
abortedFlag = false;
if (!isAllowedHttpMethod(method)) {
throw new Error("SecurityError: Request method not allowed");
}
settings = {
"method": method,
"url": url2.toString(),
"async": typeof async !== "boolean" ? true : async,
"user": user || null,
"password": password || null
};
setState(this.OPENED);
};
this.setDisableHeaderCheck = function(state) {
disableHeaderCheck = state;
};
this.setRequestHeader = function(header, value2) {
if (this.readyState != this.OPENED) {
throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");
}
if (!isAllowedHttpHeader(header)) {
console.warn('Refused to set unsafe header "' + header + '"');
return false;
}
if (sendFlag) {
throw new Error("INVALID_STATE_ERR: send flag is true");
}
headers[header] = value2;
return true;
};
this.getResponseHeader = function(header) {
if (typeof header === "string" && this.readyState > this.OPENED && response.headers[header.toLowerCase()] && !errorFlag) {
return response.headers[header.toLowerCase()];
}
return null;
};
this.getAllResponseHeaders = function() {
if (this.readyState < this.HEADERS_RECEIVED || errorFlag) {
return "";
}
var result = "";
for (var i in response.headers) {
if (i !== "set-cookie" && i !== "set-cookie2") {
result += i + ": " + response.headers[i] + "\r\n";
}
}
return result.substr(0, result.length - 2);
};
this.getRequestHeader = function(name) {
if (typeof name === "string" && headers[name]) {
return headers[name];
}
return "";
};
this.send = function(data) {
if (this.readyState != this.OPENED) {
throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");
}
if (sendFlag) {
throw new Error("INVALID_STATE_ERR: send has already been called");
}
var ssl = false, local = false;
var url2 = Url.parse(settings.url);
var host;
switch (url2.protocol) {
case "https:":
ssl = true;
// SSL & non-SSL both need host, no break here.
case "http:":
host = url2.hostname;
break;
case "file:":
local = true;
break;
case void 0:
case "":
host = "localhost";
break;
default:
throw new Error("Protocol not supported.");
}
if (local) {
if (settings.method !== "GET") {
throw new Error("XMLHttpRequest: Only GET method is supported");
}
if (settings.async) {
fs.readFile(unescape(url2.pathname), function(error, data2) {
if (error) {
self.handleError(error, error.errno || -1);
} else {
self.status = 200;
self.responseText = data2.toString("utf8");
self.response = data2;
setState(self.DONE);
}
});
} else {
try {
this.response = fs.readFileSync(unescape(url2.pathname));
this.responseText = this.response.toString("utf8");
this.status = 200;
setState(self.DONE);
} catch (e) {
this.handleError(e, e.errno || -1);
}
}
return;
}
var port = url2.port || (ssl ? 443 : 80);
var uri = url2.pathname + (url2.search ? url2.search : "");
headers["Host"] = host;
if (!(ssl && port === 443 || port === 80)) {
headers["Host"] += ":" + url2.port;
}
if (settings.user) {
if (typeof settings.password == "undefined") {
settings.password = "";
}
var authBuf = new Buffer(settings.user + ":" + settings.password);
headers["Authorization"] = "Basic " + authBuf.toString("base64");
}
if (settings.method === "GET" || settings.method === "HEAD") {
data = null;
} else if (data) {
headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data);
if (!headers["Content-Type"]) {
headers["Content-Type"] = "text/plain;charset=UTF-8";
}
} else if (settings.method === "POST") {
headers["Content-Length"] = 0;
}
var agent = opts.agent || false;
var options = {
host,
port,
path: uri,
method: settings.method,
headers,
agent
};
if (ssl) {
options.pfx = opts.pfx;
options.key = opts.key;
options.passphrase = opts.passphrase;
options.cert = opts.cert;
options.ca = opts.ca;
options.ciphers = opts.ciphers;
options.rejectUnauthorized = opts.rejectUnauthorized === false ? false : true;
}
errorFlag = false;
if (settings.async) {
var doRequest = ssl ? https.request : http.request;
sendFlag = true;
self.dispatchEvent("readystatechange");
var responseHandler = function(resp2) {
response = resp2;
if (response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {
settings.url = response.headers.location;
var url3 = Url.parse(settings.url);
host = url3.hostname;
var newOptions = {
hostname: url3.hostname,
port: url3.port,
path: url3.path,
method: response.statusCode === 303 ? "GET" : settings.method,
headers
};
if (ssl) {
newOptions.pfx = opts.pfx;
newOptions.key = opts.key;
newOptions.passphrase = opts.passphrase;
newOptions.cert = opts.cert;
newOptions.ca = opts.ca;
newOptions.ciphers = opts.ciphers;
newOptions.rejectUnauthorized = opts.rejectUnauthorized === false ? false : true;
}
request = doRequest(newOptions, responseHandler).on("error", errorHandler);
request.end();
return;
}
setState(self.HEADERS_RECEIVED);
self.status = response.statusCode;
response.on("data", function(chunk) {
if (chunk) {
var data2 = Buffer.from(chunk);
self.response = Buffer.concat([self.response, data2]);
}
if (sendFlag) {
setState(self.LOADING);
}
});
response.on("end", function() {
if (sendFlag) {
sendFlag = false;
setState(self.DONE);
self.responseText = self.response.toString("utf8");
}
});
response.on("error", function(error) {
self.handleError(error);
});
};
var errorHandler = function(error) {
self.handleError(error);
};
request = doRequest(options, responseHandler).on("error", errorHandler);
if (opts.autoUnref) {
request.on("socket", (socket) => {
socket.unref();
});
}
if (data) {
request.write(data);
}
request.end();
self.dispatchEvent("loadstart");
} else {
var contentFile = ".node-xmlhttprequest-content-" + process.pid;
var syncFile = ".node-xmlhttprequest-sync-" + process.pid;
fs.writeFileSync(syncFile, "", "utf8");
var execString = "var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http" + (ssl ? "s" : "") + ".request;var options = " + JSON.stringify(options) + ";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('" + contentFile + "', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('" + syncFile + "');});response.on('error', function(error) {fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('" + syncFile + "');});}).on('error', function(error) {fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('" + syncFile + "');});" + (data ? "req.write('" + JSON.stringify(data).slice(1, -1).replace(/'/g, "\\'") + "');" : "") + "req.end();";
var syncProc = spawn(process.argv[0], ["-e", execString]);
var statusText;
while (fs.existsSync(syncFile)) {
}
self.responseText = fs.readFileSync(contentFile, "utf8");
syncProc.stdin.end();
fs.unlinkSync(contentFile);
if (self.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)) {
var errorObj = JSON.parse(self.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/, ""));
self.handleError(errorObj, 503);
} else {
self.status = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/, "$1");
var resp = JSON.parse(self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/, "$1"));
response = {
statusCode: self.status,
headers: resp.data.headers
};
self.responseText = resp.data.text;
self.response = Buffer.from(resp.data.data, "base64");
setState(self.DONE, true);
}
}
};
this.handleError = function(error, status) {
this.status = status || 0;
this.statusText = error;
this.responseText = error.stack;
errorFlag = true;
setState(this.DONE);
};
this.abort = function() {
if (request) {
request.abort();
request = null;
}
headers = Object.assign({}, defaultHeaders);
this.responseText = "";
this.responseXML = "";
this.response = Buffer.alloc(0);
errorFlag = abortedFlag = true;
if (this.readyState !== this.UNSENT && (this.readyState !== this.OPENED || sendFlag) && this.readyState !== this.DONE) {
sendFlag = false;
setState(this.DONE);
}
this.readyState = this.UNSENT;
};
this.addEventListener = function(event, callback) {
if (!(event in listeners)) {
listeners[event] = [];
}
listeners[event].push(callback);
};
this.removeEventListener = function(event, callback) {
if (event in listeners) {
listeners[event] = listeners[event].filter(function(ev) {
return ev !== callback;
});
}
};
this.dispatchEvent = function(event) {
if (typeof self["on" + event] === "function") {
if (this.readyState === this.DONE && settings.async)
setTimeout(function() {
self["on" + event]();
}, 0);
else
self["on" + event]();
}
if (event in listeners) {
for (let i = 0, len = listeners[event].length; i < len; i++) {
if (this.readyState === this.DONE)
setTimeout(function() {
listeners[event][i].call(self);
}, 0);
else
listeners[event][i].call(self);
}
}
};
var setState = function(state) {
if (self.readyState === state || self.readyState === self.UNSENT && abortedFlag)
return;
self.readyState = state;
if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) {
self.dispatchEvent("readystatechange");
}
if (self.readyState === self.DONE) {
let fire;
if (abortedFlag)
fire = "abort";
else if (errorFlag)
fire = "error";
else
fire = "load";
self.dispatchEvent(fire);
self.dispatchEvent("loadend");
}
};
}
}
});
// node_modules/@socket.io/component-emitter/lib/cjs/index.js
var require_cjs = __commonJS({
"node_modules/@socket.io/component-emitter/lib/cjs/index.js"(exports2) {
"use strict";
exports2.Emitter = Emitter7;
function Emitter7(obj) {
if (obj) return mixin(obj);
}
function mixin(obj) {
for (var key in Emitter7.prototype) {
obj[key] = Emitter7.prototype[key];
}
return obj;
}
Emitter7.prototype.on = Emitter7.prototype.addEventListener = function(event, fn) {
this._callbacks = this._callbacks || {};
(this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
return this;
};
Emitter7.prototype.once = function(event, fn) {
function on2() {
this.off(event, on2);
fn.apply(this, arguments);
}
on2.fn = fn;
this.on(event, on2);
return this;
};
Emitter7.prototype.off = Emitter7.prototype.removeListener = Emitter7.prototype.removeAllListeners = Emitter7.prototype.removeEventListener = function(event, fn) {
this._callbacks = this._callbacks || {};
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
var callbacks = this._callbacks["$" + event];
if (!callbacks) return this;
if (1 == arguments.length) {
delete this._callbacks["$" + event];
return this;
}
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
if (callbacks.length === 0) {
delete this._callbacks["$" + event];
}
return this;
};
Emitter7.prototype.emit = function(event) {
this._callbacks = this._callbacks || {};
var args = new Array(arguments.length - 1), callbacks = this._callbacks["$" + event];
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
Emitter7.prototype.emitReserved = Emitter7.prototype.emit;
Emitter7.prototype.listeners = function(event) {
this._callbacks = this._callbacks || {};
return this._callbacks["$" + event] || [];
};
Emitter7.prototype.hasListeners = function(event) {
return !!this.listeners(event).length;
};
}
});
// node_modules/ms/index.js
var require_ms = __commonJS({
"node_modules/ms/index.js"(exports2, module2) {
"use strict";
var s = 1e3;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
module2.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === "string" && val.length > 0) {
return parse5(val);
} else if (type === "number" && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
"val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
);
};
function parse5(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n * y;
case "weeks":
case "week":
case "w":
return n * w;
case "days":
case "day":
case "d":
return n * d;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n * h;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n * m;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n * s;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n;
default:
return void 0;
}
}
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + "d";
}
if (msAbs >= h) {
return Math.round(ms / h) + "h";
}
if (msAbs >= m) {
return Math.round(ms / m) + "m";
}
if (msAbs >= s) {
return Math.round(ms / s) + "s";
}
return ms + "ms";
}
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, "day");
}
if (msAbs >= h) {
return plural(ms, msAbs, h, "hour");
}
if (msAbs >= m) {
return plural(ms, msAbs, m, "minute");
}
if (msAbs >= s) {
return plural(ms, msAbs, s, "second");
}
return ms + " ms";
}
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
}
}
});
// node_modules/debug/src/common.js
var require_common = __commonJS({
"node_modules/debug/src/common.js"(exports2, module2) {
"use strict";
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require_ms();
createDebug.destroy = destroy;
Object.keys(env).forEach((key) => {
createDebug[key] = env[key];
});
createDebug.names = [];
createDebug.skips = [];
createDebug.formatters = {};
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0;
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug12(...args) {
if (!debug12.enabled) {
return;
}
const self = debug12;
const curr = Number(/* @__PURE__ */ new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== "string") {
args.unshift("%O");
}
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
if (match === "%%") {
return "%";
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === "function") {
const val = args[index];
match = formatter.call(self, val);
args.splice(index, 1);
index--;
}
return match;
});
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug12.namespace = namespace;
debug12.useColors = createDebug.useColors();
debug12.color = createDebug.selectColor(namespace);
debug12.extend = extend;
debug12.destroy = createDebug.destroy;
Object.defineProperty(debug12, "enabled", {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: (v) => {
enableOverride = v;
}
});
if (typeof createDebug.init === "function") {
createDebug.init(debug12);
}
return debug12;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
let i;
const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
continue;
}
namespaces = split[i].replace(/\*/g, ".*?");
if (namespaces[0] === "-") {
createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
} else {
createDebug.names.push(new RegExp("^" + namespaces + "$"));
}
}
}
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
].join(",");
createDebug.enable("");
return namespaces;
}
function enabled(name) {
if (name[name.length - 1] === "*") {
return true;
}
let i;
let len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
function toNamespace(regexp) {
return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
}
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
function destroy() {
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
createDebug.enable(createDebug.load());
return createDebug;
}
module2.exports = setup;
}
});
// node_modules/debug/src/browser.js
var require_browser = __commonJS({
"node_modules/debug/src/browser.js"(exports2, module2) {
"use strict";
exports2.formatArgs = formatArgs;
exports2.save = save;
exports2.load = load;
exports2.useColors = useColors;
exports2.storage = localstorage();
exports2.destroy = /* @__PURE__ */ (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
};
})();
exports2.colors = [
"#0000CC",
"#0000FF",
"#0033CC",
"#0033FF",
"#0066CC",
"#0066FF",
"#0099CC",
"#0099FF",
"#00CC00",
"#00CC33",
"#00CC66",
"#00CC99",
"#00CCCC",
"#00CCFF",
"#3300CC",
"#3300FF",
"#3333CC",
"#3333FF",
"#3366CC",
"#3366FF",
"#3399CC",
"#3399FF",
"#33CC00",
"#33CC33",
"#33CC66",
"#33CC99",
"#33CCCC",
"#33CCFF",
"#6600CC",
"#6600FF",
"#6633CC",
"#6633FF",
"#66CC00",
"#66CC33",
"#9900CC",
"#9900FF",
"#9933CC",
"#9933FF",
"#99CC00",
"#99CC33",
"#CC0000",
"#CC0033",
"#CC0066",
"#CC0099",
"#CC00CC",
"#CC00FF",
"#CC3300",
"#CC3333",
"#CC3366",
"#CC3399",
"#CC33CC",
"#CC33FF",
"#CC6600",
"#CC6633",
"#CC9900",
"#CC9933",
"#CCCC00",
"#CCCC33",
"#FF0000",
"#FF0033",
"#FF0066",
"#FF0099",
"#FF00CC",
"#FF00FF",
"#FF3300",
"#FF3333",
"#FF3366",
"#FF3399",
"#FF33CC",
"#FF33FF",
"#FF6600",
"#FF6633",
"#FF9900",
"#FF9933",
"#FFCC00",
"#FFCC33"
];
function useColors() {
if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
return true;
}
if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
let m;
return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
function formatArgs(args) {
args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = "color: " + this.color;
args.splice(1, 0, c, "color: inherit");
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, (match) => {
if (match === "%%") {
return;
}
index++;
if (match === "%c") {
lastC = index;
}
});
args.splice(lastC, 0, c);
}
exports2.log = console.debug || console.log || (() => {
});
function save(namespaces) {
try {
if (namespaces) {
exports2.storage.setItem("debug", namespaces);
} else {
exports2.storage.removeItem("debug");
}
} catch (error) {
}
}
function load() {
let r;
try {
r = exports2.storage.getItem("debug");
} catch (error) {
}
if (!r && typeof process !== "undefined" && "env" in process) {
r = process.env.DEBUG;
}
return r;
}
function localstorage() {
try {
return localStorage;
} catch (error) {
}
}
module2.exports = require_common()(exports2);
var { formatters } = module2.exports;
formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (error) {
return "[UnexpectedJSONParseError]: " + error.message;
}
};
}
});
// node_modules/has-flag/index.js
var require_has_flag = __commonJS({
"node_modules/has-flag/index.js"(exports2, module2) {
"use strict";
module2.exports = (flag, argv = process.argv) => {
const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf("--");
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
};
}
});
// node_modules/supports-color/index.js
var require_supports_color = __commonJS({
"node_modules/supports-color/index.js"(exports2, module2) {
"use strict";
var os = require("os");
var tty = require("tty");
var hasFlag = require_has_flag();
var { env } = process;
var forceColor;
if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
forceColor = 0;
} else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
forceColor = 1;
}
if ("FORCE_COLOR" in env) {
if (env.FORCE_COLOR === "true") {
forceColor = 1;
} else if (env.FORCE_COLOR === "false") {
forceColor = 0;
} else {
forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
}
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function supportsColor(haveStream, streamIsTTY) {
if (forceColor === 0) {
return 0;
}
if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
return 3;
}
if (hasFlag("color=256")) {
return 2;
}
if (haveStream && !streamIsTTY && forceColor === void 0) {
return 0;
}
const min = forceColor || 0;
if (env.TERM === "dumb") {
return min;
}
if (process.platform === "win32") {
const osRelease = os.release().split(".");
if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ("CI" in env) {
if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
return 1;
}
return min;
}
if ("TEAMCITY_VERSION" in env) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}
if (env.COLORTERM === "truecolor") {
return 3;
}
if ("TERM_PROGRAM" in env) {
const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
switch (env.TERM_PROGRAM) {
case "iTerm.app":
return version >= 3 ? 3 : 2;
case "Apple_Terminal":
return 2;
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ("COLORTERM" in env) {
return 1;
}
return min;
}
function getSupportLevel(stream) {
const level = supportsColor(stream, stream && stream.isTTY);
return translateLevel(level);
}
module2.exports = {
supportsColor: getSupportLevel,
stdout: translateLevel(supportsColor(true, tty.isatty(1))),
stderr: translateLevel(supportsColor(true, tty.isatty(2)))
};
}
});
// node_modules/debug/src/node.js
var require_node = __commonJS({
"node_modules/debug/src/node.js"(exports2, module2) {
"use strict";
var tty = require("tty");
var util = require("util");
exports2.init = init;
exports2.log = log;
exports2.formatArgs = formatArgs;
exports2.save = save;
exports2.load = load;
exports2.useColors = useColors;
exports2.destroy = util.deprecate(
() => {
},
"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
);
exports2.colors = [6, 2, 3, 4, 5, 1];
try {
const supportsColor = require_supports_color();
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports2.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {
}
exports2.inspectOpts = Object.keys(process.env).filter((key) => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === "null") {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
function useColors() {
return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd);
}
function formatArgs(args) {
const { namespace: name, useColors: useColors2 } = this;
if (useColors2) {
const c = this.color;
const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
const prefix = ` ${colorCode};1m${name} \x1B[0m`;
args[0] = prefix + args[0].split("\n").join("\n" + prefix);
args.push(colorCode + "m+" + module2.exports.humanize(this.diff) + "\x1B[0m");
} else {
args[0] = getDate() + name + " " + args[0];
}
}
function getDate() {
if (exports2.inspectOpts.hideDate) {
return "";
}
return (/* @__PURE__ */ new Date()).toISOString() + " ";
}
function log(...args) {
return process.stderr.write(util.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
}
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
delete process.env.DEBUG;
}
}
function load() {
return process.env.DEBUG;
}
function init(debug12) {
debug12.inspectOpts = {};
const keys = Object.keys(exports2.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug12.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
}
}
module2.exports = require_common()(exports2);
var { formatters } = module2.exports;
formatters.o = function(v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
};
formatters.O = function(v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};
}
});
// node_modules/debug/src/index.js
var require_src = __commonJS({
"node_modules/debug/src/index.js"(exports2, module2) {
"use strict";
if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
module2.exports = require_browser();
} else {
module2.exports = require_node();
}
}
});
// node_modules/engine.io-client/node_modules/ws/lib/stream.js
var require_stream = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/stream.js"(exports2, module2) {
"use strict";
var { Duplex } = require("stream");
function emitClose(stream) {
stream.emit("close");
}
function duplexOnEnd() {
if (!this.destroyed && this._writableState.finished) {
this.destroy();
}
}
function duplexOnError(err) {
this.removeListener("error", duplexOnError);
this.destroy();
if (this.listenerCount("error") === 0) {
this.emit("error", err);
}
}
function createWebSocketStream2(ws, options) {
let terminateOnDestroy = true;
const duplex = new Duplex({
...options,
autoDestroy: false,
emitClose: false,
objectMode: false,
writableObjectMode: false
});
ws.on("message", function message(msg, isBinary2) {
const data = !isBinary2 && duplex._readableState.objectMode ? msg.toString() : msg;
if (!duplex.push(data)) ws.pause();
});
ws.once("error", function error(err) {
if (duplex.destroyed) return;
terminateOnDestroy = false;
duplex.destroy(err);
});
ws.once("close", function close() {
if (duplex.destroyed) return;
duplex.push(null);
});
duplex._destroy = function(err, callback) {
if (ws.readyState === ws.CLOSED) {
callback(err);
process.nextTick(emitClose, duplex);
return;
}
let called = false;
ws.once("error", function error(err2) {
called = true;
callback(err2);
});
ws.once("close", function close() {
if (!called) callback(err);
process.nextTick(emitClose, duplex);
});
if (terminateOnDestroy) ws.terminate();
};
duplex._final = function(callback) {
if (ws.readyState === ws.CONNECTING) {
ws.once("open", function open() {
duplex._final(callback);
});
return;
}
if (ws._socket === null) return;
if (ws._socket._writableState.finished) {
callback();
if (duplex._readableState.endEmitted) duplex.destroy();
} else {
ws._socket.once("finish", function finish() {
callback();
});
ws.close();
}
};
duplex._read = function() {
if (ws.isPaused) ws.resume();
};
duplex._write = function(chunk, encoding, callback) {
if (ws.readyState === ws.CONNECTING) {
ws.once("open", function open() {
duplex._write(chunk, encoding, callback);
});
return;
}
ws.send(chunk, callback);
};
duplex.on("end", duplexOnEnd);
duplex.on("error", duplexOnError);
return duplex;
}
module2.exports = createWebSocketStream2;
}
});
// node_modules/engine.io-client/node_modules/ws/lib/constants.js
var require_constants = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/constants.js"(exports2, module2) {
"use strict";
module2.exports = {
BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
EMPTY_BUFFER: Buffer.alloc(0),
GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
kListener: Symbol("kListener"),
kStatusCode: Symbol("status-code"),
kWebSocket: Symbol("websocket"),
NOOP: () => {
}
};
}
});
// node_modules/engine.io-client/node_modules/ws/lib/buffer-util.js
var require_buffer_util = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/buffer-util.js"(exports2, module2) {
"use strict";
var { EMPTY_BUFFER } = require_constants();
var FastBuffer = Buffer[Symbol.species];
function concat(list, totalLength2) {
if (list.length === 0) return EMPTY_BUFFER;
if (list.length === 1) return list[0];
const target = Buffer.allocUnsafe(totalLength2);
let offset = 0;
for (let i = 0; i < list.length; i++) {
const buf = list[i];
target.set(buf, offset);
offset += buf.length;
}
if (offset < totalLength2) {
return new FastBuffer(target.buffer, target.byteOffset, offset);
}
return target;
}
function _mask(source, mask, output, offset, length) {
for (let i = 0; i < length; i++) {
output[offset + i] = source[i] ^ mask[i & 3];
}
}
function _unmask(buffer, mask) {
for (let i = 0; i < buffer.length; i++) {
buffer[i] ^= mask[i & 3];
}
}
function toArrayBuffer(buf) {
if (buf.length === buf.buffer.byteLength) {
return buf.buffer;
}
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
}
function toBuffer2(data) {
toBuffer2.readOnly = true;
if (Buffer.isBuffer(data)) return data;
let buf;
if (data instanceof ArrayBuffer) {
buf = new FastBuffer(data);
} else if (ArrayBuffer.isView(data)) {
buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
} else {
buf = Buffer.from(data);
toBuffer2.readOnly = false;
}
return buf;
}
module2.exports = {
concat,
mask: _mask,
toArrayBuffer,
toBuffer: toBuffer2,
unmask: _unmask
};
if (!process.env.WS_NO_BUFFER_UTIL) {
try {
const bufferUtil = require("bufferutil");
module2.exports.mask = function(source, mask, output, offset, length) {
if (length < 48) _mask(source, mask, output, offset, length);
else bufferUtil.mask(source, mask, output, offset, length);
};
module2.exports.unmask = function(buffer, mask) {
if (buffer.length < 32) _unmask(buffer, mask);
else bufferUtil.unmask(buffer, mask);
};
} catch (e) {
}
}
}
});
// node_modules/engine.io-client/node_modules/ws/lib/limiter.js
var require_limiter = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/limiter.js"(exports2, module2) {
"use strict";
var kDone = Symbol("kDone");
var kRun = Symbol("kRun");
var Limiter = class {
/**
* Creates a new `Limiter`.
*
* @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
* to run concurrently
*/
constructor(concurrency) {
this[kDone] = () => {
this.pending--;
this[kRun]();
};
this.concurrency = concurrency || Infinity;
this.jobs = [];
this.pending = 0;
}
/**
* Adds a job to the queue.
*
* @param {Function} job The job to run
* @public
*/
add(job) {
this.jobs.push(job);
this[kRun]();
}
/**
* Removes a job from the queue and runs it if possible.
*
* @private
*/
[kRun]() {
if (this.pending === this.concurrency) return;
if (this.jobs.length) {
const job = this.jobs.shift();
this.pending++;
job(this[kDone]);
}
}
};
module2.exports = Limiter;
}
});
// node_modules/engine.io-client/node_modules/ws/lib/permessage-deflate.js
var require_permessage_deflate = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
"use strict";
var zlib = require("zlib");
var bufferUtil = require_buffer_util();
var Limiter = require_limiter();
var { kStatusCode } = require_constants();
var FastBuffer = Buffer[Symbol.species];
var TRAILER = Buffer.from([0, 0, 255, 255]);
var kPerMessageDeflate = Symbol("permessage-deflate");
var kTotalLength = Symbol("total-length");
var kCallback = Symbol("callback");
var kBuffers = Symbol("buffers");
var kError = Symbol("error");
var zlibLimiter;
var PerMessageDeflate = class {
/**
* Creates a PerMessageDeflate instance.
*
* @param {Object} [options] Configuration options
* @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
* for, or request, a custom client window size
* @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
* acknowledge disabling of client context takeover
* @param {Number} [options.concurrencyLimit=10] The number of concurrent
* calls to zlib
* @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
* use of a custom server window size
* @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
* disabling of server context takeover
* @param {Number} [options.threshold=1024] Size (in bytes) below which
* messages should not be compressed if context takeover is disabled
* @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
* deflate
* @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
* inflate
* @param {Boolean} [isServer=false] Create the instance in either server or
* client mode
* @param {Number} [maxPayload=0] The maximum allowed message length
*/
constructor(options, isServer, maxPayload) {
this._maxPayload = maxPayload | 0;
this._options = options || {};
this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
this._isServer = !!isServer;
this._deflate = null;
this._inflate = null;
this.params = null;
if (!zlibLimiter) {
const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
zlibLimiter = new Limiter(concurrency);
}
}
/**
* @type {String}
*/
static get extensionName() {
return "permessage-deflate";
}
/**
* Create an extension negotiation offer.
*
* @return {Object} Extension parameters
* @public
*/
offer() {
const params = {};
if (this._options.serverNoContextTakeover) {
params.server_no_context_takeover = true;
}
if (this._options.clientNoContextTakeover) {
params.client_no_context_takeover = true;
}
if (this._options.serverMaxWindowBits) {
params.server_max_window_bits = this._options.serverMaxWindowBits;
}
if (this._options.clientMaxWindowBits) {
params.client_max_window_bits = this._options.clientMaxWindowBits;
} else if (this._options.clientMaxWindowBits == null) {
params.client_max_window_bits = true;
}
return params;
}
/**
* Accept an extension negotiation offer/response.
*
* @param {Array} configurations The extension negotiation offers/reponse
* @return {Object} Accepted configuration
* @public
*/
accept(configurations) {
configurations = this.normalizeParams(configurations);
this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
return this.params;
}
/**
* Releases all resources used by the extension.
*
* @public
*/
cleanup() {
if (this._inflate) {
this._inflate.close();
this._inflate = null;
}
if (this._deflate) {
const callback = this._deflate[kCallback];
this._deflate.close();
this._deflate = null;
if (callback) {
callback(
new Error(
"The deflate stream was closed while data was being processed"
)
);
}
}
}
/**
* Accept an extension negotiation offer.
*
* @param {Array} offers The extension negotiation offers
* @return {Object} Accepted configuration
* @private
*/
acceptAsServer(offers) {
const opts = this._options;
const accepted = offers.find((params) => {
if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
return false;
}
return true;
});
if (!accepted) {
throw new Error("None of the extension offers can be accepted");
}
if (opts.serverNoContextTakeover) {
accepted.server_no_context_takeover = true;
}
if (opts.clientNoContextTakeover) {
accepted.client_no_context_takeover = true;
}
if (typeof opts.serverMaxWindowBits === "number") {
accepted.server_max_window_bits = opts.serverMaxWindowBits;
}
if (typeof opts.clientMaxWindowBits === "number") {
accepted.client_max_window_bits = opts.clientMaxWindowBits;
} else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
delete accepted.client_max_window_bits;
}
return accepted;
}
/**
* Accept the extension negotiation response.
*
* @param {Array} response The extension negotiation response
* @return {Object} Accepted configuration
* @private
*/
acceptAsClient(response) {
const params = response[0];
if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
throw new Error('Unexpected parameter "client_no_context_takeover"');
}
if (!params.client_max_window_bits) {
if (typeof this._options.clientMaxWindowBits === "number") {
params.client_max_window_bits = this._options.clientMaxWindowBits;
}
} else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
throw new Error(
'Unexpected or invalid parameter "client_max_window_bits"'
);
}
return params;
}
/**
* Normalize parameters.
*
* @param {Array} configurations The extension negotiation offers/reponse
* @return {Array} The offers/response with normalized parameters
* @private
*/
normalizeParams(configurations) {
configurations.forEach((params) => {
Object.keys(params).forEach((key) => {
let value2 = params[key];
if (value2.length > 1) {
throw new Error(`Parameter "${key}" must have only a single value`);
}
value2 = value2[0];
if (key === "client_max_window_bits") {
if (value2 !== true) {
const num = +value2;
if (!Number.isInteger(num) || num < 8 || num > 15) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value2}`
);
}
value2 = num;
} else if (!this._isServer) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value2}`
);
}
} else if (key === "server_max_window_bits") {
const num = +value2;
if (!Number.isInteger(num) || num < 8 || num > 15) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value2}`
);
}
value2 = num;
} else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
if (value2 !== true) {
throw new TypeError(
`Invalid value for parameter "${key}": ${value2}`
);
}
} else {
throw new Error(`Unknown parameter "${key}"`);
}
params[key] = value2;
});
});
return configurations;
}
/**
* Decompress data. Concurrency limited.
*
* @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @public
*/
decompress(data, fin, callback) {
zlibLimiter.add((done) => {
this._decompress(data, fin, (err, result) => {
done();
callback(err, result);
});
});
}
/**
* Compress data. Concurrency limited.
*
* @param {(Buffer|String)} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @public
*/
compress(data, fin, callback) {
zlibLimiter.add((done) => {
this._compress(data, fin, (err, result) => {
done();
callback(err, result);
});
});
}
/**
* Decompress data.
*
* @param {Buffer} data Compressed data
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @private
*/
_decompress(data, fin, callback) {
const endpoint = this._isServer ? "client" : "server";
if (!this._inflate) {
const key = `${endpoint}_max_window_bits`;
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
this._inflate = zlib.createInflateRaw({
...this._options.zlibInflateOptions,
windowBits
});
this._inflate[kPerMessageDeflate] = this;
this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = [];
this._inflate.on("error", inflateOnError);
this._inflate.on("data", inflateOnData);
}
this._inflate[kCallback] = callback;
this._inflate.write(data);
if (fin) this._inflate.write(TRAILER);
this._inflate.flush(() => {
const err = this._inflate[kError];
if (err) {
this._inflate.close();
this._inflate = null;
callback(err);
return;
}
const data2 = bufferUtil.concat(
this._inflate[kBuffers],
this._inflate[kTotalLength]
);
if (this._inflate._readableState.endEmitted) {
this._inflate.close();
this._inflate = null;
} else {
this._inflate[kTotalLength] = 0;
this._inflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._inflate.reset();
}
}
callback(null, data2);
});
}
/**
* Compress data.
*
* @param {(Buffer|String)} data Data to compress
* @param {Boolean} fin Specifies whether or not this is the last fragment
* @param {Function} callback Callback
* @private
*/
_compress(data, fin, callback) {
const endpoint = this._isServer ? "server" : "client";
if (!this._deflate) {
const key = `${endpoint}_max_window_bits`;
const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
this._deflate = zlib.createDeflateRaw({
...this._options.zlibDeflateOptions,
windowBits
});
this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = [];
this._deflate.on("data", deflateOnData);
}
this._deflate[kCallback] = callback;
this._deflate.write(data);
this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
if (!this._deflate) {
return;
}
let data2 = bufferUtil.concat(
this._deflate[kBuffers],
this._deflate[kTotalLength]
);
if (fin) {
data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
}
this._deflate[kCallback] = null;
this._deflate[kTotalLength] = 0;
this._deflate[kBuffers] = [];
if (fin && this.params[`${endpoint}_no_context_takeover`]) {
this._deflate.reset();
}
callback(null, data2);
});
}
};
module2.exports = PerMessageDeflate;
function deflateOnData(chunk) {
this[kBuffers].push(chunk);
this[kTotalLength] += chunk.length;
}
function inflateOnData(chunk) {
this[kTotalLength] += chunk.length;
if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
this[kBuffers].push(chunk);
return;
}
this[kError] = new RangeError("Max payload size exceeded");
this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
this[kError][kStatusCode] = 1009;
this.removeListener("data", inflateOnData);
this.reset();
}
function inflateOnError(err) {
this[kPerMessageDeflate]._inflate = null;
err[kStatusCode] = 1007;
this[kCallback](err);
}
}
});
// node_modules/engine.io-client/node_modules/ws/lib/validation.js
var require_validation = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/validation.js"(exports2, module2) {
"use strict";
var { isUtf8 } = require("buffer");
var tokenChars = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
// 0 - 15
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
// 16 - 31
0,
1,
0,
1,
1,
1,
1,
1,
0,
0,
1,
1,
0,
1,
1,
0,
// 32 - 47
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
// 48 - 63
0,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
// 64 - 79
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
1,
1,
// 80 - 95
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
// 96 - 111
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
1,
0,
1,
0
// 112 - 127
];
function isValidStatusCode(code) {
return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
}
function _isValidUTF8(buf) {
const len = buf.length;
let i = 0;
while (i < len) {
if ((buf[i] & 128) === 0) {
i++;
} else if ((buf[i] & 224) === 192) {
if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
return false;
}
i += 2;
} else if ((buf[i] & 240) === 224) {
if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
buf[i] === 237 && (buf[i + 1] & 224) === 160) {
return false;
}
i += 3;
} else if ((buf[i] & 248) === 240) {
if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
return false;
}
i += 4;
} else {
return false;
}
}
return true;
}
module2.exports = {
isValidStatusCode,
isValidUTF8: _isValidUTF8,
tokenChars
};
if (isUtf8) {
module2.exports.isValidUTF8 = function(buf) {
return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
};
} else if (!process.env.WS_NO_UTF_8_VALIDATE) {
try {
const isValidUTF8 = require("utf-8-validate");
module2.exports.isValidUTF8 = function(buf) {
return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
};
} catch (e) {
}
}
}
});
// node_modules/engine.io-client/node_modules/ws/lib/receiver.js
var require_receiver = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/receiver.js"(exports2, module2) {
"use strict";
var { Writable } = require("stream");
var PerMessageDeflate = require_permessage_deflate();
var {
BINARY_TYPES,
EMPTY_BUFFER,
kStatusCode,
kWebSocket
} = require_constants();
var { concat, toArrayBuffer, unmask } = require_buffer_util();
var { isValidStatusCode, isValidUTF8 } = require_validation();
var FastBuffer = Buffer[Symbol.species];
var GET_INFO = 0;
var GET_PAYLOAD_LENGTH_16 = 1;
var GET_PAYLOAD_LENGTH_64 = 2;
var GET_MASK = 3;
var GET_DATA = 4;
var INFLATING = 5;
var DEFER_EVENT = 6;
var Receiver2 = class extends Writable {
/**
* Creates a Receiver instance.
*
* @param {Object} [options] Options object
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {String} [options.binaryType=nodebuffer] The type for binary data
* @param {Object} [options.extensions] An object containing the negotiated
* extensions
* @param {Boolean} [options.isServer=false] Specifies whether to operate in
* client or server mode
* @param {Number} [options.maxPayload=0] The maximum allowed message length
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
*/
constructor(options = {}) {
super();
this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
this._binaryType = options.binaryType || BINARY_TYPES[0];
this._extensions = options.extensions || {};
this._isServer = !!options.isServer;
this._maxPayload = options.maxPayload | 0;
this._skipUTF8Validation = !!options.skipUTF8Validation;
this[kWebSocket] = void 0;
this._bufferedBytes = 0;
this._buffers = [];
this._compressed = false;
this._payloadLength = 0;
this._mask = void 0;
this._fragmented = 0;
this._masked = false;
this._fin = false;
this._opcode = 0;
this._totalPayloadLength = 0;
this._messageLength = 0;
this._fragments = [];
this._errored = false;
this._loop = false;
this._state = GET_INFO;
}
/**
* Implements `Writable.prototype._write()`.
*
* @param {Buffer} chunk The chunk of data to write
* @param {String} encoding The character encoding of `chunk`
* @param {Function} cb Callback
* @private
*/
_write(chunk, encoding, cb) {
if (this._opcode === 8 && this._state == GET_INFO) return cb();
this._bufferedBytes += chunk.length;
this._buffers.push(chunk);
this.startLoop(cb);
}
/**
* Consumes `n` bytes from the buffered data.
*
* @param {Number} n The number of bytes to consume
* @return {Buffer} The consumed bytes
* @private
*/
consume(n) {
this._bufferedBytes -= n;
if (n === this._buffers[0].length) return this._buffers.shift();
if (n < this._buffers[0].length) {
const buf = this._buffers[0];
this._buffers[0] = new FastBuffer(
buf.buffer,
buf.byteOffset + n,
buf.length - n
);
return new FastBuffer(buf.buffer, buf.byteOffset, n);
}
const dst = Buffer.allocUnsafe(n);
do {
const buf = this._buffers[0];
const offset = dst.length - n;
if (n >= buf.length) {
dst.set(this._buffers.shift(), offset);
} else {
dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
this._buffers[0] = new FastBuffer(
buf.buffer,
buf.byteOffset + n,
buf.length - n
);
}
n -= buf.length;
} while (n > 0);
return dst;
}
/**
* Starts the parsing loop.
*
* @param {Function} cb Callback
* @private
*/
startLoop(cb) {
this._loop = true;
do {
switch (this._state) {
case GET_INFO:
this.getInfo(cb);
break;
case GET_PAYLOAD_LENGTH_16:
this.getPayloadLength16(cb);
break;
case GET_PAYLOAD_LENGTH_64:
this.getPayloadLength64(cb);
break;
case GET_MASK:
this.getMask();
break;
case GET_DATA:
this.getData(cb);
break;
case INFLATING:
case DEFER_EVENT:
this._loop = false;
return;
}
} while (this._loop);
if (!this._errored) cb();
}
/**
* Reads the first two bytes of a frame.
*
* @param {Function} cb Callback
* @private
*/
getInfo(cb) {
if (this._bufferedBytes < 2) {
this._loop = false;
return;
}
const buf = this.consume(2);
if ((buf[0] & 48) !== 0) {
const error = this.createError(
RangeError,
"RSV2 and RSV3 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_2_3"
);
cb(error);
return;
}
const compressed = (buf[0] & 64) === 64;
if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
const error = this.createError(
RangeError,
"RSV1 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_1"
);
cb(error);
return;
}
this._fin = (buf[0] & 128) === 128;
this._opcode = buf[0] & 15;
this._payloadLength = buf[1] & 127;
if (this._opcode === 0) {
if (compressed) {
const error = this.createError(
RangeError,
"RSV1 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_1"
);
cb(error);
return;
}
if (!this._fragmented) {
const error = this.createError(
RangeError,
"invalid opcode 0",
true,
1002,
"WS_ERR_INVALID_OPCODE"
);
cb(error);
return;
}
this._opcode = this._fragmented;
} else if (this._opcode === 1 || this._opcode === 2) {
if (this._fragmented) {
const error = this.createError(
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
"WS_ERR_INVALID_OPCODE"
);
cb(error);
return;
}
this._compressed = compressed;
} else if (this._opcode > 7 && this._opcode < 11) {
if (!this._fin) {
const error = this.createError(
RangeError,
"FIN must be set",
true,
1002,
"WS_ERR_EXPECTED_FIN"
);
cb(error);
return;
}
if (compressed) {
const error = this.createError(
RangeError,
"RSV1 must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_RSV_1"
);
cb(error);
return;
}
if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
const error = this.createError(
RangeError,
`invalid payload length ${this._payloadLength}`,
true,
1002,
"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
);
cb(error);
return;
}
} else {
const error = this.createError(
RangeError,
`invalid opcode ${this._opcode}`,
true,
1002,
"WS_ERR_INVALID_OPCODE"
);
cb(error);
return;
}
if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
this._masked = (buf[1] & 128) === 128;
if (this._isServer) {
if (!this._masked) {
const error = this.createError(
RangeError,
"MASK must be set",
true,
1002,
"WS_ERR_EXPECTED_MASK"
);
cb(error);
return;
}
} else if (this._masked) {
const error = this.createError(
RangeError,
"MASK must be clear",
true,
1002,
"WS_ERR_UNEXPECTED_MASK"
);
cb(error);
return;
}
if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
else this.haveLength(cb);
}
/**
* Gets extended payload length (7+16).
*
* @param {Function} cb Callback
* @private
*/
getPayloadLength16(cb) {
if (this._bufferedBytes < 2) {
this._loop = false;
return;
}
this._payloadLength = this.consume(2).readUInt16BE(0);
this.haveLength(cb);
}
/**
* Gets extended payload length (7+64).
*
* @param {Function} cb Callback
* @private
*/
getPayloadLength64(cb) {
if (this._bufferedBytes < 8) {
this._loop = false;
return;
}
const buf = this.consume(8);
const num = buf.readUInt32BE(0);
if (num > Math.pow(2, 53 - 32) - 1) {
const error = this.createError(
RangeError,
"Unsupported WebSocket frame: payload length > 2^53 - 1",
false,
1009,
"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
);
cb(error);
return;
}
this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
this.haveLength(cb);
}
/**
* Payload length has been read.
*
* @param {Function} cb Callback
* @private
*/
haveLength(cb) {
if (this._payloadLength && this._opcode < 8) {
this._totalPayloadLength += this._payloadLength;
if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
const error = this.createError(
RangeError,
"Max payload size exceeded",
false,
1009,
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
);
cb(error);
return;
}
}
if (this._masked) this._state = GET_MASK;
else this._state = GET_DATA;
}
/**
* Reads mask bytes.
*
* @private
*/
getMask() {
if (this._bufferedBytes < 4) {
this._loop = false;
return;
}
this._mask = this.consume(4);
this._state = GET_DATA;
}
/**
* Reads data bytes.
*
* @param {Function} cb Callback
* @private
*/
getData(cb) {
let data = EMPTY_BUFFER;
if (this._payloadLength) {
if (this._bufferedBytes < this._payloadLength) {
this._loop = false;
return;
}
data = this.consume(this._payloadLength);
if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
unmask(data, this._mask);
}
}
if (this._opcode > 7) {
this.controlMessage(data, cb);
return;
}
if (this._compressed) {
this._state = INFLATING;
this.decompress(data, cb);
return;
}
if (data.length) {
this._messageLength = this._totalPayloadLength;
this._fragments.push(data);
}
this.dataMessage(cb);
}
/**
* Decompresses data.
*
* @param {Buffer} data Compressed data
* @param {Function} cb Callback
* @private
*/
decompress(data, cb) {
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
perMessageDeflate.decompress(data, this._fin, (err, buf) => {
if (err) return cb(err);
if (buf.length) {
this._messageLength += buf.length;
if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
const error = this.createError(
RangeError,
"Max payload size exceeded",
false,
1009,
"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
);
cb(error);
return;
}
this._fragments.push(buf);
}
this.dataMessage(cb);
if (this._state === GET_INFO) this.startLoop(cb);
});
}
/**
* Handles a data message.
*
* @param {Function} cb Callback
* @private
*/
dataMessage(cb) {
if (!this._fin) {
this._state = GET_INFO;
return;
}
const messageLength = this._messageLength;
const fragments = this._fragments;
this._totalPayloadLength = 0;
this._messageLength = 0;
this._fragmented = 0;
this._fragments = [];
if (this._opcode === 2) {
let data;
if (this._binaryType === "nodebuffer") {
data = concat(fragments, messageLength);
} else if (this._binaryType === "arraybuffer") {
data = toArrayBuffer(concat(fragments, messageLength));
} else {
data = fragments;
}
if (this._allowSynchronousEvents) {
this.emit("message", data, true);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit("message", data, true);
this._state = GET_INFO;
this.startLoop(cb);
});
}
} else {
const buf = concat(fragments, messageLength);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
const error = this.createError(
Error,
"invalid UTF-8 sequence",
true,
1007,
"WS_ERR_INVALID_UTF8"
);
cb(error);
return;
}
if (this._state === INFLATING || this._allowSynchronousEvents) {
this.emit("message", buf, false);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit("message", buf, false);
this._state = GET_INFO;
this.startLoop(cb);
});
}
}
}
/**
* Handles a control message.
*
* @param {Buffer} data Data to handle
* @return {(Error|RangeError|undefined)} A possible error
* @private
*/
controlMessage(data, cb) {
if (this._opcode === 8) {
if (data.length === 0) {
this._loop = false;
this.emit("conclude", 1005, EMPTY_BUFFER);
this.end();
} else {
const code = data.readUInt16BE(0);
if (!isValidStatusCode(code)) {
const error = this.createError(
RangeError,
`invalid status code ${code}`,
true,
1002,
"WS_ERR_INVALID_CLOSE_CODE"
);
cb(error);
return;
}
const buf = new FastBuffer(
data.buffer,
data.byteOffset + 2,
data.length - 2
);
if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
const error = this.createError(
Error,
"invalid UTF-8 sequence",
true,
1007,
"WS_ERR_INVALID_UTF8"
);
cb(error);
return;
}
this._loop = false;
this.emit("conclude", code, buf);
this.end();
}
this._state = GET_INFO;
return;
}
if (this._allowSynchronousEvents) {
this.emit(this._opcode === 9 ? "ping" : "pong", data);
this._state = GET_INFO;
} else {
this._state = DEFER_EVENT;
setImmediate(() => {
this.emit(this._opcode === 9 ? "ping" : "pong", data);
this._state = GET_INFO;
this.startLoop(cb);
});
}
}
/**
* Builds an error object.
*
* @param {function(new:Error|RangeError)} ErrorCtor The error constructor
* @param {String} message The error message
* @param {Boolean} prefix Specifies whether or not to add a default prefix to
* `message`
* @param {Number} statusCode The status code
* @param {String} errorCode The exposed error code
* @return {(Error|RangeError)} The error
* @private
*/
createError(ErrorCtor, message, prefix, statusCode, errorCode) {
this._loop = false;
this._errored = true;
const err = new ErrorCtor(
prefix ? `Invalid WebSocket frame: ${message}` : message
);
Error.captureStackTrace(err, this.createError);
err.code = errorCode;
err[kStatusCode] = statusCode;
return err;
}
};
module2.exports = Receiver2;
}
});
// node_modules/engine.io-client/node_modules/ws/lib/sender.js
var require_sender = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/sender.js"(exports2, module2) {
"use strict";
var { Duplex } = require("stream");
var { randomFillSync } = require("crypto");
var PerMessageDeflate = require_permessage_deflate();
var { EMPTY_BUFFER } = require_constants();
var { isValidStatusCode } = require_validation();
var { mask: applyMask, toBuffer: toBuffer2 } = require_buffer_util();
var kByteLength = Symbol("kByteLength");
var maskBuffer = Buffer.alloc(4);
var RANDOM_POOL_SIZE = 8 * 1024;
var randomPool;
var randomPoolPointer = RANDOM_POOL_SIZE;
var Sender2 = class _Sender {
/**
* Creates a Sender instance.
*
* @param {Duplex} socket The connection socket
* @param {Object} [extensions] An object containing the negotiated extensions
* @param {Function} [generateMask] The function used to generate the masking
* key
*/
constructor(socket, extensions, generateMask) {
this._extensions = extensions || {};
if (generateMask) {
this._generateMask = generateMask;
this._maskBuffer = Buffer.alloc(4);
}
this._socket = socket;
this._firstFragment = true;
this._compress = false;
this._bufferedBytes = 0;
this._deflating = false;
this._queue = [];
}
/**
* Frames a piece of data according to the HyBi WebSocket protocol.
*
* @param {(Buffer|String)} data The data to frame
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @return {(Buffer|String)[]} The framed data
* @public
*/
static frame(data, options) {
let mask;
let merge = false;
let offset = 2;
let skipMasking = false;
if (options.mask) {
mask = options.maskBuffer || maskBuffer;
if (options.generateMask) {
options.generateMask(mask);
} else {
if (randomPoolPointer === RANDOM_POOL_SIZE) {
if (randomPool === void 0) {
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
}
randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
randomPoolPointer = 0;
}
mask[0] = randomPool[randomPoolPointer++];
mask[1] = randomPool[randomPoolPointer++];
mask[2] = randomPool[randomPoolPointer++];
mask[3] = randomPool[randomPoolPointer++];
}
skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
offset = 6;
}
let dataLength;
if (typeof data === "string") {
if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
dataLength = options[kByteLength];
} else {
data = Buffer.from(data);
dataLength = data.length;
}
} else {
dataLength = data.length;
merge = options.mask && options.readOnly && !skipMasking;
}
let payloadLength = dataLength;
if (dataLength >= 65536) {
offset += 8;
payloadLength = 127;
} else if (dataLength > 125) {
offset += 2;
payloadLength = 126;
}
const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
target[0] = options.fin ? options.opcode | 128 : options.opcode;
if (options.rsv1) target[0] |= 64;
target[1] = payloadLength;
if (payloadLength === 126) {
target.writeUInt16BE(dataLength, 2);
} else if (payloadLength === 127) {
target[2] = target[3] = 0;
target.writeUIntBE(dataLength, 4, 6);
}
if (!options.mask) return [target, data];
target[1] |= 128;
target[offset - 4] = mask[0];
target[offset - 3] = mask[1];
target[offset - 2] = mask[2];
target[offset - 1] = mask[3];
if (skipMasking) return [target, data];
if (merge) {
applyMask(data, mask, target, offset, dataLength);
return [target];
}
applyMask(data, mask, data, 0, dataLength);
return [target, data];
}
/**
* Sends a close message to the other peer.
*
* @param {Number} [code] The status code component of the body
* @param {(String|Buffer)} [data] The message component of the body
* @param {Boolean} [mask=false] Specifies whether or not to mask the message
* @param {Function} [cb] Callback
* @public
*/
close(code, data, mask, cb) {
let buf;
if (code === void 0) {
buf = EMPTY_BUFFER;
} else if (typeof code !== "number" || !isValidStatusCode(code)) {
throw new TypeError("First argument must be a valid error code number");
} else if (data === void 0 || !data.length) {
buf = Buffer.allocUnsafe(2);
buf.writeUInt16BE(code, 0);
} else {
const length = Buffer.byteLength(data);
if (length > 123) {
throw new RangeError("The message must not be greater than 123 bytes");
}
buf = Buffer.allocUnsafe(2 + length);
buf.writeUInt16BE(code, 0);
if (typeof data === "string") {
buf.write(data, 2);
} else {
buf.set(data, 2);
}
}
const options = {
[kByteLength]: buf.length,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 8,
readOnly: false,
rsv1: false
};
if (this._deflating) {
this.enqueue([this.dispatch, buf, false, options, cb]);
} else {
this.sendFrame(_Sender.frame(buf, options), cb);
}
}
/**
* Sends a ping message to the other peer.
*
* @param {*} data The message to send
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback
* @public
*/
ping(data, mask, cb) {
let byteLength2;
let readOnly;
if (typeof data === "string") {
byteLength2 = Buffer.byteLength(data);
readOnly = false;
} else {
data = toBuffer2(data);
byteLength2 = data.length;
readOnly = toBuffer2.readOnly;
}
if (byteLength2 > 125) {
throw new RangeError("The data size must not be greater than 125 bytes");
}
const options = {
[kByteLength]: byteLength2,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 9,
readOnly,
rsv1: false
};
if (this._deflating) {
this.enqueue([this.dispatch, data, false, options, cb]);
} else {
this.sendFrame(_Sender.frame(data, options), cb);
}
}
/**
* Sends a pong message to the other peer.
*
* @param {*} data The message to send
* @param {Boolean} [mask=false] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback
* @public
*/
pong(data, mask, cb) {
let byteLength2;
let readOnly;
if (typeof data === "string") {
byteLength2 = Buffer.byteLength(data);
readOnly = false;
} else {
data = toBuffer2(data);
byteLength2 = data.length;
readOnly = toBuffer2.readOnly;
}
if (byteLength2 > 125) {
throw new RangeError("The data size must not be greater than 125 bytes");
}
const options = {
[kByteLength]: byteLength2,
fin: true,
generateMask: this._generateMask,
mask,
maskBuffer: this._maskBuffer,
opcode: 10,
readOnly,
rsv1: false
};
if (this._deflating) {
this.enqueue([this.dispatch, data, false, options, cb]);
} else {
this.sendFrame(_Sender.frame(data, options), cb);
}
}
/**
* Sends a data message to the other peer.
*
* @param {*} data The message to send
* @param {Object} options Options object
* @param {Boolean} [options.binary=false] Specifies whether `data` is binary
* or text
* @param {Boolean} [options.compress=false] Specifies whether or not to
* compress `data`
* @param {Boolean} [options.fin=false] Specifies whether the fragment is the
* last one
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Function} [cb] Callback
* @public
*/
send(data, options, cb) {
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
let opcode = options.binary ? 2 : 1;
let rsv1 = options.compress;
let byteLength2;
let readOnly;
if (typeof data === "string") {
byteLength2 = Buffer.byteLength(data);
readOnly = false;
} else {
data = toBuffer2(data);
byteLength2 = data.length;
readOnly = toBuffer2.readOnly;
}
if (this._firstFragment) {
this._firstFragment = false;
if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
rsv1 = byteLength2 >= perMessageDeflate._threshold;
}
this._compress = rsv1;
} else {
rsv1 = false;
opcode = 0;
}
if (options.fin) this._firstFragment = true;
if (perMessageDeflate) {
const opts = {
[kByteLength]: byteLength2,
fin: options.fin,
generateMask: this._generateMask,
mask: options.mask,
maskBuffer: this._maskBuffer,
opcode,
readOnly,
rsv1
};
if (this._deflating) {
this.enqueue([this.dispatch, data, this._compress, opts, cb]);
} else {
this.dispatch(data, this._compress, opts, cb);
}
} else {
this.sendFrame(
_Sender.frame(data, {
[kByteLength]: byteLength2,
fin: options.fin,
generateMask: this._generateMask,
mask: options.mask,
maskBuffer: this._maskBuffer,
opcode,
readOnly,
rsv1: false
}),
cb
);
}
}
/**
* Dispatches a message.
*
* @param {(Buffer|String)} data The message to send
* @param {Boolean} [compress=false] Specifies whether or not to compress
* `data`
* @param {Object} options Options object
* @param {Boolean} [options.fin=false] Specifies whether or not to set the
* FIN bit
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Boolean} [options.mask=false] Specifies whether or not to mask
* `data`
* @param {Buffer} [options.maskBuffer] The buffer used to store the masking
* key
* @param {Number} options.opcode The opcode
* @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
* modified
* @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
* RSV1 bit
* @param {Function} [cb] Callback
* @private
*/
dispatch(data, compress, options, cb) {
if (!compress) {
this.sendFrame(_Sender.frame(data, options), cb);
return;
}
const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
this._bufferedBytes += options[kByteLength];
this._deflating = true;
perMessageDeflate.compress(data, options.fin, (_, buf) => {
if (this._socket.destroyed) {
const err = new Error(
"The socket was closed while data was being compressed"
);
if (typeof cb === "function") cb(err);
for (let i = 0; i < this._queue.length; i++) {
const params = this._queue[i];
const callback = params[params.length - 1];
if (typeof callback === "function") callback(err);
}
return;
}
this._bufferedBytes -= options[kByteLength];
this._deflating = false;
options.readOnly = false;
this.sendFrame(_Sender.frame(buf, options), cb);
this.dequeue();
});
}
/**
* Executes queued send operations.
*
* @private
*/
dequeue() {
while (!this._deflating && this._queue.length) {
const params = this._queue.shift();
this._bufferedBytes -= params[3][kByteLength];
Reflect.apply(params[0], this, params.slice(1));
}
}
/**
* Enqueues a send operation.
*
* @param {Array} params Send operation parameters.
* @private
*/
enqueue(params) {
this._bufferedBytes += params[3][kByteLength];
this._queue.push(params);
}
/**
* Sends a frame.
*
* @param {Buffer[]} list The frame to send
* @param {Function} [cb] Callback
* @private
*/
sendFrame(list, cb) {
if (list.length === 2) {
this._socket.cork();
this._socket.write(list[0]);
this._socket.write(list[1], cb);
this._socket.uncork();
} else {
this._socket.write(list[0], cb);
}
}
};
module2.exports = Sender2;
}
});
// node_modules/engine.io-client/node_modules/ws/lib/event-target.js
var require_event_target = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/event-target.js"(exports2, module2) {
"use strict";
var { kForOnEventAttribute, kListener } = require_constants();
var kCode = Symbol("kCode");
var kData = Symbol("kData");
var kError = Symbol("kError");
var kMessage = Symbol("kMessage");
var kReason = Symbol("kReason");
var kTarget = Symbol("kTarget");
var kType = Symbol("kType");
var kWasClean = Symbol("kWasClean");
var Event = class {
/**
* Create a new `Event`.
*
* @param {String} type The name of the event
* @throws {TypeError} If the `type` argument is not specified
*/
constructor(type) {
this[kTarget] = null;
this[kType] = type;
}
/**
* @type {*}
*/
get target() {
return this[kTarget];
}
/**
* @type {String}
*/
get type() {
return this[kType];
}
};
Object.defineProperty(Event.prototype, "target", { enumerable: true });
Object.defineProperty(Event.prototype, "type", { enumerable: true });
var CloseEvent = class extends Event {
/**
* Create a new `CloseEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {Number} [options.code=0] The status code explaining why the
* connection was closed
* @param {String} [options.reason=''] A human-readable string explaining why
* the connection was closed
* @param {Boolean} [options.wasClean=false] Indicates whether or not the
* connection was cleanly closed
*/
constructor(type, options = {}) {
super(type);
this[kCode] = options.code === void 0 ? 0 : options.code;
this[kReason] = options.reason === void 0 ? "" : options.reason;
this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
}
/**
* @type {Number}
*/
get code() {
return this[kCode];
}
/**
* @type {String}
*/
get reason() {
return this[kReason];
}
/**
* @type {Boolean}
*/
get wasClean() {
return this[kWasClean];
}
};
Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
var ErrorEvent = class extends Event {
/**
* Create a new `ErrorEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.error=null] The error that generated this event
* @param {String} [options.message=''] The error message
*/
constructor(type, options = {}) {
super(type);
this[kError] = options.error === void 0 ? null : options.error;
this[kMessage] = options.message === void 0 ? "" : options.message;
}
/**
* @type {*}
*/
get error() {
return this[kError];
}
/**
* @type {String}
*/
get message() {
return this[kMessage];
}
};
Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
var MessageEvent = class extends Event {
/**
* Create a new `MessageEvent`.
*
* @param {String} type The name of the event
* @param {Object} [options] A dictionary object that allows for setting
* attributes via object members of the same name
* @param {*} [options.data=null] The message content
*/
constructor(type, options = {}) {
super(type);
this[kData] = options.data === void 0 ? null : options.data;
}
/**
* @type {*}
*/
get data() {
return this[kData];
}
};
Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
var EventTarget = {
/**
* Register an event listener.
*
* @param {String} type A string representing the event type to listen for
* @param {(Function|Object)} handler The listener to add
* @param {Object} [options] An options object specifies characteristics about
* the event listener
* @param {Boolean} [options.once=false] A `Boolean` indicating that the
* listener should be invoked at most once after being added. If `true`,
* the listener would be automatically removed when invoked.
* @public
*/
addEventListener(type, handler, options = {}) {
for (const listener of this.listeners(type)) {
if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
return;
}
}
let wrapper;
if (type === "message") {
wrapper = function onMessage(data, isBinary2) {
const event = new MessageEvent("message", {
data: isBinary2 ? data : data.toString()
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === "close") {
wrapper = function onClose(code, message) {
const event = new CloseEvent("close", {
code,
reason: message.toString(),
wasClean: this._closeFrameReceived && this._closeFrameSent
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === "error") {
wrapper = function onError(error) {
const event = new ErrorEvent("error", {
error,
message: error.message
});
event[kTarget] = this;
callListener(handler, this, event);
};
} else if (type === "open") {
wrapper = function onOpen() {
const event = new Event("open");
event[kTarget] = this;
callListener(handler, this, event);
};
} else {
return;
}
wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
wrapper[kListener] = handler;
if (options.once) {
this.once(type, wrapper);
} else {
this.on(type, wrapper);
}
},
/**
* Remove an event listener.
*
* @param {String} type A string representing the event type to remove
* @param {(Function|Object)} handler The listener to remove
* @public
*/
removeEventListener(type, handler) {
for (const listener of this.listeners(type)) {
if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
this.removeListener(type, listener);
break;
}
}
}
};
module2.exports = {
CloseEvent,
ErrorEvent,
Event,
EventTarget,
MessageEvent
};
function callListener(listener, thisArg, event) {
if (typeof listener === "object" && listener.handleEvent) {
listener.handleEvent.call(listener, event);
} else {
listener.call(thisArg, event);
}
}
}
});
// node_modules/engine.io-client/node_modules/ws/lib/extension.js
var require_extension = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/extension.js"(exports2, module2) {
"use strict";
var { tokenChars } = require_validation();
function push(dest, name, elem) {
if (dest[name] === void 0) dest[name] = [elem];
else dest[name].push(elem);
}
function parse5(header) {
const offers = /* @__PURE__ */ Object.create(null);
let params = /* @__PURE__ */ Object.create(null);
let mustUnescape = false;
let isEscaping = false;
let inQuotes = false;
let extensionName;
let paramName;
let start = -1;
let code = -1;
let end = -1;
let i = 0;
for (; i < header.length; i++) {
code = header.charCodeAt(i);
if (extensionName === void 0) {
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (i !== 0 && (code === 32 || code === 9)) {
if (end === -1 && start !== -1) end = i;
} else if (code === 59 || code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
const name = header.slice(start, end);
if (code === 44) {
push(offers, name, params);
params = /* @__PURE__ */ Object.create(null);
} else {
extensionName = name;
}
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else if (paramName === void 0) {
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (code === 32 || code === 9) {
if (end === -1 && start !== -1) end = i;
} else if (code === 59 || code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
push(params, header.slice(start, end), true);
if (code === 44) {
push(offers, extensionName, params);
params = /* @__PURE__ */ Object.create(null);
extensionName = void 0;
}
start = end = -1;
} else if (code === 61 && start !== -1 && end === -1) {
paramName = header.slice(start, i);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else {
if (isEscaping) {
if (tokenChars[code] !== 1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (start === -1) start = i;
else if (!mustUnescape) mustUnescape = true;
isEscaping = false;
} else if (inQuotes) {
if (tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (code === 34 && start !== -1) {
inQuotes = false;
end = i;
} else if (code === 92) {
isEscaping = true;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
} else if (code === 34 && header.charCodeAt(i - 1) === 61) {
inQuotes = true;
} else if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (start !== -1 && (code === 32 || code === 9)) {
if (end === -1) end = i;
} else if (code === 59 || code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
let value2 = header.slice(start, end);
if (mustUnescape) {
value2 = value2.replace(/\\/g, "");
mustUnescape = false;
}
push(params, paramName, value2);
if (code === 44) {
push(offers, extensionName, params);
params = /* @__PURE__ */ Object.create(null);
extensionName = void 0;
}
paramName = void 0;
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
}
}
if (start === -1 || inQuotes || code === 32 || code === 9) {
throw new SyntaxError("Unexpected end of input");
}
if (end === -1) end = i;
const token = header.slice(start, end);
if (extensionName === void 0) {
push(offers, token, params);
} else {
if (paramName === void 0) {
push(params, token, true);
} else if (mustUnescape) {
push(params, paramName, token.replace(/\\/g, ""));
} else {
push(params, paramName, token);
}
push(offers, extensionName, params);
}
return offers;
}
function format(extensions) {
return Object.keys(extensions).map((extension) => {
let configurations = extensions[extension];
if (!Array.isArray(configurations)) configurations = [configurations];
return configurations.map((params) => {
return [extension].concat(
Object.keys(params).map((k) => {
let values = params[k];
if (!Array.isArray(values)) values = [values];
return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
})
).join("; ");
}).join(", ");
}).join(", ");
}
module2.exports = { format, parse: parse5 };
}
});
// node_modules/engine.io-client/node_modules/ws/lib/websocket.js
var require_websocket = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/websocket.js"(exports2, module2) {
"use strict";
var EventEmitter2 = require("events");
var https = require("https");
var http = require("http");
var net = require("net");
var tls = require("tls");
var { randomBytes, createHash } = require("crypto");
var { Duplex, Readable } = require("stream");
var { URL: URL2 } = require("url");
var PerMessageDeflate = require_permessage_deflate();
var Receiver2 = require_receiver();
var Sender2 = require_sender();
var {
BINARY_TYPES,
EMPTY_BUFFER,
GUID,
kForOnEventAttribute,
kListener,
kStatusCode,
kWebSocket,
NOOP
} = require_constants();
var {
EventTarget: { addEventListener: addEventListener2, removeEventListener: removeEventListener2 }
} = require_event_target();
var { format, parse: parse5 } = require_extension();
var { toBuffer: toBuffer2 } = require_buffer_util();
var closeTimeout = 30 * 1e3;
var kAborted = Symbol("kAborted");
var protocolVersions = [8, 13];
var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
var WebSocket3 = class _WebSocket extends EventEmitter2 {
/**
* Create a new `WebSocket`.
*
* @param {(String|URL)} address The URL to which to connect
* @param {(String|String[])} [protocols] The subprotocols
* @param {Object} [options] Connection options
*/
constructor(address, protocols, options) {
super();
this._binaryType = BINARY_TYPES[0];
this._closeCode = 1006;
this._closeFrameReceived = false;
this._closeFrameSent = false;
this._closeMessage = EMPTY_BUFFER;
this._closeTimer = null;
this._extensions = {};
this._paused = false;
this._protocol = "";
this._readyState = _WebSocket.CONNECTING;
this._receiver = null;
this._sender = null;
this._socket = null;
if (address !== null) {
this._bufferedAmount = 0;
this._isServer = false;
this._redirects = 0;
if (protocols === void 0) {
protocols = [];
} else if (!Array.isArray(protocols)) {
if (typeof protocols === "object" && protocols !== null) {
options = protocols;
protocols = [];
} else {
protocols = [protocols];
}
}
initAsClient(this, address, protocols, options);
} else {
this._autoPong = options.autoPong;
this._isServer = true;
}
}
/**
* This deviates from the WHATWG interface since ws doesn't support the
* required default "blob" type (instead we define a custom "nodebuffer"
* type).
*
* @type {String}
*/
get binaryType() {
return this._binaryType;
}
set binaryType(type) {
if (!BINARY_TYPES.includes(type)) return;
this._binaryType = type;
if (this._receiver) this._receiver._binaryType = type;
}
/**
* @type {Number}
*/
get bufferedAmount() {
if (!this._socket) return this._bufferedAmount;
return this._socket._writableState.length + this._sender._bufferedBytes;
}
/**
* @type {String}
*/
get extensions() {
return Object.keys(this._extensions).join();
}
/**
* @type {Boolean}
*/
get isPaused() {
return this._paused;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onclose() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onerror() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onopen() {
return null;
}
/**
* @type {Function}
*/
/* istanbul ignore next */
get onmessage() {
return null;
}
/**
* @type {String}
*/
get protocol() {
return this._protocol;
}
/**
* @type {Number}
*/
get readyState() {
return this._readyState;
}
/**
* @type {String}
*/
get url() {
return this._url;
}
/**
* Set up the socket and the internal resources.
*
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Object} options Options object
* @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {Function} [options.generateMask] The function used to generate the
* masking key
* @param {Number} [options.maxPayload=0] The maximum allowed message size
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @private
*/
setSocket(socket, head, options) {
const receiver = new Receiver2({
allowSynchronousEvents: options.allowSynchronousEvents,
binaryType: this.binaryType,
extensions: this._extensions,
isServer: this._isServer,
maxPayload: options.maxPayload,
skipUTF8Validation: options.skipUTF8Validation
});
this._sender = new Sender2(socket, this._extensions, options.generateMask);
this._receiver = receiver;
this._socket = socket;
receiver[kWebSocket] = this;
socket[kWebSocket] = this;
receiver.on("conclude", receiverOnConclude);
receiver.on("drain", receiverOnDrain);
receiver.on("error", receiverOnError);
receiver.on("message", receiverOnMessage);
receiver.on("ping", receiverOnPing);
receiver.on("pong", receiverOnPong);
if (socket.setTimeout) socket.setTimeout(0);
if (socket.setNoDelay) socket.setNoDelay();
if (head.length > 0) socket.unshift(head);
socket.on("close", socketOnClose);
socket.on("data", socketOnData);
socket.on("end", socketOnEnd);
socket.on("error", socketOnError);
this._readyState = _WebSocket.OPEN;
this.emit("open");
}
/**
* Emit the `'close'` event.
*
* @private
*/
emitClose() {
if (!this._socket) {
this._readyState = _WebSocket.CLOSED;
this.emit("close", this._closeCode, this._closeMessage);
return;
}
if (this._extensions[PerMessageDeflate.extensionName]) {
this._extensions[PerMessageDeflate.extensionName].cleanup();
}
this._receiver.removeAllListeners();
this._readyState = _WebSocket.CLOSED;
this.emit("close", this._closeCode, this._closeMessage);
}
/**
* Start a closing handshake.
*
* +----------+ +-----------+ +----------+
* - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
* | +----------+ +-----------+ +----------+ |
* +----------+ +-----------+ |
* CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
* +----------+ +-----------+ |
* | | | +---+ |
* +------------------------+-->|fin| - - - -
* | +---+ | +---+
* - - - - -|fin|<---------------------+
* +---+
*
* @param {Number} [code] Status code explaining why the connection is closing
* @param {(String|Buffer)} [data] The reason why the connection is
* closing
* @public
*/
close(code, data) {
if (this.readyState === _WebSocket.CLOSED) return;
if (this.readyState === _WebSocket.CONNECTING) {
const msg = "WebSocket was closed before the connection was established";
abortHandshake(this, this._req, msg);
return;
}
if (this.readyState === _WebSocket.CLOSING) {
if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
this._socket.end();
}
return;
}
this._readyState = _WebSocket.CLOSING;
this._sender.close(code, data, !this._isServer, (err) => {
if (err) return;
this._closeFrameSent = true;
if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
this._socket.end();
}
});
this._closeTimer = setTimeout(
this._socket.destroy.bind(this._socket),
closeTimeout
);
}
/**
* Pause the socket.
*
* @public
*/
pause() {
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
return;
}
this._paused = true;
this._socket.pause();
}
/**
* Send a ping.
*
* @param {*} [data] The data to send
* @param {Boolean} [mask] Indicates whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when the ping is sent
* @public
*/
ping(data, mask, cb) {
if (this.readyState === _WebSocket.CONNECTING) {
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
}
if (typeof data === "function") {
cb = data;
data = mask = void 0;
} else if (typeof mask === "function") {
cb = mask;
mask = void 0;
}
if (typeof data === "number") data = data.toString();
if (this.readyState !== _WebSocket.OPEN) {
sendAfterClose(this, data, cb);
return;
}
if (mask === void 0) mask = !this._isServer;
this._sender.ping(data || EMPTY_BUFFER, mask, cb);
}
/**
* Send a pong.
*
* @param {*} [data] The data to send
* @param {Boolean} [mask] Indicates whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when the pong is sent
* @public
*/
pong(data, mask, cb) {
if (this.readyState === _WebSocket.CONNECTING) {
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
}
if (typeof data === "function") {
cb = data;
data = mask = void 0;
} else if (typeof mask === "function") {
cb = mask;
mask = void 0;
}
if (typeof data === "number") data = data.toString();
if (this.readyState !== _WebSocket.OPEN) {
sendAfterClose(this, data, cb);
return;
}
if (mask === void 0) mask = !this._isServer;
this._sender.pong(data || EMPTY_BUFFER, mask, cb);
}
/**
* Resume the socket.
*
* @public
*/
resume() {
if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
return;
}
this._paused = false;
if (!this._receiver._writableState.needDrain) this._socket.resume();
}
/**
* Send a data message.
*
* @param {*} data The message to send
* @param {Object} [options] Options object
* @param {Boolean} [options.binary] Specifies whether `data` is binary or
* text
* @param {Boolean} [options.compress] Specifies whether or not to compress
* `data`
* @param {Boolean} [options.fin=true] Specifies whether the fragment is the
* last one
* @param {Boolean} [options.mask] Specifies whether or not to mask `data`
* @param {Function} [cb] Callback which is executed when data is written out
* @public
*/
send(data, options, cb) {
if (this.readyState === _WebSocket.CONNECTING) {
throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
}
if (typeof options === "function") {
cb = options;
options = {};
}
if (typeof data === "number") data = data.toString();
if (this.readyState !== _WebSocket.OPEN) {
sendAfterClose(this, data, cb);
return;
}
const opts = {
binary: typeof data !== "string",
mask: !this._isServer,
compress: true,
fin: true,
...options
};
if (!this._extensions[PerMessageDeflate.extensionName]) {
opts.compress = false;
}
this._sender.send(data || EMPTY_BUFFER, opts, cb);
}
/**
* Forcibly close the connection.
*
* @public
*/
terminate() {
if (this.readyState === _WebSocket.CLOSED) return;
if (this.readyState === _WebSocket.CONNECTING) {
const msg = "WebSocket was closed before the connection was established";
abortHandshake(this, this._req, msg);
return;
}
if (this._socket) {
this._readyState = _WebSocket.CLOSING;
this._socket.destroy();
}
}
};
Object.defineProperty(WebSocket3, "CONNECTING", {
enumerable: true,
value: readyStates.indexOf("CONNECTING")
});
Object.defineProperty(WebSocket3.prototype, "CONNECTING", {
enumerable: true,
value: readyStates.indexOf("CONNECTING")
});
Object.defineProperty(WebSocket3, "OPEN", {
enumerable: true,
value: readyStates.indexOf("OPEN")
});
Object.defineProperty(WebSocket3.prototype, "OPEN", {
enumerable: true,
value: readyStates.indexOf("OPEN")
});
Object.defineProperty(WebSocket3, "CLOSING", {
enumerable: true,
value: readyStates.indexOf("CLOSING")
});
Object.defineProperty(WebSocket3.prototype, "CLOSING", {
enumerable: true,
value: readyStates.indexOf("CLOSING")
});
Object.defineProperty(WebSocket3, "CLOSED", {
enumerable: true,
value: readyStates.indexOf("CLOSED")
});
Object.defineProperty(WebSocket3.prototype, "CLOSED", {
enumerable: true,
value: readyStates.indexOf("CLOSED")
});
[
"binaryType",
"bufferedAmount",
"extensions",
"isPaused",
"protocol",
"readyState",
"url"
].forEach((property) => {
Object.defineProperty(WebSocket3.prototype, property, { enumerable: true });
});
["open", "error", "close", "message"].forEach((method) => {
Object.defineProperty(WebSocket3.prototype, `on${method}`, {
enumerable: true,
get() {
for (const listener of this.listeners(method)) {
if (listener[kForOnEventAttribute]) return listener[kListener];
}
return null;
},
set(handler) {
for (const listener of this.listeners(method)) {
if (listener[kForOnEventAttribute]) {
this.removeListener(method, listener);
break;
}
}
if (typeof handler !== "function") return;
this.addEventListener(method, handler, {
[kForOnEventAttribute]: true
});
}
});
});
WebSocket3.prototype.addEventListener = addEventListener2;
WebSocket3.prototype.removeEventListener = removeEventListener2;
module2.exports = WebSocket3;
function initAsClient(websocket, address, protocols, options) {
const opts = {
allowSynchronousEvents: true,
autoPong: true,
protocolVersion: protocolVersions[1],
maxPayload: 100 * 1024 * 1024,
skipUTF8Validation: false,
perMessageDeflate: true,
followRedirects: false,
maxRedirects: 10,
...options,
socketPath: void 0,
hostname: void 0,
protocol: void 0,
timeout: void 0,
method: "GET",
host: void 0,
path: void 0,
port: void 0
};
websocket._autoPong = opts.autoPong;
if (!protocolVersions.includes(opts.protocolVersion)) {
throw new RangeError(
`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
);
}
let parsedUrl;
if (address instanceof URL2) {
parsedUrl = address;
} else {
try {
parsedUrl = new URL2(address);
} catch (e) {
throw new SyntaxError(`Invalid URL: ${address}`);
}
}
if (parsedUrl.protocol === "http:") {
parsedUrl.protocol = "ws:";
} else if (parsedUrl.protocol === "https:") {
parsedUrl.protocol = "wss:";
}
websocket._url = parsedUrl.href;
const isSecure = parsedUrl.protocol === "wss:";
const isIpcUrl = parsedUrl.protocol === "ws+unix:";
let invalidUrlMessage;
if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`;
} else if (isIpcUrl && !parsedUrl.pathname) {
invalidUrlMessage = "The URL's pathname is empty";
} else if (parsedUrl.hash) {
invalidUrlMessage = "The URL contains a fragment identifier";
}
if (invalidUrlMessage) {
const err = new SyntaxError(invalidUrlMessage);
if (websocket._redirects === 0) {
throw err;
} else {
emitErrorAndClose(websocket, err);
return;
}
}
const defaultPort = isSecure ? 443 : 80;
const key = randomBytes(16).toString("base64");
const request = isSecure ? https.request : http.request;
const protocolSet = /* @__PURE__ */ new Set();
let perMessageDeflate;
opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
opts.defaultPort = opts.defaultPort || defaultPort;
opts.port = parsedUrl.port || defaultPort;
opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
opts.headers = {
...opts.headers,
"Sec-WebSocket-Version": opts.protocolVersion,
"Sec-WebSocket-Key": key,
Connection: "Upgrade",
Upgrade: "websocket"
};
opts.path = parsedUrl.pathname + parsedUrl.search;
opts.timeout = opts.handshakeTimeout;
if (opts.perMessageDeflate) {
perMessageDeflate = new PerMessageDeflate(
opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
false,
opts.maxPayload
);
opts.headers["Sec-WebSocket-Extensions"] = format({
[PerMessageDeflate.extensionName]: perMessageDeflate.offer()
});
}
if (protocols.length) {
for (const protocol4 of protocols) {
if (typeof protocol4 !== "string" || !subprotocolRegex.test(protocol4) || protocolSet.has(protocol4)) {
throw new SyntaxError(
"An invalid or duplicated subprotocol was specified"
);
}
protocolSet.add(protocol4);
}
opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
}
if (opts.origin) {
if (opts.protocolVersion < 13) {
opts.headers["Sec-WebSocket-Origin"] = opts.origin;
} else {
opts.headers.Origin = opts.origin;
}
}
if (parsedUrl.username || parsedUrl.password) {
opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
}
if (isIpcUrl) {
const parts2 = opts.path.split(":");
opts.socketPath = parts2[0];
opts.path = parts2[1];
}
let req;
if (opts.followRedirects) {
if (websocket._redirects === 0) {
websocket._originalIpc = isIpcUrl;
websocket._originalSecure = isSecure;
websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
const headers = options && options.headers;
options = { ...options, headers: {} };
if (headers) {
for (const [key2, value2] of Object.entries(headers)) {
options.headers[key2.toLowerCase()] = value2;
}
}
} else if (websocket.listenerCount("redirect") === 0) {
const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
if (!isSameHost || websocket._originalSecure && !isSecure) {
delete opts.headers.authorization;
delete opts.headers.cookie;
if (!isSameHost) delete opts.headers.host;
opts.auth = void 0;
}
}
if (opts.auth && !options.headers.authorization) {
options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
}
req = websocket._req = request(opts);
if (websocket._redirects) {
websocket.emit("redirect", websocket.url, req);
}
} else {
req = websocket._req = request(opts);
}
if (opts.timeout) {
req.on("timeout", () => {
abortHandshake(websocket, req, "Opening handshake has timed out");
});
}
req.on("error", (err) => {
if (req === null || req[kAborted]) return;
req = websocket._req = null;
emitErrorAndClose(websocket, err);
});
req.on("response", (res) => {
const location2 = res.headers.location;
const statusCode = res.statusCode;
if (location2 && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
if (++websocket._redirects > opts.maxRedirects) {
abortHandshake(websocket, req, "Maximum redirects exceeded");
return;
}
req.abort();
let addr;
try {
addr = new URL2(location2, address);
} catch (e) {
const err = new SyntaxError(`Invalid URL: ${location2}`);
emitErrorAndClose(websocket, err);
return;
}
initAsClient(websocket, addr, protocols, options);
} else if (!websocket.emit("unexpected-response", req, res)) {
abortHandshake(
websocket,
req,
`Unexpected server response: ${res.statusCode}`
);
}
});
req.on("upgrade", (res, socket, head) => {
websocket.emit("upgrade", res);
if (websocket.readyState !== WebSocket3.CONNECTING) return;
req = websocket._req = null;
const upgrade = res.headers.upgrade;
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
abortHandshake(websocket, socket, "Invalid Upgrade header");
return;
}
const digest = createHash("sha1").update(key + GUID).digest("base64");
if (res.headers["sec-websocket-accept"] !== digest) {
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
return;
}
const serverProt = res.headers["sec-websocket-protocol"];
let protError;
if (serverProt !== void 0) {
if (!protocolSet.size) {
protError = "Server sent a subprotocol but none was requested";
} else if (!protocolSet.has(serverProt)) {
protError = "Server sent an invalid subprotocol";
}
} else if (protocolSet.size) {
protError = "Server sent no subprotocol";
}
if (protError) {
abortHandshake(websocket, socket, protError);
return;
}
if (serverProt) websocket._protocol = serverProt;
const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
if (secWebSocketExtensions !== void 0) {
if (!perMessageDeflate) {
const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
abortHandshake(websocket, socket, message);
return;
}
let extensions;
try {
extensions = parse5(secWebSocketExtensions);
} catch (err) {
const message = "Invalid Sec-WebSocket-Extensions header";
abortHandshake(websocket, socket, message);
return;
}
const extensionNames = Object.keys(extensions);
if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
const message = "Server indicated an extension that was not requested";
abortHandshake(websocket, socket, message);
return;
}
try {
perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
} catch (err) {
const message = "Invalid Sec-WebSocket-Extensions header";
abortHandshake(websocket, socket, message);
return;
}
websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
}
websocket.setSocket(socket, head, {
allowSynchronousEvents: opts.allowSynchronousEvents,
generateMask: opts.generateMask,
maxPayload: opts.maxPayload,
skipUTF8Validation: opts.skipUTF8Validation
});
});
if (opts.finishRequest) {
opts.finishRequest(req, websocket);
} else {
req.end();
}
}
function emitErrorAndClose(websocket, err) {
websocket._readyState = WebSocket3.CLOSING;
websocket.emit("error", err);
websocket.emitClose();
}
function netConnect(options) {
options.path = options.socketPath;
return net.connect(options);
}
function tlsConnect(options) {
options.path = void 0;
if (!options.servername && options.servername !== "") {
options.servername = net.isIP(options.host) ? "" : options.host;
}
return tls.connect(options);
}
function abortHandshake(websocket, stream, message) {
websocket._readyState = WebSocket3.CLOSING;
const err = new Error(message);
Error.captureStackTrace(err, abortHandshake);
if (stream.setHeader) {
stream[kAborted] = true;
stream.abort();
if (stream.socket && !stream.socket.destroyed) {
stream.socket.destroy();
}
process.nextTick(emitErrorAndClose, websocket, err);
} else {
stream.destroy(err);
stream.once("error", websocket.emit.bind(websocket, "error"));
stream.once("close", websocket.emitClose.bind(websocket));
}
}
function sendAfterClose(websocket, data, cb) {
if (data) {
const length = toBuffer2(data).length;
if (websocket._socket) websocket._sender._bufferedBytes += length;
else websocket._bufferedAmount += length;
}
if (cb) {
const err = new Error(
`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
);
process.nextTick(cb, err);
}
}
function receiverOnConclude(code, reason) {
const websocket = this[kWebSocket];
websocket._closeFrameReceived = true;
websocket._closeMessage = reason;
websocket._closeCode = code;
if (websocket._socket[kWebSocket] === void 0) return;
websocket._socket.removeListener("data", socketOnData);
process.nextTick(resume, websocket._socket);
if (code === 1005) websocket.close();
else websocket.close(code, reason);
}
function receiverOnDrain() {
const websocket = this[kWebSocket];
if (!websocket.isPaused) websocket._socket.resume();
}
function receiverOnError(err) {
const websocket = this[kWebSocket];
if (websocket._socket[kWebSocket] !== void 0) {
websocket._socket.removeListener("data", socketOnData);
process.nextTick(resume, websocket._socket);
websocket.close(err[kStatusCode]);
}
websocket.emit("error", err);
}
function receiverOnFinish() {
this[kWebSocket].emitClose();
}
function receiverOnMessage(data, isBinary2) {
this[kWebSocket].emit("message", data, isBinary2);
}
function receiverOnPing(data) {
const websocket = this[kWebSocket];
if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
websocket.emit("ping", data);
}
function receiverOnPong(data) {
this[kWebSocket].emit("pong", data);
}
function resume(stream) {
stream.resume();
}
function socketOnClose() {
const websocket = this[kWebSocket];
this.removeListener("close", socketOnClose);
this.removeListener("data", socketOnData);
this.removeListener("end", socketOnEnd);
websocket._readyState = WebSocket3.CLOSING;
let chunk;
if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
websocket._receiver.write(chunk);
}
websocket._receiver.end();
this[kWebSocket] = void 0;
clearTimeout(websocket._closeTimer);
if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
websocket.emitClose();
} else {
websocket._receiver.on("error", receiverOnFinish);
websocket._receiver.on("finish", receiverOnFinish);
}
}
function socketOnData(chunk) {
if (!this[kWebSocket]._receiver.write(chunk)) {
this.pause();
}
}
function socketOnEnd() {
const websocket = this[kWebSocket];
websocket._readyState = WebSocket3.CLOSING;
websocket._receiver.end();
this.end();
}
function socketOnError() {
const websocket = this[kWebSocket];
this.removeListener("error", socketOnError);
this.on("error", NOOP);
if (websocket) {
websocket._readyState = WebSocket3.CLOSING;
this.destroy();
}
}
}
});
// node_modules/engine.io-client/node_modules/ws/lib/subprotocol.js
var require_subprotocol = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/subprotocol.js"(exports2, module2) {
"use strict";
var { tokenChars } = require_validation();
function parse5(header) {
const protocols = /* @__PURE__ */ new Set();
let start = -1;
let end = -1;
let i = 0;
for (i; i < header.length; i++) {
const code = header.charCodeAt(i);
if (end === -1 && tokenChars[code] === 1) {
if (start === -1) start = i;
} else if (i !== 0 && (code === 32 || code === 9)) {
if (end === -1 && start !== -1) end = i;
} else if (code === 44) {
if (start === -1) {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
if (end === -1) end = i;
const protocol5 = header.slice(start, end);
if (protocols.has(protocol5)) {
throw new SyntaxError(`The "${protocol5}" subprotocol is duplicated`);
}
protocols.add(protocol5);
start = end = -1;
} else {
throw new SyntaxError(`Unexpected character at index ${i}`);
}
}
if (start === -1 || end !== -1) {
throw new SyntaxError("Unexpected end of input");
}
const protocol4 = header.slice(start, i);
if (protocols.has(protocol4)) {
throw new SyntaxError(`The "${protocol4}" subprotocol is duplicated`);
}
protocols.add(protocol4);
return protocols;
}
module2.exports = { parse: parse5 };
}
});
// node_modules/engine.io-client/node_modules/ws/lib/websocket-server.js
var require_websocket_server = __commonJS({
"node_modules/engine.io-client/node_modules/ws/lib/websocket-server.js"(exports2, module2) {
"use strict";
var EventEmitter2 = require("events");
var http = require("http");
var { Duplex } = require("stream");
var { createHash } = require("crypto");
var extension = require_extension();
var PerMessageDeflate = require_permessage_deflate();
var subprotocol = require_subprotocol();
var WebSocket3 = require_websocket();
var { GUID, kWebSocket } = require_constants();
var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
var RUNNING = 0;
var CLOSING = 1;
var CLOSED = 2;
var WebSocketServer2 = class extends EventEmitter2 {
/**
* Create a `WebSocketServer` instance.
*
* @param {Object} options Configuration options
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {Boolean} [options.autoPong=true] Specifies whether or not to
* automatically send a pong in response to a ping
* @param {Number} [options.backlog=511] The maximum length of the queue of
* pending connections
* @param {Boolean} [options.clientTracking=true] Specifies whether or not to
* track clients
* @param {Function} [options.handleProtocols] A hook to handle protocols
* @param {String} [options.host] The hostname where to bind the server
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
* size
* @param {Boolean} [options.noServer=false] Enable no server mode
* @param {String} [options.path] Accept only connections matching this path
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
* permessage-deflate
* @param {Number} [options.port] The port where to bind the server
* @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
* server to use
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @param {Function} [options.verifyClient] A hook to reject connections
* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
* class to use. It must be the `WebSocket` class or class that extends it
* @param {Function} [callback] A listener for the `listening` event
*/
constructor(options, callback) {
super();
options = {
allowSynchronousEvents: true,
autoPong: true,
maxPayload: 100 * 1024 * 1024,
skipUTF8Validation: false,
perMessageDeflate: false,
handleProtocols: null,
clientTracking: true,
verifyClient: null,
noServer: false,
backlog: null,
// use default (511 as implemented in net.js)
server: null,
host: null,
path: null,
port: null,
WebSocket: WebSocket3,
...options
};
if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
throw new TypeError(
'One and only one of the "port", "server", or "noServer" options must be specified'
);
}
if (options.port != null) {
this._server = http.createServer((req, res) => {
const body = http.STATUS_CODES[426];
res.writeHead(426, {
"Content-Length": body.length,
"Content-Type": "text/plain"
});
res.end(body);
});
this._server.listen(
options.port,
options.host,
options.backlog,
callback
);
} else if (options.server) {
this._server = options.server;
}
if (this._server) {
const emitConnection = this.emit.bind(this, "connection");
this._removeListeners = addListeners(this._server, {
listening: this.emit.bind(this, "listening"),
error: this.emit.bind(this, "error"),
upgrade: (req, socket, head) => {
this.handleUpgrade(req, socket, head, emitConnection);
}
});
}
if (options.perMessageDeflate === true) options.perMessageDeflate = {};
if (options.clientTracking) {
this.clients = /* @__PURE__ */ new Set();
this._shouldEmitClose = false;
}
this.options = options;
this._state = RUNNING;
}
/**
* Returns the bound address, the address family name, and port of the server
* as reported by the operating system if listening on an IP socket.
* If the server is listening on a pipe or UNIX domain socket, the name is
* returned as a string.
*
* @return {(Object|String|null)} The address of the server
* @public
*/
address() {
if (this.options.noServer) {
throw new Error('The server is operating in "noServer" mode');
}
if (!this._server) return null;
return this._server.address();
}
/**
* Stop the server from accepting new connections and emit the `'close'` event
* when all existing connections are closed.
*
* @param {Function} [cb] A one-time listener for the `'close'` event
* @public
*/
close(cb) {
if (this._state === CLOSED) {
if (cb) {
this.once("close", () => {
cb(new Error("The server is not running"));
});
}
process.nextTick(emitClose, this);
return;
}
if (cb) this.once("close", cb);
if (this._state === CLOSING) return;
this._state = CLOSING;
if (this.options.noServer || this.options.server) {
if (this._server) {
this._removeListeners();
this._removeListeners = this._server = null;
}
if (this.clients) {
if (!this.clients.size) {
process.nextTick(emitClose, this);
} else {
this._shouldEmitClose = true;
}
} else {
process.nextTick(emitClose, this);
}
} else {
const server = this._server;
this._removeListeners();
this._removeListeners = this._server = null;
server.close(() => {
emitClose(this);
});
}
}
/**
* See if a given request should be handled by this server instance.
*
* @param {http.IncomingMessage} req Request object to inspect
* @return {Boolean} `true` if the request is valid, else `false`
* @public
*/
shouldHandle(req) {
if (this.options.path) {
const index = req.url.indexOf("?");
const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
if (pathname !== this.options.path) return false;
}
return true;
}
/**
* Handle a HTTP Upgrade request.
*
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @public
*/
handleUpgrade(req, socket, head, cb) {
socket.on("error", socketOnError);
const key = req.headers["sec-websocket-key"];
const upgrade = req.headers.upgrade;
const version = +req.headers["sec-websocket-version"];
if (req.method !== "GET") {
const message = "Invalid HTTP method";
abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
return;
}
if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
const message = "Invalid Upgrade header";
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (key === void 0 || !keyRegex.test(key)) {
const message = "Missing or invalid Sec-WebSocket-Key header";
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (version !== 8 && version !== 13) {
const message = "Missing or invalid Sec-WebSocket-Version header";
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (!this.shouldHandle(req)) {
abortHandshake(socket, 400);
return;
}
const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
let protocols = /* @__PURE__ */ new Set();
if (secWebSocketProtocol !== void 0) {
try {
protocols = subprotocol.parse(secWebSocketProtocol);
} catch (err) {
const message = "Invalid Sec-WebSocket-Protocol header";
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
}
const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
const extensions = {};
if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
const perMessageDeflate = new PerMessageDeflate(
this.options.perMessageDeflate,
true,
this.options.maxPayload
);
try {
const offers = extension.parse(secWebSocketExtensions);
if (offers[PerMessageDeflate.extensionName]) {
perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
}
} catch (err) {
const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
}
if (this.options.verifyClient) {
const info = {
origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
secure: !!(req.socket.authorized || req.socket.encrypted),
req
};
if (this.options.verifyClient.length === 2) {
this.options.verifyClient(info, (verified, code, message, headers) => {
if (!verified) {
return abortHandshake(socket, code || 401, message, headers);
}
this.completeUpgrade(
extensions,
key,
protocols,
req,
socket,
head,
cb
);
});
return;
}
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
}
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
}
/**
* Upgrade the connection to WebSocket.
*
* @param {Object} extensions The accepted extensions
* @param {String} key The value of the `Sec-WebSocket-Key` header
* @param {Set} protocols The subprotocols
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @throws {Error} If called more than once with the same socket
* @private
*/
completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
if (!socket.readable || !socket.writable) return socket.destroy();
if (socket[kWebSocket]) {
throw new Error(
"server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
);
}
if (this._state > RUNNING) return abortHandshake(socket, 503);
const digest = createHash("sha1").update(key + GUID).digest("base64");
const headers = [
"HTTP/1.1 101 Switching Protocols",
"Upgrade: websocket",
"Connection: Upgrade",
`Sec-WebSocket-Accept: ${digest}`
];
const ws = new this.options.WebSocket(null, void 0, this.options);
if (protocols.size) {
const protocol4 = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
if (protocol4) {
headers.push(`Sec-WebSocket-Protocol: ${protocol4}`);
ws._protocol = protocol4;
}
}
if (extensions[PerMessageDeflate.extensionName]) {
const params = extensions[PerMessageDeflate.extensionName].params;
const value2 = extension.format({
[PerMessageDeflate.extensionName]: [params]
});
headers.push(`Sec-WebSocket-Extensions: ${value2}`);
ws._extensions = extensions;
}
this.emit("headers", headers, req);
socket.write(headers.concat("\r\n").join("\r\n"));
socket.removeListener("error", socketOnError);
ws.setSocket(socket, head, {
allowSynchronousEvents: this.options.allowSynchronousEvents,
maxPayload: this.options.maxPayload,
skipUTF8Validation: this.options.skipUTF8Validation
});
if (this.clients) {
this.clients.add(ws);
ws.on("close", () => {
this.clients.delete(ws);
if (this._shouldEmitClose && !this.clients.size) {
process.nextTick(emitClose, this);
}
});
}
cb(ws, req);
}
};
module2.exports = WebSocketServer2;
function addListeners(server, map2) {
for (const event of Object.keys(map2)) server.on(event, map2[event]);
return function removeListeners() {
for (const event of Object.keys(map2)) {
server.removeListener(event, map2[event]);
}
};
}
function emitClose(server) {
server._state = CLOSED;
server.emit("close");
}
function socketOnError() {
this.destroy();
}
function abortHandshake(socket, code, message, headers) {
message = message || http.STATUS_CODES[code];
headers = {
Connection: "close",
"Content-Type": "text/html",
"Content-Length": Buffer.byteLength(message),
...headers
};
socket.once("finish", socket.destroy);
socket.end(
`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
);
}
function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
if (server.listenerCount("wsClientError")) {
const err = new Error(message);
Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
server.emit("wsClientError", err, socket, req);
} else {
abortHandshake(socket, code, message);
}
}
}
});
// node_modules/dotenv/package.json
var require_package = __commonJS({
"node_modules/dotenv/package.json"(exports2, module2) {
module2.exports = {
name: "dotenv",
version: "16.4.5",
description: "Loads environment variables from .env file",
main: "lib/main.js",
types: "lib/main.d.ts",
exports: {
".": {
types: "./lib/main.d.ts",
require: "./lib/main.js",
default: "./lib/main.js"
},
"./config": "./config.js",
"./config.js": "./config.js",
"./lib/env-options": "./lib/env-options.js",
"./lib/env-options.js": "./lib/env-options.js",
"./lib/cli-options": "./lib/cli-options.js",
"./lib/cli-options.js": "./lib/cli-options.js",
"./package.json": "./package.json"
},
scripts: {
"dts-check": "tsc --project tests/types/tsconfig.json",
lint: "standard",
"lint-readme": "standard-markdown",
pretest: "npm run lint && npm run dts-check",
test: "tap tests/*.js --100 -Rspec",
"test:coverage": "tap --coverage-report=lcov",
prerelease: "npm test",
release: "standard-version"
},
repository: {
type: "git",
url: "git://github.com/motdotla/dotenv.git"
},
funding: "https://dotenvx.com",
keywords: [
"dotenv",
"env",
".env",
"environment",
"variables",
"config",
"settings"
],
readmeFilename: "README.md",
license: "BSD-2-Clause",
devDependencies: {
"@definitelytyped/dtslint": "^0.0.133",
"@types/node": "^18.11.3",
decache: "^4.6.1",
sinon: "^14.0.1",
standard: "^17.0.0",
"standard-markdown": "^7.1.0",
"standard-version": "^9.5.0",
tap: "^16.3.0",
tar: "^6.1.11",
typescript: "^4.8.4"
},
engines: {
node: ">=12"
},
browser: {
fs: false
}
};
}
});
// node_modules/dotenv/lib/main.js
var require_main = __commonJS({
"node_modules/dotenv/lib/main.js"(exports2, module2) {
"use strict";
var fs = require("fs");
var path = require("path");
var os = require("os");
var crypto = require("crypto");
var packageJson = require_package();
var version = packageJson.version;
var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
function parse5(src) {
const obj = {};
let lines = src.toString();
lines = lines.replace(/\r\n?/mg, "\n");
let match;
while ((match = LINE.exec(lines)) != null) {
const key = match[1];
let value2 = match[2] || "";
value2 = value2.trim();
const maybeQuote = value2[0];
value2 = value2.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
if (maybeQuote === '"') {
value2 = value2.replace(/\\n/g, "\n");
value2 = value2.replace(/\\r/g, "\r");
}
obj[key] = value2;
}
return obj;
}
function _parseVault(options) {
const vaultPath = _vaultPath(options);
const result = DotenvModule.configDotenv({ path: vaultPath });
if (!result.parsed) {
const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
err.code = "MISSING_DATA";
throw err;
}
const keys = _dotenvKey(options).split(",");
const length = keys.length;
let decrypted;
for (let i = 0; i < length; i++) {
try {
const key = keys[i].trim();
const attrs = _instructions(result, key);
decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
break;
} catch (error) {
if (i + 1 >= length) {
throw error;
}
}
}
return DotenvModule.parse(decrypted);
}
function _log(message) {
console.log(`[dotenv@${version}][INFO] ${message}`);
}
function _warn(message) {
console.log(`[dotenv@${version}][WARN] ${message}`);
}
function _debug(message) {
console.log(`[dotenv@${version}][DEBUG] ${message}`);
}
function _dotenvKey(options) {
if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
return options.DOTENV_KEY;
}
if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
return process.env.DOTENV_KEY;
}
return "";
}
function _instructions(result, dotenvKey) {
let uri;
try {
uri = new URL(dotenvKey);
} catch (error) {
if (error.code === "ERR_INVALID_URL") {
const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
err.code = "INVALID_DOTENV_KEY";
throw err;
}
throw error;
}
const key = uri.password;
if (!key) {
const err = new Error("INVALID_DOTENV_KEY: Missing key part");
err.code = "INVALID_DOTENV_KEY";
throw err;
}
const environment = uri.searchParams.get("environment");
if (!environment) {
const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
err.code = "INVALID_DOTENV_KEY";
throw err;
}
const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
const ciphertext = result.parsed[environmentKey];
if (!ciphertext) {
const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
throw err;
}
return { ciphertext, key };
}
function _vaultPath(options) {
let possibleVaultPath = null;
if (options && options.path && options.path.length > 0) {
if (Array.isArray(options.path)) {
for (const filepath of options.path) {
if (fs.existsSync(filepath)) {
possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
}
}
} else {
possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
}
} else {
possibleVaultPath = path.resolve(process.cwd(), ".env.vault");
}
if (fs.existsSync(possibleVaultPath)) {
return possibleVaultPath;
}
return null;
}
function _resolveHome(envPath) {
return envPath[0] === "~" ? path.join(os.homedir(), envPath.slice(1)) : envPath;
}
function _configVault(options) {
_log("Loading env from encrypted .env.vault");
const parsed = DotenvModule._parseVault(options);
let processEnv = process.env;
if (options && options.processEnv != null) {
processEnv = options.processEnv;
}
DotenvModule.populate(processEnv, parsed, options);
return { parsed };
}
function configDotenv(options) {
const dotenvPath = path.resolve(process.cwd(), ".env");
let encoding = "utf8";
const debug12 = Boolean(options && options.debug);
if (options && options.encoding) {
encoding = options.encoding;
} else {
if (debug12) {
_debug("No encoding is specified. UTF-8 is used by default");
}
}
let optionPaths = [dotenvPath];
if (options && options.path) {
if (!Array.isArray(options.path)) {
optionPaths = [_resolveHome(options.path)];
} else {
optionPaths = [];
for (const filepath of options.path) {
optionPaths.push(_resolveHome(filepath));
}
}
}
let lastError;
const parsedAll = {};
for (const path2 of optionPaths) {
try {
const parsed = DotenvModule.parse(fs.readFileSync(path2, { encoding }));
DotenvModule.populate(parsedAll, parsed, options);
} catch (e) {
if (debug12) {
_debug(`Failed to load ${path2} ${e.message}`);
}
lastError = e;
}
}
let processEnv = process.env;
if (options && options.processEnv != null) {
processEnv = options.processEnv;
}
DotenvModule.populate(processEnv, parsedAll, options);
if (lastError) {
return { parsed: parsedAll, error: lastError };
} else {
return { parsed: parsedAll };
}
}
function config(options) {
if (_dotenvKey(options).length === 0) {
return DotenvModule.configDotenv(options);
}
const vaultPath = _vaultPath(options);
if (!vaultPath) {
_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
return DotenvModule.configDotenv(options);
}
return DotenvModule._configVault(options);
}
function decrypt(encrypted, keyStr) {
const key = Buffer.from(keyStr.slice(-64), "hex");
let ciphertext = Buffer.from(encrypted, "base64");
const nonce = ciphertext.subarray(0, 12);
const authTag = ciphertext.subarray(-16);
ciphertext = ciphertext.subarray(12, -16);
try {
const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
aesgcm.setAuthTag(authTag);
return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
} catch (error) {
const isRange = error instanceof RangeError;
const invalidKeyLength = error.message === "Invalid key length";
const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
if (isRange || invalidKeyLength) {
const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
err.code = "INVALID_DOTENV_KEY";
throw err;
} else if (decryptionFailed) {
const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
err.code = "DECRYPTION_FAILED";
throw err;
} else {
throw error;
}
}
}
function populate(processEnv, parsed, options = {}) {
const debug12 = Boolean(options && options.debug);
const override = Boolean(options && options.override);
if (typeof parsed !== "object") {
const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
err.code = "OBJECT_REQUIRED";
throw err;
}
for (const key of Object.keys(parsed)) {
if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
if (override === true) {
processEnv[key] = parsed[key];
}
if (debug12) {
if (override === true) {
_debug(`"${key}" is already defined and WAS overwritten`);
} else {
_debug(`"${key}" is already defined and was NOT overwritten`);
}
}
} else {
processEnv[key] = parsed[key];
}
}
}
var DotenvModule = {
configDotenv,
_configVault,
_parseVault,
config,
decrypt,
parse: parse5,
populate
};
module2.exports.configDotenv = DotenvModule.configDotenv;
module2.exports._configVault = DotenvModule._configVault;
module2.exports._parseVault = DotenvModule._parseVault;
module2.exports.config = DotenvModule.config;
module2.exports.decrypt = DotenvModule.decrypt;
module2.exports.parse = DotenvModule.parse;
module2.exports.populate = DotenvModule.populate;
module2.exports = DotenvModule;
}
});
// node_modules/markdown-to-unicode/src/partials/bold.js
var require_bold = __commonJS({
"node_modules/markdown-to-unicode/src/partials/bold.js"(exports2, module2) {
"use strict";
function convertBoldToUnicode(markdownLine) {
let unicodeLine = markdownLine;
let boldRegex = /(\*\*|__)(.*?)\1/g;
unicodeLine = unicodeLine.replace(boldRegex, (match, p1, p2) => {
let unicodeCharacters = p2.split("").map((character) => {
return convertCharToBoldUnicode(character);
});
return unicodeCharacters.join("");
});
return unicodeLine;
}
function convertCharToBoldUnicode(char) {
const codePoint = char.codePointAt(0);
if (codePoint >= 65 && codePoint <= 90) {
return String.fromCodePoint(codePoint - 65 + 119808);
} else if (codePoint >= 97 && codePoint <= 122) {
return String.fromCodePoint(codePoint - 97 + 119834);
} else if (codePoint >= 48 && codePoint <= 57) {
return String.fromCodePoint(codePoint - 48 + 120782);
} else {
return char;
}
}
module2.exports = convertBoldToUnicode;
}
});
// node_modules/markdown-to-unicode/src/partials/italic.js
var require_italic = __commonJS({
"node_modules/markdown-to-unicode/src/partials/italic.js"(exports2, module2) {
"use strict";
function convertItalicToUnicode(markdownLine) {
let unicodeLine = markdownLine;
let italicRegex = /(\*|_)(.*?)\1/g;
unicodeLine = unicodeLine.replace(italicRegex, (match, p1, p2) => {
let unicodeCharacters = p2.split("").map((character) => {
return convertCharToItalicUnicode(character);
});
return unicodeCharacters.join("");
});
return unicodeLine;
}
function convertCharToItalicUnicode(char) {
const codePoint = char.codePointAt(0);
if (codePoint >= 65 && codePoint <= 90) {
return String.fromCodePoint(codePoint - 65 + 119860);
} else if (codePoint >= 97 && codePoint <= 122) {
return String.fromCodePoint(codePoint - 97 + 119886);
} else {
return char;
}
}
module2.exports = convertItalicToUnicode;
}
});
// node_modules/markdown-to-unicode/src/partials/strikethrough.js
var require_strikethrough = __commonJS({
"node_modules/markdown-to-unicode/src/partials/strikethrough.js"(exports2, module2) {
"use strict";
function convertStrikethroughToUnicode(markdownLine) {
let unicodeLine = markdownLine;
let strikethroughRegex = /~~(.*?)~~/g;
unicodeLine = unicodeLine.replace(strikethroughRegex, (match, p1) => {
let unicodeCharacters = p1.split("").map((character) => {
return convertCharToStrikethroughUnicode(character);
});
return unicodeCharacters.join("");
});
return unicodeLine;
}
function convertCharToStrikethroughUnicode(char) {
const strikeThroughChar = "\u0336";
return char + strikeThroughChar;
}
module2.exports = convertStrikethroughToUnicode;
}
});
// node_modules/markdown-to-unicode/src/index.js
var require_src2 = __commonJS({
"node_modules/markdown-to-unicode/src/index.js"(exports2, module2) {
"use strict";
var convertBoldToUnicode = require_bold();
var convertItalicToUnicode = require_italic();
var convertStrikethroughToUnicode = require_strikethrough();
function convertMarkdownToUnicode2(markdownText) {
let getLineByLine = markdownText.split("\n");
let unicodeLineByLine = getLineByLine.map((line) => convertMarkdownLineToUnicode(line));
let unicodeText = unicodeLineByLine.join("\n");
return unicodeText;
}
function convertMarkdownLineToUnicode(markdownLine) {
let unicodeLine = markdownLine;
unicodeLine = convertBoldToUnicode(unicodeLine);
unicodeLine = convertItalicToUnicode(unicodeLine);
unicodeLine = convertStrikethroughToUnicode(unicodeLine);
return unicodeLine;
}
module2.exports = convertMarkdownToUnicode2;
}
});
// src/util/autorestart.ts
function startAutorestart() {
setTimeout(() => {
process.exit();
}, 12 * 60 * 60 * 1e3);
}
// src/util/config.ts
var import_node_fs = require("node:fs");
var YAML = __toESM(require_dist());
var import_posix = require("node:path/posix");
function loadConfig(path, defaultConfig) {
const parsed = (0, import_posix.parse)(path);
const dir = parsed.dir;
if (!(0, import_node_fs.existsSync)(dir)) {
(0, import_node_fs.mkdirSync)(dir);
}
if ((0, import_node_fs.existsSync)(path)) {
const yaml = (0, import_node_fs.readFileSync)(path).toString();
const data = YAML.parse(yaml);
return data;
} else {
saveConfig(path, defaultConfig);
return defaultConfig;
}
}
function saveConfig(path, config) {
(0, import_node_fs.writeFileSync)(path, YAML.stringify(config));
}
// src/util/time.ts
function getTime(t = Date.now(), twelveHour = true) {
const now = t;
const s = now / 1e3;
const m = s / 60;
const h = m / 60;
const hours = Math.floor(h % (twelveHour ? 12 : 24)).toString().padStart(2, "0");
const minutes = Math.floor(m % 60).toString().padStart(2, "0");
const seconds = Math.floor(s % 60).toString().padStart(2, "0");
const milliseconds = Math.floor(now % 1e3).toString().padStart(3, "0");
return {
hours,
minutes,
seconds,
milliseconds
};
}
function getHHMMSS(t = Date.now(), twelveHour = true) {
const { hours, minutes, seconds, milliseconds } = getTime(t, twelveHour);
return `${hours}:${minutes}:${seconds}.${milliseconds}`;
}
// src/util/Logger.ts
var Logger = class _Logger {
constructor(id) {
this.id = id;
}
static log(...args) {
const time = getHHMMSS();
if (typeof globalThis.rl !== "undefined") {
process.stdout.write("\x1B[2K\r");
}
console.log(`\x1B[30m${time}\x1B[0m`, ...args);
if (typeof globalThis.rl !== "undefined") {
try {
globalThis.rl.prompt();
} catch (err) {
}
}
}
info(...args) {
_Logger.log(
`\x1B[34m[${this.id}]\x1B[0m`,
`\x1B[34m[INFO]\x1B[0m`,
...args
);
}
error(...args) {
_Logger.log(
`\x1B[34m[${this.id}]\x1B[0m`,
`\x1B[31m[ERROR]\x1B[0m`,
...args
);
}
warn(...args) {
_Logger.log(
`\x1B[34m[${this.id}]\x1B[0m`,
`\x1B[33m[WARNING]\x1B[0m`,
...args
);
}
debug(...args) {
_Logger.log(
`\x1B[34m[${this.id}]\x1B[0m`,
`\x1B[32m[DEBUG]\x1B[0m`,
...args
);
}
};
// node_modules/engine.io-client/build/esm-debug/transports/polling-xhr.node.js
var XMLHttpRequestModule = __toESM(require_XMLHttpRequest(), 1);
// node_modules/engine.io-parser/build/esm/commons.js
var PACKET_TYPES = /* @__PURE__ */ Object.create(null);
PACKET_TYPES["open"] = "0";
PACKET_TYPES["close"] = "1";
PACKET_TYPES["ping"] = "2";
PACKET_TYPES["pong"] = "3";
PACKET_TYPES["message"] = "4";
PACKET_TYPES["upgrade"] = "5";
PACKET_TYPES["noop"] = "6";
var PACKET_TYPES_REVERSE = /* @__PURE__ */ Object.create(null);
Object.keys(PACKET_TYPES).forEach((key) => {
PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
});
var ERROR_PACKET = { type: "error", data: "parser error" };
// node_modules/engine.io-parser/build/esm/encodePacket.js
var encodePacket = ({ type, data }, supportsBinary, callback) => {
if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
return callback(supportsBinary ? data : "b" + toBuffer(data, true).toString("base64"));
}
return callback(PACKET_TYPES[type] + (data || ""));
};
var toBuffer = (data, forceBufferConversion) => {
if (Buffer.isBuffer(data) || data instanceof Uint8Array && !forceBufferConversion) {
return data;
} else if (data instanceof ArrayBuffer) {
return Buffer.from(data);
} else {
return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
}
};
var TEXT_ENCODER;
function encodePacketToBinary(packet, callback) {
if (packet.data instanceof ArrayBuffer || ArrayBuffer.isView(packet.data)) {
return callback(toBuffer(packet.data, false));
}
encodePacket(packet, true, (encoded) => {
if (!TEXT_ENCODER) {
TEXT_ENCODER = new TextEncoder();
}
callback(TEXT_ENCODER.encode(encoded));
});
}
// node_modules/engine.io-parser/build/esm/decodePacket.js
var decodePacket = (encodedPacket, binaryType) => {
if (typeof encodedPacket !== "string") {
return {
type: "message",
data: mapBinary(encodedPacket, binaryType)
};
}
const type = encodedPacket.charAt(0);
if (type === "b") {
const buffer = Buffer.from(encodedPacket.substring(1), "base64");
return {
type: "message",
data: mapBinary(buffer, binaryType)
};
}
if (!PACKET_TYPES_REVERSE[type]) {
return ERROR_PACKET;
}
return encodedPacket.length > 1 ? {
type: PACKET_TYPES_REVERSE[type],
data: encodedPacket.substring(1)
} : {
type: PACKET_TYPES_REVERSE[type]
};
};
var mapBinary = (data, binaryType) => {
switch (binaryType) {
case "arraybuffer":
if (data instanceof ArrayBuffer) {
return data;
} else if (Buffer.isBuffer(data)) {
return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
} else {
return data.buffer;
}
case "nodebuffer":
default:
if (Buffer.isBuffer(data)) {
return data;
} else {
return Buffer.from(data);
}
}
};
// 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, i) => {
encodePacket(packet, false, (encodedPacket) => {
encodedPackets[i] = encodedPacket;
if (++count === length) {
callback(encodedPackets.join(SEPARATOR));
}
});
});
};
var decodePayload = (encodedPayload, binaryType) => {
const encodedPackets = encodedPayload.split(SEPARATOR);
const packets = [];
for (let i = 0; i < encodedPackets.length; i++) {
const decodedPacket = decodePacket(encodedPackets[i], 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") {
header[0] |= 128;
}
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 (chunks[0].length === size) {
return chunks.shift();
}
const buffer = new Uint8Array(size);
let j = 0;
for (let i = 0; i < size; i++) {
buffer[i] = chunks[0][j++];
if (j === chunks[0].length) {
chunks.shift();
j = 0;
}
}
if (chunks.length && j < chunks[0].length) {
chunks[0] = chunks[0].slice(j);
}
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 = (header[0] & 128) === 128;
expectedLength = header[0] & 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 n = view.getUint32(0);
if (n > Math.pow(2, 53 - 32) - 1) {
controller.enqueue(ERROR_PACKET);
break;
}
expectedLength = n * 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;
// node_modules/engine.io-client/build/esm-debug/transport.js
var import_component_emitter = __toESM(require_cjs(), 1);
// node_modules/engine.io-client/build/esm-debug/globals.node.js
var nextTick = process.nextTick;
var globalThisShim = global;
var defaultBinaryType = "nodebuffer";
function createCookieJar() {
return new CookieJar();
}
function parse3(setCookieString) {
const parts2 = setCookieString.split("; ");
const i = parts2[0].indexOf("=");
if (i === -1) {
return;
}
const name = parts2[0].substring(0, i).trim();
if (!name.length) {
return;
}
let value2 = parts2[0].substring(i + 1).trim();
if (value2.charCodeAt(0) === 34) {
value2 = value2.slice(1, -1);
}
const cookie = {
name,
value: value2
};
for (let j = 1; j < parts2.length; j++) {
const subParts = parts2[j].split("=");
if (subParts.length !== 2) {
continue;
}
const key = subParts[0].trim();
const value3 = subParts[1].trim();
switch (key) {
case "Expires":
cookie.expires = new Date(value3);
break;
case "Max-Age":
const expiration = /* @__PURE__ */ new Date();
expiration.setUTCSeconds(expiration.getUTCSeconds() + parseInt(value3, 10));
cookie.expires = expiration;
break;
default:
}
}
return cookie;
}
var CookieJar = class {
constructor() {
this._cookies = /* @__PURE__ */ new Map();
}
parseCookies(values) {
if (!values) {
return;
}
values.forEach((value2) => {
const parsed = parse3(value2);
if (parsed) {
this._cookies.set(parsed.name, parsed);
}
});
}
get cookies() {
const now = Date.now();
this._cookies.forEach((cookie, name) => {
var _a;
if (((_a = cookie.expires) === null || _a === void 0 ? void 0 : _a.getTime()) < now) {
this._cookies.delete(name);
}
});
return this._cookies.entries();
}
addCookies(xhr) {
const cookies = [];
for (const [name, cookie] of this.cookies) {
cookies.push(`${name}=${cookie.value}`);
}
if (cookies.length) {
xhr.setDisableHeaderCheck(true);
xhr.setRequestHeader("cookie", cookies.join("; "));
}
}
appendCookies(headers) {
for (const [name, cookie] of this.cookies) {
headers.append("cookie", `${name}=${cookie.value}`);
}
}
};
// node_modules/engine.io-client/build/esm-debug/util.js
function pick(obj, ...attr) {
return attr.reduce((acc, k) => {
if (obj.hasOwnProperty(k)) {
acc[k] = obj[k];
}
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 c = 0, length = 0;
for (let i = 0, l = str.length; i < l; i++) {
c = str.charCodeAt(i);
if (c < 128) {
length += 1;
} else if (c < 2048) {
length += 2;
} else if (c < 55296 || c >= 57344) {
length += 3;
} else {
i++;
length += 4;
}
}
return length;
}
function randomString() {
return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
}
// node_modules/engine.io-client/build/esm-debug/contrib/parseqs.js
function encode(obj) {
let str = "";
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
if (str.length)
str += "&";
str += encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]);
}
}
return str;
}
function decode(qs) {
let qry = {};
let pairs = qs.split("&");
for (let i = 0, l = pairs.length; i < l; i++) {
let pair = pairs[i].split("=");
qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return qry;
}
// node_modules/engine.io-client/build/esm-debug/transport.js
var import_debug = __toESM(require_src(), 1);
var debug = (0, import_debug.default)("engine.io-client:transport");
var TransportError = class extends Error {
constructor(reason, description, context) {
super(reason);
this.description = description;
this.context = context;
this.type = "TransportError";
}
};
var Transport = class extends import_component_emitter.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 {
debug("transport is not open, discarding packets");
}
}
/**
* 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 : "";
}
};
// node_modules/engine.io-client/build/esm-debug/transports/polling.js
var import_debug2 = __toESM(require_src(), 1);
var debug2 = (0, import_debug2.default)("engine.io-client:polling");
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 = () => {
debug2("paused");
this.readyState = "paused";
onPause();
};
if (this._polling || !this.writable) {
let total = 0;
if (this._polling) {
debug2("we are currently polling - waiting to pause");
total++;
this.once("pollComplete", function() {
debug2("pre-pause polling complete");
--total || pause();
});
}
if (!this.writable) {
debug2("we are currently writing - waiting to pause");
total++;
this.once("drain", function() {
debug2("pre-pause writing complete");
--total || pause();
});
}
} else {
pause();
}
}
/**
* Starts polling cycle.
*
* @private
*/
_poll() {
debug2("polling");
this._polling = true;
this.doPoll();
this.emitReserved("poll");
}
/**
* Overloads onData to detect payloads.
*
* @protected
*/
onData(data) {
debug2("polling got data %s", 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 {
debug2('ignoring poll - transport state "%s"', this.readyState);
}
}
}
/**
* For polling, send a close packet.
*
* @protected
*/
doClose() {
const close = () => {
debug2("writing close packet");
this.write([{ type: "close" }]);
};
if ("open" === this.readyState) {
debug2("transport open - closing");
close();
} else {
debug2("transport not open - deferring close");
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) {
query[this.opts.timestampParam] = randomString();
}
if (!this.supportsBinary && !query.sid) {
query.b64 = 1;
}
return this.createUri(schema, query);
}
};
// node_modules/engine.io-client/build/esm-debug/transports/polling-xhr.js
var import_component_emitter2 = __toESM(require_cjs(), 1);
// node_modules/engine.io-client/build/esm-debug/contrib/has-cors.js
var value = false;
try {
value = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest();
} catch (err) {
}
var hasCORS = value;
// node_modules/engine.io-client/build/esm-debug/transports/polling-xhr.js
var import_debug3 = __toESM(require_src(), 1);
var debug3 = (0, import_debug3.default)("engine.io-client:polling");
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() {
debug3("xhr poll");
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 Request = class _Request extends import_component_emitter2.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 {
debug3("xhr open %s: %s", this._method, this._uri);
xhr.open(this._method, this._uri, true);
try {
if (this._opts.extraHeaders) {
xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
for (let i in this._opts.extraHeaders) {
if (this._opts.extraHeaders.hasOwnProperty(i)) {
xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
}
}
}
} catch (e) {
}
if ("POST" === this._method) {
try {
xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
} catch (e) {
}
}
try {
xhr.setRequestHeader("Accept", "*/*");
} catch (e) {
}
(_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);
}
};
debug3("xhr data %s", this._data);
xhr.send(this._data);
} catch (e) {
this.setTimeoutFn(() => {
this._onError(e);
}, 0);
return;
}
if (typeof document !== "undefined") {
this._index = _Request.requestsCount++;
_Request.requests[this._index] = this;
}
}
/**
* 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 (e) {
}
}
if (typeof document !== "undefined") {
delete _Request.requests[this._index];
}
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();
}
};
Request.requestsCount = 0;
Request.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 i in Request.requests) {
if (Request.requests.hasOwnProperty(i)) {
Request.requests[i].abort();
}
}
}
var hasXHR2 = function() {
const xhr = newRequest({
xdomain: false
});
return xhr && xhr.responseType !== null;
}();
function newRequest(opts) {
const xdomain = opts.xdomain;
try {
if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
return new XMLHttpRequest();
}
} catch (e) {
}
if (!xdomain) {
try {
return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
// node_modules/engine.io-client/build/esm-debug/transports/polling-xhr.node.js
var XMLHttpRequest2 = XMLHttpRequestModule.default || XMLHttpRequestModule;
var XHR = class extends BaseXHR {
request(opts = {}) {
var _a;
Object.assign(opts, { xd: this.xd, cookieJar: (_a = this.socket) === null || _a === void 0 ? void 0 : _a._cookieJar }, this.opts);
return new Request((opts2) => new XMLHttpRequest2(opts2), this.uri(), opts);
}
};
// node_modules/engine.io-client/node_modules/ws/wrapper.mjs
var import_stream = __toESM(require_stream(), 1);
var import_receiver = __toESM(require_receiver(), 1);
var import_sender = __toESM(require_sender(), 1);
var import_websocket = __toESM(require_websocket(), 1);
var import_websocket_server = __toESM(require_websocket_server(), 1);
// node_modules/engine.io-client/build/esm-debug/transports/websocket.js
var import_debug4 = __toESM(require_src(), 1);
var debug4 = (0, import_debug4.default)("engine.io-client:websocket");
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 = (e) => this.onError("websocket error", e);
}
write(packets) {
this.writable = false;
for (let i = 0; i < packets.length; i++) {
const packet = packets[i];
const lastPacket = i === packets.length - 1;
encodePacket(packet, this.supportsBinary, (data) => {
try {
this.doWrite(packet, data);
} catch (e) {
debug4("websocket closed before onclose event");
}
if (lastPacket) {
nextTick(() => {
this.writable = true;
this.emitReserved("drain");
}, this.setTimeoutFn);
}
});
}
}
doClose() {
if (typeof this.ws !== "undefined") {
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) {
query[this.opts.timestampParam] = randomString();
}
if (!this.supportsBinary) {
query.b64 = 1;
}
return this.createUri(schema, query);
}
};
var WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
// node_modules/engine.io-client/build/esm-debug/transports/websocket.node.js
var WS = class extends BaseWS {
createSocket(uri, protocols, opts) {
var _a;
if ((_a = this.socket) === null || _a === void 0 ? void 0 : _a._cookieJar) {
opts.headers = opts.headers || {};
opts.headers.cookie = typeof opts.headers.cookie === "string" ? [opts.headers.cookie] : opts.headers.cookie || [];
for (const [name, cookie] of this.socket._cookieJar.cookies) {
opts.headers.cookie.push(`${name}=${cookie.value}`);
}
}
return new import_websocket.default(uri, protocols, opts);
}
doWrite(packet, data) {
const opts = {};
if (packet.options) {
opts.compress = packet.options.compress;
}
if (this.opts.perMessageDeflate) {
const len = (
// @ts-ignore
"string" === typeof data ? Buffer.byteLength(data) : data.length
);
if (len < this.opts.perMessageDeflate.threshold) {
opts.compress = false;
}
}
this.ws.send(data, opts);
}
};
// node_modules/engine.io-client/build/esm-debug/transports/webtransport.js
var import_debug5 = __toESM(require_src(), 1);
var debug5 = (0, import_debug5.default)("engine.io-client:webtransport");
var WT = class extends Transport {
get name() {
return "webtransport";
}
doOpen() {
try {
this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
} catch (err) {
return this.emitReserved("error", err);
}
this._transport.closed.then(() => {
debug5("transport closed gracefully");
this.onClose();
}).catch((err) => {
debug5("transport closed due to %s", 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) {
debug5("session is closed");
return;
}
debug5("received chunk: %o", value2);
this.onPacket(value2);
read();
}).catch((err) => {
debug5("an error occurred while reading: %s", 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 i = 0; i < packets.length; i++) {
const packet = packets[i];
const lastPacket = i === 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();
}
};
// node_modules/engine.io-client/build/esm-debug/transports/index.js
var transports = {
websocket: WS,
webtransport: WT,
polling: XHR
};
// node_modules/engine.io-client/build/esm-debug/contrib/parseuri.js
var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
var parts = [
"source",
"protocol",
"authority",
"userInfo",
"user",
"password",
"host",
"port",
"relative",
"path",
"directory",
"file",
"query",
"anchor"
];
function parse4(str) {
if (str.length > 8e3) {
throw "URI too long";
}
const src = str, b = str.indexOf("["), e = str.indexOf("]");
if (b != -1 && e != -1) {
str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ";") + str.substring(e, str.length);
}
let m = re.exec(str || ""), uri = {}, i = 14;
while (i--) {
uri[parts[i]] = m[i] || "";
}
if (b != -1 && e != -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) {
data[$1] = $2;
}
});
return data;
}
// node_modules/engine.io-client/build/esm-debug/socket.js
var import_component_emitter3 = __toESM(require_cjs(), 1);
var import_debug6 = __toESM(require_src(), 1);
var debug6 = (0, import_debug6.default)("engine.io-client:socket");
var withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
var OFFLINE_EVENT_LISTENERS = [];
if (withEventListeners) {
addEventListener("offline", () => {
debug6("closing %d connection(s) because the network was lost", OFFLINE_EVENT_LISTENERS.length);
OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
}, false);
}
var SocketWithoutUpgrade = class _SocketWithoutUpgrade extends import_component_emitter3.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 = parse4(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 = parse4(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((t) => {
const transportName = t.prototype.name;
this.transports.push(transportName);
this._transportsByName[transportName] = t;
});
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 = decode(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") {
debug6("adding listener for the 'offline' event");
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) {
debug6('creating transport "%s"', 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.transportOptions[name]);
debug6("options: %j", opts);
return new this._transportsByName[name](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.transports[0];
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) {
debug6("setting transport %s", transport.name);
if (this.transport) {
debug6("clearing existing transport %s", this.transport.name);
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() {
debug6("socket open");
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) {
debug6('socket receive: type "%s", data "%s"', packet.type, packet.data);
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 {
debug6('packet received with socket readyState "%s"', this.readyState);
}
}
/**
* 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 delay = this._pingInterval + this._pingTimeout;
this._pingTimeoutTime = Date.now() + delay;
this._pingTimeoutTimer = this.setTimeoutFn(() => {
this._onClose("ping timeout");
}, delay);
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();
debug6("flushing %d packets in socket", packets.length);
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 i = 0; i < this.writeBuffer.length; i++) {
const data = this.writeBuffer[i].data;
if (data) {
payloadSize += byteLength(data);
}
if (i > 0 && payloadSize > this._maxPayload) {
debug6("only send %d out of %d packets", i, this.writeBuffer.length);
return this.writeBuffer.slice(0, i);
}
payloadSize += 2;
}
debug6("payload size is %d (max: %d)", payloadSize, this._maxPayload);
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) {
debug6("throttled timer detected, scheduling connection close");
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");
debug6("socket closing - telling transport to 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) {
debug6("socket error %j", err);
_SocketWithoutUpgrade.priorWebsocketSuccess = false;
if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
debug6("trying next transport");
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) {
debug6('socket close with reason: "%s"', reason);
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 i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
if (i !== -1) {
debug6("removing listener for the 'offline' event");
OFFLINE_EVENT_LISTENERS.splice(i, 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) {
debug6("starting upgrade probes");
for (let i = 0; i < this._upgrades.length; i++) {
this._probe(this._upgrades[i]);
}
}
}
/**
* Probes a transport.
*
* @param {String} name - transport name
* @private
*/
_probe(name) {
debug6('probing transport "%s"', name);
let transport = this.createTransport(name);
let failed = false;
SocketWithoutUpgrade.priorWebsocketSuccess = false;
const onTransportOpen = () => {
if (failed)
return;
debug6('probe transport "%s" opened', name);
transport.send([{ type: "ping", data: "probe" }]);
transport.once("packet", (msg) => {
if (failed)
return;
if ("pong" === msg.type && "probe" === msg.data) {
debug6('probe transport "%s" pong', name);
this.upgrading = true;
this.emitReserved("upgrading", transport);
if (!transport)
return;
SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
debug6('pausing current transport "%s"', this.transport.name);
this.transport.pause(() => {
if (failed)
return;
if ("closed" === this.readyState)
return;
debug6("changing transport and sending upgrade packet");
cleanup();
this.setTransport(transport);
transport.send([{ type: "upgrade" }]);
this.emitReserved("upgrade", transport);
transport = null;
this.upgrading = false;
this.flush();
});
} else {
debug6('probe transport "%s" failed', name);
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();
debug6('probe transport "%s" failed because of error: %s', name, err);
this.emitReserved("upgradeError", error);
};
function onTransportClose() {
onerror("transport closed");
}
function onclose() {
onerror("socket closed");
}
function onupgrade(to) {
if (transport && to.name !== transport.name) {
debug6('"%s" works - aborting "%s"', 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 i = 0; i < upgrades.length; i++) {
if (~this.transports.indexOf(upgrades[i]))
filteredUpgrades.push(upgrades[i]);
}
return filteredUpgrades;
}
};
var Socket = class extends SocketWithUpgrade {
constructor(uri, opts = {}) {
const o = typeof uri === "object" ? uri : opts;
if (!o.transports || o.transports && typeof o.transports[0] === "string") {
o.transports = (o.transports || ["polling", "websocket", "webtransport"]).map((transportName) => transports[transportName]).filter((t) => !!t);
}
super(uri, o);
}
};
// node_modules/engine.io-client/build/esm-debug/index.js
var protocol2 = Socket.protocol;
// node_modules/socket.io-client/build/esm-debug/url.js
var import_debug7 = __toESM(require_src(), 1);
var debug7 = (0, import_debug7.default)("socket.io-client:url");
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)) {
debug7("protocol-less url %s", uri);
if ("undefined" !== typeof loc) {
uri = loc.protocol + "//" + uri;
} else {
uri = "https://" + uri;
}
}
debug7("parse %s", uri);
obj = parse4(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;
}
// node_modules/socket.io-parser/build/esm-debug/index.js
var esm_debug_exports = {};
__export(esm_debug_exports, {
Decoder: () => Decoder,
Encoder: () => Encoder,
PacketType: () => PacketType,
protocol: () => protocol3
});
var import_component_emitter4 = __toESM(require_cjs(), 1);
// node_modules/socket.io-parser/build/esm-debug/is-binary.js
var withNativeArrayBuffer = typeof ArrayBuffer === "function";
var isView = (obj) => {
return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
};
var toString = Object.prototype.toString;
var withNativeBlob = 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 withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File;
}
function hasBinary(obj, toJSON) {
if (!obj || typeof obj !== "object") {
return false;
}
if (Array.isArray(obj)) {
for (let i = 0, l = obj.length; i < l; i++) {
if (hasBinary(obj[i])) {
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(obj[key])) {
return true;
}
}
return false;
}
// node_modules/socket.io-parser/build/esm-debug/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 i = 0; i < data.length; i++) {
newData[i] = _deconstructPacket(data[i], 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)) {
newData[key] = _deconstructPacket(data[key], 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) {
return buffers[data.num];
} else {
throw new Error("illegal attachments");
}
} else if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
data[i] = _reconstructPacket(data[i], buffers);
}
} else if (typeof data === "object") {
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
data[key] = _reconstructPacket(data[key], buffers);
}
}
}
return data;
}
// node_modules/socket.io-parser/build/esm-debug/index.js
var import_debug8 = __toESM(require_src(), 1);
var debug8 = (0, import_debug8.default)("socket.io-parser");
var RESERVED_EVENTS = [
"connect",
"connect_error",
"disconnect",
"disconnecting",
"newListener",
"removeListener"
// used by the Node.js EventEmitter
];
var protocol3 = 5;
var PacketType;
(function(PacketType2) {
PacketType2[PacketType2["CONNECT"] = 0] = "CONNECT";
PacketType2[PacketType2["DISCONNECT"] = 1] = "DISCONNECT";
PacketType2[PacketType2["EVENT"] = 2] = "EVENT";
PacketType2[PacketType2["ACK"] = 3] = "ACK";
PacketType2[PacketType2["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
PacketType2[PacketType2["BINARY_EVENT"] = 5] = "BINARY_EVENT";
PacketType2[PacketType2["BINARY_ACK"] = 6] = "BINARY_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) {
debug8("encoding packet %j", 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
});
}
}
return [this.encodeAsString(obj)];
}
/**
* 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);
}
debug8("encoded %j as %s", obj, str);
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;
}
};
function isObject(value2) {
return Object.prototype.toString.call(value2) === "[object Object]";
}
var Decoder = class _Decoder extends import_component_emitter4.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 i = 0;
const p = {
type: Number(str.charAt(0))
};
if (PacketType[p.type] === void 0) {
throw new Error("unknown packet type " + p.type);
}
if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
const start = i + 1;
while (str.charAt(++i) !== "-" && i != str.length) {
}
const buf = str.substring(start, i);
if (buf != Number(buf) || str.charAt(i) !== "-") {
throw new Error("Illegal attachments");
}
p.attachments = Number(buf);
}
if ("/" === str.charAt(i + 1)) {
const start = i + 1;
while (++i) {
const c = str.charAt(i);
if ("," === c)
break;
if (i === str.length)
break;
}
p.nsp = str.substring(start, i);
} else {
p.nsp = "/";
}
const next = str.charAt(i + 1);
if ("" !== next && Number(next) == next) {
const start = i + 1;
while (++i) {
const c = str.charAt(i);
if (null == c || Number(c) != c) {
--i;
break;
}
if (i === str.length)
break;
}
p.id = Number(str.substring(start, i + 1));
}
if (str.charAt(++i)) {
const payload = this.tryParse(str.substr(i));
if (_Decoder.isPayloadValid(p.type, payload)) {
p.data = payload;
} else {
throw new Error("invalid payload");
}
}
debug8("decoded %s as %j", str, p);
return p;
}
tryParse(str) {
try {
return JSON.parse(str, this.reviver);
} catch (e) {
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 payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS.indexOf(payload[0]) === -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 = [];
}
};
// node_modules/socket.io-client/build/esm-debug/on.js
function on(obj, ev, fn) {
obj.on(ev, fn);
return function subDestroy() {
obj.off(ev, fn);
};
}
// node_modules/socket.io-client/build/esm-debug/socket.js
var import_component_emitter5 = __toESM(require_cjs(), 1);
var import_debug9 = __toESM(require_src(), 1);
var debug9 = (0, import_debug9.default)("socket.io-client:socket");
var RESERVED_EVENTS2 = Object.freeze({
connect: 1,
connect_error: 1,
disconnect: 1,
disconnecting: 1,
// EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
newListener: 1,
removeListener: 1
});
var Socket2 = class extends import_component_emitter5.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();
if (!this.io["_reconnecting"])
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.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
*
* @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;
if ("function" === typeof args[args.length - 1]) {
const id = this.ids++;
debug9("emitting packet with ack id %d", id);
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) {
debug9("discard packet as the transport is not currently writable");
} 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) {
this.acks[id] = ack;
return;
}
const timer = this.io.setTimeoutFn(() => {
delete this.acks[id];
for (let i = 0; i < this.sendBuffer.length; i++) {
if (this.sendBuffer[i].id === id) {
debug9("removing packet with ack id %d from the buffer", id);
this.sendBuffer.splice(i, 1);
}
}
debug9("event with ack id %d has timed out after %d ms", id, timeout);
ack.call(this, new Error("operation has timed out"));
}, timeout);
const fn = (...args) => {
this.io.clearTimeoutFn(timer);
ack.apply(this, args);
};
fn.withError = true;
this.acks[id] = fn;
}
/**
* 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;
if (typeof args[args.length - 1] === "function") {
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._queue[0]) {
return;
}
const hasError = err !== null;
if (hasError) {
if (packet.tryCount > this._opts.retries) {
debug9("packet [%d] is discarded after %d tries", packet.id, packet.tryCount);
this._queue.shift();
if (ack) {
ack(err);
}
}
} else {
debug9("packet [%d] was successfully sent", packet.id);
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) {
debug9("draining queue");
if (!this.connected || this._queue.length === 0) {
return;
}
const packet = this._queue[0];
if (packet.pending && !force) {
debug9("packet [%d] has already been sent and is waiting for an ack", packet.id);
return;
}
packet.pending = true;
packet.tryCount++;
debug9("sending packet [%d] (try n\xB0%d)", packet.id, 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() {
debug9("transport is open - connecting");
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) {
debug9("close (%s)", reason);
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) {
const ack = this.acks[id];
delete this.acks[id];
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 {
this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
}
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 || [];
debug9("emitting event %j", args);
if (null != packet.id) {
debug9("attaching ack callback to event");
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);
if (this._pid && args.length && typeof args[args.length - 1] === "string") {
this._lastOffset = args[args.length - 1];
}
}
/**
* Produces an ack callback to emit with an event.
*
* @private
*/
ack(id) {
const self = this;
let sent = false;
return function(...args) {
if (sent)
return;
sent = true;
debug9("sending ack %j", args);
self.packet({
type: PacketType.ACK,
id,
data: args
});
};
}
/**
* Called upon a server acknowledgement.
*
* @param packet
* @private
*/
onack(packet) {
const ack = this.acks[packet.id];
if (typeof ack !== "function") {
debug9("bad ack %s", packet.id);
return;
}
delete this.acks[packet.id];
debug9("calling ack %s with %j", packet.id, packet.data);
if (ack.withError) {
packet.data.unshift(null);
}
ack.apply(this, packet.data);
}
/**
* Called upon server connect.
*
* @private
*/
onconnect(id, pid) {
debug9("socket connected with id %s", id);
this.id = id;
this.recovered = pid && this._pid === pid;
this._pid = pid;
this.connected = true;
this.emitBuffered();
this.emitReserved("connect");
this._drainQueue(true);
}
/**
* 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() {
debug9("server disconnect (%s)", this.nsp);
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;
}
this.io["_destroy"](this);
}
/**
* 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) {
debug9("performing disconnect (%s)", this.nsp);
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 i = 0; i < listeners.length; i++) {
if (listener === listeners[i]) {
listeners.splice(i, 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 i = 0; i < listeners.length; i++) {
if (listener === listeners[i]) {
listeners.splice(i, 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);
}
}
}
};
// node_modules/socket.io-client/build/esm-debug/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;
};
// node_modules/socket.io-client/build/esm-debug/manager.js
var import_component_emitter6 = __toESM(require_cjs(), 1);
var import_debug10 = __toESM(require_src(), 1);
var debug10 = (0, import_debug10.default)("socket.io-client:manager");
var Manager = class extends import_component_emitter6.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_debug_exports;
this.encoder = new _parser.Encoder();
this.decoder = new _parser.Decoder();
this._autoConnect = opts.autoConnect !== false;
if (this._autoConnect)
this.open();
}
reconnection(v) {
if (!arguments.length)
return this._reconnection;
this._reconnection = !!v;
if (!v) {
this.skipReconnect = true;
}
return this;
}
reconnectionAttempts(v) {
if (v === void 0)
return this._reconnectionAttempts;
this._reconnectionAttempts = v;
return this;
}
reconnectionDelay(v) {
var _a;
if (v === void 0)
return this._reconnectionDelay;
this._reconnectionDelay = v;
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
return this;
}
randomizationFactor(v) {
var _a;
if (v === void 0)
return this._randomizationFactor;
this._randomizationFactor = v;
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
return this;
}
reconnectionDelayMax(v) {
var _a;
if (v === void 0)
return this._reconnectionDelayMax;
this._reconnectionDelayMax = v;
(_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
return this;
}
timeout(v) {
if (!arguments.length)
return this._timeout;
this._timeout = v;
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) {
debug10("readyState %s", this._readyState);
if (~this._readyState.indexOf("open"))
return this;
debug10("opening %s", this.uri);
this.engine = new Socket(this.uri, this.opts);
const socket = this.engine;
const self = this;
this._readyState = "opening";
this.skipReconnect = false;
const openSubDestroy = on(socket, "open", function() {
self.onopen();
fn && fn();
});
const onError = (err) => {
debug10("error");
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;
debug10("connect attempt will timeout after %d", timeout);
const timer = this.setTimeoutFn(() => {
debug10("connect attempt timed out after %d", timeout);
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() {
debug10("open");
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 (e) {
this.onclose("parse error", e);
}
}
/**
* Called when parser fully decodes a packet.
*
* @private
*/
ondecoded(packet) {
nextTick(() => {
this.emitReserved("packet", packet);
}, this.setTimeoutFn);
}
/**
* Called upon socket error.
*
* @private
*/
onerror(err) {
debug10("error", err);
this.emitReserved("error", err);
}
/**
* Creates a new socket for the given `nsp`.
*
* @return {Socket}
* @public
*/
socket(nsp, opts) {
let socket = this.nsps[nsp];
if (!socket) {
socket = new Socket2(this, nsp, opts);
this.nsps[nsp] = socket;
} 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.nsps[nsp];
if (socket2.active) {
debug10("socket %s is still active, skipping close", nsp);
return;
}
}
this._close();
}
/**
* Writes a packet.
*
* @param packet
* @private
*/
_packet(packet) {
debug10("writing packet %j", packet);
const encodedPackets = this.encoder.encode(packet);
for (let i = 0; i < encodedPackets.length; i++) {
this.engine.write(encodedPackets[i], packet.options);
}
}
/**
* Clean up transport subscriptions and packet buffer.
*
* @private
*/
cleanup() {
debug10("cleanup");
this.subs.forEach((subDestroy) => subDestroy());
this.subs.length = 0;
this.decoder.destroy();
}
/**
* Close the current socket.
*
* @private
*/
_close() {
debug10("disconnect");
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;
debug10("closed due to %s", reason);
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 self = this;
if (this.backoff.attempts >= this._reconnectionAttempts) {
debug10("reconnect failed");
this.backoff.reset();
this.emitReserved("reconnect_failed");
this._reconnecting = false;
} else {
const delay = this.backoff.duration();
debug10("will wait %dms before reconnect attempt", delay);
this._reconnecting = true;
const timer = this.setTimeoutFn(() => {
if (self.skipReconnect)
return;
debug10("attempting reconnect");
this.emitReserved("reconnect_attempt", self.backoff.attempts);
if (self.skipReconnect)
return;
self.open((err) => {
if (err) {
debug10("reconnect attempt error");
self._reconnecting = false;
self.reconnect();
this.emitReserved("reconnect_error", err);
} else {
debug10("reconnect success");
self.onreconnect();
}
});
}, delay);
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);
}
};
// node_modules/socket.io-client/build/esm-debug/index.js
var import_debug11 = __toESM(require_src(), 1);
var debug11 = (0, import_debug11.default)("socket.io-client");
var cache = {};
function lookup(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 = cache[id] && path in cache[id]["nsps"];
const newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
let io;
if (newConnection) {
debug11("ignoring socket cache for %s", source);
io = new Manager(source, opts);
} else {
if (!cache[id]) {
debug11("new io instance for %s", source);
cache[id] = new Manager(source, opts);
}
io = cache[id];
}
if (parsed.query && !opts.query) {
opts.query = parsed.queryKey;
}
return io.socket(parsed.path, opts);
}
Object.assign(lookup, {
Manager,
Socket: Socket2,
io: lookup,
connect: lookup
});
// src/talkomatic/bot/TalkomaticBot.ts
var import_node_events = require("node:events");
// node_modules/@trpc/server/dist/observable/observable.mjs
function observable(subscribe) {
const self = {
subscribe(observer) {
let teardownRef = null;
let isDone = false;
let unsubscribed = false;
let teardownImmediately = false;
function unsubscribe() {
if (teardownRef === null) {
teardownImmediately = true;
return;
}
if (unsubscribed) {
return;
}
unsubscribed = true;
if (typeof teardownRef === "function") {
teardownRef();
} else if (teardownRef) {
teardownRef.unsubscribe();
}
}
teardownRef = subscribe({
next(value2) {
if (isDone) {
return;
}
observer.next?.(value2);
},
error(err) {
if (isDone) {
return;
}
isDone = true;
observer.error?.(err);
unsubscribe();
},
complete() {
if (isDone) {
return;
}
isDone = true;
observer.complete?.();
unsubscribe();
}
});
if (teardownImmediately) {
unsubscribe();
}
return {
unsubscribe
};
},
pipe(...operations) {
return operations.reduce(pipeReducer, self);
}
};
return self;
}
function pipeReducer(prev, fn) {
return fn(prev);
}
function observableToPromise(observable2) {
const ac = new AbortController();
const promise = new Promise((resolve, reject) => {
let isDone = false;
function onDone() {
if (isDone) {
return;
}
isDone = true;
obs$.unsubscribe();
}
ac.signal.addEventListener("abort", () => {
reject(ac.signal.reason);
});
const obs$ = observable2.subscribe({
next(data) {
isDone = true;
resolve(data);
onDone();
},
error(data) {
reject(data);
},
complete() {
ac.abort();
onDone();
}
});
});
return promise;
}
// node_modules/@trpc/server/dist/observable/operators.mjs
function share(_opts) {
return (source) => {
let refCount = 0;
let subscription = null;
const observers = [];
function startIfNeeded() {
if (subscription) {
return;
}
subscription = source.subscribe({
next(value2) {
for (const observer of observers) {
observer.next?.(value2);
}
},
error(error) {
for (const observer of observers) {
observer.error?.(error);
}
},
complete() {
for (const observer of observers) {
observer.complete?.();
}
}
});
}
function resetIfNeeded() {
if (refCount === 0 && subscription) {
const _sub = subscription;
subscription = null;
_sub.unsubscribe();
}
}
return observable((subscriber) => {
refCount++;
observers.push(subscriber);
startIfNeeded();
return {
unsubscribe() {
refCount--;
resetIfNeeded();
const index = observers.findIndex((v) => v === subscriber);
if (index > -1) {
observers.splice(index, 1);
}
}
};
});
};
}
// node_modules/@trpc/client/dist/links/internals/createChain.mjs
function createChain(opts) {
return observable((observer) => {
function execute(index = 0, op = opts.op) {
const next = opts.links[index];
if (!next) {
throw new Error("No more links to execute - did you forget to add an ending link?");
}
const subscription = next({
op,
next(nextOp) {
const nextObserver = execute(index + 1, nextOp);
return nextObserver;
}
});
return subscription;
}
const obs$ = execute();
return obs$.subscribe(observer);
});
}
// node_modules/@trpc/server/dist/unstable-core-do-not-import/createProxy.mjs
var _memo;
var _cacheKey;
var noop = () => {
};
var freezeIfAvailable = (obj) => {
if (Object.freeze) {
Object.freeze(obj);
}
};
function createInnerProxy(callback, path, memo) {
const cacheKey = path.join(".");
(_memo = memo)[_cacheKey = cacheKey] ?? (_memo[_cacheKey] = new Proxy(noop, {
get(_obj, key) {
if (typeof key !== "string" || key === "then") {
return void 0;
}
return createInnerProxy(callback, [
...path,
key
], memo);
},
apply(_1, _2, args) {
const lastOfPath = path[path.length - 1];
let opts = {
args,
path
};
if (lastOfPath === "call") {
opts = {
args: args.length >= 2 ? [
args[1]
] : [],
path: path.slice(0, -1)
};
} else if (lastOfPath === "apply") {
opts = {
args: args.length >= 2 ? args[1] : [],
path: path.slice(0, -1)
};
}
freezeIfAvailable(opts.args);
freezeIfAvailable(opts.path);
return callback(opts);
}
}));
return memo[cacheKey];
}
var createRecursiveProxy = (callback) => createInnerProxy(callback, [], /* @__PURE__ */ Object.create(null));
var createFlatProxy = (callback) => {
return new Proxy(noop, {
get(_obj, name) {
if (typeof name !== "string" || name === "then") {
return void 0;
}
return callback(name);
}
});
};
// node_modules/@trpc/server/dist/unstable-core-do-not-import/error/formatter.mjs
var defaultFormatter = ({ shape }) => {
return shape;
};
// node_modules/@trpc/server/dist/unstable-core-do-not-import/utils.mjs
var unsetMarker = Symbol("unsetMarker");
function mergeWithoutOverrides(obj1, ...objs) {
const newObj = Object.assign(/* @__PURE__ */ Object.create(null), obj1);
for (const overrides of objs) {
for (const key in overrides) {
if (key in newObj && newObj[key] !== overrides[key]) {
throw new Error(`Duplicate key ${key}`);
}
newObj[key] = overrides[key];
}
}
return newObj;
}
function isObject2(value2) {
return !!value2 && !Array.isArray(value2) && typeof value2 === "object";
}
function isFunction(fn) {
return typeof fn === "function";
}
function omitPrototype(obj) {
return Object.assign(/* @__PURE__ */ Object.create(null), obj);
}
// node_modules/@trpc/server/dist/unstable-core-do-not-import/error/TRPCError.mjs
var UnknownCauseError = class extends Error {
};
function getCauseFromUnknown(cause) {
if (cause instanceof Error) {
return cause;
}
const type = typeof cause;
if (type === "undefined" || type === "function" || cause === null) {
return void 0;
}
if (type !== "object") {
return new Error(String(cause));
}
if (isObject2(cause)) {
const err = new UnknownCauseError();
for (const key in cause) {
err[key] = cause[key];
}
return err;
}
return void 0;
}
function getTRPCErrorFromUnknown(cause) {
if (cause instanceof TRPCError) {
return cause;
}
if (cause instanceof Error && cause.name === "TRPCError") {
return cause;
}
const trpcError = new TRPCError({
code: "INTERNAL_SERVER_ERROR",
cause
});
if (cause instanceof Error && cause.stack) {
trpcError.stack = cause.stack;
}
return trpcError;
}
var TRPCError = class extends Error {
constructor(opts) {
const cause = getCauseFromUnknown(opts.cause);
const message = opts.message ?? cause?.message ?? opts.code;
super(message, {
cause
});
this.code = opts.code;
this.name = "TRPCError";
if (!this.cause) {
this.cause = cause;
}
}
};
// node_modules/@trpc/server/dist/unstable-core-do-not-import/stream/utils/createReadableStream.mjs
var cancelledStreamSymbol = Symbol("cancelledReadableStream");
// node_modules/@trpc/server/dist/unstable-core-do-not-import/stream/tracked.mjs
var trackedSymbol = Symbol("TrackedEnvelope");
// node_modules/@trpc/server/dist/unstable-core-do-not-import/transformer.mjs
function getDataTransformer(transformer) {
if ("input" in transformer) {
return transformer;
}
return {
input: transformer,
output: transformer
};
}
var defaultTransformer = {
input: {
serialize: (obj) => obj,
deserialize: (obj) => obj
},
output: {
serialize: (obj) => obj,
deserialize: (obj) => obj
}
};
function transformResultInner(response, transformer) {
if ("error" in response) {
const error = transformer.deserialize(response.error);
return {
ok: false,
error: {
...response,
error
}
};
}
const result = {
...response.result,
...(!response.result.type || response.result.type === "data") && {
type: "data",
data: transformer.deserialize(response.result.data)
}
};
return {
ok: true,
result
};
}
var TransformResultError = class extends Error {
constructor() {
super("Unable to transform response from server");
}
};
function transformResult(response, transformer) {
let result;
try {
result = transformResultInner(response, transformer);
} catch (err) {
throw new TransformResultError();
}
if (!result.ok && (!isObject2(result.error.error) || typeof result.error.error["code"] !== "number")) {
throw new TransformResultError();
}
if (result.ok && !isObject2(result.result)) {
throw new TransformResultError();
}
return result;
}
// node_modules/@trpc/server/dist/unstable-core-do-not-import/middleware.mjs
var middlewareMarker = "middlewareMarker";
function createMiddlewareFactory() {
function createMiddlewareInner(middlewares) {
return {
_middlewares: middlewares,
unstable_pipe(middlewareBuilderOrFn) {
const pipedMiddleware = "_middlewares" in middlewareBuilderOrFn ? middlewareBuilderOrFn._middlewares : [
middlewareBuilderOrFn
];
return createMiddlewareInner([
...middlewares,
...pipedMiddleware
]);
}
};
}
function createMiddleware(fn) {
return createMiddlewareInner([
fn
]);
}
return createMiddleware;
}
function createInputMiddleware(parse5) {
const inputMiddleware = async function inputValidatorMiddleware(opts) {
let parsedInput;
const rawInput = await opts.getRawInput();
try {
parsedInput = await parse5(rawInput);
} catch (cause) {
throw new TRPCError({
code: "BAD_REQUEST",
cause
});
}
const combinedInput = isObject2(opts.input) && isObject2(parsedInput) ? {
...opts.input,
...parsedInput
} : parsedInput;
return opts.next({
input: combinedInput
});
};
inputMiddleware._type = "input";
return inputMiddleware;
}
function createOutputMiddleware(parse5) {
const outputMiddleware = async function outputValidatorMiddleware({ next }) {
const result = await next();
if (!result.ok) {
return result;
}
try {
const data = await parse5(result.data);
return {
...result,
data
};
} catch (cause) {
throw new TRPCError({
message: "Output validation failed",
code: "INTERNAL_SERVER_ERROR",
cause
});
}
};
outputMiddleware._type = "output";
return outputMiddleware;
}
// node_modules/@trpc/server/dist/unstable-core-do-not-import/parser.mjs
function getParseFn(procedureParser) {
const parser = procedureParser;
if (typeof parser === "function" && typeof parser.assert === "function") {
return parser.assert.bind(parser);
}
if (typeof parser === "function") {
return parser;
}
if (typeof parser.parseAsync === "function") {
return parser.parseAsync.bind(parser);
}
if (typeof parser.parse === "function") {
return parser.parse.bind(parser);
}
if (typeof parser.validateSync === "function") {
return parser.validateSync.bind(parser);
}
if (typeof parser.create === "function") {
return parser.create.bind(parser);
}
if (typeof parser.assert === "function") {
return (value2) => {
parser.assert(value2);
return value2;
};
}
throw new Error("Could not find a validator fn");
}
// node_modules/@trpc/server/dist/unstable-core-do-not-import/procedureBuilder.mjs
function createNewBuilder(def1, def2) {
const { middlewares = [], inputs, meta, ...rest } = def2;
return createBuilder({
...mergeWithoutOverrides(def1, rest),
inputs: [
...def1.inputs,
...inputs ?? []
],
middlewares: [
...def1.middlewares,
...middlewares
],
meta: def1.meta && meta ? {
...def1.meta,
...meta
} : meta ?? def1.meta
});
}
function createBuilder(initDef = {}) {
const _def = {
procedure: true,
inputs: [],
middlewares: [],
...initDef
};
const builder = {
_def,
input(input) {
const parser = getParseFn(input);
return createNewBuilder(_def, {
inputs: [
input
],
middlewares: [
createInputMiddleware(parser)
]
});
},
output(output) {
const parser = getParseFn(output);
return createNewBuilder(_def, {
output,
middlewares: [
createOutputMiddleware(parser)
]
});
},
meta(meta) {
return createNewBuilder(_def, {
meta
});
},
use(middlewareBuilderOrFn) {
const middlewares = "_middlewares" in middlewareBuilderOrFn ? middlewareBuilderOrFn._middlewares : [
middlewareBuilderOrFn
];
return createNewBuilder(_def, {
middlewares
});
},
unstable_concat(builder2) {
return createNewBuilder(_def, builder2._def);
},
query(resolver) {
return createResolver({
..._def,
type: "query"
}, resolver);
},
mutation(resolver) {
return createResolver({
..._def,
type: "mutation"
}, resolver);
},
subscription(resolver) {
return createResolver({
..._def,
type: "subscription"
}, resolver);
},
experimental_caller(caller) {
return createNewBuilder(_def, {
caller
});
}
};
return builder;
}
function createResolver(_defIn, resolver) {
const finalBuilder = createNewBuilder(_defIn, {
resolver,
middlewares: [
async function resolveMiddleware(opts) {
const data = await resolver(opts);
return {
marker: middlewareMarker,
ok: true,
data,
ctx: opts.ctx
};
}
]
});
const _def = {
...finalBuilder._def,
type: _defIn.type,
experimental_caller: Boolean(finalBuilder._def.caller),
meta: finalBuilder._def.meta,
$types: null
};
const invoke = createProcedureCaller(finalBuilder._def);
const callerOverride = finalBuilder._def.caller;
if (!callerOverride) {
return invoke;
}
const callerWrapper = async (...args) => {
return await callerOverride({
args,
invoke,
_def
});
};
callerWrapper._def = _def;
return callerWrapper;
}
var codeblock = `
This is a client-only function.
If you want to call this function on the server, see https://trpc.io/docs/v11/server/server-side-calls
`.trim();
function createProcedureCaller(_def) {
async function procedure(opts) {
if (!opts || !("getRawInput" in opts)) {
throw new Error(codeblock);
}
async function callRecursive(callOpts = {
index: 0,
ctx: opts.ctx
}) {
try {
const middleware = _def.middlewares[callOpts.index];
const result2 = await middleware({
ctx: callOpts.ctx,
type: opts.type,
path: opts.path,
getRawInput: callOpts.getRawInput ?? opts.getRawInput,
meta: _def.meta,
input: callOpts.input,
next(_nextOpts) {
const nextOpts = _nextOpts;
return callRecursive({
index: callOpts.index + 1,
ctx: nextOpts && "ctx" in nextOpts ? {
...callOpts.ctx,
...nextOpts.ctx
} : callOpts.ctx,
input: nextOpts && "input" in nextOpts ? nextOpts.input : callOpts.input,
getRawInput: nextOpts && "getRawInput" in nextOpts ? nextOpts.getRawInput : callOpts.getRawInput
});
}
});
return result2;
} catch (cause) {
return {
ok: false,
error: getTRPCErrorFromUnknown(cause),
marker: middlewareMarker
};
}
}
const result = await callRecursive();
if (!result) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "No result from middlewares - did you forget to `return next()`?"
});
}
if (!result.ok) {
throw result.error;
}
return result.data;
}
procedure._def = _def;
return procedure;
}
// node_modules/@trpc/server/dist/unstable-core-do-not-import/rootConfig.mjs
var isServerDefault = typeof window === "undefined" || "Deno" in window || // eslint-disable-next-line @typescript-eslint/dot-notation
globalThis.process?.env?.["NODE_ENV"] === "test" || !!globalThis.process?.env?.["JEST_WORKER_ID"] || !!globalThis.process?.env?.["VITEST_WORKER_ID"];
// node_modules/@trpc/server/dist/unstable-core-do-not-import/router.mjs
function isRouter(procedureOrRouter) {
return procedureOrRouter._def && "router" in procedureOrRouter._def;
}
var emptyRouter = {
_ctx: null,
_errorShape: null,
_meta: null,
queries: {},
mutations: {},
subscriptions: {},
errorFormatter: defaultFormatter,
transformer: defaultTransformer
};
var reservedWords = [
/**
* Then is a reserved word because otherwise we can't return a promise that returns a Proxy
* since JS will think that `.then` is something that exists
*/
"then",
/**
* `fn.call()` and `fn.apply()` are reserved words because otherwise we can't call a function using `.call` or `.apply`
*/
"call",
"apply"
];
function createRouterFactory(config) {
function createRouterInner(input) {
const reservedWordsUsed = new Set(Object.keys(input).filter((v) => reservedWords.includes(v)));
if (reservedWordsUsed.size > 0) {
throw new Error("Reserved words used in `router({})` call: " + Array.from(reservedWordsUsed).join(", "));
}
const procedures = omitPrototype({});
function step(from, path = []) {
const aggregate = omitPrototype({});
for (const [key, item] of Object.entries(from ?? {})) {
if (isRouter(item)) {
aggregate[key] = step(item._def.record, [
...path,
key
]);
continue;
}
if (!isProcedure(item)) {
aggregate[key] = step(item, [
...path,
key
]);
continue;
}
const newPath = [
...path,
key
].join(".");
if (procedures[newPath]) {
throw new Error(`Duplicate key: ${newPath}`);
}
procedures[newPath] = item;
aggregate[key] = item;
}
return aggregate;
}
const record = step(input);
const _def = {
_config: config,
router: true,
procedures,
...emptyRouter,
record
};
return {
...record,
_def,
createCaller: createCallerFactory()({
_def
})
};
}
return createRouterInner;
}
function isProcedure(procedureOrRouter) {
return typeof procedureOrRouter === "function";
}
function createCallerFactory() {
return function createCallerInner(router) {
const _def = router._def;
return function createCaller(ctxOrCallback, options) {
return createRecursiveProxy(async ({ path, args }) => {
const fullPath = path.join(".");
if (path.length === 1 && path[0] === "_def") {
return _def;
}
const procedure = _def.procedures[fullPath];
let ctx = void 0;
try {
ctx = isFunction(ctxOrCallback) ? await Promise.resolve(ctxOrCallback()) : ctxOrCallback;
return await procedure({
path: fullPath,
getRawInput: async () => args[0],
ctx,
type: procedure._def.type
});
} catch (cause) {
options?.onError?.({
ctx,
error: getTRPCErrorFromUnknown(cause),
input: args[0],
path: fullPath,
type: procedure._def.type
});
throw cause;
}
});
};
};
}
function mergeRouters(...routerList) {
const record = mergeWithoutOverrides({}, ...routerList.map((r) => r._def.record));
const errorFormatter = routerList.reduce((currentErrorFormatter, nextRouter) => {
if (nextRouter._def._config.errorFormatter && nextRouter._def._config.errorFormatter !== defaultFormatter) {
if (currentErrorFormatter !== defaultFormatter && currentErrorFormatter !== nextRouter._def._config.errorFormatter) {
throw new Error("You seem to have several error formatters");
}
return nextRouter._def._config.errorFormatter;
}
return currentErrorFormatter;
}, defaultFormatter);
const transformer = routerList.reduce((prev, current) => {
if (current._def._config.transformer && current._def._config.transformer !== defaultTransformer) {
if (prev !== defaultTransformer && prev !== current._def._config.transformer) {
throw new Error("You seem to have several transformers");
}
return current._def._config.transformer;
}
return prev;
}, defaultTransformer);
const router = createRouterFactory({
errorFormatter,
transformer,
isDev: routerList.every((r) => r._def._config.isDev),
allowOutsideOfServer: routerList.every((r) => r._def._config.allowOutsideOfServer),
isServer: routerList.every((r) => r._def._config.isServer),
$types: routerList[0]?._def._config.$types
})(record);
return router;
}
// node_modules/@trpc/server/dist/unstable-core-do-not-import/initTRPC.mjs
var TRPCBuilder = class _TRPCBuilder {
/**
* Add a context shape as a generic to the root object
* @link https://trpc.io/docs/v11/server/context
*/
context() {
return new _TRPCBuilder();
}
/**
* Add a meta shape as a generic to the root object
* @link https://trpc.io/docs/v11/quickstart
*/
meta() {
return new _TRPCBuilder();
}
/**
* Create the root object
* @link https://trpc.io/docs/v11/server/routers#initialize-trpc
*/
create(opts) {
const config = {
transformer: getDataTransformer(opts?.transformer ?? defaultTransformer),
isDev: opts?.isDev ?? // eslint-disable-next-line @typescript-eslint/dot-notation
globalThis.process?.env["NODE_ENV"] !== "production",
allowOutsideOfServer: opts?.allowOutsideOfServer ?? false,
errorFormatter: opts?.errorFormatter ?? defaultFormatter,
isServer: opts?.isServer ?? isServerDefault,
/**
* These are just types, they can't be used at runtime
* @internal
*/
$types: null,
experimental: opts?.experimental ?? {}
};
{
const isServer = opts?.isServer ?? isServerDefault;
if (!isServer && opts?.allowOutsideOfServer !== true) {
throw new Error(`You're trying to use @trpc/server in a non-server environment. This is not supported by default.`);
}
}
return {
/**
* Your router config
* @internal
*/
_config: config,
/**
* Builder object for creating procedures
* @link https://trpc.io/docs/v11/server/procedures
*/
procedure: createBuilder({
meta: opts?.defaultMeta
}),
/**
* Create reusable middlewares
* @link https://trpc.io/docs/v11/server/middlewares
*/
middleware: createMiddlewareFactory(),
/**
* Create a router
* @link https://trpc.io/docs/v11/server/routers
*/
router: createRouterFactory(config),
/**
* Merge Routers
* @link https://trpc.io/docs/v11/server/merging-routers
*/
mergeRouters,
/**
* Create a server-side caller for a router
* @link https://trpc.io/docs/v11/server/server-side-calls
*/
createCallerFactory: createCallerFactory()
};
}
};
var initTRPC = new TRPCBuilder();
// node_modules/@trpc/server/dist/unstable-core-do-not-import/types.mjs
var ERROR_SYMBOL = Symbol("TypeError");
// node_modules/@trpc/client/dist/TRPCClientError.mjs
function isTRPCClientError(cause) {
return cause instanceof TRPCClientError || /**
* @deprecated
* Delete in next major
*/
cause instanceof Error && cause.name === "TRPCClientError";
}
function isTRPCErrorResponse(obj) {
return isObject2(obj) && isObject2(obj["error"]) && typeof obj["error"]["code"] === "number" && typeof obj["error"]["message"] === "string";
}
function getMessageFromUnknownError(err, fallback) {
if (typeof err === "string") {
return err;
}
if (isObject2(err) && typeof err["message"] === "string") {
return err["message"];
}
return fallback;
}
var TRPCClientError = class _TRPCClientError extends Error {
static from(_cause, opts = {}) {
const cause = _cause;
if (isTRPCClientError(cause)) {
if (opts.meta) {
cause.meta = {
...cause.meta,
...opts.meta
};
}
return cause;
}
if (isTRPCErrorResponse(cause)) {
return new _TRPCClientError(cause.error.message, {
...opts,
result: cause
});
}
return new _TRPCClientError(getMessageFromUnknownError(cause, "Unknown error"), {
...opts,
cause
});
}
constructor(message, opts) {
const cause = opts?.cause;
super(message, {
cause
});
this.meta = opts?.meta;
this.cause = cause;
this.shape = opts?.result?.error;
this.data = opts?.result?.error.data;
this.name = "TRPCClientError";
Object.setPrototypeOf(this, _TRPCClientError.prototype);
}
};
// node_modules/@trpc/client/dist/internals/TRPCUntypedClient.mjs
var TRPCUntypedClient = class {
$request(opts) {
const chain$ = createChain({
links: this.links,
op: {
...opts,
context: opts.context ?? {},
id: ++this.requestId
}
});
return chain$.pipe(share());
}
async requestAsPromise(opts) {
try {
const req$ = this.$request(opts);
const envelope = await observableToPromise(req$);
const data = envelope.result.data;
return data;
} catch (err) {
throw TRPCClientError.from(err);
}
}
query(path, input, opts) {
return this.requestAsPromise({
type: "query",
path,
input,
context: opts?.context,
signal: opts?.signal
});
}
mutation(path, input, opts) {
return this.requestAsPromise({
type: "mutation",
path,
input,
context: opts?.context,
signal: opts?.signal
});
}
subscription(path, input, opts) {
const observable$ = this.$request({
type: "subscription",
path,
input,
context: opts?.context,
signal: null
});
return observable$.subscribe({
next(envelope) {
if (envelope.result.type === "started") {
opts.onStarted?.({
context: envelope.context
});
} else if (envelope.result.type === "stopped") {
opts.onStopped?.();
} else {
opts.onData?.(envelope.result.data);
}
},
error(err) {
opts.onError?.(err);
},
complete() {
opts.onComplete?.();
}
});
}
constructor(opts) {
this.requestId = 0;
this.runtime = {};
this.links = opts.links.map((link) => link(this.runtime));
}
};
// node_modules/@trpc/client/dist/createTRPCClient.mjs
var clientCallTypeMap = {
query: "query",
mutate: "mutation",
subscribe: "subscription"
};
var clientCallTypeToProcedureType = (clientCallType) => {
return clientCallTypeMap[clientCallType];
};
function createTRPCClientProxy(client) {
const proxy = createRecursiveProxy(({ path, args }) => {
const pathCopy = [
...path
];
const procedureType = clientCallTypeToProcedureType(pathCopy.pop());
const fullPath = pathCopy.join(".");
return client[procedureType](fullPath, ...args);
});
return createFlatProxy((key) => {
if (client.hasOwnProperty(key)) {
return client[key];
}
if (key === "__untypedClient") {
return client;
}
return proxy[key];
});
}
function createTRPCClient(opts) {
const client = new TRPCUntypedClient(opts);
const proxy = createTRPCClientProxy(client);
return proxy;
}
// node_modules/@trpc/client/dist/getFetch.mjs
var isFunction2 = (fn) => typeof fn === "function";
function getFetch(customFetchImpl) {
if (customFetchImpl) {
return customFetchImpl;
}
if (typeof window !== "undefined" && isFunction2(window.fetch)) {
return window.fetch;
}
if (typeof globalThis !== "undefined" && isFunction2(globalThis.fetch)) {
return globalThis.fetch;
}
throw new Error("No fetch implementation found");
}
// node_modules/@trpc/client/dist/internals/dataLoader.mjs
var throwFatalError = () => {
throw new Error("Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new");
};
function dataLoader(batchLoader) {
let pendingItems = null;
let dispatchTimer = null;
const destroyTimerAndPendingItems = () => {
clearTimeout(dispatchTimer);
dispatchTimer = null;
pendingItems = null;
};
function groupItems(items) {
const groupedItems = [
[]
];
let index = 0;
while (true) {
const item = items[index];
if (!item) {
break;
}
const lastGroup = groupedItems[groupedItems.length - 1];
if (item.aborted) {
item.reject?.(new Error("Aborted"));
index++;
continue;
}
const isValid = batchLoader.validate(lastGroup.concat(item).map((it) => it.key));
if (isValid) {
lastGroup.push(item);
index++;
continue;
}
if (lastGroup.length === 0) {
item.reject?.(new Error("Input is too big for a single dispatch"));
index++;
continue;
}
groupedItems.push([]);
}
return groupedItems;
}
function dispatch() {
const groupedItems = groupItems(pendingItems);
destroyTimerAndPendingItems();
for (const items of groupedItems) {
if (!items.length) {
continue;
}
const batch = {
items
};
for (const item of items) {
item.batch = batch;
}
const promise = batchLoader.fetch(batch.items.map((_item) => _item.key));
promise.then(async (result) => {
await Promise.all(result.map(async (valueOrPromise, index) => {
const item = batch.items[index];
try {
const value2 = await Promise.resolve(valueOrPromise);
item.resolve?.(value2);
} catch (cause) {
item.reject?.(cause);
}
item.batch = null;
item.reject = null;
item.resolve = null;
}));
for (const item of batch.items) {
item.reject?.(new Error("Missing result"));
item.batch = null;
}
}).catch((cause) => {
for (const item of batch.items) {
item.reject?.(cause);
item.batch = null;
}
});
}
}
function load(key) {
const item = {
aborted: false,
key,
batch: null,
resolve: throwFatalError,
reject: throwFatalError
};
const promise = new Promise((resolve, reject) => {
item.reject = reject;
item.resolve = resolve;
if (!pendingItems) {
pendingItems = [];
}
pendingItems.push(item);
});
if (!dispatchTimer) {
dispatchTimer = setTimeout(dispatch);
}
return promise;
}
return {
load
};
}
// node_modules/@trpc/client/dist/internals/transformer.mjs
function getTransformer(transformer) {
const _transformer = transformer;
if (!_transformer) {
return {
input: {
serialize: (data) => data,
deserialize: (data) => data
},
output: {
serialize: (data) => data,
deserialize: (data) => data
}
};
}
if ("input" in _transformer) {
return _transformer;
}
return {
input: _transformer,
output: _transformer
};
}
// node_modules/@trpc/client/dist/links/internals/httpUtils.mjs
function resolveHTTPLinkOptions(opts) {
return {
url: opts.url.toString(),
fetch: opts.fetch,
transformer: getTransformer(opts.transformer),
methodOverride: opts.methodOverride
};
}
function arrayToDict(array) {
const dict = {};
for (let index = 0; index < array.length; index++) {
const element = array[index];
dict[index] = element;
}
return dict;
}
var METHOD = {
query: "GET",
mutation: "POST",
subscription: "PATCH"
};
function getInput(opts) {
return "input" in opts ? opts.transformer.input.serialize(opts.input) : arrayToDict(opts.inputs.map((_input) => opts.transformer.input.serialize(_input)));
}
var getUrl = (opts) => {
const parts2 = opts.url.split("?");
const base = parts2[0].replace(/\/$/, "");
let url2 = base + "/" + opts.path;
const queryParts = [];
if (parts2[1]) {
queryParts.push(parts2[1]);
}
if ("inputs" in opts) {
queryParts.push("batch=1");
}
if (opts.type === "query" || opts.type === "subscription") {
const input = getInput(opts);
if (input !== void 0 && opts.methodOverride !== "POST") {
queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);
}
}
if (queryParts.length) {
url2 += "?" + queryParts.join("&");
}
return url2;
};
var getBody = (opts) => {
if (opts.type === "query" && opts.methodOverride !== "POST") {
return void 0;
}
const input = getInput(opts);
return input !== void 0 ? JSON.stringify(input) : void 0;
};
var jsonHttpRequester = (opts) => {
return httpRequest({
...opts,
contentTypeHeader: "application/json",
getUrl,
getBody
});
};
var AbortError = class extends Error {
constructor() {
const name = "AbortError";
super(name);
this.name = name;
this.message = name;
}
};
var throwIfAborted = (signal) => {
if (!signal?.aborted) {
return;
}
signal.throwIfAborted?.();
if (typeof DOMException !== "undefined") {
throw new DOMException("AbortError", "AbortError");
}
throw new AbortError();
};
async function fetchHTTPResponse(opts) {
throwIfAborted(opts.signal);
const url2 = opts.getUrl(opts);
const body = opts.getBody(opts);
const { type } = opts;
const resolvedHeaders = await (async () => {
const heads = await opts.headers();
if (Symbol.iterator in heads) {
return Object.fromEntries(heads);
}
return heads;
})();
const headers = {
...opts.contentTypeHeader ? {
"content-type": opts.contentTypeHeader
} : {},
...opts.trpcAcceptHeader ? {
"trpc-accept": opts.trpcAcceptHeader
} : void 0,
...resolvedHeaders
};
return getFetch(opts.fetch)(url2, {
method: opts.methodOverride ?? METHOD[type],
signal: opts.signal,
body,
headers
});
}
async function httpRequest(opts) {
const meta = {};
const res = await fetchHTTPResponse(opts);
meta.response = res;
const json = await res.json();
meta.responseJSON = json;
return {
json,
meta
};
}
function mergeAbortSignals(opts) {
const ac = new AbortController();
if (opts.some((o) => !o.signal)) {
return ac;
}
const count = opts.length;
let abortedCount = 0;
const onAbort = () => {
if (++abortedCount === count) {
ac.abort();
}
};
for (const o of opts) {
const signal = o.signal;
if (signal.aborted) {
onAbort();
} else {
signal.addEventListener("abort", onAbort, {
once: true
});
}
}
return ac;
}
// node_modules/@trpc/client/dist/links/httpBatchLink.mjs
function httpBatchLink(opts) {
const resolvedOpts = resolveHTTPLinkOptions(opts);
const maxURLLength = opts.maxURLLength ?? Infinity;
return () => {
const batchLoader = (type) => {
return {
validate(batchOps) {
if (maxURLLength === Infinity) {
return true;
}
const path = batchOps.map((op) => op.path).join(",");
const inputs = batchOps.map((op) => op.input);
const url2 = getUrl({
...resolvedOpts,
type,
path,
inputs,
signal: null
});
return url2.length <= maxURLLength;
},
async fetch(batchOps) {
const path = batchOps.map((op) => op.path).join(",");
const inputs = batchOps.map((op) => op.input);
const ac = mergeAbortSignals(batchOps);
const res = await jsonHttpRequester({
...resolvedOpts,
path,
inputs,
type,
headers() {
if (!opts.headers) {
return {};
}
if (typeof opts.headers === "function") {
return opts.headers({
opList: batchOps
});
}
return opts.headers;
},
signal: ac.signal
});
const resJSON = Array.isArray(res.json) ? res.json : batchOps.map(() => res.json);
const result = resJSON.map((item) => ({
meta: res.meta,
json: item
}));
return result;
}
};
};
const query = dataLoader(batchLoader("query"));
const mutation = dataLoader(batchLoader("mutation"));
const loaders = {
query,
mutation
};
return ({ op }) => {
return observable((observer) => {
if (op.type === "subscription") {
throw new Error("Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`");
}
const loader = loaders[op.type];
const promise = loader.load(op);
let _res = void 0;
promise.then((res) => {
_res = res;
const transformed = transformResult(res.json, resolvedOpts.transformer.output);
if (!transformed.ok) {
observer.error(TRPCClientError.from(transformed.error, {
meta: res.meta
}));
return;
}
observer.next({
context: res.meta,
result: transformed.result
});
observer.complete();
}).catch((err) => {
observer.error(TRPCClientError.from(err, {
meta: _res?.meta
}));
});
return () => {
};
});
};
};
}
// src/util/api/trpc.ts
require_main().config();
function gettRPC(token) {
const fishingURL = process.env.FISHING_API_URL;
const firstLink = httpBatchLink({
url: fishingURL,
headers() {
return {
Authorization: token
};
}
});
const secondLink = httpBatchLink({
url: "https://fishing.hri7566.info/api",
headers() {
return {
Authorization: token
};
}
});
const links = firstLink ? [firstLink, secondLink] : [secondLink];
return createTRPCClient({ links });
}
var trpc_default = gettRPC;
// src/talkomatic/bot/TalkomaticBot.ts
require_main().config();
var convertMarkdownToUnicode = require_src2();
var ppl = {};
var TalkomaticBot = class extends import_node_events.EventEmitter {
constructor(config) {
super();
this.config = config;
this.logger = new Logger("Talkomatic - " + config.channel.name);
this.client = lookup("https://talkomatic.co/", {
extraHeaders: {
Cookie: "connect.sid=" + process.env.TALKOMATIC_SID
},
autoConnect: false
});
this.bindEventListeners();
}
client;
b = new import_node_events.EventEmitter();
logger;
trpc = trpc_default(process.env.TALKOMATIC_FISHING_TOKEN);
started = false;
defaultColor = "#abe3d6";
channelId = "";
async start() {
this.logger.info("Starting");
this.client.connect();
let data = await this.findChannel(this.config.channel.name) || await this.createChannel(
this.config.channel.name,
this.config.channel.type
);
this.logger.debug(data);
if (typeof data !== "undefined") {
try {
this.channelId = data.room.room_id;
this.setChannel(this.channelId);
this.started = true;
} catch (err) {
this.logger.error(err);
}
}
}
stop() {
this.client.disconnect();
this.started = false;
}
connected = false;
bindEventListeners() {
this.client.onAny((msg) => {
if (this.connected) return;
this.connected = true;
this.logger.info("Connected to server");
});
this.client.on(
"userTyping",
(msg) => {
const p = ppl[msg.userId] || {
name: "<unknown user>",
id: msg.userId,
color: msg.color,
typingFlag: false
};
if (p.typingTimeout) clearTimeout(p.typingTimeout);
p.typingTimeout = setTimeout(() => {
p.typingFlag = true;
ppl[msg.userId] = p;
if (msg.text.length <= 0) return;
this.emit("command", msg);
}, 500);
ppl[msg.userId] = p;
}
);
this.client.on(
"udpateRoom",
async (msg) => {
if (!Array.isArray(msg.users)) return;
try {
for (const user of msg.users) {
let color = (await this.trpc.getUserColor.query({
userId: user.id
})).color;
this.logger.debug(
"(updateRoom) user color from api:",
color
);
const p = ppl[user.id] || {
name: user.username,
id: user.id,
color,
typingFlag: false
};
ppl[user.id] = p;
}
} catch (err) {
this.logger.warn("Unable to set user data:", err);
}
}
);
this.client.on(
"roomUsers",
async (msg) => {
if (!Array.isArray(msg.users)) return;
try {
for (const user of msg.users) {
let color = (await this.trpc.getUserColor.query({
userId: user.id
})).color;
if (!color) color = this.defaultColor;
this.logger.debug(
"(roomUsers) user color from api:",
color
);
const p = ppl[user.id] || {
name: user.username,
id: user.id,
color,
typingFlag: false
};
ppl[user.id] = p;
}
} catch (err) {
}
}
);
this.on(
"command",
async (msg) => {
let prefixes;
try {
prefixes = await this.trpc.prefixes.query();
} catch (err) {
this.logger.error(err);
this.logger.warn("Unable to contact server");
return;
}
let usedPrefix = prefixes.find(
(pr) => msg.text.startsWith(pr)
);
let color = (await this.trpc.getUserColor.query({
userId: msg.userId
})).color;
if (!color) color = this.defaultColor;
if (!usedPrefix) return;
const args = msg.text.split(" ");
let part = ppl[msg.userId] || {
name: "<unknown user>",
id: msg.userId,
color,
typingFlag: false
};
this.logger.info(`${part.name}: ${msg.text}`);
const command = await this.trpc.command.query({
channel: this.channelId,
args: args.slice(1, args.length),
command: args[0].substring(usedPrefix.length),
prefix: usedPrefix,
user: {
id: part.id,
name: part.name,
color: part.color
}
});
if (!command) return;
if (command.response)
this.sendChat(command.response, void 0, msg.userId);
}
);
this.client.on(
"userJoined",
(msg) => {
const p = ppl[msg.id] || {
name: msg.username,
id: msg.id,
color: "#abe3d6",
typingFlag: false
};
ppl[msg.id] = p;
}
);
setInterval(async () => {
try {
const backs = await this.trpc.backs.query();
if (backs.length > 0) {
for (const back of backs) {
if (typeof back.m !== "string") return;
this.b.emit(back.m, back);
}
}
} catch (err) {
return;
}
}, 1e3 / 20);
this.b.on("color", async (msg) => {
if (typeof msg.color !== "string" || typeof msg.id !== "string")
return;
try {
ppl[msg.id].color = msg.color;
await this.trpc.saveColor.query({
userId: msg.id,
color: msg.color
});
} catch (err) {
this.logger.warn("Unable to save user color:", err);
}
});
this.b.on(
"sendchat",
(msg) => {
if (typeof msg.channel === "string") {
if (msg.channel !== this.channelId) return;
}
this.sendChat(msg.message);
}
);
}
oldText = "";
sendChat(text, reply, id) {
const fixedOld = this.oldText.split("\n")[-1];
if (text.toLowerCase().includes("autofish"))
text = `${fixedOld ? fixedOld + "\n" : ""}${text}`;
const msg = {
roomId: this.channelId,
// text: text.split("sack").join("ʂасκ"),
text: text.split("sack").join("caught"),
color: id ? ppl[id].color : this.defaultColor
};
for (const uuid of Object.keys(ppl)) {
const p = ppl[uuid];
msg.text = msg.text.split(`@${uuid}`).join(p.name);
if (!p) continue;
if (uuid !== id) continue;
msg.color = p.color;
}
try {
msg.text = convertMarkdownToUnicode(msg.text);
} catch (err) {
this.logger.warn("Unable to parse markdown:", err);
}
this.client.emit("typing", msg);
this.oldText = text;
}
setChannel(roomId) {
this.client.emit("joinRoom", { roomId });
}
async createChannel(roomName, roomType = "public") {
const response = await fetch(
"https://talkomatic.co/create-and-join-room",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Cookie: "connect.sid=" + process.env.TALKOMATIC_SID
},
credentials: "include",
body: JSON.stringify({
roomName,
roomType
})
}
);
if (!response.ok)
return void this.logger.warn(
"Unable to create channel:",
new TextDecoder().decode(
(await response.body?.getReader().read())?.value
)
);
try {
const data = new TextDecoder().decode(
(await response.body?.getReader().read())?.value
);
return JSON.parse(data.toString());
} catch (err) {
this.logger.warn(
"Unable to decode channel creation response data:",
err
);
}
}
async findChannel(name) {
const response = await fetch("https://talkomatic.co/rooms", {
method: "GET"
});
if (!response.ok)
return void this.logger.warn(
"Unable to create channel:",
new TextDecoder().decode(
(await response.body?.getReader().read())?.value
)
);
try {
const data = new TextDecoder().decode(
(await response.body?.getReader().read())?.value
);
const rooms = JSON.parse(data.toString());
for (const room of rooms.rooms) {
if (room.room_name == name) {
return { room };
}
}
} catch (err) {
this.logger.warn(
"Unable to decode channel creation response data:",
err
);
}
}
};
// src/talkomatic/bot/index.ts
var bots = [];
var defaults = loadConfig("config/talkomatic_bots.yml", [
{
channel: {
name: "test/fishing"
}
}
]);
function connectDefaultBots() {
defaults.forEach((conf) => {
initBot(conf);
});
}
function initBot(conf) {
const bot = new TalkomaticBot(conf);
bot.start();
bots.push(bot);
}
// src/talkomatic/index.ts
connectDefaultBots();
startAutorestart();
/*! Bundled license information:
xmlhttprequest-ssl/lib/XMLHttpRequest.js:
(**
* Wrapper for built-in http.js to emulate the browser XMLHttpRequest object.
*
* This can be used with JS designed for browsers to improve reuse of code and
* allow the use of existing libraries.
*
* Usage: include("XMLHttpRequest.js") and use XMLHttpRequest per W3C specs.
*
* @author Dan DeFelippi <dan@driverdan.com>
* @contributor David Ellis <d.f.ellis@ieee.org>
* @license MIT
*)
@trpc/server/dist/unstable-core-do-not-import/rpc/parseTRPCMessage.mjs:
(* istanbul ignore next -- @preserve *)
@trpc/server/dist/unstable-core-do-not-import/rpc/parseTRPCMessage.mjs:
(* istanbul ignore next -- @preserve *)
@trpc/server/dist/unstable-core-do-not-import/rpc/parseTRPCMessage.mjs:
(* istanbul ignore next -- @preserve *)
@trpc/server/dist/unstable-core-do-not-import/rpc/parseTRPCMessage.mjs:
(* istanbul ignore next -- @preserve *)
@trpc/server/dist/unstable-core-do-not-import/rpc/parseTRPCMessage.mjs:
(* istanbul ignore next -- @preserve *)
@trpc/client/dist/links/httpBatchLink.mjs:
(* istanbul ignore if -- @preserve *)
*/