Compare commits

...
16 Commits
17 changed files with 1200 additions and 268 deletions
+1 -1
View File
@@ -4,7 +4,7 @@
V1 scope:
- accepts only public `https://chatgpt.com/share/...` and `https://chat.openai.com/share/...` URLs
- accepts public ChatGPT links under the legacy `/share/...` path and the current `/s/t_...` path
- admin-only capture/delete UI at `${AISHARE_BASE_PATH}/admin`
- public reader pages generated as static artifacts under `/data/html/<slug>`
- screenshots under `/data/screenshots/<slug>`
+1 -1
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="robots" content="noindex" />
<title>AI Share Admin</title>
<title>AI Share</title>
</head>
<body>
<div id="app"></div>
+256 -147
View File
@@ -10,253 +10,362 @@ type Capture = {
createdAt: string;
updatedAt: string;
capturedAt: string | null;
retentionDays: number;
expiresAt: string;
publicUrl: string | null;
};
const tokenKey = "aishare.adminToken";
const themeKey = "aishare.theme";
const legacyThemeKey = "aishare.adminTheme";
const app = document.querySelector<HTMLDivElement>("#app")!;
let token = localStorage.getItem(tokenKey) || "";
let adminToken = "";
let isAdmin = false;
let page = 1;
const pageSize = 20;
let pageSize = 20;
let totalPages = 1;
let polling: number | undefined;
let toastTimer: number | undefined;
let keyValidationTimer: number | undefined;
let manualTheme = false;
function serviceBaseUrl() {
const icons = {
sun: `<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 3v2m0 14v2M3 12h2m14 0h2M5.6 5.6 7 7m10 10 1.4 1.4M18.4 5.6 17 7M7 17l-1.4 1.4"/></svg>`,
moon: `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M20 14.6A7.6 7.6 0 0 1 9.4 4 8 8 0 1 0 20 14.6Z"/></svg>`,
refresh: `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M20 11a8 8 0 1 0-2.3 6"/><path d="M20 5v6h-6"/></svg>`
};
function preferredTheme(): "light" | "dark" {
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}
function savedTheme(): "light" | "dark" | null {
const theme = localStorage.getItem(themeKey) || localStorage.getItem(legacyThemeKey);
return theme === "light" || theme === "dark" ? theme : null;
}
function applyTheme(theme: "light" | "dark", manual: boolean): void {
document.documentElement.dataset.theme = theme;
document.documentElement.style.colorScheme = theme;
manualTheme = manual;
if (manual) localStorage.setItem(themeKey, theme);
updateThemeToggle();
}
function updateThemeToggle(): void {
const theme = document.documentElement.dataset.theme === "dark" ? "dark" : "light";
const toggle = document.querySelector<HTMLButtonElement>("[data-theme-toggle]");
if (!toggle) return;
const label = theme === "dark" ? "Switch to light theme" : "Switch to dark theme";
toggle.setAttribute("aria-label", label);
toggle.setAttribute("title", label);
}
function initTheme(): void {
const theme = savedTheme();
applyTheme(theme || preferredTheme(), Boolean(theme));
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
if (!manualTheme) applyTheme(preferredTheme(), false);
});
}
function serviceBaseUrl(): URL {
const url = new URL(location.href);
url.pathname = url.pathname.replace(/\/admin\/?$/, "/");
if (!url.pathname.endsWith("/")) url.pathname += "/";
url.search = "";
url.hash = "";
return url;
}
function api(path: string, options: RequestInit = {}) {
function api(path: string, options: RequestInit = {}): Promise<Response> {
return fetch(new URL(`api${path}`, serviceBaseUrl()), {
...options,
headers: {
"content-type": "application/json",
...(token ? { authorization: `Bearer ${token}` } : {}),
...(isAdmin && adminToken ? { authorization: `Bearer ${adminToken}` } : {}),
...(options.headers || {})
}
});
}
function captureUrl(capture: Capture) {
function captureUrl(capture: Capture): string {
if (capture.slug) return new URL(`${capture.slug}/`, serviceBaseUrl()).href;
return capture.publicUrl || "";
}
function fmt(value: string | null) {
if (!value) return "";
function fmt(value: string | null): string {
if (!value) return "";
return new Date(value).toLocaleString();
}
function statusClass(status: Capture["status"]) {
return `pill ${status}`;
function escapeHtml(value: string): string {
return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
async function copy(text: string) {
async function copy(text: string): Promise<void> {
try {
await navigator.clipboard.writeText(text);
} catch {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.setAttribute("readonly", "");
textarea.style.position = "fixed";
textarea.style.left = "-9999px";
document.body.appendChild(textarea);
textarea.select();
const ok = document.execCommand("copy");
textarea.remove();
if (!ok) throw new Error("copy failed");
}
}
function renderShell() {
function showToast(message: string): void {
let toast = document.querySelector<HTMLDivElement>("[data-toast]");
if (!toast) {
toast = document.createElement("div");
toast.className = "toast";
toast.dataset.toast = "true";
toast.setAttribute("role", "status");
toast.setAttribute("aria-live", "polite");
document.body.appendChild(toast);
}
toast.textContent = message;
toast.dataset.visible = "true";
if (toastTimer) window.clearTimeout(toastTimer);
toastTimer = window.setTimeout(() => delete toast?.dataset.visible, 1800);
}
function renderShell(): void {
app.innerHTML = `
<nav class="navbar">
<div class="nav-inner">
<a class="brand" href="${escapeHtml(serviceBaseUrl().pathname)}" aria-label="AI Share home"><span class="brand-mark">A</span><span>AI Share</span></a>
<div class="nav-actions">
<label class="admin-key-field">
<span class="sr-only">Admin key</span>
<input id="admin-key" type="password" autocomplete="current-password" placeholder="Admin key" value="${escapeHtml(adminToken)}" aria-label="Admin key" />
<span class="key-state" data-key-state aria-hidden="true"></span>
</label>
<button class="icon-button theme-toggle" type="button" data-theme-toggle aria-label="Switch theme"><span class="sun-icon">${icons.sun}</span><span class="moon-icon">${icons.moon}</span></button>
</div>
</div>
</nav>
<main class="shell">
<header class="header">
<section class="intro">
<div>
<h1>AI Share Admin</h1>
<p>Capture public ChatGPT shares as read-only snapshots.</p>
</div>
<button class="icon-button" id="reset-token" title="Reset admin token" aria-label="Reset admin token">Reset</button>
</header>
<section class="panel token-panel" ${token ? "hidden" : ""}>
<label>Admin token</label>
<div class="row">
<input id="token-input" type="password" autocomplete="current-password" placeholder="AISHARE_ADMIN_TOKEN" />
<button id="save-token">Save</button>
<p class="eyebrow">Public ChatGPT snapshots</p>
<h1>${isAdmin ? "Capture library" : "Your captures"}</h1>
<p>${isAdmin ? "Manage every submitted snapshot and its retention window." : "Save a public ChatGPT conversation as an immutable page and screenshot."}</p>
</div>
${isAdmin ? '<span class="admin-badge">Admin view</span>' : ""}
</section>
<section class="panel" ${token ? "" : "hidden"}>
<section class="panel capture-panel">
<form id="capture-form" class="capture-form">
<label>
ChatGPT share URL
<input name="sourceUrl" required inputmode="url" placeholder="https://chatgpt.com/share/..." />
</label>
<label>
Slug
<input name="slug" placeholder="Optional" />
</label>
<button type="submit">Capture</button>
<label class="url-field">ChatGPT share URL<input name="sourceUrl" required inputmode="url" autocomplete="url" placeholder="https://chatgpt.com/s/t_…" /></label>
${isAdmin ? '<label class="slug-field">Custom slug<input name="slug" placeholder="Optional" /></label>' : ""}
<label class="retention-field">Keep for<select name="retentionDays" aria-label="Retention period"><option value="3" selected>3 days</option><option value="7">7 days</option><option value="10">10 days</option><option value="30">30 days</option></select></label>
<button class="primary" type="submit">Capture</button>
</form>
<p id="form-status" class="status-line"></p>
<p id="form-status" class="status-line" aria-live="polite"></p>
</section>
<section class="panel table-panel" ${token ? "" : "hidden"}>
<section class="panel table-panel">
<div class="table-head">
<h2>Captured Shares</h2>
<div><h2>${isAdmin ? "All captures" : "Recent captures"}</h2><p class="table-summary" id="table-summary">Loading…</p></div>
<div class="actions">
<button id="refresh">Refresh</button>
<button id="delete-all" class="danger">Delete all</button>
<button class="icon-button" id="refresh" title="Refresh" aria-label="Refresh">${icons.refresh}</button>
${isAdmin ? '<button id="delete-all" class="danger">Delete all</button>' : ""}
</div>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Title</th>
<th>Status</th>
<th>Created</th>
<th>Link</th>
<th></th>
</tr>
</thead>
<tbody id="captures-body"></tbody>
<thead><tr><th>Capture</th><th>Status</th><th>Created</th><th>Expires</th><th><span class="sr-only">Actions</span></th></tr></thead>
<tbody id="captures-body"><tr><td colspan="5" class="empty-state">Loading captures…</td></tr></tbody>
</table>
</div>
<div class="pager">
<button id="prev">Previous</button>
<span id="page-label"></span>
<button id="next">Next</button>
<div class="pager" aria-label="Pagination">
<span id="page-label" class="page-label"></span>
<select id="page-size" aria-label="Rows per page"><option value="10">10 rows</option><option value="20">20 rows</option><option value="50">50 rows</option><option value="100">100 rows</option></select>
<button class="pager-button" id="prev" aria-label="Previous page">←</button>
<button class="pager-button" id="next" aria-label="Next page">→</button>
</div>
</section>
</main>
`;
</main>`;
document.querySelector("#save-token")?.addEventListener("click", () => {
const input = document.querySelector<HTMLInputElement>("#token-input");
token = input?.value.trim() || "";
if (token) {
localStorage.setItem(tokenKey, token);
renderShell();
void loadCaptures();
bindShellEvents();
updateThemeToggle();
}
function bindShellEvents(): void {
const keyInput = document.querySelector<HTMLInputElement>("#admin-key");
keyInput?.addEventListener("input", () => {
if (keyValidationTimer) window.clearTimeout(keyValidationTimer);
keyValidationTimer = window.setTimeout(() => void validateAdminKey(keyInput.value.trim()), 350);
});
keyInput?.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
event.preventDefault();
if (keyValidationTimer) window.clearTimeout(keyValidationTimer);
void validateAdminKey(keyInput.value.trim());
}
});
document.querySelector("#reset-token")?.addEventListener("click", () => {
localStorage.removeItem(tokenKey);
token = "";
if (polling) window.clearInterval(polling);
renderShell();
document.querySelector("[data-theme-toggle]")?.addEventListener("click", () => {
applyTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark", true);
});
document.querySelector("#capture-form")?.addEventListener("submit", async (event) => {
event.preventDefault();
const form = event.currentTarget as HTMLFormElement;
const data = new FormData(form);
const status = document.querySelector("#form-status")!;
status.textContent = "Queued";
const status = document.querySelector<HTMLElement>("#form-status")!;
status.textContent = "Queueing capture…";
const response = await api("/captures", {
method: "POST",
body: JSON.stringify({
sourceUrl: data.get("sourceUrl"),
slug: data.get("slug")
})
body: JSON.stringify({ sourceUrl: data.get("sourceUrl"), slug: isAdmin ? data.get("slug") : null, retentionDays: Number(data.get("retentionDays") || 3) })
});
const body = await response.json();
const body = await response.json().catch(() => ({}));
if (!response.ok) {
status.textContent = body.error || "Capture failed to queue";
status.textContent = body.error || "Capture could not be queued.";
showToast(status.textContent);
return;
}
form.reset();
status.textContent = "Capture queued";
status.textContent = "Capture queued.";
showToast("Capture queued");
page = 1;
await loadCaptures();
startPolling();
});
document.querySelector("#refresh")?.addEventListener("click", () => loadCaptures());
document.querySelector("#refresh")?.addEventListener("click", async () => {
await loadCaptures();
showToast("Refreshed");
});
document.querySelector("#delete-all")?.addEventListener("click", async () => {
if (!confirm("Delete all captures and related files?")) return;
await api("/captures", { method: "DELETE" });
if (!confirm("Delete every capture and all related files?")) return;
const response = await api("/captures", { method: "DELETE" });
if (!response.ok) return showToast("Delete all failed");
page = 1;
await loadCaptures();
showToast("All captures deleted");
});
document.querySelector("#prev")?.addEventListener("click", async () => {
if (page > 1) { page -= 1; await loadCaptures(); }
});
document.querySelector("#next")?.addEventListener("click", async () => {
if (page < totalPages) { page += 1; await loadCaptures(); }
});
const pageSizeSelect = document.querySelector<HTMLSelectElement>("#page-size");
if (pageSizeSelect) {
pageSizeSelect.value = String(pageSize);
pageSizeSelect.addEventListener("change", async () => {
pageSize = Number(pageSizeSelect.value);
page = 1;
await loadCaptures();
});
document.querySelector("#prev")?.addEventListener("click", async () => {
if (page > 1) {
page -= 1;
await loadCaptures();
}
});
document.querySelector("#next")?.addEventListener("click", async () => {
page += 1;
await loadCaptures();
});
}
async function loadCaptures() {
if (!token) return;
const response = await api(`/captures?page=${page}&pageSize=${pageSize}`);
if (response.status === 401) {
async function validateAdminKey(candidate: string, initial = false): Promise<void> {
const response = await fetch(new URL("api/session", serviceBaseUrl()), {
headers: candidate ? { authorization: `Bearer ${candidate}` } : {}
});
const body = await response.json().catch(() => ({ isAdmin: false }));
const valid = Boolean(body.isAdmin);
const changed = valid !== isAdmin || (valid && candidate !== adminToken);
if (valid) {
adminToken = candidate;
isAdmin = true;
localStorage.setItem(tokenKey, candidate);
} else {
adminToken = "";
isAdmin = false;
localStorage.removeItem(tokenKey);
token = "";
}
if (changed || initial) {
page = 1;
if (polling) { window.clearInterval(polling); polling = undefined; }
renderShell();
await loadCaptures();
if (!initial) showToast(valid ? "Admin view unlocked" : "Showing your captures");
} else if (!valid) {
document.querySelector("[data-key-state]")?.setAttribute("data-invalid", "true");
}
}
async function loadCaptures(): Promise<void> {
const response = await api(`/captures?page=${page}&pageSize=${pageSize}`);
if (!response.ok) {
showToast("Could not load captures");
return;
}
const body = await response.json();
if (Boolean(body.isAdmin) !== isAdmin) {
isAdmin = Boolean(body.isAdmin);
if (!isAdmin) { adminToken = ""; localStorage.removeItem(tokenKey); }
renderShell();
return loadCaptures();
}
const captures = body.captures as Capture[];
const tbody = document.querySelector<HTMLTableSectionElement>("#captures-body")!;
tbody.innerHTML = captures
.map((capture) => {
const title = capture.title || capture.slug || capture.sourceUrl;
const link = captureUrl(capture);
return `
<tr>
<td>
<div class="title-cell">${escapeHtml(title)}</div>
<div class="sub">${escapeHtml(capture.slug || capture.id)}</div>
${capture.errorPublic ? `<div class="error">${escapeHtml(capture.errorPublic)}</div>` : ""}
</td>
<td><span class="${statusClass(capture.status)}">${capture.status}</span></td>
<td>${escapeHtml(fmt(capture.createdAt))}</td>
<td>
${link ? `<button class="small" data-copy="${escapeHtml(link)}">Copy</button> <a class="small link" href="${escapeHtml(link)}" target="_blank" rel="noreferrer">Open</a>` : ""}
</td>
<td><button class="small danger" data-delete="${capture.id}">Delete</button></td>
</tr>`;
})
.join("");
tbody.querySelectorAll<HTMLButtonElement>("[data-copy]").forEach((button) => {
button.addEventListener("click", async () => {
await copy(button.dataset.copy || "");
button.textContent = "Copied";
setTimeout(() => (button.textContent = "Copy"), 1200);
});
});
tbody.querySelectorAll<HTMLButtonElement>("[data-delete]").forEach((button) => {
button.addEventListener("click", async () => {
if (!confirm("Delete this capture and related files?")) return;
await api(`/captures/${button.dataset.delete}`, { method: "DELETE" });
await loadCaptures();
});
});
const total = Number(body.total || 0);
document.querySelector("#page-label")!.textContent = `Page ${page} of ${Math.max(1, Math.ceil(total / pageSize))}`;
(document.querySelector("#prev") as HTMLButtonElement).disabled = page <= 1;
(document.querySelector("#next") as HTMLButtonElement).disabled = page * pageSize >= total;
totalPages = Math.max(1, Math.ceil(total / pageSize));
if (page > totalPages) { page = totalPages; return loadCaptures(); }
const tbody = document.querySelector<HTMLTableSectionElement>("#captures-body")!;
tbody.innerHTML = captures.length ? captures.map(captureRow).join("") : `<tr><td colspan="5" class="empty-state"><strong>No captures yet</strong><span>Submit a public ChatGPT share above to get started.</span></td></tr>`;
bindRowEvents(tbody);
document.querySelector("#table-summary")!.textContent = `${total} ${total === 1 ? "capture" : "captures"}${isAdmin ? " across all users" : " in this browser"}`;
document.querySelector("#page-label")!.textContent = `Page ${page} of ${totalPages}`;
const size = document.querySelector<HTMLSelectElement>("#page-size");
if (size) size.value = String(pageSize);
(document.querySelector("#prev") as HTMLButtonElement).disabled = page <= 1;
(document.querySelector("#next") as HTMLButtonElement).disabled = page >= totalPages;
if (captures.some((capture) => ["queued", "capturing", "rendering"].includes(capture.status))) startPolling();
}
function startPolling() {
function captureRow(capture: Capture): string {
const title = capture.title || capture.slug || capture.sourceUrl;
const link = captureUrl(capture);
return `<tr>
<td><div class="title-cell">${escapeHtml(title)}</div><div class="sub">${escapeHtml(capture.slug || capture.id)}</div>${capture.errorPublic ? `<div class="error">${escapeHtml(capture.errorPublic)}</div>` : ""}</td>
<td><span class="pill ${capture.status}">${capture.status}</span></td>
<td class="date-cell">${escapeHtml(fmt(capture.createdAt))}</td>
<td class="date-cell"><strong>${capture.retentionDays} days</strong><span>${escapeHtml(fmt(capture.expiresAt))}</span></td>
<td><div class="row-actions">${link ? `<button class="small" data-copy="${escapeHtml(link)}">Copy</button><a class="small link" href="${escapeHtml(link)}" target="_blank" rel="noreferrer">Open</a>` : ""}${capture.status === "failed" ? `<button class="small" data-retry="${capture.id}">Retry</button>` : ""}<button class="small danger" data-delete="${capture.id}">Delete</button></div></td>
</tr>`;
}
function bindRowEvents(tbody: HTMLTableSectionElement): void {
tbody.querySelectorAll<HTMLButtonElement>("[data-copy]").forEach((button) => button.addEventListener("click", async () => {
try { await copy(button.dataset.copy || ""); showToast("Link copied"); } catch { showToast("Copy failed"); }
}));
tbody.querySelectorAll<HTMLButtonElement>("[data-retry]").forEach((button) => button.addEventListener("click", async () => {
const response = await api(`/captures/${button.dataset.retry}/retry`, { method: "POST" });
if (!response.ok) return showToast("Retry failed");
await loadCaptures(); startPolling(); showToast("Retry queued");
}));
tbody.querySelectorAll<HTMLButtonElement>("[data-delete]").forEach((button) => button.addEventListener("click", async () => {
if (!confirm("Delete this capture and its files?")) return;
const response = await api(`/captures/${button.dataset.delete}`, { method: "DELETE" });
if (!response.ok) return showToast("Delete failed");
await loadCaptures(); showToast("Capture deleted");
}));
}
function startPolling(): void {
if (polling) return;
polling = window.setInterval(async () => {
await loadCaptures();
const active = [...document.querySelectorAll(".pill")].some((pill) => ["queued", "capturing", "rendering"].includes(pill.textContent || ""));
if (!active && polling) {
window.clearInterval(polling);
polling = undefined;
}
if (!active && polling) { window.clearInterval(polling); polling = undefined; }
}, 3000);
}
function escapeHtml(value: string) {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
initTheme();
renderShell();
void loadCaptures();
void validateAdminKey(localStorage.getItem(tokenKey) || "", true);
+113 -49
View File
@@ -1,63 +1,127 @@
:root {
color-scheme: light dark;
--bg: #f6f7f9;
--bg: #f4f5f7;
--panel: #ffffff;
--text: #1f2328;
--muted: #6b7280;
--border: #d9dee7;
--accent: #0f766e;
--panel-soft: #f8f9fa;
--text: #17191c;
--muted: #69717d;
--border: #dfe3e8;
--accent: #0b7a65;
--accent-hover: #096b59;
--accent-soft: #e5f5f0;
--danger: #b42318;
--danger-soft: #fff0ee;
--warning: #9a6700;
--shadow: rgb(24 29 36 / 8%);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Arial, sans-serif;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #18181b;
--panel: #242428;
--text: #f4f4f5;
--muted: #a1a1aa;
--border: #3f3f46;
--accent: #14b8a6;
--danger: #f87171;
--bg: #171819; --panel: #222426; --panel-soft: #292c2f; --text: #f0f2f3; --muted: #a5abb3; --border: #3b3f44;
--accent: #28b995; --accent-hover: #34caa4; --accent-soft: #173c34; --danger: #ff8177; --danger-soft: #442724; --warning: #e9b949; --shadow: rgb(0 0 0 / 28%);
}
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--text); font-size: 15px; }
button, input { font: inherit; }
.shell { max-width: 1120px; margin: 0 auto; padding: 28px 20px 48px; }
.header { display: flex; justify-content: space-between; gap: 20px; align-items: start; margin-bottom: 22px; }
h1, h2, p { margin: 0; }
h1 { font-size: 30px; line-height: 1.15; letter-spacing: 0; }
h2 { font-size: 18px; }
.header p, .sub, .status-line { color: var(--muted); margin-top: 6px; }
.panel { background: var(--panel); border: 1px solid var(--border); border-radius: 8px; padding: 18px; margin-bottom: 18px; }
.row, .capture-form, .table-head, .actions, .pager { display: flex; gap: 10px; align-items: end; }
.capture-form { display: grid; grid-template-columns: minmax(280px, 1fr) minmax(160px, 260px) auto; }
label { display: grid; gap: 6px; color: var(--muted); font-size: 13px; }
input { width: 100%; min-height: 40px; border: 1px solid var(--border); border-radius: 7px; padding: 8px 10px; background: var(--panel); color: var(--text); }
button, .small.link { min-height: 38px; border: 1px solid var(--border); border-radius: 7px; padding: 8px 12px; background: var(--panel); color: var(--text); text-decoration: none; cursor: pointer; white-space: nowrap; }
button[type="submit"] { background: var(--accent); border-color: var(--accent); color: white; }
.danger { color: var(--danger); }
.icon-button { min-height: 34px; }
.table-head { justify-content: space-between; align-items: center; margin-bottom: 12px; }
.table-wrap { overflow-x: auto; border: 1px solid var(--border); border-radius: 8px; }
table { width: 100%; border-collapse: collapse; min-width: 760px; }
th, td { text-align: left; padding: 12px; border-bottom: 1px solid var(--border); vertical-align: top; }
th { font-size: 12px; color: var(--muted); font-weight: 650; }
tr:last-child td { border-bottom: 0; }
.title-cell { font-weight: 650; max-width: 420px; overflow-wrap: anywhere; }
.error { color: var(--danger); margin-top: 6px; max-width: 520px; }
.pill { display: inline-flex; align-items: center; min-height: 26px; border-radius: 999px; padding: 3px 9px; font-size: 12px; border: 1px solid var(--border); }
.pill.ready { color: var(--accent); }
.pill.failed { color: var(--danger); }
.pill.queued, .pill.capturing, .pill.rendering { color: #b7791f; }
.small { min-height: 32px; padding: 6px 9px; font-size: 13px; display: inline-flex; align-items: center; justify-content: center; }
.pager { justify-content: flex-end; margin-top: 12px; color: var(--muted); }
html[data-theme="light"] { color-scheme: light; --bg: #f4f5f7; --panel: #fff; --panel-soft: #f8f9fa; --text: #17191c; --muted: #69717d; --border: #dfe3e8; --accent: #0b7a65; --accent-hover: #096b59; --accent-soft: #e5f5f0; --danger: #b42318; --danger-soft: #fff0ee; --warning: #9a6700; --shadow: rgb(24 29 36 / 8%); }
html[data-theme="dark"] { color-scheme: dark; --bg: #171819; --panel: #222426; --panel-soft: #292c2f; --text: #f0f2f3; --muted: #a5abb3; --border: #3b3f44; --accent: #28b995; --accent-hover: #34caa4; --accent-soft: #173c34; --danger: #ff8177; --danger-soft: #442724; --warning: #e9b949; --shadow: rgb(0 0 0 / 28%); }
@media (max-width: 760px) {
.shell { padding: 20px 14px 36px; }
.header, .table-head, .actions, .pager { align-items: stretch; flex-direction: column; }
.capture-form { grid-template-columns: 1fr; }
button { width: 100%; }
* { box-sizing: border-box; }
html { min-height: 100%; background: var(--bg); }
body { min-width: 320px; margin: 0; background: var(--bg); color: var(--text); font-size: 15px; }
button, input, select { font: inherit; }
body, .navbar, .panel, input, select, button, .small.link, .table-wrap, th, td, .pill, .admin-badge { transition: background-color 220ms ease, border-color 220ms ease, color 220ms ease, box-shadow 220ms ease; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
.navbar { position: sticky; top: 0; z-index: 20; border-bottom: 1px solid var(--border); background: color-mix(in srgb, var(--panel) 92%, transparent); backdrop-filter: blur(14px); }
.nav-inner { width: min(1180px, 100%); min-height: 64px; margin: 0 auto; padding: 10px 24px; display: flex; align-items: center; justify-content: space-between; gap: 20px; }
.brand { display: inline-flex; align-items: center; gap: 10px; color: var(--text); font-size: 17px; font-weight: 720; text-decoration: none; letter-spacing: -.01em; }
.brand-mark { width: 30px; height: 30px; display: grid; place-items: center; border-radius: 9px; background: var(--text); color: var(--panel); font-size: 15px; }
.nav-actions { display: flex; align-items: center; gap: 9px; }
.admin-key-field { position: relative; display: block; }
.admin-key-field input { width: 184px; height: 38px; padding: 8px 32px 8px 11px; }
.key-state { position: absolute; right: 11px; top: 50%; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); transform: translateY(-50%); opacity: 0; }
.key-state[data-invalid="true"] { background: var(--danger); opacity: 1; }
.shell { width: min(1180px, 100%); margin: 0 auto; padding: 48px 24px 64px; }
.intro { display: flex; justify-content: space-between; align-items: end; gap: 24px; margin-bottom: 24px; }
.eyebrow { margin: 0 0 7px; color: var(--accent); font-size: 12px; font-weight: 750; letter-spacing: .08em; text-transform: uppercase; }
h1, h2, p { margin: 0; }
h1 { font-size: clamp(32px, 5vw, 48px); line-height: 1.06; letter-spacing: -.035em; }
h2 { font-size: 18px; letter-spacing: -.01em; }
.intro div > p:last-child { max-width: 660px; margin-top: 10px; color: var(--muted); font-size: 16px; line-height: 1.55; }
.admin-badge { align-self: center; border: 1px solid color-mix(in srgb, var(--accent) 42%, var(--border)); border-radius: 999px; padding: 6px 11px; background: var(--accent-soft); color: var(--accent); font-size: 12px; font-weight: 700; }
.panel { margin-bottom: 18px; border: 1px solid var(--border); border-radius: 12px; background: var(--panel); box-shadow: 0 8px 30px var(--shadow); }
.capture-panel { padding: 18px; }
.capture-form { display: grid; grid-template-columns: minmax(300px, 1fr) minmax(150px, 220px) 130px auto; gap: 12px; align-items: end; }
.capture-form:not(:has(.slug-field)) { grid-template-columns: minmax(300px, 1fr) 130px auto; }
label { display: grid; gap: 7px; color: var(--muted); font-size: 12px; font-weight: 650; }
input, select { width: 100%; min-height: 42px; border: 1px solid var(--border); border-radius: 8px; padding: 8px 11px; outline: 0; background: var(--panel); color: var(--text); }
input::placeholder { color: color-mix(in srgb, var(--muted) 72%, transparent); }
input:focus, select:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 16%, transparent); }
button, .small.link { min-height: 38px; border: 1px solid var(--border); border-radius: 8px; padding: 8px 12px; background: var(--panel); color: var(--text); text-decoration: none; cursor: pointer; white-space: nowrap; }
button:hover, .small.link:hover { background: var(--panel-soft); }
button:disabled { cursor: not-allowed; opacity: .42; }
.primary { min-height: 42px; border-color: var(--accent); background: var(--accent); color: #fff; font-weight: 700; }
.primary:hover { border-color: var(--accent-hover); background: var(--accent-hover); }
.danger { color: var(--danger); }
.status-line { min-height: 18px; margin-top: 10px; color: var(--muted); font-size: 13px; }
.icon-button { width: 38px; min-width: 38px; min-height: 38px; padding: 8px; display: inline-flex; align-items: center; justify-content: center; }
.icon-button svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.theme-toggle .moon-icon { display: none; }
html[data-theme="dark"] .theme-toggle .sun-icon { display: none; }
html[data-theme="dark"] .theme-toggle .moon-icon { display: block; }
.table-panel { padding: 18px; }
.table-head { display: flex; justify-content: space-between; align-items: center; gap: 18px; margin-bottom: 14px; }
.table-summary { margin-top: 4px; color: var(--muted); font-size: 13px; }
.actions { display: flex; align-items: center; gap: 8px; }
.table-wrap { overflow-x: auto; border: 1px solid var(--border); border-radius: 9px; }
table { width: 100%; min-width: 900px; border-collapse: collapse; }
th, td { padding: 13px 12px; border-bottom: 1px solid var(--border); text-align: left; vertical-align: top; }
th { background: var(--panel-soft); color: var(--muted); font-size: 11px; font-weight: 750; letter-spacing: .045em; text-transform: uppercase; }
tr:last-child td { border-bottom: 0; }
.title-cell { max-width: 390px; font-weight: 680; overflow-wrap: anywhere; }
.sub { margin-top: 4px; color: var(--muted); font-size: 12px; }
.error { max-width: 480px; margin-top: 6px; color: var(--danger); font-size: 13px; }
.date-cell { color: var(--muted); font-size: 13px; white-space: nowrap; }
.date-cell strong { display: block; color: var(--text); font-weight: 650; }
.date-cell span { display: block; margin-top: 3px; font-size: 11px; }
.pill { display: inline-flex; min-height: 25px; align-items: center; border: 1px solid var(--border); border-radius: 999px; padding: 3px 9px; font-size: 11px; font-weight: 700; text-transform: capitalize; }
.pill.ready { border-color: color-mix(in srgb, var(--accent) 30%, var(--border)); background: var(--accent-soft); color: var(--accent); }
.pill.failed { background: var(--danger-soft); color: var(--danger); }
.pill.queued, .pill.capturing, .pill.rendering { color: var(--warning); }
.small { min-height: 30px; padding: 5px 8px; display: inline-flex; align-items: center; justify-content: center; font-size: 12px; }
.row-actions { display: flex; justify-content: flex-end; align-items: center; gap: 6px; white-space: nowrap; }
.empty-state { padding: 42px 20px; color: var(--muted); text-align: center; }
.empty-state strong, .empty-state span { display: block; }
.empty-state strong { margin-bottom: 5px; color: var(--text); font-size: 15px; }
.pager { display: flex; justify-content: flex-end; align-items: center; gap: 8px; margin-top: 14px; }
.page-label { margin-right: 4px; color: var(--muted); font-size: 13px; font-variant-numeric: tabular-nums; }
.pager select { width: auto; min-height: 36px; padding: 6px 30px 6px 10px; }
.pager-button { width: 38px; min-height: 36px; padding: 6px; }
.toast { position: fixed; left: 50%; bottom: 22px; z-index: 50; max-width: calc(100vw - 32px); transform: translate(-50%, 12px); border: 1px solid var(--border); border-radius: 9px; padding: 9px 13px; background: var(--panel); color: var(--text); box-shadow: 0 12px 32px var(--shadow); opacity: 0; pointer-events: none; transition: opacity 160ms ease, transform 160ms ease; }
.toast[data-visible="true"] { opacity: 1; transform: translate(-50%, 0); }
@media (max-width: 820px) {
.nav-inner { padding: 10px 16px; }
.brand span:last-child { display: none; }
.admin-key-field input { width: min(42vw, 184px); }
.shell { padding: 34px 16px 48px; }
.intro { align-items: flex-start; }
.capture-form, .capture-form:not(:has(.slug-field)) { grid-template-columns: 1fr 130px; }
.url-field, .slug-field { grid-column: 1 / -1; }
.primary { width: 100%; }
}
@media (max-width: 520px) {
.intro { display: block; }
.admin-badge { display: inline-flex; margin-top: 14px; }
.capture-form, .capture-form:not(:has(.slug-field)) { grid-template-columns: 1fr; }
.url-field, .slug-field { grid-column: auto; }
.table-head { align-items: flex-start; }
.table-panel, .capture-panel { padding: 14px; }
.pager { justify-content: space-between; flex-wrap: wrap; }
.page-label { width: 100%; }
}
+26
View File
@@ -13,6 +13,7 @@
"cheerio": "1.0.0",
"express": "^4.19.2",
"fs-extra": "^11.2.0",
"katex": "^0.17.0",
"nanoid": "^5.0.7",
"playwright": "1.61.1",
"sanitize-filename": "^1.6.3",
@@ -1403,6 +1404,15 @@
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
},
"node_modules/commander": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz",
"integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==",
"license": "MIT",
"engines": {
"node": ">= 12"
}
},
"node_modules/compress-commons": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/compress-commons/-/compress-commons-6.0.2.tgz",
@@ -2182,6 +2192,22 @@
"graceful-fs": "^4.1.6"
}
},
"node_modules/katex": {
"version": "0.17.0",
"resolved": "https://registry.npmjs.org/katex/-/katex-0.17.0.tgz",
"integrity": "sha512-Vdw0ATsQ9V+LuegM/BTwQqV/6cTl5lbGcIrU+BCgLxyf6bo38ybOr372tuSIxir3CN720flu1meYR6XzNMwQnw==",
"funding": [
"https://opencollective.com/katex",
"https://github.com/sponsors/katex"
],
"license": "MIT",
"dependencies": {
"commander": "^8.3.0"
},
"bin": {
"katex": "cli.js"
}
},
"node_modules/lazystream": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz",
+3 -1
View File
@@ -7,7 +7,8 @@
"dev": "tsx watch src/server.ts",
"build": "tsc && vite build",
"start": "node dist/server.js",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"test": "npm run build && node --test tests/*.test.mjs"
},
"dependencies": {
"archiver": "^7.0.1",
@@ -15,6 +16,7 @@
"cheerio": "1.0.0",
"express": "^4.19.2",
"fs-extra": "^11.2.0",
"katex": "^0.17.0",
"nanoid": "^5.0.7",
"playwright": "1.61.1",
"sanitize-filename": "^1.6.3",
+37 -7
View File
@@ -70,22 +70,52 @@ function contentTypeForAsset(filename: string): string {
if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg";
if (ext === ".webp") return "image/webp";
if (ext === ".gif") return "image/gif";
if (ext === ".woff2") return "font/woff2";
if (ext === ".woff") return "font/woff";
return "application/octet-stream";
}
async function assetDataUri(slug: string, assetReference: string): Promise<string | null> {
if (!assetReference || assetReference.startsWith("data:") || /^https?:\/\//i.test(assetReference)) return null;
const normalized = path.normalize(assetReference).replace(/^(\.\.(\/|\\|$))+/, "");
if (!normalized.startsWith("assets/")) return null;
const assetPath = path.join(artifactDir(slug), normalized);
const bytes = await fs.readFile(assetPath);
return `data:${contentTypeForAsset(assetPath)};base64,${bytes.toString("base64")}`;
}
async function inlineCssAssetUrls(slug: string, css: string): Promise<string> {
const urls = [...css.matchAll(/url\((["']?)([^)"']+)\1\)/g)]
.map((match) => match[2])
.filter((url) => url.startsWith("assets/"));
const replacements = new Map<string, string>();
await Promise.all(
[...new Set(urls)].map(async (url) => {
const dataUri = await assetDataUri(slug, url).catch(() => null);
if (dataUri) replacements.set(url, dataUri);
})
);
return css.replace(/url\((["']?)([^)"']+)\1\)/g, (match, quote: string, url: string) => {
const replacement = replacements.get(url);
return replacement ? `url("${replacement}")` : match;
});
}
export async function selfContainedHtml(slug: string): Promise<string> {
const html = await fs.readFile(artifactIndexPath(slug), "utf8");
const $ = cheerio.load(html);
for (const image of $("img").toArray()) {
const src = $(image).attr("src");
if (!src || src.startsWith("data:") || /^https?:\/\//i.test(src)) continue;
const normalized = path.normalize(src).replace(/^(\.\.(\/|\\|$))+/, "");
if (!normalized.startsWith("assets/")) continue;
const assetPath = path.join(artifactDir(slug), normalized);
const bytes = await fs.readFile(assetPath);
const data = `data:${contentTypeForAsset(assetPath)};base64,${bytes.toString("base64")}`;
$(image).attr("src", data);
if (!src) continue;
const data = await assetDataUri(slug, src).catch(() => null);
if (data) $(image).attr("src", data);
}
for (const style of $("style").toArray()) {
const css = $(style).html();
if (!css) continue;
$(style).html(await inlineCssAssetUrls(slug, css));
}
return $.html();
+366 -21
View File
@@ -12,6 +12,8 @@ import { config } from "./config.js";
import { artifactAssetsDir, artifactIndexPath, safeAssetName, screenshotPath, screenshotsDir } from "./artifacts.js";
import { slugify } from "./slug.js";
import { writeConversationArtifact, writeFailureArtifact } from "./render.js";
import { finalizeKatexAssets, prepareKatexAssets } from "./katex-assets.js";
import { isChatGptSharePath } from "./url.js";
import type { CaptureRow, NormalizedConversation, NormalizedMessage, ScreenshotVariant } from "./types.js";
interface ExtractedConversation {
@@ -21,11 +23,36 @@ interface ExtractedConversation {
const chatGptIconUrl = "https://chatgpt.com/cdn/assets/favicon-l4nq08hd.svg";
const screenshotOnlyCss = `
button,
input,
select,
textarea,
summary,
.icon-button,
[contenteditable="true"],
[role="button"],
[role="checkbox"],
[role="combobox"],
[role="listbox"],
[role="menu"],
[role="menuitem"],
[role="radio"],
[role="slider"],
[role="spinbutton"],
[role="switch"],
[role="tab"] {
display: none !important;
}`;
function publicErrorFor(error: unknown): string {
const message = error instanceof Error ? error.message : String(error);
if (/captcha|verify|robot/i.test(message)) {
return "ChatGPT asked for verification, so this public share could not be captured automatically.";
}
if (/unavailable|no longer public|not public|redirected away/i.test(message)) {
return "This ChatGPT share is not available publicly anymore, so it cannot be captured.";
}
if (/timeout/i.test(message)) {
return "The public ChatGPT share took too long to load.";
}
@@ -42,6 +69,15 @@ function timeoutSignal(ms: number): AbortSignal {
}
async function downloadAsset(assetUrl: string, slug: string): Promise<string | null> {
const downloaded = await downloadImage(assetUrl);
if (!downloaded) return null;
const filename = safeAssetName(assetUrl, downloaded.contentType, downloaded.bytes);
await fs.ensureDir(artifactAssetsDir(slug));
await fs.writeFile(path.join(artifactAssetsDir(slug), filename), downloaded.bytes);
return `assets/${filename}`;
}
async function downloadImage(assetUrl: string): Promise<{ contentType: string; bytes: Buffer } | null> {
const response = await fetch(assetUrl, {
signal: timeoutSignal(20_000),
headers: {
@@ -53,10 +89,14 @@ async function downloadAsset(assetUrl: string, slug: string): Promise<string | n
if (!contentType?.startsWith("image/")) return null;
const bytes = Buffer.from(await response.arrayBuffer());
if (bytes.byteLength > 20 * 1024 * 1024) return null;
const filename = safeAssetName(assetUrl, contentType, bytes);
await fs.ensureDir(artifactAssetsDir(slug));
await fs.writeFile(path.join(artifactAssetsDir(slug), filename), bytes);
return `assets/${filename}`;
return { contentType, bytes };
}
async function downloadAssetDataUri(assetUrl: string): Promise<string | null> {
const downloaded = await downloadImage(assetUrl);
if (!downloaded) return null;
if (downloaded.bytes.byteLength > 256 * 1024) return null;
return `data:${downloaded.contentType};base64,${downloaded.bytes.toString("base64")}`;
}
async function localizeAssets(conversation: NormalizedConversation, slug: string): Promise<{ failures: string[] }> {
@@ -81,9 +121,10 @@ async function localizeAssets(conversation: NormalizedConversation, slug: string
continue;
}
try {
const local = await downloadAsset(absolute, slug);
if (local) {
$(image).attr("src", local);
const isCitationIcon = $(image).closest("a[data-citation]").length > 0;
const src = isCitationIcon ? await downloadAssetDataUri(absolute) : await downloadAsset(absolute, slug);
if (src) {
$(image).attr("src", src);
} else {
$(image).removeAttr("src");
failures.push(absolute);
@@ -102,11 +143,114 @@ function normalizeCopiedHtml(html: string): string {
const $ = cheerio.load(html, {}, false);
$("script, style, iframe, object, embed, form, button, textarea, input, nav").remove();
$("svg")
.filter((_, element) => $(element).parents(".katex, .katex-display").length === 0)
.remove();
function escapeCode(value: string): string {
return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
function comparableMathText(value: string): string {
return value
.replace(/\\div/g, "÷")
.replace(/\s+/g, "")
.trim();
}
function trimDuplicateMathFallback(fallback: string, expression: string): string | null {
const target = comparableMathText(expression);
if (!target) return null;
let consumed = "";
let index = 0;
while (index < fallback.length && consumed.length < target.length) {
const next = fallback.startsWith("\\div", index) ? "÷" : fallback[index];
const width = fallback.startsWith("\\div", index) ? 4 : 1;
index += width;
if (/\s/.test(next)) continue;
consumed += next;
}
if (consumed === target) return fallback.slice(index);
const leading = fallback.match(/^\s*/)?.[0] || "";
const rest = fallback.slice(leading.length);
const fallbackRun = rest.match(/^[^\s<]+/)?.[0] || "";
const mathOperators = /[=∑∏√±×⋅*/^_≥≤<>+÷]/;
if (fallbackRun.length >= 3 && mathOperators.test(fallbackRun) && mathOperators.test(target)) {
return `${leading}${rest.slice(fallbackRun.length)}`;
}
const firstLine = rest.split(/\n/, 1)[0] || "";
const compactLine = comparableMathText(firstLine);
if (compactLine.length >= 8 && mathOperators.test(compactLine) && mathOperators.test(target)) {
const available = new Map<string, number>();
for (const char of target) available.set(char, (available.get(char) || 0) + 1);
let shared = 0;
for (const char of compactLine) {
const count = available.get(char) || 0;
if (count <= 0) continue;
available.set(char, count - 1);
shared += 1;
}
if (shared / Math.min(target.length, compactLine.length) >= 0.6) {
return `${leading}${rest.slice(firstLine.length)}`;
}
}
return null;
}
function normalizeMathMl(document: cheerio.CheerioAPI): void {
type DomNode = {
type?: string;
name?: string;
data?: string;
children?: DomNode[];
parent?: DomNode;
};
function visibleMathText(math: DomNode): string {
const visibleMathNode = document(math as never).clone();
visibleMathNode.find("annotation, annotation-xml").remove();
return visibleMathNode.text();
}
function trimTextNode(node: DomNode | undefined, expression: string): boolean {
if (!node || node.type !== "text" || typeof node.data !== "string") return false;
const trimmed = trimDuplicateMathFallback(node.data, expression);
if (trimmed === null) return false;
node.data = trimmed;
return true;
}
function trimSimpleFallbackElement(node: DomNode | undefined, expression: string): boolean {
if (!node || node.type !== "tag" || node.name !== "span") return false;
const children = node.children || [];
if (children.length !== 1 || children[0]?.type !== "text") return false;
return trimTextNode(children[0], expression);
}
function normalizeChildList(children: DomNode[]): void {
for (let index = 0; index < children.length; index += 1) {
const child = children[index];
if (child?.children) normalizeChildList(child.children);
if (child?.type !== "tag" || child.name !== "math") continue;
const visibleMath = visibleMathText(child);
const next = children[index + 1];
trimTextNode(next, visibleMath) || trimSimpleFallbackElement(next, visibleMath);
}
}
document("math").find("annotation, annotation-xml").remove();
normalizeChildList(document.root()[0].children as DomNode[]);
document("math").each((_, math) => {
document(math).find("annotation, annotation-xml").remove();
});
}
$("pre")
.toArray()
.filter((pre) => $(pre).parents("pre").length === 0)
@@ -138,11 +282,19 @@ function normalizeCopiedHtml(html: string): string {
});
if (decorativeImages.length > 0) {
link.attr("data-citation", "true");
link.removeAttr("alt");
const firstImageHtml = $.html(decorativeImages.first());
const label = link.text().replace(/\s+/g, " ").trim();
link.empty();
if (firstImageHtml) link.append(firstImageHtml);
if (label) link.append(`<span>${escapeCode(label)}</span>`);
}
});
$("span").each((_, span) => {
const element = $(span);
if (element.closest("a[data-citation]").length > 0) return;
if (element.closest(".katex, .katex-display").length > 0) return;
if (Object.keys(span.attribs || {}).length === 0) element.replaceWith(element.contents());
});
@@ -153,8 +305,14 @@ function normalizeCopiedHtml(html: string): string {
);
});
$(":empty").not("br,img,hr").remove();
return $.html().trim();
$(":empty")
.not("br,img,hr")
.filter((_, element) => $(element).parents("math, .katex, .katex-display").length === 0)
.remove();
const finalDocument = cheerio.load($.html(), {}, false);
normalizeMathMl(finalDocument);
return finalDocument.html().trim();
}
function findChromiumExecutable(): string {
@@ -207,6 +365,19 @@ async function waitForCdp(port: number, process: ChildProcess): Promise<void> {
throw new Error("Chromium CDP endpoint did not become ready.");
}
async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
let timeout: NodeJS.Timeout | undefined;
const timeoutPromise = new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms.`)), timeoutMs);
});
try {
return await Promise.race([promise, timeoutPromise]);
} finally {
if (timeout) clearTimeout(timeout);
promise.catch(() => undefined);
}
}
async function stopProcess(process: ChildProcess): Promise<void> {
if (process.exitCode !== null || process.signalCode !== null) return;
process.kill("SIGTERM");
@@ -250,17 +421,26 @@ async function extractConversation(sourceUrl: string): Promise<ExtractedConversa
await waitForCdp(port, chromiumProcess);
browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`, { timeout: config.captureTimeoutMs });
const context = browser.contexts()[0];
let page = context.pages().find((candidate) => candidate.url().includes("/share/")) || context.pages()[0];
const isSharePage = (candidate: { url(): string }): boolean => {
try {
return isChatGptSharePath(new URL(candidate.url()).pathname);
} catch {
return false;
}
};
let page = context.pages().find(isSharePage) || context.pages()[0];
for (let attempt = 0; !page && attempt < 100; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 100));
page = context.pages().find((candidate) => candidate.url().includes("/share/")) || context.pages()[0];
page = context.pages().find(isSharePage) || context.pages()[0];
}
if (!page) throw new Error("Chromium CDP page target was not created.");
await page.setViewportSize({ width: 1360, height: 900 }).catch(() => undefined);
page.setDefaultTimeout(config.captureTimeoutMs);
const expectedPath = new URL(sourceUrl).pathname;
await page
.waitForFunction(
() => {
(sharePath) => {
if (!location.pathname.startsWith(sharePath)) return true;
const bodyText = document.body?.innerText || document.body?.textContent || "";
if (/verify you are human|captcha|unusual activity/i.test(bodyText)) return true;
if (document.querySelectorAll("[data-message-author-role]").length > 0) return true;
@@ -268,24 +448,77 @@ async function extractConversation(sourceUrl: string): Promise<ExtractedConversa
if ((markdown?.textContent || "").trim().length > 0) return true;
return /(?:^|\s)(You said:|ChatGPT said:)/.test(bodyText);
},
expectedPath,
{ timeout: config.captureTimeoutMs }
)
.catch(() => undefined);
await page.waitForLoadState("networkidle", { timeout: 5_000 }).catch(() => undefined);
await page.waitForTimeout(1000);
await page.evaluate(() => window.scrollTo(0, 0)).catch(() => undefined);
await page
.waitForFunction(
() => {
const firstTurn = document.querySelector("[data-testid='conversation-turn-1'], [data-turn]");
if (!firstTurn) return false;
return Boolean(firstTurn.querySelector("[data-message-author-role]")) || (firstTurn.textContent || "").trim().length > 0;
},
{ timeout: 3_000 }
)
.catch(() => undefined);
await page.waitForTimeout(750);
const extracted = await page.evaluate(() => {
const actualUrl = page.url();
if (!new URL(actualUrl).pathname.startsWith(expectedPath)) {
throw new Error(`ChatGPT share is unavailable or no longer public: page redirected away to ${actualUrl}.`);
}
const extracted = await withTimeout(page.evaluate(() => {
function cleanHtml(root: Element): string {
const clone = root.cloneNode(true) as Element;
clone.querySelectorAll("script, style, iframe, object, embed, form, button, textarea, input, nav").forEach((node) => node.remove());
clone.querySelectorAll("*").forEach((element) => {
Array.from(element.attributes).forEach((attr) => {
const name = attr.name.toLowerCase();
const keep = ["href", "src", "alt", "title", "colspan", "rowspan"].includes(name);
const elementClass = element.getAttribute("class") || "";
const inMathOrKatex =
element.closest("math, .katex, .katex-display") !== null ||
/\bkatex(?:-|$)/.test(elementClass);
const inKatexSvg = inMathOrKatex && ["svg", "path", "line"].includes(element.tagName.toLowerCase());
const keep =
["href", "src", "alt", "title", "colspan", "rowspan"].includes(name) ||
(inKatexSvg &&
[
"aria-hidden",
"class",
"d",
"fill",
"height",
"style",
"viewbox",
"width",
"xmlns"
].includes(name)) ||
(inMathOrKatex &&
[
"aria-hidden",
"class",
"display",
"encoding",
"fence",
"mathvariant",
"maxsize",
"minsize",
"separator",
"stretchy",
"style",
"xmlns"
].includes(name));
if (name.startsWith("on") || !keep) element.removeAttribute(attr.name);
if ((name === "href" || name === "src") && /^javascript:/i.test(attr.value)) element.removeAttribute(attr.name);
if (name === "style" && /(?:expression|@import|url\s*\()/i.test(attr.value)) element.removeAttribute(attr.name);
});
});
return clone.innerHTML.trim();
}
@@ -302,7 +535,10 @@ async function extractConversation(sourceUrl: string): Promise<ExtractedConversa
const title =
document.querySelector("h1")?.textContent?.trim() ||
document.title.replace(/\s*[|-]\s*ChatGPT\s*$/i, "").trim() ||
document.title
.replace(/^ChatGPT\s*[|-]\s*/i, "")
.replace(/\s*[|-]\s*ChatGPT\s*$/i, "")
.trim() ||
"ChatGPT Share";
const roleNodes = Array.from(document.querySelectorAll("[data-message-author-role]"));
@@ -325,13 +561,100 @@ async function extractConversation(sourceUrl: string): Promise<ExtractedConversa
})
.filter((message) => message.text.length > 0);
function normalizeText(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
function parsePayloadMessages(): Array<{ role: "user" | "assistant"; text: string }> {
const script = Array.from(document.scripts).find((candidate) => {
const text = candidate.textContent || "";
return text.includes("serverResponse") && text.includes("linear_conversation");
})?.textContent;
const match = script?.match(/enqueue\((.*)\);?$/s);
if (!match) return [];
try {
const flattened = JSON.parse(JSON.parse(match[1]));
const keyCache = new Map<string, number>();
function keyRef(name: string): number {
if (!keyCache.has(name)) keyCache.set(name, flattened.indexOf(name));
return keyCache.get(name) ?? -1;
}
function propRef(objectRef: unknown, key: string): unknown {
if (typeof objectRef !== "number" || objectRef < 0) return undefined;
const object = flattened[objectRef];
if (!object || typeof object !== "object" || Array.isArray(object)) return undefined;
return (object as Record<string, unknown>)[`_${keyRef(key)}`];
}
function primitive(ref: unknown): unknown {
if (typeof ref !== "number" || ref < 0) return undefined;
return flattened[ref];
}
const linearKey = keyRef("linear_conversation");
const dataObject = flattened.find((value: unknown) => {
return Boolean(value && typeof value === "object" && !Array.isArray(value) && `_${linearKey}` in (value as Record<string, unknown>));
}) as Record<string, unknown> | undefined;
const linearRef = dataObject?.[`_${linearKey}`];
const linearRefs = primitive(linearRef);
if (!Array.isArray(linearRefs)) return [];
function messageText(messageRef: unknown): string {
const contentRef = propRef(messageRef, "content");
const partsRef = propRef(contentRef, "parts");
const parts = primitive(partsRef);
if (!Array.isArray(parts)) return "";
return normalizeText(
parts
.map((partRef) => primitive(partRef))
.filter((part): part is string => typeof part === "string")
.join("\n")
);
}
return linearRefs
.map((itemRef) => {
const messageRef = propRef(itemRef, "message");
const authorRef = propRef(messageRef, "author");
const role = primitive(propRef(authorRef, "role"));
const text = messageText(messageRef);
return { role, text };
})
.filter((message): message is { role: "user" | "assistant"; text: string } => {
if (message.role !== "user" && message.role !== "assistant") return false;
if (!message.text) return false;
if (message.text === "Original custom instructions no longer available") return false;
if (message.text === "The output of this plugin was redacted.") return false;
if (/^\{"only_tools":true\}$/.test(message.text)) return false;
return true;
});
} catch {
return [];
}
}
const payloadMessages = parsePayloadMessages();
if (messages.length > 0 && payloadMessages.length > 0) {
const firstDomText = normalizeText(messages[0].text);
const firstDomIndex = payloadMessages.findIndex((message) => {
const payloadText = normalizeText(message.text);
return payloadText === firstDomText || payloadText.startsWith(firstDomText.slice(0, 120)) || firstDomText.startsWith(payloadText.slice(0, 120));
});
if (firstDomIndex > 0) {
messages.unshift(
...payloadMessages.slice(0, firstDomIndex).map((message, index) => ({
id: `payload-${index + 1}`,
role: message.role,
text: message.text,
html: textToHtml(message.text)
}))
);
}
}
const bodyText = document.body.textContent || "";
if (/verify you are human|captcha|unusual activity/i.test(bodyText)) {
throw new Error("ChatGPT verification or CAPTCHA page was shown.");
}
return { title, messages };
});
}), config.captureTimeoutMs, "Extracting ChatGPT share DOM");
if (!extracted.messages.length) {
throw new Error("Unsupported ChatGPT share page: no conversation messages were found.");
@@ -345,9 +668,10 @@ async function extractConversation(sourceUrl: string): Promise<ExtractedConversa
}
}
async function generateScreenshotVariant(slug: string, variant: ScreenshotVariant): Promise<void> {
async function generateScreenshotVariant(slug: string, variant: ScreenshotVariant): Promise<string[]> {
const browser = await chromium.launch({ headless: true });
try {
const katexFonts = new Set<string>();
const isMobile = variant.device === "mobile";
const context = await browser.newContext({
viewport: isMobile ? { width: 430, height: 932 } : { width: 1360, height: 900 },
@@ -356,8 +680,19 @@ async function generateScreenshotVariant(slug: string, variant: ScreenshotVarian
isMobile
});
const page = await context.newPage();
page.on("request", (request) => {
try {
const url = new URL(request.url());
if (!url.pathname.includes("/assets/katex/")) return;
const filename = path.basename(url.pathname);
if (/\.woff2$/i.test(filename)) katexFonts.add(filename);
} catch {
return;
}
});
const fileUrl = `file://${artifactIndexPath(slug)}?theme=${variant.theme}`;
await page.goto(fileUrl, { waitUntil: "load", timeout: 60_000 });
await page.addStyleTag({ content: screenshotOnlyCss });
const height = await page.evaluate(() => Math.ceil(document.documentElement.scrollHeight));
if (height > config.maxScreenshotHeight) {
throw new Error(`Screenshot height ${height}px exceeds limit ${config.maxScreenshotHeight}px.`);
@@ -369,12 +704,13 @@ async function generateScreenshotVariant(slug: string, variant: ScreenshotVarian
type: "png"
});
await context.close();
return [...katexFonts].sort();
} finally {
await browser.close();
}
}
async function generateScreenshots(slug: string): Promise<{ generated: string[]; failed: string[] }> {
async function generateScreenshots(slug: string): Promise<{ generated: string[]; failed: string[]; katexFonts: string[] }> {
const variants: ScreenshotVariant[] = [
{ device: "desktop", theme: "light" },
{ device: "desktop", theme: "dark" },
@@ -383,16 +719,18 @@ async function generateScreenshots(slug: string): Promise<{ generated: string[];
];
const generated: string[] = [];
const failed: string[] = [];
const katexFonts = new Set<string>();
for (const variant of variants) {
const name = `${variant.device}-${variant.theme}`;
try {
await generateScreenshotVariant(slug, variant);
const usedFonts = await generateScreenshotVariant(slug, variant);
usedFonts.forEach((fontFile) => katexFonts.add(fontFile));
generated.push(name);
} catch (error) {
failed.push(`${name}: ${error instanceof Error ? error.message : String(error)}`);
}
}
return { generated, failed };
return { generated, failed, katexFonts: [...katexFonts].sort() };
}
export async function runCapture(row: CaptureRow): Promise<void> {
@@ -416,8 +754,11 @@ export async function runCapture(row: CaptureRow): Promise<void> {
store.updateStatus(row.id, "rendering");
conversation.chatGptIconSrc = (await downloadAsset(chatGptIconUrl, slug).catch(() => null)) || chatGptIconUrl;
const assetResult = await localizeAssets(conversation, slug);
const preparedKatexFonts = await prepareKatexAssets(slug, conversation);
await writeConversationArtifact(slug, conversation);
const screenshots = await generateScreenshots(slug);
const keptKatexFonts = await finalizeKatexAssets(slug, conversation, screenshots.katexFonts);
if (keptKatexFonts.length > 0) await writeConversationArtifact(slug, conversation);
store.completeCapture(row.id, {
slug,
@@ -425,7 +766,11 @@ export async function runCapture(row: CaptureRow): Promise<void> {
dataJson: JSON.stringify(conversation),
metadataJson: JSON.stringify({
assetFailures: assetResult.failures,
screenshots
screenshots,
katexFonts: {
prepared: preparedKatexFonts.length,
kept: keptKatexFonts
}
})
});
} catch (error) {
+59 -7
View File
@@ -7,6 +7,8 @@ export interface CaptureInsert {
id: string;
sourceUrl: string;
requestedSlug: string | null;
ownerToken: string | null;
retentionDays: number;
}
export class Store {
@@ -42,17 +44,43 @@ export class Store {
CREATE INDEX IF NOT EXISTS idx_captures_status ON captures(status);
CREATE INDEX IF NOT EXISTS idx_captures_created_at ON captures(created_at);
`);
const columns = new Set(
(this.db.prepare("PRAGMA table_info(captures)").all() as Array<{ name: string }>).map((column) => column.name)
);
if (!columns.has("owner_token")) this.db.exec("ALTER TABLE captures ADD COLUMN owner_token TEXT");
if (!columns.has("retention_days")) this.db.exec("ALTER TABLE captures ADD COLUMN retention_days INTEGER NOT NULL DEFAULT 30");
if (!columns.has("expires_at")) this.db.exec("ALTER TABLE captures ADD COLUMN expires_at TEXT");
const missingExpiry = this.db.prepare("SELECT id, created_at, retention_days FROM captures WHERE expires_at IS NULL").all() as Array<{
id: string;
created_at: string;
retention_days: number;
}>;
const setExpiry = this.db.prepare("UPDATE captures SET expires_at = ? WHERE id = ?");
const backfillExpiry = this.db.transaction(() => {
for (const row of missingExpiry) {
const expiresAt = new Date(new Date(row.created_at).getTime() + row.retention_days * 86_400_000).toISOString();
setExpiry.run(expiresAt, row.id);
}
});
backfillExpiry();
this.db.exec(`
CREATE INDEX IF NOT EXISTS idx_captures_owner_created ON captures(owner_token, created_at);
CREATE INDEX IF NOT EXISTS idx_captures_expires_at ON captures(expires_at);
`);
}
createCapture(input: CaptureInsert): CaptureRow {
const now = new Date().toISOString();
const expiresAt = new Date(Date.now() + input.retentionDays * 86_400_000).toISOString();
this.db
.prepare(
`INSERT INTO captures
(id, source_url, provider, requested_slug, status, created_at, updated_at)
VALUES (?, ?, 'chatgpt', ?, 'queued', ?, ?)`
(id, source_url, provider, requested_slug, status, created_at, updated_at, owner_token, retention_days, expires_at)
VALUES (?, ?, 'chatgpt', ?, 'queued', ?, ?, ?, ?, ?)`
)
.run(input.id, input.sourceUrl, input.requestedSlug, now, now);
.run(input.id, input.sourceUrl, input.requestedSlug, now, now, input.ownerToken, input.retentionDays, expiresAt);
return this.getCapture(input.id)!;
}
@@ -65,15 +93,28 @@ export class Store {
}
listCaptures(page: number, pageSize: number): { rows: CaptureRow[]; total: number } {
return this.listCapturesWhere(page, pageSize);
}
listCapturesForOwner(ownerToken: string, page: number, pageSize: number): { rows: CaptureRow[]; total: number } {
return this.listCapturesWhere(page, pageSize, ownerToken);
}
private listCapturesWhere(page: number, pageSize: number, ownerToken?: string): { rows: CaptureRow[]; total: number } {
const limit = Math.min(Math.max(pageSize, 1), 100);
const offset = Math.max(page - 1, 0) * limit;
const rows = this.db
.prepare("SELECT * FROM captures ORDER BY created_at DESC LIMIT ? OFFSET ?")
.all(limit, offset) as CaptureRow[];
const total = (this.db.prepare("SELECT count(*) as count FROM captures").get() as { count: number }).count;
const where = ownerToken === undefined ? "" : " WHERE owner_token = ?";
const params = ownerToken === undefined ? [limit, offset] : [ownerToken, limit, offset];
const rows = this.db.prepare(`SELECT * FROM captures${where} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...params) as CaptureRow[];
const countParams = ownerToken === undefined ? [] : [ownerToken];
const total = (this.db.prepare(`SELECT count(*) as count FROM captures${where}`).get(...countParams) as { count: number }).count;
return { rows, total };
}
expiredCaptures(now = new Date().toISOString()): CaptureRow[] {
return this.db.prepare("SELECT * FROM captures WHERE expires_at <= ?").all(now) as CaptureRow[];
}
queuedCaptures(): CaptureRow[] {
return this.db
.prepare("SELECT * FROM captures WHERE status IN ('queued', 'capturing', 'rendering') ORDER BY created_at ASC")
@@ -90,6 +131,17 @@ export class Store {
.run(status, detail?.errorPublic ?? null, detail?.errorDetail ?? null, new Date().toISOString(), id);
}
retryCapture(id: string): void {
this.db
.prepare(
`UPDATE captures
SET status = 'queued', title = NULL, error_public = NULL, error_detail = NULL,
data_json = NULL, metadata_json = NULL, captured_at = NULL, updated_at = ?
WHERE id = ?`
)
.run(new Date().toISOString(), id);
}
completeCapture(id: string, input: { slug: string; title: string; dataJson: string; metadataJson: string }): void {
const now = new Date().toISOString();
this.db
+85
View File
@@ -0,0 +1,85 @@
import { createRequire } from "node:module";
import path from "node:path";
import fs from "fs-extra";
import { artifactAssetsDir } from "./artifacts.js";
import type { NormalizedConversation } from "./types.js";
const require = createRequire(import.meta.url);
const katexCssPath = require.resolve("katex/dist/katex.min.css");
const katexDistDir = path.dirname(katexCssPath);
const katexFontsDir = path.join(katexDistDir, "fonts");
const fontFacePattern = /@font-face\{[^}]*\}/g;
const woff2Pattern = /url\((?:["']?)fonts\/([^)"']+\.woff2)(?:["']?)\)/;
export function conversationUsesKatex(conversation: NormalizedConversation): boolean {
return conversation.messages.some((message) => /\bkatex(?:-|["'\s>])/.test(message.html));
}
function katexAssetDir(slug: string): string {
return path.join(artifactAssetsDir(slug), "katex");
}
async function readOfficialKatexCss(): Promise<string> {
return await fs.readFile(katexCssPath, "utf8");
}
function rewriteFontFace(block: string): { css: string; fontFile: string | null } {
const fontFile = block.match(woff2Pattern)?.[1] || null;
if (!fontFile) return { css: block, fontFile: null };
return {
css: block.replace(/src:[^;}]+(?=[;}])/, `src:url("assets/katex/${fontFile}") format("woff2")`),
fontFile
};
}
async function buildKatexCss(allowedFonts?: Set<string>): Promise<{ css: string; fonts: string[] }> {
const css = await readOfficialKatexCss();
const fonts = new Set<string>();
const rewritten = css.replace(fontFacePattern, (block) => {
const result = rewriteFontFace(block);
if (!result.fontFile) return block;
if (allowedFonts && !allowedFonts.has(result.fontFile)) return "";
fonts.add(result.fontFile);
return result.css;
});
return { css: rewritten, fonts: [...fonts].sort() };
}
async function copyFonts(slug: string, fontFiles: string[]): Promise<void> {
const destination = katexAssetDir(slug);
await fs.emptyDir(destination);
await Promise.all(
fontFiles.map(async (fontFile) => {
await fs.copyFile(path.join(katexFontsDir, fontFile), path.join(destination, fontFile));
})
);
}
export async function prepareKatexAssets(slug: string, conversation: NormalizedConversation): Promise<string[]> {
if (!conversationUsesKatex(conversation)) {
delete conversation.katexCss;
await fs.remove(katexAssetDir(slug));
return [];
}
const { css, fonts } = await buildKatexCss();
conversation.katexCss = css;
await copyFonts(slug, fonts);
return fonts;
}
export async function finalizeKatexAssets(
slug: string,
conversation: NormalizedConversation,
requestedFonts: Iterable<string>
): Promise<string[]> {
if (!conversation.katexCss) return [];
const available = new Set(await fs.readdir(katexFontsDir));
const used = new Set([...requestedFonts].filter((fontFile) => available.has(fontFile)));
if (used.size === 0) return [];
const { css, fonts } = await buildKatexCss(used);
conversation.katexCss = css;
await copyFonts(slug, fonts);
return fonts;
}
+88 -10
View File
@@ -1,5 +1,6 @@
import path from "node:path";
import fs from "fs-extra";
import * as cheerio from "cheerio";
import type { CaptureRow, NormalizedConversation } from "./types.js";
import { artifactAssetsDir, artifactDir, artifactIndexPath } from "./artifacts.js";
import { config } from "./config.js";
@@ -14,15 +15,34 @@ function escapeHtml(value: string): string {
.replace(/"/g, "&quot;");
}
function prepareMessageHtml(html: string): string {
const $ = cheerio.load(html, {}, false);
$("a").each((_, anchor) => {
const link = $(anchor);
if (link.is("[data-citation]")) return;
link.find("svg").remove();
const href = (link.attr("href") || "").trim();
if (/^https?:\/\//i.test(href) && link.find(".external-link-icon").length === 0) {
link.append('<span class="external-link-icon" aria-hidden="true"></span>');
}
});
return $.html();
}
const icons = {
download: `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v10m0 0 4-4m-4 4-4-4"/><path d="M5 18.5h14"/></svg>`,
image: `<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="4" y="5" width="16" height="14" rx="2"/><path d="m7 16 4-4 3 3 2-2 3 3"/><circle cx="8.5" cy="8.5" r="1.2"/></svg>`,
share: `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M8.5 12.5 15.5 8.5M8.5 11.5 15.5 15.5"/><circle cx="6.5" cy="12" r="2.5"/><circle cx="17.5" cy="7.5" r="2.5"/><circle cx="17.5" cy="16.5" r="2.5"/></svg>`,
chevron: `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m8 10 4 4 4-4"/></svg>`
chevron: `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m8 10 4 4 4-4"/></svg>`,
sun: `<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 3v2m0 14v2M3 12h2m14 0h2M5.6 5.6 7 7m10 10 1.4 1.4M18.4 5.6 17 7M7 17l-1.4 1.4"/></svg>`,
moon: `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M20 14.6A7.6 7.6 0 0 1 9.4 4 8 8 0 1 0 20 14.6Z"/></svg>`,
arrowUp: `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 14 6-6 6 6"/><path d="M12 8v12"/></svg>`,
arrowDown: `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 10 6 6 6-6"/><path d="M12 4v12"/></svg>`
};
function css(): string {
return `
function css(extraCss = ""): string {
return `${extraCss}
:root {
color-scheme: light dark;
--bg: #ffffff;
@@ -57,12 +77,19 @@ html[data-theme="dark"] {
--bg: #212121; --panel: #212121; --text: #ececec; --muted: #a8a8a8; --border: #3f3f46; --soft: #2f2f2f; --code: #e5e7eb; --code-bg: #171717; --user-bubble: #303030;
}
* { box-sizing: border-box; }
body, .topbar, .message.user .content, .content pre, .content :not(pre) > code, .code-block, .code-block .code-header, .content th, .content td, .content blockquote, .content a, .downloads, .icon-button, .shot-menu, .shot-menu button, .toast {
transition: background-color .22s ease, border-color .22s ease, color .22s ease, box-shadow .22s ease;
}
body { margin: 0; background: var(--bg); color: var(--text); font-size: 16px; line-height: 1.65; }
a { color: inherit; }
.page { min-height: 100vh; }
.topbar { position: sticky; top: 0; z-index: 2; border-bottom: 1px solid var(--border); background: color-mix(in srgb, var(--bg) 92%, transparent); backdrop-filter: blur(12px); }
.topbar-inner { max-width: 880px; margin: 0 auto; padding: 14px 20px; display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.topbar-actions { display: inline-flex; align-items: center; gap: 8px; min-width: 0; }
.snapshot-label { font-size: 13px; color: var(--muted); white-space: nowrap; }
.theme-toggle .moon-icon { display: none; }
html[data-theme="dark"] .theme-toggle .sun-icon { display: none; }
html[data-theme="dark"] .theme-toggle .moon-icon { display: block; }
.title { max-width: 880px; margin: 0 auto; padding: 34px 20px 18px; }
h1 { margin: 0; font-size: clamp(28px, 5vw, 44px); line-height: 1.12; letter-spacing: 0; }
.conversation { max-width: 880px; margin: 0 auto; padding: 4px 20px 36px; }
@@ -99,8 +126,17 @@ h1 { margin: 0; font-size: clamp(28px, 5vw, 44px); line-height: 1.12; letter-spa
.content th, .content td { border: 1px solid var(--border); padding: 8px 10px; text-align: left; vertical-align: top; }
.content blockquote { border-left: 3px solid var(--border); margin: 1em 0; padding-left: 14px; color: var(--muted); }
.content img { max-width: 100%; height: auto; border-radius: 8px; }
.content a[data-citation] { color: var(--muted); font-size: 0.92em; white-space: nowrap; text-decoration-thickness: 1px; text-underline-offset: 2px; }
.content a[data-citation] img { width: 14px; height: 14px; max-width: 14px; max-height: 14px; border-radius: 3px; object-fit: cover; vertical-align: -2px; margin: 0 3px 0 4px; }
.content a:not([data-citation]) { color: inherit; text-decoration: underline; text-decoration-thickness: 1px; text-underline-offset: 3px; }
.content a:not([data-citation]):hover { color: color-mix(in srgb, var(--text) 78%, var(--accent) 22%); }
.external-link-icon { display: inline-block; width: 0.82em; height: 0.82em; margin-left: 0.18em; vertical-align: -0.05em; background: currentColor; opacity: 0.72; -webkit-mask: url("data:image/svg+xml,%3Csvg%20viewBox%3D%270%200%2024%2024%27%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%3E%3Cpath%20fill%3D%27black%27%20d%3D%27M14%203h7v7h-2V6.41l-9.29%209.3-1.42-1.42%209.3-9.29H14V3ZM5%205h6v2H7v10h10v-4h2v6H5V5Z%27/%3E%3C/svg%3E") center / contain no-repeat; mask: url("data:image/svg+xml,%3Csvg%20viewBox%3D%270%200%2024%2024%27%20xmlns%3D%27http%3A//www.w3.org/2000/svg%27%3E%3Cpath%20fill%3D%27black%27%20d%3D%27M14%203h7v7h-2V6.41l-9.29%209.3-1.42-1.42%209.3-9.29H14V3ZM5%205h6v2H7v10h10v-4h2v6H5V5Z%27/%3E%3C/svg%3E") center / contain no-repeat; }
.content math { color: inherit; font-family: math, "STIX Two Math", "Cambria Math", "Noto Sans Math", serif; font-size: 1.02em; }
.content > math { display: block; max-width: 100%; margin: 0.95em 0; overflow-x: auto; overflow-y: hidden; }
.content p math, .content li math { vertical-align: -0.08em; }
.content .katex-display { max-width: 100%; padding: 14px 16px; overflow-x: auto; overflow-y: visible; border-radius: 8px; background: var(--soft); }
.content a[data-citation] { display: inline-flex; align-items: center; gap: 5px; max-width: min(100%, 260px); min-height: 24px; margin: 0 2px; padding: 2px 8px 2px 5px; border: 1px solid var(--border); border-radius: 999px; background: var(--soft); color: var(--text); font-size: 0.88em; line-height: 1.25; white-space: nowrap; text-decoration: none; vertical-align: -5px; }
.content a[data-citation]:hover { background: color-mix(in srgb, var(--soft) 82%, var(--text) 18%); }
.content a[data-citation] img { width: 16px; height: 16px; max-width: 16px; max-height: 16px; border-radius: 50%; object-fit: cover; flex: 0 0 auto; }
.content a[data-citation] span { overflow: hidden; text-overflow: ellipsis; }
.downloads { position: relative; z-index: 3; border-top: 1px solid var(--border); background: var(--soft); }
.downloads-inner { max-width: 880px; margin: 0 auto; padding: 14px 20px; display: flex; flex-wrap: nowrap; gap: 8px; align-items: center; overflow: visible; }
.icon-button { width: 36px; height: 36px; border: 1px solid var(--border); border-radius: 8px; background: var(--panel); color: var(--text); padding: 0; display: inline-grid; place-items: center; flex: 0 0 auto; cursor: pointer; text-decoration: none; }
@@ -118,6 +154,8 @@ h1 { margin: 0; font-size: clamp(28px, 5vw, 44px); line-height: 1.12; letter-spa
.toast-region { position: fixed; left: 50%; bottom: 22px; z-index: 40; display: grid; justify-items: center; pointer-events: none; transform: translateX(-50%); }
.toast { max-width: min(calc(100vw - 32px), 320px); border: 1px solid var(--border); border-radius: 8px; background: var(--panel); color: var(--text); padding: 9px 12px; font-size: 13px; line-height: 1.35; box-shadow: 0 12px 30px rgba(0,0,0,.14); opacity: 0; transform: translateY(8px); transition: opacity .16s ease, transform .16s ease; }
.toast[data-visible="true"] { opacity: 1; transform: translateY(0); }
.jump-controls { position: fixed; right: 18px; bottom: 18px; z-index: 30; display: grid; gap: 8px; }
.jump-controls .icon-button { box-shadow: 0 8px 24px rgba(0,0,0,.12); }
.source { max-width: 880px; margin: 0 auto; padding: 18px 20px 34px; color: var(--muted); font-size: 12px; }
.source a { color: var(--muted); }
.failure { max-width: 720px; margin: 0 auto; padding: 80px 20px; }
@@ -125,6 +163,7 @@ h1 { margin: 0; font-size: clamp(28px, 5vw, 44px); line-height: 1.12; letter-spa
@media (max-width: 640px) {
body { font-size: 15px; }
.topbar-inner { padding: 12px 16px; }
.topbar-actions { gap: 6px; }
.title { padding: 26px 16px 12px; }
.conversation { padding: 0 16px 28px; }
.message { padding: 16px 0; }
@@ -134,20 +173,39 @@ h1 { margin: 0; font-size: clamp(28px, 5vw, 44px); line-height: 1.12; letter-spa
.avatar, .assistant-icon { width: 26px; height: 26px; }
.content ul, .content ol { padding-left: 1.25em; }
.downloads-inner { padding: 12px 16px; }
.jump-controls { right: 12px; bottom: 12px; }
}`;
}
function initialThemeScript(): string {
return `!function(){var p=new URLSearchParams(location.search),t=p.get("theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";document.documentElement.dataset.theme=t}();`;
}
function pageScript(slug: string): string {
return `
(function () {
function currentVariant() {
var device = matchMedia("(max-width: 640px)").matches ? "mobile" : "desktop";
var theme = matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
var theme = document.documentElement.dataset.theme || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
return device + "-" + theme;
}
function downloadShot(variant) {
location.href = "screenshots/" + variant + ".png";
}
var systemTheme = matchMedia("(prefers-color-scheme: dark)");
var themeToggle = document.querySelector("[data-theme-toggle]");
var manualTheme = false;
function preferredTheme() {
return systemTheme.matches ? "dark" : "light";
}
function applyTheme(theme, manual) {
document.documentElement.dataset.theme = theme;
if (manual) manualTheme = true;
if (themeToggle) {
themeToggle.setAttribute("aria-label", theme === "dark" ? "Switch to light theme" : "Switch to dark theme");
themeToggle.setAttribute("title", theme === "dark" ? "Switch to light theme" : "Switch to dark theme");
}
}
var toastTimer;
function showToast(message) {
var region = document.querySelector("[data-toast-region]");
@@ -176,11 +234,26 @@ function pageScript(slug: string): string {
}
var params = new URLSearchParams(location.search);
var theme = params.get("theme");
if (theme === "light" || theme === "dark") document.documentElement.dataset.theme = theme;
manualTheme = theme === "light" || theme === "dark";
applyTheme(theme === "light" || theme === "dark" ? theme : preferredTheme(), theme === "light" || theme === "dark");
systemTheme.addEventListener("change", function () {
if (!manualTheme) applyTheme(preferredTheme(), false);
});
if (themeToggle) themeToggle.addEventListener("click", function () {
applyTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark", true);
});
var copy = document.querySelector("[data-copy]");
if (copy) copy.addEventListener("click", async function () {
await copyText(location.href.replace(/[?#].*$/, ""), "Link copied");
});
var jumpTop = document.querySelector("[data-jump-top]");
if (jumpTop) jumpTop.addEventListener("click", function () {
scrollTo({ top: 0, behavior: "smooth" });
});
var jumpBottom = document.querySelector("[data-jump-bottom]");
if (jumpBottom) jumpBottom.addEventListener("click", function () {
scrollTo({ top: document.documentElement.scrollHeight, behavior: "smooth" });
});
document.querySelectorAll("[data-copy-code]").forEach(function (button) {
button.addEventListener("click", async function () {
var block = button.closest(".code-block");
@@ -217,7 +290,7 @@ export function renderConversationPage(slug: string, conversation: NormalizedCon
${messageAvatar(message.role, conversation.chatGptIconSrc)}
<div class="content-wrap">
<div class="role">${message.role === "assistant" ? "Assistant" : message.role === "user" ? "You" : "Message"}</div>
<div class="content">${message.html}</div>
<div class="content">${prepareMessageHtml(message.html)}</div>
</div>
</article>`)
.join("\n");
@@ -229,11 +302,12 @@ export function renderConversationPage(slug: string, conversation: NormalizedCon
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>${title}</title>
<style>${css()}</style>
<script>${initialThemeScript()}</script>
<style>${css(conversation.katexCss || "")}</style>
</head>
<body>
<div class="page">
<header class="topbar"><div class="topbar-inner"><strong>AI Share</strong><span class="snapshot-label">ChatGPT snapshot</span></div></header>
<header class="topbar"><div class="topbar-inner"><strong>AI Share</strong><div class="topbar-actions"><span class="snapshot-label">ChatGPT snapshot</span><button class="icon-button theme-toggle" type="button" data-theme-toggle aria-label="Switch theme" title="Switch theme"><span class="sun-icon">${icons.sun}</span><span class="moon-icon">${icons.moon}</span></button></div></div></header>
<main>
<section class="title"><h1>${title}</h1></section>
<section class="conversation">${messages}</section>
@@ -260,6 +334,10 @@ export function renderConversationPage(slug: string, conversation: NormalizedCon
Captured from ChatGPT on ${escapeHtml(new Date(conversation.capturedAt).toLocaleString())}.
Source: <a href="${escapeHtml(conversation.sourceUrl)}" rel="nofollow noreferrer">${escapeHtml(conversation.sourceUrl)}</a>
</footer>
<div class="jump-controls" aria-label="Page navigation">
<button class="icon-button" type="button" data-jump-top aria-label="Jump to top" title="Jump to top">${icons.arrowUp}</button>
<button class="icon-button" type="button" data-jump-bottom aria-label="Jump to bottom" title="Jump to bottom">${icons.arrowDown}</button>
</div>
<div class="toast-region" data-toast-region aria-live="polite" aria-atomic="true"></div>
</div>
<script>${pageScript(slug)}</script>
+94 -20
View File
@@ -1,4 +1,5 @@
import path from "node:path";
import crypto from "node:crypto";
import express, { type NextFunction, type Request, type Response } from "express";
import fs from "fs-extra";
import { config } from "./config.js";
@@ -19,6 +20,8 @@ import {
} from "./artifacts.js";
const app = express();
const retentionOptions = new Set([3, 7, 10, 30]);
const ownerCookieName = "aishare_owner";
app.disable("x-powered-by");
app.enable("strict routing");
@@ -48,6 +51,45 @@ function requireAdmin(req: Request, res: Response, next: NextFunction): void {
res.status(401).json({ error: "Admin token required." });
}
function isAdminRequest(req: Request): boolean {
const header = req.header("authorization") || "";
const token = header.startsWith("Bearer ") ? header.slice("Bearer ".length) : req.header("x-admin-token");
return Boolean(config.adminToken && token && token === config.adminToken);
}
function cookieValue(req: Request, name: string): string | undefined {
const cookie = req.header("cookie") || "";
for (const part of cookie.split(";")) {
const [key, ...value] = part.trim().split("=");
if (key === name) return decodeURIComponent(value.join("="));
}
return undefined;
}
app.use((req, res, next) => {
let ownerToken = cookieValue(req, ownerCookieName);
if (!ownerToken || !/^[A-Za-z0-9_-]{32,128}$/.test(ownerToken)) {
ownerToken = crypto.randomBytes(32).toString("base64url");
const cookiePath = config.basePath || "/";
const secure = req.secure || req.header("x-forwarded-proto") === "https";
res.cookie(ownerCookieName, ownerToken, {
httpOnly: true,
sameSite: "lax",
secure,
path: cookiePath,
maxAge: 365 * 24 * 60 * 60 * 1000
});
}
(req as Request & { ownerToken?: string }).ownerToken = ownerToken;
res.locals.ownerToken = ownerToken;
next();
});
function canManageCapture(req: Request, row: NonNullable<ReturnType<typeof store.getCapture>>): boolean {
const ownerToken = (req as Request & { ownerToken?: string }).ownerToken;
return isAdminRequest(req) || Boolean(row.owner_token && row.owner_token === ownerToken);
}
function publicCapture(row: ReturnType<typeof store.getCapture>) {
if (!row) return null;
return {
@@ -61,6 +103,8 @@ function publicCapture(row: ReturnType<typeof store.getCapture>) {
createdAt: row.created_at,
updatedAt: row.updated_at,
capturedAt: row.captured_at,
retentionDays: row.retention_days,
expiresAt: row.expires_at,
publicUrl: row.slug ? publicPath(row.slug) : null
};
}
@@ -80,18 +124,35 @@ app.use(route("/assets"), express.static(path.resolve("dist-client/assets"), { i
app.use(route("/admin-assets"), express.static(path.resolve("dist-client"), { immutable: true, maxAge: "1y" }));
app.get(route("/admin"), (_req, res) => {
res.sendFile(path.resolve("dist-client/index.html"));
res.redirect(302, route() || "/");
});
function sendApp(_req: Request, res: Response): void {
res.sendFile(path.resolve("dist-client/index.html"));
}
app.get(route("/api/health"), (_req, res) => {
res.json({ ok: true });
});
app.post(route("/api/captures"), requireAdmin, (req, res) => {
app.get(route("/api/session"), (req, res) => {
res.json({ isAdmin: isAdminRequest(req) });
});
app.post(route("/api/captures"), (req, res) => {
try {
const sourceUrl = validateChatGptShareUrl(String(req.body?.sourceUrl || ""));
const requestedSlug = req.body?.slug ? slugify(String(req.body.slug)) : null;
const row = store.createCapture({ id: newCaptureId(), sourceUrl, requestedSlug });
const admin = isAdminRequest(req);
const requestedSlug = admin && req.body?.slug ? slugify(String(req.body.slug)) : null;
const retentionDays = Number(req.body?.retentionDays ?? 3);
if (!retentionOptions.has(retentionDays)) throw new Error("Retention must be 3, 7, 10, or 30 days.");
const row = store.createCapture({
id: newCaptureId(),
sourceUrl,
requestedSlug,
ownerToken: admin ? null : String(res.locals.ownerToken),
retentionDays
});
captureQueue.enqueue(row.id);
res.status(202).json({ capture: publicCapture(row) });
} catch (error) {
@@ -99,30 +160,32 @@ app.post(route("/api/captures"), requireAdmin, (req, res) => {
}
});
app.get(route("/api/captures"), requireAdmin, (req, res) => {
app.get(route("/api/captures"), (req, res) => {
const page = Number.parseInt(String(req.query.page || "1"), 10);
const pageSize = Number.parseInt(String(req.query.pageSize || "20"), 10);
const result = store.listCaptures(page, pageSize);
const admin = isAdminRequest(req);
const result = admin ? store.listCaptures(page, pageSize) : store.listCapturesForOwner(String(res.locals.ownerToken), page, pageSize);
res.json({
page,
pageSize,
total: result.total,
isAdmin: admin,
captures: result.rows.map(publicCapture)
});
});
app.get(route("/api/captures/:id"), requireAdmin, (req, res) => {
app.get(route("/api/captures/:id"), (req, res) => {
const row = store.getCapture(req.params.id);
if (!row) {
if (!row || !canManageCapture(req, row)) {
res.status(404).json({ error: "Capture not found." });
return;
}
res.json({ capture: publicCapture(row), errorDetail: row.error_detail, metadata: row.metadata_json ? JSON.parse(row.metadata_json) : null });
});
app.post(route("/api/captures/:id/retry"), requireAdmin, (req, res) => {
app.post(route("/api/captures/:id/retry"), (req, res) => {
const row = store.getCapture(req.params.id);
if (!row) {
if (!row || !canManageCapture(req, row)) {
res.status(404).json({ error: "Capture not found." });
return;
}
@@ -130,17 +193,18 @@ app.post(route("/api/captures/:id/retry"), requireAdmin, (req, res) => {
res.status(409).json({ error: "Successful captures are immutable. Create a new capture instead." });
return;
}
store.updateStatus(row.id, "queued");
store.retryCapture(row.id);
captureQueue.enqueue(row.id);
res.json({ capture: publicCapture(store.getCapture(row.id)) });
});
app.delete(route("/api/captures/:id"), requireAdmin, async (req, res) => {
const row = store.deleteCapture(req.params.id);
if (!row) {
app.delete(route("/api/captures/:id"), async (req, res) => {
const existing = store.getCapture(req.params.id);
if (!existing || !canManageCapture(req, existing)) {
res.status(404).json({ error: "Capture not found." });
return;
}
const row = store.deleteCapture(req.params.id)!;
await deleteArtifactsFor(row);
res.json({ ok: true });
});
@@ -232,14 +296,13 @@ app.get(route("/:slug"), (req, res) => {
res.redirect(308, `${req.originalUrl.replace(/[?#].*$/, "")}/`);
});
app.get(route(), (_req, res) => {
res.redirect(301, route("/admin"));
});
if (config.basePath) {
app.get(route("/"), (_req, res) => {
res.redirect(301, route("/admin"));
app.get(route(), (_req, res) => {
res.redirect(308, route("/"));
});
app.get(route("/"), sendApp);
} else {
app.get("/", sendApp);
}
app.use((error: unknown, _req: Request, res: Response, _next: NextFunction) => {
@@ -250,7 +313,18 @@ app.use((error: unknown, _req: Request, res: Response, _next: NextFunction) => {
await fs.ensureDir(config.htmlDir);
await fs.ensureDir(config.screenshotDir);
await fs.ensureDir(config.cacheDir);
async function deleteExpiredCaptures(): Promise<void> {
for (const row of store.expiredCaptures()) {
const deleted = store.deleteCapture(row.id);
if (deleted) await deleteArtifactsFor(deleted);
}
}
await deleteExpiredCaptures();
captureQueue.restorePending();
setInterval(() => {
void deleteExpiredCaptures().catch((error) => console.error("Failed to delete expired captures", error));
}, 60 * 60 * 1000).unref();
app.listen(config.port, "0.0.0.0", () => {
console.log(`aishare listening on 0.0.0.0:${config.port}`);
+5 -4
View File
@@ -5,12 +5,13 @@ export function slugify(input: string, fallback = "chatgpt-share"): string {
.normalize("NFKD")
.replace(STOP_CHARS, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/[^\p{L}\p{N}]+/gu, "-")
.replace(/^-+|-+$/g, "")
.replace(/-{2,}/g, "-")
.slice(0, 80);
.replace(/-{2,}/g, "-");
return base || fallback;
const truncated = Array.from(base).slice(0, 80).join("").replace(/-+$/g, "");
return truncated || fallback;
}
export function displayTitleFromSlug(slug: string): string {
+4
View File
@@ -15,6 +15,9 @@ export interface CaptureRow {
created_at: string;
updated_at: string;
captured_at: string | null;
owner_token: string | null;
retention_days: number;
expires_at: string;
}
export interface NormalizedConversation {
@@ -23,6 +26,7 @@ export interface NormalizedConversation {
sourceUrl: string;
capturedAt: string;
chatGptIconSrc?: string;
katexCss?: string;
messages: NormalizedMessage[];
}
+9 -2
View File
@@ -1,3 +1,10 @@
const legacySharePath = /^\/share\/[^/]+\/?$/;
const postSharePath = /^\/s\/t_[A-Za-z0-9_-]+\/?$/;
export function isChatGptSharePath(pathname: string): boolean {
return legacySharePath.test(pathname) || postSharePath.test(pathname);
}
export function validateChatGptShareUrl(raw: string): string {
let url: URL;
try {
@@ -12,8 +19,8 @@ export function validateChatGptShareUrl(raw: string): string {
const host = url.hostname.toLowerCase();
const allowedHost = host === "chatgpt.com" || host === "chat.openai.com";
if (!allowedHost || !url.pathname.startsWith("/share/")) {
throw new Error("Only public ChatGPT share URLs under /share/ are accepted.");
if (!allowedHost || !isChatGptSharePath(url.pathname)) {
throw new Error("Only public ChatGPT share URLs under /share/ or /s/t_ are accepted.");
}
url.hash = "";
+23
View File
@@ -0,0 +1,23 @@
import assert from "node:assert/strict";
import test from "node:test";
import { slugify } from "../dist/slug.js";
test("preserves Unicode letters and numbers", () => {
assert.equal(slugify("多喝水减肥效果"), "多喝水减肥效果");
assert.equal(slugify("减肥 Plan 2026"), "减肥-plan-2026");
});
test("normalizes punctuation and Latin accents", () => {
assert.equal(slugify(" Café — healthy choices! "), "cafe-healthy-choices");
});
test("uses the fallback when no letters or numbers remain", () => {
assert.equal(slugify("🎉 !!!"), "chatgpt-share");
assert.equal(slugify("🎉", "capture"), "capture");
});
test("limits slugs to 80 Unicode code points without a trailing separator", () => {
assert.equal(slugify(`${"界".repeat(79)} hello`), "界".repeat(79));
assert.equal(Array.from(slugify("界".repeat(100))).length, 80);
});
+32
View File
@@ -0,0 +1,32 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isChatGptSharePath, validateChatGptShareUrl } from "../dist/url.js";
test("accepts current ChatGPT post share URLs", () => {
const source = "https://chatgpt.com/s/t_6a5f58aa36d08191b4d794e9aac88146";
assert.equal(validateChatGptShareUrl(source), source);
assert.equal(isChatGptSharePath("/s/t_6a5f58aa36d08191b4d794e9aac88146"), true);
});
test("keeps accepting legacy ChatGPT share URLs", () => {
assert.equal(
validateChatGptShareUrl("https://chatgpt.com/share/12345678-abcd-4321-abcd-1234567890ab"),
"https://chatgpt.com/share/12345678-abcd-4321-abcd-1234567890ab"
);
assert.equal(
validateChatGptShareUrl("https://chat.openai.com/share/12345678-abcd-4321-abcd-1234567890ab"),
"https://chat.openai.com/share/12345678-abcd-4321-abcd-1234567890ab"
);
});
test("rejects non-share and deceptive ChatGPT paths", () => {
for (const source of [
"https://chatgpt.com/s/example",
"https://chatgpt.com/sharex/example",
"https://chatgpt.com/share/example/extra",
"https://example.com/s/t_6a5f58aa36d08191b4d794e9aac88146"
]) {
assert.throws(() => validateChatGptShareUrl(source), /Only public ChatGPT share URLs/);
}
});