paste-bin/ui/app.js
Jarian 985e070757 port: FastAPI rewrite built by the arch-llm spec pipeline
Spec-first port of the Flask app (still on main):
- schema.arch: signed arch-llm spec (single source of truth)
- paste_bin/: generated FastAPI backend, verified 51/51 frozen owner
  tests, 92.5% coverage (build r3, 2026-11-18)
- ui/: SPA + emitted OpenAPI contract (openapi.json + generated
  client.js); the app calls only window.PasteBinAPI
- 7 old bugs fixed (file raw 500, silent expiry, AVI-as-webp,
  stripped content, limiter leak, trusted mimetype, stale tmp)
- 62/62 live probe green; /health + JSON index added; JSON API

Full report on the wiki: 'FastAPI port (arch-llm pipeline)'.
2026-11-18 23:00:23 +00:00

501 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// paste-bin UI — app logic.
// Contract surface is ONLY window.PasteBinAPI (generated client.js from openapi.json).
// No hand-rolled fetch, no hardcoded endpoints: every call below is a generated op.
"use strict";
(() => {
const API = window.PasteBinAPI;
if (!API) {
document.body.insertAdjacentHTML(
"afterbegin",
'<div style="padding:20px;background:#e94560;color:#fff;font-family:monospace">client.js failed to load — regenerate: archllm openapi paste-bin --client --out ui</div>'
);
return;
}
const $ = (s) => document.querySelector(s);
// pinned contract literals (mirror of x-error-literals, used for early client-side feedback)
const ERR_EMPTY_CONTENT = "Content cannot be empty";
const ERR_NO_FILE = "No file selected";
const ERR_MISMATCH = "File content does not match image type.";
const ERR_TOO_LARGE = "File too large. Maximum size is 20 MB.";
const ERR_NOT_FOUND = "Paste not found";
const MAX_BYTES = 20 * 1024 * 1024;
const IMG_ACCEPT = "image/png,image/jpeg,image/gif,image/bmp,image/webp,image/svg+xml,image/tiff";
const TYPE_ICON = { text: "📝", image: "🖼", file: "📄" };
const state = { type: "text", file: null, lastView: null, lastId: null };
const recent = loadRecent();
/* ---------------- toasts ---------------- */
function toast(kind, title, detail = "", ttl = 5200) {
const el = document.createElement("div");
el.className = `toast toast-${kind}`;
const t = document.createElement("div");
t.className = "toast-title";
t.textContent = title;
el.appendChild(t);
if (detail) {
const d = document.createElement("div");
d.className = "toast-detail";
d.textContent = detail;
el.appendChild(d);
}
const x = document.createElement("button");
x.className = "toast-x";
x.setAttribute("aria-label", "Dismiss");
x.textContent = "×";
x.onclick = () => el.remove();
el.appendChild(x);
$("#toasts").appendChild(el);
requestAnimationFrame(() => el.classList.add("in"));
setTimeout(() => {
el.classList.remove("in");
setTimeout(() => el.remove(), 300);
}, ttl);
}
function errToast(e) {
const kind = e && e.status === 429 ? "warn" : "err";
const hint =
e && e.status === 429
? "upload budget (10/min) resets within 60 s"
: e && e.apiError
? `pinned contract message · ${API.ERROR_MESSAGES ? "see openapi.json x-error-literals" : ""}`
: "network error — is the API proxy up?";
toast(kind, e && e.message ? e.message : String(e), hint);
}
/* ---------------- health + contract badges ---------------- */
async function pingHealth() {
const pill = $("#healthPill");
try {
await API.getHealth();
pill.className = "pill pill-ok";
pill.innerHTML = '<span class="dot"></span>api ok';
} catch {
pill.className = "pill pill-err";
pill.innerHTML = '<span class="dot"></span>api down';
}
}
async function loadBadges() {
try {
const [idx, doc] = await Promise.all([API.getIndex(), API.fetchContract()]);
$("#brandTag").textContent = `service ${idx.service} · spec → openapi → client → ui`;
const ops = Object.values(doc.paths).reduce(
(n, p) => n + Object.keys(p).filter((m) => /^(get|post|put|delete|patch)$/.test(m)).length,
0
);
const b = $("#contractBadge");
b.textContent = `v${doc.info.version} · ${ops} ops`;
b.title = `OpenAPI ${doc.openapi} — ${doc.info.title} (openapi.json)`;
} catch {
$("#contractBadge").textContent = "v?";
}
}
/* ---------------- create: type tabs ---------------- */
function setType(t) {
state.type = t;
for (const b of $("#typeSeg").children) {
const on = b.dataset.t === t;
b.classList.toggle("on", on);
b.setAttribute("aria-selected", on ? "true" : "false");
}
$("#paneText").hidden = t !== "text";
$("#paneFile").hidden = t === "text";
$("#fileInput").accept = t === "image" ? IMG_ACCEPT : "";
$("#dzSub").textContent =
t === "image"
? "png · jpeg · gif · bmp · webp · svg · tiff — max 20 MB"
: "any file — max 20 MB";
if (state.file) validateFileForType();
}
$("#typeSeg").addEventListener("click", (e) => {
const b = e.target.closest("button[data-t]");
if (b) setType(b.dataset.t);
});
/* ---------------- create: file handling ---------------- */
const fileInput = $("#fileInput");
const dz = $("#dropzone");
function fmtSize(bytes) {
if (bytes < 1024) return bytes + " B";
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB";
return (bytes / (1024 * 1024)).toFixed(2) + " MB";
}
function validateFileForType() {
if (!state.file) return true;
if (state.type === "image" && !state.file.type.startsWith("image/")) {
toast("err", ERR_MISMATCH, state.file.name + " — switch to File tab for non-images");
return false;
}
return true;
}
function setFile(f) {
if (!f) return;
state.file = f;
if (f.size > MAX_BYTES) toast("warn", ERR_TOO_LARGE, f.name + " is " + fmtSize(f.size));
if (!validateFileForType()) {
clearFile();
return;
}
const isImg = state.type === "image" && f.type.startsWith("image/");
$("#dzIdle").hidden = true;
$("#dzPreview").hidden = false;
const thumb = $("#dzThumb");
const ico = $("#dzFileIco");
if (isImg) {
thumb.src = URL.createObjectURL(f);
thumb.hidden = false;
ico.hidden = true;
} else {
thumb.hidden = true;
thumb.removeAttribute("src");
ico.hidden = false;
ico.textContent = state.type === "file" ? "📄" : "❓";
}
$("#dzName").textContent = f.name;
$("#dzMeta").textContent = `${fmtSize(f.size)} · ${f.type || "unknown type"}`;
}
function clearFile() {
state.file = null;
fileInput.value = "";
const thumb = $("#dzThumb");
thumb.hidden = true;
thumb.removeAttribute("src");
$("#dzIdle").hidden = false;
$("#dzPreview").hidden = true;
}
dz.addEventListener("click", (e) => {
if (e.target.closest("#dzRemove")) return;
fileInput.click();
});
dz.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
fileInput.click();
}
});
fileInput.addEventListener("change", () => setFile(fileInput.files[0] || null));
$("#dzRemove").addEventListener("click", (e) => {
e.stopPropagation();
clearFile();
});
["dragenter", "dragover"].forEach((ev) =>
dz.addEventListener(ev, (e) => {
e.preventDefault();
dz.classList.add("dragover");
})
);
["dragleave", "drop"].forEach((ev) =>
dz.addEventListener(ev, (e) => {
e.preventDefault();
dz.classList.remove("dragover");
})
);
dz.addEventListener("drop", (e) => {
const f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
if (f) setFile(f);
});
/* ---------------- create: submit ---------------- */
$("#content").addEventListener("input", () => {
$("#charCount").textContent = String($("#content").value.length);
});
async function createPaste() {
const btn = $("#createBtn");
const title = $("#title").value.trim();
const expiry = $("#expiry").value;
const content = $("#content").value;
if (state.type === "text" && !content.trim()) {
toast("err", ERR_EMPTY_CONTENT);
$("#content").focus();
return;
}
if (state.type !== "text" && !state.file) {
toast("err", ERR_NO_FILE);
return;
}
if (state.file && state.file.size > MAX_BYTES) {
toast("warn", ERR_TOO_LARGE, state.file.name + " is " + fmtSize(state.file.size));
return;
}
btn.disabled = true;
btn.textContent = "Creating…";
$("#createHint").textContent = `POST /pastes · ${state.type} · ${expiry}`;
try {
const out = await API.postPastes({
paste_type: state.type,
title,
expiry,
content: state.type === "text" ? content : "",
file: state.type === "text" ? null : state.file,
});
toast("ok", `Created ${out.id}`, out.title ? `"${out.title}"` : state.type + " paste");
remember(out);
// reset the form, keep the type
$("#title").value = "";
$("#content").value = "";
$("#charCount").textContent = "0";
clearFile();
openPaste(out.id);
} catch (e) {
errToast(e);
} finally {
btn.disabled = false;
btn.textContent = "Create paste";
$("#createHint").textContent = "";
}
}
$("#createBtn").addEventListener("click", createPaste);
/* ---------------- view ---------------- */
function fmtTime(iso) {
if (!iso) return "";
const d = new Date(iso);
return isNaN(d) ? iso : d.toLocaleString();
}
function showOpenErr(msg) {
const el = $("#openErr");
el.textContent = msg;
el.hidden = !msg;
}
async function openPaste(id) {
id = (id || "").trim();
if (!API.PASTE_ID_RE.test(id)) {
showOpenErr("id must be 16 hex chars (contract: paste_id pattern)");
return;
}
showOpenErr("");
$("#openId").value = id;
$("#stage").innerHTML =
'<div class="stage-loading"><span class="spinner"></span>loading ' + id + "…</div>";
$("#viewMeta").hidden = true;
$("#viewActions").hidden = true;
try {
const v = await API.getPastesPaste_id(id);
state.lastView = v;
state.lastId = id;
renderView(v);
} catch (e) {
state.lastView = null;
state.lastId = null;
renderViewError(e);
}
}
function renderView(v) {
const stage = $("#stage");
stage.innerHTML = "";
if (v.type === "text") {
const pre = document.createElement("pre");
pre.className = "view-text";
pre.textContent = v.content == null ? "" : v.content;
stage.appendChild(pre);
} else if (v.type === "image") {
const wrap = document.createElement("div");
wrap.className = "stage-img";
const img = document.createElement("img");
img.alt = v.title || "paste image";
img.src = API.getPastesPaste_idRawUrl(v.id);
img.onerror = () => {
img.onerror = null;
renderViewError(new API.ApiError(0, "image failed to load"));
};
wrap.appendChild(img);
stage.appendChild(wrap);
} else {
const wrap = document.createElement("div");
wrap.className = "view-file";
wrap.innerHTML =
'<div class="view-file-ico" aria-hidden="true">📄</div>' +
'<div class="view-file-name"></div>' +
'<div class="view-file-sub"></div>';
wrap.querySelector(".view-file-name").textContent = v.filename || "unnamed file";
wrap.querySelector(".view-file-sub").textContent = v.mimetype || "unknown type";
stage.appendChild(wrap);
}
const bits = [];
bits.push("<b>type</b> " + v.type);
if (v.title) bits.push("<b>title</b> " + escapeHtml(v.title));
if (v.filename) bits.push("<b>file</b> " + escapeHtml(v.filename));
if (v.mimetype) bits.push("<b>mime</b> " + v.mimetype);
bits.push("<b>created</b> " + fmtTime(v.created_at));
bits.push(v.expires_at ? "<b>expires</b> " + fmtTime(v.expires_at) : "<b>expires</b> never");
const meta = $("#viewMeta");
meta.innerHTML = bits.join(" · ");
meta.hidden = false;
$("#actRaw").href = API.getPastesPaste_idRawUrl(v.id);
$("#actDownload").href = API.getPastesPaste_idDownloadUrl(v.id);
$("#viewActions").hidden = false;
}
function renderViewError(e) {
const notFound = e && e.status === 404;
$("#stage").innerHTML = "";
const wrap = document.createElement("div");
wrap.className = "view-error";
wrap.innerHTML =
'<div class="view-error-ico" aria-hidden="true">' + (notFound ? "🔍" : "⚠️") + "</div>" +
'<div class="view-error-title"></div>' +
'<div class="view-error-sub"></div>';
wrap.querySelector(".view-error-title").textContent = notFound
? ERR_NOT_FOUND
: (e && e.message) || "could not load";
wrap.querySelector(".view-error-sub").textContent = notFound
? "it expired, or the id is wrong"
: "check the health pill — is the API up?";
$("#stage").appendChild(wrap);
$("#viewMeta").hidden = true;
$("#viewActions").hidden = true;
}
function escapeHtml(s) {
return s.replace(/[&<>"']/g, (c) => ({
"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
}[c]));
}
$("#openBtn").addEventListener("click", () => openPaste($("#openId").value));
$("#openId").addEventListener("keydown", (e) => {
if (e.key === "Enter") openPaste($("#openId").value);
});
/* ---------------- view: actions ---------------- */
async function copyText(text, label) {
try {
await navigator.clipboard.writeText(text);
toast("ok", "Copied " + label);
} catch {
// fallback for non-secure contexts
const ta = document.createElement("textarea");
ta.value = text;
ta.style.position = "fixed";
ta.style.opacity = "0";
document.body.appendChild(ta);
ta.select();
try {
document.execCommand("copy");
toast("ok", "Copied " + label);
} catch {
toast("err", "Clipboard blocked", "select & copy manually");
}
ta.remove();
}
}
$("#actCopyJson").addEventListener("click", () => {
if (state.lastView) copyText(JSON.stringify(state.lastView, null, 2), "JSON");
});
$("#actCopyId").addEventListener("click", () => {
if (state.lastId) copyText(state.lastId, "id");
});
/* ---------------- recent chips (localStorage — the API has no list endpoint) ---------------- */
function loadRecent() {
try {
const raw = localStorage.getItem("pb.recent");
const arr = raw ? JSON.parse(raw) : [];
return Array.isArray(arr) ? arr : [];
} catch {
return [];
}
}
function saveRecent(list) {
try {
localStorage.setItem("pb.recent", JSON.stringify(list));
} catch {
/* private mode — chips just won't persist */
}
}
function remember(out) {
const list = loadRecent().filter((r) => r.id !== out.id);
list.unshift({ id: out.id, title: out.title, type: out.type, created_at: out.created_at });
saveRecent(list.slice(0, 12));
renderChips();
}
function renderChips() {
const list = loadRecent();
const box = $("#chips");
box.innerHTML = "";
$("#recentClear").hidden = list.length === 0;
if (!list.length) {
const s = document.createElement("span");
s.className = "chips-empty";
s.textContent = "nothing yet — pastes you create land here";
box.appendChild(s);
return;
}
for (const r of list) {
const chip = document.createElement("div");
chip.className = "chip";
chip.title = r.id + (r.title ? " — " + r.title : "") + (r.created_at ? " · " + fmtTime(r.created_at) : "");
const ico = document.createElement("span");
ico.className = "chip-ico";
ico.textContent = TYPE_ICON[r.type] || "📄";
const id = document.createElement("span");
id.className = "chip-id";
id.textContent = r.id;
chip.appendChild(ico);
chip.appendChild(id);
if (r.title) {
const t = document.createElement("span");
t.className = "chip-title";
t.textContent = r.title;
chip.appendChild(t);
}
const x = document.createElement("button");
x.className = "chip-x";
x.setAttribute("aria-label", "Remove from recent");
x.textContent = "×";
x.onclick = (e) => {
e.stopPropagation();
saveRecent(loadRecent().filter((q) => q.id !== r.id));
renderChips();
};
chip.appendChild(x);
chip.addEventListener("click", () => openPaste(r.id));
box.appendChild(chip);
}
}
$("#recentClear").addEventListener("click", () => {
saveRecent([]);
renderChips();
});
/* ---------------- boot ---------------- */
setType("text");
renderChips();
pingHealth();
setInterval(pingHealth, 30000);
loadBadges();
})();