create-freeholder 0.2.0-beta.4 → 0.2.0-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/template/.changeset/blog-playground-content.md +4 -0
- package/dist/template/.changeset/blog-wordpress-structure.md +6 -0
- package/dist/template/.changeset/managed-preview-assistant.md +4 -0
- package/dist/template/.changeset/native-linux-install.md +6 -0
- package/dist/template/.changeset/public-beta-5.md +4 -0
- package/dist/template/.changeset/public-beta-6.md +4 -0
- package/dist/template/.github/ISSUE_TEMPLATE/bug_report.yml +1 -1
- package/dist/template/.github/workflows/release-tarballs.yml +117 -0
- package/dist/template/AGENTS.md +15 -2
- package/dist/template/Dockerfile +3 -0
- package/dist/template/MASTER.md +114 -11
- package/dist/template/README.md +1 -1
- package/dist/template/app/(admin)/admin/assistant/page.tsx +9 -1
- package/dist/template/app/(admin)/admin/blog/PostSettings.tsx +26 -0
- package/dist/template/app/(admin)/admin/blog/[kind]/page.tsx +53 -0
- package/dist/template/app/(admin)/admin/blog/actions.ts +186 -6
- package/dist/template/app/(admin)/admin/blog/comments/page.tsx +25 -0
- package/dist/template/app/(admin)/admin/blog/page.tsx +21 -5
- package/dist/template/app/(admin)/admin/imports/[id]/page.tsx +2 -0
- package/dist/template/app/(admin)/admin/pages/[id]/page.tsx +3 -0
- package/dist/template/app/(admin)/assistant-actions.ts +13 -6
- package/dist/template/app/(public)/[[...slug]]/ReaderComments.tsx +25 -0
- package/dist/template/app/(public)/[[...slug]]/blog-parts.tsx +153 -0
- package/dist/template/app/(public)/[[...slug]]/comment-actions.ts +16 -0
- package/dist/template/app/(public)/[[...slug]]/page.tsx +182 -18
- package/dist/template/app/api/chat/assistant/call/route.ts +35 -0
- package/dist/template/db/migrations/0061_blog_structure.sql +89 -0
- package/dist/template/db/migrations/0062_blog_reader_comments.sql +24 -0
- package/dist/template/db/migrations/meta/_journal.json +14 -0
- package/dist/template/deploy/README.md +26 -9
- package/dist/template/deploy/blog-wordpress-2026-11-07.md +146 -0
- package/dist/template/deploy/docker-selfhost/.env.example +11 -1
- package/dist/template/deploy/docker-selfhost/README.md +79 -50
- package/dist/template/deploy/docker-selfhost/infra/backup.sh +81 -0
- package/dist/template/deploy/docker-selfhost/infra/compose.https.yml +37 -1
- package/dist/template/deploy/docker-selfhost/infra/compose.yml +37 -1
- package/dist/template/deploy/docker-selfhost/migrate.md +8 -5
- package/dist/template/deploy/docker-selfhost/recipe.yaml +9 -10
- package/dist/template/deploy/docker-selfhost/selfhost.sh +206 -0
- package/dist/template/deploy/docker-selfhost/verify.md +11 -4
- package/dist/template/deploy/f-criteria-matrix.md +89 -0
- package/dist/template/deploy/linux/.env.example +28 -0
- package/dist/template/deploy/linux/README.md +181 -0
- package/dist/template/deploy/linux/freeholder +655 -0
- package/dist/template/deploy/linux/install.sh +173 -0
- package/dist/template/deploy/linux/migrate.md +17 -0
- package/dist/template/deploy/linux/recipe.yaml +50 -0
- package/dist/template/deploy/linux/share/Caddyfile.template +19 -0
- package/dist/template/deploy/linux/share/systemd/freeholder-backup.service +13 -0
- package/dist/template/deploy/linux/share/systemd/freeholder-backup.timer +12 -0
- package/dist/template/deploy/linux/share/systemd/freeholder.service +41 -0
- package/dist/template/deploy/linux/verify.md +22 -0
- package/dist/template/deploy/managed-preview-assistant.md +99 -0
- package/dist/template/eslint.config.mjs +3 -1
- package/dist/template/gitignore.template +1 -0
- package/dist/template/locales/ar.json +85 -6
- package/dist/template/locales/en.json +83 -4
- package/dist/template/locales/es.json +83 -4
- package/dist/template/locales/fr.json +85 -6
- package/dist/template/next.config.ts +2 -0
- package/dist/template/package.json +3 -2
- package/dist/template/packages/cli/package.json +1 -1
- package/dist/template/packages/create-freeholder/package.json +1 -1
- package/dist/template/packages/freeholder-app/package.json +1 -1
- package/dist/template/packages/mobile-app/package.json +1 -1
- package/dist/template/packages/plugin-kit/package.json +1 -1
- package/dist/template/packages/sdk/package.json +1 -1
- package/dist/template/packages/sdk/src/generated.ts +177 -9
- package/dist/template/packages/sdk/src/version.ts +1 -1
- package/dist/template/packages/templates/package.json +1 -1
- package/dist/template/proxy.ts +18 -1
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/NOTICE.txt +117 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/audio-output-processor.js +267 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/decoderWorker.min.js +847 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/decoderWorker.min.wasm +0 -0
- package/dist/template/public/managed-assistant/0.1.10/duplex-codec/encoderWorker.min.js +1 -0
- package/dist/template/public/managed-assistant/0.1.10/manifest.json +12 -0
- package/dist/template/public/managed-assistant/0.1.10/pm-ai-duplex-client.js +1376 -0
- package/dist/template/scripts/build-release.d.mts +4 -0
- package/dist/template/scripts/build-release.mjs +171 -0
- package/dist/template/scripts/launch-prepare.mjs +6 -3
- package/dist/template/scripts/license-headers.mjs +3 -0
- package/dist/template/scripts/recipe-matrix.sh +22 -7
- package/dist/template/scripts/verify-wordpress-migration.d.mts +8 -0
- package/dist/template/scripts/verify-wordpress-migration.mjs +105 -0
- package/dist/template/security/adversarial-audit-2026-10-08.md +1 -1
- package/dist/template/src/adapters/ai/types.ts +5 -0
- package/dist/template/src/adapters/paradise/assistant.ts +37 -0
- package/dist/template/src/adapters/paradise/http.ts +4 -3
- package/dist/template/src/adapters/storage/local-mode.ts +54 -0
- package/dist/template/src/adapters/storage/local.ts +53 -26
- package/dist/template/src/core/contract/json-schema.ts +8 -0
- package/dist/template/src/core/demo/playground-inserts.ts +29 -0
- package/dist/template/src/core/demo/playground-policy.ts +9 -0
- package/dist/template/src/core/doctor/index.ts +19 -10
- package/dist/template/src/core/env.ts +8 -1
- package/dist/template/src/core/http/csp.ts +10 -2
- package/dist/template/src/core/http/csrf-client.ts +10 -0
- package/dist/template/src/core/import/service.ts +217 -12
- package/dist/template/src/core/import/wordpress.ts +80 -15
- package/dist/template/src/core/notifications/service.ts +1 -0
- package/dist/template/src/core/retention/registry.ts +2 -0
- package/dist/template/src/core/search/registry.ts +2 -0
- package/dist/template/src/core/seo/feeds.ts +2 -0
- package/dist/template/src/core/seo/jsonld.ts +46 -2
- package/dist/template/src/core/seo/legacy-proxy.ts +53 -0
- package/dist/template/src/core/seo/meta.ts +10 -7
- package/dist/template/src/core/seo/service.ts +14 -1
- package/dist/template/src/core/update/preflight.ts +3 -2
- package/dist/template/src/core/update/release-declaration.json +1 -1
- package/dist/template/src/core/update/service.ts +7 -17
- package/dist/template/src/modules/assistant/contract.ts +1 -1
- package/dist/template/src/modules/assistant/limits.ts +3 -0
- package/dist/template/src/modules/assistant/preview.ts +124 -0
- package/dist/template/src/modules/assistant/provider.ts +7 -0
- package/dist/template/src/modules/assistant/service.ts +21 -5
- package/dist/template/src/modules/cms/blocks/PreviewAssistantCall.tsx +176 -0
- package/dist/template/src/modules/cms/blocks/SiteChatClient.tsx +10 -4
- package/dist/template/src/modules/cms/blocks/surfaces.tsx +10 -0
- package/dist/template/src/modules/cms/blog-comments-schema.ts +27 -0
- package/dist/template/src/modules/cms/blog-comments.ts +111 -0
- package/dist/template/src/modules/cms/blog-schema.ts +146 -0
- package/dist/template/src/modules/cms/blog-service.ts +999 -0
- package/dist/template/src/modules/cms/blog.tsx +245 -25
- package/dist/template/src/modules/cms/manifest.ts +7 -1
- package/dist/template/src/modules/cms/read.ts +18 -0
- package/dist/template/src/modules/cms/service.ts +22 -4
- package/dist/template/src/modules/cms/tables.ts +2 -0
- package/dist/template/src/modules/seed/launch.ts +31 -3
- package/dist/template/tests/browser/blog-structure.spec.ts +69 -0
- package/dist/template/tests/core/agent-launch.test.ts +7 -2
- package/dist/template/tests/core/analytics-consent.test.ts +1 -1
- package/dist/template/tests/core/blog-playground.test.ts +106 -0
- package/dist/template/tests/core/blog-structure-comments.test.ts +166 -0
- package/dist/template/tests/core/client-readiness-security.test.ts +3 -1
- package/dist/template/tests/core/csp.test.ts +1 -1
- package/dist/template/tests/core/deploy-recipe.test.ts +54 -4
- package/dist/template/tests/core/internal-services.test.ts +4 -0
- package/dist/template/tests/core/legacy-redirect-proxy.test.ts +59 -0
- package/dist/template/tests/core/linux-install.test.ts +169 -0
- package/dist/template/tests/core/local-storage-mode.test.ts +29 -0
- package/dist/template/tests/core/locale-routing.test.ts +1 -1
- package/dist/template/tests/core/playground-cache.test.ts +1 -1
- package/dist/template/tests/core/playground.test.ts +3 -3
- package/dist/template/tests/core/preview-assistant-call.test.ts +88 -0
- package/dist/template/tests/core/private-preview-webhooks.test.ts +1 -1
- package/dist/template/tests/core/private-preview.test.ts +1 -1
- package/dist/template/tests/core/proxy-locale.test.ts +1 -1
- package/dist/template/tests/core/sdk-schema.test.ts +20 -0
- package/dist/template/tests/core/seo.test.ts +1 -1
- package/dist/template/tests/core/site-chat-client.test.ts +50 -0
- package/dist/template/tests/core/storage.test.ts +38 -2
- package/dist/template/tests/core/wordpress-import-flow.test.ts +81 -18
- package/dist/template/tests/core/wordpress-import.test.ts +25 -12
- package/dist/template/tests/core/wordpress-migration-verification.test.ts +37 -0
- package/dist/template/tests/modules/preview-assistant.test.ts +164 -0
- package/dist/template-manifest.json +490 -175
- package/package.json +1 -1
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// Copyright (C) 2026 Tony Aly
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"use client";
|
|
4
|
+
|
|
5
|
+
import { browserCsrfHeaders } from "@/core/http/csrf-client";
|
|
6
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
7
|
+
|
|
8
|
+
interface Config { enabled: boolean; modes: string[]; label: string; disclosure: string }
|
|
9
|
+
interface Session {
|
|
10
|
+
status: string; session_id?: string; mode?: "voice" | "video"; max_seconds?: number;
|
|
11
|
+
hard_until_ms?: number; call?: { duplex?: { session_id: string }; ice_servers?: RTCIceServer[] };
|
|
12
|
+
disclosure?: string; retry_after_ms?: number; queue_position?: number;
|
|
13
|
+
ready?: boolean;
|
|
14
|
+
}
|
|
15
|
+
interface Handle { stop(): void; isReady(): boolean; failed(): boolean }
|
|
16
|
+
export interface PreviewAssistantLabels {
|
|
17
|
+
label: string; captions: string; video: string; voice: string; leave: string; end: string;
|
|
18
|
+
waiting: string; unavailable: string; connecting: string; captionFailed: string;
|
|
19
|
+
ended: string; lost: string; microphone: string;
|
|
20
|
+
voiceFallback: string;
|
|
21
|
+
}
|
|
22
|
+
type SharedTransport = {
|
|
23
|
+
startDuplexCall(started: unknown, transcript: (text: string) => void, deps: {
|
|
24
|
+
audioContext(): AudioContext | undefined; microphone(): Promise<MediaStream | undefined>;
|
|
25
|
+
codecBase: string; endSession(): Promise<void>; signal: AbortSignal;
|
|
26
|
+
videoElement: HTMLVideoElement | null; report(): void;
|
|
27
|
+
}, hooks?: { onTranscriptSegment(segment: { speaker: "member" | "muse"; text: string; startedAt: number; endedAt: number; final: boolean }): void }): Promise<Handle | undefined>;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** The cookie stays httpOnly; the browser supplies only bounded call choices. */
|
|
31
|
+
async function control(body: Record<string, unknown>, keepalive = false): Promise<Session & Partial<Config>> {
|
|
32
|
+
const response = await fetch("/api/chat/assistant/call", {
|
|
33
|
+
method: "POST", cache: "no-store", keepalive,
|
|
34
|
+
headers: { "content-type": "application/json", ...browserCsrfHeaders() },
|
|
35
|
+
body: JSON.stringify(body),
|
|
36
|
+
});
|
|
37
|
+
if (!response.ok) throw new Error("The assistant could not connect. You can still send a message.");
|
|
38
|
+
return response.json() as Promise<Session & Partial<Config>>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Voice/video is an extension of the existing site chat, with shared PM media. */
|
|
42
|
+
export function PreviewAssistantCall({ ended, labels }: { ended: boolean; labels: PreviewAssistantLabels }) {
|
|
43
|
+
const [config, setConfig] = useState<Config | null>(null);
|
|
44
|
+
const [state, setState] = useState("idle");
|
|
45
|
+
const [notice, setNotice] = useState("");
|
|
46
|
+
const [caption, setCaption] = useState("");
|
|
47
|
+
const [mode, setMode] = useState<"voice" | "video" | null>(null);
|
|
48
|
+
const video = useRef<HTMLVideoElement>(null);
|
|
49
|
+
const live = useRef<{ id?: string; handle?: Handle; audio?: AudioContext; mic?: MediaStream; controller?: AbortController; timer?: ReturnType<typeof setInterval>; until?: number; want?: "voice" | "video" }>({});
|
|
50
|
+
|
|
51
|
+
const stop = useCallback(async (unmount = false) => {
|
|
52
|
+
const current = live.current;
|
|
53
|
+
live.current = {};
|
|
54
|
+
current.controller?.abort();
|
|
55
|
+
if (current.timer) clearInterval(current.timer);
|
|
56
|
+
current.handle?.stop();
|
|
57
|
+
current.mic?.getTracks().forEach(track => track.stop());
|
|
58
|
+
if (!unmount) { setState("idle"); setCaption(""); setMode(null); }
|
|
59
|
+
await current.audio?.close().catch(() => undefined);
|
|
60
|
+
if (current.id) await control({ action: "end", sessionId: current.id }, unmount).catch(() => undefined);
|
|
61
|
+
}, []);
|
|
62
|
+
|
|
63
|
+
useEffect(() => {
|
|
64
|
+
let active = true;
|
|
65
|
+
void control({ action: "config" }).then(value => {
|
|
66
|
+
if (active && value.enabled && Array.isArray(value.modes)) setConfig(value as unknown as Config);
|
|
67
|
+
}).catch(() => undefined);
|
|
68
|
+
return () => { active = false; void stop(true); };
|
|
69
|
+
}, [stop]);
|
|
70
|
+
useEffect(() => { if (ended) void stop(); }, [ended, stop]);
|
|
71
|
+
|
|
72
|
+
async function finish(current: typeof live.current, message: string) {
|
|
73
|
+
if (live.current !== current) return;
|
|
74
|
+
await stop();
|
|
75
|
+
if (!live.current.controller) setNotice(message);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function attach(result: Session, current: typeof live.current) {
|
|
79
|
+
if (live.current !== current || current.controller?.signal.aborted || !current.controller) {
|
|
80
|
+
if (result.session_id) await control({ action: "end", sessionId: result.session_id }).catch(() => undefined);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (result.session_id) current.id = result.session_id;
|
|
84
|
+
if (result.status === "queued") {
|
|
85
|
+
setState("queued"); setNotice(labels.waiting);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (result.status !== "live" || !result.call?.duplex || !current.id) {
|
|
89
|
+
await finish(current, labels.unavailable);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
current.until = result.hard_until_ms;
|
|
93
|
+
setMode(result.mode ?? null);
|
|
94
|
+
setState("connecting"); setNotice(current.want === "video" && result.mode === "voice" ? labels.voiceFallback : result.disclosure ?? config?.disclosure ?? labels.connecting);
|
|
95
|
+
// This is a byte-pinned local distribution of the shared transport, not
|
|
96
|
+
// another browser call implementation. Its codecs stay on this origin.
|
|
97
|
+
const moduleUrl = "/managed-assistant/0.1.10/pm-ai-duplex-client.js";
|
|
98
|
+
const sdk = await import(/* webpackIgnore: true */ moduleUrl) as SharedTransport;
|
|
99
|
+
if (live.current !== current || current.controller.signal.aborted) return;
|
|
100
|
+
const handle = await sdk.startDuplexCall({
|
|
101
|
+
sessionId: result.call.duplex.session_id, callKind: result.mode, stack: "ditto-duplex",
|
|
102
|
+
maxSeconds: result.max_seconds, duplex: result.call.duplex, iceServers: result.call.ice_servers,
|
|
103
|
+
}, text => { if (live.current === current) setCaption(text); }, {
|
|
104
|
+
audioContext: () => current.audio, microphone: async () => current.mic,
|
|
105
|
+
codecBase: "/managed-assistant/0.1.10/duplex-codec/", signal: current.controller.signal,
|
|
106
|
+
videoElement: video.current, report: () => undefined,
|
|
107
|
+
endSession: async () => { if (live.current === current) await stop(); },
|
|
108
|
+
}, { onTranscriptSegment: segment => {
|
|
109
|
+
if (live.current !== current || !segment.final || !current.id) return;
|
|
110
|
+
const { speaker, text, startedAt, endedAt } = segment;
|
|
111
|
+
void control({ action: "caption", sessionId: current.id, caption: { speaker, text, startedAt, endedAt } }).catch(() => {
|
|
112
|
+
if (live.current === current) setNotice(labels.captionFailed);
|
|
113
|
+
});
|
|
114
|
+
} });
|
|
115
|
+
if (live.current !== current || current.controller.signal.aborted) { handle?.stop(); return; }
|
|
116
|
+
if (!handle) {
|
|
117
|
+
await finish(current, labels.unavailable);
|
|
118
|
+
} else current.handle = handle;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function start(want: "voice" | "video") {
|
|
122
|
+
await stop();
|
|
123
|
+
const current = { controller: new AbortController(), want } as typeof live.current;
|
|
124
|
+
live.current = current;
|
|
125
|
+
setMode(want);
|
|
126
|
+
setState("connecting"); setNotice(labels.connecting);
|
|
127
|
+
try {
|
|
128
|
+
// Unlock audio in the person's click, before a network round trip.
|
|
129
|
+
current.audio = new AudioContext();
|
|
130
|
+
await current.audio.resume();
|
|
131
|
+
current.mic = await navigator.mediaDevices.getUserMedia({ audio: true });
|
|
132
|
+
if (current.controller!.signal.aborted) { current.mic.getTracks().forEach(track => track.stop()); return; }
|
|
133
|
+
await attach(await control({ action: "start", want }), current);
|
|
134
|
+
if (live.current !== current || !current.id) return;
|
|
135
|
+
let ticking = false;
|
|
136
|
+
current.timer = setInterval(() => {
|
|
137
|
+
if (ticking) return;
|
|
138
|
+
if (live.current !== current) return;
|
|
139
|
+
ticking = true;
|
|
140
|
+
void (async () => {
|
|
141
|
+
if (current.until && Date.now() >= current.until || current.handle?.failed()) {
|
|
142
|
+
await finish(current, labels.ended); return;
|
|
143
|
+
}
|
|
144
|
+
if (current.handle) {
|
|
145
|
+
if (current.handle.isReady()) setState("live");
|
|
146
|
+
await control({ action: "lease", sessionId: current.id, authorizedUntilMs: Math.min(Date.now() + 20000, current.until ?? 0) });
|
|
147
|
+
} else {
|
|
148
|
+
const status = await control({ action: "poll", sessionId: current.id });
|
|
149
|
+
if (live.current !== current) return;
|
|
150
|
+
if (status.status === "queued" && status.ready) await attach(await control({ action: "queued", sessionId: current.id, want }), current);
|
|
151
|
+
else if (status.status !== "queued") await finish(current, labels.ended);
|
|
152
|
+
}
|
|
153
|
+
})().catch(async () => { await finish(current, labels.lost); })
|
|
154
|
+
.finally(() => { ticking = false; });
|
|
155
|
+
}, 5000);
|
|
156
|
+
} catch {
|
|
157
|
+
await finish(current, labels.microphone);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (!config || ended) return null;
|
|
162
|
+
return <section aria-label={labels.label} className="grid gap-2 rounded-md border border-rule p-3">
|
|
163
|
+
<p className="text-sm font-semibold">{config.label}</p>
|
|
164
|
+
<p className="text-xs text-ink-muted">{config.disclosure}</p>
|
|
165
|
+
<p className="text-xs text-ink-muted">{labels.captions}</p>
|
|
166
|
+
<video ref={video} autoPlay playsInline muted className={mode !== "video" || state === "idle" || state === "queued" ? "hidden" : "max-h-72 w-full rounded-md bg-ink"} />
|
|
167
|
+
<div className="flex flex-wrap gap-3">
|
|
168
|
+
{state === "idle" ? <>
|
|
169
|
+
{config.modes.includes("video") && <button type="button" onClick={() => void start("video")} className="underline">{labels.video}</button>}
|
|
170
|
+
{config.modes.includes("voice") && <button type="button" onClick={() => void start("voice")} className="underline">{labels.voice}</button>}
|
|
171
|
+
</> : <button type="button" onClick={() => void stop()} className="underline">{state === "queued" ? labels.leave : labels.end}</button>}
|
|
172
|
+
</div>
|
|
173
|
+
{notice && <p role="status" className="text-sm">{notice}</p>}
|
|
174
|
+
{caption && <p aria-live="polite" className="text-sm">{caption}</p>}
|
|
175
|
+
</section>;
|
|
176
|
+
}
|
|
@@ -2,8 +2,11 @@
|
|
|
2
2
|
// SPDX-License-Identifier: Apache-2.0
|
|
3
3
|
"use client";
|
|
4
4
|
|
|
5
|
+
import { browserCsrfHeaders } from "@/core/http/csrf-client";
|
|
6
|
+
import { isPreviewAssistantContactPath } from "@/core/http/csp";
|
|
5
7
|
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
|
6
8
|
import { postSiteChatAction } from "../../../../app/(public)/inbound-actions";
|
|
9
|
+
import { PreviewAssistantCall, type PreviewAssistantLabels } from "./PreviewAssistantCall";
|
|
7
10
|
|
|
8
11
|
interface ChatMessage {
|
|
9
12
|
id: string;
|
|
@@ -21,6 +24,7 @@ interface Transcript {
|
|
|
21
24
|
}
|
|
22
25
|
|
|
23
26
|
interface Labels {
|
|
27
|
+
call: PreviewAssistantLabels;
|
|
24
28
|
loading: string;
|
|
25
29
|
ended: string;
|
|
26
30
|
escalated: string;
|
|
@@ -45,7 +49,8 @@ function errorMessage(value: unknown, fallback: string): string {
|
|
|
45
49
|
return fallback;
|
|
46
50
|
}
|
|
47
51
|
|
|
48
|
-
export function SiteChatClient({ locale, labels }: { locale: string; labels: Labels }) {
|
|
52
|
+
export function SiteChatClient({ locale, labels, path }: { locale: string; labels: Labels; path: string }) {
|
|
53
|
+
const assistantCallSurface = isPreviewAssistantContactPath(path);
|
|
49
54
|
const [chat, setChat] = useState<Transcript | null>(null);
|
|
50
55
|
const [ended, setEnded] = useState(false);
|
|
51
56
|
const [busy, setBusy] = useState(false);
|
|
@@ -91,7 +96,7 @@ export function SiteChatClient({ locale, labels }: { locale: string; labels: Lab
|
|
|
91
96
|
*/
|
|
92
97
|
const askAssistant = useCallback(async () => {
|
|
93
98
|
try {
|
|
94
|
-
const response = await fetch("/api/chat/assistant", { method: "POST" });
|
|
99
|
+
const response = await fetch("/api/chat/assistant", { method: "POST", headers: browserCsrfHeaders() });
|
|
95
100
|
if (!response.ok) return;
|
|
96
101
|
const body: unknown = await response.json().catch(() => ({}));
|
|
97
102
|
if ((body as { status?: string }).status === "answered") await refresh();
|
|
@@ -115,7 +120,7 @@ export function SiteChatClient({ locale, labels }: { locale: string; labels: Lab
|
|
|
115
120
|
try {
|
|
116
121
|
const response = await fetch("/api/chat", {
|
|
117
122
|
method: "POST",
|
|
118
|
-
headers: { "content-type": "application/json" },
|
|
123
|
+
headers: { "content-type": "application/json", ...browserCsrfHeaders() },
|
|
119
124
|
body: JSON.stringify({ message }),
|
|
120
125
|
});
|
|
121
126
|
const body: unknown = await response.json().catch(() => ({}));
|
|
@@ -136,7 +141,7 @@ export function SiteChatClient({ locale, labels }: { locale: string; labels: Lab
|
|
|
136
141
|
async function end() {
|
|
137
142
|
setBusy(true);
|
|
138
143
|
try {
|
|
139
|
-
const response = await fetch("/api/chat", { method: "DELETE" });
|
|
144
|
+
const response = await fetch("/api/chat", { method: "DELETE", headers: browserCsrfHeaders() });
|
|
140
145
|
if (!response.ok) {
|
|
141
146
|
const body: unknown = await response.json().catch(() => ({}));
|
|
142
147
|
setError(errorMessage(body, labels.failed));
|
|
@@ -157,6 +162,7 @@ export function SiteChatClient({ locale, labels }: { locale: string; labels: Lab
|
|
|
157
162
|
|
|
158
163
|
return (
|
|
159
164
|
<section aria-label={labels.message} className="grid max-w-xl gap-4 border-s-4 border-accent ps-4">
|
|
165
|
+
{assistantCallSurface ? <PreviewAssistantCall ended={ended || chat?.state === "closed"} labels={labels.call} /> : null}
|
|
160
166
|
{chat?.escalated ? (
|
|
161
167
|
<p role="status" className="rounded-md bg-warning-soft px-3 py-2 text-sm text-warning">
|
|
162
168
|
{labels.escalated}
|
|
@@ -864,8 +864,18 @@ export const siteChat = defineBlock({
|
|
|
864
864
|
return (
|
|
865
865
|
<div className="grid gap-4">
|
|
866
866
|
<SiteChatClient
|
|
867
|
+
path={ctx.path}
|
|
867
868
|
locale={ctx.locale}
|
|
868
869
|
labels={{
|
|
870
|
+
call: {
|
|
871
|
+
label: ctx.t("assistant.call.label"), captions: ctx.t("assistant.call.captions"),
|
|
872
|
+
video: ctx.t("assistant.call.video"), voice: ctx.t("assistant.call.voice"),
|
|
873
|
+
leave: ctx.t("assistant.call.leave"), end: ctx.t("assistant.call.end"),
|
|
874
|
+
waiting: ctx.t("assistant.call.waiting"), unavailable: ctx.t("assistant.call.unavailable"),
|
|
875
|
+
connecting: ctx.t("assistant.call.connecting"), captionFailed: ctx.t("assistant.call.captionFailed"),
|
|
876
|
+
ended: ctx.t("assistant.call.ended"), lost: ctx.t("assistant.call.lost"), microphone: ctx.t("assistant.call.microphone"),
|
|
877
|
+
voiceFallback: ctx.t("assistant.call.voiceFallback"),
|
|
878
|
+
},
|
|
869
879
|
loading: ctx.t("cms.chat.loading"),
|
|
870
880
|
ended: ctx.t("cms.chat.ended"),
|
|
871
881
|
escalated: ctx.t("cms.chat.escalated"),
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Copyright (C) 2026 Tony Aly
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
// Public reader comments are separate from private editorial annotations (C2.29).
|
|
4
|
+
import { sql } from "drizzle-orm";
|
|
5
|
+
import { check, index, pgTable, text, uniqueIndex, uuid, type AnyPgColumn } from "drizzle-orm/pg-core";
|
|
6
|
+
import { createdAtColumn, updatedAtColumn } from "@/core/db/columns";
|
|
7
|
+
import { contacts } from "@/core/contacts/schema";
|
|
8
|
+
import { pages } from "./schema";
|
|
9
|
+
export const blogReaderComments = pgTable("blog_reader_comments", {
|
|
10
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
11
|
+
// Changing a page's kind hides its thread, without deleting rollback history.
|
|
12
|
+
pageId: uuid("page_id").notNull().references(() => pages.id, { onDelete: "cascade" }),
|
|
13
|
+
parentId: uuid("parent_id").references((): AnyPgColumn => blogReaderComments.id, { onDelete: "set null" }),
|
|
14
|
+
contactId: uuid("contact_id").references(() => contacts.id, { onDelete: "set null" }),
|
|
15
|
+
authorName: text("author_name").notNull(),
|
|
16
|
+
body: text("body").notNull(),
|
|
17
|
+
status: text("status", { enum: ["pending", "approved", "spam", "trash"] }).notNull().default("pending"),
|
|
18
|
+
source: text("source").notNull().default("reader"),
|
|
19
|
+
externalId: text("external_id"),
|
|
20
|
+
createdAt: createdAtColumn(),
|
|
21
|
+
updatedAt: updatedAtColumn(),
|
|
22
|
+
}, t => [
|
|
23
|
+
check("blog_reader_comments_status_allowed", sql`${t.status} in ('pending','approved','spam','trash')`),
|
|
24
|
+
index("blog_reader_comments_page_status_idx").on(t.pageId, t.status, t.createdAt),
|
|
25
|
+
index("blog_reader_comments_contact_idx").on(t.contactId),
|
|
26
|
+
uniqueIndex("blog_reader_comments_source_external_idx").on(t.source, t.externalId).where(sql`${t.externalId} is not null`),
|
|
27
|
+
]);
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Copyright (C) 2026 Tony Aly
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import { and, asc, desc, eq, inArray, isNull } from "drizzle-orm";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { listed, row, timestamp, uuid } from "@/core/contract";
|
|
7
|
+
import { defineService, getService, ServiceError } from "@/core/service";
|
|
8
|
+
import { resolveContact, registerContactReference } from "@/core/contacts/service";
|
|
9
|
+
import { registerContactPrivacySource } from "@/core/privacy/service";
|
|
10
|
+
import { users } from "@/core/auth/schema";
|
|
11
|
+
import { pages } from "./schema";
|
|
12
|
+
import { blogPosts } from "./blog-schema";
|
|
13
|
+
import { blogReaderComments as comments } from "./blog-comments-schema";
|
|
14
|
+
import { isPublicPage, loadBlogSettings } from "./blog-service";
|
|
15
|
+
|
|
16
|
+
const state = z.enum(["pending", "approved", "spam", "trash"]);
|
|
17
|
+
const privateRow = row({ id: uuid, pageId: uuid, parentId: uuid.nullable(), contactId: uuid.nullable(), authorName: z.string(), body: z.string(), status: state, source: z.string(), externalId: z.string().nullable(), createdAt: timestamp, updatedAt: timestamp });
|
|
18
|
+
const publicRow = z.object({ id: uuid, parentId: uuid.nullable(), authorName: z.string(), body: z.string(), createdAt: timestamp });
|
|
19
|
+
|
|
20
|
+
registerContactReference({
|
|
21
|
+
table: "blog_reader_comments",
|
|
22
|
+
repoint: (tx, duplicateId, survivingId) => tx.update(comments).set({ contactId: survivingId }).where(eq(comments.contactId, duplicateId)),
|
|
23
|
+
captureForUndo: async (tx, duplicateId, survivingId) => ({ state: await tx.select({ id: comments.id, contactId: comments.contactId }).from(comments).where(inArray(comments.contactId, [duplicateId, survivingId])).orderBy(asc(comments.id)), undoable: true }),
|
|
24
|
+
restoreAfterUndo: async (tx, beforeState, afterState, duplicateId) => {
|
|
25
|
+
const pointers = z.array(z.object({ id: uuid, contactId: uuid.nullable() }));
|
|
26
|
+
const before = pointers.parse(beforeState), after = pointers.parse(afterState);
|
|
27
|
+
const current = after.length ? await tx.select({ id: comments.id, contactId: comments.contactId }).from(comments).where(inArray(comments.id, after.map(one => one.id))).orderBy(asc(comments.id)) : [];
|
|
28
|
+
if (JSON.stringify(current) !== JSON.stringify(after)) throw new ServiceError("conflict", "Reader comments changed after the contact merge.");
|
|
29
|
+
const ids = before.filter(one => one.contactId === duplicateId).map(one => one.id);
|
|
30
|
+
if (ids.length) await tx.update(comments).set({ contactId: duplicateId }).where(inArray(comments.id, ids));
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
registerContactPrivacySource({
|
|
34
|
+
scope: "cms.readerComments", tables: ["blog_reader_comments"],
|
|
35
|
+
exportData: (tx, contactId) => tx.select().from(comments).where(eq(comments.contactId, contactId)),
|
|
36
|
+
erase: async (tx, contactId) => ({ affected: (await tx.delete(comments).where(eq(comments.contactId, contactId)).returning({ id: comments.id })).length }),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
export const listReaderComments = defineService({
|
|
40
|
+
name: "cms.listReaderComments", summary: "Approved public reader comments on a published blog post; private contact details are never returned.",
|
|
41
|
+
kind: "query", permission: "public", input: z.object({ pageId: uuid, limit: z.number().int().min(1).max(100).default(100), page: z.number().int().min(1).max(10000).default(1) }), output: listed(publicRow),
|
|
42
|
+
handler: async (input, ctx) => {
|
|
43
|
+
const [page] = await ctx.tx.select({ id: pages.id, slug: pages.slug }).from(pages).innerJoin(blogPosts, eq(blogPosts.pageId, pages.id)).where(and(eq(pages.id, input.pageId), eq(pages.status, "published"), isNull(pages.trashedAt))).limit(1);
|
|
44
|
+
if (!page || !await isPublicPage(ctx, page)) return [];
|
|
45
|
+
return ctx.tx.select({ id: comments.id, parentId: comments.parentId, authorName: comments.authorName, body: comments.body, createdAt: comments.createdAt }).from(comments).where(and(eq(comments.pageId, page.id), eq(comments.status, "approved"))).orderBy(asc(comments.createdAt), asc(comments.id)).limit(input.limit).offset((input.page - 1) * input.limit);
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
export const submitReaderComment = defineService({
|
|
50
|
+
name: "cms.submitReaderComment", summary: "Submit a reader comment for moderation; this never publishes immediately or subscribes the contact to marketing.",
|
|
51
|
+
kind: "mutation", permission: "public", writeClass: "message",
|
|
52
|
+
input: z.object({ pageId: uuid, parentId: uuid.nullable().optional(), name: z.string().trim().min(1).max(200), email: z.string().trim().toLowerCase().email().max(320), body: z.string().trim().min(1).max(10000), website: z.string().max(200).default("") }),
|
|
53
|
+
rateLimit: { limit: 5, windowSeconds: 3600, subject: input => createHash("sha256").update(input.email+":"+input.pageId).digest("hex"), message: "Please wait before submitting another comment." },
|
|
54
|
+
output: z.object({ ok: z.literal(true), id: uuid }),
|
|
55
|
+
handler: async (input, ctx) => {
|
|
56
|
+
if (input.website) return { ok: true as const, id: randomUUID() };
|
|
57
|
+
const settings = await loadBlogSettings(ctx.tx);
|
|
58
|
+
const [post] = await ctx.tx.select({ id: pages.id, slug: pages.slug, title: pages.title, enabled: blogPosts.commentsEnabled }).from(pages).innerJoin(blogPosts, eq(blogPosts.pageId, pages.id)).where(and(eq(pages.id, input.pageId), eq(pages.status, "published"), isNull(pages.trashedAt))).limit(1);
|
|
59
|
+
if (!post || !settings.commentsEnabled || !post.enabled || !await isPublicPage(ctx, post)) throw new ServiceError("validation", "Comments are closed on this post.");
|
|
60
|
+
if (input.parentId) {
|
|
61
|
+
const [parent] = await ctx.tx.select({ id: comments.id }).from(comments).where(and(eq(comments.id, input.parentId), eq(comments.pageId, post.id), eq(comments.status, "approved"))).limit(1);
|
|
62
|
+
if (!parent) throw new ServiceError("validation", "That comment cannot be replied to.");
|
|
63
|
+
}
|
|
64
|
+
const resolved = await ctx.callAsSystem(resolveContact, { name: input.name, email: input.email, source: "blog-comment" });
|
|
65
|
+
const [saved] = await ctx.tx.insert(comments).values({ pageId: post.id, parentId: input.parentId ?? null, contactId: resolved.contact.id, authorName: input.name, body: input.body }).returning({ id: comments.id });
|
|
66
|
+
ctx.setSubject("blog_comment", saved!.id);
|
|
67
|
+
ctx.queueEvent("cms.readerCommentSubmitted", { pageId: post.id, commentId: saved!.id, contactId: resolved.contact.id });
|
|
68
|
+
const owners = await ctx.tx.select({ id: users.id }).from(users).where(eq(users.role, "owner"));
|
|
69
|
+
for (const owner of owners) await ctx.callAsSystem(getService("notifications.create"), { recipient: { kind: "user", id: owner.id }, topic: "cms.comment_pending", titleKey: "blog.commentNotificationTitle", bodyKey: "blog.commentNotificationBody", messageParams: { title: post.title }, href: "/admin/blog/comments", idempotencyKey: `reader-comment:${saved!.id}:${owner.id}` });
|
|
70
|
+
return { ok: true as const, id: saved!.id };
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
export const moderateReaderComment = defineService({
|
|
75
|
+
name: "cms.moderateReaderComment", summary: "Approve, hold, mark spam or trash a reader comment, keeping the moderation record.",
|
|
76
|
+
kind: "mutation", permission: "scoped", writeClass: "message", input: z.object({ id: uuid, status: state }), output: privateRow,
|
|
77
|
+
handler: async (input, ctx) => {
|
|
78
|
+
const [saved] = await ctx.tx.update(comments).set({ status: input.status, updatedAt: new Date() }).where(eq(comments.id, input.id)).returning();
|
|
79
|
+
if (!saved) throw new ServiceError("not_found", "That comment is gone.");
|
|
80
|
+
ctx.setSubject("blog_comment", saved.id); ctx.queueEvent("cms.readerCommentModerated", { commentId: saved.id, pageId: saved.pageId, status: saved.status }); return saved;
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
export const listReaderCommentsForOwner = defineService({
|
|
84
|
+
name: "cms.readerCommentsForOwner", summary: "Moderation queue for public blog comments, including held, spam and trashed records.",
|
|
85
|
+
kind: "query", permission: "scoped", input: z.object({ status: state.optional(), limit: z.number().int().min(1).max(200).default(100), page: z.number().int().min(1).max(10000).default(1) }), output: listed(privateRow),
|
|
86
|
+
handler: (input, ctx) => ctx.tx.select().from(comments).where(input.status ? eq(comments.status, input.status) : undefined).orderBy(desc(comments.createdAt), desc(comments.id)).limit(input.limit).offset((input.page - 1) * input.limit),
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
export const importReaderComment = defineService({
|
|
90
|
+
name: "cms.importReaderComment", summary: "Import one WordPress reader comment idempotently, preserving its date and moderation state.",
|
|
91
|
+
kind: "mutation", permission: "scoped", writeClass: "message",
|
|
92
|
+
input: z.object({ runId: uuid, externalId: z.string().min(1).max(200), pageId: uuid, parentId: uuid.nullable().optional(), name: z.string().min(1).max(200), email: z.string().email().nullable(), body: z.string().min(1).max(10000), status: state, createdAt: z.iso.datetime({ offset: true }).optional() }), output: privateRow,
|
|
93
|
+
handler: async (input, ctx) => {
|
|
94
|
+
const source = `import:${input.runId}`;
|
|
95
|
+
const [prior] = await ctx.tx.select().from(comments).where(and(eq(comments.source, source), eq(comments.externalId, input.externalId))).limit(1);
|
|
96
|
+
if (prior) return prior;
|
|
97
|
+
const resolved = input.email ? await ctx.callAsSystem(resolveContact, { name: input.name, email: input.email, source: "wordpress-comment" }) : null;
|
|
98
|
+
if (input.parentId) {
|
|
99
|
+
const [parent] = await ctx.tx.select({ id: comments.id }).from(comments).where(and(eq(comments.id, input.parentId), eq(comments.pageId, input.pageId))).limit(1);
|
|
100
|
+
if (!parent) throw new ServiceError("validation", "The imported parent comment belongs to another post.");
|
|
101
|
+
}
|
|
102
|
+
const [saved] = await ctx.tx.insert(comments).values({ source, externalId: input.externalId, pageId: input.pageId, parentId: input.parentId ?? null, authorName: input.name, body: input.body, status: input.status, contactId: resolved?.contact.id ?? null, ...(input.createdAt ? { createdAt: new Date(input.createdAt) } : {}) }).returning();
|
|
103
|
+
ctx.setSubject("blog_comment", saved!.id); return saved!;
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
export const rollbackImportedReaderComments = defineService({
|
|
107
|
+
name: "cms.rollbackImportedReaderComments", summary: "Remove only the reader comments created by one rolled-back import; unified contacts are retained.",
|
|
108
|
+
kind: "mutation", permission: "scoped", writeClass: "destructive", input: z.object({ runId: uuid }), output: z.object({ removed: z.number().int() }),
|
|
109
|
+
handler: async (input, ctx) => ({ removed: (await ctx.tx.delete(comments).where(eq(comments.source, `import:${input.runId}`)).returning({ id: comments.id })).length }),
|
|
110
|
+
});
|
|
111
|
+
export default [listReaderComments, submitReaderComment, moderateReaderComment, listReaderCommentsForOwner, importReaderComment, rollbackImportedReaderComments];
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// Copyright (C) 2026 Tony Aly
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
// Blog structure: posts, categories, tags and authors (C2.27, C2.28).
|
|
4
|
+
//
|
|
5
|
+
// A post is still an ordinary CMS page — block tree, revisions, working copy,
|
|
6
|
+
// approval, publish — and `blog_posts` is the row that says "this page is a
|
|
7
|
+
// post", so a post can live at any path (an imported WordPress permalink keeps
|
|
8
|
+
// its exact address) instead of only under `blog/`. Everything a post has that
|
|
9
|
+
// a page does not hangs off that row: its author, its categories and tags, and
|
|
10
|
+
// whether it takes comments.
|
|
11
|
+
//
|
|
12
|
+
// Category, tag and author archives are not pages. They are resolved by path
|
|
13
|
+
// at request time from these rows, listed in the sitemap only while they have
|
|
14
|
+
// a published post, and carry their own SEO fields. An archive with nothing in
|
|
15
|
+
// it is a thin page; one that appears the moment its first post is published
|
|
16
|
+
// needs no owner to remember to make it.
|
|
17
|
+
import { sql } from "drizzle-orm";
|
|
18
|
+
import {
|
|
19
|
+
boolean,
|
|
20
|
+
check,
|
|
21
|
+
index,
|
|
22
|
+
integer,
|
|
23
|
+
jsonb,
|
|
24
|
+
pgTable,
|
|
25
|
+
primaryKey,
|
|
26
|
+
text,
|
|
27
|
+
timestamp,
|
|
28
|
+
uniqueIndex,
|
|
29
|
+
uuid,
|
|
30
|
+
type AnyPgColumn,
|
|
31
|
+
} from "drizzle-orm/pg-core";
|
|
32
|
+
import { createdAtColumn, updatedAtColumn } from "@/core/db/columns";
|
|
33
|
+
import { users } from "@/core/auth/schema";
|
|
34
|
+
import { pages } from "./schema";
|
|
35
|
+
|
|
36
|
+
export const BLOG_TAXONOMIES = ["category", "tag"] as const;
|
|
37
|
+
export type BlogTaxonomy = (typeof BLOG_TAXONOMIES)[number];
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Where new archives live, and how many posts a listing page shows. One row;
|
|
41
|
+
* the key is fixed so there is never a second answer.
|
|
42
|
+
*/
|
|
43
|
+
export const blogSettings = pgTable("blog_settings", {
|
|
44
|
+
key: text("key").primaryKey().default("site"),
|
|
45
|
+
categoryBase: text("category_base").notNull().default("blog/category"),
|
|
46
|
+
tagBase: text("tag_base").notNull().default("blog/tag"),
|
|
47
|
+
authorBase: text("author_base").notNull().default("blog/author"),
|
|
48
|
+
postsPerPage: integer("posts_per_page").notNull().default(12),
|
|
49
|
+
commentsEnabled: boolean("comments_enabled").notNull().default(true),
|
|
50
|
+
createdAt: createdAtColumn(),
|
|
51
|
+
updatedAt: updatedAtColumn(),
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A person a post is by. Either an account on this site (`user_id`) or a
|
|
56
|
+
* profile that cannot sign in — a guest writer, or the author of an imported
|
|
57
|
+
* post. `email` is private: it only matches imports and accounts, and is
|
|
58
|
+
* never rendered.
|
|
59
|
+
*/
|
|
60
|
+
export const blogAuthors = pgTable(
|
|
61
|
+
"blog_authors",
|
|
62
|
+
{
|
|
63
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
64
|
+
slug: text("slug").notNull(),
|
|
65
|
+
/** The archive's address, e.g. "author/maple" for an imported site. */
|
|
66
|
+
path: text("path").notNull(),
|
|
67
|
+
name: text("name").notNull(),
|
|
68
|
+
bio: text("bio"),
|
|
69
|
+
email: text("email"),
|
|
70
|
+
userId: uuid("user_id").references(() => users.id, { onDelete: "set null" }),
|
|
71
|
+
/** Per-archive SEO overrides: title, description, noindex. */
|
|
72
|
+
seo: jsonb("seo").notNull().default({}),
|
|
73
|
+
/** Where it came from: "admin", or "import:<run id>". */
|
|
74
|
+
source: text("source").notNull().default("admin"),
|
|
75
|
+
createdAt: createdAtColumn(),
|
|
76
|
+
updatedAt: updatedAtColumn(),
|
|
77
|
+
},
|
|
78
|
+
(t) => [
|
|
79
|
+
uniqueIndex("blog_authors_slug_idx").on(t.slug),
|
|
80
|
+
uniqueIndex("blog_authors_path_idx").on(t.path),
|
|
81
|
+
uniqueIndex("blog_authors_user_idx").on(t.userId).where(sql`${t.userId} is not null`),
|
|
82
|
+
],
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
/** Categories (hierarchical) and tags (flat) share one table. */
|
|
86
|
+
export const blogTerms = pgTable(
|
|
87
|
+
"blog_terms",
|
|
88
|
+
{
|
|
89
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
90
|
+
taxonomy: text("taxonomy", { enum: BLOG_TAXONOMIES }).notNull(),
|
|
91
|
+
slug: text("slug").notNull(),
|
|
92
|
+
/** The archive's address: base plus the ancestors' slugs for a category. */
|
|
93
|
+
path: text("path").notNull(),
|
|
94
|
+
name: text("name").notNull(),
|
|
95
|
+
description: text("description"),
|
|
96
|
+
parentId: uuid("parent_id").references((): AnyPgColumn => blogTerms.id, { onDelete: "set null" }),
|
|
97
|
+
position: integer("position").notNull().default(0),
|
|
98
|
+
seo: jsonb("seo").notNull().default({}),
|
|
99
|
+
source: text("source").notNull().default("admin"),
|
|
100
|
+
createdAt: createdAtColumn(),
|
|
101
|
+
updatedAt: updatedAtColumn(),
|
|
102
|
+
},
|
|
103
|
+
(t) => [
|
|
104
|
+
check("blog_terms_taxonomy_allowed", sql`${t.taxonomy} in ('category', 'tag')`),
|
|
105
|
+
uniqueIndex("blog_terms_slug_idx").on(t.taxonomy, t.slug),
|
|
106
|
+
uniqueIndex("blog_terms_path_idx").on(t.path),
|
|
107
|
+
index("blog_terms_parent_idx").on(t.parentId),
|
|
108
|
+
],
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
/** The row that makes a page a post. */
|
|
112
|
+
export const blogPosts = pgTable(
|
|
113
|
+
"blog_posts",
|
|
114
|
+
{
|
|
115
|
+
pageId: uuid("page_id")
|
|
116
|
+
.primaryKey()
|
|
117
|
+
.references(() => pages.id, { onDelete: "cascade" }),
|
|
118
|
+
authorId: uuid("author_id").references(() => blogAuthors.id, { onDelete: "set null" }),
|
|
119
|
+
/** Per-post switch; the site-wide switch can still close every post. */
|
|
120
|
+
commentsEnabled: boolean("comments_enabled").notNull().default(true),
|
|
121
|
+
/** When the content last changed where it was first published. */
|
|
122
|
+
sourceModifiedAt: timestamp("source_modified_at", { withTimezone: true }),
|
|
123
|
+
source: text("source").notNull().default("admin"),
|
|
124
|
+
createdAt: createdAtColumn(),
|
|
125
|
+
updatedAt: updatedAtColumn(),
|
|
126
|
+
},
|
|
127
|
+
(t) => [index("blog_posts_author_idx").on(t.authorId)],
|
|
128
|
+
);
|
|
129
|
+
|
|
130
|
+
export const blogPostTerms = pgTable(
|
|
131
|
+
"blog_post_terms",
|
|
132
|
+
{
|
|
133
|
+
pageId: uuid("page_id")
|
|
134
|
+
.notNull()
|
|
135
|
+
.references(() => blogPosts.pageId, { onDelete: "cascade" }),
|
|
136
|
+
termId: uuid("term_id")
|
|
137
|
+
.notNull()
|
|
138
|
+
.references(() => blogTerms.id, { onDelete: "cascade" }),
|
|
139
|
+
/** The first category is the post's primary one (breadcrumbs). */
|
|
140
|
+
position: integer("position").notNull().default(0),
|
|
141
|
+
},
|
|
142
|
+
(t) => [
|
|
143
|
+
primaryKey({ columns: [t.pageId, t.termId] }),
|
|
144
|
+
index("blog_post_terms_term_idx").on(t.termId),
|
|
145
|
+
],
|
|
146
|
+
);
|