diff --git a/package-lock.json b/package-lock.json index 5f269e4..a108fe4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "fdc-website", - "version": "1.1.1", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "fdc-website", - "version": "1.1.1", + "version": "1.2.0", "hasInstallScript": true, "license": "MIT", "dependencies": { @@ -11867,11 +11867,7 @@ }, "packages/resume-master": { "name": "@fastdogcoding/resume-master", - "version": "1.3.0", - "license": "MIT", - "engines": { - "node": ">=20" - } + "version": "2.1.0" } } } diff --git a/package.json b/package.json index d621d57..f2491d5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "fdc-website", - "version": "1.1.1", + "version": "1.2.0", "description": "Fast Dog Coding portfolio site — a server-driven UI showcase built with Next.js, GraphQL, and Prisma.", "keywords": [ "fast-dog-coding", diff --git a/packages/resume-master/index.cjs b/packages/resume-master/index.cjs new file mode 100644 index 0000000..ee2c295 --- /dev/null +++ b/packages/resume-master/index.cjs @@ -0,0 +1,62 @@ +/* Generated by `npm run vendor` from src/client.ts. HTTP client only. */ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getResume = getResume; +/** Production projection service. A non-empty `baseUrl` or `RESUME_SERVICE_URL` overrides it. */ +const DEFAULT_RESUME_SERVICE_URL = "https://resume-master-nu.vercel.app"; +function serviceUrl(baseUrl) { + const explicit = baseUrl?.trim(); + if (explicit) + return explicit; + const fromEnv = process.env.RESUME_SERVICE_URL?.trim(); + if (fromEnv) + return fromEnv; + return DEFAULT_RESUME_SERVICE_URL; +} +function requestBody(options) { + const body = {}; + if (options.projectIds) + body.projectIds = options.projectIds; + if (options.workIds) + body.workIds = options.workIds; + if (options.keywords) + body.keywords = options.keywords; + if (options.mode === "strict" || options.mode === "expand") + body.mode = options.mode; + if (Object.hasOwn(options, "cutOffDate")) + body.cutOffDate = options.cutOffDate ?? null; + return JSON.stringify(body); +} +/** + * Fetch one client's projection. + * Reads nothing from disk, does not take a resume document, and does not + * carry allow lists. A non-empty `baseUrl` selects the service. Otherwise a + * non-empty `RESUME_SERVICE_URL` does. Otherwise the request goes to + * https://resume-master-nu.vercel.app. Errors never include the API key. + */ +async function getResume(apiKey, options = {}, baseUrl) { + if (typeof apiKey !== "string" || apiKey.length === 0) { + throw new Error("getResume requires an apiKey"); + } + const root = serviceUrl(baseUrl); + const endpoint = new URL("/v1/resume", root.endsWith("/") ? root : `${root}/`); + let response; + try { + response = await fetch(endpoint, { + method: "POST", + headers: { + Authorization: `Bearer ${apiKey}`, + Accept: "application/json", + "Content-Type": "application/json", + }, + body: requestBody(options), + }); + } + catch { + throw new Error("getResume request failed"); + } + if (!response.ok) { + throw new Error(`getResume failed with HTTP ${response.status}`); + } + return (await response.json()); +} diff --git a/packages/resume-master/index.d.ts b/packages/resume-master/index.d.ts index a9d3169..51d6088 100644 --- a/packages/resume-master/index.d.ts +++ b/packages/resume-master/index.d.ts @@ -1,134 +1,215 @@ /** - * Types for the resume-master v1.3.0 projection returned by POST /v1/resume. - * exhibitSlug is not part of this surface — the service strips it. + * Generated by `npm run generate:types` from this client's policy. + * Do not edit. */ -/** ISO-8601 calendar date (YYYY-MM-DD) or timestamp accepted as cutOffDate. */ -export type IsoDate = string; - /** - * resume-master API client whose policy filtered the projection. - * The portfolio website uses the portfolio API key. + * Projection for client "portfolio" at year date precision. */ -export type ClientId = string; - -/** Slice selector sent as `mode`. Accepted values are defined by the service. */ -export type SliceMode = string; -export interface GetResumeOptions { - projectIds?: string[]; - workIds?: string[]; - keywords?: string[]; - mode?: SliceMode; - cutOffDate?: IsoDate; +export interface PortfolioResume { + basics: PortfolioBasics; + work: PortfolioWork[]; + projects: PortfolioProject[]; + skills?: PortfolioSkill[]; + education?: PortfolioEducation[]; + interests?: PortfolioInterest[]; + references?: PortfolioReference[]; + meta: PortfolioMeta; } -export interface ResumeBasics { - name?: string; +export interface PortfolioBasics { + name: string; label?: string; - image?: string; email?: string; - phone?: string; url?: string; summary?: string; - location?: { - address?: string; - postalCode?: string; - city?: string; - countryCode?: string; - region?: string; - }; - profiles?: Array<{ - network?: string; - username?: string; - url?: string; - }>; + location?: PortfolioLocation; + profiles?: PortfolioProfile[]; + /** + * Country codes where this person is authorized to work for any employer. + * Not citizenship or immigration status. + */ + workAuthorization?: string[]; +} + +export interface PortfolioLocation { + city?: string; + region?: string; + countryCode?: string; +} + +export interface PortfolioProfile { + network: string; + username?: string; + url?: string; } -export interface WorkEntry { +export interface PortfolioWork { id: string; - name?: string; + name: string; position?: string; url?: string; - startDate?: IsoDate; - endDate?: IsoDate; + /** + * Year the projection emits (YYYY). + */ + startDate?: string; + /** + * Year the projection emits (YYYY). + */ + endDate?: string; summary?: string; - highlights?: string[]; - location?: string; - description?: string; + /** + * How this row relates to employment history. + * "employer" is an employer or the consulting practice. + * "client" is an engagement delivered through another work row. + */ + kind?: "employer" | "client"; + /** + * When kind is "client", the employer or practice work.id this engagement was via. + */ + via?: string; + /** + * Stable project ids under this employment or engagement. + */ + projects?: string[]; } -export interface ProjectEntry { +export interface PortfolioProject { id: string; name: string; - description?: string; - highlights?: string[]; - keywords?: string[]; - url?: string; - roles?: string[]; entity?: string; - type?: string; - startDate?: IsoDate; - endDate?: IsoDate; + /** + * JSON Resume roles. + */ + roles?: string[]; + /** + * Year the projection emits (YYYY). + */ + startDate?: string; + /** + * Year the projection emits (YYYY). + */ + endDate?: string; + /** + * When true, startDate is a best-effort estimate. + */ + startDateApproximate?: boolean; + /** + * Short project blurb (JSON Resume description). + */ + description?: string; challenge?: string; approach?: string; impact?: string; + /** + * Tech stack and topic tags (JSON Resume keywords). + */ + keywords?: string[]; + url?: string; } -export interface ReferenceEntry { +export interface PortfolioSkill { name: string; - reference: string; - title?: string; - snippets?: string[]; - /** Matches `work[].id` (for example "ks2-technologies" or "redspace"). */ - workId?: string; -} - -export interface SkillEntry { - name?: string; level?: string; keywords?: string[]; } -export interface EducationEntry { - institution?: string; - url?: string; +export interface PortfolioEducation { + institution: string; area?: string; studyType?: string; - startDate?: IsoDate; - endDate?: IsoDate; score?: string; courses?: string[]; + /** + * Extension. Not in the core JSON Resume schema. + */ + location?: string; } -export interface InterestEntry { - name?: string; +export interface PortfolioInterest { + name: string; keywords?: string[]; } -export interface ProjectionMeta { - clientId?: ClientId; - mode?: SliceMode; - cutOffDate?: IsoDate; - generatedAt?: string; - version?: string; +export interface PortfolioReference { + name: string; + reference: string; + title?: string; + relationship?: string; + /** + * Year the projection emits (YYYY). + */ + date?: string; + url?: string; + /** + * Matching work id for the organization where this reference worked with the subject. + */ + workId?: string; + /** + * Short pull-quotes. + */ + snippets?: string[]; } +/** + * Projection metadata. Always present. + */ -export interface ProjectedResume { - basics?: ResumeBasics; - work?: WorkEntry[]; - education?: EducationEntry[]; - skills?: SkillEntry[]; - interests?: InterestEntry[]; - references?: ReferenceEntry[]; - projects?: ProjectEntry[]; - meta?: ProjectionMeta; +export interface PortfolioMeta { + /** + * Client whose policy produced this projection. + */ + clientId: "portfolio"; + /** + * Cutoff actually applied, or null when the projection has no cutoff. + */ + cutOffDate: string | null; + /** + * Always true on a projection. + */ + projected: true; } -export const DEFAULT_RESUME_SERVICE_URL: "https://resume-master-nu.vercel.app"; +/** + * Names exported by resume-master 1.3.0. + * A re-vendored app can keep importing these names. + * Each alias is this client's projection, not the master document. + */ +export type IsoDate = string; +export type ClientId = string; +export type SliceMode = "strict" | "expand"; +export type WorkKind = "employer" | "client"; +export type ResumeBasics = PortfolioBasics; +export type WorkEntry = PortfolioWork; +export type ProjectEntry = PortfolioProject; +export type SkillEntry = PortfolioSkill; +export type EducationEntry = PortfolioEducation; +export type InterestEntry = PortfolioInterest; +export type ReferenceEntry = PortfolioReference; +export type ProjectionMeta = PortfolioMeta; +export type ProjectedResume = PortfolioResume; + +/** Body accepted by `POST /v1/resume`. `asOf` is not a field. */ +export interface GetResumeOptions { + projectIds?: string[]; + workIds?: string[]; + keywords?: string[]; + mode?: SliceMode; + /** + * Honored only when this client's policy allows an override. `null` clears it. + */ + cutOffDate?: string | null; +} -export function getResume( +/** + * Fetch one client's projection. + * Reads nothing from disk, does not take a resume document, and does not + * carry allow lists. A non-empty `baseUrl` selects the service. Otherwise a + * non-empty `RESUME_SERVICE_URL` does. Otherwise the request goes to + * https://resume-master-nu.vercel.app. Errors never include the API key. + */ +export declare function getResume( apiKey: string, options?: GetResumeOptions, baseUrl?: string, -): Promise; +): Promise; diff --git a/packages/resume-master/index.js b/packages/resume-master/index.js index 6993455..1afedc4 100644 --- a/packages/resume-master/index.js +++ b/packages/resume-master/index.js @@ -1,123 +1,59 @@ -"use strict"; - -/** - * resume-master v1.3.0 HTTP client. - * - * Post-Phase 4 surface only: resolve the service origin and POST /v1/resume. - * Projections never include exhibitSlug; callers key projects by id. - */ - +/* Generated by `npm run vendor` from src/client.ts. HTTP client only. */ +/** Production projection service. A non-empty `baseUrl` or `RESUME_SERVICE_URL` overrides it. */ const DEFAULT_RESUME_SERVICE_URL = "https://resume-master-nu.vercel.app"; - -const OPTION_KEYS = ["projectIds", "workIds", "keywords", "mode", "cutOffDate"]; - -function assertApiKey(apiKey) { - if (typeof apiKey !== "string" || apiKey.trim() === "") { - throw new Error("resume-master API key must be a non-empty string."); - } - return apiKey.trim(); -} - -function nonEmpty(value) { - return typeof value === "string" && value.trim() !== ""; -} - -function stripTrailingSlashes(value) { - return value.trim().replace(/\/+$/, ""); +function serviceUrl(baseUrl) { + const explicit = baseUrl?.trim(); + if (explicit) + return explicit; + const fromEnv = process.env.RESUME_SERVICE_URL?.trim(); + if (fromEnv) + return fromEnv; + return DEFAULT_RESUME_SERVICE_URL; +} +function requestBody(options) { + const body = {}; + if (options.projectIds) + body.projectIds = options.projectIds; + if (options.workIds) + body.workIds = options.workIds; + if (options.keywords) + body.keywords = options.keywords; + if (options.mode === "strict" || options.mode === "expand") + body.mode = options.mode; + if (Object.hasOwn(options, "cutOffDate")) + body.cutOffDate = options.cutOffDate ?? null; + return JSON.stringify(body); } - -function resolveHost(baseUrl) { - if (nonEmpty(baseUrl)) return stripTrailingSlashes(baseUrl); - if (nonEmpty(process.env.RESUME_SERVICE_URL)) { - return stripTrailingSlashes(process.env.RESUME_SERVICE_URL); - } - return DEFAULT_RESUME_SERVICE_URL; -} - -function definedOptions(options) { - if (options == null) return {}; - if (typeof options !== "object" || Array.isArray(options)) { - throw new Error("resume-master options must be an object."); - } - const body = {}; - for (const key of OPTION_KEYS) { - if (options[key] !== undefined) { - body[key] = options[key]; +/** + * Fetch one client's projection. + * Reads nothing from disk, does not take a resume document, and does not + * carry allow lists. A non-empty `baseUrl` selects the service. Otherwise a + * non-empty `RESUME_SERVICE_URL` does. Otherwise the request goes to + * https://resume-master-nu.vercel.app. Errors never include the API key. + */ +export async function getResume(apiKey, options = {}, baseUrl) { + if (typeof apiKey !== "string" || apiKey.length === 0) { + throw new Error("getResume requires an apiKey"); } - } - return body; -} - -function redact(message, apiKey) { - if (!message) return ""; - let redacted = message; - if (apiKey) { - redacted = redacted.split(apiKey).join("[redacted]"); - redacted = redacted.split(`Bearer ${apiKey}`).join("Bearer [redacted]"); - } - return redacted; -} - -function httpError(status, body, apiKey) { - const snippet = redact((body || "").trim().slice(0, 300), apiKey); - if (!snippet) { - return `resume-master request failed with HTTP ${status}.`; - } - return `resume-master request failed with HTTP ${status}: ${snippet}`; -} - -async function getResume(apiKey, options, baseUrl) { - const key = assertApiKey(apiKey); - const host = resolveHost(baseUrl); - const url = `${host}/v1/resume`; - const body = definedOptions(options); - - let response; - try { - response = await fetch(url, { - method: "POST", - headers: { - Authorization: `Bearer ${key}`, - "Content-Type": "application/json", - Accept: "application/json", - }, - body: JSON.stringify(body), - cache: "no-store", - }); - } catch (error) { - const reason = error instanceof Error ? error.message : "network error"; - throw new Error( - `resume-master request failed: ${redact(reason, key)}` - ); - } - - const text = await response.text(); - if (!response.ok) { - throw new Error(httpError(response.status, text, key)); - } - - if (!text.trim()) { - throw new Error("resume-master returned invalid JSON (empty body)."); - } - - let parsed; - try { - parsed = JSON.parse(text); - } catch { - const snippet = redact(text.trim().slice(0, 120), key); - throw new Error( - `resume-master returned invalid JSON${snippet ? ` (${snippet})` : ""}.` - ); - } - - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { - throw new Error("resume-master returned an unexpected payload."); - } - - return parsed; + const root = serviceUrl(baseUrl); + const endpoint = new URL("/v1/resume", root.endsWith("/") ? root : `${root}/`); + let response; + try { + response = await fetch(endpoint, { + method: "POST", + headers: { + Authorization: `Bearer ${apiKey}`, + Accept: "application/json", + "Content-Type": "application/json", + }, + body: requestBody(options), + }); + } + catch { + throw new Error("getResume request failed"); + } + if (!response.ok) { + throw new Error(`getResume failed with HTTP ${response.status}`); + } + return (await response.json()); } - -module.exports = { - DEFAULT_RESUME_SERVICE_URL, - getResume, -}; diff --git a/packages/resume-master/package.json b/packages/resume-master/package.json index 7c95015..fde090c 100644 --- a/packages/resume-master/package.json +++ b/packages/resume-master/package.json @@ -1,22 +1,21 @@ { "name": "@fastdogcoding/resume-master", - "version": "1.3.0", - "description": "HTTP client for the Fast Dog Coding resume-master projection service (v1.3.0).", - "license": "MIT", - "type": "commonjs", - "main": "./index.js", + "version": "2.1.0", + "type": "module", + "main": "./index.cjs", + "module": "./index.js", "types": "./index.d.ts", "exports": { ".": { "types": "./index.d.ts", - "default": "./index.js" + "import": "./index.js", + "require": "./index.cjs" } }, - "files": [ - "index.js", - "index.d.ts" - ], - "engines": { - "node": ">=20" + "vendorStamp": { + "clientId": "portfolio", + "version": "2.1.0", + "commit": "1d71be85118ef86ec595dd1b24987745920886c4", + "generatedAt": "2026-11-05T20:44:57.748Z" } } diff --git a/prisma/seed-content.ts b/prisma/seed-content.ts index 0860c07..80ab3e6 100644 --- a/prisma/seed-content.ts +++ b/prisma/seed-content.ts @@ -10,6 +10,7 @@ */ import type { Prisma, PrismaClient } from "@prisma/client"; +import { HOME_HERO } from "../src/lib/site-copy"; export async function seedStaticSite(prisma: PrismaClient): Promise { async function createSection( @@ -104,9 +105,8 @@ export async function seedStaticSite(prisma: PrismaClient): Promise { const homeHero = await createSection( "hero", { - heading: "Listen carefully. Think deeply. Build deliberately.", - subheading: - "We focus on solving your problems the right way.", + heading: HOME_HERO.heading, + subheading: HOME_HERO.subheading, cta_label: "Explore the Gallery", cta_href: "/gallery", }, diff --git a/prisma/seed.ts b/prisma/seed.ts index 66dfc40..12b44c2 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -48,8 +48,12 @@ async function main() { console.log("↻ Syncing exhibits and testimonials from resume-master..."); const projection = await getResume(apiKey); const result = await syncResume(prisma, projection); + const retiredNote = + result.retired.length > 0 + ? `; unpublished ${result.retired.length} stale gallery exhibit${result.retired.length === 1 ? "" : "s"}` + : ""; console.log( - ` ↳ synced ${result.exhibits.length} exhibits and ${result.testimonials.length} testimonials` + ` ↳ synced ${result.exhibits.length} exhibits and ${result.testimonials.length} testimonials${retiredNote}` ); } else { console.log( diff --git a/scripts/check-db.ts b/scripts/check-db.ts new file mode 100644 index 0000000..ab6b9d9 --- /dev/null +++ b/scripts/check-db.ts @@ -0,0 +1,32 @@ +/** + * Connectivity check for scripts/dev.sh when psql is not on PATH. + * + * Uses pgPoolConfig so Neon URLs (sslmode require/prefer/verify-ca and + * channel_binding=require) match the app pool. A URL with no sslmode, + * including postgresql://localhost:5432/fdc_website, is left unchanged. + * + * Exits 0 when SELECT 1 succeeds, 1 otherwise. + */ + +import { Pool } from "pg"; +import { pgPoolConfig } from "../src/lib/pg-config"; + +async function main(): Promise { + const connectionString = process.env.DATABASE_URL; + if (!connectionString) { + throw new Error("DATABASE_URL is not set."); + } + + const pool = new Pool(pgPoolConfig(connectionString)); + try { + await pool.query("SELECT 1"); + } finally { + await pool.end(); + } +} + +main().catch((error: unknown) => { + const message = error instanceof Error ? error.message : String(error); + console.error(message); + process.exit(1); +}); diff --git a/scripts/dev.sh b/scripts/dev.sh index e7cc9b1..dc1bed5 100755 --- a/scripts/dev.sh +++ b/scripts/dev.sh @@ -49,16 +49,8 @@ check_database() { return $? fi - # Fallback when psql is not on PATH - node --input-type=module -e " - import pg from 'pg'; - const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); - try { - await pool.query('SELECT 1'); - } finally { - await pool.end(); - } - " 2>/dev/null + # Fallback when psql is not on PATH (same pool config as the app) + npx tsx scripts/check-db.ts 2>/dev/null } if ! check_database; then diff --git a/scripts/sync-resume.ts b/scripts/sync-resume.ts index d81abd2..0d52209 100644 --- a/scripts/sync-resume.ts +++ b/scripts/sync-resume.ts @@ -3,9 +3,14 @@ * * npm run sync:db * npm run sync:db -- --no-revalidate + * npm run sync:db -- --dry-run + * + * Catalog gallery pages whose project is absent from the projection are + * unpublished (the row is kept). --dry-run prints the upsert and unpublish + * sets and writes nothing, including no ISR revalidation. * * Revalidation runs afterward when REVALIDATION_SECRET is set, unless - * --no-revalidate is passed. + * --no-revalidate or --dry-run is passed. */ import "dotenv/config"; @@ -28,7 +33,8 @@ function readApiKey(): string { } async function main() { - const skipRevalidate = process.argv.includes("--no-revalidate"); + const dryRun = process.argv.includes("--dry-run"); + const skipRevalidate = dryRun || process.argv.includes("--no-revalidate"); const apiKey = readApiKey(); const connectionString = process.env.DATABASE_URL_UNPOOLED || process.env.DATABASE_URL; @@ -41,22 +47,35 @@ async function main() { const prisma = new PrismaClient({ adapter: new PrismaPg(pool) }); try { - const result = await syncResume(prisma, projection); + const result = await syncResume(prisma, projection, { dryRun }); const exhibitSummary = result.exhibits.join(", ") || "(none)"; const testimonialSummary = result.testimonials.join(", ") || "(none)"; + const retiredSummary = result.retired.map((entry) => entry.slug).join(", ") || "(none)"; + const wrote = dryRun ? "Would upsert" : "Upserted"; + const retiredVerb = dryRun ? "Would unpublish" : "Unpublished"; + console.log( + `${wrote} ${result.exhibits.length} exhibit${result.exhibits.length === 1 ? "" : "s"}: ${exhibitSummary}` + ); console.log( - `Upserted ${result.exhibits.length} exhibit${result.exhibits.length === 1 ? "" : "s"}: ${exhibitSummary}` + `${wrote} ${result.testimonials.length} testimonial${result.testimonials.length === 1 ? "" : "s"}: ${testimonialSummary}` ); console.log( - `Upserted ${result.testimonials.length} testimonial${result.testimonials.length === 1 ? "" : "s"}: ${testimonialSummary}` + `${retiredVerb} ${result.retired.length} gallery exhibit${result.retired.length === 1 ? "" : "s"}: ${retiredSummary}` ); + if (dryRun) { + console.log("Dry run: no rows written."); + } } finally { await prisma.$disconnect(); await pool.end(); } if (skipRevalidate) { - console.log("Skipping ISR revalidation (--no-revalidate)."); + console.log( + dryRun + ? "Skipping ISR revalidation (--dry-run)." + : "Skipping ISR revalidation (--no-revalidate)." + ); return; } if (!process.env.REVALIDATION_SECRET) { diff --git a/src/app/api/revalidate/route.ts b/src/app/api/revalidate/route.ts index ec42181..46f7041 100644 --- a/src/app/api/revalidate/route.ts +++ b/src/app/api/revalidate/route.ts @@ -19,6 +19,7 @@ export async function POST(request: NextRequest) { try { revalidatePath("/", "layout"); + revalidatePath("/sitemap.xml"); return Response.json({ revalidated: true, timestamp: new Date().toISOString(), diff --git a/src/app/api/sync/__tests__/route.test.ts b/src/app/api/sync/__tests__/route.test.ts index 3b67f53..fcbb6fc 100644 --- a/src/app/api/sync/__tests__/route.test.ts +++ b/src/app/api/sync/__tests__/route.test.ts @@ -48,6 +48,8 @@ describe("POST /api/sync", () => { mockSyncResume.mockResolvedValue({ exhibits: ["exhibit-portfolio-website"], testimonials: ["testimonial-andrew"], + retired: [], + dryRun: false, }); }); @@ -96,18 +98,62 @@ describe("POST /api/sync", () => { expect(mockGetResume).toHaveBeenCalledWith("resume-key"); expect(mockSyncResume).toHaveBeenCalledWith( { tag: "prisma-singleton" }, - { projects: [], references: [] } + { projects: [], references: [] }, + { dryRun: false } ); expect(mockRevalidatePath).toHaveBeenCalledWith("/", "layout"); + expect(mockRevalidatePath).toHaveBeenCalledWith("/sitemap.xml"); expect(body).toMatchObject({ synced: true, + dryRun: false, exhibits: ["exhibit-portfolio-website"], testimonials: ["testimonial-andrew"], + retired: [], revalidated: true, }); expect(body.timestamp).toEqual(expect.any(String)); }); + it("dry run reports retirements without writing or revalidating", async () => { + mockSyncResume.mockResolvedValue({ + exhibits: ["exhibit-homesalesone"], + testimonials: [], + retired: [ + { + id: "page-phoenix", + slug: "phoenix", + title: "Phoenix — Investment Lifecycle Management", + projectId: "phoenix", + exhibitSlug: "exhibit-phoenix", + path: "/gallery/phoenix", + }, + ], + dryRun: true, + }); + + const response = await POST( + new NextRequest("http://localhost/api/sync?dryRun=true", { + method: "POST", + headers: { authorization: "Bearer test-secret" }, + }) + ); + + expect(response.status).toBe(200); + expect(mockSyncResume).toHaveBeenCalledWith( + { tag: "prisma-singleton" }, + { projects: [], references: [] }, + { dryRun: true } + ); + expect(mockRevalidatePath).not.toHaveBeenCalled(); + await expect(response.json()).resolves.toMatchObject({ + synced: false, + dryRun: true, + revalidated: false, + exhibits: ["exhibit-homesalesone"], + retired: [{ slug: "phoenix", path: "/gallery/phoenix" }], + }); + }); + it("does not revalidate or echo the API key when the sync fails", async () => { mockGetResume.mockRejectedValue( new Error("resume-master request failed and resume-key was not included") diff --git a/src/app/api/sync/route.ts b/src/app/api/sync/route.ts index fe55170..26da584 100644 --- a/src/app/api/sync/route.ts +++ b/src/app/api/sync/route.ts @@ -3,10 +3,17 @@ * * Authorization matches POST /api/revalidate (Bearer REVALIDATION_SECRET). * Fetches the portfolio projection from resume-master, upserts exhibits and - * testimonials in Neon, then purges the ISR cache. + * testimonials in Neon, unpublishes catalog gallery pages that left the + * projection, then purges the ISR cache. * * POST /api/sync * Authorization: Bearer + * + * POST /api/sync?dryRun=true + * Authorization: Bearer + * + * dryRun=true (or dryRun=1) reports exhibits, testimonials, and gallery + * pages that would be unpublished, and does not write or revalidate. */ import { revalidatePath } from "next/cache"; @@ -23,6 +30,13 @@ function resumeApiKey(): string | undefined { return trimmed === "" ? undefined : trimmed; } +function readDryRun(request: NextRequest): boolean { + const value = request.nextUrl.searchParams.get("dryRun"); + if (value === null) return false; + const normalized = value.trim().toLowerCase(); + return normalized === "1" || normalized === "true"; +} + function redact(message: string, secrets: Array): string { let redacted = message; for (const secret of secrets) { @@ -46,13 +60,19 @@ export async function POST(request: NextRequest) { try { const projection = await getResume(apiKey); - const result = await syncResume(prisma, projection); - revalidatePath("/", "layout"); + const dryRun = readDryRun(request); + const result = await syncResume(prisma, projection, { dryRun }); + if (!dryRun) { + revalidatePath("/", "layout"); + revalidatePath("/sitemap.xml"); + } return Response.json({ - synced: true, + synced: !dryRun, + dryRun, exhibits: result.exhibits, testimonials: result.testimonials, - revalidated: true, + retired: result.retired, + revalidated: !dryRun, timestamp: new Date().toISOString(), }); } catch (error) { diff --git a/src/app/opengraph-image.tsx b/src/app/opengraph-image.tsx index 5a97e52..558d2a2 100644 --- a/src/app/opengraph-image.tsx +++ b/src/app/opengraph-image.tsx @@ -1,6 +1,7 @@ import { ImageResponse } from "next/og"; +import { HOME_HERO, HOME_HERO_HEADING_TEXT } from "@/lib/site-copy"; -export const alt = "Fast Dog Coding — Principal-Level Architecture"; +export const alt = `Fast Dog Coding — ${HOME_HERO_HEADING_TEXT}`; export const size = { width: 1200, height: 630 }; export const contentType = "image/png"; @@ -53,12 +54,12 @@ export default function OpenGraphImage() { {/* Headline */} -
-
- Principal-Level Architecture. +
+
+ {HOME_HERO.heading}
-
- Enterprise-Grade Execution. +
+ {HOME_HERO.subheading}
diff --git a/src/app/sitemap.ts b/src/app/sitemap.ts index 7fa96aa..6a9f178 100644 --- a/src/app/sitemap.ts +++ b/src/app/sitemap.ts @@ -1,29 +1,31 @@ import type { MetadataRoute } from "next"; import { prisma } from "@/lib/prisma"; +import { + publishedPageWhere, + publishedSitemapEntries, +} from "@/lib/sitemap-entries"; + +/** + * Next caches sitemap handlers unless they opt into dynamic rendering. + * Read published pages on each request so an exhibit unpublished by resume + * sync leaves the sitemap without a rebuild. `revalidatePath("/sitemap.xml")` + * still runs after sync for any copy a CDN already stored. + */ +export const dynamic = "force-dynamic"; +export const revalidate = 0; export default async function sitemap(): Promise { const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || "https://fastdogcoding.com"; - // Fetch all published pages const pages = await prisma.page.findMany({ - where: { isPublished: true }, - select: { slug: true, parentSlug: true, updatedAt: true }, - }); - - const routes: MetadataRoute.Sitemap = pages.map((page) => { - // Construct full path - const path = page.parentSlug ? `/${page.parentSlug}/${page.slug}` : `/${page.slug}`; - - // Home page is just '/' - const routeUrl = page.slug === "home" && !page.parentSlug ? "" : path; - - return { - url: `${baseUrl}${routeUrl}`, - lastModified: page.updatedAt, - changeFrequency: "weekly", - priority: page.slug === "home" ? 1 : 0.8, - }; + where: publishedPageWhere, + select: { + slug: true, + parentSlug: true, + updatedAt: true, + isPublished: true, + }, }); - return routes; + return publishedSitemapEntries(pages, baseUrl); } diff --git a/src/lib/__tests__/resume-adapter.test.ts b/src/lib/__tests__/resume-adapter.test.ts index 3a5bfa1..0660654 100644 --- a/src/lib/__tests__/resume-adapter.test.ts +++ b/src/lib/__tests__/resume-adapter.test.ts @@ -1,8 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { - DEFAULT_RESUME_SERVICE_URL, getResume, - type ProjectedResume, + type PortfolioResume, } from "@fastdogcoding/resume-master"; import { EXHIBIT_CATALOG, @@ -25,20 +24,30 @@ afterEach(() => { }); type ResumeFetch = ( - url: string, + url: string | URL, init?: RequestInit -) => Promise<{ ok: boolean; status: number; text: () => Promise }>; +) => Promise<{ + ok: boolean; + status: number; + text: () => Promise; + json: () => Promise; +}>; function mockFetch(response: { ok: boolean; status: number; body: string }) { const fetchMock = vi.fn(async () => ({ ok: response.ok, status: response.status, text: async () => response.body, + json: async () => JSON.parse(response.body) as unknown, })); vi.stubGlobal("fetch", fetchMock); return fetchMock; } +function requestUrl(value: string | URL): string { + return value instanceof URL ? value.href : value; +} + function fetchCall( fetchMock: ReturnType, index: number @@ -47,7 +56,7 @@ function fetchCall( if (!invocation) throw new Error(`missing fetch call ${index}`); const init = invocation[1]; if (!init) throw new Error(`missing fetch init ${index}`); - return { url: invocation[0], init }; + return { url: requestUrl(invocation[0]), init }; } describe("getResume", () => { @@ -60,7 +69,6 @@ describe("getResume", () => { const result = await getResume(SECRET_KEY); - expect(DEFAULT_RESUME_SERVICE_URL).toBe("https://resume-master-nu.vercel.app"); expect(fetchMock).toHaveBeenCalledOnce(); const { url, init } = fetchCall(fetchMock, 0); expect(url).toBe("https://resume-master-nu.vercel.app/v1/resume"); @@ -105,13 +113,13 @@ describe("getResume", () => { await getResume(SECRET_KEY, { projectIds: ["edvisor"], keywords: undefined, - mode: "full", + mode: "strict", cutOffDate: "2020-01-01", }); expect(JSON.parse(String(fetchCall(fetchMock, 0).init.body))).toEqual({ projectIds: ["edvisor"], - mode: "full", + mode: "strict", cutOffDate: "2020-01-01", }); }); @@ -123,9 +131,9 @@ describe("getResume", () => { body: "{}", }); - await expect(getResume(" ")).rejects.toThrow(/non-empty string/); + await expect(getResume("")).rejects.toThrow(/requires an apiKey/); await expect(getResume(undefined as unknown as string)).rejects.toThrow( - /non-empty string/ + /requires an apiKey/ ); expect(fetchMock).not.toHaveBeenCalled(); }); @@ -138,7 +146,6 @@ describe("getResume", () => { }); await expect(getResume(SECRET_KEY)).rejects.toThrow(/HTTP 401/); - await expect(getResume(SECRET_KEY)).rejects.toThrow(/\[redacted\]/); try { await getResume(SECRET_KEY); } catch (error) { @@ -147,11 +154,11 @@ describe("getResume", () => { } }); - it("describes invalid JSON without leaking the API key", async () => { + it("rejects a response body that is not JSON", async () => { mockFetch({ ok: true, status: 200, - body: `not-json ${SECRET_KEY}`, + body: "not-json", }); try { @@ -160,7 +167,7 @@ describe("getResume", () => { } catch (error) { expect(error).toBeInstanceOf(Error); const message = (error as Error).message; - expect(message).toMatch(/invalid JSON/); + expect(message).toMatch(/not valid JSON/); expect(message).not.toContain(SECRET_KEY); } }); @@ -209,7 +216,9 @@ describe("exhibit catalog", () => { }); describe("project and reference mapping", () => { - const projection: ProjectedResume = { + const projection: PortfolioResume = { + basics: { name: "Grant Lindsay" }, + meta: { clientId: "portfolio", cutOffDate: null, projected: true }, work: [ { id: "ks2-technologies", name: "Example Systems, Inc." }, { id: "redspace", name: "Northwind Studio" }, diff --git a/src/lib/__tests__/site-copy.test.ts b/src/lib/__tests__/site-copy.test.ts new file mode 100644 index 0000000..5ffb352 --- /dev/null +++ b/src/lib/__tests__/site-copy.test.ts @@ -0,0 +1,38 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { HOME_HERO, HOME_HERO_HEADING_TEXT } from "@/lib/site-copy"; + +describe("home hero copy", () => { + it("matches the public home hero wording", () => { + expect(HOME_HERO.heading).toBe( + "Listen\u00a0carefully. Think\u00a0deeply. Build\u00a0deliberately." + ); + expect(HOME_HERO_HEADING_TEXT).toBe( + "Listen carefully. Think deeply. Build deliberately." + ); + expect(HOME_HERO.subheading).toBe( + "We focus on solving your problems the right way." + ); + }); + + it("is what the Open Graph image and the home hero seed render", () => { + const image = readFileSync( + path.join(process.cwd(), "src/app/opengraph-image.tsx"), + "utf8" + ); + const seed = readFileSync( + path.join(process.cwd(), "prisma/seed-content.ts"), + "utf8" + ); + + expect(image).toContain("HOME_HERO.heading"); + expect(image).toContain("HOME_HERO.subheading"); + expect(image).toContain("HOME_HERO_HEADING_TEXT"); + expect(image).not.toContain("Principal-Level Architecture"); + expect(image).not.toContain("Enterprise-Grade Execution"); + + expect(seed).toContain("heading: HOME_HERO.heading"); + expect(seed).toContain("subheading: HOME_HERO.subheading"); + }); +}); diff --git a/src/lib/__tests__/sitemap-entries.test.ts b/src/lib/__tests__/sitemap-entries.test.ts new file mode 100644 index 0000000..0024710 --- /dev/null +++ b/src/lib/__tests__/sitemap-entries.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest"; +import { publishedSitemapEntries } from "@/lib/sitemap-entries"; + +const updatedAt = new Date("2026-05-01T00:00:00.000Z"); + +describe("publishedSitemapEntries", () => { + it("lists published pages and omits retired gallery exhibits", () => { + const entries = publishedSitemapEntries( + [ + { + slug: "home", + parentSlug: null, + updatedAt, + isPublished: true, + }, + { + slug: "services", + parentSlug: null, + updatedAt, + isPublished: true, + }, + { + slug: "gallery", + parentSlug: null, + updatedAt, + isPublished: true, + }, + { + slug: "homesalesone", + parentSlug: "gallery", + updatedAt, + isPublished: true, + }, + { + slug: "phoenix", + parentSlug: "gallery", + updatedAt, + isPublished: false, + }, + { + slug: "about", + parentSlug: null, + updatedAt, + isPublished: false, + }, + ], + "https://fastdogcoding.com" + ); + + expect(entries.map((entry) => entry.url)).toEqual([ + "https://fastdogcoding.com", + "https://fastdogcoding.com/services", + "https://fastdogcoding.com/gallery", + "https://fastdogcoding.com/gallery/homesalesone", + ]); + expect(entries[0]).toMatchObject({ priority: 1, changeFrequency: "weekly" }); + expect(entries[3]).toMatchObject({ + priority: 0.8, + lastModified: updatedAt, + }); + expect(entries.some((entry) => entry.url.includes("phoenix"))).toBe(false); + }); +}); diff --git a/src/lib/__tests__/sync-resume.test.ts b/src/lib/__tests__/sync-resume.test.ts index b3a81e2..af30376 100644 --- a/src/lib/__tests__/sync-resume.test.ts +++ b/src/lib/__tests__/sync-resume.test.ts @@ -1,6 +1,6 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import type { PrismaClient } from "@prisma/client"; -import type { ProjectedResume } from "@fastdogcoding/resume-master"; +import type { PortfolioResume } from "@fastdogcoding/resume-master"; import { syncResume } from "@/lib/sync-resume"; interface Row { @@ -13,6 +13,7 @@ function createFakePrisma() { const sections = new Map(); const placements: Row[] = []; const deleted: string[] = []; + const updates: Array<{ id: string; isPublished?: boolean }> = []; function refuseDelete(label: string) { return () => { @@ -66,6 +67,36 @@ function createFakePrisma() { return created; }, deleteMany: refuseDelete("pages"), + findMany: async ({ + where, + }: { + where?: { parentSlug?: string }; + }) => + [...pages.values()].filter((page) => { + if ( + where?.parentSlug !== undefined && + page.parentSlug !== where.parentSlug + ) { + return false; + } + return true; + }), + update: async ({ + where, + data, + }: { + where: { id: string }; + data: { isPublished?: boolean }; + }) => { + const existing = [...pages.values()].find((page) => page.id === where.id); + if (!existing) { + throw new Error(`missing page ${where.id}`); + } + const next = { ...existing, ...data }; + pages.set(String(existing.slug), next); + updates.push({ id: where.id, isPublished: data.isPublished }); + return next; + }, }, section: { findUnique: async ({ where }: { where: { slug: string } }) => @@ -117,10 +148,19 @@ function createFakePrisma() { }, }; - return { prisma: prisma as unknown as PrismaClient, pages, sections, placements, deleted }; + return { + prisma: prisma as unknown as PrismaClient, + pages, + sections, + placements, + deleted, + updates, + }; } -const projection: ProjectedResume = { +const projection: PortfolioResume = { + basics: { name: "Grant Lindsay" }, + meta: { clientId: "portfolio", cutOffDate: null, projected: true }, work: [ { id: "ks2-technologies", name: "Example Systems, Inc." }, { id: "redspace", name: "Northwind Studio" }, @@ -239,4 +279,174 @@ describe("syncResume", () => { await expect(syncResume(fake.prisma, projection)).rejects.toThrow(/gallery/); expect(fake.sections.has("exhibit-homesalesone")).toBe(false); }); + + it("unpublishes a catalog gallery page missing from the projection and leaves static pages", async () => { + const fake = createFakePrisma(); + fake.pages.set("phoenix", { + id: "page-phoenix", + slug: "phoenix", + parentSlug: "gallery", + title: "Phoenix — Investment Lifecycle Management", + isPublished: true, + isNav: false, + }); + fake.pages.set("hand-built", { + id: "page-hand-built", + slug: "hand-built", + parentSlug: "gallery", + title: "Hand built exhibit", + isPublished: true, + isNav: false, + }); + fake.pages.set("edvisor", { + id: "page-edvisor", + slug: "edvisor", + parentSlug: "gallery", + title: "Edvisor — LMS Modernization", + isPublished: true, + isNav: true, + }); + fake.sections.set("exhibit-phoenix", { + id: "section-exhibit-phoenix", + slug: "exhibit-phoenix", + type: "exhibit", + data: { title: "Phoenix" }, + }); + fake.placements.push({ + id: "ps-phoenix", + pageId: "page-phoenix", + sectionId: "section-exhibit-phoenix", + sortOrder: 0, + displayHint: null, + }); + + const info = vi.spyOn(console, "info").mockImplementation(() => {}); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const result = await syncResume(fake.prisma, projection); + + expect(result.dryRun).toBe(false); + expect(result.retired).toEqual([ + { + id: "page-phoenix", + slug: "phoenix", + title: "Phoenix — Investment Lifecycle Management", + projectId: "phoenix", + exhibitSlug: "exhibit-phoenix", + path: "/gallery/phoenix", + }, + ]); + expect(info).toHaveBeenCalledWith( + expect.stringContaining( + 'unpublished gallery exhibit id=page-phoenix slug=phoenix title="Phoenix — Investment Lifecycle Management" projectId=phoenix exhibitSlug=exhibit-phoenix path=/gallery/phoenix' + ) + ); + + expect(fake.pages.get("phoenix")).toMatchObject({ + isPublished: false, + slug: "phoenix", + parentSlug: "gallery", + title: "Phoenix — Investment Lifecycle Management", + }); + expect(fake.sections.get("exhibit-phoenix")?.data).toEqual({ title: "Phoenix" }); + expect( + fake.placements.some((row) => row.pageId === "page-phoenix") + ).toBe(true); + expect(fake.pages.get("hand-built")).toMatchObject({ + isPublished: true, + title: "Hand built exhibit", + }); + expect(fake.pages.get("edvisor")?.isPublished).toBe(true); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining("refused to retire slug=edvisor") + ); + expect(fake.pages.get("services")?.title).toBe("Services"); + expect(fake.pages.get("gallery")?.title).toBe("Gallery"); + expect(fake.pages.get("home")?.slug).toBe("home"); + expect(fake.sections.get("hero-home")?.data).toEqual({ heading: "Keep me" }); + expect(fake.deleted).toEqual([]); + expect(fake.updates).toEqual([{ id: "page-phoenix", isPublished: false }]); + + info.mockClear(); + const again = await syncResume(fake.prisma, projection); + expect(again.retired).toEqual([]); + expect(fake.pages.get("phoenix")?.isPublished).toBe(false); + expect(fake.updates).toEqual([{ id: "page-phoenix", isPublished: false }]); + expect(fake.deleted).toEqual([]); + expect(info).not.toHaveBeenCalled(); + } finally { + info.mockRestore(); + warn.mockRestore(); + } + }); + + it("dry run reports the retirement and does not write", async () => { + const fake = createFakePrisma(); + fake.pages.set("phoenix", { + id: "page-phoenix", + slug: "phoenix", + parentSlug: "gallery", + title: "Phoenix — Investment Lifecycle Management", + isPublished: true, + isNav: false, + }); + + const info = vi.spyOn(console, "info").mockImplementation(() => {}); + try { + const result = await syncResume(fake.prisma, projection, { dryRun: true }); + + expect(result.dryRun).toBe(true); + expect(result.exhibits).toEqual([ + "exhibit-resume-master", + "exhibit-homesalesone", + ]); + expect(result.retired.map((entry) => entry.slug)).toEqual(["phoenix"]); + expect(fake.pages.get("phoenix")?.isPublished).toBe(true); + expect(fake.pages.has("resume-master")).toBe(false); + expect(fake.pages.has("homesalesone")).toBe(false); + expect(fake.sections.has("exhibit-homesalesone")).toBe(false); + expect(fake.updates).toEqual([]); + expect(fake.deleted).toEqual([]); + expect(fake.pages.get("services")?.title).toBe("Services"); + expect(info).toHaveBeenCalledWith( + expect.stringContaining("would unpublish gallery exhibit id=page-phoenix") + ); + } finally { + info.mockRestore(); + } + }); + + it("republishes a retired catalog page when the project returns", async () => { + const fake = createFakePrisma(); + fake.pages.set("phoenix", { + id: "page-phoenix", + slug: "phoenix", + parentSlug: "gallery", + title: "Phoenix — Investment Lifecycle Management", + isPublished: true, + isNav: false, + }); + + const info = vi.spyOn(console, "info").mockImplementation(() => {}); + try { + await syncResume(fake.prisma, projection); + expect(fake.pages.get("phoenix")?.isPublished).toBe(false); + + const returned = await syncResume(fake.prisma, { + ...projection, + projects: [...projection.projects, { id: "phoenix", name: "Phoenix" }], + }); + + expect(returned.retired).toEqual([]); + expect(returned.exhibits).toContain("exhibit-phoenix"); + expect(fake.pages.get("phoenix")).toMatchObject({ + isPublished: true, + parentSlug: "gallery", + title: "Phoenix — Investment Lifecycle Management", + }); + expect(fake.deleted).toEqual([]); + } finally { + info.mockRestore(); + } + }); }); diff --git a/src/lib/resume-adapter.ts b/src/lib/resume-adapter.ts index ccef3cc..9679754 100644 --- a/src/lib/resume-adapter.ts +++ b/src/lib/resume-adapter.ts @@ -6,10 +6,10 @@ */ import type { - ProjectEntry, - ProjectedResume, - ReferenceEntry, - WorkEntry, + PortfolioProject, + PortfolioReference, + PortfolioResume, + PortfolioWork, } from "@fastdogcoding/resume-master"; import type { ExhibitData, TestimonialData } from "@/types"; @@ -247,7 +247,7 @@ export function normalizeReferenceTitle(title: string): { }; } -export function projectToExhibitData(project: ProjectEntry): ExhibitData { +export function projectToExhibitData(project: PortfolioProject): ExhibitData { return { title: project.name, client: project.entity ?? "", @@ -261,8 +261,8 @@ export function projectToExhibitData(project: ProjectEntry): ExhibitData { } export function resolveTestimonialCompany( - reference: ReferenceEntry, - work: readonly WorkEntry[] = [] + reference: PortfolioReference, + work: readonly PortfolioWork[] = [] ): string { if (reference.workId) { const match = work.find((entry) => entry.id === reference.workId); @@ -274,7 +274,7 @@ export function resolveTestimonialCompany( return ""; } -export function resolveTestimonialRole(reference: ReferenceEntry): string { +export function resolveTestimonialRole(reference: PortfolioReference): string { const presentation = testimonialByName.get(reference.name); if (presentation) return presentation.role; if (reference.title) return normalizeReferenceTitle(reference.title).role; @@ -282,8 +282,8 @@ export function resolveTestimonialRole(reference: ReferenceEntry): string { } export function referenceToTestimonialData( - reference: ReferenceEntry, - work: readonly WorkEntry[] = [] + reference: PortfolioReference, + work: readonly PortfolioWork[] = [] ): TestimonialData { return { name: reference.name, @@ -304,7 +304,7 @@ export interface MappedTestimonial { data: TestimonialData; } -export function mapExhibits(projection: ProjectedResume): MappedExhibit[] { +export function mapExhibits(projection: PortfolioResume): MappedExhibit[] { const mapped: MappedExhibit[] = []; for (const project of projection.projects ?? []) { if (!project?.id) continue; @@ -320,7 +320,7 @@ export function mapExhibits(projection: ProjectedResume): MappedExhibit[] { } export function mapTestimonials( - projection: ProjectedResume + projection: PortfolioResume ): MappedTestimonial[] { const work = projection.work ?? []; const mapped: MappedTestimonial[] = []; diff --git a/src/lib/site-copy.ts b/src/lib/site-copy.ts new file mode 100644 index 0000000..e16621f --- /dev/null +++ b/src/lib/site-copy.ts @@ -0,0 +1,18 @@ +/** + * Public copy shared by the home hero seed and the Open Graph image. + * + * The strings are the home hero already seeded as `hero-home` + * (prisma/seed-content.ts): the headline visitors see, not a separate + * tagline. Non-breaking spaces keep each imperative phrase on one line + * in the Open Graph card. + */ +export const HOME_HERO = { + heading: "Listen\u00a0carefully. Think\u00a0deeply. Build\u00a0deliberately.", + subheading: "We focus on solving your problems the right way.", +} as const; + +/** Plain-text form of the home hero headline (normal spaces). */ +export const HOME_HERO_HEADING_TEXT = HOME_HERO.heading.replaceAll( + "\u00a0", + " " +); diff --git a/src/lib/sitemap-entries.ts b/src/lib/sitemap-entries.ts new file mode 100644 index 0000000..cc32e26 --- /dev/null +++ b/src/lib/sitemap-entries.ts @@ -0,0 +1,47 @@ +import type { MetadataRoute } from "next"; + +/** + * Pages the public site will serve. + * + * Gallery grids, page routes, and this sitemap all key off `isPublished`. + * Resume sync retires a stale exhibit by setting that flag to false and + * leaving the row in place, so the URL drops out of the sitemap and 404s. + */ +export const publishedPageWhere = { isPublished: true } as const; + +export interface SitemapSourcePage { + slug: string; + parentSlug: string | null; + updatedAt: Date; + isPublished: boolean; +} + +/** + * Sitemap entries for published pages only. + * Home is the site origin. A gallery exhibit is `/{parentSlug}/{slug}` + * (the same path GalleryGrid links to). + */ +export function publishedSitemapEntries( + pages: readonly SitemapSourcePage[], + baseUrl: string +): MetadataRoute.Sitemap { + const entries: MetadataRoute.Sitemap = []; + + for (const page of pages) { + if (page.isPublished !== true) continue; + + const path = page.parentSlug + ? `/${page.parentSlug}/${page.slug}` + : `/${page.slug}`; + const routeUrl = page.slug === "home" && !page.parentSlug ? "" : path; + + entries.push({ + url: `${baseUrl}${routeUrl}`, + lastModified: page.updatedAt, + changeFrequency: "weekly", + priority: page.slug === "home" ? 1 : 0.8, + }); + } + + return entries; +} diff --git a/src/lib/sync-resume.ts b/src/lib/sync-resume.ts index d0cd7ef..0e3da6a 100644 --- a/src/lib/sync-resume.ts +++ b/src/lib/sync-resume.ts @@ -3,22 +3,67 @@ * * Static pages (home, services, about, contact, legal, privacy, gallery, * testimonials) and their hero / prose / cta sections are left alone. - * This module never deletes rows. + * + * Retirement policy (soft-unpublish, no deletes): + * - Sync owns a gallery child only when `parentSlug` is `gallery` and the + * slug is an `EXHIBIT_CATALOG` page slug. That catalog is the managed-by + * marker. Anything else — static marketing pages, seed-only sections, and + * gallery children that are not in the catalog — is never retired. + * - The keep set is project ids present in this projection and in + * `EXHIBIT_CATALOG`. A managed gallery page whose project id is outside + * that set is unpublished (`isPublished = false`) when it is currently + * published. + * - The page row, slug, title, meta description, exhibit section, and + * placements stay. The public route already 404s when `isPublished` is + * false, and the surviving slug is enough to add a redirect later. + * A later projection that includes the project republishes the page, + * because the gallery upsert sets `isPublished` back to true. + * - Already-unpublished managed pages are left untouched, so a second run + * is a no-op for retirement. + * - Testimonial sections are not retired. Sync upserts them, but they are + * shared with the static testimonials index and the home featured quote, + * and sections have no publish flag. Detaching those placements would + * edit static pages. A retired exhibit keeps its quote placement on the + * unpublished page. A reference that leaves the projection is simply not + * re-upserted; its section row is not deleted. + * - `dryRun` reads the same set and returns it, and writes nothing. */ import type { Prisma, PrismaClient } from "@prisma/client"; -import type { ProjectedResume } from "@fastdogcoding/resume-master"; +import type { PortfolioResume } from "@fastdogcoding/resume-master"; import type { ExhibitData, TestimonialData } from "@/types"; import { + EXHIBIT_CATALOG, mapExhibits, mapTestimonials, TESTIMONIAL_CATALOG, type ExhibitPresentation, } from "@/lib/resume-adapter"; +export interface RetiredGalleryExhibit { + /** Page id, kept so the row can be found after the slug is reused in a redirect. */ + id: string; + slug: string; + title: string; + projectId: string; + exhibitSlug: string; + /** Public path, preserved for a later redirect map. */ + path: string; +} + export interface SyncResumeResult { exhibits: string[]; testimonials: string[]; + retired: RetiredGalleryExhibit[]; + dryRun: boolean; +} + +export interface SyncResumeOptions { + /** + * Compute the upsert and retirement sets without writing. + * Useful for the first run against Neon after a projection change. + */ + dryRun?: boolean; } /** Home layout: hero 0, gallery grid 1, featured quote 2, cta 3. */ @@ -26,6 +71,30 @@ const HOME_TESTIMONIAL_SLUG = "testimonial-andrew"; const HOME_TESTIMONIAL_SORT_ORDER = 2; const CTA_SLUG = "cta-default"; +const GALLERY_PARENT_SLUG = "gallery"; + +/** + * Marketing shells seeded by prisma/seed-content.ts. Never unpublish these, + * even if a catalog slug ever collided with one. + */ +const STATIC_PAGE_SLUGS = new Set([ + "home", + "gallery", + "services", + "about", + "contact", + "testimonials", + "legal", + "privacy", +]); + +const exhibitByPageSlug = new Map( + EXHIBIT_CATALOG.map((entry) => [entry.pageSlug, entry]) +); + +const exhibitByProjectId = new Map( + EXHIBIT_CATALOG.map((entry) => [entry.projectId, entry]) +); function toJson(value: ExhibitData | TestimonialData): Prisma.InputJsonValue { return JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue; @@ -84,96 +153,186 @@ async function upsertSection( }); } +function activeCatalogProjectIds(projection: PortfolioResume): Set { + const ids = new Set(); + for (const project of projection.projects ?? []) { + if (!project?.id) continue; + if (!exhibitByProjectId.has(project.id)) continue; + ids.add(project.id); + } + return ids; +} + +function logRetirement( + action: "unpublished" | "would unpublish", + entry: RetiredGalleryExhibit +): void { + console.info( + `[sync-resume] ${action} gallery exhibit id=${entry.id} slug=${entry.slug} title=${JSON.stringify(entry.title)} projectId=${entry.projectId} exhibitSlug=${entry.exhibitSlug} path=${entry.path}` + ); +} + +/** + * Unpublish catalog gallery pages whose project is absent from this projection. + * Does not delete pages, sections, or placements. + */ +async function retireStaleGalleryExhibits( + prisma: PrismaClient, + projection: PortfolioResume, + dryRun: boolean +): Promise { + const activeIds = activeCatalogProjectIds(projection); + const galleryPages = await prisma.page.findMany({ + where: { parentSlug: GALLERY_PARENT_SLUG }, + select: { + id: true, + slug: true, + title: true, + parentSlug: true, + isPublished: true, + isNav: true, + }, + }); + + const retired: RetiredGalleryExhibit[] = []; + + for (const page of galleryPages) { + const presentation: ExhibitPresentation | undefined = exhibitByPageSlug.get( + page.slug + ); + if (!presentation) continue; + + if (STATIC_PAGE_SLUGS.has(page.slug) || page.isNav) { + console.warn( + `[sync-resume] refused to retire slug=${page.slug} (static marketing page or nav item)` + ); + continue; + } + + if (activeIds.has(presentation.projectId)) continue; + if (page.isPublished !== true) continue; + + const entry: RetiredGalleryExhibit = { + id: page.id, + slug: page.slug, + title: page.title, + projectId: presentation.projectId, + exhibitSlug: presentation.exhibitSlug, + path: `/${GALLERY_PARENT_SLUG}/${page.slug}`, + }; + + if (!dryRun) { + await prisma.page.update({ + where: { id: page.id }, + data: { isPublished: false }, + }); + } + + logRetirement(dryRun ? "would unpublish" : "unpublished", entry); + retired.push(entry); + } + + retired.sort((a, b) => a.slug.localeCompare(b.slug)); + return retired; +} + export async function syncResume( prisma: PrismaClient, - projection: ProjectedResume + projection: PortfolioResume, + options: SyncResumeOptions = {} ): Promise { + const dryRun = options.dryRun === true; + const home = await requirePage(prisma, "home"); const testimonialsPage = await requirePage(prisma, "testimonials"); await requirePage(prisma, "gallery"); const cta = await requireSection(prisma, CTA_SLUG); const testimonials = mapTestimonials(projection); - const testimonialIds = new Map(); - - for (const testimonial of testimonials) { - const section = await upsertSection( - prisma, - "testimonial", - testimonial.presentation.slug, - testimonial.data - ); - testimonialIds.set(testimonial.presentation.slug, section.id); - } + const exhibits = mapExhibits(projection); + + if (!dryRun) { + const testimonialIds = new Map(); + + for (const testimonial of testimonials) { + const section = await upsertSection( + prisma, + "testimonial", + testimonial.presentation.slug, + testimonial.data + ); + testimonialIds.set(testimonial.presentation.slug, section.id); + } + + for (const presentation of TESTIMONIAL_CATALOG) { + const sectionId = + testimonialIds.get(presentation.slug) ?? + ( + await prisma.section.findUnique({ + where: { slug: presentation.slug }, + }) + )?.id; + if (!sectionId) continue; + await ensurePlacement( + prisma, + testimonialsPage.id, + sectionId, + presentation.sortOrder, + null + ); + } - for (const presentation of TESTIMONIAL_CATALOG) { - const sectionId = - testimonialIds.get(presentation.slug) ?? + const andrewId = + testimonialIds.get(HOME_TESTIMONIAL_SLUG) ?? ( await prisma.section.findUnique({ - where: { slug: presentation.slug }, + where: { slug: HOME_TESTIMONIAL_SLUG }, }) )?.id; - if (!sectionId) continue; - await ensurePlacement( - prisma, - testimonialsPage.id, - sectionId, - presentation.sortOrder, - null - ); - } - - const andrewId = - testimonialIds.get(HOME_TESTIMONIAL_SLUG) ?? - ( - await prisma.section.findUnique({ - where: { slug: HOME_TESTIMONIAL_SLUG }, - }) - )?.id; - if (andrewId) { - await ensurePlacement( - prisma, - home.id, - andrewId, - HOME_TESTIMONIAL_SORT_ORDER, - "compact" - ); - } - - const exhibits = mapExhibits(projection); - const exhibitSlugs: string[] = []; - - for (const exhibit of exhibits) { - const section = await upsertSection( - prisma, - "exhibit", - exhibit.presentation.exhibitSlug, - exhibit.data - ); - const page = await upsertGalleryPage(prisma, exhibit.presentation); - await ensurePlacement(prisma, page.id, section.id, 0, null); + if (andrewId) { + await ensurePlacement( + prisma, + home.id, + andrewId, + HOME_TESTIMONIAL_SORT_ORDER, + "compact" + ); + } - let nextOrder = 1; - if (exhibit.presentation.testimonialSlug) { - const quoteId = await resolveTestimonialId( + for (const exhibit of exhibits) { + const section = await upsertSection( prisma, - exhibit.presentation.testimonialSlug, - testimonialIds + "exhibit", + exhibit.presentation.exhibitSlug, + exhibit.data ); - if (quoteId) { - await ensurePlacement(prisma, page.id, quoteId, nextOrder, "compact"); - nextOrder += 1; + const page = await upsertGalleryPage(prisma, exhibit.presentation); + await ensurePlacement(prisma, page.id, section.id, 0, null); + + let nextOrder = 1; + if (exhibit.presentation.testimonialSlug) { + const quoteId = await resolveTestimonialId( + prisma, + exhibit.presentation.testimonialSlug, + testimonialIds + ); + if (quoteId) { + await ensurePlacement(prisma, page.id, quoteId, nextOrder, "compact"); + nextOrder += 1; + } } - } - await ensurePlacement(prisma, page.id, cta.id, nextOrder, null); - exhibitSlugs.push(exhibit.presentation.exhibitSlug); + await ensurePlacement(prisma, page.id, cta.id, nextOrder, null); + } } + const retired = await retireStaleGalleryExhibits(prisma, projection, dryRun); + return { - exhibits: unique(exhibitSlugs), + exhibits: unique(exhibits.map((entry) => entry.presentation.exhibitSlug)), testimonials: unique(testimonials.map((entry) => entry.presentation.slug)), + retired, + dryRun, }; } @@ -196,7 +355,7 @@ async function upsertGalleryPage( where: { slug: presentation.pageSlug }, create: { slug: presentation.pageSlug, - parentSlug: "gallery", + parentSlug: GALLERY_PARENT_SLUG, title: presentation.pageTitle, metaDesc: presentation.metaDesc, isPublished: true, @@ -205,7 +364,7 @@ async function upsertGalleryPage( sortOrder: presentation.sortOrder, }, update: { - parentSlug: "gallery", + parentSlug: GALLERY_PARENT_SLUG, title: presentation.pageTitle, metaDesc: presentation.metaDesc, isPublished: true,