feat(admin): publish on every save, and say when the change is actually live (#137)
Saving or deleting in the admin now starts the publish workflow by itself, and the admin
follows the change all the way to production instead of stopping at "merged".
- Auto-publish: content saves/deletes and album saves/deletes dispatch content-bump.yml
after their commit (lib/admin/autopublish). The workflow's concurrency group already
coalesces bursts (one run going, one waiting, the waiting one reads the newest main). A
failed dispatch keeps the save and is reported ("publish": "failed"); "Xuất bản" stays
as the manual retry. Audit action publish.auto.
- Live status: the build records the content commit its src/content points at
(__CONTENT_COMMIT__, from the gitlink in HEAD); /api/health and the admin report it as
version.content. A pure publishPhase() turns content head, main's pointer, the running
build, the bump PR and the last run into live / pending / building / review / deploying /
failed, shown by the PublishBar and the dashboard (which now reads it live too).
- Fixes found while tracing the flow:
- validation now matches the content schema, so a save can't queue a red build:
chapter is a positive integer, cover and coverMedia can't both be set, album is a slug
and must already have photos;
- the tags inputs update on input, so Ctrl/⌘+S no longer saves the previous tags;
- commits in the public content repo say "via admin" without the admin's email (the
private audit log keeps who did what);
- deleting an image also checks the content the live site was built from, not only
main;
- the cover gets an alt field in the editor, and the picker takes alt text for uploads;
- one-shot stories (stories/<slug>.md) can be opened and created.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0c56acd806
commit
15559ecc90
26 files changed
+647
-118
No files matched your search
+22
-1
@@ -5,6 +5,7 @@ import svelte from "@astrojs/svelte";
|
||||
import mdx from "@astrojs/mdx";
|
||||
import sitemap from "@astrojs/sitemap";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { rename, rmdir } from "node:fs/promises";
|
||||
import { DEFAULT_LOCALE, LOCALES } from "./src/i18n/routing.ts";
|
||||
@@ -71,6 +72,23 @@ const CF_BEACON_DEFAULT =
|
||||
// "what is live?" maps straight to a commit.
|
||||
const BUILD_COMMIT = process.env.WORKERS_CI_COMMIT_SHA ?? process.env.GITHUB_SHA ?? null;
|
||||
|
||||
// The poli0981/content commit this build's src/content points at: the gitlink recorded in
|
||||
// HEAD, so it is right even when the submodule checkout itself is missing or dirty. The admin
|
||||
// compares it with the content repo's head to tell "merged" from "live"; /api/health reports
|
||||
// it next to the site commit. null when git or the gitlink isn't there.
|
||||
function contentCommit() {
|
||||
try {
|
||||
const sha = execFileSync("git", ["rev-parse", "HEAD:src/content"], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
}).trim();
|
||||
return /^[0-9a-f]{40}$/.test(sha) ? sha : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const CONTENT_COMMIT = contentCommit();
|
||||
|
||||
// https://astro.build/config
|
||||
export default defineConfig({
|
||||
site: "https://poli0981.dev",
|
||||
@@ -166,7 +184,10 @@ export default defineConfig({
|
||||
// Tailwind v4 is wired through the Vite plugin (NOT the legacy @astrojs/tailwind).
|
||||
vite: {
|
||||
plugins: [tailwindcss()],
|
||||
define: { __BUILD_COMMIT__: JSON.stringify(BUILD_COMMIT) },
|
||||
define: {
|
||||
__BUILD_COMMIT__: JSON.stringify(BUILD_COMMIT),
|
||||
__CONTENT_COMMIT__: JSON.stringify(CONTENT_COMMIT),
|
||||
},
|
||||
},
|
||||
|
||||
// Self-hosted fonts via the built-in Fonts API. Subsets include `vietnamese`.
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"gallery.save": "Lưu album",
|
||||
"gallery.delete": "Xoá album",
|
||||
publish: "Xuất bản",
|
||||
"publish.auto": "Tự xuất bản",
|
||||
"denylist.add": "Chặn IP",
|
||||
"denylist.remove": "Bỏ chặn IP",
|
||||
};
|
||||
|
||||
@@ -71,7 +71,8 @@
|
||||
function create() {
|
||||
if (!newPath || taken) return;
|
||||
const params = new URLSearchParams({ new: collection, slug: slug.trim(), lang: newLang });
|
||||
if (collection === "stories") params.set("series", series.trim());
|
||||
// No series = a one-shot story (stories/<slug>.md).
|
||||
if (collection === "stories" && series.trim()) params.set("series", series.trim());
|
||||
location.href = `/admin/edit/?${params}`;
|
||||
}
|
||||
|
||||
@@ -86,7 +87,7 @@
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<h1>Nội dung</h1>
|
||||
<p>Lưu là commit vào repo nội dung; bấm “Xuất bản” để đưa lên site.</p>
|
||||
<p>Lưu hoặc xoá là commit vào repo nội dung rồi tự xuất bản lên site (thường 10–15 phút).</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -108,7 +109,10 @@
|
||||
</select>
|
||||
</label>
|
||||
{#if collection === "stories"}
|
||||
<label>Bộ truyện (slug) <input bind:value={series} placeholder="dem-khong-tieng" /></label>
|
||||
<label>
|
||||
Bộ truyện (slug, để trống nếu truyện một chương)
|
||||
<input bind:value={series} placeholder="dem-khong-tieng" />
|
||||
</label>
|
||||
{/if}
|
||||
<label>
|
||||
Slug
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { onMount } from "svelte";
|
||||
import { api, describeError } from "./api";
|
||||
import { ago, dateTime, shortSha } from "./format";
|
||||
import { PHASE_TEXT } from "@/lib/admin/publish-phase";
|
||||
|
||||
/**
|
||||
* @typedef {{ id: string; label: string; total: number; drafts: number; vi: number; en: number }} CollectionCount
|
||||
@@ -11,7 +12,7 @@
|
||||
* widgets: { yt: string; steam: string; gh: string; lastRun: string } | null;
|
||||
* config: import("@/lib/admin/status").ConfigStatus;
|
||||
* }} Overview
|
||||
* @typedef {{ contentHead: string; published: string; pr: { number: number; url: string; checks: string | null } | null; run: { status: string; conclusion: string | null; url: string } | null }} Publish
|
||||
* @typedef {{ contentHead: string; published: string; live: string | null; phase: import("@/lib/admin/publish-phase").PublishPhase; pr: { number: number; url: string; checks: string | null } | null; run: { status: string; conclusion: string | null; url: string } | null }} Publish
|
||||
*/
|
||||
|
||||
/** @type {Overview | null} */
|
||||
@@ -125,22 +126,26 @@
|
||||
<section class="card">
|
||||
<h2>Xuất bản</h2>
|
||||
{#if publish}
|
||||
{#if publish.contentHead === publish.published}
|
||||
<p><span class="pill" data-tone="ok">Đã đồng bộ</span></p>
|
||||
<p>
|
||||
<span class="pill" data-tone={PHASE_TEXT[publish.phase].tone}>
|
||||
{PHASE_TEXT[publish.phase].label}
|
||||
</span>
|
||||
</p>
|
||||
<p class="muted small">
|
||||
Repo nội dung <code>{shortSha(publish.contentHead)}</code> · đã merge
|
||||
<code>{shortSha(publish.published)}</code>
|
||||
{#if publish.live}· đang chạy <code>{shortSha(publish.live)}</code>{/if}
|
||||
</p>
|
||||
{#if publish.phase === "deploying"}
|
||||
<p class="muted small">
|
||||
Site đang dùng nội dung <code>{shortSha(publish.published)}</code>.
|
||||
</p>
|
||||
{:else}
|
||||
<p><span class="pill" data-tone="warn">Có thay đổi chưa xuất bản</span></p>
|
||||
<p class="muted small">
|
||||
Repo <code>{shortSha(publish.contentHead)}</code> · site
|
||||
<code>{shortSha(publish.published)}</code>
|
||||
Thường mất 1–3 phút sau khi merge. Lâu hơn: kiểm tra Workers Builds trên Cloudflare.
|
||||
</p>
|
||||
{/if}
|
||||
{#if publish.run?.conclusion === "failure"}
|
||||
{#if publish.phase === "failed" && publish.run}
|
||||
<p class="small">
|
||||
<span class="pill" data-tone="err">Lần chạy gần nhất lỗi</span>
|
||||
<a href={publish.run.url} target="_blank" rel="noopener noreferrer">Xem log ↗</a>
|
||||
<a href={publish.pr?.url ?? publish.run.url} target="_blank" rel="noopener noreferrer">
|
||||
Xem lỗi ↗
|
||||
</a>
|
||||
</p>
|
||||
{/if}
|
||||
{:else}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { confirmAction, toast } from "./ui";
|
||||
import { dateTime } from "./format";
|
||||
import { collectionOf, newEntryPath, validateFrontmatter } from "@/lib/admin/collections";
|
||||
import { afterSaveMessage } from "@/lib/admin/publish-phase";
|
||||
import { mediaFallbackSrc, mediaPictureHtml } from "@/lib/media";
|
||||
|
||||
/** @type {{ path?: string | null; create?: { collection: string; slug: string; lang: string; series?: string } | null }} */
|
||||
@@ -48,10 +49,13 @@
|
||||
const field = spec?.fields.find((f) => f.key === e.field);
|
||||
const message = {
|
||||
required: "Bắt buộc.",
|
||||
type: "Sai kiểu dữ liệu.",
|
||||
type: field?.integer ? "Cần một số nguyên." : "Sai kiểu dữ liệu.",
|
||||
option: "Chọn một giá trị trong danh sách.",
|
||||
max: `Tối đa ${field?.max ?? ""} ký tự.`,
|
||||
format: field?.type === "url" ? "Cần một URL http(s)." : "Sai định dạng.",
|
||||
min: `Nhỏ nhất là ${field?.min ?? ""}.`,
|
||||
conflict: "Bài đã có ảnh bìa local (cover trong file) — chỉ được dùng một trong hai.",
|
||||
missing: "Album này chưa có ảnh — tạo album ở trang Gallery trước.",
|
||||
}[e.code];
|
||||
return [e.field, message];
|
||||
}),
|
||||
@@ -200,7 +204,9 @@
|
||||
sha = result.sha;
|
||||
dirty = false;
|
||||
clearDraft();
|
||||
toast("Đã lưu vào repo nội dung — bấm “Xuất bản” để đưa lên site.");
|
||||
const message = afterSaveMessage(result.publish, "Đã lưu");
|
||||
toast(message.text, message.kind);
|
||||
if (message.queued) dispatchEvent(new Event("admin:published"));
|
||||
if (isNew) {
|
||||
isNew = false;
|
||||
history.replaceState(
|
||||
@@ -337,9 +343,29 @@
|
||||
Bỏ
|
||||
</button>
|
||||
</div>
|
||||
<!-- The alt travels with this post: picking copies the library's text once,
|
||||
and editing it here changes only this cover, not the library. -->
|
||||
<label>
|
||||
<span class="label">Mô tả ảnh bìa (alt)</span>
|
||||
<input
|
||||
maxlength="300"
|
||||
value={data[field.key].alt ?? ""}
|
||||
oninput={(event) => {
|
||||
const alt = event.currentTarget.value.trim();
|
||||
const next = { ...data[field.key] };
|
||||
if (alt) next.alt = alt;
|
||||
else delete next.alt;
|
||||
data[field.key] = next;
|
||||
}}
|
||||
placeholder="Ảnh cho thấy gì — để trống nếu chỉ trang trí"
|
||||
/>
|
||||
</label>
|
||||
{:else}
|
||||
<button type="button" onclick={() => (picking = "cover")}>Chọn ảnh bìa</button>
|
||||
{/if}
|
||||
{#if invalid(field.key)}
|
||||
<span class="field-error" id={errorId}>{fieldError[field.key]}</span>
|
||||
{/if}
|
||||
{:else}
|
||||
<label>
|
||||
<span class="label">{field.label}{field.required ? " *" : ""}</span>
|
||||
@@ -362,9 +388,11 @@
|
||||
</option>{/each}
|
||||
</select>
|
||||
{:else if field.type === "tags"}
|
||||
<!-- On every keystroke, not on change: Ctrl/⌘+S while the cursor is still
|
||||
here must save what is typed, and `change` only fires on blur. -->
|
||||
<input
|
||||
value={(data[field.key] ?? []).join(", ")}
|
||||
onchange={(event) => setTags(field.key, event.currentTarget.value)}
|
||||
oninput={(event) => setTags(field.key, event.currentTarget.value)}
|
||||
placeholder="cách nhau bởi dấu phẩy"
|
||||
/>
|
||||
{:else if field.type === "number"}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import MediaPicker from "./MediaPicker.svelte";
|
||||
import { confirmAction, toast } from "./ui";
|
||||
import { SLUG_PATTERN } from "@/lib/admin/collections";
|
||||
import { afterSaveMessage } from "@/lib/admin/publish-phase";
|
||||
import { mediaFallbackSrc } from "@/lib/media";
|
||||
|
||||
/** @typedef {{ id: string; w: number; h: number; caption: { vi: string; en: string } }} Photo */
|
||||
@@ -143,7 +144,7 @@
|
||||
const cover = current.photos.findIndex((p) => p.id === current?.coverId);
|
||||
saving = true;
|
||||
try {
|
||||
await api("/api/admin/gallery", "PUT", {
|
||||
const result = await api("/api/admin/gallery", "PUT", {
|
||||
album,
|
||||
photos: current.photos,
|
||||
sha: current.sha,
|
||||
@@ -158,7 +159,9 @@
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
toast("Đã lưu album vào repo nội dung — bấm “Xuất bản” để đưa lên site.");
|
||||
const message = afterSaveMessage(result.publish, "Đã lưu album");
|
||||
toast(message.text, message.kind);
|
||||
if (message.queued) dispatchEvent(new Event("admin:published"));
|
||||
creating = false;
|
||||
await load();
|
||||
const saved = albums.find((a) => a.album === album);
|
||||
@@ -179,8 +182,10 @@
|
||||
);
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api("/api/admin/gallery", "DELETE", { album: current.album });
|
||||
toast("Đã xoá album.");
|
||||
const result = await api("/api/admin/gallery", "DELETE", { album: current.album });
|
||||
const message = afterSaveMessage(result.publish, "Đã xoá album");
|
||||
toast(message.text, message.kind);
|
||||
if (message.queued) dispatchEvent(new Event("admin:published"));
|
||||
current = null;
|
||||
baseline = "";
|
||||
await load();
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
let items = $state([]);
|
||||
let status = $state("");
|
||||
let query = $state("");
|
||||
/** Alt text for the next upload: inserted images and covers copy it from the library. */
|
||||
let uploadAlt = $state("");
|
||||
/** @type {string[]} */
|
||||
let selected = $state([]);
|
||||
/** @type {HTMLDialogElement | undefined} */
|
||||
@@ -67,7 +69,7 @@
|
||||
for (const file of Array.from(input.files ?? [])) {
|
||||
status = `Đang xử lý ${file.name}…`;
|
||||
try {
|
||||
const { item } = await uploadImage(file);
|
||||
const { item } = await uploadImage(file, uploadAlt.trim());
|
||||
items = cache = [item, ...items.filter((i) => i.id !== item.id)];
|
||||
if (multiple && !selected.includes(item.id)) selected = [...selected, item.id];
|
||||
status = "";
|
||||
@@ -76,6 +78,7 @@
|
||||
}
|
||||
}
|
||||
input.value = "";
|
||||
uploadAlt = "";
|
||||
}
|
||||
|
||||
/** @param {MediaItem} item */
|
||||
@@ -98,6 +101,13 @@
|
||||
<div class="top">
|
||||
<strong id="picker-title">{multiple ? "Chọn ảnh (nhiều)" : "Chọn ảnh"}</strong>
|
||||
<input type="search" bind:value={query} placeholder="Tìm ảnh" aria-label="Tìm ảnh" />
|
||||
<input
|
||||
class="alt"
|
||||
bind:value={uploadAlt}
|
||||
maxlength="300"
|
||||
placeholder="Mô tả (alt) cho ảnh sắp tải"
|
||||
aria-label="Mô tả (alt) cho ảnh sắp tải lên"
|
||||
/>
|
||||
<label class="button upload">
|
||||
Tải ảnh lên <input type="file" accept="image/*" multiple onchange={upload} />
|
||||
</label>
|
||||
@@ -152,7 +162,8 @@
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.top input[type="search"] {
|
||||
.top input[type="search"],
|
||||
.top .alt {
|
||||
flex: 1;
|
||||
min-inline-size: 10rem;
|
||||
}
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
import { onMount } from "svelte";
|
||||
import { api, describeError } from "./api";
|
||||
import { toast } from "./ui";
|
||||
import { canPublish, PHASE_TEXT } from "@/lib/admin/publish-phase";
|
||||
|
||||
/** @typedef {{ number: number; url: string; autoMerge: boolean; checks: string | null }} PullRequest */
|
||||
/** @typedef {{ contentHead: string; published: string; pr: PullRequest | null; run: { status: string; conclusion: string | null; url: string } | null; singleToken?: boolean }} Status */
|
||||
/** @typedef {import("@/lib/admin/publish-phase").PublishPhase} Phase */
|
||||
/** @typedef {{ contentHead: string; published: string; live: string | null; phase: Phase; pr: PullRequest | null; run: { status: string; conclusion: string | null; url: string } | null; singleToken?: boolean }} Status */
|
||||
|
||||
/** @type {Status | null} */
|
||||
let status = $state(null);
|
||||
@@ -12,14 +14,7 @@
|
||||
let failedToLoad = $state(false);
|
||||
|
||||
const short = (/** @type {string} */ sha) => sha.slice(0, 7);
|
||||
const pending = $derived(status !== null && status.contentHead !== status.published);
|
||||
const running = $derived(
|
||||
status !== null && (status.run?.status === "in_progress" || status.run?.status === "queued"),
|
||||
);
|
||||
const checking = $derived(status?.pr?.checks === "pending");
|
||||
const runFailed = $derived(
|
||||
status !== null && !status.pr && !running && status.run?.conclusion === "failure",
|
||||
);
|
||||
const moving = $derived(status?.phase === "building" || status?.phase === "deploying");
|
||||
|
||||
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
||||
let timer;
|
||||
@@ -28,7 +23,7 @@
|
||||
function schedule() {
|
||||
clearTimeout(timer);
|
||||
if (document.visibilityState !== "visible") return;
|
||||
const delay = running || checking ? 5_000 : pending ? 30_000 : 60_000;
|
||||
const delay = moving ? 10_000 : status?.phase === "pending" ? 30_000 : 60_000;
|
||||
timer = setTimeout(refresh, delay);
|
||||
}
|
||||
|
||||
@@ -42,12 +37,13 @@
|
||||
schedule();
|
||||
}
|
||||
|
||||
// Saves publish on their own; this is the retry for a failed or never-started publish.
|
||||
async function publish() {
|
||||
busy = true;
|
||||
try {
|
||||
await api("/api/admin/publish", "POST");
|
||||
toast("Đã gửi yêu cầu xuất bản — workflow đang chạy.");
|
||||
if (status) status.run = { status: "queued", conclusion: null, url: status.run?.url ?? "" };
|
||||
if (status) status.phase = "building";
|
||||
schedule();
|
||||
} catch (error) {
|
||||
toast(describeError(error), "error");
|
||||
@@ -58,13 +54,17 @@
|
||||
|
||||
onMount(() => {
|
||||
void refresh();
|
||||
// A save elsewhere in the admin just started a publish: look again soon.
|
||||
const onSaved = () => setTimeout(refresh, 3_000);
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState === "visible") void refresh();
|
||||
else clearTimeout(timer);
|
||||
};
|
||||
addEventListener("admin:published", onSaved);
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
removeEventListener("admin:published", onSaved);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
};
|
||||
});
|
||||
@@ -74,32 +74,13 @@
|
||||
{#if status}
|
||||
{#if status.pr}
|
||||
<a href={status.pr.url} target="_blank" rel="noopener noreferrer">PR #{status.pr.number}</a>
|
||||
<span class="state" data-state={status.pr.checks ?? "pending"}>
|
||||
{status.pr.checks === "success"
|
||||
? status.pr.autoMerge
|
||||
? "build xanh — đang merge"
|
||||
: "build xanh — chờ review"
|
||||
: status.pr.checks === "failure"
|
||||
? "build lỗi"
|
||||
: "đang build…"}
|
||||
</span>
|
||||
{:else if running}
|
||||
<span class="state" data-state="pending">đang chuẩn bị PR…</span>
|
||||
{:else if runFailed && status.run}
|
||||
<a
|
||||
class="state"
|
||||
data-state="failure"
|
||||
href={status.run.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
lần xuất bản trước lỗi ↗
|
||||
</a>
|
||||
{:else if pending}
|
||||
<span class="state" data-state="pending">có thay đổi chưa xuất bản</span>
|
||||
{:else}
|
||||
<span class="state" data-state="success">đã xuất bản ({short(status.published)})</span>
|
||||
{:else if status.phase === "failed" && status.run}
|
||||
<a href={status.run.url} target="_blank" rel="noopener noreferrer">log ↗</a>
|
||||
{/if}
|
||||
<span class="state" data-tone={PHASE_TEXT[status.phase].tone}>
|
||||
{PHASE_TEXT[status.phase].label}
|
||||
{#if status.phase === "live" && status.live}({short(status.live)}){/if}
|
||||
</span>
|
||||
{#if status.singleToken}
|
||||
<a
|
||||
class="warn"
|
||||
@@ -113,12 +94,12 @@
|
||||
type="button"
|
||||
class="primary"
|
||||
onclick={publish}
|
||||
disabled={busy || !pending || running || checking}
|
||||
disabled={busy || !canPublish(status.phase)}
|
||||
>
|
||||
Xuất bản
|
||||
{status.phase === "failed" ? "Xuất bản lại" : "Xuất bản"}
|
||||
</button>
|
||||
{:else if failedToLoad}
|
||||
<span class="state" data-state="failure">không đọc được trạng thái xuất bản</span>
|
||||
<span class="state" data-tone="err">không đọc được trạng thái xuất bản</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -133,10 +114,13 @@
|
||||
.state {
|
||||
color: var(--muted);
|
||||
}
|
||||
.state[data-state="success"] {
|
||||
.state[data-tone="ok"] {
|
||||
color: var(--ok);
|
||||
}
|
||||
.state[data-state="failure"] {
|
||||
.state[data-tone="warn"] {
|
||||
color: var(--warn);
|
||||
}
|
||||
.state[data-tone="err"] {
|
||||
color: var(--err);
|
||||
}
|
||||
.warn {
|
||||
|
||||
Vendored
+2
@@ -6,6 +6,8 @@
|
||||
|
||||
/** The git commit this build was made from, or null (set by `vite.define` in astro.config.mjs). */
|
||||
declare const __BUILD_COMMIT__: string | null;
|
||||
/** The poli0981/content commit the build's src/content pointed at, or null (same place). */
|
||||
declare const __CONTENT_COMMIT__: string | null;
|
||||
|
||||
declare namespace App {
|
||||
interface Locals {
|
||||
|
||||
@@ -13,6 +13,7 @@ type AuditAction =
|
||||
| "gallery.save"
|
||||
| "gallery.delete"
|
||||
| "publish"
|
||||
| "publish.auto"
|
||||
| "denylist.add"
|
||||
| "denylist.remove";
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { env } from "cloudflare:workers";
|
||||
import { GITHUB_CONTENT_TOKEN, GITHUB_PUBLISH_TOKEN } from "astro:env/server";
|
||||
import { log } from "../log";
|
||||
import { recordAudit } from "./audit";
|
||||
import { dispatchPublish } from "./github";
|
||||
|
||||
// Every admin save or delete publishes by itself: it starts .github/workflows/content-bump.yml,
|
||||
// which points src/content at the content repo's main, and CI + auto-merge + Workers Builds
|
||||
// take it live. Saves in quick succession don't pile up — the workflow's concurrency group
|
||||
// keeps one run going and one waiting, and the waiting one always reads the newest main.
|
||||
|
||||
/** The token that may start the publish workflow (falls back to the content token). */
|
||||
export const publishToken = (): string | undefined => GITHUB_PUBLISH_TOKEN ?? GITHUB_CONTENT_TOKEN;
|
||||
|
||||
/** "queued" when the workflow was started, "failed" when it could not be (the save stands). */
|
||||
export type AutoPublish = "queued" | "failed";
|
||||
|
||||
/**
|
||||
* Start a publish after a content commit. Never throws: the commit already succeeded, so a
|
||||
* dispatch problem is reported back to the editor (which offers "Xuất bản" by hand) instead
|
||||
* of turning a good save into an error.
|
||||
*/
|
||||
export async function autoPublish(admin: string, commit: string): Promise<AutoPublish> {
|
||||
const token = publishToken();
|
||||
if (!token) return "failed";
|
||||
try {
|
||||
await dispatchPublish(token);
|
||||
} catch (error) {
|
||||
log.warn("admin.autopublish_failed", {
|
||||
admin,
|
||||
commit,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return "failed";
|
||||
}
|
||||
await recordAudit(env.KV, {
|
||||
admin,
|
||||
action: "publish.auto",
|
||||
target: "content → site",
|
||||
detail: commit,
|
||||
});
|
||||
return "queued";
|
||||
}
|
||||
@@ -13,10 +13,19 @@ interface FieldSpec {
|
||||
type: FieldType;
|
||||
required?: boolean;
|
||||
options?: readonly string[];
|
||||
/** Longest text (characters). */
|
||||
max?: number;
|
||||
/** Numbers: whole numbers only, and the smallest allowed. */
|
||||
integer?: boolean;
|
||||
min?: number;
|
||||
/** Text: the whole value must match. */
|
||||
pattern?: RegExp;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
const SLUG = "[a-z0-9][a-z0-9-]*";
|
||||
export const SLUG_PATTERN = new RegExp(`^${SLUG}$`);
|
||||
|
||||
export type CollectionId = "blog" | "stories" | "projects" | "faq" | "gallery" | "legal" | "now";
|
||||
|
||||
export interface CollectionSpec {
|
||||
@@ -71,7 +80,7 @@ export const COLLECTIONS: Record<CollectionId, CollectionSpec> = {
|
||||
fields: [
|
||||
...LONGFORM,
|
||||
{ key: "series", label: "Tên bộ truyện", type: "text" },
|
||||
{ key: "chapter", label: "Chương", type: "number" },
|
||||
{ key: "chapter", label: "Chương", type: "number", integer: true, min: 1 },
|
||||
{
|
||||
key: "status",
|
||||
label: "Trạng thái",
|
||||
@@ -140,7 +149,8 @@ export const COLLECTIONS: Record<CollectionId, CollectionSpec> = {
|
||||
label: "Mã album",
|
||||
type: "text",
|
||||
required: true,
|
||||
hint: "Chữ thường, số, gạch nối",
|
||||
pattern: SLUG_PATTERN,
|
||||
hint: "Chữ thường, số, gạch nối — album phải đã có ảnh",
|
||||
},
|
||||
{ key: "coverIndex", label: "Ảnh bìa (thứ tự, từ 0)", type: "number" },
|
||||
],
|
||||
@@ -170,11 +180,10 @@ export const COLLECTIONS: Record<CollectionId, CollectionSpec> = {
|
||||
},
|
||||
};
|
||||
|
||||
const SLUG = "[a-z0-9][a-z0-9-]*";
|
||||
// Stories are stories/<series>/<chapter>.md, or stories/<slug>.md for a one-shot.
|
||||
const ENTRY_PATH = new RegExp(
|
||||
`^(blog|projects|faq|gallery|legal|now)/${SLUG}\\.mdx?$|^stories/${SLUG}/${SLUG}\\.mdx?$`,
|
||||
`^(blog|projects|faq|gallery|legal|now)/${SLUG}\\.mdx?$|^stories/(${SLUG}/)?${SLUG}\\.mdx?$`,
|
||||
);
|
||||
export const SLUG_PATTERN = new RegExp(`^${SLUG}$`);
|
||||
|
||||
/** The collection a content path belongs to, or null if the admin may not touch it. */
|
||||
export function collectionOf(path: string): CollectionSpec | null {
|
||||
@@ -192,10 +201,10 @@ export function newEntryPath(
|
||||
series?: string,
|
||||
): string | null {
|
||||
if (!COLLECTIONS[collection]?.creatable || !SLUG_PATTERN.test(slug)) return null;
|
||||
if (collection === "stories") {
|
||||
if (!series || !SLUG_PATTERN.test(series)) return null;
|
||||
return `stories/${series}/${slug}.md`;
|
||||
if (collection === "stories" && series) {
|
||||
return SLUG_PATTERN.test(series) ? `stories/${series}/${slug}.md` : null;
|
||||
}
|
||||
// No series: a one-shot story (stories/<slug>.md), or any other collection.
|
||||
return `${collection}/${slug}.md`;
|
||||
}
|
||||
|
||||
@@ -204,7 +213,13 @@ export function galleryPhotosPath(album: string): string | null {
|
||||
return SLUG_PATTERN.test(album) ? `gallery-photos/${album}.json` : null;
|
||||
}
|
||||
|
||||
type FieldErrorCode = "required" | "type" | "option" | "max" | "format";
|
||||
/**
|
||||
* `min`: a number below the field's minimum. `conflict`: the value can't coexist with another
|
||||
* key (a local `cover` next to `coverMedia`). `missing`: it names something that doesn't
|
||||
* exist (an album without photos — checked by the API, which can see the repos).
|
||||
*/
|
||||
type FieldErrorCode =
|
||||
"required" | "type" | "option" | "max" | "format" | "min" | "conflict" | "missing";
|
||||
|
||||
export interface FieldError {
|
||||
field: string;
|
||||
@@ -243,7 +258,8 @@ function checkField(field: FieldSpec, value: unknown): FieldErrorCode | null {
|
||||
case "text":
|
||||
case "textarea":
|
||||
if (typeof value !== "string") return "type";
|
||||
return field.max !== undefined && value.length > field.max ? "max" : null;
|
||||
if (field.max !== undefined && value.length > field.max) return "max";
|
||||
return field.pattern && !field.pattern.test(value) ? "format" : null;
|
||||
case "url":
|
||||
if (typeof value !== "string") return "type";
|
||||
return isHttpUrl(value) ? null : "format";
|
||||
@@ -255,7 +271,9 @@ function checkField(field: FieldSpec, value: unknown): FieldErrorCode | null {
|
||||
case "tags":
|
||||
return Array.isArray(value) && value.every((tag) => typeof tag === "string") ? null : "type";
|
||||
case "number":
|
||||
return typeof value === "number" && Number.isFinite(value) ? null : "type";
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) return "type";
|
||||
if (field.integer && !Number.isInteger(value)) return "type";
|
||||
return field.min !== undefined && value < field.min ? "min" : null;
|
||||
case "checkbox":
|
||||
return typeof value === "boolean" ? null : "type";
|
||||
case "media":
|
||||
@@ -289,5 +307,10 @@ export function validateFrontmatter(
|
||||
const code = checkField(field, value);
|
||||
if (code) errors.push({ field: field.key, code });
|
||||
}
|
||||
// The content schema allows one cover: a local image (`cover`, set by hand in the repo) or
|
||||
// an R2 upload (`coverMedia`, set here) — not both.
|
||||
if (!isEmpty(data.cover) && !isEmpty(data.coverMedia)) {
|
||||
errors.push({ field: "coverMedia", code: "conflict" });
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
+13
-6
@@ -82,11 +82,13 @@ interface TreeEntry {
|
||||
}
|
||||
|
||||
/**
|
||||
* Every text file of the content repo's main branch, in ONE GraphQL request (three
|
||||
* directory levels: collection/series/file), plus the commit it was read at.
|
||||
* Every text file of the content repo's main branch — or of one commit, `at` — in ONE
|
||||
* GraphQL request (three directory levels: collection/series/file), plus the commit it was
|
||||
* read at.
|
||||
*/
|
||||
export async function listContentFiles(
|
||||
token: string,
|
||||
at?: string,
|
||||
): Promise<{ head: string; files: RepoFile[] }> {
|
||||
const blob = "... on Blob { oid text }";
|
||||
const level = (inner: string) => `entries { path type object { ${blob} ${inner} } }`;
|
||||
@@ -99,8 +101,10 @@ export async function listContentFiles(
|
||||
}
|
||||
}`;
|
||||
const data = await graphql<{
|
||||
repository: { ref: { target: { oid: string } }; object: { entries: TreeEntry[] } };
|
||||
}>(token, query, { ...CONTENT_REPO, expr: `${BRANCH}:` });
|
||||
repository: { ref: { target: { oid: string } }; object: { entries: TreeEntry[] } | null };
|
||||
}>(token, query, { ...CONTENT_REPO, expr: `${at ?? BRANCH}:` });
|
||||
// A commit the repo doesn't have (yet) has no tree: report it as empty, not as a crash.
|
||||
if (!data.repository.object) return { head: at ?? data.repository.ref.target.oid, files: [] };
|
||||
|
||||
const files: RepoFile[] = [];
|
||||
const walk = (entries: TreeEntry[]) => {
|
||||
@@ -116,7 +120,7 @@ export async function listContentFiles(
|
||||
}
|
||||
};
|
||||
walk(data.repository.object.entries);
|
||||
return { head: data.repository.ref.target.oid, files };
|
||||
return { head: at ?? data.repository.ref.target.oid, files };
|
||||
}
|
||||
|
||||
/** One file of the content repo at main, or null if it doesn't exist. */
|
||||
@@ -199,7 +203,10 @@ export async function commitContent(
|
||||
|
||||
export interface PublishStatus {
|
||||
contentHead: string;
|
||||
/** The content commit the live site is built from (gitlink in the site repo's main). */
|
||||
/**
|
||||
* The content commit the site repo's main points at (the src/content gitlink): merged, but
|
||||
* live only once Workers Builds has deployed that main — compare with versionInfo().content.
|
||||
*/
|
||||
published: string;
|
||||
pr: {
|
||||
number: number;
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// Where a content change is on its way to the live site, as one word for the admin. Shared
|
||||
// by /api/admin/publish (which computes it) and the PublishBar and Dashboard (which show it),
|
||||
// so "published" can no longer mean "merged into main" while production still runs the old
|
||||
// content — the symptom behind the Oct 2026 "content pushed but not on the web".
|
||||
//
|
||||
// content repo main ──dispatch──▶ content/bump PR ──build──▶ merged into site main ──deploy──▶ live
|
||||
// (pending) (building · review · failed) (deploying) (live)
|
||||
|
||||
export type PublishPhase = "live" | "pending" | "building" | "review" | "deploying" | "failed";
|
||||
|
||||
export interface PhaseInput {
|
||||
/** poli0981/content main. */
|
||||
contentHead: string;
|
||||
/** The content commit the site repo's main points at (src/content gitlink). */
|
||||
published: string;
|
||||
/** The content commit the running Worker was built with; null when unknown (local dev). */
|
||||
live: string | null;
|
||||
pr: { autoMerge: boolean; checks: "pending" | "success" | "failure" | null } | null;
|
||||
run: { status: string; conclusion: string | null } | null;
|
||||
}
|
||||
|
||||
const RUNNING = new Set(["queued", "in_progress", "requested", "waiting", "pending"]);
|
||||
|
||||
export function publishPhase(status: PhaseInput): PublishPhase {
|
||||
// Without a build-time content commit, main's pointer is the best available stand-in.
|
||||
const live = status.live ?? status.published;
|
||||
if (live === status.contentHead) return "live";
|
||||
const { pr, run } = status;
|
||||
if (pr) {
|
||||
if (pr.checks === "failure") return "failed";
|
||||
// content-bump.yml leaves auto-merge off when the publish touches .mdx (code at build time).
|
||||
return pr.autoMerge ? "building" : "review";
|
||||
}
|
||||
if (run && RUNNING.has(run.status)) return "building";
|
||||
if (status.published === status.contentHead) return "deploying";
|
||||
if (run?.conclusion === "failure") return "failed";
|
||||
return "pending";
|
||||
}
|
||||
|
||||
/** How each phase reads in the admin (Vietnamese), and the tone of its badge. */
|
||||
export const PHASE_TEXT: Record<
|
||||
PublishPhase,
|
||||
{ label: string; tone: "ok" | "warn" | "err" | "info" }
|
||||
> = {
|
||||
live: { label: "đã lên web", tone: "ok" },
|
||||
pending: { label: "có thay đổi chưa xuất bản", tone: "warn" },
|
||||
building: { label: "đang build…", tone: "info" },
|
||||
review: { label: "chờ duyệt (có file .mdx)", tone: "warn" },
|
||||
deploying: { label: "đã merge — đang deploy…", tone: "info" },
|
||||
failed: { label: "xuất bản lỗi", tone: "err" },
|
||||
};
|
||||
|
||||
/** Phases in which nothing is moving, so starting a publish by hand makes sense. */
|
||||
export const canPublish = (phase: PublishPhase) => phase === "pending" || phase === "failed";
|
||||
|
||||
/**
|
||||
* The admin's toast after a save or delete, from the `publish` field the API returns
|
||||
* ("queued" | "failed", lib/admin/autopublish). `done` says what happened, e.g. "Đã lưu".
|
||||
*/
|
||||
export function afterSaveMessage(
|
||||
publish: unknown,
|
||||
done: string,
|
||||
): { text: string; kind: "ok" | "info"; queued: boolean } {
|
||||
return publish === "queued"
|
||||
? {
|
||||
text: `${done} — đang tự xuất bản, thường lên web sau 10–15 phút.`,
|
||||
kind: "ok",
|
||||
queued: true,
|
||||
}
|
||||
: {
|
||||
text: `${done}, nhưng chưa tự xuất bản được — bấm “Xuất bản” trên thanh trên cùng.`,
|
||||
kind: "info",
|
||||
queued: false,
|
||||
};
|
||||
}
|
||||
@@ -9,6 +9,11 @@ export interface VersionInfo {
|
||||
timestamp: string | null;
|
||||
/** The commit Workers Builds built (astro.config.mjs defines __BUILD_COMMIT__). */
|
||||
commit: string | null;
|
||||
/**
|
||||
* The poli0981/content commit that build's src/content pointed at (__CONTENT_COMMIT__):
|
||||
* what the live site actually shows, as opposed to what the site repo's main points at.
|
||||
*/
|
||||
content: string | null;
|
||||
}
|
||||
|
||||
type VersionEnv = { CF_VERSION_METADATA?: Partial<WorkerVersionMetadata> };
|
||||
@@ -21,5 +26,6 @@ export function versionInfo(env: VersionEnv | undefined): VersionInfo {
|
||||
timestamp: meta?.timestamp || null,
|
||||
// `typeof` so this also runs where the build-time constant was never defined (tests).
|
||||
commit: typeof __BUILD_COMMIT__ === "string" ? __BUILD_COMMIT__ : null,
|
||||
content: typeof __CONTENT_COMMIT__ === "string" ? __CONTENT_COMMIT__ : null,
|
||||
};
|
||||
}
|
||||
@@ -2,16 +2,34 @@ import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { GITHUB_CONTENT_TOKEN } from "astro:env/server";
|
||||
import { recordAudit } from "@/lib/admin/audit";
|
||||
import { collectionOf, validateFrontmatter } from "@/lib/admin/collections";
|
||||
import { autoPublish } from "@/lib/admin/autopublish";
|
||||
import {
|
||||
collectionOf,
|
||||
galleryPhotosPath,
|
||||
validateFrontmatter,
|
||||
type FieldError,
|
||||
} from "@/lib/admin/collections";
|
||||
import { buildFile, splitFile, type Frontmatter } from "@/lib/admin/frontmatter";
|
||||
import { commitContent, listContentFiles, readContentFile } from "@/lib/admin/github";
|
||||
import { errorResponse, isPlainObject, json, readJson } from "@/lib/admin/http";
|
||||
import { localPhotoCount } from "@/lib/gallery";
|
||||
import { log } from "@/lib/log";
|
||||
|
||||
// Content entries of poli0981/content. Saving commits straight to the content repo's
|
||||
// main branch; nothing goes live until "Publish" (api/admin/publish).
|
||||
// Content entries of poli0981/content. Saving commits straight to the content repo's main
|
||||
// branch and then starts a publish (lib/admin/autopublish), so a save goes live on its own.
|
||||
export const prerender = false;
|
||||
|
||||
/**
|
||||
* An album entry must point at an album that has photos — local ones in this repo or an R2
|
||||
* list in the content repo — or the publish build fails (lib/gallery getAlbumPhotos).
|
||||
*/
|
||||
async function albumProblem(token: string, album: unknown): Promise<FieldError | null> {
|
||||
if (typeof album !== "string") return null; // validateFrontmatter already said why
|
||||
const list = galleryPhotosPath(album);
|
||||
if (!list || localPhotoCount(album) > 0 || (await readContentFile(token, list))) return null;
|
||||
return { field: "album", code: "missing" };
|
||||
}
|
||||
|
||||
const MAX_FILE_BYTES = 200_000;
|
||||
|
||||
export const GET: APIRoute = async ({ url }) => {
|
||||
@@ -81,6 +99,10 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
if (!collection.creatable) return json({ error: "not_creatable" }, 400);
|
||||
}
|
||||
const errors = validateFrontmatter(collection, input.frontmatter);
|
||||
if (errors.length === 0 && collection.id === "gallery") {
|
||||
const problem = await albumProblem(GITHUB_CONTENT_TOKEN, input.frontmatter.album);
|
||||
if (problem) errors.push(problem);
|
||||
}
|
||||
if (errors.length > 0) return json({ error: "invalid_fields", fields: errors }, 400);
|
||||
|
||||
const original = input.sha ? await readContentFile(GITHUB_CONTENT_TOKEN, input.path) : null;
|
||||
@@ -94,9 +116,11 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
}
|
||||
const verb = input.sha ? "update" : "add";
|
||||
const email = locals.admin?.email ?? "unknown";
|
||||
// The content repo is public: the commit says it came through the admin, but who it was
|
||||
// stays in the private audit log below.
|
||||
const commit = await commitContent(
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
`content(${collection.id}): ${verb} ${input.path}\n\nvia admin (${email})`,
|
||||
`content(${collection.id}): ${verb} ${input.path}\n\nvia admin`,
|
||||
[{ path: input.path, text, expectSha: input.sha }],
|
||||
);
|
||||
const saved = await readContentFile(GITHUB_CONTENT_TOKEN, input.path);
|
||||
@@ -107,7 +131,8 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
detail: commit,
|
||||
});
|
||||
log.info("admin.content_saved", { path: input.path, verb, commit, admin: email });
|
||||
return json({ commit, path: input.path, sha: saved?.sha ?? null });
|
||||
const publish = await autoPublish(email, commit);
|
||||
return json({ commit, path: input.path, sha: saved?.sha ?? null, publish });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
@@ -128,7 +153,7 @@ export const DELETE: APIRoute = async ({ request, locals }) => {
|
||||
const email = locals.admin?.email ?? "unknown";
|
||||
const commit = await commitContent(
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
`content: delete ${input.path}\n\nvia admin (${email})`,
|
||||
`content: delete ${input.path}\n\nvia admin`,
|
||||
[{ path: input.path, text: null, expectSha: input.sha }],
|
||||
);
|
||||
await recordAudit(env.KV, {
|
||||
@@ -138,7 +163,8 @@ export const DELETE: APIRoute = async ({ request, locals }) => {
|
||||
detail: commit,
|
||||
});
|
||||
log.info("admin.content_deleted", { path: input.path, commit, admin: email });
|
||||
return json({ commit });
|
||||
const publish = await autoPublish(email, commit);
|
||||
return json({ commit, publish });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { GITHUB_CONTENT_TOKEN } from "astro:env/server";
|
||||
import { recordAudit } from "@/lib/admin/audit";
|
||||
import { autoPublish } from "@/lib/admin/autopublish";
|
||||
import { galleryPhotosPath, SLUG_PATTERN } from "@/lib/admin/collections";
|
||||
import { buildFile, splitFile } from "@/lib/admin/frontmatter";
|
||||
import {
|
||||
@@ -181,7 +182,7 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
const verb = input.create ? "create" : "update";
|
||||
const commit = await commitContent(
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
`content(gallery): ${verb} album ${input.album}\n\nvia admin (${email})`,
|
||||
`content(gallery): ${verb} album ${input.album}\n\nvia admin`,
|
||||
changes,
|
||||
);
|
||||
await recordAudit(env.KV, {
|
||||
@@ -191,7 +192,8 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
detail: commit,
|
||||
});
|
||||
log.info("admin.gallery_saved", { album: input.album, verb, commit, admin: email });
|
||||
return json({ commit });
|
||||
const publish = await autoPublish(email, commit);
|
||||
return json({ commit, publish });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
@@ -214,7 +216,7 @@ export const DELETE: APIRoute = async ({ request, locals }) => {
|
||||
const email = locals.admin?.email ?? "unknown";
|
||||
const commit = await commitContent(
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
`content(gallery): delete album ${album}\n\nvia admin (${email})`,
|
||||
`content(gallery): delete album ${album}\n\nvia admin`,
|
||||
doomed.map((file) => ({ path: file.path, text: null, expectSha: file.sha })),
|
||||
);
|
||||
await recordAudit(env.KV, {
|
||||
@@ -224,7 +226,8 @@ export const DELETE: APIRoute = async ({ request, locals }) => {
|
||||
detail: commit,
|
||||
});
|
||||
log.info("admin.gallery_deleted", { album, commit, admin: email });
|
||||
return json({ commit, deleted: doomed.map((file) => file.path) });
|
||||
const publish = await autoPublish(email, commit);
|
||||
return json({ commit, deleted: doomed.map((file) => file.path), publish });
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { errorResponse, json, readJson } from "@/lib/admin/http";
|
||||
import { assertDeclaredSize, BodyTooLargeError } from "@/lib/body";
|
||||
import { log } from "@/lib/log";
|
||||
import { MEDIA_ID } from "@/lib/media";
|
||||
import { versionInfo } from "@/lib/version";
|
||||
import {
|
||||
deleteMedia,
|
||||
listMedia,
|
||||
@@ -20,6 +21,22 @@ import {
|
||||
// The R2 media library: list, upload (transform once → R2), edit alt text, delete.
|
||||
export const prerender = false;
|
||||
|
||||
/**
|
||||
* Content files that mention an image: on the content repo's main AND in the content the
|
||||
* live site was built from. Main alone is not enough — an edit that dropped the image but is
|
||||
* not live yet would let the delete break the page visitors still see.
|
||||
*/
|
||||
async function filesUsing(token: string, id: string): Promise<string[]> {
|
||||
const live = versionInfo(env as unknown as Parameters<typeof versionInfo>[0]).content;
|
||||
const main = await listContentFiles(token);
|
||||
const snapshots = [main];
|
||||
if (live && live !== main.head) snapshots.push(await listContentFiles(token, live));
|
||||
const paths = snapshots.flatMap(({ files }) =>
|
||||
files.filter((file) => file.text.includes(id)).map((file) => file.path),
|
||||
);
|
||||
return [...new Set(paths)];
|
||||
}
|
||||
|
||||
/** Multipart framing (boundaries, the alt field, headers) on top of the file itself. */
|
||||
const FORM_OVERHEAD_BYTES = 64 * 1024;
|
||||
|
||||
@@ -117,8 +134,7 @@ export const DELETE: APIRoute = async ({ request, url, locals }) => {
|
||||
// Refuse while any content still points at it — the live site would break, and a
|
||||
// publish would fail the build anyway.
|
||||
if (GITHUB_CONTENT_TOKEN) {
|
||||
const { files } = await listContentFiles(GITHUB_CONTENT_TOKEN);
|
||||
const usedIn = files.filter((f) => f.text.includes(input.id)).map((f) => f.path);
|
||||
const usedIn = await filesUsing(GITHUB_CONTENT_TOKEN, input.id);
|
||||
if (usedIn.length) return json({ error: "in_use", usedIn }, 409);
|
||||
}
|
||||
await deleteMedia(env, input.id, url.origin);
|
||||
|
||||
@@ -2,22 +2,34 @@ import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { recordAudit } from "@/lib/admin/audit";
|
||||
import { GITHUB_CONTENT_TOKEN, GITHUB_PUBLISH_TOKEN } from "astro:env/server";
|
||||
import { publishToken } from "@/lib/admin/autopublish";
|
||||
import { dispatchPublish, publishStatus } from "@/lib/admin/github";
|
||||
import { errorResponse, json } from "@/lib/admin/http";
|
||||
import { publishPhase } from "@/lib/admin/publish-phase";
|
||||
import { log } from "@/lib/log";
|
||||
import { versionInfo } from "@/lib/version";
|
||||
|
||||
// Publish = run .github/workflows/content-bump.yml on the site repo: it points the
|
||||
// src/content submodule at content's main, opens/updates the content/bump PR, and lets
|
||||
// CI + auto-merge deploy it (Workers Builds). Edits that touch .mdx wait for review.
|
||||
// Saves and deletes start it on their own (lib/admin/autopublish); POST is the manual retry.
|
||||
export const prerender = false;
|
||||
|
||||
export const GET: APIRoute = async () => {
|
||||
if (!GITHUB_CONTENT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
try {
|
||||
const status = await publishStatus(GITHUB_CONTENT_TOKEN);
|
||||
// Without its own publish token, the content token is doing the dispatching — which
|
||||
// means it has rights on this repo too. The admin shows a warning for this.
|
||||
return json({ ...status, singleToken: !GITHUB_PUBLISH_TOKEN });
|
||||
// The admin runs in the same Worker as the public site, so the content commit this
|
||||
// build was made from is exactly what visitors are seeing.
|
||||
const live = versionInfo(env as unknown as Parameters<typeof versionInfo>[0]).content;
|
||||
return json({
|
||||
...status,
|
||||
live,
|
||||
phase: publishPhase({ ...status, live }),
|
||||
// Without its own publish token, the content token is doing the dispatching — which
|
||||
// means it has rights on this repo too. The admin shows a warning for this.
|
||||
singleToken: !GITHUB_PUBLISH_TOKEN,
|
||||
});
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
}
|
||||
@@ -26,7 +38,7 @@ export const GET: APIRoute = async () => {
|
||||
export const POST: APIRoute = async ({ locals }) => {
|
||||
// Dispatching needs Actions write on the site repo — the publish token's only power.
|
||||
// Falls back to the content token for single-token setups.
|
||||
const token = GITHUB_PUBLISH_TOKEN ?? GITHUB_CONTENT_TOKEN;
|
||||
const token = publishToken();
|
||||
if (!token) return json({ error: "not_configured" }, 503);
|
||||
try {
|
||||
await dispatchPublish(token);
|
||||
|
||||
+10
-3
@@ -249,7 +249,11 @@ describe("/api/admin/overview and /api/admin/activity", () => {
|
||||
};
|
||||
assert.deepEqual(
|
||||
body.audit.map((e) => [e.action, e.target, e.admin]),
|
||||
[["content.save", "blog/b.md", OWNER]],
|
||||
// Newest first: the save, then the publish it started on its own.
|
||||
[
|
||||
["publish.auto", "content → site", OWNER],
|
||||
["content.save", "blog/b.md", OWNER],
|
||||
],
|
||||
);
|
||||
assert.equal(body.commits[0]?.message, "content(blog): update blog/b.md");
|
||||
|
||||
@@ -338,7 +342,10 @@ describe("/api/admin/gallery covers and deletion", () => {
|
||||
assert.equal(github?.files.get("gallery/other.md")?.includes("coverIndex"), false);
|
||||
assert.deepEqual(
|
||||
(await listAudit(kv.asBinding())).map((e) => [e.action, e.target]),
|
||||
[["gallery.save", "game"]],
|
||||
[
|
||||
["publish.auto", "content → site"],
|
||||
["gallery.save", "game"],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
@@ -372,7 +379,7 @@ describe("/api/admin/gallery covers and deletion", () => {
|
||||
assert.equal((await del({ album: "Bad Name" })).status, 400);
|
||||
assert.deepEqual(
|
||||
(await listAudit(kv.asBinding())).map((e) => e.action),
|
||||
["gallery.delete"],
|
||||
["publish.auto", "gallery.delete"],
|
||||
);
|
||||
setServerEnv({});
|
||||
assert.equal((await del({ album: "other" })).status, 503);
|
||||
|
||||
+108
-3
@@ -346,6 +346,59 @@ describe("/api/admin/content", () => {
|
||||
assert.match(github.files.get("blog/dem-dau.md") ?? "", /description: Mô tả mới/);
|
||||
});
|
||||
|
||||
it("publishes by itself after each save and delete, keeping the admin out of public commits", async () => {
|
||||
const saved = await call(
|
||||
contentApi.PUT,
|
||||
jsonRequest("PUT", { path: "blog/moi.md", sha: null, frontmatter: valid, body: "Hello" }),
|
||||
);
|
||||
assert.equal(((await saved.json()) as { publish: string }).publish, "queued");
|
||||
const deleted = await call(
|
||||
contentApi.DELETE,
|
||||
jsonRequest("DELETE", { path: "blog/moi.md", sha: github.sha("blog/moi.md") }),
|
||||
);
|
||||
assert.equal(((await deleted.json()) as { publish: string }).publish, "queued");
|
||||
assert.deepEqual(github.dispatched, ["main", "main"]);
|
||||
// The content repo is public: the commit says "via admin", the email stays in the audit log.
|
||||
for (const { message } of github.history) {
|
||||
assert.match(message, /\n\nvia admin$/);
|
||||
assert.doesNotMatch(message, /owner@example\.com/);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a save that could not start its publish, and says so", async () => {
|
||||
github.failDispatch = 403;
|
||||
const { result } = await captureLogs(() =>
|
||||
call(
|
||||
contentApi.PUT,
|
||||
jsonRequest("PUT", { path: "blog/moi.md", sha: null, frontmatter: valid, body: "Hi" }),
|
||||
),
|
||||
);
|
||||
assert.equal(result.status, 200);
|
||||
assert.equal(((await result.json()) as { publish: string }).publish, "failed");
|
||||
assert.ok(github.files.has("blog/moi.md"));
|
||||
assert.deepEqual(github.dispatched, []);
|
||||
});
|
||||
|
||||
it("refuses an album entry pointing at an album with no photos", async () => {
|
||||
github.files.set("gallery/game.md", "---\ntitle: Game\nlang: vi\nalbum: game\n---\n");
|
||||
github.files.set("gallery-photos/game.json", JSON.stringify({ photos: [] }));
|
||||
const put = (album: string) =>
|
||||
call(
|
||||
contentApi.PUT,
|
||||
jsonRequest("PUT", {
|
||||
path: "gallery/game.md",
|
||||
sha: github.sha("gallery/game.md"),
|
||||
frontmatter: { title: "Game", lang: "vi", date: "2026-10-24", album },
|
||||
body: "",
|
||||
}),
|
||||
);
|
||||
assert.equal((await put("game")).status, 200);
|
||||
assert.deepEqual(await (await put("nope")).json(), {
|
||||
error: "invalid_fields",
|
||||
fields: [{ field: "album", code: "missing" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("validates before writing anything", async () => {
|
||||
const put = (body: unknown) => call(contentApi.PUT, jsonRequest("PUT", body));
|
||||
assert.equal((await put({ path: 1 })).status, 400);
|
||||
@@ -473,8 +526,25 @@ describe("/api/admin/gallery", () => {
|
||||
},
|
||||
});
|
||||
assert.equal(created.status, 200);
|
||||
assert.equal(((await created.json()) as { publish: string }).publish, "queued");
|
||||
assert.match(github.files.get("gallery/trip-en.md") ?? "", /description: Hello/);
|
||||
assert.equal(JSON.parse(github.files.get("gallery-photos/trip.json") ?? "{}").photos.length, 1);
|
||||
assert.equal(github.dispatched.length, 2);
|
||||
});
|
||||
|
||||
it("deletes an album and publishes that too", async () => {
|
||||
const response = await call(
|
||||
galleryApi.DELETE,
|
||||
jsonRequest("DELETE", { album: "game" }, "/api/admin/gallery"),
|
||||
);
|
||||
const result = (await response.json()) as { deleted: string[]; publish: string };
|
||||
assert.deepEqual(result.deleted.sort(), [
|
||||
"gallery-photos/game.json",
|
||||
"gallery/game-en.md",
|
||||
"gallery/game.md",
|
||||
]);
|
||||
assert.equal(result.publish, "queued");
|
||||
assert.match(github.history[0].message, /^content\(gallery\): delete album game\n\nvia admin$/);
|
||||
});
|
||||
|
||||
it("refuses bad input and existing albums", async () => {
|
||||
@@ -612,6 +682,35 @@ describe("/api/admin/media", () => {
|
||||
assert.equal(response.status, 409);
|
||||
assert.deepEqual(((await response.json()) as { usedIn: string[] }).usedIn, ["blog/a.md"]);
|
||||
});
|
||||
|
||||
it("also refuses while the live site's content still uses it", async () => {
|
||||
// Main no longer mentions the image, but the build visitors see was made before that.
|
||||
github.files.delete("blog/a.md");
|
||||
github.snapshots.set("live-commit", { "blog/a.md": "uses 0123456789abcdef" });
|
||||
await r2.put(
|
||||
"private/meta/0123456789abcdef.json",
|
||||
JSON.stringify({ id: "0123456789abcdef", variants: [] }),
|
||||
);
|
||||
const constants = globalThis as { __CONTENT_COMMIT__?: string };
|
||||
constants.__CONTENT_COMMIT__ = "live-commit";
|
||||
try {
|
||||
const response = await call(
|
||||
mediaApi.DELETE,
|
||||
jsonRequest("DELETE", { id: "0123456789abcdef" }, "/api/admin/media"),
|
||||
);
|
||||
assert.equal(response.status, 409);
|
||||
assert.deepEqual(((await response.json()) as { usedIn: string[] }).usedIn, ["blog/a.md"]);
|
||||
// A live commit the repo doesn't know (yet) reads as empty, not as an error.
|
||||
constants.__CONTENT_COMMIT__ = "unknown-commit";
|
||||
const gone = await call(
|
||||
mediaApi.DELETE,
|
||||
jsonRequest("DELETE", { id: "0123456789abcdef" }, "/api/admin/media"),
|
||||
);
|
||||
assert.equal(gone.status, 200);
|
||||
} finally {
|
||||
delete constants.__CONTENT_COMMIT__;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("/api/admin/publish", () => {
|
||||
@@ -621,10 +720,16 @@ describe("/api/admin/publish", () => {
|
||||
|
||||
it("reports status (flagging single-token mode) and dispatches", async () => {
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN });
|
||||
const status = (await (
|
||||
await call(publishApi.GET, new Request("https://admin.poli0981.dev/api/admin/publish"))
|
||||
).json()) as { singleToken: boolean };
|
||||
const read = async () =>
|
||||
(await (
|
||||
await call(publishApi.GET, new Request("https://admin.poli0981.dev/api/admin/publish"))
|
||||
).json()) as { singleToken: boolean; phase: string; live: string | null };
|
||||
const status = await read();
|
||||
assert.equal(status.singleToken, true);
|
||||
assert.equal(status.live, null);
|
||||
assert.equal(status.phase, "live");
|
||||
github.head = "commit-9";
|
||||
assert.equal((await read()).phase, "pending");
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN, GITHUB_PUBLISH_TOKEN: "publish-token" });
|
||||
const dispatched = await call(
|
||||
publishApi.POST,
|
||||
|
||||
@@ -221,7 +221,13 @@ describe("GET /api/health", () => {
|
||||
assert.equal(response.headers.get("cache-control"), "no-store");
|
||||
assert.deepEqual(await response.json(), {
|
||||
ok: true,
|
||||
version: { id: "v-9", tag: null, timestamp: "2026-10-24T01:02:03Z", commit: null },
|
||||
version: {
|
||||
id: "v-9",
|
||||
tag: null,
|
||||
timestamp: "2026-10-24T01:02:03Z",
|
||||
commit: null,
|
||||
content: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -81,6 +81,30 @@ describe("frontmatter validation", () => {
|
||||
assert.equal(galleryPhotosPath("trip-2026"), "gallery-photos/trip-2026.json");
|
||||
assert.equal(galleryPhotosPath("../x"), null);
|
||||
});
|
||||
|
||||
it("holds the admin to the content schema's own rules", () => {
|
||||
const stories = COLLECTIONS.stories;
|
||||
// chapter: z.number().int().positive()
|
||||
assert.deepEqual(validateFrontmatter(stories, { ...valid, chapter: 2 }), []);
|
||||
assert.deepEqual(validateFrontmatter(stories, { ...valid, chapter: 1.5 }), [
|
||||
{ field: "chapter", code: "type" },
|
||||
]);
|
||||
assert.deepEqual(validateFrontmatter(stories, { ...valid, chapter: 0 }), [
|
||||
{ field: "chapter", code: "min" },
|
||||
]);
|
||||
// One cover only: a local `cover` (kept untouched by the admin) or an R2 `coverMedia`.
|
||||
const cover = { id: "0123456789abcdef", w: 800, h: 600 };
|
||||
assert.deepEqual(validateFrontmatter(blog, { ...valid, cover: "./x.jpg", coverMedia: cover }), [
|
||||
{ field: "coverMedia", code: "conflict" },
|
||||
]);
|
||||
// An album is a slug (the folder and gallery-photos/<album>.json are named after it).
|
||||
const gallery = COLLECTIONS.gallery;
|
||||
const album = { title: "A", lang: "vi", date: "2026-10-24", album: "game" };
|
||||
assert.deepEqual(validateFrontmatter(gallery, album), []);
|
||||
assert.deepEqual(validateFrontmatter(gallery, { ...album, album: "Game Shots" }), [
|
||||
{ field: "album", code: "format" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("admin collections", () => {
|
||||
@@ -97,22 +121,25 @@ describe("admin collections", () => {
|
||||
assert.equal(newEntryPath("gallery", "trip"), null);
|
||||
});
|
||||
|
||||
it("rejects bad slugs and stories without a series", () => {
|
||||
it("rejects bad slugs; a story without a series is a one-shot", () => {
|
||||
assert.equal(newEntryPath("blog", "Hello World"), null);
|
||||
assert.equal(newEntryPath("blog", "../x"), null);
|
||||
assert.equal(newEntryPath("stories", "chuong-03"), null);
|
||||
assert.equal(newEntryPath("stories", "chuong-03", "Bad Series"), null);
|
||||
assert.equal(newEntryPath("stories", "mot-dem"), "stories/mot-dem.md");
|
||||
});
|
||||
|
||||
it("only maps editable content paths to a collection", () => {
|
||||
assert.equal(collectionOf("now/now-en.md")?.id, "now");
|
||||
assert.equal(collectionOf("blog/lan-dau-viet-truyen.mdx")?.id, "blog");
|
||||
assert.equal(collectionOf("stories/dem-khong-tieng/chuong-01.md")?.id, "stories");
|
||||
assert.equal(collectionOf("stories/mot-dem.md")?.id, "stories");
|
||||
for (const path of [
|
||||
"README.md",
|
||||
"blog/../README.md",
|
||||
"gallery-photos/game.json",
|
||||
"blog/x.txt",
|
||||
".github/x.md",
|
||||
"stories/a/b/c.md",
|
||||
]) {
|
||||
assert.equal(collectionOf(path), null, path);
|
||||
}
|
||||
|
||||
+10
-4
@@ -242,18 +242,24 @@ describe("structured logs, version", () => {
|
||||
assert.deepEqual(fields, { ray: "abc", method: "GET", path: "/p" });
|
||||
});
|
||||
|
||||
it("reports the running version and build commit", () => {
|
||||
it("reports the running version, build commit and content commit", () => {
|
||||
assert.deepEqual(versionInfo(undefined), {
|
||||
id: null,
|
||||
tag: null,
|
||||
timestamp: null,
|
||||
commit: null,
|
||||
content: null,
|
||||
});
|
||||
(globalThis as { __BUILD_COMMIT__?: string }).__BUILD_COMMIT__ = "abc1234";
|
||||
const constants = globalThis as { __BUILD_COMMIT__?: string; __CONTENT_COMMIT__?: string };
|
||||
constants.__BUILD_COMMIT__ = "abc1234";
|
||||
constants.__CONTENT_COMMIT__ = "def5678";
|
||||
try {
|
||||
assert.equal(versionInfo({ CF_VERSION_METADATA: { id: "v1" } }).commit, "abc1234");
|
||||
const info = versionInfo({ CF_VERSION_METADATA: { id: "v1" } });
|
||||
assert.equal(info.commit, "abc1234");
|
||||
assert.equal(info.content, "def5678");
|
||||
} finally {
|
||||
delete (globalThis as { __BUILD_COMMIT__?: string }).__BUILD_COMMIT__;
|
||||
delete constants.__BUILD_COMMIT__;
|
||||
delete constants.__CONTENT_COMMIT__;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// Where a content change is on its way to the live site (lib/admin/publish-phase), and the
|
||||
// admin's toast after a save.
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import {
|
||||
afterSaveMessage,
|
||||
canPublish,
|
||||
PHASE_TEXT,
|
||||
publishPhase,
|
||||
type PhaseInput,
|
||||
} from "../src/lib/admin/publish-phase.ts";
|
||||
|
||||
const base: PhaseInput = {
|
||||
contentHead: "c2",
|
||||
published: "c1",
|
||||
live: "c1",
|
||||
pr: null,
|
||||
run: null,
|
||||
};
|
||||
|
||||
describe("publishPhase", () => {
|
||||
it("is live once the running build has the content head", () => {
|
||||
assert.equal(publishPhase({ ...base, published: "c2", live: "c2" }), "live");
|
||||
// Unknown build-time content commit (local dev): main's pointer stands in for it.
|
||||
assert.equal(publishPhase({ ...base, published: "c2", live: null }), "live");
|
||||
});
|
||||
|
||||
it("follows the bump PR: building, waiting for review, or failed", () => {
|
||||
const pr = (autoMerge: boolean, checks: "pending" | "success" | "failure" | null) =>
|
||||
publishPhase({ ...base, pr: { autoMerge, checks } });
|
||||
assert.equal(pr(true, "pending"), "building");
|
||||
assert.equal(pr(true, "success"), "building");
|
||||
assert.equal(pr(true, null), "building");
|
||||
assert.equal(pr(false, "success"), "review");
|
||||
assert.equal(pr(true, "failure"), "failed");
|
||||
});
|
||||
|
||||
it("is building while the workflow runs, before any PR exists", () => {
|
||||
assert.equal(
|
||||
publishPhase({ ...base, run: { status: "in_progress", conclusion: null } }),
|
||||
"building",
|
||||
);
|
||||
assert.equal(
|
||||
publishPhase({ ...base, run: { status: "queued", conclusion: null } }),
|
||||
"building",
|
||||
);
|
||||
});
|
||||
|
||||
it("is deploying when main has the content but the running build doesn't", () => {
|
||||
assert.equal(publishPhase({ ...base, published: "c2", live: "c1" }), "deploying");
|
||||
});
|
||||
|
||||
it("reports a failed last run, and plain pending changes otherwise", () => {
|
||||
assert.equal(
|
||||
publishPhase({ ...base, run: { status: "completed", conclusion: "failure" } }),
|
||||
"failed",
|
||||
);
|
||||
assert.equal(
|
||||
publishPhase({ ...base, run: { status: "completed", conclusion: "success" } }),
|
||||
"pending",
|
||||
);
|
||||
assert.equal(publishPhase(base), "pending");
|
||||
});
|
||||
|
||||
it("offers a manual publish only when nothing is moving", () => {
|
||||
assert.deepEqual((Object.keys(PHASE_TEXT) as (keyof typeof PHASE_TEXT)[]).filter(canPublish), [
|
||||
"pending",
|
||||
"failed",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("afterSaveMessage", () => {
|
||||
it("says the change is on its way, or how to publish it by hand", () => {
|
||||
const queued = afterSaveMessage("queued", "Đã lưu");
|
||||
assert.equal(queued.queued, true);
|
||||
assert.equal(queued.kind, "ok");
|
||||
assert.match(queued.text, /^Đã lưu — đang tự xuất bản/);
|
||||
for (const other of ["failed", undefined]) {
|
||||
const message = afterSaveMessage(other, "Đã xoá album");
|
||||
assert.equal(message.queued, false);
|
||||
assert.equal(message.kind, "info");
|
||||
assert.match(message.text, /^Đã xoá album, nhưng chưa tự xuất bản được/);
|
||||
}
|
||||
});
|
||||
});
|
||||
+23
-4
@@ -26,6 +26,10 @@ export class FakeGitHub {
|
||||
buildCheck: { status: string; conclusion: string | null } | null = null;
|
||||
lastRun: { status: string; conclusion: string | null } | null = null;
|
||||
readonly dispatched: string[] = [];
|
||||
/** Answer workflow dispatches with this status instead of 204 (a token without Actions). */
|
||||
failDispatch: number | null = null;
|
||||
/** The repo's files at older commits, for GraphQL reads `at` a sha (listContentFiles). */
|
||||
readonly snapshots = new Map<string, Record<string, string>>();
|
||||
/** Commits made through the API, newest first (GET …/commits). */
|
||||
readonly history: { sha: string; message: string }[] = [];
|
||||
private pendingMessage = "";
|
||||
@@ -59,7 +63,15 @@ export class FakeGitHub {
|
||||
const path = decodeURIComponent(url.pathname);
|
||||
const body = call.body ? (JSON.parse(call.body) as Record<string, unknown>) : {};
|
||||
|
||||
if (path === "/graphql") return jsonResponse({ data: this.graphqlTree() });
|
||||
if (path === "/graphql") {
|
||||
const expr = String((body.variables as { expr?: string } | undefined)?.expr ?? "main:");
|
||||
const at = expr.slice(0, -1);
|
||||
if (at === "main" || at === this.head) return jsonResponse({ data: this.graphqlTree() });
|
||||
const snapshot = this.snapshots.get(at);
|
||||
return jsonResponse({
|
||||
data: this.graphqlTree(snapshot ? new Map(Object.entries(snapshot)) : null),
|
||||
});
|
||||
}
|
||||
|
||||
if (path.startsWith(`${CONTENT}/contents/`)) {
|
||||
const file = path.slice(`${CONTENT}/contents/`.length);
|
||||
@@ -134,6 +146,9 @@ export class FakeGitHub {
|
||||
path === `${SITE}/actions/workflows/content-bump.yml/dispatches` &&
|
||||
call.method === "POST"
|
||||
) {
|
||||
if (this.failDispatch) {
|
||||
return jsonResponse({ message: "Resource not accessible" }, this.failDispatch);
|
||||
}
|
||||
this.dispatched.push(String(body.ref));
|
||||
return new Response(null, { status: 204 });
|
||||
}
|
||||
@@ -142,8 +157,12 @@ export class FakeGitHub {
|
||||
|
||||
private pendingTree: { path: string; sha?: null; content?: string }[] = [];
|
||||
|
||||
/** The GraphQL tree query's answer: collection/series/file, three levels deep. */
|
||||
private graphqlTree() {
|
||||
/**
|
||||
* The GraphQL tree query's answer: collection/series/file, three levels deep — of the
|
||||
* current files, of a snapshot, or (null) a commit the repo doesn't have: no tree at all.
|
||||
*/
|
||||
private graphqlTree(files: Map<string, string> | null = this.files) {
|
||||
if (!files) return { repository: { ref: { target: { oid: this.head } }, object: null } };
|
||||
type Node = { path: string; type: string; object: Record<string, unknown> };
|
||||
const root: Node[] = [];
|
||||
const dirs = new Map<string, Node[]>([["", root]]);
|
||||
@@ -156,7 +175,7 @@ export class FakeGitHub {
|
||||
dirs.set(dir, entries);
|
||||
return entries;
|
||||
};
|
||||
for (const [path, text] of [...this.files.entries()].sort()) {
|
||||
for (const [path, text] of [...files.entries()].sort()) {
|
||||
const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
|
||||
ensureDir(dir).push({ path, type: "blob", object: { oid: shaOf(text), text } });
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user