diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3cf55b4..bb81f886 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,10 +53,14 @@ jobs: - name: Install Dependencies run: pnpm install --frozen-lockfile + - name: Verify Payload CLI backport + run: pnpm test:payload-cli + - name: Run Payload Migrations # `payload migrate` has exited 0 without applying anything, which only # surfaced later as missing tables in the build. run: | + set -o pipefail echo "y" | pnpm exec payload migrate 2>&1 | tee migrate.log grep -q 'Done\.' migrate.log || { echo "::error::payload migrate did not finish"; exit 1; } diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 9044ab36..43c530bb 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -186,6 +186,8 @@ jobs: -c "SELECT id FROM sports_page_layout LIMIT 0;" \ -c "SELECT id, short_name, athletics_url FROM schools LIMIT 0;" \ -c "SELECT opponent_id, home_away, rpi_score, opponent_score, game_status, sport FROM articles LIMIT 0;" \ + -c "SELECT opponent_id, date, home_away, rpi_score, opponent_score, status FROM articles_games LIMIT 0;" \ + -c "SELECT _uuid, opponent_id, date, home_away, rpi_score, opponent_score, status FROM _articles_v_version_games LIMIT 0;" \ -c "SELECT id FROM staff_page_layout LIMIT 0;" \ -c "SELECT id FROM theme LIMIT 0;" \ -c "SELECT id FROM seo LIMIT 0;" diff --git a/CLAUDE.md b/CLAUDE.md index fa8df147..4d96e24b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -23,7 +23,7 @@ For deeper architectural context, see [`docs/`](docs/) (architecture, data model ## Repository Layout -- `app/(frontend)/`: public site routes (`/`, section pages, article pages, staff, search, `/live`, submission forms, `/about`, `/contact`, etc.) +- `app/(frontend)/`: public site routes (`/`, section pages, article pages, staff, search, `/live`, `/get-involved`, submission forms, `/about`, `/contact`, etc.) - `app/(payload)/`: Payload admin/app API integration routes (`/admin`, `/newsroom`) - `app/api/`: custom API routes (`/api/health`, search, push, weather, submit, etc.) - `collections/`: Payload collection + global definitions @@ -32,6 +32,7 @@ For deeper architectural context, see [`docs/`](docs/) (architecture, data model - `migrations/`: Payload-format TypeScript migrations registered via `migrations/index.ts` - `mobile/`: Capacitor Android + iOS shells (separate `package.json`; install with `pnpm install --ignore-workspace`) - `scripts/`: deploy/runtime scripts (`run_deploy_sql_migrations.sh`, `deploy-smoke.mjs`, `generate-env.js`) +- `patches/`: pnpm dependency patches (currently a Payload 3.80.0 CLI backport); see `patches/README.md` for provenance and when to remove each - `middleware.ts`: returns `410 Gone` for matching article URLs whose row is unpublished - `.github/workflows/`: CI, production deploy, Android release, and iOS simulator build workflows @@ -53,16 +54,17 @@ Collections: - `articles`: drafts/publish enabled (`versions.drafts: true`); `publishedDate` is set on first publish in a `beforeChange` hook; `lastModifiedBy` is stamped on every change; `opinionType` auto-derives from the kicker for opinion pieces - `live-articles`: live-blog entries with append-only `updates`; mirrors the photo-gallery / carousel rich-text blocks - `layout`: homepage curation (lead, slots, top-4, layout template, sections, volume/issue) — drafts enabled -- `opinion-page-layout`, `features-page-layout`, `sports-page-layout`, `staff-page-layout`: per-section page composition +- `opinion-page-layout`, `features-page-layout`, `sports-page-layout`, `news-page-layout`, `staff-page-layout`: per-section page composition +- `student-gov-updates`, `student-gov-terms`: Student Senate / Executive Board timeline updates and terms (GM Week to GM Week); see `docs/news-section.md` - `users`: staff/auth/roles + slug, headshot, retired flag, "one-liner", and seen-newsroom-notice flag - `media`: uploaded assets (alt, title, caption, source URL, photographer relationship, write-in photographer) - `job-titles`: staff position metadata - `submissions`: public op-ed / letter submissions (anonymous create, staff triage) -- `event-submissions`: public event submissions for the calendar +- `event-submissions`: archived event submissions (read-only; the public event form and Features events box were removed) - `logos`: branded section logos and homepage assets - `device-tokens`: registered Android and iOS FCM tokens (anonymous create via `/api/push/register`, admin-only read/delete) - `redirects`: short tracked links at `poly.rpi.edu/` (`path` + `destination`); `middleware.ts` answers with a 302 and captures a `redirect_followed` PostHog event per hit -- `schools`: opponents RPI teams play, each with a logo (upload collection; seeded from RPI Athletics schedules by `pnpm db:seed:schools`). Sports articles link one as `opponent`, alongside `homeAway`, `rpiScore`, `opponentScore` and `gameStatus` +- `schools`: opponents RPI teams play, each with a logo (upload collection; seeded from RPI Athletics schedules by `pnpm db:seed:schools`). Sports articles record up to two results in a `games` array (`opponent`, `date`, `homeAway`, `rpiScore`, `opponentScore`, `status`); the older single-game fields (`opponent`, `homeAway`, `rpiScore`, `opponentScore`, `gameStatus`) are hidden and kept for older articles and revisions Globals: @@ -116,6 +118,8 @@ Optional: - `pnpm test:smoke` - `pnpm test:search-limit` - `pnpm test:deploy-smoke` (manual smoke script; not used by deploy workflow) +- `pnpm test:unit` (Vitest) +- `pnpm test:payload-cli` (checks the Payload CLI patch; also runs in CI) - `pnpm generate:types` ## CI (Current) @@ -126,10 +130,13 @@ Runs on PRs + pushes to `main`: 1. Postgres service (`postgres:16`) 2. `pnpm install --frozen-lockfile` -3. `pnpm exec payload migrate` -4. `pnpm lint` -5. `pnpm typecheck` -6. `pnpm build` +3. `pnpm test:payload-cli` +4. `pnpm exec payload migrate` (fails unless the CLI prints `Done.`) +5. `pnpm lint` +6. `pnpm typecheck` +7. `pnpm build` + +Pull-request workflows don't run while a PR has merge conflicts with its base, so a conflicting PR shows no CI result at all. Playwright is not part of the current CI runtime path. @@ -223,6 +230,7 @@ Mixing PM2 users creates split daemons/process lists and inconsistent runtime ow - **Pre-commit checks:** Always run `pnpm lint` and `pnpm typecheck` before committing. Do not commit code that fails either check. - **Linting & Code Quality:** Ensure code changes are lint-safe before completing your task. Either review your code rigorously for common ESLint and React purity warnings, or execute `pnpm lint` to automatically verify. +- **Lint baseline and CMS previews:** Expect zero ESLint errors and warnings. Plain images in the five named CMS layout editor files are intentional; `eslint.config.mjs` contains a scoped `@next/next/no-img-element` exception. Public-site image checks and preview alt-text checks remain enabled. See [`docs/local-development.md`](docs/local-development.md#lint-expectations-and-cms-image-previews) for the policy and exact file scope. - **Database Migrations:** When adding or modifying Payload collection fields that change the DB schema (new fields, new collections, enum changes), you MUST create corresponding migrations in BOTH paths: 1. A TypeScript migration file in `migrations/` and register it in `migrations/index.ts` (used by CI via `pnpm exec payload migrate`) 2. The equivalent SQL in `scripts/run_deploy_sql_migrations.sh` with a tracking INSERT entry (used by production deploy) diff --git a/GEMINI.md b/GEMINI.md index a29105e1..05ec38de 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -1,10 +1,12 @@ # GEMINI.md -This document is the canonical project + operations reference for Gemini/Codex-style agents in this repository. It mirrors `CLAUDE.md` so non-Claude agents have the same operational context. +This document is the canonical project + operations reference for Gemini/Codex-style agents in this repository. It mirrors `CLAUDE.md` so non-Claude agents have the same operational context; when you change one, copy the change to the other. ## Project Overview -Polymer is The Polytechnic's web platform (public newspaper site + Payload CMS admin) built on Next.js + Payload + PostgreSQL, with a Capacitor Android shell that wraps the production site and receives FCM breaking-news pushes. +Polymer is The Polytechnic's web platform (public newspaper site + Payload CMS admin) built on Next.js + Payload + PostgreSQL, with Capacitor Android and iOS shells that wrap the production site and receive FCM breaking-news pushes. + +**This project is live in production with a real production database. Exercise caution with schema changes, migrations, and any destructive operations.** For deeper architectural context, see [`docs/`](docs/) (architecture, data model, migrations, search, push, analytics, deployment, local-development). @@ -16,50 +18,53 @@ For deeper architectural context, see [`docs/`](docs/) (architecture, data model - PostgreSQL - TypeScript - Tailwind CSS 4 -- PostHog (`posthog-js` + `posthog-node`) +- PostHog (`posthog-js` + `posthog-node`, self-hosted ingest at `t.poly.rpi.edu`) - pnpm 10 ## Repository Layout -- `app/(frontend)/`: public site routes (`/`, section pages, article pages, staff, search, `/live`, etc.) -- `app/(payload)/`: Payload admin/app integration routes (`/admin`, `/newsroom`) +- `app/(frontend)/`: public site routes (`/`, section pages, article pages, staff, search, `/live`, `/get-involved`, submission forms, `/about`, `/contact`, etc.) +- `app/(payload)/`: Payload admin/app API integration routes (`/admin`, `/newsroom`) - `app/api/`: custom API routes (`/api/health`, search, push, weather, submit, etc.) - `collections/`: Payload collection + global definitions - `components/`: UI + article layout + dashboard components -- `lib/`: server helpers (PostHog, FCM, theme, archive, weather) +- `lib/`: server helpers (PostHog, FCM, theme, archive query, weather, homepage slot resolution) - `migrations/`: Payload-format TypeScript migrations registered via `migrations/index.ts` -- `mobile/`: Capacitor Android shell +- `mobile/`: Capacitor Android + iOS shells (separate `package.json`; install with `pnpm install --ignore-workspace`) - `scripts/`: deploy/runtime scripts (`run_deploy_sql_migrations.sh`, `deploy-smoke.mjs`, `generate-env.js`) +- `patches/`: pnpm dependency patches (currently a Payload 3.80.0 CLI backport); see `patches/README.md` for provenance and when to remove each - `middleware.ts`: returns `410 Gone` for matching article URLs whose row is unpublished -- `.github/workflows/`: CI, deploy, and Android release workflows +- `.github/workflows/`: CI, production deploy, Android release, and iOS simulator build workflows ## Core Behavior - Article URL format: `/:section/:year/:month/:slug` -- Homepage composition comes from `layout` + recent section stories (`app/(frontend)/page.tsx`) +- Homepage composition comes from the `layout` collection + recent section stories (`app/(frontend)/page.tsx`) - Article layouts: - standard / news / sports / features → `StandardLayout` - opinion → `OpinionLayout` - `#photofeature#` flag in first content paragraph → `PhotofeatureLayout` - Live blog: `live-articles` collection drives `/live` and the homepage `LiveStrip` widget -- Breaking news: when an article publishes with `breakingNews=true`, the `Articles.afterChange` hook calls `/api/push/send` (with `INTERNAL_PUSH_SECRET`) to fan out FCM messages. +- Breaking news: when an article publishes with `breakingNews=true`, the `Articles.afterChange` hook calls `/api/push/send` (with `INTERNAL_PUSH_SECRET`) which fans out FCM messages to every `device-tokens` row. ## Data Model (Current) Collections: -- `articles`: drafts/publish enabled (`versions.drafts: true`); `publishedDate` set on first publish; `lastModifiedBy` stamped on every change; `opinionType` derived from kicker -- `live-articles`: live-blog entries with append-only updates +- `articles`: drafts/publish enabled (`versions.drafts: true`); `publishedDate` is set on first publish in a `beforeChange` hook; `lastModifiedBy` is stamped on every change; `opinionType` auto-derives from the kicker for opinion pieces +- `live-articles`: live-blog entries with append-only `updates`; mirrors the photo-gallery / carousel rich-text blocks - `layout`: homepage curation (lead, slots, top-4, layout template, sections, volume/issue) — drafts enabled -- `opinion-page-layout`, `features-page-layout`, `sports-page-layout`, `staff-page-layout`: per-section page composition -- `users`: staff/auth/roles + slug, headshot, retired flag -- `media`: uploaded assets (alt, title, caption, source URL, photographer) +- `opinion-page-layout`, `features-page-layout`, `sports-page-layout`, `news-page-layout`, `staff-page-layout`: per-section page composition +- `student-gov-updates`, `student-gov-terms`: Student Senate / Executive Board timeline updates and terms (GM Week to GM Week); see `docs/news-section.md` +- `users`: staff/auth/roles + slug, headshot, retired flag, "one-liner", and seen-newsroom-notice flag +- `media`: uploaded assets (alt, title, caption, source URL, photographer relationship, write-in photographer) - `job-titles`: staff position metadata -- `submissions`: public op-ed / letter submissions -- `event-submissions`: public event submissions -- `logos`: branded section/homepage assets -- `device-tokens`: registered Android FCM tokens -- `schools`: opponents RPI teams play, each with a logo (seeded by `pnpm db:seed:schools`); sports articles link one as `opponent` with the game score +- `submissions`: public op-ed / letter submissions (anonymous create, staff triage) +- `event-submissions`: archived event submissions (read-only; the public event form and Features events box were removed) +- `logos`: branded section logos and homepage assets +- `device-tokens`: registered Android and iOS FCM tokens (anonymous create via `/api/push/register`, admin-only read/delete) +- `redirects`: short tracked links at `poly.rpi.edu/` (`path` + `destination`); `middleware.ts` answers with a 302 and captures a `redirect_followed` PostHog event per hit +- `schools`: opponents RPI teams play, each with a logo (upload collection; seeded from RPI Athletics schedules by `pnpm db:seed:schools`). Sports articles record up to two results in a `games` array (`opponent`, `date`, `homeAway`, `rpiScore`, `opponentScore`, `status`); the older single-game fields (`opponent`, `homeAway`, `rpiScore`, `opponentScore`, `gameStatus`) are hidden and kept for older articles and revisions Globals: @@ -90,16 +95,16 @@ Required: Optional: -- `LEGACY_DATABASE_URI` +- `LEGACY_DATABASE_URI` (legacy Wagtail archive) - `NEXT_PUBLIC_SITE_URL` - `BASE_URL` - `PLAYWRIGHT_WEB_SERVER` - `PLAYWRIGHT_WEB_SERVER_COMMAND` - `NEXT_PUBLIC_POSTHOG_KEY` / `NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN` -- `NEXT_PUBLIC_POSTHOG_HOST` -- `INTERNAL_PUSH_SECRET` -- `FCM_SERVICE_ACCOUNT_JSON` (raw JSON) -- `PAYLOAD_DISABLE_PUSH=1` (disables Payload dev `db.push`) +- `NEXT_PUBLIC_POSTHOG_HOST` (defaults to `https://t.poly.rpi.edu`) +- `INTERNAL_PUSH_SECRET` (required to actually fan out breaking-news pushes) +- `FCM_SERVICE_ACCOUNT_JSON` (raw JSON, not base64 — required for FCM v1) +- `PAYLOAD_DISABLE_PUSH=1` (disables Payload's dev-mode `db.push` schema sync) `pnpm install` runs `scripts/generate-env.js` to create `.env` if missing. @@ -107,12 +112,14 @@ Optional: - `pnpm dev` - `pnpm build` -- `pnpm start` +- `pnpm start` (binds to `127.0.0.1`; PM2/nginx fronts it in prod) - `pnpm lint` - `pnpm typecheck` - `pnpm test:smoke` - `pnpm test:search-limit` - `pnpm test:deploy-smoke` (manual smoke script; not used by deploy workflow) +- `pnpm test:unit` (Vitest) +- `pnpm test:payload-cli` (checks the Payload CLI patch; also runs in CI) - `pnpm generate:types` ## CI (Current) @@ -123,10 +130,13 @@ Runs on PRs + pushes to `main`: 1. Postgres service (`postgres:16`) 2. `pnpm install --frozen-lockfile` -3. `pnpm exec payload migrate` -4. `pnpm lint` -5. `pnpm typecheck` -6. `pnpm build` +3. `pnpm test:payload-cli` +4. `pnpm exec payload migrate` (fails unless the CLI prints `Done.`) +5. `pnpm lint` +6. `pnpm typecheck` +7. `pnpm build` + +Pull-request workflows don't run while a PR has merge conflicts with its base, so a conflicting PR shows no CI result at all. Playwright is not part of the current CI runtime path. @@ -186,6 +196,8 @@ Use a single PM2 control plane: `actions-runner`. - Allowed: `sudo -u actions-runner pm2 ...` - Avoid: running app PM2 commands as `poly` +Mixing PM2 users creates split daemons/process lists and inconsistent runtime ownership on port 3000. + ### Runtime Process Config `ecosystem.config.cjs`: @@ -204,18 +216,25 @@ Use a single PM2 control plane: `actions-runner`. - behavior: - returns `200` with `{ status: "ok" }` when app + Payload/Postgres check succeeds - returns `503` with `{ status: "error", checks.database: "error" }` on DB/Payload failure + - response is `Cache-Control: no-store` ## Push Notifications (Breaking News) -- registration: `POST /api/push/register` (Android client) +- registration: `POST /api/push/register` (Android + iOS clients; in-memory rate limit + token de-dupe) - fan-out: `POST /api/push/send` (internal; requires `x-internal-secret` matching `INTERNAL_PUSH_SECRET`) -- transport: FCM HTTP v1 via `lib/fcm.ts` using `FCM_SERVICE_ACCOUNT_JSON` +- transport: FCM HTTP v1 via `lib/fcm.ts` using `FCM_SERVICE_ACCOUNT_JSON`; iOS devices register FCM tokens too (APNs → FCM swap in the app), so there is no separate APNs sender - trigger: `Articles.afterChange` when an article transitions to published with `breakingNews=true` +- if `INTERNAL_PUSH_SECRET` or `FCM_SERVICE_ACCOUNT_JSON` is unset, the fan-out becomes a no-op so dev/CI is unaffected ## Agent Operations -- **Linting & Code Quality:** Ensure any code changes are lint-safe before completing your task. Either review your code rigorously for common ESLint and React purity warnings, or execute `pnpm lint` to automatically verify. Run `pnpm typecheck` too. -- **Database Migrations:** When changing the DB schema, write BOTH a TypeScript migration in `migrations/` (registered in `migrations/index.ts`) AND the equivalent SQL in `scripts/run_deploy_sql_migrations.sh` with a tracking INSERT. See [`docs/migrations.md`](docs/migrations.md). +- **Pre-commit checks:** Always run `pnpm lint` and `pnpm typecheck` before committing. Do not commit code that fails either check. +- **Linting & Code Quality:** Ensure code changes are lint-safe before completing your task. Either review your code rigorously for common ESLint and React purity warnings, or execute `pnpm lint` to automatically verify. +- **Lint baseline and CMS previews:** Expect zero ESLint errors and warnings. Plain images in the five named CMS layout editor files are intentional; `eslint.config.mjs` contains a scoped `@next/next/no-img-element` exception. Public-site image checks and preview alt-text checks remain enabled. See [`docs/local-development.md`](docs/local-development.md#lint-expectations-and-cms-image-previews) for the policy and exact file scope. +- **Database Migrations:** When adding or modifying Payload collection fields that change the DB schema (new fields, new collections, enum changes), you MUST create corresponding migrations in BOTH paths: + 1. A TypeScript migration file in `migrations/` and register it in `migrations/index.ts` (used by CI via `pnpm exec payload migrate`) + 2. The equivalent SQL in `scripts/run_deploy_sql_migrations.sh` with a tracking INSERT entry (used by production deploy) + Failing to do this will break production — the site will crash on startup if Payload tries to query columns/tables that don't exist. See [`docs/migrations.md`](docs/migrations.md) for the full step-by-step. ## Incident Guardrails diff --git a/README.md b/README.md index 38e25c64..7f5f0ff7 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ Collections: - `media`: Uploaded assets with alt text, caption, photographer attribution, and source URL - `job-titles`: Reusable staff titles for profile timelines - `submissions`: Public op-ed / letter-to-the-editor submissions -- `event-submissions`: Public event submissions for the calendar +- `event-submissions`: Archived event submissions (read-only; the public event form was removed) - `logos`: Branded section logos and homepage assets - `device-tokens`: Registered Android FCM tokens for push notifications @@ -191,7 +191,6 @@ Open `http://localhost:3000` for the public site and `http://localhost:3000/admi - `GET /api/logos/file` — logo asset proxy - `GET /api/section-layout` — per-section layout fetch - `POST /api/submit` — public op-ed / letter submissions -- `POST /api/submit-event` — public event submissions - `POST /api/push/register` — Android FCM token registration - `POST /api/push/send` — internal breaking-news fan-out (requires `x-internal-secret`) - `POST /api/inline-edit` — admin inline-editing handler diff --git a/app/(frontend)/12/page.tsx b/app/(frontend)/12/page.tsx index 6ce610f1..e1266010 100644 --- a/app/(frontend)/12/page.tsx +++ b/app/(frontend)/12/page.tsx @@ -124,7 +124,7 @@ export default function DemoPage() { Features -

