@fireproof/cloud
Version:
Fireproof Cloud gateway for Fireproof
4,509 lines • 146 kB
JavaScript
"use strict";
var Connect = (() => {
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, from2, except, desc) => {
if (from2 && typeof from2 === "object" || typeof from2 === "function") {
for (let key of __getOwnPropNames(from2))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js
var require_browser = __commonJS({
"node_modules/.pnpm/ws@8.18.0/node_modules/ws/browser.js"(exports, module) {
"use strict";
module.exports = function() {
throw new Error(
"ws does not work in the browser. Browser clients must use the native WebSocket object"
);
};
}
});
// src/cloud/index.ts
var cloud_exports = {};
__export(cloud_exports, {
connect: () => connect,
rawConnect: () => rawConnect
});
// node_modules/.pnpm/@adviser+cement@0.2.41_typescript@5.7.2/node_modules/@adviser/cement/chunk-GES3MUGV.js
var __defProp2 = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp2.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __export2 = (target, all) => {
for (var name in all)
__defProp2(target, name, { get: all[name], enumerable: true });
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var encoder = new TextEncoder();
var decoder = new TextDecoder();
var Utf8EnDecoder = class {
encode(str) {
return encoder.encode(str);
}
decode(data) {
return decoder.decode(data);
}
};
var utf8EnDecoder = new Utf8EnDecoder();
function Utf8EnDecoderSingleton() {
return utf8EnDecoder;
}
// node_modules/.pnpm/@adviser+cement@0.2.41_typescript@5.7.2/node_modules/@adviser/cement/chunk-USQXEZHL.js
var utils_exports = {};
__export2(utils_exports, {
ConsoleWriterStream: () => ConsoleWriterStream,
ConsoleWriterStreamDefaultWriter: () => ConsoleWriterStreamDefaultWriter,
FanoutWriteStream: () => FanoutWriteStream,
array2stream: () => array2stream,
devnull: () => devnull,
rebuffer: () => rebuffer,
rebufferArray: () => rebufferArray,
stream2array: () => stream2array,
stream2string: () => stream2string,
stream2uint8array: () => stream2uint8array,
streamMap: () => streamMap,
string2stream: () => string2stream,
uint8array2stream: () => uint8array2stream
});
function streamMap(s, sm) {
const state = { reader: s.getReader(), streamMap: sm, idx: 0 };
return new ReadableStream({
async pull(controller) {
const { done, value } = await state.reader.read();
if (done) {
if (state.streamMap.Close) {
state.streamMap.Close();
}
controller.close();
return;
}
const promiseOrU = state.streamMap.Map(value, state.idx++);
let mapped;
if (promiseOrU instanceof Promise || typeof promiseOrU.then === "function") {
mapped = await promiseOrU;
} else {
mapped = promiseOrU;
}
controller.enqueue(mapped);
}
});
}
async function devnull(a) {
const reader = a.getReader();
let cnt = 0;
while (true) {
const { done } = await reader.read();
if (done) {
break;
}
cnt++;
}
return cnt;
}
function array2stream(a) {
let i = 0;
return new ReadableStream({
pull(controller) {
if (i >= a.length) {
controller.close();
return;
}
controller.enqueue(a[i]);
i++;
}
});
}
async function stream2array(a) {
const ret = [];
const reader = a.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
ret.push(value);
}
return ret;
}
async function rebufferArray(a, chunkSize) {
return stream2array(rebuffer(array2stream(a), chunkSize));
}
function reChunk(cs, chunkSize) {
const len = cs.reduce((acc, v) => acc + v.length, 0);
const last = cs[cs.length - 1];
const lastOfs = len - last.length;
const rest = last.subarray(chunkSize - lastOfs);
cs[cs.length - 1] = last.subarray(0, chunkSize - lastOfs);
const chunk = new Uint8Array(chunkSize);
let ofs = 0;
for (const c of cs) {
chunk.set(c, ofs);
ofs += c.length;
}
return { rest, chunk };
}
function pump(ps, controller, next) {
ps.reader.read().then(({ done, value }) => {
if (done) {
if (ps.tmpLen > 0) {
controller.enqueue(reChunk(ps.tmp, ps.tmpLen).chunk);
}
controller.close();
next();
return;
}
if (ps.tmpLen + value.length > ps.chunkSize) {
ps.tmp.push(value);
const res = reChunk(ps.tmp, ps.chunkSize);
controller.enqueue(res.chunk);
ps.tmp = [res.rest];
ps.tmpLen = res.rest.length;
next();
return;
} else if (value.length) {
ps.tmp.push(value);
ps.tmpLen += value.length;
}
pump(ps, controller, next);
});
}
function rebuffer(a, chunkSize) {
const state = {
reader: a.getReader(),
tmp: [],
tmpLen: 0,
chunkSize
};
return new ReadableStream({
async pull(controller) {
return new Promise((resolve) => {
pump(state, controller, resolve);
});
}
});
}
async function stream2string(stream, maxSize) {
if (!stream) {
return Promise.resolve("");
}
const reader = stream.getReader();
let res = "";
const decoder2 = new TextDecoder();
let rSize = 0;
while (typeof maxSize === "undefined" || rSize < maxSize) {
try {
const read = await reader.read();
if (read.done) {
break;
}
if (maxSize && rSize + read.value.length > maxSize) {
read.value = read.value.slice(0, maxSize - rSize);
}
const block = decoder2.decode(read.value, { stream: true });
rSize += read.value.length;
res += block;
} catch (err2) {
return Promise.reject(err2);
}
}
return Promise.resolve(res);
}
async function stream2uint8array(stream) {
if (!stream) {
return Promise.resolve(new Uint8Array());
}
const reader = stream.getReader();
let res = new Uint8Array();
while (1) {
try {
const { done, value } = await reader.read();
if (done) {
break;
}
res = new Uint8Array([...res, ...value]);
} catch (err2) {
return Promise.reject(err2);
}
}
return Promise.resolve(res);
}
function string2stream(str, ende = Utf8EnDecoderSingleton()) {
return uint8array2stream(ende.encode(str));
}
function uint8array2stream(str) {
return new ReadableStream({
start(controller) {
controller.enqueue(str);
controller.close();
}
});
}
var ConsoleWriterStreamDefaultWriter = class {
constructor(stream) {
this.stream = stream;
this.desiredSize = null;
this.decoder = new TextDecoder();
this._stream = stream;
this.ready = Promise.resolve(void 0);
this.closed = Promise.resolve(void 0);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any
abort(reason) {
throw new Error("Method not implemented.");
}
async close() {
}
releaseLock() {
this._stream.locked = false;
this.ready = Promise.resolve(void 0);
this.closed = Promise.resolve(void 0);
}
async write(chunk) {
let strObj = this.decoder.decode(chunk).trimEnd();
let output = "log";
try {
strObj = JSON.parse(strObj);
output = strObj.level;
} catch (e) {
}
switch (output) {
case "error":
console.error(strObj);
break;
case "warn":
console.warn(strObj);
break;
default:
console.log(strObj);
}
}
};
var ConsoleWriterStream = class {
constructor() {
this.locked = false;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars
abort(reason) {
throw new Error("Method not implemented.");
}
async close() {
return;
}
getWriter() {
if (this.locked) {
throw new Error("Stream is locked");
}
this.locked = true;
if (!this._writer) {
this._writer = new ConsoleWriterStreamDefaultWriter(this);
}
return this._writer;
}
};
var FanoutWriteStream = class {
constructor(writers) {
this.desiredSize = null;
this._writers = writers;
this.ready = Promise.all(this._writers.map((w) => w.ready)).then(() => void 0);
this.closed = Promise.all(this._writers.map((w) => w.closed)).then(() => void 0);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
abort(reason) {
return Promise.all(this._writers.map((w) => w.abort(reason))).then(() => {
});
}
close() {
return Promise.all(this._writers.map((w) => w.close())).then(() => {
});
}
releaseLock() {
this._writers.map((w) => w.releaseLock());
}
write(chunk) {
return Promise.all(this._writers.map((w) => w.write(chunk))).then(() => {
});
}
};
// node_modules/.pnpm/@adviser+cement@0.2.41_typescript@5.7.2/node_modules/@adviser/cement/chunk-F5W6VELE.js
var _promise;
var _resolveFn;
var _rejectFn;
var Future = class {
constructor() {
__privateAdd(this, _promise);
__privateAdd(this, _resolveFn, () => {
throw new Error("This Promise is not working as expected.");
});
__privateAdd(this, _rejectFn, () => {
throw new Error("This Promise is not working as expected.");
});
__privateSet(this, _promise, new Promise((resolve, reject) => {
__privateSet(this, _resolveFn, resolve);
__privateSet(this, _rejectFn, reject);
}));
}
async asPromise() {
return __privateGet(this, _promise);
}
resolve(value) {
__privateGet(this, _resolveFn).call(this, value);
}
reject(reason) {
__privateGet(this, _rejectFn).call(this, reason);
}
};
_promise = /* @__PURE__ */ new WeakMap();
_resolveFn = /* @__PURE__ */ new WeakMap();
_rejectFn = /* @__PURE__ */ new WeakMap();
var ResolveOnce = class {
constructor(ctx) {
this._onceDone = false;
this._onceFutures = [];
this._onceOk = false;
this._isPromise = false;
this.ctx = ctx;
}
get ready() {
return this._onceDone;
}
reset() {
this._onceDone = false;
this._onceOk = false;
this._onceValue = void 0;
this._onceError = void 0;
this._onceFutures.length = 0;
}
// T extends Option<infer U> ? U : T
once(fn) {
if (this._onceDone) {
if (this._onceError) {
if (this._isPromise) {
return Promise.reject(this._onceError);
} else {
throw this._onceError;
}
}
if (this._onceOk) {
if (this._isPromise) {
return Promise.resolve(this._onceValue);
} else {
return this._onceValue;
}
}
throw new Error("ResolveOnce.once impossible");
}
const future = new Future();
this._onceFutures.push(future);
if (this._onceFutures.length === 1) {
const okFn = (value) => {
this._onceValue = value;
this._onceOk = true;
this._onceDone = true;
if (this._isPromise) {
this._onceFutures.forEach((f) => f.resolve(this._onceValue));
}
this._onceFutures.length = 0;
};
const catchFn = (e) => {
this._onceError = e;
this._onceOk = false;
this._onceValue = void 0;
this._onceDone = true;
if (this._isPromise) {
this._onceFutures.forEach((f) => f.reject(this._onceError));
}
this._onceFutures.length = 0;
};
try {
const ret = fn(this.ctx);
if (typeof ret.then === "function") {
this._isPromise = true;
ret.then(okFn).catch(catchFn);
} else {
okFn(ret);
}
} catch (e) {
catchFn(e);
}
}
if (this._isPromise) {
return future.asPromise();
} else {
return this.once(fn);
}
}
};
var Keyed = class {
constructor(factory) {
this._map = /* @__PURE__ */ new Map();
this.factory = factory;
}
async asyncGet(key) {
return this.get(await key());
}
get(key) {
if (typeof key === "function") {
key = key();
}
let keyed = this._map.get(key);
if (!keyed) {
keyed = this.factory(key);
this._map.set(key, keyed);
}
return keyed;
}
unget(key) {
const keyed = this._map.get(key);
keyed == null ? void 0 : keyed.reset();
this._map.delete(key);
}
reset() {
this._map.forEach((keyed) => keyed.reset());
this._map.clear();
}
};
var KeyedResolvOnce = class extends Keyed {
constructor() {
super((key) => new ResolveOnce(key));
}
};
var _node;
_node = /* @__PURE__ */ new WeakMap();
var _deno;
_deno = /* @__PURE__ */ new WeakMap();
var _envFactory = new ResolveOnce();
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/nodes/identity.js
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;
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/visit.js
var BREAK = Symbol("break visit");
var SKIP = Symbol("skip children");
var REMOVE = Symbol("remove node");
function visit(node, visitor) {
const visitor_ = initVisitor(visitor);
if (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 (isNode(ctrl) || isPair(ctrl)) {
replaceNode(key, path, ctrl);
return visit_(key, ctrl, visitor, path);
}
if (typeof ctrl !== "symbol") {
if (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 (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 (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 (isNode(ctrl) || isPair(ctrl)) {
replaceNode(key, path, ctrl);
return visitAsync_(key, ctrl, visitor, path);
}
if (typeof ctrl !== "symbol") {
if (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 (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 (isMap(node))
return visitor.Map?.(key, node, path);
if (isSeq(node))
return visitor.Seq?.(key, node, path);
if (isPair(node))
return visitor.Pair?.(key, node, path);
if (isScalar(node))
return visitor.Scalar?.(key, node, path);
if (isAlias(node))
return visitor.Alias?.(key, node, path);
return void 0;
}
function replaceNode(key, path, node) {
const parent = path[path.length - 1];
if (isCollection(parent)) {
parent.items[key] = node;
} else if (isPair(parent)) {
if (key === "key")
parent.key = node;
else
parent.value = node;
} else if (isDocument(parent)) {
parent.contents = node;
} else {
const pt = isAlias(parent) ? "alias" : "scalar";
throw new Error(`Cannot replace node with ${pt} parent`);
}
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/doc/directives.js
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 parts = line.trim().split(/[ \t]+/);
const name = parts.shift();
switch (name) {
case "%TAG": {
if (parts.length !== 2) {
onError(0, "%TAG directive should contain exactly two parts");
if (parts.length < 2)
return false;
}
const [handle, prefix] = parts;
this.tags[handle] = prefix;
return true;
}
case "%YAML": {
this.yaml.explicit = true;
if (parts.length !== 1) {
onError(0, "%YAML directive should contain exactly one part");
return false;
}
const [version] = parts;
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 && isNode(doc.contents)) {
const tags = {};
visit(doc.contents, (_key, node) => {
if (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:" };
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/doc/anchors.js
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;
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/doc/applyReviver.js
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);
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/nodes/toJS.js
function toJS(value, arg, ctx) {
if (Array.isArray(value))
return value.map((v, i) => toJS(v, String(i), ctx));
if (value && typeof value.toJSON === "function") {
if (!ctx || !hasAnchor(value))
return value.toJSON(arg, ctx);
const data = { aliasCount: 0, count: 1, res: void 0 };
ctx.anchors.set(value, data);
ctx.onCreate = (res2) => {
data.res = res2;
delete ctx.onCreate;
};
const res = value.toJSON(arg, ctx);
if (ctx.onCreate)
ctx.onCreate(res);
return res;
}
if (typeof value === "bigint" && !ctx?.keep)
return Number(value);
return value;
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/nodes/Node.js
var NodeBase = class {
constructor(type) {
Object.defineProperty(this, 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 (!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(this, "", ctx);
if (typeof onAnchor === "function")
for (const { count, res: res2 } of ctx.anchors.values())
onAnchor(res2, count);
return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res;
}
};
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/nodes/Alias.js
var Alias = class extends NodeBase {
constructor(source) {
super(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(doc, {
Node: (_key, node) => {
if (node === this)
return visit.BREAK;
if (node.anchor === this.source)
found = node;
}
});
return found;
}
toJSON(_arg, ctx) {
if (!ctx)
return { source: this.source };
const { anchors, 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 = anchors.get(source);
if (!data) {
toJS(source, null, ctx);
data = anchors.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, anchors);
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) {
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, anchors) {
if (isAlias(node)) {
const source = node.resolve(doc);
const anchor = anchors && source && anchors.get(source);
return anchor ? anchor.count * anchor.aliasCount : 0;
} else if (isCollection(node)) {
let count = 0;
for (const item of node.items) {
const c = getAliasCount(doc, item, anchors);
if (c > count)
count = c;
}
return count;
} else if (isPair(node)) {
const kc = getAliasCount(doc, node.key, anchors);
const vc = getAliasCount(doc, node.value, anchors);
return Math.max(kc, vc);
}
return 1;
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/nodes/Scalar.js
var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object";
var Scalar = class extends NodeBase {
constructor(value) {
super(SCALAR);
this.value = value;
}
toJSON(arg, ctx) {
return ctx?.keep ? this.value : 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";
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/doc/createNode.js
var defaultTagPrefix = "tag:yaml.org,2002:";
function findTagObject(value, 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?.(value) && !t.format);
}
function createNode(value, tagName, ctx) {
if (isDocument(value))
value = value.contents;
if (isNode(value))
return value;
if (isPair(value)) {
const map2 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx);
map2.items.push(value);
return map2;
}
if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) {
value = value.valueOf();
}
const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx;
let ref = void 0;
if (aliasDuplicateObjects && value && typeof value === "object") {
ref = sourceObjects.get(value);
if (ref) {
if (!ref.anchor)
ref.anchor = onAnchor(value);
return new Alias(ref.anchor);
} else {
ref = { anchor: null, node: null };
sourceObjects.set(value, ref);
}
}
if (tagName?.startsWith("!!"))
tagName = defaultTagPrefix + tagName.slice(2);
let tagObj = findTagObject(value, tagName, schema4.tags);
if (!tagObj) {
if (value && typeof value.toJSON === "function") {
value = value.toJSON();
}
if (!value || typeof value !== "object") {
const node2 = new Scalar(value);
if (ref)
ref.node = node2;
return node2;
}
tagObj = value instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value) ? schema4[SEQ] : schema4[MAP];
}
if (onTagObj) {
onTagObj(tagObj);
delete ctx.onTagObj;
}
const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar(value);
if (tagName)
node.tag = tagName;
else if (!tagObj.default)
node.tag = tagObj.tag;
if (ref)
ref.node = node;
return node;
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/nodes/Collection.js
function collectionFromPath(schema4, path, value) {
let v = value;
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(v, void 0, {
aliasDuplicateObjects: false,
keepUndefined: false,
onAnchor: () => {
throw new Error("This should not happen, please report a bug.");
},
schema: schema4,
sourceObjects: /* @__PURE__ */ new Map()
});
}
var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done;
var Collection = class extends NodeBase {
constructor(type, schema4) {
super(type);
Object.defineProperty(this, "schema", {
value: schema4,
configurable: true,
enumerable: false,
writable: true
});
}
/**
* Create a copy of this collection.
*
* @param schema - If defined, overwrites the original's schema
*/
clone(schema4) {
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
if (schema4)
copy.schema = schema4;
copy.items = copy.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : 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, value) {
if (isEmptyPath(path))
this.add(value);
else {
const [key, ...rest] = path;
const node = this.get(key, true);
if (isCollection(node))
node.addIn(rest, value);
else if (node === void 0 && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value));
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 (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 && isScalar(node) ? node.value : node;
else
return isCollection(node) ? node.getIn(rest, keepScalar) : void 0;
}
hasAllNullValues(allowScalar) {
return this.items.every((node) => {
if (!isPair(node))
return false;
const n = node.value;
return n == null || allowScalar && 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 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, value) {
const [key, ...rest] = path;
if (rest.length === 0) {
this.set(key, value);
} else {
const node = this.get(key, true);
if (isCollection(node))
node.setIn(rest, value);
else if (node === void 0 && this.schema)
this.set(key, collectionFromPath(this.schema, rest, value));
else
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
}
}
};
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/stringify/stringifyComment.js
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;
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/stringify/foldFlowLines.js
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;
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/stringify/stringifyString.js
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(value, ctx) {
const json = JSON.stringify(value);
if (ctx.options.doubleQuotedAsJSON)
return json;
const { implicitKey } = ctx;
const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
const indent = ctx.indent || (containsDocumentMarker(value) ? " " : "");
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(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false));
}
function singleQuotedString(value, ctx) {
if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value))
return doubleQuotedString(value, ctx);
const indent = ctx.indent || (containsDocumentMarker(value) ? " " : "");
const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&
${indent}`) + "'";
return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function quotedString(value, ctx) {
const { singleQuote } = ctx.options;
let qs;
if (singleQuote === false)
qs = doubleQuotedString;
else {
const hasDouble = value.includes('"');
const hasSingle = value.includes("'");
if (hasDouble && !hasSingle)
qs = singleQuotedString;
else if (hasSingle && !hasDouble)
qs = doubleQuotedString;
else
qs = singleQuote ? singleQuotedString : doubleQuotedString;
}
return qs(value, ctx);
}
var blockEndNewlines;
try {
blockEndNewlines = new RegExp("(^|(?<!\n))\n+(?!\n|$)", "g");
} catch {
blockEndNewlines = /\n+(?!\n|$)/g;
}
function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
const { blockQuote, commentString, lineWidth } = ctx.options;
if (!blockQuote || /\n[\t ]+$/.test(value) || /^\s*$/.test(value)) {
return quotedString(value, ctx);
}
const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? " " : "");
const literal = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.BLOCK_FOLDED ? false : type === Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, lineWidth, indent.length);
if (!value)
return literal ? "|\n" : ">\n";
let chomp;
let endStart;
for (endStart = value.length; endStart > 0; --endStart) {
const ch = value[endStart - 1];
if (ch !== "\n" && ch !== " " && ch !== " ")
break;
}
let end = value.substring(endStart);
const endNlPos = end.indexOf("\n");
if (endNlPos === -1) {
chomp = "-";
} else if (value === end || endNlPos !== end.length - 1) {
chomp = "+";
if (onChompKeep)
onChompKeep();
} else {
chomp = "";
}
if (end) {
value = value.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 < value.length; ++startEnd) {
const ch = value[startEnd];
if (ch === " ")
startWithSpace = true;
else if (ch === "\n")
startNlPos = startEnd;
else
break;
}
let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
if (start) {
value = value.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) {
value = value.replace(/\n+/g, `$&${indent}`);
return `${header}
${indent}${start}${value}${end}`;
}
value = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
const body = foldFlowLines(`${start}${value}${end}`, indent, FOLD_BLOCK, getFoldOptions(ctx, true));
return `${header}
${indent}${body}`;
}
function plainString(item, ctx, onComment, onChompKeep) {
const { type, value } = item;
const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) {
return quotedString(value, ctx);
}
if (!value || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
}
if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value.includes("\n")) {
return blockString(item, ctx, onComment, onChompKeep);
}
if (containsDocumentMarker(value)) {
if (indent === "") {
ctx.forceBlockIndent = true;
return blockString(item, ctx, onComment, onChompKeep);
} else if (implicitKey && indent === indentStep) {
return quotedString(value, ctx);
}
}
const str = value.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(value, ctx);
}
return implicitKey ? str : foldFlowLines(str, indent, 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.QUOTE_DOUBLE) {
if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
type = Scalar.QUOTE_DOUBLE;
}
const _stringify = (_type) => {
switch (_type) {
case Scalar.BLOCK_FOLDED:
case Scalar.BLOCK_LITERAL:
return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
case Scalar.QUOTE_DOUBLE:
return doubleQuotedString(ss.value, ctx);
case Scalar.QUOTE_SINGLE:
return singleQuotedString(ss.value, ctx);
case 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;
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/stringify/stringify.js
function createStringifyContext(doc, options) {
const opt = Object.assign({
blockQuote: true,
commentString: 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 (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, doc }) {
if (!doc.directives)
return "";
const props = [];
const anchor = (isScalar(node) || isCollection(node)) && node.anchor;
if (anchor && anchorIsValid(anchor)) {
anchors.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 stringify(item, ctx, onComment, onChompKeep) {
if (isPair(item))
return item.toString(ctx, onComment, onChompKeep);
if (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 = 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) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep);
if (!props)
return str;
return isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}
${ctx.indent}${str}`;
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/stringify/stringifyPair.js
function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
let keyComment = isNode(key) && key.comment || null;
if (simpleKeys) {
if (keyComment) {
throw new Error("With simple keys, key nodes cannot have comments");
}
if (isCollection(key) || !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 && value == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === 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 = 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 || value == null) {
if (keyCommentDone && onComment)
onComment();
return str === "" ? "?" : explicitKey ? `? ${str}` : str;
}
} else if (allNullValues && !simpleKeys || value == null && explicitKey) {
str = `? ${str}`;
if (keyComment && !keyCommentDone) {
str += lineComment(str, ctx.indent, commentString(keyComment));
} else if (chompKeep && onChompKeep)
onChompKeep();
return str;
}
if (keyCommentDone)
keyComment = null;
if (explicitKey) {
if (keyComment)
str += lineComment(str, ctx.indent, commentString(keyComment));
str = `? ${str}
${indent}:`;
} else {
str = `${str}:`;
if (keyComment)
str += lineComment(str, ctx.indent, commentString(keyComment));
}
let vsb, vcb, valueComment;
if (isNode(value)) {
vsb = !!value.spaceBefore;
vcb = value.commentBefore;
valueComment = value.comment;
} else {
vsb = false;
vcb = null;
valueComment = null;
if (value && typeof value === "object")
value = doc.createNode(value);
}
ctx.implicitKey = false;
if (!explicitKey && !keyComment && isScalar(value))
ctx.indentAtStart = str.length + 1;
chompKeep = false;
if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value) && !value.flow && !value.tag && !value.anchor) {
ctx.indent = ctx.indent.substring(2);
}
let valueCommentDone = false;
const valueStr = stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true);
let ws = " ";
if (keyComment || vsb || vcb) {
ws = vsb ? "\n" : "";
if (vcb) {
const cs = commentString(vcb);
ws += `
${indentComment(cs, ctx.indent)}`;
}
if (valueStr === "" && !ctx.inFlow) {
if (ws === "\n")
ws = "\n\n";
} else {
ws += `
${ctx.indent}`;
}
} else if (!explicitKey && isCollection(value)) {
const vs0 = valueStr[0];
const nl0 = valueStr.indexOf("\n");
const hasNewline = nl0 !== -1;
const flow = ctx.inFlow ?? value.flow ?? value.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 += lineComment(str, ctx.indent, commentString(valueComment));
} else if (chompKeep && onChompKeep) {
onChompKeep();
}
return str;
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/log.js
function warn(logLevel, warning) {
if (logLevel === "debug" || logLevel === "warn") {
if (typeof process !== "undefined" && process.emitWarning)
process.emitWarning(warning);
else
console.warn(warning);
}
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js
var MERGE_KEY = "<<";
function addPairToJSMap(ctx, map2, { key, value }) {
if (ctx?.doc.schema.merge && isMergeKey(key)) {
value = isAlias(value) ? value.resolve(ctx.doc) : value;
if (isSeq(value))
for (const it of value.items)
mergeToJSMap(ctx, map2, it);
else if (Array.isArray(value))
for (const it of value)
mergeToJSMap(ctx, map2, it);
else
mergeToJSMap(ctx, map2, value);
} else {
const jsKey = toJS(key, "", ctx);
if (map2 instanceof Map) {
map2.set(jsKey, toJS(value, jsKey, ctx));
} else if (map2 instanceof Set) {
map2.add(jsKey);
} else {
const stringKey = stringifyKey(key, jsKey, ctx);
const jsValue = toJS(value, 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 || isScalar(key) && key.value === MERGE_KEY && (!key.type || key.type === Scalar.PLAIN);
function mergeToJSMap(ctx, map2, value) {
const source = ctx && isAlias(value) ? value.resolve(ctx.doc) : value;
if (!isMap(source))
throw new Error("Merge sources must be maps or map aliases");
const srcMap = source.toJSON(null, ctx, Map);
for (const [key, value2] of srcMap) {
if (map2 instanceof Map) {
if (!map2.has(key))
map2.set(key, value2);
} else if (map2 instanceof Set) {
map2.add(key);
} else if (!Object.prototype.hasOwnProperty.call(map2, key)) {
Object.defineProperty(map2, key, {
value: value2,
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 (isNode(key) && ctx?.doc) {
const strCtx = 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) + '..."';
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);
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/nodes/Pair.js
function createPair(key, value, ctx) {
const k = createNode(key, void 0, ctx);
const v = createNode(value, void 0, ctx);
return new Pair(k, v);
}
var Pair = class _Pair {
constructor(key, value = null) {
Object.defineProperty(this, NODE_TYPE, { value: PAIR });
this.key = key;
this.value = value;
}
clone(schema4) {
let { key, value } = this;
if (isNode(key))
key = key.clone(schema4);
if (isNode(value))
value = value.clone(schema4);
return new _Pair(key, value);
}
toJSON(_, ctx) {
const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
return addPairToJSMap(ctx, pair, this);
}
toString(ctx, onComment, onChompKeep) {
return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
}
};
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/stringify/stringifyCollection.js
function stringifyCollection(collection, ctx, options) {
const flow = ctx.inFlow ?? collection.flow;
const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection;
return stringify4(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 (isNode(item)) {
if (!chompKeep && item.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
if (item.comment)
comment2 = item.comment;
} else if (isPair(item)) {
const ik = isNode(item.key) ? item.key : null;
if (ik) {
if (!chompKeep && ik.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
}
}
chompKeep = false;
let str2 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true);
if (comment2)
str2 += 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" + 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 (isNode(item)) {
if (item.spaceBefore)
lines.push("");
addCommentBefore(ctx, lines, item.commentBefore, false);
if (item.comment)
comment = item.comment;
} else if (isPair(item)) {
const ik = 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 = 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 = stringify(item, itemCtx, () => comment = null);
if (i < items.length - 1)
str += ",";
if (comment)
str += 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 = indentComment(commentString(comment), indent);
lines.push(ic.trimStart());
}
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/nodes/YAMLMap.js
function findPair(items, key) {
const k = isScalar(key) ? key.value : key;
for (const it of items) {
if (isPair(it)) {
if (it.key === key || it.key === k)
return it;
if (isScalar(it.key) && it.key.value === k)
return it;
}
}
return void 0;
}
var YAMLMap = class extends Collection {
static get tagName() {
return "tag:yaml.org,2002:map";
}
constructor(schema4) {
super(MAP, schema4);
this.items = [];
}
/**
* A generic collection parsing method that can be extended
* to other node classes that inherit from YAMLMap
*/
static from(schema4, obj, ctx) {
const { keepUndefined, replacer } = ctx;
const map2 = new this(schema4);
const add = (key, value) => {
if (typeof replacer === "function")
value = replacer.call(obj, key, value);
else if (Array.isArray(replacer) && !replacer.includes(key))
return;
if (value !== void 0 || keepUndefined)
map2.items.push(createPair(key, value, ctx));
};
if (obj instanceof Map) {
for (const [key, value] of obj)
add(key, value);
} else if (obj && typeof obj === "object") {
for (const key of Object.keys(obj))
add(key, obj[key]);
}
if (typeof schema4.sortMapEntries === "function") {
map2.items.sort(schema4.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 (isPair(pair))
_pair = pair;
else if (!pair || typeof pair !== "object" || !("key" in pair)) {
_pair = new Pair(pair, pair?.value);
} else
_pair = new 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 (isScalar(prev.value) && 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 && isScalar(node) ? node.value : node) ?? void 0;
}
has(key) {
return !!findPair(this.items, key);
}
set(key, value) {
this.add(new Pair(key, value), 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(ctx, map2, item);
return map2;
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
for (const item of this.items) {
if (!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(this, ctx, {
blockItemPrefix: "",
flowChars: { start: "{", end: "}" },
itemIndent: ctx.indent || "",
onChompKeep,
onComment
});
}
};
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/schema/common/map.js
var map = {
collection: "map",
default: true,
nodeClass: YAMLMap,
tag: "tag:yaml.org,2002:map",
resolve(map2, onError) {
if (!isMap(map2))
onError("Expected a mapping for this tag");
return map2;
},
createNode: (schema4, obj, ctx) => YAMLMap.from(schema4, obj, ctx)
};
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/nodes/YAMLSeq.js
var YAMLSeq = class extends Collection {
static get tagName() {
return "tag:yaml.org,2002:seq";
}
constructor(schema4) {
super(SEQ, schema4);
this.items = [];
}
add(value) {
this.items.push(value);
}
/**
* 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 && 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, value) {
const idx = asItemIndex(key);
if (typeof idx !== "number")
throw new Error(`Expected a valid index, not ${key}.`);
const prev = this.items[idx];
if (isScalar(prev) && isScalarValue(value))
prev.value = value;
else
this.items[idx] = value;
}
toJSON(_, ctx) {
const seq2 = [];
if (ctx?.onCreate)
ctx.onCreate(seq2);
let i = 0;
for (const item of this.items)
seq2.push(toJS(item, String(i++), ctx));
return seq2;
}
toString(ctx, onComment, onChompKeep) {
if (!ctx)
return JSON.stringify(this);
return stringifyCollection(this, ctx, {
blockItemPrefix: "- ",
flowChars: { start: "[", end: "]" },
itemIndent: (ctx.indent || "") + " ",
onChompKeep,
onComment
});
}
static from(schema4, obj, ctx) {
const { replacer } = ctx;
const seq2 = new this(schema4);
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);
}
seq2.items.push(createNode(it, void 0, ctx));
}
}
return seq2;
}
};
function asItemIndex(key) {
let idx = isScalar(key) ? key.value : key;
if (idx && typeof idx === "string")
idx = Number(idx);
return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/schema/common/seq.js
var seq = {
collection: "seq",
default: true,
nodeClass: YAMLSeq,
tag: "tag:yaml.org,2002:seq",
resolve(seq2, onError) {
if (!isSeq(seq2))
onError("Expected a sequence for this tag");
return seq2;
},
createNode: (schema4, obj, ctx) => YAMLSeq.from(schema4, obj, ctx)
};
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/schema/json/schema.js
function intIdentify(value) {
return typeof value === "bigint" || Number.isInteger(value);
}
var stringifyJSON = ({ value }) => JSON.stringify(value);
var jsonScalars = [
{
identify: (value) => typeof value === "string",
default: true,
tag: "tag:yaml.org,2002:str",
resolve: (str) => str,
stringify: stringifyJSON
},
{
identify: (value) => value == null,
createNode: () => new Scalar(null),
default: true,
tag: "tag:yaml.org,2002:null",
test: /^null$/,
resolve: () => null,
stringify: stringifyJSON
},
{
identify: (value) => typeof value === "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 }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
},
{
identify: (value) => typeof value === "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 = [map, seq].concat(jsonScalars, jsonError);
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js
function createPairs(schema4, iterable, ctx) {
const { replacer } = ctx;
const pairs2 = new YAMLSeq(schema4);
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, value;
if (Array.isArray(it)) {
if (it.length === 2) {
key = it[0];
value = 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];
value = it[key];
} else {
throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
}
} else {
key = it;
}
pairs2.items.push(createPair(key, value, ctx));
}
return pairs2;
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js
var YAMLOMap = class _YAMLOMap extends YAMLSeq {
constructor() {
super();
this.add = YAMLMap.prototype.add.bind(this);
this.delete = YAMLMap.prototype.delete.bind(this);
this.get = YAMLMap.prototype.get.bind(this);
this.has = YAMLMap.prototype.has.bind(this);
this.set = 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, value;
if (isPair(pair)) {
key = toJS(pair.key, "", ctx);
value = toJS(pair.value, key, ctx);
} else {
key = toJS(pair, "", ctx);
}
if (map2.has(key))
throw new Error("Ordered maps must not include duplicate keys");
map2.set(key, value);
}
return map2;
}
static from(schema4, iterable, ctx) {
const pairs2 = createPairs(schema4, iterable, ctx);
const omap2 = new this();
omap2.items = pairs2.items;
return omap2;
}
};
YAMLOMap.tag = "tag:yaml.org,2002:omap";
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js
var YAMLSet = class _YAMLSet extends YAMLMap {
constructor(schema4) {
super(schema4);
this.tag = _YAMLSet.tag;
}
add(key) {
let pair;
if (isPair(key))
pair = key;
else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null)
pair = new Pair(key.key, null);
else
pair = new Pair(key, null);
const prev = 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 = findPair(this.items, key);
return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair;
}
set(key, value) {
if (typeof value !== "boolean")
throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
const prev = findPair(this.items, key);
if (prev && !value) {
this.items.splice(this.items.indexOf(prev), 1);
} else if (!prev && value) {
this.items.push(new 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(schema4, iterable, ctx) {
const { replacer } = ctx;
const set2 = new this(schema4);
if (iterable && Symbol.iterator in Object(iterable))
for (let value of iterable) {
if (typeof replacer === "function")
value = replacer.call(iterable, value, value);
set2.items.push(createPair(value, null, ctx));
}
return set2;
}
};
YAMLSet.tag = "tag:yaml.org,2002:set";
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js
function parseSexagesimal(str, asBigInt) {
const sign = str[0];
const parts = sign === "-" || sign === "+" ? str.substring(1) : str;
const num = (n) => asBigInt ? BigInt(n) : Number(n);
const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0));
return sign === "-" ? num(-1) * res : res;
}
var timestamp = {
identify: (value) => value 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 }) => value.toISOString().replace(/((T00:00)?:00)?\.000Z$/, "")
};
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/parse/cst-visit.js
var BREAK2 = Symbol("break visit");
var SKIP2 = Symbol("skip children");
var REMOVE2 = Symbol("remove item");
function visit2(cst, visitor) {
if ("type" in cst && cst.type === "document")
cst = { start: cst.start, value: cst.value };
_visit(Object.freeze([]), cst, visitor);
}
visit2.BREAK = BREAK2;
visit2.SKIP = SKIP2;
visit2.REMOVE = REMOVE2;
visit2.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;
};
visit2.parentCollection = (cst, path) => {
const parent = visit2.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 === BREAK2)
return BREAK2;
else if (ci === REMOVE2) {
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;
}
// node_modules/.pnpm/yaml@2.5.1/node_modules/yaml/browser/dist/parse/lexer.js
var hexDigits = new Set("0123456789ABCDEFabcdef");
var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
var flowIndicatorChars = new Set(",[]{}");
var invalidAnchorChars = new Set(" ,[]{}\n\r ");
// node_modules/.pnpm/@adviser+cement@0.2.41_typescript@5.7.2/node_modules/@adviser/cement/index.js
var Result = class _Result {
static Ok(t) {
return new ResultOK(t);
}
static Err(t) {
if (typeof t === "string") {
return new ResultError(new Error(t));
}
if (_Result.Is(t)) {
if (t.is_ok()) {
return new ResultError(new Error("Result Error is Ok"));
}
return t;
}
return new ResultError(t);
}
static Is(t) {
if (!t) {
return false;
}
if (t instanceof _Result) {
return true;
}
const rt2 = t;
if ([typeof rt2.is_ok, typeof rt2.is_err, typeof rt2.unwrap, typeof rt2.unwrap_err].every((x) => x === "function")) {
return true;
}
return false;
}
isOk() {
return this.is_ok();
}
isErr() {
return this.is_err();
}
Ok() {
return this.unwrap();
}
Err() {
return this.unwrap_err();
}
};
var ResultOK = class extends Result {
constructor(t) {
super();
this._t = t;
}
is_ok() {
return true;
}
is_err() {
return false;
}
unwrap_err() {
throw new Error("Result is Ok");
}
unwrap() {
return this._t;
}
};
var ResultError = class extends Result {
constructor(t) {
super();
this._error = t;
}
is_ok() {
return false;
}
is_err() {
return true;
}
unwrap() {
throw new Error(`Result is Err: ${this._error}`);
}
unwrap_err() {
return this._error;
}
};
function exception2Result(fn) {
try {
const res = fn();
if (res instanceof Promise) {
return res.then((value) => Result.Ok(value)).catch((e) => Result.Err(e));
}
return Result.Ok(res);
} catch (e) {
return Result.Err(e);
}
}
function stripper(strip, obj) {
const strips = Array.isArray(strip) ? strip : [strip];
const restrips = strips.map((s) => {
if (typeof s === "string") {
const escaped = s.replace(/[-\\[\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\^\\$\\|]/g, "\\$&");
return new RegExp(`^${escaped}$`);
}
return s;
});
return localStripper(void 0, restrips, obj);
}
function localStripper(path, restrips, obj) {
if (typeof obj !== "object" || obj === null) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map((i) => localStripper(path, restrips, i));
}
const ret = __spreadValues({}, obj);
const matcher = (key, nextPath) => {
for (const re of restrips) {
if (re.test(key) || re.test(nextPath)) {
return true;
}
}
return false;
};
for (const key in ret) {
if (Object.prototype.hasOwnProperty.call(ret, key)) {
let nextPath;
if (path) {
nextPath = [path, key].join(".");
} else {
nextPath = key;
}
if (matcher(key, nextPath)) {
delete ret[key];
continue;
}
if (typeof ret[key] === "object") {
if (Array.isArray(ret[key])) {
ret[key] = ret[key].reduce((acc, v, i) => {
const toDelete = matcher(key, `${nextPath}[${i}]`);
if (!toDelete) {
acc.push(localStripper(`${nextPath}[${i}]`, restrips, v));
}
return acc;
}, []);
} else {
ret[key] = localStripper(nextPath, restrips, ret[key]);
}
}
}
}
return ret;
}
function coerceKey(key, def) {
if (typeof key === "object") {
const keys = Object.keys(key);
if (keys.length !== 1) {
throw new Error(`Invalid key: ${JSON.stringify(key)}`);
}
return { key: keys[0], def: key[keys[0]] };
}
return { key, def };
}
function falsy2undef(value) {
return value === void 0 || value === null ? void 0 : value;
}
function ensureURLWithDefaultProto(url, defaultProtocol) {
if (!url) {
return new MutableURL(`${defaultProtocol}//`);
}
if (typeof url === "string") {
try {
return new MutableURL(url);
} catch (e) {
return new MutableURL(`${defaultProtocol}//${url}`);
}
} else {
return new MutableURL(url.toString());
}
}
function isURL(value) {
return value instanceof URL || !!value && typeof value.searchParams === "object" && typeof value.searchParams.sort === "function" && typeof value.hash === "string";
}
var MutableURL = class _MutableURL extends URL {
constructor(urlStr) {
super("defect://does.not.exist");
const partedURL = urlStr.split(":");
this._hasHostpart = hasHostPartProtocols.has(partedURL[0]);
let hostPartUrl = ["http", ...partedURL.slice(1)].join(":");
if (!this._hasHostpart) {
const pathname = hostPartUrl.replace(/http:\/\/[/]*/, "").replace(/[#?].*$/, "");
hostPartUrl = hostPartUrl.replace(/http:\/\//, `http://localhost/${pathname}`);
}
try {
this._sysURL = new URL(hostPartUrl);
} catch (ie) {
const e = ie;
e.message = `${e.message} for URL: ${urlStr}`;
throw e;
}
this._protocol = `${partedURL[0]}:`;
if (this._hasHostpart) {
this._pathname = this._sysURL.pathname;
} else {
this._pathname = urlStr.replace(new RegExp(`^${this._protocol}//`), "").replace(/[#?].*$/, "");
}
this.hash = this._sysURL.hash;
}
clone() {
return new _MutableURL(this.toString());
}
get host() {
if (!this._hasHostpart) {
throw new Error(
`you can use hostname only if protocol is ${this.toString()} ${JSON.stringify(Array.from(hasHostPartProtocols.keys()))}`
);
}
return this._sysURL.host;
}
get port() {
if (!this._hasHostpart) {
throw new Error(`you can use hostname only if protocol is ${JSON.stringify(Array.from(hasHostPartProtocols.keys()))}`);
}
return this._sysURL.port;
}
set port(p) {
if (!this._hasHostpart) {
throw new Error(`you can use port only if protocol is ${JSON.stringify(Array.from(hasHostPartProtocols.keys()))}`);
}
this._sysURL.port = p;
}
get hostname() {
if (!this._hasHostpart) {
throw new Error(`you can use hostname only if protocol is ${JSON.stringify(Array.from(hasHostPartProtocols.keys()))}`);
}
return this._sysURL.hostname;
}
set hostname(h) {
if (!this._hasHostpart) {
throw new Error(`you can use hostname only if protocol is ${JSON.stringify(Array.from(hasHostPartProtocols.keys()))}`);
}
this._sysURL.hostname = h;
}
set pathname(p) {
this._pathname = p;
}
get pathname() {
return this._pathname;
}
get protocol() {
return this._protocol;
}
set protocol(p) {
if (!p.endsWith(":")) {
p = `${p}:`;
}
this._protocol = p;
}
get searchParams() {
return this._sysURL.searchParams;
}
toString() {
let search = "";
if (this._sysURL.searchParams.size) {
for (const [key, value] of Array.from(this._sysURL.searchParams.entries()).sort((a, b) => a[0].localeCompare(b[0]))) {
search += `${!search.length ? "?" : "&"}${key}=${encodeURIComponent(value)}`;
}
}
let hostpart = "";
if (this._hasHostpart) {
hostpart = this._sysURL.hostname;
if (this._sysURL.port) {
hostpart += `:${this._sysURL.port}`;
}
if (!this._pathname.startsWith("/")) {
hostpart += "/";
}
}
return `${this._protocol}//${hostpart}${this._pathname}${search}`;
}
};
function from(fac, strURLUri, defaultProtocol) {
switch (typeof falsy2undef(strURLUri)) {
case "undefined":
return fac(new MutableURL(`${defaultProtocol}///`));
case "string":
return fac(ensureURLWithDefaultProto(strURLUri, defaultProtocol));
case "object":
if (BuildURI.is(strURLUri)) {
return fac(new MutableURL(strURLUri._url.toString()));
} else if (URI.is(strURLUri)) {
return fac(new MutableURL(strURLUri._url.toString()));
} else if (isURL(strURLUri)) {
return fac(new MutableURL(strURLUri.toString()));
}
throw new Error(`unknown object type: ${strURLUri}`);
default:
throw new Error(`Invalid argument: ${typeof strURLUri}`);
}
}
function getParamResult(key, val, msgFn = (key2) => {
return `missing parameter: ${key2}`;
}) {
if (val === void 0) {
return Result.Err(msgFn(key));
}
return Result.Ok(val);
}
function getParamsResult(keys, getParam) {
const keyDef = keys.flat().reduce(
(acc, i) => {
if (typeof i === "string") {
acc.push({ key: i });
} else if (typeof i === "object") {
acc.push(...Object.keys(i).map((k) => ({ key: k, def: typeof i[k] === "string" ? i[k] : void 0 })));
}
return acc;
},
[]
);
const msgFn = keys.find((k) => typeof k === "function") || ((...keys2) => {
const msg = keys2.join(",");
return `missing parameters: ${msg}`;
});
const errors = [];
const result = {};
for (const kd of keyDef) {
const val = getParam.getParam(kd.key);
if (val === void 0) {
if (typeof kd.def === "string") {
result[kd.key] = kd.def;
} else {
errors.push(kd.key);
}
} else {
result[kd.key] = val;
}
}
if (errors.length) {
return Result.Err(msgFn(...errors));
}
return Result.Ok(result);
}
var BuildURI = class _BuildURI {
// pathname needs this
constructor(url) {
this._url = url;
}
static is(value) {
return value instanceof _BuildURI || !!value && typeof value.delParam === "function" && typeof value.setParam === "function";
}
static from(strURLUri, defaultProtocol = "file:") {
return from((url) => new _BuildURI(url), strURLUri, defaultProtocol);
}
port(p) {
this._url.port = p;
return this;
}
hostname(h) {
this._url.hostname = h;
return this;
}
protocol(p) {
if (!p.endsWith(":")) {
p = `${p}:`;
}
this._url.protocol = p;
return this;
}
pathname(p) {
this._url.pathname = p;
return this;
}
appendRelative(p) {
const appendUrl = URI.from(p);
let pathname = appendUrl.pathname;
let basePath = this._url.pathname;
if (pathname.startsWith("/")) {
pathname = pathname.replace(/^\//, "");
}
if (basePath.length > 0) {
basePath = basePath.replace(/\/$/, "");
}
this.pathname(basePath + "/" + pathname);
for (const [key, value] of appendUrl.getParams) {
this.setParam(key, value);
}
return this;
}
cleanParams() {
for (const key of Array.from(this._url.searchParams.keys())) {
this._url.searchParams.delete(key);
}
return this;
}
delParam(key) {
this._url.searchParams.delete(key);
return this;
}
defParam(key, str) {
if (!this._url.searchParams.has(key)) {
this._url.searchParams.set(key, str);
}
return this;
}
setParam(key, str) {
this._url.searchParams.set(key, str);
return this;
}
hasParam(key) {
return this._url.searchParams.has(key);
}
get getParams() {
return this._url.searchParams.entries();
}
getParam(key, def) {
const { key: k, def: d } = coerceKey(key, def);
let val = this._url.searchParams.get(k);
if (!falsy2undef(val) && d) {
val = d;
}
return falsy2undef(val);
}
getParamResult(key, msgFn) {
return getParamResult(key, this.getParam(key), msgFn);
}
getParamsResult(...keys) {
return getParamsResult(keys, this);
}
toString() {
this._url.searchParams.sort();
return this._url.toString();
}
toJSON() {
return this.toString();
}
asURL() {
return this.URI().asURL();
}
asObj(...strips) {
return this.URI().asObj(...strips);
}
clone() {
return _BuildURI.from(this.toString());
}
URI() {
return URI.from(this._url);
}
};
var hasHostPartProtocols = /* @__PURE__ */ new Set(["http", "https", "ws", "wss"]);
var URI = class _URI {
static protocolHasHostpart(protocol) {
protocol = protocol.replace(/:$/, "");
hasHostPartProtocols.add(protocol);
return () => {
hasHostPartProtocols.delete(protocol);
};
}
// if no protocol is provided, default to file:
static merge(into, from2, defaultProtocol = "file:") {
const intoUrl = BuildURI.from(into, defaultProtocol);
const fromUrl = _URI.from(from2, defaultProtocol);
intoUrl.protocol(fromUrl.protocol);
const fPath = fromUrl.pathname;
if (!(fPath.length === 0 || fPath === "/" || fPath === "./")) {
intoUrl.pathname(fromUrl.pathname);
}
for (const [key, value] of fromUrl.getParams) {
intoUrl.setParam(key, value);
}
return intoUrl.URI();
}
static is(value) {
return value instanceof _URI || !!value && typeof value.asURL === "function" && typeof value.getParam === "function" && typeof value.hasParam === "function";
}
// if no protocol is provided, default to file:
static from(strURLUri, defaultProtocol = "file:") {
return from((url) => new _URI(url), strURLUri, defaultProtocol);
}
static fromResult(strURLUri, defaultProtocol = "file:") {
return exception2Result(() => from((url) => new _URI(url), strURLUri, defaultProtocol));
}
constructor(url) {
this._url = url.clone();
}
build() {
return BuildURI.from(this._url);
}
get hostname() {
return this._url.hostname;
}
// get password(): string {
// return this._url.password;
// }
get port() {
return this._url.port;
}
get host() {
return this._url.host;
}
// get username(): string {
// return this._url.username;
// }
// get search(): string {
// return this._url.search;
// }
get protocol() {
return this._url.protocol;
}
get pathname() {
return this._url.pathname;
}
// get hash(): string {
// return this._url.hash;
// }
// get host(): string {
// return this._url.host;
// }
get getParams() {
return this._url.searchParams.entries();
}
hasParam(key) {
return this._url.searchParams.has(key);
}
getParam(key, def) {
const { key: k, def: d } = coerceKey(key, def);
let val = this._url.searchParams.get(k);
if (!falsy2undef(val) && d) {
val = d;
}
return falsy2undef(val);
}
getParamResult(key, msgFn) {
return getParamResult(key, this.getParam(key), msgFn);
}
getParamsResult(...keys) {
return getParamsResult(keys, this);
}
clone() {
return new _URI(this._url);
}
asURL() {
return this._url.clone();
}
toString() {
return this._url.toString();
}
toJSON() {
return this.toString();
}
asObj(...strips) {
const pathURI = {
style: "path",
protocol: this.protocol,
pathname: this.pathname,
searchParams: Object.fromEntries(this.getParams)
};
if (hasHostPartProtocols.has(this.protocol.replace(/:$/, ""))) {
return stripper(strips, __spreadProps(__spreadValues({}, pathURI), {
style: "host",
hostname: this.hostname,
port: this.port
}));
}
return stripper(strips, pathURI);
}
};
function isSet(value, ref = globalThis) {
const [head, ...tail] = value.split(".");
if (["object", "function"].includes(typeof ref) && ref && ["object", "function"].includes(typeof ref[head]) && ref[head]) {
if (tail.length <= 1) {
return true;
}
return isSet(tail.join("."), ref[head]);
}
return false;
}
function runtimeFn() {
const gt = globalThis;
const isReactNative = isSet("navigator.product") && typeof gt["navigator"] === "object" && gt["navigator"]["product"] === "ReactNative";
let isNodeIsh = false;
if (!isSet("Deno")) {
isNodeIsh = isSet("process.versions.node") && !isReactNative;
}
const isDeno = isSet("Deno");
return {
isNodeIsh,
isBrowser: !(isNodeIsh || isDeno) && !isReactNative,
isDeno,
isReactNative
};
}
var Option = class _Option {
static Some(t) {
return new Some(t);
}
static None() {
return new None();
}
static Is(t) {
return t instanceof _Option;
}
static From(t) {
if (!t) {
return new None();
}
return new Some(t);
}
IsNone() {
return this.is_none();
}
IsSome() {
return this.is_some();
}
Unwrap() {
return this.unwrap();
}
};
var Some = class extends Option {
constructor(_t) {
super();
this._t = _t;
}
is_none() {
return false;
}
is_some() {
return true;
}
unwrap() {
return this._t;
}
};
var None = class extends Option {
is_none() {
return true;
}
is_some() {
return false;
}
unwrap() {
throw new Error("None.unwrap");
}
};
var LevelHandlerImpl = class {
constructor() {
this._globalLevels = /* @__PURE__ */ new Set([
"info",
"error",
"warn"
/* WARN */
]);
this._modules = /* @__PURE__ */ new Map();
this.ignoreAttr = Option.Some(/^_/);
this.isStackExposed = false;
}
enableLevel(level, ...modules) {
if (modules.length == 0) {
this._globalLevels.add(level);
return;
}
this.forModules(
level,
(p) => {
this._modules.set(p, /* @__PURE__ */ new Set([...this._globalLevels, level]));
},
...modules
);
}
disableLevel(level, ...modules) {
if (modules.length == 0) {
this._globalLevels.delete(level);
return;
}
this.forModules(
level,
(p) => {
this._modules.delete(p);
},
...modules
);
}
setExposeStack(enable) {
this.isStackExposed = !!enable;
}
setIgnoreAttr(re) {
this.ignoreAttr = Option.From(re);
}
forModules(level, fnAction, ...modules) {
for (const m of modules.flat()) {
if (typeof m !== "string") {
continue;
}
const parts = m.split(",").map((s) => s.trim()).filter((s) => s.length);
for (const p of parts) {
fnAction(p);
}
}
}
setDebug(...modules) {
this.forModules(
"debug",
(p) => {
this._modules.set(p, /* @__PURE__ */ new Set([
...this._globalLevels,
"debug"
/* DEBUG */
]));
},
...modules
);
}
isEnabled(ilevel, module) {
const level = ilevel;
if (typeof module === "string") {
const levels = this._modules.get(module);
if (levels && levels.has(level)) {
return true;
}
}
const wlevel = this._modules.get("*");
if (wlevel && typeof level === "string") {
if (wlevel.has(level)) {
return true;
}
}
if (typeof level !== "string") {
return true;
}
return this._globalLevels.has(level);
}
};
var levelSingleton = new LevelHandlerImpl();
var VERSION = Object.keys({
__packageVersion__: "xxxx"
})[0];
// src/bundle-not-impl.ts
var err = new Error("store-file not implemented");
console.error(err.stack);
throw err;
// src/connection-from-store.ts
var ConnectionFromStore = class extends (void 0).ConnectionBase {
constructor(sthis, url) {
const logger = (void 0)(sthis, "ConnectionFromStore", {
url: () => url.toString(),
this: 1,
log: 1
});
super(url, logger);
this.stores = void 0;
this.sthis = sthis;
}
async onConnect() {
this.logger.Debug().Msg("onConnect-start");
const stores = {
base: this.url
// data: this.urlData,
// meta: this.urlMeta,
};
const rName = this.url.getParamResult("name");
if (rName.isErr()) {
throw this.logger.Error().Err(rName).Msg("missing Parameter").AsError();
}
const storeRuntime = (void 0).toStoreRuntime({ stores }, this.sthis);
const loader = {
name: rName.Ok(),
ebOpts: {
logger: this.logger,
store: { stores },
storeRuntime
},
sthis: this.sthis
};
this.stores = {
data: await storeRuntime.makeDataStore(loader),
meta: await storeRuntime.makeMetaStore(loader)
};
this.logger.Debug().Msg("onConnect-done");
return;
}
};
function connectionFactory(sthis, iurl) {
return new ConnectionFromStore(sthis, URI.from(iurl));
}
function makeKeyBagUrlExtractable(sthis) {
let base = sthis.env.get("FP_KEYBAG_URL");
if (!base) {
if (runtimeFn().isBrowser) {
base = "indexdb://fp-keybag";
} else {
base = "file://./dist/kb-dir-partykit";
}
}
const kbUrl = BuildURI.from(base);
kbUrl.defParam("extractKey", "_deprecated_internal_api");
sthis.env.set("FP_KEYBAG_URL", kbUrl.toString());
sthis.logger.Debug().Url(kbUrl, "keyBagUrl").Msg("Make keybag url extractable");
}
// node_modules/.pnpm/partysocket@1.0.2/node_modules/partysocket/dist/chunk-4SNNYC7I.mjs
if (!globalThis.EventTarget || !globalThis.Event) {
console.error(`
PartySocket requires a global 'EventTarget' class to be available!
You can polyfill this global by adding this to your code before any partysocket imports:
\`\`\`
import 'partysocket/event-target-polyfill';
\`\`\`
Please file an issue at https://github.com/partykit/partykit if you're still having trouble.
`);
}
var ErrorEvent = class extends Event {
message;
error;
constructor(error, target) {
super("error", target);
this.message = error.message;
this.error = error;
}
};
var CloseEvent = class extends Event {
code;
reason;
wasClean = true;
constructor(code = 1e3, reason = "", target) {
super("close", target);
this.code = code;
this.reason = reason;
}
};
var Events = {
Event,
ErrorEvent,
CloseEvent
};
function assert(condition, msg) {
if (!condition) {
throw new Error(msg);
}
}
function cloneEventBrowser(e) {
return new e.constructor(e.type, e);
}
function cloneEventNode(e) {
if ("data" in e) {
const evt2 = new MessageEvent(e.type, e);
return evt2;
}
if ("code" in e || "reason" in e) {
const evt2 = new CloseEvent(
// @ts-expect-error we need to fix event/listener types
e.code || 1999,
// @ts-expect-error we need to fix event/listener types
e.reason || "unknown reason",
e
);
return evt2;
}
if ("error" in e) {
const evt2 = new ErrorEvent(e.error, e);
return evt2;
}
const evt = new Event(e.type, e);
return evt;
}
var isNode2 = typeof process !== "undefined" && typeof process.versions?.node !== "undefined" && typeof document === "undefined";
var cloneEvent = isNode2 ? cloneEventNode : cloneEventBrowser;
var DEFAULT = {
maxReconnectionDelay: 1e4,
minReconnectionDelay: 1e3 + Math.random() * 4e3,
minUptime: 5e3,
reconnectionDelayGrowFactor: 1.3,
connectionTimeout: 4e3,
maxRetries: Infinity,
maxEnqueuedMessages: Infinity,
startClosed: false,
debug: false
};
var didWarnAboutMissingWebSocket = false;
var ReconnectingWebSocket = class _ReconnectingWebSocket extends EventTarget {
_ws;
_retryCount = -1;
_uptimeTimeout;
_connectTimeout;
_shouldReconnect = true;
_connectLock = false;
_binaryType = "blob";
_closeCalled = false;
_messageQueue = [];
_debugLogger = console.log.bind(console);
_url;
_protocols;
_options;
constructor(url, protocols, options = {}) {
super();
this._url = url;
this._protocols = protocols;
this._options = options;
if (this._options.startClosed) {
this._shouldReconnect = false;
}
if (this._options.debugLogger) {
this._debugLogger = this._options.debugLogger;
}
this._connect();
}
static get CONNECTING() {
return 0;
}
static get OPEN() {
return 1;
}
static get CLOSING() {
return 2;
}
static get CLOSED() {
return 3;
}
get CONNECTING() {
return _ReconnectingWebSocket.CONNECTING;
}
get OPEN() {
return _ReconnectingWebSocket.OPEN;
}
get CLOSING() {
return _ReconnectingWebSocket.CLOSING;
}
get CLOSED() {
return _ReconnectingWebSocket.CLOSED;
}
get binaryType() {
return this._ws ? this._ws.binaryType : this._binaryType;
}
set binaryType(value) {
this._binaryType = value;
if (this._ws) {
this._ws.binaryType = value;
}
}
/**
* Returns the number or connection retries
*/
get retryCount() {
return Math.max(this._retryCount, 0);
}
/**
* The number of bytes of data that have been queued using calls to send() but not yet
* transmitted to the network. This value resets to zero once all queued data has been sent.
* This value does not reset to zero when the connection is closed; if you keep calling send(),
* this will continue to climb. Read only
*/
get bufferedAmount() {
const bytes = this._messageQueue.reduce((acc, message) => {
if (typeof message === "string") {
acc += message.length;
} else if (message instanceof Blob) {
acc += message.size;
} else {
acc += message.byteLength;
}
return acc;
}, 0);
return bytes + (this._ws ? this._ws.bufferedAmount : 0);
}
/**
* The extensions selected by the server. This is currently only the empty string or a list of
* extensions as negotiated by the connection
*/
get extensions() {
return this._ws ? this._ws.extensions : "";
}
/**
* A string indicating the name of the sub-protocol the server selected;
* this will be one of the strings specified in the protocols parameter when creating the
* WebSocket object
*/
get protocol() {
return this._ws ? this._ws.protocol : "";
}
/**
* The current state of the connection; this is one of the Ready state constants
*/
get readyState() {
if (this._ws) {
return this._ws.readyState;
}
return this._options.startClosed ? _ReconnectingWebSocket.CLOSED : _ReconnectingWebSocket.CONNECTING;
}
/**
* The URL as resolved by the constructor
*/
get url() {
return this._ws ? this._ws.url : "";
}
/**
* Whether the websocket object is now in reconnectable state
*/
get shouldReconnect() {
return this._shouldReconnect;
}
/**
* An event listener to be called when the WebSocket connection's readyState changes to CLOSED
*/
onclose = null;
/**
* An event listener to be called when an error occurs
*/
onerror = null;
/**
* An event listener to be called when a message is received from the server
*/
onmessage = null;
/**
* An event listener to be called when the WebSocket connection's readyState changes to OPEN;
* this indicates that the connection is ready to send and receive data
*/
onopen = null;
/**
* Closes the WebSocket connection or connection attempt, if any. If the connection is already
* CLOSED, this method does nothing
*/
close(code = 1e3, reason) {
this._closeCalled = true;
this._shouldReconnect = false;
this._clearTimeouts();
if (!this._ws) {
this._debug("close enqueued: no ws instance");
return;
}
if (this._ws.readyState === this.CLOSED) {
this._debug("close: already closed");
return;
}
this._ws.close(code, reason);
}
/**
* Closes the WebSocket connection or connection attempt and connects again.
* Resets retry counter;
*/
reconnect(code, reason) {
this._shouldReconnect = true;
this._closeCalled = false;
this._retryCount = -1;
if (!this._ws || this._ws.readyState === this.CLOSED) {
this._connect();
} else {
this._disconnect(code, reason);
this._connect();
}
}
/**
* Enqueue specified data to be transmitted to the server over the WebSocket connection
*/
send(data) {
if (this._ws && this._ws.readyState === this.OPEN) {
this._debug("send", data);
this._ws.send(data);
} else {
const { maxEnqueuedMessages = DEFAULT.maxEnqueuedMessages } = this._options;
if (this._messageQueue.length < maxEnqueuedMessages) {
this._debug("enqueue", data);
this._messageQueue.push(data);
}
}
}
_debug(...args) {
if (this._options.debug) {
this._debugLogger("RWS>", ...args);
}
}
_getNextDelay() {
const {
reconnectionDelayGrowFactor = DEFAULT.reconnectionDelayGrowFactor,
minReconnectionDelay = DEFAULT.minReconnectionDelay,
maxReconnectionDelay = DEFAULT.maxReconnectionDelay
} = this._options;
let delay = 0;
if (this._retryCount > 0) {
delay = minReconnectionDelay * Math.pow(reconnectionDelayGrowFactor, this._retryCount - 1);
if (delay > maxReconnectionDelay) {
delay = maxReconnectionDelay;
}
}
this._debug("next delay", delay);
return delay;
}
_wait() {
return new Promise((resolve) => {
setTimeout(resolve, this._getNextDelay());
});
}
_getNextProtocols(protocolsProvider) {
if (!protocolsProvider) return Promise.resolve(null);
if (typeof protocolsProvider === "string" || Array.isArray(protocolsProvider)) {
return Promise.resolve(protocolsProvider);
}
if (typeof protocolsProvider === "function") {
const protocols = protocolsProvider();
if (!protocols) return Promise.resolve(null);
if (typeof protocols === "string" || Array.isArray(protocols)) {
return Promise.resolve(protocols);
}
if (protocols.then) {
return protocols;
}
}
throw Error("Invalid protocols");
}
_getNextUrl(urlProvider) {
if (typeof urlProvider === "string") {
return Promise.resolve(urlProvider);
}
if (typeof urlProvider === "function") {
const url = urlProvider();
if (typeof url === "string") {
return Promise.resolve(url);
}
if (url.then) {
return url;
}
}
throw Error("Invalid URL");
}
_connect() {
if (this._connectLock || !this._shouldReconnect) {
return;
}
this._connectLock = true;
const {
maxRetries = DEFAULT.maxRetries,
connectionTimeout = DEFAULT.connectionTimeout
} = this._options;
if (this._retryCount >= maxRetries) {
this._debug("max retries reached", this._retryCount, ">=", maxRetries);
return;
}
this._retryCount++;
this._debug("connect", this._retryCount);
this._removeListeners();
this._wait().then(
() => Promise.all([
this._getNextUrl(this._url),
this._getNextProtocols(this._protocols || null)
])
).then(([url, protocols]) => {
if (this._closeCalled) {
this._connectLock = false;
return;
}
if (!this._options.WebSocket && typeof WebSocket === "undefined" && !didWarnAboutMissingWebSocket) {
console.error(`\u203C\uFE0F No WebSocket implementation available. You should define options.WebSocket.
For example, if you're using node.js, run \`npm install ws\`, and then in your code:
import PartySocket from 'partysocket';
import WS from 'ws';
const partysocket = new PartySocket({
host: "127.0.0.1:1999",
room: "test-room",
WebSocket: WS
});
`);
didWarnAboutMissingWebSocket = true;
}
const WS = this._options.WebSocket || WebSocket;
this._debug("connect", { url, protocols });
this._ws = protocols ? new WS(url, protocols) : new WS(url);
this._ws.binaryType = this._binaryType;
this._connectLock = false;
this._addListeners();
this._connectTimeout = setTimeout(
() => this._handleTimeout(),
connectionTimeout
);
}).catch((err2) => {
this._connectLock = false;
this._handleError(new Events.ErrorEvent(Error(err2.message), this));
});
}
_handleTimeout() {
this._debug("timeout event");
this._handleError(new Events.ErrorEvent(Error("TIMEOUT"), this));
}
_disconnect(code = 1e3, reason) {
this._clearTimeouts();
if (!this._ws) {
return;
}
this._removeListeners();
try {
this._ws.close(code, reason);
this._handleClose(new Events.CloseEvent(code, reason, this));
} catch (error) {
}
}
_acceptOpen() {
this._debug("accept open");
this._retryCount = 0;
}
_handleOpen = (event) => {
this._debug("open event");
const { minUptime = DEFAULT.minUptime } = this._options;
clearTimeout(this._connectTimeout);
this._uptimeTimeout = setTimeout(() => this._acceptOpen(), minUptime);
assert(this._ws, "WebSocket is not defined");
this._ws.binaryType = this._binaryType;
this._messageQueue.forEach((message) => this._ws?.send(message));
this._messageQueue = [];
if (this.onopen) {
this.onopen(event);
}
this.dispatchEvent(cloneEvent(event));
};
_handleMessage = (event) => {
this._debug("message event");
if (this.onmessage) {
this.onmessage(event);
}
this.dispatchEvent(cloneEvent(event));
};
_handleError = (event) => {
this._debug("error event", event.message);
this._disconnect(
void 0,
event.message === "TIMEOUT" ? "timeout" : void 0
);
if (this.onerror) {
this.onerror(event);
}
this._debug("exec error listeners");
this.dispatchEvent(cloneEvent(event));
this._connect();
};
_handleClose = (event) => {
this._debug("close event");
this._clearTimeouts();
if (this._shouldReconnect) {
this._connect();
}
if (this.onclose) {
this.onclose(event);
}
this.dispatchEvent(cloneEvent(event));
};
_removeListeners() {
if (!this._ws) {
return;
}
this._debug("removeListeners");
this._ws.removeEventListener("open", this._handleOpen);
this._ws.removeEventListener("close", this._handleClose);
this._ws.removeEventListener("message", this._handleMessage);
this._ws.removeEventListener("error", this._handleError);
}
_addListeners() {
if (!this._ws) {
return;
}
this._debug("addListeners");
this._ws.addEventListener("open", this._handleOpen);
this._ws.addEventListener("close", this._handleClose);
this._ws.addEventListener("message", this._handleMessage);
this._ws.addEventListener("error", this._handleError);
}
_clearTimeouts() {
clearTimeout(this._connectTimeout);
clearTimeout(this._uptimeTimeout);
}
};
// node_modules/.pnpm/partysocket@1.0.2/node_modules/partysocket/dist/chunk-H3IJA3WK.mjs
var valueIsNotNil = (keyValuePair) => keyValuePair[1] !== null && keyValuePair[1] !== void 0;
function generateUUID() {
if (typeof crypto !== "undefined" && crypto.randomUUID) {
return crypto.randomUUID();
}
let d = (/* @__PURE__ */ new Date()).getTime();
let d2 = typeof performance !== "undefined" && performance.now && performance.now() * 1e3 || 0;
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
let r = Math.random() * 16;
if (d > 0) {
r = (d + r) % 16 | 0;
d = Math.floor(d / 16);
} else {
r = (d2 + r) % 16 | 0;
d2 = Math.floor(d2 / 16);
}
return (c === "x" ? r : r & 3 | 8).toString(16);
});
}
function getPartyInfo(partySocketOptions, defaultProtocol, defaultParams = {}) {
const {
host: rawHost,
path: rawPath,
protocol: rawProtocol,
room,
party,
prefix,
query
} = partySocketOptions;
let host = rawHost.replace(/^(http|https|ws|wss):\/\//, "");
if (host.endsWith("/")) {
host = host.slice(0, -1);
}
if (rawPath && rawPath.startsWith("/")) {
throw new Error("path must not start with a slash");
}
const name = party ?? "main";
const path = rawPath ? `/${rawPath}` : "";
const protocol = rawProtocol || (host.startsWith("localhost:") || host.startsWith("127.0.0.1:") || host.startsWith("192.168.") || host.startsWith("10.") || host.startsWith("172.") && host.split(".")[1] >= "16" && host.split(".")[1] <= "31" || host.startsWith("[::ffff:7f00:1]:") ? (
// http / ws
defaultProtocol
) : (
// https / wss
defaultProtocol + "s"
));
const baseUrl = `${protocol}://${host}/${prefix || `parties/${name}/${room}`}${path}`;
const makeUrl = (query2 = {}) => `${baseUrl}?${new URLSearchParams([
...Object.entries(defaultParams),
...Object.entries(query2).filter(valueIsNotNil)
])}`;
const urlProvider = typeof query === "function" ? async () => makeUrl(await query()) : makeUrl(query);
return {
host,
path,
room,
name,
protocol,
partyUrl: baseUrl,
urlProvider
};
}
var PartySocket = class extends ReconnectingWebSocket {
constructor(partySocketOptions) {
const wsOptions = getWSOptions(partySocketOptions);
super(wsOptions.urlProvider, wsOptions.protocols, wsOptions.socketOptions);
this.partySocketOptions = partySocketOptions;
this.setWSProperties(wsOptions);
}
_pk;
_pkurl;
name;
room;
host;
path;
updateProperties(partySocketOptions) {
const wsOptions = getWSOptions({
...this.partySocketOptions,
...partySocketOptions,
host: partySocketOptions.host ?? this.host,
room: partySocketOptions.room ?? this.room,
path: partySocketOptions.path ?? this.path
});
this._url = wsOptions.urlProvider;
this._protocols = wsOptions.protocols;
this._options = wsOptions.socketOptions;
this.setWSProperties(wsOptions);
}
setWSProperties(wsOptions) {
const { _pk, _pkurl, name, room, host, path } = wsOptions;
this._pk = _pk;
this._pkurl = _pkurl;
this.name = name;
this.room = room;
this.host = host;
this.path = path;
}
reconnect(code, reason) {
if (!this.room || !this.host) {
throw new Error(
"The room and host must be set before connecting, use `updateProperties` method to set them or pass them to the constructor."
);
}
super.reconnect(code, reason);
}
get id() {
return this._pk;
}
/**
* Exposes the static PartyKit room URL without applying query parameters.
* To access the currently connected WebSocket url, use PartySocket#url.
*/
get roomUrl() {
return this._pkurl;
}
// a `fetch` method that uses (almost) the same options as `PartySocket`
static async fetch(options, init) {
const party = getPartyInfo(options, "http");
const url = typeof party.urlProvider === "string" ? party.urlProvider : await party.urlProvider();
const doFetch = options.fetch ?? fetch;
return doFetch(url, init);
}
};
function getWSOptions(partySocketOptions) {
const {
id,
host: _host,
path: _path,
party: _party,
room: _room,
protocol: _protocol,
query: _query,
protocols,
...socketOptions
} = partySocketOptions;
const _pk = id || generateUUID();
const party = getPartyInfo(partySocketOptions, "ws", { _pk });
return {
_pk,
_pkurl: party.partyUrl,
name: party.name,
room: party.room,
host: party.host,
path: party.path,
protocols,
socketOptions,
urlProvider: party.urlProvider
};
}
// src/cloud/gateway.ts
var FireproofCloudGateway = class {
constructor(sthis) {
this.subscriberCallbacks = /* @__PURE__ */ new Set();
this.sthis = sthis;
this.id = sthis.nextId().str;
this.logger = (void 0)(sthis, "FireproofCloudGateway", {
url: () => this.url?.toString(),
this: this.id
});
this.logger.Debug().Msg("constructor");
}
async buildUrl(baseUrl, key) {
return Result.Ok(baseUrl.build().setParam("key", key).URI());
}
async start(uri) {
this.logger.Debug().Msg("Starting FireproofCloudGateway with URI: " + uri.toString());
await this.sthis.start();
this.url = uri;
const ret = uri.build().defParam("version", "v0.1-fireproof-cloud");
const rName = uri.getParamResult("name");
if (rName.isErr()) {
return this.logger.Error().Err(rName).Msg("name not found").ResultError();
}
let dbName = rName.Ok();
if (this.url.hasParam("index")) {
dbName = dbName + "-idx";
}
ret.defParam("party", "fireproof");
ret.defParam("protocol", "wss");
let possibleUndef = { protocol: ret.getParam("protocol") };
const protocolsStr = uri.getParam("protocols");
if (protocolsStr) {
const ps = protocolsStr.split(",").map((x) => x.trim()).filter((x) => x);
if (ps.length > 0) {
possibleUndef = { ...possibleUndef, protocols: ps };
}
}
const prefixStr = uri.getParam("prefix");
if (prefixStr) {
possibleUndef = { ...possibleUndef, prefix: prefixStr };
}
const query = {};
const partySockOpts = {
id: this.id,
host: this.url.host,
room: dbName,
party: ret.getParam("party"),
...possibleUndef,
query,
path: this.url.pathname.replace(/^\//, "")
};
if (runtimeFn().isNodeIsh) {
const { WebSocket: WebSocket2 } = await Promise.resolve().then(() => __toESM(require_browser(), 1));
partySockOpts.WebSocket = WebSocket2;
}
this.pso = partySockOpts;
return Result.Ok(ret.URI());
}
async ready() {
this.logger.Debug().Msg("ready");
}
async connectFireproofCloud() {
const pkKeyThis = pkKey(this.pso);
return pkSockets.get(pkKeyThis).once(async () => {
if (!this.pso) {
throw new Error("Party socket options not found");
}
this.party = new PartySocket(this.pso);
let exposedResolve;
const openFn = () => {
this.logger.Debug().Msg("party open");
this.party?.addEventListener("message", async (event) => {
this.logger.Debug().Msg(`got message: ${event.data}`);
const mbin = this.sthis.txt.encode(event.data);
this.notifySubscribers(mbin);
});
exposedResolve(true);
};
return await new Promise((resolve) => {
exposedResolve = resolve;
this.party?.addEventListener("open", openFn);
});
});
}
async close() {
await this.ready();
this.logger.Debug().Msg("close");
this.party?.close();
return Result.Ok(void 0);
}
async put(uri, body) {
await this.ready();
const { store } = (void 0)(uri, this.sthis, (...args) => args.join("/"));
if (store === "meta") {
const bodyRes = await (void 0).addCryptoKeyToGatewayMetaPayload(uri, this.sthis, body);
if (bodyRes.isErr()) {
this.logger.Error().Err(bodyRes.Err()).Msg("Error in addCryptoKeyToGatewayMetaPayload");
throw bodyRes.Err();
}
body = bodyRes.Ok();
}
const rkey = uri.getParamResult("key");
if (rkey.isErr()) return Result.Err(rkey.Err());
const key = rkey.Ok();
if (store === "meta") {
const uploadUrl = pkMetaURL(uri, key);
return exception2Result(async () => {
const response = await fetch(uploadUrl.asURL(), { method: "PUT", body });
if (response.status === 404) {
throw this.logger.Error().Url(uploadUrl).Msg(`Failure in uploading ${store}!`).AsError();
}
});
} else {
const uploadUrl = pkURL(uri, key, "car");
return exception2Result(async () => {
const response = await fetch(uploadUrl.asURL(), { method: "PUT" });
this.logger.Debug().Url(uploadUrl).Uint64("status", response.status).Str("status-text", response.statusText).Msg("put");
if (response.status === 404) {
throw this.logger.Error().Url(uploadUrl).Msg(`Failure in uploading ${store}!`).AsError();
}
const url = (await response.json()).url;
this.logger.Debug().Url(url).Msg("put");
const uploadResponse = await fetch(url, { method: "PUT", body });
if (uploadResponse.status === 404) {
throw this.logger.Error().Url(uploadUrl).Msg(`Failure in uploading ${store}!`).AsError();
}
});
}
}
notifySubscribers(data) {
for (const callback of this.subscriberCallbacks) {
try {
callback(data);
} catch (error) {
this.logger.Error().Err(error).Msg("Error in subscriber callback execution");
}
}
}
async subscribe(uri, callback) {
await this.ready();
await this.connectFireproofCloud();
const store = uri.getParam("store");
if (store !== "meta") {
return Result.Err(new Error("store must be meta"));
}
this.subscriberCallbacks.add(callback);
return Result.Ok(() => {
this.subscriberCallbacks.delete(callback);
});
}
async get(uri) {
await this.ready();
return exception2Result(async () => {
const { store } = (void 0)(uri, this.sthis, (...args) => args.join("/"));
const key = uri.getParam("key");
if (!key) throw new Error("key not found");
let downloadUrl;
this.logger.Debug().Str("store", store).Str("key", key).Msg("get");
switch (store) {
case "meta":
downloadUrl = pkMetaURL(uri, key);
break;
case "data":
downloadUrl = pkCarGetURL(uri, key);
break;
default:
throw new Error(`Unsupported store: ${store}`);
}
const response = await fetch(downloadUrl.toString(), { method: "GET" });
if (response.status === 404) {
throw new Error(`Failure in downloading ${store}!`);
}
const body = new Uint8Array(await response.arrayBuffer());
if (store === "meta") {
const resKeyInfo = await (void 0).setCryptoKeyFromGatewayMetaPayload(uri, this.sthis, body);
if (resKeyInfo.isErr()) {
this.logger.Error().Url(uri).Err(resKeyInfo).Any("body", body).Msg("Error in setCryptoKeyFromGatewayMetaPayload");
throw resKeyInfo.Err();
}
}
return body;
});
}
async delete(_uri) {
await this.ready();
throw new Error("no delete for fireproof cloud");
}
async destroy(uri) {
await this.ready();
return exception2Result(async () => {
const deleteUrl = pkBaseURL(uri);
const response = await fetch(deleteUrl.asURL(), { method: "DELETE" });
if (response.status === 404) {
throw new Error("Failure in deleting data!");
}
return Result.Ok(void 0);
});
}
};
var pkSockets = new KeyedResolvOnce();
function pkKey(set2) {
const ret = JSON.stringify(
Object.entries(set2 || {}).sort(([a], [b]) => a.localeCompare(b)).filter(([k]) => k !== "id").map(([k, v]) => ({ [k]: v }))
);
return ret;
}
function pkURL(uri, key, type) {
const host = uri.host;
const name = uri.getParam("name");
const idx = uri.getParam("index") || "";
const protocol = uri.getParam("protocol") === "ws" ? "http" : "https";
const path = `/parties/fireproof/${name}${idx}`;
return BuildURI.from(`${protocol}://${host}${path}`).setParam(type, key).URI();
}
function pkBaseURL(uri) {
const host = uri.host;
const name = uri.getParam("name");
const idx = uri.getParam("index") || "";
const protocol = uri.getParam("protocol") === "ws" ? "http" : "https";
const path = `/parties/fireproof/${name}${idx}`;
return BuildURI.from(`${protocol}://${host}${path}`).URI();
}
function pkCarGetURL(uri, key) {
const baseUrl = uri.getParam("getBaseUrl");
if (!baseUrl) {
return pkURL(uri, key, "car");
}
const name = uri.getParam("name");
const idx = uri.getParam("index") || "";
const baseUri = URI.from(baseUrl).asURL();
baseUri.pathname = `/${name}${idx}/${key}`;
return BuildURI.from(baseUri).URI();
}
function pkMetaURL(uri, key) {
return pkURL(uri, key, "meta");
}
var FireproofCloudTestStore = class {
constructor(gw, sthis) {
this.sthis = sthis;
this.logger = (void 0)(sthis, "FireproofCloudTestStore");
this.gateway = gw;
}
async get(uri, key) {
const url = uri.build().setParam("key", key).URI();
const dbFile = this.sthis.pathOps.join((void 0).getPath(url, this.sthis), (void 0).getFileName(url, this.sthis));
this.logger.Debug().Url(url).Str("dbFile", dbFile).Msg("get");
const buffer = await this.gateway.get(url);
this.logger.Debug().Url(url).Str("dbFile", dbFile).Len(buffer).Msg("got");
return buffer.Ok();
}
};
var onceRegisterFireproofCloudStoreProtocol = new KeyedResolvOnce();
function registerFireproofCloudStoreProtocol(protocol = "fireproof:", overrideBaseURL) {
return onceRegisterFireproofCloudStoreProtocol.get(protocol).once(() => {
URI.protocolHasHostpart(protocol);
return (void 0).registerStoreProtocol({
protocol,
overrideBaseURL,
gateway: async (sthis) => {
return new FireproofCloudGateway(sthis);
},
test: async (sthis) => {
const gateway = new FireproofCloudGateway(sthis);
return new FireproofCloudTestStore(gateway, sthis);
}
});
});
}
// src/cloud/index.ts
var SYNC_DB_NAME = "fp_sync";
if (!runtimeFn().isBrowser) {
const url = BuildURI.from(process.env.FP_KEYBAG_URL || "file://./dist/kb-dir-FireproofCloud");
url.setParam("extractKey", "_deprecated_internal_api");
process.env.FP_KEYBAG_URL = url.toString();
}
registerFireproofCloudStoreProtocol();
var connectionCache = new KeyedResolvOnce();
var rawConnect = (db, remoteDbName = "", url = "fireproof://cloud.fireproof.direct") => {
const { sthis, blockstore, name: dbName } = db;
if (!dbName) {
throw new Error("dbName is required");
}
const urlObj = BuildURI.from(url);
const existingName = urlObj.getParam("name");
urlObj.defParam("name", remoteDbName || existingName || dbName);
urlObj.defParam("localName", dbName);
urlObj.defParam("storekey", `@${dbName}:data@`);
urlObj.defParam("getBaseUrl", "https://storage.fireproof.direct/");
const fpUrl = urlObj.toString().replace(/^http:\/\//, "fireproof://").replace(/^https:\/\//, "fireproof://");
return connectionCache.get(fpUrl).once(() => {
makeKeyBagUrlExtractable(sthis);
const connection = connectionFactory(sthis, fpUrl);
connection.connect_X(blockstore);
return connection;
});
};
async function getOrCreateRemoteName(dbName, remoteName) {
const syncDb = (void 0)(SYNC_DB_NAME);
const result = await syncDb.query("localName", { key: dbName, includeDocs: true });
if (result.rows.length === 0) {
const doc2 = {
remoteName: remoteName || syncDb.sthis.timeOrderedNextId().str,
localName: dbName,
firstConnect: !remoteName
};
const { id } = await syncDb.put(doc2);
return { ...doc2, _id: id };
}
const doc = result.rows[0].doc;
return doc;
}
function connect(db, remoteName, dashboardURI = "https://dashboard.fireproof.storage/", remoteURI = "fireproof://cloud.fireproof.direct") {
const dbName = db.name;
if (!dbName) {
throw new Error("Database name is required for cloud connection");
}
return getOrCreateRemoteName(dbName, remoteName).then(async (doc) => {
if (!doc) {
throw new Error("Failed to get or create remote name");
}
doc.endpoint = URI.from(remoteURI).toString();
const connection = rawConnect(db, doc.remoteName, URI.from(doc.endpoint).toString());
const connectURI = URI.from(dashboardURI).build().pathname("/fp/databases/connect");
connectURI.defParam("localName", dbName);
connectURI.defParam("remoteName", doc.remoteName);
if (doc.endpoint) {
connectURI.defParam("endpoint", doc.endpoint);
}
console.log("Fireproof Cloud: " + connectURI.toString());
if (doc.firstConnect && runtimeFn().isBrowser && window.location.href.indexOf(URI.from(dashboardURI).toString()) === -1) {
const syncDb = (void 0)(SYNC_DB_NAME);
doc.firstConnect = false;
await syncDb.put(doc);
}
connection.dashboardUrl = URI.from(connectURI);
return connection;
});
}
return __toCommonJS(cloud_exports);
})();
/*! Bundled license information:
partysocket/dist/chunk-4SNNYC7I.mjs:
(*!
* Reconnecting WebSocket
* by Pedro Ladaria <pedro.ladaria@gmail.com>
* https://github.com/pladaria/reconnecting-websocket
* License MIT
*)
*/
//# sourceMappingURL=index.global.js.map