export function utc(value) {
if (value === null || value === undefined || value === "") {
return "";
}
if (typeof value !== "string") {
return String(value);
}
const at = new Date(value);
if (Number.isNaN(at.getTime())) {
return value;
}
const iso = at.toISOString();
return `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC+00:00`;
}
function isObject(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function decoded(text) {
if (typeof text !== "string" || !/^[A-Za-z0-9_-]+$/.test(text)) {
return null;
}
try {
const bytes = Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
return isObject(value) ? value : null;
} catch {
return null;
}
}
function items(value) {
return Array.isArray(value) ? value : [];
}
function isIndex(value) {
return Number.isInteger(value) && value >= 0;
}
const LINKED = [
["dialog", "dialog"],
["attachments", "attachment"],
["analysis", "analysis"],
];
function linksOf(vcon) {
const found = [];
for (const [part, noun] of LINKED) {
items(vcon[part]).forEach((item, index) => {
if (isObject(item) && typeof item.url === "string" && item.url !== "") {
found.push({ where: `${noun} ${index + 1}`, url: item.url });
}
});
}
return found;
}
function readable(text) {
let vcon;
try {
vcon = JSON.parse(text);
} catch {
return null;
}
if (!isObject(vcon) || "ciphertext" in vcon) {
return null;
}
if ("payload" in vcon && "signatures" in vcon) {
return decoded(vcon.payload);
}
return vcon;
}
export function links(text) {
const vcon = readable(text);
return vcon === null ? [] : linksOf(vcon);
}
export const DISPLAY_LIMIT = 2 * 1024 * 1024;
export function shown(text, limit = DISPLAY_LIMIT) {
if (text.length <= limit) {
return { text, left: 0 };
}
return { text: text.slice(0, limit), left: text.length - limit };
}
const MEDIA_ENCODINGS = ["base64url", "base64"];
function listed(value) {
const made = items(value);
if (made.length === 0) {
return "none";
}
const readableItems = made.map((item) => {
if (isObject(item) && MEDIA_ENCODINGS.includes(item.encoding) && typeof item.body === "string") {
return { ...item, body: `[${item.body.length} characters of ${item.encoding}, not shown]` };
}
return item;
});
return shown(JSON.stringify(readableItems, null, 2)).text;
}
const SECTIONS = new Map([
["parties", (vcon) => listed(vcon.parties)],
["subject", (vcon) => (typeof vcon.subject === "string" && vcon.subject !== "" ? vcon.subject : "none")],
["dialog", (vcon) => listed(vcon.dialog)],
["analysis", (vcon) => listed(vcon.analysis)],
]);
export function section(text, name) {
const make = SECTIONS.get(name);
const vcon = readable(text);
return make === undefined || vcon === null ? null : make(vcon);
}
const VIEW_TEXTS = ["form", "created", "subject"];
const VIEW_COUNTS = ["dialogs", "attachments", "analyses", "links"];
const VIEW_LINES = ["parties", "dialog"];
const VIEW_SIGNATURE = ["alg", "kid", "x5t"];
export function maskedView(text) {
let view;
try {
view = JSON.parse(text);
} catch {
return null;
}
if (!isObject(view)) {
return null;
}
const isText = (value) => typeof value === "string";
const recordings = "recordings" in view ? view.recordings : [];
const signature = view.signature;
const whole =
VIEW_TEXTS.every((name) => isText(view[name])) &&
VIEW_COUNTS.every((name) => Number.isInteger(view[name]) && view[name] >= 0) &&
typeof view.seconds === "number" &&
VIEW_LINES.every((name) => Array.isArray(view[name]) && view[name].every(isText)) &&
(signature === null || (isObject(signature) && VIEW_SIGNATURE.every((name) => isText(signature[name])))) &&
Array.isArray(recordings) &&
recordings.every((r) => isObject(r) && Number.isInteger(r.dialog) && r.dialog >= 1 && isText(r.type));
if (!whole) {
return null;
}
return {
form: view.form,
created: view.created,
subject: view.subject,
parties: view.parties,
dialogs: view.dialogs,
dialog: view.dialog,
seconds: view.seconds,
attachments: view.attachments,
analyses: view.analyses,
links: view.links,
signature: signature === null ? null : { alg: signature.alg, kid: signature.kid, x5t: signature.x5t },
recordings: recordings.map((r) => ({ dialog: r.dialog, type: r.type })),
};
}
const WRONG_LISTENER = "/problems/wrong-listener";
function advice(status, type) {
if (typeof type === "string" && type.endsWith(WRONG_LISTENER)) {
return (
"Open the console at the server's other address and sign in there: " +
"one address serves tenant keys and the other serves operator keys."
);
}
if (status === 401) {
return "Sign in again with a key the server accepts.";
}
if (status === 403) {
return "Sign in with a key that holds the scope this needs.";
}
if (status === 404) {
return "Check the uuid or id: it may be deleted or belong to another tenant.";
}
if (status === 410) {
return "It was deleted: a key with the legal scope can still find it in the Legal view.";
}
if (status === 409) {
return "Reload the view and check its state before trying again.";
}
if (status === 412) {
return "It changed since you opened it: open it again, then repeat the change.";
}
if (status === 413) {
return "Send a smaller file.";
}
if (status === 400 || status === 415 || status === 422) {
return "Correct what was sent and try again.";
}
if (status === 429) {
return "Wait a minute, then try again.";
}
if (status >= 500) {
return "Try again; if it repeats, tell the server's operator.";
}
return "Try again.";
}
export function refusalText(status, title, type = undefined) {
if (status === 0) {
return "The server could not be reached. Check the connection and try again.";
}
const what = typeof title === "string" && title !== "" ? `${title} (${status})` : `HTTP ${status}`;
return `${what}. ${advice(status, type)}`;
}
export const REVEAL_PARTS = Object.freeze(["parties", "subject", "dialog", "analysis", "links", "all", "audio"]);
export function revealPath(path, part) {
if (part === null) {
return path;
}
if (!REVEAL_PARTS.includes(part)) {
throw new RangeError(`not a part a reveal can name: ${part}`);
}
if (path.includes("?") || path.includes("#")) {
throw new RangeError("a reveal is the only parameter of its read");
}
return `${path}?reveal=${part}`;
}
export function maskedPath(path) {
if (path.includes("?") || path.includes("#")) {
throw new RangeError("the masked view is the only parameter of its read");
}
return `${path}?view=masked`;
}
export const VIEW_UNREADABLE =
"The server's masked view of this vCon could not be read. Open it again; if this repeats, tell the server's operator.";
export function audioSignature(bytes) {
if (startsWith(bytes, "RIFF") && startsWith(bytes, "WAVE", 8)) {
return "audio/wav";
}
if (startsWith(bytes, "ID3") || isMpegFrame(bytes)) {
return "audio/mpeg";
}
if (startsWith(bytes, "OggS")) {
return startsWith(bytes, "OpusHead", 28) ? "audio/opus" : "audio/ogg";
}
return null;
}
function isMpegFrame(bytes) {
return (
bytes.length >= 4 &&
bytes[0] === 0xff &&
(bytes[1] & 0xe0) === 0xe0 &&
(bytes[1] & 0x18) !== 0x08 &&
(bytes[1] & 0x06) !== 0x00 &&
(bytes[2] & 0xf0) !== 0xf0 &&
(bytes[2] & 0x0c) !== 0x0c
);
}
function startsWith(bytes, text, offset = 0) {
if (bytes.length < offset + text.length) {
return false;
}
for (let i = 0; i < text.length; i++) {
if (bytes[offset + i] !== text.charCodeAt(i)) {
return false;
}
}
return true;
}
const BASE64 = /^(?:[A-Za-z0-9+/]*|[A-Za-z0-9_-]*)={0,2}$/;
function bytesOf(body) {
if (!BASE64.test(body)) {
return null;
}
let text;
try {
text = atob(body.replaceAll("-", "+").replaceAll("_", "/"));
} catch {
return null;
}
const bytes = new Uint8Array(text.length);
for (let i = 0; i < text.length; i++) {
bytes[i] = text.charCodeAt(i);
}
return bytes;
}
function offered(dialog, index, limit) {
const what = `Dialog ${index + 1}'s recording`;
if (typeof dialog.body !== "string" || dialog.body === "") {
if (typeof dialog.url === "string" && dialog.url !== "") {
return refused(`${what} is at a link outside the server, which the console never loads.`);
}
return refused(`Dialog ${index + 1} has no recording inside the vCon.`);
}
if (!MEDIA_ENCODINGS.includes(dialog.encoding)) {
return refused(`Dialog ${index + 1} holds text or data, not an encoded recording.`);
}
const type = declaredType(dialog);
if (type === "") {
return refused(`${what} does not say what type it is, so the console does not play it. Download the vCon to examine it.`);
}
let played;
if (AUDIO_TYPES.includes(type)) {
played = type;
} else if (Object.hasOwn(AUDIO_ALIASES, type)) {
played = AUDIO_ALIASES[type];
}
if (played === undefined) {
const named = type.length > TYPE_SHOWN ? `${type.slice(0, TYPE_SHOWN)}…` : type;
return refused(
`${what} is declared as ${named}, which the console does not play. ` +
`It plays ${AUDIO_TYPES.slice(0, -1).join(", ")} and ${AUDIO_TYPES.at(-1)}. ` +
"Download the vCon to use the recording another way.",
);
}
const size = Math.floor((dialog.body.replace(/=+$/, "").length * 3) / 4);
if (size > limit) {
return refused(
`${what} is about ${size} bytes, and the console plays at most ${limit}. ` +
"Download the vCon to hear it another way.",
);
}
return { ok: true, type: played, declared: type };
}
export function recording(text, index, limit = AUDIO_LIMIT) {
const vcon = readable(text);
if (vcon === null) {
return refused("This vCon cannot be read in parts, so the console cannot play from it.");
}
const dialog = isIndex(index) ? items(vcon.dialog)[index] : undefined;
if (!isObject(dialog)) {
return refused("The vCon has no such dialog to play.");
}
const offer = offered(dialog, index, limit);
if (!offer.ok) {
return offer;
}
const what = `Dialog ${index + 1}'s recording`;
const bytes = bytesOf(dialog.body);
if (bytes === null) {
return refused(`${what} cannot be decoded: its body is not base64. Download the vCon to examine it.`);
}
if (!isDeclared(bytes, offer.type)) {
return refused(
`${what} is declared as ${offer.declared}, but its bytes are not ${offer.type}. ` +
"The console does not play it. Download the vCon to examine the recording.",
);
}
return { ok: true, type: offer.type, bytes };
}
export function isDeclared(bytes, type) {
const found = audioSignature(bytes);
return found !== null && (found === type || (found === "audio/opus" && type === "audio/ogg"));
}
function declaredType(dialog) {
const declared = "mediatype" in dialog ? dialog.mediatype : dialog.mimetype;
return typeof declared === "string" ? declared.split(";")[0].trim().toLowerCase() : "";
}
const TYPE_SHOWN = 80;
function refused(reason) {
return { ok: false, reason };
}
export const AUDIO_LIMIT = 100 * 1024 * 1024;
export const AUDIO_ALIASES = Object.freeze({
"audio/x-wav": "audio/wav",
"audio/wave": "audio/wav",
"audio/vnd.wave": "audio/wav",
"audio/x-mp3": "audio/mpeg",
"audio/mp3": "audio/mpeg",
"audio/x-ogg": "audio/ogg",
});
export const AUDIO_TYPES = Object.freeze(["audio/wav", "audio/mpeg", "audio/ogg", "audio/opus"]);
const LABEL_LIMIT = 200;
export const HAND_OVER = "recording";
export function handed(data, limit = AUDIO_LIMIT) {
if (!isObject(data) || data.kind !== HAND_OVER) {
return null;
}
if (!(data.bytes instanceof ArrayBuffer) || data.bytes.byteLength > limit) {
return null;
}
if (!AUDIO_TYPES.includes(data.type) || !isDeclared(new Uint8Array(data.bytes), data.type)) {
return null;
}
if (typeof data.label !== "string" || data.label === "" || data.label.length > LABEL_LIMIT) {
return null;
}
return { type: data.type, label: data.label, bytes: data.bytes };
}
export function handOver(found, uuid, index) {
const { bytes } = found;
const whole = bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength;
return {
kind: HAND_OVER,
type: found.type,
label: `Dialog ${index + 1} of ${uuid}, ${found.type}`,
bytes: whole ? bytes.buffer : bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
};
}
export function accepts(event, sender, origin) {
return sender !== null && sender !== undefined && event.origin === origin && event.source === sender;
}
export const PLAYER_READY = "player-ready";
export const PLAYER_CLOSED = "player-closed";