+

The Constitution of the United States

diff --git a/app/(frontend)/[section]/[year]/[month]/[slug]/page.tsx b/app/(frontend)/[section]/[year]/[month]/[slug]/page.tsx index e3f4cec2..c5ddfd2d 100644 --- a/app/(frontend)/[section]/[year]/[month]/[slug]/page.tsx +++ b/app/(frontend)/[section]/[year]/[month]/[slug]/page.tsx @@ -13,7 +13,8 @@ import { getArticleUrl } from '@/utils/getArticleUrl'; import { fillSeoTemplate, getSeo } from '@/lib/getSeo'; import type { Metadata } from 'next'; import type { Article, Media, User } from '@/payload-types'; -import { toPublicArticle } from '@/lib/publicArticle'; +import { SPORTS_GAME_SELECT } from '@/lib/sportsPage'; +import { toPublicArticle, withPopulatedPhotographer } from '@/lib/publicArticle'; export const revalidate = 60; @@ -44,6 +45,7 @@ const getArticle = cache(async (slug: string, section?: string): Promise
+ ' }); + }); + await page.goto('http://opinion.test/editor'); + const slot = page.getByRole('combobox', { name: 'Article for col1-1', exact: true }); + await expect(slot).toHaveValue('42'); + await expect(slot.locator('option:checked')).toHaveText('Old pinned story'); + await page.getByPlaceholder('Search all opinion titles...').fill('Archived'); + const lead = page.getByRole('combobox', { name: 'Article for col1-0', exact: true }); + await expect(lead.locator('option[value="9"]')).toHaveCount(1); + await lead.focus(); + await page.keyboard.press('ArrowDown'); + await page.keyboard.press('Enter'); + await expect(lead).toHaveValue('9'); + await lead.selectOption(''); // Return lead to automatic; its image setting must survive. + await page.getByRole('button', { name: 'Activate', exact: true }).click(); + await expect(page.getByRole('button', { name: 'Saved', exact: true })).toBeVisible(); + expect(savedLayout?.column1).toEqual([null, 42, null, null, null]); + expect(savedLayout?.column1Images).toEqual([true, false, false, false, false]); + delaySave = true; + await lead.selectOption('9'); + await page.getByRole('button', { name: 'Activate', exact: true }).click(); + await expect(page.getByRole('button', { name: 'Saving...', exact: true })).toBeVisible(); + await lead.selectOption(''); + await expect.poll(() => !!finishSave).toBe(true); + finishSave!(); + await expect(page.getByRole('button', { name: 'Activate', exact: true })).toBeEnabled(); +}); + +test('carousel resumes after manual navigation and honors focus and pause controls', async ({ page }) => { + await page.emulateMedia({ reducedMotion: 'no-preference' }); + await page.clock.install(); + await page.route('http://opinion.test/**', (route) => route.fulfill({ contentType: 'text/html', body: '
' })); + await page.goto('http://opinion.test/carousel'); + await expect(page.getByText('Author 1', { exact: true })).toBeVisible(); + await page.getByRole('button', { name: 'Next author' }).focus(); + await page.keyboard.press('Enter'); + await expect(page.getByText('Author 2', { exact: true })).toBeVisible(); + await page.clock.fastForward(6000); + await expect(page.getByText('Author 2', { exact: true })).toBeVisible(); + await page.evaluate(() => (document.activeElement as HTMLElement).blur()); + await page.clock.fastForward(5100); + await expect(page.getByText('Author 3', { exact: true })).toBeVisible(); + await page.getByRole('button', { name: 'Pause rotation' }).focus(); + await page.keyboard.press('Enter'); + await page.evaluate(() => (document.activeElement as HTMLElement).blur()); + await page.clock.fastForward(10000); + await expect(page.getByText('Author 3', { exact: true })).toBeVisible(); + await page.getByRole('button', { name: 'Resume rotation' }).focus(); + await page.keyboard.press('Enter'); + await page.evaluate(() => (document.activeElement as HTMLElement).blur()); + await page.clock.fastForward(5100); + await expect(page.getByText('Author 1', { exact: true })).toBeVisible(); +}); diff --git a/tests/payload-cli.test.mjs b/tests/payload-cli.test.mjs new file mode 100644 index 00000000..507adf8f --- /dev/null +++ b/tests/payload-cli.test.mjs @@ -0,0 +1,109 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; + +const binPath = fileURLToPath(new URL('../node_modules/payload/bin.js', import.meta.url)); + +function fixture(run) { + const dir = mkdtempSync(path.join(tmpdir(), 'polymer-payload-cli-')); + // Keep Payload's environment search inside this isolated fixture. + writeFileSync(path.join(dir, '.env'), '\n'); + try { + run(dir); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +function invoke(dir, args, { environment = {}, nodeArgs = [] } = {}) { + const env = { ...process.env }; + delete env.NODE_ENV; + delete env.PAYLOAD_CONFIG_PATH; + const result = spawnSync(process.execPath, [...nodeArgs, binPath, ...args], { + cwd: dir, + env: { ...env, ...environment }, + encoding: 'utf8', + timeout: 30_000, + }); + assert.ifError(result.error); + assert.equal(result.signal, null, result.stderr); + return result; +} + +for (const flags of [[], ['--disable-transpile']]) { + const mode = flags.length ? 'native JS' : 'tsx'; + for (const [name, source, expected] of [ + ['completed script succeeds', 'await Promise.resolve()', 0], + ['unfinished script fails', 'await new Promise(() => {})', 13], + ['thrown error fails', "throw new Error('EXPECTED_FAILURE')", 1], + ['explicit exit code survives', 'process.exit(7)', 7], + ]) { + test(`${mode}: ${name}`, () => fixture(dir => { + const script = path.join(dir, 'script.mjs'); + writeFileSync(script, `console.log('SCRIPT_STARTED');\n${source}\n`); + const result = invoke(dir, ['run', script, ...flags]); + assert.match(result.stdout, /SCRIPT_STARTED/); + assert.equal(result.status, expected, result.stderr); + })); + } +} + +test('an unfinished config import fails before migrations', () => fixture(dir => { + const config = path.join(dir, 'config.mjs'); + writeFileSync(config, "console.log('CONFIG_STARTED');\nexport default await new Promise(() => {});\n"); + const result = invoke(dir, ['migrate', '--help'], { + environment: { PAYLOAD_CONFIG_PATH: config }, + }); + assert.match(result.stdout, /CONFIG_STARTED/); + assert.equal(result.status, 13, result.stderr); +})); + +function conditionalPackage(dir, name) { + const packageDir = path.join(dir, 'node_modules', name); + mkdirSync(packageDir, { recursive: true }); + const entry = { + development: './development.mjs', + production: './production.mjs', + node: './node.mjs', + }; + writeFileSync(path.join(packageDir, 'package.json'), JSON.stringify({ + name, + type: 'module', + exports: { '.': entry, './subpath': entry }, + })); + for (const condition of Object.keys(entry)) { + writeFileSync(path.join(packageDir, `${condition}.mjs`), `export default '${condition}';\n`); + } +} + +for (const scenario of [ + { name: 'default development', lexical: 'development', other: 'node' }, + { name: 'production from .env', dotenv: 'NODE_ENV=production\n', lexical: 'production', other: 'node' }, + { name: 'process environment overrides .env', dotenv: 'NODE_ENV=production\n', environment: { NODE_ENV: 'development' }, lexical: 'development', other: 'node' }, + { name: 'explicit conditions survive', environment: { NODE_ENV: 'production' }, nodeArgs: ['--conditions=development'], lexical: 'development', other: 'development' }, +]) { + test(`Lexical resolution: ${scenario.name}`, () => fixture(dir => { + for (const name of ['lexical', '@lexical/probe', 'unrelated-package']) conditionalPackage(dir, name); + if (scenario.dotenv) writeFileSync(path.join(dir, '.env'), scenario.dotenv); + const script = path.join(dir, 'resolve.mjs'); + writeFileSync(script, ` + import lexical from 'lexical'; + import subpath from 'lexical/subpath'; + import scoped from '@lexical/probe'; + import unrelated from 'unrelated-package'; + console.log(JSON.stringify({ lexical, subpath, scoped, unrelated })); + `); + const result = invoke(dir, ['run', script], scenario); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(JSON.parse(result.stdout.trim()), { + lexical: scenario.lexical, + subpath: scenario.lexical, + scoped: scenario.lexical, + unrelated: scenario.other, + }); + })); +} diff --git a/utils/articleAuthors.ts b/utils/articleAuthors.ts new file mode 100644 index 00000000..bec7585c --- /dev/null +++ b/utils/articleAuthors.ts @@ -0,0 +1,67 @@ +/** + * The one place an article's author list is built: staff authors in byline + * order, then write-ins. Every byline (cards via formatArticle, the article + * header, the photofeature hero, recommendations) reads from this, so they + * agree on names, order, trimming and profile links. + */ + +type StaffLike = { + id?: number | string; + firstName?: string | null; + lastName?: string | null; + slug?: string | null; +}; + +type WriteInLike = { + name?: string | null; + photo?: unknown; +}; + +export type AuthorEntry = { + key: string; + name: string; + /** Staff profile; null for write-ins */ + href: string | null; + /** The staff user, when this is a staff author */ + user: U | null; + /** The write-in's own photo field, when this is a write-in */ + writeInPhoto: unknown; +}; + +export const staffName = (user: StaffLike): string => + [user.firstName, user.lastName].map((part) => part?.trim()).filter(Boolean).join(' '); + +export const staffHref = (user: StaffLike): string | null => + user.slug || user.id != null ? `/staff/${user.slug || user.id}` : null; + +export function getArticleAuthors(article: { + authors?: ReadonlyArray | null; + writeInAuthors?: ReadonlyArray | null; +}): AuthorEntry[] { + const staff = (article.authors || []) + .filter((a): a is U => typeof a === 'object' && a !== null) + .map((user, i): AuthorEntry => ({ + key: `staff-${user.id ?? i}`, + name: staffName(user), + href: staffHref(user), + user, + writeInPhoto: null, + })); + const writeIns = (article.writeInAuthors || []).map( + (w, i): AuthorEntry => ({ + key: `write-in-${i}`, + name: w.name?.trim() || '', + href: null, + user: null, + writeInPhoto: w.photo ?? null, + }), + ); + return [...staff, ...writeIns].filter((a) => a.name); +} + +/** + * Who an article with no authors is credited to. Only a staff editorial + * speaks for the Editorial Board; anything else unsigned is the paper's. + */ +export const isStaffEditorial = (article: { opinionType?: string | null }): boolean => + article.opinionType === 'staff-editorial'; diff --git a/utils/articleDates.ts b/utils/articleDates.ts new file mode 100644 index 00000000..c2b9f0a8 --- /dev/null +++ b/utils/articleDates.ts @@ -0,0 +1,58 @@ +import { formatRelativeTime } from '@/components/LiveArticle/relativeTime'; +import { TROY_TIME_ZONE } from '@/lib/troyTime'; + +/* + * Byline dates, one set of rules for the whole site: + * - cards show how long ago a story ran ("3 hours ago") for its first week, + * then nothing (recentAge); + * - a lead story always shows a date, so after that week it shows the publish + * date instead (leadDate); + * - publish dates are read in Troy's time zone, so a story posted at 9 pm + * doesn't show the next day's date on a server running in UTC. + */ + +const WEEK_MS = 7 * 24 * 60 * 60 * 1000; + +const toDate = (input: string | Date | null | undefined): Date | null => { + if (!input) return null; + const date = input instanceof Date ? input : new Date(input); + return Number.isNaN(date.getTime()) ? null : date; +}; + +/** "3 hours ago" for a story's first week; null after that */ +export function recentAge(input: string | Date | null | undefined, now: Date = new Date()): string | null { + const date = toDate(input); + if (!date || now.getTime() - date.getTime() >= WEEK_MS) return null; + return formatRelativeTime(date, now) || null; +} + +const longFormat = new Intl.DateTimeFormat('en-US', { + month: 'long', + day: 'numeric', + year: 'numeric', + timeZone: TROY_TIME_ZONE, +}); + +const shortFormat = new Intl.DateTimeFormat('en-US', { + month: 'short', + day: 'numeric', + year: 'numeric', + timeZone: TROY_TIME_ZONE, +}); + +/** "October 22, 2026", in Troy's time zone */ +export function longDate(input: string | Date | null | undefined): string | null { + const date = toDate(input); + return date ? longFormat.format(date) : null; +} + +/** "Oct 22, 2026", in Troy's time zone */ +export function shortDate(input: string | Date | null | undefined): string | null { + const date = toDate(input); + return date ? shortFormat.format(date) : null; +} + +/** A lead story's date: how long ago in its first week, the publish date after */ +export function leadDate(article: { date?: string | null; publishedDate?: string | null }): string | null { + return article.date || longDate(article.publishedDate); +} diff --git a/utils/formatArticle.ts b/utils/formatArticle.ts index 98f92822..a70f1045 100644 --- a/utils/formatArticle.ts +++ b/utils/formatArticle.ts @@ -1,7 +1,11 @@ +import { getGames, type ArticleGameFields } from './getGames'; import { Media } from '@/payload-types'; import { Article as ComponentArticle } from '@/components/FrontPage/types'; import React from 'react'; import { focalObjectPosition } from './focalPoint'; +import { joinNameText } from './joinNames'; +import { getArticleAuthors } from './articleAuthors'; +import { longDate, recentAge } from './articleDates'; type PublicAuthorLike = { id?: number | string; @@ -10,7 +14,7 @@ type PublicAuthorLike = { slug?: string | null; }; -type PublicMediaLike = Pick & Partial> & { +type PublicMediaLike = Pick & Partial> & { title?: string | null; photographer?: number | { id: number | string; firstName: string; lastName: string; slug?: string | null } | null; writeInPhotographer?: string | null; @@ -26,14 +30,7 @@ type WriteInAuthor = { photo?: unknown; }; -type SchoolLike = { - name: string; - shortName?: string | null; - url?: string | null; - athleticsUrl?: string | null; -}; - -type FormatArticleInput = { +type FormatArticleInput = ArticleGameFields & { id: number | string; slug?: string | null; title: unknown; @@ -50,11 +47,6 @@ type FormatArticleInput = { _status?: string | null; isFollytechnic?: boolean | null; sport?: string | null; - opponent?: number | SchoolLike | null; - homeAway?: 'home' | 'away' | 'neutral' | null; - rpiScore?: number | null; - opponentScore?: number | null; - gameStatus?: string | null; }; /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -95,42 +87,11 @@ export const formatArticle = ( if (article._status && article._status !== 'published') return null; if (!article.slug) return null; - const staffNames = (article.authors || []) - .map((author) => { - if (typeof author === 'number') return ''; - return `${author.firstName} ${author.lastName}`; - }) - .filter(Boolean); - - const writeInNames = (article.writeInAuthors || []) - .map((a) => a.name) - .filter(Boolean); - - const authors = [...staffNames, ...writeInNames].join(' AND '); + const authorList = getArticleAuthors(article); + const authors = joinNameText(authorList.map((a) => a.name)); - const date = article.publishedDate ? new Date(article.publishedDate) : null; - - let dateString: string | null = null; - if (date) { - const now = new Date().getTime(); - const diffMs = now - date.getTime(); - const diffMins = Math.floor(diffMs / (1000 * 60)); - const diffHours = Math.floor(diffMs / (1000 * 60 * 60)); - const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)); - - if (absoluteDate) { - dateString = date.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }); - } else if (diffDays >= 7) { - // Hide date if older than 7 days - dateString = null; - } else if (diffMins < 60) { - dateString = `${diffMins} MINUTE${diffMins !== 1 ? 'S' : ''} AGO`; - } else if (diffHours < 24) { - dateString = `${diffHours} HOUR${diffHours !== 1 ? 'S' : ''} AGO`; - } else { - dateString = `${diffDays} DAY${diffDays !== 1 ? 'S' : ''} AGO`; - } - } + // A week of "3 hours ago" on cards, then nothing (utils/articleDates.ts) + const dateString = absoluteDate ? longDate(article.publishedDate) : recentAge(article.publishedDate); const featuredImage = article.featuredImage as PublicMediaLike | null; let imagePhotographer: string | null = null; @@ -152,7 +113,9 @@ export const formatArticle = ( title: extractTextFromLexical(article.title), richTitle: renderLexicalHeadline(article.title), excerpt: article.subdeck || '', - author: authors ? authors.toUpperCase() : 'THE POLY', + // Plain text, "A, B and C". Bylines render authorLinks; this is for + // places that only take a string + author: authors || 'The Polytechnic', date: dateString, isoDate: article.publishedDate || article.createdAt || null, // The original upload: next/image resizes it per `sizes`, so cards stay @@ -160,6 +123,8 @@ export const formatArticle = ( image: featuredImage?.url || null, imageFull: featuredImage?.url || null, imageFocus: featuredImage ? focalObjectPosition(featuredImage) : null, + imageAspect: + featuredImage?.width && featuredImage?.height ? featuredImage.width / featuredImage.height : null, imageCaption: article.imageCaption || null, imagePhotographer, imagePhotographerId, @@ -171,30 +136,8 @@ export const formatArticle = ( createdAt: article.createdAt, isFollytechnic: article.isFollytechnic || false, // Each author with a staff profile link (write-ins have no profile) - authorLinks: [ - ...(article.authors || []) - .filter((a): a is PublicAuthorLike => typeof a !== 'number') - .map((a) => ({ - name: `${a.firstName} ${a.lastName}`, - href: a.slug || a.id ? `/staff/${a.slug || a.id}` : null, - })), - ...(article.writeInAuthors || []).filter((a) => a.name).map((a) => ({ name: a.name, href: null })), - ], + authorLinks: authorList.map((a) => ({ name: a.name, href: a.href })), sport: article.sport || null, - // Only present when the opponent was populated (depth >= 1) - game: article.opponent && typeof article.opponent === 'object' - ? { - opponent: { - name: article.opponent.name, - shortName: article.opponent.shortName || article.opponent.name, - logo: article.opponent.url || null, - url: article.opponent.athleticsUrl || null, - }, - homeAway: article.homeAway || 'home', - rpiScore: article.rpiScore ?? null, - opponentScore: article.opponentScore ?? null, - status: article.gameStatus || 'Final', - } - : null, + games: getGames(article), }; }; diff --git a/utils/getGames.ts b/utils/getGames.ts new file mode 100644 index 00000000..86096652 --- /dev/null +++ b/utils/getGames.ts @@ -0,0 +1,37 @@ +import type { GameResult, GameTeam } from '@/components/FrontPage/types' +import type { School } from '@/payload-types' + +type SchoolSummary = Pick +type GameRow = { + opponent?: SchoolSummary | number | null + homeAway?: GameResult['homeAway'] | null + date?: string | null + rpiScore?: number | null + opponentScore?: number | null + status?: string | null +} +export type ArticleGameFields = Omit & { + section: string + games?: GameRow[] | null + gameStatus?: string | null +} + +export function schoolTeam(school: SchoolSummary, shortName = school.name): GameTeam { + return { name: school.name, shortName: school.shortName || shortName, logo: school.url || null, url: school.athleticsUrl || null } +} + +export function getGames(article: ArticleGameFields): GameResult[] { + if (article.section !== 'sports') return [] + const rows: GameRow[] = article.games?.length ? article.games : [{ ...article, date: null, status: article.gameStatus }] + return rows.slice(0, 2).flatMap((row) => { + if (!row.opponent || typeof row.opponent !== 'object') return [] + return [{ + opponent: schoolTeam(row.opponent), + homeAway: row.homeAway || 'home', + date: row.date ?? null, + rpiScore: row.rpiScore ?? null, + opponentScore: row.opponentScore ?? null, + status: row.status?.trim() || (row.rpiScore != null && row.opponentScore != null ? 'Final' : 'Scheduled'), + }] + }) +} diff --git a/utils/joinNames.ts b/utils/joinNames.ts new file mode 100644 index 00000000..74d109e4 --- /dev/null +++ b/utils/joinNames.ts @@ -0,0 +1,20 @@ +/** + * Pairs each name with the separator that goes before it, AP style with no + * serial comma: "A", "A and B", "A, B and C". Components render the + * separators as plain text between their own name elements (links, spans). + * Every byline joins authors through this; nothing joins them by hand. + */ +export function joinNames(items: T[]): { item: T; sep: string }[] { + const last = items.length - 1; + return items.map((item, i) => ({ + item, + sep: i === 0 ? '' : i === last ? ' and ' : ', ', + })); +} + +/** joinNames for plain strings: "A, B and C". */ +export function joinNameText(names: string[]): string { + return joinNames(names) + .map(({ item, sep }) => sep + item) + .join(''); +}