import jsonStableStringify from "json-stable-stringify";
import { encode as encodeBase64, decode as decodeBase64 } from "js-base64";
export { encodeBase64, decodeBase64 };
import { reuseInFlight } from "@cocalc/util/reuse-in-flight";
export function handleErrorMessage(mesg) {
if (mesg?.error) {
if (mesg.error.startsWith("Error: ")) {
throw Error(mesg.error.slice("Error: ".length));
} else {
throw Error(mesg.error);
}
}
return mesg;
}
export function matchesPattern({
pattern,
subject,
}: {
pattern: string;
subject: string;
}): boolean {
const subParts = subject.split(".");
const patParts = pattern.split(".");
let i = 0,
j = 0;
while (i < subParts.length && j < patParts.length) {
if (patParts[j] === ">") return true;
if (patParts[j] !== "*" && patParts[j] !== subParts[i]) return false;
i++;
j++;
}
return i === subParts.length && j === patParts.length;
}
export function isValidSubject(subject: string): boolean {
if (typeof subject !== "string" || subject.length === 0) return false;
if (subject.startsWith(".") || subject.endsWith(".")) return false;
const tokens = subject.split(".");
if (tokens.some((t) => t.length === 0)) return false;
for (let i = 0; i < tokens.length; ++i) {
const tok = tokens[i];
if (tok === ">" && i !== tokens.length - 1) return false;
if (tok !== "*" && tok !== ">") {
if (/[.\s]/u.test(tok)) {
return false;
}
}
if (/\s/u.test(tok)) {
return false;
}
}
return true;
}
export function isValidSubjectWithoutWildcards(subject: string): boolean {
return (
isValidSubject(subject) && !subject.includes("*") && !subject.endsWith(">")
);
}
export function toKey(x): string | undefined {
if (x === undefined) {
return undefined;
} else if (typeof x === "object") {
return jsonStableStringify(x);
} else {
return `${x}`;
}
}
export const getMaxPayload = reuseInFlight(async () => {
return 1e6;
});
export const waitUntilConnected = reuseInFlight(async () => {});